@agent-custody/receipts 0.16.9 → 0.16.11

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 (68) hide show
  1. package/README.md +24 -9
  2. package/dist/approval-requests.d.ts +114 -0
  3. package/dist/approval-requests.js +198 -0
  4. package/dist/approval.d.ts +8 -0
  5. package/dist/approval.js +10 -3
  6. package/dist/check.js +2 -0
  7. package/dist/cli.js +96 -16
  8. package/dist/completeness.d.ts +28 -2
  9. package/dist/completeness.js +102 -9
  10. package/dist/config.d.ts +3 -0
  11. package/dist/config.js +6 -1
  12. package/dist/console-page.js +87 -2
  13. package/dist/console.js +72 -0
  14. package/dist/crypto.d.ts +2 -0
  15. package/dist/crypto.js +2 -1
  16. package/dist/delegation.d.ts +1 -1
  17. package/dist/delegation.js +19 -2
  18. package/dist/did-key.d.ts +11 -0
  19. package/dist/did-key.js +86 -0
  20. package/dist/door-app.d.ts +3 -0
  21. package/dist/door-app.js +10 -0
  22. package/dist/door-core.d.ts +373 -0
  23. package/dist/door-core.js +743 -0
  24. package/dist/door-form.d.ts +6 -0
  25. package/dist/door-form.js +97 -0
  26. package/dist/door-worker.d.ts +133 -0
  27. package/dist/door-worker.js +259 -0
  28. package/dist/door.d.ts +18 -294
  29. package/dist/door.js +62 -722
  30. package/dist/gateway-http.d.ts +1 -6
  31. package/dist/gateway-http.js +2 -19
  32. package/dist/gateway.js +24 -3
  33. package/dist/grant-header.d.ts +8 -0
  34. package/dist/grant-header.js +19 -0
  35. package/dist/index.d.ts +7 -4
  36. package/dist/index.js +5 -2
  37. package/dist/issue.d.ts +2 -16
  38. package/dist/issue.js +2 -12
  39. package/dist/log-http.d.ts +37 -0
  40. package/dist/log-http.js +74 -0
  41. package/dist/log-sink.d.ts +3 -37
  42. package/dist/log-sink.js +5 -71
  43. package/dist/log.d.ts +2 -27
  44. package/dist/log.js +2 -173
  45. package/dist/merkle.d.ts +27 -0
  46. package/dist/merkle.js +175 -0
  47. package/dist/object-issuer.d.ts +29 -0
  48. package/dist/object-issuer.js +172 -0
  49. package/dist/receipt-pending.d.ts +16 -0
  50. package/dist/receipt-pending.js +14 -0
  51. package/dist/web-bot-auth.d.ts +26 -6
  52. package/dist/web-bot-auth.js +116 -56
  53. package/docs/approvals.md +33 -0
  54. package/docs/completeness.md +82 -12
  55. package/docs/console.md +11 -4
  56. package/docs/door-middleware.md +11 -0
  57. package/docs/door-quickstart.md +53 -17
  58. package/docs/door-signals.md +5 -5
  59. package/docs/door-worker.md +81 -0
  60. package/docs/door.md +38 -8
  61. package/docs/github-action.md +2 -2
  62. package/docs/threat-model.md +1 -1
  63. package/docs/tutorials.md +5 -0
  64. package/docs/verification.md +1 -1
  65. package/package.json +3 -1
  66. package/vectors/audit.json +27 -27
  67. package/vectors/canonical.json +5 -5
  68. package/vectors/receipts.json +1645 -1549
package/dist/console.js CHANGED
@@ -8,6 +8,8 @@ import { createHash, timingSafeEqual } from "node:crypto";
8
8
  import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
9
9
  import { createServer } from "node:http";
10
10
  import { basename, dirname, join } from "node:path";
11
+ import { DEFAULT_APPROVAL_LIFETIME_SECONDS } from "./approval.js";
12
+ import { approvalRequestPayload, denyApprovalRequest, listApprovalRequests, signApprovalRequest } from "./approval-requests.js";
11
13
  import { checkConfig } from "./check.js";
12
14
  import { loadConfig } from "./config.js";
13
15
  import { loadPrivateKey, loadPublicKey } from "./crypto.js";
@@ -425,6 +427,54 @@ export async function serveConsole(options) {
425
427
  audit("grant.revoke", { agent: decoded.agent, principal: decoded.principal, digest, already: list.includes(digest) }, by);
426
428
  return { digest, agent: decoded.agent, note: "the gateway refuses this grant, and every grant delegated from it, on its next call" };
427
429
  },
430
+ "GET /api/approvals": async () => {
431
+ const cfg = loadConfig(options.configFile);
432
+ const dir = cfg.approvals?.requests?.dir;
433
+ if (!dir)
434
+ return { configured: false };
435
+ const all = listApprovalRequests(dir);
436
+ const shown = [...all.filter((r) => r.status === "pending"), ...all.filter((r) => r.status !== "pending").reverse().slice(0, 50)];
437
+ return {
438
+ configured: true,
439
+ maxLifetimeSeconds: cfg.approvals.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS,
440
+ trustedKeyids: approverKeys(cfg).map((k) => k.keyid),
441
+ requests: shown.map((r) => ({
442
+ requestId: r.requestId, status: r.status, createdAt: r.createdAt, decidedAt: r.decidedAt ?? null, receiptId: r.receiptId,
443
+ principal: r.binding.principal, agent: r.binding.agent, tool: r.binding.tool, arguments: r.binding.args, fields: r.binding.fields ?? null,
444
+ requiredApprovers: r.requiredApprovers, signedBy: r.envelope?.signatures.map((s) => s.keyid) ?? [], reason: r.reason ?? null,
445
+ })),
446
+ };
447
+ },
448
+ // The console signs nothing: the browser signs these bytes with the approver's key, which never reaches the server.
449
+ "POST /api/approvals/prepare": async (req) => {
450
+ const body = object(await readBody(req));
451
+ const { dir, cfg } = requestsDir();
452
+ const max = cfg.approvals.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS;
453
+ const seconds = body.expiresInSeconds;
454
+ if (typeof seconds !== "number" || !Number.isInteger(seconds) || seconds <= 0 || seconds > max)
455
+ throw new HttpError(400, `expiresInSeconds is a whole number of seconds from 1 to ${max}, the gateway's approvals.maxLifetimeSeconds`);
456
+ return decided(() => approvalRequestPayload(dir, requestIdOf(body), { expiresAt: new Date(Date.now() + seconds * 1000).toISOString() }));
457
+ },
458
+ "POST /api/approvals/sign": async (req, _url, by) => {
459
+ const body = object(await readBody(req));
460
+ const { dir, cfg } = requestsDir();
461
+ const requestId = requestIdOf(body);
462
+ for (const f of ["payload", "keyid", "sig"])
463
+ if (typeof body[f] !== "string" || !body[f])
464
+ throw new HttpError(400, `send ${f} as a string`);
465
+ const r = decided(() => signApprovalRequest(dir, requestId, { payload: body.payload, keyid: body.keyid, sig: body.sig }, approverKeys(cfg), { maxLifetimeSeconds: cfg.approvals.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS }));
466
+ audit("approval.sign", { requestId, agent: r.binding.agent, tool: r.binding.tool, keyid: body.keyid, status: r.status }, by);
467
+ return { status: r.status, note: r.status === "approved" ? `Approved. ${r.binding.agent} may send ${r.binding.tool} with exactly these arguments, once.` : "Signed. It needs a second approver with a different key." };
468
+ },
469
+ "POST /api/approvals/deny": async (req, _url, by) => {
470
+ const body = object(await readBody(req));
471
+ const { dir } = requestsDir();
472
+ const requestId = requestIdOf(body);
473
+ const reason = typeof body.reason === "string" && body.reason.trim() ? body.reason.trim() : undefined;
474
+ const r = decided(() => denyApprovalRequest(dir, requestId, reason ? { reason } : {}));
475
+ audit("approval.deny", { requestId, agent: r.binding.agent, tool: r.binding.tool, ...(reason ? { reason } : {}) }, by);
476
+ return { status: r.status, note: "Denied. The gateway refuses that exact call, and tells the agent so, until the request is deleted." };
477
+ },
428
478
  "GET /api/revocations": async () => ({ digests: revokedList(loadConfig(options.configFile)) }),
429
479
  "GET /api/receipts": async (_req, url) => {
430
480
  const cfg = loadConfig(options.configFile);
@@ -437,6 +487,28 @@ export async function serveConsole(options) {
437
487
  entries: existsSync(auditFile) ? readFileSync(auditFile, "utf8").trim().split("\n").filter(Boolean).slice(-200).reverse().map((l) => JSON.parse(l)) : [],
438
488
  }),
439
489
  };
490
+ const approverKeys = (cfg) => (cfg.approvals?.trustedKeys ?? []).map(loadPublicKey);
491
+ const requestsDir = () => {
492
+ const cfg = loadConfig(options.configFile);
493
+ const dir = cfg.approvals?.requests?.dir;
494
+ if (!dir)
495
+ throw new HttpError(409, "the config has no approvals.requests.dir, which is where the gateway leaves approval requests");
496
+ return { dir, cfg };
497
+ };
498
+ const requestIdOf = (body) => {
499
+ if (typeof body.requestId !== "string" || !/^[0-9a-f]{32}$/.test(body.requestId))
500
+ throw new HttpError(400, "a request id is 32 hex characters");
501
+ return body.requestId;
502
+ };
503
+ // a request that is gone, already decided, or a signature that does not verify is the caller's conflict, not a crash
504
+ const decided = (f) => {
505
+ try {
506
+ return f();
507
+ }
508
+ catch (e) {
509
+ throw new HttpError(409, e instanceof Error ? e.message : String(e));
510
+ }
511
+ };
440
512
  const safeJson = (s) => {
441
513
  try {
442
514
  return JSON.parse(s);
package/dist/crypto.d.ts CHANGED
@@ -33,6 +33,8 @@ export interface Envelope {
33
33
  sig: string;
34
34
  }[];
35
35
  }
36
+ /** The DSSE pre-authentication encoding: the bytes a DSSE signature is made over. */
37
+ export declare function pae(payloadType: string, payload: Buffer): Buffer;
36
38
  export declare function dsseSign(payloadType: string, payloadObj: unknown, kp: KeyPair): Envelope;
37
39
  /** Adds a signature over the same payload: a countersignature, the DSSE way. The envelope keeps every earlier signature. */
38
40
  export declare function dsseCountersign(env: Envelope, kp: KeyPair): Envelope;
package/dist/crypto.js CHANGED
@@ -64,7 +64,8 @@ export function publicKeyFromPem(pem) {
64
64
  const publicKey = createPublicKey(pem);
65
65
  return { publicKey, keyid: keyidOf(publicKey) };
66
66
  }
67
- function pae(payloadType, payload) {
67
+ /** The DSSE pre-authentication encoding: the bytes a DSSE signature is made over. */
68
+ export function pae(payloadType, payload) {
68
69
  const header = `DSSEv1 ${Buffer.byteLength(payloadType)} ${payloadType} ${payload.length} `;
69
70
  return Buffer.concat([Buffer.from(header), payload]);
70
71
  }
@@ -52,7 +52,7 @@ export type DelegationVerifyResult = {
52
52
  error: string;
53
53
  };
54
54
  /** Verifies a grant, walking its chain to a grant signed by one of the trusted principal keys. */
55
- export declare function verifyDelegation(env: Envelope, trustedPrincipals: PublicKeyRef[], depth?: number): DelegationVerifyResult;
55
+ export declare function verifyDelegation(env: Envelope, trustedPrincipals: PublicKeyRef[]): DelegationVerifyResult;
56
56
  /** True when `at` (ISO) lies inside the grant's validity window. */
57
57
  /**
58
58
  * What names a grant for revocation: sha256 over the payload its signature covers. Extra signatures or envelope fields
@@ -6,6 +6,7 @@
6
6
  // parent's, and the principal is the same throughout. The receipt then names the sub-agent as the agent and the
7
7
  // principal as the principal, exactly as with a direct grant, and the whole chain travels inside the receipt.
8
8
  import { z } from "zod";
9
+ import { DID_KEY_PREFIX, didKeyAgentFault } from "./did-key.js";
9
10
  import { dsseSign, dsseVerify, publicKeyFromPem, sha256Hex } from "./crypto.js";
10
11
  export const DELEGATION_TYPE = "application/vnd.agent-custody.delegation+json";
11
12
  /** the longest chain a verifier walks: the principal's grant and up to three delegations below it */
@@ -68,7 +69,23 @@ export function delegateFrom(parent, agentKey, sub) {
68
69
  return createDelegation(agentKey, { version: "0.1", principal: p.principal, agent: sub.agent, scopes: sub.scopes, issuedAt, expiresAt, ...(sub.agentKey ? { agentKey: sub.agentKey } : {}), parent });
69
70
  }
70
71
  /** Verifies a grant, walking its chain to a grant signed by one of the trusted principal keys. */
71
- export function verifyDelegation(env, trustedPrincipals, depth = 1) {
72
+ export function verifyDelegation(env, trustedPrincipals) {
73
+ const checked = verifyChain(env, trustedPrincipals, 1);
74
+ if (!checked.ok)
75
+ return checked;
76
+ // An agent named by a did:key is its key: the identifier must decode to an Ed25519 key, and the grant's agentKey, if
77
+ // it names one, must be that key, or the grant says two things about who the agent is. Every link of a chain, since a
78
+ // parent's agentKey is what verified the link below it.
79
+ for (const [i, link] of checked.chain.entries()) {
80
+ if (!link.agent.startsWith(DID_KEY_PREFIX))
81
+ continue;
82
+ const fault = didKeyAgentFault(link.agent, link.agentKey);
83
+ if (fault)
84
+ return { ok: false, error: (i === checked.chain.length - 1 ? "" : `link ${i} (${link.agent}): `) + fault };
85
+ }
86
+ return checked;
87
+ }
88
+ function verifyChain(env, trustedPrincipals, depth) {
72
89
  if (env.payloadType !== DELEGATION_TYPE)
73
90
  return { ok: false, error: `unexpected payloadType ${env.payloadType}` };
74
91
  if (depth > MAX_DELEGATION_DEPTH)
@@ -85,7 +102,7 @@ export function verifyDelegation(env, trustedPrincipals, depth = 1) {
85
102
  return { ok: false, error: `invalid delegation: ${parsed.error.message}` };
86
103
  return { ok: true, delegation: parsed.data, keyid: r.keyid, chain: [parsed.data] };
87
104
  }
88
- const up = verifyDelegation(unverified.parent, trustedPrincipals, depth + 1);
105
+ const up = verifyChain(unverified.parent, trustedPrincipals, depth + 1);
89
106
  if (!up.ok)
90
107
  return { ok: false, error: `link ${depth}: ${up.error}` };
91
108
  const parent = up.delegation;
@@ -0,0 +1,11 @@
1
+ import { type KeyObject } from "node:crypto";
2
+ import { type PublicKeyRef } from "./crypto.ts";
3
+ export declare const DID_KEY_PREFIX = "did:key:";
4
+ export declare function base58btcEncode(bytes: Uint8Array): string;
5
+ export declare function base58btcDecode(text: string): Uint8Array;
6
+ /** The did:key of an Ed25519 public key. */
7
+ export declare function didKeyOf(publicKey: KeyObject): string;
8
+ /** The Ed25519 key a did:key names; throws, saying why, when it does not decode to one. */
9
+ export declare function publicKeyFromDidKey(did: string): PublicKeyRef;
10
+ /** Why a did:key agent does not check out, or null when it decodes and agrees with the grant's agentKey. */
11
+ export declare function didKeyAgentFault(did: string, agentKey: string | undefined): string | null;
@@ -0,0 +1,86 @@
1
+ // did:key identifiers for Ed25519 keys (W3C CCG did:key method): "did:key:z" followed by the base58btc encoding of the
2
+ // multicodec prefix for ed25519-pub (0xed 0x01) and the 32-byte public key. The identifier is the key: anyone can
3
+ // derive the key from it, and nothing about it says who holds the key or whether a principal trusts it.
4
+ import { createPublicKey } from "node:crypto";
5
+ import { keyidOf, publicKeyFromPem } from "./crypto.js";
6
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
7
+ const ED25519_PUB = [0xed, 0x01];
8
+ export const DID_KEY_PREFIX = "did:key:";
9
+ export function base58btcEncode(bytes) {
10
+ let n = 0n;
11
+ for (const b of bytes)
12
+ n = n * 256n + BigInt(b);
13
+ let out = "";
14
+ while (n > 0n) {
15
+ out = ALPHABET[Number(n % 58n)] + out;
16
+ n /= 58n;
17
+ }
18
+ for (const b of bytes) {
19
+ if (b !== 0)
20
+ break;
21
+ out = "1" + out;
22
+ }
23
+ return out;
24
+ }
25
+ export function base58btcDecode(text) {
26
+ let n = 0n;
27
+ for (const ch of text) {
28
+ const v = ALPHABET.indexOf(ch);
29
+ if (v < 0)
30
+ throw new Error(`"${ch}" is not a base58btc character`);
31
+ n = n * 58n + BigInt(v);
32
+ }
33
+ const bytes = [];
34
+ while (n > 0n) {
35
+ bytes.unshift(Number(n % 256n));
36
+ n /= 256n;
37
+ }
38
+ for (const ch of text) {
39
+ if (ch !== "1")
40
+ break;
41
+ bytes.unshift(0);
42
+ }
43
+ return Uint8Array.from(bytes);
44
+ }
45
+ /** The did:key of an Ed25519 public key. */
46
+ export function didKeyOf(publicKey) {
47
+ if (publicKey.asymmetricKeyType !== "ed25519")
48
+ throw new Error(`did:key here is for Ed25519 keys; got ${publicKey.asymmetricKeyType}`);
49
+ const raw = Buffer.from(publicKey.export({ format: "jwk" }).x, "base64url");
50
+ return `${DID_KEY_PREFIX}z${base58btcEncode(Uint8Array.from([...ED25519_PUB, ...raw]))}`;
51
+ }
52
+ /** The Ed25519 key a did:key names; throws, saying why, when it does not decode to one. */
53
+ export function publicKeyFromDidKey(did) {
54
+ // an Ed25519 did:key is 56 characters; the decode is quadratic, so a much longer one is refused before it
55
+ if (did.length > 100)
56
+ throw new Error(`the did:key is ${did.length} characters; an Ed25519 did:key is 56`);
57
+ if (!did.startsWith(`${DID_KEY_PREFIX}z`))
58
+ throw new Error(`"${did.slice(0, 40)}" is not a base58btc did:key (did:key:z...)`);
59
+ const bytes = base58btcDecode(did.slice(DID_KEY_PREFIX.length + 1));
60
+ if (bytes[0] !== ED25519_PUB[0] || bytes[1] !== ED25519_PUB[1])
61
+ throw new Error("the did:key does not name an Ed25519 key (multicodec 0xed01)");
62
+ if (bytes.length !== 34)
63
+ throw new Error(`the did:key's Ed25519 key is ${bytes.length - 2} bytes, not 32`);
64
+ const publicKey = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: Buffer.from(bytes.subarray(2)).toString("base64url") }, format: "jwk" });
65
+ return { publicKey, keyid: keyidOf(publicKey) };
66
+ }
67
+ /** Why a did:key agent does not check out, or null when it decodes and agrees with the grant's agentKey. */
68
+ export function didKeyAgentFault(did, agentKey) {
69
+ let named;
70
+ try {
71
+ named = publicKeyFromDidKey(did);
72
+ }
73
+ catch (e) {
74
+ return `the grant's did:key agent does not decode: ${e instanceof Error ? e.message : String(e)}`;
75
+ }
76
+ if (agentKey === undefined)
77
+ return null;
78
+ try {
79
+ if (publicKeyFromPem(agentKey).keyid === named.keyid)
80
+ return null;
81
+ }
82
+ catch {
83
+ return "the grant's agentKey is not a public key";
84
+ }
85
+ return "the grant's agentKey is not the key its did:key agent names";
86
+ }
@@ -2,6 +2,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  import { type DoorConfig } from "./config.ts";
3
3
  import { type DoorOptions } from "./door.ts";
4
4
  import type { FlushResult } from "./issue.ts";
5
+ export { FORM_SCRIPT_PATH, formScript } from "./door-form.ts";
5
6
  /** The receipt's `issuer.framework` for an arrival the middleware decided */
6
7
  export declare const MIDDLEWARE_FRAMEWORK = "node-middleware";
7
8
  /** The receipt's `issuer.framework` for an arrival a wrapped route handler decided */
@@ -19,6 +20,8 @@ export interface InProcessDoor {
19
20
  policyDigest(): string;
20
21
  flushOutbox(): Promise<FlushResult>;
21
22
  pendingReceipts(): number;
23
+ /** the form protector script for the config's challenge, or null without one; the middleware serves it at FORM_SCRIPT_PATH */
24
+ formScript(): string | null;
22
25
  close(): void;
23
26
  }
24
27
  /**
package/dist/door-app.js CHANGED
@@ -8,6 +8,8 @@ import { Readable } from "node:stream";
8
8
  import { loadDoorConfig } from "./config.js";
9
9
  import { digestOf } from "./crypto.js";
10
10
  import { CLASS_HEADER, RECEIPT_HEADER, createDoorCore, readBody, readStream, sendAnswer } from "./door.js";
11
+ import { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
12
+ export { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
11
13
  /** The receipt's `issuer.framework` for an arrival the middleware decided */
12
14
  export const MIDDLEWARE_FRAMEWORK = "node-middleware";
13
15
  /** The receipt's `issuer.framework` for an arrival a wrapped route handler decided */
@@ -111,7 +113,14 @@ export function door(config, options = {}) {
111
113
  if (cfg.authz)
112
114
  throw new Error("the in-process door passes an allowed request to the app it runs in; authz is for the door answering nginx or Envoy checks (`agent-custody door`)");
113
115
  const core = createDoorCore(cfg, { ...options, autoFlush: options.autoFlush ?? true }, MIDDLEWARE_FRAMEWORK);
116
+ const script = cfg.challenge ? formScript(cfg.challenge) : null;
114
117
  const middleware = (req, res, next) => {
118
+ // the script is public and the same for every arrival: served, not decided or receipted
119
+ if (script && req.method === "GET" && (req.url ?? "").split("?")[0] === FORM_SCRIPT_PATH) {
120
+ res.writeHead(200, { "content-type": "text/javascript; charset=utf-8", "cache-control": "public, max-age=300", "x-content-type-options": "nosniff" });
121
+ res.end(script);
122
+ return;
123
+ }
115
124
  if (!core.admit()) {
116
125
  req.resume();
117
126
  return sendAnswer(res, core.busy());
@@ -239,6 +248,7 @@ export function door(config, options = {}) {
239
248
  policyDigest: core.policyDigest,
240
249
  flushOutbox: core.flushOutbox,
241
250
  pendingReceipts: core.pendingReceipts,
251
+ formScript: () => script,
242
252
  close: core.close,
243
253
  });
244
254
  }