@openai/codex-security 0.1.18 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +133 -9
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/scripts/workbench_cli.py +5 -1
  4. package/_bundled_plugin/scripts/workbench_db.py +53 -0
  5. package/dist/bulk-scan-discovery.d.ts +8 -0
  6. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  7. package/dist/bulk-scan-discovery.js +15 -1
  8. package/dist/bulk-scan-discovery.js.map +1 -1
  9. package/dist/cli.d.ts +5 -2
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +364 -71
  12. package/dist/cli.js.map +1 -1
  13. package/dist/cloud-publish.d.ts +16 -0
  14. package/dist/cloud-publish.d.ts.map +1 -0
  15. package/dist/cloud-publish.js +142 -0
  16. package/dist/cloud-publish.js.map +1 -0
  17. package/dist/contract.d.ts +1 -0
  18. package/dist/contract.d.ts.map +1 -1
  19. package/dist/contract.js +4 -0
  20. package/dist/contract.js.map +1 -1
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/linear.d.ts +5 -0
  26. package/dist/linear.d.ts.map +1 -1
  27. package/dist/linear.js +25 -9
  28. package/dist/linear.js.map +1 -1
  29. package/dist/publication-events.d.ts +40 -13
  30. package/dist/publication-events.d.ts.map +1 -1
  31. package/dist/publication-events.js +218 -104
  32. package/dist/publication-events.js.map +1 -1
  33. package/dist/publication-store.d.ts +1 -0
  34. package/dist/publication-store.d.ts.map +1 -1
  35. package/dist/publication-store.js +73 -26
  36. package/dist/publication-store.js.map +1 -1
  37. package/dist/publication.d.ts +6 -0
  38. package/dist/publication.d.ts.map +1 -1
  39. package/dist/publication.js +13 -0
  40. package/dist/publication.js.map +1 -1
  41. package/dist/publish.d.ts +41 -1
  42. package/dist/publish.d.ts.map +1 -1
  43. package/dist/publish.js +611 -251
  44. package/dist/publish.js.map +1 -1
  45. package/dist/version.d.ts +1 -1
  46. package/dist/version.js +1 -1
  47. package/dist/version.js.map +1 -1
  48. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -13,6 +13,7 @@ import { Cli, z } from "incur";
13
13
  import { parse as parseToml } from "smol-toml";
14
14
  import { classifyConnectionFailure, createSecurityInternal, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, } from "./api.js";
15
15
  import { accountStatus } from "./auth.js";
16
+ import { publishScanToCloud, } from "./cloud-publish.js";
16
17
  import { createBulkScanDiscoveryDependencies, runBulkScanWizard, } from "./bulk-scan-discovery.js";
17
18
  import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanModelConfiguration, scanModelProvider, } from "./config.js";
18
19
  import { formatUsd } from "./cost.js";
@@ -21,7 +22,7 @@ import { importLinearIssues, resolveLinearApiKey, } from "./linear.js";
21
22
  import { runMultiscan } from "./multiscan.js";
22
23
  import { componentPlanSchema } from "./component-plan.js";
23
24
  import { runComponentScans } from "./component-scan.js";
24
- import { publishScan, } from "./publish.js";
25
+ import { checkScanPublication, publishScan, } from "./publish.js";
25
26
  import { bundledPluginRoot, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, expandHome, prepareCodexSecurityCredentialHome, pythonUtf8Environment, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
26
27
  import { matchScanFindingsInternal, } from "./scan-comparison.js";
27
28
  import { scanActivitiesFromEvent } from "./scan-activity.js";
@@ -98,6 +99,7 @@ const VALUE_OPTIONS = new Set([
98
99
  "--patch-severity",
99
100
  "--resume-pr",
100
101
  "--scan",
102
+ "--scan-dir",
101
103
  "--severity",
102
104
  "--max-cost",
103
105
  "--workers",
@@ -140,6 +142,58 @@ function linearApiKeyOption() {
140
142
  .optional()
141
143
  .describe("Linear personal API key; defaults to CODEX_SECURITY_LINEAR_API_KEY.");
142
144
  }
145
+ const PUBLICATION_DESTINATION_OPTIONS = z.object({
146
+ to: z.literal("linear").describe("Publication destination."),
147
+ linearTeam: optionValue("--linear-team")
148
+ .optional()
149
+ .describe("Linear team ID; defaults to CODEX_SECURITY_LINEAR_TEAM."),
150
+ linearApiKey: linearApiKeyOption(),
151
+ linearProject: optionValue("--linear-project")
152
+ .optional()
153
+ .describe("Optional Linear project ID; defaults to CODEX_SECURITY_LINEAR_PROJECT."),
154
+ project: optionValue("--project")
155
+ .optional()
156
+ .describe("Alias for --linear-project.")
157
+ .meta({ deprecated: true }),
158
+ linearAssignee: optionValue("--linear-assignee")
159
+ .optional()
160
+ .describe("Linear assignee email or user ID; omit to leave issues unassigned."),
161
+ });
162
+ function publicationDestination(options, environment) {
163
+ const linearApiKey = resolveLinearApiKey(environment, options.linearApiKey);
164
+ const assigneeId = options.linearAssignee?.trim();
165
+ if (options.linearAssignee !== undefined && !assigneeId) {
166
+ throw new CodexSecurityError("--linear-assignee must not be empty.");
167
+ }
168
+ if (assigneeId !== undefined && linearApiKey === undefined) {
169
+ throw new CodexSecurityError("--linear-assignee requires --linear-api-key or CODEX_SECURITY_LINEAR_API_KEY.");
170
+ }
171
+ const teamId = options.linearTeam?.trim() ||
172
+ environment["CODEX_SECURITY_LINEAR_TEAM"]?.trim();
173
+ if (!teamId) {
174
+ throw new CodexSecurityError("--linear-team or CODEX_SECURITY_LINEAR_TEAM is required.");
175
+ }
176
+ if (options.linearProject !== undefined &&
177
+ options.project !== undefined &&
178
+ options.linearProject.trim() !== options.project.trim()) {
179
+ throw new CodexSecurityError("--linear-project and --project must select the same project.");
180
+ }
181
+ const projectOption = options.linearProject ?? options.project;
182
+ const selectedProject = projectOption?.trim();
183
+ if (projectOption !== undefined && !selectedProject) {
184
+ throw new CodexSecurityError(`${options.linearProject === undefined ? "--project" : "--linear-project"} must not be empty.`);
185
+ }
186
+ const projectId = selectedProject ||
187
+ environment["CODEX_SECURITY_LINEAR_PROJECT"]?.trim() ||
188
+ undefined;
189
+ return {
190
+ destination: options.to,
191
+ teamId,
192
+ ...(projectId === undefined ? {} : { projectId }),
193
+ ...(linearApiKey === undefined ? {} : { linearApiKey }),
194
+ ...(assigneeId === undefined ? {} : { assigneeId }),
195
+ };
196
+ }
143
197
  function publicationScanAge(timestamp, now) {
144
198
  const completedAt = Date.parse(timestamp);
145
199
  if (!Number.isFinite(completedAt))
@@ -227,6 +281,10 @@ function renderPublicationSummary(result, color) {
227
281
  if (created > 0)
228
282
  lines.push("");
229
283
  lines.push(`${created} total issue${created === 1 ? "" : "s"} created`, `${failed} total issue${failed === 1 ? "" : "s"} failed`);
284
+ if (result.skipped !== undefined) {
285
+ const skipped = result.skipped.length;
286
+ lines.push(`${skipped} previously recorded issue${skipped === 1 ? "" : "s"} skipped`);
287
+ }
230
288
  return `${lines.join("\n")}\n`;
231
289
  }
232
290
  class PublicationProgressPresenter {
@@ -323,6 +381,14 @@ class PublicationProgressPresenter {
323
381
  }
324
382
  return;
325
383
  }
384
+ if (event.type === "handoff_recorded") {
385
+ const message = `[${event.recorded}/${event.total}] Saved Linear publication evidence.`;
386
+ if (this.#dashboard === null)
387
+ this.#write(message, true);
388
+ else
389
+ this.#dashboard.setStage(message);
390
+ return;
391
+ }
326
392
  if (event.type === "issue_completed") {
327
393
  const detail = event.error === undefined
328
394
  ? `Created ${event.issueIdentifier ?? event.findingId}`
@@ -1316,6 +1382,20 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1316
1382
  return presentHistory(await matchScanPair(beforeId, afterId), "compare", format);
1317
1383
  },
1318
1384
  });
1385
+ const reportPublicationError = (error, signal) => {
1386
+ if (signal === "SIGINT" || signal === "SIGTERM") {
1387
+ const reason = signal === "SIGINT"
1388
+ ? "Publication canceled by Ctrl-C."
1389
+ : "Publication terminated by SIGTERM.";
1390
+ const recovery = error === signal ? "" : ` ${diagnosticValue(safeErrorMessage(error))}`;
1391
+ errorOutput.write(`codex-security: ${reason}${recovery}\n`);
1392
+ exitCode = signal === "SIGINT" ? 130 : 143;
1393
+ }
1394
+ else {
1395
+ errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
1396
+ exitCode = 2;
1397
+ }
1398
+ };
1319
1399
  const publication = Cli.create("publish", {
1320
1400
  description: "Publish completed Codex Security scan findings.",
1321
1401
  }).command("scan", {
@@ -1328,66 +1408,128 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1328
1408
  .optional()
1329
1409
  .describe("Completed scan directory; omit to select a saved scan."),
1330
1410
  }),
1331
- options: z.object({
1332
- to: z.literal("linear").describe("Publication destination."),
1333
- linearTeam: optionValue("--linear-team")
1334
- .optional()
1335
- .describe("Linear team ID; defaults to CODEX_SECURITY_LINEAR_TEAM."),
1336
- linearApiKey: linearApiKeyOption(),
1337
- linearProject: optionValue("--linear-project")
1338
- .optional()
1339
- .describe("Optional Linear project ID; defaults to CODEX_SECURITY_LINEAR_PROJECT."),
1340
- project: optionValue("--project")
1341
- .optional()
1342
- .describe("Alias for --linear-project.")
1343
- .meta({ deprecated: true }),
1344
- linearAssignee: optionValue("--linear-assignee")
1345
- .optional()
1346
- .describe("Linear assignee email or user ID; omit to leave issues unassigned."),
1411
+ options: PUBLICATION_DESTINATION_OPTIONS.extend({
1412
+ scan: z
1413
+ .array(optionValue("--scan"))
1414
+ .default([])
1415
+ .describe("Saved scan ID, unique prefix, or latest; repeat for multiple scans (Linear accepts one)."),
1416
+ scanDir: z
1417
+ .array(optionValue("--scan-dir"))
1418
+ .default([])
1419
+ .describe("External completed scan directory; repeat for multiple scans (Linear accepts one)."),
1420
+ // Cloud remains an internal destination, omitted from public discovery.
1421
+ to: z
1422
+ .string()
1423
+ .refine((value) => value === "linear" || value === "cloud", {
1424
+ message: "Unsupported publication destination. Use --to linear.",
1425
+ })
1426
+ .describe("Publication destination (linear)."),
1347
1427
  dryRun: z
1348
1428
  .boolean()
1349
1429
  .default(false)
1350
1430
  .describe("Preview the findings without creating Linear issues."),
1431
+ skipExisting: z
1432
+ .boolean()
1433
+ .default(false)
1434
+ .describe("Skip findings already recorded for this exact Linear destination."),
1351
1435
  }),
1352
1436
  output: z.record(z.string(), z.unknown()).optional(),
1353
1437
  async run({ args, format, formatExplicit, options }) {
1354
1438
  const controller = new AbortController();
1355
1439
  let presentation;
1440
+ let directApiPublication = false;
1441
+ let firstSignalAt = 0;
1442
+ let observingSignals = false;
1443
+ let cloudBatch;
1356
1444
  const cancel = (signal) => {
1357
1445
  presentation?.stop();
1446
+ if (controller.signal.aborted) {
1447
+ if (!directApiPublication ||
1448
+ (controller.signal.reason === signal &&
1449
+ dependencies.now() - firstSignalAt < 500)) {
1450
+ return;
1451
+ }
1452
+ try {
1453
+ dependencies.writeSynchronously(errorOutput, "codex-security: Publication force-stopped; reconcile retained Linear publication evidence before retrying.\n");
1454
+ }
1455
+ catch { }
1456
+ removeSignalListeners();
1457
+ dependencies.forceExit(signal);
1458
+ return;
1459
+ }
1460
+ firstSignalAt = dependencies.now();
1358
1461
  controller.abort(signal);
1359
1462
  };
1463
+ const finishCancellation = (error) => {
1464
+ const signal = controller.signal.reason;
1465
+ if (signal !== "SIGINT" && signal !== "SIGTERM")
1466
+ return false;
1467
+ const reason = signal === "SIGINT"
1468
+ ? "Publication canceled by Ctrl-C."
1469
+ : "Publication terminated by SIGTERM.";
1470
+ const recovery = error === undefined || error === signal
1471
+ ? ""
1472
+ : ` ${diagnosticValue(safeErrorMessage(error))}`;
1473
+ errorOutput.write(`codex-security: ${reason}${recovery}\n`);
1474
+ exitCode = signal === "SIGINT" ? 130 : 143;
1475
+ return true;
1476
+ };
1360
1477
  const onInterrupt = () => cancel("SIGINT");
1361
1478
  const onTerminate = () => cancel("SIGTERM");
1362
- let observingSignals = false;
1479
+ const removeSignalListeners = () => {
1480
+ if (!observingSignals)
1481
+ return;
1482
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
1483
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
1484
+ observingSignals = false;
1485
+ };
1363
1486
  try {
1364
- const linearApiKey = resolveLinearApiKey(dependencies.environment, options.linearApiKey);
1365
- const assigneeId = options.linearAssignee?.trim();
1366
- if (options.linearAssignee !== undefined && !assigneeId) {
1367
- throw new CodexSecurityError("--linear-assignee must not be empty.");
1487
+ const currentDirectory = dependencies.currentDirectory();
1488
+ const directories = [
1489
+ ...new Set([
1490
+ ...(args.scanDir === undefined ? [] : [args.scanDir]),
1491
+ ...options.scanDir,
1492
+ ].map((directory) => resolveCliPath(currentDirectory, directory))),
1493
+ ];
1494
+ if (directories.length > 1 && options.to !== "cloud") {
1495
+ throw new CodexSecurityError("Multiple scan directories are only supported with --to cloud.");
1368
1496
  }
1369
- if (assigneeId !== undefined && linearApiKey === undefined) {
1370
- throw new CodexSecurityError("--linear-assignee requires --linear-api-key or CODEX_SECURITY_LINEAR_API_KEY.");
1497
+ if (options.scan.length > 0 && directories.length > 0) {
1498
+ throw new CodexSecurityError("Use --scan or scan directory inputs, not both.");
1371
1499
  }
1372
- const teamId = options.linearTeam?.trim() ||
1373
- dependencies.environment["CODEX_SECURITY_LINEAR_TEAM"]?.trim();
1374
- if (!teamId) {
1375
- throw new CodexSecurityError("--linear-team or CODEX_SECURITY_LINEAR_TEAM is required.");
1500
+ if (new Set(options.scan).size > 1 && options.to !== "cloud") {
1501
+ throw new CodexSecurityError("Multiple scans are only supported with --to cloud.");
1376
1502
  }
1377
- if (options.linearProject !== undefined &&
1378
- options.project !== undefined &&
1379
- options.linearProject.trim() !== options.project.trim()) {
1380
- throw new CodexSecurityError("--linear-project and --project must select the same project.");
1503
+ if (options.to === "cloud" &&
1504
+ (options.skipExisting ||
1505
+ [
1506
+ options.linearTeam,
1507
+ options.linearApiKey,
1508
+ options.linearProject,
1509
+ options.project,
1510
+ options.linearAssignee,
1511
+ ].some((value) => value !== undefined))) {
1512
+ throw new CodexSecurityError("Cloud publication cannot be combined with Linear options.");
1381
1513
  }
1382
- const projectOption = options.linearProject ?? options.project;
1383
- const selectedProject = projectOption?.trim();
1384
- if (projectOption !== undefined && !selectedProject) {
1385
- throw new CodexSecurityError(`${options.linearProject === undefined ? "--project" : "--linear-project"} must not be empty.`);
1514
+ const destination = options.to === "linear"
1515
+ ? publicationDestination({ ...options, to: "linear" }, dependencies.environment)
1516
+ : undefined;
1517
+ directApiPublication =
1518
+ !options.dryRun && destination?.linearApiKey !== undefined;
1519
+ if (options.to === "cloud") {
1520
+ dependencies.addSignalListener("SIGINT", onInterrupt);
1521
+ dependencies.addSignalListener("SIGTERM", onTerminate);
1522
+ observingSignals = true;
1523
+ }
1524
+ const selectedScans = directories.map((scanDir) => ({ scanDir }));
1525
+ for (const requestedId of new Set(options.scan)) {
1526
+ controller.signal.throwIfAborted();
1527
+ const scan = await resolvePublicationScan(requestedId, dependencies);
1528
+ if (!selectedScans.some(({ scanId }) => scanId === scan.scanId)) {
1529
+ selectedScans.push(scan);
1530
+ }
1386
1531
  }
1387
- const projectId = selectedProject ||
1388
- dependencies.environment["CODEX_SECURITY_LINEAR_PROJECT"]?.trim() ||
1389
- undefined;
1390
- let scanDir = args.scanDir;
1532
+ let scanDir = selectedScans[0]?.scanDir;
1391
1533
  let publicationRepository = scanDir === undefined ? "scan" : basename(scanDir);
1392
1534
  if (scanDir === undefined) {
1393
1535
  const prompt = dependencies.publishPrompt ??
@@ -1397,7 +1539,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1397
1539
  currentDirectory: dependencies.currentDirectory,
1398
1540
  }).prompt;
1399
1541
  if (!prompt.isInteractive()) {
1400
- throw new CodexSecurityError("Interactive scan selection requires a terminal. Provide a completed scan directory: codex-security publish scan /path/to/sealed-scan --to linear --linear-team TEAM_ID.");
1542
+ throw new CodexSecurityError(`Interactive scan selection requires a terminal. Select a saved scan: codex-security publish scan --scan SCAN_ID --to ${options.to}${options.to === "linear" ? " --linear-team TEAM_ID" : ""}.`);
1401
1543
  }
1402
1544
  const saved = await dependencies.runWorkbench([
1403
1545
  "list-scans",
@@ -1415,7 +1557,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1415
1557
  if (typeof directory !== "string" || directory.length === 0) {
1416
1558
  return undefined;
1417
1559
  }
1418
- const metadata = await lstat(resolve(dependencies.currentDirectory(), directory)).catch(() => undefined);
1560
+ const metadata = await lstat(resolveCliPath(currentDirectory, directory)).catch(() => undefined);
1419
1561
  return metadata?.isDirectory() === true &&
1420
1562
  !metadata.isSymbolicLink()
1421
1563
  ? scan
@@ -1426,6 +1568,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1426
1568
  dependencies.environment["NO_COLOR"] === undefined &&
1427
1569
  dependencies.environment["TERM"] !== "dumb";
1428
1570
  const repositories = new Map();
1571
+ const scansById = new Map();
1429
1572
  const rows = scans.flatMap((scan) => {
1430
1573
  if (!isJsonObject(scan))
1431
1574
  return [];
@@ -1470,13 +1613,17 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1470
1613
  .replace(/\s+/gu, " ")
1471
1614
  .slice(-6)}`;
1472
1615
  repositories.set(directory, repository);
1616
+ scansById.set(scanId, {
1617
+ scanId,
1618
+ scanDir: resolveCliPath(currentDirectory, directory),
1619
+ });
1473
1620
  return [
1474
1621
  {
1475
1622
  repository,
1476
1623
  findings,
1477
1624
  age: publicationScanAge(timestamp, now),
1478
1625
  scanId: shortScanId,
1479
- value: directory,
1626
+ value: options.to === "cloud" ? scanId : directory,
1480
1627
  },
1481
1628
  ];
1482
1629
  });
@@ -1507,31 +1654,110 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1507
1654
  value: row.value,
1508
1655
  };
1509
1656
  });
1510
- scanDir = await prompt.select("Which completed scan would you like to publish?", choices, { header });
1657
+ if (options.to === "cloud") {
1658
+ if (prompt.checkbox === undefined) {
1659
+ throw new CodexSecurityError("Interactive scan selection is unavailable.");
1660
+ }
1661
+ controller.signal.throwIfAborted();
1662
+ const selected = await prompt.checkbox("Which completed scans would you like to publish?", choices, { header, required: true }, controller.signal);
1663
+ controller.signal.throwIfAborted();
1664
+ selectedScans.push(...selected.map((scanId) => scansById.get(scanId)));
1665
+ scanDir = selectedScans[0].scanDir;
1666
+ }
1667
+ else {
1668
+ scanDir = await prompt.select("Which completed scan would you like to publish?", choices, { header });
1669
+ selectedScans.push({ scanDir });
1670
+ }
1511
1671
  publicationRepository =
1512
1672
  repositories.get(scanDir) ?? basename(scanDir);
1513
1673
  }
1674
+ if (options.to === "cloud") {
1675
+ const seenDirectories = new Set();
1676
+ for (let index = 0; index < selectedScans.length;) {
1677
+ const selected = selectedScans[index];
1678
+ const canonical = await realpath(selected.scanDir).catch(() => selected.scanDir);
1679
+ const identity = process.platform === "win32"
1680
+ ? canonical.toLowerCase()
1681
+ : canonical;
1682
+ if (seenDirectories.has(identity)) {
1683
+ selectedScans.splice(index, 1);
1684
+ continue;
1685
+ }
1686
+ seenDirectories.add(identity);
1687
+ selected.scanDir = canonical;
1688
+ index++;
1689
+ }
1690
+ scanDir = selectedScans[0].scanDir;
1691
+ controller.signal.throwIfAborted();
1692
+ if (selectedScans.length > 1) {
1693
+ cloudBatch = {
1694
+ results: [],
1695
+ failed: [],
1696
+ notAttempted: selectedScans.map(({ scanId, scanDir }) => scanId ?? scanDir),
1697
+ };
1698
+ // Keep each scan's provenance and acceptance receipt separate. Never
1699
+ // retry a failed POST: a lost response may still have been accepted.
1700
+ for (const { scanDir: directory, scanId } of selectedScans) {
1701
+ if (controller.signal.aborted) {
1702
+ finishCancellation();
1703
+ break;
1704
+ }
1705
+ cloudBatch.notAttempted.shift();
1706
+ try {
1707
+ const result = await (dependencies.publishScanToCloud ?? publishScanToCloud)(directory, {
1708
+ environment: dependencies.environment,
1709
+ dryRun: options.dryRun,
1710
+ signal: controller.signal,
1711
+ ...(scanId === undefined ? {} : { expectedScanId: scanId }),
1712
+ });
1713
+ cloudBatch.results.push({ scanDir: directory, ...result });
1714
+ }
1715
+ catch (error) {
1716
+ const message = safeErrorMessage(error);
1717
+ cloudBatch.failed.push({
1718
+ scanDir: directory,
1719
+ ...(scanId === undefined ? {} : { scanId }),
1720
+ error: message,
1721
+ });
1722
+ if (controller.signal.aborted)
1723
+ throw error;
1724
+ exitCode = 2;
1725
+ errorOutput.write(`codex-security: ${diagnosticValue(safeErrorMessage(scanId ?? directory))}: ${diagnosticValue(message)}\n`);
1726
+ }
1727
+ }
1728
+ return cloudBatch;
1729
+ }
1730
+ const result = await (dependencies.publishScanToCloud ?? publishScanToCloud)(resolveCliPath(currentDirectory, scanDir), {
1731
+ environment: dependencies.environment,
1732
+ dryRun: options.dryRun,
1733
+ signal: controller.signal,
1734
+ ...(selectedScans[0]?.scanId === undefined
1735
+ ? {}
1736
+ : { expectedScanId: selectedScans[0].scanId }),
1737
+ });
1738
+ return { ...result };
1739
+ }
1514
1740
  const progress = new PublicationProgressPresenter(errorOutput, dependencies, publicationRepository);
1515
1741
  presentation = progress;
1742
+ dependencies.addSignalListener("SIGINT", onInterrupt);
1743
+ dependencies.addSignalListener("SIGTERM", onTerminate);
1744
+ observingSignals = true;
1516
1745
  if (!options.dryRun) {
1517
- dependencies.addSignalListener("SIGINT", onInterrupt);
1518
- dependencies.addSignalListener("SIGTERM", onTerminate);
1519
- observingSignals = true;
1520
1746
  progress.start();
1521
1747
  }
1522
1748
  let result;
1523
1749
  try {
1524
- result = await (dependencies.publishScan ?? publishScan)(resolve(dependencies.currentDirectory(), scanDir), {
1525
- destination: options.to,
1526
- teamId,
1527
- ...(projectId === undefined ? {} : { projectId }),
1750
+ result = await (dependencies.publishScan ?? publishScan)(resolveCliPath(currentDirectory, scanDir), {
1751
+ ...destination,
1752
+ ...(selectedScans[0]?.scanId === undefined
1753
+ ? {}
1754
+ : { expectedScanId: selectedScans[0].scanId }),
1528
1755
  dryRun: options.dryRun,
1529
- ...(linearApiKey === undefined ? {} : { linearApiKey }),
1530
- ...(assigneeId === undefined ? {} : { assigneeId }),
1756
+ signal: controller.signal,
1757
+ ...(options.skipExisting ? { skipExisting: true } : {}),
1531
1758
  ...(options.dryRun
1532
1759
  ? {}
1533
1760
  : {
1534
- signal: controller.signal,
1535
1761
  onProgress: (event) => progress.observe(event),
1536
1762
  }),
1537
1763
  });
@@ -1560,28 +1786,46 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1560
1786
  return { ...result };
1561
1787
  }
1562
1788
  catch (error) {
1563
- const signal = controller.signal.reason;
1564
- if (signal === "SIGINT" || signal === "SIGTERM") {
1565
- const reason = signal === "SIGINT"
1566
- ? "Publication canceled by Ctrl-C."
1567
- : "Publication terminated by SIGTERM.";
1568
- const recovery = error === signal
1569
- ? ""
1570
- : ` ${diagnosticValue(safeErrorMessage(error))}`;
1571
- errorOutput.write(`codex-security: ${reason}${recovery}\n`);
1572
- exitCode = signal === "SIGINT" ? 130 : 143;
1573
- }
1574
- else {
1575
- errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
1789
+ if (!finishCancellation(error)) {
1790
+ errorOutput.write(`codex-security: ${options.to === "cloud" ? safeErrorMessage(error) : errorMessage(error)}\n`);
1576
1791
  exitCode = 2;
1577
1792
  }
1793
+ return cloudBatch;
1794
+ }
1795
+ finally {
1796
+ removeSignalListeners();
1797
+ }
1798
+ },
1799
+ });
1800
+ publication.command("check", {
1801
+ description: "Check saved scan history and Linear access without creating issues.",
1802
+ mcp: false,
1803
+ args: z.object({
1804
+ scanDir: z.string().describe("Completed scan directory."),
1805
+ }),
1806
+ options: PUBLICATION_DESTINATION_OPTIONS,
1807
+ output: z.record(z.string(), z.unknown()).optional(),
1808
+ async run({ args, options }) {
1809
+ const controller = new AbortController();
1810
+ const onInterrupt = () => controller.abort("SIGINT");
1811
+ const onTerminate = () => controller.abort("SIGTERM");
1812
+ dependencies.addSignalListener("SIGINT", onInterrupt);
1813
+ dependencies.addSignalListener("SIGTERM", onTerminate);
1814
+ try {
1815
+ const result = await (dependencies.checkScanPublication ?? checkScanPublication)(resolve(dependencies.currentDirectory(), args.scanDir), {
1816
+ ...publicationDestination(options, dependencies.environment),
1817
+ signal: controller.signal,
1818
+ });
1819
+ controller.signal.throwIfAborted();
1820
+ return { ...result };
1821
+ }
1822
+ catch (error) {
1823
+ reportPublicationError(error, controller.signal.reason);
1578
1824
  return undefined;
1579
1825
  }
1580
1826
  finally {
1581
- if (observingSignals) {
1582
- dependencies.removeSignalListener("SIGINT", onInterrupt);
1583
- dependencies.removeSignalListener("SIGTERM", onTerminate);
1584
- }
1827
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
1828
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
1585
1829
  }
1586
1830
  },
1587
1831
  });
@@ -3089,6 +3333,55 @@ async function* workbenchFindings(arguments_, dependencies) {
3089
3333
  offset = typeof page.nextOffset === "number" ? page.nextOffset : undefined;
3090
3334
  } while (offset !== undefined);
3091
3335
  }
3336
+ async function resolvePublicationScan(requestedId, dependencies) {
3337
+ let scanId = requestedId;
3338
+ if (scanId === "latest") {
3339
+ const history = await dependencies.runWorkbench([
3340
+ "list-scans",
3341
+ "--repository",
3342
+ resolve(dependencies.currentDirectory()),
3343
+ "--status",
3344
+ "complete",
3345
+ ]);
3346
+ const scans = history["scans"];
3347
+ const latest = Array.isArray(scans) ? scans[0] : undefined;
3348
+ if (latest === undefined ||
3349
+ !isJsonObject(latest) ||
3350
+ typeof latest["scanId"] !== "string") {
3351
+ throw new CodexSecurityError("No completed saved scan was found for this repository.");
3352
+ }
3353
+ scanId = latest["scanId"];
3354
+ }
3355
+ const context = await dependencies.runWorkbench([
3356
+ "get-scan",
3357
+ "--scan-id",
3358
+ scanId,
3359
+ ]);
3360
+ const scan = context["scan"];
3361
+ if (scan === undefined ||
3362
+ !isJsonObject(scan) ||
3363
+ typeof scan["scanId"] !== "string") {
3364
+ throw new CodexSecurityError(`Could not read saved scan ${scanId}.`);
3365
+ }
3366
+ scanId = scan["scanId"];
3367
+ const progress = scan["progress"];
3368
+ if (progress === undefined ||
3369
+ !isJsonObject(progress) ||
3370
+ progress["status"] !== "complete") {
3371
+ throw new CodexSecurityError(`Scan ${scanId} is not complete.`);
3372
+ }
3373
+ const storedDirectory = scan["scanDir"];
3374
+ const scanDir = typeof storedDirectory === "string" && storedDirectory.length > 0
3375
+ ? resolveCliPath(dependencies.currentDirectory(), storedDirectory)
3376
+ : undefined;
3377
+ const metadata = scanDir === undefined
3378
+ ? undefined
3379
+ : await lstat(scanDir).catch(() => undefined);
3380
+ if (scanDir === undefined || metadata?.isDirectory() !== true) {
3381
+ throw new CodexSecurityError(`Artifacts for scan ${scanId} are unavailable. Restore the completed scan artifacts or run a new scan.`);
3382
+ }
3383
+ return { ...scan, scanId, scanDir };
3384
+ }
3092
3385
  async function selectSavedFindings(identifiers, requestedScanId, severity, dependencies) {
3093
3386
  if (identifiers.some((identifier) => !isFindingIdentifier(identifier))) {
3094
3387
  throw new CodexSecurityError("Saved scan patching accepts only finding identifiers.");