@eyeoverthink/wasm-deflate-vault 0.0.0-stage → 2.0.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.
@@ -0,0 +1,859 @@
1
+ /**
2
+ * wasm-deflate-vault.js
3
+ * Self-Extracting Deflate-in-WASM Binary Container (00 61 73 6d),
4
+ * Standard PKZIP Builder & CRC-32 Verifier (0x04034b50),
5
+ * RFC 6962 Per-File Merkle Tree + Sibling Inclusion Proofs,
6
+ * WebCrypto Ed25519 Manifest Signing, and Unicode Variation-Selector Bridge.
7
+ *
8
+ * SPDX-License-Identifier: Apache-2.0
9
+ */
10
+
11
+ const textEncoder = new TextEncoder();
12
+ const textDecoder = new TextDecoder();
13
+
14
+ export const VERSION = "2.0.0";
15
+ export const VAULT_MAGIC = 0x57445631; // "WDV1"
16
+
17
+ function bytesToHex(bytes) {
18
+ let out = "";
19
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
20
+ return out;
21
+ }
22
+
23
+ function hexToBytes(hex) {
24
+ const out = new Uint8Array(hex.length / 2);
25
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
26
+ return out;
27
+ }
28
+
29
+ function concatBytes(...chunks) {
30
+ return concatByteList(chunks);
31
+ }
32
+
33
+ function concatByteList(chunks) {
34
+ let total = 0;
35
+ for (const c of chunks) total += c.length;
36
+ const out = new Uint8Array(total);
37
+ let off = 0;
38
+ for (const c of chunks) {
39
+ out.set(c, off);
40
+ off += c.length;
41
+ }
42
+ return out;
43
+ }
44
+
45
+ function bytesToBase64(bytes) {
46
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
47
+ let bin = "";
48
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
49
+ return btoa(bin);
50
+ }
51
+
52
+ function base64ToBytes(b64) {
53
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(b64, "base64"));
54
+ const bin = atob(b64);
55
+ const out = new Uint8Array(bin.length);
56
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
57
+ return out;
58
+ }
59
+
60
+ async function sha256Bytes(bytes) {
61
+ return new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
62
+ }
63
+
64
+ async function sha256Hex(bytes) {
65
+ return bytesToHex(await sha256Bytes(bytes));
66
+ }
67
+
68
+ // =========================================================================
69
+ // 1. IEEE 802.3 CRC-32 & STANDARD PKZIP ARCHIVE BUILDER / INSPECTOR
70
+ // =========================================================================
71
+
72
+ const CRC32_TABLE = (() => {
73
+ const tbl = new Uint32Array(256);
74
+ for (let i = 0; i < 256; i++) {
75
+ let c = i;
76
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
77
+ tbl[i] = c >>> 0;
78
+ }
79
+ return tbl;
80
+ })();
81
+
82
+ export function crc32(bytes) {
83
+ let c = 0xffffffff;
84
+ for (let i = 0; i < bytes.length; i++) {
85
+ c = CRC32_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
86
+ }
87
+ return (c ^ 0xffffffff) >>> 0;
88
+ }
89
+
90
+ /**
91
+ * Builds a compliant Store-mode PKZIP archive (0x04034b50 local headers,
92
+ * 0x02014b50 central directory, 0x06054b50 EOCD) from a { filename: content } map.
93
+ */
94
+ export function buildZipArchive(filesMap) {
95
+ const names = Object.keys(filesMap).sort();
96
+ const localParts = [];
97
+ const centralParts = [];
98
+ let offset = 0;
99
+
100
+ for (const name of names) {
101
+ const nameBytes = textEncoder.encode(name);
102
+ const content = filesMap[name];
103
+ const dataBytes = content instanceof Uint8Array ? content : textEncoder.encode(String(content));
104
+ const sum = crc32(dataBytes);
105
+
106
+ // Local File Header (30B + nameLen + dataLen)
107
+ const lfh = new Uint8Array(30 + nameBytes.length);
108
+ const lv = new DataView(lfh.buffer);
109
+ lv.setUint32(0, 0x04034b50, true);
110
+ lv.setUint16(4, 20, true); // version needed
111
+ lv.setUint16(6, 0x0800, true); // UTF-8 filename flag
112
+ lv.setUint16(8, 0, true); // method = Store
113
+ lv.setUint16(10, 0, true);
114
+ lv.setUint16(12, 0x5421, true);
115
+ lv.setUint32(14, sum, true);
116
+ lv.setUint32(18, dataBytes.length, true);
117
+ lv.setUint32(22, dataBytes.length, true);
118
+ lv.setUint16(26, nameBytes.length, true);
119
+ lv.setUint16(28, 0, true);
120
+ lfh.set(nameBytes, 30);
121
+
122
+ // Central Directory Header (46B + nameLen)
123
+ const cdh = new Uint8Array(46 + nameBytes.length);
124
+ const cv = new DataView(cdh.buffer);
125
+ cv.setUint32(0, 0x02014b50, true);
126
+ cv.setUint16(4, 20, true);
127
+ cv.setUint16(6, 20, true);
128
+ cv.setUint16(8, 0x0800, true);
129
+ cv.setUint16(10, 0, true);
130
+ cv.setUint16(12, 0, true);
131
+ cv.setUint16(14, 0x5421, true);
132
+ cv.setUint32(16, sum, true);
133
+ cv.setUint32(20, dataBytes.length, true);
134
+ cv.setUint32(24, dataBytes.length, true);
135
+ cv.setUint16(28, nameBytes.length, true);
136
+ cv.setUint16(30, 0, true);
137
+ cv.setUint16(32, 0, true);
138
+ cv.setUint16(34, 0, true);
139
+ cv.setUint16(36, 0, true);
140
+ cv.setUint32(38, 0, true);
141
+ cv.setUint32(42, offset, true);
142
+ cdh.set(nameBytes, 46);
143
+
144
+ localParts.push(lfh, dataBytes);
145
+ centralParts.push(cdh);
146
+ offset += lfh.length + dataBytes.length;
147
+ }
148
+
149
+ const centralBlob = concatByteList(centralParts);
150
+ const eocd = new Uint8Array(22);
151
+ const ev = new DataView(eocd.buffer);
152
+ ev.setUint32(0, 0x06054b50, true);
153
+ ev.setUint16(4, 0, true);
154
+ ev.setUint16(6, 0, true);
155
+ ev.setUint16(8, names.length, true);
156
+ ev.setUint16(10, names.length, true);
157
+ ev.setUint32(12, centralBlob.length, true);
158
+ ev.setUint32(16, offset, true);
159
+ ev.setUint16(20, 0, true);
160
+
161
+ localParts.push(centralBlob, eocd);
162
+ return concatByteList(localParts);
163
+ }
164
+
165
+ /**
166
+ * Parses a Store-mode PKZIP archive and verifies every entry's IEEE CRC-32.
167
+ */
168
+ export function inspectZipArchive(zipBytes) {
169
+ if (!(zipBytes instanceof Uint8Array) || zipBytes.length < 22) {
170
+ return { ok: false, error: "INVALID_ZIP_BUFFER" };
171
+ }
172
+ const view = new DataView(zipBytes.buffer, zipBytes.byteOffset, zipBytes.byteLength);
173
+ let pos = 0;
174
+ const entries = [];
175
+ let allCrcValid = true;
176
+
177
+ while (pos + 4 <= zipBytes.length && view.getUint32(pos, true) === 0x04034b50) {
178
+ const expectedCrc = view.getUint32(pos + 14, true);
179
+ const compSize = view.getUint32(pos + 18, true);
180
+ const uncompSize = view.getUint32(pos + 22, true);
181
+ const nameLen = view.getUint16(pos + 26, true);
182
+ const extraLen = view.getUint16(pos + 28, true);
183
+ const nameStart = pos + 30;
184
+ const dataStart = nameStart + nameLen + extraLen;
185
+ if (dataStart + compSize > zipBytes.length) {
186
+ return { ok: false, error: "ZIP_TRUNCATED_ENTRY" };
187
+ }
188
+ const name = textDecoder.decode(zipBytes.subarray(nameStart, nameStart + nameLen));
189
+ const data = zipBytes.subarray(dataStart, dataStart + compSize);
190
+ const actualCrc = crc32(data);
191
+ const crcValid = actualCrc === expectedCrc;
192
+ if (!crcValid) allCrcValid = false;
193
+
194
+ entries.push({
195
+ name,
196
+ localHeaderOffset: pos,
197
+ size: uncompSize,
198
+ expectedCrcHex: expectedCrc.toString(16).padStart(8, "0"),
199
+ actualCrcHex: actualCrc.toString(16).padStart(8, "0"),
200
+ crcValid,
201
+ contentPreview: textDecoder.decode(data).slice(0, 64),
202
+ });
203
+ pos = dataStart + compSize;
204
+ }
205
+
206
+ // Verify Central Directory records match Local File Headers 1:1
207
+ let cdIndex = 0;
208
+ let cdMatch = true;
209
+ while (pos + 46 <= zipBytes.length && view.getUint32(pos, true) === 0x02014b50) {
210
+ const cdCrc = view.getUint32(pos + 16, true);
211
+ const cdNameLen = view.getUint16(pos + 28, true);
212
+ const cdExtraLen = view.getUint16(pos + 30, true);
213
+ const cdCommentLen = view.getUint16(pos + 32, true);
214
+ const cdNameStart = pos + 46;
215
+ if (cdNameStart + cdNameLen > zipBytes.length) {
216
+ cdMatch = false;
217
+ break;
218
+ }
219
+ const cdName = textDecoder.decode(zipBytes.subarray(cdNameStart, cdNameStart + cdNameLen));
220
+ const local = entries[cdIndex];
221
+ if (!local || local.name !== cdName || cdCrc.toString(16).padStart(8, "0") !== local.expectedCrcHex) {
222
+ cdMatch = false;
223
+ }
224
+ cdIndex += 1;
225
+ pos = cdNameStart + cdNameLen + cdExtraLen + cdCommentLen;
226
+ }
227
+ if (cdIndex !== entries.length) cdMatch = false;
228
+
229
+ return {
230
+ ok: allCrcValid && cdMatch && entries.length > 0,
231
+ magicHex: "0x04034b50",
232
+ entryCount: entries.length,
233
+ totalBytes: zipBytes.length,
234
+ cdMatch,
235
+ entries,
236
+ };
237
+ }
238
+
239
+ // =========================================================================
240
+ // 2. RFC 6962 PER-FILE MERKLE TREE & INCLUSION PROOFS
241
+ // =========================================================================
242
+
243
+ async function hashFileLeaf(filename, content) {
244
+ return sha256Bytes(
245
+ concatBytes(
246
+ new Uint8Array([0x00]),
247
+ textEncoder.encode(filename),
248
+ new Uint8Array([0x1f]),
249
+ content instanceof Uint8Array ? content : textEncoder.encode(String(content)),
250
+ ),
251
+ );
252
+ }
253
+
254
+ async function hashNodePair(left32, right32) {
255
+ return sha256Bytes(concatBytes(new Uint8Array([0x01]), left32, right32));
256
+ }
257
+
258
+ export async function buildFileMerkleTree(filesMap) {
259
+ const filenames = Object.keys(filesMap).sort();
260
+ if (filenames.length === 0) throw new Error("EMPTY_FILES_MAP");
261
+
262
+ const leavesBytes = await Promise.all(
263
+ filenames.map((name) => hashFileLeaf(name, filesMap[name])),
264
+ );
265
+
266
+ const layers = [leavesBytes.map(bytesToHex)];
267
+ let current = leavesBytes;
268
+
269
+ while (current.length > 1) {
270
+ const next = [];
271
+ for (let i = 0; i < current.length; i += 2) {
272
+ const left = current[i];
273
+ const right = i + 1 < current.length ? current[i + 1] : current[i];
274
+ next.push(await hashNodePair(left, right));
275
+ }
276
+ layers.push(next.map(bytesToHex));
277
+ current = next;
278
+ }
279
+
280
+ return {
281
+ filenames,
282
+ leafCount: filenames.length,
283
+ layers,
284
+ rootHex: bytesToHex(current[0]),
285
+ };
286
+ }
287
+
288
+ export function getFileMerkleProof(tree, filename) {
289
+ let idx = tree.filenames.indexOf(filename);
290
+ if (idx === -1) throw new Error(`FILE_NOT_IN_TREE: '${filename}'`);
291
+
292
+ const proof = [];
293
+ for (let level = 0; level < tree.layers.length - 1; level++) {
294
+ const layer = tree.layers[level];
295
+ const isRightNode = idx % 2 === 1;
296
+ const siblingIdx = isRightNode ? idx - 1 : idx + 1 < layer.length ? idx + 1 : idx;
297
+ proof.push({
298
+ position: isRightNode ? "left" : "right",
299
+ hash: layer[siblingIdx],
300
+ });
301
+ idx = Math.floor(idx / 2);
302
+ }
303
+
304
+ return {
305
+ filename,
306
+ leafHash: tree.layers[0][tree.filenames.indexOf(filename)],
307
+ proof,
308
+ rootHex: tree.rootHex,
309
+ };
310
+ }
311
+
312
+ export async function verifyFileMerkleProof({ filename, content, proof, rootHex }) {
313
+ let current = await hashFileLeaf(filename, content);
314
+ for (const step of proof) {
315
+ const sib = hexToBytes(step.hash);
316
+ current = step.position === "left" ? await hashNodePair(sib, current) : await hashNodePair(current, sib);
317
+ }
318
+ const computedRoot = bytesToHex(current);
319
+ return {
320
+ ok: computedRoot === rootHex,
321
+ computedRoot,
322
+ expectedRoot: rootHex,
323
+ };
324
+ }
325
+
326
+ // =========================================================================
327
+ // 3. REAL DEFLATE-IN-WASM CONTAINER + NATIVE WebAssembly.instantiate() VERIFY
328
+ // =========================================================================
329
+
330
+ function encodeUnsignedLeb128(value) {
331
+ let v = value >>> 0;
332
+ const out = [];
333
+ do {
334
+ let b = v & 0x7f;
335
+ v >>>= 7;
336
+ if (v !== 0) b |= 0x80;
337
+ out.push(b);
338
+ } while (v !== 0);
339
+ return out;
340
+ }
341
+
342
+ function encodeSignedLeb128(value) {
343
+ let v = value | 0;
344
+ const out = [];
345
+ let more = true;
346
+ while (more) {
347
+ let b = v & 0x7f;
348
+ v >>= 7;
349
+ if ((v === 0 && (b & 0x40) === 0) || (v === -1 && (b & 0x40) !== 0)) more = false;
350
+ else b |= 0x80;
351
+ out.push(b);
352
+ }
353
+ return out;
354
+ }
355
+
356
+ // Strict unsigned LEB128 (u32) reader: refuses truncated input and encodings longer than 5 bytes.
357
+ function readUnsignedLeb128(bytes, start) {
358
+ let result = 0;
359
+ let shift = 0;
360
+ let pos = start;
361
+ for (let i = 0; i < 5; i++) {
362
+ if (pos >= bytes.length) throw new Error("WASM_LEB128_TRUNCATED");
363
+ const b = bytes[pos++];
364
+ result += (b & 0x7f) * 2 ** shift;
365
+ if ((b & 0x80) === 0) {
366
+ if (result > 0xffffffff) throw new Error("WASM_LEB128_OVERFLOW");
367
+ return { value: result, nextOffset: pos };
368
+ }
369
+ shift += 7;
370
+ }
371
+ throw new Error("WASM_LEB128_TOO_LONG");
372
+ }
373
+
374
+ function withLen(arr) {
375
+ return [...encodeUnsignedLeb128(arr.length), ...arr];
376
+ }
377
+
378
+ function makeSection(id, payloadArr) {
379
+ return [id, ...withLen(payloadArr)];
380
+ }
381
+
382
+ function appendBytes(target, bytes) {
383
+ // Avoids spreading large arrays into a call (stack overflow on big payloads).
384
+ for (let i = 0; i < bytes.length; i++) target.push(bytes[i]);
385
+ return target;
386
+ }
387
+
388
+ async function deflateBytes(raw) {
389
+ if (typeof globalThis.CompressionStream !== "function") {
390
+ return { data: raw, compressed: false };
391
+ }
392
+ const cs = new globalThis.CompressionStream("deflate");
393
+ const w = cs.writable.getWriter();
394
+ w.write(raw);
395
+ w.close();
396
+ return { data: new Uint8Array(await new Response(cs.readable).arrayBuffer()), compressed: true };
397
+ }
398
+
399
+ export const DEFAULT_MAX_INFLATED_BYTES = 64 * 1024 * 1024;
400
+
401
+ // Inflates with a hard output ceiling: stops reading (and cancels the stream) as soon as it is exceeded.
402
+ async function inflateBytes(comp, maxBytes = DEFAULT_MAX_INFLATED_BYTES) {
403
+ const ds = new globalThis.DecompressionStream("deflate");
404
+ const w = ds.writable.getWriter();
405
+ w.write(comp).catch(() => {});
406
+ w.close().catch(() => {});
407
+ const reader = ds.readable.getReader();
408
+ const chunks = [];
409
+ let total = 0;
410
+ for (;;) {
411
+ const { value, done } = await reader.read();
412
+ if (done) break;
413
+ total += value.length;
414
+ if (total > maxBytes) {
415
+ await reader.cancel().catch(() => {});
416
+ throw new Error("INFLATED_PAYLOAD_TOO_LARGE");
417
+ }
418
+ chunks.push(value);
419
+ }
420
+ return concatByteList(chunks);
421
+ }
422
+
423
+ /**
424
+ * Walks the top-level sections of a WebAssembly binary without compiling or running it.
425
+ * Returns [{ id, start, payloadStart, end, name?, nameEnd? }] or throws on a malformed layout.
426
+ */
427
+ function parseWasmSections(wasmBytes) {
428
+ if (
429
+ !(wasmBytes instanceof Uint8Array) ||
430
+ wasmBytes.length < 8 ||
431
+ wasmBytes[0] !== 0x00 ||
432
+ wasmBytes[1] !== 0x61 ||
433
+ wasmBytes[2] !== 0x73 ||
434
+ wasmBytes[3] !== 0x6d ||
435
+ wasmBytes[4] !== 0x01 ||
436
+ wasmBytes[5] !== 0x00 ||
437
+ wasmBytes[6] !== 0x00 ||
438
+ wasmBytes[7] !== 0x00
439
+ ) {
440
+ throw new Error("NOT_A_WASM_1_MODULE");
441
+ }
442
+ const out = [];
443
+ let pos = 8;
444
+ while (pos < wasmBytes.length) {
445
+ const start = pos;
446
+ const id = wasmBytes[pos++];
447
+ const lenInfo = readUnsignedLeb128(wasmBytes, pos);
448
+ const payloadStart = lenInfo.nextOffset;
449
+ const end = payloadStart + lenInfo.value;
450
+ if (end > wasmBytes.length) throw new Error("WASM_SECTION_TRUNCATED");
451
+ const sec = { id, start, payloadStart, end };
452
+ if (id === 0) {
453
+ const nameLenInfo = readUnsignedLeb128(wasmBytes, payloadStart);
454
+ const nameStart = nameLenInfo.nextOffset;
455
+ const nameEnd = nameStart + nameLenInfo.value;
456
+ if (nameEnd > end) throw new Error("WASM_CUSTOM_NAME_TRUNCATED");
457
+ sec.name = textDecoder.decode(wasmBytes.subarray(nameStart, nameEnd));
458
+ sec.nameEnd = nameEnd;
459
+ }
460
+ out.push(sec);
461
+ pos = end;
462
+ }
463
+ return out;
464
+ }
465
+
466
+ /**
467
+ * Locates the bytes of the first active data segment by parsing the Data section:
468
+ * vector count, segment flags, the i32.const offset expression, then the byte-vector length.
469
+ */
470
+ function locateFirstDataSegment(wasmBytes, sections) {
471
+ const dataSec = sections.find((s) => s.id === 11);
472
+ if (!dataSec) return null;
473
+ let pos = dataSec.payloadStart;
474
+ const count = readUnsignedLeb128(wasmBytes, pos);
475
+ if (count.value < 1) return null;
476
+ pos = count.nextOffset;
477
+ const flags = readUnsignedLeb128(wasmBytes, pos);
478
+ pos = flags.nextOffset;
479
+ if (flags.value !== 0) return null; // only "active, memory 0" segments are produced by this package
480
+ if (wasmBytes[pos++] !== 0x41) return null; // i32.const
481
+ // signed LEB128 offset
482
+ let offset = 0;
483
+ let shift = 0;
484
+ let b;
485
+ let n = 0;
486
+ do {
487
+ if (pos >= dataSec.end || n++ >= 5) throw new Error("WASM_DATA_OFFSET_MALFORMED");
488
+ b = wasmBytes[pos++];
489
+ offset |= (b & 0x7f) << shift;
490
+ shift += 7;
491
+ } while (b & 0x80);
492
+ if (shift < 32 && (b & 0x40)) offset |= -1 << shift;
493
+ if (wasmBytes[pos++] !== 0x0b) return null; // end of init expression
494
+ const len = readUnsignedLeb128(wasmBytes, pos);
495
+ const start = len.nextOffset;
496
+ const end = start + len.value;
497
+ if (end > dataSec.end) throw new Error("WASM_DATA_SEGMENT_TRUNCATED");
498
+ return { memoryOffset: offset, start, end };
499
+ }
500
+
501
+ // Binary file contents are carried as base64 inside the JSON bundle and listed in `binary`.
502
+ function serializeBundle(filesMap) {
503
+ const files = {};
504
+ const binary = [];
505
+ for (const name of Object.keys(filesMap).sort()) {
506
+ const content = filesMap[name];
507
+ if (content instanceof Uint8Array) {
508
+ files[name] = bytesToBase64(content);
509
+ binary.push(name);
510
+ } else {
511
+ files[name] = String(content);
512
+ }
513
+ }
514
+ const bundle = { schema: "wasm-deflate-vault/1", files };
515
+ if (binary.length) bundle.binary = binary;
516
+ return bundle;
517
+ }
518
+
519
+ function deserializeBundleFiles(bundle) {
520
+ if (!bundle || typeof bundle !== "object" || !bundle.files || typeof bundle.files !== "object") {
521
+ throw new Error("BUNDLE_MALFORMED");
522
+ }
523
+ const files = {};
524
+ for (const name of Object.keys(bundle.files)) {
525
+ const v = bundle.files[name];
526
+ if (typeof v !== "string") throw new Error(`BUNDLE_FILE_NOT_STRING: '${name}'`);
527
+ files[name] = v;
528
+ }
529
+ for (const name of Array.isArray(bundle.binary) ? bundle.binary : []) {
530
+ if (!Object.prototype.hasOwnProperty.call(files, name)) throw new Error(`BUNDLE_BINARY_UNKNOWN: '${name}'`);
531
+ files[name] = base64ToBytes(files[name]);
532
+ }
533
+ return files;
534
+ }
535
+
536
+ // =========================================================================
537
+ // Ed25519 key handling: raw 32-byte public keys as 64 hex characters.
538
+ // =========================================================================
539
+
540
+ const ED25519_SPKI_PREFIX = hexToBytes("302a300506032b6570032100");
541
+
542
+ // The small-order Ed25519 points (and non-canonical encodings of 0 and 1), as in libsodium's blocklist,
543
+ // compared with the sign bit cleared. With such a key, R = identity and S = 0 verify for ANY message
544
+ // (WebCrypto does not refuse them), so a "signature" can be made without a private key.
545
+ const SMALL_ORDER_KEYS = [
546
+ "0000000000000000000000000000000000000000000000000000000000000000",
547
+ "0100000000000000000000000000000000000000000000000000000000000000",
548
+ "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
549
+ "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
550
+ "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
551
+ "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
552
+ "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
553
+ ];
554
+
555
+ const HEX64 = /^[0-9a-f]{64}$/;
556
+
557
+ /** True for anything that is not a usable Ed25519 public key: malformed, or one of the small-order points. */
558
+ export function isSmallOrderKey(publicKeyHex) {
559
+ const hex = String(publicKeyHex ?? "").toLowerCase();
560
+ if (!HEX64.test(hex)) return true;
561
+ const b = hexToBytes(hex);
562
+ b[31] &= 0x7f;
563
+ const cleared = bytesToHex(b);
564
+ return SMALL_ORDER_KEYS.includes(cleared);
565
+ }
566
+
567
+ function spkiToRawHex(spkiBytes) {
568
+ if (spkiBytes.length !== 44) return null;
569
+ for (let i = 0; i < ED25519_SPKI_PREFIX.length; i++) if (spkiBytes[i] !== ED25519_SPKI_PREFIX[i]) return null;
570
+ return bytesToHex(spkiBytes.subarray(12));
571
+ }
572
+
573
+ /** Raw Ed25519 public key (64 hex chars) of a CryptoKey, for use as an expected key. */
574
+ export async function publicKeyToHex(publicKey) {
575
+ return bytesToHex(new Uint8Array(await globalThis.crypto.subtle.exportKey("raw", publicKey)));
576
+ }
577
+
578
+ function trustedKeySet(expectedPublicKeys) {
579
+ if (expectedPublicKeys == null) return new Set();
580
+ const list = Array.isArray(expectedPublicKeys) ? expectedPublicKeys : [expectedPublicKeys];
581
+ return new Set(list.map((k) => String(k).toLowerCase()).filter((k) => HEX64.test(k) && !isSmallOrderKey(k)));
582
+ }
583
+
584
+ /**
585
+ * Checks an envelope's signature against caller-pinned keys only.
586
+ * Returns { keyTrusted, signatureOk, signerPublicKeyHex, error? }.
587
+ */
588
+ async function verifyEnvelopeSignature(envelope, expectedPublicKeys) {
589
+ const out = { keyTrusted: false, signatureOk: false, signerPublicKeyHex: null };
590
+ if (!envelope || typeof envelope !== "object" || !envelope.manifest || typeof envelope.manifest !== "object") {
591
+ return { ...out, error: "ENVELOPE_MALFORMED" };
592
+ }
593
+ const signerHex = spkiToRawHex(base64ToBytes(String(envelope.publicKeySpkiB64 ?? "")));
594
+ out.signerPublicKeyHex = signerHex;
595
+ if (!signerHex) return { ...out, error: "SIGNER_KEY_MALFORMED" };
596
+ if (isSmallOrderKey(signerHex)) return { ...out, error: "WEAK_SIGNER_KEY" };
597
+ const trusted = trustedKeySet(expectedPublicKeys);
598
+ if (trusted.size === 0) return { ...out, error: "NO_EXPECTED_PUBLIC_KEYS" };
599
+ out.keyTrusted = trusted.has(signerHex);
600
+ if (!out.keyTrusted) return { ...out, error: "SIGNER_NOT_TRUSTED" };
601
+ const sig = base64ToBytes(String(envelope.signatureB64 ?? ""));
602
+ if (sig.length !== 64) return { ...out, error: "SIGNATURE_MALFORMED" };
603
+ const pub = await globalThis.crypto.subtle.importKey("raw", hexToBytes(signerHex), { name: "Ed25519" }, false, ["verify"]);
604
+ out.signatureOk = await globalThis.crypto.subtle.verify(
605
+ "Ed25519",
606
+ pub,
607
+ sig,
608
+ textEncoder.encode(JSON.stringify(envelope.manifest)),
609
+ );
610
+ if (!out.signatureOk) out.error = "SIGNATURE_INVALID";
611
+ return out;
612
+ }
613
+
614
+ // =========================================================================
615
+ // 3b. VAULT MODULE LAYOUT (built by the packer, rebuilt by the verifier)
616
+ // =========================================================================
617
+
618
+ function buildVaultWasm(payloadBytes, fileCount, envelopeBytes) {
619
+ // Sections: Type(1), Function(3), Memory(5), Export(7), Code(10), Data(11), Custom(0)
620
+ const typeSec = makeSection(1, [0x01, 0x60, 0x00, 0x01, 0x7f]); // () -> i32
621
+ const funcSec = makeSection(3, [0x04, 0x00, 0x00, 0x00, 0x00]); // 4 funcs of type 0
622
+ const memPages = Math.max(1, Math.ceil((payloadBytes.length + 64) / 65536));
623
+ const memSec = makeSection(5, [0x01, 0x00, ...encodeUnsignedLeb128(memPages)]);
624
+
625
+ const exportItem = (name, kind, idx) => [...withLen(Array.from(textEncoder.encode(name))), kind, idx];
626
+ const exportSec = makeSection(7, [
627
+ 0x05,
628
+ ...exportItem("memory", 0x02, 0),
629
+ ...exportItem("getPayloadPtr", 0x00, 0),
630
+ ...exportItem("getPayloadLen", 0x00, 1),
631
+ ...exportItem("getFileCount", 0x00, 2),
632
+ ...exportItem("getMagic", 0x00, 3),
633
+ ]);
634
+
635
+ const constFuncBody = (val) => withLen([0x00, 0x41, ...encodeSignedLeb128(val), 0x0b]);
636
+ const codeSec = makeSection(10, [
637
+ 0x04,
638
+ ...constFuncBody(0),
639
+ ...constFuncBody(payloadBytes.length),
640
+ ...constFuncBody(fileCount),
641
+ ...constFuncBody(VAULT_MAGIC | 0),
642
+ ]);
643
+
644
+ // Active Data segment (memory 0, offset i32.const 0)
645
+ const dataPayload = [0x01, 0x00, 0x41, 0x00, 0x0b, ...encodeUnsignedLeb128(payloadBytes.length)];
646
+ appendBytes(dataPayload, payloadBytes);
647
+ const dataSec = [11, ...encodeUnsignedLeb128(dataPayload.length)];
648
+ appendBytes(dataSec, dataPayload);
649
+
650
+ const secNameBytes = Array.from(textEncoder.encode("wdv.manifest"));
651
+ const customPayload = withLen(secNameBytes);
652
+ appendBytes(customPayload, envelopeBytes);
653
+ const customSec = [0x00, ...encodeUnsignedLeb128(customPayload.length)];
654
+ appendBytes(customSec, customPayload);
655
+
656
+ const all = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
657
+ for (const sec of [typeSec, funcSec, memSec, exportSec, codeSec, dataSec, customSec]) appendBytes(all, sec);
658
+ return new Uint8Array(all);
659
+ }
660
+
661
+ function bytesEqual(a, b) {
662
+ if (a.length !== b.length) return false;
663
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
664
+ return true;
665
+ }
666
+
667
+ /**
668
+ * Packs a files map into a signed WebAssembly 1.0 binary:
669
+ * - Linear Memory active Data segment holds the zlib deflate (78 9c) bundle bytes
670
+ * - Exports: memory, getPayloadPtr, getPayloadLen, getFileCount, getMagic (constant-returning functions)
671
+ * - Custom section "wdv.manifest" holds manifest + Ed25519 signature + SPKI key
672
+ * File contents may be strings or Uint8Array; binary contents are carried as base64 and come back as Uint8Array.
673
+ * Inflating is done in JavaScript; the module holds data only.
674
+ */
675
+ export async function packDeflateWasmContainer(filesMap, options = {}) {
676
+ const bundle = serializeBundle(filesMap);
677
+ const merkleTree = await buildFileMerkleTree(filesMap);
678
+ const rawJson = textEncoder.encode(JSON.stringify(bundle));
679
+ const { data: payloadBytes, compressed } = await deflateBytes(rawJson);
680
+ const payloadSha256Hex = await sha256Hex(payloadBytes);
681
+
682
+ const issuedAt = options.issuedAt || new Date().toISOString();
683
+ const keyPair =
684
+ options.keyPair ||
685
+ (await globalThis.crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]));
686
+
687
+ const manifest = {
688
+ schema: "wasm-deflate-vault/1",
689
+ issuedAt,
690
+ compressed,
691
+ rawBytes: rawJson.length,
692
+ payloadLen: payloadBytes.length,
693
+ zlibHeaderHex: bytesToHex(payloadBytes.slice(0, 2)),
694
+ fileCount: merkleTree.leafCount,
695
+ payloadSha256Hex,
696
+ merkleRootHex: merkleTree.rootHex,
697
+ };
698
+ const sig = new Uint8Array(
699
+ await globalThis.crypto.subtle.sign("Ed25519", keyPair.privateKey, textEncoder.encode(JSON.stringify(manifest))),
700
+ );
701
+ const spki = new Uint8Array(await globalThis.crypto.subtle.exportKey("spki", keyPair.publicKey));
702
+ const envelope = {
703
+ manifest,
704
+ signatureB64: bytesToBase64(sig),
705
+ publicKeySpkiB64: bytesToBase64(spki),
706
+ edFxTag: `ED-FX:${bytesToHex(sig.slice(0, 8)).toUpperCase()}`,
707
+ };
708
+
709
+ const wasmBytes = buildVaultWasm(payloadBytes, merkleTree.leafCount, textEncoder.encode(JSON.stringify(envelope)));
710
+
711
+ return {
712
+ wasmBytes,
713
+ wasmByteLength: wasmBytes.length,
714
+ manifest,
715
+ envelope,
716
+ publicKeyHex: spkiToRawHex(spki),
717
+ merkleTree,
718
+ };
719
+ }
720
+
721
+ /**
722
+ * Verifies a vault WITHOUT compiling or running it. The module is parsed as bytes and must be exactly the
723
+ * layout this package produces (rebuilt from its own data segment and manifest); anything else (a start
724
+ * function, extra code, imports) is refused before any further step.
725
+ *
726
+ * Trust: the signature is accepted only from a key the caller pins in `options.expectedPublicKeys`
727
+ * (raw Ed25519 public keys, 64 hex chars; one or an array). The key embedded in the vault is never trusted
728
+ * on its own, and small-order keys are refused. Without pinned keys the result is ok: false
729
+ * (error NO_EXPECTED_PUBLIC_KEYS) and no files are returned.
730
+ *
731
+ * options.maxInflatedBytes caps the inflated bundle (default 64 MiB).
732
+ */
733
+ export async function unpackAndVerifyWasmContainer(wasmBytes, options = {}) {
734
+ const checks = { magicOk: false, sha256Ok: false, keyTrusted: false, signatureOk: false, merkleOk: false };
735
+ try {
736
+ const sections = parseWasmSections(wasmBytes);
737
+ const manifestSec = sections.find((s) => s.id === 0 && s.name === "wdv.manifest");
738
+ if (!manifestSec) return { ok: false, checks, error: "MISSING_WDV_MANIFEST" };
739
+ const envelopeBytes = wasmBytes.subarray(manifestSec.nameEnd, manifestSec.end);
740
+ const envelope = JSON.parse(textDecoder.decode(envelopeBytes));
741
+ const manifest = envelope && envelope.manifest;
742
+ if (!manifest || typeof manifest !== "object") return { ok: false, checks, error: "ENVELOPE_MALFORMED" };
743
+
744
+ // Structure: rebuild the only module layout this package writes and require byte equality.
745
+ const seg = locateFirstDataSegment(wasmBytes, sections);
746
+ if (!seg) return { ok: false, checks, error: "MISSING_DATA_SEGMENT" };
747
+ const payloadBytes = wasmBytes.slice(seg.start, seg.end);
748
+ const fileCount = Number(manifest.fileCount);
749
+ if (!Number.isInteger(fileCount) || fileCount < 1 || fileCount > 0x7fffffff) {
750
+ return { ok: false, checks, error: "MANIFEST_FILECOUNT_INVALID" };
751
+ }
752
+ const canonical = buildVaultWasm(payloadBytes, fileCount, envelopeBytes);
753
+ checks.magicOk = bytesEqual(canonical, wasmBytes);
754
+ if (!checks.magicOk) return { ok: false, checks, error: "NON_CANONICAL_VAULT_MODULE" };
755
+ if (payloadBytes.length !== manifest.payloadLen) {
756
+ return { ok: false, checks, error: "PAYLOAD_BOUNDS_MISMATCH" };
757
+ }
758
+
759
+ checks.sha256Ok = (await sha256Hex(payloadBytes)) === manifest.payloadSha256Hex;
760
+
761
+ const sigResult = await verifyEnvelopeSignature(envelope, options.expectedPublicKeys);
762
+ checks.keyTrusted = sigResult.keyTrusted;
763
+ checks.signatureOk = sigResult.signatureOk;
764
+ if (!checks.sha256Ok || !checks.keyTrusted || !checks.signatureOk) {
765
+ return {
766
+ ok: false,
767
+ checks,
768
+ manifest,
769
+ signerPublicKeyHex: sigResult.signerPublicKeyHex,
770
+ error: !checks.sha256Ok ? "INTEGRITY_FAILED" : sigResult.error || "SIGNATURE_FAILED",
771
+ };
772
+ }
773
+
774
+ const maxInflated = options.maxInflatedBytes ?? DEFAULT_MAX_INFLATED_BYTES;
775
+ const plainBytes = manifest.compressed ? await inflateBytes(payloadBytes, maxInflated) : payloadBytes;
776
+ if (plainBytes.length !== manifest.rawBytes) return { ok: false, checks, manifest, error: "RAW_LENGTH_MISMATCH" };
777
+ const parsedBundle = JSON.parse(textDecoder.decode(plainBytes));
778
+ const files = deserializeBundleFiles(parsedBundle);
779
+ const recomputedTree = await buildFileMerkleTree(files);
780
+ checks.merkleOk = recomputedTree.rootHex === manifest.merkleRootHex && recomputedTree.leafCount === fileCount;
781
+
782
+ return {
783
+ ok: checks.magicOk && checks.sha256Ok && checks.keyTrusted && checks.signatureOk && checks.merkleOk,
784
+ checks,
785
+ manifest,
786
+ signerPublicKeyHex: sigResult.signerPublicKeyHex,
787
+ edFxTag: envelope.edFxTag,
788
+ files,
789
+ merkleTree: recomputedTree,
790
+ };
791
+ } catch (err) {
792
+ return { ok: false, checks, error: err.message };
793
+ }
794
+ }
795
+
796
+ /** Byte offset (in the .wasm file) where the first data segment's payload starts, or -1. */
797
+ export function findWasmDataSegmentByteOffset(wasmBytes) {
798
+ try {
799
+ const seg = locateFirstDataSegment(wasmBytes, parseWasmSections(wasmBytes));
800
+ return seg ? seg.start : -1;
801
+ } catch {
802
+ return -1;
803
+ }
804
+ }
805
+
806
+ // =========================================================================
807
+ // 4. UNICODE VARIATION-SELECTOR SIGNED MANIFEST BRIDGE
808
+ // =========================================================================
809
+
810
+ export function encodeBridgeCarrier(envelope, carrierGlyph = "📦") {
811
+ const payloadBytes = textEncoder.encode(JSON.stringify(envelope));
812
+ const vs = [];
813
+ for (const b of payloadBytes) {
814
+ const cp = b < 16 ? 0xfe00 + b : 0xe0100 + (b - 16);
815
+ vs.push(String.fromCodePoint(cp));
816
+ }
817
+ const head = String.fromCodePoint(carrierGlyph.codePointAt(0));
818
+ return {
819
+ carrier: head + vs.join(""),
820
+ encodedBytes: payloadBytes.length,
821
+ };
822
+ }
823
+
824
+ /**
825
+ * Decodes the longest run of consecutive variation selectors in the text (so selectors elsewhere, e.g. in an
826
+ * emoji, are ignored) and verifies the envelope's signature against caller-pinned keys only
827
+ * (`options.expectedPublicKeys`, raw Ed25519 hex). Without pinned keys the result is ok: false.
828
+ */
829
+ export async function decodeBridgeCarrier(carrierText, options = {}) {
830
+ try {
831
+ let best = [];
832
+ let run = [];
833
+ for (const ch of String(carrierText ?? "")) {
834
+ const cp = ch.codePointAt(0);
835
+ if (cp >= 0xfe00 && cp <= 0xfe0f) run.push(cp - 0xfe00);
836
+ else if (cp >= 0xe0100 && cp <= 0xe01ef) run.push(cp - 0xe0100 + 16);
837
+ else {
838
+ if (run.length > best.length) best = run;
839
+ run = [];
840
+ }
841
+ }
842
+ if (run.length > best.length) best = run;
843
+ if (best.length === 0) return { ok: false, error: "NO_BRIDGE_PAYLOAD" };
844
+ const envelope = JSON.parse(textDecoder.decode(new Uint8Array(best)));
845
+ const r = await verifyEnvelopeSignature(envelope, options.expectedPublicKeys);
846
+ const ok = r.keyTrusted && r.signatureOk;
847
+ return {
848
+ ok,
849
+ signatureValid: r.signatureOk,
850
+ keyTrusted: r.keyTrusted,
851
+ signerPublicKeyHex: r.signerPublicKeyHex,
852
+ manifest: envelope.manifest,
853
+ edFxTag: envelope.edFxTag,
854
+ ...(ok ? {} : { error: r.error }),
855
+ };
856
+ } catch (err) {
857
+ return { ok: false, error: err.message };
858
+ }
859
+ }