@agent-custody/receipts 0.16.4 → 0.16.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +7 -4
  2. package/dist/a2a.js +1 -1
  3. package/dist/cli.js +50 -7
  4. package/dist/console-page.js +144 -50
  5. package/dist/deny-report.d.ts +7 -0
  6. package/dist/deny-report.js +14 -5
  7. package/dist/design.d.ts +11 -0
  8. package/dist/design.js +91 -0
  9. package/dist/index.d.ts +4 -0
  10. package/dist/index.js +3 -0
  11. package/dist/log-admin.d.ts +2 -0
  12. package/dist/log-admin.js +113 -62
  13. package/dist/log-store.d.ts +8 -2
  14. package/dist/log-store.js +24 -12
  15. package/dist/perathos.d.ts +50 -0
  16. package/dist/perathos.js +187 -0
  17. package/dist/portal.d.ts +66 -5
  18. package/dist/portal.js +923 -246
  19. package/dist/session-audit.d.ts +46 -0
  20. package/dist/session-audit.js +150 -0
  21. package/dist/site-links.d.ts +23 -0
  22. package/dist/site-links.js +29 -0
  23. package/docs/acs.md +2 -0
  24. package/docs/approvals.md +1 -1
  25. package/docs/completeness.md +1 -1
  26. package/docs/configuration.md +2 -0
  27. package/docs/console.md +11 -2
  28. package/docs/door-signals.md +1 -1
  29. package/docs/door.md +4 -16
  30. package/docs/egress.md +3 -1
  31. package/docs/github-action.md +2 -2
  32. package/docs/mandates.md +1 -1
  33. package/docs/perathos.md +97 -0
  34. package/docs/sdk.md +32 -1
  35. package/docs/threat-model.md +2 -1
  36. package/docs/tutorials.md +2 -0
  37. package/docs/usage.md +4 -2
  38. package/docs/verification.md +1 -1
  39. package/package.json +1 -1
  40. package/vectors/interop/perathos/LICENSE +21 -0
  41. package/vectors/interop/perathos/README.md +17 -0
  42. package/vectors/interop/perathos/pocketos-replay/session.head.json +11 -0
  43. package/vectors/interop/perathos/pocketos-replay/session.jsonl +8 -0
  44. package/vectors/interop/perathos/pocketos-replay/verification.json +65 -0
@@ -8,7 +8,8 @@ import { policyDigest, policyReasons, policyRules } from "./policy.js";
8
8
  import { verifyBundle } from "./verify.js";
9
9
  const ANNOTATIONS = /^(?:\s*@\w+\s*\("(?:[^"\\]|\\.)*"\))+\s*/;
10
10
  const TARGET_ARGS = ["command", "file_path", "notebook_path", "path", "url"];
11
- function targetOf(args) {
11
+ /** The command, file path, or URL of a call, for a one-line listing. */
12
+ export function targetOf(args) {
12
13
  if (!args || typeof args !== "object")
13
14
  return "(withheld)";
14
15
  const a = args;
@@ -16,6 +17,11 @@ function targetOf(args) {
16
17
  const text = name ? a[name] : JSON.stringify(a);
17
18
  return text.replace(/\s+/g, " ").trim();
18
19
  }
20
+ /** The `@reason` and the text of each rule a decision names, from the policy's rules and reasons by their ids. */
21
+ export function ruleTexts(policyIds, rules, reasons) {
22
+ const at = (list) => policyIds.map((id) => list[Number(id.replace(/^policy/, ""))]).filter((r) => typeof r === "string");
23
+ return { reasons: at(reasons), rules: at(rules).map((r) => r.replace(/\s+/g, " ").replace(/;$/, "").replace(ANNOTATIONS, "").trim()) };
24
+ }
19
25
  export function denyReport(configFile) {
20
26
  const cfg = loadSdkConfig(configFile);
21
27
  const issuer = loadPrivateKey(cfg.identity.keyFile);
@@ -31,12 +37,14 @@ export function denyReport(configFile) {
31
37
  const reasons = policyText === null ? [] : policyReasons(policyText);
32
38
  const currentDigest = policyText === null ? null : policyDigest(policyText);
33
39
  const report = { configFile, receiptsDir: cfg.receiptsDir, observe: cfg.mode === "observe", verified: 0, wouldDeny: [], denied: [], unverified: [] };
40
+ const leafOf = new Map();
34
41
  const files = existsSync(cfg.receiptsDir)
35
42
  ? readdirSync(cfg.receiptsDir, { withFileTypes: true }).filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(".json") && !e.name.endsWith(".authorization.json")).map((e) => e.name).sort()
36
43
  : [];
37
44
  for (const file of files) {
38
45
  try {
39
- const result = verifyBundle(JSON.parse(readFileSync(join(cfg.receiptsDir, file), "utf8")), opts);
46
+ const bundle = JSON.parse(readFileSync(join(cfg.receiptsDir, file), "utf8"));
47
+ const result = verifyBundle(bundle, opts);
40
48
  if (!result.ok || !result.statement) {
41
49
  const failed = result.checks.filter((c) => !c.ok).map((c) => c.name);
42
50
  throw new Error(`failed: ${failed.join("; ")}`);
@@ -55,16 +63,17 @@ export function denyReport(configFile) {
55
63
  tool: p.tool.name,
56
64
  target: targetOf(p.request.args),
57
65
  policyIds,
58
- reasons: known ? policyIds.map((id) => reasons[Number(id.replace(/^policy/, ""))]).filter((r) => typeof r === "string") : [],
59
- rules: known ? policyIds.map((id) => rules[Number(id.replace(/^policy/, ""))]).filter((r) => typeof r === "string").map((r) => r.replace(/\s+/g, " ").replace(/;$/, "").replace(ANNOTATIONS, "").trim()) : [],
66
+ ...(known ? ruleTexts(policyIds, rules, reasons) : { reasons: [], rules: [] }),
60
67
  };
68
+ leafOf.set(call, bundle.inclusion.leafIndex);
61
69
  (p.policy.enforced === false ? report.wouldDeny : report.denied).push(call);
62
70
  }
63
71
  catch (e) {
64
72
  report.unverified.push({ file, reason: e instanceof Error ? e.message : String(e) });
65
73
  }
66
74
  }
67
- const byTime = (a, b) => (a.timestamp < b.timestamp ? -1 : a.timestamp > b.timestamp ? 1 : 0);
75
+ // Calls in the same millisecond share a timestamp, so the log's leaf index, the order they were recorded, breaks the tie.
76
+ const byTime = (a, b) => (a.timestamp < b.timestamp ? -1 : a.timestamp > b.timestamp ? 1 : leafOf.get(a) - leafOf.get(b));
68
77
  report.wouldDeny.sort(byTime);
69
78
  report.denied.sort(byTime);
70
79
  return report;
@@ -0,0 +1,11 @@
1
+ /** The app pages: the tokens, light and dark (system or data-theme), the base, and the shared components. */
2
+ export declare const DESIGN_CSS: string;
3
+ /** The site: the same tokens and components; VitePress sets the dark class itself. */
4
+ export declare const SITE_CSS: string;
5
+ /** The logo: a receipt with a check mark. The tile takes the accent colour, so the mark follows the theme. */
6
+ export declare const LOGO_MARK = "<svg class=\"mark\" viewBox=\"0 0 64 64\" aria-hidden=\"true\"><rect class=\"tile\" width=\"64\" height=\"64\" rx=\"14\"/><path d=\"M19 11H45V45L41.75 48 38.5 45 35.25 48 32 45 28.75 48 25.5 45 22.25 48 19 45Z\" fill=\"#fff\"/><path class=\"ink\" d=\"M25 20h14M25 27h14\" stroke-width=\"2.6\" stroke-linecap=\"round\"/><path class=\"ink\" d=\"M25 37.5l5 4.5 9.5-10\" fill=\"none\" stroke-width=\"3.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>";
7
+ /** The header of the review page and the case file: the logo, the name of the page, and the theme toggle. */
8
+ export declare const appHeader: (name: string) => string;
9
+ export declare const APP_HEADER_CSS = "\n.apphead { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-3) var(--space-4); border-bottom: 1px solid var(--line); background: var(--panel); }\n.apphead .brand { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--ink); font-weight: 700; text-decoration: none; }\n.apphead .pill { padding: 0 var(--space-2); border-radius: var(--radius-full); background: var(--accent-bg); color: var(--accent); font: 600 var(--text-xs)/1.6 var(--font); }\n.apphead #themeToggle { margin-left: auto; }\n.mark { width: 28px; height: 28px; display: block; } .mark .tile { fill: var(--accent); } .mark .ink { stroke: var(--accent); }\n#themeToggle[aria-pressed=\"true\"] .moon, #themeToggle[aria-pressed=\"false\"] .sun { display: none; }\n";
10
+ /** Applies the saved theme and wires the toggle. It uses the storage key of the portal. Put it after the button. */
11
+ export declare const THEME_SCRIPT = "(() => {\n const root = document.documentElement, button = document.getElementById(\"themeToggle\");\n try { const saved = localStorage.getItem(\"agent-custody-theme\"); if (saved === \"dark\" || saved === \"light\") root.dataset.theme = saved; } catch {}\n const now = () => root.dataset.theme || (matchMedia(\"(prefers-color-scheme: dark)\").matches ? \"dark\" : \"light\");\n const label = () => button.setAttribute(\"aria-pressed\", String(now() === \"dark\"));\n button.onclick = () => { const next = now() === \"dark\" ? \"light\" : \"dark\"; root.dataset.theme = next; try { localStorage.setItem(\"agent-custody-theme\", next); } catch {} label(); };\n label();\n})();\n";
package/dist/design.js ADDED
@@ -0,0 +1,91 @@
1
+ // The design tokens and the shared components of every surface: the site, the portal, the log admin, the gateway
2
+ // console, the review page, and the offline case file. The app pages inline DESIGN_CSS, so they make no outside request.
3
+ // The site imports site/.vitepress/theme/tokens.css, which a test keeps identical to SITE_CSS.
4
+ // "Inter" comes from VitePress on the site; the app pages use it only when the machine has it installed.
5
+ const LIGHT = `--bg: #fafaf9; --panel: #ffffff; --soft: #f5f5f4; --line: #e7e5e4; --line-strong: #d6d3d1;
6
+ --ink: #1c1917; --ink2: #57534e; --ink3: #78716c;
7
+ --accent: #b45309; --accent-hover: #92400e; --accent-active: #78350f; --accent-ink: #ffffff; --accent-bg: #fef3c7;
8
+ --ok: #15803d; --ok-bg: #dcfce7; --warn: #a16207; --warn-bg: #fef9c3; --bad: #b91c1c; --bad-bg: #fee2e2;
9
+ --shadow: 0 1px 2px rgb(28 25 23 / .05), 0 18px 40px -18px rgb(28 25 23 / .25);`;
10
+ const DARK = `--bg: #0c0a09; --panel: #1c1917; --soft: #292524; --line: #292524; --line-strong: #44403c;
11
+ --ink: #fafaf9; --ink2: #a8a29e; --ink3: #8a847f;
12
+ --accent: #f59e0b; --accent-hover: #fbbf24; --accent-active: #d97706; --accent-ink: #1c1917; --accent-bg: #451a03;
13
+ --ok: #4ade80; --ok-bg: #052e16; --warn: #facc15; --warn-bg: #422006; --bad: #f87171; --bad-bg: #450a0a;
14
+ --shadow: none;`;
15
+ const SCALE = `--font: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
16
+ --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
17
+ --text-xs: .75rem; --text-sm: .875rem; --text-md: 1rem; --text-lg: 1.125rem; --text-xl: 1.5rem; --text-2xl: 2rem; --text-3xl: 2.75rem;
18
+ --space-1: .25rem; --space-2: .5rem; --space-3: .75rem; --space-4: 1rem; --space-5: 1.5rem; --space-6: 2rem; --space-7: 3rem; --space-8: 4rem;
19
+ --radius-sm: 8px; --radius-md: 12px; --radius-full: 999px;`;
20
+ // The select arrow is two gradients, because the case file allows no image, not even a data URL.
21
+ const components = (button) => `
22
+ :where(h1, h2, h3) { font-family: var(--font); color: var(--ink); letter-spacing: -.015em; line-height: 1.25; }
23
+ :where(h1) { font-size: var(--text-xl); font-weight: 700; }
24
+ :where(h2) { font-size: var(--text-lg); font-weight: 600; }
25
+ :where(h3) { font-size: var(--text-md); font-weight: 600; }
26
+ ${button} { display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2); min-height: 2.5rem; padding: 0 var(--space-4); border: 1px solid var(--accent); border-radius: var(--radius-sm); background: var(--accent); color: var(--accent-ink); font: 600 var(--text-sm)/1.2 var(--font); text-decoration: none; white-space: nowrap; cursor: pointer; transition: background-color .15s, border-color .15s, color .15s; }
27
+ ${button}:not(:disabled):hover { background: var(--accent-hover); border-color: var(--accent-hover); color: var(--accent-ink); }
28
+ ${button}:not(:disabled):active { background: var(--accent-active); border-color: var(--accent-active); }
29
+ ${button}:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
30
+ ${button}:disabled { opacity: .5; cursor: not-allowed; }
31
+ ${button}:is(.quiet, .secondary) { background: transparent; border-color: var(--line-strong); color: var(--ink); }
32
+ ${button}:is(.quiet, .secondary):not(:disabled):hover { background: var(--soft); border-color: var(--ink3); color: var(--ink); }
33
+ ${button}:is(.quiet, .secondary):not(:disabled):active { background: var(--line); }
34
+ ${button}.danger { background: var(--bad); border-color: var(--bad); color: var(--panel); }
35
+ ${button}.danger:not(:disabled):hover { background: var(--bad); border-color: var(--bad); color: var(--panel); filter: brightness(1.1); }
36
+ ${button}.icon { width: 2.25rem; min-height: 2.25rem; padding: 0; background: transparent; border-color: var(--line); color: var(--ink2); }
37
+ ${button}.icon:not(:disabled):hover { background: var(--soft); border-color: var(--line-strong); color: var(--ink); }
38
+ ${button}.icon svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
39
+ select { appearance: none; min-height: 2.5rem; padding: 0 2.25rem 0 var(--space-3); border: 1px solid var(--line-strong); border-radius: var(--radius-sm); background-color: var(--panel); color: var(--ink); font: var(--text-sm) var(--font); cursor: pointer;
40
+ background-image: linear-gradient(45deg, transparent 50%, var(--ink2) 50%), linear-gradient(135deg, var(--ink2) 50%, transparent 50%);
41
+ background-position: calc(100% - 17px) 50%, calc(100% - 12px) 50%; background-size: 5px 5px; background-repeat: no-repeat; }
42
+ select:hover { border-color: var(--ink3); }
43
+ select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
44
+ select:disabled { opacity: .5; cursor: not-allowed; }
45
+ :where(.card, .panel, dialog) { background: var(--panel); color: var(--ink); border: 1px solid var(--line); border-radius: var(--radius-md); }
46
+ :where(dialog) { padding: var(--space-5); box-shadow: var(--shadow); max-width: min(32rem, calc(100vw - 2rem)); }
47
+ :where(dialog)::backdrop { background: rgb(12 10 9 / .5); }
48
+ `;
49
+ const DARK_ON_SYSTEM = `@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { ${DARK} } }
50
+ :root[data-theme="dark"] { ${DARK} }`;
51
+ /** The app pages: the tokens, light and dark (system or data-theme), the base, and the shared components. */
52
+ export const DESIGN_CSS = `
53
+ :root { color-scheme: light dark; ${SCALE} ${LIGHT} }
54
+ ${DARK_ON_SYSTEM}
55
+ :root[data-theme="light"] { color-scheme: light; } :root[data-theme="dark"] { color-scheme: dark; }
56
+ * { box-sizing: border-box; }
57
+ body { margin: 0; background: var(--bg); color: var(--ink); font: var(--text-sm)/1.5 var(--font); -webkit-font-smoothing: antialiased; }
58
+ a { color: var(--accent); text-underline-offset: 3px; }
59
+ :where(a, button, input, textarea):focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
60
+ :where(code, pre, kbd, .mono) { font-family: var(--mono); }
61
+ :where(input:not([type="checkbox"], [type="radio"]), textarea) { min-height: 2.5rem; padding: var(--space-2) var(--space-3); border: 1px solid var(--line-strong); border-radius: var(--radius-sm); background: var(--panel); color: var(--ink); font: var(--text-sm) var(--font); }
62
+ :where(textarea) { font-family: var(--mono); }
63
+ ${components(":where(.btn, button:not(.link, nav button))")}`;
64
+ /** The site: the same tokens and components; VitePress sets the dark class itself. */
65
+ export const SITE_CSS = `/* Generated from packages/receipts/src/design.ts. Do not edit; a test compares the two. */
66
+ :root { ${SCALE} ${LIGHT} }
67
+ .dark { ${DARK} }
68
+ ${components(".btn")}`;
69
+ /** The logo: a receipt with a check mark. The tile takes the accent colour, so the mark follows the theme. */
70
+ export const LOGO_MARK = '<svg class="mark" viewBox="0 0 64 64" aria-hidden="true"><rect class="tile" width="64" height="64" rx="14"/><path d="M19 11H45V45L41.75 48 38.5 45 35.25 48 32 45 28.75 48 25.5 45 22.25 48 19 45Z" fill="#fff"/><path class="ink" d="M25 20h14M25 27h14" stroke-width="2.6" stroke-linecap="round"/><path class="ink" d="M25 37.5l5 4.5 9.5-10" fill="none" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/></svg>';
71
+ const THEME_BUTTON = '<button class="icon" id="themeToggle" type="button" aria-label="Dark mode" aria-pressed="false" title="Dark mode"><svg class="moon" viewBox="0 0 24 24" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg><svg class="sun" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg></button>';
72
+ /** The header of the review page and the case file: the logo, the name of the page, and the theme toggle. */
73
+ export const appHeader = (name) => `<header class="apphead"><a class="brand" href="https://agent-custody.dev/">${LOGO_MARK}agent-custody</a><span class="pill">${name}</span>${THEME_BUTTON}</header>`;
74
+ export const APP_HEADER_CSS = `
75
+ .apphead { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-3) var(--space-4); border-bottom: 1px solid var(--line); background: var(--panel); }
76
+ .apphead .brand { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--ink); font-weight: 700; text-decoration: none; }
77
+ .apphead .pill { padding: 0 var(--space-2); border-radius: var(--radius-full); background: var(--accent-bg); color: var(--accent); font: 600 var(--text-xs)/1.6 var(--font); }
78
+ .apphead #themeToggle { margin-left: auto; }
79
+ .mark { width: 28px; height: 28px; display: block; } .mark .tile { fill: var(--accent); } .mark .ink { stroke: var(--accent); }
80
+ #themeToggle[aria-pressed="true"] .moon, #themeToggle[aria-pressed="false"] .sun { display: none; }
81
+ `;
82
+ /** Applies the saved theme and wires the toggle. It uses the storage key of the portal. Put it after the button. */
83
+ export const THEME_SCRIPT = `(() => {
84
+ const root = document.documentElement, button = document.getElementById("themeToggle");
85
+ try { const saved = localStorage.getItem("agent-custody-theme"); if (saved === "dark" || saved === "light") root.dataset.theme = saved; } catch {}
86
+ const now = () => root.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
87
+ const label = () => button.setAttribute("aria-pressed", String(now() === "dark"));
88
+ button.onclick = () => { const next = now() === "dark" ? "light" : "dark"; root.dataset.theme = next; try { localStorage.setItem("agent-custody-theme", next); } catch {} label(); };
89
+ label();
90
+ })();
91
+ `;
package/dist/index.d.ts CHANGED
@@ -15,6 +15,8 @@ export type { DraftAgent, DraftDestination, DraftSkip, EgressPolicyDraft } from
15
15
  export type { Destination, EgressEnd, EgressHost, EgressOptions, EgressResult, EgressServerOptions, RunningEgress } from "./egress.ts";
16
16
  export { ACS_ERROR, ACS_GUARDIAN_VERSION, ACS_METHODS, ACS_RECEIPT_KEY, ACS_STEP_FACT, ACS_VERSION, acsEntryHash, createAcsGuardian } from "./acs.ts";
17
17
  export type { AcsGuardian, AcsMethod, AcsResponse } from "./acs.ts";
18
+ export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceiptHash, verifyPerathosLog } from "./perathos.ts";
19
+ export type { PerathosCheck, PerathosOptions, PerathosReport } from "./perathos.ts";
18
20
  export { loadAcsGuardianConfig } from "./config.ts";
19
21
  export type { AcsGuardianConfig } from "./config.ts";
20
22
  export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
@@ -76,3 +78,5 @@ export * from "./pr-summary.ts";
76
78
  export * from "./export.ts";
77
79
  export * from "./claude-init.ts";
78
80
  export * from "./deny-report.ts";
81
+ export { DESIGN_CSS, LOGO_MARK, APP_HEADER_CSS, THEME_SCRIPT, appHeader } from "./design.ts";
82
+ export * from "./session-audit.ts";
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ export { DESTINATION_FACT, EGRESS_VERSION, PROXY_REALM, checkProxyCredential, cr
11
11
  export { internalAddress } from "./addresses.js";
12
12
  export { DRAFT_WARNING, draftEgressPolicy } from "./egress-draft.js";
13
13
  export { ACS_ERROR, ACS_GUARDIAN_VERSION, ACS_METHODS, ACS_RECEIPT_KEY, ACS_STEP_FACT, ACS_VERSION, acsEntryHash, createAcsGuardian } from "./acs.js";
14
+ export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceiptHash, verifyPerathosLog } from "./perathos.js";
14
15
  export { loadAcsGuardianConfig } from "./config.js";
15
16
  export * from "./capture.js";
16
17
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
@@ -50,3 +51,5 @@ export * from "./pr-summary.js";
50
51
  export * from "./export.js";
51
52
  export * from "./claude-init.js";
52
53
  export * from "./deny-report.js";
54
+ export { DESIGN_CSS, LOGO_MARK, APP_HEADER_CSS, THEME_SCRIPT, appHeader } from "./design.js";
55
+ export * from "./session-audit.js";
@@ -51,6 +51,8 @@ export declare function registrations(tenancy: PostgresTenancy, portal: PortalSt
51
51
  totalLeaves: number;
52
52
  };
53
53
  }>;
54
+ /** One CSV cell: RFC 4180 quoting, and a text cell a spreadsheet would read as a formula gets a leading `'`. */
55
+ export declare function csvCell(v: unknown): string;
54
56
  export interface RegistrationRow {
55
57
  tenant: string;
56
58
  logId: string;
package/dist/log-admin.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // receipts; the log holds hashes and the panel holds names.
7
7
  import { timingSafeEqual } from "node:crypto";
8
8
  import { RateLimiter, PLANS } from "./log-store.js";
9
+ import { APP_HEADER_CSS, DESIGN_CSS, THEME_SCRIPT, appHeader } from "./design.js";
9
10
  import { clientAddress } from "./log-sink.js";
10
11
  const same = (a, b) => {
11
12
  const x = Buffer.from(a);
@@ -41,7 +42,7 @@ export function welcomeSheet(o) {
41
42
  "a log copy that verify --log and audit --log read with no server.",
42
43
  "",
43
44
  "What this log does not do: hold receipt contents, forge a receipt (your gateway key signs those), or, today,",
44
- "countersign with a second independent witness. The proof table: https://agent-custody.dev/receipts/#what-a-receipt-proves-and-what-it-does-not",
45
+ "countersign with a second independent witness. The proof table: https://github.com/svayatta/agent-custody/tree/main/packages/receipts#what-a-receipt-proves-and-what-it-does-not",
45
46
  ];
46
47
  return lines.join("\n");
47
48
  }
@@ -74,6 +75,15 @@ export async function registrations(tenancy, portal, month) {
74
75
  });
75
76
  return { month: usage.month, rows, totals: { tenants: rows.length, registered: rows.filter((r) => r.email).length, appends: rows.reduce((n, r) => n + r.appends, 0), totalLeaves: rows.reduce((n, r) => n + r.totalLeaves, 0) } };
76
77
  }
78
+ /** One CSV cell: RFC 4180 quoting, and a text cell a spreadsheet would read as a formula gets a leading `'`. */
79
+ export function csvCell(v) {
80
+ if (v === null || v === undefined)
81
+ return "";
82
+ let t = String(v);
83
+ if (typeof v === "string" && /^[=+\-@\t\r]/.test(t))
84
+ t = `'${t}`;
85
+ return /[",\r\n]/.test(t) ? `"${t.replace(/"/g, '""')}"` : t;
86
+ }
77
87
  export function adminRoutes(opts) {
78
88
  // Five wrong tokens from one address, then one more a minute: enough to stop guessing, not enough to lock out a typo.
79
89
  const failures = new RateLimiter({ perSecond: 1 / 60, burst: 5 });
@@ -130,7 +140,7 @@ export function adminRoutes(opts) {
130
140
  }
131
141
  else if (req.method === "GET" && parts.length === 2 && parts[1] === "usage.csv") {
132
142
  const u = await t.usage(month);
133
- const csv = ["month,tenant,log_id,plan,quota,appends,total_leaves,live_tokens,disabled", ...u.tenants.map((x) => [u.month, x.id, x.logId, x.plan, x.quota ?? "", x.appends, x.totalLeaves, x.liveTokens, x.disabled].join(","))].join("\n") + "\n";
143
+ const csv = ["month,tenant,log_id,plan,quota,appends,total_leaves,live_tokens,disabled", ...u.tenants.map((x) => [u.month, x.id, x.logId, x.plan, x.quota ?? "", x.appends, x.totalLeaves, x.liveTokens, x.disabled].map(csvCell).join(","))].join("\n") + "\n";
134
144
  res.writeHead(200, { "content-type": "text/csv; charset=utf-8", "content-disposition": `attachment; filename="agent-custody-usage-${u.month}.csv"`, "cache-control": "no-store" });
135
145
  res.end(csv);
136
146
  }
@@ -139,8 +149,7 @@ export function adminRoutes(opts) {
139
149
  }
140
150
  else if (req.method === "GET" && parts.length === 2 && parts[1] === "registrations.csv") {
141
151
  const r = await registrations(t, opts.portal, month);
142
- const cell = (v) => (v === null ? "" : /[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v));
143
- const csv = ["month,tenant,log_id,plan,email,name,company,role,phone,telegram,registered_at,billing,appends,quota,total_leaves,live_tokens,disabled", ...r.rows.map((x) => [r.month, x.tenant, x.logId, x.plan, x.email, x.name, x.company, x.role, x.phone, x.telegram, x.registeredAt, x.billing, x.appends, x.quota, x.totalLeaves, x.liveTokens, x.disabled].map(cell).join(","))].join("\n") + "\n";
152
+ const csv = ["month,tenant,log_id,plan,email,name,company,role,phone,telegram,registered_at,billing,appends,quota,total_leaves,live_tokens,disabled", ...r.rows.map((x) => [r.month, x.tenant, x.logId, x.plan, x.email, x.name, x.company, x.role, x.phone, x.telegram, x.registeredAt, x.billing, x.appends, x.quota, x.totalLeaves, x.liveTokens, x.disabled].map(csvCell).join(","))].join("\n") + "\n";
144
153
  res.writeHead(200, { "content-type": "text/csv; charset=utf-8", "content-disposition": `attachment; filename="agent-custody-registrations-${r.month}.csv"`, "cache-control": "no-store" });
145
154
  res.end(csv);
146
155
  }
@@ -162,6 +171,8 @@ export function adminRoutes(opts) {
162
171
  const b = await body();
163
172
  if (typeof b.id !== "string" || !/^[A-Za-z0-9_.-]+$/.test(b.id))
164
173
  return json(400, { error: "id must be a plain identifier" }), true;
174
+ if (b.logId !== undefined && b.logId !== "" && (typeof b.logId !== "string" || !/^[A-Za-z0-9_.-]+$/.test(b.logId)))
175
+ return json(400, { error: "logId must be a plain identifier" }), true;
165
176
  json(200, await t.addTenant(b.id, typeof b.logId === "string" && b.logId ? b.logId : b.id, actor));
166
177
  }
167
178
  else if (req.method === "POST" && parts.length === 4 && parts[1] === "tenants" && parts[3] === "plan") {
@@ -201,79 +212,97 @@ export function adminRoutes(opts) {
201
212
  };
202
213
  }
203
214
  /** The page. One file, no framework, no third-party requests; the browser holds the admin credential it prompted for. */
215
+ const TABS = ["registrations", "tenants", "tokens", "usage", "activity"];
204
216
  const ADMIN_PAGE = `<!doctype html>
217
+ <html lang="en">
205
218
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
206
219
  <title>agent-custody log admin</title>
207
220
  <link rel="icon" href="/favicon.svg" type="image/svg+xml">
208
221
  <script>(() => { try { const t = localStorage.getItem("agent-custody-theme"); if (t === "dark" || t === "light") document.documentElement.dataset.theme = t; } catch {} })();</script>
209
222
  <style>
210
- :root { color-scheme: light dark; --ink: #1b2430; --ink2: #5b6b7a; --line: #d7dfe5; --bg: #fafbfc; --panel: #ffffff; --accent: #0f6e63; --warn: #8a5a00; --warnbg: #fbf1dc; --mono: ui-monospace, Menlo, monospace; }
211
- @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --ink: #e6ecf0; --ink2: #9fb0bd; --line: #27333c; --bg: #0e1418; --panel: #151d23; --accent: #4fc3b0; --warn: #e2b862; --warnbg: #2d2412; } }
212
- :root[data-theme="dark"] { --ink: #e6ecf0; --ink2: #9fb0bd; --line: #27333c; --bg: #0e1418; --panel: #151d23; --accent: #4fc3b0; --warn: #e2b862; --warnbg: #2d2412; }
213
- body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.5 system-ui, sans-serif; }
223
+ ${DESIGN_CSS}${APP_HEADER_CSS}
214
224
  main { max-width: 72rem; margin: 0 auto; padding: 2rem 1.25rem 4rem; }
215
- h1 { font-size: 1.4rem; margin: 0 0 .25rem; } h2 { font-size: 1.05rem; margin: 2rem 0 .75rem; }
225
+ h1 { margin: 0 0 .25rem; } h2 { margin: 1.5rem 0 .75rem; }
216
226
  .sub { color: var(--ink2); margin: 0 0 1.5rem; }
217
227
  .row { display: flex; gap: .6rem; flex-wrap: wrap; align-items: end; }
218
228
  label { display: grid; gap: .25rem; font-size: .85rem; color: var(--ink2); }
219
- input { font: inherit; padding: .45rem .6rem; border: 1px solid var(--line); border-radius: 4px; background: var(--panel); color: var(--ink); min-width: 14rem; }
220
- button { font: inherit; padding: .5rem .9rem; border: 1px solid var(--accent); border-radius: 4px; background: var(--accent); color: #fff; cursor: pointer; }
221
- button.quiet { background: transparent; color: var(--accent); }
222
- button:disabled { opacity: .5; cursor: default; }
229
+ input { min-width: 14rem; }
230
+ .scroll { overflow-x: auto; }
223
231
  table { border-collapse: collapse; width: 100%; font-size: .93rem; }
224
- th, td { text-align: left; padding: .5rem .6rem; border-bottom: 1px solid var(--line); vertical-align: top; }
225
- th { font-size: .78rem; letter-spacing: .04em; text-transform: uppercase; color: var(--ink2); }
226
- code, pre { font-family: var(--mono); font-size: .86em; }
227
- pre { background: var(--panel); border: 1px solid var(--line); border-radius: 4px; padding: .9rem 1rem; overflow-x: auto; white-space: pre-wrap; }
228
- .once { border-left: 3px solid var(--warn); background: var(--warnbg); padding: .8rem 1rem; border-radius: 0 4px 4px 0; margin: 1rem 0; }
229
- .muted { color: var(--ink2); } .err { color: #b3261e; } .ok { color: var(--accent); }
232
+ th, td { text-align: left; padding: .5rem .6rem; border-bottom: 1px solid var(--line); vertical-align: top; white-space: nowrap; }
233
+ th { font-size: var(--text-xs); font-weight: 600; color: var(--ink2); } th::first-letter { text-transform: uppercase; }
234
+ td.detail { white-space: normal; min-width: 16rem; }
235
+ code, pre { font-size: .86em; }
236
+ pre { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: .9rem 1rem; overflow-x: auto; white-space: pre-wrap; }
237
+ .once { border-left: 3px solid var(--warn); background: var(--warn-bg); padding: .8rem 1rem; border-radius: 0 var(--radius-sm) var(--radius-sm) 0; margin: 1rem 0; }
238
+ .muted { color: var(--ink2); } .err { color: var(--bad); } .ok { color: var(--ok); }
230
239
  .tok { font-family: var(--mono); font-size: 1.05rem; word-break: break-all; user-select: all; }
231
- .head { display: flex; justify-content: space-between; align-items: start; gap: 1rem; }
232
- button.theme { background: transparent; color: var(--ink2); border: 1px solid var(--line); padding: .25rem .6rem; font-size: .8rem; border-radius: 4px; } button.theme:hover { color: var(--ink); }
240
+ .tabs { display: flex; gap: var(--space-1); overflow-x: auto; border-bottom: 1px solid var(--line); margin-bottom: var(--space-4); }
241
+ .tabs a { padding: var(--space-2) var(--space-3); border-bottom: 2px solid transparent; color: var(--ink2); font-weight: 600; text-decoration: none; white-space: nowrap; }
242
+ .tabs a:hover { color: var(--ink); } .tabs a[aria-current] { color: var(--accent); border-bottom-color: var(--accent); }
243
+ .status { margin-left: var(--space-2); font-size: var(--text-sm); }
244
+ .actions { display: flex; gap: var(--space-2); justify-content: flex-end; margin-top: var(--space-5); }
233
245
  [hidden] { display: none !important; }
234
- .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); gap: .6rem; margin: 0 0 1rem; }
235
- .stat { background: var(--panel); border: 1px solid var(--line); border-radius: 4px; padding: .6rem .8rem; }
236
- .stat b { display: block; font-size: 1.4rem; font-variant-numeric: tabular-nums; } .stat span { color: var(--ink2); font-size: .8rem; }
246
+ .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); gap: .6rem; margin: .8rem 0 1rem; }
247
+ .stat { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-md); padding: .6rem .8rem; }
248
+ .stat b { display: block; font-size: var(--text-xl); font-variant-numeric: tabular-nums; } .stat span { color: var(--ink2); font-size: .8rem; }
237
249
  </style>
250
+ ${appHeader("Log admin")}
238
251
  <main>
239
- <div class="head"><div><h1>Log admin</h1>
240
- <p class="sub" id="where">Tenants and tokens on this log.</p></div><button class="theme" id="themeToggle" type="button">Dark mode</button></div>
252
+ <h1>Log admin</h1>
253
+ <p class="sub" id="where">Tenants and tokens on this log.</p>
254
+ <p class="err" role="status" data-status="page"></p>
255
+ <nav class="tabs" aria-label="Sections">${TABS.map((t) => `<a href="#tab-${t}">${t[0].toUpperCase()}${t.slice(1)}</a>`).join("")}</nav>
241
256
  <section id="app">
257
+ <div data-tab="registrations">
242
258
  <h2>Registrations</h2>
243
- <div class="row"><label>month<input id="rmonth" type="month"></label><button class="quiet" id="loadRegs">Show</button><a id="rcsv" class="quiet" href="#" style="align-self:center">Download CSV</a></div>
259
+ <div class="row"><label>month<input id="rmonth" type="month"></label><button class="quiet" id="loadRegs">Show</button><a id="rcsv" class="quiet" href="#" style="align-self:center">Download CSV</a><span class="status" role="status" data-status="regs"></span></div>
244
260
  <div class="stats"><div class="stat"><b id="sTenants">–</b><span>tenants</span></div><div class="stat"><b id="sRegistered">–</b><span>registered through the portal</span></div><div class="stat"><b id="sAppends">–</b><span>appends this month</span></div><div class="stat"><b id="sLeaves">–</b><span>leaves in total</span></div></div>
245
- <table><thead><tr><th>who</th><th>reach</th><th>tenant</th><th>plan</th><th>registered</th><th>billing</th><th>appends this month</th><th>leaves in total</th><th>live tokens</th></tr></thead><tbody id="regs"></tbody></table>
261
+ <div class="scroll" tabindex="0" role="region" aria-label="Registrations"><table><thead><tr><th>who</th><th>reach</th><th>tenant</th><th>plan</th><th>registered</th><th>billing</th><th>appends this month</th><th>leaves in total</th><th>live tokens</th></tr></thead><tbody id="regs"></tbody></table></div>
262
+ </div>
263
+ <div data-tab="tenants" hidden>
246
264
  <h2>Tenants</h2>
247
- <table><thead><tr><th>tenant</th><th>log id</th><th>plan</th><th>live tokens</th><th>created</th><th></th></tr></thead><tbody id="tenants"></tbody></table>
265
+ <div class="scroll" tabindex="0" role="region" aria-label="Tenants"><table><thead><tr><th>tenant</th><th>log id</th><th>plan</th><th>live tokens</th><th>created</th><th></th></tr></thead><tbody id="tenants"></tbody></table></div>
248
266
  <h2>New tenant</h2>
249
267
  <div class="row">
250
268
  <label>tenant id (in the URL)<input id="tid" placeholder="acme" autocomplete="off"></label>
251
269
  <label>log id (on tree heads; default = tenant id)<input id="lid" placeholder="acme-eu" autocomplete="off"></label>
252
- <button id="addTenant">Create</button>
270
+ <button id="addTenant">Create</button><span class="status" role="status" data-status="addTenant"></span>
271
+ </div>
253
272
  </div>
273
+ <div data-tab="tokens" hidden>
254
274
  <h2>New token</h2>
255
275
  <div class="row">
256
276
  <label>tenant<input id="ttid" placeholder="acme" autocomplete="off"></label>
257
277
  <label>label (which fleet)<input id="label" placeholder="support fleet" autocomplete="off"></label>
258
- <button id="mint">Mint token</button>
278
+ <button id="mint">Mint token</button><span class="status" role="status" data-status="mint"></span>
259
279
  </div>
260
280
  <div id="minted" class="once" hidden>
261
281
  <p><b>Shown once.</b> Hand it over by a channel you trust; the log keeps only its hash.</p>
262
282
  <p class="tok" id="tokval"></p>
263
- <button class="quiet" id="copyTok">Copy token</button> <button class="quiet" id="copySheet">Copy welcome sheet</button>
283
+ <button class="quiet" id="copyTok">Copy token</button> <button class="quiet" id="copySheet">Copy welcome sheet</button><span class="status" role="status" data-status="copy"></span>
264
284
  <pre id="sheet"></pre>
265
285
  </div>
266
- <h2>Usage</h2>
267
- <div class="row"><label>month<input id="month" type="month"></label><button class="quiet" id="loadUsage">Show</button><a id="csv" class="quiet" href="#" style="align-self:center">Download CSV</a></div>
268
- <table><thead><tr><th>tenant</th><th>log id</th><th>plan</th><th>appends this month</th><th>quota</th><th>leaves in total</th><th>live tokens</th></tr></thead><tbody id="usage"></tbody></table>
269
286
  <h2>Tokens of a tenant</h2>
270
- <div class="row"><label>tenant<input id="ltid" placeholder="acme" autocomplete="off"></label><button class="quiet" id="listTokens">List</button></div>
271
- <table><thead><tr><th>label</th><th>hash</th><th>created</th><th>state</th><th></th></tr></thead><tbody id="tokens"></tbody></table>
287
+ <div class="row"><label>tenant<input id="ltid" placeholder="acme" autocomplete="off"></label><button class="quiet" id="listTokens">List</button><span class="status" role="status" data-status="listTokens"></span></div>
288
+ <div class="scroll" tabindex="0" role="region" aria-label="Tokens of a tenant"><table><thead><tr><th>label</th><th>hash</th><th>created</th><th>state</th><th></th></tr></thead><tbody id="tokens"></tbody></table></div>
289
+ </div>
290
+ <div data-tab="usage" hidden>
291
+ <h2>Usage</h2>
292
+ <div class="row"><label>month<input id="month" type="month"></label><button class="quiet" id="loadUsage">Show</button><a id="csv" class="quiet" href="#" style="align-self:center">Download CSV</a><span class="status" role="status" data-status="usage"></span></div>
293
+ <div class="scroll" tabindex="0" role="region" aria-label="Usage"><table><thead><tr><th>tenant</th><th>log id</th><th>plan</th><th>appends this month</th><th>quota</th><th>leaves in total</th><th>live tokens</th></tr></thead><tbody id="usage"></tbody></table></div>
294
+ </div>
295
+ <div data-tab="activity" hidden>
272
296
  <h2>Activity</h2>
273
297
  <p class="muted">Every tenant and token change on this log, newest first, with who made it: the name entered at the sign-in prompt, or the command line on the server. Tenants see their own rows in their export.</p>
274
- <table><thead><tr><th>when</th><th>who</th><th>action</th><th>tenant</th><th>detail</th></tr></thead><tbody id="audit"></tbody></table>
275
- <p class="muted" id="msg"></p>
298
+ <div class="scroll" tabindex="0" role="region" aria-label="Activity"><table><thead><tr><th>when</th><th>who</th><th>action</th><th>tenant</th><th>detail</th></tr></thead><tbody id="audit"></tbody></table></div>
299
+ </div>
276
300
  </section>
301
+ <dialog id="planDialog" aria-labelledby="planTitle">
302
+ <h2 id="planTitle">Change the plan?</h2>
303
+ <p>Tenant <code id="dTenant"></code>: change the plan from <b id="dFrom"></b> to <b id="dTo"></b>.</p>
304
+ <div class="actions"><button class="quiet" id="planCancel" type="button">Cancel</button><button id="planSave" type="button">Save plan</button></div>
305
+ </dialog>
277
306
  </main>
278
307
  <script>
279
308
  (() => {
@@ -287,20 +316,27 @@ const ADMIN_PAGE = `<!doctype html>
287
316
  return j;
288
317
  };
289
318
  const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
290
- const say = (t, cls) => { $("msg").textContent = t; $("msg").className = cls || "muted"; };
291
- // Light or dark by choice, kept in this browser; unset, the page follows the system. The button says where it is going.
292
- const themeNow = () => document.documentElement.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
293
- const themeLabel = () => { $("themeToggle").textContent = themeNow() === "dark" ? "Light mode" : "Dark mode"; };
294
- $("themeToggle").onclick = () => { const next = themeNow() === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = next; try { localStorage.setItem("agent-custody-theme", next); } catch {} themeLabel(); };
295
- themeLabel();
319
+ // The result of an action shows beside the control that caused it.
320
+ const say = (key, t, cls) => { const el = document.querySelector("[data-status=\\"" + key + "\\"]"); if (el) { el.textContent = t; el.className = "status " + (cls || "muted"); } };
321
+ const statusSpan = (key) => "<span class=status role=status data-status=\\"" + esc(key) + "\\"></span>";
322
+ // A tab is a link to #tab-<name>. No element has that id, so the browser does not scroll.
323
+ const TABS = ${JSON.stringify(TABS)};
324
+ const showTab = () => {
325
+ const name = location.hash.replace(/^#tab-/, "");
326
+ const tab = TABS.includes(name) ? name : TABS[0];
327
+ for (const pane of document.querySelectorAll("[data-tab]")) pane.hidden = pane.dataset.tab !== tab;
328
+ for (const a of document.querySelectorAll(".tabs a")) { if (a.getAttribute("href") === "#tab-" + tab) a.setAttribute("aria-current", "page"); else a.removeAttribute("aria-current"); }
329
+ };
330
+ window.addEventListener("hashchange", showTab);
331
+ showTab();
296
332
  const loadTenants = async () => {
297
333
  const list = await api("GET", "/admin/tenants");
298
- const planPick = (t) => "<select data-plan=\\"" + esc(t.id) + "\\">" + ["free", "team", "enterprise"].map((p) => "<option" + (p === t.plan ? " selected" : "") + ">" + p + "</option>").join("") + "</select>";
299
- $("tenants").innerHTML = list.map((t) => "<tr><td><code>" + esc(t.id) + "</code></td><td><code>" + esc(t.logId) + "</code></td><td>" + planPick(t) + "</td><td>" + t.tokens + "</td><td>" + esc(t.createdAt.slice(0, 10)) + "</td><td>" + (t.disabledAt ? "<span class=muted>disabled</span>" : "<button class=quiet data-disable=\\"" + esc(t.id) + "\\">Disable</button>") + "</td></tr>").join("") || "<tr><td colspan=6 class=muted>none yet</td></tr>";
334
+ const planPick = (t) => "<select data-plan=\\"" + esc(t.id) + "\\" data-current=\\"" + esc(t.plan) + "\\" aria-label=\\"Plan of " + esc(t.id) + "\\">" + ["free", "team", "enterprise"].map((p) => "<option" + (p === t.plan ? " selected" : "") + ">" + p + "</option>").join("") + "</select>" + statusSpan("plan:" + t.id);
335
+ $("tenants").innerHTML = list.map((t) => "<tr><td><code>" + esc(t.id) + "</code></td><td><code>" + esc(t.logId) + "</code></td><td>" + planPick(t) + "</td><td>" + t.tokens + "</td><td>" + esc(t.createdAt.slice(0, 10)) + "</td><td>" + (t.disabledAt ? "<span class=muted>disabled</span>" : "<button class=quiet data-disable=\\"" + esc(t.id) + "\\">Disable</button>") + statusSpan("disable:" + t.id) + "</td></tr>").join("") || "<tr><td colspan=6 class=muted>none yet</td></tr>";
300
336
  };
301
337
  const loadTokens = async (id) => {
302
338
  const list = await api("GET", "/admin/tenants/" + encodeURIComponent(id) + "/tokens");
303
- $("tokens").innerHTML = list.map((k) => "<tr><td>" + esc(k.label) + "</td><td><code>" + esc(k.tokenHash.slice(0, 12)) + "</code></td><td>" + esc(k.createdAt.slice(0, 10)) + "</td><td>" + (k.revokedAt ? "revoked " + esc(k.revokedAt.slice(0, 10)) : "<span class=ok>live</span>") + "</td><td>" + (k.revokedAt ? "" : "<button class=quiet data-revoke=\\"" + esc(id) + "|" + esc(k.tokenHash.slice(0, 12)) + "\\">Revoke</button>") + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>no tokens</td></tr>";
339
+ $("tokens").innerHTML = list.map((k) => "<tr><td>" + esc(k.label) + "</td><td><code>" + esc(k.tokenHash.slice(0, 12)) + "</code></td><td>" + esc(k.createdAt.slice(0, 10)) + "</td><td>" + (k.revokedAt ? "revoked " + esc(k.revokedAt.slice(0, 10)) : "<span class=ok>live</span>") + "</td><td>" + (k.revokedAt ? "" : "<button class=quiet data-revoke=\\"" + esc(id) + "|" + esc(k.tokenHash.slice(0, 12)) + "\\">Revoke</button>") + statusSpan("revoke:" + k.tokenHash.slice(0, 12)) + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>no tokens</td></tr>";
304
340
  };
305
341
  const enter = async () => {
306
342
  try {
@@ -310,21 +346,21 @@ const ADMIN_PAGE = `<!doctype html>
310
346
  await loadTenants();
311
347
  await loadUsage();
312
348
  await loadAudit();
313
- } catch (e) { say(e.message, "err"); }
349
+ } catch (e) { say("page", e.message, "err"); }
314
350
  };
315
- $("addTenant").onclick = async () => { try { const t = await api("POST", "/admin/tenants", { id: $("tid").value.trim(), logId: $("lid").value.trim() }); say("tenant " + t.id + " created; reached at /t/" + t.id + "/", "ok"); $("ttid").value = t.id; await loadTenants(); await loadAudit(); } catch (e) { say(e.message, "err"); } };
351
+ $("addTenant").onclick = async () => { try { const t = await api("POST", "/admin/tenants", { id: $("tid").value.trim(), logId: $("lid").value.trim() }); $("ttid").value = t.id; await loadTenants(); await loadAudit(); say("addTenant", "tenant " + t.id + " created; reached at /t/" + t.id + "/", "ok"); } catch (e) { say("addTenant", e.message, "err"); } };
316
352
  $("mint").onclick = async () => {
317
353
  try {
318
354
  const r = await api("POST", "/admin/tenants/" + encodeURIComponent($("ttid").value.trim()) + "/tokens", { label: $("label").value.trim() });
319
355
  $("tokval").textContent = r.token; $("sheet").textContent = r.welcome || "(set --public-url on the server for the welcome sheet)"; $("minted").hidden = false;
320
- say("token minted for " + $("ttid").value.trim() + "; stored as hash " + r.tokenHash.slice(0, 12), "ok");
321
356
  await loadTenants();
322
357
  await loadAudit();
323
- } catch (e) { say(e.message, "err"); }
358
+ say("mint", "token minted for " + $("ttid").value.trim() + "; stored as hash " + r.tokenHash.slice(0, 12), "ok");
359
+ } catch (e) { say("mint", e.message, "err"); }
324
360
  };
325
- $("copyTok").onclick = () => navigator.clipboard.writeText($("tokval").textContent).then(() => say("token copied", "ok"));
326
- $("copySheet").onclick = () => navigator.clipboard.writeText($("sheet").textContent).then(() => say("welcome sheet copied", "ok"));
327
- $("listTokens").onclick = () => loadTokens($("ltid").value.trim()).catch((e) => say(e.message, "err"));
361
+ $("copyTok").onclick = () => navigator.clipboard.writeText($("tokval").textContent).then(() => say("copy", "token copied", "ok"), (e) => say("copy", e.message, "err"));
362
+ $("copySheet").onclick = () => navigator.clipboard.writeText($("sheet").textContent).then(() => say("copy", "welcome sheet copied", "ok"), (e) => say("copy", e.message, "err"));
363
+ $("listTokens").onclick = () => loadTokens($("ltid").value.trim()).then(() => say("listTokens", "", "muted"), (e) => say("listTokens", e.message, "err"));
328
364
  const loadUsage = async () => {
329
365
  const month = $("month").value || new Date().toISOString().slice(0, 7);
330
366
  const u = await api("GET", "/admin/usage?month=" + encodeURIComponent(month));
@@ -342,21 +378,36 @@ const ADMIN_PAGE = `<!doctype html>
342
378
  };
343
379
  const loadAudit = async () => {
344
380
  const a = await api("GET", "/admin/audit?limit=100");
345
- $("audit").innerHTML = a.entries.map((e) => "<tr><td>" + esc(e.at.replace("T", " ").slice(0, 19)) + "</td><td><code>" + esc(e.actor) + "</code></td><td>" + esc(e.action) + "</td><td><code>" + esc(e.tenantId || "") + "</code></td><td class=muted>" + esc(Object.entries(e.detail).map(([k, v]) => k + "=" + v).join(" ")) + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>nothing yet</td></tr>";
381
+ $("audit").innerHTML = a.entries.map((e) => "<tr><td>" + esc(e.at.replace("T", " ").slice(0, 19)) + "</td><td><code>" + esc(e.actor) + "</code></td><td>" + esc(e.action) + "</td><td><code>" + esc(e.tenantId || "") + "</code></td><td class=\\"detail muted\\">" + esc(Object.entries(e.detail).map(([k, v]) => k + "=" + v).join(" ")) + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>nothing yet</td></tr>";
346
382
  };
347
- $("loadUsage").onclick = () => loadUsage().catch((e) => say(e.message, "err"));
348
- $("loadRegs").onclick = () => loadRegs().catch((e) => say(e.message, "err"));
383
+ $("loadUsage").onclick = () => loadUsage().then(() => say("usage", "", "muted"), (e) => say("usage", e.message, "err"));
384
+ $("loadRegs").onclick = () => loadRegs().then(() => say("regs", "", "muted"), (e) => say("regs", e.message, "err"));
349
385
  $("month").value = $("rmonth").value = new Date().toISOString().slice(0, 7);
350
- document.addEventListener("change", async (e) => {
386
+ // A plan change opens the dialog. It saves only when the operator confirms; any other way out puts the old plan back.
387
+ const dialog = $("planDialog");
388
+ let pending = null;
389
+ document.addEventListener("change", (e) => {
351
390
  const s = e.target.closest("select[data-plan]"); if (!s) return;
352
- try { await api("POST", "/admin/tenants/" + encodeURIComponent(s.dataset.plan) + "/plan", { plan: s.value }); say("plan of " + s.dataset.plan + " set to " + s.value, "ok"); await loadRegs(); await loadUsage(); await loadAudit(); } catch (err) { say(err.message, "err"); await loadTenants(); }
391
+ pending = { select: s, id: s.dataset.plan, from: s.dataset.current, to: s.value };
392
+ $("dTenant").textContent = pending.id; $("dFrom").textContent = pending.from; $("dTo").textContent = pending.to;
393
+ dialog.returnValue = "";
394
+ dialog.showModal();
395
+ });
396
+ $("planCancel").onclick = () => dialog.close("cancel");
397
+ $("planSave").onclick = () => dialog.close("save");
398
+ dialog.addEventListener("close", async () => {
399
+ const p = pending; pending = null;
400
+ if (!p) return;
401
+ if (dialog.returnValue !== "save") { p.select.value = p.from; return; }
402
+ try { await api("POST", "/admin/tenants/" + encodeURIComponent(p.id) + "/plan", { plan: p.to }); await loadTenants(); await loadRegs(); await loadUsage(); await loadAudit(); say("plan:" + p.id, "plan set to " + p.to, "ok"); } catch (err) { p.select.value = p.from; say("plan:" + p.id, err.message, "err"); }
353
403
  });
354
404
  document.addEventListener("click", async (e) => {
355
405
  const b = e.target.closest("button"); if (!b) return;
356
- if (b.dataset.disable && confirm("Disable tenant " + b.dataset.disable + "? Its paths answer 404 within ten seconds.")) { try { await api("POST", "/admin/tenants/" + encodeURIComponent(b.dataset.disable) + "/disable"); await loadTenants(); await loadAudit(); say("disabled " + b.dataset.disable, "ok"); } catch (err) { say(err.message, "err"); } }
357
- if (b.dataset.revoke) { const [id, prefix] = b.dataset.revoke.split("|"); if (confirm("Revoke token " + prefix + " of " + id + "?")) { try { await api("POST", "/admin/tenants/" + encodeURIComponent(id) + "/tokens/" + prefix + "/revoke"); await loadTokens(id); await loadTenants(); await loadAudit(); say("revoked", "ok"); } catch (err) { say(err.message, "err"); } } }
406
+ if (b.dataset.disable && confirm("Disable tenant " + b.dataset.disable + "? Its paths answer 404 within ten seconds.")) { const id = b.dataset.disable; try { await api("POST", "/admin/tenants/" + encodeURIComponent(id) + "/disable"); await loadTenants(); await loadAudit(); say("disable:" + id, "disabled", "ok"); } catch (err) { say("disable:" + id, err.message, "err"); } }
407
+ if (b.dataset.revoke) { const [id, prefix] = b.dataset.revoke.split("|"); if (confirm("Revoke token " + prefix + " of " + id + "?")) { try { await api("POST", "/admin/tenants/" + encodeURIComponent(id) + "/tokens/" + prefix + "/revoke"); await loadTokens(id); await loadTenants(); await loadAudit(); say("revoke:" + prefix, "revoked", "ok"); } catch (err) { say("revoke:" + prefix, err.message, "err"); } } }
358
408
  });
359
409
  enter();
360
410
  })();
361
411
  </script>
412
+ <script>${THEME_SCRIPT}</script>
362
413
  `;
@@ -82,13 +82,16 @@ export interface TokenRecord {
82
82
  tokenHash: string;
83
83
  createdAt: string;
84
84
  revokedAt: string | null;
85
+ /** the last append with this token, to within a minute; null when never used since the column came */
86
+ lastUsedAt: string | null;
85
87
  }
88
+ export declare const AUDIT_ACTIONS: readonly ["tenant.add", "tenant.disable", "tenant.plan", "token.add", "token.revoke", "policy.add", "policy.remove", "sso.set", "sso.remove", "user.mfa-reset"];
86
89
  /** One administrative action: who did what to which tenant, when. Written by every mutation and never deleted. */
87
90
  export interface AuditEntry {
88
91
  id: number;
89
92
  at: string;
90
93
  actor: string;
91
- action: "tenant.add" | "tenant.disable" | "tenant.plan" | "token.add" | "token.revoke" | "policy.add" | "policy.remove" | "sso.set" | "sso.remove" | "user.mfa-reset";
94
+ action: (typeof AUDIT_ACTIONS)[number];
92
95
  tenantId: string | null;
93
96
  detail: Record<string, unknown>;
94
97
  }
@@ -109,6 +112,7 @@ export declare class PostgresTenancy {
109
112
  private readonly logs;
110
113
  private readonly tenantCache;
111
114
  private readonly tokenCache;
115
+ private readonly tokenUseNoted;
112
116
  private readonly quotaCache;
113
117
  private readonly quotas;
114
118
  private ready;
@@ -118,16 +122,18 @@ export declare class PostgresTenancy {
118
122
  private init;
119
123
  /** Writes one audit entry. `detail` never holds a secret or a token. */
120
124
  record(actor: string | undefined, action: AuditEntry["action"], tenantId: string | null, detail: Record<string, unknown>): Promise<void>;
121
- /** Administrative actions, newest first; for one tenant when given. What the admin page shows and a tenant's export carries. */
125
+ /** Administrative actions, newest first; for one tenant when given, and only entries older than the id `before` when given. What the admin page shows and a tenant's export carries. */
122
126
  audit(opts?: {
123
127
  tenant?: string;
124
128
  limit?: number;
129
+ before?: number;
125
130
  }): Promise<AuditEntry[]>;
126
131
  private row;
127
132
  /** The tenant, or null. Answers from a ten-second cache, so a disabled tenant is refused within that. */
128
133
  tenant(id: string): Promise<Tenant | null>;
129
134
  /** Whether the presented token is a live token of this tenant. Positive answers are cached for thirty seconds. */
130
135
  authorize(tenantId: string, token: string | null): Promise<boolean>;
136
+ private noteTokenUse;
131
137
  /** The tenant's log, one instance per tenant per process. */
132
138
  log(tenantId: string): Promise<PostgresLog>;
133
139
  /** Creates a tenant, or renames its log id. `by` names who did it in the audit trail. */