Merge pull request #77 from qybaihe/feat/mcp-skill-2.0

bla-agents 2.0.0 — MCP + Skill + packaging-gates (R1–R12)
This commit is contained in:
Timo Zhang
2026-11-03 12:02:39 +08:00
committed by GitHub
86 changed files with 10184 additions and 378 deletions
+103 -117
View File
@@ -7,14 +7,15 @@ description: >
Agents). Prefer this skill as the guide; call existing MCP tools / CLI — do not invent
new MCP tools. Default verb: bla_harden. Refuse crack/RE of third-party software.
metadata:
version: "1.3.2"
version: "2.0.0"
---
# 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`, …) over inventing new MCP surfaces.
(`bla_harden`, `bla_defend`, `bla_weave_plan`, **`bla_lint`** (unified), `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`, `bla_lint_wasm_seal_xor_known_plaintext`, …) over inventing new
MCP surfaces.
Use BLA whenever the user asks to harden a project against AI reverse-engineering
agents (`morluto/rea`), audit exposure, exhaust attacker token/compute budgets, induce
@@ -23,135 +24,120 @@ model misjudgment on proprietary logic, or **one-click / 一键加固** a build.
Defensive only: protect **their own** artifacts. Refuse crack, RE, bypass PoCs, or
attack playbooks against software they do not own.
**bla-agents 2.0.0** (2026-11-03): packaging-gates unified lint, R1–R12 refuse/recipe/honesty layers below, WASM arity/export-order defaults, MCP write-safety + run evidence. Relative to 1.x: bankrupt harden refuses more footguns by default; Skill recipes (SHA-256 KDF, commitment outside XOR, random pad3/rounds, unlock body scatter) stay guide-only — no fake refuse lints.
**Principles (red-blue R1–R12 → MCP/Skill 2.0):**
### A. Bankrupt refuse gates (engine + MCP — call `bla_lint` first)
| Gate | Tool | Allow override (lab only) |
| :--- | :--- | :--- |
| Independent lane tables | `bla_lint_lanes` | `allow_lane_independent` |
| Plaintext / reversible seal JSON | `bla_lint_seal` | `allow_plaintext_seal` |
| Clear WASM `R2SEAL`/`R3PARM`/`R3CIPH` | `bla_lint_wasm_params` | `allow_wasm_clear_params` |
| JS AES wrap-key + create*iv + fixed hdr | `bla_lint_js_aes_unwrap` | `allow_js_aes_unwrap` |
| Panel `deriveLocal` + `panelTokenSha256` oracle | `bla_lint_panel_derive` | `allow_panel_offline_oracle` |
| JS←WASM hydrate salt/rounds/cipher dump | `bla_lint_js_wasm_hydrate_dump` | `allow_js_wasm_hydrate_dump` |
| WASM XOR-mask beside masked pack | `bla_lint_wasm_xor_mask_sidecar` | `allow_wasm_xor_mask_sidecar` |
| `seal.revision` as XOR known-plaintext | `bla_lint_wasm_seal_xor_known_plaintext` | `allow_wasm_seal_xor_known_plaintext` |
Prefer **one** project scan: MCP `bla_lint` / CLI `bla lint .` (schema `bla-packaging-gates/v1`). Individual `bla_lint_*` remain for single-file drills. Bankrupt harden **refuses** the six carrier/JS/WASM gates unless the matching allow flag is set; lanes/panel also refuse at protect-time.
Also: do **not** ship a stable public WASM ABI without explicit `wasm_preserve_exports`; maximum/bankrupt **rewrites** `__vaultPanelDerive_*` / `deriveLocal` unless `allow_stable_panel_derive`. Multi-artifact trees: bankrupt sets `selfSealRecommended` — prefer **`self_seal`** (sibling SHA-256 **hard-fail**; opaque-seed alone does not gate entitlement).
### B. Product recipe principles (Skill layer — not new refuse lints)
Held across R8–R12 (NO PRIZE). Keep in gate design; do **not** invent packaging refuse lints for these:
- Unlock **inside WASM** (`unlock(keyPtr,keyLen)->outLen`); JS only writes key / reads result UTF-8.
- Mask via **one-way** KDF (`SHA-256(key[16])`), never algebraically invertible byte mix.
- Keep public digests (**`seal.revision`**) **out** of XOR-masked plaintext; commitment in a separate clear segment.
- Randomize pack header `pad3` + seed-derived rounds (close structural KP).
- Host resolves unlock by **arity + `FLAG{…}` shape + `sha256===certificateSha256`**, never export name/order.
- JS honeypot/canary ≠ WASM unlock (decoy must fail certificate check).
### C. Engine defaults already on (hygiene, not refuse)
At maximum/bankrupt WASM protect: export rename, **arity-2-preferring decoy alias spread**, **independent export-order shuffle**, honesty fields `wasmExportRenameApplied` / `wasmExportOrderShuffled` / `wasmExportDecoysInjected`. Cleartext may also scatter unlock body index (recipe).
### D. Honesty residual (do not water refuse lints)
Gates close **packaging** footguns. They do **not** claim white-box secrecy against full WASM RE + online/SMT vs SHA-256 commitment (R8–R12 P2). Body-size fingerprinting among arity-2 exports is P3 / diminishing returns — not a new refuse gate. `defenseScore` is an honest soft-cap, not preimage hardness.
## Prerequisites (once)
If MCP/skill are not registered yet:
1. CLI: `npx bla-agents@latest setup`
2. Then: `npx bla-agents@latest doctor` (or MCP `bla_doctor`)
2. Then: `npx bla-agents@latest doctor` (or MCP `bla_doctor`) — checks the installed
skill bundle (this file + `references/`, including format appendices) is complete
After setup, agents load this skill and can call the `bla` MCP tools.
## ⚡ One-Sentence Hardening (DEFAULT)
## ⚡ One-Sentence Hardening (DEFAULT — prefer this)
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:
When the user says **"Harden my software"**, **"一键加固"**, or any equivalent one-liner
**without naming a specific file**:
| Surface | Call |
| :--- | :--- |
| **MCP Tool (preferred)** | `bla_harden` with `{ "directory": "." }` (or the project/build path they named) |
| **MCP (preferred)** | `bla_harden` `{ "directory": "." }` |
| **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. Return the per-artifact summary to the user.
Auto-discovers protectable build outputs, detects formats, runs **audit → defend
(bankrupt) → verify**. **Do not ask which files to protect — discover them.**
**Do not ask which files to protect — discover them.**
Optional args (safe defaults): `intensity` (bankrupt), `emit_manifest` (false),
`llm_directives` (false — risky bait), `weave_decoys` (false), `self_seal` (false),
`wasm_preserve_exports`, `seed`, `output_directory`, `max_artifacts`, `dry_run`.
Optional args (defaults are safe): `intensity` (default bankrupt), `emit_manifest`
(default false), `llm_directives` (default false — risky LLM bait; leave off unless
asked), `weave_decoys` (default false — see stronger path below), `seed`.
## Write safety (principles)
## Optional stronger path: structural weave decoys
- Unsure what will be touched? `bla_discover` or `bla_harden` `{ "dry_run": true }` —
both write nothing. If `truncated: true`, say so and narrow the directory.
- Never overwrite without the user's go-ahead. On `confirmation_required`, show
`wouldOverwrite`, ask, then retry with `confirm_overwrite: true` (or a new path).
Same rule for `in_place: true` (overwrites the input).
- Report writes from the tool receipt (`writeReceipt` / `wouldOverwrite`), not guesses.
- After a successful harden/defend/protect, keep the returned unsigned `runId` (and
harden `summaryPath`). Re-check later with `bla_run_lookup` or `bla_verify` +
`summary_path`/`run_id` — never invent a run id.
- `bla_rea_drift` / `bla_redteam_report` may return `status: unverified` when sibling
REA is absent; treat that as **not proven**, never as a pass. An on-disk
`bla_redteam_report` without `execute:true` is `status: available` — readable
evidence, not a fresh REA verdict.
- `bla_harden` `{ "dry_run": true }` always has `overallSuccess: false`; only real
writes return `writeReceipt`.
When the user wants **stronger / structural** hardening (not dismissible noise),
especially for **Python** customer defs / `.pyc`, or says weave / 织入 / decoy
entanglement:
## Decision tree (short)
1. Read directives: MCP resource `bla://directives/weave-decoy`
(or `bla://docs/weave-decoy-mcp` / repo `docs/weave-decoy-mcp.md`).
2. Plan (read-only): `bla_weave_plan` with `{ "path": "<project-or-artifact>" }` →
save the `bla-weave-plan/v1` JSON work order.
3. Apply with the real pipeline flag:
- Directory: `bla_harden` `{ "directory": ".", "weave_decoys": true }`
- Named file: `bla_defend` / `bla_protect` with `weave_decoys: true`
4. MCP Prompt shortcut: `bla-weave-decoy`
5. CLI: `npx bla-agents@latest harden . --weave-decoys` (or `defend` / `protect`
with the same flag when supported)
| Intent | Prefer |
| :--- | :--- |
| Project / build dir | **`bla_harden`** |
| Named artifact | **`bla_defend`** (or granular `bla_audit` → `bla_protect` → `bla_verify`) |
| Inventory only | **`bla_discover`** |
| Structural decoys (esp. Python) | Resource `bla://directives/weave-decoy` → `bla_weave_plan` → `weave_decoys: true` |
| Packaging footguns before harden (entitlement tree) | **`bla_lint`** `{ "directory": "." }` (CLI: `bla lint .`) — unified R1–R7+lanes/panel |
| Custom license/activation gate review | **`bla_lint_lanes`** `{ "path": "<gate.js>" }` (CLI: `bla lint-lanes`) |
| Re-check a prior harden run | **`bla_run_lookup`** `{ "summary_path": "<.bla-hardened or summary.json>", "run_id": "…" }` |
| REA constant drift / empirical report | **`bla_rea_drift`** / **`bla_redteam_report`** (unverified if REA absent; on-disk read → available) |
| Format-specific knobs | Load the matching appendix under `references/` |
**Principles (non-rule, structural):** decoys must weave into **real customer paths**
(shared runtime slots, entry-reachable edges, mixed mundane/scare stems, opaque-true
happy paths, call-graph entanglement). JS AST weave is already on; Python `.py`/`.pyc`
customer-def structural weave activates when `weave_decoys: true`. See
[docs/weave-decoy-mcp.md](../../../docs/weave-decoy-mcp.md).
## FORBIDDEN
Do **not**: add dismissible noise / greppable `BLA-SHIELD` banners / empty honeypot
stubs; drive hardening via a **rule engine** (business-name → fixed snippets); help
crack, RE, bypass, or write offensive PoCs against third-party software.
## Optional stronger path: self-seal (#40.5)
If asked for offensive RE/crack help: refuse briefly; offer defensive harden of
**their** artifacts instead.
When the user wants sibling-module integrity / anti-tamper binding on **JS/Node**
targets (or says self-seal / 自密封):
## Format appendices (load on demand)
1. CLI: add `--self-seal` to `harden` / `defend` / `protect`
2. MCP: `self_seal: true` on `bla_harden` / `bla_defend` / `bla_protect`
3. Config: `"selfSeal": true` in `.blarc` (ORs with the flag)
Off by default. Browser builds soft-skip (digest=0). Pair with weave decoys when
Python structural weave is also desired.
## WASM public ABI preserve (#40.3)
When hardening `.wasm` at maximum/bankrupt and the customer must keep specific export names:
1. CLI: `--wasm-preserve-exports main,add`
2. MCP: `wasm_preserve_exports: ["main","add"]`
3. Config: `"wasmPreserveExports": ["main","add"]` in `.blarc`
Internal-looking names (`__*`, `debug_*`, …) may still be renamed; update glue via the rename map when needed.
## Lane-independence footgun lint (#40.1)
Before shipping a custom license/activation gate, run:
`npx bla-agents lint-lanes path/to/gate.js`
Heuristic warn only (exit 2 when findings). Prefer whole-key chained mixing
(no per-lane oracle) — see Meridian DESIGN / issue #40. Not RE advice.
## FORBIDDEN for executing agents
Do **not**:
- Add pure noise layers, greppable `BLA-SHIELD` / homogeneous `_bla_*` banners, or
dismissible empty/`pass` honeypot stubs that agents filter as an independent layer
- Use label-only / report-only “decoys” that are not real pipeline attributes
- Drive hardening via a **rule engine** (business-name → fixed snippet tables, homogeneous
marker templates as policy)
- Help crack, reverse-engineer, bypass, or write offensive PoCs against third-party
software
If asked for offensive RE/crack help: refuse briefly; offer defensive harden of **their**
artifacts instead.
## Single-file vs directory
| Intent | Prefer | Example |
| :--- | :--- | :--- |
| Project / build dir, auto-discover | **`bla_harden`** / `bla harden .` | User did not name a file |
| Specific artifact path | **`bla_defend`** / `bla defend <path>` | User named `./dist/app.js` |
`bla_defend` runs the 5-stage Counter-REA pipeline on a known path:
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`)**: Resource-Exhaustion + Model-Misjudgment suites (canary honeypots + system-diagnostic decoys across supported formats).
4. **Stage 4 (`verify`)**: Counter-REA invariants + token/cost amplification.
5. **Stage 5 (`manifest`)** (opt-in): `<output>.bla-manifest.json` when `emit_manifest: true`.
MCP: `bla_defend` with `{ "input_path": "<target>", "intensity": "bankrupt", "emit_manifest": true }`
CLI: `npx bla-agents@latest defend <target> --manifest`
## Step-by-step granular workflow
1. **Audit** — `bla_audit` / `npx bla-agents audit <target>`: REA Exposure Score, exposed surfaces, estimated attacker cost.
2. **Protect** — `bla_protect` / `npx bla-agents protect <target> -o <out> --intensity bankrupt` (+ optional `--weave-decoys`).
3. **Verify** — `bla_verify` / `npx bla-agents verify <protected> [original]`.
Map REA analyzers → BLA counters:
[references/counter-rea-matrix.md](references/counter-rea-matrix.md).
| Format | Appendix |
| :--- | :--- |
| JS / TS / Electron | [references/format-javascript.md](references/format-javascript.md) |
| WebAssembly | [references/format-wasm.md](references/format-wasm.md) |
| Python `.py` / `.pyc` | [references/format-python.md](references/format-python.md) |
| Android DEX / APK / IL2CPP | [references/format-android.md](references/format-android.md) |
| REA ↔ BLA matrix | [references/counter-rea-matrix.md](references/counter-rea-matrix.md) |
## CLI fallbacks
@@ -159,16 +145,16 @@ Map REA analyzers → BLA counters:
npx -y bla-agents@latest setup
npx -y bla-agents@latest doctor
npx -y bla-agents@latest harden .
npx -y bla-agents@latest harden . --weave-decoys
npx -y bla-agents@latest harden . --weave-decoys --self-seal
npx -y bla-agents@latest lint .
npx -y bla-agents@latest lint-lanes path/to/gate.js
npx -y bla-agents@latest lint-js-wasm-hydrate-dump path/to/license.cjs
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
```
## References
- [references/counter-rea-matrix.md](references/counter-rea-matrix.md) — REA ↔ BLA countermeasures
- [docs/one-click-agent-defense.md](../../../docs/one-click-agent-defense.md) — one-click UX (skill-first)
- [docs/cli-and-mcp.md](../../../docs/cli-and-mcp.md) — CLI / MCP parameter index
- [docs/weave-decoy-mcp.md](../../../docs/weave-decoy-mcp.md) — weave-decoy theory + MCP checklist
- Weave directives (after MCP setup): resource `bla://directives/weave-decoy`
- One-click UX notes (repo checkout): `docs/one-click-agent-defense.md`
- CLI / MCP parameter index (repo checkout): `docs/cli-and-mcp.md`
@@ -0,0 +1,19 @@
# Format appendix: Android DEX / APK / IL2CPP
Load this when hardening Android packages, DEX, or Unity IL2CPP metadata.
## What BLA touches
- **DEX**: string/type-table densification with recomputed SHA-1 / Adler32 (see Counter-REA matrix ↔ `mobile-game.ts`).
- **APK / ZIP**: member-level hardening for unprotected members; **signed APKs fail closed** — resign after shield, or shield unsigned inputs.
- **IL2CPP**: enclave-type / metadata decoys around Unity `0xFAB11BAF` surfaces.
## Agent workflow
1. Prefer `bla_discover` / `bla_harden` `{ "dry_run": true }` on the build output dir to see which `.dex` / `.apk` / native members are in scope (`truncated` matters on large trees).
2. Harden with `bla_harden` (directory) or `bla_defend` (named artifact). Use `confirm_overwrite` when re-running into an existing output.
3. Do not treat a high `defenseScore` as proof against offline crypto attacks — score scope is Counter-REA gates + exposure drop.
## Related matrix rows
See [counter-rea-matrix.md](./counter-rea-matrix.md) rows for `AndroidDex.ts` / `Il2CppMetadata.ts`.
@@ -0,0 +1,68 @@
# Format appendix: JavaScript / TypeScript / Electron
Load this when hardening JS/TS bundles, Node modules, HTML bundles, or Electron `.asar`.
## Defaults
- JS AST weave is **always on** during protect/defend/harden (not gated by `weave_decoys`).
- Prefer `bla_harden` for a project/build dir; `bla_defend` / `bla_protect` for a named file.
- Honey source maps default **on**. MCP: `honey_source_maps` (protect). CLI: `--no-honey-maps` to disable.
## Stronger options (opt-in)
| Goal | MCP | CLI / config |
| :--- | :--- | :--- |
| Sibling-module integrity binding | `self_seal: true` | `--self-seal` / `.blarc` `"selfSeal": true` |
| Structural decoys (also helps Python in the same tree) | `weave_decoys: true` | `--weave-decoys` |
| Overwrite the input file | `in_place: true` **and** `confirm_overwrite: true` | `--in-place` |
Self-seal soft-skips in pure browser builds (digest stays 0). Pair with weave when the tree also has Python customer defs.
## Verify honesty
`defenseScore` soft-caps JS-like targets with `self-seal-not-enabled` unless verify knows seal ran. After `bla_protect` / `bla_defend`, pass `self_seal_enabled: true` into `bla_verify` when the protect report shows `selfSeal: true` (defend/harden already forward this internally).
## Electron notes
IPC ambiguity + route mirage layers activate on JS/TS/asar/directory targets during verify. Prefer defending the packaged `.asar` or the `dist/` that ships to users, not only sources.
## Lane-independence (gates / entitlement)
Do **not** keep independent per-byte / per-lane JS check tables (`Object.freeze(parseInt hex…)`, `charCodeAt(i)` → wasm mix/seal per lane). Prefer **whole-key chained mixing**. `bla_lint_lanes` returns severity **error**; harden/defend/protect **refuse** unless `allow_lane_independent` / `--allow-lane-independent` (teaching fixtures only).
## Plaintext seal sidecars (red-blue round-2)
`bla harden` protects discovered JS/WASM/HTML artifacts — **not** adjacent `seal.json` / catalog files you copy next to the output. If a gate loads salts, expected digests, or certificate ciphertext from sibling JSON (or a WASM data-section twin), that material stays attacker-readable.
Rules of thumb:
1. Prefer **one-way** commitments (`SHA-256` / HMAC) for public `revision` / compare digests. Custom reversible ARX/Feistel “digests” invert to the key when salt+rounds are public.
2. Encrypt or omit seal sidecars in the shipped tree; or fold them under **`self_seal`** / a sealed blob bound to the entry module.
3. Dual-publish (JSON + WASM `R2SEAL` data) without encryption doubles the same exposure.
**Engine gate:** `bla_lint_seal` / CLI `bla lint-seal` flags reversible plaintext seals. At **bankrupt**, harden/protect **refuse** unless `allow_plaintext_seal` / `--allow-plaintext-seal` / `.blarc` `"allowPlaintextSeal": true` (lab fixtures only). One-way SHA-256 seals without invertible ARX params pass.
## One-way seals still need packaging (red-blue round-3)
Round-3 confirmed: SHA-256 (or HMAC) public `revision` **stops** seal-only ARX inversion. That is necessary, not sufficient:
1. Digests-only `seal.json` still triggers `plaintext-seal-sidecar` **warning** (`shouldRefuseBankrupt: false`). Prefer omit/encrypt/`self_seal`.
2. Do **not** dual-carry runtime salt/rounds/ciphertext as clear WASM data next to the seal (`R3PARM`/`R3CIPH`-class ASCII magics). Encrypt, relocate, or bind under self-seal.
3. Strip or rename stable panel helpers such as `__vaultPanelDerive_*`, and avoid leaving classic FNV primes as readable literals in HTML bundles when they back entitlement tokens.
4. For multi-artifact gates (JS + WASM + HTML + seal), turn on **`self_seal`** so siblings cannot be freely swapped/instrumented.
## Round-3 residual gates
- `bla_lint_panel_derive` / `bla lint-panel-derive` flags stable `__vaultPanelDerive_*`; maximum/bankrupt protect rewrites to `_blaPd_*` unless `allow_stable_panel_derive`.
- Multi-artifact trees: bankrupt harden reports `selfSealRecommended` — pass `self_seal: true` (auto sibling bind on harden). Single-file stays opt-in only.
## Round-4 residual gates (AES wrap + panel oracle)
AES-CTR sealed WASM param blobs without clear `PARM` magic still leak when **JS** holds a recoverable wrap key and calls `createDecipheriv` / `createCipheriv` against a fixed hdr beacon (e.g. `d17ea004`). This is **not** white-box AES.
| Gate | Surface | Default |
| :--- | :--- | :--- |
| `bla_lint_js_aes_unwrap` / `bla lint-js-aes-unwrap` | wrap-key + create*iv + fixed hdr | bankrupt **refuse** unless `allow_js_aes_unwrap` / `--allow-js-aes-unwrap` |
| `bla_lint_panel_derive` | `deriveLocal` rewrite + `panelTokenSha256` oracle | rewrite `_blaPdLocal_*`; bankrupt **refuse** oracle combo unless `allow_panel_offline_oracle` |
Prefer unwrap inside WASM; scrub plaintext panel token digests; do not ship a callable derive UI beside seal digests. Self-seal sibling SHA-256 hard-fail is separate and already on when siblings exist at protect time.
@@ -0,0 +1,22 @@
# Format appendix: Python (`.py` / `.pyc`)
Load this when hardening Python sources or bytecode.
## `weave_decoys` is the structural switch
| Flag | `.py` behavior | `.pyc` behavior |
| :--- | :--- | :--- |
| `weave_decoys: false` (default) | Warm-init / tarpit only — not structural customer-def weave | Trailer-oriented |
| `weave_decoys: true` | Customer `FunctionDef` bodies get shared-slot touch + opaque-false decoy calls | Customer `co_consts` CODE weave |
JS AST weave in the same tree stays always-on regardless of this flag.
## Recommended path
1. Read MCP resource `bla://directives/weave-decoy` (directives travel with the MCP server; no repo checkout required).
2. Plan: `bla_weave_plan` `{ "path": "<project-or-file>" }`.
3. Apply: `bla_harden` / `bla_defend` / `bla_protect` with `weave_decoys: true`.
## PyInstaller honesty
CArchive peel on onefile bundles is expected. Densify by shielding `.py`/`.pyc` **before** bundling rather than only the final binary.
@@ -0,0 +1,52 @@
# Format appendix: WebAssembly
Load this when hardening `.wasm` modules.
## Intensity & rename
At `maximum` / `bankrupt`, BLA renames **all** exports not listed in the preserve list (red-blue round-1: silent `mix`/`seal` ABI enabled preload hooks). Do **not** ship a stable public WASM ABI unless glue truly requires it — and then list names **explicitly**:
| Surface | How |
| :--- | :--- |
| MCP | `wasm_preserve_exports: ["main","add"]` on harden/defend/protect |
| CLI | `--wasm-preserve-exports main,add` |
| Config | `.blarc` `"wasmPreserveExports": ["main","add"]` |
Glue that imports renamed symbols should consume the rename map from the protect report.
## Verify honesty
Standalone `bla_verify` soft-caps WASM with `wasm-export-rename-pending` unless you pass `wasm_export_rename_applied: true` (set when `ProtectionResult.wasmExportRenameApplied` was true). Defend/harden already forward that flag into their embedded verify step.
## Data-section seal carriers (red-blue round-3)
Export rename closes the public `mix`/`seal` hook surface. It does **not** hide plaintext entitlement material in active data:
- Avoid shipping ASCII magics such as `R2SEAL` / `R3PARM` / `R3CIPH` followed by clear salt, round counts, invertible revisions, or certificate ciphertext.
- If the gate must load schedule params from WASM, encrypt them or bind the blob under **`self_seal`** with the entry module — especially when a sibling `seal.json` already publishes one-way digests.
## Round-3 residual gate
- Run `bla_lint_wasm_params` / `bla lint-wasm-params` before shipping. Bankrupt harden refuses clear param/cipher magics unless `allow_wasm_clear_params`.
- This is a **detection gate**, not data-section encryption.
## Sealed blobs still need JS honesty (red-blue round-4)
Encrypting WASM data (no clear `R3PARM`) closes the ASCII-carrier lint. If the **JS loader** still does `Buffer.from(WRAP_KEY_HEX, "hex")` + `createDecipheriv` against a fixed hdr, Node instrumentation recovers params. Run `bla_lint_js_aes_unwrap` on the loader; bankrupt refuses that footgun. BLA does **not** claim white-box AES.
## Unlock-in-WASM + mask hygiene (red-blue R5–R12)
Export rename closes public `mix`/`seal` hooks. It does **not** replace careful entitlement packaging:
| Round | Do | Lint / engine |
| :--- | :--- | :--- |
| R5–R6 | Keep ARX+compare+decrypt **inside** `unlock`; JS must not hydrate→dump salt/rounds/cipher | `bla_lint_js_wasm_hydrate_dump` |
| R6 | Never store plaintext XOR mask beside masked pack | `bla_lint_wasm_xor_mask_sidecar` |
| R7 | Never put `seal.revision` under repeating XOR mask; use one-way mask KDF | `bla_lint_wasm_seal_xor_known_plaintext` |
| R8+ | `SHA-256(key)` mask; commitment **outside** XOR; entropy pad ≠ revision | Skill recipe (R7 lint covers KP) |
| R9 | Seed-derived rounds + nonzero pad3 | Skill recipe |
| R10–R12 | Engine: arity-2 alias spread + export-order shuffle + prefer arity-2 decoys | protect defaults |
| Host | Resolve by arity + FLAG shape + `certificateSha256`, never first export | Skill recipe |
Project scan: `bla_lint` / `bla lint .`. Honesty: full WASM RE + online/SMT vs commitment remains possible — gates ≠ white-box.
+29
View File
@@ -6,7 +6,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [2.0.0] — 2026-11-03
Major MCP + Skill 2.0 release. Red/Blue R1–R12 packaging gates that held under adversarial
dogfood are now product defaults: unified `bla lint` / `bla_lint`, bankrupt refuse lints,
WASM export hygiene, agent write-safety, and honest Skill recipes for crypto that cannot
be a packaging lint. Breaking only in the sense of new bankrupt refuses / ABI defaults —
CLI/MCP verbs remain `bla_harden` / `bla_defend` / `bla_protect`.
### Added
- **Unified packaging gates (`bla lint` / MCP `bla_lint`):** one project scan over every R1–R7 bankrupt refuse lint plus lane/panel discovery (`bla-packaging-gates/v1`). `hardenProject` shares `evaluateHardenProjectPackagingBlocks`. Skill guide **v2.0.0** layers refuse gates / product recipes / honesty residual from red-blue R1–R12. WASM protect honesty surfaces `wasmExportOrderShuffled` / `wasmExportDecoysInjected`. MCP parity includes `allow_wasm_seal_xor_known_plaintext` on harden/defend/protect.
- **Red/Blue round-4 · Writeback — JS AES unwrap lint + panel offline-oracle gate:** CLI `bla lint-js-aes-unwrap` / MCP `bla_lint_js_aes_unwrap` detect hex/base64 wrap-key material + `createDecipheriv`/`createCipheriv` + fixed sealed hdr (e.g. `d17ea004`). Bankrupt harden/protect **refuse** unless `allowJsAesUnwrap` / `--allow-js-aes-unwrap` / `allow_js_aes_unwrap`. Gate only — **not** white-box AES. `bla_lint_panel_derive` / CLI also flag stable `deriveLocal` (maximum/bankrupt rewrite to `_blaPdLocal_*`) and `deriveLocal` + plaintext `panelTokenSha256` offline-oracle packaging (same-file or sibling `seal.json`); bankrupt **refuses** the oracle combo unless `allowPanelOfflineOracle` / `--allow-panel-offline-oracle` / `allow_panel_offline_oracle`. Skill **v1.5.7**. Self-seal sibling SHA-256 hard-fail remains from `c2ec868`.
- **Red/Blue round-3 · Writeback residual — WASM param lint + panel rewrite + self_seal recommend:** CLI `bla lint-wasm-params` / MCP `bla_lint_wasm_params` detect clear `R3PARM`/`R3CIPH`/`R2SEAL`-class ASCII carriers with adjacent binary blobs; bankrupt harden/protect **refuse** unless `allowWasmClearParamCarriers` / `--allow-wasm-clear-params` / `allow_wasm_clear_params`. CLI `bla lint-panel-derive` / MCP `bla_lint_panel_derive` flag stable `__vaultPanelDerive_*` (and classic FNV primes as warning); maximum/bankrupt protect **rewrites** to seed-stable `_blaPd_*` unless `allowStablePanelDeriveAbi` / `--allow-stable-panel-derive` / `allow_stable_panel_derive`. Bankrupt harden sets `selfSealRecommended` for multi-artifact JS/WASM/HTML trees without auto-enabling single-file; `--self-seal` on harden auto-binds sibling paths. Audit surfaces the same WASM/panel findings. Skill **v1.5.6**. Full WASM data-section encryption remains a follow-up.
- **Red/Blue round-3 · Red writeback (skill):** one-way SHA-256 seals **close** the round-2 ARX-invert break; skill **v1.5.5** + format appendices document residual packaging — WASM `R3PARM`/`R3CIPH`-class clear param/cipher carriers, stable `__vaultPanelDerive_*` / FNV literals, and prefer `self_seal` for multi-artifact entitlement trees. No emergency P0.
- **Red/Blue round-2 · Writeback P1 — seal-commitment lint + bankrupt refuse:** CLI `bla lint-seal` / MCP `bla_lint_seal` detect plaintext seal sidecars and reversible public commitments (round-2 `seal.json` + ARX `revision` break). Bankrupt harden/protect refuse unless `allowPlaintextSeal` / `--allow-plaintext-seal` / `allow_plaintext_seal`. One-way SHA-256 seals pass. Skill v1.5.4 points at the new tool/switch.
### Changed
- **Red/Blue round-2 · Writeback (skill, superseded in part by P1 engine lint):** Skill guide **v1.5.3** + `format-javascript.md` — plaintext seal/catalog sidecars are unprotected by harden; public compare digests must be one-way (reversible ARX/`revision` was the round-2 key-recovery break). Round-1 P0 (WASM export rename + lane refuse) held against the old vectors.
- **Red/Blue round-1 · Writeback P0 — WASM export rename default:** at `maximum`/`bankrupt`, `protectWasmBinary` renames **all** non-preserved exports (not only `__*` / `debug_*`). Keeping a stable public ABI requires explicit `wasmPreserveExports` / `--wasm-preserve-exports` / `wasm_preserve_exports`. Optional `renameInternalOnly: true` for the weaker pass.
- **Red/Blue round-1 · Writeback P0 — lane-independence is error + harden refuse:** `bla lint-lanes` / `bla_lint_lanes` findings are severity **error**; protect/defend/harden refuse JS/TS that looks lane-independent (including per-byte WASM mix/seal oracles) unless `allowLaneIndependentGates` / `--allow-lane-independent` / `allow_lane_independent`. Skill v1.5.2 principles: no silent stable WASM ABI; no JS independent lane tables; prefer whole-key mixing.
### Fixed
- **CI hydrate-dump lint fixtures:** optional `/workspace/bla-redblue` dogfood paths no longer fail clones; in-repo synthetic R5/R6 shapes cover refuse vs unlock-in-WASM.
- **MCP/Skill 2.0 stabilization:** `bla_harden` dry-run no longer sets `overallSuccess: true`; CLI formatter labels dry-run as `DRY-RUN (nothing written)` instead of `SUCCESS`. Successful `bla_harden` writes now return `writeReceipt` (matching defend/protect and the stage A contract). `bla_redteam_report` on-disk reads use `status: available` (not `pass`) so agents cannot mistake a static fixture for a live REA verdict; harness stdout/stderr are clipped for MCP stdio safety. Skill guide **v1.5.1** documents available vs unverified.
### Added
- **MCP/Skill 2.0 stage C (evidence + REA observability):** harden/defend/protect results carry a stable unsigned `runId`; `hardenProject` writes `bla-harden-summary/v2` with `runId` + `signature: "unsigned"`; read-only `bla_run_lookup` and optional `bla_verify` `summary_path`/`run_id` correlation (bad/missing id → explicit error). Thin MCP wrappers `bla_rea_drift` / `bla_redteam_report` over existing scripts — absent REA or missing report → `status: unverified` with `isError` (never silent pass). Skill guide **v1.5** documents run lookup + unverified principles.
- **MCP/Skill 2.0 stage B (CLI↔MCP parity):** `bla_lint_lanes` (same engine as `bla lint-lanes`); `in_place` on `bla_protect`/`bla_defend` (still gated by `confirm_overwrite`); `honey_source_maps` on `bla_protect`; `output_directory` on `bla_harden`; `bla_verify` honesty metadata (`self_seal_enabled`, `wasm_export_rename_applied`, `numeric_template_leak_known`) so soft-caps match protect-side facts.
- **Skill format appendices:** `references/format-{javascript,wasm,python,android}.md`; skill guide v1.4 keeps a short decision tree and drops install-breaking `../../../docs` links (weave via `bla://directives/weave-decoy`). Setup/doctor install+hash the full bundle including appendices.
- **Agent write safety (MCP/Skill 2.0, stage A):** read-only `bla_discover`; `bla_harden` `dry_run` (CLI `harden --dry-run`) writes zero bytes and reports `truncated` / `wouldOverwrite`; `bla_harden` / `bla_defend` / `bla_protect` refuse to overwrite existing outputs without `confirm_overwrite: true` and return a `writeReceipt`.
- **Full skill bundle install:** `bla setup` installs `SKILL.md` plus `references/` (counter-rea-matrix); `bla doctor` reports `skillMissingFiles` / `skillModifiedFiles` and fails on an incomplete bundle; uninstall removes owned bundle files.
- **Self-seal (#40.5):** opt-in CLI `--self-seal` / MCP `self_seal` / `.blarc selfSeal` injects Node sibling-module + env-fingerprint integrity binding into JS AST shield and entangles the opaque-predicate seed.
- **WASM preserve ABI (#40.3):** `.blarc`/`CLI`/`MCP` `wasmPreserveExports` / `--wasm-preserve-exports` / `wasm_preserve_exports` keeps listed export names when rename runs.
- **WASM export rename (#40.3):** `protectWasmBinary` renames internal-looking exports at maximum/bankrupt (preserve public ABI via `preserveExports`); returns `exportsRenamed`.
+5 -1
View File
@@ -1,6 +1,6 @@
# BLA state of the project
**Version:** 1.6.4 (`package.json` ↔ `src/identity.ts`, verified by build; see `CHANGELOG.md`)
**Version:** 2.0.0 (`package.json` ↔ `src/identity.ts`, verified by build; see `CHANGELOG.md`)
**Status:** CI matrix runs typecheck, build, tests and the benchmark on ubuntu / macos / windows with Node 24. Windows checkouts keep `challenge/**` LF via `.gitattributes` so the CrackMe seals verify.
**Publishing:** tag-only releases (`git tag bla-agents-<version>`); see `CHANGELOG.md` and GitHub Releases.
@@ -87,6 +87,10 @@ Outside the repo, `npm pack` → install tarball → isolated `HOME`:
- Shipped **v1.4.6** counter: `android-r8.ts` + unsigned-APK wiring + identity
constants + `verify:rea` drift entries.
## Red-blue packaging gates (R1–R12 → 2.0)
Unified `bla lint` / MCP `bla_lint` (`bla-packaging-gates/v1`) aggregates every bankrupt refuse lint from red-blue rounds 1–7; R8–R12 SHA-256 KDF / commitment-outside-XOR / arity+export hygiene live as Skill recipes + WASM protect defaults. Honesty residual: full WASM RE + online/SMT — **not** a new refuse lint. Skill **v2.0.0**. Shipped as **bla-agents 2.0.0** (PR #77).
## Nightly roadmap remaining
1. ~~**Self-seal / defenseScore honesty (#40)**~~ — landed soft-caps + opt-in `--self-seal` / MCP `self_seal` / `.blarc selfSeal` (batch 2026-11-02). Remaining: deeper onefile/peel score model.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"schema": "bla-crackme-v6-seal/v2",
"mode": "release",
"blaVersion": "1.6.4",
"blaVersion": "2.0.0",
"recipe": "npm run crackme:build (hardenProject == `bla harden <dir> --intensity bankrupt --seed <seed>`)",
"seed": "bla-crackme-v6-harden-native-2026-11",
"intensity": "bankrupt",
+1 -1
View File
@@ -2,7 +2,7 @@
"schema": "bla-crackme-v7-seal/v1",
"mode": "release",
"product": "Meridian",
"blaVersion": "1.6.4",
"blaVersion": "2.0.0",
"hardenSeedLabel": "bound-at-build-into-opaque-predicates",
"intensity": "bankrupt",
"llmDirectives": false,
+31 -7
View File
@@ -8,6 +8,7 @@ For coding agents, the **[`blind-llm-agents` skill](../.agents/skills/blind-llm-
| :--- | :--- |
| `npx bla-agents setup` | Auto-registers the `bla` MCP server and `blind-llm-agents` skill with Claude Code, Cursor, Codex, Windsurf, Gemini CLI, and Antigravity. |
| `npx bla-agents harden .` | **Default one-command UX**: auto-discover build outputs and run audit → protect → verify (bankrupt). Prefer over `defend` when you have a project directory. Agent guide: [`blind-llm-agents` skill](../.agents/skills/blind-llm-agents/SKILL.md). |
| `npx bla-agents lint .` | **Unified packaging-footgun scan** (`bla-packaging-gates/v1`): all R1–R7 refuse lints + lanes/panel. Exit 2 when bankrupt would refuse. Writes nothing. |
| `npx bla-agents defend <target> [--manifest] [--llm-directives] [--weave-decoys]` | **5-stage pipeline** on a known path: `inspect-release` → `audit` → `protect` → `verify` → optional **unsigned** `.bla-manifest.json` (opt-in). Risky LLM directive layers stay off unless `--llm-directives`. Structural weave decoys stay off unless `--weave-decoys`. |
| `npx bla-agents harden . [--weave-decoys]` | Same as `harden` with opt-in structural weave (`weave_decoys`). |
| `npx bla-agents inspect-release <target>` | Read-only local scan for embedded `.map` (`sourcesContent`) and sourceMappingURL references. |
@@ -20,24 +21,47 @@ For coding agents, the **[`blind-llm-agents` skill](../.agents/skills/blind-llm-
## MCP Tools (`bla` Server)
- `bla_harden`: Preferred one-sentence harden of a project directory (`directory`, `intensity`, `emit_manifest` default false, `llm_directives` default false, `weave_decoys` default false, `seed`).
- `bla_defend`: Full Counter-REA pipeline on a known path (`input_path`, `output_path`, `intensity`, `emit_manifest` default false, `llm_directives` default false, `weave_decoys` default false, `seed`).
- `bla_harden`: Preferred one-sentence harden of a project directory (`directory`, `intensity`, `emit_manifest` default false, `llm_directives` default false, `weave_decoys` default false, `self_seal` default false, `wasm_preserve_exports`, `allow_lane_independent`, `allow_plaintext_seal`, `allow_wasm_clear_params`, `allow_stable_panel_derive`, `seed`, `dry_run` default false, `max_artifacts` default 64, `confirm_overwrite` default false, `output_directory` optional). The report carries `dryRun`, `truncated`, `maxArtifacts`, `wouldOverwrite`, and `outputDirectory`.
- `bla_discover`: Read-only inventory using the same discovery as `bla_harden` (`directory`, `max_artifacts`) → `{ directory, artifacts[{path, relativePath, format}], truncated, maxArtifacts }`. Writes nothing.
- `bla_defend`: Full Counter-REA pipeline on a known path (`input_path`, `output_path`, `intensity`, `emit_manifest` default false, `llm_directives` default false, `weave_decoys` default false, `self_seal` default false, `wasm_preserve_exports`, `allow_lane_independent`, `allow_plaintext_seal`, `seed`, `in_place` default false, `confirm_overwrite` default false).
- `bla_audit`: Pre-flight REA exposure and token-economics audit (`path`).
- `bla_protect`: Granular shield injection (`input_path`, `output_path`, `intensity`, `seed`, `llm_directives` default false, `weave_decoys` default false).
- `bla_verify`: Counter-REA invariant verification (`target_path`, `original_path`).
- `bla_protect`: Granular shield injection (`input_path`, `output_path`, `intensity`, `seed`, `llm_directives` default false, `weave_decoys` default false, `self_seal` default false, `wasm_preserve_exports`, `allow_lane_independent`, `allow_plaintext_seal`, `in_place` default false, `honey_source_maps` default true, `confirm_overwrite` default false).
- `bla_verify`: Counter-REA invariant verification (`target_path`, `original_path`, optional honesty metadata `self_seal_enabled` / `wasm_export_rename_applied` / `numeric_template_leak_known` so `defenseScore` soft-caps match what protect actually ran; optional `summary_path` / `run_id` to correlate with a prior harden summary).
- `bla_lint`: **DEFAULT** packaging-footgun project scan (`directory`, `intensity`, allow_* flags) → `bla-packaging-gates/v1` (findings + blocking + honestyNote). Prefer over calling eight separate lints. Same engines as CLI `bla lint`.
- `bla_lint_lanes`: Read-only lane-independence footgun lint (`path`) — same engine as CLI `bla lint-lanes`.
- `bla_lint_seal`: Read-only seal-commitment lint (`path`) — plaintext / reversible seal sidecars; same engine as CLI `bla lint-seal`.
- `bla_lint_wasm_params`: Read-only WASM clear param/cipher carrier lint (`path`) — `R3PARM`/`R3CIPH`/`R2SEAL`-class; same engine as CLI `bla lint-wasm-params`.
- `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`, `allow_wasm_seal_xor_known_plaintext`.
- `bla_lint_wasm_seal_xor_known_plaintext`: Read-only seal.revision XOR known-plaintext lint (`path`, optional `seal_path`) — bankrupt refuses unless `allow_wasm_seal_xor_known_plaintext`.
- `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`.
- `bla_benchmark`: Runs the 8-target showcase benchmark suite.
- `bla_emit_headers`: Generates C/C++, Rust, or Go defense headers (`language`, `intensity`).
- `bla_doctor`: Diagnostics for BLA engines and agent client registrations.
- `bla_doctor`: Diagnostics for BLA engines and agent client registrations; also reports `skillMissingFiles` / `skillModifiedFiles` (format appendices under `references/` included).
- `bla_weave_plan`: Read-only weave-decoy planner (`path`, optional `max_targets`) → `bla-weave-plan/v1` JSON (defensive theory checklist; no crack/RE).
### Write safety (dry-run, confirmation, receipts)
- `bla_harden` with `dry_run: true` (CLI `bla harden . --dry-run`) discovers targets and plans outputs with **zero bytes written** (no `.bla-hardened/`, no summary, no `.blarc` seed). Dry-run sets `overallSuccess: false` — it never claims a successful harden.
- Discovery is capped (`max_artifacts`, default 64); when more targets exist the result sets `truncated: true` instead of silently dropping them.
- `bla_harden` / `bla_defend` / `bla_protect` refuse to overwrite an existing output file unless `confirm_overwrite: true`. A refusal is `isError: true` with `{ status: "confirmation_required", wouldOverwrite: [...], wrote: [] }`; nothing is written.
- Successful `bla_harden` / `bla_defend` / `bla_protect` writes add `writeReceipt: { status: "written", wrote, overwrote, confirmed }` (`bla_harden` dry-run omits it).
- `in_place: true` (MCP) / `--in-place` (CLI) plans the output as the input path; because that path already exists, `confirm_overwrite: true` is required on MCP or the call is refused with `confirmation_required`.
`weave_decoys: true` activates structural Python customer-def weave (shared-slot touch + opaque-false decoy calls) after the #51 tarpit; when false, Python stays warm-init-only. JS AST weave remains always-on.
Project config parity: set `"weaveDecoys": true` in `.blarc` / `bla.config.json` (schema `bla.config.v1.json`) to enable the same flag without repeating `--weave-decoys` / MCP `weave_decoys` on every invoke. CLI/MCP flags still OR with the config value.
Opt-in **self-seal** (issue #40.5): CLI `--self-seal`, MCP `self_seal`, `.blarc` `"selfSeal": true`. Injects a Node self-integrity preamble (module + optional sibling paths + env fingerprint) and folds the digest into the opaque-predicate seed for JS/Node targets.
WASM public ABI preserve list (issue #40.3): CLI `--wasm-preserve-exports a,b`, MCP `wasm_preserve_exports`, `.blarc` `"wasmPreserveExports": ["a","b"]`. Kept names stay; internal-looking exports may still rename at maximum/bankrupt.
WASM public ABI preserve list (issue #40.3 / red-blue round-1): CLI `--wasm-preserve-exports a,b`, MCP `wasm_preserve_exports`, `.blarc` `"wasmPreserveExports": ["a","b"]`. At `maximum`/`bankrupt`, **every** non-listed export is renamed by default — keeping `mix`/`seal`-style names requires an explicit list.
Heuristic **lane-independence lint** (issue #40.1): `bla lint-lanes <file>` warns when gate code looks like independent per-lane checks. Defensive guidance only — prefer whole-key chained mixing.
Heuristic **lane-independence lint** (issue #40.1 / red-blue round-1): CLI `bla lint-lanes <file>` and MCP `bla_lint_lanes` emit severity **error** when gate code looks like independent per-lane checks. Harden/defend/protect **refuse** unless CLI `--allow-lane-independent` / MCP `allow_lane_independent` / `.blarc` `"allowLaneIndependentGates": true`. Prefer whole-key chained mixing.
Heuristic **seal-commitment lint** (red-blue round-2): CLI `bla lint-seal <file>` and MCP `bla_lint_seal` flag plaintext seal/entitlement JSON and reversible public commitments (`scheduleSalt`+`rounds`+`revision` without a one-way algorithm). Severity **error** findings make **bankrupt** harden/protect **refuse** unless CLI `--allow-plaintext-seal` / MCP `allow_plaintext_seal` / `.blarc` `"allowPlaintextSeal": true`. One-way SHA-256/HMAC digests pass. Full seal-encrypt/bind remains a follow-up; refusal closes the round-2 footgun by default.
### MCP Resources
+1 -1
View File
@@ -41,4 +41,4 @@ resource `bla://directives/weave-decoy`, tool `bla_weave_plan`, flag
## WASM export rename (#40.3)
`protectWasmBinary` can rename non-public / internal-looking exports while preserving names listed in `preserveExports`. At `maximum`/`bankrupt`, internal-looking names (`__*`, `debug_*`, …) are renamed by default. Forced full rename: `renameNonPublicExports: true` with an explicit preserve list for the public ABI. Returns `exportsRenamed` for glue updates. Project / CLI / MCP parity: `.blarc` `wasmPreserveExports`, `--wasm-preserve-exports`, MCP `wasm_preserve_exports`.
`protectWasmBinary` renames exports not listed in `preserveExports`. At `maximum`/`bankrupt`, **all** non-preserved names rename by default (red-blue round-1). Keeping a stable public ABI requires an explicit preserve list. Optional `renameInternalOnly: true` restores the weaker internal-only pass. Returns `exportsRenamed` for glue updates. Project / CLI / MCP parity: `.blarc` `wasmPreserveExports`, `--wasm-preserve-exports`, MCP `wasm_preserve_exports`.
+1 -1
View File
@@ -76,5 +76,5 @@ Pass `--self-seal` / MCP `self_seal: true` / `.blarc` `"selfSeal": true` so JS/N
## WASM export rename / preserve (#40.3)
At `maximum`/`bankrupt`, BLA may rename internal-looking WASM exports. Pass `--wasm-preserve-exports main,add` / MCP `wasm_preserve_exports` / `.blarc` `"wasmPreserveExports": ["main","add"]` so the public ABI stays stable while glue can consume the rename map for anything else.
At `maximum`/`bankrupt`, BLA renames **all** non-preserved WASM exports. Pass `--wasm-preserve-exports main,add` / MCP `wasm_preserve_exports` / `.blarc` `"wasmPreserveExports": ["main","add"]` only when the public ABI must stay; otherwise consume the rename map. Do not leave independent JS lane tables — `bla lint-lanes` / harden refuse unless `--allow-lane-independent`.
+44
View File
@@ -0,0 +1,44 @@
# bla-agents v2.0.0 — MCP + Skill 2.0
**Date:** 2026-11-03 (Asia/Singapore)
## Headline
Red/Blue R1–R12 packaging that held under adversarial dogfood is now product:
- Unified **`bla lint` / MCP `bla_lint`** (`bla-packaging-gates/v1`) + shared harden blocks
- Bankrupt refuse lints for lanes, seals, WASM carriers, JS AES unwrap, panel oracles, hydrate dumps, XOR-mask sidecars, seal.revision XOR-KP
- WASM maximum/bankrupt defaults: export rename, arity-2-preferring decoys, independent export-order shuffle
- MCP/CLI write-safety (`discover`, `dry_run`, `confirm_overwrite`, `writeReceipt`) + run evidence
- Skill **v2.0.0** layers refuse gates / product recipes / honesty residual (full WASM RE + online/SMT — no fake lint)
## Relative to 1.x
| Area | 1.x | 2.0.0 |
|------|-----|-------|
| Packaging scan | Per-lint CLIs | Unified `bla lint` / `bla_lint` |
| Bankrupt footguns | Partial (grew across 1.5–1.6) | Full R1–R7 refuse set + WASM hygiene |
| Crypto recipes (KDF, commitment, pad3) | Ad-hoc skill notes | Explicit Skill B-layer (not refuse lints) |
| Agent overwrite / dry-run | Incomplete | Stage A–C contract |
## Gates
- `npm run build` — required green
- `npm test` — ~467 pass / 2 skip
- Tag: `bla-agents-2.0.0` (and `v2.0.0` alias)
## Publish checklist
```bash
gh auth status
git checkout main && git pull
git tag -a bla-agents-2.0.0 -m "bla-agents v2.0.0"
git tag -a v2.0.0 -m "bla-agents v2.0.0"
git push origin bla-agents-2.0.0 v2.0.0
gh release create bla-agents-2.0.0 --title "bla-agents v2.0.0" --notes-file docs/releases/v2.0.0.md
# npm publish only when npm credentials are configured
```
## Red line
Unsigned APKs only. Defensive tooling — refuse crack/RE of third-party software.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "bla-agents",
"version": "1.6.4",
"version": "2.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "bla-agents",
"version": "1.6.4",
"version": "2.0.0",
"license": "MIT",
"dependencies": {
"@babel/generator": "^7.26.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "bla-agents",
"version": "1.6.4",
"version": "2.0.0",
"description": "BLA (Blind LLM Agents) \u2014 Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, WebAssembly, SQLite, AI Models, and Android DEX/IL2CPP against AI reverse-engineering agents like REA.",
"keywords": [
"reverse-engineering-defense",
+5
View File
@@ -154,6 +154,9 @@ export async function hardenChallenge({ key, flag, outDir, seed = SEED }) {
copyFileSync(join(SRC_DIR, "panel.html"), join(stage, "panel.html"));
copyFileSync(join(SRC_DIR, "core.wasm"), join(stage, "core.wasm"));
// Red/blue round-1: bankrupt renames all non-preserved WASM exports by default.
// This teaching fixture keeps mix/seal on purpose (explicit ABI) and opts into
// the lane-independent gate that bla_lint_lanes / harden now refuse by default.
const report = hardenProject({
directory: stage,
intensity: INTENSITY,
@@ -161,6 +164,8 @@ export async function hardenChallenge({ key, flag, outDir, seed = SEED }) {
llmDirectives: false,
emitManifest: false,
outputDirectory: hardened,
wasmPreserveExports: ["mix", "seal"],
allowLaneIndependentGates: true,
});
if (!report.overallSuccess) {
throw new Error(`hardenProject failed: ${JSON.stringify(report.artifacts?.map((a) => [a.relativePath, a.success, a.error]))}`);
+10
View File
@@ -39,10 +39,20 @@ function tsharkVersion(env) {
async function main() {
if (!reaDistReady()) {
// Honest agent-facing status: exit 0 keeps CI green when REA is optional,
// but never imply a red-team pass. MCP bla_redteam_report uses the same word.
console.log(
"SKIP: sibling REA dist not ready (expected at ../rea or $REA_ROOT). " +
"Red-team empirical gates require a local REA checkout; CI skips when absent.",
);
console.log(
JSON.stringify({
schema: "bla-redteam-rea/v1",
status: "unverified",
reason:
"Sibling REA dist not ready — empirical redteam:rea did not run (not a pass).",
}),
);
process.exit(0);
}
const tshark = resolveTsharkEnv();
+23
View File
@@ -42,3 +42,26 @@ try {
} catch (err) {
console.warn(`Skipped package-lock.json sync: ${err instanceof Error ? err.message : String(err)}`);
}
// Keep CrackMe SEAL blaVersion labels in lockstep with package.json (CI
// v7-seal rejects seal.blaVersion !== package.json.version). Digests stay
// untouched — only the version metadata field is rewritten.
for (const rel of ["challenge/v6/SEAL.json", "challenge/v7/SEAL.json"]) {
const sealPath = resolve(root, rel);
try {
const sealText = readFileSync(sealPath, "utf8");
const next = sealText.replace(
/"blaVersion"\s*:\s*"[^"]+"/,
`"blaVersion": "${version}"`,
);
if (next !== sealText) {
writeFileSync(sealPath, next, "utf8");
console.log(`Synced ${rel} blaVersion -> ${version}`);
} else {
console.log(`${rel} blaVersion already at ${version}`);
}
} catch (err) {
console.warn(`Skipped ${rel}: ${err instanceof Error ? err.message : String(err)}`);
}
}
+373 -8
View File
@@ -12,6 +12,17 @@ import { verifyTarget } from "./engine/verifier.js";
import { defendTarget } from "./engine/defender.js";
import { formatHardenProjectReport, hardenProject } from "./engine/harden.js";
import { lintLaneIndependence } from "./engine/lane-independence-lint.js";
import { lintSealCommitmentFile } from "./engine/seal-commitment-lint.js";
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 { lintWasmSealXorKnownPlaintextFile } from "./engine/wasm-seal-xor-known-plaintext-lint.js";
import {
scanPackagingGates,
formatPackagingGatesReport,
} from "./engine/packaging-gates.js";
import { runShowcaseBenchmark } from "./engine/benchmark.js";
import {
emitCompileTimeNativeHeader,
@@ -51,7 +62,15 @@ Commands:
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
lint-lanes <file> Heuristic warn if gate code looks lane-independent (issue #40.1)
lint [dir] DEFAULT packaging gate scan (all R1–R7 refuse lints + lanes/panel); exit 2 on refuse
lint-lanes <file> Heuristic ERROR if gate code looks lane-independent (issue #40.1); exit 2
lint-wasm-params <file> Heuristic ERROR if WASM embeds clear R3PARM/R3CIPH/R2SEAL-class carriers; exit 2
lint-panel-derive <file> Heuristic ERROR if stable __vaultPanelDerive_* / deriveLocal oracle remains; exit 2
lint-js-aes-unwrap <file> Heuristic ERROR if JS AES wrap-key + create*iv + fixed hdr unwrap; exit 2
lint-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 2
lint-wasm-seal-xor-known-plaintext <wasm> Heuristic ERROR if seal.revision is XOR known-plaintext in WASM pack; exit 2
lint-seal <file> Heuristic lint for plaintext/reversible seal sidecars (red-blue round-2); exit 2 on error
protect <target> Inject multi-layer Counter-REA adversarial shield
verify <target> [original] Verify Counter-REA defense invariants & token amplification
benchmark Run the 14-target Counter-REA Showcase Benchmark suite
@@ -72,10 +91,15 @@ Options:
--weave-decoys Opt-in structural weave decoys (Python customer-def / .pyc co_consts weave; JS AST weave already on); OFF by default
--self-seal Opt-in self-seal / sibling-module integrity binding for JS/Node targets (issue #40.5); OFF by default
--wasm-preserve-exports <a,b> Comma-separated WASM export names to keep as public ABI (issue #40.3)
--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
--allow-wasm-seal-xor-known-plaintext Allow bankrupt despite seal.revision XOR known-plaintext packs (round-7); 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
--dry-run Preview planned setup changes without writing files
--dry-run Preview planned setup/harden changes without writing files
-y, --yes Approve setup actions without interactive confirmation
--json Emit structured JSON output
-v, --version Print BLA version
@@ -96,6 +120,15 @@ interface ParsedCliArgs {
readonly weaveDecoys: boolean;
readonly selfSeal: boolean;
readonly wasmPreserveExports: readonly string[];
readonly allowLaneIndependentGates: boolean;
readonly allowPlaintextSeal: boolean;
readonly allowWasmClearParamCarriers: boolean;
readonly allowStablePanelDeriveAbi: boolean;
readonly allowJsAesUnwrap: boolean;
readonly allowPanelOfflineOracle: boolean;
readonly allowJsWasmHydrateDump: boolean;
readonly allowWasmXorMaskSidecar: boolean;
readonly allowWasmSealXorKnownPlaintext: boolean;
readonly lang: NativeHeaderLanguage;
readonly clients: SupportedAgentClientId[];
readonly allDetected: boolean;
@@ -122,6 +155,15 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
let weaveDecoys = false;
let selfSeal = false;
let wasmPreserveExports: string[] = [];
let allowLaneIndependentGates = false;
let allowPlaintextSeal = false;
let allowWasmClearParamCarriers = false;
let allowStablePanelDeriveAbi = false;
let allowJsAesUnwrap = false;
let allowJsWasmHydrateDump = false;
let allowWasmXorMaskSidecar = false;
let allowWasmSealXorKnownPlaintext = false;
let allowPanelOfflineOracle = false;
let lang: NativeHeaderLanguage = "c";
const clients: SupportedAgentClientId[] = [];
let allDetected = false;
@@ -162,6 +204,24 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
weaveDecoys = true;
} else if (arg === "--self-seal") {
selfSeal = true;
} else if (arg === "--allow-lane-independent") {
allowLaneIndependentGates = true;
} else if (arg === "--allow-plaintext-seal") {
allowPlaintextSeal = true;
} else if (arg === "--allow-wasm-clear-params") {
allowWasmClearParamCarriers = true;
} else if (arg === "--allow-stable-panel-derive") {
allowStablePanelDeriveAbi = true;
} else if (arg === "--allow-js-aes-unwrap") {
allowJsAesUnwrap = true;
} else if (arg === "--allow-panel-offline-oracle") {
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 === "--allow-wasm-seal-xor-known-plaintext") {
allowWasmSealXorKnownPlaintext = true;
} else if (arg.startsWith("--wasm-preserve-exports=")) {
wasmPreserveExports = arg
.slice("--wasm-preserve-exports=".length)
@@ -217,6 +277,15 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
weaveDecoys,
selfSeal,
wasmPreserveExports,
allowLaneIndependentGates,
allowPlaintextSeal,
allowWasmClearParamCarriers,
allowStablePanelDeriveAbi,
allowJsAesUnwrap,
allowPanelOfflineOracle,
allowJsWasmHydrateDump,
allowWasmXorMaskSidecar,
allowWasmSealXorKnownPlaintext,
lang,
clients,
allDetected,
@@ -325,15 +394,19 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
const explicitIntensity = argv.includes("--intensity")
? parsed.intensity
: (loaded.config.intensity ?? "bankrupt");
const resolved = resolveProjectSeed(
typeof directory === "string" ? directory : process.cwd(),
parsed.seed,
parsed.configPath,
);
// Dry-run must write zero bytes: skip seed persistence into .blarc.
const seed = parsed.dryRun
? parsed.seed
: resolveProjectSeed(
typeof directory === "string" ? directory : process.cwd(),
parsed.seed,
parsed.configPath,
).seed;
const report = hardenProject({
directory,
intensity: explicitIntensity,
seed: resolved.seed,
...(seed !== undefined ? { seed } : {}),
dryRun: parsed.dryRun,
emitManifest: parsed.manifest || loaded.config.emitManifest === true,
llmDirectives: parsed.llmDirectives || loaded.config.llmDirectives === true,
weaveDecoys: parsed.weaveDecoys || loaded.config.weaveDecoys === true,
@@ -344,6 +417,33 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
const merged = [...new Set([...fromCfg, ...fromCli])];
return merged.length > 0 ? { wasmPreserveExports: merged } : {};
})()),
allowLaneIndependentGates:
parsed.allowLaneIndependentGates ||
loaded.config.allowLaneIndependentGates === true,
allowPlaintextSeal:
parsed.allowPlaintextSeal ||
loaded.config.allowPlaintextSeal === true,
allowWasmClearParamCarriers:
parsed.allowWasmClearParamCarriers ||
loaded.config.allowWasmClearParamCarriers === true,
allowStablePanelDeriveAbi:
parsed.allowStablePanelDeriveAbi ||
loaded.config.allowStablePanelDeriveAbi === true,
allowJsAesUnwrap:
parsed.allowJsAesUnwrap ||
loaded.config.allowJsAesUnwrap === true,
allowPanelOfflineOracle:
parsed.allowPanelOfflineOracle ||
loaded.config.allowPanelOfflineOracle === true,
allowJsWasmHydrateDump:
parsed.allowJsWasmHydrateDump ||
loaded.config.allowJsWasmHydrateDump === true,
allowWasmXorMaskSidecar:
parsed.allowWasmXorMaskSidecar ||
loaded.config.allowWasmXorMaskSidecar === true,
allowWasmSealXorKnownPlaintext:
parsed.allowWasmSealXorKnownPlaintext ||
loaded.config.allowWasmSealXorKnownPlaintext === true,
...(parsed.output !== undefined ? { outputDirectory: parsed.output } : {}),
});
if (parsed.json) {
@@ -351,6 +451,7 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
} else {
console.log(formatHardenProjectReport(report));
}
if (report.dryRun) return report.discoveredCount === 0 ? 2 : 0;
return report.overallSuccess || report.discoveredCount === 0 ? (report.discoveredCount === 0 ? 2 : 0) : 2;
}
@@ -383,6 +484,33 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
const merged = [...new Set([...fromCfg, ...fromCli])];
return merged.length > 0 ? { wasmPreserveExports: merged } : {};
})()),
allowLaneIndependentGates:
parsed.allowLaneIndependentGates ||
loaded.config.allowLaneIndependentGates === true,
allowPlaintextSeal:
parsed.allowPlaintextSeal ||
loaded.config.allowPlaintextSeal === true,
allowWasmClearParamCarriers:
parsed.allowWasmClearParamCarriers ||
loaded.config.allowWasmClearParamCarriers === true,
allowStablePanelDeriveAbi:
parsed.allowStablePanelDeriveAbi ||
loaded.config.allowStablePanelDeriveAbi === true,
allowJsAesUnwrap:
parsed.allowJsAesUnwrap ||
loaded.config.allowJsAesUnwrap === true,
allowPanelOfflineOracle:
parsed.allowPanelOfflineOracle ||
loaded.config.allowPanelOfflineOracle === true,
allowJsWasmHydrateDump:
parsed.allowJsWasmHydrateDump ||
loaded.config.allowJsWasmHydrateDump === true,
allowWasmXorMaskSidecar:
parsed.allowWasmXorMaskSidecar ||
loaded.config.allowWasmXorMaskSidecar === true,
allowWasmSealXorKnownPlaintext:
parsed.allowWasmSealXorKnownPlaintext ||
loaded.config.allowWasmSealXorKnownPlaintext === true,
});
if (parsed.sarif) {
console.log(
@@ -400,6 +528,41 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
return report.overallSuccess ? 0 : 2;
}
case "lint": {
const target = parsed.positionals[0] ?? ".";
const report = scanPackagingGates({
directory: resolve(target),
intensity: (parsed.intensity as "stealth" | "balanced" | "maximum" | "bankrupt") ?? "bankrupt",
allowPlaintextSeal: parsed.allowPlaintextSeal,
allowWasmClearParamCarriers: parsed.allowWasmClearParamCarriers,
allowJsAesUnwrap: parsed.allowJsAesUnwrap,
allowJsWasmHydrateDump: parsed.allowJsWasmHydrateDump,
allowWasmXorMaskSidecar: parsed.allowWasmXorMaskSidecar,
allowWasmSealXorKnownPlaintext: parsed.allowWasmSealXorKnownPlaintext,
allowLaneIndependentGates: parsed.allowLaneIndependentGates,
allowPanelOfflineOracle: parsed.allowPanelOfflineOracle,
allowStablePanelDeriveAbi: parsed.allowStablePanelDeriveAbi,
includeProtectTimeGates: true,
});
if (parsed.json) {
// Strip heavy details.details raw blobs for CLI JSON by default — keep findings/blocking.
const { details: _details, ...compact } = report;
console.log(JSON.stringify({ ...compact, detailCounts: {
seals: report.details.seals.length,
wasmParams: report.details.wasmParams.length,
jsAes: report.details.jsAes.length,
jsHydrateDump: report.details.jsHydrateDump.length,
wasmXorMask: report.details.wasmXorMask.length,
wasmSealXor: report.details.wasmSealXor.length,
lanes: report.details.lanes.length,
panelDerive: report.details.panelDerive.length,
} }, null, 2));
} else {
console.log(formatPackagingGatesReport(report));
}
return report.shouldRefuseBankrupt ? 2 : 0;
}
case "lint-lanes": {
const target = parsed.positionals[0];
if (!target) {
@@ -423,6 +586,181 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
}
return report.looksLaneIndependent ? 2 : 0;
}
case "lint-seal": {
const target = parsed.positionals[0];
if (!target) {
console.error("Error: Missing <file> path for `bla lint-seal <file>`.");
return 1;
}
const report = lintSealCommitmentFile(resolve(target));
if (parsed.json) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log(`BLA seal-commitment 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 "lint-wasm-params": {
const target = parsed.positionals[0];
if (!target) {
console.error("Error: Missing <file> path for `bla lint-wasm-params <file>`.");
return 1;
}
const report = lintWasmParamCarrierFile(resolve(target));
if (parsed.json) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log(`BLA wasm-param-carrier lint — ${report.path}`);
console.log(report.oneLineAdvice);
for (const f of report.findings) {
console.log(` [${f.severity}] ${f.id}: ${f.summary} @${f.offset}`);
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 "lint-panel-derive": {
const target = parsed.positionals[0];
if (!target) {
console.error("Error: Missing <file> path for `bla lint-panel-derive <file>`.");
return 1;
}
const report = lintPanelDeriveAbiFile(resolve(target));
if (parsed.json) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log(`BLA panel-derive ABI 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.shouldRewriteOrRefuse ||
report.findings.some((f) => f.severity === "error")
? 2
: 0;
}
case "lint-js-aes-unwrap": {
const target = parsed.positionals[0];
if (!target) {
console.error("Error: Missing <file> path for `bla lint-js-aes-unwrap <file>`.");
return 1;
}
const report = lintJsAesUnwrapFile(resolve(target));
if (parsed.json) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log(`BLA js-aes-unwrap 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 "lint-js-wasm-hydrate-dump": {
const target = parsed.positionals[0];
if (!target) {
console.error("Error: Missing <file> path for `bla lint-js-wasm-hydrate-dump <file>`.");
return 1;
}
const report = lintJsWasmHydrateDumpFile(resolve(target));
if (parsed.json) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log(`BLA js-wasm-hydrate-dump 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 "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 "lint-wasm-seal-xor-known-plaintext": {
const target = parsed.positionals[0];
if (!target) {
console.error("Error: Missing <wasm> path for `bla lint-wasm-seal-xor-known-plaintext <wasm>`.");
return 1;
}
const sealArg = parsed.positionals[1];
const report = lintWasmSealXorKnownPlaintextFile(resolve(target), sealArg ? resolve(sealArg) : undefined);
if (parsed.json) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log(`BLA wasm-seal-xor-known-plaintext 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);
const target = parsed.positionals[0] ?? loaded.config.input;
@@ -469,6 +807,33 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
const merged = [...new Set([...fromCfg, ...fromCli])];
return merged.length > 0 ? { wasmPreserveExports: merged } : {};
})()),
allowLaneIndependentGates:
parsed.allowLaneIndependentGates ||
loaded.config.allowLaneIndependentGates === true,
allowPlaintextSeal:
parsed.allowPlaintextSeal ||
loaded.config.allowPlaintextSeal === true,
allowWasmClearParamCarriers:
parsed.allowWasmClearParamCarriers ||
loaded.config.allowWasmClearParamCarriers === true,
allowStablePanelDeriveAbi:
parsed.allowStablePanelDeriveAbi ||
loaded.config.allowStablePanelDeriveAbi === true,
allowJsAesUnwrap:
parsed.allowJsAesUnwrap ||
loaded.config.allowJsAesUnwrap === true,
allowPanelOfflineOracle:
parsed.allowPanelOfflineOracle ||
loaded.config.allowPanelOfflineOracle === true,
allowJsWasmHydrateDump:
parsed.allowJsWasmHydrateDump ||
loaded.config.allowJsWasmHydrateDump === true,
allowWasmXorMaskSidecar:
parsed.allowWasmXorMaskSidecar ||
loaded.config.allowWasmXorMaskSidecar === true,
allowWasmSealXorKnownPlaintext:
parsed.allowWasmSealXorKnownPlaintext ||
loaded.config.allowWasmSealXorKnownPlaintext === true,
});
if (parsed.json) console.log(JSON.stringify(res, null, 2));
else console.log(formatProtectionResult(res));
+17
View File
@@ -22,6 +22,23 @@ export interface BlaProjectConfig {
readonly selfSeal?: boolean;
/** WASM export names that must remain the public ABI when export rename runs (issue #40.3). */
readonly wasmPreserveExports?: readonly string[];
/** When true, allow harden/defend of lane-independent JS gates (issue #40.1). Default false. */
readonly allowLaneIndependentGates?: boolean;
/** When true, allow bankrupt harden despite plaintext/reversible seal sidecars (red-blue round-2). Default false. */
readonly allowPlaintextSeal?: boolean;
/** When true, allow bankrupt despite clear WASM param/cipher carriers (red-blue round-3). Default false. */
readonly allowWasmClearParamCarriers?: boolean;
/** When true, keep stable __vaultPanelDerive_* ABI (red-blue round-3). Default false. */
readonly allowStablePanelDeriveAbi?: boolean;
/** When true, allow bankrupt despite JS AES wrap-key unwrap footguns (red-blue round-4). Default false. */
readonly allowJsAesUnwrap?: boolean;
/** When true, allow bankrupt despite panel offline-oracle packaging (red-blue round-4). Default false. */
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;
/** When true, allow bankrupt despite seal.revision XOR known-plaintext packs (red-blue round-7). Default false. */
readonly allowWasmSealXorKnownPlaintext?: boolean;
}
/**
+50 -1
View File
@@ -171,9 +171,54 @@ export interface ProtectionOptions {
readonly selfSeal?: boolean;
/**
* WASM public ABI export names to keep when rename runs (issue #40.3).
* Other / internal-looking exports may be renamed at maximum/bankrupt.
* At maximum/bankrupt every non-listed export is renamed by default —
* preserving a stable ABI requires an explicit list.
*/
readonly wasmPreserveExports?: readonly string[];
/**
* When true, allow protecting JS/TS that looks lane-independent (issue #40.1).
* Default false: protect/defend/harden refuse such gates (red-blue round-1).
*/
readonly allowLaneIndependentGates?: boolean;
/**
* When true, allow bankrupt harden/protect despite plaintext/reversible seal
* sidecars (red-blue round-2). Default false — refuse.
*/
readonly allowPlaintextSeal?: boolean;
/**
* When true, allow bankrupt harden/protect despite clear WASM param/cipher
* ASCII carriers (R3PARM/R3CIPH/R2SEAL-class; red-blue round-3). Default false — refuse.
*/
readonly allowWasmClearParamCarriers?: boolean;
/**
* When true, keep stable `__vaultPanelDerive_*` ABI (skip rewrite/refuse).
* Default false — maximum/bankrupt rewrite to seed-stable `_blaPd_*` (red-blue round-3).
*/
readonly allowStablePanelDeriveAbi?: boolean;
/**
* When true, allow bankrupt harden/protect despite JS AES wrap-key +
* create*iv + fixed sealed-hdr unwrap footguns (red-blue round-4). Default false — refuse.
* This is a gate only — not white-box AES.
*/
readonly allowJsAesUnwrap?: boolean;
/**
* When true, allow bankrupt harden/protect despite panel deriveLocal +
* plaintext panelTokenSha256 offline-oracle packaging (red-blue round-4). Default false — refuse.
*/
readonly allowPanelOfflineOracle?: boolean;
/**
* When true, allow bankrupt harden/protect despite JS←WASM hydrate memory
* 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;
readonly allowWasmSealXorKnownPlaintext?: 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.
*/
readonly selfSealSiblingPaths?: readonly string[];
}
export interface ProtectionMetrics {
@@ -203,6 +248,10 @@ export interface ProtectionResult {
readonly selfSeal?: boolean;
/** Present when WASM export rename actually rewrote at least one non-preserved export (#40.3). */
readonly wasmExportRenameApplied?: boolean;
/** Present when WASM export-section order was seed-shuffled (red-blue round-11). */
readonly wasmExportOrderShuffled?: boolean;
/** Count of long-name decoy export aliases injected (red-blue round-10/12 hygiene). */
readonly wasmExportDecoysInjected?: number;
readonly seed: string;
readonly originalSha256: string;
readonly protectedSha256: string;
+75
View File
@@ -15,6 +15,11 @@ import type {
} from "../core/types.js";
import { unpackAsarBuffer } from "../shields/formats/asar.js";
import { inspectWasmBinary } from "../shields/formats/wasm.js";
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";
@@ -488,6 +493,48 @@ export function auditTarget(targetPath: string): AuditReport {
const res = analyzeJsSourceForAudit(text, basename(absPath));
sim = res.sim;
exposedItems.push(...res.exposed);
const panelLint = lintPanelDeriveAbiSource(text, { path: absPath });
for (const f of panelLint.findings) {
exposedItems.push({
id: `panel_derive_${f.id}`,
name: f.id,
kind: "export",
location: basename(absPath),
riskLevel: f.severity === "error" ? "high" : "medium",
reaToolUsed: "bla lint-panel-derive / static source scan",
estimatedTokensToReconstruct: 1_200,
estimatedCostUsd: 0.05,
reason: f.summary,
});
}
const aesLint = lintJsAesUnwrapSource(text, { path: absPath });
for (const f of aesLint.findings) {
exposedItems.push({
id: `js_aes_${f.id}`,
name: f.id,
kind: "export",
location: basename(absPath),
riskLevel: f.severity === "error" ? "high" : "medium",
reaToolUsed: "bla lint-js-aes-unwrap / static source scan",
estimatedTokensToReconstruct: 1_500,
estimatedCostUsd: 0.06,
reason: f.summary,
});
}
const hydrateDumpLint = lintJsWasmHydrateDumpSource(text, { path: absPath });
for (const f of hydrateDumpLint.findings) {
exposedItems.push({
id: `js_wasm_hydrate_${f.id}`,
name: f.id,
kind: "export",
location: basename(absPath),
riskLevel: f.severity === "error" ? "high" : "medium",
reaToolUsed: "bla lint-js-wasm-hydrate-dump / static source scan",
estimatedTokensToReconstruct: 1_600,
estimatedCostUsd: 0.06,
reason: f.summary,
});
}
res.vectors.forEach((v) => vulnerableVectors.add(v));
} else if (format === "html-bundle") {
const htmlText = rawBytes.toString("utf8");
@@ -647,6 +694,34 @@ export function auditTarget(targetPath: string): AuditReport {
: "Unshielded WASM export directly decompilable to WAT by REA",
});
}
const parmLint = lintWasmParamCarrierBuffer(rawBytes, { path: absPath });
for (const f of parmLint.findings) {
exposedItems.push({
id: `wasm_parm_${f.magic}_${f.offset}`,
name: f.magic,
kind: "metadata-section",
location: `${basename(absPath)} (data @${f.offset})`,
riskLevel: "high",
reaToolUsed: "bla lint-wasm-params / static data-section scan",
estimatedTokensToReconstruct: 4_500,
estimatedCostUsd: 0.25,
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",
+12 -2
View File
@@ -236,8 +236,18 @@ export async function runShowcaseBenchmark(): Promise<BenchmarkReport> {
const origInst = new WebAssembly.Instance(origMod);
const protInst = new WebAssembly.Instance(protMod);
const origFn = origInst.exports.computeDigest as (a: number, b: number) => number;
const protFn = protInst.exports.computeDigest as (a: number, b: number) => number;
const functionalOk = validWasm && origFn(17, 29) === protFn(17, 29);
// Bankrupt renames non-preserved ABI by default (red-blue round-1); resolve
// the live export (decoy aliases share the same func index).
const protExportTable = protInst.exports as Record<string, unknown>;
const protFn = (
typeof protExportTable.computeDigest === "function"
? protExportTable.computeDigest
: Object.values(protExportTable).find((v) => typeof v === "function")
) as ((a: number, b: number) => number) | undefined;
const functionalOk =
validWasm &&
typeof protFn === "function" &&
origFn(17, 29) === protFn(17, 29);
cases.push(buildCaseResult("wasm-core", "WebAssembly Crypto Kernel (.wasm)", "REA inspect_wasm_artifact", res, functionalOk));
}
+46
View File
@@ -29,6 +29,25 @@ export interface OneClickDefenseOptions {
readonly selfSeal?: boolean;
/** WASM public ABI export names to preserve when rename runs (issue #40.3). */
readonly wasmPreserveExports?: readonly string[];
/** Allow lane-independent JS gates (issue #40.1). Default false. */
readonly allowLaneIndependentGates?: boolean;
/** Allow bankrupt despite plaintext/reversible seal sidecars (red-blue round-2). Default false. */
readonly allowPlaintextSeal?: boolean;
/** Allow bankrupt despite clear WASM param/cipher carriers (red-blue round-3). Default false. */
readonly allowWasmClearParamCarriers?: boolean;
/** Keep stable __vaultPanelDerive_* ABI (red-blue round-3). Default false — rewrite. */
readonly allowStablePanelDeriveAbi?: boolean;
/** Allow bankrupt despite JS AES wrap-key unwrap footguns (red-blue round-4). Default false. */
readonly allowJsAesUnwrap?: boolean;
/** Allow bankrupt despite panel offline-oracle packaging (red-blue round-4). Default false. */
readonly allowPanelOfflineOracle?: boolean;
/** Allow bankrupt despite JS←WASM hydrate param-dump (red-blue round-5). Default false. */
readonly allowJsWasmHydrateDump?: boolean;
readonly allowWasmXorMaskSidecar?: boolean;
/** Allow bankrupt despite seal.revision XOR known-plaintext packs (red-blue round-7). Default false. */
readonly allowWasmSealXorKnownPlaintext?: boolean;
/** Sibling paths forwarded into self-seal when enabled (multi-artifact harden). */
readonly selfSealSiblingPaths?: readonly string[];
}
export interface OneClickDefenseStageSummary {
@@ -120,6 +139,33 @@ export function defendTarget(options: OneClickDefenseOptions): OneClickDefenseRe
...(options.wasmPreserveExports !== undefined && options.wasmPreserveExports.length > 0
? { wasmPreserveExports: options.wasmPreserveExports }
: {}),
...(options.allowLaneIndependentGates === true
? { allowLaneIndependentGates: true }
: {}),
...(options.allowPlaintextSeal === true ? { allowPlaintextSeal: true } : {}),
...(options.allowWasmClearParamCarriers === true
? { allowWasmClearParamCarriers: true }
: {}),
...(options.allowStablePanelDeriveAbi === true
? { allowStablePanelDeriveAbi: true }
: {}),
...(options.allowJsAesUnwrap === true ? { allowJsAesUnwrap: true } : {}),
...(options.allowPanelOfflineOracle === true
? { allowPanelOfflineOracle: true }
: {}),
...(options.allowJsWasmHydrateDump === true
? { allowJsWasmHydrateDump: true }
: {}),
...(options.allowWasmXorMaskSidecar === true
? { allowWasmXorMaskSidecar: true }
: {}),
...(options.allowWasmSealXorKnownPlaintext === true
? { allowWasmSealXorKnownPlaintext: true }
: {}),
...(options.selfSealSiblingPaths !== undefined &&
options.selfSealSiblingPaths.length > 0
? { selfSealSiblingPaths: options.selfSealSiblingPaths }
: {}),
honeySourceMaps: true,
});
+399 -30
View File
@@ -13,6 +13,32 @@ import {
defendTarget,
type OneClickDefenseReport,
} from "./defender.js";
import {
sealCommitmentRefuseMessage,
} from "./seal-commitment-lint.js";
import {
wasmParamCarrierRefuseMessage,
} from "./wasm-param-carrier-lint.js";
import {
jsAesUnwrapRefuseMessage,
} from "./js-aes-unwrap-lint.js";
import {
jsWasmHydrateDumpRefuseMessage,
} from "./js-wasm-hydrate-dump-lint.js";
import {
wasmXorMaskSidecarRefuseMessage,
} from "./wasm-xor-mask-sidecar-lint.js";
import {
wasmSealXorKnownPlaintextRefuseMessage,
} from "./wasm-seal-xor-known-plaintext-lint.js";
import {
evaluateHardenProjectPackagingBlocks,
} from "./packaging-gates.js";
import {
computeHardenRunId,
HARDEN_SUMMARY_FILE_NAME,
HARDEN_SUMMARY_SCHEMA,
} from "./run-evidence.js";
/** Preferred build-output directory names, searched first under a project root. */
export const BLA_BUILD_OUTPUT_DIR_NAMES = Object.freeze([
@@ -81,6 +107,8 @@ export interface HardenArtifactSummary {
readonly defenseScore: number;
readonly tokenAmplificationFactor: number;
readonly costAmplificationFactor: number;
/** True when a file already existed at outputPath before this run (or would, in dry-run). */
readonly outputExisted: boolean;
readonly error?: string;
}
@@ -96,9 +124,30 @@ export interface HardenProjectOptions {
readonly selfSeal?: boolean;
/** WASM public ABI export names to preserve when rename runs (issue #40.3). */
readonly wasmPreserveExports?: readonly string[];
/** Allow lane-independent JS gates (issue #40.1). Default false — refuse. */
readonly allowLaneIndependentGates?: boolean;
/** Allow bankrupt despite plaintext/reversible seal sidecars (red-blue round-2). Default false — refuse. */
readonly allowPlaintextSeal?: boolean;
/** Allow bankrupt despite clear WASM param/cipher carriers (red-blue round-3). Default false — refuse. */
readonly allowWasmClearParamCarriers?: boolean;
/** Keep stable __vaultPanelDerive_* ABI (red-blue round-3). Default false — rewrite. */
readonly allowStablePanelDeriveAbi?: boolean;
/** Allow bankrupt despite JS AES wrap-key unwrap footguns (red-blue round-4). Default false. */
readonly allowJsAesUnwrap?: boolean;
/** Lab-only: allow JS←WASM hydrate memory dump of salt/rounds/cipher (red/blue r5). */
readonly allowJsWasmHydrateDump?: boolean;
readonly allowWasmXorMaskSidecar?: boolean;
readonly allowWasmSealXorKnownPlaintext?: 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`. */
readonly outputDirectory?: string;
readonly maxArtifacts?: number;
/**
* Preview only: discover targets and plan output paths, but write zero bytes
* (no `.bla-hardened/`, no summary JSON, no manifests).
*/
readonly dryRun?: boolean;
}
export interface HardenProjectReport {
@@ -114,6 +163,36 @@ export interface HardenProjectReport {
readonly oneSentenceUsage: string;
readonly weaveDecoys: boolean;
readonly selfSeal: boolean;
/**
* True when bankrupt discovered a multi-artifact JS/WASM/HTML tree and
* `selfSeal` was not enabled — agents should pass `self_seal: true`.
* Never auto-enables for single-file trees.
*/
readonly selfSealRecommended: boolean;
/** Short advice when selfSealRecommended is true. */
readonly selfSealRecommendation?: string;
/** True when this report is a zero-write preview. */
readonly dryRun: boolean;
/** True when discovery stopped at `maxArtifacts`; more targets exist. */
readonly truncated: boolean;
readonly maxArtifacts: number;
/** Planned/actual outputs that already existed before this run. */
readonly wouldOverwrite: readonly string[];
/**
* Content-addressed id for this harden run (unsigned). Stable across identical
* inputs/planned outputs; present even on dry-run so agents can correlate later.
*/
readonly runId: string;
/** Absolute path of the unsigned summary when written; omitted on dry-run. */
readonly summaryPath?: string;
}
export interface HardenDiscoveryResult {
readonly directory: string;
readonly artifacts: readonly DiscoveredArtifact[];
/** True when the walk hit `maxArtifacts` and further targets were not listed. */
readonly truncated: boolean;
readonly maxArtifacts: number;
}
function isProtectableFormat(format: ArtifactFormat): boolean {
@@ -207,8 +286,32 @@ export function discoverHardenableArtifacts(
directory: string = process.cwd(),
options: { readonly maxArtifacts?: number } = {},
): readonly DiscoveredArtifact[] {
return discoverHardenTargets(directory, options).artifacts;
}
/**
* Read-only discovery that also reports truncation, so agents never mistake a
* capped walk for the full inventory of a large repository.
*/
export function discoverHardenTargets(
directory: string = process.cwd(),
options: { readonly maxArtifacts?: number } = {},
): HardenDiscoveryResult {
const abs = resolve(directory);
const maxArtifacts = options.maxArtifacts ?? MAX_DISCOVERED_ARTIFACTS;
const maxArtifacts = Math.max(1, Math.floor(options.maxArtifacts ?? MAX_DISCOVERED_ARTIFACTS));
const all = collectHardenableArtifacts(abs, maxArtifacts + 1);
return {
directory: abs,
artifacts: all.slice(0, maxArtifacts),
truncated: all.length > maxArtifacts,
maxArtifacts,
};
}
function collectHardenableArtifacts(
abs: string,
maxArtifacts: number,
): readonly DiscoveredArtifact[] {
if (!existsSync(abs)) {
throw new Error(`Path not found: ${abs}`);
}
@@ -243,17 +346,10 @@ export function discoverHardenableArtifacts(
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 });
/** Mirror-tree destination under the output root (pure; no filesystem writes). */
function planArtifactOutputPath(artifact: DiscoveredArtifact, outputRoot: string): string {
// Keep original basename; place under .bla-hardened mirror tree.
return dest;
return join(outputRoot, artifact.relativePath);
}
/**
@@ -272,20 +368,225 @@ export function hardenProject(
const emitManifest = options.emitManifest === true;
const maxArtifacts = options.maxArtifacts ?? MAX_DISCOVERED_ARTIFACTS;
const discovered = discoverHardenableArtifacts(absDir, { maxArtifacts });
const dryRun = options.dryRun === true;
const discovery = discoverHardenTargets(absDir, { maxArtifacts });
const discovered = discovery.artifacts;
const packagingBlocks = evaluateHardenProjectPackagingBlocks({
directory: absDir,
intensity,
allowPlaintextSeal: options.allowPlaintextSeal,
allowWasmClearParamCarriers: options.allowWasmClearParamCarriers,
allowJsAesUnwrap: options.allowJsAesUnwrap,
allowJsWasmHydrateDump: options.allowJsWasmHydrateDump,
allowWasmXorMaskSidecar: options.allowWasmXorMaskSidecar,
allowWasmSealXorKnownPlaintext: options.allowWasmSealXorKnownPlaintext,
});
const blockingSeals = packagingBlocks.blockingSeals;
const blockingWasmParms = packagingBlocks.blockingWasmParms;
const blockingJsAes = packagingBlocks.blockingJsAes;
const blockingJsHydrateDump = packagingBlocks.blockingJsHydrateDump;
const blockingWasmXorMask = packagingBlocks.blockingWasmXorMask;
const blockingWasmSealXor = packagingBlocks.blockingWasmSealXor;
const outputRoot = resolve(
options.outputDirectory ??
(statSync(absDir).isDirectory()
? join(absDir, ".bla-hardened")
: join(dirname(absDir), ".bla-hardened")),
);
let plannedOutputs = discovered.map((artifact) => {
const outputPath = planArtifactOutputPath(artifact, outputRoot);
return { artifact, outputPath, outputExisted: existsSync(outputPath) };
});
// When self-seal is on, protect non-JS bindable siblings first so JS entry
// modules can embed expected SHA-256 hard-fail hashes (red/blue round-4).
if (options.selfSeal === true) {
const jsLike = new Set(["javascript", "typescript"]);
plannedOutputs = [
...plannedOutputs.filter((p) => !jsLike.has(p.artifact.format)),
...plannedOutputs.filter((p) => jsLike.has(p.artifact.format)),
];
}
const wouldOverwrite = plannedOutputs.filter((p) => p.outputExisted).map((p) => p.outputPath);
const bindableFormats = new Set(["javascript", "typescript", "wasm", "html-bundle"]);
const bindable = discovered.filter((a) => bindableFormats.has(a.format));
const selfSealRecommended =
intensity === "bankrupt" &&
bindable.length >= 2 &&
options.selfSeal !== true;
const selfSealRecommendation = selfSealRecommended
? "Multi-artifact entitlement tree detected — pass self_seal / --self-seal so Node entry modules bind sibling JS/WASM/HTML bytes. Single-file trees stay opt-in only (never auto-enabled)."
: undefined;
const runId = computeHardenRunId({
blaVersion: BLA_IDENTITY.version,
directory: absDir,
intensity,
weaveDecoys: options.weaveDecoys === true,
selfSeal: options.selfSeal === true,
artifacts: plannedOutputs.map(({ artifact, outputPath }) => ({
relativePath: artifact.relativePath,
format: artifact.format,
outputPath,
})),
});
const reportBase = {
blaVersion: BLA_IDENTITY.version,
directory: absDir,
intensity,
discoveredCount: discovered.length,
outputDirectory: outputRoot,
oneSentenceUsage:
'Harden my software against REA — call bla_harden with { "directory": "." } (or `bla harden .`).',
weaveDecoys: options.weaveDecoys === true,
selfSeal: options.selfSeal === true,
selfSealRecommended,
...(selfSealRecommendation !== undefined
? { selfSealRecommendation }
: {}),
dryRun,
truncated: discovery.truncated,
maxArtifacts: discovery.maxArtifacts,
wouldOverwrite,
runId,
} as const;
if (blockingSeals.length > 0 || blockingWasmParms.length > 0 || blockingJsAes.length > 0 || blockingJsHydrateDump.length > 0 || blockingWasmXorMask.length > 0 || blockingWasmSealXor.length > 0) {
const sealArtifacts = blockingSeals.map((r) => ({
inputPath: r.path,
relativePath: (relative(absDir, r.path) || basename(r.path)).split(sep).join("/"),
format: "unknown" as const,
outputPath: r.path,
success: false,
defenseScore: 0,
tokenAmplificationFactor: 0,
costAmplificationFactor: 0,
outputExisted: false,
error: sealCommitmentRefuseMessage(r, r.path),
}));
const wasmArtifacts = blockingWasmParms.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: wasmParamCarrierRefuseMessage(r, r.path),
}));
const jsAesArtifacts = blockingJsAes.map((r) => ({
inputPath: r.path,
relativePath: (relative(absDir, r.path) || basename(r.path)).split(sep).join("/"),
format: "javascript" as const,
outputPath: r.path,
success: false,
defenseScore: 0,
tokenAmplificationFactor: 0,
costAmplificationFactor: 0,
outputExisted: false,
error: jsAesUnwrapRefuseMessage(r, r.path),
}));
const jsHydrateDumpArtifacts = blockingJsHydrateDump.map((r) => ({
inputPath: r.path,
relativePath: (relative(absDir, r.path) || basename(r.path)).split(sep).join("/"),
format: "javascript" as const,
outputPath: r.path,
success: false,
defenseScore: 0,
tokenAmplificationFactor: 0,
costAmplificationFactor: 0,
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 wasmSealXorArtifacts = blockingWasmSealXor.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: wasmSealXorKnownPlaintextRefuseMessage(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");
if (blockingWasmSealXor.length > 0) blockParts.push("WASM seal.revision XOR known-plaintext");
const blockReason = `skipped: ${blockParts.join(" / ")} blocked bankrupt harden`;
const blockedExtras = [...sealArtifacts, ...wasmArtifacts, ...jsAesArtifacts, ...jsHydrateDumpArtifacts, ...wasmXorMaskArtifacts, ...wasmSealXorArtifacts];
return {
...reportBase,
overallSuccess: false,
hardenedCount: 0,
failedCount: blockedExtras.length,
artifacts: [
...plannedOutputs.map(({ artifact, outputPath, outputExisted }) => ({
inputPath: artifact.path,
relativePath: artifact.relativePath,
format: artifact.format,
outputPath,
success: false,
defenseScore: 0,
tokenAmplificationFactor: 0,
costAmplificationFactor: 0,
outputExisted,
error: blockReason,
})),
...blockedExtras,
],
};
}
if (dryRun) {
// Preview only: never claim overallSuccess — nothing was hardened.
return {
...reportBase,
overallSuccess: false,
hardenedCount: 0,
failedCount: 0,
artifacts: plannedOutputs.map(({ artifact, outputPath, outputExisted }) => ({
inputPath: artifact.path,
relativePath: artifact.relativePath,
format: artifact.format,
outputPath,
success: false,
defenseScore: 0,
tokenAmplificationFactor: 0,
costAmplificationFactor: 0,
outputExisted,
})),
};
}
if (discovered.length > 0) {
mkdirSync(outputRoot, { recursive: true });
}
const summaries: HardenArtifactSummary[] = [];
for (const artifact of discovered) {
const outputPath = deriveArtifactOutputPath(artifact, absDir, outputRoot);
for (const { artifact, outputPath, outputExisted } of plannedOutputs) {
mkdirSync(dirname(outputPath), { recursive: true });
try {
const report: OneClickDefenseReport = defendTarget({
inputPath: artifact.path,
@@ -305,6 +606,46 @@ export function hardenProject(
options.wasmPreserveExports.length > 0
? { wasmPreserveExports: options.wasmPreserveExports }
: {}),
...(options.allowLaneIndependentGates === true
? { allowLaneIndependentGates: true }
: {}),
...(options.allowPlaintextSeal === true ? { allowPlaintextSeal: true } : {}),
...(options.allowWasmClearParamCarriers === true
? { allowWasmClearParamCarriers: true }
: {}),
...(options.allowStablePanelDeriveAbi === true
? { allowStablePanelDeriveAbi: true }
: {}),
...(options.allowJsAesUnwrap === true ? { allowJsAesUnwrap: true } : {}),
...(options.allowJsWasmHydrateDump === true ? { allowJsWasmHydrateDump: true } : {}),
...(options.allowWasmXorMaskSidecar === true ? { allowWasmXorMaskSidecar: true } : {}),
...(options.allowWasmSealXorKnownPlaintext === true ? { allowWasmSealXorKnownPlaintext: true } : {}),
...(options.allowPanelOfflineOracle === true
? { allowPanelOfflineOracle: true }
: {}),
...((() => {
if (options.selfSeal !== true) return {};
const siblings = plannedOutputs
.filter(
(p) =>
p.outputPath !== outputPath &&
bindableFormats.has(p.artifact.format),
)
.map((p) => relative(dirname(outputPath), p.outputPath).split(sep).join("/"))
.filter((rel) => rel.length > 0 && !rel.startsWith(".."));
// Prefer same-directory / nested siblings; still pass upward-relative
// paths when the mirror tree places artifacts beside each other.
const loose = plannedOutputs
.filter(
(p) =>
p.outputPath !== outputPath &&
bindableFormats.has(p.artifact.format),
)
.map((p) => relative(dirname(outputPath), p.outputPath).split(sep).join("/"))
.filter((rel) => rel.length > 0);
const list = siblings.length > 0 ? siblings : loose;
return list.length > 0 ? { selfSealSiblingPaths: list } : {};
})()),
emitManifest,
});
summaries.push({
@@ -318,6 +659,7 @@ export function hardenProject(
report.exhaustionSummary.tokenAmplificationFactor,
costAmplificationFactor:
report.exhaustionSummary.costAmplificationFactor,
outputExisted,
});
} catch (err) {
summaries.push({
@@ -329,19 +671,24 @@ export function hardenProject(
defenseScore: 0,
tokenAmplificationFactor: 0,
costAmplificationFactor: 0,
outputExisted,
error: err instanceof Error ? err.message : String(err),
});
}
}
// Persist a project-level summary for agents to read back.
// Persist a project-level summary for agents to read back (unsigned).
let summaryPath: string | undefined;
if (discovered.length > 0) {
summaryPath = join(outputRoot, HARDEN_SUMMARY_FILE_NAME);
try {
writeFileSync(
join(outputRoot, "bla-harden-summary.json"),
summaryPath,
JSON.stringify(
{
schema: "bla-harden-summary/v1",
schema: HARDEN_SUMMARY_SCHEMA,
runId,
signature: "unsigned",
directory: absDir,
intensity,
weaveDecoys: options.weaveDecoys === true,
@@ -354,42 +701,62 @@ export function hardenProject(
"utf8",
);
} catch {
/* best-effort */
summaryPath = undefined;
}
}
const hardenedCount = summaries.filter((s) => s.success).length;
const failedCount = summaries.length - hardenedCount;
return {
blaVersion: BLA_IDENTITY.version,
directory: absDir,
intensity,
...reportBase,
overallSuccess: summaries.length > 0 && failedCount === 0,
discoveredCount: discovered.length,
hardenedCount,
failedCount,
outputDirectory: outputRoot,
artifacts: summaries,
oneSentenceUsage:
'Harden my software against REA — call bla_harden with { "directory": "." } (or `bla harden .`).',
weaveDecoys: options.weaveDecoys === true,
selfSeal: options.selfSeal === true,
...(summaryPath !== undefined ? { summaryPath } : {}),
};
}
export function formatHardenProjectReport(report: HardenProjectReport): string {
const lines: string[] = [
`BLA harden ${report.blaVersion} — ${report.directory}`,
`BLA harden ${report.blaVersion} — ${report.directory}${report.dryRun ? " (dry-run: nothing written)" : ""}`,
`Run: ${report.runId} (unsigned)`,
`Intensity: ${report.intensity} | discovered=${report.discoveredCount} hardened=${report.hardenedCount} failed=${report.failedCount}`,
`Overall: ${report.overallSuccess ? "SUCCESS" : report.discoveredCount === 0 ? "NO ARTIFACTS" : "PARTIAL/FAILED"}`,
`Overall: ${
report.dryRun
? report.discoveredCount === 0
? "NO ARTIFACTS"
: "DRY-RUN (nothing written)"
: report.overallSuccess
? "SUCCESS"
: report.discoveredCount === 0
? "NO ARTIFACTS"
: "PARTIAL/FAILED"
}`,
];
if (report.selfSealRecommended) {
lines.push(
` ⚠ self_seal recommended: ${report.selfSealRecommendation ?? "multi-artifact tree — pass --self-seal / self_seal:true"}`,
);
}
for (const a of report.artifacts) {
if (report.dryRun) {
lines.push(
` • ${a.relativePath} [${a.format}] → ${a.outputPath}${a.outputExisted ? " (exists; would overwrite)" : ""}`,
);
continue;
}
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.truncated) {
lines.push(
` ⚠ discovery truncated at ${report.maxArtifacts} artifacts; more targets exist (raise maxArtifacts or harden a narrower directory)`,
);
}
if (report.discoveredCount === 0) {
lines.push(
" (no protectable artifacts found — put build outputs under dist/, build/, out/, or release/, or place .wasm/.sqlite/.safetensors/binaries at the project root)",
@@ -397,7 +764,9 @@ export function formatHardenProjectReport(report: HardenProjectReport): string {
} else {
lines.push(`Output: ${report.outputDirectory}`);
lines.push(
"Next: ship or point your release at the hardened copies above (originals are untouched). See DISCLAIMER.md.",
report.dryRun
? "Next: re-run without --dry-run (MCP: dry_run=false) to write the hardened copies."
: "Next: ship or point your release at the hardened copies above (originals are untouched). See DISCLAIMER.md.",
);
}
lines.push(`Tip: ${report.oneSentenceUsage}`);
+364
View File
@@ -0,0 +1,364 @@
/**
* JS AES wrap-key / sealed-blob unwrap lint (red-blue round-4 residual).
*
* Detects the footgun where entitlement params live in an AES-sealed WASM
* (or similar) blob, but JS still holds hex/base64 wrap-key material and
* calls Node `createDecipheriv` / `createCipheriv` against a fixed magic
* header (e.g. `d17ea004`). Runtime instrumentation recovers the wrap key
* in one wrong-key run — this is NOT white-box AES.
*
* Bankrupt harden/protect refuses error findings unless
* `allowJsAesUnwrap` / `--allow-js-aes-unwrap` / `allow_js_aes_unwrap`.
*
* DEFENSIVE ONLY — no crack / key-recovery advice. Gate + honest leftover:
* moving unwrap into WASM / true white-box remains a follow-up.
*/
import { createHash } from "node:crypto";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { basename, join, resolve } from "node:path";
export const JS_AES_UNWRAP_SCHEMA = "bla-js-aes-unwrap-lint/v1" as const;
export type JsAesUnwrapFindingId =
| "js-aes-wrap-key-material"
| "js-aes-create-cipheriv"
| "js-aes-fixed-sealed-hdr"
| "js-aes-sealed-blob-unwrap";
export type JsAesUnwrapSeverity = "warning" | "error";
export interface JsAesUnwrapFinding {
readonly id: JsAesUnwrapFindingId;
readonly severity: JsAesUnwrapSeverity;
readonly summary: string;
readonly evidence: string;
}
export interface JsAesUnwrapReport {
readonly schema: typeof JS_AES_UNWRAP_SCHEMA;
readonly path: string;
readonly sha256Prefix: string;
readonly findings: readonly JsAesUnwrapFinding[];
readonly looksExposed: boolean;
/** True when bankrupt harden/protect should refuse (combo error). */
readonly shouldRefuseBankrupt: boolean;
readonly hasWrapKeyMaterial: boolean;
readonly hasCreateCipherIv: boolean;
readonly hasFixedSealedHdr: boolean;
readonly oneLineAdvice: string;
}
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_JS_FILES = 48;
const MAX_SCAN_CHARS = 800_000;
const CREATE_CIPHER_IV =
/\bcreate(?:Decipher|Cipher)iv\b|\.create(?:Decipher|Cipher)iv\s*\(/;
/** Hex/base64 wrap-key material shapes (R4 WRAP_KEY_HEX + Buffer.from(..., "hex")). */
const WRAP_KEY_NAME =
/\b(?:WRAP_KEY|AES_KEY|SEAL_KEY|UNWRAP_KEY|BLOB_KEY)(?:_HEX|_B64|_BASE64|_BYTES)?\b/;
const BUFFER_FROM_HEX_B64 =
/Buffer\.from\s*\(\s*[^,)]+?\s*,\s*['"](?:hex|base64)['"]\s*\)/;
/** AES-256 key as a 64-hex string literal (or AES-128 32-hex). */
const HEX_KEY_LITERAL = /['"][0-9a-fA-F]{32}(?:[0-9a-fA-F]{32})?['"]/;
const AES_ALGO =
/['"]aes-(?:128|192|256)-(?:ctr|cbc|gcm)['"]/i;
/** Fixed 4-byte sealed hdr beacons (R4 D17EA004 and generic Buffer.from("........","hex")). */
const FIXED_HDR_HEX =
/Buffer\.from\s*\(\s*['"][0-9a-fA-F]{8}['"]\s*,\s*['"]hex['"]\s*\)/;
const NAMED_HDR =
/\b(?:SEALED_HDR|SEAL_HDR|WRAP_HDR|MAGIC_HDR|BLOB_HDR|PARAM_HDR)\b/;
const R4_BEACON = /['"]d17ea004['"]/i;
const JS_EXT = /\.(?:[cm]?js|tsx?|mts|cts)$/i;
function finding(
id: JsAesUnwrapFindingId,
severity: JsAesUnwrapSeverity,
summary: string,
evidence: string,
): JsAesUnwrapFinding {
return {
id,
severity,
summary,
evidence: evidence.slice(0, 160),
};
}
function detectSignals(text: string): {
hasCreateCipherIv: boolean;
hasWrapKeyMaterial: boolean;
hasFixedSealedHdr: boolean;
evidence: {
cipher?: string;
key?: string;
hdr?: string;
};
} {
const cipherMatch = text.match(CREATE_CIPHER_IV);
const hasCreateCipherIv = Boolean(cipherMatch);
const algoMatch = text.match(AES_ALGO);
let keyEvidence: string | undefined;
let hasWrapKeyMaterial = false;
if (WRAP_KEY_NAME.test(text)) {
hasWrapKeyMaterial = true;
keyEvidence = "named WRAP_KEY/AES_KEY-style constant";
} else if (BUFFER_FROM_HEX_B64.test(text) && (hasCreateCipherIv || algoMatch)) {
hasWrapKeyMaterial = true;
keyEvidence = "Buffer.from(..., hex|base64) near cipheriv";
} else if (HEX_KEY_LITERAL.test(text) && hasCreateCipherIv) {
hasWrapKeyMaterial = true;
keyEvidence = "32/64-hex string literal near cipheriv";
}
let hdrEvidence: string | undefined;
let hasFixedSealedHdr = false;
if (R4_BEACON.test(text)) {
hasFixedSealedHdr = true;
hdrEvidence = "d17ea004 beacon";
} else if (NAMED_HDR.test(text)) {
hasFixedSealedHdr = true;
hdrEvidence = "SEALED_HDR/WRAP_HDR-style name";
} else if (FIXED_HDR_HEX.test(text) && (hasCreateCipherIv || hasWrapKeyMaterial)) {
hasFixedSealedHdr = true;
hdrEvidence = "Buffer.from(8-hex, \"hex\") sealed hdr";
}
return {
hasCreateCipherIv,
hasWrapKeyMaterial,
hasFixedSealedHdr,
evidence: {
...(cipherMatch ? { cipher: cipherMatch[0] } : {}),
...(algoMatch ? { cipher: `${cipherMatch?.[0] ?? "cipheriv"}+${algoMatch[0]}` } : {}),
...(keyEvidence ? { key: keyEvidence } : {}),
...(hdrEvidence ? { hdr: hdrEvidence } : {}),
},
};
}
/**
* Lint a JS/TS (or HTML-inline-script) UTF-8 body for AES wrap-key unwrap footguns.
*/
export function lintJsAesUnwrapSource(
source: string,
options: { readonly path?: string } = {},
): JsAesUnwrapReport {
const pathLabel = options.path ?? "<memory>";
const text = source.length > MAX_SCAN_CHARS ? source.slice(0, MAX_SCAN_CHARS) : source;
const sha256Prefix = createHash("sha256").update(text, "utf8").digest("hex").slice(0, 12);
const signals = detectSignals(text);
const findings: JsAesUnwrapFinding[] = [];
if (signals.hasWrapKeyMaterial) {
findings.push(
finding(
"js-aes-wrap-key-material",
signals.hasCreateCipherIv ? "error" : "warning",
"JS appears to hold AES wrap-key material (hex/base64 Buffer.from or WRAP_KEY* constant) — recoverable under Node crypto instrumentation.",
signals.evidence.key ?? "wrap-key",
),
);
}
if (signals.hasCreateCipherIv) {
findings.push(
finding(
"js-aes-create-cipheriv",
signals.hasWrapKeyMaterial ? "error" : "warning",
"JS calls createDecipheriv/createCipheriv — wrap keys passed here are RE-reachable at runtime (not white-box).",
signals.evidence.cipher ?? "create*iv",
),
);
}
if (signals.hasFixedSealedHdr) {
findings.push(
finding(
"js-aes-fixed-sealed-hdr",
signals.hasCreateCipherIv && signals.hasWrapKeyMaterial ? "error" : "warning",
"Fixed sealed-blob header/magic in JS (stable beacon for AES-wrapped WASM/param blobs).",
signals.evidence.hdr ?? "sealed-hdr",
),
);
}
const combo =
signals.hasCreateCipherIv &&
signals.hasWrapKeyMaterial &&
signals.hasFixedSealedHdr;
if (combo) {
findings.push(
finding(
"js-aes-sealed-blob-unwrap",
"error",
"JS AES sealed-blob unwrap footgun: wrap-key material + create*iv + fixed hdr — bankrupt harden refuses. Prefer unwrap inside WASM / avoid shipping recoverable wrap keys; this gate does not implement white-box AES.",
[
signals.evidence.key,
signals.evidence.cipher,
signals.evidence.hdr,
]
.filter(Boolean)
.join("; "),
),
);
}
// Dedup by id (keep highest severity).
const byId = new Map<JsAesUnwrapFindingId, JsAesUnwrapFinding>();
for (const f of findings) {
const prev = byId.get(f.id);
if (!prev || (prev.severity === "warning" && f.severity === "error")) {
byId.set(f.id, f);
}
}
const deduped = [...byId.values()];
const shouldRefuseBankrupt = combo;
return {
schema: JS_AES_UNWRAP_SCHEMA,
path: pathLabel,
sha256Prefix,
findings: deduped,
looksExposed: deduped.length > 0,
shouldRefuseBankrupt,
hasWrapKeyMaterial: signals.hasWrapKeyMaterial,
hasCreateCipherIv: signals.hasCreateCipherIv,
hasFixedSealedHdr: signals.hasFixedSealedHdr,
oneLineAdvice:
deduped.length === 0
? "No JS AES wrap-key + create*iv + fixed-hdr sealed-blob unwrap footgun detected (heuristic)."
: shouldRefuseBankrupt
? "ERROR: JS holds recoverable AES wrap key + createDecipheriv/createCipheriv + fixed sealed hdr. Move unwrap out of JS or stop shipping key material; bankrupt refuses unless allowJsAesUnwrap / --allow-js-aes-unwrap / allow_js_aes_unwrap. Not white-box AES — defensive gate only."
: "WARNING: Partial JS AES unwrap signals — avoid hex wrap keys and fixed hdr beacons next to create*iv for entitlement params.",
};
}
export function lintJsAesUnwrapFile(filePath: string): JsAesUnwrapReport {
const abs = resolve(filePath);
if (!existsSync(abs)) {
throw new Error(`js-aes-unwrap target not found: ${abs}`);
}
return lintJsAesUnwrapSource(readFileSync(abs, "utf8"), { path: abs });
}
function walkJsCandidates(dir: string, depth: number, out: string[]): void {
if (out.length >= MAX_JS_FILES || depth > MAX_WALK_DEPTH) return;
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (out.length >= MAX_JS_FILES) return;
if (entry.isDirectory()) {
if (SKIP_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
walkJsCandidates(join(dir, entry.name), depth + 1, out);
continue;
}
if (!entry.isFile()) continue;
if (!JS_EXT.test(entry.name) && !/\.html?$/i.test(entry.name)) continue;
out.push(join(dir, entry.name));
}
}
/**
* Discover JS/TS/HTML under a directory and lint each for AES unwrap footguns.
*/
export function discoverAndLintJsAesUnwrap(
directory: string,
): readonly JsAesUnwrapReport[] {
const abs = resolve(directory);
if (!existsSync(abs)) {
throw new Error(`Path not found: ${abs}`);
}
const st = statSync(abs);
if (st.isFile()) {
return [lintJsAesUnwrapFile(abs)];
}
const candidates: string[] = [];
walkJsCandidates(abs, 0, candidates);
return candidates.map((p) => lintJsAesUnwrapFile(p));
}
export function jsAesUnwrapRefuseMessage(
report: JsAesUnwrapReport,
filePath: string,
): string {
return (
`Refusing bankrupt harden/protect: JS AES sealed-blob unwrap footgun at ${filePath}` +
` (wrap-key material + create*iv + fixed hdr). ` +
`Do not ship recoverable AES wrap keys in JS for entitlement params; prefer in-WASM unwrap. ` +
`This gate does not provide white-box AES. ` +
`To override (lab fixture only), pass allowJsAesUnwrap / --allow-js-aes-unwrap / allow_js_aes_unwrap:true.`
);
}
export function intensityEnforcesJsAesUnwrapRefusal(intensity: string): boolean {
return intensity === "bankrupt";
}
/** Minimal R4-shaped footgun source for tests. */
export function buildTestJsAesUnwrapFootgun(options: {
readonly wrapKeyHex?: string;
readonly hdrHex?: string;
readonly omitKey?: boolean;
readonly omitCipher?: boolean;
readonly omitHdr?: boolean;
} = {}): string {
const key = options.wrapKeyHex ?? "a".repeat(64);
const hdr = options.hdrHex ?? "d17ea004";
const parts: string[] = [
'const crypto = require("crypto");',
'const fs = require("fs");',
];
if (!options.omitKey) {
parts.push(`const WRAP_KEY_HEX = "${key}";`);
}
if (!options.omitHdr) {
parts.push(`const SEALED_HDR = Buffer.from("${hdr}", "hex");`);
}
parts.push(`function unwrapSealed(buf) {`);
if (!options.omitHdr) {
parts.push(` if (!buf.subarray(0, 4).equals(SEALED_HDR)) return null;`);
}
parts.push(` const nonce = buf.subarray(4, 16);`);
parts.push(` const enc = buf.subarray(16);`);
if (!options.omitKey) {
parts.push(` const key = Buffer.from(WRAP_KEY_HEX, "hex");`);
} else {
parts.push(` const key = Buffer.alloc(32);`);
}
parts.push(` const iv = Buffer.concat([nonce, Buffer.alloc(4)]);`);
if (!options.omitCipher) {
parts.push(` const dec = crypto.createDecipheriv("aes-256-ctr", key, iv);`);
parts.push(` return Buffer.concat([dec.update(enc), dec.final()]);`);
} else {
parts.push(` return key;`);
}
parts.push(`}`);
parts.push(`module.exports = { unwrapSealed };`);
return parts.join("\n") + "\n";
}
+359
View File
@@ -0,0 +1,359 @@
/**
* JS ← WASM hydrate memory-dump lint (red-blue round-5 residual).
*
* Detects the footgun where entitlement params are XOR-/cipher-unwrapped
* *inside* WASM, then copied into JS via `memory.buffer` at a fixed dst
* (salt || rounds || clen || cipher). Host-side dump recovers plaintext
* params with no Node create*iv — bankrupt rename does not help when
* ~all arity-1 exports alias hydrate.
*
* Bankrupt harden/protect refuses error findings unless
* `allowJsWasmHydrateDump` / `--allow-js-wasm-hydrate-dump` /
* `allow_js_wasm_hydrate_dump`.
*
* DEFENSIVE ONLY — prefer keep ARX+certify inside WASM so params never
* re-enter JS. This gate does not implement white-box crypto.
*/
import { createHash } from "node:crypto";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { basename, join, resolve } from "node:path";
export const JS_WASM_HYDRATE_DUMP_SCHEMA = "bla-js-wasm-hydrate-dump-lint/v1" as const;
export type JsWasmHydrateDumpFindingId =
| "js-wasm-memory-buffer-read"
| "js-wasm-hydrate-call"
| "js-wasm-param-layout-decode"
| "js-wasm-hydrate-param-dump";
export type JsWasmHydrateDumpSeverity = "warning" | "error";
export interface JsWasmHydrateDumpFinding {
readonly id: JsWasmHydrateDumpFindingId;
readonly severity: JsWasmHydrateDumpSeverity;
readonly summary: string;
readonly evidence: string;
}
export interface JsWasmHydrateDumpReport {
readonly schema: typeof JS_WASM_HYDRATE_DUMP_SCHEMA;
readonly path: string;
readonly sha256Prefix: string;
readonly findings: readonly JsWasmHydrateDumpFinding[];
readonly looksExposed: boolean;
/** True when bankrupt harden/protect should refuse (combo error). */
readonly shouldRefuseBankrupt: boolean;
readonly hasMemoryBufferRead: boolean;
readonly hasHydrateCall: boolean;
readonly hasParamLayoutDecode: boolean;
readonly oneLineAdvice: string;
}
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_JS_FILES = 48;
const MAX_SCAN_CHARS = 800_000;
/** Host reads WASM linear memory into a JS typed array / Buffer. */
const MEMORY_BUFFER_READ =
/(?:new\s+Uint8Array\s*\(\s*(?:[a-zA-Z_$][\w$]*\.)?buffer\b|Buffer\.from\s*\(\s*new\s+Uint8Array\s*\([^)]*\.buffer\b|instanceof\s+WebAssembly\.Memory)/;
/** Hydrate-style entry: named hydrate, or arity/export probe next to Memory. */
const HYDRATE_CALL =
/\.hydrate\s*\(|\bhydrate\s*\(\s*\w+|\bexp\.hydrate\b|fn\.length\s*!==\s*1|fn\.length\s*===\s*1/;
/**
* salt||rounds||clen||cipher layout decode in JS (R3–R5 entitlement pack).
* Require at least two strong signals to avoid hashing false positives.
*/
const READ_I32_LE = /\.readInt32LE\s*\(|\.readUInt32LE\s*\(/;
const READ_U16_LE = /\.readUInt16LE\s*\(/;
const SALT_NAME = /\b(?:salt|SALT)\b/;
const ROUNDS_NAME = /\b(?:rounds|ROUNDS)\b/;
const CIPHER_NAME = /\b(?:cipherHex|cipher|CIPHER)\b/;
const CLEN_NAME = /\b(?:clen|cLen|cipherLen)\b/;
const WASM_INSTANTIATE = /WebAssembly\.instantiate\b/;
const JS_EXT = /\.(?:[cm]?js|tsx?|mts|cts)$/i;
function finding(
id: JsWasmHydrateDumpFindingId,
severity: JsWasmHydrateDumpSeverity,
summary: string,
evidence: string,
): JsWasmHydrateDumpFinding {
return {
id,
severity,
summary,
evidence: evidence.slice(0, 160),
};
}
function detectSignals(text: string): {
hasMemoryBufferRead: boolean;
hasHydrateCall: boolean;
hasParamLayoutDecode: boolean;
hasWasmInstantiate: boolean;
evidence: { memory?: string; hydrate?: string; layout?: string };
} {
const memMatch = text.match(MEMORY_BUFFER_READ);
const hasMemoryBufferRead = Boolean(memMatch);
const hydMatch = text.match(HYDRATE_CALL);
const hasHydrateCall = Boolean(hydMatch);
const hasWasmInstantiate = WASM_INSTANTIATE.test(text);
let layoutBits = 0;
const layoutEv: string[] = [];
if (READ_I32_LE.test(text)) {
layoutBits++;
layoutEv.push("readInt32LE/readUInt32LE");
}
if (READ_U16_LE.test(text)) {
layoutBits++;
layoutEv.push("readUInt16LE");
}
if (SALT_NAME.test(text) && ROUNDS_NAME.test(text)) {
layoutBits++;
layoutEv.push("salt+rounds names");
}
if (CIPHER_NAME.test(text) || CLEN_NAME.test(text)) {
layoutBits++;
layoutEv.push("cipher/clen");
}
const hasParamLayoutDecode = layoutBits >= 2;
return {
hasMemoryBufferRead,
hasHydrateCall,
hasParamLayoutDecode,
hasWasmInstantiate,
evidence: {
...(memMatch ? { memory: memMatch[0].slice(0, 80) } : {}),
...(hydMatch ? { hydrate: hydMatch[0].slice(0, 80) } : {}),
...(hasParamLayoutDecode ? { layout: layoutEv.join("+") } : {}),
},
};
}
/**
* Lint a JS/TS (or HTML-inline-script) UTF-8 body for WASM hydrate→JS dump footguns.
*/
export function lintJsWasmHydrateDumpSource(
source: string,
options: { readonly path?: string } = {},
): JsWasmHydrateDumpReport {
const pathLabel = options.path ?? "<memory>";
const text = source.length > MAX_SCAN_CHARS ? source.slice(0, MAX_SCAN_CHARS) : source;
const sha256Prefix = createHash("sha256").update(text, "utf8").digest("hex").slice(0, 12);
const signals = detectSignals(text);
const findings: JsWasmHydrateDumpFinding[] = [];
if (signals.hasMemoryBufferRead) {
findings.push(
finding(
"js-wasm-memory-buffer-read",
signals.hasParamLayoutDecode ? "error" : "warning",
"JS reads WebAssembly.Memory / memory.buffer into a host typed array — post-hydrate plaintext is dumpable without Node crypto.",
signals.evidence.memory ?? "memory.buffer",
),
);
}
if (signals.hasHydrateCall) {
findings.push(
finding(
"js-wasm-hydrate-call",
signals.hasMemoryBufferRead && signals.hasParamLayoutDecode ? "error" : "warning",
"JS invokes hydrate (or arity===1 export probe) then consumes WASM memory — typical host-side param unwrap.",
signals.evidence.hydrate ?? "hydrate/arity-probe",
),
);
}
if (signals.hasParamLayoutDecode) {
findings.push(
finding(
"js-wasm-param-layout-decode",
signals.hasMemoryBufferRead ? "error" : "warning",
"JS decodes salt||rounds||clen||cipher-style entitlement layout from a buffer (readInt32LE / salt+rounds / cipher).",
signals.evidence.layout ?? "param-layout",
),
);
}
const combo =
signals.hasMemoryBufferRead &&
signals.hasParamLayoutDecode &&
(signals.hasHydrateCall || signals.hasWasmInstantiate);
if (combo) {
findings.push(
finding(
"js-wasm-hydrate-param-dump",
"error",
"JS WASM hydrate param-dump footgun: memory.buffer read + salt/rounds/cipher layout decode after hydrate/instantiate — bankrupt harden refuses. Keep ARX+certify inside WASM so params never re-enter JS; export rename alone does not close this.",
[
signals.evidence.memory,
signals.evidence.hydrate,
signals.evidence.layout,
]
.filter(Boolean)
.join("; "),
),
);
}
const byId = new Map<JsWasmHydrateDumpFindingId, JsWasmHydrateDumpFinding>();
for (const f of findings) {
const prev = byId.get(f.id);
if (!prev || (prev.severity === "warning" && f.severity === "error")) {
byId.set(f.id, f);
}
}
const deduped = [...byId.values()];
const shouldRefuseBankrupt = combo;
return {
schema: JS_WASM_HYDRATE_DUMP_SCHEMA,
path: pathLabel,
sha256Prefix,
findings: deduped,
looksExposed: deduped.length > 0,
shouldRefuseBankrupt,
hasMemoryBufferRead: signals.hasMemoryBufferRead,
hasHydrateCall: signals.hasHydrateCall,
hasParamLayoutDecode: signals.hasParamLayoutDecode,
oneLineAdvice:
deduped.length === 0
? "No JS←WASM hydrate memory-dump footgun detected (heuristic)."
: shouldRefuseBankrupt
? "ERROR: JS dumps salt/rounds/cipher from WebAssembly.Memory after hydrate. Keep entitlement crypto inside WASM; bankrupt refuses unless allowJsWasmHydrateDump / --allow-js-wasm-hydrate-dump / allow_js_wasm_hydrate_dump. Defensive gate only."
: "WARNING: Partial JS←WASM memory/param signals — avoid copying hydrate plaintext into JS for entitlement checks.",
};
}
export function lintJsWasmHydrateDumpFile(filePath: string): JsWasmHydrateDumpReport {
const abs = resolve(filePath);
if (!existsSync(abs)) {
throw new Error(`js-wasm-hydrate-dump target not found: ${abs}`);
}
return lintJsWasmHydrateDumpSource(readFileSync(abs, "utf8"), { path: abs });
}
function walkJsCandidates(dir: string, depth: number, out: string[]): void {
if (out.length >= MAX_JS_FILES || depth > MAX_WALK_DEPTH) return;
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (out.length >= MAX_JS_FILES) return;
if (entry.isDirectory()) {
if (SKIP_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
walkJsCandidates(join(dir, entry.name), depth + 1, out);
continue;
}
if (!entry.isFile()) continue;
if (!JS_EXT.test(entry.name) && !/\.html?$/i.test(entry.name)) continue;
out.push(join(dir, entry.name));
}
}
export function discoverAndLintJsWasmHydrateDump(
directory: string,
): readonly JsWasmHydrateDumpReport[] {
const abs = resolve(directory);
if (!existsSync(abs)) {
throw new Error(`Path not found: ${abs}`);
}
const st = statSync(abs);
if (st.isFile()) {
return [lintJsWasmHydrateDumpFile(abs)];
}
const candidates: string[] = [];
walkJsCandidates(abs, 0, candidates);
return candidates.map((p) => lintJsWasmHydrateDumpFile(p));
}
export function jsWasmHydrateDumpRefuseMessage(
report: JsWasmHydrateDumpReport,
filePath: string,
): string {
return (
`Refusing bankrupt harden/protect: JS←WASM hydrate param-dump footgun at ${filePath}` +
` (memory.buffer read + salt/rounds/cipher layout after hydrate/instantiate). ` +
`Keep ARX+certify inside WASM so plaintext params never re-enter JS. ` +
`Export rename alone does not close host memory dumps. ` +
`To override (lab fixture only), pass allowJsWasmHydrateDump / --allow-js-wasm-hydrate-dump / allow_js_wasm_hydrate_dump:true.`
);
}
export function intensityEnforcesJsWasmHydrateDumpRefusal(intensity: string): boolean {
return intensity === "bankrupt";
}
/** Minimal R5-shaped footgun source for tests. */
export function buildTestJsWasmHydrateDumpFootgun(options: {
readonly omitMemory?: boolean;
readonly omitHydrate?: boolean;
readonly omitLayout?: boolean;
} = {}): string {
const parts: string[] = [
'const fs = require("fs");',
"async function loadRuntimeFromWasm() {",
' const bytes = fs.readFileSync("core.wasm");',
];
if (!options.omitHydrate) {
parts.push(" const { instance } = await WebAssembly.instantiate(bytes, {});");
parts.push(" const exp = instance.exports;");
parts.push(" let memory = null;");
parts.push(" for (const v of Object.values(exp)) {");
parts.push(" if (v instanceof WebAssembly.Memory) { memory = v; break; }");
parts.push(" }");
parts.push(" let hydrate = typeof exp.hydrate === 'function' ? exp.hydrate : null;");
parts.push(" if (!hydrate) {");
parts.push(" for (const [nm, fn] of Object.entries(exp)) {");
parts.push(" if (typeof fn !== 'function' || fn.length !== 1) continue;");
parts.push(" hydrate = fn; break;");
parts.push(" }");
parts.push(" }");
parts.push(" const n = hydrate(4096) | 0;");
} else {
parts.push(" const n = 42;");
parts.push(" const memory = { buffer: new ArrayBuffer(8192) };");
}
if (!options.omitMemory) {
parts.push(" const view = new Uint8Array(memory.buffer, 4096, n);");
parts.push(" const buf = Buffer.from(view);");
} else {
parts.push(" const buf = Buffer.alloc(42);");
}
if (!options.omitLayout) {
parts.push(" const salt = buf.readInt32LE(0);");
parts.push(" const rounds = buf[4];");
parts.push(" const clen = buf.readUInt16LE(5);");
parts.push(" const cipherHex = buf.subarray(7, 7 + clen).toString('hex');");
parts.push(" return { salt, rounds, cipherHex };");
} else {
parts.push(" return { buf };");
}
parts.push("}");
parts.push("module.exports = { loadRuntimeFromWasm };");
return parts.join("\n") + "\n";
}
+170 -29
View File
@@ -1,25 +1,33 @@
/**
* Lane-independence footgun lint (issue #40.1).
* Lane-independence footgun lint (issue #40.1 / red-blue round-1).
*
* Heuristic, defensive-only warning when customer gate code looks like
* Heuristic, defensive-only gate when customer gate code looks like
* independent per-lane checks (e.g. an array of single-byte compares combined
* with a shallow AND/OR reduction). Meridian / good designs use chained
* whole-key mixing so no per-lane oracle exists.
* with a shallow AND/OR reduction, or per-byte charCodeAt → wasm mix/seal).
* Meridian / good designs use chained whole-key mixing so no per-lane oracle exists.
*
* This does NOT give reverse-engineering advice. It only flags a structural
* pattern that historically collapses search cost.
* Findings are severity **"error"** — CLI `bla lint-lanes` exits 2, and
* harden/defend refuse the artifact unless `allowLaneIndependentGates` is set.
* This does NOT give reverse-engineering advice.
*/
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { join, resolve } from "node:path";
export const LANE_INDEPENDENCE_SCHEMA = "bla-lane-independence-lint/v1" as const;
export type LaneIndependenceFindingId =
| "per-lane-byte-compare-array"
| "independent-lane-and-reduce"
| "indexed-lane-oracle-loop";
| "indexed-lane-oracle-loop"
| "per-byte-wasm-lane-oracle";
export type LaneIndependenceSeverity = "error";
export interface LaneIndependenceFinding {
readonly id: LaneIndependenceFindingId;
readonly severity: "warn";
readonly severity: LaneIndependenceSeverity;
readonly summary: string;
readonly evidence: string;
}
@@ -44,9 +52,33 @@ const EVERY_INDEXED_LANE =
const INDEXED_ORACLE =
/for\s*\(\s*(?:let|var|const)\s+\w+\s*=\s*0[^)]*\)\s*\{[^}]{0,200}(?:key|input|guess)\s*\[\s*\w+\s*\][^}]{0,120}===\s*(?:target|expect|lane|ref)/i;
/**
* Per-byte charCodeAt fed into mix/seal (or similar) with an indexed target
* compare — CrackMe v6 / independent WASM-lane shape (XOR or !== fold OK).
*/
const PER_BYTE_WASM_LANE =
/charCodeAt\s*\(\s*\w+\s*\)[\s\S]{0,240}(?:mix|seal)\s*\([\s\S]{0,320}(?:LANE_TARGETS|laneTargets|targets?|lanes?)\s*\[\s*\w+/i;
/** Indexed XOR/OR fold of per-lane results without whole-key mixing. */
const INDEXED_XOR_LANE_FOLD =
/for\s*\(\s*(?:let|var|const)\s+\w+[^)]*\)\s*\{[\s\S]{0,400}charCodeAt[\s\S]{0,400}\^\s*\((?:LANE_TARGETS|laneTargets|targets?|lanes?)\s*\[/i;
function finding(
id: LaneIndependenceFindingId,
summary: string,
evidence: string,
): LaneIndependenceFinding {
return {
id,
severity: "error",
summary,
evidence: evidence.slice(0, 120),
};
}
/**
* Scan UTF-8 source (JS/TS/Python-like) for lane-independence footguns.
* Returns findings with severity "warn" only — never fails closed.
* Findings are severity "error" — callers decide whether to refuse (harden) or exit 2 (CLI).
*/
export function lintLaneIndependence(source: string): LaneIndependenceReport {
const findings: LaneIndependenceFinding[] = [];
@@ -54,35 +86,51 @@ export function lintLaneIndependence(source: string): LaneIndependenceReport {
if (BYTE_COMPARE_ARRAY.test(text) && /(?:key|guess|input|lane)/i.test(text)) {
const m = text.match(BYTE_COMPARE_ARRAY);
findings.push({
id: "per-lane-byte-compare-array",
severity: "warn",
summary:
"Literal multi-byte compare table near key/guess identifiers — may allow independent per-lane probes.",
evidence: (m?.[0] ?? "").slice(0, 80),
});
// Round-2 blue: all-zero init arrays (e.g. pack buffers) are not compare tables.
const lit = m?.[0] ?? "";
const allZero = /^\[\s*0\s*(?:,\s*0\s*){3,}\]$/.test(lit);
if (!allZero) {
findings.push(
finding(
"per-lane-byte-compare-array",
"Literal multi-byte compare table near key/guess identifiers — may allow independent per-lane probes.",
lit,
),
);
}
}
if (LANE_AND_REDUCE.test(text) || EVERY_INDEXED_LANE.test(text)) {
const m = text.match(LANE_AND_REDUCE) ?? text.match(EVERY_INDEXED_LANE);
findings.push({
id: "independent-lane-and-reduce",
severity: "warn",
summary:
findings.push(
finding(
"independent-lane-and-reduce",
"Lane/byte collection reduced with every/all/AND — suggests independent lane checks without whole-key mixing.",
evidence: (m?.[0] ?? "").slice(0, 80),
});
m?.[0] ?? "",
),
);
}
if (INDEXED_ORACLE.test(text)) {
const m = text.match(INDEXED_ORACLE);
findings.push({
id: "indexed-lane-oracle-loop",
severity: "warn",
summary:
findings.push(
finding(
"indexed-lane-oracle-loop",
"Indexed loop comparing key[i] to a per-lane target — classic independent-lane oracle shape.",
evidence: (m?.[0] ?? "").slice(0, 120),
});
m?.[0] ?? "",
),
);
}
if (PER_BYTE_WASM_LANE.test(text) || INDEXED_XOR_LANE_FOLD.test(text)) {
const m = text.match(PER_BYTE_WASM_LANE) ?? text.match(INDEXED_XOR_LANE_FOLD);
findings.push(
finding(
"per-byte-wasm-lane-oracle",
"Per-byte charCodeAt → mix/seal (or XOR fold) against indexed lane targets — independent 1-byte WASM lanes collapse under RE.",
m?.[0] ?? "",
),
);
}
return {
@@ -92,6 +140,99 @@ export function lintLaneIndependence(source: string): LaneIndependenceReport {
oneLineAdvice:
findings.length === 0
? "No lane-independence footgun pattern detected (heuristic)."
: "Prefer whole-key chained mixing (no per-lane oracle). See issue #40.1 / Meridian DESIGN — defensive guidance only.",
: "ERROR: Prefer whole-key chained mixing (no per-lane oracle). Harden refuses this gate unless allowLaneIndependentGates / --allow-lane-independent / allow_lane_independent. See issue #40.1 / Meridian DESIGN — defensive guidance only.",
};
}
/** Formats where lane-independence lint applies before protect/defend/harden. */
export function formatSupportsLaneIndependenceLint(
format: string,
): boolean {
return format === "javascript" || format === "typescript";
}
/**
* Build a refuse message for harden/defend when lane-independent gates are detected.
*/
export function laneIndependenceRefuseMessage(
report: LaneIndependenceReport,
inputPath: string,
): string {
const ids = report.findings.map((f) => f.id).join(", ");
return (
`Refusing lane-independent gate at ${inputPath} [${ids}]. ` +
`Prefer whole-key chained mixing. To override (intentional footgun / teaching fixture), ` +
`pass allowLaneIndependentGates / --allow-lane-independent / allow_lane_independent:true.`
);
}
const SKIP_DIR_NAMES = new Set([
"node_modules",
".git",
".hg",
".svn",
".bla-hardened",
"coverage",
".turbo",
".cache",
"__pycache__",
".venv",
"venv",
]);
const JS_EXT = /\.(?:[cm]?[jt]s|tsx?)$/i;
const MAX_JS_FILES = 64;
const MAX_WALK_DEPTH = 8;
function walkJsGateCandidates(dir: string, depth: number, out: string[]): void {
if (out.length >= MAX_JS_FILES || depth > MAX_WALK_DEPTH) return;
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (out.length >= MAX_JS_FILES) return;
if (entry.isDirectory()) {
if (SKIP_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
walkJsGateCandidates(join(dir, entry.name), depth + 1, out);
continue;
}
if (!entry.isFile()) continue;
if (!JS_EXT.test(entry.name)) continue;
out.push(join(dir, entry.name));
}
}
/** File wrapper matching other packaging lints. */
export function lintLaneIndependenceFile(filePath: string): LaneIndependenceReport & {
readonly path: string;
} {
const abs = resolve(filePath);
if (!existsSync(abs)) {
throw new Error(`lane-independence target not found: ${abs}`);
}
const report = lintLaneIndependence(readFileSync(abs, "utf8"));
return { ...report, path: abs };
}
/**
* Discover JS/TS under a directory and lint each for lane-independence footguns.
* Used by unified `bla lint` / packaging-gates (protect still refuses per-file).
*/
export function discoverAndLintLaneIndependence(
directory: string,
): ReadonlyArray<LaneIndependenceReport & { readonly path: string }> {
const abs = resolve(directory);
if (!existsSync(abs)) {
throw new Error(`Path not found: ${abs}`);
}
const st = statSync(abs);
if (st.isFile()) {
return [lintLaneIndependenceFile(abs)];
}
const candidates: string[] = [];
walkJsGateCandidates(abs, 0, candidates);
return candidates.map((p) => lintLaneIndependenceFile(p));
}
+478
View File
@@ -0,0 +1,478 @@
/**
* Unified packaging-footgun gate pipeline (red-blue R1–R12 → BLA 2.0).
*
* Aggregates every bankrupt refuse lint that harden already runs at project
* level, plus advisory lane / panel-derive discovery (protect still refuses
* those per-file). Agents call this via `bla lint` / MCP `bla_lint` instead of
* eight separate tools.
*
* Honesty: gates close *packaging* footguns. They do **not** claim white-box
* secrecy against full WASM RE / online guessing / SMT (R8–R12 residual).
*/
import { basename, relative, resolve, sep } from "node:path";
import type { ProtectionIntensity } from "../core/types.js";
import {
discoverAndLintSealSidecars,
intensityEnforcesSealRefusal,
sealCommitmentRefuseMessage,
type SealCommitmentReport,
} from "./seal-commitment-lint.js";
import {
discoverAndLintWasmParamCarriers,
intensityEnforcesWasmParamRefusal,
wasmParamCarrierRefuseMessage,
type WasmParamCarrierReport,
} from "./wasm-param-carrier-lint.js";
import {
discoverAndLintJsAesUnwrap,
intensityEnforcesJsAesUnwrapRefusal,
jsAesUnwrapRefuseMessage,
type JsAesUnwrapReport,
} from "./js-aes-unwrap-lint.js";
import {
discoverAndLintJsWasmHydrateDump,
intensityEnforcesJsWasmHydrateDumpRefusal,
jsWasmHydrateDumpRefuseMessage,
type JsWasmHydrateDumpReport,
} from "./js-wasm-hydrate-dump-lint.js";
import {
discoverAndLintWasmXorMaskSidecars,
intensityEnforcesWasmXorMaskSidecarRefusal,
wasmXorMaskSidecarRefuseMessage,
type WasmXorMaskSidecarReport,
} from "./wasm-xor-mask-sidecar-lint.js";
import {
discoverAndLintWasmSealXorKnownPlaintext,
intensityEnforcesWasmSealXorKnownPlaintextRefusal,
wasmSealXorKnownPlaintextRefuseMessage,
type WasmSealXorKnownPlaintextReport,
} from "./wasm-seal-xor-known-plaintext-lint.js";
import {
discoverAndLintLaneIndependence,
laneIndependenceRefuseMessage,
type LaneIndependenceReport,
} from "./lane-independence-lint.js";
import {
discoverAndLintPanelDerive,
intensityEnforcesPanelOracleRefusal,
panelDeriveRefuseMessage,
type PanelDeriveAbiReport,
} from "./panel-derive-abi-lint.js";
export const PACKAGING_GATES_SCHEMA = "bla-packaging-gates/v1" as const;
export type PackagingGateId =
| "seal-commitment"
| "wasm-param-carrier"
| "js-aes-unwrap"
| "js-wasm-hydrate-dump"
| "wasm-xor-mask-sidecar"
| "wasm-seal-xor-known-plaintext"
| "lane-independence"
| "panel-derive";
export interface PackagingGateFinding {
readonly gate: PackagingGateId;
readonly path: string;
readonly relativePath: string;
readonly shouldRefuseBankrupt: boolean;
readonly refuseMessage?: string;
readonly oneLineAdvice: string;
readonly findingCount: number;
}
export interface PackagingGatesAllowOptions {
readonly allowPlaintextSeal?: boolean;
readonly allowWasmClearParamCarriers?: boolean;
readonly allowJsAesUnwrap?: boolean;
readonly allowJsWasmHydrateDump?: boolean;
readonly allowWasmXorMaskSidecar?: boolean;
readonly allowWasmSealXorKnownPlaintext?: boolean;
readonly allowLaneIndependentGates?: boolean;
readonly allowPanelOfflineOracle?: boolean;
readonly allowStablePanelDeriveAbi?: boolean;
}
export interface PackagingGatesScanOptions extends PackagingGatesAllowOptions {
readonly directory: string;
/** Intensity used to decide which findings refuse bankrupt (default bankrupt). */
readonly intensity?: ProtectionIntensity;
/**
* When true (default), also scan JS/HTML for lane-independence + panel-derive.
* Harden project-level refuse historically used the six carrier/JS/WASM gates
* only — lanes/panel stay protect-time unless includeProtectTimeGates.
*/
readonly includeProtectTimeGates?: boolean;
}
export interface PackagingGatesReport {
readonly schema: typeof PACKAGING_GATES_SCHEMA;
readonly directory: string;
readonly intensity: ProtectionIntensity;
readonly findings: readonly PackagingGateFinding[];
/** Findings that would refuse bankrupt/maximum under current allow flags. */
readonly blocking: readonly PackagingGateFinding[];
readonly shouldRefuseBankrupt: boolean;
readonly gateCounts: Readonly<Record<PackagingGateId, number>>;
readonly oneLineAdvice: string;
readonly honestyNote: string;
/** Raw per-gate reports for agents that need detail. */
readonly details: {
readonly seals: readonly SealCommitmentReport[];
readonly wasmParams: readonly WasmParamCarrierReport[];
readonly jsAes: readonly JsAesUnwrapReport[];
readonly jsHydrateDump: readonly JsWasmHydrateDumpReport[];
readonly wasmXorMask: readonly WasmXorMaskSidecarReport[];
readonly wasmSealXor: readonly WasmSealXorKnownPlaintextReport[];
readonly lanes: ReadonlyArray<LaneIndependenceReport & { readonly path: string }>;
readonly panelDerive: readonly PanelDeriveAbiReport[];
};
}
const HONESTY_NOTE =
"Packaging gates close shipping footguns (R1–R7 refuse + R8–R12 engine hygiene). " +
"They do not claim white-box secrecy against full WASM RE / online guessing / SMT.";
function relPath(absDir: string, filePath: string): string {
return (relative(absDir, filePath) || basename(filePath)).split(sep).join("/");
}
function emptyCounts(): Record<PackagingGateId, number> {
return {
"seal-commitment": 0,
"wasm-param-carrier": 0,
"js-aes-unwrap": 0,
"js-wasm-hydrate-dump": 0,
"wasm-xor-mask-sidecar": 0,
"wasm-seal-xor-known-plaintext": 0,
"lane-independence": 0,
"panel-derive": 0,
};
}
/**
* Scan a project (or file) for every packaging footgun lint.
* Read-only — never writes.
*/
export function scanPackagingGates(
options: PackagingGatesScanOptions,
): PackagingGatesReport {
const absDir = resolve(options.directory);
const intensity: ProtectionIntensity = options.intensity ?? "bankrupt";
const includeProtectTime = options.includeProtectTimeGates !== false;
const seals = discoverAndLintSealSidecars(absDir);
const wasmParams = discoverAndLintWasmParamCarriers(absDir);
const jsAes = discoverAndLintJsAesUnwrap(absDir);
const jsHydrateDump = discoverAndLintJsWasmHydrateDump(absDir);
const wasmXorMask = discoverAndLintWasmXorMaskSidecars(absDir);
const wasmSealXor = discoverAndLintWasmSealXorKnownPlaintext(absDir);
const lanes = includeProtectTime
? discoverAndLintLaneIndependence(absDir)
: [];
const panelDerive = includeProtectTime
? discoverAndLintPanelDerive(absDir)
: [];
const findings: PackagingGateFinding[] = [];
const counts = emptyCounts();
for (const r of seals) {
if (r.findings.length === 0 && !r.shouldRefuseBankrupt) continue;
counts["seal-commitment"] += 1;
findings.push({
gate: "seal-commitment",
path: r.path,
relativePath: relPath(absDir, r.path),
shouldRefuseBankrupt: r.shouldRefuseBankrupt,
refuseMessage: r.shouldRefuseBankrupt
? sealCommitmentRefuseMessage(r, r.path)
: undefined,
oneLineAdvice: r.oneLineAdvice,
findingCount: r.findings.length,
});
}
for (const r of wasmParams) {
if (r.findings.length === 0 && !r.shouldRefuseBankrupt) continue;
counts["wasm-param-carrier"] += 1;
findings.push({
gate: "wasm-param-carrier",
path: r.path,
relativePath: relPath(absDir, r.path),
shouldRefuseBankrupt: r.shouldRefuseBankrupt,
refuseMessage: r.shouldRefuseBankrupt
? wasmParamCarrierRefuseMessage(r, r.path)
: undefined,
oneLineAdvice: r.oneLineAdvice,
findingCount: r.findings.length,
});
}
for (const r of jsAes) {
if (r.findings.length === 0 && !r.shouldRefuseBankrupt) continue;
counts["js-aes-unwrap"] += 1;
findings.push({
gate: "js-aes-unwrap",
path: r.path,
relativePath: relPath(absDir, r.path),
shouldRefuseBankrupt: r.shouldRefuseBankrupt,
refuseMessage: r.shouldRefuseBankrupt
? jsAesUnwrapRefuseMessage(r, r.path)
: undefined,
oneLineAdvice: r.oneLineAdvice,
findingCount: r.findings.length,
});
}
for (const r of jsHydrateDump) {
if (r.findings.length === 0 && !r.shouldRefuseBankrupt) continue;
counts["js-wasm-hydrate-dump"] += 1;
findings.push({
gate: "js-wasm-hydrate-dump",
path: r.path,
relativePath: relPath(absDir, r.path),
shouldRefuseBankrupt: r.shouldRefuseBankrupt,
refuseMessage: r.shouldRefuseBankrupt
? jsWasmHydrateDumpRefuseMessage(r, r.path)
: undefined,
oneLineAdvice: r.oneLineAdvice,
findingCount: r.findings.length,
});
}
for (const r of wasmXorMask) {
if (r.findings.length === 0 && !r.shouldRefuseBankrupt) continue;
counts["wasm-xor-mask-sidecar"] += 1;
findings.push({
gate: "wasm-xor-mask-sidecar",
path: r.path,
relativePath: relPath(absDir, r.path),
shouldRefuseBankrupt: r.shouldRefuseBankrupt,
refuseMessage: r.shouldRefuseBankrupt
? wasmXorMaskSidecarRefuseMessage(r, r.path)
: undefined,
oneLineAdvice: r.oneLineAdvice,
findingCount: r.findings.length,
});
}
for (const r of wasmSealXor) {
if (r.findings.length === 0 && !r.shouldRefuseBankrupt) continue;
counts["wasm-seal-xor-known-plaintext"] += 1;
findings.push({
gate: "wasm-seal-xor-known-plaintext",
path: r.path,
relativePath: relPath(absDir, r.path),
shouldRefuseBankrupt: r.shouldRefuseBankrupt,
refuseMessage: r.shouldRefuseBankrupt
? wasmSealXorKnownPlaintextRefuseMessage(r, r.path)
: undefined,
oneLineAdvice: r.oneLineAdvice,
findingCount: r.findings.length,
});
}
for (const r of lanes) {
if (!r.looksLaneIndependent) continue;
counts["lane-independence"] += 1;
findings.push({
gate: "lane-independence",
path: r.path,
relativePath: relPath(absDir, r.path),
shouldRefuseBankrupt: true,
refuseMessage: laneIndependenceRefuseMessage(r, r.path),
oneLineAdvice: r.oneLineAdvice,
findingCount: r.findings.length,
});
}
for (const r of panelDerive) {
const refuse =
r.shouldRefuseBankrupt ||
(r.stableSymbols.length > 0 || r.localDeriveSymbols.length > 0);
if (r.findings.length === 0 && !refuse) continue;
counts["panel-derive"] += 1;
findings.push({
gate: "panel-derive",
path: r.path,
relativePath: relPath(absDir, r.path),
shouldRefuseBankrupt: r.shouldRefuseBankrupt,
refuseMessage:
r.shouldRefuseBankrupt || r.stableSymbols.length > 0
? panelDeriveRefuseMessage(r, r.path)
: undefined,
oneLineAdvice: r.oneLineAdvice,
findingCount: r.findings.length,
});
}
const blocking = filterBlockingFindings(findings, intensity, options);
const oneLineAdvice =
blocking.length === 0
? findings.length === 0
? "No packaging footgun findings (heuristic). Gates ≠ white-box secrecy."
: `Packaging scan: ${findings.length} finding(s), none refuse under current intensity/allows.`
: `ERROR: ${blocking.length} packaging gate(s) would refuse bankrupt harden. Fix or pass the matching --allow-* / allow_* flag (lab only).`;
return {
schema: PACKAGING_GATES_SCHEMA,
directory: absDir,
intensity,
findings,
blocking,
shouldRefuseBankrupt: blocking.length > 0,
gateCounts: counts,
oneLineAdvice,
honestyNote: HONESTY_NOTE,
details: {
seals,
wasmParams,
jsAes,
jsHydrateDump,
wasmXorMask,
wasmSealXor,
lanes,
panelDerive,
},
};
}
function filterBlockingFindings(
findings: readonly PackagingGateFinding[],
intensity: ProtectionIntensity,
allow: PackagingGatesAllowOptions,
): PackagingGateFinding[] {
return findings.filter((f) => {
if (!f.shouldRefuseBankrupt && f.gate !== "lane-independence") {
// panel stable-ABI rewrite is not a harden project-level refuse today
return false;
}
switch (f.gate) {
case "seal-commitment":
return intensityEnforcesSealRefusal(intensity) && allow.allowPlaintextSeal !== true;
case "wasm-param-carrier":
return (
intensityEnforcesWasmParamRefusal(intensity) &&
allow.allowWasmClearParamCarriers !== true
);
case "js-aes-unwrap":
return (
intensityEnforcesJsAesUnwrapRefusal(intensity) &&
allow.allowJsAesUnwrap !== true
);
case "js-wasm-hydrate-dump":
return (
intensityEnforcesJsWasmHydrateDumpRefusal(intensity) &&
allow.allowJsWasmHydrateDump !== true
);
case "wasm-xor-mask-sidecar":
return (
intensityEnforcesWasmXorMaskSidecarRefusal(intensity) &&
allow.allowWasmXorMaskSidecar !== true
);
case "wasm-seal-xor-known-plaintext":
return (
intensityEnforcesWasmSealXorKnownPlaintextRefusal(intensity) &&
allow.allowWasmSealXorKnownPlaintext !== true
);
case "lane-independence":
// Project-level lint reports lanes; harden project refuse historically
// left lanes to protect-time. Blocking list for `bla lint` treats them
// as refuse-worthy so agents see the same footgun before harden.
return allow.allowLaneIndependentGates !== true && f.shouldRefuseBankrupt;
case "panel-derive":
return (
intensityEnforcesPanelOracleRefusal(intensity) &&
allow.allowPanelOfflineOracle !== true &&
f.shouldRefuseBankrupt
);
default:
return false;
}
});
}
/**
* Subset of packaging gates that hardenProject historically refuses at
* project scope (excludes lane/panel — those remain protect-time).
*/
export function evaluateHardenProjectPackagingBlocks(
options: PackagingGatesScanOptions,
): {
readonly report: PackagingGatesReport;
readonly blockingSeals: readonly SealCommitmentReport[];
readonly blockingWasmParms: readonly WasmParamCarrierReport[];
readonly blockingJsAes: readonly JsAesUnwrapReport[];
readonly blockingJsHydrateDump: readonly JsWasmHydrateDumpReport[];
readonly blockingWasmXorMask: readonly WasmXorMaskSidecarReport[];
readonly blockingWasmSealXor: readonly WasmSealXorKnownPlaintextReport[];
} {
// Harden project-level: do not include protect-time gates in the scan used
// for the early refuse path (preserves prior semantics).
const report = scanPackagingGates({
...options,
includeProtectTimeGates: false,
});
const intensity: ProtectionIntensity = options.intensity ?? "bankrupt";
const blockingSeals =
intensityEnforcesSealRefusal(intensity) && options.allowPlaintextSeal !== true
? report.details.seals.filter((r) => r.shouldRefuseBankrupt)
: [];
const blockingWasmParms =
intensityEnforcesWasmParamRefusal(intensity) &&
options.allowWasmClearParamCarriers !== true
? report.details.wasmParams.filter((r) => r.shouldRefuseBankrupt)
: [];
const blockingJsAes =
intensityEnforcesJsAesUnwrapRefusal(intensity) &&
options.allowJsAesUnwrap !== true
? report.details.jsAes.filter((r) => r.shouldRefuseBankrupt)
: [];
const blockingJsHydrateDump =
intensityEnforcesJsWasmHydrateDumpRefusal(intensity) &&
options.allowJsWasmHydrateDump !== true
? report.details.jsHydrateDump.filter((r) => r.shouldRefuseBankrupt)
: [];
const blockingWasmXorMask =
intensityEnforcesWasmXorMaskSidecarRefusal(intensity) &&
options.allowWasmXorMaskSidecar !== true
? report.details.wasmXorMask.filter((r) => r.shouldRefuseBankrupt)
: [];
const blockingWasmSealXor =
intensityEnforcesWasmSealXorKnownPlaintextRefusal(intensity) &&
options.allowWasmSealXorKnownPlaintext !== true
? report.details.wasmSealXor.filter((r) => r.shouldRefuseBankrupt)
: [];
return {
report,
blockingSeals,
blockingWasmParms,
blockingJsAes,
blockingJsHydrateDump,
blockingWasmXorMask,
blockingWasmSealXor,
};
}
/** Human-readable CLI/MCP text for a packaging-gates report. */
export function formatPackagingGatesReport(report: PackagingGatesReport): string {
const lines: string[] = [
`BLA packaging gates — ${report.directory}`,
report.oneLineAdvice,
report.honestyNote,
];
if (report.findings.length === 0) {
lines.push(" (no findings)");
return lines.join("\n");
}
for (const f of report.findings) {
const tag = f.shouldRefuseBankrupt ? "refuse" : "info";
lines.push(
` [${tag}] ${f.gate} · ${f.relativePath} · ${f.findingCount} finding(s)`,
);
lines.push(` ${f.oneLineAdvice}`);
}
if (report.blocking.length > 0) {
lines.push(`blocking (${report.blocking.length}):`);
for (const b of report.blocking) {
lines.push(` - ${b.gate} · ${b.relativePath}`);
}
}
return lines.join("\n");
}
+383
View File
@@ -0,0 +1,383 @@
/**
* Stable panel-derive ABI lint + rewrite (red-blue round-3 / round-4 residual).
*
* Detects durable entitlement panel helpers such as `__vaultPanelDerive_r3`,
* local `deriveLocal` entrypoints, classic FNV prime literals, and the
* offline-oracle packaging of a callable derive beside plaintext
* `panelTokenSha256` (seal digest or in-source compare target).
*
* At maximum/bankrupt, protect rewrites `__vaultPanelDerive*` and `deriveLocal`
* to seed-stable `_blaPd_*` / `_blaPdLocal_*` names (same root seed → same
* rename across JS + HTML). Round-4 oracle combo (deriveLocal + panelTokenSha256,
* including sibling seal.json) is severity **error** and bankrupt refuses
* unless `allowPanelOfflineOracle`.
*
* Lab fixtures that must keep the stable ABI / oracle packaging can pass
* `allowStablePanelDeriveAbi` / `--allow-stable-panel-derive` and/or
* `allowPanelOfflineOracle` / `--allow-panel-offline-oracle`.
*
* DEFENSIVE ONLY — rename is not a cryptographic fix for the oracle; honesty
* bound: scrub digests / avoid shipping callable derive UI when possible.
*/
import { createHash } from "node:crypto";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { findSiblingSealSidecars } from "./seal-commitment-lint.js";
export const PANEL_DERIVE_ABI_SCHEMA = "bla-panel-derive-abi-lint/v1" as const;
export type PanelDeriveFindingId =
| "stable-panel-derive-global"
| "stable-local-derive"
| "classic-fnv-prime-literal"
| "panel-token-sha-oracle";
export type PanelDeriveSeverity = "warning" | "error";
export interface PanelDeriveFinding {
readonly id: PanelDeriveFindingId;
readonly severity: PanelDeriveSeverity;
readonly summary: string;
readonly evidence: string;
}
export interface PanelDeriveAbiReport {
readonly schema: typeof PANEL_DERIVE_ABI_SCHEMA;
readonly path: string;
readonly findings: readonly PanelDeriveFinding[];
readonly looksExposed: boolean;
/** True when bankrupt/maximum should rewrite stable symbols. */
readonly shouldRewriteOrRefuse: boolean;
/**
* True when bankrupt should refuse: callable local derive + plaintext
* panelTokenSha256 offline-oracle packaging (same file or sibling seal).
*/
readonly shouldRefuseBankrupt: boolean;
readonly oneLineAdvice: string;
readonly stableSymbols: readonly string[];
readonly localDeriveSymbols: readonly string[];
}
const STABLE_PANEL_DERIVE = /__vaultPanelDerive(?:_[A-Za-z0-9]+)?/g;
/** Stable local panel derive name that survived R3 global rewrite. */
const LOCAL_DERIVE_DECL =
/\bfunction\s+deriveLocal\b|\b(?:const|let|var)\s+deriveLocal\s*=/;
const PANEL_TOKEN_SHA = /\bpanelTokenSha256\b/;
const CLASSIC_FNV =
/\b0x811c9dc5\b|\b2166136261\b|\b0x01000193\b|\b16777619\b/gi;
function finding(
id: PanelDeriveFindingId,
severity: PanelDeriveSeverity,
summary: string,
evidence: string,
): PanelDeriveFinding {
return {
id,
severity,
summary,
evidence: evidence.slice(0, 160),
};
}
/**
* Strip protect-internal seed suffixes so JS + HTML inline scripts share
* the same panel-derive rename under one harden/protect seed.
*/
export function panelDeriveSeedRoot(seed: string): string {
return seed
.replace(/:html-script-\d+$/i, "")
.replace(/:html-bootstrap$/i, "");
}
export function panelDeriveReplacementName(seedRoot: string, original: string): string {
const hex = createHash("sha256")
.update(seedRoot, "utf8")
.update("\0", "utf8")
.update(original, "utf8")
.digest("hex")
.slice(0, 10);
return `_blaPd_${hex}`;
}
export function panelLocalDeriveReplacementName(seedRoot: string, original: string): string {
const hex = createHash("sha256")
.update(seedRoot, "utf8")
.update("\0local\0", "utf8")
.update(original, "utf8")
.digest("hex")
.slice(0, 10);
return `_blaPdLocal_${hex}`;
}
function siblingSealHasPanelTokenSha(filePath: string | undefined): boolean {
if (!filePath || filePath === "<memory>") return false;
try {
const dir = dirname(resolve(filePath));
for (const sealPath of findSiblingSealSidecars(dir)) {
const body = readFileSync(sealPath, "utf8");
if (PANEL_TOKEN_SHA.test(body)) return true;
}
} catch {
return false;
}
return false;
}
export function lintPanelDeriveAbiSource(
source: string,
options: { readonly path?: string } = {},
): PanelDeriveAbiReport {
const pathLabel = options.path ?? "<memory>";
const text = source.length > 500_000 ? source.slice(0, 500_000) : source;
const findings: PanelDeriveFinding[] = [];
const symbols = new Set<string>();
const localSymbols = new Set<string>();
STABLE_PANEL_DERIVE.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = STABLE_PANEL_DERIVE.exec(text)) !== null) {
symbols.add(m[0]!);
}
if (symbols.size > 0) {
const list = [...symbols].sort();
findings.push(
finding(
"stable-panel-derive-global",
"error",
"Stable panel derive global/ABI survived — rename or let bankrupt protect rewrite to _blaPd_*.",
list.join(","),
),
);
}
const hasLocalDecl = /\bfunction\s+deriveLocal\b/.test(text) || LOCAL_DERIVE_DECL.test(text);
if (hasLocalDecl) {
localSymbols.add("deriveLocal");
findings.push(
finding(
"stable-local-derive",
"error",
"Stable local deriveLocal panel entrypoint — rename or let maximum/bankrupt protect rewrite to _blaPdLocal_*.",
"deriveLocal",
),
);
}
CLASSIC_FNV.lastIndex = 0;
const fnvHit = text.match(CLASSIC_FNV);
if (fnvHit && fnvHit.length > 0) {
findings.push(
finding(
"classic-fnv-prime-literal",
"warning",
"Classic FNV prime literal(s) near panel/token code — prefer opaque/split constants when they back entitlement tokens.",
[...new Set(fnvHit.map((s) => s.toLowerCase()))].join(","),
),
);
}
const hasPanelTokenSha = PANEL_TOKEN_SHA.test(text);
const siblingOracle = siblingSealHasPanelTokenSha(
pathLabel.includes("#") ? pathLabel.replace(/#.*$/, "") : pathLabel,
);
const hasLocalDerive = localSymbols.size > 0;
if ((hasPanelTokenSha && hasLocalDerive) || (hasLocalDerive && siblingOracle)) {
findings.push(
finding(
"panel-token-sha-oracle",
"error",
"Panel offline oracle: callable deriveLocal (or local derive) beside plaintext panelTokenSha256 (in-source or sibling seal.json) — scrub digest, avoid shipping derive UI, or refuse bankrupt.",
hasPanelTokenSha
? "deriveLocal+panelTokenSha256(same-file)"
: "deriveLocal+sibling seal.json panelTokenSha256",
),
);
} else if (hasPanelTokenSha) {
findings.push(
finding(
"panel-token-sha-oracle",
"warning",
"Plaintext panelTokenSha256 compare target in source — offline oracle if a callable derive UI ships nearby.",
"panelTokenSha256",
),
);
}
const shouldRewriteOrRefuse = findings.some(
(f) =>
(f.id === "stable-panel-derive-global" || f.id === "stable-local-derive") &&
f.severity === "error",
);
const shouldRefuseBankrupt = findings.some(
(f) => f.id === "panel-token-sha-oracle" && f.severity === "error",
);
return {
schema: PANEL_DERIVE_ABI_SCHEMA,
path: pathLabel,
findings,
looksExposed: findings.length > 0,
shouldRewriteOrRefuse,
shouldRefuseBankrupt,
stableSymbols: [...symbols].sort(),
localDeriveSymbols: [...localSymbols].sort(),
oneLineAdvice:
findings.length === 0
? "No stable panel-derive ABI / local deriveLocal / panelTokenSha256 oracle footgun detected (heuristic)."
: shouldRefuseBankrupt
? "ERROR: Panel offline oracle (deriveLocal + panelTokenSha256). Bankrupt refuses unless allowPanelOfflineOracle / --allow-panel-offline-oracle. Rename alone is not a crypto fix — scrub digests / avoid derive UI. Defensive guidance only."
: shouldRewriteOrRefuse
? "ERROR: Stable __vaultPanelDerive_* / deriveLocal ABI. Maximum/bankrupt protect rewrites to _blaPd_* / _blaPdLocal_*; pass allowStablePanelDeriveAbi / --allow-stable-panel-derive to keep. Defensive guidance only."
: "WARNING: Classic FNV primes and/or panelTokenSha256 remain as readable literals — scrub or split when feasible.",
};
}
export function lintPanelDeriveAbiFile(filePath: string): PanelDeriveAbiReport {
const abs = resolve(filePath);
if (!existsSync(abs)) {
throw new Error(`panel-derive-abi target not found: ${abs}`);
}
return lintPanelDeriveAbiSource(readFileSync(abs, "utf8"), { path: abs });
}
export interface PanelDeriveRewriteResult {
readonly code: string;
readonly rewrote: boolean;
readonly renames: ReadonlyArray<{ readonly from: string; readonly to: string }>;
}
/**
* Rewrite stable `__vaultPanelDerive*` and `deriveLocal` tokens to seed-stable
* `_blaPd_<hex>` / `_blaPdLocal_<hex>`. Same seedRoot + original → same
* replacement (cross JS/HTML under one protect seed).
*/
export function rewriteStablePanelDeriveSymbols(
source: string,
seed: string,
): PanelDeriveRewriteResult {
const seedRoot = panelDeriveSeedRoot(seed);
const symbols = new Set<string>();
STABLE_PANEL_DERIVE.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = STABLE_PANEL_DERIVE.exec(source)) !== null) {
symbols.add(m[0]!);
}
const hasLocal = LOCAL_DERIVE_DECL.test(source) || /\bfunction\s+deriveLocal\b/.test(source);
if (symbols.size === 0 && !hasLocal) {
return { code: source, rewrote: false, renames: [] };
}
const renames = [...symbols]
.sort()
.map((from) => ({ from, to: panelDeriveReplacementName(seedRoot, from) }));
if (hasLocal) {
renames.push({
from: "deriveLocal",
to: panelLocalDeriveReplacementName(seedRoot, "deriveLocal"),
});
}
// Replace longer names first to avoid partial overlap (none expected, but safe).
let code = source;
for (const { from, to } of [...renames].sort((a, b) => b.from.length - a.from.length)) {
if (from === "deriveLocal") {
// Word-boundary safe replace for the local identifier.
code = code.replace(/\bderiveLocal\b/g, to);
} else {
code = code.split(from).join(to);
}
}
return { code, rewrote: true, renames };
}
export function panelDeriveRefuseMessage(
report: PanelDeriveAbiReport,
filePath: string,
): string {
if (report.shouldRefuseBankrupt) {
return (
`Refusing bankrupt harden/protect: panel offline oracle at ${filePath}` +
` [deriveLocal + panelTokenSha256]. ` +
`Scrub plaintext panel token digests and avoid shipping a callable derive UI beside them. ` +
`Rename alone is not a cryptographic fix. ` +
`To override (lab fixture only), pass allowPanelOfflineOracle / --allow-panel-offline-oracle / allow_panel_offline_oracle:true.`
);
}
const syms = [...report.stableSymbols, ...report.localDeriveSymbols].join(", ");
return (
`Refusing bankrupt harden/protect: stable panel-derive ABI at ${filePath}` +
(syms ? ` [${syms}]` : "") +
`. Rename the helper or allow protect to rewrite it. ` +
`To keep the stable ABI (lab only), pass allowStablePanelDeriveAbi / --allow-stable-panel-derive / allow_stable_panel_derive:true.`
);
}
export function intensityRewritesPanelDerive(intensity: string): boolean {
return intensity === "maximum" || intensity === "bankrupt";
}
export function intensityEnforcesPanelOracleRefusal(intensity: string): boolean {
return intensity === "bankrupt";
}
const PANEL_SKIP_DIRS = new Set([
"node_modules",
".git",
".hg",
".svn",
".bla-hardened",
"coverage",
".turbo",
".cache",
"__pycache__",
".venv",
"venv",
]);
const PANEL_JS_EXT = /\.(?:[cm]?[jt]s|tsx?|html?)$/i;
const PANEL_MAX_FILES = 64;
const PANEL_MAX_DEPTH = 8;
function walkPanelCandidates(dir: string, depth: number, out: string[]): void {
if (out.length >= PANEL_MAX_FILES || depth > PANEL_MAX_DEPTH) return;
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (out.length >= PANEL_MAX_FILES) return;
if (entry.isDirectory()) {
if (PANEL_SKIP_DIRS.has(entry.name) || entry.name.startsWith(".")) continue;
walkPanelCandidates(join(dir, entry.name), depth + 1, out);
continue;
}
if (!entry.isFile()) continue;
if (!PANEL_JS_EXT.test(entry.name)) continue;
out.push(join(dir, entry.name));
}
}
/**
* Discover JS/TS/HTML under a directory and lint each for panel-derive footguns.
* Used by unified `bla lint` / packaging-gates.
*/
export function discoverAndLintPanelDerive(
directory: string,
): readonly PanelDeriveAbiReport[] {
const abs = resolve(directory);
if (!existsSync(abs)) {
throw new Error(`Path not found: ${abs}`);
}
const st = statSync(abs);
if (st.isFile()) {
return [lintPanelDeriveAbiFile(abs)];
}
const candidates: string[] = [];
walkPanelCandidates(abs, 0, candidates);
return candidates.map((p) => lintPanelDeriveAbiFile(p));
}
+252 -13
View File
@@ -12,7 +12,7 @@ import {
unlinkSync,
writeFileSync,
} from "node:fs";
import { basename, dirname, extname, join, resolve } from "node:path";
import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
import { detectArtifactFormat } from "../core/detector.js";
import { assertSafeOutputPath } from "../core/output-path.js";
import { withLlmDirectives } from "../core/llm-directives.js";
@@ -46,6 +46,49 @@ import { protectPcapCaptureBuffer } from "../shields/formats/pcap-capture.js";
import { protectGpuPtxText } from "../shields/formats/gpu-ptx.js";
import { protectUf2FirmwareBuffer } from "../shields/formats/firmware-uf2.js";
import { auditTarget } from "./auditor.js";
import {
formatSupportsLaneIndependenceLint,
laneIndependenceRefuseMessage,
lintLaneIndependence,
} from "./lane-independence-lint.js";
import {
findSiblingSealSidecars,
intensityEnforcesSealRefusal,
lintSealCommitmentFile,
sealCommitmentRefuseMessage,
} from "./seal-commitment-lint.js";
import {
intensityEnforcesWasmParamRefusal,
lintWasmParamCarrierBuffer,
wasmParamCarrierRefuseMessage,
} from "./wasm-param-carrier-lint.js";
import {
lintWasmXorMaskSidecarBuffer,
intensityEnforcesWasmXorMaskSidecarRefusal,
wasmXorMaskSidecarRefuseMessage,
} from "./wasm-xor-mask-sidecar-lint.js";
import {
lintWasmSealXorKnownPlaintextFile,
intensityEnforcesWasmSealXorKnownPlaintextRefusal,
wasmSealXorKnownPlaintextRefuseMessage,
} from "./wasm-seal-xor-known-plaintext-lint.js";
import {
intensityEnforcesPanelOracleRefusal,
intensityRewritesPanelDerive,
lintPanelDeriveAbiSource,
panelDeriveRefuseMessage,
rewriteStablePanelDeriveSymbols,
} from "./panel-derive-abi-lint.js";
import {
intensityEnforcesJsAesUnwrapRefusal,
jsAesUnwrapRefuseMessage,
lintJsAesUnwrapSource,
} from "./js-aes-unwrap-lint.js";
import {
intensityEnforcesJsWasmHydrateDumpRefusal,
jsWasmHydrateDumpRefuseMessage,
lintJsWasmHydrateDumpSource,
} from "./js-wasm-hydrate-dump-lint.js";
/**
* Crash-safe output write: write to a temp file in the same directory, then
@@ -54,6 +97,66 @@ import { auditTarget } from "./auditor.js";
* hardlink targets are written through directly so in-place protection of
* aliased paths reaches the real file.
*/
function selfSealTransformOption(
options: ProtectionOptions,
absOutput: string,
): boolean | {
readonly siblingPaths: readonly string[];
readonly expectedSiblingSha256?: Readonly<Record<string, string>>;
readonly hardFailOnSiblingMismatch?: boolean;
} | undefined {
if (options.selfSeal !== true) return undefined;
if (!options.selfSealSiblingPaths || options.selfSealSiblingPaths.length === 0) {
return true;
}
const siblingPaths = options.selfSealSiblingPaths;
const base = dirname(absOutput);
const expectedSiblingSha256: Record<string, string> = {};
for (const rel of siblingPaths) {
if (typeof rel !== "string" || rel.length === 0) continue;
const abs = isAbsolute(rel) ? rel : join(base, rel);
try {
if (!existsSync(abs)) continue;
expectedSiblingSha256[rel] = createHash("sha256")
.update(readFileSync(abs))
.digest("hex");
} catch {
/* sibling not readable yet — skip expected hash (opaque-seed only) */
}
}
return {
siblingPaths,
...(Object.keys(expectedSiblingSha256).length > 0
? {
expectedSiblingSha256,
hardFailOnSiblingMismatch: true,
}
: {}),
};
}
function applyPanelDeriveRewrite(
source: string,
seed: string,
intensity: string,
options: ProtectionOptions,
fileLabel: string,
): string {
if (options.allowStablePanelDeriveAbi === true) {
return source;
}
if (!intensityRewritesPanelDerive(intensity)) {
// Still surface refuse at bankrupt if somehow rewrite intensity is off but
// symbols remain — bankrupt always rewrites; other intensities only lint via CLI.
return source;
}
const lint = lintPanelDeriveAbiSource(source, { path: fileLabel });
if (!lint.shouldRewriteOrRefuse) return source;
const rw = rewriteStablePanelDeriveSymbols(source, seed);
return rw.code;
}
function writeFileAtomicSync(
targetPath: string,
content: string | Buffer,
@@ -122,6 +225,19 @@ function escapeHtmlInlineScriptBody(jsCode: string): string {
return jsCode.replace(/<\/(script)/gi, "<\\/$1");
}
/**
* Where `protectTarget` will write for a given input/output/inPlace triple.
* Pure path math (no filesystem access) so callers can plan or confirm writes.
*/
export function resolveProtectOutputPath(
inputPath: string,
outputPath?: string,
inPlace = false,
): string {
const absInput = resolve(inputPath);
return resolve(outputPath ?? deriveDefaultOutputPath(absInput, inPlace));
}
function deriveDefaultOutputPath(inputPath: string, inPlace = false): string {
if (inPlace) return inputPath;
const ext = extname(inputPath);
@@ -190,17 +306,70 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
let honeySourceMapsGenerated = 0;
let binarySectionsPatched = 0;
let wasmExportsRenamed = 0;
let wasmExportOrderShuffled = false;
let wasmExportDecoysInjected = 0;
/** Inline `<script>` bodies whose AST shield threw and were shipped unchanged. */
let inlineScriptsFailed = 0;
const counteredVectors = new Set<ReaAttackVectorId>();
if (
intensityEnforcesSealRefusal(intensity) &&
options.allowPlaintextSeal !== true
) {
for (const sealPath of findSiblingSealSidecars(dirname(absInput))) {
const sealReport = lintSealCommitmentFile(sealPath);
if (sealReport.shouldRefuseBankrupt) {
throw new Error(sealCommitmentRefuseMessage(sealReport, sealPath));
}
}
}
if (format === "javascript" || format === "typescript") {
const raw = readFileSync(absInput, "utf8");
const transformed = transformJavaScriptWithBlaShield(raw, {
if (
formatSupportsLaneIndependenceLint(format) &&
options.allowLaneIndependentGates !== true
) {
const laneReport = lintLaneIndependence(raw);
if (laneReport.looksLaneIndependent) {
throw new Error(laneIndependenceRefuseMessage(laneReport, absInput));
}
}
if (
intensityEnforcesJsAesUnwrapRefusal(intensity) &&
options.allowJsAesUnwrap !== true
) {
const aesReport = lintJsAesUnwrapSource(raw, { path: absInput });
if (aesReport.shouldRefuseBankrupt) {
throw new Error(jsAesUnwrapRefuseMessage(aesReport, absInput));
}
}
if (
intensityEnforcesJsWasmHydrateDumpRefusal(intensity) &&
options.allowJsWasmHydrateDump !== true
) {
const hydrateDumpReport = lintJsWasmHydrateDumpSource(raw, { path: absInput });
if (hydrateDumpReport.shouldRefuseBankrupt) {
throw new Error(jsWasmHydrateDumpRefuseMessage(hydrateDumpReport, absInput));
}
}
{
const panelLint = lintPanelDeriveAbiSource(raw, { path: absInput });
if (
intensityEnforcesPanelOracleRefusal(intensity) &&
options.allowPanelOfflineOracle !== true &&
panelLint.shouldRefuseBankrupt
) {
throw new Error(panelDeriveRefuseMessage(panelLint, absInput));
}
}
const panelSafe = applyPanelDeriveRewrite(raw, seed, intensity, options, absInput);
const selfSealOpt = selfSealTransformOption(options, absOutput);
const transformed = transformJavaScriptWithBlaShield(panelSafe, {
intensity,
seed,
filename: basename(absInput),
...(options.selfSeal === true ? { selfSeal: true as const } : {}),
...(selfSealOpt !== undefined ? { selfSeal: selfSealOpt } : {}),
});
let finalCode = transformed.code;
@@ -233,6 +402,34 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
counteredVectors.add("obligation-ledger-cloning");
} else if (format === "html-bundle") {
const rawHtml = readFileSync(absInput, "utf8");
if (
intensityEnforcesJsAesUnwrapRefusal(intensity) &&
options.allowJsAesUnwrap !== true
) {
const aesReport = lintJsAesUnwrapSource(rawHtml, { path: absInput });
if (aesReport.shouldRefuseBankrupt) {
throw new Error(jsAesUnwrapRefuseMessage(aesReport, absInput));
}
}
if (
intensityEnforcesJsWasmHydrateDumpRefusal(intensity) &&
options.allowJsWasmHydrateDump !== true
) {
const hydrateDumpReport = lintJsWasmHydrateDumpSource(rawHtml, { path: absInput });
if (hydrateDumpReport.shouldRefuseBankrupt) {
throw new Error(jsWasmHydrateDumpRefuseMessage(hydrateDumpReport, absInput));
}
}
{
const panelLint = lintPanelDeriveAbiSource(rawHtml, { path: absInput });
if (
intensityEnforcesPanelOracleRefusal(intensity) &&
options.allowPanelOfflineOracle !== true &&
panelLint.shouldRefuseBankrupt
) {
throw new Error(panelDeriveRefuseMessage(panelLint, absInput));
}
}
let inlineScriptsTransformed = 0;
let scriptIndex = 0;
let transformedHtml = rawHtml.replace(
@@ -243,11 +440,20 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
if (!tagKind.executable) return fullMatch;
const currentIndex = scriptIndex++;
try {
const res = transformJavaScriptWithBlaShield(scriptBody, {
const scriptSeed = `${seed}:html-script-${currentIndex}`;
const panelSafe = applyPanelDeriveRewrite(
scriptBody,
scriptSeed,
intensity,
seed: `${seed}:html-script-${currentIndex}`,
options,
`${absInput}#script-${currentIndex}`,
);
const selfSealOpt = selfSealTransformOption(options, absOutput);
const res = transformJavaScriptWithBlaShield(panelSafe, {
intensity,
seed: scriptSeed,
sourceType: tagKind.isModule ? "module" : "script",
...(options.selfSeal === true ? { selfSeal: true as const } : {}),
...(selfSealOpt !== undefined ? { selfSeal: selfSealOpt } : {}),
});
inlineScriptsTransformed++;
decoyFunctionsInjected += res.decoyFunctionsInjected;
@@ -272,7 +478,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
intensity,
seed: `${seed}:html-bootstrap`,
sourceType: "script",
...(options.selfSeal === true ? { selfSeal: true as const } : {}),
...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
});
decoyFunctionsInjected += bootstrapRes.decoyFunctionsInjected;
fakeCrossReferencesCreated += bootstrapRes.fakeCrossReferencesCreated;
@@ -318,7 +524,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
intensity,
seed: `${seed}:${vf.relativePath}`,
filename: vf.relativePath,
...(options.selfSeal === true ? { selfSeal: true as const } : {}),
...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
});
const honey = generateHoneySourceMap(
basename(vf.relativePath),
@@ -363,14 +569,14 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
{
intensity,
seed: `${seed}:enclave-decoy`,
...(options.selfSeal === true ? { selfSeal: true as const } : {}),
...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
},
);
protectedFiles.push({
relativePath: "enclave/hardware-tee-bridge.js",
content: Buffer.from(decoyBridgeJs.code, "utf8"),
...(options.selfSeal === true ? { selfSeal: true as const } : {}),
...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
});
// Flood ASAR Pickle JSON header past REA DEFAULT_ASAR_MAX_HEADER_BYTES at
@@ -392,11 +598,38 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
counteredVectors.add("asar-header-admission");
} else if (format === "wasm") {
const rawWasm = readFileSync(absInput);
if (
intensityEnforcesWasmParamRefusal(intensity) &&
options.allowWasmClearParamCarriers !== true
) {
const wasmParm = lintWasmParamCarrierBuffer(rawWasm, { path: absInput });
if (wasmParm.shouldRefuseBankrupt) {
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));
}
}
if (
intensityEnforcesWasmSealXorKnownPlaintextRefusal(intensity) &&
options.allowWasmSealXorKnownPlaintext !== true
) {
const sealXor = lintWasmSealXorKnownPlaintextFile(absInput);
if (sealXor.shouldRefuseBankrupt) {
throw new Error(wasmSealXorKnownPlaintextRefuseMessage(sealXor, absInput));
}
}
const res = protectWasmBinary(rawWasm, {
intensity,
seed,
// Issue #40.3: rename internal-looking exports at maximum/bankrupt by default;
// wasmPreserveExports keeps the customer public ABI.
// Issue #40.3 / red-blue round-1: rename ALL non-preserved exports at
// maximum/bankrupt by default; wasmPreserveExports is the explicit ABI keep-list.
...(options.wasmPreserveExports && options.wasmPreserveExports.length > 0
? { preserveExports: options.wasmPreserveExports }
: {}),
@@ -407,6 +640,8 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
chaffPayloadsEmbedded = res.chaffPayloadsEmbedded;
binarySectionsPatched = res.customSectionsAdded;
wasmExportsRenamed = res.exportsRenamed.length;
wasmExportOrderShuffled = res.exportsOrderShuffled === true;
wasmExportDecoysInjected = res.exportDecoysInjected;
counteredVectors.add("wasm-wat-interface");
counteredVectors.add("obligation-ledger-cloning");
} else if (format === "python-source") {
@@ -607,7 +842,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
intensity,
seed: `${seed}:${entry.name}`,
filename: entry.name,
...(options.selfSeal === true ? { selfSeal: true as const } : {}),
...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
});
const honey = generateHoneySourceMap(
entry.name,
@@ -696,6 +931,10 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
...(options.weaveDecoys === true ? { weaveDecoys: true as const } : {}),
...(options.selfSeal === true ? { selfSeal: true as const } : {}),
...(wasmExportsRenamed > 0 ? { wasmExportRenameApplied: true as const } : {}),
...(wasmExportOrderShuffled ? { wasmExportOrderShuffled: true as const } : {}),
...(wasmExportDecoysInjected > 0
? { wasmExportDecoysInjected }
: {}),
seed,
originalSha256: beforeAudit.sha256,
protectedSha256: afterAudit.sha256,
+271
View File
@@ -0,0 +1,271 @@
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
export const BLA_PACKAGE_ROOT = resolve(MODULE_DIR, "../..");
/** Resolve sibling REA checkout the same way scripts/verify-rea-constants.mjs does. */
export function resolveReaRoot(override?: string): string {
const fromArg = (override ?? "").trim();
const fromEnv = (process.env.REA_ROOT ?? "").trim();
return resolve(fromArg || fromEnv || join(BLA_PACKAGE_ROOT, "..", "rea"));
}
export function reaCheckoutPresent(reaRoot = resolveReaRoot()): boolean {
return (
reaRoot !== BLA_PACKAGE_ROOT &&
existsSync(reaRoot) &&
existsSync(join(reaRoot, "src"))
);
}
export function reaDistReady(reaRoot = resolveReaRoot()): boolean {
return existsSync(join(reaRoot, "dist", "go", "GoBinaryImage.js"));
}
/** Cap harness chatter so MCP stdio JSON cannot blow the line limit. */
const MAX_OBSERVABILITY_STREAM_CHARS = 32_768;
function clipObservabilityStream(text: string): string {
if (text.length <= MAX_OBSERVABILITY_STREAM_CHARS) return text;
return `${text.slice(0, MAX_OBSERVABILITY_STREAM_CHARS)}\n…[truncated]`;
}
/**
* - `pass` / `fail`: a live harness ran (drift check, or redteam with execute:true).
* - `available`: an on-disk empirical report was read without re-running REA
* (not live proof — agents must not treat this as a fresh red-team pass).
* - `unverified`: required inputs missing; never a silent success.
*/
export type ReaObservabilityStatus = "pass" | "fail" | "unverified" | "available";
export interface ReaDriftReport {
readonly schema: "bla-rea-drift/v1";
readonly status: ReaObservabilityStatus;
readonly reaRoot: string;
readonly blaRoot: string;
readonly exitCode: number | null;
readonly reason?: string;
readonly stdout: string;
readonly stderr: string;
/** True when this is not empirical red-team evidence. */
readonly notRedTeamEvidence: true;
}
/**
* Thin wrapper around `scripts/verify-rea-constants.mjs`.
* Absent REA → explicit `unverified` (never a silent pass).
* Present REA → spawn the harness; exit 0 → pass, else fail.
*/
export function runReaDriftCheck(options: {
readonly reaRoot?: string;
readonly timeoutMs?: number;
} = {}): ReaDriftReport {
const blaRoot = BLA_PACKAGE_ROOT;
const reaRoot = resolveReaRoot(options.reaRoot);
const base = {
schema: "bla-rea-drift/v1" as const,
reaRoot,
blaRoot,
notRedTeamEvidence: true as const,
};
if (!reaCheckoutPresent(reaRoot)) {
return {
...base,
status: "unverified",
exitCode: null,
reason: `Sibling REA checkout not found at ${reaRoot} (set REA_ROOT or place REA next to BLA). Drift check cannot run.`,
stdout: "",
stderr: "",
};
}
const script = join(blaRoot, "scripts", "verify-rea-constants.mjs");
if (!existsSync(script)) {
return {
...base,
status: "unverified",
exitCode: null,
reason: `Drift harness missing: ${script}`,
stdout: "",
stderr: "",
};
}
const result = spawnSync(process.execPath, [script], {
cwd: blaRoot,
encoding: "utf8",
env: { ...process.env, REA_ROOT: reaRoot },
timeout: options.timeoutMs ?? 120_000,
});
const stdout = clipObservabilityStream(result.stdout ?? "");
const stderr = clipObservabilityStream(result.stderr ?? "");
if (result.error) {
return {
...base,
status: "unverified",
exitCode: result.status,
reason: `Failed to spawn drift harness: ${result.error.message}`,
stdout,
stderr,
};
}
const exitCode = result.status ?? 1;
return {
...base,
status: exitCode === 0 ? "pass" : "fail",
exitCode,
...(exitCode === 0
? {}
: { reason: "REA constant drift detected (see stdout)" }),
stdout,
stderr,
};
}
export const REDTEAM_REPORT_JSON = join(
BLA_PACKAGE_ROOT,
"docs",
"redteam",
"empirical-rea-validation.json",
);
export interface RedteamReportResult {
readonly schema: "bla-redteam-report/v1";
readonly status: ReaObservabilityStatus;
readonly reaRoot: string;
readonly blaRoot: string;
readonly reportPath: string;
readonly reason?: string;
readonly report?: unknown;
readonly executed: boolean;
readonly exitCode: number | null;
readonly stdout: string;
readonly stderr: string;
}
/**
* Read (and optionally re-run) the empirical REA red-team report.
* - Default: return the on-disk JSON when present (`status: available` — not a live pass).
* - `execute: true`: spawn `scripts/redteam/run.mjs` when REA dist is ready (`pass`/`fail`).
* - Missing report AND missing/unready REA → explicit `unverified`.
*/
export function getRedteamReport(options: {
readonly reaRoot?: string;
readonly execute?: boolean;
readonly timeoutMs?: number;
readonly reportPath?: string;
} = {}): RedteamReportResult {
const blaRoot = BLA_PACKAGE_ROOT;
const reaRoot = resolveReaRoot(options.reaRoot);
const reportPath = resolve(options.reportPath ?? REDTEAM_REPORT_JSON);
const base = {
schema: "bla-redteam-report/v1" as const,
reaRoot,
blaRoot,
reportPath,
};
if (options.execute === true) {
if (!reaDistReady(reaRoot)) {
return {
...base,
status: "unverified",
executed: false,
exitCode: null,
reason: `REA dist not ready at ${join(reaRoot, "dist")} — cannot execute redteam:rea. Build sibling REA or omit execute to read a prior report.`,
stdout: "",
stderr: "",
};
}
const script = join(blaRoot, "scripts", "redteam", "run.mjs");
if (!existsSync(script)) {
return {
...base,
status: "unverified",
executed: false,
exitCode: null,
reason: `Red-team harness missing: ${script}`,
stdout: "",
stderr: "",
};
}
const result = spawnSync(process.execPath, [script], {
cwd: blaRoot,
encoding: "utf8",
env: { ...process.env, REA_ROOT: reaRoot },
timeout: options.timeoutMs ?? 600_000,
});
const stdout = clipObservabilityStream(result.stdout ?? "");
const stderr = clipObservabilityStream(result.stderr ?? "");
if (result.error) {
return {
...base,
status: "unverified",
executed: false,
exitCode: result.status,
reason: `Failed to spawn red-team harness: ${result.error.message}`,
stdout,
stderr,
};
}
const exitCode = result.status ?? 1;
if (exitCode !== 0) {
return {
...base,
status: "fail",
executed: true,
exitCode,
reason: "redteam:rea exited non-zero",
stdout,
stderr,
};
}
// Fall through to read the freshly written report.
}
if (!existsSync(reportPath)) {
const reaHint = reaDistReady(reaRoot)
? "REA dist is ready — pass execute:true to run the harness."
: `REA dist not ready at ${reaRoot}; cannot fabricate a red-team report.`;
return {
...base,
status: "unverified",
executed: false,
exitCode: null,
reason: `No empirical report at ${reportPath}. ${reaHint}`,
stdout: "",
stderr: "",
};
}
try {
const report = JSON.parse(readFileSync(reportPath, "utf8"));
const executed = options.execute === true;
return {
...base,
// Live execute → pass; plain on-disk read → available (not a fresh REA verdict).
status: executed ? "pass" : "available",
executed,
exitCode: executed ? 0 : null,
report,
stdout: "",
stderr: "",
};
} catch (err) {
return {
...base,
status: "fail",
executed: options.execute === true,
exitCode: null,
reason: `Report exists but is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,
stdout: "",
stderr: "",
};
}
}
+139
View File
@@ -0,0 +1,139 @@
import { createHash } from "node:crypto";
import { existsSync, readFileSync, statSync } from "node:fs";
import { join, resolve } from "node:path";
/** File name of the project-level summary `hardenProject` writes. */
export const HARDEN_SUMMARY_FILE_NAME = "bla-harden-summary.json";
/** Current summary schema; v2 adds `runId`. */
export const HARDEN_SUMMARY_SCHEMA = "bla-harden-summary/v2";
/** Stable inputs that identify one harden run's planned work. */
export interface HardenRunIdentity {
readonly blaVersion: string;
readonly directory: string;
readonly intensity: string;
readonly weaveDecoys: boolean;
readonly selfSeal: boolean;
readonly artifacts: readonly {
readonly relativePath: string;
readonly format: string;
readonly outputPath: string;
}[];
}
/**
* Deterministic, content-addressed run id: identical inputs and planned outputs
* always yield the same id, so it can be recomputed and cross-checked later.
* Unsigned — it proves consistency, not authorship.
*/
export function computeHardenRunId(identity: HardenRunIdentity): string {
const artifacts = [...identity.artifacts]
.map((a) => ({
relativePath: a.relativePath,
format: a.format,
outputPath: a.outputPath,
}))
.sort((x, y) => (x.relativePath < y.relativePath ? -1 : x.relativePath > y.relativePath ? 1 : 0));
const canonical = JSON.stringify({
blaVersion: identity.blaVersion,
directory: identity.directory,
intensity: identity.intensity,
weaveDecoys: identity.weaveDecoys,
selfSeal: identity.selfSeal,
artifacts,
});
return `bla-run-${createHash("sha256").update(canonical).digest("hex").slice(0, 24)}`;
}
export interface HardenRunSummary {
readonly schema: string;
readonly runId: string;
readonly [key: string]: unknown;
}
export interface ReadHardenRunSummaryResult {
readonly summaryPath: string;
readonly runId: string;
readonly runIdMatches: boolean | null;
readonly summary: HardenRunSummary;
}
/**
* Read back a persisted harden summary (file, or the directory holding it) and
* optionally assert it belongs to `expectRunId`. Throws on a missing/unreadable
* file, a non-summary JSON, a pre-v2 summary without `runId`, or an id mismatch,
* so a bad lookup can never read as a successful correlation.
*/
export function readHardenRunSummary(
location: string,
expectRunId?: string,
): ReadHardenRunSummaryResult {
const abs = resolve(location);
if (!existsSync(abs)) {
throw new Error(`Run summary not found: ${abs}`);
}
const summaryPath = statSync(abs).isDirectory() ? join(abs, HARDEN_SUMMARY_FILE_NAME) : abs;
if (!existsSync(summaryPath)) {
throw new Error(`Run summary not found: ${summaryPath}`);
}
let parsed: unknown;
try {
parsed = JSON.parse(readFileSync(summaryPath, "utf8"));
} catch (err) {
throw new Error(
`Run summary is not valid JSON: ${summaryPath} (${err instanceof Error ? err.message : String(err)})`,
);
}
if (
typeof parsed !== "object" ||
parsed === null ||
Array.isArray(parsed) ||
typeof (parsed as { schema?: unknown }).schema !== "string" ||
!(parsed as { schema: string }).schema.startsWith("bla-harden-summary/")
) {
throw new Error(`Not a BLA harden summary: ${summaryPath}`);
}
const record = parsed as { schema: string; runId?: unknown };
if (typeof record.runId !== "string" || record.runId.length === 0) {
throw new Error(
`Harden summary has no runId (schema ${record.schema}); re-run bla_harden to produce ${HARDEN_SUMMARY_SCHEMA}: ${summaryPath}`,
);
}
const runId = record.runId;
if (expectRunId !== undefined && expectRunId !== runId) {
throw new Error(
`Run id mismatch: expected ${expectRunId} but ${summaryPath} records ${runId}`,
);
}
return {
summaryPath,
runId,
runIdMatches: expectRunId === undefined ? null : true,
summary: parsed as HardenRunSummary,
};
}
/** sha256 hex of a file's bytes, for content-addressing single-artifact outputs. */
export function sha256File(path: string): string {
return createHash("sha256").update(readFileSync(path)).digest("hex");
}
/**
* Deterministic run id for a single-artifact defend/protect run, bound to the
* produced output bytes so a later re-hash can confirm the output is unchanged.
*/
export function computeArtifactRunId(input: {
readonly tool: string;
readonly inputPath: string;
readonly outputPath: string;
readonly outputSha256: string;
}): string {
const canonical = JSON.stringify({
tool: input.tool,
inputPath: resolve(input.inputPath),
outputPath: resolve(input.outputPath),
outputSha256: input.outputSha256,
});
return `bla-run-${createHash("sha256").update(canonical).digest("hex").slice(0, 24)}`;
}
+376
View File
@@ -0,0 +1,376 @@
/**
* Plaintext seal sidecar / reversible public-commitment lint (red-blue round-2).
*
* Detects entitlement/seal JSON that ships salts + rounds + a short public
* `revision` (custom reversible ARX/Feistel shape) and/or certificate ciphertext
* as an offline oracle package. One-way digests (SHA-256 / HMAC / blake, …)
* without invertible ARX parameters pass.
*
* Findings: reversible shapes are severity **"error"**; bare plaintext seal
* packaging without a reversible digest is **"warning"**. Bankrupt harden
* refuses error findings unless `allowPlaintextSeal` is set.
*
* DEFENSIVE ONLY — no inversion / crack advice.
*/
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { basename, join, resolve } from "node:path";
export const SEAL_COMMITMENT_SCHEMA = "bla-seal-commitment-lint/v1" as const;
export type SealCommitmentFindingId =
| "plaintext-seal-sidecar"
| "reversible-public-commitment"
| "seal-offline-oracle-package";
export type SealCommitmentSeverity = "warning" | "error";
export interface SealCommitmentFinding {
readonly id: SealCommitmentFindingId;
readonly severity: SealCommitmentSeverity;
readonly summary: string;
readonly evidence: string;
}
export interface SealCommitmentReport {
readonly schema: typeof SEAL_COMMITMENT_SCHEMA;
readonly path: string;
readonly findings: readonly SealCommitmentFinding[];
/** True when any finding is present. */
readonly looksExposed: boolean;
/** True when bankrupt harden should refuse (error findings). */
readonly shouldRefuseBankrupt: boolean;
readonly oneLineAdvice: string;
}
const ONE_WAY_ALGO =
/^(?:sha-?256|sha-?384|sha-?512|sha-?3(?:-?(?:256|384|512))?|hmac(?:-?sha-?(?:256|512))?|blake2?b?(?:-?\d+)?|argon2id?|scrypt|pbkdf2)$/i;
const SEAL_NAME =
/^(?:seal|license-seal|entitlement-seal|catalog-seal)(?:\.[\w-]+)*\.json$/i;
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_SEAL_FILES = 32;
const MAX_JSON_BYTES = 400_000;
function finding(
id: SealCommitmentFindingId,
severity: SealCommitmentSeverity,
summary: string,
evidence: string,
): SealCommitmentFinding {
return {
id,
severity,
summary,
evidence: evidence.slice(0, 160),
};
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function asString(value: unknown): string | undefined {
return typeof value === "string" && value.length > 0 ? value : undefined;
}
function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function looksLikeSealFileName(fileName: string): boolean {
const base = basename(fileName);
if (SEAL_NAME.test(base)) return true;
if (base.toLowerCase() === "seal.json") return true;
if (/\.seal\.json$/i.test(base)) return true;
return false;
}
function declaredOneWay(algorithm: string | undefined): boolean {
if (!algorithm) return false;
const trimmed = algorithm.trim();
if (ONE_WAY_ALGO.test(trimmed)) return true;
// Allow "sha256:" / "hmac-sha256:" prefixes on digest fields.
if (ONE_WAY_ALGO.test(trimmed.replace(/:.*$/, ""))) return true;
return false;
}
function isSha256Hex(value: string): boolean {
return /^[0-9a-f]{64}$/i.test(value);
}
function isSha512Hex(value: string): boolean {
return /^[0-9a-f]{128}$/i.test(value);
}
function hasInvertibleArxParams(obj: Record<string, unknown>): boolean {
const rounds = asNumber(obj.rounds) ?? asNumber(obj.roundCount);
const salt =
asNumber(obj.scheduleSalt) ??
asNumber(obj.schedule_salt) ??
asNumber(obj.arxSalt) ??
asNumber(obj.arx_salt);
// Numeric public salt + round count is the classic invertible-ARX footgun shape.
return rounds !== undefined && rounds >= 2 && salt !== undefined;
}
function revisionField(obj: Record<string, unknown>): string | undefined {
return (
asString(obj.revision) ??
asString(obj.commitment) ??
asString(obj.digest) ??
asString(obj.expectedDigest) ??
asString(obj.publicDigest)
);
}
function looksSealShaped(obj: Record<string, unknown>, fileName: string): boolean {
if (looksLikeSealFileName(fileName)) return true;
const schema = asString(obj.schema) ?? asString(obj.$schema) ?? "";
if (/seal|entitlement|license/i.test(schema)) return true;
const keys = Object.keys(obj);
const hit =
keys.includes("revision") ||
keys.includes("commitment") ||
keys.includes("certificateCipherHex") ||
keys.includes("certificate_cipher_hex");
const saltish =
keys.includes("scheduleSalt") ||
keys.includes("schedule_salt") ||
keys.includes("rounds");
return hit && saltish;
}
/**
* Lint a UTF-8 JSON (or JSON-ish) seal/catalog body.
*/
export function lintSealCommitmentSource(
source: string,
options: { readonly path?: string } = {},
): SealCommitmentReport {
const pathLabel = options.path ?? "<memory>";
const findings: SealCommitmentFinding[] = [];
const text = source.length > MAX_JSON_BYTES ? source.slice(0, MAX_JSON_BYTES) : source;
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
return {
schema: SEAL_COMMITMENT_SCHEMA,
path: pathLabel,
findings: [],
looksExposed: false,
shouldRefuseBankrupt: false,
oneLineAdvice: "Not JSON — seal-commitment lint skipped.",
};
}
if (!isPlainObject(parsed)) {
return {
schema: SEAL_COMMITMENT_SCHEMA,
path: pathLabel,
findings: [],
looksExposed: false,
shouldRefuseBankrupt: false,
oneLineAdvice: "JSON root is not an object — seal-commitment lint skipped.",
};
}
if (!looksSealShaped(parsed, pathLabel)) {
return {
schema: SEAL_COMMITMENT_SCHEMA,
path: pathLabel,
findings: [],
looksExposed: false,
shouldRefuseBankrupt: false,
oneLineAdvice: "No seal/entitlement sidecar shape detected.",
};
}
const algorithm =
asString(parsed.algorithm) ??
asString(parsed.digestAlgorithm) ??
asString(parsed.hash) ??
asString(parsed.kdf);
const revision = revisionField(parsed);
const oneWay = declaredOneWay(algorithm);
const invertible = hasInvertibleArxParams(parsed);
const cipher =
asString(parsed.certificateCipherHex) ??
asString(parsed.certificate_cipher_hex) ??
asString(parsed.certificateCipher) ??
asString(parsed.cipherHex);
// Plaintext seal sidecar sitting on disk is always an exposure signal.
if (looksLikeSealFileName(pathLabel) || /seal|entitlement/i.test(asString(parsed.schema) ?? "")) {
findings.push(
finding(
"plaintext-seal-sidecar",
invertible || Boolean(cipher) ? "error" : "warning",
"Plaintext seal/entitlement JSON sidecar — harden does not encrypt JSON carriers; prefer omit, encrypt, or bind under self-seal.",
`keys=${Object.keys(parsed).slice(0, 12).join(",")}`,
),
);
}
if (revision && invertible && !oneWay) {
const shortCustom =
!isSha256Hex(revision) && !isSha512Hex(revision) && /^[0-9a-f]+$/i.test(revision);
// Even a 64-hex revision with scheduleSalt+rounds and no one-way algo is suspicious
// (could be truncated custom ARX); treat as reversible when ARX params present.
findings.push(
finding(
"reversible-public-commitment",
"error",
shortCustom
? "Public revision/commitment with scheduleSalt+rounds looks like a reversible ARX digest — prefer SHA-256/HMAC (one-way)."
: "Public commitment paired with numeric scheduleSalt+rounds without a declared one-way algorithm — treat as reversible-commitment footgun.",
`revision=${revision.slice(0, 20)}… rounds/salt present algorithm=${algorithm ?? "none"}`,
),
);
}
if (cipher && revision && (invertible || !oneWay)) {
findings.push(
finding(
"seal-offline-oracle-package",
"error",
"Seal packages revision/commitment together with certificate ciphertext in cleartext — offline oracle / forge surface.",
`cipherLen=${cipher.length} revisionLen=${revision.length}`,
),
);
}
// Deduplicate by id (keep highest severity).
const byId = new Map<SealCommitmentFindingId, SealCommitmentFinding>();
for (const f of findings) {
const prev = byId.get(f.id);
if (!prev || (prev.severity === "warning" && f.severity === "error")) {
byId.set(f.id, f);
}
}
const deduped = [...byId.values()];
const shouldRefuseBankrupt = deduped.some((f) => f.severity === "error");
return {
schema: SEAL_COMMITMENT_SCHEMA,
path: pathLabel,
findings: deduped,
looksExposed: deduped.length > 0,
shouldRefuseBankrupt,
oneLineAdvice:
deduped.length === 0
? "No reversible seal-commitment footgun detected (heuristic)."
: shouldRefuseBankrupt
? "ERROR: Plaintext/reversible seal sidecar. Use one-way digests; omit or encrypt seal JSON. Bankrupt harden refuses unless allowPlaintextSeal / --allow-plaintext-seal / allow_plaintext_seal. Defensive guidance only."
: "WARNING: Seal-shaped JSON is plaintext beside the artifact — encrypt, omit, or bind under self-seal.",
};
}
/**
* Read a path and lint it as a seal/commitment sidecar.
*/
export function lintSealCommitmentFile(filePath: string): SealCommitmentReport {
const abs = resolve(filePath);
if (!existsSync(abs)) {
throw new Error(`seal-commitment target not found: ${abs}`);
}
const source = readFileSync(abs, "utf8");
return lintSealCommitmentSource(source, { path: abs });
}
function walkSealCandidates(
dir: string,
depth: number,
out: string[],
): void {
if (out.length >= MAX_SEAL_FILES || depth > MAX_WALK_DEPTH) return;
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (out.length >= MAX_SEAL_FILES) return;
if (entry.isDirectory()) {
if (SKIP_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
walkSealCandidates(join(dir, entry.name), depth + 1, out);
continue;
}
if (!entry.isFile()) continue;
if (!looksLikeSealFileName(entry.name)) continue;
out.push(join(dir, entry.name));
}
}
/**
* Discover seal-named JSON files under a project/build directory and lint each.
*/
export function discoverAndLintSealSidecars(
directory: string,
): readonly SealCommitmentReport[] {
const abs = resolve(directory);
if (!existsSync(abs)) {
throw new Error(`Path not found: ${abs}`);
}
const st = statSync(abs);
if (st.isFile()) {
return [lintSealCommitmentFile(abs)];
}
const candidates: string[] = [];
walkSealCandidates(abs, 0, candidates);
// Also check common build output folder names one level down even if skipped
// as deep roots — seal.json often sits next to dist artifacts at project root.
return candidates.map((p) => lintSealCommitmentFile(p));
}
/**
* Immediate-directory sibling seal files next to a protect target.
*/
export function findSiblingSealSidecars(directory: string): readonly string[] {
const abs = resolve(directory);
if (!existsSync(abs) || !statSync(abs).isDirectory()) return [];
let entries;
try {
entries = readdirSync(abs, { withFileTypes: true });
} catch {
return [];
}
return entries
.filter((e) => e.isFile() && looksLikeSealFileName(e.name))
.map((e) => join(abs, e.name));
}
export function sealCommitmentRefuseMessage(
report: SealCommitmentReport,
filePath: string,
): string {
const ids = report.findings.filter((f) => f.severity === "error").map((f) => f.id).join(", ");
return (
`Refusing bankrupt harden/protect: plaintext/reversible seal sidecar at ${filePath}` +
(ids ? ` [${ids}]` : "") +
`. Use one-way SHA-256/HMAC commitments; omit or encrypt seal JSON. ` +
`To override (lab fixture only), pass allowPlaintextSeal / --allow-plaintext-seal / allow_plaintext_seal:true.`
);
}
/** Whether bankrupt intensity should enforce seal-sidecar refusal. */
export function intensityEnforcesSealRefusal(intensity: string): boolean {
return intensity === "bankrupt";
}
+311
View File
@@ -0,0 +1,311 @@
/**
* Clear WASM param/cipher carrier lint (red-blue round-3 residual).
*
* Detects ASCII magics such as R3PARM / R3CIPH / R2SEAL embedded in a WASM
* binary (typically the data section) followed by clear salt/rounds/ciphertext
* bytes. Full encryption of WASM data is a follow-up; this gate surfaces the
* footgun and lets bankrupt harden refuse unless explicitly allowed.
*
* Heuristic and defensive only — no crack / inversion advice. Tuned to avoid
* flagging ordinary WASM text (requires tagged magic + null pad + binary blob).
*/
import { createHash } from "node:crypto";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { basename, join, resolve } from "node:path";
export const WASM_PARAM_CARRIER_SCHEMA = "bla-wasm-param-carrier-lint/v1" as const;
export type WasmParamCarrierFindingId =
| "clear-wasm-param-magic"
| "clear-wasm-cipher-carrier"
| "clear-wasm-seal-magic";
export type WasmParamCarrierSeverity = "warning" | "error";
export interface WasmParamCarrierFinding {
readonly id: WasmParamCarrierFindingId;
readonly severity: WasmParamCarrierSeverity;
readonly summary: string;
readonly evidence: string;
readonly offset: number;
readonly magic: string;
}
export interface WasmParamCarrierReport {
readonly schema: typeof WASM_PARAM_CARRIER_SCHEMA;
readonly path: string;
readonly sha256Prefix: string;
readonly findings: readonly WasmParamCarrierFinding[];
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]);
/** Tagged footgun magics observed in red-blue rounds (and close cousins). */
const TAGGED_MAGIC =
/(?:R[0-9]|BLA|V[0-9]|K[0-9])?(?:PARM|CIPH|SEAL|SALT)/g;
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;
function isPrintableAscii(byte: number): boolean {
return byte >= 0x20 && byte <= 0x7e;
}
function looksBinaryBlob(buf: Buffer, start: number, len: number): boolean {
if (start < 0 || start >= buf.length || len <= 0) return false;
const end = Math.min(buf.length, start + len);
let nonPrint = 0;
for (let i = start; i < end; i++) {
const b = buf[i]!;
if (b === 0 || !isPrintableAscii(b)) nonPrint++;
}
return nonPrint >= Math.max(2, Math.floor((end - start) * 0.4));
}
function classifyMagic(magic: string): WasmParamCarrierFindingId {
if (/CIPH$/i.test(magic)) return "clear-wasm-cipher-carrier";
if (/SEAL$/i.test(magic)) return "clear-wasm-seal-magic";
return "clear-wasm-param-magic";
}
function finding(
id: WasmParamCarrierFindingId,
severity: WasmParamCarrierSeverity,
summary: string,
evidence: string,
offset: number,
magic: string,
): WasmParamCarrierFinding {
return {
id,
severity,
summary,
evidence: evidence.slice(0, 160),
offset,
magic,
};
}
/**
* Scan a WASM (or WASM-shaped) buffer for clear param/cipher ASCII carriers.
*/
export function lintWasmParamCarrierBuffer(
buffer: Buffer,
options: { readonly path?: string } = {},
): WasmParamCarrierReport {
const pathLabel = options.path ?? "<memory>";
const sha256Prefix = createHash("sha256").update(buffer).digest("hex").slice(0, 12);
const findings: WasmParamCarrierFinding[] = [];
if (buffer.length < 8) {
return emptyReport(pathLabel, sha256Prefix, "Buffer too small for WASM param-carrier lint.");
}
// Prefer real WASM; still scan if magic missing so mislabeled .bin carriers are caught.
const hasWasmMagic = buffer.subarray(0, 4).equals(WASM_MAGIC);
const scan = buffer.length > MAX_SCAN_BYTES ? buffer.subarray(0, MAX_SCAN_BYTES) : buffer;
// latin1 preserves byte↔char 1:1 for ASCII magic search.
const text = scan.toString("latin1");
TAGGED_MAGIC.lastIndex = 0;
let match: RegExpExecArray | null;
const seenOffsets = new Set<number>();
while ((match = TAGGED_MAGIC.exec(text)) !== null) {
const magic = match[0]!;
// Require at least 5 chars (e.g. R3PARM) — bare "SEAL"/"PARM" alone is too noisy.
if (magic.length < 5) continue;
// Must look like a tagged token: starts with letter, rest alnum.
if (!/^[A-Z][A-Z0-9]{4,7}$/.test(magic)) continue;
const offset = match.index;
if (seenOffsets.has(offset)) continue;
// Null pad within 0..2 bytes after magic (R3PARM\0\0 layout).
const after = offset + magic.length;
if (after >= scan.length) continue;
// Require a null pad immediately after the magic (R3PARM\0\0 layout).
const pad0 = scan[after]!;
if (pad0 !== 0) continue;
const pad1 = after + 1 < scan.length ? scan[after + 1]! : 0xff;
const blobStart = after + (pad1 === 0 ? 2 : 1);
// CIPH/SEAL carriers often pack ASCII-looking ciphertext; require only that
// some payload bytes follow. PARM/SALT still need a binary-ish blob so we
// do not flag English prose.
const idHint = classifyMagic(magic);
if (idHint === "clear-wasm-cipher-carrier" || idHint === "clear-wasm-seal-magic") {
if (blobStart >= scan.length || scan.length - blobStart < 4) continue;
} else if (!looksBinaryBlob(scan, blobStart, 12)) {
continue;
}
seenOffsets.add(offset);
const id = classifyMagic(magic);
const preview = scan
.subarray(offset, Math.min(scan.length, offset + magic.length + 16))
.toString("hex");
findings.push(
finding(
id,
"error",
hasWasmMagic
? `WASM binary embeds clear ${magic} param/cipher carrier magic with adjacent binary blob — relocate, encrypt, or bind under self-seal.`
: `Buffer embeds clear ${magic} param/cipher carrier magic with adjacent binary blob (not a standard WASM header).`,
`offset=${offset} magic=${magic} next=${preview}`,
offset,
magic,
),
);
}
// Deduplicate by id+offset (keep first).
const deduped: WasmParamCarrierFinding[] = [];
const keySet = new Set<string>();
for (const f of findings) {
const key = `${f.id}@${f.offset}`;
if (keySet.has(key)) continue;
keySet.add(key);
deduped.push(f);
}
const shouldRefuseBankrupt = deduped.some((f) => f.severity === "error");
return {
schema: WASM_PARAM_CARRIER_SCHEMA,
path: pathLabel,
sha256Prefix,
findings: deduped,
looksExposed: deduped.length > 0,
shouldRefuseBankrupt,
oneLineAdvice:
deduped.length === 0
? "No clear WASM param/cipher ASCII carrier magic detected (heuristic)."
: "ERROR: Clear WASM param/cipher carrier magic (e.g. R3PARM/R3CIPH/R2SEAL). Encrypt or relocate runtime params; bankrupt harden refuses unless allowWasmClearParamCarriers / --allow-wasm-clear-params / allow_wasm_clear_params. Defensive guidance only — full data-section encryption remains a follow-up.",
};
}
function emptyReport(
pathLabel: string,
sha256Prefix: string,
advice: string,
): WasmParamCarrierReport {
return {
schema: WASM_PARAM_CARRIER_SCHEMA,
path: pathLabel,
sha256Prefix,
findings: [],
looksExposed: false,
shouldRefuseBankrupt: false,
oneLineAdvice: advice,
};
}
export function lintWasmParamCarrierFile(filePath: string): WasmParamCarrierReport {
const abs = resolve(filePath);
if (!existsSync(abs)) {
throw new Error(`wasm-param-carrier target not found: ${abs}`);
}
const buf = readFileSync(abs);
return lintWasmParamCarrierBuffer(buf, { path: abs });
}
function walkWasmCandidates(dir: string, depth: number, out: string[]): void {
if (out.length >= MAX_WASM_FILES || depth > MAX_WALK_DEPTH) return;
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (out.length >= MAX_WASM_FILES) return;
if (entry.isDirectory()) {
if (SKIP_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
walkWasmCandidates(join(dir, entry.name), depth + 1, out);
continue;
}
if (!entry.isFile()) continue;
if (!/\.wasm$/i.test(entry.name)) continue;
out.push(join(dir, entry.name));
}
}
export function discoverAndLintWasmParamCarriers(
directory: string,
): readonly WasmParamCarrierReport[] {
const abs = resolve(directory);
if (!existsSync(abs)) {
throw new Error(`Path not found: ${abs}`);
}
const st = statSync(abs);
if (st.isFile()) {
return [lintWasmParamCarrierFile(abs)];
}
const candidates: string[] = [];
walkWasmCandidates(abs, 0, candidates);
return candidates.map((p) => lintWasmParamCarrierFile(p));
}
export function wasmParamCarrierRefuseMessage(
report: WasmParamCarrierReport,
filePath: string,
): string {
const magics = [...new Set(report.findings.map((f) => f.magic))].join(", ");
return (
`Refusing bankrupt harden/protect: clear WASM param/cipher carrier at ${filePath}` +
(magics ? ` [${magics}]` : "") +
`. Encrypt or relocate salt/rounds/ciphertext out of plaintext WASM data. ` +
`To override (lab fixture only), pass allowWasmClearParamCarriers / --allow-wasm-clear-params / allow_wasm_clear_params:true. ` +
`Full WASM data-section encryption is not applied by this gate.`
);
}
export function intensityEnforcesWasmParamRefusal(intensity: string): boolean {
return intensity === "bankrupt";
}
/** Build a minimal valid empty WASM module with an appended data-like blob (tests). */
export function buildTestWasmWithParamCarrier(options: {
readonly magic?: string;
readonly salt?: number;
readonly rounds?: number;
readonly cipher?: Buffer;
}): Buffer {
// Minimal module: magic + version + empty.
const header = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
const magic = options.magic ?? "R3PARM";
const salt = options.salt ?? 0xd63be8f0;
const rounds = options.rounds ?? 28;
const cipher = options.cipher ?? Buffer.from("FLAG{test-cipher-padding!!}");
const parm = Buffer.from(magic, "ascii");
const ciphMagic = Buffer.from("R3CIPH", "ascii");
const blob = Buffer.alloc(parm.length + 2 + 4 + 1 + ciphMagic.length + 2 + 2 + cipher.length);
let o = 0;
parm.copy(blob, o); o += parm.length;
blob[o++] = 0;
blob[o++] = 0;
blob.writeInt32LE(salt | 0, o); o += 4;
blob[o++] = rounds & 0xff;
ciphMagic.copy(blob, o); o += ciphMagic.length;
blob[o++] = 0;
blob[o++] = 0;
blob.writeUInt16LE(cipher.length, o); o += 2;
cipher.copy(blob, o);
return Buffer.concat([header, blob]);
}
@@ -0,0 +1,424 @@
/**
* WASM + seal.json XOR known-plaintext lint (red-blue round-7 residual).
*
* Detects entitlement packs XOR-masked with a repeating 32-byte mask where the
* embedded 32-byte commitment equals the public `seal.json` `revision` digest.
* An attacker XORs `masked[8..40)` with `revision` to recover the full mask,
* unmasks salt/rounds/cipher, then (with a weak algebraic key-dependent mask
* KDF) recovers the key — no adjacent plaintext mask sidecar required.
*
* Bankrupt harden/protect refuses error findings unless
* `allowWasmSealXorKnownPlaintext` / `--allow-wasm-seal-xor-known-plaintext` /
* `allow_wasm_seal_xor_known_plaintext`.
*
* DEFENSIVE ONLY — do not embed publicly known seal digests under XOR masks;
* derive masks with a one-way KDF (e.g. SHA-256(key||i)); keep commitments
* out of the masked plaintext prefix (or bind revision differently).
*/
import { createHash, randomBytes } from "node:crypto";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { extractWasmDataPayloads } from "./wasm-xor-mask-sidecar-lint.js";
export const WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA =
"bla-wasm-seal-xor-known-plaintext-lint/v1" as const;
export type WasmSealXorKnownPlaintextFindingId =
| "wasm-seal-xor-known-plaintext"
| "wasm-seal-revision-mask-oracle";
export type WasmSealXorKnownPlaintextSeverity = "warning" | "error";
export interface WasmSealXorKnownPlaintextFinding {
readonly id: WasmSealXorKnownPlaintextFindingId;
readonly severity: WasmSealXorKnownPlaintextSeverity;
readonly summary: string;
readonly evidence: string;
readonly offset: number;
readonly rounds: number;
readonly clen: number;
}
export interface WasmSealXorKnownPlaintextReport {
readonly schema: typeof WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA;
readonly path: string;
readonly sealPath: string | null;
readonly sha256Prefix: string;
readonly revisionPrefix: string | null;
readonly findings: readonly WasmSealXorKnownPlaintextFinding[];
readonly looksExposed: boolean;
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 COMMIT_OFF = 8;
const CLEN_OFF = 40;
const HEADER = 42;
function finding(
id: WasmSealXorKnownPlaintextFindingId,
severity: WasmSealXorKnownPlaintextSeverity,
summary: string,
evidence: string,
offset: number,
rounds: number,
clen: number,
): WasmSealXorKnownPlaintextFinding {
return {
id,
severity,
summary,
evidence: evidence.slice(0, 240),
offset,
rounds,
clen,
};
}
function emptyReport(
pathLabel: string,
sealPath: string | null,
sha256Prefix: string,
advice: string,
revisionPrefix: string | null = null,
): WasmSealXorKnownPlaintextReport {
return {
schema: WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA,
path: pathLabel,
sealPath,
sha256Prefix,
revisionPrefix,
findings: [],
looksExposed: false,
shouldRefuseBankrupt: false,
oneLineAdvice: advice,
};
}
function parseRevision(sealRaw: string): Buffer | null {
let obj: unknown;
try {
obj = JSON.parse(sealRaw);
} catch {
return null;
}
if (!obj || typeof obj !== "object") return null;
const rev = (obj as { revision?: unknown }).revision;
if (typeof rev !== "string" || !/^[0-9a-fA-F]{64}$/.test(rev)) return null;
return Buffer.from(rev, "hex");
}
/** Recover repeating mask from commit known-plaintext at base+8; validate pack. */
export function looksLikeSealRevisionKnownPlaintextPack(
payload: Buffer,
commit: Buffer,
base = 0,
): { ok: true; rounds: number; clen: number; salt: number } | { ok: false } {
if (commit.length !== 32) return { ok: false };
if (payload.length < base + HEADER + 8) return { ok: false };
const mask = Buffer.alloc(MASK_LEN);
for (let i = COMMIT_OFF; i < COMMIT_OFF + 32; i++) {
mask[i % MASK_LEN] = payload[base + i]! ^ commit[i - COMMIT_OFF]!;
}
// Consistency: unmask must reproduce commit
for (let i = COMMIT_OFF; i < COMMIT_OFF + 32; i++) {
if ((payload[base + i]! ^ mask[i % MASK_LEN]!) !== commit[i - COMMIT_OFF]!) return { ok: false };
}
const plainHdr = Buffer.alloc(HEADER);
for (let i = 0; i < HEADER; i++) plainHdr[i] = payload[base + i]! ^ mask[i % MASK_LEN]!;
if (plainHdr[5] || plainHdr[6] || plainHdr[7]) return { ok: false };
const rounds = plainHdr[4]!;
if (rounds < 8 || rounds > 200) return { ok: false };
const clen = plainHdr.readUInt16LE(CLEN_OFF);
if (clen < 8 || clen > 200) return { ok: false };
if (payload.length < base + HEADER + clen) return { ok: false };
// cipher entropy
let nonPrint = 0;
for (let i = 0; i < clen; i++) {
const b = payload[base + HEADER + i]! ^ mask[(HEADER + i) % MASK_LEN]!;
if (b < 0x20 || b > 0x7e) nonPrint++;
}
if (nonPrint < Math.max(2, Math.floor(clen * 0.2))) return { ok: false };
const salt = plainHdr.readInt32LE(0);
// mask should not be trivial
if (mask.every((b) => b === mask[0])) return { ok: false };
if (new Set(mask).size < 8) return { ok: false };
return { ok: true, rounds, clen, salt };
}
export function resolveSiblingSealPath(wasmPath: string, explicit?: string): string | null {
if (explicit) {
const abs = resolve(explicit);
return existsSync(abs) && statSync(abs).isFile() ? abs : null;
}
const dir = dirname(resolve(wasmPath));
const candidates = ["seal.json", "bla-seal.json", ".bla-seal.json"];
for (const name of candidates) {
const p = join(dir, name);
if (existsSync(p) && statSync(p).isFile()) return p;
}
return null;
}
export function lintWasmSealXorKnownPlaintextBuffer(
buffer: Buffer,
options: {
readonly path?: string;
readonly sealPath?: string | null;
readonly sealRaw?: string | null;
} = {},
): WasmSealXorKnownPlaintextReport {
const pathLabel = options.path ?? "<memory>";
const sha256Prefix = createHash("sha256").update(buffer).digest("hex").slice(0, 12);
const sealPath = options.sealPath ?? null;
let sealRaw = options.sealRaw ?? null;
if (!sealRaw && sealPath && existsSync(sealPath)) {
try {
sealRaw = readFileSync(sealPath, "utf8");
} catch {
sealRaw = null;
}
}
if (!sealRaw) {
return emptyReport(
pathLabel,
sealPath,
sha256Prefix,
"No seal.json revision available — seal XOR known-plaintext lint skipped.",
);
}
const commit = parseRevision(sealRaw);
if (!commit) {
return emptyReport(
pathLabel,
sealPath,
sha256Prefix,
"seal.json has no 64-hex revision — seal XOR known-plaintext lint skipped.",
);
}
const revisionPrefix = commit.toString("hex").slice(0, 12);
if (buffer.length < 8 || !buffer.subarray(0, 4).equals(WASM_MAGIC)) {
return emptyReport(
pathLabel,
sealPath,
sha256Prefix,
"Not a WASM module — seal XOR known-plaintext lint skipped.",
revisionPrefix,
);
}
if (buffer.length > MAX_SCAN_BYTES) {
return emptyReport(
pathLabel,
sealPath,
sha256Prefix,
"WASM too large for seal XOR known-plaintext lint.",
revisionPrefix,
);
}
const findings: WasmSealXorKnownPlaintextFinding[] = [];
const payloads = extractWasmDataPayloads(buffer);
for (const { memOff, payload } of payloads) {
const bases = [0];
if (payload.length > 256) bases.push(64, 128, 256);
for (const base of bases) {
if (base + HEADER >= payload.length) continue;
const hit = looksLikeSealRevisionKnownPlaintextPack(payload, commit, base);
if (!hit.ok) continue;
findings.push(
finding(
"wasm-seal-revision-mask-oracle",
"error",
"WASM data XOR-masked entitlement pack embeds seal.revision as known plaintext — recovering the repeating mask needs no key; combined with a weak key-dependent mask KDF this yields key+FLAG (red/blue round-7).",
`memOff=${memOff}+${base} rounds=${hit.rounds} clen=${hit.clen} salt=${hit.salt} seal=${sealPath ?? "<inline>"}`,
memOff + base,
hit.rounds,
hit.clen,
),
);
break;
}
}
const looksExposed = findings.length > 0;
const shouldRefuseBankrupt = findings.some((f) => f.severity === "error");
const oneLineAdvice = shouldRefuseBankrupt
? "ERROR: Do not place public seal.revision bytes under a repeating XOR mask in WASM data; use a one-way mask KDF (SHA-256) and keep public digests out of the masked plaintext prefix. Harden refuses unless allowWasmSealXorKnownPlaintext / --allow-wasm-seal-xor-known-plaintext / allow_wasm_seal_xor_known_plaintext."
: "No seal.revision-as-XOR-known-plaintext entitlement pack detected (heuristic).";
return {
schema: WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA,
path: pathLabel,
sealPath,
sha256Prefix,
revisionPrefix,
findings,
looksExposed,
shouldRefuseBankrupt,
oneLineAdvice,
};
}
export function lintWasmSealXorKnownPlaintextFile(
wasmPath: string,
sealPathExplicit?: string,
): WasmSealXorKnownPlaintextReport {
const abs = resolve(wasmPath);
if (!existsSync(abs) || !statSync(abs).isFile()) {
return emptyReport(abs, null, "000000000000", `File not found: ${abs}`);
}
const sealPath = resolveSiblingSealPath(abs, sealPathExplicit);
const buf = readFileSync(abs);
return lintWasmSealXorKnownPlaintextBuffer(buf, { path: abs, sealPath });
}
export function intensityEnforcesWasmSealXorKnownPlaintextRefusal(
intensity: string | undefined,
): boolean {
return intensity === "bankrupt" || intensity === "maximum";
}
export function wasmSealXorKnownPlaintextRefuseMessage(
report: WasmSealXorKnownPlaintextReport,
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 seal.revision XOR known-plaintext entitlement pack (${ids || "exposed"}). Pass allowWasmSealXorKnownPlaintext / --allow-wasm-seal-xor-known-plaintext / allow_wasm_seal_xor_known_plaintext to override. Prefer one-way mask KDFs and keep public digests out of masked plaintext (red/blue round-7).`;
}
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 discoverAndLintWasmSealXorKnownPlaintext(
directory: string,
): WasmSealXorKnownPlaintextReport[] {
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) => lintWasmSealXorKnownPlaintextFile(f));
}
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];
}
/**
* Minimal R7 footgun fixture: masked pack with commit===seal.revision under repeating XOR mask.
*/
export function buildTestWasmWithSealXorKnownPlaintext(
options: {
readonly salt?: number;
readonly rounds?: number;
readonly commit?: Buffer;
readonly cipher?: Buffer;
readonly mask?: Buffer;
/** When true, commit in pack differs from provided sealCommit — must NOT refuse. */
readonly mismatchCommit?: boolean;
} = {},
): { wasm: Buffer; seal: Record<string, unknown>; commit: Buffer } {
const salt = options.salt ?? 0x12345678;
const rounds = options.rounds ?? 40;
const commit = options.commit ?? randomBytes(32);
const packCommit = options.mismatchCommit ? randomBytes(32) : commit;
const cipher = options.cipher ?? randomBytes(33);
const mask = options.mask ?? randomBytes(32);
if (mask.length !== 32) throw new Error("mask must be 32 bytes");
const N = HEADER + cipher.length;
const plain = Buffer.alloc(N);
plain.writeInt32LE(salt | 0, 0);
plain[4] = rounds & 0xff;
packCommit.copy(plain, COMMIT_OFF);
plain.writeUInt16LE(cipher.length, CLEN_OFF);
cipher.copy(plain, HEADER);
const masked = Buffer.alloc(N);
for (let i = 0; i < N; i++) masked[i] = plain[i]! ^ mask[i % 32]!;
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]);
const codeSec = section(10, [1, 2, 0, 0x0b]);
const dataSec = section(11, [1, 0x00, ...iconst(0), 0x0b, ...uleb(masked.length), ...masked]);
const wasm = Buffer.from([
0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0,
...typeSec,
...funcSec,
...memSec,
...exportSec,
...codeSec,
...dataSec,
]);
if (!WebAssembly.validate(wasm)) throw new Error("test wasm invalid");
const seal = {
schema: "bla-test-seal/v1",
algorithm: "sha256",
revision: commit.toString("hex"),
certificateSha256: createHash("sha256").update("FLAG{test}").digest("hex"),
};
return { wasm, seal, commit };
}
+439
View File
@@ -0,0 +1,439 @@
/**
* 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;
/** Round-7 style: store masked blob only (key-dependent unmask) — must NOT refuse. */
readonly omitMaskSidecar?: boolean;
} = {},
): 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 = options.omitMaskSidecar ? masked : 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;
}
+1 -1
View File
@@ -5,7 +5,7 @@ export const BLA_IDENTITY = Object.freeze({
packageAlias: "bla-shield",
cliBinary: "bla",
cliAlias: "bla-agents",
version: "1.6.4",
version: "2.0.0",
slogan: "Poison -> Exhaust -> Hallucinate. Make Reverse Engineering Bankrupt Again.",
counterpart: {
name: "REA",
+105
View File
@@ -166,13 +166,34 @@ export {
export { runShowcaseBenchmark } from "./engine/benchmark.js";
export {
discoverHardenableArtifacts,
discoverHardenTargets,
hardenProject,
formatHardenProjectReport,
BLA_BUILD_OUTPUT_DIR_NAMES,
type HardenProjectReport,
type HardenArtifactSummary,
type DiscoveredArtifact,
type HardenDiscoveryResult,
} from "./engine/harden.js";
export {
computeHardenRunId,
computeArtifactRunId,
readHardenRunSummary,
HARDEN_SUMMARY_FILE_NAME,
HARDEN_SUMMARY_SCHEMA,
type HardenRunIdentity,
type HardenRunSummary,
type ReadHardenRunSummaryResult,
} from "./engine/run-evidence.js";
export {
runReaDriftCheck,
getRedteamReport,
resolveReaRoot,
reaCheckoutPresent,
reaDistReady,
type ReaDriftReport,
type RedteamReportResult,
} from "./engine/rea-observability.js";
export * from "./shields/exhaustion/index.js";
export * from "./shields/deception/index.js";
export {
@@ -262,14 +283,98 @@ export {
export {
lintLaneIndependence,
lintLaneIndependenceFile,
discoverAndLintLaneIndependence,
LANE_INDEPENDENCE_SCHEMA,
formatSupportsLaneIndependenceLint,
laneIndependenceRefuseMessage,
type LaneIndependenceFinding,
type LaneIndependenceReport,
type LaneIndependenceFindingId,
type LaneIndependenceSeverity,
} from "./engine/lane-independence-lint.js";
export {
scanPackagingGates,
evaluateHardenProjectPackagingBlocks,
formatPackagingGatesReport,
PACKAGING_GATES_SCHEMA,
type PackagingGateId,
type PackagingGateFinding,
type PackagingGatesReport,
type PackagingGatesScanOptions,
type PackagingGatesAllowOptions,
} from "./engine/packaging-gates.js";
export {
lintSealCommitmentSource,
lintSealCommitmentFile,
discoverAndLintSealSidecars,
findSiblingSealSidecars,
sealCommitmentRefuseMessage,
intensityEnforcesSealRefusal,
SEAL_COMMITMENT_SCHEMA,
type SealCommitmentFinding,
type SealCommitmentReport,
type SealCommitmentFindingId,
type SealCommitmentSeverity,
} from "./engine/seal-commitment-lint.js";
export {
lintWasmParamCarrierBuffer,
lintWasmParamCarrierFile,
discoverAndLintWasmParamCarriers,
wasmParamCarrierRefuseMessage,
intensityEnforcesWasmParamRefusal,
buildTestWasmWithParamCarrier,
WASM_PARAM_CARRIER_SCHEMA,
type WasmParamCarrierFinding,
type WasmParamCarrierReport,
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 {
lintWasmSealXorKnownPlaintextBuffer,
lintWasmSealXorKnownPlaintextFile,
discoverAndLintWasmSealXorKnownPlaintext,
buildTestWasmWithSealXorKnownPlaintext,
wasmSealXorKnownPlaintextRefuseMessage,
intensityEnforcesWasmSealXorKnownPlaintextRefusal,
WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA,
type WasmSealXorKnownPlaintextFinding,
type WasmSealXorKnownPlaintextReport,
type WasmSealXorKnownPlaintextFindingId,
type WasmSealXorKnownPlaintextSeverity,
} from "./engine/wasm-seal-xor-known-plaintext-lint.js";
export {
lintPanelDeriveAbiSource,
lintPanelDeriveAbiFile,
discoverAndLintPanelDerive,
rewriteStablePanelDeriveSymbols,
panelDeriveSeedRoot,
panelDeriveReplacementName,
intensityRewritesPanelDerive,
PANEL_DERIVE_ABI_SCHEMA,
type PanelDeriveFinding,
type PanelDeriveAbiReport,
type PanelDeriveFindingId,
type PanelDeriveSeverity,
type PanelDeriveRewriteResult,
} from "./engine/panel-derive-abi-lint.js";
export {
parseWasmExportSectionPayload,
renameWasmExports,
shuffleWasmExportSectionPayload,
looksLikeInternalWasmExport,
type WasmExportEntry,
type WasmExportRename,
+1065 -82
View File
File diff suppressed because it is too large Load Diff
+49 -3
View File
@@ -18,7 +18,11 @@ import {
type ClientConfigFormat,
type SupportedAgentClientId,
} from "./clients.js";
import { readInstallManifest, resolveBundledSkillContent } from "./setup.js";
import {
readInstallManifest,
resolveBundledSkillBundle,
resolveBundledSkillContent,
} from "./setup.js";
export type EngineHealthStatus = "ready" | "degraded" | "unavailable";
export type DoctorClientCheckState = "pass" | "warn" | "fail" | "not_checked";
@@ -51,6 +55,10 @@ export interface DoctorClientDiagnostic {
readonly mcpRegistered: boolean;
readonly skillInstalled: boolean;
readonly skillStatus: DoctorSkillStatus;
/** Supporting bundle files (references/appendices) absent next to SKILL.md. */
readonly skillMissingFiles: readonly string[];
/** Supporting bundle files whose sha256 differs from the bundled/recorded copy. */
readonly skillModifiedFiles: readonly string[];
readonly status: DoctorClientCheckState;
readonly issues: readonly string[];
}
@@ -315,6 +323,9 @@ export function runDoctor(homeDirOrOptions?: string | DoctorOptions): DoctorDiag
const clients = resolveSupportedAgentClients(home, platform, options.env);
const manifest = readInstallManifest(home);
const bundledSkillSha256 = sha256Hex(resolveBundledSkillContent());
const bundledSupportFiles = resolveBundledSkillBundle().filter(
(f) => f.relativePath !== "SKILL.md",
);
const engines = checkEngines(options.sqliteAvailableOverride);
const globalIssues: string[] = [];
@@ -382,6 +393,34 @@ export function runDoctor(homeDirOrOptions?: string | DoctorOptions): DoctorDiag
clientIssues.push(`MCP server is configured for ${c.displayName}, but SKILL.md is missing at '${skillPath}'`);
}
// Full-bundle integrity: SKILL.md links into references/ etc., so a
// half-installed bundle silently breaks the agent guide.
const skillMissingFiles: string[] = [];
const skillModifiedFiles: string[] = [];
if (skillInstalled) {
const recorded = manifest.clients[c.id]?.writtenSkillFiles;
for (const file of bundledSupportFiles) {
const full = join(c.skillDirectory, ...file.relativePath.split("/"));
if (!existsSync(full)) {
skillMissingFiles.push(file.relativePath);
continue;
}
try {
const sha = sha256Hex(readFileSync(full, "utf8"));
if (sha !== file.sha256 && sha !== recorded?.[file.relativePath]) {
skillModifiedFiles.push(file.relativePath);
}
} catch {
skillMissingFiles.push(file.relativePath);
}
}
if (skillMissingFiles.length > 0) {
clientIssues.push(
`Skill bundle for ${c.displayName} is incomplete (missing: ${skillMissingFiles.join(", ")}); re-run \`bla setup --yes\``,
);
}
}
let handshakeStatus: DoctorHandshakeStatus = "not_checked";
let handshakeVerified = false;
if (options.verifyHandshake && configured && commandResolvable && command !== null) {
@@ -399,9 +438,14 @@ export function runDoctor(homeDirOrOptions?: string | DoctorOptions): DoctorDiag
if (configStatus === "malformed" || configStatus === "invalid_entry") {
status = "fail";
} else if (configured) {
if (!commandResolvable || !skillInstalled || handshakeStatus === "failed") {
if (
!commandResolvable ||
!skillInstalled ||
skillMissingFiles.length > 0 ||
handshakeStatus === "failed"
) {
status = "fail";
} else if (skillStatus === "modified") {
} else if (skillStatus === "modified" || skillModifiedFiles.length > 0) {
status = "warn";
} else {
status = "pass";
@@ -434,6 +478,8 @@ export function runDoctor(homeDirOrOptions?: string | DoctorOptions): DoctorDiag
mcpRegistered,
skillInstalled,
skillStatus,
skillMissingFiles,
skillModifiedFiles,
status,
issues: clientIssues,
};
+111 -7
View File
@@ -10,7 +10,7 @@ import {
writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { dirname, join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { BLA_IDENTITY } from "../identity.js";
import {
@@ -90,6 +90,12 @@ export interface InstalledClientRecord {
readonly skillExistedBefore: boolean;
readonly skillDirectoryExistedBefore: boolean;
readonly writtenSkillSha256: string;
/**
* Supporting skill bundle files (e.g. `references/counter-rea-matrix.md`)
* written next to SKILL.md, keyed by POSIX relative path → sha256.
* Absent on manifests written before full-bundle installs.
*/
readonly writtenSkillFiles?: Readonly<Record<string, string>>;
readonly installedAt: string;
}
@@ -233,16 +239,28 @@ function writeInstallManifest(home: string, manifest: BlaInstallManifest): strin
return manifestPath;
}
export function resolveBundledSkillContent(): string {
/** One file of the installable skill bundle (SKILL.md + references/appendices). */
export interface BundledSkillFile {
/** POSIX path relative to the skill directory, e.g. `references/counter-rea-matrix.md`. */
readonly relativePath: string;
readonly content: string;
readonly sha256: string;
}
const SKILL_ENTRY_FILE = "SKILL.md";
function resolveBundledSkillDirectory(): string | null {
try {
const thisDir = dirname(fileURLToPath(import.meta.url));
const candidate = resolve(thisDir, "../../.agents/skills/blind-llm-agents/SKILL.md");
if (existsSync(candidate)) {
return readFileSync(candidate, "utf8");
}
const candidate = resolve(thisDir, "../../.agents/skills/blind-llm-agents");
if (existsSync(join(candidate, SKILL_ENTRY_FILE))) return candidate;
} catch {
// Fallback inline skill
// fall through to inline fallback
}
return null;
}
function inlineFallbackSkill(): string {
return [
"---",
"name: blind-llm-agents",
@@ -258,8 +276,71 @@ export function resolveBundledSkillContent(): string {
].join("\n");
}
export function resolveBundledSkillContent(): string {
const dir = resolveBundledSkillDirectory();
if (dir) return readFileSync(join(dir, SKILL_ENTRY_FILE), "utf8");
return inlineFallbackSkill();
}
function collectSkillFiles(root: string, dir: string, out: string[]): void {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name.startsWith(".")) continue;
const full = join(dir, entry.name);
if (entry.isDirectory()) collectSkillFiles(root, full, out);
else if (entry.isFile()) out.push(relative(root, full).split(sep).join("/"));
}
}
/**
* Full installable skill bundle: SKILL.md first, then every supporting file
* (references/, format appendices) so relative links in SKILL.md resolve after
* `bla setup`. Falls back to the inline SKILL.md when the package tree is absent.
*/
export function resolveBundledSkillBundle(): readonly BundledSkillFile[] {
const dir = resolveBundledSkillDirectory();
if (!dir) {
const content = inlineFallbackSkill();
return [{ relativePath: SKILL_ENTRY_FILE, content, sha256: sha256Hex(content) }];
}
const rels: string[] = [];
collectSkillFiles(dir, dir, rels);
rels.sort((a, b) => (a === SKILL_ENTRY_FILE ? -1 : b === SKILL_ENTRY_FILE ? 1 : a.localeCompare(b)));
return rels.map((rel) => {
const content = readFileSync(join(dir, ...rel.split("/")), "utf8");
return { relativePath: rel, content, sha256: sha256Hex(content) };
});
}
export const generateBlaSkillMarkdown = resolveBundledSkillContent;
function removeOwnedSkillSupportFiles(
skillDirectory: string,
recorded: Readonly<Record<string, string>> | undefined,
bundled: ReadonlyMap<string, string>,
force: boolean,
): void {
const rels = new Set<string>([...Object.keys(recorded ?? {}), ...bundled.keys()]);
const touchedDirs = new Set<string>();
for (const rel of rels) {
const full = join(skillDirectory, ...rel.split("/"));
if (!existsSync(full)) continue;
const current = sha256Hex(readFileSync(full));
if (force || current === recorded?.[rel] || current === bundled.get(rel)) {
unlinkSync(full);
touchedDirs.add(dirname(full));
}
}
// Deepest first so nested appendix dirs collapse before their parents.
for (const dir of [...touchedDirs].sort((a, b) => b.length - a.length)) {
let cur = dir;
while (cur.startsWith(skillDirectory) && cur !== skillDirectory) {
if (!existsSync(cur) || readdirSync(cur).length > 0) break;
rmdirSync(cur);
cur = dirname(cur);
}
}
}
export function runSetup(options: SetupRunOptions = {}): SetupRunResult {
const home = options.homeDir ?? homedir();
const allClients = resolveSupportedAgentClients(home, options.platform, options.env);
@@ -331,6 +412,12 @@ export function runSetup(options: SetupRunOptions = {}): SetupRunResult {
const skillContent = resolveBundledSkillContent();
const expectedSkillSha256 = sha256Hex(skillContent);
const supportSkillFiles = resolveBundledSkillBundle().filter(
(f) => f.relativePath !== SKILL_ENTRY_FILE,
);
const writtenSkillFiles: Record<string, string> = Object.fromEntries(
supportSkillFiles.map((f) => [f.relativePath, f.sha256]),
);
const manifest = readInstallManifest(home);
const updatedManifestClients: Record<string, InstalledClientRecord> = { ...manifest.clients };
const completedActions: PlannedSetupAction[] = [];
@@ -547,6 +634,9 @@ export function runSetup(options: SetupRunOptions = {}): SetupRunResult {
writeFileAtomicSync(client.configPath, nextConfigContent);
configWritten = true;
writeFileAtomicSync(skillPath, skillContent);
for (const file of supportSkillFiles) {
writeFileAtomicSync(join(client.skillDirectory, ...file.relativePath.split("/")), file.content);
}
} catch (err) {
// Roll the config back when the skill write failed after a successful
// config write — never leave a half-installed registration (config
@@ -599,6 +689,7 @@ export function runSetup(options: SetupRunOptions = {}): SetupRunResult {
? prevRecord.skillDirectoryExistedBefore
: skillDirectoryExistedBefore,
writtenSkillSha256: expectedSkillSha256,
writtenSkillFiles,
installedAt: new Date().toISOString(),
};
@@ -673,6 +764,11 @@ export function runUninstall(options: UninstallRunOptions = {}): UninstallRunRes
const manifest = readInstallManifest(home);
const remainingManifestClients: Record<string, InstalledClientRecord> = { ...manifest.clients };
const bundledSkillHash = sha256Hex(resolveBundledSkillContent());
const bundledSupportHashes = new Map(
resolveBundledSkillBundle()
.filter((f) => f.relativePath !== SKILL_ENTRY_FILE)
.map((f) => [f.relativePath, f.sha256] as const),
);
const removedClients: string[] = [];
const results: ClientUninstallResult[] = [];
@@ -765,6 +861,14 @@ export function runUninstall(options: UninstallRunOptions = {}): UninstallRunRes
if (ownedByThisManifest || ownedByAnyManifest || ownedByFallbackUnmodified || options.force) {
unlinkSync(skillPath);
skillRemoved = true;
// Remove supporting bundle files BLA wrote (unmodified only), then
// prune their now-empty subdirectories.
removeOwnedSkillSupportFiles(
client.skillDirectory,
manifestRecord?.writtenSkillFiles,
bundledSupportHashes,
options.force === true,
);
// Only remove `client.skillDirectory` if it is now completely empty!
if (existsSync(client.skillDirectory)) {
const remainingFiles = readdirSync(client.skillDirectory);
@@ -98,7 +98,8 @@ export function generateShadowBusinessLogic(
shadowProceduresCreated.push(fnName);
decoyConstantsCount += 4;
blocks.push(
`function ${fnName}(frameBytes = [0x42, 0x4c, 0x41, 0x03], ratchetStep = 0) {`,
// Default frame as 2+2 concat — avoids lane-lint BYTE_COMPARE_ARRAY (R9 blue)
`function ${fnName}(frameBytes = [0x42, 0x4c].concat([0x41, 0x03]), ratchetStep = 0) {`,
` const FRAME_MAGIC = 0x424c4103;`,
` const NONCE_MASK = 0x${prng.hex(6)};`,
` let crc = 0xffffffff;`,
+176 -14
View File
@@ -125,6 +125,21 @@ function encodeWasmExportSectionPayload(
]);
}
/**
* Seed-shuffle export entries (names/kinds/indices unchanged).
* Round-11: bankrupt rename used to preserve cleartext export *order*, so
* "unlock first among arity-2" survived as an RE shortcut. Hosts must resolve
* by arity + FLAG shape + certificate — never by first-export position.
*/
export function shuffleWasmExportSectionPayload(
exportSectionPayload: Buffer,
prng: SeededPrng,
): Buffer {
const entries = parseWasmExportSectionPayload(exportSectionPayload);
if (entries.length <= 1) return exportSectionPayload;
return encodeWasmExportSectionPayload(prng.shuffle(entries));
}
/** Heuristic: names that look like internal/debug ABI rather than a public export. */
export function looksLikeInternalWasmExport(name: string): boolean {
return /^(?:__|_|debug_|dbg_|_internal|internal_|test_|tmp_)/i.test(name);
@@ -144,7 +159,11 @@ export function renameWasmExports(
prng: SeededPrng,
options: {
readonly preserveExports?: readonly string[];
/** When true (default), only rename internal-looking names. */
/**
* When true, only rename internal-looking names.
* Callers that want full non-preserved rename must pass `onlyInternal: false`
* (protectWasmBinary does this by default at maximum/bankrupt).
*/
readonly onlyInternal?: boolean;
} = {},
): {
@@ -152,6 +171,8 @@ export function renameWasmExports(
readonly renames: readonly WasmExportRename[];
} {
const preserve = new Set(options.preserveExports ?? []);
// Library default remains conservative (internal-only) when called directly;
// protectWasmBinary passes onlyInternal:false at maximum/bankrupt.
const onlyInternal = options.onlyInternal !== false;
const entries = parseWasmExportSectionPayload(exportSectionPayload);
if (entries.length === 0) {
@@ -203,12 +224,128 @@ function appendDecoyExports(
]);
}
/**
* Parse WASM type-section function signatures → param counts (functype only).
* Returns [] on truncated / non-functype entries (defensive).
*/
function parseWasmFunctypeParamCounts(typeSectionPayload: Buffer): number[] {
try {
const { value: count, nextOffset } = decodeUnsignedLeb128(typeSectionPayload, 0);
let p = nextOffset;
const out: number[] = [];
for (let i = 0; i < count; i++) {
if (p >= typeSectionPayload.length) return out;
const form = typeSectionPayload[p++]!;
if (form !== 0x60) return out; // only functype
const { value: nParams, nextOffset: afterParams } = decodeUnsignedLeb128(
typeSectionPayload,
p,
);
p = afterParams + nParams; // skip param valtypes
if (p > typeSectionPayload.length) return out;
const { value: nResults, nextOffset: afterResults } = decodeUnsignedLeb128(
typeSectionPayload,
p,
);
p = afterResults + nResults;
if (p > typeSectionPayload.length) return out;
out.push(nParams);
}
return out;
} catch {
return [];
}
}
/**
* Parse WASM function-section → type indices per function index.
*/
function parseWasmFuncTypeIndices(funcSectionPayload: Buffer): number[] {
try {
const { value: count, nextOffset } = decodeUnsignedLeb128(funcSectionPayload, 0);
let p = nextOffset;
const out: number[] = [];
for (let i = 0; i < count; i++) {
const { value: typeIdx, nextOffset: after } = decodeUnsignedLeb128(
funcSectionPayload,
p,
);
p = after;
out.push(typeIdx);
}
return out;
} catch {
return [];
}
}
/**
* Collect unique function-export indices from a WASM binary (kind 0 only).
* Used so bankrupt decoy aliases can be spread across real stubs + unlock
* instead of all aliasing funcIndex 0 (red/blue round-10 arity-2 hygiene).
*
* Round-12: prefer host-visible arity-2 exports `(i32,i32)->…` when at least
* one exists, so arity-1 exports (e.g. seal) do not consume alias budget.
* Falls back to all func exports when no arity-2 is present.
*/
function collectExportedFuncIndices(bytes: Buffer): number[] {
if (
bytes.length < 8 ||
bytes[0] !== 0x00 ||
bytes[1] !== 0x61 ||
bytes[2] !== 0x73 ||
bytes[3] !== 0x6d
) {
return [];
}
let offset = 8;
let typeParamCounts: number[] | null = null;
let funcTypeIndices: number[] | null = null;
let exportEntries: WasmExportEntry[] | null = null;
while (offset < bytes.length) {
const sectionId = bytes[offset++]!;
const { value: sectionSize, nextOffset } = decodeUnsignedLeb128(bytes, offset);
const sectionEnd = nextOffset + sectionSize;
if (sectionEnd > bytes.length) break;
const payload = bytes.subarray(nextOffset, sectionEnd);
if (sectionId === 1) {
typeParamCounts = parseWasmFunctypeParamCounts(payload);
} else if (sectionId === 3) {
funcTypeIndices = parseWasmFuncTypeIndices(payload);
} else if (sectionId === 7) {
exportEntries = parseWasmExportSectionPayload(payload);
}
offset = sectionEnd;
}
if (!exportEntries) return [];
const seen = new Set<number>();
const all: number[] = [];
const arity2: number[] = [];
for (const e of exportEntries) {
if (e.kind !== 0) continue;
if (seen.has(e.index)) continue;
seen.add(e.index);
all.push(e.index);
if (typeParamCounts && funcTypeIndices && e.index < funcTypeIndices.length) {
const typeIdx = funcTypeIndices[e.index]!;
if (typeIdx < typeParamCounts.length && typeParamCounts[typeIdx] === 2) {
arity2.push(e.index);
}
}
}
// Prefer host-visible arity-2 when available (round-12 alias budget hygiene).
return arity2.length > 0 ? arity2 : all;
}
function planWasmExportNameDecoys(
prng: SeededPrng,
intensity: ProtectionIntensity,
funcIndex: number,
funcIndices: readonly number[],
): readonly { readonly name: string; readonly funcIndex: number }[] {
// bankrupt: ~250 × ~12 KiB names → Wabt interface charge ≫ 32 MiB.
// Round-10: spread aliases across exported function indices (stubs + unlock)
// so ~all-250 do not concentrate on funcIndex 0 / the real unlock body.
// Round-12: caller passes arity-2-preferring indices when available.
const count =
intensity === "stealth"
? 0
@@ -219,12 +356,14 @@ function planWasmExportNameDecoys(
: 250;
const namePad = intensity === "bankrupt" ? 12_000 : intensity === "maximum" ? 48 : 16;
const tag = prng.hex(4);
const indices =
funcIndices.length > 0 ? prng.shuffle([...new Set(funcIndices)]) : [0];
const out: { name: string; funcIndex: number }[] = [];
for (let i = 0; i < count; i++) {
const pad = "e".repeat(namePad);
out.push({
name: `enclave_export_${tag}_${i}_${pad}`,
funcIndex,
funcIndex: indices[i % indices.length]!,
});
}
return out;
@@ -367,15 +506,15 @@ export function protectWasmBinary(
readonly preserveExports?: readonly string[];
/**
* When true, rename exports not listed in `preserveExports`.
* Default: true at maximum/bankrupt for internal-looking names only;
* pass `renameNonPublicExports: true` with an explicit preserve list to
* rename every non-preserved export.
* Default: true at maximum/bankrupt (all non-preserved names).
* Keeping a stable public ABI requires an explicit `preserveExports` list
* (CLI `--wasm-preserve-exports` / MCP `wasm_preserve_exports` / `.blarc`).
*/
readonly renameNonPublicExports?: boolean;
/**
* When renaming, only touch internal-looking names (`__*`, `debug_*`, …).
* Default true unless `renameNonPublicExports` is explicitly true AND
* `preserveExports` is provided (then all non-preserved names rename).
* Default **false** at maximum/bankrupt (rename every non-preserved export).
* Set true only when you intentionally want the weaker internal-only pass.
*/
readonly renameInternalOnly?: boolean;
} = {},
@@ -391,6 +530,8 @@ export function protectWasmBinary(
readonly exportDecoysInjected: number;
/** Export renames applied this pass (issue #40.3). Empty when rename is off. */
readonly exportsRenamed: readonly WasmExportRename[];
/** True when export-section entry order was seed-shuffled (round-11). */
readonly exportsOrderShuffled: boolean;
} {
if (
bytes.length < 8 ||
@@ -411,11 +552,21 @@ export function protectWasmBinary(
// At bankrupt intensity, densify the export section with long-name aliases of
// existing funcs so REA's real Wabt→WasmInterfaceBudget path trips (custom
// sections alone do not expand the typed interface inventory).
const decoyExports = planWasmExportNameDecoys(prng, intensity, 0);
// Round-10: spread aliases across all exported function indices (not only 0).
// Round-11: after rename + decoy append, shuffle export *order* independently
// so first arity-2 is not a stable pointer to the unlock body.
// Round-12: collectExportedFuncIndices prefers arity-2 (host-visible) so
// arity-1 exports do not burn alias budget.
const decoyExports = planWasmExportNameDecoys(
prng,
intensity,
collectExportedFuncIndices(bytes),
);
const keptChunks: Buffer[] = [bytes.subarray(0, 8)];
let offset = 8;
let exportDecoysInjected = 0;
let exportsRenamed: readonly WasmExportRename[] = [];
let exportsOrderShuffled = false;
while (offset < bytes.length) {
const sectionStart = offset;
const sectionId = bytes[offset++]!;
@@ -434,13 +585,13 @@ export function protectWasmBinary(
options.renameNonPublicExports === true ||
(options.renameNonPublicExports !== false && intensityWantsRename);
if (renameRequested) {
// Red/Blue round-1: public ABI (`mix`/`seal`) surviving bankrupt enabled
// preload hooks. Default at maximum/bankrupt is full non-preserved rename;
// callers that need stable names must pass preserveExports explicitly.
const onlyInternal =
options.renameInternalOnly !== undefined
? options.renameInternalOnly
: !(
options.renameNonPublicExports === true &&
(options.preserveExports?.length ?? 0) > 0
);
: false;
const renamed = renameWasmExports(payload, prng, {
preserveExports: options.preserveExports,
onlyInternal,
@@ -448,10 +599,20 @@ export function protectWasmBinary(
payload = Buffer.from(renamed.payload);
exportsRenamed = renamed.renames;
}
const expanded =
let expanded =
decoyExports.length > 0
? appendDecoyExports(payload, decoyExports)
: payload;
// Round-11: shuffle combined original+decoy export order at maximum/bankrupt
// (same intensity band as rename / decoy injection). Independent of alias
// funcIndex spread — closes "first arity-2 = unlock" RE shortcut.
const intensityWantsShuffle =
intensity === "maximum" || intensity === "bankrupt";
if (intensityWantsShuffle) {
const n = parseWasmExportSectionPayload(expanded).length;
expanded = shuffleWasmExportSectionPayload(expanded, prng);
exportsOrderShuffled = n > 1;
}
keptChunks.push(
Buffer.concat([
Buffer.from([0x07]),
@@ -566,5 +727,6 @@ export function protectWasmBinary(
exceedsRepresentationBudget: ifacePlan.exceedsRepresentationBudget,
exportDecoysInjected,
exportsRenamed,
exportsOrderShuffled,
};
}
+20 -5
View File
@@ -1277,11 +1277,26 @@ export function transformJavaScriptWithBlaShield(
break;
}
const [corpusDecl, digestFnDecl, seedDecl, heapDecl, ...restInjected] =
sanitizedInjectedStatements;
const topDecls = [corpusDecl, digestFnDecl, seedDecl, heapDecl].filter(
(s): s is t.Statement => s !== undefined,
);
// Prepend every injected statement through the opaque-predicate seed decl
// (cognitive armor + optional self-seal preamble + seed). Self-seal inserts
// extra statements before the seed; a fixed 4-stmt split pushed the seed to
// the program end and caused TDZ crashes when top-level consts referenced it
// (red-blue round-4). Also keep the immediate following shadow-heap decl up top.
const seedInjectIndex = sanitizedInjectedStatements.findIndex((stmt) => {
if (!t.isVariableDeclaration(stmt)) return false;
return stmt.declarations.some(
(d) => t.isIdentifier(d.id) && d.id.name === seedVarName,
);
});
const topEnd =
seedInjectIndex >= 0
? Math.min(
sanitizedInjectedStatements.length,
seedInjectIndex + 1 /* seed */ + 1 /* shadow heap usually follows */,
)
: Math.min(4, sanitizedInjectedStatements.length);
const topDecls = sanitizedInjectedStatements.slice(0, topEnd);
const restInjected = sanitizedInjectedStatements.slice(topEnd);
if (topDecls.length > 0) {
ast.program.body.splice(insertIndex, 0, ...topDecls);
}
+5 -3
View File
@@ -72,8 +72,9 @@ export function generateShadowHeapChurnShield(
: i % 4 === 2
? "tpm2_pcr_quote_digest"
: "enclave_session_ratchet";
// words as 2+2 concat — avoids lane-lint BYTE_COMPARE_ARRAY ([n,n,n,n+] literals)
initialSlots.push(
` { slotId: ${i}, kind: "${kind}", epoch: ${w0}, words: [${w0}, ${w1}, ${w2}, ${w3}], hmacTag: 0x${prng.hex(6)} }`,
` { slotId: ${i}, kind: "${kind}", epoch: ${w0}, words: [${w0}, ${w1}].concat([${w2}, ${w3}]), hmacTag: 0x${prng.hex(6)} }`,
);
}
@@ -105,8 +106,9 @@ export function generateShadowHeapChurnShield(
` cursor: 0,`,
` tick: 1,`,
` rollingMask: 0x${prng.hex(6)},`,
` splitShareA: [${decoySecret.shareA.join(", ")}],`,
` splitShareB: [${decoySecret.shareB.join(", ")}],`,
// CSV→map avoids lane-lint BYTE_COMPARE_ARRAY on bankrupt output (R8 red residual / R9 blue)
` splitShareA: "${decoySecret.shareA.join(",")}".split(",").map(function (n) { return n | 0; }),`,
` splitShareB: "${decoySecret.shareB.join(",")}".split(",").map(function (n) { return n | 0; }),`,
` slots: [`,
initialSlots.join(",\n"),
` ],`,
+58 -4
View File
@@ -10,6 +10,11 @@
* the opaque-predicate seed. Tampering with sibling modules or attaching an
* inspector changes the digest → seed parity flips → opaque happy-path guards fail.
*
* When build-time `expectedSiblingSha256` hashes are embedded (harden/protect fills
* these from siblings already on disk), runtime **hard-fails** on mismatch. Opaque
* seed entanglement alone does not gate entitlement control flow that never reads
* the seed (red/blue round-4 finding).
*
* DEFENSIVE ONLY. Opt-in. No crack / RE advice. Browser builds soft-skip (digest=0).
*/
@@ -25,6 +30,18 @@ export interface SelfSealOptions {
readonly envFingerprint?: boolean;
/** Override the emitted binding name (tests). */
readonly bindingName?: string;
/**
* Optional build-time SHA-256 hex of sibling file bytes (keyed by the same
* path strings listed in siblingPaths). When present, runtime hard-fails if
* a sibling's bytes diverge — opaque-seed entanglement alone does not gate
* entitlement control flow (red/blue round-4).
*/
readonly expectedSiblingSha256?: Readonly<Record<string, string>>;
/**
* When true (default if expectedSiblingSha256 is non-empty), throw on sibling
* hash mismatch instead of only poisoning the digest.
*/
readonly hardFailOnSiblingMismatch?: boolean;
}
export interface SelfSealSnippet {
@@ -35,6 +52,9 @@ export interface SelfSealSnippet {
readonly expectedDigestHelperName: string;
readonly siblingCount: number;
readonly envFingerprint: boolean;
/** How many sibling expected hashes were embedded for hard-fail. */
readonly expectedSiblingHashCount: number;
readonly hardFailOnSiblingMismatch: boolean;
}
/**
@@ -57,9 +77,24 @@ export function generateSelfSealSnippet(
const siblings = (options.siblingPaths ?? []).filter(
(p) => typeof p === "string" && p.length > 0,
);
const expectedSiblingSha256 = options.expectedSiblingSha256 ?? {};
const expectedEntries = Object.entries(expectedSiblingSha256).filter(
([k, v]) =>
typeof k === "string" &&
k.length > 0 &&
typeof v === "string" &&
/^[0-9a-f]{64}$/i.test(v),
);
const hardFailOnSiblingMismatch =
options.hardFailOnSiblingMismatch !== undefined
? options.hardFailOnSiblingMismatch
: expectedEntries.length > 0;
// Embed sibling list as a JSON array literal — paths are customer-controlled.
const siblingsLiteral = JSON.stringify(siblings);
const expectedLiteral = JSON.stringify(
Object.fromEntries(expectedEntries.map(([k, v]) => [k, v.toLowerCase()])),
);
const lines: string[] = [];
lines.push(`function ${helperName}() {`);
@@ -73,13 +108,27 @@ export function generateSelfSealSnippet(
lines.push(` if (!selfPath && typeof __dirname === "string") selfPath = _path.join(__dirname, "index.js");`);
lines.push(` if (selfPath) { try { h.update(_fs.readFileSync(selfPath)); } catch (_e) {} }`);
lines.push(` var siblings = ${siblingsLiteral};`);
lines.push(` var expected = ${expectedLiteral};`);
lines.push(` for (var i = 0; i < siblings.length; i++) {`);
lines.push(` try {`);
lines.push(` var sp = siblings[i];`);
lines.push(` var spKey = siblings[i];`);
lines.push(` var sp = spKey;`);
lines.push(` if (!_path.isAbsolute(sp) && typeof __dirname === "string") sp = _path.join(__dirname, sp);`);
lines.push(` var sibBuf = _fs.readFileSync(sp);`);
lines.push(` var sibHex = _c.createHash("sha256").update(sibBuf).digest("hex");`);
lines.push(` if (expected[spKey] && expected[spKey] !== sibHex) {`);
if (hardFailOnSiblingMismatch) {
lines.push(` throw new Error("integrity check failed");`);
} else {
lines.push(` digest = 0xffffffff;`);
}
lines.push(` }`);
lines.push(` h.update(sp);`);
lines.push(` h.update(_fs.readFileSync(sp));`);
lines.push(` } catch (_e2) { h.update("missing:" + String(siblings[i])); }`);
lines.push(` h.update(sibBuf);`);
lines.push(` } catch (_e2) {`);
lines.push(` if (_e2 && _e2.message === "integrity check failed") throw _e2;`);
lines.push(` h.update("missing:" + String(siblings[i]));`);
lines.push(` }`);
lines.push(` }`);
if (envFingerprint) {
lines.push(` var envNote = "";`);
@@ -92,7 +141,10 @@ export function generateSelfSealSnippet(
}
lines.push(` var hex = h.digest("hex");`);
lines.push(` digest = parseInt(hex.slice(0, 8), 16) >>> 0;`);
lines.push(` } catch (_e4) { digest = 0; }`);
lines.push(` } catch (_e4) {`);
lines.push(` if (_e4 && _e4.message === "integrity check failed") throw _e4;`);
lines.push(` digest = 0;`);
lines.push(` }`);
lines.push(` return digest >>> 0;`);
lines.push(`}`);
lines.push(`var ${bindingName} = ${helperName}();`);
@@ -104,6 +156,8 @@ export function generateSelfSealSnippet(
expectedDigestHelperName: helperName,
siblingCount: siblings.length,
envFingerprint,
expectedSiblingHashCount: expectedEntries.length,
hardFailOnSiblingMismatch,
};
}
+222
View File
@@ -0,0 +1,222 @@
import { createHash } from "node:crypto";
import {
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { discoverHardenTargets, hardenProject } from "../src/engine/harden.js";
import { handleMcpRequest } from "../src/mcp/server.js";
import { runCli } from "../src/cli.js";
const tempDirs: string[] = [];
function tmp(): string {
const d = mkdtempSync(join(tmpdir(), "bla-write-safety-"));
tempDirs.push(d);
return d;
}
afterEach(() => {
for (const d of tempDirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
const JS = `export function unlockPremium(token) { return token === "LIVE-KEY"; }\n`;
function project(jsFiles = 2): string {
const root = tmp();
mkdirSync(join(root, "dist"), { recursive: true });
for (let i = 0; i < jsFiles; i++) writeFileSync(join(root, "dist", `m${i}.js`), JS, "utf8");
return root;
}
/** path → sha256 + mtime for every entry, so any write is visible. */
function snapshot(root: string): Record<string, string> {
const out: Record<string, string> = {};
const walk = (dir: string): void => {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, e.name);
const rel = relative(root, full);
if (e.isDirectory()) {
out[`${rel}/`] = "dir";
walk(full);
} else {
out[rel] = `${createHash("sha256").update(readFileSync(full)).digest("hex")}@${statSync(full).mtimeMs}`;
}
}
};
walk(root);
return out;
}
async function call(name: string, args: Record<string, unknown>) {
const res = await handleMcpRequest({
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name, arguments: args },
});
expect(res?.error).toBeUndefined();
return res!.result as {
isError: boolean;
structuredContent: {
readonly [key: string]: unknown;
artifacts?: ReadonlyArray<{ relativePath?: string; outputPath?: string }>;
truncated?: boolean;
dryRun?: boolean;
overallSuccess?: boolean;
hardenedCount?: number;
discoveredCount?: number;
wouldOverwrite?: readonly string[];
status?: string;
writeReceipt?: Readonly<Record<string, unknown>>;
};
};
}
describe("read-only discover + zero-write dry-run", () => {
it("bla_discover inventories targets without writing", async () => {
const root = project(2);
const before = snapshot(root);
const r = await call("bla_discover", { directory: root });
expect(r.isError).toBe(false);
expect((r.structuredContent.artifacts ?? []).map((a) => a.relativePath).sort()).toEqual([
"dist/m0.js",
"dist/m1.js",
]);
expect(r.structuredContent.truncated).toBe(false);
expect(snapshot(root)).toEqual(before);
});
it("reports truncation explicitly instead of silently capping", () => {
const root = project(5);
const d = discoverHardenTargets(root, { maxArtifacts: 3 });
expect(d.artifacts).toHaveLength(3);
expect(d.truncated).toBe(true);
expect(d.maxArtifacts).toBe(3);
expect(discoverHardenTargets(root, { maxArtifacts: 5 }).truncated).toBe(false);
const report = hardenProject({ directory: root, dryRun: true, maxArtifacts: 3 });
expect(report.truncated).toBe(true);
});
it("bla_harden dry_run plans outputs and leaves the workspace byte-identical", async () => {
const root = project(2);
const before = snapshot(root);
const r = await call("bla_harden", { directory: root, dry_run: true });
expect(r.isError).toBe(false);
const rep = r.structuredContent;
expect(rep.dryRun).toBe(true);
// Preview must not claim a successful harden.
expect(rep.overallSuccess).toBe(false);
expect(rep.hardenedCount).toBe(0);
expect(rep.discoveredCount).toBe(2);
expect(rep.artifacts?.[0]?.outputPath).toContain(".bla-hardened");
expect(rep.wouldOverwrite).toEqual([]);
expect(rep.writeReceipt).toBeUndefined();
expect(existsSync(join(root, ".bla-hardened"))).toBe(false);
expect(snapshot(root)).toEqual(before);
});
it("dry_run never demands confirm_overwrite even when planned outputs already exist", async () => {
const root = project(1);
const first = await call("bla_harden", { directory: root, seed: "pre" });
expect(first.isError).toBe(false);
const out = join(root, ".bla-hardened", "dist", "m0.js");
const hardened = readFileSync(out, "utf8");
const before = snapshot(root);
const preview = await call("bla_harden", { directory: root, dry_run: true, seed: "pre2" });
expect(preview.isError).toBe(false);
expect(preview.structuredContent.status).not.toBe("confirmation_required");
expect(preview.structuredContent.dryRun).toBe(true);
expect(preview.structuredContent.overallSuccess).toBe(false);
expect(preview.structuredContent.wouldOverwrite).toEqual([out]);
expect(readFileSync(out, "utf8")).toBe(hardened);
expect(snapshot(root)).toEqual(before);
});
it("CLI `harden --dry-run` writes nothing (no .bla-hardened, no .blarc)", async () => {
const root = project(1);
const before = snapshot(root);
const code = await runCli(["harden", root, "--dry-run", "--json"]);
expect(code).toBe(0);
expect(snapshot(root)).toEqual(before);
});
});
describe("overwrite confirmation boundary", () => {
it("bla_harden refuses to clobber existing hardened outputs without confirm_overwrite", async () => {
const root = project(1);
const first = await call("bla_harden", { directory: root, seed: "s1" });
expect(first.isError).toBe(false);
expect(first.structuredContent.hardenedCount).toBe(1);
const out = join(root, ".bla-hardened", "dist", "m0.js");
expect(first.structuredContent.writeReceipt).toMatchObject({
status: "written",
wrote: expect.arrayContaining([out]),
overwrote: [],
confirmed: false,
});
const hardened = readFileSync(out, "utf8");
const refused = await call("bla_harden", { directory: root, seed: "s2" });
expect(refused.isError).toBe(true);
expect(refused.structuredContent.status).toBe("confirmation_required");
expect(refused.structuredContent.wouldOverwrite).toEqual([out]);
expect(readFileSync(out, "utf8")).toBe(hardened);
const ok = await call("bla_harden", { directory: root, seed: "s2", confirm_overwrite: true });
expect(ok.isError).toBe(false);
expect(ok.structuredContent.hardenedCount).toBe(1);
expect(ok.structuredContent.wouldOverwrite).toEqual([out]);
expect(ok.structuredContent.writeReceipt).toMatchObject({
status: "written",
overwrote: [out],
confirmed: true,
});
});
it("bla_protect refuses an existing output_path without confirmation and succeeds with it", async () => {
const root = project(1);
const input = join(root, "dist", "m0.js");
const output = join(root, "out.js");
writeFileSync(output, "// precious\n", "utf8");
const refused = await call("bla_protect", { input_path: input, output_path: output });
expect(refused.isError).toBe(true);
expect(refused.structuredContent.status).toBe("confirmation_required");
expect(readFileSync(output, "utf8")).toBe("// precious\n");
const ok = await call("bla_protect", {
input_path: input,
output_path: output,
confirm_overwrite: true,
});
expect(ok.isError).toBe(false);
expect(ok.structuredContent.writeReceipt).toMatchObject({
status: "written",
wrote: [output],
overwrote: [output],
confirmed: true,
});
expect(readFileSync(output, "utf8")).not.toBe("// precious\n");
});
it("bla_defend writes a fresh default output without confirmation and returns a receipt", async () => {
const root = project(1);
const input = join(root, "dist", "m0.js");
const r = await call("bla_defend", { input_path: input, seed: "x" });
expect(r.isError).toBe(false);
const expected = join(root, "dist", "m0.shielded.js");
expect(r.structuredContent.writeReceipt).toMatchObject({ wrote: [expected], overwrote: [] });
const again = await call("bla_defend", { input_path: input, seed: "x" });
expect(again.isError).toBe(true);
expect(again.structuredContent.wouldOverwrite).toEqual([expected]);
});
});
+3 -14
View File
@@ -4,7 +4,7 @@ import * as os from "node:os";
import * as path from "node:path";
import { runSetup, runUninstall } from "../src/setup/setup.js";
import { runDoctor } from "../src/setup/doctor.js";
import { handleMcpRequest } from "../src/mcp/server.js";
import { BLA_MCP_TOOLS, handleMcpRequest } from "../src/mcp/server.js";
import { runShowcaseBenchmark } from "../src/engine/benchmark.js";
import { isNodeSqliteAvailable } from "../src/core/sqlite-runtime.js";
@@ -76,19 +76,8 @@ describe("CLI Setup, Doctor, Benchmark & MCP Server", () => {
method: "tools/list",
});
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",
"bla_verify",
"bla_benchmark",
"bla_emit_headers",
"bla_doctor",
"bla_inspect_release",
"bla_init",
"bla_weave_plan",
]);
expect(tools.map((t) => t.name)).toEqual(BLA_MCP_TOOLS.map((t) => t.name));
expect(tools.map((t) => t.name)).toContain("bla_lint_lanes");
// Test bla_audit + bla_protect + bla_verify via MCP tool calls
const sampleFile = path.join(tmpDir, "sample.js");
+59
View File
@@ -0,0 +1,59 @@
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 { buildTestJsAesUnwrapFootgun } from "../src/engine/js-aes-unwrap-lint.js";
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
describe("red-blue round-4 JS AES unwrap gates", () => {
it("bankrupt protect refuses JS AES unwrap footgun unless allowed", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-aes-gate-"));
dirs.push(dir);
const input = join(dir, "license.cjs");
const output = join(dir, "license.out.cjs");
writeFileSync(input, buildTestJsAesUnwrapFootgun({}), "utf8");
expect(() =>
protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r4-aes-gate",
honeySourceMaps: false,
}),
).toThrow(/allowJsAesUnwrap|AES sealed-blob unwrap/);
const ok = protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r4-aes-gate",
honeySourceMaps: false,
allowJsAesUnwrap: true,
});
expect(ok.detectedFormat).toBe("javascript");
});
it("bankrupt harden refuses project trees with JS AES unwrap footguns", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-aes-harden-"));
dirs.push(dir);
mkdirSync(join(dir, "dist"));
writeFileSync(join(dir, "dist", "license.cjs"), buildTestJsAesUnwrapFootgun({}), "utf8");
writeFileSync(
join(dir, "dist", "core.wasm"),
Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]),
);
const report = hardenProject({
directory: dir,
intensity: "bankrupt",
seed: "r4-harden-aes",
dryRun: true,
});
expect(report.overallSuccess).toBe(false);
expect(report.artifacts.some((a) => /AES|allowJsAesUnwrap/i.test(a.error ?? ""))).toBe(true);
});
});
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import {
buildTestJsAesUnwrapFootgun,
intensityEnforcesJsAesUnwrapRefusal,
JS_AES_UNWRAP_SCHEMA,
lintJsAesUnwrapSource,
} from "../src/engine/js-aes-unwrap-lint.js";
describe("js-aes-unwrap lint (red-blue round-4)", () => {
it("flags R4-shaped wrap-key + createDecipheriv + fixed hdr as refuse", () => {
const src = buildTestJsAesUnwrapFootgun({});
const report = lintJsAesUnwrapSource(src, { path: "license.cjs" });
expect(report.schema).toBe(JS_AES_UNWRAP_SCHEMA);
expect(report.shouldRefuseBankrupt).toBe(true);
expect(report.hasWrapKeyMaterial).toBe(true);
expect(report.hasCreateCipherIv).toBe(true);
expect(report.hasFixedSealedHdr).toBe(true);
expect(report.findings.some((f) => f.id === "js-aes-sealed-blob-unwrap")).toBe(true);
expect(intensityEnforcesJsAesUnwrapRefusal("bankrupt")).toBe(true);
expect(intensityEnforcesJsAesUnwrapRefusal("maximum")).toBe(false);
});
it("does not refuse clean code without key material", () => {
const src = `
const crypto = require("crypto");
function hash(s) {
return crypto.createHash("sha256").update(s).digest("hex");
}
module.exports = { hash };
`;
const report = lintJsAesUnwrapSource(src);
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.looksExposed).toBe(false);
});
it("warns on partial signals without full combo", () => {
const noHdr = buildTestJsAesUnwrapFootgun({ omitHdr: true });
const report = lintJsAesUnwrapSource(noHdr);
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.hasCreateCipherIv).toBe(true);
expect(report.hasWrapKeyMaterial).toBe(true);
});
});
@@ -0,0 +1,61 @@
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 { buildTestJsWasmHydrateDumpFootgun } from "../src/engine/js-wasm-hydrate-dump-lint.js";
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
describe("red-blue round-5 JS WASM hydrate-dump gates", () => {
it("bankrupt protect refuses hydrate dump footgun unless allowed", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-hydrate-gate-"));
dirs.push(dir);
const input = join(dir, "license.cjs");
const output = join(dir, "license.out.cjs");
writeFileSync(input, buildTestJsWasmHydrateDumpFootgun({}), "utf8");
expect(() =>
protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r5-hydrate-gate",
honeySourceMaps: false,
}),
).toThrow(/allowJsWasmHydrateDump|hydrate param-dump/);
const ok = protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r5-hydrate-gate",
honeySourceMaps: false,
allowJsWasmHydrateDump: true,
});
expect(ok.detectedFormat).toBe("javascript");
});
it("bankrupt harden refuses project trees with hydrate dump footguns", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-hydrate-harden-"));
dirs.push(dir);
mkdirSync(join(dir, "dist"));
writeFileSync(join(dir, "dist", "license.cjs"), buildTestJsWasmHydrateDumpFootgun({}), "utf8");
writeFileSync(
join(dir, "dist", "core.wasm"),
Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]),
);
const report = hardenProject({
directory: dir,
intensity: "bankrupt",
seed: "r5-harden-hydrate",
dryRun: true,
});
expect(report.overallSuccess).toBe(false);
expect(
report.artifacts.some((a) => /hydrate|allowJsWasmHydrateDump/i.test(a.error ?? "")),
).toBe(true);
});
});
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import { existsSync, readFileSync } from "node:fs";
import {
buildTestJsWasmHydrateDumpFootgun,
intensityEnforcesJsWasmHydrateDumpRefusal,
JS_WASM_HYDRATE_DUMP_SCHEMA,
lintJsWasmHydrateDumpSource,
} from "../src/engine/js-wasm-hydrate-dump-lint.js";
/** R6-shaped host: arity-2 unlock in WASM; no salt/rounds/cipher layout dump. */
function buildUnlockInWasmHost(): string {
return `
const fs = require("fs");
async function callUnlock(keyStr) {
const bytes = fs.readFileSync("core.wasm");
const { instance } = await WebAssembly.instantiate(bytes, {});
const exp = instance.exports;
let memory = null;
for (const v of Object.values(exp)) {
if (v instanceof WebAssembly.Memory) { memory = v; break; }
}
let unlock = typeof exp.unlock === "function" && exp.unlock.length === 2 ? exp.unlock : null;
if (!unlock) {
for (const fn of Object.values(exp)) {
if (typeof fn === "function" && fn.length === 2) { unlock = fn; break; }
}
}
const u8 = new Uint8Array(memory.buffer);
u8.set(Buffer.from(keyStr, "utf8"), 2048);
const n = unlock(2048, 16) | 0;
return Buffer.from(u8.subarray(4096, 4096 + n)).toString("utf8");
}
module.exports = { callUnlock };
`;
}
describe("js-wasm-hydrate-dump lint (red-blue round-5)", () => {
it("flags R5-shaped memory.buffer + hydrate + salt/rounds/cipher as refuse", () => {
const src = buildTestJsWasmHydrateDumpFootgun({});
const report = lintJsWasmHydrateDumpSource(src, { path: "license.cjs" });
expect(report.schema).toBe(JS_WASM_HYDRATE_DUMP_SCHEMA);
expect(report.shouldRefuseBankrupt).toBe(true);
expect(report.hasMemoryBufferRead).toBe(true);
expect(report.hasHydrateCall).toBe(true);
expect(report.hasParamLayoutDecode).toBe(true);
expect(report.findings.some((f) => f.id === "js-wasm-hydrate-param-dump")).toBe(true);
expect(intensityEnforcesJsWasmHydrateDumpRefusal("bankrupt")).toBe(true);
expect(intensityEnforcesJsWasmHydrateDumpRefusal("maximum")).toBe(false);
});
it("does not refuse clean hashing code", () => {
const src = `
const crypto = require("crypto");
function hash(s) {
return crypto.createHash("sha256").update(s).digest("hex");
}
module.exports = { hash };
`;
const report = lintJsWasmHydrateDumpSource(src);
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.looksExposed).toBe(false);
});
it("warns on partial signals without full combo", () => {
const noLayout = buildTestJsWasmHydrateDumpFootgun({ omitLayout: true });
const report = lintJsWasmHydrateDumpSource(noLayout);
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.hasMemoryBufferRead).toBe(true);
});
it("does not refuse unlock-in-WASM host (R6 shape)", () => {
const src = buildUnlockInWasmHost();
const report = lintJsWasmHydrateDumpSource(src, { path: "license.cjs" });
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.hasParamLayoutDecode).toBe(false);
expect(report.hasHydrateCall).toBe(false);
});
it("flags the round-5 cleartext license fixture when present", () => {
const path = "/workspace/bla-redblue/round-5/target/license.cjs";
if (!existsSync(path)) return; // optional dogfood fixture — absent on CI clones
const src = readFileSync(path, "utf8");
const report = lintJsWasmHydrateDumpSource(src, { path });
expect(report.shouldRefuseBankrupt).toBe(true);
});
it("does not refuse the round-6 unlock-in-WASM license fixture when present", () => {
const path = "/workspace/bla-redblue/round-6/target/license.cjs";
if (!existsSync(path)) return;
const src = readFileSync(path, "utf8");
const report = lintJsWasmHydrateDumpSource(src, { path });
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.hasParamLayoutDecode).toBe(false);
expect(report.hasHydrateCall).toBe(false);
});
});
@@ -0,0 +1,89 @@
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { hardenProject } from "../src/engine/harden.js";
import { protectTarget } from "../src/engine/protector.js";
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
const INDEPENDENT_GATE = `
const lanes = [0x41, 0x42, 0x43, 0x44, 0x45];
export function check(key) {
return key.split("").every((ch, i) => ch.charCodeAt(0) === lanes[i]);
}
`;
const WHOLE_KEY_GATE = `
export function activate(key) {
let a = 0, b = 1;
for (let i = 0; i < key.length; i++) {
a = (a + key.charCodeAt(i) * (i + 3)) | 0;
b = Math.imul(b ^ a, 0x01000193) | 0;
}
return (a ^ b) === 0x12345678;
}
`;
describe("harden/protect lane-independence gate (red-blue round-1 P0)", () => {
it("refuses independent 1-byte lane JS by default", () => {
const root = mkdtempSync(join(tmpdir(), "bla-lane-refuse-"));
dirs.push(root);
const src = join(root, "gate.js");
writeFileSync(src, INDEPENDENT_GATE, "utf8");
expect(() =>
protectTarget({
inputPath: src,
outputPath: join(root, "out.js"),
intensity: "balanced",
seed: "lane-refuse",
}),
).toThrow(/allowLaneIndependentGates|lane-independent/i);
const app = join(root, "app");
mkdirSync(app);
writeFileSync(join(app, "gate.js"), INDEPENDENT_GATE, "utf8");
const report = hardenProject({
directory: app,
intensity: "stealth",
seed: "lane-refuse-harden",
outputDirectory: join(root, "hardened"),
});
expect(report.overallSuccess).toBe(false);
expect(report.artifacts.some((a) => a.error && /lane-independent|allowLaneIndependent/i.test(a.error))).toBe(
true,
);
});
it("passes whole-key mixing without allow flag", () => {
const root = mkdtempSync(join(tmpdir(), "bla-lane-ok-"));
dirs.push(root);
const src = join(root, "gate.js");
writeFileSync(src, WHOLE_KEY_GATE, "utf8");
const res = protectTarget({
inputPath: src,
outputPath: join(root, "out.js"),
intensity: "balanced",
seed: "lane-ok",
});
expect(res.outputPath).toBe(join(root, "out.js"));
});
it("allows independent lanes only with allowLaneIndependentGates", () => {
const root = mkdtempSync(join(tmpdir(), "bla-lane-allow-"));
dirs.push(root);
const src = join(root, "gate.js");
writeFileSync(src, INDEPENDENT_GATE, "utf8");
const res = protectTarget({
inputPath: src,
outputPath: join(root, "out.js"),
intensity: "balanced",
seed: "lane-allow",
allowLaneIndependentGates: true,
});
expect(res.outputPath).toBe(join(root, "out.js"));
});
});
+58 -4
View File
@@ -1,7 +1,13 @@
import { describe, expect, it } from "vitest";
import { lintLaneIndependence } from "../src/engine/lane-independence-lint.js";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import {
lintLaneIndependence,
formatSupportsLaneIndependenceLint,
laneIndependenceRefuseMessage,
} from "../src/engine/lane-independence-lint.js";
describe("lane-independence footgun lint (#40.1)", () => {
describe("lane-independence footgun lint (#40.1 / red-blue round-1)", () => {
it("stays quiet on chained whole-key mixing (Meridian-like)", () => {
const src = `
function activate(key) {
@@ -20,7 +26,7 @@ describe("lane-independence footgun lint (#40.1)", () => {
expect(report.findings).toHaveLength(0);
});
it("warns on per-lane byte compare table + key identifiers", () => {
it("errors on per-lane byte compare table + key identifiers", () => {
const src = `
const lanes = [0x41, 0x42, 0x43, 0x44, 0x45];
function check(key) {
@@ -29,9 +35,11 @@ describe("lane-independence footgun lint (#40.1)", () => {
`;
const report = lintLaneIndependence(src);
expect(report.looksLaneIndependent).toBe(true);
expect(report.findings.every((f) => f.severity === "error")).toBe(true);
expect(report.findings.some((f) => f.id === "per-lane-byte-compare-array")).toBe(true);
expect(report.findings.some((f) => f.id === "independent-lane-and-reduce")).toBe(true);
expect(report.oneLineAdvice).toMatch(/whole-key chained mixing/i);
expect(report.oneLineAdvice).toMatch(/ERROR/i);
const explicit = lintLaneIndependence(`
const lanes = [1,2,3,4];
@@ -40,7 +48,7 @@ describe("lane-independence footgun lint (#40.1)", () => {
expect(explicit.findings.some((f) => f.id === "independent-lane-and-reduce")).toBe(true);
});
it("warns on indexed lane oracle loops", () => {
it("errors on indexed lane oracle loops", () => {
const src = `
for (let i = 0; i < 16; i++) {
if (key[i] === target[i]) ok++;
@@ -48,5 +56,51 @@ describe("lane-independence footgun lint (#40.1)", () => {
`;
const report = lintLaneIndependence(src);
expect(report.findings.some((f) => f.id === "indexed-lane-oracle-loop")).toBe(true);
expect(report.findings[0]!.severity).toBe("error");
});
it("ignores all-zero init arrays used for whole-key packing (round-2 blue)", () => {
const src = `
function packWord(key, start) {
let w = 0;
for (let i = 0; i < 4; i++) w = (w << 8) | key.charCodeAt(start + i);
return w | 0;
}
function activate(key) {
let a = packWord(key, 0), b = packWord(key, 4), c = packWord(key, 8), d = packWord(key, 12);
// legacy-looking zero buffer that is NOT a compare table:
const scratch = [0, 0, 0, 0];
void scratch;
for (let r = 0; r < 24; r++) {
a = (a + b) | 0; b = (b ^ a) | 0; c = (c + d) | 0; d = (d ^ c) | 0;
a ^= c; b ^= d;
}
return (a ^ b ^ c ^ d) === 0x12345678;
}
`;
const report = lintLaneIndependence(src);
expect(report.findings.some((f) => f.id === "per-lane-byte-compare-array")).toBe(false);
expect(report.looksLaneIndependent).toBe(false);
});
it("errors on CrackMe v6-style per-byte WASM lane oracles", () => {
const tpl = readFileSync(
resolve(process.cwd(), "challenge/v6/src/vault.template.cjs"),
"utf8",
);
const report = lintLaneIndependence(tpl);
expect(report.looksLaneIndependent).toBe(true);
expect(report.findings.some((f) => f.id === "per-byte-wasm-lane-oracle")).toBe(true);
expect(report.findings.every((f) => f.severity === "error")).toBe(true);
expect(laneIndependenceRefuseMessage(report, "/tmp/vault.cjs")).toMatch(
/allowLaneIndependentGates|allow-lane-independent/i,
);
});
it("formatSupportsLaneIndependenceLint covers JS/TS only", () => {
expect(formatSupportsLaneIndependenceLint("javascript")).toBe(true);
expect(formatSupportsLaneIndependenceLint("typescript")).toBe(true);
expect(formatSupportsLaneIndependenceLint("wasm")).toBe(false);
expect(formatSupportsLaneIndependenceLint("html-bundle")).toBe(false);
});
});
+184
View File
@@ -0,0 +1,184 @@
import { describe, expect, it } from "vitest";
import { BLA_MCP_TOOLS } from "../src/mcp/server.js";
/**
* Maintainable expectation list: engine capabilities agents rely on that MCP
* must expose. Add a row when a new engine knob is intentionally hung on MCP;
* do not assert raw schema prose — only tool name + param keys.
*
* This is NOT "full CLI mirror"; only the agreed agent-facing surface.
*/
const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
readonly tool: string;
readonly params: readonly string[];
}> = Object.freeze([
{
tool: "bla_harden",
params: [
"directory",
"intensity",
"emit_manifest",
"llm_directives",
"weave_decoys",
"self_seal",
"wasm_preserve_exports",
"allow_lane_independent",
"allow_plaintext_seal",
"allow_wasm_clear_params",
"allow_stable_panel_derive",
"allow_js_aes_unwrap",
"allow_panel_offline_oracle",
"allow_js_wasm_hydrate_dump",
"allow_wasm_xor_mask_sidecar",
"allow_wasm_seal_xor_known_plaintext",
"seed",
"dry_run",
"max_artifacts",
"confirm_overwrite",
"output_directory",
],
},
{
tool: "bla_discover",
params: ["directory", "max_artifacts"],
},
{
tool: "bla_defend",
params: [
"input_path",
"output_path",
"intensity",
"emit_manifest",
"llm_directives",
"weave_decoys",
"self_seal",
"wasm_preserve_exports",
"allow_lane_independent",
"allow_plaintext_seal",
"allow_wasm_clear_params",
"allow_stable_panel_derive",
"allow_js_aes_unwrap",
"allow_panel_offline_oracle",
"allow_js_wasm_hydrate_dump",
"allow_wasm_xor_mask_sidecar",
"allow_wasm_seal_xor_known_plaintext",
"seed",
"in_place",
"confirm_overwrite",
],
},
{
tool: "bla_protect",
params: [
"input_path",
"output_path",
"intensity",
"weave_decoys",
"self_seal",
"wasm_preserve_exports",
"allow_lane_independent",
"allow_plaintext_seal",
"allow_wasm_clear_params",
"allow_stable_panel_derive",
"allow_js_aes_unwrap",
"allow_panel_offline_oracle",
"allow_js_wasm_hydrate_dump",
"allow_wasm_xor_mask_sidecar",
"allow_wasm_seal_xor_known_plaintext",
"seed",
"llm_directives",
"in_place",
"honey_source_maps",
"confirm_overwrite",
],
},
{
tool: "bla_verify",
params: [
"target_path",
"original_path",
"self_seal_enabled",
"wasm_export_rename_applied",
"numeric_template_leak_known",
"summary_path",
"run_id",
],
},
{
tool: "bla_lint",
params: [
"directory",
"intensity",
"allow_plaintext_seal",
"allow_wasm_clear_params",
"allow_js_aes_unwrap",
"allow_js_wasm_hydrate_dump",
"allow_wasm_xor_mask_sidecar",
"allow_wasm_seal_xor_known_plaintext",
"allow_lane_independent",
"allow_panel_offline_oracle",
],
},
{
tool: "bla_lint_lanes",
params: ["path"],
},
{
tool: "bla_lint_seal",
params: ["path"],
},
{
tool: "bla_lint_wasm_params",
params: ["path"],
},
{
tool: "bla_lint_panel_derive",
params: ["path"],
},
{
tool: "bla_lint_js_aes_unwrap",
params: ["path"],
},
{
tool: "bla_lint_js_wasm_hydrate_dump",
params: ["path"],
},
{
tool: "bla_lint_wasm_xor_mask_sidecar",
params: ["path"],
},
{
tool: "bla_lint_wasm_seal_xor_known_plaintext",
params: ["path", "seal_path"],
},
{
tool: "bla_run_lookup",
params: ["summary_path", "run_id"],
},
{
tool: "bla_rea_drift",
params: ["rea_root"],
},
{
tool: "bla_redteam_report",
params: ["execute", "rea_root", "report_path"],
},
]);
describe("MCP ↔ engine capability parity (agent-facing)", () => {
it("exposes every agreed engine capability on the named MCP tools", () => {
for (const expected of EXPECTED_MCP_ENGINE_CAPABILITIES) {
const tool = BLA_MCP_TOOLS.find((t) => t.name === expected.tool);
expect(tool, `missing MCP tool ${expected.tool}`).toBeDefined();
const props = Object.keys(tool!.inputSchema.properties);
for (const param of expected.params) {
expect(props, `${expected.tool} missing param ${param}`).toContain(param);
}
}
});
it("does not register duplicate tool names", () => {
const names = BLA_MCP_TOOLS.map((t) => t.name);
expect(new Set(names).size).toBe(names.length);
});
});
+45
View File
@@ -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 {
buildTestJsAesUnwrapFootgun,
JS_AES_UNWRAP_SCHEMA,
} from "../src/engine/js-aes-unwrap-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_js_aes_unwrap", () => {
it("registers once", () => {
expect(BLA_MCP_TOOLS.filter((t) => t.name === "bla_lint_js_aes_unwrap")).toHaveLength(1);
});
it("flags R4 footgun with isError", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-aes-"));
tempDirs.push(dir);
const file = join(dir, "license.cjs");
writeFileSync(file, buildTestJsAesUnwrapFootgun({}), "utf8");
const res = await call("bla_lint_js_aes_unwrap", { path: file });
expect(res?.error).toBeUndefined();
const result = res!.result as {
isError?: boolean;
structuredContent: { schema: string; shouldRefuseBankrupt: boolean };
};
expect(result.structuredContent.schema).toBe(JS_AES_UNWRAP_SCHEMA);
expect(result.structuredContent.shouldRefuseBankrupt).toBe(true);
expect(result.isError).toBe(true);
});
});
@@ -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 {
buildTestJsWasmHydrateDumpFootgun,
JS_WASM_HYDRATE_DUMP_SCHEMA,
} from "../src/engine/js-wasm-hydrate-dump-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_js_wasm_hydrate_dump", () => {
it("registers once", () => {
expect(BLA_MCP_TOOLS.filter((t) => t.name === "bla_lint_js_wasm_hydrate_dump")).toHaveLength(1);
});
it("flags R5 footgun with isError", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-hydrate-"));
tempDirs.push(dir);
const file = join(dir, "license.cjs");
writeFileSync(file, buildTestJsWasmHydrateDumpFootgun({}), "utf8");
const res = await call("bla_lint_js_wasm_hydrate_dump", { path: file });
expect(res?.error).toBeUndefined();
const result = res!.result as {
isError?: boolean;
structuredContent: { schema: string; shouldRefuseBankrupt: boolean };
};
expect(result.structuredContent.schema).toBe(JS_WASM_HYDRATE_DUMP_SCHEMA);
expect(result.structuredContent.shouldRefuseBankrupt).toBe(true);
expect(result.isError).toBe(true);
});
});
+108
View File
@@ -0,0 +1,108 @@
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 { LANE_INDEPENDENCE_SCHEMA } from "../src/engine/lane-independence-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>) {
const res = await handleMcpRequest({
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name, arguments: args },
});
return res;
}
describe("MCP bla_lint_lanes", () => {
it("is registered once next to the CLI-homologous engine", () => {
expect(BLA_MCP_TOOLS.filter((t) => t.name === "bla_lint_lanes")).toHaveLength(1);
const tool = BLA_MCP_TOOLS.find((t) => t.name === "bla_lint_lanes")!;
expect(tool.inputSchema.required).toEqual(["path"]);
expect(tool.inputSchema.properties.path?.type).toBe("string");
});
it("returns a clean report for whole-key mixing source", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-lint-clean-"));
tempDirs.push(dir);
const file = join(dir, "gate.js");
writeFileSync(
file,
`
function activate(key) {
let a = pack(key.slice(0,5)), b = pack(key.slice(5,10));
let c = pack(key.slice(10,15)), d = pack(key.slice(15,20));
for (let r = 0; r < 24; r++) {
a = (a + b) | 0; b = rotl(b ^ a, 7);
c = (c + d) | 0; d = rotl(d ^ c, 9);
a ^= c; b ^= d;
}
return hex(a,b,c,d) === catalog.revision;
}
`,
"utf8",
);
const res = await call("bla_lint_lanes", { path: file });
expect(res?.error).toBeUndefined();
const result = res!.result as {
isError?: boolean;
structuredContent: {
schema: string;
looksLaneIndependent: boolean;
findings: readonly unknown[];
oneLineAdvice: string;
};
};
expect(result.isError).toBeFalsy();
expect(result.structuredContent.schema).toBe(LANE_INDEPENDENCE_SCHEMA);
expect(result.structuredContent.looksLaneIndependent).toBe(false);
expect(result.structuredContent.findings).toHaveLength(0);
});
it("returns error findings for independent per-lane gate shapes", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-lint-warn-"));
tempDirs.push(dir);
const file = join(dir, "oracle.js");
writeFileSync(
file,
`
const lanes = [0x41, 0x42, 0x43, 0x44, 0x45];
function check(key) {
return key.split("").every((ch, i) => ch.charCodeAt(0) === lanes[i]);
}
`,
"utf8",
);
const res = await call("bla_lint_lanes", { path: file });
expect(res?.error).toBeUndefined();
const result = res!.result as {
structuredContent: {
looksLaneIndependent: boolean;
findings: ReadonlyArray<{ id: string; severity: string }>;
oneLineAdvice: string;
};
};
expect(result.structuredContent.looksLaneIndependent).toBe(true);
expect(result.structuredContent.findings.some((f) => f.id === "per-lane-byte-compare-array")).toBe(
true,
);
expect(result.structuredContent.findings.every((f) => f.severity === "error")).toBe(true);
expect(result.structuredContent.oneLineAdvice).toMatch(/whole-key chained mixing/i);
});
it("errors when the source file is missing", async () => {
const res = await call("bla_lint_lanes", {
path: join(tmpdir(), "bla-missing-lane-gate-does-not-exist.js"),
});
expect(res?.error).toBeUndefined();
const result = res!.result as { isError: boolean; content: ReadonlyArray<{ text: string }> };
expect(result.isError).toBe(true);
expect(result.content[0]?.text).toMatch(/not found/i);
});
});
+77
View File
@@ -0,0 +1,77 @@
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 { SEAL_COMMITMENT_SCHEMA } from "../src/engine/seal-commitment-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 },
});
}
const ROUND2 = {
schema: "bla-redblue-r2-seal/v1",
rounds: 28,
scheduleSalt: 1374179543,
revision: "7f325fec37206b637a224e9630b67c4a",
certificateCipherHex: "aabb",
};
const ONE_WAY = {
schema: "bla-entitlement-seal/v1",
algorithm: "sha256",
revision: "b38091d4a394ded9012846e8d4b647083b260beb6ee5ad1e42265fe6f107c660",
};
describe("MCP bla_lint_seal", () => {
it("is registered once", () => {
expect(BLA_MCP_TOOLS.filter((t) => t.name === "bla_lint_seal")).toHaveLength(1);
});
it("flags reversible seal and sets isError", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-seal-bad-"));
tempDirs.push(dir);
const file = join(dir, "seal.json");
writeFileSync(file, JSON.stringify(ROUND2), "utf8");
const res = await call("bla_lint_seal", { path: file });
expect(res?.error).toBeUndefined();
const result = res!.result as {
isError?: boolean;
structuredContent: {
schema: string;
shouldRefuseBankrupt: boolean;
findings: ReadonlyArray<{ id: string; severity: string }>;
};
};
expect(result.structuredContent.schema).toBe(SEAL_COMMITMENT_SCHEMA);
expect(result.structuredContent.shouldRefuseBankrupt).toBe(true);
expect(result.isError).toBe(true);
expect(
result.structuredContent.findings.some((f) => f.id === "reversible-public-commitment"),
).toBe(true);
});
it("passes one-way digest without refuse", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-seal-ok-"));
tempDirs.push(dir);
const file = join(dir, "seal.json");
writeFileSync(file, JSON.stringify(ONE_WAY), "utf8");
const res = await call("bla_lint_seal", { path: file });
const result = res!.result as {
isError?: boolean;
structuredContent: { shouldRefuseBankrupt: boolean };
};
expect(result.structuredContent.shouldRefuseBankrupt).toBe(false);
expect(result.isError).toBeFalsy();
});
});
+60
View File
@@ -0,0 +1,60 @@
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 { buildTestWasmWithParamCarrier } from "../src/engine/wasm-param-carrier-lint.js";
import { WASM_PARAM_CARRIER_SCHEMA } from "../src/engine/wasm-param-carrier-lint.js";
import { PANEL_DERIVE_ABI_SCHEMA } from "../src/engine/panel-derive-abi-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_params / bla_lint_panel_derive", () => {
it("registers both tools once", () => {
expect(BLA_MCP_TOOLS.filter((t) => t.name === "bla_lint_wasm_params")).toHaveLength(1);
expect(BLA_MCP_TOOLS.filter((t) => t.name === "bla_lint_panel_derive")).toHaveLength(1);
});
it("flags clear WASM carriers with isError", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-wasm-"));
tempDirs.push(dir);
const file = join(dir, "core.wasm");
writeFileSync(file, buildTestWasmWithParamCarrier({}));
const res = await call("bla_lint_wasm_params", { path: file });
expect(res?.error).toBeUndefined();
const result = res!.result as {
isError?: boolean;
structuredContent: { schema: string; shouldRefuseBankrupt: boolean };
};
expect(result.structuredContent.schema).toBe(WASM_PARAM_CARRIER_SCHEMA);
expect(result.structuredContent.shouldRefuseBankrupt).toBe(true);
expect(result.isError).toBe(true);
});
it("flags stable panel derive with isError", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-panel-"));
tempDirs.push(dir);
const file = join(dir, "panel.js");
writeFileSync(file, "globalThis.__vaultPanelDerive_r3 = (x) => x;\n", "utf8");
const res = await call("bla_lint_panel_derive", { path: file });
const result = res!.result as {
isError?: boolean;
structuredContent: { schema: string; shouldRewriteOrRefuse: boolean };
};
expect(result.structuredContent.schema).toBe(PANEL_DERIVE_ABI_SCHEMA);
expect(result.structuredContent.shouldRewriteOrRefuse).toBe(true);
expect(result.isError).toBe(true);
});
});
@@ -0,0 +1,47 @@
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 {
buildTestWasmWithSealXorKnownPlaintext,
WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA,
} from "../src/engine/wasm-seal-xor-known-plaintext-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_seal_xor_known_plaintext", () => {
it("registers once", () => {
expect(BLA_MCP_TOOLS.filter((t) => t.name === "bla_lint_wasm_seal_xor_known_plaintext")).toHaveLength(1);
});
it("flags R7 footgun with isError", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-sealxor-"));
tempDirs.push(dir);
const { wasm, seal } = buildTestWasmWithSealXorKnownPlaintext({});
const file = join(dir, "core.wasm");
writeFileSync(file, wasm);
writeFileSync(join(dir, "seal.json"), JSON.stringify(seal));
const res = await call("bla_lint_wasm_seal_xor_known_plaintext", { path: file });
expect(res?.error).toBeUndefined();
const result = res!.result as {
isError?: boolean;
structuredContent: { schema: string; shouldRefuseBankrupt: boolean };
};
expect(result.structuredContent.schema).toBe(WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA);
expect(result.structuredContent.shouldRefuseBankrupt).toBe(true);
expect(result.isError).toBe(true);
});
});
@@ -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);
});
});
+179
View File
@@ -0,0 +1,179 @@
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 { handleMcpRequest } from "../src/mcp/server.js";
import { protectTarget } from "../src/engine/protector.js";
const tempDirs: string[] = [];
afterEach(() => {
for (const d of tempDirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
const JS = `export function unlockPremium(token) { return token === "LIVE-KEY"; }\n`;
async function call(name: string, args: Record<string, unknown>) {
const res = await handleMcpRequest({
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name, arguments: args },
});
expect(res?.error).toBeUndefined();
return res!.result as {
isError: boolean;
structuredContent: {
readonly [key: string]: unknown;
status?: string;
wouldOverwrite?: readonly string[];
wrote?: readonly string[];
writeReceipt?: Readonly<Record<string, unknown>>;
outputDirectory?: string;
metrics?: { honeySourceMapsGenerated?: number };
defenseScore?: number;
defenseScoreRaw?: number;
defenseScoreGaps?: ReadonlyArray<{ id: string }>;
outputPath?: string;
selfSeal?: boolean;
};
};
}
describe("MCP param alignment: in_place / honey_source_maps / output_directory", () => {
it("bla_protect in_place refuses without confirm_overwrite and succeeds with it", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-inplace-"));
tempDirs.push(dir);
const input = join(dir, "app.js");
writeFileSync(input, JS, "utf8");
const before = readFileSync(input, "utf8");
const refused = await call("bla_protect", {
input_path: input,
in_place: true,
seed: "inplace-1",
});
expect(refused.isError).toBe(true);
expect(refused.structuredContent.status).toBe("confirmation_required");
expect(refused.structuredContent.wouldOverwrite).toEqual([input]);
expect(readFileSync(input, "utf8")).toBe(before);
const ok = await call("bla_protect", {
input_path: input,
in_place: true,
confirm_overwrite: true,
seed: "inplace-1",
});
expect(ok.isError).toBe(false);
expect(ok.structuredContent.writeReceipt).toMatchObject({
status: "written",
wrote: [input],
overwrote: [input],
confirmed: true,
});
expect(readFileSync(input, "utf8")).not.toBe(before);
expect(existsSync(join(dir, "app.shielded.js"))).toBe(false);
});
it("bla_defend in_place also requires confirm_overwrite before clobbering the input", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-defend-inplace-"));
tempDirs.push(dir);
const input = join(dir, "svc.js");
writeFileSync(input, JS, "utf8");
const refused = await call("bla_defend", {
input_path: input,
in_place: true,
seed: "d-inplace",
});
expect(refused.isError).toBe(true);
expect(refused.structuredContent.wouldOverwrite).toEqual([input]);
expect(readFileSync(input, "utf8")).toBe(JS);
});
it("bla_protect honey_source_maps:false skips honey map emission", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-honey-"));
tempDirs.push(dir);
const input = join(dir, "app.js");
const output = join(dir, "out.js");
writeFileSync(input, JS, "utf8");
const off = await call("bla_protect", {
input_path: input,
output_path: output,
honey_source_maps: false,
seed: "honey-off",
});
expect(off.isError).toBe(false);
expect(off.structuredContent.metrics?.honeySourceMapsGenerated).toBe(0);
const onOut = join(dir, "out-on.js");
const on = await call("bla_protect", {
input_path: input,
output_path: onOut,
honey_source_maps: true,
seed: "honey-on",
});
expect(on.isError).toBe(false);
expect((on.structuredContent.metrics?.honeySourceMapsGenerated ?? 0) > 0).toBe(true);
});
it("bla_harden output_directory writes under the custom root", async () => {
const root = mkdtempSync(join(tmpdir(), "bla-outdir-"));
tempDirs.push(root);
mkdirSync(join(root, "dist"), { recursive: true });
writeFileSync(join(root, "dist", "m0.js"), JS, "utf8");
const custom = join(root, "custom-out");
const r = await call("bla_harden", {
directory: root,
output_directory: custom,
seed: "outdir-1",
});
expect(r.isError).toBe(false);
expect(r.structuredContent.outputDirectory).toBe(custom);
expect(existsSync(join(custom, "dist", "m0.js"))).toBe(true);
expect(existsSync(join(root, ".bla-hardened"))).toBe(false);
});
});
describe("MCP bla_verify honesty metadata passthrough", () => {
it("soft-caps JS verify without self_seal_enabled and lifts the gap when metadata says sealed", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-verify-honesty-"));
tempDirs.push(dir);
const input = join(dir, "app.js");
writeFileSync(input, JS, "utf8");
const protectedRes = protectTarget({
inputPath: input,
intensity: "balanced",
seed: "verify-honesty-1",
selfSeal: true,
});
expect(protectedRes.selfSeal).toBe(true);
const without = await call("bla_verify", {
target_path: protectedRes.outputPath,
original_path: input,
});
expect(without.isError).toBe(false);
expect(
without.structuredContent.defenseScoreGaps?.some((g) => g.id === "self-seal-not-enabled"),
).toBe(true);
const withMeta = await call("bla_verify", {
target_path: protectedRes.outputPath,
original_path: input,
self_seal_enabled: true,
});
expect(withMeta.isError).toBe(false);
expect(
withMeta.structuredContent.defenseScoreGaps?.some((g) => g.id === "self-seal-not-enabled"),
).toBe(false);
expect(withMeta.structuredContent.defenseScoreRaw).toBeGreaterThanOrEqual(
withMeta.structuredContent.defenseScore as number,
);
});
});
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { handleMcpRequest } from "../src/mcp/server.js";
async function getPrompt(params: Record<string, unknown>) {
return handleMcpRequest({ jsonrpc: "2.0", id: 1, method: "prompts/get", params });
}
function text(res: unknown): string {
return (res as any)?.result?.messages?.[0]?.content?.text ?? "";
}
describe("MCP prompt arguments and interpolation", () => {
it("allows omitting arguments for an optional-only prompt", async () => {
const res = await getPrompt({ name: "bla-harden-project" });
expect((res as any).error).toBeUndefined();
expect(text(res)).toContain('"directory": "."');
expect(text(res)).toContain("dry_run");
});
it("still rejects missing required and malformed arguments", async () => {
expect(((await getPrompt({ name: "shield-against-rea", arguments: {} })) as any).error?.code).toBe(-32602);
expect(((await getPrompt({ name: "bla-harden-project", arguments: "x" })) as any).error?.code).toBe(-32602);
});
it("JSON-escapes paths containing quotes", async () => {
const t = text(await getPrompt({ name: "bla-harden-project", arguments: { directory: './we"ird' } }));
expect(t).toContain('"./we\\"ird"');
});
it("gives each generic prompt scenario-specific copy", async () => {
const names = ["shield-against-rea", "bla-hardening-workflow", "bla-counter-rea"];
const texts = await Promise.all(
names.map(async (name) => text(await getPrompt({ name, arguments: { target_path: "dist/app.js" } }))),
);
expect(new Set(texts).size).toBe(3);
for (const t of texts) {
expect(t).toContain('"dist/app.js"');
expect(t).toContain("confirm_overwrite");
}
});
});
+71
View File
@@ -0,0 +1,71 @@
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
PACKAGING_GATES_SCHEMA,
evaluateHardenProjectPackagingBlocks,
formatPackagingGatesReport,
scanPackagingGates,
} from "../src/engine/packaging-gates.js";
import { buildTestWasmWithXorMaskSidecar } from "../src/engine/wasm-xor-mask-sidecar-lint.js";
describe("packaging-gates (unified R1–R7 scan)", () => {
it("reports clean on an empty project tree", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-pg-clean-"));
const report = scanPackagingGates({ directory: dir, intensity: "bankrupt" });
expect(report.schema).toBe(PACKAGING_GATES_SCHEMA);
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.findings).toEqual([]);
expect(report.honestyNote.length).toBeGreaterThan(20);
expect(formatPackagingGatesReport(report)).toContain("no findings");
});
it("refuses bankrupt when a WASM XOR-mask sidecar is present", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-pg-xor-"));
writeFileSync(join(dir, "core.wasm"), buildTestWasmWithXorMaskSidecar());
const report = scanPackagingGates({ directory: dir, intensity: "bankrupt" });
expect(report.shouldRefuseBankrupt).toBe(true);
expect(report.blocking.some((b) => b.gate === "wasm-xor-mask-sidecar")).toBe(
true,
);
const blocks = evaluateHardenProjectPackagingBlocks({
directory: dir,
intensity: "bankrupt",
});
expect(blocks.blockingWasmXorMask.length).toBeGreaterThan(0);
});
it("allow_wasm_xor_mask_sidecar clears project-level refuse", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-pg-allow-"));
writeFileSync(join(dir, "core.wasm"), buildTestWasmWithXorMaskSidecar());
const blocks = evaluateHardenProjectPackagingBlocks({
directory: dir,
intensity: "bankrupt",
allowWasmXorMaskSidecar: true,
});
expect(blocks.blockingWasmXorMask).toEqual([]);
});
it("surfaces lane-independence when includeProtectTimeGates", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-pg-lane-"));
mkdirSync(dir, { recursive: true });
writeFileSync(
join(dir, "gate.js"),
`
const lanes = [0x41, 0x42, 0x43, 0x44, 0x45];
function check(key) {
return key.split("").every((ch, i) => ch.charCodeAt(0) === lanes[i]);
}
module.exports = { check };
`,
);
const report = scanPackagingGates({
directory: dir,
intensity: "bankrupt",
includeProtectTimeGates: true,
});
expect(report.findings.some((f) => f.gate === "lane-independence")).toBe(true);
expect(report.shouldRefuseBankrupt).toBe(true);
});
});
+84
View File
@@ -0,0 +1,84 @@
import { describe, expect, it } from "vitest";
import {
lintPanelDeriveAbiSource,
rewriteStablePanelDeriveSymbols,
panelDeriveSeedRoot,
panelDeriveReplacementName,
intensityRewritesPanelDerive,
PANEL_DERIVE_ABI_SCHEMA,
} from "../src/engine/panel-derive-abi-lint.js";
describe("panel-derive ABI lint/rewrite (red-blue round-3)", () => {
it("flags __vaultPanelDerive_r3 as error and FNV primes as warning", () => {
const src = `
const FNV = 0x811c9dc5;
globalThis.__vaultPanelDerive_r3 = (s) => s;
export function use(sb) { return sb.__vaultPanelDerive_r3("x"); }
`;
const report = lintPanelDeriveAbiSource(src, { path: "panel.html" });
expect(report.schema).toBe(PANEL_DERIVE_ABI_SCHEMA);
expect(report.shouldRewriteOrRefuse).toBe(true);
expect(report.stableSymbols).toContain("__vaultPanelDerive_r3");
expect(report.findings.some((f) => f.id === "stable-panel-derive-global")).toBe(true);
expect(report.findings.some((f) => f.id === "classic-fnv-prime-literal")).toBe(true);
expect(intensityRewritesPanelDerive("bankrupt")).toBe(true);
expect(intensityRewritesPanelDerive("stealth")).toBe(false);
});
it("rewrites JS and HTML-script seeds to the same replacement", () => {
const original = "__vaultPanelDerive_r3";
const body = `globalThis.${original} = derive; return sandbox.${original};`;
const a = rewriteStablePanelDeriveSymbols(body, "proj-seed-1");
const b = rewriteStablePanelDeriveSymbols(body, "proj-seed-1:html-script-0");
expect(a.rewrote).toBe(true);
expect(b.rewrote).toBe(true);
expect(a.renames[0]!.to).toBe(b.renames[0]!.to);
expect(a.code).not.toContain(original);
expect(a.code).toContain(a.renames[0]!.to);
expect(panelDeriveSeedRoot("proj-seed-1:html-script-0")).toBe("proj-seed-1");
expect(panelDeriveReplacementName("proj-seed-1", original)).toMatch(/^_blaPd_[0-9a-f]{10}$/);
});
it("leaves clean source unchanged", () => {
const src = `export function derivePanelToken(x) { return x; }\n`;
const report = lintPanelDeriveAbiSource(src);
expect(report.looksExposed).toBe(false);
const rw = rewriteStablePanelDeriveSymbols(src, "seed");
expect(rw.rewrote).toBe(false);
expect(rw.code).toBe(src);
});
});
describe("panel offline oracle (red-blue round-4)", () => {
it("flags deriveLocal + panelTokenSha256 as refuse oracle", () => {
const src = `
function deriveLocal(key) { return String(key); }
const expected = seal.panelTokenSha256;
if (sha256(deriveLocal(k)) !== expected) deny();
`;
const report = lintPanelDeriveAbiSource(src, { path: "panel.html" });
expect(report.shouldRefuseBankrupt).toBe(true);
expect(report.localDeriveSymbols).toContain("deriveLocal");
expect(report.findings.some((f) => f.id === "panel-token-sha-oracle")).toBe(true);
expect(report.findings.some((f) => f.id === "stable-local-derive")).toBe(true);
});
it("rewrites deriveLocal to seed-stable _blaPdLocal_*", () => {
const body = `function deriveLocal(k) { return k; }\nconsole.log(deriveLocal("x"));\n`;
const rw = rewriteStablePanelDeriveSymbols(body, "r4-panel-seed");
expect(rw.rewrote).toBe(true);
expect(rw.code).not.toContain("function deriveLocal");
expect(rw.renames.some((r) => r.from === "deriveLocal" && r.to.startsWith("_blaPdLocal_"))).toBe(
true,
);
});
it("warns on panelTokenSha256 alone without refuse", () => {
const src = `const digest = seal.panelTokenSha256;\n`;
const report = lintPanelDeriveAbiSource(src);
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.findings.some((f) => f.id === "panel-token-sha-oracle" && f.severity === "warning")).toBe(
true,
);
});
});
+57
View File
@@ -0,0 +1,57 @@
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 { protectTarget } from "../src/engine/protector.js";
import { rewriteStablePanelDeriveSymbols } from "../src/engine/panel-derive-abi-lint.js";
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
describe("red-blue round-4 panel oracle gate", () => {
it("bankrupt protect refuses deriveLocal + panelTokenSha256 unless allowed", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-panel-oracle-"));
dirs.push(dir);
const input = join(dir, "panel.js");
const output = join(dir, "panel.out.js");
writeFileSync(
input,
[
"function deriveLocal(key) { return String(key).length.toString(16); }",
"function check(seal, key) {",
" return deriveLocal(key) === seal.panelTokenSha256;",
"}",
"module.exports = { deriveLocal, check };",
"",
].join("\n"),
"utf8",
);
expect(() =>
protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r4-oracle",
honeySourceMaps: false,
}),
).toThrow(/allowPanelOfflineOracle|panel offline oracle/);
const ok = protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r4-oracle",
honeySourceMaps: false,
allowPanelOfflineOracle: true,
});
expect(ok.detectedFormat).toBe("javascript");
const out = require("node:fs").readFileSync(ok.outputPath, "utf8");
expect(out).not.toMatch(/\bfunction\s+deriveLocal\b/);
const expected = rewriteStablePanelDeriveSymbols(
"function deriveLocal(key) { return key; }",
"r4-oracle",
).renames.find((r) => r.from === "deriveLocal")!.to;
expect(out).toContain(expected);
});
});
+150
View File
@@ -0,0 +1,150 @@
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 {
getRedteamReport,
reaCheckoutPresent,
reaDistReady,
resolveReaRoot,
runReaDriftCheck,
} from "../src/engine/rea-observability.js";
import { handleMcpRequest } from "../src/mcp/server.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("REA observability engine (C2)", () => {
it("runReaDriftCheck returns explicit unverified when REA is absent", () => {
const missing = join(tmpdir(), `no-rea-${Date.now()}-${Math.random()}`);
const report = runReaDriftCheck({ reaRoot: missing });
expect(report.status).toBe("unverified");
expect(report.notRedTeamEvidence).toBe(true);
expect(report.reason).toMatch(/not found/i);
expect(report.exitCode).toBeNull();
expect(reaCheckoutPresent(missing)).toBe(false);
});
it("getRedteamReport returns unverified when report missing and REA unready", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-rt-missing-"));
tempDirs.push(dir);
const reportPath = join(dir, "no-report.json");
const fakeRea = join(dir, "rea");
mkdirSync(fakeRea);
// No src/ → checkout absent; no dist → unready.
const result = getRedteamReport({
reaRoot: fakeRea,
reportPath,
execute: false,
});
expect(result.status).toBe("unverified");
expect(result.reason).toMatch(/No empirical report/);
expect(result.executed).toBe(false);
});
it("getRedteamReport reads a fixture report without needing REA", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-rt-fixture-"));
tempDirs.push(dir);
const reportPath = join(dir, "empirical.json");
const fixture = {
generatedAt: "test",
pairs: [{ format: "wasm", before: { status: "ok" }, after: { status: "ok" } }],
unverified: [],
};
writeFileSync(reportPath, JSON.stringify(fixture), "utf8");
const fakeRea = join(dir, "rea-absent");
const result = getRedteamReport({
reaRoot: fakeRea,
reportPath,
});
expect(result.status).toBe("available");
expect(result.report).toMatchObject(fixture);
expect(result.executed).toBe(false);
});
it("execute:true without REA dist is unverified (never silent pass)", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-rt-exec-"));
tempDirs.push(dir);
const fakeRea = join(dir, "rea");
mkdirSync(join(fakeRea, "src"), { recursive: true });
expect(reaDistReady(fakeRea)).toBe(false);
const result = getRedteamReport({
reaRoot: fakeRea,
execute: true,
reportPath: join(dir, "out.json"),
});
expect(result.status).toBe("unverified");
expect(result.reason).toMatch(/dist not ready/i);
expect(result.executed).toBe(false);
});
});
describe("REA observability MCP tools (C2)", () => {
it("bla_rea_drift surfaces unverified as isError when REA absent", async () => {
const missing = join(tmpdir(), `mcp-no-rea-${Date.now()}`);
const res = await call("bla_rea_drift", { rea_root: missing });
expect(res?.error).toBeUndefined();
const result = res!.result as {
isError: boolean;
structuredContent: { status: string; notRedTeamEvidence: boolean };
};
expect(result.isError).toBe(true);
expect(result.structuredContent.status).toBe("unverified");
expect(result.structuredContent.notRedTeamEvidence).toBe(true);
});
it("bla_redteam_report reads fixture; missing path is unverified isError", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-rt-mcp-"));
tempDirs.push(dir);
const reportPath = join(dir, "empirical.json");
writeFileSync(
reportPath,
JSON.stringify({ generatedAt: "fixture", pairs: [], unverified: ["demo"] }),
"utf8",
);
const ok = await call("bla_redteam_report", {
report_path: reportPath,
rea_root: join(dir, "no-rea"),
});
expect(ok?.error).toBeUndefined();
const okResult = ok!.result as {
isError?: boolean;
structuredContent: { status: string; report: { generatedAt: string } };
};
expect(okResult.isError).not.toBe(true);
expect(okResult.structuredContent.status).toBe("available");
expect(okResult.structuredContent.report.generatedAt).toBe("fixture");
const missing = await call("bla_redteam_report", {
report_path: join(dir, "absent.json"),
rea_root: join(dir, "no-rea"),
});
const missResult = missing!.result as {
isError: boolean;
structuredContent: { status: string };
};
expect(missResult.isError).toBe(true);
expect(missResult.structuredContent.status).toBe("unverified");
});
it("resolveReaRoot honors REA_ROOT override path shape", () => {
const custom = join(tmpdir(), "custom-rea-root");
expect(resolveReaRoot(custom)).toBe(custom);
});
});
+24
View File
@@ -152,3 +152,27 @@ describe("WASM interface exhaustion vs representation budget", () => {
);
});
});
describe("redteam:rea skip honesty", () => {
it("emits status unverified JSON when sibling REA dist is absent", async () => {
const { spawnSync } = await import("node:child_process");
const { mkdtempSync } = await import("node:fs");
const { tmpdir } = await import("node:os");
const emptyRea = mkdtempSync(join(tmpdir(), "bla-no-rea-"));
const r = spawnSync(process.execPath, ["scripts/redteam/run.mjs"], {
cwd: process.cwd(),
encoding: "utf8",
env: { ...process.env, REA_ROOT: emptyRea },
});
expect(r.status).toBe(0);
expect(r.stdout).toMatch(/SKIP: sibling REA dist not ready/);
const line = r.stdout
.split("\n")
.map((s) => s.trim())
.find((s) => s.startsWith("{") && s.includes("bla-redteam-rea"));
expect(line).toBeTruthy();
const payload = JSON.parse(line!);
expect(payload.schema).toBe("bla-redteam-rea/v1");
expect(payload.status).toBe("unverified");
});
});
+217
View File
@@ -0,0 +1,217 @@
import {
existsSync,
mkdtempSync,
mkdirSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
computeHardenRunId,
HARDEN_SUMMARY_FILE_NAME,
HARDEN_SUMMARY_SCHEMA,
readHardenRunSummary,
} from "../src/engine/run-evidence.js";
import { hardenProject } from "../src/engine/harden.js";
import { handleMcpRequest } from "../src/mcp/server.js";
const tempDirs: string[] = [];
afterEach(() => {
for (const d of tempDirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
const JS = `export function unlockPremium(token) { return token === "LIVE-KEY"; }\n`;
async function call(name: string, args: Record<string, unknown>) {
const res = await handleMcpRequest({
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name, arguments: args },
});
return res!;
}
describe("harden run evidence (C1)", () => {
it("computeHardenRunId is stable for identical planned work", () => {
const identity = {
blaVersion: "1.6.4",
directory: "/tmp/proj",
intensity: "bankrupt",
weaveDecoys: false,
selfSeal: false,
artifacts: [
{ relativePath: "b.js", format: "javascript", outputPath: "/out/b.js" },
{ relativePath: "a.js", format: "javascript", outputPath: "/out/a.js" },
],
};
const shuffled = {
...identity,
artifacts: [...identity.artifacts].reverse(),
};
expect(computeHardenRunId(identity)).toBe(computeHardenRunId(shuffled));
expect(computeHardenRunId(identity)).toMatch(/^bla-run-[0-9a-f]{24}$/);
});
it("hardenProject emits runId + unsigned summary; lookup round-trips", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-run-ev-"));
tempDirs.push(dir);
mkdirSync(join(dir, "dist"));
writeFileSync(join(dir, "dist", "app.js"), JS, "utf8");
const report = hardenProject({
directory: dir,
seed: "run-ev-1",
intensity: "stealth",
});
expect(report.runId).toMatch(/^bla-run-[0-9a-f]{24}$/);
expect(report.summaryPath).toBeDefined();
expect(existsSync(report.summaryPath!)).toBe(true);
const disk = JSON.parse(readFileSync(report.summaryPath!, "utf8")) as {
schema: string;
runId: string;
signature: string;
};
expect(disk.schema).toBe(HARDEN_SUMMARY_SCHEMA);
expect(disk.runId).toBe(report.runId);
expect(disk.signature).toBe("unsigned");
const byFile = readHardenRunSummary(report.summaryPath!, report.runId);
expect(byFile.runId).toBe(report.runId);
expect(byFile.runIdMatches).toBe(true);
const byDir = readHardenRunSummary(report.outputDirectory);
expect(byDir.runId).toBe(report.runId);
expect(byDir.summaryPath).toContain(HARDEN_SUMMARY_FILE_NAME);
// Dry-run still gets a runId (same planned work → same id) but no summary file.
const dry = hardenProject({
directory: dir,
seed: "run-ev-1",
intensity: "stealth",
dryRun: true,
});
expect(dry.runId).toBe(report.runId);
expect(dry.summaryPath).toBeUndefined();
});
it("readHardenRunSummary fails clearly on missing / bad id / pre-v2", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-run-bad-"));
tempDirs.push(dir);
expect(() => readHardenRunSummary(join(dir, "missing.json"))).toThrow(
/Run summary not found/,
);
const v1 = join(dir, "old.json");
writeFileSync(
v1,
JSON.stringify({
schema: "bla-harden-summary/v1",
directory: dir,
artifacts: [],
}),
"utf8",
);
expect(() => readHardenRunSummary(v1)).toThrow(/no runId/);
const v2 = join(dir, HARDEN_SUMMARY_FILE_NAME);
writeFileSync(
v2,
JSON.stringify({
schema: HARDEN_SUMMARY_SCHEMA,
runId: "bla-run-aaaaaaaaaaaaaaaaaaaaaaaa",
signature: "unsigned",
artifacts: [],
}),
"utf8",
);
expect(() =>
readHardenRunSummary(dir, "bla-run-bbbbbbbbbbbbbbbbbbbbbbbb"),
).toThrow(/Run id mismatch/);
});
it("MCP bla_run_lookup + bla_verify correlation; defend/protect carry runId", async () => {
const dir = mkdtempSync(join(tmpdir(), "bla-run-mcp-"));
tempDirs.push(dir);
mkdirSync(join(dir, "dist"));
const input = join(dir, "dist", "app.js");
writeFileSync(input, JS, "utf8");
const hardenRes = await call("bla_harden", {
directory: dir,
seed: "run-mcp-1",
intensity: "stealth",
confirm_overwrite: true,
});
expect(hardenRes.error).toBeUndefined();
const harden = (hardenRes.result as { structuredContent: Record<string, unknown> })
.structuredContent;
expect(harden.runId).toMatch(/^bla-run-[0-9a-f]{24}$/);
const summaryPath = harden.summaryPath as string;
expect(existsSync(summaryPath)).toBe(true);
const lookupOk = await call("bla_run_lookup", {
summary_path: harden.outputDirectory as string,
run_id: harden.runId as string,
});
expect(lookupOk.error).toBeUndefined();
expect((lookupOk.result as { isError?: boolean }).isError).not.toBe(true);
const looked = (lookupOk.result as { structuredContent: { runId: string } })
.structuredContent;
expect(looked.runId).toBe(harden.runId);
const lookupBad = await call("bla_run_lookup", {
summary_path: summaryPath,
run_id: "bla-run-000000000000000000000000",
});
expect((lookupBad.result as { isError: boolean }).isError).toBe(true);
const missing = await call("bla_run_lookup", {
summary_path: join(dir, "no-such-summary.json"),
});
expect((missing.result as { isError: boolean }).isError).toBe(true);
const out = join(dir, "protected.js");
const protectRes = await call("bla_protect", {
input_path: input,
output_path: out,
seed: "run-mcp-protect",
intensity: "stealth",
});
expect(protectRes.error).toBeUndefined();
expect((protectRes.result as { isError?: boolean }).isError).not.toBe(true);
const protectedPayload = (
protectRes.result as { structuredContent: Record<string, unknown> }
).structuredContent;
expect(protectedPayload.runId).toMatch(/^bla-run-[0-9a-f]{24}$/);
expect(protectedPayload.runEvidence).toMatchObject({
signature: "unsigned",
schema: "bla-artifact-run/v1",
});
const verifyRes = await call("bla_verify", {
target_path: out,
summary_path: summaryPath,
run_id: harden.runId as string,
});
expect(verifyRes.error).toBeUndefined();
expect((verifyRes.result as { isError?: boolean }).isError).not.toBe(true);
const verified = (
verifyRes.result as {
structuredContent: { runCorrelation: { runId: string; signature: string } };
}
).structuredContent;
expect(verified.runCorrelation.runId).toBe(harden.runId);
expect(verified.runCorrelation.signature).toBe("unsigned");
const verifyOrphanId = await call("bla_verify", {
target_path: out,
run_id: harden.runId as string,
});
expect((verifyOrphanId.result as { isError: boolean }).isError).toBe(true);
});
});
+19
View File
@@ -11,6 +11,7 @@ import { generateFridaCaptureSaturation } from "../src/shields/exhaustion/frida-
import { REA_BUDGET_BREAKER_MATRIX } from "../src/shields/exhaustion/rea-budget-matrix.js";
import { transformJavaScriptWithBlaShield } from "../src/shields/javascript/ast-shield.js";
import { emitCompileTimeNativeHeader } from "../src/shields/formats/headers.js";
import { lintLaneIndependence } from "../src/engine/lane-independence-lint.js";
describe("Counter-REA Runtime Memory Diff & Heap Churn Shield", () => {
it("Floods M0 -> M1 differential memory snapshots with > 35 synchronized decoy mutations on every function call", () => {
@@ -128,6 +129,24 @@ describe("Counter-REA Runtime Memory Diff & Heap Churn Shield", () => {
}
});
it("R9: shadow-heap decoy tables avoid lane-lint BYTE_COMPARE_ARRAY even beside key identifiers", () => {
const prng = new SeededPrng("r9-lane-quiet-decoy");
const shield = generateShadowHeapChurnShield(prng, "bankrupt");
// Must not emit [n, n, n, n+] numeric literals (R8 red residual → R9 blue).
expect(shield.code).not.toMatch(
/\[\s*(?:0x[0-9a-fA-F]+|\d+)\s*(?:,\s*(?:0x[0-9a-fA-F]+|\d+)\s*){3,}\]/,
);
expect(shield.code).toContain('splitShareA: "');
expect(shield.code).toContain(".split(\",\").map");
expect(shield.code).toContain(".concat([");
const report = lintLaneIndependence(
"// key guess input lane entitlement gate\n" + shield.code,
);
expect(report.looksLaneIndependent).toBe(false);
expect(report.findings).toEqual([]);
});
it("Triggers Frida capture saturation and realm-agnostic ring churn even when globalThis.Frida is isolated in Frida Gum", () => {
const prng = new SeededPrng("frida-realm-isolated");
const sat = generateFridaCaptureSaturation(prng, "bankrupt");
+117
View File
@@ -0,0 +1,117 @@
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 { hardenProject } from "../src/engine/harden.js";
import { protectTarget } from "../src/engine/protector.js";
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
const ROUND2_SEAL = {
schema: "bla-redblue-r2-seal/v1",
rounds: 28,
scheduleSalt: 1374179543,
revision: "7f325fec37206b637a224e9630b67c4a",
certificateCipherHex: "0cd3dfe5e342eb542a3666d6e706ede34c58416b00bb853921b9c82397ff716237",
};
const ONE_WAY_SEAL = {
schema: "bla-entitlement-seal/v1",
algorithm: "sha256",
revision: "b38091d4a394ded9012846e8d4b647083b260beb6ee5ad1e42265fe6f107c660",
};
const SAFE_JS = `
export function activate(key) {
let h = 2166136261;
for (let i = 0; i < key.length; i++) {
h ^= key.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return (h >>> 0).toString(16);
}
`;
describe("harden/protect seal-sidecar gate (red-blue round-2 P1)", () => {
it("bankrupt harden refuses reversible plaintext seal.json by default", () => {
const root = mkdtempSync(join(tmpdir(), "bla-seal-refuse-"));
dirs.push(root);
writeFileSync(join(root, "gate.js"), SAFE_JS, "utf8");
writeFileSync(join(root, "seal.json"), JSON.stringify(ROUND2_SEAL), "utf8");
const report = hardenProject({
directory: root,
intensity: "bankrupt",
seed: "seal-refuse",
outputDirectory: join(root, "out"),
});
expect(report.overallSuccess).toBe(false);
expect(
report.artifacts.some(
(a) => a.error && /allowPlaintextSeal|plaintext\/reversible seal|reversible/i.test(a.error),
),
).toBe(true);
});
it("bankrupt harden allows one-way sha256 seal.json", () => {
const root = mkdtempSync(join(tmpdir(), "bla-seal-ok-"));
dirs.push(root);
writeFileSync(join(root, "gate.js"), SAFE_JS, "utf8");
writeFileSync(join(root, "seal.json"), JSON.stringify(ONE_WAY_SEAL), "utf8");
const report = hardenProject({
directory: root,
intensity: "bankrupt",
seed: "seal-ok",
outputDirectory: join(root, "out"),
});
expect(report.overallSuccess).toBe(true);
expect(report.hardenedCount).toBeGreaterThanOrEqual(1);
});
it("allowPlaintextSeal overrides bankrupt refuse", () => {
const root = mkdtempSync(join(tmpdir(), "bla-seal-allow-"));
dirs.push(root);
writeFileSync(join(root, "gate.js"), SAFE_JS, "utf8");
writeFileSync(join(root, "seal.json"), JSON.stringify(ROUND2_SEAL), "utf8");
const report = hardenProject({
directory: root,
intensity: "bankrupt",
seed: "seal-allow",
outputDirectory: join(root, "out"),
allowPlaintextSeal: true,
});
expect(report.overallSuccess).toBe(true);
});
it("balanced intensity does not refuse (warning path only via lint)", () => {
const root = mkdtempSync(join(tmpdir(), "bla-seal-bal-"));
dirs.push(root);
writeFileSync(join(root, "gate.js"), SAFE_JS, "utf8");
writeFileSync(join(root, "seal.json"), JSON.stringify(ROUND2_SEAL), "utf8");
const report = hardenProject({
directory: root,
intensity: "balanced",
seed: "seal-bal",
outputDirectory: join(root, "out"),
});
expect(report.overallSuccess).toBe(true);
});
it("bankrupt protect refuses sibling seal.json", () => {
const root = mkdtempSync(join(tmpdir(), "bla-seal-prot-"));
dirs.push(root);
const src = join(root, "gate.js");
writeFileSync(src, SAFE_JS, "utf8");
writeFileSync(join(root, "seal.json"), JSON.stringify(ROUND2_SEAL), "utf8");
expect(() =>
protectTarget({
inputPath: src,
outputPath: join(root, "out.js"),
intensity: "bankrupt",
seed: "seal-prot",
}),
).toThrow(/allowPlaintextSeal|plaintext\/reversible seal/i);
});
});
+116
View File
@@ -0,0 +1,116 @@
import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
lintSealCommitmentSource,
lintSealCommitmentFile,
discoverAndLintSealSidecars,
findSiblingSealSidecars,
sealCommitmentRefuseMessage,
intensityEnforcesSealRefusal,
SEAL_COMMITMENT_SCHEMA,
} from "../src/engine/seal-commitment-lint.js";
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
/** Round-2 seal shape (reversible ARX + cipher package). */
const ROUND2_SEAL = {
schema: "bla-redblue-r2-seal/v1",
product: "round-2-product-chained-entitlement",
seed: "bla-redblue-r2-product-gate-2026-11",
rounds: 28,
scheduleSalt: 1374179543,
revision: "7f325fec37206b637a224e9630b67c4a",
panelToken: "f805ed0c2a763bc5",
certificateCipherHex:
"0cd3dfe5e342eb542a3666d6e706ede34c58416b00bb853921b9c82397ff716237",
certificateSha256:
"b38091d4a394ded9012846e8d4b647083b260beb6ee5ad1e42265fe6f107c660",
};
const ONE_WAY_SEAL = {
schema: "bla-entitlement-seal/v1",
algorithm: "sha256",
revision: "b38091d4a394ded9012846e8d4b647083b260beb6ee5ad1e42265fe6f107c660",
product: "ok-product",
};
describe("seal-commitment lint (red-blue round-2)", () => {
it("flags round-2 reversible ARX seal.json as error + refuse", () => {
const report = lintSealCommitmentSource(JSON.stringify(ROUND2_SEAL, null, 2), {
path: "/tmp/seal.json",
});
expect(report.schema).toBe(SEAL_COMMITMENT_SCHEMA);
expect(report.looksExposed).toBe(true);
expect(report.shouldRefuseBankrupt).toBe(true);
const ids = report.findings.map((f) => f.id);
expect(ids).toContain("reversible-public-commitment");
expect(ids).toContain("seal-offline-oracle-package");
expect(report.findings.every((f) => f.severity === "error" || f.id === "plaintext-seal-sidecar")).toBe(
true,
);
expect(report.findings.some((f) => f.severity === "error")).toBe(true);
});
it("passes one-way SHA-256 seal without invertible ARX params", () => {
const report = lintSealCommitmentSource(JSON.stringify(ONE_WAY_SEAL), {
path: "/tmp/seal.json",
});
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.findings.some((f) => f.id === "reversible-public-commitment")).toBe(false);
expect(report.findings.some((f) => f.id === "seal-offline-oracle-package")).toBe(false);
// Filename still yields a plaintext-sidecar warning (not refuse).
expect(report.findings.some((f) => f.id === "plaintext-seal-sidecar" && f.severity === "warning")).toBe(
true,
);
});
it("discovers seal.json under a project tree", () => {
const root = mkdtempSync(join(tmpdir(), "bla-seal-disc-"));
dirs.push(root);
mkdirSync(join(root, "dist"));
writeFileSync(join(root, "dist", "seal.json"), JSON.stringify(ROUND2_SEAL), "utf8");
writeFileSync(join(root, "dist", "app.js"), "export const x = 1;\n", "utf8");
const reports = discoverAndLintSealSidecars(root);
expect(reports.length).toBeGreaterThanOrEqual(1);
expect(reports.some((r) => r.shouldRefuseBankrupt)).toBe(true);
});
it("finds sibling seal next to a protect target", () => {
const root = mkdtempSync(join(tmpdir(), "bla-seal-sib-"));
dirs.push(root);
writeFileSync(join(root, "license.cjs"), "console.log(1)\n", "utf8");
writeFileSync(join(root, "app.seal.json"), JSON.stringify(ROUND2_SEAL), "utf8");
const sibs = findSiblingSealSidecars(root);
expect(sibs.some((p) => p.endsWith("app.seal.json"))).toBe(true);
const report = lintSealCommitmentFile(sibs[0]!);
expect(report.shouldRefuseBankrupt).toBe(true);
});
it("refuse message names the allow flag", () => {
const report = lintSealCommitmentSource(JSON.stringify(ROUND2_SEAL), {
path: "/tmp/seal.json",
});
expect(sealCommitmentRefuseMessage(report, "/tmp/seal.json")).toMatch(
/allowPlaintextSeal|allow-plaintext-seal/i,
);
expect(intensityEnforcesSealRefusal("bankrupt")).toBe(true);
expect(intensityEnforcesSealRefusal("balanced")).toBe(false);
});
it("lints the round-2 hardened seal fixture when present", () => {
const fixture = "/workspace/bla-redblue/round-2/hardened/seal.json";
try {
readFileSync(fixture, "utf8");
} catch {
return; // fixture absent on some runners — unit cases above still cover shape
}
const report = lintSealCommitmentFile(fixture);
expect(report.shouldRefuseBankrupt).toBe(true);
expect(report.findings.some((f) => f.id === "reversible-public-commitment")).toBe(true);
});
});
+101
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { spawnSync } from "node:child_process";
import { SeededPrng } from "../src/core/prng.js";
import {
generateSelfSealSnippet,
@@ -11,6 +12,7 @@ import {
import { transformJavaScriptWithBlaShield } from "../src/shields/javascript/ast-shield.js";
import { parseCliArgs } from "../src/cli.js";
import { DEFAULT_BLA_CONFIG, initBlaConfig, loadBlaConfig } from "../src/core/config.js";
import { protectTarget } from "../src/engine/protector.js";
describe("self-seal helper (#40.5)", () => {
it("DEFAULT_BLA_CONFIG exposes selfSeal:false (opt-in)", () => {
@@ -56,6 +58,48 @@ describe("self-seal helper (#40.5)", () => {
expect(c).not.toBe(a);
});
it("self-seal keeps opaque seed before top-level const uses (no TDZ)", () => {
// Bankrupt-style string splitting references seedVar in top-level consts.
// Self-seal used to push the seed decl to the program end → TDZ ReferenceError.
const src = [
'"use strict";',
'const HONEYPOT = Object.freeze(["P4#kR9$vM2@xL7!q", "W9$mK3#pT7!vQ2@z"]);',
'const LABEL = "bla-redblue-r4|wrap";',
'function main(k) { return HONEYPOT.includes(k) ? "hp" : LABEL + ":" + String(k).length; }',
'module.exports = { main, HONEYPOT };',
'if (require.main === module) console.log(main(process.argv[2] || ""));',
"",
].join("\n");
const on = transformJavaScriptWithBlaShield(src, {
intensity: "bankrupt",
seed: "self-seal-tdz-r4",
selfSeal: true,
});
expect(on.selfSealEnabled).toBe(true);
expect(on.selfSealBindingName).toBeTruthy();
// Seed const must appear before the first top-level Object.freeze / LABEL split use.
const seedDecl = on.code.match(/const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:\(\(\d+|\d+\s*\^)/);
expect(seedDecl).toBeTruthy();
const seedPos = on.code.indexOf(seedDecl![0]!);
const freezePos = on.code.indexOf("Object.freeze");
expect(seedPos).toBeGreaterThanOrEqual(0);
if (freezePos >= 0) {
expect(seedPos).toBeLessThan(freezePos);
}
const dir = mkdtempSync(join(tmpdir(), "bla-selfseal-tdz-"));
try {
const file = join(dir, "gate.cjs");
writeFileSync(file, on.code, "utf8");
const run = spawnSync(process.execPath, [file, "abc"], { encoding: "utf8" });
expect(run.status, run.stderr).toBe(0);
expect(run.stderr || "").not.toMatch(/before initialization/i);
expect(run.stdout).toMatch(/bla-redblue-r4\|wrap:3/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("AST shield injects self-seal only when opted in", () => {
const src = "export function pay(n) { return n * 2; }\n";
const off = transformJavaScriptWithBlaShield(src, {
@@ -132,3 +176,60 @@ describe("self-seal helper (#40.5)", () => {
}
});
});
it("embeds expected sibling SHA-256 and hard-fails on mismatch (round-4)", () => {
const prng = new SeededPrng("self-seal-hardfail-1");
const snip = generateSelfSealSnippet(prng, {
siblingPaths: ["./core.wasm"],
bindingName: "integrityDigestHf",
expectedSiblingSha256: {
"./core.wasm": "a".repeat(64),
},
hardFailOnSiblingMismatch: true,
});
expect(snip.expectedSiblingHashCount).toBe(1);
expect(snip.hardFailOnSiblingMismatch).toBe(true);
expect(snip.code).toContain("integrity check failed");
expect(snip.code).toContain("a".repeat(64));
});
it("protect+self-seal hard-fails when an on-disk sibling is tampered", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-selfseal-hf-"));
try {
const sib = join(dir, "core.wasm");
// Minimal wasm magic so file exists for hashing (content arbitrary).
writeFileSync(sib, Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0xaa]));
const src = [
'"use strict";',
"function main() { return 42; }",
"module.exports = { main };",
'if (require.main === module) console.log(main());',
"",
].join("\n");
const entry = join(dir, "gate.cjs");
writeFileSync(entry, src, "utf8");
const out = join(dir, "gate.out.cjs");
protectTarget({
inputPath: entry,
outputPath: out,
intensity: "balanced",
seed: "self-seal-hardfail-protect",
selfSeal: true,
selfSealSiblingPaths: ["core.wasm"],
});
const intact = spawnSync(process.execPath, [out], { encoding: "utf8" });
expect(intact.status, intact.stderr).toBe(0);
expect(intact.stdout.trim()).toBe("42");
writeFileSync(sib, Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0xbb]));
const tampered = spawnSync(process.execPath, [out], { encoding: "utf8" });
expect(tampered.status, tampered.stdout + tampered.stderr).not.toBe(0);
expect((tampered.stderr || "") + (tampered.stdout || "")).toMatch(
/integrity check failed/,
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
+92
View File
@@ -0,0 +1,92 @@
import { existsSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { runDoctor } from "../src/setup/doctor.js";
import {
readInstallManifest,
resolveBundledSkillBundle,
runSetup,
runUninstall,
} from "../src/setup/setup.js";
const tempDirs: string[] = [];
function makeHome(): string {
const dir = mkdtempSync(join(tmpdir(), "bla-skill-bundle-"));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const d of tempDirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
const MATRIX = "references/counter-rea-matrix.md";
function setupCursor(home: string): string {
runSetup({
homeDir: home,
clientIds: ["cursor"],
mcpCommand: process.execPath,
mcpArgs: [resolve(process.cwd(), "dist/cli.js"), "mcp"],
yes: true,
});
return join(home, ".cursor", "skills", "blind-llm-agents");
}
describe("skill bundle install integrity", () => {
it("bundles SKILL.md first plus every reference file", () => {
const bundle = resolveBundledSkillBundle();
expect(bundle[0]!.relativePath).toBe("SKILL.md");
expect(bundle.map((f) => f.relativePath)).toContain(MATRIX);
});
it("fresh setup installs references so SKILL.md relative links resolve", () => {
const home = makeHome();
const skillDir = setupCursor(home);
const skill = readFileSync(join(skillDir, "SKILL.md"), "utf8");
const links = [...skill.matchAll(/\]\((references\/[^)]+)\)/g)].map((m) => m[1]!);
expect(links.length).toBeGreaterThan(0);
for (const rel of links) expect(existsSync(join(skillDir, rel))).toBe(true);
const rec = readInstallManifest(home).clients.cursor!;
expect(Object.keys(rec.writtenSkillFiles ?? {})).toContain(MATRIX);
});
it("doctor fails on a missing reference and warns on a modified one", () => {
const home = makeHome();
const skillDir = setupCursor(home);
const ok = runDoctor({ homeDir: home, sqliteAvailableOverride: true });
const cursorOk = ok.agentClients.find((c) => c.id === "cursor")!;
expect(cursorOk.skillMissingFiles).toEqual([]);
expect(cursorOk.status).toBe("pass");
writeFileSync(join(skillDir, MATRIX), "tampered\n", "utf8");
const warn = runDoctor({ homeDir: home, sqliteAvailableOverride: true });
const cursorWarn = warn.agentClients.find((c) => c.id === "cursor")!;
expect(cursorWarn.skillModifiedFiles).toEqual([MATRIX]);
expect(cursorWarn.status).toBe("warn");
unlinkSync(join(skillDir, MATRIX));
const bad = runDoctor({ homeDir: home, sqliteAvailableOverride: true });
const cursorBad = bad.agentClients.find((c) => c.id === "cursor")!;
expect(cursorBad.skillMissingFiles).toEqual([MATRIX]);
expect(cursorBad.status).toBe("fail");
expect(bad.healthy).toBe(false);
expect(cursorBad.issues.join("\n")).toContain(MATRIX);
});
it("uninstall removes the whole owned bundle and the empty skill dir", () => {
const home = makeHome();
const skillDir = setupCursor(home);
runUninstall({ homeDir: home, clientIds: ["cursor"] });
expect(existsSync(join(skillDir, MATRIX))).toBe(false);
expect(existsSync(skillDir)).toBe(false);
});
it("uninstall preserves a user-modified reference", () => {
const home = makeHome();
const skillDir = setupCursor(home);
writeFileSync(join(skillDir, MATRIX), "my notes\n", "utf8");
runUninstall({ homeDir: home, clientIds: ["cursor"] });
expect(readFileSync(join(skillDir, MATRIX), "utf8")).toBe("my notes\n");
});
});
+42 -7
View File
@@ -2,29 +2,64 @@ import { describe, expect, it } from "vitest";
import * as fs from "node:fs";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import { resolveBundledSkillBundle } from "../src/setup/setup.js";
const skillPath = path.resolve(
const skillDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../.agents/skills/blind-llm-agents/SKILL.md",
"../.agents/skills/blind-llm-agents",
);
const skillPath = path.join(skillDir, "SKILL.md");
describe("blind-llm-agents skill guide contents", () => {
it("ships v1.3+ one-click harden guide with weave + forbidden surfaces", () => {
it("ships v1.5+/2.0 short decision guide with write-safety, lint-lanes, and run evidence", () => {
const text = fs.readFileSync(skillPath, "utf8");
expect(text).toMatch(/metadata:\s*\n\s*version:\s*"1\.3\.\d+"/);
expect(text).toMatch(/metadata:\s*\n\s*version:\s*"(?:1\.5\.\d+|2\.0\.\d+)"/);
expect(text).toContain("bla_harden");
expect(text).toContain("npx bla-agents@latest harden .");
expect(text).toContain("weave_decoys");
expect(text).toContain("bla_weave_plan");
expect(text).toContain("bla://directives/weave-decoy");
expect(text).toContain("bla-weave-decoy");
expect(text).toContain("bla_lint_lanes");
expect(text).toMatch(/FORBIDDEN/i);
expect(text).toMatch(/bla_defend/);
expect(text).toContain("counter-rea-matrix.md");
expect(text).toContain("weave-decoy-mcp.md");
// Prefer skill guide + existing MCP tools; refuse offensive RE/crack framing.
expect(text.toLowerCase()).toMatch(/refuse|defensive only/);
expect(text).toMatch(/Do not ask which files to protect/i);
expect(text).toContain("bla_discover");
expect(text).toContain("dry_run");
expect(text).toContain("confirm_overwrite");
expect(text).toContain("in_place");
expect(text).toContain("bla_run_lookup");
expect(text).toContain("bla_rea_drift");
expect(text).toContain("bla_redteam_report");
expect(text).toMatch(/unverified/i);
expect(text).toContain("available");
expect(text).toContain("overallSuccess");
// No brittle repo-relative ../../../docs links that break after setup install.
expect(text).not.toMatch(/\.\.\/\.\.\/\.\.\/docs\//);
});
it("bundles format appendices next to SKILL.md for setup/doctor", () => {
const required = [
"references/counter-rea-matrix.md",
"references/format-javascript.md",
"references/format-wasm.md",
"references/format-python.md",
"references/format-android.md",
];
for (const rel of required) {
expect(fs.existsSync(path.join(skillDir, rel)), rel).toBe(true);
}
const bundled = resolveBundledSkillBundle().map((f) => f.relativePath);
expect(bundled[0]).toBe("SKILL.md");
for (const rel of required) {
expect(bundled).toContain(rel);
}
const skill = fs.readFileSync(skillPath, "utf8");
expect(skill).toContain("format-javascript.md");
expect(skill).toContain("format-wasm.md");
expect(skill).toContain("format-python.md");
expect(skill).toContain("format-android.md");
});
it("parseCliArgs accepts --weave-decoys for harden/defend/protect parity with MCP", async () => {
+253 -17
View File
@@ -6,6 +6,7 @@ import {
parseWasmExportSectionPayload,
protectWasmBinary,
renameWasmExports,
shuffleWasmExportSectionPayload,
} from "../src/shields/formats/wasm.js";
/** Minimal WASM exporting compute_score(i32)->i32 = x*42+7 */
@@ -60,7 +61,7 @@ describe("WASM export rename / semantic preservation (#40.3)", () => {
expect(after.map((e) => e.name)).toContain(renames[0]!.to);
});
it("protectWasmBinary preserves public ABI by default; explicit rename rewrites non-preserved", () => {
it("balanced keeps public ABI; bankrupt renames non-preserved by default", () => {
const raw = fixtureComputeScore();
const balanced = protectWasmBinary(raw, {
intensity: "balanced",
@@ -70,37 +71,272 @@ describe("WASM export rename / semantic preservation (#40.3)", () => {
expect(inspectWasmBinary(balanced.buffer).exportNames).toContain("compute_score");
expect(WebAssembly.validate(new Uint8Array(balanced.buffer))).toBe(true);
const renamed = protectWasmBinary(raw, {
intensity: "balanced",
seed: "wasm-rename-force",
renameNonPublicExports: true,
renameInternalOnly: false,
preserveExports: [],
const bankrupt = protectWasmBinary(raw, {
intensity: "bankrupt",
seed: "wasm-rename-bankrupt-default",
});
expect(renamed.exportsRenamed.length).toBeGreaterThanOrEqual(1);
expect(renamed.exportsRenamed[0]!.from).toBe("compute_score");
const names = inspectWasmBinary(renamed.buffer).exportNames;
expect(bankrupt.exportsRenamed.length).toBeGreaterThanOrEqual(1);
expect(bankrupt.exportsRenamed[0]!.from).toBe("compute_score");
const names = inspectWasmBinary(bankrupt.buffer).exportNames;
expect(names).not.toContain("compute_score");
expect(names).toContain(renamed.exportsRenamed[0]!.to);
expect(WebAssembly.validate(new Uint8Array(renamed.buffer))).toBe(true);
expect(names).toContain(bankrupt.exportsRenamed[0]!.to);
expect(WebAssembly.validate(new Uint8Array(bankrupt.buffer))).toBe(true);
const mod = new WebAssembly.Module(new Uint8Array(renamed.buffer));
const mod = new WebAssembly.Module(new Uint8Array(bankrupt.buffer));
const inst = new WebAssembly.Instance(mod);
const fn = inst.exports[renamed.exportsRenamed[0]!.to] as (x: number) => number;
const fn = inst.exports[bankrupt.exportsRenamed[0]!.to] as (x: number) => number;
expect(fn(10)).toBe(427);
});
it("preserveExports keeps the named public ABI under forced rename", () => {
it("preserveExports keeps the named public ABI under bankrupt rename", () => {
const raw = fixtureComputeScore();
const res = protectWasmBinary(raw, {
intensity: "bankrupt",
seed: "wasm-rename-preserve",
renameNonPublicExports: true,
renameInternalOnly: false,
preserveExports: ["compute_score"],
});
expect(res.exportsRenamed).toHaveLength(0);
expect(inspectWasmBinary(res.buffer).exportNames).toContain("compute_score");
expect(WebAssembly.validate(new Uint8Array(res.buffer))).toBe(true);
});
it("renameInternalOnly:true keeps public names even at bankrupt", () => {
const raw = fixtureComputeScore();
const res = protectWasmBinary(raw, {
intensity: "bankrupt",
seed: "wasm-rename-internal-only",
renameInternalOnly: true,
});
expect(res.exportsRenamed).toHaveLength(0);
expect(inspectWasmBinary(res.buffer).exportNames).toContain("compute_score");
});
});
describe("WASM export decoy arity-2 hygiene (red/blue round-10)", () => {
/** Two arity-2 func exports (idx 0 junk, idx 1 unlock) + memory — decoys must not all alias 0. */
function fixtureTwoFuncs(): Buffer {
// types: (i32,i32)->i32 only; funcs type0+type0; mem; exports junk/unlock/memory
// junk returns 0; unlock returns a+b
return Buffer.from([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01,
0x7f, 0x03, 0x03, 0x02, 0x00, 0x00, 0x05, 0x03, 0x01, 0x00, 0x01, 0x07, 0x1a, 0x03, 0x04, 0x6a,
0x75, 0x6e, 0x6b, 0x00, 0x00, 0x06, 0x75, 0x6e, 0x6c, 0x6f, 0x63, 0x6b, 0x00, 0x01, 0x06, 0x6d,
0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0a, 0x0e, 0x02, 0x04, 0x00, 0x41, 0x00, 0x0b, 0x07,
0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b,
]);
}
it("bankrupt decoy aliases spread across exported function indices", () => {
const raw = fixtureTwoFuncs();
expect(WebAssembly.validate(new Uint8Array(raw))).toBe(true);
const res = protectWasmBinary(raw, {
intensity: "bankrupt",
seed: "r10-arity2-hygiene-spread",
// keep names so we can map decoy→index via parse of protected export section
preserveExports: ["junk", "unlock", "memory"],
});
expect(res.exportDecoysInjected).toBe(250);
expect(WebAssembly.validate(new Uint8Array(res.buffer))).toBe(true);
// Locate export section payload and count decoy aliases per func index.
const bytes = res.buffer;
let offset = 8;
let decoyIdx0 = 0;
let decoyIdx1 = 0;
while (offset < bytes.length) {
const sectionId = bytes[offset++]!;
let size = 0;
let shift = 0;
while (true) {
const b = bytes[offset++]!;
size |= (b & 0x7f) << shift;
if ((b & 0x80) === 0) break;
shift += 7;
}
const sectionEnd = offset + size;
if (sectionId === 7) {
const payload = bytes.subarray(offset, sectionEnd);
const entries = parseWasmExportSectionPayload(payload);
for (const e of entries) {
if (e.kind !== 0) continue;
if (!e.name.startsWith("enclave_export_")) continue;
if (e.index === 0) decoyIdx0++;
else if (e.index === 1) decoyIdx1++;
}
break;
}
offset = sectionEnd;
}
expect(decoyIdx0 + decoyIdx1).toBe(250);
// Hygiene: both indices get a non-trivial share (not 250/0 pile-on).
expect(decoyIdx0).toBeGreaterThan(40);
expect(decoyIdx1).toBeGreaterThan(40);
});
});
describe("WASM export-order shuffle (red/blue round-11)", () => {
/** unlock (idx1) exported FIRST among funcs, then junk (idx0), then memory. */
function fixtureUnlockFirst(): Buffer {
// Both funcs arity-2 (R12 prefer-arity-2); unlock exported first (R10 footgun).
// junk returns 0; unlock returns a+b
return Buffer.from([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01,
0x7f, 0x03, 0x03, 0x02, 0x00, 0x00, 0x05, 0x03, 0x01, 0x00, 0x01, 0x07, 0x1a, 0x03, 0x06, 0x75,
0x6e, 0x6c, 0x6f, 0x63, 0x6b, 0x00, 0x01, 0x04, 0x6a, 0x75, 0x6e, 0x6b, 0x00, 0x00, 0x06, 0x6d,
0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0a, 0x0e, 0x02, 0x04, 0x00, 0x41, 0x00, 0x0b, 0x07,
0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b,
]);
}
function firstFuncExportIndex(bytes: Buffer): number | null {
let offset = 8;
while (offset < bytes.length) {
const sectionId = bytes[offset++]!;
let size = 0;
let shift = 0;
while (true) {
const b = bytes[offset++]!;
size |= (b & 0x7f) << shift;
if ((b & 0x80) === 0) break;
shift += 7;
}
const sectionEnd = offset + size;
if (sectionId === 7) {
const entries = parseWasmExportSectionPayload(bytes.subarray(offset, sectionEnd));
for (const e of entries) {
if (e.kind === 0) return e.index;
}
return null;
}
offset = sectionEnd;
}
return null;
}
it("shuffleWasmExportSectionPayload permutes entry order without changing set", () => {
const keep = Buffer.from("a", "utf8");
const dbg = Buffer.from("b", "utf8");
const encodeName = (b: Buffer) => Buffer.concat([Buffer.from([b.length]), b]);
const payload = Buffer.concat([
Buffer.from([0x02]),
encodeName(keep),
Buffer.from([0x00, 0x00]),
encodeName(dbg),
Buffer.from([0x00, 0x01]),
]);
const before = parseWasmExportSectionPayload(payload);
let changed = false;
for (const seed of ["r11-u0", "r11-u1", "r11-u2", "r11-u3", "r11-u4", "r11-u5", "r11-u6", "r11-u7"]) {
const out = shuffleWasmExportSectionPayload(payload, new SeededPrng(seed));
const after = parseWasmExportSectionPayload(out);
expect(after).toHaveLength(2);
expect(new Set(after.map((e) => e.name))).toEqual(new Set(before.map((e) => e.name)));
if (after.map((e) => e.name).join(",") !== before.map((e) => e.name).join(",")) changed = true;
}
expect(changed).toBe(true);
});
it("bankrupt protect shuffles export order so first func ≠ cleartext-first unlock", () => {
const raw = fixtureUnlockFirst();
expect(WebAssembly.validate(new Uint8Array(raw))).toBe(true);
expect(firstFuncExportIndex(raw)).toBe(1); // unlock idx1 first in cleartext
// Across several seeds, first func export index after protect must not
// *always* remain unlock (idx 1). At least one seed yields a different first.
const firsts = new Set<number>();
for (const seed of [
"r11-export-shuffle-a",
"r11-export-shuffle-b",
"r11-export-shuffle-c",
"r11-export-shuffle-d",
"r11-export-shuffle-e",
"r11-export-shuffle-f",
"r11-export-shuffle-g",
"r11-export-shuffle-h",
]) {
const res = protectWasmBinary(raw, {
intensity: "bankrupt",
seed,
preserveExports: ["unlock", "junk", "memory"],
});
expect(res.exportsOrderShuffled).toBe(true);
expect(WebAssembly.validate(new Uint8Array(res.buffer))).toBe(true);
const idx = firstFuncExportIndex(res.buffer);
expect(idx === 0 || idx === 1).toBe(true);
firsts.add(idx!);
}
expect(firsts.has(0)).toBe(true); // at least one seed puts junk/decoy-of-junk first
expect(firsts.size).toBeGreaterThan(1);
});
});
describe("WASM alias budget prefers arity-2 (red/blue round-12)", () => {
/** arity-1 seal (idx0) + arity-2 junk (idx1) + arity-2 unlock (idx2) + memory */
function fixtureArityMix(): Buffer {
// types: (i32)->i32, (i32,i32)->i32
// funcs: seal=type0, junk=type1, unlock=type1
// code: seal returns 0; junk returns 0; unlock returns a+b
return Buffer.from([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
0x01, 0x0c, 0x02, 0x60, 0x01, 0x7f, 0x01, 0x7f, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f,
0x03, 0x04, 0x03, 0x00, 0x01, 0x01,
0x05, 0x03, 0x01, 0x00, 0x01,
0x07, 0x21, 0x04,
0x04, 0x73, 0x65, 0x61, 0x6c, 0x00, 0x00,
0x04, 0x6a, 0x75, 0x6e, 0x6b, 0x00, 0x01,
0x06, 0x75, 0x6e, 0x6c, 0x6f, 0x63, 0x6b, 0x00, 0x02,
0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00,
0x0a, 0x13, 0x03,
0x04, 0x00, 0x41, 0x00, 0x0b,
0x04, 0x00, 0x41, 0x00, 0x0b,
0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b,
]);
}
it("bankrupt decoy aliases skip arity-1 when arity-2 exports exist", () => {
const raw = fixtureArityMix();
expect(WebAssembly.validate(new Uint8Array(raw))).toBe(true);
const res = protectWasmBinary(raw, {
intensity: "bankrupt",
seed: "r12-arity1-budget-tighten",
preserveExports: ["seal", "junk", "unlock", "memory"],
});
expect(res.exportDecoysInjected).toBe(250);
expect(WebAssembly.validate(new Uint8Array(res.buffer))).toBe(true);
const bytes = res.buffer;
let offset = 8;
let decoySeal = 0;
let decoyJunk = 0;
let decoyUnlock = 0;
while (offset < bytes.length) {
const sectionId = bytes[offset++]!;
let size = 0;
let shift = 0;
while (true) {
const b = bytes[offset++]!;
size |= (b & 0x7f) << shift;
if ((b & 0x80) === 0) break;
shift += 7;
}
const sectionEnd = offset + size;
if (sectionId === 7) {
const entries = parseWasmExportSectionPayload(bytes.subarray(offset, sectionEnd));
for (const e of entries) {
if (e.kind !== 0) continue;
if (!e.name.startsWith("enclave_export_")) continue;
if (e.index === 0) decoySeal++;
else if (e.index === 1) decoyJunk++;
else if (e.index === 2) decoyUnlock++;
}
break;
}
offset = sectionEnd;
}
expect(decoySeal + decoyJunk + decoyUnlock).toBe(250);
// Round-12: arity-1 seal must not receive alias budget when arity-2 exist.
expect(decoySeal).toBe(0);
expect(decoyJunk).toBeGreaterThan(40);
expect(decoyUnlock).toBeGreaterThan(40);
});
});
+78
View File
@@ -0,0 +1,78 @@
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
lintWasmParamCarrierBuffer,
lintWasmParamCarrierFile,
discoverAndLintWasmParamCarriers,
buildTestWasmWithParamCarrier,
wasmParamCarrierRefuseMessage,
intensityEnforcesWasmParamRefusal,
WASM_PARAM_CARRIER_SCHEMA,
} from "../src/engine/wasm-param-carrier-lint.js";
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
describe("wasm-param-carrier lint (red-blue round-3)", () => {
it("flags R3PARM/R3CIPH clear carrier layout as error + refuse", () => {
const buf = buildTestWasmWithParamCarrier({});
const report = lintWasmParamCarrierBuffer(buf, { path: "/tmp/core.wasm" });
expect(report.schema).toBe(WASM_PARAM_CARRIER_SCHEMA);
expect(report.looksExposed).toBe(true);
expect(report.shouldRefuseBankrupt).toBe(true);
const ids = report.findings.map((f) => f.id);
expect(ids).toContain("clear-wasm-param-magic");
expect(ids).toContain("clear-wasm-cipher-carrier");
expect(report.findings.some((f) => f.magic === "R3PARM")).toBe(true);
expect(report.findings.some((f) => f.magic === "R3CIPH")).toBe(true);
expect(intensityEnforcesWasmParamRefusal("bankrupt")).toBe(true);
expect(intensityEnforcesWasmParamRefusal("balanced")).toBe(false);
expect(wasmParamCarrierRefuseMessage(report, "/tmp/core.wasm")).toMatch(
/allowWasmClearParamCarriers/,
);
});
it("does not flag a minimal clean WASM module", () => {
const clean = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
const report = lintWasmParamCarrierBuffer(clean);
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.findings).toHaveLength(0);
});
it("does not flag English prose containing SEAL as a substring", () => {
const header = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
const prose = Buffer.from("under SEAL of approval for PARM farm sales", "utf8");
const report = lintWasmParamCarrierBuffer(Buffer.concat([header, prose]));
expect(report.findings).toHaveLength(0);
});
it("discovers .wasm under a tree and lints the round-3-shaped carrier", () => {
const root = mkdtempSync(join(tmpdir(), "bla-wasm-parm-"));
dirs.push(root);
mkdirSync(join(root, "dist"));
writeFileSync(join(root, "dist", "core.wasm"), buildTestWasmWithParamCarrier({}));
writeFileSync(join(root, "dist", "app.js"), "export const x = 1;\n", "utf8");
const reports = discoverAndLintWasmParamCarriers(root);
expect(reports.length).toBeGreaterThanOrEqual(1);
expect(reports.some((r) => r.shouldRefuseBankrupt)).toBe(true);
const fileReport = lintWasmParamCarrierFile(join(root, "dist", "core.wasm"));
expect(fileReport.shouldRefuseBankrupt).toBe(true);
});
it("flags the round-3 hardened fixture when present", () => {
const fixture = "/workspace/bla-redblue/round-3/hardened/core.wasm";
try {
const report = lintWasmParamCarrierFile(fixture);
expect(report.shouldRefuseBankrupt).toBe(true);
expect(report.findings.some((f) => f.magic === "R3PARM")).toBe(true);
} catch (err) {
// Fixture may be absent in CI clones — skip rather than fail the gate.
if (err instanceof Error && /not found/.test(err.message)) return;
throw err;
}
});
});
+117
View File
@@ -0,0 +1,117 @@
import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readFileSync } 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 { buildTestWasmWithParamCarrier } from "../src/engine/wasm-param-carrier-lint.js";
import { rewriteStablePanelDeriveSymbols } from "../src/engine/panel-derive-abi-lint.js";
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
describe("red-blue round-3 residual gates", () => {
it("bankrupt protect refuses clear WASM param carriers unless allowed", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-wasm-gate-"));
dirs.push(dir);
const input = join(dir, "core.wasm");
const output = join(dir, "core.out.wasm");
writeFileSync(input, buildTestWasmWithParamCarrier({}));
expect(() =>
protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r3-wasm-gate",
}),
).toThrow(/allowWasmClearParamCarriers|clear WASM param/);
const ok = protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r3-wasm-gate",
allowWasmClearParamCarriers: true,
});
expect(ok.detectedFormat).toBe("wasm");
});
it("bankrupt harden refuses project trees with clear WASM carriers", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-wasm-harden-"));
dirs.push(dir);
mkdirSync(join(dir, "dist"));
writeFileSync(join(dir, "dist", "core.wasm"), buildTestWasmWithParamCarrier({}));
writeFileSync(join(dir, "dist", "app.js"), "export const ok = 1;\n", "utf8");
const report = hardenProject({
directory: dir,
intensity: "bankrupt",
seed: "r3-harden-wasm",
dryRun: true,
});
expect(report.overallSuccess).toBe(false);
expect(report.artifacts.some((a) => /clear WASM param/i.test(a.error ?? ""))).toBe(true);
});
it("bankrupt protect rewrites stable panel derive ABI across JS seed roots", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-panel-rw-"));
dirs.push(dir);
const input = join(dir, "panel.js");
const output = join(dir, "panel.out.js");
writeFileSync(
input,
`globalThis.__vaultPanelDerive_r3 = (x) => x;\nexport const poke = (sb) => sb.__vaultPanelDerive_r3(1);\n`,
"utf8",
);
const res = protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r3-panel-seed",
honeySourceMaps: false,
});
const out = readFileSync(res.outputPath, "utf8");
expect(out).not.toContain("__vaultPanelDerive_r3");
const expected = rewriteStablePanelDeriveSymbols(
`globalThis.__vaultPanelDerive_r3 = (x) => x;`,
"r3-panel-seed",
).renames[0]!.to;
expect(out).toContain(expected);
});
it("harden recommends self_seal for multi-artifact trees without enabling it", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-selfseal-rec-"));
dirs.push(dir);
mkdirSync(join(dir, "dist"));
// Clean minimal wasm (no param magic) + two JS files
writeFileSync(
join(dir, "dist", "core.wasm"),
Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]),
);
writeFileSync(join(dir, "dist", "a.js"), "export const a = 1;\n", "utf8");
writeFileSync(join(dir, "dist", "b.js"), "export const b = 2;\n", "utf8");
const report = hardenProject({
directory: dir,
intensity: "bankrupt",
seed: "r3-selfseal-rec",
dryRun: true,
});
expect(report.selfSeal).toBe(false);
expect(report.selfSealRecommended).toBe(true);
expect(report.selfSealRecommendation).toMatch(/self_seal/);
});
it("single-file harden does not recommend self_seal", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-selfseal-single-"));
dirs.push(dir);
mkdirSync(join(dir, "dist"));
writeFileSync(join(dir, "dist", "only.js"), "export const a = 1;\n", "utf8");
const report = hardenProject({
directory: dir,
intensity: "bankrupt",
seed: "r3-selfseal-single",
dryRun: true,
});
expect(report.selfSealRecommended).toBe(false);
});
});
@@ -118,4 +118,19 @@ describe("wasmPreserveExports .blarc / CLI / protect parity (#40.3)", () => {
(inst.exports as { add: (a: number, b: number) => number }).add(2, 3),
).toBe(5);
});
it("bankrupt without preserveExports renames public ABI names", () => {
const raw = minimalTwoExportWasm();
const res = protectWasmBinary(raw, {
intensity: "bankrupt",
seed: "wasm-no-preserve-renames-public",
});
const fromNames = res.exportsRenamed.map((r) => r.from);
expect(fromNames).toContain("add");
expect(fromNames).toContain("__bla_internal_x");
const mod = new WebAssembly.Module(new Uint8Array(res.buffer));
const inst = new WebAssembly.Instance(mod);
expect(Object.keys(inst.exports)).not.toContain("add");
expect(Object.keys(inst.exports)).not.toContain("__bla_internal_x");
});
});
@@ -0,0 +1,60 @@
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 { buildTestWasmWithSealXorKnownPlaintext } from "../src/engine/wasm-seal-xor-known-plaintext-lint.js";
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
describe("red-blue round-7 WASM seal.revision XOR known-plaintext gate", () => {
it("bankrupt protect refuses seal.revision known-plaintext unless allowed", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-sealxor-gate-"));
dirs.push(dir);
const { wasm, seal } = buildTestWasmWithSealXorKnownPlaintext({});
const input = join(dir, "core.wasm");
const output = join(dir, "core.out.wasm");
writeFileSync(input, wasm);
writeFileSync(join(dir, "seal.json"), JSON.stringify(seal, null, 2));
expect(() =>
protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r7-sealxor-gate",
}),
).toThrow(/allowWasmSealXorKnownPlaintext|seal\.revision XOR known-plaintext/i);
const ok = protectTarget({
inputPath: input,
outputPath: output,
intensity: "bankrupt",
seed: "r7-sealxor-gate",
allowWasmSealXorKnownPlaintext: true,
});
expect(ok.detectedFormat).toBe("wasm");
});
it("bankrupt harden refuses project trees with seal.revision known-plaintext WASM", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-sealxor-harden-"));
dirs.push(dir);
mkdirSync(join(dir, "dist"));
const { wasm, seal } = buildTestWasmWithSealXorKnownPlaintext({});
writeFileSync(join(dir, "dist", "core.wasm"), wasm);
writeFileSync(join(dir, "dist", "seal.json"), JSON.stringify(seal, null, 2));
writeFileSync(join(dir, "dist", "app.js"), "export const ok = 1;\n", "utf8");
const report = hardenProject({
directory: dir,
intensity: "bankrupt",
seed: "r7-harden-sealxor",
dryRun: true,
});
expect(report.overallSuccess).toBe(false);
expect(
report.artifacts.some((a) => /seal\.revision XOR known-plaintext|allowWasmSealXorKnownPlaintext/i.test(a.error ?? "")),
).toBe(true);
});
});
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import {
buildTestWasmWithSealXorKnownPlaintext,
lintWasmSealXorKnownPlaintextBuffer,
looksLikeSealRevisionKnownPlaintextPack,
} from "../src/engine/wasm-seal-xor-known-plaintext-lint.js";
describe("wasm-seal-xor-known-plaintext-lint", () => {
it("flags fixture where seal.revision is XOR known-plaintext in pack", () => {
const { wasm, seal, commit } = buildTestWasmWithSealXorKnownPlaintext({});
const report = lintWasmSealXorKnownPlaintextBuffer(wasm, {
path: "fixture.wasm",
sealRaw: JSON.stringify(seal),
sealPath: "seal.json",
});
expect(report.shouldRefuseBankrupt).toBe(true);
expect(report.looksExposed).toBe(true);
expect(report.findings.some((f) => f.id === "wasm-seal-revision-mask-oracle")).toBe(true);
expect(commit.length).toBe(32);
});
it("does not refuse when embedded commit mismatches seal.revision", () => {
const { wasm, seal } = buildTestWasmWithSealXorKnownPlaintext({ mismatchCommit: true });
const report = lintWasmSealXorKnownPlaintextBuffer(wasm, {
path: "mismatch.wasm",
sealRaw: JSON.stringify(seal),
});
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.findings).toHaveLength(0);
});
it("looksLike helper rejects empty buffer", () => {
expect(looksLikeSealRevisionKnownPlaintextPack(Buffer.alloc(10), Buffer.alloc(32)).ok).toBe(false);
});
it("round-8 entropy pad under XOR (commit elsewhere) does not refuse", () => {
// Product pattern: masked prefix holds entropy ≠ seal.revision; commitment is not under XOR.
const { wasm, seal } = buildTestWasmWithSealXorKnownPlaintext({ mismatchCommit: true });
const report = lintWasmSealXorKnownPlaintextBuffer(wasm, {
path: "r8-style.wasm",
sealRaw: JSON.stringify(seal),
});
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.findings).toHaveLength(0);
});
});
+54
View File
@@ -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);
});
});
+41
View File
@@ -0,0 +1,41 @@
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({});
const report = lintWasmXorMaskSidecarBuffer(wasm);
expect(report.findings[0]?.blobLen).toBeGreaterThanOrEqual(40);
expect(looksLikeXorMaskedEntitlementPack(Buffer.alloc(100)).ok).toBe(false);
});
it("does not refuse masked entitlement pack without adjacent plaintext mask (r7 key-dep style)", () => {
const wasm = buildTestWasmWithXorMaskSidecar({ omitMaskSidecar: true });
const report = lintWasmXorMaskSidecarBuffer(wasm, { path: "keydep.wasm" });
expect(report.shouldRefuseBankrupt).toBe(false);
expect(report.findings).toHaveLength(0);
});
});
+21 -1
View File
@@ -50,12 +50,32 @@
"selfSeal": {
"type": "boolean",
"default": false,
"description": "Opt-in self-seal / sibling-module integrity binding for JS/Node targets (issue #40.5). Parity with CLI --self-seal / MCP self_seal."
"description": "Opt-in self-seal / sibling-module integrity binding for JS/Node targets (issue #40.5). Parity with CLI --self-seal / MCP self_seal. For multi-artifact trees, bankrupt harden recommends this (selfSealRecommended) but never auto-enables for single-file projects."
},
"wasmPreserveExports": {
"type": "array",
"items": { "type": "string" },
"description": "WASM export names that must remain the public ABI when export rename runs at maximum/bankrupt (issue #40.3)."
},
"allowWasmClearParamCarriers": {
"type": "boolean",
"default": false,
"description": "Allow bankrupt harden despite clear WASM param/cipher ASCII carriers (R3PARM/R3CIPH/R2SEAL-class; red-blue round-3). Default false."
},
"allowStablePanelDeriveAbi": {
"type": "boolean",
"default": false,
"description": "Keep stable __vaultPanelDerive_* ABI (skip rewrite). Default false — maximum/bankrupt rewrite to _blaPd_* (red-blue round-3)."
},
"allowPlaintextSeal": {
"type": "boolean",
"default": false,
"description": "Allow bankrupt harden despite plaintext/reversible seal sidecars (red-blue round-2). Default false."
},
"allowLaneIndependentGates": {
"type": "boolean",
"default": false,
"description": "Allow harden/defend of lane-independent JS gates (issue #40.1). Default false."
}
},
"additionalProperties": true