@agent-custody/receipts 0.6.18 → 0.7.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.
package/dist/gateway.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // The MCP gateway: sits between an agent and its upstreams, MCP servers or REST APIs, enforces scope + Cedar policy,
2
2
  // and emits a signed, logged receipt for every tool call, allowed or denied.
3
3
  import { randomUUID } from "node:crypto";
4
- import { readFileSync } from "node:fs";
4
+ import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
5
5
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
6
6
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
7
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
@@ -9,12 +9,14 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
9
9
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
10
10
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
11
11
  import { digestOf, loadPrivateKey, loadPublicKey } from "./crypto.js";
12
- import { delegationValidAt, verifyDelegation } from "./delegation.js";
12
+ import { delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
13
13
  import { createIssuer } from "./issue.js";
14
14
  import { openLog } from "./log-sink.js";
15
15
  import { openExporter } from "./otel.js";
16
16
  import { upstreamEvidenceOf } from "./upstream.js";
17
17
  import { restUpstream } from "./rest.js";
18
+ import { a2aUpstream } from "./a2a.js";
19
+ import { captureKeyFrom, effectiveRule } from "./capture.js";
18
20
  import { evaluate, policyDigest } from "./policy.js";
19
21
  export const GATEWAY_VERSION = "0.1.0";
20
22
  export const RECEIPT_META_KEY = "agent-custody/receipt";
@@ -71,12 +73,26 @@ export function upstreamEnv(extra) {
71
73
  }
72
74
  return { ...base, ...(extra ?? {}) };
73
75
  }
76
+ /** Writes the revocation list whole, by rename, so a gateway re-reading it never sees half a file. */
77
+ export function writeRevokedGrants(path, digests) {
78
+ const tmp = `${path}.${process.pid}.tmp`;
79
+ writeFileSync(tmp, JSON.stringify(digests, null, 2) + "\n");
80
+ renameSync(tmp, path);
81
+ }
74
82
  export async function createGatewayHost(cfg, options = {}) {
75
83
  const gatewayKey = loadPrivateKey(cfg.identity.keyFile);
76
84
  const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
77
85
  const policyText = readFileSync(cfg.policyFile, "utf8");
78
86
  const pDigest = policyDigest(policyText);
79
- const issuer = createIssuer(gatewayKey, cfg.receiptsDir, options.log ?? openLog(cfg, gatewayKey), { exporter: options.exporter ?? openExporter(cfg) });
87
+ // Private evidence: the key that encrypts withheld fields, read once; a rule in mode encrypted without it is a config error.
88
+ const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
89
+ for (const [tool, rule] of Object.entries(cfg.capture ?? {})) {
90
+ for (const side of [rule.args, rule.result, rule.facts])
91
+ if (side?.mode === "encrypted" && !captureKey)
92
+ throw new Error(`capture for ${tool} uses mode encrypted, which needs captureKeyEnv`);
93
+ }
94
+ // The rules are applied by the issuer to every statement it signs, the authorization included: the gateway hands it the call in full.
95
+ const issuer = createIssuer(gatewayKey, cfg.receiptsDir, options.log ?? openLog(cfg, gatewayKey), { exporter: options.exporter ?? openExporter(cfg), capture: { rules: cfg.capture, key: captureKey } });
80
96
  const precommit = new Set(cfg.precommit);
81
97
  const consequential = (tool) => precommit.has("*") || precommit.has(tool);
82
98
  // A fact lookup runs before the policy can decide, because the policy decides on it. It is therefore a read the
@@ -86,6 +102,41 @@ export async function createGatewayHost(cfg, options = {}) {
86
102
  if (precommit.has(f.tool))
87
103
  throw new Error(`fact "${f.name}" uses tool ${f.tool}, which precommit names as consequential; a fact lookup runs before the policy decides and must be a read`);
88
104
  }
105
+ // Revoked grants: digests of grant envelopes, from the file the operator edits (or `revoke` appends to), re-read
106
+ // whenever the file changes. Checked when a session opens and again on every call, so revocation takes effect on
107
+ // the next call of a running session, without a key rotation.
108
+ const revokedSet = new Set();
109
+ let revokedSeen = "";
110
+ const reloadRevoked = () => {
111
+ if (!cfg.revokedGrants)
112
+ return;
113
+ if (!existsSync(cfg.revokedGrants)) {
114
+ if (revokedSeen !== "absent") {
115
+ revokedSet.clear();
116
+ revokedSeen = "absent";
117
+ }
118
+ return;
119
+ }
120
+ // inode as well as mtime: `revoke` replaces the file by rename, so two writes in one mtime tick are still seen
121
+ const st = statSync(cfg.revokedGrants);
122
+ const m = `${st.ino}:${st.mtimeMs}:${st.size}`;
123
+ if (m === revokedSeen)
124
+ return;
125
+ const list = JSON.parse(readFileSync(cfg.revokedGrants, "utf8"));
126
+ if (!Array.isArray(list))
127
+ throw new Error(`${cfg.revokedGrants}: expected a JSON array of grant digests`);
128
+ revokedSet.clear();
129
+ for (const d of list)
130
+ if (typeof d === "string")
131
+ revokedSet.add(d);
132
+ revokedSeen = m;
133
+ };
134
+ const revoke = (digest) => {
135
+ reloadRevoked();
136
+ revokedSet.add(digest);
137
+ if (cfg.revokedGrants)
138
+ writeRevokedGrants(cfg.revokedGrants, [...revokedSet]);
139
+ };
89
140
  // One host, as many upstreams as the agents' jobs need. Each tool name belongs to exactly one upstream, decided at
90
141
  // startup, so a receipt's tool is unambiguous and consumed facts flow across them.
91
142
  const upstreamConfigs = cfg.upstreams ? cfg.upstreams.map((u) => ({ name: u.name, cfg: u })) : [{ name: "upstream", cfg: cfg.upstream }];
@@ -97,6 +148,9 @@ export async function createGatewayHost(cfg, options = {}) {
97
148
  if ("rest" in u) {
98
149
  client = restUpstream(name, u.rest);
99
150
  }
151
+ else if ("a2a" in u) {
152
+ client = a2aUpstream(name, u.a2a);
153
+ }
100
154
  else if ("url" in u) {
101
155
  client = new Client({ name: "agent-custody-gateway", version: GATEWAY_VERSION });
102
156
  const token = u.tokenEnv ? process.env[u.tokenEnv] : undefined;
@@ -127,19 +181,33 @@ export async function createGatewayHost(cfg, options = {}) {
127
181
  throw new Error(`no upstream offers tool "${name}"`);
128
182
  return (await upstreams.get(via).callTool({ name, arguments: args, ...(meta ? { _meta: meta } : {}) }));
129
183
  };
184
+ /** The facts for a call, the argument template of the fact config each one came from (two configs may share a name), and each lookup's full result. */
130
185
  async function gatherFacts(tool, args, meta) {
131
- const facts = {};
186
+ // null-prototype, so a fact named __proto__ or constructor is a fact and not a prototype
187
+ const facts = Object.create(null);
188
+ const templates = Object.create(null);
189
+ const results = Object.create(null);
132
190
  for (const f of cfg.facts.filter((f) => f.forTools.includes(tool))) {
133
191
  const fargs = resolveFactArgs(f.args, args, f.optional);
134
192
  if (fargs === null)
135
193
  continue;
136
- // Lookups carry the same metadata as the forwarded call: they are the gateway acting for this receipt.
137
- const result = await callUpstream(f.tool, fargs, meta);
194
+ // Lookups carry the same metadata as the forwarded call: they are the gateway acting for this receipt. A failed
195
+ // lookup, answered isError or thrown, denies the call with the answer in policy.errors; the issuer withholds it
196
+ // under a private rule.
197
+ let result;
198
+ try {
199
+ result = await callUpstream(f.tool, fargs, meta);
200
+ }
201
+ catch (e) {
202
+ throw new Error(`fact "${f.name}" lookup via ${f.tool} failed: ${String(e instanceof Error ? e.message : e)}`);
203
+ }
138
204
  if (result.isError)
139
205
  throw new Error(`fact "${f.name}" lookup via ${f.tool} failed: ${JSON.stringify(extractValue(result))}`);
140
206
  facts[f.name] = { tool: f.tool, args: fargs, value: extractValue(result), resultDigest: digestOf(result), provenance: "observed" };
207
+ templates[f.name] = f.args;
208
+ results[f.name] = result;
141
209
  }
142
- return facts;
210
+ return { facts, templates, results };
143
211
  }
144
212
  function open(grantEnvelope) {
145
213
  const grant = verifyDelegation(grantEnvelope, trusted);
@@ -149,6 +217,26 @@ export async function createGatewayHost(cfg, options = {}) {
149
217
  throw new Error("delegation grant is outside its validity window");
150
218
  const delegation = grant.delegation;
151
219
  const principalKeyid = grant.keyid;
220
+ const chainDigests = grantChainDigests(grantEnvelope);
221
+ const grantDigest = chainDigests[0];
222
+ reloadRevoked();
223
+ if (chainDigests.some((d) => revokedSet.has(d)))
224
+ throw new Error("delegation grant has been revoked");
225
+ /** Why the grant is not in force at `at`, or null. Asked on every call, and again just before a forward. */
226
+ const grantProblem = (at = new Date().toISOString()) => {
227
+ try {
228
+ reloadRevoked();
229
+ }
230
+ catch (e) {
231
+ // fail closed: a revocation list that cannot be read revokes everything until it can
232
+ return `cannot be checked against the revocation list (${e instanceof Error ? e.message : String(e)})`;
233
+ }
234
+ if (chainDigests.some((d) => revokedSet.has(d)))
235
+ return "has been revoked";
236
+ if (!delegationValidAt(delegation, at))
237
+ return Date.parse(at) < Date.parse(delegation.issuedAt) ? "is not yet valid" : "has expired";
238
+ return null;
239
+ };
152
240
  /** Every fact id an upstream has declared it served to this session, in order of first sight. A session is one agent under one grant. */
153
241
  const consumed = [];
154
242
  const noteServedFacts = (result) => {
@@ -169,15 +257,26 @@ export async function createGatewayHost(cfg, options = {}) {
169
257
  const consumedNow = [...consumed];
170
258
  const upstreamMeta = { [RECEIPT_META_KEY]: receiptId, [AGENT_META_KEY]: delegation.agent, [PRINCIPAL_META_KEY]: delegation.principal };
171
259
  let facts = {};
260
+ let factTemplates = {};
261
+ let factResults = {};
172
262
  let policy;
173
263
  let execution;
264
+ /** what the upstream answered, in full: the agent gets this; the receipt gets the captured view */
265
+ let forwarded;
174
266
  let authorization;
175
- if (!delegation.scopes.includes(tool)) {
267
+ // The grant is enforced in every mode: a call outside its scopes, or after it expired or was revoked, is denied
268
+ // and never forwarded, observe mode or not. Observe mode suspends the Cedar policy, nothing else.
269
+ const problem = grantProblem(timestamp);
270
+ const inScope = delegation.scopes.includes(tool);
271
+ if (problem) {
272
+ policy = { decision: "deny", reasons: [], errors: [`delegation grant ${problem}`], policyDigest: pDigest };
273
+ }
274
+ else if (!inScope) {
176
275
  policy = { decision: "deny", reasons: [], errors: [`tool "${tool}" is not in the delegation scopes`], policyDigest: pDigest };
177
276
  }
178
277
  else {
179
278
  try {
180
- facts = await gatherFacts(tool, args, upstreamMeta);
279
+ ({ facts, templates: factTemplates, results: factResults } = await gatherFacts(tool, args, upstreamMeta));
181
280
  const factValues = Object.fromEntries(Object.entries(facts).map(([k, f]) => [k, f.value]));
182
281
  policy = evaluate(policyText, {
183
282
  agentId: delegation.agent,
@@ -191,9 +290,19 @@ export async function createGatewayHost(cfg, options = {}) {
191
290
  }
192
291
  // Observe mode: the decision is recorded, never enforced. The receipt says so on every call, so a verifier can
193
292
  // tell a policy that was being tested from one that was in force.
194
- if (cfg.mode === "observe")
293
+ if (cfg.mode === "observe" && !problem && inScope)
195
294
  policy = { ...policy, enforced: false };
196
295
  const forward = policy.decision === "allow" || policy.enforced === false;
296
+ // Private evidence is applied by the issuer to the whole statement. What it cannot know by itself: a fact's lookup
297
+ // arguments are copied from the call, so a fact argument may stay in clear only when its template is a constant or
298
+ // copies a call argument the args rule keeps in clear (the rule's `clear` names call arguments, and a fact argument
299
+ // may carry one under another name); the template is the one of the fact config that was used, since fact names
300
+ // are not unique across tools. And the lookups' full results, behind the facts' digests.
301
+ // the same rule the issuer will apply: for a name no upstream offers that may be the wildcard, not the name's own
302
+ const argsClear = new Set(effectiveRule(cfg.capture, tool, !owner.has(tool))?.args?.clear ?? []);
303
+ const clearFactArgs = Object.fromEntries(Object.entries(factTemplates).map(([name, template]) => [name, Object.entries(template).filter(([, v]) => !v.startsWith("$args.") || argsClear.has(v.slice("$args.".length))).map(([k]) => k)]));
304
+ // a name no upstream offers is text the agent chose: the issuer selects the rule by it and masks it in the view
305
+ const captureCtx = { clearFactArgs, factResults, unknownTool: !owner.has(tool) };
197
306
  const head = {
198
307
  receiptId,
199
308
  timestamp,
@@ -211,7 +320,7 @@ export async function createGatewayHost(cfg, options = {}) {
211
320
  // before the side effect does. If the log will not take the authorization, the call is not forwarded; in
212
321
  // observe mode nothing is withheld, and the missing authorization is printed instead.
213
322
  try {
214
- authorization = await issuer.authorize({ ...head, policy: { ...policy, provenance: "observed" } });
323
+ authorization = await issuer.authorize({ ...head, policy: { ...policy, provenance: "observed" } }, captureCtx);
215
324
  }
216
325
  catch (e) {
217
326
  if (cfg.mode === "observe")
@@ -220,9 +329,14 @@ export async function createGatewayHost(cfg, options = {}) {
220
329
  execution = { status: "withheld", reason: `the log did not commit the authorization, so the call was not forwarded: ${String(e instanceof Error ? e.message : e)}`, provenance: "observed" };
221
330
  }
222
331
  }
332
+ const late = execution ? null : forward ? grantProblem() : null;
223
333
  if (execution) {
224
334
  // withheld: nothing was forwarded
225
335
  }
336
+ else if (late) {
337
+ // the grant ran out, or was revoked, while the facts were gathered or the authorization logged
338
+ execution = { status: "withheld", reason: `the delegation grant ${late} before the call was forwarded`, provenance: "observed" };
339
+ }
226
340
  else if (forward) {
227
341
  try {
228
342
  // The upstream learns which receipt this call is, and who the grant says is calling. An upstream that keeps
@@ -230,6 +344,7 @@ export async function createGatewayHost(cfg, options = {}) {
230
344
  const observed = Object.fromEntries(Object.entries(facts).map(([k, f]) => [k, f.value]));
231
345
  const result = await callUpstream(tool, args, { ...upstreamMeta, [OBSERVED_META_KEY]: observed });
232
346
  const evidence = upstreamEvidenceOf(result);
347
+ forwarded = result;
233
348
  execution = { status: result.isError ? "failed" : "executed", result, resultDigest: digestOf(result), provenance: "observed", ...(evidence ? { upstream: evidence } : {}) };
234
349
  noteServedFacts(result);
235
350
  }
@@ -247,10 +362,11 @@ export async function createGatewayHost(cfg, options = {}) {
247
362
  policy: { ...policy, provenance: "observed" },
248
363
  ...(authorization ? { authorization } : {}),
249
364
  execution,
250
- });
365
+ }, captureCtx);
251
366
  const meta = { [RECEIPT_META_KEY]: receiptId };
252
367
  const refuse = (text) => ({ isError: true, content: [{ type: "text", text: `${text} (receipt ${receiptId})` }], _meta: meta });
253
368
  switch (execution.status) {
369
+ // the agent gets the real result, the real reason, and the real error: what is withheld is withheld from the receipt
254
370
  case "denied":
255
371
  return refuse(`Denied by policy: ${execution.reason}`);
256
372
  case "error":
@@ -258,7 +374,7 @@ export async function createGatewayHost(cfg, options = {}) {
258
374
  case "withheld":
259
375
  return refuse(`Not executed: ${execution.reason}`);
260
376
  default: {
261
- const result = execution.result;
377
+ const result = forwarded ?? execution.result;
262
378
  return { ...result, _meta: { ...result._meta, ...meta } };
263
379
  }
264
380
  }
@@ -266,6 +382,8 @@ export async function createGatewayHost(cfg, options = {}) {
266
382
  return {
267
383
  agentId: delegation.agent,
268
384
  delegation,
385
+ grantDigest,
386
+ grantProblem,
269
387
  async listTools() {
270
388
  return advertised.filter((t) => delegation.scopes.includes(t.name));
271
389
  },
@@ -278,6 +396,11 @@ export async function createGatewayHost(cfg, options = {}) {
278
396
  return {
279
397
  keyid: issuer.keyid,
280
398
  open,
399
+ revoke,
400
+ revoked: () => {
401
+ reloadRevoked();
402
+ return [...revokedSet];
403
+ },
281
404
  async close() {
282
405
  for (const c of upstreams.values())
283
406
  await c.close();
package/dist/index.d.ts CHANGED
@@ -5,9 +5,12 @@ export { buildRequest, restUpstream } from "./rest.ts";
5
5
  export { openExporter, otlpExporter, spanFor } from "./otel.ts";
6
6
  export { hecEvent, splunkExporter } from "./splunk.ts";
7
7
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
8
+ export * from "./capture.ts";
9
+ export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.ts";
8
10
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
9
11
  export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
10
12
  export type { HttpGatewayOptions, RunningHttpGateway } from "./gateway-http.ts";
13
+ export type { A2aServerOptions, AgentCard, ResolvedCard, RunningA2aServer } from "./a2a.ts";
11
14
  export { exportLog, formatExport } from "./log-export.ts";
12
15
  export type { ExportOptions, ExportResult } from "./log-export.ts";
13
16
  export { fileBackend, importLogFile, PostgresLog, PostgresTenancy, RateLimiter } from "./log-store.ts";
package/dist/index.js CHANGED
@@ -4,6 +4,8 @@ export { buildRequest, restUpstream } from "./rest.js";
4
4
  export { openExporter, otlpExporter, spanFor } from "./otel.js";
5
5
  export { hecEvent, splunkExporter } from "./splunk.js";
6
6
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.js";
7
+ export * from "./capture.js";
8
+ export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
7
9
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.js";
8
10
  export { exportLog, formatExport } from "./log-export.js";
9
11
  export { fileBackend, importLogFile, PostgresLog, PostgresTenancy, RateLimiter } from "./log-store.js";
package/dist/issue.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type CaptureConfig, type CaptureContext } from "./capture.ts";
1
2
  import { type KeyPair } from "./crypto.ts";
2
3
  import { type LogSink } from "./log-sink.ts";
3
4
  import type { ReceiptExporter } from "./otel.ts";
@@ -5,14 +6,23 @@ import { type AuthorizationBundle, type AuthorizationPredicate, type ReceiptBund
5
6
  export interface Issuer {
6
7
  keyid: string;
7
8
  log: LogSink;
8
- /** Signs the statement, appends it to the log, writes the bundle. Rejects if the log refuses the leaf; no bundle is written then. */
9
- issue(predicate: ReceiptPredicate): Promise<ReceiptBundle>;
10
- /** Signs and commits an authorization before a consequential call is forwarded. Rejects if the log refuses; the caller must then not forward. */
11
- authorize(predicate: AuthorizationPredicate): Promise<AuthorizationBundle>;
9
+ /**
10
+ * Applies the tool's capture rule to the whole predicate, signs the statement, appends it to the log, writes the
11
+ * bundle. Rejects if the log refuses the leaf; no bundle is written then. The predicate is the call in full; what
12
+ * is signed, written, and exported is the view.
13
+ */
14
+ issue(predicate: ReceiptPredicate, ctx?: CaptureContext): Promise<ReceiptBundle>;
15
+ /** The same for an authorization, signed and committed before a consequential call is forwarded. Rejects if the log refuses; the caller must then not forward. */
16
+ authorize(predicate: AuthorizationPredicate, ctx?: CaptureContext): Promise<AuthorizationBundle>;
12
17
  }
13
18
  export interface IssuerOptions {
14
19
  /** told about every receipt after it is written; an exporter's failure never reaches the caller */
15
20
  exporter?: ReceiptExporter | undefined;
21
+ /** private evidence: the capture rules by tool, and the key that encrypts (`captureKeyEnv`), applied here to every statement before it is signed */
22
+ capture?: {
23
+ rules?: CaptureConfig | undefined;
24
+ key?: Buffer | undefined;
25
+ } | undefined;
16
26
  }
17
27
  /** `log` is a sink, or a file path for the local log with tree heads signed by the issuer's key. */
18
28
  export declare function createIssuer(key: KeyPair, receiptsDir: string, log: string | LogSink, opts?: IssuerOptions): Issuer;
package/dist/issue.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // Signing, logging and writing a receipt. Shared by every producer: the gateway and the SDK.
2
- import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { chmodSync, lstatSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import { SALTS_DIR, saltsFileFor } from "./retention.js";
3
4
  import { join } from "node:path";
5
+ import { effectiveRule, getAt, privateView } from "./capture.js";
4
6
  import { canonicalize, dsseSign } from "./crypto.js";
5
7
  import { fileLog } from "./log-sink.js";
6
8
  import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./receipt.js";
@@ -8,22 +10,79 @@ import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./rec
8
10
  export function createIssuer(key, receiptsDir, log, opts = {}) {
9
11
  const sink = typeof log === "string" ? fileLog(log, key) : log;
10
12
  mkdirSync(receiptsDir, { recursive: true });
13
+ const view = (predicate, ctx, prior) => privateView(predicate, effectiveRule(opts.capture?.rules, predicate.tool.name, ctx?.unknownTool), opts.capture?.key, ctx, prior);
14
+ /** the salts directory, checked before anything is signed or appended, so that a problem with it costs no leaf in the log */
15
+ const saltsDir = join(receiptsDir, SALTS_DIR);
16
+ const ensureSaltsDir = () => {
17
+ if (!opts.capture?.rules)
18
+ return;
19
+ // mkdir's mode applies only to a directory it creates: one that was there keeps its own, so it is set after
20
+ mkdirSync(saltsDir, { recursive: true, mode: 0o700 });
21
+ // the directory is the issuer's own: a link left at that name would carry every salt elsewhere
22
+ if (lstatSync(saltsDir).isSymbolicLink())
23
+ throw new Error(`${saltsDir} is a symbolic link; the salts are not written through it`);
24
+ chmodSync(saltsDir, 0o700);
25
+ };
26
+ /**
27
+ * The view committed in an authorization, by receipt id, until its receipt is issued: the receipt carries the same
28
+ * commitments and salts for the parts they share. Set once the log has taken the authorization, released when the
29
+ * receipt is issued, and bounded: a call that never reaches its receipt does not keep its view for ever.
30
+ */
31
+ const committed = new Map();
32
+ /** an authorization whose receipt has not followed within this long is a call that died; its view is let go */
33
+ const COMMITTED_FOR_MS = 60 * 60 * 1000;
34
+ const COMMITTED_AT_MOST = 100_000;
35
+ /**
36
+ * The salts behind a statement's digest-only commitments, kept beside the receipts and never in them:
37
+ * `receipts/salts/<id>.json`, the owner's alone. They are what makes a disclosure possible for a value withheld
38
+ * without its value, and what a reviewer must not be handed, since with them a guess can be confirmed. An encrypted
39
+ * commitment carries its salt inside the ciphertext, so that salt is not written: the key alone recovers it.
40
+ */
41
+ const keepSalts = (v) => {
42
+ const salts = Object.fromEntries((v.predicate.capture?.withheld ?? []).filter((w) => getAt(v.predicate, w)?.$custody === "withheld").map((w) => [JSON.stringify(w), v.salts[JSON.stringify(w)]]));
43
+ if (!Object.keys(salts).length)
44
+ return;
45
+ writeFileSync(saltsFileFor(receiptsDir, v.predicate.receiptId), JSON.stringify({ receiptId: v.predicate.receiptId, salts }, null, 2), { mode: 0o600 });
46
+ };
11
47
  return {
12
48
  keyid: key.keyid,
13
49
  log: sink,
14
- async issue(predicate) {
15
- const envelope = dsseSign(RECEIPT_TYPE, buildStatement(predicate), key);
50
+ async issue(predicate, ctx) {
51
+ ensureSaltsDir();
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
+ const prior = committed.get(predicate.receiptId)?.view;
54
+ const pv = view(predicate, ctx, prior);
55
+ const v = pv.predicate;
56
+ const envelope = dsseSign(RECEIPT_TYPE, buildStatement(v), key);
16
57
  const entry = await sink.append(canonicalize(envelope));
58
+ committed.delete(predicate.receiptId);
59
+ // the salts once the log has taken the leaf: a receipt the log refused leaves nothing behind
60
+ keepSalts(pv);
17
61
  const bundle = { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion };
18
62
  writeFileSync(join(receiptsDir, `${predicate.receiptId}.json`), JSON.stringify(bundle, null, 2));
19
- // After the evidence, not before, and awaited so a process that exits right after issuing still exports.
63
+ // After the evidence, not before, and awaited so a process that exits right after issuing still exports. The
64
+ // exporter sees the view, never the full call.
20
65
  if (opts.exporter)
21
- await opts.exporter.exported(predicate, bundle).catch(() => { });
66
+ await opts.exporter.exported(v, bundle).catch(() => { });
22
67
  return bundle;
23
68
  },
24
- async authorize(predicate) {
25
- const envelope = dsseSign(RECEIPT_TYPE, buildAuthorizationStatement(predicate), key);
69
+ async authorize(predicate, ctx) {
70
+ ensureSaltsDir();
71
+ const pv = view(predicate, ctx);
72
+ const v = pv.predicate;
73
+ const envelope = dsseSign(RECEIPT_TYPE, buildAuthorizationStatement(v), key);
26
74
  const entry = await sink.append(canonicalize(envelope));
75
+ // committed: the receipt that follows shares this view; nothing is kept for an authorization the log refused
76
+ const now = Date.now();
77
+ for (const [id, c] of committed) {
78
+ if (now - c.at <= COMMITTED_FOR_MS)
79
+ break;
80
+ committed.delete(id);
81
+ }
82
+ committed.set(predicate.receiptId, { view: pv, at: now });
83
+ if (committed.size > COMMITTED_AT_MOST)
84
+ committed.delete(committed.keys().next().value);
85
+ keepSalts(pv);
27
86
  const bundle = { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion };
28
87
  // On disk in its own right: if the process dies between forwarding and the receipt, this is the evidence that the call was authorized and sent.
29
88
  writeFileSync(join(receiptsDir, `${predicate.receiptId}.authorization.json`), JSON.stringify(bundle, null, 2));
@@ -1,5 +1,5 @@
1
1
  import { type IncomingMessage, type ServerResponse } from "node:http";
2
- import { type Envelope, type KeyPair } from "./crypto.ts";
2
+ import { type Envelope, type KeyPair, type PublicKeyRef } from "./crypto.ts";
3
3
  import { type InclusionProof } from "./log.ts";
4
4
  import { type AuditEntry, type QuotaState, type LogBackend, type PostgresTenancy, type RateLimitOptions, type PolicyRecord } from "./log-store.ts";
5
5
  import { type Signer } from "./signer.ts";
@@ -27,11 +27,19 @@ export interface HttpLogOptions {
27
27
  retries?: number;
28
28
  /** how long one append may take before it counts as unreachable; default 10000. A log that accepts and never answers must not hold a call forever. */
29
29
  timeoutMs?: number;
30
+ /** the log's public keys, pinned: the tree head in every append's answer must be signed by one of them. Without them, the key document at the log's /.well-known/agent-custody-log.json is fetched on first use and pinned for the life of the sink. */
31
+ keys?: PublicKeyRef[];
32
+ /** the id the log must write into every tree head; an answer naming another log, or none, is refused */
33
+ logId?: string;
30
34
  fetch?: typeof fetch;
31
35
  }
32
36
  /**
33
37
  * A log reached over HTTP: POST <url>/append with {leaf} or {leafHash}, expecting a LogAppend back. A 429 or a 5xx
34
38
  * is retried a few times with backoff, honouring Retry-After; anything else, or the last failure, is the caller's.
39
+ *
40
+ * The answer is not taken on trust. Before it is returned, and so before a pre-committed call is forwarded, the tree
41
+ * head must verify against the log's pinned keys, name the expected log, match the proof's size, and the inclusion
42
+ * proof must place this very leaf under the signed root. A log that answers with anything else has refused the append.
35
43
  */
36
44
  export declare function httpLog(url: string, opts?: HttpLogOptions): LogSink;
37
45
  export interface LogConfig {
@@ -41,6 +49,8 @@ export interface LogConfig {
41
49
  tokenEnv?: string | undefined;
42
50
  hashOnly?: boolean | undefined;
43
51
  timeoutMs?: number | undefined;
52
+ keys?: string[] | undefined;
53
+ logId?: string | undefined;
44
54
  } | undefined;
45
55
  }
46
56
  /** The sink a config asks for: a remote log when `log` is set, otherwise the local file. */
package/dist/log-sink.js CHANGED
@@ -5,11 +5,11 @@
5
5
  // logHandler and serveLog are the other side: a reference log server over node:http, the same code a hosted log runs.
6
6
  import { timingSafeEqual } from "node:crypto";
7
7
  import { createServer } from "node:http";
8
- import { dsseSign } from "./crypto.js";
8
+ import { dsseSign, dsseVerify, loadPublicKey } from "./crypto.js";
9
9
  import { createHash } from "node:crypto";
10
- import { leafHash, MerkleLog } from "./log.js";
10
+ import { leafHash, MerkleLog, verifyInclusion } from "./log.js";
11
11
  import { fileBackend, RateLimiter } from "./log-store.js";
12
- import { localSigner } from "./signer.js";
12
+ import { fetchLogKeys, localSigner } from "./signer.js";
13
13
  import { adminRoutes } from "./log-admin.js";
14
14
  import { TREEHEAD_TYPE } from "./receipt.js";
15
15
  function signedHead(e, key, logId) {
@@ -39,12 +39,31 @@ export function fileLog(file, key) {
39
39
  /**
40
40
  * A log reached over HTTP: POST <url>/append with {leaf} or {leafHash}, expecting a LogAppend back. A 429 or a 5xx
41
41
  * is retried a few times with backoff, honouring Retry-After; anything else, or the last failure, is the caller's.
42
+ *
43
+ * The answer is not taken on trust. Before it is returned, and so before a pre-committed call is forwarded, the tree
44
+ * head must verify against the log's pinned keys, name the expected log, match the proof's size, and the inclusion
45
+ * proof must place this very leaf under the signed root. A log that answers with anything else has refused the append.
42
46
  */
43
47
  export function httpLog(url, opts = {}) {
44
48
  const f = opts.fetch ?? fetch;
45
49
  const base = url.endsWith("/") ? url : `${url}/`;
46
50
  const attempts = opts.retries ?? 3;
47
51
  const timeoutMs = opts.timeoutMs ?? 10_000;
52
+ let pinned = opts.keys?.length ? Promise.resolve(opts.keys) : null;
53
+ const keys = () => (pinned ??= fetchLogKeys(base, f).then((r) => r.keys).catch((e) => { pinned = null; throw new Error(`log ${url}: its keys could not be fetched to check the append, and none are configured: ${e instanceof Error ? e.message : String(e)}`); }));
54
+ const checked = async (entry, leaf) => {
55
+ const th = dsseVerify(entry.treeHead, await keys());
56
+ if (!th.ok || entry.treeHead.payloadType !== TREEHEAD_TYPE)
57
+ throw new Error(`log ${url} answered with a tree head that does not verify against its keys${th.ok ? " (wrong payload type)" : `: ${th.error}`}`);
58
+ const head = th.payload;
59
+ if (opts.logId !== undefined && head.log !== opts.logId)
60
+ throw new Error(`log ${url} signed a tree head for log "${head.log ?? ""}", not "${opts.logId}"`);
61
+ if (head.treeSize !== entry.inclusion.treeSize)
62
+ throw new Error(`log ${url} answered with a tree head of size ${head.treeSize} and a proof for size ${entry.inclusion.treeSize}`);
63
+ if (!verifyInclusion(leafHash(leaf), entry.inclusion, head.rootHash))
64
+ throw new Error(`log ${url} answered with an inclusion proof that does not place this leaf under the signed root`);
65
+ return entry;
66
+ };
48
67
  return {
49
68
  kind: "http",
50
69
  where: url,
@@ -70,7 +89,7 @@ export function httpLog(url, opts = {}) {
70
89
  const body = (await res.json());
71
90
  if (!body.inclusion || !body.treeHead)
72
91
  throw new Error(`log ${url} returned a malformed append result`);
73
- return body;
92
+ return checked(body, leaf);
74
93
  }
75
94
  last = `log ${url} refused the append: ${res.status} ${(await res.text()).slice(0, 200)}`;
76
95
  if (res.status !== 429 && res.status < 500)
@@ -90,7 +109,7 @@ export function openLog(cfg, key) {
90
109
  const token = cfg.log.tokenEnv ? process.env[cfg.log.tokenEnv] : undefined;
91
110
  if (cfg.log.tokenEnv && !token)
92
111
  throw new Error(`log token: environment variable ${cfg.log.tokenEnv} is not set`);
93
- return httpLog(cfg.log.url, { ...(token === undefined ? {} : { token }), ...(cfg.log.hashOnly ? { hashOnly: true } : {}), ...(cfg.log.timeoutMs ? { timeoutMs: cfg.log.timeoutMs } : {}) });
112
+ return httpLog(cfg.log.url, { ...(token === undefined ? {} : { token }), ...(cfg.log.hashOnly ? { hashOnly: true } : {}), ...(cfg.log.timeoutMs ? { timeoutMs: cfg.log.timeoutMs } : {}), ...(cfg.log.keys ? { keys: cfg.log.keys.map(loadPublicKey) } : {}), ...(cfg.log.logId ? { logId: cfg.log.logId } : {}) });
94
113
  }
95
114
  if (!cfg.logFile)
96
115
  throw new Error("config needs logFile or log.url");
package/dist/otel.js CHANGED
@@ -24,9 +24,9 @@ export function spanFor(p, bundle, serviceName) {
24
24
  ...int("agent_custody.log.leaf_index", bundle.inclusion.leafIndex),
25
25
  ...int("agent_custody.log.tree_size", bundle.inclusion.treeSize),
26
26
  ...(auth ? int("agent_custody.authorization.leaf_index", auth.inclusion.leafIndex) : []),
27
- ...int("agent_custody.consumed.count", p.consumed?.factIds.length ?? 0),
28
- ...str("agent_custody.model", p.model.id),
29
- ...str("agent_custody.session", p.session.id),
27
+ ...int("agent_custody.consumed.count", Array.isArray(p.consumed?.factIds) ? p.consumed.factIds.length : 0),
28
+ ...str("agent_custody.model", typeof p.model.id === "string" ? p.model.id : undefined),
29
+ ...str("agent_custody.session", typeof p.session.id === "string" ? p.session.id : undefined),
30
30
  ];
31
31
  return {
32
32
  resourceSpans: [
@@ -44,7 +44,8 @@ export function spanFor(p, bundle, serviceName) {
44
44
  startTimeUnixNano: start.toString(),
45
45
  endTimeUnixNano: (end > start ? end : start).toString(),
46
46
  attributes,
47
- status: status === "executed" || status === "denied" || status === "withheld" ? { code: 1 } : { code: 2, message: status === "failed" ? "the upstream reported failure" : p.execution.error ?? status },
47
+ // 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 },
48
49
  },
49
50
  ],
50
51
  },
package/dist/portal.d.ts CHANGED
@@ -56,6 +56,13 @@ export interface PortalUser {
56
56
  id: string;
57
57
  email: string;
58
58
  createdAt: string;
59
+ /** when the address was confirmed: by a verification link, or by a provider that vouched for it; null until then */
60
+ emailVerifiedAt?: string | null;
61
+ }
62
+ /** A provider sign-in whose verified email belongs to a password account that never verified its address: refused, never linked (issue #103). */
63
+ export declare class UnverifiedAccountError extends Error {
64
+ email: string;
65
+ constructor(email: string);
59
66
  }
60
67
  /** Users, memberships, and billing records, beside the log's tables. */
61
68
  /** What a registration says about the person and the organisation; every field optional in the store, the route decides what it requires. */
@@ -76,6 +83,11 @@ export declare class PortalStore {
76
83
  static checkPassword(password: string, stored: string): boolean;
77
84
  createUser(email: string, password: string, profile?: Profile): Promise<PortalUser>;
78
85
  userByEmail(email: string): Promise<PortalUser | null>;
86
+ private static asUser;
87
+ markEmailVerified(userId: string, at?: Date): Promise<void>;
88
+ /** Links a provider identity to a signed-in account: the account proved itself with its session, so the provider's email need not match. */
89
+ linkIdentity(provider: string, subject: string, email: string, userId: string): Promise<void>;
90
+ identities(userId: string): Promise<string[]>;
79
91
  /** the account's profile, for the onboarding screen and the operator's note */
80
92
  profile(userId: string): Promise<Profile>;
81
93
  /** Accounts with a tenant, a name, and no founder's note yet, registered inside the window: the hourly job's work list. */
@@ -94,8 +106,11 @@ export declare class PortalStore {
94
106
  markFollowedUp(userId: string, at?: Date): Promise<void>;
95
107
  updateProfile(userId: string, profile: Profile): Promise<void>;
96
108
  /**
97
- * The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
98
- * now on), else a new account with a random password nobody knows. The provider's email must be verified.
109
+ * The account behind a provider sign-in: the linked one; else the account with that email, linked from now on, but
110
+ * only if that account has verified its address (otherwise anyone could register a victim's address with a
111
+ * password, wait for the victim to sign in with Google, and keep password access to the merged account: issue
112
+ * #103; the refusal is UnverifiedAccountError); else a new account with a random password nobody knows, its address
113
+ * counted as verified because the provider vouched for it. The provider's email must be verified.
99
114
  */
100
115
  findOrCreateOAuthUser(provider: string, subject: string, email: string): Promise<PortalUser>;
101
116
  authenticate(email: string, password: string): Promise<PortalUser | null>;
@@ -107,12 +122,18 @@ export declare class PortalStore {
107
122
  customerId?: string | null;
108
123
  subscriptionId?: string | null;
109
124
  status: string;
125
+ eventCreated?: number;
110
126
  }): Promise<void>;
111
127
  billing(tenantId: string): Promise<{
112
128
  customerId: string | null;
113
129
  subscriptionId: string | null;
114
130
  status: string;
131
+ eventCreated: number | null;
115
132
  } | null>;
133
+ /** Has this Stripe event id been applied already? */
134
+ stripeEventSeen(id: string): Promise<boolean>;
135
+ /** Records a Stripe event id as applied, after it was applied, so a failure before this point lets Stripe's retry through. */
136
+ noteStripeEvent(id: string): Promise<void>;
116
137
  /** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. */
117
138
  registrations(): Promise<({
118
139
  tenantId: string;