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 (
{targets.map((t) => (

{t.server} {!t.ok && Cannot apply}

{t.error !== undefined && {t.error}} {t.warnings.map((w) => ( {w} ))} {t.ok && (
    {t.apps.length > 0 && (
  1. 1. Apps
      {t.apps.map((a) => (
    • {a.name} {APP_STATE[a.state][1]} {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}`}
    • ))}
  2. )} {t.configs.length > 0 && (
  3. 2. App configs
      {t.configs.map((c) => (
    • {c.name} {CONFIG_STATE[c.state][1]} {c.error !== undefined && {c.error}} {c.changes !== undefined && }
    • ))}
  4. )} {t.settings !== null && (
  5. 3. Settings {t.settings.error !== undefined ? Cannot read : t.settings.unchanged ? Already in sync : {`${t.settings.fields.length} field(s) will change`}} {t.settings.error !== undefined && {t.settings.error}} {t.settings.secretFields.length > 0 && {t.settings.secretFields.join(', ')}: the secret values are sent but never shown.} {t.settings.error === undefined && !t.settings.unchanged && (
    )}
  6. )} {t.lists !== null && (
  7. 4. Blocked and Allowed lists {t.lists.error !== undefined ? Cannot read : t.lists.status === 'same' ? Already in sync : Will change} {t.lists.error !== undefined ? ( {t.lists.error} ) : ( Blocked: {t.lists.blocked.missing} to add, {t.lists.blocked.extra} extra. Allowed: {t.lists.allowed.missing} to add, {t.lists.allowed.extra} extra. )} {t.lists.tooMany !== undefined && {t.lists.tooMany}}
  8. )}
)}
))} {/* Only when a server has list domains the profile does not: otherwise there is nothing to remove. */} {extras > 0 && ( { opts.remove = on setRemove(on) }} /> )}
) } /* 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 = {} 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: } }, run: async (targets): Promise => { 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(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 ( { if (!o) onClose() }} title="Create a profile" close="Cancel" actions={ } >

A profile is a copy of the hub's baselines as they are now. An existing profile with the same name is replaced.

{problem !== null && {problem}} setName(e.target.value)} />
) } /* ---- View one ---- */ function ViewProfile({ token, name, onClose }: { token: string | null; name: string; onClose: () => void }) { const [view, setView] = useState(null) const [failure, setFailure] = useState(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 ( { if (!o) onClose() }} size="wide" title={`Profile: ${name}`} > {failure !== null ? ( Could not read the profile. {failure} ) : view === null ? ( ) : (

Made by {view.updatedBy} at {when(view.updatedAt)}. Secrets show as {''}; an app's config text is not shown.

Apps

{view.apps.length === 0 ? ( No apps. ) : (
    {view.apps.map((a) => (
  • {a.name} {a.version} {a.hasConfig ? 'With config' : 'No config'}
  • ))}
)}

Settings

{view.settings === null ? Not part of this profile. : {}} />}

Blocked and Allowed lists

{view.lists === null ? Not part of this profile. :

{view.lists.blocked} blocked and {view.lists.allowed} allowed domains.

}
)}
) } /* ---- Import ---- */ function ImportProfiles({ token, onClose, onDone }: { token: string | null; onClose: () => void; onDone: () => void }) { const [text, setText] = useState(null) const [plan, setPlan] = useState(null) const [problem, setProblem] = useState(null) const [busy, setBusy] = useState(false) const [done, setDone] = useState(false) const fileRef = useRef(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 ( { if (!o) onClose() }} title="Import profiles" actions={ plan === null ? ( ) : !done ? ( ) : undefined } > {problem !== null && {problem}} {plan === null ? ( <>

Choose a file made by Export. It is checked first; nothing is changed until you press Import, and no server is touched.

) : ( <> {done && The profiles were saved.}
    {plan.profiles.map((p) => (
  • {p.name} {LABEL[p.status]} {p.apps} app(s){p.settings ? ', settings' : ''}{p.lists ? ', lists' : ''}
  • ))}
)}
) } /* ---- 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(null) const [failure, setFailure] = useState(null) const [creating, setCreating] = useState(false) const [importing, setImporting] = useState(false) const [viewing, setViewing] = useState(null) const [deleting, setDeleting] = useState(null) const [request, setRequest] = useState(null) const [problem, setProblem] = useState(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 = ( ) return ( <> {profiles !== null && profiles.length > 0 && create} } >

A profile brings a new or reset server in line: it installs the apps from that server's own store and applies their configs, the shared settings and the Blocked and Allowed lists.

{problem !== null && {problem}} {failure !== null && profiles === null ? ( Could not read the profiles. {failure} ) : profiles === null ? (
) : profiles.length === 0 ? ( Make one from the baselines the hub holds now, or import a file from another hub. ) : (
    {profiles.map((p) => (
  • {p.name} {`${p.apps} app${p.apps === 1 ? '' : 's'}`} {p.configs > 0 && {`${p.configs} config${p.configs === 1 ? '' : 's'}`}} {p.settings !== null && {`${p.settings} settings`}} {p.lists !== null && {`${p.lists.blocked + p.lists.allowed} list domains`}} {p.updatedBy} · {when(p.updatedAt)}
  • ))}
)}
{creating && ( setCreating(false)} onDone={() => { setCreating(false) void load() }} /> )} {importing && ( setImporting(false)} onDone={() => void load()} /> )} {viewing !== null && setViewing(null)} />} setDeleting(null)} onConfirm={() => deleting !== null && remove(deleting)} /> {request !== null && setRequest(null)} />} ) }