ZZZ Digital Lab

Back to HushBrief

scripts/check-dist.mjs

// Release gate: a production bundle must not contain any App Check debug-token code path.
// Runs after every `vite build` (npm run build / build:live). Values are never printed.
import { readdir, readFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { root } from './configure.mjs';

// The Firebase SDK itself *reads* self.FIREBASE_APPCHECK_DEBUG_TOKEN; only an assignment
// from application code would switch a build into debug mode.
export const forbidden = [
  { name: 'debug-token assignment', test: text => /FIREBASE_APPCHECK_DEBUG_TOKEN\s*=(?!=)/.test(text) },
  { name: 'dev debug marker', test: text => text.includes('hushbrief:dev-appcheck-debug') },
  { name: 'debug token env name', test: text => text.includes('VITE_APPCHECK_DEBUG_TOKEN') },
  // Fail closed on UUID-shaped debug values without opening any private configuration.
  { name: 'possible debug-token UUID literal', test: text => /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i.test(text) },
];
async function files(dir) {
  const out = [];
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const full = join(dir, entry.name);
    if (entry.isDirectory()) out.push(...await files(full));
    else if (/\.(?:js|mjs|html|map|json)$/.test(entry.name)) out.push(full);
  }
  return out;
}
export async function checkDist(dist = resolve(root, 'dist')) {
  const problems = [];
  const list = await files(dist);
  if (!list.length) problems.push('dist: no build output found.');
  for (const file of list) {
    const text = await readFile(file, 'utf8');
    for (const rule of forbidden) if (rule.test(text)) problems.push(`${file.slice(dist.length + 1)}: ${rule.name}`);
  }
  return problems;
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  const problems = await checkDist(process.argv[2] ? resolve(process.argv[2]) : undefined);
  if (problems.length) { console.error('FAIL: production bundle contains an App Check debug path:'); for (const p of problems) console.error('  ' + p); process.exitCode = 1; }
  else console.log('PASS: production bundle has no App Check debug-token assignment, marker, env name or UUID literal (no private configuration read).');
}