@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/log.js CHANGED
@@ -1,181 +1,10 @@
1
1
  // Append-only Merkle log with RFC 6962 / RFC 9162 hashing and inclusion proofs.
2
2
  // Leaves are stored as JSONL so anyone holding the file can recompute the root.
3
- import { createHash } from "node:crypto";
4
3
  import { appendFileSync, closeSync, fstatSync, mkdirSync, openSync, readSync, statSync, truncateSync, writeSync } from "node:fs";
5
4
  import { dirname } from "node:path";
6
5
  import { withLock } from "./lock.js";
7
- const h = (...parts) => {
8
- const c = createHash("sha256");
9
- for (const p of parts)
10
- c.update(p);
11
- return c.digest();
12
- };
13
- export function leafHash(data) {
14
- return h(Buffer.from([0x00]), Buffer.from(data));
15
- }
16
- const nodeHash = (l, r) => h(Buffer.from([0x01]), l, r);
17
- // Every hash a proof check reads is 32 bytes: a proof hash and a root are each a string of 64 lowercase hex digits, as
18
- // the Python verifier requires. Checked before the loop: with children of other widths, sha256(0x01 || left || right)
19
- // no longer fixes where one child ends and the other begins.
20
- const HASH_HEX = /^[0-9a-f]{64}$/;
21
- const isHash = (x) => typeof x === "string" && HASH_HEX.test(x);
22
- const EMPTY_ROOT = createHash("sha256").digest("hex");
23
- // Sizes and indices are integers. The loops halve them with Math.floor, so a fraction such as 6.5 can walk a real path.
24
- const isSize = (n) => Number.isSafeInteger(n) && n >= 0;
25
- /** n is a power of two. Exact for every safe integer: `(n & (n - 1)) === 0` reads only the low 32 bits of n. */
26
- function isPowerOfTwo(n) {
27
- let k = 1;
28
- while (k < n)
29
- k *= 2;
30
- return k === n;
31
- }
32
- /** largest power of two strictly less than n (n >= 2) */
33
- function split(n) {
34
- let k = 1;
35
- while (k * 2 < n)
36
- k *= 2;
37
- return k;
38
- }
39
- /**
40
- * Subtree hashes over a growing list of leaves. A subtree over an aligned, complete, power-of-two range never changes
41
- * once its leaves exist, so those are cached; everything else is recomputed from at most log(n) cached parts. That
42
- * makes appends, roots, and proofs O(log n) instead of O(n), which is what keeps a long session's receipts cheap.
43
- */
44
- export class SubtreeCache {
45
- perfect = new Map();
46
- leaves;
47
- constructor(leaves) {
48
- this.leaves = leaves;
49
- }
50
- mth(lo, hi) {
51
- const n = hi - lo;
52
- if (n === 0)
53
- return createHash("sha256").digest();
54
- if (n === 1)
55
- return this.leaves[lo];
56
- const aligned = (n & (n - 1)) === 0 && lo % n === 0;
57
- const key = aligned ? `${lo}:${hi}` : "";
58
- if (aligned) {
59
- const hit = this.perfect.get(key);
60
- if (hit)
61
- return hit;
62
- }
63
- const k = split(n);
64
- const h = nodeHash(this.mth(lo, lo + k), this.mth(lo + k, hi));
65
- if (aligned)
66
- this.perfect.set(key, h);
67
- return h;
68
- }
69
- path(m, lo, hi) {
70
- const n = hi - lo;
71
- if (n <= 1)
72
- return [];
73
- const k = split(n);
74
- return m < k ? [...this.path(m, lo, lo + k), this.mth(lo + k, hi)] : [...this.path(m - k, lo + k, hi), this.mth(lo, lo + k)];
75
- }
76
- subproof(m, lo, hi, b) {
77
- const n = hi - lo;
78
- if (m === n)
79
- return b ? [] : [this.mth(lo, hi)];
80
- const k = split(n);
81
- return m <= k ? [...this.subproof(m, lo, lo + k, b), this.mth(lo + k, hi)] : [...this.subproof(m - k, lo + k, hi, false), this.mth(lo, lo + k)];
82
- }
83
- }
84
- const mth = (leaves, lo, hi) => new SubtreeCache(leaves).mth(lo, hi);
85
- const path = (m, leaves, lo, hi) => new SubtreeCache(leaves).path(m, lo, hi);
86
- /** RFC 9162 section 2.1.4.1: SUBPROOF(m, D[n], b). */
87
- const subproof = (m, leaves, lo, hi, b) => new SubtreeCache(leaves).subproof(m, lo, hi, b);
88
- /** Proof that the tree of size newSize extends the tree of size oldSize. Empty when oldSize is 0 or equal to newSize. */
89
- export function consistencyProof(leafHashes, oldSize, newSize = leafHashes.length) {
90
- if (oldSize < 0 || oldSize > newSize || newSize > leafHashes.length)
91
- throw new Error("sizes out of range");
92
- if (oldSize === 0 || oldSize === newSize)
93
- return [];
94
- return subproof(oldSize, leafHashes, 0, newSize, true).map((b) => b.toString("hex"));
95
- }
96
- /** RFC 9162 section 2.1.4.2. Pure: needs only the two sizes, the two roots, and the proof. */
97
- export function verifyConsistency(oldSize, oldRoot, newSize, newRoot, proofHex) {
98
- if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize)
99
- return false;
100
- if (!isHash(oldRoot) || !isHash(newRoot) || !Array.isArray(proofHex) || !proofHex.every(isHash))
101
- return false;
102
- // the empty tree has one root, sha256 of nothing; any other root at size 0, old or new, is a head no log could have signed
103
- if (oldSize === 0)
104
- return proofHex.length === 0 && oldRoot === EMPTY_ROOT && (newSize > 0 || newRoot === EMPTY_ROOT);
105
- if (oldSize === newSize)
106
- return proofHex.length === 0 && oldRoot === newRoot;
107
- if (proofHex.length === 0)
108
- return false;
109
- const proof = proofHex.map((x) => Buffer.from(x, "hex"));
110
- if (isPowerOfTwo(oldSize))
111
- proof.unshift(Buffer.from(oldRoot, "hex"));
112
- let fn = oldSize - 1;
113
- let sn = newSize - 1;
114
- while (fn % 2 === 1) {
115
- fn = Math.floor(fn / 2);
116
- sn = Math.floor(sn / 2);
117
- }
118
- let fr = proof[0];
119
- let sr = proof[0];
120
- for (const c of proof.slice(1)) {
121
- if (sn === 0)
122
- return false;
123
- if (fn % 2 === 1 || fn === sn) {
124
- fr = nodeHash(c, fr);
125
- sr = nodeHash(c, sr);
126
- while (fn % 2 === 0 && fn !== 0) {
127
- fn = Math.floor(fn / 2);
128
- sn = Math.floor(sn / 2);
129
- }
130
- }
131
- else {
132
- sr = nodeHash(sr, c);
133
- }
134
- fn = Math.floor(fn / 2);
135
- sn = Math.floor(sn / 2);
136
- }
137
- return sn === 0 && fr.toString("hex") === oldRoot && sr.toString("hex") === newRoot;
138
- }
139
- export function rootOf(leafHashes, size = leafHashes.length) {
140
- return mth(leafHashes, 0, size).toString("hex");
141
- }
142
- export function inclusionProof(leafHashes, leafIndex, treeSize = leafHashes.length) {
143
- if (leafIndex < 0 || leafIndex >= treeSize || treeSize > leafHashes.length)
144
- throw new Error("index out of range");
145
- return { leafIndex, treeSize, hashes: path(leafIndex, leafHashes, 0, treeSize).map((b) => b.toString("hex")) };
146
- }
147
- /** RFC 9162 section 2.1.3.2 verification. Pure function: needs only the leaf hash, proof and claimed root. */
148
- export function verifyInclusion(leaf, proof, rootHex) {
149
- if (!isSize(proof.leafIndex) || !isSize(proof.treeSize))
150
- return false;
151
- let fn = proof.leafIndex;
152
- let sn = proof.treeSize - 1;
153
- if (fn < 0 || sn < 0 || fn > sn)
154
- return false;
155
- if (leaf.length !== 32 || !isHash(rootHex) || !Array.isArray(proof.hashes) || !proof.hashes.every(isHash))
156
- return false;
157
- let r = leaf;
158
- for (const hex of proof.hashes) {
159
- if (sn === 0)
160
- return false;
161
- const p = Buffer.from(hex, "hex");
162
- if (fn % 2 === 1 || fn === sn) {
163
- r = nodeHash(p, r);
164
- if (fn % 2 === 0) {
165
- while (fn % 2 === 0 && fn !== 0) {
166
- fn = Math.floor(fn / 2);
167
- sn = Math.floor(sn / 2);
168
- }
169
- }
170
- }
171
- else {
172
- r = nodeHash(r, p);
173
- }
174
- fn = Math.floor(fn / 2);
175
- sn = Math.floor(sn / 2);
176
- }
177
- return sn === 0 && r.toString("hex") === rootHex;
178
- }
6
+ import { leafHash, SubtreeCache } from "./merkle.js";
7
+ export * from "./merkle.js";
179
8
  const LOCK_STALE_MS = 60_000;
180
9
  const LOG_LOCK_WAIT_MS = 20_000;
181
10
  /** Each hook of a coding agent is its own process, so appends overlap: one writer at a time holds `<file>.lock`. */
@@ -0,0 +1,27 @@
1
+ export interface InclusionProof {
2
+ leafIndex: number;
3
+ treeSize: number;
4
+ hashes: string[];
5
+ }
6
+ export declare function leafHash(data: string): Buffer;
7
+ /**
8
+ * Subtree hashes over a growing list of leaves. A subtree over an aligned, complete, power-of-two range never changes
9
+ * once its leaves exist, so those are cached; everything else is recomputed from at most log(n) cached parts. That
10
+ * makes appends, roots, and proofs O(log n) instead of O(n), which is what keeps a long session's receipts cheap.
11
+ */
12
+ export declare class SubtreeCache {
13
+ private readonly perfect;
14
+ private readonly leaves;
15
+ constructor(leaves: Buffer[]);
16
+ mth(lo: number, hi: number): Buffer;
17
+ path(m: number, lo: number, hi: number): Buffer[];
18
+ subproof(m: number, lo: number, hi: number, b: boolean): Buffer[];
19
+ }
20
+ /** Proof that the tree of size newSize extends the tree of size oldSize. Empty when oldSize is 0 or equal to newSize. */
21
+ export declare function consistencyProof(leafHashes: Buffer[], oldSize: number, newSize?: number): string[];
22
+ /** RFC 9162 section 2.1.4.2. Pure: needs only the two sizes, the two roots, and the proof. */
23
+ export declare function verifyConsistency(oldSize: number, oldRoot: string, newSize: number, newRoot: string, proofHex: string[]): boolean;
24
+ export declare function rootOf(leafHashes: Buffer[], size?: number): string;
25
+ export declare function inclusionProof(leafHashes: Buffer[], leafIndex: number, treeSize?: number): InclusionProof;
26
+ /** RFC 9162 section 2.1.3.2 verification. Pure function: needs only the leaf hash, proof and claimed root. */
27
+ export declare function verifyInclusion(leaf: Buffer, proof: InclusionProof, rootHex: string): boolean;
package/dist/merkle.js ADDED
@@ -0,0 +1,175 @@
1
+ // RFC 6962 / RFC 9162 Merkle tree hashing and proofs: pure functions, no files. The local log (log.ts) and every
2
+ // reader of a log (the HTTP sink, the verifiers) share them.
3
+ import { createHash } from "node:crypto";
4
+ const h = (...parts) => {
5
+ const c = createHash("sha256");
6
+ for (const p of parts)
7
+ c.update(p);
8
+ return c.digest();
9
+ };
10
+ export function leafHash(data) {
11
+ return h(Buffer.from([0x00]), Buffer.from(data));
12
+ }
13
+ const nodeHash = (l, r) => h(Buffer.from([0x01]), l, r);
14
+ // Every hash a proof check reads is 32 bytes: a proof hash and a root are each a string of 64 lowercase hex digits, as
15
+ // the Python verifier requires. Checked before the loop: with children of other widths, sha256(0x01 || left || right)
16
+ // no longer fixes where one child ends and the other begins.
17
+ const HASH_HEX = /^[0-9a-f]{64}$/;
18
+ const isHash = (x) => typeof x === "string" && HASH_HEX.test(x);
19
+ const EMPTY_ROOT = createHash("sha256").digest("hex");
20
+ // Sizes and indices are integers. The loops halve them with Math.floor, so a fraction such as 6.5 can walk a real path.
21
+ const isSize = (n) => Number.isSafeInteger(n) && n >= 0;
22
+ /** n is a power of two. Exact for every safe integer: `(n & (n - 1)) === 0` reads only the low 32 bits of n. */
23
+ function isPowerOfTwo(n) {
24
+ let k = 1;
25
+ while (k < n)
26
+ k *= 2;
27
+ return k === n;
28
+ }
29
+ /** largest power of two strictly less than n (n >= 2) */
30
+ function split(n) {
31
+ let k = 1;
32
+ while (k * 2 < n)
33
+ k *= 2;
34
+ return k;
35
+ }
36
+ /**
37
+ * Subtree hashes over a growing list of leaves. A subtree over an aligned, complete, power-of-two range never changes
38
+ * once its leaves exist, so those are cached; everything else is recomputed from at most log(n) cached parts. That
39
+ * makes appends, roots, and proofs O(log n) instead of O(n), which is what keeps a long session's receipts cheap.
40
+ */
41
+ export class SubtreeCache {
42
+ perfect = new Map();
43
+ leaves;
44
+ constructor(leaves) {
45
+ this.leaves = leaves;
46
+ }
47
+ mth(lo, hi) {
48
+ const n = hi - lo;
49
+ if (n === 0)
50
+ return createHash("sha256").digest();
51
+ if (n === 1)
52
+ return this.leaves[lo];
53
+ const aligned = (n & (n - 1)) === 0 && lo % n === 0;
54
+ const key = aligned ? `${lo}:${hi}` : "";
55
+ if (aligned) {
56
+ const hit = this.perfect.get(key);
57
+ if (hit)
58
+ return hit;
59
+ }
60
+ const k = split(n);
61
+ const h = nodeHash(this.mth(lo, lo + k), this.mth(lo + k, hi));
62
+ if (aligned)
63
+ this.perfect.set(key, h);
64
+ return h;
65
+ }
66
+ path(m, lo, hi) {
67
+ const n = hi - lo;
68
+ if (n <= 1)
69
+ return [];
70
+ const k = split(n);
71
+ return m < k ? [...this.path(m, lo, lo + k), this.mth(lo + k, hi)] : [...this.path(m - k, lo + k, hi), this.mth(lo, lo + k)];
72
+ }
73
+ subproof(m, lo, hi, b) {
74
+ const n = hi - lo;
75
+ if (m === n)
76
+ return b ? [] : [this.mth(lo, hi)];
77
+ const k = split(n);
78
+ return m <= k ? [...this.subproof(m, lo, lo + k, b), this.mth(lo + k, hi)] : [...this.subproof(m - k, lo + k, hi, false), this.mth(lo, lo + k)];
79
+ }
80
+ }
81
+ const mth = (leaves, lo, hi) => new SubtreeCache(leaves).mth(lo, hi);
82
+ const path = (m, leaves, lo, hi) => new SubtreeCache(leaves).path(m, lo, hi);
83
+ /** RFC 9162 section 2.1.4.1: SUBPROOF(m, D[n], b). */
84
+ const subproof = (m, leaves, lo, hi, b) => new SubtreeCache(leaves).subproof(m, lo, hi, b);
85
+ /** Proof that the tree of size newSize extends the tree of size oldSize. Empty when oldSize is 0 or equal to newSize. */
86
+ export function consistencyProof(leafHashes, oldSize, newSize = leafHashes.length) {
87
+ if (oldSize < 0 || oldSize > newSize || newSize > leafHashes.length)
88
+ throw new Error("sizes out of range");
89
+ if (oldSize === 0 || oldSize === newSize)
90
+ return [];
91
+ return subproof(oldSize, leafHashes, 0, newSize, true).map((b) => b.toString("hex"));
92
+ }
93
+ /** RFC 9162 section 2.1.4.2. Pure: needs only the two sizes, the two roots, and the proof. */
94
+ export function verifyConsistency(oldSize, oldRoot, newSize, newRoot, proofHex) {
95
+ if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize)
96
+ return false;
97
+ if (!isHash(oldRoot) || !isHash(newRoot) || !Array.isArray(proofHex) || !proofHex.every(isHash))
98
+ return false;
99
+ // the empty tree has one root, sha256 of nothing; any other root at size 0, old or new, is a head no log could have signed
100
+ if (oldSize === 0)
101
+ return proofHex.length === 0 && oldRoot === EMPTY_ROOT && (newSize > 0 || newRoot === EMPTY_ROOT);
102
+ if (oldSize === newSize)
103
+ return proofHex.length === 0 && oldRoot === newRoot;
104
+ if (proofHex.length === 0)
105
+ return false;
106
+ const proof = proofHex.map((x) => Buffer.from(x, "hex"));
107
+ if (isPowerOfTwo(oldSize))
108
+ proof.unshift(Buffer.from(oldRoot, "hex"));
109
+ let fn = oldSize - 1;
110
+ let sn = newSize - 1;
111
+ while (fn % 2 === 1) {
112
+ fn = Math.floor(fn / 2);
113
+ sn = Math.floor(sn / 2);
114
+ }
115
+ let fr = proof[0];
116
+ let sr = proof[0];
117
+ for (const c of proof.slice(1)) {
118
+ if (sn === 0)
119
+ return false;
120
+ if (fn % 2 === 1 || fn === sn) {
121
+ fr = nodeHash(c, fr);
122
+ sr = nodeHash(c, sr);
123
+ while (fn % 2 === 0 && fn !== 0) {
124
+ fn = Math.floor(fn / 2);
125
+ sn = Math.floor(sn / 2);
126
+ }
127
+ }
128
+ else {
129
+ sr = nodeHash(sr, c);
130
+ }
131
+ fn = Math.floor(fn / 2);
132
+ sn = Math.floor(sn / 2);
133
+ }
134
+ return sn === 0 && fr.toString("hex") === oldRoot && sr.toString("hex") === newRoot;
135
+ }
136
+ export function rootOf(leafHashes, size = leafHashes.length) {
137
+ return mth(leafHashes, 0, size).toString("hex");
138
+ }
139
+ export function inclusionProof(leafHashes, leafIndex, treeSize = leafHashes.length) {
140
+ if (leafIndex < 0 || leafIndex >= treeSize || treeSize > leafHashes.length)
141
+ throw new Error("index out of range");
142
+ return { leafIndex, treeSize, hashes: path(leafIndex, leafHashes, 0, treeSize).map((b) => b.toString("hex")) };
143
+ }
144
+ /** RFC 9162 section 2.1.3.2 verification. Pure function: needs only the leaf hash, proof and claimed root. */
145
+ export function verifyInclusion(leaf, proof, rootHex) {
146
+ if (!isSize(proof.leafIndex) || !isSize(proof.treeSize))
147
+ return false;
148
+ let fn = proof.leafIndex;
149
+ let sn = proof.treeSize - 1;
150
+ if (fn < 0 || sn < 0 || fn > sn)
151
+ return false;
152
+ if (leaf.length !== 32 || !isHash(rootHex) || !Array.isArray(proof.hashes) || !proof.hashes.every(isHash))
153
+ return false;
154
+ let r = leaf;
155
+ for (const hex of proof.hashes) {
156
+ if (sn === 0)
157
+ return false;
158
+ const p = Buffer.from(hex, "hex");
159
+ if (fn % 2 === 1 || fn === sn) {
160
+ r = nodeHash(p, r);
161
+ if (fn % 2 === 0) {
162
+ while (fn % 2 === 0 && fn !== 0) {
163
+ fn = Math.floor(fn / 2);
164
+ sn = Math.floor(sn / 2);
165
+ }
166
+ }
167
+ }
168
+ else {
169
+ r = nodeHash(r, p);
170
+ }
171
+ fn = Math.floor(fn / 2);
172
+ sn = Math.floor(sn / 2);
173
+ }
174
+ return sn === 0 && r.toString("hex") === rootHex;
175
+ }
@@ -0,0 +1,29 @@
1
+ import { type CaptureConfig } from "./capture.ts";
2
+ import { type KeyPair } from "./crypto.ts";
3
+ import type { Issuer } from "./issue.ts";
4
+ import type { LogSink } from "./log-http.ts";
5
+ /** What the issuer needs of an object store. A put must be whole or absent: R2's is. */
6
+ export interface ObjectStore {
7
+ put(key: string, text: string): Promise<void>;
8
+ /** the object's text, or null when there is none */
9
+ get(key: string): Promise<string | null>;
10
+ /** every key under the prefix */
11
+ list(prefix: string): Promise<string[]>;
12
+ delete(key: string): Promise<void>;
13
+ }
14
+ export interface ObjectIssuerOptions {
15
+ capture?: {
16
+ rules?: CaptureConfig | undefined;
17
+ key?: Buffer | undefined;
18
+ } | undefined;
19
+ /** prepended to every key, so that one bucket can hold several doors' receipts. Default "" */
20
+ prefix?: string | undefined;
21
+ }
22
+ /**
23
+ * Signs, logs, and stores receipts in `store`. As with the file issuer, a receipt reaches the store only after the log
24
+ * has taken it; with `deferLog`, a refused append keeps the signed receipt in the outbox and throws `ReceiptPending`,
25
+ * and `flushOutbox` appends it later. There is no lock across processes: two flushes at once (two Worker isolates) can
26
+ * each append one outbox entry, which puts the receipt in the log twice, under two leaves. Either inclusion proves it.
27
+ * `pending` counts the outbox entries this issuer has seen, since a count of the store would need a listing.
28
+ */
29
+ export declare function createObjectIssuer(key: KeyPair, store: ObjectStore, sink: LogSink, opts?: ObjectIssuerOptions): Issuer;
@@ -0,0 +1,172 @@
1
+ // An issuer that keeps receipts in an object store (Cloudflare R2, or anything with put, get, list, and delete) instead
2
+ // of a directory: the same signing, capture, and log rules as the file issuer (issue.ts), for a producer with no disk.
3
+ // The layout mirrors the receipts directory: `<prefix><id>.json` for a bundle, `<prefix><id>.authorization.json` for
4
+ // an authorization, `<prefix>salts/<id>.json` for the salts behind withheld values, `<prefix>outbox/<id>.json` for a
5
+ // signed receipt whose log append is pending. The salts are the owner's alone: the store must not be readable by
6
+ // anyone a receipt's withheld values are kept from.
7
+ import { effectiveRule, getAt, privateView } from "./capture.js";
8
+ import { canonicalize, dsseSign, dsseVerify } from "./crypto.js";
9
+ import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./receipt.js";
10
+ import { ReceiptPending } from "./receipt-pending.js";
11
+ /** a receipt id as the door mints it; anything else never becomes part of a key */
12
+ const RECEIPT_ID = /^[A-Za-z0-9-]{1,64}$/;
13
+ /**
14
+ * Signs, logs, and stores receipts in `store`. As with the file issuer, a receipt reaches the store only after the log
15
+ * has taken it; with `deferLog`, a refused append keeps the signed receipt in the outbox and throws `ReceiptPending`,
16
+ * and `flushOutbox` appends it later. There is no lock across processes: two flushes at once (two Worker isolates) can
17
+ * each append one outbox entry, which puts the receipt in the log twice, under two leaves. Either inclusion proves it.
18
+ * `pending` counts the outbox entries this issuer has seen, since a count of the store would need a listing.
19
+ */
20
+ export function createObjectIssuer(key, store, sink, opts = {}) {
21
+ const prefix = opts.prefix ?? "";
22
+ const bundleKey = (id) => `${prefix}${id}.json`;
23
+ const outboxKey = (id) => `${prefix}outbox/${id}.json`;
24
+ const idOk = (id) => {
25
+ if (!RECEIPT_ID.test(id))
26
+ throw new Error(`receipt id ${JSON.stringify(id)} is not a valid id`);
27
+ return id;
28
+ };
29
+ const view = (predicate, ctx, prior) => privateView(predicate, effectiveRule(opts.capture?.rules, predicate.tool.name, ctx?.unknownTool), opts.capture?.key, ctx, prior);
30
+ // as in the file issuer: the authorization's view, until its receipt is issued, so that both carry the same commitments
31
+ const committed = new Map();
32
+ const COMMITTED_FOR_MS = 60 * 60 * 1000;
33
+ const COMMITTED_AT_MOST = 10_000;
34
+ let outboxSeen = 0;
35
+ const keepSalts = async (v) => {
36
+ 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)]]));
37
+ if (!Object.keys(salts).length)
38
+ return;
39
+ await store.put(`${prefix}salts/${idOk(v.predicate.receiptId)}.json`, JSON.stringify({ receiptId: v.predicate.receiptId, salts }, null, 2));
40
+ };
41
+ const bundleOf = (envelope, entry) => ({ envelope, treeHead: entry.treeHead, inclusion: entry.inclusion });
42
+ return {
43
+ keyid: key.keyid,
44
+ log: sink,
45
+ async issue(predicate, ctx, retainPrepared, issueOpts) {
46
+ if (retainPrepared)
47
+ throw new Error("the object issuer does not retain prepared receipts");
48
+ const id = idOk(predicate.receiptId);
49
+ const pv = view(predicate, ctx, committed.get(id)?.view);
50
+ const envelope = dsseSign(RECEIPT_TYPE, buildStatement(pv.predicate), key);
51
+ let entry;
52
+ try {
53
+ entry = await sink.append(canonicalize(envelope));
54
+ }
55
+ catch (e) {
56
+ if (!issueOpts?.deferLog)
57
+ throw e;
58
+ try {
59
+ await keepSalts(pv);
60
+ await store.put(outboxKey(id), JSON.stringify({ envelope }));
61
+ }
62
+ catch (w) {
63
+ throw new Error(`${e instanceof Error ? e.message : String(e)}; the receipt could not be kept in the outbox either: ${w instanceof Error ? w.message : String(w)}`, { cause: e });
64
+ }
65
+ committed.delete(id);
66
+ outboxSeen++;
67
+ throw new ReceiptPending(id, e);
68
+ }
69
+ committed.delete(id);
70
+ await keepSalts(pv);
71
+ const bundle = bundleOf(envelope, entry);
72
+ await store.put(bundleKey(id), JSON.stringify(bundle, null, 2));
73
+ return bundle;
74
+ },
75
+ async authorize(predicate, ctx) {
76
+ const id = idOk(predicate.receiptId);
77
+ const pv = view(predicate, ctx);
78
+ const envelope = dsseSign(RECEIPT_TYPE, buildAuthorizationStatement(pv.predicate), key);
79
+ const entry = await sink.append(canonicalize(envelope));
80
+ const now = Date.now();
81
+ for (const [k, c] of committed) {
82
+ if (now - c.at <= COMMITTED_FOR_MS)
83
+ break;
84
+ committed.delete(k);
85
+ }
86
+ committed.set(id, { view: pv, at: now });
87
+ if (committed.size > COMMITTED_AT_MOST)
88
+ committed.delete(committed.keys().next().value);
89
+ await keepSalts(pv);
90
+ const bundle = { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion };
91
+ // stored before the call goes on: if nothing follows, this is the evidence that it was authorized and sent
92
+ await store.put(`${prefix}${id}.authorization.json`, JSON.stringify(bundle, null, 2));
93
+ return bundle;
94
+ },
95
+ pending: () => outboxSeen,
96
+ async flushOutbox() {
97
+ const keys = (await store.list(`${prefix}outbox/`)).filter((k) => k.endsWith(".json"));
98
+ let sent = 0;
99
+ let setAside = 0;
100
+ let foreign = 0;
101
+ const errors = [];
102
+ for (const k of keys) {
103
+ const id = k.slice(`${prefix}outbox/`.length, -".json".length);
104
+ try {
105
+ if (!RECEIPT_ID.test(id)) {
106
+ setAside++;
107
+ continue;
108
+ }
109
+ // a bundle already there: the append and the write happened, and only the removal did not
110
+ if (await store.get(bundleKey(id))) {
111
+ await store.delete(k);
112
+ sent++;
113
+ continue;
114
+ }
115
+ const text = await store.get(k);
116
+ if (text === null)
117
+ continue;
118
+ let record;
119
+ try {
120
+ record = JSON.parse(text);
121
+ }
122
+ catch {
123
+ await store.put(`${k}.bad`, text);
124
+ await store.delete(k);
125
+ setAside++;
126
+ continue;
127
+ }
128
+ const envelope = record.envelope;
129
+ if (typeof envelope?.payload !== "string" || !Array.isArray(envelope.signatures) || envelope.signatures.length === 0) {
130
+ await store.put(`${k}.bad`, text);
131
+ await store.delete(k);
132
+ setAside++;
133
+ continue;
134
+ }
135
+ if (!envelope.signatures.some((s) => s?.keyid === key.keyid)) {
136
+ foreign++;
137
+ continue;
138
+ }
139
+ const checked = dsseVerify(envelope, [key]);
140
+ const statement = (checked.ok ? checked.payload : undefined);
141
+ if (!statement || envelope.payloadType !== RECEIPT_TYPE || statement.predicate?.receiptId !== id) {
142
+ await store.put(`${k}.bad`, text);
143
+ await store.delete(k);
144
+ setAside++;
145
+ continue;
146
+ }
147
+ let entry = record.appended;
148
+ if (!entry) {
149
+ try {
150
+ entry = await sink.append(canonicalize(envelope));
151
+ }
152
+ catch (e) {
153
+ errors.push(e instanceof Error ? e.message : String(e));
154
+ break;
155
+ }
156
+ // until the bundle is written, the answer is the only proof that the log has the leaf
157
+ await store.put(k, JSON.stringify({ envelope, appended: entry }));
158
+ }
159
+ await store.put(bundleKey(id), JSON.stringify(bundleOf(envelope, entry), null, 2));
160
+ await store.delete(k);
161
+ sent++;
162
+ }
163
+ catch (e) {
164
+ errors.push(`outbox entry ${k}: ${e instanceof Error ? e.message : String(e)}`);
165
+ }
166
+ }
167
+ const remaining = (await store.list(`${prefix}outbox/`)).filter((k) => k.endsWith(".json")).length;
168
+ outboxSeen = remaining;
169
+ return { sent, pending: remaining, setAside, foreign, ...(errors.length ? { error: errors.length === 1 ? errors[0] : `${errors[0]} (and ${errors.length - 1} more)` } : {}) };
170
+ },
171
+ };
172
+ }
@@ -0,0 +1,16 @@
1
+ /** What one `flushOutbox` did. `foreign` entries are signed by another key and stay in the outbox. */
2
+ export interface FlushResult {
3
+ sent: number;
4
+ pending: number;
5
+ setAside: number;
6
+ foreign: number;
7
+ error?: string;
8
+ }
9
+ /**
10
+ * Thrown by `issue` with `deferLog` when the log did not take the receipt. The signed receipt is kept in the outbox and
11
+ * no bundle is written yet: `flushOutbox` appends it later and then writes the bundle.
12
+ */
13
+ export declare class ReceiptPending extends Error {
14
+ readonly receiptId: string;
15
+ constructor(receiptId: string, cause: unknown);
16
+ }
@@ -0,0 +1,14 @@
1
+ // What an issuer reports when a receipt's log append is pending, apart from the file issuer so that any issuer (a
2
+ // Worker's included) and the door core can share it.
3
+ /**
4
+ * Thrown by `issue` with `deferLog` when the log did not take the receipt. The signed receipt is kept in the outbox and
5
+ * no bundle is written yet: `flushOutbox` appends it later and then writes the bundle.
6
+ */
7
+ export class ReceiptPending extends Error {
8
+ receiptId;
9
+ constructor(receiptId, cause) {
10
+ super(`receipt ${receiptId} is kept in the outbox; its log append is pending: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
11
+ this.name = "ReceiptPending";
12
+ this.receiptId = receiptId;
13
+ }
14
+ }