🛡️ BLA (Blind LLM Agents) — Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, and WebAssembly against AI reverse-engineering agents like REA. Poison -> Exhaust -> Hallucinate.
JavaScript adversarial-aiclaude-codecursorelectron-securityllm-securitymcpmcp-serverobfuscationreverse-engineeringwebassembly
feat(runtime): interleaved self-seal + real sidecar coverage plan
qybaihe5ce33066e504
diff --git a/src/shields/runtime/self-seal.ts b/src/shields/runtime/self-seal.tsindex 3d051f1..f06d9e8 100644--- a/src/shields/runtime/self-seal.ts+++ b/src/shields/runtime/self-seal.ts@@ -1,5 +1,5 @@/**- * Opt-in self-seal / self-integrity helper (issue #40.5).+ * Opt-in self-seal / self-integrity helper (issue #40.5 + Direction-3).** Generates a Node-oriented JS preamble that binds a runtime digest to:* 1. SHA-256 of the current module bytes (when fs + __filename / import.meta are available)@@ -15,11 +15,20 @@* seed entanglement alone does not gate entitlement control flow that never reads* the seed (red/blue round-4 finding).*+ * Direction-3: when `interleavedSites >= 2` (default whenever siblings are present),+ * emit multiple independent measure helpers that each hard-fail on the same sibling+ * hashes. Pair with `buildInterleavedCoverageMatrix` so packaging gates can refuse+ * single-point topologies. Hash-only — no guessing.+ ** DEFENSIVE ONLY. Opt-in. No crack / RE advice. Browser builds soft-skip (digest=0).*/import { createHash } from "node:crypto";import type { SeededPrng } from "../../core/prng.js";+import {+ buildInterleavedCoverageMatrix,+ type CoverageMatrix,+} from "../../engine/integrity-coverage.js";export const SELF_SEAL_SCHEMA = "bla-self-seal/v1" as const;@@ -42,6 +51,15 @@ export interface SelfSealOptions {* hash mismatch instead of only poisoning the digest.*/readonly hardFailOnSiblingMismatch?: boolean;+ /**+ * Number of colocated interleaved check sites (Direction-3). Default: 2 when+ * siblingPaths is non-empty, else 1 (legacy single preamble).+ */+ readonly interleavedSites?: number;+ /** Stable relative path of this checker host (for coverage matrix keys). */+ readonly checkerHostPath?: string;+ /** All protected file nodes (for coverage matrix); defaults to siblingPaths + host. */+ readonly coverageFileNodes?: readonly string[];}export interface SelfSealSnippet {@@ -55,47 +73,19 @@ export interface SelfSealSnippet {/** How many sibling expected hashes were embedded for hard-fail. */readonly expectedSiblingHashCount: number;readonly hardFailOnSiblingMismatch: boolean;+ /** Colocated interleaved site count actually emitted. */+ readonly interleavedSites: number;+ /** Coverage matrix for packaging gates / bla_lint_integrity_coverage. */+ readonly coverageMatrix: CoverageMatrix;}-/**- * Build a deterministic, greppable-marker-free self-seal preamble.- * Identifiers come from the project PRNG so hardened artifacts stay mixed-vocab.- */-export function generateSelfSealSnippet(- prng: SeededPrng,- options: SelfSealOptions = {},-): SelfSealSnippet {- const bindingName =- options.bindingName ??- prng.identifier({ style: "camel", hint: "integrityDigest", entropy: 4 });- const helperName = prng.identifier({- style: "camel",- hint: "measureIntegrity",- entropy: 4,- });- const envFingerprint = options.envFingerprint !== false;- 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()])),- );-+function emitMeasureFunction(+ helperName: string,+ siblingsLiteral: string,+ expectedLiteral: string,+ hardFailOnSiblingMismatch: boolean,+ envFingerprint: boolean,+): string[] {const lines: string[] = [];lines.push(`function ${helperName}() {`);lines.push(` var digest = 0;`);@@ -104,18 +94,28 @@ export function generateSelfSealSnippet(lines.push(` var _fs = require("node:fs");`);lines.push(` var _path = require("node:path");`);lines.push(` var h = _c.createHash("sha256");`);- lines.push(` var selfPath = (typeof __filename === "string" ? __filename : null);`);- 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 selfPath = (typeof __filename === "string" ? __filename : null);`,+ );+ 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 spKey = siblings[i];`);lines.push(` var sp = spKey;`);- lines.push(` if (!_path.isAbsolute(sp) && typeof __dirname === "string") sp = _path.join(__dirname, sp);`);+ 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(+ ` 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");`);@@ -126,7 +126,9 @@ export function generateSelfSealSnippet(lines.push(` h.update(sp);`);lines.push(` h.update(sibBuf);`);lines.push(` } catch (_e2) {`);- lines.push(` if (_e2 && _e2.message === "integrity check failed") throw _e2;`);+ lines.push(+ ` if (_e2 && _e2.message === "integrity check failed") throw _e2;`,+ );lines.push(` h.update("missing:" + String(siblings[i]));`);lines.push(` }`);lines.push(` }`);@@ -135,29 +137,125 @@ export function generateSelfSealSnippet(lines.push(` try {`);lines.push(` envNote += String(process.env.NODE_OPTIONS || "");`);lines.push(` envNote += (process.execArgv || []).join(",");`);- lines.push(` envNote += (/\\[native code\\]/.test(Function.prototype.toString.call(Function.prototype.toString)) ? "N" : "T");`);+ lines.push(+ ` envNote += (/\\[native code\\]/.test(Function.prototype.toString.call(Function.prototype.toString)) ? "N" : "T");`,+ );lines.push(` } catch (_e3) { envNote += "E"; }`);lines.push(` h.update(envNote);`);}lines.push(` var hex = h.digest("hex");`);lines.push(` digest = parseInt(hex.slice(0, 8), 16) >>> 0;`);lines.push(` } catch (_e4) {`);- lines.push(` if (_e4 && _e4.message === "integrity check failed") throw _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}();`);+ return lines;+}++/**+ * Build a deterministic, greppable-marker-free self-seal preamble.+ * Identifiers come from the project PRNG so hardened artifacts stay mixed-vocab.+ */+export function generateSelfSealSnippet(+ prng: SeededPrng,+ options: SelfSealOptions = {},+): SelfSealSnippet {+ const bindingName =+ options.bindingName ??+ prng.identifier({ style: "camel", hint: "integrityDigest", entropy: 4 });+ const envFingerprint = options.envFingerprint !== false;+ 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;++ const interleavedSites =+ options.interleavedSites !== undefined+ ? Math.max(1, Math.floor(options.interleavedSites))+ : siblings.length > 0+ ? 2+ : 1;++ const siblingsLiteral = JSON.stringify(siblings);+ const expectedLiteral = JSON.stringify(+ Object.fromEntries(expectedEntries.map(([k, v]) => [k, v.toLowerCase()])),+ );++ const helperNames: string[] = [];+ const lines: string[] = [];+ for (let site = 0; site < interleavedSites; site++) {+ const helperName = prng.identifier({+ style: "camel",+ hint: site === 0 ? "measureIntegrity" : `measureIntegrity${site}`,+ entropy: 4,+ });+ helperNames.push(helperName);+ lines.push(+ ...emitMeasureFunction(+ helperName,+ siblingsLiteral,+ expectedLiteral,+ hardFailOnSiblingMismatch,+ envFingerprint,+ ),+ );+ }++ // Invoke every site; fold digests so NOP-ing one still leaves others running+ // (each already hard-fails independently on sibling mismatch before return).+ if (interleavedSites === 1) {+ lines.push(`var ${bindingName} = ${helperNames[0]}();`);+ } else {+ const parts = helperNames.map((h) => `${h}()`).join(" ^ ");+ lines.push(`var ${bindingName} = (${parts}) >>> 0;`);+ }++ const host = options.checkerHostPath ?? "entry.js";+ const fileNodes =+ options.coverageFileNodes && options.coverageFileNodes.length > 0+ ? options.coverageFileNodes+ : [...siblings, host];+ const expectedForMatrix: Record<string, string> = {+ ...Object.fromEntries(+ expectedEntries.map(([k, v]) => [k, v.toLowerCase()]),+ ),+ };+ // Host / colocated-site hashes are filled by finalizeCoverageMatrixHashes after+ // the checker file is written — never invent placeholder digests.++ const coverageMatrix = buildInterleavedCoverageMatrix({+ fileNodes,+ checkerHosts: [host],+ expectedSha256: expectedForMatrix,+ colocatedSites: interleavedSites,+ });return {schema: SELF_SEAL_SCHEMA,code: lines.join("\n"),bindingName,- expectedDigestHelperName: helperName,+ expectedDigestHelperName: helperNames[0]!,siblingCount: siblings.length,envFingerprint,expectedSiblingHashCount: expectedEntries.length,hardFailOnSiblingMismatch,+ interleavedSites,+ coverageMatrix,};}diff --git a/src/shields/runtime/sidecar-entangle.ts b/src/shields/runtime/sidecar-entangle.tsindex c292090..dfe795a 100644--- a/src/shields/runtime/sidecar-entangle.ts+++ b/src/shields/runtime/sidecar-entangle.ts@@ -1,14 +1,26 @@/**- * Sidecar / entry entanglement planner stub (issue #40 / STATE).+ * Sidecar / entry entanglement planner (issue #40 / Direction-3).*- * Full binary rewriting is intentionally deferred — see- * `docs/design/sidecar-entry-entanglement.md`. This module returns a typed plan- * agents can inspect before enabling the future opt-in flag.+ * Elevates the former planned-stub into a coverage-matrix planner that assigns+ * interleaved SHA-256 check edges across entry + sidecar paths. Full binary+ * rewriting of non-JS sidecars remains out of scope (see+ * `docs/design/sidecar-entry-entanglement.md`); JS checker hosts receive+ * `generateSelfSealSnippet` payloads via protect/harden.*- * DEFENSIVE ONLY.+ * DEFENSIVE ONLY. Hash-only — no guessing.*/+import { existsSync, readFileSync } from "node:fs";import { createHash } from "node:crypto";+import { join, isAbsolute } from "node:path";+import {+ INTEGRITY_COVERAGE_SCHEMA,+ buildInterleavedCoverageMatrix,+ evaluateCoverageMatrix,+ finalizeCoverageMatrixHashes,+ type CoverageEvaluation,+ type CoverageMatrix,+} from "../../engine/integrity-coverage.js";export const SIDECAR_ENTANGLE_SCHEMA = "bla-sidecar-entangle/v1" as const;@@ -18,6 +30,13 @@ export interface SidecarEntanglePlanOptions {readonly seedTag?: string;/** When true, plan folds the binding into self-seal / opaque seed rather than a hard throw. */readonly softFold?: boolean;+ /**+ * Optional on-disk bytes (or absolute paths to read) keyed by the same relative+ * paths listed in entry/sidecars — used to finalize expectedSha256.+ */+ readonly fileBytes?: Readonly<Record<string, Buffer | string>>;+ /** Absolute directory used to resolve relative paths when reading hashes. */+ readonly baseDir?: string;}export interface SidecarEntanglePlan {@@ -30,8 +49,11 @@ export interface SidecarEntanglePlan {/** 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 status: "planned-stub";+ /** `ready` when coverage matrix satisfies refuse predicates; else `incomplete`. */+ readonly status: "ready" | "incomplete";readonly note: string;+ readonly coverageMatrix: CoverageMatrix;+ readonly coverageEvaluation: CoverageEvaluation;}function guessHookKind(entryPath: string): SidecarEntanglePlan["entryHookKind"] {@@ -42,8 +64,13 @@ function guessHookKind(entryPath: string): SidecarEntanglePlan["entryHookKind"]return "unspecified";}+function isJsChecker(path: string): boolean {+ return /\.(mjs|cjs|js|ts|tsx|jsx)$/i.test(path);+}+/**- * Plan a sidecar↔entry entanglement binding. Does not read or rewrite files.+ * Plan interleaved sidecar↔entry entanglement as a coverage matrix.+ * Reads optional on-disk bytes to finalize hashes when `baseDir` + paths exist.*/export function planSidecarEntanglement(options: SidecarEntanglePlanOptions,@@ -59,6 +86,69 @@ export function planSidecarEntanglement(.digest("hex").slice(0, 16);+ const fileNodes = [...new Set([options.entryPath, ...sidecars])].sort();+ const checkerHosts = fileNodes.filter(isJsChecker);+ // Prefer entry as a checker host even if list empty.+ const hosts =+ checkerHosts.length > 0+ ? checkerHosts+ : isJsChecker(options.entryPath)+ ? [options.entryPath]+ : [];++ let expected: Record<string, string> = {};+ const supplied = options.fileBytes ?? {};+ for (const [k, v] of Object.entries(supplied)) {+ expected[k] = createHash("sha256")+ .update(typeof v === "string" ? Buffer.from(v) : v)+ .digest("hex");+ }++ // Optionally read from disk when baseDir is provided.+ if (options.baseDir) {+ for (const rel of fileNodes) {+ if (expected[rel]) continue;+ const abs = isAbsolute(rel) ? rel : join(options.baseDir, rel);+ try {+ if (existsSync(abs)) {+ expected[rel] = createHash("sha256")+ .update(readFileSync(abs))+ .digest("hex");+ }+ } catch {+ /* leave missing — evaluate will refuse */+ }+ }+ }++ let matrix = buildInterleavedCoverageMatrix({+ fileNodes,+ checkerHosts: hosts.length > 0 ? hosts : [options.entryPath],+ expectedSha256: expected,+ colocatedSites: 2,+ });+ matrix = finalizeCoverageMatrixHashes(matrix, {+ ...Object.fromEntries(+ Object.entries(supplied).map(([k, v]) => [+ k,+ typeof v === "string" ? Buffer.from(v) : v,+ ]),+ ),+ });+ // Re-apply disk hashes into finalize if we computed expected above.+ if (Object.keys(expected).length > 0) {+ matrix = {+ schema: INTEGRITY_COVERAGE_SCHEMA,+ nodes: matrix.nodes,+ edges: matrix.edges,+ expectedSha256: { ...matrix.expectedSha256, ...expected },+ };+ matrix = finalizeCoverageMatrixHashes(matrix, {});+ }++ const coverageEvaluation = evaluateCoverageMatrix(matrix);+ const status = coverageEvaluation.ok ? "ready" : "incomplete";+return {schema: SIDECAR_ENTANGLE_SCHEMA,entryPath: options.entryPath,@@ -68,8 +158,11 @@ export function planSidecarEntanglement(softFold: options.softFold === true,planId,entryHookKind: guessHookKind(options.entryPath),- status: "planned-stub",- note:- "Stub planner only — enable full rewrite when sidecarEntangle lands in protect paths. See docs/design/sidecar-entry-entanglement.md.",+ status,+ note: coverageEvaluation.ok+ ? "Interleaved coverage matrix ready — wire checkers via self-seal / protect."+ : `Coverage incomplete: ${coverageEvaluation.reasons.join(", ")}. ${coverageEvaluation.oneLineAdvice}`,+ coverageMatrix: matrix,+ coverageEvaluation,};}diff --git a/tests/sidecar-entangle-plan.test.ts b/tests/sidecar-entangle-plan.test.tsindex d35d4c7..d985c6b 100644--- a/tests/sidecar-entangle-plan.test.ts+++ b/tests/sidecar-entangle-plan.test.ts@@ -3,25 +3,45 @@ import {planSidecarEntanglement,SIDECAR_ENTANGLE_SCHEMA,} from "../src/shields/runtime/sidecar-entangle.js";+import { evaluateCoverageMatrix } from "../src/engine/integrity-coverage.js";-describe("sidecar entry entanglement planner stub", () => {- it("returns a bla-sidecar-entangle/v1 plan with stable planId", () => {+describe("sidecar entry entanglement planner (Direction-3)", () => {+ it("returns a bla-sidecar-entangle/v1 plan with stable planId + coverage matrix", () => {+ const fileBytes = {+ "dist/main.js": Buffer.from("entry-body-v1"),+ "dist/main.js.bla-sidecar": Buffer.from("sidecar-a"),+ "dist/assets.chaff": Buffer.from("chaff"),+ };const a = planSidecarEntanglement({entryPath: "dist/main.js",sidecarPaths: ["dist/main.js.bla-sidecar", "dist/assets.chaff"],seedTag: "test-seed",+ fileBytes,});const b = planSidecarEntanglement({entryPath: "dist/main.js",sidecarPaths: ["dist/main.js.bla-sidecar", "dist/assets.chaff"],seedTag: "test-seed",+ fileBytes,});expect(a.schema).toBe(SIDECAR_ENTANGLE_SCHEMA);- expect(a.status).toBe("planned-stub");+ expect(a.status).toBe("ready");expect(a.entryHookKind).toBe("js-preamble");expect(a.planId).toBe(b.planId);expect(a.digestAlgorithm).toBe("sha256");expect(a.sidecarPaths).toHaveLength(2);+ expect(a.coverageMatrix.schema).toBe("bla-integrity-coverage/v1");+ expect(evaluateCoverageMatrix(a.coverageMatrix).ok).toBe(true);+ });++ it("marks incomplete when hashes are missing", () => {+ const plan = planSidecarEntanglement({+ entryPath: "dist/main.js",+ sidecarPaths: ["dist/sib.wasm"],+ seedTag: "no-bytes",+ });+ expect(plan.status).toBe("incomplete");+ expect(plan.coverageEvaluation.shouldRefuseBankrupt).toBe(true);});it("guesses python / wasm hook kinds", () => {