@agent-custody/receipts 0.16.5 → 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 (42) hide show
  1. package/README.md +7 -4
  2. package/dist/cli.js +50 -7
  3. package/dist/console-page.js +144 -50
  4. package/dist/deny-report.d.ts +7 -0
  5. package/dist/deny-report.js +8 -3
  6. package/dist/design.d.ts +11 -0
  7. package/dist/design.js +91 -0
  8. package/dist/index.d.ts +4 -0
  9. package/dist/index.js +3 -0
  10. package/dist/log-admin.js +100 -59
  11. package/dist/log-store.d.ts +8 -2
  12. package/dist/log-store.js +22 -12
  13. package/dist/perathos.d.ts +50 -0
  14. package/dist/perathos.js +187 -0
  15. package/dist/portal.d.ts +66 -5
  16. package/dist/portal.js +895 -242
  17. package/dist/session-audit.d.ts +46 -0
  18. package/dist/session-audit.js +150 -0
  19. package/dist/site-links.d.ts +23 -0
  20. package/dist/site-links.js +29 -0
  21. package/docs/acs.md +2 -0
  22. package/docs/approvals.md +1 -1
  23. package/docs/completeness.md +1 -1
  24. package/docs/configuration.md +2 -0
  25. package/docs/console.md +11 -2
  26. package/docs/door-signals.md +1 -1
  27. package/docs/door.md +4 -16
  28. package/docs/egress.md +3 -1
  29. package/docs/github-action.md +2 -2
  30. package/docs/mandates.md +1 -1
  31. package/docs/perathos.md +97 -0
  32. package/docs/sdk.md +32 -1
  33. package/docs/threat-model.md +2 -1
  34. package/docs/tutorials.md +2 -0
  35. package/docs/usage.md +3 -1
  36. package/docs/verification.md +1 -1
  37. package/package.json +1 -1
  38. package/vectors/interop/perathos/LICENSE +21 -0
  39. package/vectors/interop/perathos/README.md +17 -0
  40. package/vectors/interop/perathos/pocketos-replay/session.head.json +11 -0
  41. package/vectors/interop/perathos/pocketos-replay/session.jsonl +8 -0
  42. package/vectors/interop/perathos/pocketos-replay/verification.json +65 -0
@@ -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
+ }[];