π‘οΈ 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
fix(js): de-literalize integers at bankrupt/maximum (#40) (#43)
Timo Zhangeec925ed095d
diff --git a/src/engine/verifier.ts b/src/engine/verifier.tsindex f3c0b3b..fd07aa0 100644--- a/src/engine/verifier.ts+++ b/src/engine/verifier.ts@@ -91,6 +91,10 @@ export function verifyTarget(});const passedCount = checks.filter((c) => c.passed).length;+ // defenseScore measures Counter-REA gate pass-rate + exposure drop only.+ // It is NOT a claim of cryptographic preimage hardness: numeric-literal+ // coverage, WASM export rename, opaque-predicate seed strength, and+ // opt-in self-seal helpers are tracked separately (issue #40).const defenseScore = Math.round((passedCount / checks.length) * 70 + Math.max(0, (100 - afterAudit.exposureScore) * 0.3),);diff --git a/src/shields/javascript/ast-shield.ts b/src/shields/javascript/ast-shield.tsindex e673653..028bd80 100644--- a/src/shields/javascript/ast-shield.ts+++ b/src/shields/javascript/ast-shield.ts@@ -368,6 +368,42 @@ function buildOpaqueTrueAst(return t.binaryExpression("===", bitAnd, t.numericLiteral(1));}+/**+ * Rewrite an integer literal into an opaque expression that still evaluates to+ * the same Number in O(1). The original bit pattern (e.g. 0x9e3779b9) does not+ * survive as a NumericLiteral, closing the bankrupt cleartext-constant probe+ * tracked in issue #40 while keeping runtime equivalence.+ */+function buildOpaqueIntegerAst(+ value: number,+ prng: SeededPrng,+ seedIdentifierName: string,+): t.Expression {+ const abs = Math.abs(value);+ const split =+ abs <= 1 ? 1 : prng.nextInt(1, Math.min(0xffff, Math.max(1, abs - 1)));+ const left = value > 0 ? value - split : value + split;+ const right = value > 0 ? split : -split;+ const sum = t.binaryExpression(+ "+",+ t.numericLiteral(left),+ t.numericLiteral(right),+ );+ const decoy = value ^ (prng.nextInt(1, 0x7fff) | 1);+ if (prng.nextInt(0, 1) === 0) {+ return t.conditionalExpression(+ buildOpaqueTrueAst(prng, seedIdentifierName),+ sum,+ t.numericLiteral(decoy),+ );+ }+ return t.conditionalExpression(+ buildOpaqueFalseAst(prng, seedIdentifierName),+ t.numericLiteral(decoy),+ sum,+ );+}+const RENAME_RESERVED = new Set(["exports", "module", "require", "arguments", "undefined", "NaN", "Infinity","globalThis", "global", "window", "self", "console", "Math", "Object", "Array",@@ -814,6 +850,54 @@ export function transformJavaScriptWithBlaShield(path.skip();primitiveCandidateBranchesCreated += 256;},+ NumericLiteral(path) {+ // Issue #40: bankrupt/maximum must not leave schedule / magic integers+ // bit-identical in the hardened output (probe: 0x9e3779b9).+ if (intensity !== "bankrupt" && intensity !== "maximum") {+ return;+ }+ if (+ (loader === "ts" || loader === "tsx") &&+ isInsideTsConstAssertion(path)+ ) {+ return;+ }+ const val = path.node.value;+ if (!Number.isInteger(val)) return;+ if (!Number.isSafeInteger(val)) return;+ // Leave tiny integers alone (loop bounds / booleans-as-numbers); rewrite+ // everything at |n| >= 16 so golden-ratio / salt / schedule constants go.+ if (Math.abs(val) < 16) return;+ const parent = path.parent;+ if (+ t.isObjectProperty(parent) &&+ parent.key === path.node &&+ !parent.computed+ ) {+ return;+ }+ if (+ t.isTSLiteralType(parent) ||+ t.isTSEnumMember(parent) ||+ t.isImportAttribute(parent)+ ) {+ return;+ }+ if (+ path.findParent(+ (p) =>+ p.isTSType() ||+ p.isTSEnumDeclaration() ||+ p.isTSModuleDeclaration() ||+ p.isImportAttribute(),+ )+ ) {+ return;+ }+ path.replaceWith(buildOpaqueIntegerAst(val, prng, seedVarName));+ path.skip();+ primitiveCandidateBranchesCreated += 64;+ },});const effectiveCarrier: "module" | "script" | "commonjs" =diff --git a/src/ui/reporter.ts b/src/ui/reporter.tsindex c70e3d4..01e6d71 100644--- a/src/ui/reporter.ts+++ b/src/ui/reporter.ts@@ -138,6 +138,7 @@ export function formatVerificationReport(report: VerificationReport): string {`${ANSI.bold}Verification Target:${ANSI.reset} ${report.targetPath}`,`${ANSI.bold}Defense Score:${ANSI.reset} ${report.overallPassed ? ANSI.green : ANSI.yellow}${ANSI.bold}${report.defenseScore}/100${ANSI.reset} (${report.overallPassed ? "ALL COUNTER-REA GATES PASSED" : "PARTIAL PASS"})`,`${ANSI.bold}Amplification:${ANSI.reset} ${ANSI.cyan}${report.tokenAmplificationFactor}x tokens${ANSI.reset} | ${ANSI.cyan}${report.costAmplificationFactor}x API cost${ANSI.reset} | ${ANSI.cyan}${report.obligationGraphExpansionFactor}x call-graph expansion${ANSI.reset}`,+ `${ANSI.dim}Score scope: Counter-REA gates + exposure drop β not a preimage-hardness claim (see issue #40).${ANSI.reset}`,"",`${ANSI.bold}Counter-REA Invariant Checks:${ANSI.reset}`,];@@ -235,6 +236,7 @@ export function formatOneClickDefenseReport(rep: OneClickDefenseReport): string` ${ANSI.bold}Input Target:${ANSI.reset} ${rep.inputPath}`,` ${ANSI.bold}Hardened Output:${ANSI.reset} ${ANSI.cyan}${rep.outputPath}${ANSI.reset}`,` ${ANSI.bold}Intensity Preset:${ANSI.reset} ${ANSI.magenta}${rep.intensity.toUpperCase()}${ANSI.reset} (Defense Score: ${ANSI.green}${ANSI.bold}${rep.verification.defenseScore}/100${ANSI.reset})`,+ ` ${ANSI.dim}Score scope: Counter-REA gates + exposure drop β not a preimage-hardness claim (see issue #40).${ANSI.reset}`,"",`${ANSI.bold}${ANSI.blue}ββ 5-Stage Automated Counter-REA Pipeline ββββββββββββββββββββββββββββββββββββββ${ANSI.reset}`,];diff --git a/tests/crackme-v6.test.ts b/tests/crackme-v6.test.tsindex 94bb596..aecbe86 100644--- a/tests/crackme-v6.test.ts+++ b/tests/crackme-v6.test.ts@@ -114,9 +114,10 @@ describe("CrackMe v6 (harden-native)", () => {const ra = await lib.hardenChallenge({ key: lib.FIXTURE_KEY, flag: lib.FIXTURE_FLAG, outDir: a });const rb = await lib.hardenChallenge({ key: lib.FIXTURE_KEY, flag: lib.FIXTURE_FLAG, outDir: b });expect(ra.artifacts).toEqual(rb.artifacts);- // Same public template + panel + wasm as the release β identical panel/wasm digests.- expect(ra.artifacts["panel.html"].sha256).toBe(seal.artifacts["panel.html"].sha256);- expect(ra.artifacts["core.wasm"].sha256).toBe(seal.artifacts["core.wasm"].sha256);+ // Release digests stay pinned by SEAL + the committed-artifacts test above.+ // Intentional shield-pipeline changes (e.g. issue #40 numeric de-literalization)+ // legitimately drift re-harden output from the frozen v6 release bundle, so we+ // no longer require panel/wasm sha256 == seal here.} finally {rmSync(a, { recursive: true, force: true });rmSync(b, { recursive: true, force: true });diff --git a/tests/numeric-literal-obfuscation.test.ts b/tests/numeric-literal-obfuscation.test.tsnew file mode 100644index 0000000..68d52af--- /dev/null+++ b/tests/numeric-literal-obfuscation.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from "vitest";+import * as vm from "node:vm";+import { transformJavaScriptWithBlaShield } from "../src/shields/javascript/ast-shield.js";++describe("Issue #40: numeric literal de-literalization", () => {+ it("removes bit-identical customer magic integers at bankrupt while preserving runtime values", () => {+ const source = `+ function schedule(x) {+ const GOLDEN = 0x9e3779b9;+ const SALT = 109551763;+ return (Math.imul(x ^ GOLDEN, SALT) >>> 0) + 640 + 1;+ }+ module.exports = { schedule };+ `;+ const result = transformJavaScriptWithBlaShield(source, {+ intensity: "bankrupt",+ seed: "issue-40-numeric-probe",+ sourceType: "commonjs",+ });++ // Customer schedule/salt constants must not survive as NumericLiterals.+ expect(result.code).not.toMatch(/109551763/);+ expect(result.code).not.toMatch(/\b2654435769\b/);+ // Direct assignment form of the classic probe must be gone (BLA's own+ // injected runtime shields may still mention 0x9e3779b9 in templates β+ // tracked as follow-up template hygiene, not this transform).+ expect(result.code).not.toMatch(/GOLDEN\s*=\s*0x9e3779b9/i);+ expect(result.code).not.toMatch(/GOLDEN\s*=\s*2654435769/);++ const run = (code: string) => {+ const mod = { exports: {} as { schedule: (x: number) => number } };+ vm.runInContext(+ code,+ vm.createContext({+ module: mod,+ exports: mod.exports,+ Math,+ Object,+ Array,+ String,+ Number,+ Boolean,+ Map,+ Set,+ process: undefined,+ Date,+ }),+ { timeout: 3000 },+ );+ return mod.exports;+ };++ const orig = run(source);+ const prot = run(result.code);+ for (const x of [0, 1, 7, 99, 0x1234, 0xffffff]) {+ expect(prot.schedule(x)).toEqual(orig.schedule(x));+ }+ });++ it("leaves tiny integers alone and does not rewrite at balanced intensity", () => {+ const source = `+ const n = 0x9e3779b9;+ const tiny = 3;+ module.exports = { n, tiny };+ `;+ const balanced = transformJavaScriptWithBlaShield(source, {+ intensity: "balanced",+ seed: "issue-40-balanced",+ sourceType: "commonjs",+ });+ expect(balanced.code).toMatch(/2654435769|0x9e3779b9/i);++ const bankrupt = transformJavaScriptWithBlaShield(source, {+ intensity: "bankrupt",+ seed: "issue-40-tiny",+ sourceType: "commonjs",+ });+ // User binding rewritten β no bare assignment of the classic constant.+ expect(bankrupt.code).not.toMatch(/\bn\s*=\s*0x9e3779b9/i);+ expect(bankrupt.code).not.toMatch(/\bn\s*=\s*2654435769\b/);+ });+});