// The whole JavaScript side of custos-wasm (see src/lib.rs, "ABI"): load the module, give it the // browser's CSPRNG, and pass JSON requests in and out. The vault key never leaves WebAssembly memory. /** @param {BufferSource | Response | Promise} source the custos_wasm.wasm bytes or a fetch of them */ export async function loadCustos(source) { let memory; const env = { random_fill(ptr, len) { // getRandomValues fills at most 65,536 bytes per call. for (let off = 0; off < len; off += 65536) { crypto.getRandomValues(new Uint8Array(memory.buffer, ptr + off, Math.min(65536, len - off))); } }, }; const { instance } = source instanceof Response || source instanceof Promise ? await WebAssembly.instantiateStreaming(source, { env }) : await WebAssembly.instantiate(source, { env }); const x = instance.exports; memory = x.memory; const enc = new TextEncoder(); const dec = new TextDecoder(); /** Sends one request; resolves to the parsed response ({ok: true, …} or {ok: false, error}). */ function call(request) { const bytes = enc.encode(JSON.stringify(request)); const ptr = x.alloc(bytes.length); new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes); bytes.fill(0); const packed = x.call(ptr, bytes.length); // frees and zeroes the request const outPtr = Number(packed >> 32n); const outLen = Number(packed & 0xffffffffn); const out = new Uint8Array(memory.buffer, outPtr, outLen); const text = dec.decode(out); x.dealloc(outPtr, outLen); // zeroes the response in WebAssembly memory return JSON.parse(text); } return { call }; } /** Base64 of bytes, for the `open` and `share_open` requests. */ export function toBase64(bytes) { let s = ''; for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(s); }