diff --git a/src/setup/doctor.ts b/src/setup/doctor.ts index 17e5152..9c8626d 100644 --- a/src/setup/doctor.ts +++ b/src/setup/doctor.ts @@ -12,7 +12,11 @@ import { packAsarBuffer } from "../shields/formats/asar.js"; import { protectErlangBeamBuffer } from "../shields/formats/erlang-beam.js"; import { protectEvmBytecodeBuffer } from "../shields/formats/evm-bytecode.js"; import { protectAndroidDexBuffer } from "../shields/formats/mobile-game.js"; -import { protectGgufBuffer, protectSafetensorsBuffer } from "../shields/formats/model.js"; +import { + buildSafetensorsBuffer, + protectGgufBuffer, + protectSafetensorsBuffer, +} from "../shields/formats/model.js"; import { protectNativeBinary } from "../shields/formats/native.js"; import { protectPythonSource } from "../shields/formats/python.js"; import { protectWasmBinary } from "../shields/formats/wasm.js"; @@ -93,11 +97,11 @@ export interface DoctorDiagnosticReport { readonly pythonPycMarshalShield: EngineHealthStatus; readonly nativeElfMachoPeShield: EngineHealthStatus; readonly zipApkArchiveShield: EngineHealthStatus; - readonly sqliteRuntime: EngineHealthStatus; readonly aiModelShield: EngineHealthStatus; readonly erlangBeamShield: EngineHealthStatus; readonly evmBytecodeShield: EngineHealthStatus; readonly androidDexR8Shield: EngineHealthStatus; + readonly sqliteRuntime: EngineHealthStatus; readonly astParser: EngineHealthStatus; readonly asarPacker: EngineHealthStatus; readonly wasmLeb128: EngineHealthStatus; @@ -262,6 +266,14 @@ export function probeLocalMcpHandshake( } } +const ENGINE_ALIAS_KEYS: ReadonlySet = new Set([ + "astParser", + "asarPacker", + "wasmLeb128", + "pythonMarshal", + "nativeBinary", +]); + function checkEngines(sqliteOverride?: boolean): DoctorDiagnosticReport["engines"] { let javascriptAstShield: EngineHealthStatus = "ready"; try { @@ -308,21 +320,75 @@ function checkEngines(sqliteOverride?: boolean): DoctorDiagnosticReport["engines const zipApkArchiveShield: EngineHealthStatus = typeof protectZipOrApkBuffer === "function" ? "ready" : "unavailable"; - const aiModelShield: EngineHealthStatus = - typeof protectSafetensorsBuffer === "function" && - typeof protectGgufBuffer === "function" - ? "ready" - : "unavailable"; - const erlangBeamShield: EngineHealthStatus = - typeof protectErlangBeamBuffer === "function" ? "ready" : "unavailable"; - const evmBytecodeShield: EngineHealthStatus = - typeof protectEvmBytecodeBuffer === "function" ? "ready" : "unavailable"; const androidDexR8Shield: EngineHealthStatus = typeof protectAndroidDexBuffer === "function" && typeof generateAndroidR8Counter === "function" ? "ready" : "unavailable"; + let aiModelShield: EngineHealthStatus = "ready"; + try { + const safetensors = buildSafetensorsBuffer( + { w: { dtype: "F32", shape: [2], data_offsets: [0, 8] } }, + Buffer.alloc(8, 0), + ); + const stRes = protectSafetensorsBuffer(safetensors, { + intensity: "stealth", + seed: "doctor-probe", + }); + const ggufRes = protectGgufBuffer(Buffer.alloc(0), { + intensity: "stealth", + seed: "doctor-probe", + }); + if (stRes.buffer.byteLength === 0 || ggufRes.buffer.byteLength === 0) { + aiModelShield = "unavailable"; + } + } catch { + aiModelShield = "unavailable"; + } + + let erlangBeamShield: EngineHealthStatus = "ready"; + try { + const u32 = (n: number): Buffer => { + const b = Buffer.alloc(4); + b.writeUInt32BE(n >>> 0); + return b; + }; + const chunk = (name: string, payload: Buffer): Buffer => + Buffer.concat([Buffer.from(name, "latin1"), u32(payload.length), payload]); + const atoms = ["bla_probe", "module_info"]; + const atomBody = Buffer.concat([ + u32(atoms.length), + ...atoms.map((a) => Buffer.concat([Buffer.from([a.length]), Buffer.from(a, "utf8")])), + ]); + const code = Buffer.concat([u32(16), u32(0), u32(169), u32(4), u32(2), Buffer.from("code")]); + const form = Buffer.concat([ + Buffer.from("BEAM", "latin1"), + chunk("AtU8", atomBody), + chunk("Code", code), + ]); + const beam = Buffer.concat([Buffer.from("FOR1", "latin1"), u32(form.length), form]); + const res = protectErlangBeamBuffer(beam, { intensity: "stealth", seed: "doctor-probe" }); + if (res.buffer.byteLength < beam.byteLength) { + erlangBeamShield = "unavailable"; + } + } catch { + erlangBeamShield = "unavailable"; + } + + let evmBytecodeShield: EngineHealthStatus = "ready"; + try { + const res = protectEvmBytecodeBuffer(Buffer.from([0x60, 0x00, 0x00]), { + intensity: "stealth", + seed: "doctor-probe", + }); + if (res.buffer.byteLength < 3) { + evmBytecodeShield = "unavailable"; + } + } catch { + evmBytecodeShield = "unavailable"; + } + let sqliteRuntime: EngineHealthStatus = "ready"; if (typeof sqliteOverride === "boolean") { sqliteRuntime = sqliteOverride ? "ready" : "unavailable"; @@ -344,11 +410,11 @@ function checkEngines(sqliteOverride?: boolean): DoctorDiagnosticReport["engines pythonPycMarshalShield, nativeElfMachoPeShield, zipApkArchiveShield, - sqliteRuntime, aiModelShield, erlangBeamShield, evmBytecodeShield, androidDexR8Shield, + sqliteRuntime, astParser: javascriptAstShield, asarPacker: electronAsarPacker, wasmLeb128: wasmBinaryShield, @@ -377,6 +443,7 @@ export function runDoctor(homeDirOrOptions?: string | DoctorOptions): DoctorDiag const globalIssues: string[] = []; for (const [engineName, status] of Object.entries(engines)) { + if (ENGINE_ALIAS_KEYS.has(engineName)) continue; if (status === "unavailable") { globalIssues.push(`Engine '${engineName}' is unavailable in current runtime (${process.version})`); } diff --git a/src/ui/reporter.ts b/src/ui/reporter.ts index 7be99f3..4e26988 100644 --- a/src/ui/reporter.ts +++ b/src/ui/reporter.ts @@ -5,7 +5,7 @@ import type { ProtectionResult, VerificationReport, } from "../core/types.js"; -import type { DoctorDiagnosticReport } from "../setup/doctor.js"; +import type { DoctorDiagnosticReport, EngineHealthStatus } from "../setup/doctor.js"; import type { SetupRunResult } from "../setup/setup.js"; import type { OneClickDefenseReport } from "../engine/defender.js"; @@ -205,19 +205,35 @@ export function formatBenchmarkReport(bench: BenchmarkReport): string { return lines.join("\n"); } +function formatReadiness(status: DoctorDiagnosticReport["status"]): string { + if (status === "pass") return `${ANSI.green}HEALTHY${ANSI.reset}`; + if (status === "warn") return `${ANSI.yellow}HEALTHY WITH WARNINGS${ANSI.reset}`; + return `${ANSI.red}UNHEALTHY${ANSI.reset}`; +} + +function formatEngineStatus(status: EngineHealthStatus): string { + if (status === "ready") return `${ANSI.green}${status}${ANSI.reset}`; + if (status === "degraded") return `${ANSI.yellow}${status}${ANSI.reset}`; + return `${ANSI.red}${status}${ANSI.reset}`; +} + export function formatDoctorReport(doc: DoctorDiagnosticReport): string { const lines: string[] = [ formatBanner(), "", - `${ANSI.bold}BLA Doctor Readiness:${ANSI.reset} ${ANSI.green}HEALTHY${ANSI.reset} (v${doc.blaVersion} on Node ${doc.nodeVersion}, ${doc.platform})`, + `${ANSI.bold}BLA Doctor Readiness:${ANSI.reset} ${formatReadiness(doc.status)} (v${doc.blaVersion} on Node ${doc.nodeVersion}, ${doc.platform})`, "", `${ANSI.bold}Protection Subsystems:${ANSI.reset}`, - ` • JavaScript/TypeScript AST & Semantic Budget Breaker: ${ANSI.green}${doc.engines.javascriptAstShield}${ANSI.reset}`, - ` • Electron .asar Unpacker & Integrity Repacker: ${ANSI.green}${doc.engines.electronAsarPacker}${ANSI.reset}`, - ` • WebAssembly (.wasm) Custom & Name Section Shield: ${ANSI.green}${doc.engines.wasmBinaryShield}${ANSI.reset}`, - ` • Python (.py / CPython .pyc) Marshal Tarpit Shield: ${ANSI.green}${doc.engines.pythonPycMarshalShield}${ANSI.reset}`, - ` • Native Binary (ELF / Mach-O / PE) Section Shield: ${ANSI.green}${doc.engines.nativeElfMachoPeShield}${ANSI.reset}`, - ` • Archive (ZIP / Android APK) Enclave Shield: ${ANSI.green}${doc.engines.zipApkArchiveShield}${ANSI.reset}`, + ` • JavaScript/TypeScript AST & Semantic Budget Breaker: ${formatEngineStatus(doc.engines.javascriptAstShield)}`, + ` • Electron .asar Unpacker & Integrity Repacker: ${formatEngineStatus(doc.engines.electronAsarPacker)}`, + ` • WebAssembly (.wasm) Custom & Name Section Shield: ${formatEngineStatus(doc.engines.wasmBinaryShield)}`, + ` • Python (.py / CPython .pyc) Marshal Tarpit Shield: ${formatEngineStatus(doc.engines.pythonPycMarshalShield)}`, + ` • Native Binary (ELF / Mach-O / PE) Section Shield: ${formatEngineStatus(doc.engines.nativeElfMachoPeShield)}`, + ` • Archive (ZIP / Android APK) Enclave Shield: ${formatEngineStatus(doc.engines.zipApkArchiveShield)}`, + ` • AI Model (Safetensors / GGUF) Nesting Breaker: ${formatEngineStatus(doc.engines.aiModelShield)}`, + ` • Erlang BEAM Chunk & Atom Exhaustion Shield: ${formatEngineStatus(doc.engines.erlangBeamShield)}`, + ` • EVM Bytecode Interface-Budget Shield: ${formatEngineStatus(doc.engines.evmBytecodeShield)}`, + ` • SQLite Honey-Table & Trap-Column Runtime: ${formatEngineStatus(doc.engines.sqliteRuntime)}`, "", `${ANSI.bold}Detected Coding Agent Integrations:${ANSI.reset}`, ]; @@ -229,6 +245,13 @@ export function formatDoctorReport(doc: DoctorDiagnosticReport): string { lines.push(` • ${c.displayName.padEnd(22)} (${c.id.padEnd(15)}) : ${det} | ${mcp} | ${skill}`); } + if (doc.issues.length > 0) { + lines.push("", `${ANSI.bold}Issues (${doc.issues.length}):${ANSI.reset}`); + for (const issue of doc.issues) { + lines.push(` • ${ANSI.red}${issue}${ANSI.reset}`); + } + } + return lines.join("\n"); } diff --git a/tests/doctor-engine-parity.test.ts b/tests/doctor-engine-parity.test.ts new file mode 100644 index 0000000..983e0b8 --- /dev/null +++ b/tests/doctor-engine-parity.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { runDoctor } from "../src/setup/doctor.js"; +import { formatDoctorReport } from "../src/ui/reporter.js"; + +describe("doctor reports every empirically-verified shield", () => { + const report = runDoctor({ homeDir: "/nonexistent-bla-home" }); + + it("probes the AI model, Erlang BEAM and EVM bytecode engines", () => { + expect(report.engines.aiModelShield).toBe("ready"); + expect(report.engines.erlangBeamShield).toBe("ready"); + expect(report.engines.evmBytecodeShield).toBe("ready"); + }); + + it("keeps every pure-TypeScript shield engine available", () => { + const unavailable = Object.entries(report.engines) + .filter(([name]) => name !== "sqliteRuntime") + .filter(([, status]) => status === "unavailable"); + expect(unavailable).toEqual([]); + }); + + it("surfaces the newly-probed subsystems in the CLI readiness report", () => { + const text = formatDoctorReport(report); + expect(text).toContain("AI Model (Safetensors / GGUF)"); + expect(text).toContain("Erlang BEAM"); + expect(text).toContain("EVM Bytecode"); + expect(text).toContain("SQLite"); + }); +}); diff --git a/tests/doctor-report-honest-status.test.ts b/tests/doctor-report-honest-status.test.ts new file mode 100644 index 0000000..c8aaa83 --- /dev/null +++ b/tests/doctor-report-honest-status.test.ts @@ -0,0 +1,68 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +const state = vi.hoisted(() => ({ failWasm: false })); + +vi.mock("../src/shields/formats/wasm.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + protectWasmBinary: (...args: Parameters) => { + if (state.failWasm) throw new Error("wasm probe failure"); + return actual.protectWasmBinary(...args); + }, + }; +}); + +import { runDoctor } from "../src/setup/doctor.js"; +import { formatDoctorReport } from "../src/ui/reporter.js"; + +const stripAnsi = (text: string): string => text.replace(/\x1b\[[0-9;]*m/g, ""); +const readinessLine = (text: string): string => + stripAnsi(text).split("\n").find((line) => line.includes("BLA Doctor Readiness")) ?? ""; + +describe("doctor text report reflects the real readiness verdict", () => { + afterEach(() => { + state.failWasm = false; + }); + + it("prints HEALTHY and no issues section when every check passes", () => { + const doc = runDoctor({ homeDir: "/nonexistent-bla-home", sqliteAvailableOverride: true }); + expect(doc.status).toBe("pass"); + const text = formatDoctorReport(doc); + expect(readinessLine(text)).toContain("HEALTHY"); + expect(readinessLine(text)).not.toContain("UNHEALTHY"); + expect(stripAnsi(text)).not.toContain("Issues ("); + }); + + it("prints UNHEALTHY and lists the issues when an engine is unavailable", () => { + const doc = runDoctor({ homeDir: "/nonexistent-bla-home", sqliteAvailableOverride: false }); + expect(doc.healthy).toBe(false); + const text = formatDoctorReport(doc); + expect(readinessLine(text)).toContain("UNHEALTHY"); + expect(stripAnsi(text)).toContain(`Issues (${doc.issues.length}):`); + for (const issue of doc.issues) { + expect(stripAnsi(text)).toContain(issue); + } + }); + + it("colors an unavailable engine red instead of green", () => { + const doc = runDoctor({ homeDir: "/nonexistent-bla-home", sqliteAvailableOverride: false }); + const sqliteLine = + formatDoctorReport(doc) + .split("\n") + .find((line) => line.includes("SQLite Honey-Table")) ?? ""; + expect(sqliteLine).toContain("\x1b[31munavailable"); + expect(sqliteLine).not.toContain("\x1b[32munavailable"); + }); + + it("reports an aliased engine failure once, under its primary name", () => { + state.failWasm = true; + const doc = runDoctor({ homeDir: "/nonexistent-bla-home", sqliteAvailableOverride: true }); + expect(doc.engines.wasmBinaryShield).toBe("unavailable"); + expect(doc.engines.wasmLeb128).toBe("unavailable"); + const engineIssues = doc.issues.filter((issue) => issue.startsWith("Engine '")); + expect(engineIssues).toHaveLength(1); + expect(engineIssues[0]).toContain("'wasmBinaryShield'"); + expect(doc.issues.some((issue) => issue.includes("'wasmLeb128'"))).toBe(false); + }); +});