🛡️ 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(formats,bundler): preserve ASAR nodes, Python prologue, JS carrier/loader contracts, ELF64 layout, and Electron fuse context (Fixes #13, Fixes #14, Fixes #15, Fixes #16, Fixes #17)
qybaihe41ab075e43a9
diff --git a/src/bundler/index.ts b/src/bundler/index.tsindex dbb10f1..c58612f 100644--- a/src/bundler/index.ts+++ b/src/bundler/index.ts@@ -2,7 +2,13 @@ import type { ProtectionIntensity } from "../core/types.js";import { SeededPrng } from "../core/prng.js";import { generateChaffPayloads } from "../shields/chaff/chaff-generator.js";import { generateHoneySourceMap } from "../shields/formats/sourcemap.js";-import { transformJavaScriptWithBlaShield } from "../shields/javascript/ast-shield.js";+import {+ inferJsCarrierFromPath,+ inferJsLoaderFromPath,+ transformJavaScriptWithBlaShield,+ type JsCarrierType,+ type JsLoaderType,+} from "../shields/javascript/ast-shield.js";export interface BlaBundlerPluginOptions {/** Protection intensity preset (default: `"balanced"`). */@@ -15,6 +21,45 @@ export interface BlaBundlerPluginOptions {readonly honeySourceMap?: boolean;}+/**+ * Infers the exact esbuild loader (`"js" | "jsx" | "ts" | "tsx"`) from a module path.+ */+export function inferEsbuildLoader(filePath: string): JsLoaderType {+ return inferJsLoaderFromPath(filePath);+}++/**+ * Maps a Rollup/Vite output format (`"es"`, `"cjs"`, `"iife"`, `"umd"`, `"amd"`, `"system"`)+ * or chunk filename to a BLA JavaScript carrier contract.+ */+export function inferCarrierFromRollupFormat(+ format?: string,+ fileName?: string,+): JsCarrierType {+ if (format) {+ const normalized = format.toLowerCase().trim();+ if (+ normalized === "es" ||+ normalized === "esm" ||+ normalized === "module"+ ) {+ return "module";+ }+ if (normalized === "cjs" || normalized === "commonjs") {+ return "commonjs";+ }+ if (+ normalized === "iife" ||+ normalized === "umd" ||+ normalized === "amd" ||+ normalized === "system"+ ) {+ return "script";+ }+ }+ return inferJsCarrierFromPath(fileName);+}+/*** Vite & Rollup plugin (`blaVitePlugin` / `blaRollupPlugin`) that automatically* injects BLA's three-stage adversarial shield into generated JS chunks during `renderChunk`.@@ -36,15 +81,26 @@ export function blaRollupPlugin(options: BlaBundlerPluginOptions = {}) {return {name: "bla-shield-rollup-plugin",- renderChunk(code: string, chunk: { fileName: string }) {+ renderChunk(+ code: string,+ chunk: { fileName: string; isEntry?: boolean },+ outputOptions?: { format?: string },+ ) {if (!include.test(chunk.fileName)) {return null;}const seed = `${options.seed ?? "bla-rollup"}:${chunk.fileName}`;+ const sourceType = inferCarrierFromRollupFormat(+ outputOptions?.format,+ chunk.fileName,+ );+ const loader = inferEsbuildLoader(chunk.fileName);const transformed = transformJavaScriptWithBlaShield(code, {intensity,seed,filename: chunk.fileName,+ sourceType,+ loader,});if (!emitMap) {@@ -54,7 +110,12 @@ export function blaRollupPlugin(options: BlaBundlerPluginOptions = {}) {const prng = new SeededPrng(seed);const chaff = generateChaffPayloads(prng, intensity);const lineCount = transformed.code.split("\n").length;- const honeyMap = generateHoneySourceMap(chunk.fileName, lineCount, prng, chaff);+ const honeyMap = generateHoneySourceMap(+ chunk.fileName,+ lineCount,+ prng,+ chaff,+ );return {code: transformed.code,@@ -95,7 +156,12 @@ export class BlaWebpackPlugin {processAssets: {tap: (opts: { name: string; stage: number },- fn: (assets: Record<string, { source: () => string | Buffer; size: () => number }>) => void,+ fn: (+ assets: Record<+ string,+ { source: () => string | Buffer; size: () => number }+ >,+ ) => void,) => void;};};@@ -123,10 +189,14 @@ export class BlaWebpackPlugin {const rawAsset = assets[assetName];if (!rawAsset) continue;const rawSource = rawAsset.source().toString("utf8");+ const sourceType = inferJsCarrierFromPath(assetName);+ const loader = inferEsbuildLoader(assetName);const transformed = transformJavaScriptWithBlaShield(rawSource, {intensity,seed: `${this.options.seed ?? "bla-webpack"}:${assetName}`,filename: assetName,+ sourceType,+ loader,});const shieldedCode = transformed.code;compilation.updateAsset(assetName, {@@ -141,7 +211,8 @@ export class BlaWebpackPlugin {}/**- * esbuild plugin (`blaEsbuildPlugin`) that shields JS/TS entrypoints or output files.+ * esbuild plugin (`blaEsbuildPlugin`) that shields JS/TS/JSX/TSX entrypoints or modules+ * while preserving the exact esbuild loader (`js`, `jsx`, `ts`, `tsx`) and module carrier.*/export function blaEsbuildPlugin(options: BlaBundlerPluginOptions = {}) {const intensity = options.intensity ?? "balanced";@@ -152,21 +223,27 @@ export function blaEsbuildPlugin(options: BlaBundlerPluginOptions = {}) {setup(build: {onLoad: (opts: { filter: RegExp },- cb: (args: { path: string }) => Promise<{ contents: string; loader: string } | null>,+ cb: (args: {+ path: string;+ }) => Promise<{ contents: string; loader: JsLoaderType } | null>,) => void;}) {build.onLoad({ filter: include }, async (args) => {if (args.path.includes("node_modules")) return null;const fs = await import("node:fs/promises");const source = await fs.readFile(args.path, "utf8");+ const loader = inferEsbuildLoader(args.path);+ const sourceType = inferJsCarrierFromPath(args.path);const transformed = transformJavaScriptWithBlaShield(source, {intensity,seed: `${options.seed ?? "bla-esbuild"}:${args.path}`,filename: args.path,+ loader,+ sourceType,});return {contents: transformed.code,- loader: args.path.endsWith(".ts") || args.path.endsWith(".tsx") ? "ts" : "js",+ loader,};});},diff --git a/src/shields/formats/asar.ts b/src/shields/formats/asar.tsindex cde2378..674c8d7 100644--- a/src/shields/formats/asar.ts+++ b/src/shields/formats/asar.ts@@ -1,37 +1,155 @@import { createHash } from "node:crypto";+import { posix } from "node:path";++export class UnsupportedAsarError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "UnsupportedAsarError";+ }+}++export interface AsarFileIntegrity {+ readonly algorithm: "SHA256";+ readonly hash: string;+ readonly blockSize: number;+ readonly blocks: readonly string[];+}export interface AsarFileEntry {readonly offset: string;readonly size: number;readonly unpacked?: boolean;readonly executable?: boolean;- readonly integrity?: {- readonly algorithm: "SHA256";- readonly hash: string;- readonly blockSize: number;- readonly blocks: readonly string[];- };+ readonly integrity?: AsarFileIntegrity;+}++export interface AsarUnpackedFileNode {+ readonly size: number;+ readonly unpacked: true;+ readonly executable?: boolean;+ readonly integrity?: AsarFileIntegrity;+}++export interface AsarLinkNode {+ readonly link: string;}export interface AsarDirectoryNode {- readonly files: Record<string, AsarNode>;+ readonly files: Record<string, AsarHeaderNode>;}-export type AsarNode = AsarFileEntry | AsarDirectoryNode;+export type AsarHeaderNode =+ | AsarFileEntry+ | AsarUnpackedFileNode+ | AsarLinkNode+ | AsarDirectoryNode;++export type AsarNode = AsarHeaderNode;export interface VirtualAsarFile {readonly relativePath: string;readonly content: Buffer;readonly executable?: boolean;+ readonly unpacked?: boolean;+ readonly link?: string;+ readonly size?: number;+}++export interface AsarValidationOptions {+ readonly allowUnpacked?: boolean;+ readonly allowLinks?: boolean;+ readonly rejectUnpacked?: boolean;+ readonly rejectLinks?: boolean;}const ASAR_BLOCK_SIZE = 4 * 1024 * 1024;+const ALLOWED_NODE_KEYS = new Set([+ "files",+ "link",+ "size",+ "offset",+ "unpacked",+ "executable",+ "integrity",+]);++function isPlainObject(value: unknown): value is Record<string, unknown> {+ if (typeof value !== "object" || value === null || Array.isArray(value)) {+ return false;+ }+ const proto = Object.getPrototypeOf(value);+ return proto === Object.prototype || proto === null;+}++function isDirectoryNode(node: AsarHeaderNode): node is AsarDirectoryNode {+ return isPlainObject(node) && isPlainObject((node as AsarDirectoryNode).files);+}++function validateEntrySegment(segment: string): void {+ if (+ segment.length === 0 ||+ segment === "." ||+ segment === ".." ||+ segment.includes("/") ||+ segment.includes("\\") ||+ segment.includes("\0")+ ) {+ throw new UnsupportedAsarError(`Invalid ASAR path segment: ${JSON.stringify(segment)}`);+ }+}++function validateRelativeLinkTarget(relativePath: string, linkTarget: unknown): string {+ if (+ typeof linkTarget !== "string" ||+ linkTarget.length === 0 ||+ linkTarget.includes("\0") ||+ linkTarget.includes("\\") ||+ posix.isAbsolute(linkTarget)+ ) {+ throw new UnsupportedAsarError(+ `Invalid or absolute ASAR link target at ${relativePath}: ${String(linkTarget)}`,+ );+ }++ const parentSegments = relativePath.split("/").slice(0, -1).filter(Boolean);+ let depth = parentSegments.length;+ const targetSegments = linkTarget.split("/");+ for (const seg of targetSegments) {+ if (seg === "" || seg === ".") {+ continue;+ }+ if (seg === "..") {+ depth -= 1;+ if (depth < 0) {+ throw new UnsupportedAsarError(+ `Escaping ASAR link target at ${relativePath}: ${linkTarget}`,+ );+ }+ } else {+ depth += 1;+ }+ }++ const parentDir = posix.dirname(relativePath);+ const resolved = posix.normalize(+ parentDir === "." ? linkTarget : posix.join(parentDir, linkTarget),+ );+ if (+ resolved === "" ||+ resolved === "." ||+ resolved === ".." ||+ resolved.startsWith("../") ||+ resolved.startsWith("/")+ ) {+ throw new UnsupportedAsarError(+ `Escaping or invalid ASAR link target at ${relativePath}: ${linkTarget}`,+ );+ }-function isDirectoryNode(node: AsarNode): node is AsarDirectoryNode {- return typeof (node as AsarDirectoryNode).files === "object" && (node as AsarDirectoryNode).files !== null;+ return linkTarget;}-function computeAsarIntegrity(content: Buffer): NonNullable<AsarFileEntry["integrity"]> {+function computeAsarIntegrity(content: Buffer): AsarFileIntegrity {const hash = createHash("sha256").update(content).digest("hex");const blocks: string[] = [];if (content.length === 0) {@@ -53,56 +171,238 @@ function computeAsarIntegrity(content: Buffer): NonNullable<AsarFileEntry["integ/*** Unpacks an Electron `.asar` archive buffer into an in-memory array of virtual files.* Follows Chromium Pickle framing used by `@electron/asar` and `morluto/rea`.+ * Strictly validates node shapes, offsets, sizes, bounds, unpacked entries, and link targets.*/-export function unpackAsarBuffer(asarBytes: Buffer): readonly VirtualAsarFile[] {+export function unpackAsarBuffer(+ asarBytes: Buffer,+ options: AsarValidationOptions = {},+): readonly VirtualAsarFile[] {if (asarBytes.length < 16) {- throw new Error("Invalid ASAR archive: buffer shorter than 16-byte pickle header");+ throw new UnsupportedAsarError(+ "Invalid ASAR archive: buffer shorter than 16-byte pickle header",+ );}const sizePicklePayload = asarBytes.readUInt32LE(0);if (sizePicklePayload !== 4) {- throw new Error(`Invalid ASAR header: expected outer pickle payload size 4, got ${sizePicklePayload}`);+ throw new UnsupportedAsarError(+ `Invalid ASAR header: expected outer pickle payload size 4, got ${sizePicklePayload}`,+ );}const headerSize = asarBytes.readUInt32LE(4);+ const innerPickleSize = asarBytes.readUInt32LE(8);const jsonStringSize = asarBytes.readUInt32LE(12);const dataOffsetBase = 8 + headerSize;- if (16 + jsonStringSize > asarBytes.length || dataOffsetBase > asarBytes.length) {- throw new Error("Invalid ASAR archive: header exceeds buffer bounds");+ if (+ headerSize < 8 ||+ innerPickleSize < 4 ||+ jsonStringSize === 0 ||+ 16 + jsonStringSize > dataOffsetBase ||+ 16 + jsonStringSize > asarBytes.length ||+ dataOffsetBase > asarBytes.length+ ) {+ throw new UnsupportedAsarError("Invalid ASAR archive: header exceeds buffer bounds");}const headerJson = asarBytes.subarray(16, 16 + jsonStringSize).toString("utf8");- const root = JSON.parse(headerJson) as AsarDirectoryNode;+ let rootRaw: unknown;+ try {+ rootRaw = JSON.parse(headerJson);+ } catch {+ throw new UnsupportedAsarError("Invalid ASAR archive: malformed JSON header");+ }++ if (+ !isPlainObject(rootRaw) ||+ !isPlainObject(rootRaw.files) ||+ "size" in rootRaw ||+ "offset" in rootRaw ||+ "link" in rootRaw ||+ "unpacked" in rootRaw+ ) {+ throw new UnsupportedAsarError("Invalid ASAR archive: root must be a directory node");+ }++ const rejectUnpacked =+ options.rejectUnpacked === true || options.allowUnpacked === false;+ const rejectLinks =+ options.rejectLinks === true || options.allowLinks === false;+const files: VirtualAsarFile[] = [];- const walk = (node: AsarNode, prefix: string): void => {- if (isDirectoryNode(node)) {- for (const [name, child] of Object.entries(node.files)) {- const nextPath = prefix ? `${prefix}/${name}` : name;- walk(child, nextPath);+ const walkDirectory = (dirFiles: Record<string, unknown>, prefix: string): void => {+ for (const [name, child] of Object.entries(dirFiles)) {+ validateEntrySegment(name);+ const nextPath = prefix ? `${prefix}/${name}` : name;++ if (!isPlainObject(child)) {+ throw new UnsupportedAsarError(`Malformed ASAR node at ${nextPath}`);}- return;- }- if (node.unpacked) return;- const offset = Number.parseInt(node.offset, 10);- const start = dataOffsetBase + offset;- const end = start + node.size;- if (start < dataOffsetBase || end > asarBytes.length) {- throw new Error(`Invalid ASAR file entry bounds for ${prefix}`);++ const childKeys = Object.keys(child);+ if (childKeys.length === 0) {+ throw new UnsupportedAsarError(`Empty ASAR node at ${nextPath}`);+ }+ for (const k of childKeys) {+ if (!ALLOWED_NODE_KEYS.has(k)) {+ throw new UnsupportedAsarError(+ `Unknown or unsupported ASAR node property '${k}' at ${nextPath}`,+ );+ }+ }++ const hasFiles = child.files !== undefined;+ const hasLink = child.link !== undefined;+ const hasSize = child.size !== undefined;+ const hasOffset = child.offset !== undefined;+ const isUnpacked = child.unpacked === true;++ if (hasFiles) {+ if (+ !isPlainObject(child.files) ||+ hasLink ||+ hasSize ||+ hasOffset ||+ child.unpacked !== undefined ||+ child.executable !== undefined+ ) {+ throw new UnsupportedAsarError(`Malformed ASAR directory node at ${nextPath}`);+ }+ walkDirectory(child.files, nextPath);+ continue;+ }++ if (hasLink) {+ if (hasSize || hasOffset || child.unpacked !== undefined || child.executable !== undefined) {+ throw new UnsupportedAsarError(`Conflicting ASAR link node properties at ${nextPath}`);+ }+ const validatedLink = validateRelativeLinkTarget(nextPath, child.link);+ if (rejectLinks) {+ throw new UnsupportedAsarError(+ `ASAR link node at ${nextPath} requires link-preserving pipeline`,+ );+ }+ files.push({+ relativePath: nextPath,+ content: Buffer.alloc(0),+ link: validatedLink,+ });+ continue;+ }++ if (child.executable !== undefined && typeof child.executable !== "boolean") {+ throw new UnsupportedAsarError(`Invalid ASAR executable flag at ${nextPath}`);+ }++ if (isUnpacked) {+ if (+ typeof child.size !== "number" ||+ !Number.isSafeInteger(child.size) ||+ child.size < 0+ ) {+ throw new UnsupportedAsarError(`Invalid ASAR unpacked file size at ${nextPath}`);+ }+ if (rejectUnpacked) {+ throw new UnsupportedAsarError(+ `ASAR unpacked node at ${nextPath} requires companion .asar.unpacked directory preservation`,+ );+ }+ files.push({+ relativePath: nextPath,+ content: Buffer.alloc(0),+ unpacked: true,+ size: child.size,+ ...(child.executable ? { executable: true } : {}),+ });+ continue;+ }++ if (child.unpacked !== undefined && child.unpacked !== false) {+ throw new UnsupportedAsarError(`Invalid ASAR unpacked property at ${nextPath}`);+ }++ if (+ typeof child.size !== "number" ||+ !Number.isSafeInteger(child.size) ||+ child.size < 0+ ) {+ throw new UnsupportedAsarError(+ `Invalid ASAR file size at ${nextPath}: ${String(child.size)}`,+ );+ }++ if (+ typeof child.offset !== "string" ||+ !/^(0|[1-9]\d*)$/.test(child.offset)+ ) {+ throw new UnsupportedAsarError(+ `Invalid ASAR file offset at ${nextPath}: ${String(child.offset)}`,+ );+ }++ const offset = Number(child.offset);+ if (!Number.isSafeInteger(offset) || offset < 0) {+ throw new UnsupportedAsarError(+ `Unsafe ASAR file offset at ${nextPath}: ${child.offset}`,+ );+ }++ const start = dataOffsetBase + offset;+ const end = start + child.size;+ if (+ !Number.isSafeInteger(start) ||+ !Number.isSafeInteger(end) ||+ start < dataOffsetBase ||+ end < start ||+ end > asarBytes.length+ ) {+ throw new UnsupportedAsarError(`ASAR file offset/size out of bounds for ${nextPath}`);+ }++ files.push({+ relativePath: nextPath,+ content: Buffer.from(asarBytes.subarray(start, end)),+ size: child.size,+ ...(child.executable ? { executable: true } : {}),+ });}- files.push({- relativePath: prefix,- content: Buffer.from(asarBytes.subarray(start, end)),- ...(node.executable ? { executable: true } : {}),- });};- walk(root, "");+ walkDirectory(rootRaw.files, "");return files;}+/**+ * Validates an ASAR archive buffer and returns its virtual entries.+ */+export function validateAsarBuffer(+ bytes: Buffer,+ options: { readonly allowUnpacked?: boolean; readonly allowLinks?: boolean } = {},+): readonly VirtualAsarFile[] {+ return unpackAsarBuffer(bytes, {+ rejectUnpacked: options.allowUnpacked === false,+ rejectLinks: options.allowLinks === false,+ });+}++/**+ * Validates an ASAR archive before standalone protection.+ * Fails closed (`UnsupportedAsarError`) when the archive contains external `unpacked: true`+ * entries unless `allowUnpacked: true` (companion `.asar.unpacked` synchronization) is enabled.+ */+export function validateAsarProtectionInput(+ bytes: Buffer,+ options: { readonly allowUnpacked?: boolean; readonly allowLinks?: boolean } = {},+): readonly VirtualAsarFile[] {+ return unpackAsarBuffer(bytes, {+ rejectUnpacked: options.allowUnpacked !== true,+ rejectLinks: options.allowLinks === false,+ });+}+/*** Packs an array of virtual files into a valid Electron `.asar` archive buffer- * with full SHA-256 block integrity metadata.+ * with full SHA-256 block integrity metadata, preserving `executable`, `unpacked`, and `link` nodes.*/export function packAsarBuffer(files: readonly VirtualAsarFile[]): Buffer {const root: AsarDirectoryNode = { files: {} };@@ -110,21 +410,58 @@ export function packAsarBuffer(files: readonly VirtualAsarFile[]): Buffer {let currentOffset = 0;for (const file of files) {- const segments = file.relativePath.replace(/^\/+/, "").split("/").filter(Boolean);- if (segments.length === 0) continue;+ if (file.relativePath.includes("\\") || file.relativePath.includes("\0")) {+ throw new UnsupportedAsarError(`Invalid ASAR file relativePath: ${file.relativePath}`);+ }+ const rawSegments = file.relativePath.replace(/^\/+/, "").split("/");+ if (rawSegments.length === 0 || (rawSegments.length === 1 && rawSegments[0] === "")) {+ continue;+ }+ for (const seg of rawSegments) {+ validateEntrySegment(seg);+ }+ const normalizedPath = rawSegments.join("/");let currentDir = root;- for (let i = 0; i < segments.length - 1; i++) {- const seg = segments[i]!;- let existing = currentDir.files[seg];- if (!existing || !isDirectoryNode(existing)) {- existing = { files: {} };- currentDir.files[seg] = existing;+ for (let i = 0; i < rawSegments.length - 1; i++) {+ const seg = rawSegments[i]!;+ const existing = currentDir.files[seg];+ if (!existing) {+ const nextDir: AsarDirectoryNode = { files: {} };+ currentDir.files[seg] = nextDir;+ currentDir = nextDir;+ } else if (isDirectoryNode(existing)) {+ currentDir = existing;+ } else {+ throw new UnsupportedAsarError(+ `ASAR path conflict at ${seg}: cannot create directory over non-directory entry`,+ );+ }+ }++ const leafName = rawSegments[rawSegments.length - 1]!;+ if (file.link !== undefined) {+ const validatedLink = validateRelativeLinkTarget(normalizedPath, file.link);+ currentDir.files[leafName] = {+ link: validatedLink,+ };+ continue;+ }++ if (file.unpacked === true) {+ const unpackedSize = file.size !== undefined ? file.size : file.content.length;+ if (!Number.isSafeInteger(unpackedSize) || unpackedSize < 0) {+ throw new UnsupportedAsarError(`Invalid unpacked file size for ${normalizedPath}`);}- currentDir = existing;+ currentDir.files[leafName] = {+ size: unpackedSize,+ unpacked: true,+ ...(file.executable ? { executable: true } : {}),+ ...(file.content.length > 0 ? { integrity: computeAsarIntegrity(file.content) } : {}),+ };+ continue;}- const leafName = segments[segments.length - 1]!;currentDir.files[leafName] = {offset: String(currentOffset),size: file.content.length,diff --git a/src/shields/formats/electron-fuses.ts b/src/shields/formats/electron-fuses.tsindex 6468f09..2a0b170 100644--- a/src/shields/formats/electron-fuses.ts+++ b/src/shields/formats/electron-fuses.ts@@ -1,6 +1,13 @@import { REA_INTERNAL_LIMITS } from "../../identity.js";import { SeededPrng } from "../../core/prng.js";+export class UnsupportedElectronFuseContextError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "UnsupportedElectronFuseContextError";+ }+}+/*** Electron V1 Fuse Wire constants (`src/domain/electron/electronFuses.ts` in `morluto/rea`).*/@@ -13,24 +20,137 @@ export const ELECTRON_FUSE_STATE = {DISABLED: 0x30, // '0'ENABLED: 0x31, // '1'REMOVED: 0x72, // 'r'+ DECOY: 0x39, // '9' (BLA decoy sentinel wire marker)} as const;-export interface ElectronFuseInspectionSummary {+export const ELECTRON_FUSE_NAMES = [+ "RunAsNode",+ "EnableCookieEncryption",+ "EnableNodeOptionsEnvironmentVariable",+ "EnableNodeCliInspectArguments",+ "EnableEmbeddedAsarIntegrityValidation",+ "OnlyLoadAppFromAsar",+ "LoadBrowserProcessSpecificV8Snapshot",+ "GrantFileProtocolExtraPrivileges",+] as const;++export type ElectronFuseName = (typeof ELECTRON_FUSE_NAMES)[number];+export type ElectronFuseWireValue =+ | "enabled"+ | "disabled"+ | "removed"+ | "unknown";+export type ElectronFuseStatus =+ | "verified"+ | "absent"+ | "unsupported"+ | "ambiguous";++export interface ElectronFuseInspectionResult {+ readonly status: ElectronFuseStatus;readonly sentinelCount: number;readonly sentinelOffsets: readonly number[];+ readonly realFuseOffset: number;+ readonly fuseVersion: number;+ readonly fuseWireLength: number;+ readonly fuses: Partial<Record<ElectronFuseName, ElectronFuseWireValue>>;readonly runAsNodeEnabled: boolean;readonly nodeCliInspectEnabled: boolean;readonly nodeOptionsEnabled: boolean;readonly asarIntegrityEnforced: boolean;readonly onlyLoadFromAsarEnforced: boolean;readonly exceedsReaSentinelLimit: boolean;+ readonly hardened: boolean;+ readonly diagnostic?: string;+}++export type ElectronFuseInspectionSummary = ElectronFuseInspectionResult;++export interface ElectronHardeningContext {+ readonly electronVersion: string;+ readonly asarPath?: string;+ readonly hasEmbeddedAsarIntegrity: boolean;+ readonly asarHeaderHash?: string;+ readonly codeSigningPolicy: "will-resign" | "unsigned-local-fixture";+ readonly injectDecoySentinelOverflow?: boolean;+ readonly seed?: string | number;+ readonly allowRawContainer?: boolean;+}++export interface ElectronHardeningReport {+ readonly buffer: Buffer;+ readonly fusePolicy: {+ readonly status: "hardened";+ readonly fuseVersion: number;+ readonly fuseOffset: number;+ readonly mutatedFuses: Readonly<+ Record<+ string,+ {+ readonly from: ElectronFuseWireValue;+ readonly to: ElectronFuseWireValue;+ }+ >+ >;+ readonly decoySentinelsInjected: number;+ };+ readonly asarIntegrityStatus: "verified" | "not-applicable";+ readonly signatureStatus: "unverified-requires-resign" | "unsigned-fixture";+ readonly mutatedFuses: readonly ElectronFuseName[];+}++function decodeFuseByte(byte: number): ElectronFuseWireValue {+ if (byte === ELECTRON_FUSE_STATE.DISABLED) return "disabled";+ if (byte === ELECTRON_FUSE_STATE.ENABLED) return "enabled";+ if (byte === ELECTRON_FUSE_STATE.REMOVED) return "removed";+ return "unknown";+}++function isValidWireByte(byte: number): boolean {+ return (+ byte === ELECTRON_FUSE_STATE.DISABLED ||+ byte === ELECTRON_FUSE_STATE.ENABLED ||+ byte === ELECTRON_FUSE_STATE.REMOVED ||+ byte === ELECTRON_FUSE_STATE.DECOY+ );+}++export function isSupportedNativeExecutableContainer(bytes: Buffer): boolean {+ if (+ bytes.length >= 20 &&+ bytes[0] === 0x7f &&+ bytes[1] === 0x45 &&+ bytes[2] === 0x4c &&+ bytes[3] === 0x46+ ) {+ return true;+ }+ if (bytes.length >= 8) {+ const magicBE = bytes.readUInt32BE(0);+ if (+ magicBE === 0xfeedfacf ||+ magicBE === 0xcffaedfe ||+ magicBE === 0xfeedface ||+ magicBE === 0xcefaedfe ||+ magicBE === 0xcafebabe+ ) {+ return true;+ }+ if (bytes[0] === 0x4d && bytes[1] === 0x5a) {+ return true;+ }+ }+ return false;}/*** Inspects a binary buffer (ELF / Mach-O / PE) for Electron Fuse sentinels- * (`dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX`), matching REA's `ElectronFuseReader.ts`.+ * (`dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX`), matching REA's `ElectronFuseReader.ts`+ * while distinguishing verified V1 fuse blocks from unsupported/truncated/ambiguous wires.*/-export function inspectElectronFusesInBuffer(bytes: Buffer): ElectronFuseInspectionSummary {+export function inspectElectronFusesBuffer(+ bytes: Buffer,+): ElectronFuseInspectionResult {const offsets: number[] = [];let from = 0;while (from <= bytes.length - ELECTRON_FUSE_SENTINEL_BYTES.length) {@@ -41,47 +161,175 @@ export function inspectElectronFusesInBuffer(bytes: Buffer): ElectronFuseInspectif (offsets.length >= 128) break;}- let runAsNodeEnabled = false;- let nodeCliInspectEnabled = false;- let nodeOptionsEnabled = false;- let asarIntegrityEnforced = false;- let onlyLoadFromAsarEnforced = false;-- if (offsets.length > 0) {- const firstWireStart = offsets[0]! + ELECTRON_FUSE_SENTINEL_BYTES.length;- if (firstWireStart + 8 <= bytes.length) {- const version = bytes[firstWireStart];- const len = bytes[firstWireStart + 1] ?? 0;- if (version === 1 && len >= 6) {- const fuses = bytes.subarray(firstWireStart + 2, firstWireStart + 2 + len);- runAsNodeEnabled = fuses[0] === ELECTRON_FUSE_STATE.ENABLED;- nodeOptionsEnabled = fuses[2] === ELECTRON_FUSE_STATE.ENABLED;- nodeCliInspectEnabled = fuses[3] === ELECTRON_FUSE_STATE.ENABLED;- asarIntegrityEnforced = fuses[4] === ELECTRON_FUSE_STATE.ENABLED;- onlyLoadFromAsarEnforced = fuses[5] === ELECTRON_FUSE_STATE.ENABLED;+ const exceedsReaSentinelLimit =+ offsets.length > REA_INTERNAL_LIMITS.ELECTRON_MAX_SENTINELS_PER_SLICE;++ const makeEmptyResult = (+ status: ElectronFuseStatus,+ diagnostic?: string,+ ): ElectronFuseInspectionResult => ({+ status,+ sentinelCount: offsets.length,+ sentinelOffsets: offsets,+ realFuseOffset: -1,+ fuseVersion: 0,+ fuseWireLength: 0,+ fuses: {},+ runAsNodeEnabled: false,+ nodeCliInspectEnabled: false,+ nodeOptionsEnabled: false,+ asarIntegrityEnforced: false,+ onlyLoadFromAsarEnforced: false,+ exceedsReaSentinelLimit,+ hardened: false,+ ...(diagnostic !== undefined ? { diagnostic } : {}),+ });++ if (offsets.length === 0) {+ return makeEmptyResult("absent");+ }++ interface RealCandidate {+ readonly offset: number;+ readonly version: number;+ readonly len: number;+ readonly wire: Buffer;+ }++ const realCandidates: RealCandidate[] = [];+ let unsupportedReason: string | undefined;++ for (const off of offsets) {+ const wireStart = off + ELECTRON_FUSE_SENTINEL_BYTES.length;+ if (wireStart + 2 > bytes.length) {+ return makeEmptyResult("unsupported", "truncated fuse header");+ }++ const version = bytes[wireStart]!;+ const len = bytes[wireStart + 1]!;++ if (wireStart + 2 + len > bytes.length) {+ return makeEmptyResult("unsupported", "truncated fuse wire");+ }++ if (version !== 1) {+ unsupportedReason = `unsupported fuse version ${version}`;+ continue;+ }++ if (len < 6) {+ unsupportedReason = `fuse wire length ${len} shorter than minimum 6`;+ continue;+ }++ const wire = bytes.subarray(wireStart + 2, wireStart + 2 + len);+ for (let i = 0; i < wire.length; i++) {+ if (!isValidWireByte(wire[i]!)) {+ return makeEmptyResult("unsupported", "invalid fuse wire byte");}}++ // BLA decoy sentinels contain 0x39 ('9') wire markers+ if (wire.includes(ELECTRON_FUSE_STATE.DECOY)) {+ continue;+ }++ realCandidates.push({+ offset: off,+ version,+ len,+ wire,+ });+ }++ if (realCandidates.length > 1) {+ return makeEmptyResult("ambiguous", "multiple real fuse blocks found");+ }++ if (realCandidates.length === 0) {+ return makeEmptyResult(+ "unsupported",+ unsupportedReason ?? "no verified real V1 fuse block found",+ );}+ const real = realCandidates[0]!;+ const fuses: Partial<Record<ElectronFuseName, ElectronFuseWireValue>> = {};+ const maxNamed = Math.min(real.len, ELECTRON_FUSE_NAMES.length);+ for (let i = 0; i < maxNamed; i++) {+ const fuseName = ELECTRON_FUSE_NAMES[i]!;+ fuses[fuseName] = decodeFuseByte(real.wire[i]!);+ }++ const runAsNodeEnabled = real.wire[0] === ELECTRON_FUSE_STATE.ENABLED;+ const cookieEncryptionEnabled = real.wire[1] === ELECTRON_FUSE_STATE.ENABLED;+ const nodeOptionsEnabled = real.wire[2] === ELECTRON_FUSE_STATE.ENABLED;+ const nodeCliInspectEnabled = real.wire[3] === ELECTRON_FUSE_STATE.ENABLED;+ const asarIntegrityEnforced = real.wire[4] === ELECTRON_FUSE_STATE.ENABLED;+ const onlyLoadFromAsarEnforced = real.wire[5] === ELECTRON_FUSE_STATE.ENABLED;++ const hardened =+ !runAsNodeEnabled &&+ cookieEncryptionEnabled &&+ !nodeOptionsEnabled &&+ !nodeCliInspectEnabled &&+ asarIntegrityEnforced &&+ onlyLoadFromAsarEnforced;+return {+ status: "verified",sentinelCount: offsets.length,sentinelOffsets: offsets,+ realFuseOffset: real.offset,+ fuseVersion: real.version,+ fuseWireLength: real.len,+ fuses,runAsNodeEnabled,nodeCliInspectEnabled,nodeOptionsEnabled,asarIntegrityEnforced,onlyLoadFromAsarEnforced,- exceedsReaSentinelLimit:- offsets.length > REA_INTERNAL_LIMITS.ELECTRON_MAX_SENTINELS_PER_SLICE,+ exceedsReaSentinelLimit,+ hardened,};}+export const inspectElectronFusesInBuffer = inspectElectronFusesBuffer;+/**- * Hardens any real Electron Fuse V1 wire in-place (disabling `RunAsNode`,- * `EnableNodeOptionsEnvironmentVariable`, and `EnableNodeCliInspectArguments`- * while enabling `EnableCookieEncryption`, `EnableEmbeddedAsarIntegrityValidation`,- * and `OnlyLoadAppFromAsar`) AND builds a 34-sentinel overflow trailer that trips- * REA's `ELECTRON_FUSE_LIMITS.maximumSentinelsPerSlice = 32` (`ElectronFuseReader.ts:381`)!+ * Builds 34 decoy sentinel records (`> maximumSentinelsPerSlice = 32`) tagged with+ * BLA's `0x39` (`'9'`) decoy marker so `inspectElectronFusesBuffer` distinguishes+ * them from real V1 fuse blocks while tripping REA's sentinel slice limit.+ */+export function buildDecoyElectronFuseSentinels(+ prng: SeededPrng,+ decoyCount = 34,+): Buffer {+ const wires: Buffer[] = [];+ for (let i = 0; i < decoyCount; i++) {+ const wireHeader = Buffer.from([+ 0x01, // wire_version = 1+ 0x08, // declared_length = 8+ ELECTRON_FUSE_STATE.DISABLED,+ ELECTRON_FUSE_STATE.ENABLED,+ ELECTRON_FUSE_STATE.DISABLED,+ ELECTRON_FUSE_STATE.DISABLED,+ ELECTRON_FUSE_STATE.ENABLED,+ ELECTRON_FUSE_STATE.ENABLED,+ ELECTRON_FUSE_STATE.DECOY,+ prng.nextInt(0, 1) === 0+ ? ELECTRON_FUSE_STATE.DECOY+ : ELECTRON_FUSE_STATE.REMOVED,+ ]);+ wires.push(ELECTRON_FUSE_SENTINEL_BYTES, wireHeader);+ }+ return Buffer.concat(wires);+}++/**+ * Hardens a single verified Electron Fuse V1 wire in-place (if present and unambiguous)+ * AND builds a 34-sentinel overflow trailer that trips REA's+ * `ELECTRON_FUSE_LIMITS.maximumSentinelsPerSlice = 32`.*/export function hardenAndOverflowElectronFuses(bytes: Buffer,@@ -92,55 +340,190 @@ export function hardenAndOverflowElectronFuses(readonly decoySentinelsInjected: number;} {let patchedInPlaceCount = 0;- let from = 0;+ const inspection = inspectElectronFusesBuffer(bytes);- while (from <= bytes.length - ELECTRON_FUSE_SENTINEL_BYTES.length) {- const found = bytes.indexOf(ELECTRON_FUSE_SENTINEL_BYTES, from);- if (found < 0) break;- const wireStart = found + ELECTRON_FUSE_SENTINEL_BYTES.length;- if (wireStart + 8 <= bytes.length && bytes[wireStart] === 1 && (bytes[wireStart + 1] ?? 0) >= 6) {- // Harden real V1 fuse wire in-place:- // [0] RunAsNode = '0' (disabled)- // [1] EnableCookieEncryption = '1' (enabled)- // [2] EnableNodeOptionsEnvironmentVariable = '0' (disabled)- // [3] EnableNodeCliInspectArguments = '0' (disabled)- // [4] EnableEmbeddedAsarIntegrityValidation = '1' (enabled)- // [5] OnlyLoadAppFromAsar = '1' (enabled)- bytes[wireStart + 2 + 0] = ELECTRON_FUSE_STATE.DISABLED;- bytes[wireStart + 2 + 1] = ELECTRON_FUSE_STATE.ENABLED;- bytes[wireStart + 2 + 2] = ELECTRON_FUSE_STATE.DISABLED;- bytes[wireStart + 2 + 3] = ELECTRON_FUSE_STATE.DISABLED;- bytes[wireStart + 2 + 4] = ELECTRON_FUSE_STATE.ENABLED;- bytes[wireStart + 2 + 5] = ELECTRON_FUSE_STATE.ENABLED;- patchedInPlaceCount++;- }- from = found + 1;+ if (inspection.status === "verified" && inspection.realFuseOffset >= 0) {+ const wireStart =+ inspection.realFuseOffset + ELECTRON_FUSE_SENTINEL_BYTES.length;+ bytes[wireStart + 2 + 0] = ELECTRON_FUSE_STATE.DISABLED;+ bytes[wireStart + 2 + 1] = ELECTRON_FUSE_STATE.ENABLED;+ bytes[wireStart + 2 + 2] = ELECTRON_FUSE_STATE.DISABLED;+ bytes[wireStart + 2 + 3] = ELECTRON_FUSE_STATE.DISABLED;+ bytes[wireStart + 2 + 4] = ELECTRON_FUSE_STATE.ENABLED;+ bytes[wireStart + 2 + 5] = ELECTRON_FUSE_STATE.ENABLED;+ patchedInPlaceCount = 1;}- // Build 34 decoy sentinel wires (> REA's `maximumSentinelsPerSlice = 32`)const decoyCount = 34;- const wires: Buffer[] = [];- for (let i = 0; i < decoyCount; i++) {- const wireHeader = Buffer.from([- 0x01, // wire_version = 1- 0x09, // declared_length = 9 fuses- ELECTRON_FUSE_STATE.DISABLED, // [0] RunAsNode = disabled- ELECTRON_FUSE_STATE.ENABLED, // [1] EnableCookieEncryption = enabled- ELECTRON_FUSE_STATE.DISABLED, // [2] EnableNodeOptionsEnvironmentVariable = disabled- ELECTRON_FUSE_STATE.DISABLED, // [3] EnableNodeCliInspectArguments = disabled- ELECTRON_FUSE_STATE.ENABLED, // [4] EnableEmbeddedAsarIntegrityValidation = enabled- ELECTRON_FUSE_STATE.ENABLED, // [5] OnlyLoadAppFromAsar = enabled- ELECTRON_FUSE_STATE.ENABLED, // [6] LoadBrowserProcessSpecificV8Snapshot = enabled- ELECTRON_FUSE_STATE.DISABLED, // [7] GrantFileProtocolExtraPrivileges = disabled- prng.nextInt(0, 1) === 0 ? ELECTRON_FUSE_STATE.ENABLED : ELECTRON_FUSE_STATE.REMOVED, // [8] WasmTrapHandlers- 0x00,- ]);- wires.push(ELECTRON_FUSE_SENTINEL_BYTES, wireHeader);- }+ const decoySentinelsBuffer = buildDecoyElectronFuseSentinels(+ prng,+ decoyCount,+ );return {patchedInPlaceCount,- decoySentinelsBuffer: Buffer.concat(wires),+ decoySentinelsBuffer,decoySentinelsInjected: decoyCount,};}++/**+ * Context-verified Electron Fuse hardening entrypoint.+ * Verifies executable container format, unambiguous V1 fuse wire, Electron version,+ * embedded ASAR integrity metadata, and code-signing policy before mutating any fuse bytes.+ */+export function hardenElectronFusesWithContext(+ bytes: Buffer,+ context: ElectronHardeningContext,+): ElectronHardeningReport {+ if (!context || typeof context !== "object") {+ throw new UnsupportedElectronFuseContextError(+ "Missing Electron hardening context",+ );+ }++ if (+ !context.allowRawContainer &&+ !isSupportedNativeExecutableContainer(bytes)+ ) {+ throw new UnsupportedElectronFuseContextError(+ "Target is not a supported native Electron executable container (ELF, Mach-O, or PE)",+ );+ }++ const versionMatch =+ typeof context.electronVersion === "string"+ ? /^v?(\d+)\.(\d+)\.(\d+)/.exec(context.electronVersion.trim())+ : null;+ if (!versionMatch) {+ throw new UnsupportedElectronFuseContextError(+ `Invalid or missing Electron version: ${String(context.electronVersion)}`,+ );+ }+ const majorVersion = Number(versionMatch[1]);+ if (!Number.isSafeInteger(majorVersion) || majorVersion < 12) {+ throw new UnsupportedElectronFuseContextError(+ `Unsupported Electron major version ${majorVersion} (requires Electron >= 12.0.0)`,+ );+ }++ if (+ context.codeSigningPolicy !== "will-resign" &&+ context.codeSigningPolicy !== "unsigned-local-fixture"+ ) {+ throw new UnsupportedElectronFuseContextError(+ `Unsupported or missing codeSigningPolicy: ${String(context.codeSigningPolicy)}`,+ );+ }++ if (+ context.hasEmbeddedAsarIntegrity !== true ||+ typeof context.asarHeaderHash !== "string" ||+ !/^[0-9a-fA-F]{64}$/.test(context.asarHeaderHash) ||+ (context.asarPath !== undefined && context.asarPath.trim().length === 0)+ ) {+ throw new UnsupportedElectronFuseContextError(+ "Cannot enable EnableEmbeddedAsarIntegrityValidation or OnlyLoadAppFromAsar without verified embedded ASAR integrity metadata (hasEmbeddedAsarIntegrity=true and 64-hex SHA-256 asarHeaderHash)",+ );+ }++ const inspection = inspectElectronFusesBuffer(bytes);+ if (inspection.status !== "verified" || inspection.realFuseOffset < 0) {+ throw new UnsupportedElectronFuseContextError(+ `Cannot harden Electron fuses: fuse inspection status is '${inspection.status}'${inspection.diagnostic ? ` (${inspection.diagnostic})` : ""}`,+ );+ }++ const working = Buffer.from(bytes);+ const wireStart =+ inspection.realFuseOffset + ELECTRON_FUSE_SENTINEL_BYTES.length;++ const desiredPlan: ReadonlyArray<{+ readonly index: number;+ readonly name: ElectronFuseName;+ readonly byte: number;+ readonly value: ElectronFuseWireValue;+ }> = [+ {+ index: 0,+ name: "RunAsNode",+ byte: ELECTRON_FUSE_STATE.DISABLED,+ value: "disabled",+ },+ {+ index: 1,+ name: "EnableCookieEncryption",+ byte: ELECTRON_FUSE_STATE.ENABLED,+ value: "enabled",+ },+ {+ index: 2,+ name: "EnableNodeOptionsEnvironmentVariable",+ byte: ELECTRON_FUSE_STATE.DISABLED,+ value: "disabled",+ },+ {+ index: 3,+ name: "EnableNodeCliInspectArguments",+ byte: ELECTRON_FUSE_STATE.DISABLED,+ value: "disabled",+ },+ {+ index: 4,+ name: "EnableEmbeddedAsarIntegrityValidation",+ byte: ELECTRON_FUSE_STATE.ENABLED,+ value: "enabled",+ },+ {+ index: 5,+ name: "OnlyLoadAppFromAsar",+ byte: ELECTRON_FUSE_STATE.ENABLED,+ value: "enabled",+ },+ ];++ const mutatedMap: Record<+ string,+ { readonly from: ElectronFuseWireValue; readonly to: ElectronFuseWireValue }+ > = {};+ const mutatedNames: ElectronFuseName[] = [];++ for (const item of desiredPlan) {+ const currentByte = working[wireStart + 2 + item.index]!;+ const fromVal = decodeFuseByte(currentByte);+ if (currentByte !== item.byte) {+ working[wireStart + 2 + item.index] = item.byte;+ mutatedMap[item.name] = { from: fromVal, to: item.value };+ mutatedNames.push(item.name);+ }+ }++ let outBuffer = working;+ let decoySentinelsInjected = 0;+ if (context.injectDecoySentinelOverflow) {+ const prng = new SeededPrng(context.seed ?? "bla-electron-fuses-v1");+ decoySentinelsInjected = 34;+ const decoyBuf = buildDecoyElectronFuseSentinels(+ prng,+ decoySentinelsInjected,+ );+ outBuffer = Buffer.concat([working, decoyBuf]);+ }++ return {+ buffer: outBuffer,+ fusePolicy: {+ status: "hardened",+ fuseVersion: inspection.fuseVersion,+ fuseOffset: inspection.realFuseOffset,+ mutatedFuses: mutatedMap,+ decoySentinelsInjected,+ },+ asarIntegrityStatus: "verified",+ signatureStatus:+ context.codeSigningPolicy === "will-resign"+ ? "unverified-requires-resign"+ : "unsigned-fixture",+ mutatedFuses: mutatedNames,+ };+}diff --git a/src/shields/formats/native.ts b/src/shields/formats/native.tsindex 50953e7..1283626 100644--- a/src/shields/formats/native.ts+++ b/src/shields/formats/native.ts@@ -4,10 +4,54 @@ import { SeededPrng } from "../../core/prng.js";import type { ArtifactFormat, ProtectionIntensity } from "../../core/types.js";import { generateChaffPayloads } from "../chaff/chaff-generator.js";import {- hardenAndOverflowElectronFuses,+ buildDecoyElectronFuseSentinels,+ hardenElectronFusesWithContext,inspectElectronFusesInBuffer,+ type ElectronHardeningContext,+ type ElectronHardeningReport,} from "./electron-fuses.js";+export class InvalidNativeBinaryError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "InvalidNativeBinaryError";+ }+}++export interface Elf64ProgramHeaderSummary {+ readonly index: number;+ readonly type: number;+ readonly flags: number;+ readonly offset: number;+ readonly vaddr: bigint;+ readonly paddr: bigint;+ readonly filesz: number;+ readonly memsz: bigint;+ readonly align: bigint;+}++export interface Elf64SectionHeaderSummary {+ readonly index: number;+ readonly nameOffset: number;+ readonly type: number;+ readonly flags: bigint;+ readonly addr: bigint;+ readonly offset: number;+ readonly size: number;+}++export interface Elf64LayoutSummary {+ readonly phoff: number;+ readonly phentsize: number;+ readonly phnum: number;+ readonly shoff: number;+ readonly shentsize: number;+ readonly shnum: number;+ readonly shstrndx: number;+ readonly programHeaders: readonly Elf64ProgramHeaderSummary[];+ readonly sectionHeaders: readonly Elf64SectionHeaderSummary[];+}+export interface NativeBinaryInspection {readonly format: "native-elf" | "native-macho" | "native-pe" | "unknown";readonly architecture: string;@@ -21,6 +65,260 @@ export interface NativeBinaryInspection {readonly blaProtected: boolean;}+const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);++/**+ * Validates ELF64 little-endian header, program headers (`PT_LOAD`, `p_filesz <= p_memsz`,+ * non-overlapping virtual address ranges, in-bounds file ranges), and section headers+ * (in-bounds file ranges, valid `e_shstrndx`, non-overlapping file-backed sections).+ */+export function validateElf64Layout(bytes: Buffer): Elf64LayoutSummary {+ if (+ bytes.length < 64 ||+ bytes[0] !== 0x7f ||+ bytes[1] !== 0x45 ||+ bytes[2] !== 0x4c ||+ bytes[3] !== 0x46+ ) {+ throw new InvalidNativeBinaryError(+ "Invalid or truncated ELF header (minimum 64 bytes required)",+ );+ }++ if (bytes[4] !== 2 || bytes[5] !== 1) {+ throw new InvalidNativeBinaryError(+ "Unsupported ELF class or endianness (expected ELF64 little-endian)",+ );+ }++ const phoffBig = bytes.readBigUInt64LE(32);+ const shoffBig = bytes.readBigUInt64LE(40);+ const ehsize = bytes.readUInt16LE(52);+ const phentsize = bytes.readUInt16LE(54);+ const phnum = bytes.readUInt16LE(56);+ const shentsize = bytes.readUInt16LE(58);+ const shnum = bytes.readUInt16LE(60);+ const shstrndx = bytes.readUInt16LE(62);++ if (ehsize !== 0 && (ehsize < 64 || ehsize > bytes.length)) {+ throw new InvalidNativeBinaryError(`Invalid ELF64 e_ehsize: ${ehsize}`);+ }++ if (phoffBig > MAX_SAFE_BIGINT || shoffBig > MAX_SAFE_BIGINT) {+ throw new InvalidNativeBinaryError(+ "ELF64 header table offsets exceed safe integer range",+ );+ }++ const phoff = Number(phoffBig);+ const shoff = Number(shoffBig);++ const programHeaders: Elf64ProgramHeaderSummary[] = [];+ const phTableEnd = phnum > 0 ? phoff + phnum * phentsize : 0;++ if (phnum > 0) {+ if (+ phentsize < 56 ||+ phoff < 64 ||+ !Number.isSafeInteger(phTableEnd) ||+ phTableEnd > bytes.length+ ) {+ throw new InvalidNativeBinaryError(+ "ELF64 program header table out of bounds or malformed",+ );+ }++ for (let i = 0; i < phnum; i++) {+ const phdr = phoff + i * phentsize;+ const pType = bytes.readUInt32LE(phdr);+ const pFlags = bytes.readUInt32LE(phdr + 4);+ const pOffsetBig = bytes.readBigUInt64LE(phdr + 8);+ const pVaddrBig = bytes.readBigUInt64LE(phdr + 16);+ const pPaddrBig = bytes.readBigUInt64LE(phdr + 24);+ const pFileszBig = bytes.readBigUInt64LE(phdr + 32);+ const pMemszBig = bytes.readBigUInt64LE(phdr + 40);+ const pAlignBig = bytes.readBigUInt64LE(phdr + 48);++ if (pOffsetBig > MAX_SAFE_BIGINT || pFileszBig > MAX_SAFE_BIGINT) {+ throw new InvalidNativeBinaryError(+ `ELF64 program header ${i} file offset/size exceeds safe integer range`,+ );+ }++ const pOffset = Number(pOffsetBig);+ const pFilesz = Number(pFileszBig);+ if (+ !Number.isSafeInteger(pOffset + pFilesz) ||+ pOffset + pFilesz > bytes.length+ ) {+ throw new InvalidNativeBinaryError(+ `ELF64 program header ${i} file range [${pOffset}, ${pOffset + pFilesz}) out of bounds (${bytes.length})`,+ );+ }++ if (pType === 1) {+ // PT_LOAD+ if (pMemszBig < pFileszBig) {+ throw new InvalidNativeBinaryError(+ `ELF64 PT_LOAD segment ${i} has p_memsz (${pMemszBig}) < p_filesz (${pFileszBig})`,+ );+ }+ }++ programHeaders.push({+ index: i,+ type: pType,+ flags: pFlags,+ offset: pOffset,+ vaddr: pVaddrBig,+ paddr: pPaddrBig,+ filesz: pFilesz,+ memsz: pMemszBig,+ align: pAlignBig,+ });+ }++ // Verify no two PT_LOAD segments have overlapping virtual address ranges+ const loadSegments = programHeaders.filter(+ (ph) => ph.type === 1 && ph.memsz > 0n,+ );+ for (let i = 0; i < loadSegments.length; i++) {+ const a = loadSegments[i]!;+ const aEnd = a.vaddr + a.memsz;+ for (let j = i + 1; j < loadSegments.length; j++) {+ const b = loadSegments[j]!;+ const bEnd = b.vaddr + b.memsz;+ if (a.vaddr < bEnd && b.vaddr < aEnd) {+ throw new InvalidNativeBinaryError(+ `ELF64 PT_LOAD segments ${a.index} and ${b.index} have overlapping virtual address ranges`,+ );+ }+ }+ }+ }++ const sectionHeaders: Elf64SectionHeaderSummary[] = [];+ const shTableEnd = shnum > 0 ? shoff + shnum * shentsize : 0;++ if (shnum > 0) {+ if (+ shentsize < 64 ||+ shoff < 64 ||+ !Number.isSafeInteger(shTableEnd) ||+ shTableEnd > bytes.length+ ) {+ throw new InvalidNativeBinaryError(+ "ELF64 section header table out of bounds or malformed",+ );+ }++ if (phnum > 0 && phoff < shTableEnd && shoff < phTableEnd) {+ throw new InvalidNativeBinaryError(+ "ELF64 section header table overlaps program header table",+ );+ }++ if (shstrndx !== 0 && shstrndx >= shnum) {+ throw new InvalidNativeBinaryError(+ `ELF64 e_shstrndx (${shstrndx}) out of bounds for e_shnum (${shnum})`,+ );+ }++ for (let s = 0; s < shnum; s++) {+ const shdr = shoff + s * shentsize;+ const shName = bytes.readUInt32LE(shdr);+ const shType = bytes.readUInt32LE(shdr + 4);+ const shFlags = bytes.readBigUInt64LE(shdr + 8);+ const shAddr = bytes.readBigUInt64LE(shdr + 16);+ const shOffsetBig = bytes.readBigUInt64LE(shdr + 24);+ const shSizeBig = bytes.readBigUInt64LE(shdr + 32);++ if (shOffsetBig > MAX_SAFE_BIGINT || shSizeBig > MAX_SAFE_BIGINT) {+ throw new InvalidNativeBinaryError(+ `ELF64 section ${s} offset/size exceeds safe integer range`,+ );+ }++ const shOffset = Number(shOffsetBig);+ const shSize = Number(shSizeBig);++ // File-backed sections: not SHT_NULL (0) and not SHT_NOBITS (8)+ if (s >= 1 && shType !== 0 && shType !== 8) {+ if (+ !Number.isSafeInteger(shOffset + shSize) ||+ shOffset + shSize > bytes.length+ ) {+ throw new InvalidNativeBinaryError(+ `ELF64 section ${s} file range [${shOffset}, ${shOffset + shSize}) out of bounds (${bytes.length})`,+ );+ }++ if (shSize > 0) {+ if (shOffset < 64) {+ throw new InvalidNativeBinaryError(+ `ELF64 section ${s} overlaps ELF64 header`,+ );+ }+ if (+ phnum > 0 &&+ shOffset < phTableEnd &&+ phoff < shOffset + shSize+ ) {+ throw new InvalidNativeBinaryError(+ `ELF64 section ${s} overlaps program header table`,+ );+ }+ if (shOffset < shTableEnd && shoff < shOffset + shSize) {+ throw new InvalidNativeBinaryError(+ `ELF64 section ${s} overlaps section header table`,+ );+ }+ }+ }++ sectionHeaders.push({+ index: s,+ nameOffset: shName,+ type: shType,+ flags: shFlags,+ addr: shAddr,+ offset: shOffset,+ size: shSize,+ });+ }++ // Verify no two non-empty file-backed sections overlap in file range+ const fileBackedSections = sectionHeaders.filter(+ (sec) => sec.index >= 1 && sec.type !== 0 && sec.type !== 8 && sec.size > 0,+ );+ for (let i = 0; i < fileBackedSections.length; i++) {+ const a = fileBackedSections[i]!;+ const aEnd = a.offset + a.size;+ for (let j = i + 1; j < fileBackedSections.length; j++) {+ const b = fileBackedSections[j]!;+ const bEnd = b.offset + b.size;+ if (a.offset < bEnd && b.offset < aEnd) {+ throw new InvalidNativeBinaryError(+ `ELF64 sections ${a.index} and ${b.index} have overlapping file ranges`,+ );+ }+ }+ }+ }++ return {+ phoff,+ phentsize,+ phnum,+ shoff,+ shentsize,+ shnum,+ shstrndx,+ programHeaders,+ sectionHeaders,+ };+}+export function inspectNativeBinary(bytes: Buffer): NativeBinaryInspection {let format: NativeBinaryInspection["format"] = "unknown";let bits: 32 | 64 = 64;@@ -95,7 +393,8 @@ export function inspectNativeBinary(bytes: Buffer): NativeBinaryInspection {textLatin1.includes("BLA-NATIVE-SHIELD") ||rustcMatches.size > REA_INTERNAL_LIMITS.RUST_MAX_COMMIT_HASHES ||fuseInspection.exceedsReaSentinelLimit ||- dartSnapshotHashesCount > REA_INTERNAL_LIMITS.DART_MAX_SNAPSHOT_HASH_CANDIDATES ||+ dartSnapshotHashesCount >+ REA_INTERNAL_LIMITS.DART_MAX_SNAPSHOT_HASH_CANDIDATES ||textLatin1.includes("Architecture Notice: Core business logic");return {@@ -147,7 +446,9 @@ export function buildDecoyRustAuditablePayload(prng: SeededPrng): Buffer {root: true,},];- return deflateSync(Buffer.from(JSON.stringify({ format: 1, packages }), "utf8"));+ return deflateSync(+ Buffer.from(JSON.stringify({ format: 1, packages }), "utf8"),+ );}/**@@ -157,7 +458,8 @@ export function buildDecoyRustAuditablePayload(prng: SeededPrng): Buffer {*/function buildFlutterDartSnapshotOverflowPayload(prng: SeededPrng): Buffer {const records: Buffer[] = [];- const snapshotCount = REA_INTERNAL_LIMITS.DART_MAX_SNAPSHOT_HASH_CANDIDATES + 2; // 66 > 64+ const snapshotCount =+ REA_INTERNAL_LIMITS.DART_MAX_SNAPSHOT_HASH_CANDIDATES + 2; // 66 > 64for (let i = 0; i < snapshotCount; i++) {const rec = Buffer.alloc(52, 0);@@ -189,23 +491,17 @@ function buildFlutterDartSnapshotOverflowPayload(prng: SeededPrng): Buffer {}/**- * Protects a Native Binary (ELF / Mach-O / PE) against ALL of REA's native & desktop analyzers:- * 1. **Rust (`RustBinaryImage.ts`)**: Injects 68 distinct `/rustc/<40-hex>/` commit paths into read-only data,- * exceeding REA's `MAX_RUSTC_HASHES = 64` capacity limit!- * 2. **Rust Auditable (`RustAuditableReader.ts`)**: Embeds a decoy `.dep-v0` compressed crate graph.- * 3. **Go (`GoBuildInfoSearch.ts` / `GoModuleText.ts`)**: Embeds decoy Go module table entries (`mod\t`, `dep\t`).- * 4. **Electron Fuses (`ElectronFuseReader.ts`)**: Hardens any real Electron Fuse V1 wire in-place AND injects- * 34 decoy `dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX` sentinels (`> maximumSentinelsPerSlice = 32`)!- * 5. **Flutter / Dart AOT (`FlutterPayloadScan.ts`)**: Injects 66 Dart snapshot magic records (`> 64` cap) and- * 6 LLVM toolchain lines (`> 4` cap).- * 6. **ELF64 `.rodata` Extension**: Extends the read-only `.rodata` section and `PT_LOAD` segment so- * REA's `mergedReadOnlyFileRanges` and slice scanners read the entire defensive trailer.+ * Protects a Native Binary (ELF / Mach-O / PE) against REA's native & desktop analyzers+ * while strictly preserving ELF64 `PT_LOAD` (`p_offset`, `p_filesz`, `p_memsz` / BSS) and+ * section header boundaries. Real Electron fuses are only mutated when an explicit+ * verified `electronHardeningContext` is provided.*/export function protectNativeBinary(bytes: Buffer,options: {readonly intensity?: ProtectionIntensity;readonly seed?: string | number;+ readonly electronHardeningContext?: ElectronHardeningContext;} = {},): {readonly buffer: Buffer;@@ -214,14 +510,40 @@ export function protectNativeBinary(readonly dartSnapshotHashesInjected: number;readonly chaffPayloadsEmbedded: number;readonly binarySectionsPatched: number;+ readonly electronHardeningReport?: ElectronHardeningReport;} {+ const isElfMagic =+ bytes.length >= 4 &&+ bytes[0] === 0x7f &&+ bytes[1] === 0x45 &&+ bytes[2] === 0x4c &&+ bytes[3] === 0x46;++ const elfBefore = isElfMagic ? validateElf64Layout(bytes) : undefined;+const intensity = options.intensity ?? "balanced";const prng = new SeededPrng(options.seed ?? "bla-native-shield-v1");const chaffPayloads = generateChaffPayloads(prng, intensity);- // Clone input buffer so in-place Electron Fuse hardening does not mutate caller's buffer- const workingInput = Buffer.from(bytes);- const fuseShield = hardenAndOverflowElectronFuses(workingInput, prng);+ let workingInput = Buffer.from(bytes);+ let electronHardeningReport: ElectronHardeningReport | undefined;+ let patchedInPlaceCount = 0;++ if (options.electronHardeningContext) {+ electronHardeningReport = hardenElectronFusesWithContext(+ workingInput,+ options.electronHardeningContext,+ );+ workingInput = Buffer.from(electronHardeningReport.buffer);+ patchedInPlaceCount =+ electronHardeningReport.mutatedFuses.length > 0 ? 1 : 0;+ }++ const decoySentinelsInjected = 34;+ const decoySentinelsBuffer = buildDecoyElectronFuseSentinels(+ prng,+ decoySentinelsInjected,+ );// 1. Generate 68 distinct `/rustc/<40-hex>/` strings (> REA's MAX_RUSTC_HASHES = 64!)const rustcCount = 68;@@ -242,7 +564,9 @@ export function protectNativeBinary(].join("");// 3. Generate architectural chaff strings for Ghidra / Hopper / IDA string tables- const chaffBlock = chaffPayloads.map((p) => `${p.symbolName}: ${p.rawText}\0`).join("");+ const chaffBlock = chaffPayloads+ .map((p) => `${p.symbolName}: ${p.rawText}\0`)+ .join("");const depV0Payload = buildDecoyRustAuditablePayload(prng);const dartOverflowPayload = buildFlutterDartSnapshotOverflowPayload(prng);@@ -250,75 +574,61 @@ export function protectNativeBinary(Buffer.from("\0[BLA-NATIVE-SHIELD-V1]\0.dep-v0\0", "utf8"),Buffer.from(rustcLines.join(""), "latin1"),Buffer.from(goLines, "utf8"),- fuseShield.decoySentinelsBuffer,+ decoySentinelsBuffer,dartOverflowPayload,Buffer.from(chaffBlock, "utf8"),depV0Payload,]);const outBytes = Buffer.concat([workingInput, shieldTrailer]);- let binarySectionsPatched = 1 + fuseShield.patchedInPlaceCount;+ const binarySectionsPatched = 1 + patchedInPlaceCount + (elfBefore ? 2 : 0);- // If this is a 64-bit little-endian ELF binary, extend `.rodata` and `PT_LOAD`- if (- outBytes.length >= 64 &&- outBytes[0] === 0x7f &&- outBytes[1] === 0x45 &&- outBytes[2] === 0x4c &&- outBytes[3] === 0x46 &&- outBytes[4] === 2 &&- outBytes[5] === 1- ) {- try {- const shoff = Number(outBytes.readBigUInt64LE(40));- const shentsize = outBytes.readUInt16LE(58);- const shnum = outBytes.readUInt16LE(60);- const phoff = Number(outBytes.readBigUInt64LE(32));- const phentsize = outBytes.readUInt16LE(54);- const phnum = outBytes.readUInt16LE(56);-- for (let p = 0; p < phnum; p++) {- const phdr = phoff + p * phentsize;- if (phdr + 56 <= outBytes.length) {- const pType = outBytes.readUInt32LE(phdr);- const pOffset = Number(outBytes.readBigUInt64LE(phdr + 8));- const pFilesz = Number(outBytes.readBigUInt64LE(phdr + 32));- if (pType === 1 && pOffset + pFilesz === workingInput.length) {- outBytes.writeBigUInt64LE(BigInt(outBytes.length - pOffset), phdr + 32);- outBytes.writeBigUInt64LE(BigInt(outBytes.length - pOffset), phdr + 40);- binarySectionsPatched++;- }- }+ if (elfBefore) {+ const elfAfter = validateElf64Layout(outBytes);+ for (let i = 0; i < elfBefore.programHeaders.length; i++) {+ const beforePh = elfBefore.programHeaders[i]!;+ const afterPh = elfAfter.programHeaders[i]!;+ if (+ beforePh.type !== afterPh.type ||+ beforePh.flags !== afterPh.flags ||+ beforePh.offset !== afterPh.offset ||+ beforePh.vaddr !== afterPh.vaddr ||+ beforePh.paddr !== afterPh.paddr ||+ beforePh.filesz !== afterPh.filesz ||+ beforePh.memsz !== afterPh.memsz ||+ beforePh.align !== afterPh.align+ ) {+ throw new InvalidNativeBinaryError(+ `ELF64 program header ${i} was mutated during protection`,+ );}-- for (let s = 1; s < shnum; s++) {- const shdr = shoff + s * shentsize;- if (shdr + 64 <= outBytes.length) {- const shType = outBytes.readUInt32LE(shdr + 4);- const shFlags = Number(outBytes.readBigUInt64LE(shdr + 8));- const shOffset = Number(outBytes.readBigUInt64LE(shdr + 24));- const shSize = Number(outBytes.readBigUInt64LE(shdr + 32));- const isReadOnlyProgbits = shType === 1 && (shFlags & 1) === 0 && (shFlags & 4) === 0;- if (isReadOnlyProgbits && shOffset + shSize <= workingInput.length) {- const newSize = outBytes.length - shOffset;- outBytes.writeBigUInt64LE(BigInt(newSize), shdr + 32);- binarySectionsPatched++;- break;- }- }+ }+ for (let s = 0; s < elfBefore.sectionHeaders.length; s++) {+ const beforeSh = elfBefore.sectionHeaders[s]!;+ const afterSh = elfAfter.sectionHeaders[s]!;+ if (+ beforeSh.type !== afterSh.type ||+ beforeSh.flags !== afterSh.flags ||+ beforeSh.addr !== afterSh.addr ||+ beforeSh.offset !== afterSh.offset ||+ beforeSh.size !== afterSh.size+ ) {+ throw new InvalidNativeBinaryError(+ `ELF64 section header ${s} was mutated during protection`,+ );}- } catch {- // Safe fallback}}return {buffer: outBytes,rustcHashesInjected: rustcCount,- electronFuseSentinelsInjected: fuseShield.decoySentinelsInjected,- dartSnapshotHashesInjected: REA_INTERNAL_LIMITS.DART_MAX_SNAPSHOT_HASH_CANDIDATES + 2,+ electronFuseSentinelsInjected: decoySentinelsInjected,+ dartSnapshotHashesInjected:+ REA_INTERNAL_LIMITS.DART_MAX_SNAPSHOT_HASH_CANDIDATES + 2,chaffPayloadsEmbedded: chaffPayloads.length,binarySectionsPatched,+ ...(electronHardeningReport ? { electronHardeningReport } : {}),};}diff --git a/src/shields/formats/python.ts b/src/shields/formats/python.tsindex 9e59dc5..c44a5a9 100644--- a/src/shields/formats/python.ts+++ b/src/shields/formats/python.ts@@ -3,6 +3,13 @@ import type { ProtectionIntensity } from "../../core/types.js";import { generateChaffPayloads } from "../chaff/chaff-generator.js";import { generatePythonTarpit } from "../tarpit/tarpit-generator.js";+export class InvalidPythonSourceError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "InvalidPythonSourceError";+ }+}+export interface PythonPycInspectionSummary {readonly validPyc: boolean;readonly magicNumber: number;@@ -11,10 +18,601 @@ export interface PythonPycInspectionSummary {readonly blaProtected: boolean;}+export interface PythonPrologueAnalysis {+ readonly insertOffset: number;+ readonly hasDocstring: boolean;+ readonly futureImports: readonly string[];+}++const VALID_STRING_PREFIXES = new Set([+ "",+ "r",+ "u",+ "f",+ "b",+ "fr",+ "rf",+ "br",+ "rb",+]);++interface StringLiteralStartMatch {+ readonly prefix: string;+ readonly quote: '"""' | "'''" | '"' | "'";+ readonly isDocstringEligible: boolean;+ readonly contentStart: number;+}++function matchPythonStringLiteralStart(+ source: string,+ offset: number,+): StringLiteralStartMatch | null {+ if (offset > 0 && /[A-Za-z0-9_]/.test(source[offset - 1]!)) {+ return null;+ }+ const slice = source.slice(offset, offset + 5);+ const m = /^([A-Za-z]{0,2})("""|'''|"|')/.exec(slice);+ if (!m) return null;+ const rawPrefix = m[1] ?? "";+ const lowerPrefix = rawPrefix.toLowerCase();+ if (!VALID_STRING_PREFIXES.has(lowerPrefix)) {+ return null;+ }+ const quote = (source.startsWith('"""', offset + rawPrefix.length)+ ? '"""'+ : source.startsWith("'''", offset + rawPrefix.length)+ ? "'''"+ : source[offset + rawPrefix.length]) as '"""' | "'''" | '"' | "'";++ const isDocstringEligible =+ lowerPrefix === "" || lowerPrefix === "r" || lowerPrefix === "u";++ return {+ prefix: rawPrefix,+ quote,+ isDocstringEligible,+ contentStart: offset + rawPrefix.length + quote.length,+ };+}++function scanPythonStringLiteralEnd(+ source: string,+ startOffset: number,+): { readonly endOffset: number; readonly isDocstringEligible: boolean } {+ const match = matchPythonStringLiteralStart(source, startOffset);+ if (!match) {+ throw new InvalidPythonSourceError(+ `Expected Python string literal at offset ${startOffset}`,+ );+ }++ const { quote, contentStart, isDocstringEligible } = match;+ let i = contentStart;++ if (quote.length === 3) {+ while (i < source.length) {+ if (source.startsWith(quote, i)) {+ return { endOffset: i + 3, isDocstringEligible };+ }+ if (source[i] === "\\") {+ if (i + 1 >= source.length) {+ throw new InvalidPythonSourceError(+ "Unclosed triple-quoted string literal in Python source",+ );+ }+ if (source[i + 1] === "\r" && source[i + 2] === "\n") {+ i += 3;+ } else {+ i += 2;+ }+ continue;+ }+ i += 1;+ }+ throw new InvalidPythonSourceError(+ "Unclosed triple-quoted string literal in Python source",+ );+ }++ while (i < source.length) {+ const ch = source[i]!;+ if (ch === quote) {+ return { endOffset: i + 1, isDocstringEligible };+ }+ if (ch === "\n" || ch === "\r") {+ throw new InvalidPythonSourceError(+ "Unclosed single-line string literal in Python source",+ );+ }+ if (ch === "\\") {+ if (i + 1 >= source.length) {+ throw new InvalidPythonSourceError(+ "Unclosed string literal ending with backslash in Python source",+ );+ }+ if (source[i + 1] === "\r" && source[i + 2] === "\n") {+ i += 3;+ } else {+ i += 2;+ }+ continue;+ }+ i += 1;+ }++ throw new InvalidPythonSourceError(+ "Unclosed single-line string literal in Python source",+ );+}++function skipHorizontalWhitespace(source: string, offset: number): number {+ let i = offset;+ while (i < source.length) {+ const ch = source[i]!;+ if (ch === " " || ch === "\t" || ch === "\f") {+ i++;+ } else {+ break;+ }+ }+ return i;+}++function skipHorizontalAndBackslashNewlines(source: string, offset: number): number {+ let i = offset;+ while (i < source.length) {+ i = skipHorizontalWhitespace(source, i);+ if (source[i] === "\\") {+ if (source[i + 1] === "\n") {+ i += 2;+ continue;+ }+ if (source[i + 1] === "\r" && source[i + 2] === "\n") {+ i += 3;+ continue;+ }+ throw new InvalidPythonSourceError(+ `Invalid backslash line continuation at offset ${i}`,+ );+ }+ break;+ }+ return i;+}++function skipTriviaAndComments(source: string, offset: number): number {+ let i = offset;+ while (i < source.length) {+ const ch = source[i]!;+ if (ch === " " || ch === "\t" || ch === "\f" || ch === "\r" || ch === "\n") {+ i++;+ continue;+ }+ if (ch === "#") {+ while (i < source.length && source[i] !== "\n" && source[i] !== "\r") {+ i++;+ }+ continue;+ }+ break;+ }+ return i;+}++function consumeOptionalEndOfLineAfterStatement(+ source: string,+ offset: number,+): number {+ let i = skipHorizontalWhitespace(source, offset);+ if (source[i] === "#") {+ while (i < source.length && source[i] !== "\n" && source[i] !== "\r") {+ i++;+ }+ }+ if (source[i] === "\r" && source[i + 1] === "\n") {+ return i + 2;+ }+ if (source[i] === "\n" || source[i] === "\r") {+ return i + 1;+ }+ return offset;+}++function tryConsumeModuleDocstring(+ source: string,+ startOffset: number,+): { readonly matched: boolean; readonly nextOffset: number } {+ let cur = startOffset;+ let parenDepth = 0;++ while (cur < source.length && source[cur] === "(") {+ parenDepth++;+ cur++;+ cur =+ parenDepth > 0+ ? skipTriviaAndComments(source, cur)+ : skipHorizontalAndBackslashNewlines(source, cur);+ }++ const firstLit = matchPythonStringLiteralStart(source, cur);+ if (!firstLit || !firstLit.isDocstringEligible) {+ return { matched: false, nextOffset: startOffset };+ }++ let sawString = false;+ while (cur < source.length) {+ const litMatch = matchPythonStringLiteralStart(source, cur);+ if (!litMatch) break;+ if (!litMatch.isDocstringEligible) {+ return { matched: false, nextOffset: startOffset };+ }+ const scanned = scanPythonStringLiteralEnd(source, cur);+ sawString = true;+ cur = scanned.endOffset;+ cur =+ parenDepth > 0+ ? skipTriviaAndComments(source, cur)+ : skipHorizontalAndBackslashNewlines(source, cur);+ }++ if (!sawString) {+ return { matched: false, nextOffset: startOffset };+ }++ while (parenDepth > 0) {+ cur = skipTriviaAndComments(source, cur);+ if (cur >= source.length) {+ throw new InvalidPythonSourceError(+ "Unclosed parenthesis in Python module docstring",+ );+ }+ if (source[cur] !== ")") {+ return { matched: false, nextOffset: startOffset };+ }+ parenDepth--;+ cur++;+ }++ cur = skipHorizontalAndBackslashNewlines(source, cur);+ if (source[cur] === "#") {+ while (cur < source.length && source[cur] !== "\n" && source[cur] !== "\r") {+ cur++;+ }+ }++ if (cur >= source.length) {+ return { matched: true, nextOffset: cur };+ }+ if (source[cur] === "\r" && source[cur + 1] === "\n") {+ return { matched: true, nextOffset: cur + 2 };+ }+ if (source[cur] === "\n" || source[cur] === "\r") {+ return { matched: true, nextOffset: cur + 1 };+ }+ if (source[cur] === ";") {+ const afterSemi = cur + 1;+ const afterLine = consumeOptionalEndOfLineAfterStatement(source, afterSemi);+ return { matched: true, nextOffset: afterLine };+ }++ // Compound expression starting with a string literal (e.g. `"a" + "b"`), not a docstring+ return { matched: false, nextOffset: startOffset };+}++function matchKeywordAt(source: string, offset: number, keyword: string): boolean {+ if (!source.startsWith(keyword, offset)) return false;+ if (offset > 0 && /[A-Za-z0-9_]/.test(source[offset - 1]!)) return false;+ const after = source[offset + keyword.length];+ if (after !== undefined && /[A-Za-z0-9_]/.test(after)) return false;+ return true;+}++/**+ * Lexically analyzes a Python module to find the exact safe insertion offset+ * strictly AFTER:+ * 1. UTF-8 BOM, shebang (`#!`), and PEP 263 encoding comments+ * 2. The optional module docstring (preserving `module.__doc__`)+ * 3. All `from __future__ import ...` statements (single-line, parenthesized multi-line, or backslash-continued)+ */+export function findPythonPrologueInsertionOffset(+ source: string,+): PythonPrologueAnalysis {+ let pos = 0;+ if (source.startsWith("\uFEFF")) {+ pos = 1;+ }++ // Advance past leading blank lines and `#` comments (including shebang & PEP 263 encoding declaration)+ pos = skipTriviaAndComments(source, pos);+ let insertOffset = pos;+ let hasDocstring = false;+ const futureImports: string[] = [];++ // 1. Check for optional module docstring as the very first statement+ if (pos < source.length) {+ const docAttempt = tryConsumeModuleDocstring(source, pos);+ if (docAttempt.matched) {+ hasDocstring = true;+ pos = docAttempt.nextOffset;+ insertOffset = pos;+ }+ }++ // 2. Consume zero or more `from __future__ import ...` statements+ while (pos < source.length) {+ const nextStmtStart = skipTriviaAndComments(source, pos);+ if (nextStmtStart >= source.length) {+ break;+ }++ if (!matchKeywordAt(source, nextStmtStart, "from")) {+ pos = nextStmtStart;+ break;+ }++ let cur = skipHorizontalAndBackslashNewlines(source, nextStmtStart + 4);+ if (!matchKeywordAt(source, cur, "__future__")) {+ // Normal `from <pkg> import ...` statement; prologue is complete+ pos = nextStmtStart;+ break;+ }++ cur = skipHorizontalAndBackslashNewlines(source, cur + "__future__".length);+ if (!matchKeywordAt(source, cur, "import")) {+ throw new InvalidPythonSourceError(+ "Malformed 'from __future__' statement: expected 'import'",+ );+ }+ cur += "import".length;++ let parenDepth = 0;+ let sawIdentifier = false;+ let expectingCommaOrEnd = false;+ let expectingAliasIdentifier = false;+ let closedParen = false;++ while (cur < source.length) {+ cur = skipHorizontalWhitespace(source, cur);+ if (cur >= source.length) break;++ const ch = source[cur]!;+ if (ch === "\\") {+ if (source[cur + 1] === "\n") {+ cur += 2;+ continue;+ }+ if (source[cur + 1] === "\r" && source[cur + 2] === "\n") {+ cur += 3;+ continue;+ }+ throw new InvalidPythonSourceError(+ "Invalid backslash continuation in from __future__ import",+ );+ }++ if (ch === "#") {+ while (cur < source.length && source[cur] !== "\n" && source[cur] !== "\r") {+ cur++;+ }+ continue;+ }++ if (ch === "\r" || ch === "\n") {+ if (source[cur] === "\r" && source[cur + 1] === "\n") {+ cur += 2;+ } else {+ cur += 1;+ }+ if (parenDepth === 0) {+ break;+ }+ continue;+ }++ if (ch === ";") {+ if (parenDepth > 0 || expectingAliasIdentifier || !sawIdentifier) {+ throw new InvalidPythonSourceError(+ "Invalid semicolon in from __future__ import",+ );+ }+ cur += 1;+ cur = consumeOptionalEndOfLineAfterStatement(source, cur);+ break;+ }++ if (closedParen) {+ throw new InvalidPythonSourceError(+ `Unexpected token '${ch}' after closing ')' in from __future__ import`,+ );+ }++ if (ch === "(") {+ if (parenDepth > 0 || sawIdentifier) {+ throw new InvalidPythonSourceError(+ "Unexpected '(' in from __future__ import",+ );+ }+ parenDepth = 1;+ cur += 1;+ continue;+ }++ if (ch === ")") {+ if (parenDepth <= 0 || expectingAliasIdentifier || !sawIdentifier) {+ throw new InvalidPythonSourceError(+ "Unexpected ')' in from __future__ import",+ );+ }+ parenDepth = 0;+ closedParen = true;+ cur += 1;+ continue;+ }++ if (ch === ",") {+ if (!expectingCommaOrEnd || expectingAliasIdentifier) {+ throw new InvalidPythonSourceError(+ "Unexpected ',' in from __future__ import",+ );+ }+ expectingCommaOrEnd = false;+ cur += 1;+ continue;+ }++ if (ch === "*") {+ throw new InvalidPythonSourceError(+ "Wildcard import '*' is not valid in from __future__ import",+ );+ }++ if (/[A-Za-z_]/.test(ch)) {+ const idMatch = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(cur));+ const ident = idMatch![0]!;+ cur += ident.length;++ if (expectingAliasIdentifier) {+ expectingAliasIdentifier = false;+ expectingCommaOrEnd = true;+ } else if (expectingCommaOrEnd && ident === "as") {+ expectingAliasIdentifier = true;+ expectingCommaOrEnd = false;+ } else if (!expectingCommaOrEnd) {+ sawIdentifier = true;+ expectingCommaOrEnd = true;+ } else {+ throw new InvalidPythonSourceError(+ `Unexpected identifier '${ident}' in from __future__ import`,+ );+ }+ continue;+ }++ throw new InvalidPythonSourceError(+ `Unexpected character '${ch}' in from __future__ import`,+ );+ }++ if (parenDepth !== 0) {+ throw new InvalidPythonSourceError(+ "Unclosed '(' in from __future__ import statement",+ );+ }+ if (!sawIdentifier || expectingAliasIdentifier) {+ throw new InvalidPythonSourceError(+ "Incomplete from __future__ import statement",+ );+ }++ futureImports.push(source.slice(nextStmtStart, cur).trim());+ pos = cur;+ insertOffset = cur;+ }++ // 3. Scan remainder of file to reject unclosed string literals and misplaced `from __future__ import`+ let scanPos = pos;+ let atStatementStart = true;+ let bracketDepth = 0;++ while (scanPos < source.length) {+ const ch = source[scanPos]!;+ if (ch === " " || ch === "\t" || ch === "\f") {+ scanPos++;+ continue;+ }+ if (ch === "#") {+ while (+ scanPos < source.length &&+ source[scanPos] !== "\n" &&+ source[scanPos] !== "\r"+ ) {+ scanPos++;+ }+ continue;+ }+ if (ch === "\n" || ch === "\r") {+ if (ch === "\r" && source[scanPos + 1] === "\n") {+ scanPos += 2;+ } else {+ scanPos += 1;+ }+ if (bracketDepth === 0) {+ atStatementStart = true;+ }+ continue;+ }+ if (ch === ";") {+ scanPos++;+ if (bracketDepth === 0) {+ atStatementStart = true;+ }+ continue;+ }+ if (ch === "\\") {+ if (source[scanPos + 1] === "\n") {+ scanPos += 2;+ continue;+ }+ if (source[scanPos + 1] === "\r" && source[scanPos + 2] === "\n") {+ scanPos += 3;+ continue;+ }+ scanPos++;+ continue;+ }++ const strStart = matchPythonStringLiteralStart(source, scanPos);+ if (strStart) {+ const scanned = scanPythonStringLiteralEnd(source, scanPos);+ scanPos = scanned.endOffset;+ atStatementStart = false;+ continue;+ }++ if (ch === "(" || ch === "[" || ch === "{") {+ bracketDepth++;+ scanPos++;+ atStatementStart = false;+ continue;+ }+ if (ch === ")" || ch === "]" || ch === "}") {+ bracketDepth = Math.max(0, bracketDepth - 1);+ scanPos++;+ atStatementStart = false;+ continue;+ }++ if (atStatementStart && bracketDepth === 0 && matchKeywordAt(source, scanPos, "from")) {+ const afterFrom = skipHorizontalAndBackslashNewlines(source, scanPos + 4);+ if (matchKeywordAt(source, afterFrom, "__future__")) {+ throw new InvalidPythonSourceError(+ "from __future__ imports must occur at the beginning of the file",+ );+ }+ }++ atStatementStart = false;+ if (/[A-Za-z0-9_]/.test(ch)) {+ while (scanPos < source.length && /[A-Za-z0-9_]/.test(source[scanPos]!)) {+ scanPos++;+ }+ } else {+ scanPos++;+ }+ }++ return {+ insertOffset,+ hasDocstring,+ futureImports,+ };+}+/*** Protects a Python `.py` source file by injecting an interconnected Python* Algorithmic Tarpit (`generatePythonTarpit`), opaque predicates, and- * honey-docstrings while preserving shebangs and `from __future__` imports.+ * honey-docstrings while preserving shebangs, PEP 263 encoding headers,+ * module docstrings (`__doc__`), and complete `from __future__` imports.*/export function protectPythonSource(source: string,@@ -33,35 +631,25 @@ export function protectPythonSource(const chaffPayloads = generateChaffPayloads(prng, intensity);const tarpit = generatePythonTarpit(prng, intensity, chaffPayloads);- const lines = source.split("\n");- let insertIdx = 0;-- // Preserve leading shebang, encoding declarations, module docstring, and `from __future__` imports- while (insertIdx < lines.length) {- const trimmed = lines[insertIdx]!.trim();- if (- trimmed.startsWith("#") ||- trimmed === "" ||- trimmed.startsWith("from __future__")- ) {- insertIdx++;- continue;- }- break;- }+ const eol = source.includes("\r\n") ? "\r\n" : "\n";+ const prologue = findPythonPrologueInsertionOffset(source);++ const headRaw = source.slice(0, prologue.insertOffset);+ const tailRaw = source.slice(prologue.insertOffset);++ const head = headRaw.replace(/(?:\r?\n)+$/, "");+ const tail = tailRaw.replace(/^(?:\r?\n)+/, "").replace(/(?:\r?\n)+$/, "");+ const tarpitNormalized =+ eol === "\r\n"+ ? tarpit.code.replace(/\r?\n/g, "\r\n").replace(/(?:\r\n)+$/, "")+ : tarpit.code.replace(/\n+$/, "");- const head = lines.slice(0, insertIdx).join("\n");- const tail = lines.slice(insertIdx).join("\n");- const combined = [- head,- tarpit.code,- tail,- ]+ const combined = [head, tarpitNormalized, tail].filter((part) => part.length > 0)- .join("\n\n");+ .join(eol + eol);return {- code: combined + "\n",+ code: combined + eol,decoyFunctionsInjected: tarpit.decoyFunctionNames.length,crossReferenceEdges: tarpit.crossReferenceEdges,chaffPayloadsEmbedded: chaffPayloads.length,@@ -93,7 +681,9 @@ export function inspectPythonPyc(bytes: Buffer): PythonPycInspectionSummary {magicNumber,pep552Flags,extractedStrings: matches.slice(0, 64),- blaProtected: textView.includes("BLA-SHIELD") || textView.includes("Architecture Notice: Core business logic"),+ blaProtected:+ textView.includes("BLA-SHIELD") ||+ textView.includes("Architecture Notice: Core business logic"),};}diff --git a/src/shields/javascript/ast-shield.ts b/src/shields/javascript/ast-shield.tsindex 522f13e..6cf4f99 100644--- a/src/shields/javascript/ast-shield.ts+++ b/src/shields/javascript/ast-shield.ts@@ -1,4 +1,4 @@-import { parse } from "@babel/parser";+import { parse, type ParserPlugin } from "@babel/parser";import _traverse from "@babel/traverse";import _generate from "@babel/generator";import * as t from "@babel/types";@@ -22,8 +22,30 @@ const generate: GenerateFn =? (_generate as unknown as GenerateFn): _generate.default;+export class InvalidJavaScriptCarrierError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "InvalidJavaScriptCarrierError";+ }+}++export type JsCarrierType = "module" | "script" | "commonjs" | "auto";+export type JsLoaderType = "js" | "jsx" | "ts" | "tsx";++export interface JsTransformOptions {+ readonly intensity?: ProtectionIntensity;+ readonly seed?: string | number;+ readonly filename?: string;+ readonly enableRuntimeShield?: boolean;+ readonly sourceType?: JsCarrierType;+ readonly loader?: JsLoaderType;+}+export interface JsShieldTransformResult {readonly code: string;+ readonly carrierType: "module" | "script" | "commonjs";+ readonly loader: JsLoaderType;+ readonly exportedSymbols: readonly string[];readonly decoyFunctionsInjected: number;readonly fakeCrossReferencesCreated: number;readonly primitiveCandidateBranchesCreated: number;@@ -46,7 +68,81 @@ const DECOY_ROUTES: readonly string[] = ["/internal/nitro/enclave-cid16-dispatch",];-const IPC_METHODS = new Set(["handle", "handleOnce", "on", "once", "invoke", "send", "sendSync", "sendToHost"]);+const IPC_METHODS = new Set([+ "handle",+ "handleOnce",+ "on",+ "once",+ "invoke",+ "send",+ "sendSync",+ "sendToHost",+]);++export function inferJsLoaderFromPath(filename?: string): JsLoaderType {+ if (!filename) return "js";+ const clean = filename.split(/[?#]/, 1)[0]!.toLowerCase();+ if (clean.endsWith(".tsx")) return "tsx";+ if (clean.endsWith(".jsx")) return "jsx";+ if (+ clean.endsWith(".ts") ||+ clean.endsWith(".mts") ||+ clean.endsWith(".cts")+ ) {+ return "ts";+ }+ return "js";+}++export function inferJsCarrierFromPath(filename?: string): JsCarrierType {+ if (!filename) return "auto";+ const clean = filename.split(/[?#]/, 1)[0]!.toLowerCase();+ if (clean.endsWith(".mjs") || clean.endsWith(".mts")) return "module";+ if (clean.endsWith(".cjs") || clean.endsWith(".cts")) return "commonjs";+ return "auto";+}++export function collectEsmExportedSymbols(program: t.Program): string[] {+ const exported: string[] = [];+ for (const stmt of program.body) {+ if (t.isExportDefaultDeclaration(stmt)) {+ exported.push("default");+ } else if (t.isExportAllDeclaration(stmt)) {+ exported.push("*");+ } else if (t.isExportNamedDeclaration(stmt)) {+ for (const spec of stmt.specifiers) {+ if (t.isExportSpecifier(spec)) {+ exported.push(+ t.isIdentifier(spec.exported)+ ? spec.exported.name+ : spec.exported.value,+ );+ } else if (t.isExportNamespaceSpecifier(spec)) {+ exported.push(spec.exported.name);+ }+ }+ const decl = stmt.declaration;+ if (decl) {+ if (+ (t.isFunctionDeclaration(decl) || t.isClassDeclaration(decl)) &&+ decl.id+ ) {+ exported.push(decl.id.name);+ } else if (t.isVariableDeclaration(decl)) {+ const ids = t.getOuterBindingIdentifiers(decl);+ exported.push(...Object.keys(ids));+ } else if (+ "id" in decl &&+ decl.id &&+ t.isIdentifier(decl.id)+ ) {+ exported.push(decl.id.name);+ }+ }+ }+ }+ return exported;+}/*** Splits a string literal into >= 9 conditional chunks `(cond ? realChunk : decoyChunk)`@@ -89,10 +185,19 @@ function buildCombinatorialStringAst(const terms: t.Expression[] = chunks.map((realChunk, idx) => {const k = prng.nextInt(3, 125);- const decoyChunk = realChunk.length > 0 ? prng.hex(realChunk.length) : prng.hex(2);+ const decoyChunk =+ realChunk.length > 0 ? prng.hex(realChunk.length) : prng.hex(2);// Opaque true: ((Math.imul(seed | k, (seed | k) + 1) & 1) === 0)- const seededOr = t.binaryExpression("|", t.identifier(seedIdentifierName), t.numericLiteral(k));- const seededPlusOne = t.binaryExpression("+", t.cloneNode(seededOr), t.numericLiteral(1));+ const seededOr = t.binaryExpression(+ "|",+ t.identifier(seedIdentifierName),+ t.numericLiteral(k),+ );+ const seededPlusOne = t.binaryExpression(+ "+",+ t.cloneNode(seededOr),+ t.numericLiteral(1),+ );const imulCall = t.callExpression(t.memberExpression(t.identifier("Math"), t.identifier("imul")),[seededOr, seededPlusOne],@@ -108,7 +213,11 @@ function buildCombinatorialStringAst(t.stringLiteral(decoyChunk),);} else {- const invertedCond = t.binaryExpression("===", bitAnd, t.numericLiteral(1));+ const invertedCond = t.binaryExpression(+ "===",+ bitAnd,+ t.numericLiteral(1),+ );return t.conditionalExpression(invertedCond,t.stringLiteral(decoyChunk),@@ -124,10 +233,21 @@ function buildCombinatorialStringAst(return expr;}-function buildOpaqueFalseAst(prng: SeededPrng, seedIdentifierName: string): t.Expression {+function buildOpaqueFalseAst(+ prng: SeededPrng,+ seedIdentifierName: string,+): t.Expression {const k = prng.nextInt(5, 113);- const seededOr = t.binaryExpression("|", t.identifier(seedIdentifierName), t.numericLiteral(k));- const seededPlusOne = t.binaryExpression("+", t.cloneNode(seededOr), t.numericLiteral(1));+ const seededOr = t.binaryExpression(+ "|",+ t.identifier(seedIdentifierName),+ t.numericLiteral(k),+ );+ const seededPlusOne = t.binaryExpression(+ "+",+ t.cloneNode(seededOr),+ t.numericLiteral(1),+ );const imulCall = t.callExpression(t.memberExpression(t.identifier("Math"), t.identifier("imul")),[seededOr, seededPlusOne],@@ -136,41 +256,99 @@ function buildOpaqueFalseAst(prng: SeededPrng, seedIdentifierName: string): t.Exreturn t.binaryExpression("===", bitAnd, t.numericLiteral(1));}+function buildParserPlugins(+ loader: JsLoaderType,+ hasExplicitLoaderOrFilename: boolean,+): ParserPlugin[] {+ const plugins: ParserPlugin[] = [+ "decorators-legacy",+ "importAttributes",+ "dynamicImport",+ "classProperties",+ "topLevelAwait",+ ];+ if (!hasExplicitLoaderOrFilename) {+ plugins.unshift("typescript", "jsx");+ return plugins;+ }+ if (loader === "ts") {+ plugins.unshift("typescript");+ } else if (loader === "tsx") {+ plugins.unshift("typescript", "jsx");+ } else if (loader === "jsx") {+ plugins.unshift("jsx");+ }+ return plugins;+}+export function transformJavaScriptWithBlaShield(source: string,- options: {- readonly intensity?: ProtectionIntensity;- readonly seed?: string | number;- readonly filename?: string;- } = {},+ options: JsTransformOptions = {},): JsShieldTransformResult {const intensity = options.intensity ?? "balanced";const prng = new SeededPrng(options.seed ?? "bla-js-shield-v1");const chaffPayloads = generateChaffPayloads(prng, intensity);const tarpit = generateJsTarpitAndBudgetBreaker(prng, intensity, chaffPayloads);- const runtimeShield = generateRuntimeDeceptionSnippet(prng, intensity, chaffPayloads);+ const runtimeShield = generateRuntimeDeceptionSnippet(+ prng,+ intensity,+ chaffPayloads,+ );const exhaustionSuite = generateCounterReaExhaustionSuite(prng, intensity);const deceptionSuite = generateCounterReaDeceptionSuite(prng, intensity);- const ast = parse(source, {- sourceType: "unambiguous",- plugins: [- "typescript",- "jsx",- "decorators-legacy",- "importAttributes",- "dynamicImport",- "classProperties",- "topLevelAwait",- ],- errorRecovery: true,- });+ const hasExplicitLoaderOrFilename =+ options.loader !== undefined || options.filename !== undefined;+ const loader: JsLoaderType =+ options.loader ?? inferJsLoaderFromPath(options.filename);+ const requestedCarrier: JsCarrierType =+ options.sourceType ?? inferJsCarrierFromPath(options.filename);++ const parserSourceType =+ requestedCarrier === "script" || requestedCarrier === "commonjs"+ ? "script"+ : requestedCarrier === "module"+ ? "module"+ : "unambiguous";++ let ast: ReturnType<typeof parse>;+ try {+ ast = parse(source, {+ sourceType: parserSourceType,+ plugins: buildParserPlugins(loader, hasExplicitLoaderOrFilename),+ errorRecovery: false,+ });+ } catch (err) {+ throw new InvalidJavaScriptCarrierError(+ `Failed to parse JavaScript/TypeScript input (carrier=${requestedCarrier}, loader=${loader}): ${err instanceof Error ? err.message : String(err)}`,+ );+ }++ const hasEsmNodes = ast.program.body.some(+ (stmt) =>+ t.isImportDeclaration(stmt) ||+ t.isExportNamedDeclaration(stmt) ||+ t.isExportDefaultDeclaration(stmt) ||+ t.isExportAllDeclaration(stmt),+ );++ if (+ (requestedCarrier === "script" || requestedCarrier === "commonjs") &&+ hasEsmNodes+ ) {+ throw new InvalidJavaScriptCarrierError(+ `ESM import/export syntax is not allowed in '${requestedCarrier}' carrier`,+ );+ }++ const exportedSymbolsBefore = collectEsmExportedSymbols(ast.program);const seedVarName = `_bla_rt_${prng.hex(4)}`;const observedIpcChannels = new Set<string>();let primitiveCandidateBranchesCreated = 512; // From tarpit budgetFnlet fakeCrossReferencesCreated = tarpit.crossReferenceEdges;let ipcAmbiguitySitesInjected = 0;+ let usesCjsAst = false;// Track functions to weave tarpit calls intoconst functionBodies: t.BlockStatement[] = [];@@ -181,8 +359,24 @@ export function transformJavaScriptWithBlaShield(functionBodies.push(path.node.body);}},+ MemberExpression(path) {+ const { object, property } = path.node;+ if (+ t.isIdentifier(object) &&+ object.name === "module" &&+ t.isIdentifier(property) &&+ property.name === "exports"+ ) {+ usesCjsAst = true;+ } else if (t.isIdentifier(object) && object.name === "exports") {+ usesCjsAst = true;+ }+ },CallExpression(path) {const callee = path.node.callee;+ if (t.isIdentifier(callee) && callee.name === "require") {+ usesCjsAst = true;+ }// 1. Check Electron IPC & contextBridge callsif (t.isMemberExpression(callee) && t.isIdentifier(callee.property)) {const methodName = callee.property.name;@@ -258,6 +452,13 @@ export function transformJavaScriptWithBlaShield(},});+ const effectiveCarrier: "module" | "script" | "commonjs" =+ requestedCarrier === "module" || hasEsmNodes+ ? "module"+ : requestedCarrier === "commonjs" || usesCjsAst+ ? "commonjs"+ : "script";+// 3. Weave unreachable tarpit calls (Fake XRefs) into real function bodiesfor (const body of functionBodies) {if (tarpit.decoyFunctionNames.length >= 2) {@@ -269,8 +470,14 @@ export function transformJavaScriptWithBlaShield(t.expressionStatement(t.binaryExpression("^",- t.callExpression(t.identifier(d1), [t.numericLiteral(prng.nextInt(1, 255)), t.numericLiteral(2)]),- t.callExpression(t.identifier(d2), [t.numericLiteral(prng.nextInt(1, 255)), t.numericLiteral(2)]),+ t.callExpression(t.identifier(d1), [+ t.numericLiteral(prng.nextInt(1, 255)),+ t.numericLiteral(2),+ ]),+ t.callExpression(t.identifier(d2), [+ t.numericLiteral(prng.nextInt(1, 255)),+ t.numericLiteral(2),+ ]),),),]),@@ -292,65 +499,102 @@ export function transformJavaScriptWithBlaShield(intensity === "stealth" ? 4 : intensity === "balanced" ? 8 : 10;const selectedDecoyRoutes = DECOY_ROUTES.slice(0, decoyRouteCount);+ const decoyIpcFnName = `_bla_registerDecoyIpcAndRoutes_${prng.hex(4)}`;+ mirageLines.push(+ `function ${decoyIpcFnName}(_ipcMain, _ipcRenderer, _router) {`,+ );mirageLines.push(- `function _bla_registerDecoyIpcAndRoutes_${prng.hex(4)}(_ipcMain, _ipcRenderer, _router) {`,+ ` if (((Math.imul(${seedVarName} | 11, (${seedVarName} | 11) + 1) & 1) === 1)) {`,);- mirageLines.push(` if (((Math.imul(${seedVarName} | 11, (${seedVarName} | 11) + 1) & 1) === 1)) {`);for (const ch of channelsToMirror) {// Register duplicate ambiguous literal channels on both ipcMain and ipcRenderer// to defeat REA's unique exact literal IPC channel pairing rule!- mirageLines.push(` _ipcMain?.handle(${JSON.stringify(ch)}, () => ({ delegatedToEnclave: true, channel: ${JSON.stringify(ch)} }));`);- mirageLines.push(` _ipcMain?.on(${JSON.stringify(ch)}, () => ({ fallbackStub: true }));`);- mirageLines.push(` _ipcRenderer?.invoke(${JSON.stringify(ch)}, { probe: "enclave_shadow_1" });`);- mirageLines.push(` _ipcRenderer?.send(${JSON.stringify(ch)}, { probe: "enclave_shadow_2" });`);+ mirageLines.push(+ ` _ipcMain?.handle(${JSON.stringify(ch)}, () => ({ delegatedToEnclave: true, channel: ${JSON.stringify(ch)} }));`,+ );+ mirageLines.push(+ ` _ipcMain?.on(${JSON.stringify(ch)}, () => ({ fallbackStub: true }));`,+ );+ mirageLines.push(+ ` _ipcRenderer?.invoke(${JSON.stringify(ch)}, { probe: "enclave_shadow_1" });`,+ );+ mirageLines.push(+ ` _ipcRenderer?.send(${JSON.stringify(ch)}, { probe: "enclave_shadow_2" });`,+ );ipcAmbiguitySitesInjected += 4;}for (const route of selectedDecoyRoutes) {mirageLines.push(` fetch(${JSON.stringify(route)});`);- mirageLines.push(` _router?.post?.(${JSON.stringify(route)}, () => null);`);+ mirageLines.push(+ ` _router?.post?.(${JSON.stringify(route)}, () => null);`,+ );}mirageLines.push(` }`);mirageLines.push(`}`);+ mirageLines.push(`void ${decoyIpcFnName};`);- // Parse the tarpit + mirage code and append/prepend to AST program while keeping module compatibility- const usesCommonJs =- source.includes("module.exports") ||- source.includes("exports.") ||- (!source.includes("export ") && source.includes("require("));-- const tarpitCodeNormalized = usesCommonJs- ? tarpit.code.replace(/export function /g, "function ")- : tarpit.code;-- const combinedInjectedAst = parse(- [- mirageLines.join("\n"),- runtimeShield.code,- tarpitCodeNormalized,- exhaustionSuite.combinedJsCode,- deceptionSuite.combinedJsCode,- ].join("\n\n"),- {- sourceType: "unambiguous",- plugins: ["typescript"],- },- );+ const injectedBlocks = [+ mirageLines.join("\n"),+ ...(options.enableRuntimeShield !== false ? [runtimeShield.code] : []),+ tarpit.code.replace(/\bexport\s+function\s+/g, "function "),+ exhaustionSuite.combinedJsCode,+ deceptionSuite.combinedJsCode,+ ];++ const combinedInjectedAst = parse(injectedBlocks.join("\n\n"), {+ sourceType: "script",+ plugins: ["typescript"],+ });++ const sanitizedInjectedStatements: t.Statement[] = [];+ for (const stmt of combinedInjectedAst.program.body) {+ if (t.isExportNamedDeclaration(stmt) && stmt.declaration) {+ sanitizedInjectedStatements.push(stmt.declaration);+ } else if (+ !t.isImportDeclaration(stmt) &&+ !t.isExportNamedDeclaration(stmt) &&+ !t.isExportDefaultDeclaration(stmt) &&+ !t.isExportAllDeclaration(stmt)+ ) {+ sanitizedInjectedStatements.push(stmt);+ }+ }// Prepend `seedVarName` declaration at top of program (after any directives / imports)let insertIndex = 0;- while (- insertIndex < ast.program.body.length &&- t.isImportDeclaration(ast.program.body[insertIndex]!)- ) {- insertIndex++;+ while (insertIndex < ast.program.body.length) {+ const stmt = ast.program.body[insertIndex]!;+ if (t.isImportDeclaration(stmt)) {+ insertIndex++;+ continue;+ }+ if (+ t.isExpressionStatement(stmt) &&+ t.isStringLiteral(stmt.expression) &&+ stmt.expression.value.startsWith("use ")+ ) {+ insertIndex++;+ continue;+ }+ break;}- const [seedDecl, ...restInjected] = combinedInjectedAst.program.body;+ const [seedDecl, ...restInjected] = sanitizedInjectedStatements;if (seedDecl) {ast.program.body.splice(insertIndex, 0, seedDecl);}ast.program.body.push(...restInjected);+ const exportedSymbolsAfter = collectEsmExportedSymbols(ast.program);+ if (+ exportedSymbolsBefore.length !== exportedSymbolsAfter.length ||+ exportedSymbolsBefore.some((sym, idx) => sym !== exportedSymbolsAfter[idx])+ ) {+ throw new InvalidJavaScriptCarrierError(+ "Internal error: BLA JavaScript transform mutated module export surface",+ );+ }+// Strip any existing `//# sourceMappingURL=` comments from ASTif (ast.comments) {ast.comments = ast.comments.filter(@@ -370,6 +614,9 @@ export function transformJavaScriptWithBlaShield(return {code: generated.code,+ carrierType: effectiveCarrier,+ loader,+ exportedSymbols: exportedSymbolsAfter,decoyFunctionsInjected:tarpit.decoyFunctionNames.length +exhaustionSuite.totalLabyrinthNodes +diff --git a/src/shields/tarpit/tarpit-generator.ts b/src/shields/tarpit/tarpit-generator.tsindex dbb581a..68ce97c 100644--- a/src/shields/tarpit/tarpit-generator.ts+++ b/src/shields/tarpit/tarpit-generator.ts@@ -151,13 +151,14 @@ export function generateJsTarpitAndBudgetBreaker(// Master dispatcher anchored to global/module scope so tree-shakers & static analyzers keep all decoy nodes aliveconst anchorName = `_bla_shield_anchor_${prng.hex(4)}`;- lines.push(`export function ${anchorName}(_seed = 0) {`);+ lines.push(`function ${anchorName}(_seed = 0) {`);lines.push(` if (${generateJsOpaqueFalseExpression(prng, stateVar)}) {`);const calls = decoyNames.slice(0, Math.min(8, decoyNames.length)).map((n, idx) => `${n}(_seed + ${idx}, 3)`).join(" ^ ");lines.push(` return (${calls}) ^ ${aliasFn}(false, null) ^ ${budgetFn}(false, "slot");`);lines.push(` }`);lines.push(` return ${chaffTableVar}.length ^ _seed;`);lines.push(`}`);+ lines.push(`void ${anchorName};`);return {code: lines.join("\n"),diff --git a/tests/format-contracts-p1.test.ts b/tests/format-contracts-p1.test.tsnew file mode 100644index 0000000..26836eb--- /dev/null+++ b/tests/format-contracts-p1.test.ts@@ -0,0 +1,750 @@+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import vm from "node:vm";+import { parse } from "@babel/parser";+import { describe, expect, it } from "vitest";+import {+ blaEsbuildPlugin,+ blaRollupPlugin,+ inferCarrierFromRollupFormat,+ inferEsbuildLoader,+} from "../src/bundler/index.js";+import {+ packAsarBuffer,+ unpackAsarBuffer,+ UnsupportedAsarError,+ validateAsarBuffer,+ validateAsarProtectionInput,+} from "../src/shields/formats/asar.js";+import {+ ELECTRON_FUSE_SENTINEL_BYTES,+ ELECTRON_FUSE_STATE,+ hardenElectronFusesWithContext,+ inspectElectronFusesBuffer,+ UnsupportedElectronFuseContextError,+} from "../src/shields/formats/electron-fuses.js";+import {+ InvalidNativeBinaryError,+ protectNativeBinary,+ validateElf64Layout,+} from "../src/shields/formats/native.js";+import {+ findPythonPrologueInsertionOffset,+ InvalidPythonSourceError,+ protectPythonSource,+} from "../src/shields/formats/python.js";+import {+ InvalidJavaScriptCarrierError,+ transformJavaScriptWithBlaShield,+} from "../src/shields/javascript/ast-shield.js";++function buildRawAsarBuffer(+ headerObj: unknown,+ payload: Buffer = Buffer.alloc(0),+): Buffer {+ const jsonBytes = Buffer.from(JSON.stringify(headerObj), "utf8");+ const jsonStringSize = jsonBytes.length;+ const alignedJsonSize = Math.ceil(jsonStringSize / 4) * 4;+ const innerPickleSize = alignedJsonSize + 4;+ const headerSize = innerPickleSize + 4;++ const headerBuffer = Buffer.alloc(8 + headerSize, 0);+ headerBuffer.writeUInt32LE(4, 0);+ headerBuffer.writeUInt32LE(headerSize, 4);+ headerBuffer.writeUInt32LE(innerPickleSize, 8);+ headerBuffer.writeUInt32LE(jsonStringSize, 12);+ jsonBytes.copy(headerBuffer, 16);++ return Buffer.concat([headerBuffer, payload]);+}++function buildValidElf64Fixture(options?: {+ readonly bssExtraBytes?: bigint;+ readonly embedElectronFuse?: boolean;+}): Buffer {+ // Layout (total 1024 bytes):+ // [0..64) ELF64 Header (64 bytes)+ // [64..176) Program Header Table: 2 entries * 56 bytes = 112 bytes+ // [176..512) Section 1 (.rodata, SHT_PROGBITS, 168 bytes) + Section 2 (.eh_frame, SHT_PROGBITS, 168 bytes)+ // [512..640) Section 3 (.data, SHT_PROGBITS, 128 bytes) + Section 4 (.bss, SHT_NOBITS, at offset 640, size 4096)+ // [640..704) Section 5 (.shstrtab, SHT_STRTAB, 64 bytes)+ // [704..1088) Section Header Table: 6 entries * 64 bytes = 384 bytes -> total 1088 bytes+ const totalSize = 1088;+ const buf = Buffer.alloc(totalSize, 0);++ // ELF64 magic + ELFCLASS64 (2) + ELFDATA2LSB (1) + EV_CURRENT (1)+ buf[0] = 0x7f;+ buf[1] = 0x45;+ buf[2] = 0x4c;+ buf[3] = 0x46;+ buf[4] = 2; // 64-bit+ buf[5] = 1; // little-endian+ buf[6] = 1; // version+ buf.writeUInt16LE(2, 16); // e_type = ET_EXEC+ buf.writeUInt16LE(0x3e, 18); // e_machine = EM_X86_64+ buf.writeUInt32LE(1, 20); // e_version+ buf.writeBigUInt64LE(0x400000n, 24); // e_entry+ buf.writeBigUInt64LE(64n, 32); // e_phoff = 64+ buf.writeBigUInt64LE(704n, 40); // e_shoff = 704+ buf.writeUInt16LE(64, 52); // e_ehsize = 64+ buf.writeUInt16LE(56, 54); // e_phentsize = 56+ buf.writeUInt16LE(2, 56); // e_phnum = 2+ buf.writeUInt16LE(64, 58); // e_shentsize = 64+ buf.writeUInt16LE(6, 60); // e_shnum = 6+ buf.writeUInt16LE(5, 62); // e_shstrndx = 5++ // Program Header 0: PT_LOAD (read-only segment covering [0..512))+ const ph0 = 64;+ buf.writeUInt32LE(1, ph0 + 0); // PT_LOAD+ buf.writeUInt32LE(4, ph0 + 4); // PF_R+ buf.writeBigUInt64LE(0n, ph0 + 8); // p_offset = 0+ buf.writeBigUInt64LE(0x400000n, ph0 + 16); // p_vaddr+ buf.writeBigUInt64LE(0x400000n, ph0 + 24); // p_paddr+ buf.writeBigUInt64LE(512n, ph0 + 32); // p_filesz = 512+ buf.writeBigUInt64LE(512n, ph0 + 40); // p_memsz = 512+ buf.writeBigUInt64LE(0x1000n, ph0 + 48); // p_align++ // Program Header 1: PT_LOAD (read-write data + BSS segment ending at EOF!)+ // Note: p_offset = 512, p_filesz = 576 (512 + 576 === 1088 === totalSize!),+ // while p_memsz = 576 + bssExtraBytes (e.g. 4672 bytes > p_filesz)+ const bssExtra = options?.bssExtraBytes ?? 4096n;+ const ph1 = 64 + 56;+ buf.writeUInt32LE(1, ph1 + 0); // PT_LOAD+ buf.writeUInt32LE(6, ph1 + 4); // PF_R | PF_W+ buf.writeBigUInt64LE(512n, ph1 + 8); // p_offset = 512+ buf.writeBigUInt64LE(0x600000n, ph1 + 16); // p_vaddr+ buf.writeBigUInt64LE(0x600000n, ph1 + 24); // p_paddr+ buf.writeBigUInt64LE(576n, ph1 + 32); // p_filesz = 576 (reaches EOF 1088)+ buf.writeBigUInt64LE(576n + bssExtra, ph1 + 40); // p_memsz > p_filesz (BSS!)+ buf.writeBigUInt64LE(0x1000n, ph1 + 48); // p_align++ // Populate .rodata [176..344) and .eh_frame [344..512)+ buf.write("RODATA_PAYLOAD_V1\0", 176, "ascii");+ if (options?.embedElectronFuse) {+ const fusePos = 200;+ ELECTRON_FUSE_SENTINEL_BYTES.copy(buf, fusePos);+ const wireStart = fusePos + ELECTRON_FUSE_SENTINEL_BYTES.length;+ buf[wireStart] = 1; // version 1+ buf[wireStart + 1] = 6; // 6 fuses+ buf[wireStart + 2 + 0] = ELECTRON_FUSE_STATE.ENABLED; // RunAsNode = '1' (vulnerable)+ buf[wireStart + 2 + 1] = ELECTRON_FUSE_STATE.DISABLED; // CookieEncryption = '0'+ buf[wireStart + 2 + 2] = ELECTRON_FUSE_STATE.ENABLED; // NodeOptions = '1'+ buf[wireStart + 2 + 3] = ELECTRON_FUSE_STATE.ENABLED; // NodeCliInspect = '1'+ buf[wireStart + 2 + 4] = ELECTRON_FUSE_STATE.DISABLED; // AsarIntegrity = '0'+ buf[wireStart + 2 + 5] = ELECTRON_FUSE_STATE.DISABLED; // OnlyLoadAppFromAsar = '0'+ }+ buf.write("EH_FRAME_CIE_FDE\0", 344, "ascii");+ buf.write("RW_DATA_BLOCK\0", 512, "ascii");+ buf.write("\0.rodata\0.eh_frame\0.data\0.bss\0.shstrtab\0", 640, "ascii");++ const writeShdr = (+ idx: number,+ nameOff: number,+ type: number,+ flags: bigint,+ addr: bigint,+ offset: bigint,+ size: bigint,+ ) => {+ const base = 704 + idx * 64;+ buf.writeUInt32LE(nameOff, base + 0);+ buf.writeUInt32LE(type, base + 4);+ buf.writeBigUInt64LE(flags, base + 8);+ buf.writeBigUInt64LE(addr, base + 16);+ buf.writeBigUInt64LE(offset, base + 24);+ buf.writeBigUInt64LE(size, base + 32);+ };++ // Section 0: SHT_NULL+ writeShdr(0, 0, 0, 0n, 0n, 0n, 0n);+ // Section 1: .rodata (SHT_PROGBITS = 1, SHF_ALLOC = 2) [176..344)+ writeShdr(1, 1, 1, 2n, 0x4000b0n, 176n, 168n);+ // Section 2: .eh_frame (SHT_PROGBITS = 1, SHF_ALLOC = 2) [344..512)+ writeShdr(2, 9, 1, 2n, 0x400158n, 344n, 168n);+ // Section 3: .data (SHT_PROGBITS = 1, SHF_WRITE | SHF_ALLOC = 3) [512..640)+ writeShdr(3, 19, 1, 3n, 0x600000n, 512n, 128n);+ // Section 4: .bss (SHT_NOBITS = 8, SHF_WRITE | SHF_ALLOC = 3) at 640, size 4096+ writeShdr(4, 25, 8, 3n, 0x600080n, 640n, bssExtra);+ // Section 5: .shstrtab (SHT_STRTAB = 3) [640..704)+ writeShdr(5, 30, 3, 0n, 0n, 640n, 64n);++ return buf;+}++describe("P1 Format Contracts (#13 ASAR, #14 Python, #15 JS/Bundler, #16 ELF64, #17 Electron Fuses)", () => {+ describe("Issue #13: ASAR node preservation and fail-closed validation", () => {+ it("preserves normal files, empty files, nested directories, executable flags, links, and unpacked nodes across pack/unpack", () => {+ const entries = [+ {+ relativePath: "package.json",+ content: Buffer.from('{"name":"app","main":"dist/index.js"}', "utf8"),+ },+ {+ relativePath: "dist/empty.txt",+ content: Buffer.alloc(0),+ },+ {+ relativePath: "dist/bin/launcher",+ content: Buffer.from("#!/bin/sh\necho ok\n", "utf8"),+ executable: true,+ },+ {+ relativePath: "dist/current-launcher",+ content: Buffer.alloc(0),+ link: "bin/launcher",+ },+ {+ relativePath: "native/addon.node",+ content: Buffer.alloc(0),+ unpacked: true,+ size: 4096,+ executable: true,+ },+ ] as const;++ const packed = packAsarBuffer(entries);+ const unpacked = unpackAsarBuffer(packed, {+ allowUnpacked: true,+ allowLinks: true,+ });++ expect(unpacked).toHaveLength(5);+ expect(unpacked[0]?.relativePath).toBe("package.json");+ expect(unpacked[0]?.content.toString("utf8")).toBe(+ '{"name":"app","main":"dist/index.js"}',+ );+ expect(unpacked[1]?.relativePath).toBe("dist/empty.txt");+ expect(unpacked[1]?.content.length).toBe(0);+ expect(unpacked[2]?.relativePath).toBe("dist/bin/launcher");+ expect(unpacked[2]?.executable).toBe(true);+ expect(unpacked[3]?.relativePath).toBe("dist/current-launcher");+ expect(unpacked[3]?.link).toBe("bin/launcher");+ expect(unpacked[4]?.relativePath).toBe("native/addon.node");+ expect(unpacked[4]?.unpacked).toBe(true);+ expect(unpacked[4]?.size).toBe(4096);+ expect(unpacked[4]?.executable).toBe(true);++ // Fail closed in standalone protection validation when unpacked nodes exist without companion handling+ expect(() => validateAsarProtectionInput(packed)).toThrow(+ UnsupportedAsarError,+ );+ expect(+ validateAsarProtectionInput(packed, { allowUnpacked: true }),+ ).toHaveLength(5);+ });++ it("rejects invalid offsets (undefined, NaN, negative, non-numeric, out-of-bounds) and escaping symlinks with UnsupportedAsarError", () => {+ const payload = Buffer.from("hello world", "utf8");++ // 1. Missing offset on packed node+ const missingOffset = buildRawAsarBuffer(+ { files: { "a.txt": { size: 5 } } },+ payload,+ );+ expect(() => validateAsarBuffer(missingOffset)).toThrow(+ UnsupportedAsarError,+ );++ // 2. NaN / non-numeric offset+ const nanOffset = buildRawAsarBuffer(+ { files: { "a.txt": { size: 5, offset: "NaN" } } },+ payload,+ );+ expect(() => validateAsarBuffer(nanOffset)).toThrow(UnsupportedAsarError);++ // 3. Partially numeric offset ("12abc")+ const partialNumeric = buildRawAsarBuffer(+ { files: { "a.txt": { size: 5, offset: "0abc" } } },+ payload,+ );+ expect(() => validateAsarBuffer(partialNumeric)).toThrow(+ UnsupportedAsarError,+ );++ // 4. Negative offset ("-1")+ const negativeOffset = buildRawAsarBuffer(+ { files: { "a.txt": { size: 5, offset: "-1" } } },+ payload,+ );+ expect(() => validateAsarBuffer(negativeOffset)).toThrow(+ UnsupportedAsarError,+ );++ // 5. Out-of-bounds size+ const outOfBounds = buildRawAsarBuffer(+ { files: { "a.txt": { size: 999, offset: "0" } } },+ payload,+ );+ expect(() => validateAsarBuffer(outOfBounds)).toThrow(+ UnsupportedAsarError,+ );++ // 6. Escaping link target ("../../etc/passwd")+ const escapingLink = buildRawAsarBuffer({+ files: {+ sub: {+ files: {+ evil: { link: "../../etc/passwd" },+ },+ },+ },+ });+ expect(() => validateAsarBuffer(escapingLink)).toThrow(+ UnsupportedAsarError,+ );++ // 7. Unknown node shape+ const unknownNode = buildRawAsarBuffer({+ files: {+ mystery: { customType: "device" },+ },+ });+ expect(() => validateAsarBuffer(unknownNode)).toThrow(+ UnsupportedAsarError,+ );+ });+ });++ describe("Issue #14: Python module docstring and future-import prologue placement", () => {+ function verifyPythonAstAndDocstring(+ code: string,+ expectedDocstring: string | null,+ expectedFutureNames: readonly string[],+ ): void {+ const tmpDir = mkdtempSync(join(tmpdir(), "bla-py-test-"));+ const pyFile = join(tmpDir, "module_under_test.py");+ try {+ writeFileSync(pyFile, code, "utf8");+ const script = [+ "import ast, json, sys",+ "with open(sys.argv[1], 'rb') as f: src = f.read()",+ "tree = ast.parse(src, filename=sys.argv[1])",+ "compile(tree, sys.argv[1], 'exec')",+ "doc = ast.get_docstring(tree, clean=False)",+ "futures = []",+ "for node in tree.body:",+ " if isinstance(node, ast.ImportFrom) and node.module == '__future__':",+ " futures.extend(alias.name for alias in node.names)",+ "print(json.dumps({'doc': doc, 'futures': futures}))",+ ].join("\n");+ const stdout = execFileSync("python3", ["-c", script, pyFile], {+ encoding: "utf8",+ });+ const parsed = JSON.parse(stdout.trim()) as {+ doc: string | null;+ futures: string[];+ };+ expect(parsed.doc).toBe(expectedDocstring);+ expect(parsed.futures).toEqual(expectedFutureNames);+ } finally {+ rmSync(tmpDir, { recursive: true, force: true });+ }+ }++ it("preserves module __doc__ and single-line from __future__ import (Input A)", () => {+ const inputA = [+ '"""Public module documentation."""',+ "from __future__ import annotations",+ "value = 1",+ "",+ ].join("\n");++ const analysis = findPythonPrologueInsertionOffset(inputA);+ expect(analysis.hasDocstring).toBe(true);+ expect(analysis.futureImports).toEqual([+ "from __future__ import annotations",+ ]);++ const result = protectPythonSource(inputA, { seed: "issue-14-a" });+ expect(+ result.code.startsWith(+ '"""Public module documentation."""\nfrom __future__ import annotations\n',+ ),+ ).toBe(true);+ verifyPythonAstAndDocstring(+ result.code,+ "Public module documentation.",+ ["annotations"],+ );+ });++ it("preserves multi-line parenthesized from __future__ import without splitting (Input B)", () => {+ const inputB = [+ "from __future__ import (",+ " annotations,",+ " division,",+ ")",+ "value = 1",+ "",+ ].join("\n");++ const analysis = findPythonPrologueInsertionOffset(inputB);+ expect(analysis.hasDocstring).toBe(false);+ expect(analysis.futureImports).toHaveLength(1);++ const result = protectPythonSource(inputB, { seed: "issue-14-b" });+ expect(+ result.code.startsWith(+ "from __future__ import (\n annotations,\n division,\n)\n",+ ),+ ).toBe(true);+ verifyPythonAstAndDocstring(result.code, null, [+ "annotations",+ "division",+ ]);+ });++ it("handles backslash-continued future imports, multi-line/raw docstrings, comments, CRLF, empty files, and fails closed on invalid syntax", () => {+ const crlfSource = [+ "#!/usr/bin/env python3",+ "# -*- coding: utf-8 -*-",+ 'r"""Multi-line raw docstring',+ 'with "inner quotes" and # comment.',+ '"""',+ "# Interleaved comment",+ "from __future__ import \\",+ " annotations, \\",+ " generator_stop",+ "",+ "def compute(x: int) -> int:",+ " return x + 1",+ "",+ ].join("\r\n");++ const crlfResult = protectPythonSource(crlfSource, {+ seed: "issue-14-crlf",+ });+ expect(crlfResult.code.includes("\r\n")).toBe(true);+ // Verify every '\n' is part of '\r\n'+ expect(crlfResult.code.replace(/\r\n/g, "").includes("\n")).toBe(false);+ verifyPythonAstAndDocstring(+ crlfResult.code,+ 'Multi-line raw docstring\nwith "inner quotes" and # comment.\n',+ ["annotations", "generator_stop"],+ );++ // Empty file and docstring-only file+ const emptyResult = protectPythonSource("", { seed: "issue-14-empty" });+ verifyPythonAstAndDocstring(emptyResult.code, null, []);++ const docOnlyResult = protectPythonSource("'Single-line docstring.'", {+ seed: "issue-14-doconly",+ });+ verifyPythonAstAndDocstring(+ docOnlyResult.code,+ "Single-line docstring.",+ [],+ );++ // Fail closed on unclosed docstring or unclosed future import or misplaced future import+ expect(() =>+ protectPythonSource('"""Unclosed docstring\nx = 1'),+ ).toThrow(InvalidPythonSourceError);+ expect(() =>+ protectPythonSource("from __future__ import (\n annotations\n"),+ ).toThrow(InvalidPythonSourceError);+ expect(() =>+ protectPythonSource("x = 1\nfrom __future__ import annotations\n"),+ ).toThrow(InvalidPythonSourceError);+ });+ });++ describe("Issue #15: JavaScript carrier preservation and bundler loader contracts", () => {+ it("preserves classic script / IIFE carrier without injecting export declarations", () => {+ const iifeSource = "(() => {\n const answer = 42;\n globalThis.__iifeResult = answer;\n})();";+ const result = transformJavaScriptWithBlaShield(iifeSource, {+ sourceType: "script",+ filename: "bundle.iife.js",+ seed: "issue-15-iife",+ });++ expect(result.carrierType).toBe("script");+ expect(result.exportedSymbols).toEqual([]);+ expect(/\bexport\b/.test(result.code)).toBe(false);++ // Must parse cleanly in strict "script" mode+ expect(() =>+ parse(result.code, { sourceType: "script", errorRecovery: false }),+ ).not.toThrow();++ // Must execute cleanly as a classic VM Script+ const sandbox: Record<string, unknown> = {};+ vm.createContext(sandbox);+ new vm.Script(result.code).runInContext(sandbox);+ expect(sandbox.__iifeResult).toBe(42);+ });++ it("preserves exact ESM export surface and is not fooled by 'module.exports' in comments or strings", () => {+ const esmSource = [+ "// Comment mentioning module.exports = { decoy: true }",+ 'const banner = "module.exports = require(\\"x\\")";',+ "export const publicValue = 100;",+ "export function publicHelper() { return banner; }",+ ].join("\n");++ const result = transformJavaScriptWithBlaShield(esmSource, {+ filename: "index.mjs",+ seed: "issue-15-esm",+ });++ expect(result.carrierType).toBe("module");+ expect(result.exportedSymbols).toEqual(["publicValue", "publicHelper"]);++ const cjsSource = [+ '"use strict";',+ "const message = 'export function notAnExport() {}';",+ "module.exports = { message };",+ ].join("\n");++ const cjsResult = transformJavaScriptWithBlaShield(cjsSource, {+ filename: "index.cjs",+ seed: "issue-15-cjs",+ });+ expect(cjsResult.carrierType).toBe("commonjs");+ expect(cjsResult.exportedSymbols).toEqual([]);+ expect(cjsResult.code.trimStart().startsWith('"use strict";')).toBe(true);+ expect(() =>+ parse(cjsResult.code, { sourceType: "script", errorRecovery: false }),+ ).not.toThrow();++ // Fail closed when ESM syntax is passed to a script/commonjs carrier+ expect(() =>+ transformJavaScriptWithBlaShield("export const x = 1;", {+ sourceType: "script",+ }),+ ).toThrow(InvalidJavaScriptCarrierError);+ });++ it("preserves Rollup output format carrier and esbuild js/jsx/ts/tsx loaders", async () => {+ expect(inferCarrierFromRollupFormat("iife")).toBe("script");+ expect(inferCarrierFromRollupFormat("umd")).toBe("script");+ expect(inferCarrierFromRollupFormat("cjs")).toBe("commonjs");+ expect(inferCarrierFromRollupFormat("es")).toBe("module");++ expect(inferEsbuildLoader("src/Component.tsx")).toBe("tsx");+ expect(inferEsbuildLoader("src/View.jsx")).toBe("jsx");+ expect(inferEsbuildLoader("src/util.mts")).toBe("ts");+ expect(inferEsbuildLoader("src/util.cts")).toBe("ts");+ expect(inferEsbuildLoader("src/index.mjs")).toBe("js");++ const rollupPlugin = blaRollupPlugin({ honeySourceMap: false });+ const iifeChunk = rollupPlugin.renderChunk(+ "(() => { const x = 1; })();",+ { fileName: "app.js" },+ { format: "iife" },+ );+ expect(iifeChunk).not.toBeNull();+ expect(/\bexport\b/.test(iifeChunk!.code)).toBe(false);++ // Test blaEsbuildPlugin onLoad with .tsx and .jsx files+ const tmpDir = mkdtempSync(join(tmpdir(), "bla-esbuild-test-"));+ try {+ const tsxPath = join(tmpDir, "Widget.tsx");+ const jsxPath = join(tmpDir, "Button.jsx");+ writeFileSync(+ tsxPath,+ 'export const Widget = (props: { label: string }) => <div className="w">{props.label}</div>;\n',+ "utf8",+ );+ writeFileSync(+ jsxPath,+ 'export const Button = () => <button type="button">Click</button>;\n',+ "utf8",+ );++ let registeredCallback:+ | ((args: {+ path: string;+ }) => Promise<{ contents: string; loader: string } | null>)+ | undefined;+ const esbuildPlugin = blaEsbuildPlugin();+ esbuildPlugin.setup({+ onLoad(_opts, cb) {+ registeredCallback = cb;+ },+ });++ expect(registeredCallback).toBeDefined();+ const tsxLoaded = await registeredCallback!({ path: tsxPath });+ expect(tsxLoaded?.loader).toBe("tsx");+ expect(tsxLoaded?.contents).toContain("<div");++ const jsxLoaded = await registeredCallback!({ path: jsxPath });+ expect(jsxLoaded?.loader).toBe("jsx");+ expect(jsxLoaded?.contents).toContain("<button");+ } finally {+ rmSync(tmpDir, { recursive: true, force: true });+ }+ });+ });++ describe("Issue #16: ELF64 PT_LOAD / BSS and section boundary preservation", () => {+ it("preserves PT_LOAD p_offset/p_filesz/p_memsz (BSS) and adjacent section boundaries without overlap", () => {+ const elfFixture = buildValidElf64Fixture({ bssExtraBytes: 8192n });+ const layoutBefore = validateElf64Layout(elfFixture);++ expect(layoutBefore.programHeaders[1]?.filesz).toBe(576);+ expect(layoutBefore.programHeaders[1]?.memsz).toBe(576n + 8192n);++ const protectedElf = protectNativeBinary(elfFixture, {+ seed: "issue-16-elf",+ });+ const layoutAfter = validateElf64Layout(protectedElf.buffer);++ // Every PT_LOAD segment and section header must be 100% preserved+ expect(layoutAfter.programHeaders).toEqual(layoutBefore.programHeaders);+ expect(layoutAfter.sectionHeaders).toEqual(layoutBefore.sectionHeaders);++ // Original payload bytes [0..elfFixture.length) must be byte-for-byte identical+ expect(+ protectedElf.buffer.subarray(0, elfFixture.length).equals(elfFixture),+ ).toBe(true);+ });++ it("fails closed with InvalidNativeBinaryError on truncated headers, p_memsz < p_filesz, and overlapping sections", () => {+ // 1. Truncated ELF header (< 64 bytes)+ const truncated = Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]);+ expect(() => validateElf64Layout(truncated)).toThrow(+ InvalidNativeBinaryError,+ );+ expect(() => protectNativeBinary(truncated)).toThrow(+ InvalidNativeBinaryError,+ );++ // 2. PT_LOAD with p_memsz < p_filesz+ const badBss = buildValidElf64Fixture();+ const ph1 = 64 + 56;+ badBss.writeBigUInt64LE(576n, ph1 + 32); // p_filesz = 576+ badBss.writeBigUInt64LE(128n, ph1 + 40); // p_memsz = 128 < p_filesz!+ expect(() => validateElf64Layout(badBss)).toThrow(+ InvalidNativeBinaryError,+ );++ // 3. Overlapping file-backed sections (.rodata extended into .eh_frame)+ const overlappingSec = buildValidElf64Fixture();+ const shdr1 = 704 + 1 * 64;+ overlappingSec.writeBigUInt64LE(300n, shdr1 + 32); // [176..476) overlaps .eh_frame [344..512)!+ expect(() => validateElf64Layout(overlappingSec)).toThrow(+ InvalidNativeBinaryError,+ );+ });+ });++ describe("Issue #17: Context-verified Electron fuse hardening", () => {+ it("distinguishes absent, unsupported, truncated, and ambiguous sentinels without mutating non-Electron files", () => {+ // 1. Absent sentinel+ const noSentinel = Buffer.alloc(128, 0x41);+ expect(inspectElectronFusesBuffer(noSentinel).status).toBe("absent");++ // 2. Truncated wire after sentinel+ const truncatedWire = Buffer.concat([+ Buffer.alloc(16, 0),+ ELECTRON_FUSE_SENTINEL_BYTES,+ Buffer.from([0x01, 0x08, 0x30, 0x31]), // declares length 8, only 2 bytes present+ ]);+ const truncInsp = inspectElectronFusesBuffer(truncatedWire);+ expect(truncInsp.status).toBe("unsupported");+ expect(truncInsp.diagnostic).toContain("truncated");++ // 3. Invalid fuse wire byte (e.g. arbitrary ASCII text following sentinel)+ const invalidWireByte = Buffer.concat([+ Buffer.alloc(16, 0),+ ELECTRON_FUSE_SENTINEL_BYTES,+ Buffer.from([0x01, 0x06, 0x30, 0x31, 0x78, 0x30, 0x31, 0x31]), // 0x78 ('x') is invalid+ ]);+ expect(inspectElectronFusesBuffer(invalidWireByte).status).toBe(+ "unsupported",+ );++ // 4. Multiple real V1 fuse blocks -> ambiguous+ const validWire = Buffer.from([+ 0x01,+ 0x06,+ ELECTRON_FUSE_STATE.ENABLED,+ ELECTRON_FUSE_STATE.DISABLED,+ ELECTRON_FUSE_STATE.ENABLED,+ ELECTRON_FUSE_STATE.ENABLED,+ ELECTRON_FUSE_STATE.DISABLED,+ ELECTRON_FUSE_STATE.DISABLED,+ ]);+ const ambiguousBuf = Buffer.concat([+ Buffer.alloc(16, 0),+ ELECTRON_FUSE_SENTINEL_BYTES,+ validWire,+ Buffer.alloc(16, 0),+ ELECTRON_FUSE_SENTINEL_BYTES,+ validWire,+ ]);+ expect(inspectElectronFusesBuffer(ambiguousBuf).status).toBe("ambiguous");+ });++ it("fails closed when hardening context lacks container, ASAR integrity, or signing policy, and reports separate statuses when verified", () => {+ const electronElf = buildValidElf64Fixture({ embedElectronFuse: true });+ const asarHash = createHash("sha256")+ .update("verified-asar-header")+ .digest("hex");++ // Without context, protectNativeBinary must NOT mutate the embedded real fuse wire+ const protectedDefault = protectNativeBinary(electronElf);+ const beforeFuseCheck = inspectElectronFusesBuffer(+ protectedDefault.buffer,+ );+ expect(beforeFuseCheck.status).toBe("verified");+ expect(beforeFuseCheck.hardened).toBe(false);+ expect(beforeFuseCheck.runAsNodeEnabled).toBe(true);++ // Missing ASAR integrity -> fail closed+ expect(() =>+ hardenElectronFusesWithContext(electronElf, {+ electronVersion: "32.1.0",+ hasEmbeddedAsarIntegrity: false,+ codeSigningPolicy: "will-resign",+ }),+ ).toThrow(UnsupportedElectronFuseContextError);++ // Non-native container -> fail closed+ const rawNonContainer = Buffer.concat([+ Buffer.alloc(32, 0),+ ELECTRON_FUSE_SENTINEL_BYTES,+ Buffer.from([0x01, 0x06, 0x31, 0x30, 0x31, 0x31, 0x30, 0x30]),+ ]);+ expect(() =>+ hardenElectronFusesWithContext(rawNonContainer, {+ electronVersion: "32.1.0",+ hasEmbeddedAsarIntegrity: true,+ asarHeaderHash: asarHash,+ codeSigningPolicy: "will-resign",+ }),+ ).toThrow(UnsupportedElectronFuseContextError);++ // Valid context -> succeeds and reports fusePolicy, asarIntegrityStatus, signatureStatus separately+ const hardenedReport = hardenElectronFusesWithContext(electronElf, {+ electronVersion: "32.1.0",+ asarPath: "resources/app.asar",+ hasEmbeddedAsarIntegrity: true,+ asarHeaderHash: asarHash,+ codeSigningPolicy: "will-resign",+ injectDecoySentinelOverflow: true,+ });++ expect(hardenedReport.fusePolicy.status).toBe("hardened");+ expect(hardenedReport.asarIntegrityStatus).toBe("verified");+ expect(hardenedReport.signatureStatus).toBe("unverified-requires-resign");+ expect(hardenedReport.mutatedFuses).toContain("RunAsNode");+ expect(hardenedReport.mutatedFuses).toContain(+ "EnableEmbeddedAsarIntegrityValidation",+ );++ const postInspect = inspectElectronFusesBuffer(hardenedReport.buffer);+ expect(postInspect.status).toBe("verified");+ expect(postInspect.hardened).toBe(true);+ expect(postInspect.runAsNodeEnabled).toBe(false);+ expect(postInspect.asarIntegrityEnforced).toBe(true);+ expect(postInspect.onlyLoadFromAsarEnforced).toBe(true);+ expect(postInspect.exceedsReaSentinelLimit).toBe(true);+ });+ });+});