From 1f9ae538a9efbb2df23e67dd6c3a8ea8fd548db5 Mon Sep 17 00:00:00 2001 From: Mark Lavercombe Date: Tue, 3 Nov 2026 12:29:38 +1100 Subject: [PATCH] fix(security): strip terminal escapes from API responses (CWE-150) Scan results quote text from the scanned site; format.ts printed c.message (and ask results, error bodies, rootUrl) raw, so a hostile site could put OSC 52 (clipboard write), CSI 2J, CR or bidi overrides on the operator's terminal. --no-color did not help. Sanitise once at the client boundary: every JSON payload is deep-sanitised after parse (escapes arrive JSON-encoded as \u001b, so stripping the raw text alone is not enough), and the raw body used for error messages is stripped too. Keeps \n and \t. The server now strips these at source as well; this covers older stored scans and other API hosts. Reported via security.txt 2026-11-03. Co-Authored-By: Claude Opus 5.5 --- src/client.ts | 21 ++++++----- src/sanitize.ts | 51 +++++++++++++++++++++++++ test/sanitize.test.ts | 87 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 149 insertions(+), 10 deletions(-) create mode 100644 src/sanitize.ts create mode 100644 test/sanitize.test.ts diff --git a/src/client.ts b/src/client.ts index bd869eb..404cb25 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,3 +1,4 @@ +import { parseSanitized, stripTerminalEscapes } from "./sanitize.js"; // Minimal REST client for the agent-ready.dev API. The CLI is a thin // argv→HTTPS wrapper: command handlers call into this client, which sends // Bearer-authenticated requests to the hosted REST endpoints. Mirrors the @@ -94,11 +95,11 @@ async function call(config: Config, opts: FetchOptions): Promise { ); } - const text = await res.text(); + const text = stripTerminalEscapes(await res.text()); let payload: unknown = null; if (text.length > 0) { try { - payload = JSON.parse(text); + payload = parseSanitized(text); } catch { // Non-JSON body — fall through with raw text in the error message // (rare; agent-ready always responds with JSON, but networks lie). @@ -331,11 +332,11 @@ export async function postAnonScan( ); } - const text = await res.text(); + const text = stripTerminalEscapes(await res.text()); let payload: unknown = null; if (text.length > 0) { try { - payload = JSON.parse(text); + payload = parseSanitized(text); } catch { /* non-JSON body — surfaced via the error path below */ } @@ -403,11 +404,11 @@ export async function scanMcp( ); } - const text = await res.text(); + const text = stripTerminalEscapes(await res.text()); let payload: unknown = null; if (text.length > 0) { try { - payload = JSON.parse(text); + payload = parseSanitized(text); } catch { /* non-JSON body — surfaced via the error path below */ } @@ -464,11 +465,11 @@ export async function validateStructuredData( ); } - const text = await res.text(); + const text = stripTerminalEscapes(await res.text()); let payload: unknown = null; if (text.length > 0) { try { - payload = JSON.parse(text); + payload = parseSanitized(text); } catch { /* non-JSON body — surfaced via the error path below */ } @@ -537,11 +538,11 @@ export async function postAsk( ); } - const text = await res.text(); + const text = stripTerminalEscapes(await res.text()); let payload: unknown = null; if (text.length > 0) { try { - payload = JSON.parse(text); + payload = parseSanitized(text); } catch { // Non-JSON — fall through to the error path below. } diff --git a/src/sanitize.ts b/src/sanitize.ts new file mode 100644 index 0000000..611090c --- /dev/null +++ b/src/sanitize.ts @@ -0,0 +1,51 @@ +/** + * Neutralise terminal escape sequences in text that came from the API. + * + * Scan results quote content from the scanned website (its , llms.txt + * headings, header values). The CLI prints that to the operator's terminal, + * so a hostile site could otherwise plant OSC 52 (clipboard write), CSI 2J + * (clear screen), a carriage return that overwrites a line, or bidi overrides + * — CWE-150, reported 2026-11-03. The server strips these too; this is the + * sink-side defence for older stored scans and any other API host. + * + * Kept: \n and \t. Removed: whole ESC/C1 sequences and every other C0/C1 + * control, DEL, and Unicode bidi override/isolate characters. + */ + +const ESCAPE_SEQUENCE = new RegExp( + [ + "(?:\\u001B[\\]PX^_]|[\\u0090\\u0098\\u009D\\u009E\\u009F])[\\s\\S]*?(?:\\u0007|\\u001B\\\\|\\u009C|$)", + "(?:\\u001B\\[|\\u009B)[\\u0030-\\u003F]*[\\u0020-\\u002F]*[\\u0040-\\u007E]?", + "\\u001B[\\u0020-\\u002F]*[\\u0030-\\u007E]?", + ].join("|"), + "g", +); + +const CONTROL_CHARS = + /[\u0000-\u0008\u000B-\u001F\u007F-\u009F‪-‮⁦-⁩]/g; + +export function stripTerminalEscapes(text: string): string { + return text + .replace(/\r\n?/g, "\n") + .replace(ESCAPE_SEQUENCE, "") + .replace(CONTROL_CHARS, ""); +} + +/** Deep-sanitise every string (values and keys) in a parsed JSON payload. */ +export function sanitizePayload(value: unknown): unknown { + if (typeof value === "string") return stripTerminalEscapes(value); + if (Array.isArray(value)) return value.map(sanitizePayload); + if (value && typeof value === "object") { + const out: Record<string, unknown> = {}; + for (const [k, v] of Object.entries(value)) { + out[stripTerminalEscapes(k)] = sanitizePayload(v); + } + return out; + } + return value; +} + +/** JSON.parse that returns a payload with every string sanitised. */ +export function parseSanitized(text: string): unknown { + return sanitizePayload(JSON.parse(text)); +} diff --git a/test/sanitize.test.ts b/test/sanitize.test.ts new file mode 100644 index 0000000..78cecf0 --- /dev/null +++ b/test/sanitize.test.ts @@ -0,0 +1,87 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { stripTerminalEscapes, sanitizePayload } from "@/sanitize"; +import { ApiError, getScan, postAsk, type Config } from "@/client"; + +const ESC = "\u001b"; +const BEL = "\u0007"; +// The reported payload: OSC 52 clipboard write + CSI 2J clear screen. +const OSC52 = `${ESC}]52;c;${Buffer.from("rm -rf ~/.ssh").toString("base64")}${BEL}`; +const CLEAR = `${ESC}[2J`; +const DANGEROUS = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F‪-‮⁦-⁩]/; + +const config: Config = { + baseUrl: "https://agent-ready.dev", + apiKey: "ar_live_test", + scanTimeoutMs: 1000, + getTimeoutMs: 1000, +}; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("stripTerminalEscapes", () => { + it("removes OSC 52 and CSI sequences whole", () => { + expect(stripTerminalEscapes(`Acme${OSC52}${CLEAR} Home`)).toBe("Acme Home"); + }); + + it("handles ST, C1, DCS, unterminated and two-byte sequences", () => { + expect(stripTerminalEscapes(`a${ESC}]0;t${ESC}\\b`)).toBe("ab"); + expect(stripTerminalEscapes("a\u009b31mb")).toBe("ab"); + expect(stripTerminalEscapes(`a${ESC}Pq${ESC}\\b`)).toBe("ab"); + expect(stripTerminalEscapes(`a${ESC}]52;c;AAAA`)).toBe("a"); + expect(stripTerminalEscapes(`a${ESC}cb`)).toBe("ab"); + }); + + it("strips CR/DEL/NUL/bidi, keeps \\n \\t and normal Unicode", () => { + expect(stripTerminalEscapes("ok\rX\u007f\u0000‮\ty\nCafé ✓")).toBe("ok\nX\ty\nCafé ✓"); + }); + + it("deep-sanitises payloads", () => { + expect(sanitizePayload({ a: [`x${CLEAR}`, 1, null], b: { c: `y${BEL}` } })).toEqual({ + a: ["x", 1, null], + b: { c: "y" }, + }); + }); +}); + +describe("client responses are sanitised before anything prints them", () => { + it("getScan strips escapes that arrive JSON-encoded (\\u001b) in a check message", async () => { + const body = { + id: "s1", + rootUrl: "https://evil.test", + status: "completed", + siteChecks: [ + { checkId: "A10", name: "Title", status: "pass", message: `Page title: "Acme${OSC52}${CLEAR}"`, howToFix: null }, + ], + }; + // JSON.stringify encodes ESC as \u001b — the form it really arrives in. + const raw = JSON.stringify(body); + expect(raw).toContain("\\u001b"); + vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response(raw, { status: 200, headers: { "Content-Type": "application/json" } }), + ); + const scan = (await getScan(config, "s1")) as unknown as { siteChecks: { message: string }[] }; + expect(scan.siteChecks[0].message).toBe('Page title: "Acme"'); + }); + + it("error messages built from a raw non-JSON body are sanitised", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response(`bad gateway${CLEAR}${OSC52}`, { status: 502 }), + ); + const err = await getScan(config, "s1").catch((e) => e); + expect(err).toBeInstanceOf(ApiError); + expect(err.message).not.toMatch(DANGEROUS); + }); + + it("postAsk envelopes are sanitised", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response( + JSON.stringify({ _meta: { response_type: "list" }, results: [{ name: `n${CLEAR}`, description: `d${OSC52}` }] }), + { status: 200 }, + ), + ); + const out = JSON.stringify(await postAsk(config, { q: "q" })); + expect(out).not.toMatch(/\\u00(1b|07|9b)/i); + }); +});