@openai/codex-security 0.7.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.
- package/README.md +18 -12
- package/_bundled_plugin/.codex-plugin/plugin.json +1 -0
- package/_bundled_plugin/examples/completed-scan/findings.json +34 -34
- package/_bundled_plugin/examples/completed-scan/report.md +22 -31
- package/_bundled_plugin/examples/completed-scan/scan-manifest.json +27 -29
- package/_bundled_plugin/examples/{completed-scan → legacy-completed-scan}/coverage.json +1 -0
- package/_bundled_plugin/examples/legacy-completed-scan/findings.json +57 -0
- package/_bundled_plugin/examples/legacy-completed-scan/report.md +98 -0
- package/_bundled_plugin/examples/legacy-completed-scan/scan-manifest.json +43 -0
- package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
- package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
- package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
- package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
- package/_bundled_plugin/references/core-scan.md +2 -2
- package/_bundled_plugin/references/final-report.md +16 -6
- package/_bundled_plugin/references/scan-artifacts.md +6 -6
- package/_bundled_plugin/references/scan-contract.md +10 -12
- package/_bundled_plugin/references/threat-model.md +1 -1
- package/_bundled_plugin/schemas/scan-manifest.schema.json +36 -11
- package/_bundled_plugin/schemas/tools/scan-draft.schema.json +5 -5
- package/_bundled_plugin/scripts/deep_scan_workbench.py +1 -1
- package/_bundled_plugin/scripts/finalize_scan_contract.py +97 -20
- package/_bundled_plugin/scripts/report_projection.py +5 -2
- package/_bundled_plugin/scripts/review_state.py +68 -0
- package/_bundled_plugin/scripts/servicenow_avit.py +107 -0
- package/_bundled_plugin/scripts/validate_scan_contract.py +1 -2
- package/_bundled_plugin/scripts/workbench/retained_coverage.py +49 -37
- package/_bundled_plugin/scripts/workbench/retained_records.py +7 -7
- package/_bundled_plugin/scripts/workbench/saved_coverage.py +15 -15
- package/_bundled_plugin/scripts/workbench/saved_sources.py +24 -6
- package/_bundled_plugin/scripts/workbench_constants.py +0 -1
- package/_bundled_plugin/scripts/workbench_coverage_receipts.py +4 -4
- package/_bundled_plugin/scripts/workbench_db.py +5 -150
- package/_bundled_plugin/scripts/workbench_saved_results.py +169 -4
- package/_bundled_plugin/scripts/workbench_scan_history.py +12 -7
- package/_bundled_plugin/scripts/workbench_scan_start.py +4 -1
- package/_bundled_plugin/skills/publish-findings/SKILL.md +9 -3
- package/_bundled_plugin/skills/security-diff-scan/SKILL.md +1 -1
- package/_bundled_plugin/skills/security-scan/SKILL.md +7 -7
- package/_bundled_plugin/skills/track-findings/SKILL.md +1 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +50 -27
- package/dist/api.js.map +1 -1
- package/dist/artifact-export.d.ts +12 -3
- package/dist/artifact-export.d.ts.map +1 -1
- package/dist/artifact-export.js +30 -10
- package/dist/artifact-export.js.map +1 -1
- package/dist/cli-help.d.ts.map +1 -1
- package/dist/cli-help.js +1 -0
- package/dist/cli-help.js.map +1 -1
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +69 -55
- package/dist/cli.js.map +1 -1
- package/dist/cloud-publish.d.ts.map +1 -1
- package/dist/cloud-publish.js +2 -23
- package/dist/cloud-publish.js.map +1 -1
- package/dist/contract.d.ts +4 -2
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js +39 -21
- package/dist/contract.js.map +1 -1
- package/dist/custom-publish.js +2 -2
- package/dist/custom-publish.js.map +1 -1
- package/dist/custom-validation-prompt.d.ts.map +1 -1
- package/dist/custom-validation-prompt.js +14 -6
- package/dist/custom-validation-prompt.js.map +1 -1
- package/dist/custom-validation.d.ts.map +1 -1
- package/dist/custom-validation.js +17 -15
- package/dist/custom-validation.js.map +1 -1
- package/dist/deduplication/codex-review.d.ts.map +1 -1
- package/dist/deduplication/codex-review.js +2 -2
- package/dist/deduplication/codex-review.js.map +1 -1
- package/dist/deduplication/deduplication-prompts.d.ts +1 -0
- package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
- package/dist/deduplication/deduplication-prompts.js +3 -0
- package/dist/deduplication/deduplication-prompts.js.map +1 -1
- package/dist/deduplication/records-protocol.d.ts.map +1 -1
- package/dist/deduplication/records-protocol.js +21 -1
- package/dist/deduplication/records-protocol.js.map +1 -1
- package/dist/deduplication/scan.d.ts.map +1 -1
- package/dist/deduplication/scan.js +2 -2
- package/dist/deduplication/scan.js.map +1 -1
- package/dist/external-findings-local.d.ts +1 -0
- package/dist/external-findings-local.d.ts.map +1 -1
- package/dist/external-findings-local.js +25 -2
- package/dist/external-findings-local.js.map +1 -1
- package/dist/external-findings-publish.d.ts +1 -0
- package/dist/external-findings-publish.d.ts.map +1 -1
- package/dist/external-findings-publish.js +55 -26
- package/dist/external-findings-publish.js.map +1 -1
- package/dist/external-findings-read.d.ts +1 -0
- package/dist/external-findings-read.d.ts.map +1 -1
- package/dist/external-findings-read.js +10 -0
- package/dist/external-findings-read.js.map +1 -1
- package/dist/external-findings.d.ts +2 -0
- package/dist/external-findings.d.ts.map +1 -1
- package/dist/external-findings.js.map +1 -1
- package/dist/external-import-contract.d.ts +4 -0
- package/dist/external-import-contract.d.ts.map +1 -1
- package/dist/external-import-contract.js +34 -10
- package/dist/external-import-contract.js.map +1 -1
- package/dist/finding-workflow.d.ts +2 -0
- package/dist/finding-workflow.d.ts.map +1 -1
- package/dist/finding-workflow.js +3 -0
- package/dist/finding-workflow.js.map +1 -1
- package/dist/github-advisories.d.ts.map +1 -1
- package/dist/github-advisories.js +5 -5
- package/dist/github-advisories.js.map +1 -1
- package/dist/github-dependabot-findings.d.ts +6 -0
- package/dist/github-dependabot-findings.d.ts.map +1 -0
- package/dist/github-dependabot-findings.js +247 -0
- package/dist/github-dependabot-findings.js.map +1 -0
- package/dist/github-findings.d.ts.map +1 -1
- package/dist/github-findings.js +11 -4
- package/dist/github-findings.js.map +1 -1
- package/dist/github-identifiers.d.ts +4 -0
- package/dist/github-identifiers.d.ts.map +1 -0
- package/dist/github-identifiers.js +9 -0
- package/dist/github-identifiers.js.map +1 -0
- package/dist/github.d.ts.map +1 -1
- package/dist/github.js +4 -6
- package/dist/github.js.map +1 -1
- package/dist/host-protocol.d.ts +1 -1
- package/dist/host-protocol.d.ts.map +1 -1
- package/dist/host-protocol.js +2 -2
- package/dist/host-protocol.js.map +1 -1
- package/dist/hosted-scan.d.ts.map +1 -1
- package/dist/hosted-scan.js +13 -6
- package/dist/hosted-scan.js.map +1 -1
- package/dist/import-scan.js +16 -16
- package/dist/import-scan.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/knowledge-base.js +3 -0
- package/dist/knowledge-base.js.map +1 -1
- package/dist/mock-scan.d.ts +1 -2
- package/dist/mock-scan.d.ts.map +1 -1
- package/dist/mock-scan.js +12 -17
- package/dist/mock-scan.js.map +1 -1
- package/dist/models.d.ts +9 -1
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js.map +1 -1
- package/dist/multiscan.d.ts.map +1 -1
- package/dist/multiscan.js +1 -6
- package/dist/multiscan.js.map +1 -1
- package/dist/native-json-findings.d.ts +30 -0
- package/dist/native-json-findings.d.ts.map +1 -0
- package/dist/native-json-findings.js +114 -0
- package/dist/native-json-findings.js.map +1 -0
- package/dist/opengrep-findings.d.ts +10 -0
- package/dist/opengrep-findings.d.ts.map +1 -0
- package/dist/opengrep-findings.js +198 -0
- package/dist/opengrep-findings.js.map +1 -0
- package/dist/patch-tui.d.ts.map +1 -1
- package/dist/patch-tui.js +2 -0
- package/dist/patch-tui.js.map +1 -1
- package/dist/publication.js +1 -2
- package/dist/publication.js.map +1 -1
- package/dist/record.d.ts +1 -0
- package/dist/record.d.ts.map +1 -1
- package/dist/record.js +10 -0
- package/dist/record.js.map +1 -1
- package/dist/result.d.ts +5 -3
- package/dist/result.d.ts.map +1 -1
- package/dist/result.js +9 -6
- package/dist/result.js.map +1 -1
- package/dist/scan-history-renderer.js +1 -1
- package/dist/scan-history-renderer.js.map +1 -1
- package/dist/scanner-import.d.ts +0 -1
- package/dist/scanner-import.d.ts.map +1 -1
- package/dist/scanner-import.js +9 -9
- package/dist/scanner-import.js.map +1 -1
- package/dist/security-policy.d.ts.map +1 -1
- package/dist/security-policy.js +16 -2
- package/dist/security-policy.js.map +1 -1
- package/dist/semgrep-findings.d.ts.map +1 -1
- package/dist/semgrep-findings.js +15 -82
- package/dist/semgrep-findings.js.map +1 -1
- package/docs/cli.md +55 -10
- package/docs/dedupe-records.md +15 -1
- package/docs/hosted-scans.md +14 -0
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-import-contract.js","sourceRoot":"","sources":["../src/external-import-contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAChC,OAAO,OAAO,MAAM,kBAAkB,CAAC;AACvC,OAAO,MAAM,MAAM,0CAA0C,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAUpF,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC;IACtB,MAAM,EAAE,KAAK;IACb,eAAe,EAAE,KAAK;IACtB,WAAW,EAAE,IAAI;CAClB,CAAC,CAAC;AAKH,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAC5B,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,KAAc,EAAE,EAAE,CAC7C,GAAG,KAAK,WAAW,IAAI,GAAG,KAAK,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAC9D,CACe,CAAC;AACnB,MAAM,kBAAkB,GAAqC;IAC3D,WAAW,EAAE,KAAK;IAClB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C;IACD,IACE,MAAM,KAAK,OAAO;QAClB,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,GAAG,qBAAqB;YAC/D,GAAG,GAAG,IAAI;QAEZ,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAClE,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAAc;IAClD,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IAC9B,IACE,IAAI,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI;QACxD,MAAM,CAAC,KAAK,CAAC,MAAM;QAEnB,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC3D,IACE,IAAI,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC,IAAI;QAChE,MAAM,CAAC,KAAK,CAAC,MAAM;QAEnB,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK;QAAE,wBAAwB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACzE,IAAI,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI;QAC7D,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;IAC9D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { isIP } from \"node:net\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport schema from \"../schemas/external-findings.schema.json\" with { type: \"json\" };\nimport type {\n ExternalFindingEvidence,\n FindingImportRequest,\n FindingImportReceipt,\n ImportRepositoryPage,\n SourceReportPage,\n SourceReport,\n} from \"./external-import-models.js\";\n\nconst ajv = new Ajv2020({\n strict: false,\n validateFormats: false,\n useDefaults: true,\n});\n\n/** Local storage accepts complete evidence; Cloud publication has payload limits. */\nexport type ExternalImportTarget = \"local\" | \"cloud\";\n\nconst localSchema = JSON.parse(\n JSON.stringify(schema, (key, value: unknown) =>\n key === \"maxLength\" || key === \"maxItems\" ? undefined : value,\n ),\n) as typeof schema;\nconst STRING_BYTE_LIMITS: Readonly<Record<string, number>> = {\n description: 65536,\n snippet: 65536,\n remediation_instructions: 65536,\n expected: 65536,\n actual: 65536,\n file_url: 2048,\n path: 2048,\n url: 2048,\n manifest_path: 2048,\n client_id: 128,\n next: 4096,\n};\n\n/** Compare repository URLs without changing the retained vendor evidence.\n * GitHub repository paths are case-insensitive; unknown VCS hosts stay strict.\n * Keep protocols and explicit ports distinct, matching the Cloud URL contract. */\nexport function repositoryUrlKey(value: string): string {\n const normalized = value.replace(/\\/$/u, \"\").replace(/\\.git$/u, \"\");\n const parts = /^(https?):\\/\\/([^/?#]+)((?:\\/[^?#]*)?)((?:[?#].*)?)$/iu.exec(\n normalized,\n );\n if (!parts) return normalized;\n const authority = parts[2]!.toLowerCase();\n const hostname = authority.replace(/:\\d+$/u, \"\");\n const path =\n hostname === \"github.com\" || hostname.endsWith(\".ghe.com\")\n ? parts[3]!.toLowerCase()\n : parts[3]!;\n return `${parts[1]!.toLowerCase()}://${authority}${path}${parts[4]!}`;\n}\n\n// Cloud's import catalog contains GitHub repositories, including custom Enterprise\n// hosts. Match its case-insensitive URL identity without merging schemes or ports.\nexport function cloudRepositoryUrlKey(value: string): string {\n return repositoryUrlKey(value).toLowerCase();\n}\n\n// Cloud ImportModel applies these constraints to both requests and responses.\n// Its UTF-8 limits are not exported as JSON Schema character limits: even a\n// plain string field such as a receipt error message inherits the 512-byte bound.\nfunction validateModelStrings(\n input: unknown,\n target: ExternalImportTarget,\n): void {\n if (input === null || typeof input !== \"object\") return;\n if (Array.isArray(input)) {\n for (const item of input) validateModelStrings(item, target);\n return;\n }\n for (const [field, value] of Object.entries(input)) {\n if (field === \"source_data\") continue;\n if (typeof value === \"string\") {\n if (\n (!value.trim() && ![\"snippet\", \"expected\", \"actual\"].includes(field)) ||\n value.includes(\"\\0\")\n )\n throw new Error(\n `${field} must be nonempty and contain no NUL characters.`,\n );\n const limit = STRING_BYTE_LIMITS[field] ?? 512;\n if (target === \"cloud\" && Buffer.byteLength(value) > limit)\n throw new Error(\n `${field} exceeds its Cloud limit of ${limit} UTF-8 bytes.`,\n );\n } else if (\n Array.isArray(value) &&\n value.every((item) => typeof item === \"string\")\n ) {\n if (\n target === \"cloud\" &&\n value.some((item) => Buffer.byteLength(item) > 512)\n )\n throw new Error(\n `${field} entries exceed the Cloud limit of 512 UTF-8 bytes.`,\n );\n } else validateModelStrings(value, target);\n }\n}\n\ntype ModelSchema = {\n $ref?: string;\n anyOf?: ModelSchema[];\n properties?: Record<string, ModelSchema>;\n [key: string]: unknown;\n};\nconst detailValidators = new Map<string, ReturnType<typeof ajv.compile>>();\n\n/** AJV does not apply defaults through nullable anyOf references. Validate the\n * present detail objects directly against their generated model definitions so\n * sparse normalized inputs match the backend's serialized evidence. */\nfunction materializeDetailDefaults(\n value: unknown,\n fieldSchema: ModelSchema,\n target: ExternalImportTarget,\n): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value))\n return;\n const reference =\n fieldSchema.$ref ?? fieldSchema.anyOf?.find((branch) => branch.$ref)?.$ref;\n if (!reference) return;\n const name = reference.split(\"/\").at(-1)!;\n const modelSchema = target === \"local\" ? localSchema : schema;\n const definition: ModelSchema =\n modelSchema.$defs[name as keyof typeof schema.$defs]!;\n const key = `${target}:${reference}`;\n let check = detailValidators.get(key);\n if (!check) {\n check = ajv.compile({ $defs: modelSchema.$defs, $ref: reference });\n detailValidators.set(key, check);\n }\n if (!check(value))\n throw new Error(`${name}: ${ajv.errorsText(check.errors)}`);\n for (const [field, childSchema] of Object.entries(\n definition.properties ?? {},\n ))\n materializeDetailDefaults(\n (value as Record<string, unknown>)[field],\n childSchema,\n target,\n );\n}\n\nfunction normalizeEvidenceDetails(\n value: unknown,\n target: ExternalImportTarget,\n): void {\n if (value !== null && typeof value === \"object\") {\n const fields = value as Record<string, unknown>;\n // Cloud omits these new optional fields when null. Preserve every legacy\n // default so saved Wiz requests still replay the same evidence bytes.\n if (Array.isArray(fields[\"packages\"]))\n for (const value of fields[\"packages\"]) {\n if (\n value &&\n typeof value === \"object\" &&\n value[\"vulnerable_version_range\"] === null\n )\n delete value[\"vulnerable_version_range\"];\n }\n if (fields[\"details\"] === null) delete fields[\"details\"];\n else {\n const details = fields[\"details\"];\n if (details && typeof details === \"object\" && !Array.isArray(details))\n for (const field of [\"repository\", \"advisory\"])\n if ((details as Record<string, unknown>)[field] === null)\n delete (details as Record<string, unknown>)[field];\n materializeDetailDefaults(\n fields[\"details\"],\n schema.$defs.ImportedFindingEvidence.properties.details,\n target,\n );\n }\n }\n}\n\nfunction validator<T>(\n name: keyof typeof schema.$defs,\n target: ExternalImportTarget = \"cloud\",\n) {\n const check = ajv.compile<T>({\n $defs: (target === \"local\" ? localSchema : schema).$defs,\n $ref: `#/$defs/${name}`,\n });\n return (input: unknown): T => {\n if (name === \"ImportedFindingEvidence\")\n normalizeEvidenceDetails(input, target);\n else if (input && typeof input === \"object\") {\n if (name === \"SourceReport\" && \"evidence\" in input)\n normalizeEvidenceDetails(input.evidence, target);\n if (\n name === \"FindingImportRequest\" &&\n \"items\" in input &&\n Array.isArray(input.items)\n )\n for (const item of input.items)\n normalizeEvidenceDetails(item?.evidence, target);\n }\n if (!check(input))\n throw new Error(`${name}: ${ajv.errorsText(check.errors)}`);\n validateModelStrings(input, target);\n return input;\n };\n}\n\nconst evidence = validator<ExternalFindingEvidence>(\"ImportedFindingEvidence\");\nconst localEvidence = validator<ExternalFindingEvidence>(\n \"ImportedFindingEvidence\",\n \"local\",\n);\nconst request = validator<FindingImportRequest>(\"FindingImportRequest\");\nexport const validateImportReceipt = validator<FindingImportReceipt>(\n \"FindingImportReceipt\",\n);\nexport const validateRepositories = validator<ImportRepositoryPage>(\n \"ImportRepositoryPage\",\n);\nexport const validateSourceReports =\n validator<SourceReportPage>(\"SourceReportPage\");\nexport const validateSourceReport = validator<SourceReport>(\"SourceReport\");\n\nexport function validateExternalEvidence(\n input: unknown,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindingEvidence {\n const result = (target === \"local\" ? localEvidence : evidence)(input);\n for (const location of result.locations ?? []) {\n const path = location.path.replaceAll(\"\\\\\", \"/\");\n if (\n path.startsWith(\"/\") ||\n /^[A-Za-z]:/.test(path) ||\n path.split(\"/\").includes(\"..\")\n )\n throw new Error(\"Locations must use repository-relative paths.\");\n }\n const details = result.details;\n if (details) {\n if (details.kind === \"advisory\") {\n if (!details.advisory)\n throw new Error(\"Advisory evidence requires its source context.\");\n if (details.advisory.source === \"global\" && details.repository)\n throw new Error(\n \"Global advisory evidence cannot claim a source repository.\",\n );\n if (details.advisory.source === \"repository\" && !details.repository)\n throw new Error(\n \"Repository advisory evidence requires its source repository.\",\n );\n } else {\n if (!details.repository)\n throw new Error(\n \"Repository finding evidence requires its source repository.\",\n );\n if (details.advisory)\n throw new Error(\"Advisory source context requires advisory evidence.\");\n }\n }\n const endLine = result.details?.code?.end_line;\n if (endLine !== null && endLine !== undefined) {\n const firstLine = result.locations?.[0]?.line;\n if (firstLine === null || firstLine === undefined || endLine < firstLine)\n throw new Error(\n \"The code end line requires a first source location line and cannot precede it.\",\n );\n }\n const urls = [\n result.url,\n result.details?.repository?.url,\n result.details?.file_url,\n ];\n for (const value of urls) {\n if (value === null || value === undefined) continue;\n const url = value\n .replace(/[\\t\\r\\n]/gu, \"\")\n .replace(/^[\\u0000-\\u0020]+/u, \"\");\n const authority = /^https?:\\/\\/([^/?#]+)/iu.exec(url)?.[1];\n const normalizedAuthority = (authority ?? \"\")\n .replace(/[@:#?]/gu, \"\")\n .normalize(\"NFKC\");\n let validHost = true;\n if (authority?.includes(\"[\") || authority?.includes(\"]\")) {\n const hostname = /^\\[([^\\]]+)\\](?::[\\s\\S]*)?$/u.exec(authority)?.[1];\n const [address, scope, extraScope] = (hostname ?? \"\").split(\"%\");\n // Cloud accepts scoped IPv6 and IPvFuture hosts in brackets.\n validHost =\n hostname !== undefined &&\n (/^v[a-fA-F0-9]+\\.[\\s\\S]+$/u.test(hostname) ||\n (isIP(address!) === 6 && scope !== \"\" && extraScope === undefined));\n }\n if (\n !authority ||\n authority.includes(\"@\") ||\n /[/?#@:]/u.test(normalizedAuthority) ||\n !validHost\n )\n throw new Error(\n \"Evidence URLs must be HTTP(S) links without credentials.\",\n );\n }\n // Local evidence still has to be serializable JSON, including acyclic source data.\n if (target === \"local\") JSON.stringify(result);\n let numericByteAdjustment = 0;\n const pending: [unknown, number][] = [[result, 0]];\n while (pending.length > 0) {\n const [value, depth] = pending.pop()!;\n if (target === \"cloud\" && depth > 20)\n throw new Error(\"Evidence exceeds the Cloud JSON depth limit of 20.\");\n if (value !== null && typeof value === \"object\") {\n for (const child of Object.values(value))\n pending.push([child, depth + 1]);\n } else if (typeof value === \"number\") {\n if (!Number.isFinite(value))\n throw new Error(\"Evidence must contain finite JSON numbers.\");\n if (Number.isInteger(value) && !Number.isSafeInteger(value))\n throw new Error(\n \"Evidence integers must be within JavaScript's safe integer range; export larger values as strings to preserve them exactly.\",\n );\n const wire = JSON.stringify(value);\n // Cloud pads short exponents and formats small fractions scientifically.\n const cloud = (\n wire.includes(\".\") && Math.abs(value) < 1e-4\n ? value.toExponential()\n : wire\n ).replace(/e-(\\d)$/u, \"e-0$1\");\n numericByteAdjustment += cloud.length - wire.length;\n }\n }\n if (\n target === \"cloud\" &&\n Buffer.byteLength(JSON.stringify(result)) + numericByteAdjustment >\n 256 * 1024\n )\n throw new Error(\"Evidence exceeds the Cloud limit of 256 KiB.\");\n return result;\n}\n\nexport function validateImportRequest(input: unknown): FindingImportRequest {\n const result = request(input);\n if (\n new Set(result.items.map((item) => item.client_id)).size !==\n result.items.length\n )\n throw new Error(\"Import contains duplicate client IDs.\");\n if (\n new Set(result.items.map((item) => item.source_finding_id)).size !==\n result.items.length\n )\n throw new Error(\"Import contains duplicate source finding identities.\");\n for (const item of result.items) validateExternalEvidence(item.evidence);\n if (Buffer.byteLength(JSON.stringify(result)) > 5 * 1024 * 1024)\n throw new Error(\"Import exceeds the Cloud limit of 5 MiB.\");\n return result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"external-import-contract.js","sourceRoot":"","sources":["../src/external-import-contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,OAAO,MAAM,kBAAkB,CAAC;AACvC,OAAO,MAAM,MAAM,0CAA0C,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAUpF,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC;IACtB,MAAM,EAAE,KAAK;IACb,eAAe,EAAE,KAAK;IACtB,WAAW,EAAE,IAAI;CAClB,CAAC,CAAC;AAKH,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAC5B,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,KAAc,EAAE,EAAE,CAC7C,GAAG,KAAK,WAAW,IAAI,GAAG,KAAK,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAC9D,CACe,CAAC;AACnB,MAAM,kBAAkB,GAAqC;IAC3D,WAAW,EAAE,KAAK;IAClB,OAAO,EAAE,KAAK;IACd,wBAAwB,EAAE,KAAK;IAC/B,QAAQ,EAAE,KAAK;IACf,MAAM,EAAE,KAAK;IACb,QAAQ,EAAE,IAAI;IACd,IAAI,EAAE,IAAI;IACV,GAAG,EAAE,IAAI;IACT,aAAa,EAAE,IAAI;IACnB,SAAS,EAAE,GAAG;IACd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AAiB,CAAC,CAAC,CAAC,IAAI;QAChE,MAAM,CAAC,KAAK,CAAC,MAAM;QAEnB,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK;QAAE,wBAAwB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACzE,IAAI,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI;QAC7D,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;IAC9D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { isIP } from \"node:net\";\nimport { isNumberObject } from \"node:util/types\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport schema from \"../schemas/external-findings.schema.json\" with { type: \"json\" };\nimport type {\n ExternalFindingEvidence,\n FindingImportRequest,\n FindingImportReceipt,\n ImportRepositoryPage,\n SourceReportPage,\n SourceReport,\n} from \"./external-import-models.js\";\n\nconst ajv = new Ajv2020({\n strict: false,\n validateFormats: false,\n useDefaults: true,\n});\n\n/** Local storage accepts complete evidence; Cloud publication has payload limits. */\nexport type ExternalImportTarget = \"local\" | \"cloud\";\n\nconst localSchema = JSON.parse(\n JSON.stringify(schema, (key, value: unknown) =>\n key === \"maxLength\" || key === \"maxItems\" ? undefined : value,\n ),\n) as typeof schema;\nconst STRING_BYTE_LIMITS: Readonly<Record<string, number>> = {\n description: 65536,\n snippet: 65536,\n remediation_instructions: 65536,\n expected: 65536,\n actual: 65536,\n file_url: 2048,\n path: 2048,\n url: 2048,\n manifest_path: 2048,\n client_id: 128,\n next: 4096,\n};\n\n/** Compare repository URLs without changing the retained vendor evidence.\n * GitHub repository paths are case-insensitive; unknown VCS hosts stay strict.\n * Keep protocols and explicit ports distinct, matching the Cloud URL contract. */\nexport function repositoryUrlKey(value: string): string {\n const normalized = value.replace(/\\/$/u, \"\").replace(/\\.git$/u, \"\");\n const parts = /^(https?):\\/\\/([^/?#]+)((?:\\/[^?#]*)?)((?:[?#].*)?)$/iu.exec(\n normalized,\n );\n if (!parts) return normalized;\n const authority = parts[2]!.toLowerCase();\n const hostname = authority.replace(/:\\d+$/u, \"\");\n const path =\n hostname === \"github.com\" || hostname.endsWith(\".ghe.com\")\n ? parts[3]!.toLowerCase()\n : parts[3]!;\n return `${parts[1]!.toLowerCase()}://${authority}${path}${parts[4]!}`;\n}\n\n// Cloud's import catalog contains GitHub repositories, including custom Enterprise\n// hosts. Match its case-insensitive URL identity without merging schemes or ports.\nexport function cloudRepositoryUrlKey(value: string): string {\n return repositoryUrlKey(value).toLowerCase();\n}\n\n// Cloud ImportModel applies these constraints to both requests and responses.\n// Its UTF-8 limits are not exported as JSON Schema character limits: even a\n// plain string field such as a receipt error message inherits the 512-byte bound.\nfunction validateModelStrings(\n input: unknown,\n target: ExternalImportTarget,\n): void {\n if (input === null || typeof input !== \"object\") return;\n if (Array.isArray(input)) {\n for (const item of input) validateModelStrings(item, target);\n return;\n }\n for (const [field, value] of Object.entries(input)) {\n if (field === \"source_data\") continue;\n if (typeof value === \"string\") {\n if (\n (!value.trim() && ![\"snippet\", \"expected\", \"actual\"].includes(field)) ||\n value.includes(\"\\0\")\n )\n throw new Error(\n `${field} must be nonempty and contain no NUL characters.`,\n );\n const limit = STRING_BYTE_LIMITS[field] ?? 512;\n if (target === \"cloud\" && Buffer.byteLength(value) > limit)\n throw new Error(\n `${field} exceeds its Cloud limit of ${limit} UTF-8 bytes.`,\n );\n } else if (\n Array.isArray(value) &&\n value.every((item) => typeof item === \"string\")\n ) {\n if (\n target === \"cloud\" &&\n value.some((item) => Buffer.byteLength(item) > 512)\n )\n throw new Error(\n `${field} entries exceed the Cloud limit of 512 UTF-8 bytes.`,\n );\n } else validateModelStrings(value, target);\n }\n}\n\ntype ModelSchema = {\n $ref?: string;\n anyOf?: ModelSchema[];\n properties?: Record<string, ModelSchema>;\n [key: string]: unknown;\n};\nconst detailValidators = new Map<string, ReturnType<typeof ajv.compile>>();\n\n/** AJV does not apply defaults through nullable anyOf references. Validate the\n * present detail objects directly against their generated model definitions so\n * sparse normalized inputs match the backend's serialized evidence. */\nfunction materializeDetailDefaults(\n value: unknown,\n fieldSchema: ModelSchema,\n target: ExternalImportTarget,\n): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value))\n return;\n const reference =\n fieldSchema.$ref ?? fieldSchema.anyOf?.find((branch) => branch.$ref)?.$ref;\n if (!reference) return;\n const name = reference.split(\"/\").at(-1)!;\n const modelSchema = target === \"local\" ? localSchema : schema;\n const definition: ModelSchema =\n modelSchema.$defs[name as keyof typeof schema.$defs]!;\n const key = `${target}:${reference}`;\n let check = detailValidators.get(key);\n if (!check) {\n check = ajv.compile({ $defs: modelSchema.$defs, $ref: reference });\n detailValidators.set(key, check);\n }\n if (!check(value))\n throw new Error(`${name}: ${ajv.errorsText(check.errors)}`);\n for (const [field, childSchema] of Object.entries(\n definition.properties ?? {},\n ))\n materializeDetailDefaults(\n (value as Record<string, unknown>)[field],\n childSchema,\n target,\n );\n}\n\nfunction normalizeEvidenceDetails(\n value: unknown,\n target: ExternalImportTarget,\n): void {\n if (value !== null && typeof value === \"object\") {\n const fields = value as Record<string, unknown>;\n // Cloud omits these new optional fields when null. Preserve every legacy\n // default so saved Wiz requests still replay the same evidence bytes.\n if (Array.isArray(fields[\"packages\"]))\n for (const value of fields[\"packages\"]) {\n if (\n value &&\n typeof value === \"object\" &&\n value[\"vulnerable_version_range\"] === null\n )\n delete value[\"vulnerable_version_range\"];\n }\n if (fields[\"details\"] === null) delete fields[\"details\"];\n else {\n const details = fields[\"details\"];\n if (details && typeof details === \"object\" && !Array.isArray(details))\n for (const field of [\"repository\", \"advisory\"])\n if ((details as Record<string, unknown>)[field] === null)\n delete (details as Record<string, unknown>)[field];\n materializeDetailDefaults(\n fields[\"details\"],\n schema.$defs.ImportedFindingEvidence.properties.details,\n target,\n );\n }\n }\n}\n\nfunction validator<T>(\n name: keyof typeof schema.$defs,\n target: ExternalImportTarget = \"cloud\",\n) {\n const check = ajv.compile<T>({\n $defs: (target === \"local\" ? localSchema : schema).$defs,\n $ref: `#/$defs/${name}`,\n });\n return (input: unknown): T => {\n if (name === \"ImportedFindingEvidence\")\n normalizeEvidenceDetails(input, target);\n else if (input && typeof input === \"object\") {\n if (name === \"SourceReport\" && \"evidence\" in input)\n normalizeEvidenceDetails(input.evidence, target);\n if (\n name === \"FindingImportRequest\" &&\n \"items\" in input &&\n Array.isArray(input.items)\n )\n for (const item of input.items)\n normalizeEvidenceDetails(item?.evidence, target);\n }\n if (!check(input))\n throw new Error(`${name}: ${ajv.errorsText(check.errors)}`);\n validateModelStrings(input, target);\n return input;\n };\n}\n\nconst evidence = validator<ExternalFindingEvidence>(\"ImportedFindingEvidence\");\nconst localEvidence = validator<ExternalFindingEvidence>(\n \"ImportedFindingEvidence\",\n \"local\",\n);\nconst request = validator<FindingImportRequest>(\"FindingImportRequest\");\nexport const validateImportReceipt = validator<FindingImportReceipt>(\n \"FindingImportReceipt\",\n);\nexport const validateRepositories = validator<ImportRepositoryPage>(\n \"ImportRepositoryPage\",\n);\nexport const validateSourceReports =\n validator<SourceReportPage>(\"SourceReportPage\");\nexport const validateSourceReport = validator<SourceReport>(\"SourceReport\");\n\nfunction requireJsonNumber(value: number, label: string): void {\n if (!Number.isFinite(value))\n throw new Error(`${label} must contain finite JSON numbers.`);\n if (Number.isInteger(value) && !Number.isSafeInteger(value))\n throw new Error(\n `${label} integers must be within JavaScript's safe integer range; export larger values as strings to preserve them exactly.`,\n );\n}\n\n/** Report metadata is retained in previews and receipts without Cloud evidence size limits. */\nexport function validateExternalReport(\n report: Record<string, unknown> | undefined,\n): void {\n if (report === undefined) return;\n JSON.stringify(report, (_key, value: unknown) => {\n if (isNumberObject(value)) value = +value;\n if (typeof value === \"number\") requireJsonNumber(value, \"Scanner report\");\n return value;\n });\n}\n\nexport function validateExternalEvidence(\n input: unknown,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindingEvidence {\n const result = (target === \"local\" ? localEvidence : evidence)(input);\n for (const location of result.locations ?? []) {\n const path = location.path.replaceAll(\"\\\\\", \"/\");\n if (\n path.startsWith(\"/\") ||\n /^[A-Za-z]:/.test(path) ||\n path.split(\"/\").includes(\"..\")\n )\n throw new Error(\"Locations must use repository-relative paths.\");\n }\n const details = result.details;\n if (details) {\n if (details.kind === \"advisory\") {\n if (!details.advisory)\n throw new Error(\"Advisory evidence requires its source context.\");\n if (details.advisory.source === \"global\" && details.repository)\n throw new Error(\n \"Global advisory evidence cannot claim a source repository.\",\n );\n if (details.advisory.source === \"repository\" && !details.repository)\n throw new Error(\n \"Repository advisory evidence requires its source repository.\",\n );\n } else {\n if (!details.repository)\n throw new Error(\n \"Repository finding evidence requires its source repository.\",\n );\n if (details.advisory)\n throw new Error(\"Advisory source context requires advisory evidence.\");\n }\n }\n const endLine = result.details?.code?.end_line;\n if (endLine !== null && endLine !== undefined) {\n const firstLine = result.locations?.[0]?.line;\n if (firstLine === null || firstLine === undefined || endLine < firstLine)\n throw new Error(\n \"The code end line requires a first source location line and cannot precede it.\",\n );\n }\n const urls = [\n result.url,\n result.details?.repository?.url,\n result.details?.file_url,\n ];\n for (const value of urls) {\n if (value === null || value === undefined) continue;\n const url = value\n .replace(/[\\t\\r\\n]/gu, \"\")\n .replace(/^[\\u0000-\\u0020]+/u, \"\");\n const authority = /^https?:\\/\\/([^/?#]+)/iu.exec(url)?.[1];\n const normalizedAuthority = (authority ?? \"\")\n .replace(/[@:#?]/gu, \"\")\n .normalize(\"NFKC\");\n let validHost = true;\n if (authority?.includes(\"[\") || authority?.includes(\"]\")) {\n const hostname = /^\\[([^\\]]+)\\](?::[\\s\\S]*)?$/u.exec(authority)?.[1];\n const [address, scope, extraScope] = (hostname ?? \"\").split(\"%\");\n // Cloud accepts scoped IPv6 and IPvFuture hosts in brackets.\n validHost =\n hostname !== undefined &&\n (/^v[a-fA-F0-9]+\\.[\\s\\S]+$/u.test(hostname) ||\n (isIP(address!) === 6 && scope !== \"\" && extraScope === undefined));\n }\n if (\n !authority ||\n authority.includes(\"@\") ||\n /[/?#@:]/u.test(normalizedAuthority) ||\n !validHost\n )\n throw new Error(\n \"Evidence URLs must be HTTP(S) links without credentials.\",\n );\n }\n validateExternalEvidenceJson(result, target);\n return result;\n}\n\n/** Return the validated Cloud wire size, or zero for local evidence. */\nexport function validateExternalEvidenceJson(\n input: unknown,\n target: ExternalImportTarget,\n additionalCloudBytes = 0,\n): number {\n // Local evidence still has to be serializable JSON, including acyclic source data.\n if (target === \"local\") JSON.stringify(input);\n let numericByteAdjustment = 0;\n const pending: [unknown, number][] = [[input, 0]];\n while (pending.length > 0) {\n const [value, depth] = pending.pop()!;\n if (target === \"cloud\" && depth > 20)\n throw new Error(\"Evidence exceeds the Cloud JSON depth limit of 20.\");\n if (value !== null && typeof value === \"object\") {\n for (const child of Object.values(value))\n pending.push([child, depth + 1]);\n } else if (typeof value === \"number\") {\n requireJsonNumber(value, \"Evidence\");\n const wire = JSON.stringify(value);\n // Cloud pads short exponents and formats small fractions scientifically.\n const cloud = (\n wire.includes(\".\") && Math.abs(value) < 1e-4\n ? value.toExponential()\n : wire\n ).replace(/e-(\\d)$/u, \"e-0$1\");\n numericByteAdjustment += cloud.length - wire.length;\n }\n }\n const bytes =\n target === \"cloud\"\n ? Buffer.byteLength(JSON.stringify(input)) +\n numericByteAdjustment +\n additionalCloudBytes\n : 0;\n if (bytes > 256 * 1024)\n throw new Error(\"Evidence exceeds the Cloud limit of 256 KiB.\");\n return bytes;\n}\n\nexport function validateImportRequest(input: unknown): FindingImportRequest {\n const result = request(input);\n if (\n new Set(result.items.map((item) => item.client_id)).size !==\n result.items.length\n )\n throw new Error(\"Import contains duplicate client IDs.\");\n if (\n new Set(result.items.map((item) => item.source_finding_id)).size !==\n result.items.length\n )\n throw new Error(\"Import contains duplicate source finding identities.\");\n for (const item of result.items) validateExternalEvidence(item.evidence);\n if (Buffer.byteLength(JSON.stringify(result)) > 5 * 1024 * 1024)\n throw new Error(\"Import exceeds the Cloud limit of 5 MiB.\");\n return result;\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { JsonObject } from "./config.js";
|
|
2
|
+
import type { LoadedContract } from "./contract.js";
|
|
2
3
|
import type { FindingSearchScope } from "./finding-retrieval.js";
|
|
3
4
|
import { runWorkbench, type WorkbenchCommandOptions } from "./runtime.js";
|
|
4
5
|
export type WorkflowStage = "scan" | "publish" | "dedupe";
|
|
@@ -35,6 +36,7 @@ interface SourceSnapshotOptions {
|
|
|
35
36
|
evidence?: boolean;
|
|
36
37
|
}
|
|
37
38
|
export declare function workflowDigest(value: unknown): string;
|
|
39
|
+
export declare function scanArtifactDigest({ manifest, findings, review, }: Pick<LoadedContract, "manifest" | "findings" | "review">): string;
|
|
38
40
|
export declare function workflowDestination(url: string): string;
|
|
39
41
|
/** State lives in the workbench database, never in sealed scan artifacts. */
|
|
40
42
|
export declare class FindingWorkflow {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"finding-workflow.d.ts","sourceRoot":"","sources":["../src/finding-workflow.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"finding-workflow.d.ts","sourceRoot":"","sources":["../src/finding-workflow.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAGpD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAML,YAAY,EACZ,KAAK,uBAAuB,EAC7B,MAAM,cAAc,CAAC;AAEtB,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,SAAS,GAAG,QAAQ,CAAC;AAC1D,MAAM,WAAW,eAAe;IAC9B,cAAc,CAAC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ClB,UAAU,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE,qBAAqB,GAAG;QAAE,QAAQ,CAAC,EAAE,KAAK,CAAA;KAAE,GACrD,OAAO,CAAC,UAAU,CAAC,CAAC;IACjB,cAAc,CAClB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,qBAAqB,GAAG;QAAE,QAAQ,EAAE,IAAI,CAAA;KAAE,GAClD,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;IAmBxB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAE7C;IAEK,UAAU,CACd,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,OAAO,EACf,OAAO,GAAE;QAAE,OAAO,CAAC,EAAE,OAAO,CAAA;KAAO,GAClC,OAAO,CAAC,IAAI,CAAC,CAQf;IAEK,aAAa,CACjB,MAAM,EAAE,OAAO,EACf,YAAY,EAAE,kBAAkB,GAC/B,OAAO,CAAC,IAAI,CAAC,CAOf;YAEa,OAAO;YAKP,OAAO;YAOP,IAAI;CAgBnB"}
|
package/dist/finding-workflow.js
CHANGED
|
@@ -9,6 +9,9 @@ export function workflowDigest(value) {
|
|
|
9
9
|
: item);
|
|
10
10
|
return createHash("sha256").update(json).digest("hex");
|
|
11
11
|
}
|
|
12
|
+
export function scanArtifactDigest({ manifest, findings, review, }) {
|
|
13
|
+
return workflowDigest({ manifest, findings, review });
|
|
14
|
+
}
|
|
12
15
|
export function workflowDestination(url) {
|
|
13
16
|
const destination = findingsBaseUrl(url);
|
|
14
17
|
destination.username = "";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"finding-workflow.js","sourceRoot":"","sources":["../src/finding-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAEtD,OA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AAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAC/D,CAAC;CACF","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { isAbsolute, relative, sep } from \"node:path\";\nimport type { JsonObject } from \"./config.js\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\nimport { findingsBaseUrl } from \"./findings-client.js\";\nimport type { FindingSearchScope } from \"./finding-retrieval.js\";\nimport {\n bundledPluginRoot,\n canonicalizeModelSafePath,\n codexSecurityStateDirectory,\n workbenchEnvironment,\n resolvePluginPython,\n runWorkbench,\n type WorkbenchCommandOptions,\n} from \"./runtime.js\";\n\nexport type WorkflowStage = \"scan\" | \"publish\" | \"dedupe\";\nexport interface WorkflowBinding {\n repositoryPath?: string;\n scanRequestDigest?: string;\n scanId?: string;\n scanDir?: string;\n artifactDigest?: string;\n destination?: string;\n scope?: FindingSearchScope;\n}\nexport interface WorkflowState extends WorkflowBinding {\n id: string;\n stages: Record<\n WorkflowStage,\n {\n status: \"pending\" | \"running\" | \"failed\" | \"completed\";\n result?: unknown;\n error?: string;\n pendingWrite?: DedupePendingWrite;\n }\n >;\n}\n\nexport interface DedupePendingWrite {\n groups: string[][];\n local?: { inputDigest: string; source: JsonObject; gitDisabled?: boolean };\n}\n\ninterface SourceSnapshotOptions {\n optional?: boolean;\n gitDisabled?: boolean;\n privateStatePaths?: readonly string[];\n evidence?: boolean;\n}\n\nexport function workflowDigest(value: unknown): string {\n const json = JSON.stringify(value, (_key, item: unknown) =>\n item !== null && typeof item === \"object\" && !Array.isArray(item)\n ? Object.fromEntries(\n Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n )\n : item,\n );\n return createHash(\"sha256\").update(json).digest(\"hex\");\n}\n\nexport function workflowDestination(url: string): string {\n const destination = findingsBaseUrl(url);\n destination.username = \"\";\n destination.password = \"\";\n return destination.href;\n}\n\n/** State lives in the workbench database, never in sealed scan artifacts. */\nexport class FindingWorkflow {\n private options?: Promise<WorkbenchCommandOptions>;\n\n constructor(\n readonly id: string,\n private readonly environment: NodeJS.ProcessEnv = process.env,\n private readonly workbench: typeof runWorkbench = runWorkbench,\n private readonly pythonPath?: string,\n private readonly selection: {\n protectedRoot?: string;\n workbenchOptions?: WorkbenchCommandOptions;\n } = {},\n ) {\n if (!id.trim())\n throw new CodexSecurityError(\"workflowId must be a nonempty string.\");\n if (selection.workbenchOptions !== undefined)\n this.options = Promise.resolve(selection.workbenchOptions);\n }\n\n async protectArtifacts(scanDir: string): Promise<void> {\n const path = relative(\n await canonicalizeModelSafePath(scanDir),\n await canonicalizeModelSafePath(\n codexSecurityStateDirectory(this.environment),\n ),\n );\n if (\n path === \"\" ||\n (!isAbsolute(path) && path !== \"..\" && !path.startsWith(`..${sep}`))\n ) {\n throw new CodexSecurityError(\n \"Workflow state must be outside the sealed scan artifacts.\",\n );\n }\n }\n\n async get(): Promise<WorkflowState | null> {\n return (await this.command({ action: \"get\" })) as WorkflowState | null;\n }\n\n async bind(binding: WorkflowBinding): Promise<WorkflowState> {\n return (await this.command({ action: \"bind\", binding }))!;\n }\n\n async begin(stage: WorkflowStage): Promise<WorkflowState> {\n return (await this.command({ action: \"begin\", stage }))!;\n }\n\n async complete(\n stage: WorkflowStage,\n result: unknown,\n ): Promise<WorkflowState> {\n return (await this.command({ action: \"complete\", stage, result }))!;\n }\n\n async fail(\n stage: WorkflowStage,\n error: unknown,\n result?: unknown,\n ): Promise<void> {\n await this.command({\n action: \"fail\",\n stage,\n error: errorMessage(error),\n ...(result === undefined ? {} : { result }),\n }).catch(() => undefined);\n }\n\n async run<T>(stage: WorkflowStage, operation: () => Promise<T>): Promise<T> {\n const state = await this.begin(stage);\n if (state.stages[stage].status === \"completed\")\n return state.stages[stage].result as T;\n try {\n const result = await operation();\n await this.complete(stage, result);\n return result;\n } catch (error) {\n await this.fail(stage, error);\n throw error;\n }\n }\n\n async registeredScan(scanId: string): Promise<JsonObject> {\n const context = await this.call([\"get-scan\", \"--scan-id\", scanId]);\n return context[\"scan\"] as JsonObject;\n }\n\n async sourceSnapshot(\n repository: string,\n options?: SourceSnapshotOptions & { optional?: false },\n ): Promise<JsonObject>;\n async sourceSnapshot(\n repository: string,\n options: SourceSnapshotOptions & { optional: true },\n ): Promise<JsonObject | null>;\n async sourceSnapshot(\n repository: string,\n options: SourceSnapshotOptions = {},\n ): Promise<JsonObject | null> {\n return (\n await this.request({\n action: \"source\",\n repository,\n ...(options.optional ? { optional: true } : {}),\n ...(options.gitDisabled ? { gitDisabled: true } : {}),\n ...(options.evidence ? { evidence: true } : {}),\n ...(options.privateStatePaths?.length\n ? { privateStatePaths: options.privateStatePaths }\n : {}),\n })\n )[\"source\"] as JsonObject | null;\n }\n\n async getReview(key: string): Promise<unknown> {\n return (await this.request({ action: \"get-review\", key }))[\"review\"];\n }\n\n async saveReview(\n key: string,\n binding: object,\n result: unknown,\n options: { replace?: boolean } = {},\n ): Promise<void> {\n await this.request({\n action: \"save-review\",\n key,\n binding,\n result,\n ...(options.replace ? { replace: true } : {}),\n });\n }\n\n async prepareDedupe(\n result: unknown,\n pendingWrite: DedupePendingWrite,\n ): Promise<void> {\n await this.command({\n action: \"prepare-dedupe\",\n stage: \"dedupe\",\n result,\n pendingWrite,\n });\n }\n\n private async command(payload: object): Promise<WorkflowState | null> {\n const result = await this.request(payload);\n return result[\"workflow\"] as unknown as WorkflowState | null;\n }\n\n private async request(payload: object): Promise<JsonObject> {\n return await this.call(\n [\"finding-workflow\"],\n JSON.stringify({ id: this.id, ...payload }),\n );\n }\n\n private async call(\n args: readonly string[],\n input?: string,\n ): Promise<JsonObject> {\n this.options ??= (async () => ({\n pluginRoot: await bundledPluginRoot(),\n python: await resolvePluginPython({\n environment: this.environment,\n configuredPath: this.pythonPath,\n protectedRoot: this.selection.protectedRoot,\n }),\n environment: workbenchEnvironment(this.environment),\n failureMessage: \"Could not save or resume the findings workflow\",\n }))();\n return await this.workbench(await this.options, args, input);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":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AiB,EAAE;YACrC,MAAM,EAAE,MAAM,mBAAmB,CAAC;gBAChC,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,cAAc,EAAE,IAAI,CAAC,UAAU;gBAC/B,aAAa,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa;aAC5C,CAAC;YACF,WAAW,EAAE,oBAAoB,CAAC,IAAI,CAAC,WAAW,CAAC;YACnD,cAAc,EAAE,gDAAgD;SACjE,CAAC,CAAC,EAAE,CAAC;QACN,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,MAAM,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAC/D,CAAC;CACF","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { isAbsolute, relative, sep } from \"node:path\";\nimport type { JsonObject } from \"./config.js\";\nimport type { LoadedContract } from \"./contract.js\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\nimport { findingsBaseUrl } from \"./findings-client.js\";\nimport type { FindingSearchScope } from \"./finding-retrieval.js\";\nimport {\n bundledPluginRoot,\n canonicalizeModelSafePath,\n codexSecurityStateDirectory,\n workbenchEnvironment,\n resolvePluginPython,\n runWorkbench,\n type WorkbenchCommandOptions,\n} from \"./runtime.js\";\n\nexport type WorkflowStage = \"scan\" | \"publish\" | \"dedupe\";\nexport interface WorkflowBinding {\n repositoryPath?: string;\n scanRequestDigest?: string;\n scanId?: string;\n scanDir?: string;\n artifactDigest?: string;\n destination?: string;\n scope?: FindingSearchScope;\n}\nexport interface WorkflowState extends WorkflowBinding {\n id: string;\n stages: Record<\n WorkflowStage,\n {\n status: \"pending\" | \"running\" | \"failed\" | \"completed\";\n result?: unknown;\n error?: string;\n pendingWrite?: DedupePendingWrite;\n }\n >;\n}\n\nexport interface DedupePendingWrite {\n groups: string[][];\n local?: { inputDigest: string; source: JsonObject; gitDisabled?: boolean };\n}\n\ninterface SourceSnapshotOptions {\n optional?: boolean;\n gitDisabled?: boolean;\n privateStatePaths?: readonly string[];\n evidence?: boolean;\n}\n\nexport function workflowDigest(value: unknown): string {\n const json = JSON.stringify(value, (_key, item: unknown) =>\n item !== null && typeof item === \"object\" && !Array.isArray(item)\n ? Object.fromEntries(\n Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n )\n : item,\n );\n return createHash(\"sha256\").update(json).digest(\"hex\");\n}\n\nexport function scanArtifactDigest({\n manifest,\n findings,\n review,\n}: Pick<LoadedContract, \"manifest\" | \"findings\" | \"review\">): string {\n return workflowDigest({ manifest, findings, review });\n}\n\nexport function workflowDestination(url: string): string {\n const destination = findingsBaseUrl(url);\n destination.username = \"\";\n destination.password = \"\";\n return destination.href;\n}\n\n/** State lives in the workbench database, never in sealed scan artifacts. */\nexport class FindingWorkflow {\n private options?: Promise<WorkbenchCommandOptions>;\n\n constructor(\n readonly id: string,\n private readonly environment: NodeJS.ProcessEnv = process.env,\n private readonly workbench: typeof runWorkbench = runWorkbench,\n private readonly pythonPath?: string,\n private readonly selection: {\n protectedRoot?: string;\n workbenchOptions?: WorkbenchCommandOptions;\n } = {},\n ) {\n if (!id.trim())\n throw new CodexSecurityError(\"workflowId must be a nonempty string.\");\n if (selection.workbenchOptions !== undefined)\n this.options = Promise.resolve(selection.workbenchOptions);\n }\n\n async protectArtifacts(scanDir: string): Promise<void> {\n const path = relative(\n await canonicalizeModelSafePath(scanDir),\n await canonicalizeModelSafePath(\n codexSecurityStateDirectory(this.environment),\n ),\n );\n if (\n path === \"\" ||\n (!isAbsolute(path) && path !== \"..\" && !path.startsWith(`..${sep}`))\n ) {\n throw new CodexSecurityError(\n \"Workflow state must be outside the sealed scan artifacts.\",\n );\n }\n }\n\n async get(): Promise<WorkflowState | null> {\n return (await this.command({ action: \"get\" })) as WorkflowState | null;\n }\n\n async bind(binding: WorkflowBinding): Promise<WorkflowState> {\n return (await this.command({ action: \"bind\", binding }))!;\n }\n\n async begin(stage: WorkflowStage): Promise<WorkflowState> {\n return (await this.command({ action: \"begin\", stage }))!;\n }\n\n async complete(\n stage: WorkflowStage,\n result: unknown,\n ): Promise<WorkflowState> {\n return (await this.command({ action: \"complete\", stage, result }))!;\n }\n\n async fail(\n stage: WorkflowStage,\n error: unknown,\n result?: unknown,\n ): Promise<void> {\n await this.command({\n action: \"fail\",\n stage,\n error: errorMessage(error),\n ...(result === undefined ? {} : { result }),\n }).catch(() => undefined);\n }\n\n async run<T>(stage: WorkflowStage, operation: () => Promise<T>): Promise<T> {\n const state = await this.begin(stage);\n if (state.stages[stage].status === \"completed\")\n return state.stages[stage].result as T;\n try {\n const result = await operation();\n await this.complete(stage, result);\n return result;\n } catch (error) {\n await this.fail(stage, error);\n throw error;\n }\n }\n\n async registeredScan(scanId: string): Promise<JsonObject> {\n const context = await this.call([\"get-scan\", \"--scan-id\", scanId]);\n return context[\"scan\"] as JsonObject;\n }\n\n async sourceSnapshot(\n repository: string,\n options?: SourceSnapshotOptions & { optional?: false },\n ): Promise<JsonObject>;\n async sourceSnapshot(\n repository: string,\n options: SourceSnapshotOptions & { optional: true },\n ): Promise<JsonObject | null>;\n async sourceSnapshot(\n repository: string,\n options: SourceSnapshotOptions = {},\n ): Promise<JsonObject | null> {\n return (\n await this.request({\n action: \"source\",\n repository,\n ...(options.optional ? { optional: true } : {}),\n ...(options.gitDisabled ? { gitDisabled: true } : {}),\n ...(options.evidence ? { evidence: true } : {}),\n ...(options.privateStatePaths?.length\n ? { privateStatePaths: options.privateStatePaths }\n : {}),\n })\n )[\"source\"] as JsonObject | null;\n }\n\n async getReview(key: string): Promise<unknown> {\n return (await this.request({ action: \"get-review\", key }))[\"review\"];\n }\n\n async saveReview(\n key: string,\n binding: object,\n result: unknown,\n options: { replace?: boolean } = {},\n ): Promise<void> {\n await this.request({\n action: \"save-review\",\n key,\n binding,\n result,\n ...(options.replace ? { replace: true } : {}),\n });\n }\n\n async prepareDedupe(\n result: unknown,\n pendingWrite: DedupePendingWrite,\n ): Promise<void> {\n await this.command({\n action: \"prepare-dedupe\",\n stage: \"dedupe\",\n result,\n pendingWrite,\n });\n }\n\n private async command(payload: object): Promise<WorkflowState | null> {\n const result = await this.request(payload);\n return result[\"workflow\"] as unknown as WorkflowState | null;\n }\n\n private async request(payload: object): Promise<JsonObject> {\n return await this.call(\n [\"finding-workflow\"],\n JSON.stringify({ id: this.id, ...payload }),\n );\n }\n\n private async call(\n args: readonly string[],\n input?: string,\n ): Promise<JsonObject> {\n this.options ??= (async () => ({\n pluginRoot: await bundledPluginRoot(),\n python: await resolvePluginPython({\n environment: this.environment,\n configuredPath: this.pythonPath,\n protectedRoot: this.selection.protectedRoot,\n }),\n environment: workbenchEnvironment(this.environment),\n failureMessage: \"Could not save or resume the findings workflow\",\n }))();\n return await this.workbench(await this.options, args, input);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"github-advisories.d.ts","sourceRoot":"","sources":["../src/github-advisories.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"github-advisories.d.ts","sourceRoot":"","sources":["../src/github-advisories.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAS7C,eAAO,MAAM,sBAAsB,YACjC,WAAW,EACX,OAAO,EACP,QAAQ,EACR,QAAQ,CACA,CAAC;AAEX,MAAM,WAAW,2BAA2B;IAC1C,kFAAkF;IAClF,UAAU,EAAE,MAAM,CAAC;IACnB,4DAA4D;IAC5D,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC,8EAA8E;IAC9E,MAAM,CAAC,EAAE,YAAY,GAAG,QAAQ,CAAC;IACjC,0EAA0E;IAC1E,KAAK,CAAC,EAAE,CAAC,OAAO,sBAAsB,CAAC,CAAC,MAAM,CAAC,CAAC;IAChD,yCAAyC;IACzC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gDAAgD;IAChD,WAAW,CAAC,EAAE,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAYrB;AAED,iBAAe,mBAAmB,CAChC,MAAM,EAAE,OAAO,EACf,EAAE,EAAE,MAAM,EACV,MAAM,CAAC,EAAE,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAOrB"}
|
|
@@ -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 =
|
|
17
|
-
if (!parts
|
|
17
|
+
const parts = githubRepositoryParts(repository);
|
|
18
|
+
if (!parts)
|
|
18
19
|
throw new CodexSecurityError("GitHub repository must be OWNER/REPO.");
|
|
19
|
-
const owner = parts
|
|
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) =>
|
|
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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AG;YAChB,MAAM,IAAI,kBAAkB,CAAC,+BAA+B,CAAC,CAAC;QAChE,IAAI,MAAM,KAAK,GAAG;YAChB,MAAM,IAAI,kBAAkB,CAC1B,oGAAoG,CACrG,CAAC;QACJ,IAAI,MAAM,KAAK,GAAG;YAChB,MAAM,IAAI,kBAAkB,CAC1B,4EAA4E,CAC7E,CAAC;QACJ,IAAI,MAAM,KAAK,GAAG;YAChB,MAAM,IAAI,kBAAkB,CAC1B,kDAAkD,CACnD,CAAC;QACJ,MAAM,IAAI,kBAAkB,CAC1B,0CAA0C,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,YAAY,CAAC,KAAK,CAAC,EAAE,CAC1H,CAAC;IACJ,CAAC;AACH,CAAC;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":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,MAAM,IAAI,kBAAkB,CAC1B,4EAA4E,CAC7E,CAAC;QACJ,IAAI,MAAM,KAAK,GAAG;YAChB,MAAM,IAAI,kBAAkB,CAC1B,kDAAkD,CACnD,CAAC;QACJ,MAAM,IAAI,kBAAkB,CAC1B,0CAA0C,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,YAAY,CAAC,KAAK,CAAC,EAAE,CAC1H,CAAC;IACJ,CAAC;AACH,CAAC;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 {\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
|