lasik-agents 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,18 +5,22 @@
5
5
  </p>
6
6
 
7
7
  <p align="center">
8
- Read code that was built to hide from AI.<br />
9
- LASIK removes <a href="https://github.com/qybaihe/bla">BLA</a> anti-agent hardening so coding agents and <a href="https://github.com/morluto/rea">REA</a> can analyse the real program.
8
+ Static deobfuscation for anti-agent hardening.<br />
9
+ LASIK removes <a href="https://github.com/qybaihe/bla">BLA</a> protection layers so coding agents and analysis tools can read the real program.
10
10
  </p>
11
11
 
12
12
  <p align="center">
13
- <a href="https://github.com/pktq/lasik/actions/workflows/ci.yml"><img src="https://github.com/pktq/lasik/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
14
- <a href="LICENSE"><img src="https://img.shields.io/github/license/pktq/lasik?color=blue" alt="MIT license" /></a>
15
- <img src="https://img.shields.io/badge/node-%E2%89%A520.19-339933" alt="Node 20.19+" />
13
+ <a href="https://www.npmjs.com/package/lasik-agents"><img src="https://img.shields.io/npm/v/lasik-agents?style=for-the-badge&label=npm&color=22d3ee" alt="npm version" /></a>
14
+ <a href="https://github.com/pktq/lasik/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/pktq/lasik/ci.yml?branch=main&style=for-the-badge&label=CI" alt="CI" /></a>
15
+ <a href="docs/coverage.md"><img src="https://img.shields.io/badge/BLA_3.2.2-59%2F63_shields_healed-22d3ee?style=for-the-badge" alt="BLA coverage" /></a>
16
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-64748b?style=for-the-badge" alt="MIT license" /></a>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <b>0.3:</b> structural detection. Protection is identified by what it does, not by its names, so renamed builds heal too. <a href="#resilience">Benchmark</a>
16
21
  </p>
17
22
 
18
23
  <p align="center">
19
- <a href="https://lasik.dev">Website</a> ·
20
24
  <a href="docs/how-it-works.md">How it works</a> ·
21
25
  <a href="docs/benchmark.md">Benchmark</a> ·
22
26
  <a href="CHANGELOG.md">Changelog</a>
@@ -25,23 +29,23 @@
25
29
  <br />
26
30
 
27
31
  <p align="center">
28
- <img src="docs/assets/before-after.svg" alt="The same two functions from BLA's CrackMe v6, hardened and after LASIK" width="100%" />
32
+ <img src="docs/assets/before-after.svg" alt="The same two functions from a protected build, before and after LASIK" width="100%" />
29
33
  </p>
30
34
 
31
- BLA protects a release from AI agents by burying it: thousands of opaque predicates, encrypted strings, decoy "hardware enclave" code, checks that break the program if decoys are removed, multi-megabyte padding, and text written to make the model give up. LASIK takes all of that back out, statically, and hands your agent the program that is actually there.
35
+ LASIK reads a protected build, proves which parts are protection (opaque predicates, encrypted strings, decoy code, tamper checks, binary padding, prompt-injection text), removes them, and writes a clean copy. It never runs the input.
32
36
 
33
- <p align="center"><img src="docs/assets/flow.svg" alt="A BLA-hardened release goes through lasik heal, then an agent or REA reads the real logic" width="100%" /></p>
37
+ <p align="center"><img src="docs/assets/flow.svg" alt="A protected release goes through lasik heal, then an agent or analysis tool reads the real logic" width="100%" /></p>
34
38
 
35
39
  ## Highlights
36
40
 
37
- - **1,262× fewer tokens** to read BLA's own CrackMe corpus: about 21 million down to 17 thousand.
38
- - **Proven, not guessed.** Predicates are folded only when LASIK can prove their value; anti-strip checks are recomputed before any decoy is touched; files without BLA keep their code unchanged.
39
- - **Never runs the target.** No `eval`, no sandbox, no WebAssembly instantiation, so it is safe on hostile input, including malware that adopts BLA.
40
- - **A prompt firewall** that strips the text BLA plants for the model: fake system turns, refusal bait, "nothing to see here" notices.
41
- - **Every format BLA ships**, checked against real BLA 3.2.1 output: JavaScript and TypeScript bundles, inline HTML, WebAssembly, Electron ASAR and fuses, source maps, Python and `.pyc`, native ELF/PE/Mach-O, Bun, SQLite, safetensors and GGUF, PCAP, JVM, .NET, BEAM, EVM, PTX, ZIP/APK/DEX, plists, IL2CPP and UF2 firmware.
42
- - **Names back where the program publishes them**: a function BLA renamed to `primeSparseStack_719` but exports as `clampPan` is `clampPan` again; other BLA names become neutral `p0`, `v0` instead of misleading ones.
43
- - **Keeps up with BLA**: every BLA source file is hashed in [coverage/bla.json](coverage/bla.json), and a weekly job opens an issue the moment BLA changes.
44
- - **Built for agents**: a CLI, an MCP server for Claude Code, Cursor, Codex and seven more, and a library API.
41
+ - **1,262× fewer tokens** on the public BLA CrackMe corpus: about 21 million down to 17 thousand.
42
+ - **Proof-based.** A transform runs only when LASIK can prove it preserves behaviour. Unprotected files come back byte-identical.
43
+ - **Structural detection.** Protection is recognised by behaviour, not identifiers; a renamed-build benchmark runs in CI.
44
+ - **Static only.** No `eval`, no sandbox, no WebAssembly instantiation; safe on hostile input.
45
+ - **Prompt-injection firewall** for text planted to steer the model.
46
+ - **21 formats**: JavaScript and TypeScript bundles, inline HTML, WebAssembly, Electron ASAR and fuses, source maps, Python and `.pyc`, native ELF/PE/Mach-O, Bun, SQLite, safetensors and GGUF, PCAP, JVM, .NET, BEAM, EVM, PTX, ZIP/APK/DEX, plists, IL2CPP and UF2 firmware.
47
+ - **Name recovery** where the program still publishes the original name (exports, imports); neutral names elsewhere.
48
+ - **Agent integration**: CLI, MCP server for Claude Code, Cursor, Codex and seven more, and a library API.
45
49
 
46
50
  ## Installation
47
51
 
@@ -53,7 +57,7 @@ Requires Node.js 20.19 or later. To build from source: `git clone https://github
53
57
 
54
58
  ## Usage
55
59
 
56
- Scan a build to see what BLA did to it, then write a cleaned copy:
60
+ Scan a build, then write a cleaned copy:
57
61
 
58
62
  ```console
59
63
  $ lasik scan bench/bla-crackme
@@ -64,13 +68,13 @@ Sight restored: 1.8 MB → 37.5 KB, ~21,104,859 → ~16,718 tokens
64
68
  $ lasik heal ./dist # writes a cleaned copy to ./dist.lasik
65
69
  ```
66
70
 
67
- Point your agent, or REA, at the healed copy:
71
+ Point your agent or analysis tool at the healed copy, for example [REA](https://github.com/morluto/rea):
68
72
 
69
73
  ```bash
70
74
  npx -y rea-agents@latest analyze-javascript-application "$PWD/dist.lasik" --json
71
75
  ```
72
76
 
73
- Other commands: `lasik firewall` (redact prompt decoys from any text), `lasik bench`, `lasik doctor`. Add `--json` or `--md` for machine-readable reports and `--fail-on blinded` to gate CI.
77
+ Other commands: `lasik firewall` (redact planted instructions from any text), `lasik bench`, `lasik doctor`. Add `--json` or `--md` for machine-readable reports and `--fail-on blinded` to gate CI.
74
78
 
75
79
  ### In your coding agent
76
80
 
@@ -80,16 +84,16 @@ lasik setup # registers the MCP server; --dry-run to preview
80
84
 
81
85
  | Tool | |
82
86
  |---|---|
83
- | `lasik_scan` | Which BLA layers a file or folder carries, a 0–100 blindness score and the AI-evasion techniques found |
84
- | `lasik_read` | One file with BLA removed, for the agent to read instead of the original |
85
- | `lasik_heal` | A cleaned copy of a whole app, ready for REA |
87
+ | `lasik_scan` | Protection layers in a file or folder, a 0–100 blindness score and the techniques found |
88
+ | `lasik_read` | One file with protection removed, for the agent to read instead of the original |
89
+ | `lasik_heal` | A cleaned copy of a whole app |
86
90
  | `lasik_firewall` | Planted instructions redacted from any text |
87
91
 
88
- The repository also ships an [agent skill](.agents/skills/lasik/SKILL.md) that teaches an agent to recognise BLA and reach for these tools.
92
+ The repository also ships an [agent skill](.agents/skills/lasik/SKILL.md) for agents that encounter protected builds.
89
93
 
90
94
  ## Benchmark
91
95
 
92
- Measured on the CrackMes BLA's maintainers published as challenges, vendored unchanged in [`bench/bla-crackme`](bench/bla-crackme):
96
+ The public BLA CrackMes, vendored unchanged in [`bench/bla-crackme`](bench/bla-crackme):
93
97
 
94
98
  | CrackMe | Files | Before | After | Tokens (estimated) |
95
99
  |---|---:|---:|---:|---|
@@ -98,32 +102,54 @@ Measured on the CrackMes BLA's maintainers published as challenges, vendored unc
98
102
  | v8 | 3 | 362 KB | 6.7 KB | 6,972,491 → 4,748 |
99
103
  | v9 | 4 | 381 KB | 7.4 KB | 6,977,670 → 4,941 |
100
104
 
101
- <p align="center"><img src="docs/assets/tokens.svg" alt="Log-scale bar chart: estimated tokens per BLA CrackMe artifact before and after LASIK" width="100%" /></p>
105
+ <p align="center"><img src="docs/assets/tokens.svg" alt="Log-scale bar chart: estimated tokens per CrackMe artifact before and after LASIK" width="100%" /></p>
106
+
107
+ <!-- realbench:start -->
108
+ On a project we hardened ourselves with the published `bla-agents@3.2.1`, one file per format ([details](docs/benchmark.md#your-own-code-hardened-by-real-bla-321)):
109
+
110
+ | BLA run | Files | Original | BLA-hardened | After LASIK | Tokens (estimated) | Result |
111
+ |---|---:|---:|---:|---:|---|---|
112
+ | Defaults | 21 | 151.9 KB | 31.1 MB | 150.9 KB | 32,154,076 → 152,102 | 21/21 healed, 11 byte-identical |
113
+ | All opt-in layers | 21 | 151.9 KB | 31.2 MB | 151.0 KB | 32,178,121 → 152,197 | 21/21 healed, 10 byte-identical |
114
+ <!-- realbench:end -->
102
115
 
103
116
  Per-file numbers, the method and its caveats are in [docs/benchmark.md](docs/benchmark.md). LASIK makes the CrackMes readable; it does not publish their solutions.
104
117
 
118
+ ### Resilience
119
+
120
+ `npm run bench:renamed` heals the same builds twice: as shipped, and with every generated identifier, comment, WASM section, long export name and ASAR path respelled and commutative operands reordered, with behaviour unchanged. Because detection is structural, both heal to nearly the same result. CI fails if the respelled run removes more than one point less.
121
+
122
+ <p align="center"><img src="docs/assets/renamed.svg" alt="Left: examples of what the benchmark respells. Right: tokens left per format; respelled builds heal to nearly the same size as the originals" width="100%" /></p>
123
+
124
+ | Format | As shipped: removed | Respelled: removed |
125
+ |---|---:|---:|
126
+ | JavaScript / TypeScript | 98.78% | 98.09% |
127
+ | HTML | 99.29% | 99.17% |
128
+ | WebAssembly | 99.98% | 99.98% |
129
+ | Electron ASAR | 99.998% | 99.96% |
130
+
105
131
  ## How it works
106
132
 
107
133
  <p align="center"><img src="docs/assets/pipeline.svg" alt="LASIK pass order: detect, cut interlocks, strip decoys, fold to a fixpoint, rename, firewall, report" width="100%" /></p>
108
134
 
109
- | BLA layer | What LASIK does |
135
+ | Layer | What LASIK does |
110
136
  |---|---|
111
- | Opaque predicates | Matches BLA's number-theoretic identities and proves seed-dependent ones with a known-bits analysis, then drops the dead branches |
112
- | Anti-strip interlocks | Recomputes the decoy-corpus digest and folds the check before removing anything |
113
- | Encrypted and split literals | Decodes XOR string tables with the key shipped beside them; re-joins split strings and integers |
114
- | Decoys | Removes everything unreachable from real entry points, backed by a catalog of BLA's decoy families |
115
- | Self-seals and locks | Removes BLA's own tamper and domain checks, and reports the lock's terms |
116
- | Runtime noise | Drops shadow-heap churn and fake enclave status blocks that nothing reads |
117
- | Renamed identifiers | Restores names the program exports or imports a binding under; neutral names for the rest |
118
- | Padding and planted data | Strips BLA's sections, trailers, honey tables, decoy entries and floods from binaries, databases, models and archives, and rebuilds offsets and checksums so the file stays valid |
119
- | Prompt bait | Redacts it with 40 firewall rules |
120
-
121
- The full pass order, the proofs and every fingerprint are in [docs/how-it-works.md](docs/how-it-works.md). An independent review hunted for inputs where healing changes what a program does; every case it found is fixed and pinned in [`tests/soundness.test.ts`](tests/soundness.test.ts).
137
+ | Opaque predicates | Proves constant conditions with a known-bits analysis and drops the dead branches |
138
+ | Anti-strip interlocks | Evaluates the check on a closed-subset interpreter and folds it before anything is removed |
139
+ | Encrypted and split literals | Decodes string tables with the key shipped beside them; re-joins split strings and integers |
140
+ | Decoys | Removes everything unreachable from real entry points |
141
+ | Tamper and domain locks | Removes them and reports the lock's terms |
142
+ | Runtime noise | Drops state churn and status blocks that nothing reads |
143
+ | Renamed identifiers | Restores names the program exports or imports; neutral names for the rest |
144
+ | Padding and planted data | Strips padding, trailers and planted entries from binaries, databases, models and archives, and rebuilds offsets and checksums |
145
+ | Planted instructions | Redacts them with 40 firewall rules |
146
+
147
+ Details are in [docs/how-it-works.md](docs/how-it-works.md). Two independent soundness reviews searched for inputs where healing changes behaviour or touches an unprotected file; every case found is fixed and pinned in [`tests/soundness.test.ts`](tests/soundness.test.ts).
122
148
 
123
149
  ## Format coverage
124
150
 
125
151
  <!-- coverage:start -->
126
- Pinned to BLA **3.2.1**. 59/63 BLA shield files fully healed; 44 more emit nothing into artifacts. Full per-file table: [docs/coverage.md](docs/coverage.md).
152
+ Pinned to BLA **3.2.2**. 59/63 BLA shield files fully healed; 44 more emit nothing into artifacts. Full per-file table: [docs/coverage.md](docs/coverage.md).
127
153
 
128
154
  | Surface | Status |
129
155
  |---|---|
@@ -154,9 +180,9 @@ Pinned to BLA **3.2.1**. 59/63 BLA shield files fully healed; 44 more emit nothi
154
180
 
155
181
  ## Limitations
156
182
 
157
- - Local names, comments, source maps and the few sections BLA overwrote (a Go `.go.buildinfo`, renamed WASM exports) cannot be recovered. LASIK says so rather than inventing them.
158
- - Format healers recognise BLA 3.2.1's output precisely. They are checked on real BLA output for 21 formats ([tests/fixtures/bla-3.2.1](tests/fixtures/bla-3.2.1)); Go, Flutter, Bun, BEAM, APK/DEX and IL2CPP so far only on fixtures built from BLA's source.
159
- - When BLA changes, a healer can stop matching until it is updated. The weekly drift check names the file to revisit; the JavaScript core works by proof and does not depend on BLA's names.
183
+ - Information the protection destroyed (local names, comments, original source maps, overwritten sections) cannot be recovered; LASIK reports it rather than inventing it.
184
+ - Healers are validated on real BLA 3.2.1 output for 21 formats ([tests/fixtures/bla-3.2.1](tests/fixtures/bla-3.2.1)); Go, Flutter, Bun, BEAM, APK/DEX and IL2CPP so far on fixtures built from BLA's source.
185
+ - New protection techniques can need an update. Upstream changes are tracked weekly ([coverage/bla.json](coverage/bla.json)), and builds protected with earlier versions stay supported.
160
186
 
161
187
  ## Responsible use
162
188
 
@@ -164,7 +190,7 @@ LASIK is a deobfuscator. Use it on your own software, on malware and threat samp
164
190
 
165
191
  ## Contributing
166
192
 
167
- Bug reports with a sample (or `lasik scan --json` output) are the most useful contribution, especially for new BLA versions. See [CONTRIBUTING](.github/CONTRIBUTING.md).
193
+ Bug reports with a sample (or `lasik scan --json` output) are the most useful contribution. See [CONTRIBUTING](.github/CONTRIBUTING.md).
168
194
 
169
195
  Also available in [简体中文](docs/readme/README.zh-CN.md) · [日本語](docs/readme/README.ja.md) · [한국어](docs/readme/README.ko.md) · [Español](docs/readme/README.es.md).
170
196
 
@@ -1,15 +1,24 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Findings } from "../core/types.js";
3
- import { healJs } from "../js/heal.js";
3
+ import { healJs, isHardened } from "../js/heal.js";
4
4
  import { isHoneySourceMap } from "../js/passes/comments.js";
5
5
  import { healSourceMap } from "./sourcemap.js";
6
6
  /** REA refuses asar headers above this (DEFAULT_ASAR_MAX_HEADER_BYTES). */
7
7
  const REA_MAX_HEADER = 16 * 1024 * 1024;
8
8
  const DEFAULT_BLOCK = 4 * 1024 * 1024;
9
+ /** Unreachable entries in one directory needed to call it a header flood. */
10
+ const FLOOD = 64;
11
+ /**
12
+ * Live code that names files at runtime could reach any entry: `require(x)`, `import(x)`,
13
+ * directory listings, or a file API whose path is not a plain string literal.
14
+ */
15
+ const DYNAMIC_FILE_ACCESS = /\b(?:require|import)\s*\(\s*[^'"`\s)]|readdir|opendir|\bglob(?:Sync)?\s*\(|\b(?:readFileSync|readFile|createReadStream|openSync|open|loadFile|loadURL|statSync|existsSync|accessSync)\s*\(\s*(?!["'][^"'\n]*["']\s*[,)])/;
9
16
  const INLINE_MAP = /^[ \t]*\/\/[#@][ \t]*sourceMappingURL=data:application\/json[^,\n]*;base64,([A-Za-z0-9+/=]+)[ \t]*\r?\n?/gm;
10
17
  function isDecoyPath(path) {
11
18
  return path === "enclave/hardware-tee-bridge.js" || /^enclave\/shards\/ring0-slot-[^/]*$/.test(path);
12
19
  }
20
+ /** BLA ≥ 3.2.2 opt-in sidecar entanglement: an in-archive digest note binding the decoy bridge (sidecar-entangle.ts). */
21
+ const SIDECAR_NOTE = ".bla/sidecar.v1.json";
13
22
  function integrity(content, blockSize) {
14
23
  const sha = (b) => createHash("sha256").update(b).digest("hex");
15
24
  const blocks = [];
@@ -57,9 +66,98 @@ export const healAsar = (input, file, opts) => {
57
66
  warnings.push("asar header is not valid JSON; left unchanged");
58
67
  return unchanged();
59
68
  }
69
+ const contentOf = (node, path) => {
70
+ const start = dataBase + Number(node.offset);
71
+ const size = node.size ?? 0;
72
+ if (!Number.isSafeInteger(start) || start + size > input.length)
73
+ throw new Error(`entry out of bounds: ${path}`);
74
+ return input.subarray(start, start + size);
75
+ };
76
+ const healCache = new Map();
77
+ const healedJs = (path, content) => {
78
+ let r = healCache.get(path);
79
+ if (!r)
80
+ healCache.set(path, (r = healJs(content.toString("utf8"), { filename: path, aggressive: opts.aggressive })));
81
+ return r;
82
+ };
83
+ /**
84
+ * Flood entries nothing left in a proven-hardened archive can reach. Roots are package.json, its
85
+ * `main`, and every top-level file; a reached text reaches each entry whose file name, stem or
86
+ * directory it mentions. Code that names files at runtime (`require(x)`, `import(x)`,
87
+ * `readdir`) could reach anything, so then nothing is dropped.
88
+ */
89
+ const unreachableEntries = (files) => {
90
+ const entries = [];
91
+ const list = (dir, prefix) => {
92
+ for (const [name, node] of Object.entries(dir)) {
93
+ if (node.files)
94
+ list(node.files, `${prefix + name}/`);
95
+ else if (node.link === undefined && node.unpacked !== true && !isDecoyPath(prefix + name) && prefix + name !== SIDECAR_NOTE)
96
+ entries.push({ path: prefix + name, node });
97
+ }
98
+ };
99
+ list(files, "");
100
+ let hardened = false;
101
+ const text = new Map();
102
+ for (const { path, node } of entries) {
103
+ if (/\.[cm]?js$/.test(path)) {
104
+ const r = healedJs(path, contentOf(node, path));
105
+ hardened ||= isHardened(r.findings);
106
+ text.set(path, r.code);
107
+ }
108
+ else {
109
+ // Any entry can name another (a YAML config, a binary index): scan every byte.
110
+ text.set(path, contentOf(node, path).toString("latin1"));
111
+ }
112
+ }
113
+ if (!hardened)
114
+ return new Set();
115
+ const main = (() => {
116
+ try {
117
+ const m = JSON.parse(text.get("package.json") ?? "{}").main;
118
+ return typeof m === "string" ? m.replace(/^\.\//, "") : undefined;
119
+ }
120
+ catch {
121
+ return undefined;
122
+ }
123
+ })();
124
+ const reached = new Set(entries.filter((e) => !e.path.includes("/") || e.path === main || e.path === `${main}.js`).map((e) => e.path));
125
+ const queue = [...reached];
126
+ while (queue.length) {
127
+ const path = queue.pop();
128
+ const t = text.get(path);
129
+ if (t === undefined)
130
+ continue;
131
+ if (/\.[cm]?js$/.test(path) && DYNAMIC_FILE_ACCESS.test(t))
132
+ return new Set();
133
+ for (const e of entries) {
134
+ if (reached.has(e.path))
135
+ continue;
136
+ const parts = e.path.split("/");
137
+ const file = parts[parts.length - 1];
138
+ const names = [file, file.replace(/\.[^.]+$/, ""), ...parts.slice(0, -1)];
139
+ if (names.some((n) => n && t.includes(n))) {
140
+ reached.add(e.path);
141
+ queue.push(e.path);
142
+ }
143
+ }
144
+ }
145
+ // Only floods: a lone unreachable file may still be worth reading, thousands of them never are.
146
+ const byDir = new Map();
147
+ for (const e of entries) {
148
+ if (reached.has(e.path))
149
+ continue;
150
+ const dir = e.path.slice(0, e.path.lastIndexOf("/") + 1);
151
+ byDir.set(dir, [...(byDir.get(dir) ?? []), e.path]);
152
+ }
153
+ return new Set([...byDir.values()].filter((paths) => paths.length >= FLOOD).flat());
154
+ };
155
+ let unreachable = new Set();
156
+ let unreachableDropped = 0;
60
157
  const chunks = [];
61
158
  let offset = 0;
62
159
  let decoys = 0;
160
+ let sidecarNotes = 0;
63
161
  let inlineMaps = 0;
64
162
  let honeyMaps = 0;
65
163
  let jsHealed = 0;
@@ -80,16 +178,22 @@ export const healAsar = (input, file, opts) => {
80
178
  delete dir[name];
81
179
  continue;
82
180
  }
83
- const start = dataBase + Number(node.offset);
84
- const size = node.size ?? 0;
85
- if (!Number.isSafeInteger(start) || start + size > input.length)
86
- throw new Error(`entry out of bounds: ${path}`);
87
- let content = input.subarray(start, start + size);
181
+ if (path === SIDECAR_NOTE) {
182
+ sidecarNotes++;
183
+ delete dir[name];
184
+ continue;
185
+ }
186
+ if (unreachable.has(path)) {
187
+ unreachableDropped++;
188
+ delete dir[name];
189
+ continue;
190
+ }
191
+ let content = contentOf(node, path);
88
192
  let rewritten = false;
89
193
  if (/\.[cm]?js$/.test(name)) {
90
194
  // BLA runs its full JS shield over every .js entry (protector.ts electron-asar branch).
91
195
  try {
92
- const r = healJs(content.toString("utf8"), { filename: path, aggressive: opts.aggressive });
196
+ const r = healedJs(path, content);
93
197
  if (r.changed) {
94
198
  content = Buffer.from(r.code, "utf8");
95
199
  for (const f of r.findings.list())
@@ -132,13 +236,14 @@ export const healAsar = (input, file, opts) => {
132
236
  if (!root.files)
133
237
  return unchanged();
134
238
  try {
239
+ unreachable = unreachableEntries(root.files);
135
240
  walk(root.files, "");
136
241
  }
137
242
  catch (err) {
138
243
  warnings.push(`asar parse failed (${err.message}); left unchanged`);
139
244
  return unchanged();
140
245
  }
141
- if (decoys + inlineMaps + honeyMaps + jsHealed === 0)
246
+ if (decoys + sidecarNotes + unreachableDropped + inlineMaps + honeyMaps + jsHealed === 0)
142
247
  return unchanged();
143
248
  const json = Buffer.from(JSON.stringify(root), "utf8");
144
249
  const aligned = Math.ceil(json.length / 4) * 4;
@@ -148,9 +253,15 @@ export const healAsar = (input, file, opts) => {
148
253
  header.writeUInt32LE(aligned + 4, 8);
149
254
  header.writeUInt32LE(json.length, 12);
150
255
  json.copy(header, 16);
256
+ if (sidecarNotes) {
257
+ findings.add("entangle", "asar-sidecar-note", `removed BLA sidecar entanglement note ${SIDECAR_NOTE}`, sidecarNotes);
258
+ warnings.push(`removed ${SIDECAR_NOTE}; BLA host-side verifyAsarSidecarArchiveNote will no longer pass on this archive (intended)`);
259
+ }
151
260
  if (decoys) {
152
261
  findings.add("exhaust", "asar-header-flood", "removed decoy enclave shard entries flooding the ASAR header", decoys);
153
262
  }
263
+ if (unreachableDropped)
264
+ findings.add("exhaust", "asar-unreachable-entry", "removed entries nothing left in the hardened archive can reach", unreachableDropped);
154
265
  if (inlineMaps)
155
266
  findings.add("deceive", "honey-sourcemap", "removed inline honey source maps from .js entries", inlineMaps);
156
267
  if (honeyMaps) {
@@ -7,6 +7,15 @@ const BLA_CUSTOM = /^(?:bla\.|enclave\.attestation\.\d+$)/;
7
7
  const DECOY_EXPORT = /^(?:enclave_export_[0-9a-f]+_\d+_|bla_enclave_verify_zero_trust_merkle_slot_)/;
8
8
  /** Markers of BLA's honey `name` section (decoy module name / symbol names). */
9
9
  const HONEY_NAME = /tee_hardware_enclave_transport_stub_|enclave_export_|bla_enclave_/;
10
+ /**
11
+ * Custom sections toolchains read (WebAssembly tool conventions, DWARF, Emscripten, wasm-bindgen).
12
+ * Anything else carries no meaning for execution.
13
+ */
14
+ const KNOWN_CUSTOM = /^(?:name|producers|target_features|linking|reloc\..+|sourceMappingURL|external_debug_info|dylink(?:\.0)?|metadata\.code\..+|build_id|\.debug_.+|emscripten_metadata|__wasm_bindgen_unstable|wasm-bindgen.*|go:.+|rustc.*)$/;
15
+ /** No toolchain emits export names this long; BLA's alias flood uses ~12 KB names to exhaust readers. */
16
+ const OVERSIZED_EXPORT = 1024;
17
+ /** Oversized aliases needed to call the export section a flood. */
18
+ const ALIAS_FLOOD = 16;
10
19
  /** v9 renames real exports to `ops_<hex>_...`; the originals are not recoverable. */
11
20
  const RENAMED_EXPORT = /^ops_[0-9a-f]+_/;
12
21
  function readU32(buf, pos) {
@@ -53,8 +62,9 @@ function parseExports(payload) {
53
62
  const { name, next } = readName(payload, pos);
54
63
  if (payload[next] === undefined)
55
64
  throw new Error("truncated export");
56
- pos = readU32(payload, next + 1).next; // kind byte, then index
57
- out.push({ name, raw: payload.subarray(start, pos) });
65
+ const index = readU32(payload, next + 1); // kind byte, then index
66
+ pos = index.next;
67
+ out.push({ name, target: `${payload[next]}:${index.value}`, raw: payload.subarray(start, pos) });
58
68
  }
59
69
  if (pos !== payload.length)
60
70
  throw new Error("export section size mismatch");
@@ -68,46 +78,76 @@ function healModule(input) {
68
78
  return unchanged();
69
79
  const parts = [input.subarray(0, 8)];
70
80
  const dropped = new Map();
81
+ const unknownDropped = [];
71
82
  let decoyExports = 0;
83
+ let oversizedExports = 0;
72
84
  let realExports;
73
85
  try {
74
- let pos = 8;
75
- while (pos < input.length) {
86
+ const sections = [];
87
+ for (let pos = 8; pos < input.length;) {
76
88
  const id = input[pos];
77
89
  const size = readU32(input, pos + 1);
78
90
  const end = size.next + size.value;
79
91
  if (end > input.length)
80
92
  throw new Error("section exceeds module size");
81
93
  const payload = input.subarray(size.next, end);
82
- const whole = input.subarray(pos, end);
83
- pos = end;
94
+ const s = { id, payload, whole: input.subarray(pos, end) };
84
95
  if (id === 0) {
85
96
  const { name, next } = readName(payload, 0);
86
- const honeyName = name === "name" && HONEY_NAME.test(payload.subarray(next).toString("latin1"));
97
+ s.name = name;
98
+ s.body = payload.subarray(next);
99
+ }
100
+ sections.push(s);
101
+ pos = end;
102
+ }
103
+ // Evidence that needs no BLA name: a flood of export aliases with absurdly long names. One
104
+ // long alias can be real (deeply templated C++); dozens exist only to exhaust a reader.
105
+ const exportSec = sections.find((s) => s.id === 7);
106
+ const exports = exportSec ? parseExports(exportSec.payload) : [];
107
+ const seen = new Set();
108
+ const oversized = new Set();
109
+ for (const e of [...exports].sort((a, b) => a.name.length - b.name.length)) {
110
+ if (seen.has(e.target) && Buffer.byteLength(e.name) > OVERSIZED_EXPORT)
111
+ oversized.add(e);
112
+ seen.add(e.target);
113
+ }
114
+ const blaMarked = exports.some((e) => DECOY_EXPORT.test(e.name)) || sections.some((s) => s.id === 0 && BLA_CUSTOM.test(s.name));
115
+ const padded = oversized.size >= ALIAS_FLOOD || blaMarked;
116
+ if (!padded)
117
+ oversized.clear();
118
+ for (const s of sections) {
119
+ if (s.id === 0) {
120
+ const name = s.name;
121
+ const honeyName = name === "name" && HONEY_NAME.test(s.body.toString("latin1"));
87
122
  if (BLA_CUSTOM.test(name) || honeyName) {
88
123
  const key = name.startsWith("enclave.attestation.") ? "enclave.attestation.*" : name;
89
124
  dropped.set(key, (dropped.get(key) ?? 0) + 1);
90
125
  continue;
91
126
  }
127
+ // Custom sections never change what the module does; in a padded module only known ones carry meaning.
128
+ if (padded && !KNOWN_CUSTOM.test(name)) {
129
+ unknownDropped.push(name);
130
+ continue;
131
+ }
92
132
  }
93
- else if (id === 7) {
94
- const exports = parseExports(payload);
95
- const kept = exports.filter((e) => !DECOY_EXPORT.test(e.name));
133
+ else if (s.id === 7) {
134
+ const kept = exports.filter((e) => !DECOY_EXPORT.test(e.name) && !oversized.has(e));
96
135
  realExports = kept.map((e) => e.name);
97
- decoyExports = exports.length - kept.length;
98
- if (decoyExports > 0) {
136
+ decoyExports = exports.filter((e) => DECOY_EXPORT.test(e.name)).length;
137
+ oversizedExports = exports.length - kept.length - decoyExports;
138
+ if (kept.length < exports.length) {
99
139
  parts.push(section(7, Buffer.concat([u32(kept.length), ...kept.map((e) => e.raw)])));
100
140
  continue;
101
141
  }
102
142
  }
103
- parts.push(whole);
143
+ parts.push(s.whole);
104
144
  }
105
145
  }
106
146
  catch (err) {
107
147
  warnings.push(`wasm parse failed (${err.message}); left unchanged`);
108
148
  return unchanged();
109
149
  }
110
- if (dropped.size === 0 && decoyExports === 0)
150
+ if (dropped.size === 0 && decoyExports === 0 && oversizedExports === 0 && unknownDropped.length === 0)
111
151
  return unchanged();
112
152
  const output = Buffer.concat(parts);
113
153
  if (!WebAssembly.validate(new Uint8Array(output))) {
@@ -124,10 +164,16 @@ function healModule(input) {
124
164
  if (dropped.has("bla.sidecar.v1")) {
125
165
  warnings.push("removed the bla.sidecar.v1 binding note; BLA's host-side sidecar verify will no longer pass on this module (intended)");
126
166
  }
127
- if (decoyExports > 0) {
167
+ if (unknownDropped.length) {
168
+ findings.add("exhaust", "wasm-unknown-custom", "removed non-tool custom sections from a module padded for readers (custom sections never affect execution)", unknownDropped.length);
169
+ warnings.push(`removed custom sections ${[...new Set(unknownDropped)].join(", ")}; JS that reads them through WebAssembly.Module.customSections() would see them gone`);
170
+ }
171
+ if (oversizedExports > 0)
172
+ findings.add("exhaust", "wasm-oversized-exports", `removed export aliases with names over ${OVERSIZED_EXPORT} bytes`, oversizedExports);
173
+ if (decoyExports > 0)
128
174
  findings.add("exhaust", "wasm-decoy-exports", "removed decoy WASM exports aliasing real functions", decoyExports);
175
+ if (decoyExports > 0 || oversizedExports > 0)
129
176
  warnings.push(`real exports: ${realExports?.join(", ") || "(none)"}`);
130
- }
131
177
  if (realExports?.some((n) => RENAMED_EXPORT.test(n))) {
132
178
  warnings.push("BLA renamed real exports to ops_<hex>_*; original export names are not recoverable (see the JS glue for how they are called)");
133
179
  }
@@ -1,6 +1,6 @@
1
1
  export declare const NAME = "LASIK";
2
2
  export declare const PACKAGE = "lasik-agents";
3
- export declare const VERSION = "0.2.0";
3
+ export declare const VERSION = "0.3.0";
4
4
  export declare const EXPANSION = "LLM Agent Sight In Kode";
5
5
  export declare const TAGLINE = "BLA blinds your agent. LASIK gives it its sight back.";
6
6
  export declare const REPO = "https://github.com/pktq/lasik";
package/dist/identity.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export const NAME = "LASIK";
2
2
  export const PACKAGE = "lasik-agents";
3
- export const VERSION = "0.2.0";
3
+ export const VERSION = "0.3.0";
4
4
  export const EXPANSION = "LLM Agent Sight In Kode";
5
5
  export const TAGLINE = "BLA blinds your agent. LASIK gives it its sight back.";
6
6
  export const REPO = "https://github.com/pktq/lasik";
package/dist/js/heal.d.ts CHANGED
@@ -1,4 +1,10 @@
1
1
  import { Findings } from "../core/types.js";
2
+ /**
3
+ * A file is treated as BLA-hardened (and gets the structural passes) only on this
4
+ * evidence. The last rule needs no BLA name or print shape: hand-written code almost
5
+ * never has even one branch that is provably constant, let alone dozens.
6
+ */
7
+ export declare function isHardened(f: Findings): boolean;
2
8
  export interface JsHealOptions {
3
9
  filename?: string;
4
10
  aggressive?: boolean;
@@ -8,6 +14,8 @@ export interface JsHealOptions {
8
14
  * its top-level names are closure locals nobody outside can reach.
9
15
  */
10
16
  closure?: boolean;
17
+ /** Inline script of a page without external scripts (see ShakeOptions.pageLocal). */
18
+ pageLocal?: boolean;
11
19
  /** Rename BLA-renamed module handles (default true). */
12
20
  rename?: boolean;
13
21
  /**
package/dist/js/heal.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Findings } from "../core/types.js";
2
2
  import { parseJs, printJs } from "./ast.js";
3
- import { stripScrambledComments } from "./passes/comments.js";
3
+ import { stripHardenedComments, stripScrambledComments } from "./passes/comments.js";
4
4
  import { firewallJs } from "./passes/firewall.js";
5
5
  import { eliminateDeadBranches } from "./passes/dead-code.js";
6
6
  import { cutCorpusInterlocks } from "./passes/interlock.js";
@@ -17,16 +17,25 @@ import { shakeUnreachable } from "./passes/tree-shake.js";
17
17
  const UNIQUE = new Set(["corpus-digest-interlock", "interlock-safety-corpus", "runtime-deception-block", "bind-scope", "honey-sourcemap"]);
18
18
  /** Proven BLA shapes that could, rarely, occur by coincidence: need several. */
19
19
  const REPEATED = new Set(["opaque-predicate", "fingerprinted-decoy"]);
20
- /** A file is treated as BLA-hardened (and gets the structural passes) only on this evidence. */
21
- function isHardened(f) {
20
+ /** Predicates proven constant by known-bits, whatever their printed shape. */
21
+ const PROVEN = new Set(["opaque-predicate", "seed-bit-predicate"]);
22
+ /**
23
+ * A file is treated as BLA-hardened (and gets the structural passes) only on this
24
+ * evidence. The last rule needs no BLA name or print shape: hand-written code almost
25
+ * never has even one branch that is provably constant, let alone dozens.
26
+ */
27
+ export function isHardened(f) {
22
28
  let repeated = 0;
29
+ let proven = 0;
23
30
  for (const x of f.list()) {
24
31
  if (UNIQUE.has(x.technique))
25
32
  return true;
26
33
  if (REPEATED.has(x.technique))
27
34
  repeated += x.count;
35
+ if (PROVEN.has(x.technique))
36
+ proven += x.count;
28
37
  }
29
- return repeated >= 3;
38
+ return repeated >= 3 || proven >= 16;
30
39
  }
31
40
  /** Run every JS pass to a fixpoint. Never executes the input. */
32
41
  export function healJs(code, opts = {}) {
@@ -38,7 +47,7 @@ export function healJs(code, opts = {}) {
38
47
  // Bundled BLA modules first, each as its own program; the outer file is judged on its own evidence.
39
48
  const inner = new Findings();
40
49
  const nested = healNestedModules(ast, opts.filename, (body) => {
41
- const r = healJs(body, { ...opts, closure: true, externalRoots: undefined });
50
+ const r = healJs(body, { ...opts, closure: true, externalRoots: undefined, pageLocal: undefined });
42
51
  for (const x of r.findings.list())
43
52
  inner.add(x.layer, x.technique, x.detail, x.count);
44
53
  warnings.push(...r.warnings.map((w) => `bundled module: ${w}`));
@@ -67,7 +76,7 @@ export function healJs(code, opts = {}) {
67
76
  round += stripPrivateStateSinks(ast, findings);
68
77
  round += decryptStrings(ast, findings);
69
78
  round += stripSelfSeal(ast, findings);
70
- round += shakeUnreachable(ast, findings, { externalRoots: opts.externalRoots, blaHardened: isHardened(findings), closure: opts.closure });
79
+ round += shakeUnreachable(ast, findings, { externalRoots: opts.externalRoots, blaHardened: isHardened(findings), closure: opts.closure, pageLocal: opts.pageLocal });
71
80
  changes += round;
72
81
  if (!round)
73
82
  break;
@@ -83,6 +92,7 @@ export function healJs(code, opts = {}) {
83
92
  const redacted = firewallJs(fresh, clean, { mode, hardened: false });
84
93
  return { code: redacted ? printJs(fresh) : code, findings: withInner(clean), warnings, changed: redacted > 0 || nested > 0 };
85
94
  }
95
+ changes += stripHardenedComments(ast, findings);
86
96
  if (opts.rename !== false)
87
97
  changes += renameRequireHandles(ast, findings);
88
98
  if (opts.rename !== false && hardened)