Skip to content

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

feat(github): import code scanning alerts and advisories (#1632)

Michael D'Angelo2181949a5cd7
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index f92a00fcb..5c7460c5d 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -1,6 +1,6 @@
---
name: publish-findings
-description: Import selected Snyk Open Source findings, Semgrep Code CLI/CI reports, Endor Labs findings, or Wiz package vulnerabilities, SAST, repository secrets, and IaC findings locally or to Codex Security Cloud after previewing the destination and evidence. Prefers native JSON; also supports Snyk plugin SCA bundles, Snyk Open Source and Semgrep Code SARIF, endorctl SARIF, Wiz normalized JSONL and repository package-vulnerability CSV, and gzip; does not import workload secrets or cloud configuration, run a scan, assess findings, or synchronize triage decisions.
+description: Import selected Snyk Open Source findings, Semgrep Code CLI/CI reports, Endor Labs findings, GitHub code-scanning alerts or GHSA advisories, or Wiz package vulnerabilities, SAST, repository secrets, and IaC findings locally or to Codex Security Cloud after previewing the destination and evidence. Prefers native JSON; also supports Snyk plugin SCA bundles, Snyk Open Source and Semgrep Code SARIF, endorctl SARIF, saved GitHub JSON/JSONL, Wiz normalized JSONL and repository package-vulnerability CSV, and gzip; does not import workload secrets or cloud configuration, run a scan, assess findings, or synchronize triage decisions.
---
# Publish external findings
@@ -84,6 +84,35 @@ Import the native report with `--provider semgrep`, a stable organization/projec
Keep supplied fingerprints. Reimporting the same fingerprint after code moves updates the existing source record with the new range. If the fingerprint is absent or `requires login`, the fallback uses rule, literal path and range: movement creates a second retained record, and the earlier record remains stored. Do not infer a merge or deletion. Read the persisted evidence with `codex-security findings imported /path/to/project --format json` before assessment. Source rule, CWE, snippets, traces and status are vendor evidence, not Codex assessments. Do not infer a report revision from the current checkout. Resolve scan errors and review all exclusions before uploading; do not remove error metadata to force acceptance.
+## GitHub alerts and advisories
+
+Acquire code-scanning findings with `codex-security import github OWNER/REPO --format json` and save its complete JSON output for local import or Cloud publication. This existing collector completes pagination, fetches alert details, and retains the selected ref's instance. In Codex, use the official [GitHub Codex plugin](https://github.com/openai/plugins/tree/main/plugins/github) for discovery and selecting alerts, then pass that selection to the collector. Its GitHub MCP server paginates each list call separately. Do not ask the user to download JSON from a website or reconstruct an import envelope from MCP summaries; raw MCP/API responses are not accepted by `--provider github`.
+
+The importer uses the user's GitHub CLI authentication and `GH_HOST`; plugin authentication is separate. It defaults to open alerts on the default branch. Use repeated `--github-alert NUMBER` for exact alerts or `--github-ref REF` for another ref. Save complete output without field/token filters or `--full-output`. Reading code-scanning alerts requires a token with Code scanning alerts read permission (classic: `security_events`, or `public_repo` for public repositories), along with repository access.
+
+**GHSA import stages advisory evidence for investigation; it does not establish an installed dependency or applicability to the destination repository.** Keep advisories separate from code scanning. `codex-security import github-advisories OWNER/REPO --format json` reads published repository disclosures by default. Repeated `--github-advisory GHSA-xxxx-xxxx-xxxx` selects exact IDs; `--github-state draft|triage|closed` explicitly selects an unpublished list and cannot be combined with exact IDs. Add `--github-advisory-source global` for exact public database IDs. This does not enumerate the global database. Private advisory access needs Repository security advisories read permission and access to those records. Stop on a read failure instead of publishing an incomplete selection.
+
+```sh
+codex-security import github example/project --format json > /path/to/alerts.json
+codex-security publish findings /path/to/alerts.json \
+ --to local --repository /path/to/project --provider github \
+ --source-key github.com/example/project/code-scanning --dry-run --format json
+codex-security publish findings /path/to/alerts.json \
+ --to cloud --repository https://github.com/example/project --provider github \
+ --source-key github.com/example/project/code-scanning --dry-run --format json
+
+codex-security import github-advisories example/project \
+ --github-advisory-source global --github-advisory GHSA-2345-6789-cfgh \
+ --format json > /path/to/advisories.json
+codex-security publish findings /path/to/advisories.json \
+ --to cloud --repository https://github.com/example/project --provider github \
+ --source-key github.com/example/project/security-advisories --dry-run --format json
+```
+
+Choose the local or Cloud preview for the intended destination. GHSA input supports the same choice: use `--to local --repository /path/to/project` with the advisory file and source key. Follow [local imports](#local-imports) for confirmation and readback or [Cloud publication](#review-and-publish-to-cloud) for upload review.
+
+Use separate stable source keys for the two families. Code-scanning identities include the ref; repository alerts and advisories must match the selected Cloud repository or, when available, a configured local Git remote. Global advisories omit source-repository provenance and are bound to the explicit local or Cloud destination for investigation. Preserve original evidence, package ranges and patches; do not infer installed packages or source locations from an advisory. Missing security severity stays `unknown`. Dismissal, resolution and withdrawal are source state, not Codex assessment. This path does not import Dependabot or secret-scanning alerts or write back to GitHub.
+
## Review and publish to Cloud
When publishing to staging or another Cloud deployment, set `CODEX_SECURITY_CLOUD_BASE_URL` to its API root before both preview and upload. If the Cloud page or user supplies its app URL, also set `CODEX_SECURITY_CLOUD_WEB_URL` to that full URL so the command can return a repository link. The UI setting does not change API routing or authentication. Use that deployment's login and an isolated state directory for tests. Verify `cloudApiUrl` and any `cloudUrl` in the preview against the intended deployment; the former is the API endpoint and the latter is the UI link. Saved retries are separated by deployment. The native scan setting `CODEX_SECURITY_CLOUD_PUBLISH_URL` does not route vendor imports. Never fall back to production when staging is unavailable.
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 4b8e1a6c1..fe20db296 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -674,6 +674,14 @@ repository package vulnerabilities (SCA) only; it does not add SAST, CSPM or
complete code-to-cloud coverage. Both formats support gzip. The acquisition path
still needs validation with an authorized Wiz tenant.
+For GitHub, save complete JSON from `import github` or `import github-advisories`;
+the configured GitHub plugin can help select alerts before collection. The
+[separate readers and mappings](docs/cli.md#import-github-findings-locally-or-to-cloud)
+retain code-scanning evidence or GHSA disclosures. **GHSA import does not
+establish an installed dependency or applicability to the repository.** This
+integration does not import Dependabot or secret-scanning alerts or write back
+to GitHub.
+
Use `publish findings FILE --to local --repository PATH --provider wiz
--source-key KEY` to store the same vendor evidence in the local workbench SQLite
database. Preview with `--dry-run --format json`, then confirm interactively or
@@ -688,6 +696,10 @@ Use `--provider endor` with native Endor Finding JSON; existing endorctl SARIF i
accepted as a lossy compatibility format. See
[Endor imports](docs/cli.md#import-endor-labs-findings).
+For saved GitHub code-scanning alerts or GHSA advisories, use
+`--provider github` with a separate stable source key for each finding family.
+See [local imports](docs/cli.md#import-vendor-findings-locally).
+
The SDK's `prepareLocalExternalImport(file, options)` returns a `preview` and a
separate `import()` operation. `prepareNormalizedLocalImport(findings,
options)` accepts already normalized evidence, and
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 6ae9ccf98..696681cd4 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1211,7 +1211,10 @@ evidence or deduplicate equivalent vulnerabilities across different source IDs.
Use the same vendor input and parser as Cloud publication, selecting a local
repository path instead of a Cloud repository ID or URL. Supported inputs include
-Wiz findings and [Snyk Open Source JSON and SARIF](#import-snyk-open-source-findings):
+Wiz findings, [Snyk Open Source JSON and SARIF](#import-snyk-open-source-findings),
+[Endor Labs Finding JSON and SARIF](#import-endor-labs-findings),
+[Semgrep Code JSON and SARIF](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md),
+and [saved GitHub alerts and GHSA advisories](#import-github-findings-locally-or-to-cloud):
```bash
codex-security publish findings selected-wiz.json \
@@ -2273,6 +2276,158 @@ record absolute Node/CLI paths. If those change, back up and remove the verified
generated hook, then reinstall with the same threshold. Restore the backup if
installation fails. The installer respects `core.hooksPath`.
+## Import GitHub findings locally or to Cloud
+
+Acquire code-scanning findings with the existing `import github` collector and
+save its complete JSON output. In Codex, the official
+[GitHub Codex plugin](https://github.com/openai/plugins/tree/main/plugins/github)
+can help select the repository, alert numbers and ref through GitHub's MCP
+server; pass that selection to the collector. This integration reads
+code-scanning alerts and GHSA advisories. It does not import Dependabot or
+secret-scanning alerts or write back to GitHub. Preview local storage with a
+repository path:
+
+```bash
+codex-security import github example/project --format json > /path/outside/repository/alerts.json
+codex-security publish findings /path/outside/repository/alerts.json \
+ --to local --provider github --repository ./project \
+ --source-key github.com/example/project/code-scanning --dry-run --format json
+```
+
+Or preview publication to a connected Cloud repository:
+
+```bash
+codex-security publish findings /path/outside/repository/alerts.json \
+ --to cloud --provider github --repository https://github.com/example/project \
+ --source-key github.com/example/project/code-scanning --dry-run --format json
+```
+
+The importer fetches every page, retrieves alert details, and retains the selected
+ref's instance. It writes the saved input for publication; no website download or
+hand-written JSON mapping is needed. Use `--github-alert NUMBER` repeatedly for
+selected alerts or `--github-ref REF` for another ref. Defaults are open alerts on
+the default branch. MCP list calls are paginated separately, and raw MCP/API
+responses are not the saved import format accepted by `--provider github`.
+
+The importer uses GitHub CLI authentication (`gh auth login`) and `GH_HOST`;
+the plugin's connection does not sign in `gh`. Reading alerts requires
+[code-scanning access](https://docs.github.com/en/rest/code-scanning/code-scanning#list-code-scanning-alerts-for-a-repository):
+**Code scanning alerts: read** for a fine-grained token, or `security_events` for
+a classic token (`public_repo` is sufficient for public repositories). The source
+repository must have code scanning available. For Cloud publication, the
+destination must be connected in the selected Cloud account. For local import,
+the source repository must match a configured Git remote when remotes are
+available; no Cloud login is required to store the acquired evidence.
+
+Review the destination, source, exclusions and evidence in the preview. Repeat the
+selected command without `--dry-run` and confirm it, or add `--yes` for a
+previously reviewed input. Local persistence and readback follow the
+[local import flow](#import-vendor-findings-locally); use
+`codex-security findings imported ./project --format json` to read the records.
+Cloud authentication, batching, saved receipts, partial results and
+interrupted-upload recovery follow the [publication flow](#import-wiz-findings).
+JSON, JSONL and gzip are supported. Save complete import output without field or
+token filters or `--full-output`.
+
+Use a stable source key for the GitHub host, repository and finding family.
+Code-scanning identities include the selected ref, so branches retain separate
+evidence. The original alert, rule, scanner, location, revision and source state
+remain attached. An alert-wide dismissal takes precedence over the selected
+instance's open/fixed state. Missing security severity stays `unknown`;
+SARIF error/warning/note levels are not vulnerability ratings. Imported evidence
+remains unassessed by Codex.
+
+The SDK offers the same preview and publication boundary for Cloud:
+
+```ts
+import {
+ importGitHubCodeScanningAlerts,
+ normalizeGitHubCodeScanningAlerts,
+ prepareNormalizedExternalPublication,
+} from "@openai/codex-security";
+
+const alerts = await importGitHubCodeScanningAlerts({
+ repository: "example/project",
+});
+const prepared = await prepareNormalizedExternalPublication(
+ normalizeGitHubCodeScanningAlerts(alerts),
+ {
+ provider: "github",
+ repository: "https://github.com/example/project",
+ sourceKey: "github.com/example/project/code-scanning",
+ },
+);
+console.log(prepared.preview);
+// After reviewing the preview:
+const receipt = await prepared.publish();
+```
+
+For local storage, pass the same normalized evidence to
+`prepareNormalizedLocalImport()` with `repository: "/path/to/project"`, inspect
+its preview, and call `import()`. `prepareLocalExternalImport()` accepts the saved
+import file directly. Read records with `listLocalExternalFindings({ repository })`.
+
+### Import GHSA advisories separately
+
+**Importing a GHSA advisory does not establish an installed dependency or
+applicability to the destination repository.** Repository advisories are
+disclosures maintained by a repository; global advisories describe affected
+software in GitHub's public advisory database. Both are evidence for
+investigation, not Dependabot alerts. Check the repository’s dependency versions
+and applicability separately.
+
+```bash
+# Read only published advisories for this repository.
+codex-security import github-advisories example/project --format json > /path/outside/repository/advisories.json
+
+# Select individual public database records without enumerating the database.
+codex-security import github-advisories example/project \
+ --github-advisory-source global --github-advisory GHSA-2345-6789-cfgh \
+ --format json > /path/outside/repository/advisories.json
+
+codex-security publish findings /path/outside/repository/advisories.json \
+ --to cloud --provider github --repository https://github.com/example/project \
+ --source-key github.com/example/project/security-advisories --dry-run --format json
+```
+
+For local storage, use the same advisory file, provider and source key with
+`--to local --repository ./project`. Follow the [local import flow](#import-vendor-findings-locally)
+to review, confirm and read the stored evidence.
+
+`--github-advisory-source` defaults to `repository`. Repeat `--github-advisory`
+to select exact IDs from that API, regardless of advisory state. Repository
+lists default to `--github-state published`; `draft`, `triage`, and `closed`
+require explicit selection. A nondefault state cannot be combined with exact
+IDs. Global selection requires at least one ID and never lists the advisory
+database. Both readers use `GH_HOST` and GitHub CLI authentication by default;
+the SDK also accepts `githubHost` and `githubToken`. Private or unpublished
+[repository advisories](https://docs.github.com/en/rest/security-advisories/repository-advisories#list-repository-security-advisories)
+require **Repository security advisories: read**, or the classic `repo` or
+`repository_advisories:read` scope, plus access to the advisory. Public records
+need no additional advisory permission.
+
+Review the saved evidence before local import or Cloud publication, including any
+selected private advisories. Acquisition failure returns no partial selection.
+Both destinations report invalid records as exclusions. Cloud publication retains
+acknowledged receipts if a later batch or readback fails.
+
+Advisory evidence retains GHSA/CVE IDs, affected version ranges, available
+patched versions, source status and original JSON. It does not infer an installed
+version or source location. Global advisories omit a source repository; the
+explicit local or Cloud destination binds the import for investigation. Repository
+advisories retain their source repository and check it against the Cloud target
+or configured local Git remotes when available. Withdrawal remains vendor
+state, and all imported evidence remains not assessed by Codex. Use a separate
+source key from code-scanning alerts; shared advisory IDs do not combine source
+records from different providers.
+
+In the SDK, call `importGitHubAdvisories()` and `normalizeGitHubAdvisories()`
+with `prepareNormalizedExternalPublication()` for Cloud or
+`prepareNormalizedLocalImport()` for local storage as described above.
+`importGitHubAdvisories()` defaults to `{ source: "repository", state: "published" }`; use
+`{ source: "global", advisoryIds: ["GHSA-2345-6789-cfgh"] }` for selected database
+records. Both forms require `repository: "OWNER/REPO"` as source or target context.
+
## Import alerts from the CLI
```bash
diff --git a/sdk/typescript/scripts/fixtures/package-consumer.ts b/sdk/typescript/scripts/fixtures/package-consumer.ts
index 8607de66d..01257f0ba 100644
--- a/sdk/typescript/scripts/fixtures/package-consumer.ts
+++ b/sdk/typescript/scripts/fixtures/package-consumer.ts
@@ -1,5 +1,9 @@
import {
CodexSecurity,
+ importGitHubCodeScanningAlerts,
+ importGitHubAdvisories,
+ normalizeGitHubAdvisories,
+ normalizeGitHubCodeScanningAlerts,
prepareExternalPublication,
prepareLocalExternalImport,
prepareNormalizedLocalImport,
@@ -306,6 +310,38 @@ export async function externalPublication(
return prepared.publish();
}
+export async function publishGitHubAlerts(): Promise<ExternalPublicationResult> {
+ const imported = await importGitHubCodeScanningAlerts({
+ repository: "example/project",
+ });
+ const prepared = await prepareNormalizedExternalPublication(
+ normalizeGitHubCodeScanningAlerts(imported),
+ {
+ provider: "github",
+ sourceKey: "github.com/example/project/code-scanning",
+ repository: "https://github.com/example/project",
+ },
+ );
+ return prepared.publish();
+}
+
+export async function publishGitHubAdvisories(): Promise<ExternalPublicationResult> {
+ const imported = await importGitHubAdvisories({
+ repository: "example/project",
+ source: "global",
+ advisoryIds: ["GHSA-2345-6789-cfgh"],
+ });
+ const prepared = await prepareNormalizedExternalPublication(
+ normalizeGitHubAdvisories(imported),
+ {
+ provider: "github",
+ sourceKey: "github.com/example/project/security-advisories",
+ repository: "https://github.com/example/project",
+ },
+ );
+ return prepared.publish();
+}
+
export async function publishNormalizedVendorEvidence(
input: ExternalFindings,
): Promise<ExternalPublicationResult> {
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 752f452a1..db85bf361 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -66,6 +66,8 @@ const distModules = [
"findings-import",
"git-remote",
"github",
+ "github-advisories",
+ "github-findings",
"host-records-protocol",
"index",
"import-scan",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 4026200ae..178262483 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -212,6 +212,10 @@ import {
ScanCostLimitExceededError,
ScanInterruptedError,
} from "./errors.js";
+import {
+ GITHUB_ADVISORY_STATES,
+ importGitHubAdvisories,
+} from "./github-advisories.js";
import {
GITHUB_ALERT_STATES,
importGitHubCodeScanningAlerts,
@@ -1244,6 +1248,7 @@ interface CliDependencies {
planComponents?: typeof planComponents;
linearClient?: LinearClientFactory;
importGitHubAlerts?: typeof importGitHubCodeScanningAlerts;
+ importGitHubAdvisories?: typeof importGitHubAdvisories;
importScan?: typeof importScan;
readSavedFindings?: typeof readSavedFindings;
runWorkbench(
@@ -3531,15 +3536,15 @@ export async function main(
});
publication.command("findings", {
description:
- "Preview and import selected Wiz, Snyk, Semgrep Code, or Endor findings locally or to Cloud.",
- hint: "For Snyk Open Source SCA vulnerabilities only, prefer native snyk test JSON or an official plugin snyk-findings-export/v1 bundle; Open Source SARIF 2.1.0 is also supported. Snyk licenses, Code, Container, IaC and platform backlogs are unsupported. For Semgrep Code, supply native JSON or SARIF and --source-repository-url. For Endor, supply native Finding JSON or endorctl SARIF 2.1.0. For Wiz, prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; Wiz CSV does not cover SAST or cloud posture. Other Wiz CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
+ "Preview and import selected Wiz, Snyk, Semgrep Code, Endor, or GitHub findings locally or to Cloud.",
+ hint: "For Snyk Open Source SCA vulnerabilities only, prefer native snyk test JSON or an official plugin snyk-findings-export/v1 bundle; Open Source SARIF 2.1.0 is also supported. Snyk licenses, Code, Container, IaC and platform backlogs are unsupported. For Semgrep Code, supply native JSON or SARIF and --source-repository-url. For Endor, supply native Finding JSON or endorctl SARIF 2.1.0. For GitHub, supply complete JSON/JSONL saved by import github or import github-advisories. GHSA advisories do not establish an installed dependency or applicability. For Wiz, prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; Wiz CSV does not cover SAST or cloud posture. Other Wiz CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
destructive: true,
mcp: false,
args: z.object({
file: z
.string()
.describe(
- "Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; Endor Finding JSON/endorctl SARIF; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV.",
+ "Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; Endor Finding JSON/endorctl SARIF; saved GitHub import output; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV.",
),
}),
options: z.object({
@@ -3548,8 +3553,8 @@ export async function main(
"Local repository path for --to local; authorized repository ID or URL for --to cloud.",
),
provider: z
- .enum(["wiz", "snyk", "semgrep", "endor"])
- .describe("Vendor that produced these findings."),
+ .enum(["wiz", "snyk", "semgrep", "endor", "github"])
+ .describe("Provider that produced these findings."),
sourceRepositoryUrl: optionValue("--source-repository-url")
.optional()
.describe(
@@ -3823,10 +3828,10 @@ export async function main(
},
});
const imports = Cli.create("import", {
- description: "Read GitHub code scanning alerts.",
+ description: "Read GitHub code scanning alerts and security advisories.",
}).command("github", {
description: "Read GitHub code scanning alerts without changing GitHub.",
- hint: "To save CSV or JSON findings as a local scan, use codex-security scan import --help.",
+ hint: "Save complete --format json output for publish findings --provider github. This command reads code-scanning alerts; Dependabot and secret-scanning alerts are not supported. To save CSV or JSON findings as a local scan, use codex-security scan import --help.",
destructive: false,
mcp: false,
args: z.object({
@@ -3904,6 +3909,101 @@ export async function main(
}
},
});
+ imports.command("github-advisories", {
+ description: "Read GitHub security advisories without changing GitHub.",
+ hint: "Defaults to published repository advisories. Use --github-advisory-source global with explicit --github-advisory IDs to select public database entries. Advisories do not establish an installed dependency or applicability to the selected repository.",
+ destructive: false,
+ mcp: false,
+ args: z.object({
+ repository: z
+ .string()
+ .min(1)
+ .describe(
+ "Source repository, or target context for global IDs, in OWNER/REPO form.",
+ ),
+ }),
+ options: z.object({
+ githubAdvisory: z
+ .array(
+ optionValue("--github-advisory").regex(
+ /^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/iu,
+ "GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form.",
+ ),
+ )
+ .default([])
+ .describe(
+ "Exact GHSA ID; repeat to select a subset. Required for global advisories.",
+ ),
+ githubAdvisorySource: z
+ .enum(["repository", "global"])
+ .default("repository")
+ .describe(
+ "Advisory API to read; global requires exact IDs and never lists the database.",
+ ),
+ githubState: z
+ .enum(GITHUB_ADVISORY_STATES)
+ .default("published")
+ .describe(
+ "Repository advisory list state; omit when selecting exact GHSA IDs.",
+ ),
+ }),
+ output: z
+ .array(
+ z.object({
+ source: z.literal("github-security-advisory"),
+ selection: z.enum(["repository", "global"]),
+ repository: z.string(),
+ githubHost: z.string(),
+ ghsaId: z.string(),
+ url: z.string(),
+ advisory: z.record(z.string(), z.unknown()),
+ }),
+ )
+ .optional(),
+ async run({ args, options, error: incurError }) {
+ const controller = new AbortController();
+ const removeSignals = listenForAbort(dependencies, controller);
+ try {
+ return await (
+ dependencies.importGitHubAdvisories ?? importGitHubAdvisories
+ )(
+ {
+ repository: args.repository,
+ advisoryIds: options.githubAdvisory,
+ source: options.githubAdvisorySource,
+ state: options.githubState,
+ signal: controller.signal,
+ },
+ {
+ environment: dependencies.environment,
+ currentDirectory: dependencies.currentDirectory(),
+ },
+ );
+ } catch (error) {
+ const signal = controller.signal.reason;
+ if (signal === "SIGINT" || signal === "SIGTERM") {
+ exitCode = signal === "SIGINT" ? 130 : 143;
+ errorOutput.write(
+ `codex-security: GitHub advisory import ${signal === "SIGINT" ? "canceled" : "terminated"}.\n`,
+ );
+ } else {
+ exitCode = 2;
+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
+ }
+ if (argv.includes("--full-output")) {
+ structuredError = true;
+ return incurError({
+ code: "GITHUB_IMPORT_FAILED",
+ message: diagnosticValue(error),
+ exitCode,
+ });
+ }
+ return undefined;
+ } finally {
+ removeSignals();
+ }
+ },
+ });
const infoOutput = z.object({
sdkVersion: z.string(),
bundledPluginVersion: z.string(),
diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.ts
index 5ae308d1d..00230860e 100644
--- a/sdk/typescript/src/external-findings-read.ts
+++ b/sdk/typescript/src/external-findings-read.ts
@@ -7,13 +7,14 @@ import { wizCsvRepositoryUrl } from "./wiz-csv.js";
import { readSnykFindings, snykRepositoryUrls } from "./snyk-findings.js";
import { readSemgrepFindings } from "./semgrep-findings.js";
import { readEndorFindings, endorRepositoryUrls } from "./endor-findings.js";
+import { readGitHubFindings } from "./github-findings.js";
import { isGitHubCloudHost } from "./git-remote.js";
import { isRecord } from "./record.js";
import { readVendorFindingsForPublication } from "./wiz-findings.js";
/** File readers available in this SDK, shared by local and Cloud imports. */
export interface ExternalFindingsReaderOptions {
- provider: "wiz" | "snyk" | "semgrep" | "endor";
+ provider: "wiz" | "snyk" | "semgrep" | "endor" | "github";
sourceRepositoryUrl?: string;
}
@@ -73,6 +74,8 @@ export async function readExternalFindings(
),
};
}
+ if (options.provider === "github")
+ return { findings: await readGitHubFindings(path) };
const publication = await readVendorFindingsForPublication(path);
// Raw package exports keep repository-branch URLs in retained source data.
const sourceRepositories = publication.current.findings.flatMap(
diff --git a/sdk/typescript/src/github-advisories.ts b/sdk/typescript/src/github-advisories.ts
new file mode 100644
index 000000000..403d5bd71
--- /dev/null
+++ b/sdk/typescript/src/github-advisories.ts
@@ -0,0 +1,218 @@
+import type { Octokit } from "@octokit/core";
+import { CodexSecurityError, errorMessage } from "./errors.js";
+import { createAuthenticatedGitHub } from "./github.js";
+
+export const GITHUB_ADVISORY_STATES = [
+ "published",
+ "draft",
+ "triage",
+ "closed",
+] as const;
+
+export interface GitHubAdvisoryImportOptions {
+ /** Source repository, or the selected target for explicit global advisory IDs. */
+ repository: string;
+ /** Exact GHSA IDs. Required for the global advisory API. */
+ advisoryIds?: readonly string[];
+ /** Repository advisories by default; global never enumerates the database. */
+ source?: "repository" | "global";
+ /** Repository list state (default: published). Exact IDs ignore state. */
+ state?: (typeof GITHUB_ADVISORY_STATES)[number];
+ /** Defaults to GH_HOST or github.com. */
+ githubHost?: string;
+ /** Omit to use the authenticated GitHub CLI. */
+ githubToken?: string;
+ signal?: AbortSignal;
+}
+
+type RepositoryAdvisory = Awaited<ReturnType<typeof fetchRepositoryAdvisory>>;
+type GlobalAdvisory = Awaited<ReturnType<typeof fetchGlobalAdvisory>>;
+
+export interface ImportedGitHubAdvisory {
+ source: "github-security-advisory";
+ selection: "repository" | "global";
+ repository: string;
+ githubHost: string;
+ ghsaId: string;
+ url: string;
+ /** Upstream disclosure, not proof that the selected repository is affected. */
+ advisory: RepositoryAdvisory | GlobalAdvisory;
+}
+
+interface GitHubAdvisoryImportDependencies {
+ environment?: NodeJS.ProcessEnv;
+ currentDirectory?: string;
+ createGitHub?: (host: string, signal?: AbortSignal) => Promise<Octokit>;
+}
+
+/** Read repository disclosures or explicitly selected public GHSA records. */
+export async function importGitHubAdvisories(
+ options: GitHubAdvisoryImportOptions,
+ dependencies: GitHubAdvisoryImportDependencies = {},
+): Promise<ImportedGitHubAdvisory[]> {
+ options.signal?.throwIfAborted();
+ const repository = options.repository.trim();
+ const parts = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(repository);
+ if (!parts || parts.slice(1).some((part) => /^\.{1,2}$/u.test(part)))
+ throw new CodexSecurityError("GitHub repository must be OWNER/REPO.");
+ const owner = parts[1]!;
+ const repo = parts[2]!;
+ const ids = [
+ ...new Set(
+ (options.advisoryIds ?? []).map((id) =>
+ id
+ .trim()
+ .toLowerCase()
+ .replace(/^ghsa-/u, "GHSA-"),
+ ),
+ ),
+ ];
+ if (ids.some((id) => !/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/u.test(id)))
+ throw new CodexSecurityError(
+ "GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form.",
+ );
+ const source = options.source ?? "repository";
+ const state = options.state ?? "published";
+ if (source !== "repository" && source !== "global")
+ throw new CodexSecurityError(
+ "GitHub advisory source must be repository or global.",
+ );
+ if (!GITHUB_ADVISORY_STATES.includes(state))
+ throw new CodexSecurityError("GitHub advisory state is invalid.");
+ if (source === "global" && ids.length === 0)
+ throw new CodexSecurityError(
+ "Select explicit GHSA IDs for global advisories; database-wide import is not supported.",
+ );
+ if (ids.length > 0 && state !== "published")
+ throw new CodexSecurityError(
+ "--github-state only filters repository lists; omit it when selecting exact GHSA IDs.",
+ );
+ const environment = dependencies.environment ?? process.env;
+ const host =
+ options.githubHost?.trim() ??
+ (environment["GH_HOST"]?.trim() || "github.com");
+ if (!host) throw new CodexSecurityError("GitHub host must not be empty.");
+
+ try {
+ const github = dependencies.createGitHub
+ ? await dependencies.createGitHub(host, options.signal)
+ : await createAuthenticatedGitHub(host, {
+ token: options.githubToken,
+ environment,
+ currentDirectory: dependencies.currentDirectory,
+ signal: options.signal,
+ });
+ const advisories: (RepositoryAdvisory | GlobalAdvisory)[] = [];
+ if (ids.length > 0) {
+ for (const id of ids) {
+ options.signal?.throwIfAborted();
+ advisories.push(
+ source === "global"
+ ? await fetchGlobalAdvisory(github, id, options.signal)
+ : await fetchRepositoryAdvisory(
+ github,
+ owner,
+ repo,
+ id,
+ options.signal,
+ ),
+ );
+ }
+ } else {
+ let after: string | undefined;
+ const cursors = new Set<string>();
+ do {
+ options.signal?.throwIfAborted();
+ const response = await github.request(
+ "GET /repos/{owner}/{repo}/security-advisories",
+ {
+ owner,
+ repo,
+ state,
+ per_page: 100,
+ after,
+ request: { signal: options.signal, redirect: "error" },
+ },
+ );
+ advisories.push(...response.data);
+ const next = response.headers.link
+ ?.split(",")
+ .find((link) => /;\s*rel="next"/u.test(link));
+ const nextUrl = next?.match(/<([^>]+)>/u)?.[1];
+ // Keep requests on the authenticated route; only carry over the cursor.
+ after = nextUrl
+ ? (new URL(nextUrl).searchParams.get("after") ?? undefined)
+ : undefined;
+ if (next && (!after || cursors.has(after)))
+ throw new CodexSecurityError(
+ "GitHub returned invalid advisory pagination.",
+ );
+ if (after) cursors.add(after);
+ } while (after !== undefined);
+ }
+ return advisories.map((advisory) => ({
+ source: "github-security-advisory",
+ selection: source,
+ repository,
+ githubHost: host,
+ ghsaId: advisory.ghsa_id,
+ url: advisory.html_url,
+ advisory,
+ }));
+ } catch (error) {
+ options.signal?.throwIfAborted();
+ if (error instanceof CodexSecurityError) throw error;
+ const status =
+ typeof error === "object" && error !== null && "status" in error
+ ? error.status
+ : undefined;
+ if (status === 401)
+ throw new CodexSecurityError("GitHub authentication failed.");
+ if (status === 403)
+ throw new CodexSecurityError(
+ "GitHub denied security advisory access. Check repository advisory permissions and API rate limits.",
+ );
+ if (status === 404)
+ throw new CodexSecurityError(
+ "GitHub repository or security advisory was not found or is not accessible.",
+ );
+ if (status === 429)
+ throw new CodexSecurityError(
+ "GitHub request was rate limited. Wait and retry.",
+ );
+ throw new CodexSecurityError(
+ `GitHub security advisory request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}: ${errorMessage(error)}`,
+ );
+ }
+}
+
+async function fetchRepositoryAdvisory(
+ github: Octokit,
+ owner: string,
+ repo: string,
+ id: string,
+ signal?: AbortSignal,
+) {
+ const response = await github.request(
+ "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}",
+ {
+ owner,
+ repo,
+ ghsa_id: id,
+ request: { signal, redirect: "error" },
+ },
+ );
+ return response.data;
+}
+
+async function fetchGlobalAdvisory(
+ github: Octokit,
+ id: string,
+ signal?: AbortSignal,
+) {
+ const response = await github.request("GET /advisories/{ghsa_id}", {
+ ghsa_id: id,
+ request: { signal, redirect: "error" },
+ });
+ return response.data;
+}
diff --git a/sdk/typescript/src/github-findings.ts b/sdk/typescript/src/github-findings.ts
new file mode 100644
index 000000000..91df1104c
--- /dev/null
+++ b/sdk/typescript/src/github-findings.ts
@@ -0,0 +1,313 @@
+import { hash } from "node:crypto";
+import { CodexSecurityError, errorMessage } from "./errors.js";
+import { validateExternalEvidence } from "./external-import-contract.js";
+import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
+import type { ImportedGitHubCodeScanningAlert } from "./github.js";
+import type { ImportedGitHubAdvisory } from "./github-advisories.js";
+import { parseJsonOrJsonl, readScannerText, text } from "./scanner-import.js";
+
+function object(value: unknown): Record<string, unknown> | undefined {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : undefined;
+}
+
+function repositoryName(value: unknown): string {
+ const repository = text(value);
+ const parts = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(repository ?? "");
+ if (!parts || parts.slice(1).some((part) => /^\.{1,2}$/u.test(part)))
+ throw new Error("GitHub repository must be OWNER/REPO.");
+ return repository!;
+}
+
+function sourceUrl(value: string): {
+ parsed: URL;
+ host: string;
+ origin: string;
+} {
+ const parsed = new URL(value);
+ const origin = /^(https?:\/\/([^/?#]+))/iu.exec(value);
+ if (!origin) throw new Error("GitHub evidence URL must be an HTTP(S) link.");
+ // URL.origin/host remove explicit default ports; Cloud keeps those distinct.
+ return { parsed, host: origin[2]!.toLowerCase(), origin: origin[1]! };
+}
+
+function sourceTimestamp(value: unknown): number | null {
+ if (value === undefined || value === null) return null;
+ const seconds = typeof value === "string" ? Date.parse(value) / 1000 : NaN;
+ if (!Number.isFinite(seconds) || seconds < 0)
+ throw new Error("GitHub updated_at is not a valid timestamp.");
+ return Math.floor(seconds);
+}
+
+function severity(value: unknown): string {
+ // SARIF error/warning/note are not vulnerability severity ratings.
+ return typeof value === "string" &&
+ ["critical", "high", "medium", "low", "informational"].includes(value)
+ ? value
+ : "unknown";
+}
+
+function codeScanningFinding(record: Record<string, unknown>): ExternalFinding {
+ const repository = repositoryName(record["repository"]);
+ const alert = object(record["alert"]);
+ const number = record["number"];
+ if (
+ !alert ||
+ typeof number !== "number" ||
+ !Number.isSafeInteger(number) ||
+ number < 1 ||
+ alert["number"] !== number
+ )
+ throw new Error(
+ "Expected a GitHub code-scanning import with matching alert numbers.",
+ );
+ const url = text(record["url"]);
+ if (!url || url !== alert["html_url"])
+ throw new Error("GitHub alert URL must match the original alert.");
+ const { parsed: parsedUrl, host, origin } = sourceUrl(url);
+ if (
+ !["security/code-scanning", "code-scanning"].some(
+ (route) =>
+ parsedUrl.pathname.toLowerCase() ===
+ `/${repository}/${route}/${number}`.toLowerCase(),
+ )
+ )
+ throw new Error(
+ "GitHub alert URL does not match the selected repository and alert.",
+ );
+ const rule = object(alert["rule"]);
+ const instance = object(alert["most_recent_instance"]);
+ const ref = text(instance?.["ref"]);
+ if (!ref)
+ throw new Error(
+ "GitHub code-scanning evidence requires the selected instance ref.",
+ );
+ const location = object(instance?.["location"]);
+ const tool = object(alert["tool"]);
+ const message = text(object(instance?.["message"])?.["text"]);
+ const description =
+ text(rule?.["full_description"]) ?? text(rule?.["description"]);
+ const tags = Array.isArray(rule?.["tags"]) ? rule["tags"] : [];
+ const weaknessIds = [
+ ...new Set(
+ tags.flatMap((tag: unknown) => {
+ const match =
+ typeof tag === "string"
+ ? /^external\/cwe\/cwe-(\d+)$/iu.exec(tag)
+ : null;
+ return match ? [`CWE-${Number(match[1])}`] : [];
+ }),
+ ),
+ ];
+ const path = text(location?.["path"]);
+ const sourceId = `${host}/${repository.toLowerCase()}/code-scanning/${number}/${hash("sha256", ref)}`;
+ return {
+ source_finding_id: sourceId,
+ evidence: validateExternalEvidence({
+ title:
+ text(rule?.["name"]) ??
+ text(rule?.["description"]) ??
+ `GitHub code-scanning alert #${number}`,
+ severity: severity(rule?.["security_severity_level"]),
+ description:
+ [...new Set([message, description].filter(Boolean))].join("\n\n") ||
+ null,
+ url,
+ locations: path ? [{ path, line: location?.["start_line"] ?? null }] : [],
+ branch: ref,
+ code_revision: text(instance?.["commit_sha"]),
+ source_updated_at: sourceTimestamp(alert["updated_at"]),
+ source_data: record,
+ details: {
+ kind: "sast",
+ repository: {
+ url: `${origin}/${repository}`,
+ name: repository,
+ },
+ // Dismissal covers every branch; detection state belongs to the selected ref.
+ source_status:
+ alert["state"] === "dismissed"
+ ? "dismissed"
+ : (text(instance?.["state"]) ?? text(alert["state"])),
+ scanner_origin: text(tool?.["name"]),
+ rule: { id: text(rule?.["id"]), name: text(rule?.["name"]) },
+ weakness_ids: weaknessIds,
+ remediation_instructions: text(rule?.["help"]),
+ code: path ? { end_line: location?.["end_line"] ?? null } : null,
+ },
+ }),
+ };
+}
+
+function advisoryFinding(record: Record<string, unknown>): ExternalFinding {
+ const repository = repositoryName(record["repository"]);
+ const advisory = object(record["advisory"]);
+ const id = text(record["ghsaId"]);
+ const selection = record["selection"];
+ if (
+ !advisory ||
+ !id ||
+ !/^GHSA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/iu.test(id) ||
+ text(advisory["ghsa_id"])?.toUpperCase() !== id.toUpperCase()
+ )
+ throw new Error(
+ "Expected a GitHub advisory import with matching GHSA IDs.",
+ );
+ if (selection !== "repository" && selection !== "global")
+ throw new Error("GitHub advisory selection must be repository or global.");
+ const url = text(record["url"]);
+ if (!url || url !== advisory["html_url"])
+ throw new Error("GitHub advisory URL must match the original advisory.");
+ const { parsed: parsedUrl, host: linkHost, origin } = sourceUrl(url);
+ const host = text(record["githubHost"])?.toLowerCase();
+ // Enterprise APIs may return the public advisory database's canonical link.
+ const canonicalGlobalLink =
+ selection === "global" && parsedUrl.host === "github.com";
+ const expectedPath =
+ selection === "repository"
+ ? `/${repository}/security/advisories/${id}`
+ : `/advisories/${id}`;
+ if (
+ !host ||
+ (linkHost !== host && !canonicalGlobalLink) ||
+ parsedUrl.pathname.toLowerCase() !== expectedPath.toLowerCase()
+ )
+ throw new Error(
+ "GitHub advisory URL does not match the selected source and GHSA ID.",
+ );
+ const vulnerabilities =
+ advisory["vulnerabilities"] === null ? [] : advisory["vulnerabilities"];
+ if (!Array.isArray(vulnerabilities))
+ throw new Error("GitHub advisory vulnerabilities must be an array.");
+ const identifiers = Array.isArray(advisory["identifiers"])
+ ? advisory["identifiers"]
+ : [];
+ const advisoryIds = [
+ id,
+ text(advisory["cve_id"]),
+ ...identifiers.map((identifier) => text(object(identifier)?.["value"])),
+ ].filter((value): value is string => value !== null);
+ const packages = vulnerabilities.flatMap((value) => {
+ const vulnerability = object(value);
+ const pkg = object(vulnerability?.["package"]);
+ const name = text(pkg?.["name"]);
+ // GitHub permits incomplete package metadata in advisory disclosures.
+ // Preserve it in source_data without inventing a typed package identity.
+ if (!name) return [];
+ const fixedVersion =
+ text(vulnerability?.["first_patched_version"]) ??
+ text(vulnerability?.["patched_versions"]);
+ return [
+ {
+ name,
+ ecosystem: text(pkg?.["ecosystem"]),
+ vulnerable_version_range: text(
+ vulnerability?.["vulnerable_version_range"],
+ ),
+ fixed_versions: fixedVersion ? [fixedVersion] : [],
+ },
+ ];
+ });
+ const cwes = Array.isArray(advisory["cwes"]) ? advisory["cwes"] : [];
+ return {
+ source_finding_id: `${host}/${selection === "repository" ? repository.toLowerCase() : "global"}/security-advisory/${id.toUpperCase()}`,
+ evidence: validateExternalEvidence({
+ title: text(advisory["summary"]) ?? id,
+ severity: severity(advisory["severity"]),
+ description: text(advisory["description"]),
+ url,
+ advisory_ids: [...new Set(advisoryIds)],
+ packages,
+ source_updated_at: sourceTimestamp(advisory["updated_at"]),
+ source_data: record,
+ details: {
+ kind: "advisory",
+ advisory: { source: selection },
+ ...(selection === "repository"
+ ? {
+ repository: {
+ url: `${origin}/${repository}`,
+ name: repository,
+ },
+ }
+ : {}),
+ source_status: text(advisory["withdrawn_at"])
+ ? "withdrawn"
+ : (text(advisory["state"]) ??
+ (selection === "global" ? "published" : null)),
+ scanner_origin: "GitHub Security Advisories",
+ weakness_ids: cwes
+ .map((value) => text(object(value)?.["cwe_id"]))
+ .filter((value): value is string => value !== null),
+ },
+ }),
+ };
+}
+
+function normalizeRecords(records: readonly unknown[]): ExternalFindings {
+ const result: ExternalFindings = {
+ read: records.length,
+ findings: [],
+ excluded: [],
+ };
+ const identities = new Set<string>();
+ for (const [index, value] of records.entries()) {
+ const record = object(value);
+ try {
+ if (!record) throw new Error("GitHub finding must be an object.");
+ let finding: ExternalFinding;
+ if (record["source"] === "github-code-scanning")
+ finding = codeScanningFinding(record);
+ else if (record["source"] === "github-security-advisory")
+ finding = advisoryFinding(record);
+ else
+ throw new Error(
+ "Expected saved output from import github or import github-advisories; raw or incomplete API responses need an explicit mapping.",
+ );
+ if (identities.has(finding.source_finding_id))
+ throw new CodexSecurityError(
+ `Duplicate source finding id ${JSON.stringify(finding.source_finding_id)}. Select each GitHub occurrence once.`,
+ );
+ identities.add(finding.source_finding_id);
+ result.findings.push(finding);
+ } catch (error) {
+ if (error instanceof CodexSecurityError) throw error;
+ result.excluded.push({
+ position: index + 1,
+ source_finding_id: text(record?.["url"]),
+ reason: errorMessage(error),
+ });
+ }
+ }
+ return result;
+}
+
+/** Map selected code-scanning instances while retaining complete upstream evidence. */
+export function normalizeGitHubCodeScanningAlerts(
+ alerts: readonly ImportedGitHubCodeScanningAlert[],
+): ExternalFindings {
+ return normalizeRecords(alerts);
+}
+
+/** Map advisory disclosures without asserting an installed vulnerable dependency. */
+export function normalizeGitHubAdvisories(
+ advisories: readonly ImportedGitHubAdvisory[],
+): ExternalFindings {
+ return normalizeRecords(advisories);
+}
+
+/** Read unfiltered JSON/JSONL output saved by the read-only GitHub import commands. */
+export async function readGitHubFindings(
+ path: string,
+): Promise<ExternalFindings> {
+ try {
+ const payload = parseJsonOrJsonl(await readScannerText(path));
+ return normalizeRecords(Array.isArray(payload) ? payload : [payload]);
+ } catch (cause) {
+ throw new CodexSecurityError(
+ `Could not read GitHub findings as UTF-8 JSON or JSONL: ${errorMessage(cause)}`,
+ { cause },
+ );
+ }
+}
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 3aa812715..f25caa59f 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -240,6 +240,16 @@ export type {
ImportRepository,
SourceReport,
} from "./external-import-models.js";
+export {
+ normalizeGitHubCodeScanningAlerts,
+ normalizeGitHubAdvisories,
+ readGitHubFindings,
+} from "./github-findings.js";
+export { importGitHubAdvisories } from "./github-advisories.js";
+export type {
+ GitHubAdvisoryImportOptions,
+ ImportedGitHubAdvisory,
+} from "./github-advisories.js";
export { importGitHubCodeScanningAlerts } from "./github.js";
export type {
GitHubCodeScanningImportOptions,
diff --git a/sdk/typescript/tests-ts/cli-fixtures.ts b/sdk/typescript/tests-ts/cli-fixtures.ts
index 088d3c0e6..4c6c2023c 100644
--- a/sdk/typescript/tests-ts/cli-fixtures.ts
+++ b/sdk/typescript/tests-ts/cli-fixtures.ts
@@ -211,6 +211,7 @@ export function dependencies(
onCodex?: OnCodex;
linearClient?: MainDependencies["linearClient"];
importGitHubAlerts?: MainDependencies["importGitHubAlerts"];
+ importGitHubAdvisories?: MainDependencies["importGitHubAdvisories"];
onRepositoryCommand?: (
...arguments_: Parameters<MainDependencies["runRepositoryCommand"]>
) => string | Promise<string>;
@@ -291,6 +292,9 @@ export function dependencies(
...(options.linearClient === undefined
? {}
: { linearClient: options.linearClient }),
+ ...(options.importGitHubAdvisories === undefined
+ ? {}
+ : { importGitHubAdvisories: options.importGitHubAdvisories }),
...(options.importGitHubAlerts === undefined
? {}
: { importGitHubAlerts: options.importGitHubAlerts }),
diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.ts
index 7c93670df..63233bbe5 100644
--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts
@@ -23,6 +23,7 @@ import {
prepareNormalizedExternalPublication,
type ExternalPublicationProgress,
} from "../src/external-findings-publish.js";
+import { readGitHubFindings } from "../src/github-findings.js";
import { readVendorFindings } from "../src/wiz-findings.js";
import {
validateExternalEvidence,
@@ -36,6 +37,10 @@ import type {
} from "../src/external-import-models.js";
import { main } from "../src/cli.js";
import { dependencies } from "./cli-fixtures.js";
+import {
+ importedAlert,
+ importedAdvisory,
+} from "./support/github-import-fixtures.js";
import { createCliTest } from "./support/cli-run.js";
const cleanups: (() => Promise<void>)[] = [];
@@ -2603,6 +2608,137 @@ test("normalized SDK publication preserves caller evidence and exclusion account
expect(result.verified).toBe(1);
});
+test("GitHub publication previews, imports, re-imports, updates and resumes selected-ref evidence", async () => {
+ const imported = importedAlert();
+ const f = await fixture([imported]);
+ const githubOptions = {
+ ...options,
+ provider: "github" as const,
+ sourceKey: "github.com/example/project/code-scanning",
+ };
+ const command = f.command.map((arg) =>
+ arg === "wiz"
+ ? "github"
+ : arg === options.sourceKey
+ ? githubOptions.sourceKey
+ : arg,
+ );
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli([...command, "--dry-run", "--format", "json"], f.cliDeps),
+ ).toBe(0);
+ expect(f.posts).toHaveLength(0);
+ expect(JSON.parse(cli.stdout.text()).source.provider).toBe("github");
+ const first = await (
+ await prepareExternalPublication(f.file, githubOptions, f.deps)
+ ).publish();
+ expect(first.counts.created).toBe(1);
+ expect(first.verified).toBe(1);
+ const repeated = await (
+ await prepareExternalPublication(f.file, githubOptions, f.deps)
+ ).publish();
+ expect(repeated.counts.unchanged).toBe(1);
+ imported.alert.most_recent_instance.state = "fixed";
+ await writeFile(f.file, JSON.stringify([imported]));
+ f.state.loseResponse = true;
+ await expect(
+ (await prepareExternalPublication(f.file, githubOptions, f.deps)).publish(),
+ ).rejects.toBeInstanceOf(ExternalPublicationError);
+ const prepared = await prepareExternalPublication(
+ f.file,
+ githubOptions,
+ f.deps,
+ );
+ expect(prepared.preview.resumed).toBe(true);
+ const resumed = await prepared.publish();
+ expect(resumed.counts.updated).toBe(1);
+ expect(resumed.verified).toBe(1);
+ expect([...f.reports.values()][0]).toMatchObject({
+ source: { provider: "github" },
+ evidence: { details: { source_status: "fixed" }, source_data: imported },
+ assessment: { state: "not_assessed" },
+ });
+ await writeFile(f.file, JSON.stringify([importedAlert("refs/heads/review")]));
+ const differentRef = await (
+ await prepareExternalPublication(f.file, githubOptions, f.deps)
+ ).publish();
+ expect(differentRef.counts.created).toBe(1);
+ expect(f.reports.size).toBe(2);
+});
+
+test("GitHub imports reject a different Cloud destination before uploading", async () => {
+ const imported = importedAlert("refs/heads/main", "git.example.test");
+ const f = await fixture([imported]);
+ await expect(
+ prepareExternalPublication(
+ f.file,
+ { ...options, provider: "github" },
+ f.deps,
+ ),
+ ).rejects.toThrow("does not match the selected Cloud repository");
+ expect(f.posts).toHaveLength(0);
+});
+
+test("global GHSA publication retains unassessed applicability through repeat import and withdrawal", async () => {
+ const imported = importedAdvisory("global");
+ const f = await fixture([imported]);
+ const selected = {
+ ...options,
+ provider: "github" as const,
+ sourceKey: "github.com/example/project/security-advisories",
+ };
+ expect(
+ (
+ await (
+ await prepareExternalPublication(f.file, selected, f.deps)
+ ).publish()
+ ).counts.created,
+ ).toBe(1);
+ expect(
+ (
+ await (
+ await prepareExternalPublication(f.file, selected, f.deps)
+ ).publish()
+ ).counts.unchanged,
+ ).toBe(1);
+ const withdrawn = {
+ ...imported,
+ advisory: { ...imported.advisory, withdrawn_at: "2026-01-03T00:00:00Z" },
+ };
+ await writeFile(f.file, JSON.stringify([withdrawn]));
+ const result = await (
+ await prepareExternalPublication(f.file, selected, f.deps)
+ ).publish();
+ expect(result.counts.updated).toBe(1);
+ expect(result.verified).toBe(1);
+ const report = [...f.reports.values()][0]!;
+ expect(report.evidence.details).toMatchObject({
+ kind: "advisory",
+ advisory: { source: "global" },
+ source_status: "withdrawn",
+ });
+ expect(report.evidence.details).not.toHaveProperty("repository");
+ expect(report.assessment?.state).toBe("not_assessed");
+ expect(report.evidence.packages![0]!.installed_version).toBeNull();
+});
+
+test("saved GitHub JSONL and gzip preserve evidence while malformed UTF-8 cannot change identities", async () => {
+ const imported = [importedAlert(), importedAdvisory("global")];
+ const f = await fixture(imported);
+ const jsonl = imported.map((record) => JSON.stringify(record)).join("\n");
+ for (const bytes of [Buffer.from(jsonl), gzipSync(jsonl)]) {
+ await writeFile(f.file, bytes);
+ const parsed = await readGitHubFindings(f.file);
+ expect(parsed.read).toBe(2);
+ expect(parsed.excluded).toEqual([]);
+ expect(
+ parsed.findings.map((finding) => finding.evidence.source_data) as unknown,
+ ).toEqual(imported);
+ }
+ await writeFile(f.file, Buffer.from([0xff]));
+ await expect(readGitHubFindings(f.file)).rejects.toThrow("UTF-8");
+});
+
test("normalized publication omits only new null fields to match canonical Cloud readback", async () => {
const f = await fixture();
const evidence = {
@@ -2709,6 +2845,42 @@ test("normalized SDK publication detaches raw evidence aliases before validating
expect(prepared.preview.findings).toEqual(fromFile.preview.findings);
});
+test.each(["code-scanning", "advisory"])(
+ "%s imports bind an explicit default port to the matching Cloud repository",
+ async (family) => {
+ const alert = importedAlert("refs/heads/main", "github.com:443");
+ const advisory = importedAdvisory();
+ advisory.githubHost = "github.com:443";
+ advisory.url = advisory.advisory.html_url = advisory.url.replace(
+ "github.com",
+ advisory.githubHost,
+ );
+ const f = await fixture([family === "code-scanning" ? alert : advisory]);
+ const selected = { ...options, provider: "github" as const };
+ await expect(
+ prepareExternalPublication(f.file, selected, f.deps),
+ ).rejects.toThrow("does not match the selected Cloud repository");
+ expect(f.posts).toHaveLength(0);
+ const matching = {
+ ...f.deps,
+ fetch: async (url: string, init: RequestInit) => {
+ const response = await f.deps.fetch(url, init);
+ if (new URL(url).pathname.endsWith("/repositories")) {
+ const body = await response.json();
+ body.data[0].url = "https://github.com:443/example/project";
+ return Response.json(body);
+ }
+ return response;
+ },
+ };
+ const result = await (
+ await prepareExternalPublication(f.file, selected, matching)
+ ).publish();
+ expect(result.counts.created).toBe(1);
+ expect(result.verified).toBe(1);
+ },
+);
+
test("normalized SDK publication rejects nonfinite raw evidence without JSON coercion", async () => {
const f = await fixture();
const input = {
diff --git a/sdk/typescript/tests-ts/github-advisories.test.ts b/sdk/typescript/tests-ts/github-advisories.test.ts
new file mode 100644
index 000000000..5f7030d15
--- /dev/null
+++ b/sdk/typescript/tests-ts/github-advisories.test.ts
@@ -0,0 +1,258 @@
+import { Octokit } from "@octokit/core";
+import { expect, mock, test } from "bun:test";
+import {
+ importGitHubAdvisories,
+ type GitHubAdvisoryImportOptions,
+} from "../src/github-advisories.js";
+import { main } from "../src/cli.js";
+import { dependencies, FakeSignals } from "./cli-fixtures.js";
+import { captureCli, runCapturedCli } from "./support/cli-run.js";
+import { importedAdvisory } from "./support/github-import-fixtures.js";
+
+function client(respond: (url: URL) => Response): Octokit {
+ return new Octokit({
+ auth: "SYNTHETIC_ADVISORY_TOKEN",
+ request: {
+ fetch: async (
+ resource: Parameters<typeof fetch>[0],
+ init?: Parameters<typeof fetch>[1],
+ ) => {
+ expect(init?.method).toBe("GET");
+ expect(init?.redirect).toBe("error");
+ return respond(
+ new URL(resource instanceof Request ? resource.url : resource),
+ );
+ },
+ },
+ });
+}
+
+test("repository advisory lists default to published and paginate cursors with full evidence", async () => {
+ const paths: string[] = [];
+ const github = client((url) => {
+ paths.push(url.toString());
+ expect(url.pathname).toBe("/repos/example/project/security-advisories");
+ expect(url.searchParams.get("state")).toBe("published");
+ expect(url.searchParams.get("per_page")).toBe("100");
+ return Response.json(
+ [importedAdvisory().advisory],
+ url.searchParams.has("after")
+ ? undefined
+ : {
+ headers: {
+ link: '<https://api.github.com/repos/example/project/security-advisories?after=cursor-2>; rel="next"',
+ },
+ },
+ );
+ });
+ const imported = await importGitHubAdvisories(
+ { repository: "example/project" },
+ { createGitHub: async () => github },
+ );
+ expect(paths).toHaveLength(2);
+ expect(new URL(paths[1]!).searchParams.get("after")).toBe("cursor-2");
+ expect(imported[0]).toEqual(importedAdvisory());
+ expect(JSON.stringify(imported)).not.toContain("SYNTHETIC_ADVISORY_TOKEN");
+});
+
+test("global advisory selection uses only explicit deduplicated IDs and preserves the source family", async () => {
+ const selected = importedAdvisory("global");
+ const paths: string[] = [];
+ const github = client((url) => {
+ paths.push(url.pathname);
+ return Response.json(selected.advisory);
+ });
+ const imported = await importGitHubAdvisories(
+ {
+ repository: "example/project",
+ source: "global",
+ advisoryIds: [selected.ghsaId.toLowerCase(), selected.ghsaId],
+ },
+ { createGitHub: async () => github },
+ );
+ expect(paths).toEqual([`/advisories/${selected.ghsaId}`]);
+ expect(imported).toEqual([selected]);
+});
+
+test("explicit repository IDs allow private drafts without listing other advisories", async () => {
+ const selected = importedAdvisory();
+ const draft = { ...selected.advisory, state: "draft" as const };
+ const github = client((url) => {
+ expect(url.pathname).toBe(
+ `/repos/example/project/security-advisories/${selected.ghsaId}`,
+ );
+ expect(url.searchParams.has("state")).toBe(false);
+ return Response.json(draft);
+ });
+ const imported = await importGitHubAdvisories(
+ { repository: "example/project", advisoryIds: [selected.ghsaId] },
+ { createGitHub: async () => github },
+ );
+ expect(imported[0]!.advisory).toEqual(draft);
+});
+
+test("global crawl and misleading exact-ID state filters fail before GitHub authentication", async () => {
+ const createGitHub = mock(async () => client(() => Response.json([])));
+ await expect(
+ importGitHubAdvisories(
+ { repository: "example/project", source: "global" },
+ { createGitHub },
+ ),
+ ).rejects.toThrow("explicit GHSA IDs");
+ await expect(
+ importGitHubAdvisories(
+ {
+ repository: "example/project",
+ advisoryIds: [importedAdvisory().ghsaId],
+ state: "draft",
+ },
+ { createGitHub },
+ ),
+ ).rejects.toThrow("only filters repository lists");
+ expect(createGitHub).not.toHaveBeenCalled();
+});
+
+test("a later advisory page failure returns no incomplete selection", async () => {
+ const github = client((url) =>
+ url.searchParams.has("after")
+ ? Response.json({ message: "Rate limit" }, { status: 429 })
+ : Response.json([importedAdvisory().advisory], {
+ headers: {
+ link: '<https://api.github.com/repos/example/project/security-advisories?after=next>; rel="next"',
+ },
+ }),
+ );
+ await expect(
+ importGitHubAdvisories(
+ { repository: "example/project" },
+ { createGitHub: async () => github },
+ ),
+ ).rejects.toThrow("rate limited");
+});
+
+test("GitHub advisory CLI exposes separate selection defaults and exact public IDs", async () => {
+ let options: GitHubAdvisoryImportOptions | undefined;
+ const output = captureCli(main, "stdout");
+ expect(
+ await output.run(
+ [
+ "import",
+ "github-advisories",
+ "example/project",
+ "--github-advisory",
+ importedAdvisory().ghsaId,
+ "--github-advisory-source",
+ "global",
+ "--format",
+ "json",
+ ],
+ dependencies({
+ importGitHubAdvisories: async (value) => {
+ options = value;
+ return [importedAdvisory("global")];
+ },
+ }),
+ ),
+ ).toBe(0);
+ expect(options).toMatchObject({
+ repository: "example/project",
+ source: "global",
+ state: "published",
+ advisoryIds: [importedAdvisory().ghsaId],
+ });
+ expect(JSON.parse(output.text())).toEqual([importedAdvisory("global")]);
+ const schema = captureCli(main, "stdout");
+ expect(
+ await schema.run(
+ ["import", "github-advisories", "--schema", "--format", "json"],
+ dependencies(),
+ ),
+ ).toBe(0);
+ expect(JSON.parse(schema.text())).toMatchObject({
+ options: {
+ properties: {
+ githubAdvisorySource: { default: "repository" },
+ githubState: { default: "published" },
+ },
+ },
+ });
+});
+
+test("advisory CLI cancellation removes handlers and preserves its exit code", async () => {
+ const signals = new FakeSignals();
+ expect(
+ await runCapturedCli(
+ main,
+ ["import", "github-advisories", "example/project"],
+ dependencies({
+ signals,
+ importGitHubAdvisories: async ({ signal }) => {
+ signals.emit("SIGINT");
+ signal!.throwIfAborted();
+ return [];
+ },
+ }),
+ ),
+ ).toBe(130);
+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);
+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);
+});
+
+for (const format of [
+ "json",
+ "jsonl",
+ "toon",
+ "yaml",
+ "md",
+ undefined,
+] as const) {
+ test.each([
+ ["error", 2],
+ ["SIGINT", 130],
+ ["SIGTERM", 143],
+ ] as const)(
+ `advisory CLI ${format} full output reports %s as failure`,
+ async (failure, code) => {
+ const signals = new FakeSignals();
+ const output = captureCli(main, "stdout");
+ expect(
+ await output.run(
+ [
+ "import",
+ "github-advisories",
+ "example/project",
+ ...(format === undefined ? [] : ["--format", format]),
+ "--full-output",
+ ],
+ dependencies({
+ signals,
+ importGitHubAdvisories: async ({ signal }) => {
+ if (failure === "error")
+ throw new Error("advisory request failed");
+ signals.emit(failure);
+ signal!.throwIfAborted();
+ return [];
+ },
+ }),
+ ),
+ ).toBe(code);
+ if (format === "json" || format === "jsonl") {
+ expect(JSON.parse(output.text())).toMatchObject({
+ ok: false,
+ error: {
+ code: "GITHUB_IMPORT_FAILED",
+ message: failure === "error" ? "advisory request failed" : failure,
+ },
+ });
+ } else {
+ expect(output.text()).toMatch(/(?:^ok:\s*|^## ok\s+)false/m);
+ expect(output.text()).toContain("GITHUB_IMPORT_FAILED");
+ expect(output.text()).toContain(
+ failure === "error" ? "advisory request failed" : failure,
+ );
+ }
+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);
+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);
+ },
+ );
+}
diff --git a/sdk/typescript/tests-ts/github-findings-local.test.ts b/sdk/typescript/tests-ts/github-findings-local.test.ts
new file mode 100644
index 000000000..ef691bcba
--- /dev/null
+++ b/sdk/typescript/tests-ts/github-findings-local.test.ts
@@ -0,0 +1,191 @@
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { afterEach, expect, test } from "bun:test";
+import { prepareLocalExternalImport } from "../src/external-findings-import.js";
+import { listLocalExternalFindings } from "../src/external-findings-local.js";
+import { localFindingsFixture } from "./external-findings-local-helpers.js";
+import {
+ importedAlert,
+ importedAdvisory,
+} from "./support/github-import-fixtures.js";
+
+const fixtures: Awaited<ReturnType<typeof localFindingsFixture>>[] = [];
+afterEach(async () => {
+ for (const fixture of fixtures.splice(0)) await fixture.dispose();
+});
+
+type Source = "code-scanning" | "repository-advisory" | "global-advisory";
+
+function githubSource(source: Source) {
+ return source === "code-scanning"
+ ? importedAlert()
+ : importedAdvisory(source === "global-advisory" ? "global" : "repository");
+}
+
+test.each(["code-scanning", "repository-advisory", "global-advisory"] as const)(
+ "GitHub %s imports into local storage and updates source evidence without assessing it",
+ async (kind) => {
+ const fixture = await localFindingsFixture({
+ remote: "https://github.com/example/project",
+ });
+ fixtures.push(fixture);
+ const source = githubSource(kind);
+ const file = join(fixture.root, "github.json");
+ await writeFile(file, JSON.stringify([source]));
+ const options = {
+ repository: fixture.repository,
+ provider: "github" as const,
+ sourceKey: "github/example/project",
+ };
+ const dependencies = { environment: fixture.environment };
+ const prepare = () =>
+ prepareLocalExternalImport(file, options, dependencies);
+ const read = () => listLocalExternalFindings(options, dependencies);
+
+ const prepared = await prepare();
+ expect(prepared.preview.excluded).toEqual([]);
+ expect(await read()).toEqual([]);
+ expect((await prepared.import()).counts).toEqual({
+ created: 1,
+ updated: 0,
+ unchanged: 0,
+ });
+ const stored = await read();
+ expect(stored).toHaveLength(1);
+ const initial = stored[0]!;
+ expect(initial).toMatchObject({
+ repository: fixture.repository,
+ provider: "github",
+ sourceKey: options.sourceKey,
+ assessment: { state: "not_assessed" },
+ version: 1,
+ evidence: { source_data: source },
+ });
+ if (kind !== "code-scanning") {
+ expect(initial.evidence.locations).toEqual([]);
+ expect(initial.evidence.packages?.[0]).toMatchObject({
+ installed_version: null,
+ manifest_path: null,
+ });
+ }
+ if (kind === "global-advisory")
+ expect(initial.evidence.details).not.toHaveProperty("repository");
+ expect(initial.evidence).not.toHaveProperty("confidence");
+ expect(initial.evidence).not.toHaveProperty("assessment");
+
+ expect((await (await prepare()).import()).counts).toEqual({
+ created: 0,
+ updated: 0,
+ unchanged: 1,
+ });
+ expect(await read()).toEqual(stored);
+
+ if (source.source === "github-code-scanning") {
+ source.alert.most_recent_instance.state = "fixed";
+ source.alert.most_recent_instance.commit_sha = "b".repeat(40);
+ delete source.alert.rule.security_severity_level;
+ } else {
+ source.advisory.withdrawn_at = "2026-01-03T00:00:00Z";
+ source.advisory.severity = null;
+ }
+ await writeFile(file, JSON.stringify([source]));
+ expect((await (await prepare()).import()).counts).toEqual({
+ created: 0,
+ updated: 1,
+ unchanged: 0,
+ });
+ const updated = await read();
+ expect(updated).toHaveLength(1);
+ expect(updated[0]).toMatchObject({
+ id: initial.id,
+ sourceFindingId: initial.sourceFindingId,
+ createdAt: initial.createdAt,
+ version: 2,
+ assessment: { state: "not_assessed" },
+ evidence: {
+ severity: "unknown",
+ source_data: source,
+ details: {
+ source_status: kind === "code-scanning" ? "fixed" : "withdrawn",
+ },
+ },
+ });
+ },
+);
+
+test.each(["code-scanning", "repository-advisory"] as const)(
+ "GitHub %s refuses to attach another repository's evidence locally",
+ async (kind) => {
+ const fixture = await localFindingsFixture({
+ remote: "https://github.com/example/other",
+ });
+ fixtures.push(fixture);
+ const file = join(fixture.root, "github.json");
+ await writeFile(file, JSON.stringify([githubSource(kind)]));
+ await expect(
+ prepareLocalExternalImport(
+ file,
+ {
+ repository: fixture.repository,
+ provider: "github",
+ sourceKey: "github/example/project",
+ },
+ { environment: fixture.environment },
+ ),
+ ).rejects.toThrow(/repository/iu);
+ expect(
+ await listLocalExternalFindings(
+ { repository: fixture.repository },
+ { environment: fixture.environment },
+ ),
+ ).toEqual([]);
+ },
+);
+
+test.each(["code-scanning", "repository-advisory"] as const)(
+ "GitHub %s matches custom Enterprise repository names without changing source evidence",
+ async (kind) => {
+ const fixture = await localFindingsFixture({
+ remote: "[email protected]:example/project.git",
+ });
+ fixtures.push(fixture);
+ const source =
+ kind === "code-scanning"
+ ? importedAlert("refs/heads/main", "git.example.test")
+ : importedAdvisory();
+ source.repository = "Example/Project";
+ if (source.source === "github-security-advisory") {
+ source.githubHost = "git.example.test";
+ source.url = source.url.replace("github.com", "git.example.test");
+ source.advisory.html_url = source.url;
+ }
+ const file = join(fixture.root, "github-enterprise.json");
+ await writeFile(file, JSON.stringify([source]));
+ const options = {
+ repository: fixture.repository,
+ provider: "github" as const,
+ sourceKey: "github/example/project",
+ };
+ const dependencies = { environment: fixture.environment };
+ const prepared = await prepareLocalExternalImport(
+ file,
+ options,
+ dependencies,
+ );
+ expect(prepared.preview.excluded).toEqual([]);
+ expect(
+ prepared.preview.findings[0]!.evidence.details!.repository,
+ ).toMatchObject({
+ url: "https://git.example.test/Example/Project",
+ name: "Example/Project",
+ });
+ expect((await prepared.import()).counts).toEqual({
+ created: 1,
+ updated: 0,
+ unchanged: 0,
+ });
+ const stored = await listLocalExternalFindings(options, dependencies);
+ expect(stored[0]!.evidence).toEqual(prepared.preview.findings[0]!.evidence);
+ expect(stored[0]!.evidence.source_data).toEqual({ ...source });
+ },
+);
diff --git a/sdk/typescript/tests-ts/github-findings.test.ts b/sdk/typescript/tests-ts/github-findings.test.ts
new file mode 100644
index 000000000..7901ed477
--- /dev/null
+++ b/sdk/typescript/tests-ts/github-findings.test.ts
@@ -0,0 +1,344 @@
+import { expect, test } from "bun:test";
+import { Octokit } from "@octokit/core";
+import { importGitHubCodeScanningAlerts } from "../src/github.js";
+import { importGitHubAdvisories } from "../src/github-advisories.js";
+import { validateExternalEvidence } from "../src/external-import-contract.js";
+import {
+ normalizeGitHubCodeScanningAlerts,
+ normalizeGitHubAdvisories,
+} from "../src/github-findings.js";
+import type { ImportedGitHubCodeScanningAlert } from "../src/github.js";
+
+import {
+ importedAlert,
+ importedAdvisory,
+} from "./support/github-import-fixtures.js";
+
+test("code-scanning mapping preserves full evidence and selected instance status without assessing it", () => {
+ const imported = importedAlert("refs/heads/review");
+ const result = normalizeGitHubCodeScanningAlerts([imported]);
+ expect(result.excluded).toEqual([]);
+ expect(result.findings[0]).toMatchObject({
+ evidence: {
+ title: "Untrusted query input",
+ severity: "high",
+ branch: "refs/heads/review",
+ code_revision: "a".repeat(40),
+ source_updated_at: 1767312000,
+ source_data: imported,
+ locations: [{ path: "src/query.ts", line: 12 }],
+ details: {
+ kind: "sast",
+ repository: { url: "https://github.com/example/project" },
+ source_status: "open",
+ scanner_origin: "Synthetic Scanner",
+ weakness_ids: ["CWE-89"],
+ code: { end_line: 14 },
+ },
+ },
+ });
+ expect(result.findings[0]!.evidence).not.toHaveProperty("assessment");
+});
+
+test("code-scanning identities isolate hosts, repositories and selected refs but not updated evidence", () => {
+ const first = importedAlert();
+ const changed = structuredClone(first);
+ changed.alert.most_recent_instance.commit_sha = "b".repeat(40);
+ changed.alert.most_recent_instance.state = "fixed";
+ const identity = (input: ImportedGitHubCodeScanningAlert) =>
+ normalizeGitHubCodeScanningAlerts([input]).findings[0]!.source_finding_id;
+ expect(identity(changed)).toBe(identity(first));
+ expect(identity(importedAlert("refs/heads/review"))).not.toBe(
+ identity(first),
+ );
+ expect(
+ identity(importedAlert("refs/heads/main", "git.example.test")),
+ ).not.toBe(identity(first));
+ const other = JSON.parse(
+ JSON.stringify(first).replaceAll("example/project", "example/other"),
+ ) as ImportedGitHubCodeScanningAlert;
+ expect(identity(other)).not.toBe(identity(first));
+ expect(() => normalizeGitHubCodeScanningAlerts([first, changed])).toThrow(
+ "Duplicate source finding id",
+ );
+});
+
+test("SARIF levels do not fabricate security severity and malformed siblings remain explicit exclusions", () => {
+ const noRating = importedAlert();
+ delete noRating.alert.rule.security_severity_level;
+ const badRepository = importedAlert("refs/heads/other");
+ badRepository.repository = "example/wrong";
+ const result = normalizeGitHubCodeScanningAlerts([badRepository, noRating]);
+ expect(result.read).toBe(2);
+ expect(result.findings).toHaveLength(1);
+ expect(result.findings[0]!.evidence.severity).toBe("unknown");
+ expect(result.excluded).toEqual([
+ {
+ position: 1,
+ source_finding_id: badRepository.url,
+ reason:
+ "GitHub alert URL does not match the selected repository and alert.",
+ },
+ ]);
+});
+
+test.each(["repository", "global"] as const)(
+ "%s advisories preserve package ranges without claiming an installed dependency",
+ (selection) => {
+ const imported = importedAdvisory(selection);
+ const result = normalizeGitHubAdvisories([imported]);
+ expect(result.excluded).toEqual([]);
+ expect(result.findings[0]!.evidence).toMatchObject({
+ advisory_ids: [imported.ghsaId, "CVE-2026-0001"],
+ packages: [
+ {
+ name: "example-package",
+ ecosystem: "npm",
+ vulnerable_version_range: ">= 1.0.0, < 1.2.3",
+ installed_version: null,
+ manifest_path: null,
+ fixed_versions: ["1.2.3"],
+ },
+ ],
+ locations: [],
+ source_data: imported,
+ details: {
+ kind: "advisory",
+ advisory: { source: selection },
+ source_status: "published",
+ },
+ });
+ if (selection === "repository")
+ expect(result.findings[0]!.evidence.details!.repository!.url).toBe(
+ "https://github.com/example/project",
+ );
+ else
+ expect(result.findings[0]!.evidence.details).not.toHaveProperty(
+ "repository",
+ );
+ },
+);
+
+test("advisory withdrawal and unknown severity remain source evidence with stable identity", () => {
+ const imported = importedAdvisory("global");
+ const before = normalizeGitHubAdvisories([imported]).findings[0]!;
+ const changed = {
+ ...imported,
+ advisory: {
+ ...imported.advisory,
+ withdrawn_at: "2026-01-03T00:00:00Z",
+ severity: null,
+ },
+ };
+ const after = normalizeGitHubAdvisories([changed as typeof imported])
+ .findings[0]!;
+ expect(after.source_finding_id).toBe(before.source_finding_id);
+ expect(after.evidence.severity).toBe("unknown");
+ expect(after.evidence.details!.source_status).toBe("withdrawn");
+ expect(after.evidence).not.toHaveProperty("assessment");
+});
+
+test("repository/global advisory identities stay separate and source URL conflicts are explicit exclusions", () => {
+ const repository = importedAdvisory();
+ const global = importedAdvisory("global");
+ expect(normalizeGitHubAdvisories([repository, global]).findings).toHaveLength(
+ 2,
+ );
+ repository.repository = "example/other";
+ const result = normalizeGitHubAdvisories([repository, global]);
+ expect(result.findings).toHaveLength(1);
+ expect(result.excluded[0]!.reason).toContain(
+ "does not match the selected source",
+ );
+});
+
+test.each(["repository", "global"] as const)(
+ "%s advisories retain disclosures with nullable package metadata",
+ (selection) => {
+ const imported = importedAdvisory(selection);
+ const known = imported.advisory.vulnerabilities![0]!;
+ for (const vulnerabilities of [
+ null,
+ [
+ { ...known, package: null },
+ { ...known, package: { ecosystem: "npm", name: null } },
+ known,
+ ],
+ ]) {
+ const input = {
+ ...imported,
+ advisory: { ...imported.advisory, vulnerabilities },
+ } as unknown as typeof imported;
+ const result = normalizeGitHubAdvisories([input]);
+ expect(result.excluded).toEqual([]);
+ expect(result.findings).toHaveLength(1);
+ expect(result.findings[0]!.evidence.source_data as unknown).toEqual(
+ input,
+ );
+ expect(result.findings[0]!.evidence.packages).toHaveLength(
+ vulnerabilities === null ? 0 : 1,
+ );
+ }
+ },
+);
+
+test("normalized global advisory evidence rejects invented source repository provenance", () => {
+ const evidence = normalizeGitHubAdvisories([importedAdvisory("global")])
+ .findings[0]!.evidence;
+ evidence.details!.repository = { url: "https://github.com/example/project" };
+ expect(() => validateExternalEvidence(evidence)).toThrow(
+ "Global advisory evidence cannot claim a source repository",
+ );
+});
+
+test.each([
+ { kind: "sast" },
+ { kind: "secret" },
+ { kind: "iac" },
+ { kind: "advisory" },
+ { kind: "advisory", advisory: { source: "repository" } },
+ {
+ kind: "sast",
+ repository: { url: "https://github.com/example/project" },
+ advisory: { source: "repository" },
+ },
+])(
+ "external evidence enforces repository and advisory source context: %j",
+ (details) => {
+ expect(() =>
+ validateExternalEvidence({
+ title: "Synthetic evidence",
+ severity: "unknown",
+ details,
+ }),
+ ).toThrow();
+ },
+);
+
+test("global advisories accept canonical public links from an Enterprise API without changing source host identity", () => {
+ const imported = importedAdvisory("global");
+ imported.githubHost = "git.example.test";
+ const result = normalizeGitHubAdvisories([imported]);
+ expect(result.excluded).toEqual([]);
+ expect(result.findings[0]!.source_finding_id).toStartWith(
+ "git.example.test/global/security-advisory/",
+ );
+ expect(result.findings[0]!.evidence.url).toBe(imported.url);
+ expect(result.findings[0]!.evidence.source_data as unknown).toEqual(imported);
+ expect(result.findings[0]!.evidence.details).not.toHaveProperty("repository");
+ const wrongRepositoryHost = importedAdvisory("repository");
+ wrongRepositoryHost.githubHost = "git.example.test";
+ expect(
+ normalizeGitHubAdvisories([wrongRepositoryHost]).excluded,
+ ).toHaveLength(1);
+});
+
+test("repository-wide dismissal takes precedence over detection state while selected refs keep their own open/fixed state", () => {
+ const imported = importedAlert("refs/heads/review");
+ imported.alert.state = "dismissed";
+ imported.alert.dismissed_reason = "false positive";
+ expect(
+ normalizeGitHubCodeScanningAlerts([imported]).findings[0]!.evidence.details!
+ .source_status,
+ ).toBe("dismissed");
+ imported.alert.state = "fixed";
+ imported.alert.dismissed_reason = null;
+ expect(
+ normalizeGitHubCodeScanningAlerts([imported]).findings[0]!.evidence.details!
+ .source_status,
+ ).toBe("open");
+});
+
+test.each(["security/code-scanning", "code-scanning"])(
+ "code-scanning accepts the %s HTML route without changing identity or repository binding",
+ (route) => {
+ const original = importedAlert();
+ const imported = structuredClone(original);
+ imported.url = `https://github.com/example/project/${route}/12`;
+ imported.alert.html_url = imported.url;
+ const result = normalizeGitHubCodeScanningAlerts([imported]);
+ expect(result.excluded).toEqual([]);
+ expect(result.findings[0]!.source_finding_id).toBe(
+ normalizeGitHubCodeScanningAlerts([original]).findings[0]!
+ .source_finding_id,
+ );
+ expect(result.findings[0]!.evidence.source_data as unknown).toEqual(
+ imported,
+ );
+ imported.repository = "example/other";
+ expect(normalizeGitHubCodeScanningAlerts([imported]).excluded).toHaveLength(
+ 1,
+ );
+ imported.repository = original.repository;
+ imported.url = `https://github.com/example/project/${route}/13`;
+ imported.alert.html_url = imported.url;
+ expect(normalizeGitHubCodeScanningAlerts([imported]).excluded).toHaveLength(
+ 1,
+ );
+ },
+);
+
+test("real GitHub readers and mappings preserve explicit ports in repository evidence and identities", async () => {
+ const codeIds = new Set<string>();
+ const advisoryIds = new Set<string>();
+ for (const port of ["", ":443", ":8443"]) {
+ const host = `git.example.test${port}`;
+ const alert = importedAlert("refs/heads/main", host);
+ const advisory = importedAdvisory();
+ advisory.githubHost = host;
+ advisory.url = advisory.advisory.html_url = advisory.url.replace(
+ "github.com",
+ host,
+ );
+ const github = new Octokit({
+ request: {
+ fetch: async (resource: Parameters<typeof fetch>[0]) => {
+ const url = new URL(
+ resource instanceof Request ? resource.url : resource,
+ );
+ return Response.json(
+ url.pathname.includes("code-scanning")
+ ? alert.alert
+ : advisory.advisory,
+ );
+ },
+ },
+ });
+ const dependency = {
+ createGitHub: async (selectedHost: string) => {
+ expect(selectedHost).toBe(host);
+ return github;
+ },
+ };
+ const importedAlerts = await importGitHubCodeScanningAlerts(
+ { repository: alert.repository, alertNumbers: [12], githubHost: host },
+ dependency,
+ );
+ const code = normalizeGitHubCodeScanningAlerts(importedAlerts);
+ const importedAdvisories = await importGitHubAdvisories(
+ {
+ repository: advisory.repository,
+ advisoryIds: [advisory.ghsaId],
+ githubHost: host,
+ },
+ dependency,
+ );
+ const disclosed = normalizeGitHubAdvisories(importedAdvisories);
+ expect(code.excluded).toEqual([]);
+ expect(disclosed.excluded).toEqual([]);
+ for (const result of [code, disclosed])
+ expect(result.findings[0]!.evidence.details!.repository!.url).toBe(
+ `https://${host}/example/project`,
+ );
+ expect(code.findings[0]!.evidence.source_data as unknown).toEqual(
+ importedAlerts[0],
+ );
+ expect(disclosed.findings[0]!.evidence.source_data as unknown).toEqual(
+ importedAdvisories[0],
+ );
+ codeIds.add(code.findings[0]!.source_finding_id);
+ advisoryIds.add(disclosed.findings[0]!.source_finding_id);
+ }
+ expect(codeIds.size).toBe(3);
+ expect(advisoryIds.size).toBe(3);
+});
diff --git a/sdk/typescript/tests-ts/support/github-import-fixtures.ts b/sdk/typescript/tests-ts/support/github-import-fixtures.ts
new file mode 100644
index 000000000..f0be01843
--- /dev/null
+++ b/sdk/typescript/tests-ts/support/github-import-fixtures.ts
@@ -0,0 +1,82 @@
+import type { ImportedGitHubCodeScanningAlert } from "../../src/github.js";
+
+export function importedAlert(
+ ref = "refs/heads/main",
+ host = "github.com",
+): ImportedGitHubCodeScanningAlert {
+ const url = `https://${host}/example/project/security/code-scanning/12`;
+ return {
+ source: "github-code-scanning",
+ repository: "example/project",
+ number: 12,
+ url,
+ alert: {
+ number: 12,
+ html_url: url,
+ state: "open",
+ dismissed_reason: null,
+ dismissed_comment: null,
+ updated_at: "2026-01-02T00:00:00Z",
+ rule: {
+ id: "synthetic/sql-query",
+ name: "Untrusted query input",
+ security_severity_level: "high",
+ severity: "error",
+ description: "Query input reaches the database.",
+ help: "Use query parameters.",
+ tags: ["external/cwe/cwe-089"],
+ },
+ tool: { name: "Synthetic Scanner", version: "1.0" },
+ most_recent_instance: {
+ ref,
+ commit_sha: "a".repeat(40),
+ state: "open",
+ message: { text: "Untrusted input at the query." },
+ location: { path: "src/query.ts", start_line: 12, end_line: 14 },
+ },
+ } as ImportedGitHubCodeScanningAlert["alert"],
+ };
+}
+
+export function importedAdvisory(
+ selection: "repository" | "global" = "repository",
+) {
+ const ghsaId = "GHSA-2345-6789-cfgh";
+ const url =
+ selection === "repository"
+ ? `https://github.com/example/project/security/advisories/${ghsaId}`
+ : `https://github.com/advisories/${ghsaId}`;
+ return {
+ source: "github-security-advisory" as const,
+ selection,
+ repository: "example/project",
+ githubHost: "github.com",
+ ghsaId,
+ url,
+ advisory: {
+ ghsa_id: ghsaId,
+ cve_id: "CVE-2026-0001",
+ html_url: url,
+ summary: "Synthetic dependency advisory",
+ description: "A published report for an example package.",
+ severity: "high",
+ state: "published",
+ withdrawn_at: null,
+ updated_at: "2026-01-02T00:00:00Z",
+ identifiers: [
+ { type: "GHSA", value: ghsaId },
+ { type: "CVE", value: "CVE-2026-0001" },
+ ],
+ vulnerabilities: [
+ {
+ package: { name: "example-package", ecosystem: "npm" },
+ vulnerable_version_range: ">= 1.0.0, < 1.2.3",
+ ...(selection === "repository"
+ ? { patched_versions: "1.2.3" }
+ : { first_patched_version: "1.2.3" }),
+ },
+ ],
+ cwes: [{ cwe_id: "CWE-79", name: "Synthetic weakness" }],
+ },
+ } as unknown as import("../../src/github-advisories.js").ImportedGitHubAdvisory;
+}