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: preserve Continuum import retries and active sign-in credentials (#2531)

Michael D'Angelo6871181ef9da
diff --git a/docs/scanner-imports/README.md b/docs/scanner-imports/README.md
index 5a87c2e58..b1f7acb9e 100644
--- a/docs/scanner-imports/README.md
+++ b/docs/scanner-imports/README.md
@@ -32,8 +32,10 @@ The guides cover local and Cloud imports unless an input is marked local only.
[Install the CLI](../../README.md#quick-start) and open the repository the
findings apply to. Keep reports and preview output in a private directory
-outside that checkout. For commands that use `mktemp`, set `TMPDIR` there
-if needed. In CI, redirect stdout and stderr to private files.
+outside that checkout. To choose where `mktemp -d` creates the directory,
+set `TMPDIR` to an existing directory outside the checkout and pass it in the
+template, as in `mktemp -d "${TMPDIR:-/tmp}/report.XXXXXX"`. This works on
+both macOS and Linux. In CI, redirect stdout and stderr to private files.
**In the terminal**, follow your scanner's guide. Run examples that use
`--repository .` from the checkout root. For a saved report, `publish findings`
diff --git a/docs/scanner-imports/blackduck.md b/docs/scanner-imports/blackduck.md
index 1d6b29b4c..d4aadb2ae 100644
--- a/docs/scanner-imports/blackduck.md
+++ b/docs/scanner-imports/blackduck.md
@@ -143,11 +143,12 @@ print(json.dumps({"_meta": {"href": url}, "totalCount": total, "items": items}))
```
Run the script in isolated mode so Python loads packages from the trusted
-environment. Point `TMPDIR` to a private directory outside the checkout.
+environment. The example creates a private report directory under `TMPDIR`
+or, if unset, under `/tmp`.
```sh
report=
-out=$(mktemp -d) &&
+out=$(mktemp -d "${TMPDIR:-/tmp}/blackduck.XXXXXX") &&
/path/to/venv/bin/python -I /private/path/export.py > "$out/blackduck.tmp" &&
mv "$out/blackduck.tmp" "$out/blackduck.json" &&
report="$out/blackduck.json"
diff --git a/docs/scanner-imports/continuum.md b/docs/scanner-imports/continuum.md
index eb8ac2df9..ff092fb79 100644
--- a/docs/scanner-imports/continuum.md
+++ b/docs/scanner-imports/continuum.md
@@ -1,8 +1,9 @@
# Import AWS Continuum code findings
-Use `GetCodeFinding` JSON to import selected findings with their locations,
-mitigation, and AWS validation evidence. Use `ListCodeFindings` JSON for
-summaries from an environment dedicated to one repository.
+Use `GetCodeFinding` JSON to import selected findings with their locations
+and mitigation. When AWS has run validation, the export also includes the
+validation result. Use `ListCodeFindings` JSON for summaries from an
+environment dedicated to one repository.
## Quick start
@@ -20,7 +21,8 @@ report=/private/path/continuum.json
### Export findings for one repository
To create a report, sign in to the environment's AWS account and Region with
-an AWS CLI that supports `continuum`. Choose one export.
+AWS CLI v2.38.5 or later, the first release with `aws continuum`. Choose one
+export.
**One finding.** Set `FINDING_ID` to the Continuum ID of the finding you
verified. In an environment with several repositories, use this command to
@@ -28,7 +30,7 @@ export one verified finding at a time. [AWS CLI get-code-finding](https://docs.a
```sh
report=
-out=$(mktemp -d) &&
+out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
aws continuum get-code-finding --environment-id "$ENVIRONMENT_ID" \
--finding-id "$FINDING_ID" --output json > "$out/continuum.tmp" &&
mv "$out/continuum.tmp" "$out/continuum.json" &&
@@ -41,7 +43,7 @@ combine the saved objects into a JSON array with `jq`.
```sh
report=
-out=$(mktemp -d) &&
+out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
jq -s '.' first-detail.json second-detail.json > "$out/selected.json" &&
report="$out/selected.json"
```
@@ -52,7 +54,7 @@ page. [AWS CLI list-code-findings](https://docs.aws.amazon.com/cli/latest/refere
```sh
report=
-out=$(mktemp -d) &&
+out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
aws continuum list-code-findings --environment-id "$ENVIRONMENT_ID" \
--output json > "$out/continuum.tmp" &&
mv "$out/continuum.tmp" "$out/continuum.json" &&
diff --git a/sdk/typescript/bin/codex-security.mjs b/sdk/typescript/bin/codex-security.mjs
index 848590a00..58fc77a6e 100755
--- a/sdk/typescript/bin/codex-security.mjs
+++ b/sdk/typescript/bin/codex-security.mjs
@@ -11,8 +11,8 @@ async function launch() {
throw new Error("Cannot resolve CLI entrypoint.");
}
const cli = join(dirname(realpathSync(entrypoint)), "..", "dist", "cli.js");
- const { main } = await import(pathToFileURL(cli).href);
- return await main();
+ const { runCli } = await import(pathToFileURL(cli).href);
+ return await runCli();
}
void launch().then(
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index a7d650b0d..75ad04935 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1572,9 +1572,13 @@ Enterprise repository URL or its Cloud ID. Either works for retries. If
several connectors share the URL, use the ID. You can import before the
repository's first native scan.
-Cloud requires a file-backed ChatGPT login. To use your regular Codex login,
-set `cli_auth_credentials_store = "file"` in Codex `config.toml`, then sign in
-again with the ChatGPT account you want to use.
+Cloud requires a file-backed ChatGPT login. Codex Security signs in with the
+`cli_auth_credentials_store` set in your Codex `config.toml`
+(`~/.codex/config.toml`, or `$CODEX_HOME/config.toml`). Without it, the login
+can be saved in the system keyring. To publish, set
+`cli_auth_credentials_store = "file"` there, then run `codex-security login`
+with the ChatGPT account you want to use. `codex-security login status`
+checks the current sign-in without changing credential storage.
### Review the Cloud destination
@@ -1721,9 +1725,12 @@ prefix of at least eight characters, or `latest` for the current repository.
Local sealed artifacts are required. Dry runs need no login or network access.
Uploads require ChatGPT credentials saved to a file. Set
-`cli_auth_credentials_store = "file"` in Codex `config.toml`, then sign in again.
-Cloud publication rejects automatic/keyring storage even when `auth.json` exists,
-because that file may be stale or belong to another account.
+`cli_auth_credentials_store = "file"` in Codex `config.toml`, then run
+`codex-security login` again. Login, scans and other commands use that setting
+for the Codex Security sign-in.
+A dedicated login using automatic storage can publish if Codex Security
+recorded the native file fallback. An unverified file can belong to another
+account, so Cloud publication requires an explicit file store for an ambient login.
Use a positional scan directory or repeated `--scan-dir PATH` for artifacts
outside history. Each must contain one completed sealed scan, not a bulk-run
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 9d2d39896..4807bb6aa 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -63,13 +63,13 @@ import {
} from "./provider-profile.js";
import {
- CODEX_AUTH_CONFIG_KEYS,
NO_CREDENTIALS_MESSAGE,
accountStatus,
configuredCodexHome,
environmentEntry,
CodexLoginHandle,
loginApiKey as persistApiKey,
+ prepareLoginConfig,
logout as codexLogout,
withoutOpenAiApiKeys,
type AccountStatus,
@@ -80,6 +80,7 @@ import {
shellEnvironmentReference,
} from "./codex-prompt.js";
import {
+ CODEX_AUTH_CONFIG_KEYS,
EXTERNAL_CODEX_PROVIDERS,
inlineToml,
isExternalModelProvider,
@@ -254,10 +255,12 @@ import {
canonicalConfigPath,
acquireCodexSecurityCredentialHomeLock,
withCredentialHomeLock,
+ writeCredentialHomeConfig,
bootstrapPlugin,
bundledPluginRoot,
cleanupSdkDirectory,
codexSecurityCredentialAllowsAmbientImport,
+ credentialHomeUsesFileStorage,
codexSecurityCredentialHome,
codexSecurityHasStoredFileCredentials,
codexSecurityStateDirectory,
@@ -796,6 +799,7 @@ export class CodexSecurity {
readonly #onDeepScanDiagnostic: CodexSecurityRuntimeOptions["onDeepScanDiagnostic"];
readonly #loginHandles = new Set<CodexLoginHandle>();
readonly #abortController = new AbortController();
+ readonly #loginPreparation = new AbortController();
#activeOperation: Promise<unknown> | null = null;
#operationTelemetry: OperationTelemetry | null = null;
#operationTelemetryStart: Promise<void> | null = null;
@@ -4226,21 +4230,26 @@ export class CodexSecurity {
public async loginApiKey(apiKey: string): Promise<void> {
await this.#trackOperation(async () => {
- const authentication = await this.#authentication();
- this.#requireOpen();
- const result = await persistApiKey(
- await this.#providerPreflightCommand(),
- authentication.environment,
- apiKey,
- this.#abortController.signal,
- );
- if (!result.success) {
- throw new CodexSecurityError(
- `Codex API-key login failed: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`,
+ const { command, environment, codexHome, release } =
+ await this.#prepareLogin();
+ try {
+ this.#requireOpen();
+ const result = await persistApiKey(
+ command,
+ environment,
+ apiKey,
+ this.#abortController.signal,
);
+ if (!result.success) {
+ throw new CodexSecurityError(
+ `Codex API-key login failed: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`,
+ );
+ }
+ await this.#recordLogin(codexHome, "api_key");
+ this.#requireOpen();
+ } finally {
+ await release();
}
- await this.#recordLogin(authentication.codexHome, "api_key");
- this.#requireOpen();
});
}
@@ -4253,18 +4262,24 @@ export class CodexSecurity {
}
async #startLogin(deviceCode: boolean): Promise<CodexLoginHandle> {
- const authentication = await this.#authentication();
- this.#requireOpen();
- const command = await this.#providerPreflightCommand();
- this.#requireOpen();
- const handle = this.#trackLoginHandle(
- new CodexLoginHandle(
- command,
- deviceCode ? ["login", "--device-auth"] : ["login"],
- authentication.environment,
- () => this.#recordLogin(authentication.codexHome, "stored_credentials"),
- ),
- );
+ const { command, environment, codexHome, release } =
+ await this.#prepareLogin();
+ let handle: CodexLoginHandle;
+ try {
+ this.#requireOpen();
+ handle = this.#trackLoginHandle(
+ new CodexLoginHandle(
+ command,
+ deviceCode ? ["login", "--device-auth"] : ["login"],
+ environment,
+ () => this.#recordLogin(codexHome, "stored_credentials"),
+ release,
+ ),
+ );
+ } catch (error) {
+ await release();
+ throw error;
+ }
await handle.waitForInstructions({ deviceCode });
this.#requireOpen();
return handle;
@@ -4312,7 +4327,7 @@ export class CodexSecurity {
await logoutCredentialHome(
codexHome,
scanCodexHome(this.#dependencies.environment),
- () => codexLogout(command, environment, signal),
+ (store) => codexLogout(command, environment, signal, store),
() => {
if (this.#runtime !== null)
this.#runtime.credentialsAvailable = false;
@@ -4339,9 +4354,9 @@ export class CodexSecurity {
async #finishClose(): Promise<void> {
const activeOperation = this.#activeOperation;
const loginHandles = [...this.#loginHandles];
- if (activeOperation !== null || loginHandles.length > 0) {
- this.#abortController.abort();
- }
+ // A login waiting on the credential home does not yet have a child handle.
+ this.#loginPreparation.abort();
+ if (activeOperation !== null) this.#abortController.abort();
for (const handle of loginHandles) handle.cancel();
await Promise.allSettled(
[activeOperation, ...loginHandles.map((handle) => handle.wait())].filter(
@@ -4398,6 +4413,31 @@ export class CodexSecurity {
};
}
+ async #prepareLogin() {
+ const authentication = await this.#authentication();
+ const config = await mergedCodexConfig(
+ this.config,
+ scanCodexHome(this.#dependencies.environment),
+ "login",
+ );
+ const command = await this.#providerPreflightCommand(config);
+ this.#requireOpen();
+ const release = await acquireCodexSecurityCredentialHomeLock(
+ authentication.codexHome,
+ this.#loginPreparation.signal,
+ );
+ try {
+ await prepareLoginConfig(
+ authentication.codexHome,
+ resolveCodexProfile(config),
+ );
+ return { ...authentication, command, release };
+ } catch (error) {
+ await release();
+ throw error;
+ }
+ }
+
async #recordLogin(
codexHome: string,
source: "api_key" | "stored_credentials",
@@ -5134,7 +5174,7 @@ export class CodexSecurity {
runtime.codexHome,
sharedCredentialCodexConfig(mergedConfig, runtime.codexHome),
);
- await writeCodexConfig(join(runtime.codexHome, "config.toml"), config);
+ await writeCredentialHomeConfig(runtime.codexHome, config);
runtime.plugin = await bootstrapPlugin(
runtime.codexHome,
runtime.plugin.pluginRoot,
@@ -5625,7 +5665,7 @@ export class CodexSecurity {
codexHome,
sharedCredentialCodexConfig(requestedConfig, codexHome),
);
- await writeCodexConfig(join(codexHome, "config.toml"), codexConfig);
+ await writeCredentialHomeConfig(codexHome, codexConfig);
const configPath = join(bootstrapWorkspace, "config-preflight.toml");
throwIfAborted(signal);
const codexCommand =
@@ -5747,7 +5787,14 @@ export async function initialCredentialsAvailable(
if (!(await codexSecurityCredentialAllowsAmbientImport(isolatedHome))) {
return false;
}
+ if (
+ !(await credentialHomeUsesFileStorage(isolatedHome, {
+ allowAmbientImport: true,
+ }))
+ )
+ return false;
if (await codexSecurityHasStoredFileCredentials(isolatedHome)) return true;
+ if (!(await credentialHomeUsesFileStorage(ambientHome))) return false;
return await importer(ambientHome, isolatedHome);
}
@@ -7051,8 +7098,9 @@ function sharedCredentialCodexConfig(
approval_policy: scanApprovalPolicy(config),
features: { plugins: true },
};
+ const resolved = resolveCodexProfile(config);
for (const key of CODEX_AUTH_CONFIG_KEYS) {
- if (Object.hasOwn(config, key)) shared[key] = structuredClone(config[key]!);
+ if (resolved[key] !== undefined) shared[key] = resolved[key];
}
return scanRuntimeCodexConfig(shared, credentialHome);
}
diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.ts
index e1f87d7ad..6dbc6392d 100644
--- a/sdk/typescript/src/auth.ts
+++ b/sdk/typescript/src/auth.ts
@@ -4,16 +4,18 @@ import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { parse } from "smol-toml";
-import type { JsonObject } from "./config.js";
+import { CODEX_AUTH_CONFIG_KEYS, type JsonObject } from "./config.js";
import {
CodexSecurityError,
PluginBootstrapError,
errorMessage,
} from "./errors.js";
import {
+ beginCredentialLogin,
executablePathForSpawn,
expandHome,
runCodexCommand,
+ writeCredentialHomeConfig,
type CodexCommand,
type ProcessEnvironment,
} from "./runtime.js";
@@ -68,6 +70,7 @@ export async function readCodexHomeConfig(
encoding: "utf8",
signal,
}),
+ { integersAsBigInt: "asNeeded" },
) as JsonObject;
} catch (error) {
signal?.throwIfAborted();
@@ -111,6 +114,7 @@ export class CodexLoginHandle {
args: readonly string[],
environment: ProcessEnvironment,
onSuccess: () => void | Promise<void>,
+ onFinish?: () => Promise<void>,
) {
void this.#urlReady.promise.catch(() => undefined);
void this.#deviceReady.promise.catch(() => undefined);
@@ -132,7 +136,7 @@ export class CodexLoginHandle {
this.#child.stderr.on("data", (chunk: string) => {
this.#recordOutput("stderr", chunk);
});
- this.#completion = new Promise((resolve, reject) => {
+ this.#completion = new Promise<LoginResult>((resolve, reject) => {
this.#child.once("close", (exitCode) => {
clearTimeout(this.#forcedTermination);
if (!this.#canceled) {
@@ -162,7 +166,7 @@ export class CodexLoginHandle {
});
reject(error);
});
- });
+ }).finally(onFinish);
}
public get loginId(): null {
@@ -297,14 +301,21 @@ export async function accountStatus(
};
}
+export function nativeLogoutArgs(store?: string): string[] {
+ return store === undefined
+ ? ["logout"]
+ : ["-c", `cli_auth_credentials_store=${JSON.stringify(store)}`, "logout"];
+}
+
export async function logout(
command: CodexCommand,
environment: ProcessEnvironment,
signal?: AbortSignal,
+ store?: string,
): Promise<void> {
const result = await runCodexCommand(
command,
- ["logout"],
+ nativeLogoutArgs(store),
environment,
undefined,
signal,
@@ -316,12 +327,25 @@ export async function logout(
}
}
-/** @internal Authentication settings shared by login and model commands. */
-export const CODEX_AUTH_CONFIG_KEYS = [
- "cli_auth_credentials_store",
- "forced_login_method",
- "forced_chatgpt_workspace_id",
-] as const;
+/** Prepare native login under the credential-home lock, preserving unrelated settings. */
+export async function prepareLoginConfig(
+ credentialHome: string,
+ requested: JsonObject,
+): Promise<void> {
+ const config = await readCodexHomeConfig({ CODEX_HOME: credentialHome });
+ let changed = false;
+ for (const key of CODEX_AUTH_CONFIG_KEYS) {
+ const value = requested[key];
+ // Keep existing users in their native store until they select another.
+ if (key === "cli_auth_credentials_store" && value === undefined) continue;
+ if (config[key] === value) continue;
+ if (value === undefined) delete config[key];
+ else config[key] = value;
+ changed = true;
+ }
+ if (changed) await writeCredentialHomeConfig(credentialHome, config);
+ await beginCredentialLogin(credentialHome);
+}
/** @internal Shared login recovery guidance for model commands. */
export const NO_CREDENTIALS_MESSAGE =
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index d9e0e8cb7..f6919a98e 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -103,7 +103,8 @@ import {
} from "./api.js";
import {
accountStatus,
- CODEX_AUTH_CONFIG_KEYS,
+ nativeLogoutArgs,
+ prepareLoginConfig,
NO_CREDENTIALS_MESSAGE,
configuredCodexHome,
environmentEntry,
@@ -186,6 +187,7 @@ import {
type BulkScanPrompt,
} from "./bulk-scan-discovery.js";
import {
+ CODEX_AUTH_CONFIG_KEYS,
DEFAULT_CODEX_CONFIG,
deepMerge,
EXTERNAL_CODEX_PROVIDERS,
@@ -198,6 +200,7 @@ import {
resolveCommandAuthConfig,
resolveCodexProfile,
mergedCodexConfig,
+ readCodexAuthConfig,
readCodexFileProfile,
scanPricingContext,
scanModel,
@@ -296,6 +299,7 @@ import {
resolvePluginPath,
acquireCodexSecurityCredentialHomeLock,
withCredentialHomeLock,
+ writeCredentialHomeConfig,
requireOutputOutsideRepositories,
canonicalizeModelSafePath,
codexSecurityCredentialAllowsAmbientImport,
@@ -397,6 +401,7 @@ import {
CODEX_EXECUTABLE_VERSION,
CODEX_SDK_VERSION,
formatUpdateNotice,
+ invokedWithNpx,
updateNoticeEnabled,
type UpdateNotice,
VERSION,
@@ -1779,10 +1784,7 @@ async function runCodexSkillProcess(
credentialConfig["model_providers"] = {
[provider]: providerConfiguration,
};
- await writeCodexConfig(
- join(codexHome, "config.toml"),
- credentialConfig,
- );
+ await writeCredentialHomeConfig(codexHome, credentialConfig);
credentialsAvailable = await initialCredentialsAvailable(
selected,
configuredCodexHome(selected),
@@ -1898,9 +1900,7 @@ async function runCodexSkillProcess(
cwd: output?.appServer?.directory ?? parse(process.execPath).root,
stdio:
output === undefined
- ? input === undefined
- ? "inherit"
- : ["pipe", "inherit", "inherit"]
+ ? [input === undefined ? "inherit" : "pipe", "inherit", "pipe"]
: [
output.appServer !== undefined || input !== undefined
? "pipe"
@@ -1958,29 +1958,33 @@ async function runCodexSkillProcess(
process.on("SIGTERM", onTerminate);
try {
let diagnostic = "";
- invocation.stderr?.setEncoding("utf8").on("data", (chunk: string) => {
- diagnostic += chunk;
- });
- const captured =
+ let forwarded: Promise<void> | undefined;
+ if (output === undefined && invocation.stderr) {
+ forwarded = forwardSignInHints(invocation.stderr, processEnvironment);
+ } else {
+ invocation.stderr?.setEncoding("utf8").on("data", (chunk: string) => {
+ diagnostic += chunk;
+ });
+ }
+ const captured = Promise.race([
output === undefined || invocation.stdout === null
- ? Promise.resolve(undefined)
- : Promise.race([
- readSkillCommandOutput(
- invocation.stdout,
- output.appServer === undefined
- ? undefined
- : {
- ...output.appServer,
- apiKey,
- modelProvider,
- onThreadStarted: releaseCredentialHome,
- input: invocation.stdin!,
- },
- ),
- new Promise<undefined>((resolve) => {
- forceCaptureCompletion = () => resolve(undefined);
- }),
- ]);
+ ? forwarded?.then(() => undefined)
+ : readSkillCommandOutput(
+ invocation.stdout,
+ output.appServer === undefined
+ ? undefined
+ : {
+ ...output.appServer,
+ apiKey,
+ modelProvider,
+ onThreadStarted: releaseCredentialHome,
+ input: invocation.stdin!,
+ },
+ ),
+ new Promise<undefined>((resolve) => {
+ forceCaptureCompletion = () => resolve(undefined);
+ }),
+ ]);
invocationStatus = new Promise<number>((resolve, reject) => {
const complete = (
code: number | null,
@@ -2051,6 +2055,12 @@ async function runCodexSkillProcess(
invocation.stderr?.destroy();
requestTermination("SIGTERM");
await invocationStatus?.catch(() => undefined);
+ // The sign-in diagnostic stream is closed; a second diagnostic cannot be delivered.
+ if (
+ output === undefined &&
+ (error as NodeJS.ErrnoException)?.code === "EPIPE"
+ )
+ return 1;
throw error;
} finally {
if (forcedTermination !== undefined) clearTimeout(forcedTermination);
@@ -2065,6 +2075,37 @@ async function runCodexSkillProcess(
}
}
+/** Forward native prompts immediately, including commands split across stderr writes. */
+async function forwardSignInHints(
+ stderr: Readable,
+ environment: NodeJS.ProcessEnv,
+): Promise<void> {
+ const cli = invokedWithNpx(environment)
+ ? "npx @openai/codex-security"
+ : "codex-security";
+ const hints = ["`codex login", "| codex login"];
+ const rewrite = (text: string) =>
+ text.replace(/(`|\| )codex login(?=[\s`]|$)/gu, `$1${cli} login`);
+ let pending = "";
+ for await (const chunk of stderr.setEncoding(
+ "utf8",
+ ) as AsyncIterable<string>) {
+ let text = pending + chunk;
+ pending = "";
+ // Hold only a partial command at the end of this chunk.
+ const start = Math.max(text.lastIndexOf("`"), text.lastIndexOf("|"));
+ if (start >= 0) {
+ const tail = text.slice(start);
+ if (hints.some((hint) => hint.startsWith(tail))) {
+ pending = tail;
+ text = text.slice(0, start);
+ }
+ }
+ if (text) await writeCliOutput(process.stderr, rewrite(text));
+ }
+ if (pending) await writeCliOutput(process.stderr, rewrite(pending));
+}
+
/**
* Stored auth switches homes. Native origins preserve ambient settings at
* app-server startup, including telemetry controls and model discovery gates.
@@ -2245,11 +2286,30 @@ function handleDisconnectedResize(error: NodeJS.ErrnoException): void {
}
}
+/** Run the standalone CLI, which owns the process and its stdio. */
+export async function runCli(): Promise<number> {
+ let signInInterrupted = false;
+ const exitCode = await main(
+ process.argv.slice(2),
+ process.stdout,
+ process.stderr,
+ DEFAULT_DEPENDENCIES,
+ () => {
+ signInInterrupted = true;
+ },
+ );
+ // Managed output and child cleanup are complete. An interrupted prompt may
+ // still have a write pending on stderr if its reader stopped draining.
+ if (signInInterrupted) process.exit(exitCode);
+ return exitCode;
+}
+
export async function main(
argv: readonly string[] = process.argv.slice(2),
output: Writable = process.stdout,
errorOutput: Writable = process.stderr,
dependencies: CliDependencies = DEFAULT_DEPENDENCIES,
+ onInterruptedSignIn?: () => void,
): Promise<number> {
const remediationOperation =
argv[0] === "patch"
@@ -7109,34 +7169,38 @@ export async function main(
dependencies.environment,
);
const authentication = scanAuthentication(dependencies.environment);
- if (args.action === "status" && authentication.method !== "api_key") {
- const ambientHome = scanCodexHome(dependencies.environment);
- await withCredentialHomeLock(credentialHome, () =>
- initialCredentialsAvailable(
+ exitCode = await withCredentialHomeLock(credentialHome, async () => {
+ if (args.action === undefined) {
+ await prepareLoginConfig(
+ credentialHome,
+ await readCodexAuthConfig(
+ scanCodexHome(dependencies.environment),
+ true,
+ ),
+ );
+ } else if (authentication.method !== "api_key") {
+ await initialCredentialsAvailable(
dependencies.environment,
- ambientHome,
+ scanCodexHome(dependencies.environment),
credentialHome,
- ),
+ );
+ }
+ const status = await dependencies.runCodex(
+ [
+ "login",
+ ...(args.action === undefined ? [] : [args.action]),
+ ...(options.deviceAuth ? ["--device-auth"] : []),
+ ...(options.withApiKey ? ["--with-api-key"] : []),
+ ...(options.withAccessToken ? ["--with-access-token"] : []),
+ ],
+ undefined,
+ { ...dependencies.environment, CODEX_HOME: credentialHome },
);
- }
- const authenticationEnvironment = {
- ...dependencies.environment,
- CODEX_HOME: credentialHome,
- };
- exitCode = await dependencies.runCodex(
- [
- "login",
- ...(args.action === undefined ? [] : [args.action]),
- ...(options.deviceAuth ? ["--device-auth"] : []),
- ...(options.withApiKey ? ["--with-api-key"] : []),
- ...(options.withAccessToken ? ["--with-access-token"] : []),
- ],
- undefined,
- authenticationEnvironment,
- );
- if (args.action === undefined && exitCode === 0) {
- await setCodexSecurityCredentialLogout(credentialHome, false);
- }
+ if (args.action === undefined && status === 0) {
+ await setCodexSecurityCredentialLogout(credentialHome, false);
+ }
+ return status;
+ });
if (args.action === "status") {
if (
authentication.method === "api_key" &&
@@ -7184,16 +7248,20 @@ export async function main(
const credentialHome = await prepareCodexSecurityCredentialHome(
dependencies.environment,
);
- const runLogout = () =>
- dependencies.runCodex(["logout"], undefined, {
- ...dependencies.environment,
- CODEX_HOME: credentialHome,
- });
+ const environment = {
+ ...dependencies.environment,
+ CODEX_HOME: credentialHome,
+ };
exitCode = await withCredentialHomeLock(credentialHome, () =>
logoutCredentialHome(
credentialHome,
scanCodexHome(dependencies.environment),
- runLogout,
+ (store) =>
+ dependencies.runCodex(
+ nativeLogoutArgs(store),
+ undefined,
+ environment,
+ ),
),
);
},
@@ -7691,6 +7759,11 @@ export async function main(
} finally {
updateController.abort();
}
+ if (
+ (command === "login" || command === "logout") &&
+ (exitCode === 130 || exitCode === 143)
+ )
+ onInterruptedSignIn?.();
let frameworkOutput = frameworkCapture.text();
if (filteredScanFailure !== undefined) {
// Success-field filters do not apply to diagnostics. Reuse Incur's format
@@ -12477,7 +12550,7 @@ const interruptedExitCode = (signal: AbortSignal): number | undefined =>
: undefined;
if (invokedAsMain()) {
- void main().then(
+ void runCli().then(
(exitCode) => {
process.exitCode = exitCode;
},
diff --git a/sdk/typescript/src/cloud-publish.ts b/sdk/typescript/src/cloud-publish.ts
index fe2e69de5..807c86d21 100644
--- a/sdk/typescript/src/cloud-publish.ts
+++ b/sdk/typescript/src/cloud-publish.ts
@@ -21,12 +21,14 @@ import {
codexSecurityCredentialAllowsAmbientImport,
codexSecurityCredentialHome,
codexSecurityHasStoredFileCredentials,
+ credentialHomeUsesFileStorage,
+ withCredentialHomeLock,
expandHome,
} from "./runtime.js";
import { VERSION } from "./version.js";
import { cloudBaseUrl } from "./cloud-endpoint.js";
const CHATGPT_LOGIN_REQUIRED =
- "Cloud publication requires a ChatGPT login already available to Codex Security. Run a scan or sign in with ChatGPT using Codex file credential storage, then retry.";
+ "Cloud publication requires a ChatGPT login already available to Codex Security and saved to a file. Set cli_auth_credentials_store = \"file\" in ~/.codex/config.toml (or $CODEX_HOME/config.toml), run 'codex-security login', then retry.";
const credentialsSchema = z.object({
auth_mode: z.literal("chatgpt").optional(),
@@ -173,7 +175,10 @@ async function publishCloudPayload(
const publishUrl =
environment["CODEX_SECURITY_CLOUD_PUBLISH_URL"]?.trim() ||
`${cloudBaseUrl(environment)}/cli/findings`;
- const credentials = await readCloudCredentials(environment);
+ const credentials = await readCloudCredentials(
+ environment,
+ dependencies.signal,
+ );
const timeout = AbortSignal.timeout(30_000);
const signal = dependencies.signal
? AbortSignal.any([dependencies.signal, timeout])
@@ -246,41 +251,54 @@ async function publishCloudPayload(
}
/** @internal Shared sign-in for local Cloud publishers. */
-export async function readCloudCredentials(environment: NodeJS.ProcessEnv) {
+export async function readCloudCredentials(
+ environment: NodeJS.ProcessEnv,
+ signal?: AbortSignal,
+) {
+ const dedicatedHome = codexSecurityCredentialHome(environment);
+ if (existsSync(dedicatedHome)) {
+ const dedicated = await withCredentialHomeLock(
+ dedicatedHome,
+ async () => {
+ if (
+ !(await codexSecurityCredentialAllowsAmbientImport(dedicatedHome))
+ ) {
+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);
+ }
+ if (await codexSecurityHasStoredFileCredentials(dedicatedHome)) {
+ if (await credentialHomeUsesFileStorage(dedicatedHome))
+ return readCloudLoginFile(dedicatedHome);
+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);
+ }
+ // A dedicated configuration may point to a different account in the keyring.
+ if (existsSync(join(dedicatedHome, "config.toml")))
+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);
+ },
+ signal,
+ );
+ if (dedicated) return dedicated;
+ }
const configuredHome = environment["CODEX_HOME"];
- let home = expandHome(
+ const home = expandHome(
configuredHome?.trim() ? configuredHome : "~/.codex",
environment,
);
- let requireFileStorage = true;
- const dedicatedHome = codexSecurityCredentialHome(environment);
- if (existsSync(dedicatedHome)) {
- if (!(await codexSecurityCredentialAllowsAmbientImport(dedicatedHome))) {
- throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);
- }
- if (await codexSecurityHasStoredFileCredentials(dedicatedHome)) {
- home = dedicatedHome;
- requireFileStorage = false;
- } else if (existsSync(join(dedicatedHome, "config.toml"))) {
- // Do not silently switch accounts when the dedicated login may be in a keyring.
- throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);
- }
- }
- if (requireFileStorage) {
- let credentialStorage: unknown;
- try {
- credentialStorage = parseToml(
- await readFile(join(home, "config.toml"), "utf8"),
- )["cli_auth_credentials_store"];
- } catch {
- throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);
- }
- // File presence is not proof that it is the active ambient login:
- // automatic or keyring storage can leave auth.json for another account.
- if (credentialStorage !== "file") {
- throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);
- }
+ let credentialStorage: unknown;
+ try {
+ credentialStorage = parseToml(
+ await readFile(join(home, "config.toml"), "utf8"),
+ { integersAsBigInt: "asNeeded" },
+ )["cli_auth_credentials_store"];
+ } catch {
+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);
}
+ // Ambient auto storage can leave a file for another account.
+ if (credentialStorage !== "file")
+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);
+ return readCloudLoginFile(home);
+}
+
+async function readCloudLoginFile(home: string) {
try {
const credentials = credentialsSchema.safeParse(
JSON.parse(await readFile(join(home, "auth.json"), "utf8")),
diff --git a/sdk/typescript/src/config.ts b/sdk/typescript/src/config.ts
index 4276f0a0d..346c2e8ce 100644
--- a/sdk/typescript/src/config.ts
+++ b/sdk/typescript/src/config.ts
@@ -89,6 +89,41 @@ export const DEFAULT_CODEX_CONFIG: Readonly<JsonObject> = Object.freeze({
}),
});
+/** @internal Authentication settings shared by login and model commands. */
+export const CODEX_AUTH_CONFIG_KEYS = [
+ "cli_auth_credentials_store",
+ "forced_login_method",
+ "forced_chatgpt_workspace_id",
+] as const;
+
+/**
+ * @internal Read only the native sign-in preferences. Scans with independently
+ * supplied credentials may not have access to the ambient home.
+ */
+export async function readCodexAuthConfig(
+ home: string,
+ required = false,
+): Promise<JsonObject> {
+ let config: JsonObject;
+ try {
+ config = parse(await readFile(join(home, "config.toml"), "utf8"), {
+ integersAsBigInt: "asNeeded",
+ }) as JsonObject;
+ } catch (error) {
+ if (!required || (error as NodeJS.ErrnoException).code === "ENOENT")
+ return {};
+ throw new ConfigurationError(
+ `Could not read Codex sign-in settings from ${join(home, "config.toml")}: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: error },
+ );
+ }
+ return Object.fromEntries(
+ CODEX_AUTH_CONFIG_KEYS.flatMap((key) =>
+ config[key] === undefined ? [] : [[key, config[key]]],
+ ),
+ );
+}
+
export function scanModelConfiguration(
config: Readonly<JsonObject>,
): ScanModelConfiguration {
@@ -438,6 +473,7 @@ export function resolveNestedConfigPaths(
export async function mergedCodexConfig(
config: CodexSecurityConfig,
profileHome?: string,
+ purpose: "scan" | "login" = "scan",
): Promise<JsonObject> {
if (config.codexOverrides !== undefined && !isObject(config.codexOverrides)) {
throw new ConfigurationError("codexOverrides must be an object.");
@@ -456,6 +492,13 @@ export async function mergedCodexConfig(
}
}
const defaults: JsonObject = structuredClone(DEFAULT_CODEX_CONFIG);
+ // Native login keeps the credential home's existing store unless one was requested.
+ if (purpose === "login") delete defaults["cli_auth_credentials_store"];
+ if (profileHome !== undefined)
+ Object.assign(
+ defaults,
+ await readCodexAuthConfig(profileHome, purpose === "login"),
+ );
const effectiveOverrides = deepMerge(nativeProfile, overrides);
validateNativeMultiAgentV2Overrides(effectiveOverrides);
if (scanModelProvider(effectiveOverrides) === "amazon-bedrock") {
diff --git a/sdk/typescript/src/continuum-findings.ts b/sdk/typescript/src/continuum-findings.ts
index a2ee150e1..0bc6163b2 100644
--- a/sdk/typescript/src/continuum-findings.ts
+++ b/sdk/typescript/src/continuum-findings.ts
@@ -170,6 +170,41 @@ function reportRows(input: unknown, previous: boolean) {
};
}
+function subcategoryCwe(row: Record<string, unknown>) {
+ return /^(CWE-[1-9]\d*):/u.exec(text(row["subCategory"]) ?? "")?.[1];
+}
+
+/** @internal Match 0.9.x checkpoints for both raw imports and saved SDK output. */
+export function previousContinuumCweProjection(
+ current: ExternalFindings,
+): ExternalFindings {
+ let changed = false;
+ const findings = current.findings.map((finding) => {
+ const { details, source_data } = finding.evidence;
+ const native = source_data?.["finding"];
+ // Remove only the inferred field. Caller edits and all other evidence must
+ // still match the immutable checkpoint before it can be resumed.
+ if (
+ source_data?.["format"] !== format ||
+ !isRecord(native) ||
+ details?.kind !== "sast" ||
+ details.weakness_ids?.length !== 1 ||
+ strings(native["cweIds"]).length ||
+ details.weakness_ids[0] !== subcategoryCwe(native)
+ )
+ return finding;
+ changed = true;
+ return {
+ ...finding,
+ evidence: {
+ ...finding.evidence,
+ details: { ...details, weakness_ids: [] },
+ },
+ };
+ });
+ return changed ? { ...current, findings } : current;
+}
+
function statusUpdatedAt(value: unknown) {
const seconds = Math.floor(awsTimestampSeconds(value));
return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : null;
@@ -307,19 +342,30 @@ function normalize(
const updatedAt = previous
? null
: statusUpdatedAt(row["statusUpdatedAt"]);
- // Keep the status timestamp when structured packages exceed the Cloud budget.
+ const enrichment = previous
+ ? undefined
+ : {
+ packages: affectedPackages(packages, target),
+ source_updated_at: updatedAt,
+ };
+ // Native code findings can identify a CWE only in subCategory.
+ const namedCwe =
+ !previous && evidence.details?.weakness_ids.length === 0
+ ? subcategoryCwe(row)
+ : undefined;
+ const inferred = namedCwe
+ ? { details: { ...evidence.details, weakness_ids: [namedCwe] } }
+ : undefined;
+ // Keep previously admissible evidence if an optional projection exceeds the Cloud budget.
return validateEnrichedExternalEvidence(
evidence,
target,
- previous
- ? undefined
- : {
- packages: affectedPackages(packages, target),
- source_updated_at: updatedAt,
- },
+ inferred ? { ...enrichment, ...inferred } : undefined,
+ enrichment,
packages.length && updatedAt !== null
? { source_updated_at: updatedAt }
: undefined,
+ inferred,
);
},
(value) => {
diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.ts
index c4a5a94b7..11293a691 100644
--- a/sdk/typescript/src/external-findings-publish.ts
+++ b/sdk/typescript/src/external-findings-publish.ts
@@ -120,7 +120,10 @@ import {
projectedBlackDuckRepositoryUrl,
} from "./blackduck-findings.js";
import { checkmarxSelection } from "./checkmarx-repository.js";
-import { continuumReportRepositories } from "./continuum-findings.js";
+import {
+ continuumReportRepositories,
+ previousContinuumCweProjection,
+} from "./continuum-findings.js";
import { veracodeReportRepositories } from "./veracode-findings.js";
import { inspectorReportRepository } from "./inspector-findings.js";
import { sonarRepositoryUrls } from "./sonar-findings.js";
@@ -737,8 +740,9 @@ export async function prepareExternalPublication(
: await normalizeSnykFile(report, "cloud", references);
const selection = normalizedPublicationInput(findings, provider);
if (semgrep && hasPreviousCloudProjection(findings))
- selection.readPreviousFindings = () =>
- normalizePreviousSemgrepFindings(report, semgrepOptions);
+ selection.previousReaders = [
+ () => normalizePreviousSemgrepFindings(report, semgrepOptions),
+ ];
return selection;
};
const hosted =
@@ -790,7 +794,8 @@ export async function prepareExternalPublication(
input =
parsed.publication ??
normalizedPublicationInput(parsed.findings, provider);
- input.readPreviousFindings = parsed.previousFindings;
+ if (parsed.previousFindings)
+ (input.previousReaders ??= []).push(parsed.previousFindings);
if (provider === "endor") {
fileRepositories = () => parsed.sourceRepositories ?? [];
input.requiresStructuredReport = requiresStructuredEndorReport(
@@ -1030,7 +1035,7 @@ function hostedRepositoryMatcher(
interface PublicationSelection extends ExternalPublicationInput {
requiresStructuredReport?: boolean;
sourcePositions?: ReadonlyMap<string, readonly number[]>;
- readPreviousFindings?: () => ExternalFindings;
+ previousReaders?: (() => ExternalFindings)[];
original?: {
parsed: ExternalFindings;
identity: unknown;
@@ -1349,6 +1354,10 @@ function normalizedPublicationInput(
legacy: current,
currentIdentity: identity,
legacyIdentity: identity,
+ previousReaders:
+ provider === "continuum"
+ ? [() => previousContinuumCweProjection(current)]
+ : undefined,
sourcePositions: getOpenGrepSourcePositions(ownData(input, "findings")),
original,
freshError,
@@ -1563,13 +1572,12 @@ async function preparePublicationInput(
function pendingFile(key: string) {
return join(state, `${key}.pending.json`);
}
- let previousFindings: ExternalFindings | undefined;
+ let previousFindings: ExternalFindings[] | undefined;
async function previousFindingsIfSaved(
input: PublicationSelection,
currentKey?: string,
) {
- if (!input.readPreviousFindings || previousFindings)
- return previousFindings;
+ if (!input.previousReaders || previousFindings) return previousFindings;
// An empty state directory (or just this current receipt) needs only the
// current reader for its preview.
const entries = (await readdir(state).catch(nullIfMissingFile)) ?? [];
@@ -1580,7 +1588,7 @@ async function preparePublicationInput(
name.split(".", 1)[0] !== currentKey,
)
)
- previousFindings = input.readPreviousFindings();
+ previousFindings = input.previousReaders.map((read) => read());
return previousFindings;
}
async function checkSelection(input: PublicationSelection) {
@@ -1596,7 +1604,9 @@ async function preparePublicationInput(
!input.uncertainFindingIds?.length &&
!input.unprovenOccurrenceCount &&
!input.unprovenIdPrefixes?.length &&
- !(await previousFindingsIfSaved(input))?.findings.length
+ !(await previousFindingsIfSaved(input))?.some(
+ (report) => report.findings.length,
+ )
)
throw new NoPublishableFindingsError(parsed);
}
@@ -1607,7 +1617,8 @@ async function preparePublicationInput(
// Validate the configured return destination before authentication or uploads.
cloudFindingsUrl(environment, options.repository);
const credentials = await (
- dependencies.credentials ?? (() => readCloudCredentials(environment))
+ dependencies.credentials ??
+ (() => readCloudCredentials(environment, dependencies.signal))
)();
let canStartJob = false;
let repositorySeverities: string[] | undefined;
@@ -1650,10 +1661,16 @@ async function preparePublicationInput(
error?: { message?: string };
} | null;
const retryAfter = response.headers.get("Retry-After");
- throw new CloudImportError(
- response.status,
- `Cloud import failed (HTTP ${response.status}). ${payload?.error?.message ?? response.statusText}${retryAfter ? ` Retry-After: ${retryAfter}.` : ""}`,
- );
+ const detail = payload?.error?.message ?? response.statusText;
+ let message = `Cloud import failed (HTTP ${response.status}).`;
+ if (detail) message += ` ${detail}`;
+ if (repositoryCatalog && response.status === 404) {
+ if (!/[.!?]$/u.test(message)) message += ".";
+ message +=
+ " Cloud import is not available for this account or deployment.";
+ }
+ if (retryAfter) message += ` Retry-After: ${retryAfter}.`;
+ throw new CloudImportError(response.status, message);
}
if (repositoryCatalog) {
const advertised = (header: string) =>
@@ -1778,22 +1795,22 @@ async function preparePublicationInput(
dependencies.signal,
);
let previewContext: PrivateImportContext | undefined;
- const currentReaderKey = resolved.readPreviousFindings
+ const currentReaderKey = resolved.previousReaders
? scopeKey(resolved.currentIdentity)
: undefined;
- let alternateKey: string | undefined;
+ const alternateReaders = new Map<string, ExternalFindings>();
let resumingPreviousReader = false;
- function previousCandidateKey(previous: ExternalFindings | undefined) {
- if (!previous?.findings.length) return;
- // The file reader already validated plain JSON evidence for Cloud. Only a
- // matching checkpoint needs the full normalized publication snapshot.
- const previousKey = scopeKey(
- publicationIdentity(previous, options.provider),
- );
- return previousKey !== currentReaderKey ? previousKey : undefined;
+ function addPreviousReaders(readers: ExternalFindings[] | undefined) {
+ // A source can produce identical evidence under multiple reader versions.
+ for (const reader of readers ?? []) {
+ if (reader === resolved.current || !reader.findings.length) continue;
+ const key = scopeKey(publicationIdentity(reader, options.provider));
+ if (key !== currentReaderKey) alternateReaders.set(key, reader);
+ }
}
async function alternateCheckpoint(
key: string,
+ reader: ExternalFindings,
context: () => Promise<PrivateImportContext>,
): Promise<{ pending: string | undefined } | undefined> {
const pending = await readOptionalFile(pendingFile(key));
@@ -1806,13 +1823,9 @@ async function preparePublicationInput(
// A completed import cannot acknowledge findings newly admitted by the
// current reader. Pending uploads and jobs always retain their original bytes.
if (
- !resumingPreviousReader &&
- previousFindings &&
+ key !== currentReaderKey &&
checkpoint.receipt?.status === "completed" &&
- !sameFindingSelection(
- previousFindings.findings,
- resolved.current.findings,
- )
+ !sameFindingSelection(reader.findings, resolved.current.findings)
)
return;
if (checkpoint.contextVersion === (await context()).context_version)
@@ -1821,30 +1834,31 @@ async function preparePublicationInput(
async function assertNoAlternateCheckpoint(
context = () => privateClient.context(),
) {
- if (alternateKey && (await alternateCheckpoint(alternateKey, context)))
- throw new CodexSecurityError(
- resumingPreviousReader
- ? "Both reader versions have saved publications for this report. Resume either one using its original normalized findings."
- : "Another publication prepared this input. Run the command again to review and resume the saved request.",
- );
+ for (const [key, reader] of alternateReaders) {
+ if (await alternateCheckpoint(key, reader, context))
+ throw new CodexSecurityError(
+ resumingPreviousReader
+ ? "Multiple reader versions have saved publications for this report. Resume one using its original normalized findings."
+ : "Another publication prepared this input. Run the command again to review and resume the saved request.",
+ );
+ }
}
- if (currentReaderKey)
- alternateKey = previousCandidateKey(
+ if (currentReaderKey) {
+ addPreviousReaders(
await previousFindingsIfSaved(resolved, currentReaderKey),
);
- if (alternateKey && previousFindings) {
const context = async () =>
(previewContext ??= await privateClient.context());
- const checkpoint = await alternateCheckpoint(alternateKey, context);
- capturedPending = checkpoint?.pending;
- if (checkpoint) {
- projection = normalizedPublicationInput(
- previousFindings,
- options.provider,
- );
+ for (const [key, reader] of alternateReaders) {
+ const checkpoint = await alternateCheckpoint(key, reader, context);
+ if (!checkpoint) continue;
+ capturedPending = checkpoint.pending;
+ projection = normalizedPublicationInput(reader, options.provider);
resumingPreviousReader = true;
- alternateKey = currentReaderKey;
+ alternateReaders.delete(key);
+ alternateReaders.set(currentReaderKey, resolved.current);
await assertNoAlternateCheckpoint(context);
+ break;
}
}
const input = projection;
@@ -2840,15 +2854,14 @@ async function preparePublicationInput(
await rm(lookupPath, { force: true }).catch(() => undefined);
}
- const lockKeys = [key, fileKey, stagingKey];
- if (alternateKey) lockKeys.push(alternateKey);
+ const lockKeys = [key, fileKey, stagingKey, ...alternateReaders.keys()];
async function underPublishLocks<T>(operation: () => Promise<T>) {
// An older publisher may already hold its lock before its checkpoint exists.
// Derive that key for actual writes, even after a checkpoint-free preview.
- if (resolved.readPreviousFindings && !previousFindings) {
- previousFindings = resolved.readPreviousFindings();
- alternateKey = previousCandidateKey(previousFindings);
- if (alternateKey) lockKeys.push(alternateKey);
+ if (resolved.previousReaders && !previousFindings) {
+ previousFindings = resolved.previousReaders.map((read) => read());
+ addPreviousReaders(previousFindings);
+ lockKeys.push(...alternateReaders.keys());
}
return underLocks(lockKeys, operation);
}
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 1b05ab886..17d08cbf4 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -36,7 +36,6 @@ import {
lstat,
mkdir,
mkdtemp,
- open,
readFile,
readdir,
realpath,
@@ -81,7 +80,11 @@ import {
errorMessage,
abortReason,
} from "./errors.js";
-import type { JsonObject } from "./config.js";
+import {
+ writeCodexConfig,
+ writePrivateConfig,
+ type JsonObject,
+} from "./config.js";
import { isRecord } from "./record.js";
import {
isWithin,
@@ -129,6 +132,7 @@ const MODEL_UNSAFE_PATH = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u;
const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
const CREDENTIAL_LOCK_DATABASE = ".codex-security-scan.sqlite3";
const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
+const KEYRING_LOGIN = ".codex-security-keyring-login";
const CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS = 5_000;
const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
@@ -1589,25 +1593,146 @@ async function hasSeparateAmbientLink(
}
}
+/** Native Codex defaults to file storage when the managed home has no setting. */
+async function credentialStore(home: string): Promise<unknown> {
+ const contents = await readFile(join(home, "config.toml"), "utf8").catch(
+ nullIfMissingFileError,
+ );
+ return contents === null
+ ? "file"
+ : (parse(contents, { integersAsBigInt: "asNeeded" })[
+ "cli_auth_credentials_store"
+ ] ?? "file");
+}
+
+async function hasCredentialFile(home: string): Promise<boolean> {
+ const file = await lstat(join(home, "auth.json")).catch(
+ nullIfMissingFileError,
+ );
+ return file?.isFile() === true;
+}
+
+function savedKeyringHistory(home: string) {
+ return readFile(join(home, KEYRING_LOGIN), "utf8").catch(
+ nullIfMissingFileError,
+ );
+}
+
+function canUseKeyring(store: unknown): boolean {
+ return store === "auto" || store === "keyring";
+}
+
+function keyringHistory(
+ saved: string | null,
+ store: unknown,
+ hasFile: boolean,
+) {
+ if (saved === "keyring" || saved === "pending") return "keyring";
+ // On upgrade, a prior keyring login may exist. Auto can also move a file
+ // credential into the keyring on refresh, removing auth.json.
+ if (
+ (saved === null && canUseKeyring(store)) ||
+ (saved === "file" && store === "auto" && !hasFile)
+ )
+ return "keyring";
+ return hasFile ? "file" : "none";
+}
+
+async function rememberStoredFile(home: string) {
+ if ((await savedKeyringHistory(home)) === "none") {
+ await writePrivateConfig(join(home, KEYRING_LOGIN), "file");
+ }
+}
+
+/** Arm logout before a native login can persist a keyring grant and be interrupted. */
+export async function beginCredentialLogin(home: string): Promise<void> {
+ const store = await credentialStore(home);
+ if (!canUseKeyring(store)) return;
+ const marker = join(home, KEYRING_LOGIN);
+ const saved = await savedKeyringHistory(home);
+ const present = await hasCredentialFile(home);
+ const previous = keyringHistory(saved, store, present);
+ // Only this login's successful file fallback can discharge a new pending marker.
+ const next = previous === "keyring" ? "keyring" : "pending";
+ if (next !== saved) await writePrivateConfig(marker, next);
+}
+
+/** Is the managed file the active login, or a known-empty file destination for an ambient import? */
+export async function credentialHomeUsesFileStorage(
+ home: string,
+ options: { allowAmbientImport?: boolean } = {},
+): Promise<boolean> {
+ const store = await credentialStore(home);
+ if (store !== "auto") return store === "file";
+ const saved = await savedKeyringHistory(home);
+ const hasFile = await hasCredentialFile(home);
+ return hasFile
+ ? saved === "file"
+ : options.allowAmbientImport === true && saved === "none";
+}
+
+/** Preserve credential provenance before a scan or sign-in replaces the shared config. */
+export async function writeCredentialHomeConfig(
+ home: string,
+ config: JsonObject,
+): Promise<void> {
+ const old = await credentialStore(home);
+ if (
+ canUseKeyring(old) ||
+ canUseKeyring(config["cli_auth_credentials_store"])
+ ) {
+ const marker = join(home, KEYRING_LOGIN);
+ const saved = await savedKeyringHistory(home);
+ const hasFile = await hasCredentialFile(home);
+ const observed = keyringHistory(saved, old, hasFile);
+ if (observed !== saved) await writePrivateConfig(marker, observed);
+ }
+ await writeCodexConfig(join(home, "config.toml"), config);
+}
+
/** Run under the credential-home lock so status cannot reimport the sign-in during logout. */
export async function logoutCredentialHome<T extends number | void>(
home: string,
ambientHome: string,
- nativeLogout: () => Promise<T>,
+ nativeLogout: (store?: string) => Promise<T>,
onLoggedOut?: () => void,
): Promise<T> {
const localPath = join(home, "auth.json");
const shared = await hasSeparateAmbientLink(localPath, ambientHome);
+ let recorded = false;
const recordLogout = async () => {
+ if (recorded) return;
await setCodexSecurityCredentialLogout(home, true);
if (shared) await rm(localPath);
onLoggedOut?.();
+ recorded = true;
};
// Detach before native logout can revoke a shared token, even if native cleanup fails.
if (shared) await recordLogout();
- const status = await nativeLogout();
- if (!shared && (status === undefined || status === 0)) await recordLogout();
+ const marker = join(home, KEYRING_LOGIN);
+ const previous = await savedKeyringHistory(home);
+ const active = await credentialStore(home);
+ const hasFile = await hasCredentialFile(home);
+ const keyring =
+ keyringHistory(previous, active, hasFile || shared) === "keyring";
+ if (keyring && hasFile) {
+ // Native keyring logout also unlinks the file, but only revokes the token it loads.
+ const status = await nativeLogout(active === "file" ? undefined : "file");
+ if (status !== undefined && status !== 0) return status;
+ // A retry must not re-import ambient credentials after the file was revoked.
+ await recordLogout();
+ }
+ let override: string | undefined;
+ if (keyring && !canUseKeyring(active)) override = "keyring";
+ else if (!keyring && active !== "file" && (hasFile || canUseKeyring(active)))
+ override = "file";
+ const status = await nativeLogout(override);
+ if (status === undefined || status === 0) {
+ await recordLogout();
+ if (canUseKeyring(active)) await writePrivateConfig(marker, "none");
+ else await rm(marker, { force: true });
+ }
return status;
}
@@ -1618,27 +1743,25 @@ export async function setCodexSecurityCredentialLogout(
await requireSecureCredentialHome(codexHome);
const marker = join(codexHome, CREDENTIAL_LOGOUT_MARKER);
if (!loggedOut) {
+ // Native auto removes auth.json on keyring success and leaves it on file fallback.
+ const store = await credentialStore(codexHome);
+ const history = join(codexHome, KEYRING_LOGIN);
+ if (
+ store === "keyring" ||
+ (store === "auto" && !(await hasCredentialFile(codexHome)))
+ ) {
+ await writePrivateConfig(history, "keyring");
+ } else if (
+ store === "auto" &&
+ (await savedKeyringHistory(codexHome)) === "pending"
+ ) {
+ await writePrivateConfig(history, "file");
+ }
await rm(marker, { force: true });
return;
}
- const temporary = join(
- codexHome,
- `.codex-security-logout-${randomUUID()}.tmp`,
- );
- try {
- const handle = await open(temporary, "wx", 0o600);
- try {
- await handle.chmod(0o600);
- await handle.writeFile("logged out\n", "utf8");
- await handle.sync();
- } finally {
- await handle.close();
- }
- await rename(temporary, marker);
- } finally {
- await rm(temporary, { force: true });
- }
+ await writePrivateConfig(marker, "logged out\n");
}
export async function codexSecurityCredentialAllowsAmbientImport(
@@ -2678,6 +2801,7 @@ export async function importAmbientAuth(
throw error;
}
await chmod(destination, 0o600);
+ await rememberStoredFile(isolatedHome);
return true;
} catch (error) {
throw new PluginBootstrapError(
diff --git a/sdk/typescript/src/version.ts b/sdk/typescript/src/version.ts
index 6a4d53117..c6db1b8da 100644
--- a/sdk/typescript/src/version.ts
+++ b/sdk/typescript/src/version.ts
@@ -29,6 +29,18 @@ export function updateNoticeEnabled(environment: NodeJS.ProcessEnv): boolean {
);
}
+/** @internal Whether the current CLI invocation runs through npm exec or npx. */
+export function invokedWithNpx(
+ environment: NodeJS.ProcessEnv,
+ path = new URL(import.meta.url).pathname,
+): boolean {
+ return (
+ environment["npm_command"] === "exec" ||
+ environment["npm_lifecycle_event"] === "npx" ||
+ path.includes("/_npx/")
+ );
+}
+
export function updateCommand(
environment: NodeJS.ProcessEnv = process.env,
entrypoint: string = fileURLToPath(import.meta.url),
@@ -44,11 +56,7 @@ export function updateCommand(
: entrypoint.replaceAll("\\", "/").toLowerCase();
const agent = (environment["npm_config_user_agent"] ?? "").toLowerCase();
- if (
- environment["npm_command"] === "exec" ||
- environment["npm_lifecycle_event"] === "npx" ||
- path.includes("/_npx/")
- ) {
+ if (invokedWithNpx(environment, path)) {
return `npx ${PACKAGE_NAME}@latest`;
}
if (path.includes("/.install/node_modules/")) {
diff --git a/sdk/typescript/tests-ts/api-credentials.test.ts b/sdk/typescript/tests-ts/api-credentials.test.ts
index 5b294da87..3c068777a 100644
--- a/sdk/typescript/tests-ts/api-credentials.test.ts
+++ b/sdk/typescript/tests-ts/api-credentials.test.ts
@@ -646,6 +646,39 @@ describe("CodexSecurity orchestration", () => {
expect(existsSync(dedicatedHome)).toBe(true);
});
+ test.each(["auto", "keyring"] as const)(
+ "does not seed a stale ambient file when the %s store may hold a different login",
+ async (store) => {
+ const root = await temporaryDirectory();
+ const ambient = join(root, "ambient");
+ const managed = join(root, "managed");
+ await mkdir(ambient, { mode: 0o700 });
+ await mkdir(managed, { mode: 0o700 });
+ await writeFile(
+ join(ambient, "auth.json"),
+ '{"token":"synthetic-ambient"}',
+ { mode: 0o600 },
+ );
+ const config = `cli_auth_credentials_store = "${store}"\n`;
+ await writeFile(join(managed, "config.toml"), config);
+ await setCodexSecurityCredentialLogout(managed, false);
+ expect(await initialCredentialsAvailable({}, ambient, managed)).toBe(
+ false,
+ );
+ expect(existsSync(join(managed, "auth.json"))).toBe(false);
+ // An explicitly file-backed destination must also check the source's active store.
+ await writeFile(
+ join(managed, "config.toml"),
+ 'cli_auth_credentials_store = "file"',
+ );
+ await writeFile(join(ambient, "config.toml"), config);
+ expect(await initialCredentialsAvailable({}, ambient, managed)).toBe(
+ false,
+ );
+ expect(existsSync(join(managed, "auth.json"))).toBe(false);
+ },
+ );
+
test("does not reimport ambient credentials after an explicit logout", async () => {
const root = await temporaryDirectory();
const ambientHome = join(root, "ambient-home");
diff --git a/sdk/typescript/tests-ts/api-file-profile-replay.test.ts b/sdk/typescript/tests-ts/api-file-profile-replay.test.ts
index d28a56b61..168fb6db2 100644
--- a/sdk/typescript/tests-ts/api-file-profile-replay.test.ts
+++ b/sdk/typescript/tests-ts/api-file-profile-replay.test.ts
@@ -349,6 +349,20 @@ test.each(
for (const path of [repository, home, runtimeHome, scanDir])
await mkdir(path, { mode: 0o700 });
const profilePath = join(home, "review.config.toml");
+ const ambientAuth = {
+ cli_auth_credentials_store: "file",
+ forced_login_method: "chatgpt",
+ forced_chatgpt_workspace_id: "synthetic-ambient-workspace",
+ };
+ await writeFile(join(home, "config.toml"), stringify(ambientAuth));
+ const authOverrides: JsonObject =
+ skills === "explicit"
+ ? {
+ cli_auth_credentials_store: "ephemeral",
+ forced_login_method: "api",
+ forced_chatgpt_workspace_id: "synthetic-explicit-workspace",
+ }
+ : {};
const fileProfile = (version: string) => ({
openai_base_url: `https://${version}.example.test/v1`,
model: version === "first" ? "initial-model" : "updated-model",
@@ -372,6 +386,7 @@ test.each(
});
await writeFile(profilePath, stringify(fileProfile("first")));
const explicit: JsonObject = {
+ ...authOverrides,
profile: "review",
analytics: { enabled: false },
shell_environment_policy: {
@@ -451,6 +466,8 @@ test.each(
await mergedCodexConfig({ codexOverrides: replay }, home),
);
expect(restored).toMatchObject({
+ ...ambientAuth,
+ ...authOverrides,
openai_base_url: explicitEndpoint ?? "https://reloaded.example.test/v1",
model: "updated-model",
model_reasoning_effort: "high",
diff --git a/sdk/typescript/tests-ts/api-login.test.ts b/sdk/typescript/tests-ts/api-login.test.ts
index a59a97c1f..17bf708db 100644
--- a/sdk/typescript/tests-ts/api-login.test.ts
+++ b/sdk/typescript/tests-ts/api-login.test.ts
@@ -1,8 +1,10 @@
import { existsSync } from "node:fs";
-import { writeFile } from "node:fs/promises";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
-import { afterEach, expect, test } from "bun:test";
+import { afterEach, expect, spyOn, test } from "bun:test";
+import { parse } from "smol-toml";
+import * as runtime from "../src/runtime.js";
import { TestClient } from "./support/api-client.js";
import { nodeCommand } from "./support/shell.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
@@ -51,3 +53,129 @@ process.exit(1);
}
},
);
+
+test("close cancels a login queued behind another credential-home owner", async () => {
+ const root = await temporaryDirectory();
+ const environment = {
+ CODEX_HOME: root,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ };
+ const home = await runtime.prepareCodexSecurityCredentialHome(environment);
+ const acquire = runtime.acquireCodexSecurityCredentialHomeLock;
+ const release = await acquire(home);
+ const queued = Promise.withResolvers<void>();
+ const observer = spyOn(
+ runtime,
+ "acquireCodexSecurityCredentialHomeLock",
+ ).mockImplementation((...args) => {
+ queued.resolve();
+ return acquire(...args);
+ });
+ const client = new TestClient(
+ {},
+ { environment, resolveCodexCommand: nodeCommand },
+ );
+ try {
+ const login = client.loginChatGPT();
+ await queued.promise;
+ const closed = client.close();
+ await expect(login).rejects.toMatchObject({ name: "AbortError" });
+ await closed;
+ } finally {
+ observer.mockRestore();
+ await release();
+ await client.close();
+ }
+});
+
+test("SDK sign-in honors the ambient login restriction and explicit overrides", async () => {
+ const root = await temporaryDirectory();
+ const ambient = join(root, "ambient");
+ await mkdir(ambient, { mode: 0o700 });
+ const environment = {
+ PATH: process.env["PATH"],
+ HOME: root,
+ USERPROFILE: root,
+ CODEX_HOME: ambient,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ };
+ const home = await runtime.prepareCodexSecurityCredentialHome(environment);
+ await writeFile(
+ join(home, "config.toml"),
+ 'cli_auth_credentials_store = "ephemeral"\n',
+ );
+ await writeFile(
+ join(ambient, "config.toml"),
+ 'forced_login_method = "chatgpt"\ncli_auth_credentials_store = "file"\n',
+ );
+ await using restricted = TestClient.withDependencies({ environment });
+ await expect(restricted.loginApiKey("synthetic-sdk-key")).rejects.toThrow(
+ "API key login is disabled",
+ );
+ expect(existsSync(join(home, "auth.json"))).toBe(false);
+
+ await using allowed = new TestClient(
+ { codexOverrides: { forced_login_method: "api" } },
+ { environment },
+ );
+ await allowed.loginApiKey("synthetic-sdk-key");
+ expect(
+ JSON.parse(await readFile(join(home, "auth.json"), "utf8")).OPENAI_API_KEY,
+ ).toBe("synthetic-sdk-key");
+ expect((await allowed.account()).authenticated).toBe(true);
+ await allowed.logout();
+ expect(existsSync(join(home, "auth.json"))).toBe(false);
+}, 30_000);
+
+test.each(["loginChatGPT", "loginChatGPTDeviceCode"] as const)(
+ "%s launches native sign-in with the requested storage and workspace",
+ async (method) => {
+ const root = await temporaryDirectory();
+ const ambient = join(root, "ambient");
+ await mkdir(ambient, { mode: 0o700 });
+ await writeFile(
+ join(ambient, "config.toml"),
+ 'cli_auth_credentials_store = "file"\n',
+ );
+ const script = join(root, "native-login.mjs");
+ const observed = join(root, "config-at-login.toml");
+ await writeFile(
+ script,
+ `
+import { readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+if (process.argv.includes("logout")) process.exit(0);
+if (process.argv.includes("status")) process.exit(1);
+writeFileSync(${JSON.stringify(observed)}, readFileSync(join(process.env.CODEX_HOME, "config.toml")));
+console.error("Open https://auth.example.test/device");
+console.error("User code: ABCD-EFGH");
+setInterval(() => {}, 1000);
+`,
+ );
+ await using client = new TestClient(
+ {
+ codexOverrides: { forced_chatgpt_workspace_id: "synthetic-workspace" },
+ },
+ {
+ environment: {
+ PATH: process.env["PATH"],
+ CODEX_HOME: ambient,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ },
+ resolveCodexCommand: () => ({ ...nodeCommand(), args: [script] }),
+ },
+ );
+ const login = await client[method]();
+ const lock = join(root, "state", "codex-home", ".codex-security-scan.lock");
+ expect(existsSync(lock)).toBe(true);
+ expect(parse(await readFile(observed, "utf8"))).toMatchObject({
+ cli_auth_credentials_store: "file",
+ forced_chatgpt_workspace_id: "synthetic-workspace",
+ });
+ const logout = client.logout();
+ login.cancel();
+ expect((await login.wait()).success).toBe(false);
+ await logout;
+ expect(existsSync(lock)).toBe(false);
+ },
+);
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 81586cd5e..46f872c2d 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -1692,6 +1692,17 @@ describe("CodexSecurity orchestration", () => {
forced_login_method: index % 2 ? "api" : "chatgpt",
forced_chatgpt_workspace_id: `synthetic-workspace-${index}`,
};
+ // The user's Codex config applies below explicit scan overrides.
+ const ambientHome = join(root, `ambient-${index}`);
+ const ambientAuthentication: Record<string, string> = {
+ cli_auth_credentials_store: "file",
+ forced_chatgpt_workspace_id: "synthetic-ambient-workspace",
+ };
+ await mkdir(ambientHome, { mode: 0o700 });
+ await writeFile(
+ join(ambientHome, "config.toml"),
+ 'cli_auth_credentials_store = "file"\nforced_chatgpt_workspace_id = "synthetic-ambient-workspace"\n',
+ );
return new TestClient(
{
pluginPath: PLUGIN_ROOT,
@@ -1704,6 +1715,7 @@ describe("CodexSecurity orchestration", () => {
},
{
environment: {
+ CODEX_HOME: ambientHome,
CODEX_SECURITY_STATE_DIR: stateDirectory,
AWS_BEARER_TOKEN_BEDROCK: `synthetic-bedrock-key-${index}`,
AWS_REGION: index % 2 === 0 ? "us-east-2" : "us-west-2",
@@ -1831,6 +1843,7 @@ describe("CodexSecurity orchestration", () => {
"forced_chatgpt_workspace_id",
] as const) {
const expected = (authentication[key] ??
+ ambientAuthentication[key] ??
DEFAULT_CODEX_CONFIG[key]) as string | undefined;
expect(workerConfig[key]).toEqual(expected);
expect(options.config?.[key]).toEqual(expected);
@@ -15738,9 +15751,11 @@ if __name__ == "__main__":
{},
{ parent: "scan-thread" },
);
- await (options.signal.aborted
- ? undefined
- : once(options.signal, "abort"));
+ if (!options.signal.aborted) {
+ await once(options.signal, "abort", {
+ signal: AbortSignal.timeout(5_000),
+ });
+ }
throw new DOMException("aborted", "AbortError");
}
return { events: events() };
@@ -15829,7 +15844,6 @@ if __name__ == "__main__":
postScanPrompt: "Do not spend another model turn.",
onLifecycle,
onWarning: (warning) => warnings.push(warning),
- signal: AbortSignal.timeout(5_000),
});
if (completion === "unavailable" || completion === "failed") {
await expect(result).rejects.toBeInstanceOf(
diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.ts
index 8d30b3cf4..9c2ff5646 100644
--- a/sdk/typescript/tests-ts/cli-authentication.test.ts
+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts
@@ -2,7 +2,8 @@ import { readJsonLines } from "./support/json.js";
import { runProviderSkill } from "./support/cli-provider-authentication.js";
import { TestClient } from "./support/api-client.js";
import { resolving } from "./support/promises.js";
-import { spawnSync } from "node:child_process";
+import { spawn, spawnSync } from "node:child_process";
+import { once } from "node:events";
import { existsSync } from "node:fs";
import {
chmod,
@@ -122,6 +123,75 @@ describe("CLI authentication", () => {
}
});
+ test.each([
+ [{}, "codex-security"],
+ [{ npm_command: "exec" }, "npx @openai/codex-security"],
+ ] as const)("points native sign-in hints at %p", async (environment, cli) => {
+ const chunks = [
+ "Open the URL. On a remote machine? Use `codex lo",
+ "gin --device-auth` instead.\nRun `codex logout` or `codex login`.\n",
+ "Try `printenv OPENAI_API_KEY | co",
+ "dex login --with-api-key` or `printenv CODEX_ACCESS_TOKEN | codex log",
+ "in --with-access-token`.\nUnquoted codex login, `codex login",
+ "-helper`, and partial `codex lo",
+ ];
+ const source = `for (const chunk of ${JSON.stringify(chunks)}) {
+ await new Promise(done => process.stderr.write(chunk, done));
+ await new Promise(done => setTimeout(done, 10));
+ }
+ process.exitCode = 3;`;
+ const write = process.stderr.write;
+ let stderr = "";
+ process.stderr.write = ((chunk: string | Uint8Array, done?: () => void) => {
+ stderr += chunk.toString();
+ done?.();
+ return true;
+ }) as typeof process.stderr.write;
+ try {
+ expect(
+ await runCodexSkillCommand(
+ ["-e", source],
+ undefined,
+ { command: process.execPath },
+ { PATH: process.env["PATH"], ...environment },
+ ),
+ ).toBe(3);
+ } finally {
+ process.stderr.write = write;
+ }
+ expect(stderr).toBe(
+ `Open the URL. On a remote machine? Use \`${cli} login --device-auth\` instead.\n` +
+ `Run \`codex logout\` or \`${cli} login\`.\n` +
+ `Try \`printenv OPENAI_API_KEY | ${cli} login --with-api-key\` or \`printenv CODEX_ACCESS_TOKEN | ${cli} login --with-access-token\`.\n` +
+ "Unquoted codex login, `codex login-helper`, and partial `codex lo",
+ );
+ });
+
+ test("reaps the native login and reports failure when the stderr reader closes", async () => {
+ const pidFile = join(stateDirectory, "native.pid");
+ const completed = join(stateDirectory, "login-completed");
+ const native = `require("node:fs").writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));
+ process.stderr.write("Open the sign-in URL.\\n");
+ setTimeout(() => require("node:fs").writeFileSync(${JSON.stringify(completed)}, "done"), 8000);`;
+ const wrapper = `import { runCodexSkillCommand } from ${JSON.stringify(new URL("../src/cli.ts", import.meta.url).href)};
+ const status = await runCodexSkillCommand(["-e", ${JSON.stringify(native)}], undefined, { command: process.execPath }).catch(() => 1);
+ process.exitCode = status === 0 ? 1 : 0;`;
+ const child = spawn(process.execPath, ["-e", wrapper], {
+ stdio: ["ignore", "ignore", "pipe"],
+ });
+ const closed = once(child, "close");
+ child.stderr.destroy();
+ const [exitCode] = await closed;
+ const pid = Number(await readFile(pidFile, "utf8"));
+ expect(pid).toBeGreaterThan(1);
+ // If the wrapper leaked its child, this assertion also cleans it up.
+ expect(() => process.kill(pid, "SIGKILL")).toThrow(
+ expect.objectContaining({ code: "ESRCH" }),
+ );
+ expect(existsSync(completed)).toBe(false);
+ expect(exitCode).toBe(0);
+ });
+
test("uses the same stable credential home for login, status, and logout", async () => {
const expectedHome = join(stateDirectory, "codex-home");
@@ -149,6 +219,56 @@ describe("CLI authentication", () => {
}
});
+ test("login follows native settings while status and logout keep the active store", async () => {
+ const home = await createCredentialHome();
+ const ambient = join(stateDirectory, "ambient");
+ await mkdir(ambient, { mode: 0o700 });
+ const managed = join(home, "config.toml");
+ const source = join(ambient, "config.toml");
+ await writeFile(
+ managed,
+ 'cli_auth_credentials_store = "file"\nmodel = "kept"\n',
+ );
+ await writeFile(
+ source,
+ [
+ 'cli_auth_credentials_store = "ephemeral"',
+ 'forced_login_method = "chatgpt"',
+ "[ghost_snapshot]",
+ "ignore_large_untracked_files = 9223372036854775807",
+ ].join("\n"),
+ );
+ const deps = dependencies();
+ const run = mock<typeof deps.runCodex>(resolving(0));
+ deps.runCodex = run;
+ const { runCli } = createCliTest(main);
+ for (const args of [["login", "status"], ["logout"]]) {
+ expect(await runCli(args, deps)).toBe(0);
+ expect(run.mock.lastCall?.[0]).toEqual(args);
+ expect(parseToml(await readFile(managed, "utf8"))).toEqual({
+ cli_auth_credentials_store: "file",
+ model: "kept",
+ });
+ }
+ expect(await runCli(["login"], deps)).toBe(0);
+ expect(run.mock.lastCall?.[0]).toEqual(["login"]);
+ expect(parseToml(await readFile(managed, "utf8"))).toEqual({
+ cli_auth_credentials_store: "ephemeral",
+ forced_login_method: "chatgpt",
+ model: "kept",
+ });
+ await rm(source);
+ expect(await runCli(["login"], deps)).toBe(0);
+ expect(parseToml(await readFile(managed, "utf8"))).toEqual({
+ cli_auth_credentials_store: "ephemeral",
+ model: "kept",
+ });
+ await writeFile(source, 'forced_login_method = "chatgpt"\ninvalid = [');
+ run.mockClear();
+ expect(await runCli(["login"], deps)).toBe(2);
+ expect(run).not.toHaveBeenCalled();
+ });
+
test("logout detaches only a separate ambient hard link before native failure", async () => {
const home = await createCredentialHome();
const auth = join(home, "auth.json");
@@ -2296,24 +2416,31 @@ describe("skill authentication", () => {
}),
{ mode: 0o600 },
);
+ const native = join(stateDirectory, "native.cjs");
+ await writeFile(
+ native,
+ [
+ "const args = process.argv.slice(2);",
+ 'if (args.at(-2) === "login" && args.at(-1) === "status") console.log("Logged in using ChatGPT");',
+ 'else console.log(JSON.stringify({type:"item.completed",item:{type:"agent_message",text:JSON.stringify({args:[process.execPath, ...args],home:process.env.CODEX_HOME})}}));',
+ ].join("\n"),
+ );
const run = async () => {
const stdout = capture();
- const source =
- 'console.log(JSON.stringify({type:"item.completed",item:{type:"agent_message",text:JSON.stringify({args:process.argv,home:process.env.CODEX_HOME})}}))';
- expect(
- await runCodexSkillCommand(
- ["-e", source, "--"],
- {
- command: "validate",
- auth,
- directory: skillDirectory,
- stdout: stdout.stream,
- stderr: capture().stream,
- },
- { command: process.execPath },
- environment,
- ),
- ).toBe(0);
+ const stderr = capture();
+ const exit = await runCodexSkillCommand(
+ [native],
+ {
+ command: "validate",
+ auth,
+ directory: skillDirectory,
+ stdout: stdout.stream,
+ stderr: stderr.stream,
+ },
+ { command: process.execPath, args: [native] },
+ environment,
+ );
+ expect(exit, stderr.text()).toBe(0);
return JSON.parse(stdout.text());
};
const { args, home: runtimeHome } = await run();
diff --git a/sdk/typescript/tests-ts/cli-launcher.test.ts b/sdk/typescript/tests-ts/cli-launcher.test.ts
index 0f09d38d5..691c606ec 100644
--- a/sdk/typescript/tests-ts/cli-launcher.test.ts
+++ b/sdk/typescript/tests-ts/cli-launcher.test.ts
@@ -1,4 +1,12 @@
-import { copyFile, mkdir, symlink, writeFile } from "node:fs/promises";
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+import {
+ copyFile,
+ mkdir,
+ readFile,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, test } from "bun:test";
import { VERSION } from "../src/index.js";
@@ -92,7 +100,7 @@ describe("CLI launcher", () => {
);
});
- test.each(["import", "main", "missing", "success"])(
+ test.each(["import", "runCli", "missing", "success"])(
"preserves installed-launcher %s results",
async (scenario) => {
await using temp = await scopedTemporaryDirectory(
@@ -109,9 +117,9 @@ describe("CLI launcher", () => {
await writeFile(
join(root, "dist", "cli.js"),
scenario === "success"
- ? "export const main = () => 7;\n"
- : scenario === "main"
- ? "export const main = async () => { throw process.env.TEST_DIAGNOSTIC; };\n"
+ ? "export const runCli = () => 7;\n"
+ : scenario === "runCli"
+ ? "export const runCli = async () => { throw process.env.TEST_DIAGNOSTIC; };\n"
: "throw new Error(process.env.TEST_DIAGNOSTIC);\n",
);
const child = await runCommand("node", [launcher], {
@@ -135,4 +143,68 @@ describe("CLI launcher", () => {
);
},
);
+
+ test.skipIf(process.platform === "win32")(
+ "exits after interrupting a native login with a full stderr pipe",
+ async () => {
+ await using temp = await scopedTemporaryDirectory("cli-login-signal-");
+ const root = temp.path;
+ const native = join(root, "native.cjs");
+ const pid = join(root, "native.pid");
+ await writeFile(
+ native,
+ `#!/usr/bin/env node
+ require("node:fs").writeFileSync(${JSON.stringify(pid)}, String(process.pid));
+ process.stderr.write("Open the sign-in URL.\\n");
+ setInterval(() => {}, 30000);`,
+ { mode: 0o700 },
+ );
+ const preload = join(root, "fill-stderr.mjs");
+ await writeFile(
+ preload,
+ `import { writeSync } from "node:fs";
+ const write = process.stderr.write.bind(process.stderr);
+ const padding = Buffer.alloc(4096);
+ try { while (true) writeSync(2, padding); }
+ catch (error) { if (error.code !== "EAGAIN") throw error; }
+ process.stderr.write = (...args) => {
+ const result = write(...args);
+ process.kill(process.pid, process.env.TEST_SIGNAL);
+ return result;
+ };`,
+ );
+
+ for (const [signal, status] of [
+ ["SIGINT", 130],
+ ["SIGTERM", 143],
+ ] as const) {
+ const child = spawn(
+ process.execPath,
+ ["--preload", preload, join(packageRoot, "src", "cli.ts"), "login"],
+ {
+ env: {
+ PATH: process.env["PATH"],
+ HOME: root,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ CODEX_CLI_PATH: native,
+ NO_UPDATE_NOTIFIER: "1",
+ TEST_SIGNAL: signal,
+ },
+ stdio: ["ignore", "ignore", "pipe"],
+ timeout: 8000,
+ killSignal: "SIGKILL",
+ },
+ );
+ const [code, exitSignal] = await once(child, "exit");
+ child.stderr.destroy();
+ const nativePid = Number(await readFile(pid, "utf8"));
+ expect(nativePid).toBeGreaterThan(1);
+ // Clean up a leaked native child if the launcher failed to reap it.
+ expect(() => process.kill(nativePid, "SIGKILL")).toThrow(
+ expect.objectContaining({ code: "ESRCH" }),
+ );
+ expect([code, exitSignal]).toEqual([status, null]);
+ }
+ },
+ );
});
diff --git a/sdk/typescript/tests-ts/cloud-publish.test.ts b/sdk/typescript/tests-ts/cloud-publish.test.ts
index 42cbde45e..2b7812464 100644
--- a/sdk/typescript/tests-ts/cloud-publish.test.ts
+++ b/sdk/typescript/tests-ts/cloud-publish.test.ts
@@ -15,6 +15,7 @@ import {
import {
codexSecurityCredentialHome,
setCodexSecurityCredentialLogout,
+ writeCredentialHomeConfig,
} from "../src/runtime.js";
import { copyCompletedScanFixture } from "./plugin-root.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
@@ -608,10 +609,9 @@ describe("Cloud publication", () => {
}),
{ mode: 0o600 },
);
- await writeFile(
- join(home, "config.toml"),
- 'cli_auth_credentials_store = "auto"\n',
- );
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: "auto",
+ });
const send = mock(async (_url: string, options: RequestInit) => {
expect(new Headers(options!.headers).get("ChatGPT-Account-ID")).toBe(
@@ -627,6 +627,27 @@ describe("Cloud publication", () => {
expect(send).toHaveBeenCalledTimes(1);
});
+ test.each(["auto", "keyring", "ephemeral"])(
+ "does not publish an ambient account copied into the dedicated %s store",
+ async (store) => {
+ const { scan, home: ambient, environment } = await fixture();
+ const home = codexSecurityCredentialHome(environment);
+ await mkdir(home, { recursive: true, mode: 0o700 });
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: store,
+ });
+ // A successful native keyring login removed the old file. Account status
+ // can subsequently import a different account's ambient credentials.
+ await setCodexSecurityCredentialLogout(home, false);
+ await fs.copyFile(join(ambient, "auth.json"), join(home, "auth.json"));
+ const send = mock(receiptResponse);
+ await expect(
+ publishScanToCloud(scan, { environment, fetch: send }),
+ ).rejects.toThrow("ChatGPT login already available to Codex Security");
+ expect(send).not.toHaveBeenCalled();
+ },
+ );
+
test("resolves missing or empty CODEX_HOME through the existing user-home helper", async () => {
const { scan, home, environment } = await fixture();
await mkdir(join(home, ".codex"), { mode: 0o700 });
@@ -719,7 +740,7 @@ describe("Cloud publication", () => {
await writeFile(
join(home, "config.toml"),
- 'cli_auth_credentials_store = "file"\n',
+ 'cli_auth_credentials_store = "file"\n[ghost_snapshot]\nignore_large_untracked_files = 9223372036854775807\n',
);
await publishScanToCloud(scan, {
environment,
diff --git a/sdk/typescript/tests-ts/config.test.ts b/sdk/typescript/tests-ts/config.test.ts
index 2d265c1d5..6743b3c4b 100644
--- a/sdk/typescript/tests-ts/config.test.ts
+++ b/sdk/typescript/tests-ts/config.test.ts
@@ -337,6 +337,36 @@ describe("Codex configuration", () => {
);
});
+ test("uses the sign-in settings from the user's Codex config below explicit overrides", async () => {
+ const home = await temporaryDirectory();
+ expect(
+ (await mergedCodexConfig({}, home))["cli_auth_credentials_store"],
+ ).toBe("auto");
+ await writeFile(
+ join(home, "config.toml"),
+ [
+ 'cli_auth_credentials_store = "file"',
+ 'forced_login_method = "chatgpt"',
+ 'model = "ambient-model"',
+ ].join("\n"),
+ );
+
+ const config = await mergedCodexConfig({}, home);
+ expect(config).toMatchObject({
+ cli_auth_credentials_store: "file",
+ forced_login_method: "chatgpt",
+ });
+ expect(config["model"]).toBe(DEFAULT_CODEX_CONFIG["model"]);
+ expect(
+ (
+ await mergedCodexConfig(
+ { codexOverrides: { cli_auth_credentials_store: "keyring" } },
+ home,
+ )
+ )["cli_auth_credentials_store"],
+ ).toBe("keyring");
+ });
+
test("resolves selected profile model and effort before root settings", async () => {
const scenarios = [
{
diff --git a/sdk/typescript/tests-ts/continuum-findings.test.ts b/sdk/typescript/tests-ts/continuum-findings.test.ts
index f823477ef..c951d6923 100644
--- a/sdk/typescript/tests-ts/continuum-findings.test.ts
+++ b/sdk/typescript/tests-ts/continuum-findings.test.ts
@@ -141,6 +141,57 @@ test("preserves dependency and posture evidence without classifying it as a code
});
});
+test("reads the weakness Continuum names in subCategory for its own findings", () => {
+ const { cweIds: _, vulnerabilities: __, ...detail } = continuumDetail();
+ const native = {
+ ...detail,
+ type: "CONTINUUM_CODE_VULN",
+ category: "CWE-137: Data Neutralization Issues",
+ subCategory: "CWE-89: Improper Neutralization of Special Elements",
+ vulnerabilities: [],
+ };
+ const weaknesses = (finding: unknown) =>
+ normalize(finding).findings[0]!.evidence.details?.weakness_ids;
+
+ expect(weaknesses(native)).toEqual(["CWE-89"]);
+ // Explicit IDs win, and other category text is not a weakness.
+ expect(weaknesses({ ...native, cweIds: ["CWE-20"] })).toEqual(["CWE-20"]);
+ expect(weaknesses({ ...native, subCategory: "Injection" })).toEqual([]);
+ expect(
+ normalizePreviousContinuumFindings(native, continuumRepository).findings[0]!
+ .evidence.details?.weakness_ids,
+ ).toEqual([]);
+});
+
+test("an inferred weakness cannot exclude a Cloud finding at its evidence limit", () => {
+ const { cweIds: _, ...detail } = continuumDetail();
+ const finding = {
+ ...detail,
+ type: "CONTINUUM_CODE_VULN",
+ subCategory: "CWE-89: SQL Injection",
+ vulnerabilities: [],
+ stepsToReproduce: Array<string>(31).fill("x".repeat(8192)).concat(""),
+ };
+ const original = normalizePreviousContinuumFindings(
+ finding,
+ continuumRepository,
+ ).findings[0]!.evidence;
+ const bytes = Buffer.byteLength(JSON.stringify(original));
+ finding.stepsToReproduce[31] = "x".repeat(256 * 1024 - bytes);
+ const result = normalize(finding);
+ expect(result.excluded).toEqual([]);
+ expect(result.findings[0]!.evidence).toMatchObject({
+ details: { weakness_ids: [] },
+ source_data: { finding },
+ });
+ // Leave room for the status timestamp, but not both it and the inferred CWE.
+ finding.stepsToReproduce[31] = finding.stepsToReproduce[31]!.slice(10);
+ expect(normalize(finding).findings[0]!.evidence).toMatchObject({
+ source_updated_at: Date.parse(finding.statusUpdatedAt) / 1000,
+ details: { weakness_ids: [] },
+ });
+});
+
test("keeps package-manager selectors in the native finding", () => {
const finding = {
...continuumSummary(),
diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.ts
index 391ae0b0d..122bb21d8 100644
--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts
@@ -116,7 +116,10 @@ import {
normalizeInspectorFindings,
normalizePreviousInspectorFindings,
} from "../src/inspector-findings.js";
-import { normalizePreviousContinuumFindings } from "../src/continuum-findings.js";
+import {
+ normalizePreviousContinuumFindings,
+ readContinuumFindings,
+} from "../src/continuum-findings.js";
import {
trivyReport,
trivyReportWithManyLocations,
@@ -4545,6 +4548,37 @@ test("Checkmarx publishes a native SAST finding only to its declared Cloud repos
expect(f.posts[1]).toBe(f.posts[0]!);
});
+test("explains a Cloud account or deployment without the import catalog", async () => {
+ const f = await fixture(continuumDetail(), continuumRepository);
+ const missing = (status: number) => ({
+ ...f.deps,
+ fetch: async () =>
+ Response.json({ error: { message: "Not found" } }, { status }),
+ });
+ const selected = {
+ ...options,
+ provider: "continuum" as const,
+ sourceKey: "continuum/example/project",
+ sourceRepositoryUrl: continuumRepository,
+ };
+ await expect(
+ prepareExternalPublication(f.file, selected, missing(404)),
+ ).rejects.toThrow(
+ "Cloud import failed (HTTP 404). Not found. Cloud import is not available for this account or deployment.",
+ );
+ await expect(
+ prepareExternalPublication(f.file, selected, {
+ ...f.deps,
+ fetch: async () => new Response(null, { status: 404 }),
+ }),
+ ).rejects.toThrow(
+ "Cloud import failed (HTTP 404). Cloud import is not available for this account or deployment.",
+ );
+ await expect(
+ prepareExternalPublication(f.file, selected, missing(500)),
+ ).rejects.toThrow(/^Cloud import failed \(HTTP 500\)\. Not found$/u);
+});
+
test("Continuum Cloud publication checks repository and provider and replays an interrupted request", async () => {
const detail = continuumDetail();
const f = await fixture(detail, continuumRepository);
@@ -4591,6 +4625,70 @@ test("Continuum Cloud publication checks repository and provider and replays an
expect(f.posts).toEqual([f.posts[0]!, f.posts[0]!]);
});
+test.each(["single detail", "selected array"])(
+ "a Continuum %s reuses its interrupted 0.9.x request after CWE enrichment",
+ async (shape) => {
+ const { cweIds: _, ...detail } = continuumDetail();
+ const native = {
+ ...detail,
+ source: "CONTINUUM",
+ type: "CONTINUUM_CODE_VULN",
+ vulnerabilities: [],
+ subCategory: "CWE-89: SQL Injection",
+ };
+ const f = await fixture(
+ shape === "single detail" ? native : [native],
+ continuumRepository,
+ );
+ const settings = {
+ ...options,
+ provider: "continuum" as const,
+ sourceRepositoryUrl: continuumRepository,
+ };
+ // 0.9.x retained the status timestamp but did not infer a structured CWE.
+ const released = normalizePreviousContinuumFindings(
+ native,
+ continuumRepository,
+ );
+ released.findings[0]!.evidence.source_updated_at =
+ Date.parse(native.statusUpdatedAt) / 1000;
+ expect(hash("sha256", canonicalJson(released.findings))).toBe(
+ "2d1bca6f9e46758b8b7d9d679e5e7912a9dd8f99ca4c3cb6889b40eaa4b2506e",
+ );
+ const original = await prepareNormalizedExternalPublication(
+ released,
+ settings,
+ f.deps,
+ );
+ const pending = await f.loseResponse(original);
+
+ const prepare = () => prepareExternalPublication(f.file, settings, f.deps);
+ const retry = await prepare();
+ expect(retry.preview.resumed).toBe(true);
+ expect(retry.preview.requests).toEqual(original.preview.requests);
+ expect(await f.loseResponse(retry)).toBe(pending);
+
+ const sdk = await readContinuumFindings(f.file, continuumRepository);
+ const prepareSdk = (input: ExternalFindings) =>
+ prepareNormalizedExternalPublication(input, settings, f.deps);
+ const edited = structuredClone(sdk);
+ edited.findings[0]!.evidence.details!.weakness_ids = ["CWE-20"];
+ expect((await prepareSdk(edited)).preview.resumed).toBe(false);
+
+ const sdkRetry = await prepareSdk(sdk);
+ expect(sdkRetry.preview.requests).toEqual(original.preview.requests);
+ expect(await f.loseResponse(sdkRetry)).toBe(pending);
+ const restored = await prepareSdk(JSON.parse(JSON.stringify(sdk)));
+ expect(restored.preview.resumed).toBe(true);
+ expect((await restored.publish()).verified).toBe(1);
+ expect(f.posts).toEqual(Array(4).fill(f.posts[0]));
+ expect(await Bun.file(pending).exists()).toBe(false);
+ expect(
+ (await prepare()).preview.findings[0]!.evidence.details?.weakness_ids,
+ ).toEqual(["CWE-89"]);
+ },
+);
+
test("Inspector publication checks its source and reuses the finding ARN", async () => {
const { f, input, prepare } = await inspectorPublicationFixture();
const prepared = await prepare();
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index d46e8f91c..08a2cadbf 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -75,6 +75,8 @@ import {
acquireCodexSecurityCredentialHomeLock,
bundledPluginCandidates,
canonicalizeModelSafePath,
+ beginCredentialLogin,
+ credentialHomeUsesFileStorage,
codexSecurityCredentialAllowsAmbientImport,
codexSecurityCredentialHome,
codexSecurityHasStoredFileCredentials,
@@ -102,6 +104,8 @@ import {
requireTrustedOutputAncestor,
runWorkbench,
workbenchEnvironment,
+ writeCredentialHomeConfig,
+ logoutCredentialHome,
setCodexSecurityCredentialLogout,
streamWindowsCredentialAclDescriptors,
windowsCredentialAncestorAclScript,
@@ -3806,6 +3810,122 @@ describe("runtime directories and plugin Python boundary", () => {
}
});
+ test.each(["upgraded", "new"] as const)(
+ "logout retries a previous keyring login after revoking a newer file credential (%s)",
+ async (origin) => {
+ const { home, root } = await credentialHome(true);
+ const file = join(home, "auth.json");
+ if (origin === "upgraded") {
+ await writeFile(
+ join(home, "config.toml"),
+ 'cli_auth_credentials_store = "auto"\n',
+ );
+ } else {
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: "auto",
+ });
+ // Successful auto sign-in with no fallback file used the keyring.
+ await setCodexSecurityCredentialLogout(home, false);
+ }
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: "file",
+ });
+ await writeFile(file, "synthetic credential", { mode: 0o600 });
+ await setCodexSecurityCredentialLogout(home, false);
+ let keyringAvailable = false;
+ const revoke = mock(async (store?: string) => {
+ if (store === "keyring") return keyringAvailable ? 0 : 17;
+ await rm(file, { force: true });
+ return 0;
+ });
+ expect(await logoutCredentialHome(home, root, revoke)).toBe(17);
+ expect(revoke.mock.calls).toEqual([[undefined], ["keyring"]]);
+ expect(await codexSecurityCredentialAllowsAmbientImport(home)).toBe(
+ false,
+ );
+ keyringAvailable = true;
+ revoke.mockClear();
+ expect(await logoutCredentialHome(home, root, revoke)).toBe(0);
+ expect(revoke.mock.calls).toEqual([["keyring"]]);
+ revoke.mockClear();
+ expect(await logoutCredentialHome(home, root, revoke)).toBe(0);
+ expect(revoke.mock.calls).toEqual([[undefined]]);
+ },
+ );
+ test("a confirmed file-only home can log out after the configured backend changes", async () => {
+ const { home, root } = await credentialHome(true);
+ const path = join(home, "auth.json");
+ await writeFile(path, "synthetic key", { mode: 0o600 });
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: "auto",
+ });
+ await beginCredentialLogin(home);
+ expect(await credentialHomeUsesFileStorage(home)).toBe(false);
+ // Native auto fell back to the file because no keyring was available.
+ await setCodexSecurityCredentialLogout(home, false);
+ expect(await credentialHomeUsesFileStorage(home)).toBe(true);
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: "keyring",
+ });
+ const revoke = mock(async (_store?: string) => {
+ await rm(path);
+ return 0;
+ });
+ expect(await logoutCredentialHome(home, root, revoke)).toBe(0);
+ expect(revoke.mock.calls).toEqual([["file"]]);
+ });
+
+ test.each(["auto", "file"])(
+ "logout finds a credential native auto refreshed into the keyring (current store: %s)",
+ async (store) => {
+ const { home, root } = await credentialHome(true);
+ const path = join(home, "auth.json");
+ await writeFile(path, "synthetic credential", { mode: 0o600 });
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: "auto",
+ });
+ // Auto refresh saves to the keyring and unlinks the former file.
+ await rm(path);
+ if (store === "file")
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: "file",
+ });
+ const revoke = mock(async (_store?: string) => 0);
+ expect(await logoutCredentialHome(home, root, revoke)).toBe(0);
+ expect(revoke.mock.calls).toEqual([
+ [store === "auto" ? undefined : "keyring"],
+ ]);
+ revoke.mockClear();
+ expect(await logoutCredentialHome(home, root, revoke)).toBe(0);
+ expect(revoke.mock.calls).toEqual([
+ [store === "auto" ? "file" : undefined],
+ ]);
+ },
+ );
+
+ test.each(["auto", "keyring"])(
+ "logout clears an interrupted first %s login even after a later file login",
+ async (store) => {
+ const { home, root } = await credentialHome(true);
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: store,
+ });
+ await beginCredentialLogin(home);
+ // Native persisted the grant but the wrapper never got its success callback.
+ await writeCredentialHomeConfig(home, {
+ cli_auth_credentials_store: "file",
+ });
+ const file = join(home, "auth.json");
+ await writeFile(file, "second synthetic login", { mode: 0o600 });
+ await setCodexSecurityCredentialLogout(home, false);
+ const revoke = mock(async (backend?: string) => {
+ if (backend === undefined) await rm(file);
+ return 0;
+ });
+ expect(await logoutCredentialHome(home, root, revoke)).toBe(0);
+ expect(revoke.mock.calls).toEqual([[undefined], ["keyring"]]);
+ },
+ );
test("prevents ambient credential imports after an explicit logout", async () => {
const { home } = await credentialHome(true);
diff --git a/sdk/typescript/tests-ts/support/replay-worker-boundary.ts b/sdk/typescript/tests-ts/support/replay-worker-boundary.ts
index 3b23ffa92..a783de335 100644
--- a/sdk/typescript/tests-ts/support/replay-worker-boundary.ts
+++ b/sdk/typescript/tests-ts/support/replay-worker-boundary.ts
@@ -107,6 +107,9 @@ async function assertWorkerReplay(
selected = deepMerge(selected, parse(argv[++index]!) as JsonObject);
for (const key of [
"analytics",
+ "cli_auth_credentials_store",
+ "forced_login_method",
+ "forced_chatgpt_workspace_id",
"openai_base_url",
"shell_environment_policy",
"otel",