feat(sidecar): Bun companion strip⇒fail + defenseScore honesty gap

Extend opt-in sidecarEntangle to Bun/EOF-preserved native companions via a
sibling .bla-sidecar.v1.json note (generateSidecarBunCompanionNote /
bindBunSidecarEntanglement / entangleBunEntryWithSidecars /
verifyBunSidecarCompanionNote). protectTarget auto-binds the planted
.bunfs-snapshot without rewriting the byte-exact binary; hardenProject
covers Bun-only trees. Add sidecar-entangle-not-enabled defenseScore
soft-cap (93) with sidecarEntangleEnabled / MCP sidecar_entangle_enabled.
Fix harden sidecar post-pass options.inPlace TypeScript break from #148.
Release bla-agents@3.2.0.
This commit is contained in:
qybaihe
2026-11-09 02:16:14 +08:00
parent d7ba47aff6
commit 439d0e5ea2
21 changed files with 717 additions and 19 deletions
+12
View File
@@ -6,6 +6,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [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.
### Added
- **Sidecar Bun companion strip⇒fail (`.bla-sidecar.v1.json`):** `generateSidecarBunCompanionNote` / `bindBunSidecarEntanglement` / `entangleBunEntryWithSidecars` / `verifyBunSidecarCompanionNote`. When `sidecarEntangle` is on, `protectTarget` auto-binds the planted `<binary>.bunfs-snapshot` via a sibling companion note without rewriting the Bun/EOF-preserved binary (runtime red line). `hardenProject` Bun-only post-pass covers native trees with no JS/Python/WASM entry. Default still OFF.
- **defenseScore honesty gap `sidecar-entangle-not-enabled`:** soft-cap 93 when formats that support sidecarEntangle (JS/TS/HTML/ASAR/WASM/Python/native) were verified without the opt-in. Plumbed as `sidecarEntangleEnabled` / MCP `sidecar_entangle_enabled` (mirrors self-seal honesty).
### Fixed
- **`hardenProject` sidecar post-pass TypeScript:** replaced invalid `options.inPlace` references (introduced by #148) with `allowLinkWriteThrough: false` so `tsc` passes; harden always writes under the output directory.
## [3.1.1]
## [3.1.1] — 2026-11-08
Patch release shipping `@babel/*` v8.1.0 compatibility, WASM custom-section sidecar strip⇒fail entanglement, multi-language (`JS/TS`, `Python`, `C/C++/Rust/Go`) planner & verifier hardening from subagent dogfooding, and recursive `bla_encrypt_strings` discovery.
+1 -1
View File
@@ -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 (`generateSidecarWasmCustomSection` / protect+harden WASM-only). Remaining: ASAR/Bun companions, defenseScore gap when off.
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`.
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.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"schema": "bla-crackme-v6-seal/v2",
"mode": "release",
"blaVersion": "3.1.2",
"blaVersion": "3.2.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": "3.1.2",
"blaVersion": "3.2.0",
"hardenSeedLabel": "bound-at-build-into-opaque-predicates",
"intensity": "bankrupt",
"llmDirectives": false,
+1 -1
View File
@@ -2,7 +2,7 @@
"schema": "bla-crackme-v8-seal/v2",
"mode": "release",
"product": "Aegis",
"blaVersion": "3.1.2",
"blaVersion": "3.2.0",
"recipe": "npm run crackme:v8:build (hardenProject == `bla harden <dir> --intensity bankrupt --seed <private> --self-seal`); harden/schedule seed is private (derived from release secrets) and NOT published",
"label": "bla-crackme-v8-aegis-2026-11",
"intensity": "bankrupt",
+1 -1
View File
@@ -2,7 +2,7 @@
"schema": "bla-crackme-v9-seal/v1",
"mode": "release",
"product": "Sovereign",
"blaVersion": "3.1.2",
"blaVersion": "3.2.0",
"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",
+4 -3
View File
@@ -1,6 +1,6 @@
# DESIGN: Sidecar / entry entanglement (issue #40 / STATE)
Status: **JS + Python + WASM strip⇒fail** — binding digest + JS/Python preambles + WASM `bla.sidecar.v1` custom-section note + protect/harden opt-in landed; ASAR/Bun companions + defenseScore gap when off still TBD.
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.
## Goal
@@ -40,5 +40,6 @@ checks beat orphan honeypot files.
- ~~Entry self-coverage~~ — landed 2026-11-05: self-seal embeds a canonical entry self-digest finalized at write time; harden reports `integrityCoverageSelfVerified` and drops paper self edges when it does not verify.
- ~~Wire planner into `protectTarget` for JS + Python when `sidecarEntangle` is set.~~ — JS 2026-11-05; Python 2026-11-06 nightly.
- ~~WASM custom-section note + host-side verify.~~ — 2026-11-07 nightly: `generateSidecarWasmCustomSection` / `bindWasmSidecarEntanglement` / `entangleWasmEntryWithSidecars` / `verifyWasmSidecarCustomSection`; protect + harden WASM-only post-pass.
- Extend to ASAR / Bun snapshot / native companion files.
- Honesty: when entanglement is off, defenseScore gap annotation (like self-seal).
- ~~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).
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "bla-agents",
"version": "3.1.2",
"version": "3.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "bla-agents",
"version": "3.1.2",
"version": "3.2.0",
"license": "MIT",
"dependencies": {
"@babel/generator": "^8.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "bla-agents",
"version": "3.1.2",
"version": "3.2.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",
+1 -1
View File
@@ -103,7 +103,7 @@ Options:
--llm-directives Opt-in risky LLM directive layers (COPPA/medical bait, dual-use imitation, AI chat markers); OFF by default
--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
--sidecar-entangle Opt-in sidecar/entry entanglement strip⇒fail for JS/Python (issue #40); OFF by default
--sidecar-entangle Opt-in sidecar/entry entanglement strip⇒fail for JS/Python/WASM + Bun companion note (issue #40); 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
+2
View File
@@ -231,6 +231,8 @@ export function defendTarget(options: OneClickDefenseOptions): OneClickDefenseRe
// Stage 4: Verify Counter-REA Invariants
const verification = verifyTarget(protection.outputPath, absInput, {
selfSealEnabled: options.selfSeal === true || protection.selfSeal === true,
sidecarEntangleEnabled:
options.sidecarEntangle === true || protection.sidecarEntangle === true,
wasmExportRenameApplied: protection.wasmExportRenameApplied === true,
});
+28
View File
@@ -17,6 +17,7 @@ export const DEFENSE_SCORE_DISCLAIMER =
export type DefenseScoreGapId =
| "wasm-export-rename-pending"
| "self-seal-not-enabled"
| "sidecar-entangle-not-enabled"
| "numeric-template-hygiene-partial";
export interface DefenseScoreGap {
@@ -30,6 +31,8 @@ export interface DefenseScoreHonestyInput {
readonly detectedFormat: ArtifactFormat;
/** True when protect/harden ran with selfSeal / self_seal opt-in. */
readonly selfSealEnabled?: boolean;
/** True when protect/harden ran with sidecarEntangle / sidecar_entangle opt-in. */
readonly sidecarEntangleEnabled?: boolean;
/** True when WASM public-ABI rename pass actually rewrote non-ABI exports. */
readonly wasmExportRenameApplied?: boolean;
/** True when remaining BLA-injected templates still hardcode classic golden constants. */
@@ -52,6 +55,19 @@ const JS_LIKE: ReadonlySet<ArtifactFormat> = new Set([
"electron-asar",
]);
/** Formats that already ship an opt-in sidecarEntangle strip⇒fail hook. */
const SIDECAR_ENTANGLE_FORMATS: ReadonlySet<ArtifactFormat> = new Set([
"javascript",
"typescript",
"html-bundle",
"electron-asar",
"wasm",
"python-source",
"native-elf",
"native-macho",
"native-pe",
]);
/**
* Known product gaps that should annotate / soft-cap a raw gate score.
* Caps are intentionally soft (still allow high Counter-REA scores) so the
@@ -80,6 +96,18 @@ export function collectDefenseScoreGaps(
});
}
if (
SIDECAR_ENTANGLE_FORMATS.has(input.detectedFormat) &&
input.sidecarEntangleEnabled !== true
) {
gaps.push({
id: "sidecar-entangle-not-enabled",
summary:
"Opt-in sidecarEntangle strip⇒fail binding was not enabled (JS/Python preamble, WASM bla.sidecar.v1, or Bun .bla-sidecar.v1.json companion); default remains OFF (issue #40 / DESIGN).",
scoreCap: 93,
});
}
if (input.numericTemplateLeakKnown === true) {
gaps.push({
id: "numeric-template-hygiene-partial",
+52 -3
View File
@@ -37,6 +37,8 @@ import {
evaluateHardenProjectPackagingBlocks,
} from "./packaging-gates.js";
import {
BUN_SIDECAR_COMPANION_SUFFIX,
entangleBunEntryWithSidecars,
entangleJsEntryWithSidecars,
entanglePythonEntryWithSidecars,
entangleWasmEntryWithSidecars,
@@ -364,6 +366,7 @@ function collectRootArtifacts(
if (/\.shielded(\.|$)/i.test(name)) return false;
if (name.endsWith(".bla-manifest.json")) return false;
if (name.endsWith(".bunfs-snapshot")) return false;
if (name.endsWith(".bla-sidecar.v1.json")) return false;
formats.set(full, format);
return true;
},
@@ -1048,7 +1051,7 @@ export function hardenProject(
if (bound) {
const finalized = finalizeSelfSealSelfDigest(bound.code);
writeFileAtomicSync(entryAbs, finalized.content, "utf8", {
allowLinkWriteThrough: options.inPlace === true,
allowLinkWriteThrough: false,
});
}
}
@@ -1087,7 +1090,7 @@ export function hardenProject(
});
if (bound) {
writeFileAtomicSync(entryAbs, bound.code, "utf8", {
allowLinkWriteThrough: options.inPlace === true,
allowLinkWriteThrough: false,
});
}
}
@@ -1126,12 +1129,58 @@ export function hardenProject(
});
if (bound) {
writeFileAtomicSync(entryAbs, bound.bytes, undefined, {
allowLinkWriteThrough: options.inPlace === true,
allowLinkWriteThrough: false,
});
}
}
}
}
// Bun / EOF-preserved native companion note only when no JS/Python/WASM
// entry was bound — binary stays byte-exact; `.bla-sidecar.v1.json`
// binds the sibling `.bunfs-snapshot` planted by protect.
if (!jsEntry && !pyEntry && !wasmEntry) {
const nativeLike = summaries.filter(
(s) =>
s.success &&
(s.format === "native-elf" ||
s.format === "native-macho" ||
s.format === "native-pe"),
);
for (const nativeEntry of nativeLike) {
const entryAbs = join(outputRoot, nativeEntry.relativePath);
const snapshotAbs = `${entryAbs}.bunfs-snapshot`;
if (!existsSync(entryAbs) || !existsSync(snapshotAbs)) continue;
const entryLabel = basename(entryAbs);
const snapshotLabel = `${entryLabel}.bunfs-snapshot`;
const sidecars: { pathLabel: string; bytes: Buffer }[] = [
{ pathLabel: snapshotLabel, bytes: readFileSync(snapshotAbs) },
];
const entryDir = dirname(entryAbs);
for (const s of summaries) {
if (!s.success || s.relativePath === nativeEntry.relativePath) continue;
const abs = join(outputRoot, s.relativePath);
const rel = relative(entryDir, abs).split(sep).join("/");
if (rel.length === 0 || rel.startsWith("..") || !existsSync(abs)) continue;
if (rel === snapshotLabel) continue;
sidecars.push({ pathLabel: rel, bytes: readFileSync(abs) });
}
const bound = entangleBunEntryWithSidecars({
entryPath: entryLabel,
entryBytes: readFileSync(entryAbs),
sidecars,
seedTag: String(options.seed ?? runId),
});
if (bound) {
writeFileAtomicSync(
`${entryAbs}${BUN_SIDECAR_COMPANION_SUFFIX}`,
bound.noteBytes,
"utf8",
{ 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
+39
View File
@@ -92,6 +92,8 @@ import {
} from "./js-wasm-hydrate-dump-lint.js";
import { finalizeSelfSealSelfDigest } from "../shields/runtime/self-seal.js";
import {
BUN_SIDECAR_COMPANION_SUFFIX,
entangleBunEntryWithSidecars,
entangleJsEntryWithSidecars,
entanglePythonEntryWithSidecars,
entangleWasmEntryWithSidecars,
@@ -874,6 +876,43 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
decoyFunctionsInjected += decoy.moduleCount;
chaffPayloadsEmbedded += decoy.chaffPayloadsEmbedded;
counteredVectors.add("bun-standalone-module-graph");
// Opt-in sidecarEntangle: bind the byte-exact binary to its
// `.bunfs-snapshot` (and any explicit sidecarEntanglePaths) via a sibling
// `.bla-sidecar.v1.json` companion note — never rewrite the binary.
if (options.sidecarEntangle === true) {
const entryLabel = basename(absOutput);
const snapshotLabel = `${entryLabel}.bunfs-snapshot`;
const sidecars: { pathLabel: string; bytes: Uint8Array }[] = [
{ pathLabel: snapshotLabel, bytes: decoy.buffer },
];
const base = dirname(absOutput);
for (const rel of options.sidecarEntanglePaths ?? []) {
if (typeof rel !== "string" || rel.length === 0) continue;
if (rel === snapshotLabel || basename(rel) === snapshotLabel) continue;
const abs = isAbsolute(rel) ? rel : join(base, rel);
try {
if (!existsSync(abs)) continue;
sidecars.push({ pathLabel: rel, bytes: readFileSync(abs) });
} catch {
/* skip unreadable */
}
}
const bound = entangleBunEntryWithSidecars({
entryPath: entryLabel,
entryBytes: res.buffer,
sidecars,
seedTag: String(seed),
softFold: options.sidecarEntangleSoftFold === true,
});
if (bound) {
writeProtectedOutput(
`${absOutput}${BUN_SIDECAR_COMPANION_SUFFIX}`,
bound.noteBytes,
"utf8",
);
sidecarEntangleApplied = true;
}
}
}
} else if (format === "sqlite") {
const rawDb = readFileSync(absInput);
+2
View File
@@ -13,6 +13,7 @@ import {
export interface VerifyTargetOptions {
readonly selfSealEnabled?: boolean;
readonly sidecarEntangleEnabled?: boolean;
readonly wasmExportRenameApplied?: boolean;
readonly numericTemplateLeakKnown?: boolean;
}
@@ -119,6 +120,7 @@ export function verifyTarget(
const honesty = applyDefenseScoreHonesty(rawDefenseScore, {
detectedFormat: afterAudit.detectedFormat,
selfSealEnabled: options.selfSealEnabled === true,
sidecarEntangleEnabled: options.sidecarEntangleEnabled === true,
wasmExportRenameApplied: options.wasmExportRenameApplied === true,
numericTemplateLeakKnown: options.numericTemplateLeakKnown === true,
});
+1 -1
View File
@@ -5,7 +5,7 @@ export const BLA_IDENTITY = Object.freeze({
packageAlias: "bla-shield",
cliBinary: "bla",
cliAlias: "bla-agents",
version: "3.1.2",
version: "3.2.0",
slogan: "Poison -> Exhaust -> Hallucinate. Make Reverse Engineering Bankrupt Again.",
counterpart: {
name: "REA",
+12
View File
@@ -492,16 +492,22 @@ export {
generateSidecarJsPreamble,
generateSidecarPythonPreamble,
generateSidecarWasmCustomSection,
generateSidecarBunCompanionNote,
bindSidecarEntanglement,
bindPythonSidecarEntanglement,
bindWasmSidecarEntanglement,
bindBunSidecarEntanglement,
entangleJsEntryWithSidecars,
entanglePythonEntryWithSidecars,
entangleWasmEntryWithSidecars,
entangleBunEntryWithSidecars,
verifyWasmSidecarCustomSection,
verifyBunSidecarCompanionNote,
stripWasmSidecarCustomSection,
SIDECAR_ENTANGLE_SCHEMA,
WASM_SIDECAR_SECTION_NAME,
BUN_SIDECAR_COMPANION_SUFFIX,
BUN_SIDECAR_COMPANION_KIND,
type SidecarEntanglePlan,
type SidecarEntanglePlanOptions,
type SidecarBindingPart,
@@ -519,6 +525,12 @@ export {
type WasmSidecarNote,
type WasmSidecarVerifyOptions,
type WasmSidecarVerifyResult,
type SidecarBunInjectOptions,
type SidecarBunInjectResult,
type SidecarBunBindResult,
type BunSidecarCompanionNote,
type BunSidecarVerifyOptions,
type BunSidecarVerifyResult,
} from "./shields/runtime/sidecar-entangle.js";
export {
+9 -1
View File
@@ -610,7 +610,7 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
{
name: "bla_verify",
description:
"Verifies a BLA-protected artifact against REA's static/semantic resource limits, call-graph tarpit expansion, and token bankruptcy amplification. Pass protection-side honesty metadata (self_seal_enabled / wasm_export_rename_applied) so defenseScore soft-caps reflect what actually ran — same fields defend/harden already forward from ProtectionResult. Optional run_id / summary_path correlate this verify with a prior harden summary (unsigned).",
"Verifies a BLA-protected artifact against REA's static/semantic resource limits, call-graph tarpit expansion, and token bankruptcy amplification. Pass protection-side honesty metadata (self_seal_enabled / sidecar_entangle_enabled / wasm_export_rename_applied) so defenseScore soft-caps reflect what actually ran — same fields defend/harden already forward from ProtectionResult. Optional run_id / summary_path correlate this verify with a prior harden summary (unsigned).",
inputSchema: {
type: "object",
properties: {
@@ -627,6 +627,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
description:
"Honesty metadata: true when protect/defend ran with self-seal. Omitting it soft-caps JS-like scores with self-seal-not-enabled (issue #40.6).",
},
sidecar_entangle_enabled: {
type: "boolean",
description:
"Honesty metadata: true when protect/defend/harden ran with sidecarEntangle. Omitting it soft-caps formats that support strip⇒fail entanglement with sidecar-entangle-not-enabled (issue #40 / DESIGN).",
},
wasm_export_rename_applied: {
type: "boolean",
description:
@@ -1486,6 +1491,9 @@ function verifyHonestyOptions(args: Record<string, unknown>): VerifyTargetOption
...(typeof args.self_seal_enabled === "boolean"
? { selfSealEnabled: args.self_seal_enabled }
: {}),
...(typeof args.sidecar_entangle_enabled === "boolean"
? { sidecarEntangleEnabled: args.sidecar_entangle_enabled }
: {}),
...(typeof args.wasm_export_rename_applied === "boolean"
? { wasmExportRenameApplied: args.wasm_export_rename_applied }
: {}),
+310 -2
View File
@@ -6,7 +6,9 @@
* strip⇒fail rewrite is available via `bindSidecarEntanglement` /
* `generateSidecarJsPreamble` / `generateSidecarPythonPreamble` when
* `sidecarEntangle` is set; WASM uses a `bla.sidecar.v1` custom-section note
* plus host-side `verifyWasmSidecarCustomSection` (see
* plus host-side `verifyWasmSidecarCustomSection`; Bun standalone plants a
* sibling `.bla-sidecar.v1.json` companion note (byte-exact binary preserved)
* verified by `verifyBunSidecarCompanionNote` (see
* `docs/design/sidecar-entry-entanglement.md`).
*
* DEFENSIVE ONLY. Hash-only — no guessing.
@@ -58,7 +60,7 @@ export interface SidecarEntanglePlan {
readonly softFold: boolean;
/** Offline binding id (hash of paths + seedTag) — not the runtime content digest. */
readonly planId: string;
readonly entryHookKind: "js-preamble" | "python-preamble" | "wasm-custom-section" | "unspecified";
readonly entryHookKind: "js-preamble" | "python-preamble" | "wasm-custom-section" | "bun-companion-note" | "asar-archive-note" | "unspecified";
/** `ready` when coverage matrix satisfies refuse predicates; else `incomplete`. */
readonly status: "ready" | "incomplete" | "bound";
readonly note: string;
@@ -965,6 +967,312 @@ export function verifyWasmSidecarCustomSection(
};
}
/** Sibling companion note next to a Bun standalone / native EOF-preserved binary. */
export const BUN_SIDECAR_COMPANION_SUFFIX = ".bla-sidecar.v1.json" as const;
export const BUN_SIDECAR_COMPANION_KIND = "bun-companion-note" as const;
export interface BunSidecarCompanionNote {
readonly schema: typeof SIDECAR_ENTANGLE_SCHEMA;
readonly kind: typeof BUN_SIDECAR_COMPANION_KIND;
readonly digest: string;
readonly seedTag: string;
readonly entryPath: string;
readonly sidecarPaths: readonly string[];
readonly softFold: boolean;
readonly mode: "sidecars";
}
export interface SidecarBunInjectOptions {
readonly entryPath: string;
readonly sidecarPaths: readonly string[];
readonly seedTag?: string;
/** Offline expected digest (from computeSidecarBindingDigest). */
readonly expectedHex: string;
readonly softFold?: boolean;
}
export interface SidecarBunInjectResult {
readonly schema: typeof SIDECAR_ENTANGLE_SCHEMA;
readonly kind: typeof BUN_SIDECAR_COMPANION_KIND;
/** UTF-8 JSON companion note (written next to the binary; binary stays byte-exact). */
readonly noteJson: string;
readonly note: BunSidecarCompanionNote;
readonly expectedHex: string;
readonly expectedU32: number;
readonly softFold: boolean;
readonly sidecarCount: number;
/** Suggested filename suffix relative to the entry basename (`<entry>.bla-sidecar.v1.json`). */
readonly companionSuffix: typeof BUN_SIDECAR_COMPANION_SUFFIX;
}
/**
* Build a Bun companion note that embeds the protect-time sidecar binding
* digest + path labels. The Bun / EOF-preserved binary itself is NEVER
* rewritten (runtime red line — Bun locates the appended graph relative to
* EOF). Strip/alter detection is via host-side `verifyBunSidecarCompanionNote`.
*
* Typical sidecar is `<binary>.bunfs-snapshot` planted by protectNativeBinary.
*
* DEFENSIVE ONLY. Opt-in. No crack / RE advice.
*/
export function generateSidecarBunCompanionNote(
options: SidecarBunInjectOptions,
): SidecarBunInjectResult {
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: BunSidecarCompanionNote = {
schema: SIDECAR_ENTANGLE_SCHEMA,
kind: BUN_SIDECAR_COMPANION_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: BUN_SIDECAR_COMPANION_KIND,
noteJson,
note,
expectedHex,
expectedU32,
softFold,
sidecarCount: sidecars.length,
companionSuffix: BUN_SIDECAR_COMPANION_SUFFIX,
};
}
export interface SidecarBunBindResult {
readonly plan: SidecarEntanglePlan;
readonly digest: SidecarBindingDigest;
readonly inject: SidecarBunInjectResult;
/** Companion note JSON bytes to write next to the entry (entry bytes untouched). */
readonly noteBytes: Buffer;
}
/**
* Plan + bind for a Bun / EOF-preserved native entry: compute the offline
* digest from in-memory sidecar bytes (typically `.bunfs-snapshot`) and return
* a `bound` plan plus companion-note bytes. Uses sidecars-mode digest; the
* entry binary is never mutated.
*/
export function bindBunSidecarEntanglement(
options: SidecarEntanglePlanOptions & {
readonly entryBytes: Uint8Array;
readonly sidecarBytes: readonly Uint8Array[];
},
): SidecarBunBindResult {
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 = generateSidecarBunCompanionNote({
entryPath: options.entryPath,
sidecarPaths: plan.sidecarPaths,
seedTag: plan.seedTag,
expectedHex: digest.hex,
softFold: plan.softFold,
});
const boundPlan: SidecarEntanglePlan = {
...plan,
entryHookKind: "bun-companion-note",
status: "bound",
note: "Bound — Bun companion `.bla-sidecar.v1.json` ready; ship next to the byte-exact binary with `.bunfs-snapshot` sidecars. Strip/alter fails closed via verifyBunSidecarCompanionNote.",
};
return {
plan: boundPlan,
digest,
inject,
noteBytes: Buffer.from(inject.noteJson, "utf8"),
};
}
/**
* Convenience: given final on-disk sidecar bytes + Bun entry bytes, produce
* the companion note. Returns null when there are no sidecars to bind.
* Does NOT rewrite entry bytes.
*/
export function entangleBunEntryWithSidecars(options: {
readonly entryPath: string;
readonly entryBytes: Uint8Array;
readonly sidecars: readonly SidecarBindingPart[];
readonly seedTag?: string;
readonly softFold?: boolean;
}): SidecarBunBindResult | null {
if (options.sidecars.length === 0) return null;
return bindBunSidecarEntanglement({
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 BunSidecarVerifyOptions {
/** Companion note JSON bytes (or parsed UTF-8 string). */
readonly noteBytes: Uint8Array | string;
/**
* Absolute directory used to resolve relative sidecar paths from the note.
* Required when note.sidecarPaths are relative and not supplied in-memory.
*/
readonly baseDir?: string;
/** Optional in-memory sidecar bytes keyed by pathLabel (overrides disk read). */
readonly sidecarBytes?: Readonly<Record<string, Uint8Array>>;
}
export interface BunSidecarVerifyResult {
readonly ok: boolean;
readonly reason?: string;
readonly note?: BunSidecarCompanionNote;
readonly expectedHex?: string;
readonly measuredHex?: string;
readonly measuredU32?: number;
readonly softFold?: boolean;
}
/**
* Host-side strip⇒fail check for Bun companions: parse `.bla-sidecar.v1.json`,
* re-hash sibling sidecar bytes with the same layout as
* `computeSidecarBindingDigest` (sidecars mode), and compare to the embedded
* digest. Missing note / missing sibling / altered sibling ⇒ ok:false.
*
* DEFENSIVE ONLY — for tests, loaders, and harden post-pass verification.
*/
export function verifyBunSidecarCompanionNote(
options: BunSidecarVerifyOptions,
): BunSidecarVerifyResult {
let note: BunSidecarCompanionNote;
try {
const raw =
typeof options.noteBytes === "string"
? options.noteBytes
: Buffer.from(options.noteBytes).toString("utf8");
const parsed = JSON.parse(raw) as BunSidecarCompanionNote;
if (
parsed.schema !== SIDECAR_ENTANGLE_SCHEMA ||
parsed.kind !== BUN_SIDECAR_COMPANION_KIND ||
typeof parsed.digest !== "string" ||
!/^[0-9a-f]{64}$/i.test(parsed.digest)
) {
return { ok: false, reason: "bun companion note malformed" };
}
note = {
schema: SIDECAR_ENTANGLE_SCHEMA,
kind: BUN_SIDECAR_COMPANION_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: "bun companion note is not valid JSON" };
}
const sidecarParts: SidecarBindingPart[] = [];
for (const label of note.sidecarPaths) {
const override = options.sidecarBytes?.[label];
if (override) {
sidecarParts.push({ pathLabel: label, bytes: override });
continue;
}
if (!options.baseDir) {
return {
ok: false,
reason: `sidecar ${label} not supplied and no baseDir to read`,
note,
expectedHex: note.digest,
softFold: note.softFold,
};
}
const abs = isAbsolute(label) ? label : join(options.baseDir, label);
try {
if (!existsSync(abs)) {
sidecarParts.push({
pathLabel: label,
bytes: new TextEncoder().encode(`missing:${label}`),
});
continue;
}
sidecarParts.push({ pathLabel: label, bytes: readFileSync(abs) });
} catch {
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);
+26
View File
@@ -34,11 +34,36 @@ describe("Issue #40.6: defenseScore honesty", () => {
const honesty = applyDefenseScoreHonesty(99, {
detectedFormat: "javascript",
selfSealEnabled: false,
sidecarEntangleEnabled: true,
});
expect(honesty.gaps.map((g) => g.id)).toContain("self-seal-not-enabled");
expect(honesty.cappedScore).toBe(92);
});
it("annotates formats without sidecarEntangle and soft-caps above 93", () => {
const honesty = applyDefenseScoreHonesty(99, {
detectedFormat: "javascript",
selfSealEnabled: true,
sidecarEntangleEnabled: false,
});
expect(honesty.gaps.map((g) => g.id)).toContain("sidecar-entangle-not-enabled");
expect(honesty.cappedScore).toBe(93);
const wasm = applyDefenseScoreHonesty(99, {
detectedFormat: "wasm",
wasmExportRenameApplied: true,
sidecarEntangleEnabled: false,
});
expect(wasm.gaps.map((g) => g.id)).toContain("sidecar-entangle-not-enabled");
expect(wasm.cappedScore).toBe(93);
const on = applyDefenseScoreHonesty(99, {
detectedFormat: "javascript",
selfSealEnabled: true,
sidecarEntangleEnabled: true,
});
expect(on.gaps.map((g) => g.id)).not.toContain("sidecar-entangle-not-enabled");
expect(on.cappedScore).toBe(99);
});
it("does not raise a low raw score when gaps apply", () => {
const honesty = applyDefenseScoreHonesty(40, {
detectedFormat: "wasm",
@@ -108,6 +133,7 @@ describe("Issue #40.6: defenseScore honesty", () => {
const report = verifyTarget(protectedRes.outputPath, undefined, {
wasmExportRenameApplied: true,
selfSealEnabled: true,
sidecarEntangleEnabled: true,
});
expect(
report.defenseScoreGaps?.some((g) => g.id === "wasm-export-rename-pending"),
+211
View File
@@ -0,0 +1,211 @@
import { describe, expect, it } from "vitest";
import {
chmodSync,
existsSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import {
BUN_SIDECAR_COMPANION_KIND,
BUN_SIDECAR_COMPANION_SUFFIX,
bindBunSidecarEntanglement,
computeSidecarBindingDigest,
generateSidecarBunCompanionNote,
SIDECAR_ENTANGLE_SCHEMA,
verifyBunSidecarCompanionNote,
} from "../src/shields/runtime/sidecar-entangle.js";
import { protectTarget } from "../src/engine/protector.js";
import { SeededPrng } from "../src/core/prng.js";
import {
BUN_TRAILER,
generateBunStandaloneDecoyGraph,
} from "../src/shields/formats/bun-standalone.js";
/** Minimal ELF-like bytes ending with a Bun appended-trailer decoy graph. */
function fixtureBunCarrier(): Buffer {
const payload = Buffer.alloc(64, 0x41);
// Offsets(32) + trailer — enough for detectBunStandaloneGraph appended-trailer.
const offsets = Buffer.alloc(32, 0);
offsets.writeBigUInt64LE(BigInt(payload.length), 0);
return Buffer.concat([
Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00]), // ELF64 magic-ish head
Buffer.alloc(120, 0),
payload,
offsets,
BUN_TRAILER,
]);
}
describe("sidecar Bun companion-note strip⇒fail", () => {
it("generateSidecarBunCompanionNote rejects non-hex expected digests", () => {
expect(() =>
generateSidecarBunCompanionNote({
entryPath: "app",
sidecarPaths: ["app.bunfs-snapshot"],
expectedHex: "deadbeef",
}),
).toThrow(/64-char/);
});
it("bindBunSidecarEntanglement leaves entry bytes untouched and emits companion note", () => {
const entry = fixtureBunCarrier();
const snapshot = Buffer.from("decoy-graph-bytes\n");
const before = Buffer.from(entry);
const bound = bindBunSidecarEntanglement({
entryPath: "app",
sidecarPaths: ["app.bunfs-snapshot"],
seedTag: "bun-inject-v1",
entryBytes: entry,
sidecarBytes: [snapshot],
});
expect(bound.plan.schema).toBe(SIDECAR_ENTANGLE_SCHEMA);
expect(bound.plan.status).toBe("bound");
expect(bound.plan.entryHookKind).toBe("bun-companion-note");
expect(bound.inject.kind).toBe(BUN_SIDECAR_COMPANION_KIND);
expect(bound.inject.companionSuffix).toBe(BUN_SIDECAR_COMPANION_SUFFIX);
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(BUN_SIDECAR_COMPANION_KIND);
expect(parsed.digest).toBe(bound.digest.hex);
expect(parsed.sidecarPaths).toEqual(["app.bunfs-snapshot"]);
});
it("digest matches computeSidecarBindingDigest sidecars-mode", () => {
const entry = fixtureBunCarrier();
const snap = Buffer.from("sidecar-payload\n");
const digest = computeSidecarBindingDigest(
{ pathLabel: "app", bytes: entry },
[{ pathLabel: "app.bunfs-snapshot", bytes: snap }],
"parity-bun-v1",
);
const inject = generateSidecarBunCompanionNote({
entryPath: "app",
sidecarPaths: ["app.bunfs-snapshot"],
seedTag: "parity-bun-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 sidecars pass; mutate or strip snapshot fails", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-sidecar-bun-inject-"));
try {
const entry = fixtureBunCarrier();
const snapName = "app.bunfs-snapshot";
const snapBytes = Buffer.from("bun-decoy-graph\n");
writeFileSync(join(dir, snapName), snapBytes);
const bound = bindBunSidecarEntanglement({
entryPath: "app",
sidecarPaths: [snapName],
seedTag: "verify-bun-v1",
entryBytes: entry,
sidecarBytes: [snapBytes],
});
const notePath = join(dir, `app${BUN_SIDECAR_COMPANION_SUFFIX}`);
writeFileSync(notePath, bound.noteBytes);
const ok = verifyBunSidecarCompanionNote({
noteBytes: readFileSync(notePath),
baseDir: dir,
});
expect(ok.ok).toBe(true);
expect(ok.measuredHex).toBe(bound.digest.hex);
writeFileSync(join(dir, snapName), Buffer.from("tampered\n"));
const bad = verifyBunSidecarCompanionNote({
noteBytes: readFileSync(notePath),
baseDir: dir,
});
expect(bad.ok).toBe(false);
expect(bad.reason).toMatch(/mismatch/);
rmSync(join(dir, snapName));
const missing = verifyBunSidecarCompanionNote({
noteBytes: readFileSync(notePath),
baseDir: dir,
});
expect(missing.ok).toBe(false);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("protectTarget with sidecarEntangle plants companion note next to Bun carrier; binary byte-exact", () => {
const hostElf = "/bin/true";
if (!existsSync(hostElf)) return;
const dir = mkdtempSync(join(tmpdir(), "bla-sidecar-bun-protect-"));
try {
const input = join(dir, "app");
const output = join(dir, "out", "app");
const graph = generateBunStandaloneDecoyGraph(
new SeededPrng("bun-entangle-embedded"),
"stealth",
).buffer;
writeFileSync(input, Buffer.concat([readFileSync(hostElf), graph]));
chmodSync(input, 0o755);
const inputBytes = readFileSync(input);
const res = protectTarget({
inputPath: input,
outputPath: output,
intensity: "balanced",
seed: "bun-entangle-protect-1",
sidecarEntangle: true,
});
expect(res.counteredReaVectors).toContain("bun-standalone-module-graph");
expect(res.sidecarEntangle).toBe(true);
expect(existsSync(`${output}.bunfs-snapshot`)).toBe(true);
expect(existsSync(`${output}${BUN_SIDECAR_COMPANION_SUFFIX}`)).toBe(true);
// Runtime red line: Bun/EOF carrier stays byte-exact.
expect(readFileSync(output).equals(inputBytes)).toBe(true);
const verified = verifyBunSidecarCompanionNote({
noteBytes: readFileSync(`${output}${BUN_SIDECAR_COMPANION_SUFFIX}`),
baseDir: join(dir, "out"),
});
expect(verified.ok).toBe(true);
// Strip snapshot ⇒ verify fails.
rmSync(`${output}.bunfs-snapshot`);
expect(
verifyBunSidecarCompanionNote({
noteBytes: readFileSync(`${output}${BUN_SIDECAR_COMPANION_SUFFIX}`),
baseDir: join(dir, "out"),
}).ok,
).toBe(false);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("protectTarget default (sidecarEntangle off) does not plant companion note", () => {
const hostElf = "/bin/true";
if (!existsSync(hostElf)) return;
const dir = mkdtempSync(join(tmpdir(), "bla-sidecar-bun-off-"));
try {
const input = join(dir, "app");
const output = join(dir, "out", "app");
const graph = generateBunStandaloneDecoyGraph(
new SeededPrng("bun-entangle-off"),
"stealth",
).buffer;
writeFileSync(input, Buffer.concat([readFileSync(hostElf), graph]));
protectTarget({
inputPath: input,
outputPath: output,
intensity: "balanced",
seed: "bun-entangle-off-1",
sidecarEntangle: false,
});
expect(existsSync(`${output}.bunfs-snapshot`)).toBe(true);
expect(existsSync(`${output}${BUN_SIDECAR_COMPANION_SUFFIX}`)).toBe(false);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});