/**
 * vf-w4c-secret-boot-guard-proof.ts  (AS/PLATFORM/2026/007 — Wave W4c)
 *
 * Behavioral proof for server/lib/secret-boot-guard.ts — the boot-time secret
 * auditor (presence + minLen + FU-007 NAME-as-value bad-paste catch + accepted
 * fallback + FU-042 prodOnly filtering + FU-009 env-scoped bypass matrix).
 *
 * This module touches NO database. It is exercised by INJECTING a fully
 * synthetic env baseline (all required names set to a 40-char non-label fake
 * value) and then mutating ONE axis per leg, calling the REAL exported
 * `enforceSecretBootGuard()` each time. Paired POS/NEG (Rule 18).
 *
 * RULE 1 (CRITICAL): this harness NEVER prints any process.env value. It sets
 * its OWN fake values and asserts only on booleans / counts / names / the
 * guard's own reason strings (which, for the mutated vars, contain only the
 * fake/label/short values THIS harness injected — never a real secret). The
 * real secrets in this process's env are overwritten with fakes before the
 * module is imported, so the import-time self-exec audits fakes too.
 *
 * Run: cd /home/runner/workspace && timeout 60 npx tsx scripts/vf-w4c-secret-boot-guard-proof.ts
 */

const FAKE = "x".repeat(40); // >= 32 (HMAC floor) and >= 16 (salt floor); not any known label

const NON_PRODONLY = [
  "WAVE10_SIGNING_SECRET", "WAVE10_PDF_SECRET", "DEMO_PACK_SIGNING_SECRET", "SLSA_SIGNING_SECRET",
  "ONBOARD_SIGNING_SECRET", "CROSS_PILLAR_SIGNING_SECRET", "TENANT_EXPORT_SIGNING_SECRET",
  "TENANT_EXPORT_KEY", "EXAMINER_TOKEN_SALT", "PII_AES_MASTER_KEY", "PII_HMAC_MASTER_KEY",
];
const PRODONLY = [
  "AEGIS_ADMIN_PASSWORD", "AEGIS_CISO_PASSWORD", "AEGIS_AUDITOR_PASSWORD", "ENCRYPTION_KEY",
  "ENGINEER_OKOT_PASSWORD", "ENGINEER_OKELLO_PASSWORD", "MLCO_PASSWORD",
];
const ALL = [...NON_PRODONLY, ...PRODONLY];
const FLAGS = ["REQUIRE_PROD_SECRETS", "ALLOW_INSECURE_FALLBACKS", "SECRET_GUARD_DEV_MODE"];

function baseline(nodeEnv: "development" | "production") {
  process.env.NODE_ENV = nodeEnv;
  for (const n of ALL) process.env[n] = FAKE;
  for (const f of FLAGS) delete process.env[f];
}

// Set a clean dev baseline BEFORE importing the module (its top-level self-exec
// will then audit fakes and pass without throwing).
baseline("development");

type Leg = { id: string; label: string; pass: boolean; detail: string };
const legs: Leg[] = [];
const rec = (id: string, label: string, pass: boolean, detail: string) => {
  legs.push({ id, label, pass, detail });
  console.log(`  [${pass ? "PASS" : "FAIL"}] ${id} — ${label}\n         ${detail}`);
};

type GuardCall = { threw: boolean; err?: string; result?: any };

async function main() {
  const mod = await import("../server/lib/secret-boot-guard");
  const enforce = mod.enforceSecretBootGuard;

  const call = (): GuardCall => {
    try { return { threw: false, result: enforce() }; }
    catch (e) { return { threw: true, err: (e as Error).message }; }
  };

  console.log("=== W4c — secret-boot-guard proof (synthetic env injection; NO secret values printed) ===\n");

  // T1 POS — dev baseline clean: no throw, 0 fails, only the 11 non-prodOnly audited.
  baseline("development");
  let r = call();
  rec("T1", "dev clean baseline -> no throw, failCount=0, prodOnly filtered (audit=11)",
    !r.threw && r.result?.failCount === 0 && r.result?.audit?.length === NON_PRODONLY.length && r.result?.bypassed === false,
    `threw=${r.threw} fail=${r.result?.failCount} ok=${r.result?.okCount} auditLen=${r.result?.audit?.length} bypassed=${r.result?.bypassed}`);

  // T2 NEG — dev missing one secret (enforce default) -> throws naming it.
  baseline("development"); delete process.env.WAVE10_PDF_SECRET;
  r = call();
  rec("T2", "dev missing secret -> REFUSES (throws naming the secret)",
    r.threw && /WAVE10_PDF_SECRET/.test(r.err || ""), `threw=${r.threw} namesSecret=${/WAVE10_PDF_SECRET/.test(r.err || "")}`);

  // T3 too-short (paired vs T1 long): value below minLen -> throws "too short".
  baseline("development"); process.env.EXAMINER_TOKEN_SALT = "shortie7"; // 8 < 16
  r = call();
  rec("T3", "too-short value -> REFUSES ('too short'); paired POS is T1 (long passes)",
    r.threw && /too short/.test(r.err || "") && /EXAMINER_TOKEN_SALT/.test(r.err || ""),
    `threw=${r.threw} tooShort=${/too short/.test(r.err || "")}`);

  // T4 FU-007 NAME-as-value: salt set to its own 19-char label (length alone PASSES) -> still REFUSES.
  baseline("development"); process.env.EXAMINER_TOKEN_SALT = "EXAMINER_TOKEN_SALT"; // 19 chars >= 16
  r = call();
  const t4neg = r.threw && /FU-007|NAME label/.test(r.err || "");
  // Paired control: a 19-char NON-label value passes -> proves it's the label, not the length.
  baseline("development"); process.env.EXAMINER_TOKEN_SALT = "abcdefghijklmnopqrs"; // 19 chars, not a label
  const r4b = call();
  rec("T4", "FU-007 NAME-as-value (len-19 label) REFUSED; 19-char non-label PASSES (proves label-catch, not length)",
    t4neg && !r4b.threw && r4b.result?.failCount === 0, `labelRefused=${t4neg} nonLabelPassed=${!r4b.threw && r4b.result?.failCount === 0}`);

  // T5 fallback POS: DEMO_PACK unset but WAVE10 present -> DEMO_PACK ok via fallback.
  baseline("development"); delete process.env.DEMO_PACK_SIGNING_SECRET;
  r = call();
  const demoEntry = r.result?.audit?.find((a: any) => a.name === "DEMO_PACK_SIGNING_SECRET");
  rec("T5", "fallback POS: DEMO_PACK unset + WAVE10 present -> OK via fallback:WAVE10_SIGNING_SECRET",
    !r.threw && r.result?.failCount === 0 && demoEntry?.ok === true && demoEntry?.source === "fallback:WAVE10_SIGNING_SECRET",
    `threw=${r.threw} demoOk=${demoEntry?.ok} source=${demoEntry?.source}`);

  // T6 fallback NEG: both DEMO_PACK and WAVE10 unset. (a) enforce -> throws; (b) warn -> inspect failedNames.
  baseline("development"); delete process.env.DEMO_PACK_SIGNING_SECRET; delete process.env.WAVE10_SIGNING_SECRET;
  const r6a = call();
  baseline("development"); delete process.env.DEMO_PACK_SIGNING_SECRET; delete process.env.WAVE10_SIGNING_SECRET;
  process.env.SECRET_GUARD_DEV_MODE = "warn"; // dev opt-out so we can inspect the result
  const r6b = call();
  const demoFail = r6b.result?.audit?.find((a: any) => a.name === "DEMO_PACK_SIGNING_SECRET");
  rec("T6", "fallback NEG: both unset -> enforce throws; warn-mode shows DEMO_PACK failed (fallback also unset)",
    r6a.threw && /DEMO_PACK_SIGNING_SECRET/.test(r6a.err || "") &&
    !r6b.threw && (r6b.result?.failedNames || []).includes("DEMO_PACK_SIGNING_SECRET") && /fallback/.test(demoFail?.reason || ""),
    `enforceThrew=${r6a.threw} warnDemoFail=${(r6b.result?.failedNames || []).includes("DEMO_PACK_SIGNING_SECRET")} reasonHasFallback=${/fallback/.test(demoFail?.reason || "")}`);

  // T7 prodOnly filtering (paired dev-ignores / prod-requires).
  baseline("development"); delete process.env.AEGIS_ADMIN_PASSWORD; // prodOnly
  const r7a = call();
  const adminInDev = (r7a.result?.audit || []).some((a: any) => a.name === "AEGIS_ADMIN_PASSWORD");
  baseline("production"); delete process.env.AEGIS_ADMIN_PASSWORD; // prod requires it
  const r7b = call();
  rec("T7", "prodOnly: dev IGNORES AEGIS_ADMIN_PASSWORD (not audited, no throw); prod REQUIRES it (throws)",
    !r7a.threw && r7a.result?.failCount === 0 && !adminInDev && r7b.threw && /AEGIS_ADMIN_PASSWORD/.test(r7b.err || ""),
    `devThrew=${r7a.threw} adminAuditedInDev=${adminInDev} prodThrew=${r7b.threw}`);

  // T8 FU-009 env-scoped bypass matrix (missing one non-prodOnly secret each time).
  // T8a prod + ALLOW_INSECURE_FALLBACKS -> bypass (no throw, bypassed=true).
  baseline("production"); delete process.env.SLSA_SIGNING_SECRET; process.env.ALLOW_INSECURE_FALLBACKS = "true";
  const r8a = call();
  // T8b dev + ALLOW_INSECURE_FALLBACKS (prod flag, dev env) -> IGNORED -> throws.
  baseline("development"); delete process.env.SLSA_SIGNING_SECRET; process.env.ALLOW_INSECURE_FALLBACKS = "true";
  const r8b = call();
  // T8c dev + SECRET_GUARD_DEV_MODE=warn -> dev opt-out -> no throw, bypassed=false.
  baseline("development"); delete process.env.SLSA_SIGNING_SECRET; process.env.SECRET_GUARD_DEV_MODE = "warn";
  const r8c = call();
  // T8d prod + SECRET_GUARD_DEV_MODE=warn (dev flag, prod env) -> IGNORED -> throws.
  baseline("production"); delete process.env.SLSA_SIGNING_SECRET; process.env.SECRET_GUARD_DEV_MODE = "warn";
  const r8d = call();
  rec("T8", "FU-009 env-scoped bypass: prod ALLOW_INSECURE ok(bypassed); dev ALLOW_INSECURE ignored(throw); dev WARN ok; prod WARN ignored(throw)",
    !r8a.threw && r8a.result?.bypassed === true && r8b.threw && !r8c.threw && r8c.result?.bypassed === false && r8d.threw,
    `prodAllow=${!r8a.threw}/bypassed=${r8a.result?.bypassed} devAllowThrew=${r8b.threw} devWarn=${!r8c.threw}/bypassed=${r8c.result?.bypassed} prodWarnThrew=${r8d.threw}`);

  const ok = legs.every(l => l.pass);
  console.log(`\n${legs.filter(l => l.pass).length}/${legs.length} legs PASS — ${ok ? "ALL PASS" : "FAIL"}`);
  process.exit(ok ? 0 : 1);
}

main().catch((e) => { console.error("PROBE ERROR:", e); process.exit(1); });
