Skip to content

armgit / bla

Public Imported from GitHub
0

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

feat(python): remmarshal .pyc customer-def weave_decoys (v1.6.4) (#54)

Timo Zhanga426ca4a177a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a0a98e0..145d989 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,8 +23,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- **`weave_decoys` is a real pipeline attribute** for Python source (not label-only):
- planner maturity for `python-source` is `woven`; MCP/docs/`pipelineHook.todayBehaviorZh`
- describe structural weave. `.pyc` remains warm-init / trailer oriented.
+ planner maturity for `python-source` and `python-pyc` is `woven`; MCP/docs/`pipelineHook.todayBehaviorZh`
+ describe structural weave. `.pyc` without `weave_decoys` stays trailer-oriented.
- **Python tarpit densification** (`tarpit-generator.ts`, `python.ts`): decoys
no longer look like empty `_bla_*` honeypots — mixed mundane/scare stems,
heterogeneous always-executed bodies that mutate shared state, and a live
@@ -41,6 +41,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
densify by shielding `.py`/`.pyc` before bundling (`python.ts` /
`native.ts` notes + `docs/counter-rea-deception.md`).
+## [1.6.4] — 2026-11-02
+
+### Added
+
+- **Python `.pyc` customer-def weave** (`src/shields/formats/python-pyc-weave.ts`):
+ when `weave_decoys: true`, remmarshal the code object (CPython FLAG_REF early-reserve
+ for containers/CODE; copy shared `co_consts` before mutate) and append unused decoy
+ `TYPE_CODE` into module + customer `co_consts` (no `FLAG_REF` on decoys; original
+ `co_code` preserved). Trailer canary/diagnostic honey still applied. Planner maturity
+ for `python-pyc` is now `woven`.
+
## [1.6.3] — 2026-11-01
Patch release shipping CrackMe v7 Meridian (challenge, scripts, tests, docs, website) on top of the 1.6.2 UF2 firmware shield. No library or CLI behavior changes.
diff --git a/STATE.md b/STATE.md
index 87cbd6a..3296d72 100644
--- a/STATE.md
+++ b/STATE.md
@@ -1,6 +1,6 @@
# BLA state of the project
-**Version:** 1.6.3 (`package.json` ↔ `src/identity.ts`, verified by build; see `CHANGELOG.md`)
+**Version:** 1.6.4 (`package.json` ↔ `src/identity.ts`, verified by build; see `CHANGELOG.md`)
**Status:** CI matrix runs typecheck, build, tests and the benchmark on ubuntu / macos / windows with Node 24. Windows checkouts keep `challenge/**` LF via `.gitattributes` so the CrackMe seals verify.
**Publishing:** tag-only releases (`git tag bla-agents-<version>`); see `CHANGELOG.md` and GitHub Releases.
@@ -20,7 +20,7 @@ Also: `bla_harden` MCP tool with `{ "directory": "." }`.
| JavaScript / TypeScript | ✓ | **verified** — real REA `resourceLimits` (alias/getter/primitive) + anti-strip | AST + semantic budgets |
| Electron ASAR | ✓ | **verified** — `DEFAULT_ASAR_MAX_HEADER_BYTES` | |
| WebAssembly | ✓ export decoys | **verified** — Wabt `WASM_INTERFACE_REPRESENTATION_BYTES` / partial | needs Wabt for REA path |
-| Python `.py` / `.pyc` | ✓ | designed-for | |
+| Python `.py` / `.pyc` | ✓ | designed-for | `.py` AST weave + `.pyc` remmarshal `co_consts` CODE weave when `weave_decoys` |
| Native ELF (Go/Flutter/Electron fuses) | ✓ | **verified** — `MAX_BUILD_INFO_BYTES`, pool URIs/tokens, fuse sentinels | |
| SQLite | ✓ honey + trap columns | **verified** on Node 24 — `SqliteColumnEvaluationFailure`; Node 22 soft `capability_gated` | |
| Safetensors | ✓ nesting breaker | **verified** — `MODEL_JSON_NESTING` (HF-loadable) | |
@@ -89,14 +89,13 @@ Outside the repo, `npm pack` → install tarball → isolated `HOME`:
## Nightly roadmap remaining
-1. **Empirical JADX / Android red-team** — run real REA Android mapping + JNI
- tools against a BLA-hardened unsigned APK fixture; record before/after.
-2. **Manifest-component decoys** — counter REA #7379 selected manifest component
- declarations (binary AndroidManifest.xml decoys for unsigned APKs).
-3. **GPU objects** — make PTX (and later CUDA/SPIR-V/AMD) trip a real REA budget without breaking validity
-4. **Firmware** — decide scope or keep skipped
-5. **Signed APK** — keep refuse-by-default; optional resign workflow documentation
-6. Polish doctor subsystem list (SQLite / models / BEAM / EVM / Android R8) for parity with shields
+1. **Self-seal / defenseScore honesty (#40)** — opt-in self-integrity + honest scores for onefile/peel limits.
+2. **Sidecar entry entanglement** — entangle protectors with entry/sidecar so stripping decoys breaks runtime.
+3. **Deception shields → more formats** — WASM custom sections/export names, DEX string pool, SQLite comments/metadata, Safetensors/GGUF header metadata.
+4. **Empirical JADX / Android red-team** — real REA mapping+JNI vs BLA-hardened unsigned APK.
+5. **ESP flash / esp-image (#8228)** — if REA moved there; UF2 empirical red-team otherwise.
+6. **Dependabot majors #29–#35** — still held pending review.
+7. Polish doctor subsystem list (SQLite / models / BEAM / EVM / Android R8) for parity with shields.
## Publish checklist (once a GitHub token exists)
diff --git a/docs/weave-decoy-mcp.md b/docs/weave-decoy-mcp.md
index 09269f0..a21b7ff 100644
--- a/docs/weave-decoy-mcp.md
+++ b/docs/weave-decoy-mcp.md
@@ -24,7 +24,7 @@
| :--- | :--- | :--- |
| **JavaScript / TypeScript** (`ast-shield.ts`) | **已织入** | opaque-true 包裹快乐路径语句;真实函数体织入步进器与 tarpit 互调;认知装甲与 seed 纠缠 |
| **Python `.py`** (`python-ast-weave.ts` + tarpit) | **woven(需 `weave_decoys: true`)** | #51 稠密异构体 + warm-init 之后,对客户 `FunctionDef` 做结构织入:共享槽 touch + opaque-false 诱饵调用;按 tarpit 名表**身份**跳过已注入 decoy/warm(非业务名规则) |
-| **Python `.pyc`** | warm-init / trailer 为主 | 客户入口织入仍有限 |
+| **Python `.pyc`** | `weave_decoys:true` → co_consts decoy TYPE_CODE 织入 | false 时仍为 trailer honey |
| 若干二进制 / sidecar 格式 | sidecar / 附加块 | 原则仍适用;完整入口纠缠列为后续 |
`weave_decoys: false` 时 Python 行为与 #51 一致(仅 warm-init,不改客户 `def` 体)。
@@ -77,7 +77,7 @@
## 8. Follow-up
-- `.pyc` / 更多格式的客户入口纠缠验收
+- 更多 sidecar 格式的入口纠缠验收;可选 self-seal / defenseScore honesty (#40)
- 可选 self-seal 与 `defenseScore` 对 onefile 诚实性(#40)
## 相关文档
diff --git a/package.json b/package.json
index 3041a52..cb591cb 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "bla-agents",
- "version": "1.6.3",
+ "version": "1.6.4",
"description": "BLA (Blind LLM Agents) \u2014 Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, WebAssembly, SQLite, AI Models, and Android DEX/IL2CPP against AI reverse-engineering agents like REA.",
"keywords": [
"reverse-engineering-defense",
diff --git a/src/engine/protector.ts b/src/engine/protector.ts
index 9b86a86..e4e31b2 100644
--- a/src/engine/protector.ts
+++ b/src/engine/protector.ts
@@ -355,12 +355,20 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
counteredVectors.add("call-graph-tracing");
} else if (format === "python-pyc") {
const rawPyc = readFileSync(absInput);
- const res = protectPythonPycBuffer(rawPyc, { intensity, seed });
+ const res = protectPythonPycBuffer(rawPyc, {
+ intensity,
+ seed,
+ weaveDecoys: options.weaveDecoys === true,
+ });
writeFileSync(absOutput, res.buffer);
- decoyFunctionsInjected = 14;
+ decoyFunctionsInjected =
+ res.decoyCodeObjectsInjected > 0 ? res.decoyCodeObjectsInjected : 14;
chaffPayloadsEmbedded = res.chaffPayloadsEmbedded;
binarySectionsPatched = 1;
counteredVectors.add("python-pyc-marshal");
+ if (res.weaveDecoys && res.customerDefsWoven > 0) {
+ counteredVectors.add("call-graph-tracing");
+ }
} else if (
format === "native-elf" ||
format === "native-macho" ||
diff --git a/src/identity.ts b/src/identity.ts
index fe42b4a..88b0835 100644
--- a/src/identity.ts
+++ b/src/identity.ts
@@ -5,7 +5,7 @@ export const BLA_IDENTITY = Object.freeze({
packageAlias: "bla-shield",
cliBinary: "bla",
cliAlias: "bla-agents",
- version: "1.6.3",
+ version: "1.6.4",
slogan: "Poison -> Exhaust -> Hallucinate. Make Reverse Engineering Bankrupt Again.",
counterpart: {
name: "REA",
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 18d3942..7dae63e 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -126,7 +126,7 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
weave_decoys: {
type: "boolean",
description:
- "Opt-in weave-decoy entanglement: JS AST weave (always) + structural Python customer-def weave (shared-slot + opaque-false decoy xref). When false, Python stays warm-init-only. See bla://directives/weave-decoy. Default false.",
+ "Opt-in weave-decoy entanglement: JS AST weave (always) + Python .py customer-def weave + .pyc co_consts TYPE_CODE weave. When false, Python stays warm-init/trailer-only. See bla://directives/weave-decoy. Default false.",
},
seed: {
type: "string",
@@ -167,7 +167,7 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
weave_decoys: {
type: "boolean",
description:
- "Opt-in weave-decoy entanglement (shared-state / entry-reachable decoys into customer paths; not dismissible noise). Python .py structural weave when true. Default false.",
+ "Opt-in weave-decoy entanglement (shared-state / entry-reachable decoys into customer paths; not dismissible noise). Python .py structural weave + .pyc co_consts CODE weave when true. Default false.",
},
seed: {
type: "string",
@@ -217,7 +217,7 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
weave_decoys: {
type: "boolean",
description:
- "Opt-in weave-decoy entanglement (shared-state / entry-reachable decoys into customer paths; not dismissible noise). Python .py structural weave when true. Default false.",
+ "Opt-in weave-decoy entanglement (shared-state / entry-reachable decoys into customer paths; not dismissible noise). Python .py structural weave + .pyc co_consts CODE weave when true. Default false.",
},
seed: {
type: "string",
diff --git a/src/shields/formats/python-pyc-weave.ts b/src/shields/formats/python-pyc-weave.ts
new file mode 100644
index 0000000..4584494
--- /dev/null
+++ b/src/shields/formats/python-pyc-weave.ts
@@ -0,0 +1,664 @@
+/**
+ * Structural .pyc decoy weave — remmarshal code objects so unused decoy
+ * TYPE_CODE entries sit in customer/module `co_consts` pools.
+ *
+ * REA `inspect_python_pyc` inventories them as real functions; CPython never
+ * executes them (no MAKE_FUNCTION / call references them).
+ *
+ * Safety rules (engineering red line):
+ * - Decode with a FLAG_REF intern table, then re-emit WITHOUT FLAG_REF so
+ * shared consts/filename refs expand to concrete copies (behavior-identical).
+ * - Original co_code / arg counts / flags / names tables preserved.
+ * - On unsupported marshal forms, abort and let caller keep trailer-only honey.
+ */
+import { SeededPrng } from "../../core/prng.js";
+import type { ProtectionIntensity } from "../../core/types.js";
+
+export type PythonPycCodeLayout = "py37" | "py38" | "py311";
+
+const FLAG_REF = 0x80;
+const TYPE_NULL = 0x30;
+const TYPE_NONE = 0x4e;
+const TYPE_FALSE = 0x46;
+const TYPE_TRUE = 0x54;
+const TYPE_STOPITER = 0x53;
+const TYPE_ELLIPSIS = 0x2e;
+const TYPE_INT = 0x69;
+const TYPE_INT64 = 0x49;
+const TYPE_FLOAT_TEXT = 0x66;
+const TYPE_FLOAT = 0x67;
+const TYPE_COMPLEX_TEXT = 0x78;
+const TYPE_COMPLEX = 0x79;
+const TYPE_LONG = 0x6c;
+const TYPE_BYTES = 0x73;
+const TYPE_INTERNED = 0x74;
+const TYPE_REF = 0x72;
+const TYPE_TUPLE = 0x28;
+const TYPE_LIST = 0x5b;
+const TYPE_DICT = 0x7b;
+const TYPE_CODE = 0x63;
+const TYPE_UNICODE = 0x75;
+const TYPE_SET = 0x3c;
+const TYPE_FROZENSET = 0x3e;
+const TYPE_ASCII = 0x61;
+const TYPE_ASCII_INTERNED = 0x41;
+const TYPE_SMALL_TUPLE = 0x29;
+const TYPE_SHORT_ASCII = 0x7a;
+const TYPE_SHORT_ASCII_INTERNED = 0x5a;
+
+const MAGIC_LAYOUT: ReadonlyMap<number, PythonPycCodeLayout> = new Map([
+ ...range(3390, 3394, "py37"),
+ ...range(3400, 3401, "py37"),
+ ...range(3410, 3439, "py38"),
+ ...range(3494, 3495, "py311"),
+ ...range(3500, 3531, "py311"),
+ ...range(3550, 3571, "py311"),
+]);
+
+function range(
+ start: number,
+ end: number,
+ layout: PythonPycCodeLayout,
+): Array<[number, PythonPycCodeLayout]> {
+ const out: Array<[number, PythonPycCodeLayout]> = [];
+ for (let m = start; m <= end; m++) out.push([m, layout]);
+ return out;
+}
+
+export function layoutForPycMagic(magic: number): PythonPycCodeLayout | null {
+ return MAGIC_LAYOUT.get(magic) ?? null;
+}
+
+const MUNDANE_STEMS = [
+ "reconcile_invoice_batch",
+ "hydrate_session_cache",
+ "flush_telemetry_buffer",
+ "normalize_locale_bundle",
+ "schedule_backoff_retry",
+ "compact_wal_segment",
+ "project_catalog_facet",
+ "bind_worker_pool_slot",
+ "materialize_report_cursor",
+ "encode_transport_frame",
+ "observe_metric_histogram",
+ "adapt_gateway_policy",
+ "reduce_pipeline_shard",
+ "capture_audit_sample",
+ "prime_connection_pool",
+ "transform_lookup_vector",
+] as const;
+
+const SCARE_STEMS = [
+ "verify_enclave_attestation",
+ "derive_hardware_kdf_schedule",
+ "authenticate_tpm_quote_digest",
+ "negotiate_vsock_channel_cipher",
+ "synchronize_hsm_key_slot",
+ "unseal_protected_memory_page",
+] as const;
+
+export interface PythonPycWeaveResult {
+ readonly buffer: Buffer;
+ readonly decoyCodeObjectsInjected: number;
+ readonly customerDefsWoven: number;
+ readonly layout: PythonPycCodeLayout;
+}
+
+type MarshalValue =
+ | { readonly kind: "none" }
+ | { readonly kind: "bool"; readonly value: boolean }
+ | { readonly kind: "ellipsis" }
+ | { readonly kind: "stopiter" }
+ | { readonly kind: "int"; readonly value: number }
+ | { readonly kind: "int64"; readonly bytes: Buffer }
+ | { readonly kind: "float"; readonly bytes: Buffer }
+ | { readonly kind: "complex"; readonly bytes: Buffer }
+ | { readonly kind: "float_text"; readonly text: string }
+ | { readonly kind: "complex_text"; readonly real: string; readonly imag: string }
+ | { readonly kind: "long"; readonly digits: Buffer; readonly negative: boolean }
+ | { readonly kind: "bytes"; readonly data: Buffer }
+ | { readonly kind: "str"; readonly data: string }
+ | { readonly kind: "tuple"; readonly items: MarshalValue[] }
+ | { readonly kind: "list"; readonly items: MarshalValue[] }
+ | { readonly kind: "set"; readonly items: MarshalValue[]; readonly frozen: boolean }
+ | { readonly kind: "dict"; readonly items: Array<[MarshalValue, MarshalValue]> }
+ | { readonly kind: "code"; readonly code: CodeValue };
+
+interface CodeValue {
+ argcount: number;
+ posonlyargcount: number | null;
+ kwonlyargcount: number;
+ nlocals: number | null;
+ stacksize: number;
+ flags: number;
+ bytecode: Buffer;
+ consts: MarshalValue[];
+ names: MarshalValue[];
+ localsplusnames: MarshalValue[] | null;
+ localspluskinds: Buffer | null;
+ varnames: MarshalValue[] | null;
+ freevars: MarshalValue[] | null;
+ cellvars: MarshalValue[] | null;
+ filename: string;
+ name: string;
+ qualname: string | null;
+ firstlineno: number;
+ linetable: Buffer;
+ exceptiontable: Buffer | null;
+}
+
+class Reader {
+ offset = 0;
+ readonly refs: MarshalValue[] = [];
+ constructor(
+ readonly buf: Buffer,
+ readonly layout: PythonPycCodeLayout,
+ ) {}
+
+ u8(): number {
+ if (this.offset >= this.buf.length) throw new Error("truncated u8");
+ return this.buf[this.offset++]!;
+ }
+ i32(): number {
+ if (this.offset + 4 > this.buf.length) throw new Error("truncated i32");
+ const v = this.buf.readInt32LE(this.offset);
+ this.offset += 4;
+ return v;
+ }
+ u32(): number {
+ if (this.offset + 4 > this.buf.length) throw new Error("truncated u32");
+ const v = this.buf.readUInt32LE(this.offset);
+ this.offset += 4;
+ return v;
+ }
+ slice(n: number): Buffer {
+ if (n < 0 || this.offset + n > this.buf.length) throw new Error("truncated slice");
+ const s = this.buf.subarray(this.offset, this.offset + n);
+ this.offset += n;
+ return Buffer.from(s);
+ }
+
+ read(): MarshalValue {
+ const raw = this.u8();
+ const flagged = (raw & FLAG_REF) !== 0;
+ const type = raw & ~FLAG_REF;
+ if (type === TYPE_REF) {
+ const idx = this.u32();
+ const hit = this.refs[idx];
+ if (hit === undefined || hit === null) {
+ throw new Error(`bad TYPE_REF ${idx} (have ${this.refs.length})`);
+ }
+ return hit;
+ }
+ // CPython reserves FLAG_REF slots for containers BEFORE reading children so
+ // nested TYPE_REF indices stay stable (see Python/marshal.c r_object).
+ // Match CPython: tuples/lists/dicts/sets R_REF before children;
+ // CODE and non-empty frozenset use r_ref_reserve before body (marshal.c).
+ const earlyContainer =
+ type === TYPE_TUPLE ||
+ type === TYPE_SMALL_TUPLE ||
+ type === TYPE_LIST ||
+ type === TYPE_DICT ||
+ type === TYPE_SET ||
+ type === TYPE_FROZENSET ||
+ type === TYPE_CODE;
+ let slot = -1;
+ if (flagged && earlyContainer) {
+ slot = this.refs.length;
+ this.refs.push(null as unknown as MarshalValue);
+ }
+ const value = this.readType(type);
+ if (flagged) {
+ if (slot >= 0) this.refs[slot] = value;
+ else this.refs.push(value);
+ }
+ return value;
+ }
+
+ private readType(type: number): MarshalValue {
+ switch (type) {
+ case TYPE_NULL:
+ throw new Error("unexpected NULL");
+ case TYPE_NONE:
+ return { kind: "none" };
+ case TYPE_FALSE:
+ return { kind: "bool", value: false };
+ case TYPE_TRUE:
+ return { kind: "bool", value: true };
+ case TYPE_STOPITER:
+ return { kind: "stopiter" };
+ case TYPE_ELLIPSIS:
+ return { kind: "ellipsis" };
+ case TYPE_INT:
+ return { kind: "int", value: this.i32() };
+ case TYPE_INT64:
+ return { kind: "int64", bytes: this.slice(8) };
+ case TYPE_FLOAT:
+ return { kind: "float", bytes: this.slice(8) };
+ case TYPE_COMPLEX:
+ return { kind: "complex", bytes: this.slice(16) };
+ case TYPE_FLOAT_TEXT: {
+ const n = this.u8();
+ return { kind: "float_text", text: this.slice(n).toString("ascii") };
+ }
+ case TYPE_COMPLEX_TEXT: {
+ const n1 = this.u8();
+ const real = this.slice(n1).toString("ascii");
+ const n2 = this.u8();
+ const imag = this.slice(n2).toString("ascii");
+ return { kind: "complex_text", real, imag };
+ }
+ case TYPE_LONG: {
+ const n = this.i32();
+ const abs = Math.abs(n);
+ return {
+ kind: "long",
+ digits: this.slice(abs * 2),
+ negative: n < 0,
+ };
+ }
+ case TYPE_BYTES: {
+ const n = this.u32();
+ return { kind: "bytes", data: this.slice(n) };
+ }
+ case TYPE_INTERNED:
+ case TYPE_UNICODE:
+ case TYPE_ASCII:
+ case TYPE_ASCII_INTERNED: {
+ const n = this.u32();
+ return { kind: "str", data: this.slice(n).toString("utf8") };
+ }
+ case TYPE_SHORT_ASCII:
+ case TYPE_SHORT_ASCII_INTERNED: {
+ const n = this.u8();
+ return { kind: "str", data: this.slice(n).toString("utf8") };
+ }
+ case TYPE_SMALL_TUPLE: {
+ const n = this.u8();
+ const items: MarshalValue[] = [];
+ for (let i = 0; i < n; i++) items.push(this.read());
+ return { kind: "tuple", items };
+ }
+ case TYPE_TUPLE: {
+ const n = this.u32();
+ const items: MarshalValue[] = [];
+ for (let i = 0; i < n; i++) items.push(this.read());
+ return { kind: "tuple", items };
+ }
+ case TYPE_LIST: {
+ const n = this.u32();
+ const items: MarshalValue[] = [];
+ for (let i = 0; i < n; i++) items.push(this.read());
+ return { kind: "list", items };
+ }
+ case TYPE_SET:
+ case TYPE_FROZENSET: {
+ const n = this.u32();
+ const items: MarshalValue[] = [];
+ for (let i = 0; i < n; i++) items.push(this.read());
+ return { kind: "set", items, frozen: type === TYPE_FROZENSET };
+ }
+ case TYPE_DICT: {
+ const items: Array<[MarshalValue, MarshalValue]> = [];
+ while (true) {
+ const raw = this.buf[this.offset];
+ if (raw === undefined) throw new Error("dict truncated");
+ if ((raw & ~FLAG_REF) === TYPE_NULL) {
+ this.u8();
+ break;
+ }
+ const k = this.read();
+ const v = this.read();
+ items.push([k, v]);
+ }
+ return { kind: "dict", items };
+ }
+ case TYPE_CODE:
+ return { kind: "code", code: this.readCode() };
+ default:
+ throw new Error(`unsupported marshal type 0x${type.toString(16)}`);
+ }
+ }
+
+ private readCode(): CodeValue {
+ const argcount = this.u32();
+ const posonlyargcount = this.layout === "py37" ? null : this.u32();
+ const kwonlyargcount = this.u32();
+ const nlocals = this.layout === "py311" ? null : this.u32();
+ const stacksize = this.i32();
+ const flags = this.i32();
+ const bytecodeVal = this.read();
+ if (bytecodeVal.kind !== "bytes") throw new Error("co_code not bytes");
+ const constsVal = this.read();
+ if (constsVal.kind !== "tuple") throw new Error("co_consts not tuple");
+ const namesVal = this.read();
+ if (namesVal.kind !== "tuple") throw new Error("co_names not tuple");
+
+ let localsplusnames: MarshalValue[] | null = null;
+ let localspluskinds: Buffer | null = null;
+ let varnames: MarshalValue[] | null = null;
+ let freevars: MarshalValue[] | null = null;
+ let cellvars: MarshalValue[] | null = null;
+ if (this.layout === "py311") {
+ const lp = this.read();
+ if (lp.kind !== "tuple") throw new Error("localsplusnames not tuple");
+ localsplusnames = lp.items;
+ const lk = this.read();
+ if (lk.kind !== "bytes") throw new Error("localspluskinds not bytes");
+ localspluskinds = lk.data;
+ } else {
+ const vn = this.read();
+ const fv = this.read();
+ const cv = this.read();
+ if (vn.kind !== "tuple" || fv.kind !== "tuple" || cv.kind !== "tuple") {
+ throw new Error("var/free/cell names not tuples");
+ }
+ varnames = vn.items;
+ freevars = fv.items;
+ cellvars = cv.items;
+ }
+
+ const filenameVal = this.read();
+ if (filenameVal.kind !== "str") throw new Error("co_filename not str");
+ const nameVal = this.read();
+ if (nameVal.kind !== "str") throw new Error("co_name not str");
+ let qualname: string | null = null;
+ if (this.layout === "py311") {
+ const q = this.read();
+ if (q.kind !== "str") throw new Error("co_qualname not str");
+ qualname = q.data;
+ }
+ const firstlineno = this.i32();
+ const lt = this.read();
+ if (lt.kind !== "bytes") throw new Error("co_linetable not bytes");
+ let exceptiontable: Buffer | null = null;
+ if (this.layout === "py311") {
+ const et = this.read();
+ if (et.kind !== "bytes") throw new Error("co_exceptiontable not bytes");
+ exceptiontable = et.data;
+ }
+
+ return {
+ argcount,
+ posonlyargcount,
+ kwonlyargcount,
+ nlocals,
+ stacksize,
+ flags,
+ bytecode: bytecodeVal.data,
+ consts: constsVal.items,
+ names: namesVal.items,
+ localsplusnames,
+ localspluskinds,
+ varnames,
+ freevars,
+ cellvars,
+ filename: filenameVal.data,
+ name: nameVal.data,
+ qualname,
+ firstlineno,
+ linetable: lt.data,
+ exceptiontable,
+ };
+ }
+}
+
+function u32(n: number): Buffer {
+ const b = Buffer.alloc(4);
+ b.writeUInt32LE(n >>> 0, 0);
+ return b;
+}
+function i32(n: number): Buffer {
+ const b = Buffer.alloc(4);
+ b.writeInt32LE(n, 0);
+ return b;
+}
+
+function encode(value: MarshalValue, layout: PythonPycCodeLayout): Buffer {
+ switch (value.kind) {
+ case "none":
+ return Buffer.from([TYPE_NONE]);
+ case "bool":
+ return Buffer.from([value.value ? TYPE_TRUE : TYPE_FALSE]);
+ case "stopiter":
+ return Buffer.from([TYPE_STOPITER]);
+ case "ellipsis":
+ return Buffer.from([TYPE_ELLIPSIS]);
+ case "int":
+ return Buffer.concat([Buffer.from([TYPE_INT]), i32(value.value)]);
+ case "int64":
+ return Buffer.concat([Buffer.from([TYPE_INT64]), value.bytes]);
+ case "float":
+ return Buffer.concat([Buffer.from([TYPE_FLOAT]), value.bytes]);
+ case "complex":
+ return Buffer.concat([Buffer.from([TYPE_COMPLEX]), value.bytes]);
+ case "float_text": {
+ const t = Buffer.from(value.text, "ascii");
+ return Buffer.concat([Buffer.from([TYPE_FLOAT_TEXT, t.length]), t]);
+ }
+ case "complex_text": {
+ const r = Buffer.from(value.real, "ascii");
+ const im = Buffer.from(value.imag, "ascii");
+ return Buffer.concat([
+ Buffer.from([TYPE_COMPLEX_TEXT, r.length]),
+ r,
+ Buffer.from([im.length]),
+ im,
+ ]);
+ }
+ case "long": {
+ const n = value.digits.length / 2;
+ return Buffer.concat([
+ Buffer.from([TYPE_LONG]),
+ i32(value.negative ? -n : n),
+ value.digits,
+ ]);
+ }
+ case "bytes":
+ return Buffer.concat([
+ Buffer.from([TYPE_BYTES]),
+ u32(value.data.length),
+ value.data,
+ ]);
+ case "str": {
+ const b = Buffer.from(value.data, "utf8");
+ if (b.length <= 255) {
+ return Buffer.concat([Buffer.from([TYPE_SHORT_ASCII, b.length]), b]);
+ }
+ return Buffer.concat([Buffer.from([TYPE_ASCII]), u32(b.length), b]);
+ }
+ case "tuple": {
+ const parts = value.items.map((it) => encode(it, layout));
+ if (value.items.length <= 255) {
+ return Buffer.concat([
+ Buffer.from([TYPE_SMALL_TUPLE, value.items.length]),
+ ...parts,
+ ]);
+ }
+ return Buffer.concat([Buffer.from([TYPE_TUPLE]), u32(value.items.length), ...parts]);
+ }
+ case "list": {
+ const parts = value.items.map((it) => encode(it, layout));
+ return Buffer.concat([Buffer.from([TYPE_LIST]), u32(value.items.length), ...parts]);
+ }
+ case "set": {
+ const parts = value.items.map((it) => encode(it, layout));
+ return Buffer.concat([
+ Buffer.from([value.frozen ? TYPE_FROZENSET : TYPE_SET]),
+ u32(value.items.length),
+ ...parts,
+ ]);
+ }
+ case "dict": {
+ const parts: Buffer[] = [Buffer.from([TYPE_DICT])];
+ for (const [k, v] of value.items) {
+ parts.push(encode(k, layout), encode(v, layout));
+ }
+ parts.push(Buffer.from([TYPE_NULL]));
+ return Buffer.concat(parts);
+ }
+ case "code":
+ return encodeCode(value.code, layout);
+ default: {
+ const _exhaustive: never = value;
+ return _exhaustive;
+ }
+ }
+}
+
+function encodeCode(code: CodeValue, layout: PythonPycCodeLayout): Buffer {
+ const parts: Buffer[] = [Buffer.from([TYPE_CODE]), u32(code.argcount)];
+ if (layout !== "py37") parts.push(u32(code.posonlyargcount ?? 0));
+ parts.push(u32(code.kwonlyargcount));
+ if (layout !== "py311") parts.push(u32(code.nlocals ?? 0));
+ parts.push(i32(code.stacksize), i32(code.flags));
+ parts.push(encode({ kind: "bytes", data: code.bytecode }, layout));
+ parts.push(encode({ kind: "tuple", items: code.consts }, layout));
+ parts.push(encode({ kind: "tuple", items: code.names }, layout));
+ if (layout === "py311") {
+ parts.push(encode({ kind: "tuple", items: code.localsplusnames ?? [] }, layout));
+ parts.push(
+ encode({ kind: "bytes", data: code.localspluskinds ?? Buffer.alloc(0) }, layout),
+ );
+ } else {
+ parts.push(encode({ kind: "tuple", items: code.varnames ?? [] }, layout));
+ parts.push(encode({ kind: "tuple", items: code.freevars ?? [] }, layout));
+ parts.push(encode({ kind: "tuple", items: code.cellvars ?? [] }, layout));
+ }
+ parts.push(encode({ kind: "str", data: code.filename }, layout));
+ parts.push(encode({ kind: "str", data: code.name }, layout));
+ if (layout === "py311") {
+ parts.push(encode({ kind: "str", data: code.qualname ?? code.name }, layout));
+ }
+ parts.push(i32(code.firstlineno));
+ parts.push(encode({ kind: "bytes", data: code.linetable }, layout));
+ if (layout === "py311") {
+ parts.push(
+ encode({ kind: "bytes", data: code.exceptiontable ?? Buffer.alloc(0) }, layout),
+ );
+ }
+ return Buffer.concat(parts);
+}
+
+function buildDecoyCode(layout: PythonPycCodeLayout, name: string, filename: string): CodeValue {
+ return {
+ argcount: 0,
+ posonlyargcount: layout === "py37" ? null : 0,
+ kwonlyargcount: 0,
+ nlocals: layout === "py311" ? null : 0,
+ stacksize: 1,
+ flags: 0x40, // CO_NOFREE
+ bytecode: Buffer.from([0x64, 0x00, 0x53, 0x00]), // LOAD_CONST 0; RETURN_VALUE
+ consts: [{ kind: "none" }],
+ names: [],
+ localsplusnames: layout === "py311" ? [] : null,
+ localspluskinds: layout === "py311" ? Buffer.alloc(0) : null,
+ varnames: layout === "py311" ? null : [],
+ freevars: layout === "py311" ? null : [],
+ cellvars: layout === "py311" ? null : [],
+ filename,
+ name,
+ qualname: layout === "py311" ? name : null,
+ firstlineno: 1,
+ linetable: Buffer.alloc(0),
+ exceptiontable: layout === "py311" ? Buffer.alloc(0) : null,
+ };
+}
+
+function decoyCountForIntensity(intensity: ProtectionIntensity): number {
+ switch (intensity) {
+ case "stealth":
+ return 2;
+ case "balanced":
+ return 6;
+ case "maximum":
+ return 12;
+ case "bankrupt":
+ return 20;
+ default:
+ return 6;
+ }
+}
+
+function pickDecoyName(prng: SeededPrng, index: number): string {
+ const scare = index % 3 === 0;
+ const pool = scare ? SCARE_STEMS : MUNDANE_STEMS;
+ const stem = pool[prng.nextInt(0, pool.length - 1)]!;
+ return `${stem}_${prng.nextInt(1000, 9999)}`;
+}
+
+function injectDecoys(
+ code: CodeValue,
+ layout: PythonPycCodeLayout,
+ prng: SeededPrng,
+ moduleDecoys: number,
+ stats: { injected: number; woven: number },
+ isRoot: boolean,
+): void {
+ // CPython interns identical co_consts tuples via FLAG_REF/TYPE_REF; our Reader
+ // returns the same array reference. Copy before mutating so sibling code objects
+ // that shared a const tuple do not inherit each other's decoys.
+ code.consts = code.consts.slice();
+
+ // Snapshot nested codes before we push decoys into this consts list.
+ const nestedCodes: CodeValue[] = [];
+ for (const item of code.consts) {
+ if (item.kind === "code") nestedCodes.push(item.code);
+ }
+ for (const child of nestedCodes) {
+ injectDecoys(child, layout, prng, 0, stats, false);
+ }
+
+ const decoysToAdd = isRoot ? moduleDecoys : code.name !== "<module>" ? 1 : 0;
+ if (!isRoot && code.name !== "<module>" && decoysToAdd > 0) {
+ stats.woven += 1;
+ }
+ for (let i = 0; i < decoysToAdd; i++) {
+ const nm = pickDecoyName(prng, stats.injected + i);
+ const decoy = buildDecoyCode(layout, nm, code.filename || "shielded.py");
+ code.consts.push({ kind: "code", code: decoy });
+ stats.injected += 1;
+ }
+}
+
+/**
+ * Weave unused decoy CODE objects into a CPython .pyc buffer.
+ * Returns null when magic/layout is unknown or marshal round-trip fails.
+ */
+export function weavePythonPycBuffer(
+ bytes: Buffer,
+ options: {
+ readonly intensity?: ProtectionIntensity;
+ readonly seed?: string | number;
+ } = {},
+): PythonPycWeaveResult | null {
+ if (bytes.length < 17 || bytes[2] !== 0x0d || bytes[3] !== 0x0a) return null;
+ const magic = bytes.readUInt16LE(0);
+ const layout = layoutForPycMagic(magic);
+ if (!layout) return null;
+
+ const intensity = options.intensity ?? "balanced";
+ const prng = new SeededPrng(options.seed ?? "bla-pyc-weave-v1");
+ const moduleDecoys = decoyCountForIntensity(intensity);
+
+ try {
+ const header = bytes.subarray(0, 16);
+ const reader = new Reader(bytes.subarray(16), layout);
+ const root = reader.read();
+ if (root.kind !== "code") return null;
+ const trailing = bytes.subarray(16 + reader.offset);
+
+ const stats = { injected: 0, woven: 0 };
+ injectDecoys(root.code, layout, prng, moduleDecoys, stats, true);
+ const wovenRoot = encode(root, layout);
+
+ return {
+ buffer: Buffer.concat([header, wovenRoot, trailing]),
+ decoyCodeObjectsInjected: stats.injected,
+ customerDefsWoven: stats.woven,
+ layout,
+ };
+ } catch {
+ return null;
+ }
+}
diff --git a/src/shields/formats/python.ts b/src/shields/formats/python.ts
index f6168bc..a373047 100644
--- a/src/shields/formats/python.ts
+++ b/src/shields/formats/python.ts
@@ -4,6 +4,7 @@ import { generateChaffPayloads } from "../chaff/chaff-generator.js";
import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.js";
import { generatePythonTarpit } from "../tarpit/tarpit-generator.js";
import { weavePythonDecoyCalls } from "./python-ast-weave.js";
+import { weavePythonPycBuffer } from "./python-pyc-weave.js";
export class InvalidPythonSourceError extends Error {
constructor(message: string) {
@@ -814,25 +815,49 @@ export function protectPythonPycBuffer(
options: {
readonly intensity?: ProtectionIntensity;
readonly seed?: string | number;
+ /**
+ * When true, structurally weave unused decoy TYPE_CODE objects into customer
+ * and module `co_consts` (append-only; preserves FLAG_REF intern indices and
+ * executed bytecode). Falls back to trailer-only honey when marshal walk fails.
+ */
+ readonly weaveDecoys?: boolean;
} = {},
): {
readonly buffer: Buffer;
readonly chaffPayloadsEmbedded: number;
readonly canaryTokensEmbedded: number;
readonly diagnosticsEmbedded: number;
+ readonly weaveDecoys: boolean;
+ readonly decoyCodeObjectsInjected: number;
+ readonly customerDefsWoven: number;
} {
if (bytes.length < 16 || bytes[2] !== 0x0d || bytes[3] !== 0x0a) {
throw new Error("Invalid CPython .pyc header (missing 0x0d 0x0a magic marker)");
}
const intensity = options.intensity ?? "balanced";
- const prng = new SeededPrng(options.seed ?? "bla-pyc-shield-v1");
+ const weaveDecoys = options.weaveDecoys === true;
+ const seed = options.seed ?? "bla-pyc-shield-v1";
+ const prng = new SeededPrng(seed);
const chaffPayloads = generateChaffPayloads(prng, intensity);
const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
+ let working = bytes;
+ let decoyCodeObjectsInjected = 0;
+ let customerDefsWoven = 0;
+ if (weaveDecoys) {
+ const woven = weavePythonPycBuffer(bytes, { intensity, seed });
+ if (woven) {
+ working = woven.buffer;
+ decoyCodeObjectsInjected = woven.decoyCodeObjectsInjected;
+ customerDefsWoven = woven.customerDefsWoven;
+ }
+ }
+
// Construct marshal-framed ASCII constant records (TYPE_ASCII = 0x61 + uint32LE length + utf8 bytes).
// Keep distinctive prefixes within REA's PYTHON_PYC_CONST_PREVIEW_LIMIT (80) so canary tokens
// and diagnostic errorClass/systemCode survive truncated previews.
+ // Trailers sit AFTER the root marshal object so importlib stops at the woven root.
const marshalRecords: Buffer[] = [];
const pushAscii = (raw: string) => {
const strBytes = Buffer.from(raw, "utf8");
@@ -859,9 +884,12 @@ export function protectPythonPycBuffer(
}
return {
- buffer: Buffer.concat([bytes, ...marshalRecords]),
+ buffer: Buffer.concat([working, ...marshalRecords]),
chaffPayloadsEmbedded: chaffPayloads.length,
canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
+ weaveDecoys,
+ decoyCodeObjectsInjected,
+ customerDefsWoven,
};
}
diff --git a/src/shields/weave/weave-decoy.ts b/src/shields/weave/weave-decoy.ts
index d48e4bc..ea774fb 100644
--- a/src/shields/weave/weave-decoy.ts
+++ b/src/shields/weave/weave-decoy.ts
@@ -251,7 +251,8 @@ function maturityForFormat(format: ArtifactFormat): WeaveMaturity {
// Structural customer-def weave lands when weave_decoys:true (warm-init remains when false).
return "woven";
case "python-pyc":
- return "warm-init-only";
+ // Nested TYPE_CODE weave into customer/module co_consts when weave_decoys:true.
+ return "woven";
case "electron-asar":
case "firmware-uf2":
case "android-dex":
@@ -285,7 +286,7 @@ function notesForMaturity(maturity: WeaveMaturity): string {
case "woven":
return "JS AST / Python 结构织入已将诱饵织入真实函数体(opaque + tarpit/xref)。Python 需 weave_decoys:true;保持此路径,禁止再加可剥离噪声层。";
case "warm-init-only":
- return "该格式目前以稠密诱饵 + 模块 warm-init / sidecar 为主(如 .pyc);完整客户入口织入仍有限。";
+ return "该格式目前以稠密诱饵 + 模块 warm-init / sidecar 为主;完整客户入口织入仍有限。";
case "sidecar-decoy":
return "格式以 sidecar / 附加块诱饵为主;织入原则仍适用:避免空同质 scare,保持可达与词干混用。";
case "gap":
@@ -305,7 +306,7 @@ function actionsForMaturity(maturity: WeaveMaturity): readonly string[] {
case "warm-init-only":
return Object.freeze([
"Keep densified tarpit + warm-init; do not add empty honeypot modules.",
- "Prefer .py sources with weave_decoys:true when customer-def weave is required.",
+ "Prefer .py sources (or .pyc with weave_decoys:true for co_consts CODE weave) when customer-def weave is required.",
"Optional: self-seal binding (issue #40).",
]);
case "sidecar-decoy":
@@ -486,9 +487,9 @@ const PIPELINE_HOOK = Object.freeze({
mcpFlag: "weave_decoys" as const,
hardenOption: "weaveDecoys" as const,
todayBehaviorZh:
- "weave_decoys=true 时:JS 保持现有 AST 织入;Python `.py` 在稠密 tarpit + warm-init 之后,对客户 FunctionDef 做结构织入(共享槽 touch + opaque-false 诱饵调用,按身份跳过已注入 decoy/warm)。false 时 Python 仍为 warm-init-only。报告标注 weaveDecoys。",
+ "weave_decoys=true 时:JS 保持现有 AST 织入;Python `.py` 对客户 FunctionDef 做结构织入;Python `.pyc` 向客户/模块 co_consts 追加未执行 decoy TYPE_CODE(append-only,保 FLAG_REF)。false 时 .py 为 warm-init-only、.pyc 为 trailer honey。报告标注 weaveDecoys。",
followUpZh:
- "Follow-up:.pyc 客户入口织入;可选 self-seal;扩展 sidecar 格式的入口纠缠验收。",
+ "Follow-up:可选 self-seal / defenseScore honesty;扩展 sidecar 格式的入口纠缠验收;.pyc 已支持 co_consts CODE 织入。",
});
/** Markdown theory pack returned by MCP resources/read (Chinese-friendly). */
diff --git a/tests/python-pyc-weave.test.ts b/tests/python-pyc-weave.test.ts
new file mode 100644
index 0000000..3c53ae5
--- /dev/null
+++ b/tests/python-pyc-weave.test.ts
@@ -0,0 +1,189 @@
+import { describe, expect, it } from "vitest";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, readFileSync, writeFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import {
+ inspectPythonPyc,
+ protectPythonPycBuffer,
+} from "../src/shields/formats/python.js";
+import {
+ layoutForPycMagic,
+ weavePythonPycBuffer,
+} from "../src/shields/formats/python-pyc-weave.js";
+import { buildWeavePlan } from "../src/shields/weave/weave-decoy.js";
+
+function compileSamplePyc(): Buffer {
+ const dir = mkdtempSync(join(tmpdir(), "bla-pyc-weave-"));
+ try {
+ const srcPath = join(dir, "sample.py");
+ const pycPath = join(dir, "sample.pyc");
+ writeFileSync(
+ srcPath,
+ [
+ "def calculate(x, y):",
+ " return x + y",
+ "",
+ "def convert(v):",
+ " return str(v)",
+ "",
+ "def stats(xs):",
+ " return sum(xs) / max(len(xs), 1)",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+ execFileSync(
+ "python3",
+ ["-c", `import py_compile; py_compile.compile(${JSON.stringify(srcPath)}, cfile=${JSON.stringify(pycPath)}, doraise=True)`],
+ { stdio: "pipe" },
+ );
+ return readFileSync(pycPath);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+function importAndCall(pyc: Buffer): { calculate: number; convert: string; stats: number } {
+ const dir = mkdtempSync(join(tmpdir(), "bla-pyc-run-"));
+ try {
+ const pycPath = join(dir, "sample.pyc");
+ writeFileSync(pycPath, pyc);
+ const script = `
+import importlib.util, sys
+spec = importlib.util.spec_from_file_location("sample", ${JSON.stringify(pycPath)})
+mod = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(mod)
+print(mod.calculate(2, 3))
+print(mod.convert(7))
+print(mod.stats([1, 2, 3, 4]))
+`;
+ const out = execFileSync("python3", ["-c", script], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ const lines = out.trim().split(/\r?\n/);
+ return {
+ calculate: Number(lines[0]),
+ convert: lines[1]!,
+ stats: Number(lines[2]),
+ };
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+function countCodeObjects(pyc: Buffer): number {
+ // latin1 scan for TYPE_CODE bytes is noisy; use a marshal walk via python.
+ const dir = mkdtempSync(join(tmpdir(), "bla-pyc-count-"));
+ try {
+ const pycPath = join(dir, "sample.pyc");
+ writeFileSync(pycPath, pyc);
+ const script = `
+import marshal, types, sys
+raw = open(${JSON.stringify(pycPath)}, "rb").read()
+code = marshal.loads(raw[16:])
+stack = [code]
+n = 0
+while stack:
+ c = stack.pop()
+ if isinstance(c, types.CodeType):
+ n += 1
+ stack.extend(x for x in c.co_consts if isinstance(x, types.CodeType))
+print(n)
+`;
+ return Number(
+ execFileSync("python3", ["-c", script], { encoding: "utf8" }).trim(),
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+describe("python-pyc-weave", () => {
+ it("maps current CPython magic to a known layout", () => {
+ const pyc = compileSamplePyc();
+ const magic = pyc.readUInt16LE(0);
+ expect(layoutForPycMagic(magic)).toBe("py311");
+ });
+
+ it("weave_decoys:true injects decoy TYPE_CODE into customer co_consts without breaking import", () => {
+ const raw = compileSamplePyc();
+ const before = importAndCall(raw);
+ expect(before.calculate).toBe(5);
+ expect(before.convert).toBe("7");
+ expect(before.stats).toBeCloseTo(2.5);
+
+ const codesBefore = countCodeObjects(raw);
+ expect(codesBefore).toBe(4); // <module> + calculate + convert + stats
+
+ const woven = weavePythonPycBuffer(raw, {
+ intensity: "balanced",
+ seed: "pyc-weave-test",
+ });
+ expect(woven).not.toBeNull();
+ expect(woven!.customerDefsWoven).toBe(3);
+ expect(woven!.decoyCodeObjectsInjected).toBeGreaterThanOrEqual(9); // 3 customer + 6 module
+
+ const codesAfter = countCodeObjects(woven!.buffer);
+ expect(codesAfter).toBe(codesBefore + woven!.decoyCodeObjectsInjected);
+
+ const after = importAndCall(woven!.buffer);
+ expect(after).toEqual(before);
+
+ // Header preserved
+ expect(woven!.buffer.subarray(0, 16).equals(raw.subarray(0, 16))).toBe(true);
+ });
+
+ it("protectPythonPycBuffer weaveDecoys:false stays trailer-only (no co_consts CODE growth)", () => {
+ const raw = compileSamplePyc();
+ const before = countCodeObjects(raw);
+ const res = protectPythonPycBuffer(raw, {
+ intensity: "balanced",
+ seed: "pyc-trailer",
+ weaveDecoys: false,
+ });
+ expect(res.weaveDecoys).toBe(false);
+ expect(res.decoyCodeObjectsInjected).toBe(0);
+ expect(res.customerDefsWoven).toBe(0);
+ expect(countCodeObjects(res.buffer)).toBe(before);
+ expect(res.buffer.length).toBeGreaterThan(raw.length);
+ expect(inspectPythonPyc(res.buffer).blaProtected).toBe(true);
+ expect(importAndCall(res.buffer).calculate).toBe(5);
+ });
+
+ it("protectPythonPycBuffer weaveDecoys:true weaves CODE + trailers", () => {
+ const raw = compileSamplePyc();
+ const before = countCodeObjects(raw);
+ const res = protectPythonPycBuffer(raw, {
+ intensity: "balanced",
+ seed: "pyc-full",
+ weaveDecoys: true,
+ });
+ expect(res.weaveDecoys).toBe(true);
+ expect(res.customerDefsWoven).toBe(3);
+ expect(res.decoyCodeObjectsInjected).toBeGreaterThanOrEqual(9);
+ expect(countCodeObjects(res.buffer)).toBe(before + res.decoyCodeObjectsInjected);
+ expect(res.buffer.toString("latin1")).toContain("PROTECTED_CANARY_CREDENTIAL=");
+ expect(inspectPythonPyc(res.buffer).blaProtected).toBe(true);
+ expect(importAndCall(res.buffer)).toEqual({
+ calculate: 5,
+ convert: "7",
+ stats: 2.5,
+ });
+ });
+
+ it("weave planner marks python-pyc as woven", () => {
+ const dir = mkdtempSync(join(tmpdir(), "bla-pyc-plan-"));
+ try {
+ const pycPath = join(dir, "app.pyc");
+ writeFileSync(pycPath, compileSamplePyc());
+ const plan = buildWeavePlan(dir);
+ const file = plan.targets.find((t) => t.relativePath.endsWith("app.pyc"));
+ expect(file?.maturity).toBe("woven");
+ expect(file?.status).toBe("ready");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});