🛡️ 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(lint-wasm-xor-mask-sidecar): refuse XOR-mask-beside-blob packs (red/blue r6)
qybaihef96928c364d6
diff --git a/.agents/skills/blind-llm-agents/SKILL.md b/.agents/skills/blind-llm-agents/SKILL.mdindex f110897..d75079a 100644--- a/.agents/skills/blind-llm-agents/SKILL.md+++ b/.agents/skills/blind-llm-agents/SKILL.md@@ -7,14 +7,14 @@ description: >Agents). Prefer this skill as the guide; call existing MCP tools / CLI — do not inventnew MCP tools. Default verb: bla_harden. Refuse crack/RE of third-party software.metadata:- version: "1.5.9"+ version: "1.5.10"---# BLA: Blind LLM Agents**This skill is the primary one-click harden GUIDE.** MCP (`bla` server) and the`bla-agents` CLI are the **execution layer**. Prefer teaching/calling existing tools-(`bla_harden`, `bla_defend`, `bla_weave_plan`, `bla_lint_lanes`, `bla_lint_seal`, `bla_lint_wasm_params`, `bla_lint_panel_derive`, `bla_lint_js_aes_unwrap`, `bla_lint_js_wasm_hydrate_dump`, …) over inventing new+(`bla_harden`, `bla_defend`, `bla_weave_plan`, `bla_lint_lanes`, `bla_lint_seal`, `bla_lint_wasm_params`, `bla_lint_panel_derive`, `bla_lint_js_aes_unwrap`, `bla_lint_js_wasm_hydrate_dump`, `bla_lint_wasm_xor_mask_sidecar`, …) over inventing newMCP surfaces.Use BLA whenever the user asks to harden a project against AI reverse-engineering@@ -24,7 +24,7 @@ model misjudgment on proprietary logic, or **one-click / 一键加固** a build.Defensive only: protect **their own** artifacts. Refuse crack, RE, bypass PoCs, orattack playbooks against software they do not own.-**Principles (red-blue round-1+2+3+4+5+6):** do not ship a stable public WASM ABI without an explicit `wasm_preserve_exports` list; do not leave JS-side independent lane tables — prefer whole-key chained mixing (`bla_lint_lanes` / harden refuse). **Do not** place plaintext seal/catalog JSON (`revision`, salts, certificate ciphertext) beside hardened outputs. Public compare targets must be **one-way** (SHA-256/HMAC/etc.); reversible ARX/Feistel digests as public `revision` are a key-recovery footgun (round-2 break — **closed in round-3** when seal is digests-only). Enforce with `bla_lint_seal` / `bla lint-seal`; bankrupt harden **refuses** unless `allow_plaintext_seal` / `--allow-plaintext-seal`. Round-3 residual **gates**: `bla_lint_wasm_params` / `bla lint-wasm-params` — bankrupt refuses clear `R2SEAL`/`R3PARM`/`R3CIPH`-class carriers unless `allow_wasm_clear_params`; `bla_lint_panel_derive` — maximum/bankrupt **rewrites** `__vaultPanelDerive_*` to `_blaPd_*` unless `allow_stable_panel_derive`; bankrupt harden sets `selfSealRecommended` for multi-artifact trees (never auto for single-file) — prefer **`self_seal`**. Round-4 gates: `bla_lint_js_aes_unwrap` / `bla lint-js-aes-unwrap` — bankrupt **refuses** JS wrap-key + `create*iv` + fixed sealed hdr (e.g. `d17ea004`) unless `allow_js_aes_unwrap` (gate only — **not** white-box AES; prefer in-WASM unwrap). `bla_lint_panel_derive` flags `deriveLocal` (rewritten to `_blaPdLocal_*`) and **refuses** `deriveLocal` + plaintext `panelTokenSha256` offline-oracle packaging unless `allow_panel_offline_oracle` (rename is not a crypto fix — scrub digests / avoid derive UI). `self_seal` embeds **expected sibling SHA-256 hard-fail** when siblings exist at protect time (harden processes JS last); opaque-seed entanglement alone does **not** gate entitlement control flow. Round-5 gates: `bla_lint_js_wasm_hydrate_dump` / `bla lint-js-wasm-hydrate-dump` — bankrupt **refuses** JS that copies salt/rounds/cipher from `WebAssembly.Memory` after hydrate/instantiate unless `allow_js_wasm_hydrate_dump` (host memory dump needs **no** Node `create*iv`; export rename alone does not close this — prefer keep ARX+certify **inside** WASM so params never re-enter JS). Round-6 product pattern: export `unlock(keyPtr,keyLen)->outLen` (or equivalent) so ARX+compare+decrypt stay in WASM; JS only writes key bytes and reads the result — do **not** call hydrate then decode salt/rounds/cipher in JS (closes the round-5 host memory-dump residual under bankrupt defaults). Honesty: WASM reverse-engineering of the unlock body remains a theoretical surface; gates do not claim white-box secrecy.+**Principles (red-blue round-1+2+3+4+5+6):** do not ship a stable public WASM ABI without an explicit `wasm_preserve_exports` list; do not leave JS-side independent lane tables — prefer whole-key chained mixing (`bla_lint_lanes` / harden refuse). **Do not** place plaintext seal/catalog JSON (`revision`, salts, certificate ciphertext) beside hardened outputs. Public compare targets must be **one-way** (SHA-256/HMAC/etc.); reversible ARX/Feistel digests as public `revision` are a key-recovery footgun (round-2 break — **closed in round-3** when seal is digests-only). Enforce with `bla_lint_seal` / `bla lint-seal`; bankrupt harden **refuses** unless `allow_plaintext_seal` / `--allow-plaintext-seal`. Round-3 residual **gates**: `bla_lint_wasm_params` / `bla lint-wasm-params` — bankrupt refuses clear `R2SEAL`/`R3PARM`/`R3CIPH`-class carriers unless `allow_wasm_clear_params`; `bla_lint_panel_derive` — maximum/bankrupt **rewrites** `__vaultPanelDerive_*` to `_blaPd_*` unless `allow_stable_panel_derive`; bankrupt harden sets `selfSealRecommended` for multi-artifact trees (never auto for single-file) — prefer **`self_seal`**. Round-4 gates: `bla_lint_js_aes_unwrap` / `bla lint-js-aes-unwrap` — bankrupt **refuses** JS wrap-key + `create*iv` + fixed sealed hdr (e.g. `d17ea004`) unless `allow_js_aes_unwrap` (gate only — **not** white-box AES; prefer in-WASM unwrap). `bla_lint_panel_derive` flags `deriveLocal` (rewritten to `_blaPdLocal_*`) and **refuses** `deriveLocal` + plaintext `panelTokenSha256` offline-oracle packaging unless `allow_panel_offline_oracle` (rename is not a crypto fix — scrub digests / avoid derive UI). `self_seal` embeds **expected sibling SHA-256 hard-fail** when siblings exist at protect time (harden processes JS last); opaque-seed entanglement alone does **not** gate entitlement control flow. Round-5 gates: `bla_lint_js_wasm_hydrate_dump` / `bla lint-js-wasm-hydrate-dump` — bankrupt **refuses** JS that copies salt/rounds/cipher from `WebAssembly.Memory` after hydrate/instantiate unless `allow_js_wasm_hydrate_dump` (host memory dump needs **no** Node `create*iv`; export rename alone does not close this — prefer keep ARX+certify **inside** WASM so params never re-enter JS). Round-6 product pattern: export `unlock(keyPtr,keyLen)->outLen` (or equivalent) so ARX+compare+decrypt stay in WASM; JS only writes key bytes and reads the result — do **not** call hydrate then decode salt/rounds/cipher in JS (closes the round-5 host memory-dump residual under bankrupt defaults). Honesty: WASM reverse-engineering of the unlock body remains a theoretical surface; gates do not claim white-box secrecy. Round-6 **break residual**: do **not** store a plaintext XOR mask adjacent to a masked entitlement pack (`salt||rounds||expected-words||cipher`) in WASM data — static unmask needs no key; combined with invertible ARX expected-state compare this recovers the prize (`bla_lint_wasm_xor_mask_sidecar` / `bla lint-wasm-xor-mask-sidecar`; bankrupt refuses unless `allow_wasm_xor_mask_sidecar`). Prefer key-dependent unmask and **one-way** commitments inside WASM (not reversible expected words).## Prerequisites (once)diff --git a/docs/cli-and-mcp.md b/docs/cli-and-mcp.mdindex 345bdbe..6858085 100644--- a/docs/cli-and-mcp.md+++ b/docs/cli-and-mcp.md@@ -32,6 +32,7 @@ For coding agents, the **[`blind-llm-agents` skill](../.agents/skills/blind-llm-- `bla_lint_panel_derive`: Read-only panel-derive ABI lint (`path`) — stable `__vaultPanelDerive_*` / `deriveLocal` / `panelTokenSha256` oracle; same engine as CLI `bla lint-panel-derive`.- `bla_lint_js_aes_unwrap`: Read-only JS AES wrap-key unwrap lint (`path`) — wrap-key + create*iv + fixed hdr; same engine as CLI `bla lint-js-aes-unwrap`. Gate only — not white-box AES.- `bla_lint_js_wasm_hydrate_dump`: Read-only JS←WASM hydrate param-dump lint (`path`) — memory.buffer + salt/rounds/cipher after hydrate; same engine as CLI `bla lint-js-wasm-hydrate-dump`. Prefer in-WASM ARX+certify.+- `bla_lint_wasm_xor_mask_sidecar`: Read-only WASM XOR-mask sidecar lint (`path`) — masked entitlement pack beside plaintext 32-byte mask in WASM data; bankrupt refuses unless `allow_wasm_xor_mask_sidecar`.- `bla_run_lookup`: Read-only harden-run correlation (`summary_path`, optional `run_id`). Summaries are **unsigned**; missing/mismatched id is an error.- `bla_rea_drift`: Thin wrapper over `npm run verify:rea` / `scripts/verify-rea-constants.mjs`. Absent sibling REA → `status: unverified` (not red-team evidence).- `bla_redteam_report`: Read (or `execute:true` re-run) `docs/redteam/empirical-rea-validation.json`. On-disk read → `status: available` (not a live REA verdict); `execute:true` → `pass`/`fail`; missing report / unready REA → `status: unverified`.diff --git a/src/cli.ts b/src/cli.tsindex d8d136c..4d29514 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -17,6 +17,7 @@ import { lintWasmParamCarrierFile } from "./engine/wasm-param-carrier-lint.js";import { lintPanelDeriveAbiFile } from "./engine/panel-derive-abi-lint.js";import { lintJsAesUnwrapFile } from "./engine/js-aes-unwrap-lint.js";import { lintJsWasmHydrateDumpFile } from "./engine/js-wasm-hydrate-dump-lint.js";+import { lintWasmXorMaskSidecarFile } from "./engine/wasm-xor-mask-sidecar-lint.js";import { runShowcaseBenchmark } from "./engine/benchmark.js";import {emitCompileTimeNativeHeader,@@ -61,6 +62,7 @@ Commands:lint-panel-derive <file> Heuristic ERROR if stable __vaultPanelDerive_* / deriveLocal oracle remains; exit 2lint-js-aes-unwrap <file> Heuristic ERROR if JS AES wrap-key + create*iv + fixed hdr unwrap; exit 2lint-js-wasm-hydrate-dump <file> Heuristic ERROR if JS dumps WASM hydrate salt/rounds/cipher; exit 2+ lint-wasm-xor-mask-sidecar <file> Heuristic ERROR if WASM data has XOR-mask beside masked entitlement pack; exit 2lint-seal <file> Heuristic lint for plaintext/reversible seal sidecars (red-blue round-2); exit 2 on errorprotect <target> Inject multi-layer Counter-REA adversarial shieldverify <target> [original] Verify Counter-REA defense invariants & token amplification@@ -85,6 +87,7 @@ Options:--allow-lane-independent Allow harden/defend of lane-independent JS gates (issue #40.1); OFF by default--allow-plaintext-seal Allow bankrupt harden despite plaintext/reversible seal JSON (round-2); OFF by default--allow-js-wasm-hydrate-dump Allow bankrupt despite JS←WASM hydrate param-dump (round-5); OFF by default+ --allow-wasm-xor-mask-sidecar Allow bankrupt despite WASM XOR-mask-beside-blob packs (round-6); OFF by default--lang <c|rust|go> Target language for emit-headers (default: c)--client <id> Agent client ID for setup (repeatable: claude_code, cursor, codex, etc.)--all-detected Configure all detected coding agents on this machine@@ -116,6 +119,7 @@ interface ParsedCliArgs {readonly allowJsAesUnwrap: boolean;readonly allowPanelOfflineOracle: boolean;readonly allowJsWasmHydrateDump: boolean;+ readonly allowWasmXorMaskSidecar: boolean;readonly lang: NativeHeaderLanguage;readonly clients: SupportedAgentClientId[];readonly allDetected: boolean;@@ -148,6 +152,7 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {let allowStablePanelDeriveAbi = false;let allowJsAesUnwrap = false;let allowJsWasmHydrateDump = false;+ let allowWasmXorMaskSidecar = false;let allowPanelOfflineOracle = false;let lang: NativeHeaderLanguage = "c";const clients: SupportedAgentClientId[] = [];@@ -203,6 +208,8 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {allowPanelOfflineOracle = true;} else if (arg === "--allow-js-wasm-hydrate-dump") {allowJsWasmHydrateDump = true;+ } else if (arg === "--allow-wasm-xor-mask-sidecar") {+ allowWasmXorMaskSidecar = true;} else if (arg.startsWith("--wasm-preserve-exports=")) {wasmPreserveExports = arg.slice("--wasm-preserve-exports=".length)@@ -265,6 +272,7 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {allowJsAesUnwrap,allowPanelOfflineOracle,allowJsWasmHydrateDump,+ allowWasmXorMaskSidecar,lang,clients,allDetected,@@ -417,6 +425,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): PallowJsWasmHydrateDump:parsed.allowJsWasmHydrateDump ||loaded.config.allowJsWasmHydrateDump === true,+ allowWasmXorMaskSidecar:+ parsed.allowWasmXorMaskSidecar ||+ loaded.config.allowWasmXorMaskSidecar === true,...(parsed.output !== undefined ? { outputDirectory: parsed.output } : {}),});if (parsed.json) {@@ -478,6 +489,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): PallowJsWasmHydrateDump:parsed.allowJsWasmHydrateDump ||loaded.config.allowJsWasmHydrateDump === true,+ allowWasmXorMaskSidecar:+ parsed.allowWasmXorMaskSidecar ||+ loaded.config.allowWasmXorMaskSidecar === true,});if (parsed.sarif) {console.log(@@ -641,6 +655,30 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P? 2: 0;}+ case "lint-wasm-xor-mask-sidecar": {+ const target = parsed.positionals[0];+ if (!target) {+ console.error("Error: Missing <file> path for `bla lint-wasm-xor-mask-sidecar <file>`.");+ return 1;+ }+ const report = lintWasmXorMaskSidecarFile(resolve(target));+ if (parsed.json) {+ console.log(JSON.stringify(report, null, 2));+ } else {+ console.log(`BLA wasm-xor-mask-sidecar lint — ${report.path}`);+ console.log(report.oneLineAdvice);+ for (const f of report.findings) {+ console.log(` [${f.severity}] ${f.id}: ${f.summary}`);+ if (f.evidence) console.log(` evidence: ${f.evidence}`);+ }+ if (report.findings.length === 0) {+ console.log(" (no findings)");+ }+ }+ return report.shouldRefuseBankrupt || report.findings.some((f) => f.severity === "error")+ ? 2+ : 0;+ }case "audit": {const loaded = loadBlaConfig(process.cwd(), parsed.configPath);@@ -709,6 +747,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): PallowJsWasmHydrateDump:parsed.allowJsWasmHydrateDump ||loaded.config.allowJsWasmHydrateDump === true,+ allowWasmXorMaskSidecar:+ parsed.allowWasmXorMaskSidecar ||+ loaded.config.allowWasmXorMaskSidecar === true,});if (parsed.json) console.log(JSON.stringify(res, null, 2));else console.log(formatProtectionResult(res));diff --git a/src/core/config.ts b/src/core/config.tsindex 1c139cf..b4294bf 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -36,6 +36,7 @@ export interface BlaProjectConfig {readonly allowPanelOfflineOracle?: boolean;/** When true, allow bankrupt despite JS←WASM hydrate param-dump (red-blue round-5). Default false. */readonly allowJsWasmHydrateDump?: boolean;+ readonly allowWasmXorMaskSidecar?: boolean;}/**diff --git a/src/core/types.ts b/src/core/types.tsindex e38b2be..79b2734 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -211,6 +211,8 @@ export interface ProtectionOptions {* dumps of salt/rounds/cipher (red-blue round-5). Default false — refuse.*/readonly allowJsWasmHydrateDump?: boolean;+ /** Red/blue round-6: allow WASM XOR-mask-beside-blob entitlement packs under bankrupt/maximum. */+ readonly allowWasmXorMaskSidecar?: boolean;/*** Optional sibling paths for self-seal when `selfSeal` is true (multi-artifact harden).* Relative paths are resolved from the protected module's directory at runtime.diff --git a/src/engine/auditor.ts b/src/engine/auditor.tsindex b75eacf..cea0572 100644--- a/src/engine/auditor.ts+++ b/src/engine/auditor.ts@@ -19,6 +19,7 @@ import { lintWasmParamCarrierBuffer } from "./wasm-param-carrier-lint.js";import { lintPanelDeriveAbiSource } from "./panel-derive-abi-lint.js";import { lintJsAesUnwrapSource } from "./js-aes-unwrap-lint.js";import { lintJsWasmHydrateDumpSource } from "./js-wasm-hydrate-dump-lint.js";+import { lintWasmXorMaskSidecarBuffer } from "./wasm-xor-mask-sidecar-lint.js";import { inspectPythonPyc } from "../shields/formats/python.js";import { inspectNativeBinary } from "../shields/formats/native.js";import { detectBunStandaloneGraph } from "../shields/formats/bun-standalone.js";@@ -707,6 +708,20 @@ export function auditTarget(targetPath: string): AuditReport {reason: f.summary,});}+ const xorMaskLint = lintWasmXorMaskSidecarBuffer(rawBytes, { path: absPath });+ for (const f of xorMaskLint.findings) {+ exposedItems.push({+ id: `wasm_xor_mask_${f.id}_${f.offset}`,+ name: f.id,+ kind: "metadata-section",+ location: `${basename(absPath)} (data @${f.offset})`,+ riskLevel: "high",+ reaToolUsed: "bla lint-wasm-xor-mask-sidecar / static data-section scan",+ estimatedTokensToReconstruct: 6_000,+ estimatedCostUsd: 0.3,+ reason: f.summary,+ });+ }sim = {...sim,examinationStatus: isProtected ? "limited" : "complete",diff --git a/src/engine/defender.ts b/src/engine/defender.tsindex 39acbef..ca2e943 100644--- a/src/engine/defender.ts+++ b/src/engine/defender.ts@@ -43,6 +43,7 @@ export interface OneClickDefenseOptions {readonly allowPanelOfflineOracle?: boolean;/** Allow bankrupt despite JS←WASM hydrate param-dump (red-blue round-5). Default false. */readonly allowJsWasmHydrateDump?: boolean;+ readonly allowWasmXorMaskSidecar?: boolean;/** Sibling paths forwarded into self-seal when enabled (multi-artifact harden). */readonly selfSealSiblingPaths?: readonly string[];}@@ -153,6 +154,9 @@ export function defendTarget(options: OneClickDefenseOptions): OneClickDefenseRe...(options.allowJsWasmHydrateDump === true? { allowJsWasmHydrateDump: true }: {}),+ ...(options.allowWasmXorMaskSidecar === true+ ? { allowWasmXorMaskSidecar: true }+ : {}),...(options.selfSealSiblingPaths !== undefined &&options.selfSealSiblingPaths.length > 0? { selfSealSiblingPaths: options.selfSealSiblingPaths }diff --git a/src/engine/harden.ts b/src/engine/harden.tsindex c5b3ecf..8a19cdd 100644--- a/src/engine/harden.ts+++ b/src/engine/harden.ts@@ -33,6 +33,11 @@ import {intensityEnforcesJsWasmHydrateDumpRefusal,jsWasmHydrateDumpRefuseMessage,} from "./js-wasm-hydrate-dump-lint.js";+import {+ discoverAndLintWasmXorMaskSidecars,+ intensityEnforcesWasmXorMaskSidecarRefusal,+ wasmXorMaskSidecarRefuseMessage,+} from "./wasm-xor-mask-sidecar-lint.js";import {computeHardenRunId,HARDEN_SUMMARY_FILE_NAME,@@ -135,6 +140,7 @@ export interface HardenProjectOptions {readonly allowJsAesUnwrap?: boolean;/** Lab-only: allow JS←WASM hydrate memory dump of salt/rounds/cipher (red/blue r5). */readonly allowJsWasmHydrateDump?: boolean;+ readonly allowWasmXorMaskSidecar?: boolean;/** Allow bankrupt despite panel offline-oracle packaging (red-blue round-4). Default false. */readonly allowPanelOfflineOracle?: boolean;/** Optional output root; defaults to `<dir>/.bla-hardened`. */@@ -392,6 +398,12 @@ export function hardenProject(options.allowJsWasmHydrateDump !== true? jsHydrateDumpReports.filter((r) => r.shouldRefuseBankrupt): [];+ const wasmXorMaskReports = discoverAndLintWasmXorMaskSidecars(absDir);+ const blockingWasmXorMask =+ intensityEnforcesWasmXorMaskSidecarRefusal(intensity) &&+ options.allowWasmXorMaskSidecar !== true+ ? wasmXorMaskReports.filter((r) => r.shouldRefuseBankrupt)+ : [];const outputRoot = resolve(options.outputDirectory ??(statSync(absDir).isDirectory()@@ -458,7 +470,7 @@ export function hardenProject(runId,} as const;- if (blockingSeals.length > 0 || blockingWasmParms.length > 0 || blockingJsAes.length > 0 || blockingJsHydrateDump.length > 0) {+ if (blockingSeals.length > 0 || blockingWasmParms.length > 0 || blockingJsAes.length > 0 || blockingJsHydrateDump.length > 0 || blockingWasmXorMask.length > 0) {const sealArtifacts = blockingSeals.map((r) => ({inputPath: r.path,relativePath: (relative(absDir, r.path) || basename(r.path)).split(sep).join("/"),@@ -507,13 +519,26 @@ export function hardenProject(outputExisted: false,error: jsWasmHydrateDumpRefuseMessage(r, r.path),}));+ const wasmXorMaskArtifacts = blockingWasmXorMask.map((r) => ({+ inputPath: r.path,+ relativePath: (relative(absDir, r.path) || basename(r.path)).split(sep).join("/"),+ format: "wasm" as const,+ outputPath: r.path,+ success: false,+ defenseScore: 0,+ tokenAmplificationFactor: 0,+ costAmplificationFactor: 0,+ outputExisted: false,+ error: wasmXorMaskSidecarRefuseMessage(r, r.path),+ }));const blockParts: string[] = [];if (blockingSeals.length > 0) blockParts.push("plaintext/reversible seal sidecar");if (blockingWasmParms.length > 0) blockParts.push("clear WASM param carrier");if (blockingJsAes.length > 0) blockParts.push("JS AES wrap-key unwrap");if (blockingJsHydrateDump.length > 0) blockParts.push("JS WASM hydrate param-dump");+ if (blockingWasmXorMask.length > 0) blockParts.push("WASM XOR-mask sidecar");const blockReason = `skipped: ${blockParts.join(" / ")} blocked bankrupt harden`;- const blockedExtras = [...sealArtifacts, ...wasmArtifacts, ...jsAesArtifacts, ...jsHydrateDumpArtifacts];+ const blockedExtras = [...sealArtifacts, ...wasmArtifacts, ...jsAesArtifacts, ...jsHydrateDumpArtifacts, ...wasmXorMaskArtifacts];return {...reportBase,overallSuccess: false,@@ -596,6 +621,7 @@ export function hardenProject(: {}),...(options.allowJsAesUnwrap === true ? { allowJsAesUnwrap: true } : {}),...(options.allowJsWasmHydrateDump === true ? { allowJsWasmHydrateDump: true } : {}),+ ...(options.allowWasmXorMaskSidecar === true ? { allowWasmXorMaskSidecar: true } : {}),...(options.allowPanelOfflineOracle === true? { allowPanelOfflineOracle: true }: {}),diff --git a/src/engine/protector.ts b/src/engine/protector.tsindex 8818bb7..48696fb 100644--- a/src/engine/protector.ts+++ b/src/engine/protector.ts@@ -62,6 +62,11 @@ import {lintWasmParamCarrierBuffer,wasmParamCarrierRefuseMessage,} from "./wasm-param-carrier-lint.js";+import {+ lintWasmXorMaskSidecarBuffer,+ intensityEnforcesWasmXorMaskSidecarRefusal,+ wasmXorMaskSidecarRefuseMessage,+} from "./wasm-xor-mask-sidecar-lint.js";import {intensityEnforcesPanelOracleRefusal,intensityRewritesPanelDerive,@@ -595,6 +600,15 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {throw new Error(wasmParamCarrierRefuseMessage(wasmParm, absInput));}}+ if (+ intensityEnforcesWasmXorMaskSidecarRefusal(intensity) &&+ options.allowWasmXorMaskSidecar !== true+ ) {+ const xorMask = lintWasmXorMaskSidecarBuffer(rawWasm, { path: absInput });+ if (xorMask.shouldRefuseBankrupt) {+ throw new Error(wasmXorMaskSidecarRefuseMessage(xorMask, absInput));+ }+ }const res = protectWasmBinary(rawWasm, {intensity,seed,diff --git a/src/engine/wasm-xor-mask-sidecar-lint.ts b/src/engine/wasm-xor-mask-sidecar-lint.tsnew file mode 100644index 0000000..492e331--- /dev/null+++ b/src/engine/wasm-xor-mask-sidecar-lint.ts@@ -0,0 +1,437 @@+/**+ * WASM XOR-mask sidecar lint (red-blue round-6 residual).+ *+ * Detects entitlement packs stored as `masked_blob || plaintext_mask` in a+ * WASM data section (or initialized linear memory). Hosts can XOR-unmask+ * salt/rounds/expected-words/cipher with **no** key and **no** export call —+ * bankrupt export rename does not help. Round-6 red recovered the prize by+ * combining this static unpack with an invertible ARX expected-state compare.+ *+ * Bankrupt harden/protect refuses error findings unless+ * `allowWasmXorMaskSidecar` / `--allow-wasm-xor-mask-sidecar` /+ * `allow_wasm_xor_mask_sidecar`.+ *+ * DEFENSIVE ONLY — prefer key-dependent unmask, omit plaintext masks from the+ * binary, and one-way commitments instead of reversible expected words.+ */++import { createHash, randomBytes } from "node:crypto";+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { basename, join, resolve } from "node:path";++export const WASM_XOR_MASK_SIDECAR_SCHEMA = "bla-wasm-xor-mask-sidecar-lint/v1" as const;++export type WasmXorMaskSidecarFindingId =+ | "wasm-xor-mask-sidecar"+ | "wasm-xor-mask-entitlement-pack";++export type WasmXorMaskSidecarSeverity = "warning" | "error";++export interface WasmXorMaskSidecarFinding {+ readonly id: WasmXorMaskSidecarFindingId;+ readonly severity: WasmXorMaskSidecarSeverity;+ readonly summary: string;+ readonly evidence: string;+ readonly offset: number;+ readonly blobLen: number;+ readonly maskLen: number;+}++export interface WasmXorMaskSidecarReport {+ readonly schema: typeof WASM_XOR_MASK_SIDECAR_SCHEMA;+ readonly path: string;+ readonly sha256Prefix: string;+ readonly findings: readonly WasmXorMaskSidecarFinding[];+ readonly looksExposed: boolean;+ /** True when bankrupt harden/protect should refuse (error findings). */+ readonly shouldRefuseBankrupt: boolean;+ readonly oneLineAdvice: string;+}++const WASM_MAGIC = Buffer.from([0x00, 0x61, 0x73, 0x6d]);++const SKIP_DIR_NAMES = new Set([+ "node_modules",+ ".git",+ ".hg",+ ".svn",+ ".bla-hardened",+ "coverage",+ ".next",+ ".turbo",+ "vendor",+ "__pycache__",+]);++const MAX_WALK_DEPTH = 6;+const MAX_WASM_FILES = 32;+const MAX_SCAN_BYTES = 32 * 1024 * 1024;+const MASK_LEN = 32;+const MIN_BLOB = 40;+const MAX_BLOB = 120;++function finding(+ id: WasmXorMaskSidecarFindingId,+ severity: WasmXorMaskSidecarSeverity,+ summary: string,+ evidence: string,+ offset: number,+ blobLen: number,+ maskLen: number,+): WasmXorMaskSidecarFinding {+ return {+ id,+ severity,+ summary,+ evidence: evidence.slice(0, 200),+ offset,+ blobLen,+ maskLen,+ };+}++function emptyReport(pathLabel: string, sha256Prefix: string, advice: string): WasmXorMaskSidecarReport {+ return {+ schema: WASM_XOR_MASK_SIDECAR_SCHEMA,+ path: pathLabel,+ sha256Prefix,+ findings: [],+ looksExposed: false,+ shouldRefuseBankrupt: false,+ oneLineAdvice: advice,+ };+}++function readUleb(buf: Buffer, off: number): [number, number] {+ let r = 0;+ let s = 0;+ let b = 0;+ let o = off;+ do {+ if (o >= buf.length) throw new Error("uleb truncated");+ b = buf[o++]!;+ r |= (b & 0x7f) << s;+ s += 7;+ } while (b & 0x80);+ return [r >>> 0, o];+}++function readI32Leb(buf: Buffer, off: number): [number, number] {+ let r = 0;+ let s = 0;+ let b = 0;+ let o = off;+ do {+ if (o >= buf.length) throw new Error("ileb truncated");+ b = buf[o++]!;+ r |= (b & 0x7f) << s;+ s += 7;+ } while (b & 0x80);+ if (s < 32 && (b & 0x40)) r |= (~0 << s);+ return [r | 0, o];+}++function uleb(v: number): number[] {+ const out: number[] = [];+ v >>>= 0;+ do {+ let b = v & 0x7f;+ v >>>= 7;+ if (v) b |= 0x80;+ out.push(b);+ } while (v);+ return out;+}++function iconst(v: number): number[] {+ v |= 0;+ const out = [0x41];+ while (true) {+ let b = v & 0x7f;+ v >>= 7;+ if ((v === 0 && (b & 0x40) === 0) || (v === -1 && (b & 0x40) !== 0)) {+ out.push(b);+ break;+ }+ out.push(b | 0x80);+ }+ return out;+}++function section(id: number, body: number[]): number[] {+ return [id, ...uleb(body.length), ...body];+}++/** Extract active data-segment payloads (mem0) from a WASM binary. */+export function extractWasmDataPayloads(buffer: Buffer): Array<{ memOff: number; payload: Buffer }> {+ const out: Array<{ memOff: number; payload: Buffer }> = [];+ if (buffer.length < 8 || !buffer.subarray(0, 4).equals(WASM_MAGIC)) return out;+ let off = 8;+ while (off < buffer.length) {+ const id = buffer[off++]!;+ let size = 0;+ try {+ [size, off] = readUleb(buffer, off);+ } catch {+ break;+ }+ const start = off;+ const end = off + size;+ if (end > buffer.length) break;+ if (id === 11) {+ let p = start;+ try {+ let count = 0;+ [count, p] = readUleb(buffer, p);+ for (let i = 0; i < count; i++) {+ if (p >= end) break;+ const flags = buffer[p++]!;+ let memOff = 0;+ if (flags === 0 || flags === 2) {+ if (flags === 2) {+ // memory index+ let _memIdx = 0;+ [_memIdx, p] = readUleb(buffer, p);+ }+ if (buffer[p] === 0x41) {+ p++;+ [memOff, p] = readI32Leb(buffer, p);+ if (buffer[p] === 0x0b) p++;+ } else {+ while (p < end && buffer[p] !== 0x0b) p++;+ if (p < end) p++;+ }+ } else {+ // passive / declarative — skip body length only+ let dlen = 0;+ [dlen, p] = readUleb(buffer, p);+ p += dlen;+ continue;+ }+ let dlen = 0;+ [dlen, p] = readUleb(buffer, p);+ if (p + dlen > end) break;+ out.push({ memOff, payload: Buffer.from(buffer.subarray(p, p + dlen)) });+ p += dlen;+ }+ } catch {+ // ignore malformed data section+ }+ }+ off = end;+ }+ return out;+}++function maskEntropyOk(mask: Buffer): boolean {+ if (mask.length !== MASK_LEN) return false;+ if (mask.every((b) => b === 0)) return false;+ const first = mask[0]!;+ if (mask.every((b) => b === first)) return false;+ const seen = new Set(mask);+ return seen.size >= 8;+}++/**+ * True when `payload[base .. base+N) XOR payload[base+N .. base+N+32)` looks like+ * the round-3..6 entitlement pack: salt_i32le || rounds_u8 || pad3 || 4×i32 || clen_u16le || cipher.+ */+export function looksLikeXorMaskedEntitlementPack(+ payload: Buffer,+ base = 0,+): { ok: true; blobLen: number; rounds: number; clen: number; salt: number } | { ok: false } {+ for (let N = MIN_BLOB; N <= Math.min(MAX_BLOB, payload.length - base - MASK_LEN); N++) {+ const mask = payload.subarray(base + N, base + N + MASK_LEN);+ if (!maskEntropyOk(mask)) continue;+ const plain = Buffer.alloc(N);+ for (let i = 0; i < N; i++) plain[i] = payload[base + i]! ^ mask[i % MASK_LEN]!;+ if (plain[5] || plain[6] || plain[7]) continue;+ const rounds = plain[4]!;+ if (rounds < 8 || rounds > 200) continue;+ const clen = plain.readUInt16LE(24);+ if (clen < 8 || clen > 200) continue;+ if (26 + clen !== N) continue;+ const words = [8, 12, 16, 20].map((o) => plain.readInt32LE(o));+ const nonzero = words.filter((w) => w !== 0).length;+ if (nonzero < 2) continue;+ const salt = plain.readInt32LE(0);+ // cipher should look binary-ish+ let nonPrint = 0;+ for (let i = 26; i < N; i++) {+ const b = plain[i]!;+ if (b < 0x20 || b > 0x7e) nonPrint++;+ }+ if (nonPrint < Math.max(2, Math.floor(clen * 0.25))) continue;+ return { ok: true, blobLen: N, rounds, clen, salt };+ }+ return { ok: false };+}++export function lintWasmXorMaskSidecarBuffer(+ buffer: Buffer,+ options: { readonly path?: string } = {},+): WasmXorMaskSidecarReport {+ const pathLabel = options.path ?? "<memory>";+ const sha256Prefix = createHash("sha256").update(buffer).digest("hex").slice(0, 12);+ if (buffer.length < 8 || !buffer.subarray(0, 4).equals(WASM_MAGIC)) {+ return emptyReport(pathLabel, sha256Prefix, "Not a WASM module — XOR-mask sidecar lint skipped.");+ }+ if (buffer.length > MAX_SCAN_BYTES) {+ return emptyReport(pathLabel, sha256Prefix, "WASM too large for XOR-mask sidecar lint.");+ }++ const findings: WasmXorMaskSidecarFinding[] = [];+ const payloads = extractWasmDataPayloads(buffer);+ for (const { memOff, payload } of payloads) {+ // Scan a few bases inside the payload (data@0 is the common case).+ const bases = [0];+ if (payload.length > 256) bases.push(64, 128, 256);+ for (const base of bases) {+ if (base >= payload.length) continue;+ const hit = looksLikeXorMaskedEntitlementPack(payload, base);+ if (!hit.ok) continue;+ findings.push(+ finding(+ "wasm-xor-mask-entitlement-pack",+ "error",+ "WASM data section looks like XOR-masked entitlement pack with adjacent plaintext 32-byte mask — static unmask recovers salt/rounds/expected-words/cipher without a key.",+ `memOff=${memOff}+${base} blobLen=${hit.blobLen} rounds=${hit.rounds} clen=${hit.clen} salt=${hit.salt}`,+ memOff + base,+ hit.blobLen,+ MASK_LEN,+ ),+ );+ break;+ }+ }++ const looksExposed = findings.length > 0;+ const shouldRefuseBankrupt = findings.some((f) => f.severity === "error");+ const oneLineAdvice = shouldRefuseBankrupt+ ? "ERROR: Prefer key-dependent unmask / omit plaintext XOR masks from WASM data; use one-way commitments instead of reversible expected words. Harden refuses unless allowWasmXorMaskSidecar / --allow-wasm-xor-mask-sidecar / allow_wasm_xor_mask_sidecar."+ : "No XOR-mask-beside-blob entitlement pack detected in WASM data sections (heuristic).";++ return {+ schema: WASM_XOR_MASK_SIDECAR_SCHEMA,+ path: pathLabel,+ sha256Prefix,+ findings,+ looksExposed,+ shouldRefuseBankrupt,+ oneLineAdvice,+ };+}++export function lintWasmXorMaskSidecarFile(filePath: string): WasmXorMaskSidecarReport {+ const abs = resolve(filePath);+ if (!existsSync(abs) || !statSync(abs).isFile()) {+ return emptyReport(abs, "000000000000", `File not found: ${abs}`);+ }+ const buf = readFileSync(abs);+ return lintWasmXorMaskSidecarBuffer(buf, { path: abs });+}++export function intensityEnforcesWasmXorMaskSidecarRefusal(+ intensity: string | undefined,+): boolean {+ return intensity === "bankrupt" || intensity === "maximum";+}++export function wasmXorMaskSidecarRefuseMessage(+ report: WasmXorMaskSidecarReport,+ pathLabel?: string,+): string {+ const p = pathLabel ?? report.path;+ const ids = report.findings.map((f) => f.id).join(",");+ return `BLA refused bankrupt/maximum protect of ${p}: WASM XOR-mask sidecar entitlement pack (${ids || "exposed"}). Pass allowWasmXorMaskSidecar / --allow-wasm-xor-mask-sidecar / allow_wasm_xor_mask_sidecar to override. Prefer key-dependent unmask and one-way commitments (red/blue round-6).`;+}++function walkWasmFiles(root: string, out: string[], depth: number): void {+ if (out.length >= MAX_WASM_FILES || depth > MAX_WALK_DEPTH) return;+ let entries: string[] = [];+ try {+ entries = readdirSync(root);+ } catch {+ return;+ }+ for (const name of entries) {+ if (out.length >= MAX_WASM_FILES) break;+ if (SKIP_DIR_NAMES.has(name)) continue;+ const full = join(root, name);+ let st;+ try {+ st = statSync(full);+ } catch {+ continue;+ }+ if (st.isDirectory()) walkWasmFiles(full, out, depth + 1);+ else if (st.isFile() && /\.wasm$/i.test(name) && st.size <= MAX_SCAN_BYTES) out.push(full);+ }+}++export function discoverAndLintWasmXorMaskSidecars(directory: string): WasmXorMaskSidecarReport[] {+ const abs = resolve(directory);+ const files: string[] = [];+ if (existsSync(abs) && statSync(abs).isFile() && /\.wasm$/i.test(abs)) files.push(abs);+ else if (existsSync(abs) && statSync(abs).isDirectory()) walkWasmFiles(abs, files, 0);+ return files.map((f) => lintWasmXorMaskSidecarFile(f));+}++/**+ * Minimal WASM footgun fixture: data section = masked entitlement pack || 32-byte mask.+ * Used by unit / harden-gate tests (not a customer sample).+ */+export function buildTestWasmWithXorMaskSidecar(+ options: {+ readonly salt?: number;+ readonly rounds?: number;+ readonly words?: readonly [number, number, number, number];+ readonly cipher?: Buffer;+ readonly mask?: Buffer;+ } = {},+): Buffer {+ const salt = options.salt ?? 0x12345678;+ const rounds = options.rounds ?? 40;+ const words = options.words ?? [0x11111111, 0x22222222, 0x33333333, 0x44444444];+ const cipher = options.cipher ?? randomBytes(31);+ const mask = options.mask ?? randomBytes(32);+ if (mask.length !== 32) throw new Error("mask must be 32 bytes");+ const N = 26 + cipher.length;+ const plain = Buffer.alloc(N);+ plain.writeInt32LE(salt | 0, 0);+ plain[4] = rounds & 0xff;+ plain.writeInt32LE(words[0]!, 8);+ plain.writeInt32LE(words[1]!, 12);+ plain.writeInt32LE(words[2]!, 16);+ plain.writeInt32LE(words[3]!, 20);+ plain.writeUInt16LE(cipher.length, 24);+ cipher.copy(plain, 26);+ const masked = Buffer.alloc(N);+ for (let i = 0; i < N; i++) masked[i] = plain[i]! ^ mask[i % 32]!;+ const dataPayload = Buffer.concat([masked, mask]);++ const typeSec = section(1, [1, 0x60, 0, 0]);+ const funcSec = section(3, [1, 0]);+ const memSec = section(5, [1, 0, 1]);+ const exportSec = section(7, [1, ...uleb(3), 0x6e, 0x6f, 0x70, 0x00, 0]); // "nop"+ const codeSec = section(10, [1, 2, 0, 0x0b]); // empty function+ const dataSec = section(11, [+ 1,+ 0x00,+ ...iconst(0),+ 0x0b,+ ...uleb(dataPayload.length),+ ...dataPayload,+ ]);+ const bytes = Buffer.from([+ 0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0,+ ...typeSec,+ ...funcSec,+ ...memSec,+ ...exportSec,+ ...codeSec,+ ...dataSec,+ ]);+ if (!WebAssembly.validate(bytes)) throw new Error("test wasm invalid");+ return bytes;+}diff --git a/src/index.ts b/src/index.tsindex e677956..1488d36 100644--- a/src/index.ts+++ b/src/index.ts@@ -317,6 +317,19 @@ export {type WasmParamCarrierFindingId,type WasmParamCarrierSeverity,} from "./engine/wasm-param-carrier-lint.js";+export {+ lintWasmXorMaskSidecarBuffer,+ lintWasmXorMaskSidecarFile,+ discoverAndLintWasmXorMaskSidecars,+ buildTestWasmWithXorMaskSidecar,+ wasmXorMaskSidecarRefuseMessage,+ intensityEnforcesWasmXorMaskSidecarRefusal,+ WASM_XOR_MASK_SIDECAR_SCHEMA,+ type WasmXorMaskSidecarFinding,+ type WasmXorMaskSidecarReport,+ type WasmXorMaskSidecarFindingId,+ type WasmXorMaskSidecarSeverity,+} from "./engine/wasm-xor-mask-sidecar-lint.js";export {lintPanelDeriveAbiSource,lintPanelDeriveAbiFile,diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex a69d65e..b9a0eec 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -33,6 +33,10 @@ import {lintJsWasmHydrateDumpFile,type JsWasmHydrateDumpReport,} from "../engine/js-wasm-hydrate-dump-lint.js";+import {+ lintWasmXorMaskSidecarFile,+ type WasmXorMaskSidecarReport,+} from "../engine/wasm-xor-mask-sidecar-lint.js";import {computeArtifactRunId,readHardenRunSummary,@@ -211,6 +215,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([description:"Allow bankrupt harden/protect despite JS←WASM hydrate memory dumps of salt/rounds/cipher. Default false — refuse (red-blue round-5). Prefer in-WASM ARX+certify; gate only.",},+ allow_wasm_xor_mask_sidecar: {+ type: "boolean",+ description:+ "Allow bankrupt harden/protect despite WASM data-section XOR-mask-beside-blob entitlement packs. Default false — refuse (red-blue round-6). Prefer key-dependent unmask + one-way commitments.",+ },seed: {type: "string",description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc",@@ -336,6 +345,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([description:"Allow bankrupt harden/protect despite JS←WASM hydrate memory dumps of salt/rounds/cipher. Default false — refuse (red-blue round-5). Prefer in-WASM ARX+certify; gate only.",},+ allow_wasm_xor_mask_sidecar: {+ type: "boolean",+ description:+ "Allow bankrupt harden/protect despite WASM data-section XOR-mask-beside-blob entitlement packs. Default false — refuse (red-blue round-6). Prefer key-dependent unmask + one-way commitments.",+ },seed: {type: "string",description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc",@@ -442,6 +456,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([description:"Allow bankrupt harden/protect despite JS←WASM hydrate memory dumps of salt/rounds/cipher. Default false — refuse (red-blue round-5). Prefer in-WASM ARX+certify; gate only.",},+ allow_wasm_xor_mask_sidecar: {+ type: "boolean",+ description:+ "Allow bankrupt harden/protect despite WASM data-section XOR-mask-beside-blob entitlement packs. Default false — refuse (red-blue round-6). Prefer key-dependent unmask + one-way commitments.",+ },seed: {type: "string",description: "Optional deterministic seed; when omitted, BLA mints an ephemeral random seed (prefer project .blarc via CLI)",@@ -721,6 +740,22 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([additionalProperties: false,},},+ {+ name: "bla_lint_wasm_xor_mask_sidecar",+ description:+ "Read-only WASM XOR-mask sidecar lint (same engine as CLI `bla lint-wasm-xor-mask-sidecar`). Flags masked entitlement packs stored beside a plaintext 32-byte XOR mask in WASM data. Bankrupt harden refuses unless allow_wasm_xor_mask_sidecar. Prefer key-dependent unmask + one-way commitments. Writes nothing.",+ inputSchema: {+ type: "object",+ properties: {+ path: {+ type: "string",+ description: "Path to a .wasm file to lint",+ },+ },+ required: ["path"],+ additionalProperties: false,+ },+ },{name: "bla_run_lookup",description:@@ -987,6 +1022,9 @@ function runDefend(handlers: McpEngineHandlers, args: Record<string, unknown>):...(args.allow_js_wasm_hydrate_dump === true? { allowJsWasmHydrateDump: true }: {}),+ ...(args.allow_wasm_xor_mask_sidecar === true+ ? { allowWasmXorMaskSidecar: true }+ : {}),...(typeof args.seed === "string" ? { seed: args.seed } : {}),});}@@ -1025,6 +1063,9 @@ function runProtect(handlers: McpEngineHandlers, args: Record<string, unknown>):...(args.allow_js_wasm_hydrate_dump === true? { allowJsWasmHydrateDump: true }: {}),+ ...(args.allow_wasm_xor_mask_sidecar === true+ ? { allowWasmXorMaskSidecar: true }+ : {}),});}@@ -1091,6 +1132,14 @@ function runLintJsWasmHydrateDump(args: Record<string, unknown>): JsWasmHydrateDreturn lintJsWasmHydrateDumpFile(abs);}+function runLintWasmXorMaskSidecar(args: Record<string, unknown>): WasmXorMaskSidecarReport {+ const abs = resolvePath(args.path as string);+ if (!existsSync(abs)) {+ throw new Error(`lint-wasm-xor-mask-sidecar target not found: ${abs}`);+ }+ return lintWasmXorMaskSidecarFile(abs);+}+export function validateMcpToolCall(params: unknown,):@@ -1557,6 +1606,9 @@ export async function handleMcpRequest(...(args.allow_js_wasm_hydrate_dump === true? { allowJsWasmHydrateDump: true }: {}),+ ...(args.allow_wasm_xor_mask_sidecar === true+ ? { allowWasmXorMaskSidecar: true }+ : {}),...(typeof args.seed === "string" ? { seed: args.seed } : {}),});// Dry-run / confirmation_required leave no write receipt; real writes do.@@ -1687,6 +1739,9 @@ export async function handleMcpRequest(} else if (name === "bla_lint_js_wasm_hydrate_dump") {payload = runLintJsWasmHydrateDump(args);refused = (payload as JsWasmHydrateDumpReport).shouldRefuseBankrupt;+ } else if (name === "bla_lint_wasm_xor_mask_sidecar") {+ payload = runLintWasmXorMaskSidecar(args);+ refused = (payload as WasmXorMaskSidecarReport).shouldRefuseBankrupt;} else if (name === "bla_run_lookup") {payload = readHardenRunSummary(args.summary_path as string,diff --git a/tests/mcp-engine-capability-parity.test.ts b/tests/mcp-engine-capability-parity.test.tsindex 67b703b..6955bc0 100644--- a/tests/mcp-engine-capability-parity.test.ts+++ b/tests/mcp-engine-capability-parity.test.ts@@ -29,6 +29,7 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{"allow_js_aes_unwrap","allow_panel_offline_oracle","allow_js_wasm_hydrate_dump",+ "allow_wasm_xor_mask_sidecar","seed","dry_run","max_artifacts",@@ -58,6 +59,7 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{"allow_js_aes_unwrap","allow_panel_offline_oracle","allow_js_wasm_hydrate_dump",+ "allow_wasm_xor_mask_sidecar","seed","in_place","confirm_overwrite",@@ -79,6 +81,7 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{"allow_js_aes_unwrap","allow_panel_offline_oracle","allow_js_wasm_hydrate_dump",+ "allow_wasm_xor_mask_sidecar","seed","llm_directives","in_place",@@ -122,6 +125,10 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{tool: "bla_lint_js_wasm_hydrate_dump",params: ["path"],},+ {+ tool: "bla_lint_wasm_xor_mask_sidecar",+ params: ["path"],+ },{tool: "bla_run_lookup",params: ["summary_path", "run_id"],diff --git a/tests/mcp-lint-wasm-xor-mask-sidecar.test.ts b/tests/mcp-lint-wasm-xor-mask-sidecar.test.tsnew file mode 100644index 0000000..9f31bc8--- /dev/null+++ b/tests/mcp-lint-wasm-xor-mask-sidecar.test.ts@@ -0,0 +1,45 @@+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { handleMcpRequest, BLA_MCP_TOOLS } from "../src/mcp/server.js";+import {+ buildTestWasmWithXorMaskSidecar,+ WASM_XOR_MASK_SIDECAR_SCHEMA,+} from "../src/engine/wasm-xor-mask-sidecar-lint.js";++const tempDirs: string[] = [];+afterEach(() => {+ for (const d of tempDirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++async function call(name: string, args: Record<string, unknown>) {+ return handleMcpRequest({+ jsonrpc: "2.0",+ id: 1,+ method: "tools/call",+ params: { name, arguments: args },+ });+}++describe("MCP bla_lint_wasm_xor_mask_sidecar", () => {+ it("registers once", () => {+ expect(BLA_MCP_TOOLS.filter((t) => t.name === "bla_lint_wasm_xor_mask_sidecar")).toHaveLength(1);+ });++ it("flags R6 footgun with isError", async () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-mcp-xor-"));+ tempDirs.push(dir);+ const file = join(dir, "core.wasm");+ writeFileSync(file, buildTestWasmWithXorMaskSidecar({}));+ const res = await call("bla_lint_wasm_xor_mask_sidecar", { path: file });+ expect(res?.error).toBeUndefined();+ const result = res!.result as {+ isError?: boolean;+ structuredContent: { schema: string; shouldRefuseBankrupt: boolean };+ };+ expect(result.structuredContent.schema).toBe(WASM_XOR_MASK_SIDECAR_SCHEMA);+ expect(result.structuredContent.shouldRefuseBankrupt).toBe(true);+ expect(result.isError).toBe(true);+ });+});diff --git a/tests/wasm-xor-mask-harden-gate.test.ts b/tests/wasm-xor-mask-harden-gate.test.tsnew file mode 100644index 0000000..be5b1a9--- /dev/null+++ b/tests/wasm-xor-mask-harden-gate.test.ts@@ -0,0 +1,54 @@+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { protectTarget } from "../src/engine/protector.js";+import { hardenProject } from "../src/engine/harden.js";+import { buildTestWasmWithXorMaskSidecar } from "../src/engine/wasm-xor-mask-sidecar-lint.js";++const dirs: string[] = [];+afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++describe("red-blue round-6 WASM XOR-mask sidecar gate", () => {+ it("bankrupt protect refuses XOR-mask sidecar unless allowed", () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-xor-gate-"));+ dirs.push(dir);+ const input = join(dir, "core.wasm");+ const output = join(dir, "core.out.wasm");+ writeFileSync(input, buildTestWasmWithXorMaskSidecar({}));+ expect(() =>+ protectTarget({+ inputPath: input,+ outputPath: output,+ intensity: "bankrupt",+ seed: "r6-xor-gate",+ }),+ ).toThrow(/allowWasmXorMaskSidecar|XOR-mask sidecar/);+ const ok = protectTarget({+ inputPath: input,+ outputPath: output,+ intensity: "bankrupt",+ seed: "r6-xor-gate",+ allowWasmXorMaskSidecar: true,+ });+ expect(ok.detectedFormat).toBe("wasm");+ });++ it("bankrupt harden refuses project trees with XOR-mask sidecar WASM", () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-xor-harden-"));+ dirs.push(dir);+ mkdirSync(join(dir, "dist"));+ writeFileSync(join(dir, "dist", "core.wasm"), buildTestWasmWithXorMaskSidecar({}));+ writeFileSync(join(dir, "dist", "app.js"), "export const ok = 1;\n", "utf8");+ const report = hardenProject({+ directory: dir,+ intensity: "bankrupt",+ seed: "r6-harden-xor",+ dryRun: true,+ });+ expect(report.overallSuccess).toBe(false);+ expect(report.artifacts.some((a) => /XOR-mask sidecar/i.test(a.error ?? ""))).toBe(true);+ });+});diff --git a/tests/wasm-xor-mask-sidecar-lint.test.ts b/tests/wasm-xor-mask-sidecar-lint.test.tsnew file mode 100644index 0000000..8a72a2b--- /dev/null+++ b/tests/wasm-xor-mask-sidecar-lint.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";+import {+ buildTestWasmWithXorMaskSidecar,+ lintWasmXorMaskSidecarBuffer,+ looksLikeXorMaskedEntitlementPack,+} from "../src/engine/wasm-xor-mask-sidecar-lint.js";++describe("wasm-xor-mask-sidecar-lint", () => {+ it("flags fixture entitlement pack with adjacent plaintext mask", () => {+ const wasm = buildTestWasmWithXorMaskSidecar({+ salt: -1378167267,+ rounds: 40,+ words: [1041213620, -2107783877, -126968763, -156377045],+ });+ const report = lintWasmXorMaskSidecarBuffer(wasm, { path: "fixture.wasm" });+ expect(report.shouldRefuseBankrupt).toBe(true);+ expect(report.looksExposed).toBe(true);+ expect(report.findings.some((f) => f.id === "wasm-xor-mask-entitlement-pack")).toBe(true);+ });++ it("does not flag empty WASM header", () => {+ const clean = Buffer.from([0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0]);+ const report = lintWasmXorMaskSidecarBuffer(clean);+ expect(report.shouldRefuseBankrupt).toBe(false);+ expect(report.findings).toHaveLength(0);+ });++ it("looksLikeXorMaskedEntitlementPack requires tight pack + entropy", () => {+ const wasm = buildTestWasmWithXorMaskSidecar({});+ // data payload starts after sections — use lint instead of raw guess+ const report = lintWasmXorMaskSidecarBuffer(wasm);+ expect(report.findings[0]?.blobLen).toBeGreaterThanOrEqual(40);+ expect(looksLikeXorMaskedEntitlementPack(Buffer.alloc(100)).ok).toBe(false);+ });+});