@ternent/ledger 0.1.8 → 0.2.0-alpha.1

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.
@@ -0,0 +1,529 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { decodeBase64Url, encodeBase64Url, validatePublicIdentity, verifySignature } from "@ternent/identity";
3
+
4
+ // src/common/errors.ts
5
+ const ok = (value) => ({
6
+ ok: true,
7
+ value
8
+ });
9
+ const error = (code, phase, path) => ({
10
+ code,
11
+ phase,
12
+ message: code.replaceAll("_", " ").toLowerCase(),
13
+ ...path === void 0 ? {} : { path }
14
+ });
15
+ var Fault = class extends Error {
16
+ finding;
17
+ constructor(finding) {
18
+ super(finding.code);
19
+ this.finding = finding;
20
+ }
21
+ };
22
+ function fail(code, phase = "protocol", path) {
23
+ throw new Fault(error(code, phase, path));
24
+ }
25
+ function caught(cause, fallback, phase) {
26
+ return cause instanceof Fault ? cause.finding : error(fallback, phase);
27
+ }
28
+ function attempt(body, fallback = "SCHEMA_INVALID", phase = "protocol") {
29
+ try {
30
+ return ok(body());
31
+ } catch (cause) {
32
+ return {
33
+ ok: false,
34
+ error: caught(cause, fallback, phase)
35
+ };
36
+ }
37
+ }
38
+
39
+ // src/protocol/json.ts
40
+ const utf8 = new TextEncoder();
41
+ const text = new TextDecoder("utf-8", {
42
+ fatal: true,
43
+ ignoreBOM: true
44
+ });
45
+ function unicode(value) {
46
+ for (let i = 0; i < value.length; i++) {
47
+ const c = value.charCodeAt(i);
48
+ if (c >= 55296 && c <= 56319) {
49
+ const next = value.charCodeAt(++i);
50
+ if (!(next >= 56320 && next <= 57343)) return false;
51
+ } else if (c >= 56320 && c <= 57343) return false;
52
+ }
53
+ return true;
54
+ }
55
+ function encodeJson(input, maxDepth = 64) {
56
+ const active = /* @__PURE__ */ new Set();
57
+ function encode(value, depth) {
58
+ if (value === null) return "null";
59
+ if (typeof value === "string") {
60
+ if (!unicode(value)) fail("JSON_INVALID", "input");
61
+ return JSON.stringify(value);
62
+ }
63
+ if (typeof value === "boolean") return String(value);
64
+ if (typeof value === "number") {
65
+ if (!Number.isSafeInteger(value) || Object.is(value, -0)) fail("JSON_INVALID", "input");
66
+ return String(value);
67
+ }
68
+ if (!value || typeof value !== "object") fail("JSON_INVALID", "input");
69
+ if (depth + 1 > maxDepth) fail("RESOURCE_LIMIT");
70
+ const prototype = Object.getPrototypeOf(value);
71
+ if (Array.isArray(value) && prototype !== Array.prototype || !Array.isArray(value) && prototype !== null && prototype !== Object.prototype || active.has(value)) fail("JSON_INVALID", "input");
72
+ const descriptors = Object.getOwnPropertyDescriptors(value);
73
+ if (Object.getOwnPropertySymbols(value).length || Object.values(descriptors).some((d) => !("value" in d))) fail("JSON_INVALID", "input");
74
+ active.add(value);
75
+ let output;
76
+ if (Array.isArray(value)) {
77
+ if (Object.keys(descriptors).length !== value.length + 1) fail("JSON_INVALID", "input");
78
+ const items = [];
79
+ for (let i = 0; i < value.length; i++) {
80
+ if (!Object.hasOwn(descriptors, String(i))) fail("JSON_INVALID", "input");
81
+ items.push(encode(descriptors[i].value, depth + 1));
82
+ }
83
+ output = `[${items.join(",")}]`;
84
+ } else output = `{${Object.keys(descriptors).sort().map((key) => `${encode(key, depth + 1)}:${encode(descriptors[key].value, depth + 1)}`).join(",")}}`;
85
+ active.delete(value);
86
+ return output;
87
+ }
88
+ return utf8.encode(encode(input, 0));
89
+ }
90
+ function canonicalize(value) {
91
+ return attempt(() => encodeJson(value), "JSON_INVALID", "input");
92
+ }
93
+ function numberToken(token) {
94
+ const match = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(token);
95
+ let digits = (match[2] + (match[3] ?? "")).replace(/^0+/, "");
96
+ if (!digits) {
97
+ if (match[1]) fail("JSON_INVALID", "input");
98
+ return 0;
99
+ }
100
+ const scale = Number(match[4] ?? 0) - (match[3]?.length ?? 0);
101
+ if (!Number.isSafeInteger(scale)) fail("JSON_INVALID", "input");
102
+ if (scale < 0) {
103
+ if (-scale > digits.length || !digits.endsWith("0".repeat(-scale))) fail("JSON_INVALID", "input");
104
+ digits = digits.slice(0, scale);
105
+ } else {
106
+ if (digits.length + scale > 16) fail("JSON_INVALID", "input");
107
+ digits += "0".repeat(scale);
108
+ }
109
+ if (digits.length > 16 || digits.length === 16 && digits > "9007199254740991") fail("JSON_INVALID", "input");
110
+ return Number(`${match[1]}${digits}`);
111
+ }
112
+ function parseJson(bytes, maxDepth = 64, maxBytes = 16777216) {
113
+ if (bytes.length > maxBytes) fail("RESOURCE_LIMIT");
114
+ let source;
115
+ try {
116
+ source = text.decode(bytes);
117
+ } catch {
118
+ fail("JSON_INVALID", "input");
119
+ }
120
+ if (source.charCodeAt(0) === 65279) fail("JSON_INVALID", "input");
121
+ let offset = 0;
122
+ function space() {
123
+ while (offset < source.length && " \n\r".includes(source[offset])) offset++;
124
+ }
125
+ function string() {
126
+ const start = offset++;
127
+ while (offset < source.length) {
128
+ const c = source[offset++];
129
+ if (c === "\"") {
130
+ let value;
131
+ try {
132
+ value = JSON.parse(source.slice(start, offset));
133
+ } catch {
134
+ fail("JSON_INVALID", "input");
135
+ }
136
+ if (!unicode(value)) fail("JSON_INVALID", "input");
137
+ return value;
138
+ }
139
+ if (c === "\\") offset++;
140
+ }
141
+ return fail("JSON_INVALID", "input");
142
+ }
143
+ function value(depth) {
144
+ space();
145
+ const c = source[offset];
146
+ if (c === "\"") return string();
147
+ if (c === "{" || c === "[") {
148
+ if (depth + 1 > maxDepth) fail("RESOURCE_LIMIT");
149
+ offset++;
150
+ space();
151
+ if (c === "[") {
152
+ const result = [];
153
+ if (source[offset] === "]") {
154
+ offset++;
155
+ return result;
156
+ }
157
+ while (true) {
158
+ result.push(value(depth + 1));
159
+ space();
160
+ if (source[offset] === "]") {
161
+ offset++;
162
+ return result;
163
+ }
164
+ if (source[offset++] !== ",") fail("JSON_INVALID", "input");
165
+ }
166
+ }
167
+ const result = Object.create(null);
168
+ const keys = /* @__PURE__ */ new Set();
169
+ if (source[offset] === "}") {
170
+ offset++;
171
+ return result;
172
+ }
173
+ while (true) {
174
+ space();
175
+ if (source[offset] !== "\"") fail("JSON_INVALID", "input");
176
+ const key = string();
177
+ if (keys.has(key)) fail("JSON_INVALID", "input");
178
+ keys.add(key);
179
+ space();
180
+ if (source[offset++] !== ":") fail("JSON_INVALID", "input");
181
+ result[key] = value(depth + 1);
182
+ space();
183
+ if (source[offset] === "}") {
184
+ offset++;
185
+ return result;
186
+ }
187
+ if (source[offset++] !== ",") fail("JSON_INVALID", "input");
188
+ }
189
+ }
190
+ for (const [literal, result] of [
191
+ ["true", true],
192
+ ["false", false],
193
+ ["null", null]
194
+ ]) if (source.startsWith(literal, offset)) {
195
+ offset += literal.length;
196
+ return result;
197
+ }
198
+ const number = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(source.slice(offset));
199
+ if (number) {
200
+ offset += number[0].length;
201
+ return numberToken(number[0]);
202
+ }
203
+ return fail("JSON_INVALID", "input");
204
+ }
205
+ const result = value(0);
206
+ space();
207
+ if (offset !== source.length) fail("JSON_INVALID", "input");
208
+ return result;
209
+ }
210
+
211
+ // src/schema.ts
212
+ const defaults = {
213
+ maxBytes: 16777216,
214
+ maxCommits: 1e4,
215
+ maxEntries: 1e5,
216
+ maxDepth: 64,
217
+ maxMetadataBytes: 65536,
218
+ maxPayloadBytes: 16777216
219
+ };
220
+ function limits(input = {}) {
221
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => !Object.hasOwn(defaults, key))) fail("HOST_CONFIGURATION", "requirements");
222
+ const output = {
223
+ ...defaults,
224
+ ...input
225
+ };
226
+ if (Object.values(output).some((value) => !Number.isSafeInteger(value) || value <= 0)) fail("HOST_CONFIGURATION", "requirements");
227
+ return output;
228
+ }
229
+ function record(value) {
230
+ return value !== null && typeof value === "object" && !Array.isArray(value);
231
+ }
232
+ function closed(value, keys, path) {
233
+ if (!record(value) || Object.keys(value).length !== keys.length || keys.some((key) => !Object.hasOwn(value, key))) fail("SCHEMA_INVALID", "protocol", path);
234
+ }
235
+ function id(value, kind, path) {
236
+ if (typeof value !== "string" || !new RegExp(`^${kind}:[0-9a-f]{64}$`).test(value)) fail("SCHEMA_INVALID", "protocol", path);
237
+ }
238
+ function bytes(value, size, path) {
239
+ if (typeof value !== "string") fail("SCHEMA_INVALID", "protocol", path);
240
+ const decoded = decodeBase64Url(value);
241
+ if (!decoded.ok || decoded.value.length !== size) fail("SCHEMA_INVALID", "protocol", path);
242
+ return decoded.value;
243
+ }
244
+ function timestamp(value) {
245
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value) || !Number.isFinite(Date.parse(value)) || new Date(value).toISOString() !== value) fail("SCHEMA_INVALID", "protocol");
246
+ }
247
+ function metadata(value, lim) {
248
+ if (value !== null && !record(value)) fail("SCHEMA_INVALID", "protocol");
249
+ if (value !== null && encodeJson(value, lim.maxDepth).length > lim.maxMetadataBytes) fail("RESOURCE_LIMIT", "protocol");
250
+ }
251
+ function appendInput(input, lim) {
252
+ if (!record(input) || Object.keys(input).some((key) => ![
253
+ "kind",
254
+ "payload",
255
+ "meta",
256
+ "nonce"
257
+ ].includes(key)) || typeof input.kind !== "string" || input.kind.length < 1 || input.kind.length > 128) fail("SCHEMA_INVALID", "input");
258
+ if (input.nonce !== void 0) bytes(input.nonce, 16, "/nonce");
259
+ metadata(input.meta ?? null, lim);
260
+ if (encodeJson(input.payload ?? null, lim.maxDepth).length > lim.maxPayloadBytes) fail("RESOURCE_LIMIT", "input");
261
+ }
262
+ function entrySubject(input, path, lim) {
263
+ closed(input, [
264
+ "version",
265
+ "parent",
266
+ "nonce",
267
+ "kind",
268
+ "author",
269
+ "authoredAt",
270
+ "meta",
271
+ "payload"
272
+ ], path);
273
+ const subject = input;
274
+ if (subject.version !== 1 || typeof subject.kind !== "string" || subject.kind.length < 1 || subject.kind.length > 128 || typeof subject.author !== "string") fail("SCHEMA_INVALID", "protocol", path);
275
+ if (subject.parent !== null) id(subject.parent, "commit", `${path}/parent`);
276
+ bytes(subject.nonce, 16, `${path}/nonce`);
277
+ timestamp(subject.authoredAt);
278
+ metadata(subject.meta, lim);
279
+ closed(subject.payload, ["type", "data"], `${path}/payload`);
280
+ if (subject.payload.type !== "plain") fail("ENTRY_KIND_UNSUPPORTED", "protocol", path);
281
+ if (encodeJson(subject.payload.data, lim.maxDepth).length > lim.maxPayloadBytes) fail("RESOURCE_LIMIT", "protocol", path);
282
+ }
283
+ function commitSubject(input, path, lim) {
284
+ closed(input, [
285
+ "version",
286
+ "suite",
287
+ "parent",
288
+ "nonce",
289
+ "signer",
290
+ "committedAt",
291
+ "entryIds",
292
+ "metadata"
293
+ ], path);
294
+ const subject = input;
295
+ if (subject.version !== 1 || subject.suite !== "ledger-ed25519-v1") fail("SUITE_UNSUPPORTED", "protocol", path);
296
+ if (subject.parent !== null) id(subject.parent, "commit", `${path}/parent`);
297
+ bytes(subject.nonce, 16, `${path}/nonce`);
298
+ if (!record(subject.signer) || !validatePublicIdentity(subject.signer).ok) fail("IDENTITY_INVALID", "protocol", path);
299
+ timestamp(subject.committedAt);
300
+ metadata(subject.metadata, lim);
301
+ if (!Array.isArray(subject.entryIds) || subject.entryIds.length > lim.maxEntries) fail("SCHEMA_INVALID", "protocol", path);
302
+ subject.entryIds.forEach((entryId, index) => id(entryId, "entry", `${path}/entryIds/${index}`));
303
+ }
304
+ function snapshot(input, lim) {
305
+ closed(input, [
306
+ "format",
307
+ "version",
308
+ "documentId",
309
+ "head",
310
+ "commits",
311
+ "entries"
312
+ ], "");
313
+ if (input.format !== "ledger" || input.version !== 1) fail("PROTOCOL_UNSUPPORTED", "protocol");
314
+ id(input.documentId, "commit", "/documentId");
315
+ id(input.head, "commit", "/head");
316
+ if (!Array.isArray(input.commits) || !input.commits.length || !Array.isArray(input.entries)) fail("SCHEMA_INVALID", "protocol");
317
+ if (input.commits.length > lim.maxCommits || input.entries.length > lim.maxEntries) fail("RESOURCE_LIMIT", "protocol");
318
+ for (const [index, entry] of input.entries.entries()) {
319
+ const path = `/entries/${index}`;
320
+ closed(entry, ["id", "subject"], path);
321
+ id(entry.id, "entry", `${path}/id`);
322
+ entrySubject(entry.subject, `${path}/subject`, lim);
323
+ }
324
+ let offset = 0;
325
+ for (const [index, commit] of input.commits.entries()) {
326
+ const path = `/commits/${index}`;
327
+ closed(commit, [
328
+ "id",
329
+ "subject",
330
+ "signature"
331
+ ], path);
332
+ id(commit.id, "commit", `${path}/id`);
333
+ commitSubject(commit.subject, `${path}/subject`, lim);
334
+ const subject = commit.subject;
335
+ if (index > 0 && !subject.entryIds.length) fail("SCHEMA_INVALID", "protocol", path);
336
+ for (const [entryIndex, entryId] of subject.entryIds.entries()) {
337
+ id(entryId, "entry", `${path}/subject/entryIds/${entryIndex}`);
338
+ const entry = input.entries[offset++];
339
+ if (record(entry) && record(entry.subject) && entry.subject.author !== subject.signer.id) fail("IDENTITY_MISMATCH", "protocol", `/entries/${offset - 1}/subject/author`);
340
+ }
341
+ bytes(commit.signature, 64, `${path}/signature`);
342
+ }
343
+ }
344
+
345
+ // src/protocol/verify.ts
346
+ const domains = {
347
+ entry: "ledger.entry/1\0",
348
+ commit: "ledger.commit/1\0",
349
+ signature: "ledger.signature/1\0"
350
+ };
351
+ const hexadecimal = (value) => Array.from(value, (v) => v.toString(16).padStart(2, "0")).join("");
352
+ function concat(a, b) {
353
+ const out = new Uint8Array(a.length + b.length);
354
+ out.set(a);
355
+ out.set(b, a.length);
356
+ return out;
357
+ }
358
+ function signatureMessage(subject, depth = 64) {
359
+ return concat(utf8.encode(domains.signature), encodeJson(subject, depth));
360
+ }
361
+ function identifier(subject, kind, depth = 64) {
362
+ return `${kind}:${hexadecimal(sha256(concat(utf8.encode(domains[kind]), encodeJson(subject, depth))))}`;
363
+ }
364
+ const unsupported = /* @__PURE__ */ new Set([
365
+ "PROTOCOL_UNSUPPORTED",
366
+ "SUITE_UNSUPPORTED",
367
+ "ENTRY_KIND_UNSUPPORTED",
368
+ "RESOURCE_LIMIT",
369
+ "HOST_CONFIGURATION"
370
+ ]);
371
+ async function inspectProtocol(bytes$1, options = {}) {
372
+ const report = {
373
+ integrity: "invalid",
374
+ documentId: null,
375
+ head: null,
376
+ checkedCommits: 0,
377
+ checkedEntries: 0,
378
+ findings: []
379
+ };
380
+ let untrustedHistory = [];
381
+ try {
382
+ const lim = limits(options.limits);
383
+ if (bytes$1.byteLength > lim.maxBytes) fail("RESOURCE_LIMIT");
384
+ const parsed = parseJson(new Uint8Array(bytes$1), lim.maxDepth, lim.maxBytes);
385
+ snapshot(parsed, lim);
386
+ untrustedHistory = parsed.commits;
387
+ report.documentId = parsed.documentId;
388
+ report.head = parsed.head;
389
+ if (encodeJson(parsed, lim.maxDepth).length > lim.maxBytes) fail("RESOURCE_LIMIT");
390
+ const entryIds = /* @__PURE__ */ new Set(), commitIds = /* @__PURE__ */ new Set(), references = /* @__PURE__ */ new Set();
391
+ for (let i = 0; i < parsed.entries.length; i++) {
392
+ const record = parsed.entries[i];
393
+ if (entryIds.has(record.id)) fail("DUPLICATE_RECORD", "protocol", `/entries/${i}/id`);
394
+ entryIds.add(record.id);
395
+ }
396
+ const expected = [];
397
+ const referencePaths = [];
398
+ for (let i = 0; i < parsed.commits.length; i++) {
399
+ const record = parsed.commits[i];
400
+ if (commitIds.has(record.id)) fail("DUPLICATE_RECORD", "protocol", `/commits/${i}/id`);
401
+ commitIds.add(record.id);
402
+ for (let j = 0; j < record.subject.entryIds.length; j++) {
403
+ const id = record.subject.entryIds[j];
404
+ if (references.has(id)) fail("DUPLICATE_RECORD", "protocol", `/commits/${i}/subject/entryIds/${j}`);
405
+ references.add(id);
406
+ expected.push(id);
407
+ referencePaths.push(`/commits/${i}/subject/entryIds/${j}`);
408
+ }
409
+ }
410
+ for (let i = 0; i < expected.length; i++) if (!entryIds.has(expected[i])) fail("ENTRY_MISSING", "protocol", referencePaths[i]);
411
+ for (let i = 0; i < parsed.entries.length; i++) if (!references.has(parsed.entries[i].id)) fail("UNREFERENCED_RECORD", "protocol", `/entries/${i}`);
412
+ for (let i = 0; i < expected.length; i++) if (parsed.entries[i]?.id !== expected[i]) fail("ENTRY_ORDER", "protocol", `/entries/${i}`);
413
+ const selected = parsed.commits.findIndex((commit) => commit.id === parsed.head);
414
+ const linear = parsed.commits.every((commit, index) => commit.subject.parent === (index === 0 ? null : parsed.commits[index - 1].id));
415
+ if (selected >= 0 && selected < parsed.commits.length - 1 && !linear) {
416
+ const records = new Map(parsed.commits.map((commit) => [commit.id, commit]));
417
+ const reachable = /* @__PURE__ */ new Set();
418
+ let cursor = parsed.head;
419
+ while (cursor !== null && records.has(cursor) && !reachable.has(cursor)) {
420
+ reachable.add(cursor);
421
+ cursor = records.get(cursor).subject.parent;
422
+ }
423
+ const detached = parsed.commits.findIndex((commit) => !reachable.has(commit.id));
424
+ if (detached >= 0) fail("UNREFERENCED_RECORD", "protocol", `/commits/${detached}`);
425
+ }
426
+ for (let i = 0; i < parsed.entries.length; i++) {
427
+ if (identifier(parsed.entries[i].subject, "entry", lim.maxDepth) !== parsed.entries[i].id) fail("HASH_MISMATCH", "protocol", `/entries/${i}/id`);
428
+ report.checkedEntries++;
429
+ }
430
+ for (let i = 0; i < parsed.commits.length; i++) if (identifier(parsed.commits[i].subject, "commit", lim.maxDepth) !== parsed.commits[i].id) fail("HASH_MISMATCH", "protocol", `/commits/${i}/id`);
431
+ let offset = 0;
432
+ for (let i = 0; i < parsed.commits.length; i++) {
433
+ const subject = parsed.commits[i].subject;
434
+ if (subject.parent !== (i === 0 ? null : parsed.commits[i - 1].id)) fail("LINK_INVALID", "protocol", `/commits/${i}/subject/parent`);
435
+ const nonces = /* @__PURE__ */ new Set();
436
+ for (let j = 0; j < subject.entryIds.length; j++) {
437
+ const entry = parsed.entries[offset++];
438
+ if (entry.subject.parent !== subject.parent) fail("LINK_INVALID", "protocol", `/entries/${offset - 1}/subject/parent`);
439
+ if (nonces.has(entry.subject.nonce)) fail("SCHEMA_INVALID", "protocol", `/entries/${offset - 1}/subject/nonce`);
440
+ nonces.add(entry.subject.nonce);
441
+ }
442
+ }
443
+ if (parsed.documentId !== parsed.commits[0].id) fail("HEAD_INVALID", "protocol", "/documentId");
444
+ if (parsed.head !== parsed.commits.at(-1).id) fail("HEAD_INVALID", "protocol", "/head");
445
+ for (let i = 0; i < parsed.commits.length; i++) {
446
+ const record = parsed.commits[i];
447
+ if (!validatePublicIdentity(record.subject.signer).ok) fail("IDENTITY_INVALID", "protocol", `/commits/${i}/subject/signer`);
448
+ const valid = await verifySignature(record.subject.signer, signatureMessage(record.subject, lim.maxDepth), bytes(record.signature, 64, `/commits/${i}/signature`));
449
+ if (!valid.ok || !valid.value) fail("SIGNATURE_INVALID", "protocol", `/commits/${i}/signature`);
450
+ report.checkedCommits++;
451
+ }
452
+ report.integrity = "valid";
453
+ return {
454
+ report,
455
+ snapshot: parsed,
456
+ untrustedHistory
457
+ };
458
+ } catch (cause) {
459
+ const finding = caught(cause, "SCHEMA_INVALID", "protocol");
460
+ report.integrity = unsupported.has(finding.code) ? "unsupported" : "invalid";
461
+ report.findings = [finding];
462
+ return {
463
+ report,
464
+ untrustedHistory
465
+ };
466
+ }
467
+ }
468
+ async function verifyDocument(bytes, options) {
469
+ return (await inspectProtocol(bytes, options)).report;
470
+ }
471
+ async function compareSnapshots(a, b, options) {
472
+ const left = await inspectProtocol(a, options), right = await inspectProtocol(b, options);
473
+ if (!left.snapshot) return {
474
+ ok: false,
475
+ error: left.report.findings[0]
476
+ };
477
+ if (!right.snapshot) return {
478
+ ok: false,
479
+ error: right.report.findings[0]
480
+ };
481
+ const x = left.snapshot, y = right.snapshot;
482
+ return ok(x.documentId !== y.documentId ? "unrelated" : x.head === y.head ? "equal" : y.commits.some((c) => c.id === x.head) ? "behind" : x.commits.some((c) => c.id === y.head) ? "ahead" : "diverged");
483
+ }
484
+ const inspectLedger = inspectProtocol;
485
+ const ledgerSignatureMessage = signatureMessage;
486
+ const verifyLedger = verifyDocument;
487
+ const compareLedgers = compareSnapshots;
488
+ /** Ordered records from a verified snapshot; traversal does not itself establish trust. */
489
+ function* orderedEntries(snapshot) {
490
+ let offset = 0;
491
+ for (const commit of snapshot.commits) for (let index = 0; index < commit.subject.entryIds.length; index++) yield {
492
+ commit,
493
+ entry: snapshot.entries[offset++]
494
+ };
495
+ }
496
+ function hashLedgerEntry(subject) {
497
+ return attempt(() => {
498
+ const safe = parseJson(encodeJson(subject));
499
+ entrySubject(safe, "", limits());
500
+ return identifier(safe, "entry");
501
+ });
502
+ }
503
+ function hashLedgerCommit(subject) {
504
+ return attempt(() => {
505
+ const safe = parseJson(encodeJson(subject));
506
+ commitSubject(safe, "", limits());
507
+ return identifier(safe, "commit");
508
+ });
509
+ }
510
+
511
+ // src/common/immutable.ts
512
+ function freeze(value) {
513
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
514
+ for (const item of Object.values(value)) freeze(item);
515
+ Object.freeze(value);
516
+ }
517
+ return value;
518
+ }
519
+ function detached(value) {
520
+ return freeze(structuredClone(value));
521
+ }
522
+
523
+ // src/common/random.ts
524
+ function nonce() {
525
+ return encodeBase64Url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)));
526
+ }
527
+
528
+ export { error as A, parseJson as C, Fault as D, utf8 as E, ok as M, attempt as O, encodeJson as S, unicode as T, appendInput as _, compareSnapshots as a, timestamp as b, hashLedgerEntry as c, inspectProtocol as d, ledgerSignatureMessage as f, verifyLedger as g, verifyDocument as h, compareLedgers as i, fail as j, caught as k, identifier as l, signatureMessage as m, detached as n, concat as o, orderedEntries as p, freeze as r, hashLedgerCommit as s, nonce as t, inspectLedger as u, limits as v, text as w, canonicalize as x, snapshot as y };
529
+ //# sourceMappingURL=protocol-Cx0QN0oK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol-Cx0QN0oK.js","names":["schema.limits","bytes","schema.bytes"],"sources":["../src/common/errors.ts","../src/protocol/json.ts","../src/schema.ts","../src/protocol/verify.ts","../src/common/immutable.ts","../src/common/random.ts"],"sourcesContent":["import type { JsonObject } from \"../protocol/types.js\";\n\nexport type HistoryError = {\n code: string;\n phase: string;\n message: string;\n path?: string;\n commitId?: string;\n entryId?: string;\n details?: Readonly<JsonObject>;\n};\nexport type Result<T, E = HistoryError> = { ok: true; value: T } | { ok: false; error: E };\nexport const ok = <T>(value: T): Result<T> => ({ ok: true, value });\nexport const error = (code: string, phase: string, path?: string): HistoryError => ({\n code,\n phase,\n message: code.replaceAll(\"_\", \" \").toLowerCase(),\n ...(path === undefined ? {} : { path }),\n});\nexport class Fault extends Error {\n constructor(readonly finding: HistoryError) {\n super(finding.code);\n }\n}\nexport function fail(code: string, phase = \"protocol\", path?: string): never {\n throw new Fault(error(code, phase, path));\n}\nexport function caught(cause: unknown, fallback: string, phase: string): HistoryError {\n return cause instanceof Fault ? cause.finding : error(fallback, phase);\n}\nexport function attempt<T>(\n body: () => T,\n fallback = \"SCHEMA_INVALID\",\n phase = \"protocol\",\n): Result<T> {\n try {\n return ok(body());\n } catch (cause) {\n return { ok: false, error: caught(cause, fallback, phase) };\n }\n}\n","import { attempt, fail, type Result } from \"../common/errors.js\";\nimport type { Json } from \"./types.js\";\nexport const utf8 = new TextEncoder();\nexport const text = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\nexport function unicode(value: string): boolean {\n for (let i = 0; i < value.length; i++) {\n const c = value.charCodeAt(i);\n if (c >= 0xd800 && c <= 0xdbff) {\n const next = value.charCodeAt(++i);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false;\n } else if (c >= 0xdc00 && c <= 0xdfff) return false;\n }\n return true;\n}\nexport function encodeJson(input: unknown, maxDepth = 64): Uint8Array {\n const active = new Set<object>();\n function encode(value: unknown, depth: number): string {\n if (value === null) return \"null\";\n if (typeof value === \"string\") {\n if (!unicode(value)) fail(\"JSON_INVALID\", \"input\");\n return JSON.stringify(value);\n }\n if (typeof value === \"boolean\") return String(value);\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || Object.is(value, -0)) fail(\"JSON_INVALID\", \"input\");\n return String(value);\n }\n if (!value || typeof value !== \"object\") fail(\"JSON_INVALID\", \"input\");\n if (depth + 1 > maxDepth) fail(\"RESOURCE_LIMIT\");\n const prototype = Object.getPrototypeOf(value);\n if (\n (Array.isArray(value) && prototype !== Array.prototype) ||\n (!Array.isArray(value) && prototype !== null && prototype !== Object.prototype) ||\n active.has(value)\n )\n fail(\"JSON_INVALID\", \"input\");\n const descriptors = Object.getOwnPropertyDescriptors(value);\n if (\n Object.getOwnPropertySymbols(value).length ||\n Object.values(descriptors).some((d) => !(\"value\" in d))\n )\n fail(\"JSON_INVALID\", \"input\");\n active.add(value);\n let output: string;\n if (Array.isArray(value)) {\n if (Object.keys(descriptors).length !== value.length + 1) fail(\"JSON_INVALID\", \"input\");\n const items: string[] = [];\n for (let i = 0; i < value.length; i++) {\n if (!Object.hasOwn(descriptors, String(i))) fail(\"JSON_INVALID\", \"input\");\n items.push(encode(descriptors[i].value, depth + 1));\n }\n output = `[${items.join(\",\")}]`;\n } else {\n output = `{${Object.keys(descriptors)\n .sort()\n .map((key) => `${encode(key, depth + 1)}:${encode(descriptors[key].value, depth + 1)}`)\n .join(\",\")}}`;\n }\n active.delete(value);\n return output;\n }\n return utf8.encode(encode(input, 0));\n}\nexport function canonicalize(value: unknown): Result<Uint8Array> {\n return attempt(() => encodeJson(value), \"JSON_INVALID\", \"input\");\n}\nfunction numberToken(token: string): number {\n const match = /^(-?)(\\d+)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/.exec(token)!;\n let digits = (match[2] + (match[3] ?? \"\")).replace(/^0+/, \"\");\n if (!digits) {\n if (match[1]) fail(\"JSON_INVALID\", \"input\");\n return 0;\n }\n const scale = Number(match[4] ?? 0) - (match[3]?.length ?? 0);\n if (!Number.isSafeInteger(scale)) fail(\"JSON_INVALID\", \"input\");\n if (scale < 0) {\n if (-scale > digits.length || !digits.endsWith(\"0\".repeat(-scale)))\n fail(\"JSON_INVALID\", \"input\");\n digits = digits.slice(0, scale);\n } else {\n if (digits.length + scale > 16) fail(\"JSON_INVALID\", \"input\");\n digits += \"0\".repeat(scale);\n }\n if (digits.length > 16 || (digits.length === 16 && digits > \"9007199254740991\"))\n fail(\"JSON_INVALID\", \"input\");\n return Number(`${match[1]}${digits}`);\n}\nexport function parseJson(bytes: Uint8Array, maxDepth = 64, maxBytes = 16 * 1024 * 1024): Json {\n if (bytes.length > maxBytes) fail(\"RESOURCE_LIMIT\");\n let source: string;\n try {\n source = text.decode(bytes);\n } catch {\n fail(\"JSON_INVALID\", \"input\");\n }\n if (source.charCodeAt(0) === 0xfeff) fail(\"JSON_INVALID\", \"input\");\n let offset = 0;\n function space() {\n while (offset < source.length && \" \\t\\n\\r\".includes(source[offset])) offset++;\n }\n function string(): string {\n const start = offset++;\n while (offset < source.length) {\n const c = source[offset++];\n if (c === '\"') {\n let value: string;\n try {\n value = JSON.parse(source.slice(start, offset));\n } catch {\n fail(\"JSON_INVALID\", \"input\");\n }\n if (!unicode(value)) fail(\"JSON_INVALID\", \"input\");\n return value;\n }\n if (c === \"\\\\\") offset++;\n }\n return fail(\"JSON_INVALID\", \"input\");\n }\n function value(depth: number): Json {\n space();\n const c = source[offset];\n if (c === '\"') return string();\n if (c === \"{\" || c === \"[\") {\n if (depth + 1 > maxDepth) fail(\"RESOURCE_LIMIT\");\n offset++;\n space();\n if (c === \"[\") {\n const result: Json[] = [];\n if (source[offset] === \"]\") {\n offset++;\n return result;\n }\n while (true) {\n result.push(value(depth + 1));\n space();\n if (source[offset] === \"]\") {\n offset++;\n return result;\n }\n if (source[offset++] !== \",\") fail(\"JSON_INVALID\", \"input\");\n }\n }\n const result: Record<string, Json> = Object.create(null);\n const keys = new Set<string>();\n if (source[offset] === \"}\") {\n offset++;\n return result;\n }\n while (true) {\n space();\n if (source[offset] !== '\"') fail(\"JSON_INVALID\", \"input\");\n const key = string();\n if (keys.has(key)) fail(\"JSON_INVALID\", \"input\");\n keys.add(key);\n space();\n if (source[offset++] !== \":\") fail(\"JSON_INVALID\", \"input\");\n result[key] = value(depth + 1);\n space();\n if (source[offset] === \"}\") {\n offset++;\n return result;\n }\n if (source[offset++] !== \",\") fail(\"JSON_INVALID\", \"input\");\n }\n }\n for (const [literal, result] of [\n [\"true\", true],\n [\"false\", false],\n [\"null\", null],\n ] as const)\n if (source.startsWith(literal, offset)) {\n offset += literal.length;\n return result;\n }\n const number = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/.exec(source.slice(offset));\n if (number) {\n offset += number[0].length;\n return numberToken(number[0]);\n }\n return fail(\"JSON_INVALID\", \"input\");\n }\n const result = value(0);\n space();\n if (offset !== source.length) fail(\"JSON_INVALID\", \"input\");\n return result;\n}\n","import { decodeBase64Url, validatePublicIdentity } from \"@ternent/identity\";\nimport { encodeJson } from \"./protocol/json.js\";\nimport { fail } from \"./common/errors.js\";\nimport type {\n LedgerSnapshot,\n LedgerLimits,\n LedgerAppendInput,\n LedgerEntrySubject,\n LedgerCommitSubject,\n} from \"./types.js\";\n\nconst defaults: LedgerLimits = {\n maxBytes: 16 * 1024 * 1024,\n maxCommits: 10_000,\n maxEntries: 100_000,\n maxDepth: 64,\n maxMetadataBytes: 64 * 1024,\n // Framework ciphertext is opaque JSON here; the total snapshot cap remains authoritative.\n maxPayloadBytes: 16 * 1024 * 1024,\n};\nexport function limits(input: Partial<LedgerLimits> = {}): LedgerLimits {\n if (\n !input ||\n typeof input !== \"object\" ||\n Array.isArray(input) ||\n Object.keys(input).some((key) => !Object.hasOwn(defaults, key))\n )\n fail(\"HOST_CONFIGURATION\", \"requirements\");\n const output = { ...defaults, ...input };\n if (Object.values(output).some((value) => !Number.isSafeInteger(value) || value <= 0))\n fail(\"HOST_CONFIGURATION\", \"requirements\");\n return output;\n}\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction closed(\n value: unknown,\n keys: readonly string[],\n path: string,\n): asserts value is Record<string, unknown> {\n if (\n !record(value) ||\n Object.keys(value).length !== keys.length ||\n keys.some((key) => !Object.hasOwn(value, key))\n )\n fail(\"SCHEMA_INVALID\", \"protocol\", path);\n}\nfunction id(value: unknown, kind: \"commit\" | \"entry\", path: string): void {\n if (typeof value !== \"string\" || !new RegExp(`^${kind}:[0-9a-f]{64}$`).test(value))\n fail(\"SCHEMA_INVALID\", \"protocol\", path);\n}\nexport function bytes(value: unknown, size: number, path: string): Uint8Array {\n if (typeof value !== \"string\") fail(\"SCHEMA_INVALID\", \"protocol\", path);\n const decoded = decodeBase64Url(value);\n if (!decoded.ok || decoded.value.length !== size) fail(\"SCHEMA_INVALID\", \"protocol\", path);\n return decoded.value;\n}\nexport function timestamp(value: unknown): asserts value is string {\n if (\n typeof value !== \"string\" ||\n !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/.test(value) ||\n !Number.isFinite(Date.parse(value)) ||\n new Date(value).toISOString() !== value\n )\n fail(\"SCHEMA_INVALID\", \"protocol\");\n}\nfunction metadata(value: unknown, lim: LedgerLimits): void {\n if (value !== null && !record(value)) fail(\"SCHEMA_INVALID\", \"protocol\");\n if (value !== null && encodeJson(value, lim.maxDepth).length > lim.maxMetadataBytes)\n fail(\"RESOURCE_LIMIT\", \"protocol\");\n}\nexport function appendInput(input: unknown, lim: LedgerLimits): asserts input is LedgerAppendInput {\n if (\n !record(input) ||\n Object.keys(input).some((key) => ![\"kind\", \"payload\", \"meta\", \"nonce\"].includes(key)) ||\n typeof input.kind !== \"string\" ||\n input.kind.length < 1 ||\n input.kind.length > 128\n )\n fail(\"SCHEMA_INVALID\", \"input\");\n if (input.nonce !== undefined) bytes(input.nonce, 16, \"/nonce\");\n metadata(input.meta ?? null, lim);\n if (encodeJson(input.payload ?? null, lim.maxDepth).length > lim.maxPayloadBytes)\n fail(\"RESOURCE_LIMIT\", \"input\");\n}\nexport function entrySubject(\n input: unknown,\n path: string,\n lim: LedgerLimits,\n): asserts input is LedgerEntrySubject {\n closed(\n input,\n [\"version\", \"parent\", \"nonce\", \"kind\", \"author\", \"authoredAt\", \"meta\", \"payload\"],\n path,\n );\n const subject = input;\n if (\n subject.version !== 1 ||\n typeof subject.kind !== \"string\" ||\n subject.kind.length < 1 ||\n subject.kind.length > 128 ||\n typeof subject.author !== \"string\"\n )\n fail(\"SCHEMA_INVALID\", \"protocol\", path);\n if (subject.parent !== null) id(subject.parent, \"commit\", `${path}/parent`);\n bytes(subject.nonce, 16, `${path}/nonce`);\n timestamp(subject.authoredAt);\n metadata(subject.meta, lim);\n closed(subject.payload, [\"type\", \"data\"], `${path}/payload`);\n if (subject.payload.type !== \"plain\") fail(\"ENTRY_KIND_UNSUPPORTED\", \"protocol\", path);\n if (encodeJson(subject.payload.data, lim.maxDepth).length > lim.maxPayloadBytes)\n fail(\"RESOURCE_LIMIT\", \"protocol\", path);\n}\nexport function commitSubject(\n input: unknown,\n path: string,\n lim: LedgerLimits,\n): asserts input is LedgerCommitSubject {\n closed(\n input,\n [\"version\", \"suite\", \"parent\", \"nonce\", \"signer\", \"committedAt\", \"entryIds\", \"metadata\"],\n path,\n );\n const subject = input;\n if (subject.version !== 1 || subject.suite !== \"ledger-ed25519-v1\")\n fail(\"SUITE_UNSUPPORTED\", \"protocol\", path);\n if (subject.parent !== null) id(subject.parent, \"commit\", `${path}/parent`);\n bytes(subject.nonce, 16, `${path}/nonce`);\n if (!record(subject.signer) || !validatePublicIdentity(subject.signer).ok)\n fail(\"IDENTITY_INVALID\", \"protocol\", path);\n timestamp(subject.committedAt);\n metadata(subject.metadata, lim);\n if (!Array.isArray(subject.entryIds) || subject.entryIds.length > lim.maxEntries)\n fail(\"SCHEMA_INVALID\", \"protocol\", path);\n\n subject.entryIds.forEach((entryId, index) => id(entryId, \"entry\", `${path}/entryIds/${index}`));\n}\nexport function snapshot(input: unknown, lim: LedgerLimits): asserts input is LedgerSnapshot {\n closed(input, [\"format\", \"version\", \"documentId\", \"head\", \"commits\", \"entries\"], \"\");\n if (input.format !== \"ledger\" || input.version !== 1) fail(\"PROTOCOL_UNSUPPORTED\", \"protocol\");\n id(input.documentId, \"commit\", \"/documentId\");\n id(input.head, \"commit\", \"/head\");\n if (!Array.isArray(input.commits) || !input.commits.length || !Array.isArray(input.entries))\n fail(\"SCHEMA_INVALID\", \"protocol\");\n if (input.commits.length > lim.maxCommits || input.entries.length > lim.maxEntries)\n fail(\"RESOURCE_LIMIT\", \"protocol\");\n for (const [index, entry] of input.entries.entries()) {\n const path = `/entries/${index}`;\n closed(entry, [\"id\", \"subject\"], path);\n id(entry.id, \"entry\", `${path}/id`);\n entrySubject(entry.subject, `${path}/subject`, lim);\n }\n let offset = 0;\n for (const [index, commit] of input.commits.entries()) {\n const path = `/commits/${index}`;\n closed(commit, [\"id\", \"subject\", \"signature\"], path);\n id(commit.id, \"commit\", `${path}/id`);\n commitSubject(commit.subject, `${path}/subject`, lim);\n const subject = commit.subject;\n if (index > 0 && !subject.entryIds.length) fail(\"SCHEMA_INVALID\", \"protocol\", path);\n for (const [entryIndex, entryId] of subject.entryIds.entries()) {\n id(entryId, \"entry\", `${path}/subject/entryIds/${entryIndex}`);\n const entry = input.entries[offset++];\n if (record(entry) && record(entry.subject) && entry.subject.author !== subject.signer.id)\n fail(\"IDENTITY_MISMATCH\", \"protocol\", `/entries/${offset - 1}/subject/author`);\n }\n bytes(commit.signature, 64, `${path}/signature`);\n }\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { validatePublicIdentity, verifySignature } from \"@ternent/identity\";\nimport { attempt, caught, fail, ok, type Result } from \"../common/errors.js\";\nimport { encodeJson, parseJson, utf8 } from \"./json.js\";\nimport type { CommitId, EntryId, Relationship, VerificationReport } from \"./types.js\";\n\nimport * as schema from \"../schema.js\";\nimport type {\n LedgerSnapshot,\n LedgerLimits,\n LedgerEntrySubject,\n LedgerCommitSubject,\n} from \"../types.js\";\nconst domains = {\n entry: \"ledger.entry/1\\0\",\n commit: \"ledger.commit/1\\0\",\n signature: \"ledger.signature/1\\0\",\n};\nconst hexadecimal = (value: Uint8Array) =>\n Array.from(value, (v) => v.toString(16).padStart(2, \"0\")).join(\"\");\nexport function concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a);\n out.set(b, a.length);\n return out;\n}\n\nexport function signatureMessage(subject: LedgerCommitSubject, depth = 64): Uint8Array {\n return concat(utf8.encode(domains.signature), encodeJson(subject, depth));\n}\nexport function identifier(subject: LedgerEntrySubject, kind: \"entry\", depth?: number): EntryId;\nexport function identifier(subject: LedgerCommitSubject, kind: \"commit\", depth?: number): CommitId;\nexport function identifier(\n subject: LedgerEntrySubject | LedgerCommitSubject,\n kind: \"entry\" | \"commit\",\n depth = 64,\n): EntryId | CommitId {\n return `${kind}:${hexadecimal(sha256(concat(utf8.encode(domains[kind]), encodeJson(subject, depth))))}`;\n}\nconst unsupported = new Set([\n \"PROTOCOL_UNSUPPORTED\",\n \"SUITE_UNSUPPORTED\",\n \"ENTRY_KIND_UNSUPPORTED\",\n \"RESOURCE_LIMIT\",\n \"HOST_CONFIGURATION\",\n]);\nexport async function inspectProtocol(\n bytes: Uint8Array,\n options: { limits?: Partial<LedgerLimits> } = {},\n): Promise<{\n report: VerificationReport;\n snapshot?: LedgerSnapshot;\n untrustedHistory: readonly LedgerSnapshot[\"commits\"][number][];\n}> {\n const report: VerificationReport = {\n integrity: \"invalid\",\n documentId: null,\n head: null,\n checkedCommits: 0,\n checkedEntries: 0,\n findings: [],\n };\n let untrustedHistory: readonly LedgerSnapshot[\"commits\"][number][] = [];\n try {\n const lim = schema.limits(options.limits);\n if (bytes.byteLength > lim.maxBytes) fail(\"RESOURCE_LIMIT\");\n const parsed = parseJson(new Uint8Array(bytes), lim.maxDepth, lim.maxBytes);\n schema.snapshot(parsed, lim);\n // Parsed envelopes are inspection evidence; only snapshot grants verified input.\n untrustedHistory = parsed.commits;\n report.documentId = parsed.documentId;\n report.head = parsed.head;\n if (encodeJson(parsed, lim.maxDepth).length > lim.maxBytes) fail(\"RESOURCE_LIMIT\");\n const entryIds = new Set<string>(),\n commitIds = new Set<string>(),\n references = new Set<string>();\n for (let i = 0; i < parsed.entries.length; i++) {\n const record = parsed.entries[i];\n if (entryIds.has(record.id)) fail(\"DUPLICATE_RECORD\", \"protocol\", `/entries/${i}/id`);\n entryIds.add(record.id);\n }\n const expected: EntryId[] = [];\n const referencePaths: string[] = [];\n for (let i = 0; i < parsed.commits.length; i++) {\n const record = parsed.commits[i];\n if (commitIds.has(record.id)) fail(\"DUPLICATE_RECORD\", \"protocol\", `/commits/${i}/id`);\n commitIds.add(record.id);\n for (let j = 0; j < record.subject.entryIds.length; j++) {\n const id = record.subject.entryIds[j];\n if (references.has(id))\n fail(\"DUPLICATE_RECORD\", \"protocol\", `/commits/${i}/subject/entryIds/${j}`);\n references.add(id);\n expected.push(id);\n referencePaths.push(`/commits/${i}/subject/entryIds/${j}`);\n }\n }\n for (let i = 0; i < expected.length; i++)\n if (!entryIds.has(expected[i])) fail(\"ENTRY_MISSING\", \"protocol\", referencePaths[i]);\n for (let i = 0; i < parsed.entries.length; i++)\n if (!references.has(parsed.entries[i].id))\n fail(\"UNREFERENCED_RECORD\", \"protocol\", `/entries/${i}`);\n for (let i = 0; i < expected.length; i++)\n if (parsed.entries[i]?.id !== expected[i]) fail(\"ENTRY_ORDER\", \"protocol\", `/entries/${i}`);\n const selected = parsed.commits.findIndex((commit) => commit.id === parsed.head);\n const linear = parsed.commits.every(\n (commit, index) =>\n commit.subject.parent === (index === 0 ? null : parsed.commits[index - 1].id),\n );\n if (selected >= 0 && selected < parsed.commits.length - 1 && !linear) {\n const records = new Map(parsed.commits.map((commit) => [commit.id, commit]));\n const reachable = new Set<string>();\n let cursor: CommitId | null = parsed.head;\n while (cursor !== null && records.has(cursor) && !reachable.has(cursor)) {\n reachable.add(cursor);\n cursor = records.get(cursor)!.subject.parent;\n }\n const detached = parsed.commits.findIndex((commit) => !reachable.has(commit.id));\n if (detached >= 0) fail(\"UNREFERENCED_RECORD\", \"protocol\", `/commits/${detached}`);\n }\n for (let i = 0; i < parsed.entries.length; i++) {\n if (identifier(parsed.entries[i].subject, \"entry\", lim.maxDepth) !== parsed.entries[i].id)\n fail(\"HASH_MISMATCH\", \"protocol\", `/entries/${i}/id`);\n report.checkedEntries++;\n }\n for (let i = 0; i < parsed.commits.length; i++)\n if (identifier(parsed.commits[i].subject, \"commit\", lim.maxDepth) !== parsed.commits[i].id)\n fail(\"HASH_MISMATCH\", \"protocol\", `/commits/${i}/id`);\n let offset = 0;\n for (let i = 0; i < parsed.commits.length; i++) {\n const subject = parsed.commits[i].subject;\n if (subject.parent !== (i === 0 ? null : parsed.commits[i - 1].id))\n fail(\"LINK_INVALID\", \"protocol\", `/commits/${i}/subject/parent`);\n const nonces = new Set<string>();\n for (let j = 0; j < subject.entryIds.length; j++) {\n const entry = parsed.entries[offset++];\n if (entry.subject.parent !== subject.parent)\n fail(\"LINK_INVALID\", \"protocol\", `/entries/${offset - 1}/subject/parent`);\n if (nonces.has(entry.subject.nonce))\n fail(\"SCHEMA_INVALID\", \"protocol\", `/entries/${offset - 1}/subject/nonce`);\n nonces.add(entry.subject.nonce);\n }\n }\n if (parsed.documentId !== parsed.commits[0].id) fail(\"HEAD_INVALID\", \"protocol\", \"/documentId\");\n if (parsed.head !== parsed.commits.at(-1)!.id) fail(\"HEAD_INVALID\", \"protocol\", \"/head\");\n for (let i = 0; i < parsed.commits.length; i++) {\n const record = parsed.commits[i];\n if (!validatePublicIdentity(record.subject.signer).ok)\n fail(\"IDENTITY_INVALID\", \"protocol\", `/commits/${i}/subject/signer`);\n const valid = await verifySignature(\n record.subject.signer,\n signatureMessage(record.subject, lim.maxDepth),\n schema.bytes(record.signature, 64, `/commits/${i}/signature`),\n );\n if (!valid.ok || !valid.value)\n fail(\"SIGNATURE_INVALID\", \"protocol\", `/commits/${i}/signature`);\n report.checkedCommits++;\n }\n report.integrity = \"valid\";\n return { report, snapshot: parsed, untrustedHistory };\n } catch (cause) {\n const finding = caught(cause, \"SCHEMA_INVALID\", \"protocol\");\n report.integrity = unsupported.has(finding.code) ? \"unsupported\" : \"invalid\";\n report.findings = [finding];\n return { report, untrustedHistory };\n }\n}\nexport async function verifyDocument(\n bytes: Uint8Array,\n options?: { limits?: Partial<LedgerLimits> },\n): Promise<VerificationReport> {\n return (await inspectProtocol(bytes, options)).report;\n}\nexport async function compareSnapshots(\n a: Uint8Array,\n b: Uint8Array,\n options?: { limits?: Partial<LedgerLimits> },\n): Promise<Result<Relationship>> {\n const left = await inspectProtocol(a, options),\n right = await inspectProtocol(b, options);\n if (!left.snapshot) return { ok: false, error: left.report.findings[0] };\n if (!right.snapshot) return { ok: false, error: right.report.findings[0] };\n const x = left.snapshot,\n y = right.snapshot;\n return ok(\n x.documentId !== y.documentId\n ? \"unrelated\"\n : x.head === y.head\n ? \"equal\"\n : y.commits.some((c) => c.id === x.head)\n ? \"behind\"\n : x.commits.some((c) => c.id === y.head)\n ? \"ahead\"\n : \"diverged\",\n );\n}\n\nexport const inspectLedger = inspectProtocol;\nexport const ledgerSignatureMessage = signatureMessage;\nexport const verifyLedger = verifyDocument;\nexport const compareLedgers = compareSnapshots;\n/** Ordered records from a verified snapshot; traversal does not itself establish trust. */\nexport function* orderedEntries(snapshot: LedgerSnapshot) {\n let offset = 0;\n for (const commit of snapshot.commits)\n for (let index = 0; index < commit.subject.entryIds.length; index++)\n yield { commit, entry: snapshot.entries[offset++] };\n}\nexport function hashLedgerEntry(subject: LedgerEntrySubject) {\n return attempt(() => {\n const safe = parseJson(encodeJson(subject));\n schema.entrySubject(safe, \"\", schema.limits());\n return identifier(safe, \"entry\");\n });\n}\nexport function hashLedgerCommit(subject: LedgerCommitSubject) {\n return attempt(() => {\n const safe = parseJson(encodeJson(subject));\n schema.commitSubject(safe, \"\", schema.limits());\n return identifier(safe, \"commit\");\n });\n}\n","export function freeze<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const item of Object.values(value)) freeze(item);\n Object.freeze(value);\n }\n return value;\n}\nexport function detached<T>(value: T): T {\n return freeze(structuredClone(value));\n}\n","import { encodeBase64Url } from \"@ternent/identity\";\nexport function nonce(): string {\n return encodeBase64Url(crypto.getRandomValues(new Uint8Array(16)));\n}\n"],"mappings":";;;;AAYA,MAAa,MAAS,WAAyB;CAAE,IAAI;CAAM;AAAM;AACjE,MAAa,SAAS,MAAc,OAAe,UAAiC;CAClF;CACA;CACA,SAAS,KAAK,WAAW,KAAK,GAAG,CAAC,CAAC,YAAY;CAC/C,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,KAAK;AACvC;AACA,IAAa,QAAb,cAA2B,MAAM;CACV;CAArB,YAAY,AAAS,SAAuB;EAC1C,MAAM,QAAQ,IAAI;EADC;CAErB;AACF;AACA,SAAgB,KAAK,MAAc,QAAQ,YAAY,MAAsB;CAC3E,MAAM,IAAI,MAAM,MAAM,MAAM,OAAO,IAAI,CAAC;AAC1C;AACA,SAAgB,OAAO,OAAgB,UAAkB,OAA6B;CACpF,OAAO,iBAAiB,QAAQ,MAAM,UAAU,MAAM,UAAU,KAAK;AACvE;AACA,SAAgB,QACd,MACA,WAAW,kBACX,QAAQ,YACG;CACX,IAAI;EACF,OAAO,GAAG,KAAK,CAAC;CAClB,SAAS,OAAO;EACd,OAAO;GAAE,IAAI;GAAO,OAAO,OAAO,OAAO,UAAU,KAAK;EAAE;CAC5D;AACF;;;ACtCA,MAAa,OAAO,IAAI,YAAY;AACpC,MAAa,OAAO,IAAI,YAAY,SAAS;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC;AAC7E,SAAgB,QAAQ,OAAwB;CAC9C,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,IAAI,MAAM,WAAW,CAAC;EAC5B,IAAI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