@mikeargento/bitgraph-verify 1.3.0 → 1.5.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/dist/fuse.js ADDED
@@ -0,0 +1,688 @@
1
+ // Copyright (c) 2024-2026 Mike Argento. Licensed under the MIT License. See LICENSE.
2
+ /**
3
+ * BitGraph Fuse, profile `bitgraph-fuse/1`: construction and parsing.
4
+ *
5
+ * A fused artifact is a file that contains a commitment to a signed slot
6
+ * allocation obtained BEFORE the file was finished. The ordinary bitgraph/1
7
+ * primitive then commits the file's digest exactly as it commits any digest.
8
+ * A valid fused proof therefore bounds the file from below (the slot) and from
9
+ * above (the commit): the exact fused bytes could not feasibly have been
10
+ * finalized before their slot allocation and were committed no later than
11
+ * their commit position.
12
+ *
13
+ * Everything a verifier needs to REBUILD a fused artifact from an original and
14
+ * a proof lives here, which is why it is in the MIT package: the slot record
15
+ * hash (the enclave's own canonical subset), the commitment, and a registry of
16
+ * placements that say byte for byte how the commitment and the origin digest
17
+ * were placed. Nothing here talks to a service.
18
+ *
19
+ * Definitions (spec 3.5):
20
+ * slotRecordHash = SHA256(canonical slot record body) 32 bytes
21
+ * slotCommitment = SHA256(UTF8("bitgraph-fuse/1") || 0x00 || slotRecordHash || nonce)
22
+ * with the nonce as its raw 32 bytes. The raw nonce never enters a fused file;
23
+ * only the commitment does, so a partially written file cannot be used to
24
+ * claim the slot.
25
+ */
26
+ import { sha256 } from "@noble/hashes/sha256";
27
+ import { canonicalize } from "./canonical.js";
28
+ // ---------------------------------------------------------------------------
29
+ // Constants
30
+ // ---------------------------------------------------------------------------
31
+ export const FUSE_PROFILE = "bitgraph-fuse/1";
32
+ /** Domain separation prefix: the 15 profile bytes followed by one zero byte. */
33
+ export const FUSE_DOMAIN = (() => {
34
+ const label = new TextEncoder().encode(FUSE_PROFILE);
35
+ const out = new Uint8Array(label.length + 1);
36
+ out.set(label, 0);
37
+ out[label.length] = 0x00;
38
+ return out;
39
+ })();
40
+ /**
41
+ * The signed attribution name that marks a fused proof (spec 6.5): the profile
42
+ * id itself, the stable wire identifier of this construction. A product name
43
+ * may change; the v1 wire identifier does not (ruled 2026-09-03).
44
+ */
45
+ export const FUSE_ATTRIBUTION_NAME = FUSE_PROFILE;
46
+ /** Trailer placement: 8 ASCII magic bytes, 8 reserved zero bytes, 32 commitment bytes. */
47
+ export const TRAILER_MAGIC = "BGFUSE01";
48
+ export const TRAILER_LENGTH = 48;
49
+ /** Fixed paths inside a container/1 archive. */
50
+ export const CONTAINER_MANIFEST_PATH = "bitgraph-fuse/manifest.json";
51
+ export const CONTAINER_ORIGINAL_PATH = "bitgraph-fuse/original";
52
+ // ---------------------------------------------------------------------------
53
+ // Byte helpers (pure JS, so the module runs in browsers and Node alike)
54
+ // ---------------------------------------------------------------------------
55
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
56
+ const B64_LOOKUP = {};
57
+ for (let i = 0; i < B64.length; i++)
58
+ B64_LOOKUP[B64[i]] = i;
59
+ export function bytesToBase64(bytes) {
60
+ let out = "";
61
+ for (let i = 0; i < bytes.length; i += 3) {
62
+ const a = bytes[i];
63
+ const b = i + 1 < bytes.length ? bytes[i + 1] : 0;
64
+ const c = i + 2 < bytes.length ? bytes[i + 2] : 0;
65
+ out += B64[a >> 2] + B64[((a & 3) << 4) | (b >> 4)];
66
+ out += i + 1 < bytes.length ? B64[((b & 15) << 2) | (c >> 6)] : "=";
67
+ out += i + 2 < bytes.length ? B64[c & 63] : "=";
68
+ }
69
+ return out;
70
+ }
71
+ /** Strict standard base64 (RFC 4648 section 4): no whitespace, no URL-safe alphabet, correct padding. */
72
+ export function base64ToBytes(b64) {
73
+ if (typeof b64 !== "string" || b64.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(b64))
74
+ return null;
75
+ const pad = b64.endsWith("==") ? 2 : b64.endsWith("=") ? 1 : 0;
76
+ const out = new Uint8Array((b64.length / 4) * 3 - pad);
77
+ let o = 0;
78
+ for (let i = 0; i < b64.length; i += 4) {
79
+ const n = (B64_LOOKUP[b64[i]] << 18) |
80
+ (B64_LOOKUP[b64[i + 1]] << 12) |
81
+ ((b64[i + 2] === "=" ? 0 : B64_LOOKUP[b64[i + 2]]) << 6) |
82
+ (b64[i + 3] === "=" ? 0 : B64_LOOKUP[b64[i + 3]]);
83
+ out[o++] = (n >> 16) & 255;
84
+ if (o < out.length)
85
+ out[o++] = (n >> 8) & 255;
86
+ if (o < out.length)
87
+ out[o++] = n & 255;
88
+ }
89
+ // Reject non-canonical padding bits (e.g. "AQ=" style trailing garbage).
90
+ if (bytesToBase64(out) !== b64)
91
+ return null;
92
+ return out;
93
+ }
94
+ export function bytesToHex(bytes) {
95
+ let s = "";
96
+ for (const b of bytes)
97
+ s += (b < 16 ? "0" : "") + b.toString(16);
98
+ return s;
99
+ }
100
+ /** Lowercase hex only; uppercase is rejected so one digest has one spelling. */
101
+ export function hexToBytes(hex) {
102
+ if (typeof hex !== "string" || hex.length % 2 !== 0 || !/^[0-9a-f]*$/.test(hex))
103
+ return null;
104
+ const out = new Uint8Array(hex.length / 2);
105
+ for (let i = 0; i < out.length; i++)
106
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
107
+ return out;
108
+ }
109
+ export function bytesEqual(a, b) {
110
+ if (a.length !== b.length)
111
+ return false;
112
+ let diff = 0;
113
+ for (let i = 0; i < a.length; i++)
114
+ diff |= a[i] ^ b[i];
115
+ return diff === 0;
116
+ }
117
+ function concat(...parts) {
118
+ let n = 0;
119
+ for (const p of parts)
120
+ n += p.length;
121
+ const out = new Uint8Array(n);
122
+ let o = 0;
123
+ for (const p of parts) {
124
+ out.set(p, o);
125
+ o += p.length;
126
+ }
127
+ return out;
128
+ }
129
+ const utf8 = (s) => new TextEncoder().encode(s);
130
+ // ---------------------------------------------------------------------------
131
+ // Slot record hash and slot commitment
132
+ // ---------------------------------------------------------------------------
133
+ /**
134
+ * The enclave's canonical slot body: the signed subset of the slot record,
135
+ * excluding signatureB64, with `time` and `chainId` present only when the
136
+ * record carries them. Identical to the reconstruction in verifier.ts
137
+ * (verifySlotAllocation) and to the enclave's own slotBody. There is exactly
138
+ * one serialization of a slot record; this is it.
139
+ */
140
+ export function canonicalSlotBody(slot) {
141
+ return {
142
+ version: slot.version,
143
+ nonceB64: slot.nonceB64,
144
+ counter: slot.counter,
145
+ ...(slot.time !== undefined ? { time: slot.time } : {}),
146
+ epochId: slot.epochId,
147
+ publicKeyB64: slot.publicKeyB64,
148
+ ...(slot.chainId ? { chainId: slot.chainId } : {}),
149
+ };
150
+ }
151
+ /** SHA-256 of the canonical slot body; equals the proof's commit.slotHashB64. */
152
+ export function computeSlotRecordHash(slot) {
153
+ return sha256(canonicalize(canonicalSlotBody(slot)));
154
+ }
155
+ /** The exact preimage of the commitment, for vectors and audits: domain || slotRecordHash || nonce. */
156
+ export function slotCommitmentPreimage(slot) {
157
+ const nonce = base64ToBytes(slot.nonceB64);
158
+ if (nonce === null || nonce.length !== 32) {
159
+ throw new TypeError("slot.nonceB64 must decode to exactly 32 bytes");
160
+ }
161
+ return concat(FUSE_DOMAIN, computeSlotRecordHash(slot), nonce);
162
+ }
163
+ /** slotCommitment = SHA256(domain || slotRecordHash || nonce). */
164
+ export function computeSlotCommitment(slot) {
165
+ return sha256(slotCommitmentPreimage(slot));
166
+ }
167
+ /** Build the canonical Form C payload bytes (spec 6.2). Digests are lowercase hex. */
168
+ export function buildFusePayload(commitment, originDigest) {
169
+ if (commitment.length !== 32)
170
+ throw new TypeError("commitment must be 32 bytes");
171
+ if (originDigest !== undefined && originDigest.length !== 32)
172
+ throw new TypeError("originDigest must be 32 bytes");
173
+ const payload = {
174
+ type: FUSE_PROFILE,
175
+ ...(originDigest !== undefined ? { origin: { algorithm: "sha256", digest: bytesToHex(originDigest) } } : {}),
176
+ slotCommitment: { algorithm: "sha256", digest: bytesToHex(commitment) },
177
+ };
178
+ return canonicalize(payload);
179
+ }
180
+ function isPlainObject(x) {
181
+ return x !== null && typeof x === "object" && !Array.isArray(x) && Object.getPrototypeOf(x) === Object.prototype;
182
+ }
183
+ function readDigestField(x) {
184
+ if (!isPlainObject(x))
185
+ return null;
186
+ const keys = Object.keys(x);
187
+ if (keys.length !== 2 || x["algorithm"] !== "sha256" || typeof x["digest"] !== "string")
188
+ return null;
189
+ const bytes = hexToBytes(x["digest"]);
190
+ return bytes !== null && bytes.length === 32 ? bytes : null;
191
+ }
192
+ /**
193
+ * Strict parse of Form C bytes. The bytes must be valid UTF-8 JSON, a plain
194
+ * object with exactly the allowed keys, the profile type, lowercase-hex
195
+ * 32-byte digests, and must equal their own re-canonicalization byte for byte
196
+ * (which rejects whitespace, key-order games, and duplicate keys, since a
197
+ * duplicate cannot survive a round trip). Returns null on any deviation.
198
+ */
199
+ export function parseFusePayload(bytes) {
200
+ let text;
201
+ try {
202
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
203
+ }
204
+ catch {
205
+ return null;
206
+ }
207
+ let parsed;
208
+ try {
209
+ parsed = JSON.parse(text);
210
+ }
211
+ catch {
212
+ return null;
213
+ }
214
+ if (!isPlainObject(parsed))
215
+ return null;
216
+ const keys = Object.keys(parsed).sort();
217
+ const allowed = keys.length === 2 ? ["slotCommitment", "type"] : keys.length === 3 ? ["origin", "slotCommitment", "type"] : null;
218
+ if (allowed === null || keys.join(",") !== allowed.join(","))
219
+ return null;
220
+ if (parsed["type"] !== FUSE_PROFILE)
221
+ return null;
222
+ const commitment = readDigestField(parsed["slotCommitment"]);
223
+ if (commitment === null)
224
+ return null;
225
+ let originDigest;
226
+ if ("origin" in parsed) {
227
+ const o = readDigestField(parsed["origin"]);
228
+ if (o === null)
229
+ return null;
230
+ originDigest = o;
231
+ }
232
+ if (!bytesEqual(buildFusePayload(commitment, originDigest), bytes))
233
+ return null;
234
+ return originDigest !== undefined ? { commitment, originDigest } : { commitment };
235
+ }
236
+ // ---------------------------------------------------------------------------
237
+ // Minimal deterministic ustar (POSIX.1-1988) for container/1
238
+ // ---------------------------------------------------------------------------
239
+ const BLOCK = 512;
240
+ const MAX_ENTRY = 0o77777777777; // 8 GiB - 1, the 11-digit octal size field
241
+ function octal(n, width) {
242
+ const s = n.toString(8).padStart(width - 1, "0") + "\0";
243
+ if (s.length !== width)
244
+ throw new RangeError("field overflow");
245
+ return utf8(s);
246
+ }
247
+ function ustarHeader(name, size) {
248
+ if (size > MAX_ENTRY)
249
+ throw new RangeError("container/1 entries are limited to 8 GiB");
250
+ const h = new Uint8Array(BLOCK);
251
+ const nameBytes = utf8(name);
252
+ if (nameBytes.length > 100)
253
+ throw new RangeError("ustar name too long");
254
+ h.set(nameBytes, 0);
255
+ h.set(utf8("0000644\0"), 100); // mode
256
+ h.set(utf8("0000000\0"), 108); // uid
257
+ h.set(utf8("0000000\0"), 116); // gid
258
+ h.set(octal(size, 12), 124); // size
259
+ h.set(utf8("00000000000\0"), 136); // mtime: 0, the epoch; nothing about a clock enters the bytes
260
+ h.set(utf8(" "), 148); // checksum placeholder
261
+ h[156] = 0x30; // typeflag '0' regular file
262
+ h.set(utf8("ustar\0"), 257); // magic
263
+ h.set(utf8("00"), 263); // version
264
+ // uname, gname, devmajor, devminor, prefix: all zero
265
+ let sum = 0;
266
+ for (const b of h)
267
+ sum += b;
268
+ h.set(utf8(sum.toString(8).padStart(6, "0") + "\0 "), 148);
269
+ return h;
270
+ }
271
+ function padTo(n) {
272
+ return (BLOCK - (n % BLOCK)) % BLOCK;
273
+ }
274
+ /** Build a container/1 archive: manifest entry, then the original, then two zero blocks. */
275
+ function buildContainer(original, manifest) {
276
+ return concat(ustarHeader(CONTAINER_MANIFEST_PATH, manifest.length), manifest, new Uint8Array(padTo(manifest.length)), ustarHeader(CONTAINER_ORIGINAL_PATH, original.length), original, new Uint8Array(padTo(original.length)), new Uint8Array(BLOCK * 2));
277
+ }
278
+ /** Parse a ustar stream into entries; null when malformed. Does not accept extensions. */
279
+ function parseTar(bytes) {
280
+ const entries = [];
281
+ let off = 0;
282
+ while (off + BLOCK <= bytes.length) {
283
+ const h = bytes.subarray(off, off + BLOCK);
284
+ if (h.every((b) => b === 0)) {
285
+ // End marker: two zero blocks, then nothing.
286
+ const rest = bytes.subarray(off);
287
+ if (rest.length !== BLOCK * 2 || !rest.every((b) => b === 0))
288
+ return null;
289
+ return entries;
290
+ }
291
+ const nameEnd = h.indexOf(0, 0);
292
+ const name = new TextDecoder().decode(h.subarray(0, nameEnd < 0 || nameEnd > 100 ? 100 : nameEnd));
293
+ const sizeText = new TextDecoder().decode(h.subarray(124, 135));
294
+ if (!/^[0-7]{11}$/.test(sizeText))
295
+ return null;
296
+ const size = parseInt(sizeText, 8);
297
+ if (off + BLOCK + size > bytes.length)
298
+ return null;
299
+ const data = bytes.subarray(off + BLOCK, off + BLOCK + size);
300
+ entries.push({ name, data, headerBytes: h });
301
+ off += BLOCK + size + padTo(size);
302
+ }
303
+ return null;
304
+ }
305
+ const trailer1 = {
306
+ id: "trailer/1",
307
+ form: "A",
308
+ byteExact: true,
309
+ build({ original, commitment }) {
310
+ if (original === undefined)
311
+ throw new TypeError("trailer/1 requires the original bytes");
312
+ if (commitment.length !== 32)
313
+ throw new TypeError("commitment must be 32 bytes");
314
+ return concat(original, utf8(TRAILER_MAGIC), new Uint8Array(8), commitment);
315
+ },
316
+ locate(fused) {
317
+ if (fused.length < TRAILER_LENGTH)
318
+ return null;
319
+ const t = fused.subarray(fused.length - TRAILER_LENGTH);
320
+ if (!bytesEqual(t.subarray(0, 8), utf8(TRAILER_MAGIC)))
321
+ return null;
322
+ if (!t.subarray(8, 16).every((b) => b === 0))
323
+ return null;
324
+ return { commitment: new Uint8Array(t.subarray(16, 48)), originalBytes: fused.subarray(0, fused.length - TRAILER_LENGTH) };
325
+ },
326
+ };
327
+ const container1 = {
328
+ id: "container/1",
329
+ form: "B",
330
+ byteExact: true,
331
+ build({ original, originDigest, commitment }) {
332
+ if (original === undefined)
333
+ throw new TypeError("container/1 requires the original bytes");
334
+ const digest = originDigest ?? sha256(original);
335
+ return buildContainer(original, buildFusePayload(commitment, digest));
336
+ },
337
+ locate(fused) {
338
+ const entries = parseTar(fused);
339
+ if (entries === null || entries.length !== 2)
340
+ return null;
341
+ const [m, o] = entries;
342
+ if (m.name !== CONTAINER_MANIFEST_PATH || o.name !== CONTAINER_ORIGINAL_PATH)
343
+ return null;
344
+ const payload = parseFusePayload(m.data);
345
+ if (payload === null || payload.originDigest === undefined)
346
+ return null;
347
+ // The archive must be the one this module would build: headers included.
348
+ const rebuilt = buildContainer(o.data, m.data);
349
+ if (!bytesEqual(rebuilt, fused))
350
+ return null;
351
+ return { commitment: payload.commitment, originDigest: payload.originDigest, originalBytes: o.data };
352
+ },
353
+ };
354
+ const produced1 = {
355
+ id: "produced/1",
356
+ form: "C",
357
+ byteExact: false,
358
+ build({ original, originDigest, commitment }) {
359
+ if (original !== undefined)
360
+ throw new TypeError("produced/1 takes no original; pass originDigest for a source reference");
361
+ return buildFusePayload(commitment, originDigest);
362
+ },
363
+ locate(fused) {
364
+ const payload = parseFusePayload(fused);
365
+ if (payload === null)
366
+ return null;
367
+ return payload.originDigest !== undefined
368
+ ? { commitment: payload.commitment, originDigest: payload.originDigest }
369
+ : { commitment: payload.commitment };
370
+ },
371
+ };
372
+ /** Registered placements in the fixed order a verifier tries them when none is declared. */
373
+ export const PLACEMENTS = Object.freeze([trailer1, container1, produced1]);
374
+ // ---------------------------------------------------------------------------
375
+ // Set manifest (placement set/1): N files fused under ONE slot
376
+ // ---------------------------------------------------------------------------
377
+ //
378
+ // A set is N files fused under one slot. The commitment c is computed once
379
+ // from the one slot record; every member's fused bytes carry c via that
380
+ // member's own placement (trailer/1 or container/1, chosen per file as
381
+ // today); and the COMMITTED ARTIFACT is a canonical manifest listing the
382
+ // members' fused digests, origin digests and placement ids, plus c itself.
383
+ // The manifest is a Form C artifact under the placement id "set/1".
384
+ //
385
+ // Its canonical encoding is load-bearing: one committed hash must stand for
386
+ // exactly one member list. buildSetManifest is the single source of the byte
387
+ // layout (rows strictly ascending by artifact digest, lowercase hex, sorted
388
+ // keys, no whitespace) and parseSetManifest accepts nothing that is not byte
389
+ // for byte equal to its own rebuild. Anything outside that domain is refused,
390
+ // never normalized.
391
+ export const SET_PLACEMENT_ID = "set/1";
392
+ /**
393
+ * The proof.metadata key under which a set proof carries its manifest as a
394
+ * parsed plain object: the profile id itself, namespaced so it cannot collide
395
+ * with a site's own metadata keys. metadata is UNSIGNED and advisory. The
396
+ * manifest is protected only because its canonical bytes must hash to the
397
+ * signed artifact digest, which verifyFuseMember checks before reading a row.
398
+ */
399
+ export const SET_METADATA_KEY = FUSE_PROFILE;
400
+ /** A placement id is a lowercase name, a slash, and a positive version: "trailer/1". */
401
+ const PLACEMENT_ID_PATTERN = /^[a-z0-9][a-z0-9-]*\/[1-9][0-9]*$/;
402
+ /**
403
+ * Build the canonical set manifest bytes. Rows are sorted strictly ascending
404
+ * by artifact digest (byte order, which is the lexicographic order of the
405
+ * lowercase hex), so the same members in any input order give the same bytes.
406
+ * Throws on a commitment or digest that is not 32 bytes, an empty list, a
407
+ * malformed placement id, a member placement of "set/1" (no nesting in v1),
408
+ * or a duplicate artifact digest. Duplicate ORIGIN digests are permitted: one
409
+ * original fused two ways is two members with two artifact digests.
410
+ */
411
+ export function buildSetManifest(commitment, members) {
412
+ if (commitment.length !== 32)
413
+ throw new TypeError("commitment must be 32 bytes");
414
+ if (members.length === 0)
415
+ throw new TypeError("a set lists at least one member");
416
+ const rows = [];
417
+ const seen = new Set();
418
+ for (const m of members) {
419
+ if (m.artifact.length !== 32)
420
+ throw new TypeError("member artifact digest must be 32 bytes");
421
+ if (m.origin.length !== 32)
422
+ throw new TypeError("member origin digest must be 32 bytes");
423
+ if (!PLACEMENT_ID_PATTERN.test(m.placement))
424
+ throw new TypeError(`member placement "${m.placement}" is not a placement id`);
425
+ if (m.placement === SET_PLACEMENT_ID)
426
+ throw new TypeError("a set cannot list a set as a member");
427
+ const artifact = bytesToHex(m.artifact);
428
+ if (seen.has(artifact))
429
+ throw new TypeError(`duplicate member artifact digest ${artifact}`);
430
+ seen.add(artifact);
431
+ rows.push({
432
+ artifact: { algorithm: "sha256", digest: artifact },
433
+ origin: { algorithm: "sha256", digest: bytesToHex(m.origin) },
434
+ placement: m.placement,
435
+ });
436
+ }
437
+ rows.sort((a, b) => (a.artifact.digest < b.artifact.digest ? -1 : 1));
438
+ const manifest = {
439
+ members: rows,
440
+ placement: SET_PLACEMENT_ID,
441
+ slotCommitment: { algorithm: "sha256", digest: bytesToHex(commitment) },
442
+ type: FUSE_PROFILE,
443
+ };
444
+ return canonicalize(manifest);
445
+ }
446
+ /**
447
+ * Strict parse of set manifest bytes, in the style of parseFusePayload. The
448
+ * bytes must be valid UTF-8 JSON, a plain object with exactly the keys
449
+ * {members, placement, slotCommitment, type}, the profile type, placement
450
+ * "set/1", a lowercase-hex 32-byte commitment, at least one row, every row
451
+ * exactly {artifact, origin, placement} with 32-byte digests and a
452
+ * well-formed placement id other than "set/1", and finally must equal
453
+ * buildSetManifest over what was read byte for byte. That one comparison
454
+ * rejects whitespace, key reordering, duplicate JSON keys (a duplicate cannot
455
+ * survive a round trip), unsorted or duplicated rows, non-canonical escapes
456
+ * and trailing bytes. Registration of a row's placement is NOT checked here:
457
+ * a v2 placement must not poison v1 readers, and it surfaces per row as
458
+ * UNDETERMINED_PLACEMENT at verify time. Returns null on any deviation.
459
+ */
460
+ export function parseSetManifest(bytes) {
461
+ let text;
462
+ try {
463
+ // ignoreBOM keeps a leading BOM in the text, where JSON.parse refuses it,
464
+ // rather than stripping it as though it were whitespace.
465
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
466
+ }
467
+ catch {
468
+ return null;
469
+ }
470
+ let parsed;
471
+ try {
472
+ parsed = JSON.parse(text);
473
+ }
474
+ catch {
475
+ return null;
476
+ }
477
+ if (!isPlainObject(parsed))
478
+ return null;
479
+ if (Object.keys(parsed).sort().join(",") !== "members,placement,slotCommitment,type")
480
+ return null;
481
+ if (parsed["type"] !== FUSE_PROFILE || parsed["placement"] !== SET_PLACEMENT_ID)
482
+ return null;
483
+ const commitment = readDigestField(parsed["slotCommitment"]);
484
+ if (commitment === null)
485
+ return null;
486
+ const list = parsed["members"];
487
+ if (!Array.isArray(list) || list.length === 0)
488
+ return null;
489
+ const members = [];
490
+ for (const row of list) {
491
+ if (!isPlainObject(row))
492
+ return null;
493
+ if (Object.keys(row).sort().join(",") !== "artifact,origin,placement")
494
+ return null;
495
+ const artifact = readDigestField(row["artifact"]);
496
+ const origin = readDigestField(row["origin"]);
497
+ const placement = row["placement"];
498
+ if (artifact === null || origin === null || typeof placement !== "string")
499
+ return null;
500
+ if (!PLACEMENT_ID_PATTERN.test(placement) || placement === SET_PLACEMENT_ID)
501
+ return null;
502
+ members.push({ artifact, origin, placement });
503
+ }
504
+ let rebuilt;
505
+ try {
506
+ rebuilt = buildSetManifest(commitment, members);
507
+ }
508
+ catch {
509
+ return null;
510
+ }
511
+ if (!bytesEqual(rebuilt, bytes))
512
+ return null;
513
+ return { commitment, members };
514
+ }
515
+ /**
516
+ * The manifest bytes a proof carries under proof.metadata[SET_METADATA_KEY],
517
+ * re-canonicalized from the parsed object, or null when there is none or it
518
+ * is not a plain object. UNBOUND and UNVALIDATED: metadata is unsigned, so
519
+ * this returns bytes only, never rows. Nothing reads a member from it except
520
+ * through verifyFuseMember, which first requires these bytes to parse
521
+ * strictly and to hash to the signed artifact digest.
522
+ */
523
+ export function readSetMetadata(proof) {
524
+ const value = proof.metadata?.[SET_METADATA_KEY];
525
+ if (!isPlainObject(value))
526
+ return null;
527
+ try {
528
+ return canonicalize(value);
529
+ }
530
+ catch {
531
+ return null;
532
+ }
533
+ }
534
+ const set1 = {
535
+ id: SET_PLACEMENT_ID,
536
+ form: "C",
537
+ byteExact: false,
538
+ build() {
539
+ throw new TypeError("set/1 is built with buildSetManifest(commitment, members)");
540
+ },
541
+ locate(fused) {
542
+ const manifest = parseSetManifest(fused);
543
+ return manifest === null ? null : { commitment: manifest.commitment };
544
+ },
545
+ };
546
+ /**
547
+ * Resolve a placement by id. set/1 resolves here but is NOT in PLACEMENTS:
548
+ * the undeclared scan is for bytes whose placement was not declared, whereas
549
+ * a set manifest is identified by hashing to the signed artifact digest and
550
+ * by its signed title, so the scan order of every existing fixture is
551
+ * literally unchanged.
552
+ */
553
+ export function getPlacement(id) {
554
+ return [...PLACEMENTS, set1].find((p) => p.id === id);
555
+ }
556
+ // ---------------------------------------------------------------------------
557
+ // Attribution (the signed carrier of placement and origin, spec 6.5)
558
+ // ---------------------------------------------------------------------------
559
+ /**
560
+ * attribution.name = "bitgraph-fuse/1" (the profile id), title = placement id,
561
+ * message = origin digest in standard base64. A set has no single origin, so
562
+ * set/1 refuses an origin digest: a set/1 marker carrying one is out of
563
+ * profile and verifyFuseMember refuses it.
564
+ */
565
+ export function fuseAttribution(placement, originDigest) {
566
+ if (originDigest !== undefined && originDigest.length !== 32)
567
+ throw new TypeError("originDigest must be 32 bytes");
568
+ if (placement === SET_PLACEMENT_ID && originDigest !== undefined)
569
+ throw new TypeError("set/1 has no single origin; a set marker carries no origin digest");
570
+ return {
571
+ name: FUSE_ATTRIBUTION_NAME,
572
+ title: placement,
573
+ ...(originDigest !== undefined ? { message: bytesToBase64(originDigest) } : {}),
574
+ };
575
+ }
576
+ /** Read the fused marker from a proof's signed attribution, or null when the proof is not marked fused. */
577
+ export function readFuseAttribution(proof) {
578
+ const a = proof.attribution;
579
+ if (a === undefined || a.name !== FUSE_ATTRIBUTION_NAME)
580
+ return null;
581
+ const declared = typeof a.title === "string" && a.title.length > 0;
582
+ const marker = { placement: declared ? a.title : null, placementSource: declared ? "attribution" : null, source: "attribution" };
583
+ if (typeof a.message === "string" && a.message.length > 0) {
584
+ const d = base64ToBytes(a.message);
585
+ // A message that is not a digest is still a fused marker; the origin is simply undeclared.
586
+ if (d !== null && d.length === 32) {
587
+ marker.originDigest = d;
588
+ marker.originSource = "attribution";
589
+ }
590
+ }
591
+ return marker;
592
+ }
593
+ /** Merge the signed marker with a manifest marker: the signature wins wherever it declares. */
594
+ export function mergeMarkers(signed, manifest) {
595
+ if (signed === null)
596
+ return manifest;
597
+ if (manifest === null)
598
+ return signed;
599
+ const out = { ...signed };
600
+ if (out.placement === null && manifest.placement !== null) {
601
+ out.placement = manifest.placement;
602
+ out.placementSource = "manifest";
603
+ }
604
+ if (out.originDigest === undefined && manifest.originDigest !== undefined) {
605
+ out.originDigest = manifest.originDigest;
606
+ out.originSource = "manifest";
607
+ }
608
+ return out;
609
+ }
610
+ export function buildFrame(input) {
611
+ const frame = {
612
+ type: FUSE_PROFILE,
613
+ manifest: {
614
+ placement: input.placement,
615
+ ...(input.originDigest !== undefined ? { origin: { algorithm: "sha256", digest: bytesToHex(input.originDigest) } } : {}),
616
+ artifact: { algorithm: "sha256", digest: bytesToHex(input.artifactDigest) },
617
+ fusedFile: input.fusedFile,
618
+ },
619
+ proof: input.proof,
620
+ };
621
+ if (input.fusePayload !== undefined) {
622
+ const parsed = parseFusePayload(input.fusePayload);
623
+ if (parsed === null)
624
+ throw new TypeError("fusePayload is not a canonical bitgraph-fuse/1 payload");
625
+ frame.fusePayload = JSON.parse(new TextDecoder().decode(input.fusePayload));
626
+ }
627
+ return frame;
628
+ }
629
+ /**
630
+ * Structural read of a Frame. The manifest is advisory: nothing here is
631
+ * trusted beyond its shape, and the nested proof is returned exactly as
632
+ * found for the ordinary verifier. Null when this is not a Frame.
633
+ */
634
+ export function parseFrame(input) {
635
+ const obj = typeof input === "string" ? (() => { try {
636
+ return JSON.parse(input);
637
+ }
638
+ catch {
639
+ return null;
640
+ } })() : input;
641
+ if (!isPlainObject(obj) || obj["type"] !== FUSE_PROFILE)
642
+ return null;
643
+ const m = obj["manifest"];
644
+ if (!isPlainObject(m))
645
+ return null;
646
+ if (m["placement"] !== undefined && typeof m["placement"] !== "string")
647
+ return null;
648
+ const artifact = readDigestField(m["artifact"]);
649
+ if (artifact === null)
650
+ return null;
651
+ if (m["origin"] !== undefined && readDigestField(m["origin"]) === null)
652
+ return null;
653
+ if (m["fusedFile"] !== null && typeof m["fusedFile"] !== "string")
654
+ return null;
655
+ const proof = obj["proof"];
656
+ if (!isPlainObject(proof) || proof["version"] !== "bitgraph/1")
657
+ return null;
658
+ const frame = {
659
+ type: FUSE_PROFILE,
660
+ manifest: {
661
+ placement: typeof m["placement"] === "string" ? m["placement"] : "",
662
+ ...(m["origin"] !== undefined ? { origin: m["origin"] } : {}),
663
+ artifact: m["artifact"],
664
+ fusedFile: m["fusedFile"],
665
+ },
666
+ proof: proof,
667
+ };
668
+ if (obj["fusePayload"] !== undefined) {
669
+ if (!isPlainObject(obj["fusePayload"]))
670
+ return null;
671
+ frame.fusePayload = obj["fusePayload"];
672
+ }
673
+ return frame;
674
+ }
675
+ /** Marker from a Frame's advisory manifest (unsigned; made self-proving only by reconstruction). */
676
+ export function readFrameMarker(frame) {
677
+ const declared = frame.manifest.placement.length > 0;
678
+ const marker = { placement: declared ? frame.manifest.placement : null, placementSource: declared ? "manifest" : null, source: "manifest" };
679
+ if (frame.manifest.origin !== undefined) {
680
+ const d = hexToBytes(frame.manifest.origin.digest);
681
+ if (d !== null && d.length === 32) {
682
+ marker.originDigest = d;
683
+ marker.originSource = "manifest";
684
+ }
685
+ }
686
+ return marker;
687
+ }
688
+ //# sourceMappingURL=fuse.js.map