Skip to content

armgit / bla

Public Imported from GitHub
0

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

fix(mcp): cap stdio line size to bound server memory (#42)

Dery Ferdika8c8f1407241f
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 480b4fc..9439725 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -816,17 +816,62 @@ export async function handleMcpRequest(
/**
* Starts the BLA MCP server over stdio (supporting newline-delimited JSON-RPC 2.0).
*/
-export function startMcpStdioServer(): void {
+/** Largest single stdio line accepted before the client is treated as misbehaving. */
+export const MAX_STDIO_LINE_BYTES = 1_048_576;
+
+export interface StdioLineProcessorHooks {
+ readonly onLine: (line: string) => void;
+ readonly onOversizedLine?: () => void;
+}
+
+export interface StdioLineProcessor {
+ readonly push: (chunk: string) => void;
+}
+
+/**
+ * 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.
+ */
+export function createStdioLineProcessor(hooks: StdioLineProcessorHooks): StdioLineProcessor {
let buffer = "";
+ let discarding = 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;
+ buffer = chunk.slice(nl + 1);
+ } else {
+ buffer += chunk;
+ }
+ let newlineIdx: number;
+ while ((newlineIdx = buffer.indexOf("\n")) >= 0) {
+ const line = buffer.slice(0, newlineIdx).trim();
+ buffer = buffer.slice(newlineIdx + 1);
+ if (!line || line.startsWith("Content-Length:")) continue;
+ if (line.length > MAX_STDIO_LINE_BYTES) {
+ hooks.onOversizedLine?.();
+ continue;
+ }
+ hooks.onLine(line);
+ }
+ if (buffer.length > MAX_STDIO_LINE_BYTES) {
+ buffer = "";
+ discarding = true;
+ hooks.onOversizedLine?.();
+ }
+ },
+ };
+}
+
+export function startMcpStdioServer(): void {
let processingQueue = Promise.resolve();
- process.stdin.setEncoding("utf8");
- process.stdin.on("data", (chunk: string) => {
- buffer += chunk;
- let newlineIdx: number;
- while ((newlineIdx = buffer.indexOf("\n")) >= 0) {
- const line = buffer.slice(0, newlineIdx).trim();
- buffer = buffer.slice(newlineIdx + 1);
- if (!line || line.startsWith("Content-Length:")) continue;
+ const processor = createStdioLineProcessor({
+ onLine: (line: string) => {
processingQueue = processingQueue.then(async () => {
try {
const req = JSON.parse(line) as JsonRpcRequest;
@@ -846,6 +891,19 @@ export function startMcpStdioServer(): void {
process.stdout.write(JSON.stringify(parseErr) + "\n");
}
});
- }
+ },
+ onOversizedLine: () => {
+ const parseErr: JsonRpcResponse = {
+ jsonrpc: "2.0",
+ id: null,
+ error: {
+ code: -32700,
+ message: `Parse error: line exceeds ${MAX_STDIO_LINE_BYTES} byte limit`,
+ },
+ };
+ process.stdout.write(JSON.stringify(parseErr) + "\n");
+ },
});
+ process.stdin.setEncoding("utf8");
+ process.stdin.on("data", (chunk: string) => processor.push(chunk));
}
diff --git a/tests/mcp-stdio-limit.test.ts b/tests/mcp-stdio-limit.test.ts
new file mode 100644
index 0000000..49e147a
--- /dev/null
+++ b/tests/mcp-stdio-limit.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+import { createStdioLineProcessor, MAX_STDIO_LINE_BYTES } from "../src/mcp/server.js";
+
+function collect() {
+ const lines: string[] = [];
+ let oversized = 0;
+ const processor = createStdioLineProcessor({
+ onLine: (line) => lines.push(line),
+ onOversizedLine: () => {
+ oversized++;
+ },
+ });
+ return { lines, processor, oversizedCount: () => oversized };
+}
+
+describe("MCP stdio line processor", () => {
+ it("delimits newline-framed JSON-RPC lines across chunk boundaries and skips framing lines", () => {
+ const { lines, processor } = collect();
+ processor.push('{"jsonrpc":"2.0","id":1,"method":"in');
+ processor.push('itialize"}\nContent-Length: 64\r\n\r\n');
+ processor.push('{"jsonrpc":"2.0","id":2,"method":"ping"}\n');
+ expect(lines).toEqual([
+ '{"jsonrpc":"2.0","id":1,"method":"initialize"}',
+ '{"jsonrpc":"2.0","id":2,"method":"ping"}',
+ ]);
+ });
+
+ it("rejects an unterminated partial line past the cap and recovers at the next newline", () => {
+ const { lines, processor, oversizedCount } = collect();
+ processor.push("x".repeat(MAX_STDIO_LINE_BYTES + 1));
+ expect(oversizedCount()).toBe(1);
+ expect(lines).toEqual([]);
+ // The rest of the oversized line drains silently, then a valid message flows through.
+ processor.push("y".repeat(64) + '\n{"jsonrpc":"2.0","id":3,"method":"ping"}\n');
+ expect(oversizedCount()).toBe(1);
+ expect(lines).toEqual(['{"jsonrpc":"2.0","id":3,"method":"ping"}']);
+ });
+
+ it("rejects a complete single line past the cap instead of parsing it", () => {
+ const { lines, processor, oversizedCount } = collect();
+ processor.push("z".repeat(MAX_STDIO_LINE_BYTES + 1) + "\n");
+ expect(oversizedCount()).toBe(1);
+ expect(lines).toEqual([]);
+ // Buffer must be empty again: the next small message is not poisoned.
+ processor.push('{"id":4}\n');
+ expect(lines).toEqual(['{"id":4}']);
+ });
+
+ it("keeps a partial line buffered until its newline arrives", () => {
+ const { lines, processor, oversizedCount } = collect();
+ processor.push('{"jsonrpc":"2.0","id":5,');
+ expect(lines).toEqual([]);
+ expect(oversizedCount()).toBe(0);
+ processor.push('"method":"ping"}\n');
+ expect(lines).toEqual(['{"jsonrpc":"2.0","id":5,"method":"ping"}']);
+ });
+});