Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(auth): use a credential-only Codex runtime (#363)

ianw-oaif22f995ee4d1
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 4bb081bee..74c8d3f32 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -1277,80 +1277,51 @@ export class CodexSecurity {
}
public async loginApiKey(apiKey: string): Promise<void> {
- const { result, runtime } = await this.#runOperation(
- async (preparedRuntime, signal) => ({
- runtime: preparedRuntime,
- result: await persistApiKey(
- this.#codexCommand(),
- preparedRuntime.environment,
- apiKey,
- signal,
- ),
- }),
- "chatgpt",
- );
- if (!result.success) {
- throw new CodexSecurityError(
- `Codex API-key login failed: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`,
+ await this.#trackOperation(async () => {
+ const authentication = await this.#authentication();
+ this.#requireOpen();
+ const result = await persistApiKey(
+ this.#codexCommand(),
+ authentication.environment,
+ apiKey,
+ this.#abortController.signal,
);
- }
- if (runtime.persistentCredentialHome === true) {
- await setCodexSecurityCredentialLogout(runtime.codexHome, false);
- }
- runtime.credentialsAvailable = true;
- this.#runtimeCredentialSource = "api_key";
+ if (!result.success) {
+ throw new CodexSecurityError(
+ `Codex API-key login failed: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`,
+ );
+ }
+ await this.#recordLogin(authentication.codexHome, "api_key");
+ this.#requireOpen();
+ });
}
public async loginChatGPT(): Promise<CodexLoginHandle> {
- const runtime = await this.#ensureRuntime(
- undefined,
- undefined,
- undefined,
- "chatgpt",
- );
- this.#requireOpen();
- const handle = this.#trackLoginHandle(
- new CodexLoginHandle(
- this.#codexCommand(),
- ["login"],
- runtime.environment,
- () => {
- runtime.credentialsAvailable = true;
- this.#runtimeCredentialSource = "stored_credentials";
- },
- ),
- );
- await handle.waitForInstructions();
- this.#requireOpen();
- return handle;
+ return await this.#startLogin(false);
}
public async loginChatGPTDeviceCode(): Promise<CodexLoginHandle> {
- const runtime = await this.#ensureRuntime(
- undefined,
- undefined,
- undefined,
- "chatgpt",
- );
+ return await this.#startLogin(true);
+ }
+
+ async #startLogin(deviceCode: boolean): Promise<CodexLoginHandle> {
+ const authentication = await this.#authentication();
this.#requireOpen();
const handle = this.#trackLoginHandle(
new CodexLoginHandle(
this.#codexCommand(),
- ["login", "--device-auth"],
- runtime.environment,
- () => {
- runtime.credentialsAvailable = true;
- this.#runtimeCredentialSource = "stored_credentials";
- },
+ deviceCode ? ["login", "--device-auth"] : ["login"],
+ authentication.environment,
+ () => this.#recordLogin(authentication.codexHome, "stored_credentials"),
),
);
- await handle.waitForInstructions({ deviceCode: true });
+ await handle.waitForInstructions({ deviceCode });
this.#requireOpen();
return handle;
}
public async account(): Promise<AccountStatus> {
- return await this.#runOperation(async (runtime, signal) => {
+ return await this.#trackOperation(async () => {
const apiKey = environmentApiKey(this.#dependencies.environment);
if (apiKey !== null) {
return {
@@ -1358,31 +1329,35 @@ export class CodexSecurity {
details: "Authenticated with an API key.",
};
}
+ const authentication = await this.#authentication();
+ this.#requireOpen();
return await accountStatus(
this.#codexCommand(),
- runtime.environment,
- signal,
+ authentication.environment,
+ this.#abortController.signal,
);
});
}
public async logout(): Promise<void> {
- const runtime = await this.#runOperation(
- async (preparedRuntime, signal) => {
- await codexLogout(
- this.#codexCommand(),
- preparedRuntime.environment,
- signal,
- );
- return preparedRuntime;
- },
- "chatgpt",
- );
- if (runtime.persistentCredentialHome === true) {
- await setCodexSecurityCredentialLogout(runtime.codexHome, true);
- }
- runtime.credentialsAvailable = false;
- this.#runtimeCredentialSource = null;
+ await this.#trackOperation(async () => {
+ const authentication = await this.#authentication();
+ this.#requireOpen();
+ await codexLogout(
+ this.#codexCommand(),
+ authentication.environment,
+ this.#abortController.signal,
+ );
+ if (
+ this.#runtime === null ||
+ this.#runtime.persistentCredentialHome === true
+ ) {
+ await setCodexSecurityCredentialLogout(authentication.codexHome, true);
+ }
+ if (this.#runtime !== null) this.#runtime.credentialsAvailable = false;
+ this.#runtimeCredentialSource = null;
+ this.#requireOpen();
+ });
}
public async close(): Promise<void> {
@@ -1435,23 +1410,39 @@ export class CodexSecurity {
await this.close();
}
- async #runOperation<T>(
- operation: (runtime: PreparedRuntime, signal: AbortSignal) => Promise<T>,
- auth: ScanAuthMode = "auto",
- ): Promise<T> {
- return await this.#trackOperation(async () => {
- const signal = this.#abortController.signal;
- const runtime = await this.#ensureRuntime(
- signal,
- undefined,
- undefined,
- auth,
- );
- this.#requireOpen();
- const result = await operation(runtime, signal);
- this.#requireOpen();
- return result;
- });
+ async #authentication(): Promise<{
+ codexHome: string;
+ environment: Record<string, string>;
+ }> {
+ this.#requireOpen();
+ const environment = selectedScanEnvironment(
+ this.#runtime?.environment ?? this.#dependencies.environment,
+ "chatgpt",
+ );
+ const codexHome =
+ this.#runtime?.codexHome ??
+ (await prepareCodexSecurityCredentialHome(environment));
+ return {
+ codexHome,
+ environment: {
+ ...withoutCodexHome(environment),
+ CODEX_HOME: codexHome,
+ },
+ };
+ }
+
+ async #recordLogin(
+ codexHome: string,
+ source: "api_key" | "stored_credentials",
+ ): Promise<void> {
+ if (
+ this.#runtime === null ||
+ this.#runtime.persistentCredentialHome === true
+ ) {
+ await setCodexSecurityCredentialLogout(codexHome, false);
+ }
+ if (this.#runtime !== null) this.#runtime.credentialsAvailable = true;
+ this.#runtimeCredentialSource = source;
}
async #trackOperation<T>(operation: () => Promise<T>): Promise<T> {
diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.ts
index 8c33dc07e..aa3c3a6b6 100644
--- a/sdk/typescript/src/auth.ts
+++ b/sdk/typescript/src/auth.ts
@@ -4,7 +4,6 @@ import { PluginBootstrapError } from "./errors.js";
import type { CodexCommand, ProcessEnvironment } from "./runtime.js";
const LOGIN_CHILD_TERMINATION_GRACE_MS = 1_000;
-type TerminalEscapeState = "text" | "escape" | "csi" | "osc" | "osc-escape";
export interface LoginResult {
success: boolean;
@@ -21,44 +20,29 @@ export interface AccountStatus {
export class CodexLoginHandle {
readonly #child: ChildProcessWithoutNullStreams;
readonly #completion: Promise<LoginResult>;
- readonly #urlReady: Promise<void>;
- readonly #deviceReady: Promise<void>;
- #resolveUrlReady!: () => void;
- #rejectUrlReady!: (error: unknown) => void;
- #resolveDeviceReady!: () => void;
- #rejectDeviceReady!: (error: unknown) => void;
- #urlReadySettled = false;
- #deviceReadySettled = false;
+ readonly #urlReady = Promise.withResolvers<void>();
+ readonly #deviceReady = Promise.withResolvers<void>();
#canceled = false;
#forcedTermination: ReturnType<typeof setTimeout> | undefined;
- #forceCompletion: (() => void) | null = null;
- #stdout = "";
- #stderr = "";
- #stdoutInstructionTail = "";
- #stderrInstructionTail = "";
- #stdoutTerminalState: TerminalEscapeState = "text";
- #stderrTerminalState: TerminalEscapeState = "text";
- #stdoutAuthUrl: string | null = null;
- #stderrAuthUrl: string | null = null;
- #stdoutUserCode: string | null = null;
- #stderrUserCode: string | null = null;
+ readonly #output = { stdout: "", stderr: "" };
+ readonly #tails = { stdout: "", stderr: "" };
+ readonly #urls: Record<"stdout" | "stderr", string | null> = {
+ stdout: null,
+ stderr: null,
+ };
+ readonly #codes: Record<"stdout" | "stderr", string | null> = {
+ stdout: null,
+ stderr: null,
+ };
public constructor(
command: CodexCommand,
args: readonly string[],
environment: ProcessEnvironment,
- onSuccess: () => void,
+ onSuccess: () => void | Promise<void>,
) {
- this.#urlReady = new Promise<void>((resolve, reject) => {
- this.#resolveUrlReady = resolve;
- this.#rejectUrlReady = reject;
- });
- this.#deviceReady = new Promise<void>((resolve, reject) => {
- this.#resolveDeviceReady = resolve;
- this.#rejectDeviceReady = reject;
- });
- void this.#urlReady.catch(() => undefined);
- void this.#deviceReady.catch(() => undefined);
+ void this.#urlReady.promise.catch(() => undefined);
+ void this.#deviceReady.promise.catch(() => undefined);
this.#child = spawn(command.command, [...command.prefixArgs, ...args], {
env: environment,
stdio: ["pipe", "pipe", "pipe"],
@@ -74,51 +58,33 @@ export class CodexLoginHandle {
this.#recordOutput("stderr", chunk);
});
this.#completion = new Promise((resolve, reject) => {
- let fallback: ReturnType<typeof setTimeout> | undefined;
- let completed = false;
- const complete = (exitCode: number | null): void => {
- if (completed) return;
- completed = true;
- if (fallback !== undefined) clearTimeout(fallback);
- this.#clearForcedTermination();
- this.#forceCompletion = null;
- this.#destroyPipes();
+ this.#child.once("close", (exitCode) => {
+ clearTimeout(this.#forcedTermination);
if (!this.#canceled) {
this.#flushInstructionTails();
}
const result = {
success: exitCode === 0 && !this.#canceled,
exitCode,
- stdout: this.#stdout,
- stderr: this.#stderr,
+ ...this.#output,
};
this.#settleInstructionWaiters(result);
- if (result.success) onSuccess();
- resolve(result);
- };
- this.#forceCompletion = () => complete(this.#child.exitCode);
+ if (result.success) {
+ Promise.resolve(onSuccess()).then(() => resolve(result), reject);
+ } else {
+ resolve(result);
+ }
+ });
this.#child.once("error", (error) => {
- if (completed) return;
- completed = true;
- if (fallback !== undefined) clearTimeout(fallback);
- this.#clearForcedTermination();
- this.#forceCompletion = null;
- this.#destroyPipes();
+ clearTimeout(this.#forcedTermination);
this.#settleInstructionWaiters({
success: false,
exitCode: null,
- stdout: this.#stdout,
+ stdout: this.#output.stdout,
stderr: error.message,
});
reject(error);
});
- this.#child.once("close", complete);
- this.#child.once("exit", (exitCode) => {
- fallback = setTimeout(() => {
- this.#destroyPipes();
- complete(exitCode);
- }, LOGIN_CHILD_TERMINATION_GRACE_MS);
- });
});
}
@@ -127,7 +93,7 @@ export class CodexLoginHandle {
}
public get authUrl(): string | null {
- return this.#stdoutAuthUrl ?? this.#stderrAuthUrl;
+ return this.#urls.stdout ?? this.#urls.stderr;
}
public get verificationUrl(): string | null {
@@ -135,7 +101,7 @@ export class CodexLoginHandle {
}
public get userCode(): string | null {
- return this.#stdoutUserCode ?? this.#stderrUserCode;
+ return this.#codes.stdout ?? this.#codes.stderr;
}
public async wait(): Promise<LoginResult> {
@@ -145,123 +111,57 @@ export class CodexLoginHandle {
public async waitForInstructions(
options: { deviceCode?: boolean } = {},
): Promise<void> {
- await (options.deviceCode === true ? this.#deviceReady : this.#urlReady);
+ await (options.deviceCode === true ? this.#deviceReady : this.#urlReady)
+ .promise;
}
public cancel(): void {
this.#canceled = true;
- this.#requestTermination();
- }
-
- #requestTermination(): void {
- if (
- this.#child.exitCode !== null ||
- this.#child.signalCode !== null ||
- this.#forceCompletion === null
- ) {
- this.#destroyPipes();
- this.#forceCompletion?.();
+ if (this.#child.exitCode !== null || this.#child.signalCode !== null)
return;
- }
this.#child.kill("SIGTERM");
if (this.#forcedTermination !== undefined) return;
this.#forcedTermination = setTimeout(() => {
- this.#forcedTermination = undefined;
if (this.#child.exitCode === null && this.#child.signalCode === null) {
this.#child.kill("SIGKILL");
}
- this.#destroyPipes();
- this.#forceCompletion?.();
+ this.#child.stdin.destroy();
+ this.#child.stdout.destroy();
+ this.#child.stderr.destroy();
}, LOGIN_CHILD_TERMINATION_GRACE_MS);
}
- #clearForcedTermination(): void {
- if (this.#forcedTermination === undefined) return;
- clearTimeout(this.#forcedTermination);
- this.#forcedTermination = undefined;
- }
-
- #destroyPipes(): void {
- this.#child.stdin.destroy();
- this.#child.stdout.destroy();
- this.#child.stderr.destroy();
- }
-
#recordOutput(stream: "stdout" | "stderr", chunk: string): void {
- if (stream === "stdout") {
- this.#stdout += chunk;
- } else {
- this.#stderr += chunk;
- }
-
- const tail =
- stream === "stdout"
- ? this.#stdoutInstructionTail
- : this.#stderrInstructionTail;
- const visible = visibleTerminalChunk(
- chunk,
- stream === "stdout"
- ? this.#stdoutTerminalState
- : this.#stderrTerminalState,
- );
- const lastDelimiter = visible.text.lastIndexOf("\n");
+ this.#output[stream] += chunk;
+ const output = `${this.#tails[stream]}${chunk.replaceAll("\r", "\n")}`;
+ const lastDelimiter = output.lastIndexOf("\n");
const completed =
- lastDelimiter === -1
- ? ""
- : `${tail}${visible.text.slice(0, lastDelimiter + 1)}`;
- const url = preferredAuthUrl(completed);
- const userCode = userCodeFromOutput(completed);
- const nextTail =
- lastDelimiter === -1
- ? `${tail}${visible.text}`
- : visible.text.slice(lastDelimiter + 1);
- if (stream === "stdout") {
- this.#stdoutAuthUrl ??= url;
- this.#stdoutUserCode ??= userCode;
- this.#stdoutInstructionTail = nextTail;
- this.#stdoutTerminalState = visible.state;
- } else {
- this.#stderrAuthUrl ??= url;
- this.#stderrUserCode ??= userCode;
- this.#stderrInstructionTail = nextTail;
- this.#stderrTerminalState = visible.state;
- }
+ lastDelimiter === -1 ? "" : output.slice(0, lastDelimiter + 1);
+ this.#urls[stream] ??= preferredAuthUrl(completed);
+ this.#codes[stream] ??= userCodeFromOutput(completed);
+ this.#tails[stream] =
+ lastDelimiter === -1 ? output : output.slice(lastDelimiter + 1);
this.#notifyInstructions();
}
#flushInstructionTails(): void {
- this.#stdoutAuthUrl ??= preferredAuthUrl(this.#stdoutInstructionTail);
- this.#stdoutUserCode ??= userCodeFromOutput(this.#stdoutInstructionTail);
- this.#stderrAuthUrl ??= preferredAuthUrl(this.#stderrInstructionTail);
- this.#stderrUserCode ??= userCodeFromOutput(this.#stderrInstructionTail);
+ for (const stream of ["stdout", "stderr"] as const) {
+ this.#urls[stream] ??= preferredAuthUrl(this.#tails[stream]);
+ this.#codes[stream] ??= userCodeFromOutput(this.#tails[stream]);
+ }
}
#notifyInstructions(): void {
- if (!this.#urlReadySettled && this.authUrl !== null) {
- this.#urlReadySettled = true;
- this.#resolveUrlReady();
- }
- if (
- !this.#deviceReadySettled &&
- this.verificationUrl !== null &&
- this.userCode !== null
- ) {
- this.#deviceReadySettled = true;
- this.#resolveDeviceReady();
- }
+ if (this.authUrl !== null) this.#urlReady.resolve();
+ if (this.verificationUrl !== null && this.userCode !== null)
+ this.#deviceReady.resolve();
}
#settleInstructionWaiters(result: LoginResult): void {
this.#notifyInstructions();
if (result.success) {
- if (!this.#urlReadySettled) {
- this.#urlReadySettled = true;
- this.#resolveUrlReady();
- }
- if (!this.#deviceReadySettled) {
- this.#deviceReadySettled = true;
- this.#resolveDeviceReady();
- }
+ this.#urlReady.resolve();
+ this.#deviceReady.resolve();
return;
}
const error = new PluginBootstrapError(
@@ -269,14 +169,8 @@ export class CodexLoginHandle {
? "Codex login was canceled."
: `Codex login exited before authentication instructions were available: ${result.stderr.trim() || result.stdout.trim() || result.exitCode || "unknown error"}`,
);
- if (!this.#urlReadySettled) {
- this.#urlReadySettled = true;
- this.#rejectUrlReady(error);
- }
- if (!this.#deviceReadySettled) {
- this.#deviceReadySettled = true;
- this.#rejectDeviceReady(error);
- }
+ this.#urlReady.reject(error);
+ this.#deviceReady.reject(error);
}
}
@@ -456,44 +350,3 @@ function plainTerminalText(value: string): string {
.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "")
.replace(/\r/g, "");
}
-
-function visibleTerminalChunk(
- value: string,
- initialState: TerminalEscapeState,
-): { text: string; state: TerminalEscapeState } {
- let state = initialState;
- let text = "";
- for (const character of value) {
- if (state === "text") {
- if (character === "\u001b") {
- state = "escape";
- } else {
- text += character === "\r" ? "\n" : character;
- }
- continue;
- }
- if (state === "escape") {
- if (character === "[") {
- state = "csi";
- } else if (character === "]") {
- state = "osc";
- } else {
- text += `\u001b${character}`;
- state = "text";
- }
- continue;
- }
- if (state === "csi") {
- if (character >= "@" && character <= "~") state = "text";
- continue;
- }
- if (state === "osc") {
- if (character === "\u0007") state = "text";
- else if (character === "\u001b") state = "osc-escape";
- continue;
- }
- if (character === "\\" || character === "\u0007") state = "text";
- else if (character !== "\u001b") state = "osc";
- }
- return { text, state };
-}
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 03b373afd..7e1a483ee 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -4844,6 +4844,39 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
+ test("authenticates without initializing the plugin runtime", async () => {
+ const root = await temporaryDirectory();
+ const stateDirectory = join(root, "state");
+ const codexHome = join(stateDirectory, "codex-home");
+ const fakeCodex = join(root, "codex.mjs");
+ await writeFile(fakeCodex, "process.exitCode = 1;\n");
+ const client = new TestClient(
+ { pluginPath: join(root, "missing-plugin") },
+ {
+ environment: { CODEX_SECURITY_STATE_DIR: stateDirectory },
+ prepareRuntime: async () => {
+ throw new Error("authentication must not initialize the plugin");
+ },
+ resolveCodexCommand: () => ({
+ command: process.execPath,
+ prefixArgs: [fakeCodex],
+ }),
+ },
+ );
+
+ try {
+ await expect(client.account()).resolves.toMatchObject({
+ authenticated: false,
+ });
+ expect(existsSync(join(codexHome, "config.toml"))).toBe(false);
+ expect(existsSync(join(codexHome, "sdk-marketplace"))).toBe(false);
+ } finally {
+ await client.close();
+ }
+
+ expect(existsSync(codexHome)).toBe(true);
+ });
+
test("passes environment API keys transiently without native login or keyring persistence", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
@@ -5571,23 +5604,31 @@ if (process.argv.slice(2).join(" ") !== "login status") {
test("cleans the bootstrap workspace when credential-home cleanup fails", async () => {
const root = await temporaryDirectory();
+ const repository = join(root, "repository");
const codexHome = join(root, "codex-home");
const bootstrapWorkspace = join(root, "bootstrap-workspace");
+ await mkdir(repository);
await mkdir(codexHome);
await mkdir(bootstrapWorkspace);
const client = new TestClient(
{},
{
- environment: { OPENAI_API_KEY: "ambient-key" },
+ environment: {
+ CODEX_SECURITY_STATE_DIR: root,
+ OPENAI_API_KEY: "ambient-key",
+ },
prepareRuntime: async () => ({
...preparedRuntime(codexHome),
bootstrapWorkspace,
}),
+ resolvePluginPython: async () => "/managed/python",
+ repositoryRevision: async () => null,
+ createCodex: () => {
+ throw new Error("scan reached");
+ },
},
);
- await expect(client.account()).resolves.toMatchObject({
- authenticated: true,
- });
+ await expect(client.run(repository)).rejects.toThrow("scan reached");
const originalRm = fsPromises.rm;
const attempted: string[] = [];
mock.module("node:fs/promises", () => ({
@@ -5682,7 +5723,7 @@ if (process.argv.slice(2).join(" ") !== "login status") {
const root = await temporaryDirectory();
const codexHome = join(root, "codex-home");
const fakeCodex = join(root, "codex.mjs");
- await mkdir(codexHome);
+ await mkdir(codexHome, { mode: 0o700 });
await writeFile(
fakeCodex,
'console.error("Open https://auth.example.test/device");\nconsole.error("User code: ABCD-EFGH");\nprocess.on("SIGTERM", () => {});\nsetInterval(() => {}, 1000);\n',
@@ -5690,7 +5731,7 @@ if (process.argv.slice(2).join(" ") !== "login status") {
const client = new TestClient(
{},
{
- environment: {},
+ environment: { CODEX_SECURITY_STATE_DIR: root },
prepareRuntime: async () => ({
codexHome,
plugin: {
@@ -5732,43 +5773,22 @@ if (process.argv.slice(2).join(" ") !== "login status") {
await expect(login.wait()).resolves.toMatchObject({ success: false });
});
- test("keeps ambient credentials available after successful ChatGPT login", async () => {
+ test("keeps ambient credentials available to scans", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
const codexHome = join(root, "codex-home");
- const fakeCodex = join(root, "codex.mjs");
- const keyLog = join(root, "api-keys");
const scanDir = join(root, "scan");
await mkdir(repository);
- await mkdir(codexHome);
+ await mkdir(codexHome, { mode: 0o700 });
await mkdir(scanDir, { mode: 0o700 });
- await writeFile(
- fakeCodex,
- `
-import { appendFileSync, writeSync } from "node:fs";
-
-const args = process.argv.slice(2).join(" ");
-if (args === "login --with-api-key") {
- let apiKey = "";
- for await (const chunk of process.stdin) apiKey += chunk;
- if (!["secret-key", "ambient-key"].includes(apiKey.trim())) {
- process.exitCode = 3;
- } else {
- appendFileSync(${JSON.stringify(keyLog)}, apiKey);
- }
-} else if (args === "login") {
- writeSync(2, "Open https://auth.example.test/login\\n");
- process.exit(0);
-} else {
- process.exitCode = 2;
-}
-`,
- );
let codexOptions: CodexOptions | null = null;
const client = new TestClient(
{},
{
- environment: { OPENAI_API_KEY: "ambient-key" },
+ environment: {
+ CODEX_SECURITY_STATE_DIR: root,
+ OPENAI_API_KEY: "ambient-key",
+ },
prepareRuntime: async () => ({
codexHome,
plugin: {
@@ -5787,10 +5807,6 @@ if (args === "login --with-api-key") {
},
credentialsAvailable: false,
}),
- resolveCodexCommand: () => ({
- command: "node",
- prefixArgs: [fakeCodex],
- }),
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
@@ -5809,9 +5825,6 @@ if (args === "login --with-api-key") {
},
);
try {
- await client.loginApiKey("secret-key");
- const login = await client.loginChatGPT();
- await expect(login.wait()).resolves.toMatchObject({ success: true });
await client.run(repository);
expect((codexOptions as CodexOptions | null)?.apiKey).toBe("ambient-key");
expect(
@@ -5820,7 +5833,6 @@ if (args === "login --with-api-key") {
["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()),
),
).toBe(false);
- expect(await readFile(keyLog, "utf8")).toBe("secret-key\n");
} finally {
await client.close();
}
@@ -5831,7 +5843,7 @@ if (args === "login --with-api-key") {
const codexHome = join(root, "codex-home");
const fakeCodex = join(root, "codex.mjs");
const ready = join(root, "ready");
- await mkdir(codexHome);
+ await mkdir(codexHome, { mode: 0o700 });
await writeFile(
fakeCodex,
`
@@ -5848,7 +5860,7 @@ setInterval(() => {}, 1000);
const client = new TestClient(
{},
{
- environment: {},
+ environment: { CODEX_SECURITY_STATE_DIR: root },
prepareRuntime: async () => ({
codexHome,
plugin: {
@@ -5887,6 +5899,6 @@ setInterval(() => {}, 1000);
await expect(login).rejects.toThrow();
await expect(
import("node:fs/promises").then(({ stat }) => stat(codexHome)),
- ).rejects.toThrow();
+ ).resolves.toBeDefined();
});
});
diff --git a/sdk/typescript/tests-ts/auth.test.ts b/sdk/typescript/tests-ts/auth.test.ts
index b7d1f396e..dc622e5e5 100644
--- a/sdk/typescript/tests-ts/auth.test.ts
+++ b/sdk/typescript/tests-ts/auth.test.ts
@@ -1,9 +1,8 @@
-import { ChildProcess } from "node:child_process";
-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
-import { afterEach, describe, expect, spyOn, test } from "bun:test";
+import { afterEach, describe, expect, test } from "bun:test";
import {
accountStatus,
CodexLoginHandle,
@@ -181,104 +180,6 @@ setTimeout(() => {
expect(succeeded).toBe(true);
});
- test("ignores authentication instructions hidden in a split terminal escape", async () => {
- const root = await mkdtemp(join(tmpdir(), "codex-security-auth-escape-"));
- temporaryDirectories.push(root);
- const script = join(root, "login.mjs");
- await writeFile(
- script,
- `
-process.stderr.write("\\u001b]0;" + "x".repeat(5 * 1024));
-setTimeout(() => process.stderr.write("https://hidden.example.test/device"), 10);
-setTimeout(() => {
- process.stderr.write("\\u0007\\nOpen https://auth.example.test/device\\nUser code: SAFE-1234\\n");
- setTimeout(() => process.exit(0), 10);
-}, 20);
-`,
- );
- const handle = new CodexLoginHandle(
- { command: process.execPath, prefixArgs: [script] },
- ["login", "--device-auth"],
- process.env,
- () => {},
- );
-
- await handle.waitForInstructions({ deviceCode: true });
- expect(handle.verificationUrl).toBe("https://auth.example.test/device");
- expect(handle.userCode).toBe("SAFE-1234");
- await expect(handle.wait()).resolves.toMatchObject({ success: true });
- });
-
- test("waits for complete login instructions split across output chunks", async () => {
- const root = await mkdtemp(join(tmpdir(), "codex-security-auth-fragment-"));
- temporaryDirectories.push(root);
- const script = join(root, "login.mjs");
- await writeFile(
- script,
- `
-process.stderr.write("Open https://auth.example");
-setTimeout(() => process.stderr.write(".test/device\\nUser code: ABCD"), 10);
-setTimeout(() => {
- process.stderr.write("-EFGH\\n");
- setTimeout(() => process.exit(0), 10);
-}, 20);
-`,
- );
- const handle = new CodexLoginHandle(
- { command: process.execPath, prefixArgs: [script] },
- ["login", "--device-auth"],
- process.env,
- () => {},
- );
-
- 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("recognizes carriage-return-separated interactive login instructions", async () => {
- const root = await mkdtemp(join(tmpdir(), "codex-security-auth-carriage-"));
- temporaryDirectories.push(root);
- const script = join(root, "login.mjs");
- await writeFile(
- script,
- 'process.stderr.write("Open https://auth.example.test/device\\rUser code: ABCD-EFGH\\r"); setTimeout(() => process.exit(0), 25);\n',
- );
- const handle = new CodexLoginHandle(
- { command: process.execPath, prefixArgs: [script] },
- ["login", "--device-auth"],
- process.env,
- () => {},
- );
-
- 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("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 " + "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] },
- ["login", "--device-auth"],
- process.env,
- () => {},
- );
-
- 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 () => {
const root = await mkdtemp(join(tmpdir(), "codex-security-auth-stderr-"));
temporaryDirectories.push(root);
@@ -388,157 +289,6 @@ grandchild.once("error", (error) => {
},
);
- test("releases native login pipes when the cross-platform fallback fires", async () => {
- const root = await mkdtemp(join(tmpdir(), "codex-security-auth-pipes-"));
- temporaryDirectories.push(root);
- const ready = join(root, "grandchild-ready");
- const release = join(root, "release-grandchild");
- const script = join(root, "login-pipes.mjs");
- const grandchildScript = `
-import { existsSync, writeFileSync } from "node:fs";
-
-const ready = process.argv[1];
-const release = process.argv[2];
-const timeout = setTimeout(() => process.exit(1), 10_000);
-const watcher = setInterval(() => {
- if (!existsSync(release)) return;
- clearInterval(watcher);
- clearTimeout(timeout);
- process.exit(0);
-}, 25);
-writeFileSync(ready, String(process.pid));
-`;
- await writeFile(
- script,
- `
-import { spawn } from "node:child_process";
-import { existsSync } from "node:fs";
-
-const grandchild = spawn(
- process.execPath,
- ["-e", ${JSON.stringify(grandchildScript)}, ${JSON.stringify(ready)}, ${JSON.stringify(release)}],
- {
- stdio: ["ignore", "inherit", "inherit"],
- windowsHide: true,
- detached: true,
- },
-);
-const readyTimeout = setTimeout(() => {
- clearInterval(readyWatcher);
- grandchild.kill();
- console.error("Timed out waiting for the Windows login grandchild.");
- process.exit(1);
-}, 10_000);
-const readyWatcher = setInterval(() => {
- if (!existsSync(${JSON.stringify(ready)})) return;
- clearInterval(readyWatcher);
- clearTimeout(readyTimeout);
- process.stdout.write("ready\\n", (error) => process.exit(error ? 1 : 0));
-}, 25);
-grandchild.once("error", (error) => {
- clearInterval(readyWatcher);
- clearTimeout(readyTimeout);
- console.error(error.message);
- process.exit(1);
-});
-`,
- );
-
- const originalOnce = ChildProcess.prototype.once;
- let loginChild: ChildProcess | undefined;
- const processObserver = spyOn(ChildProcess.prototype, "once");
- processObserver.mockImplementation(function (
- this: ChildProcess,
- event: string,
- listener: (...eventArguments: never[]) => void,
- ) {
- if (event === "exit") loginChild = this;
- return Reflect.apply(originalOnce, this, [event, listener]);
- });
-
- let handle: CodexLoginHandle;
- try {
- handle = new CodexLoginHandle(
- { command: process.execPath, prefixArgs: [script] },
- ["login"],
- process.env,
- () => {},
- );
- } finally {
- processObserver.mockRestore();
- }
-
- const readMarker = async (path: string): Promise<string> => {
- const deadline = Date.now() + 5_000;
- while (true) {
- try {
- return await readFile(path, "utf8");
- } catch (error) {
- if (
- !(error instanceof Error) ||
- !("code" in error) ||
- error.code !== "ENOENT" ||
- Date.now() >= deadline
- ) {
- throw error;
- }
- await delay(25);
- }
- }
- };
-
- let grandchildPid: number | undefined;
- try {
- const readyMarker = await readMarker(ready);
- expect(readyMarker).toMatch(/^\d+$/u);
- grandchildPid = Number(readyMarker);
- expect(Number.isSafeInteger(grandchildPid)).toBe(true);
- expect(grandchildPid).toBeGreaterThan(0);
- const timeout = AbortSignal.timeout(5_000);
- const completion = Promise.race([
- handle.wait(),
- new Promise<never>((_, reject) => {
- timeout.addEventListener(
- "abort",
- () => reject(new Error("The login fallback timed out.")),
- { once: true },
- );
- }),
- ]);
- await expect(completion).resolves.toMatchObject({
- success: true,
- exitCode: 0,
- });
- expect(loginChild?.stdout?.destroyed).toBe(true);
- expect(loginChild?.stderr?.destroyed).toBe(true);
- } finally {
- await writeFile(release, "released");
- if (grandchildPid !== undefined) {
- const deadline = Date.now() + 5_000;
- while (true) {
- try {
- process.kill(grandchildPid, 0);
- } catch (error) {
- if (
- error instanceof Error &&
- "code" in error &&
- error.code === "ESRCH"
- ) {
- break;
- }
- throw error;
- }
- if (Date.now() >= deadline) {
- throw new Error(
- "The login grandchild did not exit after pipe cleanup.",
- );
- }
- await delay(25);
- }
- }
- }
- });
-
test("escalates cancellation when a login child ignores SIGTERM", async () => {
const root = await mkdtemp(join(tmpdir(), "codex-security-auth-sigkill-"));
temporaryDirectories.push(root);