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
feat: upload to Codex Security Cloud (#612)
Will Holleyf85eeff2568a
diff --git a/README.md b/README.mdindex b6fb48217..9fe844e16 100644--- a/README.md+++ b/README.md@@ -133,15 +133,18 @@ incomplete or their original location was not reviewed.Publish every finding from a completed scan to a Linear team:```bash-npx @openai/codex-security publish scan /path/to/scan \+npx @openai/codex-security publish scan --scan SCAN_ID \--to linear \--linear-team TEAM_ID```Add `--linear-project PROJECT_ID` to place the issues in a Linear project, oromit it to create issues directly in the team. The existing `--project` flag-remains an alias. Omit the scan directory to select a-completed scan interactively. You can also set `CODEX_SECURITY_LINEAR_TEAM` and+remains an alias. Omit `--scan` to select a completed scan interactively. Use+`scans list --json` to find saved scan IDs, or pass `--scan latest` for the+current repository's latest completed scan. External scan artifacts can still+be supplied with `--scan-dir PATH` or a positional directory.+You can also set `CODEX_SECURITY_LINEAR_TEAM` andthe optional `CODEX_SECURITY_LINEAR_PROJECT` instead of passing the destinationflags. Add `--dry-run` to preview the issues or `--json` to returnmachine-readable results.diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex c87f8848d..3c10c62ef 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -730,6 +730,80 @@ and scans stopped at their configured cost limit do not start another turn.invocation and defaults to `1`. Results remain under `--output-dir`; rerun thesame command to resume.+### Publish multiple completed scans to Cloud++Choose completed scans from your local history:++```bash+npx @openai/codex-security publish scan --to cloud --dry-run --json+```++The picker shows each scan's repository, finding count, age, and scan ID.+Choose scans, then select **Done**. No scans are selected automatically.++For scripts, repeat `--scan` with saved scan IDs or unique ID prefixes (at+least eight characters):++```bash+npx @openai/codex-security publish scan \+ --scan SCAN_ID_A --scan SCAN_ID_B \+ --to cloud --dry-run --json+```++Use `scans list --json` to find IDs for the current repository. `--scan latest`+selects its latest completed scan. The CLI resolves IDs through saved history,+processes each selected scan once, and checks that its sealed artifacts match+the selected ID. The artifacts must still be available locally.++`--dry-run` validates the scans and prints their findings without uploading or+requiring a login. Remove `--dry-run` to upload. Live uploads require ChatGPT+credentials explicitly stored in a file. Set this in your Codex `config.toml`,+then sign in with ChatGPT again:++```toml+cli_auth_credentials_store = "file"+```++Automatic and keyring credential storage are not accepted for Cloud+publication, even when an `auth.json` file exists, because that file may be+stale and belong to a different account. The CLI sends one scan at a time,+with each scan's findings and metadata in a separate request.++For artifacts outside local history, use repeated `--scan-dir PATH` instead.+A single positional directory is still accepted and can be combined with+`--scan-dir`. Do not combine directory inputs with `--scan`. Each directory+must contain one completed, sealed scan; bulk-run directories and+`results.jsonl` files are not accepted. Relative paths start at the current+directory, and `~/...` starts at your home directory. Each resolved directory+is processed once.++For multiple distinct scans, output contains:++- `results`: receipts or dry-run previews, each with its `scanId` and `scanDir`.+- `failed`: errors with `scanDir` and, for saved selections, `scanId`.+- `notAttempted`: saved scan IDs, or paths for directory inputs, that the command+ did not reach before cancellation.++For one distinct scan, the CLI returns the scan result directly,+without the batch fields above.++The CLI continues after a failed scan and exits with code `2` if any scan+fails. Ctrl-C or SIGTERM stops new requests and returns the results collected+so far. When cancellation stops work before every requested publication is+confirmed, the exit code is `130` for Ctrl-C and `143` for SIGTERM. If the+single response or final batch response has already confirmed the complete+publication, the command exits with code `0`. Cloud publication receipts+appear in command output; the CLI does not save them to scan history.++A successful receipt contains one opaque Cloud finding ID for each submitted+finding, in request order. These are not local finding IDs. The CLI verifies+the authenticated response status, count, and ID uniqueness, but cannot map+opaque server IDs back to individual local findings independently.++The CLI never retries an upload automatically. An upload with a missing or+invalid receipt may already have been accepted. Check whether Cloud accepted+that scan before retrying it. Do not resend scans with confirmed receipts.+### Custom validationUse a prompt file to replace the final validation step in a standard or diff@@ -802,17 +876,21 @@ Publish every finding from a completed standard, deep, or scoped scan to oneLinear team:```bash-npx @openai/codex-security publish scan /path/to/completed-scan \+npx @openai/codex-security publish scan --scan SCAN_ID \--to linear \--linear-team TEAM_ID```+Linear accepts one scan. Use a saved scan ID, a unique ID prefix, or `latest`.+For external artifacts, a positional directory or `--scan-dir PATH` is also+accepted.+Add `--linear-project PROJECT_ID` to place the issues in a Linear project.The existing `--project` flag remains an alias. Without a project, issues arecreated directly in the selected team.To choose from all completed scans saved in your local scan history, omit the-scan directory. The selector highlights each repository and shows its finding+scan selector. The selector highlights each repository and shows its findingcount, relative run time, and abbreviated scan ID:```bashdiff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjsindex 7074bdcd3..ca7820224 100644--- a/sdk/typescript/scripts/check-package.mjs+++ b/sdk/typescript/scripts/check-package.mjs@@ -165,6 +165,7 @@ const distFiles = new Set("auth","bulk-scan-discovery","cli",+ "cloud-publish","codex-prompt","component-plan","component-scan",diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex c6ea0dec5..4f39a36f6 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -55,6 +55,10 @@ import {type ScanPreflight,} from "./api.js";import { accountStatus } from "./auth.js";+import {+ publishScanToCloud,+ type CloudPublicationResult,+} from "./cloud-publish.js";import {createBulkScanDiscoveryDependencies,runBulkScanWizard,@@ -237,6 +241,7 @@ const VALUE_OPTIONS = new Set(["--patch-severity","--resume-pr","--scan",+ "--scan-dir","--severity","--max-cost","--workers",@@ -966,6 +971,7 @@ interface CliDependencies {scanAuthenticationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;publishPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;publishScan?: typeof publishScan;+ publishScanToCloud?: typeof publishScanToCloud;confirmPatchReview?: (question: string) => Promise<boolean>;patchEditor?: (repository: string,@@ -1897,7 +1903,25 @@ export async function main(.describe("Completed scan directory; omit to select a saved scan."),}),options: z.object({- to: z.literal("linear").describe("Publication destination."),+ scan: z+ .array(optionValue("--scan"))+ .default([])+ .describe(+ "Saved scan ID, unique prefix, or latest; repeat for multiple scans (Linear accepts one).",+ ),+ scanDir: z+ .array(optionValue("--scan-dir"))+ .default([])+ .describe(+ "External completed scan directory; repeat for multiple scans (Linear accepts one).",+ ),+ // Cloud remains an internal destination, omitted from public discovery.+ to: z+ .string()+ .refine((value) => value === "linear" || value === "cloud", {+ message: "Unsupported publication destination. Use --to linear.",+ })+ .describe("Publication destination (linear)."),linearTeam: optionValue("--linear-team").optional().describe("Linear team ID; defaults to CODEX_SECURITY_LINEAR_TEAM."),@@ -1925,18 +1949,81 @@ export async function main(async run({ args, format, formatExplicit, options }) {const controller = new AbortController();let presentation: PublicationProgressPresenter | undefined;+ let cloudBatch:+ | {+ results: (CloudPublicationResult & { scanDir: string })[];+ failed: { scanDir: string; scanId?: string; error: string }[];+ notAttempted: string[];+ }+ | undefined;const cancel = (signal: SignalName): void => {presentation?.stop();controller.abort(signal);};+ const finishCancellation = (error?: unknown): boolean => {+ const signal = controller.signal.reason;+ if (signal !== "SIGINT" && signal !== "SIGTERM") return false;+ const reason =+ signal === "SIGINT"+ ? "Publication canceled by Ctrl-C."+ : "Publication terminated by SIGTERM.";+ const recovery =+ error === undefined || error === signal+ ? ""+ : ` ${diagnosticValue(safeErrorMessage(error))}`;+ errorOutput.write(`codex-security: ${reason}${recovery}\n`);+ exitCode = signal === "SIGINT" ? 130 : 143;+ return true;+ };const onInterrupt = (): void => cancel("SIGINT");const onTerminate = (): void => cancel("SIGTERM");let observingSignals = false;try {- const linearApiKey = resolveLinearApiKey(- dependencies.environment,- options.linearApiKey,- );+ const currentDirectory = dependencies.currentDirectory();+ const directories = [+ ...new Set(+ [+ ...(args.scanDir === undefined ? [] : [args.scanDir]),+ ...options.scanDir,+ ].map((directory) => resolveCliPath(currentDirectory, directory)),+ ),+ ];+ if (directories.length > 1 && options.to !== "cloud") {+ throw new CodexSecurityError(+ "Multiple scan directories are only supported with --to cloud.",+ );+ }+ if (options.scan.length > 0 && directories.length > 0) {+ throw new CodexSecurityError(+ "Use --scan or scan directory inputs, not both.",+ );+ }+ if (new Set(options.scan).size > 1 && options.to !== "cloud") {+ throw new CodexSecurityError(+ "Multiple scans are only supported with --to cloud.",+ );+ }+ if (+ options.to === "cloud" &&+ [+ options.linearTeam,+ options.linearApiKey,+ options.linearProject,+ options.project,+ options.linearAssignee,+ ].some((value) => value !== undefined)+ ) {+ throw new CodexSecurityError(+ "Cloud publication cannot be combined with Linear options.",+ );+ }+ const linearApiKey =+ options.to === "linear"+ ? resolveLinearApiKey(+ dependencies.environment,+ options.linearApiKey,+ )+ : undefined;const assigneeId = options.linearAssignee?.trim();if (options.linearAssignee !== undefined && !assigneeId) {throw new CodexSecurityError("--linear-assignee must not be empty.");@@ -1948,8 +2035,9 @@ export async function main(}const teamId =options.linearTeam?.trim() ||- dependencies.environment["CODEX_SECURITY_LINEAR_TEAM"]?.trim();- if (!teamId) {+ dependencies.environment["CODEX_SECURITY_LINEAR_TEAM"]?.trim() ||+ "";+ if (options.to === "linear" && !teamId) {throw new CodexSecurityError("--linear-team or CODEX_SECURITY_LINEAR_TEAM is required.",);@@ -1975,7 +2063,21 @@ export async function main(dependencies.environment["CODEX_SECURITY_LINEAR_PROJECT"]?.trim() ||undefined;- let scanDir = args.scanDir;+ if (options.to === "cloud") {+ dependencies.addSignalListener("SIGINT", onInterrupt);+ dependencies.addSignalListener("SIGTERM", onTerminate);+ observingSignals = true;+ }+ const selectedScans: { scanDir: string; scanId?: string }[] =+ directories.map((scanDir) => ({ scanDir }));+ for (const requestedId of new Set(options.scan)) {+ controller.signal.throwIfAborted();+ const scan = await resolvePublicationScan(requestedId, dependencies);+ if (!selectedScans.some(({ scanId }) => scanId === scan.scanId)) {+ selectedScans.push(scan);+ }+ }+ let scanDir = selectedScans[0]?.scanDir;let publicationRepository =scanDir === undefined ? "scan" : basename(scanDir);if (scanDir === undefined) {@@ -1988,7 +2090,7 @@ export async function main(}).prompt;if (!prompt.isInteractive()) {throw new CodexSecurityError(- "Interactive scan selection requires a terminal. Provide a completed scan directory: codex-security publish scan /path/to/sealed-scan --to linear --linear-team TEAM_ID.",+ `Interactive scan selection requires a terminal. Select a saved scan: codex-security publish scan --scan SCAN_ID --to ${options.to}${options.to === "linear" ? " --linear-team TEAM_ID" : ""}.`,);}const saved = await dependencies.runWorkbench([@@ -2011,7 +2113,7 @@ export async function main(return undefined;}const metadata = await lstat(- resolve(dependencies.currentDirectory(), directory),+ resolveCliPath(currentDirectory, directory),).catch(() => undefined);return metadata?.isDirectory() === true &&!metadata.isSymbolicLink()@@ -2026,6 +2128,10 @@ export async function main(dependencies.environment["NO_COLOR"] === undefined &&dependencies.environment["TERM"] !== "dumb";const repositories = new Map<string, string>();+ const scansById = new Map<+ string,+ { scanId: string; scanDir: string }+ >();const rows = scans.flatMap((scan) => {if (!isJsonObject(scan)) return [];const progress = scan["progress"];@@ -2075,13 +2181,17 @@ export async function main(.replace(/\s+/gu, " ").slice(-6)}`;repositories.set(directory, repository);+ scansById.set(scanId, {+ scanId,+ scanDir: resolveCliPath(currentDirectory, directory),+ });return [{repository,findings,age: publicationScanAge(timestamp, now),scanId: shortScanId,- value: directory,+ value: options.to === "cloud" ? scanId : directory,},];});@@ -2126,15 +2236,118 @@ export async function main(value: row.value,};});- scanDir = await prompt.select(- "Which completed scan would you like to publish?",- choices,- { header },- );+ if (options.to === "cloud") {+ let remaining = choices;+ while (true) {+ controller.signal.throwIfAborted();+ const selected = await prompt.select(+ "Which completed scans would you like to publish?",+ selectedScans.length === 0+ ? remaining+ : [+ {+ label: `Done (${selectedScans.length} selected)`,+ value: "",+ },+ ...remaining,+ ],+ { header },+ controller.signal,+ );+ controller.signal.throwIfAborted();+ if (selected === "") break;+ selectedScans.push(scansById.get(selected)!);+ remaining = remaining.filter(({ value }) => value !== selected);+ }+ scanDir = selectedScans[0]!.scanDir;+ } else {+ scanDir = await prompt.select(+ "Which completed scan would you like to publish?",+ choices,+ { header },+ );+ selectedScans.push({ scanDir });+ }publicationRepository =repositories.get(scanDir) ?? basename(scanDir);}+ if (options.to === "cloud") {+ const seenDirectories = new Set<string>();+ for (let index = 0; index < selectedScans.length; ) {+ const selected = selectedScans[index]!;+ const canonical = await realpath(selected.scanDir).catch(+ () => selected.scanDir,+ );+ const identity =+ process.platform === "win32"+ ? canonical.toLowerCase()+ : canonical;+ if (seenDirectories.has(identity)) {+ selectedScans.splice(index, 1);+ continue;+ }+ seenDirectories.add(identity);+ selected.scanDir = canonical;+ index++;+ }+ scanDir = selectedScans[0]!.scanDir;+ controller.signal.throwIfAborted();+ if (selectedScans.length > 1) {+ cloudBatch = {+ results: [],+ failed: [],+ notAttempted: selectedScans.map(+ ({ scanId, scanDir }) => scanId ?? scanDir,+ ),+ };+ // Keep each scan's provenance and acceptance receipt separate. Never+ // retry a failed POST: a lost response may still have been accepted.+ for (const { scanDir: directory, scanId } of selectedScans) {+ if (controller.signal.aborted) {+ finishCancellation();+ break;+ }+ cloudBatch.notAttempted.shift();+ try {+ const result = await (+ dependencies.publishScanToCloud ?? publishScanToCloud+ )(directory, {+ environment: dependencies.environment,+ dryRun: options.dryRun,+ signal: controller.signal,+ ...(scanId === undefined ? {} : { expectedScanId: scanId }),+ });+ cloudBatch.results.push({ scanDir: directory, ...result });+ } catch (error) {+ const message = safeErrorMessage(error);+ cloudBatch.failed.push({+ scanDir: directory,+ ...(scanId === undefined ? {} : { scanId }),+ error: message,+ });+ if (controller.signal.aborted) throw error;+ exitCode = 2;+ errorOutput.write(+ `codex-security: ${diagnosticValue(safeErrorMessage(scanId ?? directory))}: ${diagnosticValue(message)}\n`,+ );+ }+ }+ return cloudBatch;+ }+ const result = await (+ dependencies.publishScanToCloud ?? publishScanToCloud+ )(resolveCliPath(currentDirectory, scanDir), {+ environment: dependencies.environment,+ dryRun: options.dryRun,+ signal: controller.signal,+ ...(selectedScans[0]?.scanId === undefined+ ? {}+ : { expectedScanId: selectedScans[0].scanId }),+ });+ return { ...result };+ }+const progress = new PublicationProgressPresenter(errorOutput,dependencies,@@ -2150,9 +2363,12 @@ export async function main(let result;try {result = await (dependencies.publishScan ?? publishScan)(- resolve(dependencies.currentDirectory(), scanDir),+ resolveCliPath(currentDirectory, scanDir),{- destination: options.to,+ destination: "linear",+ ...(selectedScans[0]?.scanId === undefined+ ? {}+ : { expectedScanId: selectedScans[0].scanId }),teamId,...(projectId === undefined ? {} : { projectId }),dryRun: options.dryRun,@@ -2195,23 +2411,13 @@ export async function main(}return { ...result };} catch (error) {- const signal = controller.signal.reason;- if (signal === "SIGINT" || signal === "SIGTERM") {- const reason =- signal === "SIGINT"- ? "Publication canceled by Ctrl-C."- : "Publication terminated by SIGTERM.";- const recovery =- error === signal- ? ""- : ` ${diagnosticValue(safeErrorMessage(error))}`;- errorOutput.write(`codex-security: ${reason}${recovery}\n`);- exitCode = signal === "SIGINT" ? 130 : 143;- } else {- errorOutput.write(`codex-security: ${errorMessage(error)}\n`);+ if (!finishCancellation(error)) {+ errorOutput.write(+ `codex-security: ${options.to === "cloud" ? safeErrorMessage(error) : errorMessage(error)}\n`,+ );exitCode = 2;}- return undefined;+ return cloudBatch;} finally {if (observingSignals) {dependencies.removeSignalListener("SIGINT", onInterrupt);@@ -4182,6 +4388,71 @@ async function* workbenchFindings(} while (offset !== undefined);}+async function resolvePublicationScan(+ requestedId: string,+ dependencies: CliDependencies,+): Promise<SavedScan> {+ let scanId = requestedId;+ if (scanId === "latest") {+ const history = await dependencies.runWorkbench([+ "list-scans",+ "--repository",+ resolve(dependencies.currentDirectory()),+ "--status",+ "complete",+ ]);+ const scans = history["scans"];+ const latest = Array.isArray(scans) ? scans[0] : undefined;+ if (+ latest === undefined ||+ !isJsonObject(latest) ||+ typeof latest["scanId"] !== "string"+ ) {+ throw new CodexSecurityError(+ "No completed saved scan was found for this repository.",+ );+ }+ scanId = latest["scanId"];+ }+ const context = await dependencies.runWorkbench([+ "get-scan",+ "--scan-id",+ scanId,+ ]);+ const scan = context["scan"];+ if (+ scan === undefined ||+ !isJsonObject(scan) ||+ typeof scan["scanId"] !== "string"+ ) {+ throw new CodexSecurityError(`Could not read saved scan ${scanId}.`);+ }+ scanId = scan["scanId"];+ const progress = scan["progress"];+ if (+ progress === undefined ||+ !isJsonObject(progress) ||+ progress["status"] !== "complete"+ ) {+ throw new CodexSecurityError(`Scan ${scanId} is not complete.`);+ }+ const storedDirectory = scan["scanDir"];+ const scanDir =+ typeof storedDirectory === "string" && storedDirectory.length > 0+ ? resolveCliPath(dependencies.currentDirectory(), storedDirectory)+ : undefined;+ const metadata =+ scanDir === undefined+ ? undefined+ : await lstat(scanDir).catch(() => undefined);+ if (scanDir === undefined || metadata?.isDirectory() !== true) {+ throw new CodexSecurityError(+ `Artifacts for scan ${scanId} are unavailable. Restore the completed scan artifacts or run a new scan.`,+ );+ }+ return { ...scan, scanId, scanDir };+}+async function selectSavedFindings(identifiers: readonly string[],requestedScanId: string | undefined,diff --git a/sdk/typescript/src/cloud-publish.ts b/sdk/typescript/src/cloud-publish.tsnew file mode 100644index 000000000..8e3e22a88--- /dev/null+++ b/sdk/typescript/src/cloud-publish.ts@@ -0,0 +1,186 @@+import { existsSync } from "node:fs";+import { readFile } from "node:fs/promises";+import { join } from "node:path";+import { z } from "incur";+import { parse as parseToml } from "smol-toml";+import { loadContract } from "./contract.js";+import { AuthenticationRequiredError, CodexSecurityError } from "./errors.js";+import type { Finding } from "./models.js";+import {+ bundledPluginRoot,+ codexSecurityCredentialAllowsAmbientImport,+ codexSecurityCredentialHome,+ codexSecurityHasStoredFileCredentials,+ expandHome,+} from "./runtime.js";++const CLOUD_PUBLISH_URL =+ "https://chatgpt.com/backend-api/aardvark/cli/findings";+const CHATGPT_LOGIN_REQUIRED =+ 'Cloud publication requires ChatGPT credentials stored with cli_auth_credentials_store = "file". Automatic and keyring storage are not read because a stale auth.json may belong to another account. Configure file storage, sign in with ChatGPT again, then retry.';++const credentialsSchema = z.object({+ auth_mode: z.literal("chatgpt").optional(),+ OPENAI_API_KEY: z.null().optional(),+ tokens: z.object({+ access_token: z.string().trim().min(1),+ account_id: z.string().trim().min(1),+ }),+});++const receiptSchema = z.object({+ status: z.literal("accepted"),+ finding_ids: z.array(z.string().min(1)),+ finding_count: z.number().int().positive(),+});++export interface CloudPublicationResult {+ scanId: string;+ findingIds: string[];+ findingCount: number;+ dryRun?: true;+ findings?: Finding[];+}++export async function publishScanToCloud(+ scanDirectory: string,+ dependencies: {+ environment?: NodeJS.ProcessEnv;+ fetch?: (url: string, options: RequestInit) => Promise<Response>;+ signal?: AbortSignal;+ dryRun?: boolean;+ expectedScanId?: string;+ } = {},+): Promise<CloudPublicationResult> {+ const { manifest, findings } = await loadContract(scanDirectory, {+ pluginRoot: await bundledPluginRoot(),+ signal: dependencies.signal,+ expectedScanId: dependencies.expectedScanId,+ });+ if (findings.findings.length === 0) {+ throw new CodexSecurityError(+ "The completed scan has no findings to publish.",+ );+ }+ dependencies.signal?.throwIfAborted();+ if (dependencies.dryRun) {+ return {+ scanId: manifest.scan.id,+ findingIds: [],+ findingCount: findings.findings.length,+ dryRun: true,+ findings: findings.findings,+ };+ }+ const credentials = await readCloudCredentials(+ dependencies.environment ?? process.env,+ );+ const publishUrl =+ dependencies.environment?.["CODEX_SECURITY_CLOUD_PUBLISH_URL"]?.trim() ||+ CLOUD_PUBLISH_URL;+ const timeout = AbortSignal.timeout(30_000);+ const signal = dependencies.signal+ ? AbortSignal.any([dependencies.signal, timeout])+ : timeout;+ let response: Response;+ try {+ response = await (dependencies.fetch ?? globalThis.fetch)(publishUrl, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${credentials.access_token}`,+ "ChatGPT-Account-ID": credentials.account_id,+ "Content-Type": "application/json",+ Accept: "application/json",+ },+ body: JSON.stringify({+ schemaVersion: "1.0",+ scan: manifest.scan,+ findings: findings.findings,+ }),+ redirect: "error",+ signal,+ });+ } catch {+ // A lost response does not establish whether the server accepted the POST.+ throw new CodexSecurityError(+ "Cloud publication was not confirmed. The request was not retried; check whether it was accepted before submitting again.",+ );+ }+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ const detail =+ response.status === 401+ ? "Sign in with ChatGPT again before retrying."+ : response.status === 403+ ? "The signed-in account is not authorized to publish to Cloud."+ : response.status === 404+ ? "Cloud publication is not available for this account or deployment."+ : "The request was not retried.";+ throw new CodexSecurityError(+ `Cloud publication failed (HTTP ${response.status}). ${detail}`,+ );+ }+ const receipt = receiptSchema.safeParse(+ await response.json().catch(() => undefined),+ );+ // Cloud assigns opaque IDs in request order, so they cannot be compared to+ // local finding IDs. The authenticated response must still preserve the+ // submitted count and return one distinct observation for each finding.+ if (+ (response.status !== 200 && response.status !== 201) ||+ !receipt.success ||+ receipt.data.finding_count !== findings.findings.length ||+ receipt.data.finding_ids.length !== findings.findings.length ||+ new Set(receipt.data.finding_ids).size !== receipt.data.finding_ids.length+ ) {+ throw new CodexSecurityError(+ "Cloud publication returned an invalid acceptance receipt. Check whether the request was accepted before submitting again.",+ );+ }+ return {+ scanId: manifest.scan.id,+ findingIds: receipt.data.finding_ids,+ findingCount: receipt.data.finding_count,+ };+}++async function readCloudCredentials(environment: NodeJS.ProcessEnv) {+ let home = expandHome(+ environment["CODEX_HOME"]?.trim() || "~/.codex",+ environment,+ );+ const dedicatedHome = codexSecurityCredentialHome(environment);+ if (existsSync(dedicatedHome)) {+ if (!(await codexSecurityCredentialAllowsAmbientImport(dedicatedHome))) {+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);+ }+ if (await codexSecurityHasStoredFileCredentials(dedicatedHome)) {+ home = dedicatedHome;+ } else if (existsSync(join(dedicatedHome, "config.toml"))) {+ // Do not silently switch accounts when the dedicated login may be in a keyring.+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);+ }+ }+ let credentialStorage: unknown;+ try {+ credentialStorage = parseToml(+ await readFile(join(home, "config.toml"), "utf8"),+ )["cli_auth_credentials_store"];+ } catch {+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);+ }+ // File presence is not proof that it is the active login: automatic or+ // keyring storage can leave an auth.json from a different account.+ if (credentialStorage !== "file") {+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);+ }+ try {+ const credentials = credentialsSchema.safeParse(+ JSON.parse(await readFile(join(home, "auth.json"), "utf8")),+ );+ if (credentials.success) return credentials.data.tokens;+ } catch {+ // Parsing and filesystem diagnostics must not reflect credential contents.+ }+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);+}diff --git a/sdk/typescript/src/contract.ts b/sdk/typescript/src/contract.tsindex 655b2ba64..5db97542d 100644--- a/sdk/typescript/src/contract.ts+++ b/sdk/typescript/src/contract.ts@@ -66,6 +66,7 @@ export interface LoadedContract {type LoadContractOptions = {pluginRoot: string;+ expectedScanId?: string;expectation?: ScanExpectation;workbenchValidated?: boolean;signal?: AbortSignal;@@ -154,6 +155,14 @@ export async function loadContractWithScanDirectory(const manifest = payloads["scan-manifest.json"] as unknown as ScanManifest;const findings = findingsPayload as FindingsDocument;const coverage = payloads["coverage.json"] as unknown as CoverageDocument;+ if (+ options.expectedScanId !== undefined &&+ manifest.scan.id !== options.expectedScanId+ ) {+ throw new ContractValidationError(+ `Scan artifacts do not match selected scan ${options.expectedScanId}.`,+ );+ }if (findings.scanId !== manifest.scan.id ||coverage.scanId !== manifest.scan.iddiff --git a/sdk/typescript/src/publication.ts b/sdk/typescript/src/publication.tsindex 78f758818..4656bfec3 100644--- a/sdk/typescript/src/publication.ts+++ b/sdk/typescript/src/publication.ts@@ -22,6 +22,7 @@ export interface PrepareScanPublicationOptions {teamId: string;projectId?: string;uploadedAt?: string;+ expectedScanId?: string;}export interface PreparedPublicationIssue {@@ -55,6 +56,7 @@ export async function prepareScanPublication(const { contract, scanDirectory: canonicalScanDirectory } =await loadContractWithScanDirectory(scanDirectory, {pluginRoot: await bundledPluginRoot(),+ expectedScanId: options.expectedScanId,});const uploadedAt = options.uploadedAt ?? new Date().toISOString();const scanId = contract.manifest.scan.id;diff --git a/sdk/typescript/src/publish.ts b/sdk/typescript/src/publish.tsindex 93639959b..1ac8a4943 100644--- a/sdk/typescript/src/publish.ts+++ b/sdk/typescript/src/publish.ts@@ -41,6 +41,7 @@ import {} from "./runtime.js";export interface PublishScanOptions {+ expectedScanId?: string;destination: "linear";teamId: string;projectId?: string;diff --git a/sdk/typescript/tests-ts/cli-cloud-publish.test.ts b/sdk/typescript/tests-ts/cli-cloud-publish.test.tsnew file mode 100644index 000000000..fb2620ad4--- /dev/null+++ b/sdk/typescript/tests-ts/cli-cloud-publish.test.ts@@ -0,0 +1,966 @@+import { mkdir, mkdtemp, realpath, rm, symlink } from "node:fs/promises";+import { homedir, tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { afterEach, describe, expect, test } from "bun:test";+import { main } from "../src/cli.js";+import type { JsonObject } from "../src/index.js";+import {+ capture,+ dependencies,+ FakeSignals,+ SYNTHETIC_CREDENTIALS,+} from "./cli-fixtures.js";++const receipt = {+ scanId: "scan-1",+ findingIds: ["finding-1"],+ findingCount: 1,+};++const temporaryDirectories: string[] = [];+afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((path) => rm(path, { recursive: true, force: true })),+ );+});++async function savedScansFixture() {+ const root = await mkdtemp(join(tmpdir(), "cloud-saved-scans-"));+ temporaryDirectories.push(root);+ const scans = await Promise.all(+ [1, 2, 3].map(async (index) => {+ const scanDir = join(root, `scan ${index}`);+ await mkdir(scanDir);+ return {+ scanId: `${String(index).repeat(8)}-1111-4111-8111-111111111111`,+ scanDir,+ targetSummary: `example/repo-${index}`,+ progress: { status: "complete" },+ findingCount: index,+ };+ }),+ );+ const workbenchCalls: string[][] = [];+ const deps = dependencies({+ onWorkbench: (args): JsonObject => {+ workbenchCalls.push([...args]);+ if (args[0] === "list-scans") return { scans };+ expect(args.slice(0, 2)).toEqual(["get-scan", "--scan-id"]);+ const scan = scans.find(({ scanId }) => scanId.startsWith(args[2]!));+ if (!scan) throw new Error("Codex Security scan not found.");+ return { scan };+ },+ });+ return { scans, deps, workbenchCalls };+}++describe("publish scan to Cloud", () => {+ test("resolves IDs, prefixes, and latest before publishing and deduplicates aliases", async () => {+ const { scans, deps, workbenchCalls } = await savedScansFixture();+ const [first, second] = scans;+ const calls: string[] = [];+ deps.publishScanToCloud = async (directory, options) => {+ expect(workbenchCalls).toHaveLength(4);+ const scan = scans[calls.length]!;+ expect(directory).toBe(await realpath(scan.scanDir));+ expect(options?.expectedScanId).toBe(scan.scanId);+ expect(options?.dryRun).toBe(true);+ calls.push(scan.scanId);+ return { ...receipt, scanId: scan.scanId, dryRun: true };+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ "--scan",+ first!.scanId,+ `--scan=${second!.scanId.slice(0, 8)}`,+ "--scan",+ "latest",+ "--to",+ "cloud",+ "--dry-run",+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(workbenchCalls).toContainEqual([+ "list-scans",+ "--repository",+ resolve(deps.currentDirectory()),+ "--status",+ "complete",+ ]);+ expect(calls).toEqual([first!.scanId, second!.scanId]);+ expect(JSON.parse(stdout.text()).results).toHaveLength(2);+ expect(stderr.text()).toBe("");+ });++ test.each(["missing", "incomplete", "unavailable"])(+ "rejects a %s saved scan before uploading any selected scan",+ async (failure) => {+ const { scans, deps } = await savedScansFixture();+ const [first, second] = scans;+ let requestedId = second!.scanId;+ if (failure === "missing") requestedId = "99999999";+ if (failure === "incomplete") second!.progress.status = "running";+ if (failure === "unavailable")+ await rm(second!.scanDir, { recursive: true });+ let uploads = 0;+ deps.publishScanToCloud = async () => {+ uploads++;+ return receipt;+ };+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ "--scan",+ first!.scanId,+ "--scan",+ requestedId,+ "--to",+ "cloud",+ ],+ capture().stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(uploads).toBe(0);+ expect(stderr.text()).toMatch(+ /not found|not complete|artifacts or run a new scan/,+ );+ if (failure !== "missing")+ expect(stderr.text()).toContain(second!.scanId);+ },+ );++ test("rejects mixed ID and directory selectors before reading history", async () => {+ const deps = dependencies({+ onWorkbench: () => {+ throw new Error("unexpected lookup");+ },+ });+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ "--scan",+ "11111111",+ "--scan-dir",+ "external-scan",+ "--to",+ "cloud",+ ],+ capture().stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stderr.text()).toContain("Use --scan or scan directory inputs");+ });++ test("selects several saved scans by ID and stops at Done without selecting the rest", async () => {+ const { scans, deps } = await savedScansFixture();+ const picks = [scans[1]!.scanId, scans[0]!.scanId, ""];+ let selections = 0;+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async (_question, choices, presentation, signal) => {+ expect(signal).toBeInstanceOf(AbortSignal);+ expect(presentation?.header).toContain("SCAN ID");+ expect(choices.some(({ value }) => value === "")).toBe(selections > 0);+ expect(+ choices.some(({ label }) => label.includes(scans[0]!.scanDir)),+ ).toBe(false);+ const pick = picks[selections++]!;+ return choices.find(({ value }) => value === pick)!.value;+ },+ };+ const calls: string[] = [];+ deps.publishScanToCloud = async (_directory, options) => {+ expect(selections).toBe(3);+ calls.push(options!.expectedScanId!);+ return { ...receipt, scanId: options!.expectedScanId! };+ };+ const stdout = capture();+ expect(+ await main(+ ["publish", "scan", "--to", "cloud", "--json"],+ stdout.stream,+ capture().stream,+ deps,+ ),+ ).toBe(0);+ expect(calls).toEqual(picks.slice(0, 2));+ expect(+ JSON.parse(stdout.text()).results.map(+ (result: { scanId: string }) => result.scanId,+ ),+ ).toEqual(calls);+ });++ test("cancels in the picker without uploading already selected scans", async () => {+ const { deps } = await savedScansFixture();+ const signals = new FakeSignals();+ deps.addSignalListener = (signal, listener) =>+ signals.add(signal, listener);+ deps.removeSignalListener = (signal, listener) =>+ signals.remove(signal, listener);+ let selections = 0;+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async (_question, choices, _presentation, signal) => {+ if (selections++ > 0) {+ signals.emit("SIGINT");+ signal!.throwIfAborted();+ }+ return choices[0]!.value;+ },+ };+ let uploads = 0;+ deps.publishScanToCloud = async () => {+ uploads++;+ return receipt;+ };+ expect(+ await main(+ ["publish", "scan", "--to", "cloud"],+ capture().stream,+ capture().stream,+ deps,+ ),+ ).toBe(130);+ expect(uploads).toBe(0);+ expect(+ [...signals.listeners.values()].every(+ (listeners) => listeners.size === 0,+ ),+ ).toBe(true);+ });++ test("identifies failed and unattempted saved scans by ID on cancellation", async () => {+ const { scans, deps } = await savedScansFixture();+ const signals = new FakeSignals();+ deps.addSignalListener = (signal, listener) =>+ signals.add(signal, listener);+ deps.removeSignalListener = (signal, listener) =>+ signals.remove(signal, listener);+ deps.publishScanToCloud = async (_directory, options) => {+ if (options!.expectedScanId === scans[1]!.scanId) {+ signals.emit("SIGTERM");+ throw new Error("Publication was not confirmed.");+ }+ return { ...receipt, scanId: options!.expectedScanId! };+ };+ const stdout = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ ...scans.flatMap(({ scanId }) => ["--scan", scanId]),+ "--to",+ "cloud",+ "--json",+ ],+ stdout.stream,+ capture().stream,+ deps,+ ),+ ).toBe(143);+ expect(JSON.parse(stdout.text())).toMatchObject({+ results: [{ scanId: scans[0]!.scanId }],+ failed: [+ { scanId: scans[1]!.scanId, error: "Publication was not confirmed." },+ ],+ notAttempted: [scans[2]!.scanId],+ });+ });++ test("preserves a fully confirmed batch when cancellation follows the final response", async () => {+ const { scans, deps } = await savedScansFixture();+ const signals = new FakeSignals();+ deps.addSignalListener = (signal, listener) =>+ signals.add(signal, listener);+ deps.removeSignalListener = (signal, listener) =>+ signals.remove(signal, listener);+ let uploads = 0;+ deps.publishScanToCloud = async (_directory, options) => {+ uploads++;+ if (uploads === scans.length) signals.emit("SIGINT");+ return { ...receipt, scanId: options!.expectedScanId! };+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ ...scans.flatMap(({ scanId }) => ["--scan", scanId]),+ "--to",+ "cloud",+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(uploads).toBe(scans.length);+ expect(JSON.parse(stdout.text())).toMatchObject({+ results: scans.map(({ scanId }) => ({ scanId })),+ failed: [],+ notAttempted: [],+ });+ expect(stderr.text()).toBe("");+ expect(+ [...signals.listeners.values()].every(+ (listeners) => listeners.size === 0,+ ),+ ).toBe(true);+ });++ test("publishes multiple explicit scans in order and deduplicates resolved paths", async () => {+ for (const dryRun of [false, true]) {+ const deps = dependencies({+ onWorkbench: () => {+ throw new Error("must not inspect scan history");+ },+ });+ deps.createSecurity = () => {+ throw new Error("must not initialize Codex");+ };+ deps.publishScan = async () => {+ throw new Error("must not publish to Linear");+ };+ const directories = ["scan one", "scan-two"].map((path) =>+ resolve(deps.currentDirectory(), path),+ );+ const calls: string[] = [];+ let publishing = false;+ const results = directories.map((scanDir, index) => ({+ scanDir,+ scanId: `scan-${index + 1}`,+ findingIds: dryRun ? [] : [`finding-${index + 1}`],+ findingCount: 1,+ ...(dryRun ? { dryRun: true as const, findings: [] } : {}),+ }));+ deps.publishScanToCloud = async (directory, options) => {+ expect(publishing).toBe(false);+ publishing = true;+ expect(directory).toBe(directories[calls.length]!);+ expect(options).toEqual({+ environment: deps.environment,+ dryRun,+ signal: expect.any(AbortSignal),+ });+ const { scanDir: _, ...result } = results[calls.length]!;+ calls.push(directory);+ await Promise.resolve();+ publishing = false;+ return result;+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ "--scan-dir",+ "scan one",+ "--to=cloud",+ "--scan-dir=scan-two",+ "--scan-dir",+ "./scan one",+ "--json",+ ...(dryRun ? ["--dry-run"] : []),+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(calls).toEqual(directories);+ expect(JSON.parse(stdout.text())).toEqual({+ results,+ failed: [],+ notAttempted: [],+ });+ expect(stderr.text()).toBe("");+ }+ });++ test("keeps receipts and continues after a failed scan without retrying", async () => {+ const deps = dependencies();+ const directories = ["scan-one", "scan-two", "scan-three"].map((path) =>+ resolve(deps.currentDirectory(), path),+ );+ const calls: string[] = [];+ deps.publishScanToCloud = async (directory) => {+ calls.push(directory);+ if (directory === directories[1]) {+ throw new Error(`Cloud failed: ${SYNTHETIC_CREDENTIALS}`);+ }+ return {+ ...receipt,+ scanId: directory === directories[0] ? "scan-1" : "scan-3",+ };+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ ...directories.flatMap((directory) => ["--scan-dir", directory]),+ "--to",+ "cloud",+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(calls).toEqual(directories);+ expect(JSON.parse(stdout.text())).toEqual({+ results: [+ { scanDir: directories[0], ...receipt },+ { scanDir: directories[2], ...receipt, scanId: "scan-3" },+ ],+ failed: [{ scanDir: directories[1], error: "[redacted]" }],+ notAttempted: [],+ });+ expect(stderr.text()).toContain("[redacted]");+ expect(stderr.text()).not.toContain(SYNTHETIC_CREDENTIALS);+ });++ test.each([false, true])(+ "preserves batch receipts on cancellation with a confirmed response: %s",+ async (confirmed) => {+ for (const [signal, code] of [+ ["SIGINT", 130],+ ["SIGTERM", 143],+ ] as const) {+ const signals = new FakeSignals();+ const deps = dependencies({ signals });+ const directories = ["scan-one", "scan-two", "scan-three"].map((path) =>+ resolve(deps.currentDirectory(), path),+ );+ const calls: string[] = [];+ deps.publishScanToCloud = async (directory, options) => {+ calls.push(directory);+ if (directory === directories[1]) {+ signals.emit(signal);+ expect(options?.signal?.aborted).toBe(true);+ if (confirmed) return { ...receipt, scanId: "scan-2" };+ throw new Error(+ "Cloud publication was not confirmed. Check acceptance before resubmitting.",+ );+ }+ return receipt;+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ ...directories.flatMap((directory) => ["--scan-dir", directory]),+ "--to",+ "cloud",+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(code);+ expect(calls).toEqual(directories.slice(0, 2));+ expect(JSON.parse(stdout.text())).toEqual({+ results: [+ { scanDir: directories[0], ...receipt },+ ...(confirmed+ ? [{ scanDir: directories[1], ...receipt, scanId: "scan-2" }]+ : []),+ ],+ failed: confirmed+ ? []+ : [+ {+ scanDir: directories[1],+ error:+ "Cloud publication was not confirmed. Check acceptance before resubmitting.",+ },+ ],+ notAttempted: [directories[2]],+ });+ expect(stderr.text()).toContain(+ signal === "SIGINT" ? "canceled" : "terminated",+ );+ expect(+ [...signals.listeners.values()].every(+ (listeners) => listeners.size === 0,+ ),+ ).toBe(true);+ }+ },+ );++ test("rejects multiple scans for Linear before publishing any findings", async () => {+ const deps = dependencies();+ let calls = 0;+ deps.publishScan = async () => {+ calls++;+ throw new Error("unexpected publication");+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ "scan-one",+ "--scan-dir",+ "scan-two",+ "--to",+ "linear",+ "--linear-team",+ "synthetic-team",+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(calls).toBe(0);+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toContain("Multiple scan directories");+ });++ test.each(["positional", "flag"])(+ "routes an explicit %s scan to Cloud without initializing Codex or Linear",+ async (syntax) => {+ for (const destination of [["--to=cloud"], ["--to", "cloud"]]) {+ for (const dryRun of [false, true]) {+ const currentDirectory = join(tmpdir(), "cloud-publish-current");+ const deps = dependencies({+ currentDirectory,+ environment: { CODEX_SECURITY_LINEAR_API_KEY: " " },+ onWorkbench: () => {+ throw new Error("must not inspect scan history");+ },+ });+ deps.createSecurity = () => {+ throw new Error("must not initialize Codex");+ };+ deps.publishScan = async () => {+ throw new Error("must not publish to Linear");+ };+ let calls = 0;+ const result = dryRun+ ? {+ ...receipt,+ findingIds: [],+ dryRun: true as const,+ findings: [],+ }+ : receipt;+ deps.publishScanToCloud = async (directory, options) => {+ calls++;+ expect(directory).toBe(join(currentDirectory, "completed-scan"));+ expect(options).toEqual({+ environment: deps.environment,+ dryRun,+ signal: expect.any(AbortSignal),+ });+ return result;+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ ...(syntax === "flag"+ ? ["--scan-dir", "completed-scan"]+ : ["completed-scan"]),+ ...destination,+ "--json",+ ...(dryRun ? ["--dry-run"] : []),+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(calls).toBe(1);+ expect(JSON.parse(stdout.text())).toEqual(result);+ expect(stderr.text()).toBe("");+ }+ }+ },+ );++ test("expands home-relative scan inputs and deduplicates mixed positional and flag paths", async () => {+ const first = join(homedir(), "scan-one");+ const second = join(homedir(), "scan-two");+ for (const { inputs, expected } of [+ { inputs: ["~/scan-one"], expected: [first] },+ {+ inputs: ["--scan-dir", "~/scan-one", "--scan-dir", first],+ expected: [first],+ },+ {+ inputs: ["~/scan-one", "--scan-dir", first, "--scan-dir", "~/scan-two"],+ expected: [first, second],+ },+ ]) {+ const deps = dependencies({+ onWorkbench: () => {+ throw new Error("must not inspect scan history");+ },+ });+ const calls: string[] = [];+ deps.publishScanToCloud = async (directory) => {+ calls.push(directory);+ return receipt;+ };+ const stdout = capture();+ expect(+ await main(+ ["publish", "scan", ...inputs, "--to", "cloud", "--json"],+ stdout.stream,+ capture().stream,+ deps,+ ),+ ).toBe(0);+ expect(calls).toEqual(expected);+ expect(JSON.parse(stdout.text())).toEqual(+ expected.length === 1+ ? receipt+ : {+ results: expected.map((scanDir) => ({ scanDir, ...receipt })),+ failed: [],+ notAttempted: [],+ },+ );+ }+ });++ test("publishes a scan once through canonical and directory-linked paths", async () => {+ const root = await mkdtemp(join(tmpdir(), "cloud-publish-links-"));+ temporaryDirectories.push(root);+ const scans = join(root, "scans");+ const scanDir = join(scans, "completed-scan");+ const linkedScans = join(root, "linked-scans");+ await mkdir(scanDir, { recursive: true });+ await symlink(+ scans,+ linkedScans,+ process.platform === "win32" ? "junction" : "dir",+ );+ const canonicalScan = await realpath(scanDir);+ const calls: string[] = [];+ const deps = dependencies({+ onWorkbench: () => {+ throw new Error("must not inspect scan history");+ },+ });+ deps.publishScanToCloud = async (directory) => {+ calls.push(directory);+ return receipt;+ };+ const stdout = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ "--scan-dir",+ scanDir,+ "--scan-dir",+ join(linkedScans, "completed-scan"),+ "--to",+ "cloud",+ "--json",+ ],+ stdout.stream,+ capture().stream,+ deps,+ ),+ ).toBe(0);+ expect(calls).toEqual([canonicalScan]);+ expect(JSON.parse(stdout.text())).toEqual(receipt);+ });++ test("rejects missing or empty scan flags and extra positionals before publishing", async () => {+ for (const inputs of [+ ["--scan"],+ ["--scan="],+ ["--scan", "--json"],+ ["--scan-dir"],+ ["--scan-dir="],+ ["--scan-dir", "--json"],+ ["scan-one", "scan-two"],+ ]) {+ const deps = dependencies();+ let calls = 0;+ deps.publishScanToCloud = async () => {+ calls++;+ return receipt;+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ ["publish", "scan", ...inputs, "--to", "cloud"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(calls).toBe(0);+ expect(stdout.text()).toBe("");+ expect(stderr.text()).not.toBe("");+ }+ });++ test("reuses the completed-scan picker when no directory is supplied", async () => {+ const root = await mkdtemp(join(tmpdir(), "cloud-publish-picker-"));+ const scanDir = join(root, "completed-scan");+ try {+ await mkdir(scanDir);+ const deps = dependencies({+ onWorkbench: (args) => {+ expect(args).toEqual(["list-scans", "--status", "complete"]);+ return {+ scans: [+ {+ scanId: "scan-1",+ scanDir,+ progress: { status: "complete" },+ findingCount: 1,+ },+ ],+ };+ },+ });+ let selections = 0;+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async (_question, choices) => {+ selections++;+ const directories: string[] = choices.map(({ value }) => value);+ if (selections === 1) {+ expect(directories).toEqual(["scan-1"]);+ return choices[0]!.value;+ }+ expect(directories).toEqual([""]);+ expect(choices[0]!.label).toBe("Done (1 selected)");+ return choices[0]!.value;+ },+ };+ deps.publishScanToCloud = async (directory, options) => {+ expect(directory).toBe(await realpath(scanDir));+ expect(options?.expectedScanId).toBe("scan-1");+ return receipt;+ };+ const stdout = capture();+ expect(+ await main(+ ["publish", "scan", "--to", "cloud", "--json"],+ stdout.stream,+ capture().stream,+ deps,+ ),+ ).toBe(0);+ expect(selections).toBe(2);+ expect(JSON.parse(stdout.text())).toEqual(receipt);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ test("requests an explicit scan outside a terminal without suggesting Linear options", async () => {+ const deps = dependencies();+ deps.publishPrompt = {+ isInteractive: () => false,+ select: async () => {+ throw new Error("unexpected picker");+ },+ };+ deps.publishScanToCloud = async () => {+ throw new Error("unexpected publication");+ };+ const stderr = capture();+ expect(+ await main(+ ["publish", "scan", "--to", "cloud"],+ capture().stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stderr.text()).toContain("--scan SCAN_ID --to cloud");+ expect(stderr.text()).not.toContain("--linear-team");+ });++ test("rejects Linear-specific options before uploading to Cloud", async () => {+ for (const flag of [+ "--linear-team",+ "--linear-project",+ "--project",+ "--linear-assignee",+ "--linear-api-key",+ ]) {+ const deps = dependencies();+ let calls = 0;+ deps.publishScanToCloud = async () => {+ calls++;+ return receipt;+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ "--to",+ "cloud",+ flag,+ "synthetic-value",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(calls).toBe(0);+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toContain("cannot be combined with Linear options");+ }+ });++ test("keeps the internal Cloud destination out of help and discovery", async () => {+ for (const flag of ["--help", "--schema", "--llms", "--llms-full"]) {+ const stdout = capture();+ const deps = dependencies();+ deps.publishScanToCloud = async () => {+ throw new Error("unexpected publication");+ };+ expect(+ await main(+ ["publish", "scan", flag],+ stdout.stream,+ capture().stream,+ deps,+ ),+ ).toBe(0);+ expect(stdout.text().toLowerCase()).not.toContain("cloud");+ }+ });++ test("reports publication failures without leaking credentials or claiming success", async () => {+ const deps = dependencies();+ deps.publishScanToCloud = async () => {+ throw new Error(`Cloud failed: ${SYNTHETIC_CREDENTIALS}`);+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ ["publish", "scan", "completed-scan", "--to", "cloud"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toBe("codex-security: [redacted]\n");+ });++ test("preserves a confirmed single-scan receipt when cancellation follows the response", async () => {+ const signals = new FakeSignals();+ const deps = dependencies({ signals });+ deps.publishScanToCloud = async () => {+ signals.emit("SIGINT");+ return receipt;+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ ["publish", "scan", "completed-scan", "--to", "cloud", "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(JSON.parse(stdout.text())).toEqual(receipt);+ expect(stderr.text()).toBe("");+ expect(+ [...signals.listeners.values()].every(+ (listeners) => listeners.size === 0,+ ),+ ).toBe(true);+ });++ test("aborts Cloud publication and removes signal listeners", async () => {+ for (const [signal, code] of [+ ["SIGINT", 130],+ ["SIGTERM", 143],+ ] as const) {+ const signals = new FakeSignals();+ const deps = dependencies({ signals });+ deps.publishScanToCloud = async (_directory, options) => {+ signals.emit(signal);+ expect(options?.signal?.aborted).toBe(true);+ options?.signal?.throwIfAborted();+ return receipt;+ };+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ ["publish", "scan", "completed-scan", "--to", "cloud"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(code);+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toContain(+ signal === "SIGINT" ? "canceled" : "terminated",+ );+ expect(+ [...signals.listeners.values()].every(+ (listeners) => listeners.size === 0,+ ),+ ).toBe(true);+ }+ });+});diff --git a/sdk/typescript/tests-ts/cli-publish.test.ts b/sdk/typescript/tests-ts/cli-publish.test.tsindex 8d5ec5134..d7cbe2383 100644--- a/sdk/typescript/tests-ts/cli-publish.test.ts+++ b/sdk/typescript/tests-ts/cli-publish.test.ts@@ -74,6 +74,45 @@ function publicationResult(}describe("publish scan", () => {+ test("resolves a saved scan ID for Linear publication", async () => {+ const scanDir = await publicationDirectory();+ const deps = dependencies({+ onWorkbench: (args) => {+ expect(args).toEqual(["get-scan", "--scan-id", "scan-123"]);+ return {+ scan: {+ scanId: "scan-123",+ scanDir,+ progress: { status: "complete" },+ },+ };+ },+ });+ let calls = 0;+ deps.publishScan = async (directory, options) => {+ calls++;+ expect(directory).toBe(scanDir);+ expect(options.expectedScanId).toBe("scan-123");+ return publicationResult();+ };+ expect(+ await main(+ [+ "publish",+ "scan",+ "--scan",+ "scan-123",+ ...DESTINATION_OPTIONS,+ "--json",+ ],+ capture().stream,+ capture().stream,+ deps,+ ),+ ).toBe(0);+ expect(calls).toBe(1);+ });+test("accepts the Linear project flag and its published alias", async () => {for (const flag of ["--linear-project", "--project"]) {let projectId: string | undefined;@@ -125,49 +164,60 @@ describe("publish scan", () => {);});- test("publishes an explicit scan directory without inspecting scan history", async () => {- const currentDirectory = join(tmpdir(), "codex-security-publish-current");- const stdout = capture();- const stderr = capture();- let invocation:- | { scanDirectory: string; options: Record<string, unknown> }- | undefined;- const deps = dependencies({- currentDirectory,- onWorkbench: () => {- throw new Error("scan history must not be inspected");- },- });- deps.createSecurity = () => {- throw new Error("a new security scan must not be started");- };- deps.publishScan = async (scanDirectory, options) => {- invocation = { scanDirectory, options: { ...options } };- return publicationResult();- };+ test.each(["positional", "flag"])(+ "publishes an explicit %s scan directory without inspecting scan history",+ async (syntax) => {+ const currentDirectory = join(tmpdir(), "codex-security-publish-current");+ const stdout = capture();+ const stderr = capture();+ let invocation:+ | { scanDirectory: string; options: Record<string, unknown> }+ | undefined;+ const deps = dependencies({+ currentDirectory,+ onWorkbench: () => {+ throw new Error("scan history must not be inspected");+ },+ });+ deps.createSecurity = () => {+ throw new Error("a new security scan must not be started");+ };+ deps.publishScan = async (scanDirectory, options) => {+ invocation = { scanDirectory, options: { ...options } };+ return publicationResult();+ };- expect(- await main(- ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],- stdout.stream,- stderr.stream,- deps,- ),- ).toBe(0);- expect(invocation).toEqual({- scanDirectory: resolve(currentDirectory, "completed-scan"),- options: {- destination: "linear",- teamId: "team-from-flags",- projectId: "project-from-flags",- dryRun: false,- signal: expect.any(AbortSignal),- onProgress: expect.any(Function),- },- });- expect(JSON.parse(stdout.text())).toEqual(publicationResult());- expect(stderr.text()).toBe("");- });+ expect(+ await main(+ [+ "publish",+ "scan",+ ...(syntax === "flag"+ ? ["--scan-dir", "completed-scan"]+ : ["completed-scan"]),+ ...DESTINATION_OPTIONS,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(invocation).toEqual({+ scanDirectory: resolve(currentDirectory, "completed-scan"),+ options: {+ destination: "linear",+ teamId: "team-from-flags",+ projectId: "project-from-flags",+ dryRun: false,+ signal: expect.any(AbortSignal),+ onProgress: expect.any(Function),+ },+ });+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());+ expect(stderr.text()).toBe("");+ },+ );test("selects direct Linear publication and forwards the requested assignee", async () => {for (const scenario of [diff --git a/sdk/typescript/tests-ts/cloud-publish.test.ts b/sdk/typescript/tests-ts/cloud-publish.test.tsnew file mode 100644index 000000000..e81bfb6f4--- /dev/null+++ b/sdk/typescript/tests-ts/cloud-publish.test.ts@@ -0,0 +1,511 @@+import { createHash } from "node:crypto";+import {+ chmod,+ cp,+ mkdir,+ mkdtemp,+ readFile,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, test } from "bun:test";+import { publishScanToCloud } from "../src/cloud-publish.js";+import {+ codexSecurityCredentialHome,+ setCodexSecurityCredentialLogout,+} from "../src/runtime.js";+import { PLUGIN_ROOT } from "./plugin-root.js";++const directories: string[] = [];+const login = {+ auth_mode: "chatgpt",+ tokens: {+ access_token: "synthetic-access-token",+ account_id: "synthetic-account",+ refresh_token: "synthetic-refresh-token",+ id_token: "synthetic-id-token",+ },+};+const receipt = {+ status: "accepted",+ finding_ids: ["finding-1"],+ finding_count: 1,+};++afterEach(async () => {+ await Promise.all(+ directories+ .splice(0)+ .map((path) => rm(path, { recursive: true, force: true })),+ );+});++async function fixture() {+ const root = await mkdtemp(join(tmpdir(), "codex-security-cloud-"));+ directories.push(root);+ const scan = join(root, "scan");+ const home = join(root, "home");+ await cp(join(PLUGIN_ROOT, "examples", "completed-scan"), scan, {+ recursive: true,+ });+ if (process.platform !== "win32") await chmod(scan, 0o700);+ await mkdir(home, { mode: 0o700 });+ await writeFile(join(home, "auth.json"), JSON.stringify(login), {+ mode: 0o600,+ });+ await writeFile(+ join(home, "config.toml"),+ 'cli_auth_credentials_store = "file"\n',+ );+ return {+ scan,+ home,+ environment: {+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ },+ };+}++async function addSecondFinding(scan: string): Promise<void> {+ const findingsPath = join(scan, "findings.json");+ const manifestPath = join(scan, "scan-manifest.json");+ const findings = JSON.parse(await readFile(findingsPath, "utf8")) as {+ findings: Array<{+ findingId: string;+ occurrenceId: string;+ ruleId: string;+ identity: { anchor: string; instance?: string };+ fingerprints: { primary: string };+ title: string;+ }>;+ };+ const manifest = JSON.parse(await readFile(manifestPath, "utf8")) as {+ scan: {+ id: string;+ target: { targetId: string };+ artifacts: Array<{ path: string; sha256: string }>;+ };+ };+ const second = structuredClone(findings.findings[0]!);+ second.identity.instance = "second-instance";+ second.title = "A second synthetic finding";+ const sha256 = (value: string): string =>+ createHash("sha256").update(value).digest("hex");+ const fingerprint = `codex-security/v1:sha256:${sha256(+ [+ "codex-security/v1",+ manifest.scan.target.targetId,+ second.ruleId,+ second.identity.anchor,+ second.identity.instance,+ ].join("\0"),+ )}`;+ second.findingId = `csf_${sha256(fingerprint).slice(0, 24)}`;+ second.occurrenceId = `occ_${sha256(+ [manifest.scan.id, fingerprint].join("\0"),+ ).slice(0, 24)}`;+ second.fingerprints.primary = fingerprint;+ findings.findings.push(second);+ await writeFile(findingsPath, `${JSON.stringify(findings, null, 2)}\n`);+ const artifact = manifest.scan.artifacts.find(+ ({ path }) => path === "findings.json",+ )!;+ artifact.sha256 = createHash("sha256")+ .update(await readFile(findingsPath))+ .digest("hex");+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);+}++describe("Cloud publication", () => {+ test.each([false, true])(+ "rejects artifacts from another scan before upload or preview (dryRun=%s)",+ async (dryRun) => {+ const { scan, environment } = await fixture();+ let requests = 0;+ await expect(+ publishScanToCloud(scan, {+ environment,+ dryRun,+ expectedScanId: "another-scan",+ fetch: async () => {+ requests++;+ throw new Error("unexpected request");+ },+ }),+ ).rejects.toThrow(+ "Scan artifacts do not match selected scan another-scan.",+ );+ expect(requests).toBe(0);+ },+ );++ test("previews validated findings without credentials or network access", async () => {+ const { scan, home, environment } = await fixture();+ await rm(join(home, "auth.json"));+ const manifest = JSON.parse(+ await readFile(join(scan, "scan-manifest.json"), "utf8"),+ );+ const findings = JSON.parse(+ await readFile(join(scan, "findings.json"), "utf8"),+ );+ let requests = 0;+ expect(+ await publishScanToCloud(scan, {+ environment,+ dryRun: true,+ expectedScanId: manifest.scan.id,+ fetch: async () => {+ requests++;+ throw new Error("unexpected request");+ },+ }),+ ).toEqual({+ scanId: manifest.scan.id,+ findingIds: [],+ findingCount: findings.findings.length,+ dryRun: true,+ findings: findings.findings,+ });+ expect(requests).toBe(0);+ await writeFile(join(scan, "findings.json"), "{}");+ await expect(+ publishScanToCloud(scan, { environment, dryRun: true }),+ ).rejects.toThrow();+ });++ test("posts validated findings and scan provenance with only ChatGPT access credentials", async () => {+ const { scan, environment } = await fixture();+ const manifest = JSON.parse(+ await readFile(join(scan, "scan-manifest.json"), "utf8"),+ );+ const findings = JSON.parse(+ await readFile(join(scan, "findings.json"), "utf8"),+ );+ let requests = 0;+ const result = await publishScanToCloud(scan, {+ environment: { ...environment, OPENAI_API_KEY: "synthetic-api-key" },+ fetch: async (url, options) => {+ requests++;+ expect(new URL(String(url)).origin).toBe("https://chatgpt.com");+ expect(options).toMatchObject({+ method: "POST",+ redirect: "error",+ headers: {+ Authorization: "Bearer synthetic-access-token",+ "ChatGPT-Account-ID": "synthetic-account",+ "Content-Type": "application/json",+ Accept: "application/json",+ },+ });+ expect(JSON.parse(String(options!.body))).toEqual({+ schemaVersion: "1.0",+ scan: manifest.scan,+ findings: findings.findings,+ });+ expect(JSON.stringify(options)).not.toContain(+ "synthetic-refresh-token",+ );+ expect(JSON.stringify(options)).not.toContain("synthetic-id-token");+ expect(options!.signal).toBeInstanceOf(AbortSignal);+ return Response.json(receipt, { status: 201 });+ },+ });+ expect(result).toEqual({+ scanId: manifest.scan.id,+ findingIds: ["finding-1"],+ findingCount: 1,+ });+ expect(requests).toBe(1);+ });++ test("accepts opaque Cloud finding IDs that differ from local finding IDs", async () => {+ const { scan, environment } = await fixture();+ const localFindings = JSON.parse(+ await readFile(join(scan, "findings.json"), "utf8"),+ ) as { findings: Array<{ findingId: string }> };+ const opaqueId = "cloud-observation-synthetic";+ expect(+ localFindings.findings.map(({ findingId }) => findingId),+ ).not.toContain(opaqueId);+ expect(+ await publishScanToCloud(scan, {+ environment,+ fetch: async () =>+ Response.json({+ status: "accepted",+ finding_ids: [opaqueId],+ finding_count: 1,+ }),+ }),+ ).toEqual({+ scanId: "scan_example_001",+ findingIds: [opaqueId],+ findingCount: 1,+ });+ });++ test("honors a Cloud publication URL override", async () => {+ const { scan, environment } = await fixture();+ const publishUrl =+ "https://chatgpt-staging.com/backend-api/aardvark/cli/findings";+ let requestedUrl: string | undefined;+ await publishScanToCloud(scan, {+ environment: {+ ...environment,+ CODEX_SECURITY_CLOUD_PUBLISH_URL: publishUrl,+ },+ fetch: async (url) => {+ requestedUrl = String(url);+ return Response.json(receipt);+ },+ });+ expect(requestedUrl).toBe(publishUrl);+ });++ test("prefers the dedicated file login and honors an explicit logout", async () => {+ const { scan, environment } = await fixture();+ const home = codexSecurityCredentialHome(environment);+ await mkdir(home, { recursive: true, mode: 0o700 });+ await writeFile(+ join(home, "auth.json"),+ JSON.stringify({+ ...login,+ tokens: { ...login.tokens, account_id: "dedicated-account" },+ }),+ { mode: 0o600 },+ );+ let requests = 0;+ const send = async (_url: string, options: RequestInit) => {+ requests++;+ expect(new Headers(options!.headers).get("ChatGPT-Account-ID")).toBe(+ "dedicated-account",+ );+ return Response.json(receipt);+ };+ await expect(+ publishScanToCloud(scan, { environment, fetch: send }),+ ).rejects.toThrow('cli_auth_credentials_store = "file"');+ expect(requests).toBe(0);+ await writeFile(+ join(home, "config.toml"),+ 'cli_auth_credentials_store = "file"\n',+ );+ await publishScanToCloud(scan, { environment, fetch: send });+ await setCodexSecurityCredentialLogout(home, true);+ await expect(+ publishScanToCloud(scan, { environment, fetch: send }),+ ).rejects.toThrow('cli_auth_credentials_store = "file"');+ expect(requests).toBe(1);+ });++ test("resolves missing or empty CODEX_HOME through the existing user-home helper", async () => {+ const { scan, home, environment } = await fixture();+ await mkdir(join(home, ".codex"), { mode: 0o700 });+ await writeFile(join(home, ".codex", "auth.json"), JSON.stringify(login), {+ mode: 0o600,+ });+ await writeFile(+ join(home, ".codex", "config.toml"),+ 'cli_auth_credentials_store = "file"\n',+ );+ for (const codexHome of [undefined, "", " "]) {+ const result = await publishScanToCloud(scan, {+ environment: {+ ...environment,+ CODEX_HOME: codexHome,+ HOME: home,+ USERPROFILE: home,+ },+ fetch: async () => Response.json(receipt),+ });+ expect(result.findingIds).toEqual(["finding-1"]);+ }+ });++ test("requires an explicit file credential setting before reading auth.json", async () => {+ const { scan, home, environment } = await fixture();+ let requests = 0;+ const send = async () => {+ requests++;+ return Response.json(receipt);+ };+ for (const config of [undefined, "[features]\nplugins = true\n"]) {+ if (config === undefined) {+ await rm(join(home, "config.toml"));+ } else {+ await writeFile(join(home, "config.toml"), config);+ }+ await expect(+ publishScanToCloud(scan, { environment, fetch: send }),+ ).rejects.toThrow('cli_auth_credentials_store = "file"');+ }+ expect(requests).toBe(0);+ });++ test("rejects unsupported, missing, or malformed credentials without leaking their contents", async () => {+ const { scan, home, environment } = await fixture();+ let requests = 0;+ const send = async () => {+ requests++;+ return Response.json(receipt);+ };+ for (const credentials of [+ { auth_mode: "apikey", OPENAI_API_KEY: "synthetic-api-secret" },+ { ...login, auth_mode: "personal_access_token" },+ { ...login, tokens: { access_token: "synthetic-access-token" } },+ {},+ ]) {+ await writeFile(join(home, "auth.json"), JSON.stringify(credentials), {+ mode: 0o600,+ });+ await expect(+ publishScanToCloud(scan, { environment, fetch: send }),+ ).rejects.toThrow('cli_auth_credentials_store = "file"');+ }+ await writeFile(join(home, "auth.json"), "malformed-synthetic-secret");+ await expect(+ publishScanToCloud(scan, { environment, fetch: send }),+ ).rejects.toThrow('cli_auth_credentials_store = "file"');+ await rm(join(home, "auth.json"));+ await expect(+ publishScanToCloud(scan, { environment, fetch: send }),+ ).rejects.toThrow('cli_auth_credentials_store = "file"');+ expect(requests).toBe(0);+ });++ test("does not use a stale file when keyring or automatic credential storage is selected", async () => {+ const { scan, home, environment } = await fixture();+ let requests = 0;+ for (const mode of ["keyring", "auto"]) {+ await writeFile(+ join(home, "config.toml"),+ `cli_auth_credentials_store = "${mode}"\n`,+ );+ const error = await publishScanToCloud(scan, {+ environment,+ fetch: async () => {+ requests++;+ return Response.json(receipt);+ },+ }).then(+ () => undefined,+ (failure: unknown) => failure,+ );+ expect(String(error)).toContain('cli_auth_credentials_store = "file"');+ expect(String(error)).toContain(+ "a stale auth.json may belong to another account",+ );+ }+ expect(requests).toBe(0);++ await writeFile(+ join(home, "config.toml"),+ 'cli_auth_credentials_store = "file"\n',+ );+ await publishScanToCloud(scan, {+ environment,+ fetch: async () => {+ requests++;+ return Response.json(receipt);+ },+ });+ expect(requests).toBe(1);+ });++ test("rejects tampered scan artifacts before reading credentials or uploading", async () => {+ const { scan, environment } = await fixture();+ await writeFile(join(scan, "findings.json"), "{}");+ let requests = 0;+ await expect(+ publishScanToCloud(scan, {+ environment,+ fetch: async () => {+ requests++;+ return Response.json(receipt);+ },+ }),+ ).rejects.toThrow();+ expect(requests).toBe(0);+ });++ test("does not retry HTTP errors or expose server response bodies", async () => {+ const { scan, environment } = await fixture();+ for (const status of [401, 403, 404, 413, 422, 429, 503]) {+ let requests = 0;+ try {+ await publishScanToCloud(scan, {+ environment,+ fetch: async () => {+ requests++;+ return new Response("synthetic-access-token", { status });+ },+ });+ throw new Error("expected publication to fail");+ } catch (error) {+ expect(String(error)).toContain(`HTTP ${status}`);+ expect(String(error)).not.toContain("synthetic-access-token");+ }+ expect(requests).toBe(1);+ }+ });++ test("does not retry an ambiguous transport failure", async () => {+ const { scan, environment } = await fixture();+ let requests = 0;+ await expect(+ publishScanToCloud(scan, {+ environment,+ fetch: async () => {+ requests++;+ throw new Error("synthetic-access-token");+ },+ }),+ ).rejects.toThrow("Cloud publication was not confirmed");+ expect(requests).toBe(1);+ });++ test("requires a complete acceptance receipt instead of treating any 2xx as success", async () => {+ const { scan, environment } = await fixture();+ for (const body of [+ {},+ { ...receipt, status: "queued" },+ { ...receipt, finding_count: 2 },+ { ...receipt, finding_ids: [] },+ ]) {+ await expect(+ publishScanToCloud(scan, {+ environment,+ fetch: async () => Response.json(body),+ }),+ ).rejects.toThrow("invalid acceptance receipt");+ }+ await expect(+ publishScanToCloud(scan, {+ environment,+ fetch: async () => Response.json(receipt, { status: 202 }),+ }),+ ).rejects.toThrow("invalid acceptance receipt");+ });++ test("rejects duplicate opaque IDs in an otherwise complete receipt", async () => {+ const { scan, environment } = await fixture();+ await addSecondFinding(scan);+ await expect(+ publishScanToCloud(scan, {+ environment,+ fetch: async () =>+ Response.json({+ status: "accepted",+ finding_ids: [+ "cloud-observation-duplicate",+ "cloud-observation-duplicate",+ ],+ finding_count: 2,+ }),+ }),+ ).rejects.toThrow("invalid acceptance receipt");+ });+});diff --git a/sdk/typescript/tests-ts/publication.test.ts b/sdk/typescript/tests-ts/publication.test.tsindex c676dff35..d09c4599d 100644--- a/sdk/typescript/tests-ts/publication.test.ts+++ b/sdk/typescript/tests-ts/publication.test.ts@@ -68,6 +68,26 @@ async function reseal(scanDirectory: string): Promise<void> {}describe("scan publication preparation", () => {+ test("requires artifacts to match the selected saved scan", async () => {+ const scanDirectory = await copyExample();+ await expect(+ prepareScanPublication(scanDirectory, {+ ...DESTINATION,+ expectedScanId: "another-scan",+ }),+ ).rejects.toThrow(+ "Scan artifacts do not match selected scan another-scan.",+ );+ expect(+ (+ await prepareScanPublication(scanDirectory, {+ ...DESTINATION,+ expectedScanId: "scan_example_001",+ })+ ).scanId,+ ).toBe("scan_example_001");+ });+test("prepares sealed findings with scan-based upload IDs and full traceability", async () => {const scanDirectory = await copyExample();const publication = await prepareScanPublication(