Skip to content

armgit / bla

Public Imported from GitHub
0

๐Ÿ›ก๏ธ 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.

fix(self-seal): hard-fail on sibling SHA-256 mismatch (red/blue r4)

qybaihec2ec8681b1fc
diff --git a/.agents/skills/blind-llm-agents/SKILL.md b/.agents/skills/blind-llm-agents/SKILL.md
index f06b22c..61e2522 100644
--- a/.agents/skills/blind-llm-agents/SKILL.md
+++ b/.agents/skills/blind-llm-agents/SKILL.md
@@ -24,7 +24,7 @@ model misjudgment on proprietary logic, or **one-click / ไธ€้”ฎๅŠ ๅ›บ** a build.
Defensive only: protect **their own** artifacts. Refuse crack, RE, bypass PoCs, or
attack playbooks against software they do not own.
-**Principles (red-blue round-1+2+3):** do not ship a stable public WASM ABI without an explicit `wasm_preserve_exports` list; do not leave JS-side independent lane tables โ€” prefer whole-key chained mixing (`bla_lint_lanes` / harden refuse). **Do not** place plaintext seal/catalog JSON (`revision`, salts, certificate ciphertext) beside hardened outputs. Public compare targets must be **one-way** (SHA-256/HMAC/etc.); reversible ARX/Feistel digests as public `revision` are a key-recovery footgun (round-2 break โ€” **closed in round-3** when seal is digests-only). Enforce with `bla_lint_seal` / `bla lint-seal`; bankrupt harden **refuses** unless `allow_plaintext_seal` / `--allow-plaintext-seal`. Round-3 residual **gates**: `bla_lint_wasm_params` / `bla lint-wasm-params` โ€” bankrupt refuses clear `R2SEAL`/`R3PARM`/`R3CIPH`-class carriers unless `allow_wasm_clear_params`; `bla_lint_panel_derive` โ€” maximum/bankrupt **rewrites** `__vaultPanelDerive_*` to `_blaPd_*` unless `allow_stable_panel_derive`; bankrupt harden sets `selfSealRecommended` for multi-artifact trees (never auto for single-file) โ€” prefer **`self_seal`**. Full WASM data-section encryption remains a follow-up.
+**Principles (red-blue round-1+2+3+4):** do not ship a stable public WASM ABI without an explicit `wasm_preserve_exports` list; do not leave JS-side independent lane tables โ€” prefer whole-key chained mixing (`bla_lint_lanes` / harden refuse). **Do not** place plaintext seal/catalog JSON (`revision`, salts, certificate ciphertext) beside hardened outputs. Public compare targets must be **one-way** (SHA-256/HMAC/etc.); reversible ARX/Feistel digests as public `revision` are a key-recovery footgun (round-2 break โ€” **closed in round-3** when seal is digests-only). Enforce with `bla_lint_seal` / `bla lint-seal`; bankrupt harden **refuses** unless `allow_plaintext_seal` / `--allow-plaintext-seal`. Round-3 residual **gates**: `bla_lint_wasm_params` / `bla lint-wasm-params` โ€” bankrupt refuses clear `R2SEAL`/`R3PARM`/`R3CIPH`-class carriers unless `allow_wasm_clear_params`; `bla_lint_panel_derive` โ€” maximum/bankrupt **rewrites** `__vaultPanelDerive_*` to `_blaPd_*` unless `allow_stable_panel_derive`; bankrupt harden sets `selfSealRecommended` for multi-artifact trees (never auto for single-file) โ€” prefer **`self_seal`**. Round-4: AES-CTR sealed WASM param blobs (no clear PARM magic) still leak when the **JS wrap key** is passed to `crypto.createDecipheriv` โ€” treat wrap keys as RE-reachable under Node instrumentation; prefer unwrap inside WASM / white-box, avoid fixed hdr beacons when feasible. `self_seal` now embeds **expected sibling SHA-256 hard-fail** when siblings already exist on disk at protect time (harden processes JS last); opaque-seed entanglement alone does **not** gate entitlement control flow. Panel-local `deriveLocal` + plaintext `panelTokenSha256` remain an offline oracle surface โ€” rename/scrub and avoid shipping digests beside UI when possible.
## Prerequisites (once)
diff --git a/src/engine/harden.ts b/src/engine/harden.ts
index cbb1d94..6531b67 100644
--- a/src/engine/harden.ts
+++ b/src/engine/harden.ts
@@ -370,10 +370,20 @@ export function hardenProject(
? join(absDir, ".bla-hardened")
: join(dirname(absDir), ".bla-hardened")),
);
- const plannedOutputs = discovered.map((artifact) => {
+ let plannedOutputs = discovered.map((artifact) => {
const outputPath = planArtifactOutputPath(artifact, outputRoot);
return { artifact, outputPath, outputExisted: existsSync(outputPath) };
});
+ // When self-seal is on, protect non-JS bindable siblings first so JS entry
+ // modules can embed expected SHA-256 hard-fail hashes (red/blue round-4).
+ if (options.selfSeal === true) {
+ const jsLike = new Set(["javascript", "typescript"]);
+ plannedOutputs = [
+ ...plannedOutputs.filter((p) => !jsLike.has(p.artifact.format)),
+ ...plannedOutputs.filter((p) => jsLike.has(p.artifact.format)),
+ ];
+ }
+
const wouldOverwrite = plannedOutputs.filter((p) => p.outputExisted).map((p) => p.outputPath);
const bindableFormats = new Set(["javascript", "typescript", "wasm", "html-bundle"]);
diff --git a/src/engine/protector.ts b/src/engine/protector.ts
index 490f17e..ee44c7c 100644
--- a/src/engine/protector.ts
+++ b/src/engine/protector.ts
@@ -12,7 +12,7 @@ import {
unlinkSync,
writeFileSync,
} from "node:fs";
-import { basename, dirname, extname, join, resolve } from "node:path";
+import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
import { detectArtifactFormat } from "../core/detector.js";
import { assertSafeOutputPath } from "../core/output-path.js";
import { withLlmDirectives } from "../core/llm-directives.js";
@@ -78,12 +78,40 @@ import {
function selfSealTransformOption(
options: ProtectionOptions,
-): boolean | { readonly siblingPaths: readonly string[] } | undefined {
+ absOutput: string,
+): boolean | {
+ readonly siblingPaths: readonly string[];
+ readonly expectedSiblingSha256?: Readonly<Record<string, string>>;
+ readonly hardFailOnSiblingMismatch?: boolean;
+} | undefined {
if (options.selfSeal !== true) return undefined;
- if (options.selfSealSiblingPaths && options.selfSealSiblingPaths.length > 0) {
- return { siblingPaths: options.selfSealSiblingPaths };
+ if (!options.selfSealSiblingPaths || options.selfSealSiblingPaths.length === 0) {
+ return true;
}
- return true;
+ const siblingPaths = options.selfSealSiblingPaths;
+ const base = dirname(absOutput);
+ const expectedSiblingSha256: Record<string, string> = {};
+ for (const rel of siblingPaths) {
+ if (typeof rel !== "string" || rel.length === 0) continue;
+ const abs = isAbsolute(rel) ? rel : join(base, rel);
+ try {
+ if (!existsSync(abs)) continue;
+ expectedSiblingSha256[rel] = createHash("sha256")
+ .update(readFileSync(abs))
+ .digest("hex");
+ } catch {
+ /* sibling not readable yet โ€” skip expected hash (opaque-seed only) */
+ }
+ }
+ return {
+ siblingPaths,
+ ...(Object.keys(expectedSiblingSha256).length > 0
+ ? {
+ expectedSiblingSha256,
+ hardFailOnSiblingMismatch: true,
+ }
+ : {}),
+ };
}
function applyPanelDeriveRewrite(
@@ -284,7 +312,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
}
}
const panelSafe = applyPanelDeriveRewrite(raw, seed, intensity, options, absInput);
- const selfSealOpt = selfSealTransformOption(options);
+ const selfSealOpt = selfSealTransformOption(options, absOutput);
const transformed = transformJavaScriptWithBlaShield(panelSafe, {
intensity,
seed,
@@ -340,7 +368,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
options,
`${absInput}#script-${currentIndex}`,
);
- const selfSealOpt = selfSealTransformOption(options);
+ const selfSealOpt = selfSealTransformOption(options, absOutput);
const res = transformJavaScriptWithBlaShield(panelSafe, {
intensity,
seed: scriptSeed,
@@ -370,7 +398,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
intensity,
seed: `${seed}:html-bootstrap`,
sourceType: "script",
- ...(selfSealTransformOption(options) !== undefined ? { selfSeal: selfSealTransformOption(options)! } : {}),
+ ...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
});
decoyFunctionsInjected += bootstrapRes.decoyFunctionsInjected;
fakeCrossReferencesCreated += bootstrapRes.fakeCrossReferencesCreated;
@@ -416,7 +444,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
intensity,
seed: `${seed}:${vf.relativePath}`,
filename: vf.relativePath,
- ...(selfSealTransformOption(options) !== undefined ? { selfSeal: selfSealTransformOption(options)! } : {}),
+ ...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
});
const honey = generateHoneySourceMap(
basename(vf.relativePath),
@@ -461,14 +489,14 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
{
intensity,
seed: `${seed}:enclave-decoy`,
- ...(selfSealTransformOption(options) !== undefined ? { selfSeal: selfSealTransformOption(options)! } : {}),
+ ...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
},
);
protectedFiles.push({
relativePath: "enclave/hardware-tee-bridge.js",
content: Buffer.from(decoyBridgeJs.code, "utf8"),
- ...(selfSealTransformOption(options) !== undefined ? { selfSeal: selfSealTransformOption(options)! } : {}),
+ ...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
});
// Flood ASAR Pickle JSON header past REA DEFAULT_ASAR_MAX_HEADER_BYTES at
@@ -714,7 +742,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
intensity,
seed: `${seed}:${entry.name}`,
filename: entry.name,
- ...(selfSealTransformOption(options) !== undefined ? { selfSeal: selfSealTransformOption(options)! } : {}),
+ ...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
});
const honey = generateHoneySourceMap(
entry.name,
diff --git a/src/shields/runtime/self-seal.ts b/src/shields/runtime/self-seal.ts
index 458e257..3d051f1 100644
--- a/src/shields/runtime/self-seal.ts
+++ b/src/shields/runtime/self-seal.ts
@@ -10,6 +10,11 @@
* the opaque-predicate seed. Tampering with sibling modules or attaching an
* inspector changes the digest โ†’ seed parity flips โ†’ opaque happy-path guards fail.
*
+ * When build-time `expectedSiblingSha256` hashes are embedded (harden/protect fills
+ * these from siblings already on disk), runtime **hard-fails** on mismatch. Opaque
+ * seed entanglement alone does not gate entitlement control flow that never reads
+ * the seed (red/blue round-4 finding).
+ *
* DEFENSIVE ONLY. Opt-in. No crack / RE advice. Browser builds soft-skip (digest=0).
*/
@@ -25,6 +30,18 @@ export interface SelfSealOptions {
readonly envFingerprint?: boolean;
/** Override the emitted binding name (tests). */
readonly bindingName?: string;
+ /**
+ * Optional build-time SHA-256 hex of sibling file bytes (keyed by the same
+ * path strings listed in siblingPaths). When present, runtime hard-fails if
+ * a sibling's bytes diverge โ€” opaque-seed entanglement alone does not gate
+ * entitlement control flow (red/blue round-4).
+ */
+ readonly expectedSiblingSha256?: Readonly<Record<string, string>>;
+ /**
+ * When true (default if expectedSiblingSha256 is non-empty), throw on sibling
+ * hash mismatch instead of only poisoning the digest.
+ */
+ readonly hardFailOnSiblingMismatch?: boolean;
}
export interface SelfSealSnippet {
@@ -35,6 +52,9 @@ export interface SelfSealSnippet {
readonly expectedDigestHelperName: string;
readonly siblingCount: number;
readonly envFingerprint: boolean;
+ /** How many sibling expected hashes were embedded for hard-fail. */
+ readonly expectedSiblingHashCount: number;
+ readonly hardFailOnSiblingMismatch: boolean;
}
/**
@@ -57,9 +77,24 @@ export function generateSelfSealSnippet(
const siblings = (options.siblingPaths ?? []).filter(
(p) => typeof p === "string" && p.length > 0,
);
+ const expectedSiblingSha256 = options.expectedSiblingSha256 ?? {};
+ const expectedEntries = Object.entries(expectedSiblingSha256).filter(
+ ([k, v]) =>
+ typeof k === "string" &&
+ k.length > 0 &&
+ typeof v === "string" &&
+ /^[0-9a-f]{64}$/i.test(v),
+ );
+ const hardFailOnSiblingMismatch =
+ options.hardFailOnSiblingMismatch !== undefined
+ ? options.hardFailOnSiblingMismatch
+ : expectedEntries.length > 0;
// Embed sibling list as a JSON array literal โ€” paths are customer-controlled.
const siblingsLiteral = JSON.stringify(siblings);
+ const expectedLiteral = JSON.stringify(
+ Object.fromEntries(expectedEntries.map(([k, v]) => [k, v.toLowerCase()])),
+ );
const lines: string[] = [];
lines.push(`function ${helperName}() {`);
@@ -73,13 +108,27 @@ export function generateSelfSealSnippet(
lines.push(` if (!selfPath && typeof __dirname === "string") selfPath = _path.join(__dirname, "index.js");`);
lines.push(` if (selfPath) { try { h.update(_fs.readFileSync(selfPath)); } catch (_e) {} }`);
lines.push(` var siblings = ${siblingsLiteral};`);
+ lines.push(` var expected = ${expectedLiteral};`);
lines.push(` for (var i = 0; i < siblings.length; i++) {`);
lines.push(` try {`);
- lines.push(` var sp = siblings[i];`);
+ lines.push(` var spKey = siblings[i];`);
+ lines.push(` var sp = spKey;`);
lines.push(` if (!_path.isAbsolute(sp) && typeof __dirname === "string") sp = _path.join(__dirname, sp);`);
+ lines.push(` var sibBuf = _fs.readFileSync(sp);`);
+ lines.push(` var sibHex = _c.createHash("sha256").update(sibBuf).digest("hex");`);
+ lines.push(` if (expected[spKey] && expected[spKey] !== sibHex) {`);
+ if (hardFailOnSiblingMismatch) {
+ lines.push(` throw new Error("integrity check failed");`);
+ } else {
+ lines.push(` digest = 0xffffffff;`);
+ }
+ lines.push(` }`);
lines.push(` h.update(sp);`);
- lines.push(` h.update(_fs.readFileSync(sp));`);
- lines.push(` } catch (_e2) { h.update("missing:" + String(siblings[i])); }`);
+ lines.push(` h.update(sibBuf);`);
+ lines.push(` } catch (_e2) {`);
+ lines.push(` if (_e2 && _e2.message === "integrity check failed") throw _e2;`);
+ lines.push(` h.update("missing:" + String(siblings[i]));`);
+ lines.push(` }`);
lines.push(` }`);
if (envFingerprint) {
lines.push(` var envNote = "";`);
@@ -92,7 +141,10 @@ export function generateSelfSealSnippet(
}
lines.push(` var hex = h.digest("hex");`);
lines.push(` digest = parseInt(hex.slice(0, 8), 16) >>> 0;`);
- lines.push(` } catch (_e4) { digest = 0; }`);
+ lines.push(` } catch (_e4) {`);
+ lines.push(` if (_e4 && _e4.message === "integrity check failed") throw _e4;`);
+ lines.push(` digest = 0;`);
+ lines.push(` }`);
lines.push(` return digest >>> 0;`);
lines.push(`}`);
lines.push(`var ${bindingName} = ${helperName}();`);
@@ -104,6 +156,8 @@ export function generateSelfSealSnippet(
expectedDigestHelperName: helperName,
siblingCount: siblings.length,
envFingerprint,
+ expectedSiblingHashCount: expectedEntries.length,
+ hardFailOnSiblingMismatch,
};
}
diff --git a/tests/self-seal.test.ts b/tests/self-seal.test.ts
index 92aee6f..69164b4 100644
--- a/tests/self-seal.test.ts
+++ b/tests/self-seal.test.ts
@@ -12,6 +12,7 @@ import {
import { transformJavaScriptWithBlaShield } from "../src/shields/javascript/ast-shield.js";
import { parseCliArgs } from "../src/cli.js";
import { DEFAULT_BLA_CONFIG, initBlaConfig, loadBlaConfig } from "../src/core/config.js";
+import { protectTarget } from "../src/engine/protector.js";
describe("self-seal helper (#40.5)", () => {
it("DEFAULT_BLA_CONFIG exposes selfSeal:false (opt-in)", () => {
@@ -175,3 +176,60 @@ describe("self-seal helper (#40.5)", () => {
}
});
});
+
+ it("embeds expected sibling SHA-256 and hard-fails on mismatch (round-4)", () => {
+ const prng = new SeededPrng("self-seal-hardfail-1");
+ const snip = generateSelfSealSnippet(prng, {
+ siblingPaths: ["./core.wasm"],
+ bindingName: "integrityDigestHf",
+ expectedSiblingSha256: {
+ "./core.wasm": "a".repeat(64),
+ },
+ hardFailOnSiblingMismatch: true,
+ });
+ expect(snip.expectedSiblingHashCount).toBe(1);
+ expect(snip.hardFailOnSiblingMismatch).toBe(true);
+ expect(snip.code).toContain("integrity check failed");
+ expect(snip.code).toContain("a".repeat(64));
+ });
+
+ it("protect+self-seal hard-fails when an on-disk sibling is tampered", () => {
+ const dir = mkdtempSync(join(tmpdir(), "bla-selfseal-hf-"));
+ try {
+ const sib = join(dir, "core.wasm");
+ // Minimal wasm magic so file exists for hashing (content arbitrary).
+ writeFileSync(sib, Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0xaa]));
+ const src = [
+ '"use strict";',
+ "function main() { return 42; }",
+ "module.exports = { main };",
+ 'if (require.main === module) console.log(main());',
+ "",
+ ].join("\n");
+ const entry = join(dir, "gate.cjs");
+ writeFileSync(entry, src, "utf8");
+
+ const out = join(dir, "gate.out.cjs");
+ protectTarget({
+ inputPath: entry,
+ outputPath: out,
+ intensity: "balanced",
+ seed: "self-seal-hardfail-protect",
+ selfSeal: true,
+ selfSealSiblingPaths: ["core.wasm"],
+ });
+
+ const intact = spawnSync(process.execPath, [out], { encoding: "utf8" });
+ expect(intact.status, intact.stderr).toBe(0);
+ expect(intact.stdout.trim()).toBe("42");
+
+ writeFileSync(sib, Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0xbb]));
+ const tampered = spawnSync(process.execPath, [out], { encoding: "utf8" });
+ expect(tampered.status, tampered.stdout + tampered.stderr).not.toBe(0);
+ expect((tampered.stderr || "") + (tampered.stdout || "")).toMatch(
+ /integrity check failed/,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });