Add Storage, Users, Secrets, Webhooks, Scheduled tasks, Audit log screens

Full management surfaces for the platform-admin tenant, mirroring the
existing Tenants pattern (DataTable + row actions + create/edit dialogs +
ConfirmDialog for destructive ops, all data-action tagged for the
command bus, useRegisterAdminContext publishing for the assistant).

- Storage (/storage): backends + credentials. Write-only secret fields,
  Validate/Activate/Deactivate/Set-default/Mark-degraded/Maintenance.
- Users (/users): tabs for Users, Invitations, Roles. Per-user View
  drawer with profile, role add/remove, API keys (one-time reveal on
  create), usage + quota.
- Secrets (/secrets): /api/v1/admin/secrets — create/rotate/rollback,
  versions dialog, enable/disable, generate-value helper.
- Webhooks (/webhooks): CRUD, pause/resume, regenerate-secret with
  one-time reveal, send test event, deliveries dialog.
- Scheduled tasks (/scheduled-tasks): cron CRUD, run-now trigger,
  enable/disable, expandable run history.
- Audit log (/activity): replaces the empty stub. Filter by severity,
  resource type, date range; click for full JSON detail.

All endpoints are hand-rolled HTTP because most aren't covered by the
generated OpenAPI typed paths yet — switch to arcadia.typed.* when the
backend wires them into OpenApiSpex.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
jules
2026-05-01 22:50:09 +10:00
parent 45fa130951
commit a907e25a7c
19 changed files with 7439 additions and 25 deletions

866
app/routes/storage.tsx Normal file
View File

@@ -0,0 +1,866 @@
import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router"
import {
CheckCircle2,
HardDrive,
Pause,
Play,
Plus,
RefreshCw,
ShieldCheck,
Star,
Trash2,
Wrench,
} from "lucide-react"
import { ArcadiaError, useArcadiaClient } from "@crema/arcadia-client"
import {
ActionsCell,
BadgeCell,
DataTable,
DateCell,
Pagination,
useTable,
type ActionItem,
type BadgeTone,
type Column,
} from "@crema/table-ui"
import { SearchInput } from "@crema/search-ui"
import { AlertBanner, ConfirmDialog, EmptyState, LoadingOverlay } from "@crema/feedback-ui"
import { AppShell } from "~/components/layout/app-shell"
import { Button } from "~/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "~/components/ui/dialog"
import { Input } from "~/components/ui/input"
import { Label } from "~/components/ui/label"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "~/components/ui/select"
import { Switch } from "~/components/ui/switch"
import { Textarea } from "~/components/ui/textarea"
import {
activateStorageConfig,
createStorageConfig,
deactivateStorageConfig,
deleteStorageConfig,
isMaskedSecret,
isSecretField,
listStorageConfigs,
markStorageConfigDegraded,
markStorageConfigMaintenance,
OPTIONAL_FIELDS,
REQUIRED_FIELDS,
setDefaultStorageConfig,
updateStorageConfig,
validateStorageConfig,
type StorageBackend,
type StorageConfig,
type StorageConfigInput,
type StorageStatus,
} from "~/lib/arcadia/storage-configs"
import { pageTitle } from "~/lib/page-meta"
import { useSession } from "~/lib/session"
import { useRegisterAdminContext } from "~/lib/admin-context"
export const meta = () => pageTitle("Storage")
type PendingAction =
| { kind: "deactivate" | "degraded" | "maintenance" | "delete"; config: StorageConfig }
| null
type EditorState =
| { mode: "create" }
| { mode: "edit"; config: StorageConfig }
| null
export default function StorageRoute() {
const session = useSession()
const arcadia = useArcadiaClient()
const [configs, setConfigs] = useState<StorageConfig[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [info, setInfo] = useState<string | null>(null)
const [pending, setPending] = useState<PendingAction>(null)
const [editor, setEditor] = useState<EditorState>(null)
const [search, setSearch] = useState("")
const refresh = useCallback(async () => {
setError(null)
setLoading(true)
try {
const list = await listStorageConfigs(arcadia)
setConfigs(list)
} catch (err) {
setError(err instanceof ArcadiaError ? err.message : "Failed to load storage configs.")
} finally {
setLoading(false)
}
}, [arcadia])
useEffect(() => {
if (session) refresh()
}, [session, refresh])
const runAction = useCallback(
async (action: PendingAction) => {
if (!action) return
try {
if (action.kind === "deactivate") await deactivateStorageConfig(arcadia, action.config.id)
else if (action.kind === "degraded")
await markStorageConfigDegraded(arcadia, action.config.id)
else if (action.kind === "maintenance")
await markStorageConfigMaintenance(arcadia, action.config.id)
else if (action.kind === "delete") await deleteStorageConfig(arcadia, action.config.id)
setPending(null)
await refresh()
} catch (err) {
setError(err instanceof ArcadiaError ? err.message : "Action failed.")
setPending(null)
}
},
[arcadia, refresh],
)
const validate = useCallback(
async (config: StorageConfig) => {
setError(null)
setInfo(null)
try {
const result = await validateStorageConfig(arcadia, config.id)
if (result?.ok) {
setInfo(`${config.name}: validation passed.`)
} else {
setError(`${config.name}: ${result?.message ?? "validation failed."}`)
}
} catch (err) {
setError(err instanceof ArcadiaError ? err.message : "Validation failed.")
}
},
[arcadia],
)
const columns = useMemo<Column<StorageConfig>[]>(
() => [
{
id: "name",
header: "Name",
accessor: "name",
sortable: true,
cell: (c) => (
<span className="flex items-center gap-2 font-medium">
{c.is_default ? <Star className="size-3.5 fill-amber-400 text-amber-400" /> : null}
{c.name}
</span>
),
},
{
id: "backend",
header: "Backend",
accessor: "backend_type",
sortable: true,
cell: (c) => (
<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs uppercase">
{c.backend_type}
</code>
),
},
{
id: "status",
header: "Status",
accessor: "status",
sortable: true,
cell: (c) => <BadgeCell label={c.status} tone={statusTone(c.status)} />,
},
{
id: "size",
header: "Max size",
accessor: "max_file_size_bytes",
sortable: true,
cell: (c) => (
<span className="text-muted-foreground">{formatBytes(c.max_file_size_bytes)}</span>
),
},
{
id: "updated",
header: "Updated",
accessor: "updated_at",
sortable: true,
cell: (c) => <DateCell value={c.updated_at} format="short" />,
},
{
id: "actions",
header: "",
align: "right",
cell: (c) => (
<ActionsCell
items={rowActions(c, {
arcadia,
refresh,
setPending,
setEditor,
setError,
validate,
})}
triggerDataAction={`storage-${slugify(c.name)}-actions`}
/>
),
},
],
[arcadia, refresh, validate],
)
const summary = useMemo(
() => ({
total: configs.length,
byStatus: configs.reduce<Record<string, number>>((acc, c) => {
acc[c.status] = (acc[c.status] ?? 0) + 1
return acc
}, {}),
byBackend: configs.reduce<Record<string, number>>((acc, c) => {
acc[c.backend_type] = (acc[c.backend_type] ?? 0) + 1
return acc
}, {}),
configs: configs.map((c) => ({
id: c.id,
name: c.name,
backend_type: c.backend_type,
status: c.status,
is_default: c.is_default,
max_file_size_bytes: c.max_file_size_bytes,
updated_at: c.updated_at,
})),
}),
[configs],
)
useRegisterAdminContext("storage", summary)
const table = useTable<StorageConfig>({
data: configs,
columns,
getRowId: (c) => c.id,
initialPageSize: 25,
initialSearch: search,
})
useEffect(() => {
table.setSearch(search)
}, [search, table])
if (!session) {
return (
<AppShell title="Storage">
<div className="p-8">
<Card className="max-w-md">
<CardHeader>
<CardTitle>Sign in required</CardTitle>
<CardDescription>
Storage administration requires an admin session.
</CardDescription>
</CardHeader>
<CardContent>
<Button asChild>
<Link to="/login?next=/storage">Sign in</Link>
</Button>
</CardContent>
</Card>
</div>
</AppShell>
)
}
return (
<AppShell title="Storage">
<div className="flex flex-col gap-4 p-6">
<header className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-semibold tracking-tight">Storage</h1>
<p className="text-sm text-muted-foreground">
Storage backends and credentials for the platform-admin tenant.
</p>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={refresh}
disabled={loading}
data-action="storage-refresh"
>
<RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
Refresh
</Button>
<Button
size="sm"
onClick={() => setEditor({ mode: "create" })}
data-action="storage-create"
>
<Plus className="size-4" />
New storage config
</Button>
</div>
</header>
{error ? (
<AlertBanner variant="error" dismissible onDismiss={() => setError(null)}>
{error}
</AlertBanner>
) : null}
{info ? (
<AlertBanner variant="success" dismissible onDismiss={() => setInfo(null)}>
{info}
</AlertBanner>
) : null}
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-4">
<SearchInput
value={search}
onValueChange={setSearch}
placeholder="Search by name, backend, or status"
data-action="storage-search"
className="max-w-sm flex-1"
/>
<div className="text-xs text-muted-foreground">
{table.total} of {configs.length}
</div>
</CardHeader>
<CardContent className="relative p-0">
<LoadingOverlay active={loading && configs.length === 0} label="Loading storage configs…" />
{table.total === 0 && !loading ? (
<EmptyState
title={search ? "No configs match that search." : "No storage configs yet."}
description={
search
? "Try a different name, backend, or status."
: "Create your first storage config to start uploading objects."
}
className="py-12"
/>
) : (
<>
<DataTable
columns={columns}
rows={table.pageRows}
getRowId={(c) => c.id}
sort={table.sort}
onSortToggle={table.toggleSort}
loading={loading && configs.length > 0}
stickyHeader
/>
<Pagination
page={table.page}
pageSize={table.pageSize}
total={table.total}
onPageChange={table.setPage}
onPageSizeChange={table.setPageSize}
/>
</>
)}
</CardContent>
</Card>
</div>
<ConfirmDialog
open={pending?.kind === "deactivate"}
onOpenChange={(o) => !o && setPending(null)}
title="Deactivate storage config?"
description={
pending
? `${pending.config.name} will stop accepting new uploads. Existing objects remain accessible.`
: ""
}
confirmLabel="Deactivate"
variant="default"
onConfirm={() => runAction(pending)}
/>
<ConfirmDialog
open={pending?.kind === "degraded"}
onOpenChange={(o) => !o && setPending(null)}
title="Mark as degraded?"
description={
pending
? `${pending.config.name} will be flagged as degraded. The platform may route new uploads elsewhere.`
: ""
}
confirmLabel="Mark degraded"
variant="default"
onConfirm={() => runAction(pending)}
/>
<ConfirmDialog
open={pending?.kind === "maintenance"}
onOpenChange={(o) => !o && setPending(null)}
title="Mark as in maintenance?"
description={
pending
? `${pending.config.name} will be put into maintenance mode.`
: ""
}
confirmLabel="Mark maintenance"
variant="default"
onConfirm={() => runAction(pending)}
/>
<ConfirmDialog
open={pending?.kind === "delete"}
onOpenChange={(o) => !o && setPending(null)}
title="Delete storage config?"
description={
pending
? `${pending.config.name} will be permanently removed. Objects already stored on this backend may become unreachable.`
: ""
}
confirmLabel="Delete"
variant="danger"
onConfirm={() => runAction(pending)}
/>
<StorageEditorDialog
state={editor}
onClose={() => setEditor(null)}
onSaved={async () => {
setEditor(null)
await refresh()
}}
onError={setError}
/>
</AppShell>
)
}
function statusTone(status: StorageStatus): BadgeTone {
if (status === "active") return "success"
if (status === "degraded") return "warning"
if (status === "maintenance") return "warning"
if (status === "inactive") return "default"
return "default"
}
function rowActions(
c: StorageConfig,
ctx: {
arcadia: ReturnType<typeof useArcadiaClient>
refresh: () => Promise<void>
setPending: (p: PendingAction) => void
setEditor: (s: EditorState) => void
setError: (msg: string | null) => void
validate: (c: StorageConfig) => Promise<void>
},
): ActionItem[] {
const { arcadia, refresh, setPending, setEditor, setError, validate } = ctx
const slug = slugify(c.name)
const items: ActionItem[] = []
items.push({
id: "validate",
label: "Validate",
icon: <ShieldCheck className="size-4" />,
dataAction: `storage-${slug}-validate`,
onSelect: () => validate(c),
})
items.push({
id: "edit",
label: "Edit",
dataAction: `storage-${slug}-edit`,
onSelect: () => setEditor({ mode: "edit", config: c }),
})
if (c.status === "active") {
items.push({
id: "deactivate",
label: "Deactivate",
icon: <Pause className="size-4" />,
dataAction: `storage-${slug}-deactivate`,
onSelect: () => setPending({ kind: "deactivate", config: c }),
})
} else {
items.push({
id: "activate",
label: "Activate",
icon: <Play className="size-4" />,
dataAction: `storage-${slug}-activate`,
onSelect: async () => {
try {
await activateStorageConfig(arcadia, c.id)
await refresh()
} catch (err) {
setError(err instanceof ArcadiaError ? err.message : "Activate failed.")
}
},
})
}
if (!c.is_default) {
items.push({
id: "set-default",
label: "Set as default",
icon: <Star className="size-4" />,
dataAction: `storage-${slug}-set-default`,
onSelect: async () => {
try {
await setDefaultStorageConfig(arcadia, c.id)
await refresh()
} catch (err) {
setError(err instanceof ArcadiaError ? err.message : "Set default failed.")
}
},
})
}
items.push({
id: "mark-degraded",
label: "Mark degraded",
icon: <Wrench className="size-4" />,
dataAction: `storage-${slug}-mark-degraded`,
onSelect: () => setPending({ kind: "degraded", config: c }),
})
items.push({
id: "mark-maintenance",
label: "Mark maintenance",
icon: <Wrench className="size-4" />,
dataAction: `storage-${slug}-mark-maintenance`,
onSelect: () => setPending({ kind: "maintenance", config: c }),
})
items.push({
id: "delete",
label: "Delete",
icon: <Trash2 className="size-4" />,
destructive: true,
dataAction: `storage-${slug}-delete`,
onSelect: () => setPending({ kind: "delete", config: c }),
})
return items
}
function StorageEditorDialog({
state,
onClose,
onSaved,
onError,
}: {
state: EditorState
onClose: () => void
onSaved: () => Promise<void>
onError: (msg: string | null) => void
}) {
const arcadia = useArcadiaClient()
const open = state !== null
const isEdit = state?.mode === "edit"
const initial = isEdit ? state.config : null
const [name, setName] = useState("")
const [backend, setBackend] = useState<StorageBackend>("s3")
const [isDefault, setIsDefault] = useState(false)
const [maxSize, setMaxSize] = useState<string>("")
const [allowedTypes, setAllowedTypes] = useState<string>("")
const [fields, setFields] = useState<Record<string, string>>({})
const [secretTouched, setSecretTouched] = useState<Record<string, boolean>>({})
const [saving, setSaving] = useState(false)
// Reset form whenever the dialog opens / target changes.
useEffect(() => {
if (!open) return
if (initial) {
setName(initial.name)
setBackend(initial.backend_type)
setIsDefault(initial.is_default)
setMaxSize(
initial.max_file_size_bytes == null ? "" : String(initial.max_file_size_bytes),
)
setAllowedTypes((initial.allowed_content_types ?? []).join(", "))
const initialFields: Record<string, string> = {}
const cfg = (initial.config ?? {}) as Record<string, unknown>
for (const k of Object.keys(cfg)) {
const v = cfg[k]
initialFields[k] = isMaskedSecret(v) ? "" : v == null ? "" : String(v)
}
setFields(initialFields)
setSecretTouched({})
} else {
setName("")
setBackend("s3")
setIsDefault(false)
setMaxSize("")
setAllowedTypes("")
setFields({})
setSecretTouched({})
}
}, [open, initial])
const required = REQUIRED_FIELDS[backend]
const optional = OPTIONAL_FIELDS[backend]
const setField = (key: string, value: string) => {
setFields((f) => ({ ...f, [key]: value }))
if (isSecretField(backend, key)) {
setSecretTouched((t) => ({ ...t, [key]: true }))
}
}
const submit = async () => {
onError(null)
setSaving(true)
try {
const config: Record<string, unknown> = {}
for (const k of [...required, ...optional]) {
const v = fields[k]
if (isSecretField(backend, k)) {
// Only send a secret if the user typed a fresh value.
if (secretTouched[k] && v !== "") config[k] = v
} else if (v !== undefined && v !== "") {
config[k] = v
}
}
const allowed = allowedTypes
.split(",")
.map((s) => s.trim())
.filter(Boolean)
const max = maxSize.trim() === "" ? null : Number(maxSize)
if (max != null && Number.isNaN(max)) {
throw new Error("Max file size must be a number (bytes).")
}
const input: StorageConfigInput = {
name,
backend_type: backend,
config,
is_default: isDefault,
max_file_size_bytes: max,
allowed_content_types: allowed.length ? allowed : undefined,
}
if (isEdit && initial) {
await updateStorageConfig(arcadia, initial.id, input)
} else {
await createStorageConfig(arcadia, input)
}
await onSaved()
} catch (err) {
onError(err instanceof ArcadiaError ? err.message : err instanceof Error ? err.message : "Save failed.")
} finally {
setSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{isEdit ? "Edit storage config" : "New storage config"}</DialogTitle>
<DialogDescription>
{isEdit
? "Secrets are write-only — leave masked fields blank to keep the existing value."
: "Connect a backend to start storing objects on this tenant."}
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="storage-name">Name</Label>
<Input
id="storage-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Primary S3 storage"
data-action="storage-form-name"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label>Backend</Label>
<Select
value={backend}
onValueChange={(v) => setBackend(v as StorageBackend)}
disabled={isEdit}
>
<SelectTrigger data-action="storage-form-backend">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="s3">S3 (or S3-compatible)</SelectItem>
<SelectItem value="gcs">Google Cloud Storage</SelectItem>
<SelectItem value="local">Local filesystem</SelectItem>
</SelectContent>
</Select>
</div>
{required.map((k) => (
<BackendField
key={k}
label={fieldLabel(k)}
field={k}
backend={backend}
value={fields[k] ?? ""}
originalIsMasked={
!!initial && isMaskedSecret((initial.config ?? {})[k as keyof typeof initial.config])
}
touched={!!secretTouched[k]}
onChange={(v) => setField(k, v)}
required
/>
))}
{optional.map((k) => (
<BackendField
key={k}
label={fieldLabel(k)}
field={k}
backend={backend}
value={fields[k] ?? ""}
originalIsMasked={false}
touched={false}
onChange={(v) => setField(k, v)}
/>
))}
<div className="flex flex-col gap-1.5">
<Label htmlFor="storage-max-size">Max file size (bytes)</Label>
<Input
id="storage-max-size"
value={maxSize}
onChange={(e) => setMaxSize(e.target.value)}
placeholder="e.g. 104857600"
data-action="storage-form-max-size"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="storage-allowed-types">Allowed content types (comma-separated)</Label>
<Textarea
id="storage-allowed-types"
value={allowedTypes}
onChange={(e) => setAllowedTypes(e.target.value)}
placeholder="image/jpeg, image/png, application/pdf"
data-action="storage-form-allowed-types"
rows={2}
/>
</div>
<div className="flex items-center justify-between rounded-md border px-3 py-2">
<div>
<div className="text-sm font-medium">Default backend</div>
<div className="text-xs text-muted-foreground">
New uploads go here unless another backend is specified.
</div>
</div>
<Switch
checked={isDefault}
onCheckedChange={setIsDefault}
data-action="storage-form-is-default"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={saving} data-action="storage-form-cancel">
Cancel
</Button>
<Button onClick={submit} disabled={saving || name.trim() === ""} data-action="storage-form-save">
{saving ? (
<RefreshCw className="size-4 animate-spin" />
) : (
<CheckCircle2 className="size-4" />
)}
{isEdit ? "Save changes" : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
function BackendField({
label,
field,
backend,
value,
originalIsMasked,
touched,
onChange,
required,
}: {
label: string
field: string
backend: StorageBackend
value: string
originalIsMasked: boolean
touched: boolean
onChange: (v: string) => void
required?: boolean
}) {
const secret = isSecretField(backend, field)
const isJson = field === "service_account_json"
const placeholder = secret && originalIsMasked && !touched ? "•••••• (unchanged)" : ""
const inputId = `storage-config-field-${field}`
return (
<div className="flex flex-col gap-1.5">
<Label htmlFor={inputId}>
{label}
{required ? <span className="ml-1 text-destructive">*</span> : null}
</Label>
{isJson ? (
<Textarea
id={inputId}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder || "Paste service account JSON"}
rows={4}
data-action={`storage-form-config-${field}`}
/>
) : (
<Input
id={inputId}
type={secret ? "password" : "text"}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
data-action={`storage-form-config-${field}`}
/>
)}
</div>
)
}
function fieldLabel(key: string): string {
return key
.split("_")
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" ")
}
function slugify(s: string): string {
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "config"
}
function formatBytes(n: number | null): string {
if (n == null) return "—"
const units = ["B", "KB", "MB", "GB", "TB"]
let i = 0
let v = n
while (v >= 1024 && i < units.length - 1) {
v /= 1024
i++
}
return `${v < 10 ? v.toFixed(1) : Math.round(v)} ${units[i]}`
}