diff --git a/CHANGELOG.md b/CHANGELOG.md index 56b31b1..829df5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [3.2.2] — 2026-11-09 + +Patch extending opt-in `sidecarEntangle` to **Electron ASAR archive-note companions**. + +### Added +- **Sidecar ASAR archive-note strip⇒fail (`.bla/sidecar.v1.json`):** `generateSidecarAsarArchiveNote` / `bindAsarSidecarEntanglement` / `entangleAsarEntryWithSidecars` / `verifyAsarSidecarArchiveNote`. When `sidecarEntangle` is on, `protectTarget` plants an in-archive `.bla/sidecar.v1.json` note binding the decoy `enclave/hardware-tee-bridge.js` (plus any explicit `sidecarEntanglePaths`). `hardenProject` ASAR-only post-pass covers trees with no JS/Python/WASM entry. Default still OFF. + +### Fixed +- Removed accidental `selfSeal` spread onto the ASAR decoy `VirtualAsarFile` for `enclave/hardware-tee-bridge.js`. + ## [3.2.0] — 2026-11-08 Minor release extending opt-in `sidecarEntangle` to **Bun / EOF-preserved native companions** and closing the defenseScore honesty gap when entanglement is left OFF. diff --git a/NIGHTLY.md b/NIGHTLY.md index e6f6dfd..0fb6d60 100644 --- a/NIGHTLY.md +++ b/NIGHTLY.md @@ -1,5 +1,29 @@ # BLA nightly development log +## 2026-11-09 ~Asia/Shanghai + +### REA delta +- Pulled `morluto/rea`: `559083be2` → `e9b6c87c1` (**+142** commits). +- Headline surface area: desktop/AppImage host tooling, Android `.note.android.ident`, + Deno compile inventory (#8527), ELF unwind/init arrays, V8 cachedData boundaries — + no new 1:1 trip-able budget constants that beat the queued ASAR companion slice. +- Electron ASAR tests/polish only (`#9549` authorized ASAR path) — reinforces + archive-note strip⇒fail as the right defensive increment. + +### Done tonight +- ASAR archive-note sidecar entanglement (`generateSidecarAsarArchiveNote` / + `bindAsar` / `entangleAsar` / `verifyAsarSidecarArchiveNote`; in-archive + `.bla/sidecar.v1.json` binding `enclave/hardware-tee-bridge.js`; protect + + harden ASAR-only post-pass; default OFF via existing `sidecarEntangle`). +- Fixed accidental `selfSeal` spread onto the ASAR decoy `VirtualAsarFile`. +- Gates: build OK, tests **683 passed / 4 skipped**, benchmark **14/14** runtime-equivalent. +- Pushed `origin/main`; release **bla-agents@3.2.2**. + +### Next step (following night) +1. Optional ASAR main JS preamble (Electron fs-patched member re-measure). +2. Optional JS-loader `verifyWasmSidecarCustomSection`. +3. Scan REA Deno compile (#8527) / ELF unwind for a net-positive 1:1 counter. + ## 2026-11-01 ~02:10 (Asia/Singapore) ### REA delta diff --git a/README.md b/README.md index eadf51b..2fc3d50 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ **The open-source Counter-REA Blue Defense MCP & CLI that protects software releases against AI reverse-engineering agents (`morluto/rea`, autonomous decompilers, and LLM recon pipelines) — verified across 14 showcase benchmark targets.** -[![npm version](https://img.shields.io/badge/npm-bla--agents_v3.2.1-2563eb?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/bla-agents) +[![npm version](https://img.shields.io/badge/npm-bla--agents_v3.2.2-2563eb?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/bla-agents) [![GitHub Trending](https://img.shields.io/badge/GitHub_Trending-%2315_Daily-7c3aed?style=for-the-badge&logo=github&logoColor=white)](https://trendshift.io/repositories/323569) [![MCP Server](https://img.shields.io/badge/MCP-25_Defense_Tools-0ea5e9?style=for-the-badge)](docs/cli-and-mcp.md) [![Formats](https://img.shields.io/badge/Formats-19%2B_Artifacts-0284c7?style=for-the-badge)](#format-coverage) diff --git a/STATE.md b/STATE.md index 68730e3..3a33da8 100644 --- a/STATE.md +++ b/STATE.md @@ -1,6 +1,6 @@ # BLA state of the project -**Version:** 3.1.1 (`package.json` ↔ `src/identity.ts`, verified by build; see `CHANGELOG.md`) +**Version:** 3.2.2 (`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:** tagged releases (`git tag bla-agents-`) plus GitHub Releases. The release workflow can also publish the packed tarball to npm with provenance when `NPM_TOKEN`/OIDC is configured; a release cut may intentionally skip the npm step (see `CHANGELOG.md`). @@ -106,7 +106,7 @@ CrackMe v8 red team (round-20261106): **NO PRIZE** — key/FLAG not recovered; ` ## 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. -2. **Sidecar entry entanglement** — JS strip⇒fail landed 2026-11-05; Python preamble landed 2026-11-06 nightly; WASM `bla.sidecar.v1` custom-section + host verify landed 2026-11-07 nightly; Bun `.bla-sidecar.v1.json` companion + defenseScore `sidecar-entangle-not-enabled` gap landed 2026-11-08 nightly. Remaining: ASAR archive-note companion; optional JS-loader `verifyWasmSidecarCustomSection`. +2. **Sidecar entry entanglement** — JS strip⇒fail landed 2026-11-05; Python preamble landed 2026-11-06 nightly; WASM `bla.sidecar.v1` custom-section + host verify landed 2026-11-07 nightly; Bun `.bla-sidecar.v1.json` companion + defenseScore `sidecar-entangle-not-enabled` gap landed 2026-11-08 nightly; ASAR `.bla/sidecar.v1.json` archive-note landed 2026-11-09 nightly. Remaining: optional ASAR main JS preamble; optional JS-loader `verifyWasmSidecarCustomSection`. 3. **Deception shields → more formats** — WASM export rename + `wasmPreserveExports` landed; DEX/SQLite/model densify and broader numeric template hygiene still open. 4. **Empirical JADX / Android red-team** — real REA mapping+JNI vs BLA-hardened unsigned APK. 5. **ESP flash / esp-image (#8228)** — if REA moved there; UF2 empirical red-team otherwise. diff --git a/challenge/v6/SEAL.json b/challenge/v6/SEAL.json index eb08033..52fa0a5 100644 --- a/challenge/v6/SEAL.json +++ b/challenge/v6/SEAL.json @@ -1,7 +1,7 @@ { "schema": "bla-crackme-v6-seal/v2", "mode": "release", - "blaVersion": "3.2.1", + "blaVersion": "3.2.2", "recipe": "npm run crackme:build (hardenProject == `bla harden --intensity bankrupt --seed `)", "seed": "bla-crackme-v6-harden-native-2026-11", "intensity": "bankrupt", diff --git a/challenge/v7/SEAL.json b/challenge/v7/SEAL.json index 3f4b0b5..31b661c 100644 --- a/challenge/v7/SEAL.json +++ b/challenge/v7/SEAL.json @@ -2,7 +2,7 @@ "schema": "bla-crackme-v7-seal/v1", "mode": "release", "product": "Meridian", - "blaVersion": "3.2.1", + "blaVersion": "3.2.2", "hardenSeedLabel": "bound-at-build-into-opaque-predicates", "intensity": "bankrupt", "llmDirectives": false, diff --git a/challenge/v8/SEAL.json b/challenge/v8/SEAL.json index 29bcc22..87dcccb 100644 --- a/challenge/v8/SEAL.json +++ b/challenge/v8/SEAL.json @@ -2,7 +2,7 @@ "schema": "bla-crackme-v8-seal/v2", "mode": "release", "product": "Aegis", - "blaVersion": "3.2.1", + "blaVersion": "3.2.2", "recipe": "npm run crackme:v8:build (hardenProject == `bla harden --intensity bankrupt --seed --self-seal`); harden/schedule seed is private (derived from release secrets) and NOT published", "label": "bla-crackme-v8-aegis-2026-11", "intensity": "bankrupt", diff --git a/challenge/v9/SEAL.json b/challenge/v9/SEAL.json index 644c275..859aa37 100644 --- a/challenge/v9/SEAL.json +++ b/challenge/v9/SEAL.json @@ -2,7 +2,7 @@ "schema": "bla-crackme-v9-seal/v1", "mode": "release", "product": "Sovereign", - "blaVersion": "3.2.1", + "blaVersion": "3.2.2", "recipe": "npm run crackme:v9:build (4-Stage BLA 3.0 Playbook: bla_lint -> bla_weave_plan -> bla_verify_weave -> bla_harden --intensity bankrupt --weave-decoys --self-seal --sidecar-entangle); harden/schedule seed is private", "label": "bla-crackme-v9-sovereign-2026-11", "intensity": "bankrupt", diff --git a/docs/design/sidecar-entry-entanglement.md b/docs/design/sidecar-entry-entanglement.md index fd9999e..480df4b 100644 --- a/docs/design/sidecar-entry-entanglement.md +++ b/docs/design/sidecar-entry-entanglement.md @@ -1,6 +1,6 @@ # DESIGN: Sidecar / entry entanglement (issue #40 / STATE) -Status: **JS + Python + WASM + Bun companion strip⇒fail** — binding digest + JS/Python preambles + WASM `bla.sidecar.v1` custom-section note + Bun sibling `.bla-sidecar.v1.json` companion note (byte-exact binary) + protect/harden opt-in landed; defenseScore gap when `sidecarEntangle` is off landed; ASAR archive-note companion still TBD. +Status: **JS + Python + WASM + Bun companion + ASAR archive-note strip⇒fail** — binding digest + JS/Python preambles + WASM `bla.sidecar.v1` custom-section note + Bun sibling `.bla-sidecar.v1.json` companion note (byte-exact binary) + ASAR in-archive `.bla/sidecar.v1.json` note + protect/harden opt-in landed; defenseScore gap when `sidecarEntangle` is off landed; optional ASAR main JS preamble / JS-loader `verifyWasmSidecarCustomSection` still TBD. ## Goal @@ -42,4 +42,4 @@ checks beat orphan honeypot files. - ~~WASM custom-section note + host-side verify.~~ — 2026-11-07 nightly: `generateSidecarWasmCustomSection` / `bindWasmSidecarEntanglement` / `entangleWasmEntryWithSidecars` / `verifyWasmSidecarCustomSection`; protect + harden WASM-only post-pass. - ~~Bun / EOF-preserved native companion note.~~ — 2026-11-08 nightly: `generateSidecarBunCompanionNote` / `bindBunSidecarEntanglement` / `entangleBunEntryWithSidecars` / `verifyBunSidecarCompanionNote`; protect auto-binds `.bunfs-snapshot`; harden Bun-only post-pass; binary stays byte-exact. - ~~Honesty: when entanglement is off, defenseScore gap annotation (like self-seal).~~ — 2026-11-08 nightly: `sidecar-entangle-not-enabled` soft-cap (93) via `sidecarEntangleEnabled` / MCP `sidecar_entangle_enabled`. -- Extend to ASAR archive-note companion (plant `.bla/sidecar.v1.json` + optional main JS preamble). +- ~~Extend to ASAR archive-note companion~~ — 2026-11-09 nightly: `generateSidecarAsarArchiveNote` / `bindAsarSidecarEntanglement` / `entangleAsarEntryWithSidecars` / `verifyAsarSidecarArchiveNote`; protect + harden ASAR post-pass plant `.bla/sidecar.v1.json` binding `enclave/hardware-tee-bridge.js`. Optional in-archive main JS preamble still TBD. diff --git a/docs/readme/README_zh.md b/docs/readme/README_zh.md index 77a7549..afe347a 100644 --- a/docs/readme/README_zh.md +++ b/docs/readme/README_zh.md @@ -12,7 +12,7 @@ **开源的 Counter-REA 蓝队防御 MCP 服务与 CLI 工具 —— 专为保护软件发布产物免受 AI 逆向分析代理(`morluto/rea`、自动化反编译与大模型逆向流水线)还原而设计,同时保持 100% 运行时等价。** -[![npm version](https://img.shields.io/badge/npm-bla--agents_v3.2.1-2563eb?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/bla-agents) +[![npm version](https://img.shields.io/badge/npm-bla--agents_v3.2.2-2563eb?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/bla-agents) [![GitHub Trending](https://img.shields.io/badge/GitHub_Trending-%2315_Daily-7c3aed?style=for-the-badge&logo=github&logoColor=white)](https://trendshift.io/repositories/323569) [![MCP Server](https://img.shields.io/badge/MCP-25_项防御工具-0ea5e9?style=for-the-badge)](../cli-and-mcp.md) [![Formats](https://img.shields.io/badge/支持格式-19%2B_种构建产物-0284c7?style=for-the-badge)](#支持的产物格式与覆盖矩阵) diff --git a/package-lock.json b/package-lock.json index a19a32c..fd2bac6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "bla-agents", - "version": "3.2.1", + "version": "3.2.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "bla-agents", - "version": "3.2.1", + "version": "3.2.2", "license": "MIT", "dependencies": { "@babel/generator": "^8.1.0", diff --git a/package.json b/package.json index 848c486..e2fe09f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bla-agents", - "version": "3.2.1", + "version": "3.2.2", "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", diff --git a/src/engine/harden.ts b/src/engine/harden.ts index 21e718e..2803252 100644 --- a/src/engine/harden.ts +++ b/src/engine/harden.ts @@ -36,13 +36,16 @@ import { evaluateHardenProjectPackagingBlocks, } from "./packaging-gates.js"; import { + ASAR_SIDECAR_ARCHIVE_NOTE_PATH, BUN_SIDECAR_COMPANION_SUFFIX, + entangleAsarEntryWithSidecars, entangleBunEntryWithSidecars, entangleJsEntryWithSidecars, entanglePythonEntryWithSidecars, entangleWasmEntryWithSidecars, planSidecarEntanglement, } from "../shields/runtime/sidecar-entangle.js"; +import { packAsarBuffer, unpackAsarBuffer } from "../shields/formats/asar.js"; import { finalizeSelfSealSelfDigest, verifySelfSealSelfDigest, @@ -1180,6 +1183,58 @@ export function hardenProject( } } } + + // ASAR archive-note post-pass only when no JS/Python/WASM/Bun entry was + // bound — plant `.bla/sidecar.v1.json` binding the decoy bridge member. + const asarLike = summaries.filter( + (s) => + s.success && + (s.format === "electron-asar" || + /\.asar$/i.test(s.relativePath.replaceAll("\\", "/"))), + ); + if (!jsEntry && !pyEntry && !wasmEntry && asarLike.length > 0) { + for (const asarEntry of asarLike) { + const entryAbs = join(outputRoot, asarEntry.relativePath); + if (!existsSync(entryAbs)) continue; + const raw = readFileSync(entryAbs); + let members; + try { + members = unpackAsarBuffer(raw); + } catch { + continue; + } + if (members.some((m) => m.relativePath === ASAR_SIDECAR_ARCHIVE_NOTE_PATH)) { + continue; // already planted by protect + } + const bridge = members.find( + (m) => m.relativePath === "enclave/hardware-tee-bridge.js", + ); + if (!bridge) continue; + const entryLabel = basename(entryAbs); + const bound = entangleAsarEntryWithSidecars({ + entryPath: entryLabel, + entryBytes: raw, + sidecars: [ + { + pathLabel: "enclave/hardware-tee-bridge.js", + bytes: bridge.content, + }, + ], + seedTag: String(options.seed ?? runId), + }); + if (!bound) continue; + const repacked = packAsarBuffer([ + ...members, + { + relativePath: ASAR_SIDECAR_ARCHIVE_NOTE_PATH, + content: bound.noteBytes, + }, + ]); + writeFileAtomicSync(entryAbs, repacked, undefined, { + allowLinkWriteThrough: false, + }); + } + } } catch (err) { // Entanglement was explicitly requested, so a failure is not a harmless // no-op: the entry ships without the strip⇒fail binding. Record it so the diff --git a/src/engine/protector.ts b/src/engine/protector.ts index d5129d3..2217ff9 100644 --- a/src/engine/protector.ts +++ b/src/engine/protector.ts @@ -92,7 +92,9 @@ import { } from "./js-wasm-hydrate-dump-lint.js"; import { finalizeSelfSealSelfDigest } from "../shields/runtime/self-seal.js"; import { + ASAR_SIDECAR_ARCHIVE_NOTE_PATH, BUN_SIDECAR_COMPANION_SUFFIX, + entangleAsarEntryWithSidecars, entangleBunEntryWithSidecars, entangleJsEntryWithSidecars, entanglePythonEntryWithSidecars, @@ -730,11 +732,10 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult { ...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}), }, ); + const decoyBridgeContent = Buffer.from(decoyBridgeJs.code, "utf8"); protectedFiles.push({ relativePath: "enclave/hardware-tee-bridge.js", - content: Buffer.from(decoyBridgeJs.code, "utf8"), - - ...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}), + content: decoyBridgeContent, }); // Flood ASAR Pickle JSON header past REA DEFAULT_ASAR_MAX_HEADER_BYTES at @@ -744,6 +745,49 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult { protectedFiles.push(decoy); } + // Opt-in sidecarEntangle: plant `.bla/sidecar.v1.json` archive note binding + // the decoy bridge (+ explicit sidecarEntanglePaths that resolve to members). + if (options.sidecarEntangle === true) { + const entryLabel = basename(absOutput); + const sidecars: { pathLabel: string; bytes: Uint8Array }[] = [ + { pathLabel: "enclave/hardware-tee-bridge.js", bytes: decoyBridgeContent }, + ]; + const memberIndex = new Map( + protectedFiles.map((f) => [f.relativePath, f.content] as const), + ); + for (const rel of options.sidecarEntanglePaths ?? []) { + if (typeof rel !== "string" || rel.length === 0) continue; + if (rel === "enclave/hardware-tee-bridge.js") continue; + if (rel === ASAR_SIDECAR_ARCHIVE_NOTE_PATH) continue; + const member = memberIndex.get(rel); + if (member) { + sidecars.push({ pathLabel: rel, bytes: member }); + continue; + } + const abs = isAbsolute(rel) ? rel : join(dirname(absOutput), rel); + try { + if (!existsSync(abs)) continue; + sidecars.push({ pathLabel: rel, bytes: readFileSync(abs) }); + } catch { + /* skip unreadable */ + } + } + const bound = entangleAsarEntryWithSidecars({ + entryPath: entryLabel, + entryBytes: rawAsar, + sidecars, + seedTag: String(seed), + softFold: options.sidecarEntangleSoftFold === true, + }); + if (bound) { + protectedFiles.push({ + relativePath: ASAR_SIDECAR_ARCHIVE_NOTE_PATH, + content: bound.noteBytes, + }); + sidecarEntangleApplied = true; + } + } + const repacked = packAsarBuffer(protectedFiles); writeProtectedOutput(absOutput, repacked); binarySectionsPatched = 1 + asarAmplification.files.length; diff --git a/src/identity.ts b/src/identity.ts index ccbf08a..fcfa824 100644 --- a/src/identity.ts +++ b/src/identity.ts @@ -5,7 +5,7 @@ export const BLA_IDENTITY = Object.freeze({ packageAlias: "bla-shield", cliBinary: "bla", cliAlias: "bla-agents", - version: "3.2.1", + version: "3.2.2", slogan: "Poison -> Exhaust -> Hallucinate. Make Reverse Engineering Bankrupt Again.", counterpart: { name: "REA", diff --git a/src/index.ts b/src/index.ts index 05d4169..cb724d6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -493,21 +493,27 @@ export { generateSidecarPythonPreamble, generateSidecarWasmCustomSection, generateSidecarBunCompanionNote, + generateSidecarAsarArchiveNote, bindSidecarEntanglement, bindPythonSidecarEntanglement, bindWasmSidecarEntanglement, bindBunSidecarEntanglement, + bindAsarSidecarEntanglement, entangleJsEntryWithSidecars, entanglePythonEntryWithSidecars, entangleWasmEntryWithSidecars, entangleBunEntryWithSidecars, + entangleAsarEntryWithSidecars, verifyWasmSidecarCustomSection, verifyBunSidecarCompanionNote, + verifyAsarSidecarArchiveNote, stripWasmSidecarCustomSection, SIDECAR_ENTANGLE_SCHEMA, WASM_SIDECAR_SECTION_NAME, BUN_SIDECAR_COMPANION_SUFFIX, BUN_SIDECAR_COMPANION_KIND, + ASAR_SIDECAR_ARCHIVE_NOTE_PATH, + ASAR_SIDECAR_ARCHIVE_NOTE_KIND, type SidecarEntanglePlan, type SidecarEntanglePlanOptions, type SidecarBindingPart, @@ -531,6 +537,12 @@ export { type BunSidecarCompanionNote, type BunSidecarVerifyOptions, type BunSidecarVerifyResult, + type SidecarAsarInjectOptions, + type SidecarAsarInjectResult, + type SidecarAsarBindResult, + type AsarSidecarArchiveNote, + type AsarSidecarVerifyOptions, + type AsarSidecarVerifyResult, } from "./shields/runtime/sidecar-entangle.js"; export { diff --git a/src/shields/runtime/sidecar-entangle.ts b/src/shields/runtime/sidecar-entangle.ts index 40574b7..86088ee 100644 --- a/src/shields/runtime/sidecar-entangle.ts +++ b/src/shields/runtime/sidecar-entangle.ts @@ -8,7 +8,8 @@ * `sidecarEntangle` is set; WASM uses a `bla.sidecar.v1` custom-section note * plus host-side `verifyWasmSidecarCustomSection`; Bun standalone plants a * sibling `.bla-sidecar.v1.json` companion note (byte-exact binary preserved) - * verified by `verifyBunSidecarCompanionNote` (see + * verified by `verifyBunSidecarCompanionNote`; Electron ASAR plants an in-archive + * `.bla/sidecar.v1.json` note verified by `verifyAsarSidecarArchiveNote` (see * `docs/design/sidecar-entry-entanglement.md`). * * DEFENSIVE ONLY. Hash-only — no guessing. @@ -33,6 +34,7 @@ import { readWasmCustomSectionContent, stripWasmCustomSectionByName, } from "../formats/wasm.js"; +import { unpackAsarBuffer } from "../formats/asar.js"; export const SIDECAR_ENTANGLE_SCHEMA = "bla-sidecar-entangle/v1" as const; @@ -73,6 +75,7 @@ function guessHookKind(entryPath: string): SidecarEntanglePlan["entryHookKind"] if (/\.(mjs|cjs|js|ts|tsx|jsx)$/.test(lower)) return "js-preamble"; if (/\.py$/.test(lower)) return "python-preamble"; if (/\.wasm$/.test(lower)) return "wasm-custom-section"; + if (/\.asar$/.test(lower)) return "asar-archive-note"; return "unspecified"; } @@ -1273,6 +1276,327 @@ export function verifyBunSidecarCompanionNote( }; } + + +/** In-archive companion note path inside an Electron `.asar` (Pickle member). */ +export const ASAR_SIDECAR_ARCHIVE_NOTE_PATH = ".bla/sidecar.v1.json" as const; +export const ASAR_SIDECAR_ARCHIVE_NOTE_KIND = "asar-archive-note" as const; + +export interface AsarSidecarArchiveNote { + readonly schema: typeof SIDECAR_ENTANGLE_SCHEMA; + readonly kind: typeof ASAR_SIDECAR_ARCHIVE_NOTE_KIND; + readonly digest: string; + readonly seedTag: string; + readonly entryPath: string; + readonly sidecarPaths: readonly string[]; + readonly softFold: boolean; + readonly mode: "sidecars"; +} + +export interface SidecarAsarInjectOptions { + readonly entryPath: string; + readonly sidecarPaths: readonly string[]; + readonly seedTag?: string; + /** Offline expected digest (from computeSidecarBindingDigest). */ + readonly expectedHex: string; + readonly softFold?: boolean; +} + +export interface SidecarAsarInjectResult { + readonly schema: typeof SIDECAR_ENTANGLE_SCHEMA; + readonly kind: typeof ASAR_SIDECAR_ARCHIVE_NOTE_KIND; + /** UTF-8 JSON archive note (written as `.bla/sidecar.v1.json` member). */ + readonly noteJson: string; + readonly note: AsarSidecarArchiveNote; + readonly expectedHex: string; + readonly expectedU32: number; + readonly softFold: boolean; + readonly sidecarCount: number; + /** Canonical in-archive member path for the note. */ + readonly archiveNotePath: typeof ASAR_SIDECAR_ARCHIVE_NOTE_PATH; +} + +/** + * Build an ASAR archive-note that embeds the protect-time sidecar binding + * digest + path labels. The note is planted as the Pickle member + * `.bla/sidecar.v1.json` (not a sibling on disk). Strip/alter detection is via + * host-side `verifyAsarSidecarArchiveNote` (and optional future main JS preamble). + * + * Typical sidecars are in-archive decoys such as `enclave/hardware-tee-bridge.js`. + * + * DEFENSIVE ONLY. Opt-in. No crack / RE advice. + */ +export function generateSidecarAsarArchiveNote( + options: SidecarAsarInjectOptions, +): SidecarAsarInjectResult { + const sidecars = (options.sidecarPaths ?? []).filter((p) => p.length > 0); + const seedTag = options.seedTag ?? "bla-sidecar-v1"; + const softFold = options.softFold === true; + const expectedHex = options.expectedHex.toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(expectedHex)) { + throw new Error("expectedHex must be a 64-char lowercase hex SHA-256 digest"); + } + const expectedU32 = parseInt(expectedHex.slice(0, 8), 16) >>> 0; + const note: AsarSidecarArchiveNote = { + schema: SIDECAR_ENTANGLE_SCHEMA, + kind: ASAR_SIDECAR_ARCHIVE_NOTE_KIND, + digest: expectedHex, + seedTag, + entryPath: options.entryPath, + sidecarPaths: sidecars, + softFold, + mode: "sidecars", + }; + const noteJson = `${JSON.stringify(note, null, 2)}\n`; + return { + schema: SIDECAR_ENTANGLE_SCHEMA, + kind: ASAR_SIDECAR_ARCHIVE_NOTE_KIND, + noteJson, + note, + expectedHex, + expectedU32, + softFold, + sidecarCount: sidecars.length, + archiveNotePath: ASAR_SIDECAR_ARCHIVE_NOTE_PATH, + }; +} + +export interface SidecarAsarBindResult { + readonly plan: SidecarEntanglePlan; + readonly digest: SidecarBindingDigest; + readonly inject: SidecarAsarInjectResult; + /** Archive-note JSON bytes to plant as `.bla/sidecar.v1.json` (entry asar rebuilt). */ + readonly noteBytes: Buffer; +} + +/** + * Plan + bind for an Electron ASAR entry: compute the offline digest from + * in-memory in-archive sidecar member bytes and return a `bound` plan plus + * archive-note bytes. Uses sidecars-mode digest; the asar is repacked with the + * note member (real app modules otherwise untouched by this helper). + */ +export function bindAsarSidecarEntanglement( + options: SidecarEntanglePlanOptions & { + readonly entryBytes: Uint8Array; + readonly sidecarBytes: readonly Uint8Array[]; + }, +): SidecarAsarBindResult { + const plan = planSidecarEntanglement(options); + if (options.sidecarBytes.length !== plan.sidecarPaths.length) { + throw new Error("sidecarBytes length must match sidecarPaths length"); + } + const digest = computeSidecarBindingDigest( + { pathLabel: options.entryPath, bytes: options.entryBytes }, + plan.sidecarPaths.map((pathLabel, i) => ({ + pathLabel, + bytes: options.sidecarBytes[i]!, + })), + plan.seedTag, + "sidecars", + ); + const inject = generateSidecarAsarArchiveNote({ + entryPath: options.entryPath, + sidecarPaths: plan.sidecarPaths, + seedTag: plan.seedTag, + expectedHex: digest.hex, + softFold: plan.softFold, + }); + const boundPlan: SidecarEntanglePlan = { + ...plan, + entryHookKind: "asar-archive-note", + status: "bound", + note: "Bound — ASAR archive note `.bla/sidecar.v1.json` ready; plant as Pickle member with decoy sidecars. Strip/alter fails closed via verifyAsarSidecarArchiveNote.", + }; + return { + plan: boundPlan, + digest, + inject, + noteBytes: Buffer.from(inject.noteJson, "utf8"), + }; +} + +/** + * Convenience: given final in-archive sidecar member bytes + ASAR entry label, + * produce the archive note. Returns null when there are no sidecars to bind. + * Does NOT rewrite other members — caller plants `noteBytes` and repacks. + */ +export function entangleAsarEntryWithSidecars(options: { + readonly entryPath: string; + readonly entryBytes: Uint8Array; + readonly sidecars: readonly SidecarBindingPart[]; + readonly seedTag?: string; + readonly softFold?: boolean; +}): SidecarAsarBindResult | null { + if (options.sidecars.length === 0) return null; + return bindAsarSidecarEntanglement({ + entryPath: options.entryPath, + sidecarPaths: options.sidecars.map((s) => s.pathLabel), + seedTag: options.seedTag, + softFold: options.softFold, + entryBytes: options.entryBytes, + sidecarBytes: options.sidecars.map((s) => s.bytes), + fileBytes: Object.fromEntries( + options.sidecars.map((s) => [s.pathLabel, Buffer.from(s.bytes)]), + ), + }); +} + +export interface AsarSidecarVerifyOptions { + /** Archive note JSON bytes (or parsed UTF-8 string), or full ASAR buffer to unpack. */ + readonly noteBytes?: Uint8Array | string; + /** Full ASAR bytes — when set, note is read from `.bla/sidecar.v1.json` member. */ + readonly asarBytes?: Uint8Array; + /** + * In-memory archive members keyed by relative path (overrides asar unpack / + * disk). Used for unit tests and protect-time checks. + */ + readonly memberBytes?: Readonly>; +} + +export interface AsarSidecarVerifyResult { + readonly ok: boolean; + readonly reason?: string; + readonly note?: AsarSidecarArchiveNote; + readonly expectedHex?: string; + readonly measuredHex?: string; + readonly measuredU32?: number; + readonly softFold?: boolean; +} + +function parseAsarSidecarArchiveNote( + raw: string, +): { ok: true; note: AsarSidecarArchiveNote } | { ok: false; reason: string } { + try { + const parsed = JSON.parse(raw) as AsarSidecarArchiveNote; + if ( + parsed.schema !== SIDECAR_ENTANGLE_SCHEMA || + parsed.kind !== ASAR_SIDECAR_ARCHIVE_NOTE_KIND || + typeof parsed.digest !== "string" || + !/^[0-9a-f]{64}$/i.test(parsed.digest) + ) { + return { ok: false, reason: "asar archive note malformed" }; + } + return { + ok: true, + note: { + schema: SIDECAR_ENTANGLE_SCHEMA, + kind: ASAR_SIDECAR_ARCHIVE_NOTE_KIND, + digest: parsed.digest.toLowerCase(), + seedTag: typeof parsed.seedTag === "string" ? parsed.seedTag : "bla-sidecar-v1", + entryPath: typeof parsed.entryPath === "string" ? parsed.entryPath : "", + sidecarPaths: Array.isArray(parsed.sidecarPaths) + ? parsed.sidecarPaths.filter((p): p is string => typeof p === "string" && p.length > 0) + : [], + softFold: parsed.softFold === true, + mode: "sidecars", + }, + }; + } catch { + return { ok: false, reason: "asar archive note is not valid JSON" }; + } +} + +/** + * Host-side strip⇒fail check for ASAR archive notes: parse + * `.bla/sidecar.v1.json`, re-hash listed in-archive member bytes with the same + * layout as `computeSidecarBindingDigest` (sidecars mode), and compare to the + * embedded digest. Missing note / missing member / altered member ⇒ ok:false. + * + * DEFENSIVE ONLY — for tests, loaders, and harden post-pass verification. + */ +export function verifyAsarSidecarArchiveNote( + options: AsarSidecarVerifyOptions, +): AsarSidecarVerifyResult { + let noteRaw: string | undefined; + const members: Record = { + ...(options.memberBytes ?? {}), + }; + + if (options.asarBytes) { + try { + const unpacked = unpackAsarBuffer(Buffer.from(options.asarBytes)); + for (const vf of unpacked) { + if (!(vf.relativePath in members)) { + members[vf.relativePath] = vf.content; + } + } + } catch { + return { ok: false, reason: "asar archive could not be unpacked" }; + } + } + + if (options.noteBytes !== undefined) { + noteRaw = + typeof options.noteBytes === "string" + ? options.noteBytes + : Buffer.from(options.noteBytes).toString("utf8"); + } else if (members[ASAR_SIDECAR_ARCHIVE_NOTE_PATH]) { + noteRaw = Buffer.from(members[ASAR_SIDECAR_ARCHIVE_NOTE_PATH]!).toString("utf8"); + } else { + return { ok: false, reason: "asar archive note not supplied" }; + } + + const parsed = parseAsarSidecarArchiveNote(noteRaw); + if (!parsed.ok) return { ok: false, reason: parsed.reason }; + const note = parsed.note; + + const sidecarParts: SidecarBindingPart[] = []; + for (const label of note.sidecarPaths) { + const override = members[label]; + if (override) { + sidecarParts.push({ pathLabel: label, bytes: override }); + continue; + } + sidecarParts.push({ + pathLabel: label, + bytes: new TextEncoder().encode(`missing:${label}`), + }); + } + + const measured = computeSidecarBindingDigest( + { + pathLabel: note.entryPath, + bytes: new Uint8Array(0), + }, + sidecarParts, + note.seedTag, + "sidecars", + ); + + if (measured.hex === note.digest) { + return { + ok: true, + note, + expectedHex: note.digest, + measuredHex: measured.hex, + measuredU32: measured.u32, + softFold: note.softFold, + }; + } + + if (note.softFold) { + return { + ok: false, + reason: "integrity binding mismatch (soft-fold)", + note, + expectedHex: note.digest, + measuredHex: measured.hex, + measuredU32: (measured.u32 ^ 0xffffffff) >>> 0, + softFold: true, + }; + } + + return { + ok: false, + reason: "integrity binding mismatch", + note, + expectedHex: note.digest, + measuredHex: measured.hex, + measuredU32: measured.u32, + softFold: false, + }; +} + /** Test/helper: strip the sidecar note section from a WASM binary. */ export function stripWasmSidecarCustomSection(bytes: Uint8Array): Buffer { return stripWasmCustomSectionByName(Buffer.from(bytes), WASM_SIDECAR_SECTION_NAME); diff --git a/tests/sidecar-asar-inject.test.ts b/tests/sidecar-asar-inject.test.ts new file mode 100644 index 0000000..c3f0a92 --- /dev/null +++ b/tests/sidecar-asar-inject.test.ts @@ -0,0 +1,193 @@ +import { describe, expect, it } from "vitest"; +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { + ASAR_SIDECAR_ARCHIVE_NOTE_KIND, + ASAR_SIDECAR_ARCHIVE_NOTE_PATH, + bindAsarSidecarEntanglement, + computeSidecarBindingDigest, + generateSidecarAsarArchiveNote, + SIDECAR_ENTANGLE_SCHEMA, + verifyAsarSidecarArchiveNote, +} from "../src/shields/runtime/sidecar-entangle.js"; +import { packAsarBuffer, unpackAsarBuffer } from "../src/shields/formats/asar.js"; +import { protectTarget } from "../src/engine/protector.js"; + +describe("sidecar ASAR archive-note strip⇒fail", () => { + it("generateSidecarAsarArchiveNote rejects non-hex expected digests", () => { + expect(() => + generateSidecarAsarArchiveNote({ + entryPath: "app.asar", + sidecarPaths: ["enclave/hardware-tee-bridge.js"], + expectedHex: "deadbeef", + }), + ).toThrow(/64-char/); + }); + + it("bindAsarSidecarEntanglement emits archive note without mutating caller buffers", () => { + const entry = Buffer.from("asar-placeholder"); + const bridge = Buffer.from("export function verifyHardwareEnclaveLease(){return true}\n"); + const before = Buffer.from(entry); + const bound = bindAsarSidecarEntanglement({ + entryPath: "app.asar", + sidecarPaths: ["enclave/hardware-tee-bridge.js"], + seedTag: "asar-inject-v1", + entryBytes: entry, + sidecarBytes: [bridge], + }); + expect(bound.plan.schema).toBe(SIDECAR_ENTANGLE_SCHEMA); + expect(bound.plan.status).toBe("bound"); + expect(bound.plan.entryHookKind).toBe("asar-archive-note"); + expect(bound.inject.kind).toBe(ASAR_SIDECAR_ARCHIVE_NOTE_KIND); + expect(bound.inject.archiveNotePath).toBe(ASAR_SIDECAR_ARCHIVE_NOTE_PATH); + expect(bound.inject.expectedHex).toBe(bound.digest.hex); + expect(Buffer.compare(entry, before)).toBe(0); + const parsed = JSON.parse(bound.inject.noteJson); + expect(parsed.kind).toBe(ASAR_SIDECAR_ARCHIVE_NOTE_KIND); + expect(parsed.digest).toBe(bound.digest.hex); + expect(parsed.sidecarPaths).toEqual(["enclave/hardware-tee-bridge.js"]); + }); + + it("digest matches computeSidecarBindingDigest sidecars-mode", () => { + const entry = Buffer.from("asar-bytes"); + const bridge = Buffer.from("bridge-body\n"); + const digest = computeSidecarBindingDigest( + { pathLabel: "app.asar", bytes: entry }, + [{ pathLabel: "enclave/hardware-tee-bridge.js", bytes: bridge }], + "parity-asar-v1", + ); + const inject = generateSidecarAsarArchiveNote({ + entryPath: "app.asar", + sidecarPaths: ["enclave/hardware-tee-bridge.js"], + seedTag: "parity-asar-v1", + expectedHex: digest.hex, + }); + expect(inject.expectedHex).toBe(digest.hex); + expect(inject.expectedU32).toBe(digest.u32); + expect(inject.note.digest).toBe(digest.hex); + }); + + it("verify: intact members pass; mutate or strip bridge fails", () => { + const bridgePath = "enclave/hardware-tee-bridge.js"; + const bridgeBytes = Buffer.from("bridge-ok\n"); + const bound = bindAsarSidecarEntanglement({ + entryPath: "app.asar", + sidecarPaths: [bridgePath], + seedTag: "verify-asar-v1", + entryBytes: Buffer.from("entry"), + sidecarBytes: [bridgeBytes], + }); + const packed = packAsarBuffer([ + { relativePath: "main.js", content: Buffer.from("console.log(1)\n") }, + { relativePath: bridgePath, content: bridgeBytes }, + { relativePath: ASAR_SIDECAR_ARCHIVE_NOTE_PATH, content: bound.noteBytes }, + ]); + + const ok = verifyAsarSidecarArchiveNote({ asarBytes: packed }); + expect(ok.ok).toBe(true); + expect(ok.measuredHex).toBe(bound.digest.hex); + + const tampered = packAsarBuffer([ + { relativePath: "main.js", content: Buffer.from("console.log(1)\n") }, + { relativePath: bridgePath, content: Buffer.from("tampered\n") }, + { relativePath: ASAR_SIDECAR_ARCHIVE_NOTE_PATH, content: bound.noteBytes }, + ]); + const bad = verifyAsarSidecarArchiveNote({ asarBytes: tampered }); + expect(bad.ok).toBe(false); + expect(bad.reason).toMatch(/mismatch/); + + const stripped = packAsarBuffer([ + { relativePath: "main.js", content: Buffer.from("console.log(1)\n") }, + { relativePath: ASAR_SIDECAR_ARCHIVE_NOTE_PATH, content: bound.noteBytes }, + ]); + const missing = verifyAsarSidecarArchiveNote({ asarBytes: stripped }); + expect(missing.ok).toBe(false); + }); + + it("protectTarget with sidecarEntangle plants .bla/sidecar.v1.json; strip bridge fails verify", () => { + const dir = mkdtempSync(join(tmpdir(), "bla-sidecar-asar-protect-")); + try { + const input = join(dir, "app.asar"); + const output = join(dir, "out", "app.asar"); + writeFileSync( + input, + packAsarBuffer([ + { relativePath: "main.js", content: Buffer.from("exports.x = 1;\n") }, + { + relativePath: "package.json", + content: Buffer.from('{"main":"main.js"}\n'), + }, + ]), + ); + const res = protectTarget({ + inputPath: input, + outputPath: output, + intensity: "balanced", + seed: "asar-entangle-protect-1", + sidecarEntangle: true, + }); + expect(res.counteredReaVectors).toContain("asar-header-admission"); + expect(res.sidecarEntangle).toBe(true); + expect(existsSync(output)).toBe(true); + const members = unpackAsarBuffer(readFileSync(output)); + expect(members.some((m) => m.relativePath === ASAR_SIDECAR_ARCHIVE_NOTE_PATH)).toBe( + true, + ); + expect( + members.some((m) => m.relativePath === "enclave/hardware-tee-bridge.js"), + ).toBe(true); + const verified = verifyAsarSidecarArchiveNote({ + asarBytes: readFileSync(output), + }); + expect(verified.ok).toBe(true); + + // Strip decoy bridge ⇒ verify fails. + const withoutBridge = members.filter( + (m) => m.relativePath !== "enclave/hardware-tee-bridge.js", + ); + const strippedAsar = packAsarBuffer(withoutBridge); + expect( + verifyAsarSidecarArchiveNote({ asarBytes: strippedAsar }).ok, + ).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("protectTarget default (sidecarEntangle off) does not plant archive note", () => { + const dir = mkdtempSync(join(tmpdir(), "bla-sidecar-asar-off-")); + try { + const input = join(dir, "app.asar"); + const output = join(dir, "out", "app.asar"); + writeFileSync( + input, + packAsarBuffer([ + { relativePath: "main.js", content: Buffer.from("exports.x = 1;\n") }, + ]), + ); + protectTarget({ + inputPath: input, + outputPath: output, + intensity: "stealth", + seed: "asar-entangle-off", + }); + const members = unpackAsarBuffer(readFileSync(output)); + expect(members.some((m) => m.relativePath === ASAR_SIDECAR_ARCHIVE_NOTE_PATH)).toBe( + false, + ); + // decoy bridge still planted by protect + expect( + members.some((m) => m.relativePath === "enclave/hardware-tee-bridge.js"), + ).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/tests/sidecar-entangle-plan.test.ts b/tests/sidecar-entangle-plan.test.ts index d985c6b..732531b 100644 --- a/tests/sidecar-entangle-plan.test.ts +++ b/tests/sidecar-entangle-plan.test.ts @@ -44,7 +44,7 @@ describe("sidecar entry entanglement planner (Direction-3)", () => { expect(plan.coverageEvaluation.shouldRefuseBankrupt).toBe(true); }); - it("guesses python / wasm hook kinds", () => { + it("guesses python / wasm / asar hook kinds", () => { expect( planSidecarEntanglement({ entryPath: "app.py", sidecarPaths: ["app.pyc"] }) .entryHookKind, @@ -53,5 +53,9 @@ describe("sidecar entry entanglement planner (Direction-3)", () => { planSidecarEntanglement({ entryPath: "core.wasm", sidecarPaths: ["core.name"] }) .entryHookKind, ).toBe("wasm-custom-section"); + expect( + planSidecarEntanglement({ entryPath: "app.asar", sidecarPaths: ["enclave/hardware-tee-bridge.js"] }) + .entryHookKind, + ).toBe("asar-archive-note"); }); });