OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix: preserve diagnostic text without secret redaction (#1179)
mldangelo-oai2fd7880490f2
diff --git a/AGENTS.md b/AGENTS.mdindex 07f8161fd..2ae08790c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -8,7 +8,8 @@ Codex Security is a thin wrapper around Codex and its security plugin.approved path.- Do not add arbitrary limits or extra checks without a real problem to solve.- Do not let optional logging or progress updates stop the main task.-- Keep protections for credentials, unsafe paths, and settings the user explicitly requests.+- Keep credential access, storage, and configuration protections, unsafe-path+ checks, and settings the user explicitly requests.- Prefer straightforward code and tests for real behavior.- Mention another `openai/` repository in comments or pull request descriptionsonly after checking that it is public. If you cannot confirm its visibility,@@ -39,21 +40,28 @@ child-process boundary. Keep per-scan settings isolated from concurrent scans.hypothetical problems. State the concrete failure it fixes.- When extending an existing command, preserve its output behavior. Do notintroduce a new sanitization policy for names, paths, or status messages.-- Keep existing credential, unsafe-path, and scan-integrity protections.- Do not extend them to unrelated values without a demonstrated need.+- Keep existing protections for credential access, storage, and configuration,+ unsafe paths, and scan integrity. Do not extend them to unrelated values+ without a demonstrated need.- Do not invent a restriction and then add tests whose only purpose is toenforce that restriction.-## CLI secret and log redaction--- Do not add or reintroduce CLI-layer secret or log redaction, including- credential-pattern filtering that masks or replaces diagnostic messages.- Keep CLI diagnostics intact for local troubleshooting.-- This guidance concerns CLI implementation behavior. It does not authorize- removing or bypassing upstream SDK or native Codex protections, credential- handling safeguards, or controls on persisted or published artifacts.-- Local output may contain sensitive information. Keep it private and review- it before sharing; the public disclosure requirements below still apply.+## Preserve diagnostic text++- Do not add or reintroduce wrapper-owned secret or credential redaction,+ including as a security-review follow-up. This applies to CLI and SDK+ diagnostics, verbose logs, progress displays, saved failures, publication+ receipts, and patch-risk reports and summaries.+- Do not mask credential-shaped substrings, replace messages with `[redacted]`,+ or suppress diagnostic details solely because they might contain credentials.+ Do not add redaction flags, environment variables, or opt-out settings.+- Keep terminal-control escaping, unsafe-path and link validation, credential+ access, storage, and configuration controls, and upstream Codex protections.+ These do not authorize adding message redaction in this wrapper. This policy+ does not require changing authentication advice or serializing internal+ request objects.+- Continue reviewing public changes and artifacts for sensitive information+ before publication as required below.## Public CLI changesdiff --git a/sdk/typescript/AGENTS.md b/sdk/typescript/AGENTS.mdindex 6fdcaa3f2..857bbd1db 100644--- a/sdk/typescript/AGENTS.md+++ b/sdk/typescript/AGENTS.md@@ -20,7 +20,10 @@ outside an approved path.- Reuse Codex APIs and shared helpers instead of adding extra trust gates or orchestration.- Root read and workspace write are enough for the sandbox.- Treat repository paths, symlinks, archives, and other repository-controlled data as untrusted.-- Keep protections for credentials, unsafe paths, scan integrity, and settings the user explicitly requests.+- Keep credential access, storage, and configuration protections, unsafe-path+ checks, scan integrity, and settings the user explicitly requests.+- Follow the root `AGENTS.md` diagnostic-text policy: do not reintroduce secret+ redaction in CLI/SDK output or saved diagnostics, or add a setting to control it.- Do not add arbitrary size, count, depth, or buffering limits to local inputs or Codex output. Keep limits required by an actual security boundary or an upstream contract.- Do not let optional logging, progress, or cost tracking stop a scan. Still enforce limits the user requests, such as `--max-cost`.- Preserve completed scan artifacts and keep database migrations append-only.diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 57e1a744c..14cb10068 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -959,7 +959,6 @@ restrictions.| `CODEX_SECURITY_LINEAR_TEAM`, `CODEX_SECURITY_LINEAR_PROJECT` | Default team and project for completed-scan publication. || `CODEX_SECURITY_LINEAR_API_KEY` | Personal API key for Linear patching and direct publication. || `CODEX_SECURITY_LOG_LEVEL` | CLI-only; `debug` enables verbose diagnostics. |-| `CODEX_SECURITY_REDACT_LOGS` | CLI-only; `0` disables diagnostic redaction. Unset or any other value keeps it enabled. || `LOG_LEVEL` | CLI-only fallback when `CODEX_SECURITY_LOG_LEVEL` is unset or blank. || `CODEX_SECURITY_STATE_DIR` | Private scan-history, workbench, and default artifact directory. || `CODEX_SECURITY_PROJECT_CONFIG` | Trusted project file for `scan`, `bulk-scan`, `scan-components`, and `info`; `-c` wins. Unset by default. |@@ -981,68 +980,23 @@ Python lookup order: `--python` (on `scan`, `bulk-scan`, or `export`) or SDKon `PATH` (`py` also works on Windows). `CODEX_SECURITY_STATE_DIR` overrides`CODEX_HOME` for state storage. Keep state and results outside the repository.-### Troubleshooting redacted output+### Troubleshooting-Verbosity and redaction are independent controls. By default, scans show progress,-state transitions, warnings, and summaries. Add `--verbose` or set+By default, scans show progress, state transitions, warnings, and summaries.+Add `--verbose` or set`CODEX_SECURITY_LOG_LEVEL=debug` to include lifecycle, configuration, retry,and worker diagnostics on stderr. `LOG_LEVEL=debug` is the fallback when-`CODEX_SECURITY_LOG_LEVEL` is unset or blank. Verbosity does not disable redaction.--Only the exact value `CODEX_SECURITY_REDACT_LOGS=0` disables CLI diagnostic-redaction. An unset variable or any other value retains the default redaction-behavior. Disabling redaction does not enable verbose diagnostics.--| Verbose diagnostics | CLI redaction | Behavior |-| ------------------- | ------------- | ---------------------------------------------------- |-| Off (default) | On (default) | Normal progress and summaries with redaction. |-| On | On | Additional diagnostics on stderr with redaction. |-| Off | Off | Normal output detail with diagnostic redaction off. |-| On | Off | Additional diagnostics on stderr with redaction off. |--Scan errors and warnings use the same checks in plain stderr, verbose message-fields, and JSON errors. Progress/dashboard redaction also honors the setting.-The checks detect recognizable credentials and sensitive field assignments.-A match replaces the whole message or value-with `[redacted]`. For example, `token=example` triggers redaction even if the-value is synthetic. Diagnostic event names, error classifications, counters,-and fixed metadata remain available when a message is redacted. Dedicated path-fields keep their paths, and observer warnings keep the observer's name while-redacting the error detail.--For local troubleshooting with verbose diagnostics and redaction disabled:+`CODEX_SECURITY_LOG_LEVEL` is unset or blank.```bash-CODEX_SECURITY_REDACT_LOGS=0 npx @openai/codex-security scan . --verbose+npx @openai/codex-security scan . --verbose```-In PowerShell, set it in the current shell and remove it afterward:--```powershell-$env:CODEX_SECURITY_REDACT_LOGS = "0"-npx @openai/codex-security scan . --verbose-Remove-Item Env:CODEX_SECURITY_REDACT_LOGS-```--Deep Scan discovery and reducer worker displays, including resumed workers,-follow the current CLI invocation's diagnostic settings. These settings are not-saved in scan recipes; select them again when running `scans resume` or-`scans rerun` if needed.--Neither control enables additional raw session capture or uploads logs. Raw-session log capture and the original model output and results remain unchanged;-paths are not generally redacted. Output can still contain source code,-credentials, and other sensitive information, especially with redaction disabled.-Keep it private and review it before sharing or uploading it.--The redaction setting does not change credential configuration, SDK error-sanitization, stored failure summaries, or publication receipts. It cannot recover-content already replaced with `[redacted]`, including errors sanitized before-reaching the CLI, and does not control native Codex or OpenTelemetry log and-trace redaction. Deep Scan workers use native Codex; this setting applies when-the parent CLI displays their diagnostics. Patch-risk report diagnostics honor-the opt-out, but the summary used in a published pull request keeps its credential-redaction.+Codex Security preserves diagnostic text, including credential-shaped values,+in CLI output, stored failures, publication receipts, and patch-risk summaries.+Verbosity controls the amount of diagnostic detail. Native Codex and upstream+SDK output may already have been redacted before reaching Codex Security.+Review output and artifacts for sensitive information before sharing them.### Progress and costdiff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 193954b2f..8160fbde1 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -116,7 +116,6 @@ import {OutputDirectoryError,OutputDirectoryNotEmptyError,errorMessage,- safeErrorMessage,ScanCostLimitExceededError,ScanInterruptedError,} from "./errors.js";@@ -1065,7 +1064,7 @@ export class CodexSecurity {if (options.maxCostUsd !== undefined) budgetController.abort(error);elsewarn(- `Could not track policy-generation cost: ${safeErrorMessage(error)}`,+ `Could not track policy-generation cost: ${errorMessage(error)}`,);},});@@ -1087,7 +1086,7 @@ export class CodexSecurity {tracker.start(event["thread_id"]);}},- onReconnect: (message) => warn(safeErrorMessage(message)),+ onReconnect: warn,});usage = turn.usage;signal.throwIfAborted();@@ -1099,7 +1098,7 @@ export class CodexSecurity {const snapshot = await tracker.stop(usage).catch((error: unknown) => {if (options.maxCostUsd !== undefined) throw error;warn(- `Could not track policy-generation cost: ${safeErrorMessage(error)}`,+ `Could not track policy-generation cost: ${errorMessage(error)}`,);const cost = estimateScanCost(model.model, usage);if (cost !== null) reportCost(cost);@@ -1130,7 +1129,7 @@ export class CodexSecurity {if (!stopped)await tracker.stop(usage)- .catch((error: unknown) => warn(safeErrorMessage(error)));+ .catch((error: unknown) => warn(errorMessage(error)));}};return await runSecurityPolicyStages({@@ -1980,7 +1979,7 @@ export class CodexSecurity {"onWarning",options.onWarning,options.onObserverError,- `Could not save scan session: ${safeErrorMessage(error)}`,+ `Could not save scan session: ${errorMessage(error)}`,);}},@@ -2375,7 +2374,7 @@ export class CodexSecurity {await writeCustomValidationStatus(scanDir, {scanId: activeScan.id,status: "incomplete",- reason: safeErrorMessage(failure),+ reason: errorMessage(failure),}).catch(() => undefined);}try {@@ -2383,9 +2382,8 @@ export class CodexSecurity {"fail-scan","--scan-id",activeScan.id,- // Scan history can be shared; never persist credential-bearing failures."--message",- safeErrorMessage(failure).slice(0, 2400),+ errorMessage(failure).slice(0, 2400),...(snapshot?.cost? ["--cost-json", JSON.stringify(snapshot.cost)]: []),@@ -3298,7 +3296,7 @@ export class CodexSecurity {"--scan-id",activeScan.id,"--message",- safeErrorMessage(error).slice(0, 2400),+ errorMessage(error).slice(0, 2400),]).catch(() => undefined);}if (this.#closed) this.#requireOpen();diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex a46fa5b97..a24418efd 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -139,8 +139,6 @@ import {OutputInsideProtectedRootError,PluginPythonUnavailableError,errorMessage,- safeErrorMessage,- logErrorMessage,ScanCostLimitExceededError,ScanInterruptedError,} from "./errors.js";@@ -562,8 +560,7 @@ function publicationIssueUrl(value: string | undefined): string | undefined {value === undefined ||value !== value.trim() ||value !== stripVTControlCharacters(value) ||- /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u.test(value) ||- safeErrorMessage(value) !== value+ /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u.test(value)) {return undefined;}@@ -607,7 +604,7 @@ function renderPublicationSummary(for (const issue of result.created.slice(0, 5)) {const identifier =- stripVTControlCharacters(safeErrorMessage(issue.issueIdentifier))+ stripVTControlCharacters(issue.issueIdentifier).replaceAll(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu, " ").replace(/\s+/gu, " ").trim() || "Unknown Linear issue";@@ -661,8 +658,6 @@ class PublicationProgressPresenter {presentation: "publication",clock: this.#dependencies,color: this.#dependencies.environment["NO_COLOR"] === undefined,- sanitize: (value) =>- logErrorMessage(value, this.#dependencies.environment),});dashboard.setStage("Connecting to Linear");try {@@ -782,9 +777,7 @@ class PublicationProgressPresenter {}#write(message: string, compact = false): void {- const sanitized = diagnosticValue(- logErrorMessage(message, this.#dependencies.environment),- );+ const sanitized = diagnosticValue(message);if (!compact) {this.#stream.write(`${sanitized}\n`);return;@@ -835,8 +828,6 @@ class FindingProgressPresenter {presentation: "verification",clock: this.#dependencies,color: this.#dependencies.environment["NO_COLOR"] === undefined,- sanitize: (value) =>- logErrorMessage(value, this.#dependencies.environment),});dashboard.setPublicationProgress(0, this.#total);dashboard.setStage(`Verifying findings · 0/${this.#total}`);@@ -859,7 +850,7 @@ class FindingProgressPresenter {public startPatch(finding: Finding, index: number): void {try {this.#progress.startTimer(- `Patching ${index + 1}/${this.#total} · ${safePatchText(finding.title, this.#dependencies.environment)}`,+ `Patching ${index + 1}/${this.#total} · ${safePatchText(finding.title)}`,);} catch {this.stop();@@ -966,9 +957,7 @@ class FindingProgressPresenter {#write(message: string): void {try {this.#progress.writeAboveTimer(() => {- this.#stream.write(- `${safePatchText(message, this.#dependencies.environment)}\n`,- );+ this.#stream.write(`${safePatchText(message)}\n`);});} catch {}}@@ -2286,9 +2275,7 @@ export async function main(verbose: z.boolean().default(false)- .describe(- "Print additional scan diagnostics to stderr without disabling redaction. Set CODEX_SECURITY_REDACT_LOGS=0 to opt out (may expose credentials).",- ),+ .describe("Print additional scan diagnostics to stderr."),}),output: z.record(z.string(), z.unknown()).optional(),async run({ args, error: incurError, options }) {@@ -2376,9 +2363,7 @@ export async function main(verbose: z.boolean().default(false)- .describe(- "Print additional scan diagnostics to stderr without disabling redaction. Set CODEX_SECURITY_REDACT_LOGS=0 to opt out (may expose credentials).",- ),+ .describe("Print additional scan diagnostics to stderr."),}),output: z.record(z.string(), z.unknown()).optional(),async run({ args, error: incurError, format, options }) {@@ -2582,10 +2567,7 @@ export async function main(signal === "SIGINT"? "Publication canceled by Ctrl-C.": "Publication terminated by SIGTERM.";- const recovery =- error === signal- ? ""- : ` ${diagnosticValue(logErrorMessage(error, dependencies.environment))}`;+ const recovery = error === signal ? "" : ` ${diagnosticValue(error)}`;errorOutput.write(`codex-security: ${reason}${recovery}\n`);exitCode = signal === "SIGINT" ? 130 : 143;} else {@@ -2716,7 +2698,7 @@ export async function main(const recovery =error === undefined || error === signal? ""- : ` ${diagnosticValue(logErrorMessage(error, dependencies.environment))}`;+ : ` ${diagnosticValue(error)}`;errorOutput.write(`codex-security: ${reason}${recovery}\n`);exitCode = signal === "SIGINT" ? 130 : 143;return true;@@ -3081,10 +3063,7 @@ export async function main(});cloudBatch.results.push({ scanDir: directory, ...result });} catch (error) {- const message = logErrorMessage(- error,- dependencies.environment,- );+ const message = errorMessage(error);cloudBatch.failed.push({scanDir: directory,...(scanId === undefined ? {} : { scanId }),@@ -3093,7 +3072,7 @@ export async function main(if (controller.signal.aborted) throw error;exitCode = 2;errorOutput.write(- `codex-security: ${diagnosticValue(logErrorMessage(scanId ?? directory, dependencies.environment))}: ${diagnosticValue(message)}\n`,+ `codex-security: ${diagnosticValue(scanId ?? directory)}: ${diagnosticValue(message)}\n`,);}}@@ -3173,9 +3152,7 @@ export async function main(if ("warnings" in result && Array.isArray(result.warnings)) {for (const warning of result.warnings) {if (typeof warning !== "string") continue;- errorOutput.write(- `codex-security: ${diagnosticValue(logErrorMessage(warning, dependencies.environment))}\n`,- );+ errorOutput.write(`codex-security: ${diagnosticValue(warning)}\n`);}}if (@@ -3194,9 +3171,7 @@ export async function main(return { ...result };} catch (error) {if (!finishCancellation(error)) {- errorOutput.write(- `codex-security: ${options.to === "cloud" ? logErrorMessage(error, dependencies.environment) : errorMessage(error)}\n`,- );+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);exitCode = 2;}return cloudBatch;@@ -3315,7 +3290,7 @@ export async function main();} else {exitCode = 2;- errorOutput.write(`codex-security: ${errorMessage(error)}\n`);+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);}return undefined;} finally {@@ -3325,8 +3300,7 @@ export async function main(},});const cli = Cli.create("codex-security", {- description:- "Find, review, and fix security issues in your code. Set CODEX_SECURITY_REDACT_LOGS=0 to disable CLI diagnostic redaction (may expose credentials).",+ description: "Find, review, and fix security issues in your code.",version: VERSION,mcp: {command: "npx --yes @openai/codex-security --mcp",@@ -3516,9 +3490,9 @@ export async function main(? policyDisplayData(outcome.data): outcome.data;} catch (error) {- const message = logErrorMessage(error, dependencies.environment);+ const message = errorMessage(error);try {- errorOutput.write(`codex-security: ${message}\n`);+ errorOutput.write(`codex-security: ${diagnosticValue(message)}\n`);} catch {}return fail(message, 2);}@@ -3560,9 +3534,7 @@ export async function main(verbose: z.boolean().default(false)- .describe(- "Print additional scan diagnostics to stderr without disabling redaction. Set CODEX_SECURITY_REDACT_LOGS=0 to opt out (may expose credentials).",- ),+ .describe("Print additional scan diagnostics to stderr."),safetyIdentifier: optionValue("--safety-identifier").optional().describe(@@ -3780,10 +3752,7 @@ export async function main(exitCode = outcome.exitCode;if (outcome.error !== undefined) {if (format === "json" || format === "jsonl") {- const message = logErrorMessage(- outcome.error,- dependencies.environment,- );+ const message = errorMessage(outcome.error);if (!argv.includes("--full-output"))return { status: "failed", code: "SCAN_FAILED", message };// Incur would wrap returned data in an ok: true envelope.@@ -3943,7 +3912,7 @@ export async function main(} catch (error) {const signal = controller.signal.reason;errorOutput.write(- `codex-security: ${signal === "SIGINT" || signal === "SIGTERM" ? "Owner suggestions canceled." : logErrorMessage(error, dependencies.environment)}\n`,+ `codex-security: ${signal === "SIGINT" || signal === "SIGTERM" ? "Owner suggestions canceled." : diagnosticValue(error)}\n`,);exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2;return undefined;@@ -4045,7 +4014,7 @@ export async function main(} catch (error) {const signal = controller.signal.reason;errorOutput.write(- `codex-security: ${signal === "SIGINT" || signal === "SIGTERM" ? "Severity classification canceled." : logErrorMessage(error, dependencies.environment)}\n`,+ `codex-security: ${signal === "SIGINT" || signal === "SIGTERM" ? "Severity classification canceled." : diagnosticValue(error)}\n`,);exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2;return undefined;@@ -4174,7 +4143,7 @@ export async function main(`codex-security: ${signal === "SIGINT" || signal === "SIGTERM"? "Deduplication canceled. Findings are unchanged."- : logErrorMessage(error, dependencies.environment)+ : diagnosticValue(error)}\n`,);exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2;@@ -4364,8 +4333,6 @@ export async function main(showCost: options.showCost,clock: dependencies,color: dependencies.environment["NO_COLOR"] === undefined,- sanitize: (value) =>- logErrorMessage(value, dependencies.environment),input: process.stdin,onInterrupt,});@@ -4428,7 +4395,7 @@ export async function main(if (dashboard !== null) dashboard.updateComponent(component);elseerrorOutput.write(- `codex-security: ${component.name} ${component.status}${component.error === undefined ? "" : `: ${component.error}`}\n`,+ `codex-security: ${component.name} ${component.status}${component.error === undefined ? "" : `: ${diagnosticValue(component.error)}`}\n`,);},onComplete: (result) => {@@ -4771,7 +4738,7 @@ export async function main(onProgress: ({ repository, status, attempt, error, warning }) => {const detail = error ?? warning;errorOutput.write(- `codex-security: ${repository} ${status} (attempt ${attempt})${detail === undefined ? "" : `: ${errorMessage(detail)}`}\n`,+ `codex-security: ${repository} ${status} (attempt ${attempt})${detail === undefined ? "" : `: ${diagnosticValue(detail)}`}\n`,);},});@@ -5125,15 +5092,13 @@ export async function main(}for (const result of results) {output.write(- `${result.status.toUpperCase()} ${safePatchText(result.id, dependencies.environment)}: ${safePatchText(result.evidence, dependencies.environment)}\n`,+ `${result.status.toUpperCase()} ${safePatchText(result.id)}: ${safePatchText(result.evidence)}\n`,);}return undefined;} catch (error) {exitCode = 2;- errorOutput.write(- `codex-security: ${logErrorMessage(error, dependencies.environment)}\n`,- );+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);return undefined;}},@@ -5502,8 +5467,8 @@ export async function main(};} catch (error) {if (exitCode === 0) exitCode = 2;- const message = logErrorMessage(error, dependencies.environment);- errorOutput.write(`codex-security: ${message}\n`);+ const message = errorMessage(error);+ errorOutput.write(`codex-security: ${diagnosticValue(message)}\n`);if (!structuredOutput) return;patchStructuredError = true;const failure = {@@ -6048,8 +6013,8 @@ async function runScanImport(const message =signal === "SIGINT" || signal === "SIGTERM"? "Scan import canceled."- : logErrorMessage(error, dependencies.environment);- errorOutput.write(`codex-security: ${message}\n`);+ : errorMessage(error);+ errorOutput.write(`codex-security: ${diagnosticValue(message)}\n`);return {exitCode: signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2,error: message,@@ -6901,12 +6866,12 @@ async function publishPatchBranch();}stderr.write(- `${gitlab ? "Merge" : "Pull"} request: ${safePatchText(url, dependencies.environment)}\n`,+ `${gitlab ? "Merge" : "Pull"} request: ${safePatchText(url)}\n`,);return { branch, url };} catch (error) {stderr.write(- `Patch commit saved. Retry from this repository with: codex-security patch --resume-pr ${safePatchText(branch, dependencies.environment)}\n`,+ `Patch commit saved. Retry from this repository with: codex-security patch --resume-pr ${safePatchText(branch)}\n`,);throw error;}@@ -7109,24 +7074,15 @@ async function snapshotPatchDirectory(return files;}-function safePatchText(- value: string,- environment: NodeJS.ProcessEnv = {},-): string {- return stripVTControlCharacters(- logErrorMessage(value, environment),- ).replaceAll(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu, " ");+function safePatchText(value: string): string {+ return stripVTControlCharacters(value).replaceAll(+ /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu,+ " ",+ );}-function safePatchReport(- value: string,- environment: NodeJS.ProcessEnv = {},-): string {- return value- .split(/\r?\n/gu)- .map((line) => safePatchText(line, environment))- .join("\n")- .trim();+function safePatchReport(value: string): string {+ return value.split(/\r?\n/gu).map(safePatchText).join("\n").trim();}function parsePatchRiskReport(report: string): PatchRiskAssessment {@@ -7173,7 +7129,7 @@ async function runPatchRiskAssessment(}const assessment = parsePatchRiskReport(result.report);stderr.write(- `Patch risk assessment:\n${safePatchReport(assessment.report, dependencies.environment)}\n`,+ `Patch risk assessment:\n${safePatchReport(assessment.report)}\n`,);return assessment;}@@ -7432,9 +7388,9 @@ async function runFindingPatches(}}- const title = safePatchText(finding.title, dependencies.environment);+ const title = safePatchText(finding.title);stderr.write(- ` ${patch.status.toUpperCase()} ${title}${patch.reason === undefined ? "" : `: ${safePatchText(patch.reason, dependencies.environment)}`}\n`,+ ` ${patch.status.toUpperCase()} ${title}${patch.reason === undefined ? "" : `: ${safePatchText(patch.reason)}`}\n`,);patches.push(patch);}@@ -8285,8 +8241,6 @@ async function executeScan(const verbose =arguments_.verbose === true ||configuredLogLevel?.toLowerCase() === "debug";- const diagnosticMessage = (value: unknown): string =>- diagnosticValue(logErrorMessage(value, dependencies.environment));const writeAboveProgress = (write: () => void): void => {if (progress === null) {write();@@ -8301,13 +8255,8 @@ async function executeScan(if (!verbose) return;const attributes = Object.entries(fields).flatMap(([name, value]) => {if (value === undefined) return [];- // Redact free-form messages, preserving structured metadata and paths.const displayed =- typeof value !== "string"- ? value- : name === "message"- ? diagnosticMessage(value)- : diagnosticValue(value);+ typeof value === "string" ? diagnosticValue(value) : value;return [`${name}=${JSON.stringify(displayed)}`];});writeAboveProgress(() => {@@ -8483,7 +8432,6 @@ async function executeScan(: { maxCostUsd: arguments_.maxCostUsd }),clock: dependencies,color: dependencies.environment["NO_COLOR"] === undefined,- sanitize: (value) => logErrorMessage(value, dependencies.environment),input: scanInput,onInterrupt,});@@ -8760,9 +8708,7 @@ async function executeScan(}writeAboveProgress(() => {diagnostic("scan.warning", { message });- errorOutput.write(- `codex-security: warning: ${diagnosticMessage(warning)}\n`,- );+ errorOutput.write(`codex-security: warning: ${message}\n`);});},onObserverError: (observer, error) => {@@ -8770,7 +8716,7 @@ async function executeScan(observer,classification: classifyConnectionFailure(error),});- const warning = `${observer} observer failed: ${diagnosticMessage(error)}`;+ const warning = `${observer} observer failed: ${diagnosticValue(error)}`;if (dashboard === null) {writeAboveProgress(() => {errorOutput.write(`codex-security: warning: ${warning}\n`);@@ -8829,11 +8775,7 @@ async function executeScan(const message =failure instanceof OutputInsideProtectedRootError? errorMessage(protectedRootErrorMessage(failure))- : scanFailureMessage(- failure,- selectedAuthentication,- dependencies.environment,- );+ : scanFailureMessage(failure, selectedAuthentication);diagnostic("scan.failed", {classification:costLimitFailure !== undefined@@ -9058,9 +9000,7 @@ async function executeScan(}}} catch (error) {- errorOutput.write(- `codex-security: ${logErrorMessage(error, dependencies.environment)}\n`,- );+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);scanData = { ...scanData, patches };return completedScan(2);}@@ -9170,10 +9110,8 @@ function authenticationFailureMessage(function scanFailureMessage(error: unknown,authentication: ScanAuthentication | null,- environment: NodeJS.ProcessEnv,): string {- // A local failure keeps its own diagnostic, subject to log redaction.- // Classification matches bare words+ // A local failure keeps its own message. Classification matches bare words// such as "permission denied" anywhere in the text, so an EACCES from a// read-only TMPDIR would otherwise be reported as a credential problem.//@@ -9181,8 +9119,7 @@ function scanFailureMessage(// appending it. That is deliberate: upstream authentication and authorization// errors can name the organization or project, which must not reach stderr or// the JSON error field.- if (isLocalScanFailure(error))- return diagnosticValue(logErrorMessage(error, environment));+ if (isLocalScanFailure(error)) return diagnosticValue(error);const message = errorMessage(error);const nativeRefreshRecovery = message.match(/\b(?:your access token could not be refreshed because you have since logged out or signed in to another account\. Please sign in again\.|your authentication session could not be refreshed automatically\. Please log out and sign in again\.)/iu,@@ -9223,7 +9160,7 @@ function scanFailureMessage(case "network_error":case "timeout":case "unknown":- return diagnosticValue(logErrorMessage(error, environment));+ return diagnosticValue(error);}}diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.tsindex 4c7bb186b..6ea29edfe 100644--- a/sdk/typescript/src/component-scan.ts+++ b/sdk/typescript/src/component-scan.ts@@ -19,7 +19,7 @@ import {type CodexSecurityConfig,} from "./config.js";import type { ScanCost, ScanSessionEvent } from "./cost.js";-import { safeErrorMessage } from "./errors.js";+import { errorMessage } from "./errors.js";import type { CoverageCompleteness, Finding } from "./models.js";import type { ScanResult } from "./result.js";import type { ScanActivity } from "./scan-activity.js";@@ -231,7 +231,7 @@ export async function runComponentScans(receipt.coverage === "complete" ? "completed" : "incomplete";} catch (error) {receipt.status = "failed";- receipt.error = safeErrorMessage(error);+ receipt.error = errorMessage(error);}notify(() =>options.onProgress?.({ ...receipt, paths: [...receipt.paths] }),@@ -392,7 +392,7 @@ async function deduplicateFindings(} catch (failure) {error = options.signal?.aborted? "Cross-component matching was canceled."- : safeErrorMessage(failure);+ : errorMessage(failure);}const remainSeparate = ({beforeOccurrenceId,diff --git a/sdk/typescript/src/custom-validation.ts b/sdk/typescript/src/custom-validation.tsindex 7e671e9dd..281958185 100644--- a/sdk/typescript/src/custom-validation.ts+++ b/sdk/typescript/src/custom-validation.ts@@ -10,7 +10,7 @@ import {import { basename, dirname, join } from "node:path";import Ajv2020 from "ajv/dist/2020.js";import { normalizePersistedFindings, requireScanFile } from "./contract.js";-import { IncompleteScanError, safeErrorMessage } from "./errors.js";+import { IncompleteScanError, errorMessage } from "./errors.js";import type { CoverageDocument, FindingsDocument } from "./models.js";import { requirePrivateOutputDirectory } from "./runtime.js";import type { NormalizedTarget } from "./targets.js";@@ -363,7 +363,7 @@ export async function runCustomValidation(options: {for (const [index, name] of DOCUMENTS.entries())await writeJson(scanDir, name, documents[index]);throw new IncompleteScanError(- `Custom validation is incomplete: ${safeErrorMessage(error)}`,+ `Custom validation is incomplete: ${errorMessage(error)}`,{ cause: error },);}diff --git a/sdk/typescript/src/deduplication/codex-review.ts b/sdk/typescript/src/deduplication/codex-review.tsindex 719877893..618b85833 100644--- a/sdk/typescript/src/deduplication/codex-review.ts+++ b/sdk/typescript/src/deduplication/codex-review.ts@@ -25,7 +25,7 @@ import { VERSION } from "../version.js";import {DeduplicationReviewError,type DeduplicationReviewFailureCategory,- safeErrorMessage,+ errorMessage,} from "../errors.js";import { configuredCodexHome, readCodexHomeConfig } from "../auth.js";import {@@ -165,14 +165,14 @@ export class CodexReviewRunner {error instanceof ReviewAttemptError? error.supportReason: "Codex review transport failed.";- const displayReason = safeErrorMessage(error);+ const displayReason = errorMessage(error);throw new DeduplicationReviewError({stage: review.stage,model: review.model,category,attempts: state.attempts,- reason: displayReason === "[redacted]" ? "[redacted]" : supportReason,+ reason: supportReason,},displayReason,);diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.tsindex f8dbfec4b..7314dd6d2 100644--- a/sdk/typescript/src/errors.ts+++ b/sdk/typescript/src/errors.ts@@ -5,34 +5,6 @@ export function errorMessage(error: unknown): string {return error instanceof Error ? error.message : String(error);}-/** Omit credential-bearing messages at persistence and display boundaries. */-export function safeErrorMessage(error: unknown): string {- const message = errorMessage(error);- const recognizableCredential =- /(?:\b(?:sk-(?:proj-)?|github_pat_|gh[pousr]_|npm_)\S+|\b(?:bearer|basic|token)(?:\s|%20|\+)+\S+|:\/\/[^\s/@]+@|-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----)/iu.test(- message,- );- const assignments = message.matchAll(- /(?<![\w%.-])[\w%.-]+(?:\\*["']|\]|%5d)*\s*(?:[:=]|%3[ad])/giu,- );- const sensitiveField = Array.from(assignments).some(([field]) =>- /(?:api(?:[_-]|%5f|%2d)?key|access(?:[_-]|%5f|%2d)?key|private(?:[_-]|%5f|%2d)?key|authorization|auth(?!or)|token|secret|credential|signature|sig(?=[^A-Za-z0-9]|value|data|token|secret|credential|password|header|field|id|key|$)|password|passwd)/iu.test(- field,- ),- );- return recognizableCredential || sensitiveField ? "[redacted]" : message;-}--/** Format CLI diagnostics; persistence continues to use safeErrorMessage. */-export function logErrorMessage(- error: unknown,- environment: NodeJS.ProcessEnv,-): string {- return environment["CODEX_SECURITY_REDACT_LOGS"] === "0"- ? errorMessage(error)- : safeErrorMessage(error);-}-/** Base error for Codex Security SDK failures. */export class CodexSecurityError extends Error {public constructor(message: string, options?: ErrorOptions) {diff --git a/sdk/typescript/src/finding-workflow.ts b/sdk/typescript/src/finding-workflow.tsindex 07a3df6e9..998d73772 100644--- a/sdk/typescript/src/finding-workflow.ts+++ b/sdk/typescript/src/finding-workflow.ts@@ -1,7 +1,7 @@import { createHash } from "node:crypto";import { isAbsolute, relative, sep } from "node:path";import type { JsonObject } from "./config.js";-import { CodexSecurityError, safeErrorMessage } from "./errors.js";+import { CodexSecurityError, errorMessage } from "./errors.js";import type { FindingSearchScope } from "./finding-retrieval.js";import {bundledPluginRoot,@@ -108,7 +108,7 @@ export class FindingWorkflow {await this.command({action: "fail",stage,- error: safeErrorMessage(error),+ error: errorMessage(error),}).catch(() => undefined);}diff --git a/sdk/typescript/src/github.ts b/sdk/typescript/src/github.tsindex 8cfcfac0b..da780d734 100644--- a/sdk/typescript/src/github.ts+++ b/sdk/typescript/src/github.ts@@ -1,7 +1,7 @@import { execFile as execFileCallback } from "node:child_process";import { promisify } from "node:util";import { Octokit } from "@octokit/core";-import { CodexSecurityError } from "./errors.js";+import { CodexSecurityError, errorMessage } from "./errors.js";import { resolveTrustedExecutable } from "./trusted-executable.js";const execFile = promisify(execFileCallback);@@ -226,9 +226,8 @@ export async function importGitHubCodeScanningAlerts(throw new CodexSecurityError("GitHub request was rate limited. Wait and retry.",);- // Octokit errors can contain credential-bearing request headers.throw new CodexSecurityError(- `GitHub code scanning request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}.`,+ `GitHub code scanning request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}: ${errorMessage(error)}`,);}}diff --git a/sdk/typescript/src/import-scan.ts b/sdk/typescript/src/import-scan.tsindex 2a7152a54..48d1856a6 100644--- a/sdk/typescript/src/import-scan.ts+++ b/sdk/typescript/src/import-scan.ts@@ -16,7 +16,7 @@ import { loadContract, sameCheckedFileDevice } from "./contract.js";import {CodexSecurityError,ScanInterruptedError,- safeErrorMessage,+ errorMessage,} from "./errors.js";import {bindImportedFindings,@@ -338,7 +338,7 @@ export async function importScan("--scan-id",activeScan.id,"--message",- safeErrorMessage(error).slice(0, 2400),+ errorMessage(error).slice(0, 2400),]).catch(() => undefined);}if (signal?.aborted) {diff --git a/sdk/typescript/src/linear.ts b/sdk/typescript/src/linear.tsindex fd14cc05e..0fba72be9 100644--- a/sdk/typescript/src/linear.ts+++ b/sdk/typescript/src/linear.ts@@ -5,7 +5,7 @@ import {RatelimitedLinearError,} from "@linear/sdk";import type { JsonObject } from "./config.js";-import { CodexSecurityError, safeErrorMessage } from "./errors.js";+import { CodexSecurityError, errorMessage } from "./errors.js";export type LinearClientFactory<Method extends keyof LinearClient = "issue" | "projects",@@ -143,9 +143,8 @@ export async function importLinearIssues(options: {"Linear request was rate limited. Wait and retry.",);}- const message = safeErrorMessage(error);throw new CodexSecurityError(- `Linear request failed: ${message.includes(credential) ? "[redacted]" : message}`,+ `Linear request failed: ${errorMessage(error)}`,);}}diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.tsindex 885559733..38b96cb00 100644--- a/sdk/typescript/src/multiscan.ts+++ b/sdk/typescript/src/multiscan.ts@@ -24,7 +24,7 @@ import type { CodexSecurityConfig } from "./config.js";import type { ScanCost } from "./cost.js";import {OutputDirectoryNotEmptyError,- safeErrorMessage,+ errorMessage,ScanCostLimitExceededError,} from "./errors.js";import type { CoverageDocument } from "./models.js";@@ -455,10 +455,8 @@ async function runCampaign(}requiresRecovery = error instanceof OutputDirectoryNotEmptyError;failure = requiresRecovery- ? safeErrorMessage(- `Bulk attempt directory is not empty: ${scanDir}. Existing artifacts and checkout were preserved. Run the same bulk-scan command with --recover to recover interrupted scans or retry failed scans in new attempt directories.`,- )- : safeErrorMessage(error);+ ? `Bulk attempt directory is not empty: ${scanDir}. Existing artifacts and checkout were preserved. Run the same bulk-scan command with --recover to recover interrupted scans or retry failed scans in new attempt directories.`+ : errorMessage(error);} finally {if (options.recoverScan === undefined && checkout !== undefined) {await rm(checkout, { recursive: true, force: true });diff --git a/sdk/typescript/src/patch-tui.tsx b/sdk/typescript/src/patch-tui.tsxindex 8b6a33590..b9f0c3035 100644--- a/sdk/typescript/src/patch-tui.tsx+++ b/sdk/typescript/src/patch-tui.tsx@@ -3,7 +3,6 @@ import { basename, isAbsolute, relative, resolve, sep } from "node:path";import { stripVTControlCharacters } from "node:util";import { Box, Text, render, useApp, useInput, useStdout } from "ink";import { useMemo, useRef, useState } from "react";-import { safeErrorMessage } from "./errors.js";import type { Finding, FindingCodeEvidence } from "./models.js";const SEVERITY_COLORS = {@@ -57,7 +56,7 @@ interface PatchTuiProps {}function safeText(value: unknown): string {- return stripVTControlCharacters(safeErrorMessage(String(value)))+ return stripVTControlCharacters(String(value)).replaceAll(/\r\n?/gu, "\n").replaceAll(/[\u0000-\u0009\u000B-\u001F\u007F-\u009F\u2028\u2029]/gu, " ");}diff --git a/sdk/typescript/src/publish.ts b/sdk/typescript/src/publish.tsindex 8086cf50f..4323f38cb 100644--- a/sdk/typescript/src/publish.ts+++ b/sdk/typescript/src/publish.ts@@ -26,7 +26,6 @@ import {CodexSecurityError,ConfigurationError,errorMessage,- safeErrorMessage,} from "./errors.js";import {createLinearClient,@@ -479,7 +478,7 @@ export async function publishScanInternal();eventLogNotice = `Linear connector-event evidence remains at ${file}.`;} catch (error) {- eventLogNotice = `Could not preserve Linear connector-event evidence: ${safeErrorMessage(error)}.`;+ eventLogNotice = `Could not preserve Linear connector-event evidence: ${errorMessage(error)}.`;}};if (handoffResults.indeterminate) {@@ -493,7 +492,7 @@ export async function publishScanInternal(await saveReceipt(result, environment);} catch (error) {result.warnings.push(- `Could not save the initial indeterminate publication receipt: ${safeErrorMessage(error)}.`,+ `Could not save the initial indeterminate publication receipt: ${errorMessage(error)}.`,);}}@@ -560,7 +559,7 @@ export async function publishScanInternal(if (result.created.length === 0 || options.signal?.aborted) throw error;result.warnings = [...(result.warnings ?? []),- `Could not save the publication receipt: ${safeErrorMessage(error)}. Linear issues were already created; do not retry publication.`,+ `Could not save the publication receipt: ${errorMessage(error)}. Linear issues were already created; do not retry publication.`,];}options.signal?.throwIfAborted();@@ -796,7 +795,7 @@ async function publishLinearApiIssues(outcome = { issueIdentifier: result.identifier, url: result.url };} catch (error) {outcome = {- error: safeErrorMessage(error),+ error: errorMessage(error),...(mutationSucceeded ||error instanceof InternalLinearError ||error instanceof NetworkLinearError ||@@ -828,7 +827,7 @@ async function publishLinearApiIssues();if (rejected !== undefined) {throw new CodexSecurityError(- `Could not preserve created Linear issues: ${safeErrorMessage(rejected.reason)}. The publication handoff remains at ${handoffFile}; recover it before retrying to avoid creating duplicate issues.`,+ `Could not preserve created Linear issues: ${errorMessage(rejected.reason)}. The publication handoff remains at ${handoffFile}; recover it before retrying to avoid creating duplicate issues.`,{ cause: rejected.reason },);}diff --git a/sdk/typescript/src/scan-dashboard.ts b/sdk/typescript/src/scan-dashboard.tsindex 0f2c8a344..85d8c2693 100644--- a/sdk/typescript/src/scan-dashboard.ts+++ b/sdk/typescript/src/scan-dashboard.ts@@ -64,7 +64,6 @@ interface ScanDashboardOptions {showCost?: boolean;clock: DashboardClock;color?: boolean;- sanitize?: (value: string) => string;input?: DashboardInput;onInterrupt?: () => void;}@@ -636,12 +635,7 @@ export class ScanDashboard {lines.map((line, index) => {const text = typeof line === "string" ? line : line.text;- const clean = fitLine(- typeof line !== "string" && this.#view === "details"- ? text- : (this.#options.sanitize?.(text) ?? text),- width,- );+ const clean = fitLine(text, width);const colored =this.#options.color === true? styleLine(@@ -662,7 +656,6 @@ export class ScanDashboard {? styleInlineCode(colored, line): colored,line.links,- this.#options.sanitize,);return `${ERASE_LINE}${formatted}`;})@@ -746,7 +739,7 @@ export class ScanDashboard {findings: string,cost: string,): string =>- ` ${marker} ${fitLine(this.#options.sanitize?.(name) ?? name, nameWidth).padEnd(nameWidth)} ${fitLine(status, 24).padEnd(24)} ${files.padStart(11)} ${findings.padStart(8)}${this.#showCost ? ` ${cost.padStart(8)}` : ""}`;+ ` ${marker} ${fitLine(name, nameWidth).padEnd(nameWidth)} ${fitLine(status, 24).padEnd(24)} ${files.padStart(11)} ${findings.padStart(8)}${this.#showCost ? ` ${cost.padStart(8)}` : ""}`;const table = this.#components.slice(first, first + rows).map(({ receipt, dashboard }, index) => {@@ -963,7 +956,6 @@ export class ScanDashboard {value: string,kind: DashboardActivityLine["kind"],): void => {- value = this.#options.sanitize?.(value) ?? value;if (kind !== "message" && kind !== "reasoning") {for (const text of wrapActivity(prefix, value, width)) {lines.push({ text, kind });@@ -1121,10 +1113,9 @@ function styleInlineCode(value: string, line: DashboardActivityLine): string {function linkActivity(value: string,links: readonly DashboardActivityLink[] | undefined,- sanitize: ((value: string) => string) | undefined,): string {for (const { label, target } of links ?? []) {- const safe = safeHyperlinkTarget(sanitize?.(target) ?? target);+ const safe = safeHyperlinkTarget(target);if (safe !== undefined) {value = value.replace(label,diff --git a/sdk/typescript/src/security-policy-cli.ts b/sdk/typescript/src/security-policy-cli.tsindex 543cb61e3..0defee3ed 100644--- a/sdk/typescript/src/security-policy-cli.ts+++ b/sdk/typescript/src/security-policy-cli.ts@@ -2,7 +2,7 @@ import type { CodexSecurity, ScanAuthMode } from "./api.js";import type { BulkScanPrompt } from "./bulk-scan-discovery.js";import type { CodexSecurityConfig } from "./config.js";import { formatScanCost } from "./cost-model.js";-import { logErrorMessage } from "./errors.js";+import { errorMessage } from "./errors.js";import {formatSecurityPolicyText as display,type SecurityPolicyOptions,@@ -132,9 +132,7 @@ export async function runPolicyCommand(},onStage: (stage) => write(STAGES[stage]),onWarning: (warning) =>- write(- `codex-security: ${display(logErrorMessage(warning, dependencies.environment))}`,- ),+ write(`codex-security: ${display(errorMessage(warning))}`),...(interactive? {answerQuestions: async (@@ -173,7 +171,7 @@ export async function runPolicyCommand(controller.signal.throwIfAborted();diff = "Preview unavailable. Review the saved draft.";write(- `codex-security: Could not preview the policy: ${display(logErrorMessage(error, dependencies.environment))}`,+ `codex-security: Could not preview the policy: ${display(errorMessage(error))}`,);}const preview = [@@ -232,7 +230,7 @@ export async function runPolicyCommand(? "Policy generation canceled by Ctrl-C.": signal === "SIGTERM"? "Policy generation terminated by SIGTERM."- : display(logErrorMessage(error, dependencies.environment));+ : display(errorMessage(error));write(`codex-security: ${message}`);if (outputDir !== undefined)write(`Saved artifacts: ${display(outputDir)}`);@@ -246,7 +244,7 @@ export async function runPolicyCommand(await security?.close();} catch (error) {write(- `codex-security: Could not clean up the policy runtime: ${display(logErrorMessage(error, dependencies.environment))}`,+ `codex-security: Could not clean up the policy runtime: ${display(errorMessage(error))}`,);}}diff --git a/sdk/typescript/src/suggest-owners.ts b/sdk/typescript/src/suggest-owners.tsindex 711c8ff32..e807a82ba 100644--- a/sdk/typescript/src/suggest-owners.ts+++ b/sdk/typescript/src/suggest-owners.ts@@ -11,7 +11,7 @@ import {scanModelConfiguration,type ScanModelConfiguration,} from "./config.js";-import { CodexSecurityError, safeErrorMessage } from "./errors.js";+import { CodexSecurityError, errorMessage } from "./errors.js";import {runReadOnlyCodex,type ReadOnlyCodexOptions,@@ -177,7 +177,7 @@ export async function suggestOwnersInternal(} catch (error) {options.signal?.throwIfAborted();result.status = "error";- result.reason = safeErrorMessage(error);+ result.reason = errorMessage(error);}}options.signal?.throwIfAborted();diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex ceb37ccf7..bab090810 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -59,7 +59,6 @@ import {} from "../src/runtime.js";import { matchScanFindingsInternal } from "../src/scan-comparison.js";import { normalizeTarget } from "../src/targets.js";-import { SYNTHETIC_CREDENTIALS } from "./cli-fixtures.js";import { INTEGRATION_TARGET, PLUGIN_ROOT } from "./plugin-root.js";import {mockScanRegistration,@@ -5413,7 +5412,7 @@ describe("CodexSecurity orchestration", () => {await client.close();});- test("keeps credential-bearing failures out of saved scan history", async () => {+ test("preserves original failures in saved scan history", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");const codexHome = join(root, "codex-home");@@ -5432,8 +5431,7 @@ describe("CodexSecurity orchestration", () => {const quotedCredential = JSON.stringify({client_secret_value: "SYNTHETIC correct horse battery staple",});- const originalFailure = `${SYNTHETIC_CREDENTIALS} ${quotedCredential}`;- const storedFailure = "[redacted]";+ const originalFailure = `request failed: token=SYNTHETIC_TOKEN ${quotedCredential}`;const client = new TestClient({},{@@ -5471,12 +5469,12 @@ describe("CodexSecurity orchestration", () => {},);- await expect(client.run(repository)).rejects.toThrow(SYNTHETIC_CREDENTIALS);+ await expect(client.run(repository)).rejects.toThrow(originalFailure);const failure = commands.find((args) => args[0] === "fail-scan");const scanId = failure?.[2] ?? "";expect(scanId).toMatch(/^[0-9a-f-]{36}$/);expect(failure?.[3]).toBe("--message");- expect(failure?.[4]).toBe(storedFailure);+ expect(failure?.[4]).toBe(originalFailure);// `scans show` reads the stored message back through get-scan.const context = await runWorkbench(@@ -5486,11 +5484,9 @@ describe("CodexSecurity orchestration", () => {expect(context["scan"]).toMatchObject({continuationThreadId: "failed-thread",progress: { status: "failed" },- failureMessage: storedFailure,+ failureMessage: originalFailure,});- const database = await readFile(join(stateDirectory, "workbench.sqlite3"));- expect(database.toString("latin1")).not.toContain("SYNTHETIC");await client.close();});diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.tsindex 9a51eaea1..cc807fefd 100644--- a/sdk/typescript/tests-ts/cli-authentication.test.ts+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts@@ -1022,7 +1022,7 @@ describe("CLI authentication", () => {expect(JSON.parse(stdout.text())).toMatchObject({status: "failed",code: "SCAN_FAILED",- message: message.includes("access token") ? "[redacted]" : message,+ message,});expect(stderr.text()).toContain(`${message}\n`);expect(stderr.text()).not.toContain("PRIVATE_UPSTREAM_DETAIL");diff --git a/sdk/typescript/tests-ts/cli-cloud-publish.test.ts b/sdk/typescript/tests-ts/cli-cloud-publish.test.tsindex 2f3af3c54..38acb8792 100644--- a/sdk/typescript/tests-ts/cli-cloud-publish.test.ts+++ b/sdk/typescript/tests-ts/cli-cloud-publish.test.ts@@ -513,6 +513,7 @@ describe("publish scan to Cloud", () => {});test("keeps receipts and continues after a failed scan without retrying", async () => {+ const failure = `Cloud failed: ${SYNTHETIC_CREDENTIALS}\u001b[2J\ncontinued`;const deps = dependencies();const directories = ["scan-one", "scan-two", "scan-three"].map((path) =>resolve(deps.currentDirectory(), path),@@ -521,7 +522,7 @@ describe("publish scan to Cloud", () => {deps.publishScanToCloud = async (directory) => {calls.push(directory);if (directory === directories[1]) {- throw new Error(`Cloud failed: ${SYNTHETIC_CREDENTIALS}`);+ throw new Error(failure);}return {...receipt,@@ -551,11 +552,18 @@ describe("publish scan to Cloud", () => {{ scanDir: directories[0], ...receipt },{ scanDir: directories[2], ...receipt, scanId: "scan-3" },],- failed: [{ scanDir: directories[1], error: "[redacted]" }],+ failed: [+ {+ scanDir: directories[1],+ error: failure,+ },+ ],notAttempted: [],});- expect(stderr.text()).toContain("[redacted]");- expect(stderr.text()).not.toContain(SYNTHETIC_CREDENTIALS);+ expect(stderr.text()).toContain(+ `Cloud failed: ${SYNTHETIC_CREDENTIALS} [2J continued\n`,+ );+ expect(stderr.text()).not.toContain("\u001b");});test.each([false, true])(@@ -989,10 +997,12 @@ describe("publish scan to Cloud", () => {}});- test("reports publication failures without leaking credentials or claiming success", async () => {+ test("reports original publication failures without claiming success", async () => {const deps = dependencies();deps.publishScanToCloud = async () => {- throw new Error(`Cloud failed: ${SYNTHETIC_CREDENTIALS}`);+ throw new Error(+ `Cloud failed: ${SYNTHETIC_CREDENTIALS}\u001b[2J\ncontinued`,+ );};const stdout = capture();const stderr = capture();@@ -1005,7 +1015,9 @@ describe("publish scan to Cloud", () => {),).toBe(2);expect(stdout.text()).toBe("");- expect(stderr.text()).toBe("codex-security: [redacted]\n");+ expect(stderr.text()).toBe(+ `codex-security: Cloud failed: ${SYNTHETIC_CREDENTIALS} [2J continued\n`,+ );});test("preserves a confirmed single-scan receipt when cancellation follows the response", async () => {diff --git a/sdk/typescript/tests-ts/cli-diagnostics.test.ts b/sdk/typescript/tests-ts/cli-diagnostics.test.tsnew file mode 100644index 000000000..55111b4ff--- /dev/null+++ b/sdk/typescript/tests-ts/cli-diagnostics.test.ts@@ -0,0 +1,285 @@+import { stripVTControlCharacters } from "node:util";+import { describe, expect, test } from "bun:test";+import { main } from "../src/cli.js";+import { CodexSecurityError, OutputDirectoryError } from "../src/errors.js";+import {+ capture,+ dependencies,+ fakePreflight,+ fakeResult,+} from "./cli-fixtures.js";++describe("CLI diagnostics", () => {+ test.each([+ {+ command: "policy",+ args: ["policy", "--json", "--full-output"],+ structured: true,+ },+ {+ command: "suggest-owners",+ args: ["suggest-owners", "findings.json"],+ structured: false,+ },+ {+ command: "classify-severity",+ args: ["classify-severity", "--scan", "latest"],+ structured: false,+ },+ {+ command: "dedupe",+ args: [+ "dedupe",+ "--scan",+ "latest",+ "--findings-url",+ "https://example.test/findings",+ ],+ structured: false,+ },+ {+ command: "verify-fix",+ args: ["verify-fix", "Synthetic finding"],+ structured: false,+ },+ {+ command: "patch",+ args: ["patch", "Synthetic finding", "--json"],+ structured: true,+ },+ {+ command: "scan import",+ args: ["--json", "scan", "import", "--csv", "findings.csv"],+ structured: false,+ },+ {+ command: "GitHub import",+ args: ["import", "github", "example/repository"],+ structured: false,+ },+ ])(+ "escapes terminal controls in $command failures while preserving details",+ async ({ command, args, structured }) => {+ const message =+ "Operation failed: token=SYNTHETIC_VALUE\u001b[2J\ncontinued\r\ttail";+ const fail = () => {+ throw new Error(message);+ };+ const deps = dependencies({ onCodex: fail, onRepositoryCommand: fail });+ deps.classifyScanSeverity = fail;+ deps.deduplicateScan = fail;+ deps.importScan = fail;+ deps.importGitHubAlerts = fail;+ if (command === "policy" || command === "suggest-owners")+ deps.currentDirectory = fail;+ const stdout = capture();+ const stderr = capture();++ expect(await main(args, stdout.stream, stderr.stream, deps)).toBe(2);+ expect(stderr.text()).toContain(+ "codex-security: Operation failed: token=SYNTHETIC_VALUE [2J continued tail\n",+ );+ expect(stderr.text()).not.toContain("\u001b");+ if (structured) {+ const result = JSON.parse(stdout.text());+ expect(result.error?.message ?? result.message).toBe(message);+ }+ },+ );++ test.each([+ new CodexSecurityError("token budget exceeded"),+ new CodexSecurityError("basic validation failed"),+ new OutputDirectoryError(+ "Could not write results: token=SYNTHETIC_LOCAL_VALUE",+ ),+ new CodexSecurityError("request timed out token=SYNTHETIC_TIMEOUT_VALUE"),+ ])("preserves scan failure details for %s", async (failure) => {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.createSecurity = () => ({+ run: async () => {+ throw failure;+ },+ preflight: async () => fakePreflight(),+ close: async () => {},+ });++ expect(+ await main(+ ["scan", ".", "--json", "--verbose"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(JSON.parse(stdout.text()).message).toBe(failure.message);+ expect(stderr.text()).toContain(failure.message);+ });++ test.each([+ { name: "dashboard", args: [], environment: {}, tty: true, verbose: false },+ { name: "plain", args: [], environment: {}, tty: false, verbose: false },+ {+ name: "headless",+ args: ["--headless"],+ environment: {},+ tty: true,+ verbose: false,+ },+ {+ name: "verbose flag",+ args: ["--verbose"],+ environment: {},+ tty: true,+ verbose: true,+ },+ {+ name: "debug environment",+ args: [],+ environment: { CODEX_SECURITY_LOG_LEVEL: " DeBuG " },+ tty: true,+ verbose: true,+ },+ {+ name: "shared debug fallback",+ args: [],+ environment: { CODEX_SECURITY_LOG_LEVEL: " ", LOG_LEVEL: " DEBUG " },+ tty: false,+ verbose: true,+ },+ {+ name: "dedicated level precedence",+ args: [],+ environment: { CODEX_SECURITY_LOG_LEVEL: "info", LOG_LEVEL: "debug" },+ tty: false,+ verbose: false,+ },+ {+ name: "verbose flag precedence",+ args: ["--verbose"],+ environment: { CODEX_SECURITY_LOG_LEVEL: "error", LOG_LEVEL: "warn" },+ tty: false,+ verbose: true,+ },+ ])("preserves warning details and verbosity for $name", async (mode) => {+ const warning = "recoverable warning: token=SYNTHETIC_WARNING_VALUE";+ const observer = "observer failure: token=SYNTHETIC_OBSERVER_VALUE";+ const stdout = capture();+ const stderr = capture(mode.tty);+ const result = fakeResult([], "complete", {+ input_tokens: 200,+ cached_input_tokens: 20,+ output_tokens: 10,+ });+ const deps = dependencies({+ environment: { ...mode.environment, NO_COLOR: "1" },+ });+ deps.createSecurity = () => ({+ run: async (_repository, options) => {+ options?.onAuthentication?.({+ method: "api_key",+ source: "OPENAI_API_KEY",+ verified: false,+ });+ options?.onScanStarted?.();+ options?.onCost?.(result.cost!);+ options?.onWarning?.(warning);+ options?.onObserverError?.("onWorkerStatus", new Error(observer));+ return result;+ },+ preflight: async () => fakePreflight(),+ close: async () => {},+ });++ expect(+ await main(+ ["scan", ".", ...mode.args],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ const output = stripVTControlCharacters(stderr.text()).replace(+ /\s+/gu,+ " ",+ );+ expect(output).toContain(`codex-security: warning: ${warning}`);+ expect(output).toContain(`onWorkerStatus observer failed: ${observer}`);+ expect(output.includes("codex-security: debug:")).toBe(mode.verbose);+ if (mode.verbose) {+ expect(output).toContain(+ `codex-security: debug: scan.warning message=${JSON.stringify(warning)}`,+ );+ expect(output).toContain(+ 'authentication.selected requested="auto" method="api_key" source="OPENAI_API_KEY" verified=false',+ );+ expect(output).toContain("input_tokens=200 cached_input_tokens=20");+ expect(output).toContain(+ 'scan.observer_failed observer="onWorkerStatus" classification="unknown"',+ );+ }+ });++ test("preserves target warning details in diagnostics and result data", async () => {+ const warning = "Source changed: token=SYNTHETIC_TARGET_VALUE";+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.createSecurity = () => ({+ run: async (_repository, options) => {+ options?.onWarning?.(warning, { kind: "target_changed" });+ return fakeResult();+ },+ preflight: async () => fakePreflight(),+ close: async () => {},+ });+ expect(+ await main(+ ["scan", ".", "--json", "--verbose"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(JSON.parse(stdout.text()).warnings).toEqual([warning]);+ expect(stderr.text()).toContain(`codex-security: warning: ${warning}`);+ });++ test("preserves live activity and observer messages", async () => {+ const activity = "command result: token=SYNTHETIC_ACTIVITY_VALUE";+ const observer = "observer result: token=SYNTHETIC_OBSERVER_VALUE";+ const stdout = capture();+ const stderr = capture(true);+ const deps = dependencies({ environment: { NO_COLOR: "1" } });+ deps.createSecurity = () => ({+ run: async (_repository, options) => {+ options?.onScanStarted?.();+ options?.onActivity?.({+ id: "synthetic-command",+ kind: "command",+ status: "completed",+ description: activity,+ paths: [],+ });+ options?.onObserverError?.("onWorkerStatus", new Error(observer));+ return fakeResult();+ },+ preflight: async () => fakePreflight(),+ close: async () => {},+ });++ expect(await main(["scan", "."], stdout.stream, stderr.stream, deps)).toBe(+ 0,+ );+ const output = stripVTControlCharacters(stderr.text()).replace(+ /\s+/gu,+ " ",+ );+ expect(output).toContain(activity);+ expect(output).toContain(observer);+ expect(stderr.text()).toContain("\u001B[?1049h");+ expect(stderr.text()).toContain("\u001B[?1049l");+ });+});diff --git a/sdk/typescript/tests-ts/cli-patch.test.ts b/sdk/typescript/tests-ts/cli-patch.test.tsindex 35af5b6a1..a29bdde1d 100644--- a/sdk/typescript/tests-ts/cli-patch.test.ts+++ b/sdk/typescript/tests-ts/cli-patch.test.ts@@ -735,80 +735,71 @@ describe("scan and patch workflow", () => {}});- test.each([undefined, "0", "1"])(- "applies redaction setting %p to patch-risk display while protecting publication summaries",- async (value) => {- const result = resultWithFindings(["high"]);- const detail = "Diagnostic detail: token=SYNTHETIC_RISK_VALUE";- const report = patchRiskAssessment().report.replace(- patchRiskSummary(),- `${patchRiskSummary()}\n\n${detail}`,- );- const repositoryCommands: Array<{- command: string;- args: readonly string[];- }> = [];- const outcome = await runWorkflow(- [- "patch",- "--scan",- "scan-1",- "--assess-patch-risk",- "--create-pr",- "--json",- ],- {- environment: { CODEX_SECURITY_REDACT_LOGS: value },- onWorkbench: () => savedScan(result),- onRepositoryCommand: (command, args) => {- repositoryCommands.push({ command, args });- if (command === "git") {- if (args[0] === "remote") {- return "https://github.example.test/example/repository.git";- }- return args.includes("--name-only") ? "src/finding-1.ts\0" : "";+ test("preserves patch-risk details in display and publication summaries", async () => {+ const result = resultWithFindings(["high"]);+ const detail = "Diagnostic detail: token=SYNTHETIC_RISK_VALUE";+ const report = patchRiskAssessment().report.replace(+ patchRiskSummary(),+ `${patchRiskSummary()}\n\n${detail}`,+ );+ const repositoryCommands: Array<{+ command: string;+ args: readonly string[];+ }> = [];+ const outcome = await runWorkflow(+ [+ "patch",+ "--scan",+ "scan-1",+ "--assess-patch-risk",+ "--create-pr",+ "--json",+ ],+ {+ onWorkbench: () => savedScan(result),+ onRepositoryCommand: (command, args) => {+ repositoryCommands.push({ command, args });+ if (command === "git") {+ if (args[0] === "remote") {+ return "https://github.example.test/example/repository.git";}- return args[1] === "create"- ? "https://github.example.test/example/repository/pull/15"- : "";- },+ return args.includes("--name-only") ? "src/finding-1.ts\0" : "";+ }+ return args[1] === "create"+ ? "https://github.example.test/example/repository/pull/15"+ : "";},- {- configure: (current) => {- Object.assign(current, {- assessPatchRisk: async () => ({ report }),- });- },+ },+ {+ configure: (current) => {+ Object.assign(current, {+ assessPatchRisk: async () => ({ report }),+ });},- );+ },+ );- expect(outcome.exitCode, outcome.stderr).toBe(0);- expect(outcome.stderr).toContain("Patch risk assessment:");- expect(outcome.stderr).toContain(patchRiskSummary());- expect(outcome.stderr).toContain(value === "0" ? detail : "[redacted]");- expect(outcome.stderr.includes("SYNTHETIC_RISK_VALUE")).toBe(- value === "0",- );- // The report is result data; only its CLI display follows the log setting.- expect(JSON.parse(outcome.stdout).patchRisk.report).toContain(detail);- const published = repositoryCommands.find(- ({ command, args }) => command === "gh" && args[1] === "create",- )?.args;- const persisted = repositoryCommands.find(- ({ command, args }) =>- command === "git" &&- args[0] === "config" &&- args[2]?.endsWith(".codexSecurityPatchPullRequestBody"),- )?.args;- expect(published).toBeDefined();- expect(persisted).toBeDefined();- for (const body of [published?.at(-1), persisted?.at(-1)]) {- expect(body).toContain(patchRiskSummary());- expect(body).toContain("[redacted]");- expect(body).not.toContain("SYNTHETIC_RISK_VALUE");- }- },- );+ expect(outcome.exitCode, outcome.stderr).toBe(0);+ expect(outcome.stderr).toContain("Patch risk assessment:");+ expect(outcome.stderr).toContain(patchRiskSummary());+ expect(outcome.stderr).toContain(detail);+ expect(JSON.parse(outcome.stdout).patchRisk.report).toContain(detail);+ const published = repositoryCommands.find(+ ({ command, args }) => command === "gh" && args[1] === "create",+ )?.args;+ const persisted = repositoryCommands.find(+ ({ command, args }) =>+ command === "git" &&+ args[0] === "config" &&+ args[2]?.endsWith(".codexSecurityPatchPullRequestBody"),+ )?.args;+ expect(published).toBeDefined();+ expect(persisted).toBeDefined();+ for (const body of [published?.at(-1), persisted?.at(-1)]) {+ expect(body).toContain(patchRiskSummary());+ expect(body).toContain(detail);+ }+ });test("assesses only changes made during a literal patch run", async () => {const directory = await mkdtemp(@@ -2278,22 +2269,32 @@ describe("scan and patch workflow", () => {},);- test("redacts credentials when saved-finding pull request creation fails", async () => {- const result = resultWithFindings(["high"]);- const outcome = await runWorkflow(- ["patch", "--scan", "scan-1", "--create-pr"],- {- onWorkbench: () => savedScan(result),- onRepositoryCommand: () => {- throw new Error("GitHub rejected github_pat_SYNTHETIC_SECRET_123");+ test.each(["patch", "scan"])(+ "escapes controls in %s pull request failures while preserving error details",+ async (command) => {+ const result = resultWithFindings(["high"]);+ const outcome = await runWorkflow(+ command === "patch"+ ? ["patch", "--scan", "scan-1", "--create-pr"]+ : ["scan", ".", "--patch", "--create-pr"],+ {+ result,+ onWorkbench: () => savedScan(result),+ onRepositoryCommand: () => {+ throw new Error(+ "GitHub rejected github_pat_SYNTHETIC_SECRET_123\u001b[2J\ncontinued",+ );+ },},- },- );+ );- expect(outcome.exitCode).toBe(2);- expect(outcome.stderr).toContain("[redacted]");- expect(outcome.stderr).not.toContain("SYNTHETIC_SECRET_123");- });+ expect(outcome.exitCode).toBe(2);+ expect(outcome.stderr).toContain(+ "GitHub rejected github_pat_SYNTHETIC_SECRET_123 [2J continued\n",+ );+ expect(outcome.stderr).not.toContain("\u001b");+ },+ );test("resolves a finding identifier to its saved scan and checkout", async () => {const result = resultWithFindings(["high"]);diff --git a/sdk/typescript/tests-ts/cli-publish.test.ts b/sdk/typescript/tests-ts/cli-publish.test.tsindex 530810d3e..ba7c5a4b7 100644--- a/sdk/typescript/tests-ts/cli-publish.test.ts+++ b/sdk/typescript/tests-ts/cli-publish.test.ts@@ -903,7 +903,7 @@ describe("publish scan", () => {test("reports sanitized receipt warnings after terminal restoration without contaminating publication output", async () => {const warning =- "Could not save the publication receipt: [redacted]. Linear issues were already created; do not retry publication.";+ "Could not save the publication receipt: token=SYNTHETIC_RECEIPT_VALUE. Linear issues were already created; do not retry publication.";const unsafeWarning = "Injected\u001B[31m\nsecond line\u0007";for (const { json, tty, failed } of [{ json: false, tty: false, failed: false },@@ -2449,7 +2449,7 @@ describe("publish scan", () => {test("surfaces receipt warnings without changing published issues or JSON output", async () => {const warning =- "Could not save the publication receipt: [redacted]. Linear issues were already created; do not retry publication.";+ "Could not save the publication receipt: token=SYNTHETIC_RECEIPT_VALUE. Linear issues were already created; do not retry publication.";const result = { ...publicationResult(), warnings: [warning] };const stdout = capture();const stderr = capture();@@ -2491,7 +2491,7 @@ describe("publish scan", () => {expect(stderr.text()).toBe(`codex-security: ${warning}\n`);});- test("sanitizes receipt warnings while preserving partial publication results", async () => {+ test("normalizes receipt warning controls while preserving diagnostic text and partial results", async () => {const warnings = ["Receipt storage failed.\n\u001B[31mDo not retry publication.","Receipt storage failed: sk-proj-SYNTHETIC_RECEIPT_SECRET",@@ -2518,10 +2518,9 @@ describe("publish scan", () => {expect(JSON.parse(stdout.text())).toEqual(result);expect(stderr.text()).toBe("codex-security: Receipt storage failed. [31mDo not retry publication.\n" +- "codex-security: [redacted]\n",+ "codex-security: Receipt storage failed: sk-proj-SYNTHETIC_RECEIPT_SECRET\n",);expect(stderr.text()).not.toContain("\u001B");- expect(stderr.text()).not.toContain("SYNTHETIC_RECEIPT_SECRET");});test("returns a nonzero exit code while preserving partial publication results", async () => {diff --git a/sdk/typescript/tests-ts/cli-redaction.test.ts b/sdk/typescript/tests-ts/cli-redaction.test.tsdeleted file mode 100644index ec22aeb1d..000000000--- a/sdk/typescript/tests-ts/cli-redaction.test.ts+++ /dev/null@@ -1,402 +0,0 @@-import { stripVTControlCharacters } from "node:util";-import { describe, expect, test } from "bun:test";-import { main } from "../src/cli.js";-import { CodexSecurityError, OutputDirectoryError } from "../src/errors.js";-import {- capture,- dependencies,- fakePreflight,- fakeResult,-} from "./cli-fixtures.js";--describe("CLI log redaction", () => {- test("documents the opt-out in scan help and its generated schema", async () => {- const help = capture();- expect(- await main(- ["scan", "--help"],- help.stream,- capture().stream,- dependencies(),- ),- ).toBe(0);- expect(help.text()).toContain("CODEX_SECURITY_REDACT_LOGS=0");-- const schema = capture();- expect(- await main(- ["scan", "--schema", "--format", "json"],- schema.stream,- capture().stream,- dependencies(),- ),- ).toBe(0);- expect(JSON.parse(schema.text())).toMatchObject({- options: {- properties: {- verbose: {- description: expect.stringContaining(- "CODEX_SECURITY_REDACT_LOGS=0",- ),- },- },- },- });- });-- test.each([- [false, false],- [false, true],- [true, false],- [true, true],- ])(- "isolates concurrent scan error settings with full output %p and verbose %p",- async (fullOutput, verbose) => {- const message = "request failed: token=SYNTHETIC_LOG_VALUE";- const selections = [undefined, "0", "1"];- let started = 0;- let release!: () => void;- const allStarted = new Promise<void>((resolve) => {- release = resolve;- });-- await Promise.all(- selections.map(async (value) => {- const stdout = capture();- const stderr = capture();- const deps = dependencies({- environment: { CODEX_SECURITY_REDACT_LOGS: value },- });- deps.createSecurity = () => ({- run: async () => {- started += 1;- if (started === selections.length) release();- await allStarted;- throw new CodexSecurityError(message);- },- preflight: async () => fakePreflight(),- close: async () => {},- });-- expect(- await main(- [- "scan",- ".",- "--json",- ...(fullOutput ? ["--full-output"] : []),- ...(verbose ? ["--verbose"] : []),- ],- stdout.stream,- stderr.stream,- deps,- ),- ).toBe(2);- const output = JSON.parse(stdout.text());- const expected = {- code: "SCAN_FAILED",- message: value === "0" ? message : "[redacted]",- };- if (fullOutput) {- expect(output.ok).toBe(false);- expect(output.error).toEqual(expected);- expect(output).not.toHaveProperty("data");- } else {- expect(output).toEqual({ status: "failed", ...expected });- }- expect(stderr.text()).toContain(expected.message);- expect(stderr.text().includes(message)).toBe(value === "0");- expect(stderr.text().includes("codex-security: debug:")).toBe(- verbose,- );- }),- );- },- );-- test.each([- { name: "dashboard", args: [], environment: {}, tty: true, verbose: false },- { name: "plain", args: [], environment: {}, tty: false, verbose: false },- {- name: "headless",- args: ["--headless"],- environment: {},- tty: true,- verbose: false,- },- {- name: "verbose flag",- args: ["--verbose"],- environment: {},- tty: true,- verbose: true,- },- {- name: "debug environment",- args: [],- environment: { CODEX_SECURITY_LOG_LEVEL: " DeBuG " },- tty: true,- verbose: true,- },- {- name: "shared debug fallback",- args: [],- environment: { CODEX_SECURITY_LOG_LEVEL: " ", LOG_LEVEL: " DEBUG " },- tty: false,- verbose: true,- },- {- name: "dedicated level precedence",- args: [],- environment: { CODEX_SECURITY_LOG_LEVEL: "info", LOG_LEVEL: "debug" },- tty: false,- verbose: false,- },- {- name: "verbose flag precedence",- args: ["--verbose"],- environment: { CODEX_SECURITY_LOG_LEVEL: "error", LOG_LEVEL: "warn" },- tty: false,- verbose: true,- },- ])("keeps verbosity and redaction independent for $name", async (mode) => {- for (const value of [undefined, "0", "1"]) {- const warning = "recoverable warning: token=SYNTHETIC_WARNING_VALUE";- const observer = "observer failure: token=SYNTHETIC_OBSERVER_VALUE";- const stdout = capture();- const stderr = capture(mode.tty);- const result = fakeResult([], "complete", {- input_tokens: 200,- cached_input_tokens: 20,- output_tokens: 10,- });- const deps = dependencies({- environment: {- ...mode.environment,- NO_COLOR: "1",- CODEX_SECURITY_REDACT_LOGS: value,- },- });- deps.createSecurity = () => ({- run: async (_repository, options) => {- options?.onAuthentication?.({- method: "api_key",- source: "OPENAI_API_KEY",- verified: false,- });- options?.onScanStarted?.();- options?.onCost?.(result.cost!);- options?.onWarning?.(warning);- options?.onObserverError?.("onWorkerStatus", new Error(observer));- return result;- },- preflight: async () => fakePreflight(),- close: async () => {},- });-- expect(- await main(- ["scan", ".", ...mode.args],- stdout.stream,- stderr.stream,- deps,- ),- ).toBe(0);- const output = stripVTControlCharacters(stderr.text()).replace(- /\s+/gu,- " ",- );- const expectedWarning = value === "0" ? warning : "[redacted]";- const expectedObserver = value === "0" ? observer : "[redacted]";- expect(output).toContain(`codex-security: warning: ${expectedWarning}`);- expect(output).toContain(- `onWorkerStatus observer failed: ${expectedObserver}`,- );- expect(output.includes("SYNTHETIC_WARNING_VALUE")).toBe(value === "0");- expect(output.includes("SYNTHETIC_OBSERVER_VALUE")).toBe(value === "0");- expect(output.includes("codex-security: debug:")).toBe(mode.verbose);- if (mode.verbose) {- expect(output).toContain(- `codex-security: debug: scan.warning message=${JSON.stringify(expectedWarning)}`,- );- expect(output).toContain(- 'authentication.selected requested="auto" method="api_key" source="OPENAI_API_KEY" verified=false',- );- expect(output).toContain("input_tokens=200 cached_input_tokens=20");- expect(output).toContain(- 'scan.observer_failed observer="onWorkerStatus" classification="unknown"',- );- }- }- });-- test.each([undefined, "0", "1"])(- "preserves target-warning result data with redaction setting %p",- async (value) => {- const warning = "Source changed: token=SYNTHETIC_TARGET_VALUE";- const stdout = capture();- const stderr = capture();- const deps = dependencies({- environment: { CODEX_SECURITY_REDACT_LOGS: value },- });- deps.createSecurity = () => ({- run: async (_repository, options) => {- options?.onWarning?.(warning, { kind: "target_changed" });- return fakeResult();- },- preflight: async () => fakePreflight(),- close: async () => {},- });- expect(- await main(- ["scan", ".", "--json", "--verbose"],- stdout.stream,- stderr.stream,- deps,- ),- ).toBe(2);- expect(JSON.parse(stdout.text()).warnings).toEqual([warning]);- expect(stderr.text()).toContain(- `codex-security: warning: ${value === "0" ? warning : "[redacted]"}`,- );- expect(stderr.text().includes("SYNTHETIC_TARGET_VALUE")).toBe(- value === "0",- );- },- );-- test.each([- {- name: "local",- failure: new OutputDirectoryError(- "Could not write results: token=SYNTHETIC_LOCAL_VALUE",- ),- },- {- name: "network",- failure: new CodexSecurityError(- "network failure ECONNRESET token=SYNTHETIC_NETWORK_VALUE",- ),- },- {- name: "timeout",- failure: new CodexSecurityError(- "request timed out token=SYNTHETIC_TIMEOUT_VALUE",- ),- },- ])("applies redaction to $name scan failures", async ({ failure }) => {- for (const value of [undefined, "0", "1"]) {- const stdout = capture();- const stderr = capture();- const deps = dependencies({- environment: { CODEX_SECURITY_REDACT_LOGS: value },- });- deps.createSecurity = () => ({- run: async () => {- throw failure;- },- preflight: async () => fakePreflight(),- close: async () => {},- });- expect(- await main(- ["scan", ".", "--json", "--verbose"],- stdout.stream,- stderr.stream,- deps,- ),- ).toBe(2);- const message = value === "0" ? failure.message : "[redacted]";- expect(JSON.parse(stdout.text()).message).toBe(message);- expect(stderr.text()).toContain(message);- expect(stderr.text().includes(failure.message)).toBe(value === "0");- }- });-- test.each([- "401 invalid API key for synthetic-organization token=SYNTHETIC_AUTH_VALUE",- "403 forbidden for synthetic-organization token=SYNTHETIC_AUTH_VALUE",- ])(- "keeps authentication advice independent of redaction for %s",- async (message) => {- const outputs = [];- for (const value of [undefined, "0"]) {- const stdout = capture();- const stderr = capture();- const deps = dependencies({- environment: { CODEX_SECURITY_REDACT_LOGS: value },- });- deps.createSecurity = () => ({- run: async () => {- throw new CodexSecurityError(message);- },- preflight: async () => fakePreflight(),- close: async () => {},- });- expect(- await main(- ["scan", ".", "--json", "--verbose"],- stdout.stream,- stderr.stream,- deps,- ),- ).toBe(2);- expect(stderr.text()).not.toContain("SYNTHETIC_AUTH_VALUE");- expect(stderr.text()).not.toContain("synthetic-organization");- outputs.push({ stdout: stdout.text(), stderr: stderr.text() });- }- expect(outputs[0]).toEqual(outputs[1]);- },- );-- test.each([undefined, "0"])(- "applies environment value %p to live activity and observer messages",- async (value) => {- const activity = "command result: token=SYNTHETIC_ACTIVITY_VALUE";- const observer = "observer result: token=SYNTHETIC_OBSERVER_VALUE";- const stdout = capture();- const stderr = capture(true);- const deps = dependencies({- environment: {- NO_COLOR: "1",- CODEX_SECURITY_REDACT_LOGS: value,- },- });- deps.createSecurity = () => ({- run: async (_repository, options) => {- options?.onScanStarted?.();- options?.onActivity?.({- id: "synthetic-command",- kind: "command",- status: "completed",- description: activity,- paths: [],- });- options?.onObserverError?.("onWorkerStatus", new Error(observer));- return fakeResult();- },- preflight: async () => fakePreflight(),- close: async () => {},- });-- expect(- await main(["scan", "."], stdout.stream, stderr.stream, deps),- ).toBe(0);- const output = stripVTControlCharacters(stderr.text()).replace(- /\s+/gu,- " ",- );- if (value === "0") {- expect(output).toContain(activity);- expect(output).toContain(observer);- expect(output).not.toContain("[redacted]");- } else {- expect(output).toContain("[redacted]");- expect(output).not.toContain("SYNTHETIC_ACTIVITY_VALUE");- expect(output).not.toContain("SYNTHETIC_OBSERVER_VALUE");- }- expect(stderr.text()).toContain("\u001B[?1049h");- expect(stderr.text()).toContain("\u001B[?1049l");- },- );-});diff --git a/sdk/typescript/tests-ts/cli-skills.test.ts b/sdk/typescript/tests-ts/cli-skills.test.tsindex ab68d17c7..f1069c5b5 100644--- a/sdk/typescript/tests-ts/cli-skills.test.ts+++ b/sdk/typescript/tests-ts/cli-skills.test.ts@@ -1384,7 +1384,7 @@ process.stdout.write(JSON.stringify({},);- test("forwards only completed skill output and redacts subprocess diagnostics", async () => {+ test("forwards completed skill output and classifies authentication failures", async () => {const cases = [{source:@@ -1649,7 +1649,7 @@ lines.on("line", (line) => {);});- test("redacts app-server patch failures", async () => {+ test("classifies app-server patch authentication failures", async () => {const source = ['const readline=require("node:readline");',"const lines=readline.createInterface({input:process.stdin});",diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex 795b657c2..95e52a535 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -987,7 +987,7 @@ describe("CLI", () => {},);- test("keeps credentials out of bulk-scan failures and progress", async () => {+ test("preserves diagnostic text in bulk-scan failures and progress", async () => {const root = await mkdtemp(join(tmpdir(), "codex-security-cli-multiscan-"));try {await multiscanInventory(root);@@ -1021,8 +1021,7 @@ describe("CLI", () => {skipped: 0,});expect(stderr.text()).toContain("sample failed (attempt 1)");- expect(stderr.text()).toContain("[redacted]");- expect(stderr.text()).not.toContain("SYNTHETIC_KEY_123");+ expect(stderr.text()).toContain("scan failed sk-proj-SYNTHETIC_KEY_123");} finally {await rm(root, { recursive: true, force: true });}@@ -2243,8 +2242,7 @@ describe("CLI", () => {);expect(text).not.toContain("thinking ·");expect(text).not.toContain("said ·");- expect(text).toContain("[redacted]");- expect(text).not.toContain("SYNTHETIC_OPENAI_VALUE_123");+ expect(text).toContain("Bearer sk-proj-SYNTHETIC_OPENAI_VALUE_123");expect(text).not.toContain("Building the file inventory");expect(text).not.toContain("Running a scan command");expect(text).toContain("3 / 1,258 reviewed");@@ -3864,7 +3862,7 @@ describe("CLI", () => {}});- test("preserves verbose output paths while redacting observer errors", async () => {+ test("preserves verbose output paths and observer errors", async () => {const stdout = capture();const stderr = capture();const deps = dependencies();@@ -3905,9 +3903,8 @@ describe("CLI", () => {'codex-security: debug: scan.observer_failed observer="onWorkerStatus"',);expect(stderr.text()).toContain(- "onWorkerStatus observer failed: [redacted]",+ `onWorkerStatus observer failed: observer failed ${SYNTHETIC_CREDENTIALS}`,);- expect(stderr.text()).not.toContain("SYNTHETIC_OPENAI_VALUE_123");});test("excludes observer failure context from verbose diagnostics", async () => {@@ -4167,7 +4164,7 @@ describe("CLI", () => {}});- test("redacts credentials from full-output scan failures", async () => {+ test("preserves diagnostic text in full-output scan failures", async () => {const stdout = capture();const stderr = capture();const deps = dependencies();@@ -4191,11 +4188,11 @@ describe("CLI", () => {).toBe(2);expect(JSON.parse(stdout.text()).error).toEqual({code: "SCAN_FAILED",- message: "[redacted]",+ message: `network failure ECONNRESET ${SYNTHETIC_CREDENTIALS}`,});- expect(stdout.text()).not.toContain("SYNTHETIC_KEY_123");- expect(stderr.text()).toContain("[redacted]");- expect(stderr.text()).not.toContain("SYNTHETIC_KEY_123");+ expect(stderr.text()).toContain(+ `network failure ECONNRESET ${SYNTHETIC_CREDENTIALS}`,+ );});test("surfaces underlying scanner errors instead of inventing a model outage", async () => {@@ -4331,7 +4328,7 @@ describe("CLI", () => {}});- test("redacts credentials in underlying network errors", async () => {+ test("preserves diagnostic text in underlying network errors", async () => {const stdout = capture();const stderr = capture();const deps = dependencies();@@ -4351,10 +4348,11 @@ describe("CLI", () => {expect(JSON.parse(stdout.text())).toEqual({status: "failed",code: "SCAN_FAILED",- message: "[redacted]",+ message: `network failure ECONNRESET ${SYNTHETIC_CREDENTIALS}`,});- expect(stderr.text()).toContain("[redacted]");- expect(stderr.text()).not.toContain("SYNTHETIC_KEY_123");+ expect(stderr.text()).toContain(+ `network failure ECONNRESET ${SYNTHETIC_CREDENTIALS}`,+ );expect(stderr.text()).not.toContain("model service could not be reached");});@@ -4378,10 +4376,12 @@ describe("CLI", () => {});expect(await main(["scan"], stdout.stream, stderr.stream, deps)).toBe(2);- expect(stderr.text()).toContain("[redacted]");+ expect(stderr.text()).toContain("unable to open database file");expect(stderr.text()).not.toContain("model service could not be reached");expect(stderr.text()).not.toContain("Check your network connection");- expect(stderr.text()).not.toContain("SYNTHETIC_DATABASE_SECRET");+ expect(stderr.text()).toContain(+ "token=sk-proj-SYNTHETIC_DATABASE_SECRET_123",+ );});test("prints only the completion summary for default scans", async () => {@@ -4565,7 +4565,7 @@ describe("CLI", () => {}});- test("redacts scan warnings in verbose diagnostics", async () => {+ test("preserves scan warnings in verbose diagnostics", async () => {const stdout = capture();const stderr = capture();const deps = dependencies();@@ -4590,10 +4590,11 @@ describe("CLI", () => {).toBe(0);expect(JSON.parse(stdout.text())).toEqual(fakeResult().toJSON());expect(stderr.text()).toContain(- 'codex-security: debug: scan.warning message="[redacted]"',+ 'codex-security: debug: scan.warning message="Repository HEAD changed during the scan: sk-proj-SYNTHETIC_WARNING_SECRET_123"',+ );+ expect(stderr.text()).toContain(+ "codex-security: warning: Repository HEAD changed during the scan: sk-proj-SYNTHETIC_WARNING_SECRET_123",);- expect(stderr.text()).toContain("codex-security: warning: [redacted]");- expect(stderr.text()).not.toContain("SYNTHETIC_WARNING_SECRET");});test("prints granted trusted cyber access without warning or corrupting JSON scans", async () => {@@ -4718,9 +4719,8 @@ describe("CLI", () => {).toBe(0);expect(JSON.parse(stdout.text())).toEqual(fakeResult().toJSON());expect(stderr.text()).toContain(- "codex-security: warning: onWorkerStatus observer failed: [redacted]",+ `codex-security: warning: onWorkerStatus observer failed: status observer failed ${SYNTHETIC_CREDENTIALS}`,);- expect(stderr.text()).not.toContain("SYNTHETIC_OPENAI_VALUE_123");});test("maps failed scan stdout writes to the runtime-error exit code", async () => {@@ -5607,7 +5607,7 @@ describe("CLI", () => {expect(stderr.text()).toContain(`Protected root: ${protectedRoot}`);});- test("redacts credentials in caught scan and interruption failures", async () => {+ test("preserves diagnostic text in caught scan and interruption failures", async () => {for (const failure of [new CodexSecurityError(`scan failed ${SYNTHETIC_CREDENTIALS}`),new ScanInterruptedError(@@ -5630,7 +5630,9 @@ describe("CLI", () => {await main(["scan", "."], stdout.stream, stderr.stream, failing),).toBe(2);expect(stdout.text()).toBe("");- expect(stderr.text()).toBe("[00:00] Preparing scan\n[redacted]\n");+ expect(stderr.text()).toBe(+ `[00:00] Preparing scan\nscan failed ${SYNTHETIC_CREDENTIALS}\n`,+ );}});diff --git a/sdk/typescript/tests-ts/codex-review.test.ts b/sdk/typescript/tests-ts/codex-review.test.tsindex 93b74aa93..11512567a 100644--- a/sdk/typescript/tests-ts/codex-review.test.ts+++ b/sdk/typescript/tests-ts/codex-review.test.ts@@ -43,7 +43,7 @@ const failureReasons: Record<string, string> = {"bad-request-turn": "Invalid model configuration","unknown-turn": "Unknown model failure","request-error": "Authentication required",- "credential-error": "[redacted]",+ "credential-error": "Authentication failed: Bearer synthetic-review-key","invalid-json": "Codex returned malformed JSON","invalid-submission": "Review validation failed: Invalid decision","required-source-error":@@ -379,19 +379,17 @@ for (const {: 1) * sessions,reason: refused? "The model refused the deduplication review."- : scenario === "credential-error"- ? "[redacted]"- : scenario === "invalid-submission"- ? "The submitted review failed semantic validation."- : scenario === "text-only"- ? "Codex did not submit a validated review."- : modelFailures.has(scenario)- ? "Codex review turn failed."- : reportsBlocker- ? "A required review check could not be completed."- : scenario === "request-error"- ? "Codex rejected the review request."- : "Codex review transport failed.",+ : scenario === "invalid-submission"+ ? "The submitted review failed semantic validation."+ : scenario === "text-only"+ ? "Codex did not submit a validated review."+ : modelFailures.has(scenario)+ ? "Codex review turn failed."+ : reportsBlocker+ ? "A required review check could not be completed."+ : ["request-error", "credential-error"].includes(scenario)+ ? "Codex rejected the review request."+ : "Codex review transport failed.",});const supportBundle = JSON.stringify(reviewFailure.metadata);expect(supportBundle).not.toContain("synthetic-review-key");diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.tsindex 06a1d0ac0..9a3b3eb8b 100644--- a/sdk/typescript/tests-ts/component-scan.test.ts+++ b/sdk/typescript/tests-ts/component-scan.test.ts@@ -369,13 +369,16 @@ test("bounds standard scans, continues after failure, and preserves partial resuexpect(await json(summary.summaryPath!)).toMatchObject({completeness: "partial",findingCount: 2,+ components: expect.arrayContaining([+ expect.objectContaining({+ id: "component-1",+ error: "Authorization: Bearer SYNTHETIC_SECRET_123",+ }),+ ]),});expect(await json(summary.retryPlanPath!)).toEqual({components: components.slice(0, 2),});- expect(await readFile(summary.summaryPath!, "utf8")).not.toContain(- "SYNTHETIC_SECRET_123",- );expect(await readFile(join(paths.outputDir, "component-2", "report.md"), "utf8"),).toBe("Original report");@@ -549,6 +552,42 @@ test.each([},);+test("CLI escapes component failure controls while preserving the saved error", async () => {+ const paths = await fixture();+ const failure = "Component failed: token=SYNTHETIC_VALUE\u001b[2J\ncontinued";+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "scan-components",+ paths.repository,+ "--component",+ "apps/api",+ "--output-dir",+ paths.outputDir,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ {+ ...dependencies({ currentDirectory: paths.root }),+ createSecurity: client(async () => {+ throw new Error(failure);+ }),+ },+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(+ "Component failed: token=SYNTHETIC_VALUE [2J continued\n",+ );+ expect(stderr.text()).not.toContain("\u001b");+ const result = JSON.parse(stdout.text());+ expect(await json(result.summaryPath)).toMatchObject({+ components: [expect.objectContaining({ error: failure })],+ });+});+test("CLI restores the dashboard and reports saved partial results on cancellation", async () => {const paths = await fixture();const stdout = capture();@@ -1416,6 +1455,7 @@ test.each([false, true])("CLI reports matching completion (failure: %j)",async (failMatching) => {const paths = await fixture();+ const failure = "Authorization: Bearer SYNTHETIC_MATCH_SECRET_123";let calls = 0;const result = await cli(paths,@@ -1437,8 +1477,7 @@ test.each([false, true])(model: "gpt-5.6-terra",model_reasoning_effort: "high",});- if (failMatching)- throw new Error("Authorization: Bearer SYNTHETIC_MATCH_SECRET_123");+ if (failMatching) throw new Error(failure);return {matches: [match([before[0]!.occurrenceId], [after[0]!.occurrenceId]),@@ -1459,8 +1498,11 @@ test.each([false, true])(failed: 0,deduplication: { status: failMatching ? "incomplete" : "completed" },});- expect(saved + result.stdout + result.stderr).not.toContain(- "SYNTHETIC_MATCH_SECRET_123",+ expect(JSON.parse(saved).deduplication.error).toBe(+ failMatching ? failure : undefined,+ );+ expect(JSON.parse(result.stdout).deduplication.error).toBe(+ failMatching ? failure : undefined,);},);diff --git a/sdk/typescript/tests-ts/errors.property.test.ts b/sdk/typescript/tests-ts/errors.property.test.tsindex ced620dc7..8f6d2a18f 100644--- a/sdk/typescript/tests-ts/errors.property.test.ts+++ b/sdk/typescript/tests-ts/errors.property.test.ts@@ -1,63 +1,14 @@import { describe, expect, test } from "bun:test";import fc from "fast-check";-import { errorMessage, safeErrorMessage } from "../src/errors.js";+import { errorMessage } from "../src/errors.js";import { propertyOptions } from "./support/property.js";-const word = fc.stringMatching(/^[a-zA-Z0-9]{1,40}$/u);-const credential = word.map((value) => `SYNTHETIC_${value}`);-describe("error-message invariants", () => {- test("omits recognized credentials in plain, JSON, and URL-encoded errors", () => {- fc.assert(- fc.property(- credential,- fc.constantFrom(- "api_key",- "apikey",- "accesskey",- "access-key",- "privatekey",- "private-key",- "sig",- "access_token",- "clientSecret",- "password",- "authorization",- ),- (secret, field) => {- const json = JSON.stringify({ [field]: secret });- for (const message of [- `${field}=${secret}`,- json,- JSON.stringify(json),- encodeURIComponent(json),- `Bearer ${secret}`,- `Basic ${secret}`,- `token%20${secret}`,- `sk-${secret}`,- `sk-proj-${secret}`,- `github_pat_${secret}`,- ...["ghp_", "gho_", "ghu_", "ghs_", "ghr_", "npm_"].map(- (prefix) => `${prefix}${secret}`,- ),- `https://synthetic:${secret}@example.test/`,- ]) {- expect(safeErrorMessage(message)).toBe("[redacted]");- expect(safeErrorMessage(new Error(message))).toBe("[redacted]");- expect(errorMessage(new Error(message))).toBe(message);- }- },- ),- propertyOptions,- );- });-- test("preserves ordinary diagnostic text exactly", () => {+ test("preserves arbitrary diagnostic text exactly", () => {fc.assert(- fc.property(fc.nat(), word, (index, detail) => {- const message = `operation failed for item ${index} (${detail})`;- expect(safeErrorMessage(message)).toBe(message);- expect(safeErrorMessage(new Error(message))).toBe(message);+ fc.property(fc.string(), (message) => {+ expect(errorMessage(message)).toBe(message);+ expect(errorMessage(new Error(message))).toBe(message);}),propertyOptions,);diff --git a/sdk/typescript/tests-ts/errors.test.ts b/sdk/typescript/tests-ts/errors.test.tsindex a18f9cbdc..656a4e907 100644--- a/sdk/typescript/tests-ts/errors.test.ts+++ b/sdk/typescript/tests-ts/errors.test.ts@@ -5,8 +5,6 @@ import {ScanCostLimitExceededError,ScanInterruptedError,errorMessage,- logErrorMessage,- safeErrorMessage,} from "../src/errors.js";describe("error messages", () => {@@ -61,8 +59,13 @@ describe("error messages", () => {expect(limit.message).toContain("/scan");});- test("preserves error messages exactly", () => {- const message = "request failed: token=SYNTHETIC_TOKEN";+ test.each([+ "request failed: token=SYNTHETIC_TOKEN",+ "Authorization: Bearer sk-proj-SYNTHETIC_KEY_123",+ "token budget exceeded",+ "basic validation failed",+ "unable to open database file",+ ])("preserves error messages exactly: %s", (message) => {expect(errorMessage(new Error(message))).toBe(message);expect(errorMessage(message)).toBe(message);});@@ -71,65 +74,4 @@ describe("error messages", () => {expect(errorMessage(42)).toBe("42");expect(errorMessage(null)).toBe("null");});-- test.each([undefined, "1", "", "false", "unexpected"])(- "keeps log redaction enabled with environment value %p",- (value) => {- const environment = { CODEX_SECURITY_REDACT_LOGS: value };- expect(- logErrorMessage(new Error("token=SYNTHETIC_TOKEN"), environment),- ).toBe("[redacted]");- expect(logErrorMessage("service unavailable", environment)).toBe(- "service unavailable",- );- },- );-- test("opts out of log redaction without changing persistence redaction", () => {- const message = "request failed: token=SYNTHETIC_TOKEN";- const error = new Error(message);- const environment = { CODEX_SECURITY_REDACT_LOGS: "0" };- expect(logErrorMessage(error, environment)).toBe(message);- expect(logErrorMessage(message, environment)).toBe(message);- expect(logErrorMessage(null, environment)).toBe("null");- expect(safeErrorMessage(error)).toBe("[redacted]");- });-- test("omits credential-bearing messages at output boundaries", () => {- for (const message of [- "request failed: token=SYNTHETIC_TOKEN",- "Authorization: Bearer sk-proj-SYNTHETIC_KEY_123",- 'upstream failed: {"clientSecret":"correct horse battery staple"}',- JSON.stringify(JSON.stringify({ clientSecret: "SYNTHETIC_SECRET" })),- "authorizationHeaderValue=SYNTHETIC_SECRET",- "api_key_header_value=SYNTHETIC_SECRET",- 'config["api_key"]="SYNTHETIC_SECRET"',- JSON.stringify('config["api_key"]="SYNTHETIC_SECRET"'),- encodeURIComponent(JSON.stringify({ api_key: "SYNTHETIC_SECRET" })),- "https://example.test/?credentials[access_token]=SYNTHETIC_SECRET",- "https://example.test/?user[password]=SYNTHETIC_SECRET",- "https://example.test/?config[api_key]=SYNTHETIC_SECRET",- "https://example.test/?access%5Fkey=SYNTHETIC_SECRET",- "https://example.test/?private%2Dkey=SYNTHETIC_SECRET",- "sig_value=SYNTHETIC_SIGNATURE",- "sigHeader=SYNTHETIC_SIGNATURE",- "proxy https://user:[email protected]",- "-----BEGIN PRIVATE KEY-----\nSYNTHETIC_PRIVATE_KEY",- "-----BEGIN PGP PRIVATE KEY BLOCK-----\nSYNTHETIC_PRIVATE_KEY",- ]) {- expect(safeErrorMessage(new Error(message))).toBe("[redacted]");- }- expect(safeErrorMessage("upstream service unavailable")).toBe(- "upstream service unavailable",- );- expect(safeErrorMessage("author=Michael")).toBe("author=Michael");- expect(safeErrorMessage("signal=active")).toBe("signal=active");- expect(safeErrorMessage("design=complete")).toBe("design=complete");- expect(safeErrorMessage('worker 1: rg -n "password" src/login.ts')).toBe(- 'worker 1: rg -n "password" src/login.ts',- );- expect(safeErrorMessage("secret".repeat(4_000))).toBe(- "secret".repeat(4_000),- );- });});diff --git a/sdk/typescript/tests-ts/github.test.ts b/sdk/typescript/tests-ts/github.test.tsindex 1eed0f7c5..f9b377f6b 100644--- a/sdk/typescript/tests-ts/github.test.ts+++ b/sdk/typescript/tests-ts/github.test.ts@@ -195,9 +195,8 @@ describe("GitHub code scanning import", () => {[403, "denied code scanning access"],[404, "not found or is not accessible"],[429, "rate limited"],- [503, "HTTP 503"],] as const)(- "reports HTTP %i without exposing token-bearing diagnostics",+ "reports actionable advice for HTTP %i",async (status, message) => {const failure = await importGitHubCodeScanningAlerts({ repository: "example/repository" },@@ -216,6 +215,31 @@ describe("GitHub code scanning import", () => {},);+ test("preserves unclassified HTTP and transport error details", async () => {+ const message = "Connection failed: token=SYNTHETIC_DIAGNOSTIC_VALUE";+ const failure = Object.assign(new Error(message), {+ request: { headers: { authorization: "SYNTHETIC_REQUEST_HEADER" } },+ });+ for (const status of [503, undefined]) {+ const result = await importGitHubCodeScanningAlerts(+ { repository: "example/repository" },+ {+ createGitHub: async () => {+ if (status === undefined) throw failure;+ return github(() => Response.json({ message }, { status }));+ },+ },+ ).catch((error: Error) => error);+ expect(result).toBeInstanceOf(Error);+ expect((result as Error).message).toContain(message);+ if (status !== undefined)+ expect((result as Error).message).toContain(`HTTP ${status}`);+ expect((result as Error).message).not.toContain(+ "SYNTHETIC_REQUEST_HEADER",+ );+ }+ });+test("validates selectors before authentication and supports cancellation", async () => {let authenticated = false;const createGitHub = async () => {diff --git a/sdk/typescript/tests-ts/linear.test.ts b/sdk/typescript/tests-ts/linear.test.tsindex 0ddcfd503..22ee602eb 100644--- a/sdk/typescript/tests-ts/linear.test.ts+++ b/sdk/typescript/tests-ts/linear.test.ts@@ -156,13 +156,13 @@ describe("Linear issue intake", () => {}});- test("reports SDK failures without exposing credentials", async () => {+ test("reports SDK failures with original diagnostic details", async () => {for (const [error, message] of [[new AuthenticationLinearError(), "Linear authentication failed."],[new RatelimitedLinearError(), "Linear request was rate limited."],[new Error("Invalid lin_api_SYNTHETIC_SECRET"),- "Linear request failed: [redacted]",+ "Linear request failed: Invalid lin_api_SYNTHETIC_SECRET",],] as const) {await expect(diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.tsindex 2918d5f2d..9bcadcaa9 100644--- a/sdk/typescript/tests-ts/multiscan.test.ts+++ b/sdk/typescript/tests-ts/multiscan.test.ts@@ -307,6 +307,50 @@ describe("multiscan", () => {);});+ test("CLI escapes bulk failure controls while preserving the saved receipt", async () => {+ const paths = await fixture();+ const source = await repository(paths.root, "failure");+ await writeFile(+ paths.input,+ `id,repository,revision\nrepo,${source.path},${source.revision}\n`,+ );+ const failure = "Bulk failed: token=SYNTHETIC_VALUE\u001b[2J\ncontinued";+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ expect(+ await main(+ [+ "bulk-scan",+ paths.input,+ "--output-dir",+ paths.output,+ "--max-attempts",+ "1",+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ {+ ...deps,+ createSecurity: (config) => ({+ ...deps.createSecurity(config),+ run: async () => {+ throw new Error(failure);+ },+ }),+ },+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(+ "Bulk failed: token=SYNTHETIC_VALUE [2J continued\n",+ );+ expect(stderr.text()).not.toContain("\u001b");+ expect(await results(JSON.parse(stdout.text()).resultsPath)).toMatchObject([+ { status: "failed", error: failure },+ ]);+ });+test("recovery skips untouched rows and saves an interrupted ledger tail before appending", async () => {const paths = await fixture();const source = await repository(paths.root, "tail");@@ -1943,24 +1987,8 @@ describe("multiscan", () => {test("retries a failed attempt and records both durable receipts", async () => {const paths = await fixture();const source = await repository(paths.root, "retry");- const secret = "sk-proj-SYNTHETIC_MULTISCAN_SECRET_123";+ const failure = "temporary failure: token=SYNTHETIC_MULTISCAN_TOKEN";const knowledgeBasePaths = ["architecture.md"];- const proxyUrl =- "https://SYNTHETIC_USER:[email protected]/v1/responses";- const queryUrl =- "https://proxy.test/v1/responses?api_key=SYNTHETIC_MULTISCAN_QUERY_123&safe=1";- const shortAuthorization = "Bearer abc123";- const suffixedSecret = "SYNTHETIC_SUFFIXED_CLIENT_SECRET_123";- const suffixedToken = "SYNTHETIC_SUFFIXED_ACCESS_TOKEN_123";- const suffixedQuery = "SYNTHETIC_SUFFIXED_QUERY_SECRET_123";- const quotedSecret = "SYNTHETIC correct horse battery staple";- const opaqueAuthorization = "SYNTHETIC opaque authorization secret";- const npmAuthorization = "SYNTHETIC_NPM_AUTH_VALUE_123";- const customAuthorization = "SYNTHETIC_CUSTOM_AUTHORIZATION_123";- const suffixedAuthorization = "SYNTHETIC_SUFFIXED_AUTHORIZATION_123";- const paddedAuthorization = "SYNTHETIC_PADDED_AUTHORIZATION_TOKEN==";- const keyedAuthorization = "SYNTHETIC_KEYED_AUTHORIZATION_SECRET_123";- const camelCaseSecret = "SYNTHETIC_CAMEL_CASE_CLIENT_SECRET_123";await writeFile(paths.input,`id,repository,revision\nretry,${source.path},${source.revision}\n`,@@ -1974,9 +2002,7 @@ describe("multiscan", () => {expect(scanOptions.knowledgeBasePaths).toEqual(knowledgeBasePaths);attempts += 1;if (attempts === 1) {- throw new Error(- `temporary failure ${secret} ${shortAuthorization} client_secret_value=${suffixedSecret} access_token_value=${suffixedToken} ${JSON.stringify({ client_secret_value: quotedSecret })} authorization="${opaqueAuthorization}" _auth=${npmAuthorization} Authorization: ApiKey ${customAuthorization} client_authorization_value=ApiKey ${suffixedAuthorization} auth=ApiKey ${paddedAuthorization} Authorization: Custom key=${keyedAuthorization} clientSecretValue=${camelCaseSecret} sending request for url (${proxyUrl}) and ${queryUrl}&client_secret_value=${suffixedQuery}`,- );+ throw new Error(failure);}return await completedScan(scanOptions.outputDir!);}),@@ -1987,12 +2013,9 @@ describe("multiscan", () => {expect(attempts).toBe(2);expect(summary).toMatchObject({ completed: 1, failed: 0 });expect(await results(summary.resultsPath)).toMatchObject([- { id: "retry", status: "failed", attempt: 1 },+ { id: "retry", status: "failed", attempt: 1, error: failure },{ id: "retry", status: "completed", attempt: 2 },]);- const ledger = await readFile(summary.resultsPath, "utf8");- expect(ledger).toContain('"error":"[redacted]"');- expect(ledger).not.toContain("SYNTHETIC");});test("resumes complete bundles, repairs missing output, and rejects manifest drift", async () => {diff --git a/sdk/typescript/tests-ts/patch-tui.test.ts b/sdk/typescript/tests-ts/patch-tui.test.tsindex 1239c141a..15a7055b3 100644--- a/sdk/typescript/tests-ts/patch-tui.test.ts+++ b/sdk/typescript/tests-ts/patch-tui.test.ts@@ -225,8 +225,7 @@ describe("interactive patch finding browser", () => {expect(reviewed).toContain("› │");expect(reviewed).toContain("includeDeleted: false");expect(reviewed).toContain("7 │ audit.record(tenant);");- expect(reviewed).toContain("[redacted]");- expect(reviewed).not.toContain("SYNTHETIC_KEY_123");+ expect(reviewed).toContain('const token = "sk-proj-SYNTHETIC_KEY_123";');expect(reviewed).toContain("../outside.ts:1");expect(reviewed).toContain("src/outside-link.ts:1");expect(reviewed).not.toContain("OUTSIDE_PRIVATE_SOURCE");@@ -381,7 +380,7 @@ describe("interactive patch finding browser", () => {}});- test("sanitizes terminal escapes and credential-bearing finding details", () => {+ test("strips terminal escapes and preserves credential-shaped finding details", () => {const [finding] = findings(["high"]);finding!.title = "\u001B[31mUnsafe title\u001B[0m\nforged line";finding!.summary = "sk-proj-SYNTHETIC_KEY_123";@@ -395,8 +394,7 @@ describe("interactive patch finding browser", () => {);expect(app.lastFrame()).toContain("Unsafe title forged line");- expect(app.lastFrame()).toContain("[redacted]");- expect(app.lastFrame()).not.toContain("SYNTHETIC_KEY_123");+ expect(app.lastFrame()).toContain("sk-proj-SYNTHETIC_KEY_123");expect(app.lastFrame()).not.toContain("\u001B[31m");});diff --git a/sdk/typescript/tests-ts/publication-integration.test.ts b/sdk/typescript/tests-ts/publication-integration.test.tsindex 26dcdfa99..03d9b8d09 100644--- a/sdk/typescript/tests-ts/publication-integration.test.ts+++ b/sdk/typescript/tests-ts/publication-integration.test.ts@@ -967,11 +967,9 @@ describe("database-backed Linear publication integration", () => {result.created.map(({ issueIdentifier }) => issueIdentifier),).toEqual(["SEC-801", "SEC-802"]);expect(result.warnings).toEqual([- "Could not save the publication receipt: [redacted]. Linear issues were already created; do not retry publication.",+ "Could not save the publication receipt: Receipt storage unavailable: sk-proj-SYNTHETIC_RECEIPT_SECRET. Linear issues were already created; do not retry publication.",]);expect(stderr.text()).toContain(result.warnings![0]!);- expect(stdout.text()).not.toContain("SYNTHETIC_RECEIPT_SECRET");- expect(stderr.text()).not.toContain("SYNTHETIC_RECEIPT_SECRET");expect(publicationAttempts).toBe(1);expect(storedPublications(completed).map(({ external_id }) => external_id),diff --git a/sdk/typescript/tests-ts/publish.test.ts b/sdk/typescript/tests-ts/publish.test.tsindex 7720aeb40..a5a703f21 100644--- a/sdk/typescript/tests-ts/publish.test.ts+++ b/sdk/typescript/tests-ts/publish.test.ts@@ -3651,9 +3651,8 @@ describe("connected Linear publication", () => {failed: partialFailure ? 1 : 0,});expect(result.warnings).toEqual([- "Could not save the publication receipt: [redacted]. Linear issues were already created; do not retry publication.",+ "Could not save the publication receipt: OPENAI_API_KEY=sk-proj-SYNTHETIC_RECEIPT_SECRET_123. Linear issues were already created; do not retry publication.",]);- expect(JSON.stringify(result)).not.toContain("SYNTHETIC_RECEIPT_SECRET");expect(progress.at(-1)).toEqual({type: "completed",created: expectedCreated.length,diff --git a/sdk/typescript/tests-ts/scan-dashboard.test.ts b/sdk/typescript/tests-ts/scan-dashboard.test.tsindex e814f773a..2f8c6b58a 100644--- a/sdk/typescript/tests-ts/scan-dashboard.test.ts+++ b/sdk/typescript/tests-ts/scan-dashboard.test.ts@@ -313,7 +313,7 @@ describe("live scan dashboard", () => {expect(stderr.text().split("\u001B[?1049h")).toHaveLength(2);});- test("navigates a long component list and shows sanitized failure details", () => {+ test("navigates a long component list and shows original failure details", () => {const stderr = capture(true);const input = new DashboardTestInput();let interrupted = false;@@ -324,7 +324,6 @@ describe("live scan dashboard", () => {presentation: "components",input,clock: fakeClock(),- sanitize: (value) => value.replaceAll("synthetic-secret", "[redacted]"),onInterrupt: () => {interrupted = true;},@@ -352,7 +351,7 @@ describe("live scan dashboard", () => {input.emit("data", "\u001B[F");expect(frame()).toContain("Component 19");expect(frame()).not.toContain("Component 0 ");- expect(frame()).toContain("[redacted] unavailable");+ expect(frame()).toContain("synthetic-secret unavailable");expect(frame()).not.toContain("Cost");expect(frame()@@ -946,7 +945,7 @@ describe("live scan dashboard", () => {dashboard.stop();});- test("shows unredacted, chronological session events and keeps the activity view safe", () => {+ test("preserves chronological session events and strips terminal controls from activity", () => {const stderr = capture(true);const input = new DashboardTestInput();const dashboard = new ScanDashboard(@@ -956,7 +955,6 @@ describe("live scan dashboard", () => {input,color: true,clock: fakeClock(),- sanitize: (value) => value.replaceAll("synthetic-secret", "[redacted]"),},);@@ -1030,7 +1028,7 @@ describe("live scan dashboard", () => {}let frame = lastFrame(stderr);- expect(frame).toContain("rg -n [redacted] routes/login.ts");+ expect(frame).toContain("rg -n synthetic-secret routes/login.ts");expect(frame).toContain("d details");input.emit("data", "d");@@ -1078,8 +1076,7 @@ describe("live scan dashboard", () => {input.emit("data", "d");frame = lastFrame(stderr);- expect(frame).toContain("rg -n [redacted] routes/login.ts");- expect(frame).not.toContain("synthetic-secret");+ expect(frame).toContain("rg -n synthetic-secret routes/login.ts");dashboard.stop();});@@ -1358,7 +1355,7 @@ describe("live scan dashboard", () => {dashboard.stop();});- test("redacts external Markdown link targets and rejects unsafe links", () => {+ test("preserves external Markdown link targets and rejects unsafe links", () => {const stderr = capture(true);const dashboard = new ScanDashboard({ ...stderr.stream, columns: 120, rows: 18 },@@ -1366,7 +1363,6 @@ describe("live scan dashboard", () => {repository: "/code/juice-shop",color: false,clock: fakeClock(),- sanitize: (value) => value.replaceAll("secret-token", "[redacted]"),},);@@ -1381,9 +1377,8 @@ describe("live scan dashboard", () => {});expect(stderr.text()).toContain(- "See \u001B]8;;https://example.com/report?token=[redacted]\u0007report\u001B]8;;\u0007, unsafe, and control.",+ "See \u001B]8;;https://example.com/report?token=secret-token\u0007report\u001B]8;;\u0007, unsafe, and control.",);- expect(stderr.text()).not.toContain("secret-token");expect(stderr.text()).not.toContain("javascript:");expect(stderr.text()).not.toContain("spoof");expect(stderr.text()).not.toContain("\u001B]8;;javascript:");@@ -1402,7 +1397,7 @@ describe("live scan dashboard", () => {dashboard.stop();});- test("sanitizes complete activity descriptions before line wrapping", () => {+ test("preserves credential-shaped activity descriptions across line wrapping", () => {const stderr = capture(true);const dashboard = new ScanDashboard({ ...stderr.stream, columns: 50, rows: 18 },@@ -1410,8 +1405,6 @@ describe("live scan dashboard", () => {repository: "/code/juice-shop",color: false,clock: fakeClock(),- sanitize: (value) =>- value.includes("client_secret=") ? "[redacted]" : value,},);@@ -1425,8 +1418,8 @@ describe("live scan dashboard", () => {paths: [],});- expect(lastFrame(stderr)).toContain("[redacted]");- expect(stderr.text()).not.toContain("SYNTHETIC_SECRET_VALUE");+ expect(lastFrame(stderr)).toContain("client_secret=");+ expect(lastFrame(stderr)).toContain("SYNTHETIC_SECRET_VALUE");dashboard.stop();});