🛡️ BLA (Blind LLM Agents) — Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, and WebAssembly against AI reverse-engineering agents like REA. Poison -> Exhaust -> Hallucinate.
JavaScript adversarial-aiclaude-codecursorelectron-securityllm-securitymcpmcp-serverobfuscationreverse-engineeringwebassembly
feat(mcp): add read-only bla_discover, bla_harden dry_run, and confirm_overwrite boundary with write receipts
qybaihe9a90defa35b5
diff --git a/src/engine/protector.ts b/src/engine/protector.tsindex 4cd1d86..dd9a4e2 100644--- a/src/engine/protector.ts+++ b/src/engine/protector.ts@@ -122,6 +122,19 @@ function escapeHtmlInlineScriptBody(jsCode: string): string {return jsCode.replace(/<\/(script)/gi, "<\\/$1");}+/**+ * Where `protectTarget` will write for a given input/output/inPlace triple.+ * Pure path math (no filesystem access) so callers can plan or confirm writes.+ */+export function resolveProtectOutputPath(+ inputPath: string,+ outputPath?: string,+ inPlace = false,+): string {+ const absInput = resolve(inputPath);+ return resolve(outputPath ?? deriveDefaultOutputPath(absInput, inPlace));+}+function deriveDefaultOutputPath(inputPath: string, inPlace = false): string {if (inPlace) return inputPath;const ext = extname(inputPath);diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex b99ccef..c108333 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -3,10 +3,11 @@ import { initBlaConfig } from "../core/config.js";import { inspectReleaseExposure } from "../core/release-exposure.js";import type { ProtectionIntensity } from "../core/types.js";import { auditTarget } from "../engine/auditor.js";-import { protectTarget } from "../engine/protector.js";+import { protectTarget, resolveProtectOutputPath } from "../engine/protector.js";import { verifyTarget } from "../engine/verifier.js";import { defendTarget } from "../engine/defender.js";-import { hardenProject } from "../engine/harden.js";+import { existsSync } from "node:fs";+import { discoverHardenTargets, hardenProject } from "../engine/harden.js";import { runShowcaseBenchmark } from "../engine/benchmark.js";import {emitCompileTimeNativeHeader,@@ -145,6 +146,39 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([type: "string",description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc",},+ dry_run: {+ type: "boolean",+ description:+ "Preview only: return discovered targets, planned output paths, wouldOverwrite and truncation without writing a single byte. Default false.",+ },+ max_artifacts: {+ type: "number",+ description: "Optional cap on discovered artifacts (default 64); the report sets truncated=true when more exist.",+ },+ confirm_overwrite: {+ type: "boolean",+ description:+ "Explicit write-confirmation boundary. Required (true) when this call would overwrite an existing output file; without it the call is refused with a confirmation_required receipt listing the paths. Default false.",+ },+ },+ additionalProperties: false,+ },+ },+ {+ name: "bla_discover",+ description:+ "Read-only inventory of protectable artifacts under a project/build directory using the exact discovery bla_harden uses (format per file, truncated flag when the cap is hit). Writes nothing. Use it to scope work before bla_harden / bla_defend.",+ inputSchema: {+ type: "object",+ properties: {+ directory: {+ type: "string",+ description: "Project or build directory to inventory (default: current working directory)",+ },+ max_artifacts: {+ type: "number",+ description: "Optional cap on listed artifacts (default 64); truncated=true when more exist.",+ },},additionalProperties: false,},@@ -197,6 +231,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([type: "string",description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc",},+ confirm_overwrite: {+ type: "boolean",+ description:+ "Explicit write-confirmation boundary. Required (true) when this call would overwrite an existing output file; without it the call is refused with a confirmation_required receipt listing the paths. Default false.",+ },},required: ["input_path"],additionalProperties: false,@@ -262,6 +301,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([type: "boolean",description: "Opt-in risky LLM directive layers. Default false.",},+ confirm_overwrite: {+ type: "boolean",+ description:+ "Explicit write-confirmation boundary. Required (true) when this call would overwrite an existing output file; without it the call is refused with a confirmation_required receipt listing the paths. Default false.",+ },},required: ["input_path"],additionalProperties: false,@@ -490,6 +534,85 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null && !Array.isArray(value);}+/**+ * Write-confirmation boundary for destructive MCP calls. Returns the existing+ * paths a call would overwrite; the caller refuses unless confirm_overwrite.+ */+function existingPaths(paths: readonly string[]): string[] {+ return paths.filter((p) => existsSync(p));+}++function confirmationRequiredPayload(+ tool: string,+ wouldOverwrite: readonly string[],+): Record<string, unknown> {+ return {+ status: "confirmation_required",+ tool,+ wrote: [],+ wouldOverwrite,+ message: `${tool} would overwrite ${wouldOverwrite.length} existing file(s); nothing was written. Confirm with the user, then retry with confirm_overwrite: true (or choose a new output path).`,+ };+}++function writeReceipt(+ outputs: readonly string[],+ overwritten: readonly string[],+ confirmed: boolean,+): Record<string, unknown> {+ return { status: "written", wrote: outputs, overwrote: overwritten, confirmed };+}++function optionalCount(value: unknown): number | undefined {+ return typeof value === "number" && Number.isFinite(value) && value > 0+ ? Math.floor(value)+ : undefined;+}++function runDefend(handlers: McpEngineHandlers, args: Record<string, unknown>): unknown {+ return handlers.defendTarget({+ inputPath: args.input_path as string,+ ...(typeof args.output_path === "string"+ ? { outputPath: args.output_path }+ : {}),+ intensity:+ typeof args.intensity === "string"+ ? (args.intensity as ProtectionIntensity)+ : "bankrupt",+ emitManifest: Boolean(args.emit_manifest),+ llmDirectives: Boolean(args.llm_directives),+ weaveDecoys: Boolean(args.weave_decoys),+ selfSeal: Boolean(args.self_seal),+ ...(Array.isArray(args.wasm_preserve_exports)+ ? {+ wasmPreserveExports: (args.wasm_preserve_exports as unknown[])+ .filter((x): x is string => typeof x === "string" && x.length > 0),+ }+ : {}),+ ...(typeof args.seed === "string" ? { seed: args.seed } : {}),+ });+}++function runProtect(handlers: McpEngineHandlers, args: Record<string, unknown>): unknown {+ return handlers.protectTarget({+ inputPath: args.input_path as string,+ ...(typeof args.output_path === "string" ? { outputPath: args.output_path } : {}),+ ...(typeof args.intensity === "string"+ ? { intensity: args.intensity as ProtectionIntensity }+ : {}),+ ...(typeof args.seed === "string" ? { seed: args.seed } : {}),+ llmDirectives: Boolean(args.llm_directives),+ weaveDecoys: Boolean(args.weave_decoys),+ selfSeal: Boolean(args.self_seal),+ ...(Array.isArray(args.wasm_preserve_exports)+ ? {+ wasmPreserveExports: (args.wasm_preserve_exports as unknown[])+ .filter((x): x is string => typeof x === "string" && x.length > 0),+ }+ : {}),+ });+}+export function validateMcpToolCall(params: unknown,):@@ -869,70 +992,88 @@ export async function handleMcpRequest(const name = tool.name;let payload: unknown;- if (name === "bla_harden") {- payload = handlers.hardenProject({- directory:- typeof args.directory === "string" && args.directory.trim().length > 0- ? (args.directory as string)- : process.cwd(),- intensity:- typeof args.intensity === "string"- ? (args.intensity as ProtectionIntensity)- : "bankrupt",- emitManifest: Boolean(args.emit_manifest),- llmDirectives: Boolean(args.llm_directives),- weaveDecoys: Boolean(args.weave_decoys),- selfSeal: Boolean(args.self_seal),- ...(Array.isArray(args.wasm_preserve_exports)- ? {- wasmPreserveExports: (args.wasm_preserve_exports as unknown[])- .filter((x): x is string => typeof x === "string" && x.length > 0),- }- : {}),- ...(typeof args.seed === "string" ? { seed: args.seed } : {}),- });- } else if (name === "bla_defend") {- payload = handlers.defendTarget({- inputPath: args.input_path as string,- ...(typeof args.output_path === "string"- ? { outputPath: args.output_path }- : {}),- intensity:- typeof args.intensity === "string"- ? (args.intensity as ProtectionIntensity)- : "bankrupt",- emitManifest: Boolean(args.emit_manifest),- llmDirectives: Boolean(args.llm_directives),- weaveDecoys: Boolean(args.weave_decoys),- selfSeal: Boolean(args.self_seal),- ...(Array.isArray(args.wasm_preserve_exports)- ? {- wasmPreserveExports: (args.wasm_preserve_exports as unknown[])- .filter((x): x is string => typeof x === "string" && x.length > 0),- }- : {}),- ...(typeof args.seed === "string" ? { seed: args.seed } : {}),- });+ let refused = false;+ const confirmed = args.confirm_overwrite === true;+ if (name === "bla_discover") {+ payload = discoverHardenTargets(+ typeof args.directory === "string" && args.directory.trim().length > 0+ ? args.directory+ : process.cwd(),+ {+ ...(optionalCount(args.max_artifacts) !== undefined+ ? { maxArtifacts: optionalCount(args.max_artifacts)! }+ : {}),+ },+ );+ } else if (name === "bla_harden") {+ const hardenDir =+ typeof args.directory === "string" && args.directory.trim().length > 0+ ? (args.directory as string)+ : process.cwd();+ const maxArtifacts = optionalCount(args.max_artifacts);+ const dryRun = args.dry_run === true;+ let preOverwrite: readonly string[] = [];+ if (!dryRun && existsSync(hardenDir)) {+ // Zero-write preview with the real engine to find clobbered outputs.+ preOverwrite = hardenProject({+ directory: hardenDir,+ dryRun: true,+ ...(maxArtifacts !== undefined ? { maxArtifacts } : {}),+ }).wouldOverwrite;+ }+ if (!dryRun && preOverwrite.length > 0 && !confirmed) {+ refused = true;+ payload = confirmationRequiredPayload(name, preOverwrite);+ } else {+ payload = handlers.hardenProject({+ directory: hardenDir,+ dryRun,+ ...(maxArtifacts !== undefined ? { maxArtifacts } : {}),+ intensity:+ typeof args.intensity === "string"+ ? (args.intensity as ProtectionIntensity)+ : "bankrupt",+ emitManifest: Boolean(args.emit_manifest),+ llmDirectives: Boolean(args.llm_directives),+ weaveDecoys: Boolean(args.weave_decoys),+ selfSeal: Boolean(args.self_seal),+ ...(Array.isArray(args.wasm_preserve_exports)+ ? {+ wasmPreserveExports: (args.wasm_preserve_exports as unknown[])+ .filter((x): x is string => typeof x === "string" && x.length > 0),+ }+ : {}),+ ...(typeof args.seed === "string" ? { seed: args.seed } : {}),+ });+ }+ } else if (name === "bla_defend" || name === "bla_protect") {+ const out = resolveProtectOutputPath(+ args.input_path as string,+ typeof args.output_path === "string" ? args.output_path : undefined,+ );+ const planned =+ name === "bla_defend" && args.emit_manifest === true+ ? [out, `${out}.bla-manifest.json`]+ : [out];+ const clobbered = existingPaths(planned);+ if (clobbered.length > 0 && !confirmed) {+ refused = true;+ payload = confirmationRequiredPayload(name, clobbered);+ } else {+ const report = (name === "bla_defend"+ ? runDefend(handlers, args)+ : runProtect(handlers, args)) as Record<string, unknown>;+ payload = {+ ...report,+ writeReceipt: writeReceipt(+ existingPaths(planned),+ clobbered,+ confirmed,+ ),+ };+ }} else if (name === "bla_audit") {payload = handlers.auditTarget(args.path as string);- } else if (name === "bla_protect") {- payload = handlers.protectTarget({- inputPath: args.input_path as string,- ...(typeof args.output_path === "string" ? { outputPath: args.output_path } : {}),- ...(typeof args.intensity === "string"- ? { intensity: args.intensity as ProtectionIntensity }- : {}),- ...(typeof args.seed === "string" ? { seed: args.seed } : {}),- llmDirectives: Boolean(args.llm_directives),- weaveDecoys: Boolean(args.weave_decoys),- selfSeal: Boolean(args.self_seal),- ...(Array.isArray(args.wasm_preserve_exports)- ? {- wasmPreserveExports: (args.wasm_preserve_exports as unknown[])- .filter((x): x is string => typeof x === "string" && x.length > 0),- }- : {}),- });} else if (name === "bla_verify") {payload = handlers.verifyTarget(args.target_path as string,@@ -979,7 +1120,8 @@ export async function handleMcpRequest(},],structuredContent: payload,- isError: false,+ // A refused write is a tool-level error the agent must act on.+ isError: refused,},};}diff --git a/tests/agent-write-safety.test.ts b/tests/agent-write-safety.test.tsnew file mode 100644index 0000000..c46267c--- /dev/null+++ b/tests/agent-write-safety.test.ts@@ -0,0 +1,175 @@+import { createHash } from "node:crypto";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join, relative } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { discoverHardenTargets, hardenProject } from "../src/engine/harden.js";+import { handleMcpRequest } from "../src/mcp/server.js";+import { runCli } from "../src/cli.js";++const tempDirs: string[] = [];+function tmp(): string {+ const d = mkdtempSync(join(tmpdir(), "bla-write-safety-"));+ tempDirs.push(d);+ return d;+}+afterEach(() => {+ for (const d of tempDirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++const JS = `export function unlockPremium(token) { return token === "LIVE-KEY"; }\n`;++function project(jsFiles = 2): string {+ const root = tmp();+ mkdirSync(join(root, "dist"), { recursive: true });+ for (let i = 0; i < jsFiles; i++) writeFileSync(join(root, "dist", `m${i}.js`), JS, "utf8");+ return root;+}++/** path → sha256 + mtime for every entry, so any write is visible. */+function snapshot(root: string): Record<string, string> {+ const out: Record<string, string> = {};+ const walk = (dir: string): void => {+ for (const e of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, e.name);+ const rel = relative(root, full);+ if (e.isDirectory()) {+ out[`${rel}/`] = "dir";+ walk(full);+ } else {+ out[rel] = `${createHash("sha256").update(readFileSync(full)).digest("hex")}@${statSync(full).mtimeMs}`;+ }+ }+ };+ walk(root);+ return out;+}++async function call(name: string, args: Record<string, unknown>) {+ const res = await handleMcpRequest({+ jsonrpc: "2.0",+ id: 1,+ method: "tools/call",+ params: { name, arguments: args },+ });+ expect(res?.error).toBeUndefined();+ return res!.result as { isError: boolean; structuredContent: Record<string, any> };+}++describe("read-only discover + zero-write dry-run", () => {+ it("bla_discover inventories targets without writing", async () => {+ const root = project(2);+ const before = snapshot(root);+ const r = await call("bla_discover", { directory: root });+ expect(r.isError).toBe(false);+ expect(r.structuredContent.artifacts.map((a: any) => a.relativePath).sort()).toEqual([+ "dist/m0.js",+ "dist/m1.js",+ ]);+ expect(r.structuredContent.truncated).toBe(false);+ expect(snapshot(root)).toEqual(before);+ });++ it("reports truncation explicitly instead of silently capping", () => {+ const root = project(5);+ const d = discoverHardenTargets(root, { maxArtifacts: 3 });+ expect(d.artifacts).toHaveLength(3);+ expect(d.truncated).toBe(true);+ expect(d.maxArtifacts).toBe(3);+ expect(discoverHardenTargets(root, { maxArtifacts: 5 }).truncated).toBe(false);+ const report = hardenProject({ directory: root, dryRun: true, maxArtifacts: 3 });+ expect(report.truncated).toBe(true);+ });++ it("bla_harden dry_run plans outputs and leaves the workspace byte-identical", async () => {+ const root = project(2);+ const before = snapshot(root);+ const r = await call("bla_harden", { directory: root, dry_run: true });+ expect(r.isError).toBe(false);+ const rep = r.structuredContent;+ expect(rep.dryRun).toBe(true);+ expect(rep.discoveredCount).toBe(2);+ expect(rep.artifacts[0].outputPath).toContain(".bla-hardened");+ expect(rep.wouldOverwrite).toEqual([]);+ expect(existsSync(join(root, ".bla-hardened"))).toBe(false);+ expect(snapshot(root)).toEqual(before);+ });++ it("CLI `harden --dry-run` writes nothing (no .bla-hardened, no .blarc)", async () => {+ const root = project(1);+ const before = snapshot(root);+ const code = await runCli(["harden", root, "--dry-run", "--json"]);+ expect(code).toBe(0);+ expect(snapshot(root)).toEqual(before);+ });+});++describe("overwrite confirmation boundary", () => {+ it("bla_harden refuses to clobber existing hardened outputs without confirm_overwrite", async () => {+ const root = project(1);+ const first = await call("bla_harden", { directory: root, seed: "s1" });+ expect(first.isError).toBe(false);+ expect(first.structuredContent.hardenedCount).toBe(1);+ const out = join(root, ".bla-hardened", "dist", "m0.js");+ const hardened = readFileSync(out, "utf8");++ const refused = await call("bla_harden", { directory: root, seed: "s2" });+ expect(refused.isError).toBe(true);+ expect(refused.structuredContent.status).toBe("confirmation_required");+ expect(refused.structuredContent.wouldOverwrite).toEqual([out]);+ expect(readFileSync(out, "utf8")).toBe(hardened);++ const ok = await call("bla_harden", { directory: root, seed: "s2", confirm_overwrite: true });+ expect(ok.isError).toBe(false);+ expect(ok.structuredContent.hardenedCount).toBe(1);+ expect(ok.structuredContent.wouldOverwrite).toEqual([out]);+ });++ it("bla_protect refuses an existing output_path without confirmation and succeeds with it", async () => {+ const root = project(1);+ const input = join(root, "dist", "m0.js");+ const output = join(root, "out.js");+ writeFileSync(output, "// precious\n", "utf8");++ const refused = await call("bla_protect", { input_path: input, output_path: output });+ expect(refused.isError).toBe(true);+ expect(refused.structuredContent.status).toBe("confirmation_required");+ expect(readFileSync(output, "utf8")).toBe("// precious\n");++ const ok = await call("bla_protect", {+ input_path: input,+ output_path: output,+ confirm_overwrite: true,+ });+ expect(ok.isError).toBe(false);+ expect(ok.structuredContent.writeReceipt).toMatchObject({+ status: "written",+ wrote: [output],+ overwrote: [output],+ confirmed: true,+ });+ expect(readFileSync(output, "utf8")).not.toBe("// precious\n");+ });++ it("bla_defend writes a fresh default output without confirmation and returns a receipt", async () => {+ const root = project(1);+ const input = join(root, "dist", "m0.js");+ const r = await call("bla_defend", { input_path: input, seed: "x" });+ expect(r.isError).toBe(false);+ const expected = join(root, "dist", "m0.shielded.js");+ expect(r.structuredContent.writeReceipt).toMatchObject({ wrote: [expected], overwrote: [] });++ const again = await call("bla_defend", { input_path: input, seed: "x" });+ expect(again.isError).toBe(true);+ expect(again.structuredContent.wouldOverwrite).toEqual([expected]);+ });+});diff --git a/tests/cli-mcp-setup.test.ts b/tests/cli-mcp-setup.test.tsindex 0aa1efb..6f0bea2 100644--- a/tests/cli-mcp-setup.test.ts+++ b/tests/cli-mcp-setup.test.ts@@ -78,6 +78,7 @@ describe("CLI Setup, Doctor, Benchmark & MCP Server", () => {const tools = (listRes?.result as { tools: Array<{ name: string }> }).tools;expect(tools.map((t) => t.name)).toEqual(["bla_harden",+ "bla_discover","bla_defend","bla_audit","bla_protect",