#!/usr/bin/env node // check-signing-key.mjs (Closed by Default, free check, v1.1.1) // // Question: does my Supabase project sign its users' sign-in tokens with P-256, // the curve in the December 2026 cryptography news? // // It reads one public file from your Supabase project (the list of keys that // sign your sign-in tokens) and tells you which kind of key you're on. // Optionally it decodes your own sign-in token and scans your own code folder. // It never sends a write, never uses a key it finds, and uploads nothing. // // Usage (Node 20 or later, no npm install): // node check-signing-key.mjs --url https://your-app.example // node check-signing-key.mjs --supabase-url https://abcd1234.supabase.co // node check-signing-key.mjs --url https://your-app.example --code ./my-app-folder // node check-signing-key.mjs --supabase-url https://abcd1234.supabase.co --token token.txt // // Options: // --url your live app; the check finds your Supabase project in its JavaScript // --supabase-url your Supabase project URL (Project Settings > API) // --token a text file holding your own sign-in token (see README) // --code your app's source folder, scanned on this computer only // --i-own confirm ownership up front (skips the prompt) // --json print the result as JSON // --no-color plain text (also honours the NO_COLOR environment variable) // // Only run this against apps you own or have written permission to test. import { readFile, writeFile, mkdir, readdir, stat } from "node:fs/promises"; import { homedir } from "node:os"; import { join, relative, extname, basename } from "node:path"; import { createInterface } from "node:readline/promises"; const VERSION = "1.1.1"; const MORE_URL = "https://publicbydefault.dev/kit"; const NEWS_DATE = "6 Dec 2026"; const UA = `closed-by-default/${VERSION} (own-app check)`; const MAX_REQUESTS = 60; const MAX_SCRIPTS = 57; const MAX_BODY = 5 * 1024 * 1024; // ---------- args ---------- const argv = process.argv.slice(2); const flag = (n) => argv.includes(n); const opt = (n) => { const i = argv.indexOf(n); return i === -1 ? undefined : argv[i + 1]; }; if (flag("--help") || flag("-h") || argv.length === 0) { console.log(readHelp()); process.exit(argv.length === 0 ? 3 : 0); } const args = { url: opt("--url"), supabaseUrl: opt("--supabase-url"), token: opt("--token"), code: opt("--code"), iOwn: opt("--i-own"), json: flag("--json"), noColor: flag("--no-color"), }; if (!args.url && !args.supabaseUrl && !args.token && !args.code) { fail(3, "Give --url, --supabase-url, --token or --code. Run with --help for examples."); } // ---------- output helpers ---------- // Colour uses the terminal's own ANSI codes: no packages. It switches off for --no-color, // NO_COLOR, --json, or when the output is piped to a file. const useColor = !args.json && !args.noColor && !("NO_COLOR" in process.env) && (("FORCE_COLOR" in process.env) || (process.stdout.isTTY && process.stdout.hasColors?.())); const paint = (open, close) => (t) => (useColor ? `\x1b[${open}m${t}\x1b[${close}m` : String(t)); const c = { bold: paint(1, 22), dim: paint(2, 22), cyan: paint(36, 39), underline: paint(4, 24), badge: { WATCH: paint("1;30;43", "0"), OK: paint("1;30;42", "0"), HOLE: paint("1;97;41", "0"), CANT_TELL: paint("1;30;47", "0") }, text: { WATCH: paint(33, 39), OK: paint(32, 39), HOLE: paint(31, 39), CANT_TELL: paint(37, 39) }, }; const WIDTH = Math.max(60, Math.min(process.stdout.columns || 80, 100)); function wrap(text, indent, first = indent) { const out = []; let line = first; for (const w of String(text).split(" ")) { if (line.trim() && (line + w).length > WIDTH) { out.push(line.trimEnd()); line = indent; } line += w + " "; } out.push(line.trimEnd()); return out; } const lines = []; const say = (s = "") => { if (!args.json) console.log(s); lines.push(s); }; const field = (name, value) => say(`${c.dim(name.padEnd(9))}${value}`); function fail(code, msg) { if (args?.json) console.log(JSON.stringify({ status: "ERROR", message: msg }, null, 2)); else console.error(msg); process.exit(code); } const mask = (v) => { const s = String(v); return s.length <= 12 ? "…" : `${s.slice(0, 6)}…${s.slice(-4)}`; }; // ---------- http: one target, one request a second ---------- const allowedHosts = new Set(); let requests = 0; let lastAt = 0; async function get(url, headers = {}) { const u = new URL(url); if (!allowedHosts.has(u.host)) fail(4, `Refused: ${u.host} isn't the app you confirmed.`); if (++requests > MAX_REQUESTS) fail(4, `Refused: request cap (${MAX_REQUESTS}) reached.`); const wait = lastAt + 1000 - Date.now(); if (wait > 0) await new Promise((r) => setTimeout(r, wait)); lastAt = Date.now(); let res; try { res = await fetch(u, { headers: { "User-Agent": UA, ...headers }, redirect: "manual", signal: AbortSignal.timeout(15000), }); } catch (e) { return { status: 0, error: e.cause?.code || e.name, text: "" }; } if (res.status >= 300 && res.status < 400 && res.headers.get("location")) { const next = new URL(res.headers.get("location"), u); if (next.host !== u.host) return { status: res.status, offHost: next.href, text: "" }; return get(next.href, headers); } const buf = await res.arrayBuffer(); const text = new TextDecoder().decode(buf.byteLength > MAX_BODY ? buf.slice(0, MAX_BODY) : buf); return { status: res.status, headers: res.headers, text }; } // ---------- ownership ---------- async function confirmOwnership(host) { const dir = join(homedir(), ".closed-by-default"); const file = join(dir, "targets.json"); let known = {}; try { known = JSON.parse(await readFile(file, "utf8")); } catch {} if (known[host]) return; if (args.iOwn && args.iOwn.toLowerCase() === host.toLowerCase()) { // confirmed on the command line } else { if (!process.stdin.isTTY) fail(4, `Refused: confirm ownership with --i-own ${host}`); const rl = createInterface({ input: process.stdin, output: process.stdout }); console.log(`\nOnly test apps you own or have written permission to test.`); const ans = await rl.question(`Type ${host} to confirm that's you: `); rl.close(); if (ans.trim().toLowerCase() !== host.toLowerCase()) fail(4, "Not confirmed. Nothing was sent."); } known[host] = new Date().toISOString().slice(0, 10); try { await mkdir(dir, { recursive: true }); await writeFile(file, JSON.stringify(known, null, 2)); } catch {} } // ---------- JWT helpers ---------- const b64json = (part) => { try { return JSON.parse(Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8")); } catch { return null; } }; const JWT_RE = /eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g; function decodeJwt(t) { const [h, p] = t.split("."); return { header: b64json(h), payload: b64json(p) }; } // ---------- step 1: find the Supabase project from the site ---------- const SUPA_RE = /https:\/\/([a-z0-9]{20})\.supabase\.co/g; async function crawl(siteUrl) { const site = new URL(siteUrl); allowedHosts.add(site.host); await confirmOwnership(site.host); const page = await get(site.href); if (page.status !== 200) return { error: page.error || `the page answered ${page.status}${page.offHost ? ` (redirects to ${page.offHost})` : ""}` }; const found = { projects: new Set(), legacyAnon: false, publishable: null, scripts: 0 }; const scan = (text) => { for (const m of text.matchAll(SUPA_RE)) found.projects.add(`https://${m[1]}.supabase.co`); for (const m of text.matchAll(JWT_RE)) { const { payload } = decodeJwt(m[0]); if (payload?.iss === "supabase" && payload?.role === "anon") found.legacyAnon = true; } const pk = text.match(/sb_publishable_[A-Za-z0-9_-]{10,}/); if (pk && !found.publishable) found.publishable = pk[0]; }; scan(page.text); const queue = []; const seen = new Set(); const add = (src, base) => { try { const u = new URL(src, base); if (u.host !== site.host || seen.has(u.href)) return; seen.add(u.href); queue.push(u.href); } catch {} }; for (const m of page.text.matchAll(/]+src=["']([^"']+)["']/gi)) add(m[1], site); while (queue.length && found.scripts < MAX_SCRIPTS && found.projects.size === 0) { const src = queue.shift(); const r = await get(src); found.scripts++; if (r.status !== 200) continue; scan(r.text); for (const m of r.text.matchAll(/["'`]((?:\.?\/)?(?:assets|_next\/static\/chunks)\/[A-Za-z0-9_./-]+\.js)["'`]/g)) add(m[1], src); } return found; } // ---------- step 2: read the project's signing keys ---------- function classify(k) { if (k.kty === "EC" && k.crv === "P-256") return "P-256"; if (k.kty === "EC") return `EC ${k.crv || "?"}`; if (k.kty === "RSA") return "RSA"; if (k.kty === "OKP") return k.crv || "OKP"; return k.kty || "unknown"; } async function readKeys(projectUrl, publishable) { const u = new URL(projectUrl); allowedHosts.add(u.host); const jwksUrl = new URL("/auth/v1/.well-known/jwks.json", u).href; let r = await get(jwksUrl); if ((r.status === 401 || r.status === 403) && publishable) r = await get(jwksUrl, { apikey: publishable }); if (r.status !== 200) return { error: r.error || `Supabase answered ${r.status}` }; let body; try { body = JSON.parse(r.text); } catch { return { error: "the key list wasn't valid JSON" }; } const keys = Array.isArray(body.keys) ? body.keys : []; return { keys: keys.map((k) => ({ kid: k.kid, alg: k.alg, type: classify(k) })) }; } // ---------- step 3 (optional): the member's own token ---------- async function readToken(file) { const raw = await readFile(file, "utf8").catch(() => null); if (raw === null) return { error: `can't read ${file}` }; const m = raw.match(JWT_RE); if (!m) return { error: `no sign-in token found in ${file}` }; const tok = m.find((t) => decodeJwt(t).payload?.role === "authenticated") || m[0]; const { header, payload } = decodeJwt(tok); if (!header) return { error: "the token header couldn't be read" }; return { alg: header.alg, kid: header.kid, iss: payload?.iss }; } // ---------- step 4 (optional): scan the member's own code ---------- const CODE_EXT = new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".py"]); const SKIP_DIRS = new Set(["node_modules", ".git", ".next", "dist", "build", ".vercel", ".svelte-kit", "coverage", "__pycache__", ".venv", "venv"]); const CODE_RULES = [ { id: "pasted-key", re: /-----BEGIN (?:EC |RSA )?PUBLIC KEY-----/, what: "A public key pasted into code. Verify against your project's JWKS URL instead, so key rotations don't break you." }, { id: "jwt-secret", re: /\b(?:SUPABASE_JWT_SECRET|JWT_SECRET)\b/, what: "Uses the old shared JWT secret. Supabase advises verifying with getClaims() or the JWKS URL, and not moving back to the shared secret." }, { id: "hs256-allowed", re: /algorithms?\s*[:=]\s*\[[^\]]*["'](?:HS256|none)["']/i, what: "Allows HS256 or 'none'. Allow only the algorithm your project uses." }, { id: "verify-no-alg", re: /\b(?:jwt\.verify|jwtVerify|jwt\.decode)\s*\(/, what: "Verifies or decodes a JWT here. Check it passes an explicit algorithms list and uses the JWKS URL, or switch to supabase.auth.getClaims()." }, ]; const ENV_RULES = [ { id: "jwt-secret-env", re: /^\s*(?:SUPABASE_JWT_SECRET|JWT_SECRET)\s*=\s*(.+)$/m, what: "The old shared JWT secret is in an env file. Anything holding it can mint tokens for your project." }, ]; async function scanCode(root) { const hits = []; let files = 0; async function walk(dir, depth) { if (depth > 12 || files > 5000) return; let entries; try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; } for (const e of entries) { const p = join(dir, e.name); if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) await walk(p, depth + 1); continue; } if (!e.isFile()) continue; const isEnv = basename(p).startsWith(".env") && !basename(p).endsWith(".example"); if (!isEnv && !CODE_EXT.has(extname(p))) continue; const st = await stat(p).catch(() => null); if (!st || st.size > 1024 * 1024) continue; files++; const text = await readFile(p, "utf8").catch(() => ""); const rules = isEnv ? ENV_RULES : CODE_RULES; const textLines = text.split(/\r?\n/); for (const rule of rules) { textLines.forEach((ln, i) => { if (!rule.re.test(ln)) return; if (rule.id === "verify-no-alg") { const joined = textLines.slice(i, i + 4).join(" "); const ctx = joined.slice(0, (joined.indexOf(";") + 1) || joined.length); if (/algorithms?\s*[:=]/.test(ctx) || /createRemoteJWKSet|jwks/i.test(ctx)) return; } let shown = ln.trim().slice(0, 120); if (rule.id === "jwt-secret-env") shown = shown.replace(/=\s*(.+)$/, (_, v) => `= ${mask(v.trim())}`); else { // Never print a value from code in full: mask quoted strings and bare // values assigned to a secret-looking name. shown = shown.replace(/(["'`])([^"'`]{8,})\1/g, (_, q, v) => `${q}${mask(v)}${q}`); shown = shown.replace(/\b((?:SUPABASE_)?JWT_SECRET\s*[:=]\s*)([^\s"'`;,)]{8,})/g, (_, k, v) => `${k}${mask(v)}`); } hits.push({ rule: rule.id, file: relative(root, p), line: i + 1, code: shown, what: rule.what }); }); } } } await walk(root, 0); return { files, hits }; } // ---------- run ---------- const result = { check: "signing-key", version: VERSION, status: "CANT_TELL", project: null, keys: [], token: null, code: null, notes: [] }; say(`${c.bold("Closed by Default")} ${c.dim("·")} Which key signs your sign-in tokens ${c.dim(`(v${VERSION})`)}`); let projectUrl = args.supabaseUrl; let publishable = null; let legacyAnon = false; if (args.url && !projectUrl) { field("Site", args.url); const found = await crawl(args.url); if (found.error) { result.notes.push(`Couldn't load the site: ${found.error}.`); } else { legacyAnon = found.legacyAnon; publishable = found.publishable; if (found.projects.size === 1) projectUrl = [...found.projects][0]; else if (found.projects.size > 1) result.notes.push(`Found ${found.projects.size} Supabase projects in the site's code: ${[...found.projects].join(", ")}. Rerun with --supabase-url for the one you mean.`); else result.notes.push(`Scanned ${found.scripts} script files and found no *.supabase.co URL. If you use a custom domain, rerun with --supabase-url.`); } } if (projectUrl) { let pu; try { pu = new URL(projectUrl); } catch { fail(3, `Not a URL: ${projectUrl}`); } result.project = pu.origin; field("Project", pu.origin); // A project URL typed with --supabase-url always needs its own confirmation, // even when --url is given too. One found by crawling your confirmed site doesn't. if (args.supabaseUrl) await confirmOwnership(pu.host); const k = await readKeys(pu.origin, publishable); if (k.error) result.notes.push(`Couldn't read the project's signing keys: ${k.error}.`); else result.keys = k.keys; result.keysRead = !k.error; } if (args.token) { const t = await readToken(args.token); if (t.error) result.notes.push(`Token: ${t.error}.`); else result.token = t; } if (args.code) { const c = await scanCode(args.code); result.code = c; } // ---------- decide ---------- const types = [...new Set(result.keys.map((k) => k.type))]; const tokenAlg = result.token?.alg; let headline; let doThis = false; if (tokenAlg === "HS256" || (result.keysRead && types.length === 0)) { result.status = "WATCH"; headline = (tokenAlg === "HS256" ? "Your project still signs sign-in tokens with the old shared secret (HS256)." : "Your project publishes no signing keys, which usually means it still signs sign-in tokens with the old shared secret (HS256). Rerun with --token to be sure.") + " That isn't P-256, so the curve in the news doesn't apply. But Supabase calls moving to signing keys \"the one prerequisite\" for any later post-quantum step, and anything holding that secret can mint tokens for your project."; doThis = true; result.notes.push("Next: in the Supabase dashboard, JWT Keys > Migrate JWT secret, then rotate when your code no longer verifies with the old secret. Practice on a staging project first."); } else if (tokenAlg === "ES256" || (types.length === 1 && types[0] === "P-256")) { result.status = "WATCH"; headline = "Your sign-in tokens are signed with P-256 (ES256), the curve in this month's news. Nothing is broken today: no attack on P-256 has been published. Don't switch back to the old shared secret, and don't rush a key rotation, because no post-quantum signing option exists yet."; doThis = true; } else if (tokenAlg === "RS256" || (types.length === 1 && types[0] === "RSA")) { result.status = "OK"; headline = "Your sign-in tokens are signed with RSA (RS256), not the curve in the news. Supabase's RSA keys are 2048-bit, which NIST plans to phase out after 2030, so the steps below are still worth doing, without any rush."; doThis = true; } else if (tokenAlg === "EdDSA" || (types.length === 1 && types[0] === "Ed25519")) { result.status = "WATCH"; headline = "Your sign-in tokens are signed with Ed25519, not P-256. Nothing official names Ed25519, but some cryptographers think every 256-bit curve, Ed25519 included, may be weaker than thought. Nothing is broken today, and the steps below still apply."; doThis = true; } else if (types.length > 1) { result.status = "WATCH"; headline = `Your project publishes more than one kind of signing key (${types.join(", ")}), so a rotation is set up or in progress. Rerun with --token to see which one signs your users' tokens today.`; } else if (types.length === 1) { result.status = "OK"; headline = `Your sign-in tokens are signed with ${types[0]}, not P-256.`; } else { result.status = "CANT_TELL"; headline = "Couldn't tell which key signs your project's tokens."; } if (legacyAnon && result.status !== "CANT_TELL") { result.notes.push("Your site's code still ships the legacy anon key (a long eyJ… token). Supabase recommends moving to the new publishable key; that's separate from P-256 and not urgent."); } // ---------- print ---------- say(""); if (result.keys.length) { field("Keys", `${result.keys.map((k) => `${k.type}${k.alg ? ` (${k.alg})` : ""}${k.kid ? ` kid ${mask(k.kid)}` : ""}`).join("; ")}`); } if (result.token) field("Token", `signed with ${result.token.alg}${result.token.kid ? `, kid ${mask(result.token.kid)}` : ""}`); say(""); const label = result.status === "CANT_TELL" ? "CAN'T TELL" : result.status; const badge = c.badge[result.status] || c.bold; const tint = c.text[result.status] || ((t) => t); const rule = tint("─".repeat(WIDTH)); say(rule); const [head, ...rest] = wrap(headline, " "); say(useColor ? badge(` ${label} `) : `[ ${label} ]`); say(c.bold(head)); for (const l of rest) say(c.bold(l)); for (const n of result.notes) for (const l of wrap(n, " ")) say(l); say(rule); if (doThis) { say(""); say(c.bold("Do these three things this week:")); say(` ${c.cyan("1.")} Make sure your server code checks sign-in tokens with supabase.auth.getClaims() or against`); say(" your project's JWKS URL, not a key or secret pasted into an environment variable."); say(` ${c.cyan("2.")} Make sure it accepts only the algorithm your project uses (for example algorithms: ['ES256']).`); say(` ${c.cyan("3.")} Practice a key rotation on a staging project, so a real one later is routine.`); if (!args.code) say(c.dim(" Rerun with --code ./your-app-folder to check 1 and 2 on your own code (it stays on this computer).")); } if (result.code) { say(""); field("Code", `scanned ${result.code.files} files in ${args.code}`); if (!result.code.hits.length) say(" Nothing matched. Still read your token-checking code once by eye."); for (const h of result.code.hits.slice(0, 40)) { say(` ${c.cyan(`${h.file}:${h.line}`)} ${h.code}`); say(` ${h.what}`); } if (result.code.hits.length > 40) say(` …and ${result.code.hits.length - 40} more.`); } say(""); say(c.dim(`Sent ${requests} request${requests === 1 ? "" : "s"}, one per second. Nothing was changed and nothing was uploaded.`)); for (const l of wrap("This check reports which algorithm signs your project's tokens and, with --code, how your code checks them. It doesn't test whether tokens can be forged, and it says nothing about other holes.", " ", "Scope ")) say(c.dim(l)); say(c.dim(`News Based on what was public on ${NEWS_DATE}. More checks like this: `) + c.cyan(c.underline(MORE_URL))); if (args.json) console.log(JSON.stringify(result, null, 2)); process.exit(result.status === "CANT_TELL" ? 2 : 0); function readHelp() { return `Closed by Default: which key signs your Supabase sign-in tokens (v${VERSION}) node check-signing-key.mjs --url https://your-app.example node check-signing-key.mjs --supabase-url https://abcd1234.supabase.co node check-signing-key.mjs --url https://your-app.example --code ./my-app-folder --url your live app (finds your Supabase project in its code) --supabase-url your Supabase project URL --token a file with your own sign-in token, to see which key signs it today --code scan your own source folder on this computer --i-own confirm ownership without the prompt --json JSON output --no-color plain text, no colours Results: WATCH (P-256 or the old shared secret: nothing broken, steps to take), OK (another algorithm), CAN'T TELL (couldn't reach or read the keys). Only run this against apps you own or have written permission to test.`; }