@qntx/spark-wasm 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,6 @@
1
+ qntx/spark
2
+ Copyright 2026 QuantX
3
+
4
+ This product includes software derived from Spark (https://github.com/buildonspark/spark),
5
+ Copyright Lightspark Group, Inc., licensed under the Apache License, Version 2.0.
6
+ Modified files carry a notice stating the upstream path, commit and changes.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @qntx/spark-wasm
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
+ `spark.wasm` SparkCrypto backend — `crates/spark-ffi` compiled to WebAssembly behind a C ABI —
4
+ for use with [`@qntx/spark`](../spark). Platform-neutral: the default entry loads the artifact
5
+ from disk-friendly bundlers, the `browser` export fetches it over HTTP.
6
+
7
+ Status: **pre-release**. See the [repository](https://github.com/qntx/spark) and
8
+ [CHANGELOG](https://github.com/qntx/spark/blob/main/CHANGELOG.md).
9
+
10
+ ## Usage
11
+
12
+ ```ts
13
+ import { loadSparkWasm } from "@qntx/spark-wasm";
14
+
15
+ const crypto = await loadSparkWasm();
16
+ ```
17
+
18
+ Every call compiles a fresh `SparkCrypto` instance the caller owns.
19
+
20
+ ## Verifying the artifact (Worker / fetch SRI)
21
+
22
+ `SPARK_WASM_INTEGRITY` is the build-time Subresource Integrity hash (`sha256-<base64>`) of the
23
+ shipped `spark.wasm`. A host that fetches the artifact itself — e.g. a Wallet Worker — can pin
24
+ it at fetch time and pass the verified bytes to `loadSparkWasm`:
25
+
26
+ ```ts
27
+ import { loadSparkWasm, SPARK_WASM_INTEGRITY } from "@qntx/spark-wasm";
28
+
29
+ const res = await fetch(wasmUrl, { integrity: SPARK_WASM_INTEGRITY });
30
+ const crypto = await loadSparkWasm({ module: await res.arrayBuffer() });
31
+ ```
32
+
33
+ `loadSparkWasm()` without `module` loads `spark.wasm` itself and does **not** verify the hash —
34
+ callers that need SRI enforcement must fetch with `integrity` as above. The constant is
35
+ reproduced by the pinned `linux/amd64` Docker build (`bun run build:wasm`) and checked against
36
+ the packed artifact in tests.
@@ -0,0 +1,10 @@
1
+ import { n as LoadSparkWasmOptions, r as WasmPoisonedError, t as SPARK_WASM_INTEGRITY } from "./integrity-DJEbBCbf.mjs";
2
+ import { SparkCrypto } from "@qntx/spark/crypto";
3
+ //#region src/load.browser.d.ts
4
+ /**
5
+ * Compiles and instantiates `spark.wasm`. Every call returns a fresh {@link SparkCrypto} the caller
6
+ * owns.
7
+ */
8
+ export declare function loadSparkWasm(opts?: LoadSparkWasmOptions): Promise<SparkCrypto>;
9
+ //#endregion
10
+ export { type LoadSparkWasmOptions, SPARK_WASM_INTEGRITY, WasmPoisonedError };
@@ -0,0 +1,22 @@
1
+ import { i as instantiateSparkWasm, n as WasmPoisonedError, r as bindSparkExports, t as SPARK_WASM_INTEGRITY } from "./integrity-BqCxc4x5.mjs";
2
+ import { SparkError } from "@qntx/spark/crypto";
3
+ //#region src/load.browser.ts
4
+ async function fetchWasmUrl(url) {
5
+ const res = await fetch(url);
6
+ if (!res.ok) throw new SparkError(`spark.wasm fetch failed (HTTP ${res.status})`);
7
+ return new Uint8Array(await res.arrayBuffer());
8
+ }
9
+ async function wasmBytes(opts) {
10
+ const source = opts?.module;
11
+ if (source !== void 0) return source;
12
+ return fetchWasmUrl(new URL("spark.wasm", import.meta.url));
13
+ }
14
+ /**
15
+ * Compiles and instantiates `spark.wasm`. Every call returns a fresh {@link SparkCrypto} the caller
16
+ * owns.
17
+ */
18
+ async function loadSparkWasm(opts) {
19
+ return bindSparkExports(await instantiateSparkWasm(await wasmBytes(opts)));
20
+ }
21
+ //#endregion
22
+ export { SPARK_WASM_INTEGRITY, WasmPoisonedError, loadSparkWasm };
@@ -0,0 +1,10 @@
1
+ import { n as LoadSparkWasmOptions, r as WasmPoisonedError, t as SPARK_WASM_INTEGRITY } from "./integrity-DJEbBCbf.mjs";
2
+ import { SparkCrypto } from "@qntx/spark/crypto";
3
+ //#region src/load.d.ts
4
+ /**
5
+ * Compiles and instantiates `spark.wasm`. Every call returns a fresh {@link SparkCrypto} the caller
6
+ * owns.
7
+ */
8
+ export declare function loadSparkWasm(opts?: LoadSparkWasmOptions): Promise<SparkCrypto>;
9
+ //#endregion
10
+ export { type LoadSparkWasmOptions, SPARK_WASM_INTEGRITY, WasmPoisonedError };
package/dist/index.mjs ADDED
@@ -0,0 +1,24 @@
1
+ import { i as instantiateSparkWasm, n as WasmPoisonedError, r as bindSparkExports, t as SPARK_WASM_INTEGRITY } from "./integrity-BqCxc4x5.mjs";
2
+ import { SparkError } from "@qntx/spark/crypto";
3
+ //#region src/load.ts
4
+ async function defaultWasmHref() {
5
+ return (await import("./spark-3CkElv_w.mjs")).default;
6
+ }
7
+ async function wasmBytes(opts) {
8
+ const source = opts?.module;
9
+ if (source !== void 0) return source;
10
+ const href = new URL(await defaultWasmHref(), import.meta.url);
11
+ if (href.protocol !== "file:") throw new SparkError(`spark.wasm URL must use the file: scheme, got ${href.protocol}`);
12
+ const { readFile } = await import("node:fs/promises");
13
+ const { fileURLToPath } = await import("node:url");
14
+ return new Uint8Array(await readFile(fileURLToPath(href)));
15
+ }
16
+ /**
17
+ * Compiles and instantiates `spark.wasm`. Every call returns a fresh {@link SparkCrypto} the caller
18
+ * owns.
19
+ */
20
+ async function loadSparkWasm(opts) {
21
+ return bindSparkExports(await instantiateSparkWasm(await wasmBytes(opts)));
22
+ }
23
+ //#endregion
24
+ export { SPARK_WASM_INTEGRITY, WasmPoisonedError, loadSparkWasm };
@@ -0,0 +1,204 @@
1
+ import { SPARK_ABI_VERSION, SparkCryptoError, SparkError } from "@qntx/spark/crypto";
2
+ //#region src/abi.ts
3
+ const OUT_PARAMS_LEN = 8;
4
+ const INTERNAL_ERROR = 8;
5
+ function requireMemory(value) {
6
+ if (!(value instanceof WebAssembly.Memory)) throw new SparkError("spark.wasm missing memory export");
7
+ return value;
8
+ }
9
+ function requireFn(value, name) {
10
+ if (typeof value !== "function") throw new SparkError(`spark.wasm missing ${name} export`);
11
+ return value;
12
+ }
13
+ function sparkWasmExports(raw) {
14
+ return {
15
+ memory: requireMemory(raw["memory"]),
16
+ qs_abi_version: requireFn(raw["qs_abi_version"], "qs_abi_version"),
17
+ qs_alloc: requireFn(raw["qs_alloc"], "qs_alloc"),
18
+ qs_free: requireFn(raw["qs_free"], "qs_free"),
19
+ qs_frost_commit: requireFn(raw["qs_frost_commit"], "qs_frost_commit"),
20
+ qs_frost_sign: requireFn(raw["qs_frost_sign"], "qs_frost_sign"),
21
+ qs_frost_aggregate: requireFn(raw["qs_frost_aggregate"], "qs_frost_aggregate"),
22
+ qs_ecies_encrypt: requireFn(raw["qs_ecies_encrypt"], "qs_ecies_encrypt"),
23
+ qs_ecies_decrypt: requireFn(raw["qs_ecies_decrypt"], "qs_ecies_decrypt"),
24
+ qs_split_secret_with_proofs: requireFn(raw["qs_split_secret_with_proofs"], "qs_split_secret_with_proofs")
25
+ };
26
+ }
27
+ /**
28
+ * Copies `bytes` into a fresh `qs_alloc` region. Empty inputs return 0 — the C side treats `(NULL,
29
+ * 0)` as an empty slice.
30
+ */
31
+ function copyIn(exports, bytes) {
32
+ const len = bytes.length;
33
+ if (len === 0) return 0;
34
+ const ptr = Number(exports.qs_alloc(len)) >>> 0;
35
+ if (ptr === 0) throw new SparkCryptoError(INTERNAL_ERROR);
36
+ new Uint8Array(exports.memory.buffer, ptr, len).set(bytes);
37
+ return ptr;
38
+ }
39
+ /** Wipes then releases a region allocated by {@link copyIn}. */
40
+ function freeIn(exports, ptr, len) {
41
+ if (ptr === 0 || len === 0) return;
42
+ new Uint8Array(exports.memory.buffer, ptr, len).fill(0);
43
+ exports.qs_free(ptr, len);
44
+ }
45
+ /**
46
+ * Runs `invoke(out, outLen)` with the 8-byte out-param region and returns the output bytes. The
47
+ * region views are taken fresh after the call because the module may grow memory inside it.
48
+ */
49
+ function callOut(exports, invoke) {
50
+ const params = Number(exports.qs_alloc(OUT_PARAMS_LEN)) >>> 0;
51
+ if (params === 0) throw new SparkCryptoError(INTERNAL_ERROR);
52
+ try {
53
+ const code = Number(invoke(params, params + 4));
54
+ if (code !== 0) throw new SparkCryptoError(code);
55
+ const view = new DataView(exports.memory.buffer, params, OUT_PARAMS_LEN);
56
+ const outPtr = view.getUint32(0, true) >>> 0;
57
+ const outLen = view.getUint32(4, true) >>> 0;
58
+ if (outPtr === 0) return /* @__PURE__ */ new Uint8Array(0);
59
+ const result = new Uint8Array(outLen);
60
+ result.set(new Uint8Array(exports.memory.buffer, outPtr, outLen));
61
+ exports.qs_free(outPtr, outLen);
62
+ return result;
63
+ } finally {
64
+ freeIn(exports, params, OUT_PARAMS_LEN);
65
+ }
66
+ }
67
+ function wasmFrostCommit(exports, hedge, random) {
68
+ const hedgePtr = copyIn(exports, hedge);
69
+ const randomPtr = copyIn(exports, random);
70
+ try {
71
+ return callOut(exports, (out, outLen) => exports.qs_frost_commit(hedgePtr, hedge.length, randomPtr, random.length, out, outLen));
72
+ } finally {
73
+ freeIn(exports, hedgePtr, hedge.length);
74
+ freeIn(exports, randomPtr, random.length);
75
+ }
76
+ }
77
+ function wasmFrostSign(exports, request) {
78
+ const requestPtr = copyIn(exports, request);
79
+ try {
80
+ return callOut(exports, (out, outLen) => exports.qs_frost_sign(requestPtr, request.length, out, outLen));
81
+ } finally {
82
+ freeIn(exports, requestPtr, request.length);
83
+ }
84
+ }
85
+ function wasmFrostAggregate(exports, request) {
86
+ const requestPtr = copyIn(exports, request);
87
+ try {
88
+ return callOut(exports, (out, outLen) => exports.qs_frost_aggregate(requestPtr, request.length, out, outLen));
89
+ } finally {
90
+ freeIn(exports, requestPtr, request.length);
91
+ }
92
+ }
93
+ function wasmEciesEncrypt(exports, publicKey, plaintext, random) {
94
+ const pkPtr = copyIn(exports, publicKey);
95
+ const msgPtr = copyIn(exports, plaintext);
96
+ const randomPtr = copyIn(exports, random);
97
+ try {
98
+ return callOut(exports, (out, outLen) => exports.qs_ecies_encrypt(pkPtr, publicKey.length, msgPtr, plaintext.length, randomPtr, random.length, out, outLen));
99
+ } finally {
100
+ freeIn(exports, pkPtr, publicKey.length);
101
+ freeIn(exports, msgPtr, plaintext.length);
102
+ freeIn(exports, randomPtr, random.length);
103
+ }
104
+ }
105
+ function wasmEciesDecrypt(exports, privateKey, ciphertext) {
106
+ const skPtr = copyIn(exports, privateKey);
107
+ const ctPtr = copyIn(exports, ciphertext);
108
+ try {
109
+ return callOut(exports, (out, outLen) => exports.qs_ecies_decrypt(skPtr, privateKey.length, ctPtr, ciphertext.length, out, outLen));
110
+ } finally {
111
+ freeIn(exports, skPtr, privateKey.length);
112
+ freeIn(exports, ctPtr, ciphertext.length);
113
+ }
114
+ }
115
+ /**
116
+ * Mirrors the native `toUint32` guard: a JS `number` arrives as a double and the wasm ABI coerces
117
+ * it to i32, truncating fractions and wrapping values past 2^32 — reject them first.
118
+ */
119
+ function checkUint32(value, name) {
120
+ if (!Number.isInteger(value) || value < 0 || value > 4294967295) throw new SparkError(`${name} must be an integer in [0, 2^32)`);
121
+ }
122
+ function wasmSplitSecretWithProofs(exports, secret, threshold, shares, random) {
123
+ checkUint32(threshold, "threshold");
124
+ checkUint32(shares, "shares");
125
+ const secretPtr = copyIn(exports, secret);
126
+ const randomPtr = copyIn(exports, random);
127
+ try {
128
+ return callOut(exports, (out, outLen) => exports.qs_split_secret_with_proofs(secretPtr, secret.length, threshold, shares, randomPtr, random.length, out, outLen));
129
+ } finally {
130
+ freeIn(exports, secretPtr, secret.length);
131
+ freeIn(exports, randomPtr, random.length);
132
+ }
133
+ }
134
+ /**
135
+ * Compiles and instantiates `spark.wasm`. The module must declare no imports and must implement ABI
136
+ * version {@link SPARK_ABI_VERSION} — a mismatch means the artifact predates or postdates this
137
+ * loader and instantiation fails.
138
+ */
139
+ async function instantiateSparkWasm(bytes) {
140
+ const module = await WebAssembly.compile(bytes);
141
+ const imports = WebAssembly.Module.imports(module);
142
+ if (imports.length > 0) throw new SparkError(`spark.wasm module must not declare imports (got ${imports.length})`);
143
+ const instance = await WebAssembly.instantiate(module, {});
144
+ const version = Number(requireFn(instance.exports["qs_abi_version"], "qs_abi_version")());
145
+ if (version !== SPARK_ABI_VERSION) throw new SparkError(`spark.wasm ABI version ${version} does not match loader ABI version ${SPARK_ABI_VERSION}`);
146
+ return sparkWasmExports(instance.exports);
147
+ }
148
+ //#endregion
149
+ //#region src/instance.ts
150
+ /** Wasm instance aborted; later calls on that instance fail. */
151
+ var WasmPoisonedError = class extends SparkCryptoError {
152
+ name = "WasmPoisonedError";
153
+ };
154
+ /**
155
+ * Runs `fn` unless the instance is already poisoned; a `WebAssembly.RuntimeError` aborts the
156
+ * instance, so it is converted to {@link WasmPoisonedError} and rethrown on every later call. The
157
+ * aborted instance's whole linear memory is zeroed first — per-input regions are wiped on the
158
+ * success path, but a trap can leave secret copies elsewhere in memory.
159
+ */
160
+ function runSparkPoisoned(poison, memory, fn) {
161
+ if (poison.error !== void 0) throw poison.error;
162
+ try {
163
+ return fn();
164
+ } catch (error) {
165
+ if (error instanceof WebAssembly.RuntimeError) {
166
+ new Uint8Array(memory.buffer).fill(0);
167
+ poison.error = new WasmPoisonedError(8, { cause: error });
168
+ throw poison.error;
169
+ }
170
+ throw error;
171
+ }
172
+ }
173
+ /** Binds the raw wasm exports into a {@link SparkCrypto} backend. */
174
+ function bindSparkExports(exports) {
175
+ const poison = {};
176
+ const run = (fn) => runSparkPoisoned(poison, exports.memory, fn);
177
+ return {
178
+ abiVersion: SPARK_ABI_VERSION,
179
+ frostCommit: (hedge, random) => run(() => wasmFrostCommit(exports, hedge, random)),
180
+ frostSign: (request) => run(() => wasmFrostSign(exports, request)),
181
+ frostAggregate: (request) => run(() => wasmFrostAggregate(exports, request)),
182
+ eciesEncrypt: (publicKey, plaintext, random) => run(() => wasmEciesEncrypt(exports, publicKey, plaintext, random)),
183
+ eciesDecrypt: (privateKey, ciphertext) => run(() => wasmEciesDecrypt(exports, privateKey, ciphertext)),
184
+ splitSecretWithProofs: (secret, threshold, shares, random) => run(() => wasmSplitSecretWithProofs(exports, secret, threshold, shares, random))
185
+ };
186
+ }
187
+ //#endregion
188
+ //#region src/integrity.ts
189
+ /**
190
+ * Subresource Integrity hash (`sha256-<base64>`) of the shipped `spark.wasm`, regenerated whenever
191
+ * the artifact is rebuilt. Consumers that fetch the module themselves — for example a Wallet Worker
192
+ * — can pin it at fetch time and hand the verified bytes to `loadSparkWasm`:
193
+ *
194
+ * ```ts
195
+ * const res = await fetch(wasmUrl, { integrity: SPARK_WASM_INTEGRITY });
196
+ * const crypto = await loadSparkWasm({ module: await res.arrayBuffer() });
197
+ * ```
198
+ *
199
+ * `loadSparkWasm()` without `module` loads `spark.wasm` itself and does NOT verify this hash —
200
+ * callers that want SRI enforcement must fetch with `integrity` and pass `module`.
201
+ */
202
+ const SPARK_WASM_INTEGRITY = "sha256-Fz0TXNqWeqJrTBlBJIx38L71/3ZrOjKgIxPvLXi6sTI=";
203
+ //#endregion
204
+ export { instantiateSparkWasm as i, WasmPoisonedError as n, bindSparkExports as r, SPARK_WASM_INTEGRITY as t };
@@ -0,0 +1,28 @@
1
+ import { SparkCrypto, SparkCryptoError } from "@qntx/spark/crypto";
2
+ //#region src/instance.d.ts
3
+ type LoadSparkWasmOptions = {
4
+ /** Wasm module bytes. When omitted the platform loader reads the bundled `spark.wasm` artifact. */
5
+ module?: ArrayBuffer | ArrayBufferView | undefined;
6
+ };
7
+ /** Wasm instance aborted; later calls on that instance fail. */
8
+ declare class WasmPoisonedError extends SparkCryptoError {
9
+ name: string;
10
+ }
11
+ //#endregion
12
+ //#region src/integrity.d.ts
13
+ /**
14
+ * Subresource Integrity hash (`sha256-<base64>`) of the shipped `spark.wasm`, regenerated whenever
15
+ * the artifact is rebuilt. Consumers that fetch the module themselves — for example a Wallet Worker
16
+ * — can pin it at fetch time and hand the verified bytes to `loadSparkWasm`:
17
+ *
18
+ * ```ts
19
+ * const res = await fetch(wasmUrl, { integrity: SPARK_WASM_INTEGRITY });
20
+ * const crypto = await loadSparkWasm({ module: await res.arrayBuffer() });
21
+ * ```
22
+ *
23
+ * `loadSparkWasm()` without `module` loads `spark.wasm` itself and does NOT verify this hash —
24
+ * callers that want SRI enforcement must fetch with `integrity` and pass `module`.
25
+ */
26
+ declare const SPARK_WASM_INTEGRITY = "sha256-Fz0TXNqWeqJrTBlBJIx38L71/3ZrOjKgIxPvLXi6sTI=";
27
+ //#endregion
28
+ export { LoadSparkWasmOptions as n, WasmPoisonedError as r, SPARK_WASM_INTEGRITY as t };
@@ -0,0 +1,4 @@
1
+ //#region \0wasm-url:/home/runner/work/spark/spark/packages/spark-wasm/src/spark.wasm
2
+ var spark_default = new URL("spark.wasm", import.meta.url).href;
3
+ //#endregion
4
+ export { spark_default as default };
Binary file
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@qntx/spark-wasm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "spark.wasm SparkCrypto backend — C ABI from crates/spark-ffi, platform-neutral and browser-first",
5
+ "keywords": [
6
+ "bitcoin",
7
+ "ecies",
8
+ "frost",
9
+ "lightning",
10
+ "secret-sharing",
11
+ "spark",
12
+ "threshold-signatures",
13
+ "typescript",
14
+ "vss",
15
+ "wasm",
16
+ "webassembly"
17
+ ],
18
+ "license": "Apache-2.0",
19
+ "author": {
20
+ "name": "quantumcat",
21
+ "url": "https://x.com/quantumcat"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/qntx/spark.git",
26
+ "directory": "packages/spark-wasm"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "LICENSE",
31
+ "NOTICE"
32
+ ],
33
+ "type": "module",
34
+ "sideEffects": [
35
+ "**/*.wasm"
36
+ ],
37
+ "exports": {
38
+ ".": {
39
+ "types": "./dist/index.d.mts",
40
+ "browser": "./dist/browser.mjs",
41
+ "import": "./dist/index.mjs",
42
+ "default": "./dist/index.mjs"
43
+ },
44
+ "./browser": {
45
+ "types": "./dist/browser.d.mts",
46
+ "import": "./dist/browser.mjs",
47
+ "default": "./dist/browser.mjs"
48
+ },
49
+ "./package.json": "./package.json"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "scripts": {
55
+ "build": "vp pack",
56
+ "build:wasm": "vp run @qntx/spark#build && bash scripts/docker-build.sh && vp pack",
57
+ "test": "vp run @qntx/spark#build && vp pack && vp test",
58
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.src.json",
59
+ "check:pkg": "vp run @qntx/spark#build && vp pack && publint && attw --pack . --profile esm-only"
60
+ },
61
+ "devDependencies": {
62
+ "@arethetypeswrong/cli": "0.18.5",
63
+ "@qntx/spark": "0.1.0",
64
+ "@qntx/tsconfig": "1.0.1",
65
+ "@types/node": "26.6.5",
66
+ "publint": "0.3.25",
67
+ "typescript": "7.0.2",
68
+ "vite-plus": "1.2.0"
69
+ },
70
+ "peerDependencies": {
71
+ "@qntx/spark": "^0.1.0"
72
+ }
73
+ }