#!/usr/bin/env node /** * Env gate: the validated schema, .env.example, and the deploy config all list * the same variables. * * Why this needs a gate. A missing environment variable in production is one of * the most common ways a deploy breaks, and it is entirely preventable. The * usual sequence: someone adds process.env.STRIPE_WEBHOOK_SECRET, it works * locally because their own .env.local has it, and it fails in production * because nothing told anyone to set it there. Nothing in the type system knows * that .env.example and the Vercel project settings exist. * * This assumes you validate env at boot with Zod, which you should do anyway: * * // src/env.ts * export const env = z.object({ * DATABASE_URL: z.string().url(), * STRIPE_SECRET_KEY: z.string().startsWith('sk_'), * NEXT_PUBLIC_APP_URL: z.string().url(), * }).parse(process.env) * * Four checks, plus one family: * 1. IN-SCHEMA-NOT-EXAMPLE a new clone cannot boot and nobody told them why. * 2. IN-EXAMPLE-NOT-SCHEMA either dead, or being read unvalidated somewhere. * 3. UNVALIDATED-READ process.env.X in source, with no X in the schema. * 4. NOT-IN-DEPLOY-LIST the variable is not set where it has to run. * 5. Client secrets: a server key that reaches the browser. Four codes, * SECRET-IN-CLIENT-VAR (a NEXT_PUBLIC_ or VITE_ name that says secret), * SECRET-IN-CLIENT-CODE (a secret read in a "use client" file), * SECRET-IN-BUNDLE-CONFIG (a secret in next.config env or vite.config * define) and SECRET-LITERAL-IN-CLIENT (a key written into client code). * These run first, with or without a schema, because an app that never * wrote one (most Lovable, Bolt and v0 output) is the app most likely to * ship a service-role key to every visitor. They fail without --check: a * leaked key is not a nag. * * Check 4 is optional and off unless deployListFile is set, because it needs a * file only someone with deploy access can produce. See the "gate or nag" * question in chapter 2: if the person committing cannot satisfy it, it does not * belong in the commit path. * * WHAT --check FAILS ON: all of it. Checks 2 and 3 used to print and exit 0, * which meant the gate this repo advertises passed on the exact defect it * exists to find: a NEW_SECRET read straight out of process.env, named in the * output, exit code 0. There is no half-finding here. Either something is worth * saying and a committer can fix it offline from a fresh clone, in which case it * gates, or it should not be printed. Anything genuinely unfixable at commit * time belongs in the session-start nag instead, which is where check 4 lives * whenever deployListFile is set. * * WHAT IT DOES NOT PROVE. * That a secret is not reachable some other way: a server route that returns * it, a log, a source map. It reads names and literals, not data flow. * That gitleaks would pass. check-secrets does that. * Client files are "use client" files and CONFIG.clientDirs; a Vite app's * src is not treated as client until you list it. * That the schema is right, only that it, the example file and the code agree. * * EXIT CODES. 0 clean, 1 findings, 2 cannot check (a CONFIG.clientSafe entry * with no reason or no date). * * Usage: * node scripts/check-env.mjs * node scripts/check-env.mjs --check * node scripts/check-env.mjs --check src/a.ts schema findings only for these files; client secrets stay whole-repo * node scripts/check-env.mjs --print-config what the hook needs to wire it */ import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs' // ---------------------------------------------------------------- CONFIG --- const CONFIG = { schemaFile: 'src/env.ts', exampleFile: '.env.example', // Where source is scanned for direct process.env reads. This is also what the // pre-commit hook triggers on, via --print-config: a repo that keeps its code // somewhere other than src/ would otherwise be scanned by a gate that never // runs. sourceDirs: ['src'], // Optional. A plain text file, one variable name per line, listing what the // hosting platform has set. Produce it with `vercel env ls` or equivalent and // commit it. Leave null to skip check 3. deployListFile: null, // Variables that are legitimately absent from .env.example: injected by the // platform, or optional with a working default. Each entry needs a reason. exempt: { NODE_ENV: 'set by the runtime', VERCEL_URL: 'injected by the platform', PORT: 'injected by the platform', NEXT_RUNTIME: 'set by Next itself', CI: 'set by the CI runner', }, // The files allowed to touch process.env directly. The schema file has to: // it is the thing doing the validating. Add a bootstrap or an instrumentation // file here if one genuinely needs raw access, with the reason in a comment. readsEnvDirectly: ['src/env.ts'], // Prefixes a bundler inlines into client code. clientPrefixes: ['NEXT_PUBLIC_', 'VITE_', 'EXPO_PUBLIC_', 'PUBLIC_', 'REACT_APP_', 'NUXT_PUBLIC_'], // Words that mark a variable as a secret. Matched on underscore-token // boundaries, (^|_)WORD(_|$), on the name after the client prefix: // NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY matches SERVICE_ROLE, // VITE_SECRETARY_EMAIL does not match SECRET. secretWords: ['SERVICE_ROLE', 'SECRET', 'PRIVATE_KEY', 'PASSWORD', 'DATABASE_URL', 'DB_URL', 'SERVICE_KEY', 'ADMIN_KEY'], // Directories whose every file ships to the browser (a Vite app's src). // Files starting with 'use client' count wherever they are. clientDirs: [], // Bundler configs whose env block (next.config) or define block // (vite.config) is inlined into the client. define: { 'process.env': // process.env } is the common Vite leak, and is a finding on its own. bundleConfigFiles: ['next.config.js', 'next.config.mjs', 'next.config.ts', 'vite.config.js', 'vite.config.ts', 'vite.config.mjs'], // Names that look secret and are not. Reason and until (YYYY-MM-DD) are // required; past the date the finding is live again. // NEXT_PUBLIC_PASSWORD_MIN_LENGTH: { reason: 'a number, not a password', until: '2027-01-01' } clientSafe: {}, } // The schema file always may, wherever it was moved to. Leaving this to the // list above meant that pointing CONFIG.schemaFile at src/config/env.ts turned // the schema itself into an offender, and a gate that fails on its own // correctly-written schema is a gate that gets removed. if (!CONFIG.readsEnvDirectly.includes(CONFIG.schemaFile)) { CONFIG.readsEnvDirectly.push(CONFIG.schemaFile) } // ----------------------------------------------------------------- PARSE --- /** * Pull variable names out of the Zod schema. Deliberately a regex over the * source rather than an import: importing env.ts runs .parse(process.env), * which throws in CI where the variables are not set, so the gate would fail * for the wrong reason. Matching UPPER_SNAKE keys followed by z. is precise * enough in practice, and a false negative here is caught by check 2. */ function schemaVars(file) { const text = readFileSync(file, 'utf8') const found = new Set() // \s* between `z` and the dot, because a long chain is written // LOG_LEVEL: z // .enum([...]) // and a same-line match read those keys as undeclared, which flagged every // one of them as IN-EXAMPLE-NOT-SCHEMA. const re = /^\s*([A-Z][A-Z0-9_]*)\s*:\s*z\s*\./gm let m while ((m = re.exec(text))) found.add(m[1]) return found } /** * Variable names from a dotenv file. Blank lines and comments ignored, unless * `commented` is set: `# NAME=value` is how an example documents an optional * variable, so for "is it written down" it counts, and for "is it a live * entry" it does not. */ function dotenvVars(file, { commented = false } = {}) { const text = readFileSync(file, 'utf8') const found = new Set() for (const line of text.split('\n')) { let trimmed = line.trim() if (commented) trimmed = trimmed.replace(/^#+\s*/, '') if (!trimmed || trimmed.startsWith('#')) continue const m = trimmed.match(/^([A-Z][A-Z0-9_]*)\s*=/) if (m) found.add(m[1]) } return found } /** Variable names from a plain list, one per line. */ function listVars(file) { const text = readFileSync(file, 'utf8') return new Set( text .split('\n') .map((l) => l.trim()) .filter((l) => l && !l.startsWith('#')) ) } /** * Every process.env.X read directly in source, with the file it was read in. * * Two different defects live here and the file matters for telling them apart. * A variable read this way and absent from the schema is UNVALIDATED: it is * undefined at runtime rather than failing at boot with a clear message. A * variable read this way and present in the schema is a BYPASS: the validated * value exists and this line went around it, so the coercion, the default and * the startsWith('sk_') never ran. The second one was invisible before, because * checking membership alone made a declared variable look fine however it was * read. */ function directReads(dirs) { const found = new Map() // NAME -> Set(file) const walk = (dir) => { let entries try { entries = readdirSync(dir) } catch { return } for (const entry of entries) { if (['node_modules', '.next', '.git', 'dist'].includes(entry)) continue const full = `${dir}/${entry}` if (statSync(full).isDirectory()) walk(full) else if (/\.(ts|tsx|js|jsx|mjs)$/.test(entry)) { const text = readFileSync(full, 'utf8') const re = /process\.env\.([A-Z][A-Z0-9_]*)/g let m while ((m = re.exec(text))) { if (!found.has(m[1])) found.set(m[1], new Set()) found.get(m[1]).add(full) } } } } dirs.forEach(walk) return found } /** NAME, value and line for each assignment in a dotenv file. */ function dotenvEntries(file) { const out = [] readFileSync(file, 'utf8') .split('\n') .forEach((line, i) => { const m = line.trim().match(/^([A-Z][A-Z0-9_]*)\s*=\s*(.*)$/) if (m) out.push({ name: m[1], value: m[2].replace(/^['"]|['"]$/g, ''), line: i + 1 }) }) return out } // --------------------------------------------------------- CLIENT SECRETS --- const today = () => new Date().toISOString().slice(0, 10) const lineOf = (text, index) => text.slice(0, index).split('\n').length /** The client prefix a name starts with (the longest), or null. */ function clientPrefix(name) { return [...CONFIG.clientPrefixes].sort((a, b) => b.length - a.length).find((p) => name.startsWith(p)) ?? null } /** Whether a name carries a secret word, on token boundaries, after any client prefix. */ function hasSecretWord(name) { const prefix = clientPrefix(name) const rest = prefix ? name.slice(prefix.length) : name return CONFIG.secretWords.some((w) => new RegExp(`(^|_)${w}(_|$)`).test(rest)) } /** A clientSafe entry is live until its date passes. */ const isClientSafe = (name) => { const entry = CONFIG.clientSafe[name] return Boolean(entry) && today() <= entry.until } const DATE = /^\d{4}-\d{2}-\d{2}$/ function checkClientSafe() { for (const [name, entry] of Object.entries(CONFIG.clientSafe)) { if (!entry || typeof entry.reason !== 'string' || !entry.reason.trim() || !DATE.test(entry.until ?? '')) { console.error(`check-env: CONFIG.clientSafe.${name} needs a reason and an until date (YYYY-MM-DD).`) console.error(`fix: clientSafe: { ${name}: { reason: 'why this is not a secret', until: '2027-01-01' } }`) process.exit(2) } } } const SERVER_KEY_LITERAL = /^(sb_secret_|sk_live_|sk_test_|rk_live_)/ const SERVER_KEY_IN_CODE = /['"`](sb_secret_|sk_live_|sk_test_|rk_live_)[\w-]+/g const JWT = /eyJ[\w-]{10,}\.eyJ[\w-]{10,}\.[\w-]+/g /** A JWT whose payload says role service_role. Never returns the token. */ function isServiceRoleJwt(token) { try { const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8')) return payload?.role === 'service_role' } catch { return false } } /** Every source file in the dirs, with whether it ships to the browser. */ function clientScan(sourceDirs, clientDirs) { const files = new Map() // path -> { text, client } const walk = (dir, inClientDir) => { let entries try { entries = readdirSync(dir) } catch { return } for (const entry of entries) { if (['node_modules', '.next', '.git', 'dist'].includes(entry)) continue const full = `${dir}/${entry}` if (statSync(full).isDirectory()) walk(full, inClientDir) else if (/\.(ts|tsx|js|jsx|mjs)$/.test(entry)) { const text = readFileSync(full, 'utf8') const directive = /^\s*(?:\/\/[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*['"]use client['"]/.test(text) const prior = files.get(full) files.set(full, { text, client: inClientDir || directive || Boolean(prior?.client) }) } } } sourceDirs.forEach((d) => walk(d, false)) clientDirs.forEach((d) => walk(d, true)) return files } /** The body of the first `key: { ... }` block in text, balanced, or null. */ function blockOf(text, key) { const m = new RegExp(`\\b${key}\\s*:\\s*\\{`).exec(text) if (!m) return null let depth = 0 for (let i = m.index + m[0].length - 1; i < text.length; i++) { if (text[i] === '{') depth++ else if (text[i] === '}' && --depth === 0) return { body: text.slice(m.index, i + 1), index: m.index } } return { body: text.slice(m.index), index: m.index } } const ENV_READ = /(?:process\.env|import\.meta\.env)(?:\.|\[\s*['"])([A-Z][A-Z0-9_]*)/g function clientSecretErrors(schemaNames, exampleEntries) { const errors = [] const files = clientScan(CONFIG.sourceDirs, CONFIG.clientDirs) // SECRET-IN-CLIENT-VAR: where a client-prefixed secret name appears. const clientVars = new Map() // NAME -> Set(where) const note = (name, where) => { if (!clientPrefix(name) || !hasSecretWord(name) || isClientSafe(name)) return if (!clientVars.has(name)) clientVars.set(name, new Set()) clientVars.get(name).add(where) } for (const name of schemaNames) note(name, CONFIG.schemaFile) for (const { name } of exampleEntries) note(name, CONFIG.exampleFile) const inClientCode = new Map() // NAME -> Set(file) for (const [file, { text, client }] of files) { for (const m of text.matchAll(ENV_READ)) { const name = m[1] note(name, file) if (client && !clientPrefix(name) && hasSecretWord(name) && !isClientSafe(name)) { if (!inClientCode.has(name)) inClientCode.set(name, new Set()) inClientCode.get(name).add(file) } } } const list = (set) => [...set].slice(0, 3).join(', ') + (set.size > 3 ? `, +${set.size - 3} more` : '') for (const [name, where] of clientVars) { const prefix = clientPrefix(name) errors.push( `SECRET-IN-CLIENT-VAR ${name}\n` + ` ${list(where)}\n` + ` A ${prefix} variable is inlined into the browser bundle.\n` + ` fix: drop the prefix and read it only on the server. If it was ever deployed, rotate it.` ) } for (const [name, where] of inClientCode) { errors.push( `SECRET-IN-CLIENT-CODE ${name}\n` + ` ${list(where)}\n` + ` This file ships to the browser.\n` + ` fix: move the read to a server module or route, and pass the result down.` ) } // SECRET-IN-BUNDLE-CONFIG: what the bundler config inlines. for (const file of CONFIG.bundleConfigFiles) { if (!existsSync(file)) continue const text = readFileSync(file, 'utf8') const key = file.startsWith('next.config') ? 'env' : 'define' const block = blockOf(text, key) if (!block) continue const reasons = [] for (const name of new Set(block.body.match(/\b[A-Z][A-Z0-9_]{2,}\b/g) ?? [])) { if (hasSecretWord(name) && !isClientSafe(name)) reasons.push(name) } const all = /['"]process\.env['"]\s*:\s*process\.env\b(?!\s*\.)|\.\.\.\s*process\.env\b(?!\s*\.)/.test(block.body) if (all) reasons.push('all of process.env') for (const what of reasons) { errors.push( `SECRET-IN-BUNDLE-CONFIG ${what}\n` + ` ${file}:${lineOf(text, block.index)}\n` + ` ${file} ${key} values are inlined into the client.\n` + ` fix: read the secret on the server instead.` ) } } // SECRET-LITERAL-IN-CLIENT: a key written into client code, or into a // client-prefixed example value. The literal is never printed. const literal = (where) => errors.push( `SECRET-LITERAL-IN-CLIENT ${where}\n` + ` \n` + ` A server key is written into client code.\n` + ` fix: remove it and rotate it now.` ) for (const [file, { text, client }] of files) { if (!client) continue const seen = new Set() for (const m of text.matchAll(SERVER_KEY_IN_CODE)) seen.add(lineOf(text, m.index)) for (const m of text.matchAll(JWT)) if (isServiceRoleJwt(m[0])) seen.add(lineOf(text, m.index)) for (const line of [...seen].sort((a, b) => a - b)) literal(`${file}:${line}`) } for (const { name, value, line } of exampleEntries) { if (!clientPrefix(name)) continue if (SERVER_KEY_LITERAL.test(value) || (value.match(JWT) ?? []).some(isServiceRoleJwt)) { literal(`${CONFIG.exampleFile}:${line}`) } } return errors } /** Paths that are allowed to read process.env directly. */ const mayReadDirectly = (file) => CONFIG.readsEnvDirectly.some((allowed) => file === allowed || file.endsWith(`/${allowed}`)) // ------------------------------------------------------------------ MAIN --- function main() { const strict = process.argv.includes('--check') const errors = [] // The hook asks the checker where its files are instead of assuming the // defaults. Customising schemaFile is documented and supported, and a hook // that hardcodes src/ env.ts responds to that by silently skipping itself: // the check is installed, the commit passes, and nothing says why. if (process.argv.includes('--print-config')) { console.log(`schemaFile\t${CONFIG.schemaFile}`) console.log(`exampleFile\t${CONFIG.exampleFile}`) for (const dir of CONFIG.sourceDirs) console.log(`sourceDir\t${dir}`) for (const file of CONFIG.bundleConfigFiles) if (existsSync(file)) console.log(`watchFile\t${file}`) for (const dir of CONFIG.clientDirs) console.log(`clientDir\t${dir}`) process.exit(0) } checkClientSafe() // The client-secret checks run before the early exits below, so their // findings print when the schema or the example file is missing. They fail // whatever --check says. const hasSchema = existsSync(CONFIG.schemaFile) const hasExample = existsSync(CONFIG.exampleFile) const secretErrors = clientSecretErrors( hasSchema ? schemaVars(CONFIG.schemaFile) : new Set(), hasExample ? dotenvEntries(CONFIG.exampleFile) : [] ) if (!hasSchema) { // The schema half is opt-in: 39 of 48 repos in the field study had none. // Say once that it is off, so a pass is not read as "reads are checked". console.log(`note: no ${CONFIG.schemaFile}, so new process.env reads are not checked; add a schema to turn it on.`) if (!secretErrors.length) { console.log(`env: ok. No client secret found.`) process.exit(0) } console.log(`\nenv: ${secretErrors.length} error(s)\n`) for (const e of secretErrors) console.log(` ${e}\n`) process.exit(1) } if (!hasExample) { if (secretErrors.length) { console.log(`\nenv: ${secretErrors.length} error(s)\n`) for (const e of secretErrors) console.log(` ${e}\n`) } console.error(`No ${CONFIG.exampleFile}. Create it: it is the only instruction`) console.error(`a new clone gets about what it needs to boot.`) process.exit(1) } const inSchema = schemaVars(CONFIG.schemaFile) const inExample = dotenvVars(CONFIG.exampleFile) const documented = dotenvVars(CONFIG.exampleFile, { commented: true }) // Staged paths narrow the schema half to the files being committed. A repo // with an old schema and a hundred unmigrated reads would otherwise block // every commit that touched any source file (9 of 74 blocked edits in the // field study). What is left over is counted, not hidden. The client-secret // half above is not narrowed: it is as strict as it was. const staged = process.argv .slice(2) .filter((a) => !a.startsWith('--')) .map((p) => p.replace(/^\.\//, '')) const touches = (file) => staged.includes(file.replace(/^\.\//, '')) const owns = (...files) => !staged.length || files.filter(Boolean).some(touches) let outside = 0 const push = (list, owner, text) => { if (owner) list.push(text) else outside++ } // 1. In the schema, missing from the example. for (const name of inSchema) { if (!documented.has(name) && !CONFIG.exempt[name]) { push( errors, owns(CONFIG.schemaFile, CONFIG.exampleFile), `IN-SCHEMA-NOT-EXAMPLE ${name}\n` + ` A fresh clone will fail to boot with no hint about this.\n` + ` fix: add "${name}=" to ${CONFIG.exampleFile}, with a comment saying where to get it` ) } } // 2. In the example, missing from the schema. for (const name of inExample) { if (!inSchema.has(name) && !CONFIG.exempt[name]) { push( errors, owns(CONFIG.schemaFile, CONFIG.exampleFile), `IN-EXAMPLE-NOT-SCHEMA ${name}\n` + ` Either dead, or read somewhere without validation.\n` + ` fix: add it to ${CONFIG.schemaFile}, or delete it from ${CONFIG.exampleFile}` ) } } // 3. Read directly, instead of through the validated env object. const reads = directReads(CONFIG.sourceDirs) for (const [name, files] of reads) { if (CONFIG.exempt[name]) continue const all = [...files].filter((f) => !mayReadDirectly(f)) if (!all.length) continue // Only the staged files' reads are this commit's. If none are, the whole // finding is debt and goes to the count. const offenders = staged.length ? all.filter(touches) : all const owned = offenders.length > 0 const where = offenders.slice(0, 3).join(', ') + (offenders.length > 3 ? `, +${offenders.length - 3} more` : '') if (!inSchema.has(name)) { push( errors, owned, `UNVALIDATED-READ ${name}\n` + ` ${where}\n` + ` Read via process.env but not in the schema, so it is undefined at\n` + ` runtime instead of failing at boot with a clear message.\n` + ` fix: add it to ${CONFIG.schemaFile} and import env from there` ) } else { push( errors, owned, `DIRECT-READ ${name}\n` + ` ${where}\n` + ` It IS in the schema, and this line goes around it. The parse, the\n` + ` default and any coercion never run, so a validated variable is read\n` + ` here as a raw string or as undefined.\n` + ` fix: import { env } from '${CONFIG.schemaFile.replace(/\.[tj]sx?$/, '')}' and read env.${name}` ) } } errors.push(...secretErrors) // 4. Missing from the deploy platform. if (CONFIG.deployListFile && existsSync(CONFIG.deployListFile)) { const deployed = listVars(CONFIG.deployListFile) for (const name of inSchema) { if (!deployed.has(name) && !CONFIG.exempt[name]) { push( errors, owns(CONFIG.schemaFile, CONFIG.deployListFile), `NOT-IN-DEPLOY-LIST ${name}\n` + ` In the schema, so the app will not boot in production without it.\n` + ` fix: set it on the platform, then refresh ${CONFIG.deployListFile}` ) } } } // -------------------------------------------------------------- REPORT --- const debt = outside ? ` note: ${outside} more schema finding(s) outside the staged files, not blocking this commit. Run without paths to see them.\n` : '' if (!errors.length) { console.log( `env: ok. ${inSchema.size} variable(s); schema and example agree, and nothing` + ` reads process.env around the schema.` ) if (debt) console.log(debt) process.exit(0) } console.log(`\nenv: ${errors.length} error(s)\n`) for (const e of errors) console.log(` ${e}\n`) if (debt) console.log(debt) process.exit(strict || secretErrors.length ? 1 : 0) } main()