Skip to content

armgit / bla

Public Imported from GitHub
0

🛡️ 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.

feat(ux): add bla_harden one-sentence auto-discover hardening

qybaihec59d07b418b2
diff --git a/.agents/skills/blind-llm-agents/SKILL.md b/.agents/skills/blind-llm-agents/SKILL.md
index 3b3f1cc..998e287 100644
--- a/.agents/skills/blind-llm-agents/SKILL.md
+++ b/.agents/skills/blind-llm-agents/SKILL.md
@@ -1,17 +1,27 @@
---
name: blind-llm-agents
-description: Audit, protect, and verify software artifacts (JavaScript/TypeScript, Electron ASAR, WebAssembly, Python .py/.pyc, SQLite, Safetensors/GGUF AI Models, Android DEX/IL2CPP, and Native ELF/Mach-O/PE Binaries) against AI reverse-engineering agents like REA using BLA (Blind LLM Agents).
+description: Audit, protect, and verify software artifacts (JavaScript/TypeScript, Electron ASAR, WebAssembly, Python .py/.pyc, SQLite, Safetensors/GGUF AI Models, Android DEX/IL2CPP, Apple plist, .NET, JVM, ZIP/APK, and Native ELF/Mach-O/PE Binaries) against AI reverse-engineering agents like REA using BLA (Blind LLM Agents). Default verb: bla_harden.
metadata:
- version: "1.1.0"
+ version: "1.2.0"
---
# BLA: Blind LLM Agents
Use BLA whenever the user asks to harden a project against AI reverse-engineering agents (`morluto/rea`), audit exposure, exhaust attacker token/compute budgets, or induce model misjudgment on proprietary logic.
-## ⚡ One-Click Agent Defense Hardening (Recommended)
+## ⚡ One-Sentence Hardening (DEFAULT — prefer this)
-When the user says **"Harden this project against REA"**, **"一键启动防御强化"**, or **"Run BLA defense"**, invoke the single one-click pipeline immediately:
+When the user says **"Harden my software"**, **"Harden this project against REA"**, **"一键启动防御强化"**, **"Run BLA defense"**, or any equivalent one-liner **without naming a specific file**, invoke:
+
+- **MCP Tool (preferred)**: `bla_harden` with `{ "directory": "." }` (or the project/build path they named)
+- **CLI**: `npx bla-agents@latest harden .`
+- **MCP Prompt**: `bla-harden-project`
+
+`bla_harden` / `bla harden` auto-discovers protectable build outputs under `dist/`, `build/`, `out/`, `release/`, `.asar`, native binaries, `.wasm`, `.py`/`.pyc`, `.sqlite`, `.safetensors`/`.gguf`, `.dex`, `.class`, `.dll`, Apple plists, ZIP/APK, etc., detects each artifact's format, and runs the full **audit → defend (bankrupt) → verify** pipeline on all of them. Return the per-artifact summary to the user. Do **not** ask which files to protect — discover them.
+
+## One-Click Single-Artifact Defense
+
+When the user already named a **specific file**, use:
- **MCP Tool**: `bla_defend` with `{ "input_path": "<target>", "intensity": "bankrupt", "emit_manifest": true }`
- **CLI Command**: `npx bla-agents@latest defend <target> --manifest`
@@ -19,8 +29,8 @@ When the user says **"Harden this project against REA"**, **"一键启动防御
`bla_defend` / `bla defend` executes all 5 Counter-REA defense stages automatically:
1. **Stage 1 (`inspect-release`)**: Read-only scan for accidental `.map` (`sourcesContent`) and symbol leaks.
2. **Stage 2 (`audit`)**: 16-vector REA vulnerability & Claude Opus 4 / Sonnet 4 / o3 token-cost simulation.
-3. **Stage 3 (`protect --intensity bankrupt`)**: Injects both the **Resource-Exhaustion Suite** (`REA_BUDGET_BREAKER_MATRIX`, 22-family `ReconstructionObligationLedger` flood, Tarjan SCC Call-Graph Labyrinth, BPE Subword Token Sink) and the **Model-Misjudgment Induction Suite** (`ShadowBusinessLogic`, `EvidenceContractPoison` competing-explanation lures, gRPC/vsock `ArchitectureMirage`, `SemanticHoneypot` bait exports, and Shared-ArrayBuffer `DecompilerIllusion`).
-4. **Stage 4 (`verify`)**: Verifies all Counter-REA mathematical invariants and confirms `16x–51x` token/cost bankruptcy amplification.
+3. **Stage 3 (`protect --intensity bankrupt`)**: Injects both the **Resource-Exhaustion Suite** and the **Model-Misjudgment Induction Suite** (including canary honeypots + system-diagnostic decoys across JS, WASM, Python, SQLite, Safetensors/GGUF, DEX, IL2CPP, Apple plist, .NET, JVM, ZIP/APK).
+4. **Stage 4 (`verify`)**: Verifies all Counter-REA mathematical invariants and confirms token/cost bankruptcy amplification.
5. **Stage 5 (`manifest`)**: Emits `<output>.bla-manifest.json` attesting to the hardened build.
## Step-by-Step Granular Workflow: Audit -> Protect -> Verify
@@ -28,23 +38,19 @@ When the user says **"Harden this project against REA"**, **"一键启动防御
1. **Audit (`bla_audit` or `npx bla-agents audit <target>`)**:
- Reports the **REA Exposure Score (0–100)**, exposed functions/classes/IPC channels/routes, and estimated attacker token and dollar costs.
2. **Protect (`bla_protect` or `npx bla-agents protect <target> -o <output> --intensity bankrupt`)**:
- - **Resource Exhaustion (耗尽对方资源)**:
- - Trips REA's `SEMANTIC_PRIMITIVE_CANDIDATE_LIMIT = 256` ($2^9 = 512$ opaque ternary chunks), `SEMANTIC_ALIAS_SELECTION_LIMIT = 512` (520+ selector states), `SEMANTIC_GETTER_EXPANSION_LIMIT = 512` (self-referential getter rings), and `SEMANTIC_PRIMITIVE_JSON_BYTES_LIMIT = 1_048_576` (`codeUnits * 6 + 2` Cartesian string explosion).
- - Floods all 22 `ReconstructionObligationPolicies` families (`context-bridge-api`, `ipc-channel`, `ipc-handler`, `endpoint`, `storage`, `worker`, `service-worker`, `native-addon`, `child-process`, `stdio`, `signal`, `config-source`, etc.), multiplying mandatory verification fixtures (`positive`, `negative`, `malformed`, `cancellation`, `teardown`) by `20x–60x`.
- - Injects Tarjan SCC mutually-recursive call-graph labyrinths and BPE subword token amplifiers.
- - **Model Misjudgment Induction (诱导模型误判)**:
- - Exploits REA's `COMMON_DISCIPLINE` (*"Report Observations only from cited Evidence... Keep incomplete coverage explicit as Unknowns"*): wraps real business logic in `status: "unknown"` semantic budget breakers while leaving crystal-clear **Shadow Business Logic** (`shamir-ed25519-license-ring`, `enterprise-tiered-pricing-matrix`, `binary-wire-frame-ratchet`, `tpm2-pcr-dongle-handshake`) 100% `observed`, inducing the LLM to reconstruct the decoy algorithm.
- - Plants high-confidence Evidence Contract competing-explanation lures, gRPC/vsock hardware enclave mirages, and shared-`ArrayBuffer` decompiler aliasing illusions.
+ - **Resource Exhaustion (耗尽对方资源)** and **Model Misjudgment Induction (诱导模型误判)** as documented in [references/counter-rea-matrix.md](references/counter-rea-matrix.md).
3. **Verify (`bla_verify` or `npx bla-agents verify <protected> [original]`)**:
- Confirms that all Counter-REA gates pass and reports exact Token & API Cost Amplification.
## CLI Fallback Commands
```bash
+npx -y bla-agents@latest harden .
npx -y bla-agents@latest defend /absolute/path/to/target --manifest --json
npx -y bla-agents@latest audit /absolute/path/to/target --json
npx -y bla-agents@latest protect /absolute/path/to/target -o /absolute/path/to/protected --intensity bankrupt --json
npx -y bla-agents@latest verify /absolute/path/to/protected /absolute/path/to/target --json
+npx -y bla-agents@latest doctor
```
See [references/counter-rea-matrix.md](references/counter-rea-matrix.md) for the complete mapping between REA's internal analyzers and BLA's countermeasures.
diff --git a/src/cli.ts b/src/cli.ts
index df12620..49dfd4e 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -10,6 +10,7 @@ import { auditTarget } from "./engine/auditor.js";
import { protectTarget } from "./engine/protector.js";
import { verifyTarget } from "./engine/verifier.js";
import { defendTarget } from "./engine/defender.js";
+import { formatHardenProjectReport, hardenProject } from "./engine/harden.js";
import { runShowcaseBenchmark } from "./engine/benchmark.js";
import {
emitCompileTimeNativeHeader,
@@ -40,6 +41,7 @@ Usage:
Commands:
setup Configure agent MCP integrations & install the BLA skill
+ harden [dir] DEFAULT: auto-discover build outputs under a project/build dir and bankrupt-harden all of them
defend <target> One-click full Counter-REA pipeline (inspect -> audit -> bankrupt protect -> verify)
inspect-release <target> Read-only local source-map & symbol exposure check
audit <target> Pre-flight REA exposure & vulnerability scan
@@ -270,6 +272,29 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
return report.status === "complete" ? 0 : 2;
}
+ case "harden": {
+ const loaded = loadBlaConfig(process.cwd(), parsed.configPath);
+ const directory = parsed.positionals[0] ?? loaded.config.input ?? process.cwd();
+ const explicitIntensity = argv.includes("--intensity")
+ ? parsed.intensity
+ : (loaded.config.intensity ?? "bankrupt");
+ const report = hardenProject({
+ directory,
+ intensity: explicitIntensity,
+ ...((parsed.seed ?? loaded.config.seed) !== undefined
+ ? { seed: (parsed.seed ?? loaded.config.seed)! }
+ : {}),
+ emitManifest: argv.includes("--manifest") || loaded.config.emitManifest !== false,
+ ...(parsed.output !== undefined ? { outputDirectory: parsed.output } : {}),
+ });
+ if (parsed.json) {
+ console.log(JSON.stringify(report, null, 2));
+ } else {
+ console.log(formatHardenProjectReport(report));
+ }
+ return report.overallSuccess || report.discoveredCount === 0 ? (report.discoveredCount === 0 ? 2 : 0) : 2;
+ }
+
case "defend": {
const loaded = loadBlaConfig(process.cwd(), parsed.configPath);
const target = parsed.positionals[0] ?? loaded.config.input;
diff --git a/src/engine/harden.ts b/src/engine/harden.ts
new file mode 100644
index 0000000..07a71a9
--- /dev/null
+++ b/src/engine/harden.ts
@@ -0,0 +1,332 @@
+import {
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { basename, dirname, join, relative, resolve } from "node:path";
+import { detectArtifactFormat } from "../core/detector.js";
+import type { ArtifactFormat, ProtectionIntensity } from "../core/types.js";
+import { BLA_IDENTITY } from "../identity.js";
+import {
+ defendTarget,
+ type OneClickDefenseReport,
+} from "./defender.js";
+
+/** Preferred build-output directory names, searched first under a project root. */
+export const BLA_BUILD_OUTPUT_DIR_NAMES = Object.freeze([
+ "dist",
+ "build",
+ "out",
+ "release",
+ "bin",
+ ".next",
+ "target",
+] as const);
+
+const SKIP_DIR_NAMES = new Set([
+ "node_modules",
+ ".git",
+ ".hg",
+ ".svn",
+ ".bla-hardened",
+ "coverage",
+ ".turbo",
+ ".cache",
+ "__pycache__",
+ ".venv",
+ "venv",
+]);
+
+const MAX_DISCOVERED_ARTIFACTS = 64;
+const MAX_WALK_DEPTH = 8;
+
+export interface DiscoveredArtifact {
+ readonly path: string;
+ readonly format: ArtifactFormat;
+ readonly relativePath: string;
+}
+
+export interface HardenArtifactSummary {
+ readonly inputPath: string;
+ readonly relativePath: string;
+ readonly format: ArtifactFormat;
+ readonly outputPath: string;
+ readonly success: boolean;
+ readonly defenseScore: number;
+ readonly tokenAmplificationFactor: number;
+ readonly costAmplificationFactor: number;
+ readonly error?: string;
+}
+
+export interface HardenProjectOptions {
+ /** Project or build directory (default: cwd). A single file is also accepted. */
+ readonly directory?: string;
+ readonly intensity?: ProtectionIntensity;
+ readonly seed?: string | number;
+ readonly emitManifest?: boolean;
+ /** Optional output root; defaults to `<dir>/.bla-hardened`. */
+ readonly outputDirectory?: string;
+ readonly maxArtifacts?: number;
+}
+
+export interface HardenProjectReport {
+ readonly blaVersion: string;
+ readonly directory: string;
+ readonly intensity: ProtectionIntensity;
+ readonly overallSuccess: boolean;
+ readonly discoveredCount: number;
+ readonly hardenedCount: number;
+ readonly failedCount: number;
+ readonly artifacts: readonly HardenArtifactSummary[];
+ readonly oneSentenceUsage: string;
+}
+
+function isProtectableFormat(format: ArtifactFormat): boolean {
+ return format !== "unknown" && format !== "directory";
+}
+
+/**
+ * Prefer known build-output directories when present; otherwise walk the project
+ * root. Always skips VCS/dependency caches.
+ */
+function resolveSearchRoots(absRoot: string): readonly string[] {
+ const preferred: string[] = [];
+ for (const name of BLA_BUILD_OUTPUT_DIR_NAMES) {
+ const candidate = join(absRoot, name);
+ try {
+ if (statSync(candidate).isDirectory()) preferred.push(candidate);
+ } catch {
+ /* absent */
+ }
+ }
+ // Rust/cargo nested release
+ const cargoRelease = join(absRoot, "target", "release");
+ try {
+ if (statSync(cargoRelease).isDirectory() && !preferred.includes(cargoRelease)) {
+ preferred.push(cargoRelease);
+ }
+ } catch {
+ /* absent */
+ }
+ return preferred.length > 0 ? preferred : [absRoot];
+}
+
+function walkCollect(
+ dir: string,
+ root: string,
+ depth: number,
+ out: DiscoveredArtifact[],
+ maxArtifacts: number,
+): void {
+ if (out.length >= maxArtifacts || depth > MAX_WALK_DEPTH) return;
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (out.length >= maxArtifacts) return;
+ if (entry.name.startsWith(".") && entry.name !== ".asar") {
+ // Still allow probing files that begin with '.', but skip hidden dirs.
+ if (entry.isDirectory()) continue;
+ }
+ if (entry.isDirectory()) {
+ if (SKIP_DIR_NAMES.has(entry.name)) continue;
+ walkCollect(join(dir, entry.name), root, depth + 1, out, maxArtifacts);
+ continue;
+ }
+ const full = join(dir, entry.name);
+ const format = detectArtifactFormat(full);
+ if (!isProtectableFormat(format)) continue;
+ // Skip already-shielded outputs to avoid re-hardening loops.
+ if (/\.shielded(\.|$)/i.test(entry.name)) continue;
+ if (entry.name.endsWith(".bla-manifest.json")) continue;
+ out.push({
+ path: full,
+ format,
+ relativePath: relative(root, full) || basename(full),
+ });
+ }
+}
+
+/**
+ * Auto-discovers protectable build artifacts under a project or build directory.
+ * Recognises dist/build/out/release/.asar/native/.wasm/.py/.pyc/.sqlite/
+ * .safetensors/.gguf/.dex/.class/.dll and magic-byte formats.
+ */
+export function discoverHardenableArtifacts(
+ directory: string = process.cwd(),
+ options: { readonly maxArtifacts?: number } = {},
+): readonly DiscoveredArtifact[] {
+ const abs = resolve(directory);
+ const maxArtifacts = options.maxArtifacts ?? MAX_DISCOVERED_ARTIFACTS;
+ if (!existsSync(abs)) {
+ throw new Error(`Path not found: ${abs}`);
+ }
+ const stats = statSync(abs);
+ if (stats.isFile()) {
+ const format = detectArtifactFormat(abs);
+ if (!isProtectableFormat(format)) {
+ throw new Error(`Unsupported artifact format at ${abs}`);
+ }
+ return [{ path: abs, format, relativePath: basename(abs) }];
+ }
+ if (!stats.isDirectory()) {
+ throw new Error(`Not a file or directory: ${abs}`);
+ }
+
+ const found: DiscoveredArtifact[] = [];
+ const roots = resolveSearchRoots(abs);
+ for (const root of roots) {
+ walkCollect(root, abs, 0, found, maxArtifacts);
+ }
+ // De-dupe by absolute path (cargo release may overlap target/)
+ const seen = new Set<string>();
+ const unique: DiscoveredArtifact[] = [];
+ for (const item of found) {
+ if (seen.has(item.path)) continue;
+ seen.add(item.path);
+ unique.push(item);
+ }
+ return unique;
+}
+
+function deriveArtifactOutputPath(
+ artifact: DiscoveredArtifact,
+ projectRoot: string,
+ outputRoot: string,
+): string {
+ const rel = artifact.relativePath;
+ const dest = join(outputRoot, rel);
+ const dir = dirname(dest);
+ mkdirSync(dir, { recursive: true });
+ // Keep original basename; place under .bla-hardened mirror tree.
+ return dest;
+}
+
+/**
+ * One-sentence Counter-REA hardening: discover every protectable build artifact
+ * under a project/build directory and run the full audit→defend→verify pipeline
+ * with the bankrupt profile. Modelled on REA's `npx rea-agents setup` simplicity.
+ *
+ * Usage: `bla harden .` / MCP `bla_harden` with `{ "directory": "." }`
+ */
+export function hardenProject(
+ options: HardenProjectOptions = {},
+): HardenProjectReport {
+ const absDir = resolve(options.directory ?? process.cwd());
+ const intensity: ProtectionIntensity = options.intensity ?? "bankrupt";
+ const emitManifest = options.emitManifest !== false;
+ const maxArtifacts = options.maxArtifacts ?? MAX_DISCOVERED_ARTIFACTS;
+
+ const discovered = discoverHardenableArtifacts(absDir, { maxArtifacts });
+ const outputRoot = resolve(
+ options.outputDirectory ??
+ (statSync(absDir).isDirectory()
+ ? join(absDir, ".bla-hardened")
+ : join(dirname(absDir), ".bla-hardened")),
+ );
+ if (discovered.length > 0) {
+ mkdirSync(outputRoot, { recursive: true });
+ }
+
+ const summaries: HardenArtifactSummary[] = [];
+ for (const artifact of discovered) {
+ const outputPath = deriveArtifactOutputPath(artifact, absDir, outputRoot);
+ try {
+ const report: OneClickDefenseReport = defendTarget({
+ inputPath: artifact.path,
+ outputPath,
+ intensity,
+ ...(options.seed !== undefined ? { seed: options.seed } : {}),
+ emitManifest,
+ });
+ summaries.push({
+ inputPath: artifact.path,
+ relativePath: artifact.relativePath,
+ format: artifact.format,
+ outputPath: report.outputPath,
+ success: report.overallSuccess,
+ defenseScore: report.verification.defenseScore,
+ tokenAmplificationFactor:
+ report.exhaustionSummary.tokenAmplificationFactor,
+ costAmplificationFactor:
+ report.exhaustionSummary.costAmplificationFactor,
+ });
+ } catch (err) {
+ summaries.push({
+ inputPath: artifact.path,
+ relativePath: artifact.relativePath,
+ format: artifact.format,
+ outputPath,
+ success: false,
+ defenseScore: 0,
+ tokenAmplificationFactor: 0,
+ costAmplificationFactor: 0,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
+ // Persist a project-level summary for agents to read back.
+ if (discovered.length > 0) {
+ try {
+ writeFileSync(
+ join(outputRoot, "bla-harden-summary.json"),
+ JSON.stringify(
+ {
+ schema: "bla-harden-summary/v1",
+ directory: absDir,
+ intensity,
+ artifacts: summaries,
+ },
+ null,
+ 2,
+ ),
+ "utf8",
+ );
+ } catch {
+ /* best-effort */
+ }
+ }
+
+ const hardenedCount = summaries.filter((s) => s.success).length;
+ const failedCount = summaries.length - hardenedCount;
+ return {
+ blaVersion: BLA_IDENTITY.version,
+ directory: absDir,
+ intensity,
+ overallSuccess: summaries.length > 0 && failedCount === 0,
+ discoveredCount: discovered.length,
+ hardenedCount,
+ failedCount,
+ artifacts: summaries,
+ oneSentenceUsage:
+ 'Harden my software against REA — call bla_harden with { "directory": "." } (or `bla harden .`).',
+ };
+}
+
+export function formatHardenProjectReport(report: HardenProjectReport): string {
+ const lines: string[] = [
+ `BLA harden ${report.blaVersion} — ${report.directory}`,
+ `Intensity: ${report.intensity} | discovered=${report.discoveredCount} hardened=${report.hardenedCount} failed=${report.failedCount}`,
+ `Overall: ${report.overallSuccess ? "SUCCESS" : report.discoveredCount === 0 ? "NO ARTIFACTS" : "PARTIAL/FAILED"}`,
+ ];
+ for (const a of report.artifacts) {
+ lines.push(
+ a.success
+ ? ` ✓ ${a.relativePath} [${a.format}] score=${a.defenseScore} tokens×${a.tokenAmplificationFactor.toFixed(1)} → ${a.outputPath}`
+ : ` ✗ ${a.relativePath} [${a.format}] ${a.error ?? "failed"}`,
+ );
+ }
+ if (report.discoveredCount === 0) {
+ lines.push(
+ " (no protectable build artifacts found — place outputs under dist/, build/, out/, or release/)",
+ );
+ }
+ lines.push(`Tip: ${report.oneSentenceUsage}`);
+ return lines.join("\n");
+}
diff --git a/src/index.ts b/src/index.ts
index bb55cbf..5e08454 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -129,6 +129,15 @@ export {
type OneClickDefenseStageSummary,
} from "./engine/defender.js";
export { runShowcaseBenchmark } from "./engine/benchmark.js";
+export {
+ discoverHardenableArtifacts,
+ hardenProject,
+ formatHardenProjectReport,
+ BLA_BUILD_OUTPUT_DIR_NAMES,
+ type HardenProjectReport,
+ type HardenArtifactSummary,
+ type DiscoveredArtifact,
+} from "./engine/harden.js";
export * from "./shields/exhaustion/index.js";
export * from "./shields/deception/index.js";
export * from "./shields/formats/apple-plist.js";
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 03c0ef4..4254e3d 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -6,6 +6,7 @@ import { auditTarget } from "../engine/auditor.js";
import { protectTarget } from "../engine/protector.js";
import { verifyTarget } from "../engine/verifier.js";
import { defendTarget } from "../engine/defender.js";
+import { hardenProject } from "../engine/harden.js";
import { runShowcaseBenchmark } from "../engine/benchmark.js";
import {
emitCompileTimeNativeHeader,
@@ -61,6 +62,7 @@ export interface McpPromptDefinition {
}
export interface McpEngineHandlers {
+ readonly hardenProject: typeof hardenProject;
readonly defendTarget: typeof defendTarget;
readonly auditTarget: typeof auditTarget;
readonly protectTarget: typeof protectTarget;
@@ -73,6 +75,7 @@ export interface McpEngineHandlers {
}
const DEFAULT_ENGINE_HANDLERS: McpEngineHandlers = Object.freeze({
+ hardenProject,
defendTarget,
auditTarget,
protectTarget,
@@ -90,6 +93,30 @@ export const SUPPORTED_MCP_PROTOCOL_VERSIONS = Object.freeze([
] as const);
export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
+ {
+ name: "bla_harden",
+ description:
+ "DEFAULT one-sentence Counter-REA hardening. Auto-discovers build outputs (dist/, build/, out/, release/, .asar, native binaries, .wasm, .py/.pyc, .sqlite, .safetensors/.gguf, .dex, .class, etc.), detects each artifact's format, and runs the full audit→defend→verify pipeline with the bankrupt profile. Pass just a project or build directory (default: cwd). Prefer this over bla_defend when the user says 'harden my software' without naming a specific file.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ directory: {
+ type: "string",
+ description: "Project or build directory to harden (default: current working directory)",
+ },
+ intensity: {
+ type: "string",
+ enum: ["stealth", "balanced", "maximum", "bankrupt"],
+ description: "Protection intensity preset (default: bankrupt)",
+ },
+ emit_manifest: {
+ type: "boolean",
+ description: "Emit a signed .bla-manifest.json per artifact (default: true)",
+ },
+ },
+ additionalProperties: false,
+ },
+ },
{
name: "bla_defend",
description:
@@ -277,6 +304,18 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
]);
export const BLA_MCP_PROMPTS: readonly McpPromptDefinition[] = Object.freeze([
+ {
+ name: "bla-harden-project",
+ description:
+ "One-sentence Counter-REA hardening: discover every protectable build artifact under a project directory and run bla_harden (audit→defend→verify, bankrupt profile).",
+ arguments: [
+ {
+ name: "directory",
+ description: "Project or build directory (default: .)",
+ required: false,
+ },
+ ],
+ },
{
name: "shield-against-rea",
description:
@@ -592,7 +631,21 @@ export async function handleMcpRequest(
}
}
}
- const targetPath = String(promptArgs.target_path);
+ let promptText: string;
+ if (promptDef.name === "bla-harden-project") {
+ const directory =
+ typeof promptArgs.directory === "string" && promptArgs.directory.trim().length > 0
+ ? String(promptArgs.directory)
+ : ".";
+ promptText =
+ `Harden my software against REA in one step: call bla_harden with { "directory": "${directory}" }. ` +
+ `It auto-discovers build outputs, runs audit→defend→verify with the bankrupt profile on every artifact, and returns a per-artifact summary. ` +
+ `Do not ask which files to protect — discover them.`;
+ } else {
+ const targetPath = String(promptArgs.target_path ?? ".");
+ promptText =
+ `Inspect and audit '${targetPath}' using bla_inspect_release and bla_audit, then review findings before applying bla_protect or bla_defend and verifying with bla_verify.`;
+ }
return {
jsonrpc: "2.0",
id: req.id,
@@ -603,7 +656,7 @@ export async function handleMcpRequest(
role: "user",
content: {
type: "text",
- text: `Inspect and audit '${targetPath}' using bla_inspect_release and bla_audit, then review findings before applying bla_protect or bla_defend and verifying with bla_verify.`,
+ text: promptText,
},
},
],
@@ -628,7 +681,20 @@ export async function handleMcpRequest(
const name = tool.name;
let payload: unknown;
- if (name === "bla_defend") {
+ 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:
+ args.emit_manifest === undefined ? true : Boolean(args.emit_manifest),
+ });
+ } else if (name === "bla_defend") {
payload = handlers.defendTarget({
inputPath: args.input_path as string,
...(typeof args.output_path === "string"
diff --git a/src/setup/setup.ts b/src/setup/setup.ts
index 1985ca5..74b4207 100644
--- a/src/setup/setup.ts
+++ b/src/setup/setup.ts
@@ -634,7 +634,7 @@ export function runSetup(options: SetupRunOptions = {}): SetupRunResult {
manifestPath,
message:
overallStatus === "applied"
- ? `Configured BLA MCP server and skill for ${appliedCount} agent client(s). Restart your agent to load BLA tools.`
+ ? `Configured BLA MCP server and skill for ${appliedCount} agent client(s). Restart your agent to load BLA tools, then run bla_harden . (or: Harden my software against REA).`
: `Completed setup with status '${overallStatus}' (${appliedCount}/${completedActions.length} applied).`,
};
}
diff --git a/tests/cli-mcp-setup.test.ts b/tests/cli-mcp-setup.test.ts
index d115461..9f6333b 100644
--- a/tests/cli-mcp-setup.test.ts
+++ b/tests/cli-mcp-setup.test.ts
@@ -77,6 +77,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_defend",
"bla_audit",
"bla_protect",
diff --git a/tests/harden-autodiscover.test.ts b/tests/harden-autodiscover.test.ts
new file mode 100644
index 0000000..b2689f2
--- /dev/null
+++ b/tests/harden-autodiscover.test.ts
@@ -0,0 +1,189 @@
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ discoverHardenableArtifacts,
+ hardenProject,
+} from "../src/engine/harden.js";
+import { handleMcpRequest } from "../src/mcp/server.js";
+import { runCli } from "../src/cli.js";
+import { writeZipArchive } from "../src/shields/formats/archive.js";
+
+const tempDirs: string[] = [];
+function createTempDir(): string {
+ const dir = mkdtempSync(join(tmpdir(), "bla-harden-"));
+ tempDirs.push(dir);
+ return dir;
+}
+
+afterEach(() => {
+ for (const dir of tempDirs.splice(0)) {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+function minimalDex(): Buffer {
+ const dex = Buffer.alloc(112, 0);
+ dex.write("dex\n035\0", 0, "ascii");
+ dex.writeUInt32LE(112, 32);
+ dex.writeUInt32LE(112, 36);
+ dex.writeUInt32LE(0x12345678, 40);
+ return dex;
+}
+
+function minimalWasm(): Buffer {
+ // \0asm + version 1
+ return Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
+}
+
+describe("bla_harden auto-discovery + one-sentence UX", () => {
+ it("discovers mixed artifact types under dist/ and hardens them all", () => {
+ const root = createTempDir();
+ const dist = join(root, "dist");
+ mkdirSync(dist, { recursive: true });
+
+ writeFileSync(
+ join(dist, "app.js"),
+ `export function unlockPremium(token) { return token === "LIVE-KEY"; }\n`,
+ "utf8",
+ );
+ writeFileSync(join(dist, "module.wasm"), minimalWasm());
+ writeFileSync(join(dist, "classes.dex"), minimalDex());
+ writeFileSync(
+ join(dist, "payload.py"),
+ "def verify_license(key: str) -> bool:\n return key.startswith('ENT-')\n",
+ "utf8",
+ );
+ // Noise that must be ignored
+ mkdirSync(join(root, "node_modules", "left-pad"), { recursive: true });
+ writeFileSync(join(root, "node_modules", "left-pad", "index.js"), "module.exports=1\n");
+ writeFileSync(join(root, "README.md"), "# demo\n");
+
+ const discovered = discoverHardenableArtifacts(root);
+ const formats = discovered.map((d) => d.format).sort();
+ expect(formats).toEqual(
+ expect.arrayContaining(["javascript", "wasm", "android-dex", "python-source"]),
+ );
+ expect(discovered.every((d) => !d.path.includes("node_modules"))).toBe(true);
+
+ const report = hardenProject({
+ directory: root,
+ intensity: "bankrupt",
+ seed: "harden-mix-v1",
+ emitManifest: true,
+ });
+
+ expect(report.discoveredCount).toBeGreaterThanOrEqual(4);
+ expect(report.hardenedCount).toBe(report.discoveredCount);
+ expect(report.failedCount).toBe(0);
+ expect(report.overallSuccess).toBe(true);
+ expect(report.oneSentenceUsage).toContain("bla_harden");
+
+ for (const a of report.artifacts) {
+ expect(a.success).toBe(true);
+ expect(a.defenseScore).toBeGreaterThanOrEqual(50);
+ expect(existsSync(a.outputPath)).toBe(true);
+ const bytes = readFileSync(a.outputPath);
+ // Every hardened format should still be loadable / magic-valid
+ if (a.format === "wasm") {
+ expect(bytes.subarray(0, 4).toString("latin1")).toBe("\0asm");
+ }
+ if (a.format === "android-dex") {
+ expect(bytes.subarray(0, 4).toString("latin1")).toBe("dex\n");
+ expect(bytes.toString("latin1")).toContain("PROTECTED_CANARY_CREDENTIAL=");
+ }
+ if (a.format === "javascript") {
+ expect(bytes.toString("utf8")).toContain("unlockPremium");
+ }
+ if (a.format === "python-source") {
+ expect(bytes.toString("utf8")).toContain("verify_license");
+ }
+ }
+ });
+
+ it("exposes bla_harden over MCP and CLI `bla harden`", async () => {
+ const root = createTempDir();
+ const dist = join(root, "dist");
+ mkdirSync(dist, { recursive: true });
+ writeFileSync(
+ join(dist, "core.js"),
+ `export const secret = (k) => k.length > 8;\n`,
+ "utf8",
+ );
+
+ const mcpRes = await handleMcpRequest({
+ jsonrpc: "2.0",
+ id: 7,
+ method: "tools/call",
+ params: {
+ name: "bla_harden",
+ arguments: { directory: root, intensity: "bankrupt" },
+ },
+ });
+ expect(mcpRes?.result).toBeDefined();
+ const structured = (mcpRes!.result as { structuredContent: { overallSuccess: boolean; hardenedCount: number; discoveredCount: number } }).structuredContent;
+ expect(structured.discoveredCount).toBeGreaterThanOrEqual(1);
+ expect(structured.hardenedCount).toBe(structured.discoveredCount);
+ expect(structured.overallSuccess).toBe(true);
+
+ const promptRes = await handleMcpRequest({
+ jsonrpc: "2.0",
+ id: 8,
+ method: "prompts/get",
+ params: {
+ name: "bla-harden-project",
+ arguments: { directory: "." },
+ },
+ });
+ const messages = (promptRes!.result as { messages: Array<{ content: { text: string } }> }).messages;
+ expect(messages[0]!.content.text).toContain("bla_harden");
+
+ const log: string[] = [];
+ const originalLog = console.log;
+ console.log = (...args: unknown[]) => {
+ log.push(args.map(String).join(" "));
+ };
+ try {
+ const code = await runCli(["harden", root, "--json"]);
+ expect(code).toBe(0);
+ } finally {
+ console.log = originalLog;
+ }
+ const cliReport = JSON.parse(log.join("\n")) as {
+ overallSuccess: boolean;
+ hardenedCount: number;
+ };
+ expect(cliReport.overallSuccess).toBe(true);
+ expect(cliReport.hardenedCount).toBeGreaterThanOrEqual(1);
+ });
+
+ it("hardens DEX members inside an unsigned APK-shaped ZIP discovered under release/", () => {
+ const root = createTempDir();
+ const release = join(root, "release");
+ mkdirSync(release, { recursive: true });
+ const apk = writeZipArchive([
+ { name: "AndroidManifest.xml", data: Buffer.from("<manifest package='com.demo'/>") },
+ { name: "classes.dex", data: minimalDex() },
+ ]);
+ writeFileSync(join(release, "app-unsigned.apk"), apk);
+
+ const report = hardenProject({
+ directory: root,
+ intensity: "stealth",
+ seed: "apk-discover",
+ emitManifest: false,
+ });
+ expect(report.discoveredCount).toBeGreaterThanOrEqual(1);
+ const apkArtifact = report.artifacts.find((a) => a.format === "android-apk");
+ expect(apkArtifact).toBeDefined();
+ expect(apkArtifact!.success).toBe(true);
+ });
+});
diff --git a/tests/setup-mcp-doctor-release.test.ts b/tests/setup-mcp-doctor-release.test.ts
index 3bdb718..ff960ee 100644
--- a/tests/setup-mcp-doctor-release.test.ts
+++ b/tests/setup-mcp-doctor-release.test.ts
@@ -516,13 +516,17 @@ describe("Issue #10: MCP Runtime Argument Validation, Prompts Contract & Subproc
expect(prompts.length).toBeGreaterThanOrEqual(1);
for (const p of prompts) {
+ const isHarden = p.name === "bla-harden-project";
+ const args = isHarden
+ ? { directory: "./dist" }
+ : { target_path: "./dist/app.js" };
const getRes = await handleMcpRequest({
jsonrpc: "2.0",
id: 2,
method: "prompts/get",
params: {
name: p.name,
- arguments: { target_path: "./dist/app.js" },
+ arguments: args,
},
});
expect(getRes?.error).toBeUndefined();
@@ -531,9 +535,14 @@ describe("Issue #10: MCP Runtime Argument Validation, Prompts Contract & Subproc
messages: Array<{ role: string; content: { type: string; text: string } }>;
};
expect(result.messages.length).toBeGreaterThan(0);
- expect(result.messages[0]?.content.text).toContain("./dist/app.js");
+ if (isHarden) {
+ expect(result.messages[0]?.content.text).toContain("bla_harden");
+ expect(result.messages[0]?.content.text).toContain("./dist");
+ } else {
+ expect(result.messages[0]?.content.text).toContain("./dist/app.js");
+ }
- // Missing target_path must return -32602
+ // Missing required args must return -32602; optional-only prompts succeed.
const badRes = await handleMcpRequest({
jsonrpc: "2.0",
id: 3,
@@ -543,7 +552,11 @@ describe("Issue #10: MCP Runtime Argument Validation, Prompts Contract & Subproc
arguments: {},
},
});
- expect(badRes?.error?.code).toBe(-32602);
+ if (p.arguments.some((a) => a.required)) {
+ expect(badRes?.error?.code).toBe(-32602);
+ } else {
+ expect(badRes?.error).toBeUndefined();
+ }
}
});