Pick a WASM variant, validate provenance, load a module
Pick the SIMD or scalar WASM build for the engine, and check its provenance before loading it.
Apache-2.0Node
Package: @awacloud/fw-wasm-crypto
Run it
Node Guide
Choose the SIMD or scalar variant for this engine, validate a vendored-source
provenance record (a corrupted copy lists its errors), and load a .wasm
through the ABI-checking loader when one is present.
Uses @awacloud/fw-wasm-crypto (Apache-2.0). This example's code is Apache-2.0.
When to use it
You ship or audit the WebAssembly crypto modules outside fw's runtime: a build script that checks which variant a host can run, a supply-chain check of the vendored sources' provenance, or a custom loader that reads the bytes from your own location.
Copy-paste steps
npm install @awacloud/fw-wasm-crypto @awacloud/fw(fw ships the committed.wasmfiles the second command loads).- Copy
main.jsand runbun main.js(validates the installed package's ownvendor/PROVENANCE.json), orbun main.js <record.json> node_modules/@awacloud/fw/src/crypto/wasmto also load a committed.wasm(node main.js …works the same). - Keep
fetchBytespointing at wherever your.wasmfiles live; without it the loader reads the package's owndist/.
What it shows
supportsSimd()andselectVariant(): the engine decides betweensimdandscalar.provenanceErrors(record)(sorted list, empty when valid) andvalidateProvenance(record)(throws on the first error).loadWasmModule(name, expectedExports, { variant, fetchBytes }): the zero-import invariant and thememory/alloc/freeABI are checked before the handle is returned.- An absent module is a reported state, not an exception.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
// Run: bun main.js [provenance.json] [dir-with-wasm] (or node main.js …)
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadWasmModule, selectVariant, supportsSimd } from '@awacloud/fw-wasm-crypto/loader';
import { provenanceErrors, validateProvenance } from '@awacloud/fw-wasm-crypto/provenance';
/** The package's own record, where npm puts it; pass another path as the first argument. */
export const DEFAULT_PROVENANCE = 'node_modules/@awacloud/fw-wasm-crypto/vendor/PROVENANCE.json';
/** The variant the loader would pick here, and why. */
export function pickVariant() {
return { simd: supportsSimd(), variant: selectVariant() };
}
/**
* Non-throwing and throwing validation of one record.
* @param {unknown} record
* @returns {{ valid: boolean, errors: string[] }}
*/
export function checkProvenance(record) {
const errors = provenanceErrors(record);
if (errors.length === 0) validateProvenance(record); // the throwing form agrees
return { valid: errors.length === 0, errors };
}
/**
* Load `<dir>/<name>.<variant>.wasm` when it exists; the loader checks the
* zero-import invariant, the memory / alloc / free ABI, and that the
* algorithm function `<name>` is exported, before returning.
* @param {string} name e.g. `blake2b`
* @param {string} dir
* @returns {Promise<{ loaded: boolean, reason?: string, variant?: string, functions?: string[] }>}
*/
export async function loadIfPresent(name, dir) {
const variant = ['simd', 'scalar'].find((v) => existsSync(join(dir, `${name}.${v}.wasm`)));
if (!variant) return { loaded: false, reason: `no ${name}.{simd,scalar}.wasm in the given directory` };
/** @param {string} n @param {string} v */
const fetchBytes = async (n, v) => new Uint8Array(readFileSync(join(dir, `${n}.${v}.wasm`)));
const handle = await loadWasmModule(name, [name], { variant, fetchBytes });
const functions = Object.keys(handle.exports).filter((k) => typeof handle.exports[k] === 'function').sort();
return { loaded: true, variant: handle.variant, functions };
}
/** @param {string[]} argv */
export async function main(argv = process.argv.slice(2)) {
const [provenancePath = DEFAULT_PROVENANCE, wasmDir] = argv;
const record = JSON.parse(readFileSync(provenancePath, 'utf8'));
// A corrupted copy: every pinned digest replaced. `sha256: ""` would mean "unpinned seed", not corrupt.
const corrupted = { ...record, trees: record.trees.map((t) => ({ ...t, sha256: 'not-a-digest' })) };
const { variant, simd } = pickVariant();
const lines = [
`variant: ${variant} (simd128 ${simd ? 'supported' : 'not supported'})`,
`provenance: ${checkProvenance(record).valid ? 'valid' : 'INVALID'} (${record.trees.length} tree(s))`,
`corrupted copy: ${checkProvenance(corrupted).errors.join('; ')}`,
];
const load = wasmDir ? await loadIfPresent('blake2b', wasmDir) : { loaded: false, reason: 'no directory given' };
lines.push(load.loaded ? `blake2b.${load.variant}.wasm loaded, exports ${load.functions?.join(', ')}`
: `wasm: ${load.reason}`);
return lines;
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
for (const line of await main()) console.log(line);
}