diff --git a/lib/codegen_deno.ml b/lib/codegen_deno.ml index 04980143..86a0d476 100644 --- a/lib/codegen_deno.ml +++ b/lib/codegen_deno.ml @@ -287,6 +287,37 @@ const None = { tag: "None" }; const Ok = (value) => ({ tag: "Ok", value }); const Err = (value) => ({ tag: "Err", value }); const Unit = null; +// ---- crypto (#746): node:crypto via getBuiltinModule (Node, Bun) ---- +// snip: host crypto only; typed-wasm has no lowering for these externs yet. +const __as_crypto = () => { + const getBuiltinModule = globalThis.process?.getBuiltinModule; + if (!getBuiltinModule) throw new Error("crypto host (node:crypto) is unavailable"); + return getBuiltinModule("node:crypto"); +}; +// snip:prod - trust boundary: reject non-byte Ints instead of wrapping mod 256. +const __as_bytes = (a) => { + for (const x of a) { + if (!Number.isInteger(x) || x < 0 || x > 255) throw new RangeError(`not a byte: ${x}`); + } + return Uint8Array.from(a); +}; +// snip:prod - only RSA keys; an EC/Ed key would silently give a non-RS256 signature. +const __as_rsaKey = (pem, priv) => { + const c = __as_crypto(); + const k = priv ? c.createPrivateKey(pem) : c.createPublicKey(pem); + if (k.asymmetricKeyType !== "rsa") throw new Error(`expected an RSA key, got ${k.asymmetricKeyType}`); + return k; +}; +const __as_sha256 = (b) => Array.from(__as_crypto().createHash("sha256").update(__as_bytes(b)).digest()); +const __as_hmacSha256 = (k, m) => Array.from(__as_crypto().createHmac("sha256", __as_bytes(k)).update(__as_bytes(m)).digest()); +const __as_b64urlEncode = (b) => globalThis.Buffer.from(__as_bytes(b)).toString("base64url"); +// snip:prod - Buffer's base64url decoder skips bad characters silently; reject them. +const __as_b64urlDecode = (s) => { + if (!/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1) throw new Error("invalid base64url"); + return Array.from(globalThis.Buffer.from(s, "base64url")); +}; +const __as_rsaSign = (pem, m) => Array.from(__as_crypto().sign("sha256", __as_bytes(m), __as_rsaKey(pem, true))); +const __as_rsaVerify = (pem, m, sig) => __as_crypto().verify("sha256", __as_bytes(m), __as_rsaKey(pem, false), __as_bytes(sig)); const __as_regexMatch = (s, pat) => new RegExp(pat).test(String(s)); const __as_wasmInstance = (bytes) => new WebAssembly.Instance(new WebAssembly.Module(bytes), @@ -921,6 +952,13 @@ let () = b "dateNowIso" (fun _ -> "(new Date().toISOString())"); (* `performance.now()` — high-resolution sub-millisecond timer. *) b "performance_now" (fun _ -> "performance.now()"); + (* ---- crypto (#746): helpers in common_prelude ---- *) + b "sha256" (fun a -> Printf.sprintf "__as_sha256(%s)" (arg 0 a)); + b "hmac_sha256" (fun a -> Printf.sprintf "__as_hmacSha256(%s, %s)" (arg 0 a) (arg 1 a)); + b "base64url_encode" (fun a -> Printf.sprintf "__as_b64urlEncode(%s)" (arg 0 a)); + b "base64url_decode" (fun a -> Printf.sprintf "__as_b64urlDecode(%s)" (arg 0 a)); + b "rsa_sign_pkcs1_sha256" (fun a -> Printf.sprintf "__as_rsaSign(%s, %s)" (arg 0 a) (arg 1 a)); + b "rsa_verify_pkcs1_sha256" (fun a -> Printf.sprintf "__as_rsaVerify(%s, %s, %s)" (arg 0 a) (arg 1 a) (arg 2 a)); (* Math.random + derived integer-range helpers (campaign #239 STEP 4-B / standards#327). Non-crypto PRNG. *) b "math_random" (fun _ -> "Math.random()"); diff --git a/stdlib/Crypto.affine b/stdlib/Crypto.affine index cc1d8308..d7d69cb3 100644 --- a/stdlib/Crypto.affine +++ b/stdlib/Crypto.affine @@ -9,3 +9,15 @@ module Crypto; pub extern fn random_string(n: Int) -> String; pub extern fn random_f64() -> Float; pub extern fn time_ms() -> Int; + +// #746: digest, MAC, base64url and RS256 signing. Bytes are [Int] in 0..255; +// a value outside that range panics. Lowered on the Bun-ESM backend (Node +// and Bun) through node:crypto. The typed-wasm backend has no lowering yet. +pub extern fn sha256(bytes: [Int]) -> [Int]; +pub extern fn hmac_sha256(key: [Int], msg: [Int]) -> [Int]; +pub extern fn base64url_encode(bytes: [Int]) -> String; +pub extern fn base64url_decode(s: String) -> [Int]; +// key_pem: PKCS#1 or PKCS#8 RSA private key. Panics on a non-RSA key. +pub extern fn rsa_sign_pkcs1_sha256(key_pem: String, msg: [Int]) -> [Int]; +// key_pem: RSA public key (or private key). False on a bad signature. +pub extern fn rsa_verify_pkcs1_sha256(key_pem: String, msg: [Int], sig: [Int]) -> Bool; diff --git a/tests/codegen-deno/crypto_smoke.affine b/tests/codegen-deno/crypto_smoke.affine new file mode 100644 index 00000000..c88a922c --- /dev/null +++ b/tests/codegen-deno/crypto_smoke.affine @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MPL-2.0 +// #746: sha256 / hmac_sha256 / base64url / RS256 sign+verify smoke. +// The harness supplies the test vectors and the RSA key pair. + +use Crypto::{ sha256, hmac_sha256, base64url_encode, base64url_decode, + rsa_sign_pkcs1_sha256, rsa_verify_pkcs1_sha256 }; + +pub fn digest(b: [Int]) -> [Int] = sha256(b); + +pub fn mac(k: [Int], m: [Int]) -> [Int] = hmac_sha256(k, m); + +pub fn b64e(b: [Int]) -> String = base64url_encode(b); + +pub fn b64d(s: String) -> [Int] = base64url_decode(s); + +pub fn sign(pem: String, m: [Int]) -> [Int] = rsa_sign_pkcs1_sha256(pem, m); + +pub fn verify(pem: String, m: [Int], sig: [Int]) -> Bool = rsa_verify_pkcs1_sha256(pem, m, sig); diff --git a/tests/codegen-deno/crypto_smoke.harness.mjs b/tests/codegen-deno/crypto_smoke.harness.mjs new file mode 100644 index 00000000..aeb05702 --- /dev/null +++ b/tests/codegen-deno/crypto_smoke.harness.mjs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MPL-2.0 +// #746: Node-ESM harness for the Crypto externs. + +import assert from "node:assert/strict"; +import { generateKeyPairSync } from "node:crypto"; + +const { digest, mac, b64e, b64d, sign, verify } = await import("./crypto_smoke.bun.js"); + +const bytes = (s) => Array.from(new TextEncoder().encode(s)); +const hex = (a) => a.map((x) => x.toString(16).padStart(2, "0")).join(""); + +// FIPS 180-2 vectors (from the issue). +assert.equal(hex(digest(bytes("abc"))), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); +assert.equal(hex(digest([])), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + +// RFC 4231 test case 2. +assert.equal(hex(mac(bytes("Jefe"), bytes("what do ya want for nothing?"))), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"); + +// base64url: RFC 4648 alphabet, no padding, round trip. +assert.equal(b64e([0xfb, 0xff, 0xfe]), "-__-"); +assert.equal(b64e(bytes("{\"alg\":\"RS256\",\"typ\":\"JWT\"}")), "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"); +const all = Array.from({ length: 256 }, (_, i) => i); +assert.deepEqual(b64d(b64e(all)), all); +assert.throws(() => b64d("ab=c"), /invalid base64url/); +assert.throws(() => b64d("abcde"), /invalid base64url/); + +// Bytes outside 0..255 are rejected, not wrapped. +assert.throws(() => digest([256]), RangeError); +assert.throws(() => digest([-1]), RangeError); + +// RS256: sign with PKCS#8 and PKCS#1 keys, verify, reject tampering and wrong key. +const kp = () => generateKeyPairSync("rsa", { modulusLength: 2048 }); +const { privateKey, publicKey } = kp(); +const pkcs8 = privateKey.export({ type: "pkcs8", format: "pem" }); +const pkcs1 = privateKey.export({ type: "pkcs1", format: "pem" }); +const pub = publicKey.export({ type: "spki", format: "pem" }); +const msg = bytes("eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiIxIn0"); +const sig = sign(pkcs8, msg); +assert.equal(sig.length, 256); +assert.deepEqual(sign(pkcs1, msg), sig); // PKCS#1 v1.5 is deterministic +assert.equal(verify(pub, msg, sig), true); +assert.equal(verify(pub, [...msg, 0x41], sig), false); +assert.equal(verify(pub, msg, [...sig.slice(0, 255), sig[255] ^ 1]), false); +assert.equal(verify(kp().publicKey.export({ type: "spki", format: "pem" }), msg, sig), false); + +// Non-RSA keys are refused. +const ec = generateKeyPairSync("ec", { namedCurve: "P-256" }).privateKey.export({ type: "pkcs8", format: "pem" }); +assert.throws(() => sign(ec, msg), /expected an RSA key/); + +console.log("crypto_smoke: ok");