@openai/codex-security 0.1.29 → 0.1.31
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.
- package/README.md +106 -5
- package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
- package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
- package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +19 -4
- package/_bundled_plugin/scripts/rank_preview.py +1 -0
- package/dist/auth.js +1 -1
- package/dist/auth.js.map +1 -1
- package/dist/cli.d.ts +4 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +108 -8
- package/dist/cli.js.map +1 -1
- package/dist/deduplication/codex-review.d.ts +2 -7
- package/dist/deduplication/codex-review.d.ts.map +1 -1
- package/dist/deduplication/codex-review.js.map +1 -1
- package/dist/deduplication/deduplication-prompts.d.ts +2 -0
- package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
- package/dist/deduplication/deduplication-prompts.js +2 -2
- package/dist/deduplication/deduplication-prompts.js.map +1 -1
- package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
- package/dist/deduplication/deduplication-reviewer.js +4 -10
- package/dist/deduplication/deduplication-reviewer.js.map +1 -1
- package/dist/deduplication/finding-schema.d.ts +4 -0
- package/dist/deduplication/finding-schema.d.ts.map +1 -0
- package/dist/deduplication/finding-schema.js +14 -0
- package/dist/deduplication/finding-schema.js.map +1 -0
- package/dist/deduplication/records-protocol.d.ts +9 -0
- package/dist/deduplication/records-protocol.d.ts.map +1 -0
- package/dist/deduplication/records-protocol.js +191 -0
- package/dist/deduplication/records-protocol.js.map +1 -0
- package/dist/deduplication/records.d.ts +33 -0
- package/dist/deduplication/records.d.ts.map +1 -0
- package/dist/deduplication/records.js +134 -0
- package/dist/deduplication/records.js.map +1 -0
- package/dist/deduplication/review.d.ts +21 -0
- package/dist/deduplication/review.d.ts.map +1 -0
- package/dist/deduplication/review.js +2 -0
- package/dist/deduplication/review.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/knowledge-base.js +5 -1
- package/dist/knowledge-base.js.map +1 -1
- package/dist/owner-evidence.d.ts +29 -0
- package/dist/owner-evidence.d.ts.map +1 -0
- package/dist/owner-evidence.js +196 -0
- package/dist/owner-evidence.js.map +1 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +27 -14
- package/dist/runtime.js.map +1 -1
- package/dist/scan-comparison.d.ts +1 -1
- package/dist/scan-comparison.d.ts.map +1 -1
- package/dist/scan-comparison.js.map +1 -1
- package/dist/suggest-owners.d.ts +38 -0
- package/dist/suggest-owners.d.ts.map +1 -0
- package/dist/suggest-owners.js +112 -0
- package/dist/suggest-owners.js.map +1 -0
- package/dist/targets.d.ts +6 -2
- package/dist/targets.d.ts.map +1 -1
- package/dist/targets.js +5 -4
- package/dist/targets.js.map +1 -1
- package/dist/thread-source.d.ts +1 -0
- package/dist/thread-source.d.ts.map +1 -1
- package/dist/thread-source.js +1 -0
- package/dist/thread-source.js.map +1 -1
- package/docs/dedupe-records.md +305 -0
- package/package.json +13 -11
package/README.md
CHANGED
|
@@ -598,6 +598,9 @@ execution failure writes one structured object to stdout:
|
|
|
598
598
|
}
|
|
599
599
|
```
|
|
600
600
|
|
|
601
|
+
With `--full-output`, the same code and message are reported under `error` in
|
|
602
|
+
an `ok: false` envelope instead.
|
|
603
|
+
|
|
601
604
|
The command still exits with `2` for runtime, export, invalid-input, or
|
|
602
605
|
incomplete-scan failures, and human-readable diagnostics remain on stderr.
|
|
603
606
|
Use `scan --schema --format json` to discover this failure variant alongside
|
|
@@ -1422,6 +1425,53 @@ once before they can be reused.
|
|
|
1422
1425
|
Pass `signal` to cancel any classification operation. Keep human overrides in the
|
|
1423
1426
|
calling workflow or issue tracker; assessments remain separate recommendations.
|
|
1424
1427
|
|
|
1428
|
+
### Suggest finding owners
|
|
1429
|
+
|
|
1430
|
+
Suggest contributors who can fix findings in a local Git repository:
|
|
1431
|
+
|
|
1432
|
+
```bash
|
|
1433
|
+
npx @openai/codex-security suggest-owners findings.json --source-root /path/to/repo --json > owners.json
|
|
1434
|
+
```
|
|
1435
|
+
|
|
1436
|
+
The input is a Codex Security findings document or a JSON object containing a
|
|
1437
|
+
`findings` array, such as the output of `export --export-format json`. The source
|
|
1438
|
+
root defaults to the current directory. The command reads committed `HEAD`,
|
|
1439
|
+
source around each finding location, blame for the affected lines, and file
|
|
1440
|
+
history reachable from that commit. It does not read uncommitted source or change
|
|
1441
|
+
findings, files, or ticket assignments.
|
|
1442
|
+
|
|
1443
|
+
The checkout must own its Git references and objects. Linked worktrees and bound
|
|
1444
|
+
separate Git directories are supported. Checkouts that borrow external object
|
|
1445
|
+
stores, including `git clone --shared`, are rejected; use an independent clone.
|
|
1446
|
+
|
|
1447
|
+
Each result preserves the finding and occurrence IDs and has status `identified`,
|
|
1448
|
+
`abstained`, or `error`. Identified results include an observed Git author name
|
|
1449
|
+
and email, a reason, and checked Git citations. Missing source or unclear
|
|
1450
|
+
ownership produces an abstention. Git identities do not establish active
|
|
1451
|
+
employment or an issue tracker account. Match accounts before assigning tickets.
|
|
1452
|
+
Use a checkout that matches the findings; otherwise their line ranges may be stale.
|
|
1453
|
+
|
|
1454
|
+
The command uses existing Codex credentials and the Codex Security default model and effort.
|
|
1455
|
+
Use `--model` and `--effort` to override them. Model selection runs with tools and
|
|
1456
|
+
network access disabled. Exit code `0` includes successful recommendations and
|
|
1457
|
+
abstentions; `2` means invalid input or at least one failed recommendation. A
|
|
1458
|
+
per-finding failure retains the other results in the report. Cancellation uses
|
|
1459
|
+
exit code `130` for SIGINT or `143` for SIGTERM.
|
|
1460
|
+
|
|
1461
|
+
The SDK accepts finding IDs, titles, summaries, and source locations directly:
|
|
1462
|
+
|
|
1463
|
+
```ts
|
|
1464
|
+
import { suggestOwners } from "@openai/codex-security";
|
|
1465
|
+
|
|
1466
|
+
const owners = await suggestOwners("/path/to/repo", result.findings, {
|
|
1467
|
+
reasoningEffort: "high",
|
|
1468
|
+
});
|
|
1469
|
+
```
|
|
1470
|
+
|
|
1471
|
+
SDK inputs may include `sourceRevision`. If it differs from `HEAD`, the collector
|
|
1472
|
+
ignores the old line ranges and reports the mismatch. Reports record the analyzed
|
|
1473
|
+
revision, model, effort, and limitations; they remain separate from scan artifacts.
|
|
1474
|
+
|
|
1425
1475
|
### Feedback
|
|
1426
1476
|
|
|
1427
1477
|
Send a problem report to OpenAI and share the returned feedback ID with support:
|
|
@@ -1608,9 +1658,45 @@ runtime/export error, `130` for interruption, and `143` for termination.
|
|
|
1608
1658
|
JSON scans do not use interactive controls. `validate`, `login`, and `logout`
|
|
1609
1659
|
reject `--json`.
|
|
1610
1660
|
|
|
1611
|
-
`install-hook`
|
|
1612
|
-
|
|
1613
|
-
|
|
1661
|
+
`install-hook` adds an optional local Git pre-commit check for staged and
|
|
1662
|
+
unstaged changes. It's advisory; use a required CI check to enforce a passing
|
|
1663
|
+
scan. When Git runs the hook, it blocks commits if the scan can't finish or
|
|
1664
|
+
finds an issue at or above the threshold (`high` by default). Set it when
|
|
1665
|
+
installing with `--fail-on-severity`. The installer respects `core.hooksPath`
|
|
1666
|
+
and leaves custom hooks alone.
|
|
1667
|
+
|
|
1668
|
+
We recommend installing the CLI outside the repository and running that copy
|
|
1669
|
+
directly. For a global installation:
|
|
1670
|
+
|
|
1671
|
+
```bash
|
|
1672
|
+
npm install --global @openai/codex-security
|
|
1673
|
+
```
|
|
1674
|
+
|
|
1675
|
+
If the repository also has a local copy, `npx` may run it instead.
|
|
1676
|
+
|
|
1677
|
+
Before installing or replacing a hook, run
|
|
1678
|
+
`git -C /path/to/repository rev-parse --git-path hooks/pre-commit`. Git may
|
|
1679
|
+
return a path relative to `/path/to/repository`. Check the hook, if it exists,
|
|
1680
|
+
and the path to its directory for symlinks or shared locations. Leave custom,
|
|
1681
|
+
linked, shared, or unverified hooks alone. If they need to change, contact the
|
|
1682
|
+
owner or use a required CI check. Check older generated hooks too; the installer
|
|
1683
|
+
can update them automatically.
|
|
1684
|
+
|
|
1685
|
+
If the hooks directory belongs only to this repository and there is no hook,
|
|
1686
|
+
run the global CLI from outside the repository:
|
|
1687
|
+
|
|
1688
|
+
```bash
|
|
1689
|
+
codex-security install-hook /path/to/repository
|
|
1690
|
+
```
|
|
1691
|
+
|
|
1692
|
+
To migrate a hook, confirm it's a regular file used only by this repository
|
|
1693
|
+
and contains only the generated Codex Security command. Keep its severity.
|
|
1694
|
+
The installer can update older hooks that invoke `npx` if you use the same
|
|
1695
|
+
severity. Newer hooks store absolute paths to Node and the CLI. If either path
|
|
1696
|
+
changes, the installer won't replace the hook: back it up, remove it, and rerun
|
|
1697
|
+
`codex-security install-hook /path/to/repository` with the same
|
|
1698
|
+
`--fail-on-severity` value (default: `high`). If reinstallation fails, restore
|
|
1699
|
+
the backup and verify the hook before relying on it.
|
|
1614
1700
|
|
|
1615
1701
|
### Import alerts from the CLI
|
|
1616
1702
|
|
|
@@ -2069,6 +2155,18 @@ shape. No command, flag, or default changes are required.
|
|
|
2069
2155
|
This behavior applies to post-scan Luna/Sol deduplication. Deep Scan's internal
|
|
2070
2156
|
reducer uses a separate workflow.
|
|
2071
2157
|
|
|
2158
|
+
### Host-provided records deduplication
|
|
2159
|
+
|
|
2160
|
+
`codex-security dedupe --records` accepts a versioned JSON-RPC run over stdin
|
|
2161
|
+
and emits serial `review.run` requests on stdout for a host-provided model
|
|
2162
|
+
backend. It requires no saved scan or Findings API and performs no local model
|
|
2163
|
+
execution or persistence. The SDK exposes `deduplicateRecords(input,
|
|
2164
|
+
{ reviewRunner, signal })`. The input contains original observations and explicit candidate links. Results
|
|
2165
|
+
contain groups of observation IDs and unresolved observations.
|
|
2166
|
+
|
|
2167
|
+
See the [records protocol and Python fake-host example](docs/dedupe-records.md)
|
|
2168
|
+
for the complete input, review contract, cancellation, and persistence rules.
|
|
2169
|
+
|
|
2072
2170
|
### Stored duplicate groups
|
|
2073
2171
|
|
|
2074
2172
|
`POST /v1/dedupe-groups` accepts a batch of explicitly reviewed member sets:
|
|
@@ -2491,8 +2589,9 @@ Compose accepts `CODEX_SECURITY_IMAGE`, `CODEX_SECURITY_USER`,
|
|
|
2491
2589
|
`CODEX_SECURITY_SECCOMP`, `CODEX_SECURITY_CSV`, `CODEX_SECURITY_RESULTS`, and
|
|
2492
2590
|
`CODEX_SECURITY_STATE` for the image, user, seccomp profile, and mounts.
|
|
2493
2591
|
|
|
2592
|
+
Codex 0.156.1 requires Bubblewrap for filesystem-restricted execution on Linux.
|
|
2494
2593
|
On Ubuntu hosts that restrict unprivileged user namespaces, an administrator
|
|
2495
|
-
|
|
2594
|
+
must install the AppArmor profile and use the Compose override:
|
|
2496
2595
|
|
|
2497
2596
|
```bash
|
|
2498
2597
|
sudo install -m 0644 docker/codex-security.apparmor /etc/apparmor.d/codex-security-container
|
|
@@ -2501,7 +2600,9 @@ docker compose -f compose.yaml -f compose.apparmor.yaml run --rm codex-security
|
|
|
2501
2600
|
```
|
|
2502
2601
|
|
|
2503
2602
|
The override keeps the nonroot user, dropped capabilities, no-new-privileges,
|
|
2504
|
-
and seccomp policy.
|
|
2603
|
+
and seccomp policy. It enables the nested namespaces required by Bubblewrap.
|
|
2604
|
+
The legacy Landlock fallback is no longer supported for these scans. Other
|
|
2605
|
+
Docker hosts that permit nested user namespaces do not need this override.
|
|
2505
2606
|
|
|
2506
2607
|
## Local security model
|
|
2507
2608
|
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -6,6 +6,24 @@
|
|
|
6
6
|
"$defs": {
|
|
7
7
|
"reducerInputs": {
|
|
8
8
|
"type": "object",
|
|
9
|
+
"properties": {
|
|
10
|
+
"cursor": {
|
|
11
|
+
"type": "string",
|
|
12
|
+
"pattern": "^(0|[1-9][0-9]*)$",
|
|
13
|
+
"description": "Continue the same document from its returned nextCursor."
|
|
14
|
+
},
|
|
15
|
+
"maxBytes": {
|
|
16
|
+
"type": "integer",
|
|
17
|
+
"minimum": 1,
|
|
18
|
+
"maximum": 9007199254740991,
|
|
19
|
+
"description": "Caller-selected byte budget for the serialized MCP response. Choose below the transport and output budgets; reduce it if transport reports an oversized response."
|
|
20
|
+
},
|
|
21
|
+
"findingRef": {
|
|
22
|
+
"type": "string",
|
|
23
|
+
"description": "Omit to page assigned findings and the previous aggregate without retained provenance bodies. Use source:<sourceFindingId> to fetch a complete original, or previous:<zero-based index> to fetch a complete previous aggregate finding, including its retained history."
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"required": ["maxBytes"],
|
|
9
27
|
"additionalProperties": false
|
|
10
28
|
},
|
|
11
29
|
"reductionInput": {
|
|
@@ -31,10 +49,7 @@
|
|
|
31
49
|
"$ref": "codex-security://schemas/tools/scan-draft.schema.json#/$defs/scanDraftInput/properties/findings"
|
|
32
50
|
}
|
|
33
51
|
},
|
|
34
|
-
"required": [
|
|
35
|
-
"scanId",
|
|
36
|
-
"findings"
|
|
37
|
-
],
|
|
52
|
+
"required": ["scanId", "findings"],
|
|
38
53
|
"additionalProperties": false
|
|
39
54
|
}
|
|
40
55
|
}
|
package/dist/auth.js
CHANGED
|
@@ -228,7 +228,7 @@ function preferredAuthUrl(value) {
|
|
|
228
228
|
return null;
|
|
229
229
|
}
|
|
230
230
|
function userCodeFromOutput(value) {
|
|
231
|
-
const output = plainTerminalText(value);
|
|
231
|
+
const output = plainTerminalText(value).replace(/https?:\/\/[^\s<>"']+/g, "");
|
|
232
232
|
return (output.match(/(?:code|user code)\s*[:=]\s*([A-Z0-9-]{4,})/i)?.[1] ??
|
|
233
233
|
output.match(/\b[A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+\b/)?.[0] ??
|
|
234
234
|
null);
|
package/dist/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"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AK,WAAW;gBACxB,CAAC,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC;gBAChC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;gBACtD,QAAQ,KAAK,SAAS;gBACtB,QAAQ,KAAK,OAAO;gBACpB,QAAQ,KAAK,MAAM;gBACnB,QAAQ,KAAK,cAAc;gBAC3B,CAAC,QAAQ,CAAC,UAAU,CAAC,YAAY,CAAC;gBAClC,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,EAC7B,CAAC;gBACD,OAAO,GAAG,CAAC;YACb,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAa;IACvC,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC;IACxC,OAAO,CACL,MAAM,CAAC,KAAK,CAAC,8CAA8C,CAAC,EAAE,CAAC,CAAC,CAAC;QACjE,MAAM,CAAC,KAAK,CAAC,oCAAoC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvD,IAAI,CACL,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAa;IACtC,OAAO,KAAK;SACT,OAAO,CAAC,wCAAwC,EAAE,EAAE,CAAC;SACrD,OAAO,CAAC,4BAA4B,EAAE,EAAE,CAAC;SACzC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACxB,CAAC","sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { isIP } from \"node:net\";\nimport { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { parse } from \"smol-toml\";\nimport type { JsonObject } from \"./config.js\";\nimport { CodexSecurityError, PluginBootstrapError } from \"./errors.js\";\nimport {\n executablePathForSpawn,\n expandHome,\n runCodexCommand,\n type CodexCommand,\n type ProcessEnvironment,\n} from \"./runtime.js\";\n\nconst LOGIN_CHILD_TERMINATION_GRACE_MS = 1_000;\n\n/** @internal */\nexport function environmentEntry(\n environment: ProcessEnvironment,\n requested: string,\n): string | undefined {\n const exact = environment[requested];\n if (exact !== undefined || process.platform !== \"win32\") return exact;\n const upper = requested.toUpperCase();\n return Object.entries(environment).find(\n ([name]) => name.toUpperCase() === upper,\n )?.[1];\n}\n\n/** @internal */\nexport function configuredCodexHome(environment: ProcessEnvironment): string {\n return resolve(\n expandHome(\n environmentEntry(environment, \"CODEX_HOME\")?.trim() ||\n join(homedir(), \".codex\"),\n environment,\n ),\n );\n}\n\n/** @internal */\nexport async function readCodexHomeConfig(\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<JsonObject> {\n try {\n return parse(\n await readFile(join(configuredCodexHome(environment), \"config.toml\"), {\n encoding: \"utf8\",\n signal,\n }),\n ) as JsonObject;\n } catch (error) {\n signal?.throwIfAborted();\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw new CodexSecurityError(\n \"Could not read the configured Codex provider.\",\n );\n }\n}\n\nexport interface LoginResult {\n success: boolean;\n exitCode: number | null;\n stdout: string;\n stderr: string;\n}\n\nexport interface AccountStatus {\n authenticated: boolean;\n details: string;\n}\n\nexport class CodexLoginHandle {\n readonly #child: ChildProcessWithoutNullStreams;\n readonly #completion: Promise<LoginResult>;\n readonly #urlReady = Promise.withResolvers<void>();\n readonly #deviceReady = Promise.withResolvers<void>();\n #canceled = false;\n #forcedTermination: ReturnType<typeof setTimeout> | undefined;\n readonly #output = { stdout: \"\", stderr: \"\" };\n readonly #tails = { stdout: \"\", stderr: \"\" };\n readonly #urls: Record<\"stdout\" | \"stderr\", string | null> = {\n stdout: null,\n stderr: null,\n };\n readonly #codes: Record<\"stdout\" | \"stderr\", string | null> = {\n stdout: null,\n stderr: null,\n };\n\n public constructor(\n command: CodexCommand,\n args: readonly string[],\n environment: ProcessEnvironment,\n onSuccess: () => void | Promise<void>,\n ) {\n void this.#urlReady.promise.catch(() => undefined);\n void this.#deviceReady.promise.catch(() => undefined);\n this.#child = spawn(executablePathForSpawn(command.command), [...args], {\n env: environment,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n this.#child.stdin.end();\n this.#child.stdout.setEncoding(\"utf8\");\n this.#child.stderr.setEncoding(\"utf8\");\n this.#child.stdout.on(\"data\", (chunk: string) => {\n this.#recordOutput(\"stdout\", chunk);\n });\n this.#child.stderr.on(\"data\", (chunk: string) => {\n this.#recordOutput(\"stderr\", chunk);\n });\n this.#completion = new Promise((resolve, reject) => {\n this.#child.once(\"close\", (exitCode) => {\n clearTimeout(this.#forcedTermination);\n if (!this.#canceled) {\n this.#flushInstructionTails();\n }\n const result = {\n success: exitCode === 0 && !this.#canceled,\n exitCode,\n ...this.#output,\n };\n this.#settleInstructionWaiters(result);\n if (result.success) {\n Promise.resolve(onSuccess()).then(() => resolve(result), reject);\n } else {\n resolve(result);\n }\n });\n this.#child.once(\"error\", (error) => {\n clearTimeout(this.#forcedTermination);\n this.#settleInstructionWaiters({\n success: false,\n exitCode: null,\n stdout: this.#output.stdout,\n stderr: error.message,\n });\n reject(error);\n });\n });\n }\n\n public get loginId(): null {\n return null;\n }\n\n public get authUrl(): string | null {\n return this.#urls.stdout ?? this.#urls.stderr;\n }\n\n public get verificationUrl(): string | null {\n return this.authUrl;\n }\n\n public get userCode(): string | null {\n return this.#codes.stdout ?? this.#codes.stderr;\n }\n\n public async wait(): Promise<LoginResult> {\n return await this.#completion;\n }\n\n public async waitForInstructions(\n options: { deviceCode?: boolean } = {},\n ): Promise<void> {\n await (options.deviceCode === true ? this.#deviceReady : this.#urlReady)\n .promise;\n }\n\n public cancel(): void {\n this.#canceled = true;\n if (this.#child.exitCode !== null || this.#child.signalCode !== null)\n return;\n this.#child.kill(\"SIGTERM\");\n if (this.#forcedTermination !== undefined) return;\n this.#forcedTermination = setTimeout(() => {\n if (this.#child.exitCode === null && this.#child.signalCode === null) {\n this.#child.kill(\"SIGKILL\");\n }\n this.#child.stdin.destroy();\n this.#child.stdout.destroy();\n this.#child.stderr.destroy();\n }, LOGIN_CHILD_TERMINATION_GRACE_MS);\n }\n\n #recordOutput(stream: \"stdout\" | \"stderr\", chunk: string): void {\n this.#output[stream] += chunk;\n const output = `${this.#tails[stream]}${chunk.replaceAll(\"\\r\", \"\\n\")}`;\n const lastDelimiter = output.lastIndexOf(\"\\n\");\n const completed =\n lastDelimiter === -1 ? \"\" : output.slice(0, lastDelimiter + 1);\n this.#urls[stream] ??= preferredAuthUrl(completed);\n this.#codes[stream] ??= userCodeFromOutput(completed);\n this.#tails[stream] =\n lastDelimiter === -1 ? output : output.slice(lastDelimiter + 1);\n this.#notifyInstructions();\n }\n\n #flushInstructionTails(): void {\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n this.#urls[stream] ??= preferredAuthUrl(this.#tails[stream]);\n this.#codes[stream] ??= userCodeFromOutput(this.#tails[stream]);\n }\n }\n\n #notifyInstructions(): void {\n if (this.authUrl !== null) this.#urlReady.resolve();\n if (this.verificationUrl !== null && this.userCode !== null)\n this.#deviceReady.resolve();\n }\n\n #settleInstructionWaiters(result: LoginResult): void {\n this.#notifyInstructions();\n if (result.success) {\n this.#urlReady.resolve();\n this.#deviceReady.resolve();\n return;\n }\n const error = new PluginBootstrapError(\n this.#canceled\n ? \"Codex login was canceled.\"\n : `Codex login exited before authentication instructions were available: ${result.stderr.trim() || result.stdout.trim() || result.exitCode || \"unknown error\"}`,\n );\n this.#urlReady.reject(error);\n this.#deviceReady.reject(error);\n }\n}\n\nexport async function loginApiKey(\n command: CodexCommand,\n environment: ProcessEnvironment,\n apiKey: string,\n signal?: AbortSignal,\n): Promise<LoginResult> {\n if (apiKey.trim().length === 0) {\n throw new PluginBootstrapError(\"The API key must be non-empty.\");\n }\n return await runCodexCommand(\n command,\n [\"login\", \"--with-api-key\"],\n environment,\n `${apiKey}\\n`,\n signal,\n );\n}\n\nexport async function accountStatus(\n command: CodexCommand,\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<AccountStatus> {\n const result = await runCodexCommand(\n command,\n [\"login\", \"status\"],\n environment,\n undefined,\n signal,\n );\n const details = [result.stdout.trim(), result.stderr.trim()]\n .filter(Boolean)\n .join(\"\\n\");\n return {\n authenticated:\n result.exitCode === 0 && !/not logged in|unauthenticated/i.test(details),\n details,\n };\n}\n\nexport async function logout(\n command: CodexCommand,\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<void> {\n const result = await runCodexCommand(\n command,\n [\"logout\"],\n environment,\n undefined,\n signal,\n );\n if (!result.success) {\n throw new PluginBootstrapError(\n `Codex logout failed: ${result.stderr.trim() || result.stdout.trim() || \"unknown error\"}`,\n );\n }\n}\n\n/** @internal Authentication settings shared by login and model commands. */\nexport const CODEX_AUTH_CONFIG_KEYS = [\n \"cli_auth_credentials_store\",\n \"forced_login_method\",\n \"forced_chatgpt_workspace_id\",\n] as const;\n\n/** @internal Shared login recovery guidance for model commands. */\nexport const NO_CREDENTIALS_MESSAGE =\n \"No credentials were found. Run 'codex-security login', use \" +\n \"'codex-security login --device-auth' on a remote or headless machine, or set \" +\n \"OPENAI_API_KEY or CODEX_API_KEY for CI.\";\n\nfunction preferredAuthUrl(value: string): string | null {\n for (const match of plainTerminalText(value).matchAll(\n /https?:\\/\\/[^\\s<>\"']+/g,\n )) {\n const url = match[0].replace(/[.,;:!?)\\]}]+$/, \"\");\n try {\n const hostname = new URL(url).hostname.toLowerCase().replace(/\\.$/, \"\");\n if (\n hostname !== \"localhost\" &&\n !hostname.endsWith(\".localhost\") &&\n !(isIP(hostname) === 4 && hostname.startsWith(\"127.\")) &&\n hostname !== \"0.0.0.0\" &&\n hostname !== \"[::1]\" &&\n hostname !== \"[::]\" &&\n hostname !== \"[::ffff:0:0]\" &&\n !hostname.startsWith(\"[::ffff:7f\") &&\n !hostname.startsWith(\"[::7f\")\n ) {\n return url;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\nfunction userCodeFromOutput(value: string): string | null {\n const output = plainTerminalText(value);\n return (\n output.match(/(?:code|user code)\\s*[:=]\\s*([A-Z0-9-]{4,})/i)?.[1] ??\n output.match(/\\b[A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+\\b/)?.[0] ??\n null\n );\n}\n\nfunction plainTerminalText(value: string): string {\n return value\n .replace(/\\u001b\\][^\\u0007]*(?:\\u0007|\\u001b\\\\)/g, \"\")\n .replace(/\\u001b\\[[0-?]*[ -/]*[@-~]/g, \"\")\n .replace(/\\r/g, \"\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EACL,sBAAsB,EACtB,UAAU,EACV,eAAe,GAGhB,MAAM,cAAc,CAAC;AAEtB,MAAM,gCAAgC,GAAG,KAAK,CAAC;AAE/C,gBAAgB;AAChB,MAAM,UAAU,gBAAgB,CAC9B,WAA+B,EAC/B,SAAiB;IAEjB,MAAM,KAAK,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC;IACrC,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IACtE,MAAM,KAAK,GAAG,SAAS,CAAC,WAAW,EAAE,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ACvD,IAAI,CACL,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAa;IACtC,OAAO,KAAK;SACT,OAAO,CAAC,wCAAwC,EAAE,EAAE,CAAC;SACrD,OAAO,CAAC,4BAA4B,EAAE,EAAE,CAAC;SACzC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACxB,CAAC","sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { isIP } from \"node:net\";\nimport { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { parse } from \"smol-toml\";\nimport type { JsonObject } from \"./config.js\";\nimport { CodexSecurityError, PluginBootstrapError } from \"./errors.js\";\nimport {\n executablePathForSpawn,\n expandHome,\n runCodexCommand,\n type CodexCommand,\n type ProcessEnvironment,\n} from \"./runtime.js\";\n\nconst LOGIN_CHILD_TERMINATION_GRACE_MS = 1_000;\n\n/** @internal */\nexport function environmentEntry(\n environment: ProcessEnvironment,\n requested: string,\n): string | undefined {\n const exact = environment[requested];\n if (exact !== undefined || process.platform !== \"win32\") return exact;\n const upper = requested.toUpperCase();\n return Object.entries(environment).find(\n ([name]) => name.toUpperCase() === upper,\n )?.[1];\n}\n\n/** @internal */\nexport function configuredCodexHome(environment: ProcessEnvironment): string {\n return resolve(\n expandHome(\n environmentEntry(environment, \"CODEX_HOME\")?.trim() ||\n join(homedir(), \".codex\"),\n environment,\n ),\n );\n}\n\n/** @internal */\nexport async function readCodexHomeConfig(\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<JsonObject> {\n try {\n return parse(\n await readFile(join(configuredCodexHome(environment), \"config.toml\"), {\n encoding: \"utf8\",\n signal,\n }),\n ) as JsonObject;\n } catch (error) {\n signal?.throwIfAborted();\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw new CodexSecurityError(\n \"Could not read the configured Codex provider.\",\n );\n }\n}\n\nexport interface LoginResult {\n success: boolean;\n exitCode: number | null;\n stdout: string;\n stderr: string;\n}\n\nexport interface AccountStatus {\n authenticated: boolean;\n details: string;\n}\n\nexport class CodexLoginHandle {\n readonly #child: ChildProcessWithoutNullStreams;\n readonly #completion: Promise<LoginResult>;\n readonly #urlReady = Promise.withResolvers<void>();\n readonly #deviceReady = Promise.withResolvers<void>();\n #canceled = false;\n #forcedTermination: ReturnType<typeof setTimeout> | undefined;\n readonly #output = { stdout: \"\", stderr: \"\" };\n readonly #tails = { stdout: \"\", stderr: \"\" };\n readonly #urls: Record<\"stdout\" | \"stderr\", string | null> = {\n stdout: null,\n stderr: null,\n };\n readonly #codes: Record<\"stdout\" | \"stderr\", string | null> = {\n stdout: null,\n stderr: null,\n };\n\n public constructor(\n command: CodexCommand,\n args: readonly string[],\n environment: ProcessEnvironment,\n onSuccess: () => void | Promise<void>,\n ) {\n void this.#urlReady.promise.catch(() => undefined);\n void this.#deviceReady.promise.catch(() => undefined);\n this.#child = spawn(executablePathForSpawn(command.command), [...args], {\n env: environment,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n this.#child.stdin.end();\n this.#child.stdout.setEncoding(\"utf8\");\n this.#child.stderr.setEncoding(\"utf8\");\n this.#child.stdout.on(\"data\", (chunk: string) => {\n this.#recordOutput(\"stdout\", chunk);\n });\n this.#child.stderr.on(\"data\", (chunk: string) => {\n this.#recordOutput(\"stderr\", chunk);\n });\n this.#completion = new Promise((resolve, reject) => {\n this.#child.once(\"close\", (exitCode) => {\n clearTimeout(this.#forcedTermination);\n if (!this.#canceled) {\n this.#flushInstructionTails();\n }\n const result = {\n success: exitCode === 0 && !this.#canceled,\n exitCode,\n ...this.#output,\n };\n this.#settleInstructionWaiters(result);\n if (result.success) {\n Promise.resolve(onSuccess()).then(() => resolve(result), reject);\n } else {\n resolve(result);\n }\n });\n this.#child.once(\"error\", (error) => {\n clearTimeout(this.#forcedTermination);\n this.#settleInstructionWaiters({\n success: false,\n exitCode: null,\n stdout: this.#output.stdout,\n stderr: error.message,\n });\n reject(error);\n });\n });\n }\n\n public get loginId(): null {\n return null;\n }\n\n public get authUrl(): string | null {\n return this.#urls.stdout ?? this.#urls.stderr;\n }\n\n public get verificationUrl(): string | null {\n return this.authUrl;\n }\n\n public get userCode(): string | null {\n return this.#codes.stdout ?? this.#codes.stderr;\n }\n\n public async wait(): Promise<LoginResult> {\n return await this.#completion;\n }\n\n public async waitForInstructions(\n options: { deviceCode?: boolean } = {},\n ): Promise<void> {\n await (options.deviceCode === true ? this.#deviceReady : this.#urlReady)\n .promise;\n }\n\n public cancel(): void {\n this.#canceled = true;\n if (this.#child.exitCode !== null || this.#child.signalCode !== null)\n return;\n this.#child.kill(\"SIGTERM\");\n if (this.#forcedTermination !== undefined) return;\n this.#forcedTermination = setTimeout(() => {\n if (this.#child.exitCode === null && this.#child.signalCode === null) {\n this.#child.kill(\"SIGKILL\");\n }\n this.#child.stdin.destroy();\n this.#child.stdout.destroy();\n this.#child.stderr.destroy();\n }, LOGIN_CHILD_TERMINATION_GRACE_MS);\n }\n\n #recordOutput(stream: \"stdout\" | \"stderr\", chunk: string): void {\n this.#output[stream] += chunk;\n const output = `${this.#tails[stream]}${chunk.replaceAll(\"\\r\", \"\\n\")}`;\n const lastDelimiter = output.lastIndexOf(\"\\n\");\n const completed =\n lastDelimiter === -1 ? \"\" : output.slice(0, lastDelimiter + 1);\n this.#urls[stream] ??= preferredAuthUrl(completed);\n this.#codes[stream] ??= userCodeFromOutput(completed);\n this.#tails[stream] =\n lastDelimiter === -1 ? output : output.slice(lastDelimiter + 1);\n this.#notifyInstructions();\n }\n\n #flushInstructionTails(): void {\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n this.#urls[stream] ??= preferredAuthUrl(this.#tails[stream]);\n this.#codes[stream] ??= userCodeFromOutput(this.#tails[stream]);\n }\n }\n\n #notifyInstructions(): void {\n if (this.authUrl !== null) this.#urlReady.resolve();\n if (this.verificationUrl !== null && this.userCode !== null)\n this.#deviceReady.resolve();\n }\n\n #settleInstructionWaiters(result: LoginResult): void {\n this.#notifyInstructions();\n if (result.success) {\n this.#urlReady.resolve();\n this.#deviceReady.resolve();\n return;\n }\n const error = new PluginBootstrapError(\n this.#canceled\n ? \"Codex login was canceled.\"\n : `Codex login exited before authentication instructions were available: ${result.stderr.trim() || result.stdout.trim() || result.exitCode || \"unknown error\"}`,\n );\n this.#urlReady.reject(error);\n this.#deviceReady.reject(error);\n }\n}\n\nexport async function loginApiKey(\n command: CodexCommand,\n environment: ProcessEnvironment,\n apiKey: string,\n signal?: AbortSignal,\n): Promise<LoginResult> {\n if (apiKey.trim().length === 0) {\n throw new PluginBootstrapError(\"The API key must be non-empty.\");\n }\n return await runCodexCommand(\n command,\n [\"login\", \"--with-api-key\"],\n environment,\n `${apiKey}\\n`,\n signal,\n );\n}\n\nexport async function accountStatus(\n command: CodexCommand,\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<AccountStatus> {\n const result = await runCodexCommand(\n command,\n [\"login\", \"status\"],\n environment,\n undefined,\n signal,\n );\n const details = [result.stdout.trim(), result.stderr.trim()]\n .filter(Boolean)\n .join(\"\\n\");\n return {\n authenticated:\n result.exitCode === 0 && !/not logged in|unauthenticated/i.test(details),\n details,\n };\n}\n\nexport async function logout(\n command: CodexCommand,\n environment: ProcessEnvironment,\n signal?: AbortSignal,\n): Promise<void> {\n const result = await runCodexCommand(\n command,\n [\"logout\"],\n environment,\n undefined,\n signal,\n );\n if (!result.success) {\n throw new PluginBootstrapError(\n `Codex logout failed: ${result.stderr.trim() || result.stdout.trim() || \"unknown error\"}`,\n );\n }\n}\n\n/** @internal Authentication settings shared by login and model commands. */\nexport const CODEX_AUTH_CONFIG_KEYS = [\n \"cli_auth_credentials_store\",\n \"forced_login_method\",\n \"forced_chatgpt_workspace_id\",\n] as const;\n\n/** @internal Shared login recovery guidance for model commands. */\nexport const NO_CREDENTIALS_MESSAGE =\n \"No credentials were found. Run 'codex-security login', use \" +\n \"'codex-security login --device-auth' on a remote or headless machine, or set \" +\n \"OPENAI_API_KEY or CODEX_API_KEY for CI.\";\n\nfunction preferredAuthUrl(value: string): string | null {\n for (const match of plainTerminalText(value).matchAll(\n /https?:\\/\\/[^\\s<>\"']+/g,\n )) {\n const url = match[0].replace(/[.,;:!?)\\]}]+$/, \"\");\n try {\n const hostname = new URL(url).hostname.toLowerCase().replace(/\\.$/, \"\");\n if (\n hostname !== \"localhost\" &&\n !hostname.endsWith(\".localhost\") &&\n !(isIP(hostname) === 4 && hostname.startsWith(\"127.\")) &&\n hostname !== \"0.0.0.0\" &&\n hostname !== \"[::1]\" &&\n hostname !== \"[::]\" &&\n hostname !== \"[::ffff:0:0]\" &&\n !hostname.startsWith(\"[::ffff:7f\") &&\n !hostname.startsWith(\"[::7f\")\n ) {\n return url;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\nfunction userCodeFromOutput(value: string): string | null {\n const output = plainTerminalText(value).replace(/https?:\\/\\/[^\\s<>\"']+/g, \"\");\n return (\n output.match(/(?:code|user code)\\s*[:=]\\s*([A-Z0-9-]{4,})/i)?.[1] ??\n output.match(/\\b[A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+\\b/)?.[0] ??\n null\n );\n}\n\nfunction plainTerminalText(value: string): string {\n return value\n .replace(/\\u001b\\][^\\u0007]*(?:\\u0007|\\u001b\\\\)/g, \"\")\n .replace(/\\u001b\\[[0-?]*[ -/]*[@-~]/g, \"\")\n .replace(/\\r/g, \"\");\n}\n"]}
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { Readable } from "node:stream";
|
|
2
3
|
import { CodexSecurity, type ScanAuthMode, type ScanAuthentication } from "./api.js";
|
|
4
|
+
import { suggestOwnersInternal } from "./suggest-owners.js";
|
|
3
5
|
import { publishScanToCustom } from "./custom-publish.js";
|
|
4
6
|
import { deduplicateScanInternal } from "./deduplication/scan.js";
|
|
5
7
|
import { classifyScanSeverityInternal, classifyScanDirectorySeverityInternal } from "./classify-scan-severity.js";
|
|
@@ -89,6 +91,8 @@ interface CliDependencies {
|
|
|
89
91
|
deduplicateScan?: typeof deduplicateScanInternal;
|
|
90
92
|
classifyScanSeverity?: typeof classifyScanSeverityInternal;
|
|
91
93
|
classifyScanDirectorySeverity?: typeof classifyScanDirectorySeverityInternal;
|
|
94
|
+
suggestOwners?: typeof suggestOwnersInternal;
|
|
95
|
+
recordsInput?: Readable;
|
|
92
96
|
publishFindingsCsvToCloud?: typeof publishFindingsCsvToCloud;
|
|
93
97
|
publishScanToCloud?: typeof publishScanToCloud;
|
|
94
98
|
publishScanToCustom?: typeof publishScanToCustom;
|
package/dist/cli.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AA0CA,OAAO,EAAE,QAAQ,EAA4B,MAAM,aAAa,CAAC;AAOjE,OAAO,EAEL,aAAa,EAWb,KAAK,YAAY,EACjB,KAAK,kBAAkB,EAGxB,MAAM,UAAU,CAAC;AASlB,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAE5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAE1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAElE,OAAO,EACL,4BAA4B,EAC5B,qCAAqC,EACtC,MAAM,6BAA6B,CAAC;AAMrC,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAEnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAGL,KAAK,6BAA6B,EAClC,KAAK,cAAc,EACpB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAcL,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,UAAU,EAEhB,MAAM,aAAa,CA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M,CAKlC;IAEM,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAGlC;IAEM,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAevC;IAEM,SAAS,IAAI,IAAI,CAsCvB;IAEM,eAAe,CAAC,KAAK,EAAE,MAAM,IAAI,GAAG,IAAI,CAY9C;CAmCF"}
|
package/dist/cli.js
CHANGED
|
@@ -17,9 +17,12 @@ import { parse as parseToml } from "smol-toml";
|
|
|
17
17
|
import { classifyConnectionFailure, createSecurityInternal, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, runtimeScanAuthentication, selectedScanEnvironment, } from "./api.js";
|
|
18
18
|
import { accountStatus, CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, configuredCodexHome, readCodexHomeConfig, } from "./auth.js";
|
|
19
19
|
import { loadContract } from "./contract.js";
|
|
20
|
+
import { suggestOwnersInternal } from "./suggest-owners.js";
|
|
21
|
+
import { parseImportedFindings } from "./findings-import.js";
|
|
20
22
|
import { publishScanToCustom } from "./custom-publish.js";
|
|
21
23
|
import { DEFAULT_DEDUPE_CONCURRENCY } from "./deduplication/deduplication.js";
|
|
22
24
|
import { deduplicateScanInternal } from "./deduplication/scan.js";
|
|
25
|
+
import { runRecordsProtocol } from "./deduplication/records-protocol.js";
|
|
23
26
|
import { classifyScanSeverityInternal, classifyScanDirectorySeverityInternal, } from "./classify-scan-severity.js";
|
|
24
27
|
import { resolveCompletedScan, resolveWorkflowScan, } from "./saved-scan.js";
|
|
25
28
|
import { publishFindingsCsvToCloud, publishScanToCloud, } from "./cloud-publish.js";
|
|
@@ -1108,6 +1111,39 @@ export function exportEnvironment(environment = process.env) {
|
|
|
1108
1111
|
.map((key) => [key, environment[key]])));
|
|
1109
1112
|
}
|
|
1110
1113
|
export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
|
|
1114
|
+
if (argv[0] === "dedupe" &&
|
|
1115
|
+
argv.includes("--records") &&
|
|
1116
|
+
!argv.includes("--help") &&
|
|
1117
|
+
!argv.includes("-h") &&
|
|
1118
|
+
!argv.includes("--schema")) {
|
|
1119
|
+
if (argv.length !== 2) {
|
|
1120
|
+
errorOutput.write("codex-security: --records must be used alone with dedupe.\n");
|
|
1121
|
+
return 2;
|
|
1122
|
+
}
|
|
1123
|
+
const controller = new AbortController();
|
|
1124
|
+
const interrupt = () => controller.abort("SIGINT");
|
|
1125
|
+
const terminate = () => controller.abort("SIGTERM");
|
|
1126
|
+
dependencies.addSignalListener("SIGINT", interrupt);
|
|
1127
|
+
dependencies.addSignalListener("SIGTERM", terminate);
|
|
1128
|
+
let exitCode;
|
|
1129
|
+
try {
|
|
1130
|
+
const code = await runRecordsProtocol(dependencies.recordsInput ?? process.stdin, output, controller.signal);
|
|
1131
|
+
exitCode =
|
|
1132
|
+
controller.signal.reason === "SIGINT"
|
|
1133
|
+
? 130
|
|
1134
|
+
: controller.signal.reason === "SIGTERM"
|
|
1135
|
+
? 143
|
|
1136
|
+
: code;
|
|
1137
|
+
}
|
|
1138
|
+
finally {
|
|
1139
|
+
dependencies.removeSignalListener("SIGINT", interrupt);
|
|
1140
|
+
dependencies.removeSignalListener("SIGTERM", terminate);
|
|
1141
|
+
}
|
|
1142
|
+
// Protocol writes have flushed or been canceled. Node's stdout ignores destroy().
|
|
1143
|
+
if (output === process.stdout)
|
|
1144
|
+
process.exit(exitCode);
|
|
1145
|
+
return exitCode;
|
|
1146
|
+
}
|
|
1111
1147
|
argv = normalizeScanImportArguments(defaultListCommand(argv));
|
|
1112
1148
|
const policyFullOutput = argv[cliCommandIndex(argv)] === "policy" && argv.includes("--full-output");
|
|
1113
1149
|
const positionals = [];
|
|
@@ -1143,6 +1179,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
1143
1179
|
let renderedPolicy;
|
|
1144
1180
|
let renderedPatch;
|
|
1145
1181
|
let patchStructuredError = false;
|
|
1182
|
+
let scanStructuredError = false;
|
|
1146
1183
|
const runImport = (options) => runScanImport(options, errorOutput, dependencies);
|
|
1147
1184
|
const history = async (args, select = (value) => value) => {
|
|
1148
1185
|
try {
|
|
@@ -2620,11 +2657,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2620
2657
|
exitCode = outcome.exitCode;
|
|
2621
2658
|
if (outcome.error !== undefined) {
|
|
2622
2659
|
if (format === "json" || format === "jsonl") {
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
code: "SCAN_FAILED",
|
|
2626
|
-
|
|
2627
|
-
|
|
2660
|
+
const message = safeErrorMessage(outcome.error);
|
|
2661
|
+
if (!argv.includes("--full-output"))
|
|
2662
|
+
return { status: "failed", code: "SCAN_FAILED", message };
|
|
2663
|
+
// Incur would wrap returned data in an ok: true envelope.
|
|
2664
|
+
scanStructuredError = true;
|
|
2665
|
+
return incurError({ code: "SCAN_FAILED", message, exitCode });
|
|
2628
2666
|
}
|
|
2629
2667
|
return incurError({
|
|
2630
2668
|
code: "SCAN_FAILED",
|
|
@@ -2641,7 +2679,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2641
2679
|
},
|
|
2642
2680
|
})
|
|
2643
2681
|
.command("install-hook", {
|
|
2644
|
-
description: "Install
|
|
2682
|
+
description: "Install an advisory local Git pre-commit check. Require a passing scan in CI.",
|
|
2645
2683
|
destructive: true,
|
|
2646
2684
|
mcp: false,
|
|
2647
2685
|
args: z.object({
|
|
@@ -2708,6 +2746,58 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2708
2746
|
.command(scanHistory)
|
|
2709
2747
|
.command(findingFeedback)
|
|
2710
2748
|
.command(publication)
|
|
2749
|
+
.command("suggest-owners", {
|
|
2750
|
+
description: "Suggest finding owners from committed source and Git history.",
|
|
2751
|
+
destructive: false,
|
|
2752
|
+
mcp: false,
|
|
2753
|
+
args: z.object({
|
|
2754
|
+
findings: z
|
|
2755
|
+
.string()
|
|
2756
|
+
.min(1)
|
|
2757
|
+
.describe("Codex Security findings JSON file."),
|
|
2758
|
+
}),
|
|
2759
|
+
options: z.object({
|
|
2760
|
+
sourceRoot: optionValue("--source-root")
|
|
2761
|
+
.optional()
|
|
2762
|
+
.describe("Local Git repository (default: current directory); analyzes committed HEAD."),
|
|
2763
|
+
model: optionValue("--model")
|
|
2764
|
+
.optional()
|
|
2765
|
+
.describe("Model for owner suggestions (default: Codex Security model)."),
|
|
2766
|
+
effort: effortOption().describe("Reasoning effort (default: Codex Security effort)."),
|
|
2767
|
+
}),
|
|
2768
|
+
output: z.record(z.string(), z.unknown()).optional(),
|
|
2769
|
+
async run({ args, options }) {
|
|
2770
|
+
const controller = new AbortController();
|
|
2771
|
+
const onInterrupt = () => controller.abort("SIGINT");
|
|
2772
|
+
const onTerminate = () => controller.abort("SIGTERM");
|
|
2773
|
+
dependencies.addSignalListener("SIGINT", onInterrupt);
|
|
2774
|
+
dependencies.addSignalListener("SIGTERM", onTerminate);
|
|
2775
|
+
try {
|
|
2776
|
+
const directory = dependencies.currentDirectory();
|
|
2777
|
+
const repository = resolveCliPath(directory, options.sourceRoot ?? ".");
|
|
2778
|
+
const findings = await parseImportedFindings(await readRegularInputFile(resolveCliPath(directory, args.findings), repository), "json", await bundledPluginRoot());
|
|
2779
|
+
const result = await (dependencies.suggestOwners ?? suggestOwnersInternal)(repository, findings, {
|
|
2780
|
+
environment: dependencies.environment,
|
|
2781
|
+
signal: controller.signal,
|
|
2782
|
+
model: options.model,
|
|
2783
|
+
reasoningEffort: options.effort,
|
|
2784
|
+
}, "cli");
|
|
2785
|
+
if (result.results.some(({ status }) => status === "error"))
|
|
2786
|
+
exitCode = 2;
|
|
2787
|
+
return { ...result };
|
|
2788
|
+
}
|
|
2789
|
+
catch (error) {
|
|
2790
|
+
const signal = controller.signal.reason;
|
|
2791
|
+
errorOutput.write(`codex-security: ${signal === "SIGINT" || signal === "SIGTERM" ? "Owner suggestions canceled." : safeErrorMessage(error)}\n`);
|
|
2792
|
+
exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2;
|
|
2793
|
+
return undefined;
|
|
2794
|
+
}
|
|
2795
|
+
finally {
|
|
2796
|
+
dependencies.removeSignalListener("SIGINT", onInterrupt);
|
|
2797
|
+
dependencies.removeSignalListener("SIGTERM", onTerminate);
|
|
2798
|
+
}
|
|
2799
|
+
},
|
|
2800
|
+
})
|
|
2711
2801
|
.command("classify-severity", {
|
|
2712
2802
|
description: "Classify saved findings using an optional rubric and save a separate severity assessment.",
|
|
2713
2803
|
destructive: true,
|
|
@@ -2785,7 +2875,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2785
2875
|
},
|
|
2786
2876
|
})
|
|
2787
2877
|
.command("dedupe", {
|
|
2788
|
-
description: "
|
|
2878
|
+
description: "Dedupe a saved scan, or use --records for host-provided reviews over JSON-RPC.",
|
|
2789
2879
|
destructive: true,
|
|
2790
2880
|
mcp: false,
|
|
2791
2881
|
options: z.object({
|
|
@@ -2795,6 +2885,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2795
2885
|
.positive()
|
|
2796
2886
|
.default(DEFAULT_DEDUPE_CONCURRENCY)
|
|
2797
2887
|
.describe("Maximum concurrent dedupe jobs across Luna and Sol; use 1 for serial execution."),
|
|
2888
|
+
records: z
|
|
2889
|
+
.boolean()
|
|
2890
|
+
.default(false)
|
|
2891
|
+
.describe("Run the versioned records JSON-RPC protocol on stdin/stdout; use alone."),
|
|
2798
2892
|
workflowId: optionValue("--workflow-id")
|
|
2799
2893
|
.optional()
|
|
2800
2894
|
.describe("Resume the named local findings workflow; reuses its saved scan."),
|
|
@@ -2808,6 +2902,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2808
2902
|
findingsUrl: z
|
|
2809
2903
|
.string()
|
|
2810
2904
|
.url()
|
|
2905
|
+
.optional()
|
|
2811
2906
|
.describe("Findings API base URL; the scan's findings must already be indexed."),
|
|
2812
2907
|
}),
|
|
2813
2908
|
output: z
|
|
@@ -2828,12 +2923,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2828
2923
|
})
|
|
2829
2924
|
.optional(),
|
|
2830
2925
|
async run({ options }) {
|
|
2926
|
+
if (options.records)
|
|
2927
|
+
throw new CodexSecurityError("Use dedupe --records alone.");
|
|
2831
2928
|
const controller = new AbortController();
|
|
2832
2929
|
const onInterrupt = () => controller.abort("SIGINT");
|
|
2833
2930
|
const onTerminate = () => controller.abort("SIGTERM");
|
|
2834
2931
|
dependencies.addSignalListener("SIGINT", onInterrupt);
|
|
2835
2932
|
dependencies.addSignalListener("SIGTERM", onTerminate);
|
|
2836
2933
|
try {
|
|
2934
|
+
if (options.findingsUrl === undefined)
|
|
2935
|
+
throw new CodexSecurityError("Saved-scan deduplication requires --findings-url.");
|
|
2837
2936
|
const scanId = options.scan ??
|
|
2838
2937
|
(options.workflowId === undefined
|
|
2839
2938
|
? undefined
|
|
@@ -4229,7 +4328,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
4229
4328
|
if (notice !== undefined)
|
|
4230
4329
|
errorOutput.write(formatUpdateNotice(notice));
|
|
4231
4330
|
if (frameworkExit !== undefined) {
|
|
4232
|
-
if (policyFullOutput || patchStructuredError) {
|
|
4331
|
+
if (policyFullOutput || patchStructuredError || scanStructuredError) {
|
|
4233
4332
|
if (exitCode === 0)
|
|
4234
4333
|
exitCode = 2;
|
|
4235
4334
|
}
|
|
@@ -4487,6 +4586,7 @@ function validateCliArguments(argv, positionals) {
|
|
|
4487
4586
|
"import",
|
|
4488
4587
|
"validate",
|
|
4489
4588
|
"verify-fix",
|
|
4589
|
+
"suggest-owners",
|
|
4490
4590
|
"patch",
|
|
4491
4591
|
"login",
|
|
4492
4592
|
"logout",
|