@openai/codex-security 0.8.0 → 0.8.1

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 (73) hide show
  1. package/README.md +8 -8
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -0
  3. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
  5. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  6. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  7. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  8. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  9. package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
  10. package/_bundled_plugin/references/scan-artifacts.md +1 -1
  11. package/_bundled_plugin/scripts/finalize_scan_contract.py +37 -1
  12. package/_bundled_plugin/scripts/servicenow_avit.py +107 -0
  13. package/_bundled_plugin/scripts/workbench_scan_start.py +4 -1
  14. package/_bundled_plugin/skills/publish-findings/SKILL.md +5 -3
  15. package/_bundled_plugin/skills/security-scan/SKILL.md +1 -1
  16. package/dist/api.d.ts.map +1 -1
  17. package/dist/api.js +33 -12
  18. package/dist/api.js.map +1 -1
  19. package/dist/artifact-export.d.ts +12 -3
  20. package/dist/artifact-export.d.ts.map +1 -1
  21. package/dist/artifact-export.js +30 -10
  22. package/dist/artifact-export.js.map +1 -1
  23. package/dist/cli-help.d.ts.map +1 -1
  24. package/dist/cli-help.js +1 -0
  25. package/dist/cli-help.js.map +1 -1
  26. package/dist/cli.d.ts +1 -1
  27. package/dist/cli.d.ts.map +1 -1
  28. package/dist/cli.js +45 -42
  29. package/dist/cli.js.map +1 -1
  30. package/dist/contract.d.ts +1 -0
  31. package/dist/contract.d.ts.map +1 -1
  32. package/dist/contract.js +12 -8
  33. package/dist/contract.js.map +1 -1
  34. package/dist/custom-validation-prompt.d.ts.map +1 -1
  35. package/dist/custom-validation-prompt.js +12 -4
  36. package/dist/custom-validation-prompt.js.map +1 -1
  37. package/dist/external-findings-local.d.ts.map +1 -1
  38. package/dist/external-findings-local.js +19 -0
  39. package/dist/external-findings-local.js.map +1 -1
  40. package/dist/external-findings-publish.d.ts.map +1 -1
  41. package/dist/external-findings-publish.js +5 -4
  42. package/dist/external-findings-publish.js.map +1 -1
  43. package/dist/github-advisories.d.ts.map +1 -1
  44. package/dist/github-advisories.js +5 -5
  45. package/dist/github-advisories.js.map +1 -1
  46. package/dist/github-dependabot-findings.d.ts +6 -0
  47. package/dist/github-dependabot-findings.d.ts.map +1 -0
  48. package/dist/github-dependabot-findings.js +247 -0
  49. package/dist/github-dependabot-findings.js.map +1 -0
  50. package/dist/github-findings.d.ts.map +1 -1
  51. package/dist/github-findings.js +11 -4
  52. package/dist/github-findings.js.map +1 -1
  53. package/dist/github-identifiers.d.ts +4 -0
  54. package/dist/github-identifiers.d.ts.map +1 -0
  55. package/dist/github-identifiers.js +9 -0
  56. package/dist/github-identifiers.js.map +1 -0
  57. package/dist/github.d.ts.map +1 -1
  58. package/dist/github.js +4 -6
  59. package/dist/github.js.map +1 -1
  60. package/dist/hosted-scan.d.ts.map +1 -1
  61. package/dist/hosted-scan.js +13 -5
  62. package/dist/hosted-scan.js.map +1 -1
  63. package/dist/index.d.ts +1 -0
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +1 -0
  66. package/dist/index.js.map +1 -1
  67. package/dist/scanner-import.d.ts +0 -1
  68. package/dist/scanner-import.d.ts.map +1 -1
  69. package/dist/scanner-import.js +9 -9
  70. package/dist/scanner-import.js.map +1 -1
  71. package/docs/cli.md +39 -7
  72. package/docs/hosted-scans.md +14 -0
  73. package/package.json +4 -4
@@ -1,3 +1,4 @@
1
+ import { CANONICAL_GHSA_ID, githubRepositoryParts, } from "./github-identifiers.js";
1
2
  import { CodexSecurityError, errorMessage } from "./errors.js";
2
3
  import { requireExternalImports } from "./external-imports-feature.js";
3
4
  import { createAuthenticatedGitHub } from "./github.js";
@@ -13,18 +14,17 @@ export async function importGitHubAdvisories(options, dependencies = {}) {
13
14
  const environment = dependencies.environment ?? process.env;
14
15
  requireExternalImports(environment);
15
16
  const repository = options.repository.trim();
16
- const parts = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(repository);
17
- if (!parts || parts.slice(1).some((part) => /^\.{1,2}$/u.test(part)))
17
+ const parts = githubRepositoryParts(repository);
18
+ if (!parts)
18
19
  throw new CodexSecurityError("GitHub repository must be OWNER/REPO.");
19
- const owner = parts[1];
20
- const repo = parts[2];
20
+ const [owner, repo] = parts;
21
21
  const ids = [
22
22
  ...new Set((options.advisoryIds ?? []).map((id) => id
23
23
  .trim()
24
24
  .toLowerCase()
25
25
  .replace(/^ghsa-/u, "GHSA-"))),
26
26
  ];
27
- if (ids.some((id) => !/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/u.test(id)))
27
+ if (ids.some((id) => !CANONICAL_GHSA_ID.test(id)))
28
28
  throw new CodexSecurityError("GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form.");
29
29
  const source = options.source ?? "repository";
30
30
  const state = options.state ?? "published";
@@ -1 +1 @@
1
- {"version":3,"file":"github-advisories.js","sourceRoot":"","sources":["../src/github-advisories.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAExD,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,WAAW;IACX,OAAO;IACP,QAAQ;IACR,QAAQ;CACA,CAAC;AAsCX,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,OAAoC,EACpC,YAAY,GAAqC,EAAE;IAEnD,OAAO,CAAC,MAAM,EAAE,cAAc,EAA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;AAED,KAAK,UAAU,uBAAuB,CACpC,MAAe,EACf,KAAa,EACb,IAAY,EACZ,EAAU,EACV,MAAoB;IAEpB,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,OAAO,CACnC,yDAAyD,EACzD;QACE,KAAK;QACL,IAAI;QACJ,OAAO,EAAE,EAAE;QACX,OAAO,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE;KACvC,CACF,CAAC;IACF,OAAO,QAAQ,CAAC,IAAI,CAAC;AACvB,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,MAAe,EACf,EAAU,EACV,MAAoB;IAEpB,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,2BAA2B,EAAE;QACjE,OAAO,EAAE,EAAE;QACX,OAAO,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE;KACvC,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC,IAAI,CAAC;AACvB,CAAC","sourcesContent":["import type { Octokit } from \"@octokit/core\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\nimport { requireExternalImports } from \"./external-imports-feature.js\";\nimport { createAuthenticatedGitHub } from \"./github.js\";\n\nexport const GITHUB_ADVISORY_STATES = [\n \"published\",\n \"draft\",\n \"triage\",\n \"closed\",\n] as const;\n\nexport interface GitHubAdvisoryImportOptions {\n /** Source repository, or the selected target for explicit global advisory IDs. */\n repository: string;\n /** Exact GHSA IDs. Required for the global advisory API. */\n advisoryIds?: readonly string[];\n /** Repository advisories by default; global never enumerates the database. */\n source?: \"repository\" | \"global\";\n /** Repository list state (default: published). Exact IDs ignore state. */\n state?: (typeof GITHUB_ADVISORY_STATES)[number];\n /** Defaults to GH_HOST or github.com. */\n githubHost?: string;\n /** Omit to use the authenticated GitHub CLI. */\n githubToken?: string;\n signal?: AbortSignal;\n}\n\ntype RepositoryAdvisory = Awaited<ReturnType<typeof fetchRepositoryAdvisory>>;\ntype GlobalAdvisory = Awaited<ReturnType<typeof fetchGlobalAdvisory>>;\n\nexport interface ImportedGitHubAdvisory {\n source: \"github-security-advisory\";\n selection: \"repository\" | \"global\";\n repository: string;\n githubHost: string;\n ghsaId: string;\n url: string;\n /** Upstream disclosure, not proof that the selected repository is affected. */\n advisory: RepositoryAdvisory | GlobalAdvisory;\n}\n\ninterface GitHubAdvisoryImportDependencies {\n environment?: NodeJS.ProcessEnv;\n currentDirectory?: string;\n createGitHub?: (host: string, signal?: AbortSignal) => Promise<Octokit>;\n}\n\n/** Read repository disclosures or explicitly selected public GHSA records. */\nexport async function importGitHubAdvisories(\n options: GitHubAdvisoryImportOptions,\n dependencies: GitHubAdvisoryImportDependencies = {},\n): Promise<ImportedGitHubAdvisory[]> {\n options.signal?.throwIfAborted();\n const environment = dependencies.environment ?? process.env;\n requireExternalImports(environment);\n const repository = options.repository.trim();\n const parts = /^([a-z0-9_.-]+)\\/([a-z0-9_.-]+)$/iu.exec(repository);\n if (!parts || parts.slice(1).some((part) => /^\\.{1,2}$/u.test(part)))\n throw new CodexSecurityError(\"GitHub repository must be OWNER/REPO.\");\n const owner = parts[1]!;\n const repo = parts[2]!;\n const ids = [\n ...new Set(\n (options.advisoryIds ?? []).map((id) =>\n id\n .trim()\n .toLowerCase()\n .replace(/^ghsa-/u, \"GHSA-\"),\n ),\n ),\n ];\n if (ids.some((id) => !/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/u.test(id)))\n throw new CodexSecurityError(\n \"GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form.\",\n );\n const source = options.source ?? \"repository\";\n const state = options.state ?? \"published\";\n if (source !== \"repository\" && source !== \"global\")\n throw new CodexSecurityError(\n \"GitHub advisory source must be repository or global.\",\n );\n if (!GITHUB_ADVISORY_STATES.includes(state))\n throw new CodexSecurityError(\"GitHub advisory state is invalid.\");\n if (source === \"global\" && ids.length === 0)\n throw new CodexSecurityError(\n \"Select explicit GHSA IDs for global advisories; database-wide import is not supported.\",\n );\n if (ids.length > 0 && state !== \"published\")\n throw new CodexSecurityError(\n \"--github-state only filters repository lists; omit it when selecting exact GHSA IDs.\",\n );\n const host =\n options.githubHost?.trim() ??\n (environment[\"GH_HOST\"]?.trim() || \"github.com\");\n if (!host) throw new CodexSecurityError(\"GitHub host must not be empty.\");\n\n try {\n const github = dependencies.createGitHub\n ? await dependencies.createGitHub(host, options.signal)\n : await createAuthenticatedGitHub(host, {\n token: options.githubToken,\n environment,\n currentDirectory: dependencies.currentDirectory,\n signal: options.signal,\n });\n const advisories: (RepositoryAdvisory | GlobalAdvisory)[] = [];\n if (ids.length > 0) {\n for (const id of ids) {\n options.signal?.throwIfAborted();\n advisories.push(\n source === \"global\"\n ? await fetchGlobalAdvisory(github, id, options.signal)\n : await fetchRepositoryAdvisory(\n github,\n owner,\n repo,\n id,\n options.signal,\n ),\n );\n }\n } else {\n let after: string | undefined;\n const cursors = new Set<string>();\n do {\n options.signal?.throwIfAborted();\n const response = await github.request(\n \"GET /repos/{owner}/{repo}/security-advisories\",\n {\n owner,\n repo,\n state,\n per_page: 100,\n after,\n request: { signal: options.signal, redirect: \"error\" },\n },\n );\n advisories.push(...response.data);\n const next = response.headers.link\n ?.split(\",\")\n .find((link) => /;\\s*rel=\"next\"/u.test(link));\n const nextUrl = next?.match(/<([^>]+)>/u)?.[1];\n // Keep requests on the authenticated route; only carry over the cursor.\n after = nextUrl\n ? (new URL(nextUrl).searchParams.get(\"after\") ?? undefined)\n : undefined;\n if (next && (!after || cursors.has(after)))\n throw new CodexSecurityError(\n \"GitHub returned invalid advisory pagination.\",\n );\n if (after) cursors.add(after);\n } while (after !== undefined);\n }\n return advisories.map((advisory) => ({\n source: \"github-security-advisory\",\n selection: source,\n repository,\n githubHost: host,\n ghsaId: advisory.ghsa_id,\n url: advisory.html_url,\n advisory,\n }));\n } catch (error) {\n options.signal?.throwIfAborted();\n if (error instanceof CodexSecurityError) throw error;\n const status =\n typeof error === \"object\" && error !== null && \"status\" in error\n ? error.status\n : undefined;\n if (status === 401)\n throw new CodexSecurityError(\"GitHub authentication failed.\");\n if (status === 403)\n throw new CodexSecurityError(\n \"GitHub denied security advisory access. Check repository advisory permissions and API rate limits.\",\n );\n if (status === 404)\n throw new CodexSecurityError(\n \"GitHub repository or security advisory was not found or is not accessible.\",\n );\n if (status === 429)\n throw new CodexSecurityError(\n \"GitHub request was rate limited. Wait and retry.\",\n );\n throw new CodexSecurityError(\n `GitHub security advisory request failed${typeof status === \"number\" ? ` (HTTP ${status})` : \"\"}: ${errorMessage(error)}`,\n );\n }\n}\n\nasync function fetchRepositoryAdvisory(\n github: Octokit,\n owner: string,\n repo: string,\n id: string,\n signal?: AbortSignal,\n) {\n const response = await github.request(\n \"GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}\",\n {\n owner,\n repo,\n ghsa_id: id,\n request: { signal, redirect: \"error\" },\n },\n );\n return response.data;\n}\n\nasync function fetchGlobalAdvisory(\n github: Octokit,\n id: string,\n signal?: AbortSignal,\n) {\n const response = await github.request(\"GET /advisories/{ghsa_id}\", {\n ghsa_id: id,\n request: { signal, redirect: \"error\" },\n });\n return response.data;\n}\n"]}
1
+ {"version":3,"file":"github-advisories.js","sourceRoot":"","sources":["../src/github-advisories.ts"],"names":[],"mappings":"AACA,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAExD,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,WAAW;IACX,OAAO;IACP,QAAQ;IACR,QAAQ;CACA,CAAC;AAsCX,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,OAAoC,EACpC,YAAY,GAAqC,EAAE;IAEnD,OAAO,CAAC,MAAM,EAAE,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OAAO,EAAE,EAAE;QACX,OAAO,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE;KACvC,CACF,CAAC;IACF,OAAO,QAAQ,CAAC,IAAI,CAAC;AACvB,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,MAAe,EACf,EAAU,EACV,MAAoB;IAEpB,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,2BAA2B,EAAE;QACjE,OAAO,EAAE,EAAE;QACX,OAAO,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE;KACvC,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC,IAAI,CAAC;AACvB,CAAC","sourcesContent":["import type { Octokit } from \"@octokit/core\";\nimport {\n CANONICAL_GHSA_ID,\n githubRepositoryParts,\n} from \"./github-identifiers.js\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\nimport { requireExternalImports } from \"./external-imports-feature.js\";\nimport { createAuthenticatedGitHub } from \"./github.js\";\n\nexport const GITHUB_ADVISORY_STATES = [\n \"published\",\n \"draft\",\n \"triage\",\n \"closed\",\n] as const;\n\nexport interface GitHubAdvisoryImportOptions {\n /** Source repository, or the selected target for explicit global advisory IDs. */\n repository: string;\n /** Exact GHSA IDs. Required for the global advisory API. */\n advisoryIds?: readonly string[];\n /** Repository advisories by default; global never enumerates the database. */\n source?: \"repository\" | \"global\";\n /** Repository list state (default: published). Exact IDs ignore state. */\n state?: (typeof GITHUB_ADVISORY_STATES)[number];\n /** Defaults to GH_HOST or github.com. */\n githubHost?: string;\n /** Omit to use the authenticated GitHub CLI. */\n githubToken?: string;\n signal?: AbortSignal;\n}\n\ntype RepositoryAdvisory = Awaited<ReturnType<typeof fetchRepositoryAdvisory>>;\ntype GlobalAdvisory = Awaited<ReturnType<typeof fetchGlobalAdvisory>>;\n\nexport interface ImportedGitHubAdvisory {\n source: \"github-security-advisory\";\n selection: \"repository\" | \"global\";\n repository: string;\n githubHost: string;\n ghsaId: string;\n url: string;\n /** Upstream disclosure, not proof that the selected repository is affected. */\n advisory: RepositoryAdvisory | GlobalAdvisory;\n}\n\ninterface GitHubAdvisoryImportDependencies {\n environment?: NodeJS.ProcessEnv;\n currentDirectory?: string;\n createGitHub?: (host: string, signal?: AbortSignal) => Promise<Octokit>;\n}\n\n/** Read repository disclosures or explicitly selected public GHSA records. */\nexport async function importGitHubAdvisories(\n options: GitHubAdvisoryImportOptions,\n dependencies: GitHubAdvisoryImportDependencies = {},\n): Promise<ImportedGitHubAdvisory[]> {\n options.signal?.throwIfAborted();\n const environment = dependencies.environment ?? process.env;\n requireExternalImports(environment);\n const repository = options.repository.trim();\n const parts = githubRepositoryParts(repository);\n if (!parts)\n throw new CodexSecurityError(\"GitHub repository must be OWNER/REPO.\");\n const [owner, repo] = parts;\n const ids = [\n ...new Set(\n (options.advisoryIds ?? []).map((id) =>\n id\n .trim()\n .toLowerCase()\n .replace(/^ghsa-/u, \"GHSA-\"),\n ),\n ),\n ];\n if (ids.some((id) => !CANONICAL_GHSA_ID.test(id)))\n throw new CodexSecurityError(\n \"GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form.\",\n );\n const source = options.source ?? \"repository\";\n const state = options.state ?? \"published\";\n if (source !== \"repository\" && source !== \"global\")\n throw new CodexSecurityError(\n \"GitHub advisory source must be repository or global.\",\n );\n if (!GITHUB_ADVISORY_STATES.includes(state))\n throw new CodexSecurityError(\"GitHub advisory state is invalid.\");\n if (source === \"global\" && ids.length === 0)\n throw new CodexSecurityError(\n \"Select explicit GHSA IDs for global advisories; database-wide import is not supported.\",\n );\n if (ids.length > 0 && state !== \"published\")\n throw new CodexSecurityError(\n \"--github-state only filters repository lists; omit it when selecting exact GHSA IDs.\",\n );\n const host =\n options.githubHost?.trim() ??\n (environment[\"GH_HOST\"]?.trim() || \"github.com\");\n if (!host) throw new CodexSecurityError(\"GitHub host must not be empty.\");\n\n try {\n const github = dependencies.createGitHub\n ? await dependencies.createGitHub(host, options.signal)\n : await createAuthenticatedGitHub(host, {\n token: options.githubToken,\n environment,\n currentDirectory: dependencies.currentDirectory,\n signal: options.signal,\n });\n const advisories: (RepositoryAdvisory | GlobalAdvisory)[] = [];\n if (ids.length > 0) {\n for (const id of ids) {\n options.signal?.throwIfAborted();\n advisories.push(\n source === \"global\"\n ? await fetchGlobalAdvisory(github, id, options.signal)\n : await fetchRepositoryAdvisory(\n github,\n owner,\n repo,\n id,\n options.signal,\n ),\n );\n }\n } else {\n let after: string | undefined;\n const cursors = new Set<string>();\n do {\n options.signal?.throwIfAborted();\n const response = await github.request(\n \"GET /repos/{owner}/{repo}/security-advisories\",\n {\n owner,\n repo,\n state,\n per_page: 100,\n after,\n request: { signal: options.signal, redirect: \"error\" },\n },\n );\n advisories.push(...response.data);\n const next = response.headers.link\n ?.split(\",\")\n .find((link) => /;\\s*rel=\"next\"/u.test(link));\n const nextUrl = next?.match(/<([^>]+)>/u)?.[1];\n // Keep requests on the authenticated route; only carry over the cursor.\n after = nextUrl\n ? (new URL(nextUrl).searchParams.get(\"after\") ?? undefined)\n : undefined;\n if (next && (!after || cursors.has(after)))\n throw new CodexSecurityError(\n \"GitHub returned invalid advisory pagination.\",\n );\n if (after) cursors.add(after);\n } while (after !== undefined);\n }\n return advisories.map((advisory) => ({\n source: \"github-security-advisory\",\n selection: source,\n repository,\n githubHost: host,\n ghsaId: advisory.ghsa_id,\n url: advisory.html_url,\n advisory,\n }));\n } catch (error) {\n options.signal?.throwIfAborted();\n if (error instanceof CodexSecurityError) throw error;\n const status =\n typeof error === \"object\" && error !== null && \"status\" in error\n ? error.status\n : undefined;\n if (status === 401)\n throw new CodexSecurityError(\"GitHub authentication failed.\");\n if (status === 403)\n throw new CodexSecurityError(\n \"GitHub denied security advisory access. Check repository advisory permissions and API rate limits.\",\n );\n if (status === 404)\n throw new CodexSecurityError(\n \"GitHub repository or security advisory was not found or is not accessible.\",\n );\n if (status === 429)\n throw new CodexSecurityError(\n \"GitHub request was rate limited. Wait and retry.\",\n );\n throw new CodexSecurityError(\n `GitHub security advisory request failed${typeof status === \"number\" ? ` (HTTP ${status})` : \"\"}: ${errorMessage(error)}`,\n );\n }\n}\n\nasync function fetchRepositoryAdvisory(\n github: Octokit,\n owner: string,\n repo: string,\n id: string,\n signal?: AbortSignal,\n) {\n const response = await github.request(\n \"GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}\",\n {\n owner,\n repo,\n ghsa_id: id,\n request: { signal, redirect: \"error\" },\n },\n );\n return response.data;\n}\n\nasync function fetchGlobalAdvisory(\n github: Octokit,\n id: string,\n signal?: AbortSignal,\n) {\n const response = await github.request(\"GET /advisories/{ghsa_id}\", {\n ghsa_id: id,\n request: { signal, redirect: \"error\" },\n });\n return response.data;\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import { type ExternalImportTarget } from "./external-import-contract.js";
2
+ import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
3
+ export declare function isGitHubDependabotAlert(value: unknown): value is Record<string, unknown>;
4
+ export declare function dependabotRepository({ source_finding_id: id, evidence: { source_data: sourceData, url }, }: ExternalFinding): string | undefined;
5
+ export declare function normalizeGitHubDependabotAlerts(input: unknown, target?: ExternalImportTarget): ExternalFindings;
6
+ //# sourceMappingURL=github-dependabot-findings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-dependabot-findings.d.ts","sourceRoot":"","sources":["../src/github-dependabot-findings.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,oBAAoB,EAE1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAKhF,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAalC;AAkHD,wBAAgB,oBAAoB,CAAC,EACnC,iBAAiB,EAAE,EAAE,EACrB,QAAQ,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,GAAG,EAAE,GAC3C,EAAE,eAAe,GAAG,MAAM,GAAG,SAAS,CA8BtC;AAmID,wBAAgB,+BAA+B,CAC7C,KAAK,EAAE,OAAO,EACd,MAAM,GAAE,oBAA8B,GACrC,gBAAgB,CAwClB"}
@@ -0,0 +1,247 @@
1
+ import { z } from "zod";
2
+ import { GHSA_ID, githubRepositoryParts } from "./github-identifiers.js";
3
+ import { CodexSecurityError, errorMessage } from "./errors.js";
4
+ import { validateExternalEvidence, } from "./external-import-contract.js";
5
+ import { isGitHubCloudHost } from "./git-remote.js";
6
+ import { isRecord } from "./record.js";
7
+ import { record, relativePath, requiredText, text } from "./scanner-import.js";
8
+ export function isGitHubDependabotAlert(value) {
9
+ return (isRecord(value) &&
10
+ ("security_vulnerability" in value ||
11
+ ("dependency" in value && "security_advisory" in value) ||
12
+ [value["url"], value["html_url"]].some((url) => typeof url === "string" &&
13
+ /^\/(?:[^/]+\/[^/]+\/security\/dependabot|(?:api\/v3\/)?repos\/[^/]+\/[^/]+\/dependabot\/alerts)\/\d+$/iu.test(URL.parse(url)?.pathname ?? ""))));
14
+ }
15
+ function webIdentity(url) {
16
+ const match = /^(https?):\/\/([^/?#@\\\s]+)\/([^/?#]+\/[^/?#]+)\/security\/dependabot\/([1-9]\d*)$/iu.exec(url);
17
+ if (!match || !githubRepositoryParts(match[3]))
18
+ return null;
19
+ const parsed = URL.parse(url);
20
+ if (!parsed ||
21
+ (parsed.protocol === "http:" && isGitHubCloudHost(parsed.hostname)))
22
+ return null;
23
+ const host = match[2].toLowerCase();
24
+ const repository = match[3].toLowerCase();
25
+ const origin = `${parsed.protocol}//${host}`;
26
+ const number = match[4];
27
+ const apiBase = isGitHubCloudHost(parsed.hostname)
28
+ ? `https://api.${host}`
29
+ : `${origin}/api/v3`;
30
+ const repositoryUrl = `${origin}/${repository}`;
31
+ const apiRepo = `${apiBase}/repos/${repository}`;
32
+ return {
33
+ repository,
34
+ repositoryUrl,
35
+ apiRepo,
36
+ number,
37
+ sourceId: `${host}/${repository}/dependabot/${number}`,
38
+ htmlUrl: `${repositoryUrl}/security/dependabot/${number}`,
39
+ apiUrl: `${apiRepo}/dependabot/alerts/${number}`,
40
+ };
41
+ }
42
+ // Normalized SDK evidence may link to either REST or the web UI.
43
+ function alertUrlIdentity(url) {
44
+ if (typeof url !== "string")
45
+ return null;
46
+ const web = webIdentity(url);
47
+ if (web)
48
+ return web;
49
+ const api = /^(https?:\/\/)([^/?#@\\\s]+)\/(api\/v3\/)?repos\/([^/]+\/[^/]+)\/dependabot\/alerts\/([1-9]\d*)$/iu.exec(url);
50
+ if (!api)
51
+ return null;
52
+ const host = api[3] ? api[2] : api[2].replace(/^api\./iu, "");
53
+ const parsed = webIdentity(`${api[1]}${host}/${api[4]}/security/dependabot/${api[5]}`);
54
+ return parsed?.apiUrl === url.toLowerCase() ? parsed : null;
55
+ }
56
+ function checkSourceFamily(alert) {
57
+ if (alert["source"] === "github-code-scanning" ||
58
+ alert["source"] === "github-security-advisory")
59
+ throw new Error("Dependabot alert conflicts with its GitHub source family.");
60
+ }
61
+ function checkNativeClaims(alert, occurrence) {
62
+ if ("number" in alert && alert["number"] !== Number(occurrence.number))
63
+ throw new Error("Dependabot alert number must match the repository alert URL.");
64
+ if (("url" in alert &&
65
+ text(alert["url"])?.toLowerCase() !== occurrence.apiUrl) ||
66
+ ("html_url" in alert &&
67
+ text(alert["html_url"])?.toLowerCase() !== occurrence.htmlUrl))
68
+ throw new Error("Dependabot API url and html_url must identify the same host, repository and alert number.");
69
+ if ("repository" in alert) {
70
+ const declared = record(alert["repository"], "Dependabot repository");
71
+ if (text(declared["full_name"])?.toLowerCase() !== occurrence.repository ||
72
+ ("html_url" in declared &&
73
+ text(declared["html_url"])?.toLowerCase() !==
74
+ occurrence.repositoryUrl) ||
75
+ ("url" in declared &&
76
+ text(declared["url"])?.toLowerCase() !== occurrence.apiRepo))
77
+ throw new Error("Dependabot repository metadata conflicts with its alert URLs.");
78
+ }
79
+ }
80
+ function identity(alert) {
81
+ checkSourceFamily(alert);
82
+ const number = alert["number"];
83
+ if (typeof number !== "number" || !Number.isSafeInteger(number) || number < 1)
84
+ throw new Error("Dependabot alert number must be a positive safe integer.");
85
+ const url = requiredText(alert["html_url"], "Dependabot html_url");
86
+ const parsed = webIdentity(url);
87
+ if (!parsed || parsed.number !== String(number))
88
+ throw new Error("Dependabot html_url must identify the repository and alert number.");
89
+ requiredText(alert["url"], "Dependabot API url");
90
+ checkNativeClaims(alert, parsed);
91
+ return {
92
+ repositoryUrl: parsed.repositoryUrl,
93
+ sourceId: parsed.sourceId,
94
+ url,
95
+ };
96
+ }
97
+ export function dependabotRepository({ source_finding_id: id, evidence: { source_data: sourceData, url }, }) {
98
+ const native = isGitHubDependabotAlert(sourceData) ? sourceData : null;
99
+ const raw = native &&
100
+ (alertUrlIdentity(native["html_url"]) ?? alertUrlIdentity(native["url"]));
101
+ const projected = alertUrlIdentity(url);
102
+ const occurrence = raw ?? projected;
103
+ const structuredId = /^[^/]+\/[^/]+\/[^/]+\/(?:dependabot|code-scanning|security-advisory)\//u.test(id);
104
+ if (!occurrence) {
105
+ if (/^[^/]+\/[^/]+\/[^/]+\/dependabot\/[1-9]\d*$/u.test(id))
106
+ throw new CodexSecurityError("The normalized Dependabot occurrence needs the original alert or its repository alert URL.");
107
+ return;
108
+ }
109
+ if (isRecord(sourceData))
110
+ checkSourceFamily(sourceData);
111
+ if (native)
112
+ checkNativeClaims(native, occurrence);
113
+ // A caller may have stored this occurrence under an opaque ID before native imports existed.
114
+ if ((structuredId || id === "") && id !== occurrence.sourceId)
115
+ throw new CodexSecurityError("The normalized source finding ID does not match the original Dependabot alert.");
116
+ if (raw && projected && raw.htmlUrl !== projected.htmlUrl)
117
+ throw new CodexSecurityError("The normalized alert URL does not match the original Dependabot alert.");
118
+ return occurrence.repositoryUrl;
119
+ }
120
+ function selectedAlerts(input) {
121
+ const selection = Array.isArray(input) ? input : [input];
122
+ const hasPages = selection.some(Array.isArray);
123
+ if (hasPages && !selection.every(Array.isArray))
124
+ throw new Error("Dependabot input must not mix alert records and page arrays.");
125
+ const rows = hasPages ? selection.flat() : selection;
126
+ if (!rows.every(isGitHubDependabotAlert))
127
+ throw new Error("Expected complete native Dependabot repository alerts, not mixed families, page shapes or API envelopes.");
128
+ return rows;
129
+ }
130
+ // Parse only the matched vulnerability projection. Keep the complete upstream alert as evidence.
131
+ const nonblank = z.string().regex(/\S/u);
132
+ const matchedVulnerability = z.object({
133
+ package: z.object({ name: nonblank, ecosystem: nonblank }),
134
+ vulnerable_version_range: nonblank,
135
+ first_patched_version: z.object({ identifier: nonblank }).nullable(),
136
+ severity: z.enum(["critical", "high", "medium", "low"]),
137
+ });
138
+ function evidence(alert, url) {
139
+ const dependency = record(alert["dependency"], "Dependabot dependency");
140
+ const advisory = record(alert["security_advisory"], "Dependabot security_advisory");
141
+ const { package: { name, ecosystem }, vulnerable_version_range: range, first_patched_version: patch, severity, } = matchedVulnerability.parse(alert["security_vulnerability"]);
142
+ if ("package" in dependency) {
143
+ const observed = record(dependency["package"], "Dependabot dependency package");
144
+ if (observed["name"] !== name || observed["ecosystem"] !== ecosystem)
145
+ throw new Error("Dependabot dependency and matched vulnerability packages disagree.");
146
+ }
147
+ const path = dependency["manifest_path"] ?? null;
148
+ if (path !== null) {
149
+ const filename = relativePath(path)?.split("/").at(-1);
150
+ if (typeof path !== "string" ||
151
+ /^[a-z][a-z\d+.-]*:/iu.test(path) ||
152
+ !filename ||
153
+ filename === ".")
154
+ throw new Error("Dependabot manifest_path must identify a repository-relative file.");
155
+ }
156
+ const ghsa = requiredText(advisory["ghsa_id"], "Dependabot GHSA ID");
157
+ if (!GHSA_ID.test(ghsa))
158
+ throw new Error("Dependabot security_advisory must identify a GHSA.");
159
+ const affected = advisory["vulnerabilities"];
160
+ if (!Array.isArray(affected) ||
161
+ !affected.some((entry) => isRecord(entry) &&
162
+ isRecord(entry["package"]) &&
163
+ entry["package"]["name"] === name &&
164
+ entry["package"]["ecosystem"] === ecosystem &&
165
+ entry["vulnerable_version_range"] === range))
166
+ throw new Error("Dependabot advisory does not cover the matched package and vulnerable range.");
167
+ const state = alert["state"];
168
+ if (typeof state !== "string" ||
169
+ !["open", "dismissed", "auto_dismissed", "fixed"].includes(state))
170
+ throw new Error("Dependabot alert state must be open, dismissed, auto_dismissed or fixed.");
171
+ const updated = Date.parse(requiredText(alert["updated_at"], "Dependabot updated_at")) /
172
+ 1000;
173
+ if (!Number.isFinite(updated) || updated < 0)
174
+ throw new Error("Dependabot updated_at must be a valid timestamp.");
175
+ const advisoryIds = new Set([ghsa]);
176
+ const cve = text(advisory["cve_id"]);
177
+ if (cve)
178
+ advisoryIds.add(cve);
179
+ const identifiers = advisory["identifiers"];
180
+ if (Array.isArray(identifiers)) {
181
+ for (const item of identifiers) {
182
+ const value = isRecord(item) && text(item["value"]);
183
+ if (!value)
184
+ continue;
185
+ if ((item["type"] === "GHSA" || /^GHSA-/iu.test(value)) &&
186
+ value.toUpperCase() !== ghsa.toUpperCase())
187
+ throw new Error("Dependabot advisory identifiers disagree on the GHSA.");
188
+ advisoryIds.add(value);
189
+ }
190
+ }
191
+ return {
192
+ title: requiredText(advisory["summary"], "Dependabot advisory summary"),
193
+ description: text(advisory["description"]),
194
+ severity,
195
+ url,
196
+ advisory_ids: [...advisoryIds],
197
+ packages: [
198
+ {
199
+ name,
200
+ ecosystem,
201
+ manifest_path: path,
202
+ vulnerable_version_range: range,
203
+ fixed_versions: patch ? [patch.identifier] : [],
204
+ },
205
+ ],
206
+ locations: path ? [{ path }] : [],
207
+ source_updated_at: Math.floor(updated),
208
+ source_data: structuredClone(alert),
209
+ };
210
+ }
211
+ export function normalizeGitHubDependabotAlerts(input, target = "cloud") {
212
+ const alerts = selectedAlerts(input);
213
+ const result = {
214
+ read: alerts.length,
215
+ findings: [],
216
+ excluded: [],
217
+ };
218
+ const ids = new Set();
219
+ let sourceRepository;
220
+ for (const [index, alert] of alerts.entries()) {
221
+ const { repositoryUrl, sourceId, url } = identity(alert);
222
+ if (sourceRepository !== undefined && sourceRepository !== repositoryUrl)
223
+ throw new CodexSecurityError("Select Dependabot alerts from only one GitHub host and repository.");
224
+ sourceRepository = repositoryUrl;
225
+ if (ids.has(sourceId))
226
+ throw new CodexSecurityError(`Duplicate source finding id ${JSON.stringify(sourceId)}. Select each Dependabot alert once.`);
227
+ ids.add(sourceId);
228
+ const inputEvidence = evidence(alert, url);
229
+ try {
230
+ if (target === "cloud" && Buffer.byteLength(sourceId) > 512)
231
+ throw new Error("Source finding ID exceeds the Cloud limit of 512 UTF-8 bytes.");
232
+ result.findings.push({
233
+ source_finding_id: sourceId,
234
+ evidence: validateExternalEvidence(inputEvidence, target),
235
+ });
236
+ }
237
+ catch (error) {
238
+ result.excluded.push({
239
+ position: index + 1,
240
+ source_finding_id: sourceId,
241
+ reason: errorMessage(error),
242
+ });
243
+ }
244
+ }
245
+ return result;
246
+ }
247
+ //# sourceMappingURL=github-dependabot-findings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-dependabot-findings.js","sourceRoot":"","sources":["../src/github-dependabot-findings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAEL,wBAAwB,GACzB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAE/E,MAAM,UAAU,uBAAuB,CACrC,KAAc;IAEd,OAAO,CACL,QAAQ,CAAC,KAAK,CAAC;QACf,CAAC,wBAAwB,IAAI,KAAK;YAChC,CAAC,YAA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QACjC,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC;YACnB,MAAM,IAAI,kBAAkB,CAC1B,+BAA+B,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,sCAAsC,CAC9F,CAAC;QACJ,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAClB,MAAM,aAAa,GAAG,QAAQ,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QAC3C,IAAI,CAAC;YACH,IAAI,MAAM,KAAK,OAAO,IAAI,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,GAAG,GAAG;gBACzD,MAAM,IAAI,KAAK,CACb,+DAA+D,CAChE,CAAC;YACJ,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACnB,iBAAiB,EAAE,QAAQ;gBAC3B,QAAQ,EAAE,wBAAwB,CAAC,aAAa,EAAE,MAAM,CAAC;aAC1D,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACnB,QAAQ,EAAE,KAAK,GAAG,CAAC;gBACnB,iBAAiB,EAAE,QAAQ;gBAC3B,MAAM,EAAE,YAAY,CAAC,KAAK,CAAC;aAC5B,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { GHSA_ID, githubRepositoryParts } from \"./github-identifiers.js\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\nimport {\n type ExternalImportTarget,\n validateExternalEvidence,\n} from \"./external-import-contract.js\";\nimport type { ExternalFinding, ExternalFindings } from \"./external-findings.js\";\nimport { isGitHubCloudHost } from \"./git-remote.js\";\nimport { isRecord } from \"./record.js\";\nimport { record, relativePath, requiredText, text } from \"./scanner-import.js\";\n\nexport function isGitHubDependabotAlert(\n value: unknown,\n): value is Record<string, unknown> {\n return (\n isRecord(value) &&\n (\"security_vulnerability\" in value ||\n (\"dependency\" in value && \"security_advisory\" in value) ||\n [value[\"url\"], value[\"html_url\"]].some(\n (url) =>\n typeof url === \"string\" &&\n /^\\/(?:[^/]+\\/[^/]+\\/security\\/dependabot|(?:api\\/v3\\/)?repos\\/[^/]+\\/[^/]+\\/dependabot\\/alerts)\\/\\d+$/iu.test(\n URL.parse(url)?.pathname ?? \"\",\n ),\n ))\n );\n}\n\nfunction webIdentity(url: string) {\n const match =\n /^(https?):\\/\\/([^/?#@\\\\\\s]+)\\/([^/?#]+\\/[^/?#]+)\\/security\\/dependabot\\/([1-9]\\d*)$/iu.exec(\n url,\n );\n if (!match || !githubRepositoryParts(match[3]!)) return null;\n const parsed = URL.parse(url);\n if (\n !parsed ||\n (parsed.protocol === \"http:\" && isGitHubCloudHost(parsed.hostname))\n )\n return null;\n const host = match[2]!.toLowerCase();\n const repository = match[3]!.toLowerCase();\n const origin = `${parsed.protocol}//${host}`;\n const number = match[4]!;\n const apiBase = isGitHubCloudHost(parsed.hostname)\n ? `https://api.${host}`\n : `${origin}/api/v3`;\n const repositoryUrl = `${origin}/${repository}`;\n const apiRepo = `${apiBase}/repos/${repository}`;\n return {\n repository,\n repositoryUrl,\n apiRepo,\n number,\n sourceId: `${host}/${repository}/dependabot/${number}`,\n htmlUrl: `${repositoryUrl}/security/dependabot/${number}`,\n apiUrl: `${apiRepo}/dependabot/alerts/${number}`,\n };\n}\n\n// Normalized SDK evidence may link to either REST or the web UI.\nfunction alertUrlIdentity(url: unknown) {\n if (typeof url !== \"string\") return null;\n const web = webIdentity(url);\n if (web) return web;\n const api =\n /^(https?:\\/\\/)([^/?#@\\\\\\s]+)\\/(api\\/v3\\/)?repos\\/([^/]+\\/[^/]+)\\/dependabot\\/alerts\\/([1-9]\\d*)$/iu.exec(\n url,\n );\n if (!api) return null;\n const host = api[3] ? api[2] : api[2]!.replace(/^api\\./iu, \"\");\n const parsed = webIdentity(\n `${api[1]}${host}/${api[4]}/security/dependabot/${api[5]}`,\n );\n return parsed?.apiUrl === url.toLowerCase() ? parsed : null;\n}\n\nfunction checkSourceFamily(alert: Record<string, unknown>) {\n if (\n alert[\"source\"] === \"github-code-scanning\" ||\n alert[\"source\"] === \"github-security-advisory\"\n )\n throw new Error(\n \"Dependabot alert conflicts with its GitHub source family.\",\n );\n}\n\nfunction checkNativeClaims(\n alert: Record<string, unknown>,\n occurrence: NonNullable<ReturnType<typeof webIdentity>>,\n) {\n if (\"number\" in alert && alert[\"number\"] !== Number(occurrence.number))\n throw new Error(\n \"Dependabot alert number must match the repository alert URL.\",\n );\n if (\n (\"url\" in alert &&\n text(alert[\"url\"])?.toLowerCase() !== occurrence.apiUrl) ||\n (\"html_url\" in alert &&\n text(alert[\"html_url\"])?.toLowerCase() !== occurrence.htmlUrl)\n )\n throw new Error(\n \"Dependabot API url and html_url must identify the same host, repository and alert number.\",\n );\n if (\"repository\" in alert) {\n const declared = record(alert[\"repository\"], \"Dependabot repository\");\n if (\n text(declared[\"full_name\"])?.toLowerCase() !== occurrence.repository ||\n (\"html_url\" in declared &&\n text(declared[\"html_url\"])?.toLowerCase() !==\n occurrence.repositoryUrl) ||\n (\"url\" in declared &&\n text(declared[\"url\"])?.toLowerCase() !== occurrence.apiRepo)\n )\n throw new Error(\n \"Dependabot repository metadata conflicts with its alert URLs.\",\n );\n }\n}\n\nfunction identity(alert: Record<string, unknown>) {\n checkSourceFamily(alert);\n const number = alert[\"number\"];\n if (typeof number !== \"number\" || !Number.isSafeInteger(number) || number < 1)\n throw new Error(\"Dependabot alert number must be a positive safe integer.\");\n const url = requiredText(alert[\"html_url\"], \"Dependabot html_url\");\n const parsed = webIdentity(url);\n if (!parsed || parsed.number !== String(number))\n throw new Error(\n \"Dependabot html_url must identify the repository and alert number.\",\n );\n requiredText(alert[\"url\"], \"Dependabot API url\");\n checkNativeClaims(alert, parsed);\n return {\n repositoryUrl: parsed.repositoryUrl,\n sourceId: parsed.sourceId,\n url,\n };\n}\n\nexport function dependabotRepository({\n source_finding_id: id,\n evidence: { source_data: sourceData, url },\n}: ExternalFinding): string | undefined {\n const native = isGitHubDependabotAlert(sourceData) ? sourceData : null;\n const raw =\n native &&\n (alertUrlIdentity(native[\"html_url\"]) ?? alertUrlIdentity(native[\"url\"]));\n const projected = alertUrlIdentity(url);\n const occurrence = raw ?? projected;\n const structuredId =\n /^[^/]+\\/[^/]+\\/[^/]+\\/(?:dependabot|code-scanning|security-advisory)\\//u.test(\n id,\n );\n if (!occurrence) {\n if (/^[^/]+\\/[^/]+\\/[^/]+\\/dependabot\\/[1-9]\\d*$/u.test(id))\n throw new CodexSecurityError(\n \"The normalized Dependabot occurrence needs the original alert or its repository alert URL.\",\n );\n return;\n }\n if (isRecord(sourceData)) checkSourceFamily(sourceData);\n if (native) checkNativeClaims(native, occurrence);\n // A caller may have stored this occurrence under an opaque ID before native imports existed.\n if ((structuredId || id === \"\") && id !== occurrence.sourceId)\n throw new CodexSecurityError(\n \"The normalized source finding ID does not match the original Dependabot alert.\",\n );\n if (raw && projected && raw.htmlUrl !== projected.htmlUrl)\n throw new CodexSecurityError(\n \"The normalized alert URL does not match the original Dependabot alert.\",\n );\n return occurrence.repositoryUrl;\n}\n\nfunction selectedAlerts(input: unknown) {\n const selection = Array.isArray(input) ? input : [input];\n const hasPages = selection.some(Array.isArray);\n if (hasPages && !selection.every(Array.isArray))\n throw new Error(\n \"Dependabot input must not mix alert records and page arrays.\",\n );\n const rows: unknown[] = hasPages ? selection.flat() : selection;\n if (!rows.every(isGitHubDependabotAlert))\n throw new Error(\n \"Expected complete native Dependabot repository alerts, not mixed families, page shapes or API envelopes.\",\n );\n return rows;\n}\n\n// Parse only the matched vulnerability projection. Keep the complete upstream alert as evidence.\nconst nonblank = z.string().regex(/\\S/u);\nconst matchedVulnerability = z.object({\n package: z.object({ name: nonblank, ecosystem: nonblank }),\n vulnerable_version_range: nonblank,\n first_patched_version: z.object({ identifier: nonblank }).nullable(),\n severity: z.enum([\"critical\", \"high\", \"medium\", \"low\"]),\n});\n\nfunction evidence(alert: Record<string, unknown>, url: string) {\n const dependency = record(alert[\"dependency\"], \"Dependabot dependency\");\n const advisory = record(\n alert[\"security_advisory\"],\n \"Dependabot security_advisory\",\n );\n const {\n package: { name, ecosystem },\n vulnerable_version_range: range,\n first_patched_version: patch,\n severity,\n } = matchedVulnerability.parse(alert[\"security_vulnerability\"]);\n if (\"package\" in dependency) {\n const observed = record(\n dependency[\"package\"],\n \"Dependabot dependency package\",\n );\n if (observed[\"name\"] !== name || observed[\"ecosystem\"] !== ecosystem)\n throw new Error(\n \"Dependabot dependency and matched vulnerability packages disagree.\",\n );\n }\n const path = dependency[\"manifest_path\"] ?? null;\n if (path !== null) {\n const filename = relativePath(path)?.split(\"/\").at(-1);\n if (\n typeof path !== \"string\" ||\n /^[a-z][a-z\\d+.-]*:/iu.test(path) ||\n !filename ||\n filename === \".\"\n )\n throw new Error(\n \"Dependabot manifest_path must identify a repository-relative file.\",\n );\n }\n const ghsa = requiredText(advisory[\"ghsa_id\"], \"Dependabot GHSA ID\");\n if (!GHSA_ID.test(ghsa))\n throw new Error(\"Dependabot security_advisory must identify a GHSA.\");\n const affected = advisory[\"vulnerabilities\"];\n if (\n !Array.isArray(affected) ||\n !affected.some(\n (entry) =>\n isRecord(entry) &&\n isRecord(entry[\"package\"]) &&\n entry[\"package\"][\"name\"] === name &&\n entry[\"package\"][\"ecosystem\"] === ecosystem &&\n entry[\"vulnerable_version_range\"] === range,\n )\n )\n throw new Error(\n \"Dependabot advisory does not cover the matched package and vulnerable range.\",\n );\n const state = alert[\"state\"];\n if (\n typeof state !== \"string\" ||\n ![\"open\", \"dismissed\", \"auto_dismissed\", \"fixed\"].includes(state)\n )\n throw new Error(\n \"Dependabot alert state must be open, dismissed, auto_dismissed or fixed.\",\n );\n const updated =\n Date.parse(requiredText(alert[\"updated_at\"], \"Dependabot updated_at\")) /\n 1000;\n if (!Number.isFinite(updated) || updated < 0)\n throw new Error(\"Dependabot updated_at must be a valid timestamp.\");\n const advisoryIds = new Set([ghsa]);\n const cve = text(advisory[\"cve_id\"]);\n if (cve) advisoryIds.add(cve);\n const identifiers = advisory[\"identifiers\"];\n if (Array.isArray(identifiers)) {\n for (const item of identifiers) {\n const value = isRecord(item) && text(item[\"value\"]);\n if (!value) continue;\n if (\n (item[\"type\"] === \"GHSA\" || /^GHSA-/iu.test(value)) &&\n value.toUpperCase() !== ghsa.toUpperCase()\n )\n throw new Error(\n \"Dependabot advisory identifiers disagree on the GHSA.\",\n );\n advisoryIds.add(value);\n }\n }\n return {\n title: requiredText(advisory[\"summary\"], \"Dependabot advisory summary\"),\n description: text(advisory[\"description\"]),\n severity,\n url,\n advisory_ids: [...advisoryIds],\n packages: [\n {\n name,\n ecosystem,\n manifest_path: path,\n vulnerable_version_range: range,\n fixed_versions: patch ? [patch.identifier] : [],\n },\n ],\n locations: path ? [{ path }] : [],\n source_updated_at: Math.floor(updated),\n source_data: structuredClone(alert),\n };\n}\n\nexport function normalizeGitHubDependabotAlerts(\n input: unknown,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n const alerts = selectedAlerts(input);\n const result: ExternalFindings = {\n read: alerts.length,\n findings: [],\n excluded: [],\n };\n const ids = new Set<string>();\n let sourceRepository: string | undefined;\n for (const [index, alert] of alerts.entries()) {\n const { repositoryUrl, sourceId, url } = identity(alert);\n if (sourceRepository !== undefined && sourceRepository !== repositoryUrl)\n throw new CodexSecurityError(\n \"Select Dependabot alerts from only one GitHub host and repository.\",\n );\n sourceRepository = repositoryUrl;\n if (ids.has(sourceId))\n throw new CodexSecurityError(\n `Duplicate source finding id ${JSON.stringify(sourceId)}. Select each Dependabot alert once.`,\n );\n ids.add(sourceId);\n const inputEvidence = evidence(alert, url);\n try {\n if (target === \"cloud\" && Buffer.byteLength(sourceId) > 512)\n throw new Error(\n \"Source finding ID exceeds the Cloud limit of 512 UTF-8 bytes.\",\n );\n result.findings.push({\n source_finding_id: sourceId,\n evidence: validateExternalEvidence(inputEvidence, target),\n });\n } catch (error) {\n result.excluded.push({\n position: index + 1,\n source_finding_id: sourceId,\n reason: errorMessage(error),\n });\n }\n }\n return result;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"github-findings.d.ts","sourceRoot":"","sources":["../src/github-findings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAI1E,OAAO,KAAK,EAAmB,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAySrE,uFAAuF;AACvF,wBAAgB,iCAAiC,CAC/C,MAAM,EAAE,SAAS,+BAA+B,EAAE,EAClD,MAAM,GAAE,oBAA8B,GACrC,gBAAgB,CAElB;AAED,qFAAqF;AACrF,wBAAgB,yBAAyB,CACvC,UAAU,EAAE,SAAS,sBAAsB,EAAE,EAC7C,MAAM,GAAE,oBAA8B,GACrC,gBAAgB,CAElB;AAED,uFAAuF;AACvF,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,MAAM,EACZ,MAAM,GAAE,oBAA8B,GACrC,OAAO,CAAC,gBAAgB,CAAC,CAa3B"}
1
+ {"version":3,"file":"github-findings.d.ts","sourceRoot":"","sources":["../src/github-findings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAK1E,OAAO,KAAK,EAAmB,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AA4SrE,uFAAuF;AACvF,wBAAgB,iCAAiC,CAC/C,MAAM,EAAE,SAAS,+BAA+B,EAAE,EAClD,MAAM,GAAE,oBAA8B,GACrC,gBAAgB,CAElB;AAED,qFAAqF;AACrF,wBAAgB,yBAAyB,CACvC,UAAU,EAAE,SAAS,sBAAsB,EAAE,EAC7C,MAAM,GAAE,oBAA8B,GACrC,gBAAgB,CAElB;AAED,uFAAuF;AACvF,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,MAAM,EACZ,MAAM,GAAE,oBAA8B,GACrC,OAAO,CAAC,gBAAgB,CAAC,CAoB3B"}
@@ -1,6 +1,8 @@
1
1
  import { hash } from "node:crypto";
2
+ import { GHSA_ID, githubRepositoryParts } from "./github-identifiers.js";
2
3
  import { CodexSecurityError, errorMessage } from "./errors.js";
3
4
  import { validateExternalEvidence } from "./external-import-contract.js";
5
+ import { isGitHubDependabotAlert, normalizeGitHubDependabotAlerts, } from "./github-dependabot-findings.js";
4
6
  import { parseJsonOrJsonl, readScannerText, text } from "./scanner-import.js";
5
7
  function object(value) {
6
8
  return value !== null && typeof value === "object" && !Array.isArray(value)
@@ -9,8 +11,7 @@ function object(value) {
9
11
  }
10
12
  function repositoryName(value) {
11
13
  const repository = text(value);
12
- const parts = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(repository ?? "");
13
- if (!parts || parts.slice(1).some((part) => /^\.{1,2}$/u.test(part)))
14
+ if (!repository || !githubRepositoryParts(repository))
14
15
  throw new Error("GitHub repository must be OWNER/REPO.");
15
16
  return repository;
16
17
  }
@@ -117,7 +118,7 @@ function advisoryFinding(record, target = "cloud") {
117
118
  const selection = record["selection"];
118
119
  if (!advisory ||
119
120
  !id ||
120
- !/^GHSA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/iu.test(id) ||
121
+ !GHSA_ID.test(id) ||
121
122
  text(advisory["ghsa_id"])?.toUpperCase() !== id.toUpperCase())
122
123
  throw new Error("Expected a GitHub advisory import with matching GHSA IDs.");
123
124
  if (selection !== "repository" && selection !== "global")
@@ -249,7 +250,13 @@ export function normalizeGitHubAdvisories(advisories, target = "cloud") {
249
250
  export async function readGitHubFindings(path, target = "cloud") {
250
251
  try {
251
252
  const payload = parseJsonOrJsonl(await readScannerText(path));
252
- return normalizeRecords(Array.isArray(payload) ? payload : [payload], target);
253
+ const rows = Array.isArray(payload) ? payload : [payload];
254
+ if ((rows.length > 0 && rows.every(Array.isArray)) ||
255
+ rows.some((row) => Array.isArray(row)
256
+ ? row.some(isGitHubDependabotAlert)
257
+ : isGitHubDependabotAlert(row)))
258
+ return normalizeGitHubDependabotAlerts(payload, target);
259
+ return normalizeRecords(rows, target);
253
260
  }
254
261
  catch (cause) {
255
262
  throw new CodexSecurityError(`Could not read GitHub findings as UTF-8 JSON or JSONL: ${errorMessage(cause)}`, { cause });
@@ -1 +1 @@
1
- {"version":3,"file":"github-findings.js","sourceRoot":"","sources":["../src/github-findings.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAIzE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAE9E,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACzE,CAAC,CAAE,KAAiC;QACpC,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAED,SAAS,cAAc,CAAC,KAAc;IACpC,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/B,MAAM,KAAK,GAAG,oCAAoC,CAAC,IAAI,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC;IAC1E,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,C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AC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,kBAAkB;gBAAE,MAAM,KAAK,CAAC;YACrD,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACnB,QAAQ,EAAE,KAAK,GAAG,CAAC;gBACnB,iBAAiB,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;gBACxC,MAAM,EAAE,YAAY,CAAC,KAAK,CAAC;aAC5B,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,iCAAiC,CAC/C,MAAkD,EAClD,MAAM,GAAyB,OAAO;IAEtC,OAAO,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC1C,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,yBAAyB,CACvC,UAA6C,EAC7C,MAAM,GAAyB,OAAO;IAEtC,OAAO,gBAAgB,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;AAC9C,CAAC;AAED,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,IAAY,EACZ,MAAM,GAAyB,OAAO;IAEtC,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,gBAAgB,CAAC,MAAM,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC;QAC9D,OAAO,gBAAgB,CACrB,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAC5C,MAAM,CACP,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,kBAAkB,CAC1B,0DAA0D,YAAY,CAAC,KAAK,CAAC,EAAE,EAC/E,EAAE,KAAK,EAAE,CACV,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { ExternalImportTarget } from \"./external-import-contract.js\";\nimport { hash } from \"node:crypto\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\nimport { validateExternalEvidence } from \"./external-import-contract.js\";\nimport type { ExternalFinding, ExternalFindings } from \"./external-findings.js\";\nimport type { ImportedGitHubCodeScanningAlert } from \"./github.js\";\nimport type { ImportedGitHubAdvisory } from \"./github-advisories.js\";\nimport { parseJsonOrJsonl, readScannerText, text } from \"./scanner-import.js\";\n\nfunction object(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction repositoryName(value: unknown): string {\n const repository = text(value);\n const parts = /^([a-z0-9_.-]+)\\/([a-z0-9_.-]+)$/iu.exec(repository ?? \"\");\n if (!parts || parts.slice(1).some((part) => /^\\.{1,2}$/u.test(part)))\n throw new Error(\"GitHub repository must be OWNER/REPO.\");\n return repository!;\n}\n\nfunction sourceUrl(value: string): {\n parsed: URL;\n host: string;\n origin: string;\n} {\n const parsed = new URL(value);\n const origin = /^(https?:\\/\\/([^/?#]+))/iu.exec(value);\n if (!origin) throw new Error(\"GitHub evidence URL must be an HTTP(S) link.\");\n // URL.origin/host remove explicit default ports; Cloud keeps those distinct.\n return { parsed, host: origin[2]!.toLowerCase(), origin: origin[1]! };\n}\n\nfunction sourceTimestamp(value: unknown): number | null {\n if (value === undefined || value === null) return null;\n const seconds = typeof value === \"string\" ? Date.parse(value) / 1000 : NaN;\n if (!Number.isFinite(seconds) || seconds < 0)\n throw new Error(\"GitHub updated_at is not a valid timestamp.\");\n return Math.floor(seconds);\n}\n\nfunction severity(value: unknown): string {\n // SARIF error/warning/note are not vulnerability severity ratings.\n return typeof value === \"string\" &&\n [\"critical\", \"high\", \"medium\", \"low\", \"informational\"].includes(value)\n ? value\n : \"unknown\";\n}\n\nfunction codeScanningFinding(\n record: Record<string, unknown>,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFinding {\n const repository = repositoryName(record[\"repository\"]);\n const alert = object(record[\"alert\"]);\n const number = record[\"number\"];\n if (\n !alert ||\n typeof number !== \"number\" ||\n !Number.isSafeInteger(number) ||\n number < 1 ||\n alert[\"number\"] !== number\n )\n throw new Error(\n \"Expected a GitHub code-scanning import with matching alert numbers.\",\n );\n const url = text(record[\"url\"]);\n if (!url || url !== alert[\"html_url\"])\n throw new Error(\"GitHub alert URL must match the original alert.\");\n const { parsed: parsedUrl, host, origin } = sourceUrl(url);\n if (\n ![\"security/code-scanning\", \"code-scanning\"].some(\n (route) =>\n parsedUrl.pathname.toLowerCase() ===\n `/${repository}/${route}/${number}`.toLowerCase(),\n )\n )\n throw new Error(\n \"GitHub alert URL does not match the selected repository and alert.\",\n );\n const rule = object(alert[\"rule\"]);\n const instance = object(alert[\"most_recent_instance\"]);\n const ref = text(instance?.[\"ref\"]);\n if (!ref)\n throw new Error(\n \"GitHub code-scanning evidence requires the selected instance ref.\",\n );\n const location = object(instance?.[\"location\"]);\n const tool = object(alert[\"tool\"]);\n const message = text(object(instance?.[\"message\"])?.[\"text\"]);\n const description =\n text(rule?.[\"full_description\"]) ?? text(rule?.[\"description\"]);\n const tags = Array.isArray(rule?.[\"tags\"]) ? rule[\"tags\"] : [];\n const weaknessIds = [\n ...new Set(\n tags.flatMap((tag: unknown) => {\n const match =\n typeof tag === \"string\"\n ? /^external\\/cwe\\/cwe-(\\d+)$/iu.exec(tag)\n : null;\n return match ? [`CWE-${Number(match[1])}`] : [];\n }),\n ),\n ];\n const path = text(location?.[\"path\"]);\n const sourceId = `${host}/${repository.toLowerCase()}/code-scanning/${number}/${hash(\"sha256\", ref)}`;\n return {\n source_finding_id: sourceId,\n evidence: validateExternalEvidence(\n {\n title:\n text(rule?.[\"name\"]) ??\n text(rule?.[\"description\"]) ??\n `GitHub code-scanning alert #${number}`,\n severity: severity(rule?.[\"security_severity_level\"]),\n description:\n [...new Set([message, description].filter(Boolean))].join(\"\\n\\n\") ||\n null,\n url,\n locations: path\n ? [{ path, line: location?.[\"start_line\"] ?? null }]\n : [],\n branch: ref,\n code_revision: text(instance?.[\"commit_sha\"]),\n source_updated_at: sourceTimestamp(alert[\"updated_at\"]),\n source_data: record,\n details: {\n kind: \"sast\",\n repository: {\n url: `${origin}/${repository}`,\n name: repository,\n },\n // Dismissal covers every branch; detection state belongs to the selected ref.\n source_status:\n alert[\"state\"] === \"dismissed\"\n ? \"dismissed\"\n : (text(instance?.[\"state\"]) ?? text(alert[\"state\"])),\n scanner_origin: text(tool?.[\"name\"]),\n rule: { id: text(rule?.[\"id\"]), name: text(rule?.[\"name\"]) },\n weakness_ids: weaknessIds,\n remediation_instructions: text(rule?.[\"help\"]),\n code: path ? { end_line: location?.[\"end_line\"] ?? null } : null,\n },\n },\n target,\n ),\n };\n}\n\nfunction advisoryFinding(\n record: Record<string, unknown>,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFinding {\n const repository = repositoryName(record[\"repository\"]);\n const advisory = object(record[\"advisory\"]);\n const id = text(record[\"ghsaId\"]);\n const selection = record[\"selection\"];\n if (\n !advisory ||\n !id ||\n !/^GHSA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/iu.test(id) ||\n text(advisory[\"ghsa_id\"])?.toUpperCase() !== id.toUpperCase()\n )\n throw new Error(\n \"Expected a GitHub advisory import with matching GHSA IDs.\",\n );\n if (selection !== \"repository\" && selection !== \"global\")\n throw new Error(\"GitHub advisory selection must be repository or global.\");\n const url = text(record[\"url\"]);\n if (!url || url !== advisory[\"html_url\"])\n throw new Error(\"GitHub advisory URL must match the original advisory.\");\n const { parsed: parsedUrl, host: linkHost, origin } = sourceUrl(url);\n const host = text(record[\"githubHost\"])?.toLowerCase();\n // Enterprise APIs may return the public advisory database's canonical link.\n const canonicalGlobalLink =\n selection === \"global\" && parsedUrl.host === \"github.com\";\n const expectedPath =\n selection === \"repository\"\n ? `/${repository}/security/advisories/${id}`\n : `/advisories/${id}`;\n if (\n !host ||\n (linkHost !== host && !canonicalGlobalLink) ||\n parsedUrl.pathname.toLowerCase() !== expectedPath.toLowerCase()\n )\n throw new Error(\n \"GitHub advisory URL does not match the selected source and GHSA ID.\",\n );\n const vulnerabilities =\n advisory[\"vulnerabilities\"] === null ? [] : advisory[\"vulnerabilities\"];\n if (!Array.isArray(vulnerabilities))\n throw new Error(\"GitHub advisory vulnerabilities must be an array.\");\n const identifiers = Array.isArray(advisory[\"identifiers\"])\n ? advisory[\"identifiers\"]\n : [];\n const advisoryIds = [\n id,\n text(advisory[\"cve_id\"]),\n ...identifiers.map((identifier) => text(object(identifier)?.[\"value\"])),\n ].filter((value): value is string => value !== null);\n const packages = vulnerabilities.flatMap((value) => {\n const vulnerability = object(value);\n const pkg = object(vulnerability?.[\"package\"]);\n const name = text(pkg?.[\"name\"]);\n // GitHub permits incomplete package metadata in advisory disclosures.\n // Preserve it in source_data without inventing a typed package identity.\n if (!name) return [];\n const fixedVersion =\n text(vulnerability?.[\"first_patched_version\"]) ??\n text(vulnerability?.[\"patched_versions\"]);\n return [\n {\n name,\n ecosystem: text(pkg?.[\"ecosystem\"]),\n vulnerable_version_range: text(\n vulnerability?.[\"vulnerable_version_range\"],\n ),\n fixed_versions: fixedVersion ? [fixedVersion] : [],\n },\n ];\n });\n const cwes = Array.isArray(advisory[\"cwes\"]) ? advisory[\"cwes\"] : [];\n return {\n source_finding_id: `${host}/${selection === \"repository\" ? repository.toLowerCase() : \"global\"}/security-advisory/${id.toUpperCase()}`,\n evidence: validateExternalEvidence(\n {\n title: text(advisory[\"summary\"]) ?? id,\n severity: severity(advisory[\"severity\"]),\n description: text(advisory[\"description\"]),\n url,\n advisory_ids: [...new Set(advisoryIds)],\n packages,\n source_updated_at: sourceTimestamp(advisory[\"updated_at\"]),\n source_data: record,\n details: {\n kind: \"advisory\",\n advisory: { source: selection },\n ...(selection === \"repository\"\n ? {\n repository: {\n url: `${origin}/${repository}`,\n name: repository,\n },\n }\n : {}),\n source_status: text(advisory[\"withdrawn_at\"])\n ? \"withdrawn\"\n : (text(advisory[\"state\"]) ??\n (selection === \"global\" ? \"published\" : null)),\n scanner_origin: \"GitHub Security Advisories\",\n weakness_ids: cwes\n .map((value) => text(object(value)?.[\"cwe_id\"]))\n .filter((value): value is string => value !== null),\n },\n },\n target,\n ),\n };\n}\n\nfunction normalizeRecords(\n records: readonly unknown[],\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n const result: ExternalFindings = {\n read: records.length,\n findings: [],\n excluded: [],\n };\n const identities = new Set<string>();\n for (const [index, value] of records.entries()) {\n const record = object(value);\n try {\n if (!record) throw new Error(\"GitHub finding must be an object.\");\n let finding: ExternalFinding;\n if (record[\"source\"] === \"github-code-scanning\")\n finding = codeScanningFinding(record, target);\n else if (record[\"source\"] === \"github-security-advisory\")\n finding = advisoryFinding(record, target);\n else\n throw new Error(\n \"Expected saved output from import github or import github-advisories; raw or incomplete API responses need an explicit mapping.\",\n );\n if (identities.has(finding.source_finding_id))\n throw new CodexSecurityError(\n `Duplicate source finding id ${JSON.stringify(finding.source_finding_id)}. Select each GitHub occurrence once.`,\n );\n identities.add(finding.source_finding_id);\n result.findings.push(finding);\n } catch (error) {\n if (error instanceof CodexSecurityError) throw error;\n result.excluded.push({\n position: index + 1,\n source_finding_id: text(record?.[\"url\"]),\n reason: errorMessage(error),\n });\n }\n }\n return result;\n}\n\n/** Map selected code-scanning instances while retaining complete upstream evidence. */\nexport function normalizeGitHubCodeScanningAlerts(\n alerts: readonly ImportedGitHubCodeScanningAlert[],\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n return normalizeRecords(alerts, target);\n}\n\n/** Map advisory disclosures without asserting an installed vulnerable dependency. */\nexport function normalizeGitHubAdvisories(\n advisories: readonly ImportedGitHubAdvisory[],\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n return normalizeRecords(advisories, target);\n}\n\n/** Read unfiltered JSON/JSONL output saved by the read-only GitHub import commands. */\nexport async function readGitHubFindings(\n path: string,\n target: ExternalImportTarget = \"cloud\",\n): Promise<ExternalFindings> {\n try {\n const payload = parseJsonOrJsonl(await readScannerText(path));\n return normalizeRecords(\n Array.isArray(payload) ? payload : [payload],\n target,\n );\n } catch (cause) {\n throw new CodexSecurityError(\n `Could not read GitHub findings as UTF-8 JSON or JSONL: ${errorMessage(cause)}`,\n { cause },\n );\n }\n}\n"]}
1
+ {"version":3,"file":"github-findings.js","sourceRoot":"","sources":["../src/github-findings.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAIzE,OAAO,EACL,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAE9E,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACzE,CAAC,CAAE,KAAiC;QACpC,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAED,SAAS,cAAc,CAAC,KAAc;IACpC,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/B,IAAI,CAAC,UAAU,IAAI,CAAC,qBAAqB,CAAC,UAAU,CAAC;QACnD,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC3D,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAK9B,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IAC9B,MAAM,MAAM,GAAG,2BAA2B,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACvD,IAAI,CAA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AC,EAAE,EAC/E,EAAE,KAAK,EAAE,CACV,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { ExternalImportTarget } from \"./external-import-contract.js\";\nimport { hash } from \"node:crypto\";\nimport { GHSA_ID, githubRepositoryParts } from \"./github-identifiers.js\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\nimport { validateExternalEvidence } from \"./external-import-contract.js\";\nimport type { ExternalFinding, ExternalFindings } from \"./external-findings.js\";\nimport type { ImportedGitHubCodeScanningAlert } from \"./github.js\";\nimport type { ImportedGitHubAdvisory } from \"./github-advisories.js\";\nimport {\n isGitHubDependabotAlert,\n normalizeGitHubDependabotAlerts,\n} from \"./github-dependabot-findings.js\";\nimport { parseJsonOrJsonl, readScannerText, text } from \"./scanner-import.js\";\n\nfunction object(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction repositoryName(value: unknown): string {\n const repository = text(value);\n if (!repository || !githubRepositoryParts(repository))\n throw new Error(\"GitHub repository must be OWNER/REPO.\");\n return repository;\n}\n\nfunction sourceUrl(value: string): {\n parsed: URL;\n host: string;\n origin: string;\n} {\n const parsed = new URL(value);\n const origin = /^(https?:\\/\\/([^/?#]+))/iu.exec(value);\n if (!origin) throw new Error(\"GitHub evidence URL must be an HTTP(S) link.\");\n // URL.origin/host remove explicit default ports; Cloud keeps those distinct.\n return { parsed, host: origin[2]!.toLowerCase(), origin: origin[1]! };\n}\n\nfunction sourceTimestamp(value: unknown): number | null {\n if (value === undefined || value === null) return null;\n const seconds = typeof value === \"string\" ? Date.parse(value) / 1000 : NaN;\n if (!Number.isFinite(seconds) || seconds < 0)\n throw new Error(\"GitHub updated_at is not a valid timestamp.\");\n return Math.floor(seconds);\n}\n\nfunction severity(value: unknown): string {\n // SARIF error/warning/note are not vulnerability severity ratings.\n return typeof value === \"string\" &&\n [\"critical\", \"high\", \"medium\", \"low\", \"informational\"].includes(value)\n ? value\n : \"unknown\";\n}\n\nfunction codeScanningFinding(\n record: Record<string, unknown>,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFinding {\n const repository = repositoryName(record[\"repository\"]);\n const alert = object(record[\"alert\"]);\n const number = record[\"number\"];\n if (\n !alert ||\n typeof number !== \"number\" ||\n !Number.isSafeInteger(number) ||\n number < 1 ||\n alert[\"number\"] !== number\n )\n throw new Error(\n \"Expected a GitHub code-scanning import with matching alert numbers.\",\n );\n const url = text(record[\"url\"]);\n if (!url || url !== alert[\"html_url\"])\n throw new Error(\"GitHub alert URL must match the original alert.\");\n const { parsed: parsedUrl, host, origin } = sourceUrl(url);\n if (\n ![\"security/code-scanning\", \"code-scanning\"].some(\n (route) =>\n parsedUrl.pathname.toLowerCase() ===\n `/${repository}/${route}/${number}`.toLowerCase(),\n )\n )\n throw new Error(\n \"GitHub alert URL does not match the selected repository and alert.\",\n );\n const rule = object(alert[\"rule\"]);\n const instance = object(alert[\"most_recent_instance\"]);\n const ref = text(instance?.[\"ref\"]);\n if (!ref)\n throw new Error(\n \"GitHub code-scanning evidence requires the selected instance ref.\",\n );\n const location = object(instance?.[\"location\"]);\n const tool = object(alert[\"tool\"]);\n const message = text(object(instance?.[\"message\"])?.[\"text\"]);\n const description =\n text(rule?.[\"full_description\"]) ?? text(rule?.[\"description\"]);\n const tags = Array.isArray(rule?.[\"tags\"]) ? rule[\"tags\"] : [];\n const weaknessIds = [\n ...new Set(\n tags.flatMap((tag: unknown) => {\n const match =\n typeof tag === \"string\"\n ? /^external\\/cwe\\/cwe-(\\d+)$/iu.exec(tag)\n : null;\n return match ? [`CWE-${Number(match[1])}`] : [];\n }),\n ),\n ];\n const path = text(location?.[\"path\"]);\n const sourceId = `${host}/${repository.toLowerCase()}/code-scanning/${number}/${hash(\"sha256\", ref)}`;\n return {\n source_finding_id: sourceId,\n evidence: validateExternalEvidence(\n {\n title:\n text(rule?.[\"name\"]) ??\n text(rule?.[\"description\"]) ??\n `GitHub code-scanning alert #${number}`,\n severity: severity(rule?.[\"security_severity_level\"]),\n description:\n [...new Set([message, description].filter(Boolean))].join(\"\\n\\n\") ||\n null,\n url,\n locations: path\n ? [{ path, line: location?.[\"start_line\"] ?? null }]\n : [],\n branch: ref,\n code_revision: text(instance?.[\"commit_sha\"]),\n source_updated_at: sourceTimestamp(alert[\"updated_at\"]),\n source_data: record,\n details: {\n kind: \"sast\",\n repository: {\n url: `${origin}/${repository}`,\n name: repository,\n },\n // Dismissal covers every branch; detection state belongs to the selected ref.\n source_status:\n alert[\"state\"] === \"dismissed\"\n ? \"dismissed\"\n : (text(instance?.[\"state\"]) ?? text(alert[\"state\"])),\n scanner_origin: text(tool?.[\"name\"]),\n rule: { id: text(rule?.[\"id\"]), name: text(rule?.[\"name\"]) },\n weakness_ids: weaknessIds,\n remediation_instructions: text(rule?.[\"help\"]),\n code: path ? { end_line: location?.[\"end_line\"] ?? null } : null,\n },\n },\n target,\n ),\n };\n}\n\nfunction advisoryFinding(\n record: Record<string, unknown>,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFinding {\n const repository = repositoryName(record[\"repository\"]);\n const advisory = object(record[\"advisory\"]);\n const id = text(record[\"ghsaId\"]);\n const selection = record[\"selection\"];\n if (\n !advisory ||\n !id ||\n !GHSA_ID.test(id) ||\n text(advisory[\"ghsa_id\"])?.toUpperCase() !== id.toUpperCase()\n )\n throw new Error(\n \"Expected a GitHub advisory import with matching GHSA IDs.\",\n );\n if (selection !== \"repository\" && selection !== \"global\")\n throw new Error(\"GitHub advisory selection must be repository or global.\");\n const url = text(record[\"url\"]);\n if (!url || url !== advisory[\"html_url\"])\n throw new Error(\"GitHub advisory URL must match the original advisory.\");\n const { parsed: parsedUrl, host: linkHost, origin } = sourceUrl(url);\n const host = text(record[\"githubHost\"])?.toLowerCase();\n // Enterprise APIs may return the public advisory database's canonical link.\n const canonicalGlobalLink =\n selection === \"global\" && parsedUrl.host === \"github.com\";\n const expectedPath =\n selection === \"repository\"\n ? `/${repository}/security/advisories/${id}`\n : `/advisories/${id}`;\n if (\n !host ||\n (linkHost !== host && !canonicalGlobalLink) ||\n parsedUrl.pathname.toLowerCase() !== expectedPath.toLowerCase()\n )\n throw new Error(\n \"GitHub advisory URL does not match the selected source and GHSA ID.\",\n );\n const vulnerabilities =\n advisory[\"vulnerabilities\"] === null ? [] : advisory[\"vulnerabilities\"];\n if (!Array.isArray(vulnerabilities))\n throw new Error(\"GitHub advisory vulnerabilities must be an array.\");\n const identifiers = Array.isArray(advisory[\"identifiers\"])\n ? advisory[\"identifiers\"]\n : [];\n const advisoryIds = [\n id,\n text(advisory[\"cve_id\"]),\n ...identifiers.map((identifier) => text(object(identifier)?.[\"value\"])),\n ].filter((value): value is string => value !== null);\n const packages = vulnerabilities.flatMap((value) => {\n const vulnerability = object(value);\n const pkg = object(vulnerability?.[\"package\"]);\n const name = text(pkg?.[\"name\"]);\n // GitHub permits incomplete package metadata in advisory disclosures.\n // Preserve it in source_data without inventing a typed package identity.\n if (!name) return [];\n const fixedVersion =\n text(vulnerability?.[\"first_patched_version\"]) ??\n text(vulnerability?.[\"patched_versions\"]);\n return [\n {\n name,\n ecosystem: text(pkg?.[\"ecosystem\"]),\n vulnerable_version_range: text(\n vulnerability?.[\"vulnerable_version_range\"],\n ),\n fixed_versions: fixedVersion ? [fixedVersion] : [],\n },\n ];\n });\n const cwes = Array.isArray(advisory[\"cwes\"]) ? advisory[\"cwes\"] : [];\n return {\n source_finding_id: `${host}/${selection === \"repository\" ? repository.toLowerCase() : \"global\"}/security-advisory/${id.toUpperCase()}`,\n evidence: validateExternalEvidence(\n {\n title: text(advisory[\"summary\"]) ?? id,\n severity: severity(advisory[\"severity\"]),\n description: text(advisory[\"description\"]),\n url,\n advisory_ids: [...new Set(advisoryIds)],\n packages,\n source_updated_at: sourceTimestamp(advisory[\"updated_at\"]),\n source_data: record,\n details: {\n kind: \"advisory\",\n advisory: { source: selection },\n ...(selection === \"repository\"\n ? {\n repository: {\n url: `${origin}/${repository}`,\n name: repository,\n },\n }\n : {}),\n source_status: text(advisory[\"withdrawn_at\"])\n ? \"withdrawn\"\n : (text(advisory[\"state\"]) ??\n (selection === \"global\" ? \"published\" : null)),\n scanner_origin: \"GitHub Security Advisories\",\n weakness_ids: cwes\n .map((value) => text(object(value)?.[\"cwe_id\"]))\n .filter((value): value is string => value !== null),\n },\n },\n target,\n ),\n };\n}\n\nfunction normalizeRecords(\n records: readonly unknown[],\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n const result: ExternalFindings = {\n read: records.length,\n findings: [],\n excluded: [],\n };\n const identities = new Set<string>();\n for (const [index, value] of records.entries()) {\n const record = object(value);\n try {\n if (!record) throw new Error(\"GitHub finding must be an object.\");\n let finding: ExternalFinding;\n if (record[\"source\"] === \"github-code-scanning\")\n finding = codeScanningFinding(record, target);\n else if (record[\"source\"] === \"github-security-advisory\")\n finding = advisoryFinding(record, target);\n else\n throw new Error(\n \"Expected saved output from import github or import github-advisories; raw or incomplete API responses need an explicit mapping.\",\n );\n if (identities.has(finding.source_finding_id))\n throw new CodexSecurityError(\n `Duplicate source finding id ${JSON.stringify(finding.source_finding_id)}. Select each GitHub occurrence once.`,\n );\n identities.add(finding.source_finding_id);\n result.findings.push(finding);\n } catch (error) {\n if (error instanceof CodexSecurityError) throw error;\n result.excluded.push({\n position: index + 1,\n source_finding_id: text(record?.[\"url\"]),\n reason: errorMessage(error),\n });\n }\n }\n return result;\n}\n\n/** Map selected code-scanning instances while retaining complete upstream evidence. */\nexport function normalizeGitHubCodeScanningAlerts(\n alerts: readonly ImportedGitHubCodeScanningAlert[],\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n return normalizeRecords(alerts, target);\n}\n\n/** Map advisory disclosures without asserting an installed vulnerable dependency. */\nexport function normalizeGitHubAdvisories(\n advisories: readonly ImportedGitHubAdvisory[],\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n return normalizeRecords(advisories, target);\n}\n\n/** Read unfiltered JSON/JSONL output saved by the read-only GitHub import commands. */\nexport async function readGitHubFindings(\n path: string,\n target: ExternalImportTarget = \"cloud\",\n): Promise<ExternalFindings> {\n try {\n const payload = parseJsonOrJsonl(await readScannerText(path));\n const rows = Array.isArray(payload) ? payload : [payload];\n if (\n (rows.length > 0 && rows.every(Array.isArray)) ||\n rows.some((row) =>\n Array.isArray(row)\n ? row.some(isGitHubDependabotAlert)\n : isGitHubDependabotAlert(row),\n )\n )\n return normalizeGitHubDependabotAlerts(payload, target);\n return normalizeRecords(rows, target);\n } catch (cause) {\n throw new CodexSecurityError(\n `Could not read GitHub findings as UTF-8 JSON or JSONL: ${errorMessage(cause)}`,\n { cause },\n );\n }\n}\n"]}
@@ -0,0 +1,4 @@
1
+ export declare const CANONICAL_GHSA_ID: RegExp;
2
+ export declare const GHSA_ID: RegExp;
3
+ export declare function githubRepositoryParts(value: string): [string, string] | undefined;
4
+ //# sourceMappingURL=github-identifiers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-identifiers.d.ts","sourceRoot":"","sources":["../src/github-identifiers.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB,QAAgD,CAAC;AAE/E,eAAO,MAAM,OAAO,QAAsC,CAAC;AAE3D,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,MAAM,GACZ,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAI9B"}
@@ -0,0 +1,9 @@
1
+ export const CANONICAL_GHSA_ID = /^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/u;
2
+ // File imports and CLI arguments also accept the original mixed-case spelling.
3
+ export const GHSA_ID = new RegExp(CANONICAL_GHSA_ID, "iu");
4
+ export function githubRepositoryParts(value) {
5
+ const match = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(value);
6
+ if (match && !match.slice(1).some((part) => /^\.{1,2}$/u.test(part)))
7
+ return [match[1], match[2]];
8
+ }
9
+ //# sourceMappingURL=github-identifiers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-identifiers.js","sourceRoot":"","sources":["../src/github-identifiers.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,iBAAiB,GAAG,6CAA6C,CAAC;AAC/E,+EAA+E;AAC/E,MAAM,CAAC,MAAM,OAAO,GAAG,IAAI,MAAM,CAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC;AAE3D,MAAM,UAAU,qBAAqB,CACnC,KAAa;IAEb,MAAM,KAAK,GAAG,oCAAoC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAClE,OAAO,CAAC,KAAK,CAAC,CAAC,CAAE,EAAE,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC;AAClC,CAAC","sourcesContent":["export const CANONICAL_GHSA_ID = /^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/u;\n// File imports and CLI arguments also accept the original mixed-case spelling.\nexport const GHSA_ID = new RegExp(CANONICAL_GHSA_ID, \"iu\");\n\nexport function githubRepositoryParts(\n value: string,\n): [string, string] | undefined {\n const match = /^([a-z0-9_.-]+)\\/([a-z0-9_.-]+)$/iu.exec(value);\n if (match && !match.slice(1).some((part) => /^\\.{1,2}$/u.test(part)))\n return [match[1]!, match[2]!];\n}\n"]}