@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
package/README.md CHANGED
@@ -39,6 +39,7 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
39
39
  - [Threat model](docs/threat-model.md): every party who could make a receipt false, the move, what stops it, and whether that is a property of the evidence or of the deployment; and what is not defended
40
40
  - [What a receipt costs](docs/performance.md): each step of the issuer's hot path in microseconds, measured with `bun run bench`, what is and is not fsynced, and where the time goes
41
41
  - [Aligning with IETF SCITT](docs/scitt.md): the receipt as a SCITT signed statement, the log as a transparency service, our RFC 9162 proofs as COSE Receipts (RFC 9942), what differs and the options for each, an agent-action profile, and the steps toward the working group
42
+ - [Reading a Perathos log](docs/perathos.md): `verify-perathos` checks another project's agent records, a Perathos session log, against its spec; what a valid log proves and does not, and how its fields map onto an agent-custody receipt
42
43
 
43
44
  ## Getting started
44
45
 
@@ -69,7 +70,7 @@ const bundle = JSON.parse(readFileSync("receipts/<id>.json", "utf8"));
69
70
  verifyBundle(bundle, { issuerKeys: [loadPublicKey("keys/app.pub")], logFile: "log.jsonl" }).ok; // true
70
71
  ```
71
72
 
72
- For your own Claude Code sessions, one command does the whole setup (key, config in observe mode, starter deny policy, hooks), and `agent-custody report` lists the calls the policy would have denied: `npm install -g @agent-custody/receipts`, then `agent-custody init claude-code`, then see [docs/sdk.md](docs/sdk.md#claude-code).
73
+ To see first what it would have caught, `npx -y @agent-custody/receipts audit-sessions --since 7d` reads your past Claude Code transcripts against the starter policy and writes nothing ([docs/sdk.md](docs/sdk.md#before-you-install-your-past-sessions)). For your own Claude Code sessions, one command does the whole setup (key, config in observe mode, starter deny policy, hooks), and `agent-custody report` lists the calls the policy would have denied: `npm install -g @agent-custody/receipts`, then `agent-custody init claude-code`, then see [docs/sdk.md](docs/sdk.md#claude-code).
73
74
 
74
75
  Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, OpenClaw, DeepSeek Harness, Hermes and Google ADK, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx @agent-custody/receipts gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md); between an agent and the agents it delegates to over A2A, `--a2a` serves the gateway as an A2A agent itself. The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published after each npm release by running the `mcp-registry` workflow from the Actions tab (GitHub OIDC, no token).
75
76
 
@@ -262,7 +263,8 @@ src/crypto.ts canonical JSON, sha256, Ed25519 keys, DSSE sign/verify
262
263
  src/log.ts Merkle log: append, root, inclusion and consistency proofs, verify, JSONL persistence; a lock file makes an append safe when several processes share one log file, and a partial last line from a killed writer is moved to `<file>.torn`
263
264
  src/lock.ts the one lock file design (owner token, liveness check, rename to break a stale lock) that the local log, prune, and the gateway outbox share
264
265
  src/log-check.ts the outside monitor: verifies the head, checkpoints, witness, and anchor of a running log
265
- src/portal.ts the tenant portal: register, first key, usage against plan, keys, Stripe billing, export, member roles, TOTP MFA, single sign-on, on the log's Postgres
266
+ src/design.ts the design tokens and shared components (button, select, card, dialog, headings) that the site, the portal, and the consoles share; the app pages inline DESIGN_CSS
267
+ src/portal.ts the tenant portal: register, first key, usage against plan, activity, keys with last use, Stripe billing, export, member roles, password reset and change, TOTP MFA with a QR code and recovery codes, single sign-on, on the log's Postgres
266
268
  src/sso.ts enterprise sign-in for the portal: OIDC (code and PKCE, id_token checked against the IdP's key set) and SAML 2.0 (signed assertions only, through @node-saml/node-saml)
267
269
  src/log-export.ts a tenant's export of their own log, self-checked, as a log file the verifier reads
268
270
  src/witness.ts the witness: countersigns the log's checkpoints from another operator's machine, or refuses with an alarm
@@ -300,7 +302,7 @@ src/rest.ts the REST connector: an HTTP API described as tools, standing
300
302
  src/a2a.ts agents delegating to agents: a remote A2A agent as an upstream, and the gateway serving A2A itself in front of it
301
303
  src/upstream.ts attested execution: an upstream signs its result for the receipt; the verifier checks it with the upstream key
302
304
  src/capture.ts private evidence: per-tool capture rules applied by the issuer to the whole statement, withheld values as salted commitments or encrypted under the customer's key, restore and reveal
303
- vectors/ conformance vectors: receipts, keys, logs, proofs, and expected verdicts; `bun run vectors` regenerates them
305
+ vectors/ conformance vectors: receipts, keys, logs, proofs, and expected verdicts; `bun run vectors` regenerates them; `interop/` holds other projects' records, copied as they wrote them and never regenerated
304
306
  src/verify.ts offline verification, the human-readable report, and the audit that a later log extends an earlier one
305
307
  src/claude-init.ts `init claude-code`: the agent key, the observe-mode config, the starter policy, and the three hooks merged into the settings file with absolute paths
306
308
  src/deny-report.ts `report`: verifies the receipts of an SDK config and lists the calls the policy would have denied
@@ -380,7 +382,7 @@ The design is several producers feeding one verifier. The SDK is the top of the
380
382
  - Completeness from the provider's side (issue #178): `agent-custody completeness` lists Stripe's refunds, payouts, or transfers over a window with the auditor's own read-only key, and matches each to a verified receipt by the provider's object id. It reports actions with no receipt, receipts the provider does not have, amount, currency, and beneficiary mismatches, calls forwarded without an outcome receipt, and receipts it cannot match ([completeness](docs/completeness.md), example 35).
381
383
 
382
384
  **Next, in the order it pays off**
383
-
385
+ <!-- #region receipts-next -->
384
386
  The first three close the gap between a log the operator cannot rewrite and a record the operator cannot shape.
385
387
 
386
388
  1. Run the anchor for log.agent-custody.dev on mainnet: a funded key held only by the anchor service on the host, its records served beside the checkpoints, its address and each tenant's log id published in the welcome sheet and on the security page, and the monitor checking it. The code is done. [Issue #176](https://github.com/svayatta/agent-custody/issues/176).
@@ -390,3 +392,4 @@ The first three close the gap between a log the operator cannot rewrite and a re
390
392
  5. Post-quantum signatures: ML-DSA beside Ed25519 in the same DSSE envelope, hybrid by default when a PQ key is present, in every signed artefact and in the browser verifier. [Issue #11](https://github.com/svayatta/agent-custody/issues/11).
391
393
  6. Receiver attestation for agent-to-agent calls: the delegate signs its answer for the receipt, as a signing upstream does today.
392
394
  7. SD-JWT redaction, then ZK proofs of policy compliance. Not before.
395
+ <!-- #endregion receipts-next -->
package/dist/a2a.js CHANGED
@@ -371,7 +371,7 @@ export async function serveA2a(host, cfg, opts) {
371
371
  handler(req, res).catch((e) => {
372
372
  log(`agent-custody gateway (a2a): ${e instanceof Error ? e.message : String(e)}`);
373
373
  if (!res.headersSent)
374
- sendBody(res, 500, "application/json", JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: e instanceof Error ? e.message : String(e) } }));
374
+ sendBody(res, 500, "application/json", JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "internal error" } }));
375
375
  else
376
376
  res.end();
377
377
  });
package/dist/cli.js CHANGED
@@ -23,6 +23,8 @@ import { createDoorHost, serveDoor } from "./door.js";
23
23
  import { createEgressHost, serveEgress } from "./egress.js";
24
24
  import { draftEgressPolicy } from "./egress-draft.js";
25
25
  import { createAcsGuardian } from "./acs.js";
26
+ import { auditSessions, defaultTranscriptDir, formatSessionAudit, parseSince } from "./session-audit.js";
27
+ import { formatPerathosReport, perathosHead, verifyPerathosLog } from "./perathos.js";
26
28
  import { serveA2a } from "./a2a.js";
27
29
  import { PortalStore, sendFollowUps, servePortal } from "./portal.js";
28
30
  import { exportLog, formatExport } from "./log-export.js";
@@ -115,6 +117,8 @@ const USAGE = `agent-custody <command>
115
117
  init claude-code [--dir <dir>] [--user] [--enforce] [--log-url <url> [--log-id <id>] [--log-token-env NAME] [--log-key <pub>]]
116
118
  one command for your own Claude Code sessions: an agent key, sdk.json in observe mode, a starter deny
117
119
  policy, and the three hooks in .claude/settings.local.json (--user: ~/.claude/settings.json). Safe to run twice
120
+ audit-sessions [--since 7d|24h|<date>|all] [--dir <claude projects dir>] [--policy <file.cedar>] [--counts] [--json]
121
+ a read-only preview: which of your past Claude Code tool calls the policy would have denied, from the transcripts; writes nothing
118
122
  report --config <sdk.json> the calls that the policy would have denied, from the receipts: tool, command or path, rule, receipt id;
119
123
  a receipt that does not verify is counted apart. Exits 1 when any receipt does not verify
120
124
  hook [--config <sdk.json>] Claude Code hook command; reads the event on stdin (or AGENT_CUSTODY_CONFIG)
@@ -124,6 +128,8 @@ const USAGE = `agent-custody <command>
124
128
  log --file <log.jsonl> --key <log.key> [--port 8787] [--host 127.0.0.1] [--token-env <NAME>] reference log server
125
129
  verify <bundle.json> --issuer-key <pub> [--principal-key <pub>] [--approval-key <pub>] [--log-key <pub> | --log-url <url>] [--log-id <id>] [--require-strict] [--upstream-key <pub>] [--stripe-secret-env NAME] [--github-secret-env NAME] [--log <log.jsonl>] [--disclose <file>] [--capture-key-env NAME] [--json]
126
130
  verify --markdown <dir|bundle.json>... --issuer-key <pub> one Markdown table for a directory of bundles; exit 1 when one does not verify or none exists
131
+ verify-perathos <session.jsonl> [--key <hex>]... [--allow-unsigned] [--head <session.head.json>] [--json]
132
+ check another project's record format, a Perathos session log (perathos.receipt/v1), against its spec; exit 1 when it is not valid
127
133
  export --receipts <dir> --out <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--since <ISO time>] [--allow-clear]
128
134
  copies the verified receipt bundles that keep their values private into a directory for a pull request, byte for byte.
129
135
  Reads only <id>.json at the top level; never salts/, outbox/, or *.authorization.json. Exits 1 when it refuses a receipt, and when it copies none
@@ -179,7 +185,8 @@ const USAGE = `agent-custody <command>
179
185
  [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]
180
186
  the tenant portal: register, first key, usage against plan, keys, billing, export
181
187
  log-admin --db-env NAME import --file <log.jsonl> [--tenant default] copies a file log into the database as hashes
182
- portal-followup --db-env NAME --mail-key-env NAME --mail-from <address> [--mail-notify <address>] [--portal-url <url>] [--dry-run]
188
+ portal-followup --db-env NAME --secret-env NAME --mail-key-env NAME --mail-from <address> [--mail-notify <address>] [--mail-reply-to <address>]
189
+ [--signer <name>] [--signer-role <role>] [--portal-url <url>] [--dry-run]
183
190
  the founder's note to registrations an hour to a week old that have not had it; hourly from cron
184
191
  audit --older <bundle.json> --newer <bundle.json> (--log <log.jsonl> | --log-url <url>) [--issuer-key <pub>] [--log-key <pub>] [--log-id <id>] [--witness-key <pub> | --witness-url <url>] [--json]
185
192
  with --log-url the log's published keys are fetched and pinned by keyid; with a witness key or
@@ -456,6 +463,20 @@ async function main(argv) {
456
463
  });
457
464
  return 0;
458
465
  }
466
+ case "audit-sessions": {
467
+ const { values } = parseArgs({ args: rest, options: { since: { type: "string", default: "7d" }, dir: { type: "string" }, policy: { type: "string" }, json: { type: "boolean", default: false }, counts: { type: "boolean", default: false } } });
468
+ if (values.policy && isRegoFile(values.policy))
469
+ throw new Error("audit-sessions reads a Cedar policy; a Rego policy needs opa, which writes files");
470
+ const templateUrl = new URL("../templates/claude-code.cedar", import.meta.url);
471
+ const audit = auditSessions({
472
+ dir: values.dir ?? defaultTranscriptDir(),
473
+ policyText: readFileSync(values.policy ?? templateUrl, "utf8"),
474
+ policyName: values.policy ?? "the init claude-code template",
475
+ ...(values.since === "all" ? {} : { since: parseSince(values.since) }),
476
+ });
477
+ console.log(values.json ? JSON.stringify(audit, null, 2) : formatSessionAudit(audit, { counts: values.counts }));
478
+ return 0;
479
+ }
459
480
  case "report": {
460
481
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" } } });
461
482
  if (!values.config)
@@ -592,18 +613,21 @@ async function main(argv) {
592
613
  }
593
614
  case "portal-followup": {
594
615
  // The founder's note to every registration between an hour and a week old that has not had it; run hourly from cron.
595
- const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "portal-url": { type: "string", default: "https://app.agent-custody.dev/" }, "dry-run": { type: "boolean", default: false } } });
596
- if (!values["db-env"] || !values["mail-key-env"] || !values["mail-from"])
597
- throw new Error("portal-followup needs --db-env, --mail-key-env, and --mail-from");
616
+ const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "mail-reply-to": { type: "string" }, "secret-env": { type: "string" }, signer: { type: "string" }, "signer-role": { type: "string" }, "portal-url": { type: "string", default: "https://app.agent-custody.dev/" }, "dry-run": { type: "boolean", default: false } } });
617
+ if (!values["db-env"] || !values["secret-env"] || !values["mail-key-env"] || !values["mail-from"])
618
+ throw new Error("portal-followup needs --db-env, --secret-env, --mail-key-env, and --mail-from");
598
619
  const apiKey = process.env[values["mail-key-env"]];
599
620
  if (!apiKey)
600
621
  throw new Error(`portal-followup: environment variable ${values["mail-key-env"]} is not set`);
601
- const r = await sendFollowUps(new PortalStore(openPostgres(values["db-env"])), { apiKey, from: values["mail-from"], ...(values["mail-notify"] ? { notify: values["mail-notify"] } : {}) }, { portalUrl: values["portal-url"], dryRun: values["dry-run"] });
622
+ const secret = process.env[values["secret-env"]];
623
+ if (!secret)
624
+ throw new Error(`portal-followup: environment variable ${values["secret-env"]} is not set`);
625
+ const r = await sendFollowUps(new PortalStore(openPostgres(values["db-env"])), { apiKey, from: values["mail-from"], ...(values["mail-notify"] ? { notify: values["mail-notify"] } : {}), ...(values["mail-reply-to"] ? { replyTo: values["mail-reply-to"] } : {}) }, { portalUrl: values["portal-url"], secret, ...(values.signer ? { signer: values.signer } : {}), ...(values["signer-role"] ? { signerRole: values["signer-role"] } : {}), dryRun: values["dry-run"] });
602
626
  console.log(`${values["dry-run"] ? "would send" : "sent"} ${r.sent.length}, skipped ${r.skipped.length} (operator's own), failed ${r.failed.length}${r.sent.length ? `: ${r.sent.join(", ")}` : ""}`);
603
627
  return r.failed.length ? 1 : 0;
604
628
  }
605
629
  case "portal": {
606
- const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "secret-env": { type: "string" }, "public-url": { type: "string" }, "checkpoints-url": { type: "string" }, "portal-url": { type: "string" }, port: { type: "string", default: "8792" }, host: { type: "string", default: "127.0.0.1" }, "stripe-key-env": { type: "string" }, "stripe-webhook-env": { type: "string" }, "stripe-price-team": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "github-client-id": { type: "string" }, "github-secret-env": { type: "string" }, "google-client-id": { type: "string" }, "google-secret-env": { type: "string" }, "trust-proxy": { type: "boolean", default: false } } });
630
+ const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "secret-env": { type: "string" }, "public-url": { type: "string" }, "checkpoints-url": { type: "string" }, "portal-url": { type: "string" }, port: { type: "string", default: "8792" }, host: { type: "string", default: "127.0.0.1" }, "stripe-key-env": { type: "string" }, "stripe-webhook-env": { type: "string" }, "stripe-price-team": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "mail-reply-to": { type: "string" }, "github-client-id": { type: "string" }, "github-secret-env": { type: "string" }, "google-client-id": { type: "string" }, "google-secret-env": { type: "string" }, "trust-proxy": { type: "boolean", default: false } } });
607
631
  if (!values["db-env"] || !values["secret-env"] || !values["public-url"])
608
632
  throw new Error("portal needs --db-env, --secret-env, and --public-url");
609
633
  let oauth;
@@ -628,7 +652,7 @@ async function main(argv) {
628
652
  const apiKey = process.env[values["mail-key-env"]];
629
653
  if (!apiKey)
630
654
  throw new Error(`portal: environment variable ${values["mail-key-env"]} is not set`);
631
- mail = { apiKey, from: values["mail-from"], ...(values["mail-notify"] ? { notify: values["mail-notify"] } : {}) };
655
+ mail = { apiKey, from: values["mail-from"], ...(values["mail-notify"] ? { notify: values["mail-notify"] } : {}), ...(values["mail-reply-to"] ? { replyTo: values["mail-reply-to"] } : {}) };
632
656
  }
633
657
  const secret = process.env[values["secret-env"]];
634
658
  if (!secret || secret.length < 32)
@@ -839,6 +863,25 @@ async function main(argv) {
839
863
  await running.close();
840
864
  return 0;
841
865
  }
866
+ case "verify-perathos": {
867
+ const { values, positionals } = parseArgs({
868
+ args: rest,
869
+ allowPositionals: true,
870
+ options: { key: { type: "string", multiple: true }, "allow-unsigned": { type: "boolean", default: false }, head: { type: "string" }, json: { type: "boolean", default: false } },
871
+ });
872
+ if (positionals.length !== 1)
873
+ throw new Error("verify-perathos needs one session log");
874
+ for (const k of values.key ?? [])
875
+ if (!/^[0-9a-fA-F]{64}$/.test(k))
876
+ throw new Error(`--key takes an Ed25519 public key as 64 hex characters; got "${k}"`);
877
+ const report = verifyPerathosLog(readFileSync(positionals[0], "utf8"), {
878
+ ...(values.key ? { trustedKeys: values.key } : {}),
879
+ allowUnsigned: values["allow-unsigned"],
880
+ ...(values.head ? { head: perathosHead(readFileSync(values.head, "utf8")) } : {}),
881
+ });
882
+ console.log(values.json ? JSON.stringify(report, null, 2) : formatPerathosReport(report));
883
+ return report.ok ? 0 : 1;
884
+ }
842
885
  case "verify": {
843
886
  const { values, positionals } = parseArgs({
844
887
  args: rest,
@@ -1,47 +1,50 @@
1
1
  // The console's one page. The data it shows is written into the document with textContent only, never as markup, and the
2
2
  // content-security-policy allows exactly this script and this style by hash, so a value that reaches the page cannot run.
3
3
  import { createHash } from "node:crypto";
4
- const STYLE = String.raw `
5
- :root { --bg: #fafaf9; --panel: #ffffff; --ink: #1c1917; --muted: #78716c; --line: #e7e5e4; --accent: #b45309; --accent-ink: #ffffff; --ok: #15803d; --warn: #b45309; --bad: #b91c1c; --code: #f5f5f4; color-scheme: light dark; }
6
- @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --bg: #1c1917; --panel: #292524; --ink: #fafaf9; --muted: #a8a29e; --line: #44403c; --accent: #f59e0b; --accent-ink: #1c1917; --ok: #4ade80; --warn: #fbbf24; --bad: #f87171; --code: #1c1917; } }
7
- :root[data-theme="dark"] { --bg: #1c1917; --panel: #292524; --ink: #fafaf9; --muted: #a8a29e; --line: #44403c; --accent: #f59e0b; --accent-ink: #1c1917; --ok: #4ade80; --warn: #fbbf24; --bad: #f87171; --code: #1c1917; }
8
- * { box-sizing: border-box; }
9
- body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.5 Inter, system-ui, -apple-system, "Segoe UI", sans-serif; }
4
+ import { DESIGN_CSS } from "./design.js";
5
+ const STYLE = DESIGN_CSS + String.raw `
6
+ :root { --muted: var(--ink2); --code: var(--soft); }
10
7
  header { display: flex; align-items: center; gap: 16px; padding: 12px 24px; border-bottom: 1px solid var(--line); background: var(--panel); flex-wrap: wrap; }
11
- header h1 { font-size: 15px; margin: 0; font-weight: 650; }
8
+ header h1 { font-size: var(--text-md); margin: 0; }
12
9
  nav { display: flex; gap: 4px; flex-wrap: wrap; flex: 1; }
13
- nav button { background: none; border: 0; padding: 6px 12px; border-radius: 6px; color: var(--muted); cursor: pointer; font: inherit; }
10
+ nav button { background: none; border: 0; padding: 6px 12px; border-radius: var(--radius-sm); color: var(--muted); cursor: pointer; font: inherit; }
14
11
  nav button[aria-current="page"] { background: var(--code); color: var(--ink); font-weight: 600; }
15
12
  main { max-width: 1100px; margin: 0 auto; padding: 24px 16px 64px; }
16
- h2 { font-size: 18px; margin: 0 0 12px; }
17
- h3 { font-size: 14px; margin: 0 0 8px; }
18
- .card { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 16px; margin-bottom: 16px; }
13
+ h2 { margin: 0 0 12px; }
14
+ h3 { margin: 0 0 8px; }
15
+ .card { padding: 16px; margin-bottom: 16px; }
19
16
  .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 16px; }
20
17
  .grid .card { margin: 0; }
21
18
  table { width: 100%; border-collapse: collapse; }
22
19
  th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; }
23
- th { color: var(--muted); font-weight: 600; font-size: 12px; white-space: nowrap; overflow-wrap: normal; }
20
+ th { color: var(--muted); font-weight: 600; font-size: var(--text-xs); white-space: nowrap; overflow-wrap: normal; }
24
21
  table.kv th { width: 9em; white-space: nowrap; overflow-wrap: normal; }
25
22
  tr.click { cursor: pointer; } tr.click:hover { background: var(--code); }
26
- code, pre, textarea { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }
27
- pre { background: var(--code); padding: 10px; border-radius: 6px; overflow: auto; max-height: 420px; margin: 8px 0 0; }
28
- textarea { width: 100%; min-height: 280px; background: var(--code); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 10px; resize: vertical; }
29
- input[type=password], input[type=text], select { background: var(--code); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 6px 10px; font: inherit; }
30
- button.primary { background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 6px; padding: 7px 14px; font: inherit; font-weight: 600; cursor: pointer; }
31
- button.secondary { background: var(--panel); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 7px 14px; font: inherit; cursor: pointer; }
32
- button.danger { background: var(--bad); color: #fff; border: 0; border-radius: 6px; padding: 7px 14px; font: inherit; font-weight: 600; cursor: pointer; }
33
- button:disabled { opacity: .5; cursor: default; }
23
+ code, pre, textarea { font-family: var(--mono); font-size: var(--text-xs); }
24
+ pre { background: var(--code); padding: 10px; border-radius: var(--radius-sm); overflow: auto; max-height: 420px; margin: 8px 0 0; }
25
+ textarea { width: 100%; min-height: 280px; background: var(--code); color: var(--ink); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 10px; resize: vertical; }
34
26
  .row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin: 8px 0; }
35
27
  .muted { color: var(--muted); }
36
28
  .ok { color: var(--ok); } .warn { color: var(--warn); } .error, .bad { color: var(--bad); }
37
- .pill { display: inline-block; padding: 0 8px; border-radius: 999px; border: 1px solid var(--line); font-size: 12px; }
38
- .banner { border: 1px solid var(--line); border-left: 4px solid var(--accent); background: var(--panel); border-radius: 6px; padding: 10px 14px; margin-bottom: 16px; }
29
+ .pill { display: inline-block; padding: 0 8px; border-radius: var(--radius-full); border: 1px solid var(--line); font-size: var(--text-xs); }
30
+ .banner { border: 1px solid var(--line); border-left: 4px solid var(--accent); background: var(--panel); border-radius: var(--radius-sm); padding: 10px 14px; margin-bottom: 16px; }
39
31
  .banner.bad { border-left-color: var(--bad); }
40
32
  .finding { display: grid; grid-template-columns: 56px 130px 1fr; gap: 8px; padding: 4px 0; border-bottom: 1px solid var(--line); }
41
33
  #login { max-width: 420px; margin: 96px auto; }
42
34
  [hidden] { display: none !important; }
43
35
  .mt { margin-top: 16px; }
44
36
  textarea.short { min-height: 140px; }
37
+ dialog { background: var(--panel); color: var(--ink); border: 1px solid var(--line); border-radius: 8px; padding: 16px; max-width: min(480px, calc(100vw - 32px)); }
38
+ dialog::backdrop { background: rgba(0, 0, 0, .5); }
39
+ dialog h3 { margin: 0 0 8px; }
40
+ dialog p { margin: 8px 0; overflow-wrap: anywhere; }
41
+ .inline { margin-left: 4px; }
42
+ button.link { background: none; border: 0; padding: 0; font: inherit; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; color: var(--accent); text-decoration: underline; cursor: pointer; }
43
+ details { margin-top: 8px; }
44
+ summary { cursor: pointer; color: var(--muted); }
45
+ .scroll { overflow-x: auto; } .scroll table { min-width: 640px; }
46
+ .detail h3:focus { outline: 2px solid var(--accent); outline-offset: 2px; }
47
+ .pair { padding: 1px 0; }
45
48
  @media (max-width: 600px) { .finding { grid-template-columns: 56px 1fr; } .finding .check { display: none; } }
46
49
  `;
47
50
  const SCRIPT = String.raw `
@@ -56,6 +59,7 @@ const SCRIPT = String.raw `
56
59
  var tabs = ['Overview', 'Check', 'Policy', 'Grants', 'Receipts', 'Audit'];
57
60
  var current = 'Overview';
58
61
  var policyDigest = '';
62
+ var dirty = false;
59
63
 
60
64
  function h(tag, attrs) {
61
65
  var e = document.createElement(tag);
@@ -109,6 +113,57 @@ const SCRIPT = String.raw `
109
113
  return box;
110
114
  }
111
115
  function short(s) { return s ? String(s).slice(0, 12) + '…' : '-'; }
116
+ // the one place a time is formatted: local time to read, the UTC ISO value in the title and in datetime
117
+ function when(v) {
118
+ var d = v == null || v === '' ? null : new Date(v);
119
+ if (!d || isNaN(d.getTime())) return v == null || v === '' ? '-' : String(v);
120
+ var iso = d.toISOString();
121
+ return h('time', { datetime: iso, title: iso + ' (UTC)', text: d.toLocaleString() });
122
+ }
123
+ function digest(v) { return h('code', { title: String(v), text: short(v) }); }
124
+ function isDigest(v) { return typeof v === 'string' && /^(sha256:)?[0-9a-f]{32,}$/i.test(v); }
125
+ function isIso(v) { return typeof v === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z$/.test(v); }
126
+ function value(v) {
127
+ if (isDigest(v)) return digest(v);
128
+ if (isIso(v)) return when(v);
129
+ if (typeof v === 'boolean') return v ? 'yes' : 'no';
130
+ if (Array.isArray(v)) return v.length ? v.join(', ') : 'none';
131
+ if (v !== null && typeof v === 'object') return JSON.stringify(v);
132
+ return v == null ? '-' : String(v);
133
+ }
134
+ function pairs(o) {
135
+ var box = h('div');
136
+ Object.keys(o).forEach(function (k) { box.appendChild(h('div', { class: 'pair' }, h('span', { class: 'muted', text: k + ' ' }), value(o[k]))); });
137
+ return box;
138
+ }
139
+ function inline(el, text, bad) { el.className = 'inline ' + (bad ? 'bad' : 'ok'); el.textContent = text; }
140
+ function inlineFail(el) { return function (e) { inline(el, e.message || String(e), true); }; }
141
+
142
+ // An in-page question built on the native dialog. It resolves true on the confirm button and false on Cancel or Escape.
143
+ function ask(title, body, label, danger) {
144
+ return new Promise(function (resolve) {
145
+ var dlg = h('dialog', { 'aria-labelledby': 'dlg-title' });
146
+ var cancel = h('button', { type: 'button', class: 'secondary', autofocus: !!danger, onclick: function () { dlg.close('cancel'); } }, 'Cancel');
147
+ var go = h('button', { type: 'button', class: danger ? 'danger' : 'primary', autofocus: !danger, onclick: function () { dlg.close('ok'); } }, label);
148
+ dlg.appendChild(h('h3', { id: 'dlg-title', text: title }));
149
+ body.forEach(function (t) { dlg.appendChild(h('p', { text: t })); });
150
+ dlg.appendChild(h('div', { class: 'row' }, go, cancel));
151
+ dlg.addEventListener('close', function () { document.body.removeChild(dlg); resolve(dlg.returnValue === 'ok'); });
152
+ document.body.appendChild(dlg);
153
+ dlg.showModal();
154
+ });
155
+ }
156
+
157
+ var ACTIONS = { 'policy.save': 'Policy saved', 'grant.revoke': 'Grant revoked' };
158
+ function historyTable(files) {
159
+ var t = h('table', null, h('tr', null, h('th', { text: 'saved' }), h('th', { text: 'digest' })));
160
+ files.forEach(function (f) {
161
+ var m = /^(\d{4}-\d\d-\d\d)T(\d\d)-(\d\d)-(\d\d)-(\d+)Z-([0-9a-f]+)\.cedar$/.exec(f);
162
+ t.appendChild(m ? h('tr', null, h('td', null, when(m[1] + 'T' + m[2] + ':' + m[3] + ':' + m[4] + '.' + m[5] + 'Z')), h('td', null, h('code', { text: m[6] })))
163
+ : h('tr', null, h('td', { colspan: 2, text: f })));
164
+ });
165
+ return t;
166
+ }
112
167
 
113
168
  var renderers = {
114
169
  Overview: function () {
@@ -126,7 +181,7 @@ const SCRIPT = String.raw `
126
181
  h('div', { class: 'card' }, h('h3', { text: 'Gateway' }), kv([['status', gw], ['key id', o.gatewayKeyid ? short(o.gatewayKeyid) : 'not created yet'], ['mode', o.mode], ['config', o.configFile]])),
127
182
  h('div', { class: 'card' }, h('h3', { text: 'Evidence' }), kv([['receipts', String(o.receiptCount)], ['last receipt', o.lastReceiptAt], ['log', o.log.kind === 'remote' ? 'remote ' + o.log.url + (o.log.hashOnly ? ' (hashes only)' : '') : 'local ' + o.log.file], ['precommit', o.precommit.length ? o.precommit.join(', ') : 'none']])),
128
183
  h('div', { class: 'card' }, h('h3', { text: 'Who is trusted' }), kv([['principal keys', String(o.principals.length)], ['key ids', o.principals.map(short).join(', ') || 'none'], ['revoked grants', String(o.revokedCount)]])),
129
- h('div', { class: 'card' }, h('h3', { text: 'Config check' }), h('p', null, h('span', { class: errs ? 'bad' : 'ok', text: errs + ' error' + (errs === 1 ? '' : 's') }), ', ', h('span', { class: warns ? 'warn' : 'muted', text: warns + ' warning' + (warns === 1 ? '' : 's') })), h('button', { class: 'secondary', onclick: function () { show('Check'); } }, 'See the findings'))),
184
+ h('div', { class: 'card' }, h('h3', { text: 'Config check' }), h('p', null, h('span', { class: errs ? 'bad' : 'ok', text: errs + ' error' + (errs === 1 ? '' : 's') }), ', ', h('span', { class: warns ? 'warn' : 'muted', text: warns + ' warning' + (warns === 1 ? '' : 's') })), h('button', { class: 'secondary', onclick: function () { location.hash = hashOf('Check'); } }, 'See the findings'))),
130
185
  o.keyProblems.length ? h('div', { class: 'banner bad' }, o.keyProblems.join('. ')) : null,
131
186
  h('div', { class: 'card mt' }, h('h3', { text: 'Upstreams' }), up),
132
187
  o.facts.length ? h('div', { class: 'card' }, h('h3', { text: 'Fact lookups the gateway makes itself' }), kv(o.facts.map(function (f) { return [f.name, f.tool + ' for ' + f.forTools.join(', ')]; }))) : null);
@@ -152,7 +207,10 @@ const SCRIPT = String.raw `
152
207
  policyDigest = p.digest;
153
208
  var area = h('textarea', { 'aria-label': 'Cedar policy', spellcheck: 'false' });
154
209
  area.value = p.text;
210
+ dirty = false;
155
211
  var out = h('div');
212
+ var result = h('span', { role: 'status' });
213
+ area.addEventListener('input', function () { dirty = true; inline(result, ''); });
156
214
  function validate() {
157
215
  return api('POST', '/api/policy/validate', { text: area.value }).then(function (r) {
158
216
  clear(out);
@@ -184,12 +242,14 @@ const SCRIPT = String.raw `
184
242
  function save() {
185
243
  return validate().then(function (v) {
186
244
  if (!v.ok) return;
187
- var ask = 'Save this policy?\n\nA running gateway applies it from its next call.';
188
- if (v.issues.length) ask = 'Confirm before saving:\n\n' + v.issues.join('\n\n') + '\n\nSave this policy anyway?';
189
- if (!window.confirm(ask)) return;
190
- return api('PUT', '/api/policy', { text: area.value, expectDigest: policyDigest, confirm: v.issues.length > 0 }).then(function (r) {
191
- policyDigest = r.digest;
192
- say('Saved (' + short(r.digest) + '). ' + r.note);
245
+ var body = ['A running gateway applies it from its next call.'].concat(v.issues);
246
+ return ask('Save the policy ' + p.path + '?', body, v.issues.length ? 'Save anyway' : 'Save').then(function (yes) {
247
+ if (!yes) return;
248
+ return api('PUT', '/api/policy', { text: area.value, expectDigest: policyDigest, confirm: v.issues.length > 0 }).then(function (r) {
249
+ policyDigest = r.digest;
250
+ dirty = false;
251
+ inline(result, 'Saved (' + short(r.digest) + '). A running gateway applies it from its next call.');
252
+ });
193
253
  });
194
254
  });
195
255
  }
@@ -199,9 +259,9 @@ const SCRIPT = String.raw `
199
259
  area, h('div', { class: 'row' },
200
260
  h('button', { class: 'secondary', onclick: function () { validate().catch(fail); } }, 'Validate'),
201
261
  h('button', { class: 'secondary', onclick: function () { simulate().catch(fail); } }, 'Replay recorded calls'),
202
- h('button', { class: 'primary', onclick: function () { save().catch(fail); } }, 'Save')),
262
+ h('button', { class: 'primary', onclick: function () { inline(result, ''); save().catch(inlineFail(result)); } }, 'Save'), result),
203
263
  out,
204
- p.history.length ? h('div', { class: 'card' }, h('h3', { text: 'Earlier versions kept' }), h('p', { class: 'muted', text: p.history.join(', ') })) : null);
264
+ p.history.length ? h('div', { class: 'card' }, h('h3', { text: 'Earlier versions kept' }), historyTable(p.history)) : null);
205
265
  });
206
266
  },
207
267
 
@@ -209,26 +269,31 @@ const SCRIPT = String.raw `
209
269
  var area = h('textarea', { 'aria-label': 'Grant', placeholder: 'Paste a grant (the JSON of a grant file)', spellcheck: 'false', class: 'short' });
210
270
  var out = h('div');
211
271
  var last = null;
272
+ var note = h('span', { role: 'status' });
212
273
  function inspect() {
213
274
  return api('POST', '/api/grants/inspect', { grant: area.value }).then(function (g) {
214
275
  last = g;
215
276
  clear(out);
216
277
  out.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Grant' }), kv([
217
278
  ['status', h('span', { class: g.status === 'valid' ? 'ok' : 'bad', text: g.status })],
218
- ['agent', g.agent], ['principal', g.principal], ['scopes', g.scopes.join(', ')], ['issued', g.issuedAt], ['expires', g.expiresAt],
219
- ['delegated from another grant', g.delegated ? 'yes' : 'no'], ['can delegate', g.canDelegate ? 'yes' : 'no'], ['digest', g.digest], ['why not valid', g.error]]),
220
- h('div', { class: 'row' }, g.revoked ? h('span', { class: 'pill', text: 'already revoked' }) : h('button', { class: 'danger', onclick: function () { revoke().catch(fail); } }, 'Revoke this grant'))));
279
+ ['agent', g.agent], ['principal', g.principal], ['scopes', g.scopes.join(', ')], ['issued', when(g.issuedAt)], ['expires', when(g.expiresAt)],
280
+ ['delegated from another grant', g.delegated ? 'yes' : 'no'], ['can delegate', g.canDelegate ? 'yes' : 'no'], ['digest', g.digest ? digest(g.digest) : null], ['why not valid', g.error]]),
281
+ h('div', { class: 'row' }, g.revoked ? h('span', { class: 'pill', text: 'already revoked' }) : h('button', { class: 'danger', onclick: function () { inline(note, ''); revoke().catch(inlineFail(note)); } }, 'Revoke this grant'), note)));
221
282
  });
222
283
  }
223
284
  function revoke() {
224
- if (!last || !window.confirm('Revoke the grant for ' + last.agent + '?\n\nIt, and every grant delegated from it, is refused on its next call. This cannot be undone here.')) return Promise.resolve();
225
- return api('POST', '/api/grants/revoke', { grant: area.value }).then(function (r) { say('Revoked the grant for ' + r.agent + '. ' + r.note); return inspect().then(list); });
285
+ if (!last) return Promise.resolve();
286
+ var who = last.agent + ' (digest ' + short(last.digest) + ')';
287
+ return ask('Revoke the grant for ' + who + '?', ['The grant, and every grant delegated from it, is refused on its next call. This cannot be undone here.'], 'Revoke', true).then(function (yes) {
288
+ if (!yes) return;
289
+ return api('POST', '/api/grants/revoke', { grant: area.value }).then(function (r) { return inspect().then(list).then(function () { inline(note, 'Revoked the grant for ' + r.agent + '. The gateway refuses it, and every grant delegated from it, on its next call.'); }); });
290
+ });
226
291
  }
227
292
  var revoked = h('div');
228
293
  function list() {
229
294
  return api('GET', '/api/revocations').then(function (r) {
230
295
  clear(revoked);
231
- revoked.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Revoked grants (' + r.digests.length + ')' }), r.digests.length ? h('table', null, r.digests.map(function (d) { return h('tr', null, h('td', null, h('code', { text: d }))); })) : h('p', { class: 'muted', text: 'None.' })));
296
+ revoked.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Revoked grants (' + r.digests.length + ')' }), r.digests.length ? r.digests.reduce(function (t, d) { t.appendChild(h('tr', null, h('td', null, h('code', { text: d })))); return t; }, h('table', null, h('tr', null, h('th', { text: 'digest' })))) : h('p', { class: 'muted', text: 'None.' })));
232
297
  });
233
298
  }
234
299
  list().catch(fail);
@@ -244,20 +309,36 @@ const SCRIPT = String.raw `
244
309
  var body = h('table');
245
310
  function draw() {
246
311
  clear(body);
247
- body.appendChild(h('tr', null, h('th', { text: 'time' }), h('th', { text: 'agent' }), h('th', { text: 'tool' }), h('th', { text: 'decision' }), h('th', { text: 'outcome' }), h('th', { text: 'verifies' })));
312
+ body.appendChild(h('tr', null, h('th', { text: 'receipt' }), h('th', { text: 'time' }), h('th', { text: 'agent' }), h('th', { text: 'tool' }), h('th', { text: 'decision' }), h('th', { text: 'outcome' }), h('th', { text: 'verifies' })));
248
313
  r.receipts.filter(function (x) { return !filter.value || x.status === filter.value; }).forEach(function (x) {
249
- body.appendChild(h('tr', { class: 'click', onclick: function () { open(x.id); } },
250
- h('td', { text: x.timestamp || '-' }), h('td', { text: x.agent || '-' }), h('td', { text: x.tool || '-' }),
314
+ body.appendChild(h('tr', { class: 'click', onclick: function (ev) { open(x.id, ev.currentTarget.querySelector('button')); } },
315
+ h('td', null, h('button', { type: 'button', class: 'link', 'data-id': x.id, title: x.id, text: short(x.id) })),
316
+ h('td', null, when(x.timestamp)), h('td', { text: x.agent || '-' }), h('td', { text: x.tool || '-' }),
251
317
  h('td', { class: x.decision === 'deny' ? 'bad' : '', text: x.decision ? x.decision + (x.enforced ? '' : ' (not enforced)') : '-' }),
252
318
  h('td', { text: x.status ? x.status + (x.reason ? ': ' + x.reason : '') : '-' }),
253
319
  h('td', { class: x.verified ? 'ok' : 'bad', text: x.verified ? 'yes' : 'NO: ' + (x.failing || []).join(', ') })));
254
320
  });
255
321
  }
256
- function open(id) {
322
+ function close(id) {
323
+ clear(detail);
324
+ var row = body.querySelector('button[data-id="' + id + '"]');
325
+ (row || filter).focus();
326
+ }
327
+ function open(id, opener) {
257
328
  api('GET', '/api/receipts/' + encodeURIComponent(id)).then(function (d) {
258
- clear(detail);
259
- detail.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Receipt ' + id }), h('pre', { text: JSON.stringify(d.statement, null, 2) })));
260
- detail.scrollIntoView();
329
+ var s = d.summary || {};
330
+ var st = d.statement || {};
331
+ var title = h('h3', { tabindex: '-1', text: 'Receipt ' + id });
332
+ var args = st.request && st.request.argsDigest;
333
+ var res = st.execution && st.execution.resultDigest;
334
+ var rows = [['tool', s.tool], ['decision', s.decision ? s.decision + (s.enforced ? '' : ' (not enforced)') : null],
335
+ ['status', s.status ? s.status + (s.reason ? ': ' + s.reason : '') : null], ['time', when(s.timestamp)], ['agent', s.agent], ['principal', s.principal],
336
+ ['grant', st.delegation ? 'a signed grant was presented' : 'none'], ['arguments digest', args ? digest(args) : null], ['result digest', res ? digest(res) : null],
337
+ ['verifies', h('span', { class: s.verified ? 'ok' : 'bad', text: s.verified ? 'yes' : 'NO: ' + (s.failing || []).join(', ') })]];
338
+ clear(detail).appendChild(h('div', { class: 'card detail' }, title, kv(rows),
339
+ h('details', null, h('summary', { text: 'Raw JSON' }), h('pre', { text: JSON.stringify(d.statement, null, 2) })),
340
+ h('div', { class: 'row' }, h('button', { type: 'button', class: 'secondary', onclick: function () { close(id); } }, 'Close'))));
341
+ title.focus();
261
342
  }).catch(fail);
262
343
  }
263
344
  filter.addEventListener('change', draw);
@@ -265,7 +346,7 @@ const SCRIPT = String.raw `
265
346
  return h('div', null, h('h2', { text: 'Receipts' }),
266
347
  h('p', { class: 'muted', text: r.total + ' receipts on disk, the newest ' + r.receipts.length + ' shown. Each is verified against the gateway key, the trusted principals, and the local log.' }),
267
348
  r.problems.length ? h('div', { class: 'banner bad' }, r.problems.join('. ')) : null,
268
- h('div', { class: 'row' }, h('label', null, 'Outcome ', filter)), h('div', { class: 'card' }, body), detail);
349
+ h('div', { class: 'row' }, h('label', null, 'Outcome ', filter)), h('div', { class: 'card scroll' }, body), detail);
269
350
  });
270
351
  },
271
352
 
@@ -274,15 +355,19 @@ const SCRIPT = String.raw `
274
355
  var t = h('table', null, h('tr', null, h('th', { text: 'when' }), h('th', { text: 'by' }), h('th', { text: 'action' }), h('th', { text: 'detail' })));
275
356
  a.entries.forEach(function (e) {
276
357
  var rest = {}; Object.keys(e).forEach(function (k) { if (k !== 'at' && k !== 'by' && k !== 'action') rest[k] = e[k]; });
277
- t.appendChild(h('tr', null, h('td', { text: e.at }), h('td', { text: e.by }), h('td', { text: e.action }), h('td', null, h('code', { text: JSON.stringify(rest) }))));
358
+ t.appendChild(h('tr', null, h('td', null, when(e.at)), h('td', { text: e.by }), h('td', { text: ACTIONS[e.action] || e.action }), h('td', null, pairs(rest))));
278
359
  });
279
- return h('div', null, h('h2', { text: 'Audit trail' }), h('p', { class: 'muted', text: 'Every change made here: who, when, and what.' }), h('div', { class: 'card' }, a.entries.length ? t : h('p', { class: 'muted', text: 'No changes yet.' })));
360
+ return h('div', null, h('h2', { text: 'Audit trail' }), h('p', { class: 'muted', text: 'Every change made here: who, when, and what.' }), h('div', { class: 'card scroll' }, a.entries.length ? t : h('p', { class: 'muted', text: 'No changes yet.' })));
280
361
  });
281
362
  }
282
363
  };
283
364
 
365
+ // "tab=" keeps the hash from ever matching an element id, so the browser does not scroll to one
366
+ function hashOf(name) { return '#tab=' + name.toLowerCase(); }
367
+ function tabOf(hash) { return tabs.filter(function (n) { return hashOf(n) === hash; })[0]; }
284
368
  function show(name) {
285
369
  current = name;
370
+ dirty = false;
286
371
  say('');
287
372
  Array.prototype.forEach.call(document.querySelectorAll('nav button'), function (b) { if (b.textContent === name) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); });
288
373
  clear(view).appendChild(h('p', { class: 'muted', text: 'Loading…' }));
@@ -290,7 +375,16 @@ const SCRIPT = String.raw `
290
375
  }
291
376
 
292
377
  var nav = document.getElementById('nav');
293
- tabs.forEach(function (n) { nav.appendChild(h('button', { type: 'button', onclick: function () { show(n); } }, n)); });
378
+ tabs.forEach(function (n) { nav.appendChild(h('button', { type: 'button', onclick: function () { location.hash = hashOf(n); } }, n)); });
379
+ window.addEventListener('hashchange', function () {
380
+ var name = tabOf(location.hash);
381
+ if (document.getElementById('app').hidden || !name || name === current) return;
382
+ if (!dirty) return show(name);
383
+ ask('Leave the policy editor?', ['The policy has changes that are not saved. If you leave, they are lost.'], 'Discard the changes', true).then(function (yes) {
384
+ if (yes) show(name); else history.replaceState(null, '', hashOf(current));
385
+ });
386
+ });
387
+ window.addEventListener('beforeunload', function (ev) { if (dirty) { ev.preventDefault(); ev.returnValue = ''; } });
294
388
  document.getElementById('signout').addEventListener('click', signOut);
295
389
  document.getElementById('theme').addEventListener('click', function () {
296
390
  var dark = document.documentElement.getAttribute('data-theme') === 'dark' || (!document.documentElement.getAttribute('data-theme') && window.matchMedia('(prefers-color-scheme: dark)').matches);
@@ -306,11 +400,11 @@ const SCRIPT = String.raw `
306
400
  try { sessionStorage.setItem(KEY, token); } catch (e) {}
307
401
  document.getElementById('login').hidden = true;
308
402
  document.getElementById('app').hidden = false;
309
- show(current);
403
+ show(tabOf(location.hash) || current);
310
404
  }).catch(function (e) { clear(document.getElementById('login-msg')).appendChild(h('p', { class: 'bad', role: 'alert', text: e.message })); });
311
405
  });
312
406
  if (token) {
313
- api('GET', '/api/audit').then(function () { document.getElementById('login').hidden = true; document.getElementById('app').hidden = false; show(current); }).catch(function () { signOut(); });
407
+ api('GET', '/api/audit').then(function () { document.getElementById('login').hidden = true; document.getElementById('app').hidden = false; show(tabOf(location.hash) || current); }).catch(function () { signOut(); });
314
408
  }
315
409
  })();
316
410
  `;
@@ -26,5 +26,12 @@ export interface DenyReport {
26
26
  reason: string;
27
27
  }[];
28
28
  }
29
+ /** The command, file path, or URL of a call, for a one-line listing. */
30
+ export declare function targetOf(args: unknown): string;
31
+ /** The `@reason` and the text of each rule a decision names, from the policy's rules and reasons by their ids. */
32
+ export declare function ruleTexts(policyIds: string[], rules: (string | null)[], reasons: (string | null)[]): {
33
+ reasons: string[];
34
+ rules: string[];
35
+ };
29
36
  export declare function denyReport(configFile: string): DenyReport;
30
37
  export declare function formatDenyReport(r: DenyReport): string;