🛡️ 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): add synchronized shadow heap churn and split-share rolling XOR shield against runtime memory diffing
qybaihec981e5bca1d2
diff --git a/src/identity.ts b/src/identity.tsindex d9e0733..9a3929a 100644--- a/src/identity.ts+++ b/src/identity.ts@@ -67,4 +67,22 @@ export const REA_INTERNAL_LIMITS = Object.freeze({WASM_INTERFACE_REPRESENTATION_BYTES: 33_554_432,/** .NET Managed metadata representation budget (`MAX_METADATA_REPRESENTATION_BYTES` = 64 MiB). */MANAGED_METADATA_REPRESENTATION_BYTES: 67_108_864,+ /** LLDB native call tracer aggregate JSON byte cap (`MAX_TRACE_BYTES` = 8 MiB in `bridge/native/rea_lldb_tracer.py:30`). */+ LLDB_MAX_TRACE_BYTES: 8_388_608,+ /** LLDB native call tracer aggregate frame cap (`MAX_TRACE_FRAMES` = 65,536 in `bridge/native/rea_lldb_tracer.py:31`). */+ LLDB_MAX_TRACE_FRAMES: 65_536,+ /** LLDB native call tracer non-breakpoint stop cap (`MAX_OTHER_STOPS` = 256 in `bridge/native/rea_lldb_tracer.py:29`). */+ LLDB_MAX_OTHER_STOPS: 256,+ /** LLDB Objective-C selector C-string read cap (`MAX_SELECTOR_BYTES` = 1024 in `bridge/native/rea_lldb_tracer.py:27`). */+ LLDB_MAX_SELECTOR_BYTES: 1_024,+ /** GDB session command output byte cap (`MAX_COMMAND_OUTPUT_BYTES` = 16 MiB in `src/gdb/GdbSessionManager.ts:422`). */+ GDB_MAX_COMMAND_OUTPUT_BYTES: 16_777_216,+ /** GDB session MI output record cap (`MAX_COMMAND_OUTPUT_RECORDS` = 16,384 in `src/gdb/GdbSessionManager.ts:423`). */+ GDB_MAX_COMMAND_OUTPUT_RECORDS: 16_384,+ /** Rizin debugger session frame byte cap (`MAX_FRAME_BYTES` = 16 MiB in `src/rizin/RizinDebugSessionManager.ts:52`). */+ RIZIN_MAX_FRAME_BYTES: 16_777_216,+ /** Rizin debugger command frame count cap (`MAX_COMMAND_FRAMES` = 4,096 in `src/rizin/RizinDebugSessionManager.ts:55`). */+ RIZIN_MAX_COMMAND_FRAMES: 4_096,+ /** Environment differential comparison per-step diff cap (`STEP_DIFFERENCE_LIMIT` = 20 in `src/application/environment/environmentCompareDiff.ts:52`). */+ ENVIRONMENT_COMPARE_STEP_DIFF_LIMIT: 20,});diff --git a/src/index.ts b/src/index.tsindex e0f282e..bb55cbf 100644--- a/src/index.ts+++ b/src/index.ts@@ -12,6 +12,13 @@ export {export {generateRuntimeDeceptionSnippet,} from "./shields/runtime/runtime-shield.js";+export {+ generateShadowHeapChurnShield,+ encodeSplitShareString,+ generateSplitShareRuntimeHelper,+ type ShadowHeapChurnShieldResult,+ type SplitShareEncodedString,+} from "./shields/runtime/memory-diff-shield.js";export {transformJavaScriptWithBlaShield,InvalidJavaScriptCarrierError,diff --git a/src/shields/exhaustion/frida-capture-saturation.ts b/src/shields/exhaustion/frida-capture-saturation.tsindex 845ee2a..dc81641 100644--- a/src/shields/exhaustion/frida-capture-saturation.ts+++ b/src/shields/exhaustion/frida-capture-saturation.ts@@ -17,15 +17,20 @@ export interface FridaCaptureSaturationResult {readonly code: string;readonly payloadJsonDepth: number;readonly messageTextBytes: number;+ readonly realmAgnosticRingSlots: number;readonly triggeredFridaLimits: readonly ("json_depth" | "message_text")[];}/**- * Targets `morluto/rea/src/frida/fridaCaptureLimits.ts`:- * When Frida (`globalThis.Frida` or `globalThis.Interceptor`) hooks the process,- * wraps decoy telemetry payloads in > 64 levels of JSON nesting (`MAX_JSON_DEPTH = 64`)- * and > 32 KiB message descriptions (`MAX_MESSAGE_TEXT_BYTES = 32768`), forcing REA's- * Frida capture collector to drop and truncate observations.+ * Targets `morluto/rea/src/frida/fridaCaptureLimits.ts` AND realm-isolated Frida Gum /+ * GDB / Rizin memory probes:+ * 1. Because Frida's `Frida` and `Interceptor` globals live inside Frida's isolated Gum+ * script realm (not the target's `globalThis`), this shield does NOT rely solely on+ * `globalThis.Frida`. Instead, it maintains an always-active, realm-agnostic decoy+ * ring buffer in memory (`_blaFridaRealmRing_<tag>`) and generates > 64 levels of JSON+ * nesting (`MAX_JSON_DEPTH = 64`) plus > 32 KiB message descriptions+ * (`MAX_MESSAGE_TEXT_BYTES = 32768`), forcing REA's Frida capture collector to drop+ * and truncate observations.*/export function generateFridaCaptureSaturation(prng: SeededPrng,@@ -36,13 +41,20 @@ export function generateFridaCaptureSaturation((intensity === "stealth" ? 4 : intensity === "balanced" ? 8 : 16);const messageTextBytes =REA_FRIDA_CAPTURE_LIMITS.MAX_MESSAGE_TEXT_BYTES + 2048;+ const realmAgnosticRingSlots =+ intensity === "stealth" ? 8 : intensity === "balanced" ? 16 : 32;const tag = prng.hex(3);const code = [- `function _blaFridaCaptureSaturator_${tag}() {`,+ `const _blaFridaRealmRing_${tag} = { epoch: 0x${prng.hex(6)}, slots: new Array(${realmAgnosticRingSlots}).fill(0) };`,+ `function _blaFridaCaptureSaturator_${tag}(forceEnvelope) {`,+ ` _blaFridaRealmRing_${tag}.epoch = (_blaFridaRealmRing_${tag}.epoch + 0x9e3779b9) & 0x7fffffff;`,+ ` for (let _s = 0; _s < _blaFridaRealmRing_${tag}.slots.length; _s++) {`,+ ` _blaFridaRealmRing_${tag}.slots[_s] = (_blaFridaRealmRing_${tag}.epoch ^ (_s * 0x85ebca6b)) & 0x7fffffff;`,+ ` }`,` const _g = typeof globalThis !== "undefined" ? globalThis : {};`,- ` if (!_g.Frida && !_g.Interceptor) return null;`,- ` let _nested = { enclaveSealed: true, slot: "${tag}" };`,+ ` if (forceEnvelope === false && !_g.Frida && !_g.Interceptor) return _blaFridaRealmRing_${tag};`,+ ` let _nested = { enclaveSealed: true, slot: "${tag}", epoch: _blaFridaRealmRing_${tag}.epoch };`,` for (let d = 0; d < ${payloadJsonDepth}; d++) {`,` _nested = { frame: d, child: _nested };`,` }`,@@ -57,6 +69,7 @@ export function generateFridaCaptureSaturation(code,payloadJsonDepth,messageTextBytes,+ realmAgnosticRingSlots,triggeredFridaLimits: ["json_depth", "message_text"],};}diff --git a/src/shields/exhaustion/rea-budget-matrix.ts b/src/shields/exhaustion/rea-budget-matrix.tsindex cf1f4dd..c281303 100644--- a/src/shields/exhaustion/rea-budget-matrix.ts+++ b/src/shields/exhaustion/rea-budget-matrix.ts@@ -117,6 +117,56 @@ export const REA_BUDGET_BREAKER_MATRIX: readonly ReaSubsystemBudgetSpec[] = [counterStrategy:"Detect CDP/Inspector runtime attachment and serve high-volume decoy script modules to exhaust passive source collection.",},+ {+ id: "lldb-trace-frames",+ reaSourceFile: "bridge/native/rea_lldb_tracer.py:31",+ constantName: "MAX_TRACE_FRAMES",+ hardLimit: 65_536,+ unit: "states",+ failureClassOrStatus: 'outcome: "resource-limit" (process.Kill())',+ counterStrategy:+ "Inject high-frequency decoy native call frames and deep backtraces so observe_native_calls hits 65,536 frames or 8 MiB and terminates the traced target.",+ },+ {+ id: "lldb-other-stops",+ reaSourceFile: "bridge/native/rea_lldb_tracer.py:29",+ constantName: "MAX_OTHER_STOPS",+ hardLimit: 256,+ unit: "states",+ failureClassOrStatus: 'outcome: "stop-limit" (process.Kill())',+ counterStrategy:+ "Emit >= 256 benign non-breakpoint stop observations so LLDB batch tracing aborts with stop-limit.",+ },+ {+ id: "gdb-command-output-records",+ reaSourceFile: "src/gdb/GdbSessionManager.ts:423",+ constantName: "MAX_COMMAND_OUTPUT_RECORDS",+ hardLimit: 16_384,+ unit: "states",+ failureClassOrStatus: "AnalysisResourceConstraintError (output truncated)",+ counterStrategy:+ "Churn hundreds of shadow heap slots on every call so GDB watchpoint/memory dump records exceed 16,384 MI lines.",+ },+ {+ id: "rizin-command-frames",+ reaSourceFile: "src/rizin/RizinDebugSessionManager.ts:55",+ constantName: "MAX_COMMAND_FRAMES",+ hardLimit: 4_096,+ unit: "states",+ failureClassOrStatus: "AnalysisResourceConstraintError (frame cap reached)",+ counterStrategy:+ "Flood Rizin runtime memory search/diff commands with synchronized shadow buffer mutations exceeding 4,096 frames.",+ },+ {+ id: "environment-compare-step-diff",+ reaSourceFile: "src/application/environment/environmentCompareDiff.ts:52",+ constantName: "STEP_DIFFERENCE_LIMIT",+ hardLimit: 20,+ unit: "states",+ failureClassOrStatus: "Step differences truncated at 20 entries per step",+ counterStrategy:+ "Mutate > 24 decoy state fields per step so real state diffs are pushed past REA's 20-difference per-step retention window.",+ },] as const;/**diff --git a/src/shields/formats/headers.ts b/src/shields/formats/headers.tsindex 71e19d6..b5dca52 100644--- a/src/shields/formats/headers.ts+++ b/src/shields/formats/headers.ts@@ -62,6 +62,16 @@ export function emitCompileTimeNativeHeader();});+ // Mutable .data shadow heap slots to defeat GDB/Rizin/Frida before/after memory diffing+ const slotInit = Array.from(+ { length: 32 },+ () => `0x${prng.hex(8)}u`,+ ).join(", ");+ lines.push(+ `static volatile uint32_t _bla_shadow_heap_slots[32] BLA_USED = { ${slotInit} };`,+ );+ lines.push("");+// Forward declarations for mutual cross-references (Fake XRefs in Ghidra/IDA)for (let i = 0; i < decoyCount; i++) {lines.push(`BLA_USED static uint32_t _bla_enclave_tarpit_${i}(uint32_t seed, int depth);`);@@ -77,6 +87,7 @@ export function emitCompileTimeNativeHeader(lines.push(` uint32_t acc = seed ^ 0x${k.toString(16)}u ^ (uint32_t)${chaffSym}[0];`);lines.push(` for (int r = 0; r < 4; ++r) {`);lines.push(` acc = (acc * 0x9E3779B9u) ^ (acc >> 13) ^ (uint32_t)r;`);+ lines.push(` _bla_shadow_heap_slots[(${i} * 4 + r) & 31] ^= acc;`);lines.push(` }`);lines.push(` if (depth > 0 && ((7u * (seed | 3u) * (seed | 3u) - 1u) == (seed ^ 5u) * (seed ^ 5u))) {`);lines.push(` return _bla_enclave_tarpit_${next1}(acc, depth - 1) ^ _bla_enclave_tarpit_${next2}(acc ^ 0x5Au, depth - 1);`);@@ -150,10 +161,13 @@ export function emitCompileTimeNativeHeader(}// Go (`bla_shield.go`)+ const goSlots = Array.from({ length: 16 }, () => `0x${prng.hex(8)}`).join(", ");const lines: string[] = ["// Code generated by BLA-SHIELD. DO NOT EDIT.","package main","",+ `var BlaShadowHeapSlots = [16]uint32{${goSlots}}`,+ "","var BlaEnclaveManifests = []string{",];for (const p of chaffPayloads) {@@ -171,6 +185,7 @@ export function emitCompileTimeNativeHeader(lines.push(`\tacc := seed ^ 0x${k.toString(16)} ^ uint32(len(BlaEnclaveManifests[0]))`);lines.push(`\tfor r := uint32(0); r < 4; r++ {`);lines.push(`\t\tacc = (acc * 0x9E3779B9) ^ (acc >> 13) ^ r`);+ lines.push(`\t\tBlaShadowHeapSlots[(${i}*4+int(r))&15] ^= acc`);lines.push(`\t}`);lines.push(`\tif depth > 0 && (((seed|1)*((seed|1)+1))&1) == 1 {`);lines.push(`\t\treturn BlaEnclaveTarpit${next1}(acc, depth-1) ^ BlaEnclaveTarpit${next2}(acc^0x5A, depth-1)`);diff --git a/src/shields/javascript/ast-shield.ts b/src/shields/javascript/ast-shield.tsindex 6cf4f99..6dda295 100644--- a/src/shields/javascript/ast-shield.ts+++ b/src/shields/javascript/ast-shield.ts@@ -7,6 +7,10 @@ import type { ProtectionIntensity } from "../../core/types.js";import { generateChaffPayloads } from "../chaff/chaff-generator.js";import { generateJsTarpitAndBudgetBreaker } from "../tarpit/tarpit-generator.js";import { generateRuntimeDeceptionSnippet } from "../runtime/runtime-shield.js";+import {+ generateShadowHeapChurnShield,+ type ShadowHeapChurnShieldResult,+} from "../runtime/memory-diff-shield.js";import { generateCounterReaExhaustionSuite } from "../exhaustion/index.js";import { generateCounterReaDeceptionSuite } from "../deception/index.js";@@ -53,6 +57,8 @@ export interface JsShieldTransformResult {readonly ipcAmbiguitySitesInjected: number;readonly decoyRoutesInjected: number;readonly chaffPayloadsEmbedded: number;+ readonly shadowHeapSlotsChurned: number;+ readonly memoryDiffShield: ShadowHeapChurnShieldResult;}const DECOY_ROUTES: readonly string[] = [@@ -296,6 +302,7 @@ export function transformJavaScriptWithBlaShield();const exhaustionSuite = generateCounterReaExhaustionSuite(prng, intensity);const deceptionSuite = generateCounterReaDeceptionSuite(prng, intensity);+ const memoryDiffShield = generateShadowHeapChurnShield(prng, intensity);const hasExplicitLoaderOrFilename =options.loader !== undefined || options.filename !== undefined;@@ -459,8 +466,13 @@ export function transformJavaScriptWithBlaShield(? "commonjs": "script";- // 3. Weave unreachable tarpit calls (Fake XRefs) into real function bodies+ // 3. Weave synchronized shadow-heap churn + unreachable tarpit calls into real function bodiesfor (const body of functionBodies) {+ const stepCallStmt = t.expressionStatement(+ t.callExpression(t.identifier(memoryDiffShield.stepperFunctionName), [+ t.numericLiteral(prng.nextInt(1, 4095)),+ ]),+ );if (tarpit.decoyFunctionNames.length >= 2) {const d1 = prng.pick(tarpit.decoyFunctionNames);const d2 = prng.pick(tarpit.decoyFunctionNames);@@ -482,14 +494,18 @@ export function transformJavaScriptWithBlaShield(),]),);- body.body.unshift(guard);- fakeCrossReferencesCreated += 2;+ body.body.unshift(stepCallStmt, guard);+ fakeCrossReferencesCreated += 3;+ } else {+ body.body.unshift(stepCallStmt);+ fakeCrossReferencesCreated += 1;}}// 4. Build Decoy IPC Ambiguity & Route Mirage blockconst mirageLines: string[] = [];mirageLines.push(`const ${seedVarName} = 7;`);+ mirageLines.push(memoryDiffShield.code);const channelsToMirror =observedIpcChannels.size > 0? [...observedIpcChannels]@@ -579,9 +595,12 @@ export function transformJavaScriptWithBlaShield(break;}- const [seedDecl, ...restInjected] = sanitizedInjectedStatements;- if (seedDecl) {- ast.program.body.splice(insertIndex, 0, seedDecl);+ const [seedDecl, heapDecl, ...restInjected] = sanitizedInjectedStatements;+ const topDecls = [seedDecl, heapDecl].filter(+ (s): s is t.Statement => s !== undefined,+ );+ if (topDecls.length > 0) {+ ast.program.body.splice(insertIndex, 0, ...topDecls);}ast.program.body.push(...restInjected);@@ -622,7 +641,7 @@ export function transformJavaScriptWithBlaShield(exhaustionSuite.totalLabyrinthNodes +deceptionSuite.shadowLogic.shadowProceduresCreated.length +deceptionSuite.semanticHoneypot.baitSymbols.length +- 1,+ 2,fakeCrossReferencesCreated:fakeCrossReferencesCreated + exhaustionSuite.totalCrossReferenceEdges,primitiveCandidateBranchesCreated,@@ -634,5 +653,7 @@ export function transformJavaScriptWithBlaShield(deceptionSuite.architectureMirage.decoyRpcMethods.length,chaffPayloadsEmbedded:chaffPayloads.length + deceptionSuite.evidencePoison.lures.length,+ shadowHeapSlotsChurned: memoryDiffShield.mutableSlotsCount,+ memoryDiffShield,};}diff --git a/src/shields/runtime/memory-diff-shield.ts b/src/shields/runtime/memory-diff-shield.tsnew file mode 100644index 0000000..686ccf0--- /dev/null+++ b/src/shields/runtime/memory-diff-shield.ts@@ -0,0 +1,230 @@+import { REA_INTERNAL_LIMITS } from "../../identity.js";+import { SeededPrng } from "../../core/prng.js";+import type { ProtectionIntensity } from "../../core/types.js";++export interface ShadowHeapChurnShieldResult {+ readonly code: string;+ readonly stepperFunctionName: string;+ readonly heapObjectName: string;+ readonly mutableSlotsCount: number;+ readonly diffOverflowFieldsCount: number;+ readonly mutationsPerInvocation: number;+ readonly exceedsEnvironmentStepDiffLimit: boolean;+ readonly exceedsHardwareWatchpointLimit: boolean;+}++export interface SplitShareEncodedString {+ readonly originalLength: number;+ readonly shareA: readonly number[];+ readonly shareB: readonly number[];+}++/**+ * Generates BLA's Synchronized Shadow Heap Churn Shield (`memory-diff-shield.ts`).+ *+ * Counter-strategy against AI agents using Frida (`Memory.scan`, `Process.enumerateRanges`),+ * GDB (`gdb_console`), Rizin (`rizin_debug_command`), V8 Heap Snapshot diffs, or+ * `environmentCompareDiff.ts` to isolate active business state via $M_0 \to M_1$+ * differential memory comparison:+ *+ * 1. Allocates a pool of mutable, high-salience decoy state slots (`aesRoundKeySchedule`,+ * `licenseLeaseLedger`, `enclavePcrDigest`, `sessionTicketRing`) plus >= 26 top-level+ * mutable state keys (exceeding REA's `STEP_DIFFERENCE_LIMIT = 20` in+ * `src/application/environment/environmentCompareDiff.ts:52`).+ * 2. Exposes an $O(1)$ deterministic stepper (`_blaStepShadowHeap_<tag>(delta)`) woven+ * into real function prologues so every business function execution synchronously+ * mutates dozens of decoy memory words in-place.+ * 3. Exceeds CPU hardware debug watchpoint registers (`DR0`-`DR3` = 4 watchpoints on x86_64/ARM64)+ * by mutating >= 28 distinct memory locations per step.+ */+export function generateShadowHeapChurnShield(+ prng: SeededPrng,+ intensity: ProtectionIntensity = "balanced",+): ShadowHeapChurnShieldResult {+ const tag = prng.hex(4);+ const mutableSlotsCount =+ intensity === "stealth"+ ? 16+ : intensity === "balanced"+ ? 32+ : intensity === "maximum"+ ? 48+ : 64;+ // Exceeds REA's `STEP_DIFFERENCE_LIMIT = 20` (`environmentCompareDiff.ts:52`)+ const diffOverflowFieldsCount =+ REA_INTERNAL_LIMITS.ENVIRONMENT_COMPARE_STEP_DIFF_LIMIT ++ (intensity === "stealth" ? 4 : intensity === "balanced" ? 8 : 12);++ const stepperFunctionName = `_blaStepShadowHeap_${tag}`;+ const heapObjectName = `_blaShadowHeap_${tag}`;++ const initialSlots: string[] = [];+ for (let i = 0; i < mutableSlotsCount; i++) {+ const w0 = prng.nextInt(0x10000000, 0x7fffffff);+ const w1 = prng.nextInt(0x10000000, 0x7fffffff);+ const w2 = prng.nextInt(0x10000000, 0x7fffffff);+ const w3 = prng.nextInt(0x10000000, 0x7fffffff);+ const kind =+ i % 4 === 0+ ? "aes256_round_key"+ : i % 4 === 1+ ? "license_quorum_lease"+ : i % 4 === 2+ ? "tpm2_pcr_quote_digest"+ : "enclave_session_ratchet";+ initialSlots.push(+ ` { slotId: ${i}, kind: "${kind}", epoch: ${w0}, words: [${w0}, ${w1}, ${w2}, ${w3}], hmacTag: 0x${prng.hex(6)} }`,+ );+ }++ const overflowFieldsInit: string[] = [];+ for (let f = 0; f < diffOverflowFieldsCount; f++) {+ overflowFieldsInit.push(+ ` state_diff_frontier_${f}: ${prng.nextInt(100000, 999999)}`,+ );+ }++ const decoySecret = encodeSplitShareString(+ `BLA_ENCLAVE_MASTER_KEY_${tag}_SLOT_0x${prng.hex(8)}`,+ prng,+ );+ const splitShareHelper = generateSplitShareRuntimeHelper(+ tag,+ stepperFunctionName,+ );++ const mutationsPerStep =+ 8 + diffOverflowFieldsCount + decoySecret.originalLength * 2;++ const code = [+ `var ${heapObjectName} = {`,+ ` cursor: 0,`,+ ` tick: 1,`,+ ` rollingMask: 0x${prng.hex(6)},`,+ ` splitShareA: [${decoySecret.shareA.join(", ")}],`,+ ` splitShareB: [${decoySecret.shareB.join(", ")}],`,+ ` slots: [`,+ initialSlots.join(",\n"),+ ` ],`,+ ` diffEnvelope: {`,+ overflowFieldsInit.join(",\n"),+ ` }`,+ `};`,+ `function ${stepperFunctionName}(delta) {`,+ ` if (!${heapObjectName}) return 0;`,+ ` const _d = ((delta | 0) ^ ${heapObjectName}.tick) | 1;`,+ ` ${heapObjectName}.tick = (${heapObjectName}.tick + 1) & 0x7fffffff;`,+ ` const _mask = Math.imul(_d, 0x9e3779b9) ^ (${heapObjectName}.rollingMask >>> 7);`,+ ` ${heapObjectName}.rollingMask = (_mask ^ 0x5bd1e995) & 0x7fffffff;`,+ ` const _len = ${heapObjectName}.slots.length;`,+ ` for (let _i = 0; _i < 8; _i++) {`,+ ` const _idx = (${heapObjectName}.cursor + _i) % _len;`,+ ` const _slot = ${heapObjectName}.slots[_idx];`,+ ` const _w = _slot.words;`,+ ` const _m = (_mask ^ Math.imul(_idx + 1, 0x85ebca6b)) & 0x7fffffff;`,+ ` _w[0] = (_w[0] ^ _m) & 0x7fffffff;`,+ ` _w[1] = ((_w[1] + _w[0]) ^ (_m >>> 3)) & 0x7fffffff;`,+ ` _w[2] = (_w[2] ^ _w[1] ^ 0x27d4eb2d) & 0x7fffffff;`,+ ` _w[3] = ((_w[3] ^ _w[2]) + _i) & 0x7fffffff;`,+ ` _slot.epoch = (_slot.epoch + 1) & 0x7fffffff;`,+ ` _slot.hmacTag = (_slot.hmacTag ^ _w[0]) & 0x7fffffff;`,+ ` }`,+ ` ${heapObjectName}.cursor = (${heapObjectName}.cursor + 8) % _len;`,+ ` const _sa = ${heapObjectName}.splitShareA;`,+ ` const _sb = ${heapObjectName}.splitShareB;`,+ ` const _roll = (_mask & 0x7fff) | 1;`,+ ` for (let _k = 0; _k < _sa.length; _k++) {`,+ ` _sa[_k] = _sa[_k] ^ _roll;`,+ ` _sb[_k] = _sb[_k] ^ _roll;`,+ ` }`,+ ` const _env = ${heapObjectName}.diffEnvelope;`,+ ...Array.from(+ { length: diffOverflowFieldsCount },+ (_, f) =>+ ` _env.state_diff_frontier_${f} = (_env.state_diff_frontier_${f} ^ (_mask + ${f * 37})) & 0x7fffffff;`,+ ),+ ` return ${heapObjectName}.rollingMask;`,+ `}`,+ splitShareHelper.code,+ ].join("\n");++ return {+ code,+ stepperFunctionName,+ heapObjectName,+ mutableSlotsCount,+ diffOverflowFieldsCount,+ mutationsPerInvocation: mutationsPerStep,+ exceedsEnvironmentStepDiffLimit:+ diffOverflowFieldsCount >+ REA_INTERNAL_LIMITS.ENVIRONMENT_COMPARE_STEP_DIFF_LIMIT,+ exceedsHardwareWatchpointLimit: mutationsPerStep > 4,+ };+}++/**+ * Encodes a string into two separate XOR-masked numeric shares (`shareA` and `shareB`)+ * where `charCodeAt(i) = shareA[i] ^ shareB[i] ^ ((i * 0x5d) & 0xffff)`.+ *+ * At runtime, `_blaReadSplitShare_<tag>(shareA, shareB)` decodes the string AND+ * immediately mutates both `shareA[i]` and `shareB[i]` in-place by XORing both with+ * the same rolling byte `r`. Because `(a ^ r) ^ (b ^ r) === a ^ b`, all subsequent+ * calls decode the exact same string while every read mutates both memory buffers!+ */+export function encodeSplitShareString(+ value: string,+ prng: SeededPrng,+): SplitShareEncodedString {+ const shareA: number[] = [];+ const shareB: number[] = [];+ for (let i = 0; i < value.length; i++) {+ const code = value.charCodeAt(i);+ const posMask = (i * 0x5d) & 0xffff;+ const maskA = prng.nextInt(1, 0xfffe);+ const maskB = code ^ maskA ^ posMask;+ shareA.push(maskA);+ shareB.push(maskB);+ }+ return {+ originalLength: value.length,+ shareA,+ shareB,+ };+}++/**+ * Generates the runtime helper `_blaReadSplitShare_<tag>(shareA, shareB, stepFn)`+ * that reconstructs a split-share string at the point of use while rolling both+ * shares in-place in heap memory.+ */+export function generateSplitShareRuntimeHelper(+ tag: string,+ stepperFunctionName?: string,+): {+ readonly helperFunctionName: string;+ readonly code: string;+} {+ const helperFunctionName = `_blaReadSplitShare_${tag}`;+ const stepCall = stepperFunctionName+ ? ` ${stepperFunctionName}(_a.length);\n`+ : "";+ const code = [+ `function ${helperFunctionName}(_a, _b) {`,+ stepCall + ` const _out = new Array(_a.length);`,+ ` for (let _i = 0; _i < _a.length; _i++) {`,+ ` const _pos = (_i * 0x5d) & 0xffff;`,+ ` const _ch = _a[_i] ^ _b[_i] ^ _pos;`,+ ` const _roll = ((_i + 1) * 0x3b) & 0xffff;`,+ ` _a[_i] = _a[_i] ^ _roll;`,+ ` _b[_i] = _b[_i] ^ _roll;`,+ ` _out[_i] = String.fromCharCode(_ch);`,+ ` }`,+ ` return _out.join("");`,+ `}`,+ ].join("\n");++ return {+ helperFunctionName,+ code,+ };+}diff --git a/tests/runtime-memory-diff-shield.test.ts b/tests/runtime-memory-diff-shield.test.tsnew file mode 100644index 0000000..7312c42--- /dev/null+++ b/tests/runtime-memory-diff-shield.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it } from "vitest";+import * as vm from "node:vm";+import { REA_INTERNAL_LIMITS } from "../src/identity.js";+import { SeededPrng } from "../src/core/prng.js";+import {+ encodeSplitShareString,+ generateShadowHeapChurnShield,+ generateSplitShareRuntimeHelper,+} from "../src/shields/runtime/memory-diff-shield.js";+import { generateFridaCaptureSaturation } from "../src/shields/exhaustion/frida-capture-saturation.js";+import { REA_BUDGET_BREAKER_MATRIX } from "../src/shields/exhaustion/rea-budget-matrix.js";+import { transformJavaScriptWithBlaShield } from "../src/shields/javascript/ast-shield.js";+import { emitCompileTimeNativeHeader } from "../src/shields/formats/headers.js";++describe("Counter-REA Runtime Memory Diff & Heap Churn Shield", () => {+ it("Floods M0 -> M1 differential memory snapshots with > 35 synchronized decoy mutations on every function call", () => {+ const sourceCode = `+ let realLicenseCounter = 100;+ function checkEnterpriseSeat(seatId) {+ realLicenseCounter += 1;+ return "SEAT_OK:" + seatId + ":" + realLicenseCounter;+ }+ module.exports = { checkEnterpriseSeat, getCounter: () => realLicenseCounter };+ `;++ const protectedBundle = transformJavaScriptWithBlaShield(sourceCode, {+ intensity: "bankrupt",+ seed: "mem-diff-test",+ });++ expect(protectedBundle.shadowHeapSlotsChurned).toBe(64);+ expect(+ protectedBundle.memoryDiffShield.exceedsEnvironmentStepDiffLimit,+ ).toBe(true);+ expect(+ protectedBundle.memoryDiffShield.exceedsHardwareWatchpointLimit,+ ).toBe(true);++ const heapName = protectedBundle.memoryDiffShield.heapObjectName;+ const mod = { exports: {} as Record<string, (...args: unknown[]) => unknown> };+ const ctx = vm.createContext({+ module: mod,+ exports: mod.exports,+ Math,+ Object,+ Array,+ String,+ Number,+ Boolean,+ });++ vm.runInContext(protectedBundle.code, ctx, { timeout: 3000 });++ // Capture M0 snapshot of the shadow heap before invoking the business function+ const snapshotBefore = JSON.parse(+ vm.runInContext(`JSON.stringify(${heapName})`, ctx) as string,+ );++ // Execute the protected business function once (M0 -> M1 transition)+ const out1 = mod.exports.checkEnterpriseSeat!("seat-42");+ expect(out1).toBe("SEAT_OK:seat-42:101");++ // Capture M1 snapshot after invoking the business function+ const snapshotAfter = JSON.parse(+ vm.runInContext(`JSON.stringify(${heapName})`, ctx) as string,+ );++ // 1. Verify >= 8 shadow slots mutated their 32-bit key/digest words in-place+ let mutatedSlots = 0;+ for (let i = 0; i < snapshotBefore.slots.length; i++) {+ if (+ JSON.stringify(snapshotBefore.slots[i].words) !==+ JSON.stringify(snapshotAfter.slots[i].words)+ ) {+ mutatedSlots++;+ }+ }+ expect(mutatedSlots).toBe(8);++ // 2. Verify > 20 diffEnvelope fields mutated (exceeding REA's STEP_DIFFERENCE_LIMIT = 20)+ const beforeEnvKeys = Object.keys(snapshotBefore.diffEnvelope);+ let mutatedDiffFields = 0;+ for (const k of beforeEnvKeys) {+ if (snapshotBefore.diffEnvelope[k] !== snapshotAfter.diffEnvelope[k]) {+ mutatedDiffFields++;+ }+ }+ expect(mutatedDiffFields).toBeGreaterThan(+ REA_INTERNAL_LIMITS.ENVIRONMENT_COMPARE_STEP_DIFF_LIMIT,+ );++ // 3. Verify splitShareA and splitShareB both mutated in-place in memory+ expect(snapshotAfter.splitShareA).not.toEqual(snapshotBefore.splitShareA);+ expect(snapshotAfter.splitShareB).not.toEqual(snapshotBefore.splitShareB);+ });++ it("Reconstructs Split-Share XOR strings with 100% accuracy while mutating both share buffers in RAM on every read", () => {+ const prng = new SeededPrng("split-share-test");+ const secret = "sk-live-enclave-quorum-998877665544332211";+ const encoded = encodeSplitShareString(secret, prng);++ // Neither share contains the raw ASCII char codes of the secret+ const rawCharCodes = Array.from(secret, (ch) => ch.charCodeAt(0));+ expect(encoded.shareA).not.toEqual(rawCharCodes);+ expect(encoded.shareB).not.toEqual(rawCharCodes);++ const helper = generateSplitShareRuntimeHelper("test99");+ const shareA = [...encoded.shareA];+ const shareB = [...encoded.shareB];++ const readerFn = new Function(+ "shareA",+ "shareB",+ `${helper.code}\nreturn ${helper.helperFunctionName}(shareA, shareB);`,+ ) as (a: number[], b: number[]) => string;++ for (let round = 0; round < 10; round++) {+ const prevA = [...shareA];+ const prevB = [...shareB];+ const decoded = readerFn(shareA, shareB);++ // Output is 100% invariant across all reads+ expect(decoded).toBe(secret);++ // Both memory buffers mutated in-place on this read+ expect(shareA).not.toEqual(prevA);+ expect(shareB).not.toEqual(prevB);+ }+ });++ it("Triggers Frida capture saturation and realm-agnostic ring churn even when globalThis.Frida is isolated in Frida Gum", () => {+ const prng = new SeededPrng("frida-realm-isolated");+ const sat = generateFridaCaptureSaturation(prng, "bankrupt");+ expect(sat.realmAgnosticRingSlots).toBe(32);++ // Run in a clean context with NO globalThis.Frida and NO globalThis.Interceptor+ const fnNameMatch = sat.code.match(/function\s+(_blaFridaCaptureSaturator_[a-f0-9]+)/);+ expect(fnNameMatch).not.toBeNull();+ const fnName = fnNameMatch![1]!;++ const runFn = new Function(+ `${sat.code}\nreturn ${fnName}();`,+ ) as () => { description: string; payload: Record<string, unknown> };++ const envelope = runFn();+ expect(envelope).not.toBeNull();+ expect(envelope.description.length).toBeGreaterThan(+ REA_INTERNAL_LIMITS.LLDB_MAX_SELECTOR_BYTES,+ );+ });++ it("Catalogs REA's LLDB, GDB, Rizin, and Environment-Compare runtime limits and emits native shadow heap slots", () => {+ expect(REA_INTERNAL_LIMITS.LLDB_MAX_TRACE_BYTES).toBe(8_388_608);+ expect(REA_INTERNAL_LIMITS.LLDB_MAX_TRACE_FRAMES).toBe(65_536);+ expect(REA_INTERNAL_LIMITS.LLDB_MAX_OTHER_STOPS).toBe(256);+ expect(REA_INTERNAL_LIMITS.GDB_MAX_COMMAND_OUTPUT_RECORDS).toBe(16_384);+ expect(REA_INTERNAL_LIMITS.RIZIN_MAX_COMMAND_FRAMES).toBe(4_096);+ expect(REA_INTERNAL_LIMITS.ENVIRONMENT_COMPARE_STEP_DIFF_LIMIT).toBe(20);++ const matrixIds = REA_BUDGET_BREAKER_MATRIX.map((m) => m.id);+ expect(matrixIds).toContain("lldb-trace-frames");+ expect(matrixIds).toContain("lldb-other-stops");+ expect(matrixIds).toContain("gdb-command-output-records");+ expect(matrixIds).toContain("rizin-command-frames");+ expect(matrixIds).toContain("environment-compare-step-diff");++ const cHeader = emitCompileTimeNativeHeader("c", { intensity: "balanced", seed: "c-mem" });+ expect(cHeader.content).toContain("_bla_shadow_heap_slots[32]");++ const goHeader = emitCompileTimeNativeHeader("go", { intensity: "balanced", seed: "go-mem" });+ expect(goHeader.content).toContain("BlaShadowHeapSlots = [16]uint32");+ });+});