Files
technitium-console/src/screens/apps/Profiles.tsx
T
DenozordecandClaude Opus 5.5 9742f0fe69
CI / check (push) Successful in 4m27s
Hub / check (push) Successful in 1m17s
CI / image (push) Successful in 1m54s
Hub / image (push) Successful in 1m56s
Hub stage 8: settings drift, webhook notices, profiles
The drift check now also covers the settings baseline and the Blocked
and Allowed lists baseline; the drift dialog offers Open compare,
Accept as baseline and Revert to baseline for them. Old drift.json
files still load.

HUB_WEBHOOK_URL (and an optional HUB_WEBHOOK_SECRET for an HMAC
signature) receives drift.found, drift.cleared and write.failed
notices, only on change, without values, never blocking a request and
never logging the address beyond its host. Admins see the webhook
status and can send a test from About and from the drift dialog.

Profiles bundle the hub's app, settings and lists baselines. Applying
one to a server runs install, app configs, settings and lists in order
after a preview; a failed step stops that server's later steps and
Retry failed resumes from it. Profiles export and import as a file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 02:11:19 +07:00

547 lines
23 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from 'react'
import {
applyProfile,
deleteProfile,
exportProfiles,
getProfile,
importProfiles,
listProfiles,
previewProfile,
snapshotProfile,
type ProfileImportPlan,
type ProfileSummary,
type ProfileTargetPreview,
type ProfileView,
} from '../../api/hub-profiles'
import type { RunOutcome } from '../../api/apps'
import { Alert } from '../../ui/Alert'
import { Button } from '../../ui/Button'
import { Check } from '../../ui/Check'
import { Confirm } from '../../ui/Confirm'
import { Dialog } from '../../ui/Dialog'
import { Empty, Failure } from '../../ui/Empty'
import { LabeledInput, LabeledTextarea } from '../../ui/Field'
import { Tag } from '../../ui/Tag'
import { Skeleton } from '@/components/ui/skeleton'
import { DiffView } from './ConfigDiffView'
import { RunFlow, pickerServers, type RunRequest } from './RunFlow'
/*
Behind a hub, for an admin: profiles, named bundles of store apps (with the hub's baseline config of
each), the shared settings and the Blocked and Allowed lists. One is made from the hub's current
baselines, can be exported to another hub, and is applied to one or several servers through the
same picker, review and results as every other change here. A server's steps run in order (apps,
app configs, settings, lists) and a failed one stops the rest for that server; "Retry failed" starts
again at the failed step. Nothing here shows a secret or an app's config text.
*/
const sessionEnded = (kind: string, message?: string): string => (kind === 'error' ? (message ?? 'Failed.') : 'The session ended.')
const when = (iso: string): string => (iso === '' ? '' : new Date(iso).toLocaleString())
const APP_STATE = {
install: ['warn', 'Will be installed'],
present: ['ok', 'Already installed'],
'version-differs': ['info', 'Other version installed'],
'not-in-store': ['dan', 'Not in this store'],
} as const
const CONFIG_STATE = {
same: ['ok', 'Same'],
differs: ['warn', 'Will change'],
'after-install': ['info', 'Set after install'],
unreadable: ['dan', 'Cannot read'],
} as const
/* ---- Apply: the review of what each server would get ---- */
function PreviewBody({ targets, opts }: { targets: ProfileTargetPreview[]; opts: { remove: boolean } }) {
const [remove, setRemove] = useState(opts.remove)
const extras = targets.reduce((n, t) => n + (t.lists?.blocked.extra ?? 0) + (t.lists?.allowed.extra ?? 0), 0)
return (
<div className="flex flex-col gap-6">
{targets.map((t) => (
<section key={t.server} aria-label={`Preview ${t.server}`} className="flex flex-col gap-3">
<h3 className="m-0 flex items-center gap-2 text-sm font-semibold">
{t.server}
{!t.ok && <Tag tone="dan">Cannot apply</Tag>}
</h3>
{t.error !== undefined && <Alert type="danger" title="Error">{t.error}</Alert>}
{t.warnings.map((w) => (
<Alert key={w} type="warning" title="Warning">
{w}
</Alert>
))}
{t.ok && (
<ol className="m-0 flex list-none flex-col gap-3 p-0" aria-label={`Steps on ${t.server}`}>
{t.apps.length > 0 && (
<li className="flex flex-col gap-1 text-sm">
<span className="font-medium">1. Apps</span>
<ul className="m-0 flex list-none flex-col gap-1 p-0 pl-4">
{t.apps.map((a) => (
<li key={a.name} className="flex flex-wrap items-center gap-2 text-xs">
<span className="font-medium">{a.name}</span>
<Tag tone={APP_STATE[a.state][0]}>{APP_STATE[a.state][1]}</Tag>
<span className="text-muted-foreground">
{a.state === 'version-differs' ? `${a.installedVersion} here, ${a.profileVersion} in the profile; it is not updated` : a.state === 'install' ? `Store offers ${a.storeVersion}` : `Version ${a.profileVersion}`}
</span>
</li>
))}
</ul>
</li>
)}
{t.configs.length > 0 && (
<li className="flex flex-col gap-1 text-sm">
<span className="font-medium">2. App configs</span>
<ul className="m-0 flex list-none flex-col gap-2 p-0 pl-4">
{t.configs.map((c) => (
<li key={c.name} className="flex flex-col gap-1 text-xs">
<span className="flex flex-wrap items-center gap-2">
<span className="font-medium">{c.name}</span>
<Tag tone={CONFIG_STATE[c.state][0]}>{CONFIG_STATE[c.state][1]}</Tag>
{c.error !== undefined && <span className="text-muted-foreground">{c.error}</span>}
</span>
{c.changes !== undefined && <DiffView diff={c.changes} from="Now" to="After apply" />}
</li>
))}
</ul>
</li>
)}
{t.settings !== null && (
<li className="flex flex-col gap-1 text-sm">
<span className="flex items-center gap-2 font-medium">
3. Settings
{t.settings.error !== undefined ? <Tag tone="dan">Cannot read</Tag> : t.settings.unchanged ? <Tag tone="ok">Already in sync</Tag> : <Tag tone="warn">{`${t.settings.fields.length} field(s) will change`}</Tag>}
</span>
{t.settings.error !== undefined && <span className="pl-4 text-xs text-muted-foreground">{t.settings.error}</span>}
{t.settings.secretFields.length > 0 && <span className="pl-4 text-xs text-muted-foreground">{t.settings.secretFields.join(', ')}: the secret values are sent but never shown.</span>}
{t.settings.error === undefined && !t.settings.unchanged && (
<div className="pl-4">
<DiffView diff={t.settings.changes} from="Now" to="After apply" />
</div>
)}
</li>
)}
{t.lists !== null && (
<li className="flex flex-col gap-1 text-sm">
<span className="flex items-center gap-2 font-medium">
4. Blocked and Allowed lists
{t.lists.error !== undefined ? <Tag tone="dan">Cannot read</Tag> : t.lists.status === 'same' ? <Tag tone="ok">Already in sync</Tag> : <Tag tone="warn">Will change</Tag>}
</span>
{t.lists.error !== undefined ? (
<span className="pl-4 text-xs text-muted-foreground">{t.lists.error}</span>
) : (
<span className="pl-4 text-xs text-muted-foreground">
Blocked: {t.lists.blocked.missing} to add, {t.lists.blocked.extra} extra. Allowed: {t.lists.allowed.missing} to add, {t.lists.allowed.extra} extra.
</span>
)}
{t.lists.tooMany !== undefined && <span className="pl-4 text-xs text-muted-foreground">{t.lists.tooMany}</span>}
</li>
)}
</ol>
)}
</section>
))}
{/* Only when a server has list domains the profile does not: otherwise there is nothing to remove. */}
{extras > 0 && (
<Check
label="Also remove extras"
help={`Deletes the ${extras} list domain(s) a server has that the profile does not. The server's lists are saved to the hub's history first.`}
checked={remove}
onChange={(on) => {
opts.remove = on
setRemove(on)
}}
/>
)}
</div>
)
}
/* The picker, the review and the results of applying one profile. */
function applyRequestFor(token: string | null, name: string, servers: { id: string; writable: boolean }[]): RunRequest {
const opts = { remove: false }
// Where each server should start next time: the step that failed on it.
const from: Record<string, string> = {}
return {
title: `Apply the profile ${name}`,
intro: 'Each server goes through the steps in order: install missing apps from its own store, apply the app configs, the settings, then the lists. A step that fails stops the later ones for that server.',
confirmLabel: 'Preview',
servers: pickerServers(servers),
preselected: [],
review: async (targets) => {
opts.remove = false
const outcome = await previewProfile(token, name, targets, false)
if (outcome.kind !== 'ok') return { kind: 'error', message: sessionEnded(outcome.kind, outcome.kind === 'error' ? outcome.message : undefined) }
return { kind: 'ok', confirmLabel: 'Apply', context: undefined, body: <PreviewBody targets={outcome.data.response.targets} opts={opts} /> }
},
run: async (targets): Promise<RunOutcome> => {
const outcome = await applyProfile(token, name, targets, opts.remove, { ...from })
if (outcome.kind === 'ok') {
for (const r of outcome.data.response.results) {
const failed = r.steps?.find((s) => s.status === 'failed')
if (r.ok || failed === undefined) delete from[r.server]
else from[r.server] = failed.step
}
}
return outcome
},
}
}
/* ---- Make one ---- */
function CreateProfile({ token, onClose, onDone }: { token: string | null; onClose: () => void; onDone: () => void }) {
const [name, setName] = useState('')
const [apps, setApps] = useState(true)
const [settings, setSettings] = useState(true)
const [lists, setLists] = useState(true)
const [busy, setBusy] = useState(false)
const [problem, setProblem] = useState<string | null>(null)
async function create() {
setBusy(true)
setProblem(null)
const outcome = await snapshotProfile(token, name.trim(), { apps: apps ? undefined : [], settings, lists })
setBusy(false)
if (outcome.kind !== 'ok') return setProblem(sessionEnded(outcome.kind, outcome.kind === 'error' ? outcome.message : undefined))
onDone()
}
return (
<Dialog
open
onOpenChange={(o) => {
if (!o) onClose()
}}
title="Create a profile"
close="Cancel"
actions={
<Button variant="primary" disabled={busy || name.trim() === '' || (!apps && !settings && !lists)} onClick={() => void create()}>
Create
</Button>
}
>
<p className="m-0 text-sm text-muted-foreground">
A profile is a copy of the hub&apos;s baselines as they are now. An existing profile with the same name is replaced.
</p>
{problem !== null && <Alert type="danger" title="Error">{problem}</Alert>}
<LabeledInput label="Profile name" value={name} maxLength={60} onChange={(e) => setName(e.target.value)} />
<div className="flex flex-col gap-3" role="group" aria-label="Parts">
<Check label="Apps" help="Every app that has a baseline, with its store version and its baseline config. Store apps only." checked={apps} onChange={setApps} />
<Check label="Settings" help="The shared fields of the settings baseline. Host fields stay out." checked={settings} onChange={setSettings} />
<Check label="Blocked and Allowed lists" help="The lists baseline." checked={lists} onChange={setLists} />
</div>
</Dialog>
)
}
/* ---- View one ---- */
function ViewProfile({ token, name, onClose }: { token: string | null; name: string; onClose: () => void }) {
const [view, setView] = useState<ProfileView | null>(null)
const [failure, setFailure] = useState<string | null>(null)
const load = useCallback(async () => {
const outcome = await getProfile(token, name)
if (outcome.kind === 'ok') {
setView(outcome.data.response)
setFailure(null)
} else setFailure(sessionEnded(outcome.kind, outcome.kind === 'error' ? outcome.message : undefined))
}, [token, name])
useEffect(() => {
void load()
}, [load])
return (
<Dialog
open
onOpenChange={(o) => {
if (!o) onClose()
}}
size="wide"
title={`Profile: ${name}`}
>
{failure !== null ? (
<Failure>
<span className="flex flex-col items-center gap-3">
<span>Could not read the profile. {failure}</span>
<Button variant="primary" onClick={() => void load()}>
Retry
</Button>
</span>
</Failure>
) : view === null ? (
<Skeleton className="h-24 w-full" role="status" aria-label="Loading the profile" />
) : (
<div className="flex flex-col gap-4">
<p className="m-0 text-xs text-muted-foreground">
Made by {view.updatedBy} at {when(view.updatedAt)}. Secrets show as {'<secret>'}; an app&apos;s config text is not shown.
</p>
<section aria-label="Apps" className="flex flex-col gap-2">
<h3 className="m-0 text-sm font-semibold">Apps</h3>
{view.apps.length === 0 ? (
<Empty compact>No apps.</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-1 p-0">
{view.apps.map((a) => (
<li key={a.name} className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{a.name}</span>
<span className="text-muted-foreground">{a.version}</span>
<Tag tone={a.hasConfig ? 'info' : 'neutral'}>{a.hasConfig ? 'With config' : 'No config'}</Tag>
</li>
))}
</ul>
)}
</section>
<section aria-label="Settings" className="flex flex-col gap-2">
<h3 className="m-0 text-sm font-semibold">Settings</h3>
{view.settings === null ? <Empty compact>Not part of this profile.</Empty> : <LabeledTextarea label="Shared settings (JSON)" mono rows={10} readOnly spellCheck={false} value={JSON.stringify(view.settings, null, 2)} onChange={() => {}} />}
</section>
<section aria-label="Lists" className="flex flex-col gap-2">
<h3 className="m-0 text-sm font-semibold">Blocked and Allowed lists</h3>
{view.lists === null ? <Empty compact>Not part of this profile.</Empty> : <p className="m-0 text-sm">{view.lists.blocked} blocked and {view.lists.allowed} allowed domains.</p>}
</section>
</div>
)}
</Dialog>
)
}
/* ---- Import ---- */
function ImportProfiles({ token, onClose, onDone }: { token: string | null; onClose: () => void; onDone: () => void }) {
const [text, setText] = useState<string | null>(null)
const [plan, setPlan] = useState<ProfileImportPlan | null>(null)
const [problem, setProblem] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [done, setDone] = useState(false)
const fileRef = useRef<HTMLInputElement>(null)
async function check() {
const file = fileRef.current?.files?.[0]
if (!file) return setProblem('Please select a profiles file.')
setBusy(true)
setProblem(null)
const content = await file.text()
const outcome = await importProfiles(token, content, false)
setBusy(false)
if (outcome.kind !== 'ok') return setProblem(sessionEnded(outcome.kind, outcome.kind === 'error' ? outcome.message : undefined))
setText(content)
setPlan(outcome.data.response)
}
async function commit() {
if (text === null) return
setBusy(true)
const outcome = await importProfiles(token, text, true)
setBusy(false)
if (outcome.kind !== 'ok') return setProblem(sessionEnded(outcome.kind, outcome.kind === 'error' ? outcome.message : undefined))
setPlan(outcome.data.response)
setDone(true)
onDone()
}
const changes = plan?.profiles.filter((p) => p.status !== 'same').length ?? 0
const TONE = { new: 'info', changed: 'warn', same: 'ok' } as const
const LABEL = { new: 'New', changed: 'Changed', same: 'Same' } as const
return (
<Dialog
open
onOpenChange={(o) => {
if (!o) onClose()
}}
title="Import profiles"
actions={
plan === null ? (
<Button variant="primary" disabled={busy} onClick={() => void check()}>
Check file
</Button>
) : !done ? (
<Button variant="primary" disabled={busy || changes === 0} onClick={() => void commit()}>
Import
</Button>
) : undefined
}
>
{problem !== null && <Alert type="danger" title="Error">{problem}</Alert>}
{plan === null ? (
<>
<p className="m-0 text-sm text-muted-foreground">Choose a file made by Export. It is checked first; nothing is changed until you press Import, and no server is touched.</p>
<LabeledInput label="Profiles file" type="file" accept="application/json,.json" ref={fileRef} />
</>
) : (
<>
{done && <Alert type="success" title="Imported.">The profiles were saved.</Alert>}
<ul className="m-0 flex list-none flex-col gap-2 p-0" aria-label="Profiles in the file">
{plan.profiles.map((p) => (
<li key={p.name} className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{p.name}</span>
<Tag tone={TONE[p.status]}>{LABEL[p.status]}</Tag>
<span className="text-xs text-muted-foreground">{p.apps} app(s){p.settings ? ', settings' : ''}{p.lists ? ', lists' : ''}</span>
</li>
))}
</ul>
</>
)}
</Dialog>
)
}
/* ---- The list ---- */
export function Profiles({
open,
onOpenChange,
token,
servers,
}: {
open: boolean
onOpenChange: (o: boolean) => void
token: string | null
/** The servers of the hub, and whether it holds an admin token for each. */
servers: { id: string; writable: boolean }[]
}) {
const [profiles, setProfiles] = useState<ProfileSummary[] | null>(null)
const [failure, setFailure] = useState<string | null>(null)
const [creating, setCreating] = useState(false)
const [importing, setImporting] = useState(false)
const [viewing, setViewing] = useState<string | null>(null)
const [deleting, setDeleting] = useState<string | null>(null)
const [request, setRequest] = useState<RunRequest | null>(null)
const [problem, setProblem] = useState<string | null>(null)
const load = useCallback(async () => {
const outcome = await listProfiles(token)
if (outcome.kind === 'ok') {
setProfiles(outcome.data.response.profiles)
setFailure(null)
} else setFailure(sessionEnded(outcome.kind, outcome.kind === 'error' ? outcome.message : undefined))
}, [token])
useEffect(() => {
if (open) void load()
}, [open, load])
async function exportFile(name: string) {
setProblem(null)
const outcome = await exportProfiles(token, name)
if (outcome.kind !== 'ok') return setProblem(sessionEnded(outcome.kind, outcome.kind === 'error' ? outcome.message : undefined))
const url = URL.createObjectURL(new Blob([outcome.data.text], { type: 'application/json' }))
const link = document.createElement('a')
link.href = url
link.download = outcome.data.filename
link.click()
URL.revokeObjectURL(url)
}
async function remove(name: string) {
const outcome = await deleteProfile(token, name)
if (outcome.kind !== 'ok') setProblem(sessionEnded(outcome.kind, outcome.kind === 'error' ? outcome.message : undefined))
await load()
}
const create = (
<Button variant="primary" onClick={() => setCreating(true)}>
Create from current baselines
</Button>
)
return (
<>
<Dialog
open={open}
onOpenChange={onOpenChange}
size="wide"
title="Profiles"
actions={
<>
<Button onClick={() => setImporting(true)}>Import profiles</Button>
{profiles !== null && profiles.length > 0 && create}
</>
}
>
<p className="m-0 text-sm text-muted-foreground">
A profile brings a new or reset server in line: it installs the apps from that server&apos;s own store and applies their configs, the shared settings and the Blocked and Allowed lists.
</p>
{problem !== null && <Alert type="danger" title="Error">{problem}</Alert>}
{failure !== null && profiles === null ? (
<Failure>
<span className="flex flex-col items-center gap-3">
<span>Could not read the profiles. {failure}</span>
<Button variant="primary" onClick={() => void load()}>
Retry
</Button>
</span>
</Failure>
) : profiles === null ? (
<div className="flex flex-col gap-3" role="status" aria-label="Loading the profiles">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
) : profiles.length === 0 ? (
<Empty title="No profiles yet" actions={create}>
Make one from the baselines the hub holds now, or import a file from another hub.
</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-3 p-0" aria-label="Profiles">
{profiles.map((p) => (
<li key={p.name} aria-label={p.name} className="flex flex-wrap items-center gap-3 border-b border-border pb-3 text-sm last:border-b-0">
<span className="font-medium">{p.name}</span>
<Tag tone="neutral">{`${p.apps} app${p.apps === 1 ? '' : 's'}`}</Tag>
{p.configs > 0 && <Tag tone="neutral">{`${p.configs} config${p.configs === 1 ? '' : 's'}`}</Tag>}
{p.settings !== null && <Tag tone="neutral">{`${p.settings} settings`}</Tag>}
{p.lists !== null && <Tag tone="neutral">{`${p.lists.blocked + p.lists.allowed} list domains`}</Tag>}
<span className="text-xs text-muted-foreground">{p.updatedBy} · {when(p.updatedAt)}</span>
<span className="ml-auto flex flex-wrap gap-2">
<Button size="sm" onClick={() => setViewing(p.name)}>
View
</Button>
<Button size="sm" variant="primary" onClick={() => setRequest(applyRequestFor(token, p.name, servers))}>
Apply to servers…
</Button>
<Button size="sm" onClick={() => void exportFile(p.name)}>
Export
</Button>
<Button size="sm" variant="danger" onClick={() => setDeleting(p.name)}>
Delete
</Button>
</span>
</li>
))}
</ul>
)}
</Dialog>
{creating && (
<CreateProfile
token={token}
onClose={() => setCreating(false)}
onDone={() => {
setCreating(false)
void load()
}}
/>
)}
{importing && (
<ImportProfiles
token={token}
onClose={() => setImporting(false)}
onDone={() => void load()}
/>
)}
{viewing !== null && <ViewProfile token={token} name={viewing} onClose={() => setViewing(null)} />}
<Confirm
open={deleting !== null}
title="Delete profile"
text={`Delete the profile ${deleting ?? ''}? Servers that already had it applied keep what they got.`}
label="Delete"
onClose={() => setDeleting(null)}
onConfirm={() => deleting !== null && remove(deleting)}
/>
{request !== null && <RunFlow request={request} onClose={() => setRequest(null)} />}
</>
)
}