scripts/configure.mjs
import { readFile, writeFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
export const fields = {
VITE_FIREBASE_API_KEY: { required: true, valid: v => /^AIza[\w-]{35}$/.test(v), format: 'Firebase Web API key format (39 characters)' },
VITE_FIREBASE_AUTH_DOMAIN: { required: true, valid: v => /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}$/i.test(v), format: 'hostname only; no scheme, port or path' },
VITE_FIREBASE_PROJECT_ID: { required: true, valid: v => /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(v), format: '6–30 lowercase letters, digits or hyphens; start with a letter' },
VITE_FIREBASE_APP_ID: { required: true, valid: v => /^1:\d+:web:[a-f0-9]+$/i.test(v), format: 'Firebase Web app ID: 1:<number>:web:<hex>' },
VITE_FIREBASE_STORAGE_BUCKET: { required: false, valid: v => /^[a-z0-9][a-z0-9._-]{1,220}[a-z0-9]$/i.test(v), format: 'bucket hostname only, e.g. <project>.firebasestorage.app' },
VITE_FIREBASE_MESSAGING_SENDER_ID: { required: false, valid: v => /^\d{6,20}$/.test(v), format: 'numeric messaging sender ID' },
// Required for release builds and whenever the local App Check debug provider is off.
VITE_RECAPTCHA_ENTERPRISE_SITE_KEY: { required: false, siteKey: true, valid: v => /^6[\w-]{20,100}$/.test(v), format: 'reCAPTCHA Enterprise public site key; no whitespace' },
VITE_CLOUD_MODEL: { required: false, valid: v => /^gemini-[a-z0-9][a-z0-9.-]{0,99}$/.test(v), format: 'Gemini model identifier' },
VITE_APPCHECK_DEBUG: { required: true, valid: v => /^(?:true|false)$/.test(v), format: 'literal true or false; false for release' },
};
export const root = resolve(import.meta.dirname, '..');
export const template = `# Fill privately. Never commit this file. Do not add server keys or debug tokens.
VITE_FIREBASE_API_KEY=REPLACE_WITH_FIREBASE_WEB_API_KEY
VITE_FIREBASE_AUTH_DOMAIN=REPLACE_WITH_AUTH_HOSTNAME
VITE_FIREBASE_PROJECT_ID=REPLACE_WITH_PROJECT_ID
VITE_FIREBASE_APP_ID=REPLACE_WITH_WEB_APP_ID
VITE_FIREBASE_STORAGE_BUCKET=REPLACE_WITH_STORAGE_BUCKET
VITE_FIREBASE_MESSAGING_SENDER_ID=REPLACE_WITH_SENDER_ID
VITE_RECAPTCHA_ENTERPRISE_SITE_KEY=REPLACE_WITH_ENTERPRISE_SITE_KEY
VITE_CLOUD_MODEL=gemini-3.5-flash-lite
VITE_APPCHECK_DEBUG=false
`;
// Development-only App Check debug settings live in the untracked .env.development.local.
// Vite loads that file for `vite` (development mode) only, never for `vite build`.
export const devFile = '.env.development.local';
export const devFields = {
VITE_APPCHECK_DEBUG: { valid: v => /^(?:true|false)$/.test(v), format: 'literal true or false' },
VITE_APPCHECK_DEBUG_TOKEN: { valid: v => /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), format: 'UUID v4 from npm run configure -- --debug-token' },
};
const placeholderValue = value => !value || /REPLACE_|YOUR_|<|>|\$\{|[\r\n]/i.test(value);
// Values never leave this function in an error or diagnostic. Unknown names are
// also suppressed: a mistyped line could itself contain a credential.
function parseEnv(text, allowed, unknownMessage) {
const values = Object.create(null);
const issues = [];
for (const [index, original] of text.replace(/^\uFEFF/, '').split(/\r?\n/).entries()) {
const line = original.trim();
if (!line || line.startsWith('#')) continue;
const match = /^(?:export\s+)?([A-Za-z_][\w]*)\s*=\s*(.*)$/.exec(line);
if (!match) { issues.push(`Line ${index + 1}: expected FIELD=value; contents suppressed.`); continue; }
const [, name] = match;
if (!Object.hasOwn(allowed, name)) { issues.push(`Line ${index + 1}: ${unknownMessage}`); continue; }
if (Object.hasOwn(values, name)) { issues.push(`${name}: duplicate field.`); continue; }
let value = match[2].trim();
if (/^["']/.test(value)) {
const quote = value[0];
const end = value.indexOf(quote, 1);
if (end < 0 || !/^(?:\s*#.*)?$/.test(value.slice(end + 1))) { issues.push(`${name}: invalid quoting.`); continue; }
value = value.slice(1, end);
} else value = value.replace(/\s+#.*$/, '').trim();
values[name] = value;
if (placeholderValue(value)) { if (!allowed[name].siteKey) issues.push(`${name}: missing or still a placeholder.`); }
else if (!allowed[name].valid(value)) issues.push(`${name}: invalid format; expected ${allowed[name].format}.`);
}
return { values, issues };
}
export function validateConfig(text, { release = false, devDebug = false } = {}) {
const { values, issues } = parseEnv(text, fields, 'unsupported field name; remove it. Server keys and App Check debug tokens are forbidden in .env.local.');
for (const [name, field] of Object.entries(fields)) if (field.required && !Object.hasOwn(values, name)) issues.push(`${name}: missing field.`);
const debug = !release && (devDebug || values.VITE_APPCHECK_DEBUG === 'true');
if (placeholderValue(values.VITE_RECAPTCHA_ENTERPRISE_SITE_KEY) && !debug) issues.push('VITE_RECAPTCHA_ENTERPRISE_SITE_KEY: missing; required for release builds and whenever the App Check debug provider is off.');
if (release && values.VITE_APPCHECK_DEBUG !== 'false') issues.push('VITE_APPCHECK_DEBUG: release requires false.');
return { ok: issues.length === 0, issues, fieldsPresent: Object.keys(values), debug };
}
// The development-only file may hold just the debug switch and the debug token.
export function validateDevConfig(text) {
const { values, issues } = parseEnv(text, devFields, `unsupported field name in ${devFile}; only VITE_APPCHECK_DEBUG and VITE_APPCHECK_DEBUG_TOKEN are allowed.`);
return { ok: issues.length === 0, issues, fieldsPresent: Object.keys(values), debug: values.VITE_APPCHECK_DEBUG === 'true', token: !placeholderValue(values.VITE_APPCHECK_DEBUG_TOKEN) };
}
export async function checkLocal(options = {}) {
let dev = { issues: [], debug: false, token: false };
if (!options.release) {
try { dev = validateDevConfig(await readFile(resolve(root, devFile), 'utf8')); }
catch (error) { if (error.code !== 'ENOENT') dev = { issues: ['unable to read privately; check file permissions.'], debug: false, token: false }; }
}
try {
const main = validateConfig(await readFile(resolve(root, '.env.local'), 'utf8'), { ...options, devDebug: dev.debug });
const issues = [...main.issues, ...dev.issues.map(issue => `${devFile}: ${issue}`)];
return { ...main, ok: issues.length === 0, issues, debugToken: dev.token };
}
catch (error) {
return { ok: false, issues: [error.code === 'ENOENT' ? '.env.local: missing. Owner: run npm run configure -- --init, fill it privately, then run npm run configure.' : '.env.local: unable to read privately; check file permissions.'], fieldsPresent: [], debug: false };
}
}
async function main() {
const args = new Set(process.argv.slice(2));
if (args.has('--help')) { console.log(`Owner-only configuration: npm run configure [-- --init|--debug-token|--release]. Reads .env.local locally, never prints values, makes no network calls. --init creates placeholders without overwriting an existing file. --debug-token creates the development-only ${devFile} with a fresh App Check debug token (value not printed; the SDK shows it in the DevTools console under npm run dev:live).`); return; }
if (args.has('--debug-token')) {
const body = `# Development only. Never commit or share. Vite never loads this file for production builds.\nVITE_APPCHECK_DEBUG=true\nVITE_APPCHECK_DEBUG_TOKEN=${randomUUID()}\n`;
try { await writeFile(resolve(root, devFile), body, { encoding: 'utf8', flag: 'wx' }); console.log(`Created private ${devFile} with a new App Check debug token (value not printed).`); }
catch (error) { console.error(error.code === 'EEXIST' ? `${devFile} already exists; left unchanged.` : `Could not create ${devFile}.`); process.exitCode = 1; }
return;
}
if (args.has('--init')) {
try { await writeFile(resolve(root, '.env.local'), template, { encoding: 'utf8', flag: 'wx' }); console.log('Created private .env.local with placeholders. Fill it yourself; never share the file.'); }
catch (error) { console.error(error.code === 'EEXIST' ? '.env.local already exists; left unchanged.' : 'Could not create .env.local.'); process.exitCode = 1; }
return;
}
const result = await checkLocal({ release: args.has('--release') });
console.log(result.ok ? 'PASS: field names and formats. Values suppressed; live services are not verified.' : 'Configuration needs attention (values suppressed):');
for (const issue of result.issues) console.log(`MISSING / FIX: ${issue}`);
if (!result.ok) process.exitCode = 1;
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) await main();