SPB Git

Repository Public

Activity.tsx 8.3 KB 105 lines tsx

1// Activity: the hash-chained audit trail, verified in this browser.2import { useCallback, useEffect, useMemo, useState } from "react";3import { dateTime, engine, onLive, reportError } from "../state.ts";4import { Badge, Btn, Callout, Empty, ErrorText, Icon, type IconName, PageHead, Segmented, Skeleton } from "./common.tsx";56type Cat = "all" | "security" | "sharing" | "agents";7const NAMES: Record<string, [string, IconName]> = {8  "account.created": ["Account created", "user"], "account.rekeyed": ["Account rekeyed", "refresh"], "session.login": ["Signed in with passkey", "passkey"],9  "passkey.added": ["Passkey added", "passkey"], "passkey.removed": ["Passkey removed", "passkey"],10  "device.enrolled": ["Device enrolled", "device"], "device.revoked": ["Device revoked", "device"],11  "recovery.started": ["Recovery attempt started", "alert"], "recovery.rotated": ["Recovery key replaced", "key"],12  "vault.created": ["Vault created", "vault"], "vault.deleted": ["Vault deleted", "vault"], "vault.member_added": ["Vault member added", "users"],13  "vault.shared_with_you": ["A vault was shared with you", "users"], "vault.access_removed": ["Your access to a vault was removed", "users"], "vault.key_rotated": ["Vault key rotated", "refresh"],14  "share.created": ["Item shared", "share"], "share.received": ["Item received", "inbox"], "share.opened": ["Shared item opened", "eye"], "share.revoked": ["Share revoked", "share"],15  "export.plaintext": ["Plaintext export", "alert"], "export.backup": ["Encrypted backup exported", "download"], "import": ["Items imported", "upload"], "item.revealed-bulk": ["Many secrets revealed", "eye"],16  "connect.identity_created": ["Workload identity created", "bot"], "connect.identity_revoked": ["Workload identity revoked", "bot"],17  "connect.secret_created": ["Managed secret created", "key"], "connect.secret_rotated": ["Managed secret rotated", "refresh"], "connect.secret_deleted": ["Managed secret deleted", "trash"],18  "connect.grant_created": ["Grant created", "check"], "connect.grant_revoked": ["Grant revoked", "x"], "connect.approved": ["Agent request approved", "check"], "connect.denied": ["Agent request denied", "x"],19  "connect.kill_engaged": ["Kill switch engaged", "power"], "connect.kill_released": ["Kill switch released", "power"],20  "agent.denied": ["Agent request refused by policy", "alert"], "agent.approval_requested": ["Agent asked for approval", "bot"], "agent.secret_delivered": ["Secret delivered to a workload", "alert"], "agent.operation": ["Brokered operation", "bot"],21};22const catOf = (kind: string): Exclude<Cat, "all"> | "other" =>23  /^(connect|agent)\./.test(kind) ? "agents" : /^share\.|^vault\.(member_added|shared_with_you|access_removed)$/.test(kind) ? "sharing" : /^(account|session|passkey|device|recovery|export)\.|^import$|^item\.|^vault\.key_rotated$/.test(kind) ? "security" : "other";24const NOTABLE = new Set(["device.enrolled", "device.revoked", "recovery.started", "recovery.rotated", "account.rekeyed", "export.plaintext", "agent.secret_delivered", "connect.kill_engaged", "passkey.added", "passkey.removed"]);2526const short = (id: unknown) => (typeof id === "string" ? id.slice(0, 8) : "");27function detailText(e: any): string {28  const d = e.detail ?? {}, parts: string[] = [];29  if (d.platform) parts.push(String(d.platform));30  if (d.via) parts.push(d.via === "recovery-key" ? "using the recovery key" : `via ${d.via}`);31  if (d.kind && e.kind.startsWith("share.")) parts.push(d.kind === "link" ? "by link" : "to an account");32  if (d.kind && e.kind.startsWith("connect.")) parts.push(String(d.kind));33  if (d.role) parts.push(`role ${d.role}`);34  if (d.views != null) parts.push(`view ${d.views}`);35  if (d.epoch != null) parts.push(`epoch ${d.epoch}`);36  if (d.keyEpoch != null) parts.push(`key epoch ${d.keyEpoch}`);37  if (d.removed) parts.push(`${d.removed} member removed`);38  if (d.mode) parts.push(`mode ${d.mode}`);39  if (d.approval && typeof d.approval === "string" && d.approval.length < 10) parts.push(`approval ${d.approval}`);40  if (d.op) parts.push(`operation ${d.op}`);41  if (d.method && d.host) parts.push(`${d.method} ${d.host}`);42  if (d.reason) parts.push(String(d.reason));43  if (d.version != null) parts.push(`version ${d.version}`);44  for (const k of ["vault", "share", "secret", "identity", "grant", "device"]) if (typeof d[k] === "string") parts.push(`${k} ${short(d[k])}…`);45  return parts.join(" · ");46}4748export function ActivityPage({ onBack }: { onBack: () => void }) {49  const [events, setEvents] = useState<any[] | null>(null);50  const [verified, setVerified] = useState<boolean | null>(null);51  const [more, setMore] = useState(true);52  const [cat, setCat] = useState<Cat>("all");53  const [devices, setDevices] = useState<Map<string, string>>(new Map());54  const [error, setError] = useState("");55  const [busy, setBusy] = useState(false);5657  const load = useCallback(async (append: any[] | null) => {58    setBusy(true);59    try {60      const page = await engine.audit(append?.length ? append[append.length - 1].id : undefined);61      const all = append ? [...append, ...page] : page;62      setEvents(all); setMore(page.length >= 100); setError("");63      setVerified(all.length ? await engine.verifyAuditPage(all) : null);64    } catch (e) { reportError(e); setError("The activity log could not be loaded."); }65    finally { setBusy(false); }66  }, []);67  useEffect(() => {68    void load(null);69    engine.devices().then((ds) => setDevices(new Map(ds.map((d) => [d.deviceId, d.current ? `${d.platform} (this device)` : d.platform]))), () => {});70    return onLive(["activity"], () => void load(null));71  }, [load]);7273  const shown = useMemo(() => (events ?? []).filter((e) => cat === "all" || catOf(e.kind) === cat), [events, cat]);74  const actor = (e: any) => e.actor === "public-link" ? "Someone holding a share link" : typeof e.actor === "string" && e.actor.startsWith("agent:") ? `Workload ${short(e.actor.slice(6))}…` : e.deviceId ? devices.get(e.deviceId) ?? `Device ${short(e.deviceId)}… (removed)` : "Server / another account";7576  return (77    <div className="page" data-testid="activity-page">78      <PageHead title="Activity" sub="Security-relevant events of your account. Entries never contain item content. Each entry is chained to the previous one by a hash that this browser recomputes." onBack={onBack} actions={<Btn small icon="refresh" onClick={() => load(null)} busy={busy}>Refresh</Btn>} />79      {verified === true && <Callout kind="ok" title="Chain verified ✓"><p data-testid="chain-status">The {events!.length} loaded entries link to each other without a gap or alteration.</p></Callout>}80      {verified === false && <Callout kind="security" title="Chain ALTERED"><p data-testid="chain-status">The hash chain of the loaded entries does not verify: entries were modified, removed or reordered on the server. Treat this server as compromised.</p></Callout>}81      <ErrorText text={error} />82      <Segmented label="Category" value={cat} onChange={setCat} options={[{ value: "all", label: "All" }, { value: "security", label: "Security" }, { value: "sharing", label: "Sharing" }, { value: "agents", label: "Agents" }]} />83      {!events && !error ? <Skeleton rows={5} /> : shown.length === 0 ? <Empty icon="activity" title="No activity in this category" /> : (84        <ol className="timeline" data-testid="activity-list">85          {shown.map((e) => {86            const [name, icon] = NAMES[e.kind] ?? [e.kind, "activity" as IconName];87            return (88              <li key={e.id} className={NOTABLE.has(e.kind) ? "notable" : ""}>89                <span className="tl-icon"><Icon name={icon} size={16} /></span>90                <div className="tl-body">91                  <strong>{name} {NOTABLE.has(e.kind) && <Badge kind="brass">review</Badge>}</strong>92                  <span className="muted">{dateTime(e.at)} · {actor(e)}</span>93                  {detailText(e) && <span className="muted small">{detailText(e)}</span>}94                </div>95              </li>96            );97          })}98        </ol>99      )}100      {events && more && <div className="row center"><Btn onClick={() => load(events)} busy={busy}>Load older entries</Btn></div>}101      <p className="fine">Verification covers the entries loaded on this page. A server could still withhold the newest entries from a device: compare “Verify sync state” between two devices to detect divergence.</p>102    </div>103  );104}105
Files main
Menu

Theme