OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(dashboard): retain fragmented input and final scan activity (#1284)
Michael D'Angelo0e271755ab39
diff --git a/sdk/typescript/src/scan-dashboard.ts b/sdk/typescript/src/scan-dashboard.tsindex 74be02927..132982521 100644--- a/sdk/typescript/src/scan-dashboard.ts+++ b/sdk/typescript/src/scan-dashboard.ts@@ -89,6 +89,7 @@ type DashboardActivityKind = ScanActivity["kind"] | "status" | "warning";interface DashboardActivityLine {text: string;kind: DashboardActivityKind | "path" | "code";+ contentStart?: number;links?: readonly DashboardActivityLink[];code?: readonly string[];bold?: readonly string[];@@ -151,7 +152,7 @@ export class ScanDashboard {request: ScanBudget;input: string;error: string;- finish: (limit?: number) => void;+ finish: (limit?: number, preserveInput?: boolean) => void;} | null = null;#timer: NodeJS.Timeout | null = null;#refreshPending = false;@@ -163,6 +164,7 @@ export class ScanDashboard {#observingStreamErrors = false;readonly #onStreamError = (): void => {};#keyInput: PassThrough | null = null;+ #ss3Parameters = false;#inputKeys: {keys: string[];continued: boolean;@@ -205,6 +207,7 @@ export class ScanDashboard {this.#keyInput = input;if (input === null) return;let pending = 0;+ this.#ss3Parameters = false;input.setEncoding("utf8");input.on("data", (text: string) => {if (this.#inputKeys !== null) {@@ -221,26 +224,48 @@ export class ScanDashboard {key: { sequence: string; meta?: boolean; code?: string },) => {pending -= key.sequence.length;+ if (this.#ss3Parameters) {+ if (/^[ -?]+$/u.test(key.sequence)) return;+ this.#ss3Parameters = false;+ if (/^[@-~]$/u.test(key.sequence)) return;+ }const escapes =key.code === undefined? undefined: key.sequence.match(/^\u001B+(?=\u001B)/u)?.[0];- const keys =- (key.meta && key.code === undefined) ||- key.sequence.includes("\u0003")- ? Array.from(key.sequence)- : escapes !== undefined- ? [...escapes, key.sequence.slice(escapes.length)]- : [key.sequence];+ // Readline ends modified SS3 keys at the parameter separator.+ const modifiedSs3 =+ key.code !== undefined &&+ /^\u001BO[0-?]+$/u.test(key.sequence.slice(escapes?.length ?? 0));+ if (modifiedSs3) this.#ss3Parameters = true;+ const keys = modifiedSs3+ ? [...(escapes ?? ""), key.sequence.slice(escapes?.length ?? 0)]+ : key.code !== undefined && key.sequence.endsWith("\u001B")+ ? ["\u001B"]+ : (key.meta && key.code === undefined) ||+ key.sequence.includes("\u0003")+ ? Array.from(key.sequence)+ : escapes !== undefined+ ? [...escapes, key.sequence.slice(escapes.length)]+ : [key.sequence];const batch = this.#inputKeys;const continued = batch?.continued === true;if (batch !== null) batch.continued = false;if (batch === null) this.#handleKeys(keys);else if (- this.#budget === null &&+ this.#budget !== null &&+ batch.keys.length === 0 &&keys.length > 1 &&- keys.every((key) => key === "\u001B")+ keys[0] === "\u001B" &&+ continued) {+ // The buffered Escape belongs to the prior chunk's budget dismissal.+ // Replay the complete remaining key, including a prefix from prior chunks.+ this.#handleKeys(["\u001B"]);+ this.#setKeyInput(new PassThrough());+ batch.replay =+ key.sequence.slice(1) + (pending ? batch.text.slice(-pending) : "");+ } else if (keys.length > 1 && keys.every((key) => key === "\u001B")) {// Readline can consume a following key's Escape as a repeated Escape.// Keep that introducer with the remaining decoded text for replay.const remaining =@@ -249,17 +274,6 @@ export class ScanDashboard {for (const escape of prefix.slice(0, -1)) batch.keys.push(escape);this.#setKeyInput(new PassThrough());batch.replay = remaining.slice(prefix.length - 1);- } else if (- this.#budget !== null &&- batch.keys.length === 0 &&- keys.length > 1 &&- keys[0] === "\u001B" &&- continued- ) {- // The buffered Escape belongs to the prior chunk's budget dismissal.- // Decode this chunk again after that transition, retaining its own keys.- this.#handleKeys(["\u001B"]);- batch.replay = true;} else batch.keys.push(...keys);},);@@ -274,7 +288,7 @@ export class ScanDashboard {budget.finish();this.#options.onInterrupt?.();} else if (key === "\u001B") {- budget.finish();+ budget.finish(undefined, true);} else if (key === "\r" || key === "\n") {const value = budget.input.trim();const limit = Number(value);@@ -395,6 +409,7 @@ export class ScanDashboard {public stop(): void {if (this.#timer === null) return;+ if (this.#refreshPending) this.#refresh();this.#options.clock.clearInterval(this.#timer);this.#timer = null;this.#budget?.finish();@@ -560,10 +575,11 @@ export class ScanDashboard {this.#setKeyInput(new PassThrough());return new Promise((resolve) => {const abort = () => finish();- const finish = (limit?: number) => {+ const finish = (limit?: number, preserveInput = false) => {request.signal.removeEventListener("abort", abort);this.#budget = null;- if (this.#timer !== null) this.#setKeyInput(new PassThrough());+ if (this.#timer !== null && !preserveInput)+ this.#setKeyInput(new PassThrough());this.#refresh();resolve(limit);};@@ -787,6 +803,7 @@ export class ScanDashboard {? styleInlineCode(colored, line): colored,line.links,+ line.contentStart,);return `${ERASE_LINE}${formatted}`;})@@ -794,7 +811,7 @@ export class ScanDashboard {);}- #componentInput(keys: string[]): void {+ #componentInput(keys: readonly string[]): void {for (const key of keys) {if (key === "\u0003") {this.#options.onInterrupt?.();@@ -1054,7 +1071,10 @@ export class ScanDashboard {}const source = worker === undefined ? "main" : `worker ${worker}`;- const prefix = ` [${formatLocalTime(recordedAt)}] ${source} · `;+ const prefix = fitActivityPrefix(+ ` [${formatLocalTime(recordedAt)}] ${source} · `,+ width,+ );const code: string[] = [];const bold: string[] = [];if (prose) {@@ -1079,7 +1099,13 @@ export class ScanDashboard {),);for (const text of lines) {- cache.lines.push({ text, kind: "path", code, bold });+ cache.lines.push({+ text,+ kind: "path",+ code,+ bold,+ contentStart: prefix.length,+ });}}return cache.lines;@@ -1094,7 +1120,9 @@ export class ScanDashboard {prefix: string,value: string,kind: DashboardActivityLine["kind"],+ generatedPrefix = "",): void => {+ prefix = fitActivityPrefix(prefix, width);if (kind !== "message" && kind !== "reasoning") {for (const text of wrapActivity(prefix, value, width)) {lines.push({ text, kind });@@ -1134,7 +1162,16 @@ export class ScanDashboard {? wrapCode(started ? continuation : prefix, description, width): wrapActivity(started ? continuation : prefix, description, width);for (const text of wrapped) {- lines.push({ text, kind: fenced ? "code" : kind, links, code });+ lines.push({+ text,+ kind: fenced ? "code" : kind,+ links,+ code,+ contentStart: prefix.length + generatedPrefix.length,+ });+ generatedPrefix = generatedPrefix+ .slice(text.length - prefix.length)+ .trimStart();started = true;}}@@ -1163,7 +1200,7 @@ export class ScanDashboard {const worker =entry.worker === undefined ? "" : `worker ${entry.worker} · `;const prefix = ` ${timestamp} ${icon} `;- append(prefix, `${worker}${entry.description}`, kind);+ append(prefix, `${worker}${entry.description}`, kind, worker);for (const path of entry.paths) {append(" ".repeat(prefix.length), path, "path");}@@ -1245,27 +1282,43 @@ function replaceVisibleText(value: string,search: string,replacement: string,+ contentStart = 0,): string {let replaced = false;+ let offset = 0;return value.split(/(\u001B\[[0-?]*[ -/]*[@-~]|\u001B\][\s\S]*?(?:\u0007|\u001B\\))/gu).map((part, index) => {- if (index % 2 === 1 || replaced || !part.includes(search)) return part;- replaced = true;- return part.replace(search, () => replacement);+ if (index % 2 === 1) return part;+ const start = Math.max(0, contentStart - offset);+ offset += part.length;+ if (replaced || start >= part.length) return part;+ return (+ part.slice(0, start) ++ part.slice(start).replace(search, () => {+ replaced = true;+ return replacement;+ })+ );}).join("");}function styleInlineCode(value: string, line: DashboardActivityLine): string {for (const text of line.bold ?? []) {- value = replaceVisibleText(value, text, `\u001B[1m${text}\u001B[22m`);+ value = replaceVisibleText(+ value,+ text,+ `\u001B[1m${text}\u001B[22m`,+ line.contentStart,+ );}for (const text of line.code ?? []) {value = replaceVisibleText(value,text,`\u001B[2m${text}\u001B[22m${line.kind === "message" ? "\u001B[1m" : ""}`,+ line.contentStart,);}return value;@@ -1274,6 +1327,7 @@ function styleInlineCode(value: string, line: DashboardActivityLine): string {function linkActivity(value: string,links: readonly DashboardActivityLink[] | undefined,+ contentStart?: number,): string {for (const { label, target } of links ?? []) {const safe = safeHyperlinkTarget(target);@@ -1282,6 +1336,7 @@ function linkActivity(value,label,`\u001B]8;;${safe}\u0007${label}\u001B]8;;\u0007`,+ contentStart,);}}@@ -1327,8 +1382,12 @@ function formatLocalTime(timestamp: number): string {.join(":");}+function fitActivityPrefix(prefix: string, width: number): string {+ return width <= 2 ? "" : fitLine(prefix, width - 2);+}+function wrapActivity(prefix: string, value: string, width: number): string[] {- prefix = width <= 2 ? "" : fitLine(prefix, width - 2);+ prefix = fitActivityPrefix(prefix, width);const available = Math.max(1, width - stringWidth(prefix));const continuation = " ".repeat(prefix.length);const lines: string[] = [];@@ -1450,7 +1509,7 @@ function columnChunks(}function wrapCode(prefix: string, value: string, width: number): string[] {- prefix = width <= 2 ? "" : fitLine(prefix, width - 2);+ prefix = fitActivityPrefix(prefix, width);const prefixWidth = stringWidth(prefix);const continuation = " ".repeat(prefixWidth);return columnChunks(diff --git a/sdk/typescript/tests-ts/scan-dashboard.test.ts b/sdk/typescript/tests-ts/scan-dashboard.test.tsindex 986266b0a..6841dfafe 100644--- a/sdk/typescript/tests-ts/scan-dashboard.test.ts+++ b/sdk/typescript/tests-ts/scan-dashboard.test.ts@@ -57,6 +57,219 @@ class DashboardTestInput extends EventEmitter {}describe("live scan dashboard", () => {+ test("flushes queued activity before stopping without rendering afterward", () => {+ const stderr = capture(true);+ const pending: (() => void)[] = [];+ const dashboard = createDashboard(stderr.stream, {+ clock: {+ ...fakeClock(),+ queueMicrotask: (callback) => pending.push(callback),+ },+ });+ dashboard.start();+ dashboard.note("First event");+ dashboard.note("Final event");+ dashboard.stop();+ const stopped = stderr.text();+ expect(stripVTControlCharacters(stopped)).toContain("Final event");+ for (const callback of pending) callback();+ expect(stderr.text()).toBe(stopped);+ });++ test("keeps whole and fragmented function keys out of worker selection", () => {+ const stderr = capture(true);+ const input = new DashboardTestInput();+ const dashboard = createDashboard(stderr.stream, { input });+ dashboard.start();+ input.emit("data", "d");+ for (const key of ["", "\u001B", "\u001B\u001B"].flatMap((prefix) =>+ ["\u001BO1;5P", "\u001B[1;2Q"].map((key) => prefix + key),+ )) {+ for (let split = 1; split <= key.length; split++) {+ input.emit("data", key.slice(0, split));+ input.emit("data", key.slice(split));+ expect(lastFrame(stderr)).not.toContain("DETAILS · worker");+ }+ }+ input.emit("data", "3");+ expect(lastFrame(stderr)).toContain("DETAILS · worker 3");+ dashboard.stop();+ });++ test.each(["\u001BO", "\u001BO1;"])(+ "discards incomplete input %j when the dashboard restarts",+ (prefix) => {+ const stderr = capture(true);+ const input = new DashboardTestInput();+ const dashboard = createDashboard(stderr.stream, { input });+ dashboard.start();+ input.emit("data", "d");+ input.emit("data", prefix);+ dashboard.stop();+ dashboard.start();+ input.emit("data", "3");+ expect(lastFrame(stderr)).toContain("DETAILS · worker 3");+ dashboard.stop();+ },+ );++ test("keeps function-key fragments out of worker selection when dismissing a budget", async () => {+ const stderr = capture(true);+ const input = new DashboardTestInput();+ const dashboard = createDashboard(stderr.stream, { input });+ dashboard.start();+ try {+ input.emit("data", "d");+ const answer = dashboard.requestBudgetIncrease({+ maxCostUsd: 20,+ cost: fakeResult([], "complete", {+ input_tokens: 100,+ output_tokens: 1,+ }).cost!,+ signal: new AbortController().signal,+ });+ input.emit("data", "\u001BO");+ input.emit("data", "1;5P\u001B\u001B[A");+ await expect(answer).resolves.toBeUndefined();+ expect(lastFrame(stderr)).toContain("DETAILS");+ expect(lastFrame(stderr)).not.toContain("DETAILS · worker");+ } finally {+ dashboard.stop();+ }+ });++ test.each(["\u001BO", "\u001B[1;"])(+ "honors Escape and Ctrl-C after incomplete input %j",+ async (prefix) => {+ for (const key of ["\u001B", "\u0003"]) {+ const stderr = capture(true);+ const input = new DashboardTestInput();+ const interrupted = mock(() => {});+ const dashboard = createDashboard(stderr.stream, {+ input,+ onInterrupt: interrupted,+ });+ dashboard.start();+ const answer = dashboard.requestBudgetIncrease({+ maxCostUsd: 20,+ cost: fakeResult([], "complete", {+ input_tokens: 100,+ output_tokens: 1,+ }).cost!,+ signal: new AbortController().signal,+ });+ input.emit("data", prefix);+ expect(lastFrame(stderr)).toContain("Raise total USD limit");+ input.emit("data", key);+ expect(lastFrame(stderr)).not.toContain("Raise total USD limit");+ expect(interrupted).toHaveBeenCalledTimes(key === "\u0003" ? 1 : 0);+ await expect(answer).resolves.toBeUndefined();+ dashboard.stop();+ }+ },+ );++ test.each([+ ["complete after Escape", ["\u001B", "\u001BO1;5P\u0003"], 1],+ ["split after Escape", ["\u001B", "\u001BO1;", "5P"], 0],+ ["coalesced prefix", ["\u001B\u001BO1;", "5P"], 0],+ ["split final byte", ["\u001B", "\u001BO1;5", "P\u0003"], 1],+ ["coalesced prefix then interrupt", ["\u001B\u001BO1;", "5P\u0003"], 1],+ ["repeated Escape prefix", ["\u001B\u001B\u001BO1;", "5P\u0003"], 1],+ ["coalesced CSI prefix", ["\u001B\u001B[1;", "2Q"], 0],+ ["split CSI prefix", ["\u001B", "\u001B[1;", "2Q\u0003"], 1],+ ["repeated CSI prefix", ["\u001B\u001B\u001B[1;", "2Q\u0003"], 1],+ ] as const)(+ "keeps modified function keys and following controls across budget dismissal: %s",+ async (_name, chunks, interrupts) => {+ const stderr = capture(true);+ const input = new DashboardTestInput();+ const interrupted = mock(() => {});+ const dashboard = createDashboard(stderr.stream, {+ input,+ onInterrupt: interrupted,+ });+ dashboard.start();+ try {+ input.emit("data", "d");+ const answer = dashboard.requestBudgetIncrease({+ maxCostUsd: 20,+ cost: fakeResult([], "complete", {+ input_tokens: 100,+ output_tokens: 1,+ }).cost!,+ signal: new AbortController().signal,+ });+ for (const chunk of chunks) input.emit("data", chunk);+ expect(lastFrame(stderr)).not.toContain("Raise total USD limit");+ await expect(answer).resolves.toBeUndefined();+ expect(interrupted).toHaveBeenCalledTimes(interrupts);+ expect(lastFrame(stderr)).not.toContain("DETAILS · worker");+ input.emit("data", "3");+ expect(lastFrame(stderr)).toContain("DETAILS · worker 3");+ } finally {+ dashboard.stop();+ }+ },+ );++ test("styles numeric inline content without matching its timestamp", () => {+ const stderr = capture(true);+ const dashboard = createDashboard(stderr.stream, { color: true });+ dashboard.start();+ dashboard.record({+ id: "numeric-markup",+ kind: "message",+ status: "completed",+ description: "Inspect `1` and [09](https://example.test/report).",+ paths: [],+ });+ expect(stderr.text()).toContain("\u001B[2m[09:41:00]\u001B[22m");+ expect(stderr.text()).toContain("Inspect \u001B[2m1\u001B[22m");+ expect(stderr.text()).toContain(+ "and \u001B]8;;https://example.test/report\u000709\u001B]8;;\u0007.",+ );+ dashboard.stop();+ });+ test.each([21, 32, 120])(+ "keeps worker labels outside inline markup at width %d",+ (columns) => {+ for (const kind of ["message", "reasoning"] as const) {+ for (const markup of ["`1`", "[1](https://example.test/report)"]) {+ const stderr = capture(true);+ const dashboard = createDashboard(+ { ...stderr.stream, columns, rows: 24 },+ { color: true },+ );+ dashboard.start();+ dashboard.record({+ id: "worker-markup",+ worker: 1,+ kind,+ status: "completed",+ description: `See ${markup}.`,+ paths: [],+ });+ const marked = stderr+ .text()+ .split("\u001B[H")+ .at(-1)!+ .replaceAll("\u001B[2m1\u001B[22m", "<code>1</code>")+ .replaceAll(+ "\u001B]8;;https://example.test/report\u00071\u001B]8;;\u0007",+ "<link>1</link>",+ );+ const frame = stripVTControlCharacters(marked).replaceAll(+ /\s+/gu,+ " ",+ );+ const tag = markup.startsWith("`") ? "code" : "link";+ expect(frame).toContain(`worker 1 · See <${tag}>1</${tag}>.`);+ dashboard.stop();+ }+ }+ },+ );test.each([["single line", () => "START" + "x".repeat(4 * 1024 * 1024) + "界END"],[@@ -511,6 +724,12 @@ describe("live scan dashboard", () => {cost,signal: controller.signal,});+ for (const chunk of ["\u001BO", "1;", "5P", "\u001B[1", ";5P"]) {+ input.emit("data", chunk);+ expect(stderr.text().split("\u001B[H").at(-1)).toContain(+ "Raise total USD limit",+ );+ }for (const byte of Buffer.from("é🙂"))input.emit("data", Uint8Array.of(byte));expect(stderr.text()).toContain("é🙂_");@@ -750,37 +969,46 @@ describe("live scan dashboard", () => {},);- test("discards a partial key when a budget request aborts externally", async () => {- jest.useFakeTimers();- const stderr = capture(true);- const input = new DashboardTestInput();- const dashboard = createDashboard(- { ...stderr.stream, rows: 14 },- { input },- );- const controller = new AbortController();- dashboard.start();- try {- for (let index = 0; index < 20; index++)- dashboard.note(`Activity ${index}`);- const answer = dashboard.requestBudgetIncrease({- maxCostUsd: 20,- cost: fakeResult([], "complete", {- input_tokens: 100,- output_tokens: 1,- }).cost!,- signal: controller.signal,- });- input.emit("data", "\u001B[");- controller.abort();- await expect(answer).resolves.toBeUndefined();- input.emit("data", "A");- expect(lastFrame(stderr)).not.toContain("above live");- expect(jest.getTimerCount()).toBe(0);- } finally {- dashboard.stop();- }- });+ test.each([+ ["navigation", "\u001B[", "A"],+ ["worker selection", "\u001BO1;", "3"],+ ])(+ "discards a partial key before %s when a budget request aborts externally",+ async (action, prefix, nextKey) => {+ jest.useFakeTimers();+ const stderr = capture(true);+ const input = new DashboardTestInput();+ const dashboard = createDashboard(+ { ...stderr.stream, rows: 14 },+ { input },+ );+ const controller = new AbortController();+ dashboard.start();+ if (action === "worker selection") input.emit("data", "d");+ try {+ for (let index = 0; index < 20; index++)+ dashboard.note(`Activity ${index}`);+ const answer = dashboard.requestBudgetIncrease({+ maxCostUsd: 20,+ cost: fakeResult([], "complete", {+ input_tokens: 100,+ output_tokens: 1,+ }).cost!,+ signal: controller.signal,+ });+ input.emit("data", prefix);+ controller.abort();+ await expect(answer).resolves.toBeUndefined();+ input.emit("data", nextKey);+ if (action === "worker selection")+ expect(lastFrame(stderr)).toContain("DETAILS · worker 3");+ else expect(lastFrame(stderr)).not.toContain("above live");+ expect(jest.getTimerCount()).toBe(0);+ } finally {+ dashboard.stop();+ }+ },+ );test("owns only its input listeners and drops pending Escape on stop and restart", async () => {jest.useFakeTimers();@@ -1078,6 +1306,10 @@ describe("live scan dashboard", () => {expect(frame()).toContain("API only activity");expect(frame()).not.toContain("Web only activity");expect(frame()).toContain("$1.00");+ for (const chunk of ["\u001BO", "1;5P"]) {+ input.emit("data", chunk);+ expect(frame()).toContain("API only activity");+ }input.emit("data", "d");expect(frame()).toContain("API session detail");expect(frame()).not.toContain("Web session detail");@@ -2372,3 +2604,57 @@ test("aligns component columns by terminal width and retains trailing cost", asy).toBe(1);dashboard.stop();});++test.each([16, 25, 120])(+ "preserves markup after clipped prefixes at width %i",+ (columns) => {+ for (const worker of [undefined, 1]) {+ for (const kind of ["message", "reasoning"] as const) {+ for (const markup of ["`x`", "[x](https://example.test/report)"]) {+ const stderr = capture(true);+ const dashboard = createDashboard(+ { ...stderr.stream, columns, rows: 60 },+ { color: true },+ );+ dashboard.start();+ dashboard.record({+ id: "clipped-markup",+ worker,+ kind,+ status: "completed",+ description: markup,+ paths: [],+ });+ const frame = stderr.text().split("\u001B[H").at(-1)!;+ expect(frame).toContain(+ markup.startsWith("`")+ ? "\u001B[2mx\u001B[22m"+ : "\u001B]8;;https://example.test/report\u0007x\u001B]8;;\u0007",+ );+ dashboard.stop();+ }+ }+ const stderr = capture(true);+ const input = new DashboardTestInput();+ const dashboard = createDashboard(+ { ...stderr.stream, columns, rows: 60 },+ { color: true, input },+ );+ dashboard.start();+ input.emit("data", "d");+ dashboard.recordDetails({+ threadId: "synthetic-thread",+ parentThreadId: null,+ worker,+ event: {+ type: "event_msg",+ payload: { type: "agent_message", message: "`x`" },+ },+ });+ expect(stderr.text().split("\u001B[H").at(-1)!).toContain(+ "\u001B[2mx\u001B[22m",+ );+ dashboard.stop();+ }+ },+);