@agent-custody/receipts 0.7.0 → 0.9.0

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 (51) hide show
  1. package/README.md +29 -13
  2. package/dist/approval.d.ts +74 -0
  3. package/dist/approval.js +196 -0
  4. package/dist/capture.js +49 -1
  5. package/dist/check.d.ts +19 -0
  6. package/dist/check.js +288 -0
  7. package/dist/cli.js +238 -11
  8. package/dist/config.d.ts +85 -0
  9. package/dist/config.js +72 -2
  10. package/dist/console-page.d.ts +4 -0
  11. package/dist/console-page.js +342 -0
  12. package/dist/console.d.ts +20 -0
  13. package/dist/console.js +521 -0
  14. package/dist/gateway.d.ts +9 -0
  15. package/dist/gateway.js +335 -45
  16. package/dist/index.d.ts +9 -2
  17. package/dist/index.js +7 -1
  18. package/dist/issue.d.ts +8 -3
  19. package/dist/issue.js +13 -4
  20. package/dist/log-store.d.ts +3 -2
  21. package/dist/log-store.js +2 -0
  22. package/dist/operations.d.ts +101 -0
  23. package/dist/operations.js +239 -0
  24. package/dist/otel.js +12 -5
  25. package/dist/policy.d.ts +2 -0
  26. package/dist/policy.js +10 -0
  27. package/dist/portal.d.ts +78 -4
  28. package/dist/portal.js +516 -26
  29. package/dist/receipt.d.ts +36 -1
  30. package/dist/rest.js +14 -1
  31. package/dist/simulate.d.ts +58 -0
  32. package/dist/simulate.js +204 -0
  33. package/dist/splunk.js +11 -4
  34. package/dist/sso.d.ts +47 -0
  35. package/dist/sso.js +161 -0
  36. package/dist/verify.d.ts +2 -0
  37. package/dist/verify.js +241 -7
  38. package/docs/approvals.md +107 -0
  39. package/docs/codex-recovery.md +132 -0
  40. package/docs/configuration.md +224 -0
  41. package/docs/console.md +79 -0
  42. package/docs/financial-operations.md +99 -0
  43. package/docs/policies.md +23 -0
  44. package/docs/threat-model.md +13 -0
  45. package/docs/tutorials.md +9 -0
  46. package/docs/usage.md +49 -4
  47. package/docs/verification.md +26 -8
  48. package/package.json +8 -2
  49. package/vectors/audit.json +27 -27
  50. package/vectors/canonical.json +5 -5
  51. package/vectors/receipts.json +2866 -464
package/dist/issue.js CHANGED
@@ -3,7 +3,7 @@ import { chmodSync, lstatSync, mkdirSync, writeFileSync } from "node:fs";
3
3
  import { SALTS_DIR, saltsFileFor } from "./retention.js";
4
4
  import { join } from "node:path";
5
5
  import { effectiveRule, getAt, privateView } from "./capture.js";
6
- import { canonicalize, dsseSign } from "./crypto.js";
6
+ import { canonicalize, dsseSign, dsseVerify } from "./crypto.js";
7
7
  import { fileLog } from "./log-sink.js";
8
8
  import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./receipt.js";
9
9
  /** `log` is a sink, or a file path for the local log with tree heads signed by the issuer's key. */
@@ -47,13 +47,22 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
47
47
  return {
48
48
  keyid: key.keyid,
49
49
  log: sink,
50
- async issue(predicate, ctx) {
50
+ async issue(predicate, ctx, retainPrepared) {
51
51
  ensureSaltsDir();
52
52
  // the authorization's view stays until the log has taken the receipt: a producer that retries after a refusal gets the same commitments and salts
53
53
  const prior = committed.get(predicate.receiptId)?.view;
54
- const pv = view(predicate, ctx, prior);
54
+ const candidate = view(predicate, ctx, prior);
55
+ // A durable producer may retain the first signed view, salts included, before any append. Concurrent and
56
+ // restarted issuers then commit exactly those bytes rather than re-salting the same logical receipt.
57
+ const prepared = retainPrepared ? retainPrepared({ envelope: dsseSign(RECEIPT_TYPE, buildStatement(candidate.predicate), key), view: candidate }) : { envelope: dsseSign(RECEIPT_TYPE, buildStatement(candidate.predicate), key), view: candidate };
58
+ const pv = prepared.view;
55
59
  const v = pv.predicate;
56
- const envelope = dsseSign(RECEIPT_TYPE, buildStatement(v), key);
60
+ const envelope = prepared.envelope;
61
+ if (retainPrepared) {
62
+ const checked = dsseVerify(envelope, [key]);
63
+ if (!checked.ok || envelope.payloadType !== RECEIPT_TYPE || v.receiptId !== predicate.receiptId || canonicalize(checked.payload) !== canonicalize(buildStatement(v)))
64
+ throw new Error("prepared receipt does not match this issuer, predicate, or receipt id");
65
+ }
57
66
  const entry = await sink.append(canonicalize(envelope));
58
67
  committed.delete(predicate.receiptId);
59
68
  // the salts once the log has taken the leaf: a receipt the log refused leaves nothing behind
@@ -88,7 +88,7 @@ export interface AuditEntry {
88
88
  id: number;
89
89
  at: string;
90
90
  actor: string;
91
- action: "tenant.add" | "tenant.disable" | "tenant.plan" | "token.add" | "token.revoke" | "policy.add" | "policy.remove";
91
+ action: "tenant.add" | "tenant.disable" | "tenant.plan" | "token.add" | "token.revoke" | "policy.add" | "policy.remove" | "sso.set" | "sso.remove" | "user.mfa-reset";
92
92
  tenantId: string | null;
93
93
  detail: Record<string, unknown>;
94
94
  }
@@ -116,7 +116,8 @@ export declare class PostgresTenancy {
116
116
  quotas?: Partial<Record<Plan, number | null>>;
117
117
  });
118
118
  private init;
119
- private record;
119
+ /** Writes one audit entry. `detail` never holds a secret or a token. */
120
+ record(actor: string | undefined, action: AuditEntry["action"], tenantId: string | null, detail: Record<string, unknown>): Promise<void>;
120
121
  /** Administrative actions, newest first; for one tenant when given. What the admin page shows and a tenant's export carries. */
121
122
  audit(opts?: {
122
123
  tenant?: string;
package/dist/log-store.js CHANGED
@@ -204,7 +204,9 @@ export class PostgresTenancy {
204
204
  }
205
205
  return this.ready;
206
206
  }
207
+ /** Writes one audit entry. `detail` never holds a secret or a token. */
207
208
  async record(actor, action, tenantId, detail) {
209
+ await this.init();
208
210
  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)]);
209
211
  }
210
212
  /** Administrative actions, newest first; for one tenant when given. What the admin page shows and a tenant's export carries. */
@@ -0,0 +1,101 @@
1
+ export declare const OPERATION_META_KEY = "agent-custody/operation";
2
+ export type OperationStatus = "submitted" | "pending" | "confirmed" | "failed" | "unknown";
3
+ /**
4
+ * A stamp that tells one process from a later process with the same PID: the kernel start time of the process.
5
+ * The prefix names the source, so two stamps from different sources never compare equal. Returns undefined when
6
+ * the start time cannot be read.
7
+ */
8
+ export declare function processStamp(pid: number): string | undefined;
9
+ /**
10
+ * The start time from `ps`, for a system without /proc. `ps` prints it in local time, so the time zone is pinned to
11
+ * UTC: a creator and an operator that run under different TZ values must still get the same text.
12
+ */
13
+ export declare function psStamp(pid: number): string | undefined;
14
+ /**
15
+ * Whether the process that created an operation may still run. A process that is gone is not alive. A live process
16
+ * with the same PID but another start time is a different process (a container restart gives PID 1 again). When a
17
+ * start time cannot be compared, the answer is "alive": recovery waits, and never releases a live forward.
18
+ */
19
+ export declare function ownerAlive(op: Pick<OperationRecord, "ownerPid" | "ownerStart">): boolean;
20
+ export interface OperationRecord {
21
+ id: string;
22
+ /** Creator process on this machine. A live submitted call cannot be reconciled underneath its forward. */
23
+ ownerPid: number;
24
+ /** `processStamp` of the creator, so that a later process with the same PID is not taken for it. */
25
+ ownerStart?: string;
26
+ issuerKeyid: string;
27
+ providerDigest?: string;
28
+ idempotencyKey: string;
29
+ principal: string;
30
+ agent: string;
31
+ tool: string;
32
+ argsDigest: string;
33
+ budget: string;
34
+ currency: string;
35
+ amount: number;
36
+ /** UTC date on which this operation was reserved; a retry never moves it to a new budget period. */
37
+ period: string;
38
+ status: OperationStatus;
39
+ originalReceiptId: string;
40
+ /** Signed authorization or execution bundle, saved before forwarding or returning it to the caller. */
41
+ original?: unknown;
42
+ /** The call as the gateway decided it, kept until `original` exists. It lets recovery sign a receipt for a call that was never forwarded. Holds raw request values: keep the database private. */
43
+ unsent?: unknown;
44
+ result?: unknown;
45
+ reconciliation?: unknown;
46
+ updatedAt: string;
47
+ }
48
+ export interface OperationReservation {
49
+ id: string;
50
+ issuerKeyid: string;
51
+ /** Digest of the configured upstream and destination; prevents retrying a key against a changed provider. */
52
+ providerDigest?: string;
53
+ principal: string;
54
+ agent: string;
55
+ tool: string;
56
+ argsDigest: string;
57
+ budget: string;
58
+ currency: string;
59
+ amount: number;
60
+ limit: number;
61
+ originalReceiptId: string;
62
+ /** Normally omitted; the gateway always uses the current UTC date. */
63
+ period?: string;
64
+ /** See `OperationRecord.unsent`. */
65
+ unsent?: unknown;
66
+ }
67
+ export interface OperationUpdate {
68
+ status?: OperationStatus;
69
+ original?: unknown;
70
+ unsent?: unknown;
71
+ result?: unknown;
72
+ reconciliation?: unknown;
73
+ }
74
+ /** One owner-only SQLite database, shared by all gateway sessions/processes using the same budgets. */
75
+ export declare class OperationStore {
76
+ private readonly db;
77
+ constructor(file: string);
78
+ get(id: string): OperationRecord | undefined;
79
+ /** Stable enumeration for an operator recovering outstanding work after a restart. */
80
+ list(): OperationRecord[];
81
+ reserve(input: OperationReservation): {
82
+ created: boolean;
83
+ operation: OperationRecord;
84
+ };
85
+ update(id: string, patch: OperationUpdate): OperationRecord;
86
+ /**
87
+ * Save the signed authorization of a submitted operation, and let the gateway forward. This is a compare-and-set:
88
+ * it refuses once recovery has closed the operation or claimed a reconciliation, whatever a liveness check said,
89
+ * so a call that recovery closed as "not forwarded" is never forwarded afterwards.
90
+ */
91
+ saveAuthorization(id: string, original: unknown): OperationRecord;
92
+ /**
93
+ * Persist one terminal reconciliation intent before its asynchronous log append; later reconcilers use it.
94
+ * With `unsent`, the claim says that the call was never forwarded, and it holds only while no authorization is saved.
95
+ */
96
+ claimReconciliation(id: string, candidate: unknown, unsent?: boolean): unknown;
97
+ /** Retain the first signed/captured receipt and its private salts, so every crash/concurrent retry uses identical bytes. */
98
+ prepareReconciliation(id: string, prepared: unknown): unknown;
99
+ close(): void;
100
+ private transaction;
101
+ }
@@ -0,0 +1,239 @@
1
+ // A side effect is claimed durably before it may be forwarded. An existing claim is never forwarded again,
2
+ // even after a crash: only a provider reconciliation read may resolve its outcome and release its reservation.
3
+ import { execFileSync } from "node:child_process";
4
+ import { closeSync, constants, lstatSync, mkdirSync, openSync, chmodSync, readFileSync } from "node:fs";
5
+ import { createRequire } from "node:module";
6
+ import { dirname, resolve } from "node:path";
7
+ import { digestOf } from "./crypto.js";
8
+ export const OPERATION_META_KEY = "agent-custody/operation";
9
+ /**
10
+ * A stamp that tells one process from a later process with the same PID: the kernel start time of the process.
11
+ * The prefix names the source, so two stamps from different sources never compare equal. Returns undefined when
12
+ * the start time cannot be read.
13
+ */
14
+ export function processStamp(pid) {
15
+ try {
16
+ // Linux: field 22 of /proc/<pid>/stat, in clock ticks since boot. The command name (field 2) may hold spaces.
17
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
18
+ const field = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
19
+ if (field)
20
+ return `proc:${field}`;
21
+ }
22
+ catch { /* no /proc: try ps */ }
23
+ return psStamp(pid);
24
+ }
25
+ /**
26
+ * The start time from `ps`, for a system without /proc. `ps` prints it in local time, so the time zone is pinned to
27
+ * UTC: a creator and an operator that run under different TZ values must still get the same text.
28
+ */
29
+ export function psStamp(pid) {
30
+ try {
31
+ const started = execFileSync("/bin/ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, env: { LC_ALL: "C", TZ: "UTC" }, stdio: ["ignore", "pipe", "ignore"] }).trim();
32
+ if (started)
33
+ return `ps:${started}`;
34
+ }
35
+ catch { /* unreadable */ }
36
+ return undefined;
37
+ }
38
+ let own;
39
+ /**
40
+ * Whether the process that created an operation may still run. A process that is gone is not alive. A live process
41
+ * with the same PID but another start time is a different process (a container restart gives PID 1 again). When a
42
+ * start time cannot be compared, the answer is "alive": recovery waits, and never releases a live forward.
43
+ */
44
+ export function ownerAlive(op) {
45
+ try {
46
+ process.kill(op.ownerPid, 0);
47
+ }
48
+ catch (error) {
49
+ if (error.code === "ESRCH")
50
+ return false;
51
+ }
52
+ const now = op.ownerStart === undefined ? undefined : processStamp(op.ownerPid);
53
+ if (op.ownerStart === undefined || now === undefined || op.ownerStart.split(":")[0] !== now.split(":")[0])
54
+ return true;
55
+ return now === op.ownerStart;
56
+ }
57
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
58
+ const STATUS = new Set(["submitted", "pending", "confirmed", "failed", "unknown"]);
59
+ const BINDING = ["issuerKeyid", "providerDigest", "principal", "agent", "tool", "argsDigest", "budget", "currency", "amount"];
60
+ /** One owner-only SQLite database, shared by all gateway sessions/processes using the same budgets. */
61
+ export class OperationStore {
62
+ db;
63
+ constructor(file) {
64
+ const path = resolve(file);
65
+ const directory = dirname(path);
66
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
67
+ const dir = lstatSync(directory);
68
+ if (!dir.isDirectory() || dir.isSymbolicLink() || (dir.mode & 0o077) !== 0)
69
+ throw new Error("operation database needs an owner-only directory (0700)");
70
+ // Create the file without following a symlink, before SQLite can open it. An existing regular file is
71
+ // tightened to 0600; the private parent prevents another user from swapping it while SQLite opens it.
72
+ try {
73
+ closeSync(openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600));
74
+ }
75
+ catch (error) {
76
+ if (error.code !== "EEXIST")
77
+ throw error;
78
+ }
79
+ const stat = lstatSync(path);
80
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)
81
+ throw new Error("operation database must be a regular file, without symlinks or hard links");
82
+ chmodSync(path, 0o600);
83
+ // Deliberately lazy: gateways without financial operations never load SQLite (Node 22 may warn).
84
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
85
+ this.db = new DatabaseSync(path);
86
+ this.db.exec("PRAGMA busy_timeout = 10000; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;");
87
+ this.db.exec("CREATE TABLE IF NOT EXISTS operations (id TEXT PRIMARY KEY, budget TEXT NOT NULL, currency TEXT NOT NULL, period TEXT NOT NULL, amount INTEGER NOT NULL, status TEXT NOT NULL, json TEXT NOT NULL)");
88
+ this.db.exec("CREATE INDEX IF NOT EXISTS operations_budget_period ON operations (budget, period, status)");
89
+ }
90
+ get(id) {
91
+ const row = this.db.prepare("SELECT json FROM operations WHERE id = ?").get(id);
92
+ return row ? JSON.parse(row.json) : undefined;
93
+ }
94
+ /** Stable enumeration for an operator recovering outstanding work after a restart. */
95
+ list() {
96
+ return this.db.prepare("SELECT json FROM operations ORDER BY id").all().map((row) => JSON.parse(row.json));
97
+ }
98
+ reserve(input) {
99
+ if (!UUID.test(input.id))
100
+ throw new Error("operation id must be a lowercase UUID");
101
+ if (!Number.isSafeInteger(input.amount) || input.amount <= 0)
102
+ throw new Error("operation amount must be a positive safe integer in minor units");
103
+ if (!Number.isSafeInteger(input.limit) || input.limit < 0)
104
+ throw new Error("operation budget limit must be a nonnegative safe integer in minor units");
105
+ for (const name of ["issuerKeyid", "principal", "agent", "tool", "argsDigest", "budget", "currency", "originalReceiptId"]) {
106
+ if (typeof input[name] !== "string" || !input[name].length)
107
+ throw new Error(`operation ${name} is required`);
108
+ }
109
+ if (input.budget.length > 128)
110
+ throw new Error("operation budget id must be at most 128 characters");
111
+ if (!/^[A-Z]{3}$/.test(input.currency))
112
+ throw new Error("operation currency must be three uppercase letters");
113
+ const period = input.period ?? new Date().toISOString().slice(0, 10);
114
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(period) || !Number.isFinite(Date.parse(`${period}T00:00:00.000Z`)) || new Date(`${period}T00:00:00.000Z`).toISOString().slice(0, 10) !== period)
115
+ throw new Error("operation period must be a UTC date");
116
+ return this.transaction(() => {
117
+ const previous = this.get(input.id);
118
+ if (previous) {
119
+ for (const field of BINDING) {
120
+ if (previous[field] !== input[field])
121
+ throw new Error(`operation id is already bound to different ${field}`);
122
+ }
123
+ return { created: false, operation: previous };
124
+ }
125
+ // Bind the currency even when an older operation failed or belongs to a previous day. Changing a
126
+ // budget's unit under the same name would otherwise make its amounts incomparable.
127
+ const otherCurrency = this.db.prepare("SELECT 1 FROM operations WHERE budget = ? AND currency <> ? LIMIT 1").get(input.budget, input.currency);
128
+ if (otherCurrency)
129
+ throw new Error("operation budget is already bound to another currency");
130
+ // Add with BigInt: individual minor-unit amounts are safe JS integers, but a sum need not be.
131
+ const reserved = this.db.prepare("SELECT amount FROM operations WHERE budget = ? AND period = ? AND status <> 'failed'").all(input.budget, period).reduce((sum, row) => sum + BigInt(row.amount), 0n);
132
+ if (reserved + BigInt(input.amount) > BigInt(input.limit))
133
+ throw new Error(`operation budget ${input.budget} exceeded for ${period}`);
134
+ const operation = {
135
+ id: input.id,
136
+ ownerPid: process.pid,
137
+ ...((own ??= { stamp: processStamp(process.pid) }).stamp !== undefined ? { ownerStart: own.stamp } : {}),
138
+ issuerKeyid: input.issuerKeyid,
139
+ ...(input.providerDigest !== undefined ? { providerDigest: input.providerDigest } : {}),
140
+ idempotencyKey: digestOf({ issuerKeyid: input.issuerKeyid, providerDigest: input.providerDigest ?? null, tool: input.tool, principal: input.principal, agent: input.agent, id: input.id }),
141
+ principal: input.principal,
142
+ agent: input.agent,
143
+ tool: input.tool,
144
+ argsDigest: input.argsDigest,
145
+ budget: input.budget,
146
+ currency: input.currency,
147
+ amount: input.amount,
148
+ period,
149
+ status: "submitted",
150
+ originalReceiptId: input.originalReceiptId,
151
+ ...(input.unsent !== undefined ? { unsent: input.unsent } : {}),
152
+ updatedAt: new Date().toISOString(),
153
+ };
154
+ this.db.prepare("INSERT INTO operations (id, budget, currency, period, amount, status, json) VALUES (?, ?, ?, ?, ?, ?, ?)").run(operation.id, operation.budget, operation.currency, operation.period, operation.amount, operation.status, JSON.stringify(operation));
155
+ return { created: true, operation };
156
+ });
157
+ }
158
+ update(id, patch) {
159
+ if (patch.status !== undefined && !STATUS.has(patch.status))
160
+ throw new Error("invalid operation status");
161
+ return this.transaction(() => {
162
+ const operation = this.get(id);
163
+ if (!operation)
164
+ throw new Error("operation not found");
165
+ if ((operation.status === "confirmed" || operation.status === "failed") && patch.status !== undefined && patch.status !== operation.status)
166
+ throw new Error(`operation ${operation.status} is terminal`);
167
+ const updated = { ...operation, ...patch, updatedAt: new Date().toISOString() };
168
+ this.db.prepare("UPDATE operations SET status = ?, json = ? WHERE id = ?").run(updated.status, JSON.stringify(updated), id);
169
+ return updated;
170
+ });
171
+ }
172
+ /**
173
+ * Save the signed authorization of a submitted operation, and let the gateway forward. This is a compare-and-set:
174
+ * it refuses once recovery has closed the operation or claimed a reconciliation, whatever a liveness check said,
175
+ * so a call that recovery closed as "not forwarded" is never forwarded afterwards.
176
+ */
177
+ saveAuthorization(id, original) {
178
+ return this.transaction(() => {
179
+ const operation = this.get(id);
180
+ if (!operation)
181
+ throw new Error("operation not found");
182
+ if (operation.status !== "submitted" || operation.reconciliation !== undefined)
183
+ throw new Error(`operation was closed (${operation.status}) before its call was forwarded`);
184
+ const updated = { ...operation, original, updatedAt: new Date().toISOString() };
185
+ delete updated.unsent;
186
+ this.db.prepare("UPDATE operations SET json = ? WHERE id = ?").run(JSON.stringify(updated), id);
187
+ return updated;
188
+ });
189
+ }
190
+ /**
191
+ * Persist one terminal reconciliation intent before its asynchronous log append; later reconcilers use it.
192
+ * With `unsent`, the claim says that the call was never forwarded, and it holds only while no authorization is saved.
193
+ */
194
+ claimReconciliation(id, candidate, unsent = false) {
195
+ if (candidate === undefined || candidate === null)
196
+ throw new Error("reconciliation intent is required");
197
+ return this.transaction(() => {
198
+ const operation = this.get(id);
199
+ if (!operation)
200
+ throw new Error("operation not found");
201
+ if (operation.reconciliation !== undefined)
202
+ return operation.reconciliation;
203
+ if (unsent && (operation.original !== undefined || operation.status !== "submitted"))
204
+ throw new Error("the operation saved its authorization meanwhile; it may have been forwarded");
205
+ const updated = { ...operation, reconciliation: candidate, updatedAt: new Date().toISOString() };
206
+ this.db.prepare("UPDATE operations SET json = ? WHERE id = ?").run(JSON.stringify(updated), id);
207
+ return candidate;
208
+ });
209
+ }
210
+ /** Retain the first signed/captured receipt and its private salts, so every crash/concurrent retry uses identical bytes. */
211
+ prepareReconciliation(id, prepared) {
212
+ return this.transaction(() => {
213
+ const operation = this.get(id);
214
+ if (!operation || !operation.reconciliation)
215
+ throw new Error("reconciliation intent is required");
216
+ const reconciliation = operation.reconciliation;
217
+ if (reconciliation.prepared !== undefined)
218
+ return reconciliation.prepared;
219
+ const updated = { ...operation, reconciliation: { ...reconciliation, prepared }, updatedAt: new Date().toISOString() };
220
+ this.db.prepare("UPDATE operations SET json = ? WHERE id = ?").run(JSON.stringify(updated), id);
221
+ return prepared;
222
+ });
223
+ }
224
+ close() { this.db.close(); }
225
+ transaction(body) {
226
+ // The write lock covers BOTH looking up the key and checking/reserving the budget. A second process
227
+ // cannot claim the same operation or pass the same budget check while this one is committing it.
228
+ this.db.exec("BEGIN IMMEDIATE");
229
+ try {
230
+ const result = body();
231
+ this.db.exec("COMMIT");
232
+ return result;
233
+ }
234
+ catch (error) {
235
+ this.db.exec("ROLLBACK");
236
+ throw error;
237
+ }
238
+ }
239
+ }
package/dist/otel.js CHANGED
@@ -7,20 +7,27 @@ export function spanFor(p, bundle, serviceName) {
7
7
  const traceId = hex.length === 32 ? hex : hex.padEnd(32, "0").slice(0, 32);
8
8
  const start = BigInt(Date.parse(p.timestamp)) * 1000000n;
9
9
  const end = BigInt(Date.now()) * 1000000n;
10
- const status = p.execution.status;
10
+ // A reconciliation receipt records a provider read that the gateway made. The gateway evaluated no policy, and it did
11
+ // not execute the payment tool again. The span says so: a dashboard must not count it as a second allowed call.
12
+ const reconciliation = p.reconciliation !== undefined;
13
+ const status = reconciliation ? "reconciled" : p.execution.status;
14
+ const operationFailed = reconciliation && p.operation?.status === "failed";
11
15
  const auth = p.authorization;
12
16
  const attributes = [
13
17
  ...str("agent_custody.receipt_id", p.receiptId),
14
18
  ...str("agent_custody.issuer.kind", p.issuer.kind),
15
19
  ...str("agent_custody.issuer.keyid", p.issuer.keyid),
16
20
  ...str("agent_custody.tool", p.tool.name),
21
+ ...(reconciliation ? [{ key: "agent_custody.reconciliation", value: { boolValue: true } }, ...str("agent_custody.reconciliation.lookup_tool", p.reconciliation.lookup?.tool)] : []),
22
+ ...str("agent_custody.operation.status", p.operation?.status),
23
+ ...str("agent_custody.operation.original_receipt_id", p.operation?.originalReceiptId),
17
24
  ...str("agent_custody.upstream", p.tool.upstream),
18
25
  ...str("agent_custody.agent", p.agent.id),
19
26
  ...str("agent_custody.agent.provenance", p.agent.provenance),
20
27
  ...str("agent_custody.principal", p.principal.id),
21
28
  ...str("agent_custody.execution.status", status),
22
- ...str("agent_custody.policy.decision", p.policy?.decision),
23
- ...str("agent_custody.policy.digest", p.policy?.policyDigest),
29
+ ...(reconciliation ? [] : str("agent_custody.policy.decision", p.policy?.decision)),
30
+ ...(reconciliation ? [] : str("agent_custody.policy.digest", p.policy?.policyDigest)),
24
31
  ...int("agent_custody.log.leaf_index", bundle.inclusion.leafIndex),
25
32
  ...int("agent_custody.log.tree_size", bundle.inclusion.treeSize),
26
33
  ...(auth ? int("agent_custody.authorization.leaf_index", auth.inclusion.leafIndex) : []),
@@ -39,13 +46,13 @@ export function spanFor(p, bundle, serviceName) {
39
46
  {
40
47
  traceId,
41
48
  spanId: traceId.slice(0, 16),
42
- name: `${p.tool.name}`,
49
+ name: reconciliation ? `${p.tool.name} reconciliation` : `${p.tool.name}`,
43
50
  kind: 3, // CLIENT: the agent calling out
44
51
  startTimeUnixNano: start.toString(),
45
52
  endTimeUnixNano: (end > start ? end : start).toString(),
46
53
  attributes,
47
54
  // Status.message is a string in OTLP; under a capture rule the error is a commitment, and the span says so
48
- status: status === "executed" || status === "denied" || status === "withheld" ? { code: 1 } : { code: 2, message: status === "failed" ? "the upstream reported failure" : typeof p.execution.error === "string" ? (p.execution.error) : p.execution.error ? "the upstream reported an error (withheld under the capture rule)" : status },
55
+ status: operationFailed ? { code: 2, message: "the provider reports that the operation failed" } : status === "executed" || status === "reconciled" || status === "denied" || status === "withheld" ? { code: 1 } : { code: 2, message: status === "failed" ? "the upstream reported failure" : typeof p.execution.error === "string" ? (p.execution.error) : p.execution.error ? "the upstream reported an error (withheld under the capture rule)" : status },
49
56
  },
50
57
  ],
51
58
  },
package/dist/policy.d.ts CHANGED
@@ -14,6 +14,8 @@ export interface PolicyRequest {
14
14
  /** Cedar context. Numbers must be integers; Cedar has no floats. */
15
15
  context: Record<string, unknown>;
16
16
  }
17
+ /** True when the policy set contains a permit rule. Cedar answers, so a `permit(` in a comment does not count. */
18
+ export declare function hasPermitRule(policyText: string): boolean;
17
19
  export declare function policyDigest(policyText: string): string;
18
20
  /**
19
21
  * Cedar's JSON context reads `{ "__entity": … }` and `{ "__extn": … }` as typed values. Arguments come from the agent,
package/dist/policy.js CHANGED
@@ -1,6 +1,16 @@
1
1
  // Cedar policy evaluation. Fails closed: any evaluation error is a deny.
2
2
  import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
3
3
  import { sha256Hex } from "./crypto.js";
4
+ /** True when the policy set contains a permit rule. Cedar answers, so a `permit(` in a comment does not count. */
5
+ export function hasPermitRule(policyText) {
6
+ const parts = cedar.policySetTextToParts(policyText);
7
+ if (parts.type !== "success")
8
+ return false;
9
+ return parts.policies.some((p) => {
10
+ const j = cedar.policyToJson(p);
11
+ return j.type === "success" && j.json.effect === "permit";
12
+ });
13
+ }
4
14
  export function policyDigest(policyText) {
5
15
  return sha256Hex(policyText);
6
16
  }
package/dist/portal.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type IncomingMessage, type ServerResponse } from "node:http";
2
2
  import { type PostgresLike, type PostgresTenancy } from "./log-store.ts";
3
+ import { type OidcConfig, type SamlConfig, type SsoIdentity } from "./sso.ts";
3
4
  export interface StripeOptions {
4
5
  secretKey: string;
5
6
  webhookSecret: string;
@@ -46,6 +47,8 @@ export interface PortalOptions {
46
47
  stripe?: StripeOptions;
47
48
  mail?: MailOptions;
48
49
  oauth?: OAuthOptions;
50
+ /** the fetch for OIDC discovery, keys, and tokens; the global one by default */
51
+ ssoFetch?: typeof fetch;
49
52
  /** key throttles by X-Forwarded-For; only behind a proxy you run. Also marks cookies Secure. */
50
53
  trustProxy?: boolean;
51
54
  /** table prefix; default portal_ */
@@ -64,6 +67,18 @@ export declare class UnverifiedAccountError extends Error {
64
67
  email: string;
65
68
  constructor(email: string);
66
69
  }
70
+ /** A single sign-on identity that the tenant's rules refuse: another domain, or an account in another tenant. */
71
+ export declare class SsoRefusedError extends Error {
72
+ }
73
+ /** One tenant's enterprise identity provider. Set by the operator only, because an IdP is trusted for the domains that the operator checked. */
74
+ export interface SsoSetting {
75
+ tenant: string;
76
+ protocol: "oidc" | "saml";
77
+ config: OidcConfig | SamlConfig;
78
+ domains: string[];
79
+ defaultRole: Role;
80
+ enforced: boolean;
81
+ }
67
82
  /** Users, memberships, and billing records, beside the log's tables. */
68
83
  /** What a registration says about the person and the organisation; every field optional in the store, the route decides what it requires. */
69
84
  export interface Profile {
@@ -73,6 +88,13 @@ export interface Profile {
73
88
  phone?: string | null;
74
89
  telegram?: string | null;
75
90
  }
91
+ /** Lowest first. */
92
+ export declare const ROLES: readonly ["readonly", "reviewer", "admin", "owner"];
93
+ export type Role = (typeof ROLES)[number];
94
+ export declare const base32: (b: Buffer) => string;
95
+ export declare function totp(key: Buffer, step: number): string;
96
+ /** The time step the code matches, one step either side of now allowed; null when none. */
97
+ export declare function totpStep(key: Buffer, code: string, now?: number): number | null;
76
98
  export declare class PortalStore {
77
99
  private readonly client;
78
100
  private readonly p;
@@ -115,7 +137,56 @@ export declare class PortalStore {
115
137
  findOrCreateOAuthUser(provider: string, subject: string, email: string): Promise<PortalUser>;
116
138
  authenticate(email: string, password: string): Promise<PortalUser | null>;
117
139
  user(id: string): Promise<PortalUser | null>;
118
- addMember(userId: string, tenantId: string): Promise<void>;
140
+ addMember(userId: string, tenantId: string, role?: Role): Promise<void>;
141
+ roleOf(userId: string, tenantId: string): Promise<Role | null>;
142
+ members(tenantId: string): Promise<{
143
+ id: string;
144
+ email: string;
145
+ role: Role;
146
+ joinedAt: string;
147
+ mfa: boolean;
148
+ }[]>;
149
+ setRole(tenantId: string, userId: string, role: Role): Promise<boolean>;
150
+ removeMember(tenantId: string, userId: string): Promise<boolean>;
151
+ invite(tenantId: string, email: string, role: Role, by: string): Promise<void>;
152
+ invitesOf(tenantId: string): Promise<{
153
+ email: string;
154
+ role: Role;
155
+ invitedBy: string;
156
+ createdAt: string;
157
+ }[]>;
158
+ invitesFor(email: string): Promise<{
159
+ tenant: string;
160
+ role: Role;
161
+ }[]>;
162
+ removeInvite(tenantId: string, email: string): Promise<boolean>;
163
+ takeInvite(tenantId: string, email: string): Promise<Role | null>;
164
+ mfa(userId: string): Promise<{
165
+ secret: string | null;
166
+ enabled: boolean;
167
+ }>;
168
+ setMfaSecret(userId: string, secretHex: string): Promise<boolean>;
169
+ /** False when this step or a later one was used already. */
170
+ takeMfaStep(userId: string, step: number): Promise<boolean>;
171
+ enableMfa(userId: string): Promise<void>;
172
+ resetMfa(email: string): Promise<boolean>;
173
+ /** Replaces the tenant's setting. A domain belongs to one tenant, so a domain that another tenant holds is refused. */
174
+ setSso(s: SsoSetting): Promise<void>;
175
+ private ssoWhere;
176
+ ssoOf(tenant: string): Promise<SsoSetting | null>;
177
+ ssoByDomain(domain: string): Promise<SsoSetting | null>;
178
+ removeSso(tenant: string): Promise<boolean>;
179
+ /**
180
+ * The account behind an identity that the tenant's IdP vouched for: the linked one; else the account with that
181
+ * email, linked from now on, if it verified its address; else a new verified account with a random password.
182
+ * The IdP proves the address, so an account that never verified it loses the address: the account goes, with its
183
+ * password, its sessions, and its links. A tenant that it owned stays for the operator. There are two exceptions: an
184
+ * unverified member of this same tenant, who verifies by password first (UnverifiedAccountError), and an
185
+ * unverified member of another tenant that has other members, who is refused. An account with
186
+ * no tenant joins with the default role. A member that an admin removed joins again only through a new invite,
187
+ * with the invited role.
188
+ */
189
+ findOrCreateSsoUser(s: SsoSetting, id: SsoIdentity): Promise<PortalUser>;
119
190
  /** the user's tenant; one per account today */
120
191
  tenantOf(userId: string): Promise<string | null>;
121
192
  setBilling(tenantId: string, b: {
@@ -134,7 +205,7 @@ export declare class PortalStore {
134
205
  stripeEventSeen(id: string): Promise<boolean>;
135
206
  /** Records a Stripe event id as applied, after it was applied, so a failure before this point lets Stripe's retry through. */
136
207
  noteStripeEvent(id: string): Promise<void>;
137
- /** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. */
208
+ /** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. Owners only. */
138
209
  registrations(): Promise<({
139
210
  tenantId: string;
140
211
  email: string;
@@ -143,8 +214,11 @@ export declare class PortalStore {
143
214
  } & Profile)[]>;
144
215
  tenantBySubscription(subscriptionId: string): Promise<string | null>;
145
216
  }
146
- export declare function signSession(secret: string, userId: string, ttlMs?: number): string;
147
- export declare function readSession(secret: string, cookie: string | undefined): string | null;
217
+ /** `via` records how the user signed in, for example `sso:acme`. */
218
+ export declare function signSession(secret: string, userId: string, ttlMs?: number, via?: string): string;
219
+ export declare const readSession: (secret: string, cookie: string | undefined) => string | null;
220
+ /** The `via` of a valid session, or null. */
221
+ export declare const readSessionVia: (secret: string, cookie: string | undefined) => string | null;
148
222
  export declare function stripeRequest(s: StripeOptions, path: string, body: Record<string, string>): Promise<Record<string, unknown>>;
149
223
  /** Stripe-Signature: t=<unix>,v1=<hmac>; the mac is over `${t}.${rawBody}` with the endpoint secret. */
150
224
  export declare function verifyStripeSignature(header: string | undefined, rawBody: string, secret: string, now?: number, toleranceMs?: number): boolean;