mirror of
https://github.com/qybaihe/bla.git
synced 2026-11-20 08:20:59 +08:00
Merge pull request #224 from DeryFerd/fix/mcp-inplace-write-confirmation
fix(mcp): require confirm_overwrite before in-place encrypt-strings and bind-scope runs
This commit is contained in:
+4
-4
@@ -76,8 +76,8 @@ Argument bounds are enforced before any tool runs: count arguments (`max_artifac
|
||||
- `bla_polymorph_report`: Compare two hardened directories (`dir_a`, `dir_b`, optional thresholds) and report structural drift (export-name Jaccard, export-order Kendall-tau, byte-diff ratio, identifier overlap, aggregate `driftScore`). Drift is a stability signal, not a cracking-resistance proof.
|
||||
- `bla_benchmark`: Runs the 14-target showcase benchmark suite.
|
||||
- `bla_emit_headers`: Generates C/C++, Rust, or Go defense headers (`language`, `intensity`).
|
||||
- `bla_bind_scope`: Optional honest code-lock — write public `bind-scope.json` (domains / validFrom / validUntil) and inject `BLA_BIND_SCOPE_CHECK` into the license entry. Default OFF; never a covert backdoor.
|
||||
- `bla_encrypt_strings`: Encrypt sensitive literals in `panel.html` / `license.cjs` with a seed-derived XOR keystream plus a runtime decrypt stub (`path`, `seed`, optional `out_dir`, `include_urls`, `dry_run`). Raises static-grep cost only — not white-box AES.
|
||||
- `bla_bind_scope`: Optional honest code-lock — write public `bind-scope.json` (domains / validFrom / validUntil) and inject `BLA_BIND_SCOPE_CHECK` into the license entry. Default OFF; never a covert backdoor. In-place runs require `confirm_overwrite` (see write-safety below).
|
||||
- `bla_encrypt_strings`: Encrypt sensitive literals in `panel.html` / `license.cjs` with a seed-derived XOR keystream plus a runtime decrypt stub (`path`, `seed`, optional `out_dir`, `include_urls`, `dry_run`, `confirm_overwrite`). Raises static-grep cost only — not white-box AES.
|
||||
- `bla_lint_bind_scope`: Read-only lint for `bla-bind-scope/v1` (refuses non-public / hidden fields / missing runtime check).
|
||||
- `bla_doctor`: Diagnostics for BLA engines and agent client registrations; also reports `skillMissingFiles` / `skillModifiedFiles` (format appendices under `references/` included).
|
||||
- `bla_weave_plan`: Read-only weave-decoy planner (`path`, optional `max_targets`) → `bla-weave-plan/v1` JSON (defensive theory checklist + AST `surgicalWorkorder` with `entryFunctions`, `sharedStateSlots`, `branchCandidates`, and `agentRewriteRecipe`; no crack/RE).
|
||||
@@ -87,8 +87,8 @@ Argument bounds are enforced before any tool runs: count arguments (`max_artifac
|
||||
|
||||
- `bla_harden` with `dry_run: true` (CLI `bla harden . --dry-run`) discovers targets and plans outputs with **zero bytes written** (no `.bla-hardened/`, no summary, no `.blarc` seed). Dry-run sets `overallSuccess: false` — it never claims a successful harden.
|
||||
- Discovery is capped (`max_artifacts`, default 64); when more targets exist the result sets `truncated: true` and `nextOffset` instead of silently dropping them — page with `offset` until `truncated` is false.
|
||||
- `bla_harden` / `bla_defend` / `bla_protect` refuse to overwrite an existing output file unless `confirm_overwrite: true`. A refusal is `isError: true` with `{ status: "confirmation_required", wouldOverwrite: [...], wrote: [] }`; nothing is written.
|
||||
- Successful `bla_harden` / `bla_defend` / `bla_protect` writes add `writeReceipt: { status: "written", wrote, overwrote, confirmed }` (`bla_harden` dry-run omits it).
|
||||
- `bla_harden` / `bla_defend` / `bla_protect` / `bla_encrypt_strings` / `bla_bind_scope` refuse to overwrite an existing output file unless `confirm_overwrite: true`. A refusal is `isError: true` with `{ status: "confirmation_required", wouldOverwrite: [...], wrote: [] }`; nothing is written.
|
||||
- Successful `bla_harden` / `bla_defend` / `bla_protect` / `bla_encrypt_strings` / `bla_bind_scope` writes add `writeReceipt: { status: "written", wrote, overwrote, confirmed }` (`bla_harden` dry-run and runs that write nothing omit it).
|
||||
- `in_place: true` (MCP) / `--in-place` (CLI) plans the output as the input path; because that path already exists, `confirm_overwrite: true` is required on MCP or the call is refused with `confirmation_required`.
|
||||
|
||||
`weave_decoys: true` activates structural Python customer-def weave (shared-slot touch + opaque-false decoy calls) after the #51 tarpit; when false, Python stays warm-init-only. JS AST weave remains always-on.
|
||||
|
||||
+70
-14
@@ -1182,7 +1182,7 @@ const RAW_BLA_MCP_TOOLS: readonly McpToolDefinition[] = [
|
||||
{
|
||||
name: "bla_encrypt_strings",
|
||||
description:
|
||||
"Encrypt sensitive string literals in panel.html / license.cjs with a seed-derived XOR keystream and inject a runtime decrypt stub. Reuses SeededPrng.derive(\"string.encrypt\") — never JS AES wrap-key (that footgun is refused by bla_lint_js_aes_unwrap). Honesty: raises static grep cost only; prove equivalence with verify / CrackMe / REA. Writes outputs (or dry_run).",
|
||||
"Encrypt sensitive string literals in panel.html / license.cjs with a seed-derived XOR keystream and inject a runtime decrypt stub. Reuses SeededPrng.derive(\"string.encrypt\") — never JS AES wrap-key (that footgun is refused by bla_lint_js_aes_unwrap). Honesty: raises static grep cost only; prove equivalence with verify / CrackMe / REA. Writes outputs (or dry_run); an in-place run refuses until confirm_overwrite: true.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -1206,6 +1206,11 @@ const RAW_BLA_MCP_TOOLS: readonly McpToolDefinition[] = [
|
||||
type: "boolean",
|
||||
description: "Report only; write nothing",
|
||||
},
|
||||
confirm_overwrite: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Required when the run would rewrite an existing file in place. Re-run with true to confirm.",
|
||||
},
|
||||
},
|
||||
required: ["path", "seed"],
|
||||
additionalProperties: false,
|
||||
@@ -1234,7 +1239,7 @@ const RAW_BLA_MCP_TOOLS: readonly McpToolDefinition[] = [
|
||||
{
|
||||
name: "bla_bind_scope",
|
||||
description:
|
||||
"Optional honest code-lock: write a PUBLIC bind-scope.json (domains + validity window) and inject a deterministic runtime check into license.cjs/entry. Default OFF. Never a covert backdoor — public:true is mandatory; hidden fields refuse. Host for Node comes from BLA_BIND_HOST (or location.hostname in browsers).",
|
||||
"Optional honest code-lock: write a PUBLIC bind-scope.json (domains + validity window) and inject a deterministic runtime check into license.cjs/entry. Default OFF. Never a covert backdoor — public:true is mandatory; hidden fields refuse. Host for Node comes from BLA_BIND_HOST (or location.hostname in browsers). In-place runs refuse until confirm_overwrite: true.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -1268,6 +1273,11 @@ const RAW_BLA_MCP_TOOLS: readonly McpToolDefinition[] = [
|
||||
type: "boolean",
|
||||
description: "Report only; write nothing",
|
||||
},
|
||||
confirm_overwrite: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Required when the run would rewrite an existing entry or contract. Re-run with true to confirm.",
|
||||
},
|
||||
},
|
||||
required: ["directory"],
|
||||
additionalProperties: false,
|
||||
@@ -1443,6 +1453,22 @@ function writeReceipt(
|
||||
return { status: "written", wrote: outputs, overwrote: overwritten, confirmed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Planned write targets for `bla_bind_scope`, resolved with a zero-write
|
||||
* dry run so the overwrite gate can name the exact files before anything is
|
||||
* mutated. An invalid contract returns `[]` here so the real run surfaces the
|
||||
* contract error instead of a misleading confirmation request.
|
||||
*/
|
||||
function plannedBindScopeWrites(
|
||||
options: Parameters<typeof applyBindScope>[0],
|
||||
): string[] {
|
||||
const preview = applyBindScope({ ...options, dryRun: true });
|
||||
if (preview.status === "error") return [];
|
||||
return [preview.contractPath, preview.entryPath].filter(
|
||||
(p): p is string => typeof p === "string" && p.length > 0,
|
||||
);
|
||||
}
|
||||
|
||||
function attachArtifactRunEvidence(
|
||||
tool: string,
|
||||
inputPath: string,
|
||||
@@ -2582,7 +2608,7 @@ export async function handleMcpRequest(
|
||||
refused = status === "fail" || status === "error";
|
||||
}
|
||||
} else if (name === "bla_encrypt_strings") {
|
||||
payload = encryptStrings({
|
||||
const encryptArgs = {
|
||||
path: args.path as string,
|
||||
seed: args.seed as string,
|
||||
...(typeof args.out_dir === "string" && args.out_dir.trim().length > 0
|
||||
@@ -2591,11 +2617,28 @@ export async function handleMcpRequest(
|
||||
...(typeof args.include_urls === "boolean"
|
||||
? { includeUrls: args.include_urls as boolean }
|
||||
: {}),
|
||||
dryRun: args.dry_run === true,
|
||||
});
|
||||
{
|
||||
const status = (payload as { status: string }).status;
|
||||
refused = status === "error";
|
||||
};
|
||||
const dryRun = args.dry_run === true;
|
||||
const clobbered = dryRun
|
||||
? []
|
||||
: existingPaths(
|
||||
encryptStrings({ ...encryptArgs, dryRun: true })
|
||||
.files.filter((f) => f.encryptedCount > 0)
|
||||
.map((f) => f.outPath),
|
||||
);
|
||||
if (clobbered.length > 0 && !confirmed) {
|
||||
refused = true;
|
||||
payload = confirmationRequiredPayload(name, clobbered);
|
||||
} else {
|
||||
const report = encryptStrings({ ...encryptArgs, dryRun });
|
||||
const written = report.files
|
||||
.filter((f) => f.written)
|
||||
.map((f) => f.outPath);
|
||||
payload =
|
||||
written.length > 0
|
||||
? { ...report, writeReceipt: writeReceipt(written, clobbered, confirmed) }
|
||||
: report;
|
||||
refused = report.status === "error";
|
||||
}
|
||||
} else if (name === "bla_lint_plaintext_secrets") {
|
||||
const allow = args.allow_plaintext_string === true;
|
||||
@@ -2620,7 +2663,7 @@ export async function handleMcpRequest(
|
||||
const domains = Array.isArray(args.domains)
|
||||
? args.domains.filter((d) => typeof d === "string")
|
||||
: undefined;
|
||||
payload = applyBindScope({
|
||||
const bindArgs = {
|
||||
directory: args.directory as string,
|
||||
...(domains && domains.length > 0 ? { domains } : {}),
|
||||
...(typeof args.valid_from === "string" && args.valid_from.trim()
|
||||
@@ -2635,11 +2678,24 @@ export async function handleMcpRequest(
|
||||
...(typeof args.out_dir === "string" && args.out_dir.trim()
|
||||
? { outDir: args.out_dir as string }
|
||||
: {}),
|
||||
dryRun: args.dry_run === true,
|
||||
});
|
||||
{
|
||||
const status = (payload as { status: string }).status;
|
||||
refused = status === "error";
|
||||
};
|
||||
const dryRun = args.dry_run === true;
|
||||
const clobbered = dryRun
|
||||
? []
|
||||
: existingPaths(plannedBindScopeWrites(bindArgs));
|
||||
if (clobbered.length > 0 && !confirmed) {
|
||||
refused = true;
|
||||
payload = confirmationRequiredPayload(name, clobbered);
|
||||
} else {
|
||||
const report = applyBindScope({ ...bindArgs, dryRun });
|
||||
const written = report.written
|
||||
? [report.contractPath, ...(report.entryPath ? [report.entryPath] : [])]
|
||||
: [];
|
||||
payload =
|
||||
written.length > 0
|
||||
? { ...report, writeReceipt: writeReceipt(written, clobbered, confirmed) }
|
||||
: report;
|
||||
refused = report.status === "error";
|
||||
}
|
||||
} else if (name === "bla_lint_bind_scope") {
|
||||
const allow = args.allow_missing_bind_runtime === true;
|
||||
|
||||
@@ -847,6 +847,7 @@ async def verify_access_policy(
|
||||
arguments: {
|
||||
path: dir,
|
||||
seed: "dogfood-seed-2026",
|
||||
confirm_overwrite: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -155,6 +155,7 @@ describe("bind-scope (Direction-4 honest code lock)", () => {
|
||||
directory: dir,
|
||||
domains: ["mcp.example"],
|
||||
valid_until: "2099-12-31T00:00:00.000Z",
|
||||
confirm_overwrite: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -179,7 +179,7 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
|
||||
},
|
||||
{
|
||||
tool: "bla_encrypt_strings",
|
||||
params: ["path", "seed", "out_dir", "include_urls", "dry_run"],
|
||||
params: ["path", "seed", "out_dir", "include_urls", "dry_run", "confirm_overwrite"],
|
||||
},
|
||||
{
|
||||
tool: "bla_lint_plaintext_secrets",
|
||||
@@ -187,7 +187,7 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
|
||||
},
|
||||
{
|
||||
tool: "bla_bind_scope",
|
||||
params: ["directory", "domains", "valid_from", "valid_until", "entry_path", "out_dir", "dry_run"],
|
||||
params: ["directory", "domains", "valid_from", "valid_until", "entry_path", "out_dir", "dry_run", "confirm_overwrite"],
|
||||
},
|
||||
{
|
||||
tool: "bla_lint_bind_scope",
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { handleMcpRequest } from "../src/mcp/server.js";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
afterEach(() => {
|
||||
for (const d of tempDirs.splice(0)) rmSync(d, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const SECRET_ENTRY = `module.exports.unlock = function unlock(key) {
|
||||
const flag = "FLAG{mcp_gate_demo_fixture}";
|
||||
const token = "7f3a9c2e1b8d4f6a0e5c9b7d3a1f8e6c";
|
||||
return key === "ok" ? flag : token;
|
||||
};
|
||||
`;
|
||||
|
||||
const PLAIN_ENTRY = `"use strict";
|
||||
module.exports.unlock = function unlock(key) {
|
||||
return key === "ok" ? "FLAG{in_scope}" : null;
|
||||
};
|
||||
`;
|
||||
|
||||
async function call(name: string, args: Record<string, unknown>) {
|
||||
const res = await handleMcpRequest({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "tools/call",
|
||||
params: { name, arguments: args },
|
||||
});
|
||||
expect(res?.error).toBeUndefined();
|
||||
return res!.result as {
|
||||
isError: boolean;
|
||||
structuredContent: {
|
||||
readonly [key: string]: unknown;
|
||||
status?: string;
|
||||
wouldOverwrite?: readonly string[];
|
||||
writeReceipt?: Record<string, unknown>;
|
||||
totalEncrypted?: number;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
describe("MCP in-place writes require confirm_overwrite", () => {
|
||||
it("bla_encrypt_strings refuses an unconfirmed in-place rewrite", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-enc-"));
|
||||
tempDirs.push(dir);
|
||||
const file = join(dir, "license.cjs");
|
||||
writeFileSync(file, SECRET_ENTRY, "utf8");
|
||||
|
||||
const refused = await call("bla_encrypt_strings", {
|
||||
path: dir,
|
||||
seed: "mcp-gate-1",
|
||||
});
|
||||
|
||||
expect(refused.isError).toBe(true);
|
||||
expect(refused.structuredContent.status).toBe("confirmation_required");
|
||||
expect(refused.structuredContent.wouldOverwrite).toEqual([file]);
|
||||
expect(readFileSync(file, "utf8")).toBe(SECRET_ENTRY);
|
||||
});
|
||||
|
||||
it("bla_encrypt_strings rewrites in place once confirmed", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-enc-ok-"));
|
||||
tempDirs.push(dir);
|
||||
const file = join(dir, "license.cjs");
|
||||
writeFileSync(file, SECRET_ENTRY, "utf8");
|
||||
|
||||
const ok = await call("bla_encrypt_strings", {
|
||||
path: dir,
|
||||
seed: "mcp-gate-1",
|
||||
confirm_overwrite: true,
|
||||
});
|
||||
|
||||
expect(ok.isError).toBe(false);
|
||||
expect(ok.structuredContent.status).toBe("ok");
|
||||
const after = readFileSync(file, "utf8");
|
||||
expect(after).not.toContain("FLAG{mcp_gate_demo_fixture}");
|
||||
expect(after).not.toContain("7f3a9c2e1b8d4f6a0e5c9b7d3a1f8e6c");
|
||||
expect(ok.structuredContent.writeReceipt).toEqual({
|
||||
status: "written",
|
||||
wrote: [file],
|
||||
overwrote: [file],
|
||||
confirmed: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("bla_encrypt_strings dry_run never needs confirmation and writes nothing", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-enc-dry-"));
|
||||
tempDirs.push(dir);
|
||||
const file = join(dir, "license.cjs");
|
||||
writeFileSync(file, SECRET_ENTRY, "utf8");
|
||||
|
||||
const dry = await call("bla_encrypt_strings", {
|
||||
path: dir,
|
||||
seed: "mcp-gate-1",
|
||||
dry_run: true,
|
||||
});
|
||||
|
||||
expect(dry.isError).toBe(false);
|
||||
expect(dry.structuredContent.status).toBe("ok");
|
||||
expect(dry.structuredContent.writeReceipt).toBeUndefined();
|
||||
expect(readFileSync(file, "utf8")).toBe(SECRET_ENTRY);
|
||||
});
|
||||
|
||||
it("bla_encrypt_strings keeps out_dir runs confirmation-free when nothing is clobbered", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-enc-out-"));
|
||||
tempDirs.push(dir);
|
||||
writeFileSync(join(dir, "license.cjs"), SECRET_ENTRY, "utf8");
|
||||
|
||||
const ok = await call("bla_encrypt_strings", {
|
||||
path: dir,
|
||||
seed: "mcp-gate-1",
|
||||
out_dir: join(dir, "out"),
|
||||
});
|
||||
|
||||
expect(ok.isError).toBe(false);
|
||||
expect(ok.structuredContent.status).toBe("ok");
|
||||
expect(ok.structuredContent.writeReceipt).toEqual({
|
||||
status: "written",
|
||||
wrote: [join(dir, "out", "license.cjs")],
|
||||
overwrote: [],
|
||||
confirmed: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("bla_bind_scope refuses to rewrite an existing entry without confirmation", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-bind-"));
|
||||
tempDirs.push(dir);
|
||||
const entry = join(dir, "license.cjs");
|
||||
writeFileSync(entry, PLAIN_ENTRY, "utf8");
|
||||
|
||||
const refused = await call("bla_bind_scope", {
|
||||
directory: dir,
|
||||
domains: ["app.example.com"],
|
||||
valid_from: "2020-01-01T00:00:00.000Z",
|
||||
valid_until: "2099-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(refused.isError).toBe(true);
|
||||
expect(refused.structuredContent.status).toBe("confirmation_required");
|
||||
expect(refused.structuredContent.wouldOverwrite).toEqual([entry]);
|
||||
expect(readFileSync(entry, "utf8")).toBe(PLAIN_ENTRY);
|
||||
});
|
||||
|
||||
it("bla_bind_scope writes once confirmed", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "bla-mcp-bind-ok-"));
|
||||
tempDirs.push(dir);
|
||||
const entry = join(dir, "license.cjs");
|
||||
writeFileSync(entry, PLAIN_ENTRY, "utf8");
|
||||
|
||||
const ok = await call("bla_bind_scope", {
|
||||
directory: dir,
|
||||
domains: ["app.example.com"],
|
||||
valid_from: "2020-01-01T00:00:00.000Z",
|
||||
valid_until: "2099-01-01T00:00:00.000Z",
|
||||
confirm_overwrite: true,
|
||||
});
|
||||
|
||||
expect(ok.isError).toBe(false);
|
||||
expect(ok.structuredContent.status).toBe("ok");
|
||||
expect(readFileSync(entry, "utf8")).toContain("BLA_BIND_SCOPE_CHECK");
|
||||
expect(ok.structuredContent.writeReceipt).toEqual({
|
||||
status: "written",
|
||||
wrote: [join(dir, "bind-scope.json"), entry],
|
||||
overwrote: [entry],
|
||||
confirmed: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user