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
chore(codex-security): sync public projection
David Chouinardb54f89c22e1c
diff --git a/README.md b/README.mdindex 0dfc70da6..5a8622fff 100644--- a/README.md+++ b/README.md@@ -47,6 +47,8 @@ npx codex-security scan /path/to/repo --output-dir /path/outside/repo/resultsnpx codex-security scan /path/to/repo --output-dir /path/outside/repo/results --archive-existingnpx codex-security scan /path/to/repo --dry-runnpx codex-security scan /path/to/repo --fail-on-severity high+npx codex-security bulk-scan+npx codex-security bulk-scan repositories.csv --output-dir ./security-scansnpx codex-security scans list /path/to/reponpx codex-security scans list --scan-root /path/outside/repo/resultsnpx codex-security scans show SCAN_ID@@ -64,6 +66,18 @@ worktree. When SARIF is produced, it is written to`<scan-dir>/exports/results.sarif`. Use `npx codex-security scan --help` for alltarget, output, and runtime options.+Run `npx codex-security bulk-scan` in an interactive terminal to discover+GitHub repositories, review the matches, and confirm before starting a scan.+The default selection includes private and internal repositories pushed in the+last 90 days. Select **Something else** to filter by repository-name keywords,+activity, primary language, and one or more visibility levels. Private and+internal visibility are selected by default. Private repository checkouts reuse+your GitHub CLI sign-in without changing your global Git configuration.+Archived repositories and forks are always excluded. For automation or an+existing repository list, pass a CSV containing `id`, `repository`, and full+immutable `revision` columns and specify `--output-dir`. Use+`npx codex-security bulk-scan --help` for all options.+The CLI uses [Incur](https://github.com/wevm/incur) for agent-friendly discoveryand structured output. Use `--llms` for the command manifest,`scan --schema --format json` for a command schema, register an MCP server withdiff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 0fb456974..30a4fdc34 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -60,12 +60,13 @@ npx codex-security scan /path/to/repository --output-dir /path/outside/repositornpx codex-security scan /path/to/repository --output-dir /path/outside/repository/results --archive-existingnpx codex-security scan /path/to/repository --dry-runnpx codex-security scan /path/to/repository --fail-on-severity high+npx codex-security bulk-scan+npx codex-security bulk-scan repositories.csv --output-dir /tmp/security-scans --workers 4npx codex-security scans list /path/to/repositorynpx codex-security scans list --scan-root /path/outside/repository/resultsnpx codex-security scans show SCAN_IDnpx codex-security scans rerun SCAN_IDnpx codex-security scans compare PREVIOUS_SCAN_ID CURRENT_SCAN_ID-npx codex-security scan-csv repositories.csv --output-dir /tmp/security-scans --workers 4npx codex-security export /path/outside/repository/results --export-format sarif --output results.sarifnpx codex-security export /path/outside/repository/results --export-format csv --output findings.csvnpx codex-security export /path/outside/repository/results --export-format json --output findings.json@@ -99,10 +100,23 @@ Scans use `gpt-5.6-sol` with extra-high reasoning effort by default. Overrideeither setting with repeatable `--codex KEY=VALUE` options, for example`--codex 'model="gpt-5.6-sol"' --codex 'model_reasoning_effort="high"'`.-Run `npx codex-security scan --help` or `npx codex-security scan-csv --help`+Run `npx codex-security scan --help` or `npx codex-security bulk-scan --help`for the complete CLI references.-Use `scan-csv` to scan repositories from a CSV manifest with required `id`,+Run `npx codex-security bulk-scan` in an interactive terminal to discover+repositories through an authenticated GitHub CLI. The default selection+includes private and internal repositories pushed in the last 90 days and+excludes archived repositories and forks. Select **Something else** to choose+repository-name keywords, an activity window, a primary language, and+one or more repository visibility levels. Private and internal repositories+are selected by default, and multiple name keywords match any of the specified+terms. Private repository checkouts reuse your GitHub CLI sign-in without+changing your global Git configuration. Review the matching repositories and+choose an output directory; scanning starts only after you confirm. The+selected repositories are recorded in `<output-dir>/repositories.csv` so the+scan can be reviewed or resumed.++To use an existing repository list or run in CI, pass a CSV with required `id`,`repository`, and `revision` columns. Revisions must be full commit hashes;optional `scope` and `mode` columns narrow individual scans:@@ -141,7 +155,7 @@ server with `mcp add`, sync agent skills with `skills add`, or generate shellcompletions 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, CSV-based multi-repository scans,+read-only metadata command; scans, bulk repository scans,authentication, exports, validation, and patching remain CLI-only because theMCP transport cannot cancel active scans.diff --git a/sdk/typescript/package.json b/sdk/typescript/package.jsonindex c63e09be7..75eab78ad 100644--- a/sdk/typescript/package.json+++ b/sdk/typescript/package.json@@ -46,7 +46,7 @@"generate:models": "node scripts/generate-models.cjs","generate:models:check": "node scripts/generate-models.cjs --check","lint": "tsc --noEmit",- "test": "bun test --timeout 30000 tests-ts/api.test.ts tests-ts/auth.test.ts tests-ts/cli.test.ts tests-ts/config.test.ts tests-ts/contract.test.ts tests-ts/multiscan.test.ts tests-ts/result.test.ts tests-ts/runtime.test.ts tests-ts/skeleton.test.ts tests-ts/targets.test.ts tests-ts/trusted-executable.test.ts tests-ts/worker-progress.test.ts",+ "test": "bun test --timeout 30000 tests-ts/api.test.ts tests-ts/auth.test.ts tests-ts/bulk-scan-discovery.test.ts tests-ts/cli.test.ts tests-ts/config.test.ts tests-ts/contract.test.ts tests-ts/multiscan.test.ts tests-ts/result.test.ts tests-ts/runtime.test.ts tests-ts/skeleton.test.ts tests-ts/targets.test.ts tests-ts/trusted-executable.test.ts tests-ts/worker-progress.test.ts","types": "pnpm run generate:models:check && tsc --noEmit"},"dependencies": {diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjsindex f99ef1232..a0bb64eb1 100644--- a/sdk/typescript/scripts/check-package.mjs+++ b/sdk/typescript/scripts/check-package.mjs@@ -130,6 +130,7 @@ const distFiles = new Set(["api","auth",+ "bulk-scan-discovery","cli","config","contract",diff --git a/sdk/typescript/src/bulk-scan-discovery.ts b/sdk/typescript/src/bulk-scan-discovery.tsnew file mode 100644index 000000000..b84f3b4e7--- /dev/null+++ b/sdk/typescript/src/bulk-scan-discovery.ts@@ -0,0 +1,928 @@+import { spawn } 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 { emitKeypressEvents } from "node:readline";+import { createInterface } from "node:readline/promises";+import { Writable } from "node:stream";+import { z } from "incur";+import Papa from "papaparse";+import { inspectMultiscanInventory } from "./multiscan.js";+import { resolveTrustedExecutable } from "./trusted-executable.js";++const DEFAULT_ACTIVITY_DAYS = 90;+const PREVIEW_LIMIT = 10;+const DAY_MILLISECONDS = 86_400_000;+const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];+const GITHUB_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;+const GITHUB_NAME = /^[A-Za-z0-9_.-]{1,100}$/u;+const GITHUB_REPOSITORIES_QUERY = `+ query($owner: String!, $endCursor: String, $privacy: RepositoryPrivacy) {+ repositoryOwner(login: $owner) {+ repositories(+ first: 100+ after: $endCursor+ privacy: $privacy+ isArchived: false+ isFork: false+ orderBy: { field: PUSHED_AT, direction: DESC }+ ) {+ nodes {+ nameWithOwner+ url+ visibility+ isArchived+ isFork+ isEmpty+ pushedAt+ primaryLanguage { name }+ defaultBranchRef { target { oid } }+ }+ pageInfo { hasNextPage endCursor }+ }+ }+ }+`.trim();++const githubAuthenticationSchema = z.object({+ hosts: z.record(+ z.string(),+ z.array(+ z.object({+ active: z.boolean().optional(),+ state: z.string().optional(),+ }),+ ),+ ),+});++const githubOwnerRepositoriesSchema = z.object({+ data: z.object({+ repositoryOwner: z+ .object({+ repositories: z.object({+ nodes: z.array(+ z+ .object({+ nameWithOwner: z.string(),+ url: z.string(),+ visibility: z.string(),+ isArchived: z.boolean(),+ isFork: z.boolean(),+ isEmpty: z.boolean(),+ pushedAt: z.string().nullable(),+ primaryLanguage: z.object({ name: z.string() }).nullable(),+ defaultBranchRef: z+ .object({+ target: z.object({+ oid: z.string().regex(/^[0-9a-f]{40,64}$/iu),+ }),+ })+ .nullable(),+ })+ .nullable(),+ ),+ pageInfo: z.object({+ hasNextPage: z.boolean(),+ endCursor: z.string().nullable(),+ }),+ }),+ })+ .nullable(),+ }),+ errors: z.array(z.object({ message: z.string() })).optional(),+});++type GitHubVisibility = "PRIVATE" | "INTERNAL" | "PUBLIC";++interface BulkScanRepositoryFilters {+ nameKeywords: readonly string[];+ activeWithinDays: number | null;+ language: string | null;+ visibility: readonly GitHubVisibility[];+}++const DEFAULT_REPOSITORY_FILTERS: BulkScanRepositoryFilters = {+ nameKeywords: [],+ activeWithinDays: DEFAULT_ACTIVITY_DAYS,+ language: null,+ visibility: ["PRIVATE", "INTERNAL"],+};++export interface BulkScanCommandResult {+ exitCode: number;+ stdout: string;+ stderr: string;+}++export interface BulkScanPrompt {+ isInteractive(): boolean;+ write(value: string): void;+ confirm(question: string, defaultValue?: boolean): Promise<boolean>;+ input(question: string, defaultValue?: string): Promise<string>;+ select<Value extends string>(+ question: string,+ options: readonly { label: string; value: Value }[],+ defaultValue?: Value,+ ): Promise<Value>;+ multiSelect<Value extends string>(+ question: string,+ options: readonly { label: string; value: Value }[],+ defaultValues?: readonly Value[],+ ): Promise<Value[]>;+}++export interface BulkScanDiscoveryDependencies {+ prompt: BulkScanPrompt;+ now(): number;+ currentDirectory(): string;+ githubHost?: string;+ runGitHub(+ args: readonly string[],+ options?: { host?: string; interactive?: boolean; signal?: AbortSignal },+ ): Promise<BulkScanCommandResult>;+}++export interface BulkScanWizardResult {+ inputPath: string;+ outputDir: string;+ githubHost?: string;+}++export class BulkScanInterruptedError extends Error {+ public constructor() {+ super("Bulk scan canceled.");+ this.name = "BulkScanInterruptedError";+ }+}++interface GitHubRepository {+ fullName: string;+ url: string;+ revision: string;+}++interface PromptOutput {+ write(value: string): unknown;+ readonly isTTY?: boolean;+}++export function createBulkScanDiscoveryDependencies(options: {+ output: PromptOutput;+ now(): number;+ currentDirectory(): string;+}): BulkScanDiscoveryDependencies {+ return {+ prompt: createTerminalPrompt(options.output),+ now: options.now,+ currentDirectory: options.currentDirectory,+ ...(process.env["GH_HOST"]?.trim()+ ? { githubHost: process.env["GH_HOST"].trim() }+ : {}),+ runGitHub: async (args, commandOptions = {}) => {+ const trusted = await resolveTrustedExecutable(+ "gh",+ process.env,+ options.currentDirectory(),+ );+ if (trusted === null) {+ throw new Error(+ "GitHub CLI is required to discover repositories. Install gh, then run 'codex-security bulk-scan' again.",+ );+ }+ const environment = {+ ...trusted.environment,+ ...(commandOptions.host === undefined+ ? {}+ : { GH_HOST: commandOptions.host }),+ };+ return await runGitHubCommand(+ trusted.executable,+ args,+ environment,+ commandOptions,+ );+ },+ };+}++export async function runBulkScanWizard(+ dependencies: BulkScanDiscoveryDependencies,+ signal?: AbortSignal,+): Promise<BulkScanWizardResult | null> {+ const { prompt } = dependencies;+ if (!prompt.isInteractive()) {+ throw new Error(+ "Interactive repository selection requires a terminal. Provide a CSV with 'codex-security bulk-scan repositories.csv --output-dir ./security-scans'.",+ );+ }+ signal?.throwIfAborted();+ const hasRepositoryList = await prompt.confirm(+ "Do you already have a list of repositories to scan?",+ false,+ );+ let providedInput: string | undefined;+ let repositories: GitHubRepository[] | undefined;+ let githubHost: string | undefined;+ let repositoryNames: string[];++ if (hasRepositoryList) {+ prompt.write(+ "\nEnter the path to a CSV containing id, repository, and revision columns.\n",+ );+ const input = await prompt.input("CSV path");+ if (!input.trim()) throw new Error("A repository CSV path is required.");+ providedInput = resolve(dependencies.currentDirectory(), input.trim());+ const inventory = await inspectMultiscanInventory(providedInput);+ repositoryNames = inventory.repositories;+ } else {+ if (+ !(await prompt.confirm("Are your repositories hosted on GitHub?", true))+ ) {+ prompt.write(+ "\nAutomatic repository discovery currently supports GitHub only. Provide a CSV with id, repository, and revision columns.\n",+ );+ return null;+ }+ const host = await selectGitHubHost(dependencies, signal);+ githubHost = host;+ const owner = await selectGitHubOwner(dependencies, host, signal);+ const selection = await prompt.select(+ "Which repositories do you want to scan?\nNo scan will start until you confirm.",+ [+ {+ label: "Private and internal repositories active in the last 90 days",+ value: "default",+ },+ { label: "Something else", value: "custom" },+ ],+ );+ const filters =+ selection === "default"+ ? DEFAULT_REPOSITORY_FILTERS+ : await selectRepositoryFilters(prompt);+ repositories = await withLoading(+ prompt,+ selection === "default"+ ? "Finding active private and internal repositories..."+ : "Finding repositories that match your filters...",+ async () =>+ await discoverGitHubRepositories(+ dependencies,+ host,+ owner,+ filters,+ signal,+ ),+ );+ if (repositories.length === 0) {+ prompt.write("\nNo repositories matched your selection.\n");+ return null;+ }+ repositoryNames = repositories.map((repository) => repository.fullName);+ }++ prompt.write(`\nFound ${repositoryNames.length} repositories:\n\n`);+ for (const repository of repositoryNames.slice(0, PREVIEW_LIMIT)) {+ prompt.write(` ${repository}\n`);+ }+ if (repositoryNames.length > PREVIEW_LIMIT) {+ prompt.write(`\n and ${repositoryNames.length - PREVIEW_LIMIT} more\n`);+ }++ const selectedOutput = await prompt.input(+ "\nWhere should scan results be saved?",+ "./security-scans",+ );+ const outputDir = resolve(+ dependencies.currentDirectory(),+ selectedOutput.trim() || "./security-scans",+ );+ const inputPath = providedInput ?? join(outputDir, "repositories.csv");+ await validateWizardOutput(outputDir, providedInput === undefined);+ prompt.write(+ `\nReady to scan ${repositoryNames.length} repositories?\n\n` ++ `Results will be saved to:\n\n ${outputDir}\n\n` ++ (providedInput === undefined+ ? `The selected repositories will be saved to:\n\n ${inputPath}\n\n`+ : `Repository list:\n\n ${inputPath}\n\n`),+ );+ if (!(await prompt.confirm("Start scanning?", false))) {+ prompt.write("\nScan canceled.\n");+ return null;+ }+ signal?.throwIfAborted();+ if (repositories !== undefined) {+ await mkdir(outputDir, { recursive: true, mode: 0o700 });+ const rows = repositories.map((repository) => ({+ id: repositoryId(repository.fullName),+ repository: repository.url,+ revision: repository.revision,+ }));+ const identifiers = new Set(rows.map((row) => row.id.toLowerCase()));+ if (identifiers.size !== rows.length) {+ throw new Error("Discovered repositories have conflicting scan IDs.");+ }+ await writeFile(inputPath, `${Papa.unparse(rows)}\n`, {+ flag: "wx",+ mode: 0o600,+ ...(signal === undefined ? {} : { signal }),+ });+ }+ return {+ inputPath,+ outputDir,+ ...(githubHost === undefined ? {} : { githubHost }),+ };+}++async function selectRepositoryFilters(+ prompt: BulkScanPrompt,+): Promise<BulkScanRepositoryFilters> {+ const names = await prompt.input(+ "Repository name contains (comma-separated; leave blank for any)",+ );+ const nameKeywords = [...new Set(names.split(",").map((name) => name.trim()))]+ .filter(Boolean)+ .map((name) => name.toLowerCase());+ if (+ nameKeywords.length > 8 ||+ nameKeywords.some((name) => name.length > 80)+ ) {+ throw new Error(+ "Enter at most eight repository-name keywords of 80 characters or fewer.",+ );+ }++ const activity = await prompt.select(+ "Last repository activity",+ [+ { label: "Last 30 days", value: "30" },+ { label: "Last 90 days", value: "90" },+ { label: "Last 180 days", value: "180" },+ { label: "Last year", value: "365" },+ { label: "Any time", value: "all" },+ ],+ "90",+ );+ const language = await prompt.input("Primary language (leave blank for any)");+ if (language.trim().length > 80) {+ throw new Error("Enter a primary language of 80 characters or fewer.");+ }+ const visibility = await prompt.multiSelect(+ "Repository visibility",+ [+ { label: "Private", value: "PRIVATE" },+ { label: "Internal", value: "INTERNAL" },+ { label: "Public", value: "PUBLIC" },+ ],+ ["PRIVATE", "INTERNAL"],+ );+ if (visibility.length === 0) {+ throw new Error("Select at least one repository visibility.");+ }++ return {+ nameKeywords,+ activeWithinDays: activity === "all" ? null : Number(activity),+ language: language.trim() || null,+ visibility,+ };+}++async function withLoading<Value>(+ prompt: BulkScanPrompt,+ message: string,+ operation: () => Promise<Value>,+): Promise<Value> {+ let frame = 0;+ prompt.write(`\n${SPINNER_FRAMES[frame]} ${message}`);+ const interval = setInterval(() => {+ frame = (frame + 1) % SPINNER_FRAMES.length;+ prompt.write(`\r\u001b[2K${SPINNER_FRAMES[frame]} ${message}`);+ }, 100);+ interval.unref();+ try {+ return await operation();+ } finally {+ clearInterval(interval);+ prompt.write("\r\u001b[2K");+ }+}++async function selectGitHubHost(+ dependencies: BulkScanDiscoveryDependencies,+ signal?: AbortSignal,+): Promise<string> {+ const version = await dependencies.runGitHub(["--version"], { signal });+ requireGitHubSuccess(version, "GitHub CLI could not be started.");+ const authentication = await dependencies.runGitHub(+ ["auth", "status", "--json", "hosts"],+ { signal },+ );+ const hosts = parseAuthenticatedHosts(+ authentication,+ dependencies.githubHost,+ );+ if (hosts.length === 1) return hosts[0]!;+ if (hosts.length > 1) {+ return await dependencies.prompt.select(+ "Which GitHub host should we use?",+ hosts.map((host) => ({ label: host, value: host })),+ );+ }+ dependencies.prompt.write(+ "\nSign in to GitHub to find repositories you can access.\n" ++ "No scan will start until you confirm.\n",+ );+ if (+ !(await dependencies.prompt.confirm("Continue to GitHub sign-in?", false))+ ) {+ throw new Error("GitHub sign-in is required to discover repositories.");+ }+ const login = await dependencies.runGitHub(+ [+ "auth",+ "login",+ ...(dependencies.githubHost === undefined+ ? []+ : ["--hostname", dependencies.githubHost]),+ ],+ { interactive: true, signal },+ );+ requireGitHubSuccess(login, "GitHub sign-in did not complete.");+ const refreshed = await dependencies.runGitHub(+ ["auth", "status", "--json", "hosts"],+ { signal },+ );+ const refreshedHosts = parseAuthenticatedHosts(+ refreshed,+ dependencies.githubHost,+ );+ if (refreshedHosts.length === 0) {+ throw new Error("GitHub sign-in could not be confirmed.");+ }+ if (refreshedHosts.length === 1) return refreshedHosts[0]!;+ return await dependencies.prompt.select(+ "Which GitHub host should we use?",+ refreshedHosts.map((host) => ({ label: host, value: host })),+ );+}++function parseAuthenticatedHosts(+ result: BulkScanCommandResult,+ configuredHost?: string,+): string[] {+ if (result.exitCode !== 0 || !result.stdout.trim()) return [];+ let value: unknown;+ try {+ value = JSON.parse(result.stdout);+ } catch {+ return [];+ }+ const parsed = githubAuthenticationSchema.safeParse(value);+ if (!parsed.success) return [];+ return Object.entries(parsed.data.hosts)+ .filter(+ ([host, accounts]) =>+ (configuredHost === undefined || host === configuredHost) &&+ accounts.some(+ (account) => account.active === true && account.state === "success",+ ),+ )+ .map(([host]) => host)+ .sort();+}++async function selectGitHubOwner(+ dependencies: BulkScanDiscoveryDependencies,+ host: string,+ signal?: AbortSignal,+): Promise<string> {+ const organizations = await dependencies.runGitHub(+ ["api", "user/orgs", "--paginate", "--jq", ".[].login"],+ { host, signal },+ );+ requireGitHubSuccess(+ organizations,+ "GitHub organizations could not be listed. Check your organization access or SSO authorization.",+ );+ const owners = [...new Set(organizations.stdout.split(/\r?\n/u))]+ .map((owner) => owner.trim())+ .filter(Boolean)+ .sort();+ if (owners.some((owner) => !GITHUB_OWNER.test(owner))) {+ throw new Error("GitHub returned an invalid organization name.");+ }+ if (owners.length === 1) {+ dependencies.prompt.write(`\nSearching repositories in ${owners[0]}.\n`);+ return owners[0]!;+ }+ if (owners.length > 1) {+ return await dependencies.prompt.select(+ "Which account or organization should we search?",+ owners.map((owner) => ({ label: owner, value: owner })),+ );+ }+ const user = await dependencies.runGitHub(["api", "user", "--jq", ".login"], {+ host,+ signal,+ });+ requireGitHubSuccess(+ user,+ "The active GitHub account could not be determined.",+ );+ const owner = user.stdout.trim();+ if (!GITHUB_OWNER.test(owner)) {+ throw new Error("GitHub returned an invalid account name.");+ }+ dependencies.prompt.write(`\nSearching repositories in ${owner}.\n`);+ return owner;+}++async function discoverGitHubRepositories(+ dependencies: BulkScanDiscoveryDependencies,+ host: string,+ owner: string,+ filters: BulkScanRepositoryFilters,+ signal?: AbortSignal,+): Promise<GitHubRepository[]> {+ if (!GITHUB_OWNER.test(owner)) {+ throw new Error("GitHub account or organization name is invalid.");+ }+ const repositories: GitHubRepository[] = [];+ const cutoff =+ filters.activeWithinDays === null+ ? null+ : dependencies.now() - filters.activeWithinDays * DAY_MILLISECONDS;+ const privacy = filters.visibility.includes("PUBLIC")+ ? filters.visibility.length === 1+ ? "PUBLIC"+ : undefined+ : "PRIVATE";+ let cursor: string | undefined;++ while (true) {+ signal?.throwIfAborted();+ const response = await dependencies.runGitHub(+ [+ "api",+ "graphql",+ "-f",+ `query=${GITHUB_REPOSITORIES_QUERY}`,+ "-f",+ `owner=${owner}`,+ ...(privacy === undefined ? [] : ["-f", `privacy=${privacy}`]),+ ...(cursor === undefined ? [] : ["-f", `endCursor=${cursor}`]),+ ],+ { host, signal },+ );+ requireGitHubSuccess(response, "GitHub repository discovery failed.");+ const page = parseJson(+ githubOwnerRepositoriesSchema,+ response.stdout,+ "GitHub returned an invalid repository discovery response.",+ );+ if (page.errors?.length || page.data.repositoryOwner === null) {+ throw new Error("GitHub could not list repositories for this account.");+ }++ let reachedActivityCutoff = false;+ const connection = page.data.repositoryOwner.repositories;+ for (const repository of connection.nodes) {+ if (repository === null) continue;+ const pushedAt = Date.parse(repository.pushedAt ?? "");+ if (!Number.isFinite(pushedAt)) continue;+ if (cutoff !== null && pushedAt < cutoff) {+ reachedActivityCutoff = true;+ break;+ }+ const parts = repository.nameWithOwner.split("/");+ if (+ parts.length !== 2 ||+ parts[0]!.toLowerCase() !== owner.toLowerCase() ||+ !GITHUB_NAME.test(parts[1]!) ||+ !filters.visibility.some(+ (visibility) => visibility === repository.visibility,+ ) ||+ repository.isArchived ||+ repository.isFork ||+ repository.isEmpty ||+ repository.defaultBranchRef === null ||+ (filters.nameKeywords.length > 0 &&+ !filters.nameKeywords.some((keyword) =>+ parts[1]!.toLowerCase().includes(keyword),+ )) ||+ (filters.language !== null &&+ repository.primaryLanguage?.name.toLowerCase() !==+ filters.language.toLowerCase())+ ) {+ continue;+ }+ repositories.push({+ fullName: repository.nameWithOwner,+ url: validateRepositoryUrl(repository.url, host),+ revision: repository.defaultBranchRef.target.oid.toLowerCase(),+ });+ }+ if (reachedActivityCutoff || !connection.pageInfo.hasNextPage) break;+ if (connection.pageInfo.endCursor === null) {+ throw new Error(+ "GitHub returned an invalid repository pagination cursor.",+ );+ }+ cursor = connection.pageInfo.endCursor;+ }+ return repositories;+}++function validateRepositoryUrl(value: string, host: string): string {+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ throw new Error("GitHub returned an invalid repository URL.");+ }+ if (+ url.protocol !== "https:" ||+ url.hostname.toLowerCase() !== host.toLowerCase() ||+ url.username ||+ url.password ||+ url.search ||+ url.hash+ ) {+ throw new Error("GitHub returned an unsafe repository URL.");+ }+ url.pathname = url.pathname.replace(/\/$/u, "");+ if (!url.pathname.endsWith(".git")) url.pathname += ".git";+ return url.toString();+}++function repositoryId(fullName: string): string {+ const value = fullName.replace("/", "--");+ if (value.length <= 128) return value;+ const digest = createHash("sha256")+ .update(fullName)+ .digest("hex")+ .slice(0, 16);+ return `${value.slice(0, 111)}-${digest}`;+}++async function validateWizardOutput(+ outputDir: string,+ discovered: boolean,+): Promise<void> {+ const metadata = await lstat(outputDir).catch(+ (error: NodeJS.ErrnoException) => {+ if (error.code === "ENOENT") return undefined;+ throw error;+ },+ );+ if (metadata !== undefined && !metadata.isDirectory()) {+ throw new Error("The scan output must be a real directory.");+ }+ if (!discovered || metadata === undefined) return;+ for (const name of ["repositories.csv", "manifest.json"]) {+ const existing = await lstat(join(outputDir, name)).catch(+ (error: NodeJS.ErrnoException) => {+ if (error.code === "ENOENT") return undefined;+ throw error;+ },+ );+ if (existing !== undefined) {+ throw new Error(+ "The selected output directory already contains a repository list or scan. Choose a new directory or resume the existing scan.",+ );+ }+ }+}++function requireGitHubSuccess(+ result: BulkScanCommandResult,+ message: string,+): void {+ if (result.exitCode === 0) return;+ const detail = result.stderr.trim().split("\n").at(-1);+ throw new Error(detail ? `${message} ${detail}` : message);+}++function parseJson<Schema extends z.ZodType>(+ schema: Schema,+ source: string,+ message: string,+): z.output<Schema> {+ let value: unknown;+ try {+ value = JSON.parse(source);+ } catch {+ throw new Error(message);+ }+ const parsed = schema.safeParse(value);+ if (!parsed.success) throw new Error(message);+ return parsed.data;+}++async function runGitHubCommand(+ executable: string,+ args: readonly string[],+ environment: Record<string, string | undefined>,+ options: { interactive?: boolean; signal?: AbortSignal },+): Promise<BulkScanCommandResult> {+ return await new Promise((resolveCommand, reject) => {+ const command = spawn(executable, [...args], {+ env: environment,+ stdio: options.interactive ? "inherit" : ["ignore", "pipe", "pipe"],+ windowsHide: true,+ ...(options.signal === undefined ? {} : { signal: options.signal }),+ });+ let stdout = "";+ let stderr = "";+ command.stdout?.on("data", (chunk: Buffer) => {+ stdout += chunk.toString("utf8");+ });+ command.stderr?.on("data", (chunk: Buffer) => {+ stderr = `${stderr}${chunk.toString("utf8")}`.slice(-64 * 1024);+ });+ command.once("error", reject);+ command.once("close", (code) => {+ resolveCommand({ exitCode: code ?? 1, stdout, stderr });+ });+ });+}++function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {+ return {+ isInteractive: () => stdin.isTTY === true && output.isTTY === true,+ write: (value) => {+ output.write(value);+ },+ confirm: async (question, defaultValue = false) => {+ const suffix = defaultValue ? "[Y/n]" : "[y/N]";+ for (;;) {+ const response = (await questionInput(output, `${question} ${suffix} `))+ .trim()+ .toLowerCase();+ if (!response) return defaultValue;+ if (["y", "yes"].includes(response)) return true;+ if (["n", "no"].includes(response)) return false;+ output.write("Please answer yes or no.\n");+ }+ },+ input: async (question, defaultValue) => {+ const suffix = defaultValue === undefined ? ": " : ` [${defaultValue}]: `;+ const response = (+ await questionInput(output, `${question}${suffix}`)+ ).trim();+ return response || defaultValue || "";+ },+ select: async (question, options, defaultValue) => {+ if (options.length === 0) {+ throw new Error("No selection options are available.");+ }+ output.write(`\n${question}\n\n`);+ const defaultIndex = options.findIndex(+ (option) => option.value === defaultValue,+ );+ let selected = defaultIndex < 0 ? 0 : defaultIndex;+ const render = (): void => {+ for (let index = 0; index < options.length; index += 1) {+ output.write(+ `\u001b[2K\r${index === selected ? "❯" : " "} ${options[index]!.label}\n`,+ );+ }+ };+ render();+ emitKeypressEvents(stdin);+ const wasRaw = stdin.isRaw;+ stdin.setRawMode(true);+ stdin.resume();+ return await new Promise((resolveSelection, reject) => {+ const cleanup = (): void => {+ stdin.removeListener("keypress", onKeypress);+ stdin.setRawMode(wasRaw === true);+ stdin.pause();+ };+ const onKeypress = (+ _value: string | undefined,+ key: { name?: string; ctrl?: boolean },+ ): void => {+ if (key.ctrl && key.name === "c") {+ cleanup();+ reject(new BulkScanInterruptedError());+ return;+ }+ if (key.name === "return" || key.name === "enter") {+ cleanup();+ output.write("\n");+ resolveSelection(options[selected]!.value);+ return;+ }+ if (key.name !== "up" && key.name !== "down") return;+ selected =+ key.name === "up"+ ? (selected + options.length - 1) % options.length+ : (selected + 1) % options.length;+ output.write(`\u001b[${options.length}A`);+ render();+ };+ stdin.on("keypress", onKeypress);+ });+ },+ multiSelect: async (question, options, defaultValues = []) => {+ if (options.length === 0) {+ throw new Error("No selection options are available.");+ }+ output.write(+ `\n${question}\nUse ↑/↓ to move, Space to toggle, and Enter to confirm.\n\n`,+ );+ let focused = 0;+ const selected = new Set(defaultValues);+ const render = (): void => {+ for (let index = 0; index < options.length; index += 1) {+ const option = options[index]!;+ const cursor = index === focused ? "❯" : " ";+ const checkbox = selected.has(option.value) ? "[x]" : "[ ]";+ output.write(`\u001b[2K\r${cursor} ${checkbox} ${option.label}\n`);+ }+ };+ render();+ emitKeypressEvents(stdin);+ const wasRaw = stdin.isRaw;+ stdin.setRawMode(true);+ stdin.resume();+ return await new Promise((resolveSelection, reject) => {+ const cleanup = (): void => {+ stdin.removeListener("keypress", onKeypress);+ stdin.setRawMode(wasRaw === true);+ stdin.pause();+ };+ const onKeypress = (+ value: string | undefined,+ key: { name?: string; ctrl?: boolean },+ ): void => {+ if (key.ctrl && key.name === "c") {+ cleanup();+ reject(new BulkScanInterruptedError());+ return;+ }+ if (key.name === "return" || key.name === "enter") {+ if (selected.size === 0) {+ output.write("\u0007");+ return;+ }+ cleanup();+ output.write("\n");+ resolveSelection(+ options+ .filter((option) => selected.has(option.value))+ .map((option) => option.value),+ );+ return;+ }+ if (key.name === "space" || value === " ") {+ const option = options[focused]!;+ if (selected.has(option.value)) selected.delete(option.value);+ else selected.add(option.value);+ } else if (key.name === "up" || key.name === "down") {+ focused =+ key.name === "up"+ ? (focused + options.length - 1) % options.length+ : (focused + 1) % options.length;+ } else {+ return;+ }+ output.write(`\u001b[${options.length}A`);+ render();+ };+ stdin.on("keypress", onKeypress);+ });+ },+ };+}++async function questionInput(+ output: PromptOutput,+ question: string,+): Promise<string> {+ const destination = new Writable({+ write(chunk: Buffer, _encoding, callback) {+ try {+ output.write(chunk.toString("utf8"));+ callback();+ } catch (error) {+ callback(error instanceof Error ? error : new Error(String(error)));+ }+ },+ });+ const terminal = createInterface({+ input: stdin,+ output: destination,+ terminal: true,+ });+ try {+ return await terminal.question(question);+ } finally {+ terminal.close();+ }+}diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 1054c1f41..dccb42049 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -27,6 +27,12 @@ import { pathToFileURL } from "node:url";import { Cli, z } from "incur";import { parse as parseToml } from "smol-toml";import { CodexSecurity, type ScanOptions, type ScanPreflight } from "./api.js";+import {+ BulkScanInterruptedError,+ createBulkScanDiscoveryDependencies,+ runBulkScanWizard,+ type BulkScanDiscoveryDependencies,+} from "./bulk-scan-discovery.js";import type { CodexSecurityConfig, JsonObject, JsonValue } from "./config.js";import {CodexSecurityError,@@ -151,6 +157,7 @@ interface CliDependencies {output?: Writable,): Promise<Uint8Array | undefined>;runCodex(args: readonly string[]): Promise<number>;+ bulkScan?: BulkScanDiscoveryDependencies;runWorkbench(args: readonly string[]): Promise<JsonObject>;}@@ -649,17 +656,23 @@ export async function main(},}).command(scanHistory)- .command("scan-csv", {- description: "Run resumable repository scans from a CSV inventory.",+ .command("bulk-scan", {+ description:+ "Discover repositories and run resumable bulk security scans.",destructive: true,mcp: false,args: z.object({- input: z.string().min(1).describe("CSV repository inventory."),+ input: z+ .string()+ .min(1)+ .optional()+ .describe("CSV repository list; omit to discover repositories."),}),options: z.object({outputDir: z.string().min(1, "--output-dir must not be empty.")+ .optional().describe("Directory for scan artifacts and resumable results."),workers: z.number().int().positive().default(4),mode: z.enum(["standard", "deep"]).default("standard"),@@ -688,9 +701,41 @@ export async function main(dependencies.addSignalListener("SIGTERM", onTerminate);try {const currentDirectory = dependencies.currentDirectory();+ let inputPath: string;+ let outputDir: string;+ let githubHost: string | undefined;+ if (args.input === undefined) {+ if (argv.length !== 1 || argv[0] !== "bulk-scan") {+ throw new Error(+ "Run 'codex-security bulk-scan' without options to discover repositories, or provide a CSV and --output-dir.",+ );+ }+ const wizard = await runBulkScanWizard(+ dependencies.bulkScan ??+ createBulkScanDiscoveryDependencies({+ output: errorOutput,+ now: dependencies.now,+ currentDirectory: dependencies.currentDirectory,+ }),+ controller.signal,+ );+ if (wizard === null) return;+ inputPath = wizard.inputPath;+ outputDir = wizard.outputDir;+ githubHost = wizard.githubHost;+ } else {+ if (options.outputDir === undefined) {+ throw new Error(+ "--output-dir is required with a repository CSV.",+ );+ }+ inputPath = resolve(currentDirectory, args.input);+ outputDir = resolve(currentDirectory, options.outputDir);+ }const result = await runMultiscan({- inputPath: resolve(currentDirectory, args.input),- outputDir: resolve(currentDirectory, options.outputDir),+ inputPath,+ outputDir,+ ...(githubHost === undefined ? {} : { githubHost }),workers: options.workers,mode: options.mode,maxAttempts: options.maxAttempts,@@ -710,7 +755,9 @@ export async function main(exitCode = interruptedExitCode() ?? (result.failed > 0 ? 2 : 0);return { ...result };} catch (error) {- exitCode = interruptedExitCode() ?? 2;+ exitCode =+ interruptedExitCode() ??+ (error instanceof BulkScanInterruptedError ? 130 : 2);errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);} finally {dependencies.removeSignalListener("SIGINT", onInterrupt);@@ -1035,8 +1082,8 @@ function validateCliArguments(const commandIndex = argv.findIndex((value) =>["scan",+ "bulk-scan","scans",- "scan-csv","export","validate","patch",diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.tsindex 905debf33..d934d22d2 100644--- a/sdk/typescript/src/multiscan.ts+++ b/sdk/typescript/src/multiscan.ts@@ -45,6 +45,7 @@ interface MultiscanReceipt extends MultiscanTask {export interface MultiscanOptions {inputPath: string;outputDir: string;+ githubHost?: string;workers: number;mode: ScanMode;maxAttempts: number;@@ -69,6 +70,21 @@ export interface MultiscanResult {resultsPath: string;}+export async function inspectMultiscanInventory(+ inputPath: string,+ mode: ScanMode = "standard",+): Promise<{ total: number; repositories: string[] }> {+ const tasks = parseInventory(+ await readFile(inputPath, "utf8"),+ dirname(resolve(inputPath)),+ mode,+ );+ return {+ total: tasks.length,+ repositories: tasks.map((task) => task.id),+ };+}+export async function runMultiscan(options: MultiscanOptions,): Promise<MultiscanResult> {@@ -157,7 +173,12 @@ async function runCampaign(await mkdir(dirname(scanDir), { recursive: true, mode: 0o700 });await rm(checkout, { recursive: true, force: true });await mkdir(checkout, { mode: 0o700 });- await checkoutRevision(task, checkout, options.signal);+ await checkoutRevision(+ task,+ checkout,+ options.signal,+ options.githubHost,+ );if (task.scope !== undefined) {const scoped = await realpath(join(checkout, task.scope));const outside = relative(await realpath(checkout), scoped);@@ -436,6 +457,7 @@ async function checkoutRevision(task: MultiscanTask,path: string,signal?: AbortSignal,+ githubHost?: string,): Promise<void> {const environment = { ...process.env };for (const name of [@@ -460,7 +482,14 @@ async function checkoutRevision(const git = async (...args: string[]): Promise<string> => {const result = await execFile("git",- ["-c", "core.hooksPath=/dev/null", "-C", path, ...args],+ [+ "-c",+ "core.hooksPath=/dev/null",+ ...buildGitHubCredentialArgs(githubHost),+ "-C",+ path,+ ...args,+ ],{ env: command.environment, signal },);return result.stdout.trim();@@ -481,6 +510,28 @@ async function checkoutRevision(}}+export function buildGitHubCredentialArgs(host: string | undefined): string[] {+ if (host === undefined) return [];+ let url: URL;+ try {+ url = new URL(`https://${host}`);+ } catch {+ throw new Error("GitHub credential host is invalid.");+ }+ if (+ url.host !== host.toLowerCase() ||+ url.pathname !== "/" ||+ url.username ||+ url.password ||+ url.search ||+ url.hash+ ) {+ throw new Error("GitHub credential host is invalid.");+ }+ const key = `credential.${url.origin}.helper`;+ return ["-c", `${key}=`, "-c", `${key}=!gh auth git-credential`];+}+function redactError(error: unknown): string {return (error instanceof Error ? error.message : String(error)).replaceAll(diff --git a/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts b/sdk/typescript/tests-ts/bulk-scan-discovery.test.tsnew file mode 100644index 000000000..4bf04dd8c--- /dev/null+++ b/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts@@ -0,0 +1,767 @@+import {+ lstat,+ 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 {+ runBulkScanWizard,+ type BulkScanCommandResult,+ type BulkScanDiscoveryDependencies,+ type BulkScanPrompt,+} from "../src/bulk-scan-discovery.js";++const temporaryDirectories: string[] = [];+const NOW = Date.parse("2026-07-22T12:00:00.000Z");+const REVISION = "0123456789abcdef0123456789abcdef01234567";++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((path) => rm(path, { recursive: true, force: true })),+ );+});++async function temporaryDirectory(): Promise<string> {+ const root = await mkdtemp(join(tmpdir(), "codex-security-bulk-discovery-"));+ temporaryDirectories.push(root);+ return root;+}++class FakePrompt implements BulkScanPrompt {+ public readonly messages: string[] = [];+ public readonly questions: string[] = [];+ public readonly selections: string[] = [];+ public interactive = true;+ public confirms: boolean[] = [];+ public inputs: string[] = [];+ public choices: string[] = [];+ public multiChoices: string[][] = [];++ public isInteractive(): boolean {+ return this.interactive;+ }++ public write(value: string): void {+ this.messages.push(value);+ }++ public async confirm(+ question: string,+ defaultValue = false,+ ): Promise<boolean> {+ this.questions.push(question);+ return this.confirms.shift() ?? defaultValue;+ }++ public async input(question: string, defaultValue?: string): Promise<string> {+ this.questions.push(question);+ return this.inputs.shift() ?? defaultValue ?? "";+ }++ public async select<Value extends string>(+ question: string,+ options: readonly { label: string; value: Value }[],+ defaultValue?: Value,+ ): Promise<Value> {+ this.questions.push(question);+ this.selections.push(...options.map((option) => option.label));+ const selection = this.choices.shift();+ const chosen =+ selection === undefined+ ? options.find((option) => option.value === defaultValue) ?? options[0]+ : options.find((option) => option.value === selection);+ if (chosen === undefined) throw new Error("Unexpected test selection.");+ return chosen.value;+ }++ public async multiSelect<Value extends string>(+ question: string,+ options: readonly { label: string; value: Value }[],+ defaultValues: readonly Value[] = [],+ ): Promise<Value[]> {+ this.questions.push(question);+ this.selections.push(...options.map((option) => option.label));+ const selected = this.multiChoices.shift() ?? defaultValues;+ return options+ .filter((option) => selected.includes(option.value))+ .map((option) => option.value);+ }+}++function success(stdout: string): BulkScanCommandResult {+ return { exitCode: 0, stdout, stderr: "" };+}++function discoveryDependencies(+ root: string,+ options: {+ prompt?: FakePrompt;+ host?: string;+ organizations?: string[];+ repositories?: Array<{+ fullName: string;+ visibility?: "private" | "internal" | "public";+ archived?: boolean;+ fork?: boolean;+ empty?: boolean;+ pushedAt?: string;+ language?: string | null;+ }>;+ authenticated?: boolean;+ } = {},+): {+ dependencies: BulkScanDiscoveryDependencies;+ prompt: FakePrompt;+ commands: Array<{ args: readonly string[]; host?: string }>;+} {+ const prompt = options.prompt ?? new FakePrompt();+ const host = options.host ?? "github.com";+ const repositories = options.repositories ?? [+ { fullName: "acme/payments-api", visibility: "private" as const },+ { fullName: "acme/identity-service", visibility: "internal" as const },+ ];+ const commands: Array<{ args: readonly string[]; host?: string }> = [];+ let authenticated = options.authenticated ?? true;+ const dependencies: BulkScanDiscoveryDependencies = {+ prompt,+ now: () => NOW,+ currentDirectory: () => root,+ ...(options.host === undefined ? {} : { githubHost: host }),+ runGitHub: async (args, commandOptions) => {+ commands.push({+ args,+ ...(commandOptions?.host === undefined+ ? {}+ : { host: commandOptions.host }),+ });+ if (args[0] === "--version") return success("gh version test\n");+ if (args[0] === "auth" && args[1] === "status") {+ return success(+ JSON.stringify({+ hosts: authenticated+ ? { [host]: [{ active: true, state: "success" }] }+ : {},+ }),+ );+ }+ if (args[0] === "auth" && args[1] === "login") {+ authenticated = true;+ return success("");+ }+ if (args[0] === "api" && args[1] === "user/orgs") {+ return success((options.organizations ?? ["acme"]).join("\n"));+ }+ if (args[0] === "api" && args[1] === "user") {+ return success("personal-account\n");+ }+ if (args[0] === "api" && args[1] === "graphql") {+ const query = args.find((argument) => argument.startsWith("query="));+ if (query?.includes("repositoryOwner(login: $owner)")) {+ const cursor = args+ .find((argument) => argument.startsWith("endCursor="))+ ?.slice("endCursor=".length);+ const start = cursor === undefined ? 0 : Number(cursor);+ const page = repositories.slice(start, start + 100);+ const next = start + page.length;+ return success(+ JSON.stringify({+ data: {+ repositoryOwner: {+ repositories: {+ nodes: page.map((repository) => ({+ nameWithOwner: repository.fullName,+ url: `https://${host}/${repository.fullName}`,+ visibility: (+ repository.visibility ?? "private"+ ).toUpperCase(),+ isArchived: repository.archived ?? false,+ isFork: repository.fork ?? false,+ isEmpty: repository.empty ?? false,+ pushedAt: repository.pushedAt ?? "2026-07-20T00:00:00Z",+ primaryLanguage:+ repository.language === undefined ||+ repository.language === null+ ? null+ : { name: repository.language },+ defaultBranchRef: repository.empty+ ? null+ : { target: { oid: REVISION } },+ })),+ pageInfo: {+ hasNextPage: next < repositories.length,+ endCursor:+ next < repositories.length ? String(next) : null,+ },+ },+ },+ },+ }),+ );+ }+ }+ throw new Error(`Unexpected GitHub command: ${args.join(" ")}`);+ },+ };+ return { dependencies, prompt, commands };+}++describe("bulk scan repository discovery", () => {+ test("discovers active private and internal repositories without repository search", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root);+ prompt.confirms = [false, true, true];+ prompt.inputs = ["./security-scans"];++ const result = await runBulkScanWizard(dependencies);++ expect(result).toEqual({+ inputPath: join(root, "security-scans", "repositories.csv"),+ outputDir: join(root, "security-scans"),+ githubHost: "github.com",+ });+ expect(commands.some(({ args }) => args[0] === "search")).toBe(false);+ const graphql = commands.find(+ ({ args }) => args[0] === "api" && args[1] === "graphql",+ )?.args;+ const query = graphql?.find((argument) => argument.startsWith("query="));+ expect(query).toContain("privacy: $privacy");+ expect(graphql).toContain("privacy=PRIVATE");+ expect(query).toContain("isArchived: false");+ expect(query).toContain("isFork: false");+ expect(query).toContain("field: PUSHED_AT");+ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("id,repository,revision");+ expect(csv).toContain(+ `acme--payments-api,https://github.com/acme/payments-api.git,${REVISION}`,+ );+ expect(csv).toContain(+ `acme--identity-service,https://github.com/acme/identity-service.git,${REVISION}`,+ );+ expect(prompt.messages.join("")).toContain("Found 2 repositories");+ expect(prompt.messages.join("")).toContain(+ "Finding active private and internal repositories...",+ );+ expect(prompt.questions).not.toContain(+ "Which account or organization should we search?",+ );+ });++ test("discovers more than 100 active repositories across GitHub pages", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ repositories: Array.from({ length: 151 }, (_value, index) => ({+ fullName: `acme/service-${String(index).padStart(3, "0")}`,+ })),+ });+ prompt.confirms = [false, true, true];++ const result = await runBulkScanWizard(dependencies);++ expect(result).not.toBeNull();+ expect(prompt.messages.join("")).toContain("Found 151 repositories");+ expect(+ commands.filter(({ args }) => args[0] === "api" && args[1] === "graphql"),+ ).toHaveLength(2);+ expect(commands.some(({ args }) => args[0] === "search")).toBe(false);+ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--service-000");+ expect(csv).toContain("acme--service-150");+ });++ test("stops paginating when repositories are older than 90 days", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ repositories: [+ { fullName: "acme/active-service" },+ {+ fullName: "acme/old-service",+ pushedAt: "2026-04-22T00:00:00Z",+ },+ ...Array.from({ length: 100 }, (_value, index) => ({+ fullName: `acme/older-${index}`,+ pushedAt: "2026-04-21T00:00:00Z",+ })),+ ],+ });+ prompt.confirms = [false, true, true];++ const result = await runBulkScanWizard(dependencies);++ expect(result).not.toBeNull();+ expect(prompt.messages.join("")).toContain("Found 1 repositories");+ expect(+ commands.filter(({ args }) => args[0] === "api" && args[1] === "graphql"),+ ).toHaveLength(1);+ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--active-service");+ expect(csv).not.toContain("old-service");+ });++ test("matches any custom repository-name keyword without GitHub search", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ repositories: [+ { fullName: "acme/owl" },+ { fullName: "acme/openai" },+ { fullName: "acme/openai-public", visibility: "public" },+ { fullName: "acme/unrelated-service" },+ ],+ });+ prompt.confirms = [false, true, true];+ prompt.choices = ["custom"];+ prompt.inputs = [" OwL, OPENAI ", "", "./custom-results"];++ const result = await runBulkScanWizard(dependencies);++ expect(result?.outputDir).toBe(join(root, "custom-results"));+ expect(commands.some(({ args }) => args[0] === "search")).toBe(false);+ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--owl");+ expect(csv).toContain("acme--openai");+ expect(csv).not.toContain("openai-public");+ expect(csv).not.toContain("unrelated-service");+ expect(prompt.messages.join("")).toContain(+ "Finding repositories that match your filters...",+ );+ expect(prompt.selections).toContain("Something else");+ expect(prompt.questions).toContain(+ "Repository name contains (comma-separated; leave blank for any)",+ );+ expect(prompt.questions).toContain("Last repository activity");+ expect(prompt.questions).toContain(+ "Primary language (leave blank for any)",+ );+ expect(prompt.questions).toContain("Repository visibility");+ expect(prompt.selections).toContain("Private");+ expect(prompt.selections).toContain("Internal");+ expect(prompt.selections).toContain("Public");+ expect(prompt.questions.join(" ").toLowerCase()).not.toContain("topic");+ expect(prompt.questions.join(" ").toLowerCase()).not.toContain("archived");+ expect(prompt.questions.join(" ").toLowerCase()).not.toContain("fork");+ });++ test("filters repositories by primary language case-insensitively", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt } = discoveryDependencies(root, {+ repositories: [+ { fullName: "acme/python-service", language: "Python" },+ { fullName: "acme/typescript-service", language: "TypeScript" },+ { fullName: "acme/unknown-service" },+ ],+ });+ prompt.confirms = [false, true, true];+ prompt.choices = ["custom"];+ prompt.inputs = ["service", "python", "./python-results"];++ const result = await runBulkScanWizard(dependencies);++ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--python-service");+ expect(csv).not.toContain("typescript-service");+ expect(csv).not.toContain("unknown-service");+ });++ test("orders activity windows chronologically while defaulting to 90 days", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt } = discoveryDependencies(root, {+ repositories: [+ {+ fullName: "acme/active-within-90-days",+ pushedAt: "2026-06-12T00:00:00Z",+ },+ {+ fullName: "acme/older-than-90-days",+ pushedAt: "2026-04-01T00:00:00Z",+ },+ ],+ });+ prompt.confirms = [false, true, true];+ prompt.choices = ["custom"];+ prompt.inputs = ["", "", "./activity-results"];++ const result = await runBulkScanWizard(dependencies);++ const firstActivity = prompt.selections.indexOf("Last 30 days");+ expect(prompt.selections.slice(firstActivity, firstActivity + 5)).toEqual([+ "Last 30 days",+ "Last 90 days",+ "Last 180 days",+ "Last year",+ "Any time",+ ]);+ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--active-within-90-days");+ expect(csv).not.toContain("older-than-90-days");+ });++ test("filters internal repositories without including private repositories", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ repositories: [+ { fullName: "acme/private-service", visibility: "private" },+ { fullName: "acme/internal-service", visibility: "internal" },+ { fullName: "acme/public-service", visibility: "public" },+ ],+ });+ prompt.confirms = [false, true, true];+ prompt.choices = ["custom", "90"];+ prompt.multiChoices = [["INTERNAL"]];+ prompt.inputs = ["", "", "./internal-results"];++ const result = await runBulkScanWizard(dependencies);++ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--internal-service");+ expect(csv).not.toContain("private-service");+ expect(csv).not.toContain("public-service");+ expect(+ commands.find(({ args }) => args[0] === "api" && args[1] === "graphql")+ ?.args,+ ).toContain("privacy=PRIVATE");+ });++ test("filters public repositories and sets GitHub public privacy", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ repositories: [+ { fullName: "acme/private-service", visibility: "private" },+ { fullName: "acme/public-service", visibility: "public" },+ ],+ });+ prompt.confirms = [false, true, true];+ prompt.choices = ["custom", "90"];+ prompt.multiChoices = [["PUBLIC"]];+ prompt.inputs = ["", "", "./public-results"];++ const result = await runBulkScanWizard(dependencies);++ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--public-service");+ expect(csv).not.toContain("private-service");+ expect(+ commands.find(({ args }) => args[0] === "api" && args[1] === "graphql")+ ?.args,+ ).toContain("privacy=PUBLIC");+ });++ test("includes every visibility when all repositories are selected", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ repositories: [+ { fullName: "acme/private-service", visibility: "private" },+ { fullName: "acme/internal-service", visibility: "internal" },+ { fullName: "acme/public-service", visibility: "public" },+ ],+ });+ prompt.confirms = [false, true, true];+ prompt.choices = ["custom", "90"];+ prompt.multiChoices = [["PRIVATE", "INTERNAL", "PUBLIC"]];+ prompt.inputs = ["", "", "./all-results"];++ const result = await runBulkScanWizard(dependencies);++ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--private-service");+ expect(csv).toContain("acme--internal-service");+ expect(csv).toContain("acme--public-service");+ expect(+ commands+ .find(({ args }) => args[0] === "api" && args[1] === "graphql")+ ?.args.some((argument) => argument.startsWith("privacy=")),+ ).toBe(false);+ });++ test("allows private and public visibility to be selected together", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ repositories: [+ { fullName: "acme/private-service", visibility: "private" },+ { fullName: "acme/internal-service", visibility: "internal" },+ { fullName: "acme/public-service", visibility: "public" },+ ],+ });+ prompt.confirms = [false, true, true];+ prompt.choices = ["custom", "90"];+ prompt.multiChoices = [["PRIVATE", "PUBLIC"]];+ prompt.inputs = ["", "", "./mixed-visibility-results"];++ const result = await runBulkScanWizard(dependencies);++ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--private-service");+ expect(csv).toContain("acme--public-service");+ expect(csv).not.toContain("internal-service");+ expect(+ commands+ .find(({ args }) => args[0] === "api" && args[1] === "graphql")+ ?.args.some((argument) => argument.startsWith("privacy=")),+ ).toBe(false);+ });++ test("requires at least one selected repository visibility", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root);+ prompt.confirms = [false, true];+ prompt.choices = ["custom", "90"];+ prompt.multiChoices = [[]];+ prompt.inputs = ["", ""];++ await expect(runBulkScanWizard(dependencies)).rejects.toThrow(+ "Select at least one repository visibility",+ );+ expect(+ commands.some(({ args }) => args[0] === "api" && args[1] === "graphql"),+ ).toBe(false);+ await expect(lstat(join(root, "security-scans"))).rejects.toMatchObject({+ code: "ENOENT",+ });+ });++ test("supports an all-time activity window", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt } = discoveryDependencies(root, {+ repositories: [+ { fullName: "acme/active-service" },+ {+ fullName: "acme/old-service",+ pushedAt: "2024-01-01T00:00:00Z",+ },+ ],+ });+ prompt.confirms = [false, true, true];+ prompt.choices = ["custom", "all"];+ prompt.inputs = ["", "", "./all-time-results"];++ const result = await runBulkScanWizard(dependencies);++ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--active-service");+ expect(csv).toContain("acme--old-service");+ });++ test("rejects an excessive number of name keywords before discovery", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root);+ prompt.confirms = [false, true];+ prompt.choices = ["custom"];+ prompt.inputs = ["one,two,three,four,five,six,seven,eight,nine"];++ await expect(runBulkScanWizard(dependencies)).rejects.toThrow(+ "at most eight repository-name keywords",+ );+ expect(+ commands.some(({ args }) => args[0] === "api" && args[1] === "graphql"),+ ).toBe(false);+ });++ test("honors a configured GitHub Enterprise host", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ host: "github.acme.example",+ });+ prompt.confirms = [false, true, true];++ const result = await runBulkScanWizard(dependencies);++ expect(result).not.toBeNull();+ expect(result?.githubHost).toBe("github.acme.example");+ expect(+ commands+ .filter(({ args }) => args[0] === "api" || args[0] === "search")+ .every((call) => call.host === "github.acme.example"),+ ).toBe(true);+ expect(await readFile(result!.inputPath, "utf8")).toContain(+ "https://github.acme.example/acme/payments-api.git",+ );+ });++ test("confirms GitHub sign-in before discovering repositories", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ authenticated: false,+ });+ prompt.confirms = [false, true, true, true];++ expect(await runBulkScanWizard(dependencies)).not.toBeNull();+ expect(prompt.questions).toContain("Continue to GitHub sign-in?");+ expect(+ commands.find(({ args }) => args[0] === "auth" && args[1] === "login")+ ?.args,+ ).toEqual(["auth", "login"]);+ expect(prompt.messages.join("")).toContain(+ "Sign in to GitHub to find repositories you can access.",+ );+ });++ test("preserves a configured enterprise hostname during GitHub sign-in", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ authenticated: false,+ host: "github.acme.example",+ });+ prompt.confirms = [false, true, true, true];++ expect(await runBulkScanWizard(dependencies)).not.toBeNull();+ expect(+ commands.find(({ args }) => args[0] === "auth" && args[1] === "login")+ ?.args,+ ).toEqual(["auth", "login", "--hostname", "github.acme.example"]);+ });++ test("does not search GitHub when sign-in is declined", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root, {+ authenticated: false,+ });+ prompt.confirms = [false, true, false];++ await expect(runBulkScanWizard(dependencies)).rejects.toThrow(+ "GitHub sign-in is required",+ );+ expect(commands.some(({ args }) => args[0] === "search")).toBe(false);+ await expect(lstat(join(root, "security-scans"))).rejects.toMatchObject({+ code: "ENOENT",+ });+ });++ test("leaves non-GitHub repository discovery unsupported", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root);+ prompt.confirms = [false, false];++ expect(await runBulkScanWizard(dependencies)).toBeNull();+ expect(prompt.messages.join("")).toContain("supports GitHub only");+ expect(commands).toEqual([]);+ });++ test("asks for an owner only when several organizations are available", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt } = discoveryDependencies(root, {+ organizations: ["acme", "acme-labs"],+ });+ prompt.confirms = [false, true, true];+ prompt.choices = ["acme", "default"];++ await runBulkScanWizard(dependencies);++ expect(prompt.questions).toContain(+ "Which account or organization should we search?",+ );+ expect(prompt.selections).toContain("acme");+ expect(prompt.selections).toContain("acme-labs");+ });++ test("always excludes archived, forked, and empty repositories", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt } = discoveryDependencies(root, {+ repositories: [+ { fullName: "acme/payments-api" },+ { fullName: "acme/archive", archived: true },+ { fullName: "acme/fork", fork: true },+ { fullName: "acme/empty", empty: true },+ { fullName: "another-owner/service" },+ ],+ });+ prompt.confirms = [false, true, true];++ const result = await runBulkScanWizard(dependencies);++ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("acme--payments-api");+ expect(csv).not.toContain("archive");+ expect(csv).not.toContain("fork");+ expect(csv).not.toContain("empty");+ expect(csv).not.toContain("another-owner");+ });++ test("validates an existing CSV without using GitHub discovery", async () => {+ const root = await temporaryDirectory();+ const input = join(root, "existing.csv");+ await writeFile(+ input,+ `id,repository,revision\nservice,https://github.com/acme/service.git,${REVISION}\n`,+ );+ const { dependencies, prompt, commands } = discoveryDependencies(root);+ prompt.confirms = [true, true];+ prompt.inputs = ["existing.csv", "./existing-results"];++ expect(await runBulkScanWizard(dependencies)).toEqual({+ inputPath: input,+ outputDir: join(root, "existing-results"),+ });+ expect(commands).toEqual([]);+ });++ test("does not create a repository list when confirmation is declined", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt } = discoveryDependencies(root);+ prompt.confirms = [false, true, false];++ expect(await runBulkScanWizard(dependencies)).toBeNull();+ await expect(lstat(join(root, "security-scans"))).rejects.toMatchObject({+ code: "ENOENT",+ });+ expect(prompt.messages.join("")).toContain("Scan canceled.");+ });++ test("does not create a repository list when no repositories match", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt } = discoveryDependencies(root, {+ repositories: [],+ });+ prompt.confirms = [false, true];++ expect(await runBulkScanWizard(dependencies)).toBeNull();+ await expect(lstat(join(root, "security-scans"))).rejects.toMatchObject({+ code: "ENOENT",+ });+ expect(prompt.messages.join("")).toContain("No repositories matched");+ });++ test("rejects an existing scan instead of replacing its repository list", async () => {+ const root = await temporaryDirectory();+ const output = join(root, "existing-results");+ const existing = join(output, "repositories.csv");+ await mkdir(output, { recursive: true });+ await writeFile(existing, "do not overwrite\n");+ const { dependencies, prompt } = discoveryDependencies(root);+ prompt.confirms = [false, true];+ prompt.inputs = ["./existing-results"];++ await expect(runBulkScanWizard(dependencies)).rejects.toThrow(+ "already contains a repository list or scan",+ );+ expect(await readFile(existing, "utf8")).toBe("do not overwrite\n");+ });++ test("rejects interactive discovery without a terminal", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root);+ prompt.interactive = false;++ await expect(runBulkScanWizard(dependencies)).rejects.toThrow(+ "requires a terminal",+ );+ expect(commands).toEqual([]);+ });++ test("honors cancellation before prompting or starting discovery", async () => {+ const root = await temporaryDirectory();+ const { dependencies, prompt, commands } = discoveryDependencies(root);+ const controller = new AbortController();+ controller.abort();++ await expect(+ runBulkScanWizard(dependencies, controller.signal),+ ).rejects.toThrow();+ expect(prompt.questions).toEqual([]);+ expect(commands).toEqual([]);+ });+});diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex 0da06ba5e..8ef7f9714 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -291,6 +291,7 @@ function dependencies(onInterrupt?: () => void;onClose?: () => void | Promise<void>;onCodex?: (args: readonly string[]) => number;+ bulkScan?: MainDependencies["bulkScan"];onWorkbench?: (args: readonly string[]) => JsonObject | Promise<JsonObject>;currentDirectory?: string;preflight?: ScanPreflight;@@ -342,6 +343,7 @@ function dependencies(writeSynchronously: (stream, value) => stream.write(value),forceExit: () => {},runCodex: async (args) => options.onCodex?.(args) ?? 0,+ ...(options.bulkScan === undefined ? {} : { bulkScan: options.bulkScan }),runWorkbench: async (args) =>(await options.onWorkbench?.(args)) ?? { scans: [] },exportFindings: async (arguments_) => {@@ -373,7 +375,7 @@ describe("CLI", () => {const stderr = capture();expect(await main([], root.stream, stderr.stream, dependencies())).toBe(0);expect(root.text()).toContain("Usage: codex-security <command>");- expect(root.text()).toContain("scan-csv");+ expect(root.text()).toContain("bulk-scan");expect(root.text()).not.toContain("multiscan");expect(root.text()).toContain("Integrations:");expect(root.text()).toContain("completions");@@ -405,7 +407,7 @@ describe("CLI", () => {await main(["--llms"], manifest.stream, capture().stream, dependencies()),).toBe(0);expect(manifest.text()).toContain("codex-security scan [repository]");- expect(manifest.text()).toContain("codex-security scan-csv <input>");+ expect(manifest.text()).toContain("codex-security bulk-scan [input]");expect(manifest.text()).toContain("codex-security export <scanDir>");expect(manifest.text()).toContain("codex-security validate <findings...>");expect(manifest.text()).toContain("codex-security patch <issues...>");@@ -429,7 +431,7 @@ describe("CLI", () => {expect(completions.text()).toContain('export COMPLETE="bash"');});- test("runs scan-csv and keeps structured output on stdout", async () => {+ test("runs a bulk scan and keeps structured output on stdout", async () => {const root = await mkdtemp(join(tmpdir(), "codex-security-cli-multiscan-"));try {await multiscanInventory(root);@@ -440,7 +442,7 @@ describe("CLI", () => {expect(await main([- "scan-csv",+ "bulk-scan","repositories.csv","--output-dir","results",@@ -477,7 +479,7 @@ describe("CLI", () => {}});- test("preserves the scan-csv failure summary and redacts progress errors", async () => {+ test("preserves the bulk-scan failure summary and redacts progress errors", async () => {const root = await mkdtemp(join(tmpdir(), "codex-security-cli-multiscan-"));try {await multiscanInventory(root);@@ -485,7 +487,13 @@ describe("CLI", () => {const stderr = capture();expect(await main(- ["scan-csv", "repositories.csv", "--output-dir", "results", "--json"],+ [+ "bulk-scan",+ "repositories.csv",+ "--output-dir",+ "results",+ "--json",+ ],stdout.stream,stderr.stream,dependencies({@@ -512,6 +520,84 @@ describe("CLI", () => {}});+ test("requires a terminal for a bulk scan without a repository list", async () => {+ const stdout = capture();+ const stderr = capture();+ let started = false;++ expect(+ await main(+ ["bulk-scan"],+ stdout.stream,+ stderr.stream,+ dependencies({ onRun: () => (started = true) }),+ ),+ ).toBe(2);+ expect(started).toBe(false);+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toContain("requires a terminal");+ });++ test("requires an output directory for a supplied bulk scan CSV", async () => {+ const stdout = capture();+ const stderr = capture();++ expect(+ await main(+ ["bulk-scan", "repositories.csv"],+ stdout.stream,+ stderr.stream,+ dependencies(),+ ),+ ).toBe(2);+ expect(stderr.text()).toContain("--output-dir is required");+ expect(stdout.text()).toBe("");+ });++ test("starts an existing-CSV bulk scan after interactive confirmation", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-cli-bulk-scan-"));+ try {+ await multiscanInventory(root);+ const stdout = capture();+ const stderr = capture();+ const confirmations = [true, true];+ const answers = ["repositories.csv", "results"];+ const wizard: NonNullable<MainDependencies["bulkScan"]> = {+ prompt: {+ isInteractive: () => true,+ write: (value) => {+ stderr.stream.write(value);+ },+ confirm: async () => confirmations.shift() ?? false,+ input: async () => answers.shift() ?? "",+ select: async (_question, options) => options[0]!.value,+ multiSelect: async (_question, _options, defaults = []) => [+ ...defaults,+ ],+ },+ now: () => 0,+ currentDirectory: () => root,+ runGitHub: async () => {+ throw new Error("GitHub should not run for an existing CSV.");+ },+ };++ expect(+ await main(+ ["bulk-scan"],+ stdout.stream,+ stderr.stream,+ dependencies({ currentDirectory: root, bulkScan: wizard }),+ ),+ ).toBe(0);+ expect(stdout.text()).toContain("completed");+ expect(stderr.text()).toContain("sample started (attempt 1)");+ expect(stderr.text()).toContain("sample completed (attempt 1)");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+test("exposes only typed, read-only SDK metadata over MCP", () => {const child = spawnSync(process.execPath,diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.tsindex b8cfbed65..d57449cee 100644--- a/sdk/typescript/tests-ts/multiscan.test.ts+++ b/sdk/typescript/tests-ts/multiscan.test.ts@@ -14,7 +14,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, test } from "bun:test";import type { ScanResult } from "../src/result.js";-import { runMultiscan } from "../src/multiscan.js";+import { buildGitHubCredentialArgs, runMultiscan } from "../src/multiscan.js";type MultiscanOptions = Parameters<typeof runMultiscan>[0];type SecurityClient = ReturnType<MultiscanOptions["createSecurity"]>;@@ -120,6 +120,65 @@ async function results(path: string): Promise<Record<string, unknown>[]> {}describe("multiscan", () => {+ test("scopes GitHub CLI credentials to the discovered GitHub host", () => {+ expect(buildGitHubCredentialArgs(undefined)).toEqual([]);+ expect(buildGitHubCredentialArgs("github.com")).toEqual([+ "-c",+ "credential.https://github.com.helper=",+ "-c",+ "credential.https://github.com.helper=!gh auth git-credential",+ ]);+ expect(buildGitHubCredentialArgs("github.acme.example")).toEqual([+ "-c",+ "credential.https://github.acme.example.helper=",+ "-c",+ "credential.https://github.acme.example.helper=!gh auth git-credential",+ ]);+ for (const host of [+ "github.com/another-owner",+ "[email protected]",+ "github.com?token=secret",+ "github.com#fragment",+ ]) {+ expect(() => buildGitHubCredentialArgs(host)).toThrow(+ "GitHub credential host is invalid",+ );+ }+ });++ test("uses GitHub credentials for discovered checkouts without changing global Git configuration", async () => {+ const paths = await fixture();+ const source = await repository(paths.root, "github-credentials");+ await writeFile(+ paths.input,+ `id,repository,revision\nprivate,${source.path},${source.revision}\n`,+ );+ const configured = execFileSync(+ "git",+ [+ ...buildGitHubCredentialArgs("github.acme.example"),+ "config",+ "--get-all",+ "credential.https://github.acme.example.helper",+ ],+ { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },+ );+ expect(configured.trim()).toBe("!gh auth git-credential");++ const summary = await runMultiscan(+ options(+ paths,+ client(+ async (_checkout, scanOptions = {}) =>+ await completedScan(scanOptions.outputDir!),+ ),+ { githubHost: "github.acme.example" },+ ),+ );++ expect(summary).toMatchObject({ total: 1, completed: 1, failed: 0 });+ });+test("parses quoted CSV fields, embedded delimiters, and Windows line endings", async () => {const paths = await fixture();const source = await repository(paths.root, "comma, quoted");