Skip to content

armgit / bla

Public Imported from GitHub
0

🛡️ BLA (Blind LLM Agents) — Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, and WebAssembly against AI reverse-engineering agents like REA. Poison -> Exhaust -> Hallucinate.

fix(archive): reject unsafe ZIP rewrites and unsupported APK protection

Codexf5ee3ec4cf8d
diff --git a/README.md b/README.md
index bd15125..d731e43 100644
--- a/README.md
+++ b/README.md
@@ -168,8 +168,9 @@ BLA requires Node.js `^22.13.0 || >=24.0.0` and npm. All format shields run loca
| WASM artifacts | Strips debug sections; adds decoy `"name"` section (`tee_hardware_enclave_stub`) + custom sections | `bla protect core.wasm` · Built-in LEB128 binary parser; preserves 100% `WebAssembly.validate` |
| Python & `.pyc` | Injects call-graph state machines into `.py` & `TYPE_ASCII` marshal entries into `.pyc` pools | `bla protect module.pyc` · Built-in CPython 3.7–3.14 `.pyc` header & marshal framing shield |
| SQLite databases | Adds 3 decoy tables with `GENERATED ALWAYS AS (bla_enclave_unseal(...)) VIRTUAL` column guards | `bla protect data.sqlite` · Real tables stay queryable; read-only inspection hits `SqliteColumnEvaluationFailure` |
-| Model artifacts | Adds `35 > 32` nested JSON/ARRAY headers into `.safetensors` and `.gguf` metadata headers | `bla protect weights.safetensors` · Trips `ModelFormatFailure (json-nesting / metadata-nesting > 32)` |
-| Android DEX & APKs | Appends `Lcom/enclave/sgx/...` decoy descriptors into `classes.dex` and recomputes SHA-1/Adler32 | `bla protect classes.dex` or `app.apk` · Valid Dalvik/ART verification; expands decompiler class trees |
+| Model artifacts | Validated Safetensors metadata transformation preserving tensor descriptors and data bytes | `bla protect weights.safetensors` · Fails closed on malformed headers or unsupported dtypes |
+| Android DEX & APKs | Appends `Lcom/enclave/sgx/...` decoy descriptors into `classes.dex`; **APK protection is unsupported** pending a signing-aware pipeline | `bla protect classes.dex` · `bla protect app.apk` refuses without modifying input or existing output |
+| ZIP archives | Only a restricted classic, metadata-free ZIP subset can be rewritten | Unsupported features fail closed; see [archive admission policy](docs/archive-integrity.md) |
| Unity IL2CPP metadata | Appends enclave bridge metadata and method-topology entries to `global-metadata.dat` (`0xFAB11BAF`) | `bla protect global-metadata.dat` · Dilutes `inspect_il2cpp_metadata` type/method recovery |
| C / C++ / Rust / Go src | Generates compile-time `bla_shield.h`, `bla_shield.rs`, or `bla_shield.go` headers | `bla emit-headers --lang c\|rust\|go` · Compiles into binary symbol and control-flow graphs |
diff --git a/docs/archive-integrity.md b/docs/archive-integrity.md
new file mode 100644
index 0000000..cd2679a
--- /dev/null
+++ b/docs/archive-integrity.md
@@ -0,0 +1,47 @@
+# Archive integrity admission
+
+BLA is not a general-purpose ZIP/APK repacker. Archive protection now rejects input
+it cannot fully represent, rather than silently omitting members or treating failed
+DEFLATE decoding as original file data.
+
+## Supported ZIP subset
+
+- Single-disk classic ZIP, terminal EOCD with no archive comment or trailing bytes.
+- Contiguous local records followed immediately by the complete central directory;
+ every entry's name, offset, flags, sizes, method and CRC must agree.
+- Stored or raw-DEFLATE entries; decoded length and CRC must match. DEFLATE must
+ consume exactly its declared compressed stream.
+- Unique, printable ASCII filenames; zero flags, timestamps, extra fields,
+ entry comments and file attributes. Required ZIP version must be at most 2.0.
+- At most 64 MiB decoded per entry and 256 MiB total declared decoded content.
+ Inflater output is separately capped by the declared length, so false size
+ claims cannot cause unbounded decompression.
+
+This intentionally excludes many perfectly valid ZIPs, including ordinary archives
+with timestamps or Unix permission attributes. Metadata is rejected rather than
+silently discarded. Encryption, data descriptors, ZIP64, multi-volume archives,
+unsupported encodings/compression, prepended executables, gaps and signing blocks
+are unsupported. `readZipEntries` also enforces this subset; therefore auditing
+unsupported archives fails explicitly instead of returning a partial inventory.
+
+Protection additionally refuses AndroidManifest.xml, signature entries under
+META-INF (`.SF`, `.RSA`, `.DSA`, `.EC`) and existing entries in the reserved
+`assets/enclave/` or `enclave/` output namespaces. These checks are conservative
+admission rules, not a universal signature detector or signature verification.
+
+## APKs and failure behavior
+
+All explicitly identified APK protection requests, including unsigned fixtures,
+throw `UnsupportedApkProtectionError`. BLA does not implement signing, re-signing,
+alignment preservation or APK signature validation. Renaming an APK does not make
+it a supported package. ZIP rejection throws `UnsupportedArchiveError`.
+
+The file engine preflights before audit, payload generation, directory creation or
+output writes. On admission failure, input and existing output remain unchanged,
+including in-place requests. CLI and MCP propagate these failures through their
+existing error handling. No installability or real Android runtime claim is made.
+
+The existing admitted ZIP transformation remains unchanged. Embedded JS/WASM is
+copied, not recursively protected. Tests establish small fixture content
+preservation and rejection behavior, not anti-analysis effectiveness, complete ZIP
+compatibility, or production application correctness.
diff --git a/src/engine/protector.ts b/src/engine/protector.ts
index 96919ce..2723643 100644
--- a/src/engine/protector.ts
+++ b/src/engine/protector.ts
@@ -23,7 +23,7 @@ import { packAsarBuffer, unpackAsarBuffer, type VirtualAsarFile } from "../shiel
import { protectWasmBinary } from "../shields/formats/wasm.js";
import { protectPythonPycBuffer, protectPythonSource } from "../shields/formats/python.js";
import { protectNativeBinary } from "../shields/formats/native.js";
-import { protectZipOrApkBuffer } from "../shields/formats/archive.js";
+import { protectZipOrApkBuffer, validateZipProtectionInput, UnsupportedApkProtectionError } from "../shields/formats/archive.js";
import { protectSqliteBuffer } from "../shields/formats/sqlite.js";
import { protectGgufBuffer, protectSafetensorsBuffer } from "../shields/formats/model.js";
import { protectAndroidDexBuffer, protectIl2cppMetadataBuffer } from "../shields/formats/mobile-game.js";
@@ -53,6 +53,14 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {
throw new Error(`Unsupported or missing target path: ${absInput}`);
}
+ // Reject before auditing, generating payloads, or creating any output paths.
+ if (format === "android-apk") throw new UnsupportedApkProtectionError();
+ const absOutput = resolve(
+ options.outputPath ?? deriveDefaultOutputPath(absInput, options.inPlace),
+ );
+ assertSafeOutputPath(absInput, absOutput, format === "directory", options.inPlace);
+ if (format === "archive-zip") validateZipProtectionInput(readFileSync(absInput));
+
const intensity = options.intensity ?? "balanced";
const seed = String(options.seed ?? "bla-shield-seed-v1");
const prng = new SeededPrng(seed);
@@ -64,15 +72,6 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {
: undefined;
const beforeAudit = auditTarget(absInput);
- const absOutput = resolve(
- options.outputPath ?? deriveDefaultOutputPath(absInput, options.inPlace),
- );
- assertSafeOutputPath(
- absInput,
- absOutput,
- format === "directory",
- options.inPlace,
- );
if (format !== "directory") {
mkdirSync(dirname(absOutput), { recursive: true });
@@ -315,12 +314,12 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {
chaffPayloadsEmbedded = res.chaffPayloadsEmbedded;
binarySectionsPatched = 1;
counteredVectors.add("android-dex-il2cpp-inspection");
- } else if (format === "archive-zip" || format === "android-apk") {
+ } else if (format === "archive-zip") {
const rawZip = readFileSync(absInput);
const res = protectZipOrApkBuffer(rawZip, {
intensity,
seed,
- isApk: format === "android-apk",
+ isApk: false,
});
writeFileSync(absOutput, res.buffer);
decoyFunctionsInjected = 12;
diff --git a/src/index.ts b/src/index.ts
index ede6b1d..e9bf735 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -64,6 +64,8 @@ export {
protectIl2cppMetadataBuffer,
} from "./shields/formats/mobile-game.js";
export {
+ UnsupportedArchiveError,
+ UnsupportedApkProtectionError,
readZipEntries,
writeZipArchive,
protectZipOrApkBuffer,
diff --git a/src/shields/formats/archive.ts b/src/shields/formats/archive.ts
index 919301d..6aa332e 100644
--- a/src/shields/formats/archive.ts
+++ b/src/shields/formats/archive.ts
@@ -31,55 +31,97 @@ function crc32(buf: Buffer): number {
return (crc ^ 0xffffffff) >>> 0;
}
-/**
- * Reads entries from a standard ZIP or Android APK archive (`PK\x03\x04`).
- */
-export function readZipEntries(bytes: Buffer): readonly ZipEntryInfo[] {
- const entries: ZipEntryInfo[] = [];
- let offset = 0;
-
- while (offset + 30 <= bytes.length) {
- const sig = bytes.readUInt32LE(offset);
- if (sig !== 0x04034b50) break; // Stop at Central Directory (`0x02014b50`)
+export class UnsupportedArchiveError extends Error {
+ constructor(reason: string) {
+ super(`ZIP input cannot be rewritten safely: ${reason}`);
+ this.name = "UnsupportedArchiveError";
+ }
+}
- const compressionMethod = bytes.readUInt16LE(offset + 8);
- const compressedSize = bytes.readUInt32LE(offset + 18);
- const uncompressedSize = bytes.readUInt32LE(offset + 22);
- const nameLen = bytes.readUInt16LE(offset + 26);
- const extraLen = bytes.readUInt16LE(offset + 28);
+export class UnsupportedApkProtectionError extends Error {
+ constructor() {
+ super("APK protection is unsupported: a signing-aware, integrity-preserving pipeline is required. Input and existing output are unchanged.");
+ this.name = "UnsupportedApkProtectionError";
+ }
+}
- const nameStart = offset + 30;
- const dataStart = nameStart + nameLen + extraLen;
+/** Reads only the explicitly supported, metadata-free classic ZIP subset. */
+export function readZipEntries(bytes: Buffer): readonly ZipEntryInfo[] {
+ const reject = (reason: string): never => { throw new UnsupportedArchiveError(reason); };
+ const end = bytes.length - 22;
+ if (end < 0 || bytes.readUInt32LE(end) !== 0x06054b50) reject("missing terminal EOCD, comments, or trailing data");
+ if (bytes.readUInt16LE(end + 4) || bytes.readUInt16LE(end + 6) || bytes.readUInt16LE(end + 20)) reject("multi-disk archives or comments");
+ const count = bytes.readUInt16LE(end + 10);
+ const size = bytes.readUInt32LE(end + 12);
+ const start = bytes.readUInt32LE(end + 16);
+ if (count === 0xffff || size === 0xffffffff || start === 0xffffffff) reject("ZIP64");
+ if (bytes.readUInt16LE(end + 8) !== count || start + size !== end) reject("inconsistent central directory");
+ const entries: ZipEntryInfo[] = [];
+ const names = new Set<string>();
+ let local = 0;
+ let central = start;
+ let decodedTotal = 0;
+ for (let i = 0; i < count; i++) {
+ if (central + 46 > end || bytes.readUInt32LE(central) !== 0x02014b50) reject("truncated central directory");
+ const flags = bytes.readUInt16LE(central + 8);
+ const method = bytes.readUInt16LE(central + 10);
+ const crc = bytes.readUInt32LE(central + 16);
+ const compressedSize = bytes.readUInt32LE(central + 20);
+ const uncompressedSize = bytes.readUInt32LE(central + 24);
+ const nameLen = bytes.readUInt16LE(central + 28);
+ if (flags !== 0) reject("flags (including encryption, data descriptors, or alternate filename encodings)");
+ if (method !== 0 && method !== 8) reject("unsupported compression method");
+ if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff) reject("ZIP64 sizes");
+ if (bytes.readUInt16LE(central + 6) > 20 || bytes.readUInt32LE(central + 12) ||
+ bytes.readUInt16LE(central + 30) || bytes.readUInt16LE(central + 32) ||
+ bytes.readUInt16LE(central + 34) || bytes.readUInt16LE(central + 36) || bytes.readUInt32LE(central + 38)) {
+ reject("unsupported versions, timestamps, extra fields, comments, disks, or file attributes");
+ }
+ if (central + 46 + nameLen > end || bytes.readUInt32LE(central + 42) !== local) reject("entry offsets or names are inconsistent");
+ if (local + 30 > start || bytes.readUInt32LE(local) !== 0x04034b50) reject("missing local header or unrepresented data");
+ if (bytes.readUInt16LE(local + 4) !== bytes.readUInt16LE(central + 6) ||
+ bytes.readUInt16LE(local + 6) !== flags || bytes.readUInt16LE(local + 8) !== method ||
+ bytes.readUInt32LE(local + 10) || bytes.readUInt32LE(local + 14) !== crc ||
+ bytes.readUInt32LE(local + 18) !== compressedSize || bytes.readUInt32LE(local + 22) !== uncompressedSize ||
+ bytes.readUInt16LE(local + 26) !== nameLen || bytes.readUInt16LE(local + 28)) reject("local/central header mismatch or local metadata");
+ const dataStart = local + 30 + nameLen;
const dataEnd = dataStart + compressedSize;
- if (dataEnd > bytes.length) break;
-
- const name = bytes.subarray(nameStart, nameStart + nameLen).toString("utf8");
- const rawCompressed = bytes.subarray(dataStart, dataEnd);
- let data = rawCompressed;
- if (compressionMethod === 8 && compressedSize > 0) {
+ if (dataEnd > start) reject("truncated entry data");
+ const nameBytes = bytes.subarray(local + 30, dataStart);
+ if (!nameBytes.equals(bytes.subarray(central + 46, central + 46 + nameLen)) ||
+ nameBytes.length === 0 || nameBytes.some((v) => v < 32 || v > 126)) reject("unsupported or inconsistent filenames");
+ const name = nameBytes.toString("ascii");
+ if (names.has(name)) reject("duplicate filenames");
+ names.add(name);
+ decodedTotal += uncompressedSize;
+ if (uncompressedSize > 64 * 1024 * 1024 || decodedTotal > 256 * 1024 * 1024) reject("decoded size exceeds admission limits");
+ const compressed = bytes.subarray(dataStart, dataEnd);
+ let data: Buffer;
+ if (method === 0) {
+ if (compressedSize !== uncompressedSize) reject("stored entry size mismatch");
+ data = Buffer.from(compressed);
+ } else {
try {
- data = inflateRawSync(rawCompressed);
+ const result = inflateRawSync(compressed, { maxOutputLength: Math.max(1, uncompressedSize + 1), info: true });
+ // Node's info result reports consumed input, detecting trailing compressed garbage.
+ const decoded = result as unknown as { buffer: Buffer; engine: { bytesWritten: number } };
+ if (decoded.engine.bytesWritten !== compressedSize) reject("unconsumed compressed bytes");
+ data = decoded.buffer;
} catch {
- data = rawCompressed;
+ data = reject("invalid or incomplete deflate stream");
}
}
-
- entries.push({
- name,
- compressedSize,
- uncompressedSize,
- compressionMethod,
- data: Buffer.from(data),
- });
-
- offset = dataEnd;
+ if (data.length !== uncompressedSize || crc32(data) !== crc) reject("decoded size or CRC mismatch");
+ entries.push({ name, compressedSize, uncompressedSize, compressionMethod: method, data });
+ local = dataEnd;
+ central += 46 + nameLen;
}
-
+ if (central !== end || local !== start) reject("unrepresented entries, signing structures, or gaps");
return entries;
}
/**
- * Writes a valid ZIP / Android APK archive from a list of named file buffers.
+ * Writes a minimal ZIP archive from a list of named file buffers.
*/
export function writeZipArchive(
files: readonly { readonly name: string; readonly data: Buffer; readonly storeOnly?: boolean }[],
@@ -150,9 +192,21 @@ export function writeZipArchive(
return Buffer.concat([...localHeaders, ...centralHeaders, eocd]);
}
+/** Admission shared with the file engine, before any output paths are created. */
+export function validateZipProtectionInput(bytes: Buffer): readonly ZipEntryInfo[] {
+ const existingEntries = readZipEntries(bytes);
+ if (existingEntries.some((e) => e.name === "AndroidManifest.xml" || /^META-INF\/.*\.(SF|RSA|DSA|EC)$/i.test(e.name))) {
+ throw new UnsupportedArchiveError("APK or signed archive requires a signing-aware pipeline");
+ }
+ if (existingEntries.some((e) => e.name.startsWith("assets/enclave/") || e.name.startsWith("enclave/"))) {
+ throw new UnsupportedArchiveError("existing entries overlap the reserved output namespace");
+ }
+ return existingEntries;
+}
+
/**
- * Protects a ZIP or Android APK archive against `rea inspect-artifact` and `rea inspect-android-package`
- * by injecting decoy enclave manifests, decoy DEX/native stub descriptors, and protecting embedded JS/WASM assets.
+ * Rewrites the admitted ZIP subset. APK rewriting is explicitly unsupported.
+ * Embedded executable assets are copied, not recursively transformed.
*/
export function protectZipOrApkBuffer(
bytes: Buffer,
@@ -166,11 +220,11 @@ export function protectZipOrApkBuffer(
readonly decoyEntriesInjected: number;
readonly chaffPayloadsEmbedded: number;
} {
+ if (options.isApk) throw new UnsupportedApkProtectionError();
+ const existingEntries = validateZipProtectionInput(bytes);
const intensity = options.intensity ?? "balanced";
const prng = new SeededPrng(options.seed ?? "bla-archive-shield-v1");
const chaffPayloads = generateChaffPayloads(prng, intensity);
- const existingEntries = readZipEntries(bytes);
-
const outputFiles: { name: string; data: Buffer; storeOnly?: boolean }[] = existingEntries.map((e) => ({
name: e.name,
data: e.data,
diff --git a/tests/archive-integrity.test.ts b/tests/archive-integrity.test.ts
new file mode 100644
index 0000000..ae349a3
--- /dev/null
+++ b/tests/archive-integrity.test.ts
@@ -0,0 +1,90 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { protectZipOrApkBuffer, readZipEntries, UnsupportedApkProtectionError, UnsupportedArchiveError, writeZipArchive } from "../src/shields/formats/archive.js";
+import { protectTarget } from "../src/engine/protector.js";
+
+const fixture = () => writeZipArchive([{ name: "file.txt", data: Buffer.from("harmless content ".repeat(8)) }]);
+const centralOffset = (b: Buffer) => b.readUInt32LE(b.length - 6);
+function mutate(change: (b: Buffer, c: number) => void): Buffer {
+ const b = fixture(); change(b, centralOffset(b)); return b;
+}
+function gapBeforeDirectory(asCompressedData: boolean): Buffer {
+ const b = fixture(); const c = centralOffset(b);
+ const result = Buffer.concat([b.subarray(0, c), Buffer.from([0]), b.subarray(c)]);
+ result.writeUInt32LE(c + 1, result.length - 6);
+ if (asCompressedData) {
+ result.writeUInt32LE(b.readUInt32LE(18) + 1, 18);
+ result.writeUInt32LE(b.readUInt32LE(18) + 1, c + 1 + 20);
+ }
+ return result;
+}
+const bad: [string, () => Buffer][] = [
+ ["unrepresented signing-block-like gap", () => gapBeforeDirectory(false)],
+ ["trailing compressed garbage", () => gapBeforeDirectory(true)],
+ ["extra fields", () => mutate((b, c) => { b.writeUInt16LE(1, c + 30); })],
+ ["central/local mismatch", () => mutate((b, c) => { b[c + 46] = 120; })],
+ ["trailing archive bytes", () => Buffer.concat([fixture(), Buffer.from([0])])],
+ ["data descriptors", () => mutate((b, c) => { b.writeUInt16LE(8, 6); b.writeUInt16LE(8, c + 8); })],
+ ["encryption", () => mutate((b, c) => { b.writeUInt16LE(1, 6); b.writeUInt16LE(1, c + 8); })],
+ ["unknown compression", () => mutate((b, c) => { b.writeUInt16LE(99, 8); b.writeUInt16LE(99, c + 10); })],
+ ["truncated EOCD", () => fixture().subarray(0, -1)],
+ ["bad CRC", () => mutate((b, c) => { b.writeUInt32LE(0, 14); b.writeUInt32LE(0, c + 16); })],
+ ["invalid deflate", () => mutate((b) => { b[38] = 0xff; })],
+ ["decoded size mismatch", () => mutate((b, c) => { b.writeUInt32LE(1, 22); b.writeUInt32LE(1, c + 24); })],
+ ["oversized declared output", () => mutate((b, c) => { b.writeUInt32LE(64 * 1024 * 1024 + 1, 22); b.writeUInt32LE(64 * 1024 * 1024 + 1, c + 24); })],
+ ["missing entries", () => mutate((b) => { b.writeUInt16LE(2, b.length - 14); b.writeUInt16LE(2, b.length - 12); })],
+ ["incorrect local offset", () => mutate((b, c) => { b.writeUInt32LE(1, c + 42); })],
+ ["unpreserved timestamps", () => mutate((b, c) => { b.writeUInt16LE(33, 12); b.writeUInt16LE(33, c + 14); })],
+ ["unpreserved attributes", () => mutate((b, c) => { b.writeUInt32LE(0x81a40000, c + 38); })],
+ ["truncated entry", () => mutate((b, c) => { b.writeUInt32LE(c, 18); b.writeUInt32LE(c, c + 20); })],
+ ["ZIP64", () => mutate((b) => { b.writeUInt16LE(0xffff, b.length - 12); })],
+];
+
+describe("archive admission preserves bytes or fails closed", () => {
+ const dirs: string[] = [];
+ afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
+ it("reads an independently specified classic stored ZIP fixture", () => {
+ const input = Buffer.from([
+ "504b03041400000000000000000086a610360500000005000000010000006168656c6c6f",
+ "504b010214001400000000000000000086a61036050000000500000001000000000000000000000000000000000061",
+ "504b050600000000010001002f000000240000000000",
+ ].join(""), "hex");
+ expect(readZipEntries(input)[0]?.data.toString()).toBe("hello");
+ });
+ it("preserves stored and deflated file contents", () => {
+ const originals = [{ name: "short", data: Buffer.from("hello") }, { name: "long", data: Buffer.from("plain content ".repeat(20)) }];
+ const input = writeZipArchive(originals);
+ const result = protectZipOrApkBuffer(input, { intensity: "stealth", seed: "integrity" });
+ const entries = readZipEntries(result.buffer);
+ for (const item of originals) expect(entries.find((e) => e.name === item.name)?.data).toEqual(item.data);
+ });
+ it.each(bad)("rejects %s without changing the supplied buffer", (_name, create) => {
+ const input = create(); const before = Buffer.from(input);
+ expect(() => readZipEntries(input)).toThrow(UnsupportedArchiveError);
+ expect(() => protectZipOrApkBuffer(input)).toThrow(UnsupportedArchiveError);
+ expect(input).toEqual(before);
+ });
+ it("refuses unsigned APKs and APK contents renamed as ZIP", () => {
+ expect(() => protectZipOrApkBuffer(fixture(), { isApk: true })).toThrow(UnsupportedApkProtectionError);
+ const renamed = writeZipArchive([{ name: "AndroidManifest.xml", data: Buffer.from("fixture") }]);
+ expect(() => protectZipOrApkBuffer(renamed)).toThrow(/signing-aware/);
+ });
+ it("refuses signed archives and duplicate names", () => {
+ expect(() => protectZipOrApkBuffer(writeZipArchive([{ name: "META-INF/TEST.RSA", data: Buffer.from("not a real signature") }]))).toThrow(/signing-aware/);
+ expect(() => readZipEntries(writeZipArchive([{ name: "a", data: Buffer.from("1") }, { name: "a", data: Buffer.from("2") }]))).toThrow(/duplicate/);
+ });
+ it.each(["bad.zip", "unsigned.apk", "renamed.zip"])("retains input/output and creates no directory for %s", (name) => {
+ const dir = mkdtempSync(join(tmpdir(), "bla-archive-")); dirs.push(dir);
+ const input = join(dir, name); const output = join(dir, "existing.zip");
+ const bytes = name === "bad.zip" ? bad[0]![1]() : name === "renamed.zip" ? writeZipArchive([{ name: "AndroidManifest.xml", data: Buffer.from("fixture") }]) : fixture();
+ writeFileSync(input, bytes); writeFileSync(output, "existing output");
+ expect(() => protectTarget({ inputPath: input, outputPath: output })).toThrow();
+ expect(readFileSync(output, "utf8")).toBe("existing output");
+ expect(() => protectTarget({ inputPath: input, inPlace: true })).toThrow();
+ expect(readFileSync(input)).toEqual(bytes);
+ expect(() => protectTarget({ inputPath: input, outputPath: join(dir, "new", "out.zip") })).toThrow();
+ expect(existsSync(join(dir, "new"))).toBe(false);
+ });
+});
diff --git a/tests/multi-format-shields.test.ts b/tests/multi-format-shields.test.ts
index 5c35c7c..d0ec696 100644
--- a/tests/multi-format-shields.test.ts
+++ b/tests/multi-format-shields.test.ts
@@ -183,7 +183,7 @@ describe("Multi-Format Shields (WASM, Python, Native ELF/Mach-O/PE, C/Rust/Go He
expect(goHeader.content).toContain("func BlaEnclaveTarpit0");
});
- it("protects ZIP and Android APK archives while preserving existing entries", () => {
+ it("protects supported minimal ZIP archives while preserving existing entries", () => {
const rawZip = writeZipArchive([
{
name: "assets/index.js",
@@ -201,7 +201,7 @@ describe("Multi-Format Shields (WASM, Python, Native ELF/Mach-O/PE, C/Rust/Go He
const protectedZip = protectZipOrApkBuffer(rawZip, {
intensity: "balanced",
seed: "zip-test-seed",
- isApk: true,
+ isApk: false,
});
expect(protectedZip.decoyEntriesInjected).toBe(5);