@int-loop/core 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +59 -0
  2. package/README.md +22 -2
  3. package/dist/anchor.d.ts +70 -0
  4. package/dist/anchor.js +201 -0
  5. package/dist/binding.d.ts +103 -0
  6. package/dist/binding.js +54 -0
  7. package/dist/cbor.d.ts +11 -0
  8. package/dist/cbor.js +94 -0
  9. package/dist/comprehension.d.ts +12 -0
  10. package/dist/comprehension.js +81 -0
  11. package/dist/der.d.ts +53 -0
  12. package/dist/der.js +246 -0
  13. package/dist/evidence-pack.d.ts +68 -0
  14. package/dist/evidence-pack.js +355 -0
  15. package/dist/hash.d.ts +16 -0
  16. package/dist/hash.js +90 -0
  17. package/dist/index.d.ts +23 -0
  18. package/dist/index.js +23 -0
  19. package/dist/jcs.d.ts +4 -0
  20. package/dist/jcs.js +69 -0
  21. package/dist/ledger.d.ts +10 -0
  22. package/dist/ledger.js +32 -0
  23. package/dist/receipt.d.ts +29 -0
  24. package/dist/receipt.js +80 -0
  25. package/dist/schema/common.d.ts +38 -0
  26. package/dist/schema/common.js +42 -0
  27. package/dist/schema/decision.d.ts +72 -0
  28. package/dist/schema/decision.js +67 -0
  29. package/dist/schema/directory.d.ts +59 -0
  30. package/dist/schema/directory.js +47 -0
  31. package/dist/schema/ledger.d.ts +61 -0
  32. package/dist/schema/ledger.js +40 -0
  33. package/dist/schema/pack.d.ts +60 -0
  34. package/dist/schema/pack.js +53 -0
  35. package/dist/schema/policy.d.ts +215 -0
  36. package/dist/schema/policy.js +85 -0
  37. package/dist/schema/receipt.d.ts +74 -0
  38. package/dist/schema/receipt.js +40 -0
  39. package/dist/schema/request.d.ts +252 -0
  40. package/dist/schema/request.js +102 -0
  41. package/dist/tsa-roots.d.ts +9 -0
  42. package/dist/tsa-roots.js +150 -0
  43. package/dist/tsp.d.ts +37 -0
  44. package/dist/tsp.js +228 -0
  45. package/dist/verify.d.ts +18 -0
  46. package/dist/verify.js +151 -0
  47. package/dist/webauthn.d.ts +54 -0
  48. package/dist/webauthn.js +190 -0
  49. package/dist/x509.d.ts +93 -0
  50. package/dist/x509.js +329 -0
  51. package/package.json +25 -3
package/LICENSE ADDED
@@ -0,0 +1,59 @@
1
+ Copyright 2026 Captivated Ltd
2
+
3
+ Licensed under the Apache License, Version 2.0 (the full text follows).
4
+
5
+ Apache License
6
+
7
+ Version 2.0, January 2004
8
+
9
+ http://www.apache.org/licenses/
10
+
11
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
12
+
13
+ 1. Definitions.
14
+
15
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
16
+
17
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
18
+
19
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
20
+
21
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
22
+
23
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
24
+
25
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
26
+
27
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
28
+
29
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
30
+
31
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
32
+
33
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
34
+
35
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
36
+
37
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
38
+
39
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
40
+
41
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
42
+
43
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
44
+
45
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
46
+
47
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
48
+
49
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
50
+
51
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
52
+
53
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
54
+
55
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
56
+
57
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
58
+
59
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
- # Temporary Holding Version
1
+ # @int-loop/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The shared code behind [int-loop](https://int-loop.com), the approval service for AI agents, and its offline verifier.
4
+
5
+ - Request, decision, ledger and receipt schemas (zod)
6
+ - RFC 8785 (JCS) canonicalisation and SHA-256 helpers
7
+ - Passkey (WebAuthn) binding construction and assertion verification
8
+ - Offline verification of ledgers, evidence packs and receipts
9
+
10
+ It has no I/O and no platform-specific APIs, so it runs in Node, browsers and Workers alike. Most people want the CLI, [`@int-loop/verify`](https://www.npmjs.com/package/@int-loop/verify).
11
+
12
+ ```ts
13
+ import { verifyReceipt } from "@int-loop/core";
14
+
15
+ const report = await verifyReceipt(receiptJson, trustedKeys, {
16
+ documents: { article: articleBytes },
17
+ });
18
+ if (!report.ok) throw new Error("not approved");
19
+ ```
20
+
21
+ `trustedKeys` is int-loop's published key list, from `https://int-loop.com/.well-known/int-loop-keys.json`. Fetch it once and pin it.
22
+
23
+ Licensed under Apache-2.0.
@@ -0,0 +1,70 @@
1
+ import { z } from "zod";
2
+ import type { LedgerEntry } from "./schema/ledger.ts";
3
+ import type { VerificationFailure } from "./verify.ts";
4
+ export declare const ANCHOR_LEAF_TYPE = "int-loop.anchor-leaf/1";
5
+ export declare const AnchorTimestamp: z.ZodObject<{
6
+ tsa: z.ZodString;
7
+ token: z.ZodString;
8
+ gen_time: z.ZodISODateTime;
9
+ }, z.core.$strict>;
10
+ export type AnchorTimestamp = z.infer<typeof AnchorTimestamp>;
11
+ export declare const AnchorCreatedPayload: z.ZodObject<{
12
+ anchored: z.ZodObject<{
13
+ seq: z.ZodNumber;
14
+ entry_hash: z.ZodString;
15
+ }, z.core.$strict>;
16
+ merkle: z.ZodObject<{
17
+ root: z.ZodString;
18
+ leaf_index: z.ZodNumber;
19
+ tree_size: z.ZodNumber;
20
+ path: z.ZodArray<z.ZodString>;
21
+ }, z.core.$strict>;
22
+ timestamps: z.ZodArray<z.ZodObject<{
23
+ tsa: z.ZodString;
24
+ token: z.ZodString;
25
+ gen_time: z.ZodISODateTime;
26
+ }, z.core.$strict>>;
27
+ }, z.core.$strict>;
28
+ export type AnchorCreatedPayload = z.infer<typeof AnchorCreatedPayload>;
29
+ export type AnchorLeaf = {
30
+ tenant_id: string;
31
+ seq: number;
32
+ entry_hash: string;
33
+ };
34
+ export declare const AnchorLeafSchema: z.ZodObject<{
35
+ tenant_id: z.ZodString;
36
+ seq: z.ZodNumber;
37
+ entry_hash: z.ZodString;
38
+ }, z.core.$strict>;
39
+ export declare function anchorLeafHash(leaf: AnchorLeaf): Promise<Uint8Array<ArrayBuffer>>;
40
+ export declare function merkleRoot(leafHashes: readonly Uint8Array[]): Promise<Uint8Array<ArrayBuffer>>;
41
+ /** The inclusion path for leaf `index`, nearest sibling first. */
42
+ export declare function merklePath(leafHashes: readonly Uint8Array[], index: number): Promise<Uint8Array<ArrayBuffer>[]>;
43
+ /** Recomputes the root from a leaf and its path (RFC 9162 2.1.3.2), or null if the path does not fit the tree. */
44
+ export declare function rootFromPath(leafHash: Uint8Array, index: number, size: number, path: readonly Uint8Array[]): Promise<Uint8Array | null>;
45
+ /**
46
+ * The tree for one anchoring round: one leaf per tenant, in tenant order. Returns the root
47
+ * to stamp, and each tenant's anchor.created payload once the stamps are in.
48
+ */
49
+ export declare function anchorTree(leaves: readonly AnchorLeaf[]): Promise<{
50
+ root: Uint8Array<ArrayBuffer>;
51
+ payload: (tenantId: string, timestamps: AnchorTimestamp[]) => Promise<AnchorCreatedPayload>;
52
+ }>;
53
+ /** How far a TSA's clock may disagree with int-loop's before the verifier objects. */
54
+ export declare const ANCHOR_CLOCK_TOLERANCE_MS: number;
55
+ export type AnchorReport = {
56
+ anchors_checked: number;
57
+ /** The newest anchored entry and the earliest time a TSA vouches it existed. */
58
+ anchored_through: {
59
+ seq: number;
60
+ gen_time: string;
61
+ tsas: string[];
62
+ } | null;
63
+ failures: VerificationFailure[];
64
+ };
65
+ /**
66
+ * Checks every anchor.created entry: the anchored entry is in the ledger with that hash,
67
+ * its leaf leads to the stamped root, and every timestamp token verifies against `roots`
68
+ * for that root, at a time consistent with when the entries were recorded.
69
+ */
70
+ export declare function verifyAnchors(entries: readonly LedgerEntry[], roots: readonly Uint8Array[]): Promise<AnchorReport>;
package/dist/anchor.js ADDED
@@ -0,0 +1,201 @@
1
+ // Anchoring: once an hour, each tenant's latest ledger entry is timestamped by
2
+ // independent RFC 3161 timestamp authorities, so not even int-loop can rewrite
3
+ // history afterwards without it showing.
4
+ //
5
+ // One stamp covers every tenant. The heads are the leaves of a Merkle tree (RFC 9162
6
+ // hashing, domain-separated leaves and nodes); the TSAs stamp the root, and each
7
+ // tenant's anchor.created entry records its own leaf's path to that root. A tenant's
8
+ // evidence pack therefore proves its own chain head existed at the stamped time and
9
+ // reveals nothing about other tenants beyond opaque sibling hashes.
10
+ import { z } from "zod";
11
+ import { canonicalise } from "./jcs.js";
12
+ import { concatBytes, fromBase64Url, fromHex, sha256, toHex, utf8 } from "./hash.js";
13
+ import { Base64Url, Sha256Hex, TenantId, Timestamp } from "./schema/common.js";
14
+ import { verifyTimestampToken } from "./tsp.js";
15
+ export const ANCHOR_LEAF_TYPE = "int-loop.anchor-leaf/1";
16
+ export const AnchorTimestamp = z.strictObject({
17
+ /** Which TSA, e.g. "freetsa". Informational: trust comes from the token's certificate chain. */
18
+ tsa: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/),
19
+ /** The DER TimeStampToken. */
20
+ token: Base64Url,
21
+ /** The time inside the token, repeated for readers; the verifier checks they agree. */
22
+ gen_time: Timestamp,
23
+ });
24
+ export const AnchorCreatedPayload = z.strictObject({
25
+ anchored: z.strictObject({ seq: z.number().int().positive(), entry_hash: Sha256Hex }),
26
+ merkle: z.strictObject({
27
+ root: Sha256Hex,
28
+ leaf_index: z.number().int().nonnegative(),
29
+ tree_size: z.number().int().positive(),
30
+ path: z.array(Sha256Hex).max(64),
31
+ }),
32
+ timestamps: z.array(AnchorTimestamp).min(1).max(8),
33
+ });
34
+ export const AnchorLeafSchema = z.strictObject({ tenant_id: TenantId, seq: z.number().int().positive(), entry_hash: Sha256Hex });
35
+ // ---- Merkle tree (RFC 9162 section 2.1) ----------------------------------------------
36
+ export async function anchorLeafHash(leaf) {
37
+ const body = utf8(canonicalise({ type: ANCHOR_LEAF_TYPE, tenant_id: leaf.tenant_id, seq: leaf.seq, entry_hash: leaf.entry_hash }));
38
+ return sha256(concatBytes(Uint8Array.of(0), body));
39
+ }
40
+ const node = (left, right) => sha256(concatBytes(Uint8Array.of(1), left, right));
41
+ /** The largest power of two smaller than n (n > 1). */
42
+ const split = (n) => 2 ** Math.floor(Math.log2(n - 1));
43
+ export async function merkleRoot(leafHashes) {
44
+ if (leafHashes.length === 0)
45
+ throw new Error("a Merkle tree needs at least one leaf");
46
+ if (leafHashes.length === 1)
47
+ return new Uint8Array(leafHashes[0]);
48
+ const k = split(leafHashes.length);
49
+ return node(await merkleRoot(leafHashes.slice(0, k)), await merkleRoot(leafHashes.slice(k)));
50
+ }
51
+ /** The inclusion path for leaf `index`, nearest sibling first. */
52
+ export async function merklePath(leafHashes, index) {
53
+ if (index < 0 || index >= leafHashes.length)
54
+ throw new Error("leaf index out of range");
55
+ if (leafHashes.length === 1)
56
+ return [];
57
+ const k = split(leafHashes.length);
58
+ return index < k
59
+ ? [...(await merklePath(leafHashes.slice(0, k), index)), await merkleRoot(leafHashes.slice(k))]
60
+ : [...(await merklePath(leafHashes.slice(k), index - k)), await merkleRoot(leafHashes.slice(0, k))];
61
+ }
62
+ /** Recomputes the root from a leaf and its path (RFC 9162 2.1.3.2), or null if the path does not fit the tree. */
63
+ export async function rootFromPath(leafHash, index, size, path) {
64
+ if (index >= size)
65
+ return null;
66
+ let fn = index;
67
+ let sn = size - 1;
68
+ let r = leafHash;
69
+ for (const p of path) {
70
+ if (sn === 0)
71
+ return null;
72
+ if (fn % 2 === 1 || fn === sn) {
73
+ r = await node(p, r);
74
+ while (fn % 2 === 0 && fn !== 0) {
75
+ fn = Math.floor(fn / 2);
76
+ sn = Math.floor(sn / 2);
77
+ }
78
+ }
79
+ else {
80
+ r = await node(r, p);
81
+ }
82
+ fn = Math.floor(fn / 2);
83
+ sn = Math.floor(sn / 2);
84
+ }
85
+ return sn === 0 ? r : null;
86
+ }
87
+ /**
88
+ * The tree for one anchoring round: one leaf per tenant, in tenant order. Returns the root
89
+ * to stamp, and each tenant's anchor.created payload once the stamps are in.
90
+ */
91
+ export async function anchorTree(leaves) {
92
+ const sorted = [...leaves].map((l) => AnchorLeafSchema.parse(l)).sort((a, b) => (a.tenant_id < b.tenant_id ? -1 : a.tenant_id > b.tenant_id ? 1 : 0));
93
+ for (let i = 1; i < sorted.length; i++)
94
+ if (sorted[i].tenant_id === sorted[i - 1].tenant_id)
95
+ throw new Error(`two leaves for ${sorted[i].tenant_id}`);
96
+ const hashes = await Promise.all(sorted.map((l) => anchorLeafHash(l)));
97
+ const root = await merkleRoot(hashes);
98
+ return {
99
+ root,
100
+ payload: async (tenantId, timestamps) => {
101
+ const index = sorted.findIndex((l) => l.tenant_id === tenantId);
102
+ if (index < 0)
103
+ throw new Error(`no leaf for ${tenantId}`);
104
+ const leaf = sorted[index];
105
+ return AnchorCreatedPayload.parse({
106
+ anchored: { seq: leaf.seq, entry_hash: leaf.entry_hash },
107
+ merkle: { root: toHex(root), leaf_index: index, tree_size: sorted.length, path: (await merklePath(hashes, index)).map(toHex) },
108
+ timestamps,
109
+ });
110
+ },
111
+ };
112
+ }
113
+ // ---- Verification -----------------------------------------------------------------------
114
+ /** How far a TSA's clock may disagree with int-loop's before the verifier objects. */
115
+ export const ANCHOR_CLOCK_TOLERANCE_MS = 5 * 60_000;
116
+ /**
117
+ * Checks every anchor.created entry: the anchored entry is in the ledger with that hash,
118
+ * its leaf leads to the stamped root, and every timestamp token verifies against `roots`
119
+ * for that root, at a time consistent with when the entries were recorded.
120
+ */
121
+ export async function verifyAnchors(entries, roots) {
122
+ const failures = [];
123
+ const bySeq = new Map(entries.map((e) => [e.seq, e]));
124
+ let anchors_checked = 0;
125
+ let anchored_through = null;
126
+ for (const entry of entries) {
127
+ if (entry.type !== "anchor.created")
128
+ continue;
129
+ anchors_checked++;
130
+ const fail = (check, message) => failures.push({ seq: entry.seq, check, message });
131
+ try {
132
+ const parsed = AnchorCreatedPayload.safeParse(entry.payload);
133
+ if (!parsed.success) {
134
+ fail("anchor", parsed.error.issues.map((i) => i.message).join("; "));
135
+ continue;
136
+ }
137
+ const p = parsed.data;
138
+ const anchored = bySeq.get(p.anchored.seq);
139
+ if (p.anchored.seq >= entry.seq) {
140
+ fail("anchor", "an anchor can only cover entries recorded before it");
141
+ continue;
142
+ }
143
+ if (!anchored) {
144
+ fail("anchor", `anchored entry ${p.anchored.seq} is not in this ledger`);
145
+ continue;
146
+ }
147
+ if (anchored.entry_hash !== p.anchored.entry_hash) {
148
+ fail("anchor", `anchored hash does not match entry ${p.anchored.seq}`);
149
+ continue;
150
+ }
151
+ const leaf = await anchorLeafHash({ tenant_id: entry.tenant_id, seq: p.anchored.seq, entry_hash: p.anchored.entry_hash });
152
+ const root = await rootFromPath(leaf, p.merkle.leaf_index, p.merkle.tree_size, p.merkle.path.map(fromHex));
153
+ if (root === null || toHex(root) !== p.merkle.root) {
154
+ fail("anchor", "the anchored entry is not in the stamped Merkle tree");
155
+ continue;
156
+ }
157
+ // Labels are the recorder's word; independence is judged by the root each token chains to.
158
+ const tsas = new Set();
159
+ const rootsUsed = new Map();
160
+ const verified = [];
161
+ let earliest = null;
162
+ for (const ts of p.timestamps) {
163
+ const problems = [];
164
+ if (tsas.has(ts.tsa))
165
+ problems.push(`two timestamps from ${ts.tsa}`);
166
+ tsas.add(ts.tsa);
167
+ const result = await verifyTimestampToken(fromBase64Url(ts.token), { digest: fromHex(p.merkle.root), roots });
168
+ if (!result.ok) {
169
+ fail("timestamp", `${ts.tsa}: ${result.reason}`);
170
+ continue;
171
+ }
172
+ const at = Date.parse(result.gen_time);
173
+ if (at !== Date.parse(ts.gen_time))
174
+ problems.push(`recorded time ${ts.gen_time} differs from the token's ${result.gen_time}`);
175
+ if (at < Date.parse(anchored.recorded_at) - ANCHOR_CLOCK_TOLERANCE_MS)
176
+ problems.push(`stamped before entry ${anchored.seq} was recorded`);
177
+ if (at > Date.parse(entry.recorded_at) + ANCHOR_CLOCK_TOLERANCE_MS)
178
+ problems.push("stamped after the anchor itself was recorded");
179
+ const sameRoot = rootsUsed.get(result.root_sha256);
180
+ if (sameRoot !== undefined)
181
+ problems.push(`chains to the same root as ${sameRoot}, so it is not an independent timestamp`);
182
+ rootsUsed.set(result.root_sha256, ts.tsa);
183
+ // Only a timestamp with nothing wrong counts towards what the anchor proves.
184
+ if (problems.length) {
185
+ for (const m of problems)
186
+ fail("timestamp", `${ts.tsa}: ${m}`);
187
+ continue;
188
+ }
189
+ verified.push(ts.tsa);
190
+ earliest = earliest === null ? at : Math.min(earliest, at);
191
+ }
192
+ if (earliest !== null && (anchored_through === null || p.anchored.seq >= anchored_through.seq)) {
193
+ anchored_through = { seq: p.anchored.seq, gen_time: new Date(earliest).toISOString(), tsas: verified };
194
+ }
195
+ }
196
+ catch (err) {
197
+ fail("internal", err instanceof Error ? err.message : String(err));
198
+ }
199
+ }
200
+ return { anchors_checked, anchored_through, failures };
201
+ }
@@ -0,0 +1,103 @@
1
+ import { z } from "zod";
2
+ import { Fact } from "./schema/request.ts";
3
+ /** Exactly what the approval page rendered. Hashed to `displayed_hash`. */
4
+ export declare const DisplayedContent: z.ZodObject<{
5
+ title: z.ZodString;
6
+ facts: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
7
+ key: z.ZodString;
8
+ label: z.ZodString;
9
+ type: z.ZodLiteral<"money">;
10
+ value: z.ZodObject<{
11
+ amount_minor: z.ZodNumber;
12
+ currency: z.ZodString;
13
+ }, z.core.$strict>;
14
+ }, z.core.$strict>, z.ZodObject<{
15
+ key: z.ZodString;
16
+ label: z.ZodString;
17
+ type: z.ZodLiteral<"text">;
18
+ value: z.ZodString;
19
+ }, z.core.$strict>, z.ZodObject<{
20
+ key: z.ZodString;
21
+ label: z.ZodString;
22
+ type: z.ZodLiteral<"date">;
23
+ value: z.ZodUnion<readonly [z.ZodISODate, z.ZodISODateTime]>;
24
+ }, z.core.$strict>, z.ZodObject<{
25
+ key: z.ZodString;
26
+ label: z.ZodString;
27
+ type: z.ZodLiteral<"enum">;
28
+ value: z.ZodString;
29
+ choices: z.ZodOptional<z.ZodArray<z.ZodString>>;
30
+ }, z.core.$strict>, z.ZodObject<{
31
+ key: z.ZodString;
32
+ label: z.ZodString;
33
+ type: z.ZodLiteral<"list">;
34
+ value: z.ZodArray<z.ZodString>;
35
+ }, z.core.$strict>, z.ZodObject<{
36
+ key: z.ZodString;
37
+ label: z.ZodString;
38
+ type: z.ZodLiteral<"url">;
39
+ value: z.ZodURL;
40
+ }, z.core.$strict>, z.ZodObject<{
41
+ key: z.ZodString;
42
+ label: z.ZodString;
43
+ type: z.ZodLiteral<"count">;
44
+ value: z.ZodNumber;
45
+ }, z.core.$strict>, z.ZodObject<{
46
+ key: z.ZodString;
47
+ label: z.ZodString;
48
+ type: z.ZodLiteral<"document">;
49
+ value: z.ZodObject<{
50
+ media_type: z.ZodEnum<{
51
+ "text/markdown": "text/markdown";
52
+ "text/plain": "text/plain";
53
+ }>;
54
+ body: z.ZodString;
55
+ }, z.core.$strict>;
56
+ }, z.core.$strict>], "type">>;
57
+ narrative: z.ZodString;
58
+ options: z.ZodArray<z.ZodObject<{
59
+ id: z.ZodString;
60
+ label: z.ZodString;
61
+ kind: z.ZodEnum<{
62
+ approve: "approve";
63
+ approve_with_conditions: "approve_with_conditions";
64
+ choose: "choose";
65
+ deny: "deny";
66
+ more_info: "more_info";
67
+ }>;
68
+ }, z.core.$strict>>;
69
+ policy_reason: z.ZodArray<z.ZodString>;
70
+ clarifications: z.ZodOptional<z.ZodArray<z.ZodObject<{
71
+ question: z.ZodString;
72
+ answer: z.ZodString;
73
+ }, z.core.$strict>>>;
74
+ }, z.core.$strict>;
75
+ export type DisplayedContent = z.infer<typeof DisplayedContent>;
76
+ export declare const ComprehensionAnswer: z.ZodObject<{
77
+ question_id: z.ZodString;
78
+ answer: z.ZodString;
79
+ }, z.core.$strict>;
80
+ export declare const BindingInput: z.ZodObject<{
81
+ request_id: z.ZodString;
82
+ request_version: z.ZodNumber;
83
+ displayed_hash: z.ZodString;
84
+ option_id: z.ZodString;
85
+ rationale_hash: z.ZodNullable<z.ZodString>;
86
+ text_hash: z.ZodNullable<z.ZodString>;
87
+ comprehension: z.ZodNullable<z.ZodObject<{
88
+ question_id: z.ZodString;
89
+ answer: z.ZodString;
90
+ }, z.core.$strict>>;
91
+ approver_id: z.ZodString;
92
+ nonce: z.ZodString;
93
+ issued_at: z.ZodISODateTime;
94
+ }, z.core.$strict>;
95
+ export type BindingInput = z.infer<typeof BindingInput>;
96
+ /**
97
+ * SHA-256 (hex) of each document fact's body, as UTF-8, keyed by fact key. A publisher checks
98
+ * the bytes it is about to ship against this value.
99
+ */
100
+ export declare function documentHashes(facts: readonly Fact[]): Promise<Record<string, string>>;
101
+ export declare function displayedHash(content: DisplayedContent): Promise<string>;
102
+ /** The 32-byte WebAuthn challenge: SHA-256(JCS(binding)). */
103
+ export declare function bindingChallenge(input: BindingInput): Promise<Uint8Array<ArrayBuffer>>;
@@ -0,0 +1,54 @@
1
+ // Passkey binding: the WebAuthn challenge commits to exactly what the approver
2
+ // saw and chose, so the assertion proves the holder of that passkey approved
3
+ // that payload and nothing else. See "Passkey binding" in CLAUDE.md.
4
+ import { z } from "zod";
5
+ import { hashCanonical, hashCanonicalHex, hashTextHex } from "./hash.js";
6
+ import { Base64Url, PersonId, RequestId, Sha256Hex, Slug, Timestamp } from "./schema/common.js";
7
+ import { Fact, Option } from "./schema/request.js";
8
+ /** Exactly what the approval page rendered. Hashed to `displayed_hash`. */
9
+ export const DisplayedContent = z.strictObject({
10
+ title: z.string(),
11
+ facts: z.array(Fact),
12
+ narrative: z.string(),
13
+ options: z.array(Option),
14
+ // "Why you're receiving this": the names of the matching policy rules.
15
+ policy_reason: z.array(z.string()),
16
+ // Questions approvers asked and the agent's answers, from earlier versions.
17
+ clarifications: z.array(z.strictObject({ question: z.string(), answer: z.string() })).optional(),
18
+ });
19
+ export const ComprehensionAnswer = z.strictObject({
20
+ question_id: z.string().min(1),
21
+ answer: z.string(),
22
+ });
23
+ export const BindingInput = z.strictObject({
24
+ request_id: RequestId,
25
+ request_version: z.number().int().positive(),
26
+ displayed_hash: Sha256Hex,
27
+ option_id: Slug,
28
+ rationale_hash: Sha256Hex.nullable(),
29
+ // The approver's conditions (approve_with_conditions) or question (more_info).
30
+ text_hash: Sha256Hex.nullable(),
31
+ comprehension: ComprehensionAnswer.nullable(),
32
+ approver_id: PersonId,
33
+ // Server-issued, single use: 32 random bytes, base64url.
34
+ nonce: Base64Url.min(43),
35
+ issued_at: Timestamp,
36
+ });
37
+ /**
38
+ * SHA-256 (hex) of each document fact's body, as UTF-8, keyed by fact key. A publisher checks
39
+ * the bytes it is about to ship against this value.
40
+ */
41
+ export async function documentHashes(facts) {
42
+ const out = {};
43
+ for (const f of facts)
44
+ if (f.type === "document")
45
+ out[f.key] = await hashTextHex(f.value.body);
46
+ return out;
47
+ }
48
+ export async function displayedHash(content) {
49
+ return hashCanonicalHex(DisplayedContent.parse(content));
50
+ }
51
+ /** The 32-byte WebAuthn challenge: SHA-256(JCS(binding)). */
52
+ export async function bindingChallenge(input) {
53
+ return hashCanonical(BindingInput.parse(input));
54
+ }
package/dist/cbor.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export type CborValue = number | Uint8Array | string | boolean | null | CborValue[] | Map<CborValue, CborValue>;
2
+ export declare class CborError extends Error {
3
+ name: string;
4
+ }
5
+ /** Decodes exactly one CBOR item and rejects trailing bytes. */
6
+ export declare function decodeCbor(bytes: Uint8Array): CborValue;
7
+ /** Decodes the first CBOR item and reports how many bytes it used. */
8
+ export declare function decodeCborPrefix(bytes: Uint8Array): {
9
+ value: CborValue;
10
+ length: number;
11
+ };
package/dist/cbor.js ADDED
@@ -0,0 +1,94 @@
1
+ // Minimal CBOR decoder (RFC 8949), enough to read a COSE_Key: unsigned and
2
+ // negative integers, byte and text strings, arrays, maps, and true/false/null.
3
+ // Indefinite lengths, tags and floats are rejected, as no COSE_Key uses them.
4
+ export class CborError extends Error {
5
+ name = "CborError";
6
+ }
7
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false });
8
+ /** Decodes exactly one CBOR item and rejects trailing bytes. */
9
+ export function decodeCbor(bytes) {
10
+ const { value, length } = decodeCborPrefix(bytes);
11
+ if (length !== bytes.length)
12
+ throw new CborError("trailing bytes after CBOR item");
13
+ return value;
14
+ }
15
+ /** Decodes the first CBOR item and reports how many bytes it used. */
16
+ export function decodeCborPrefix(bytes) {
17
+ const state = { bytes, pos: 0 };
18
+ const value = readItem(state, 0);
19
+ return { value, length: state.pos };
20
+ }
21
+ function readByte(s) {
22
+ const b = s.bytes[s.pos];
23
+ if (b === undefined)
24
+ throw new CborError("unexpected end of CBOR data");
25
+ s.pos++;
26
+ return b;
27
+ }
28
+ function readLength(s, info) {
29
+ if (info < 24)
30
+ return info;
31
+ const size = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : info === 27 ? 8 : 0;
32
+ if (size === 0)
33
+ throw new CborError(`unsupported additional info ${info}`);
34
+ let n = 0;
35
+ for (let i = 0; i < size; i++)
36
+ n = n * 256 + readByte(s);
37
+ if (!Number.isSafeInteger(n))
38
+ throw new CborError("CBOR integer exceeds safe range");
39
+ return n;
40
+ }
41
+ function readBytes(s, len) {
42
+ if (s.pos + len > s.bytes.length)
43
+ throw new CborError("unexpected end of CBOR data");
44
+ const out = s.bytes.slice(s.pos, s.pos + len);
45
+ s.pos += len;
46
+ return out;
47
+ }
48
+ function readItem(s, depth) {
49
+ if (depth > 16)
50
+ throw new CborError("CBOR nesting too deep");
51
+ const initial = readByte(s);
52
+ const major = initial >> 5;
53
+ const info = initial & 0x1f;
54
+ switch (major) {
55
+ case 0:
56
+ return readLength(s, info);
57
+ case 1:
58
+ return -1 - readLength(s, info);
59
+ case 2:
60
+ return readBytes(s, readLength(s, info));
61
+ case 3:
62
+ return decoder.decode(readBytes(s, readLength(s, info)));
63
+ case 4: {
64
+ const len = readLength(s, info);
65
+ const arr = [];
66
+ for (let i = 0; i < len; i++)
67
+ arr.push(readItem(s, depth + 1));
68
+ return arr;
69
+ }
70
+ case 5: {
71
+ const len = readLength(s, info);
72
+ const map = new Map();
73
+ for (let i = 0; i < len; i++) {
74
+ const key = readItem(s, depth + 1);
75
+ if (typeof key !== "number" && typeof key !== "string")
76
+ throw new CborError("CBOR map keys must be integers or text");
77
+ if (map.has(key))
78
+ throw new CborError(`duplicate CBOR map key ${key}`);
79
+ map.set(key, readItem(s, depth + 1));
80
+ }
81
+ return map;
82
+ }
83
+ case 7:
84
+ if (info === 20)
85
+ return false;
86
+ if (info === 21)
87
+ return true;
88
+ if (info === 22)
89
+ return null;
90
+ throw new CborError(`unsupported CBOR simple value ${info}`);
91
+ default:
92
+ throw new CborError(`unsupported CBOR major type ${major}`);
93
+ }
94
+ }
@@ -0,0 +1,12 @@
1
+ import type { Fact } from "./schema/request.ts";
2
+ export type ComprehensionQuestion = {
3
+ question_id: string;
4
+ fact_key: string;
5
+ prompt: string;
6
+ /** Formatted values, in display order. Exactly one is correct. */
7
+ choices: string[];
8
+ answer: string;
9
+ };
10
+ /** Facts a question can be built from: values with plausible wrong answers. */
11
+ export declare function comprehensionFacts(facts: readonly Fact[]): Fact[];
12
+ export declare function comprehensionQuestion(facts: readonly Fact[], seed: string, format: (f: Fact) => string): Promise<ComprehensionQuestion | null>;