Skip to content

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

chore(codex-security): sync public projection

ianw-oai2034f7b04a3e
diff --git a/README.md b/README.md
index 5a8622fff..929bd96df 100644
--- a/README.md
+++ b/README.md
@@ -66,17 +66,14 @@ worktree. When SARIF is produced, it is written to
`<scan-dir>/exports/results.sarif`. Use `npx codex-security scan --help` for all
target, 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.
+Sign in with `gh auth login`, then run `npx codex-security bulk-scan` to discover
+GitHub repositories pushed in the last 90 days. Archived
+repositories and forks are excluded. Optionally filter by comma-separated
+repository-name keywords, review the matches, and confirm before scanning.
+Private checkouts reuse your GitHub CLI sign-in without changing your global Git
+configuration. 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 discovery
and structured output. Use `--llms` for the command manifest,
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 30a4fdc34..d03777512 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -103,18 +103,13 @@ either setting with repeatable `--codex KEY=VALUE` options, for example
Run `npx codex-security scan --help` or `npx codex-security bulk-scan --help`
for the complete CLI references.
-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.
+Sign in with `gh auth login`, then run `npx codex-security bulk-scan` to discover
+GitHub repositories pushed in the last 90 days. Archived
+repositories and forks are excluded. Optionally filter by comma-separated
+repository-name keywords, review the matches, and confirm before scanning.
+Private checkouts reuse your GitHub CLI sign-in without changing your global Git
+configuration. The selected repositories are saved to
+`<output-dir>/repositories.csv` for review or resumption.
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;
diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json
index 75eab78ad..bf70b2fa0 100644
--- a/sdk/typescript/package.json
+++ b/sdk/typescript/package.json
@@ -50,6 +50,8 @@
"types": "pnpm run generate:models:check && tsc --noEmit"
},
"dependencies": {
+ "@inquirer/prompts": "8.3.0",
+ "@octokit/core": "7.0.6",
"@openai/codex": "0.144.6",
"@openai/codex-sdk": "0.144.6",
"ajv": "8.20.0",
diff --git a/sdk/typescript/pnpm-lock.yaml b/sdk/typescript/pnpm-lock.yaml
index 22cca3fa0..f3df45ff8 100644
--- a/sdk/typescript/pnpm-lock.yaml
+++ b/sdk/typescript/pnpm-lock.yaml
@@ -8,6 +8,12 @@ importers:
.:
dependencies:
+ '@inquirer/prompts':
+ specifier: 8.3.0
+ version: 8.3.0(@types/[email protected])
+ '@octokit/core':
+ specifier: 7.0.6
+ version: 7.0.6
'@openai/codex':
specifier: 0.144.6
version: 0.144.6
@@ -61,6 +67,140 @@ packages:
'@cfworker/[email protected]':
resolution: {integrity: sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==}
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-b6xmA/VlTe0ZgDQHDui+Nav470u7u49nRd8/iuhOcQPO9Ch7lGuogydhi2VOmNlZ+zXcM8IcPuNSwQcdJaF/kw==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-eb8DBZcz/2qHWQda4rk2JiQk5h9QV/cVHi1yjt0f69WFZMRFn0sJTye3EAP8icut8UDMjQPsaH5KbcOogefrFQ==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-Qd6GJT1yVyrZZCfN8W2qKF5ApmqryXRhRKCuip8h01x2w/esJQ2XIYc6f9abMIHgKQdBfFTSOdbHRLAhuM09UA==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-ZRVd/oD+sYsUd5zVm0NflqEzlqfYCyHNsqkHl2oWXEUHs12tCbcSFi+wVFEvD8+LGRaMUsVrE7qeo6lSG/S1Vg==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-YmQpenjbFSHAK3sOd44puHh3V1KXXr+JiNpUztoSQ4drLh2rTVzTap/YtlAVu/5xavifIlBfNEzJ/neZJ1a/1g==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-6thf5I8q7lZwzGLAxPaaGEREEkZ3nyePPDQ1oyobblxmEE8mqTLguScP7pDjUTAibiyb4hfXl+qjUEJ+di/aNA==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-aJ8TBPOGB6f/2qziPfElISTCEd5XOYTFckA2SGjhNmiKzfK/u4ot3v0DUzGVdUnKjN10EqnnEPck36BkyfLnJw==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-9K/DDBSQpOyZSkt6sOVP9Vo0TR7atX2kuILsUu0x3wVcVbe97lJwIJKMLdMw25tDYuXl/qp6erT0Xs1rfmcfZg==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-XF4IXAbPnGPgw0wsbC/i2tPcyfdZgDpUlhsqU0SfT4IRIGWha6Xm9VRgN5yYxJq+jnyXlfXI/nQ3ulfk0iEICA==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-3XBfF7DAsp5qeDsvN5Rd1HmbNokVvEQoUM0QLrRcybC9nX96w3Pbmu7qUsb3IT3J3jBvs2+mTXaKHOUsgHMLzg==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-JAj66kjdH/F1+B7LCigjARbwstt3SNUOSzMdjpsvwJmzunK88gJeXmcm95L9nw1KynvFVuY4SzXh/3Y0lvtgSg==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-QqdTqQddL3qPX/PPrjobpsO25NZ4dWXgTLenrR445L2ptLEYE6Z+PD5c5CNDJNx4ugRgELAIpSIJxZaO2jJ2Og==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-xJj8QWKRSrfKoBIITLZK61dD3zwo0Rz11fgDImku30/Oe81zMdIdGgrLY2h6RkJ+KZ/GhNYIRMKnH/62qBTA5g==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-FlDndEUww8m7BfukO2nJa25vhD+H5jxxCv4oGioKqzyWz3nPHhhw4LKdYRSlXuAx7DsdWia7iyaBPKKS95Evfw==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-t28inv14nMQ1PhKpsJPY+kEs/c00qzeCOS2gTNRyTjG5d6qsVA2fItxW4hkvGZ5lvanGLdtCzVIx5dwdRpN1+g==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
'@jsdevtools/[email protected]':
resolution: {integrity: sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==}
@@ -72,6 +212,36 @@ packages:
resolution: {integrity: sha512-pjMZcNEt1dOq0aJCcY3b7w1Ayh+qmQN2xlfTELcGV9yiAjEGIczBPBLWWW0k0zzo5T8kiv15jtKPsWeHGxLvLg==}
engines: {node: '>=20'}
+ '@octokit/[email protected]':
+ resolution: {integrity: sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==}
+ engines: {node: '>= 20'}
+
+ '@octokit/[email protected]':
+ resolution: {integrity: sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q==}
+ engines: {node: '>= 20'}
+
+ '@octokit/[email protected]':
+ resolution: {integrity: sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag==}
+ engines: {node: '>= 20'}
+
+ '@octokit/[email protected]':
+ resolution: {integrity: sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA==}
+ engines: {node: '>= 20'}
+
+ '@octokit/[email protected]':
+ resolution: {integrity: sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA==}
+
+ '@octokit/[email protected]':
+ resolution: {integrity: sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw==}
+ engines: {node: '>= 20'}
+
+ '@octokit/[email protected]':
+ resolution: {integrity: sha512-+s7HUxjfFqOMS9VlIwDffq0MikjSAK0gSpG73W+meAvVAvX4MBrHYTK5Bj3Uot55qFT4gzUtfzE4mGWY4Br8/Q==}
+ engines: {node: '>= 20'}
+
+ '@octokit/[email protected]':
+ resolution: {integrity: sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==}
+
'@openai/[email protected]':
resolution: {integrity: sha512-jFgXHjFq2//PTfJa8CySqhUilRBPVmCLuQoH5F+iJ2x4owZwPlnqmIbCkWIJJ6IxDuQdjf3ewg0LaDtc3i6h9Q==}
engines: {node: '>=18'}
@@ -148,12 +318,26 @@ packages:
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
+ resolution: {integrity: sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==}
+
resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==}
resolution: {integrity: sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA==}
+ resolution: {integrity: sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==}
+
+ resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==}
+ engines: {node: '>= 12'}
+
+ resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
@@ -174,9 +358,18 @@ packages:
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
+ resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==}
+
+ resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==}
+
resolution: {integrity: sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==}
+ resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==}
+
resolution: {integrity: sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==}
@@ -196,6 +389,10 @@ packages:
resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-BeKlYFLIsRCgC8IxsUd3S2/4kPeZaNf1Rbz+Kz41jQII4jOgr7j5w4KYe00aAEQa3V0Ur57BVxE5JDTx8L2s5Q==}
engines: {node: '>=22'}
@@ -221,6 +418,9 @@ packages:
resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}
+ resolution: {integrity: sha512-Vcx+JVNEBts/xfcoCS69sKrOhOk/3TVlvlT+XzUOefVKnnrbYSCKpDCm10pohsJFtsJVYnwa/cXRZ4eElzaM6w==}
+
resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
@@ -230,6 +430,10 @@ packages:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
+ resolution: {integrity: sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==}
+ engines: {node: ^20.17.0 || >=22.9.0}
+
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
@@ -255,6 +459,13 @@ packages:
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
+
+ resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
+ engines: {node: '>=14'}
+
resolution: {integrity: sha512-dWUG8F5sIIARXih1DTaQAX4SsiTXhInKf1buxdY9DIg4ZYPZK5nGM1VRIYmEbDbsHt7USo99xSLFu5Q1IqTmsg==}
engines: {node: '>= 18'}
@@ -274,6 +485,9 @@ packages:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
+ resolution: {integrity: sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==}
+
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
@@ -298,6 +512,125 @@ snapshots:
'@cfworker/[email protected]': {}
+ '@inquirer/[email protected]': {}
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/ansi': 2.0.7
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/figures': 2.0.7
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/ansi': 2.0.7
+ '@inquirer/figures': 2.0.7
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ cli-width: 4.1.0
+ fast-wrap-ansi: 0.2.2
+ mute-stream: 3.0.0
+ signal-exit: 4.1.0
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/external-editor': 3.0.3(@types/[email protected])
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ chardet: 2.2.0
+ iconv-lite: 0.7.3
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected]': {}
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/ansi': 2.0.7
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/checkbox': 5.2.1(@types/[email protected])
+ '@inquirer/confirm': 6.1.1(@types/[email protected])
+ '@inquirer/editor': 5.2.2(@types/[email protected])
+ '@inquirer/expand': 5.1.1(@types/[email protected])
+ '@inquirer/input': 5.1.2(@types/[email protected])
+ '@inquirer/number': 4.1.1(@types/[email protected])
+ '@inquirer/password': 5.1.1(@types/[email protected])
+ '@inquirer/rawlist': 5.3.1(@types/[email protected])
+ '@inquirer/search': 4.2.1(@types/[email protected])
+ '@inquirer/select': 5.2.1(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/figures': 2.0.7
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/ansi': 2.0.7
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/figures': 2.0.7
+ '@inquirer/type': 4.0.7(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 22.19.17
+
+ '@inquirer/[email protected](@types/[email protected])':
+ optionalDependencies:
+ '@types/node': 22.19.17
+
'@jsdevtools/[email protected]': {}
'@modelcontextprotocol/[email protected]':
@@ -309,6 +642,48 @@ snapshots:
'@modelcontextprotocol/core': 2.0.0-beta.4
zod: 4.4.3
+ '@octokit/[email protected]': {}
+
+ '@octokit/[email protected]':
+ dependencies:
+ '@octokit/auth-token': 6.0.0
+ '@octokit/graphql': 9.0.3
+ '@octokit/request': 10.0.11
+ '@octokit/request-error': 7.1.0
+ '@octokit/types': 16.0.0
+ before-after-hook: 4.0.0
+ universal-user-agent: 7.0.3
+
+ '@octokit/[email protected]':
+ dependencies:
+ '@octokit/types': 16.0.0
+ universal-user-agent: 7.0.3
+
+ '@octokit/[email protected]':
+ dependencies:
+ '@octokit/request': 10.0.11
+ '@octokit/types': 16.0.0
+ universal-user-agent: 7.0.3
+
+ '@octokit/[email protected]': {}
+
+ '@octokit/[email protected]':
+ dependencies:
+ '@octokit/types': 16.0.0
+
+ '@octokit/[email protected]':
+ dependencies:
+ '@octokit/endpoint': 11.0.3
+ '@octokit/request-error': 7.1.0
+ '@octokit/types': 16.0.0
+ content-type: 2.0.0
+ json-with-bigint: 3.5.10
+ universal-user-agent: 7.0.3
+
+ '@octokit/[email protected]':
+ dependencies:
+ '@octokit/openapi-types': 27.0.0
+
'@openai/[email protected]':
dependencies:
'@openai/codex': 0.144.6
@@ -374,12 +749,20 @@ snapshots:
+
dependencies:
'@types/node': 22.19.17
+
+
+
dependencies:
ms: 2.1.3
@@ -400,8 +783,18 @@ snapshots:
+
+ dependencies:
+ fast-string-truncated-width: 3.0.3
+
+ dependencies:
+ fast-string-width: 3.0.2
+
dependencies:
pend: 1.2.0
@@ -416,6 +809,10 @@ snapshots:
dependencies:
pump: 3.0.4
+ dependencies:
+ safer-buffer: 2.1.2
+
dependencies:
'@cfworker/json-schema': 4.1.1
@@ -450,12 +847,16 @@ snapshots:
+
+
dependencies:
wrappy: 1.0.2
@@ -475,6 +876,10 @@ snapshots:
+
+
@@ -488,6 +893,8 @@ snapshots:
+
diff --git a/sdk/typescript/src/bulk-scan-discovery.ts b/sdk/typescript/src/bulk-scan-discovery.ts
index b84f3b4e7..e3c1848d3 100644
--- a/sdk/typescript/src/bulk-scan-discovery.ts
+++ b/sdk/typescript/src/bulk-scan-discovery.ts
@@ -1,119 +1,54 @@
-import { spawn } from "node:child_process";
+import { execFile as execFileCallback } from "node:child_process";
import { createHash } from "node:crypto";
import { lstat, mkdir, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { stdin } from "node:process";
-import { emitKeypressEvents } from "node:readline";
-import { createInterface } from "node:readline/promises";
import { Writable } from "node:stream";
-import { z } from "incur";
+import { promisify } from "node:util";
+import { confirm, input, select } from "@inquirer/prompts";
+import { Octokit } from "@octokit/core";
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 execFile = promisify(execFileCallback);
const GITHUB_REPOSITORIES_QUERY = `
- query($owner: String!, $endCursor: String, $privacy: RepositoryPrivacy) {
+ query($owner: String!, $cursor: String) {
repositoryOwner(login: $owner) {
repositories(
first: 100
- after: $endCursor
- privacy: $privacy
+ after: $cursor
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[];
+interface GitHubRepository {
+ fullName: string;
+ url: string;
+ revision: string;
}
-const DEFAULT_REPOSITORY_FILTERS: BulkScanRepositoryFilters = {
- nameKeywords: [],
- activeWithinDays: DEFAULT_ACTIVITY_DAYS,
- language: null,
- visibility: ["PRIVATE", "INTERNAL"],
-};
-
-export interface BulkScanCommandResult {
- exitCode: number;
- stdout: string;
- stderr: string;
+interface GitHubRepositoriesResponse {
+ repositoryOwner: {
+ repositories: {
+ nodes: Array<{
+ nameWithOwner: string;
+ pushedAt: string;
+ defaultBranchRef: { target: { oid: string } } | null;
+ }>;
+ pageInfo: { hasNextPage: boolean; endCursor: string | null };
+ };
+ } | null;
}
export interface BulkScanPrompt {
@@ -124,13 +59,7 @@ export interface BulkScanPrompt {
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 {
@@ -138,29 +67,13 @@ export interface BulkScanDiscoveryDependencies {
now(): number;
currentDirectory(): string;
githubHost?: string;
- runGitHub(
- args: readonly string[],
- options?: { host?: string; interactive?: boolean; signal?: AbortSignal },
- ): Promise<BulkScanCommandResult>;
+ createGitHub(host: string, signal?: AbortSignal): Promise<Octokit>;
}
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;
+ githubHost: string;
}
interface PromptOutput {
@@ -180,7 +93,7 @@ export function createBulkScanDiscoveryDependencies(options: {
...(process.env["GH_HOST"]?.trim()
? { githubHost: process.env["GH_HOST"].trim() }
: {}),
- runGitHub: async (args, commandOptions = {}) => {
+ createGitHub: async (host, signal) => {
const trusted = await resolveTrustedExecutable(
"gh",
process.env,
@@ -188,21 +101,28 @@ export function createBulkScanDiscoveryDependencies(options: {
);
if (trusted === null) {
throw new Error(
- "GitHub CLI is required to discover repositories. Install gh, then run 'codex-security bulk-scan' again.",
+ "GitHub CLI is required. Install gh and sign in first.",
);
}
- const environment = {
- ...trusted.environment,
- ...(commandOptions.host === undefined
- ? {}
- : { GH_HOST: commandOptions.host }),
- };
- return await runGitHubCommand(
- trusted.executable,
- args,
- environment,
- commandOptions,
- );
+
+ let token: string;
+ try {
+ const { stdout } = await execFile(
+ trusted.executable,
+ ["auth", "token", "--hostname", host],
+ { env: trusted.environment, signal },
+ );
+ token = stdout.trim();
+ } catch {
+ signal?.throwIfAborted();
+ throw new Error(
+ "GitHub sign-in is required. Run 'gh auth login' first.",
+ );
+ }
+ return new Octokit({
+ auth: token,
+ ...(host === "github.com" ? {} : { baseUrl: `https://${host}/api/v3` }),
+ });
},
};
}
@@ -218,711 +138,201 @@ export async function runBulkScanWizard(
);
}
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);
+ const githubHost = dependencies.githubHost ?? "github.com";
+ const github = await dependencies.createGitHub(githubHost, signal);
+ const owner = await selectGitHubOwner(github, prompt, signal);
+ const names = await prompt.input(
+ "Repository name contains (comma-separated; leave blank for all)",
+ );
+ const keywords = names
+ .split(",")
+ .map((name) => name.trim().toLowerCase())
+ .filter(Boolean);
+ prompt.write("\nFinding active repositories...\n");
+ const repositories = await discoverGitHubRepositories(
+ github,
+ githubHost,
+ owner,
+ keywords,
+ dependencies.now() - 90 * 86_400_000,
+ signal,
+ );
+ if (repositories.length === 0) {
+ prompt.write("\nNo repositories matched your selection.\n");
+ return null;
}
- prompt.write(`\nFound ${repositoryNames.length} repositories:\n\n`);
- for (const repository of repositoryNames.slice(0, PREVIEW_LIMIT)) {
- prompt.write(` ${repository}\n`);
+ prompt.write(`\nFound ${repositories.length} repositories:\n`);
+ for (const { fullName } of repositories.slice(0, 10)) {
+ prompt.write(` ${fullName}\n`);
}
- if (repositoryNames.length > PREVIEW_LIMIT) {
- prompt.write(`\n and ${repositoryNames.length - PREVIEW_LIMIT} more\n`);
+ if (repositories.length > 10) {
+ prompt.write(` and ${repositories.length - 10} more\n`);
}
- const selectedOutput = await prompt.input(
- "\nWhere should scan results be saved?",
- "./security-scans",
- );
const outputDir = resolve(
dependencies.currentDirectory(),
- selectedOutput.trim() || "./security-scans",
+ await prompt.input(
+ "Where should scan results be saved?",
+ "./security-scans",
+ ),
);
- const inputPath = providedInput ?? join(outputDir, "repositories.csv");
- await validateWizardOutput(outputDir, providedInput === undefined);
+ const inputPath = join(outputDir, "repositories.csv");
+ await validateWizardOutput(outputDir);
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`),
+ `\nReady to scan ${repositories.length} repositories?\n` +
+ `Results: ${outputDir}\nRepository list: ${inputPath}\n`,
);
- if (!(await prompt.confirm("Start scanning?", false))) {
+ if (!(await prompt.confirm("Start scanning?"))) {
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 })),
+ await mkdir(outputDir, { recursive: true, mode: 0o700 });
+ await writeFile(
+ inputPath,
+ `${Papa.unparse(
+ repositories.map(({ fullName, url, revision }) => ({
+ id: repositoryId(fullName),
+ repository: url,
+ revision,
+ })),
+ )}\n`,
+ { flag: "wx", mode: 0o600, ...(signal === undefined ? {} : { signal }) },
);
-}
-
-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();
+ return { inputPath, outputDir, githubHost };
}
async function selectGitHubOwner(
- dependencies: BulkScanDiscoveryDependencies,
- host: string,
+ github: Octokit,
+ prompt: BulkScanPrompt,
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,
+ const { data } = await github.request("GET /user/orgs", {
+ per_page: 100,
+ request: { 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.");
+ const organizations = data.map(({ login }) => login).sort();
+ if (organizations.length > 1) {
+ return await prompt.select(
+ "Which account or organization should we scan?",
+ organizations.map((owner) => ({ label: owner, value: owner })),
+ );
}
- dependencies.prompt.write(`\nSearching repositories in ${owner}.\n`);
+ const owner =
+ organizations[0] ??
+ (await github.request("GET /user", { request: { signal } })).data.login;
+ prompt.write(`\nFinding repositories in ${owner}.\n`);
return owner;
}
async function discoverGitHubRepositories(
- dependencies: BulkScanDiscoveryDependencies,
+ github: Octokit,
host: string,
owner: string,
- filters: BulkScanRepositoryFilters,
+ keywords: string[],
+ cutoff: number,
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;
+ let cursor: string | null = null;
- while (true) {
+ do {
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.",
+ const result: GitHubRepositoriesResponse = await github.graphql(
+ GITHUB_REPOSITORIES_QUERY,
+ { owner, cursor, request: { signal } },
);
- if (page.errors?.length || page.data.repositoryOwner === null) {
+ const connection = result.repositoryOwner?.repositories;
+ if (connection === undefined) {
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 (Date.parse(repository.pushedAt) < cutoff) return repositories;
+ const name = repository.nameWithOwner.split("/").at(-1)!;
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())
+ (keywords.length > 0 &&
+ !keywords.some((keyword) => name.toLowerCase().includes(keyword)))
) {
continue;
}
repositories.push({
fullName: repository.nameWithOwner,
- url: validateRepositoryUrl(repository.url, host),
+ url: `https://${host}/${repository.nameWithOwner}.git`,
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;
-}
+ cursor = connection.pageInfo.hasNextPage
+ ? connection.pageInfo.endCursor
+ : null;
+ } while (cursor !== null);
-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();
+ return repositories;
}
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}`;
+ const id = fullName.replace("/", "--");
+ if (id.length <= 128) return id;
+ const hash = createHash("sha256").update(fullName).digest("hex").slice(0, 16);
+ return `${id.slice(0, 111)}-${hash}`;
}
-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()) {
+async function validateWizardOutput(outputDir: string): Promise<void> {
+ let metadata;
+ try {
+ metadata = await lstat(outputDir);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
+ throw error;
+ }
+ if (!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.",
- );
+ try {
+ await lstat(join(outputDir, name));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
+ throw error;
}
+ 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 {
+ const context = () => ({
+ input: stdin,
+ output: new Writable({
+ write(chunk: Buffer, _encoding, callback) {
+ output.write(chunk.toString("utf8"));
+ callback();
+ },
+ }),
});
-}
-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);
- });
- },
+ confirm: (message, defaultValue = false) =>
+ confirm({ message, default: defaultValue }, context()),
+ input: (message, defaultValue) =>
+ input({ message, default: defaultValue }, context()),
+ select: (message, options) =>
+ select(
+ {
+ message,
+ choices: options.map(({ label, value }) => ({ name: label, value })),
+ },
+ context(),
+ ),
};
}
-
-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.ts
index dccb42049..a2ff09b7b 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -28,7 +28,6 @@ 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,
@@ -757,7 +756,9 @@ export async function main(
} catch (error) {
exitCode =
interruptedExitCode() ??
- (error instanceof BulkScanInterruptedError ? 130 : 2);
+ (error instanceof Error && error.name === "ExitPromptError"
+ ? 130
+ : 2);
errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
} finally {
dependencies.removeSignalListener("SIGINT", onInterrupt);
diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.ts
index d934d22d2..05c19a776 100644
--- a/sdk/typescript/src/multiscan.ts
+++ b/sdk/typescript/src/multiscan.ts
@@ -70,21 +70,6 @@ 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> {
diff --git a/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts b/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts
index 4bf04dd8c..e3f21771d 100644
--- a/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts
+++ b/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts
@@ -8,10 +8,10 @@ import {
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { Octokit } from "@octokit/core";
import { afterEach, describe, expect, test } from "bun:test";
import {
runBulkScanWizard,
- type BulkScanCommandResult,
type BulkScanDiscoveryDependencies,
type BulkScanPrompt,
} from "../src/bulk-scan-discovery.js";
@@ -37,12 +37,10 @@ async function temporaryDirectory(): Promise<string> {
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;
@@ -52,172 +50,165 @@ class FakePrompt implements BulkScanPrompt {
this.messages.push(value);
}
- public async confirm(
- question: string,
- defaultValue = false,
- ): Promise<boolean> {
+ public async confirm(question: string, fallback = false): Promise<boolean> {
this.questions.push(question);
- return this.confirms.shift() ?? defaultValue;
+ return this.confirms.shift() ?? fallback;
}
- public async input(question: string, defaultValue?: string): Promise<string> {
+ public async input(question: string, fallback = ""): Promise<string> {
this.questions.push(question);
- return this.inputs.shift() ?? defaultValue ?? "";
+ return this.inputs.shift() ?? fallback;
}
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;
+ const value = this.choices.shift();
+ return (options.find((option) => option.value === value) ?? options[0]!)
+ .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);
- }
+interface Repository {
+ fullName: string;
+ visibility?: "private" | "internal" | "public";
+ archived?: boolean;
+ fork?: boolean;
+ empty?: boolean;
+ pushedAt?: string;
}
-function success(stdout: string): BulkScanCommandResult {
- return { exitCode: 0, stdout, stderr: "" };
+interface GitHubRequest {
+ path: string;
+ query?: string;
+ variables?: { owner: string; cursor: string | null };
}
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;
- }>;
+ repositories?: Repository[];
authenticated?: boolean;
} = {},
): {
dependencies: BulkScanDiscoveryDependencies;
prompt: FakePrompt;
- commands: Array<{ args: readonly string[]; host?: string }>;
+ hosts: string[];
+ requests: GitHubRequest[];
} {
- const prompt = options.prompt ?? new FakePrompt();
+ const 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 },
+ { fullName: "acme/public-api", visibility: "public" as const },
];
- const commands: Array<{ args: readonly string[]; host?: string }> = [];
- let authenticated = options.authenticated ?? true;
- const dependencies: BulkScanDiscoveryDependencies = {
+ const hosts: string[] = [];
+ const requests: GitHubRequest[] = [];
+
+ return {
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
+ hosts,
+ requests,
+ dependencies: {
+ prompt,
+ now: () => NOW,
+ currentDirectory: () => root,
+ ...(options.host === undefined ? {} : { githubHost: host }),
+ createGitHub: async (githubHost) => {
+ hosts.push(githubHost);
+ if (options.authenticated === false) {
+ throw new Error(
+ "GitHub sign-in is required. Run 'gh auth login' first.",
+ );
+ }
+
+ return new Octokit({
+ auth: "test-token",
+ baseUrl:
+ githubHost === "github.com"
+ ? "https://api.github.com"
+ : `https://${githubHost}/api/v3`,
+ request: {
+ fetch: async (
+ resource: Parameters<typeof fetch>[0],
+ init?: Parameters<typeof fetch>[1],
+ ) => {
+ const url = new URL(
+ resource instanceof Request ? resource.url : resource,
+ );
+ const path = url.pathname.replace(/^\/api(?:\/v3)?/u, "");
+ const body =
+ init?.body === undefined
+ ? undefined
+ : (JSON.parse(String(init.body)) as {
+ query: string;
+ variables: GitHubRequest["variables"];
+ });
+ requests.push({
+ path,
+ ...(body === undefined
+ ? {}
+ : { query: body.query, variables: body.variables }),
+ });
+
+ if (path === "/user/orgs") {
+ return Response.json(
+ (options.organizations ?? ["acme"]).map((login) => ({
+ login,
+ })),
+ );
+ }
+ if (path === "/user") {
+ return Response.json({ login: "personal-account" });
+ }
+ if (path !== "/graphql" || body === undefined) {
+ throw new Error(`Unexpected GitHub request: ${path}`);
+ }
+
+ const visible = repositories.filter(
+ ({ archived, fork }) => !archived && !fork,
+ );
+ const start = Number(body.variables?.cursor ?? 0);
+ const page = visible.slice(start, start + 100);
+ const next = start + page.length;
+ return Response.json({
+ data: {
+ repositoryOwner: {
+ repositories: {
+ nodes: page.map((repository) => ({
+ nameWithOwner: repository.fullName,
+ pushedAt: repository.pushedAt ?? "2026-07-20T00:00:00Z",
+ defaultBranchRef: repository.empty
? null
- : { name: repository.language },
- defaultBranchRef: repository.empty
- ? null
- : { target: { oid: REVISION } },
- })),
- pageInfo: {
- hasNextPage: next < repositories.length,
- endCursor:
- next < repositories.length ? String(next) : null,
+ : { target: { oid: REVISION } },
+ })),
+ pageInfo: {
+ hasNextPage: next < visible.length,
+ endCursor: next < visible.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 () => {
+ test("discovers active public, private, and internal repositories with Octokit", async () => {
const root = await temporaryDirectory();
- const { dependencies, prompt, commands } = discoveryDependencies(root);
- prompt.confirms = [false, true, true];
- prompt.inputs = ["./security-scans"];
+ const { dependencies, prompt, hosts, requests } =
+ discoveryDependencies(root);
+ prompt.confirms = [true];
const result = await runBulkScanWizard(dependencies);
@@ -226,542 +217,175 @@ describe("bulk scan repository discovery", () => {
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(hosts).toEqual(["github.com"]);
+ const query = requests.find(({ path }) => path === "/graphql")?.query;
+ expect(query).not.toContain("privacy:");
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?",
- );
+ expect(csv).toContain("acme--identity-service");
+ expect(csv).toContain("acme--public-api");
+ expect(prompt.messages.join("")).toContain("Found 3 repositories");
});
- test("discovers more than 100 active repositories across GitHub pages", async () => {
+ test("paginates repositories and stops at the 90-day cutoff", 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, {
+ const active = Array.from({ length: 101 }, (_value, index) => ({
+ fullName: `acme/service-${index}`,
+ }));
+ const { dependencies, prompt, requests } = 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",
- })),
+ ...active,
+ { fullName: "acme/old", pushedAt: "2026-04-01T00:00:00Z" },
+ ...active,
],
});
- prompt.confirms = [false, true, true];
+ prompt.confirms = [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);
+ expect(requests.filter(({ path }) => path === "/graphql")).toHaveLength(2);
const csv = await readFile(result!.inputPath, "utf8");
- expect(csv).toContain("acme--active-service");
- expect(csv).not.toContain("old-service");
+ expect(csv).toContain("acme--service-100");
+ expect(csv).not.toContain("acme--old");
});
- test("matches any custom repository-name keyword without GitHub search", async () => {
+ test("filters repository names with case-insensitive keywords", async () => {
const root = await temporaryDirectory();
- const { dependencies, prompt, commands } = discoveryDependencies(root, {
+ const { dependencies, prompt } = discoveryDependencies(root, {
repositories: [
{ fullName: "acme/owl" },
{ fullName: "acme/openai" },
- { fullName: "acme/openai-public", visibility: "public" },
- { fullName: "acme/unrelated-service" },
+ { fullName: "acme/unrelated" },
],
});
- prompt.confirms = [false, true, true];
- prompt.choices = ["custom"];
- prompt.inputs = [" OwL, OPENAI ", "", "./custom-results"];
+ prompt.confirms = [true];
+ 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");
+ expect(csv).not.toContain("unrelated");
});
- test("filters repositories by primary language case-insensitively", async () => {
+ test("includes public repositories and excludes archived, forked, and empty repositories", 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",
- },
+ { fullName: "acme/service" },
+ { fullName: "acme/public", visibility: "public" },
+ { fullName: "acme/archive", archived: true },
+ { fullName: "acme/fork", fork: true },
+ { fullName: "acme/empty", empty: true },
],
});
- prompt.confirms = [false, true, true];
- prompt.choices = ["custom", "all"];
- prompt.inputs = ["", "", "./all-time-results"];
+ prompt.confirms = [true];
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);
+ expect(csv).toContain("acme--service");
+ expect(csv).toContain("acme--public");
+ expect(csv).not.toContain("archive");
+ expect(csv).not.toContain("fork");
+ expect(csv).not.toContain("empty");
});
- test("honors a configured GitHub Enterprise host", async () => {
+ test("honors GitHub Enterprise hosts", async () => {
const root = await temporaryDirectory();
- const { dependencies, prompt, commands } = discoveryDependencies(root, {
+ const { dependencies, prompt, hosts } = discoveryDependencies(root, {
host: "github.acme.example",
});
- prompt.confirms = [false, true, true];
+ prompt.confirms = [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(hosts).toEqual(["github.acme.example"]);
expect(await readFile(result!.inputPath, "utf8")).toContain(
"https://github.acme.example/acme/payments-api.git",
);
});
- test("confirms GitHub sign-in before discovering repositories", async () => {
+ test("requires an existing GitHub sign-in", async () => {
const root = await temporaryDirectory();
- const { dependencies, prompt, commands } = discoveryDependencies(root, {
+ const { dependencies, requests } = 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",
+ "Run 'gh auth login' first",
);
- 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([]);
+ expect(requests).toEqual([]);
});
- test("asks for an owner only when several organizations are available", async () => {
+ test("asks for the 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"];
+ prompt.confirms = [true];
+ prompt.choices = ["acme"];
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`,
+ "Which account or organization should we scan?",
);
- 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("does not write an inventory when canceled or no repositories match", async () => {
+ for (const options of [
+ { confirms: [false] },
+ { confirms: [], repositories: [] },
+ ]) {
+ const root = await temporaryDirectory();
+ const { dependencies, prompt } = discoveryDependencies(root, options);
+ prompt.confirms = options.confirms;
+
+ expect(await runBulkScanWizard(dependencies)).toBeNull();
+ await expect(lstat(join(root, "security-scans"))).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ }
});
- test("rejects an existing scan instead of replacing its repository list", async () => {
+ test("rejects an existing scan without replacing its inventory", 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 inventory = join(output, "repositories.csv");
+ await mkdir(output);
+ await writeFile(inventory, "do not overwrite\n");
const { dependencies, prompt } = discoveryDependencies(root);
- prompt.confirms = [false, true];
- prompt.inputs = ["./existing-results"];
+ 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");
+ expect(await readFile(inventory, "utf8")).toBe("do not overwrite\n");
});
- test("rejects interactive discovery without a terminal", async () => {
+ test("requires an interactive terminal and honors cancellation", async () => {
const root = await temporaryDirectory();
- const { dependencies, prompt, commands } = discoveryDependencies(root);
+ const { dependencies, prompt, requests } = 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);
+ prompt.interactive = true;
const controller = new AbortController();
controller.abort();
-
await expect(
runBulkScanWizard(dependencies, controller.signal),
).rejects.toThrow();
expect(prompt.questions).toEqual([]);
- expect(commands).toEqual([]);
+ expect(requests).toEqual([]);
});
});
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index 8ef7f9714..d0e58663a 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -554,50 +554,6 @@ describe("CLI", () => {
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,