@eyeoverthink/wasm-deflate-vault 0.0.0-stage → 1.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.
package/LICENSE ADDED
@@ -0,0 +1,174 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the Work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or
41
+ Object form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf
53
+ of the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated into the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work a copy of this
95
+ License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the NOTICE file within such Work,
109
+ excluding those notices that do not pertain to any part of
110
+ the Derivative Works, in at least one of the following places:
111
+ within a NOTICE text file distributed as part of the Work; within
112
+ the Source form or documentation, if provided along with the
113
+ Work; or, within a display generated by the Derivative Works,
114
+ if and wherever such third-party notices normally appear. The
115
+ contents of the NOTICE file are for informational purposes only
116
+ and do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional notices cannot be construed as modifying
120
+ the License.
121
+
122
+ You may add Your own copyright notice to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the copyright notice.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (including intentional or gross
155
+ negligence) damages, shall any Contributor be liable to You for
156
+ damages, including any direct, indirect, incidental, special,
157
+ incidental, or consequential damages of any kind arising out of this
158
+ License or out of the use or inability to use the Work (including
159
+ but not limited to loss of data, loss of profits, or business
160
+ interruption), even if such Contributor has been advised of the
161
+ possibility of such damages.
162
+
163
+ 9. Accepting Warranty or Additional Liability. While redistributing
164
+ the Work or Derivative Works thereof, You may choose to offer,
165
+ and charge a fee for, acceptance of support, warranty, indemnity,
166
+ or other liability obligations and/or rights consistent with this
167
+ License. However, in accepting such obligations, You may act only
168
+ on Your own behalf and on Your own sole responsibility, not on behalf
169
+ of any other Contributor, and only if You agree to indemnify,
170
+ defend, and hold each Contributor harmless for any liability
171
+ incurred by, or claims asserted against, such Contributor by reason
172
+ of your accepting any such warranty or additional liability.
173
+
174
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # WASM Deflate Vault (`v1.0.0`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/eyeoverthink/wasm-deflate-vault/actions/workflows/ci.yml/badge.svg)](https://github.com/eyeoverthink/wasm-deflate-vault/actions/workflows/ci.yml)
4
+ [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
5
+
6
+ Zero-dependency, **100% offline** unification of `java__java-rosetta-stone-perfect-v2.html` + `transmutation__Transmutation-Bridge-Key-Encoded.html`:
7
+
8
+ - **Live Vault Studio:** https://eyeoverthink.github.io/wasm-deflate-vault/
9
+ - **Repository:** https://github.com/eyeoverthink/wasm-deflate-vault (`v1.0.0`, Apache-2.0)
10
+
11
+ ## Primitives
12
+
13
+ 1. **Self-Extracting Deflate-in-WASM (`packDeflateWasmContainer` / `unpackAndVerifyWasmContainer`):** Compresses multi-file bundles via `CompressionStream('deflate')` (`78 9c` zlib header), embeds the payload into a `.wasm` linear-memory Data segment alongside `"wdv.manifest"`, instantiates via native `WebAssembly.instantiate()`, and verifies magic `0x57445631`, SHA-256, Ed25519 signature, and RFC 6962 Merkle root.
14
+ 2. **Per-File RFC 6962 Merkle Inclusion Proofs:** Proves any single file (`getFileMerkleProof` / `verifyFileMerkleProof`) against the signed root.
15
+ 3. **Standard PKZIP (`0x04034b50` + CRC-32) Builder & Inspector** + **Variation-Selector Signed Carrier Bridge**.
16
+
17
+ ## Quick Start
18
+
19
+ ```bash
20
+ npm install @eyeoverthink/wasm-deflate-vault
21
+ npm test
22
+ ```
23
+
24
+ ## License
25
+
26
+ Apache-2.0 — see [LICENSE](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@eyeoverthink/wasm-deflate-vault",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Zero-dependency Self-Extracting Deflate-in-WASM container, IEEE 802.3 CRC-32 PKZIP builder/inspector, RFC 6962 per-file Merkle inclusion prover, WebCrypto Ed25519 signing, and Unicode Variation-Selector bridge.",
6
+ "license": "Apache-2.0",
7
+ "main": "./src/wasm-deflate-vault.js",
8
+ "types": "./src/wasm-deflate-vault.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./src/wasm-deflate-vault.d.ts",
12
+ "import": "./src/wasm-deflate-vault.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "src/",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "keywords": [
21
+ "wasm",
22
+ "deflate",
23
+ "pkzip",
24
+ "merkle-tree",
25
+ "rfc6962",
26
+ "ed25519",
27
+ "steganography",
28
+ "zero-dependency"
29
+ ],
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/eyeoverthink/wasm-deflate-vault.git"
33
+ },
34
+ "homepage": "https://eyeoverthink.github.io/wasm-deflate-vault/",
35
+ "bugs": {
36
+ "url": "https://github.com/eyeoverthink/wasm-deflate-vault/issues"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "scripts": {
42
+ "test": "node --test test/vault.test.js"
43
+ },
44
+ "engines": {
45
+ "node": ">=20.0.0"
46
+ }
47
+ }
@@ -0,0 +1,17 @@
1
+ export const VERSION: string;
2
+ export const VAULT_MAGIC: number;
3
+
4
+ export function crc32(bytes: Uint8Array): number;
5
+ export function buildZipArchive(filesMap: Record<string, string | Uint8Array>): Uint8Array;
6
+ export function inspectZipArchive(zipBytes: Uint8Array): { ok: boolean; magicHex?: string; entryCount?: number; totalBytes?: number; cdMatch?: boolean; entries?: unknown[]; error?: string };
7
+
8
+ export function buildFileMerkleTree(filesMap: Record<string, string | Uint8Array>): Promise<{ filenames: string[]; leafCount: number; layers: string[][]; rootHex: string }>;
9
+ export function getFileMerkleProof(tree: { filenames: string[]; layers: string[][]; rootHex: string }, filename: string): { filename: string; leafHash: string; proof: Array<{ position: "left" | "right"; hash: string }>; rootHex: string };
10
+ export function verifyFileMerkleProof(opts: { filename: string; content: string | Uint8Array; proof: Array<{ position: "left" | "right"; hash: string }>; rootHex: string }): Promise<{ ok: boolean; computedRoot: string; expectedRoot: string }>;
11
+
12
+ export function packDeflateWasmContainer(filesMap: Record<string, string | Uint8Array>, options?: { issuedAt?: string; keyPair?: CryptoKeyPair }): Promise<{ wasmBytes: Uint8Array; wasmByteLength: number; manifest: Record<string, unknown>; envelope: Record<string, unknown>; merkleTree: Awaited<ReturnType<typeof buildFileMerkleTree>> }>;
13
+ export function unpackAndVerifyWasmContainer(wasmBytes: Uint8Array): Promise<{ ok: boolean; checks: { magicOk: boolean; sha256Ok: boolean; signatureOk: boolean; merkleOk: boolean }; manifest?: Record<string, unknown>; edFxTag?: string; files?: Record<string, string>; merkleTree?: Awaited<ReturnType<typeof buildFileMerkleTree>>; error?: string }>;
14
+ export function findWasmDataSegmentByteOffset(wasmBytes: Uint8Array): number;
15
+
16
+ export function encodeBridgeCarrier(envelope: Record<string, unknown>, carrierGlyph?: string): { carrier: string; encodedBytes: number };
17
+ export function decodeBridgeCarrier(carrierText: string): Promise<{ ok: boolean; signatureValid?: boolean; manifest?: Record<string, unknown>; edFxTag?: string; error?: string }>;
@@ -0,0 +1,639 @@
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 = "1.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
+ let total = 0;
31
+ for (const c of chunks) total += c.length;
32
+ const out = new Uint8Array(total);
33
+ let off = 0;
34
+ for (const c of chunks) {
35
+ out.set(c, off);
36
+ off += c.length;
37
+ }
38
+ return out;
39
+ }
40
+
41
+ function bytesToBase64(bytes) {
42
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
43
+ let bin = "";
44
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
45
+ return btoa(bin);
46
+ }
47
+
48
+ function base64ToBytes(b64) {
49
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(b64, "base64"));
50
+ const bin = atob(b64);
51
+ const out = new Uint8Array(bin.length);
52
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
53
+ return out;
54
+ }
55
+
56
+ async function sha256Bytes(bytes) {
57
+ return new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
58
+ }
59
+
60
+ async function sha256Hex(bytes) {
61
+ return bytesToHex(await sha256Bytes(bytes));
62
+ }
63
+
64
+ // =========================================================================
65
+ // 1. IEEE 802.3 CRC-32 & STANDARD PKZIP ARCHIVE BUILDER / INSPECTOR
66
+ // =========================================================================
67
+
68
+ const CRC32_TABLE = (() => {
69
+ const tbl = new Uint32Array(256);
70
+ for (let i = 0; i < 256; i++) {
71
+ let c = i;
72
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
73
+ tbl[i] = c >>> 0;
74
+ }
75
+ return tbl;
76
+ })();
77
+
78
+ export function crc32(bytes) {
79
+ let c = 0xffffffff;
80
+ for (let i = 0; i < bytes.length; i++) {
81
+ c = CRC32_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
82
+ }
83
+ return (c ^ 0xffffffff) >>> 0;
84
+ }
85
+
86
+ /**
87
+ * Builds a compliant Store-mode PKZIP archive (0x04034b50 local headers,
88
+ * 0x02014b50 central directory, 0x06054b50 EOCD) from a { filename: content } map.
89
+ */
90
+ export function buildZipArchive(filesMap) {
91
+ const names = Object.keys(filesMap).sort();
92
+ const localParts = [];
93
+ const centralParts = [];
94
+ let offset = 0;
95
+
96
+ for (const name of names) {
97
+ const nameBytes = textEncoder.encode(name);
98
+ const content = filesMap[name];
99
+ const dataBytes = content instanceof Uint8Array ? content : textEncoder.encode(String(content));
100
+ const sum = crc32(dataBytes);
101
+
102
+ // Local File Header (30B + nameLen + dataLen)
103
+ const lfh = new Uint8Array(30 + nameBytes.length);
104
+ const lv = new DataView(lfh.buffer);
105
+ lv.setUint32(0, 0x04034b50, true);
106
+ lv.setUint16(4, 20, true); // version needed
107
+ lv.setUint16(6, 0x0800, true); // UTF-8 filename flag
108
+ lv.setUint16(8, 0, true); // method = Store
109
+ lv.setUint16(10, 0, true);
110
+ lv.setUint16(12, 0x5421, true);
111
+ lv.setUint32(14, sum, true);
112
+ lv.setUint32(18, dataBytes.length, true);
113
+ lv.setUint32(22, dataBytes.length, true);
114
+ lv.setUint16(26, nameBytes.length, true);
115
+ lv.setUint16(28, 0, true);
116
+ lfh.set(nameBytes, 30);
117
+
118
+ // Central Directory Header (46B + nameLen)
119
+ const cdh = new Uint8Array(46 + nameBytes.length);
120
+ const cv = new DataView(cdh.buffer);
121
+ cv.setUint32(0, 0x02014b50, true);
122
+ cv.setUint16(4, 20, true);
123
+ cv.setUint16(6, 20, true);
124
+ cv.setUint16(8, 0x0800, true);
125
+ cv.setUint16(10, 0, true);
126
+ cv.setUint16(12, 0, true);
127
+ cv.setUint16(14, 0x5421, true);
128
+ cv.setUint32(16, sum, true);
129
+ cv.setUint32(20, dataBytes.length, true);
130
+ cv.setUint32(24, dataBytes.length, true);
131
+ cv.setUint16(28, nameBytes.length, true);
132
+ cv.setUint16(30, 0, true);
133
+ cv.setUint16(32, 0, true);
134
+ cv.setUint16(34, 0, true);
135
+ cv.setUint16(36, 0, true);
136
+ cv.setUint32(38, 0, true);
137
+ cv.setUint32(42, offset, true);
138
+ cdh.set(nameBytes, 46);
139
+
140
+ localParts.push(lfh, dataBytes);
141
+ centralParts.push(cdh);
142
+ offset += lfh.length + dataBytes.length;
143
+ }
144
+
145
+ const centralBlob = concatBytes(...centralParts);
146
+ const eocd = new Uint8Array(22);
147
+ const ev = new DataView(eocd.buffer);
148
+ ev.setUint32(0, 0x06054b50, true);
149
+ ev.setUint16(4, 0, true);
150
+ ev.setUint16(6, 0, true);
151
+ ev.setUint16(8, names.length, true);
152
+ ev.setUint16(10, names.length, true);
153
+ ev.setUint32(12, centralBlob.length, true);
154
+ ev.setUint32(16, offset, true);
155
+ ev.setUint16(20, 0, true);
156
+
157
+ return concatBytes(...localParts, centralBlob, eocd);
158
+ }
159
+
160
+ /**
161
+ * Parses a Store-mode PKZIP archive and verifies every entry's IEEE CRC-32.
162
+ */
163
+ export function inspectZipArchive(zipBytes) {
164
+ if (!(zipBytes instanceof Uint8Array) || zipBytes.length < 22) {
165
+ return { ok: false, error: "INVALID_ZIP_BUFFER" };
166
+ }
167
+ const view = new DataView(zipBytes.buffer, zipBytes.byteOffset, zipBytes.byteLength);
168
+ let pos = 0;
169
+ const entries = [];
170
+ let allCrcValid = true;
171
+
172
+ while (pos + 4 <= zipBytes.length && view.getUint32(pos, true) === 0x04034b50) {
173
+ const expectedCrc = view.getUint32(pos + 14, true);
174
+ const compSize = view.getUint32(pos + 18, true);
175
+ const uncompSize = view.getUint32(pos + 22, true);
176
+ const nameLen = view.getUint16(pos + 26, true);
177
+ const extraLen = view.getUint16(pos + 28, true);
178
+ const nameStart = pos + 30;
179
+ const dataStart = nameStart + nameLen + extraLen;
180
+ if (dataStart + compSize > zipBytes.length) {
181
+ return { ok: false, error: "ZIP_TRUNCATED_ENTRY" };
182
+ }
183
+ const name = textDecoder.decode(zipBytes.subarray(nameStart, nameStart + nameLen));
184
+ const data = zipBytes.subarray(dataStart, dataStart + compSize);
185
+ const actualCrc = crc32(data);
186
+ const crcValid = actualCrc === expectedCrc;
187
+ if (!crcValid) allCrcValid = false;
188
+
189
+ entries.push({
190
+ name,
191
+ localHeaderOffset: pos,
192
+ size: uncompSize,
193
+ expectedCrcHex: expectedCrc.toString(16).padStart(8, "0"),
194
+ actualCrcHex: actualCrc.toString(16).padStart(8, "0"),
195
+ crcValid,
196
+ contentPreview: textDecoder.decode(data).slice(0, 64),
197
+ });
198
+ pos = dataStart + compSize;
199
+ }
200
+
201
+ // Verify Central Directory records match Local File Headers 1:1
202
+ let cdIndex = 0;
203
+ let cdMatch = true;
204
+ while (pos + 46 <= zipBytes.length && view.getUint32(pos, true) === 0x02014b50) {
205
+ const cdCrc = view.getUint32(pos + 16, true);
206
+ const cdNameLen = view.getUint16(pos + 28, true);
207
+ const cdExtraLen = view.getUint16(pos + 30, true);
208
+ const cdCommentLen = view.getUint16(pos + 32, true);
209
+ const cdNameStart = pos + 46;
210
+ if (cdNameStart + cdNameLen > zipBytes.length) {
211
+ cdMatch = false;
212
+ break;
213
+ }
214
+ const cdName = textDecoder.decode(zipBytes.subarray(cdNameStart, cdNameStart + cdNameLen));
215
+ const local = entries[cdIndex];
216
+ if (!local || local.name !== cdName || cdCrc.toString(16).padStart(8, "0") !== local.expectedCrcHex) {
217
+ cdMatch = false;
218
+ }
219
+ cdIndex += 1;
220
+ pos = cdNameStart + cdNameLen + cdExtraLen + cdCommentLen;
221
+ }
222
+ if (cdIndex !== entries.length) cdMatch = false;
223
+
224
+ return {
225
+ ok: allCrcValid && cdMatch && entries.length > 0,
226
+ magicHex: "0x04034b50",
227
+ entryCount: entries.length,
228
+ totalBytes: zipBytes.length,
229
+ cdMatch,
230
+ entries,
231
+ };
232
+ }
233
+
234
+ // =========================================================================
235
+ // 2. RFC 6962 PER-FILE MERKLE TREE & INCLUSION PROOFS
236
+ // =========================================================================
237
+
238
+ async function hashFileLeaf(filename, content) {
239
+ return sha256Bytes(
240
+ concatBytes(
241
+ new Uint8Array([0x00]),
242
+ textEncoder.encode(filename),
243
+ new Uint8Array([0x1f]),
244
+ content instanceof Uint8Array ? content : textEncoder.encode(String(content)),
245
+ ),
246
+ );
247
+ }
248
+
249
+ async function hashNodePair(left32, right32) {
250
+ return sha256Bytes(concatBytes(new Uint8Array([0x01]), left32, right32));
251
+ }
252
+
253
+ export async function buildFileMerkleTree(filesMap) {
254
+ const filenames = Object.keys(filesMap).sort();
255
+ if (filenames.length === 0) throw new Error("EMPTY_FILES_MAP");
256
+
257
+ const leavesBytes = await Promise.all(
258
+ filenames.map((name) => hashFileLeaf(name, filesMap[name])),
259
+ );
260
+
261
+ const layers = [leavesBytes.map(bytesToHex)];
262
+ let current = leavesBytes;
263
+
264
+ while (current.length > 1) {
265
+ const next = [];
266
+ for (let i = 0; i < current.length; i += 2) {
267
+ const left = current[i];
268
+ const right = i + 1 < current.length ? current[i + 1] : current[i];
269
+ next.push(await hashNodePair(left, right));
270
+ }
271
+ layers.push(next.map(bytesToHex));
272
+ current = next;
273
+ }
274
+
275
+ return {
276
+ filenames,
277
+ leafCount: filenames.length,
278
+ layers,
279
+ rootHex: bytesToHex(current[0]),
280
+ };
281
+ }
282
+
283
+ export function getFileMerkleProof(tree, filename) {
284
+ let idx = tree.filenames.indexOf(filename);
285
+ if (idx === -1) throw new Error(`FILE_NOT_IN_TREE: '${filename}'`);
286
+
287
+ const proof = [];
288
+ for (let level = 0; level < tree.layers.length - 1; level++) {
289
+ const layer = tree.layers[level];
290
+ const isRightNode = idx % 2 === 1;
291
+ const siblingIdx = isRightNode ? idx - 1 : idx + 1 < layer.length ? idx + 1 : idx;
292
+ proof.push({
293
+ position: isRightNode ? "left" : "right",
294
+ hash: layer[siblingIdx],
295
+ });
296
+ idx = Math.floor(idx / 2);
297
+ }
298
+
299
+ return {
300
+ filename,
301
+ leafHash: tree.layers[0][tree.filenames.indexOf(filename)],
302
+ proof,
303
+ rootHex: tree.rootHex,
304
+ };
305
+ }
306
+
307
+ export async function verifyFileMerkleProof({ filename, content, proof, rootHex }) {
308
+ let current = await hashFileLeaf(filename, content);
309
+ for (const step of proof) {
310
+ const sib = hexToBytes(step.hash);
311
+ current = step.position === "left" ? await hashNodePair(sib, current) : await hashNodePair(current, sib);
312
+ }
313
+ const computedRoot = bytesToHex(current);
314
+ return {
315
+ ok: computedRoot === rootHex,
316
+ computedRoot,
317
+ expectedRoot: rootHex,
318
+ };
319
+ }
320
+
321
+ // =========================================================================
322
+ // 3. REAL DEFLATE-IN-WASM CONTAINER + NATIVE WebAssembly.instantiate() VERIFY
323
+ // =========================================================================
324
+
325
+ function encodeUnsignedLeb128(value) {
326
+ let v = value >>> 0;
327
+ const out = [];
328
+ do {
329
+ let b = v & 0x7f;
330
+ v >>>= 7;
331
+ if (v !== 0) b |= 0x80;
332
+ out.push(b);
333
+ } while (v !== 0);
334
+ return out;
335
+ }
336
+
337
+ function encodeSignedLeb128(value) {
338
+ let v = value | 0;
339
+ const out = [];
340
+ let more = true;
341
+ while (more) {
342
+ let b = v & 0x7f;
343
+ v >>= 7;
344
+ if ((v === 0 && (b & 0x40) === 0) || (v === -1 && (b & 0x40) !== 0)) more = false;
345
+ else b |= 0x80;
346
+ out.push(b);
347
+ }
348
+ return out;
349
+ }
350
+
351
+ function readUnsignedLeb128(bytes, start) {
352
+ let result = 0;
353
+ let shift = 0;
354
+ let pos = start;
355
+ while (pos < bytes.length) {
356
+ const b = bytes[pos++];
357
+ result |= (b & 0x7f) << shift;
358
+ if ((b & 0x80) === 0) break;
359
+ shift += 7;
360
+ }
361
+ return { value: result >>> 0, nextOffset: pos };
362
+ }
363
+
364
+ function withLen(arr) {
365
+ return [...encodeUnsignedLeb128(arr.length), ...arr];
366
+ }
367
+
368
+ function makeSection(id, payloadArr) {
369
+ return [id, ...withLen(payloadArr)];
370
+ }
371
+
372
+ async function deflateBytes(raw) {
373
+ if (typeof globalThis.CompressionStream !== "function") {
374
+ return { data: raw, compressed: false };
375
+ }
376
+ const cs = new globalThis.CompressionStream("deflate");
377
+ const w = cs.writable.getWriter();
378
+ w.write(raw);
379
+ w.close();
380
+ return { data: new Uint8Array(await new Response(cs.readable).arrayBuffer()), compressed: true };
381
+ }
382
+
383
+ async function inflateBytes(comp) {
384
+ const ds = new globalThis.DecompressionStream("deflate");
385
+ const w = ds.writable.getWriter();
386
+ w.write(comp);
387
+ w.close();
388
+ return new Uint8Array(await new Response(ds.readable).arrayBuffer());
389
+ }
390
+
391
+ function parseWasmCustomSections(wasmBytes) {
392
+ const out = [];
393
+ if (
394
+ wasmBytes.length < 8 ||
395
+ wasmBytes[0] !== 0x00 ||
396
+ wasmBytes[1] !== 0x61 ||
397
+ wasmBytes[2] !== 0x73 ||
398
+ wasmBytes[3] !== 0x6d
399
+ ) {
400
+ return out;
401
+ }
402
+ let pos = 8;
403
+ while (pos < wasmBytes.length) {
404
+ const secId = wasmBytes[pos++];
405
+ const lenInfo = readUnsignedLeb128(wasmBytes, pos);
406
+ pos = lenInfo.nextOffset;
407
+ const end = pos + lenInfo.value;
408
+ if (end > wasmBytes.length) break;
409
+ if (secId === 0) {
410
+ const nameLenInfo = readUnsignedLeb128(wasmBytes, pos);
411
+ const nameStart = nameLenInfo.nextOffset;
412
+ const nameEnd = nameStart + nameLenInfo.value;
413
+ const name = textDecoder.decode(wasmBytes.subarray(nameStart, nameEnd));
414
+ const payload = wasmBytes.subarray(nameEnd, end);
415
+ out.push({ name, payload, dataOffset: nameEnd });
416
+ } else if (secId === 11) {
417
+ out.push({ id: 11, offset: pos, end });
418
+ }
419
+ pos = end;
420
+ }
421
+ return out;
422
+ }
423
+
424
+ /**
425
+ * Packs a files map into a signed self-extracting WebAssembly 1.0 binary:
426
+ * - Linear Memory active Data segment holds zlib deflate (78 9c) bundle bytes
427
+ * - Exports: memory, getPayloadPtr, getPayloadLen, getFileCount, getMagic
428
+ * - Custom section "wdv.manifest" holds manifest + Ed25519 signature + SPKI key
429
+ */
430
+ export async function packDeflateWasmContainer(filesMap, options = {}) {
431
+ const merkleTree = await buildFileMerkleTree(filesMap);
432
+ const rawJson = textEncoder.encode(JSON.stringify({ schema: "wasm-deflate-vault/1", files: filesMap }));
433
+ const { data: payloadBytes, compressed } = await deflateBytes(rawJson);
434
+ const payloadSha256Hex = await sha256Hex(payloadBytes);
435
+
436
+ const issuedAt = options.issuedAt || new Date().toISOString();
437
+ const keyPair =
438
+ options.keyPair ||
439
+ (await globalThis.crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]));
440
+
441
+ const manifest = {
442
+ schema: "wasm-deflate-vault/1",
443
+ issuedAt,
444
+ compressed,
445
+ rawBytes: rawJson.length,
446
+ payloadLen: payloadBytes.length,
447
+ zlibHeaderHex: bytesToHex(payloadBytes.slice(0, 2)),
448
+ fileCount: merkleTree.leafCount,
449
+ payloadSha256Hex,
450
+ merkleRootHex: merkleTree.rootHex,
451
+ };
452
+ const sig = new Uint8Array(
453
+ await globalThis.crypto.subtle.sign("Ed25519", keyPair.privateKey, textEncoder.encode(JSON.stringify(manifest))),
454
+ );
455
+ const spki = new Uint8Array(await globalThis.crypto.subtle.exportKey("spki", keyPair.publicKey));
456
+ const envelope = {
457
+ manifest,
458
+ signatureB64: bytesToBase64(sig),
459
+ publicKeySpkiB64: bytesToBase64(spki),
460
+ edFxTag: `ED-FX:${bytesToHex(sig.slice(0, 8)).toUpperCase()}`,
461
+ };
462
+
463
+ // Build WASM sections: Type(1), Function(3), Memory(5), Export(7), Code(10), Data(11), Custom(0)
464
+ const typeSec = makeSection(1, [0x01, 0x60, 0x00, 0x01, 0x7f]); // () -> i32
465
+ const funcSec = makeSection(3, [0x04, 0x00, 0x00, 0x00, 0x00]); // 4 funcs of type 0
466
+ const memPages = Math.max(1, Math.ceil((payloadBytes.length + 64) / 65536));
467
+ const memSec = makeSection(5, [0x01, 0x00, ...encodeUnsignedLeb128(memPages)]);
468
+
469
+ const exportItem = (name, kind, idx) => [...withLen(Array.from(textEncoder.encode(name))), kind, idx];
470
+ const exportSec = makeSection(7, [
471
+ 0x05,
472
+ ...exportItem("memory", 0x02, 0),
473
+ ...exportItem("getPayloadPtr", 0x00, 0),
474
+ ...exportItem("getPayloadLen", 0x00, 1),
475
+ ...exportItem("getFileCount", 0x00, 2),
476
+ ...exportItem("getMagic", 0x00, 3),
477
+ ]);
478
+
479
+ const constFuncBody = (val) => withLen([0x00, 0x41, ...encodeSignedLeb128(val), 0x0b]);
480
+ const codeSec = makeSection(10, [
481
+ 0x04,
482
+ ...constFuncBody(0),
483
+ ...constFuncBody(payloadBytes.length),
484
+ ...constFuncBody(merkleTree.leafCount),
485
+ ...constFuncBody(VAULT_MAGIC | 0),
486
+ ]);
487
+
488
+ // Active Data segment (memory 0, offset i32.const 0)
489
+ const dataSec = makeSection(11, [
490
+ 0x01,
491
+ 0x00,
492
+ 0x41, 0x00, 0x0b,
493
+ ...encodeUnsignedLeb128(payloadBytes.length),
494
+ ...Array.from(payloadBytes),
495
+ ]);
496
+
497
+ const secNameBytes = Array.from(textEncoder.encode("wdv.manifest"));
498
+ const envBytes = Array.from(textEncoder.encode(JSON.stringify(envelope)));
499
+ const customSec = makeSection(0, [...withLen(secNameBytes), ...envBytes]);
500
+
501
+ const wasmBytes = new Uint8Array([
502
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
503
+ ...typeSec,
504
+ ...funcSec,
505
+ ...memSec,
506
+ ...exportSec,
507
+ ...codeSec,
508
+ ...dataSec,
509
+ ...customSec,
510
+ ]);
511
+
512
+ return {
513
+ wasmBytes,
514
+ wasmByteLength: wasmBytes.length,
515
+ manifest,
516
+ envelope,
517
+ merkleTree,
518
+ };
519
+ }
520
+
521
+ export async function unpackAndVerifyWasmContainer(wasmBytes) {
522
+ const checks = { magicOk: false, sha256Ok: false, signatureOk: false, merkleOk: false };
523
+ try {
524
+ const sections = parseWasmCustomSections(wasmBytes);
525
+ const manifestSec = sections.find((s) => s.name === "wdv.manifest");
526
+ if (!manifestSec) return { ok: false, checks, error: "MISSING_WDV_MANIFEST" };
527
+
528
+ const envelope = JSON.parse(textDecoder.decode(manifestSec.payload));
529
+ const { manifest, signatureB64, publicKeySpkiB64 } = envelope;
530
+
531
+ const { instance } = await WebAssembly.instantiate(wasmBytes, {});
532
+ const { exports } = instance;
533
+ checks.magicOk = (exports.getMagic() >>> 0) === VAULT_MAGIC;
534
+ if (!checks.magicOk) return { ok: false, checks, error: "VAULT_MAGIC_MISMATCH" };
535
+
536
+ const ptr = exports.getPayloadPtr() >>> 0;
537
+ const len = exports.getPayloadLen() >>> 0;
538
+ const memView = new Uint8Array(exports.memory.buffer);
539
+ if (ptr + len > memView.length || len !== manifest.payloadLen) {
540
+ return { ok: false, checks, error: "PAYLOAD_BOUNDS_MISMATCH" };
541
+ }
542
+ const payloadBytes = memView.slice(ptr, ptr + len);
543
+
544
+ const actualSha = await sha256Hex(payloadBytes);
545
+ checks.sha256Ok = actualSha === manifest.payloadSha256Hex;
546
+
547
+ const pub = await globalThis.crypto.subtle.importKey(
548
+ "spki",
549
+ base64ToBytes(publicKeySpkiB64),
550
+ { name: "Ed25519" },
551
+ false,
552
+ ["verify"],
553
+ );
554
+ checks.signatureOk = await globalThis.crypto.subtle.verify(
555
+ "Ed25519",
556
+ pub,
557
+ base64ToBytes(signatureB64),
558
+ textEncoder.encode(JSON.stringify(manifest)),
559
+ );
560
+
561
+ if (!checks.sha256Ok || !checks.signatureOk) {
562
+ return { ok: false, checks, manifest, error: "INTEGRITY_OR_SIGNATURE_FAILED" };
563
+ }
564
+
565
+ const plainBytes = manifest.compressed ? await inflateBytes(payloadBytes) : payloadBytes;
566
+ const parsedBundle = JSON.parse(textDecoder.decode(plainBytes));
567
+ const recomputedTree = await buildFileMerkleTree(parsedBundle.files);
568
+ checks.merkleOk = recomputedTree.rootHex === manifest.merkleRootHex;
569
+
570
+ return {
571
+ ok: checks.magicOk && checks.sha256Ok && checks.signatureOk && checks.merkleOk,
572
+ checks,
573
+ manifest,
574
+ edFxTag: envelope.edFxTag,
575
+ files: parsedBundle.files,
576
+ merkleTree: recomputedTree,
577
+ };
578
+ } catch (err) {
579
+ return { ok: false, checks, error: err.message };
580
+ }
581
+ }
582
+
583
+ export function findWasmDataSegmentByteOffset(wasmBytes) {
584
+ const sections = parseWasmCustomSections(wasmBytes);
585
+ const dataSec = sections.find((s) => s.id === 11);
586
+ return dataSec ? dataSec.offset + 8 : -1;
587
+ }
588
+
589
+ // =========================================================================
590
+ // 4. UNICODE VARIATION-SELECTOR SIGNED MANIFEST BRIDGE
591
+ // =========================================================================
592
+
593
+ export function encodeBridgeCarrier(envelope, carrierGlyph = "📦") {
594
+ const payloadBytes = textEncoder.encode(JSON.stringify(envelope));
595
+ const vs = [];
596
+ for (const b of payloadBytes) {
597
+ const cp = b < 16 ? 0xfe00 + b : 0xe0100 + (b - 16);
598
+ vs.push(String.fromCodePoint(cp));
599
+ }
600
+ const head = String.fromCodePoint(carrierGlyph.codePointAt(0));
601
+ return {
602
+ carrier: head + vs.join(""),
603
+ encodedBytes: payloadBytes.length,
604
+ };
605
+ }
606
+
607
+ export async function decodeBridgeCarrier(carrierText) {
608
+ try {
609
+ const bytes = [];
610
+ for (const ch of String(carrierText ?? "")) {
611
+ const cp = ch.codePointAt(0);
612
+ if (cp >= 0xfe00 && cp <= 0xfe0f) bytes.push(cp - 0xfe00);
613
+ else if (cp >= 0xe0100 && cp <= 0xe01ef) bytes.push(cp - 0xe0100 + 16);
614
+ }
615
+ if (bytes.length === 0) return { ok: false, error: "NO_BRIDGE_PAYLOAD" };
616
+ const envelope = JSON.parse(textDecoder.decode(new Uint8Array(bytes)));
617
+ const pub = await globalThis.crypto.subtle.importKey(
618
+ "spki",
619
+ base64ToBytes(envelope.publicKeySpkiB64),
620
+ { name: "Ed25519" },
621
+ false,
622
+ ["verify"],
623
+ );
624
+ const sigValid = await globalThis.crypto.subtle.verify(
625
+ "Ed25519",
626
+ pub,
627
+ base64ToBytes(envelope.signatureB64),
628
+ textEncoder.encode(JSON.stringify(envelope.manifest)),
629
+ );
630
+ return {
631
+ ok: sigValid,
632
+ signatureValid: sigValid,
633
+ manifest: envelope.manifest,
634
+ edFxTag: envelope.edFxTag,
635
+ };
636
+ } catch (err) {
637
+ return { ok: false, error: err.message };
638
+ }
639
+ }