#!/usr/bin/env node /** * Regression guard for the "crypto.randomUUID is not a function" crash. * * `crypto.randomUUID()` only exists in secure contexts (HTTPS, localhost, * 127.0.0.1). On a LAN HTTP page — e.g. http://192.168.200.15:8080 — the * browser exposes `crypto` WITHOUT `randomUUID`, so any direct call throws * and model saving dies. `crypto.getRandomValues()` has no secure-context * requirement, so the shared helper can always mint a proper v4 UUID. * * Two layers of protection, mirroring check-storage-ssr.mjs: * 1. behavioural — lib/ids.ts must produce unique, well-formed v4 UUIDs * under every crypto shape a browser can present, including the exact * insecure-context shape that produced the original crash. * 2. static — direct `crypto.randomUUID(` calls are banned outside * lib/ids.ts, so the crash cannot be reintroduced by copying the old * pattern into a new page. * * Run with `npm test` (or `node scripts/check-random-uuid.mjs`). */ import { readFileSync, readdirSync } from "node:fs"; import { dirname, join, relative } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; const HERE = dirname(fileURLToPath(import.meta.url)); const ROOT = join(HERE, ".."); const SRC = join(ROOT, "src"); const HELPER = join(SRC, "lib", "ids.ts"); let failures = 0; function fail(message) { failures += 1; console.error(`FAIL ${message}`); } function ok(message) { console.log(`ok ${message}`); } const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; /** Capture the platform crypto before any test replaces it. */ const REAL_CRYPTO = globalThis.crypto; /** Replace the global under test. Node's own binding may be getter-only. */ function setGlobalCrypto(value) { Object.defineProperty(globalThis, "crypto", { value, configurable: true, writable: true, }); } const { randomId } = await import(pathToFileURL(HELPER).href); // ---- 1. behavioural ---------------------------------------------------- // The exact shape a LAN HTTP browser presents: crypto WITHOUT randomUUID. // This is the configuration that produced the original crash. const insecureContextCrypto = { getRandomValues: REAL_CRYPTO.getRandomValues.bind(REAL_CRYPTO), }; setGlobalCrypto(insecureContextCrypto); try { const ids = new Set(Array.from({ length: 1000 }, randomId)); if (ids.size !== 1000) fail(`insecure context: duplicate ids (${1000 - ids.size} collisions)`); else if (![...ids].every((id) => UUID_V4.test(id))) { fail("insecure context: ids are not all well-formed v4 UUIDs"); } else { ok("insecure-context crypto (getRandomValues only) yields unique v4 UUIDs"); } } catch (err) { fail(`insecure-context crypto threw: ${err.message}`); } // crypto present but BOTH sources missing (exotic embed / ancient runtime). setGlobalCrypto({}); try { const ids = new Set(Array.from({ length: 1000 }, randomId)); if (ids.size !== 1000) fail(`method-less crypto: duplicate ids (${1000 - ids.size} collisions)`); else if (![...ids].every((id) => id.length >= 16)) { fail("method-less crypto: ids too short to be collision-resistant"); } else { ok( "method-less crypto degrades to unique best-effort ids without throwing", ); } } catch (err) { fail(`method-less crypto threw: ${err.message}`); } // crypto entirely absent. setGlobalCrypto(undefined); try { const ids = new Set(Array.from({ length: 1000 }, randomId)); if (ids.size !== 1000) fail(`absent crypto: duplicate ids (${1000 - ids.size} collisions)`); else ok("absent crypto degrades to unique best-effort ids without throwing"); } catch (err) { fail(`absent crypto threw: ${err.message}`); } // A fully-featured crypto (secure context / Node default) must still be used // directly — guards against a helper that ignores randomUUID. setGlobalCrypto(REAL_CRYPTO); try { const probe = { used: false }; setGlobalCrypto({ randomUUID: () => { probe.used = true; return REAL_CRYPTO.randomUUID(); }, getRandomValues: REAL_CRYPTO.getRandomValues.bind(REAL_CRYPTO), }); const id = randomId(); if (!probe.used) fail("native randomUUID available but not preferred"); else if (!UUID_V4.test(id)) fail(`secure-context id malformed: ${id}`); else ok("native randomUUID preferred when available"); } catch (err) { fail(`secure-context crypto threw: ${err.message}`); } finally { setGlobalCrypto(REAL_CRYPTO); } // ---- 2. static --------------------------------------------------------- const UNSAFE = /crypto\.randomUUID\s*\(/; const EXTENSIONS = [".ts", ".js", ".svelte"]; function walk(dir) { const found = []; for (const entry of readdirSync(dir, { withFileTypes: true })) { const full = join(dir, entry.name); if (entry.isDirectory()) { if (entry.name === "node_modules") continue; found.push(...walk(full)); } else if (EXTENSIONS.some((ext) => entry.name.endsWith(ext))) { found.push(full); } } return found; } const offenders = []; for (const file of walk(SRC)) { if (file === HELPER) continue; // the one place allowed to call the native API const lines = readFileSync(file, "utf8").split("\n"); lines.forEach((line, i) => { if (UNSAFE.test(line)) offenders.push(`${relative(ROOT, file)}:${i + 1}: ${line.trim()}`); }); } if (offenders.length) { fail( `direct \`crypto.randomUUID()\` call outside lib/ids.ts — use randomId() instead (insecure contexts crash on it):\n ${offenders.join("\n ")}`, ); } else { ok("no direct `crypto.randomUUID()` calls in src/"); } // ---- result ------------------------------------------------------------ if (failures) { console.error(`\n${failures} randomId/insecure-context check(s) failed.`); process.exit(1); } console.log("\nrandomId insecure-context checks passed.");