Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -94,11 +95,11 @@ async function call<T>(config: Config, opts: FetchOptions): Promise<T> {
);
}

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).
Expand Down Expand Up @@ -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 */
}
Expand Down Expand Up @@ -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 */
}
Expand Down Expand Up @@ -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 */
}
Expand Down Expand Up @@ -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.
}
Expand Down
51 changes: 51 additions & 0 deletions src/sanitize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* Neutralise terminal escape sequences in text that came from the API.
*
* Scan results quote content from the scanned website (its <title>, 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));
}
87 changes: 87 additions & 0 deletions test/sanitize.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading