Skip to content

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

feat(typescript): import GitHub code scanning alerts (#646)

Kyle Browna4c001bb43d1
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 3178c7db5..db3f2bfd5 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -105,6 +105,52 @@ to the Codex Security state directory's `validations/` folder. Pass `auth` to
select authentication or `signal` to cancel. Failed, incomplete, or malformed
responses reject the promise.
+### Import GitHub code scanning alerts
+
+Use `importGitHubCodeScanningAlerts()` to read GitHub code scanning findings,
+including third-party SARIF uploads, before independent validation:
+
+```ts
+import {
+ CodexSecurity,
+ importGitHubCodeScanningAlerts,
+} from "@openai/codex-security";
+
+const findings = await importGitHubCodeScanningAlerts({
+ repository: "example/repository",
+ alertNumbers: [12, 18], // Omit to list all open alerts on the default branch.
+ githubToken: process.env["GH_TOKEN"],
+});
+
+const security = new CodexSecurity();
+try {
+ for (const finding of findings) {
+ const result = await security.validate({
+ repositoryPath: "/path/to/repository",
+ finding,
+ });
+ console.log(finding.url, result.disposition, result.outputDir);
+ }
+} finally {
+ await security.close();
+}
+```
+
+Each result contains `source`, `repository`, `number`, `url`, and the full
+upstream `alert`, including rule/help text, locations, commit/ref, and dismissal
+context. Import does not start Codex, register a scan, or change GitHub state.
+Validate against the intended local checkout; import does not check out code.
+
+Without `alertNumbers`, `state` defaults to `"open"`; `"closed"`, `"dismissed"`,
+`"fixed"`, and `"all"` are also accepted. Exact alert numbers ignore state and
+cannot be combined with a nondefault `state`. `ref` selects another branch or
+pull-request reference and preserves that reference's alert instance.
+
+Authentication reuses `gh auth token` (including GitHub CLI token environment
+variables) unless `githubToken` is supplied. `githubHost` defaults to `GH_HOST`
+or `github.com`; `signal` cancels requests. The token needs read access to code
+scanning alerts. Access failures reject the import.
+
### SDK configuration and scan options
Pass runtime configuration to the `CodexSecurity` constructor:
@@ -298,6 +344,7 @@ npx @openai/codex-security publish scan --to linear --linear-team TEAM_ID
npx @openai/codex-security publish scan --to cloud --csv /path/outside/repository/findings.csv
npx @openai/codex-security validate /path/outside/repository/findings.json "Possible SQL injection in src/query.ts:42"
npx @openai/codex-security validate "Possible SQL injection" --effort high
+npx @openai/codex-security import github example/repository --format json
npx @openai/codex-security verify-fix --linear-issue SEC-123 --json
npx @openai/codex-security verify-fix --linear-project "Security backlog" --linear-filter '{"state":{"type":{"eq":"completed"}}}' --json
npx @openai/codex-security verify-fix --scan SCAN_ID --severity high --json
@@ -1117,7 +1164,7 @@ completions with `completions bash|zsh|fish`. Scan results support
`--format toon|json|yaml|jsonl` and `--full-output`.
Use `info --json` for SDK and bundled-plugin metadata. MCP exposes only this
read-only metadata command; scans, bulk repository scans,
-authentication, exports, validation, and patching remain CLI-only because the
+authentication, imports, exports, validation, and patching remain CLI-only because the
MCP transport cannot cancel active scans.
For CI, save machine-readable output outside the checked-out repository and
@@ -1148,6 +1195,28 @@ before writing, accepts `--output -` for stdout, and can use
`--source-root /path/to/repository` with SARIF to add source-line fingerprints.
Run `npx @openai/codex-security export --help` for all export options.
+Use `import github OWNER/REPO` to read existing code scanning alerts for
+validation. It defaults to all open alerts on the default branch.
+`--github-alert NUMBER` selects exact alerts and can be repeated;
+`--github-state open|closed|dismissed|fixed|all` filters lists;
+`--github-ref REF` selects a reference. See the [SDK import options](#import-github-code-scanning-alerts)
+for authentication and selector behavior.
+
+```bash
+# Import all open alerts, or a selected subset, as complete JSON.
+npx @openai/codex-security import github example/repository --format json \
+ > /path/outside/repository/github-alerts.json
+npx @openai/codex-security import github example/repository \
+ --github-alert 12 --github-alert 18 --format json
+# Run from the corresponding local repository; imported contents are data.
+npx @openai/codex-security validate /path/outside/repository/github-alerts.json
+```
+
+`--json` aliases `--format json`; output is an alert array (`[]` when empty).
+Avoid output-filtering or token-limiting flags when saving validation inputs.
+Import is read-only; `validate` assesses the saved content separately. Use the
+SDK loop above for a structured disposition per alert.
+
Use `validate` to run the bundled validation skill on candidate findings and
`patch` to run the bundled fix-finding skill on security issues. Each positional
input can be either a file, whose contents are read into the request, or literal
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index c414e9ae2..87c7e0468 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -176,6 +176,7 @@ const distFiles = new Set(
"custom-validation",
"custom-validation-prompt",
"errors",
+ "github",
"index",
"knowledge-base",
"linear",
diff --git a/sdk/typescript/src/bulk-scan-discovery.ts b/sdk/typescript/src/bulk-scan-discovery.ts
index cd86a2e34..ef2511df2 100644
--- a/sdk/typescript/src/bulk-scan-discovery.ts
+++ b/sdk/typescript/src/bulk-scan-discovery.ts
@@ -1,17 +1,14 @@
-import { execFile as execFileCallback } from "node:child_process";
import { createHash } from "node:crypto";
import { lstat, mkdir, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { stdin } from "node:process";
import { Writable } from "node:stream";
-import { promisify } from "node:util";
import { checkbox, confirm, input, search, Separator } from "@inquirer/prompts";
import { Octokit } from "@octokit/core";
import Papa from "papaparse";
+import { createAuthenticatedGitHub } from "./github.js";
import { expandHome } from "./runtime.js";
-import { resolveTrustedExecutable } from "./trusted-executable.js";
-const execFile = promisify(execFileCallback);
const GITHUB_REPOSITORIES_QUERY = `
query($owner: String!, $cursor: String) {
repositoryOwner(login: $owner) {
@@ -111,37 +108,12 @@ export function createBulkScanDiscoveryDependencies(options: {
...(process.env["GH_HOST"]?.trim()
? { githubHost: process.env["GH_HOST"].trim() }
: {}),
- createGitHub: async (host, signal) => {
- const trusted = await resolveTrustedExecutable(
- "gh",
- process.env,
- options.currentDirectory(),
- );
- if (trusted === null) {
- throw new Error(
- "GitHub CLI is required. Install gh and sign in first.",
- );
- }
-
- let token: string;
- try {
- const { stdout } = await execFile(
- trusted.executable,
- ["auth", "token", "--hostname", host],
- { env: trusted.environment, signal },
- );
- token = stdout.trim();
- } catch {
- signal?.throwIfAborted();
- throw new Error(
- "GitHub sign-in is required. Run 'gh auth login' first.",
- );
- }
- return new Octokit({
- auth: token,
- ...(host === "github.com" ? {} : { baseUrl: `https://${host}/api/v3` }),
- });
- },
+ createGitHub: (host, signal) =>
+ createAuthenticatedGitHub(host, {
+ environment: process.env,
+ currentDirectory: options.currentDirectory(),
+ signal,
+ }),
};
}
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 3838592c5..5f279b9bb 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -91,6 +91,10 @@ import {
ScanCostLimitExceededError,
ScanInterruptedError,
} from "./errors.js";
+import {
+ GITHUB_ALERT_STATES,
+ importGitHubCodeScanningAlerts,
+} from "./github.js";
import {
importLinearIssues,
resolveLinearApiKey,
@@ -245,6 +249,9 @@ const VALUE_OPTIONS = new Set([
"--linear-issue",
"--linear-project",
"--linear-filter",
+ "--github-alert",
+ "--github-ref",
+ "--github-state",
"--fail-on-severity",
"--patch-severity",
"--resume-pr",
@@ -1109,6 +1116,7 @@ interface CliDependencies {
bulkScan?: BulkScanDiscoveryDependencies;
planComponents?: typeof planComponents;
linearClient?: LinearClientFactory;
+ importGitHubAlerts?: typeof importGitHubCodeScanningAlerts;
runWorkbench(args: readonly string[], input?: string): Promise<JsonObject>;
matchFindings: typeof matchScanFindings;
checkForUpdate(signal: AbortSignal): Promise<UpdateNotice | undefined>;
@@ -2579,9 +2587,94 @@ export async function main(
}
},
});
+ const imports = Cli.create("import", {
+ description: "Read upstream findings for local validation or triage.",
+ }).command("github", {
+ description: "Import GitHub code scanning alerts without changing GitHub.",
+ destructive: false,
+ mcp: false,
+ args: z.object({
+ repository: z
+ .string()
+ .min(1)
+ .describe("GitHub repository in OWNER/REPO form."),
+ }),
+ options: z.object({
+ githubAlert: z
+ .array(
+ optionValue("--github-alert").regex(
+ /^[1-9]\d*$/u,
+ "GitHub alert numbers must be positive integers.",
+ ),
+ )
+ .default([])
+ .describe(
+ "Exact alert number, regardless of state; repeat to select a subset.",
+ ),
+ githubRef: optionValue("--github-ref")
+ .optional()
+ .describe("Git reference to inspect (default: default branch)."),
+ githubState: z
+ .enum(GITHUB_ALERT_STATES)
+ .default("open")
+ .describe(
+ "State to list; all includes dismissed and fixed alerts. Not used with exact alert numbers.",
+ ),
+ }),
+ output: z
+ .array(
+ z.object({
+ source: z.literal("github-code-scanning"),
+ repository: z.string(),
+ number: z.number().int().positive(),
+ url: z.string(),
+ alert: z.record(z.string(), z.unknown()),
+ }),
+ )
+ .optional(),
+ async run({ args, options }) {
+ const controller = new AbortController();
+ const onInterrupt = () => controller.abort("SIGINT");
+ const onTerminate = () => controller.abort("SIGTERM");
+ dependencies.addSignalListener("SIGINT", onInterrupt);
+ dependencies.addSignalListener("SIGTERM", onTerminate);
+ try {
+ return await (
+ dependencies.importGitHubAlerts ?? importGitHubCodeScanningAlerts
+ )(
+ {
+ repository: args.repository,
+ alertNumbers: options.githubAlert.map(Number),
+ ref: options.githubRef,
+ state: options.githubState,
+ signal: controller.signal,
+ },
+ {
+ environment: dependencies.environment,
+ currentDirectory: dependencies.currentDirectory(),
+ },
+ );
+ } catch (error) {
+ const signal = controller.signal.reason;
+ if (signal === "SIGINT" || signal === "SIGTERM") {
+ exitCode = signal === "SIGINT" ? 130 : 143;
+ errorOutput.write(
+ `codex-security: GitHub import ${signal === "SIGINT" ? "canceled" : "terminated"}.\n`,
+ );
+ } else {
+ exitCode = 2;
+ errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
+ }
+ return undefined;
+ } finally {
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
+ }
+ },
+ });
const cli = Cli.create("codex-security", {
description:
- "Run, validate, patch, verify fixes, export, and publish Codex Security findings.",
+ "Run, import, validate, patch, verify fixes, export, and publish Codex Security findings.",
version: VERSION,
mcp: {
command: "npx --yes @openai/codex-security --mcp",
@@ -2921,6 +3014,7 @@ export async function main(
.command(scanHistory)
.command(findingFeedback)
.command(publication)
+ .command(imports)
.command("scan-components", {
description:
"Run standard scans for project components and combine the results.",
@@ -4270,6 +4364,7 @@ function validateCliArguments(
"findings",
"export",
"publish",
+ "import",
"validate",
"verify-fix",
"patch",
@@ -4334,7 +4429,10 @@ function validateCliArguments(
}
}
const nestedCommand =
- command === "scans" || command === "findings" || command === "publish";
+ command === "scans" ||
+ command === "findings" ||
+ command === "publish" ||
+ command === "import";
const subcommand = nestedCommand ? argv[commandIndex + 1] : undefined;
if (command === "info") {
const metadataFields = new Set([
diff --git a/sdk/typescript/src/github.ts b/sdk/typescript/src/github.ts
new file mode 100644
index 000000000..8cfcfac0b
--- /dev/null
+++ b/sdk/typescript/src/github.ts
@@ -0,0 +1,253 @@
+import { execFile as execFileCallback } from "node:child_process";
+import { promisify } from "node:util";
+import { Octokit } from "@octokit/core";
+import { CodexSecurityError } from "./errors.js";
+import { resolveTrustedExecutable } from "./trusted-executable.js";
+
+const execFile = promisify(execFileCallback);
+type GitHubAlert = Awaited<ReturnType<typeof fetchGitHubAlert>>;
+
+export const GITHUB_ALERT_STATES = [
+ "open",
+ "closed",
+ "dismissed",
+ "fixed",
+ "all",
+] as const;
+
+export interface GitHubCodeScanningImportOptions {
+ /** GitHub repository in OWNER/REPO form. */
+ repository: string;
+ /** Exact alert numbers, regardless of state. Omit to list matching alerts. */
+ alertNumbers?: readonly number[];
+ /** State used when listing alerts (default: open). */
+ state?: (typeof GITHUB_ALERT_STATES)[number];
+ /** Git reference to inspect; omitted lists the default branch. */
+ ref?: string;
+ /** Defaults to GH_HOST or github.com. */
+ githubHost?: string;
+ /** Omit to use the authenticated GitHub CLI, including its token environment. */
+ githubToken?: string;
+ signal?: AbortSignal;
+}
+
+export interface ImportedGitHubCodeScanningAlert {
+ source: "github-code-scanning";
+ repository: string;
+ number: number;
+ url: string;
+ /** Upstream evidence, not a validated or sealed Codex Security finding. */
+ alert: GitHubAlert;
+}
+
+interface GitHubImportDependencies {
+ environment?: NodeJS.ProcessEnv;
+ currentDirectory?: string;
+ createGitHub?: (host: string, signal?: AbortSignal) => Promise<Octokit>;
+}
+
+export async function createAuthenticatedGitHub(
+ host: string,
+ options: {
+ environment?: NodeJS.ProcessEnv;
+ currentDirectory?: string;
+ token?: string;
+ signal?: AbortSignal;
+ } = {},
+): Promise<Octokit> {
+ options.signal?.throwIfAborted();
+ let token = options.token;
+ if (token === undefined) {
+ const trusted = await resolveTrustedExecutable(
+ "gh",
+ options.environment ?? process.env,
+ options.currentDirectory ?? process.cwd(),
+ );
+ if (trusted === null) {
+ throw new CodexSecurityError(
+ "GitHub CLI is required. Install gh and sign in first.",
+ );
+ }
+ try {
+ const { stdout } = await execFile(
+ trusted.executable,
+ ["auth", "token", "--hostname", host],
+ { env: trusted.environment, signal: options.signal },
+ );
+ token = stdout.trim();
+ } catch {
+ options.signal?.throwIfAborted();
+ throw new CodexSecurityError(
+ "GitHub sign-in is required. Run 'gh auth login' first.",
+ );
+ }
+ }
+ if (token.trim().length === 0) {
+ throw new CodexSecurityError("GitHub access token must not be empty.");
+ }
+ return new Octokit({
+ auth: token,
+ ...(host === "github.com" ? {} : { baseUrl: `https://${host}/api/v3` }),
+ });
+}
+
+export async function importGitHubCodeScanningAlerts(
+ options: GitHubCodeScanningImportOptions,
+ dependencies: GitHubImportDependencies = {},
+): Promise<ImportedGitHubCodeScanningAlert[]> {
+ options.signal?.throwIfAborted();
+ const repository = options.repository.trim();
+ const parts = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(repository);
+ if (
+ parts === null ||
+ parts.slice(1).some((part) => /^\.{1,2}$/u.test(part))
+ ) {
+ throw new CodexSecurityError("GitHub repository must be OWNER/REPO.");
+ }
+ const owner = parts[1]!;
+ const repo = parts[2]!;
+ const numbers = [...new Set(options.alertNumbers ?? [])];
+ if (numbers.some((number) => !Number.isSafeInteger(number) || number < 1)) {
+ throw new CodexSecurityError(
+ "GitHub alert numbers must be positive integers.",
+ );
+ }
+ const state = options.state ?? "open";
+ if (!GITHUB_ALERT_STATES.includes(state)) {
+ throw new CodexSecurityError("GitHub alert state is invalid.");
+ }
+ if (numbers.length > 0 && state !== "open") {
+ throw new CodexSecurityError(
+ "--github-state only filters lists; use it without --github-alert.",
+ );
+ }
+ const ref = options.ref?.trim();
+ if (ref === "") {
+ throw new CodexSecurityError("GitHub reference must not be empty.");
+ }
+ const environment = dependencies.environment ?? process.env;
+ const host =
+ options.githubHost?.trim() ??
+ (environment["GH_HOST"]?.trim() || "github.com");
+ if (host.length === 0) {
+ throw new CodexSecurityError("GitHub host must not be empty.");
+ }
+
+ try {
+ const github = dependencies.createGitHub
+ ? await dependencies.createGitHub(host, options.signal)
+ : await createAuthenticatedGitHub(host, {
+ token: options.githubToken,
+ environment,
+ currentDirectory: dependencies.currentDirectory,
+ signal: options.signal,
+ });
+ const selected = new Map<number, GitHubAlert["most_recent_instance"]>();
+ if (numbers.length === 0 || ref !== undefined) {
+ let page = 1;
+ while (true) {
+ options.signal?.throwIfAborted();
+ // Octokit's list route omits GitHub's "closed" state.
+ const response = await github.request<
+ Pick<GitHubAlert, "number" | "most_recent_instance">[]
+ >({
+ method: "GET",
+ url: "/repos/{owner}/{repo}/code-scanning/alerts",
+ owner,
+ repo,
+ per_page: 100,
+ page,
+ ref,
+ state: numbers.length > 0 || state === "all" ? undefined : state,
+ request: { signal: options.signal, redirect: "error" },
+ });
+ for (const alert of response.data) {
+ if (numbers.length === 0 || numbers.includes(alert.number)) {
+ selected.set(alert.number, alert.most_recent_instance);
+ }
+ }
+ if (
+ !response.headers.link?.includes('rel="next"') ||
+ (numbers.length > 0 && selected.size === numbers.length)
+ )
+ break;
+ page += 1;
+ }
+ if (numbers.some((number) => !selected.has(number))) {
+ throw new CodexSecurityError(
+ "One or more selected GitHub alerts were not found on the requested reference.",
+ );
+ }
+ }
+ const alerts: ImportedGitHubCodeScanningAlert[] = [];
+ for (const number of numbers.length > 0 ? numbers : selected.keys()) {
+ options.signal?.throwIfAborted();
+ const alert = await fetchGitHubAlert(
+ github,
+ owner,
+ repo,
+ number,
+ options.signal,
+ );
+ // Detail requests use the default branch; retain the listed ref's evidence.
+ const instance = selected.get(number);
+ alerts.push({
+ source: "github-code-scanning",
+ repository,
+ number,
+ url: alert.html_url,
+ alert:
+ instance === undefined
+ ? alert
+ : { ...alert, most_recent_instance: instance },
+ });
+ }
+ return alerts;
+ } catch (error) {
+ options.signal?.throwIfAborted();
+ if (error instanceof CodexSecurityError) throw error;
+ const status =
+ typeof error === "object" && error !== null && "status" in error
+ ? error.status
+ : undefined;
+ if (status === 401)
+ throw new CodexSecurityError("GitHub authentication failed.");
+ if (status === 403) {
+ throw new CodexSecurityError(
+ "GitHub denied code scanning access. Check repository permissions, code scanning availability, and API rate limits.",
+ );
+ }
+ if (status === 404) {
+ throw new CodexSecurityError(
+ "GitHub repository or code scanning alert was not found or is not accessible.",
+ );
+ }
+ if (status === 429)
+ throw new CodexSecurityError(
+ "GitHub request was rate limited. Wait and retry.",
+ );
+ // Octokit errors can contain credential-bearing request headers.
+ throw new CodexSecurityError(
+ `GitHub code scanning request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}.`,
+ );
+ }
+}
+
+async function fetchGitHubAlert(
+ github: Octokit,
+ owner: string,
+ repo: string,
+ alertNumber: number,
+ signal?: AbortSignal,
+) {
+ const response = await github.request(
+ "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}",
+ {
+ owner,
+ repo,
+ alert_number: alertNumber,
+ request: { signal, redirect: "error" },
+ },
+ );
+ return response.data;
+}
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index b29340fd5..b693ed894 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -64,6 +64,11 @@ export { loadContract, requireScanFile } from "./contract.js";
export type { LoadedContract, ScanExpectation } from "./contract.js";
export type * from "./models.js";
export { checkScanPublication, publishScan } from "./publish.js";
+export { importGitHubCodeScanningAlerts } from "./github.js";
+export type {
+ GitHubCodeScanningImportOptions,
+ ImportedGitHubCodeScanningAlert,
+} from "./github.js";
export type {
CheckScanPublicationOptions,
CheckScanPublicationResult,
diff --git a/sdk/typescript/tests-ts/cli-fixtures.ts b/sdk/typescript/tests-ts/cli-fixtures.ts
index 175bbda29..c02abc485 100644
--- a/sdk/typescript/tests-ts/cli-fixtures.ts
+++ b/sdk/typescript/tests-ts/cli-fixtures.ts
@@ -194,6 +194,7 @@ export function dependencies(
...arguments_: Parameters<MainDependencies["runCodex"]>
) => number | Promise<number>;
linearClient?: MainDependencies["linearClient"];
+ importGitHubAlerts?: MainDependencies["importGitHubAlerts"];
onRepositoryCommand?: (
...arguments_: Parameters<MainDependencies["runRepositoryCommand"]>
) => string | Promise<string>;
@@ -269,6 +270,9 @@ export function dependencies(
...(options.linearClient === undefined
? {}
: { linearClient: options.linearClient }),
+ ...(options.importGitHubAlerts === undefined
+ ? {}
+ : { importGitHubAlerts: options.importGitHubAlerts }),
runWorkbench: async (args, input) =>
(await options.onWorkbench?.(args, input)) ?? { scans: [] },
matchFindings: async (input) =>
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index 504e52a02..2cda6d522 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -220,6 +220,9 @@ describe("CLI", () => {
);
expect(manifest.text()).toContain("codex-security bulk-scan [input]");
expect(manifest.text()).toContain("codex-security export [scanDir]");
+ expect(manifest.text()).toContain(
+ "codex-security import github <repository>",
+ );
expect(manifest.text()).toContain("codex-security validate <findings...>");
expect(manifest.text()).toContain(
"codex-security verify-fix [findings...]",
diff --git a/sdk/typescript/tests-ts/github.test.ts b/sdk/typescript/tests-ts/github.test.ts
new file mode 100644
index 000000000..1eed0f7c5
--- /dev/null
+++ b/sdk/typescript/tests-ts/github.test.ts
@@ -0,0 +1,434 @@
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Octokit } from "@octokit/core";
+import { describe, expect, test } from "bun:test";
+import { main } from "../src/cli.js";
+import {
+ createAuthenticatedGitHub,
+ GITHUB_ALERT_STATES,
+ importGitHubCodeScanningAlerts,
+ type GitHubCodeScanningImportOptions,
+} from "../src/github.js";
+import { capture, dependencies, FakeSignals } from "./cli-fixtures.js";
+
+function alert(number: number, ref = "refs/heads/main") {
+ return {
+ number,
+ url: `https://api.github.com/repos/example/repository/code-scanning/alerts/${number}`,
+ html_url: `https://github.com/example/repository/security/code-scanning/${number}`,
+ state: "open",
+ dismissed_reason: null,
+ dismissed_comment: null,
+ rule: {
+ id: "synthetic/sql-injection",
+ severity: "error",
+ security_severity_level: "high",
+ name: "Synthetic query finding",
+ description: "A synthetic query candidate",
+ full_description:
+ "Synthetic full description for independent assessment.",
+ help: "# Synthetic remediation\nUse parameter binding.",
+ tags: ["security", "external/cwe/cwe-089"],
+ },
+ tool: { name: "Synthetic Scanner", version: "1.0.0", guid: null },
+ most_recent_instance: {
+ ref,
+ commit_sha: "a".repeat(40),
+ state: "open",
+ message: { text: "Synthetic untrusted query input." },
+ location: { path: "src/query.ts", start_line: number, end_line: number },
+ },
+ };
+}
+
+function github(
+ respond: (
+ url: URL,
+ init?: Parameters<typeof fetch>[1],
+ ) => Response | Promise<Response>,
+): Octokit {
+ return new Octokit({
+ auth: "SYNTHETIC_GITHUB_TOKEN",
+ request: {
+ fetch: async (
+ resource: Parameters<typeof fetch>[0],
+ init?: Parameters<typeof fetch>[1],
+ ) => {
+ expect(init?.method).toBe("GET");
+ expect(init?.redirect).toBe("error");
+ return await respond(
+ new URL(resource instanceof Request ? resource.url : resource),
+ init,
+ );
+ },
+ },
+ });
+}
+
+describe("GitHub code scanning import", () => {
+ test("paginates open alerts and preserves rule detail and selected-ref evidence", async () => {
+ const paths: string[] = [];
+ const client = github((url) => {
+ paths.push(`${url.pathname}${url.search}`);
+ if (url.pathname.endsWith("/alerts")) {
+ expect(url.searchParams.get("state")).toBe("open");
+ expect(url.searchParams.get("ref")).toBe("refs/heads/review");
+ expect(url.searchParams.get("per_page")).toBe("100");
+ const page = Number(url.searchParams.get("page"));
+ const item = alert(page, "refs/heads/review");
+ item.most_recent_instance.commit_sha = "b".repeat(40);
+ return Response.json(
+ [item],
+ page === 1
+ ? {
+ headers: {
+ link: '<https://api.github.com/repos/example/repository/code-scanning/alerts?page=2>; rel="next"',
+ },
+ }
+ : undefined,
+ );
+ }
+ return Response.json(alert(Number(url.pathname.split("/").at(-1))));
+ });
+ const results = await importGitHubCodeScanningAlerts(
+ { repository: "example/repository", ref: "refs/heads/review" },
+ { createGitHub: async () => client },
+ );
+ expect(paths).toHaveLength(4);
+ expect(results.map(({ number }) => number)).toEqual([1, 2]);
+ expect(results[0]).toMatchObject({
+ source: "github-code-scanning",
+ repository: "example/repository",
+ number: 1,
+ url: alert(1).html_url,
+ alert: {
+ rule: alert(1).rule,
+ tool: alert(1).tool,
+ most_recent_instance: {
+ ...alert(1, "refs/heads/review").most_recent_instance,
+ commit_sha: "b".repeat(40),
+ },
+ },
+ });
+ expect(JSON.stringify(results)).not.toContain("SYNTHETIC_GITHUB_TOKEN");
+ });
+
+ test("imports exact alert numbers in requested order, including dismissed alerts", async () => {
+ const paths: string[] = [];
+ const client = github((url) => {
+ paths.push(url.pathname);
+ const item = alert(Number(url.pathname.split("/").at(-1)));
+ return Response.json({
+ ...item,
+ state: "dismissed",
+ dismissed_reason: "false positive",
+ dismissed_comment: "Synthetic prior reviewer evidence.",
+ });
+ });
+ const results = await importGitHubCodeScanningAlerts(
+ { repository: "example/repository", alertNumbers: [42, 7, 42] },
+ { createGitHub: async () => client },
+ );
+ expect(paths).toEqual([
+ "/repos/example/repository/code-scanning/alerts/42",
+ "/repos/example/repository/code-scanning/alerts/7",
+ ]);
+ expect(results.map(({ number }) => number)).toEqual([42, 7]);
+ expect(results[0]!.alert).toMatchObject({
+ state: "dismissed",
+ dismissed_reason: "false positive",
+ dismissed_comment: "Synthetic prior reviewer evidence.",
+ });
+ });
+
+ test.each(["all", "dismissed"] as const)(
+ "lists the requested %s state",
+ async (state) => {
+ const result = await importGitHubCodeScanningAlerts(
+ { repository: "example/repository", state },
+ {
+ createGitHub: async () =>
+ github((url) => {
+ expect(url.searchParams.get("state")).toBe(
+ state === "all" ? null : state,
+ );
+ expect(url.searchParams.has("ref")).toBe(false);
+ return Response.json([]);
+ }),
+ },
+ );
+ expect(result).toEqual([]);
+ },
+ );
+
+ test("selected alert numbers plus a ref retain that instance and do not filter state", async () => {
+ const result = await importGitHubCodeScanningAlerts(
+ { repository: "example/repository", alertNumbers: [7], ref: "review" },
+ {
+ createGitHub: async () =>
+ github((url) => {
+ if (url.pathname.endsWith("/alerts")) {
+ expect(url.searchParams.get("state")).toBeNull();
+ return Response.json([
+ alert(8, "refs/heads/review"),
+ alert(7, "refs/heads/review"),
+ ]);
+ }
+ expect(url.pathname.endsWith("/7")).toBe(true);
+ return Response.json(alert(7));
+ }),
+ },
+ );
+ expect(result).toHaveLength(1);
+ expect(result[0]!.alert.most_recent_instance.ref).toBe("refs/heads/review");
+ await expect(
+ importGitHubCodeScanningAlerts(
+ { repository: "example/repository", alertNumbers: [7], ref: "missing" },
+ { createGitHub: async () => github(() => Response.json([])) },
+ ),
+ ).rejects.toThrow("not found on the requested reference");
+ });
+
+ test.each([
+ [401, "authentication failed"],
+ [403, "denied code scanning access"],
+ [404, "not found or is not accessible"],
+ [429, "rate limited"],
+ [503, "HTTP 503"],
+ ] as const)(
+ "reports HTTP %i without exposing token-bearing diagnostics",
+ async (status, message) => {
+ const failure = await importGitHubCodeScanningAlerts(
+ { repository: "example/repository" },
+ {
+ createGitHub: async () =>
+ github(() =>
+ Response.json({ message: "SYNTHETIC_GITHUB_TOKEN" }, { status }),
+ ),
+ },
+ ).catch((error: Error) => error);
+ expect(failure).toBeInstanceOf(Error);
+ expect((failure as Error).message).toContain(message);
+ expect((failure as Error).message).not.toContain(
+ "SYNTHETIC_GITHUB_TOKEN",
+ );
+ },
+ );
+
+ test("validates selectors before authentication and supports cancellation", async () => {
+ let authenticated = false;
+ const createGitHub = async () => {
+ authenticated = true;
+ return github(() => Response.json([]));
+ };
+ for (const options of [
+ { repository: "https://github.com/example/repository" },
+ { repository: "example/.." },
+ { repository: "example/repository", alertNumbers: [0] },
+ { repository: "example/repository", alertNumbers: [1.5] },
+ { repository: "example/repository", ref: " " },
+ { repository: "example/repository", githubHost: "" },
+ { repository: "example/repository", alertNumbers: [1], state: "all" },
+ ] satisfies GitHubCodeScanningImportOptions[]) {
+ await expect(
+ importGitHubCodeScanningAlerts(options, { createGitHub }),
+ ).rejects.toThrow();
+ }
+ await expect(
+ importGitHubCodeScanningAlerts(
+ {
+ repository: "example/repository",
+ signal: AbortSignal.abort(new Error("Synthetic cancellation")),
+ },
+ { createGitHub },
+ ),
+ ).rejects.toThrow("Synthetic cancellation");
+ expect(authenticated).toBe(false);
+
+ const controller = new AbortController();
+ await expect(
+ importGitHubCodeScanningAlerts(
+ { repository: "example/repository", signal: controller.signal },
+ {
+ createGitHub: async () =>
+ github(() => {
+ controller.abort(new Error("Canceled after list"));
+ return Response.json([alert(1)]);
+ }),
+ },
+ ),
+ ).rejects.toThrow("Canceled after list");
+ });
+
+ test("supports SDK tokens and Enterprise hosts without requiring gh", async () => {
+ const client = await createAuthenticatedGitHub("github.example.com:8443", {
+ token: "SYNTHETIC_SDK_TOKEN",
+ environment: {},
+ });
+ expect(await client.auth()).toMatchObject({ token: "SYNTHETIC_SDK_TOKEN" });
+ expect(client.request.endpoint("GET /user")).toMatchObject({
+ url: "https://github.example.com:8443/api/v3/user",
+ });
+ await expect(
+ createAuthenticatedGitHub("github.com", { token: " " }),
+ ).rejects.toThrow("must not be empty");
+ });
+});
+
+describe("GitHub import CLI", () => {
+ test("emits complete JSON for file validation without starting Codex during import", async () => {
+ const root = await mkdtemp(join(tmpdir(), "codex-security-github-import-"));
+ try {
+ const stdout = capture();
+ const stderr = capture();
+ const imported = await importGitHubCodeScanningAlerts(
+ { repository: "example/repository", alertNumbers: [42] },
+ { createGitHub: async () => github(() => Response.json(alert(42))) },
+ );
+ const mustNotStartCodex = () => {
+ throw new Error("Import must not start Codex");
+ };
+ expect(
+ await main(
+ ["import", "github", "example/repository", "--json"],
+ stdout.stream,
+ stderr.stream,
+ dependencies({
+ importGitHubAlerts: async () => imported,
+ onCodex: mustNotStartCodex,
+ onRun: mustNotStartCodex,
+ }),
+ ),
+ ).toBe(0);
+ expect(stderr.text()).toBe("");
+ expect(JSON.parse(stdout.text())).toEqual(imported);
+
+ const file = join(root, "github-alerts.json");
+ await writeFile(file, stdout.text());
+ let input = "";
+ expect(
+ await main(
+ ["validate", file],
+ capture().stream,
+ capture().stream,
+ dependencies({
+ currentDirectory: root,
+ onCodex: (_args, _output, _environment, prompt) => {
+ input = prompt!;
+ return 0;
+ },
+ }),
+ ),
+ ).toBe(0);
+ expect(JSON.parse(input.split("\n").at(-1)!)).toEqual([stdout.text()]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ test("routes repeated selectors, state, and ref and documents their schema", async () => {
+ let options: GitHubCodeScanningImportOptions | undefined;
+ const stdout = capture();
+ expect(
+ await main(
+ [
+ "import",
+ "github",
+ "example/repository",
+ "--github-alert",
+ "12",
+ "--github-alert",
+ "18",
+ "--github-ref",
+ "refs/heads/review",
+ "--format",
+ "json",
+ ],
+ stdout.stream,
+ capture().stream,
+ dependencies({
+ importGitHubAlerts: async (selected) => {
+ options = selected;
+ return [];
+ },
+ }),
+ ),
+ ).toBe(0);
+ expect(options).toMatchObject({
+ alertNumbers: [12, 18],
+ ref: "refs/heads/review",
+ state: "open",
+ });
+ expect(JSON.parse(stdout.text())).toEqual([]);
+ const schema = capture();
+ expect(
+ await main(
+ ["import", "github", "--schema", "--format", "json"],
+ schema.stream,
+ capture().stream,
+ dependencies(),
+ ),
+ ).toBe(0);
+ expect(JSON.parse(schema.text())).toMatchObject({
+ args: { required: ["repository"] },
+ options: {
+ properties: {
+ githubAlert: { type: "array" },
+ githubRef: { type: "string" },
+ githubState: { default: "open", enum: [...GITHUB_ALERT_STATES] },
+ },
+ },
+ });
+ });
+
+ test.each(
+ [
+ ["import", "github"],
+ ["import", "github", "example/repository", "extra"],
+ ["import", "github", "example/repository", "--github-alert"],
+ ["import", "github", "example/repository", "--github-alert", "0"],
+ ["import", "github", "example/repository", "--github-alert", "1.5"],
+ ["import", "github", "example/repository", "--github-state", "unknown"],
+ ].map((argv) => [argv] as const),
+ )("rejects invalid arguments %j", async (argv) => {
+ let called = false;
+ expect(
+ await main(
+ argv,
+ capture().stream,
+ capture().stream,
+ dependencies({
+ importGitHubAlerts: async () => {
+ called = true;
+ return [];
+ },
+ }),
+ ),
+ ).toBe(2);
+ expect(called).toBe(false);
+ });
+
+ test("returns cancellation and removes signal handlers", async () => {
+ const signals = new FakeSignals();
+ const stderr = capture();
+ expect(
+ await main(
+ ["import", "github", "example/repository"],
+ capture().stream,
+ stderr.stream,
+ dependencies({
+ signals,
+ importGitHubAlerts: async ({ signal }) => {
+ signals.emit("SIGINT");
+ signal!.throwIfAborted();
+ return [];
+ },
+ }),
+ ),
+ ).toBe(130);
+ expect(stderr.text()).toContain("canceled");
+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);
+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);
+ });
+});