/**
 * AUDIT-2 smoke — no module may keep a hardcoded fallback string for
 * NEXTAUTH_SECRET.
 *
 * Background (2026-05-23 audit):
 *   `src/lib/executive-auth.ts:3` contained
 *     const SECRET = process.env.NEXTAUTH_SECRET || "fallback-secret-DO-NOT-USE-IN-PROD";
 *   If env loading raced (Docker secret mount) or the var was missing,
 *   every executive cookie became forgeable from public source.
 *
 * Fix: replaced the `|| "literal"` form with a throwing IIFE that
 * fails loudly at module load. validateEnv (P0-8) is still the primary
 * gate; this is defense-in-depth.
 *
 * audit3-followup (2026-05-30): src/lib/executive-auth.ts was removed with
 * the executive_session JWT handoff (replaced by the executive_display token
 * system, which uses no NEXTAUTH_SECRET fallback). This smoke now guards the
 * remaining auth modules.
 *
 * This smoke asserts:
 *   1. src/proxy.ts has no `NEXTAUTH_SECRET || "<string>"` fallback.
 *   2. src/lib/auth.ts has no such fallback.
 */
import './_lib';
import { ok, fail } from './_lib';
import { readFileSync } from 'fs';
import path from 'path';

const ROOT = path.resolve(__dirname, '../..');
const MIDDLEWARE = path.join(ROOT, 'src/proxy.ts');
const AUTH = path.join(ROOT, 'src/lib/auth.ts');

function read(rel: string, abs: string): string {
    try {
        return readFileSync(abs, 'utf8');
    } catch (err) {
        fail(`read ${rel}`, String(err));
    }
}

function assertNotPresent(label: string, src: string, needle: string | RegExp): void {
    const re = typeof needle === 'string'
        ? new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
        : needle;
    if (re.test(src)) fail(label, `pattern still present: ${String(needle)}`);
    ok(label);
}

function main(): void {
    // Spot-check middleware and auth.ts — they read the var directly,
    // never via a fallback string. (executive-auth.ts was removed.)
    const mw = read('src/proxy.ts', MIDDLEWARE);
    assertNotPresent('audit-2: middleware has no fallback literal', mw, /process\.env\.NEXTAUTH_SECRET\s*\|\|\s*['"][^'"]+['"]/);

    const auth = read('src/lib/auth.ts', AUTH);
    assertNotPresent('audit-2: auth.ts has no fallback literal', auth, /process\.env\.NEXTAUTH_SECRET\s*\|\|\s*['"][^'"]+['"]/);

    ok('audit-2-fallback-secret', 'no hardcoded fallback for NEXTAUTH_SECRET');
}

main();
