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(publish): add direct Linear API publication and assignees (#470)
Kyle Browna4076de51983
diff --git a/README.md b/README.mdindex 4089fb3cd..cc7a02b9b 100644--- a/README.md+++ b/README.md@@ -96,11 +96,30 @@ the optional `CODEX_SECURITY_LINEAR_PROJECT` instead of passing the destinationflags. Add `--dry-run` to preview the issues or `--json` to returnmachine-readable results.-Publishing uses your existing Codex sign-in and connected Linear app; no-separate Linear token is required. Every finding creates a new issue containing-the scan ID, affected code locations, source snippets, and remediation guidance.-Choose a destination authorized to receive the repository's source code and-vulnerability details.+By default, publishing uses your existing Codex sign-in and connected Linear+app without a separate Linear token. To publish directly through the Linear API+instead, set `CODEX_SECURITY_LINEAR_API_KEY` to a Linear personal API key.+Direct publication leaves issues unassigned by default; pass+`--linear-assignee EMAIL_OR_USER_ID` to select a Linear user:++```bash+export CODEX_SECURITY_LINEAR_API_KEY=YOUR_LINEAR_PERSONAL_API_KEY+npx @openai/codex-security publish scan /path/to/scan \+ --to linear \+ --linear-team TEAM_ID \+ --project PROJECT_ID \+ --linear-assignee [email protected]+```++Use `--linear-assignee USER_ID` to select a Linear user ID instead of an email+address, or omit the flag to leave the issues unassigned.++`--linear-api-key KEY` also selects direct publication and takes precedence+over the environment variable. Prefer the environment variable to keep API keys+out of shell history and process listings. Every finding creates a new issue+containing the scan ID, affected code locations, source snippets, and+remediation guidance. Choose a destination authorized to receive the+repository's source code and vulnerability details.## Verbose diagnosticsdiff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 27044f633..1c6b4bf66 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -434,6 +434,8 @@ The CLI and SDK recognize the following user-configurable environment:| Variable | Effect || --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- || `OPENAI_API_KEY`, `CODEX_API_KEY` | Scan authentication; `OPENAI_API_KEY` wins when both are present. |+| `CODEX_SECURITY_LINEAR_TEAM`, `CODEX_SECURITY_LINEAR_PROJECT` | Default Linear team and project for completed-scan publication. |+| `CODEX_SECURITY_LINEAR_API_KEY` | Publish directly to Linear with a personal API key; safer than a command-line key. || `CODEX_SECURITY_LOG_LEVEL` | CLI-only; set to `debug` for verbose diagnostics. || `LOG_LEVEL` | CLI-only fallback when `CODEX_SECURITY_LOG_LEVEL` is unset. || `CODEX_SECURITY_STATE_DIR` | Override the private scan-history, workbench, and default artifact directory. |@@ -578,10 +580,32 @@ Interactive publication shows a full-screen activity view with live Codexoutput and issue-creation progress. Other terminals receive plain progress onstderr, so `--json` output remains machine-readable.-Publishing starts Codex with your existing Codex configuration and connected-Linear app. Sign in to Codex and connect Linear before publishing. The command-does not require a Linear API token and does not use the isolated Codex home-created for security scans.+By default, publishing starts Codex with your existing Codex configuration and+connected Linear app. Sign in to Codex and connect Linear before publishing in+this mode. No separate Linear API token is required, and publication does not+use the isolated Codex home created for security scans.++To publish directly through the Linear API without starting Codex, configure a+Linear personal API key:++```bash+export CODEX_SECURITY_LINEAR_API_KEY=YOUR_LINEAR_PERSONAL_API_KEY+npx @openai/codex-security publish scan /path/to/completed-scan \+ --to linear \+ --linear-team TEAM_ID+```++Direct API publication leaves issues unassigned by default. Pass+`--linear-assignee [email protected]` or `--linear-assignee USER_ID` to+assign the issues to a Linear user by email address or user ID.+`--linear-assignee` requires direct API publication.++You can also pass `--linear-api-key KEY`, which takes precedence over+`CODEX_SECURITY_LINEAR_API_KEY`. Prefer the environment variable to avoid+exposing your API key in shell history and process listings. API keys are not+added to successful publication results, scan history, or sealed scan artifacts.+Error messages are preserved as returned. `--dry-run` never contacts Linear in+either mode.Each finding creates a separate new issue titled`[Codex Security][HIGH] Finding title`. The issue includes the scan ID,@@ -623,6 +647,19 @@ console.log(publication.created.length);Add `projectId: "PROJECT_ID"` to the options to publish into a specific Linearproject instead of directly to the team.+Pass `linearApiKey` to publish directly through the Linear API. Omit+`assigneeId` to leave issues unassigned, or supply a Linear user ID or email+address to select an assignee:++```ts+const directPublication = await publishScan("/path/to/completed-scan", {+ destination: "linear",+ teamId: "TEAM_ID",+ linearApiKey: process.env["CODEX_SECURITY_LINEAR_API_KEY"],+ assigneeId: "[email protected]",+});+```+### Scan history and reruns`scans` or `scans list` lists scans for the current repository. Pass a repositorydiff --git a/sdk/typescript/package.json b/sdk/typescript/package.jsonindex 93420a6fd..741426bf3 100644--- a/sdk/typescript/package.json+++ b/sdk/typescript/package.json@@ -54,6 +54,7 @@},"dependencies": {"@inquirer/prompts": "8.3.0",+ "@linear/sdk": "89.0.0","@octokit/core": "7.0.6","@openai/codex": "0.148.0-alpha.8","@openai/codex-sdk": "0.148.0-alpha.8",diff --git a/sdk/typescript/pnpm-lock.yaml b/sdk/typescript/pnpm-lock.yamlindex 178ce1350..eca8be0e5 100644--- a/sdk/typescript/pnpm-lock.yaml+++ b/sdk/typescript/pnpm-lock.yaml@@ -11,6 +11,9 @@ importers:'@inquirer/prompts':specifier: 8.3.0version: 8.3.0(@types/[email protected])+ '@linear/sdk':+ specifier: 89.0.0+ version: 89.0.0([email protected])'@octokit/core':specifier: 7.0.6version: 7.0.6@@ -73,6 +76,11 @@ packages:'@cfworker/[email protected]':resolution: {integrity: sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==}+ '@graphql-typed-document-node/[email protected]':+ resolution: {integrity: sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==}+ peerDependencies:+ graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0+'@inquirer/[email protected]':resolution: {integrity: sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q==}engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}@@ -210,6 +218,10 @@ packages:'@jsdevtools/[email protected]':resolution: {integrity: sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==}+ '@linear/[email protected]':+ resolution: {integrity: sha512-LiV2wsIg1Wym4GgaAUMrALo953WEgIAAceyK8qL91q75Ws8+lqwAkPW252MHtwktZCR7exMBd5wCAdct3yLU7w==}+ engines: {node: '>=18.x'}+'@modelcontextprotocol/[email protected]':resolution: {integrity: sha512-nsMXd4wQBKzmph6r+WOhum+mXjDYljTAqwY/XUg3hLtvNOQ8+JVqBSJOVCMJvx9lXhTpTOPrGZ3BuNiaNPjSvg==}engines: {node: '>=20'}@@ -470,6 +482,10 @@ packages:resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==}engines: {node: '>=8'}+ resolution: {integrity: sha512-FRWbddMxfkjiB7z+aQDWIR+E34xo9I8c9mtK2RPv8PmMzKRvrdsreHL/Ui/TmwHJfhHChEtsFPyMHKI+xuarQQ==}+ engines: {node: ^22.0.0 || ^24.0.0 || ^25.0.0 || >=26.0.0}+resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}engines: {node: '>=0.10.0'}@@ -597,6 +613,10 @@ snapshots:'@cfworker/[email protected]': {}+ '@graphql-typed-document-node/[email protected]([email protected])':+ dependencies:+ graphql: 17.0.2+'@inquirer/[email protected]': {}'@inquirer/[email protected](@types/[email protected])':@@ -718,6 +738,12 @@ snapshots:'@jsdevtools/[email protected]': {}+ '@linear/[email protected]([email protected])':+ dependencies:+ '@graphql-typed-document-node/core': 3.2.0([email protected])+ transitivePeerDependencies:+ - graphql+'@modelcontextprotocol/[email protected]':dependencies:zod: 4.4.3@@ -942,6 +968,8 @@ snapshots:dependencies:pump: 3.0.4+ [email protected]: {}+dependencies:safer-buffer: 2.1.2diff --git a/sdk/typescript/scripts/smoke-package.mjs b/sdk/typescript/scripts/smoke-package.mjsindex b2c811d2d..9c7307b6b 100644--- a/sdk/typescript/scripts/smoke-package.mjs+++ b/sdk/typescript/scripts/smoke-package.mjs@@ -446,6 +446,53 @@ try {assert.equal(publication.counts.created, 0);assert.match(publication.issues[0].title, /^\[Codex Security\]\[HIGH\] /u);+ const networkGuard = join(consumer, "reject-publication-network.cjs");+ await writeFile(+ networkGuard,+ 'globalThis.fetch = async () => { throw new Error("Publication dry runs must not make network requests."); };\n',+ );+ const directPublicationText = run(+ process.execPath,+ [+ "--require",+ networkGuard,+ launcher,+ "publish",+ "scan",+ publicationScan,+ "--to",+ "linear",+ "--linear-team",+ "team-example",+ "--project",+ "project-example",+ "--linear-api-key",+ "lin_api_SYNTHETIC_INSTALLED_OVERRIDE",+ "--linear-assignee",+ "[email protected]",+ "--dry-run",+ "--json",+ ],+ {+ cwd: consumer,+ capture: true,+ env: {+ ...process.env,+ CODEX_SECURITY_STATE_DIR: join(consumer, "publication-state"),+ CODEX_SECURITY_LINEAR_API_KEY: "lin_api_SYNTHETIC_INSTALLED_ENV",+ },+ },+ );+ const directPublication = JSON.parse(directPublicationText);+ assert.equal(directPublication.scanId, publication.scanId);+ assert.equal(directPublication.dryRun, true);+ assert.equal(directPublication.counts.findings, 1);+ assert.equal(directPublication.counts.created, 0);+ assert.doesNotMatch(+ directPublicationText,+ /lin_api_|security@example\.test/u,+ );+await smokeNestedDeepScanWorker(installedRoot, consumer);console.log(diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 5c3f774ce..57e06a7ec 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -223,7 +223,9 @@ const VALUE_OPTIONS = new Set(["--reason","--to","--linear-team",+ "--linear-api-key","--project",+ "--linear-assignee",]);const PROVIDER_OPTION = z.enum(["openai", "openrouter", "fireworks", "amazon-bedrock"])@@ -1538,11 +1540,21 @@ export async function main(linearTeam: optionValue("--linear-team").optional().describe("Linear team ID; defaults to CODEX_SECURITY_LINEAR_TEAM."),+ linearApiKey: optionValue("--linear-api-key")+ .optional()+ .describe(+ "Linear personal API key; defaults to CODEX_SECURITY_LINEAR_API_KEY.",+ ),project: optionValue("--project").optional().describe("Optional Linear project ID; defaults to CODEX_SECURITY_LINEAR_PROJECT.",),+ linearAssignee: optionValue("--linear-assignee")+ .optional()+ .describe(+ "Linear assignee email or user ID; omit to leave issues unassigned.",+ ),dryRun: z.boolean().default(false)@@ -1560,6 +1572,22 @@ export async function main(const onTerminate = (): void => cancel("SIGTERM");let observingSignals = false;try {+ const selectedApiKey =+ options.linearApiKey ??+ dependencies.environment["CODEX_SECURITY_LINEAR_API_KEY"];+ const linearApiKey = selectedApiKey?.trim() || undefined;+ if (options.linearApiKey !== undefined && linearApiKey === undefined) {+ throw new CodexSecurityError("--linear-api-key must not be empty.");+ }+ const assigneeId = options.linearAssignee?.trim();+ if (options.linearAssignee !== undefined && !assigneeId) {+ throw new CodexSecurityError("--linear-assignee must not be empty.");+ }+ if (assigneeId !== undefined && linearApiKey === undefined) {+ throw new CodexSecurityError(+ "--linear-assignee requires --linear-api-key or CODEX_SECURITY_LINEAR_API_KEY.",+ );+ }const teamId =options.linearTeam?.trim() ||dependencies.environment["CODEX_SECURITY_LINEAR_TEAM"]?.trim();@@ -1758,6 +1786,8 @@ export async function main(teamId,...(projectId === undefined ? {} : { projectId }),dryRun: options.dryRun,+ ...(linearApiKey === undefined ? {} : { linearApiKey }),+ ...(assigneeId === undefined ? {} : { assigneeId }),...(options.dryRun? {}: {diff --git a/sdk/typescript/src/publish.ts b/sdk/typescript/src/publish.tsindex 46c7feb6e..266de10f1 100644--- a/sdk/typescript/src/publish.ts+++ b/sdk/typescript/src/publish.ts@@ -9,6 +9,7 @@ import {writeFile,} from "node:fs/promises";import { join } from "node:path";+import { LinearClient } from "@linear/sdk";import {CodexSecurityError,ConfigurationError,@@ -38,6 +39,8 @@ export interface PublishScanOptions {destination: "linear";teamId: string;projectId?: string;+ linearApiKey?: string;+ assigneeId?: string;dryRun?: boolean;signal?: AbortSignal;onProgress?: (event: PublishScanProgress) => void;@@ -92,6 +95,9 @@ export interface PublicationCodexResult {export interface PublishScanDependencies {environment?: NodeJS.ProcessEnv;+ linearClient?: (+ options: ConstructorParameters<typeof LinearClient>[0],+ ) => Pick<LinearClient, "users" | "createIssue">;prepare?: typeof prepareScanPublication;resolveCodex?: (environment: NodeJS.ProcessEnv) => CodexCommand;runCodex?: (@@ -135,6 +141,17 @@ export async function publishScanInternal();}+ const environment = dependencies.environment ?? process.env;+ const linearApiKey =+ options.linearApiKey?.trim() ||+ environment["CODEX_SECURITY_LINEAR_API_KEY"]?.trim() ||+ undefined;+ if (options.assigneeId !== undefined && linearApiKey === undefined) {+ throw new ConfigurationError(+ "A Linear API key is required to select a publication assignee.",+ );+ }+const prepared = await (dependencies.prepare ?? prepareScanPublication)(scanDirectory,options,@@ -157,15 +174,39 @@ export async function publishScanInternal(}if (prepared.issues.length === 0) return result;- const environment = dependencies.environment ?? process.env;await (dependencies.preparePublicationStore ?? preparePublicationStore)(prepared,environment,);options.signal?.throwIfAborted();- const command = (dependencies.resolveCodex ?? resolveCodexCommand)(- environment,- );+ const linearClient =+ linearApiKey === undefined+ ? undefined+ : (+ dependencies.linearClient ??+ ((configuration) => new LinearClient(configuration))+ )({+ apiKey: linearApiKey,+ redirect: "error",+ ...(options.signal === undefined ? {} : { signal: options.signal }),+ });+ let assigneeId = options.assigneeId;+ if (linearClient !== undefined && assigneeId?.includes("@")) {+ const users = await linearClient.users({+ filter: { email: { eqIgnoreCase: assigneeId } },+ first: 2,+ });+ if (users.nodes.length !== 1) {+ throw new ConfigurationError(+ "Linear could not resolve exactly one matching issue assignee.",+ );+ }+ assigneeId = users.nodes[0]!.id;+ }+ const command =+ linearClient === undefined+ ? (dependencies.resolveCodex ?? resolveCodexCommand)(environment)+ : undefined;options.signal?.throwIfAborted();const handoff = await createPublicationHandoff(prepared, environment);const progressObserver = options.onProgress;@@ -175,62 +216,80 @@ export async function publishScanInternal(total: prepared.issues.length,});const completedFindings = new Set<string>();- const invocation = await (dependencies.runCodex ?? runPublicationCodex)(- command,- [- "exec",- "--model",- "gpt-5.6-luna",- "-c",- 'model_reasoning_effort="low"',- "--ephemeral",- "--json",- "--sandbox",- "workspace-write",- "--skip-git-repo-check",- "--cd",- handoff.directory,- "-",- ],- publicationPrompt(prepared, handoff.file, handoff.publicationFile),- environment,- progressObserver === undefined- ? undefined- : (event) => {- reportPublicationProgress(progressObserver, {- type: "codex_event",- event,- });- reportCompletedIssue(- event,- prepared,- completedFindings,- progressObserver,- );- },- options.signal,- ).catch(async (error: unknown) => {- const cause = error instanceof CodexSecurityError ? error.cause : undefined;- if (- dependencies.runCodex === undefined &&- error instanceof CodexSecurityError &&- error.message === "Could not start Codex for Linear publication." &&- isRecord(cause) &&- typeof cause["syscall"] === "string" &&- cause["syscall"].startsWith("spawn ")- ) {- await rm(handoff.directory, { recursive: true, force: true }).catch(- () => undefined,- );- }- throw error;- });+ let invocation: PublicationCodexResult | undefined;+ if (linearClient !== undefined) {+ await publishLinearApiIssues(+ prepared,+ handoff.file,+ linearClient,+ assigneeId,+ completedFindings,+ progressObserver,+ options.signal,+ );+ } else {+ invocation = await (dependencies.runCodex ?? runPublicationCodex)(+ command!,+ [+ "exec",+ "--model",+ "gpt-5.6-luna",+ "-c",+ 'model_reasoning_effort="low"',+ "--ephemeral",+ "--json",+ "--sandbox",+ "workspace-write",+ "--skip-git-repo-check",+ "--cd",+ handoff.directory,+ "-",+ ],+ publicationPrompt(prepared, handoff.file, handoff.publicationFile),+ environment,+ progressObserver === undefined+ ? undefined+ : (event) => {+ reportPublicationProgress(progressObserver, {+ type: "codex_event",+ event,+ });+ reportCompletedIssue(+ event,+ prepared,+ completedFindings,+ progressObserver,+ );+ },+ options.signal,+ ).catch(async (error: unknown) => {+ const cause =+ error instanceof CodexSecurityError ? error.cause : undefined;+ if (+ dependencies.runCodex === undefined &&+ error instanceof CodexSecurityError &&+ error.message === "Could not start Codex for Linear publication." &&+ isRecord(cause) &&+ typeof cause["syscall"] === "string" &&+ cause["syscall"].startsWith("spawn ")+ ) {+ await rm(handoff.directory, { recursive: true, force: true }).catch(+ () => undefined,+ );+ }+ throw error;+ });+ }const failureMessage =- invocation.exitCode === 0- ? "Codex did not create a Linear issue for this finding."- : codexFailureMessage(invocation.stderr, invocation.exitCode);+ linearClient !== undefined+ ? options.signal?.aborted+ ? "Linear API publication was interrupted before this finding could be created."+ : "The Linear API did not create an issue for this finding."+ : invocation!.exitCode === 0+ ? "Codex did not create a Linear issue for this finding."+ : codexFailureMessage(invocation!.stderr, invocation!.exitCode);const events = collectPublicationEvents(- invocation.stdout,+ invocation?.stdout ?? "",prepared,failureMessage,);@@ -319,6 +378,97 @@ export async function publishScanInternal(return result;}+async function publishLinearApiIssues(+ publication: PreparedScanPublication,+ handoffFile: string,+ client: Pick<LinearClient, "createIssue">,+ assigneeId: string | undefined,+ completed: Set<string>,+ observer: PublishScanOptions["onProgress"],+ signal?: AbortSignal,+): Promise<void> {+ let handoffWrites = Promise.resolve();+ const appendHandoff = async (+ record: Record<string, unknown>,+ ): Promise<void> => {+ const pending = handoffWrites.then(async () => {+ await appendFile(handoffFile, `${JSON.stringify(record)}\n`, "utf8");+ });+ handoffWrites = pending.catch(() => undefined);+ await pending;+ };++ for (let index = 0; index < publication.issues.length; index += 20) {+ if (signal?.aborted) break;+ const batch = publication.issues.slice(index, index + 20);+ const settled = await Promise.allSettled(+ batch.map(async (issue) => {+ const content = {+ title: issue.title,+ description: issue.description,+ ...(issue.priority === undefined ? {} : { priority: issue.priority }),+ };+ const arguments_ = {+ team: publication.destination.teamId,+ ...(publication.destination.projectId === undefined+ ? {}+ : { project: publication.destination.projectId }),+ ...content,+ };+ let outcome:+ | { issueIdentifier: string; url: string }+ | { error: string };+ try {+ const response = await client.createIssue({+ teamId: publication.destination.teamId,+ ...(publication.destination.projectId === undefined+ ? {}+ : { projectId: publication.destination.projectId }),+ ...content,+ ...(assigneeId === undefined ? {} : { assigneeId }),+ });+ const result = await response.issue;+ if (!response.success || result === undefined) {+ throw new CodexSecurityError("Linear did not create an issue.");+ }+ outcome = { issueIdentifier: result.identifier, url: result.url };+ } catch (error) {+ if (signal?.aborted) return;+ outcome = { error: safeErrorMessage(error) };+ }++ await appendHandoff({+ scanId: publication.scanId,+ findingId: issue.findingId,+ occurrenceId: issue.occurrenceId,+ ...outcome,+ arguments: arguments_,+ });+ completed.add(issue.findingId);+ reportPublicationProgress(observer, {+ type: "issue_completed",+ findingId: issue.findingId,+ ...("error" in outcome+ ? { error: outcome.error }+ : { issueIdentifier: outcome.issueIdentifier }),+ completed: completed.size,+ total: publication.issues.length,+ });+ }),+ );+ const rejected = settled.find(+ (outcome): outcome is PromiseRejectedResult =>+ outcome.status === "rejected",+ );+ 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.`,+ { cause: rejected.reason },+ );+ }+ }+}+function reportPublicationProgress(observer: PublishScanOptions["onProgress"],event: PublishScanProgress,diff --git a/sdk/typescript/tests-ts/cli-publish.test.ts b/sdk/typescript/tests-ts/cli-publish.test.tsindex 42c5a5888..743daf6fd 100644--- a/sdk/typescript/tests-ts/cli-publish.test.ts+++ b/sdk/typescript/tests-ts/cli-publish.test.ts@@ -118,6 +118,109 @@ describe("publish scan", () => {expect(stderr.text()).toBe("");});+ test("selects direct Linear publication and forwards the requested assignee", async () => {+ for (const scenario of [+ { flags: [], key: "environment-key", assignee: undefined },+ {+ flags: [+ "--linear-api-key",+ "explicit-key",+ "--linear-assignee",+ "[email protected]",+ ],+ key: "explicit-key",+ assignee: "[email protected]",+ },+ {+ flags: ["--linear-assignee", "user-123"],+ key: "environment-key",+ assignee: "user-123",+ },+ ]) {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies({+ environment: { CODEX_SECURITY_LINEAR_API_KEY: "environment-key" },+ });+ let options: Record<string, unknown> | undefined;+ deps.publishScan = async (_directory, selected) => {+ options = { ...selected };+ return publicationResult();+ };++ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ ...DESTINATION_OPTIONS,+ ...scenario.flags,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(options).toMatchObject({+ linearApiKey: scenario.key,+ ...(scenario.assignee === undefined+ ? {}+ : { assigneeId: scenario.assignee }),+ });+ if (scenario.assignee === undefined) {+ expect(options).not.toHaveProperty("assigneeId");+ }+ expect(stdout.text()).not.toContain(scenario.key);+ }+ });++ test("rejects a Linear assignee without direct API authentication", async () => {+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ ...DESTINATION_OPTIONS,+ "--linear-assignee",+ "[email protected]",+ ],+ stdout.stream,+ stderr.stream,+ dependencies(),+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(+ "--linear-assignee requires --linear-api-key or CODEX_SECURITY_LINEAR_API_KEY.",+ );+ });++ test("preserves Linear API error details", async () => {+ const key = "lin_api_SYNTHETIC_ERROR_DETAILS";+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies({+ environment: { CODEX_SECURITY_LINEAR_API_KEY: key },+ });+ deps.publishScan = async () => {+ throw new Error(`Linear rejected ${key}.`);+ };++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(key);+ });+test("publishes directly to a Linear team when no project is selected", async () => {const stdout = capture();const stderr = capture();diff --git a/sdk/typescript/tests-ts/publication-integration.test.ts b/sdk/typescript/tests-ts/publication-integration.test.tsindex 816dc69ba..b3f959a70 100644--- a/sdk/typescript/tests-ts/publication-integration.test.ts+++ b/sdk/typescript/tests-ts/publication-integration.test.ts@@ -24,6 +24,7 @@ import type {} from "../src/models.js";import {publishScanInternal,+ type PublishScanDependencies,type PublishScanProgress,type PublishScanResult,} from "../src/publish.js";@@ -279,6 +280,105 @@ function receiptPath(fixture: PublicationFixture): string {}describe("database-backed Linear publication integration", () => {+ test("persists unassigned direct team-only publication", async () => {+ const completed = await fixture(23);+ const sealed = await artifactDigests(completed.scanDirectory);+ const key = "lin_api_SYNTHETIC_INTEGRATION_KEY";+ const environment = {+ ...completed.environment,+ CODEX_SECURITY_LINEAR_API_KEY: key,+ };+ const stdout = capture();+ const stderr = capture();+ const created: string[] = [];+ const cli = dependencies({ environment });+ type LinearClient = ReturnType<+ NonNullable<PublishScanDependencies["linearClient"]>+ >;+ type IssueInput = Parameters<LinearClient["createIssue"]>[0];++ cli.publishScan = async (directory, options) =>+ publishScanInternal(directory, options, {+ environment,+ resolveCodex: () => {+ throw new Error("Direct publication must not start Codex.");+ },+ linearClient: ({ apiKey }) => {+ expect(apiKey).toBe(key);+ return {+ users: async () => {+ throw new Error("Unassigned publication must not look up users.");+ },+ createIssue: async (input: IssueInput) => {+ const index = completed.findings.findIndex(({ findingId }) =>+ input.description?.includes(findingId),+ );+ expect(index).toBeGreaterThanOrEqual(0);+ expect(input).toMatchObject({+ teamId: OPTIONS.teamId,+ priority: 2,+ });+ expect(input).not.toHaveProperty("assigneeId");+ expect(input).not.toHaveProperty("projectId");+ if (index >= 20)+ expect(created.length).toBeGreaterThanOrEqual(20);+ const identifier = `SEC-${index + 1}`;+ created.push(identifier);+ return {+ success: true,+ issue: Promise.resolve({+ identifier,+ url: `https://linear.app/example/issue/${identifier}`,+ }),+ };+ },+ } as unknown as LinearClient;+ },+ });++ expect(+ await main(+ [+ "publish",+ "scan",+ completed.scanDirectory,+ "--to",+ "linear",+ "--linear-team",+ OPTIONS.teamId,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ cli,+ ),+ ).toBe(0);++ const result = JSON.parse(stdout.text()) as PublishScanResult;+ expect(result.destination).toEqual({+ type: "linear",+ teamId: OPTIONS.teamId,+ });+ expect(result.counts).toEqual({ findings: 23, created: 23, failed: 0 });+ expect(storedPublications(completed)).toEqual(+ completed.findings.map((finding, index) => ({+ scan_id: SCAN_ID,+ finding_id: finding.findingId,+ occurrence_id: finding.occurrenceId,+ destination_type: "linear",+ team_id: OPTIONS.teamId,+ project_id: null,+ external_id: `SEC-${index + 1}`,+ external_url: `https://linear.app/example/issue/SEC-${index + 1}`,+ })),+ );+ expect(JSON.parse(await readFile(receiptPath(completed), "utf8"))).toEqual(+ result,+ );+ expect(await artifactDigests(completed.scanDirectory)).toEqual(sealed);+ expect(stdout.text()).not.toContain(key);+ });+test("publishes 23 sealed findings through a durable handoff without Codex JSON", async () => {const completed = await fixture(23);const sealed = await artifactDigests(completed.scanDirectory);diff --git a/sdk/typescript/tests-ts/publish.test.ts b/sdk/typescript/tests-ts/publish.test.tsindex e3c3d5a40..197f6c0b8 100644--- a/sdk/typescript/tests-ts/publish.test.ts+++ b/sdk/typescript/tests-ts/publish.test.ts@@ -142,6 +142,43 @@ function dependencies(};}+type LinearClient = ReturnType<+ NonNullable<PublishScanDependencies["linearClient"]>+>;+type LinearIssueInput = Parameters<LinearClient["createIssue"]>[0];++function linearApiClient(+ publication: PreparedScanPublication,+ options: {+ configured?: (apiKey: string) => void;+ create?: (+ input: LinearIssueInput,+ signal: AbortSignal | null | undefined,+ ) => Promise<void> | void;+ } = {},+): NonNullable<PublishScanDependencies["linearClient"]> {+ return ({ apiKey, signal }) => {+ options.configured?.(apiKey ?? "");+ return {+ users: async () => ({ nodes: [{ id: "assignee-from-email" }] }),+ createIssue: async (input: LinearIssueInput) => {+ await options.create?.(input, signal);+ const index = publication.issues.findIndex(+ ({ title }) => title === input.title,+ );+ const identifier = `SEC-${index + 1}`;+ return {+ success: true,+ issue: Promise.resolve({+ identifier,+ url: `https://linear.app/example/issue/${identifier}`,+ }),+ };+ },+ } as unknown as LinearClient;+ };+}+interface PublicationPromptData {scanId: string;handoffFile: string;@@ -230,6 +267,178 @@ async function processHasExited(pid: number): Promise<boolean> {return false;}+describe("direct Linear API publication", () => {+ test("leaves issues unassigned unless an email or user ID is selected", async () => {+ for (const scenario of [+ { requested: undefined, assigned: undefined, teamOnly: false },+ {+ requested: "[email protected]",+ assigned: "assignee-from-email",+ teamOnly: true,+ },+ { requested: "user-123", assigned: "user-123", teamOnly: false },+ ]) {+ const publication = preparedPublication();+ if (scenario.teamOnly) delete publication.destination.projectId;+ const inputs: LinearIssueInput[] = [];+ let configuredKey = "";+ const injected = dependencies(+ publication,+ {},+ {+ linearClient: linearApiClient(publication, {+ configured: (key) => {+ configuredKey = key;+ },+ create: (input) => {+ inputs.push(input);+ },+ }),+ resolveCodex: () => {+ throw new Error("Direct publication must not start Codex.");+ },+ },+ );+ injected.environment!["CODEX_SECURITY_LINEAR_API_KEY"] =+ "environment-key";+ const result = await publishScanInternal(+ publication.scanDirectory,+ {+ destination: "linear",+ teamId: OPTIONS.teamId,+ ...(scenario.teamOnly ? {} : { projectId: OPTIONS.projectId }),+ ...(scenario.requested === undefined+ ? {}+ : { linearApiKey: "explicit-key", assigneeId: scenario.requested }),+ },+ injected,+ );++ expect(configuredKey).toBe(+ scenario.requested === undefined ? "environment-key" : "explicit-key",+ );+ expect(inputs).toEqual([+ {+ teamId: OPTIONS.teamId,+ ...(scenario.teamOnly ? {} : { projectId: OPTIONS.projectId }),+ title: publication.issues[0]!.title,+ description: publication.issues[0]!.description,+ priority: 2,+ ...(scenario.assigned === undefined+ ? {}+ : { assigneeId: scenario.assigned }),+ },+ ]);+ if (scenario.assigned === undefined) {+ expect(inputs[0]).not.toHaveProperty("assigneeId");+ }+ expect(result.counts).toEqual({ findings: 1, created: 1, failed: 0 });+ }+ });++ test("completes direct batches before continuing and preserves individual failures", async () => {+ const publication = preparedPublication(23);+ let started = 0;+ let completed = 0;+ let releaseFirstBatch: (() => void) | undefined;+ const firstBatchStarted = new Promise<void>((resolve) => {+ releaseFirstBatch = resolve;+ });+ const result = await publishScanInternal(+ publication.scanDirectory,+ { ...OPTIONS, linearApiKey: "synthetic-key" },+ dependencies(+ publication,+ {},+ {+ linearClient: linearApiClient(publication, {+ create: async (input) => {+ const index = publication.issues.findIndex(+ ({ title }) => title === input.title,+ );+ started += 1;+ if (started === 20) releaseFirstBatch?.();+ if (index < 20) await firstBatchStarted;+ else expect(completed).toBeGreaterThanOrEqual(20);+ completed += 1;+ if (index === 21)+ throw new Error("Linear rejected this finding.");+ },+ }),+ },+ ),+ );++ expect(started).toBe(23);+ expect(result.counts).toEqual({ findings: 23, created: 22, failed: 1 });+ expect(result.failed).toEqual([+ { findingId: "finding-22", error: "Linear rejected this finding." },+ ]);+ });++ test("recovers completed direct issues before honoring cancellation", async () => {+ const publication = preparedPublication(23);+ const controller = new AbortController();+ let started = 0;+ let stopped = 0;+ let persisted: string[] = [];+ let receipt: unknown;+ const injected = dependencies(+ publication,+ {},+ {+ linearClient: linearApiClient(publication, {+ create: async (input, signal) => {+ started += 1;+ if (input.title === publication.issues[0]!.title) return;+ await new Promise<void>((_resolve, reject) => {+ signal?.addEventListener(+ "abort",+ () => {+ stopped += 1;+ reject(new Error("Publication canceled."));+ },+ { once: true },+ );+ });+ },+ }),+ recordPublishedIssues: async (_prepared, issues) => {+ persisted = issues.map(({ issueIdentifier }) => issueIdentifier);+ return [...issues];+ },+ writeReceipt: async (result) => {+ receipt = result;+ },+ },+ );++ await expect(+ publishScanInternal(+ publication.scanDirectory,+ {+ ...OPTIONS,+ linearApiKey: "synthetic-key",+ signal: controller.signal,+ onProgress: ({ type }) => {+ if (type === "issue_completed") controller.abort("SIGINT");+ },+ },+ injected,+ ),+ ).rejects.toThrow(/publication handoff remains at/u);++ expect({ started, stopped, persisted }).toEqual({+ started: 20,+ stopped: 19,+ persisted: ["SEC-1"],+ });+ expect(receipt).toMatchObject({+ counts: { findings: 23, created: 1, failed: 22 },+ });+ });+});+describe("connected Linear publication", () => {test("rejects pre-aborted publication before preparing scans or touching local state", async () => {const publication = preparedPublication();