Skip to content

Commit 4bdf9ca

Browse files
authored
fix(tui): block terminal controls in system messages (#118998)
* fix(tui): sanitize rendered system messages * test(tui): keep PTY safety proof within lint budget * test(tui): clarify terminal safety PTY proof * test(tui): de-churn terminal safety harness * fix(tui): sanitize connection status output * test(tui): split PTY harness support * fix(tui): sanitize selector and footer output * fix(tui): harden terminal display boundaries * fix(tui): harden terminal display boundaries * fix(tui): harden terminal output boundaries * test(tui): repair terminal safety proof * test(tui): harden terminal safety oracle * test(tui): type OSC terminator candidates * fix(tui): authenticate current terminal rendering * fix(tui): harden terminal output safety evidence * test(tui): keep PTY cell type internal * test(tui): reject literal tabs in PTY oracle * test(tui): reject literal backspace in PTY oracle
1 parent 1e38803 commit 4bdf9ca

30 files changed

Lines changed: 2041 additions & 226 deletions
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
title: TUI terminal rendering and output safety PTY contracts
2+
scenario:
3+
id: tui-terminal-safety-pty
4+
surface: tui
5+
category: tui.rendering-and-output-safety
6+
coverage:
7+
primary:
8+
- tui.terminal-rendering-primitives
9+
- tui.output-safety
10+
risk: medium
11+
objective: Prove narrow terminal rendering and hostile display-boundary sanitization through the real runTui PTY loop.
12+
successCriteria:
13+
- Long Unicode output renders through narrow real PTY frames without replacement characters.
14+
- Wrapped URLs retain their complete copy-safe OSC 8 target.
15+
- ANSI, OSC, clipboard, and C1 payloads cannot reach raw terminal frames.
16+
- Printable text surrounding hostile terminal controls remains visible.
17+
- A row-aware synchronized-frame oracle proves selector labels, descriptions, footer fields, connection status, BTW questions, and complete headers collapse CR, LF, and tab payloads to exact single-space one-line copies while preserving printable Unicode and RTL isolation.
18+
- The authenticated row oracle uses the final bounded viewport at the fixture's exact PTY dimensions, including autowrap and bottom scrolling, and matches only visible cells authenticated by balanced synchronized frames; later frames preserve untouched authenticated cells, while unsynchronized writes and erases revoke touched cells.
19+
- The oracle has negative controls for split rows, literal tabs, stale spaces, post-frame text and erases, right-margin wrapping, scrolling, and incomplete synchronized frames or trailing controls, which invalidate prior frames until controls and OSC 8 state are complete.
20+
- Hostile selected session and agent identity fields cannot inject controls through the header while their stored identity remains raw.
21+
- Live tool titles sanitize before trusted styling, tool-result Markdown sanitizes source before parsing and isolates rendered RTL content outside OSC 8 and padding, and control-only system or BTW error output renders a neutral visible fallback.
22+
- Restored in-flight Markdown and dynamic command descriptions sanitize display copies, while unsafe thinking-level completion values are omitted before editor rendering.
23+
- Model and session selections pass exact unmodified backend values to patchSession and loadHistory.
24+
codeRefs:
25+
- src/tui/components/btw-inline-message.ts
26+
- src/tui/components/chat-log.ts
27+
- src/tui/components/filterable-select-list.ts
28+
- src/tui/components/hyperlink-markdown.ts
29+
- src/tui/components/searchable-select-list.ts
30+
- src/tui/components/tool-execution.ts
31+
- src/tui/tui-autocomplete.ts
32+
- src/tui/tui-pty-harness-assertion-test-support.ts
33+
- src/tui/tui-pty-harness.e2e.test.ts
34+
- src/tui/tui.ts
35+
- src/tui/tui-formatters.ts
36+
- src/tui/osc8-hyperlinks.ts
37+
execution:
38+
kind: script
39+
path: test/e2e/qa-lab/tui/tui-pty-evidence-producer.ts
40+
summary: Runs independently matched real-PTY rendering and output-safety assertions and authenticates their fresh Vitest results.
41+
timeoutMs: 180000
42+
args:
43+
- --artifact-base
44+
- ${outputDir}
45+
- --scenario-id
46+
- ${scenarioId}
47+
config:
48+
tuiPtyCases:
49+
- coverageId: tui.terminal-rendering-primitives
50+
testFile: src/tui/tui-pty-harness.e2e.test.ts
51+
testNamePattern: ^TUI PTY harness renders long Unicode output and copy-safe URLs in narrow real PTY frames$
52+
- coverageId: tui.output-safety
53+
testFile: src/tui/tui-pty-harness.e2e.test.ts
54+
testNamePattern: ^TUI PTY harness sanitizes ANSI OSC and C1 payloads across real PTY display boundaries$
55+
- coverageId: tui.output-safety
56+
testFile: src/tui/tui-pty-harness-assertion-test-support.test.ts
57+
testNamePattern: ^hasSynchronizedFrameRow requires exact single-space text and all markers on one completed row$
58+
- coverageId: tui.output-safety
59+
testFile: src/tui/tui-pty-harness-assertion-test-support.test.ts
60+
testNamePattern: ^hasSynchronizedFrameRow rejects terminal row reconstruction false positives$

‎src/tui/components/btw-inline-message.test.ts‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// BTW inline message tests cover compact inline status message rendering.
22
import { describe, expect, it } from "vitest";
3+
import { normalizeTestText } from "../../../test/helpers/normalize-text.js";
34
import { BtwInlineMessage } from "./btw-inline-message.js";
45

56
describe("btw inline message", () => {
@@ -17,4 +18,96 @@ describe("btw inline message", () => {
1718
" Press Enter or Esc to dismiss ",
1819
]);
1920
});
21+
22+
it("sanitizes the question and successful Markdown result on every update", () => {
23+
const firstQuestionAttack = "\x1b[3Jquestion";
24+
const firstTextAttack = "\x1b]52;c;T08_BTW_CLIPBOARD\x07";
25+
const nextQuestionAttack = "\u009b3Jquestion";
26+
const nextTextAttack = "\u009d0;T08_BTW_TITLE\u009c";
27+
const url = "https://example.test/tui/btw?copy=caf%C3%A9";
28+
const message = new BtwInlineMessage({
29+
question: `first ${firstQuestionAttack}\r\nمرحبا\tשלום`,
30+
text: `${firstTextAttack}**first café**\nsecond body ${url}`,
31+
});
32+
33+
let lines = message.render(140);
34+
let raw = lines.join("\n");
35+
let rendered = normalizeTestText(raw);
36+
expect(rendered).toContain("BTW: \u2067first question مرحبا שלום\u2069");
37+
expect(rendered).toContain("مرحبا שלום");
38+
expect(rendered).toContain("first café");
39+
expect(rendered).toContain("second body");
40+
expect(lines[1]).not.toMatch(/[\r\n\t]/u);
41+
expect(raw).toContain(`\x1b]8;;${url}\x07`);
42+
expect(raw).not.toContain(firstQuestionAttack);
43+
expect(raw).not.toContain(firstTextAttack);
44+
45+
message.setResult({
46+
question: `next ${nextQuestionAttack}\r\nשלום\tمرحبا`,
47+
text: `${nextTextAttack}**next 東京** ${url}`,
48+
});
49+
50+
lines = message.render(140);
51+
raw = lines.join("\n");
52+
rendered = normalizeTestText(raw);
53+
expect(rendered).toContain("BTW: \u2067next question שלום مرحبا\u2069");
54+
expect(rendered).toContain("שלום مرحبا");
55+
expect(rendered).toContain("next 東京");
56+
expect(rendered).not.toContain("first question");
57+
expect(rendered).not.toContain("first café");
58+
expect(raw).not.toContain(nextQuestionAttack);
59+
expect(raw).not.toContain(nextTextAttack);
60+
expect(lines[1]).not.toMatch(/[\r\n\t]/u);
61+
});
62+
63+
it("passes sanitized RTL source through Markdown exactly once", () => {
64+
const message = new BtwInlineMessage({
65+
question: "structure proof",
66+
text: "\u202e# مرحبا\u202c\n\n\u200f> שלום\n\n\u2066- عنصر\u2069",
67+
});
68+
69+
const lines = message.render(100);
70+
const normalized = lines
71+
.map((line) => normalizeTestText(line).replace(/[\u2067\u2069]/gu, ""))
72+
.join("\n");
73+
expect(normalized).toContain("مرحبا");
74+
expect(normalized).not.toContain("# مرحبا");
75+
expect(normalized).toContain("│ שלום");
76+
expect(normalized).toContain("- عنصر");
77+
for (const line of lines.filter((entry) => /[\u0590-\u08ff]/u.test(entry))) {
78+
expect(line.match(/\u2067/gu)).toHaveLength(1);
79+
expect(line.match(/\u2069/gu)).toHaveLength(1);
80+
}
81+
});
82+
83+
it("sanitizes BTW error questions and text before applying trusted themes", () => {
84+
const questionAttack = "\x1b]0;T08_BTW_QUESTION_TITLE\x07";
85+
const errorAttack = "\u009b3Jretry";
86+
const message = new BtwInlineMessage({
87+
question: `why ${questionAttack}failed?\r\nمرحبا\tשלום`,
88+
text: `${errorAttack} **plain** safely café`,
89+
isError: true,
90+
});
91+
92+
const raw = message.render(100).join("\n");
93+
const rendered = normalizeTestText(raw);
94+
expect(rendered).toContain("BTW: \u2067why failed? مرحبا שלום\u2069");
95+
expect(rendered).toContain("مرحبا שלום");
96+
expect(rendered).toContain("retry **plain** safely café");
97+
expect(raw).not.toContain(questionAttack);
98+
expect(raw).not.toContain(errorAttack);
99+
});
100+
101+
it.each(["", " \x1b]0;hidden title\x07 "])(
102+
"renders a visible fallback when a BTW error sanitizes to empty",
103+
(text) => {
104+
const message = new BtwInlineMessage({
105+
question: "what failed?",
106+
text,
107+
isError: true,
108+
});
109+
110+
expect(normalizeTestText(message.render(80).join("\n"))).toContain("(no output)");
111+
},
112+
);
20113
});

‎src/tui/components/btw-inline-message.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// BTW inline message component renders compact aside messages in chat.
22
import { Container, Spacer, Text } from "@earendil-works/pi-tui";
33
import { theme } from "../theme/theme.js";
4+
import { sanitizeRenderableLine, sanitizeRenderableText } from "../tui-formatters.js";
45
import { AssistantMessageComponent } from "./assistant-message.js";
56

67
// Inline overlay message for BTW follow-up answers inside the chat log.
@@ -19,13 +20,21 @@ export class BtwInlineMessage extends Container {
1920

2021
/** Replaces the current BTW content without reallocating the host component. */
2122
setResult(params: BtwInlineMessageParams) {
23+
const question = sanitizeRenderableLine(params.question);
24+
let text = params.text;
25+
if (params.isError) {
26+
text = sanitizeRenderableText(text);
27+
if (!text.trim()) {
28+
text = "(no output)";
29+
}
30+
}
2231
this.clear();
2332
this.addChild(new Spacer(1));
24-
this.addChild(new Text(theme.header(`BTW: ${params.question}`), 1, 0));
33+
this.addChild(new Text(theme.header(`BTW: ${question}`), 1, 0));
2534
if (params.isError) {
26-
this.addChild(new Text(theme.error(params.text), 1, 0));
35+
this.addChild(new Text(theme.error(text), 1, 0));
2736
} else {
28-
this.addChild(new AssistantMessageComponent(params.text));
37+
this.addChild(new AssistantMessageComponent(text));
2938
}
3039
this.addChild(new Text(theme.dim("Press Enter or Esc to dismiss"), 1, 0));
3140
}

‎src/tui/components/chat-log.test.ts‎

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,49 @@ describe("ChatLog", () => {
1616
expect(rendered).not.toContain("system-1");
1717
});
1818

19+
it("sanitizes terminal controls before rendering an initial system message", () => {
20+
const chatLog = new ChatLog(20);
21+
const sgr = "\x1b[38;5;201mcolor";
22+
const erase = "\x1b[3Jerase";
23+
const osc52 = "\x1b]52;c;T08_CHAT_LOG_CLIPBOARD\x07";
24+
const c1Csi = "\u009b3Jc1";
25+
const c1Osc = "\u009d0;T08_CHAT_LOG_TITLE\u009c";
26+
27+
chatLog.addSystem(`before ${sgr}\x1b[0m ${erase} ${osc52}${c1Csi} ${c1Osc}after`);
28+
29+
const raw = chatLog.render(120).join("\n");
30+
const rendered = normalizeTestText(raw);
31+
expect(rendered).toContain("before color erase c1 after");
32+
for (const attack of [sgr, erase, osc52, c1Csi, c1Osc]) {
33+
expect(raw).not.toContain(attack);
34+
}
35+
});
36+
1937
it("coalesces consecutive repeatable system messages", () => {
2038
const chatLog = new ChatLog(20);
39+
const rawText = "\x1b[?7777h\x1b]52;c;T08_CHAT_LOG_ONLY_CONTROLS\x07";
2140

22-
chatLog.addSystem("no active run", { coalesceConsecutive: true });
23-
chatLog.addSystem("no active run", { coalesceConsecutive: true });
24-
chatLog.addSystem("no active run", { coalesceConsecutive: true });
41+
chatLog.addSystem(rawText, { coalesceConsecutive: true });
42+
chatLog.addSystem(rawText, { coalesceConsecutive: true });
43+
chatLog.addSystem(rawText, { coalesceConsecutive: true });
2544

26-
const rendered = normalizeTestText(chatLog.render(120).join("\n"));
45+
const raw = chatLog.render(120).join("\n");
46+
const rendered = normalizeTestText(raw);
2747
expect(chatLog.children.length).toBe(1);
28-
expect(rendered).toContain("no active run x3");
48+
expect(rendered).toContain("(no output) x3");
49+
expect(raw).not.toContain(rawText);
50+
});
51+
52+
it("does not coalesce distinct raw system messages that sanitize identically", () => {
53+
const chatLog = new ChatLog(20);
54+
55+
chatLog.addSystem("\x1b[?7776h", { coalesceConsecutive: true });
56+
chatLog.addSystem("\u009b777;888H", { coalesceConsecutive: true });
57+
58+
const rendered = normalizeTestText(chatLog.render(120).join("\n"));
59+
expect(chatLog.children.length).toBe(2);
60+
expect(rendered.match(/\(no output\)/g)).toHaveLength(2);
61+
expect(rendered).not.toContain("x2");
2962
});
3063

3164
it("does not coalesce ordinary system messages", () => {
@@ -848,13 +881,18 @@ describe("ChatLog", () => {
848881

849882
it("replaces an existing pending system notice for the same runId", () => {
850883
const chatLog = new ChatLog(40);
884+
const firstAttack = "\x1b]52;c;T08_PENDING_FIRST\x07";
885+
const secondAttack = "\u009d0;T08_PENDING_SECOND\u009c";
851886

852-
chatLog.addPendingSystem("run-1", "first notice");
853-
chatLog.addPendingSystem("run-1", "second notice");
887+
chatLog.addPendingSystem("run-1", `first ${firstAttack}notice`);
888+
chatLog.addPendingSystem("run-1", secondAttack);
854889

855-
const rendered = chatLog.render(120).join("\n");
890+
const raw = chatLog.render(120).join("\n");
891+
const rendered = normalizeTestText(raw);
856892
expect(rendered).not.toContain("first notice");
857-
expect(rendered).toContain("second notice");
893+
expect(rendered).toContain("(no output)");
894+
expect(raw).not.toContain(firstAttack);
895+
expect(raw).not.toContain(secondAttack);
858896
expect(chatLog.children.length).toBe(1);
859897
});
860898
});

‎src/tui/components/chat-log.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import type { Component } from "@earendil-works/pi-tui";
33
import { Container, Spacer, Text } from "@earendil-works/pi-tui";
44
import { theme } from "../theme/theme.js";
5+
import { sanitizeRenderableText } from "../tui-formatters.js";
56
import { AssistantMessageComponent } from "./assistant-message.js";
67
import { BtwInlineMessage } from "./btw-inline-message.js";
78
import { ToolExecutionComponent } from "./tool-execution.js";
@@ -194,13 +195,15 @@ export class ChatLog extends Container {
194195
this.pendingUsers.clear();
195196
}
196197

197-
private formatRepeatedSystemText(text: string, count: number) {
198-
return count > 1 ? `${text} x${count}` : text;
198+
private formatSystemText(text: string, count = 1) {
199+
const sanitized = sanitizeRenderableText(text);
200+
const visible = sanitized.trim() || (text ? "(no output)" : "");
201+
return theme.system(count > 1 ? `${visible} x${count}` : visible);
199202
}
200203

201204
private createSystemMessage(text: string): RepeatableSystemMessage {
202205
const entry = new Container();
203-
const textNode = new Text(theme.system(text), 1, 0);
206+
const textNode = new Text(this.formatSystemText(text), 1, 0);
204207
entry.addChild(new Spacer(1));
205208
entry.addChild(textNode);
206209
return {
@@ -219,7 +222,7 @@ export class ChatLog extends Container {
219222
) {
220223
this.repeatableSystemMessage.count += 1;
221224
this.repeatableSystemMessage.textNode.setText(
222-
theme.system(this.formatRepeatedSystemText(text, this.repeatableSystemMessage.count)),
225+
this.formatSystemText(text, this.repeatableSystemMessage.count),
223226
);
224227
return;
225228
}

‎src/tui/components/filterable-select-list.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,4 +166,50 @@ describe("FilterableSelectList", () => {
166166

167167
expect(list.getSelectedItem()?.value).toBe("codex");
168168
});
169+
170+
it("sanitizes rendered fields without changing filtering or the selected value", () => {
171+
const attacks = [
172+
"\u001b[38;5;201m",
173+
"\u001b[3J",
174+
"\u001b]0;filter-title\u0007",
175+
"\u001b]52;c;filter-clipboard\u0007",
176+
"\u009b2K",
177+
"\u009d0;filter-c1-title\u009c",
178+
];
179+
const rawValue = `fv-start${attacks[1]}fv-end\r\nمرحبا\tשלום`;
180+
const description = `fd-start${attacks[3]}fd-end\n東京`;
181+
const list = new FilterableSelectList(
182+
[
183+
{ value: "decoy", label: "decoy" },
184+
{
185+
value: rawValue,
186+
label: attacks.join(""),
187+
description,
188+
searchText: "raw-filter-target",
189+
},
190+
],
191+
5,
192+
mockTheme,
193+
);
194+
let selectedValue: string | undefined;
195+
list.onSelect = (item) => {
196+
selectedValue = item.value;
197+
};
198+
199+
typeInput(list, "raw-filter-target");
200+
const rendered = list.render(160).join("\n");
201+
202+
expect(rendered).toContain("fv-startfv-end");
203+
expect(rendered).toContain("مرحبا שלום");
204+
expect(rendered).toContain("fd-startfd-end 東京");
205+
expect(rendered).toContain("\u2067");
206+
expect(rendered).toContain("\u2069");
207+
for (const attack of attacks) {
208+
expect(rendered).not.toContain(attack);
209+
}
210+
expect(rendered).not.toContain("fv-end\r\nمرحبا\tשלום");
211+
212+
list.handleInput("\r");
213+
expect(selectedValue).toBe(rawValue);
214+
});
169215
});

0 commit comments

Comments
 (0)