@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/dist/log-store.js CHANGED
@@ -174,6 +174,7 @@ export class PostgresLog {
174
174
  export const PLANS = ["free", "team", "enterprise"];
175
175
  export const PLAN_QUOTAS = { free: 10_000, team: 1_000_000, enterprise: null };
176
176
  const sha256hex = (s) => createHash("sha256").update(s).digest("hex");
177
+ export const AUDIT_ACTIONS = ["tenant.add", "tenant.disable", "tenant.plan", "token.add", "token.revoke", "policy.add", "policy.remove", "sso.set", "sso.remove", "user.mfa-reset"];
177
178
  /** Tenants and their tokens, in Postgres. Tokens are stored hashed; a lookup hashes what the caller presented. */
178
179
  export class PostgresTenancy {
179
180
  client;
@@ -181,6 +182,7 @@ export class PostgresTenancy {
181
182
  logs = new Map();
182
183
  tenantCache = new Map();
183
184
  tokenCache = new Map();
185
+ tokenUseNoted = new Map();
184
186
  quotaCache = new Map();
185
187
  quotas;
186
188
  ready = null;
@@ -197,6 +199,7 @@ export class PostgresTenancy {
197
199
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}tenants (id TEXT PRIMARY KEY, log_id TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), disabled_at TIMESTAMPTZ)`);
198
200
  await this.client.query(`ALTER TABLE ${p}tenants ADD COLUMN IF NOT EXISTS plan TEXT NOT NULL DEFAULT 'free'`);
199
201
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}tokens (token_hash TEXT PRIMARY KEY, tenant_id TEXT NOT NULL REFERENCES ${p}tenants(id), label TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), revoked_at TIMESTAMPTZ)`);
202
+ await this.client.query(`ALTER TABLE ${p}tokens ADD COLUMN IF NOT EXISTS last_used_at TIMESTAMPTZ`);
200
203
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}audit (id BIGSERIAL PRIMARY KEY, at TIMESTAMPTZ NOT NULL DEFAULT now(), actor TEXT NOT NULL, action TEXT NOT NULL, tenant_id TEXT, detail JSONB NOT NULL DEFAULT '{}')`);
201
204
  // named policy versions a tenant chose to publish, so a receipt's policy digest can be read as a name; enforcement never reads this table
202
205
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}policies (id TEXT PRIMARY KEY, tenant_id TEXT NOT NULL REFERENCES ${p}tenants(id), name TEXT NOT NULL, digest TEXT NOT NULL, text TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_by TEXT NOT NULL, UNIQUE (tenant_id, digest))`);
@@ -209,13 +212,11 @@ export class PostgresTenancy {
209
212
  await this.init();
210
213
  await this.client.query(`INSERT INTO ${this.prefix}audit (actor, action, tenant_id, detail) VALUES ($1, $2, $3, $4)`, [actor ?? "unattributed", action, tenantId, JSON.stringify(detail)]);
211
214
  }
212
- /** Administrative actions, newest first; for one tenant when given. What the admin page shows and a tenant's export carries. */
215
+ /** 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. */
213
216
  async audit(opts = {}) {
214
217
  await this.init();
215
- const limit = Math.min(Math.max(1, opts.limit ?? 200), 1000);
216
- const rows = (opts.tenant
217
- ? await this.client.query(`SELECT id, at, actor, action, tenant_id, detail FROM ${this.prefix}audit WHERE tenant_id = $1 ORDER BY id DESC LIMIT ${limit}`, [opts.tenant])
218
- : await this.client.query(`SELECT id, at, actor, action, tenant_id, detail FROM ${this.prefix}audit ORDER BY id DESC LIMIT ${limit}`)).rows;
218
+ const limit = Math.min(Math.max(1, Math.trunc(opts.limit ?? 200)), 1000);
219
+ const rows = (await this.client.query(`SELECT id, at, actor, action, tenant_id, detail FROM ${this.prefix}audit WHERE ($1::text IS NULL OR tenant_id = $1) AND ($2::bigint IS NULL OR id < $2) ORDER BY id DESC LIMIT ${limit}`, [opts.tenant ?? null, opts.before ?? null])).rows;
219
220
  return rows.map((r) => ({ id: Number(r.id), at: new Date(r.at).toISOString(), actor: String(r.actor), action: r.action, tenantId: r.tenant_id === null || r.tenant_id === undefined ? null : String(r.tenant_id), detail: (typeof r.detail === "string" ? JSON.parse(r.detail) : r.detail) }));
220
221
  }
221
222
  row(r) {
@@ -240,14 +241,23 @@ export class PostgresTenancy {
240
241
  const hash = sha256hex(token);
241
242
  const key = `${tenantId}:${hash}`;
242
243
  const at = this.tokenCache.get(key);
243
- if (at && Date.now() - at < 30_000)
244
- return true;
245
- const rows = (await this.client.query(`SELECT 1 FROM ${this.prefix}tokens WHERE token_hash = $1 AND tenant_id = $2 AND revoked_at IS NULL`, [hash, tenantId])).rows;
246
- if (rows.length === 0)
247
- return false;
248
- this.tokenCache.set(key, Date.now());
244
+ if (!(at && Date.now() - at < 30_000)) {
245
+ const rows = (await this.client.query(`SELECT 1 FROM ${this.prefix}tokens WHERE token_hash = $1 AND tenant_id = $2 AND revoked_at IS NULL`, [hash, tenantId])).rows;
246
+ if (rows.length === 0)
247
+ return false;
248
+ this.tokenCache.set(key, Date.now());
249
+ }
250
+ this.noteTokenUse(hash);
249
251
  return true;
250
252
  }
253
+ // At most one write a minute per token per process, off the append's path: a failure costs only the "last used" time.
254
+ noteTokenUse(hash) {
255
+ const now = Date.now();
256
+ if (now - (this.tokenUseNoted.get(hash) ?? 0) < 60_000)
257
+ return;
258
+ this.tokenUseNoted.set(hash, now);
259
+ this.client.query(`UPDATE ${this.prefix}tokens SET last_used_at = now() WHERE token_hash = $1`, [hash]).catch(() => this.tokenUseNoted.delete(hash));
260
+ }
251
261
  /** The tenant's log, one instance per tenant per process. */
252
262
  async log(tenantId) {
253
263
  let l = this.logs.get(tenantId);
@@ -261,6 +271,8 @@ export class PostgresTenancy {
261
271
  async addTenant(id, logId = id, by) {
262
272
  if (!/^[A-Za-z0-9_.-]+$/.test(id))
263
273
  throw new Error(`tenant id must be a plain identifier; got "${id}"`);
274
+ if (!/^[A-Za-z0-9_.-]+$/.test(logId))
275
+ throw new Error(`log id must be a plain identifier; got "${logId}"`);
264
276
  await this.init();
265
277
  const rows = (await this.client.query(`INSERT INTO ${this.prefix}tenants (id, log_id) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET log_id = EXCLUDED.log_id RETURNING id, log_id, plan, created_at, disabled_at`, [id, logId])).rows;
266
278
  this.tenantCache.delete(id);
@@ -402,7 +414,7 @@ export class PostgresTenancy {
402
414
  }
403
415
  async listTokens(tenantId) {
404
416
  await this.init();
405
- return (await this.client.query(`SELECT tenant_id, label, token_hash, created_at, revoked_at FROM ${this.prefix}tokens WHERE tenant_id = $1 ORDER BY created_at`, [tenantId])).rows.map((r) => ({ tenantId: String(r.tenant_id), label: String(r.label), tokenHash: String(r.token_hash), createdAt: new Date(r.created_at).toISOString(), revokedAt: r.revoked_at ? new Date(r.revoked_at).toISOString() : null }));
417
+ return (await this.client.query(`SELECT tenant_id, label, token_hash, created_at, revoked_at, last_used_at FROM ${this.prefix}tokens WHERE tenant_id = $1 ORDER BY created_at`, [tenantId])).rows.map((r) => ({ tenantId: String(r.tenant_id), label: String(r.label), tokenHash: String(r.token_hash), createdAt: new Date(r.created_at).toISOString(), revokedAt: r.revoked_at ? new Date(r.revoked_at).toISOString() : null, lastUsedAt: r.last_used_at ? new Date(r.last_used_at).toISOString() : null }));
406
418
  }
407
419
  }
408
420
  /**
@@ -0,0 +1,50 @@
1
+ export declare const PERATHOS_RECEIPT_V1 = "perathos.receipt/v1";
2
+ export interface PerathosCheck {
3
+ name: string;
4
+ ok: boolean;
5
+ detail?: string;
6
+ }
7
+ export interface PerathosReport {
8
+ ok: boolean;
9
+ checks: PerathosCheck[];
10
+ warnings: string[];
11
+ session: string | null;
12
+ agent: string | null;
13
+ receipts: number;
14
+ toolCalls: number;
15
+ checkpoints: number;
16
+ signers: string[];
17
+ /** the seq of the last checkpoint; receipts after it are an unsealed tail, which is not an error */
18
+ sealedThrough: number;
19
+ unsealedTail: number;
20
+ /** pre receipts whose guard decided deny: calls that never ran */
21
+ denied: number;
22
+ signerFailures: number;
23
+ firstTs: string | null;
24
+ lastTs: string | null;
25
+ provenance: string;
26
+ }
27
+ export interface PerathosOptions {
28
+ /** Ed25519 public keys as 64 hex characters; when given, every checkpoint signer must be one of them */
29
+ trustedKeys?: string[];
30
+ /** accept a log with no checkpoint or an unsigned one, as a warning */
31
+ allowUnsigned?: boolean;
32
+ /** the head witness (`<session_id>.head.json`): the latest checkpoint's seq and receipt_hash */
33
+ head?: {
34
+ seq: number;
35
+ receipt_hash: string;
36
+ };
37
+ }
38
+ type Receipt = Record<string, unknown>;
39
+ /** The receipt_hash the spec defines: SHA-256 of the canonical JSON of every field but receipt_hash and signature. */
40
+ export declare function perathosReceiptHash(r: Receipt): string;
41
+ /** The head witness file, `{ "seq", "receipt_hash" }`, checked for shape. */
42
+ export declare function perathosHead(text: string): {
43
+ seq: number;
44
+ receipt_hash: string;
45
+ };
46
+ /** Check a Perathos session log (JSON Lines) against rules 1 to 9 of the v1 spec. */
47
+ export declare function verifyPerathosLog(text: string, opts?: PerathosOptions): PerathosReport;
48
+ /** The report as text, in the style of `verify`. */
49
+ export declare function formatPerathosReport(r: PerathosReport): string;
50
+ export {};
@@ -0,0 +1,187 @@
1
+ /**
2
+ * A reader for another project's agent records: Perathos session logs (`perathos.receipt/v1`), checked against the
3
+ * verification rules of their published spec (docs/specs/RECEIPT_V1.md in perathos-protocol/perathos). Written from
4
+ * that spec alone, so a Perathos log and an agent-custody receipt can be checked with one tool, each for what it proves.
5
+ *
6
+ * A Perathos log is recorded by hooks inside the agent's host and sealed by checkpoints signed with a key held there.
7
+ * A valid log shows that the key holder sealed this sequence and nothing up to the last checkpoint changed since. It
8
+ * does not show that an enforcement point outside the agent saw each call, which is what an agent-custody receipt
9
+ * attests, so the report says which kind of evidence it is. RFC 3161 anchors are not checked here.
10
+ */
11
+ import { createPublicKey, verify } from "node:crypto";
12
+ import { canonicalize, sha256Hex } from "./crypto.js";
13
+ export const PERATHOS_RECEIPT_V1 = "perathos.receipt/v1";
14
+ const KINDS = new Set(["pre", "post", "checkpoint"]);
15
+ const ZERO = "0".repeat(64);
16
+ const HEX64 = /^[0-9a-f]{64}$/;
17
+ // the spec's only form: fixed width, UTC, microseconds, so string order is time order
18
+ const TS = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
19
+ const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
20
+ /** The receipt_hash the spec defines: SHA-256 of the canonical JSON of every field but receipt_hash and signature. */
21
+ export function perathosReceiptHash(r) {
22
+ const body = {};
23
+ for (const [k, v] of Object.entries(r))
24
+ if (k !== "receipt_hash" && k !== "signature")
25
+ body[k] = v;
26
+ return sha256Hex(canonicalize(body));
27
+ }
28
+ function ed25519Key(hex) {
29
+ return createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, Buffer.from(hex, "hex")]), format: "der", type: "spki" });
30
+ }
31
+ function signatureOk(r) {
32
+ const signer = r.signer;
33
+ const s = r.signature;
34
+ if (typeof signer !== "string" || !HEX64.test(signer))
35
+ return "no signer key";
36
+ if (!s || typeof s !== "object")
37
+ return "no signature";
38
+ if (s.algorithm !== "ed25519")
39
+ return `algorithm ${String(s.algorithm)}`;
40
+ if (s.verify_key !== signer)
41
+ return "verify_key is not the signer";
42
+ if (typeof s.signature !== "string" || !/^[0-9a-f]{128}$/.test(s.signature))
43
+ return "signature is not 64 bytes of hex";
44
+ if (typeof r.receipt_hash !== "string" || !HEX64.test(r.receipt_hash))
45
+ return "no receipt_hash";
46
+ try {
47
+ return verify(null, Buffer.from(r.receipt_hash, "hex"), ed25519Key(signer), Buffer.from(s.signature, "hex")) ? null : "signature does not verify";
48
+ }
49
+ catch {
50
+ return "the signer is not an Ed25519 public key";
51
+ }
52
+ }
53
+ /** The head witness file, `{ "seq", "receipt_hash" }`, checked for shape. */
54
+ export function perathosHead(text) {
55
+ const h = JSON.parse(text);
56
+ if (!h || typeof h !== "object" || !Number.isInteger(h.seq) || h.seq < 1 || typeof h.receipt_hash !== "string" || !HEX64.test(h.receipt_hash))
57
+ throw new Error('the head witness must be { "seq": <integer from 1>, "receipt_hash": <64 hex> }');
58
+ return { seq: h.seq, receipt_hash: h.receipt_hash };
59
+ }
60
+ /** Check a Perathos session log (JSON Lines) against rules 1 to 9 of the v1 spec. */
61
+ export function verifyPerathosLog(text, opts = {}) {
62
+ const checks = [];
63
+ const warnings = [];
64
+ const add = (name, problems) => checks.push({ name, ok: problems.length === 0, ...(problems.length ? { detail: problems.slice(0, 3).join("; ") + (problems.length > 3 ? `; and ${problems.length - 3} more` : "") } : {}) });
65
+ const receipts = [];
66
+ const parse = [];
67
+ text.split("\n").forEach((line, i) => {
68
+ if (!line.trim())
69
+ return;
70
+ try {
71
+ const v = JSON.parse(line);
72
+ if (v && typeof v === "object" && !Array.isArray(v))
73
+ receipts.push(v);
74
+ else
75
+ parse.push(`line ${i + 1} is not an object`);
76
+ }
77
+ catch {
78
+ parse.push(`line ${i + 1} is not JSON`);
79
+ }
80
+ });
81
+ add("every line is a JSON object", parse.length ? parse : receipts.length ? [] : ["the log is empty"]);
82
+ const format = [], seq = [], chain = [], hashes = [], order = [], sigs = [], unsigned = [];
83
+ const signers = new Set();
84
+ const checkpoints = [];
85
+ const sealed = [];
86
+ let signerFailures = 0;
87
+ receipts.forEach((r, i) => {
88
+ const at = `seq ${String(r.seq ?? i + 1)}`;
89
+ if (r.v !== PERATHOS_RECEIPT_V1 || !KINDS.has(String(r.kind)))
90
+ format.push(`${at}: v ${String(r.v)}, kind ${String(r.kind)}`);
91
+ if (r.seq !== i + 1)
92
+ seq.push(`line ${i + 1} has seq ${String(r.seq)}`);
93
+ const prev = i === 0 ? ZERO : receipts[i - 1].receipt_hash;
94
+ if (r.prev_hash !== prev)
95
+ chain.push(`${at}: prev_hash does not match the receipt before`);
96
+ if (r.receipt_hash !== perathosReceiptHash(r))
97
+ hashes.push(`${at}: receipt_hash does not recompute`);
98
+ if (r.session_id !== receipts[0].session_id)
99
+ order.push(`${at}: session ${String(r.session_id)}`);
100
+ if (typeof r.ts !== "string" || !TS.test(r.ts))
101
+ order.push(`${at}: ts ${JSON.stringify(r.ts)} is not YYYY-MM-DDTHH:MM:SS.mmmmmmZ`);
102
+ else if (i > 0 && typeof receipts[i - 1].ts === "string" && TS.test(receipts[i - 1].ts) && r.ts < receipts[i - 1].ts)
103
+ order.push(`${at}: time goes back`);
104
+ if (r.kind !== "checkpoint")
105
+ return;
106
+ checkpoints.push(r);
107
+ if (r.signature === undefined && r.signer === undefined) {
108
+ unsigned.push(`${at}${typeof r.signer_error === "string" ? `: the recorder's signer failed when it was sealed (${r.signer_error})` : ""}`);
109
+ if (typeof r.signer_error === "string")
110
+ signerFailures++;
111
+ return;
112
+ }
113
+ const problem = signatureOk(r);
114
+ if (problem)
115
+ sigs.push(`${at}: ${problem}`);
116
+ else {
117
+ signers.add(r.signer);
118
+ sealed.push(r);
119
+ }
120
+ });
121
+ add("format is perathos.receipt/v1 with a known kind", format);
122
+ add("seq is 1, 2, 3, ... in file order", seq);
123
+ add("prev_hash chains each receipt to the one before", chain);
124
+ add("receipt_hash recomputes", hashes);
125
+ add("one session, and time never goes back", order);
126
+ add("checkpoint signatures verify", sigs);
127
+ const sealing = checkpoints.length ? unsigned : ["no checkpoint seals the log", ...unsigned];
128
+ if (opts.allowUnsigned) {
129
+ warnings.push(...sealing);
130
+ add("every checkpoint is signed (unsigned allowed)", []);
131
+ }
132
+ else
133
+ add("every checkpoint is signed", sealing);
134
+ if (opts.trustedKeys) {
135
+ const trusted = new Set(opts.trustedKeys.map((k) => k.toLowerCase()));
136
+ add("every signer is a trusted key", [...signers].filter((k) => !trusted.has(k)).map((k) => `untrusted signer ${k.slice(0, 12)}`));
137
+ }
138
+ else {
139
+ // without a pinned key, a second key could seal receipts appended after the recorder's last checkpoint
140
+ add("one key seals the session (no --key given)", signers.size > 1 ? [`${signers.size} keys sealed this session: ${[...signers].map((k) => k.slice(0, 12)).join(", ")}; pin the recorder's key with --key`] : []);
141
+ warnings.push("no key pinned: a VALID result shows the log is consistent with itself, not who sealed it; pin the recorder's key with --key");
142
+ }
143
+ if (opts.head) {
144
+ const h = opts.head;
145
+ const found = checkpoints.some((c) => c.seq === h.seq && c.receipt_hash === h.receipt_hash);
146
+ add("the head witness's checkpoint is in the log", found ? [] : [`no checkpoint at seq ${h.seq} with that receipt_hash: the log was cut or replaced`]);
147
+ }
148
+ // only a checkpoint whose signature verified, by a pinned key when keys are pinned, seals what comes before it
149
+ const pinned = opts.trustedKeys ? new Set(opts.trustedKeys.map((k) => k.toLowerCase())) : null;
150
+ const last = sealed.filter((c) => !pinned || pinned.has(c.signer)).at(-1);
151
+ const sealedThrough = typeof last?.seq === "number" ? last.seq : 0;
152
+ const agent = typeof receipts[0]?.agent === "string" ? receipts[0].agent : null;
153
+ return {
154
+ ok: checks.every((c) => c.ok),
155
+ checks,
156
+ warnings,
157
+ session: typeof receipts[0]?.session_id === "string" ? receipts[0].session_id : null,
158
+ agent,
159
+ receipts: receipts.length,
160
+ toolCalls: receipts.filter((r) => r.kind === "pre").length,
161
+ checkpoints: checkpoints.length,
162
+ signers: [...signers],
163
+ sealedThrough,
164
+ unsealedTail: Math.max(0, receipts.length - sealedThrough),
165
+ denied: receipts.filter((r) => r.kind === "pre" && r.guard?.decision === "deny").length,
166
+ signerFailures,
167
+ firstTs: typeof receipts[0]?.ts === "string" ? receipts[0].ts : null,
168
+ lastTs: typeof receipts.at(-1)?.ts === "string" ? receipts.at(-1).ts : null,
169
+ provenance: `perathos.receipt/v1, recorded by hooks inside the agent's host (${agent ?? "unknown"}); the checkpoint key is held on that host, so a valid log shows that the key holder sealed this sequence, not that an enforcement point outside the agent saw each call; times are the host's clock, and RFC 3161 anchors were not checked`,
170
+ };
171
+ }
172
+ /** The report as text, in the style of `verify`. */
173
+ export function formatPerathosReport(r) {
174
+ const lines = r.checks.map((c) => `${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? ` (${c.detail})` : ""}`);
175
+ for (const w of r.warnings)
176
+ lines.push(`WARN ${w}`);
177
+ lines.push("", `RESULT: ${r.ok ? "VALID" : "INVALID"}`, "");
178
+ lines.push(`session ${r.session ?? "-"}`);
179
+ lines.push(`receipts ${r.receipts} (${r.toolCalls} tool calls, ${r.checkpoints} checkpoints)`);
180
+ lines.push(`sealed through seq ${r.sealedThrough}${r.unsealedTail ? `, ${r.unsealedTail} receipt(s) after it unsealed` : ""}`);
181
+ lines.push(`signers ${r.signers.length ? r.signers.map((k) => k.slice(0, 12)).join(", ") : "-"}`);
182
+ lines.push(`time ${r.firstTs ?? "-"} to ${r.lastTs ?? "-"} (host clock)`);
183
+ if (r.denied)
184
+ lines.push(`denied ${r.denied} call(s) stopped by the guard`);
185
+ lines.push("", `PROVENANCE: ${r.provenance}`);
186
+ return lines.join("\n");
187
+ }
package/dist/portal.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type IncomingMessage, type ServerResponse } from "node:http";
2
- import { type PostgresLike, type PostgresTenancy } from "./log-store.ts";
2
+ import { type Plan, type PostgresLike, type PostgresTenancy } from "./log-store.ts";
3
3
  import { type OidcConfig, type SamlConfig, type SsoIdentity } from "./sso.ts";
4
4
  export interface StripeOptions {
5
5
  secretKey: string;
@@ -15,6 +15,8 @@ export interface MailOptions {
15
15
  from: string;
16
16
  /** an operator address that gets a note per registration, with the contact details */
17
17
  notify?: string;
18
+ /** where a reply goes, when it is not the sender */
19
+ replyTo?: string;
18
20
  /** the endpoint; Resend's by default */
19
21
  url?: string;
20
22
  fetch?: typeof fetch;
@@ -59,8 +61,10 @@ export interface PortalUser {
59
61
  id: string;
60
62
  email: string;
61
63
  createdAt: string;
62
- /** when the address was confirmed: by a verification link, or by a provider that vouched for it; null until then */
64
+ /** when the address was confirmed: by a verification link, a password reset, or a provider that vouched for it; null until then */
63
65
  emailVerifiedAt?: string | null;
66
+ /** a session or an MFA cookie signed before this time (ms) is not valid: set by a password reset or change */
67
+ sessionsAfter?: number;
64
68
  }
65
69
  /** A provider sign-in whose verified email belongs to a password account that never verified its address: refused, never linked (issue #103). */
66
70
  export declare class UnverifiedAccountError extends Error {
@@ -95,6 +99,10 @@ export declare const base32: (b: Buffer) => string;
95
99
  export declare function totp(key: Buffer, step: number): string;
96
100
  /** The time step the code matches, one step either side of now allowed; null when none. */
97
101
  export declare function totpStep(key: Buffer, code: string, now?: number): number | null;
102
+ /** The modules of the QR code for `text`, true for dark, without the quiet zone. */
103
+ export declare function qrMatrix(text: string): boolean[][];
104
+ /** The QR code as an SVG, dark on white with a four-module quiet zone, whatever the page's theme. */
105
+ export declare function qrSvg(text: string): string;
98
106
  export declare class PortalStore {
99
107
  private readonly client;
100
108
  private readonly p;
@@ -125,6 +133,7 @@ export declare class PortalStore {
125
133
  tenantId: string;
126
134
  createdAt: string;
127
135
  }[]>;
136
+ optOutOfFollowUps(userId: string): Promise<boolean>;
128
137
  markFollowedUp(userId: string, at?: Date): Promise<void>;
129
138
  updateProfile(userId: string, profile: Profile): Promise<void>;
130
139
  /**
@@ -136,6 +145,13 @@ export declare class PortalStore {
136
145
  */
137
146
  findOrCreateOAuthUser(provider: string, subject: string, email: string): Promise<PortalUser>;
138
147
  authenticate(email: string, password: string): Promise<PortalUser | null>;
148
+ /** A reset token for the account, good for `ttlMs` and once. Only its hash is stored. */
149
+ createPasswordReset(userId: string, ttlMs?: number): Promise<string>;
150
+ /** The account of a reset token that has not expired, and the token is gone; null otherwise. */
151
+ takePasswordReset(token: string): Promise<string | null>;
152
+ /** Sets the password, ends every session and MFA cookie signed before `at`, and drops the account's reset tokens. */
153
+ setPassword(userId: string, password: string, at?: number): Promise<void>;
154
+ unlinkIdentities(userId: string): Promise<void>;
139
155
  user(id: string): Promise<PortalUser | null>;
140
156
  addMember(userId: string, tenantId: string, role?: Role): Promise<void>;
141
157
  roleOf(userId: string, tenantId: string): Promise<Role | null>;
@@ -164,7 +180,12 @@ export declare class PortalStore {
164
180
  mfa(userId: string): Promise<{
165
181
  secret: string | null;
166
182
  enabled: boolean;
183
+ recoveryCodes: number;
167
184
  }>;
185
+ /** Replaces the account's recovery codes with ten new ones, returned once; only their hashes are stored. */
186
+ newRecoveryCodes(userId: string): Promise<string[]>;
187
+ /** False when the code is not one of the account's unused recovery codes. */
188
+ takeRecoveryCode(userId: string, code: string): Promise<boolean>;
168
189
  setMfaSecret(userId: string, secretHex: string): Promise<boolean>;
169
190
  /** False when this step or a later one was used already. */
170
191
  takeMfaStep(userId: string, step: number): Promise<boolean>;
@@ -226,32 +247,65 @@ export interface RunningPortal {
226
247
  url: string;
227
248
  close(): Promise<void>;
228
249
  }
250
+ export interface MailContent {
251
+ heading: string;
252
+ /** the line that an inbox shows beside the subject */
253
+ preheader?: string;
254
+ paragraphs: string[];
255
+ /** a block that keeps its line breaks and uses a fixed-width font */
256
+ code?: string;
257
+ /** the one action of the message */
258
+ button?: {
259
+ label: string;
260
+ url: string;
261
+ };
262
+ footer?: (string | {
263
+ label: string;
264
+ url: string;
265
+ })[];
266
+ }
267
+ /** Builds the HTML part and the plain-text part of one message from the same fields. Every value in the HTML is escaped, and only an http or https URL becomes a link. */
268
+ export declare function renderMail(c: MailContent): {
269
+ html: string;
270
+ text: string;
271
+ };
229
272
  /** One message through the provider. Best effort: a refusal or a failure is reported through `log`, never thrown. Returns whether it was accepted. */
230
273
  export declare function deliverMail(mail: MailOptions, m: {
231
274
  to: string;
232
275
  subject: string;
233
276
  text: string;
277
+ html?: string;
278
+ headers?: Record<string, string>;
234
279
  }, log?: (message: string) => void): Promise<boolean>;
235
280
  /**
236
281
  * The founder's note, sent about an hour after a registration by `sendFollowUps`, once. Written to get the first
237
282
  * receipt appended: it asks which stack they are on, offers to do the integration, and says to start in observe mode.
283
+ * The signer is a setting; the default is the team.
238
284
  */
239
285
  export declare function founderNote(o: {
240
286
  name: string;
241
287
  tenant: string;
242
288
  company: string | null;
243
289
  portalUrl: string;
244
- from: string;
290
+ unsubscribeUrl: string;
291
+ signer?: string;
292
+ signerRole?: string;
245
293
  }): {
246
294
  subject: string;
247
295
  text: string;
296
+ html: string;
297
+ headers: Record<string, string>;
248
298
  };
249
299
  /**
250
300
  * Sends the founder's note to every account registered between an hour and a week ago that has not had it, and
251
- * marks each one. Accounts on the operator's own mail domains are marked without a message. Idempotent: run it hourly.
301
+ * marks each one. Accounts on the operator's own mail domains and accounts that opted out are skipped without a message.
302
+ * `secret` is the portal's secret: it signs the opt-out link. Idempotent: run it hourly.
252
303
  */
253
- export declare function sendFollowUps(store: PortalStore, mail: MailOptions, o?: {
304
+ export declare function sendFollowUps(store: PortalStore, mail: MailOptions, o: {
254
305
  portalUrl: string;
306
+ secret: string;
307
+ signer?: string;
308
+ signerRole?: string;
255
309
  now?: Date;
256
310
  minAgeMs?: number;
257
311
  maxAgeMs?: number;
@@ -267,3 +321,10 @@ export declare function servePortal(o: PortalOptions, opts: {
267
321
  port: number;
268
322
  host?: string;
269
323
  }): Promise<RunningPortal>;
324
+ /** The plan cards of the Billing page. The appends come from PLAN_QUOTAS; a test keeps the names, prices, and appends equal to site/pricing.md. */
325
+ export declare const PLAN_CARDS: readonly {
326
+ plan: Plan;
327
+ name: string;
328
+ price: string;
329
+ points: string[];
330
+ }[];