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: remove authentication output and instruction limits (#328)
mldangelo-oaib0aeec895160
diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.tsindex d53a42f0f..8c33dc07e 100644--- a/sdk/typescript/src/auth.ts+++ b/sdk/typescript/src/auth.ts@@ -4,12 +4,6 @@ import { PluginBootstrapError } from "./errors.js";import type { CodexCommand, ProcessEnvironment } from "./runtime.js";const LOGIN_CHILD_TERMINATION_GRACE_MS = 1_000;-const MAX_CODEX_AUTH_OUTPUT_BYTES = 64 * 1024;-const LOGIN_OUTPUT_LIMIT_MESSAGE =- "Codex login output exceeded the 64 KiB safety limit.";-const COMMAND_OUTPUT_LIMIT_MESSAGE =- "Codex authentication command output exceeded the 64 KiB safety limit.";-const INSTRUCTION_TAIL_BYTES = 4 * 1024;type TerminalEscapeState = "text" | "escape" | "csi" | "osc" | "osc-escape";export interface LoginResult {@@ -48,7 +42,6 @@ export class CodexLoginHandle {#stderrAuthUrl: string | null = null;#stdoutUserCode: string | null = null;#stderrUserCode: string | null = null;- #outputLimitExceeded = false;public constructor(command: CodexCommand,@@ -90,22 +83,15 @@ export class CodexLoginHandle {this.#clearForcedTermination();this.#forceCompletion = null;this.#destroyPipes();- if (!this.#outputLimitExceeded && !this.#canceled) {+ if (!this.#canceled) {this.#flushInstructionTails();}- const result = this.#outputLimitExceeded- ? {- success: false,- exitCode,- stdout: "",- stderr: LOGIN_OUTPUT_LIMIT_MESSAGE,- }- : {- success: exitCode === 0 && !this.#canceled,- exitCode,- stdout: this.#stdout,- stderr: this.#stderr,- };+ const result = {+ success: exitCode === 0 && !this.#canceled,+ exitCode,+ stdout: this.#stdout,+ stderr: this.#stderr,+ };this.#settleInstructionWaiters(result);if (result.success) onSuccess();resolve(result);@@ -202,24 +188,10 @@ export class CodexLoginHandle {}#recordOutput(stream: "stdout" | "stderr", chunk: string): void {- if (this.#outputLimitExceeded) return;- const current = stream === "stdout" ? this.#stdout : this.#stderr;- const appended = appendUtf8Tail(- current,- chunk,- MAX_CODEX_AUTH_OUTPUT_BYTES,- );if (stream === "stdout") {- this.#stdout = appended.value;+ this.#stdout += chunk;} else {- this.#stderr = appended.value;- }- if (appended.exceeded) {- this.#outputLimitExceeded = true;- this.#stdout = "";- this.#stderr = LOGIN_OUTPUT_LIMIT_MESSAGE;- this.#requestTermination();- return;+ this.#stderr += chunk;}const tail =@@ -232,19 +204,17 @@ export class CodexLoginHandle {? this.#stdoutTerminalState: this.#stderrTerminalState,);- const candidate = `${tail}${visible.text}`;- const lastDelimiter = Math.max(- candidate.lastIndexOf("\n"),- candidate.lastIndexOf("\r"),- );- const completed = candidate.slice(0, lastDelimiter + 1);+ const lastDelimiter = visible.text.lastIndexOf("\n");+ const completed =+ lastDelimiter === -1+ ? ""+ : `${tail}${visible.text.slice(0, lastDelimiter + 1)}`;const url = preferredAuthUrl(completed);const userCode = userCodeFromOutput(completed);- const nextTail = appendUtf8Tail(- "",- candidate.slice(lastDelimiter + 1),- INSTRUCTION_TAIL_BYTES,- ).value;+ const nextTail =+ lastDelimiter === -1+ ? `${tail}${visible.text}`+ : visible.text.slice(lastDelimiter + 1);if (stream === "stdout") {this.#stdoutAuthUrl ??= url;this.#stdoutUserCode ??= userCode;@@ -405,28 +375,13 @@ export async function runCodex(child.stderr.destroy();}, LOGIN_CHILD_TERMINATION_GRACE_MS);};- const recordOutput = (stream: "stdout" | "stderr", chunk: string): void => {- if (processError !== null) return;- const appended = appendUtf8Tail(- stream === "stdout" ? stdout : stderr,- chunk,- MAX_CODEX_AUTH_OUTPUT_BYTES,- );- if (stream === "stdout") stdout = appended.value;- else stderr = appended.value;- if (!appended.exceeded) return;- stdout = "";- stderr = "";- processError = new PluginBootstrapError(COMMAND_OUTPUT_LIMIT_MESSAGE);- terminate();- };child.stdout.setEncoding("utf8");child.stderr.setEncoding("utf8");child.stdout.on("data", (chunk: string) => {- recordOutput("stdout", chunk);+ stdout += chunk;});child.stderr.on("data", (chunk: string) => {- recordOutput("stderr", chunk);+ stderr += chunk;});const completion = new Promise<LoginResult>((resolve, reject) => {child.once("error", (error) => {@@ -495,30 +450,6 @@ function userCodeFromOutput(value: string): string | null {);}-function appendUtf8Tail(- current: string,- chunk: string,- maximumBytes: number,-): { value: string; exceeded: boolean } {- const currentBytes = Buffer.from(current);- const chunkBytes = Buffer.from(chunk);- const exceeded = currentBytes.length + chunkBytes.length > maximumBytes;- if (!exceeded) return { value: `${current}${chunk}`, exceeded: false };- if (chunkBytes.length >= maximumBytes) {- return {- value: chunkBytes.subarray(chunkBytes.length - maximumBytes).toString(),- exceeded: true,- };- }- const retained = currentBytes.subarray(- Math.max(0, currentBytes.length - (maximumBytes - chunkBytes.length)),- );- return {- value: Buffer.concat([retained, chunkBytes]).toString(),- exceeded: true,- };-}-function plainTerminalText(value: string): string {return value.replace(/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g, "")diff --git a/sdk/typescript/tests-ts/auth.test.ts b/sdk/typescript/tests-ts/auth.test.tsindex fca13e135..b7d1f396e 100644--- a/sdk/typescript/tests-ts/auth.test.ts+++ b/sdk/typescript/tests-ts/auth.test.ts@@ -100,64 +100,26 @@ describe("Codex authentication process boundary", () => {).resolves.toMatchObject({ success: false, exitCode: 1 });});- test("rejects oversized noninteractive authentication output", async () => {+ test("retains large noninteractive authentication output", async () => {const root = await mkdtemp(join(tmpdir(), "codex-security-auth-output-"));temporaryDirectories.push(root);- const secret = "sk-proj-SYNTHETIC_OVERSIZED_OUTPUT_SECRET";+ const output = "verbose authentication output ".repeat(3_000);for (const stream of ["stdout", "stderr"] as const) {const script = join(root, `${stream}.mjs`);await writeFile(script,- `process.${stream}.write(${JSON.stringify(secret)}.repeat(3_000), () => process.exit(0));\n`,+ `process.${stream}.write(${JSON.stringify(output)}, () => process.exit(0));\n`,);- const failure = await runCodex(+ const result = await runCodex({ command: process.execPath, prefixArgs: [script] },[],process.env,- ).then(- () => null,- (error: unknown) => error,);- expect(failure).toBeInstanceOf(PluginBootstrapError);- expect(String(failure)).toContain("64 KiB safety limit");- expect(String(failure)).not.toContain(secret);+ expect(result.success).toBe(true);+ expect(result[stream]).toBe(output);}});- test("forces oversized noninteractive authentication to terminate", async () => {- const root = await mkdtemp(- join(tmpdir(), "codex-security-auth-command-kill-"),- );- temporaryDirectories.push(root);- const script = join(root, "command.mjs");- await writeFile(- script,- `-process.on("SIGTERM", () => {});-process.stderr.write("x".repeat(128 * 1024));-setInterval(() => {}, 1000);-`,- );- const timeout = AbortSignal.timeout(2_500);-- await expect(- Promise.race([- runCodex(- { command: process.execPath, prefixArgs: [script] },- [],- process.env,- ),- new Promise<never>((_, reject) => {- timeout.addEventListener(- "abort",- () => reject(new Error("Oversized authentication did not settle.")),- { once: true },- );- }),- ]),- ).rejects.toThrow("64 KiB safety limit");- });-test("reports account state and performs logout", async () => {const command = await fakeCodex();await expect(accountStatus(command, process.env)).resolves.toMatchObject({@@ -185,18 +147,18 @@ setInterval(() => {}, 1000);expect(succeeded).toBe(true);});- test("bounds interactive output while retaining discovered instructions", async () => {+ test("retains large interactive output and login instructions", async () => {const root = await mkdtemp(join(tmpdir(), "codex-security-auth-output-"));temporaryDirectories.push(root);const script = join(root, "login.mjs");- const secret = "sk-proj-SYNTHETIC_INTERACTIVE_OUTPUT_SECRET";+ const output = "verbose authentication output ".repeat(3_000);await writeFile(script,`console.error("Open https://auth.example.test/device");console.error("User code: ABCD-EFGH");setTimeout(() => {- process.stderr.write(${JSON.stringify(secret)}.repeat(3_000), () => process.exit(0));+ process.stderr.write(${JSON.stringify(output)}, () => process.exit(0));}, 10);`,);@@ -214,13 +176,9 @@ setTimeout(() => {expect(handle.verificationUrl).toBe("https://auth.example.test/device");expect(handle.userCode).toBe("ABCD-EFGH");const result = await handle.wait();- expect(result).toMatchObject({- success: false,- stdout: "",- stderr: "Codex login output exceeded the 64 KiB safety limit.",- });- expect(JSON.stringify(result)).not.toContain(secret);- expect(succeeded).toBe(false);+ expect(result).toMatchObject({ success: true, exitCode: 0, stdout: "" });+ expect(result.stderr).toContain(output);+ expect(succeeded).toBe(true);});test("ignores authentication instructions hidden in a split terminal escape", async () => {@@ -300,44 +258,13 @@ setTimeout(() => {await expect(handle.wait()).resolves.toMatchObject({ success: true });});- test("rejects instruction waiters when an unfinished login exceeds its output bound", async () => {+ test("preserves login instructions on long output lines", async () => {const root = await mkdtemp(join(tmpdir(), "codex-security-auth-tail-"));temporaryDirectories.push(root);const script = join(root, "login.mjs");await writeFile(script,- 'process.stderr.write("Open https://auth.example.test/device"); setTimeout(() => process.stderr.write("x".repeat(128 * 1024)), 20);\n',- );- const handle = new CodexLoginHandle(- { command: process.execPath, prefixArgs: [script] },- ["login"],- process.env,- () => {},- );-- await expect(handle.waitForInstructions()).rejects.toThrow(- "64 KiB safety limit",- );- await expect(handle.wait()).resolves.toMatchObject({ success: false });- });-- test("forces an oversized login to settle when it ignores termination", async () => {- const root = await mkdtemp(- join(tmpdir(), "codex-security-auth-output-kill-"),- );- temporaryDirectories.push(root);- const script = join(root, "login.mjs");- await writeFile(- script,- `-console.error("Open https://auth.example.test/device");-console.error("User code: ABCD-EFGH");-process.on("SIGTERM", () => {});-setTimeout(() => {- process.stderr.write("x".repeat(128 * 1024));- setInterval(() => {}, 1000);-}, 10);-`,+ 'process.stderr.write("Open https://auth.example.test/device " + "x".repeat(128 * 1024), () => process.stderr.write("\\nUser code: ABCD-EFGH\\n", () => process.exit(0)));\n',);const handle = new CodexLoginHandle({ command: process.execPath, prefixArgs: [script] },@@ -346,27 +273,10 @@ setTimeout(() => {() => {},);- try {- await handle.waitForInstructions({ deviceCode: true });- const timeout = AbortSignal.timeout(2_500);- const result = await Promise.race([- handle.wait(),- new Promise<never>((_, reject) => {- timeout.addEventListener(- "abort",- () => reject(new Error("Oversized login did not settle.")),- { once: true },- );- }),- ]);- expect(result).toMatchObject({- success: false,- stderr: "Codex login output exceeded the 64 KiB safety limit.",- });- } finally {- handle.cancel();- await handle.wait();- }+ await handle.waitForInstructions({ deviceCode: true });+ expect(handle.verificationUrl).toBe("https://auth.example.test/device");+ expect(handle.userCode).toBe("ABCD-EFGH");+ await expect(handle.wait()).resolves.toMatchObject({ success: true });});test("drains native login stderr before resolving authentication", async () => {