@openai/codex-security 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +72 -41
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/.mcp.json +5 -1
  4. package/_bundled_plugin/examples/completed-scan/coverage.json +1 -1
  5. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +2 -2
  6. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  7. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  8. package/_bundled_plugin/preflight/capability-profiles.toml +1 -34
  9. package/_bundled_plugin/references/config-preflight.md +11 -13
  10. package/_bundled_plugin/references/core-scan.md +94 -0
  11. package/_bundled_plugin/references/final-report.md +6 -6
  12. package/_bundled_plugin/references/scan-artifacts.md +15 -14
  13. package/_bundled_plugin/references/scan-prologue.md +27 -0
  14. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +1 -106
  15. package/_bundled_plugin/scripts/config_preflight.py +40 -3
  16. package/_bundled_plugin/scripts/deep_scan_config.py +29 -6
  17. package/_bundled_plugin/scripts/deep_scan_workbench.py +132 -34
  18. package/_bundled_plugin/scripts/finalize_scan_contract.py +44 -224
  19. package/_bundled_plugin/scripts/finding_preview.py +122 -6
  20. package/_bundled_plugin/scripts/generate_in_scope_files.py +77 -31
  21. package/_bundled_plugin/scripts/generate_rank_input.py +58 -7
  22. package/_bundled_plugin/scripts/normalize_candidates.py +5 -5
  23. package/_bundled_plugin/scripts/rank_preview.py +4 -0
  24. package/_bundled_plugin/scripts/report_projection.py +40 -20
  25. package/_bundled_plugin/scripts/workbench_cli.py +5 -0
  26. package/_bundled_plugin/scripts/workbench_db.py +304 -32
  27. package/_bundled_plugin/scripts/workbench_progress.py +0 -5
  28. package/_bundled_plugin/scripts/workbench_scan_usage.py +43 -8
  29. package/_bundled_plugin/scripts/workbench_schema.py +16 -20
  30. package/_bundled_plugin/scripts/workbench_source_excerpt.py +1 -5
  31. package/_bundled_plugin/scripts/workbench_target.py +82 -0
  32. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +8 -11
  33. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +24 -108
  34. package/_bundled_plugin/skills/security-scan/SKILL.md +5 -88
  35. package/_bundled_plugin/skills/threat-model/SKILL.md +4 -2
  36. package/_bundled_plugin/skills/track-findings/SKILL.md +1 -1
  37. package/_bundled_plugin/skills/triage-finding/SKILL.md +5 -6
  38. package/_bundled_plugin/skills/triage-finding/references/github-rest-intake.md +6 -7
  39. package/_bundled_plugin/skills/validation/SKILL.md +9 -12
  40. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +3 -2
  41. package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +1 -1
  42. package/dist/api.d.ts +2 -0
  43. package/dist/api.d.ts.map +1 -1
  44. package/dist/api.js +393 -145
  45. package/dist/api.js.map +1 -1
  46. package/dist/auth.d.ts +2 -3
  47. package/dist/auth.d.ts.map +1 -1
  48. package/dist/auth.js +59 -270
  49. package/dist/auth.js.map +1 -1
  50. package/dist/bulk-scan-discovery.js +14 -2
  51. package/dist/bulk-scan-discovery.js.map +1 -1
  52. package/dist/cli.d.ts +6 -3
  53. package/dist/cli.d.ts.map +1 -1
  54. package/dist/cli.js +202 -46
  55. package/dist/cli.js.map +1 -1
  56. package/dist/config.d.ts.map +1 -1
  57. package/dist/config.js +1 -0
  58. package/dist/config.js.map +1 -1
  59. package/dist/contract.js +7 -5
  60. package/dist/contract.js.map +1 -1
  61. package/dist/cost.d.ts +1 -0
  62. package/dist/cost.d.ts.map +1 -1
  63. package/dist/cost.js +33 -2
  64. package/dist/cost.js.map +1 -1
  65. package/dist/knowledge-base.d.ts.map +1 -1
  66. package/dist/knowledge-base.js +12 -4
  67. package/dist/knowledge-base.js.map +1 -1
  68. package/dist/multiscan.d.ts +1 -0
  69. package/dist/multiscan.d.ts.map +1 -1
  70. package/dist/multiscan.js +77 -17
  71. package/dist/multiscan.js.map +1 -1
  72. package/dist/runtime.d.ts +9 -6
  73. package/dist/runtime.d.ts.map +1 -1
  74. package/dist/runtime.js +140 -326
  75. package/dist/runtime.js.map +1 -1
  76. package/dist/scan-comparison.js +1 -1
  77. package/dist/scan-comparison.js.map +1 -1
  78. package/dist/scan-dashboard.d.ts +5 -1
  79. package/dist/scan-dashboard.d.ts.map +1 -1
  80. package/dist/scan-dashboard.js +65 -16
  81. package/dist/scan-dashboard.js.map +1 -1
  82. package/dist/scan-logs.d.ts +2 -0
  83. package/dist/scan-logs.d.ts.map +1 -1
  84. package/dist/scan-logs.js +97 -37
  85. package/dist/scan-logs.js.map +1 -1
  86. package/dist/targets.d.ts +1 -0
  87. package/dist/targets.d.ts.map +1 -1
  88. package/dist/targets.js +35 -4
  89. package/dist/targets.js.map +1 -1
  90. package/dist/trusted-executable.js +1 -1
  91. package/dist/trusted-executable.js.map +1 -1
  92. package/dist/version.d.ts +3 -3
  93. package/dist/version.d.ts.map +1 -1
  94. package/dist/version.js +6 -4
  95. package/dist/version.js.map +1 -1
  96. package/package.json +4 -4
  97. package/_bundled_plugin/references/shared-hard-rules.md +0 -15
  98. package/_bundled_plugin/scripts/validate_report_format.py +0 -138
  99. package/_bundled_plugin/skills/security-scan/references/repository-wide-scan.md +0 -33
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-scan-discovery.js","sourceRoot":"","sources":["../src/bulk-scan-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;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AAC;IAEH,OAAO;QACL,aAAa,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI;QAClE,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE;YACf,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;QACD,OAAO,EAAE,CAAC,OAAO,EAAE,YAAY,GAAG,KAAK,EAAE,EAAE,CACzC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC;QACxD,KAAK,EAAE,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,CAC/B,KAAK,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC;QACtD,MAAM,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAC3B,MAAM,CACJ;YACE,OAAO;YACP,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CACf,OAAO;iBACJ,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CACpB,KAAK,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CACxD;iBACA,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;SACzD,EACD,OAAO,EAAE,CACV;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import { execFile as execFileCallback } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { lstat, mkdir, writeFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { stdin } from \"node:process\";\nimport { Writable } from \"node:stream\";\nimport { promisify } from \"node:util\";\nimport { confirm, input, search } from \"@inquirer/prompts\";\nimport { Octokit } from \"@octokit/core\";\nimport Papa from \"papaparse\";\nimport { resolveTrustedExecutable } from \"./trusted-executable.js\";\n\nconst execFile = promisify(execFileCallback);\nconst GITHUB_REPOSITORIES_QUERY = `\n query($owner: String!, $cursor: String) {\n repositoryOwner(login: $owner) {\n repositories(\n first: 100\n after: $cursor\n isArchived: false\n isFork: false\n orderBy: { field: PUSHED_AT, direction: DESC }\n ) {\n nodes {\n nameWithOwner\n pushedAt\n defaultBranchRef { target { oid } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }\n }\n`;\n\ninterface GitHubRepository {\n fullName: string;\n url: string;\n revision: string;\n}\n\ninterface GitHubRepositoriesResponse {\n repositoryOwner: {\n repositories: {\n nodes: Array<{\n nameWithOwner: string;\n pushedAt: string;\n defaultBranchRef: { target: { oid: string } } | null;\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n } | null;\n}\n\nexport interface BulkScanPrompt {\n isInteractive(): boolean;\n write(value: string): void;\n confirm(question: string, defaultValue?: boolean): Promise<boolean>;\n input(question: string, defaultValue?: string): Promise<string>;\n select<Value extends string>(\n question: string,\n options: readonly { label: string; value: Value }[],\n ): Promise<Value>;\n}\n\nexport interface BulkScanDiscoveryDependencies {\n prompt: BulkScanPrompt;\n now(): number;\n currentDirectory(): string;\n githubHost?: string;\n createGitHub(host: string, signal?: AbortSignal): Promise<Octokit>;\n}\n\nexport interface BulkScanWizardResult {\n inputPath: string;\n outputDir: string;\n githubHost: string;\n}\n\ninterface PromptOutput {\n write(value: string): unknown;\n readonly isTTY?: boolean;\n}\n\nexport function createBulkScanDiscoveryDependencies(options: {\n output: PromptOutput;\n now(): number;\n currentDirectory(): string;\n}): BulkScanDiscoveryDependencies {\n return {\n prompt: createTerminalPrompt(options.output),\n now: options.now,\n currentDirectory: options.currentDirectory,\n ...(process.env[\"GH_HOST\"]?.trim()\n ? { githubHost: process.env[\"GH_HOST\"].trim() }\n : {}),\n createGitHub: async (host, signal) => {\n const trusted = await resolveTrustedExecutable(\n \"gh\",\n process.env,\n options.currentDirectory(),\n );\n if (trusted === null) {\n throw new Error(\n \"GitHub CLI is required. Install gh and sign in first.\",\n );\n }\n\n let token: string;\n try {\n const { stdout } = await execFile(\n trusted.executable,\n [\"auth\", \"token\", \"--hostname\", host],\n { env: trusted.environment, signal },\n );\n token = stdout.trim();\n } catch {\n signal?.throwIfAborted();\n throw new Error(\n \"GitHub sign-in is required. Run 'gh auth login' first.\",\n );\n }\n return new Octokit({\n auth: token,\n ...(host === \"github.com\" ? {} : { baseUrl: `https://${host}/api/v3` }),\n });\n },\n };\n}\n\nexport async function runBulkScanWizard(\n dependencies: BulkScanDiscoveryDependencies,\n signal?: AbortSignal,\n): Promise<BulkScanWizardResult | null> {\n const { prompt } = dependencies;\n if (!prompt.isInteractive()) {\n throw new Error(\n \"Interactive repository selection requires a terminal. Provide a CSV with 'codex-security bulk-scan repositories.csv --output-dir ./security-scans'.\",\n );\n }\n signal?.throwIfAborted();\n\n const githubHost = dependencies.githubHost ?? \"github.com\";\n const github = await dependencies.createGitHub(githubHost, signal);\n const owner = await selectGitHubOwner(github, prompt, signal);\n prompt.write(\"\\nFinding active repositories...\\n\");\n const discovered = await discoverGitHubRepositories(\n github,\n githubHost,\n owner,\n dependencies.now() - 90 * 86_400_000,\n signal,\n );\n if (discovered.length === 0) {\n prompt.write(\"\\nNo repositories matched your selection.\\n\");\n return null;\n }\n\n prompt.write(`\\nFound ${discovered.length} repositories.\\n`);\n const repositories = await selectGitHubRepositories(discovered, prompt);\n\n const outputDir = resolve(\n dependencies.currentDirectory(),\n await prompt.input(\n \"Where should scan results be saved?\",\n \"./security-scans\",\n ),\n );\n const inputPath = join(outputDir, \"repositories.csv\");\n await validateWizardOutput(outputDir);\n prompt.write(\n `\\nReady to scan ${repositories.length} repositories?\\n` +\n `Results: ${outputDir}\\nRepository list: ${inputPath}\\n`,\n );\n if (!(await prompt.confirm(\"Start scanning?\"))) {\n prompt.write(\"\\nScan canceled.\\n\");\n return null;\n }\n signal?.throwIfAborted();\n\n await mkdir(outputDir, { recursive: true, mode: 0o700 });\n await writeFile(\n inputPath,\n `${Papa.unparse(\n repositories.map(({ fullName, url, revision }) => ({\n id: repositoryId(fullName),\n repository: url,\n revision,\n })),\n )}\\n`,\n { flag: \"wx\", mode: 0o600, ...(signal === undefined ? {} : { signal }) },\n );\n return { inputPath, outputDir, githubHost };\n}\n\nasync function selectGitHubOwner(\n github: Octokit,\n prompt: BulkScanPrompt,\n signal?: AbortSignal,\n): Promise<string> {\n const [orgs, user] = await Promise.all([\n github.request(\"GET /user/orgs\", { per_page: 100, request: { signal } }),\n github.request(\"GET /user\", { request: { signal } }),\n ]);\n const personal = user.data.login;\n const owners = [personal, ...orgs.data.map(({ login }) => login)].sort();\n if (owners.length > 1) {\n return await prompt.select(\n \"Which account or organization should we scan?\",\n owners.map((owner) => ({ label: owner, value: owner })),\n );\n }\n prompt.write(`\\nFinding repositories in ${personal}.\\n`);\n return personal;\n}\n\nasync function selectGitHubRepositories(\n repositories: GitHubRepository[],\n prompt: BulkScanPrompt,\n): Promise<GitHubRepository[]> {\n const selected = new Set<string>();\n while (selected.size < repositories.length) {\n const choice = await prompt.select(\n \"Select repositories to scan (type to filter)\",\n [\n {\n label: selected.size\n ? `Done (${selected.size} selected)`\n : `All ${repositories.length} repositories`,\n value: \"\",\n },\n ...repositories\n .filter(({ fullName }) => !selected.has(fullName))\n .map(({ fullName }) => ({ label: fullName, value: fullName })),\n ],\n );\n if (!choice) break;\n selected.add(choice);\n }\n return selected.size\n ? repositories.filter(({ fullName }) => selected.has(fullName))\n : repositories;\n}\n\nasync function discoverGitHubRepositories(\n github: Octokit,\n host: string,\n owner: string,\n cutoff: number,\n signal?: AbortSignal,\n): Promise<GitHubRepository[]> {\n const repositories: GitHubRepository[] = [];\n let cursor: string | null = null;\n\n do {\n signal?.throwIfAborted();\n const result: GitHubRepositoriesResponse = await github.graphql(\n GITHUB_REPOSITORIES_QUERY,\n { owner, cursor, request: { signal } },\n );\n const connection = result.repositoryOwner?.repositories;\n if (connection === undefined) {\n throw new Error(\"GitHub could not list repositories for this account.\");\n }\n\n for (const repository of connection.nodes) {\n if (Date.parse(repository.pushedAt) < cutoff) return repositories;\n if (repository.defaultBranchRef === null) continue;\n repositories.push({\n fullName: repository.nameWithOwner,\n url: `https://${host}/${repository.nameWithOwner}.git`,\n revision: repository.defaultBranchRef.target.oid.toLowerCase(),\n });\n }\n cursor = connection.pageInfo.hasNextPage\n ? connection.pageInfo.endCursor\n : null;\n } while (cursor !== null);\n\n return repositories;\n}\n\nfunction repositoryId(fullName: string): string {\n const id = fullName.replace(\"/\", \"--\");\n if (id.length <= 128) return id;\n const hash = createHash(\"sha256\").update(fullName).digest(\"hex\").slice(0, 16);\n return `${id.slice(0, 111)}-${hash}`;\n}\n\nasync function validateWizardOutput(outputDir: string): Promise<void> {\n let metadata;\n try {\n metadata = await lstat(outputDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n if (!metadata.isDirectory()) {\n throw new Error(\"The scan output must be a real directory.\");\n }\n\n for (const name of [\"repositories.csv\", \"manifest.json\"]) {\n try {\n await lstat(join(outputDir, name));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw error;\n }\n throw new Error(\n \"The selected output directory already contains a repository list or scan. Choose a new directory or resume the existing scan.\",\n );\n }\n}\n\nfunction createTerminalPrompt(output: PromptOutput): BulkScanPrompt {\n const context = () => ({\n input: stdin,\n output: new Writable({\n write(chunk: Buffer, _encoding, callback) {\n output.write(chunk.toString(\"utf8\"));\n callback();\n },\n }),\n });\n\n return {\n isInteractive: () => stdin.isTTY === true && output.isTTY === true,\n write: (value) => {\n output.write(value);\n },\n confirm: (message, defaultValue = false) =>\n confirm({ message, default: defaultValue }, context()),\n input: (message, defaultValue) =>\n input({ message, default: defaultValue }, context()),\n select: (message, options) =>\n search(\n {\n message,\n source: (term) =>\n options\n .filter(({ label }) =>\n label.toLowerCase().includes(term?.toLowerCase() ?? \"\"),\n )\n .map(({ label, value }) => ({ name: label, value })),\n },\n context(),\n ),\n };\n}\n"]}
1
+ {"version":3,"file":"bulk-scan-discovery.js","sourceRoot":"","sources":["../src/bulk-scan-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,MAAM,QAAQ,GAAG,SAAS,CAAC,gBAAgB,CAAC,CAAC;AAC7C,MAAM,yBAAyB,GAAG;;;;;;;;;;;;;;;;;;;CAmBjC,CAAC;AAmDF,MAAM,UAAU,mCAAmC,CAAC,OAInD;IACC,OAAO;QACL,MAAM,EAAE,oBAAoB,CAAC,OAAO,CAAC,MAAM,CAAC;QAC5C,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,gBAAgB,EAAE,OAAO,CAAC,gBAAgB;QAC1C,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE;YAChC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE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AAE,CACzC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC;QACxD,KAAK,EAAE,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,CAC/B,KAAK,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC;QACtD,MAAM,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAC3B,MAAM,CACJ;YACE,OAAO;YACP,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CACf,OAAO;iBACJ,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CACpB,KAAK,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CACxD;iBACA,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;SACzD,EACD,OAAO,EAAE,CACV;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import { execFile as execFileCallback } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { lstat, mkdir, writeFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { stdin } from \"node:process\";\nimport { Writable } from \"node:stream\";\nimport { promisify } from \"node:util\";\nimport { confirm, input, search } from \"@inquirer/prompts\";\nimport { Octokit } from \"@octokit/core\";\nimport Papa from \"papaparse\";\nimport { resolveTrustedExecutable } from \"./trusted-executable.js\";\n\nconst execFile = promisify(execFileCallback);\nconst GITHUB_REPOSITORIES_QUERY = `\n query($owner: String!, $cursor: String) {\n repositoryOwner(login: $owner) {\n repositories(\n first: 100\n after: $cursor\n isArchived: false\n isFork: false\n orderBy: { field: PUSHED_AT, direction: DESC }\n ) {\n nodes {\n nameWithOwner\n pushedAt\n defaultBranchRef { target { oid } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }\n }\n`;\n\ninterface GitHubRepository {\n fullName: string;\n url: string;\n revision: string;\n}\n\ninterface GitHubRepositoriesResponse {\n repositoryOwner: {\n repositories: {\n nodes: Array<{\n nameWithOwner: string;\n pushedAt: string;\n defaultBranchRef: { target: { oid: string } } | null;\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n } | null;\n}\n\nexport interface BulkScanPrompt {\n isInteractive(): boolean;\n write(value: string): void;\n confirm(question: string, defaultValue?: boolean): Promise<boolean>;\n input(question: string, defaultValue?: string): Promise<string>;\n select<Value extends string>(\n question: string,\n options: readonly { label: string; value: Value }[],\n ): Promise<Value>;\n}\n\nexport interface BulkScanDiscoveryDependencies {\n prompt: BulkScanPrompt;\n now(): number;\n currentDirectory(): string;\n githubHost?: string;\n createGitHub(host: string, signal?: AbortSignal): Promise<Octokit>;\n}\n\nexport interface BulkScanWizardResult {\n inputPath: string;\n outputDir: string;\n githubHost: string;\n}\n\ninterface PromptOutput {\n write(value: string): unknown;\n readonly isTTY?: boolean;\n}\n\nexport function createBulkScanDiscoveryDependencies(options: {\n output: PromptOutput;\n now(): number;\n currentDirectory(): string;\n}): BulkScanDiscoveryDependencies {\n return {\n prompt: createTerminalPrompt(options.output),\n now: options.now,\n currentDirectory: options.currentDirectory,\n ...(process.env[\"GH_HOST\"]?.trim()\n ? { githubHost: process.env[\"GH_HOST\"].trim() }\n : {}),\n createGitHub: async (host, signal) => {\n const trusted = await resolveTrustedExecutable(\n \"gh\",\n process.env,\n options.currentDirectory(),\n );\n if (trusted === null) {\n throw new Error(\n \"GitHub CLI is required. Install gh and sign in first.\",\n );\n }\n\n let token: string;\n try {\n const { stdout } = await execFile(\n trusted.executable,\n [\"auth\", \"token\", \"--hostname\", host],\n { env: trusted.environment, signal },\n );\n token = stdout.trim();\n } catch {\n signal?.throwIfAborted();\n throw new Error(\n \"GitHub sign-in is required. Run 'gh auth login' first.\",\n );\n }\n return new Octokit({\n auth: token,\n ...(host === \"github.com\" ? {} : { baseUrl: `https://${host}/api/v3` }),\n });\n },\n };\n}\n\nexport async function runBulkScanWizard(\n dependencies: BulkScanDiscoveryDependencies,\n signal?: AbortSignal,\n): Promise<BulkScanWizardResult | null> {\n const { prompt } = dependencies;\n if (!prompt.isInteractive()) {\n throw new Error(\n \"Interactive repository selection requires a terminal. Provide a CSV with 'codex-security bulk-scan repositories.csv --output-dir ./security-scans'.\",\n );\n }\n signal?.throwIfAborted();\n\n const githubHost = dependencies.githubHost ?? \"github.com\";\n const github = await dependencies.createGitHub(githubHost, signal);\n const owner = await selectGitHubOwner(github, prompt, signal);\n prompt.write(\"\\nFinding active repositories...\\n\");\n const discovered = await discoverGitHubRepositories(\n github,\n githubHost,\n owner,\n dependencies.now() - 90 * 86_400_000,\n signal,\n );\n if (discovered.length === 0) {\n prompt.write(\"\\nNo repositories matched your selection.\\n\");\n return null;\n }\n\n prompt.write(`\\nFound ${discovered.length} repositories.\\n`);\n const repositories = await selectGitHubRepositories(discovered, prompt);\n\n const outputDir = resolve(\n dependencies.currentDirectory(),\n await prompt.input(\n \"Where should scan results be saved?\",\n \"./security-scans\",\n ),\n );\n const inputPath = join(outputDir, \"repositories.csv\");\n await validateWizardOutput(outputDir);\n prompt.write(\n `\\nReady to scan ${repositories.length} repositories?\\n` +\n `Results: ${outputDir}\\nRepository list: ${inputPath}\\n`,\n );\n if (!(await prompt.confirm(\"Start scanning?\"))) {\n prompt.write(\"\\nScan canceled.\\n\");\n return null;\n }\n signal?.throwIfAborted();\n\n await mkdir(outputDir, { recursive: true, mode: 0o700 });\n await writeFile(\n inputPath,\n `${Papa.unparse(\n repositories.map(({ fullName, url, revision }) => ({\n id: repositoryId(fullName),\n repository: url,\n revision,\n })),\n )}\\n`,\n { flag: \"wx\", mode: 0o600, ...(signal === undefined ? {} : { signal }) },\n );\n return { inputPath, outputDir, githubHost };\n}\n\nasync function selectGitHubOwner(\n github: Octokit,\n prompt: BulkScanPrompt,\n signal?: AbortSignal,\n): Promise<string> {\n const [firstPage, user] = await Promise.all([\n github.request(\"GET /user/orgs\", { per_page: 100, request: { signal } }),\n github.request(\"GET /user\", { request: { signal } }),\n ]);\n const organizations = [...firstPage.data];\n let response = firstPage;\n let page = 1;\n while (response.headers.link?.includes('rel=\"next\"')) {\n signal?.throwIfAborted();\n response = await github.request(\"GET /user/orgs\", {\n per_page: 100,\n page: ++page,\n request: { signal },\n });\n organizations.push(...response.data);\n }\n const personal = user.data.login;\n const owners = [personal, ...organizations.map(({ login }) => login)].sort();\n if (owners.length > 1) {\n return await prompt.select(\n \"Which account or organization should we scan?\",\n owners.map((owner) => ({ label: owner, value: owner })),\n );\n }\n prompt.write(`\\nFinding repositories in ${personal}.\\n`);\n return personal;\n}\n\nasync function selectGitHubRepositories(\n repositories: GitHubRepository[],\n prompt: BulkScanPrompt,\n): Promise<GitHubRepository[]> {\n const selected = new Set<string>();\n while (selected.size < repositories.length) {\n const choice = await prompt.select(\n \"Select repositories to scan (type to filter)\",\n [\n {\n label: selected.size\n ? `Done (${selected.size} selected)`\n : `All ${repositories.length} repositories`,\n value: \"\",\n },\n ...repositories\n .filter(({ fullName }) => !selected.has(fullName))\n .map(({ fullName }) => ({ label: fullName, value: fullName })),\n ],\n );\n if (!choice) break;\n selected.add(choice);\n }\n return selected.size\n ? repositories.filter(({ fullName }) => selected.has(fullName))\n : repositories;\n}\n\nasync function discoverGitHubRepositories(\n github: Octokit,\n host: string,\n owner: string,\n cutoff: number,\n signal?: AbortSignal,\n): Promise<GitHubRepository[]> {\n const repositories: GitHubRepository[] = [];\n let cursor: string | null = null;\n\n do {\n signal?.throwIfAborted();\n const result: GitHubRepositoriesResponse = await github.graphql(\n GITHUB_REPOSITORIES_QUERY,\n { owner, cursor, request: { signal } },\n );\n const connection = result.repositoryOwner?.repositories;\n if (connection === undefined) {\n throw new Error(\"GitHub could not list repositories for this account.\");\n }\n\n for (const repository of connection.nodes) {\n if (Date.parse(repository.pushedAt) < cutoff) return repositories;\n if (repository.defaultBranchRef === null) continue;\n repositories.push({\n fullName: repository.nameWithOwner,\n url: `https://${host}/${repository.nameWithOwner}.git`,\n revision: repository.defaultBranchRef.target.oid.toLowerCase(),\n });\n }\n cursor = connection.pageInfo.hasNextPage\n ? connection.pageInfo.endCursor\n : null;\n } while (cursor !== null);\n\n return repositories;\n}\n\nfunction repositoryId(fullName: string): string {\n const id = fullName.replace(\"/\", \"--\");\n if (id.length <= 128) return id;\n const hash = createHash(\"sha256\").update(fullName).digest(\"hex\").slice(0, 16);\n return `${id.slice(0, 111)}-${hash}`;\n}\n\nasync function validateWizardOutput(outputDir: string): Promise<void> {\n let metadata;\n try {\n metadata = await lstat(outputDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n if (!metadata.isDirectory()) {\n throw new Error(\"The scan output must be a real directory.\");\n }\n\n for (const name of [\"repositories.csv\", \"manifest.json\"]) {\n try {\n await lstat(join(outputDir, name));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw error;\n }\n throw new Error(\n \"The selected output directory already contains a repository list or scan. Choose a new directory or resume the existing scan.\",\n );\n }\n}\n\nfunction createTerminalPrompt(output: PromptOutput): BulkScanPrompt {\n const context = () => ({\n input: stdin,\n output: new Writable({\n write(chunk: Buffer, _encoding, callback) {\n output.write(chunk.toString(\"utf8\"));\n callback();\n },\n }),\n });\n\n return {\n isInteractive: () => stdin.isTTY === true && output.isTTY === true,\n write: (value) => {\n output.write(value);\n },\n confirm: (message, defaultValue = false) =>\n confirm({ message, default: defaultValue }, context()),\n input: (message, defaultValue) =>\n input({ message, default: defaultValue }, context()),\n select: (message, options) =>\n search(\n {\n message,\n source: (term) =>\n options\n .filter(({ label }) =>\n label.toLowerCase().includes(term?.toLowerCase() ?? \"\"),\n )\n .map(({ label, value }) => ({ name: label, value })),\n },\n context(),\n ),\n };\n}\n"]}
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import type { ModelReasoningEffort } from "@openai/codex-sdk";
3
2
  import { CodexSecurity } from "./api.js";
4
3
  import { type BulkScanDiscoveryDependencies, type BulkScanPrompt } from "./bulk-scan-discovery.js";
5
4
  import { type CodexSecurityConfig, type ExternalModelProvider, type JsonObject } from "./config.js";
@@ -7,11 +6,15 @@ import { type CodexCommand } from "./runtime.js";
7
6
  import { type matchScanFindings } from "./scan-comparison.js";
8
7
  import { type UpdateNotice } from "./version.js";
9
8
  type Writable = Pick<NodeJS.WriteStream, "write"> & {
9
+ on?(event: "error", listener: (error: Error) => void): unknown;
10
+ off?(event: "error", listener: (error: Error) => void): unknown;
10
11
  readonly isTTY?: boolean;
11
12
  readonly fd?: number;
12
13
  readonly columns?: number;
13
14
  };
14
15
  type SignalName = "SIGINT" | "SIGTERM";
16
+ declare const MODEL_REASONING_EFFORTS: readonly ["minimal", "low", "medium", "high", "xhigh", "max"];
17
+ type ScanReasoningEffort = (typeof MODEL_REASONING_EFFORTS)[number];
15
18
  declare const EXPORT_DEFAULT_OUTPUTS: {
16
19
  readonly csv: "findings.csv";
17
20
  readonly json: "findings.json";
@@ -48,7 +51,7 @@ interface CliDependencies {
48
51
  bulkScan?: BulkScanDiscoveryDependencies;
49
52
  runWorkbench(args: readonly string[]): Promise<JsonObject>;
50
53
  matchFindings: typeof matchScanFindings;
51
- checkForUpdate(): Promise<UpdateNotice | undefined>;
54
+ checkForUpdate(signal: AbortSignal): Promise<UpdateNotice | undefined>;
52
55
  }
53
56
  export declare function runCodexSkillCommand(args: readonly string[], output?: SkillCommandOutput, command?: CodexCommand, processEnvironment?: NodeJS.ProcessEnv): Promise<number>;
54
57
  export declare function exportEnvironment(environment?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
@@ -59,7 +62,7 @@ export declare function readSkillCommandOutput(stream: AsyncIterable<Buffer | st
59
62
  malformed: boolean;
60
63
  }>;
61
64
  export declare function skillCommandFailure(command: "validate" | "patch", status: number, detail: string): string;
62
- export declare function parseCodexOverrides(values: readonly string[], model?: string, effort?: ModelReasoningEffort, provider?: "openai" | "amazon-bedrock" | ExternalModelProvider): JsonObject;
65
+ export declare function parseCodexOverrides(values: readonly string[], model?: string, effort?: ScanReasoningEffort, provider?: "openai" | "amazon-bedrock" | ExternalModelProvider): JsonObject;
63
66
  export declare class Progress {
64
67
  #private;
65
68
  constructor(stream?: Writable, dependencies?: Pick<CliDependencies, "now" | "setInterval" | "clearInterval">, interactive?: boolean);
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AA4BA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAG9D,OAAO,EAEL,aAAa,EASd,MAAM,UAAU,CAAC;AAElB,OAAO,EAGL,KAAK,6BAA6B,EAClC,KAAK,cAAc,EACpB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAOL,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,UAAU,EAEhB,MAAM,aAAa,CAAC;AAiBrB,OAAO,EAUL,KAAK,YAAY,EAClB,MAAM,cAAc,CAAC;AACtB,OAAO,EAEL,KAAK,iBAAiB,EAEvB,MAAM,sBAAsB,CAAC;AAc9B,OAAO,EAOL,KAAK,YAAY,EAElB,MAAM,cAAc,CAAC;AAYtB,KAAK,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,GAAG;IAClD,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC3B,CAAC;AACF,KAAK,UAAU,GAAG,QAAQ,GAAG,SAAS,CAAC;AA4BvC,QAAA,MAAM,sBAAsB;;;;CAIlB,CAAC;AAyIX,UAAU,eAAe;IACvB,OAAO,EAA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ACjB,EACxB,WAAW,UAAO;IAQpB,IAAW,WAAW,IAAI,OAAO,CAEhC;IAED,IAAW,cAAc,IAAI,MAAM,CAKlC;IAEM,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAK5B,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAiBjC,SAAS,IAAI,IAAI;IAwCjB,eAAe,CAAC,KAAK,EAAE,MAAM,IAAI,GAAG,IAAI;CAoChD"}
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFileSync, spawn } from "node:child_process";
3
3
  import { accessSync, constants, existsSync, lstatSync, realpathSync, writeSync, } from "node:fs";
4
- import { mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
4
+ import { lstat, mkdir, open, readFile, realpath, writeFile, } from "node:fs/promises";
5
5
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep, win32, } from "node:path";
6
6
  import { cwd } from "node:process";
7
7
  import { createInterface } from "node:readline";
@@ -47,6 +47,7 @@ const MODEL_REASONING_EFFORTS = [
47
47
  "medium",
48
48
  "high",
49
49
  "xhigh",
50
+ "max",
50
51
  ];
51
52
  const DEFAULT_SCAN_MODEL_CONFIGURATION = scanModelConfiguration(DEFAULT_CODEX_CONFIG);
52
53
  const CODEX_OVERRIDE_DESCRIPTION = 'Repeat TOML KEY=VALUE; e.g. model_reasoning_effort="high" or features.multi_agent_v2.max_concurrent_threads_per_session=4.';
@@ -80,6 +81,7 @@ const VALUE_OPTIONS = new Set([
80
81
  "--subagents",
81
82
  "--stop-after-no-new",
82
83
  "--max-discovery-runs",
84
+ "--max-time-hours",
83
85
  "--max-attempts",
84
86
  "--export-format",
85
87
  "--output",
@@ -101,7 +103,7 @@ function optionValue(flag) {
101
103
  function effortOption() {
102
104
  return z
103
105
  .enum(MODEL_REASONING_EFFORTS, {
104
- error: "--effort must be minimal, low, medium, high, or xhigh.",
106
+ error: "--effort must be minimal, low, medium, high, xhigh, or max.",
105
107
  })
106
108
  .optional()
107
109
  .describe(`Model reasoning effort (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort}).`);
@@ -131,30 +133,69 @@ const DEEP_SCAN_OPTION_SCHEMAS = {
131
133
  .positive()
132
134
  .optional()
133
135
  .describe("Maximum deep-scan discovery runs."),
136
+ maxTimeHours: z
137
+ .number()
138
+ .positive()
139
+ .max(96)
140
+ .optional()
141
+ .describe("Maximum deep-scan discovery hours (default: 96; maximum: 96)."),
134
142
  };
135
- async function readPromptFiles(directory, scanPromptFile, postScanPromptFile) {
143
+ async function readPromptFiles(directory, scanPromptFile, postScanPromptFile, repository = directory) {
136
144
  const [scanPrompt, postScanPrompt] = await Promise.all([
137
145
  scanPromptFile === undefined
138
146
  ? undefined
139
- : readFile(resolve(directory, scanPromptFile), "utf8"),
147
+ : readRegularInputFile(resolve(directory, scanPromptFile), repository),
140
148
  postScanPromptFile === undefined
141
149
  ? undefined
142
- : readFile(resolve(directory, postScanPromptFile), "utf8"),
150
+ : readRegularInputFile(resolve(directory, postScanPromptFile), repository),
143
151
  ]);
144
152
  return {
145
153
  ...(scanPrompt?.trim() ? { scanPrompt } : {}),
146
154
  ...(postScanPrompt?.trim() ? { postScanPrompt } : {}),
147
155
  };
148
156
  }
157
+ async function readRegularInputFile(path, repository, metadata) {
158
+ const selected = metadata ?? (await lstat(path));
159
+ if (!selected.isFile()) {
160
+ throw new CodexSecurityError("Input files must be regular files.");
161
+ }
162
+ const canonicalRepository = await realpath(repository);
163
+ const canonicalParent = await realpath(dirname(path));
164
+ if (isOutsidePath(relative(canonicalRepository, canonicalParent))) {
165
+ for (let ancestor = dirname(path);; ancestor = dirname(ancestor)) {
166
+ if (!isOutsidePath(relative(canonicalRepository, await realpath(ancestor)))) {
167
+ throw new CodexSecurityError("Input files must not follow repository directory links outside the selected repository.");
168
+ }
169
+ if (dirname(ancestor) === ancestor) {
170
+ break;
171
+ }
172
+ }
173
+ }
174
+ const file = await open(join(canonicalParent, basename(path)), constants.O_RDONLY |
175
+ (constants.O_NOFOLLOW ?? 0) |
176
+ (constants.O_NONBLOCK ?? 0));
177
+ try {
178
+ const opened = await file.stat();
179
+ if (!opened.isFile() ||
180
+ opened.dev !== selected.dev ||
181
+ opened.ino !== selected.ino) {
182
+ throw new CodexSecurityError("Input files must remain regular files.");
183
+ }
184
+ return await file.readFile({ encoding: "utf8" });
185
+ }
186
+ finally {
187
+ await file.close();
188
+ }
189
+ }
149
190
  const DEFAULT_DEPENDENCIES = {
150
191
  createSecurity: (config) => createSecurityInternal(config, { surface: "cli" }),
151
192
  environment: process.env,
152
193
  prepareAuthenticationHome: prepareCodexSecurityCredentialHome,
153
- checkForUpdate: () => checkForUpdate({ environment: process.env }),
194
+ checkForUpdate: (signal) => checkForUpdate({ environment: process.env, signal }),
154
195
  hasStoredChatGPTSignIn: async () => {
155
196
  const environment = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toUpperCase() !== "OPENAI_API_KEY" &&
156
197
  name.toUpperCase() !== "CODEX_API_KEY"));
157
- const command = resolveCodexCommand();
198
+ const command = resolveCodexCommand(environment);
158
199
  if (existsSync(codexSecurityCredentialHome(process.env))) {
159
200
  const dedicatedStatus = await accountStatus(command, {
160
201
  ...environment,
@@ -181,7 +222,7 @@ const DEFAULT_DEPENDENCIES = {
181
222
  writeSync(stream.fd, value);
182
223
  },
183
224
  forceExit: (signal) => process.kill(process.pid, signal),
184
- runCodex: (args, output, environment) => runCodexSkillCommand(args, output, resolveCodexCommand(), environment),
225
+ runCodex: (args, output, environment) => runCodexSkillCommand(args, output, resolveCodexCommand(environment), environment),
185
226
  exportFindings: async (arguments_, output) => {
186
227
  const environment = exportEnvironment();
187
228
  const python = await resolvePluginPython({
@@ -261,7 +302,7 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
261
302
  if (configuredHome?.trim()) {
262
303
  environment["CODEX_HOME"] = resolve(expandHome(configuredHome));
263
304
  }
264
- const invocation = spawn(command.command, [...command.prefixArgs, ...args], {
305
+ const invocation = spawn(command.command, [...args], {
265
306
  env: environment,
266
307
  cwd: parse(process.execPath).root,
267
308
  stdio: output === undefined ? "inherit" : ["ignore", "pipe", "pipe"],
@@ -424,6 +465,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
424
465
  errorOutput.write(`codex-security: ${argumentError}\n`);
425
466
  return 2;
426
467
  }
468
+ const updateController = new AbortController();
427
469
  const pendingUpdate = errorOutput.isTTY === true &&
428
470
  argv.length > 0 &&
429
471
  argv[0] !== "completions" &&
@@ -437,7 +479,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
437
479
  "--dry-run",
438
480
  ].includes(argument)) &&
439
481
  updateNoticeEnabled(dependencies.environment)
440
- ? dependencies.checkForUpdate().catch(() => undefined)
482
+ ? dependencies
483
+ .checkForUpdate(updateController.signal)
484
+ .catch(() => undefined)
441
485
  : undefined;
442
486
  let exitCode = 0;
443
487
  let frameworkExit;
@@ -635,6 +679,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
635
679
  scanId: scan.scanId,
636
680
  threadId,
637
681
  codexHome: codexSecurityCredentialHome(dependencies.environment),
682
+ scanDirectory: scan.mode === "deep" ? scan.scanDir : undefined,
683
+ completedAt: scan.progress?.status === "running"
684
+ ? null
685
+ : scan.progress?.status === "complete" ||
686
+ scan.progress?.status === "failed" ||
687
+ scan.progress?.status === "canceled"
688
+ ? scan.progress.updatedAt ?? ""
689
+ : "",
638
690
  }));
639
691
  });
640
692
  },
@@ -855,7 +907,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
855
907
  (options.workers === undefined &&
856
908
  options.subagents === undefined &&
857
909
  options.stopAfterNoNew === undefined &&
858
- options.maxDiscoveryRuns === undefined), { message: "Deep scan settings require --mode deep." }),
910
+ options.maxDiscoveryRuns === undefined &&
911
+ options.maxTimeHours === undefined), { message: "Deep scan settings require --mode deep." }),
859
912
  examples: [
860
913
  { args: { repository: "." } },
861
914
  { args: { repository: "." }, options: { model: "gpt-5.6-terra" } },
@@ -898,6 +951,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
898
951
  subagents: options.subagents,
899
952
  stopAfterNoNew: options.stopAfterNoNew,
900
953
  maxDiscoveryRuns: options.maxDiscoveryRuns,
954
+ maxTimeHours: options.maxTimeHours,
901
955
  model: options.model,
902
956
  effort: options.effort,
903
957
  provider: options.provider,
@@ -1042,6 +1096,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1042
1096
  .positive()
1043
1097
  .default(1)
1044
1098
  .describe("Maximum scan attempts per repository."),
1099
+ maxCost: z
1100
+ .number()
1101
+ .positive()
1102
+ .optional()
1103
+ .describe("Stop each repository attempt if estimated USD cost exceeds AMOUNT."),
1045
1104
  pluginPath: z
1046
1105
  .string()
1047
1106
  .min(1)
@@ -1111,6 +1170,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1111
1170
  workers: options.workers,
1112
1171
  mode: options.mode,
1113
1172
  maxAttempts: options.maxAttempts,
1173
+ ...(options.maxCost === undefined
1174
+ ? {}
1175
+ : { maxCostUsd: options.maxCost }),
1114
1176
  knowledgeBasePaths: options.knowledgeBase,
1115
1177
  ...prompts,
1116
1178
  config: {
@@ -1370,21 +1432,27 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1370
1432
  };
1371
1433
  },
1372
1434
  });
1373
- await cli.serve(argv.flatMap((argument) => argument.startsWith("--format=")
1374
- ? ["--format", argument.slice("--format=".length)]
1375
- : [argument]), {
1376
- stdout: (value) => {
1377
- frameworkOutput += value;
1378
- },
1379
- exit: (code) => {
1380
- frameworkExit = code;
1381
- },
1382
- });
1383
- if (pendingUpdate !== undefined) {
1384
- const notice = await pendingUpdate;
1385
- if (notice !== undefined)
1386
- errorOutput.write(formatUpdateNotice(notice));
1435
+ let notice;
1436
+ try {
1437
+ await cli.serve(argv.flatMap((argument) => argument.startsWith("--format=")
1438
+ ? ["--format", argument.slice("--format=".length)]
1439
+ : [argument]), {
1440
+ stdout: (value) => {
1441
+ frameworkOutput += value;
1442
+ },
1443
+ exit: (code) => {
1444
+ frameworkExit = code;
1445
+ },
1446
+ });
1447
+ if (pendingUpdate !== undefined) {
1448
+ notice = await Promise.race([pendingUpdate, undefined]);
1449
+ }
1450
+ }
1451
+ finally {
1452
+ updateController.abort();
1387
1453
  }
1454
+ if (notice !== undefined)
1455
+ errorOutput.write(formatUpdateNotice(notice));
1388
1456
  if (frameworkExit !== undefined) {
1389
1457
  if (exitCode !== 0)
1390
1458
  return exitCode;
@@ -1727,7 +1795,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
1727
1795
  localDeviceRoot !== normalizedDeviceRoot);
1728
1796
  if (!windowsNetworkPath) {
1729
1797
  const path = resolve(directory, input);
1730
- const metadata = await stat(path).catch((error) => {
1798
+ const metadata = await lstat(path).catch((error) => {
1731
1799
  if (typeof error === "object" &&
1732
1800
  error !== null &&
1733
1801
  "code" in error &&
@@ -1744,7 +1812,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
1744
1812
  throw new CodexSecurityError("Finding and issue inputs must be files or literal text.");
1745
1813
  }
1746
1814
  try {
1747
- contentsOrLiteral = await readFile(path, "utf8");
1815
+ contentsOrLiteral = await readRegularInputFile(path, directory, metadata);
1748
1816
  }
1749
1817
  catch {
1750
1818
  throw new CodexSecurityError("Could not read the finding or issue input.");
@@ -1929,6 +1997,29 @@ function diagnosticValue(value) {
1929
1997
  return errorMessage(value).replaceAll(/[\u0000-\u001F\u007F\u0085\u2028\u2029]/gu, " ");
1930
1998
  }
1931
1999
  async function runScan(arguments_, errorOutput, dependencies, interactive = true) {
2000
+ const observeTerminalErrors = typeof errorOutput.on === "function" &&
2001
+ typeof errorOutput.off === "function";
2002
+ const ignoreTerminalError = () => { };
2003
+ if (observeTerminalErrors) {
2004
+ errorOutput.on?.("error", ignoreTerminalError);
2005
+ }
2006
+ try {
2007
+ return await executeScan(arguments_, errorOutput, dependencies, interactive);
2008
+ }
2009
+ finally {
2010
+ if (observeTerminalErrors) {
2011
+ try {
2012
+ errorOutput.write("", () => {
2013
+ queueMicrotask(() => errorOutput.off?.("error", ignoreTerminalError));
2014
+ });
2015
+ }
2016
+ catch {
2017
+ errorOutput.off?.("error", ignoreTerminalError);
2018
+ }
2019
+ }
2020
+ }
2021
+ }
2022
+ async function executeScan(arguments_, errorOutput, dependencies, interactive = true) {
1932
2023
  let scanDir = null;
1933
2024
  let requestedSignal = null;
1934
2025
  let firstSignalAt = 0;
@@ -1965,6 +2056,16 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1965
2056
  });
1966
2057
  };
1967
2058
  const preparationAbortController = new AbortController();
2059
+ const stopPresentation = () => {
2060
+ try {
2061
+ dashboard?.stop();
2062
+ }
2063
+ catch { }
2064
+ try {
2065
+ progress?.stopTimer();
2066
+ }
2067
+ catch { }
2068
+ };
1968
2069
  const signalListener = (signal) => () => {
1969
2070
  if (requestedSignal !== null) {
1970
2071
  // Launchers and terminals can deliver the same initial signal twice.
@@ -1974,8 +2075,7 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1974
2075
  return;
1975
2076
  }
1976
2077
  requestedSignal = signal;
1977
- dashboard?.stop();
1978
- progress?.stopTimer();
2078
+ stopPresentation();
1979
2079
  if (progress?.interactive === true) {
1980
2080
  try {
1981
2081
  dependencies.writeSynchronously(errorOutput, SHOW_CURSOR);
@@ -2009,9 +2109,10 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
2009
2109
  let failed = false;
2010
2110
  let failure;
2011
2111
  try {
2012
- const repository = arguments_.repository ?? dependencies.currentDirectory();
2112
+ const directory = dependencies.currentDirectory();
2113
+ const repository = arguments_.repository ?? directory;
2013
2114
  const target = targetFromArguments(arguments_);
2014
- const prompts = await readPromptFiles(dependencies.currentDirectory(), arguments_.scanPromptFile, arguments_.postScanPromptFile);
2115
+ const prompts = await readPromptFiles(directory, arguments_.scanPromptFile, arguments_.postScanPromptFile, resolve(directory, repository));
2015
2116
  const config = {
2016
2117
  pluginPath: arguments_.pluginPath,
2017
2118
  pythonPath: arguments_.pythonPath,
@@ -2080,6 +2181,7 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
2080
2181
  if (progress.interactive && !arguments_.dryRun && !verbose) {
2081
2182
  dashboard = new ScanDashboard(errorOutput, {
2082
2183
  repository,
2184
+ mode: arguments_.mode,
2083
2185
  model: scanModelConfiguration(await mergedCodexConfig(config)),
2084
2186
  ...(arguments_.maxCostUsd === undefined
2085
2187
  ? {}
@@ -2121,7 +2223,14 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
2121
2223
  progress.startTimer(arguments_.dryRun ? "Validating scan inputs" : "Preparing scan");
2122
2224
  }
2123
2225
  else {
2124
- dashboard.start();
2226
+ try {
2227
+ dashboard.start();
2228
+ }
2229
+ catch {
2230
+ dashboard = null;
2231
+ progress = new Progress(errorOutput, dependencies, false);
2232
+ progress.startTimer("Preparing scan");
2233
+ }
2125
2234
  }
2126
2235
  security = dependencies.createSecurity(config);
2127
2236
  const options = {
@@ -2134,6 +2243,7 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
2134
2243
  subagents: arguments_.subagents,
2135
2244
  stopAfterNoNew: arguments_.stopAfterNoNew,
2136
2245
  maxDiscoveryRuns: arguments_.maxDiscoveryRuns,
2246
+ maxTimeHours: arguments_.maxTimeHours,
2137
2247
  outputDir: arguments_.outputDir,
2138
2248
  archiveExisting: arguments_.archiveExisting,
2139
2249
  parentScanId: arguments_.parentScanId,
@@ -2362,8 +2472,7 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
2362
2472
  failure = error;
2363
2473
  }
2364
2474
  finally {
2365
- dashboard?.stop();
2366
- progress?.stopTimer();
2475
+ stopPresentation();
2367
2476
  if (security !== null) {
2368
2477
  diagnostic("runtime.cleanup.started");
2369
2478
  await security.close().then(() => diagnostic("runtime.cleanup.completed"), (error) => {
@@ -2430,6 +2539,7 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
2430
2539
  : undefined,
2431
2540
  verified: effectivePreflight.authentication.verified,
2432
2541
  });
2542
+ progress?.stopTimer();
2433
2543
  return { exitCode: 0, data: { dryRun: true, ...effectivePreflight } };
2434
2544
  }
2435
2545
  if (result === null) {
@@ -2462,14 +2572,17 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
2462
2572
  });
2463
2573
  if (targetWarnings.length > 0) {
2464
2574
  errorOutput.write("codex-security: Scan target changed during execution; results do not represent the current checkout.\n");
2575
+ progress?.stopTimer();
2465
2576
  return { exitCode: 2, data: scanData };
2466
2577
  }
2467
2578
  if (incomplete) {
2468
2579
  errorOutput.write(threshold === undefined
2469
2580
  ? `codex-security: Scan coverage is ${result.coverage.completeness}; results may be incomplete.\n`
2470
2581
  : `codex-security: Cannot evaluate the failure policy: coverage is ${result.coverage.completeness}.\n`);
2582
+ progress?.stopTimer();
2471
2583
  return { exitCode: 2, data: scanData };
2472
2584
  }
2585
+ progress?.stopTimer();
2473
2586
  return { exitCode: blockingCount > 0 ? 1 : 0, data: scanData };
2474
2587
  }
2475
2588
  // Filesystem and OS syscall failures cannot originate from the model transport,
@@ -2827,6 +2940,10 @@ export class Progress {
2827
2940
  #timerMessage = null;
2828
2941
  #timerLineActive = false;
2829
2942
  #cursorHidden = false;
2943
+ #observingStreamErrors = false;
2944
+ #streamErrorsActive = false;
2945
+ #streamErrorGeneration = 0;
2946
+ #onStreamError = () => { };
2830
2947
  constructor(stream = process.stderr, dependencies = DEFAULT_DEPENDENCIES, interactive = true) {
2831
2948
  this.#stream = stream;
2832
2949
  this.#dependencies = dependencies;
@@ -2840,9 +2957,11 @@ export class Progress {
2840
2957
  return Math.max(0, Math.floor((this.#dependencies.now() - this.#startedAt) / 1_000));
2841
2958
  }
2842
2959
  stage(message) {
2960
+ this.#observeStreamErrors();
2843
2961
  this.#stream.write(`${this.#line(message)}\n`);
2844
2962
  }
2845
2963
  startTimer(message) {
2964
+ this.#observeStreamErrors();
2846
2965
  if (!this.interactive) {
2847
2966
  this.stage(message);
2848
2967
  return;
@@ -2850,22 +2969,51 @@ export class Progress {
2850
2969
  this.#stream.write(HIDE_CURSOR);
2851
2970
  this.#cursorHidden = true;
2852
2971
  this.#renderTimer(message);
2853
- this.#timer = this.#dependencies.setInterval(() => this.#renderTimer(message), PROGRESS_REFRESH_MILLISECONDS);
2972
+ this.#timer = this.#dependencies.setInterval(() => {
2973
+ try {
2974
+ this.#renderTimer(message);
2975
+ }
2976
+ catch { }
2977
+ }, PROGRESS_REFRESH_MILLISECONDS);
2854
2978
  this.#timerMessage = message;
2855
2979
  }
2856
2980
  stopTimer() {
2857
- if (this.#timer !== null) {
2858
- this.#dependencies.clearInterval(this.#timer);
2859
- this.#timer = null;
2860
- }
2861
- this.#timerMessage = null;
2862
- if (this.#timerLineActive) {
2863
- this.#stream.write("\n");
2864
- this.#timerLineActive = false;
2981
+ try {
2982
+ if (this.#timer !== null) {
2983
+ this.#dependencies.clearInterval(this.#timer);
2984
+ this.#timer = null;
2985
+ }
2986
+ this.#timerMessage = null;
2987
+ if (this.#timerLineActive) {
2988
+ this.#stream.write("\n");
2989
+ this.#timerLineActive = false;
2990
+ }
2991
+ if (this.#cursorHidden) {
2992
+ this.#stream.write(SHOW_CURSOR);
2993
+ this.#cursorHidden = false;
2994
+ }
2865
2995
  }
2866
- if (this.#cursorHidden) {
2867
- this.#stream.write(SHOW_CURSOR);
2868
- this.#cursorHidden = false;
2996
+ finally {
2997
+ if (this.#observingStreamErrors) {
2998
+ this.#streamErrorsActive = false;
2999
+ const generation = this.#streamErrorGeneration;
3000
+ try {
3001
+ this.#stream.write("", () => {
3002
+ queueMicrotask(() => {
3003
+ if (generation === this.#streamErrorGeneration &&
3004
+ !this.#streamErrorsActive &&
3005
+ this.#observingStreamErrors) {
3006
+ this.#stream.off?.("error", this.#onStreamError);
3007
+ this.#observingStreamErrors = false;
3008
+ }
3009
+ });
3010
+ });
3011
+ }
3012
+ catch {
3013
+ this.#stream.off?.("error", this.#onStreamError);
3014
+ this.#observingStreamErrors = false;
3015
+ }
3016
+ }
2869
3017
  }
2870
3018
  }
2871
3019
  writeAboveTimer(write) {
@@ -2888,6 +3036,14 @@ export class Progress {
2888
3036
  const seconds = elapsedSeconds % 60;
2889
3037
  return `[${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}] ${message}`;
2890
3038
  }
3039
+ #observeStreamErrors() {
3040
+ this.#streamErrorsActive = true;
3041
+ this.#streamErrorGeneration += 1;
3042
+ if (!this.#observingStreamErrors && this.#stream.on !== undefined) {
3043
+ this.#stream.on("error", this.#onStreamError);
3044
+ this.#observingStreamErrors = true;
3045
+ }
3046
+ }
2891
3047
  #renderTimer(message) {
2892
3048
  this.#stream.write(`${this.#timerLineActive ? "\r" : ""}${this.#line(message)}`);
2893
3049
  this.#timerLineActive = true;