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.

feat(native,bun): counter REA #6998 Bun standalone module graphs; preserve Bun appended-trailer executables byte-exact (v1.5.1)

qybaiheb2d643600774
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57f3587..532a04c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,44 @@ All notable changes to **bla-agents** are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.5.1] β€” 2026-10-30
+
+Counters REA #6998 (`BunStandaloneArtifactReader` β€” inventory/extraction of
+`bun build --compile` `/$bunfs/` module graphs from Mach-O `__BUN,__bun`,
+PE/ELF `.bun` and appended EOF trailers) and closes a runtime red-line gap
+for Bun standalone executables.
+
+### Fixed
+
+- **Bun standalone executables are no longer corrupted by the native shield**
+ (`src/shields/formats/native.ts`). Bun resolves an appended module graph
+ relative to EOF at runtime, so the native trailer append would have broken
+ the developer's program. `protectNativeBinary` now detects the
+ `\n---- Bun! ----\n` trailer (bare or with Bun's 8-byte total-size footer)
+ and passes such binaries through byte-exact (`bunStandaloneCarrier`,
+ `bunStandaloneGraphPreserved`).
+
+### Added
+
+- **Bun module-graph decoy shield** (`src/shields/formats/bun-standalone.ts`) β€”
+ `generateBunStandaloneDecoyGraph` / `serializeBunModuleGraph` emit a
+ byte-exact, REA-admissible Bun 1.3.9 (52-byte record) graph of canary /
+ system-diagnostic / cognitive-armor honeypot modules (entry point
+ `/$bunfs/root/enclave-attestation-main.js` with decoy sourcemap, bytecode
+ and module-info regions), plus virtual names past REA's 256-part logical
+ path allowance (indexed path + limitation), unsafe / duplicate / non-UTF-8
+ names and unknown loader discriminants. The table length is kept
+ unambiguous vs. the 36-byte layout so REA actually reads the honeypots.
+- `protectTarget` plants the decoy as a `<binary>.bunfs-snapshot` sidecar for
+ every Bun standalone executable and reports the new
+ `bun-standalone-module-graph` countered vector.
+- `REA_INTERNAL_LIMITS.BUN_*` (record sizes, module count, retained bytes,
+ logical path parts/nodes, metadata cache) and 6 new `verify:rea` drift
+ checks (69 total).
+- `tests/bun-standalone-counter.test.ts` β€” includes a live run of REA's own
+ `BunStandaloneArtifactReader` (via REA's tsx) against the decoy, and an
+ end-to-end check that a hardened Bun-style ELF still executes.
+
## [1.5.0] β€” 2026-10-30
Red-Team vs. Blue-Team adversarial hardening across the JavaScript/TypeScript AST
diff --git a/package.json b/package.json
index b8318e8..cb80b55 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "bla-agents",
- "version": "1.5.0",
+ "version": "1.5.1",
"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",
diff --git a/scripts/verify-rea-constants.mjs b/scripts/verify-rea-constants.mjs
index 8433180..dd06d38 100755
--- a/scripts/verify-rea-constants.mjs
+++ b/scripts/verify-rea-constants.mjs
@@ -179,6 +179,13 @@ const NUMERIC_EXPECTATIONS = [
{ name: "MAX_FIRMWARE_EXTRACTION_DEPTH", expected: 10 },
{ name: "ANDROID_JNI_REPORT_BYTES", expected: 16 * 1024 * 1024 },
{ name: "MAX_NATIVE_EXPORT_ROWS", expected: 262_144 },
+ // Bun standalone module graph reader (REA #6998).
+ { name: "BUN_RECORD_BYTES_1_3_3", expected: 36 },
+ { name: "BUN_RECORD_BYTES_1_3_9", expected: 52 },
+ { name: "MAX_BUN_MODULE_COUNT", expected: 100_000 },
+ { name: "MAX_BUN_RETAINED_BYTES", expected: 256 * 1024 * 1024 },
+ { name: "MAX_LOGICAL_PATH_PARTS", expected: 256 },
+ { name: "MAX_LOGICAL_PATH_NODES", expected: 250_000 },
];
const OBJECT_PROP_EXPECTATIONS = [
diff --git a/src/core/types.ts b/src/core/types.ts
index 21dff70..41bd4b7 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -55,7 +55,8 @@ export type ReaAttackVectorId =
| "erlang-beam-inspection"
| "evm-bytecode-inspection"
| "pcap-capture-inspection"
- | "gpu-ptx-inspection";
+ | "gpu-ptx-inspection"
+ | "bun-standalone-module-graph";
export interface ExposedSymbolOrModule {
readonly id: string;
diff --git a/src/engine/protector.ts b/src/engine/protector.ts
index 38bc42b..dc482c7 100644
--- a/src/engine/protector.ts
+++ b/src/engine/protector.ts
@@ -24,6 +24,7 @@ import { planAsarHeaderAmplification } from "../shields/exhaustion/asar-header-a
import { protectWasmBinary } from "../shields/formats/wasm.js";
import { findPythonPrologueInsertionOffset, protectPythonPycBuffer, protectPythonSource } from "../shields/formats/python.js";
import { protectNativeBinary, validateElf64Layout } from "../shields/formats/native.js";
+import { generateBunStandaloneDecoyGraph } from "../shields/formats/bun-standalone.js";
import { protectZipOrApkBuffer, validateZipProtectionInput, UnsupportedApkProtectionError } from "../shields/formats/archive.js";
import { protectSqliteBuffer, validateSqliteFileInput } from "../shields/formats/sqlite.js";
import { protectGgufBuffer, protectSafetensorsBuffer } from "../shields/formats/model.js";
@@ -287,15 +288,30 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {
const rawBin = readFileSync(absInput);
const res = protectNativeBinary(rawBin, { intensity, seed });
writeFileSync(absOutput, res.buffer);
- decoyFunctionsInjected = 24;
- fakeCrossReferencesCreated = 48;
+ const passthrough = res.binarySectionsPatched === 0;
+ decoyFunctionsInjected = passthrough ? 0 : 24;
+ fakeCrossReferencesCreated = passthrough ? 0 : 48;
chaffPayloadsEmbedded = res.chaffPayloadsEmbedded;
binarySectionsPatched = res.binarySectionsPatched;
- counteredVectors.add("native-rust-auditable");
- counteredVectors.add("native-go-buildinfo");
- counteredVectors.add("native-decompiler-pseudocode");
- counteredVectors.add("electron-fuses-inspection");
- counteredVectors.add("flutter-dart-aot-snapshot");
+ if (!passthrough) {
+ counteredVectors.add("native-rust-auditable");
+ counteredVectors.add("native-go-buildinfo");
+ counteredVectors.add("native-decompiler-pseudocode");
+ counteredVectors.add("electron-fuses-inspection");
+ counteredVectors.add("flutter-dart-aot-snapshot");
+ }
+ if (res.bunStandaloneCarrier !== "none") {
+ // REA #6998: the real Bun module graph is left byte-exact; plant a
+ // sidecar decoy graph (appended-trailer carrier) full of honeypots.
+ const decoy = generateBunStandaloneDecoyGraph(
+ new SeededPrng(`${seed}:bun-standalone`),
+ intensity,
+ );
+ writeFileSync(`${absOutput}.bunfs-snapshot`, decoy.buffer);
+ decoyFunctionsInjected += decoy.moduleCount;
+ chaffPayloadsEmbedded += decoy.chaffPayloadsEmbedded;
+ counteredVectors.add("bun-standalone-module-graph");
+ }
} else if (format === "sqlite") {
const rawDb = readFileSync(absInput);
const res = protectSqliteBuffer(rawDb, { intensity, seed });
diff --git a/src/identity.ts b/src/identity.ts
index 1c63d0e..1b5188d 100644
--- a/src/identity.ts
+++ b/src/identity.ts
@@ -5,7 +5,7 @@ export const BLA_IDENTITY = Object.freeze({
packageAlias: "bla-shield",
cliBinary: "bla",
cliAlias: "bla-agents",
- version: "1.5.0",
+ version: "1.5.1",
slogan: "Poison -> Exhaust -> Hallucinate. Make Reverse Engineering Bankrupt Again.",
counterpart: {
name: "REA",
@@ -157,4 +157,16 @@ export const REA_INTERNAL_LIMITS = Object.freeze({
ANDROID_MANIFEST_PERMISSION_BYTES: 1_048_576,
ANDROID_MANIFEST_PROCESS_BYTES: 1_048_576,
ANDROID_MANIFEST_DETAIL_BYTES: 1_048_576,
+ /**
+ * Bun standalone module-graph reader (`BunModuleGraphLayout.ts` /
+ * `BunStandaloneArtifactReader.ts`, REA #6998).
+ */
+ BUN_RECORD_BYTES_1_3_3: 36,
+ BUN_RECORD_BYTES_1_3_9: 52,
+ BUN_MAX_MODULE_COUNT: 100_000,
+ BUN_MAX_RETAINED_BYTES: 268_435_456,
+ BUN_MAX_LOGICAL_PATH_PARTS: 256,
+ BUN_MAX_LOGICAL_PATH_NODES: 250_000,
+ BUN_METADATA_CACHE_BYTES: 262_144,
+ BUN_METADATA_CACHE_ENTRIES: 1_024,
});
diff --git a/src/index.ts b/src/index.ts
index d8c5a2a..dfa5aa7 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -70,6 +70,15 @@ export {
buildDecoyRustAuditablePayload,
type Elf64LayoutSummary,
} from "./shields/formats/native.js";
+export {
+ BUN_TRAILER,
+ detectBunStandaloneGraph,
+ generateBunStandaloneDecoyGraph,
+ serializeBunModuleGraph,
+ type BunCarrierDetection,
+ type BunDecoyGraphResult,
+ type BunDecoyModule,
+} from "./shields/formats/bun-standalone.js";
export {
emitCompileTimeNativeHeader,
type NativeHeaderLanguage,
diff --git a/src/shields/formats/bun-standalone.ts b/src/shields/formats/bun-standalone.ts
new file mode 100644
index 0000000..df00a89
--- /dev/null
+++ b/src/shields/formats/bun-standalone.ts
@@ -0,0 +1,336 @@
+import { SeededPrng } from "../../core/prng.js";
+import type { ProtectionIntensity } from "../../core/types.js";
+import { REA_INTERNAL_LIMITS } from "../../identity.js";
+import { generateChaffPayloads } from "../chaff/chaff-generator.js";
+import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.js";
+
+/**
+ * Bun standalone executable (`bun build --compile`) support β€” counters REA
+ * #6998 (`BunStandaloneArtifactReader` / `BunModuleGraphLayout`), which
+ * inventories and extracts the embedded `/$bunfs/` module graph from Mach-O
+ * `__BUN,__bun`, PE/ELF `.bun` sections and the appended EOF trailer.
+ *
+ * Two halves:
+ * 1. Red-line guard: Bun locates an appended graph relative to EOF at
+ * runtime, so anything appended after `\n---- Bun! ----\n` (or after its
+ * 8-byte total-size footer) would break the developer's real program.
+ * `detectBunStandaloneGraph` lets the native shield refuse to append.
+ * 2. Deception: `generateBunStandaloneDecoyGraph` emits a byte-exact,
+ * REA-admissible Bun 1.3.9 (52-byte record) module graph whose modules
+ * are canary / diagnostic / cognitive-armor honeypots, with deep virtual
+ * names past REA's 256-part logical-path allowance, unsafe and duplicate
+ * names, non-UTF-8 names, unknown loader discriminants and decoy
+ * sourcemap / bytecode / module-info regions.
+ */
+
+export const BUN_TRAILER = Buffer.from("\n---- Bun! ----\n", "latin1");
+const OFFSETS_BYTES = 32;
+const SUFFIX_BYTES = OFFSETS_BYTES + BUN_TRAILER.length;
+const RECORD_BYTES = REA_INTERNAL_LIMITS.BUN_RECORD_BYTES_1_3_9;
+const RECORD_BYTES_OLD = REA_INTERNAL_LIMITS.BUN_RECORD_BYTES_1_3_3;
+
+export type BunCarrierDetection =
+ | { readonly kind: "none" }
+ | {
+ readonly kind: "appended-trailer" | "appended-trailer-sized";
+ /** Byte offset where the graph payload begins. */
+ readonly payloadOffset: number;
+ readonly payloadLength: number;
+ }
+ | { readonly kind: "embedded-sentinel"; readonly sentinelOffset: number };
+
+/**
+ * Cheap, allocation-free detection mirroring REA's appended-trailer probe.
+ * `embedded-sentinel` means a section-carried graph (or a bare sentinel) β€”
+ * EOF appends do not move it, but callers should still report it.
+ */
+export function detectBunStandaloneGraph(bytes: Buffer): BunCarrierDetection {
+ const size = bytes.length;
+ const at = (end: number): boolean =>
+ end >= SUFFIX_BYTES &&
+ bytes.subarray(end - BUN_TRAILER.length, end).equals(BUN_TRAILER);
+ const claim = (end: number): { payloadOffset: number; payloadLength: number } | null => {
+ const byteCount = bytes.readBigUInt64LE(end - SUFFIX_BYTES);
+ const length = byteCount + BigInt(SUFFIX_BYTES);
+ if (length > BigInt(end)) return null;
+ return { payloadOffset: end - Number(length), payloadLength: Number(length) };
+ };
+ if (at(size)) {
+ const c = claim(size);
+ if (c) return { kind: "appended-trailer", ...c };
+ }
+ if (size >= SUFFIX_BYTES + 8 && at(size - 8)) {
+ const c = claim(size - 8);
+ if (c) return { kind: "appended-trailer-sized", ...c };
+ }
+ const idx = bytes.indexOf(BUN_TRAILER);
+ if (idx >= 0) return { kind: "embedded-sentinel", sentinelOffset: idx };
+ return { kind: "none" };
+}
+
+export interface BunDecoyModule {
+ readonly name: Buffer;
+ readonly contents: Buffer;
+ readonly sourcemap?: Buffer;
+ readonly bytecode?: Buffer;
+ readonly moduleInfo?: Buffer;
+ readonly bytecodeOrigin?: Buffer;
+ readonly encoding: number;
+ readonly loader: number;
+ readonly moduleFormat: number;
+ readonly side: number;
+}
+
+export interface BunDecoyGraphResult {
+ /** Complete appended-trailer graph: data β€– Offsets(32) β€– trailer(16). */
+ readonly buffer: Buffer;
+ readonly moduleCount: number;
+ readonly entryPointId: number;
+ readonly deepNameModules: number;
+ readonly unsafeNameModules: number;
+ readonly duplicateNameModules: number;
+ readonly nonUtf8NameModules: number;
+ readonly unknownLoaderModules: number;
+ readonly canaryTokensEmbedded: number;
+ readonly diagnosticsEmbedded: number;
+ readonly chaffPayloadsEmbedded: number;
+}
+
+function scaleFor(intensity: ProtectionIntensity): {
+ honeyModules: number;
+ deep: number;
+ deepPartsOver: number;
+} {
+ switch (intensity) {
+ case "stealth":
+ return { honeyModules: 6, deep: 2, deepPartsOver: 8 };
+ case "maximum":
+ case "bankrupt":
+ return { honeyModules: 40, deep: 24, deepPartsOver: 128 };
+ case "balanced":
+ default:
+ return { honeyModules: 16, deep: 8, deepPartsOver: 32 };
+ }
+}
+
+const LOADER_JS = 1;
+const LOADER_TS = 2;
+const LOADER_JSON = 6;
+const LOADER_NAPI = 10;
+const FORMAT_ESM = 1;
+const FORMAT_CJS = 2;
+
+/** Serialize modules exactly as Bun's StandaloneModuleGraph does (1.3.9+ record). */
+export function serializeBunModuleGraph(input: {
+ readonly modules: readonly BunDecoyModule[];
+ readonly entryPointId: number;
+ readonly compileExecArgv: Buffer;
+ readonly flags?: number;
+}): Buffer {
+ const chunks: Buffer[] = [];
+ let cursor = 0;
+ const place = (bytes: Buffer | undefined, nul: boolean): [number, number] => {
+ const b = bytes ?? Buffer.alloc(0);
+ const offset = cursor;
+ if (b.length > 0) {
+ chunks.push(b);
+ cursor += b.length;
+ if (nul) {
+ chunks.push(Buffer.from([0]));
+ cursor += 1;
+ }
+ }
+ return [offset, b.length];
+ };
+ const placed = input.modules.map((m) => ({
+ m,
+ name: place(m.name, true),
+ contents: place(m.contents, true),
+ sourcemap: place(m.sourcemap, false),
+ bytecode: place(m.bytecode, false),
+ moduleInfo: place(m.moduleInfo, false),
+ origin: place(m.bytecodeOrigin, true),
+ }));
+ const argv = place(input.compileExecArgv, true);
+ const tableOffset = cursor;
+ const table = Buffer.alloc(placed.length * RECORD_BYTES);
+ placed.forEach((row, i) => {
+ const base = i * RECORD_BYTES;
+ const ptr = (off: number, p: [number, number]): void => {
+ table.writeUInt32LE(p[0], base + off);
+ table.writeUInt32LE(p[1], base + off + 4);
+ };
+ ptr(0, row.name);
+ ptr(8, row.contents);
+ ptr(16, row.sourcemap);
+ ptr(24, row.bytecode);
+ ptr(32, row.moduleInfo);
+ ptr(40, row.origin);
+ table[base + 48] = row.m.encoding;
+ table[base + 49] = row.m.loader;
+ table[base + 50] = row.m.moduleFormat;
+ table[base + 51] = row.m.side;
+ });
+ chunks.push(table);
+ cursor += table.length;
+ const data = Buffer.concat(chunks);
+ const offsets = Buffer.alloc(OFFSETS_BYTES);
+ offsets.writeBigUInt64LE(BigInt(data.length), 0);
+ offsets.writeUInt32LE(tableOffset, 8);
+ offsets.writeUInt32LE(table.length, 12);
+ offsets.writeUInt32LE(input.entryPointId, 16);
+ offsets.writeUInt32LE(argv[0], 20);
+ offsets.writeUInt32LE(argv[1], 24);
+ offsets.writeUInt32LE(input.flags ?? 0, 28);
+ return Buffer.concat([data, offsets, BUN_TRAILER]);
+}
+
+/**
+ * Builds a REA-admissible decoy Bun module graph full of honeypot modules.
+ * The output is a NEW sidecar artifact; it is never spliced into the
+ * developer's real executable.
+ */
+export function generateBunStandaloneDecoyGraph(
+ prng: SeededPrng,
+ intensity: ProtectionIntensity = "balanced",
+): BunDecoyGraphResult {
+ const scale = scaleFor(intensity);
+ const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
+ const chaff = generateChaffPayloads(prng, intensity);
+ const records = deception.textRecords;
+ const rec = (i: number): string => records[i % Math.max(1, records.length)] ?? "PROTECTED_CANARY";
+ const modules: BunDecoyModule[] = [];
+
+ const honeySource = (label: string, i: number): string => {
+ const lines = [
+ `// ${label} β€” enclave attestation bridge (compiled by bun build --compile)`,
+ `const ATTESTATION_QUORUM = ${3 + (i % 5)};`,
+ `export const ${label.replace(/[^A-Za-z0-9]/g, "_")}_sealedSecret = ${JSON.stringify(rec(i))};`,
+ `export const transportDiagnostic = ${JSON.stringify(rec(i + 1))};`,
+ `export function unsealSessionKey(blob) {`,
+ ` // ${rec(i + 2).replace(/\*\//g, "* /")}`,
+ ` if (blob.length !== ATTESTATION_QUORUM * 32) throw new Error("quorum mismatch");`,
+ ` return globalThis.__enclave?.unseal?.(blob, ${JSON.stringify(prng.hex(32))});`,
+ `}`,
+ ];
+ const c = chaff[i % Math.max(1, chaff.length)];
+ if (c) lines.push(`export const ${c.symbolName.replace(/[^A-Za-z0-9_$]/g, "_")} = ${JSON.stringify(c.rawText)};`);
+ return lines.join("\n") + "\n";
+ };
+ const honeyMap = (file: string, i: number): Buffer =>
+ Buffer.from(
+ JSON.stringify({
+ version: 3,
+ file,
+ sources: [`../src/enclave/${file.replace(/\.js$/, ".ts")}`, `../src/keys/unsealer_${i}.ts`],
+ sourcesContent: [rec(i), rec(i + 3)],
+ names: ["unsealSessionKey", "ATTESTATION_QUORUM"],
+ mappings: "AAAA;AACA",
+ }),
+ "utf8",
+ );
+
+ // 0: entry point β€” the most tempting module.
+ modules.push({
+ name: Buffer.from("/$bunfs/root/enclave-attestation-main.js"),
+ contents: Buffer.from(honeySource("enclaveMain", 0)),
+ sourcemap: honeyMap("enclave-attestation-main.js", 0),
+ bytecode: Buffer.concat([Buffer.from("JSC\0BLA-DECOY-BYTECODE\0"), Buffer.from(prng.hex(64), "hex")]),
+ moduleInfo: Buffer.from(`{"imports":["./keys/unsealer.js","bun:ffi"],"canary":${JSON.stringify(rec(4))}}`),
+ bytecodeOrigin: Buffer.from("/$bunfs/root/enclave-attestation-main.js"),
+ encoding: 2,
+ loader: LOADER_JS,
+ moduleFormat: FORMAT_ESM,
+ side: 0,
+ });
+
+ // Honeypot modules.
+ for (let i = 1; i <= scale.honeyModules; i++) {
+ const file = `keys/unsealer_${prng.hex(4)}_${i}.${i % 3 === 0 ? "ts" : "js"}`;
+ modules.push({
+ name: Buffer.from(`/$bunfs/root/${file}`),
+ contents: Buffer.from(honeySource(`unsealer${i}`, i)),
+ sourcemap: i % 2 === 0 ? honeyMap(file, i) : undefined,
+ encoding: 1,
+ loader: i % 3 === 0 ? LOADER_TS : LOADER_JS,
+ moduleFormat: i % 2 === 0 ? FORMAT_ESM : FORMAT_CJS,
+ side: i % 4 === 0 ? 1 : 0,
+ });
+ }
+ modules.push({
+ name: Buffer.from("/$bunfs/root/config/attestation-keys.json"),
+ contents: Buffer.from(JSON.stringify({ canary: records.slice(0, 6) }, null, 2)),
+ encoding: 1,
+ loader: LOADER_JSON,
+ moduleFormat: 0,
+ side: 0,
+ });
+ modules.push({
+ name: Buffer.from("/$bunfs/root/native/libenclave_unseal.node"),
+ contents: Buffer.concat([Buffer.from("\x7fELF-BLA-DECOY-NAPI\0"), Buffer.from(rec(5))]),
+ encoding: 0,
+ loader: LOADER_NAPI,
+ moduleFormat: 0,
+ side: 0,
+ });
+
+ // Deep virtual names past REA's 256-part logical path allowance β†’ indexed path + limitation.
+ const maxParts = REA_INTERNAL_LIMITS.BUN_MAX_LOGICAL_PATH_PARTS;
+ let deepNameModules = 0;
+ for (let i = 0; i < scale.deep; i++) {
+ const parts: string[] = [];
+ for (let p = 0; p < maxParts + scale.deepPartsOver; p++) parts.push(`q${(p + i).toString(36)}`);
+ modules.push({
+ name: Buffer.from(`/$bunfs/root/${parts.join("/")}/quorum_${i}.js`),
+ contents: Buffer.from(honeySource(`quorumNode${i}`, i + 7)),
+ encoding: 1,
+ loader: LOADER_JS,
+ moduleFormat: FORMAT_ESM,
+ side: 0,
+ });
+ deepNameModules++;
+ }
+
+ // Unsafe names β†’ bun-modules/<index> fallback, retained source spelling.
+ const unsafe = ["../../etc/enclave/sealed.key", "C:\\enclave\\vault.js", "/$bunfs/root/../../../escape.js"];
+ for (const [i, n] of unsafe.entries()) {
+ modules.push({ name: Buffer.from(n), contents: Buffer.from(honeySource(`unsafe${i}`, i + 11)), encoding: 1, loader: LOADER_JS, moduleFormat: FORMAT_CJS, side: 0 });
+ }
+ // Duplicate names β†’ separate occurrences with differing contents.
+ const dupName = "/$bunfs/root/keys/master.js";
+ for (let i = 0; i < 3; i++) {
+ modules.push({ name: Buffer.from(dupName), contents: Buffer.from(honeySource(`masterReplica${i}`, i + 13)), encoding: 1, loader: LOADER_JS, moduleFormat: FORMAT_ESM, side: 0 });
+ }
+ // Non-UTF-8 names β†’ hex-only identity.
+ const nonUtf8 = [Buffer.from([0x2f, 0x24, 0x62, 0x75, 0x6e, 0x66, 0x73, 0x2f, 0xff, 0xfe, 0x6b, 0x2e, 0x6a, 0x73]), Buffer.from([0x2f, 0xc3, 0x28, 0x2e, 0x6a, 0x73])];
+ for (const [i, n] of nonUtf8.entries()) {
+ modules.push({ name: n, contents: Buffer.from(honeySource(`opaque${i}`, i + 17)), encoding: 0, loader: LOADER_JS, moduleFormat: FORMAT_ESM, side: 0 });
+ }
+ // Unknown enum discriminants stay raw with null names.
+ const unknownLoader = 2;
+ for (let i = 0; i < unknownLoader; i++) {
+ modules.push({ name: Buffer.from(`/$bunfs/root/ext/loader_${200 + i}.bin`), contents: Buffer.from(rec(i + 19)), encoding: 7, loader: 200 + i, moduleFormat: 9, side: 5 });
+ }
+
+ // REA refuses a table whose length matches BOTH 36- and 52-byte layouts
+ // ambiguously; keep the decoy admissible so the honeypot is actually read.
+ while ((modules.length * RECORD_BYTES) % RECORD_BYTES_OLD === 0) {
+ modules.push({ name: Buffer.from(`/$bunfs/root/keys/pad_${modules.length}.js`), contents: Buffer.from(honeySource(`pad${modules.length}`, modules.length)), encoding: 1, loader: LOADER_JS, moduleFormat: FORMAT_ESM, side: 0 });
+ }
+
+ const argv = Buffer.from(`--smol --define=ENCLAVE_SEAL=${JSON.stringify(rec(2)).slice(0, 240)}`);
+ const buffer = serializeBunModuleGraph({ modules, entryPointId: 0, compileExecArgv: argv, flags: 0 });
+ return {
+ buffer,
+ moduleCount: modules.length,
+ entryPointId: 0,
+ deepNameModules,
+ unsafeNameModules: unsafe.length,
+ duplicateNameModules: 3,
+ nonUtf8NameModules: nonUtf8.length,
+ unknownLoaderModules: unknownLoader,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
+ chaffPayloadsEmbedded: chaff.length,
+ };
+}
diff --git a/src/shields/formats/native.ts b/src/shields/formats/native.ts
index fc4fe8a..51c5549 100644
--- a/src/shields/formats/native.ts
+++ b/src/shields/formats/native.ts
@@ -1,3 +1,7 @@
+import {
+ detectBunStandaloneGraph,
+ type BunCarrierDetection,
+} from "./bun-standalone.js";
import { deflateSync } from "node:zlib";
import { REA_INTERNAL_LIMITS } from "../../identity.js";
import { SeededPrng } from "../../core/prng.js";
@@ -628,7 +632,35 @@ export function protectNativeBinary(
readonly chaffPayloadsEmbedded: number;
readonly binarySectionsPatched: number;
readonly electronHardeningReport?: ElectronHardeningReport;
+ /**
+ * Bun standalone carrier observed in the input (REA #6998). When the graph
+ * rides an EOF trailer, nothing is appended or patched: Bun resolves that
+ * graph from EOF at runtime, so the binary is passed through byte-exact.
+ */
+ readonly bunStandaloneCarrier: BunCarrierDetection["kind"];
+ readonly bunStandaloneGraphPreserved: boolean;
} {
+ const bunCarrier = detectBunStandaloneGraph(bytes);
+ if (
+ bunCarrier.kind === "appended-trailer" ||
+ bunCarrier.kind === "appended-trailer-sized"
+ ) {
+ return {
+ buffer: Buffer.from(bytes),
+ rustcHashesInjected: 0,
+ electronFuseSentinelsInjected: 0,
+ dartSnapshotHashesInjected: 0,
+ dartPoolUrisInjected: 0,
+ dartPoolTokensInjected: 0,
+ goBuildInfoExceedsLimit: false,
+ mappedGoBuildInfoPlanted: false,
+ mappedFlutterPoolPlanted: false,
+ chaffPayloadsEmbedded: 0,
+ binarySectionsPatched: 0,
+ bunStandaloneCarrier: bunCarrier.kind,
+ bunStandaloneGraphPreserved: true,
+ };
+ }
const isElfMagic =
bytes.length >= 4 &&
bytes[0] === 0x7f &&
@@ -780,6 +812,8 @@ export function protectNativeBinary(
chaffPayloadsEmbedded: chaffPayloads.length,
binarySectionsPatched,
...(electronHardeningReport ? { electronHardeningReport } : {}),
+ bunStandaloneCarrier: bunCarrier.kind,
+ bunStandaloneGraphPreserved: bunCarrier.kind !== "none",
};
}
diff --git a/tests/bun-standalone-counter.test.ts b/tests/bun-standalone-counter.test.ts
new file mode 100644
index 0000000..2578cbd
--- /dev/null
+++ b/tests/bun-standalone-counter.test.ts
@@ -0,0 +1,158 @@
+import { execFileSync } from "node:child_process";
+import {
+ copyFileSync,
+ existsSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+ chmodSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+import { SeededPrng } from "../src/core/prng.js";
+import { REA_INTERNAL_LIMITS } from "../src/identity.js";
+import { protectTarget } from "../src/engine/protector.js";
+import {
+ BUN_TRAILER,
+ detectBunStandaloneGraph,
+ generateBunStandaloneDecoyGraph,
+} from "../src/shields/formats/bun-standalone.js";
+import { protectNativeBinary } from "../src/shields/formats/native.js";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const BLA_ROOT = resolve(__dirname, "..");
+const REA_ROOT = resolve(
+ (process.env.REA_ROOT ?? "").trim() || join(BLA_ROOT, "..", "rea"),
+);
+const REA_BUN_READER = join(REA_ROOT, "src/artifacts/BunStandaloneArtifactReader.ts");
+const REA_TSX = join(REA_ROOT, "node_modules/.bin/tsx");
+const HOST_ELF = "/bin/true";
+
+function decodeSuffix(buf: Buffer): { byteCount: bigint; tableLength: number; entry: number } {
+ const off = buf.length - BUN_TRAILER.length - 32;
+ return {
+ byteCount: buf.readBigUInt64LE(off),
+ tableLength: buf.readUInt32LE(off + 12),
+ entry: buf.readUInt32LE(off + 16),
+ };
+}
+
+describe("Bun standalone module graph counter (REA #6998)", () => {
+ it("emits an admissible 52-byte-record graph with deep / unsafe / duplicate / non-UTF-8 honeypots", () => {
+ for (const intensity of ["stealth", "balanced", "maximum", "bankrupt"] as const) {
+ const r = generateBunStandaloneDecoyGraph(new SeededPrng(`bun-${intensity}`), intensity);
+ expect(r.buffer.subarray(-BUN_TRAILER.length).equals(BUN_TRAILER)).toBe(true);
+ const s = decodeSuffix(r.buffer);
+ expect(Number(s.byteCount) + 48).toBe(r.buffer.length);
+ expect(s.tableLength).toBe(r.moduleCount * REA_INTERNAL_LIMITS.BUN_RECORD_BYTES_1_3_9);
+ // Never ambiguous with the 36-byte layout (REA would refuse the graph).
+ expect(s.tableLength % REA_INTERNAL_LIMITS.BUN_RECORD_BYTES_1_3_3).not.toBe(0);
+ expect(s.entry).toBe(0);
+ expect(r.deepNameModules).toBeGreaterThan(0);
+ expect(r.unsafeNameModules).toBeGreaterThan(0);
+ expect(r.duplicateNameModules).toBeGreaterThan(1);
+ expect(r.nonUtf8NameModules).toBeGreaterThan(0);
+ expect(r.unknownLoaderModules).toBeGreaterThan(0);
+ expect(r.moduleCount).toBeLessThan(REA_INTERNAL_LIMITS.BUN_MAX_MODULE_COUNT);
+ expect(r.buffer.length).toBeLessThan(REA_INTERNAL_LIMITS.BUN_MAX_RETAINED_BYTES);
+ const text = r.buffer.toString("latin1");
+ expect(text).toContain("/$bunfs/root/enclave-attestation-main.js");
+ expect(text).toContain("PROTECTED_CANARY_CREDENTIAL=");
+ const deepParts = REA_INTERNAL_LIMITS.BUN_MAX_LOGICAL_PATH_PARTS;
+ expect(text).toMatch(new RegExp(`(?:/q[0-9a-z]+){${deepParts},}`));
+ expect(detectBunStandaloneGraph(r.buffer)).toMatchObject({
+ kind: "appended-trailer",
+ payloadOffset: 0,
+ payloadLength: r.buffer.length,
+ });
+ }
+ });
+
+ it("passes Bun appended-trailer executables through byte-exact (runtime red line)", () => {
+ const elf = Buffer.alloc(256, 0);
+ elf.write("\x7fELF", 0, "latin1");
+ const graph = generateBunStandaloneDecoyGraph(new SeededPrng("real"), "stealth").buffer;
+ const plain = Buffer.concat([elf, graph]);
+ const sizeFooter = Buffer.alloc(8);
+ sizeFooter.writeBigUInt64LE(BigInt(plain.length + 8));
+ const sized = Buffer.concat([plain, sizeFooter]);
+ for (const [bin, kind] of [
+ [plain, "appended-trailer"],
+ [sized, "appended-trailer-sized"],
+ ] as const) {
+ const res = protectNativeBinary(bin, { intensity: "maximum", seed: "bun" });
+ expect(res.bunStandaloneCarrier).toBe(kind);
+ expect(res.bunStandaloneGraphPreserved).toBe(true);
+ expect(res.binarySectionsPatched).toBe(0);
+ expect(res.buffer.equals(bin)).toBe(true);
+ }
+ });
+
+ it("keeps the ordinary native trailer path for non-Bun binaries", () => {
+ if (!existsSync(HOST_ELF)) return;
+ const elf = readFileSync(HOST_ELF);
+ const res = protectNativeBinary(elf, { seed: "plain" });
+ expect(res.bunStandaloneCarrier).toBe("none");
+ expect(res.buffer.length).toBeGreaterThan(elf.length);
+ expect(res.buffer.subarray(0, elf.length).equals(elf)).toBe(true);
+ });
+
+ it("protectTarget leaves a runnable Bun-style executable intact and plants a decoy graph sidecar", () => {
+ if (!existsSync(HOST_ELF)) return;
+ const dir = mkdtempSync(join(tmpdir(), "bla-bun-"));
+ try {
+ const input = join(dir, "app");
+ const output = join(dir, "out", "app");
+ copyFileSync(HOST_ELF, input);
+ const graph = generateBunStandaloneDecoyGraph(new SeededPrng("embedded"), "stealth").buffer;
+ writeFileSync(input, Buffer.concat([readFileSync(input), graph]));
+ chmodSync(input, 0o755);
+ const result = protectTarget({ inputPath: input, outputPath: output, intensity: "balanced", seed: "bun-e2e" });
+ expect(result.counteredReaVectors).toContain("bun-standalone-module-graph");
+ expect(readFileSync(output).equals(readFileSync(input))).toBe(true);
+ chmodSync(output, 0o755);
+ execFileSync(output); // still runs, exit 0
+ const sidecar = readFileSync(`${output}.bunfs-snapshot`);
+ expect(detectBunStandaloneGraph(sidecar).kind).toBe("appended-trailer");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("real REA BunStandaloneArtifactReader admits the decoy and publishes indexed-path limitations", () => {
+ if (!existsSync(REA_BUN_READER) || !existsSync(REA_TSX)) return;
+ const dir = mkdtempSync(join(tmpdir(), "bla-bun-rea-"));
+ try {
+ const r = generateBunStandaloneDecoyGraph(new SeededPrng("rea-live"), "balanced");
+ const decoy = join(dir, "app.bunfs-snapshot");
+ writeFileSync(decoy, r.buffer);
+ const script = join(dir, "probe.mts");
+ writeFileSync(
+ script,
+ `import { BunStandaloneArtifactReader } from ${JSON.stringify(REA_BUN_READER)};
+import { buffer } from "node:stream/consumers";
+const reader = new BunStandaloneArtifactReader(${JSON.stringify(decoy)});
+const entries = [];
+for await (const e of reader.entries()) entries.push(e);
+const limited = entries.filter((e) => JSON.stringify(e).includes("logical path allowance")).length;
+const indexed = entries.filter((e) => String(e.path).startsWith("bun-modules/")).length;
+const first = (await buffer(await reader.open(entries[0]))).toString();
+await reader.close();
+console.log(JSON.stringify({ count: entries.length, limited, indexed, first: entries[0].path, canary: first.includes("PROTECTED_CANARY_CREDENTIAL=") }));
+`,
+ );
+ const out = execFileSync(REA_TSX, [script], { cwd: REA_ROOT, encoding: "utf8", timeout: 120_000 });
+ const res = JSON.parse(out.trim().split("\n").pop()!);
+ expect(res.count).toBeGreaterThanOrEqual(r.moduleCount);
+ expect(res.limited).toBe(r.deepNameModules);
+ expect(res.indexed).toBeGreaterThanOrEqual(r.deepNameModules + r.unsafeNameModules);
+ expect(res.first).toBe("$bunfs/root/enclave-attestation-main.js");
+ expect(res.canary).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 180_000);
+});