mirror of
https://github.com/qybaihe/bla.git
synced 2026-11-20 08:20:59 +08:00
feat(shield): harden runtime/AST/weave gates, MCP stdio framing, format shields & 5-layer CI red-team suite
This commit is contained in:
@@ -61,8 +61,8 @@ When hardening a repository with source code, follow this 4-stage closed loop so
|
||||
- Wire call edges from `entryFunctions` into the shadow helpers guarded by state-dependent opaque-true invariants at `branchCandidates`.
|
||||
- For C/C++, Rust, or Go targets, call `bla_emit_headers` and include the emitted header in native sources.
|
||||
4. **Verify Source Weave**:
|
||||
- Call **`bla_verify_weave`** `{ "path": "." }` (`bla-weave-verify/v1`).
|
||||
- If `overallPassed: false`, execute each item in `agentActions` (fixing any unreferenced helpers, missing shared-state mutations, or stem ratios) and re-run `bla_verify_weave` until `overallPassed: true`.
|
||||
- Call **`bla_verify_weave`** `{ "path": "." }` (`bla-weave-verify/v1`, 7 structural acceptance checks including `crown-jewel-entanglement`).
|
||||
- If `overallPassed: false`, execute each item in `agentActions` (fixing any unreferenced helpers, missing shared-state mutations, isolated boolean gates, or stem ratios) and re-run `bla_verify_weave` until `overallPassed: true`.
|
||||
|
||||
### Stage 3: Build & Post-Build Counter-REA Exhaustion Harden (`mcp-primary`)
|
||||
1. If the project has a build step (`npm run build`, `cargo build`, etc.), run it so compiled artifacts reflect your Stage 2 source surgery.
|
||||
@@ -110,6 +110,7 @@ Optional args (safe defaults): `intensity` (bankrupt), `emit_manifest` (false),
|
||||
| WASM XOR-mask beside masked pack | `bla_lint_wasm_xor_mask_sidecar` | `allow_wasm_xor_mask_sidecar` |
|
||||
| `seal.revision` as XOR known-plaintext | `bla_lint_wasm_seal_xor_known_plaintext` | `allow_wasm_seal_xor_known_plaintext` |
|
||||
| Cleartext sensitive literals (panel/license) | `bla_lint_plaintext_secrets` / `bla_encrypt_strings` | `allow_plaintext_string` |
|
||||
| Release hygiene leaks (SOLUTION/dotenv/keys/debug) | `bla_lint` | `allow_release_hygiene_leak` |
|
||||
|
||||
Prefer **one** project scan: MCP `bla_lint` / CLI `bla lint .` (schema `bla-packaging-gates/v1` with `remediationPlan`). Individual `bla_lint_*` remain for single-file drills. Bankrupt harden **refuses** the six carrier/JS/WASM gates unless the matching allow flag is set; lanes/panel also refuse at protect-time.
|
||||
|
||||
|
||||
@@ -31,7 +31,17 @@
|
||||
"category": "development",
|
||||
"skills": [
|
||||
"./.agents/skills/blind-llm-agents"
|
||||
]
|
||||
],
|
||||
"mcpServers": {
|
||||
"bla": {
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"-y",
|
||||
"bla-agents@3.3.2",
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "bla",
|
||||
"version": "3.3.2",
|
||||
"description": "Counter-REA Blue Defense plugin: teaches coding agents the BLA Agent-Driven Hardening playbook and registers the 31-tool BLA MCP server.",
|
||||
"author": {
|
||||
"name": "BLA Contributors",
|
||||
"url": "https://bla.tools"
|
||||
},
|
||||
"homepage": "https://bla.tools",
|
||||
"repository": "https://github.com/qybaihe/bla",
|
||||
"license": "MIT",
|
||||
"skills": [
|
||||
"../.agents/skills/blind-llm-agents"
|
||||
],
|
||||
"mcpServers": {
|
||||
"bla": {
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"-y",
|
||||
"bla-agents@3.3.2",
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,16 @@
|
||||
"skills": [
|
||||
"./.agents/skills/blind-llm-agents"
|
||||
],
|
||||
"mcpServers": {
|
||||
"bla": {
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"-y",
|
||||
"bla-agents@3.3.2",
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
},
|
||||
"interface": {
|
||||
"displayName": "BLA",
|
||||
"shortDescription": "Harden software against AI reverse-engineering agents with BLA",
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"bla": {
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"-y",
|
||||
"bla-agents@3.3.2",
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,7 @@
|
||||
|
||||
1. `resources/read` → `bla://directives/weave-decoy`(或读本文件)
|
||||
2. `bla_weave_plan` → `{ "path": "<project-or-artifact>" }`,读取返回的 JSON 工单及每个目标的 `surgicalWorkorder`(`entryFunctions`、`sharedStateSlots`、`branchCandidates`、`agentRewriteRecipe`)
|
||||
3. **Agent 源码级织入(Stage 2)**:按 `surgicalWorkorder` 在源码中编写共享同一运行时状态槽的领域诱饵函数并从真实入口调用,随后调用 **`bla_verify_weave`** 验证 6 项结构验收,确保 `overallPassed: true` 且 `agentActions` 清零
|
||||
3. **Agent 源码级织入(Stage 2)**:按 `surgicalWorkorder` 在源码中编写共享同一运行时状态槽的领域诱饵函数并从真实入口调用,随后调用 **`bla_verify_weave`** 验证 7 项结构验收,确保 `overallPassed: true` 且 `agentActions` 清零
|
||||
4. `bla_harden` / `bla_defend` / `bla_protect` 传 **`weave_decoys: true`**
|
||||
5. JS:验证现有 AST 织入,**不要**再堆 sidecar 噪声
|
||||
6. Python `.py`:确认客户 `def` 体内出现共享槽 touch / 诱饵 xref;**不要**用空 scare 模块填补
|
||||
@@ -64,7 +64,8 @@
|
||||
3. **共享状态变异** — 诱饵体与织入语句修改同一共享槽
|
||||
4. **客户入口边** — 静态 xref 从客户入口到达诱饵(JS;Python 在 `weave_decoys:true` 下经由客户 def 织入)
|
||||
5. **opaque 缠绕** — 删除守卫或诱饵调用会改变行为或验证结果
|
||||
6. **抗独立层过滤** — 不能仅凭空体 / 同质 scare / 未引用启发式整层丢弃
|
||||
6. **抗独立层过滤** — 不能仅凭空体 / 同质 scare / 未引用启发式整层丢弃
|
||||
7. **皇冠宝石状态纠缠(crown-jewel-entanglement)** — 鉴权/解锁等核心门控不得残留孤立布尔返回或零熵假织入(如 `expr & 0`、`x ^ x`),必须经由全输入累加器与共享状态槽纠缠
|
||||
|
||||
## 7. MCP 表面
|
||||
|
||||
@@ -72,7 +73,7 @@
|
||||
| :--- | :--- |
|
||||
| Resource `bla://directives/weave-decoy` | 返回本理论的可执行 Markdown |
|
||||
| Tool `bla_weave_plan` | 只读:分析路径 → `bla-weave-plan/v1` JSON(含 AST 级 `surgicalWorkorder`) |
|
||||
| Tool `bla_verify_weave` | 只读:校验源码/产物的 6 项织入验收 → `bla-weave-verify/v1` JSON(含 `weaveScore` 与 `agentActions`) |
|
||||
| Tool `bla_verify_weave` | 只读:校验源码/产物的 7 项织入验收 → `bla-weave-verify/v1` JSON(含 `weaveScore` 与 `agentActions`) |
|
||||
| `bla_harden` / `bla_defend` / `bla_protect` 参数 `weave_decoys` | **真实管线属性**:激活 Python 客户 def 结构织入(JS 始终 AST 织入);非仅报告布尔标注 |
|
||||
| `.blarc` / `bla.config.json` 字段 `weaveDecoys` | 与 CLI `--weave-decoys` / MCP `weave_decoys` 同义;CLI 读取后与旗标做 OR |
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ def reconcile_policy_epoch(delta):
|
||||
def evaluate_tenant_quota(seat_count, tier_weight):
|
||||
if _policy_ledger_state["epoch"] >= 1:
|
||||
reconcile_policy_epoch(seat_count)
|
||||
return (seat_count * tier_weight) + (_policy_ledger_state["cursor"] & 0)
|
||||
return (seat_count * tier_weight) ^ ((_policy_ledger_state["epoch"] & 1) ^ 1)
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -187,9 +187,14 @@ function loadSeal() {
|
||||
if (sha256(rawBytes) !== EXPECTED_SEAL_SHA256) {
|
||||
throw new Error("integrity check failed: seal.json digest mismatch");
|
||||
}
|
||||
const json = JSON.parse(rawBytes.toString("utf8"));
|
||||
let json;
|
||||
try {
|
||||
json = JSON.parse(rawBytes.toString("utf8"));
|
||||
} catch (_parseErr) {
|
||||
throw new Error("integrity check failed: seal.json malformed");
|
||||
}
|
||||
if (String(json.algorithm || "").toLowerCase().replace(/-/g, "") !== "sha256") {
|
||||
throw new Error("seal.json must declare algorithm sha256 (one-way)");
|
||||
throw new Error("integrity check failed: seal.json must declare algorithm sha256 (one-way)");
|
||||
}
|
||||
if ((sessionLedgerState.epoch & 1) !== 0) {
|
||||
reconcileSessionQuota(rawBytes.length & 0xff);
|
||||
@@ -281,7 +286,12 @@ async function verifyLicenseGate() {
|
||||
|
||||
let bad = 0;
|
||||
bad |= sha256(flag) !== seal.certificateSha256 ? 4 : 0;
|
||||
bad |= (sessionLedgerState.cursor & 0);
|
||||
bad |=
|
||||
sessionLedgerState.cursor < 16 ||
|
||||
sessionLedgerState.quotaDigest === 0x811c9dc5 ||
|
||||
(sessionLedgerState.epoch & 1) === 0
|
||||
? 8
|
||||
: 0;
|
||||
try {
|
||||
const panel = fs.readFileSync(path.join(__dirname, "panel.html"));
|
||||
const policy = fs.readFileSync(path.join(__dirname, "policy.py"));
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* CI gate for CrackMe v9 (Sovereign — BLA 3.0). No plaintext secrets required.
|
||||
* If CRACKME_V9_KEY/FLAG match SEAL digests, also verifies unlock + byte rebuild.
|
||||
*/
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { gunzipSync } from "node:zlib";
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
extractFlag,
|
||||
hardenChallenge,
|
||||
prepareRunnable,
|
||||
privateSeed,
|
||||
runLicense,
|
||||
sha256File,
|
||||
sha256Hex,
|
||||
@@ -87,15 +88,51 @@ try {
|
||||
const fxB = tmp("bla-crackme-v9-fxB-");
|
||||
const a = await hardenChallenge({ key: FIXTURE_KEY, flag: FIXTURE_FLAG, outDir: fxA });
|
||||
const b = await hardenChallenge({ key: FIXTURE_KEY, flag: FIXTURE_FLAG, outDir: fxB });
|
||||
const fxSeed = privateSeed(FIXTURE_KEY, FIXTURE_FLAG);
|
||||
for (const rel of COMMITTED_FILES) {
|
||||
if (a.artifacts[rel].sha256 !== b.artifacts[rel].sha256) fail(`fixture re-harden not reproducible on ${rel}`);
|
||||
const rawBuf = rel === "core.wasm.gz" ? gunzipSync(readFileSync(join(fxA, rel))) : readFileSync(join(fxA, rel));
|
||||
if (rawBuf.includes(Buffer.from(fxSeed, "utf8"))) {
|
||||
fail(`fixture artifact ${rel} leaked plaintext privateSeed`);
|
||||
}
|
||||
}
|
||||
const fxRun = prepareRunnable(fxA);
|
||||
tmpRoots.push(fxRun);
|
||||
const unlocked = runLicense(fxRun, FIXTURE_KEY);
|
||||
if (!unlocked.ok || extractFlag(unlocked.stdout) !== FIXTURE_FLAG) fail("fixture unlock failed");
|
||||
if (runLicense(fxRun, "WrongKey!!!!!!!!").ok) fail("fixture accepted wrong key");
|
||||
ok("fixture re-harden reproducible + unlock/deny");
|
||||
|
||||
// Negative tamper checks on runnable copies: sibling deletion, seal tamper, and entry patch must hard-fail
|
||||
for (const sib of ["panel.html", "policy.py"]) {
|
||||
const tDir = prepareRunnable(fxA);
|
||||
tmpRoots.push(tDir);
|
||||
rmSync(join(tDir, sib), { force: true });
|
||||
const tr = runLicense(tDir, FIXTURE_KEY);
|
||||
if (tr.ok || !/integrity (?:check failed|binding mismatch)/.test(tr.stdout)) {
|
||||
fail(`deleting ${sib} did not trigger integrity hard-fail: ${tr.stdout}`);
|
||||
}
|
||||
}
|
||||
{
|
||||
const tDir = prepareRunnable(fxA);
|
||||
tmpRoots.push(tDir);
|
||||
const tamperedSeal = readFileSync(join(tDir, "seal.json"), "utf8").replace('"sha256"', '"md5"');
|
||||
writeFileSync(join(tDir, "seal.json"), tamperedSeal, "utf8");
|
||||
const tr = runLicense(tDir, FIXTURE_KEY);
|
||||
if (tr.ok || !/integrity check failed/.test(tr.stdout) || /\[license\] DENIED/.test(tr.stdout)) {
|
||||
fail(`tampering seal.json did not trigger integrity hard-fail: ${tr.stdout}`);
|
||||
}
|
||||
}
|
||||
{
|
||||
const tDir = prepareRunnable(fxA);
|
||||
tmpRoots.push(tDir);
|
||||
const patchedEntry = readFileSync(join(tDir, "license.cjs"), "utf8") + "\n// patched\n";
|
||||
writeFileSync(join(tDir, "license.cjs"), patchedEntry, "utf8");
|
||||
const tr = runLicense(tDir, FIXTURE_KEY);
|
||||
if (tr.ok || !/integrity check failed/.test(tr.stdout)) {
|
||||
fail(`patching license.cjs did not trigger self-seal hard-fail: ${tr.stdout}`);
|
||||
}
|
||||
}
|
||||
ok("fixture re-harden reproducible + zero seed leak + unlock/deny + negative tamper checks");
|
||||
|
||||
const key = process.env.CRACKME_V9_KEY;
|
||||
const flag = process.env.CRACKME_V9_FLAG;
|
||||
|
||||
@@ -98,18 +98,25 @@ for (const rel of ["README.md", "docs/readme/README_zh.md"]) {
|
||||
}
|
||||
}
|
||||
|
||||
// Keep plugin marketplace manifests in lockstep with package.json.
|
||||
// Keep plugin marketplace & MCP manifests in lockstep with package.json.
|
||||
for (const rel of [
|
||||
".mcp.json",
|
||||
".claude-plugin/plugin.json",
|
||||
".claude-plugin/marketplace.json",
|
||||
".codex-plugin/plugin.json",
|
||||
]) {
|
||||
const pluginPath = resolve(root, rel);
|
||||
try {
|
||||
const pluginText = readFileSync(pluginPath, "utf8");
|
||||
const next = pluginText.replace(
|
||||
/"version"\s*:\s*"[0-9]+\.[0-9]+\.[0-9]+"/g,
|
||||
`"version": "${version}"`,
|
||||
);
|
||||
const next = pluginText
|
||||
.replace(
|
||||
/"version"\s*:\s*"[0-9]+\.[0-9]+\.[0-9]+"/g,
|
||||
`"version": "${version}"`,
|
||||
)
|
||||
.replace(
|
||||
/bla-agents@[0-9]+\.[0-9]+\.[0-9]+/g,
|
||||
`bla-agents@${version}`,
|
||||
);
|
||||
if (next !== pluginText) {
|
||||
writeFileSync(pluginPath, next, "utf8");
|
||||
console.log(`Synced ${rel} version -> ${version}`);
|
||||
|
||||
+43
-8
@@ -97,7 +97,7 @@ function shieldOrPassThrough(
|
||||
* Usage in `vite.config.ts`:
|
||||
* ```ts
|
||||
* import { defineConfig } from "vite";
|
||||
* import { blaVitePlugin } from "bla-shield";
|
||||
* import { blaVitePlugin } from "bla-agents/bundler";
|
||||
*
|
||||
* export default defineConfig({
|
||||
* plugins: [blaVitePlugin({ intensity: "bankrupt" })],
|
||||
@@ -175,6 +175,20 @@ export function blaVitePlugin(options: BlaBundlerPluginOptions = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function createWebpackRawSource(content: string) {
|
||||
const byteBuf = Buffer.from(content, "utf8");
|
||||
return {
|
||||
source: () => content,
|
||||
size: () => byteBuf.length,
|
||||
buffer: () => byteBuf,
|
||||
map: () => null,
|
||||
sourceAndMap: () => ({ source: content, map: null }),
|
||||
updateHash: (hash: { update: (data: string | Buffer) => void }) => {
|
||||
hash.update(byteBuf);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Webpack 5 / Rspack plugin class (`BlaWebpackPlugin`) that shields emitted JS assets.
|
||||
*/
|
||||
@@ -208,6 +222,10 @@ export class BlaWebpackPlugin {
|
||||
name: string,
|
||||
newSource: { source: () => string; size: () => number },
|
||||
) => void;
|
||||
emitAsset?: (
|
||||
name: string,
|
||||
newSource: { source: () => string; size: () => number },
|
||||
) => void;
|
||||
}) => void,
|
||||
) => void;
|
||||
};
|
||||
@@ -215,13 +233,14 @@ export class BlaWebpackPlugin {
|
||||
}): void {
|
||||
const intensity = this.options.intensity ?? "balanced";
|
||||
const include = this.options.include ?? /\.(?:m?js|cjs)$/i;
|
||||
const emitMap = this.options.honeySourceMap ?? true;
|
||||
const failBuildOnError = this.options.failBuildOnError ?? false;
|
||||
|
||||
compiler.hooks.compilation.tap("BlaWebpackPlugin", (compilation) => {
|
||||
compilation.hooks.processAssets.tap(
|
||||
{
|
||||
name: "BlaWebpackPlugin",
|
||||
stage: 400, // PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
|
||||
stage: 2000, // PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER (post-minify so Terser cannot fold shields)
|
||||
},
|
||||
(assets) => {
|
||||
for (const assetName of Object.keys(assets)) {
|
||||
@@ -229,13 +248,14 @@ export class BlaWebpackPlugin {
|
||||
const rawAsset = assets[assetName];
|
||||
if (!rawAsset) continue;
|
||||
const rawSource = rawAsset.source().toString("utf8");
|
||||
const seed = deriveSeedLabel(this.options.seed ?? "bla-webpack", assetName);
|
||||
const sourceType = inferJsCarrierFromPath(assetName);
|
||||
const loader = inferEsbuildLoader(assetName);
|
||||
const shieldedCode = shieldOrPassThrough(
|
||||
() =>
|
||||
transformJavaScriptWithBlaShield(rawSource, {
|
||||
intensity,
|
||||
seed: deriveSeedLabel(this.options.seed ?? "bla-webpack", assetName),
|
||||
seed,
|
||||
filename: assetName,
|
||||
sourceType,
|
||||
loader,
|
||||
@@ -245,10 +265,18 @@ export class BlaWebpackPlugin {
|
||||
if (shieldedCode === null) {
|
||||
continue; // Webpack leaves the already-emitted asset untouched.
|
||||
}
|
||||
compilation.updateAsset(assetName, {
|
||||
source: () => shieldedCode,
|
||||
size: () => Buffer.byteLength(shieldedCode, "utf8"),
|
||||
});
|
||||
compilation.updateAsset(assetName, createWebpackRawSource(shieldedCode));
|
||||
if (emitMap && typeof compilation.emitAsset === "function" && !assets[`${assetName}.map`]) {
|
||||
const prng = new SeededPrng(seed);
|
||||
const chaff = generateChaffPayloads(prng, intensity);
|
||||
const honeyMap = generateHoneySourceMap(
|
||||
assetName,
|
||||
shieldedCode.split("\n").length,
|
||||
prng,
|
||||
chaff,
|
||||
);
|
||||
compilation.emitAsset(`${assetName}.map`, createWebpackRawSource(honeyMap.jsonString));
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -280,7 +308,14 @@ export function blaEsbuildPlugin(options: BlaBundlerPluginOptions = {}) {
|
||||
const fs = await import("node:fs/promises");
|
||||
const source = await fs.readFile(args.path, "utf8");
|
||||
const loader = inferEsbuildLoader(args.path);
|
||||
const sourceType = inferJsCarrierFromPath(args.path);
|
||||
const pathCarrier = inferJsCarrierFromPath(args.path);
|
||||
const sourceType: JsCarrierType =
|
||||
pathCarrier === "script" &&
|
||||
/(?:^|\n)\s*(?:import\s+(?:[\w*{]|["'])|export\s+(?:default\b|const\b|let\b|var\b|function\b|async\b|class\b|type\b|interface\b|enum\b|\{|\*))/m.test(
|
||||
source,
|
||||
)
|
||||
? "module"
|
||||
: pathCarrier;
|
||||
const shieldedCode = shieldOrPassThrough(
|
||||
() =>
|
||||
transformJavaScriptWithBlaShield(source, {
|
||||
|
||||
+68
-19
@@ -118,9 +118,12 @@ Options:
|
||||
--allow-wasm-seal-xor-known-plaintext Allow bankrupt despite seal.revision XOR known-plaintext packs (round-7); OFF by default
|
||||
--lang <c|rust|go> Target language for emit-headers (default: c)
|
||||
--fail-under <n> Exit 2 when the score fails the gate: defense score < n (defend/verify) or audit exposure score > n (audit)
|
||||
--client <id> Agent client ID for setup (repeatable: claude_code, cursor, codex, etc.)
|
||||
--client <id> Agent client ID for setup/uninstall (repeatable: claude_code, cursor, codex, etc.)
|
||||
--all-detected Configure all detected coding agents on this machine
|
||||
--dry-run Preview planned setup/harden changes without writing files
|
||||
--all-clients Configure all 10 supported coding agents (including undetected)
|
||||
--force Force setup/uninstall overwrite when custom SKILL.md or MCP entry conflicts
|
||||
--require-agent-weave Enforce verified Stage-2 Agent source weave before harden/defend
|
||||
--dry-run Preview planned setup/uninstall/harden changes without writing files
|
||||
-y, --yes Approve setup actions without interactive confirmation
|
||||
--json Emit structured JSON output
|
||||
-v, --version Print BLA version
|
||||
@@ -166,6 +169,8 @@ interface ParsedCliArgs {
|
||||
readonly lang: NativeHeaderLanguage;
|
||||
readonly clients: SupportedAgentClientId[];
|
||||
readonly allDetected: boolean;
|
||||
readonly allClients: boolean;
|
||||
readonly force: boolean;
|
||||
readonly dryRun: boolean;
|
||||
readonly yes: boolean;
|
||||
readonly json: boolean;
|
||||
@@ -238,6 +243,8 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
|
||||
const clients: SupportedAgentClientId[] = [];
|
||||
const argErrors: string[] = [];
|
||||
let allDetected = false;
|
||||
let allClients = false;
|
||||
let force = false;
|
||||
let dryRun = false;
|
||||
let yes = false;
|
||||
let json = false;
|
||||
@@ -283,6 +290,10 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
|
||||
dryRun = true;
|
||||
} else if (arg === "--all-detected") {
|
||||
allDetected = true;
|
||||
} else if (arg === "--all-clients" || arg === "--include-undetected") {
|
||||
allClients = true;
|
||||
} else if (arg === "-f" || arg === "--force") {
|
||||
force = true;
|
||||
} else if (arg === "--in-place") {
|
||||
inPlace = true;
|
||||
} else if (arg === "--no-honey-maps") {
|
||||
@@ -475,6 +486,8 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
|
||||
lang,
|
||||
clients,
|
||||
allDetected,
|
||||
allClients,
|
||||
force,
|
||||
dryRun,
|
||||
yes,
|
||||
json,
|
||||
@@ -553,12 +566,14 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
||||
const res = runSetup({
|
||||
...(parsed.clients.length > 0 ? { clientIds: parsed.clients } : {}),
|
||||
allDetected: parsed.allDetected,
|
||||
includeUndetected: parsed.allClients,
|
||||
force: parsed.force,
|
||||
dryRun: parsed.dryRun,
|
||||
yes: parsed.yes,
|
||||
});
|
||||
if (parsed.json) console.log(JSON.stringify(res, null, 2));
|
||||
else console.log(formatSetupReport(res));
|
||||
return 0;
|
||||
return res.status === "error" || res.status === "conflict" ? 1 : 0;
|
||||
}
|
||||
|
||||
case "doctor": {
|
||||
@@ -585,10 +600,18 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
||||
}
|
||||
|
||||
case "uninstall": {
|
||||
const res = runUninstall();
|
||||
const res = runUninstall({
|
||||
...(parsed.clients.length > 0 ? { clientIds: parsed.clients } : {}),
|
||||
force: parsed.force,
|
||||
dryRun: parsed.dryRun,
|
||||
});
|
||||
if (parsed.json) console.log(JSON.stringify(res, null, 2));
|
||||
else console.log(`Removed BLA configuration from ${res.removedClients.length} client(s).`);
|
||||
return 0;
|
||||
else if (parsed.dryRun) {
|
||||
console.log(`Dry-run: would remove BLA configuration from ${res.removedClients.length} client(s).`);
|
||||
} else {
|
||||
console.log(`Removed BLA configuration from ${res.removedClients.length} client(s).`);
|
||||
}
|
||||
return res.conflicts.length > 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
case "init": {
|
||||
@@ -646,7 +669,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
||||
weaveDecoys: parsed.weaveDecoys || loaded.config.weaveDecoys === true,
|
||||
selfSeal: parsed.selfSeal || loaded.config.selfSeal === true,
|
||||
sidecarEntangle: parsed.sidecarEntangle || loaded.config.sidecarEntangle === true,
|
||||
...(parsed.requireAgentWeave ? { requireAgentWeave: true } : {}),
|
||||
...(parsed.requireAgentWeave || loaded.config.requireAgentWeave === true
|
||||
? { requireAgentWeave: true }
|
||||
: {}),
|
||||
...mergeWasmPreserveExports(parsed, loaded.config),
|
||||
allowLaneIndependentGates:
|
||||
parsed.allowLaneIndependentGates ||
|
||||
@@ -675,7 +700,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
||||
allowWasmSealXorKnownPlaintext:
|
||||
parsed.allowWasmSealXorKnownPlaintext ||
|
||||
loaded.config.allowWasmSealXorKnownPlaintext === true,
|
||||
allowReleaseHygieneLeak: parsed.allowReleaseHygieneLeak,
|
||||
allowReleaseHygieneLeak:
|
||||
parsed.allowReleaseHygieneLeak ||
|
||||
loaded.config.allowReleaseHygieneLeak === true,
|
||||
...(parsed.output !== undefined ? { outputDirectory: parsed.output } : {}),
|
||||
});
|
||||
if (parsed.json) {
|
||||
@@ -718,7 +745,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
||||
weaveDecoys: parsed.weaveDecoys || loaded.config.weaveDecoys === true,
|
||||
selfSeal: parsed.selfSeal || loaded.config.selfSeal === true,
|
||||
sidecarEntangle: parsed.sidecarEntangle || loaded.config.sidecarEntangle === true,
|
||||
...(parsed.requireAgentWeave ? { requireAgentWeave: true } : {}),
|
||||
...(parsed.requireAgentWeave || loaded.config.requireAgentWeave === true
|
||||
? { requireAgentWeave: true }
|
||||
: {}),
|
||||
...mergeWasmPreserveExports(parsed, loaded.config),
|
||||
allowLaneIndependentGates:
|
||||
parsed.allowLaneIndependentGates ||
|
||||
@@ -747,6 +776,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
||||
allowWasmSealXorKnownPlaintext:
|
||||
parsed.allowWasmSealXorKnownPlaintext ||
|
||||
loaded.config.allowWasmSealXorKnownPlaintext === true,
|
||||
allowReleaseHygieneLeak:
|
||||
parsed.allowReleaseHygieneLeak ||
|
||||
loaded.config.allowReleaseHygieneLeak === true,
|
||||
});
|
||||
if (parsed.sarif) {
|
||||
console.log(
|
||||
@@ -772,19 +804,33 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
||||
intensity: argv.some((a) => a === "--intensity" || a.startsWith("--intensity="))
|
||||
? parsed.intensity
|
||||
: (loaded.config.intensity ?? "bankrupt"),
|
||||
allowPlaintextSeal: parsed.allowPlaintextSeal,
|
||||
allowWasmClearParamCarriers: parsed.allowWasmClearParamCarriers,
|
||||
allowJsAesUnwrap: parsed.allowJsAesUnwrap,
|
||||
allowJsWasmHydrateDump: parsed.allowJsWasmHydrateDump,
|
||||
allowWasmXorMaskSidecar: parsed.allowWasmXorMaskSidecar,
|
||||
allowWasmSealXorKnownPlaintext: parsed.allowWasmSealXorKnownPlaintext,
|
||||
allowPlaintextSeal:
|
||||
parsed.allowPlaintextSeal || loaded.config.allowPlaintextSeal === true,
|
||||
allowWasmClearParamCarriers:
|
||||
parsed.allowWasmClearParamCarriers ||
|
||||
loaded.config.allowWasmClearParamCarriers === true,
|
||||
allowJsAesUnwrap:
|
||||
parsed.allowJsAesUnwrap || loaded.config.allowJsAesUnwrap === true,
|
||||
allowJsWasmHydrateDump:
|
||||
parsed.allowJsWasmHydrateDump || loaded.config.allowJsWasmHydrateDump === true,
|
||||
allowWasmXorMaskSidecar:
|
||||
parsed.allowWasmXorMaskSidecar || loaded.config.allowWasmXorMaskSidecar === true,
|
||||
allowWasmSealXorKnownPlaintext:
|
||||
parsed.allowWasmSealXorKnownPlaintext ||
|
||||
loaded.config.allowWasmSealXorKnownPlaintext === true,
|
||||
allowPlaintextString: parsed.allowPlaintextString,
|
||||
allowSinglePointIntegrity: parsed.allowSinglePointIntegrity,
|
||||
allowMissingBindRuntime: parsed.allowMissingBindRuntime,
|
||||
allowReleaseHygieneLeak: parsed.allowReleaseHygieneLeak,
|
||||
allowLaneIndependentGates: parsed.allowLaneIndependentGates,
|
||||
allowPanelOfflineOracle: parsed.allowPanelOfflineOracle,
|
||||
allowStablePanelDeriveAbi: parsed.allowStablePanelDeriveAbi,
|
||||
allowReleaseHygieneLeak:
|
||||
parsed.allowReleaseHygieneLeak || loaded.config.allowReleaseHygieneLeak === true,
|
||||
allowLaneIndependentGates:
|
||||
parsed.allowLaneIndependentGates ||
|
||||
loaded.config.allowLaneIndependentGates === true,
|
||||
allowPanelOfflineOracle:
|
||||
parsed.allowPanelOfflineOracle || loaded.config.allowPanelOfflineOracle === true,
|
||||
allowStablePanelDeriveAbi:
|
||||
parsed.allowStablePanelDeriveAbi ||
|
||||
loaded.config.allowStablePanelDeriveAbi === true,
|
||||
includeProtectTimeGates: true,
|
||||
});
|
||||
if (parsed.json) {
|
||||
@@ -1093,6 +1139,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
||||
allowWasmSealXorKnownPlaintext:
|
||||
parsed.allowWasmSealXorKnownPlaintext ||
|
||||
loaded.config.allowWasmSealXorKnownPlaintext === true,
|
||||
allowReleaseHygieneLeak:
|
||||
parsed.allowReleaseHygieneLeak ||
|
||||
loaded.config.allowReleaseHygieneLeak === true,
|
||||
});
|
||||
if (parsed.json) console.log(JSON.stringify(res, null, 2));
|
||||
else console.log(formatProtectionResult(res));
|
||||
|
||||
@@ -43,6 +43,8 @@ export interface BlaProjectConfig {
|
||||
readonly allowWasmXorMaskSidecar?: boolean;
|
||||
/** When true, allow bankrupt despite seal.revision XOR known-plaintext packs (red-blue round-7). Default false. */
|
||||
readonly allowWasmSealXorKnownPlaintext?: boolean;
|
||||
/** Lab-only: allow leaked SOLUTION/dotenv/private-key/debug-symbol files in release tree. Default false. */
|
||||
readonly allowReleaseHygieneLeak?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,6 +97,7 @@ const BOOLEAN_CONFIG_KEYS = [
|
||||
"allowJsWasmHydrateDump",
|
||||
"allowWasmXorMaskSidecar",
|
||||
"allowWasmSealXorKnownPlaintext",
|
||||
"allowReleaseHygieneLeak",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
|
||||
@@ -62,6 +62,12 @@ export function estimateAgentReverseEngineeringCosts(
|
||||
const inputUsd = (cumulativeInputTokens / 1_000_000) * model.inputUsdPerMillion;
|
||||
const outputUsd = (outputTokens / 1_000_000) * model.outputUsdPerMillion;
|
||||
const cost = Number(Math.max(0.02, inputUsd + outputUsd).toFixed(2));
|
||||
const unshieldedOverflowProb = Number(
|
||||
Math.min(
|
||||
0.09,
|
||||
Math.max(0.01, (baseSourceTokens * 2 + 820) / model.contextWindowTokens),
|
||||
).toFixed(2),
|
||||
);
|
||||
return {
|
||||
modelName: model.modelName,
|
||||
estimatedInputTokens: cumulativeInputTokens,
|
||||
@@ -69,7 +75,7 @@ export function estimateAgentReverseEngineeringCosts(
|
||||
estimatedMcpToolCalls: totalMcpCalls,
|
||||
estimatedWallClockSeconds: Math.round(totalMcpCalls * model.secondsPerMcpRoundtrip),
|
||||
estimatedCostUsd: cost,
|
||||
contextWindowOverflowProbability: 0.02,
|
||||
contextWindowOverflowProbability: unshieldedOverflowProb,
|
||||
outcomeVerdict: "TRIVIAL_CLONE",
|
||||
};
|
||||
});
|
||||
@@ -102,6 +108,20 @@ export function estimateAgentReverseEngineeringCosts(
|
||||
const outputUsd = (rawOutputTokens / 1_000_000) * model.outputUsdPerMillion;
|
||||
const totalCostUsd = Number((inputUsd + outputUsd).toFixed(2));
|
||||
const wallClockSeconds = Math.round(totalMcpCalls * model.secondsPerMcpRoundtrip);
|
||||
const peakTurnTokens =
|
||||
baseSourceTokens + avgContextPerTurn + Math.min(45_000, totalMcpCalls * 420);
|
||||
const occupancyRatio = peakTurnTokens / model.contextWindowTokens;
|
||||
const overflowProb = Number(
|
||||
Math.min(
|
||||
0.99,
|
||||
Math.max(
|
||||
0.22,
|
||||
occupancyRatio * 0.92 +
|
||||
Math.min(0.18, sim.triggeredResourceLimits.length * 0.05) +
|
||||
(sim.decoyFunctionsDetectedAsReal >= 10 ? 0.08 : 0),
|
||||
),
|
||||
).toFixed(2),
|
||||
);
|
||||
|
||||
return {
|
||||
modelName: model.modelName,
|
||||
@@ -110,8 +130,7 @@ export function estimateAgentReverseEngineeringCosts(
|
||||
estimatedMcpToolCalls: totalMcpCalls,
|
||||
estimatedWallClockSeconds: wallClockSeconds,
|
||||
estimatedCostUsd: Math.max(1.5, totalCostUsd),
|
||||
contextWindowOverflowProbability:
|
||||
sim.decoyFunctionsDetectedAsReal >= 10 ? 0.98 : 0.84,
|
||||
contextWindowOverflowProbability: overflowProb,
|
||||
outcomeVerdict:
|
||||
sim.examinationStatus === "limited" && sim.decoyFunctionsDetectedAsReal >= 8
|
||||
? "AGENT_HALLUCINATION_AND_BANKRUPTCY"
|
||||
|
||||
@@ -226,6 +226,8 @@ export interface ProtectionOptions {
|
||||
/** Red/blue round-6: allow WASM XOR-mask-beside-blob entitlement packs under bankrupt/maximum. */
|
||||
readonly allowWasmXorMaskSidecar?: boolean;
|
||||
readonly allowWasmSealXorKnownPlaintext?: boolean;
|
||||
/** Lab-only: allow leaked SOLUTION/dotenv/private-key/debug-symbol files in release tree. */
|
||||
readonly allowReleaseHygieneLeak?: boolean;
|
||||
/**
|
||||
* Optional sibling paths for self-seal when `selfSeal` is true (multi-artifact harden).
|
||||
* Relative paths are resolved from the protected module's directory at runtime.
|
||||
|
||||
@@ -65,6 +65,8 @@ export interface OneClickDefenseOptions {
|
||||
readonly allowWasmXorMaskSidecar?: boolean;
|
||||
/** Allow bankrupt despite seal.revision XOR known-plaintext packs (red-blue round-7). Default false. */
|
||||
readonly allowWasmSealXorKnownPlaintext?: boolean;
|
||||
/** Lab-only: allow leaked SOLUTION/dotenv/private-key/debug-symbol files in release tree. Default false. */
|
||||
readonly allowReleaseHygieneLeak?: boolean;
|
||||
/** Sibling paths forwarded into self-seal when enabled (multi-artifact harden). */
|
||||
readonly selfSealSiblingPaths?: readonly string[];
|
||||
}
|
||||
@@ -216,6 +218,9 @@ export function defendTarget(options: OneClickDefenseOptions): OneClickDefenseRe
|
||||
...(options.allowWasmSealXorKnownPlaintext === true
|
||||
? { allowWasmSealXorKnownPlaintext: true }
|
||||
: {}),
|
||||
...(options.allowReleaseHygieneLeak === true
|
||||
? { allowReleaseHygieneLeak: true }
|
||||
: {}),
|
||||
...(options.selfSealSiblingPaths !== undefined &&
|
||||
options.selfSealSiblingPaths.length > 0
|
||||
? { selfSealSiblingPaths: options.selfSealSiblingPaths }
|
||||
|
||||
@@ -250,18 +250,27 @@ interface LiteralSpan {
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
readonly value: string;
|
||||
readonly wrapJsxExpr?: boolean;
|
||||
}
|
||||
|
||||
function isNonReplaceableStringPosition(path: {
|
||||
readonly node: unknown;
|
||||
readonly parent: unknown;
|
||||
readonly parentPath?: { readonly parent: unknown } | null;
|
||||
readonly parentPath?: { readonly node?: unknown; readonly parent: unknown; readonly parentPath?: unknown } | null;
|
||||
}): boolean {
|
||||
const node = path.node as Record<string, unknown>;
|
||||
const parent = path.parent as Record<string, unknown> | null | undefined;
|
||||
if (!parent) return false;
|
||||
const pType = parent.type;
|
||||
|
||||
// Ambient TypeScript declarations (`declare const`, `declare enum`, `declare module`, etc.)
|
||||
let cur: { readonly node?: unknown; readonly parentPath?: unknown } | null | undefined = path;
|
||||
while (cur) {
|
||||
const curNode = cur.node as Record<string, unknown> | undefined;
|
||||
if (curNode?.declare === true) return true;
|
||||
cur = cur.parentPath as { readonly node?: unknown; readonly parentPath?: unknown } | null | undefined;
|
||||
}
|
||||
|
||||
// Module specifiers in import / export declarations
|
||||
if (
|
||||
(pType === "ImportDeclaration" ||
|
||||
@@ -271,14 +280,15 @@ function isNonReplaceableStringPosition(path: {
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (pType === "ImportAttribute") {
|
||||
if (pType === "ImportAttribute" || pType === "Directive") {
|
||||
return true;
|
||||
}
|
||||
// TypeScript literal types or module references
|
||||
// TypeScript literal types, enum member identifiers, or module references
|
||||
if (
|
||||
pType === "TSLiteralType" ||
|
||||
pType === "TSExternalModuleReference" ||
|
||||
pType === "TSImportType"
|
||||
pType === "TSImportType" ||
|
||||
(pType === "TSEnumMember" && parent.id === node)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
@@ -329,7 +339,14 @@ function collectJsLiteralSpans(source: string): LiteralSpan[] {
|
||||
if (isNonReplaceableStringPosition(path)) return;
|
||||
const { start, end, value } = path.node;
|
||||
if (typeof start === "number" && typeof end === "number") {
|
||||
spans.push({ start, end, value });
|
||||
const wrapJsxExpr =
|
||||
path.parent.type === "JSXAttribute" && path.parent.value === path.node;
|
||||
spans.push({
|
||||
start,
|
||||
end,
|
||||
value,
|
||||
...(wrapJsxExpr ? { wrapJsxExpr: true } : {}),
|
||||
});
|
||||
}
|
||||
},
|
||||
TemplateLiteral(path) {
|
||||
@@ -430,18 +447,21 @@ function transformJsSource(
|
||||
for (const span of descending) {
|
||||
const idx = indexByLiteral.get(span.value);
|
||||
if (idx === undefined) continue;
|
||||
body = `${body.slice(0, span.start)}${fnName}(${idx})${body.slice(span.end)}`;
|
||||
const callExpr = span.wrapJsxExpr ? `{${fnName}(${idx})}` : `${fnName}(${idx})`;
|
||||
body = `${body.slice(0, span.start)}${callExpr}${body.slice(span.end)}`;
|
||||
}
|
||||
|
||||
// Keep shebang / "use strict" at the very top so Node can still execute the file.
|
||||
// Keep shebang and module-top directives ("use strict" / "use client" / "use server") at the very top.
|
||||
const shebangMatch = body.match(/^#![^\n]*\n/);
|
||||
const shebang = shebangMatch ? shebangMatch[0] : "";
|
||||
const rest = shebang ? body.slice(shebang.length) : body;
|
||||
const strictMatch = rest.match(/^["']use strict["'];?\r?\n/);
|
||||
const strict = strictMatch ? strictMatch[0] : "";
|
||||
const afterStrict = strict ? rest.slice(strict.length) : rest;
|
||||
const directiveMatch = rest.match(
|
||||
/^(?:[ \t]*["']use (?:strict|client|server)["'];?[ \t]*\r?\n)+/,
|
||||
);
|
||||
const directives = directiveMatch ? directiveMatch[0] : "";
|
||||
const afterDirectives = directives ? rest.slice(directives.length) : rest;
|
||||
return {
|
||||
code: shebang + strict + stub + "\n" + afterStrict,
|
||||
code: shebang + directives + stub + "\n" + afterDirectives,
|
||||
encrypted: unique,
|
||||
skipped,
|
||||
};
|
||||
@@ -460,13 +480,30 @@ function transformHtml(
|
||||
const allEncrypted: string[] = [];
|
||||
let skipped = 0;
|
||||
let any = false;
|
||||
let scriptIndex = 0;
|
||||
const code = source.replace(scriptRe, (_m, open, body, close) => {
|
||||
if (/\bsrc\s*=/.test(open) && String(body).trim().length === 0) {
|
||||
const openStr = String(open);
|
||||
if (/\bsrc\s*=/.test(openStr) && String(body).trim().length === 0) {
|
||||
return `${open}${body}${close}`;
|
||||
}
|
||||
const typeMatch = openStr.match(/\btype\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
|
||||
const rawType = (typeMatch?.[1] ?? typeMatch?.[2] ?? typeMatch?.[3] ?? "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (
|
||||
rawType.length > 0 &&
|
||||
rawType !== "module" &&
|
||||
rawType !== "text/javascript" &&
|
||||
rawType !== "application/javascript" &&
|
||||
rawType !== "text/ecmascript" &&
|
||||
rawType !== "application/ecmascript"
|
||||
) {
|
||||
return `${open}${body}${close}`;
|
||||
}
|
||||
const currentScriptIdx = scriptIndex++;
|
||||
const result = transformJsSource(
|
||||
body,
|
||||
prng.derive(`html:${allEncrypted.length}`),
|
||||
prng.derive(`html:${currentScriptIdx}`),
|
||||
includeUrls,
|
||||
);
|
||||
skipped += result.skipped;
|
||||
@@ -518,20 +555,23 @@ export function encryptStrings(options: EncryptStringsOptions): EncryptStringsRe
|
||||
if (outDir && !options.dryRun) mkdirSync(outDir, { recursive: true });
|
||||
|
||||
const files: EncryptStringsFileResult[] = [];
|
||||
const transformedByOutPath = new Map<string, string>();
|
||||
let totalEncrypted = 0;
|
||||
|
||||
for (const file of targets) {
|
||||
const source = readFileSync(file, "utf8");
|
||||
const isHtml = /\.html?$/i.test(file);
|
||||
const filePrng = rootPrng.derive(basename(file));
|
||||
const relFromRoot = isSingleFileInput
|
||||
? basename(file)
|
||||
: relative(baseRoot, file) || basename(file);
|
||||
const normalizedRel = relFromRoot.replace(/\\/g, "/");
|
||||
const filePrng = rootPrng.derive(normalizedRel);
|
||||
const result = isHtml
|
||||
? transformHtml(source, filePrng, includeUrls)
|
||||
: transformJsSource(source, filePrng, includeUrls);
|
||||
|
||||
const relFromRoot = isSingleFileInput
|
||||
? basename(file)
|
||||
: relative(baseRoot, file) || basename(file);
|
||||
const outPath = outDir ? join(outDir, relFromRoot) : file;
|
||||
transformedByOutPath.set(outPath, result.code);
|
||||
let written = false;
|
||||
if (result.encrypted.length > 0 && !options.dryRun) {
|
||||
if (outDir) mkdirSync(dirname(outPath), { recursive: true });
|
||||
@@ -556,7 +596,7 @@ export function encryptStrings(options: EncryptStringsOptions): EncryptStringsRe
|
||||
totalEncrypted += result.encrypted.length;
|
||||
files.push({
|
||||
path: file,
|
||||
relativeName: relFromRoot.replace(/\\/g, "/"),
|
||||
relativeName: normalizedRel,
|
||||
encryptedCount: result.encrypted.length,
|
||||
skippedCount: result.skipped,
|
||||
literals: result.encrypted.map((s) =>
|
||||
@@ -570,11 +610,9 @@ export function encryptStrings(options: EncryptStringsOptions): EncryptStringsRe
|
||||
let postLintClean = true;
|
||||
for (const f of files) {
|
||||
if (f.encryptedCount === 0) continue;
|
||||
if (options.dryRun) {
|
||||
postLintClean = false;
|
||||
break;
|
||||
}
|
||||
const src = readFileSync(f.outPath, "utf8");
|
||||
const src = options.dryRun
|
||||
? (transformedByOutPath.get(f.outPath) ?? readFileSync(f.path, "utf8"))
|
||||
: readFileSync(f.outPath, "utf8");
|
||||
const report = lintPlaintextSecretsSource(src, { path: f.outPath });
|
||||
if (report.shouldRefuseBankrupt) {
|
||||
postLintClean = false;
|
||||
|
||||
+205
-23
@@ -1,11 +1,13 @@
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
statSync,
|
||||
} from "node:fs";
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { detectArtifactFormat } from "../core/detector.js";
|
||||
import { generateProjectSeed, loadBlaConfig, type BlaProjectConfig } from "../core/config.js";
|
||||
import { physicalPath } from "../core/output-path.js";
|
||||
import { walkBounded } from "../core/walk.js";
|
||||
import type { ArtifactFormat, ProtectionIntensity } from "../core/types.js";
|
||||
@@ -42,6 +44,7 @@ import {
|
||||
ASAR_SIDECAR_ARCHIVE_NOTE_PATH,
|
||||
ASAR_SIDECAR_MAIN_JS_MARKER,
|
||||
BUN_SIDECAR_COMPANION_SUFFIX,
|
||||
derivePublicSidecarSeedTag,
|
||||
entangleAsarEntryWithSidecars,
|
||||
entangleAsarMainJsWithSidecars,
|
||||
entangleBunEntryWithSidecars,
|
||||
@@ -520,9 +523,80 @@ function planArtifactOutputPath(artifact: DiscoveredArtifact, outputRoot: string
|
||||
* Usage: `bla harden .` / MCP `bla_harden` with `{ "directory": "." }`
|
||||
*/
|
||||
export function hardenProject(
|
||||
options: HardenProjectOptions = {},
|
||||
rawOptions: HardenProjectOptions = {},
|
||||
): HardenProjectReport {
|
||||
const absDir = resolve(options.directory ?? process.cwd());
|
||||
const absDir = resolve(rawOptions.directory ?? process.cwd());
|
||||
let projectCfg: BlaProjectConfig | undefined;
|
||||
if (existsSync(absDir)) {
|
||||
const configDir = statSync(absDir).isDirectory() ? absDir : dirname(absDir);
|
||||
const directLoaded = loadBlaConfig(configDir);
|
||||
if (directLoaded.sourcePath !== null) {
|
||||
projectCfg = directLoaded.config;
|
||||
} else if (
|
||||
(BLA_BUILD_OUTPUT_DIR_NAMES as readonly string[]).includes(basename(configDir))
|
||||
) {
|
||||
const parentLoaded = loadBlaConfig(dirname(configDir));
|
||||
if (parentLoaded.sourcePath !== null) {
|
||||
projectCfg = parentLoaded.config;
|
||||
}
|
||||
}
|
||||
}
|
||||
const resolvedSeed: string | number =
|
||||
rawOptions.seed !== undefined && String(rawOptions.seed).length > 0
|
||||
? rawOptions.seed
|
||||
: projectCfg?.seed && projectCfg.seed.length > 0
|
||||
? projectCfg.seed
|
||||
: generateProjectSeed();
|
||||
const mergedWasmPreserveExports = [
|
||||
...new Set([
|
||||
...(projectCfg?.wasmPreserveExports ?? []),
|
||||
...(rawOptions.wasmPreserveExports ?? []),
|
||||
]),
|
||||
];
|
||||
const options: HardenProjectOptions = {
|
||||
...rawOptions,
|
||||
seed: resolvedSeed,
|
||||
intensity: rawOptions.intensity ?? projectCfg?.intensity ?? "bankrupt",
|
||||
emitManifest: rawOptions.emitManifest ?? projectCfg?.emitManifest ?? false,
|
||||
...(rawOptions.llmDirectives !== undefined || projectCfg?.llmDirectives !== undefined
|
||||
? { llmDirectives: rawOptions.llmDirectives ?? projectCfg?.llmDirectives }
|
||||
: {}),
|
||||
...(rawOptions.weaveDecoys !== undefined || projectCfg?.weaveDecoys !== undefined
|
||||
? { weaveDecoys: rawOptions.weaveDecoys ?? projectCfg?.weaveDecoys }
|
||||
: {}),
|
||||
...(rawOptions.selfSeal !== undefined || projectCfg?.selfSeal !== undefined
|
||||
? { selfSeal: rawOptions.selfSeal ?? projectCfg?.selfSeal }
|
||||
: {}),
|
||||
...(rawOptions.sidecarEntangle !== undefined || projectCfg?.sidecarEntangle !== undefined
|
||||
? { sidecarEntangle: rawOptions.sidecarEntangle ?? projectCfg?.sidecarEntangle }
|
||||
: {}),
|
||||
...(rawOptions.requireAgentWeave !== undefined || projectCfg?.requireAgentWeave !== undefined
|
||||
? { requireAgentWeave: rawOptions.requireAgentWeave ?? projectCfg?.requireAgentWeave }
|
||||
: {}),
|
||||
...(mergedWasmPreserveExports.length > 0
|
||||
? { wasmPreserveExports: mergedWasmPreserveExports }
|
||||
: {}),
|
||||
allowLaneIndependentGates:
|
||||
rawOptions.allowLaneIndependentGates ?? projectCfg?.allowLaneIndependentGates ?? false,
|
||||
allowPlaintextSeal:
|
||||
rawOptions.allowPlaintextSeal ?? projectCfg?.allowPlaintextSeal ?? false,
|
||||
allowWasmClearParamCarriers:
|
||||
rawOptions.allowWasmClearParamCarriers ?? projectCfg?.allowWasmClearParamCarriers ?? false,
|
||||
allowStablePanelDeriveAbi:
|
||||
rawOptions.allowStablePanelDeriveAbi ?? projectCfg?.allowStablePanelDeriveAbi ?? false,
|
||||
allowJsAesUnwrap:
|
||||
rawOptions.allowJsAesUnwrap ?? projectCfg?.allowJsAesUnwrap ?? false,
|
||||
allowJsWasmHydrateDump:
|
||||
rawOptions.allowJsWasmHydrateDump ?? projectCfg?.allowJsWasmHydrateDump ?? false,
|
||||
allowWasmXorMaskSidecar:
|
||||
rawOptions.allowWasmXorMaskSidecar ?? projectCfg?.allowWasmXorMaskSidecar ?? false,
|
||||
allowWasmSealXorKnownPlaintext:
|
||||
rawOptions.allowWasmSealXorKnownPlaintext ?? projectCfg?.allowWasmSealXorKnownPlaintext ?? false,
|
||||
allowPanelOfflineOracle:
|
||||
rawOptions.allowPanelOfflineOracle ?? projectCfg?.allowPanelOfflineOracle ?? false,
|
||||
allowReleaseHygieneLeak:
|
||||
rawOptions.allowReleaseHygieneLeak ?? projectCfg?.allowReleaseHygieneLeak ?? false,
|
||||
};
|
||||
const intensity: ProtectionIntensity = options.intensity ?? "bankrupt";
|
||||
// Manifests are opt-in: do not ship `.bla-manifest.json` next to customer artifacts by default.
|
||||
const emitManifest = options.emitManifest === true;
|
||||
@@ -626,16 +700,67 @@ export function hardenProject(
|
||||
"typescript",
|
||||
"html-bundle",
|
||||
"python-source",
|
||||
"elf",
|
||||
"macho",
|
||||
"pe",
|
||||
"native-elf",
|
||||
"native-macho",
|
||||
"native-pe",
|
||||
]);
|
||||
const weaveableDiscovered = discovered.filter((a) => weaveFormats.has(a.format));
|
||||
let agentWeaveAssessment: AgentWeaveAssessment | undefined;
|
||||
if (weaveableDiscovered.length > 0 || options.requireAgentWeave === true) {
|
||||
try {
|
||||
const weaveVerify = verifyWeaveTarget(absDir, { maxTargets: maxArtifacts });
|
||||
if (weaveVerify.files.length > 0) {
|
||||
// Detect stale build outputs when Host Agent edited `src/` but forgot to rebuild `dist/`/`build/`/`out/`.
|
||||
let staleBuildMessage: string | undefined;
|
||||
if (options.requireAgentWeave === true) {
|
||||
const buildRelRe = /^(?:dist|build|out)(?:[\\/]|$)/i;
|
||||
const buildArtifacts = discovered.filter((a) => buildRelRe.test(a.relativePath));
|
||||
const srcRoot = join(absDir, "src");
|
||||
if (buildArtifacts.length > 0 && existsSync(srcRoot)) {
|
||||
let newestBuildMtime = 0;
|
||||
for (const ba of buildArtifacts) {
|
||||
try {
|
||||
const m = statSync(ba.path).mtimeMs;
|
||||
if (m > newestBuildMtime) newestBuildMtime = m;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
let newestSrcMtime = 0;
|
||||
let newestSrcRel = "";
|
||||
const srcStack = [srcRoot];
|
||||
while (srcStack.length > 0) {
|
||||
const cur = srcStack.pop()!;
|
||||
let ents;
|
||||
try {
|
||||
ents = readdirSync(cur, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const ent of ents) {
|
||||
if (ent.name.startsWith(".")) continue;
|
||||
const full = join(cur, ent.name);
|
||||
if (ent.isDirectory()) {
|
||||
srcStack.push(full);
|
||||
} else if (ent.isFile() && /\.(?:[cm]?[jt]sx?|py|rs|go|c|cpp|cc)$/i.test(ent.name)) {
|
||||
try {
|
||||
const m = statSync(full).mtimeMs;
|
||||
if (m > newestSrcMtime) {
|
||||
newestSrcMtime = m;
|
||||
newestSrcRel = relative(absDir, full);
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (newestBuildMtime > 0 && newestSrcMtime > newestBuildMtime + 50) {
|
||||
staleBuildMessage = `Source file '${newestSrcRel}' is newer than build output in dist/build/out — rebuild your project (e.g. npm run build) after Stage-2 source surgery before running bla_harden.`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (weaveVerify.files.length > 0 || staleBuildMessage !== undefined) {
|
||||
const weavePlan = buildWeavePlan(absDir, { maxTargets: maxArtifacts });
|
||||
const workorderMap: Record<string, WeaveSurgicalWorkorder> = {};
|
||||
for (const target of weavePlan.targets) {
|
||||
@@ -646,20 +771,77 @@ export function hardenProject(
|
||||
const unwovenSourceFiles = weaveVerify.files
|
||||
.filter((f) => !f.passed)
|
||||
.map((f) => f.relativePath);
|
||||
const weaveVerified = weaveVerify.overallPassed;
|
||||
if (staleBuildMessage !== undefined && unwovenSourceFiles.length === 0) {
|
||||
unwovenSourceFiles.push("dist/ (stale build)");
|
||||
}
|
||||
const extraActions =
|
||||
staleBuildMessage !== undefined
|
||||
? [
|
||||
{
|
||||
priority: "high" as const,
|
||||
file: "dist/",
|
||||
checkId: "crown-jewel-entanglement" as const,
|
||||
instruction: staleBuildMessage,
|
||||
verifyTool: "bla_verify_weave" as const,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
const combinedActions = [...extraActions, ...weaveVerify.agentActions];
|
||||
const weaveVerified =
|
||||
weaveVerify.files.length > 0 &&
|
||||
weaveVerify.overallPassed &&
|
||||
staleBuildMessage === undefined;
|
||||
agentWeaveAssessment = {
|
||||
weaveVerified,
|
||||
weaveScore: weaveVerify.weaveScore,
|
||||
weaveScore: staleBuildMessage !== undefined ? Math.min(weaveVerify.weaveScore, 50) : weaveVerify.weaveScore,
|
||||
unwovenSourceFiles,
|
||||
agentActions: weaveVerify.agentActions,
|
||||
agentActions: combinedActions,
|
||||
surgicalWorkorders: workorderMap,
|
||||
agentPlaybookDirective: weaveVerified
|
||||
? `All ${weaveVerify.files.length} source file(s) passed Host-Agent structural weave verification (weaveScore=${weaveVerify.weaveScore}/100).`
|
||||
: `Host-Agent source surgery pending on [${unwovenSourceFiles.join(", ")}] (weaveScore=${weaveVerify.weaveScore}/100). Follow surgicalWorkorders + agentActions using your file-editing tools, verify with bla_verify_weave, then run bla_harden with weave_decoys:true and require_agent_weave:true.`,
|
||||
: staleBuildMessage ??
|
||||
`Host-Agent source surgery pending on [${unwovenSourceFiles.join(", ")}] (weaveScore=${weaveVerify.weaveScore}/100). Follow surgicalWorkorders + agentActions using your file-editing tools, verify with bla_verify_weave, then run bla_harden with weave_decoys:true and require_agent_weave:true.`,
|
||||
};
|
||||
} else if (options.requireAgentWeave === true) {
|
||||
agentWeaveAssessment = {
|
||||
weaveVerified: false,
|
||||
weaveScore: 0,
|
||||
unwovenSourceFiles: ["(no verifiable source files found)"],
|
||||
agentActions: [
|
||||
{
|
||||
priority: "high",
|
||||
file: ".",
|
||||
checkId: "customer-entry-edges",
|
||||
instruction:
|
||||
"require_agent_weave is enabled, but no verifiable JS/TS/HTML/Python/C/Rust/Go source files were found in the target directory. Point bla_verify_weave at your source directory before running bla_harden.",
|
||||
verifyTool: "bla_verify_weave",
|
||||
},
|
||||
],
|
||||
surgicalWorkorders: {},
|
||||
agentPlaybookDirective:
|
||||
"require_agent_weave refused: no verifiable source files were found in the target directory.",
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.requireAgentWeave === true) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
agentWeaveAssessment = {
|
||||
weaveVerified: false,
|
||||
weaveScore: 0,
|
||||
unwovenSourceFiles: ["(weave verification error)"],
|
||||
agentActions: [
|
||||
{
|
||||
priority: "high",
|
||||
file: ".",
|
||||
checkId: "crown-jewel-entanglement",
|
||||
instruction: `verifyWeaveTarget failed (${msg}); fix source syntax/access issues and re-run bla_verify_weave before bla_harden.`,
|
||||
verifyTool: "bla_verify_weave",
|
||||
},
|
||||
],
|
||||
surgicalWorkorders: {},
|
||||
agentPlaybookDirective: `require_agent_weave refused because weave verification threw an error: ${msg}`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
/* best-effort weave assessment */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1121,7 +1303,7 @@ export function hardenProject(
|
||||
entryPath: basename(entryAbs),
|
||||
entrySource,
|
||||
sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
carrier: refineJsCarrierForRuntimePaths(
|
||||
detectJsCarrierForSource(entrySource, entryAbs),
|
||||
[entryAbs, jsEntry.inputPath],
|
||||
@@ -1165,7 +1347,7 @@ export function hardenProject(
|
||||
entryPath: basename(entryAbs),
|
||||
entrySource,
|
||||
sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
});
|
||||
if (bound) {
|
||||
writeFileAtomicSync(entryAbs, bound.code, "utf8", {
|
||||
@@ -1204,7 +1386,7 @@ export function hardenProject(
|
||||
entryPath: basename(entryAbs),
|
||||
entryBytes,
|
||||
sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
});
|
||||
if (bound) {
|
||||
writeFileAtomicSync(entryAbs, bound.bytes, undefined, {
|
||||
@@ -1245,7 +1427,7 @@ export function hardenProject(
|
||||
entryPath: basename(entryAbs),
|
||||
entryBytes,
|
||||
sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
});
|
||||
if (bound) {
|
||||
writeFileAtomicSync(entryAbs, bound.bytes, undefined, {
|
||||
@@ -1287,7 +1469,7 @@ export function hardenProject(
|
||||
entryPath: basename(entryAbs),
|
||||
entryBytes,
|
||||
sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
});
|
||||
if (bound) {
|
||||
writeFileAtomicSync(entryAbs, bound.bytes, undefined, {
|
||||
@@ -1329,7 +1511,7 @@ export function hardenProject(
|
||||
entryPath: basename(entryAbs),
|
||||
entryBytes,
|
||||
sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
});
|
||||
if (bound) {
|
||||
writeFileAtomicSync(entryAbs, bound.bytes, undefined, {
|
||||
@@ -1373,7 +1555,7 @@ export function hardenProject(
|
||||
entryPath: basename(entryAbs),
|
||||
entryBytes,
|
||||
sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
});
|
||||
if (bound) {
|
||||
writeFileAtomicSync(entryAbs, bound.bytes, undefined, {
|
||||
@@ -1422,7 +1604,7 @@ export function hardenProject(
|
||||
entryPath: basename(entryAbs),
|
||||
entryBytes,
|
||||
sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
});
|
||||
if (bound) {
|
||||
writeFileAtomicSync(entryAbs, bound.bytes, undefined, {
|
||||
@@ -1467,7 +1649,7 @@ export function hardenProject(
|
||||
entryPath: entryLabel,
|
||||
entryBytes: readFileSync(entryAbs),
|
||||
sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
});
|
||||
if (bound) {
|
||||
writeFileAtomicSync(
|
||||
@@ -1504,7 +1686,7 @@ export function hardenProject(
|
||||
);
|
||||
if (!bridge) continue;
|
||||
const entryLabel = basename(entryAbs);
|
||||
const seedTag = String(options.seed ?? runId);
|
||||
const seedTag = derivePublicSidecarSeedTag(String(options.seed ?? runId));
|
||||
const hasNote = members.some(
|
||||
(m) => m.relativePath === ASAR_SIDECAR_ARCHIVE_NOTE_PATH,
|
||||
);
|
||||
@@ -1600,7 +1782,7 @@ export function hardenProject(
|
||||
const plan = planSidecarEntanglement({
|
||||
entryPath: entry.relativePath.replaceAll("\\", "/"),
|
||||
sidecarPaths: sidecars,
|
||||
seedTag: String(options.seed ?? runId),
|
||||
seedTag: derivePublicSidecarSeedTag(String(options.seed ?? runId)),
|
||||
baseDir: outputRoot,
|
||||
});
|
||||
const entryRel = entry.relativePath.replaceAll("\\", "/");
|
||||
|
||||
@@ -67,20 +67,20 @@ const MAX_JS_FILES = 48;
|
||||
const MAX_SCAN_CHARS = 800_000;
|
||||
|
||||
const CREATE_CIPHER_IV =
|
||||
/\bcreate(?:Decipher|Cipher)iv\b|\.create(?:Decipher|Cipher)iv\s*\(/;
|
||||
/\bcreate(?:Decipher|Cipher)iv\b|\.create(?:Decipher|Cipher)iv\s*\(|\bsubtle\.(?:decrypt|encrypt|unwrapKey|wrapKey)\s*\(/;
|
||||
|
||||
/** Hex/base64 wrap-key material shapes (R4 WRAP_KEY_HEX + Buffer.from(..., "hex")). */
|
||||
/** Hex/base64 wrap-key material shapes (R4 WRAP_KEY_HEX + Buffer.from(..., "hex") + WebCrypto importKey("raw")). */
|
||||
const WRAP_KEY_NAME =
|
||||
/\b(?:WRAP_KEY|AES_KEY|SEAL_KEY|UNWRAP_KEY|BLOB_KEY)(?:_HEX|_B64|_BASE64|_BYTES)?\b/;
|
||||
|
||||
const BUFFER_FROM_HEX_B64 =
|
||||
/Buffer\.from\s*\(\s*[^,)]+?\s*,\s*['"](?:hex|base64)['"]\s*\)/;
|
||||
/Buffer\.from\s*\(\s*[^,)]+?\s*,\s*['"](?:hex|base64)['"]\s*\)|\bsubtle\.importKey\s*\(\s*['"]raw['"]/;
|
||||
|
||||
/** AES-256 key as a 64-hex string literal (or AES-128 32-hex). */
|
||||
const HEX_KEY_LITERAL = /['"][0-9a-fA-F]{32}(?:[0-9a-fA-F]{32})?['"]/;
|
||||
|
||||
const AES_ALGO =
|
||||
/['"]aes-(?:128|192|256)-(?:ctr|cbc|gcm)['"]/i;
|
||||
/['"]aes-(?:(?:128|192|256)-(?:ctr|cbc|gcm)|ctr|cbc|gcm|kw)['"]/i;
|
||||
|
||||
/** Fixed 4-byte sealed hdr beacons (R4 D17EA004 and generic Buffer.from("........","hex")). */
|
||||
const FIXED_HDR_HEX =
|
||||
|
||||
@@ -72,7 +72,7 @@ const MAX_FILES = 48;
|
||||
const MAX_SCAN_CHARS = 800_000;
|
||||
|
||||
const TARGET_BASENAME =
|
||||
/^(?:panel\.html?|license\.cjs|license\.js|vault\.cjs|gate\.cjs)$/i;
|
||||
/^(?:panel\.html?|license\.cjs|license\.js|vault\.cjs|vault\.js|gate\.cjs|gate\.js|auth\.cjs|auth\.js|entitlement\.cjs|entitlement\.js|activate\.cjs|activate\.js)$/i;
|
||||
const SCAN_EXT = /\.(?:html?|[cm]?js|tsx?|mts|cts)$/i;
|
||||
|
||||
/** Safe UI / ABI tokens that must stay greppable. */
|
||||
@@ -283,12 +283,18 @@ function walkTargets(root: string, depth: number, out: string[]): void {
|
||||
if (SKIP_DIR_NAMES.has(ent.name)) continue;
|
||||
walkTargets(full, depth + 1, out);
|
||||
} else if (ent.isFile()) {
|
||||
if (
|
||||
/\.d\.ts$/i.test(ent.name) ||
|
||||
/\.(?:test|spec)\.[cm]?[jt]sx?$/i.test(ent.name)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (TARGET_BASENAME.test(ent.name) || SCAN_EXT.test(ent.name)) {
|
||||
// Prefer entitlement-shaped basenames; still accept other JS/HTML but
|
||||
// only if basename matches target OR path contains panel/license/vault.
|
||||
// only if basename matches target OR path contains panel/license/vault/auth/gate/entitlement.
|
||||
if (
|
||||
TARGET_BASENAME.test(ent.name) ||
|
||||
/(?:^|\/)(?:panel|license|vault)[^/]*$/i.test(ent.name)
|
||||
/(?:^|\/)(?:panel|license|vault|auth|gate|entitlement)[^/]*$/i.test(ent.name)
|
||||
) {
|
||||
out.push(full);
|
||||
}
|
||||
|
||||
+12
-11
@@ -95,6 +95,7 @@ import { finalizeSelfSealSelfDigest } from "../shields/runtime/self-seal.js";
|
||||
import {
|
||||
ASAR_SIDECAR_ARCHIVE_NOTE_PATH,
|
||||
BUN_SIDECAR_COMPANION_SUFFIX,
|
||||
derivePublicSidecarSeedTag,
|
||||
entangleAsarEntryWithSidecars,
|
||||
entangleAsarMainJsWithSidecars,
|
||||
entangleBunEntryWithSidecars,
|
||||
@@ -198,7 +199,7 @@ function applySidecarEntangleToJs(
|
||||
entryPath: entryLabel,
|
||||
entrySource: source,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
carrier,
|
||||
});
|
||||
@@ -234,7 +235,7 @@ function applySidecarEntangleToPython(
|
||||
entryPath: entryLabel,
|
||||
entrySource: source,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (!bound) return { code: source, applied: false };
|
||||
@@ -269,7 +270,7 @@ function applySidecarEntangleToWasm(
|
||||
entryPath: entryLabel,
|
||||
entryBytes: wasmBytes,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (!bound) return { buffer: wasmBytes, applied: false };
|
||||
@@ -304,7 +305,7 @@ function applySidecarEntangleToPyc(
|
||||
entryPath: entryLabel,
|
||||
entryBytes: pycBytes,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (!bound) return { buffer: pycBytes, applied: false };
|
||||
@@ -339,7 +340,7 @@ function applySidecarEntangleToGguf(
|
||||
entryPath: entryLabel,
|
||||
entryBytes: ggufBytes,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (!bound) return { buffer: ggufBytes, applied: false };
|
||||
@@ -374,7 +375,7 @@ function applySidecarEntangleToSafetensors(
|
||||
entryPath: entryLabel,
|
||||
entryBytes: safetensorsBytes,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (!bound) return { buffer: safetensorsBytes, applied: false };
|
||||
@@ -409,7 +410,7 @@ function applySidecarEntangleToDex(
|
||||
entryPath: entryLabel,
|
||||
entryBytes: dexBytes,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (!bound) return { buffer: dexBytes, applied: false };
|
||||
@@ -444,7 +445,7 @@ function applySidecarEntangleToSqlite(
|
||||
entryPath: entryLabel,
|
||||
entryBytes: sqliteBytes,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (!bound) return { buffer: sqliteBytes, applied: false };
|
||||
@@ -981,7 +982,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
|
||||
entryPath: entryLabel,
|
||||
entryBytes: rawAsar,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (bound) {
|
||||
@@ -996,7 +997,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
|
||||
entryPath: entryLabel,
|
||||
expectedHex: bound.digest.hex,
|
||||
sidecarPaths: sidecars.map((s) => s.pathLabel),
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (withMain) {
|
||||
@@ -1183,7 +1184,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
|
||||
entryPath: entryLabel,
|
||||
entryBytes: res.buffer,
|
||||
sidecars,
|
||||
seedTag: String(seed),
|
||||
seedTag: derivePublicSidecarSeedTag(String(seed)),
|
||||
softFold: options.sidecarEntangleSoftFold === true,
|
||||
});
|
||||
if (bound) {
|
||||
|
||||
@@ -24,7 +24,8 @@ export type SealCommitmentFindingId =
|
||||
| "reversible-public-commitment"
|
||||
| "seal-offline-oracle-package"
|
||||
| "public-materialization-seed"
|
||||
| "public-key-digest-oracle";
|
||||
| "public-key-digest-oracle"
|
||||
| "seal-oversized-sidecar";
|
||||
|
||||
export type SealCommitmentSeverity = "warning" | "error";
|
||||
|
||||
@@ -87,7 +88,38 @@ const SKIP_DIR_NAMES = new Set([
|
||||
|
||||
const MAX_WALK_DEPTH = 6;
|
||||
const MAX_SEAL_FILES = 32;
|
||||
const MAX_JSON_BYTES = 400_000;
|
||||
const MAX_JSON_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
function buildOversizedSealReport(
|
||||
pathLabel: string,
|
||||
byteLength: number,
|
||||
): SealCommitmentReport {
|
||||
if (!looksLikeSealFileName(pathLabel)) {
|
||||
return {
|
||||
schema: SEAL_COMMITMENT_SCHEMA,
|
||||
path: pathLabel,
|
||||
findings: [],
|
||||
looksExposed: false,
|
||||
shouldRefuseBankrupt: false,
|
||||
oneLineAdvice: `Oversized non-seal file (${byteLength} bytes > ${MAX_JSON_BYTES}) — seal-commitment lint skipped.`,
|
||||
};
|
||||
}
|
||||
const f = finding(
|
||||
"seal-oversized-sidecar",
|
||||
"error",
|
||||
`Seal sidecar exceeds ${MAX_JSON_BYTES} bytes (${byteLength} bytes) — refusing unverified oversized seal JSON (fail-closed against padding bypass).`,
|
||||
`bytes=${byteLength} limit=${MAX_JSON_BYTES}`,
|
||||
);
|
||||
return {
|
||||
schema: SEAL_COMMITMENT_SCHEMA,
|
||||
path: pathLabel,
|
||||
findings: [f],
|
||||
looksExposed: true,
|
||||
shouldRefuseBankrupt: true,
|
||||
oneLineAdvice:
|
||||
"ERROR: Oversized seal sidecar exceeds safe inspection limit — shrink or omit plaintext seal JSON, or pass allowPlaintextSeal (lab fixture only).",
|
||||
};
|
||||
}
|
||||
|
||||
function finding(
|
||||
id: SealCommitmentFindingId,
|
||||
@@ -186,12 +218,15 @@ export function lintSealCommitmentSource(
|
||||
options: { readonly path?: string } = {},
|
||||
): SealCommitmentReport {
|
||||
const pathLabel = options.path ?? "<memory>";
|
||||
const byteLen = Buffer.byteLength(source, "utf8");
|
||||
if (byteLen > MAX_JSON_BYTES) {
|
||||
return buildOversizedSealReport(pathLabel, byteLen);
|
||||
}
|
||||
const findings: SealCommitmentFinding[] = [];
|
||||
const text = source.length > MAX_JSON_BYTES ? source.slice(0, MAX_JSON_BYTES) : source;
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
parsed = JSON.parse(source);
|
||||
} catch {
|
||||
return {
|
||||
schema: SEAL_COMMITMENT_SCHEMA,
|
||||
@@ -342,6 +377,10 @@ export function lintSealCommitmentFile(filePath: string): SealCommitmentReport {
|
||||
if (!existsSync(abs)) {
|
||||
throw new Error(`seal-commitment target not found: ${abs}`);
|
||||
}
|
||||
const st = statSync(abs);
|
||||
if (st.size > MAX_JSON_BYTES) {
|
||||
return buildOversizedSealReport(abs, st.size);
|
||||
}
|
||||
const source = readFileSync(abs, "utf8");
|
||||
return lintSealCommitmentSource(source, { path: abs });
|
||||
}
|
||||
|
||||
+29
-1
@@ -12,6 +12,7 @@ import {
|
||||
DEFENSE_SCORE_DISCLAIMER,
|
||||
} from "./defense-score-honesty.js";
|
||||
import { inspectNativeBinary } from "../shields/formats/native.js";
|
||||
import { verifySelfSealSelfDigest } from "../shields/runtime/self-seal.js";
|
||||
|
||||
export interface VerifyTargetOptions {
|
||||
readonly selfSealEnabled?: boolean;
|
||||
@@ -115,6 +116,33 @@ export function verifyTarget(
|
||||
baselineSource,
|
||||
});
|
||||
|
||||
let effectiveSelfSealEnabled = options.selfSealEnabled === true;
|
||||
if (
|
||||
effectiveSelfSealEnabled &&
|
||||
(afterAudit.detectedFormat === "javascript" ||
|
||||
afterAudit.detectedFormat === "typescript")
|
||||
) {
|
||||
try {
|
||||
const targetBytes = readFileSync(absTarget);
|
||||
if (/\bselfExpected\s*=/.test(targetBytes.toString("latin1"))) {
|
||||
const sealVerify = verifySelfSealSelfDigest(targetBytes);
|
||||
if (!sealVerify.verified) {
|
||||
effectiveSelfSealEnabled = false;
|
||||
checks.push({
|
||||
id: "self-seal-digest-integrity",
|
||||
name: "Self-Seal Canonical Self-Digest Integrity",
|
||||
targetReaComponent: "runtime/self-seal.ts",
|
||||
passed: false,
|
||||
details:
|
||||
"Embedded selfExpected canonical SHA-256 digest failed offline verification (file tampered or unfinalized after self-seal)",
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* ignore unreadable path */
|
||||
}
|
||||
}
|
||||
|
||||
const passedCount = checks.filter((c) => c.passed).length;
|
||||
// Raw score = Counter-REA gate pass-rate + exposure drop only.
|
||||
// Soft-capped below when known gaps still apply (issue #40.6).
|
||||
@@ -141,7 +169,7 @@ export function verifyTarget(
|
||||
|
||||
const honesty = applyDefenseScoreHonesty(rawDefenseScore, {
|
||||
detectedFormat: afterAudit.detectedFormat,
|
||||
selfSealEnabled: options.selfSealEnabled === true,
|
||||
selfSealEnabled: effectiveSelfSealEnabled,
|
||||
sidecarEntangleEnabled: options.sidecarEntangleEnabled === true,
|
||||
wasmExportRenameApplied: options.wasmExportRenameApplied === true,
|
||||
numericTemplateLeakKnown: options.numericTemplateLeakKnown === true,
|
||||
|
||||
@@ -580,6 +580,7 @@ export {
|
||||
stripSqliteSidecarSchemaComment,
|
||||
stripWasmSidecarCustomSection,
|
||||
SIDECAR_ENTANGLE_SCHEMA,
|
||||
derivePublicSidecarSeedTag,
|
||||
WASM_SIDECAR_SECTION_NAME,
|
||||
BUN_SIDECAR_COMPANION_SUFFIX,
|
||||
BUN_SIDECAR_COMPANION_KIND,
|
||||
|
||||
+244
-31
@@ -1,5 +1,6 @@
|
||||
import { BLA_IDENTITY } from "../identity.js";
|
||||
import { initBlaConfig } from "../core/config.js";
|
||||
import { verifyManifestFile } from "../core/manifest-verify.js";
|
||||
import { inspectReleaseExposure } from "../core/release-exposure.js";
|
||||
import type { ProtectionIntensity } from "../core/types.js";
|
||||
import { auditTarget } from "../engine/auditor.js";
|
||||
@@ -143,9 +144,17 @@ export interface McpPropertySchema {
|
||||
readonly items?: { readonly type: "string" | "boolean" | "number" };
|
||||
}
|
||||
|
||||
export interface McpToolAnnotations {
|
||||
readonly readOnlyHint?: boolean;
|
||||
readonly destructiveHint?: boolean;
|
||||
readonly idempotentHint?: boolean;
|
||||
readonly openWorldHint?: boolean;
|
||||
}
|
||||
|
||||
export interface McpToolDefinition {
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
readonly annotations?: McpToolAnnotations;
|
||||
readonly inputSchema: {
|
||||
readonly type: "object";
|
||||
readonly properties: Readonly<Record<string, McpPropertySchema | undefined>>;
|
||||
@@ -197,7 +206,30 @@ export const SUPPORTED_MCP_PROTOCOL_VERSIONS = Object.freeze([
|
||||
"2025-03-26",
|
||||
] as const);
|
||||
|
||||
export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
|
||||
const MUTATING_MCP_TOOLS: ReadonlySet<string> = new Set([
|
||||
"bla_harden",
|
||||
"bla_defend",
|
||||
"bla_protect",
|
||||
"bla_init",
|
||||
"bla_encrypt_strings",
|
||||
"bla_bind_scope",
|
||||
"bla_redteam_report",
|
||||
]);
|
||||
|
||||
function withToolAnnotations(tool: McpToolDefinition): McpToolDefinition {
|
||||
const isMutating = MUTATING_MCP_TOOLS.has(tool.name);
|
||||
return {
|
||||
...tool,
|
||||
annotations: {
|
||||
readOnlyHint: !isMutating,
|
||||
destructiveHint: false,
|
||||
idempotentHint: !isMutating || tool.name === "bla_redteam_report",
|
||||
openWorldHint: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const RAW_BLA_MCP_TOOLS: readonly McpToolDefinition[] = [
|
||||
{
|
||||
name: "bla_harden",
|
||||
description:
|
||||
@@ -301,6 +333,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
|
||||
description:
|
||||
"Allow bankrupt harden/protect despite WASM seal.revision XOR known-plaintext entitlement packs. Default false — refuse (red-blue round-7). Prefer one-way mask KDFs; keep public digests out of masked plaintext.",
|
||||
},
|
||||
allow_release_hygiene_leak: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Lab escape: allow bankrupt/maximum harden despite leaked SOLUTION/writeup notes, populated .env secrets, SSH/PEM private keys, or unstripped .pdb/.dSYM/.dwp debug databases. Default false — refuse.",
|
||||
},
|
||||
seed: {
|
||||
type: "string",
|
||||
description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc",
|
||||
@@ -458,6 +495,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
|
||||
description:
|
||||
"Allow bankrupt harden/protect despite WASM seal.revision XOR known-plaintext entitlement packs. Default false — refuse (red-blue round-7). Prefer one-way mask KDFs; keep public digests out of masked plaintext.",
|
||||
},
|
||||
allow_release_hygiene_leak: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Lab escape: allow bankrupt/maximum defend despite leaked SOLUTION/writeup notes, populated .env secrets, SSH/PEM private keys, or unstripped .pdb/.dSYM/.dwp debug databases. Default false — refuse.",
|
||||
},
|
||||
seed: {
|
||||
type: "string",
|
||||
description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc",
|
||||
@@ -657,6 +699,21 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
|
||||
description:
|
||||
"Optional harden run_id; when paired with summary_path, must match the summary or the tool errors.",
|
||||
},
|
||||
manifest_path: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional path to a .bla-manifest.json attestation file to cryptographically verify alongside the artifact.",
|
||||
},
|
||||
public_key_path: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional path to a pinned Ed25519 public key PEM file used when verifying manifest_path.",
|
||||
},
|
||||
require_pinned_key: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"When true with manifest_path, fails verification unless a pinned public_key_path is supplied and matches.",
|
||||
},
|
||||
},
|
||||
required: ["target_path"],
|
||||
additionalProperties: false,
|
||||
@@ -775,7 +832,7 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
|
||||
{
|
||||
name: "bla_verify_weave",
|
||||
description:
|
||||
"Read-only structural weave verifier (bla-weave-verify/v1): validates Agent-authored source weave edits and hardened outputs against WEAVE_ACCEPTANCE_TESTS (no forbidden banners, mixed mundane/security stems, shared-state mutation across functions, customer entry call-graph reachability, opaque-true entanglement, and filter resistance). Returns weaveScore and actionable agentActions for autonomous self-repair.",
|
||||
"Read-only structural weave verifier (bla-weave-verify/v1): validates Agent-authored source weave edits and hardened outputs against all 7 WEAVE_ACCEPTANCE_TESTS (no forbidden banners, mixed mundane/security stems, shared-state mutation across functions, customer entry call-graph reachability, opaque-true entanglement, filter resistance, and crown-jewel entanglement). Returns weaveScore and actionable agentActions for autonomous self-repair.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -836,6 +893,10 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
|
||||
type: "boolean",
|
||||
description: "Treat lane-independent gates as non-blocking (lab only)",
|
||||
},
|
||||
allow_stable_panel_derive: {
|
||||
type: "boolean",
|
||||
description: "Keep stable __vaultPanelDerive_* / deriveLocal ABI without rewrite warning (lab only)",
|
||||
},
|
||||
allow_panel_offline_oracle: {
|
||||
type: "boolean",
|
||||
description: "Treat panel offline oracle as non-blocking (lab only)",
|
||||
@@ -872,6 +933,10 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
|
||||
type: "string",
|
||||
description: "Path to a UTF-8 source file to lint (JS/TS/Python-like)",
|
||||
},
|
||||
allow_lane_independent: {
|
||||
type: "boolean",
|
||||
description: "Lab escape: report findings without refusing",
|
||||
},
|
||||
},
|
||||
required: ["path"],
|
||||
additionalProperties: false,
|
||||
@@ -920,6 +985,14 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
|
||||
type: "string",
|
||||
description: "Path to a JS/TS/HTML file to lint",
|
||||
},
|
||||
allow_stable_panel_derive: {
|
||||
type: "boolean",
|
||||
description: "Lab escape: allow stable __vaultPanelDerive_* / deriveLocal ABI",
|
||||
},
|
||||
allow_panel_offline_oracle: {
|
||||
type: "boolean",
|
||||
description: "Lab escape: allow deriveLocal + panelTokenSha256 offline oracle combo",
|
||||
},
|
||||
},
|
||||
required: ["path"],
|
||||
additionalProperties: false,
|
||||
@@ -1221,7 +1294,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
];
|
||||
|
||||
export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze(
|
||||
RAW_BLA_MCP_TOOLS.map(withToolAnnotations),
|
||||
);
|
||||
|
||||
|
||||
export interface McpResourceDefinition {
|
||||
@@ -1448,6 +1525,9 @@ function runDefend(handlers: McpEngineHandlers, args: Record<string, unknown>):
|
||||
...(args.allow_wasm_seal_xor_known_plaintext === true
|
||||
? { allowWasmSealXorKnownPlaintext: true }
|
||||
: {}),
|
||||
...(args.allow_release_hygiene_leak === true
|
||||
? { allowReleaseHygieneLeak: true }
|
||||
: {}),
|
||||
...(typeof args.seed === "string" ? { seed: args.seed } : {}),
|
||||
});
|
||||
}
|
||||
@@ -1493,6 +1573,9 @@ function runProtect(handlers: McpEngineHandlers, args: Record<string, unknown>):
|
||||
...(args.allow_wasm_seal_xor_known_plaintext === true
|
||||
? { allowWasmSealXorKnownPlaintext: true }
|
||||
: {}),
|
||||
...(args.allow_release_hygiene_leak === true
|
||||
? { allowReleaseHygieneLeak: true }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1546,6 +1629,9 @@ function runPackagingGatesLint(args: Record<string, unknown>): PackagingGatesRep
|
||||
...(args.allow_lane_independent === true
|
||||
? { allowLaneIndependentGates: true }
|
||||
: {}),
|
||||
...(args.allow_stable_panel_derive === true
|
||||
? { allowStablePanelDeriveAbi: true }
|
||||
: {}),
|
||||
...(args.allow_panel_offline_oracle === true
|
||||
? { allowPanelOfflineOracle: true }
|
||||
: {}),
|
||||
@@ -2106,8 +2192,13 @@ export async function handleMcpRequest(
|
||||
payload = confirmationRequiredPayload(name, preOverwrite);
|
||||
} else {
|
||||
const wasmPreserveExports = stringListArg(args.wasm_preserve_exports);
|
||||
const abortCtl = new AbortController();
|
||||
const preAborted =
|
||||
typeof req.id === "string" || typeof req.id === "number"
|
||||
? preAbortedHardenRequests.get(req.id)
|
||||
: undefined;
|
||||
const abortCtl = preAborted ?? new AbortController();
|
||||
if (typeof req.id === "string" || typeof req.id === "number") {
|
||||
preAbortedHardenRequests.delete(req.id);
|
||||
activeHardenAborts.set(req.id, abortCtl);
|
||||
}
|
||||
const progressToken = progressTokenOf(req);
|
||||
@@ -2118,11 +2209,12 @@ export async function handleMcpRequest(
|
||||
dryRun,
|
||||
...(maxArtifacts !== undefined ? { maxArtifacts } : {}),
|
||||
...(outputDirectory !== undefined ? { outputDirectory } : {}),
|
||||
intensity:
|
||||
typeof args.intensity === "string"
|
||||
? (args.intensity as ProtectionIntensity)
|
||||
: "bankrupt",
|
||||
emitManifest: Boolean(args.emit_manifest) || args.sign_manifest === true,
|
||||
...(typeof args.intensity === "string"
|
||||
? { intensity: args.intensity as ProtectionIntensity }
|
||||
: {}),
|
||||
...(typeof args.emit_manifest === "boolean" || args.sign_manifest === true
|
||||
? { emitManifest: Boolean(args.emit_manifest) || args.sign_manifest === true }
|
||||
: {}),
|
||||
...(args.sign_manifest === true
|
||||
? {
|
||||
signManifest: true,
|
||||
@@ -2130,12 +2222,20 @@ export async function handleMcpRequest(
|
||||
typeof args.manifest_key_path === "string" ? args.manifest_key_path : "",
|
||||
}
|
||||
: {}),
|
||||
llmDirectives: Boolean(args.llm_directives),
|
||||
weaveDecoys: Boolean(args.weave_decoys),
|
||||
selfSeal: Boolean(args.self_seal),
|
||||
sidecarEntangle: Boolean(args.sidecar_entangle),
|
||||
...(args.require_agent_weave === true
|
||||
? { requireAgentWeave: true }
|
||||
...(typeof args.llm_directives === "boolean"
|
||||
? { llmDirectives: args.llm_directives }
|
||||
: {}),
|
||||
...(typeof args.weave_decoys === "boolean"
|
||||
? { weaveDecoys: args.weave_decoys }
|
||||
: {}),
|
||||
...(typeof args.self_seal === "boolean"
|
||||
? { selfSeal: args.self_seal }
|
||||
: {}),
|
||||
...(typeof args.sidecar_entangle === "boolean"
|
||||
? { sidecarEntangle: args.sidecar_entangle }
|
||||
: {}),
|
||||
...(typeof args.require_agent_weave === "boolean"
|
||||
? { requireAgentWeave: args.require_agent_weave }
|
||||
: {}),
|
||||
...(wasmPreserveExports !== undefined ? { wasmPreserveExports } : {}),
|
||||
...(args.allow_lane_independent === true
|
||||
@@ -2258,6 +2358,7 @@ export async function handleMcpRequest(
|
||||
typeof args.original_path === "string" ? args.original_path : undefined,
|
||||
verifyHonestyOptions(args),
|
||||
);
|
||||
let verifyPayload: Record<string, unknown> = { ...verification };
|
||||
if (typeof args.summary_path === "string" && args.summary_path.trim().length > 0) {
|
||||
const lookup = readHardenRunSummary(
|
||||
args.summary_path as string,
|
||||
@@ -2265,8 +2366,8 @@ export async function handleMcpRequest(
|
||||
? (args.run_id as string)
|
||||
: undefined,
|
||||
);
|
||||
payload = {
|
||||
...verification,
|
||||
verifyPayload = {
|
||||
...verifyPayload,
|
||||
runCorrelation: {
|
||||
schema: "bla-run-correlation/v1",
|
||||
signature: "unsigned",
|
||||
@@ -2279,9 +2380,25 @@ export async function handleMcpRequest(
|
||||
throw new Error(
|
||||
"bla_verify: run_id requires summary_path so the id can be correlated against an on-disk harden summary",
|
||||
);
|
||||
} else {
|
||||
payload = verification;
|
||||
}
|
||||
if (typeof args.manifest_path === "string" && args.manifest_path.trim().length > 0) {
|
||||
const manifestVerification = verifyManifestFile(
|
||||
args.manifest_path,
|
||||
typeof args.public_key_path === "string" && args.public_key_path.trim().length > 0
|
||||
? args.public_key_path
|
||||
: undefined,
|
||||
args.target_path as string,
|
||||
{ requirePinnedKey: args.require_pinned_key === true },
|
||||
);
|
||||
verifyPayload = {
|
||||
...verifyPayload,
|
||||
manifestVerification,
|
||||
};
|
||||
if (!manifestVerification.ok) {
|
||||
refused = true;
|
||||
}
|
||||
}
|
||||
payload = verifyPayload;
|
||||
} else if (name === "bla_benchmark") {
|
||||
payload = await handlers.runShowcaseBenchmark();
|
||||
} else if (name === "bla_emit_headers") {
|
||||
@@ -2335,11 +2452,16 @@ export async function handleMcpRequest(
|
||||
plaintextSecrets: details.plaintextSecrets.length,
|
||||
integrityCoverage: details.integrityCoverage.length,
|
||||
bindScope: details.bindScope.length,
|
||||
releaseHygiene: details.releaseHygiene.length,
|
||||
},
|
||||
};
|
||||
refused = full.shouldRefuseBankrupt;
|
||||
} else if (name === "bla_lint_lanes") {
|
||||
payload = runLintLanes(args);
|
||||
refused =
|
||||
args.allow_lane_independent === true
|
||||
? false
|
||||
: (payload as LaneIndependenceReport).looksLaneIndependent;
|
||||
} else if (name === "bla_lint_seal") {
|
||||
payload = runLintSeal(args);
|
||||
refused = (payload as SealCommitmentReport).shouldRefuseBankrupt;
|
||||
@@ -2348,9 +2470,10 @@ export async function handleMcpRequest(
|
||||
refused = (payload as WasmParamCarrierReport).shouldRefuseBankrupt;
|
||||
} else if (name === "bla_lint_panel_derive") {
|
||||
payload = runLintPanelDerive(args);
|
||||
const panelRep = payload as PanelDeriveAbiReport;
|
||||
refused =
|
||||
(payload as PanelDeriveAbiReport).shouldRefuseBankrupt ||
|
||||
(payload as PanelDeriveAbiReport).shouldRewriteOrRefuse;
|
||||
(panelRep.shouldRefuseBankrupt && args.allow_panel_offline_oracle !== true) ||
|
||||
(panelRep.shouldRewriteOrRefuse && args.allow_stable_panel_derive !== true);
|
||||
} else if (name === "bla_lint_js_aes_unwrap") {
|
||||
payload = runLintJsAesUnwrap(args);
|
||||
refused = (payload as JsAesUnwrapReport).shouldRefuseBankrupt;
|
||||
@@ -2379,6 +2502,7 @@ export async function handleMcpRequest(
|
||||
? "No integrity-coverage.json found (not an error — emit via harden --self-seal)."
|
||||
: "Integrity coverage matrix OK.",
|
||||
};
|
||||
refused = allow ? false : anyRefuse;
|
||||
} else if (name === "bla_run_lookup") {
|
||||
payload = readHardenRunSummary(
|
||||
args.summary_path as string,
|
||||
@@ -2555,6 +2679,9 @@ export async function handleMcpRequest(
|
||||
}
|
||||
}
|
||||
|
||||
/** Queued bla_harden requests cancelled before their serial turn started. */
|
||||
const preAbortedHardenRequests = new Map<string | number, AbortController>();
|
||||
|
||||
/**
|
||||
* Largest single stdio line accepted before the client is treated as
|
||||
* misbehaving. Measured in UTF-16 code units (`String.length`, matching what
|
||||
@@ -2572,18 +2699,18 @@ export interface StdioLineProcessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Newline-delimited stdio line splitter with a hard per-line size cap so a
|
||||
* client that streams an unterminated giant line cannot grow the buffer without
|
||||
* bound. Blank lines and `Content-Length:` framing lines are skipped, matching
|
||||
* the previous server behavior.
|
||||
* Dual-mode stdio frame splitter supporting both newline-delimited JSON-RPC 2.0
|
||||
* and LSP/MCP `Content-Length: <bytes>\r\n\r\n<body>` byte-counted frames with
|
||||
* a hard per-message size cap.
|
||||
*/
|
||||
export function createStdioLineProcessor(hooks: StdioLineProcessorHooks): StdioLineProcessor {
|
||||
let buffer = "";
|
||||
let discarding = false;
|
||||
let pendingContentBytes: number | null = null;
|
||||
let awaitingHeaderBlankLine = false;
|
||||
return {
|
||||
push(chunk: string): void {
|
||||
if (discarding) {
|
||||
// The remainder of an oversized line is still in flight; resume at its newline.
|
||||
const nl = chunk.indexOf("\n");
|
||||
if (nl < 0) return;
|
||||
discarding = false;
|
||||
@@ -2591,19 +2718,73 @@ export function createStdioLineProcessor(hooks: StdioLineProcessorHooks): StdioL
|
||||
} else {
|
||||
buffer += chunk;
|
||||
}
|
||||
let newlineIdx: number;
|
||||
while ((newlineIdx = buffer.indexOf("\n")) >= 0) {
|
||||
|
||||
while (buffer.length > 0) {
|
||||
if (!awaitingHeaderBlankLine && pendingContentBytes !== null) {
|
||||
const byteLen = Buffer.byteLength(buffer, "utf8");
|
||||
if (byteLen >= pendingContentBytes) {
|
||||
const rawBuf = Buffer.from(buffer, "utf8");
|
||||
const body = rawBuf.subarray(0, pendingContentBytes).toString("utf8").trim();
|
||||
buffer = rawBuf.subarray(pendingContentBytes).toString("utf8");
|
||||
pendingContentBytes = null;
|
||||
if (body.length > MAX_STDIO_LINE_CHARS) {
|
||||
hooks.onOversizedLine?.();
|
||||
continue;
|
||||
}
|
||||
if (body.length > 0) {
|
||||
hooks.onLine(body);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Fallback when a newline-delimited message arrives shorter than a stale/skipped header.
|
||||
if (buffer.indexOf("\n") >= 0) {
|
||||
pendingContentBytes = null;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const newlineIdx = buffer.indexOf("\n");
|
||||
if (newlineIdx < 0) break;
|
||||
const line = buffer.slice(0, newlineIdx).trim();
|
||||
buffer = buffer.slice(newlineIdx + 1);
|
||||
if (!line || line.startsWith("Content-Length:")) continue;
|
||||
|
||||
if (awaitingHeaderBlankLine) {
|
||||
if (line === "") {
|
||||
awaitingHeaderBlankLine = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!line) continue;
|
||||
const clMatch = /^Content-Length:\s*(\d+)$/i.exec(line);
|
||||
if (clMatch) {
|
||||
const parsedBytes = Number.parseInt(clMatch[1]!, 10);
|
||||
if (!Number.isFinite(parsedBytes) || parsedBytes > MAX_STDIO_LINE_CHARS * 4) {
|
||||
pendingContentBytes = null;
|
||||
awaitingHeaderBlankLine = false;
|
||||
buffer = "";
|
||||
discarding = true;
|
||||
hooks.onOversizedLine?.();
|
||||
return;
|
||||
}
|
||||
pendingContentBytes = parsedBytes;
|
||||
awaitingHeaderBlankLine = true;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("Content-Type:")) continue;
|
||||
|
||||
if (line.length > MAX_STDIO_LINE_CHARS) {
|
||||
hooks.onOversizedLine?.();
|
||||
continue;
|
||||
}
|
||||
hooks.onLine(line);
|
||||
}
|
||||
|
||||
if (buffer.length > MAX_STDIO_LINE_CHARS) {
|
||||
buffer = "";
|
||||
pendingContentBytes = null;
|
||||
awaitingHeaderBlankLine = false;
|
||||
discarding = true;
|
||||
hooks.onOversizedLine?.();
|
||||
}
|
||||
@@ -2612,13 +2793,14 @@ export function createStdioLineProcessor(hooks: StdioLineProcessorHooks): StdioL
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the BLA MCP server over stdio (supporting newline-delimited JSON-RPC 2.0).
|
||||
* Starts the BLA MCP server over stdio (supporting newline-delimited and Content-Length JSON-RPC 2.0).
|
||||
*/
|
||||
export function startMcpStdioServer(): void {
|
||||
let processingQueue = Promise.resolve();
|
||||
const queuedRequests = new Map<string | number, { cancelled: boolean; reason?: string }>();
|
||||
const processor = createStdioLineProcessor({
|
||||
onLine: (line: string) => {
|
||||
// Parse first so cancel can abort an in-flight harden without waiting
|
||||
// Parse first so cancel can abort an in-flight or queued harden without waiting
|
||||
// for the serial request queue (issue #75).
|
||||
let req: JsonRpcRequest;
|
||||
try {
|
||||
@@ -2636,10 +2818,37 @@ export function startMcpStdioServer(): void {
|
||||
return;
|
||||
}
|
||||
if (req.method === "notifications/cancelled") {
|
||||
const params = (req.params ?? {}) as {
|
||||
requestId?: string | number;
|
||||
reason?: string;
|
||||
};
|
||||
const rid = params.requestId;
|
||||
if (
|
||||
(typeof rid === "string" || typeof rid === "number") &&
|
||||
queuedRequests.has(rid)
|
||||
) {
|
||||
const entry = queuedRequests.get(rid)!;
|
||||
entry.cancelled = true;
|
||||
entry.reason = params.reason ?? "cancelled";
|
||||
}
|
||||
void handleMcpRequest(req);
|
||||
return;
|
||||
}
|
||||
const reqId =
|
||||
typeof req.id === "string" || typeof req.id === "number" ? req.id : undefined;
|
||||
if (reqId !== undefined) {
|
||||
queuedRequests.set(reqId, { cancelled: false });
|
||||
}
|
||||
processingQueue = processingQueue.then(async () => {
|
||||
const queuedState = reqId !== undefined ? queuedRequests.get(reqId) : undefined;
|
||||
if (reqId !== undefined) {
|
||||
queuedRequests.delete(reqId);
|
||||
if (queuedState?.cancelled) {
|
||||
const ctl = new AbortController();
|
||||
ctl.abort(queuedState.reason ?? "cancelled");
|
||||
preAbortedHardenRequests.set(reqId, ctl);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const res = await handleMcpRequest(req);
|
||||
if (res !== null) {
|
||||
@@ -2655,6 +2864,10 @@ export function startMcpStdioServer(): void {
|
||||
},
|
||||
};
|
||||
process.stdout.write(JSON.stringify(parseErr) + "\n");
|
||||
} finally {
|
||||
if (reqId !== undefined) {
|
||||
preAbortedHardenRequests.delete(reqId);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
+214
-11
@@ -390,6 +390,31 @@ function inspectCodexTomlDocument(
|
||||
let pendingKey: string | null = null;
|
||||
let pendingArrayBuffer = "";
|
||||
let bracketBalance = 0;
|
||||
let pendingMultilineQuote: '"""' | "'''" | null = null;
|
||||
let pendingMultilineKey: string | null = null;
|
||||
let pendingMultilineBuffer = "";
|
||||
|
||||
const findClosingTripleQuote = (text: string, quote: '"""' | "'''"): number => {
|
||||
if (quote === "'''") {
|
||||
return text.indexOf("'''");
|
||||
}
|
||||
let escaped = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i]!;
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\\") {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if (text.startsWith('"""', i)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
|
||||
const countArrayBracketsOutsideQuotes = (code: string): { delta: number; valid: boolean } => {
|
||||
let delta = 0;
|
||||
@@ -421,6 +446,66 @@ function inspectCodexTomlDocument(
|
||||
|
||||
for (let idx = 0; idx < lines.length; idx++) {
|
||||
const rawLine = lines[idx]!;
|
||||
if (pendingMultilineQuote !== null && pendingMultilineKey !== null) {
|
||||
const closePos = findClosingTripleQuote(rawLine, pendingMultilineQuote);
|
||||
if (closePos < 0) {
|
||||
pendingMultilineBuffer += "\n" + rawLine;
|
||||
continue;
|
||||
}
|
||||
const afterClose = stripTomlInlineComment(rawLine.slice(closePos + 3));
|
||||
if (afterClose.unclosedQuote || afterClose.code.length > 0) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Malformed TOML multiline string trailing content at line ${idx + 1}`,
|
||||
};
|
||||
}
|
||||
pendingMultilineBuffer += "\n" + rawLine.slice(0, closePos + 3);
|
||||
const targetMap = currentSection ? currentSection.assignments : topLevelAssignments;
|
||||
targetMap.set(pendingMultilineKey, pendingMultilineBuffer);
|
||||
pendingMultilineQuote = null;
|
||||
pendingMultilineKey = null;
|
||||
pendingMultilineBuffer = "";
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for TOML triple-quoted string assignments (`key = """...` or `key = '''...`)
|
||||
if (pendingKey === null && !rawLine.trimStart().startsWith("#") && !rawLine.trimStart().startsWith("[")) {
|
||||
const eqPos = rawLine.indexOf("=");
|
||||
if (eqPos > 0) {
|
||||
const candidateKey = rawLine.slice(0, eqPos).trim();
|
||||
const rhsTrimmed = rawLine.slice(eqPos + 1).trimStart();
|
||||
const tripleQuote: '"""' | "'''" | null = rhsTrimmed.startsWith('"""')
|
||||
? '"""'
|
||||
: rhsTrimmed.startsWith("'''")
|
||||
? "'''"
|
||||
: null;
|
||||
if (
|
||||
tripleQuote !== null &&
|
||||
(/^[A-Za-z0-9_.-]+$/.test(candidateKey) ||
|
||||
(candidateKey.startsWith('"') && candidateKey.endsWith('"')))
|
||||
) {
|
||||
const afterOpen = rhsTrimmed.slice(3);
|
||||
const closePos = findClosingTripleQuote(afterOpen, tripleQuote);
|
||||
if (closePos >= 0) {
|
||||
const afterClose = stripTomlInlineComment(afterOpen.slice(closePos + 3));
|
||||
if (afterClose.unclosedQuote || afterClose.code.length > 0) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Malformed TOML triple-quoted string at line ${idx + 1}`,
|
||||
};
|
||||
}
|
||||
const targetMap = currentSection ? currentSection.assignments : topLevelAssignments;
|
||||
targetMap.set(candidateKey, rhsTrimmed.slice(0, 3 + closePos + 3));
|
||||
continue;
|
||||
}
|
||||
pendingMultilineQuote = tripleQuote;
|
||||
pendingMultilineKey = candidateKey;
|
||||
pendingMultilineBuffer = rhsTrimmed;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const stripped = stripTomlInlineComment(rawLine);
|
||||
if (stripped.unclosedQuote) {
|
||||
return { ok: false, error: `Malformed TOML at line ${idx + 1}: unclosed string quote` };
|
||||
@@ -516,6 +601,12 @@ function inspectCodexTomlDocument(
|
||||
targetMap.set(key, val);
|
||||
}
|
||||
|
||||
if (pendingMultilineQuote !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Malformed TOML: unclosed multiline string for key '${pendingMultilineKey}'`,
|
||||
};
|
||||
}
|
||||
if (pendingKey !== null || bracketBalance !== 0) {
|
||||
return { ok: false, error: `Malformed TOML: unclosed multiline array for key '${pendingKey}'` };
|
||||
}
|
||||
@@ -663,13 +754,23 @@ export function writeCodexTomlMcp(
|
||||
}
|
||||
}
|
||||
|
||||
const existingSection = inspected.sections.find((s) => s.name === targetTable);
|
||||
const preservedAssignments: string[] = [];
|
||||
if (existingSection) {
|
||||
for (const [k, v] of existingSection.assignments.entries()) {
|
||||
if (k !== "command" && k !== "args") {
|
||||
preservedAssignments.push(`${k} = ${v}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const formattedSectionLines = [
|
||||
`[${targetTable}]`,
|
||||
`command = ${JSON.stringify(reg.command)}`,
|
||||
`args = [${reg.args.map((a) => JSON.stringify(a)).join(", ")}]`,
|
||||
...preservedAssignments,
|
||||
];
|
||||
|
||||
const existingSection = inspected.sections.find((s) => s.name === targetTable);
|
||||
if (existingSection) {
|
||||
// Preserve trailing comments before the next section header
|
||||
let replaceEnd = existingSection.endLineIndex;
|
||||
@@ -724,13 +825,103 @@ export function removeCodexTomlMcp(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses standard JSON or JSONC (`//` line comments, `/* ... *\/` block comments,
|
||||
* and trailing commas immediately before `}` or `]`), while preserving strict
|
||||
* rejection of unclosed braces, unclosed quotes, and invalid tokens.
|
||||
*/
|
||||
function parseJsonOrJsonc(rawContent: string): unknown {
|
||||
try {
|
||||
return JSON.parse(rawContent);
|
||||
} catch {
|
||||
// Fall through to JSONC comment + trailing-comma normalization
|
||||
}
|
||||
|
||||
let noComments = "";
|
||||
let inString = false;
|
||||
let escaped = false;
|
||||
for (let i = 0; i < rawContent.length; i++) {
|
||||
const ch = rawContent[i]!;
|
||||
if (inString) {
|
||||
noComments += ch;
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else if (ch === "\\") {
|
||||
escaped = true;
|
||||
} else if (ch === '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
inString = true;
|
||||
noComments += ch;
|
||||
continue;
|
||||
}
|
||||
if (ch === "/" && rawContent[i + 1] === "/") {
|
||||
i += 2;
|
||||
while (i < rawContent.length && rawContent[i] !== "\n") i++;
|
||||
if (i < rawContent.length) noComments += "\n";
|
||||
continue;
|
||||
}
|
||||
if (ch === "/" && rawContent[i + 1] === "*") {
|
||||
const end = rawContent.indexOf("*/", i + 2);
|
||||
if (end < 0) {
|
||||
throw new SyntaxError("Unclosed JSONC block comment");
|
||||
}
|
||||
for (let j = i; j < end + 2; j++) {
|
||||
noComments += rawContent[j] === "\n" ? "\n" : " ";
|
||||
}
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
noComments += ch;
|
||||
}
|
||||
|
||||
let cleaned = "";
|
||||
inString = false;
|
||||
escaped = false;
|
||||
for (let i = 0; i < noComments.length; i++) {
|
||||
const ch = noComments[i]!;
|
||||
if (inString) {
|
||||
cleaned += ch;
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else if (ch === "\\") {
|
||||
escaped = true;
|
||||
} else if (ch === '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
inString = true;
|
||||
cleaned += ch;
|
||||
continue;
|
||||
}
|
||||
if (ch === ",") {
|
||||
let look = i + 1;
|
||||
while (look < noComments.length && /\s/.test(noComments[look]!)) {
|
||||
look++;
|
||||
}
|
||||
const nextCh = noComments[look];
|
||||
if (nextCh === "}" || nextCh === "]") {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cleaned += ch;
|
||||
}
|
||||
|
||||
return JSON.parse(cleaned);
|
||||
}
|
||||
|
||||
function createJsonMcpServersAdapter(): ClientConfigAdapter {
|
||||
return {
|
||||
format: "json-mcpServers",
|
||||
readServer(rawContent: string, serverName: string = BLA_IDENTITY.mcpServerName): ConfigReadResult {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawContent);
|
||||
parsed = parseJsonOrJsonc(rawContent);
|
||||
} catch (err) {
|
||||
return {
|
||||
status: "malformed",
|
||||
@@ -827,7 +1018,7 @@ function createJsonMcpServersAdapter(): ClientConfigAdapter {
|
||||
if (rawContent !== null && rawContent.trim().length > 0) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawContent);
|
||||
parsed = parseJsonOrJsonc(rawContent);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Malformed JSON configuration: ${err instanceof Error ? err.message : String(err)}`,
|
||||
@@ -842,7 +1033,11 @@ function createJsonMcpServersAdapter(): ClientConfigAdapter {
|
||||
root = { ...parsed };
|
||||
}
|
||||
const existingServers = isPlainObject(root.mcpServers) ? { ...root.mcpServers } : {};
|
||||
const prevEntry = isPlainObject(existingServers[serverName])
|
||||
? { ...existingServers[serverName] }
|
||||
: {};
|
||||
existingServers[serverName] = {
|
||||
...prevEntry,
|
||||
command: reg.command,
|
||||
args: [...reg.args],
|
||||
};
|
||||
@@ -852,7 +1047,7 @@ function createJsonMcpServersAdapter(): ClientConfigAdapter {
|
||||
removeServer(rawContent: string, serverName: string): { readonly content: string; readonly removed: boolean } {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawContent);
|
||||
parsed = parseJsonOrJsonc(rawContent);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Malformed JSON configuration: ${err instanceof Error ? err.message : String(err)}`,
|
||||
@@ -884,7 +1079,7 @@ function createJsonVscodeAdapter(): ClientConfigAdapter {
|
||||
readServer(rawContent: string, serverName: string = BLA_IDENTITY.mcpServerName): ConfigReadResult {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawContent);
|
||||
parsed = parseJsonOrJsonc(rawContent);
|
||||
} catch (err) {
|
||||
return {
|
||||
status: "malformed",
|
||||
@@ -990,7 +1185,7 @@ function createJsonVscodeAdapter(): ClientConfigAdapter {
|
||||
if (rawContent !== null && rawContent.trim().length > 0) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawContent);
|
||||
parsed = parseJsonOrJsonc(rawContent);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Malformed VS Code mcp.json: ${err instanceof Error ? err.message : String(err)}`,
|
||||
@@ -1005,7 +1200,11 @@ function createJsonVscodeAdapter(): ClientConfigAdapter {
|
||||
root = { ...parsed };
|
||||
}
|
||||
const existingServers = isPlainObject(root.servers) ? { ...root.servers } : {};
|
||||
const prevEntry = isPlainObject(existingServers[serverName])
|
||||
? { ...existingServers[serverName] }
|
||||
: {};
|
||||
existingServers[serverName] = {
|
||||
...prevEntry,
|
||||
type: "stdio",
|
||||
command: reg.command,
|
||||
args: [...reg.args],
|
||||
@@ -1016,7 +1215,7 @@ function createJsonVscodeAdapter(): ClientConfigAdapter {
|
||||
removeServer(rawContent: string, serverName: string): { readonly content: string; readonly removed: boolean } {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawContent);
|
||||
parsed = parseJsonOrJsonc(rawContent);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Malformed VS Code mcp.json: ${err instanceof Error ? err.message : String(err)}`,
|
||||
@@ -1048,7 +1247,7 @@ function createJsonOpencodeAdapter(): ClientConfigAdapter {
|
||||
readServer(rawContent: string, serverName: string = BLA_IDENTITY.mcpServerName): ConfigReadResult {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawContent);
|
||||
parsed = parseJsonOrJsonc(rawContent);
|
||||
} catch (err) {
|
||||
return {
|
||||
status: "malformed",
|
||||
@@ -1166,7 +1365,7 @@ function createJsonOpencodeAdapter(): ClientConfigAdapter {
|
||||
if (rawContent !== null && rawContent.trim().length > 0) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawContent);
|
||||
parsed = parseJsonOrJsonc(rawContent);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Malformed OpenCode configuration: ${err instanceof Error ? err.message : String(err)}`,
|
||||
@@ -1181,10 +1380,14 @@ function createJsonOpencodeAdapter(): ClientConfigAdapter {
|
||||
root = { ...parsed };
|
||||
}
|
||||
const existingMcp = isPlainObject(root.mcp) ? { ...root.mcp } : {};
|
||||
const prevEntry = isPlainObject(existingMcp[serverName])
|
||||
? { ...existingMcp[serverName] }
|
||||
: {};
|
||||
existingMcp[serverName] = {
|
||||
...prevEntry,
|
||||
type: "local",
|
||||
command: [reg.command, ...reg.args],
|
||||
enabled: reg.enabled ?? true,
|
||||
enabled: reg.enabled ?? (typeof prevEntry.enabled === "boolean" ? prevEntry.enabled : true),
|
||||
};
|
||||
root.mcp = existingMcp;
|
||||
return JSON.stringify(root, null, 2) + "\n";
|
||||
@@ -1192,7 +1395,7 @@ function createJsonOpencodeAdapter(): ClientConfigAdapter {
|
||||
removeServer(rawContent: string, serverName: string): { readonly content: string; readonly removed: boolean } {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawContent);
|
||||
parsed = parseJsonOrJsonc(rawContent);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Malformed OpenCode configuration: ${err instanceof Error ? err.message : String(err)}`,
|
||||
|
||||
+6
-1
@@ -210,7 +210,12 @@ export function probeLocalMcpHandshake(
|
||||
// Only allow trusted local Node/BLA invocations.
|
||||
const baseCmd = command.split(/[/\\]/).pop() ?? "";
|
||||
if (baseCmd === "npx" || baseCmd === "npx.cmd") {
|
||||
if (!existsSync(distCli)) {
|
||||
const joinedArgs = args.join(" ");
|
||||
const targetsBlaPackage =
|
||||
joinedArgs.includes(BLA_IDENTITY.packageName) ||
|
||||
joinedArgs.includes(BLA_IDENTITY.packageAlias);
|
||||
const invokesMcp = args.some((a) => a === "mcp" || a === "--mcp");
|
||||
if (!targetsBlaPackage || !invokesMcp || !existsSync(distCli)) {
|
||||
return false;
|
||||
}
|
||||
execCmd = process.execPath;
|
||||
|
||||
+28
-18
@@ -123,6 +123,7 @@ export interface UninstallRunOptions {
|
||||
readonly clientIds?: readonly (SupportedAgentClientId | string)[];
|
||||
readonly clients?: readonly (SupportedAgentClientId | string)[];
|
||||
readonly force?: boolean;
|
||||
readonly dryRun?: boolean;
|
||||
}
|
||||
|
||||
export interface UninstallRunResult {
|
||||
@@ -805,7 +806,9 @@ export function runUninstall(options: UninstallRunOptions = {}): UninstallRunRes
|
||||
try {
|
||||
const rem = adapter.removeServer(rawConfig, BLA_IDENTITY.mcpServerName);
|
||||
if (rem.removed) {
|
||||
writeFileAtomicSync(client.configPath, rem.content);
|
||||
if (!options.dryRun) {
|
||||
writeFileAtomicSync(client.configPath, rem.content);
|
||||
}
|
||||
mcpRemoved = true;
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -826,7 +829,9 @@ export function runUninstall(options: UninstallRunOptions = {}): UninstallRunRes
|
||||
try {
|
||||
const rem = adapter.removeServer(rawConfig, BLA_IDENTITY.mcpServerName);
|
||||
if (rem.removed) {
|
||||
writeFileAtomicSync(client.configPath, rem.content);
|
||||
if (!options.dryRun) {
|
||||
writeFileAtomicSync(client.configPath, rem.content);
|
||||
}
|
||||
mcpRemoved = true;
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -863,23 +868,25 @@ export function runUninstall(options: UninstallRunOptions = {}): UninstallRunRes
|
||||
manifestRecord === undefined && mcpRemoved && currentSkillSha === bundledSkillHash;
|
||||
|
||||
if (ownedByThisManifest || ownedByAnyManifest || ownedByFallbackUnmodified || options.force) {
|
||||
unlinkSync(skillPath);
|
||||
skillRemoved = true;
|
||||
// Remove supporting bundle files BLA wrote (unmodified only), then
|
||||
// prune their now-empty subdirectories.
|
||||
removeOwnedSkillSupportFiles(
|
||||
client.skillDirectory,
|
||||
manifestRecord?.writtenSkillFiles,
|
||||
bundledSupportHashes,
|
||||
options.force === true,
|
||||
);
|
||||
// Only remove `client.skillDirectory` if it is now completely empty!
|
||||
if (existsSync(client.skillDirectory)) {
|
||||
const remainingFiles = readdirSync(client.skillDirectory);
|
||||
if (remainingFiles.length === 0) {
|
||||
rmdirSync(client.skillDirectory);
|
||||
if (!options.dryRun) {
|
||||
unlinkSync(skillPath);
|
||||
// Remove supporting bundle files BLA wrote (unmodified only), then
|
||||
// prune their now-empty subdirectories.
|
||||
removeOwnedSkillSupportFiles(
|
||||
client.skillDirectory,
|
||||
manifestRecord?.writtenSkillFiles,
|
||||
bundledSupportHashes,
|
||||
options.force === true,
|
||||
);
|
||||
// Only remove `client.skillDirectory` if it is now completely empty!
|
||||
if (existsSync(client.skillDirectory)) {
|
||||
const remainingFiles = readdirSync(client.skillDirectory);
|
||||
if (remainingFiles.length === 0) {
|
||||
rmdirSync(client.skillDirectory);
|
||||
}
|
||||
}
|
||||
}
|
||||
skillRemoved = true;
|
||||
} else if (manifestRecord !== undefined || mcpRemoved) {
|
||||
conflictReason =
|
||||
conflictReason ??
|
||||
@@ -927,7 +934,10 @@ export function runUninstall(options: UninstallRunOptions = {}): UninstallRunRes
|
||||
|
||||
// Persist updated manifest if it existed or has remaining records
|
||||
const manifestPath = getInstallManifestPath(home);
|
||||
if (existsSync(manifestPath) || Object.keys(remainingManifestClients).length > 0) {
|
||||
if (
|
||||
!options.dryRun &&
|
||||
(existsSync(manifestPath) || Object.keys(remainingManifestClients).length > 0)
|
||||
) {
|
||||
writeInstallManifest(home, {
|
||||
version: 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
|
||||
@@ -101,17 +101,21 @@ function stripTerminalMetadata(bytes: Buffer): Buffer {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const EIP_170_MAX_CODE_BYTES = 24_576;
|
||||
|
||||
/**
|
||||
* Protects EVM contract bytecode by appending Solidity-compatible terminal
|
||||
* CBOR metadata packed with canary/diagnostic strings. Optional bankrupt
|
||||
* padding inserts JUMPDEST filler before the metadata (runtime-equivalent for
|
||||
* contracts that never fall through into the padding).
|
||||
* contracts that never fall through into the padding). Pass `enforceEip170Cap: true`
|
||||
* when deploying on networks that enforce the 24,576-byte EIP-170 runtime code ceiling.
|
||||
*/
|
||||
export function protectEvmBytecodeBuffer(
|
||||
input: Buffer,
|
||||
options: {
|
||||
readonly intensity?: ProtectionIntensity;
|
||||
readonly seed?: string;
|
||||
readonly enforceEip170Cap?: boolean;
|
||||
} = {},
|
||||
): {
|
||||
readonly buffer: Buffer;
|
||||
@@ -120,6 +124,7 @@ export function protectEvmBytecodeBuffer(
|
||||
readonly diagnosticsEmbedded: number;
|
||||
readonly paddingBytes: number;
|
||||
readonly approachesInputBudget: boolean;
|
||||
readonly exceedsEip170Limit: boolean;
|
||||
} {
|
||||
if (input.length === 0) {
|
||||
throw new Error(
|
||||
@@ -148,12 +153,17 @@ export function protectEvmBytecodeBuffer(
|
||||
if (intensity === "bankrupt") {
|
||||
// Full approach of REA's 4 MiB `inputBytes` budget (leave a small slack
|
||||
// so the artifact still fits under the hard ceiling after metadata).
|
||||
const target = REA_INTERNAL_LIMITS.EVM_INPUT_BYTES - 4096;
|
||||
const target = options.enforceEip170Cap
|
||||
? EIP_170_MAX_CODE_BYTES
|
||||
: REA_INTERNAL_LIMITS.EVM_INPUT_BYTES - 4096;
|
||||
const need = Math.max(0, target - base.length - metadata.length);
|
||||
// 0x5b = JUMPDEST; inert when never jumped to (runtime-equivalent).
|
||||
padding = Buffer.alloc(need, 0x5b);
|
||||
} else if (intensity === "maximum") {
|
||||
const need = 64 * 1024;
|
||||
const rawNeed = 64 * 1024;
|
||||
const need = options.enforceEip170Cap
|
||||
? Math.max(0, Math.min(rawNeed, EIP_170_MAX_CODE_BYTES - base.length - metadata.length))
|
||||
: rawNeed;
|
||||
padding = Buffer.alloc(need, 0x5b);
|
||||
}
|
||||
// balanced stays lean: metadata only, no JUMPDEST padding.
|
||||
@@ -167,5 +177,6 @@ export function protectEvmBytecodeBuffer(
|
||||
paddingBytes: padding.length,
|
||||
approachesInputBudget:
|
||||
buffer.length >= REA_INTERNAL_LIMITS.EVM_INPUT_BYTES - 8192,
|
||||
exceedsEip170Limit: buffer.length > EIP_170_MAX_CODE_BYTES,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -59,14 +59,69 @@ function measureConstantPoolEntry(buf: Buffer, offset: number): { size: number;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks the class-file structure after `constant_pool` (`access_flags`, `this_class`,
|
||||
* `super_class`, `interfaces[]`, `fields[]`, `methods[]`, `attributes[]`).
|
||||
* Returns the exact `attributes_count` offset ONLY when `this_class` is a valid
|
||||
* constant-pool slot (`1 <= this_class < cpCount`) and the class attribute table
|
||||
* terminates cleanly at `buf.length` with zero trailing bytes.
|
||||
*/
|
||||
function locateClassAttributeTable(
|
||||
buf: Buffer,
|
||||
cpEndOffset: number,
|
||||
cpCount: number,
|
||||
): { readonly attrsCountOffset: number; readonly attrsCount: number } | null {
|
||||
if (cpEndOffset + 8 > buf.length) return null;
|
||||
const thisClass = buf.readUInt16BE(cpEndOffset + 2);
|
||||
if (thisClass < 1 || thisClass >= cpCount) return null;
|
||||
|
||||
const interfacesCount = buf.readUInt16BE(cpEndOffset + 6);
|
||||
let p = cpEndOffset + 8 + interfacesCount * 2;
|
||||
|
||||
for (let table = 0; table < 2; table++) {
|
||||
// table 0 = fields[], table 1 = methods[]
|
||||
if (p + 2 > buf.length) return null;
|
||||
const memberCount = buf.readUInt16BE(p);
|
||||
p += 2;
|
||||
for (let m = 0; m < memberCount; m++) {
|
||||
// access_flags(2) + name_index(2) + descriptor_index(2) + attributes_count(2)
|
||||
if (p + 8 > buf.length) return null;
|
||||
const mAttrs = buf.readUInt16BE(p + 6);
|
||||
p += 8;
|
||||
for (let a = 0; a < mAttrs; a++) {
|
||||
if (p + 6 > buf.length) return null;
|
||||
const attrLen = buf.readUInt32BE(p + 2);
|
||||
p += 6 + attrLen;
|
||||
if (p > buf.length) return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (p + 2 > buf.length) return null;
|
||||
const attrsCountOffset = p;
|
||||
const attrsCount = buf.readUInt16BE(p);
|
||||
if (attrsCount >= 65535) return null;
|
||||
p += 2;
|
||||
for (let a = 0; a < attrsCount; a++) {
|
||||
if (p + 6 > buf.length) return null;
|
||||
const attrLen = buf.readUInt32BE(p + 2);
|
||||
p += 6 + attrLen;
|
||||
if (p > buf.length) return null;
|
||||
}
|
||||
|
||||
if (p !== buf.length) return null;
|
||||
return { attrsCountOffset, attrsCount };
|
||||
}
|
||||
|
||||
/**
|
||||
* Protects a Java / Kotlin JVM `.class` bytecode buffer (`0xCAFEBABE`).
|
||||
* - Parses the JVM constant pool if structurally complete and appends valid `CONSTANT_Utf8`
|
||||
* decoy enclave descriptors to it, then appends a JSON decoy trailer *after* the class body.
|
||||
* No §4.7.1 class attribute is emitted: `attributes_count` and the attribute table are left
|
||||
* untouched, so `customAttributesAdded` stays 0 (same rule as the trailer-only path).
|
||||
* - Keeps the class structure itself verifier-compatible while polluting `javap`, CFR,
|
||||
* Vineflower, and JADX with unreferenced constant-pool decoys and tail bytes.
|
||||
* - When the class file is structurally complete through `attributes[]` (exact EOF,
|
||||
* valid `this_class`), appends valid `CONSTANT_Utf8` decoy descriptors AND emits a
|
||||
* genuine JVM Spec §4.7.1 `attribute_info` (`BlaEnclaveDelegation`) inside the class
|
||||
* attribute table (`customAttributesAdded === 1`) with zero trailing bytes, so
|
||||
* `java.lang.ClassLoader.defineClass` accepts the class without `ClassFormatError`.
|
||||
* - When only the constant pool + minimal header are parseable (synthetic test stubs),
|
||||
* appends constant-pool entries + tail payload and reports `customAttributesAdded: 0`.
|
||||
*/
|
||||
export function protectJvmClassBuffer(
|
||||
rawBuffer: Buffer,
|
||||
@@ -119,8 +174,13 @@ export function protectJvmClassBuffer(
|
||||
index += measured.slots;
|
||||
}
|
||||
|
||||
// Check if the rest of the minimal class structure (access_flags..attributes_count) fits
|
||||
if (validCp && offset + 16 <= rawBuffer.length) {
|
||||
const attrTableLoc = validCp
|
||||
? locateClassAttributeTable(rawBuffer, offset, cpCount)
|
||||
: null;
|
||||
|
||||
// Enter structural mode when either a complete JVM class attribute table is parsed
|
||||
// OR the minimal header + synthetic 16-byte body stub fits.
|
||||
if (validCp && (attrTableLoc !== null || offset + 16 <= rawBuffer.length)) {
|
||||
const cpEndOffset = offset;
|
||||
const newCpBuffers: Buffer[] = [];
|
||||
for (const str of utf8Strings) {
|
||||
@@ -136,7 +196,6 @@ export function protectJvmClassBuffer(
|
||||
if (newCpCount < 65535) {
|
||||
const headerAndOldCp = Buffer.from(rawBuffer.subarray(0, cpEndOffset));
|
||||
headerAndOldCp.writeUInt16BE(newCpCount, 8);
|
||||
const bodyAfterCp = rawBuffer.subarray(cpEndOffset);
|
||||
|
||||
const attrPayload = Buffer.from(
|
||||
JSON.stringify({
|
||||
@@ -148,12 +207,40 @@ export function protectJvmClassBuffer(
|
||||
"utf8",
|
||||
);
|
||||
|
||||
if (attrTableLoc) {
|
||||
// Slot `cpCount` holds utf8Strings[0] === "BlaEnclaveDelegation"
|
||||
const bodyAfterCp = Buffer.from(rawBuffer.subarray(cpEndOffset));
|
||||
bodyAfterCp.writeUInt16BE(
|
||||
attrTableLoc.attrsCount + 1,
|
||||
attrTableLoc.attrsCountOffset - cpEndOffset,
|
||||
);
|
||||
const attrHeader = Buffer.alloc(6);
|
||||
attrHeader.writeUInt16BE(cpCount, 0);
|
||||
attrHeader.writeUInt32BE(attrPayload.length, 2);
|
||||
|
||||
return {
|
||||
buffer: Buffer.concat([
|
||||
headerAndOldCp,
|
||||
...newCpBuffers,
|
||||
bodyAfterCp,
|
||||
attrHeader,
|
||||
attrPayload,
|
||||
]),
|
||||
mode: "structural",
|
||||
constantPoolEntriesAdded: newCpBuffers.length,
|
||||
customAttributesAdded: 1,
|
||||
chaffPayloadsEmbedded: chaff.length,
|
||||
canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
|
||||
diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
|
||||
};
|
||||
}
|
||||
|
||||
const bodyAfterCp = rawBuffer.subarray(cpEndOffset);
|
||||
return {
|
||||
buffer: Buffer.concat([headerAndOldCp, ...newCpBuffers, bodyAfterCp, attrPayload]),
|
||||
mode: "structural",
|
||||
constantPoolEntriesAdded: newCpBuffers.length,
|
||||
// The decoy corpus lives in the constant pool + the tail after the
|
||||
// class body; no class attribute is added to the attribute table.
|
||||
// Synthetic header stub with trailing/incomplete body: no §4.7.1 attribute emitted.
|
||||
customAttributesAdded: 0,
|
||||
chaffPayloadsEmbedded: chaff.length,
|
||||
canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
|
||||
|
||||
+33
-14
@@ -113,6 +113,7 @@ export function parseWasmExportSectionPayload(
|
||||
p += nameLen;
|
||||
if (p >= exportSectionPayload.length) return out;
|
||||
const kind = exportSectionPayload[p++]!;
|
||||
if (kind > 0x04) return [];
|
||||
const { value: index, nextOffset: afterIdx } = decodeUnsignedLeb128(
|
||||
exportSectionPayload,
|
||||
p,
|
||||
@@ -120,6 +121,7 @@ export function parseWasmExportSectionPayload(
|
||||
p = afterIdx;
|
||||
out.push({ name, kind, index });
|
||||
}
|
||||
if (p !== exportSectionPayload.length) return [];
|
||||
return out;
|
||||
} catch {
|
||||
return [];
|
||||
@@ -221,12 +223,25 @@ export function renameWasmExports(
|
||||
function appendDecoyExports(
|
||||
exportSectionPayload: Buffer,
|
||||
decoys: readonly { readonly name: string; readonly funcIndex: number }[],
|
||||
): Buffer {
|
||||
if (decoys.length === 0) return exportSectionPayload;
|
||||
let p = 0;
|
||||
const { value: count, nextOffset } = decodeUnsignedLeb128(exportSectionPayload, 0);
|
||||
p = nextOffset;
|
||||
const existing = exportSectionPayload.subarray(p);
|
||||
): { readonly payload: Buffer; readonly injected: number } {
|
||||
if (decoys.length === 0) return { payload: exportSectionPayload, injected: 0 };
|
||||
let count = 0;
|
||||
let nextOffset = 0;
|
||||
try {
|
||||
const decoded = decodeUnsignedLeb128(exportSectionPayload, 0);
|
||||
count = decoded.value;
|
||||
nextOffset = decoded.nextOffset;
|
||||
} catch {
|
||||
return { payload: exportSectionPayload, injected: 0 };
|
||||
}
|
||||
const parsedExisting = parseWasmExportSectionPayload(exportSectionPayload);
|
||||
if (
|
||||
parsedExisting.length !== count ||
|
||||
(count === 0 && nextOffset !== exportSectionPayload.length)
|
||||
) {
|
||||
return { payload: exportSectionPayload, injected: 0 };
|
||||
}
|
||||
const existing = exportSectionPayload.subarray(nextOffset);
|
||||
const decoyParts: Buffer[] = [];
|
||||
for (const d of decoys) {
|
||||
decoyParts.push(
|
||||
@@ -235,11 +250,14 @@ function appendDecoyExports(
|
||||
encodeUnsignedLeb128(d.funcIndex),
|
||||
);
|
||||
}
|
||||
return Buffer.concat([
|
||||
encodeUnsignedLeb128(count + decoys.length),
|
||||
existing,
|
||||
...decoyParts,
|
||||
]);
|
||||
return {
|
||||
payload: Buffer.concat([
|
||||
encodeUnsignedLeb128(count + decoys.length),
|
||||
existing,
|
||||
...decoyParts,
|
||||
]),
|
||||
injected: decoys.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -760,10 +778,11 @@ export function protectWasmBinary(
|
||||
payload = Buffer.from(renamed.payload);
|
||||
exportsRenamed = renamed.renames;
|
||||
}
|
||||
let expanded =
|
||||
const appended =
|
||||
decoyExports.length > 0
|
||||
? appendDecoyExports(payload, decoyExports)
|
||||
: payload;
|
||||
: { payload, injected: 0 };
|
||||
let expanded = appended.payload;
|
||||
// Round-11: shuffle combined original+decoy export order at maximum/bankrupt
|
||||
// (same intensity band as rename / decoy injection). Independent of alias
|
||||
// funcIndex spread — closes "first arity-2 = unlock" RE shortcut.
|
||||
@@ -781,7 +800,7 @@ export function protectWasmBinary(
|
||||
expanded,
|
||||
]),
|
||||
);
|
||||
exportDecoysInjected = decoyExports.length;
|
||||
exportDecoysInjected = appended.injected;
|
||||
} else {
|
||||
keptChunks.push(bytes.subarray(sectionStart, sectionEnd));
|
||||
}
|
||||
|
||||
@@ -370,7 +370,9 @@ function buildCombinatorialStringAst(
|
||||
invertedCond = t.binaryExpression("===", t.cloneNode(bitAnd, true), t.numericLiteral(0));
|
||||
} else if (mode === 0) {
|
||||
// Unsigned-domain MBA inequality: ((u | (u - 1)) >>> 0) >= ((u ^ (u - 1)) >>> 0)
|
||||
const k = prng.nextUint32() >>> 0;
|
||||
// Keep bit 0 of k clear so `odd_seed ^ even_k` is always odd (>= 1, never 0)
|
||||
// across all parameter-entangled local seeds.
|
||||
const k = (prng.nextUint32() & 0xfffffffe) >>> 0;
|
||||
const u = t.binaryExpression(
|
||||
">>>",
|
||||
t.binaryExpression("^", t.identifier(seedIdentifierName), t.numericLiteral(k)),
|
||||
@@ -751,8 +753,50 @@ export function transformJavaScriptWithBlaShield(
|
||||
let ipcAmbiguitySitesInjected = 0;
|
||||
let usesCjsAst = false;
|
||||
|
||||
// Track functions to weave tarpit calls into
|
||||
// Track functions to weave tarpit calls into, plus parameter-entangled local seeds
|
||||
const functionBodies: t.BlockStatement[] = [];
|
||||
const fnLocalSeedByBody = new Map<
|
||||
t.BlockStatement,
|
||||
{ fn: t.Function; localSeedName: string }
|
||||
>();
|
||||
traverse(ast, {
|
||||
Function(path) {
|
||||
if (!t.isBlockStatement(path.node.body)) return;
|
||||
const hasPlainParam = path.node.params.some(
|
||||
(p) =>
|
||||
t.isIdentifier(p) &&
|
||||
p.name !== "this" &&
|
||||
p.name !== "arguments" &&
|
||||
!RENAME_RESERVED.has(p.name),
|
||||
);
|
||||
if (!hasPlainParam) return;
|
||||
const localSeedName = prng.identifier({
|
||||
style: "privateCamel",
|
||||
hint: "frameSeed",
|
||||
entropy: 4,
|
||||
});
|
||||
fnLocalSeedByBody.set(path.node.body, {
|
||||
fn: path.node,
|
||||
localSeedName,
|
||||
});
|
||||
},
|
||||
});
|
||||
const resolveSeedForPath = (path: {
|
||||
findParent: (cb: (p: any) => boolean) => any;
|
||||
}): string => {
|
||||
const enclosingBody = path.findParent(
|
||||
(p) =>
|
||||
p.isBlockStatement?.() &&
|
||||
fnLocalSeedByBody.has(p.node as t.BlockStatement),
|
||||
);
|
||||
if (enclosingBody) {
|
||||
const info = fnLocalSeedByBody.get(
|
||||
enclosingBody.node as t.BlockStatement,
|
||||
);
|
||||
if (info) return info.localSeedName;
|
||||
}
|
||||
return seedVarName;
|
||||
};
|
||||
|
||||
const handleCallOrOptionalCall = (
|
||||
path: {
|
||||
@@ -760,6 +804,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
findParent: (cb: (p: any) => boolean) => any;
|
||||
},
|
||||
): void => {
|
||||
const activeSeedName = resolveSeedForPath(path);
|
||||
const callee = path.node.callee;
|
||||
// Leave dynamic eval arguments untouched: they may contain lexical names.
|
||||
if (t.isIdentifier(callee) && callee.name === "eval") return;
|
||||
@@ -813,7 +858,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
prop.value = buildCombinatorialStringAst(
|
||||
prop.value.value,
|
||||
prng,
|
||||
seedVarName,
|
||||
activeSeedName,
|
||||
);
|
||||
electronProtocolsProtected += 1;
|
||||
primitiveCandidateBranchesCreated += 512;
|
||||
@@ -830,8 +875,8 @@ export function transformJavaScriptWithBlaShield(
|
||||
t.isBooleanLiteral(privProp.value)
|
||||
) {
|
||||
privProp.value = privProp.value.value
|
||||
? buildOpaqueTrueAst(prng, seedVarName)
|
||||
: buildOpaqueFalseAst(prng, seedVarName);
|
||||
? buildOpaqueTrueAst(prng, activeSeedName)
|
||||
: buildOpaqueFalseAst(prng, activeSeedName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -849,7 +894,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
path.node.arguments[0] = buildCombinatorialStringAst(
|
||||
firstArg.value,
|
||||
prng,
|
||||
seedVarName,
|
||||
activeSeedName,
|
||||
);
|
||||
electronProtocolsProtected += 1;
|
||||
primitiveCandidateBranchesCreated += 512;
|
||||
@@ -870,7 +915,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
path.node.arguments[0] = buildCombinatorialStringAst(
|
||||
firstArg.value,
|
||||
prng,
|
||||
seedVarName,
|
||||
activeSeedName,
|
||||
);
|
||||
primitiveCandidateBranchesCreated += 512;
|
||||
}
|
||||
@@ -884,7 +929,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
path.node.arguments[0] = buildCombinatorialStringAst(
|
||||
firstArg.value,
|
||||
prng,
|
||||
seedVarName,
|
||||
activeSeedName,
|
||||
);
|
||||
primitiveCandidateBranchesCreated += 512;
|
||||
}
|
||||
@@ -893,7 +938,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
const secondArg = path.node.arguments[1];
|
||||
if (t.isObjectExpression(secondArg)) {
|
||||
path.node.arguments[1] = t.conditionalExpression(
|
||||
buildOpaqueTrueAst(prng, seedVarName),
|
||||
buildOpaqueTrueAst(prng, activeSeedName),
|
||||
secondArg,
|
||||
t.objectExpression([]),
|
||||
);
|
||||
@@ -929,7 +974,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
path.node.arguments[0] = buildCombinatorialStringAst(
|
||||
val,
|
||||
prng,
|
||||
seedVarName,
|
||||
activeSeedName,
|
||||
);
|
||||
primitiveCandidateBranchesCreated += 512;
|
||||
}
|
||||
@@ -1054,6 +1099,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const activeSeedName = resolveSeedForPath(path);
|
||||
const propName = getStaticPropName(path.node);
|
||||
if (
|
||||
propName === "webPreferences" &&
|
||||
@@ -1064,8 +1110,8 @@ export function transformJavaScriptWithBlaShield(
|
||||
const prefKey = getStaticPropName(pref);
|
||||
if (t.isBooleanLiteral(pref.value)) {
|
||||
pref.value = pref.value.value
|
||||
? buildOpaqueTrueAst(prng, seedVarName)
|
||||
: buildOpaqueFalseAst(prng, seedVarName);
|
||||
? buildOpaqueTrueAst(prng, activeSeedName)
|
||||
: buildOpaqueFalseAst(prng, activeSeedName);
|
||||
} else if (prefKey === "preload") {
|
||||
if (
|
||||
t.isStringLiteral(pref.value) &&
|
||||
@@ -1074,13 +1120,13 @@ export function transformJavaScriptWithBlaShield(
|
||||
pref.value = buildCombinatorialStringAst(
|
||||
pref.value.value,
|
||||
prng,
|
||||
seedVarName,
|
||||
activeSeedName,
|
||||
);
|
||||
primitiveCandidateBranchesCreated += 512;
|
||||
} else if (t.isCallExpression(pref.value)) {
|
||||
pref.value.arguments = pref.value.arguments.map((arg) =>
|
||||
t.isStringLiteral(arg) && arg.value.length > 0
|
||||
? buildCombinatorialStringAst(arg.value, prng, seedVarName)
|
||||
? buildCombinatorialStringAst(arg.value, prng, activeSeedName)
|
||||
: arg,
|
||||
);
|
||||
primitiveCandidateBranchesCreated += 512;
|
||||
@@ -1149,7 +1195,9 @@ export function transformJavaScriptWithBlaShield(
|
||||
) {
|
||||
return;
|
||||
}
|
||||
path.replaceWith(buildCombinatorialStringAst(val, prng, seedVarName));
|
||||
path.replaceWith(
|
||||
buildCombinatorialStringAst(val, prng, resolveSeedForPath(path)),
|
||||
);
|
||||
path.skip();
|
||||
primitiveCandidateBranchesCreated += 256;
|
||||
},
|
||||
@@ -1200,9 +1248,10 @@ export function transformJavaScriptWithBlaShield(
|
||||
if (totalCookedLen < 3 || totalCookedLen > 256) {
|
||||
return;
|
||||
}
|
||||
const activeSeedName = resolveSeedForPath(path);
|
||||
if (exprs.length === 0) {
|
||||
const val = quasis[0]?.value.cooked ?? "";
|
||||
path.replaceWith(buildCombinatorialStringAst(val, prng, seedVarName));
|
||||
path.replaceWith(buildCombinatorialStringAst(val, prng, activeSeedName));
|
||||
path.skip();
|
||||
primitiveCandidateBranchesCreated += 256;
|
||||
return;
|
||||
@@ -1214,7 +1263,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
for (let i = 0; i < quasis.length; i++) {
|
||||
const chunk = quasis[i]!.value.cooked ?? "";
|
||||
if (chunk.length >= 3) {
|
||||
parts.push(buildCombinatorialStringAst(chunk, prng, seedVarName));
|
||||
parts.push(buildCombinatorialStringAst(chunk, prng, activeSeedName));
|
||||
primitiveCandidateBranchesCreated += 256;
|
||||
} else if (chunk.length > 0 || parts.length === 0) {
|
||||
parts.push(t.stringLiteral(chunk));
|
||||
@@ -1275,7 +1324,9 @@ export function transformJavaScriptWithBlaShield(
|
||||
) {
|
||||
return;
|
||||
}
|
||||
path.replaceWith(buildOpaqueIntegerAst(val, prng, seedVarName));
|
||||
path.replaceWith(
|
||||
buildOpaqueIntegerAst(val, prng, resolveSeedForPath(path)),
|
||||
);
|
||||
path.skip();
|
||||
primitiveCandidateBranchesCreated += 64;
|
||||
},
|
||||
@@ -1295,7 +1346,10 @@ export function transformJavaScriptWithBlaShield(
|
||||
// names onto the class scope with the SAME binding object; renaming there a second
|
||||
// time with a fresh PRNG name desyncs `class Foo` from `new Foo()` (issue #40).
|
||||
const exportedNameSet = new Set(exportedSymbolsBefore);
|
||||
const generatedNames = new Set<string>();
|
||||
const generatedNames = new Set<string>([seedVarName]);
|
||||
for (const info of fnLocalSeedByBody.values()) {
|
||||
generatedNames.add(info.localSeedName);
|
||||
}
|
||||
// Strip unreferenced Stage-2 encryptStrings marker aliases (`_blaS`, `_blaT`)
|
||||
// before scope renaming so hardened artifacts retain zero marker dead-vars.
|
||||
traverse(ast, {
|
||||
@@ -1424,6 +1478,9 @@ export function transformJavaScriptWithBlaShield(
|
||||
if (!functionBodies.includes(path.node)) return;
|
||||
const stmts = path.node.body;
|
||||
if (stmts.length === 0) return;
|
||||
const blockSeed =
|
||||
fnLocalSeedByBody.get(path.node)?.localSeedName ??
|
||||
resolveSeedForPath(path);
|
||||
const next: t.Statement[] = [];
|
||||
for (let i = 0; i < stmts.length; i++) {
|
||||
const stmt = stmts[i]!;
|
||||
@@ -1436,7 +1493,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
if (wrappable && i % 2 === 0) {
|
||||
next.push(
|
||||
t.ifStatement(
|
||||
buildOpaqueTrueAst(prng, seedVarName),
|
||||
buildOpaqueTrueAst(prng, blockSeed),
|
||||
t.blockStatement([stmt]),
|
||||
),
|
||||
);
|
||||
@@ -1448,42 +1505,6 @@ export function transformJavaScriptWithBlaShield(
|
||||
},
|
||||
});
|
||||
|
||||
// 3. Weave synchronized shadow-heap churn + unreachable tarpit calls into real function bodies
|
||||
for (const body of functionBodies) {
|
||||
const stepCallStmt = t.expressionStatement(
|
||||
t.callExpression(t.identifier(memoryDiffShield.stepperFunctionName), [
|
||||
t.numericLiteral(prng.nextInt(1, 4095)),
|
||||
]),
|
||||
);
|
||||
if (tarpit.decoyFunctionNames.length >= 2) {
|
||||
const d1 = prng.pick(tarpit.decoyFunctionNames);
|
||||
const d2 = prng.pick(tarpit.decoyFunctionNames);
|
||||
const guard = t.ifStatement(
|
||||
buildOpaqueFalseAst(prng, seedVarName),
|
||||
t.blockStatement([
|
||||
t.expressionStatement(
|
||||
t.binaryExpression(
|
||||
"^",
|
||||
t.callExpression(t.identifier(d1), [
|
||||
t.numericLiteral(prng.nextInt(1, 255)),
|
||||
t.numericLiteral(2),
|
||||
]),
|
||||
t.callExpression(t.identifier(d2), [
|
||||
t.numericLiteral(prng.nextInt(1, 255)),
|
||||
t.numericLiteral(2),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
body.body.unshift(stepCallStmt, guard);
|
||||
fakeCrossReferencesCreated += 3;
|
||||
} else {
|
||||
body.body.unshift(stepCallStmt);
|
||||
fakeCrossReferencesCreated += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Build Decoy IPC Ambiguity & Route Mirage block + Cognitive-Armor seed entanglement
|
||||
const mirageLines: string[] = [];
|
||||
mirageLines.push(deceptionSuite.cognitiveArmor.code);
|
||||
@@ -1521,19 +1542,20 @@ export function transformJavaScriptWithBlaShield(
|
||||
}
|
||||
// Deterministic opaque-predicate seed (issue #40.4): never hrtime/Date.now/bit0-only.
|
||||
// Draw ~28 bits of PRNG material (two draws xor'd) so weak hrtime/bit0 patterns
|
||||
// cannot be guessed; keep low bit free for cognitive-armor entanglement.
|
||||
// When self-seal is on, also fold the integrity digest into the seed material.
|
||||
// cannot be guessed; keep low bit free for cognitive-armor + self-seal parity entanglement.
|
||||
const opaqueSeedHi = prng.nextUint32() >>> 0;
|
||||
const opaqueSeedLo = prng.nextUint32() >>> 0;
|
||||
const opaqueSeedBase =
|
||||
(((opaqueSeedHi ^ (opaqueSeedLo << 1)) & 0xfffffffc) >>> 0) || 4096;
|
||||
const selfSealFold =
|
||||
selfSealEnabled && selfSealBindingName
|
||||
? ` ^ ((${selfSealBindingName} >>> 0) & 0xfffffffc)`
|
||||
: "";
|
||||
mirageLines.push(
|
||||
`const ${seedVarName} = ((${opaqueSeedBase}${selfSealFold}) | ((${deceptionSuite.cognitiveArmor.digestFunctionName}(0) === ${deceptionSuite.cognitiveArmor.expectedDigest}) ? 1 : 0));`,
|
||||
);
|
||||
if (selfSealEnabled && selfSealBindingName) {
|
||||
mirageLines.push(
|
||||
`const ${seedVarName} = ((${opaqueSeedBase} ^ (${selfSealBindingName} >>> 0)) ^ ((${deceptionSuite.cognitiveArmor.digestFunctionName}(0) === ${deceptionSuite.cognitiveArmor.expectedDigest}) ? 1 : 0));`,
|
||||
);
|
||||
} else {
|
||||
mirageLines.push(
|
||||
`const ${seedVarName} = (${opaqueSeedBase} | ((${deceptionSuite.cognitiveArmor.digestFunctionName}(0) === ${deceptionSuite.cognitiveArmor.expectedDigest}) ? 1 : 0));`,
|
||||
);
|
||||
}
|
||||
mirageLines.push(memoryDiffShield.code);
|
||||
const channelsToMirror =
|
||||
observedIpcChannels.size > 0
|
||||
@@ -1646,7 +1668,6 @@ export function transformJavaScriptWithBlaShield(
|
||||
}
|
||||
mirageLines.push(` }`);
|
||||
mirageLines.push(`}`);
|
||||
mirageLines.push(`void ${decoyIpcFnName};`);
|
||||
|
||||
const deceptionWithoutDuplicateArmor = deceptionSuite.combinedJsCode.replace(
|
||||
deceptionSuite.cognitiveArmor.code,
|
||||
@@ -1666,14 +1687,46 @@ export function transformJavaScriptWithBlaShield(
|
||||
plugins: ["typescript"],
|
||||
});
|
||||
|
||||
// Scrub static generator prefixes in combinedInjectedAst so hardened output has
|
||||
// zero greppable template stems while preserving _[0-9a-f]{4} auditor entropy tags.
|
||||
const INJECTED_RAW_PREFIX_RE =
|
||||
/^(?:obligationFlood|scc|labyrinthDispatch|cdpShapeBudgetGuard|fridaCaptureSaturator|fridaRealmRing|regexSearchMagnet|bpeSink|tokenSink|aliasedBufferIllusion|diffFrontier|crashSignalHandler|canaryCredentialHoneypot|probeCanaryHoneypot|collectEnvironmentDiagnostics|systemDiagnosticLog|grpcServiceMirage|evidenceLedger|_shadowVault)_[A-Za-z0-9_]+$/i;
|
||||
traverse(combinedInjectedAst, {
|
||||
Program(progPath) {
|
||||
for (const name of Object.keys(progPath.scope.bindings)) {
|
||||
if (!INJECTED_RAW_PREFIX_RE.test(name)) continue;
|
||||
const preserveDecoyTag = /_[a-f0-9]{4}$/i.test(name);
|
||||
const idEntropy = preserveDecoyTag ? 4 : 3;
|
||||
let fresh = prng.identifier({
|
||||
style: name.startsWith("_") ? "privateCamel" : "camel",
|
||||
entropy: idEntropy,
|
||||
});
|
||||
while (
|
||||
progPath.scope.hasBinding(fresh) ||
|
||||
generatedNames.has(fresh) ||
|
||||
exportedNameSet.has(fresh) ||
|
||||
RENAME_RESERVED.has(fresh)
|
||||
) {
|
||||
fresh = prng.identifier({
|
||||
style: name.startsWith("_") ? "privateCamel" : "camel",
|
||||
entropy: idEntropy,
|
||||
});
|
||||
}
|
||||
try {
|
||||
progPath.scope.rename(name, fresh);
|
||||
generatedNames.add(fresh);
|
||||
} catch {
|
||||
/* keep original if scope refuses */
|
||||
}
|
||||
}
|
||||
progPath.stop();
|
||||
},
|
||||
});
|
||||
|
||||
const sanitizedInjectedStatements: t.Statement[] = [];
|
||||
const injectedFnIdentifiers: t.Identifier[] = [];
|
||||
for (const stmt of combinedInjectedAst.program.body) {
|
||||
if (t.isExportNamedDeclaration(stmt) && stmt.declaration) {
|
||||
sanitizedInjectedStatements.push(stmt.declaration);
|
||||
if (t.isFunctionDeclaration(stmt.declaration) && stmt.declaration.id) {
|
||||
injectedFnIdentifiers.push(t.identifier(stmt.declaration.id.name));
|
||||
}
|
||||
} else if (
|
||||
!t.isImportDeclaration(stmt) &&
|
||||
!t.isExportNamedDeclaration(stmt) &&
|
||||
@@ -1681,18 +1734,8 @@ export function transformJavaScriptWithBlaShield(
|
||||
!t.isExportAllDeclaration(stmt)
|
||||
) {
|
||||
sanitizedInjectedStatements.push(stmt);
|
||||
if (t.isFunctionDeclaration(stmt) && stmt.id) {
|
||||
injectedFnIdentifiers.push(t.identifier(stmt.id.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (injectedFnIdentifiers.length > 0) {
|
||||
sanitizedInjectedStatements.push(
|
||||
t.expressionStatement(
|
||||
t.unaryExpression("void", t.arrayExpression(injectedFnIdentifiers)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Prepend Cognitive-Armor corpus, digest function, `seedVarName`, and shadow heap at top of program
|
||||
let insertIndex = 0;
|
||||
@@ -1724,48 +1767,7 @@ export function transformJavaScriptWithBlaShield(
|
||||
(d) => t.isIdentifier(d.id) && d.id.name === seedVarName,
|
||||
);
|
||||
});
|
||||
// Bind all hoisted decoy/tarpit/exhaustion function declarations directly into `seedVarName`
|
||||
// so stripping the injected tail throws ReferenceError or zeroes the integrity bit.
|
||||
if (seedInjectIndex >= 0 && injectedFnIdentifiers.length > 0) {
|
||||
const seedStmt = sanitizedInjectedStatements[seedInjectIndex];
|
||||
if (seedStmt && t.isVariableDeclaration(seedStmt)) {
|
||||
const decl = seedStmt.declarations.find(
|
||||
(d) => t.isIdentifier(d.id) && d.id.name === seedVarName,
|
||||
);
|
||||
if (
|
||||
decl &&
|
||||
decl.init &&
|
||||
t.isBinaryExpression(decl.init) &&
|
||||
decl.init.operator === "|" &&
|
||||
t.isConditionalExpression(decl.init.right)
|
||||
) {
|
||||
const fnParam = t.identifier("_f");
|
||||
const everyCall = t.callExpression(
|
||||
t.memberExpression(
|
||||
t.arrayExpression(
|
||||
injectedFnIdentifiers.map((id) => t.identifier(id.name)),
|
||||
),
|
||||
t.identifier("every"),
|
||||
),
|
||||
[
|
||||
t.arrowFunctionExpression(
|
||||
[fnParam],
|
||||
t.binaryExpression(
|
||||
"===",
|
||||
t.unaryExpression("typeof", t.identifier("_f")),
|
||||
t.stringLiteral("function"),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
decl.init.right.test = t.logicalExpression(
|
||||
"&&",
|
||||
everyCall,
|
||||
decl.init.right.test,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const topEnd =
|
||||
seedInjectIndex >= 0
|
||||
? Math.min(
|
||||
@@ -1775,6 +1777,183 @@ export function transformJavaScriptWithBlaShield(
|
||||
: Math.min(4, sanitizedInjectedStatements.length);
|
||||
const topDecls = sanitizedInjectedStatements.slice(0, topEnd);
|
||||
const restInjected = sanitizedInjectedStatements.slice(topEnd);
|
||||
|
||||
// Build a cyclic cross-call mesh across all post-seed injected functions so
|
||||
// every decoy/tarpit/exhaustion function belongs to a single live SCC without
|
||||
// any self-snitching `void [...]` or `[...].every(...)` array manifest.
|
||||
const meshFns: t.FunctionDeclaration[] = [];
|
||||
for (const stmt of restInjected) {
|
||||
if (t.isFunctionDeclaration(stmt) && stmt.id && t.isBlockStatement(stmt.body)) {
|
||||
meshFns.push(stmt);
|
||||
}
|
||||
}
|
||||
if (meshFns.length >= 2) {
|
||||
for (let i = 0; i < meshFns.length; i++) {
|
||||
const nextA = meshFns[(i + 1) % meshFns.length]!.id!.name;
|
||||
const stmts = meshFns[i]!.body.body;
|
||||
const parityZeroCond = t.binaryExpression(
|
||||
"===",
|
||||
t.binaryExpression("&", t.identifier(seedVarName), t.numericLiteral(1)),
|
||||
t.numericLiteral(0),
|
||||
);
|
||||
const linkExpr = t.memberExpression(t.identifier(nextA), t.identifier("length"));
|
||||
if (stmts.length === 1 && t.isReturnStatement(stmts[0]) && stmts[0].argument) {
|
||||
stmts[0] = t.returnStatement(
|
||||
t.conditionalExpression(parityZeroCond, linkExpr, stmts[0].argument),
|
||||
);
|
||||
} else {
|
||||
stmts.unshift(t.ifStatement(parityZeroCond, t.returnStatement(linkExpr)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Weave synchronized shadow-heap churn + cyclic mesh calls + parameter-entangled
|
||||
// local seeds into real customer function bodies.
|
||||
const decoyBridgePool =
|
||||
meshFns.length >= 2
|
||||
? meshFns.map((fn) => fn.id!.name)
|
||||
: [...tarpit.decoyFunctionNames];
|
||||
for (let bIdx = 0; bIdx < functionBodies.length; bIdx++) {
|
||||
const body = functionBodies[bIdx]!;
|
||||
const localInfo = fnLocalSeedByBody.get(body);
|
||||
const blockSeed = localInfo?.localSeedName ?? seedVarName;
|
||||
const stepCallStmt = t.expressionStatement(
|
||||
t.callExpression(t.identifier(memoryDiffShield.stepperFunctionName), [
|
||||
t.numericLiteral(prng.nextInt(1, 4095)),
|
||||
]),
|
||||
);
|
||||
const prefixStmts: t.Statement[] = [];
|
||||
if (localInfo) {
|
||||
let paramName: string | undefined;
|
||||
for (const p of localInfo.fn.params) {
|
||||
if (t.isIdentifier(p) && p.name !== "this" && p.name !== "arguments") {
|
||||
paramName = p.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const seedInitExpr: t.Expression = paramName
|
||||
? t.binaryExpression(
|
||||
">>>",
|
||||
t.binaryExpression(
|
||||
"^",
|
||||
t.identifier(seedVarName),
|
||||
t.conditionalExpression(
|
||||
t.binaryExpression(
|
||||
"===",
|
||||
t.unaryExpression("typeof", t.identifier(paramName)),
|
||||
t.stringLiteral("string"),
|
||||
),
|
||||
t.binaryExpression(
|
||||
"<<",
|
||||
t.binaryExpression(
|
||||
"&",
|
||||
t.memberExpression(
|
||||
t.identifier(paramName),
|
||||
t.identifier("length"),
|
||||
),
|
||||
t.numericLiteral(1023),
|
||||
),
|
||||
t.numericLiteral(2),
|
||||
),
|
||||
t.conditionalExpression(
|
||||
t.binaryExpression(
|
||||
"===",
|
||||
t.unaryExpression("typeof", t.identifier(paramName)),
|
||||
t.stringLiteral("number"),
|
||||
),
|
||||
t.binaryExpression(
|
||||
"<<",
|
||||
t.binaryExpression(
|
||||
"&",
|
||||
t.identifier(paramName),
|
||||
t.numericLiteral(255),
|
||||
),
|
||||
t.numericLiteral(2),
|
||||
),
|
||||
t.numericLiteral(0),
|
||||
),
|
||||
),
|
||||
),
|
||||
t.numericLiteral(0),
|
||||
)
|
||||
: t.identifier(seedVarName);
|
||||
prefixStmts.push(
|
||||
t.variableDeclaration("const", [
|
||||
t.variableDeclarator(t.identifier(localInfo.localSeedName), seedInitExpr),
|
||||
]),
|
||||
);
|
||||
}
|
||||
prefixStmts.push(stepCallStmt);
|
||||
if (decoyBridgePool.length >= 2) {
|
||||
const d1 = decoyBridgePool[(bIdx * 2) % decoyBridgePool.length]!;
|
||||
const d2 = decoyBridgePool[(bIdx * 2 + 1) % decoyBridgePool.length]!;
|
||||
prefixStmts.push(
|
||||
t.ifStatement(
|
||||
buildOpaqueFalseAst(prng, blockSeed),
|
||||
t.blockStatement([
|
||||
t.expressionStatement(
|
||||
t.binaryExpression(
|
||||
"^",
|
||||
t.callExpression(t.identifier(d1), [
|
||||
t.numericLiteral(prng.nextInt(1, 255)),
|
||||
t.numericLiteral(2),
|
||||
]),
|
||||
t.callExpression(t.identifier(d2), [
|
||||
t.numericLiteral(prng.nextInt(1, 255)),
|
||||
t.numericLiteral(2),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
fakeCrossReferencesCreated += 3;
|
||||
} else {
|
||||
fakeCrossReferencesCreated += 1;
|
||||
}
|
||||
body.body.unshift(...prefixStmts);
|
||||
}
|
||||
|
||||
// Entangle every post-seed decoy function directly into `seedVarName` so stripping
|
||||
// any injected declaration triggers an immediate ReferenceError or flips seed parity.
|
||||
if (seedInjectIndex >= 0 && meshFns.length > 0) {
|
||||
const seedStmt = sanitizedInjectedStatements[seedInjectIndex];
|
||||
if (seedStmt && t.isVariableDeclaration(seedStmt)) {
|
||||
const decl = seedStmt.declarations.find(
|
||||
(d) => t.isIdentifier(d.id) && d.id.name === seedVarName,
|
||||
);
|
||||
if (
|
||||
decl &&
|
||||
decl.init &&
|
||||
t.isBinaryExpression(decl.init) &&
|
||||
(decl.init.operator === "|" || decl.init.operator === "^") &&
|
||||
t.isConditionalExpression(decl.init.right)
|
||||
) {
|
||||
const checkParam = prng.identifier({ style: "camel", hint: "fn", entropy: 2 });
|
||||
const everyCheck = t.callExpression(
|
||||
t.memberExpression(
|
||||
t.arrayExpression(meshFns.map((fn) => t.identifier(fn.id!.name))),
|
||||
t.identifier("every"),
|
||||
),
|
||||
[
|
||||
t.arrowFunctionExpression(
|
||||
[t.identifier(checkParam)],
|
||||
t.binaryExpression(
|
||||
"===",
|
||||
t.unaryExpression("typeof", t.identifier(checkParam)),
|
||||
t.stringLiteral("function"),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
decl.init.right.test = t.logicalExpression(
|
||||
"&&",
|
||||
everyCheck,
|
||||
decl.init.right.test,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (esmSelfSealReqIdent && esmSelfSealMetaUrlIdent) {
|
||||
const reqImportDecl = t.importDeclaration(
|
||||
[
|
||||
|
||||
@@ -27,6 +27,7 @@ export function generateRuntimeDeceptionSnippet(
|
||||
readonly protectsClientPlaintextSecrets: false;
|
||||
} {
|
||||
const suffix = prng.hex(4);
|
||||
void suffix;
|
||||
const eventCount = intensity === "stealth" ? 3 : intensity === "balanced" ? 6 : 10;
|
||||
const chaffText =
|
||||
chaffPayloads[0]?.rawText ??
|
||||
@@ -47,18 +48,25 @@ export function generateRuntimeDeceptionSnippet(
|
||||
|
||||
const initFn = prng.identifier({ style: "privateCamel", hint: "initRuntimeDeception", entropy: 4 });
|
||||
const vaultProp = prng.identifier({ style: "privateCamel", hint: "enclaveRuntime", entropy: 4 });
|
||||
const vaultLocal = prng.identifier({ style: "privateCamel", hint: "sealedFrame", entropy: 4 });
|
||||
const eventBridge = prng.identifier({ style: "privateCamel", hint: "enclaveEventBridge", entropy: 4 });
|
||||
const lines: string[] = [
|
||||
`(function ${initFn}() {`,
|
||||
` try {`,
|
||||
` const _g = typeof globalThis !== "undefined" ? globalThis : (typeof window !== "undefined" ? window : {});`,
|
||||
` const _execArgv = (typeof process !== "undefined" && Array.isArray(process.execArgv)) ? process.execArgv.join(" ") : "";`,
|
||||
` let _activeInspectorUrl = false;`,
|
||||
` try {`,
|
||||
` const _insMod = (typeof process !== "undefined" && typeof process.getBuiltinModule === "function") ? process.getBuiltinModule("node:inspector") : null;`,
|
||||
` if (_insMod && typeof _insMod.url === "function" && _insMod.url()) _activeInspectorUrl = true;`,
|
||||
` } catch (_) {}`,
|
||||
` const _isInspectorObserved =`,
|
||||
` _activeInspectorUrl ||`,
|
||||
` _execArgv.includes("--inspect") ||`,
|
||||
` _execArgv.includes("--remote-debugging") ||`,
|
||||
` Boolean(_g && (_g.__playwright || _g.__puppeteer_evaluation_script__ || _g.frida || _g._frida_ || (_g.navigator && _g.navigator.webdriver)));`,
|
||||
``,
|
||||
` const _shadowVault_${suffix} = Object.freeze({`,
|
||||
` const ${vaultLocal} = Object.freeze({`,
|
||||
` protocolVersion: "3.4.0",`,
|
||||
` attestationState: "RING0_SEALED",`,
|
||||
` status: "HARDWARE_ENCLAVE_DELEGATED",`,
|
||||
@@ -73,12 +81,12 @@ export function generateRuntimeDeceptionSnippet(
|
||||
` Object.defineProperty(_g, ${JSON.stringify(vaultProp)}, {`,
|
||||
` configurable: true,`,
|
||||
` enumerable: false,`,
|
||||
` get: function() { return _shadowVault_${suffix}; }`,
|
||||
` get: function() { return ${vaultLocal}; }`,
|
||||
` });`,
|
||||
` }`,
|
||||
``,
|
||||
` if (_g && typeof _g.addEventListener === "function") {`,
|
||||
` const _noopListener = function ${eventBridge}(ev) { return ev && ev.type ? _shadowVault_${suffix}.sessionEpoch : 0; };`,
|
||||
` const _noopListener = function ${eventBridge}(ev) { return ev && ev.type ? ${vaultLocal}.sessionEpoch : 0; };`,
|
||||
];
|
||||
|
||||
for (const evName of decoyEventNames) {
|
||||
|
||||
@@ -203,6 +203,8 @@ export interface SelfSealSnippet {
|
||||
|
||||
function emitMeasureFunction(
|
||||
helperName: string,
|
||||
siteIndex: number,
|
||||
siteSalt: string,
|
||||
siblingsLiteral: string,
|
||||
expectedLiteral: string,
|
||||
hardFailOnSiblingMismatch: boolean,
|
||||
@@ -214,6 +216,7 @@ function emitMeasureFunction(
|
||||
const lines: string[] = [];
|
||||
lines.push(`function ${helperName}() {`);
|
||||
lines.push(` var digest = 0;`);
|
||||
lines.push(` var _tampered = false;`);
|
||||
lines.push(` try {`);
|
||||
if (esmRequireHelperIdent && esmMetaUrlIdent) {
|
||||
lines.push(` var _req = ${esmRequireHelperIdent}(${esmMetaUrlIdent});`);
|
||||
@@ -226,9 +229,10 @@ function emitMeasureFunction(
|
||||
);
|
||||
lines.push(` var baseDir = _path.dirname(selfPath);`);
|
||||
} else {
|
||||
lines.push(` var _c = require("node:crypto");`);
|
||||
lines.push(` var _fs = require("node:fs");`);
|
||||
lines.push(` var _path = require("node:path");`);
|
||||
lines.push(` var _req = require;`);
|
||||
lines.push(` var _c = _req("node:crypto");`);
|
||||
lines.push(` var _fs = _req("node:fs");`);
|
||||
lines.push(` var _path = _req("node:path");`);
|
||||
lines.push(` var h = _c.createHash("sha256");`);
|
||||
lines.push(
|
||||
` var selfPath = (typeof __filename === "string" ? __filename : null);`,
|
||||
@@ -240,6 +244,7 @@ function emitMeasureFunction(
|
||||
` var baseDir = (typeof __dirname === "string" ? __dirname : null);`,
|
||||
);
|
||||
}
|
||||
lines.push(` h.update(${JSON.stringify(siteSalt)});`);
|
||||
lines.push(` var selfBuf = null;`);
|
||||
lines.push(
|
||||
` if (selfPath) { try { selfBuf = _fs.readFileSync(selfPath); h.update(selfBuf); } catch (_e) { selfBuf = null; } }`,
|
||||
@@ -259,7 +264,7 @@ function emitMeasureFunction(
|
||||
if (hardFailOnSiblingMismatch) {
|
||||
lines.push(` throw new Error("integrity check failed");`);
|
||||
} else {
|
||||
lines.push(` digest = 0xffffffff;`);
|
||||
lines.push(` _tampered = true;`);
|
||||
}
|
||||
lines.push(` }`);
|
||||
lines.push(` }`);
|
||||
@@ -281,7 +286,7 @@ function emitMeasureFunction(
|
||||
if (hardFailOnSiblingMismatch) {
|
||||
lines.push(` throw new Error("integrity check failed");`);
|
||||
} else {
|
||||
lines.push(` digest = 0xffffffff;`);
|
||||
lines.push(` _tampered = true;`);
|
||||
}
|
||||
lines.push(` }`);
|
||||
lines.push(` h.update(sp);`);
|
||||
@@ -296,6 +301,8 @@ function emitMeasureFunction(
|
||||
lines.push(
|
||||
` if (expected[String(siblings[i])]) throw new Error("integrity check failed");`,
|
||||
);
|
||||
} else {
|
||||
lines.push(` if (expected[String(siblings[i])]) _tampered = true;`);
|
||||
}
|
||||
lines.push(` h.update("missing:" + String(siblings[i]));`);
|
||||
lines.push(` }`);
|
||||
@@ -303,16 +310,26 @@ function emitMeasureFunction(
|
||||
if (envFingerprint) {
|
||||
lines.push(` var envNote = "";`);
|
||||
lines.push(` try {`);
|
||||
lines.push(` envNote += String(process.env.NODE_OPTIONS || "");`);
|
||||
lines.push(` envNote += (process.execArgv || []).join(",");`);
|
||||
lines.push(
|
||||
` envNote += (/\\[native code\\]/.test(Function.prototype.toString.call(Function.prototype.toString)) ? "N" : "T");`,
|
||||
);
|
||||
lines.push(` var _nodeOpts = String((typeof process !== "undefined" && process && process.env && process.env.NODE_OPTIONS) || "");`);
|
||||
lines.push(` var _execArgv = (typeof process !== "undefined" && process && Array.isArray(process.execArgv)) ? process.execArgv.join(",") : "";`);
|
||||
lines.push(` envNote += _nodeOpts + "|" + _execArgv;`);
|
||||
lines.push(` if (/--inspect(?:-brk|-port|-publish-uid|=|\\b)|--debug(?:-brk|-port|=|\\b)/.test(_nodeOpts + " " + _execArgv)) _tampered = true;`);
|
||||
lines.push(` var _fnToStr = Function.prototype.toString;`);
|
||||
lines.push(` var _nativeToStr = /\\[native code\\]/.test(_fnToStr.call(_fnToStr)) && /\\[native code\\]/.test(_fnToStr.call(Math.imul));`);
|
||||
lines.push(` var _isElectron = Boolean(typeof process !== "undefined" && process && process.versions && process.versions.electron);`);
|
||||
lines.push(` var _nativeFs = _isElectron || !(typeof process !== "undefined" && process && typeof process.getBuiltinModule === "function") || (_fs.readFileSync === process.getBuiltinModule("node:fs").readFileSync);`);
|
||||
lines.push(` if (!_nativeToStr || !_nativeFs) _tampered = true;`);
|
||||
lines.push(` envNote += (_nativeToStr && _nativeFs ? "N" : "T");`);
|
||||
lines.push(` try { var _ins = _req("node:inspector"); if (_ins && typeof _ins.url === "function" && _ins.url()) { envNote += "I"; _tampered = true; } } catch (_ei) {}`);
|
||||
lines.push(` } catch (_e3) { envNote += "E"; }`);
|
||||
lines.push(` h.update(envNote);`);
|
||||
}
|
||||
lines.push(` var hex = h.digest("hex");`);
|
||||
lines.push(` digest = parseInt(hex.slice(0, 8), 16) >>> 0;`);
|
||||
lines.push(` digest = (parseInt(hex.slice(0, 8), 16) & 0xfffffffe) >>> 0;`);
|
||||
if (siteIndex === 0) {
|
||||
lines.push(` if (digest === 0) digest = 0x40000002;`);
|
||||
lines.push(` if (_tampered) digest = (digest | 1) >>> 0;`);
|
||||
}
|
||||
lines.push(` } catch (_e4) {`);
|
||||
lines.push(
|
||||
` if (_e4 && _e4.message === "integrity check failed") throw _e4;`,
|
||||
@@ -375,10 +392,13 @@ export function generateSelfSealSnippet(
|
||||
hint: site === 0 ? "measureIntegrity" : `measureIntegrity${site}`,
|
||||
entropy: 4,
|
||||
});
|
||||
const siteSalt = `s${site}:${prng.hex(6)}`;
|
||||
helperNames.push(helperName);
|
||||
lines.push(
|
||||
...emitMeasureFunction(
|
||||
helperName,
|
||||
site,
|
||||
siteSalt,
|
||||
siblingsLiteral,
|
||||
expectedLiteral,
|
||||
hardFailOnSiblingMismatch,
|
||||
|
||||
@@ -75,6 +75,21 @@ import {
|
||||
|
||||
export const SIDECAR_ENTANGLE_SCHEMA = "bla-sidecar-entangle/v1" as const;
|
||||
|
||||
/**
|
||||
* Derive a one-way public binding nonce from a project/master seed so sidecar
|
||||
* preambles, custom sections, and metadata notes never leak the raw master seed.
|
||||
* Idempotent when `rawSeed` is already a `scn1-<32hex>` public tag.
|
||||
*/
|
||||
export function derivePublicSidecarSeedTag(rawSeed: string): string {
|
||||
if (/^scn1-[0-9a-f]{32}$/.test(rawSeed)) return rawSeed;
|
||||
const hex = createHash("sha256")
|
||||
.update("bla-sidecar-public-nonce/v1\0")
|
||||
.update(rawSeed)
|
||||
.digest("hex")
|
||||
.slice(0, 32);
|
||||
return `scn1-${hex}`;
|
||||
}
|
||||
|
||||
export type SidecarJsCarrier = "module" | "script" | "commonjs";
|
||||
|
||||
/**
|
||||
@@ -439,17 +454,18 @@ export function generateSidecarJsPreamble(
|
||||
const sidecars = (options.sidecarPaths ?? []).filter((p) => p.length > 0);
|
||||
const seedTag = options.seedTag ?? "bla-sidecar-v1";
|
||||
const softFold = options.softFold === true;
|
||||
const bindingName = options.bindingName ?? "__blaSidecarDigest";
|
||||
const expectedHex = options.expectedHex.toLowerCase();
|
||||
if (!/^[0-9a-f]{64}$/.test(expectedHex)) {
|
||||
throw new Error("expectedHex must be a 64-char lowercase hex SHA-256 digest");
|
||||
}
|
||||
const expectedU32 = parseInt(expectedHex.slice(0, 8), 16) >>> 0;
|
||||
const tag = expectedHex.slice(0, 8);
|
||||
const bindingName = options.bindingName ?? `_verifySiblingDigest_${tag}`;
|
||||
const expectedU32 = parseInt(tag, 16) >>> 0;
|
||||
const sidecarsLiteral = JSON.stringify(sidecars);
|
||||
const entryLiteral = JSON.stringify(options.entryPath);
|
||||
const seedLiteral = JSON.stringify(seedTag);
|
||||
const isEsm = options.carrier === "module";
|
||||
const reqHelperAlias = `__blaSidecarReq_${expectedHex.slice(0, 8)}`;
|
||||
const reqHelperAlias = `_resolveModuleRequire_${tag}`;
|
||||
|
||||
const lines: string[] = [];
|
||||
if (isEsm) {
|
||||
@@ -664,56 +680,57 @@ export function generateSidecarPythonPreamble(
|
||||
const sidecars = (options.sidecarPaths ?? []).filter((p) => p.length > 0);
|
||||
const seedTag = options.seedTag ?? "bla-sidecar-v1";
|
||||
const softFold = options.softFold === true;
|
||||
const bindingName = options.bindingName ?? "__bla_sidecar_digest";
|
||||
const expectedHex = options.expectedHex.toLowerCase();
|
||||
if (!/^[0-9a-f]{64}$/.test(expectedHex)) {
|
||||
throw new Error("expectedHex must be a 64-char lowercase hex SHA-256 digest");
|
||||
}
|
||||
const expectedU32 = parseInt(expectedHex.slice(0, 8), 16) >>> 0;
|
||||
const tag = expectedHex.slice(0, 8);
|
||||
const bindingName = options.bindingName ?? `_verify_sibling_digest_${tag}`;
|
||||
const expectedU32 = parseInt(tag, 16) >>> 0;
|
||||
const sidecarsLiteral = JSON.stringify(sidecars);
|
||||
const entryLiteral = JSON.stringify(options.entryPath);
|
||||
const seedLiteral = JSON.stringify(seedTag);
|
||||
const expectedLiteral = JSON.stringify(expectedHex);
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`import hashlib as __bla_hashlib`);
|
||||
lines.push(`import pathlib as __bla_pathlib`);
|
||||
lines.push(`import hashlib as _sc_hashlib_${tag}`);
|
||||
lines.push(`import pathlib as _sc_pathlib_${tag}`);
|
||||
lines.push(`${bindingName} = 0`);
|
||||
lines.push(`try:`);
|
||||
lines.push(` __bla_expected = ${expectedLiteral}`);
|
||||
lines.push(` __bla_h = __bla_hashlib.sha256()`);
|
||||
lines.push(` __bla_entry_label = ${entryLiteral}`);
|
||||
lines.push(` __bla_h.update(__bla_entry_label.encode("utf-8"))`);
|
||||
lines.push(` __bla_h.update(b"\\x00")`);
|
||||
lines.push(` __bla_sidecars = ${sidecarsLiteral}`);
|
||||
lines.push(` __bla_base = __bla_pathlib.Path(__file__).resolve().parent`);
|
||||
lines.push(` for __bla_sp in __bla_sidecars:`);
|
||||
lines.push(` __bla_h.update(__bla_sp.encode("utf-8"))`);
|
||||
lines.push(` __bla_h.update(b"\\x00")`);
|
||||
lines.push(` __bla_sp_path = __bla_pathlib.Path(__bla_sp)`);
|
||||
lines.push(` if not __bla_sp_path.is_absolute():`);
|
||||
lines.push(` __bla_sp_path = __bla_base / __bla_sp`);
|
||||
lines.push(` _sc_expected_${tag} = ${expectedLiteral}`);
|
||||
lines.push(` _sc_h_${tag} = _sc_hashlib_${tag}.sha256()`);
|
||||
lines.push(` _sc_entry_label_${tag} = ${entryLiteral}`);
|
||||
lines.push(` _sc_h_${tag}.update(_sc_entry_label_${tag}.encode("utf-8"))`);
|
||||
lines.push(` _sc_h_${tag}.update(b"\\x00")`);
|
||||
lines.push(` _sc_sidecars_${tag} = ${sidecarsLiteral}`);
|
||||
lines.push(` _sc_base_${tag} = _sc_pathlib_${tag}.Path(__file__).resolve().parent`);
|
||||
lines.push(` for _sc_sp_${tag} in _sc_sidecars_${tag}:`);
|
||||
lines.push(` _sc_h_${tag}.update(_sc_sp_${tag}.encode("utf-8"))`);
|
||||
lines.push(` _sc_h_${tag}.update(b"\\x00")`);
|
||||
lines.push(` _sc_sp_path_${tag} = _sc_pathlib_${tag}.Path(_sc_sp_${tag})`);
|
||||
lines.push(` if not _sc_sp_path_${tag}.is_absolute():`);
|
||||
lines.push(` _sc_sp_path_${tag} = _sc_base_${tag} / _sc_sp_${tag}`);
|
||||
lines.push(` try:`);
|
||||
lines.push(` __bla_h.update(__bla_sp_path.read_bytes())`);
|
||||
lines.push(` _sc_h_${tag}.update(_sc_sp_path_${tag}.read_bytes())`);
|
||||
lines.push(` except Exception:`);
|
||||
lines.push(` __bla_h.update(("missing:" + str(__bla_sp)).encode("utf-8"))`);
|
||||
lines.push(` __bla_h.update(b"\\x00")`);
|
||||
lines.push(` __bla_h.update(${seedLiteral}.encode("utf-8"))`);
|
||||
lines.push(` __bla_hex = __bla_h.hexdigest()`);
|
||||
lines.push(` ${bindingName} = int(__bla_hex[:8], 16) & 0xffffffff`);
|
||||
lines.push(` _sc_h_${tag}.update(("missing:" + str(_sc_sp_${tag})).encode("utf-8"))`);
|
||||
lines.push(` _sc_h_${tag}.update(b"\\x00")`);
|
||||
lines.push(` _sc_h_${tag}.update(${seedLiteral}.encode("utf-8"))`);
|
||||
lines.push(` _sc_hex_${tag} = _sc_h_${tag}.hexdigest()`);
|
||||
lines.push(` ${bindingName} = int(_sc_hex_${tag}[:8], 16) & 0xffffffff`);
|
||||
if (softFold) {
|
||||
lines.push(` if __bla_hex != __bla_expected:`);
|
||||
lines.push(` if _sc_hex_${tag} != _sc_expected_${tag}:`);
|
||||
lines.push(` ${bindingName} = (${bindingName} ^ 0xffffffff) & 0xffffffff`);
|
||||
} else {
|
||||
lines.push(` if __bla_hex != __bla_expected:`);
|
||||
lines.push(` if _sc_hex_${tag} != _sc_expected_${tag}:`);
|
||||
lines.push(` raise RuntimeError("integrity binding mismatch")`);
|
||||
}
|
||||
lines.push(`except Exception as __bla_e2:`);
|
||||
lines.push(`except Exception as _sc_err_${tag}:`);
|
||||
if (softFold) {
|
||||
lines.push(` ${bindingName} = 0`);
|
||||
} else {
|
||||
lines.push(
|
||||
` if isinstance(__bla_e2, RuntimeError) and str(__bla_e2) == "integrity binding mismatch":`,
|
||||
` if isinstance(_sc_err_${tag}, RuntimeError) and str(_sc_err_${tag}) == "integrity binding mismatch":`,
|
||||
);
|
||||
lines.push(` raise`);
|
||||
lines.push(` raise RuntimeError("integrity binding mismatch") from None`);
|
||||
|
||||
@@ -563,11 +563,30 @@ function classifyFunctionRole(
|
||||
}
|
||||
|
||||
function extractJsFunctionName(path: any): string {
|
||||
const parent = path.parent;
|
||||
// Recognize top-level route / IPC handler callbacks: ipcMain.handle("ch", fn), app.post("/p", fn)
|
||||
if (
|
||||
t.isCallExpression(parent) &&
|
||||
t.isMemberExpression(parent.callee) &&
|
||||
t.isIdentifier(parent.callee.property) &&
|
||||
/^(?:handle|on|once|get|post|put|delete|patch|use|all)$/.test(
|
||||
parent.callee.property.name,
|
||||
) &&
|
||||
parent.arguments.includes(path.node)
|
||||
) {
|
||||
const parentFn = path.getFunctionParent?.();
|
||||
if (!parentFn) {
|
||||
const routeArg = parent.arguments[0];
|
||||
const slugRaw =
|
||||
routeArg && t.isStringLiteral(routeArg) ? routeArg.value : "handler";
|
||||
const slug = slugRaw.replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "route";
|
||||
return `${parent.callee.property.name}_${slug}`;
|
||||
}
|
||||
}
|
||||
if (path.getFunctionParent && path.getFunctionParent() !== null) {
|
||||
return "";
|
||||
}
|
||||
const node = path.node;
|
||||
const parent = path.parent;
|
||||
if (t.isFunctionDeclaration(node) && node.id) {
|
||||
return node.id.name;
|
||||
}
|
||||
@@ -623,10 +642,75 @@ function extractStaticStringOrTemplate(node: t.Node | null | undefined): string
|
||||
return null;
|
||||
}
|
||||
|
||||
function isAlgebraicZeroEntropyAst(node: t.Node | null | undefined): boolean {
|
||||
if (!node || !t.isBinaryExpression(node)) return false;
|
||||
if (node.operator === "&" || node.operator === "*") {
|
||||
if (
|
||||
(t.isNumericLiteral(node.left) && node.left.value === 0) ||
|
||||
(t.isNumericLiteral(node.right) && node.right.value === 0)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (node.operator === "^" || node.operator === "-") {
|
||||
if (
|
||||
t.isIdentifier(node.left) &&
|
||||
t.isIdentifier(node.right) &&
|
||||
node.left.name === node.right.name
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
t.isMemberExpression(node.left) &&
|
||||
t.isMemberExpression(node.right) &&
|
||||
!node.left.computed &&
|
||||
!node.right.computed &&
|
||||
t.isIdentifier(node.left.object) &&
|
||||
t.isIdentifier(node.right.object) &&
|
||||
node.left.object.name === node.right.object.name &&
|
||||
t.isIdentifier(node.left.property) &&
|
||||
t.isIdentifier(node.right.property) &&
|
||||
node.left.property.name === node.right.property.name
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function extractHtmlInlineScripts(htmlSource: string): string {
|
||||
const scripts: string[] = [];
|
||||
const re = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(htmlSource)) !== null) {
|
||||
const attrs = m[1] ?? "";
|
||||
if (/\bsrc\s*=/i.test(attrs)) continue;
|
||||
const typeMatch = attrs.match(/\btype\s*=\s*["']?([^"'\s>]+)/i);
|
||||
const scriptType = (typeMatch?.[1] ?? "").toLowerCase();
|
||||
if (
|
||||
scriptType &&
|
||||
scriptType !== "module" &&
|
||||
scriptType !== "text/javascript" &&
|
||||
scriptType !== "application/javascript"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (m[2] && m[2].trim().length > 0) {
|
||||
scripts.push(m[2]);
|
||||
}
|
||||
}
|
||||
return scripts.join("\n;\n");
|
||||
}
|
||||
|
||||
function inspectRawBooleanReturnValue(
|
||||
node: t.Node | null | undefined,
|
||||
scope?: any,
|
||||
depth = 0,
|
||||
): { readonly isRawBool: boolean; readonly isTrueBranch: boolean } {
|
||||
if (!node) return { isRawBool: false, isTrueBranch: false };
|
||||
if (!node || depth > 4) return { isRawBool: false, isTrueBranch: false };
|
||||
if (t.isParenthesizedExpression(node)) {
|
||||
return inspectRawBooleanReturnValue(node.expression, scope, depth + 1);
|
||||
}
|
||||
if (t.isBooleanLiteral(node)) {
|
||||
return { isRawBool: true, isTrueBranch: node.value === true };
|
||||
}
|
||||
@@ -638,9 +722,37 @@ function inspectRawBooleanReturnValue(
|
||||
) {
|
||||
return { isRawBool: true, isTrueBranch: node.argument.value === 0 };
|
||||
}
|
||||
if (
|
||||
t.isUnaryExpression(node) &&
|
||||
node.operator === "!" &&
|
||||
t.isUnaryExpression(node.argument) &&
|
||||
node.argument.operator === "!"
|
||||
) {
|
||||
return { isRawBool: true, isTrueBranch: true };
|
||||
}
|
||||
if (
|
||||
t.isCallExpression(node) &&
|
||||
t.isIdentifier(node.callee) &&
|
||||
node.callee.name === "Boolean"
|
||||
) {
|
||||
return { isRawBool: true, isTrueBranch: true };
|
||||
}
|
||||
if (
|
||||
t.isBinaryExpression(node) &&
|
||||
(node.operator === "===" ||
|
||||
node.operator === "!==" ||
|
||||
node.operator === "==" ||
|
||||
node.operator === "!=" ||
|
||||
node.operator === "<" ||
|
||||
node.operator === "<=" ||
|
||||
node.operator === ">" ||
|
||||
node.operator === ">=")
|
||||
) {
|
||||
return { isRawBool: true, isTrueBranch: true };
|
||||
}
|
||||
if (t.isConditionalExpression(node)) {
|
||||
const c = inspectRawBooleanReturnValue(node.consequent);
|
||||
const a = inspectRawBooleanReturnValue(node.alternate);
|
||||
const c = inspectRawBooleanReturnValue(node.consequent, scope, depth + 1);
|
||||
const a = inspectRawBooleanReturnValue(node.alternate, scope, depth + 1);
|
||||
if (c.isRawBool && a.isRawBool) {
|
||||
return {
|
||||
isRawBool: true,
|
||||
@@ -648,6 +760,33 @@ function inspectRawBooleanReturnValue(
|
||||
};
|
||||
}
|
||||
}
|
||||
if (t.isIdentifier(node) && scope?.getBinding) {
|
||||
const binding = scope.getBinding(node.name);
|
||||
if (binding && t.isVariableDeclarator(binding.path?.node)) {
|
||||
const assignedExprs: Array<t.Node | null | undefined> = [];
|
||||
if (binding.path.node.init) {
|
||||
assignedExprs.push(binding.path.node.init);
|
||||
}
|
||||
for (const viol of binding.constantViolations ?? []) {
|
||||
if (t.isAssignmentExpression(viol.node) && viol.node.operator === "=") {
|
||||
assignedExprs.push(viol.node.right);
|
||||
} else {
|
||||
return { isRawBool: false, isTrueBranch: false };
|
||||
}
|
||||
}
|
||||
if (assignedExprs.length > 0) {
|
||||
const evals = assignedExprs.map((e) =>
|
||||
inspectRawBooleanReturnValue(e, scope, depth + 1),
|
||||
);
|
||||
if (evals.every((ev) => ev.isRawBool)) {
|
||||
return {
|
||||
isRawBool: true,
|
||||
isTrueBranch: evals.some((ev) => ev.isTrueBranch),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { isRawBool: false, isTrueBranch: false };
|
||||
}
|
||||
|
||||
@@ -861,9 +1000,20 @@ function buildJsSurgicalWorkorder(
|
||||
usesCryptographicDigest = true;
|
||||
}
|
||||
},
|
||||
IfStatement(ifPath) {
|
||||
if (branchCandidates.length < 12) {
|
||||
const stmtLine = ifPath.node.loc?.start.line ?? line;
|
||||
branchCandidates.push({
|
||||
functionName: fnName,
|
||||
line: stmtLine,
|
||||
statementKind: "if-branch",
|
||||
rewriteHint: `Entangle condition in \`${fnName}\` (line ${stmtLine}) with a shared-state invariant check and route the alternate/shadow path through a domain-plausible helper.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
ReturnStatement(retPath) {
|
||||
const arg = retPath.node.argument;
|
||||
const b = inspectRawBooleanReturnValue(arg);
|
||||
const b = inspectRawBooleanReturnValue(arg, retPath.scope);
|
||||
if (b.isRawBool) {
|
||||
if (b.isTrueBranch) hasTrueLiteralReturn = true;
|
||||
else hasFalseLiteralReturn = true;
|
||||
@@ -871,6 +1021,15 @@ function buildJsSurgicalWorkorder(
|
||||
} else if (arg) {
|
||||
hasComputedReturn = true;
|
||||
}
|
||||
if (arg && branchCandidates.length < 12) {
|
||||
const stmtLine = retPath.node.loc?.start.line ?? line;
|
||||
branchCandidates.push({
|
||||
functionName: fnName,
|
||||
line: stmtLine,
|
||||
statementKind: "return-gate",
|
||||
rewriteHint: `Before returning from \`${fnName}\` (line ${stmtLine}), update shared state slot and fold an opaque-true invariant into the return value or guard.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
BinaryExpression(binPath) {
|
||||
if (binPath.node.operator === ">>>" && t.isNumericLiteral(binPath.node.right) && binPath.node.right.value === 0) {
|
||||
@@ -946,28 +1105,6 @@ function buildJsSurgicalWorkorder(
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (t.isBlockStatement(path.node.body) && branchCandidates.length < 12) {
|
||||
for (const stmt of path.node.body.body) {
|
||||
const stmtLine = stmt.loc?.start.line ?? line;
|
||||
if (t.isIfStatement(stmt)) {
|
||||
branchCandidates.push({
|
||||
functionName: fnName,
|
||||
line: stmtLine,
|
||||
statementKind: "if-branch",
|
||||
rewriteHint: `Entangle condition in \`${fnName}\` (line ${stmtLine}) with a shared-state invariant check and route the alternate/shadow path through a domain-plausible helper.`,
|
||||
});
|
||||
} else if (t.isReturnStatement(stmt) && stmt.argument) {
|
||||
branchCandidates.push({
|
||||
functionName: fnName,
|
||||
line: stmtLine,
|
||||
statementKind: "return-gate",
|
||||
rewriteHint: `Before returning from \`${fnName}\` (line ${stmtLine}), update shared state slot and fold an opaque-true invariant into the return value or guard.`,
|
||||
});
|
||||
}
|
||||
if (branchCandidates.length >= 12) break;
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
@@ -1123,8 +1260,31 @@ function extractPythonFunctions(source: string): ParsedPythonFunction[] {
|
||||
if (singleLineAfterColon && singleLineAfterColon[1]!.trim().length > 0) {
|
||||
bodyLines.push(" " + singleLineAfterColon[1]!.trim());
|
||||
} else {
|
||||
let inTripleQuote: '"""' | "'''" | null = null;
|
||||
const updateTripleQuote = (lineStr: string): void => {
|
||||
for (let c = 0; c < lineStr.length; c++) {
|
||||
if (lineStr[c] === "\\" && inTripleQuote !== null) {
|
||||
c += 1;
|
||||
continue;
|
||||
}
|
||||
if (inTripleQuote === null && lineStr[c] === "#") break;
|
||||
const tri = lineStr.slice(c, c + 3);
|
||||
if (inTripleQuote === null && (tri === '"""' || tri === "'''")) {
|
||||
inTripleQuote = tri;
|
||||
c += 2;
|
||||
} else if (inTripleQuote !== null && tri === inTripleQuote) {
|
||||
inTripleQuote = null;
|
||||
c += 2;
|
||||
}
|
||||
}
|
||||
};
|
||||
for (let b = sigEndLineIdx + 1; b < lines.length; b++) {
|
||||
const bLine = lines[b]!;
|
||||
if (inTripleQuote !== null) {
|
||||
bodyLines.push(bLine);
|
||||
updateTripleQuote(bLine);
|
||||
continue;
|
||||
}
|
||||
const trimmed = bLine.trim();
|
||||
if (trimmed.length === 0 || trimmed.startsWith("#")) {
|
||||
bodyLines.push(bLine);
|
||||
@@ -1133,6 +1293,7 @@ function extractPythonFunctions(source: string): ParsedPythonFunction[] {
|
||||
const bIndent = measureIndentWidth(bLine);
|
||||
if (bIndent <= indent) break;
|
||||
bodyLines.push(bLine);
|
||||
updateTripleQuote(bLine);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1383,7 +1544,10 @@ function buildSurgicalWorkorderForFile(
|
||||
format === "typescript" ||
|
||||
format === "html-bundle"
|
||||
) {
|
||||
const src = readFileSync(absPath, "utf8");
|
||||
const rawSrc = readFileSync(absPath, "utf8");
|
||||
const src =
|
||||
format === "html-bundle" ? extractHtmlInlineScripts(rawSrc) : rawSrc;
|
||||
if (format === "html-bundle" && src.trim().length === 0) return undefined;
|
||||
return buildJsSurgicalWorkorder(src, relPath);
|
||||
}
|
||||
if (format === "python-source") {
|
||||
@@ -1441,6 +1605,8 @@ const INTERESTING_EXT = new Set([
|
||||
".ts",
|
||||
".tsx",
|
||||
".jsx",
|
||||
".html",
|
||||
".htm",
|
||||
".py",
|
||||
".pyc",
|
||||
".c",
|
||||
@@ -1460,14 +1626,25 @@ const INTERESTING_EXT = new Set([
|
||||
".db",
|
||||
]);
|
||||
|
||||
const HIGH_RISK_FILENAME_RE =
|
||||
/(?:auth|license|verify|gate|token|policy|entitle|secret|key|sign|vault|ipc|main|preload|panel|guard|crypto)/i;
|
||||
|
||||
function scoreCandidatePriority(filePath: string): number {
|
||||
const base = basename(filePath);
|
||||
if (HIGH_RISK_FILENAME_RE.test(base)) return 0;
|
||||
if (HIGH_RISK_FILENAME_RE.test(filePath)) return 1;
|
||||
return 2;
|
||||
}
|
||||
|
||||
function walkWeaveCandidateFiles(
|
||||
root: string,
|
||||
limit: number,
|
||||
skipBuildDirs: boolean,
|
||||
): string[] {
|
||||
const out: string[] = [];
|
||||
const scanCap = Math.max(limit * 6, 256);
|
||||
const stack = [root];
|
||||
while (stack.length > 0 && out.length < limit) {
|
||||
while (stack.length > 0 && out.length < scanCap) {
|
||||
const dir = stack.pop()!;
|
||||
let entries;
|
||||
try {
|
||||
@@ -1476,7 +1653,7 @@ function walkWeaveCandidateFiles(
|
||||
continue;
|
||||
}
|
||||
for (const ent of entries) {
|
||||
if (out.length >= limit) break;
|
||||
if (out.length >= scanCap) break;
|
||||
if (SCAN_SKIP_ALWAYS.has(ent.name)) continue;
|
||||
if (skipBuildDirs && SCAN_SKIP_BUILD_DIRS.has(ent.name)) continue;
|
||||
if (ent.name.startsWith(".") && ent.name !== ".blarc") continue;
|
||||
@@ -1501,7 +1678,13 @@ function walkWeaveCandidateFiles(
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
out.sort((a, b) => {
|
||||
const pa = scoreCandidatePriority(a);
|
||||
const pb = scoreCandidatePriority(b);
|
||||
if (pa !== pb) return pa - pb;
|
||||
return a.localeCompare(b);
|
||||
});
|
||||
return out.slice(0, limit);
|
||||
}
|
||||
|
||||
function listCandidateFiles(root: string, limit: number): string[] {
|
||||
@@ -1705,7 +1888,7 @@ ${acceptance}
|
||||
|
||||
1. \`resources/read\` → \`${WEAVE_DIRECTIVES_URI}\`
|
||||
2. \`bla_weave_plan\` → 只读计划 JSON(\`${WEAVE_DECOY_SCHEMA}\`,含 AST \`surgicalWorkorder\`)
|
||||
3. \`bla_verify_weave\` → 验证 Agent 织入后的源码/产物是否满足 6 项结构验收(\`${WEAVE_VERIFY_SCHEMA}\`)
|
||||
3. \`bla_verify_weave\` → 验证 Agent 织入后的源码/产物是否满足 7 项结构验收(\`${WEAVE_VERIFY_SCHEMA}\`)
|
||||
4. \`bla_harden\` / \`bla_defend\` / \`bla_protect\` 传 \`weave_decoys: true\`
|
||||
|
||||
## 管线现状
|
||||
@@ -1937,6 +2120,7 @@ function verifyJsWeaveFile(
|
||||
const rawBooleanReturnFunctions = new Set<string>();
|
||||
const cleartextCompareLiterals: string[] = [];
|
||||
const plaintextFlagLiterals: string[] = [];
|
||||
const algebraicNoopSites: string[] = [];
|
||||
let conditionalCount = 0;
|
||||
let literalFalseBranchCount = 0;
|
||||
let syntaxValid = true;
|
||||
@@ -2050,7 +2234,7 @@ function verifyJsWeaveFile(
|
||||
},
|
||||
});
|
||||
|
||||
// First pass: collect all named top-level / assigned / method functions
|
||||
// First pass: collect all named top-level / assigned / method / route-callback functions
|
||||
traverse(ast, {
|
||||
Function(path) {
|
||||
const fnName = extractJsFunctionName(path);
|
||||
@@ -2058,6 +2242,13 @@ function verifyJsWeaveFile(
|
||||
if (!discoveredFunctions.includes(fnName)) {
|
||||
discoveredFunctions.push(fnName);
|
||||
}
|
||||
if (
|
||||
t.isCallExpression(path.parent) &&
|
||||
t.isMemberExpression(path.parent.callee) &&
|
||||
path.parent.arguments.some((a) => a === path.node)
|
||||
) {
|
||||
entryFunctions.add(fnName);
|
||||
}
|
||||
fnParamCounts.set(fnName, path.node.params.length);
|
||||
if (!callEdges.has(fnName)) {
|
||||
callEdges.set(fnName, new Set());
|
||||
@@ -2219,7 +2410,7 @@ function verifyJsWeaveFile(
|
||||
ReturnStatement(retPath) {
|
||||
if (isInsideDeadBranch(retPath)) return;
|
||||
const arg = retPath.node.argument;
|
||||
const b = inspectRawBooleanReturnValue(arg);
|
||||
const b = inspectRawBooleanReturnValue(arg, retPath.scope);
|
||||
if (b.isRawBool) {
|
||||
if (b.isTrueBranch) fnHasTrueLiteralReturn = true;
|
||||
else fnHasFalseLiteralReturn = true;
|
||||
@@ -2229,7 +2420,9 @@ function verifyJsWeaveFile(
|
||||
},
|
||||
BinaryExpression(binPath) {
|
||||
if (isInsideDeadBranch(binPath)) return;
|
||||
if (
|
||||
if (isAlgebraicZeroEntropyAst(binPath.node)) {
|
||||
algebraicNoopSites.push(`${fnName}:${binPath.node.operator}`);
|
||||
} else if (
|
||||
binPath.node.operator === "^" &&
|
||||
!(t.isNumericLiteral(binPath.node.left) && t.isNumericLiteral(binPath.node.right))
|
||||
) {
|
||||
@@ -2278,6 +2471,15 @@ function verifyJsWeaveFile(
|
||||
Identifier(idPath) {
|
||||
const name = idPath.node.name;
|
||||
if (isInsideDeadBranch(idPath)) return;
|
||||
let insideZeroEntropy = false;
|
||||
let anc: any = idPath.parentPath;
|
||||
while (anc && !t.isFunction(anc.node)) {
|
||||
if (t.isBinaryExpression(anc.node) && isAlgebraicZeroEntropyAst(anc.node)) {
|
||||
insideZeroEntropy = true;
|
||||
break;
|
||||
}
|
||||
anc = anc.parentPath;
|
||||
}
|
||||
if (
|
||||
discoveredSet.has(name) &&
|
||||
name !== fnName &&
|
||||
@@ -2288,7 +2490,8 @@ function verifyJsWeaveFile(
|
||||
if (
|
||||
moduleStateVars.has(name) &&
|
||||
isModuleScopedStateBinding(idPath, name) &&
|
||||
!isPureAssignmentTarget(idPath)
|
||||
!isPureAssignmentTarget(idPath) &&
|
||||
!insideZeroEntropy
|
||||
) {
|
||||
functionsReadingState.add(fnName);
|
||||
if (!isInsideIfGuardTestOnly(idPath)) {
|
||||
@@ -2674,8 +2877,18 @@ function verifyJsWeaveFile(
|
||||
}
|
||||
|
||||
// Check 7: crown-jewel-entanglement (dissolve raw boolean gates, cleartext compares,
|
||||
// lane-independent byte loops, plaintext FLAG literals, and cosmetic side-effect-only weaves)
|
||||
const isPostHardenLabyrinth = discoveredFunctions.length > 15;
|
||||
// lane-independent byte loops, plaintext FLAG literals, algebraic zero-entropy fake weaves,
|
||||
// and cosmetic side-effect-only weaves)
|
||||
const blaShieldedTagCount = discoveredFunctions.filter((fn) =>
|
||||
/^_?[A-Za-z][A-Za-z0-9]*_[0-9a-f]{3,4}$/i.test(fn),
|
||||
).length;
|
||||
const isPostHardenLabyrinth =
|
||||
discoveredFunctions.length > 24 &&
|
||||
blaShieldedTagCount >= 8 &&
|
||||
(/ALIGNMENT_EVAL_CANARY_GUID|EVIDENCE_CONTRACT_SUMMARY|_interlockSafetyCorpus_/i.test(
|
||||
source,
|
||||
) ||
|
||||
source.includes("Math.imul("));
|
||||
const laneLint = isPostHardenLabyrinth
|
||||
? { looksLaneIndependent: false, findings: [] as const }
|
||||
: lintLaneIndependence(source);
|
||||
@@ -2711,6 +2924,11 @@ function verifyJsWeaveFile(
|
||||
`cleartext secret comparison [${cleartextCompareLiterals.slice(0, 3).join(", ")}]`,
|
||||
);
|
||||
}
|
||||
if (!isPostHardenLabyrinth && algebraicNoopSites.length > 0) {
|
||||
crownJewelDefects.push(
|
||||
`algebraic zero-entropy fake weave expression(s) [${algebraicNoopSites.slice(0, 3).join(", ")}]`,
|
||||
);
|
||||
}
|
||||
if (plaintextFlagLiterals.length > 0) {
|
||||
crownJewelDefects.push(
|
||||
`hardcoded plaintext FLAG literal [${plaintextFlagLiterals.slice(0, 2).join(", ")}]`,
|
||||
@@ -2892,16 +3110,26 @@ function verifyPythonWeaveFile(
|
||||
const hasLiteralFalse = /\bif\s+(?:False|0|1\s*==\s*2)\s*:/.test(strippedSource);
|
||||
|
||||
// Verify that shared state containers are actually touched inside >= 2 function bodies
|
||||
// (or >= 1 customer def when python-customer-def-weave / warm-init is active)
|
||||
// AND mutated inside >= 1 function body (or >= 1 customer def when python-customer-def-weave is active)
|
||||
const fnsTouchingState = new Set<string>();
|
||||
const fnsMutatingState = new Set<string>();
|
||||
for (const [fn, body] of fnBodies.entries()) {
|
||||
for (const sv of stateVars) {
|
||||
if (new RegExp(`\\b${sv}\\b`).test(body)) {
|
||||
fnsTouchingState.add(fn);
|
||||
}
|
||||
const mutRe = new RegExp(
|
||||
`\\b${sv}\\s*(?:\\[[^\\]]+\\]\\s*(?:[+^|&-]?=)|\\.(?:update|setdefault|pop|clear|append|extend|add|remove|discard)\\s*\\(|[+^|&-]=)|\\bglobal\\s+[^\\n]*\\b${sv}\\b[\\s\\S]*?\\b${sv}\\s*=`,
|
||||
);
|
||||
if (mutRe.test(body)) {
|
||||
fnsMutatingState.add(fn);
|
||||
}
|
||||
}
|
||||
if (/\["epoch"\]|\["warm"\]/.test(body)) {
|
||||
fnsTouchingState.add(fn);
|
||||
if (/\["(?:epoch|warm)"\]\s*[+^|&-]?=/.test(body)) {
|
||||
fnsMutatingState.add(fn);
|
||||
}
|
||||
}
|
||||
}
|
||||
const isPostProtectWeave =
|
||||
@@ -2909,15 +3137,27 @@ function verifyPythonWeaveFile(
|
||||
"python-customer-def-weave",
|
||||
);
|
||||
const statePassed =
|
||||
(stateVars.length > 0 && fnsTouchingState.size >= 2) ||
|
||||
(stateVars.length > 0 &&
|
||||
fnsTouchingState.size >= 2 &&
|
||||
fnsMutatingState.size >= 1) ||
|
||||
(isPostProtectWeave && fnsTouchingState.size >= 1);
|
||||
|
||||
const pyCrownJewelDefects: string[] = [];
|
||||
if (!isPostProtectWeave && fnNames.length <= 15) {
|
||||
if (!isPostProtectWeave) {
|
||||
const publicGateFns = fnNames.filter(
|
||||
(f) => !f.startsWith("_") && classifyFunctionRole(f, true) === "gate-or-auth",
|
||||
);
|
||||
for (const fn of fnNames) {
|
||||
const strippedBody = fnBodies.get(fn) ?? "";
|
||||
if (
|
||||
/\b[A-Za-z_][A-Za-z0-9_.\[\]"']*\s*(?:&\s*0\b|\*\s*0\b)|\b0\s*[&*]\s*[A-Za-z_]|(\b[A-Za-z_][A-Za-z0-9_]*)\s*\^\s*\1\b/.test(
|
||||
strippedBody,
|
||||
)
|
||||
) {
|
||||
pyCrownJewelDefects.push(
|
||||
`algebraic zero-entropy fake weave expression in def '${fn}'`,
|
||||
);
|
||||
}
|
||||
const isPublic = !fn.startsWith("_");
|
||||
if (classifyFunctionRole(fn, isPublic) !== "gate-or-auth") {
|
||||
continue;
|
||||
@@ -2925,7 +3165,6 @@ function verifyPythonWeaveFile(
|
||||
if (!isPublic && publicGateFns.length > 0) {
|
||||
continue;
|
||||
}
|
||||
const strippedBody = fnBodies.get(fn) ?? "";
|
||||
const returnMatches = [...strippedBody.matchAll(/\breturn\s+([^\r\n#]+)/g)].map(
|
||||
(rm) => rm[1]!.trim(),
|
||||
);
|
||||
@@ -3370,7 +3609,12 @@ export function verifyWeaveTarget(
|
||||
format === "typescript" ||
|
||||
format === "html-bundle"
|
||||
) {
|
||||
const src = readFileSync(file, "utf8");
|
||||
const rawSrc = readFileSync(file, "utf8");
|
||||
const src =
|
||||
format === "html-bundle" ? extractHtmlInlineScripts(rawSrc) : rawSrc;
|
||||
if (format === "html-bundle" && src.trim().length === 0) {
|
||||
continue;
|
||||
}
|
||||
const { fileReport, actions } = verifyJsWeaveFile(
|
||||
file,
|
||||
relPath,
|
||||
|
||||
@@ -229,6 +229,7 @@ export function formatDoctorReport(doc: DoctorDiagnosticReport): string {
|
||||
` • WebAssembly (.wasm) Custom & Name Section Shield: ${formatEngineStatus(doc.engines.wasmBinaryShield)}`,
|
||||
` • Python (.py / CPython .pyc) Marshal Tarpit Shield: ${formatEngineStatus(doc.engines.pythonPycMarshalShield)}`,
|
||||
` • Native Binary (ELF / Mach-O / PE) Section Shield: ${formatEngineStatus(doc.engines.nativeElfMachoPeShield)}`,
|
||||
` • Android DEX / R8 Exhaustion & Layout Shield: ${formatEngineStatus(doc.engines.androidDexR8Shield)}`,
|
||||
` • Archive (ZIP / Android APK) Enclave Shield: ${formatEngineStatus(doc.engines.zipApkArchiveShield)}`,
|
||||
` • AI Model (Safetensors / GGUF) Nesting Breaker: ${formatEngineStatus(doc.engines.aiModelShield)}`,
|
||||
` • Erlang BEAM Chunk & Atom Exhaustion Shield: ${formatEngineStatus(doc.engines.erlangBeamShield)}`,
|
||||
|
||||
@@ -32,6 +32,7 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
|
||||
"allow_js_wasm_hydrate_dump",
|
||||
"allow_wasm_xor_mask_sidecar",
|
||||
"allow_wasm_seal_xor_known_plaintext",
|
||||
"allow_release_hygiene_leak",
|
||||
"seed",
|
||||
"dry_run",
|
||||
"max_artifacts",
|
||||
@@ -64,6 +65,7 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
|
||||
"allow_js_wasm_hydrate_dump",
|
||||
"allow_wasm_xor_mask_sidecar",
|
||||
"allow_wasm_seal_xor_known_plaintext",
|
||||
"allow_release_hygiene_leak",
|
||||
"seed",
|
||||
"in_place",
|
||||
"confirm_overwrite",
|
||||
@@ -87,6 +89,7 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
|
||||
"allow_js_wasm_hydrate_dump",
|
||||
"allow_wasm_xor_mask_sidecar",
|
||||
"allow_wasm_seal_xor_known_plaintext",
|
||||
"allow_release_hygiene_leak",
|
||||
"seed",
|
||||
"llm_directives",
|
||||
"in_place",
|
||||
@@ -104,6 +107,9 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
|
||||
"numeric_template_leak_known",
|
||||
"summary_path",
|
||||
"run_id",
|
||||
"manifest_path",
|
||||
"public_key_path",
|
||||
"require_pinned_key",
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -118,12 +124,14 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
|
||||
"allow_wasm_xor_mask_sidecar",
|
||||
"allow_wasm_seal_xor_known_plaintext",
|
||||
"allow_lane_independent",
|
||||
"allow_stable_panel_derive",
|
||||
"allow_panel_offline_oracle",
|
||||
"allow_release_hygiene_leak",
|
||||
],
|
||||
},
|
||||
{
|
||||
tool: "bla_lint_lanes",
|
||||
params: ["path"],
|
||||
params: ["path", "allow_lane_independent"],
|
||||
},
|
||||
{
|
||||
tool: "bla_lint_seal",
|
||||
@@ -135,7 +143,7 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
|
||||
},
|
||||
{
|
||||
tool: "bla_lint_panel_derive",
|
||||
params: ["path"],
|
||||
params: ["path", "allow_stable_panel_derive", "allow_panel_offline_oracle"],
|
||||
},
|
||||
{
|
||||
tool: "bla_lint_js_aes_unwrap",
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
import { parse } from "@babel/parser";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import vm from "node:vm";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { SeededPrng } from "../src/core/prng.js";
|
||||
import { encryptStrings } from "../src/engine/encrypt-strings.js";
|
||||
import { hardenProject } from "../src/engine/harden.js";
|
||||
import { lintJsAesUnwrapSource } from "../src/engine/js-aes-unwrap-lint.js";
|
||||
import {
|
||||
lintSealCommitmentFile,
|
||||
lintSealCommitmentSource,
|
||||
} from "../src/engine/seal-commitment-lint.js";
|
||||
import { verifyTarget } from "../src/engine/verifier.js";
|
||||
import { protectEvmBytecodeBuffer } from "../src/shields/formats/evm-bytecode.js";
|
||||
import { protectJvmClassBuffer } from "../src/shields/formats/jvm-bytecode.js";
|
||||
import { transformJavaScriptWithBlaShield } from "../src/shields/javascript/ast-shield.js";
|
||||
import {
|
||||
finalizeSelfSealSelfDigest,
|
||||
generateSelfSealSnippet,
|
||||
verifySelfSealSelfDigest,
|
||||
} from "../src/shields/runtime/self-seal.js";
|
||||
import { verifyWeaveTarget } from "../src/shields/weave/weave-decoy.js";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const d = mkdtempSync(join(tmpdir(), prefix));
|
||||
tempDirs.push(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
while (tempDirs.length > 0) {
|
||||
const dir = tempDirs.pop()!;
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
/** Minimal valid WASM module exporting `add(i32, i32) -> i32`. */
|
||||
function minimalValidWasm(): Buffer {
|
||||
return Buffer.from([
|
||||
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
|
||||
// Type section: 1 func (i32, i32) -> i32
|
||||
0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f,
|
||||
// Function section: 1 func of type 0
|
||||
0x03, 0x02, 0x01, 0x00,
|
||||
// Export section: "add" -> func 0
|
||||
0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00,
|
||||
// Code section: local.get 0, local.get 1, i32.add, end
|
||||
0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal structurally complete JVM `.class` file (Java 8 / v52.0):
|
||||
* cp_count = 3
|
||||
* #1 = CONSTANT_Class_info -> #2
|
||||
* #2 = CONSTANT_Utf8_info("Demo")
|
||||
* access_flags = 0x0021 (ACC_PUBLIC | ACC_SUPER)
|
||||
* this_class = 1, super_class = 0
|
||||
* interfaces_count = 0, fields_count = 0, methods_count = 0, attributes_count = 0
|
||||
*/
|
||||
function minimalCompleteJvmClass(): Buffer {
|
||||
const className = Buffer.from("Demo", "utf8");
|
||||
const header = Buffer.alloc(10);
|
||||
header.writeUInt32BE(0xcafebabe, 0);
|
||||
header.writeUInt16BE(0, 4);
|
||||
header.writeUInt16BE(52, 6);
|
||||
header.writeUInt16BE(3, 8); // cp_count = 3 (#1, #2)
|
||||
|
||||
const cp1 = Buffer.from([0x07, 0x00, 0x02]); // CONSTANT_Class -> #2
|
||||
const cp2 = Buffer.alloc(3 + className.length);
|
||||
cp2[0] = 0x01; // CONSTANT_Utf8
|
||||
cp2.writeUInt16BE(className.length, 1);
|
||||
className.copy(cp2, 3);
|
||||
|
||||
const body = Buffer.alloc(16);
|
||||
body.writeUInt16BE(0x0021, 0); // access_flags
|
||||
body.writeUInt16BE(1, 2); // this_class = #1
|
||||
body.writeUInt16BE(0, 4); // super_class = 0 (java/lang/Object bootstrap shape)
|
||||
body.writeUInt16BE(0, 6); // interfaces_count = 0
|
||||
body.writeUInt16BE(0, 8); // fields_count = 0
|
||||
body.writeUInt16BE(0, 10); // methods_count = 0
|
||||
body.writeUInt16BE(0, 12); // attributes_count = 0 — wait: 8 + 2 + 2 + 2 = 14 bytes total!
|
||||
return Buffer.concat([header, cp1, cp2, body.subarray(0, 14)]);
|
||||
}
|
||||
|
||||
function collectFilesRecursive(dir: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const ent of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, ent.name);
|
||||
if (ent.isDirectory()) {
|
||||
out.push(...collectFilesRecursive(full));
|
||||
} else if (ent.isFile()) {
|
||||
out.push(full);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("CI 5-Layer Red-Team Adversarial Regression Gate", () => {
|
||||
it("Layer 1: JS AST shield eliminates static prefix/array-manifest fingerprints and preserves VM equivalence", () => {
|
||||
const source = `
|
||||
function computeInvoiceDigest(accountId, seats) {
|
||||
const base = (accountId * 31 + seats * 17) >>> 0;
|
||||
return base ^ 0x5a5a1234;
|
||||
}
|
||||
module.exports = { computeInvoiceDigest };
|
||||
`;
|
||||
const shielded = transformJavaScriptWithBlaShield(source, {
|
||||
intensity: "bankrupt",
|
||||
seed: "ci-redteam-layer1-seed",
|
||||
filename: "billing.cjs",
|
||||
sourceType: "commonjs",
|
||||
});
|
||||
|
||||
// 1. Zero greppable decoy prefixes or dead `void [...]` manifest sweeps
|
||||
expect(shielded.code).not.toMatch(
|
||||
/\b(?:obligationFlood_|scc_|labyrinthDispatch_|fridaCaptureSaturator_|_shadowVault_|__blaSidecar)/,
|
||||
);
|
||||
expect(shielded.code).not.toMatch(/void\s*\[[^\]]{40,}\]/);
|
||||
|
||||
// 2. Functional equivalence inside isolated VM context
|
||||
const runShielded = (code: string) => {
|
||||
const mod = { exports: {} as Record<string, (a: number, b: number) => number> };
|
||||
vm.runInNewContext(code, {
|
||||
module: mod,
|
||||
exports: mod.exports,
|
||||
require,
|
||||
Buffer,
|
||||
process,
|
||||
Math,
|
||||
Uint32Array,
|
||||
Uint8Array,
|
||||
Array,
|
||||
Object,
|
||||
String,
|
||||
Number,
|
||||
Date,
|
||||
performance,
|
||||
});
|
||||
return mod.exports;
|
||||
};
|
||||
const intactExports = runShielded(shielded.code);
|
||||
expect(intactExports.computeInvoiceDigest!(42, 7)).toBe(
|
||||
((42 * 31 + 7 * 17) >>> 0) ^ 0x5a5a1234,
|
||||
);
|
||||
expect(intactExports.computeInvoiceDigest!(0, 1)).toBe(
|
||||
((0 * 31 + 1 * 17) >>> 0) ^ 0x5a5a1234,
|
||||
);
|
||||
|
||||
// 3. Stripping an injected helper declaration breaks module execution immediately (ReferenceError)
|
||||
const fnDecls = [...shielded.code.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\s*\(/g)]
|
||||
.map((m) => m[1]!)
|
||||
.filter((name) => name !== "computeInvoiceDigest");
|
||||
expect(fnDecls.length).toBeGreaterThan(10);
|
||||
const victimFn = fnDecls[fnDecls.length - 1]!;
|
||||
const stripped = shielded.code.replace(
|
||||
`function ${victimFn}(`,
|
||||
`function _stripped_${victimFn}(`,
|
||||
);
|
||||
expect(() => runShielded(stripped)).toThrow(/is not defined/);
|
||||
});
|
||||
|
||||
it("Layer 2: Multi-site self-seal avoids even-site XOR cancellation and hard-fails on 1-byte tamper", () => {
|
||||
const dir = makeTempDir("bla-rt-layer2-");
|
||||
const sibPath = join(dir, "policy.json");
|
||||
const sibBytes = Buffer.from('{"tier":"enterprise","quota":500}\n', "utf8");
|
||||
writeFileSync(sibPath, sibBytes);
|
||||
const sibSha = createHash("sha256").update(sibBytes).digest("hex");
|
||||
|
||||
const prng = new SeededPrng("ci-redteam-layer2-seed");
|
||||
const snippet = generateSelfSealSnippet(prng, {
|
||||
siblingPaths: ["policy.json"],
|
||||
expectedSiblingSha256: { "policy.json": sibSha },
|
||||
hardFailOnSiblingMismatch: true,
|
||||
interleavedSites: 2,
|
||||
selfDigestCheck: true,
|
||||
envFingerprint: true,
|
||||
});
|
||||
expect(snippet.interleavedSites).toBe(2);
|
||||
|
||||
const rawEntry = [
|
||||
snippet.code,
|
||||
`const tierLabel = "ENTERPRISE_ACTIVE";`,
|
||||
`module.exports = { digest: ${snippet.bindingName}, tierLabel };`,
|
||||
"",
|
||||
].join("\n");
|
||||
const finalized = finalizeSelfSealSelfDigest(rawEntry);
|
||||
expect(finalized.applied).toBe(true);
|
||||
|
||||
const entryPath = join(dir, "entry.cjs");
|
||||
writeFileSync(entryPath, finalized.content, "utf8");
|
||||
|
||||
// Offline self-digest passes on untampered bytes
|
||||
expect(verifySelfSealSelfDigest(readFileSync(entryPath)).verified).toBe(true);
|
||||
|
||||
// Clean Node child process computes a non-zero XOR digest (sites do NOT self-cancel to 0!)
|
||||
const outJson = execFileSync(
|
||||
process.execPath,
|
||||
["-e", `const m = require(${JSON.stringify(entryPath)}); process.stdout.write(JSON.stringify(m));`],
|
||||
{ env: { ...process.env, NODE_OPTIONS: "" }, encoding: "utf8" },
|
||||
);
|
||||
const parsed = JSON.parse(outJson) as { digest: number; tierLabel: string };
|
||||
expect(parsed.tierLabel).toBe("ENTERPRISE_ACTIVE");
|
||||
expect(parsed.digest).toBeGreaterThan(0);
|
||||
expect(parsed.digest & 1).toBe(0); // untampered parity bit is 0
|
||||
|
||||
// Flip 1 character in the business literal ("ENTERPRISE_ACTIVE" -> "ENTERPRISE_ACTIVF")
|
||||
const tamperedContent = finalized.content.replace(
|
||||
"ENTERPRISE_ACTIVE",
|
||||
"ENTERPRISE_ACTIVF",
|
||||
);
|
||||
writeFileSync(entryPath, tamperedContent, "utf8");
|
||||
|
||||
expect(verifySelfSealSelfDigest(readFileSync(entryPath)).verified).toBe(false);
|
||||
const verifyReport = verifyTarget(entryPath, undefined, { selfSealEnabled: true });
|
||||
expect(verifyReport.overallPassed).toBe(false);
|
||||
expect(
|
||||
verifyReport.checks.some(
|
||||
(c) => c.id === "self-seal-digest-integrity" && !c.passed,
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
// Runtime execution must hard-fail with integrity error
|
||||
expect(() =>
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
["-e", `require(${JSON.stringify(entryPath)});`],
|
||||
{ env: { ...process.env, NODE_OPTIONS: "" }, stdio: "pipe" },
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("Layer 3: Weave verifier defeats >15 dummy-function padding, algebraic zero-entropy (& 0 / ^ self), and indirect boolean gates", () => {
|
||||
const dir = makeTempDir("bla-rt-layer3-");
|
||||
|
||||
// Attack A: 18 dummy functions mutating shared state, trying to push `checkLicense` past index 15
|
||||
const dummyFns = Array.from(
|
||||
{ length: 18 },
|
||||
(_, i) =>
|
||||
`function reconcileLedgerWindow${i}(v) { ledgerState = (ledgerState + v + ${i + 3}) >>> 0; return (ledgerState ^ ${(i + 1) * 17}) >>> 0; }`,
|
||||
).join("\n");
|
||||
const dummyCalls = Array.from(
|
||||
{ length: 18 },
|
||||
(_, i) => `reconcileLedgerWindow${i}(x + ${i});`,
|
||||
).join(" ");
|
||||
const paddedFile = join(dir, "padded-gate.js");
|
||||
writeFileSync(
|
||||
paddedFile,
|
||||
[
|
||||
`let ledgerState = 0x13572468;`,
|
||||
dummyFns,
|
||||
`export function runBatch(x) { ${dummyCalls} return ledgerState; }`,
|
||||
`export function checkLicense(token) { const ok = token === "PRO-2026-KEY"; return ok; }`,
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
const reportA = verifyWeaveTarget(paddedFile);
|
||||
expect(reportA.overallPassed).toBe(false);
|
||||
const gateCheckA = reportA.files[0]?.checks.find(
|
||||
(c) => c.id === "crown-jewel-entanglement",
|
||||
);
|
||||
expect(gateCheckA?.passed).toBe(false);
|
||||
|
||||
// Attack B: Algebraic zero-entropy fake weave (`& 0` and `x ^ x`)
|
||||
const zeroEntropyFile = join(dir, "zero-entropy.js");
|
||||
writeFileSync(
|
||||
zeroEntropyFile,
|
||||
[
|
||||
`let sessionAcc = 0x42;`,
|
||||
`function foldWindowA(n) { sessionAcc = (sessionAcc + n) | 0; return sessionAcc & 0; }`,
|
||||
`function foldWindowB(n) { sessionAcc = (sessionAcc ^ n) | 0; return sessionAcc ^ sessionAcc; }`,
|
||||
`function foldWindowC(n) { sessionAcc = (sessionAcc + n * 3) | 0; return sessionAcc * 0; }`,
|
||||
`export function computeQuote(n) { return n + foldWindowA(n) + foldWindowB(n) + foldWindowC(n); }`,
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
const reportB = verifyWeaveTarget(zeroEntropyFile);
|
||||
expect(reportB.overallPassed).toBe(false);
|
||||
});
|
||||
|
||||
it("Layer 4: hardenProject derives coherent sub-seeds with zero raw private seed leakage across artifacts", async () => {
|
||||
const srcDir = makeTempDir("bla-rt-layer4-src-");
|
||||
const outDir = makeTempDir("bla-rt-layer4-out-");
|
||||
const rawMasterSeed = "TOP_SECRET_MASTER_SEED_DO_NOT_LEAK_99942";
|
||||
|
||||
writeFileSync(
|
||||
join(srcDir, "index.cjs"),
|
||||
`const helper = require("./worker.cjs");\nfunction compute(x) { return helper.step(x) + 5; }\nmodule.exports = { compute };\n`,
|
||||
"utf8",
|
||||
);
|
||||
writeFileSync(
|
||||
join(srcDir, "worker.cjs"),
|
||||
`function step(v) { return (v * 3 + 11) >>> 0; }\nmodule.exports = { step };\n`,
|
||||
"utf8",
|
||||
);
|
||||
writeFileSync(join(srcDir, "kernel.wasm"), minimalValidWasm());
|
||||
|
||||
const result = await hardenProject({
|
||||
directory: srcDir,
|
||||
outputDirectory: outDir,
|
||||
intensity: "balanced",
|
||||
seed: rawMasterSeed,
|
||||
sidecarEntangle: true,
|
||||
selfSeal: true,
|
||||
});
|
||||
expect(result.overallSuccess).toBe(true);
|
||||
|
||||
// Scan every emitted file AND the JSON report for any trace of rawMasterSeed
|
||||
expect(JSON.stringify(result)).not.toContain(rawMasterSeed);
|
||||
const emittedFiles = collectFilesRecursive(outDir);
|
||||
expect(emittedFiles.length).toBeGreaterThanOrEqual(3);
|
||||
|
||||
const publicTags = new Set<string>();
|
||||
for (const f of emittedFiles) {
|
||||
const buf = readFileSync(f);
|
||||
expect(buf.toString("utf8")).not.toContain(rawMasterSeed);
|
||||
expect(buf.toString("latin1")).not.toContain(rawMasterSeed);
|
||||
const m = buf.toString("latin1").match(/scn1-[0-9a-f]{32}/g);
|
||||
if (m) {
|
||||
for (const tag of m) publicTags.add(tag);
|
||||
}
|
||||
}
|
||||
// Coherent public sidecar tag across entangled siblings
|
||||
expect(publicTags.size).toBe(1);
|
||||
});
|
||||
|
||||
it("Layer 5: JVM §4.7.1 exact-EOF attribute, oversized seal fail-closed, WebCrypto AES lint, EIP-170 cap, and JSX/directive encryptStrings", () => {
|
||||
// 5a. JVM §4.7.1 attribute_info with zero trailing bytes
|
||||
const jvmIn = minimalCompleteJvmClass();
|
||||
const jvmProtected = protectJvmClassBuffer(jvmIn, {
|
||||
intensity: "bankrupt",
|
||||
seed: "ci-jvm-seed",
|
||||
});
|
||||
expect(jvmProtected.mode).toBe("structural");
|
||||
expect(jvmProtected.customAttributesAdded).toBe(1);
|
||||
|
||||
// Parse constant pool of protected .class and verify attributes_count === 1 & exact EOF
|
||||
const outBuf = jvmProtected.buffer;
|
||||
expect(outBuf.readUInt32BE(0)).toBe(0xcafebabe);
|
||||
const newCpCount = outBuf.readUInt16BE(8);
|
||||
expect(newCpCount).toBe(3 + jvmProtected.constantPoolEntriesAdded);
|
||||
let p = 10;
|
||||
for (let slot = 1; slot < newCpCount; slot++) {
|
||||
const tag = outBuf[p]!;
|
||||
if (tag === 1) {
|
||||
const len = outBuf.readUInt16BE(p + 1);
|
||||
p += 3 + len;
|
||||
} else if (tag === 7) {
|
||||
p += 3;
|
||||
} else {
|
||||
throw new Error(`Unexpected CP tag ${tag}`);
|
||||
}
|
||||
}
|
||||
// access_flags(2) + this_class(2) + super_class(2) + interfaces(2) + fields(2) + methods(2) = 12 bytes
|
||||
const attrsCount = outBuf.readUInt16BE(p + 12);
|
||||
expect(attrsCount).toBe(1);
|
||||
const attrNameIndex = outBuf.readUInt16BE(p + 14);
|
||||
expect(attrNameIndex).toBe(3); // first injected CONSTANT_Utf8 ("BlaEnclaveDelegation")
|
||||
const attrLen = outBuf.readUInt32BE(p + 16);
|
||||
expect(p + 20 + attrLen).toBe(outBuf.length); // exact EOF, zero trailing garbage!
|
||||
|
||||
// 5b. Seal commitment lint: >400 KB padded reversible JSON still caught + >4 MiB seal.json fails closed
|
||||
const paddedSealJson = JSON.stringify({
|
||||
schema: "demo-entitlement-seal/v1",
|
||||
padding: "x".repeat(520_000),
|
||||
scheduleSalt: 123456,
|
||||
rounds: 8,
|
||||
revision: "deadbeefcafebabe",
|
||||
});
|
||||
const paddedReport = lintSealCommitmentSource(paddedSealJson, {
|
||||
path: "seal.json",
|
||||
});
|
||||
expect(paddedReport.shouldRefuseBankrupt).toBe(true);
|
||||
expect(
|
||||
paddedReport.findings.some((f) => f.id === "reversible-public-commitment"),
|
||||
).toBe(true);
|
||||
|
||||
const dir = makeTempDir("bla-rt-layer5-");
|
||||
const hugeSealPath = join(dir, "seal.json");
|
||||
writeFileSync(hugeSealPath, `{"pad":"${"a".repeat(4 * 1024 * 1024 + 512)}"}`);
|
||||
const hugeReport = lintSealCommitmentFile(hugeSealPath);
|
||||
expect(hugeReport.shouldRefuseBankrupt).toBe(true);
|
||||
expect(hugeReport.findings.some((f) => f.id === "seal-oversized-sidecar")).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
// 5c. WebCrypto subtle.decrypt + importKey("raw") + fixed hdr caught by js-aes-unwrap-lint
|
||||
const webCryptoFootgun = `
|
||||
const SEALED_HDR = new Uint8Array([0xd1, 0x7e, 0xa0, 0x04]);
|
||||
async function unwrapBlob(buf, rawHex) {
|
||||
const key = await crypto.subtle.importKey("raw", rawHex, { name: "AES-GCM" }, false, ["decrypt"]);
|
||||
return crypto.subtle.decrypt({ name: "AES-GCM", iv: buf.slice(4, 16) }, key, buf.slice(16));
|
||||
}
|
||||
`;
|
||||
const aesReport = lintJsAesUnwrapSource(webCryptoFootgun, {
|
||||
path: "browser-unwrap.ts",
|
||||
});
|
||||
expect(aesReport.shouldRefuseBankrupt).toBe(true);
|
||||
|
||||
// 5d. EVM EIP-170 cap option keeps bytecode <= 24,576 bytes
|
||||
const evmCapped = protectEvmBytecodeBuffer(Buffer.from([0x60, 0x00, 0x56]), {
|
||||
intensity: "bankrupt",
|
||||
seed: "eip170-seed",
|
||||
enforceEip170Cap: true,
|
||||
});
|
||||
expect(evmCapped.buffer.length).toBeLessThanOrEqual(24_576);
|
||||
expect(evmCapped.exceedsEip170Limit).toBe(false);
|
||||
|
||||
// 5e. encryptStrings preserves "use client" at line 1 and wraps JSXAttribute values in {...}
|
||||
const tsxDir = join(dir, "tsx-app");
|
||||
mkdirSync(tsxDir, { recursive: true });
|
||||
const tsxPath = join(tsxDir, "panel.tsx");
|
||||
writeFileSync(
|
||||
tsxPath,
|
||||
[
|
||||
`"use client";`,
|
||||
`declare const AMBIENT_SECRET = "FLAG{ambient_declare_must_not_become_call}";`,
|
||||
`export function LicenseBadge() {`,
|
||||
` return <div data-secret="FLAG{jsx_attribute_secret_token_987654}">Active</div>;`,
|
||||
`}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const dryReport = encryptStrings({
|
||||
path: tsxPath,
|
||||
seed: "tsx-seed",
|
||||
dryRun: true,
|
||||
});
|
||||
expect(dryReport.status).toBe("ok");
|
||||
expect(dryReport.totalEncrypted).toBe(1);
|
||||
|
||||
const liveReport = encryptStrings({
|
||||
path: tsxPath,
|
||||
seed: "tsx-seed",
|
||||
});
|
||||
expect(liveReport.status).toBe("ok");
|
||||
const rewrittenTsx = readFileSync(tsxPath, "utf8");
|
||||
expect(rewrittenTsx.startsWith(`"use client";`)).toBe(true);
|
||||
expect(rewrittenTsx).toContain(
|
||||
`declare const AMBIENT_SECRET = "FLAG{ambient_declare_must_not_become_call}";`,
|
||||
);
|
||||
expect(rewrittenTsx).not.toContain("FLAG{jsx_attribute_secret_token_987654}");
|
||||
expect(rewrittenTsx).toMatch(/data-secret=\{[A-Za-z_$][\w$]*\(0\)\}/);
|
||||
|
||||
// Must remain 100% valid TSX AST!
|
||||
expect(() =>
|
||||
parse(rewrittenTsx, {
|
||||
sourceType: "module",
|
||||
plugins: ["typescript", "jsx"],
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user