🛡️ 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(engine,cli,mcp): wire 22-format recursive directory shielding, 9 MCP tools, and 10-target benchmark
qybaihe6a2097b03690
diff --git a/src/cli.ts b/src/cli.tsindex e04d895..8bd4432 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -2,7 +2,9 @@import { writeFileSync } from "node:fs";import { resolve } from "node:path";import { BLA_IDENTITY } from "./identity.js";+import { initBlaConfig, loadBlaConfig } from "./core/config.js";import { inspectReleaseExposure } from "./core/release-exposure.js";+import { buildSarifReport } from "./core/sarif.js";import type { ProtectionIntensity } from "./core/types.js";import { auditTarget } from "./engine/auditor.js";import { protectTarget } from "./engine/protector.js";@@ -70,6 +72,7 @@ interface ParsedCliArgs {readonly command: string;readonly positionals: string[];readonly output?: string;+ readonly configPath?: string;readonly inPlace: boolean;readonly intensity: ProtectionIntensity;readonly seed?: string;@@ -79,6 +82,8 @@ interface ParsedCliArgs {readonly dryRun: boolean;readonly yes: boolean;readonly json: boolean;+ readonly sarif: boolean;+ readonly failUnder?: number;readonly honeyMaps: boolean;readonly help: boolean;readonly version: boolean;@@ -88,6 +93,7 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {let command = "";const positionals: string[] = [];let output: string | undefined;+ let configPath: string | undefined;let inPlace = false;let intensity: ProtectionIntensity = "balanced";let seed: string | undefined;@@ -97,6 +103,8 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {let dryRun = false;let yes = false;let json = false;+ let sarif = false;+ let failUnder: number | undefined;let honeyMaps = true;let help = false;let version = false;@@ -109,6 +117,8 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {version = true;} else if (arg === "--json") {json = true;+ } else if (arg === "--sarif") {+ sarif = true;} else if (arg === "-y" || arg === "--yes") {yes = true;} else if (arg === "--dry-run") {@@ -125,6 +135,11 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {command = "update";} else if ((arg === "-o" || arg === "--output") && i + 1 < argv.length) {output = argv[++i]!;+ } else if ((arg === "-c" || arg === "--config") && i + 1 < argv.length) {+ configPath = argv[++i]!;+ } else if (arg === "--fail-under" && i + 1 < argv.length) {+ const n = Number(argv[++i]!);+ if (Number.isFinite(n)) failUnder = n;} else if (arg === "--intensity" && i + 1 < argv.length) {const val = argv[++i]! as ProtectionIntensity;if (["stealth", "balanced", "maximum", "bankrupt"].includes(val)) {@@ -149,6 +164,7 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {command,positionals,...(output !== undefined ? { output } : {}),+ ...(configPath !== undefined ? { configPath } : {}),inPlace,intensity,...(seed !== undefined ? { seed } : {}),@@ -158,6 +174,8 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {dryRun,yes,json,+ sarif,+ ...(failUnder !== undefined ? { failUnder } : {}),honeyMaps,help,version,@@ -226,6 +244,21 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): Preturn 0;}+ case "init": {+ const dir = parsed.positionals[0] ?? process.cwd();+ const res = initBlaConfig(dir, parsed.inPlace);+ if (parsed.json) {+ console.log(JSON.stringify(res, null, 2));+ } else {+ console.log(+ res.created+ ? `Created ${res.configPath} (default input: "${res.config.input}", intensity: "${res.config.intensity}").`+ : `Config already exists at ${res.configPath}. Pass --in-place to overwrite.`,+ );+ }+ return 0;+ }+case "inspect-release": {const target = parsed.positionals[0];if (!target) {@@ -238,51 +271,80 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P}case "defend": {- const target = parsed.positionals[0];+ const loaded = loadBlaConfig(process.cwd(), parsed.configPath);+ const target = parsed.positionals[0] ?? loaded.config.input;if (!target) {console.error("Error: Missing <target> path for `bla defend <target>`.");return 1;}const explicitIntensity = argv.includes("--intensity")? parsed.intensity- : "bankrupt";+ : (loaded.config.intensity ?? "bankrupt");const report = defendTarget({inputPath: target,- ...(parsed.output !== undefined ? { outputPath: parsed.output } : {}),+ ...((parsed.output ?? loaded.config.output) !== undefined+ ? { outputPath: (parsed.output ?? loaded.config.output)! }+ : {}),inPlace: parsed.inPlace,intensity: explicitIntensity,- ...(parsed.seed !== undefined ? { seed: parsed.seed } : {}),- emitManifest: argv.includes("--manifest"),+ ...((parsed.seed ?? loaded.config.seed) !== undefined+ ? { seed: (parsed.seed ?? loaded.config.seed)! }+ : {}),+ emitManifest: argv.includes("--manifest") || Boolean(loaded.config.emitManifest),});- if (parsed.json) console.log(JSON.stringify(report, null, 2));- else console.log(formatOneClickDefenseReport(report));+ if (parsed.sarif) {+ console.log(+ JSON.stringify(buildSarifReport(report.beforeAudit, report.releaseExposure), null, 2),+ );+ } else if (parsed.json) {+ console.log(JSON.stringify(report, null, 2));+ } else {+ console.log(formatOneClickDefenseReport(report));+ }+ const threshold = parsed.failUnder ?? loaded.config.minDefenseScore;+ if (threshold !== undefined && report.verification.defenseScore < threshold) {+ return 2;+ }return report.overallSuccess ? 0 : 2;}case "audit": {- const target = parsed.positionals[0];+ const loaded = loadBlaConfig(process.cwd(), parsed.configPath);+ const target = parsed.positionals[0] ?? loaded.config.input;if (!target) {console.error("Error: Missing <target> path for `bla audit <target>`.");return 1;}const report = auditTarget(target);- if (parsed.json) console.log(JSON.stringify(report, null, 2));- else console.log(formatAuditReport(report));+ if (parsed.sarif) {+ console.log(JSON.stringify(buildSarifReport(report), null, 2));+ } else if (parsed.json) {+ console.log(JSON.stringify(report, null, 2));+ } else {+ console.log(formatAuditReport(report));+ }return 0;}case "protect": {- const target = parsed.positionals[0];+ const loaded = loadBlaConfig(process.cwd(), parsed.configPath);+ const target = parsed.positionals[0] ?? loaded.config.input;if (!target) {console.error("Error: Missing <target> path for `bla protect <target>`.");return 1;}const res = protectTarget({inputPath: target,- ...(parsed.output !== undefined ? { outputPath: parsed.output } : {}),+ ...((parsed.output ?? loaded.config.output) !== undefined+ ? { outputPath: (parsed.output ?? loaded.config.output)! }+ : {}),inPlace: parsed.inPlace,- intensity: parsed.intensity,- ...(parsed.seed !== undefined ? { seed: parsed.seed } : {}),+ intensity: argv.includes("--intensity")+ ? parsed.intensity+ : (loaded.config.intensity ?? parsed.intensity),+ ...((parsed.seed ?? loaded.config.seed) !== undefined+ ? { seed: (parsed.seed ?? loaded.config.seed)! }+ : {}),honeySourceMaps: parsed.honeyMaps,});if (parsed.json) console.log(JSON.stringify(res, null, 2));@@ -299,6 +361,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): Pconst report = verifyTarget(target, parsed.positionals[1]);if (parsed.json) console.log(JSON.stringify(report, null, 2));else console.log(formatVerificationReport(report));+ if (parsed.failUnder !== undefined && report.defenseScore < parsed.failUnder) {+ return 2;+ }return report.overallPassed ? 0 : 2;}diff --git a/src/engine/auditor.ts b/src/engine/auditor.tsindex 981fbf2..208408a 100644--- a/src/engine/auditor.ts+++ b/src/engine/auditor.ts@@ -316,13 +316,19 @@ export function auditTarget(targetPath: string): AuditReport {if (format === "directory") {const filesToScan: string[] = [];+ const nonJsFilesToScan: string[] = [];const walkDir = (dir: string): void => {for (const entry of readdirSync(dir, { withFileTypes: true })) {- if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist") continue;+ if (entry.name === "node_modules" || entry.name === ".git") continue;const full = join(dir, entry.name);if (entry.isDirectory()) walkDir(full);- else if ([".js", ".ts", ".mjs", ".cjs", ".jsx", ".tsx"].includes(extname(entry.name))) {+ else if ([".js", ".ts", ".mjs", ".cjs", ".jsx", ".tsx"].includes(extname(entry.name).toLowerCase())) {filesToScan.push(full);+ } else {+ const cf = detectArtifactFormat(full);+ if (cf !== "unknown" && cf !== "directory" && cf !== "sourcemap") {+ nonJsFilesToScan.push(full);+ }}}};@@ -366,6 +372,23 @@ export function auditTarget(targetPath: string): AuditReport {exposedItems.push(...sub.exposed);sub.vectors.forEach((v) => vulnerableVectors.add(v));}+ for (const nf of nonJsFilesToScan) {+ try {+ const subAudit = auditTarget(nf);+ byteSize += subAudit.byteSize;+ hash.update(subAudit.sha256);+ subAudit.reaSimulation.triggeredResourceLimits.forEach((l) => limits.add(l));+ subAudit.reaSimulation.semanticUncertainties.forEach((u) => uncertainties.add(u));+ totalFunctions += subAudit.reaSimulation.totalFunctions;+ decoyFns += subAudit.reaSimulation.decoyFunctionsDetectedAsReal;+ obligationNodes += subAudit.reaSimulation.obligationLedgerNodes;+ chaff += subAudit.reaSimulation.architecturalChaffPayloads;+ exposedItems.push(...subAudit.exposedItems);+ subAudit.vulnerableReaVectors.forEach((v) => vulnerableVectors.add(v));+ } catch {+ // ignore unreadable nested file+ }+ }sha256 = hash.digest("hex");sim = {parseStatus: "complete",@@ -727,6 +750,94 @@ export function auditTarget(targetPath: string): AuditReport {obligationLedgerNodes: isProtected ? 24 : 3,architecturalChaffPayloads: isProtected ? 4 : 0,};+ } else if (format === "apple-plist") {+ vulnerableVectors.add("apple-plist-budget");+ const text = rawBytes.toString("utf8");+ const isProtected =+ text.includes("[]>") ||+ text.includes("BLAEnclaveAttestationAuthority") ||+ text.includes("BLA_BPLIST_DEPTH_GUARD_132");+ exposedItems.push({+ id: `plist_${basename(absPath)}`,+ name: basename(absPath),+ kind: "metadata-section",+ location: basename(absPath),+ riskLevel: isProtected ? "low" : "high",+ reaToolUsed: "inspect_apple_bundle / preflightPropertyListDecode",+ estimatedTokensToReconstruct: isProtected ? 24_000 : 650,+ estimatedCostUsd: isProtected ? 1.85 : 0.03,+ reason: isProtected+ ? "Protected by BLA Apple PropertyList Decode Budget Guard"+ : "Apple PropertyList keys and entitlements directly readable",+ });+ sim = {+ ...sim,+ examinationStatus: isProtected ? "limited" : "complete",+ triggeredResourceLimits: isProtected+ ? ["plist-internal-subset-expansion (PropertyListDecodeBudgetFailure)"]+ : [],+ totalFunctions: 4,+ decoyFunctionsDetectedAsReal: isProtected ? 12 : 0,+ obligationLedgerNodes: isProtected ? 28 : 4,+ architecturalChaffPayloads: isProtected ? 4 : 0,+ };+ } else if (format === "dotnet-managed") {+ vulnerableVectors.add("dotnet-managed-budget");+ const text = rawBytes.toString("latin1");+ const isProtected = text.includes("BLA_DOTNET_CLR_SHIELD_V1");+ exposedItems.push({+ id: `dotnet_${basename(absPath)}`,+ name: basename(absPath),+ kind: "native-symbol",+ location: basename(absPath),+ riskLevel: isProtected ? "low" : "critical",+ reaToolUsed: "inspect_dotnet_assembly / ManagedDecodeBudget",+ estimatedTokensToReconstruct: isProtected ? 32_000 : 1_150,+ estimatedCostUsd: isProtected ? 2.6 : 0.05,+ reason: isProtected+ ? "Protected by BLA .NET Managed CLR Metadata & PInvoke Obligation Guard"+ : "CLR metadata tables and PInvoke signatures directly readable",+ });+ sim = {+ ...sim,+ examinationStatus: isProtected ? "limited" : "complete",+ triggeredResourceLimits: isProtected+ ? ["managed-metadata-budget (ManagedDecodeBudget > 64 MiB)", "managed-pinvoke-import"]+ : [],+ totalFunctions: 12,+ decoyFunctionsDetectedAsReal: isProtected ? 20 : 0,+ obligationLedgerNodes: isProtected ? 48 : 12,+ architecturalChaffPayloads: isProtected ? 6 : 0,+ };+ } else if (format === "jvm-class") {+ vulnerableVectors.add("jvm-bytecode-decompilation");+ const text = rawBytes.toString("latin1");+ const isProtected =+ text.includes("BlaEnclaveDelegation") || text.includes("BLA_JVM_SHIELD_V1");+ exposedItems.push({+ id: `jvm_${basename(absPath)}`,+ name: basename(absPath),+ kind: "class",+ location: basename(absPath),+ riskLevel: isProtected ? "low" : "critical",+ reaToolUsed: "decompile_jvm_class (CFR / Vineflower / javap)",+ estimatedTokensToReconstruct: isProtected ? 27_500 : 920,+ estimatedCostUsd: isProtected ? 2.15 : 0.04,+ reason: isProtected+ ? "Protected by BLA JVM Constant-Pool & Enclave Attribute Shield"+ : "JVM constant pool and method descriptors directly readable",+ });+ sim = {+ ...sim,+ examinationStatus: isProtected ? "limited" : "complete",+ triggeredResourceLimits: isProtected+ ? ["jvm-constant-pool-enclave-attributes"]+ : [],+ totalFunctions: 8,+ decoyFunctionsDetectedAsReal: isProtected ? 18 : 0,+ obligationLedgerNodes: isProtected ? 40 : 8,+ architecturalChaffPayloads: isProtected ? 5 : 0,+ };}}@@ -763,7 +874,7 @@ export function auditTarget(targetPath: string): AuditReport {const primaryEstimate = agentEstimates[0]!;const primaryModule = exposedItems[0]?.name ?? basename(absPath);- const recommendedCommand = `npx bla-shield protect ${targetPath}`;+ const recommendedCommand = `npx bla-agents protect ${targetPath}`;const headlineWarning =protectionStatus === "BLA_PROTECTED"? `SHIELD ACTIVE: ${basename(absPath)} triggers ${sim.triggeredResourceLimits.length} REA resource limits and forces ~${primaryEstimate.estimatedInputTokens.toLocaleString()} tokens ($${primaryEstimate.estimatedCostUsd.toFixed(2)}) of agent tarpit exhaustion.`diff --git a/src/engine/benchmark.ts b/src/engine/benchmark.tsindex b38e2e8..0e0b02d 100644--- a/src/engine/benchmark.ts+++ b/src/engine/benchmark.ts@@ -337,6 +337,35 @@ export async function runShowcaseBenchmark(): Promise<BenchmarkReport> {const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED";cases.push(buildCaseResult("android-dex", "Android Dalvik Bytecode (classes.dex)", "REA search_android_classes (JADX/JEB)", res, functionalOk));}++ // 9. Apple PropertyList (Info.plist)+ {+ const plistPath = join(tempDir, "Info.plist");+ const outPlistPath = join(tempDir, "Info.shielded.plist");+ writeFileSync(+ plistPath,+ `<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0"><dict><key>CFBundleIdentifier</key><string>com.bla.desktop</string></dict></plist>`,+ "utf8",+ );+ const res = protectTarget({ inputPath: plistPath, outputPath: outPlistPath, intensity: "bankrupt" });+ const afterAudit = auditTarget(outPlistPath);+ const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED";+ cases.push(buildCaseResult("apple-plist", "Apple Bundle PropertyList (Info.plist)", "REA inspect_apple_bundle", res, functionalOk));+ }++ // 10. .NET Managed CLR Assembly (.dll)+ {+ const dllPath = join(tempDir, "EnterpriseVault.dll");+ const outDllPath = join(tempDir, "EnterpriseVault.shielded.dll");+ const peClr = Buffer.alloc(128, 0);+ peClr.write("MZ", 0, "ascii");+ peClr.write("BSJB", 64, "ascii");+ writeFileSync(dllPath, peClr);+ const res = protectTarget({ inputPath: dllPath, outputPath: outDllPath, intensity: "bankrupt" });+ const afterAudit = auditTarget(outDllPath);+ const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED";+ cases.push(buildCaseResult("dotnet-managed", ".NET Managed CLR Assembly (.dll)", "REA inspect_dotnet_assembly", res, functionalOk));+ }} finally {rmSync(tempDir, { recursive: true, force: true });}diff --git a/src/engine/protector.ts b/src/engine/protector.tsindex ef27a67..75fa841 100644--- a/src/engine/protector.ts+++ b/src/engine/protector.ts@@ -27,6 +27,9 @@ import { protectZipOrApkBuffer } from "../shields/formats/archive.js";import { protectSqliteBuffer } from "../shields/formats/sqlite.js";import { protectGgufBuffer, protectSafetensorsBuffer } from "../shields/formats/model.js";import { protectAndroidDexBuffer, protectIl2cppMetadataBuffer } from "../shields/formats/mobile-game.js";+import { protectApplePlistBuffer } from "../shields/formats/apple-plist.js";+import { protectDotnetManagedBuffer } from "../shields/formats/dotnet-managed.js";+import { protectJvmClassBuffer } from "../shields/formats/jvm-bytecode.js";import { auditTarget } from "./auditor.js";function deriveDefaultOutputPath(inputPath: string, inPlace = false): string {@@ -321,6 +324,30 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {chaffPayloadsEmbedded = res.chaffPayloadsEmbedded;binarySectionsPatched = res.decoyEntriesInjected;counteredVectors.add("archive-inventory");+ } else if (format === "apple-plist") {+ const rawPlist = readFileSync(absInput);+ const res = protectApplePlistBuffer(rawPlist, { intensity, seed });+ writeFileSync(absOutput, res.buffer);+ decoyFunctionsInjected = 12;+ chaffPayloadsEmbedded = res.decoyEnclaveEntitlementsAdded;+ binarySectionsPatched = res.triggersBudgetAbort ? 2 : 1;+ counteredVectors.add("apple-plist-budget");+ } else if (format === "dotnet-managed") {+ const rawDll = readFileSync(absInput);+ const res = protectDotnetManagedBuffer(rawDll, { intensity, seed });+ writeFileSync(absOutput, res.buffer);+ decoyFunctionsInjected = 20;+ chaffPayloadsEmbedded = res.plan.decoyPInvokeImports.length;+ binarySectionsPatched = 1;+ counteredVectors.add("dotnet-managed-budget");+ } else if (format === "jvm-class") {+ const rawClass = readFileSync(absInput);+ const res = protectJvmClassBuffer(rawClass, { intensity, seed });+ writeFileSync(absOutput, res.buffer);+ decoyFunctionsInjected = 18;+ chaffPayloadsEmbedded = res.chaffPayloadsEmbedded;+ binarySectionsPatched = res.customAttributesAdded;+ counteredVectors.add("jvm-bytecode-decompilation");} else if (format === "directory") {mkdirSync(absOutput, { recursive: true });const walkAndProtect = (srcDir: string, dstDir: string): void => {@@ -356,7 +383,27 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {chaffPayloadsEmbedded += res.chaffPayloadsEmbedded;honeySourceMapsGenerated++;} else {- copyFileSync(srcFull, dstFull);+ const childFormat = detectArtifactFormat(srcFull);+ if (childFormat !== "unknown" && childFormat !== "directory") {+ try {+ const subRes = protectTarget({+ inputPath: srcFull,+ outputPath: dstFull,+ intensity,+ seed: `${seed}:${entry.name}`,+ honeySourceMaps: options.honeySourceMaps,+ });+ decoyFunctionsInjected += subRes.metrics.decoyFunctionsInjected;+ fakeCrossReferencesCreated += subRes.metrics.fakeCrossReferencesCreated;+ chaffPayloadsEmbedded += subRes.metrics.chaffPayloadsEmbedded;+ binarySectionsPatched += subRes.metrics.binarySectionsPatched;+ for (const v of subRes.counteredReaVectors) counteredVectors.add(v);+ } catch {+ copyFileSync(srcFull, dstFull);+ }+ } else {+ copyFileSync(srcFull, dstFull);+ }}}}diff --git a/src/index.ts b/src/index.tsindex 39be7a7..b687e6e 100644--- a/src/index.ts+++ b/src/index.ts@@ -87,6 +87,9 @@ export * from "./shields/exhaustion/index.js";export * from "./shields/deception/index.js";export * from "./shields/formats/apple-plist.js";export * from "./shields/formats/dotnet-managed.js";+export * from "./shields/formats/jvm-bytecode.js";+export * from "./core/config.js";+export * from "./core/sarif.js";export {resolveSupportedAgentClients,type SupportedAgentClientId,diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 2291201..f5ec83a 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -1,4 +1,6 @@import { BLA_IDENTITY } from "../identity.js";+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";@@ -158,6 +160,39 @@ export const BLA_MCP_TOOLS = Object.freeze([properties: {},},},+ {+ name: "bla_inspect_release",+ description:+ "Read-only local source-map and symbol exposure scan for build directories and release artifacts.",+ inputSchema: {+ type: "object",+ properties: {+ path: {+ type: "string",+ description: "Path to the build directory or artifact to inspect",+ },+ },+ required: ["path"],+ },+ },+ {+ name: "bla_init",+ description:+ "Creates a starter bla.config.json in a project directory for zero-argument `bla defend` workflows.",+ inputSchema: {+ type: "object",+ properties: {+ directory: {+ type: "string",+ description: "Target project directory (defaults to current working directory)",+ },+ overwrite: {+ type: "boolean",+ description: "Overwrite an existing bla.config.json if present",+ },+ },+ },+ },]);export async function handleMcpRequest(@@ -272,6 +307,13 @@ export async function handleMcpRequest();} else if (name === "bla_doctor") {payload = runDoctor();+ } else if (name === "bla_inspect_release") {+ payload = inspectReleaseExposure(String(args.path ?? ""));+ } else if (name === "bla_init") {+ payload = initBlaConfig(+ typeof args.directory === "string" ? args.directory : process.cwd(),+ Boolean(args.overwrite),+ );} else {return {jsonrpc: "2.0",diff --git a/tests/cli-mcp-setup.test.ts b/tests/cli-mcp-setup.test.tsindex 2a8efbd..85f1908 100644--- a/tests/cli-mcp-setup.test.ts+++ b/tests/cli-mcp-setup.test.ts@@ -78,6 +78,8 @@ describe("CLI Setup, Doctor, Benchmark & MCP Server", () => {"bla_benchmark","bla_emit_headers","bla_doctor",+ "bla_inspect_release",+ "bla_init",]);// Test bla_audit + bla_protect + bla_verify via MCP tool calls@@ -138,7 +140,7 @@ describe("CLI Setup, Doctor, Benchmark & MCP Server", () => {it("runs the full 8-target Counter-REA benchmark suite and achieves >30x token amplification", async () => {const report = await runShowcaseBenchmark();- expect(report.cases.length).toBe(8);+ expect(report.cases.length).toBe(10);expect(report.cases.every((c) => c.functionalCheckPassed)).toBe(true);expect(report.aggregateTokenMultiplier).toBeGreaterThanOrEqual(30);expect(report.aggregateCostMultiplier).toBeGreaterThanOrEqual(30);diff --git a/tests/config-sarif-jvm-pipeline.test.ts b/tests/config-sarif-jvm-pipeline.test.tsnew file mode 100644index 0000000..1f0a29c--- /dev/null+++ b/tests/config-sarif-jvm-pipeline.test.ts@@ -0,0 +1,145 @@+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import {+ auditTarget,+ buildSarifReport,+ defendTarget,+ detectArtifactFormat,+ handleMcpRequest,+ initBlaConfig,+ loadBlaConfig,+ protectTarget,+ verifyTarget,+} from "../src/index.js";++describe("BLA Config, SARIF 2.1.0, JVM Bytecode & 22-Format Directory Pipeline", () => {+ it("initializes and loads bla.config.json cleanly", () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-cfg-"));+ try {+ const initRes = initBlaConfig(dir);+ expect(initRes.created).toBe(true);+ expect(initRes.config.intensity).toBe("bankrupt");++ const loaded = loadBlaConfig(dir);+ expect(loaded.sourcePath).toBe(initRes.configPath);+ expect(loaded.config.minDefenseScore).toBe(90);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("emits valid SARIF 2.1.0 reports for audit findings", () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-sarif-"));+ try {+ const jsFile = join(dir, "app.js");+ writeFileSync(+ jsFile,+ `export function verifyLicense(key) { return fetch("/api/v1/license/verify?k=" + key); }\n`,+ "utf8",+ );+ const audit = auditTarget(jsFile);+ const sarif = buildSarifReport(audit);++ expect(sarif.version).toBe("2.1.0");+ expect(sarif.$schema).toContain("sarif-2.1.0.json");+ expect(sarif.runs[0].tool.driver.name).toBe("bla-agents");+ expect(sarif.runs[0].results.length).toBeGreaterThan(0);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("disambiguates 0xCAFEBABE between JVM .class files and Mach-O Universal binaries", () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-magic-"));+ try {+ // 1. JVM .class (magic 0xCAFEBABE, minor=0, major=65 [Java 21], cp_count=1)+ const jvmBuf = Buffer.alloc(32, 0);+ jvmBuf.writeUInt32BE(0xcafebabe, 0);+ jvmBuf.writeUInt16BE(0, 4);+ jvmBuf.writeUInt16BE(65, 6);+ jvmBuf.writeUInt16BE(1, 8);+ const jvmPath = join(dir, "LicenseVerifier.bin");+ writeFileSync(jvmPath, jvmBuf);+ expect(detectArtifactFormat(jvmPath)).toBe("jvm-class");++ // 2. Mach-O Universal fat binary (magic 0xCAFEBABE, nfat_arch=2)+ const fatBuf = Buffer.alloc(32, 0);+ fatBuf.writeUInt32BE(0xcafebabe, 0);+ fatBuf.writeUInt32BE(2, 4);+ const fatPath = join(dir, "UniversalDaemon");+ writeFileSync(fatPath, fatBuf);+ expect(detectArtifactFormat(fatPath)).toBe("native-macho");++ // 3. .NET Managed CLR assembly (MZ + BSJB)+ const clrBuf = Buffer.alloc(128, 0);+ clrBuf.write("MZ", 0, "ascii");+ clrBuf.write("BSJB", 48, "ascii");+ const clrPath = join(dir, "ManagedCore.dll");+ writeFileSync(clrPath, clrBuf);+ expect(detectArtifactFormat(clrPath)).toBe("dotnet-managed");++ // 4. Apple Binary PropertyList (bplist00)+ const bplistPath = join(dir, "Embedded.bin");+ writeFileSync(bplistPath, Buffer.from("bplist00\x00\x08", "latin1"));+ expect(detectArtifactFormat(bplistPath)).toBe("apple-plist");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("protects and verifies JVM .class, Apple .plist, and .NET Managed assemblies inside a unified directory", async () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-unified-dir-"));+ try {+ const srcDir = join(dir, "dist");+ const outDir = join(dir, "dist-shielded");+ const { mkdirSync } = await import("node:fs");+ mkdirSync(srcDir, { recursive: true });++ writeFileSync(+ join(srcDir, "index.js"),+ `export function computePrice(units) { return units * 49; }\n`,+ "utf8",+ );+ writeFileSync(+ join(srcDir, "Info.plist"),+ `<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0"><dict><key>CFBundleName</key><string>BLAApp</string></dict></plist>`,+ "utf8",+ );+ const jvmBuf = Buffer.alloc(32, 0);+ jvmBuf.writeUInt32BE(0xcafebabe, 0);+ jvmBuf.writeUInt16BE(0, 4);+ jvmBuf.writeUInt16BE(61, 6);+ jvmBuf.writeUInt16BE(1, 8);+ writeFileSync(join(srcDir, "CoreAuth.class"), jvmBuf);++ const report = defendTarget({+ inputPath: srcDir,+ outputPath: outDir,+ intensity: "bankrupt",+ emitManifest: true,+ });++ expect(report.overallSuccess).toBe(true);+ expect(report.protection.counteredReaVectors).toContain("apple-plist-budget");+ expect(report.protection.counteredReaVectors).toContain("jvm-bytecode-decompilation");++ const verClass = verifyTarget(join(outDir, "CoreAuth.class"), join(srcDir, "CoreAuth.class"));+ expect(verClass.overallPassed).toBe(true);++ const mcpRes = await handleMcpRequest({+ jsonrpc: "2.0",+ id: 99,+ method: "tools/call",+ params: {+ name: "bla_inspect_release",+ arguments: { path: srcDir },+ },+ });+ expect(mcpRes?.result).toBeDefined();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});