@aleutian/verification 0.0.0 → 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Aleutian AI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,485 @@
1
+ # @aleutian/verification
2
+
3
+ Aleutian AI verification SDK for offline V3 SAR chain entry, anchor, and
4
+ webhook verification. All verification runs offline; no network calls.
5
+
6
+ ## Features
7
+
8
+ - **V3 SAR chain entry verification** — verify the cryptographic signature on
9
+ a Data Subject Access Request audit chain entry (`verifyChainEntryV3`,
10
+ ML-DSA-65 / FIPS 204). Byte-identical to the Go and Python SDKs against
11
+ shared golden vectors.
12
+ - **Anchor verification** — verify ML-DSA-65 anchor signatures using
13
+ embedded or supplied public keys (v7 with the FIPS 204 context
14
+ `aleutian.proof.anchor.v7`, v1–v6 with the empty context).
15
+ - **Chain verification** — verify SHA-512 chain hash integrity for chain
16
+ formats v4 (leaf hash + chain hash; erased entries recomputed from their
17
+ leaf hash), v3 and v2, including v2/v3 chains continued in v4.
18
+ - **Anchor binding** — bind v1–v4, v6 and v7 anchors to the entries they
19
+ cover; v7 anchors by sequence, with the expected subject and predecessor.
20
+ - **Tombstone detection** — validate GDPR deletion markers.
21
+ - **Webhook verification** — verify HMAC-SHA-512 webhook signatures
22
+ (Node.js only).
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ npm install @aleutian/verification
28
+ ```
29
+
30
+ ## Quick Start
31
+
32
+ ### Verify a V3 SAR chain entry
33
+
34
+ The single public verifier:
35
+
36
+ ```typescript
37
+ import {
38
+ TrustManifestV3,
39
+ verifyChainEntryV3,
40
+ type SARFulfilledEntryV3,
41
+ } from "@aleutian/verification";
42
+
43
+ // 1. Build the trust manifest from your controller's published signing keys.
44
+ const trustManifest = TrustManifestV3.fromMap({
45
+ "anchor-signer-2026-v1": new Uint8Array([
46
+ /* 1952 ML-DSA-65 public-key bytes */
47
+ ]),
48
+ });
49
+
50
+ // 2. The chain entry your controller signed (snake_case → camelCase mapping
51
+ // happens at JSON-decode time; see the cross-SDK golden vectors for the
52
+ // canonical shape).
53
+ const entry: SARFulfilledEntryV3 = {
54
+ companyId: "comp_01HK7AAAAAAAAAAAAAAAAAAAAA",
55
+ entryType: "sar_fulfilled",
56
+ signingKeyId: "anchor-signer-2026-v1",
57
+ timestampMs: 1_715_000_000_000,
58
+ certificateId: "cert_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
59
+ fulfillmentKind: "erasure",
60
+ intentEntryId: "018fa1b3-c4d5-7000-8000-1234567890ab",
61
+ legalBasis: "art_17_erasure",
62
+ manifestRoot: "d".repeat(128),
63
+ requestId: "01HK7BBBBBBBBBBBBBBBBBBBBB",
64
+ tombstoneCount: 42,
65
+ };
66
+
67
+ // 3. The signature + content_hash from the BigQuery row (or your
68
+ // controller's published audit feed).
69
+ const signature = new Uint8Array(/* 3309 raw ML-DSA-65 bytes */);
70
+ const contentHash = new Uint8Array(/* 64 raw SHA-512 bytes */);
71
+
72
+ try {
73
+ await verifyChainEntryV3(entry, signature, contentHash, trustManifest);
74
+ console.log("verified");
75
+ } catch (e) {
76
+ // Branch on the typed error subclass (NOT on err.message — Privacy Inv 4).
77
+ console.error("verification failed:", (e as Error).name);
78
+ }
79
+ ```
80
+
81
+ The verifier throws one of: `ErrInvalidEntryV3`, `ErrContentHashMismatchV3`,
82
+ `ErrSignatureInvalidV3`, `ErrSignatureMalformedV3`, `ErrUnknownSigningKeyV3`,
83
+ or `ErrPublicKeyMalformedV3`. All extend `ErrInvalidEntryV3` so customers
84
+ can catch broadly or narrowly.
85
+
86
+ ### Operating the verifier safely (M3 — production hygiene)
87
+
88
+ A few patterns to avoid when deploying this SDK on a public verifier
89
+ endpoint (e.g. `verify.your-company.com`):
90
+
91
+ - **Do NOT `console.log(entry)` or `console.log(canonical)` in production.**
92
+ V3 SAR entries carry `requestId` (a per-tenant SAR identifier) and
93
+ HMAC digests over caller-supplied cleartext. Even though the digests
94
+ are redacted by `toString` / `toJSON` (the SDK ships this protection
95
+ for `TenantHMACDigestV3` out of the box), an `entry` object also
96
+ contains the `requestId` and `timestampMs` pair, which together pin
97
+ a per-tenant SAR within ~1ms. Log the typed error name instead
98
+ (`err.name`), never the entry object.
99
+ - **Do NOT mint signing keys in your verifier process.** ML-DSA-65
100
+ keypairs are produced by Aleutian's KMS, distributed via the trust
101
+ manifest. A verifier that generates keys locally to "test" signature
102
+ paths can accidentally publish them or hold them in memory next to
103
+ user data. Use `TrustManifestV3.fromMap` with bytes you fetched
104
+ from an authenticated source.
105
+ - **Do NOT echo the bad value in error messages your verifier shows
106
+ to data subjects.** The SDK never echoes caller input in its own
107
+ error messages (Privacy Inv 4 — regression-guarded). Preserve this
108
+ posture in your own catch-block when surfacing errors via UI.
109
+ - **Do branch on the typed error subclass** (`err instanceof
110
+ ErrContentHashMismatchV3`) rather than parsing `err.message`. The
111
+ message text is intentionally opaque.
112
+
113
+ ### Verify Chain Export
114
+
115
+ ```typescript
116
+ import {
117
+ loadAnchor,
118
+ loadExportedEntries,
119
+ verifyAnchorLocally,
120
+ verifyChainOffline,
121
+ SEED_ANCHOR_HASH,
122
+ } from "@aleutian/verification";
123
+
124
+ // Load and verify anchor
125
+ const anchor = await loadAnchor("anchor-2026-01-20.json");
126
+ verifyAnchorLocally(anchor); // Throws on failure
127
+
128
+ // Load and verify chain
129
+ const entries = await loadExportedEntries("export-2026-01.json");
130
+ const result = await verifyChainOffline(entries, {
131
+ anchor,
132
+ // For genesis anchors pass SEED_ANCHOR_HASH (or omit; SDK auto-fills).
133
+ // For mid-chain anchors pass the prior anchor's chainHash here.
134
+ previousAnchorHash: SEED_ANCHOR_HASH,
135
+ });
136
+
137
+ if (result.valid) {
138
+ console.log(`Chain valid: ${result.entriesVerified} entries`);
139
+ } else {
140
+ console.log(`Chain invalid: ${result.breaks.length} breaks`);
141
+ }
142
+ ```
143
+
144
+ ### Verify a v4 chain and bind a v7 anchor
145
+
146
+ ```typescript
147
+ import {
148
+ bindAnchorV7ToEntries,
149
+ parseAnchorText,
150
+ parseEntriesText,
151
+ verifyAnchorLocally,
152
+ verifyChainOffline,
153
+ } from "@aleutian/verification";
154
+
155
+ const entries = parseEntriesText(entriesBytes); // v2, v3 and v4 entries
156
+ const result = await verifyChainOffline(entries);
157
+ // result.erasedFound: erased v4 entries — still recomputed, so still verified.
158
+ // result.entriesNotVerified: entries up to the last v2/v3 tombstone (never verified).
159
+
160
+ const anchor = parseAnchorText(anchorBytes); // v7: entry_count, start_seq, end_seq are strings
161
+ verifyAnchorLocally(anchor, publicKey); // context "aleutian.proof.anchor.v7"
162
+ const bind = await bindAnchorV7ToEntries(anchor, entries, { subject: "orders" });
163
+ if (bind.bound && bind.subjectChecked) {
164
+ // the anchor is about "orders" and binds these entries
165
+ }
166
+ ```
167
+
168
+ v7's sequence numbers and count are JSON strings because they may exceed 2^53;
169
+ `parseAnchorText` and `parseEntriesText` return them as `bigint`, never as a
170
+ rounded `number`. Without `subject`, the result says `subjectChecked: false`.
171
+
172
+ ### Verify a proof sink export bundle
173
+
174
+ A bundle (`aleutian.proof.bundle.v1` or `aleutian.proof.bundle.v2`, proof's
175
+ `bundle-format.md`) is a sink's evidence exported so that someone else can
176
+ check it without the sink, the writer, or proof's code. This verifier was
177
+ written from the spec alone and is held to the shared `bundle_v1_vectors.json`
178
+ and `bundle_v2_vectors.json`. Both formats produce the same
179
+ `aleutian.proof.bundle-result.v1`; v2 (proof v0.5.0) carries chain format v4
180
+ entries, v7 checkpoints and `record.v2` signatures. **Trust is yours:** you supply the
181
+ ML-DSA-65 public keys you trust for checkpoints and for record signatures; a
182
+ bundle never adds a key.
183
+
184
+ ```sh
185
+ aleutian-verify verify-proof-bundle bundle.json \
186
+ --checkpoint-key checkpoint.pub --record-key record.pub [--json]
187
+ ```
188
+
189
+ | Exit | Meaning |
190
+ |---|---|
191
+ | 0 | `ok`: no problem, and every entry is authenticated by a key you trust |
192
+ | 1 | `failed`: at least one problem |
193
+ | 2 | usage: bad arguments, a missing or unreadable file, an invalid key file |
194
+ | 3 | the bundle is unreadable |
195
+ | 4 | `unauthenticated`: consistent, but provenance is not established |
196
+ | 5 | an internal error in the verifier: never a verdict on the bundle |
197
+
198
+ `--json` prints exactly the `aleutian.proof.bundle-result.v1` result. Key files
199
+ are the PEM files `proof keygen` and `proof sink init` write. Without any key
200
+ the best possible verdict is `unauthenticated`: chain hashes need no key, so
201
+ anyone can fabricate a chain whose hashes recompute.
202
+
203
+ A pass does **not** prove that the bundle holds every chain, that a chain is
204
+ complete to its end, or anything against a writer who controls the evidence and
205
+ every key you trust (bundle-format §1). Output never prints a bundle value
206
+ other than a valid chain id.
207
+
208
+ ```typescript
209
+ import { parseProofPublicKeyFile, verifyProofBundle } from "@aleutian/verification";
210
+
211
+ const result = await verifyProofBundle(bundleBytes, {
212
+ checkpointKeys: [parseProofPublicKeyFile(checkpointPemBytes)],
213
+ recordKeys: [],
214
+ });
215
+ if (result.readable && result.verdict === "ok") {
216
+ // every entry authenticated by a checkpoint key you trust
217
+ }
218
+ ```
219
+
220
+ The library API is browser-safe.
221
+
222
+ ### Verify Webhook (Node.js)
223
+
224
+ ```typescript
225
+ import express from "express";
226
+ import { isValidWebhook } from "@aleutian/verification";
227
+
228
+ app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
229
+ if (
230
+ !isValidWebhook(
231
+ req.headers["x-aleutian-signature"] as string,
232
+ req.body,
233
+ process.env.WEBHOOK_SECRET!
234
+ )
235
+ ) {
236
+ return res.status(401).send("Invalid signature");
237
+ }
238
+ // Process webhook...
239
+ res.sendStatus(200);
240
+ });
241
+ ```
242
+
243
+ ## API Reference
244
+
245
+ ### Chain Verification
246
+
247
+ - `computeChainHash(previousHash, runId, sequenceNum, timestamp, contentHash)` - Compute chain hash (v2)
248
+ - `computeChainHashMs(previousHash, runId, sequenceNum, timestampMs, contentHash)` - Compute hash from Unix milliseconds
249
+ - `computeLeafHashV4(entryId, entryType, contentHash, salt)` - Compute a v4 leaf hash
250
+ - `computeChainHashV4(previousHash, globalSeq, timestamp, leafHash)` - Compute a v4 chain hash
251
+ - `verifyChainOffline(entries, options?)` - Verify complete chain (v2, v3, v4)
252
+ - `parseEntriesText(text)` - Read an entries file strictly
253
+ - `bindAnchorToEntries(anchor, entries, previousAnchorHash)` - Bind a v1–v6 anchor
254
+ - `bindAnchorV7ToEntries(anchor, entries, { subject?, previousAnchorHash? })` - Bind a v7 anchor
255
+
256
+ ### Anchor Verification
257
+
258
+ - `verifyAnchorLocally(anchor, publicKey?)` - Verify anchor signature (context by declared version)
259
+ - `parseAnchorText(text)` - Read an anchor strictly (format-spec §9.8)
260
+ - `canonicalizeAnchorForVersion(anchor)` - Canonical bytes for the declared version
261
+ - `computeAnchorChainHashV7(previousAnchorHash, subject, startSeq, endSeq, tip)` - v7 anchor chain hash
262
+ - `canonicalizeAnchor(anchor)` - Get canonical JSON for verification
263
+ - `loadAnchor(path)` - Load anchor from file (Node.js)
264
+ - `loadExportedEntries(path)` - Load entries from file (Node.js)
265
+
266
+ ### Webhook Verification (Node.js only)
267
+
268
+ - `isValidWebhook(signatureHeader, payload, secret)` - Simple validation (returns boolean)
269
+ - `verifyWebhookSignature(signatureHeader, payload, secret, options?)` - Full validation (throws on error)
270
+ - `verifyWebhookWithSecrets(signatureHeader, payload, secrets, options?)` - Support secret rotation
271
+ - `computeWebhookSignature(secret, timestamp, payload)` - Compute signature (for testing)
272
+ - `decodeSecret(secret)` - Decode base64 or hex secret from dashboard
273
+
274
+ ### Tombstone Detection
275
+
276
+ - `isTombstone(entryType, entryId)` - Check if entry is a tombstone
277
+ - `isTombstoneContentHash(contentHash)` - Quick prefix check
278
+ - `validateTombstoneContentHash(contentHash)` - Full format validation
279
+
280
+ ### Keys
281
+
282
+ - `getPublicKey(keyId)` - Get embedded public key
283
+ - `isKnownKey(keyId)` - Check if key ID is known
284
+ - `listKeyIds()` - List all embedded key IDs
285
+
286
+ ## Types
287
+
288
+ ```typescript
289
+ interface Anchor {
290
+ version: number;
291
+ anchorId: string;
292
+ companyId: string;
293
+ region: string;
294
+ chainState: ChainState;
295
+ metadata: Metadata;
296
+ signature: Signature;
297
+ }
298
+
299
+ interface ExportedEntry {
300
+ entryId: string;
301
+ entryType: string;
302
+ timestamp: string;
303
+ runId: string;
304
+ sequenceNum: number;
305
+ globalSeq: number;
306
+ contentHash: string;
307
+ chainHash: string;
308
+ }
309
+
310
+ interface OfflineVerificationResult {
311
+ valid: boolean;
312
+ entriesVerified: number;
313
+ tombstonesFound: number;
314
+ breaks: OfflineBreak[];
315
+ durationMs: number;
316
+ }
317
+ ```
318
+
319
+ ### Anchor int64 fields: `bigint | number`
320
+
321
+ As of 0.3.0, `Anchor.entryCount`, `Anchor.createdAtMs`, and
322
+ `Anchor.verifiedThrough` accept either `bigint` or `number`. Real-world
323
+ millisecond timestamps and counters fit in `number` and need no caller
324
+ change. For int64 values that exceed `Number.MAX_SAFE_INTEGER` (2^53 − 1)
325
+ — for example, the synthetic 2^63 − 1 boundary — pass them as `bigint`
326
+ or as JSON strings; `parseAnchor` will route strings through `BigInt(...)`.
327
+
328
+ ```typescript
329
+ // Number — preserves the existing API
330
+ const a1 = parseAnchor({ /* ... */ entry_count: 42, created_at_ms: 1700000000000 });
331
+
332
+ // JSON string — preserves full int64 precision
333
+ const a2 = parseAnchor({ /* ... */ verified_through: "9223372036854775807" });
334
+
335
+ // Consuming the field
336
+ const n = typeof a2.entryCount === "bigint"
337
+ ? a2.entryCount // use BigInt arithmetic
338
+ : BigInt(a2.entryCount); // promote for uniform handling
339
+ ```
340
+
341
+
342
+ ## Conformance
343
+
344
+ One of three implementations of the same format, held to a **shared set of
345
+ conformance vectors** kept in the public `proof` repository and vendored here
346
+ with a manifest of SHA-256 digests.
347
+
348
+ ```
349
+ proof/fixtures/testdata/ ← canonical, public
350
+ │ vendored + digest-checked
351
+ ┌───────────────┼───────────────┐
352
+ ▼ ▼ ▼
353
+ Go Python JavaScript
354
+ └────── all must reproduce ─────┘
355
+ ```
356
+
357
+ The expected outputs are **data**, never regenerated by an implementation during
358
+ a run: a vector edited to make one implementation pass fails the other two.
359
+ `test/conformanceVectors.test.ts` verifies the vendored copy before any test
360
+ trusts it.
361
+
362
+ **Vector set passed:** proof v0.5.0's plus the X-Wing specification's official
363
+ vectors (`xwing_spec_vectors.json`), `sdk/testdata/MANIFEST.json` with
364
+ SHA-256 `304583d41eca4e74e2fb19cd799f499e663d60d0366bb70f4f712db903264d3c`
365
+ (`shasum -a 256 MANIFEST.json`), every case of every file it lists.
366
+
367
+ **Formats this SDK verifies:**
368
+
369
+ | Format | Spec | Vectors |
370
+ |---|---|---|
371
+ | Chain hash v4 (leaf hash, chain hash, erasure, continuation from v2/v3) | format-spec §2.0, §2.5, §5.0 | `chain_v4_vectors.json` |
372
+ | Chain hash v3, v2 (frozen) | format-spec §2.1, §2.3 | `chain_v3_vectors.json`, `chain_vectors.json` |
373
+ | Verifier verdicts: break order and counters, v7 keyless bind | format-spec §5.5, §9.7 | `verify_verdict_v4_vectors.json`, `verify_verdict_vectors.json` |
374
+ | Anchors v7 (context `aleutian.proof.anchor.v7`) | format-spec §9 | `anchor_v7_canonical_vectors.json` |
375
+ | Anchors v1, v3, v4, v6 (frozen), anchor chain hash | format-spec §9 | `anchor_v6_canonical_vectors.json`, `anchor_v4_canonical_vectors.json`, `anchor_chain_hash_vectors.json` |
376
+ | Sink bundles `aleutian.proof.bundle.v2` and `.v1` | bundle-format §1–§16 | `bundle_v2_vectors.json`, `bundle_v1_vectors.json` |
377
+ | Record envelopes `aleutian.proof.record.v2` (context `aleutian.proof.record.v2`) and `.v1` | sink-format §9.1 | `record_v2_vectors.json`, `record_v1_vectors.json` |
378
+ | Key ids, salted commitments, Merkle trees, capture leaf v3 | format-spec §9.6, §8, §7, §6 | `keyid_vectors.json`, `commitment_vectors.json`, `merkle_golden.json`, `v3_golden_capture_request.json` |
379
+
380
+ This SDK is also tested against artifacts the Go implementation produced —
381
+ a v3 chain from `proof append` and a v6 anchor signed by `proof anchor` with a
382
+ real ML-DSA-65 key.
383
+
384
+ ### What this SDK does not do
385
+
386
+ It **verifies**; it does not produce. No signing, no chain linking, no key
387
+ generation — those live in the Go implementation. A verifier should be small,
388
+ dependency-light and safe to drop into an auditor's environment, including a
389
+ browser.
390
+
391
+ ## Security
392
+
393
+ - **ML-DSA-65** (FIPS 204) anchor signatures — post-quantum, verify-only. This
394
+ SDK cannot sign; see "What this SDK does not do".
395
+ - HMAC-**SHA-512** webhook signatures via Node.js crypto (constant-time)
396
+ - [tweetnacl](https://tweetnacl.js.org/) is used for **X25519 key exchange** in
397
+ the tier-2 unseal path (audited, constant-time) — NOT for signatures. An
398
+ earlier version of this section said "Ed25519 signatures via tweetnacl",
399
+ which was wrong on both counts.
400
+ - Webhook verification uses `crypto.timingSafeEqual` to prevent timing attacks
401
+ - Secret rotation verifies ALL secrets to prevent timing side-channel (H-5)
402
+ - Signature parsing uses constant-time pattern (H-1)
403
+
404
+ ### Privacy Notes
405
+
406
+ - `anchor.companyId` contains business-identifying information - do not log
407
+ - `OfflineBreak.entryId` may correlate to PII - truncate hashes before logging
408
+ - `durationMs` can reveal chain size - do not log in production
409
+
410
+ ## Browser Support
411
+
412
+ The SDK ships a dedicated browser bundle alongside the Node bundle. Modern
413
+ browsers (Chrome 80+, Firefox 75+, Safari 14+, Edge 80+) are supported.
414
+
415
+ ### npm consumers (bundlers — Vite, webpack, esbuild, Rollup)
416
+
417
+ No special configuration required. The `package.json` `exports` map
418
+ includes a `"browser"` conditional, so bundlers automatically resolve
419
+ to `dist/browser/index.js` (ESM) when building for a browser target.
420
+
421
+ ```typescript
422
+ import {
423
+ verifyChainEntryV3,
424
+ TrustManifestV3,
425
+ encodeAndHashV3,
426
+ } from "@aleutian/verification";
427
+ ```
428
+
429
+ ### CDN / `<script>` include (no bundler)
430
+
431
+ The IIFE bundle exposes everything on a `window.AleutianVerification`
432
+ global:
433
+
434
+ ```html
435
+ <script src="https://unpkg.com/@aleutian/verification/dist/browser/index.global.js"></script>
436
+ <script type="module">
437
+ const { encodeAndHashV3, verifyChainEntryV3 } = window.AleutianVerification;
438
+
439
+ // Fetch your anchor and entry from your server / Aleutian
440
+ const entryJson = await fetch("/entry.json").then((r) => r.json());
441
+
442
+ // ... convert wire JSON to typed ChainEntryV3 (camelCase) ...
443
+ const { canonical, contentHash } = await encodeAndHashV3(entry);
444
+ // ...
445
+ </script>
446
+ ```
447
+
448
+ ### What's NOT in the browser bundle
449
+
450
+ The browser bundle intentionally omits two surfaces:
451
+
452
+ - **Webhook verification** (`verifyWebhookSignature`, `isValidWebhook`,
453
+ etc.) — webhooks are server→server and the existing API is sync
454
+ HMAC-SHA-512, which has no async-free browser equivalent. Use the
455
+ Node bundle for webhook verification.
456
+ - **File-system loaders** (`loadAnchor`, `loadExportedEntries`) —
457
+ browsers don't have filesystem access. Use `fetch(...)` then
458
+ `parseAnchor` / `parseExportedEntries` instead.
459
+
460
+ ### Threat-model caveat for constant-time compare in browsers
461
+
462
+ The constant-time hash and signature compares in `verifyChainEntryV3`
463
+ prefer the Node built-in (`crypto.timingSafeEqual`, C-level) when
464
+ available; in the browser they fall back to a pure-JS implementation.
465
+ The pure-JS fallback is best-effort under JIT — for high-assurance
466
+ deployments, prefer running verification under Node.
467
+
468
+ ### Browser-bundle CI
469
+
470
+ Two suites cover the browser bundle:
471
+
472
+ - `npm test` (vitest) runs the happy-dom smoke at
473
+ `test/browserBundle.smoke.test.ts` — fast, covers the ESM import
474
+ surface and the `crypto.subtle.digest("SHA-512", ...)` contract.
475
+ - `npm run test:browser` (Playwright + Chromium) runs a real-browser
476
+ pass at `test/playwright/browser_smoke.spec.ts` that loads the IIFE
477
+ bundle via `<script>`, attaches `window.AleutianVerification`, and
478
+ re-hashes the same Go-baked V3 SAR golden vector inside real V8.
479
+ Requires `npx playwright install chromium` once.
480
+
481
+ ## License
482
+
483
+ Apache-2.0
484
+
485
+ Copyright 2026 Aleutian AI