OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(imports): add shared Cloud findings publisher (#1441)
Michael D'Angelo17c04c09e589
diff --git a/plugins/codex-security/plugin-files.json b/plugins/codex-security/plugin-files.jsonindex 9cbe2c5bc..e9fe70b06 100644--- a/plugins/codex-security/plugin-files.json+++ b/plugins/codex-security/plugin-files.json@@ -133,6 +133,8 @@"skills/security-scan/references/scan-artifacts-and-ledger.md","skills/threat-model/SKILL.md","skills/threat-model/agents/openai.yaml",+ "skills/publish-findings/SKILL.md",+ "skills/publish-findings/agents/openai.yaml","skills/track-findings/SKILL.md","skills/track-findings/agents/openai.yaml","skills/track-findings/references/github-security-advisories.md",diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.mdnew file mode 100644index 000000000..73595107c--- /dev/null+++ b/plugins/codex-security/skills/publish-findings/SKILL.md@@ -0,0 +1,38 @@+---+name: publish-findings+description: Import selected Wiz package vulnerabilities, SAST, repository secrets, and IaC findings to Codex Security Cloud after previewing the destination and evidence. Supports plain or gzip-compressed JSON and normalized JSONL; does not import workload secrets or cloud configuration, run a scan, or assess findings.+---++# Publish external findings++Use the installed `codex-security publish findings` command for both preview and upload. It owns source mapping, Cloud authentication, source versions, and saved request retries. Do not implement another HTTP uploader or put credentials in a command argument.++Cloud destinations currently support connected GitHub and GitHub Enterprise repositories, including custom Enterprise hostnames. Resolve the user's destination to its repository URL or Cloud repository ID; the command accepts either. Confirm that the repository is connected in the intended Cloud account and has an authorized environment. Use the existing file-backed ChatGPT login; explain a missing or incompatible login rather than changing credential storage automatically.++## Wiz findings++Prefer the user's configured Wiz plugin or authorized [Wiz MCP](https://www.wiz.io/blog/introducing-wiz-mcp) connection to read selected findings. Use an authorized Wiz API connection when the required records are not exposed by MCP. Save the actual selected records locally with their original occurrence IDs and evidence. Inspect the returned fields: a summary, Wiz Issue, or local Wiz CLI scan result is not automatically a supported finding record. Do not invent fields to make a response fit the mapper.++Finish the requested pagination; for an explicit subset, retain that selection and its named collection. The publisher reads plain or gzip-compressed JSON and normalized JSONL with `source_finding_id` and `evidence` as documented in the CLI guide. A supplied export can use the same path. The command does not fetch from Wiz or accept CSV, scan events, workload secrets, cloud configuration, or external network exports.++Use a stable Wiz tenant/finding namespace as `--source-key`. A project filter is selection context, not a new identity. Confirm the selected assets or builds belong to the destination repository; do not infer a scanner branch or revision from the current checkout. Do not publish vendor credentials, unrelated records, or local assessments as original scanner evidence.++For package vulnerability UI exports, use **Vulnerability Findings → Save as → Report**, keeping the repository and finding filters. Select **Repository Branch** (remove the default Virtual Machine selection), **JSON**, and **Detailed** columns. Download the completed report; default gzip compression is supported, even with a `.json` filename. **Raw Event** on Code & Build Scans contains scan metadata and cannot supply findings. Do not create a scheduled report or enable notifications or external storage unless requested.++For SAST, repository secrets, and IaC, retain the explicit `data.sastFindings.nodes`, `data.secretInstances.nodes`, or `data.iacFindings.nodes` collection. Bare arrays cannot identify these finding families. Include a verified URL on the source repository metadata or supply `data.versionControlResources.nodes` with matching `repository.id` and `repository.url`. Retain the documented inventory `platform` field; explicit `GITHUB` establishes case-insensitive matching on custom GitHub Enterprise hosts. Resolve conflicting platform or URL metadata for a repository ID before publishing. For secrets, the repository is `resource.typedProperties.repository` and resource type must be `REPOSITORY_BRANCH`. Do not map names, inventory node IDs, `providerID`, or Wiz UUIDs directly to Cloud repository IDs. The importer verifies source URLs against the selected destination; resolve a missing or conflicting mapping before uploading.++Keep raw source records unchanged in `source_data`. New raw occurrence IDs are prefixed `sast:`, `secret:`, or `iac:`; existing package IDs are unchanged. For CSV report conversion, use a reviewed mapping of the actual header names into the documented normalized JSONL profile, set `evidence.details.kind` and the verified `details.repository.url`, and use the same prefixed occurrence ID. The command does not parse CSV directly. Select source paths and line numbers explicitly in secret reports; the standard metadata query lacks them. Preserve rule/CWE, range/snippet, detector validation, and IaC comparison fields in the typed details described in the CLI docs. Preserve empty comparison strings. Do not invent missing IDs, severity, revisions, or locations, retrieve credential values, test credentials, or apply suggested fixes. Vendor status, AI verdict, secret validation, introduced commits, and logical IaC resources are evidence, not Codex assessment or proof of runtime deployment.++For 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.++```sh+codex-security publish findings /path/to/selected-wiz-findings.json \+ --to cloud --repository https://github.com/example/project --provider wiz \+ --source-key TENANT_ID/vulnerability-finding --dry-run --format json+```++Show a concise preview of the Cloud API endpoint, account, repository, environments, source namespace, severity counts, and exclusions. Identify the saved evidence file and let the user inspect the complete JSON preview; do not paste an entire large report into the conversation. Explain that imported vendor evidence is not a Codex assessment. Obtain explicit confirmation for this upload, including any skipped records, then run the same command without `--dry-run`, adding `--yes`. Existing authorization to inspect or assess findings alone does not authorize sending them to Cloud. A user who already approved the concrete preview need not approve it again.++After a lost response or retryable failure, repeat the same command with unchanged input and destination. The publisher resends only unacknowledged requests, using their saved IDs and bodies. Existing findings keep their original Cloud environment even if the repository’s default changes. After a repository reset, stop and show the error; require fresh discovery and confirmation before a new publication. Report partial failures and retain their explanations. Successful receipts and source-record readback confirm stored vendor evidence. They do not establish a Codex assessment or visibility in the shared Cloud Findings view. Include the returned `cloudUrl` as a clickable repository link when available; do not derive a UI URL from the API endpoint or invent a link.++Read the result even when the process exits nonzero. `complete` exits 0, `partial` exits 1 for local exclusions or final item failures, and `interrupted` exits 2 while preserving acknowledged counts and receipts. Report `failures` by vendor source ID, distinguish `verified` from `unacknowledged`, and retain `savedSubmission` and the recovery error. A lost response does not mean that no findings reached Cloud. Preparation failures use `failed`; cancellation keeps the normal signal exit code. Terminal progress goes to stderr and does not replace the JSON result.diff --git a/plugins/codex-security/skills/publish-findings/agents/openai.yaml b/plugins/codex-security/skills/publish-findings/agents/openai.yamlnew file mode 100644index 000000000..56d284a1d--- /dev/null+++ b/plugins/codex-security/skills/publish-findings/agents/openai.yaml@@ -0,0 +1,6 @@+interface:+ display_name: "Publish Findings"+ short_description: "Preview and publish vendor findings to Cloud"+ default_prompt: "Use $publish-findings to preview selected vendor findings for my Cloud repository."+policy:+ allow_implicit_invocation: truediff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 95f036724..e19014efb 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -650,6 +650,15 @@ grant Cloud access. See [Cloud publication](docs/cli.md#publish-findings-to-cloufor setup and review steps, or [Linear publication](docs/cli.md#publish-completed-scans-to-linear)for issue creation.+The SDK also exposes `prepareExternalPublication(file, options)` for supported+vendor exports and `prepareNormalizedExternalPublication(findings, options)` for+normalized external evidence from any provider in the Cloud import contract.+The normalized API accepts `NormalizedExternalPublicationOptions`; file readers+use `ExternalPublicationOptions` for their supported formats. Both resolve the Cloud repository and return a+`preview` plus a separate `publish()` operation. Inspect the preview before+calling `publish()`. Imported evidence remains not assessed by Codex, and saved+requests and receipts support retries after interruption.+## Findings storage and deduplicationSaved-scan deduplication uses local SQLite directly:diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex d2aaef00e..43037ef6e 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -874,24 +874,26 @@ For filesystem and approval behavior, see the### Environment variables-| Variable | Effect |-| --------------------------------------------------------------------------- | ------------------------------------------------------------------ |-| `OPENAI_API_KEY`, `CODEX_API_KEY` | Scan credentials; the first takes precedence. |-| `CODEX_SECURITY_STATE_DIR` | Private history, database, and default artifacts. |-| `CODEX_SECURITY_PROJECT_CONFIG` | Selected project file; `-c` overrides it. |-| `CODEX_HOME` | Ambient Codex home; default `~/.codex`. |-| `CODEX_CLI_PATH` | Codex executable for login, setup, scans, and workers. |-| `PYTHON` | Python interpreter unless an explicit option overrides it. |-| `CODEX_SECURITY_LOG_LEVEL` | CLI diagnostics; `debug` enables verbose output. |-| `LOG_LEVEL` | Fallback if `CODEX_SECURITY_LOG_LEVEL` is unset or blank. |-| `CODEX_SECURITY_LINEAR_TEAM`, `CODEX_SECURITY_LINEAR_PROJECT` | Default publication destination. |-| `CODEX_SECURITY_LINEAR_API_KEY` | Linear personal API key. |-| `CODEX_SECURITY_EMBEDDINGS_URL` | Local dedupe and findings service embeddings endpoint. |-| `GH_HOST` | GitHub Enterprise host for bulk discovery. |-| `CODEX_SECURITY_NO_UPDATE_NOTICE`, `NO_UPDATE_NOTIFIER` | Disable interactive update notices. |-| `CODEX_SECURITY_NPM_REGISTRY`, `npm_config_registry`, `NPM_CONFIG_REGISTRY` | Update registry, in precedence order. |-| `CI` | Disable interactive update notices. |-| `NO_COLOR`, `TERM` | Disable colored history when `NO_COLOR` is defined or `TERM=dumb`. |+| Variable | Effect |+| --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |+| `OPENAI_API_KEY`, `CODEX_API_KEY` | Scan credentials; the first takes precedence. |+| `CODEX_SECURITY_STATE_DIR` | Private history, database, and default artifacts. |+| `CODEX_SECURITY_PROJECT_CONFIG` | Selected project file; `-c` overrides it. |+| `CODEX_HOME` | Ambient Codex home; default `~/.codex`. |+| `CODEX_CLI_PATH` | Codex executable for login, setup, scans, and workers. |+| `PYTHON` | Python interpreter unless an explicit option overrides it. |+| `CODEX_SECURITY_LOG_LEVEL` | CLI diagnostics; `debug` enables verbose output. |+| `LOG_LEVEL` | Fallback if `CODEX_SECURITY_LOG_LEVEL` is unset or blank. |+| `CODEX_SECURITY_LINEAR_TEAM`, `CODEX_SECURITY_LINEAR_PROJECT` | Default publication destination. |+| `CODEX_SECURITY_LINEAR_API_KEY` | Linear personal API key. |+| `CODEX_SECURITY_CLOUD_BASE_URL` | Cloud API root for discovery, imports, and scan publication. Defaults to `https://chatgpt.com/backend-api/aardvark`. |+| `CODEX_SECURITY_CLOUD_WEB_URL` | Cloud app URL for repository links when an alternate deployment serves its UI separately. |+| `CODEX_SECURITY_EMBEDDINGS_URL` | Local dedupe and findings service embeddings endpoint. |+| `GH_HOST` | GitHub Enterprise host for bulk discovery. |+| `CODEX_SECURITY_NO_UPDATE_NOTICE`, `NO_UPDATE_NOTIFIER` | Disable interactive update notices. |+| `CODEX_SECURITY_NPM_REGISTRY`, `npm_config_registry`, `NPM_CONFIG_REGISTRY` | Update registry, in precedence order. |+| `CI` | Disable interactive update notices. |+| `NO_COLOR`, `TERM` | Disable colored history when `NO_COLOR` is defined or `TERM=dumb`. |Custom Codex executables need thread source attribution for `exec` and`app-server` (Codex 0.149.1+). On Windows, use a native `.exe` or `.com`;@@ -1192,6 +1194,274 @@ Supply the validation prompt again when rerunning.## Publish findings to Cloud+### Import Wiz findings++Import selected Wiz package vulnerabilities, SAST findings, repository secrets,+and IaC findings without creating a scan. Imported records retain vendor evidence+and remain **not assessed by Codex**, including when Wiz marks them resolved or+reports an AI verdict. Workload secrets, cloud configuration findings, and external+network findings are not supported by this repository importer. Cloud destinations+currently support connected GitHub and GitHub Enterprise repositories, including+custom Enterprise hostnames. Named Wiz exports do not add other VCS destinations.++Use an authorized Wiz connection to acquire findings. If a Wiz plugin is available+in your Codex workspace, use its MCP connection; otherwise configure+[Wiz MCP](https://www.wiz.io/blog/introducing-wiz-mcp) or use the Wiz API.+The publisher reads the selected records saved by that connection. It does not+fetch from Wiz or require a manual website download.++Inspect the connection's actual response before importing it. MCP summaries,+Wiz Issues, and local Wiz CLI scan results are not automatically compatible with+this finding mapper. Keep the original occurrence IDs and evidence; use the+named collections below when the response contains repository findings.++Before the first import:++1. Select an existing repository in Codex Security Cloud and copy its URL or+ Cloud repository ID. The repository needs an+ authorized environment, but does not need a completed native scan.+2. Read the selected records through the authorized connection and save their+ JSON. For **package vulnerabilities**, include `id`, `name`, `detailedName`,+ `vendorSeverity` (or `severity`), and `vulnerableAsset.id`; retain available+ package, image, and source metadata. For SAST, repository secrets, and IaC,+ retain the named API collections and repository metadata described below.+ Complete the selected pages before importing; a summary or unfinished page+ is not a complete finding selection.+3. Choose a stable source key such as `TENANT_ID/vulnerability-finding`. Reuse it+ for that Wiz tenant and finding class across exports. Do not create a new key+ for each project filter or import; that creates different source identities.+4. Check the ChatGPT account used by your existing file-backed Codex Security+ login. API-key-only and keyring-only logins are not supported for Cloud+ publication. See the credential-storage instructions below.++Saved package-vulnerability reports are also supported. In Wiz **Vulnerability+Findings**, retain the repository and finding filters, choose **Save as → Report**,+select **Repository Branch**, **JSON**, and **Detailed** columns, then download+the completed report. Gzip is detected regardless of the filename extension.+**Raw Event** on Code & Build Scans contains scan metadata rather than findings.++For an alternate Cloud deployment, set `CODEX_SECURITY_CLOUD_BASE_URL` to its+API root before previewing or uploading, for example+`https://cloud.example.test/backend-api/aardvark`. Remote APIs require HTTPS;+HTTP is accepted only for loopback development (`localhost`, `127.0.0.0/8`, or+`::1`). Use a login issued by that deployment and an isolated+`CODEX_SECURITY_STATE_DIR` for testing. The endpoint+does not change your login or sign you into another deployment. An invalid or+empty configured URL stops the import before authentication or network requests.+With the variable unset, the existing production endpoint remains the default.+The older `CODEX_SECURITY_CLOUD_PUBLISH_URL` overrides only the final native scan+publication endpoint; it does not route vendor imports.++If that deployment serves its UI separately, set `CODEX_SECURITY_CLOUD_WEB_URL`+to the full Cloud app URL shown in the browser. The import handoff supplies both+deployment settings. The preview and result include a repository-specific+`cloudUrl`, and terminal completion prints the link. This setting only controls+the return link; all API requests still use `CODEX_SECURITY_CLOUD_BASE_URL`.+For custom API destinations without a configured app URL, completion retains+the manual navigation guidance rather than guessing a UI host or port.++Preview the selection and destination:++```bash+codex-security publish findings selected-wiz.json \+ --to cloud --repository https://github.com/example/project --provider wiz \+ --source-key TENANT_ID/vulnerability-finding --dry-run --format json+```++`--repository` accepts the repository's URL or ID. Both resolve to the same Cloud+destination and resume the same saved submission. This command reads the+authorized destination and current source versions during+preview. It uses the same saved ChatGPT file login as scan publication. The Cloud+repository needs an existing environment; no native scan is required. Review the+Cloud API endpoint, account, repository, environments, findings, and exclusions,+then rerun without+`--dry-run`. The default terminal prompt is No; `--yes` confirms a previously+reviewed input for scripts or the plugin. Without a terminal or `--yes`, no upload+occurs. Existing source findings keep their Cloud environment; new findings use+the repository’s current authorized default. Preview shows the environments that+will receive the selected findings. The terminal preview summarizes severities,+shows up to five finding IDs and titles, and identifies the evidence file and+exclusions. `--dry-run --format json` retains all normalized findings and complete+evidence for inspection. A prompt explicitly includes any records that will be+skipped.++Package input can be a downloaded Wiz JSON vulnerability report, a vulnerability+finding, an array, a complete `data.vulnerabilityFindings.nodes` response, or JSONL+with one package record per line. Plain and gzip-compressed files are accepted.+A response that advertises another page is rejected. Complete the requested pages+or save only the explicitly selected records; retain the named collection for+SAST, repository secrets, and IaC. Normalized JSONL is also accepted:++```json+{+ "source_finding_id": "vendor-finding-42",+ "evidence": {+ "title": "Vulnerable example package",+ "severity": "high",+ "source_data": { "id": "vendor-finding-42" }+ }+}+```++Use Wiz's finding `id`, not a CVE, as identity. Keep the source key stable across+exports; a selected project filter does not change the vendor namespace. Confirm+that the selected assets or builds map to this repository. The raw Wiz adapter+retains each record in `source_data`, uses reported severity, and leaves unknown+branch/revision empty. Repository-branch findings retain their repository-relative+file paths; container and other workload paths remain vendor evidence rather than+source-code locations. It does not+fetch from Wiz, assess findings, or change vendor or Cloud triage decisions.+Findings from external network scans are excluded from this package vulnerability+mapping.++For SAST, repository secrets, and IaC, save the documented JSON API collection:++| Finding family | Collection | Raw occurrence identity |+| ------------------ | ---------------------------- | ----------------------- |+| SAST | `data.sastFindings.nodes` | `sast:<id>` |+| Repository secrets | `data.secretInstances.nodes` | `secret:<id>` |+| IaC | `data.iacFindings.nodes` | `iac:<id>` |++The collection identifies the mapping. Bare arrays of these raw findings are+excluded because their overlapping fields do not identify a family. An export+may contain multiple named collections. GraphQL errors and unfinished pages stop+the import. Secret resources must have `type: "REPOSITORY_BRANCH"`; a workload's+relationship to source code does not make it a repository secret.++Each new finding needs a verified source repository URL. Supply `repository.url`+in the finding's repository metadata, or include the matching repository inventory+in `data.versionControlResources.nodes`. For secrets, repository metadata is under+`resource.typedProperties.repository`. The importer joins the inventory's+`repository.id` to that source ID and uses `repository.url`; inventory node IDs,+`providerID`, names, and Wiz UUIDs are not Cloud repository IDs. A supplied URL+must agree with the inventory and with the selected Cloud repository before any+finding is uploaded. Keep each inventory node's `platform` field: `GITHUB`+establishes case-insensitive repository matching on custom GitHub Enterprise+hosts. Fresh imports preserve the reported branch name literally. Duplicate+entries for one repository ID must agree on their platform and repository URL.+For example, this synthetic selection supplies the inventory alongside its SAST+collection:++```json+{+ "data": {+ "sastFindings": {+ "nodes": [+ {+ "id": "finding-42",+ "name": "Untrusted query construction",+ "severity": "HIGH",+ "repository": { "id": "source-repository-1" },+ "filePath": "src/query.ts",+ "startLine": 10,+ "endLine": 12+ }+ ]+ },+ "versionControlResources": {+ "nodes": [+ {+ "repository": {+ "id": "source-repository-1",+ "url": "https://github.com/example/project"+ }+ }+ ]+ }+ }+}+```++The adapters preserve each selected raw node exactly in `source_data`. Typed+`evidence.details` carries `kind`, verified `repository`, vendor `source_status`,+and family-specific evidence:++| Family | Evidence retained in typed fields |+| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |+| SAST | CWE IDs, first location's end line and snippet, scanner origin and verdict, remediation instructions |+| Repository secrets | Detector rule, type, confidence, vendor validation status, encryption/management flags, introduced commit when supplied |+| IaC | Rule IDs and name, first location's range and matched content, platform, expected/actual content, separate file link, remediation instructions |++Vendor status and verdict remain separate from Codex assessment. A secret's+introduced commit is not its scanned revision. Missing source revisions and scan+IDs stay unknown. A logical IaC resource is retained in the original record and+does not establish that it is deployed. Precise original timestamps remain in+`source_data`; only an explicit record-update timestamp maps to the whole-second+`source_updated_at` field. SAST creation time and IaC last-seen time are not update+timestamps.++Native SAST and secret report downloads can be CSV, including gzip-compressed+CSV. CSV is not parsed directly. Convert a selected report with a reviewed mapping+for its actual column headers into normalized JSONL, preserving each original row+in `source_data`. Set `details.kind` and `details.repository.url` explicitly after+verifying the source repository. Use the same prefixed occurrence ID shown above+so API and report imports update the same finding; normalized IDs are accepted+exactly as supplied. Never substitute a rule ID, CWE, title, token, or file path+for a vendor occurrence ID. Missing IDs or severity must be corrected at the+source rather than invented.++For repository-secret reports, select `path` and `lineNumber` for source+navigation, detector fields under `rule`, and `vcsDetails.initialCommitHash` only+as the introduced commit. The standard secret metadata API does not supply a+path or line. For IaC reports, explicitly select `filePath`, `startLine`, `endLine`,+`rule.id`, `rule.shortId`, `expectedContent`, `foundContent`, `matchContent`, and+repository/branch metadata. Preserve the original fields; source locations must+be repository-relative, and an end line requires a start line. Keep credential+values out of the metadata selection; the importer does not retrieve or test+credentials or apply remediation instructions.++Inputs must be valid UTF-8. Integer-valued evidence outside JavaScript's safe+integer range is rejected; export those values as strings to preserve them+exactly. Invalid records appear in `excluded` with their source ID and reason.++Requests contain at most 100 findings and respect the Cloud payload limits.+Before uploading, the publisher saves request IDs and bodies privately under+the configured Codex Security state directory. After an uncertain response,+repeat the same command with unchanged input and Cloud API endpoint to resume those+requests. Different deployments have separate saved submissions, including when+their account and repository IDs match. The preview and result include+`cloudApiUrl` so scripts can verify which API received the findings; this is an+API endpoint, not a link to the Cloud UI. A reset+retires the old request without republishing; review and explicitly approve a+fresh invocation.++Results distinguish completion from partial or interrupted work:++| Status | Exit code | Meaning |+| ------------- | --------- | -------------------------------------------------------------------------------------------------- |+| `complete` | 0 | All selected records were acknowledged and their source records read back. |+| `partial` | 1 | The import finished, but some records were excluded locally or rejected by Cloud. |+| `interrupted` | 2 | Upload, verification, or receipt persistence stopped; acknowledged work is included in the result. |+| `failed` | 2 | Preparation failed before uploading; structured output includes the error. |++For finding imports, `--full-output` requires `--format json` or `--format jsonl`.+Failed and interrupted imports set the envelope's `ok` to `false`, with+`error.code: "IMPORT_FAILED"`, while retaining available results, receipts, and+counts under `data`. Other full-output format combinations are rejected before+reading the input or contacting Cloud; omit `--full-output` to use those formats.++Ctrl-C and SIGTERM retain exit codes 130 and 143. Interrupted JSON output preserves+`receipts`, `counts`, `failures` with vendor source IDs, `excluded`, `verified`, and+`unacknowledged`. A lost response can mean unacknowledged findings were accepted;+resume the saved submission rather than treating them as never uploaded. When+available, `savedSubmission` identifies the checkpoint to resume by repeating the+same command. Review `error` before retrying; a repository reset retires the old+submission and requires fresh approval. Correct local exclusions or final source+conflicts before preparing a new submission.++Counts are cumulative for the saved submission: a resumed result includes+batches acknowledged by earlier invocations, not just the latest upload attempt.++Terminal progress reports preparation, acknowledged uploads, and verification+on stderr; JSON results stay on stdout. Lookups and readback use at most four+concurrent requests, while uploads remain sequential. Successful receipts are+saved locally. Verification reads the imported source records and checks their+identities and evidence against the receipts. This does not establish a Codex+assessment or visibility in the shared Cloud Findings view.+When available, `cloudUrl` links to the destination repository in Cloud.++### Publish completed scans+Preview selected completed scans before uploading:```bashdiff --git a/sdk/typescript/package.json b/sdk/typescript/package.jsonindex 939cba539..f25e9d973 100644--- a/sdk/typescript/package.json+++ b/sdk/typescript/package.json@@ -69,6 +69,8 @@"format": "prettier --check --ignore-path .gitignore --ignore-path .prettierignore \"**/*.{cjs,mjs,js,ts,mts,tsx,json}\" \"../../.github/scripts/*.mts\" \"../../examples/custom-validation/*.mts\" \"../../plugins/codex-security/native/*.mts\" \"../../evals/{deep-reducer,secret-discovery,workflow-routing}/*.mts\" \"../../evals/triage-finding/{assertions,scripts,sastbench/assertions,sastbench/scripts}/*.mts\" \"../../evals/triage-finding/types.ts\" \"../../evals/tsconfig.json\" && node scripts/check-markdown.mjs","generate:models": "node scripts/generate-models.cjs","generate:models:check": "node scripts/generate-models.cjs --check",+ "generate:external-import-models": "node scripts/generate-external-import-models.cjs",+ "generate:external-import-models:check": "node scripts/generate-external-import-models.cjs --check","lint": "tsc --noEmit","prepack": "node --run build:plugin && node --run build","test": "node --run build:plugin && bun test --timeout 30000 ./tests-ts",@@ -76,7 +78,7 @@"test:mcp": "node --run build:plugin && pnpm --dir ../../plugins/codex-security/mcp-app run test:mcp","test:mutation": "stryker run","test:package": "node scripts/smoke-package.mjs",- "types": "node scripts/generate-deep-defaults.mjs --check && node scripts/generate-project-config-schema.mjs --check && pnpm run generate:models:check && pnpm --dir ../../plugins/codex-security/mcp-app run typecheck && tsc --noEmit"+ "types": "node scripts/generate-deep-defaults.mjs --check && node scripts/generate-project-config-schema.mjs --check && pnpm run generate:models:check && pnpm run generate:external-import-models:check && pnpm --dir ../../plugins/codex-security/mcp-app run typecheck && tsc --noEmit"},"dependencies": {"@inquirer/prompts": "8.7.3",diff --git a/sdk/typescript/schemas/external-findings.schema.json b/sdk/typescript/schemas/external-findings.schema.jsonnew file mode 100644index 000000000..f04ad771b--- /dev/null+++ b/sdk/typescript/schemas/external-findings.schema.json@@ -0,0 +1,1421 @@+{+ "$defs": {+ "FindingImportItem": {+ "additionalProperties": false,+ "properties": {+ "client_id": {+ "maxLength": 128,+ "minLength": 1,+ "title": "Client Id",+ "type": "string"+ },+ "source_finding_id": {+ "maxLength": 512,+ "minLength": 1,+ "title": "Source Finding Id",+ "type": "string"+ },+ "expected_version": {+ "minimum": 0,+ "title": "Expected Version",+ "type": "integer"+ },+ "evidence": {+ "$ref": "#/$defs/ImportedFindingEvidence"+ }+ },+ "required": [+ "client_id",+ "source_finding_id",+ "expected_version",+ "evidence"+ ],+ "title": "FindingImportItem",+ "type": "object"+ },+ "FindingImportReceipt": {+ "additionalProperties": false,+ "properties": {+ "id": {+ "format": "uuid",+ "title": "Id",+ "type": "string"+ },+ "object": {+ "const": "security.finding_import",+ "default": "security.finding_import",+ "title": "Object",+ "type": "string"+ },+ "repository": {+ "$ref": "#/$defs/ImportDestination"+ },+ "source": {+ "$ref": "#/$defs/ImportSource"+ },+ "actor": {+ "title": "Actor",+ "type": "string"+ },+ "created_at": {+ "title": "Created At",+ "type": "integer"+ },+ "item_count": {+ "maximum": 100,+ "minimum": 1,+ "title": "Item Count",+ "type": "integer"+ },+ "counts": {+ "$ref": "#/$defs/ImportCounts"+ },+ "results": {+ "items": {+ "$ref": "#/$defs/FindingImportResult"+ },+ "title": "Results",+ "type": "array"+ }+ },+ "required": [+ "id",+ "repository",+ "source",+ "actor",+ "created_at",+ "item_count",+ "counts",+ "results"+ ],+ "title": "FindingImportReceipt",+ "type": "object"+ },+ "FindingImportRequest": {+ "additionalProperties": false,+ "properties": {+ "request_id": {+ "format": "uuid",+ "title": "Request Id",+ "type": "string"+ },+ "repository": {+ "$ref": "#/$defs/ImportDestination"+ },+ "source": {+ "$ref": "#/$defs/ImportSource"+ },+ "items": {+ "items": {+ "$ref": "#/$defs/FindingImportItem"+ },+ "maxItems": 100,+ "minItems": 1,+ "title": "Items",+ "type": "array"+ }+ },+ "required": ["request_id", "repository", "source", "items"],+ "title": "FindingImportRequest",+ "type": "object"+ },+ "FindingImportResult": {+ "additionalProperties": false,+ "properties": {+ "client_id": {+ "title": "Client Id",+ "type": "string"+ },+ "outcome": {+ "enum": ["created", "updated", "unchanged", "error"],+ "title": "Outcome",+ "type": "string"+ },+ "source_report_id": {+ "anyOf": [+ {+ "pattern": "^aif_[0-9a-f]{64}$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Source Report Id"+ },+ "observation_id": {+ "anyOf": [+ {+ "pattern": "^aio_[0-9a-f]{64}$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Observation Id"+ },+ "canonical_finding_id": {+ "anyOf": [+ {+ "pattern": "^acf_[0-9a-f]{32}$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Canonical Finding Id"+ },+ "version": {+ "anyOf": [+ {+ "minimum": 1,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Version"+ },+ "error": {+ "anyOf": [+ {+ "$ref": "#/$defs/ImportItemError"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ }+ },+ "required": ["client_id", "outcome"],+ "title": "FindingImportResult",+ "type": "object"+ },+ "ImportCounts": {+ "additionalProperties": false,+ "properties": {+ "created": {+ "default": 0,+ "minimum": 0,+ "title": "Created",+ "type": "integer"+ },+ "updated": {+ "default": 0,+ "minimum": 0,+ "title": "Updated",+ "type": "integer"+ },+ "unchanged": {+ "default": 0,+ "minimum": 0,+ "title": "Unchanged",+ "type": "integer"+ },+ "error": {+ "default": 0,+ "minimum": 0,+ "title": "Error",+ "type": "integer"+ }+ },+ "title": "ImportCounts",+ "type": "object"+ },+ "ImportDestination": {+ "additionalProperties": false,+ "properties": {+ "id": {+ "maxLength": 512,+ "minLength": 1,+ "title": "Id",+ "type": "string"+ },+ "repo_connector_id": {+ "maxLength": 512,+ "minLength": 1,+ "title": "Repo Connector Id",+ "type": "string"+ },+ "environment_id": {+ "maxLength": 512,+ "minLength": 1,+ "title": "Environment Id",+ "type": "string"+ },+ "reset_marker": {+ "maxLength": 512,+ "minLength": 1,+ "title": "Reset Marker",+ "type": "string"+ }+ },+ "required": ["id", "repo_connector_id", "environment_id", "reset_marker"],+ "title": "ImportDestination",+ "type": "object"+ },+ "ImportItemError": {+ "additionalProperties": false,+ "properties": {+ "code": {+ "enum": [+ "version_conflict",+ "scope_conflict",+ "stale_source_snapshot"+ ],+ "title": "Code",+ "type": "string"+ },+ "message": {+ "title": "Message",+ "type": "string"+ }+ },+ "required": ["code", "message"],+ "title": "ImportItemError",+ "type": "object"+ },+ "ImportRepository": {+ "additionalProperties": false,+ "properties": {+ "id": {+ "title": "Id",+ "type": "string"+ },+ "object": {+ "const": "security.repository",+ "default": "security.repository",+ "title": "Object",+ "type": "string"+ },+ "repo_connector_id": {+ "title": "Repo Connector Id",+ "type": "string"+ },+ "url": {+ "title": "Url",+ "type": "string"+ },+ "default_branch": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Default Branch"+ },+ "reset_marker": {+ "title": "Reset Marker",+ "type": "string"+ },+ "import_environment_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Import Environment Id"+ }+ },+ "required": ["id", "repo_connector_id", "url", "reset_marker"],+ "title": "ImportRepository",+ "type": "object"+ },+ "ImportRepositoryPage": {+ "additionalProperties": false,+ "properties": {+ "object": {+ "const": "page",+ "default": "page",+ "title": "Object",+ "type": "string"+ },+ "data": {+ "items": {+ "$ref": "#/$defs/ImportRepository"+ },+ "title": "Data",+ "type": "array"+ },+ "has_more": {+ "title": "Has More",+ "type": "boolean"+ },+ "next": {+ "anyOf": [+ {+ "maxLength": 4096,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Next"+ }+ },+ "required": ["data", "has_more", "next"],+ "title": "ImportRepositoryPage",+ "type": "object"+ },+ "ImportSource": {+ "additionalProperties": false,+ "properties": {+ "provider": {+ "enum": ["wiz", "endor", "snyk", "github", "semgrep"],+ "title": "Provider",+ "type": "string"+ },+ "source_key": {+ "maxLength": 512,+ "minLength": 1,+ "title": "Source Key",+ "type": "string"+ }+ },+ "required": ["provider", "source_key"],+ "title": "ImportSource",+ "type": "object"+ },+ "ImportedAdvisoryContext": {+ "additionalProperties": false,+ "description": "Where the advisory was read; applicability is assessed separately.",+ "properties": {+ "source": {+ "enum": ["repository", "global"],+ "title": "Source",+ "type": "string"+ }+ },+ "required": ["source"],+ "title": "ImportedAdvisoryContext",+ "type": "object"+ },+ "ImportedAssessment": {+ "additionalProperties": false,+ "properties": {+ "state": {+ "const": "not_assessed",+ "default": "not_assessed",+ "title": "State",+ "type": "string"+ }+ },+ "title": "ImportedAssessment",+ "type": "object"+ },+ "ImportedCodeContext": {+ "additionalProperties": false,+ "description": "Optional range and snippet for the evidence's first source location.",+ "properties": {+ "end_line": {+ "anyOf": [+ {+ "minimum": 1,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "End Line"+ },+ "snippet": {+ "anyOf": [+ {+ "maxLength": 65536,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Snippet"+ }+ },+ "title": "ImportedCodeContext",+ "type": "object"+ },+ "ImportedConfigurationDetails": {+ "additionalProperties": false,+ "properties": {+ "platform": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Platform"+ },+ "cloud_platform": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Cloud Platform"+ },+ "expected": {+ "anyOf": [+ {+ "maxLength": 65536,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Expected"+ },+ "actual": {+ "anyOf": [+ {+ "maxLength": 65536,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Actual"+ }+ },+ "title": "ImportedConfigurationDetails",+ "type": "object"+ },+ "ImportedFindingDetails": {+ "additionalProperties": false,+ "description": "Typed repository evidence; vendor state is not a Codex assessment.",+ "properties": {+ "kind": {+ "enum": ["sast", "secret", "iac", "advisory"],+ "title": "Kind",+ "type": "string"+ },+ "repository": {+ "anyOf": [+ {+ "$ref": "#/$defs/ImportedRepositoryReference"+ },+ {+ "type": "null"+ }+ ]+ },+ "advisory": {+ "anyOf": [+ {+ "$ref": "#/$defs/ImportedAdvisoryContext"+ },+ {+ "type": "null"+ }+ ]+ },+ "source_status": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Source Status"+ },+ "scanner_origin": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Scanner Origin"+ },+ "scanner_verdict": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Scanner Verdict"+ },+ "rule": {+ "anyOf": [+ {+ "$ref": "#/$defs/ImportedFindingRule"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "weakness_ids": {+ "default": [],+ "items": {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ "maxItems": 100,+ "title": "Weakness Ids",+ "type": "array"+ },+ "remediation_instructions": {+ "anyOf": [+ {+ "maxLength": 65536,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Remediation Instructions"+ },+ "code": {+ "anyOf": [+ {+ "$ref": "#/$defs/ImportedCodeContext"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "secret": {+ "anyOf": [+ {+ "$ref": "#/$defs/ImportedSecretDetails"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "configuration": {+ "anyOf": [+ {+ "$ref": "#/$defs/ImportedConfigurationDetails"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "file_url": {+ "anyOf": [+ {+ "maxLength": 2048,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "File Url"+ }+ },+ "required": ["kind"],+ "title": "ImportedFindingDetails",+ "type": "object"+ },+ "ImportedFindingEvidence": {+ "additionalProperties": false,+ "properties": {+ "title": {+ "maxLength": 512,+ "minLength": 1,+ "title": "Title",+ "type": "string"+ },+ "severity": {+ "enum": [+ "critical",+ "high",+ "medium",+ "low",+ "informational",+ "unknown"+ ],+ "title": "Severity",+ "type": "string"+ },+ "description": {+ "anyOf": [+ {+ "maxLength": 65536,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Description"+ },+ "url": {+ "anyOf": [+ {+ "maxLength": 2048,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Url"+ },+ "advisory_ids": {+ "default": [],+ "items": {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ "maxItems": 100,+ "title": "Advisory Ids",+ "type": "array"+ },+ "packages": {+ "default": [],+ "items": {+ "$ref": "#/$defs/ImportedPackage"+ },+ "maxItems": 100,+ "title": "Packages",+ "type": "array"+ },+ "locations": {+ "default": [],+ "items": {+ "$ref": "#/$defs/ImportedLocation"+ },+ "maxItems": 100,+ "title": "Locations",+ "type": "array"+ },+ "branch": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Branch"+ },+ "code_revision": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Code Revision"+ },+ "source_scan_id": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Source Scan Id"+ },+ "image_digests": {+ "default": [],+ "items": {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ "maxItems": 100,+ "title": "Image Digests",+ "type": "array"+ },+ "source_updated_at": {+ "anyOf": [+ {+ "minimum": 0,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Source Updated At"+ },+ "source_data": {+ "additionalProperties": true,+ "default": {},+ "title": "Source Data",+ "type": "object"+ },+ "details": {+ "anyOf": [+ {+ "$ref": "#/$defs/ImportedFindingDetails"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["title", "severity"],+ "title": "ImportedFindingEvidence",+ "type": "object"+ },+ "ImportedFindingRule": {+ "additionalProperties": false,+ "properties": {+ "id": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Id"+ },+ "short_id": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Short Id"+ },+ "name": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Name"+ }+ },+ "title": "ImportedFindingRule",+ "type": "object"+ },+ "ImportedLocation": {+ "additionalProperties": false,+ "properties": {+ "path": {+ "maxLength": 2048,+ "minLength": 1,+ "title": "Path",+ "type": "string"+ },+ "line": {+ "anyOf": [+ {+ "minimum": 1,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Line"+ }+ },+ "required": ["path"],+ "title": "ImportedLocation",+ "type": "object"+ },+ "ImportedPackage": {+ "additionalProperties": false,+ "properties": {+ "name": {+ "maxLength": 512,+ "minLength": 1,+ "title": "Name",+ "type": "string"+ },+ "ecosystem": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Ecosystem"+ },+ "installed_version": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Installed Version"+ },+ "vulnerable_version_range": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Vulnerable Version Range"+ },+ "manifest_path": {+ "anyOf": [+ {+ "maxLength": 2048,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Manifest Path"+ },+ "fixed_versions": {+ "default": [],+ "items": {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ "maxItems": 100,+ "title": "Fixed Versions",+ "type": "array"+ }+ },+ "required": ["name"],+ "title": "ImportedPackage",+ "type": "object"+ },+ "ImportedRepositoryReference": {+ "additionalProperties": false,+ "description": "Vendor repository identity, resolved to the full source-control URL.",+ "properties": {+ "url": {+ "maxLength": 2048,+ "minLength": 1,+ "title": "Url",+ "type": "string"+ },+ "id": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Id"+ },+ "name": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Name"+ }+ },+ "required": ["url"],+ "title": "ImportedRepositoryReference",+ "type": "object"+ },+ "ImportedSecretConfidence": {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ "ImportedSecretDetails": {+ "additionalProperties": false,+ "properties": {+ "type": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Type"+ },+ "confidence": {+ "anyOf": [+ {+ "$ref": "#/$defs/ImportedSecretConfidence"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "validation_status": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Validation Status"+ },+ "is_encrypted": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Is Encrypted"+ },+ "is_managed": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Is Managed"+ },+ "introduced_commit": {+ "anyOf": [+ {+ "maxLength": 512,+ "minLength": 1,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Introduced Commit"+ }+ },+ "title": "ImportedSecretDetails",+ "type": "object"+ },+ "LastImport": {+ "additionalProperties": false,+ "properties": {+ "id": {+ "format": "uuid",+ "title": "Id",+ "type": "string"+ },+ "actor": {+ "title": "Actor",+ "type": "string"+ },+ "created_at": {+ "title": "Created At",+ "type": "integer"+ }+ },+ "required": ["id", "actor", "created_at"],+ "title": "LastImport",+ "type": "object"+ },+ "SourceReport": {+ "additionalProperties": false,+ "properties": {+ "id": {+ "pattern": "^aif_[0-9a-f]{64}$",+ "title": "Id",+ "type": "string"+ },+ "object": {+ "const": "security.source_report",+ "default": "security.source_report",+ "title": "Object",+ "type": "string"+ },+ "origin": {+ "const": "imported",+ "default": "imported",+ "title": "Origin",+ "type": "string"+ },+ "repo_id": {+ "title": "Repo Id",+ "type": "string"+ },+ "repo_connector_id": {+ "title": "Repo Connector Id",+ "type": "string"+ },+ "environment_id": {+ "title": "Environment Id",+ "type": "string"+ },+ "canonical_finding_id": {+ "pattern": "^acf_[0-9a-f]{32}$",+ "title": "Canonical Finding Id",+ "type": "string"+ },+ "source": {+ "$ref": "#/$defs/ImportSource"+ },+ "source_finding_id": {+ "title": "Source Finding Id",+ "type": "string"+ },+ "observation_id": {+ "pattern": "^aio_[0-9a-f]{64}$",+ "title": "Observation Id",+ "type": "string"+ },+ "version": {+ "minimum": 1,+ "title": "Version",+ "type": "integer"+ },+ "evidence": {+ "$ref": "#/$defs/ImportedFindingEvidence"+ },+ "assessment": {+ "$ref": "#/$defs/ImportedAssessment"+ },+ "last_import": {+ "anyOf": [+ {+ "$ref": "#/$defs/LastImport"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "created_at": {+ "title": "Created At",+ "type": "integer"+ },+ "updated_at": {+ "title": "Updated At",+ "type": "integer"+ }+ },+ "required": [+ "id",+ "repo_id",+ "repo_connector_id",+ "environment_id",+ "canonical_finding_id",+ "source",+ "source_finding_id",+ "observation_id",+ "version",+ "evidence",+ "created_at",+ "updated_at"+ ],+ "title": "SourceReport",+ "type": "object"+ },+ "SourceReportPage": {+ "additionalProperties": false,+ "properties": {+ "object": {+ "const": "page",+ "default": "page",+ "title": "Object",+ "type": "string"+ },+ "data": {+ "items": {+ "$ref": "#/$defs/SourceReportSummary"+ },+ "title": "Data",+ "type": "array"+ },+ "has_more": {+ "title": "Has More",+ "type": "boolean"+ },+ "next": {+ "anyOf": [+ {+ "maxLength": 4096,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Next"+ }+ },+ "required": ["data", "has_more", "next"],+ "title": "SourceReportPage",+ "type": "object"+ },+ "SourceReportSummary": {+ "additionalProperties": false,+ "properties": {+ "id": {+ "pattern": "^aif_[0-9a-f]{64}$",+ "title": "Id",+ "type": "string"+ },+ "object": {+ "const": "security.source_report_summary",+ "default": "security.source_report_summary",+ "title": "Object",+ "type": "string"+ },+ "origin": {+ "const": "imported",+ "default": "imported",+ "title": "Origin",+ "type": "string"+ },+ "repo_id": {+ "title": "Repo Id",+ "type": "string"+ },+ "repo_connector_id": {+ "title": "Repo Connector Id",+ "type": "string"+ },+ "environment_id": {+ "title": "Environment Id",+ "type": "string"+ },+ "canonical_finding_id": {+ "pattern": "^acf_[0-9a-f]{32}$",+ "title": "Canonical Finding Id",+ "type": "string"+ },+ "source": {+ "$ref": "#/$defs/ImportSource"+ },+ "source_finding_id": {+ "title": "Source Finding Id",+ "type": "string"+ },+ "observation_id": {+ "pattern": "^aio_[0-9a-f]{64}$",+ "title": "Observation Id",+ "type": "string"+ },+ "version": {+ "minimum": 1,+ "title": "Version",+ "type": "integer"+ },+ "title": {+ "title": "Title",+ "type": "string"+ },+ "severity": {+ "enum": [+ "critical",+ "high",+ "medium",+ "low",+ "informational",+ "unknown"+ ],+ "title": "Severity",+ "type": "string"+ },+ "source_updated_at": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Source Updated At"+ },+ "assessment": {+ "$ref": "#/$defs/ImportedAssessment"+ },+ "created_at": {+ "title": "Created At",+ "type": "integer"+ },+ "updated_at": {+ "title": "Updated At",+ "type": "integer"+ }+ },+ "required": [+ "id",+ "repo_id",+ "repo_connector_id",+ "environment_id",+ "canonical_finding_id",+ "source",+ "source_finding_id",+ "observation_id",+ "version",+ "title",+ "severity",+ "source_updated_at",+ "created_at",+ "updated_at"+ ],+ "title": "SourceReportSummary",+ "type": "object"+ }+ },+ "additionalProperties": false,+ "description": "Schema export root; transport endpoints return the individual models.",+ "properties": {+ "request": {+ "$ref": "#/$defs/FindingImportRequest"+ },+ "receipt": {+ "$ref": "#/$defs/FindingImportReceipt"+ },+ "repositories": {+ "$ref": "#/$defs/ImportRepositoryPage"+ },+ "source_report": {+ "$ref": "#/$defs/SourceReport"+ },+ "source_reports": {+ "$ref": "#/$defs/SourceReportPage"+ }+ },+ "required": [+ "request",+ "receipt",+ "repositories",+ "source_report",+ "source_reports"+ ],+ "title": "ExternalFindingContracts",+ "type": "object"+}diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjsindex 9745f7ebc..2aba2953a 100644--- a/sdk/typescript/scripts/check-package.mjs+++ b/sdk/typescript/scripts/check-package.mjs@@ -113,6 +113,7 @@ function validatePackagePaths(entries) {"package/dist/index.d.ts","package/dist/cli.js","package/schemas/project-config.schema.json",+ "package/schemas/external-findings.schema.json","package/_bundled_plugin/.codex-plugin/plugin.json",];diff --git a/sdk/typescript/scripts/fixtures/package-consumer.ts b/sdk/typescript/scripts/fixtures/package-consumer.tsindex 062823f0f..3ee57f218 100644--- a/sdk/typescript/scripts/fixtures/package-consumer.ts+++ b/sdk/typescript/scripts/fixtures/package-consumer.ts@@ -1,5 +1,11 @@import {CodexSecurity,+ prepareExternalPublication,+ prepareNormalizedExternalPublication,+ type ExternalFindings,+ type ExternalPublicationOptions,+ type NormalizedExternalPublicationOptions,+ type ExternalPublicationResult,DiffTarget,classifySeverity,classifyScanSeverity,@@ -282,6 +288,30 @@ export async function dedupeRecords(return await deduplicateRecords(input, { reviewRunner, signal });}+export async function externalPublication(+ file: string,+ input: ExternalFindings,+ options: ExternalPublicationOptions,+): Promise<ExternalPublicationResult> {+ const fromFile = await prepareExternalPublication(file, options);+ fromFile.preview.requests[0]?.source.provider satisfies+ "wiz" | "endor" | "snyk" | "github" | "semgrep" | undefined;+ const prepared = await prepareNormalizedExternalPublication(input, options);+ return prepared.publish();+}++export async function publishNormalizedVendorEvidence(+ input: ExternalFindings,+): Promise<ExternalPublicationResult> {+ const options: NormalizedExternalPublicationOptions = {+ provider: "endor",+ sourceKey: "example-namespace/example-project/main",+ repository: "https://github.com/example/project",+ };+ const prepared = await prepareNormalizedExternalPublication(input, options);+ return prepared.publish();+}+export const ownerVariants: OwnerSuggestion["owner"][] = [{ name: "Alex Example", email: "[email protected]" },{ kind: "person", provider: "github", handle: "example-user" },diff --git a/sdk/typescript/scripts/generate-external-import-models.cjs b/sdk/typescript/scripts/generate-external-import-models.cjsnew file mode 100644index 000000000..cec33f043--- /dev/null+++ b/sdk/typescript/scripts/generate-external-import-models.cjs@@ -0,0 +1,35 @@+const { readFileSync, writeFileSync } = require("node:fs");+const { resolve } = require("node:path");+const { compile } = require("json-schema-to-typescript");+const { format } = require("prettier");++async function generate() {+ const schema = JSON.parse(+ readFileSync(+ resolve(__dirname, "../schemas/external-findings.schema.json"),+ "utf8",+ ),+ );+ const types = await compile(schema, "ExternalFindingContracts", {+ bannerComment:+ "/* Generated from schemas/external-findings.schema.json. Run pnpm generate:external-import-models. */",+ format: false,+ ignoreMinAndMaxItems: true,+ unknownAny: true,+ });+ const output = await format(+ `${types}\nexport type ExternalFindingEvidence = ImportedFindingEvidence;\n`,+ { parser: "typescript" },+ );+ const target = resolve(__dirname, "../src/external-import-models.ts");+ if (process.argv.includes("--check")) {+ if (readFileSync(target, "utf8").replaceAll("\r\n", "\n") !== output)+ throw new Error(+ "External import models are stale. Run pnpm generate:external-import-models.",+ );+ } else writeFileSync(target, output);+}+generate().catch((error) => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex a7c8df98b..ad7d207f4 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -21,7 +21,14 @@ const distModules = ["severity-store","severity-review","default-severity-rubric",+ "cloud-endpoint","cloud-publish",+ "external-findings",+ "scanner-import",+ "external-findings-publish",+ "external-import-contract",+ "external-import-models",+ "wiz-findings","codex-prompt","codex-sdk-environment","component-plan",diff --git a/sdk/typescript/scripts/smoke-package.mjs b/sdk/typescript/scripts/smoke-package.mjsindex 7145aa561..236dca3ea 100644--- a/sdk/typescript/scripts/smoke-package.mjs+++ b/sdk/typescript/scripts/smoke-package.mjs@@ -395,7 +395,7 @@ try {"--input-type=module","--eval",`const sdk = await import(${JSON.stringify(packageManifest.name)});- for (const name of ["CodexSecurity", "publishScan", "publishScanToCustom", "checkScanPublication", "deduplicateScan", "deduplicateRecords", "classifySeverity", "classifyScanSeverity", "classifyScanDirectorySeverity", "matchScanFindings", "securityPolicyDiff", "loadProjectConfig", "resolveProjectConfig"]) {+ for (const name of ["CodexSecurity", "publishScan", "publishScanToCustom", "checkScanPublication", "deduplicateScan", "deduplicateRecords", "classifySeverity", "classifyScanSeverity", "classifyScanDirectorySeverity", "matchScanFindings", "securityPolicyDiff", "loadProjectConfig", "resolveProjectConfig", "prepareExternalPublication", "prepareNormalizedExternalPublication"]) {if (typeof sdk[name] !== "function") {throw new Error("The installed package does not export " + name + ".");}diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 5f94b0774..82a3eae02 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -104,6 +104,12 @@ import { isRecord as isJsonObject } from "./record.js";import { suggestOwnersInternal } from "./suggest-owners.js";import { parseImportedFindings } from "./findings-import.js";import { publishScanToCustom } from "./custom-publish.js";+import {+ ExternalPublicationError,+ prepareExternalPublication,+ type ExternalPublicationProgress,+ type ExternalPublicationResult,+} from "./external-findings-publish.js";import {publishPatchReview,resolvePatchReviewPublisher,@@ -605,6 +611,36 @@ function publicationIssueUrl(value: string | undefined): string | undefined {return value;}+function renderExternalPublicationSummary(+ result: ExternalPublicationResult,+): string {+ return [+ `Import ${result.status}.`,+ `Submission totals — Created: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Failed: ${result.counts.error}`,+ `Excluded: ${result.excluded.length} Awaiting acknowledgement: ${result.unacknowledged} Verified: ${result.verified}`,+ ...result.failures.map(+ (item) =>+ `Failed ${diagnosticValue(item.source_finding_id)} (${item.code}): ${diagnosticValue(item.message)}`,+ ),+ ...result.excluded.map(+ (item) =>+ `Excluded item ${item.position}${item.source_finding_id ? ` (${diagnosticValue(item.source_finding_id)})` : ""}: ${diagnosticValue(item.reason)}`,+ ),+ ...(result.savedSubmission+ ? [`Saved submission: ${diagnosticValue(result.savedSubmission)}`]+ : []),+ ...(result.status === "interrupted"+ ? []+ : [+ "Imported evidence remains not assessed by Codex.",+ result.cloudUrl+ ? `View Cloud repository: ${diagnosticValue(result.cloudUrl)}`+ : "Open the repository in Codex Security Cloud.",+ ]),+ "",+ ].join("\n");+}+function renderPublicationSummary(result: PublishScanResult,color: boolean,@@ -1151,6 +1187,7 @@ interface CliDependencies {scanInput?: ConstructorParameters<typeof ScanDashboard>[1]["input"];publishPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select"> &Partial<Pick<BulkScanPrompt, "checkbox">>;+ externalPublicationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "confirm">;checkScanPublication?: typeof checkScanPublication;publishScan?: typeof publishScan;deduplicateScan?: typeof deduplicateScanInternal;@@ -1976,7 +2013,7 @@ export async function main(let renderedOutput: string | undefined;let structuredError = false;let failedResultOutput:- { format: "json" | "jsonl"; message: string } | undefined;+ { format: "json" | "jsonl"; code?: string; message: string } | undefined;let filteredScanFailure:{ format: string; data: Record<string, unknown> } | undefined;const finishScan = (@@ -3440,6 +3477,204 @@ export async function main(});},});+ publication.command("findings", {+ description:+ "Preview and import selected Wiz repository findings to Cloud.",+ hint: "Supply a package vulnerability JSON report, named SAST/repository-secret/IaC JSON collections with repository metadata, or normalized JSONL. Gzip is supported; CSV, scan events, workload secrets, and cloud configuration exports are not. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to cloud --repository https://github.com/example/project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",+ destructive: true,+ mcp: false,+ args: z.object({+ file: z+ .string()+ .describe(+ "Saved Wiz finding collections, package vulnerability JSON, or normalized JSONL.",+ ),+ }),+ options: z.object({+ to: z.literal("cloud").describe("Publication destination."),+ repository: optionValue("--repository").describe(+ "Authorized Cloud repository ID or repository URL copied from Cloud.",+ ),+ provider: z+ .literal("wiz")+ .describe("Vendor that produced these findings."),+ sourceKey: optionValue("--source-key").describe(+ "Stable vendor tenant and finding namespace; not a project selection filter.",+ ),+ dryRun: z+ .boolean()+ .default(false)+ .describe(+ "Read and preview the destination and findings without uploading.",+ ),+ yes: z+ .boolean()+ .default(false)+ .describe(+ "Confirm publication of the previewed input without a terminal prompt.",+ ),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args, options, format, formatExplicit, error: incurError }) {+ return await withTerminalErrorsHandled(errorOutput, async () => {+ const writeDiagnostic = (message: string): void =>+ notify(() => errorOutput.write(message));+ if (+ argv.includes("--full-output") &&+ format !== "json" &&+ format !== "jsonl"+ ) {+ structuredError = true;+ exitCode = 2;+ return incurError({+ code: "INVALID_ARGUMENTS",+ message:+ "Finding imports support --full-output with --format json or --format jsonl. Choose one of those formats or omit --full-output.",+ exitCode,+ });+ }+ const controller = new AbortController();+ const removeSignals = listenForAbort(dependencies, controller);+ const structured = formatExplicit && format !== "toon";+ const humanSummary =+ format === "toon" &&+ !formatExplicit &&+ !argv.some((argument) => OUTPUT_OPTION.test(argument));+ let lastProgress = "";+ const onProgress = (event: ExternalPublicationProgress) => {+ if (errorOutput.isTTY !== true) return;+ const step = event.total+ ? Math.floor((event.completed * 10) / event.total)+ : 0;+ const key = `${event.phase}:${step}`;+ if (key === lastProgress) return;+ lastProgress = key;+ const labels = {+ reading: "Reading selected findings",+ discovering: "Checking Cloud account and repository",+ preparing: "Preparing findings",+ waiting: "Waiting for publication access",+ uploading: "Acknowledged findings",+ verifying: "Verifying source records",+ };+ writeDiagnostic(+ `${labels[event.phase]}${event.total === undefined ? "..." : `: ${event.completed}/${event.total}`}\n`,+ );+ };+ try {+ const prepared = await prepareExternalPublication(+ resolveCliPath(dependencies.currentDirectory(), args.file),+ options,+ {+ environment: dependencies.environment,+ fetch: dependencies.cloudFetch,+ signal: controller.signal,+ onProgress,+ },+ );+ const { preview } = prepared;+ const showPreview = () => {+ writeDiagnostic(+ `Cloud API: ${diagnosticValue(preview.cloudApiUrl)}\nAccount: ${diagnosticValue(preview.accountId)}\nDestination: ${diagnosticValue(preview.destination.url)} (${diagnosticValue(preview.destination.id)})\nEnvironment: ${[...new Set(preview.requests.map((request) => request.repository.environment_id))].map(diagnosticValue).join(", ")}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}${preview.resumed ? "\nResuming the saved submission." : ""}\n`,+ );+ if (preview.cloudUrl)+ writeDiagnostic(+ `Cloud app: ${diagnosticValue(preview.cloudUrl)}\n`,+ );+ for (const excluded of preview.excluded)+ writeDiagnostic(+ `Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`,+ );+ writeDiagnostic(+ `Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\n`,+ );+ const severities = new Map<string, number>();+ for (const finding of preview.findings)+ severities.set(+ finding.evidence.severity,+ (severities.get(finding.evidence.severity) ?? 0) + 1,+ );+ writeDiagnostic(+ `Severities: ${[...severities].map(([severity, count]) => `${severity}: ${count}`).join(" ")}\n`,+ );+ for (const finding of preview.findings.slice(0, 5))+ writeDiagnostic(+ ` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`,+ );+ if (preview.findings.length > 5)+ writeDiagnostic(+ `Showing 5 of ${preview.findings.length} findings.\n`,+ );+ writeDiagnostic(+ "Use --dry-run --format json to inspect all normalized findings and the complete evidence before uploading.\n",+ );+ };+ if (!structured) showPreview();+ if (options.dryRun) {+ if (humanSummary)+ renderedOutput = "Dry run complete. No findings uploaded.\n";+ return { ...preview, dryRun: true };+ }+ if (!options.yes) {+ const prompt =+ dependencies.externalPublicationPrompt ??+ createTerminalPrompt(errorOutput);+ if (!prompt.isInteractive())+ throw new CodexSecurityError(+ "Publication needs confirmation. Run --dry-run, review the results, then use --yes to approve this input.",+ );+ if (structured) showPreview();+ if (+ !(await prompt.confirm(+ `Publish these ${preview.findings.length} findings${preview.excluded.length ? ` and skip ${preview.excluded.length} excluded records` : ""}?`,+ false,+ controller.signal,+ ))+ ) {+ if (humanSummary) renderedOutput = "No findings published.\n";+ return { published: false, preview };+ }+ }+ const result = await prepared.publish();+ if (result.status === "partial") exitCode = 1;+ if (humanSummary)+ renderedOutput = renderExternalPublicationSummary(result);+ else if (!structured)+ writeDiagnostic(renderExternalPublicationSummary(result));+ return { ...result };+ } catch (error) {+ if (+ argv.includes("--full-output") &&+ (format === "json" || format === "jsonl")+ )+ failedResultOutput = {+ format,+ code: "IMPORT_FAILED",+ message: diagnosticValue(error),+ };+ reportPublicationError(+ diagnosticValue(error),+ controller.signal.aborted ? controller.signal.reason : undefined,+ );+ if (error instanceof ExternalPublicationError) {+ if (humanSummary)+ renderedOutput = renderExternalPublicationSummary(error.result);+ return { ...error.result };+ }+ const failure = { status: "failed", error: diagnosticValue(error) };+ if (+ (format === "json" || format === "jsonl") &&+ !argv.includes("--full-output") &&+ argv.some((argument) => /^--filter-output(?:=|$)/u.test(argument))+ )+ filteredScanFailure = { format, data: failure };+ return structured ? failure : undefined;+ } finally {+ removeSignals();+ }+ });+ },+ });publication.command("check", {description:"Check saved scan history and Linear access without creating issues.",@@ -6550,7 +6785,7 @@ export async function main(...envelope,ok: false,error: {- code: "SCAN_FAILED",+ code: failedResultOutput.code ?? "SCAN_FAILED",message: failedResultOutput.message,},},diff --git a/sdk/typescript/src/cloud-endpoint.ts b/sdk/typescript/src/cloud-endpoint.tsnew file mode 100644index 000000000..3f3cc308b--- /dev/null+++ b/sdk/typescript/src/cloud-endpoint.ts@@ -0,0 +1,71 @@+import { isIP } from "node:net";+import { CodexSecurityError } from "./errors.js";++export const DEFAULT_CLOUD_BASE_URL =+ "https://chatgpt.com/backend-api/aardvark";++const CLOUD_APP_PATH =+ "/mcp-app/connector_openai_defense_factory/open_defense_factory";++/** Custom deployments can serve their UI separately from the authenticated API. */+export function cloudFindingsUrl(+ environment: NodeJS.ProcessEnv,+ repositoryId: string,+): string | undefined {+ const configured = environment["CODEX_SECURITY_CLOUD_WEB_URL"];+ const api = new URL(cloudBaseUrl(environment));+ const hosted = api.href === DEFAULT_CLOUD_BASE_URL;+ if (configured === undefined && !hosted) return undefined;+ let url: URL;+ try {+ url = new URL(configured?.trim() ?? `${api.origin}${CLOUD_APP_PATH}`);+ } catch {+ throw new CodexSecurityError(+ "CODEX_SECURITY_CLOUD_WEB_URL must be an absolute HTTP(S) Cloud app URL.",+ );+ }+ if (+ !["https:", "http:"].includes(url.protocol) ||+ url.username ||+ url.password+ )+ throw new CodexSecurityError(+ "CODEX_SECURITY_CLOUD_WEB_URL must be an HTTP(S) Cloud app URL without credentials.",+ );+ url.hash = `/repositories/${encodeURIComponent(repositoryId)}/findings`;+ return url.href;+}++/** Resolve the deployment once so discovery, writes, and retries share a host. */+export function cloudBaseUrl(environment: NodeJS.ProcessEnv): string {+ const configured = environment["CODEX_SECURITY_CLOUD_BASE_URL"];+ if (configured === undefined) return DEFAULT_CLOUD_BASE_URL;+ let url: URL;+ try {+ url = new URL(configured.trim());+ } catch {+ throw new CodexSecurityError(+ "CODEX_SECURITY_CLOUD_BASE_URL must be an absolute HTTP(S) Cloud API base URL.",+ );+ }+ if (+ !["https:", "http:"].includes(url.protocol) ||+ url.username ||+ url.password ||+ url.search ||+ url.hash+ )+ throw new CodexSecurityError(+ "CODEX_SECURITY_CLOUD_BASE_URL must be an HTTP(S) Cloud API base URL without credentials, a query, or a fragment.",+ );+ if (+ url.protocol === "http:" &&+ url.hostname !== "localhost" &&+ url.hostname !== "[::1]" &&+ !(isIP(url.hostname) === 4 && url.hostname.startsWith("127."))+ )+ throw new CodexSecurityError(+ "CODEX_SECURITY_CLOUD_BASE_URL requires HTTPS for remote Cloud APIs; HTTP is supported only for loopback development.",+ );+ return url.href.replace(/\/+$/u, "");+}diff --git a/sdk/typescript/src/cloud-publish.ts b/sdk/typescript/src/cloud-publish.tsindex 4829693c8..e2c3c04fe 100644--- a/sdk/typescript/src/cloud-publish.ts+++ b/sdk/typescript/src/cloud-publish.ts@@ -24,9 +24,7 @@ import {expandHome,} from "./runtime.js";import { VERSION } from "./version.js";--const CLOUD_PUBLISH_URL =- "https://chatgpt.com/backend-api/aardvark/cli/findings";+import { cloudBaseUrl } from "./cloud-endpoint.js";const CHATGPT_LOGIN_REQUIRED ="Cloud publication requires a ChatGPT login already available to Codex Security. Run a scan or sign in with ChatGPT using Codex file credential storage, then retry.";@@ -192,12 +190,11 @@ async function publishCloudPayload(findings,};}- const credentials = await readCloudCredentials(- dependencies.environment ?? process.env,- );+ const environment = dependencies.environment ?? process.env;const publishUrl =- dependencies.environment?.["CODEX_SECURITY_CLOUD_PUBLISH_URL"]?.trim() ||- CLOUD_PUBLISH_URL;+ environment["CODEX_SECURITY_CLOUD_PUBLISH_URL"]?.trim() ||+ `${cloudBaseUrl(environment)}/cli/findings`;+ const credentials = await readCloudCredentials(environment);const timeout = AbortSignal.timeout(30_000);const signal = dependencies.signal? AbortSignal.any([dependencies.signal, timeout])@@ -268,7 +265,8 @@ async function publishCloudPayload(};}-async function readCloudCredentials(environment: NodeJS.ProcessEnv) {+/** @internal Shared sign-in for local Cloud publishers. */+export async function readCloudCredentials(environment: NodeJS.ProcessEnv) {const configuredHome = environment["CODEX_HOME"];let home = expandHome(configuredHome?.trim() ? configuredHome : "~/.codex",diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.tsnew file mode 100644index 000000000..ce64a0f52--- /dev/null+++ b/sdk/typescript/src/external-findings-publish.ts@@ -0,0 +1,1009 @@+import { hash, randomUUID } from "node:crypto";+import { chmodSync } from "node:fs";+import {+ lstat,+ mkdir,+ open,+ readFile,+ readdir,+ rename,+ rm,+} from "node:fs/promises";+import { createRequire } from "node:module";+import { join } from "node:path";+import { setTimeout as delay } from "node:timers/promises";+import { readCloudCredentials } from "./cloud-publish.js";+import {+ cloudBaseUrl,+ cloudFindingsUrl,+ DEFAULT_CLOUD_BASE_URL,+} from "./cloud-endpoint.js";+import { CodexSecurityError } from "./errors.js";+import {+ codexSecurityStateDirectory,+ createWindowsOutputDirectory,+ validatePreparedOutputDir,+} from "./runtime.js";+import { readVendorFindingsForPublication } from "./wiz-findings.js";+import type {+ ExternalFindings,+ ExternalPublicationInput,+} from "./external-findings.js";+import {+ cloudRepositoryUrlKey,+ validateImportRequest,+ validateExternalEvidence,+ validateImportReceipt,+ validateRepositories,+ validateSourceReports,+ validateSourceReport,+} from "./external-import-contract.js";+import type {+ FindingImportRequest,+ FindingImportReceipt,+ ImportRepository,+ SourceReportSummary,+} from "./external-import-models.js";++const MAX_REQUEST_BYTES = 5 * 1024 * 1024;++/** Source and destination for evidence already normalized to the Cloud contract. */+export interface NormalizedExternalPublicationOptions {+ repository: string;+ provider: FindingImportRequest["source"]["provider"];+ sourceKey: string;+}++/** File readers accept the vendor formats installed in this SDK. */+export interface ExternalPublicationOptions extends NormalizedExternalPublicationOptions {+ provider: "wiz";+}++/** Optional transport, account, cancellation, and progress hooks. */+export interface ExternalPublicationDependencies {+ environment?: NodeJS.ProcessEnv;+ fetch?: (url: string, options: RequestInit) => Promise<Response>;+ credentials?: () => Promise<{ access_token: string; account_id: string }>;+ signal?: AbortSignal;+ onProgress?: (event: ExternalPublicationProgress) => void;+}++export interface ExternalPublicationProgress {+ phase:+ | "reading"+ | "discovering"+ | "preparing"+ | "waiting"+ | "uploading"+ | "verifying";+ completed: number;+ total?: number;+}++/** Counts describe acknowledged receipts, even when later transport or readback fails. */+export interface ExternalPublicationResult {+ cloudApiUrl: string;+ cloudUrl?: string;+ status: "complete" | "partial" | "interrupted";+ read: number;+ ready: number;+ excluded: ExternalFindings["excluded"];+ receipts: FindingImportReceipt[];+ counts: Required<FindingImportReceipt["counts"]>;+ failures: { source_finding_id: string; code: string; message: string }[];+ unacknowledged: number;+ verified: number;+ error?: string;+ savedSubmission?: string;+}++/** Preserve accepted work in CLI JSON output when publication cannot finish. */+export class ExternalPublicationError extends CodexSecurityError {+ constructor(+ message: string,+ public readonly result: ExternalPublicationResult,+ cause: unknown,+ ) {+ super(message, { cause });+ }+}++interface SavedSubmission {+ accountId: string;+ requests: FindingImportRequest[];+ receipts?: FindingImportReceipt[];+ inputProjection?: { inputDigest: string; savedEvidenceDigest: string };+}++export interface ExternalPublicationPreview extends ExternalFindings {+ cloudApiUrl: string;+ cloudUrl?: string;+ accountId: string;+ destination: ImportRepository;+ source: FindingImportRequest["source"];+ resumed: boolean;+ requests: FindingImportRequest[];+}++export interface PreparedExternalPublication {+ preview: ExternalPublicationPreview;+ publish(): Promise<ExternalPublicationResult>;+}++// Limit read concurrency to avoid one network round trip per finding in series.+// Wait for the entire batch on failure so callers never outlive their read tasks.+async function readInBatches<T, U>(+ items: T[],+ read: (item: T) => Promise<U>,+): Promise<U[]> {+ const output: U[] = [];+ for (let start = 0; start < items.length; start += 4) {+ const batch = await Promise.allSettled(+ items.slice(start, start + 4).map(read),+ );+ for (const result of batch) {+ if (result.status === "rejected") throw result.reason;+ output.push(result.value);+ }+ }+ return output;+}++function canonicalJson(+ value: unknown,+ compareKeys?: (left: string, right: string) => number,+): string {+ return JSON.stringify(value, (_key, child: unknown) => {+ if (child !== null && typeof child === "object" && !Array.isArray(child)) {+ const record = child as Record<string, unknown>;+ return Object.fromEntries(+ Object.keys(record)+ .sort(compareKeys)+ .map((key) => [key, record[key]]),+ );+ }+ return child;+ });+}++function sameSubmission(+ left: SavedSubmission,+ right: SavedSubmission,+): boolean {+ return (+ left.accountId === right.accountId &&+ canonicalJson(left.requests) === canonicalJson(right.requests)+ );+}++function submissionFindings(+ requests: readonly FindingImportRequest[],+): ExternalFindings["findings"] {+ return requests.flatMap((batch) =>+ batch.items.map(({ source_finding_id, evidence }) => ({+ source_finding_id,+ evidence,+ })),+ );+}++function sameFindingSelection(+ left: ExternalFindings["findings"],+ right: ExternalFindings["findings"],+): boolean {+ return (+ left.length === right.length &&+ left.every(+ (finding, index) =>+ finding.source_finding_id === right[index]!.source_finding_id,+ )+ );+}++async function readOptionalFile(path: string): Promise<string | undefined> {+ return readFile(path, "utf8").catch((error: NodeJS.ErrnoException) => {+ if (error.code === "ENOENT") return undefined;+ throw error;+ });+}++async function writeAtomicJson(path: string, value: unknown): Promise<void> {+ const temporary = `${path}.${randomUUID()}.tmp`;+ try {+ const file = await open(temporary, "wx", 0o600);+ try {+ await file.writeFile(JSON.stringify(value));+ await file.sync();+ } finally {+ await file.close();+ }+ await rename(temporary, path);+ } finally {+ await rm(temporary, { force: true });+ }+}++function sourcePath(repository: ImportRepository): string {+ return `/repository_connectors/${encodeURIComponent(repository.repo_connector_id)}/repositories/${encodeURIComponent(repository.id)}/source_reports`;+}++class CloudImportError extends CodexSecurityError {+ constructor(+ public readonly status: number,+ message: string,+ ) {+ super(message);+ }+}++function validatePublicationReceipt(+ value: unknown,+ batch: FindingImportRequest,+): FindingImportReceipt {+ const receipt = validateImportReceipt(value);+ const batchItems = new Map(batch.items.map((item) => [item.client_id, item]));+ if (+ receipt.id !== batch.request_id ||+ canonicalJson(receipt.repository) !== canonicalJson(batch.repository) ||+ canonicalJson(receipt.source) !== canonicalJson(batch.source) ||+ receipt.item_count !== batch.items.length ||+ receipt.results.length !== batch.items.length ||+ new Set(receipt.results.map((item) => item.client_id)).size !==+ batch.items.length ||+ receipt.results.some((item) => !batchItems.has(item.client_id))+ )+ throw new CodexSecurityError(+ "Cloud returned a receipt for a different publication.",+ );+ const actual = { created: 0, updated: 0, unchanged: 0, error: 0 };+ for (const result of receipt.results) {+ actual[result.outcome]++;+ if (result.outcome === "error") {+ if (+ !result.error ||+ result.source_report_id !== null ||+ result.observation_id !== null ||+ result.canonical_finding_id !== null ||+ result.version !== null+ )+ throw new CodexSecurityError(+ "Cloud returned inconsistent item error fields.",+ );+ } else if (+ result.error !== null ||+ !result.source_report_id ||+ !result.observation_id ||+ !result.canonical_finding_id ||+ result.version === null+ )+ throw new CodexSecurityError(+ "Cloud returned an incomplete saved finding.",+ );+ }+ if (canonicalJson(receipt.counts) !== canonicalJson(actual))+ throw new CodexSecurityError(+ "Cloud returned inconsistent publication counts.",+ );+ return receipt;+}++async function withImportLock<T>(+ state: string,+ key: string,+ signal: AbortSignal | undefined,+ operation: () => Promise<T>,+): Promise<T> {+ if (process.platform === "win32")+ await createWindowsOutputDirectory(state, true);+ else await mkdir(state, { recursive: true, mode: 0o700 });+ await validatePreparedOutputDir(state, undefined, true);+ const path = join(state, `${key}.lock.sqlite`);+ const metadata = await lstat(path).catch((error: NodeJS.ErrnoException) => {+ if (error.code === "ENOENT") return undefined;+ throw error;+ });+ if (metadata && !metadata.isFile())+ throw new CodexSecurityError("The publication lock is not a regular file.");+ const require = createRequire(import.meta.url);+ const Database = (+ process.versions["bun"]+ ? require("bun:sqlite").Database+ : require("node:sqlite").DatabaseSync+ ) as new (path: string) => { exec(sql: string): void; close(): void };+ const guard = new Database(path);+ try {+ if (process.platform !== "win32") chmodSync(path, 0o600);+ guard.exec("PRAGMA busy_timeout = 0");+ for (;;) {+ signal?.throwIfAborted();+ try {+ // Keep this inode across invocations. SQLite releases the transaction+ // on process exit, so a paused publisher cannot lose its lock to a lease.+ guard.exec("BEGIN EXCLUSIVE");+ break;+ } catch (error) {+ const sqliteError = error as { code?: string; errcode?: number };+ if (sqliteError.errcode !== 5 && sqliteError.code !== "SQLITE_BUSY")+ throw error;+ await delay(50, undefined, { signal });+ }+ }+ return await operation();+ } finally {+ guard.close();+ }+}++export async function prepareExternalPublication(+ path: string,+ options: ExternalPublicationOptions,+ dependencies: ExternalPublicationDependencies = {},+): Promise<PreparedExternalPublication> {+ const input = await readVendorFindingsForPublication(path);+ return preparePublicationInput(input, options, dependencies);+}++/** Prepare normalized provider evidence without reading a vendor export. */+export async function prepareNormalizedExternalPublication(+ input: ExternalFindings,+ options: NormalizedExternalPublicationOptions,+ dependencies: ExternalPublicationDependencies = {},+): Promise<PreparedExternalPublication> {+ // Validation adds Cloud defaults; leave the caller's objects unchanged.+ const current = structuredClone(input);+ // structuredClone preserves aliases. Detach every raw record before adding+ // typed defaults, including aliases shared with another finding's evidence.+ for (const finding of current.findings)+ if (finding.evidence.source_data !== undefined)+ finding.evidence.source_data = structuredClone(+ finding.evidence.source_data,+ );+ const identities = new Set<string>();+ for (const finding of current.findings) {+ const id = finding.source_finding_id;+ if (!id.trim() || id.includes("\0") || Buffer.byteLength(id) > 512)+ throw new CodexSecurityError(+ "Source finding id must contain 1–512 UTF-8 bytes and no NUL characters.",+ );+ if (identities.has(id))+ throw new CodexSecurityError(+ `Duplicate source finding id ${JSON.stringify(id)}.`,+ );+ identities.add(id);+ finding.evidence = validateExternalEvidence(finding.evidence);+ }+ return preparePublicationInput(+ {+ current,+ legacy: current,+ currentIdentity: current.findings,+ legacyIdentity: current.findings,+ },+ options,+ dependencies,+ );+}++async function preparePublicationInput(+ input: ExternalPublicationInput,+ options: NormalizedExternalPublicationOptions,+ dependencies: ExternalPublicationDependencies,+): Promise<PreparedExternalPublication> {+ const progress = (event: ExternalPublicationProgress): void => {+ try {+ dependencies.onProgress?.(event);+ } catch {+ // Optional progress must not interrupt preparation or publication.+ }+ };+ if (+ !options.sourceKey.trim() ||+ options.sourceKey.includes("\0") ||+ Buffer.byteLength(options.sourceKey) > 512+ ) {+ throw new CodexSecurityError(+ "The source key must contain 1–512 UTF-8 bytes and no NUL characters. Use a stable scanner organization/project/branch namespace across imports.",+ );+ }+ progress({ phase: "reading", completed: 0 });+ const {+ current: parsed,+ legacy: legacyParsed,+ currentIdentity,+ legacyIdentity,+ } = input;+ if (parsed.findings.length === 0) {+ throw new CodexSecurityError(+ `No supported findings are ready to publish. ${parsed.excluded.map((item) => `Item ${item.position}: ${item.reason}`).join(" ")}`,+ );+ }+ progress({ phase: "discovering", completed: 0 });+ const environment = dependencies.environment ?? process.env;+ const apiBaseUrl = cloudBaseUrl(environment);+ const cloudApiUrl = `${apiBaseUrl}/external`;+ // Validate the configured return destination before authentication or uploads.+ cloudFindingsUrl(environment, options.repository);+ const credentials = await (+ dependencies.credentials ?? (() => readCloudCredentials(environment))+ )();+ async function request(+ endpoint: string,+ body?: FindingImportRequest,+ ): Promise<unknown> {+ dependencies.signal?.throwIfAborted();+ // Allow upload and response transport around the server's publication budget.+ const timeout = AbortSignal.timeout(body ? 60_000 : 30_000);+ const response = await (dependencies.fetch ?? globalThis.fetch)(+ `${cloudApiUrl}${endpoint}`,+ {+ method: body ? "POST" : "GET",+ headers: {+ Authorization: `Bearer ${credentials.access_token}`,+ "ChatGPT-Account-ID": credentials.account_id,+ Accept: "application/json",+ ...(body ? { "Content-Type": "application/json" } : {}),+ },+ ...(body ? { body: JSON.stringify(body) } : {}),+ redirect: "error",+ signal: dependencies.signal+ ? AbortSignal.any([dependencies.signal, timeout])+ : timeout,+ },+ );+ if (!response.ok) {+ const payload = (await response.json().catch(() => null)) as {+ error?: { message?: string };+ } | null;+ const retryAfter = response.headers.get("Retry-After");+ throw new CloudImportError(+ response.status,+ `Cloud import failed (HTTP ${response.status}). ${payload?.error?.message ?? response.statusText}${retryAfter ? ` Retry-After: ${retryAfter}.` : ""}`,+ );+ }+ return response.json();+ }+ const destinations: ImportRepository[] = [];+ let page: string | null = null;+ const seenPages = new Set<string>();+ do {+ const result = validateRepositories(+ await request(+ `/repositories?limit=20&repository=${encodeURIComponent(options.repository)}${page ? `&page=${encodeURIComponent(page)}` : ""}`,+ ),+ );+ destinations.push(+ ...result.data.filter(+ (item) =>+ item.id === options.repository ||+ cloudRepositoryUrlKey(item.url) ===+ cloudRepositoryUrlKey(options.repository),+ ),+ );+ page = result.next;+ if (+ result.has_more !== (page !== null) ||+ (page !== null && seenPages.has(page))+ )+ throw new CodexSecurityError(+ "Cloud returned invalid repository pagination.",+ );+ if (page !== null) seenPages.add(page);+ } while (page !== null);+ if (destinations.length !== 1)+ throw new CodexSecurityError(+ destinations.length+ ? "The repository matches multiple connectors. Select an unambiguous Cloud repository."+ : "The destination repository is not available to this Cloud account. Copy its repository URL or ID from Codex Security Cloud and check that you are signed into the intended account.",+ );+ const destination = destinations[0]!;+ const source = { provider: options.provider, source_key: options.sourceKey };+ const state = join(+ codexSecurityStateDirectory(environment),+ "external-finding-publications",+ );+ const checkpointIdentity = [+ // Keep existing production checkpoints readable; other deployments must+ // never share a saved request or receipt with the production default.+ ...(apiBaseUrl === DEFAULT_CLOUD_BASE_URL ? [] : [apiBaseUrl]),+ credentials.account_id,+ destination.id,+ destination.repo_connector_id,+ source,+ ];+ const inputDigest = hash("sha256", canonicalJson(currentIdentity));+ const legacyInputDigest = hash("sha256", canonicalJson(legacyIdentity));+ function validateSaved(serialized: string, legacy = false): SavedSubmission {+ const content = JSON.parse(serialized) as SavedSubmission;+ if (+ content.accountId !== credentials.account_id ||+ !Array.isArray(content.requests) ||+ content.requests.length === 0+ )+ throw new Error("Saved import account or requests do not match.");+ content.requests = content.requests.map(validateImportRequest);+ const savedFindings = submissionFindings(content.requests);+ const savedEvidence = canonicalJson(savedFindings);+ const expected = legacy ? legacyParsed.findings : parsed.findings;+ const matches =+ content.inputProjection !== undefined+ ? sameFindingSelection(savedFindings, expected) &&+ content.inputProjection?.inputDigest ===+ (legacy ? legacyInputDigest : inputDigest) &&+ content.inputProjection?.savedEvidenceDigest ===+ hash("sha256", savedEvidence)+ : savedEvidence === canonicalJson(expected);+ if (!matches)+ throw new Error(+ "Saved import evidence does not match the selected input.",+ );+ for (const submission of content.requests) {+ if (+ submission.repository.id !== destination.id ||+ submission.repository.repo_connector_id !==+ destination.repo_connector_id ||+ canonicalJson(submission.source) !== canonicalJson(source)+ )+ throw new Error("Saved import destination does not match.");+ }+ return content;+ }+ const key = hash(+ "sha256",+ canonicalJson([...checkpointIdentity, currentIdentity]),+ );+ const pendingPath = join(state, `${key}.pending.json`);+ const historicalKey = hash(+ "sha256",+ canonicalJson(+ [...checkpointIdentity, legacyParsed.findings],+ (left, right) => left.localeCompare(right),+ ),+ );+ const legacyKeys = new Set([+ hash("sha256", canonicalJson([...checkpointIdentity, legacyIdentity])),+ historicalKey,+ ]);+ async function rejectUnidentifiedLegacyCheckpoint(): Promise<void> {+ const entries = await readdir(state, { withFileTypes: true }).catch(+ (error: NodeJS.ErrnoException) => {+ if (error.code === "ENOENT") return [];+ throw error;+ },+ );+ if (entries.length) await validatePreparedOutputDir(state, undefined, true);+ for (const entry of entries) {+ if (!entry.isFile() || !/^[a-f0-9]{64}\.pending\.json$/u.test(entry.name))+ continue;+ const candidateKey = entry.name.slice(0, -".pending.json".length);+ if (candidateKey === key || legacyKeys.has(candidateKey)) continue;+ const serialized = await readOptionalFile(join(state, entry.name));+ if (serialized === undefined) continue;+ try {+ // Locale-dependent filenames predate input projections. Later formats+ // must remain isolated by their deployment-bound checkpoint keys.+ const content = JSON.parse(serialized) as SavedSubmission | null;+ if (!content || content.inputProjection !== undefined) continue;+ validateSaved(serialized, true);+ } catch {+ continue;+ }+ // These older bodies contain no deployment identity. Do not guess a+ // destination or replace their immutable request with a fresh publication.+ throw new CodexSecurityError(+ "An older pending import matches this input, but its checkpoint identity could not be established. Resume it using the original deployment and locale before publishing this selection. The saved request was preserved without uploading.",+ );+ }+ }+ let recovered: SavedSubmission | undefined;+ for (const legacyKey of legacyKeys) {+ if (legacyKey === key) continue;+ const legacyPath = join(state, `${legacyKey}.pending.json`);+ const captured = await readOptionalFile(legacyPath);+ if (captured !== undefined) {+ // Preserve requests staged by the earlier locale-based filename format.+ // Hold both publication locks while moving the original checkpoint.+ await withImportLock(state, key, dependencies.signal, async () =>+ withImportLock(state, legacyKey, dependencies.signal, async () => {+ const current = await readOptionalFile(pendingPath);+ const serialized = await readOptionalFile(legacyPath);+ if (current !== undefined) {+ recovered = validateSaved(current);+ if (serialized !== undefined) {+ // A crash may leave both copies after installing the canonical file.+ // Retire only an identical immutable submission, never another request.+ let duplicate: SavedSubmission | null = null;+ try {+ duplicate = JSON.parse(serialized) as SavedSubmission | null;+ } catch (error) {+ if (!(error instanceof SyntaxError)) throw error;+ }+ if (+ duplicate !== null &&+ typeof duplicate === "object" &&+ sameSubmission(duplicate, recovered)+ )+ await rm(legacyPath);+ }+ return;+ }+ // A competing resumer may have completed and removed both paths while+ // this caller waited. Retain its observed immutable request and receipts.+ const content = validateSaved(serialized ?? captured, true);+ if (!sameFindingSelection(legacyParsed.findings, parsed.findings))+ throw new CodexSecurityError(+ "The saved import selects different findings from this input. Resume the original selection before publishing this selection.",+ );+ if (+ content.requests.some(+ (submission) =>+ submission.repository.reset_marker !== destination.reset_marker,+ )+ ) {+ if (serialized !== undefined) await rm(legacyPath);+ throw new CloudImportError(+ 409,+ "The repository was reset after this submission. The saved request was retired without uploading. Review the destination and run the command again to approve a fresh publication.",+ );+ }+ const savedEvidenceDigest =+ content.inputProjection?.savedEvidenceDigest ??+ hash("sha256", canonicalJson(legacyParsed.findings));+ const rebindProjection =+ content.inputProjection !== undefined ||+ savedEvidenceDigest !== inputDigest;+ if (rebindProjection)+ content.inputProjection = { inputDigest, savedEvidenceDigest };+ recovered = content;+ if (serialized === undefined) return;+ if (!rebindProjection) {+ await rename(legacyPath, pendingPath);+ } else {+ // Bind the new input projection to the original immutable evidence,+ // so later inventory reordering still resumes these exact requests.+ await writeAtomicJson(pendingPath, content);+ await rm(legacyPath);+ }+ }),+ );+ }+ }+ const serialized = await readOptionalFile(pendingPath);+ const saved =+ serialized === undefined ? recovered : validateSaved(serialized);+ if (!saved) await rejectUnidentifiedLegacyCheckpoint();+ if (saved) {+ const content = saved;+ for (const submission of content.requests) {+ if (submission.repository.reset_marker !== destination.reset_marker) {+ // The old request is never sent after reset. A subsequent explicit+ // invocation prepares a fresh submission and asks for approval again.+ await withImportLock(state, key, dependencies.signal, async () => {+ const current = await readOptionalFile(pendingPath);+ if (+ current !== undefined &&+ sameSubmission(JSON.parse(current) as SavedSubmission, content)+ )+ await rm(pendingPath);+ });+ throw new CloudImportError(+ 409,+ "The repository was reset after this submission. The saved request was retired without uploading. Review the destination and run the command again to approve a fresh publication.",+ );+ }+ }+ }+ let requests = saved?.requests;+ if (!requests) {+ for (const finding of parsed.findings) {+ const sourceRepository = finding.evidence.details?.repository;+ if (+ sourceRepository &&+ cloudRepositoryUrlKey(sourceRepository.url) !==+ cloudRepositoryUrlKey(destination.url)+ )+ throw new CodexSecurityError(+ `Finding ${JSON.stringify(finding.source_finding_id)} belongs to ${JSON.stringify(sourceRepository.url)}, which does not match the selected Cloud repository ${JSON.stringify(destination.url)}. Verify the source repository mapping before publishing.`,+ );+ }+ let preparedCount = 0;+ progress({+ phase: "preparing",+ completed: 0,+ total: parsed.findings.length,+ });+ const previousReports = await readInBatches(+ parsed.findings,+ async (finding): Promise<SourceReportSummary | undefined> => {+ const query = new URLSearchParams({+ provider: source.provider,+ source_key: source.source_key,+ source_finding_id: finding.source_finding_id,+ limit: "2",+ });+ const summaries = validateSourceReports(+ await request(`${sourcePath(destination)}?${query}`),+ );+ if (summaries.has_more || summaries.data.length > 1)+ throw new CodexSecurityError(+ "Cloud returned more than one report for a source identity.",+ );+ const previous = summaries.data[0];+ if (+ previous &&+ (previous.source_finding_id !== finding.source_finding_id ||+ previous.source.provider !== source.provider ||+ previous.source.source_key !== source.source_key ||+ previous.repo_id !== destination.id ||+ previous.repo_connector_id !== destination.repo_connector_id)+ )+ throw new CodexSecurityError(+ "Cloud returned a different source identity.",+ );+ progress({+ phase: "preparing",+ completed: ++preparedCount,+ total: parsed.findings.length,+ });+ return previous;+ },+ );+ requests = [];+ let current: FindingImportRequest | undefined;+ for (const [index, finding] of parsed.findings.entries()) {+ const previous = previousReports[index];+ const environmentId =+ previous?.environment_id ?? destination.import_environment_id;+ if (environmentId == null)+ throw new CodexSecurityError(+ "Configure an authorized Cloud environment for this repository before importing findings.",+ );+ const repository = {+ id: destination.id,+ repo_connector_id: destination.repo_connector_id,+ environment_id: environmentId,+ reset_marker: destination.reset_marker,+ };+ const item = {+ client_id: `item-${index + 1}`,+ source_finding_id: finding.source_finding_id,+ expected_version: previous?.version ?? 0,+ evidence: finding.evidence,+ };+ if (+ current &&+ (current.repository.environment_id !== environmentId ||+ current.items.length === 100 ||+ Buffer.byteLength(+ JSON.stringify({ ...current, items: [...current.items, item] }),+ ) > MAX_REQUEST_BYTES)+ ) {+ requests.push(validateImportRequest(current));+ current = undefined;+ }+ current ??= { request_id: randomUUID(), repository, source, items: [] };+ current.items.push(item);+ }+ if (current) requests.push(validateImportRequest(current));+ }+ const submission: SavedSubmission = {+ accountId: credentials.account_id,+ requests,+ receipts: saved?.receipts,+ inputProjection: saved?.inputProjection ?? {+ inputDigest,+ savedEvidenceDigest: hash(+ "sha256",+ canonicalJson(submissionFindings(requests)),+ ),+ },+ };+ const preview: ExternalPublicationPreview = {+ ...parsed,+ findings: submissionFindings(requests),+ cloudApiUrl,+ cloudUrl: cloudFindingsUrl(environment, destination.id),+ accountId: credentials.account_id,+ destination,+ source,+ resumed: saved !== undefined,+ requests,+ };+ return {+ preview,+ async publish() {+ progress({ phase: "waiting", completed: 0 });+ const result = (+ acknowledged: FindingImportReceipt[],+ verified: number,+ ): ExternalPublicationResult => {+ const counts = { created: 0, updated: 0, unchanged: 0, error: 0 };+ const failures: ExternalPublicationResult["failures"] = [];+ for (const [index, receipt] of acknowledged.entries()) {+ for (const outcome of Object.keys(counts) as (keyof typeof counts)[])+ counts[outcome] += receipt.counts[outcome] ?? 0;+ const ids = new Map(+ requests[index]!.items.map((item) => [+ item.client_id,+ item.source_finding_id,+ ]),+ );+ for (const item of receipt.results)+ if (item.error)+ failures.push({+ source_finding_id: ids.get(item.client_id)!,+ ...item.error,+ });+ }+ return {+ cloudApiUrl,+ cloudUrl: preview.cloudUrl,+ status:+ parsed.excluded.length || counts.error ? "partial" : "complete",+ read: parsed.read,+ ready: parsed.findings.length,+ excluded: parsed.excluded,+ receipts: acknowledged,+ counts,+ failures,+ unacknowledged:+ parsed.findings.length -+ Object.values(counts).reduce((sum, count) => sum + count, 0),+ verified,+ };+ };+ let acquired = false;+ return await withImportLock(state, key, dependencies.signal, async () => {+ acquired = true;+ // Re-read under the lock to keep checkpoints from another publisher.+ const pending = await readOptionalFile(pendingPath);+ if (pending === undefined && !saved)+ await rejectUnidentifiedLegacyCheckpoint();+ const current =+ pending === undefined+ ? submission+ : (JSON.parse(pending) as SavedSubmission);+ if (!sameSubmission(current, submission))+ throw new CodexSecurityError(+ "Another publication prepared this input. Run the command again to review and resume that saved request.",+ );+ const receipts = (current.receipts ?? []).map(validateImportReceipt);+ if (receipts.length > requests.length)+ throw new CodexSecurityError(+ "Saved publication has more receipts than requests.",+ );+ const acknowledged: FindingImportReceipt[] = [];+ let verified = 0;+ let persisted = pending !== undefined;+ try {+ if (pending === undefined) {+ await writeAtomicJson(pendingPath, submission);+ persisted = true;+ }+ progress({+ phase: "uploading",+ completed: 0,+ total: parsed.findings.length,+ });+ let acknowledgedCount = 0;+ for (const [batchIndex, batch] of requests.entries()) {+ const receipt = validatePublicationReceipt(+ receipts[batchIndex] ??+ (await request("/finding_imports", batch)),+ batch,+ );+ acknowledged.push(receipt);+ acknowledgedCount += receipt.item_count;+ progress({+ phase: "uploading",+ completed: acknowledgedCount,+ total: parsed.findings.length,+ });+ if (batchIndex === receipts.length) {+ receipts.push(receipt);+ // Acknowledged batches must not consume another POST quota on retry.+ // Readback can still resume after this checkpoint without replaying writes.+ await writeAtomicJson(pendingPath, {+ ...submission,+ receipts,+ });+ }+ }+ // Verify readable source records without mistaking a newer concurrent+ // observation for failure of the original, immutable import receipt.+ const readbacks = receipts.flatMap((receipt, batchIndex) => {+ const batch = requests[batchIndex]!;+ const batchItems = new Map(+ batch.items.map((item) => [item.client_id, item]),+ );+ return receipt.results+ .filter((item) => item.outcome !== "error")+ .map((item) => ({+ item,+ expected: batchItems.get(item.client_id)!,+ batch,+ }));+ });+ progress({+ phase: "verifying",+ completed: 0,+ total: readbacks.length,+ });+ await readInBatches(readbacks, async ({ item, expected, batch }) => {+ const report = validateSourceReport(+ await request(+ `${sourcePath(destination)}/${encodeURIComponent(item.source_report_id!)}`,+ ),+ );+ if (+ report.id !== item.source_report_id ||+ report.canonical_finding_id !== item.canonical_finding_id ||+ report.version < item.version! ||+ (report.version === item.version &&+ (report.observation_id !== item.observation_id ||+ canonicalJson(report.evidence) !==+ canonicalJson(expected.evidence))) ||+ report.source_finding_id !== expected.source_finding_id ||+ report.repo_id !== destination.id ||+ report.repo_connector_id !== destination.repo_connector_id ||+ report.environment_id !== batch.repository.environment_id ||+ canonicalJson(report.source) !== canonicalJson(source)+ )+ throw new CodexSecurityError(+ "Cloud readback did not match the saved finding identity.",+ );+ progress({+ phase: "verifying",+ completed: ++verified,+ total: readbacks.length,+ });+ });+ const completed = result(acknowledged, verified);+ await writeAtomicJson(join(state, `${key}.result.json`), completed);+ await rm(pendingPath, { force: true });+ return completed;+ } catch (error) {+ if (error instanceof CloudImportError && error.status === 409) {+ await rm(pendingPath, { force: true });+ persisted = false;+ }+ const message = `${error instanceof Error ? error.message : String(error)} ${error instanceof CloudImportError && error.status === 409 ? "The old submission was retired. Rediscover and approve a fresh publication." : persisted ? `Repeat the same command to resume the saved request. Saved submission: ${pendingPath}` : "No resumable request was saved. Correct the error and review the input before retrying."}`;+ throw new ExternalPublicationError(+ message,+ {+ ...result(acknowledged, verified),+ status: "interrupted",+ error: message,+ ...(persisted ? { savedSubmission: pendingPath } : {}),+ },+ error,+ );+ }+ }).catch((error: unknown) => {+ if (acquired || !dependencies.signal?.aborted) throw error;+ // The active publisher owns the checkpoint. Report only acknowledgements+ // already observed during preparation, without rewriting its files.+ const known = submission.receipts ?? [];+ if (known.length > requests.length)+ throw new CodexSecurityError(+ "Saved publication has more receipts than requests.",+ );+ const acknowledged = known.map((receipt, index) =>+ validatePublicationReceipt(receipt, requests[index]!),+ );+ const message = saved+ ? `Publication canceled while waiting. Repeat the same command to resume the saved request. Saved submission: ${pendingPath}`+ : "Publication canceled while waiting. No resumable request was saved by this invocation.";+ throw new ExternalPublicationError(+ message,+ {+ ...result(acknowledged, 0),+ status: "interrupted",+ error: message,+ ...(saved ? { savedSubmission: pendingPath } : {}),+ },+ error,+ );+ });+ },+ };+}diff --git a/sdk/typescript/src/external-findings.ts b/sdk/typescript/src/external-findings.tsnew file mode 100644index 000000000..3c4a0436c--- /dev/null+++ b/sdk/typescript/src/external-findings.ts@@ -0,0 +1,25 @@+import type { ExternalFindingEvidence } from "./external-import-models.js";++/** A provider occurrence and its evidence, before Cloud assigns a source report. */+export interface ExternalFinding {+ source_finding_id: string;+ evidence: ExternalFindingEvidence;+}++export interface ExternalFindings {+ read: number;+ findings: ExternalFinding[];+ excluded: {+ position: number;+ source_finding_id: string | null;+ reason: string;+ }[];+}++/** @internal Keep earlier provider projections only for immutable request replay. */+export interface ExternalPublicationInput {+ current: ExternalFindings;+ legacy: ExternalFindings;+ currentIdentity: unknown;+ legacyIdentity: unknown;+}diff --git a/sdk/typescript/src/external-import-contract.ts b/sdk/typescript/src/external-import-contract.tsnew file mode 100644index 000000000..8df3bcc24--- /dev/null+++ b/sdk/typescript/src/external-import-contract.ts@@ -0,0 +1,322 @@+import { isIP } from "node:net";+import Ajv2020 from "ajv/dist/2020.js";+import schema from "../schemas/external-findings.schema.json" with { type: "json" };+import type {+ ExternalFindingEvidence,+ FindingImportRequest,+ FindingImportReceipt,+ ImportRepositoryPage,+ SourceReportPage,+ SourceReport,+} from "./external-import-models.js";++const ajv = new Ajv2020({+ strict: false,+ validateFormats: false,+ useDefaults: true,+});+const STRING_BYTE_LIMITS: Readonly<Record<string, number>> = {+ description: 65536,+ snippet: 65536,+ remediation_instructions: 65536,+ expected: 65536,+ actual: 65536,+ file_url: 2048,+ path: 2048,+ url: 2048,+ manifest_path: 2048,+ client_id: 128,+ next: 4096,+};++/** Compare repository URLs without changing the retained vendor evidence.+ * GitHub repository paths are case-insensitive; unknown VCS hosts stay strict.+ * Keep protocols and explicit ports distinct, matching the Cloud URL contract. */+export function repositoryUrlKey(value: string): string {+ const normalized = value.replace(/\/$/u, "").replace(/\.git$/u, "");+ const parts = /^(https?):\/\/([^/?#]+)([^?#]*)(.*)$/iu.exec(normalized);+ if (!parts) return normalized;+ const authority = parts[2]!.toLowerCase();+ const hostname = authority.replace(/:\d+$/u, "");+ const path =+ hostname === "github.com" || hostname.endsWith(".ghe.com")+ ? parts[3]!.toLowerCase()+ : parts[3]!;+ return `${parts[1]!.toLowerCase()}://${authority}${path}${parts[4]!}`;+}++// Cloud's import catalog contains GitHub repositories, including custom Enterprise+// hosts. Match its case-insensitive URL identity without merging schemes or ports.+export function cloudRepositoryUrlKey(value: string): string {+ return repositoryUrlKey(value).toLowerCase();+}++// Cloud ImportModel applies these constraints to both requests and responses.+// Its UTF-8 limits are not exported as JSON Schema character limits: even a+// plain string field such as a receipt error message inherits the 512-byte bound.+function validateModelStrings(input: unknown): void {+ if (input === null || typeof input !== "object") return;+ if (Array.isArray(input)) {+ for (const item of input) validateModelStrings(item);+ return;+ }+ for (const [field, value] of Object.entries(input)) {+ if (field === "source_data") continue;+ if (typeof value === "string") {+ if (+ (!value.trim() && !["snippet", "expected", "actual"].includes(field)) ||+ value.includes("\0")+ )+ throw new Error(+ `${field} must be nonempty and contain no NUL characters.`,+ );+ const limit = STRING_BYTE_LIMITS[field] ?? 512;+ if (Buffer.byteLength(value) > limit)+ throw new Error(+ `${field} exceeds its Cloud limit of ${limit} UTF-8 bytes.`,+ );+ } else if (+ Array.isArray(value) &&+ value.every((item) => typeof item === "string")+ ) {+ if (value.some((item) => Buffer.byteLength(item) > 512))+ throw new Error(+ `${field} entries exceed the Cloud limit of 512 UTF-8 bytes.`,+ );+ } else validateModelStrings(value);+ }+}++type ModelSchema = {+ $ref?: string;+ anyOf?: ModelSchema[];+ properties?: Record<string, ModelSchema>;+ [key: string]: unknown;+};+const modelSchemas: Record<string, ModelSchema> = schema.$defs;+const detailValidators = new Map<string, ReturnType<typeof ajv.compile>>();++/** AJV does not apply defaults through nullable anyOf references. Validate the+ * present detail objects directly against their generated model definitions so+ * sparse normalized inputs match the backend's serialized evidence. */+function materializeDetailDefaults(+ value: unknown,+ fieldSchema: ModelSchema,+): void {+ if (value === null || typeof value !== "object" || Array.isArray(value))+ return;+ const reference =+ fieldSchema.$ref ?? fieldSchema.anyOf?.find((branch) => branch.$ref)?.$ref;+ if (!reference) return;+ const name = reference.split("/").at(-1)!;+ const definition = modelSchemas[name]!;+ let check = detailValidators.get(reference);+ if (!check) {+ check = ajv.compile({ $defs: schema.$defs, $ref: reference });+ detailValidators.set(reference, check);+ }+ if (!check(value))+ throw new Error(`${name}: ${ajv.errorsText(check.errors)}`);+ for (const [field, childSchema] of Object.entries(+ definition.properties ?? {},+ ))+ materializeDetailDefaults(+ (value as Record<string, unknown>)[field],+ childSchema,+ );+}++function normalizeEvidenceDetails(value: unknown): void {+ if (value !== null && typeof value === "object") {+ const fields = value as Record<string, unknown>;+ // Cloud omits these new optional fields when null. Preserve every legacy+ // default so saved Wiz requests still replay the same evidence bytes.+ if (Array.isArray(fields["packages"]))+ for (const value of fields["packages"]) {+ if (+ value &&+ typeof value === "object" &&+ value["vulnerable_version_range"] === null+ )+ delete value["vulnerable_version_range"];+ }+ if (fields["details"] === null) delete fields["details"];+ else {+ const details = fields["details"];+ if (details && typeof details === "object" && !Array.isArray(details))+ for (const field of ["repository", "advisory"])+ if ((details as Record<string, unknown>)[field] === null)+ delete (details as Record<string, unknown>)[field];+ materializeDetailDefaults(+ fields["details"],+ modelSchemas["ImportedFindingEvidence"]!.properties!["details"]!,+ );+ }+ }+}++function validator<T>(name: keyof typeof schema.$defs) {+ const check = ajv.compile<T>({+ $defs: schema.$defs,+ $ref: `#/$defs/${name}`,+ });+ return (input: unknown): T => {+ if (name === "ImportedFindingEvidence") normalizeEvidenceDetails(input);+ else if (input && typeof input === "object") {+ if (name === "SourceReport" && "evidence" in input)+ normalizeEvidenceDetails(input.evidence);+ if (+ name === "FindingImportRequest" &&+ "items" in input &&+ Array.isArray(input.items)+ )+ for (const item of input.items)+ normalizeEvidenceDetails(item?.evidence);+ }+ if (!check(input))+ throw new Error(`${name}: ${ajv.errorsText(check.errors)}`);+ validateModelStrings(input);+ return input;+ };+}++const evidence = validator<ExternalFindingEvidence>("ImportedFindingEvidence");+const request = validator<FindingImportRequest>("FindingImportRequest");+export const validateImportReceipt = validator<FindingImportReceipt>(+ "FindingImportReceipt",+);+export const validateRepositories = validator<ImportRepositoryPage>(+ "ImportRepositoryPage",+);+export const validateSourceReports =+ validator<SourceReportPage>("SourceReportPage");+export const validateSourceReport = validator<SourceReport>("SourceReport");++export function validateExternalEvidence(+ input: unknown,+): ExternalFindingEvidence {+ const result = evidence(input);+ for (const location of result.locations ?? []) {+ const path = location.path.replaceAll("\\", "/");+ if (+ path.startsWith("/") ||+ /^[A-Za-z]:/.test(path) ||+ path.split("/").includes("..")+ )+ throw new Error("Locations must use repository-relative paths.");+ }+ const details = result.details;+ if (details) {+ if (details.kind === "advisory") {+ if (!details.advisory)+ throw new Error("Advisory evidence requires its source context.");+ if (details.advisory.source === "global" && details.repository)+ throw new Error(+ "Global advisory evidence cannot claim a source repository.",+ );+ if (details.advisory.source === "repository" && !details.repository)+ throw new Error(+ "Repository advisory evidence requires its source repository.",+ );+ } else {+ if (!details.repository)+ throw new Error(+ "Repository finding evidence requires its source repository.",+ );+ if (details.advisory)+ throw new Error("Advisory source context requires advisory evidence.");+ }+ }+ const endLine = result.details?.code?.end_line;+ if (endLine !== null && endLine !== undefined) {+ const firstLine = result.locations?.[0]?.line;+ if (firstLine === null || firstLine === undefined || endLine < firstLine)+ throw new Error(+ "The code end line requires a first source location line and cannot precede it.",+ );+ }+ const urls = [+ result.url,+ result.details?.repository?.url,+ result.details?.file_url,+ ];+ for (const value of urls) {+ if (value === null || value === undefined) continue;+ const url = value+ .replace(/[\t\r\n]/gu, "")+ .replace(/^[\u0000-\u0020]+/u, "");+ const authority = /^https?:\/\/([^/?#]+)/iu.exec(url)?.[1];+ const normalizedAuthority = (authority ?? "")+ .replace(/[@:#?]/gu, "")+ .normalize("NFKC");+ let validHost = true;+ if (authority?.includes("[") || authority?.includes("]")) {+ const hostname = /^\[([^\]]+)\](?::[\s\S]*)?$/u.exec(authority)?.[1];+ const [address, scope, extraScope] = (hostname ?? "").split("%");+ // Cloud accepts scoped IPv6 and IPvFuture hosts in brackets.+ validHost =+ hostname !== undefined &&+ (/^v[a-fA-F0-9]+\.[\s\S]+$/u.test(hostname) ||+ (isIP(address!) === 6 && scope !== "" && extraScope === undefined));+ }+ if (+ !authority ||+ authority.includes("@") ||+ /[/?#@:]/u.test(normalizedAuthority) ||+ !validHost+ )+ throw new Error(+ "Evidence URLs must be HTTP(S) links without credentials.",+ );+ }+ let numericByteAdjustment = 0;+ const pending: [unknown, number][] = [[result, 0]];+ while (pending.length > 0) {+ const [value, depth] = pending.pop()!;+ if (depth > 20)+ throw new Error("Evidence exceeds the Cloud JSON depth limit of 20.");+ if (value !== null && typeof value === "object") {+ for (const child of Object.values(value))+ pending.push([child, depth + 1]);+ } else if (typeof value === "number") {+ if (!Number.isFinite(value))+ throw new Error("Evidence must contain finite JSON numbers.");+ if (Number.isInteger(value) && !Number.isSafeInteger(value))+ throw new Error(+ "Evidence integers must be within JavaScript's safe integer range; export larger values as strings to preserve them exactly.",+ );+ const wire = JSON.stringify(value);+ // Cloud pads short exponents and formats small fractions scientifically.+ const cloud = (+ wire.includes(".") && Math.abs(value) < 1e-4+ ? value.toExponential()+ : wire+ ).replace(/e-(\d)$/u, "e-0$1");+ numericByteAdjustment += cloud.length - wire.length;+ }+ }+ if (+ Buffer.byteLength(JSON.stringify(result)) + numericByteAdjustment >+ 256 * 1024+ )+ throw new Error("Evidence exceeds the Cloud limit of 256 KiB.");+ return result;+}++export function validateImportRequest(input: unknown): FindingImportRequest {+ const result = request(input);+ if (+ new Set(result.items.map((item) => item.client_id)).size !==+ result.items.length+ )+ throw new Error("Import contains duplicate client IDs.");+ if (+ new Set(result.items.map((item) => item.source_finding_id)).size !==+ result.items.length+ )+ throw new Error("Import contains duplicate source finding identities.");+ for (const item of result.items) validateExternalEvidence(item.evidence);+ if (Buffer.byteLength(JSON.stringify(result)) > 5 * 1024 * 1024)+ throw new Error("Import exceeds the Cloud limit of 5 MiB.");+ return result;+}diff --git a/sdk/typescript/src/external-import-models.ts b/sdk/typescript/src/external-import-models.tsnew file mode 100644index 000000000..1f55518c0--- /dev/null+++ b/sdk/typescript/src/external-import-models.ts@@ -0,0 +1,368 @@+/* Generated from schemas/external-findings.schema.json. Run pnpm generate:external-import-models. */++export type RequestId = string;+export type Id = string;+export type RepoConnectorId = string;+export type EnvironmentId = string;+export type ResetMarker = string;+export type Provider = "wiz" | "endor" | "snyk" | "github" | "semgrep";+export type SourceKey = string;+export type ClientId = string;+export type SourceFindingId = string;+export type ExpectedVersion = number;+export type Title = string;+export type Severity =+ "critical" | "high" | "medium" | "low" | "informational" | "unknown";+export type Description = string | null;+export type Url = string | null;+/**+ * @maxItems 100+ */+export type AdvisoryIds = string[];+export type Name = string;+export type Ecosystem = string | null;+export type InstalledVersion = string | null;+export type VulnerableVersionRange = string | null;+export type ManifestPath = string | null;+/**+ * @maxItems 100+ */+export type FixedVersions = string[];+/**+ * @maxItems 100+ */+export type Packages = ImportedPackage[];+export type Path = string;+export type Line = number | null;+/**+ * @maxItems 100+ */+export type Locations = ImportedLocation[];+export type Branch = string | null;+export type CodeRevision = string | null;+export type SourceScanId = string | null;+/**+ * @maxItems 100+ */+export type ImageDigests = string[];+export type SourceUpdatedAt = number | null;+export type Kind = "sast" | "secret" | "iac" | "advisory";+export type Url1 = string;+export type Id1 = string | null;+export type Name1 = string | null;+export type Source = "repository" | "global";+export type SourceStatus = string | null;+export type ScannerOrigin = string | null;+export type ScannerVerdict = string | null;+export type Id2 = string | null;+export type ShortId = string | null;+export type Name2 = string | null;+/**+ * @maxItems 100+ */+export type WeaknessIds = string[];+export type RemediationInstructions = string | null;+export type EndLine = number | null;+export type Snippet = string | null;+export type Type = string | null;+export type ImportedSecretConfidence = string;+export type ValidationStatus = string | null;+export type IsEncrypted = boolean | null;+export type IsManaged = boolean | null;+export type IntroducedCommit = string | null;+export type Platform = string | null;+export type CloudPlatform = string | null;+export type Expected = string | null;+export type Actual = string | null;+export type FileUrl = string | null;+/**+ * @minItems 1+ * @maxItems 100+ */+export type Items = FindingImportItem[];+export type Id3 = string;+export type Object = "security.finding_import";+export type Actor = string;+export type CreatedAt = number;+export type ItemCount = number;+export type Created = number;+export type Updated = number;+export type Unchanged = number;+export type Error = number;+export type ClientId1 = string;+export type Outcome = "created" | "updated" | "unchanged" | "error";+export type SourceReportId = string | null;+export type ObservationId = string | null;+export type CanonicalFindingId = string | null;+export type Version = number | null;+export type Code =+ "version_conflict" | "scope_conflict" | "stale_source_snapshot";+export type Message = string;+export type Results = FindingImportResult[];+export type Object1 = "page";+export type Id4 = string;+export type Object2 = "security.repository";+export type RepoConnectorId1 = string;+export type Url2 = string;+export type DefaultBranch = string | null;+export type ResetMarker1 = string;+export type ImportEnvironmentId = string | null;+export type Data = ImportRepository[];+export type HasMore = boolean;+export type Next = string | null;+export type Id5 = string;+export type Object3 = "security.source_report";+export type Origin = "imported";+export type RepoId = string;+export type RepoConnectorId2 = string;+export type EnvironmentId1 = string;+export type CanonicalFindingId1 = string;+export type SourceFindingId1 = string;+export type ObservationId1 = string;+export type Version1 = number;+export type State = "not_assessed";+export type Id6 = string;+export type Actor1 = string;+export type CreatedAt1 = number;+export type CreatedAt2 = number;+export type UpdatedAt = number;+export type Object4 = "page";+export type Id7 = string;+export type Object5 = "security.source_report_summary";+export type Origin1 = "imported";+export type RepoId1 = string;+export type RepoConnectorId3 = string;+export type EnvironmentId2 = string;+export type CanonicalFindingId2 = string;+export type SourceFindingId2 = string;+export type ObservationId2 = string;+export type Version2 = number;+export type Title1 = string;+export type Severity1 =+ "critical" | "high" | "medium" | "low" | "informational" | "unknown";+export type SourceUpdatedAt1 = number | null;+export type CreatedAt3 = number;+export type UpdatedAt1 = number;+export type Data1 = SourceReportSummary[];+export type HasMore1 = boolean;+export type Next1 = string | null;++/**+ * Schema export root; transport endpoints return the individual models.+ */+export interface ExternalFindingContracts {+ request: FindingImportRequest;+ receipt: FindingImportReceipt;+ repositories: ImportRepositoryPage;+ source_report: SourceReport;+ source_reports: SourceReportPage;+}+export interface FindingImportRequest {+ request_id: RequestId;+ repository: ImportDestination;+ source: ImportSource;+ items: Items;+}+export interface ImportDestination {+ id: Id;+ repo_connector_id: RepoConnectorId;+ environment_id: EnvironmentId;+ reset_marker: ResetMarker;+}+export interface ImportSource {+ provider: Provider;+ source_key: SourceKey;+}+export interface FindingImportItem {+ client_id: ClientId;+ source_finding_id: SourceFindingId;+ expected_version: ExpectedVersion;+ evidence: ImportedFindingEvidence;+}+export interface ImportedFindingEvidence {+ title: Title;+ severity: Severity;+ description?: Description;+ url?: Url;+ advisory_ids?: AdvisoryIds;+ packages?: Packages;+ locations?: Locations;+ branch?: Branch;+ code_revision?: CodeRevision;+ source_scan_id?: SourceScanId;+ image_digests?: ImageDigests;+ source_updated_at?: SourceUpdatedAt;+ source_data?: SourceData;+ details?: ImportedFindingDetails | null;+}+export interface ImportedPackage {+ name: Name;+ ecosystem?: Ecosystem;+ installed_version?: InstalledVersion;+ vulnerable_version_range?: VulnerableVersionRange;+ manifest_path?: ManifestPath;+ fixed_versions?: FixedVersions;+}+export interface ImportedLocation {+ path: Path;+ line?: Line;+}+export interface SourceData {+ [k: string]: unknown;+}+/**+ * Typed repository evidence; vendor state is not a Codex assessment.+ */+export interface ImportedFindingDetails {+ kind: Kind;+ repository?: ImportedRepositoryReference | null;+ advisory?: ImportedAdvisoryContext | null;+ source_status?: SourceStatus;+ scanner_origin?: ScannerOrigin;+ scanner_verdict?: ScannerVerdict;+ rule?: ImportedFindingRule | null;+ weakness_ids?: WeaknessIds;+ remediation_instructions?: RemediationInstructions;+ code?: ImportedCodeContext | null;+ secret?: ImportedSecretDetails | null;+ configuration?: ImportedConfigurationDetails | null;+ file_url?: FileUrl;+}+/**+ * Vendor repository identity, resolved to the full source-control URL.+ */+export interface ImportedRepositoryReference {+ url: Url1;+ id?: Id1;+ name?: Name1;+}+/**+ * Where the advisory was read; applicability is assessed separately.+ */+export interface ImportedAdvisoryContext {+ source: Source;+}+export interface ImportedFindingRule {+ id?: Id2;+ short_id?: ShortId;+ name?: Name2;+}+/**+ * Optional range and snippet for the evidence's first source location.+ */+export interface ImportedCodeContext {+ end_line?: EndLine;+ snippet?: Snippet;+}+export interface ImportedSecretDetails {+ type?: Type;+ confidence?: ImportedSecretConfidence | null;+ validation_status?: ValidationStatus;+ is_encrypted?: IsEncrypted;+ is_managed?: IsManaged;+ introduced_commit?: IntroducedCommit;+}+export interface ImportedConfigurationDetails {+ platform?: Platform;+ cloud_platform?: CloudPlatform;+ expected?: Expected;+ actual?: Actual;+}+export interface FindingImportReceipt {+ id: Id3;+ object?: Object;+ repository: ImportDestination;+ source: ImportSource;+ actor: Actor;+ created_at: CreatedAt;+ item_count: ItemCount;+ counts: ImportCounts;+ results: Results;+}+export interface ImportCounts {+ created?: Created;+ updated?: Updated;+ unchanged?: Unchanged;+ error?: Error;+}+export interface FindingImportResult {+ client_id: ClientId1;+ outcome: Outcome;+ source_report_id?: SourceReportId;+ observation_id?: ObservationId;+ canonical_finding_id?: CanonicalFindingId;+ version?: Version;+ error?: ImportItemError | null;+}+export interface ImportItemError {+ code: Code;+ message: Message;+}+export interface ImportRepositoryPage {+ object?: Object1;+ data: Data;+ has_more: HasMore;+ next: Next;+}+export interface ImportRepository {+ id: Id4;+ object?: Object2;+ repo_connector_id: RepoConnectorId1;+ url: Url2;+ default_branch?: DefaultBranch;+ reset_marker: ResetMarker1;+ import_environment_id?: ImportEnvironmentId;+}+export interface SourceReport {+ id: Id5;+ object?: Object3;+ origin?: Origin;+ repo_id: RepoId;+ repo_connector_id: RepoConnectorId2;+ environment_id: EnvironmentId1;+ canonical_finding_id: CanonicalFindingId1;+ source: ImportSource;+ source_finding_id: SourceFindingId1;+ observation_id: ObservationId1;+ version: Version1;+ evidence: ImportedFindingEvidence;+ assessment?: ImportedAssessment;+ last_import?: LastImport | null;+ created_at: CreatedAt2;+ updated_at: UpdatedAt;+}+export interface ImportedAssessment {+ state?: State;+}+export interface LastImport {+ id: Id6;+ actor: Actor1;+ created_at: CreatedAt1;+}+export interface SourceReportPage {+ object?: Object4;+ data: Data1;+ has_more: HasMore1;+ next: Next1;+}+export interface SourceReportSummary {+ id: Id7;+ object?: Object5;+ origin?: Origin1;+ repo_id: RepoId1;+ repo_connector_id: RepoConnectorId3;+ environment_id: EnvironmentId2;+ canonical_finding_id: CanonicalFindingId2;+ source: ImportSource;+ source_finding_id: SourceFindingId2;+ observation_id: ObservationId2;+ version: Version2;+ title: Title1;+ severity: Severity1;+ source_updated_at: SourceUpdatedAt1;+ assessment?: ImportedAssessment;+ created_at: CreatedAt3;+ updated_at: UpdatedAt1;+}++export type ExternalFindingEvidence = ImportedFindingEvidence;diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 96ac7634e..626ac10c7 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -202,6 +202,28 @@ export type {DeduplicationDiagnosticObserver,} from "./deduplication/diagnostics.js";export type { FindingEmbedder } from "./server/embeddings.js";+export {+ ExternalPublicationError,+ prepareExternalPublication,+ prepareNormalizedExternalPublication,+} from "./external-findings-publish.js";+export type {+ ExternalPublicationOptions,+ NormalizedExternalPublicationOptions,+ ExternalPublicationDependencies,+ ExternalPublicationPreview,+ ExternalPublicationProgress,+ ExternalPublicationResult,+ PreparedExternalPublication,+} from "./external-findings-publish.js";+export type { ExternalFinding, ExternalFindings } from "./external-findings.js";+export type {+ ExternalFindingEvidence,+ FindingImportRequest,+ FindingImportReceipt,+ ImportRepository,+ SourceReport,+} from "./external-import-models.js";export { importGitHubCodeScanningAlerts } from "./github.js";export type {GitHubCodeScanningImportOptions,diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 45b0e3518..a9c22f5e1 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -2096,7 +2096,7 @@ async function prepareOutputDirectory(}}-async function createWindowsOutputDirectory(+export async function createWindowsOutputDirectory(path: string,recursive: boolean,): Promise<string | undefined> {diff --git a/sdk/typescript/src/scanner-import.ts b/sdk/typescript/src/scanner-import.tsnew file mode 100644index 000000000..28db27f41--- /dev/null+++ b/sdk/typescript/src/scanner-import.ts@@ -0,0 +1,148 @@+import { hash } from "node:crypto";+import { readFile } from "node:fs/promises";+import { promisify } from "node:util";+import { gunzip } from "node:zlib";+import { CodexSecurityError, errorMessage } from "./errors.js";+import type { ExternalFinding, ExternalFindings } from "./external-findings.js";++export function record(value: unknown, label: string): Record<string, unknown> {+ if (!value || typeof value !== "object" || Array.isArray(value))+ throw new Error(`${label} must be an object.`);+ return value as Record<string, unknown>;+}++export function array(value: unknown, label: string): unknown[] {+ if (!Array.isArray(value)) throw new Error(`${label} must be an array.`);+ return value;+}++export function text(value: unknown): string | null {+ return typeof value === "string" && value.trim() ? value : null;+}++export function requiredText(value: unknown, label: string): string {+ const result = text(value);+ if (!result) throw new Error(`${label} must be nonempty text.`);+ return result;+}++export function strings(value: unknown): string[] {+ return Array.isArray(value)+ ? value.filter((v): v is string => text(v) !== null)+ : [];+}++/** Paths that cannot be attributed to a repository stay in original evidence. */+export function relativePath(value: unknown): string | null {+ const path = text(value)?.replaceAll("\\", "/");+ return path &&+ !path.startsWith("/") &&+ !path.includes("\0") &&+ !/^[A-Za-z]:/.test(path) &&+ !path.split("/").includes("..")+ ? path+ : null;+}++export function stableId(prefix: string, fields: unknown[]): string {+ return `${prefix}:${hash("sha256", JSON.stringify(fields))}`;+}++/** Detect gzip from the report bytes and preserve identities with strict UTF-8. */+export async function readScannerText(path: string): Promise<string> {+ let bytes = await readFile(path);+ if (bytes[0] === 0x1f && bytes[1] === 0x8b)+ bytes = await promisify(gunzip)(bytes);+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);+}++export function parseJsonOrJsonl(contents: string): unknown {+ try {+ return JSON.parse(contents);+ } catch {+ return contents+ .split(/\r?\n/u)+ .filter((line) => line.trim())+ .map((line) => JSON.parse(line));+ }+}++export async function readScannerJson(path: string): Promise<unknown> {+ let bytes = await readFile(path);+ if (bytes[0] === 0x1f && bytes[1] === 0x8b)+ bytes = await promisify(gunzip)(bytes);+ let decoded: string;+ try {+ decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);+ } catch (error) {+ throw new CodexSecurityError(+ `Scanner report is not valid UTF-8. ${errorMessage(error)}`,+ { cause: error },+ );+ }+ try {+ return JSON.parse(decoded.replace(/^\uFEFF/u, ""));+ } catch (error) {+ throw new CodexSecurityError(+ `Scanner JSON could not be parsed. ${errorMessage(error)}`,+ { cause: error },+ );+ }+}++/** Exclude every colliding record: choosing the first could overwrite another occurrence. */+export function normalizeRecords<T>(+ records: T[],+ normalize: (record: T, id: string) => ExternalFinding,+ identify: (record: T) => string,+): ExternalFindings {+ const result: ExternalFindings = {+ read: records.length,+ findings: [],+ excluded: [],+ };+ const identified: { position: number; value: T; id: string }[] = [];+ const counts = new Map<string, number>();+ for (const [index, value] of records.entries()) {+ try {+ const id = identify(value);+ if (!id.trim() || id.includes("\0") || Buffer.byteLength(id) > 512)+ throw new Error(+ "Source finding ID must contain 1–512 UTF-8 bytes and no NUL characters.",+ );+ identified.push({ position: index + 1, value, id });+ counts.set(id, (counts.get(id) ?? 0) + 1);+ } catch (error) {+ result.excluded.push({+ position: index + 1,+ source_finding_id: null,+ reason: errorMessage(error),+ });+ }+ }+ for (const { position, value, id } of identified) {+ if (counts.get(id)! > 1) {+ result.excluded.push({+ position,+ source_finding_id: id,+ reason:+ "Ambiguous duplicate source identity; select one complete finding or separate source projects.",+ });+ continue;+ }+ try {+ const finding = normalize(value, id);+ if (finding.source_finding_id !== id)+ throw new Error("Finding identity changed during normalization.");+ result.findings.push(finding);+ } catch (error) {+ result.excluded.push({+ position,+ source_finding_id: id,+ reason: errorMessage(error),+ });+ }+ }+ result.excluded.sort((a, b) => a.position - b.position);+ return result;+}diff --git a/sdk/typescript/src/wiz-findings.ts b/sdk/typescript/src/wiz-findings.tsnew file mode 100644index 000000000..0fd16fd1a--- /dev/null+++ b/sdk/typescript/src/wiz-findings.ts@@ -0,0 +1,575 @@+import { CodexSecurityError } from "./errors.js";+import {+ repositoryUrlKey,+ validateExternalEvidence,+} from "./external-import-contract.js";+import { parseJsonOrJsonl, readScannerText } from "./scanner-import.js";+import type {+ ExternalFinding as VendorFinding,+ ExternalFindings as VendorFindings,+} from "./external-findings.js";++export type {+ ExternalFinding as VendorFinding,+ ExternalFindings as VendorFindings,+} from "./external-findings.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 text(value: unknown): string | null {+ return typeof value === "string" && value.trim() ? value : null;+}++function sourceFindingId(value: unknown): string {+ const id = text(value);+ if (!id || id.includes("\0") || Buffer.byteLength(id) > 512)+ throw new Error(+ "Source finding id must contain 1–512 UTF-8 bytes and no NUL characters.",+ );+ return id;+}++/** Keep a Wiz vulnerability occurrence intact; advisory names are not identities. */+function wizFinding(record: Record<string, unknown>): VendorFinding {+ if (record["detectionMethod"] === "EXTERNAL_NETWORK_SCAN")+ throw new Error(+ "Wiz external network findings are not supported by the package vulnerability mapping.",+ );+ const id = sourceFindingId(record["id"]);+ const name = text(record["name"]);+ const packageName = text(record["detailedName"]);+ const version = text(record["version"]);+ const severity = text(record["vendorSeverity"]) ?? text(record["severity"]);+ const asset = object(record["vulnerableAsset"]);+ const artifact = object(record["artifactType"]);+ if (!name || !packageName || !text(asset?.["id"])) {+ throw new Error(+ "Expected a Wiz package vulnerability finding with name, detailedName, and vulnerableAsset.id. Other finding classes need a separate mapping.",+ );+ }+ const assetType = text(asset?.["type"]);+ const repositoryAsset =+ assetType === "REPOSITORY_BRANCH" ||+ asset?.["nativeType"] === "github#repositoryBranch";+ // Wiz repository reports prefix root-relative paths with '/'. Workload paths+ // are not source locations and must remain only in the original evidence.+ const locationPath = text(record["locationPath"]);+ const repositoryPath =+ repositoryAsset && locationPath ? locationPath.replace(/^\/+/, "") : null;+ const digest =+ text(asset?.["imageDigest"]) ??+ text(record["imageDigest"]) ??+ (assetType === null ||+ assetType === "CONTAINER_IMAGE" ||+ assetType === "CONTAINER"+ ? (text(asset?.["imageId"]) ??+ text(asset?.["containerImageId"]) ??+ text(asset?.["ImageExternalId"]))+ : null);+ // lastDetectedAt is not proof that the entire vendor record was updated.+ const evidence = {+ title:+ text(record["title"]) ??+ [packageName, version, name].filter(Boolean).join(" "),+ description: text(record["description"]),+ severity: severity?.toLowerCase(),+ url: text(record["portalUrl"]),+ advisory_ids: [text(record["vulnerabilityExternalId"]) ?? name],+ packages: [+ {+ name: packageName,+ ecosystem:+ text(record["packageManager"]) ??+ text(artifact?.["osPackageManager"]) ??+ text(artifact?.["codeLibraryLanguage"]) ??+ text(record["codeLibraryLanguage"]),+ installed_version: version,+ manifest_path: repositoryPath,+ fixed_versions: text(record["fixedVersion"])+ ? [record["fixedVersion"]]+ : [],+ },+ ],+ locations: repositoryPath ? [{ path: repositoryPath }] : [],+ branch: null,+ code_revision: null,+ source_scan_id: null,+ image_digests: digest ? [digest] : [],+ source_updated_at: updatedAt(record["updatedAt"], "updatedAt"),+ source_data: record,+ };+ return {+ source_finding_id: id,+ evidence: validateExternalEvidence(evidence),+ };+}++type RepositoryFindingKind = "sast" | "secret" | "iac";++type InputRecord = {+ value: unknown;+ kind?: "sca" | RepositoryFindingKind | "cloud_configuration";+};++type RepositoryMetadata = {+ id: string | null;+ name: string | null;+ url: string;+};++type FindingInput = {+ records: InputRecord[];+ repositories: Map<string, RepositoryMetadata & { platform: string | null }>;+ legacyRepositories?: FindingInput["repositories"];+};++// Wiz's documented inventory platform establishes custom GitHub host semantics.+// Keep this context separate from the repository metadata published as evidence.+function inventoryRepositoryUrlKey(+ value: string,+ platform: string | null | undefined,+): string {+ const key = repositoryUrlKey(value);+ return platform === "GITHUB" ? key.toLowerCase() : key;+}++function sourceRepository(+ repository: Record<string, unknown> | undefined,+ repositories: FindingInput["repositories"],+): RepositoryMetadata {+ const id = text(repository?.["id"]);+ const inventory = id ? repositories.get(id) : undefined;+ const suppliedUrl = text(repository?.["url"]);+ if (+ suppliedUrl &&+ inventory &&+ inventoryRepositoryUrlKey(suppliedUrl, inventory.platform) !==+ inventoryRepositoryUrlKey(inventory.url, inventory.platform)+ )+ throw new Error(+ "The finding and repository inventory have conflicting repository URLs.",+ );+ const url = suppliedUrl ?? inventory?.url;+ if (!url)+ throw new Error(+ "A verified source repository URL is required. Include repository.url or the matching repository.id and repository.url from data.versionControlResources.nodes; names and Wiz IDs are not Cloud repository IDs.",+ );+ return {+ id,+ name: text(repository?.["name"]) ?? inventory?.name ?? null,+ url,+ };+}++function sourceBranch(+ branch: Record<string, unknown> | undefined,+ repository: RepositoryMetadata,+ legacy = false,+): string | null {+ const name = text(branch?.["name"]);+ if (!name) return null;+ // Repository names and URL paths can both be literal branch prefixes. Keep+ // the old mapping only for an already approved publication checkpoint.+ if (!legacy) return name;+ const qualifiers = repository.name ? [repository.name] : [];++ // Include the URL qualifier before selecting the longest repository prefix.+ // Keep URL normalization and the branch suffix's original case and slashes.+ const repositoryKey = repositoryUrlKey(repository.url).toLowerCase();+ const url = /^(https?:\/\/[^/?#]+)\/([^?#]+)$/iu.exec(repositoryKey);+ if (url) {+ const prefixParts = url[2]!.split("/").length;+ const parts = name.split("/");+ const qualifier = parts.slice(0, prefixParts).join("/");+ if (+ parts.length > prefixParts &&+ repositoryUrlKey(url[1] + "/" + qualifier).toLowerCase() === repositoryKey+ )+ qualifiers.push(qualifier);+ }+ for (const qualifier of qualifiers.sort(+ (left, right) => right.length - left.length,+ )) {+ const prefix = qualifier + "/";+ if (name.toLowerCase().startsWith(prefix.toLowerCase()))+ return name.slice(prefix.length) || null;+ }+ return url || repository.name ? name : null;+}++function updatedAt(value: unknown, field: string): number | null {+ const timestamp = text(value);+ if (!timestamp) return null;+ const seconds = Date.parse(timestamp) / 1000;+ if (!Number.isFinite(seconds) || seconds < 0)+ throw new Error(`Wiz ${field} is not a valid timestamp.`);+ return Math.floor(seconds);+}++// Empty code and configuration strings are meaningful vendor evidence.+function content(value: unknown): string | null {+ return typeof value === "string" ? value : null;+}++/** Map only explicitly identified repository finding collections. */+function repositoryFinding(+ kind: RepositoryFindingKind,+ record: Record<string, unknown>,+ repositories: FindingInput["repositories"],+ legacy = false,+): VendorFinding {+ const id = sourceFindingId(record["id"]);+ const resource = object(record["resource"]);+ if (kind === "secret" && resource?.["type"] !== "REPOSITORY_BRANCH")+ throw new Error(+ "Only repository-branch secret findings can be published to a repository. Workload secrets require a resource-scoped import and are not supported.",+ );+ const suppliedRepository =+ kind === "secret"+ ? object(object(resource?.["typedProperties"])?.["repository"])+ : object(record["repository"]);+ const repository = sourceRepository(suppliedRepository, repositories);+ const branch =+ kind === "secret"+ ? resource+ : object(record[kind === "sast" ? "repositoryBranch" : "branch"]);+ const rule = object(record["rule"]);+ const path = text(record[kind === "secret" ? "path" : "filePath"]);+ const line = record[kind === "secret" ? "lineNumber" : "startLine"];+ const details = {+ kind,+ repository,+ source_status: text(record["status"]),+ scanner_origin: kind === "sast" ? text(record["origin"]) : null,+ scanner_verdict:+ kind === "sast" ? text(object(record["aiAnalysis"])?.["verdict"]) : null,+ rule: rule+ ? {+ id: text(rule["id"]),+ short_id: text(rule["shortId"]),+ name: text(rule["name"]),+ }+ : null,+ weakness_ids:+ kind === "sast" && Array.isArray(record["weaknesses"])+ ? record["weaknesses"].map((weakness) => object(weakness)?.["id"])+ : [],+ remediation_instructions:+ text(record["remediationInstructions"]) ??+ text(rule?.["remediationInstructions"]),+ code:+ path && kind !== "secret"+ ? {+ end_line: record["endLine"] ?? null,+ snippet: content(+ record[kind === "sast" ? "snippet" : "matchContent"],+ ),+ }+ : null,+ secret:+ kind === "secret"+ ? {+ type: text(record["type"]),+ confidence: text(record["confidence"]),+ validation_status: text(record["validationStatus"]),+ is_encrypted: record["isEncrypted"] ?? null,+ is_managed: record["isManaged"] ?? null,+ introduced_commit: text(+ object(record["vcsDetails"])?.["initialCommitHash"],+ ),+ }+ : null,+ configuration:+ kind === "iac"+ ? {+ platform: text(record["platform"]),+ cloud_platform: text(record["cloudPlatform"]),+ expected: content(record["expectedContent"]),+ actual: content(record["foundContent"]),+ }+ : null,+ file_url: text(record["fileURL"]),+ };+ return {+ // Existing package occurrence IDs remain unchanged. New families cannot+ // collide with one another when the same tenant source key is used.+ source_finding_id: sourceFindingId(`${kind}:${id}`),+ evidence: validateExternalEvidence({+ title: text(record["name"]) ?? text(rule?.["name"]),+ severity: text(record["severity"])?.toLowerCase(),+ description: text(record["description"]) ?? text(rule?.["description"]),+ url: text(record["wizUrl"]) ?? text(record["portalUrl"]),+ locations: path ? [{ path, line: line ?? null }] : [],+ branch: sourceBranch(branch, repository, legacy),+ code_revision: null,+ source_scan_id: null,+ source_updated_at:+ kind === "secret"+ ? updatedAt(record["lastUpdatedAt"], "lastUpdatedAt")+ : kind === "iac"+ ? updatedAt(record["updatedAt"], "updatedAt")+ : null,+ source_data: record,+ details,+ }),+ };+}++function records(payload: unknown): FindingInput {+ const repositories: FindingInput["repositories"] = new Map();+ const legacyRepositories: FindingInput["repositories"] = new Map();+ if (Array.isArray(payload))+ return { records: payload.map((value) => ({ value })), repositories };+ const envelope = object(payload);+ if (!envelope)+ throw new Error(+ "Expected finding objects or a named Wiz finding collection.",+ );+ if (+ object(envelope["scannersRunStatuses"]) &&+ object(envelope["codeAnalyzerDetails"])+ )+ throw new Error(+ "This is a Wiz Code & Build Scan event, which contains scan metadata rather than vulnerability records. In Vulnerability Findings, filter the repository and selection, then choose Save as → Report with JSON format and Detailed columns. Download that report instead of Raw Event.",+ );+ if (Array.isArray(envelope["errors"]) && envelope["errors"].length > 0)+ throw new Error(+ "Wiz returned GraphQL errors. Resolve them before publishing this response.",+ );+ if (+ envelope["source_finding_id"] !== undefined ||+ envelope["id"] !== undefined+ )+ return { records: [{ value: envelope }], repositories };+ const data = object(envelope["data"]) ?? envelope;+ const inventory = object(data["versionControlResources"]);+ if (object(inventory?.["pageInfo"])?.["hasNextPage"] === true)+ throw new Error(+ "Wiz repository inventory has another page. Finish the selected inventory before publishing.",+ );+ if (Array.isArray(inventory?.["nodes"])) {+ const entries = inventory["nodes"].flatMap((entry) => {+ const node = object(entry);+ const repository = object(node?.["repository"]);+ const id = text(repository?.["id"]);+ const url = text(repository?.["url"]);+ return id && url+ ? [+ {+ id,+ name: text(repository?.["name"]),+ url,+ platform: text(node?.["platform"]),+ },+ ]+ : [];+ });+ // Resolve provider hints before comparing URLs, so duplicate row order cannot+ // discard a known platform or reject a case variant before its GITHUB hint.+ for (const entry of entries) {+ const previous = repositories.get(entry.id);+ if (+ previous?.platform &&+ entry.platform &&+ previous.platform !== entry.platform+ )+ throw new Error(+ `Repository inventory contains conflicting platforms for ${JSON.stringify(entry.id)}.`,+ );+ repositories.set(entry.id, {+ ...entry,+ // Equivalent inventory aliases must produce the same evidence when the+ // export reorders its rows. Keep a stable supplied URL and nonempty name.+ url: previous && previous.url < entry.url ? previous.url : entry.url,+ name:+ previous?.name && (!entry.name || previous.name < entry.name)+ ? previous.name+ : entry.name,+ platform: entry.platform ?? previous?.platform ?? null,+ });+ legacyRepositories.set(entry.id, {+ ...entry,+ platform: entry.platform ?? previous?.platform ?? null,+ });+ }+ for (const entry of entries) {+ const resolved = repositories.get(entry.id)!;+ if (+ inventoryRepositoryUrlKey(entry.url, resolved.platform) !==+ inventoryRepositoryUrlKey(resolved.url, resolved.platform)+ )+ throw new Error(+ `Repository inventory contains conflicting URLs for ${JSON.stringify(entry.id)}.`,+ );+ }+ }+ const collections = {+ vulnerabilityFindings: "sca",+ sastFindings: "sast",+ secretInstances: "secret",+ iacFindings: "iac",+ configurationFindings: "cloud_configuration",+ } as const;+ const selected: InputRecord[] = [];+ let found = false;+ for (const [root, kind] of Object.entries(collections)) {+ const collection = object(data[root]);+ if (!collection) continue;+ found = true;+ if (!Array.isArray(collection["nodes"]))+ throw new Error(`Wiz ${root}.nodes must be an array.`);+ if (object(collection["pageInfo"])?.["hasNextPage"] === true)+ throw new Error(+ "Wiz response has another page. Complete the requested pages or save the explicitly selected records in their named collection before publishing.",+ );+ for (const value of collection["nodes"]) selected.push({ value, kind });+ }+ if (found)+ return {+ records: selected,+ repositories,+ legacyRepositories,+ };+ throw new Error(+ "Unsupported Wiz export. Supply vulnerability finding objects, named sastFindings/secretInstances/iacFindings collections, or normalized JSONL. CSV reports must be converted to the documented normalized JSONL profile.",+ );+}++export async function readVendorFindings(+ path: string,+): Promise<VendorFindings> {+ return normalizeFindings(await readFindingInput(path));+}++/** @internal Preserve older inventory projections only for saved publication replay. */+export async function readVendorFindingsForPublication(path: string): Promise<{+ current: VendorFindings;+ legacy: VendorFindings;+ currentIdentity: unknown[];+ legacyIdentity: unknown[];+}> {+ const input = await readFindingInput(path);+ const normalized = new WeakSet<VendorFinding>();+ const current = normalizeFindings(input, normalized);+ const legacy = normalizeFindings(+ { ...input, repositories: input.legacyRepositories ?? input.repositories },+ normalized,+ true,+ );+ const identity = (parsed: VendorFindings) =>+ parsed.findings.map((finding) => {+ if (normalized.has(finding)) return finding;+ const repository = finding.evidence.details?.repository;+ return {+ source_finding_id: finding.source_finding_id,+ evidence: {+ // Raw vendor records retain every original branch/ref and source field.+ // Inventory display aliases must not change an outstanding request's identity.+ source_data: finding.evidence.source_data,+ repository: repository+ ? {+ id: repository.id,+ // Publication targets use Cloud's GitHub URL semantics. Input+ // joins above still require provenance for custom-host folding.+ url: repositoryUrlKey(repository.url).toLowerCase(),+ }+ : null,+ },+ };+ });+ return {+ current,+ legacy,+ currentIdentity: identity(current),+ legacyIdentity: identity(legacy),+ };+}++async function readFindingInput(path: string): Promise<FindingInput> {+ try {+ return records(parseJsonOrJsonl(await readScannerText(path)));+ } catch (cause) {+ throw new CodexSecurityError(+ `Could not read vendor findings as UTF-8 JSON or JSONL: ${cause instanceof Error ? cause.message : String(cause)}`,+ { cause },+ );+ }+}++function normalizeFindings(+ input: FindingInput,+ normalized?: WeakSet<VendorFinding>,+ legacy = false,+): VendorFindings {+ const result: VendorFindings = {+ read: input.records.length,+ findings: [],+ excluded: [],+ };+ const identities = new Set<string>();+ for (const [index, item] of input.records.entries()) {+ const record = object(item.value);+ try {+ if (!record) throw new Error("Finding must be an object.");+ let finding: VendorFinding;+ if ("source_finding_id" in record) {+ if (+ Object.keys(record).some(+ (key) => !["source_finding_id", "evidence"].includes(key),+ )+ ) {+ throw new Error(+ "Normalized input permits only source_finding_id and evidence.",+ );+ }+ finding = {+ source_finding_id: sourceFindingId(record["source_finding_id"]),+ evidence: validateExternalEvidence(record["evidence"]),+ };+ } else if (item.kind === "cloud_configuration") {+ throw new Error(+ "Cloud configuration findings require a resource-scoped import and cannot be published to a repository.",+ );+ } else if (item.kind && item.kind !== "sca") {+ finding = repositoryFinding(+ item.kind,+ record,+ input.repositories,+ legacy,+ );+ } else {+ if (+ !item.kind &&+ (object(record["repository"]) ||+ object(record["repositoryBranch"]) ||+ object(record["resource"]))+ )+ throw new Error(+ "Raw SAST, secret, and IaC records require their named sastFindings, secretInstances, or iacFindings collection. Bare arrays do not identify the finding family; use normalized JSONL for an explicit mapping.",+ );+ finding = wizFinding(record);+ }+ if (identities.has(finding.source_finding_id)) {+ throw new CodexSecurityError(+ `Duplicate source finding id ${JSON.stringify(finding.source_finding_id)}. Select each vendor occurrence once.`,+ );+ }+ identities.add(finding.source_finding_id);+ result.findings.push(finding);+ if ("source_finding_id" in record) normalized?.add(finding);+ } catch (error) {+ if (error instanceof CodexSecurityError) throw error;+ result.excluded.push({+ position: index + 1,+ source_finding_id:+ text(record?.["source_finding_id"]) ?? text(record?.["id"]),+ reason: error instanceof Error ? error.message : String(error),+ });+ }+ }+ return result;+}diff --git a/sdk/typescript/tests-ts/bind-repo-scopes.test.ts b/sdk/typescript/tests-ts/bind-repo-scopes.test.tsindex 2bc19b750..1075691da 100644--- a/sdk/typescript/tests-ts/bind-repo-scopes.test.ts+++ b/sdk/typescript/tests-ts/bind-repo-scopes.test.ts@@ -287,6 +287,7 @@ test.skipIf(process.platform === "win32")(const f = fixture();const target = join(f.root, "coverage-target.json");writeFileSync(target, "{}", { mode: 0o640 });+ chmodSync(target, 0o640);rmSync(f.coverage);symlinkSync(target, f.coverage);expect(run(f).status).toBe(0);diff --git a/sdk/typescript/tests-ts/cloud-publish.test.ts b/sdk/typescript/tests-ts/cloud-publish.test.tsindex 9a12be5b2..dcba30e77 100644--- a/sdk/typescript/tests-ts/cloud-publish.test.ts+++ b/sdk/typescript/tests-ts/cloud-publish.test.ts@@ -587,6 +587,53 @@ describe("Cloud publication", () => {expect(requestedUrl).toBe(publishUrl);});+ test("uses the shared Cloud API base while preserving the publication URL override", async () => {+ const { scan, environment } = await fixture();+ const cloudBase = "https://cloud.example.test/pilot/backend-api/aardvark";+ const urls: string[] = [];+ const fetch = async (url: string | URL | Request) => {+ urls.push(String(url));+ return Response.json(receipt);+ };+ await publishScanToCloud(scan, {+ environment: {+ ...environment,+ CODEX_SECURITY_CLOUD_BASE_URL: `${cloudBase}/`,+ },+ fetch,+ });+ const publishUrl = "https://other-cloud.example.test/publish";+ await publishScanToCloud(scan, {+ environment: {+ ...environment,+ CODEX_SECURITY_CLOUD_BASE_URL: cloudBase,+ CODEX_SECURITY_CLOUD_PUBLISH_URL: publishUrl,+ },+ fetch,+ });+ expect(urls).toEqual([`${cloudBase}/cli/findings`, publishUrl]);+ });++ test("rejects a remote HTTP Cloud base before reading credentials or sending a scan", async () => {+ const { scan, home, environment } = await fixture();+ await rm(join(home, "auth.json"));+ let requests = 0;+ await expect(+ publishScanToCloud(scan, {+ environment: {+ ...environment,+ CODEX_SECURITY_CLOUD_BASE_URL:+ "http://cloud.example.test/backend-api/aardvark",+ },+ fetch: async () => {+ requests++;+ return Response.json(receipt);+ },+ }),+ ).rejects.toThrow("requires HTTPS");+ expect(requests).toBe(0);+ });+test("reuses the dedicated Codex Security login and honors an explicit logout", async () => {const { scan, environment } = await fixture();const home = codexSecurityCredentialHome(environment);diff --git a/sdk/typescript/tests-ts/deep-review-input.test.ts b/sdk/typescript/tests-ts/deep-review-input.test.tsindex 8a71452a3..97d699026 100644--- a/sdk/typescript/tests-ts/deep-review-input.test.ts+++ b/sdk/typescript/tests-ts/deep-review-input.test.ts@@ -1,5 +1,6 @@import { spawnSync } from "node:child_process";import {+ chmodSync,existsSync,mkdirSync,mkdtempSync,@@ -359,6 +360,7 @@ describe("deep-review worklists", () => {const f = fixture();const target = join(f.root, "target.jsonl");writeFileSync(target, "existing", { mode: 0o640 });+ chmodSync(target, 0o640);symlinkSync(target, f.output);write(f.input, [candidate("a.py")]);const inputLink = join(f.root, "input-link");diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.tsnew file mode 100644index 000000000..743ee60be--- /dev/null+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts@@ -0,0 +1,2774 @@+import { createServer, type ServerResponse } from "node:http";+import { execFile } from "node:child_process";+import { hash } from "node:crypto";+import * as fs from "node:fs/promises";+import {+ mkdtemp,+ mkdir,+ readFile,+ readdir,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import { promisify } from "node:util";+import { gzipSync } from "node:zlib";+import { Database } from "bun:sqlite";+import { afterEach, expect, spyOn, test } from "bun:test";+import {+ ExternalPublicationError,+ prepareExternalPublication,+ prepareNormalizedExternalPublication,+ type ExternalPublicationProgress,+} from "../src/external-findings-publish.js";+import { readVendorFindings } from "../src/wiz-findings.js";+import {+ validateExternalEvidence,+ validateImportRequest,+ validateRepositories,+} from "../src/external-import-contract.js";+import type {+ FindingImportReceipt,+ FindingImportRequest,+ SourceReport,+} from "../src/external-import-models.js";+import { main } from "../src/cli.js";+import { dependencies } from "./cli-fixtures.js";+import { createCliTest } from "./support/cli-run.js";++const cleanups: (() => Promise<void>)[] = [];+afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();+});+const options = {+ repository: "repo-example",+ provider: "wiz" as const,+ sourceKey: "tenant-example/vulnerability-finding",+};+const normalized = (id = "vendor-1", severity = "high") => ({+ source_finding_id: id,+ evidence: {+ title: "Example vulnerable package",+ severity,+ source_data: { id },+ },+});++test("Wiz's gzip JSON report retains finding identity, evidence and repository locations", async () => {+ const report = {+ id: "vendor-report-1",+ name: "CVE-2026-0001",+ detailedName: "example-package",+ version: "1.2.3",+ fixedVersion: "1.2.4",+ vendorSeverity: "HIGH",+ detectionMethod: "LIBRARY",+ description: "Reported vulnerable package in the repository lockfile.",+ locationPath: "/pnpm-lock.yaml",+ lastDetectedAt: "2026-01-01T00:00:00Z",+ vulnerableAsset: {+ id: "vendor-repository-branch-1",+ nativeType: "github#repositoryBranch",+ name: "example/project/main",+ cloudProviderURL: "https://github.com/example/project/tree/main",+ },+ };+ const f = await fixture();+ // Wiz can keep the .json filename while compression is enabled.+ await writeFile(+ f.file,+ gzipSync(+ [report, { ...report, id: "vendor-report-2" }]+ .map((record) => JSON.stringify(record))+ .join("\n"),+ ),+ );+ const parsed = await readVendorFindings(f.file);+ expect(parsed.read).toBe(2);+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]).toMatchObject({+ source_finding_id: report.id,+ evidence: {+ severity: "high",+ packages: [{ name: "example-package", manifest_path: "pnpm-lock.yaml" }],+ locations: [{ path: "pnpm-lock.yaml" }],+ source_updated_at: null,+ code_revision: null,+ source_data: report,+ },+ });+ const result = await (+ await prepareExternalPublication(f.file, options, f.deps)+ ).publish();+ expect(result.counts.created).toBe(2);+ expect(result.verified).toBe(2);++ await writeFile(+ f.file,+ JSON.stringify([+ {+ ...report,+ vulnerableAsset: { id: "workload-1", type: "CONTAINER_IMAGE" },+ },+ ]),+ );+ const workload = await readVendorFindings(f.file);+ expect(workload.findings[0]!.evidence.locations).toEqual([]);+ expect(+ workload.findings[0]!.evidence.packages?.[0]?.manifest_path,+ ).toBeNull();+});++test("a Wiz Raw Event export explains the finding-report path before contacting Cloud", async () => {+ const f = await fixture({+ id: "scan-event-1",+ codeAnalyzerDetails: { commit: { ref: "main" } },+ scannersRunStatuses: {+ vulnerabilities: { enabled: true, status: "SUCCESS" },+ },+ analytics: { numVulnerabilityFindings: 3 },+ });+ let contactedCloud = false;+ await expect(+ prepareExternalPublication(f.file, options, {+ ...f.deps,+ fetch: async () => {+ contactedCloud = true;+ throw new Error("Unexpected Cloud request");+ },+ }),+ ).rejects.toThrow("scan metadata rather than vulnerability records");+ expect(contactedCloud).toBe(false);+});++async function fixture(records: unknown = [normalized()]) {+ const root = await mkdtemp(join(tmpdir(), "external-findings-"));+ cleanups.push(() => rm(root, { recursive: true, force: true }));+ const file = join(root, "selected findings.json");+ await writeFile(file, JSON.stringify(records));+ const environment = {+ ...process.env,+ CODEX_HOME: join(root, "credentials"),+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ };+ await mkdir(environment.CODEX_HOME, { mode: 0o700 });+ await writeFile(+ join(environment.CODEX_HOME, "config.toml"),+ 'cli_auth_credentials_store = "file"\n',+ );+ await writeFile(+ join(environment.CODEX_HOME, "auth.json"),+ JSON.stringify({+ tokens: {+ access_token: "synthetic-token",+ account_id: "synthetic-account",+ },+ }),+ );+ const reports = new Map<string, SourceReport>();+ const receipts = new Map<string, FindingImportReceipt>();+ const posts: string[] = [];+ const state = {+ marker: "generation-1",+ environmentId: "environment-example" as string | null,+ materializeDefaults: false,+ holdReadback: null as (() => void) | null,+ loseResponse: false,+ brokenReadback: false,+ throttle: false,+ postBudget: Infinity,+ finalError: false,+ };+ const destination = () => ({+ id: options.repository,+ object: "security.repository",+ repo_connector_id: "github",+ url: "https://github.com/example/project",+ default_branch: "main",+ reset_marker: state.marker,+ import_environment_id: state.environmentId,+ });+ function json(response: ServerResponse, value: unknown, status = 200) {+ response.writeHead(status, { "Content-Type": "application/json" });+ response.end(JSON.stringify(value));+ }+ const server = createServer(async (incoming, response) => {+ try {+ expect(incoming.headers.authorization).toBe("Bearer synthetic-token");+ expect(incoming.headers["chatgpt-account-id"]).toBe("synthetic-account");+ const url = new URL(incoming.url!, "http://localhost");+ if (url.pathname.endsWith("/repositories"))+ return json(response, {+ object: "page",+ data: [destination()],+ has_more: false,+ next: null,+ });+ if (url.pathname.endsWith("/source_reports")) {+ const report = reports.get(url.searchParams.get("source_finding_id")!);+ let summary;+ if (report) {+ const { evidence, last_import: _lastImport, ...rest } = report;+ summary = {+ ...rest,+ object: "security.source_report_summary",+ title: evidence.title,+ severity: evidence.severity,+ source_updated_at: evidence.source_updated_at ?? null,+ };+ }+ return json(response, {+ object: "page",+ data: summary ? [summary] : [],+ has_more: false,+ next: null,+ });+ }+ if (url.pathname.includes("/source_reports/")) {+ if (state.holdReadback) return state.holdReadback();+ if (state.brokenReadback)+ return json(+ response,+ { error: { message: "Readback unavailable" } },+ 503,+ );+ const report = [...reports.values()].find(+ (item) =>+ item.id === decodeURIComponent(url.pathname.split("/").at(-1)!),+ );+ if (report && state.materializeDefaults)+ return json(response, {+ ...report,+ evidence: {+ advisory_ids: [],+ locations: [],+ image_digests: [],+ source_data: {},+ ...report.evidence,+ packages: (report.evidence.packages ?? []).map((entry) => ({+ fixed_versions: [],+ ...entry,+ })),+ },+ });+ return json(response, report, report ? 200 : 404);+ }+ if (url.pathname.endsWith("/finding_imports")) {+ let body = "";+ for await (const chunk of incoming) body += chunk;+ posts.push(body);+ const request = validateImportRequest(JSON.parse(body));+ if (state.throttle || state.postBudget === 0) {+ response.setHeader("Retry-After", "1");+ return json(response, { error: { message: "Slow down" } }, 429);+ }+ state.postBudget--;+ if (request.repository.reset_marker !== state.marker)+ return json(+ response,+ { error: { message: "stale_reset_marker" } },+ 409,+ );+ let receipt = receipts.get(request.request_id);+ if (!receipt) {+ receipt = {+ id: request.request_id,+ object: "security.finding_import",+ repository: request.repository,+ source: request.source,+ actor: "synthetic-user",+ created_at: 1,+ item_count: request.items.length,+ counts: { created: 0, updated: 0, unchanged: 0, error: 0 },+ results: [],+ };+ for (const item of request.items) {+ const previous = reports.get(item.source_finding_id);+ const scopeConflict =+ previous !== undefined &&+ previous.environment_id !== request.repository.environment_id;+ if (state.finalError || scopeConflict) {+ receipt.counts.error = (receipt.counts.error ?? 0) + 1;+ receipt.results.push({+ client_id: item.client_id,+ outcome: "error",+ source_report_id: null,+ observation_id: null,+ canonical_finding_id: null,+ version: null,+ error: {+ code: scopeConflict ? "scope_conflict" : "version_conflict",+ message: scopeConflict+ ? "Source report belongs to a different Cloud environment"+ : "Reload current evidence",+ },+ });+ continue;+ }+ const outcome = previous+ ? JSON.stringify(previous.evidence) ===+ JSON.stringify(item.evidence)+ ? "unchanged"+ : "updated"+ : "created";+ if (outcome === "updated")+ expect(item.expected_version).toBe(previous!.version);+ const version = previous+ ? previous.version + (outcome === "updated" ? 1 : 0)+ : 1;+ const identity = hash("sha256", item.source_finding_id);+ const report: SourceReport = {+ id: `aif_${identity}`,+ object: "security.source_report",+ origin: "imported",+ repo_id: request.repository.id,+ repo_connector_id: request.repository.repo_connector_id,+ environment_id: request.repository.environment_id,+ canonical_finding_id: `acf_${identity.slice(0, 32)}`,+ source: request.source,+ source_finding_id: item.source_finding_id,+ observation_id: `aio_${hash("sha256", `${identity}:${version}`)}`,+ version,+ evidence: item.evidence,+ assessment: { state: "not_assessed" },+ last_import: null,+ created_at: 1,+ updated_at: version,+ };+ reports.set(item.source_finding_id, report);+ receipt.counts[outcome] = (receipt.counts[outcome] ?? 0) + 1;+ receipt.results.push({+ client_id: item.client_id,+ outcome,+ source_report_id: report.id,+ observation_id: report.observation_id,+ canonical_finding_id: report.canonical_finding_id,+ version,+ error: null,+ });+ }+ receipts.set(request.request_id, receipt);+ }+ if (state.loseResponse) {+ state.loseResponse = false;+ response.destroy();+ return;+ }+ return json(response, receipt);+ }+ json(response, { error: { message: "Unexpected fixture route" } }, 404);+ } catch (error) {+ json(response, { error: { message: String(error) } }, 500);+ }+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ cleanups.push(+ () =>+ new Promise<void>((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()));+ server.closeAllConnections();+ }),+ );+ const port = (server.address() as { port: number }).port;+ const transport = (url: string, init: RequestInit) =>+ fetch(+ `http://127.0.0.1:${port}${new URL(url).pathname}${new URL(url).search}`,+ init,+ );+ const deps = { environment, fetch: transport };+ const cliDeps = { ...dependencies(), environment, cloudFetch: transport };+ const command = [+ "publish",+ "findings",+ file,+ "--to",+ "cloud",+ "--repository",+ options.repository,+ "--provider",+ options.provider,+ "--source-key",+ options.sourceKey,+ "--format",+ "json",+ ];+ return {+ root,+ file,+ reports,+ receipts,+ posts,+ state,+ destination,+ environment,+ port,+ deps,+ cliDeps,+ command,+ };+}++test("Wiz occurrence mapping preserves original evidence without inventing repository provenance", async () => {+ const record = {+ id: "wiz-occurrence",+ name: "CVE-2099-0001",+ detailedName: "example-lib",+ version: "1.2.0",+ fixedVersion: "1.2.1",+ vendorSeverity: "HIGH",+ portalUrl: "https://example.test/finding",+ locationPath: "/usr/lib/example",+ lastDetectedAt: "2026-10-01T00:00:00Z",+ projects: [{ id: "project-a" }, { id: "project-b" }],+ packageManager: "legacy-manager",+ vulnerableAsset: { id: "image-resource", imageDigest: "sha256:example" },+ };+ const f = await fixture([record]);+ const parsed = await readVendorFindings(f.file);+ expect(parsed.findings[0]).toMatchObject({+ source_finding_id: record.id,+ evidence: {+ severity: "high",+ locations: [],+ code_revision: null,+ branch: null,+ source_updated_at: null,+ source_data: record,+ image_digests: ["sha256:example"],+ advisory_ids: [record.name],+ packages: [{ name: "example-lib", ecosystem: "legacy-manager" }],+ },+ });+});++test("Wiz API nodes preserve artifact ecosystems and distinguish container digests from VM image IDs", async () => {+ const finding = {+ name: "Vendor display advisory",+ vulnerabilityExternalId: "CVE-2099-0001",+ detailedName: "example-package",+ version: "1.2.0",+ vendorSeverity: "HIGH",+ };+ const records = [+ {+ ...finding,+ id: "container-package",+ artifactType: { osPackageManager: "DPKG", codeLibraryLanguage: null },+ codeLibraryLanguage: "JAVA",+ vulnerableAsset: {+ id: "container-image",+ type: "CONTAINER_IMAGE",+ imageId: `sha256:${"a".repeat(64)}`,+ },+ },+ {+ ...finding,+ id: "vm-library",+ artifactType: { osPackageManager: null, codeLibraryLanguage: "PYTHON" },+ codeLibraryLanguage: "JAVA",+ vulnerableAsset: {+ id: "virtual-machine",+ type: "VIRTUAL_MACHINE",+ imageId: "ami-synthetic",+ containerImageId: "ami-synthetic-alias",+ },+ },+ {+ ...finding,+ id: "container-alias",+ vulnerableAsset: {+ id: "aliased-image",+ type: "CONTAINER_IMAGE",+ containerImageId: `sha256:${"d".repeat(64)}`,+ },+ },+ {+ ...finding,+ id: "running-container",+ vulnerableAsset: {+ id: "running-image",+ type: "CONTAINER",+ ImageExternalId: `sha256:${"e".repeat(64)}`,+ },+ },+ {+ ...finding,+ id: "explicit-metadata",+ packageManager: "reported-manager",+ imageDigest: `sha256:${"b".repeat(64)}`,+ artifactType: { osPackageManager: "DPKG" },+ codeLibraryLanguage: "JAVA",+ vulnerableAsset: {+ id: "explicit-container",+ type: "CONTAINER_IMAGE",+ imageId: `sha256:${"c".repeat(64)}`,+ },+ },+ {+ ...finding,+ id: "legacy-library",+ codeLibraryLanguage: "JAVASCRIPT",+ vulnerableAsset: { id: "legacy-image" },+ },+ ];+ const f = await fixture({+ data: {+ vulnerabilityFindings: {+ nodes: records,+ pageInfo: { hasNextPage: false },+ },+ },+ });+ const parsed = await readVendorFindings(f.file);+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.evidence.title).toContain(finding.name);+ expect(parsed.findings.map(({ evidence }) => evidence.advisory_ids)).toEqual(+ records.map(() => [finding.vulnerabilityExternalId]),+ );+ expect(+ parsed.findings.map(({ evidence }) => ({+ ecosystem: evidence.packages?.[0]?.ecosystem,+ digests: evidence.image_digests,+ })),+ ).toEqual([+ { ecosystem: "DPKG", digests: [`sha256:${"a".repeat(64)}`] },+ { ecosystem: "PYTHON", digests: [] },+ { ecosystem: null, digests: [`sha256:${"d".repeat(64)}`] },+ { ecosystem: null, digests: [`sha256:${"e".repeat(64)}`] },+ { ecosystem: "reported-manager", digests: [`sha256:${"b".repeat(64)}`] },+ { ecosystem: "JAVASCRIPT", digests: [] },+ ]);+ expect(parsed.findings.map(({ evidence }) => evidence.source_data)).toEqual(+ records,+ );+});++test("Wiz network-scan findings are excluded without requiring a detection method on package exports", async () => {+ const supported = {+ id: "package-occurrence",+ name: "CVE-2099-0001",+ detailedName: "example-package",+ vendorSeverity: "HIGH",+ vulnerableAsset: { id: "synthetic-asset" },+ };+ const network = {+ ...supported,+ id: "network-occurrence",+ name: "CWE-89",+ detailedName: "GET /synthetic-endpoint",+ detectionMethod: "EXTERNAL_NETWORK_SCAN",+ };+ const f = await fixture([supported, network]);+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ expect(+ prepared.preview.findings.map((finding) => finding.source_finding_id),+ ).toEqual([supported.id]);+ expect(prepared.preview.excluded).toEqual([+ expect.objectContaining({+ source_finding_id: network.id,+ reason: expect.stringContaining("external network"),+ }),+ ]);+ expect((await prepared.publish()).counts.created).toBe(1);+ expect(f.reports.has(network.id)).toBe(false);+});++test("unsupported records are visible exclusions; duplicate identities and unfinished pages stop publication", async () => {+ const f = await fixture([normalized(), normalized("unknown", "unsupported")]);+ const parsed = await readVendorFindings(f.file);+ expect(parsed.findings).toHaveLength(1);+ expect(parsed.excluded).toHaveLength(1);+ await writeFile(f.file, JSON.stringify([normalized(), normalized()]));+ await expect(readVendorFindings(f.file)).rejects.toThrow("Duplicate source");+ await writeFile(+ f.file,+ JSON.stringify({+ data: {+ vulnerabilityFindings: {+ nodes: [normalized()],+ pageInfo: { hasNextPage: true },+ },+ },+ }),+ );+ await expect(readVendorFindings(f.file)).rejects.toThrow("another page");+});++test("Cloud evidence constraints exclude invalid normalized records before approval", async () => {+ let nested: unknown = "leaf";+ for (let index = 0; index < 20; index++) nested = { child: nested };+ const invalid = [+ { title: "é".repeat(300) },+ { description: "" },+ { packages: [{ name: "example", installed_version: "1.0\0" }] },+ { advisory_ids: ["é".repeat(300)] },+ { locations: [{ path: "../outside.ts" }] },+ { url: "https://[email protected]/finding" },+ { source_data: { content: "x".repeat(6 * 1024 * 1024) } },+ { source_data: { nested } },+ { url: "https://[example.test" },+ ].map((evidence, index) => ({+ source_finding_id: `invalid-${index}`,+ evidence: { ...normalized().evidence, ...evidence },+ }));+ const f = await fixture([normalized(), ...invalid]);+ const cli = createCliTest(main);+ expect(await cli.runCli([...f.command, "--dry-run"], f.cliDeps)).toBe(0);+ const preview = JSON.parse(cli.stdout.text());+ expect(preview.findings).toHaveLength(1);+ expect(preview.excluded).toHaveLength(invalid.length);+ expect(preview.excluded[6].reason).toContain("256 KiB");+ expect(f.posts).toHaveLength(0);+ await writeFile(f.file, JSON.stringify(invalid));+ const rejected = createCliTest(main);+ expect(await rejected.runCli([...f.command, "--yes"], f.cliDeps)).toBe(2);+ expect(rejected.stderr.text()).toContain("No supported findings");+ expect(f.posts).toHaveLength(0);+ expect(await readdir(join(f.root, "state")).catch(() => [])).toEqual([]);+});++test("raw Wiz records apply Cloud string and URL constraints before approval", async () => {+ const wiz = {+ id: "wiz-valid",+ name: "CVE-2099-0001",+ detailedName: "example-package",+ vendorSeverity: "HIGH",+ vulnerableAsset: { id: "example-image" },+ };+ const f = await fixture([+ wiz,+ { ...wiz, id: "wiz-title", title: "é".repeat(300) },+ { ...wiz, id: "é".repeat(300) },+ { ...wiz, id: "wiz\0id" },+ { ...wiz, id: "wiz-url", portalUrl: "https://@example.test" },+ ]);+ const cli = createCliTest(main);+ expect(await cli.runCli([...f.command, "--dry-run"], f.cliDeps)).toBe(0);+ const preview = JSON.parse(cli.stdout.text());+ expect(preview.findings).toHaveLength(1);+ expect(preview.excluded).toHaveLength(4);+ expect(f.posts).toHaveLength(0);+});++test("Cloud validation preserves allowed evidence boundaries and raw vendor strings", () => {+ let nested: unknown = "leaf";+ for (let index = 0; index < 18; index++) nested = { child: nested };+ const evidence = {+ title: "é".repeat(256),+ severity: "high" as const,+ description: "é".repeat(32768),+ url: "https://example.test:non-numeric/finding",+ advisory_ids: [" ", "\0", "é".repeat(256)],+ packages: [{ name: "example", manifest_path: "../vendor-manifest" }],+ locations: [{ path: "src\\example.ts" }],+ source_data: { nested, title: "", path: "\0", content: "x".repeat(4096) },+ };+ expect(validateExternalEvidence(evidence)).toEqual(evidence);+ for (const url of [+ "ftp://example.test",+ "https:///finding",+ "https:\\example.test",+ "http://@example.test",+ "https://[127.0.0.1]/finding",+ "https://[example.test]/finding",+ "https://prefix[::1]/finding",+ "https://[::1]suffix/finding",+ "https://[::1%]/finding",+ "https://[::1%a%b]/finding",+ "https://example.com/path",+ "https://example.test\uFF1A443/finding",+ "https://exam\u2100ple.test/finding",+ ]) {+ expect(() => validateExternalEvidence({ ...evidence, url })).toThrow(+ "HTTP(S)",+ );+ }+ for (const url of [+ "https://[::1]/finding",+ "https://[fe80::1%25eth0]/finding",+ "https://[fe80::1%zone!]/finding",+ "https://[v1.example]/finding",+ "https://[vF.example]:service",+ "https://[fe80::1%eth0]/finding",+ "https://[::1]:non-numeric/finding",+ "https://bücher.example/finding",+ ]) {+ expect(validateExternalEvidence({ ...evidence, url }).url).toBe(url);+ }+ for (const path of ["/absolute.ts", "C:\\source.ts", "src\\..\\outside.ts"]) {+ expect(() =>+ validateExternalEvidence({ ...evidence, locations: [{ path }] }),+ ).toThrow("repository-relative");+ }+ expect(() =>+ validateExternalEvidence({ ...evidence, source_data: { value: Infinity } }),+ ).toThrow("finite JSON");+});++test("request and pagination metadata retain Cloud byte limits and distinct identities", async () => {+ const f = await fixture();+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ const request = prepared.preview.requests[0]!;+ expect(() =>+ validateImportRequest({+ ...request,+ source: { ...request.source, source_key: "tenant\0" },+ }),+ ).toThrow("NUL");+ expect(() =>+ validateImportRequest({+ ...request,+ repository: { ...request.repository, id: "é".repeat(300) },+ }),+ ).toThrow("UTF-8");+ const item = request.items[0]!;+ expect(() =>+ validateImportRequest({+ ...request,+ items: [{ ...item, client_id: "é".repeat(100) }],+ }),+ ).toThrow("128 UTF-8");+ expect(() =>+ validateImportRequest({+ ...request,+ items: [item, { ...item, source_finding_id: "another" }],+ }),+ ).toThrow("duplicate client");+ expect(() =>+ validateImportRequest({+ ...request,+ items: [item, { ...item, client_id: "another" }],+ }),+ ).toThrow("duplicate source");+ const page = {+ data: [f.destination()],+ has_more: true,+ next: "é".repeat(2048),+ };+ expect(validateRepositories(page).next).toBe(page.next);+ expect(() =>+ validateRepositories({ ...page, next: `${page.next}é` }),+ ).toThrow("4096 UTF-8");+});++test("CLI preview and rejected confirmation never POST or persist an upload", async () => {+ const f = await fixture();+ const cli = createCliTest(main);+ const code = await cli.runCli([...f.command, "--dry-run"], f.cliDeps);+ expect({ code, error: cli.stderr.text() }).toEqual({ code: 0, error: "" });+ expect(JSON.parse(cli.stdout.text())).toMatchObject({+ dryRun: true,+ accountId: "synthetic-account",+ destination: {+ id: options.repository,+ import_environment_id: "environment-example",+ },+ read: 1,+ });+ expect(f.posts).toHaveLength(0);+ expect(await readdir(join(f.root, "state")).catch(() => [])).toEqual([]);+ const rejected = createCliTest(main);+ expect(+ await rejected.runCli(f.command, {+ ...f.cliDeps,+ externalPublicationPrompt: {+ isInteractive: () => true,+ confirm: async () => false,+ },+ }),+ ).toBe(0);+ expect(f.posts).toHaveLength(0);+ const headless = createCliTest(main);+ expect(await headless.runCli(f.command, f.cliDeps)).toBe(2);+ expect(headless.stderr.text()).toContain("needs confirmation");+});++test("CLI creates, reimports unchanged, and updates the same canonical finding", async () => {+ const f = await fixture();+ const first = createCliTest(main);+ expect(await first.runCli([...f.command, "--yes"], f.cliDeps)).toBe(0);+ const canonical = f.reports.get("vendor-1")!.canonical_finding_id;+ expect(JSON.parse(first.stdout.text()).counts.created).toBe(1);+ expect(first.stderr.text()).not.toContain("Selected findings and evidence:");+ const again = await prepareExternalPublication(f.file, options, f.deps);+ expect((await again.publish()).counts.unchanged).toBe(1);+ await writeFile(f.file, JSON.stringify([normalized("vendor-1", "critical")]));+ const updated = await prepareExternalPublication(f.file, options, f.deps);+ expect(updated.preview.requests[0]!.items[0]!.expected_version).toBe(1);+ expect((await updated.publish()).counts.updated).toBe(1);+ expect(f.reports.get("vendor-1")).toMatchObject({+ canonical_finding_id: canonical,+ version: 2,+ });+});++test("normalized input accepts server-materialized optional evidence defaults", async () => {+ const f = await fixture([+ {+ source_finding_id: "vendor-1",+ evidence: {+ title: "Example vulnerable package",+ severity: "high",+ packages: [{ name: "example-package" }],+ },+ },+ ]);+ f.state.materializeDefaults = true;+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ expect((await prepared.publish()).counts.created).toBe(1);+ expect(f.reports.get("vendor-1")?.evidence).toMatchObject({+ advisory_ids: [],+ packages: [{ name: "example-package", fixed_versions: [] }],+ locations: [],+ image_digests: [],+ source_data: {},+ });+ const stateFiles = await readdir(+ join(f.root, "state", "external-finding-publications"),+ );+ expect(stateFiles.some((name) => name.endsWith(".pending.json"))).toBe(false);+});++test.each(["human", "json"])(+ "interactive %s publication summarizes the input and confirms exclusions",+ async (format) => {+ const selected = {+ ...normalized("vendor-selected"),+ evidence: {+ ...normalized("vendor-selected").evidence,+ title: "Selected \u001b[31m evidence",+ description: "Description to approve",+ source_data: { id: "vendor-selected", note: "Original vendor detail" },+ },+ };+ const f = await fixture([+ selected,+ normalized("unsupported", "unsupported"),+ ]);+ const cli = createCliTest(main);+ let prompted = false;+ expect(+ await cli.runCli(format === "json" ? f.command : f.command.slice(0, -2), {+ ...f.cliDeps,+ externalPublicationPrompt: {+ isInteractive: () => true,+ confirm: async (question, defaultValue) => {+ prompted = true;+ expect(defaultValue).toBe(false);+ expect(cli.stderr.text()).toContain(+ "https://github.com/example/project",+ );+ expect(cli.stderr.text()).toContain(options.sourceKey);+ expect(cli.stderr.text()).toContain("synthetic-account");+ expect(cli.stderr.text()).toContain("environment-example");+ expect(cli.stderr.text()).toContain("Excluded: 1");+ expect(question).toContain("skip 1 excluded");+ expect(cli.stderr.text()).toContain("vendor-selected [high]");+ expect(cli.stderr.text()).toContain(f.file);+ expect(cli.stderr.text()).toContain("--dry-run --format json");+ expect(cli.stderr.text()).not.toContain("Original vendor detail");+ expect(cli.stderr.text()).not.toContain("\u001b");+ expect(cli.stderr.text()).not.toContain("synthetic-token");+ expect(cli.stdout.text()).toBe("");+ expect(f.posts).toHaveLength(0);+ return true;+ },+ },+ }),+ ).toBe(1);+ expect(prompted).toBe(true);+ expect(f.reports.has("vendor-selected")).toBe(true);+ if (format === "json") {+ const result = JSON.parse(cli.stdout.text());+ expect(result.status).toBe("partial");+ expect(result.counts.created).toBe(1);+ expect(result.cloudUrl).toBe(+ `https://chatgpt.com/mcp-app/connector_openai_defense_factory/open_defense_factory#/repositories/${options.repository}/findings`,+ );+ } else {+ expect(cli.stdout.text()).toContain(+ "View Cloud repository: https://chatgpt.com/mcp-app/",+ );+ expect(cli.stdout.text()).not.toContain("/codex/cloud/security/findings");+ }+ },+);++test.each([false, true])(+ "saved request survives a publisher process restart (abrupt: %p)",+ async (abrupt) => {+ const f = await fixture();+ const runner = join(f.root, "run-cli.ts");+ const cliUrl = pathToFileURL(join(import.meta.dir, "../src/cli.ts")).href;+ const fixturesUrl = pathToFileURL(+ join(import.meta.dir, "cli-fixtures.ts"),+ ).href;+ await writeFile(+ runner,+ `import { main } from ${JSON.stringify(cliUrl)};\nimport { dependencies } from ${JSON.stringify(fixturesUrl)};\nprocess.exitCode = await main(process.argv.slice(2), process.stdout, process.stderr, { ...dependencies({ environment: process.env }), cloudFetch: (url, init) => fetch('http://127.0.0.1:${f.port}' + new URL(url).pathname + new URL(url).search, init) });\n`,+ );+ function run() {+ const process = Bun.spawn(+ [Bun.which("bun")!, runner, ...f.command, "--yes"],+ { env: f.environment, stdout: "pipe", stderr: "pipe" },+ );+ const result = Promise.all([+ process.exited,+ new Response(process.stdout).text(),+ new Response(process.stderr).text(),+ ]).then(([code, stdout, stderr]) => ({ code, stdout, stderr }));+ return { process, result };+ }+ const readback = Promise.withResolvers<void>();+ if (abrupt) f.state.holdReadback = () => readback.resolve();+ else f.state.loseResponse = true;+ const first = run();+ if (abrupt) {+ await readback.promise;+ first.process.kill("SIGKILL");+ }+ const lost = await first.result;+ expect(lost.code).not.toBe(0);+ if (!abrupt) {+ expect(lost.code).toBe(2);+ expect(lost.stderr).toContain("resume the saved request");+ }+ expect(f.reports.size).toBe(1);+ const firstBody = f.posts[0];+ f.state.holdReadback = null;+ const second = await run().result;+ expect(second.code).toBe(0);+ if (abrupt) expect(f.posts).toHaveLength(1);+ else expect(f.posts[1]).toBe(firstBody);+ expect(f.receipts.size).toBe(1);+ expect(JSON.parse(second.stdout).counts.created).toBe(1);+ },+);++function observeLockContention() {+ const contended = Promise.withResolvers<void>();+ const original = Database.prototype.exec;+ const spy = spyOn(Database.prototype, "exec").mockImplementation(function (+ this: Database,+ ...args: Parameters<typeof original>+ ) {+ try {+ return original.apply(this, args);+ } catch (error) {+ if (+ args[0] === "BEGIN EXCLUSIVE" &&+ (error as { code?: string }).code === "SQLITE_BUSY"+ )+ contended.resolve();+ throw error;+ }+ });+ return { contended: contended.promise, restore: () => spy.mockRestore() };+}++async function pauseAtPublication(+ f: Awaited<ReturnType<typeof fixture>>,+ stage: "receipt" | "readback" = "readback",+) {+ const arrived = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const completion = (+ await prepareExternalPublication(f.file, options, {+ ...f.deps,+ fetch: async (url, init) => {+ const response =+ stage === "receipt" ? await f.deps.fetch(url, init) : undefined;+ if (+ (stage === "receipt" && init.method === "POST") ||+ (stage === "readback" &&+ new URL(url).pathname.includes("/source_reports/"))+ ) {+ arrived.resolve();+ await release.promise;+ }+ return response ?? f.deps.fetch(url, init);+ },+ })+ ).publish();+ await Promise.race([+ arrived.promise,+ completion.then(() => {+ throw new Error("Publication completed without reaching the pause.");+ }),+ ]);+ return { completion, release };+}++test("overlapping retries cannot delete a newer pending submission or roll back newer evidence", async () => {+ const f = await fixture();+ f.state.brokenReadback = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("resume the saved request");+ f.state.brokenReadback = false;+ const { completion: first, release } = await pauseAtPublication(f);+ const observer = observeLockContention();+ const second = (+ await prepareExternalPublication(f.file, options, f.deps)+ ).publish();+ try {+ await Promise.race([+ observer.contended,+ second.then(() => {+ throw new Error("Concurrent publication skipped the active lock.");+ }),+ ]);+ expect(f.posts).toHaveLength(1);+ release.resolve();+ await Promise.all([first, second]);+ expect(f.posts).toHaveLength(1);+ } finally {+ release.resolve();+ observer.restore();+ await Promise.allSettled([first, second]);+ }+ const newer = await prepareExternalPublication(f.file, options, f.deps);+ f.state.loseResponse = true;+ await expect(newer.publish()).rejects.toThrow("resume the saved request");+ const acceptedBody = f.posts.at(-1);+ await writeFile(f.file, JSON.stringify([normalized("vendor-1", "critical")]));+ await (await prepareExternalPublication(f.file, options, f.deps)).publish();+ await writeFile(f.file, JSON.stringify([normalized()]));+ const retry = await prepareExternalPublication(f.file, options, f.deps);+ expect(retry.preview.resumed).toBe(true);+ expect(retry.preview.requests[0]!.request_id).toBe(+ newer.preview.requests[0]!.request_id,+ );+ await retry.publish();+ expect(f.posts.at(-1)).toBe(acceptedBody);+ expect(f.reports.get("vendor-1")?.evidence.severity).toBe("critical");+});++test("reset retirement tolerates a checkpoint written while waiting for the active publisher", async () => {+ const f = await fixture();+ const { completion: active, release } = await pauseAtPublication(+ f,+ "receipt",+ );+ f.state.marker = "generation-2";+ f.state.environmentId = "replacement-environment";+ f.state.brokenReadback = true;+ const observer = observeLockContention();+ const reset = prepareExternalPublication(f.file, options, f.deps);+ const resetResult = reset.then(+ () => "unexpected-success",+ (error: Error) => error.message,+ );+ try {+ await Promise.race([+ observer.contended,+ resetResult.then(() => {+ throw new Error("Reset skipped the active publication lock.");+ }),+ ]);+ expect(f.posts).toHaveLength(1);+ release.resolve();+ await expect(active).rejects.toThrow("resume the saved request");+ expect(await resetResult).toContain("retired without uploading");+ } finally {+ release.resolve();+ observer.restore();+ await Promise.allSettled([active, resetResult]);+ }+ f.state.brokenReadback = false;+ f.reports.clear();+ const fresh = await prepareExternalPublication(f.file, options, f.deps);+ expect(fresh.preview.resumed).toBe(false);+ expect((await fresh.publish()).counts.created).toBe(1);+});++test.each(["receipt", "readback"] as const)(+ "canceling a waiting CLI preserves acknowledgements and the active request during %s",+ async (stage) => {+ const f = await fixture();+ const { completion: active, release } = await pauseAtPublication(f, stage);+ const directory = join(f.root, "state", "external-finding-publications");+ const name = (await readdir(directory)).find((name) =>+ name.endsWith(".pending.json"),+ )!;+ const before = await readFile(join(directory, name), "utf8");+ const listeners = new Map<string, () => void>();+ const cli = createCliTest(main);+ const observer = observeLockContention();+ const waiting = cli.runCli([...f.command, "--yes"], {+ ...f.cliDeps,+ addSignalListener: (signal, listener) => {+ listeners.set(signal, listener);+ },+ removeSignalListener: (signal) => {+ listeners.delete(signal);+ },+ });+ try {+ await Promise.race([+ observer.contended,+ waiting.then(() => {+ throw new Error("Concurrent publication skipped the active lock.");+ }),+ ]);+ listeners.get("SIGINT")!();+ expect(await waiting).toBe(130);+ const interrupted = JSON.parse(cli.stdout.text());+ expect(interrupted).toMatchObject({+ status: "interrupted",+ counts: { created: stage === "readback" ? 1 : 0 },+ unacknowledged: stage === "readback" ? 0 : 1,+ verified: 0,+ savedSubmission: join(directory, name),+ });+ expect(interrupted.receipts).toEqual(JSON.parse(before).receipts ?? []);+ expect(await readFile(join(directory, name), "utf8")).toBe(before);+ expect(listeners.size).toBe(0);+ expect(f.posts).toHaveLength(1);+ const retry = await prepareExternalPublication(f.file, options, f.deps);+ expect(retry.preview.resumed).toBe(true);+ expect(retry.preview.requests[0]!.request_id).toBe(+ JSON.parse(f.posts[0]!).request_id,+ );+ release.resolve();+ expect((await active).counts.created).toBe(1);+ } finally {+ release.resolve();+ observer.restore();+ await Promise.allSettled([active, waiting]);+ }+ },+);++test("canceling before acquiring a new publication lock reports no saved work", async () => {+ const f = await fixture();+ const controller = new AbortController();+ const prepared = await prepareExternalPublication(f.file, options, {+ ...f.deps,+ signal: controller.signal,+ });+ controller.abort();+ try {+ await prepared.publish();+ throw new Error("Expected cancellation");+ } catch (error) {+ expect(error).toBeInstanceOf(ExternalPublicationError);+ const result = (error as ExternalPublicationError).result;+ expect(result).toMatchObject({+ status: "interrupted",+ receipts: [],+ counts: { created: 0, updated: 0, unchanged: 0, error: 0 },+ unacknowledged: 1,+ verified: 0,+ });+ expect(result.savedSubmission).toBeUndefined();+ }+ expect(f.posts).toEqual([]);+ expect(+ (+ await readdir(join(f.root, "state", "external-finding-publications"))+ ).filter((name) => name.endsWith(".pending.json")),+ ).toEqual([]);+});++test("lock cancellation does not report a saved receipt for another request", async () => {+ const f = await fixture();+ f.state.brokenReadback = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("resume the saved request");+ const directory = join(f.root, "state", "external-finding-publications");+ const name = (await readdir(directory)).find((name) =>+ name.endsWith(".pending.json"),+ )!;+ const saved = JSON.parse(await readFile(join(directory, name), "utf8"));+ saved.receipts[0].id = "another-request";+ const bytes = JSON.stringify(saved);+ await writeFile(join(directory, name), bytes);+ const controller = new AbortController();+ const prepared = await prepareExternalPublication(f.file, options, {+ ...f.deps,+ signal: controller.signal,+ });+ controller.abort();+ await expect(prepared.publish()).rejects.toThrow(+ "receipt for a different publication",+ );+ expect(await readFile(join(directory, name), "utf8")).toBe(bytes);+ expect(f.posts).toHaveLength(1);+});++test.skipIf(process.platform !== "win32")(+ "Windows publication checkpoints start private beneath a shared parent",+ async () => {+ const f = await fixture();+ const shared = join(f.root, "shared");+ await mkdir(shared);+ f.environment.CODEX_SECURITY_STATE_DIR = join(shared, "state");+ const exec = promisify(execFile);+ const system = join(process.env["SystemRoot"] ?? "C:\\Windows", "System32");+ await exec(join(system, "icacls.exe"), [+ shared,+ "/grant",+ "*S-1-1-0:(OI)(CI)R",+ ]);+ const descriptor = async (path: string): Promise<string> => {+ const result = await exec(+ join(system, "WindowsPowerShell", "v1.0", "powershell.exe"),+ [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ "$ErrorActionPreference = 'Stop'; (Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $env:CODEX_SECURITY_TEST_ACL_PATH).Sddl",+ ],+ {+ env: {+ ...Object.fromEntries(+ Object.entries(process.env).filter(+ ([name]) => name.toUpperCase() !== "PSMODULEPATH",+ ),+ ),+ CODEX_SECURITY_TEST_ACL_PATH: path,+ PSModulePath: join(system, "WindowsPowerShell", "v1.0", "Modules"),+ },+ },+ );+ return result.stdout.trim();+ };+ const before = await descriptor(shared);+ expect(before).toContain(";;;WD)");+ f.state.brokenReadback = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("resume the saved request");+ const directory = join(+ f.environment.CODEX_SECURITY_STATE_DIR,+ "external-finding-publications",+ );+ const name = (await readdir(directory)).find((name) =>+ name.endsWith(".pending.json"),+ )!;+ for (const path of [f.environment.CODEX_SECURITY_STATE_DIR, directory]) {+ const acl = await descriptor(path);+ expect(acl).toContain("D:P");+ expect(acl).not.toContain(";;;WD)");+ }+ expect(await descriptor(join(directory, name))).not.toContain(";;;WD)");+ expect(await descriptor(shared)).toBe(before);+ f.state.brokenReadback = false;+ expect(+ (+ await (+ await prepareExternalPublication(f.file, options, f.deps)+ ).publish()+ ).counts.created,+ ).toBe(1);+ expect(f.posts).toHaveLength(1);+ },+ 60_000,+);++test("readback failure retries acknowledged receipts without another POST", async () => {+ const f = await fixture();+ f.state.brokenReadback = true;+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ await expect(prepared.publish()).rejects.toThrow("resume the saved request");+ f.state.brokenReadback = false;+ const retry = await prepareExternalPublication(f.file, options, f.deps);+ expect(retry.preview.resumed).toBe(true);+ expect((await retry.publish()).counts.created).toBe(1);+ expect(f.posts).toHaveLength(1);+});++test("an older pending receipt can resume after newer evidence without rolling it back", async () => {+ const f = await fixture();+ f.state.loseResponse = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("resume the saved request");+ const original = f.posts[0];+ await writeFile(f.file, JSON.stringify([normalized("vendor-1", "critical")]));+ expect(+ (+ await (+ await prepareExternalPublication(f.file, options, f.deps)+ ).publish()+ ).counts.updated,+ ).toBe(1);+ await writeFile(f.file, JSON.stringify([normalized()]));+ const replay = await (+ await prepareExternalPublication(f.file, options, f.deps)+ ).publish();+ expect(f.posts.at(-1)).toBe(original);+ expect(replay.receipts[0]!.results[0]!.version).toBe(1);+ expect(f.reports.get("vendor-1")).toMatchObject({+ version: 2,+ evidence: { severity: "critical" },+ });+});++test.each(["environment-example", "replacement-environment", null])(+ "repository reset retires a pending request with environment %p",+ async (environmentId) => {+ const f = await fixture();+ f.state.throttle = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("Retry-After: 1");+ f.state.marker = "generation-2";+ f.state.environmentId = environmentId;+ await expect(+ prepareExternalPublication(f.file, options, f.deps),+ ).rejects.toThrow("retired without uploading");+ expect(f.posts).toHaveLength(1);+ if (environmentId === null) {+ await expect(+ prepareExternalPublication(f.file, options, f.deps),+ ).rejects.toThrow("Configure an authorized Cloud environment");+ f.state.environmentId = "replacement-environment";+ }+ f.state.throttle = false;+ const fresh = await prepareExternalPublication(f.file, options, f.deps);+ expect(fresh.preview.resumed).toBe(false);+ expect(fresh.preview.requests[0]!.repository).toMatchObject({+ reset_marker: "generation-2",+ environment_id: f.state.environmentId,+ });+ expect((await fresh.publish()).counts.created).toBe(1);+ expect(f.posts).toHaveLength(2);+ expect(JSON.parse(f.posts[1]!).request_id).not.toBe(+ JSON.parse(f.posts[0]!).request_id,+ );+ },+);++test("batching preserves item order and keeps final item errors visible", async () => {+ const f = await fixture(+ Array.from({ length: 101 }, (_, index) => normalized(`vendor-${index}`)),+ );+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ expect(+ prepared.preview.requests.map((request) => request.items.length),+ ).toEqual([100, 1]);+ expect((await prepared.publish()).counts.created).toBe(101);+ const errorFixture = await fixture();+ errorFixture.state.finalError = true;+ const cli = createCliTest(main);+ expect(+ await cli.runCli([...errorFixture.command, "--yes"], errorFixture.cliDeps),+ ).toBe(1);+ expect(JSON.parse(cli.stdout.text()).receipts[0].results[0]).toMatchObject({+ outcome: "error",+ error: { code: "version_conflict" },+ });+});++test("local receipts contain no credential and pending bodies match transmitted bytes", async () => {+ const f = await fixture();+ f.state.throttle = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("Slow down");+ const directory = join(f.root, "state", "external-finding-publications");+ const name = (await readdir(directory)).find((name) =>+ name.endsWith(".pending.json"),+ )!;+ const saved = await readFile(join(directory, name), "utf8");+ expect(saved).not.toContain("synthetic-token");+ expect(+ JSON.stringify(+ (JSON.parse(saved) as { requests: FindingImportRequest[] }).requests[0],+ ),+ ).toBe(f.posts[0]!);+});++test("a restarted large publication resumes after the ten-request rate window", async () => {+ const f = await fixture(+ Array.from({ length: 1001 }, (_, i) => normalized(`bulk-${i}`)),+ );+ const runner = join(f.root, "run-batched-cli.ts");+ const cliUrl = pathToFileURL(join(import.meta.dir, "../src/cli.ts")).href;+ const fixturesUrl = pathToFileURL(+ join(import.meta.dir, "cli-fixtures.ts"),+ ).href;+ await writeFile(+ runner,+ `import { main } from ${JSON.stringify(cliUrl)};\nimport { dependencies } from ${JSON.stringify(fixturesUrl)};\nprocess.exitCode = await main(process.argv.slice(2), process.stdout, process.stderr, { ...dependencies({ environment: process.env }), cloudFetch: (url, init) => fetch('http://127.0.0.1:${f.port}' + new URL(url).pathname + new URL(url).search, init) });\n`,+ );+ async function run() {+ const child = Bun.spawn(+ [Bun.which("bun")!, runner, ...f.command, "--yes"],+ {+ env: f.environment,+ stdout: "pipe",+ stderr: "pipe",+ },+ );+ const [code, stdout, stderr] = await Promise.all([+ child.exited,+ new Response(child.stdout).text(),+ new Response(child.stderr).text(),+ ]);+ return { code, stdout, stderr };+ }+ f.state.postBudget = 10;+ const first = await run();+ expect(first.code).toBe(2);+ expect(first.stderr).toContain("HTTP 429");+ expect(f.reports.size).toBe(1000);+ expect(f.posts).toHaveLength(11);+ const rejectedBody = f.posts[10];+ f.state.postBudget = 10;+ const second = await run();+ expect(second.code).toBe(0);+ expect(JSON.parse(second.stdout).counts.created).toBe(1001);+ expect(f.posts).toHaveLength(12);+ expect(f.posts[11]).toBe(rejectedBody);+ expect(f.reports.size).toBe(1001);+ expect(f.receipts.size).toBe(11);+});++test("a failed checkpoint leaves the original pending request recoverable", async () => {+ const f = await fixture();+ const rename = fs.rename;+ const checkpoint = spyOn(fs, "rename").mockImplementation(+ async (source, destination) => {+ if (String(destination).endsWith(".pending.json") && f.posts.length > 0)+ throw new Error("Checkpoint interrupted");+ return rename(source, destination);+ },+ );+ try {+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("Checkpoint interrupted");+ } finally {+ checkpoint.mockRestore();+ }+ const directory = join(f.root, "state", "external-finding-publications");+ const name = (await readdir(directory)).find((name) =>+ name.endsWith(".pending.json"),+ )!;+ const saved = JSON.parse(await readFile(join(directory, name), "utf8"));+ expect(saved.receipts).toBeUndefined();+ expect(JSON.stringify(saved.requests[0])).toBe(f.posts[0]!);+ await writeFile(join(directory, `${name}.orphan.tmp`), "{");+ expect(+ (+ await (+ await prepareExternalPublication(f.file, options, f.deps)+ ).publish()+ ).counts.created,+ ).toBe(1);+ expect(f.posts).toHaveLength(2);+ expect(f.posts[1]).toBe(f.posts[0]);+ expect(f.receipts.size).toBe(1);+});++test.each(["pending", "result"])(+ "a failed %s file installation cleans up temporary files and can be retried",+ async (stage) => {+ const f = await fixture();+ const rename = fs.rename;+ const installation = spyOn(fs, "rename").mockImplementation(+ async (source, destination) => {+ if (String(destination).endsWith(`.${stage}.json`))+ throw new Error("File installation interrupted");+ return rename(source, destination);+ },+ );+ try {+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("File installation interrupted");+ } finally {+ installation.mockRestore();+ }+ const directory = join(f.root, "state", "external-finding-publications");+ const files = await readdir(directory);+ expect(files.filter((name) => name.endsWith(".tmp"))).toEqual([]);+ expect(files.some((name) => name.endsWith(".pending.json"))).toBe(+ stage === "result",+ );+ expect(f.posts).toHaveLength(stage === "result" ? 1 : 0);+ expect(+ (+ await (+ await prepareExternalPublication(f.file, options, f.deps)+ ).publish()+ ).counts.created,+ ).toBe(1);+ expect(f.posts).toHaveLength(1);+ },+);++test.each(["request", "counts", "length", "schema"])(+ "cached receipts retain publication validation (%s)",+ async (invalid) => {+ const f = await fixture();+ f.state.brokenReadback = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("resume the saved request");+ const directory = join(f.root, "state", "external-finding-publications");+ const name = (await readdir(directory)).find((name) =>+ name.endsWith(".pending.json"),+ )!;+ const pending = join(directory, name);+ const saved = JSON.parse(await readFile(pending, "utf8"));+ if (invalid === "request")+ saved.receipts[0].id = "00000000-0000-4000-8000-000000000000";+ if (invalid === "counts") saved.receipts[0].counts.error = 1;+ if (invalid === "length") saved.receipts.push(saved.receipts[0]);+ if (invalid === "schema") saved.receipts[0].source.provider = "unsupported";+ await writeFile(pending, JSON.stringify(saved));+ f.state.brokenReadback = false;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow();+ expect(f.posts).toHaveLength(1);+ expect(+ (await readdir(directory)).filter((name) => name.endsWith(".tmp")),+ ).toEqual([]);+ },+);++test.each([1, 101])(+ "a prepared retry keeps its receipts after another resumer completes (%i items)",+ async (count) => {+ const f = await fixture(+ Array.from({ length: count }, (_, index) => normalized(`item-${index}`)),+ );+ f.state.postBudget = 1;+ f.state.brokenReadback = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("resume the saved request");+ f.state.brokenReadback = false;+ const first = await prepareExternalPublication(f.file, options, f.deps);+ const second = await prepareExternalPublication(f.file, options, f.deps);+ f.state.postBudget = Infinity;+ expect((await first.publish()).counts.created).toBe(count);+ const completedPosts = f.posts.length;+ f.state.postBudget = count === 1 ? 0 : 1;+ expect((await second.publish()).counts.created).toBe(count);+ expect(f.posts.slice(completedPosts)).toEqual(+ count === 1 ? [] : [JSON.stringify(second.preview.requests[1])],+ );+ const fresh = await prepareExternalPublication(f.file, options, f.deps);+ expect(fresh.preview.resumed).toBe(false);+ expect(fresh.preview.requests[0]!.request_id).not.toBe(+ first.preview.requests[0]!.request_id,+ );+ f.state.postBudget = Infinity;+ expect((await fresh.publish()).counts.unchanged).toBe(count);+ },+);++test.each([+ ["initial", "write"],+ ["initial", "sync"],+ ["result", "write"],+ ["result", "sync"],+ ["result", "rename"],+])(+ "failed %s staging cleans temporary data and remains retryable (%s)",+ async (stage, fault) => {+ const f = await fixture();+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ const originalOpen = fs.open;+ const originalRename = fs.rename;+ let temporaryOpens = 0;+ let injected = false;+ const openSpy = spyOn(fs, "open").mockImplementation(async (...args) => {+ const handle = await originalOpen(...args);+ // A fresh publication stages the pending body, its checkpoint, then its result.+ if (+ String(args[0]).endsWith(".tmp") &&+ ++temporaryOpens === (stage === "initial" ? 1 : 3)+ ) {+ if (fault === "write") {+ const originalWrite = handle.writeFile.bind(handle);+ handle.writeFile = async (data) => {+ const serialized = String(data);+ await originalWrite(+ serialized.slice(0, Math.ceil(serialized.length / 2)),+ );+ injected = true;+ throw new Error("Synthetic disk write failed");+ };+ } else if (fault === "sync") {+ handle.sync = async () => {+ injected = true;+ throw new Error("Synthetic file sync failed");+ };+ }+ }+ return handle;+ });+ const renameSpy = spyOn(fs, "rename").mockImplementation(+ async (from, to) => {+ if (fault === "rename" && String(to).endsWith(".result.json")) {+ injected = true;+ throw new Error("Synthetic result rename failed");+ }+ return originalRename(from, to);+ },+ );+ try {+ await expect(prepared.publish()).rejects.toThrow("Synthetic");+ } finally {+ openSpy.mockRestore();+ renameSpy.mockRestore();+ }+ expect(injected).toBe(true);+ const directory = join(f.root, "state", "external-finding-publications");+ const files = await readdir(directory);+ expect(files.filter((name) => name.endsWith(".tmp"))).toEqual([]);+ expect(files.some((name) => name.endsWith(".pending.json"))).toBe(+ stage === "result",+ );+ expect(f.posts).toHaveLength(stage === "initial" ? 0 : 1);+ const retry = await prepareExternalPublication(f.file, options, f.deps);+ expect(retry.preview.resumed).toBe(stage === "result");+ expect((await retry.publish()).counts.created).toBe(1);+ expect(f.posts).toHaveLength(1);+ expect(f.receipts.size).toBe(1);+ expect(+ (await readdir(directory)).some((name) => name.endsWith(".tmp")),+ ).toBe(false);+ },+);++test.each(["JSON", "JSONL"])(+ "malformed %s input keeps Node parser diagnostics terminal-safe",+ async (format) => {+ const f = await fixture();+ await writeFile(+ f.file,+ `${format === "JSONL" ? "{}\n" : ""}\u001b[2Jmalformed`,+ );+ // Bundle beneath the SDK so the real Node process resolves installed packages.+ const bundle = await mkdtemp(+ join(import.meta.dir, "..", ".import-parser-"),+ );+ cleanups.push(() => rm(bundle, { recursive: true, force: true }));+ const runner = join(bundle, "parse-input.mts");+ await writeFile(+ runner,+ `+ export { main } from "../src/cli.js";+ export { dependencies } from "../tests-ts/cli-fixtures.js";+ `,+ );+ const built = await Bun.build({+ entrypoints: [runner],+ outdir: bundle,+ target: "node",+ format: "esm",+ packages: "external",+ });+ expect(built.success).toBe(true);+ const invocation = join(bundle, "invoke.mjs");+ await writeFile(+ invocation,+ `+ import { main, dependencies } from ${JSON.stringify(pathToFileURL(built.outputs[0]!.path).href)};+ process.exitCode = await main(process.argv.slice(2), process.stdout, process.stderr, {+ ...dependencies({ environment: process.env }),+ cloudFetch: async () => { throw new Error("Unexpected Cloud request"); },+ });+ `,+ );+ const child = Bun.spawn(+ [Bun.which("node")!, invocation, ...f.command, "--dry-run"],+ {+ env: f.environment,+ stdout: "pipe",+ stderr: "pipe",+ },+ );+ const [code, stdout, stderr] = await Promise.all([+ child.exited,+ new Response(child.stdout).text(),+ new Response(child.stderr).text(),+ ]);+ expect(code).toBe(2);+ expect(JSON.parse(stdout)).toMatchObject({+ status: "failed",+ error: expect.stringContaining("malformed"),+ });+ expect(stdout).not.toContain("\u001b");+ expect(stderr).toContain(+ "Could not read vendor findings as UTF-8 JSON or JSONL:",+ );+ expect(stderr).toContain("malformed");+ expect(stderr).not.toContain("\u001b");+ expect(f.posts).toHaveLength(0);+ expect(await readdir(join(f.root, "state")).catch(() => [])).toEqual([]);+ },+);++test.each([+ {+ kind: "OS package container image",+ artifactType: { group: "OS_PACKAGE", osPackageManager: "RPM" },+ vulnerableAsset: { id: "image-os", imageId: "sha256:os-image" },+ ecosystem: "RPM",+ digest: "sha256:os-image",+ },+ {+ kind: "code library container image",+ artifactType: { group: "CODE_LIBRARY", codeLibraryLanguage: "PYTHON" },+ vulnerableAsset: { id: "image-library", imageId: "sha256:library-image" },+ ecosystem: "PYTHON",+ digest: "sha256:library-image",+ },+ {+ kind: "running container",+ artifactType: { group: "CODE_LIBRARY", codeLibraryLanguage: "JAVA" },+ vulnerableAsset: {+ id: "container-library",+ ImageExternalId: "sha256:running-image",+ },+ ecosystem: "JAVA",+ digest: "sha256:running-image",+ },+])(+ "Wiz GraphQL nodes retain $kind metadata",+ async ({ artifactType, vulnerableAsset, ecosystem, digest }) => {+ const record = {+ id: "synthetic-occurrence",+ name: "CVE-2099-0002",+ detailedName: "example-lib",+ version: "1.0.0",+ vendorSeverity: "HIGH",+ artifactType,+ vulnerableAsset,+ };+ const f = await fixture({+ data: {+ vulnerabilityFindings: {+ nodes: [record],+ pageInfo: { hasNextPage: false },+ },+ },+ });+ const parsed = await readVendorFindings(f.file);+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]).toMatchObject({+ source_finding_id: record.id,+ evidence: {+ packages: [+ { name: "example-lib", ecosystem, installed_version: "1.0.0" },+ ],+ image_digests: [digest],+ source_data: record,+ },+ });+ },+);++test.each([false, true])(+ "receipt client IDs correlate reordered results (cached: %p)",+ async (cached) => {+ const f = await fixture([+ normalized("vendor-first", "high"),+ normalized("vendor-second", "low"),+ ]);+ const deps = {+ ...f.deps,+ fetch: async (url: string, init: RequestInit) => {+ const response = await f.deps.fetch(url, init);+ if (init.method !== "POST" || !response.ok) return response;+ const receipt = (await response.json()) as FindingImportReceipt;+ receipt.results.reverse();+ return new Response(JSON.stringify(receipt), {+ headers: { "Content-Type": "application/json" },+ });+ },+ };+ let prepared = await prepareExternalPublication(f.file, options, deps);+ if (cached) {+ f.state.brokenReadback = true;+ await expect(prepared.publish()).rejects.toThrow("Readback unavailable");+ f.state.brokenReadback = false;+ f.state.postBudget = 0;+ prepared = await prepareExternalPublication(f.file, options, deps);+ expect(prepared.preview.resumed).toBe(true);+ }+ const result = await prepared.publish();+ expect(result.counts.created).toBe(2);+ expect(result.receipts[0]!.results.map((item) => item.client_id)).toEqual([+ "item-2",+ "item-1",+ ]);+ expect(f.posts).toHaveLength(1);+ expect(f.receipts.size).toBe(1);+ },+);++test.each(["duplicate", "missing", "unexpected"])(+ "receipt client IDs reject %s results before checkpointing",+ async (invalid) => {+ const f = await fixture([+ normalized("vendor-first"),+ normalized("vendor-second"),+ ]);+ const deps = {+ ...f.deps,+ fetch: async (url: string, init: RequestInit) => {+ const response = await f.deps.fetch(url, init);+ if (init.method !== "POST" || !response.ok) return response;+ const receipt = (await response.json()) as FindingImportReceipt;+ if (invalid === "duplicate")+ receipt.results[1]!.client_id = receipt.results[0]!.client_id;+ if (invalid === "missing") receipt.results.pop();+ if (invalid === "unexpected")+ receipt.results[0]!.client_id = "unexpected-client";+ return new Response(JSON.stringify(receipt), {+ headers: { "Content-Type": "application/json" },+ });+ },+ };+ await expect(+ (await prepareExternalPublication(f.file, options, deps)).publish(),+ ).rejects.toThrow("Cloud returned a receipt for a different publication");+ const directory = join(f.root, "state", "external-finding-publications");+ const pending = (await readdir(directory)).find((name) =>+ name.endsWith(".pending.json"),+ )!;+ expect(+ JSON.parse(await readFile(join(directory, pending), "utf8")).receipts ??+ [],+ ).toEqual([]);+ expect(f.posts).toHaveLength(1);+ },+);++test.each(["replacement-environment", null])(+ "saved publication preserves its environment when discovery changes to %p",+ async (environmentId) => {+ const f = await fixture();+ f.state.loseResponse = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("resume the saved request");+ const original = f.posts[0]!;+ f.state.environmentId = environmentId;+ const retry = await prepareExternalPublication(f.file, options, f.deps);+ expect(retry.preview.resumed).toBe(true);+ expect(retry.preview.requests[0]!.repository.environment_id).toBe(+ "environment-example",+ );+ expect((await retry.publish()).counts.created).toBe(1);+ expect(f.posts.at(-1)).toBe(original);+ },+);++test("mixed environments preserve input order and are shown before confirmation", async () => {+ const f = await fixture([normalized("existing-a"), normalized("existing-c")]);+ await (await prepareExternalPublication(f.file, options, f.deps)).publish();+ const originalIds = ["existing-a", "existing-c"].map(+ (id) => f.reports.get(id)!.canonical_finding_id,+ );+ f.state.environmentId = "replacement-environment";+ await writeFile(+ f.file,+ JSON.stringify([+ normalized("existing-a", "critical"),+ normalized("new-b"),+ normalized("existing-c", "critical"),+ ]),+ );+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ expect(+ prepared.preview.requests.map(+ (request) => request.repository.environment_id,+ ),+ ).toEqual([+ "environment-example",+ "replacement-environment",+ "environment-example",+ ]);+ expect(+ prepared.preview.requests.flatMap((request) =>+ request.items.map((item) => [+ item.source_finding_id,+ item.expected_version,+ ]),+ ),+ ).toEqual([+ ["existing-a", 1],+ ["new-b", 0],+ ["existing-c", 1],+ ]);+ f.state.throttle = true;+ await expect(prepared.publish()).rejects.toThrow("Retry-After");+ f.state.throttle = false;+ f.state.environmentId = "changed-default";+ const cli = createCliTest(main);+ expect(+ await cli.runCli(f.command, {+ ...f.cliDeps,+ externalPublicationPrompt: {+ isInteractive: () => true,+ confirm: async () => {+ expect(cli.stderr.text()).toContain(+ "Environment: environment-example, replacement-environment",+ );+ expect(cli.stderr.text()).not.toContain("changed-default");+ expect(f.posts).toHaveLength(2);+ return true;+ },+ },+ }),+ ).toBe(0);+ expect(+ JSON.parse(cli.stdout.text()).receipts.map(+ (receipt: FindingImportReceipt) => receipt.id,+ ),+ ).toEqual(prepared.preview.requests.map((request) => request.request_id));+ expect(f.posts[2]).toBe(f.posts[1]);+ expect(JSON.parse(cli.stdout.text()).counts).toEqual({+ created: 1,+ updated: 2,+ unchanged: 0,+ error: 0,+ });+ expect(+ ["existing-a", "new-b", "existing-c"].map(+ (id) => f.reports.get(id)!.environment_id,+ ),+ ).toEqual([+ "environment-example",+ "replacement-environment",+ "environment-example",+ ]);+ expect(+ ["existing-a", "existing-c"].map(+ (id) => f.reports.get(id)!.canonical_finding_id,+ ),+ ).toEqual(originalIds);+});++test("existing source updates do not need a newly discovered default environment", async () => {+ const f = await fixture();+ await (await prepareExternalPublication(f.file, options, f.deps)).publish();+ f.state.environmentId = null;+ await writeFile(f.file, JSON.stringify([normalized("vendor-1", "critical")]));+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ expect(prepared.preview.requests[0]!.repository.environment_id).toBe(+ "environment-example",+ );+ expect((await prepared.publish()).counts.updated).toBe(1);+ const posts = f.posts.length;+ await writeFile(f.file, JSON.stringify([normalized("new-vendor")]));+ await expect(+ prepareExternalPublication(f.file, options, f.deps),+ ).rejects.toThrow("Configure an authorized Cloud environment");+ expect(f.posts).toHaveLength(posts);+});++test.each([+ ["id", `aif_${"0".repeat(64)}`],+ ["environment_id", "unexpected-environment"],+])("source readback must preserve acknowledged %s", async (field, value) => {+ const f = await fixture();+ const prepared = await prepareExternalPublication(f.file, options, {+ ...f.deps,+ fetch: async (url, init) => {+ const response = await f.deps.fetch(url, init);+ if (new URL(url).pathname.includes("/source_reports/")) {+ return Response.json({+ ...(await response.json()),+ [field]: value,+ });+ }+ return response;+ },+ });+ await expect(prepared.publish()).rejects.toThrow(+ "Cloud readback did not match the saved finding identity",+ );+ expect(f.posts).toHaveLength(1);+ const retry = await prepareExternalPublication(f.file, options, f.deps);+ expect((await retry.publish()).counts.created).toBe(1);+ expect(f.posts).toHaveLength(1);+});++test("malformed bracketed URLs exclude only their own finding before upload", async () => {+ const invalid = normalized("invalid-url");+ const f = await fixture([+ normalized("valid-url"),+ {+ ...invalid,+ evidence: { ...invalid.evidence, url: "https://[127.0.0.1]/finding" },+ },+ ]);+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ expect(+ prepared.preview.findings.map((finding) => finding.source_finding_id),+ ).toEqual(["valid-url"]);+ expect(prepared.preview.excluded).toHaveLength(1);+ expect(prepared.preview.excluded[0]!.reason).toContain("HTTP(S)");+ expect((await prepared.publish()).counts.created).toBe(1);+ expect(f.reports.has("invalid-url")).toBe(false);+});++test.each([false, true])(+ "publication waits through the server budget while retaining cancellation: %p",+ async (cancel) => {+ const f = await fixture();+ const arrived = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const controller = new AbortController();+ const prepared = await prepareExternalPublication(f.file, options, {+ ...f.deps,+ signal: controller.signal,+ fetch: async (url, init) => {+ if (init.method === "POST") {+ arrived.resolve();+ await release.promise;+ }+ return f.deps.fetch(url, init);+ },+ });+ const deadlines: { milliseconds: number; controller: AbortController }[] =+ [];+ const timeout = spyOn(AbortSignal, "timeout").mockImplementation(+ (milliseconds) => {+ const controller = new AbortController();+ deadlines.push({ milliseconds, controller });+ return controller.signal;+ },+ );+ const completion = prepared.publish();+ try {+ await Promise.race([+ arrived.promise,+ completion.then(() => {+ throw new Error(+ "Publication completed before the POST was released.",+ );+ }),+ ]);+ // Advance a controlled clock through the server's publication budget.+ for (const deadline of deadlines) {+ if (deadline.milliseconds <= 45_000)+ deadline.controller.abort(+ new DOMException("Publication deadline elapsed", "TimeoutError"),+ );+ }+ if (cancel) controller.abort(new Error("Synthetic cancellation"));+ release.resolve();+ if (cancel) {+ await expect(completion).rejects.toThrow("Synthetic cancellation");+ expect(f.posts).toHaveLength(0);+ const retry = await prepareExternalPublication(f.file, options, f.deps);+ expect(retry.preview.resumed).toBe(true);+ expect(retry.preview.requests[0]!.request_id).toBe(+ prepared.preview.requests[0]!.request_id,+ );+ expect((await retry.publish()).counts.created).toBe(1);+ expect(f.posts[0]).toBe(JSON.stringify(prepared.preview.requests[0]));+ } else {+ expect((await completion).counts.created).toBe(1);+ expect(f.posts).toHaveLength(1);+ }+ } finally {+ release.resolve();+ await completion.catch(() => undefined);+ timeout.mockRestore();+ }+ },+);++test("numeric evidence size excludes an oversized item and preserves a valid mixed-format sibling", async () => {+ const oversized = {+ ...normalized("oversized-numbers"),+ evidence: {+ ...normalized().evidence,+ source_data: { metrics: Array(48_000).fill(1e-7) },+ },+ };+ const accepted = {+ ...normalized("accepted-numbers"),+ evidence: {+ ...normalized().evidence,+ source_data: {+ metrics: [...Array(10_000).fill(1e-7), ...Array(30_000).fill(1e-6)],+ },+ },+ };+ expect(Buffer.byteLength(JSON.stringify(accepted.evidence))).toBeGreaterThan(+ 256 * 1024,+ );+ const f = await fixture([oversized, accepted]);+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ expect(+ prepared.preview.findings.map((finding) => finding.source_finding_id),+ ).toEqual(["accepted-numbers"]);+ expect(prepared.preview.excluded).toHaveLength(1);+ expect(prepared.preview.excluded[0]!.reason).toContain("256 KiB");+ expect((await prepared.publish()).counts.created).toBe(1);+ expect(f.posts).toHaveLength(1);+ expect(JSON.parse(f.posts[0]!).items[0].evidence.source_data).toEqual(+ accepted.evidence.source_data,+ );+ expect(f.reports.has("oversized-numbers")).toBe(false);+});++test.each([0xff, 0xfe])(+ "invalid UTF-8 byte %p cannot change a source identity",+ async (byte) => {+ const f = await fixture();+ await writeFile(+ f.file,+ Buffer.concat([+ Buffer.from('{"source_finding_id":"vendor-'),+ Buffer.from([byte]),+ Buffer.from('","evidence":{"title":"Example","severity":"high"}}'),+ ]),+ );+ await expect(+ prepareExternalPublication(f.file, options, f.deps),+ ).rejects.toThrow("UTF-8");+ expect(f.posts).toHaveLength(0);+ await writeFile(+ f.file,+ `\uFEFF${JSON.stringify(normalized("vendor-\uFFFD"))}`,+ );+ expect(+ (await readVendorFindings(f.file)).findings[0]!.source_finding_id,+ ).toBe("vendor-\uFFFD");+ },+);++test("unsafe evidence integers are rejected while exact strings and safe integers survive", async () => {+ const f = await fixture();+ await writeFile(+ f.file,+ `[+ {"source_finding_id":"unsafe-a","evidence":{"title":"Example","severity":"high","source_data":{"counter":9007199254740992}}},+ {"source_finding_id":"unsafe-b","evidence":{"title":"Example","severity":"high","source_data":{"counter":9007199254740993}}},+ {"source_finding_id":"unsafe-negative","evidence":{"title":"Example","severity":"high","source_data":{"counter":-9007199254740993}}},+ {"source_finding_id":"exact","evidence":{"title":"Example","severity":"high","source_data":{"counter":"9007199254740993","safe":9007199254740991,"fraction":0.125}}}+ ]`,+ );+ const parsed = await readVendorFindings(f.file);+ expect(parsed.excluded.map((item) => item.source_finding_id)).toEqual([+ "unsafe-a",+ "unsafe-b",+ "unsafe-negative",+ ]);+ expect(+ parsed.excluded.every((item) => item.reason.includes("safe integer")),+ ).toBe(true);+ expect(parsed.findings[0]!.evidence.source_data).toEqual({+ counter: "9007199254740993",+ safe: Number.MAX_SAFE_INTEGER,+ fraction: 0.125,+ });+});++test("mixed valid and rejected input reports partial completion with exit code 1", async () => {+ const f = await fixture([+ normalized("invalid", "unsupported"),+ normalized("valid"),+ ]);+ const cli = createCliTest(main);+ expect(await cli.runCli([...f.command, "--yes"], f.cliDeps)).toBe(1);+ expect(JSON.parse(cli.stdout.text())).toMatchObject({+ status: "partial",+ read: 2,+ ready: 1,+ counts: { created: 1, error: 0 },+ unacknowledged: 0,+ verified: 1,+ excluded: [{ source_finding_id: "invalid", position: 1 }],+ });+});++test("server item failures identify the vendor record after local exclusions", async () => {+ const f = await fixture([+ normalized("invalid", "unsupported"),+ normalized("rejected-vendor"),+ ]);+ f.state.finalError = true;+ const cli = createCliTest(main);+ expect(await cli.runCli([...f.command, "--yes"], f.cliDeps)).toBe(1);+ expect(JSON.parse(cli.stdout.text())).toMatchObject({+ status: "partial",+ verified: 0,+ unacknowledged: 0,+ failures: [+ {+ source_finding_id: "rejected-vendor",+ code: "version_conflict",+ message: "Reload current evidence",+ },+ ],+ });+});++test("interrupted CLI output preserves acknowledged batches and resumes only unfinished uploads", async () => {+ const f = await fixture(+ Array.from({ length: 101 }, (_, i) => normalized(`vendor-${i}`)),+ );+ f.state.postBudget = 1;+ const first = createCliTest(main);+ expect(await first.runCli([...f.command, "--yes"], f.cliDeps)).toBe(2);+ const partial = JSON.parse(first.stdout.text());+ expect(partial).toMatchObject({+ status: "interrupted",+ ready: 101,+ counts: { created: 100 },+ unacknowledged: 1,+ verified: 0,+ });+ expect(partial.receipts).toHaveLength(1);+ expect(partial.savedSubmission).toEndWith(".pending.json");+ expect(partial.error).toContain("Repeat the same command");+ expect(f.reports.size).toBe(100);+ f.state.postBudget = Infinity;+ const retry = createCliTest(main);+ expect(await retry.runCli([...f.command, "--yes"], f.cliDeps)).toBe(0);+ expect(JSON.parse(retry.stdout.text())).toMatchObject({+ status: "complete",+ counts: { created: 101 },+ unacknowledged: 0,+ verified: 101,+ });+ expect(f.posts).toHaveLength(3);+ expect(f.posts[2]).toBe(f.posts[1]);+});++test("readback interruption distinguishes acknowledged findings from verified findings", async () => {+ const f = await fixture();+ f.state.brokenReadback = true;+ const prepared = await prepareExternalPublication(f.file, options, f.deps);+ try {+ await prepared.publish();+ throw new Error("Expected readback interruption");+ } catch (error) {+ expect(error).toBeInstanceOf(ExternalPublicationError);+ expect((error as ExternalPublicationError).result).toMatchObject({+ status: "interrupted",+ counts: { created: 1 },+ unacknowledged: 0,+ verified: 0,+ });+ }+});++test("repository selection is sent on every discovery page", async () => {+ const f = await fixture();+ const repository = `${f.destination().url}.git`;+ const queries: URLSearchParams[] = [];+ const prepared = await prepareExternalPublication(+ f.file,+ { ...options, repository },+ {+ ...f.deps,+ fetch: async (input, init) => {+ const url = new URL(input);+ if (!url.pathname.endsWith("/repositories"))+ return f.deps.fetch(input, init);+ queries.push(url.searchParams);+ const first = queries.length === 1;+ return Response.json({+ object: "page",+ data: first ? [] : [f.destination()],+ has_more: first,+ next: first ? "next-page" : null,+ });+ },+ },+ );+ expect(prepared.preview.destination.id).toBe(options.repository);+ expect(queries.map((query) => query.get("repository"))).toEqual([+ repository,+ repository,+ ]);+ expect(queries.map((query) => query.get("page"))).toEqual([+ null,+ "next-page",+ ]);+ expect(f.posts).toHaveLength(0);+});++test("repository URLs and IDs share the same resumable destination", async () => {+ const f = await fixture();+ f.state.loseResponse = true;+ const first = await prepareExternalPublication(+ f.file,+ { ...options, repository: `${f.destination().url}.git` },+ f.deps,+ );+ expect(first.preview.destination.id).toBe(options.repository);+ await expect(first.publish()).rejects.toThrow("resume the saved request");+ const retry = await prepareExternalPublication(f.file, options, f.deps);+ expect(retry.preview.resumed).toBe(true);+ expect((await retry.publish()).status).toBe("complete");+ expect(f.posts[1]).toBe(f.posts[0]);+});++test("Cloud deployment routing covers every request and isolates saved retries", async () => {+ const f = await fixture();+ const cloudBase = "https://cloud.example.test/pilot/backend-api/aardvark";+ const requested: string[] = [];+ const deps = {+ ...f.deps,+ environment: {+ ...f.deps.environment,+ CODEX_SECURITY_CLOUD_BASE_URL: `${cloudBase}///`,+ },+ fetch: async (url: string, init: RequestInit) => {+ requested.push(url);+ expect(url.startsWith(`${cloudBase}/external/`)).toBe(true);+ return f.deps.fetch(url, init);+ },+ };+ f.state.brokenReadback = true;+ const prepared = await prepareExternalPublication(f.file, options, deps);+ expect(prepared.preview.cloudApiUrl).toBe(`${cloudBase}/external`);+ await expect(prepared.publish()).rejects.toThrow("resume the saved request");+ const otherDeployment = await prepareExternalPublication(f.file, options, {+ ...f.deps,+ environment: {+ ...f.deps.environment,+ CODEX_SECURITY_CLOUD_BASE_URL:+ "https://other-cloud.example.test/backend-api/aardvark",+ },+ });+ expect(otherDeployment.preview.resumed).toBe(false);+ const retry = await prepareExternalPublication(f.file, options, deps);+ expect(retry.preview.resumed).toBe(true);+ expect(retry.preview.requests).toEqual(prepared.preview.requests);+ f.state.brokenReadback = false;+ const result = await retry.publish();+ expect(result.cloudApiUrl).toBe(`${cloudBase}/external`);+ expect(result.cloudUrl).toBeUndefined();+ expect(result.verified).toBe(1);+ expect(f.posts).toHaveLength(1);+ expect(requested.some((url) => url.includes("/repositories?"))).toBe(true);+ expect(requested.some((url) => url.includes("/source_reports?"))).toBe(true);+ expect(requested.some((url) => url.endsWith("/finding_imports"))).toBe(true);+ expect(requested.some((url) => url.includes("/source_reports/"))).toBe(true);+});++test.each(["localhost", "127.0.0.1", "127.0.0.2", "[::1]"])(+ "loopback Cloud APIs support local HTTP publication: %s",+ async (host) => {+ const f = await fixture();+ const cloudBase = `http://${host}:4200/backend-api/aardvark`;+ const prepared = await prepareExternalPublication(f.file, options, {+ ...f.deps,+ environment: {+ ...f.environment,+ CODEX_SECURITY_CLOUD_BASE_URL: cloudBase,+ },+ fetch: (url, init) => {+ expect(url.startsWith(`${cloudBase}/external/`)).toBe(true);+ return f.deps.fetch(url, init);+ },+ });+ expect((await prepared.publish()).status).toBe("complete");+ expect(f.posts).toHaveLength(1);+ },+);++test("a separate Cloud app URL follows the resolved repository without changing API routing", async () => {+ const f = await fixture();+ const requested: string[] = [];+ const environment = {+ ...f.environment,+ CODEX_SECURITY_CLOUD_BASE_URL:+ "https://api.example.test/backend-api/aardvark",+ CODEX_SECURITY_CLOUD_WEB_URL:+ "http://localhost:4200/security?preview=true#/old",+ };+ const prepared = await prepareExternalPublication(+ f.file,+ { ...options, repository: f.destination().url },+ {+ ...f.deps,+ environment,+ fetch: (url, init) => {+ requested.push(url);+ return f.deps.fetch(url, init);+ },+ },+ );+ const link = `http://localhost:4200/security?preview=true#/repositories/${options.repository}/findings`;+ expect(prepared.preview.cloudUrl).toBe(link);+ expect((await prepared.publish()).cloudUrl).toBe(link);+ expect(+ requested.every((url) =>+ url.startsWith(environment.CODEX_SECURITY_CLOUD_BASE_URL),+ ),+ ).toBe(true);++ const cli = createCliTest(main);+ expect(+ await cli.runCli(+ f.command+ .filter((value) => !["--format", "json"].includes(value))+ .concat("--yes"),+ { ...f.cliDeps, environment },+ ),+ ).toBe(0);+ expect(cli.stdout.text()).toContain(`View Cloud repository: ${link}`);+});++test.each([+ "",+ "/relative",+ "file:///tmp/cloud",+ "https://user:[email protected]",+])(+ "invalid Cloud app URL fails before authentication or network: %s",+ async (url) => {+ const f = await fixture();+ let calls = 0;+ await expect(+ prepareExternalPublication(f.file, options, {+ ...f.deps,+ environment: { ...f.environment, CODEX_SECURITY_CLOUD_WEB_URL: url },+ credentials: async () => {+ calls++;+ throw new Error("Unexpected auth");+ },+ fetch: async () => {+ calls++;+ throw new Error("Unexpected network");+ },+ }),+ ).rejects.toThrow("CODEX_SECURITY_CLOUD_WEB_URL");+ expect(calls).toBe(0);+ },+);++test.each([+ "",+ " ",+ "/relative",+ "file:///tmp/cloud",+ "https://user:[email protected]",+ "https://cloud.example.test?deployment=pilot",+ "https://cloud.example.test#pilot",+ "http://cloud.example.test/backend-api/aardvark",+ "http://127.example.test/backend-api/aardvark",+ "http://192.0.2.1/backend-api/aardvark",+])(+ "invalid Cloud base URL fails before authentication or network: %s",+ async (baseUrl) => {+ const f = await fixture();+ let calls = 0;+ await expect(+ prepareExternalPublication(f.file, options, {+ ...f.deps,+ environment: {+ ...f.deps.environment,+ CODEX_SECURITY_CLOUD_BASE_URL: baseUrl,+ },+ credentials: async () => {+ calls++;+ throw new Error("Unexpected credential read");+ },+ fetch: async () => {+ calls++;+ throw new Error("Unexpected network request");+ },+ }),+ ).rejects.toThrow("CODEX_SECURITY_CLOUD_BASE_URL");+ expect(calls).toBe(0);+ },+);++test("read lookups and verification run concurrently with bounded requests and ordered input", async () => {+ const f = await fixture(+ Array.from({ length: 9 }, (_, i) => normalized(`vendor-${i}`)),+ );+ const phases: ExternalPublicationProgress[] = [];+ let active = 0;+ let maximum = 0;+ const prepared = await prepareExternalPublication(f.file, options, {+ ...f.deps,+ onProgress: (event) => phases.push(event),+ fetch: async (url, init) => {+ if (!url.includes("/source_reports")) return f.deps.fetch(url, init);+ active++;+ maximum = Math.max(maximum, active);+ try {+ await Promise.resolve();+ return await f.deps.fetch(url, init);+ } finally {+ active--;+ }+ },+ });+ expect(+ prepared.preview.requests.flatMap((batch) =>+ batch.items.map((item) => item.source_finding_id),+ ),+ ).toEqual(Array.from({ length: 9 }, (_, i) => `vendor-${i}`));+ expect((await prepared.publish()).status).toBe("complete");+ expect(maximum).toBeGreaterThan(1);+ expect(maximum).toBeLessThanOrEqual(4);+ expect(active).toBe(0);+ for (const phase of ["preparing", "uploading", "verifying"])+ expect(+ phases.filter((event) => event.phase === phase).at(-1),+ ).toMatchObject({ completed: 9, total: 9 });+});++test("progress is optional and stderr progress never corrupts JSON results", async () => {+ const f = await fixture();+ const prepared = await prepareExternalPublication(f.file, options, {+ ...f.deps,+ onProgress: () => {+ throw new Error("Optional observer failed");+ },+ });+ expect((await prepared.publish()).status).toBe("complete");+ const cli = createCliTest(main, { stderr: true });+ expect(await cli.runCli([...f.command, "--yes"], f.cliDeps)).toBe(0);+ expect(JSON.parse(cli.stdout.text())).toMatchObject({+ status: "complete",+ counts: { unchanged: 1 },+ });+ expect(cli.stderr.text()).toContain("Preparing findings");+ expect(cli.stderr.text()).toContain("Verifying source records: 1/1");+});++test("human previews stay compact while JSON previews retain complete evidence", async () => {+ const records = Array.from({ length: 6 }, (_, i) => ({+ ...normalized(`vendor-${i}`),+ evidence: {+ ...normalized().evidence,+ source_data: { detail: `complete-vendor-evidence-${i}` },+ },+ }));+ const f = await fixture(records);+ const human = createCliTest(main);+ expect(+ await human.runCli([...f.command.slice(0, -2), "--dry-run"], f.cliDeps),+ ).toBe(0);+ expect(human.stderr.text()).toContain("Showing 5 of 6 findings");+ expect(human.stderr.text()).not.toContain("complete-vendor-evidence-");+ expect(human.stdout.text()).not.toContain("request_id");+ const json = createCliTest(main);+ expect(await json.runCli([...f.command, "--dry-run"], f.cliDeps)).toBe(0);+ expect(JSON.parse(json.stdout.text()).findings).toHaveLength(6);+ expect(+ JSON.parse(json.stdout.text()).findings[5].evidence.source_data.detail,+ ).toBe("complete-vendor-evidence-5");+ expect(f.posts).toHaveLength(0);+});++test("normalized SDK publication preserves caller evidence and exclusion accounting", async () => {+ const f = await fixture();+ const input = {+ read: 2,+ findings: [normalized()],+ excluded: [+ {+ position: 2,+ source_finding_id: null,+ reason: "Unsupported source record.",+ },+ ],+ };+ const original = structuredClone(input);+ const prepared = await prepareNormalizedExternalPublication(+ input as Parameters<typeof prepareNormalizedExternalPublication>[0],+ options,+ f.deps,+ );+ expect(input).toEqual(original);+ expect(prepared.preview.read).toBe(2);+ const result = await prepared.publish();+ expect(result.status).toBe("partial");+ expect(result.counts.created).toBe(1);+ expect(result.excluded).toEqual(input.excluded);+ expect(result.verified).toBe(1);+});++test("normalized publication omits only new null fields to match canonical Cloud readback", async () => {+ const f = await fixture();+ const evidence = {+ title: "Synthetic advisory without known package range",+ severity: "unknown" as const,+ packages: [+ {+ name: "example-package",+ vulnerable_version_range: null,+ installed_version: null,+ },+ ],+ details: {+ kind: "advisory" as const,+ repository: null,+ advisory: { source: "global" as const },+ },+ };+ const prepared = await prepareNormalizedExternalPublication(+ {+ read: 1,+ findings: [{ source_finding_id: "synthetic-global-advisory", evidence }],+ excluded: [],+ },+ options,+ f.deps,+ );+ const sent = prepared.preview.findings[0]!.evidence;+ expect(sent.packages![0]).not.toHaveProperty("vulnerable_version_range");+ expect(sent.packages![0]!.installed_version).toBeNull();+ expect(sent.details).not.toHaveProperty("repository");+ expect(evidence.details.repository).toBeNull();+ expect((await prepared.publish()).verified).toBe(1);++ await writeFile(+ f.file,+ JSON.stringify([+ {+ source_finding_id: "synthetic-sast",+ evidence: {+ title: "Synthetic SAST evidence",+ severity: "high",+ packages: [+ { name: "example-package", vulnerable_version_range: null },+ ],+ details: {+ kind: "sast",+ repository: { url: "https://github.com/example/project" },+ advisory: null,+ },+ },+ },+ ]),+ );+ const wiz = await prepareExternalPublication(f.file, options, f.deps);+ expect(wiz.preview.findings[0]!.evidence.details).not.toHaveProperty(+ "advisory",+ );+ expect(wiz.preview.findings[0]!.evidence.details!.scanner_origin).toBeNull();+ expect((await wiz.publish()).verified).toBe(1);+});++test("normalized SDK publication detaches raw evidence aliases before validating every finding", async () => {+ const f = await fixture();+ const sharedPackage = { name: "example-package" };+ const input = {+ read: 2,+ findings: [+ {+ source_finding_id: "shared-first",+ evidence: {+ title: "First report",+ severity: "high" as const,+ packages: [sharedPackage],+ source_data: { package: sharedPackage },+ },+ },+ {+ source_finding_id: "shared-second",+ evidence: {+ title: "Second report",+ severity: "high" as const,+ source_data: { earlier_package: sharedPackage },+ },+ },+ ],+ excluded: [],+ };+ const original = JSON.stringify(input);+ const prepared = await prepareNormalizedExternalPublication(+ input,+ options,+ f.deps,+ );+ expect(JSON.stringify(input)).toBe(original);+ expect(prepared.preview.findings[0]!.evidence.source_data).toEqual({+ package: { name: "example-package" },+ });+ expect(prepared.preview.findings[1]!.evidence.source_data).toEqual({+ earlier_package: { name: "example-package" },+ });+ await writeFile(f.file, JSON.stringify(input.findings));+ const fromFile = await prepareExternalPublication(f.file, options, f.deps);+ expect(prepared.preview.findings).toEqual(fromFile.preview.findings);+});++test("normalized SDK publication rejects nonfinite raw evidence without JSON coercion", async () => {+ const f = await fixture();+ const input = {+ read: 1,+ findings: [+ {+ source_finding_id: "nonfinite-raw-evidence",+ evidence: {+ title: "Synthetic evidence",+ severity: "high" as const,+ source_data: { score: Infinity },+ },+ },+ ],+ excluded: [],+ };+ await expect(+ prepareNormalizedExternalPublication(input, options, f.deps),+ ).rejects.toThrow("finite JSON numbers");+ expect(input.findings[0]!.evidence.source_data.score).toBe(Infinity);+ expect(f.posts).toHaveLength(0);+});++test("invalid source namespaces fail before authentication or Cloud requests", async () => {+ const f = await fixture();+ const contacted: string[] = [];+ for (const sourceKey of [" ", "x".repeat(513), "tenant\0namespace"])+ await expect(+ prepareExternalPublication(+ f.file,+ { ...options, sourceKey },+ {+ ...f.deps,+ credentials: async () => {+ contacted.push("credentials");+ throw new Error("Unexpected authentication");+ },+ fetch: async () => {+ contacted.push("fetch");+ throw new Error("Unexpected Cloud request");+ },+ },+ ),+ ).rejects.toThrow("source key must contain");+ expect(contacted).toEqual([]);+});++test("normalized SDK publication accepts Cloud providers without their file reader", async () => {+ const f = await fixture();+ const prepared = await prepareNormalizedExternalPublication(+ {+ read: 1,+ findings: [+ {+ source_finding_id: "synthetic-endor-finding",+ evidence: { title: "Synthetic finding", severity: "unknown" },+ },+ ],+ excluded: [],+ },+ { ...options, provider: "endor" },+ f.deps,+ );+ expect(prepared.preview.source.provider).toBe("endor");+ expect((await prepared.publish()).verified).toBe(1);+ expect(JSON.parse(f.posts[0]!).source.provider).toBe("endor");+});diff --git a/sdk/typescript/tests-ts/fixtures/wiz-details-roundtrip.json b/sdk/typescript/tests-ts/fixtures/wiz-details-roundtrip.jsonnew file mode 100644index 000000000..fd8814a9d--- /dev/null+++ b/sdk/typescript/tests-ts/fixtures/wiz-details-roundtrip.json@@ -0,0 +1,167 @@+[+ {+ "name": "sast-sparse-code-rule",+ "input": {+ "kind": "sast",+ "repository": {+ "url": "https://github.com/example/project"+ },+ "code": {+ "snippet": " "+ },+ "rule": {+ "id": "example-rule"+ }+ },+ "expected": {+ "kind": "sast",+ "repository": {+ "url": "https://github.com/example/project",+ "id": null,+ "name": null+ },+ "source_status": null,+ "scanner_origin": null,+ "scanner_verdict": null,+ "rule": {+ "id": "example-rule",+ "short_id": null,+ "name": null+ },+ "weakness_ids": [],+ "remediation_instructions": null,+ "code": {+ "end_line": null,+ "snippet": " "+ },+ "secret": null,+ "configuration": null,+ "file_url": null+ }+ },+ {+ "name": "secret-empty-models",+ "input": {+ "kind": "secret",+ "repository": {+ "url": "https://github.com/example/project"+ },+ "secret": {},+ "rule": {}+ },+ "expected": {+ "kind": "secret",+ "repository": {+ "url": "https://github.com/example/project",+ "id": null,+ "name": null+ },+ "source_status": null,+ "scanner_origin": null,+ "scanner_verdict": null,+ "rule": {+ "id": null,+ "short_id": null,+ "name": null+ },+ "weakness_ids": [],+ "remediation_instructions": null,+ "code": null,+ "secret": {+ "type": null,+ "confidence": null,+ "validation_status": null,+ "is_encrypted": null,+ "is_managed": null,+ "introduced_commit": null+ },+ "configuration": null,+ "file_url": null+ }+ },+ {+ "name": "iac-empty-comparison",+ "input": {+ "kind": "iac",+ "repository": {+ "url": "https://github.com/example/project"+ },+ "configuration": {+ "expected": "",+ "actual": " "+ },+ "rule": {+ "short_id": "EXAMPLE-1"+ }+ },+ "expected": {+ "kind": "iac",+ "repository": {+ "url": "https://github.com/example/project",+ "id": null,+ "name": null+ },+ "source_status": null,+ "scanner_origin": null,+ "scanner_verdict": null,+ "rule": {+ "id": null,+ "short_id": "EXAMPLE-1",+ "name": null+ },+ "weakness_ids": [],+ "remediation_instructions": null,+ "code": null,+ "secret": null,+ "configuration": {+ "platform": null,+ "cloud_platform": null,+ "expected": "",+ "actual": " "+ },+ "file_url": null+ }+ },+ {+ "name": "iac-empty-models",+ "input": {+ "kind": "iac",+ "repository": {+ "url": "https://github.com/example/project"+ },+ "configuration": {},+ "rule": {},+ "code": {}+ },+ "expected": {+ "kind": "iac",+ "repository": {+ "url": "https://github.com/example/project",+ "id": null,+ "name": null+ },+ "source_status": null,+ "scanner_origin": null,+ "scanner_verdict": null,+ "rule": {+ "id": null,+ "short_id": null,+ "name": null+ },+ "weakness_ids": [],+ "remediation_instructions": null,+ "code": {+ "end_line": null,+ "snippet": null+ },+ "secret": null,+ "configuration": {+ "platform": null,+ "cloud_platform": null,+ "expected": null,+ "actual": null+ },+ "file_url": null+ }+ }+]diff --git a/sdk/typescript/tests-ts/package-tar-listing.test.ts b/sdk/typescript/tests-ts/package-tar-listing.test.tsindex b0cf5ec6b..ac8e73768 100644--- a/sdk/typescript/tests-ts/package-tar-listing.test.ts+++ b/sdk/typescript/tests-ts/package-tar-listing.test.ts@@ -87,6 +87,7 @@ function packageTar({"package/docs/hosted-remediation.md","package/schemas/hosted-scan-v2.fixture.json","package/schemas/project-config.schema.json",+ "package/schemas/external-findings.schema.json","package/LICENSE",...executablePaths,...packageDistFiles,diff --git a/sdk/typescript/tests-ts/scanner-import.test.ts b/sdk/typescript/tests-ts/scanner-import.test.tsnew file mode 100644index 000000000..88c78f1c8--- /dev/null+++ b/sdk/typescript/tests-ts/scanner-import.test.ts@@ -0,0 +1,14 @@+import { expect, test } from "bun:test";+import { relativePath } from "../src/scanner-import.js";++test("scanner repository paths retain colons outside Windows drive prefixes", () => {+ expect(relativePath("schema:prod.json")).toBe("schema:prod.json");+ expect(relativePath("src/schema:prod.ts")).toBe("src/schema:prod.ts");+ for (const path of [+ "C:\\project\\source.ts",+ "C:source.ts",+ "/source.ts",+ "../source.ts",+ ])+ expect(relativePath(path)).toBeNull();+});diff --git a/sdk/typescript/tests-ts/wiz-findings.test.ts b/sdk/typescript/tests-ts/wiz-findings.test.tsnew file mode 100644index 000000000..e35ba7e1d--- /dev/null+++ b/sdk/typescript/tests-ts/wiz-findings.test.ts@@ -0,0 +1,2398 @@+import { hash } from "node:crypto";+import {+ mkdtemp,+ mkdir,+ readFile,+ readdir,+ rename,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Writable } from "node:stream";+import { gzipSync } from "node:zlib";+import { afterEach, expect, test } from "bun:test";+import { main } from "../src/cli.js";+import {+ ExternalPublicationError,+ prepareExternalPublication,+} from "../src/external-findings-publish.js";+import { DEFAULT_CLOUD_BASE_URL } from "../src/cloud-endpoint.js";+import { validateExternalEvidence } from "../src/external-import-contract.js";+import type {+ ExternalFindingEvidence,+ FindingImportRequest,+ SourceReport,+} from "../src/external-import-models.js";+import {+ readVendorFindings,+ readVendorFindingsForPublication,+} from "../src/wiz-findings.js";+import { capture, dependencies } from "./cli-fixtures.js";+import { createCliTest } from "./support/cli-run.js";+import roundtripFixtures from "./fixtures/wiz-details-roundtrip.json" with { type: "json" };++const directories: string[] = [];+afterEach(async () => {+ await Promise.all(+ directories+ .splice(0)+ .map((path) => rm(path, { recursive: true, force: true })),+ );+});+const repository = { id: "wiz-repository", name: "example/project" };+const repositoryUrl = "https://github.com/example/project";+const inventory = {+ nodes: [+ {+ id: "wiz-branch-inventory",+ platform: "GITHUB",+ providerID: "github.com##example/project##feature/parser",+ type: "REPOSITORY_BRANCH",+ repository: { ...repository, url: repositoryUrl },+ },+ ],+ pageInfo: { hasNextPage: false },+};+const sast = {+ id: "occurrence-1",+ name: "Untrusted query construction",+ description: "Synthetic source finding",+ severity: "HIGH",+ status: "OPEN",+ createdAt: "2026-10-01T10:00:00.123Z",+ filePath: "src/query.ts",+ startLine: 10,+ endLine: 12,+ snippet: "query(input)",+ repository,+ repositoryBranch: {+ id: "wiz-branch",+ name: "example/project/feature/parser",+ },+ weaknesses: [{ id: "CWE-89", name: "SQL injection" }],+ origin: "THIRD_PARTY_SCANNER",+ remediationInstructions: "Use a parameterized query.",+ aiAnalysis: { verdict: "FALSE_POSITIVE" },+};+const secret = {+ id: "occurrence-1",+ name: "Example credential metadata",+ severity: "MEDIUM",+ type: "API_KEY",+ confidence: "HIGH",+ validationStatus: "NOT_VALIDATED",+ isEncrypted: false,+ isManaged: true,+ status: "RESOLVED",+ lastUpdatedAt: "2026-10-01T10:00:00.987Z",+ resolvedAt: "2026-10-01T10:00:00.987Z",+ rule: { id: "example-secret-rule", name: "Example API key", type: "API_KEY" },+ resource: {+ id: "wiz-branch",+ type: "REPOSITORY_BRANCH",+ name: "example/project/feature/parser",+ typedProperties: { repository },+ },+ secretDataEntities: [+ { id: "metadata-only", name: "Example detector metadata", type: "API_KEY" },+ ],+};+const iac = {+ id: "occurrence-1",+ name: "Example infrastructure setting",+ severity: "LOW",+ status: "OPEN",+ expectedContent: "",+ foundContent: " ",+ matchContent: "enabled = true",+ filePath: "infra/main.tf",+ startLine: 20,+ endLine: 22,+ repository,+ branch: { id: "wiz-branch", name: "feature/parser" },+ platform: "TERRAFORM",+ cloudPlatform: "AWS",+ fileURL: "https://github.com/example/project/blob/main/infra/main.tf",+ wizUrl: "https://vendor.example.test/findings/occurrence-1",+ firstSeenAt: "2026-10-01T10:00:00Z",+ lastSeenAt: "2026-10-02T10:00:00Z",+ rule: { id: "example-rule", shortId: "EXAMPLE-1", name: "Example setting" },+ resourceGraphEntity: {+ id: "logical-resource",+ type: "BUCKET",+ properties: { deployed: false },+ },+ fileRemediation: { filePath: "infra/main.tf" },+};++function envelope(root: string, nodes: unknown[], withInventory = true) {+ return {+ data: {+ [root]: { nodes, pageInfo: { hasNextPage: false } },+ ...(withInventory ? { versionControlResources: inventory } : {}),+ },+ };+}++async function fixture(payload: unknown, compressed = false) {+ const root = await mkdtemp(join(tmpdir(), "wiz-repository-findings-"));+ directories.push(root);+ const file = join(root, "selected.json");+ const contents = JSON.stringify(payload);+ await writeFile(file, compressed ? gzipSync(contents) : contents);+ return { root, file };+}++async function parse(payload: unknown) {+ const { file } = await fixture(payload);+ return readVendorFindings(file);+}++test("SAST maps source range, CWE, scanner verdict, and repository inventory without changing raw evidence", async () => {+ const { file } = await fixture(envelope("sastFindings", [sast]), true);+ const parsed = await readVendorFindings(file);+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]).toMatchObject({+ source_finding_id: "sast:occurrence-1",+ evidence: {+ severity: "high",+ locations: [{ path: "src/query.ts", line: 10 }],+ branch: "example/project/feature/parser",+ code_revision: null,+ source_scan_id: null,+ source_updated_at: null,+ advisory_ids: [],+ packages: [],+ source_data: sast,+ details: {+ kind: "sast",+ repository: { ...repository, url: repositoryUrl },+ source_status: "OPEN",+ scanner_origin: "THIRD_PARTY_SCANNER",+ scanner_verdict: "FALSE_POSITIVE",+ weakness_ids: ["CWE-89"],+ remediation_instructions: sast.remediationInstructions,+ code: { end_line: 12, snippet: "query(input)" },+ },+ },+ });+ expect(parsed.findings[0]!.evidence).not.toHaveProperty("assessment");+});++test("repository secrets preserve detector and vendor validation metadata without inventing a source location or scanned revision", async () => {+ const detailed = {+ ...secret,+ id: "detailed",+ path: "config/example.env",+ lineNumber: 3,+ vcsDetails: { initialCommitHash: "a".repeat(40) },+ };+ const parsed = await parse(envelope("secretInstances", [secret, detailed]));+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.evidence).toMatchObject({+ severity: "medium",+ locations: [],+ source_updated_at: 1790848800,+ code_revision: null,+ source_data: secret,+ details: {+ kind: "secret",+ source_status: "RESOLVED",+ rule: { id: "example-secret-rule", name: "Example API key" },+ secret: {+ type: "API_KEY",+ confidence: "HIGH",+ validation_status: "NOT_VALIDATED",+ is_encrypted: false,+ is_managed: true,+ introduced_commit: null,+ },+ },+ });+ expect(parsed.findings[1]!.evidence).toMatchObject({+ locations: [{ path: detailed.path, line: 3 }],+ code_revision: null,+ details: { secret: { introduced_commit: "a".repeat(40) } },+ source_data: detailed,+ });+});++test("IaC keeps exact empty comparison text, the rule, file link, and logical resource separately", async () => {+ const parsed = await parse(envelope("iacFindings", [iac]));+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.evidence).toMatchObject({+ url: iac.wizUrl,+ source_updated_at: null,+ code_revision: null,+ source_data: iac,+ details: {+ kind: "iac",+ rule: {+ id: "example-rule",+ short_id: "EXAMPLE-1",+ name: "Example setting",+ },+ code: { end_line: 22, snippet: "enabled = true" },+ configuration: {+ platform: "TERRAFORM",+ cloud_platform: "AWS",+ expected: "",+ actual: " ",+ },+ file_url: iac.fileURL,+ },+ });+});++test("explicit finding families namespace reused vendor occurrence IDs", async () => {+ const parsed = await parse({+ data: {+ versionControlResources: inventory,+ sastFindings: { nodes: [sast] },+ secretInstances: { nodes: [secret] },+ iacFindings: { nodes: [iac] },+ },+ });+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings.map((finding) => finding.source_finding_id)).toEqual([+ "sast:occurrence-1",+ "secret:occurrence-1",+ "iac:occurrence-1",+ ]);+});++test("bare arrays cannot guess a new finding family even when package fields also exist", async () => {+ const ambiguous = {+ ...sast,+ detailedName: "example-package",+ vulnerableAsset: { id: "asset" },+ };+ const parsed = await parse([sast, secret, iac, ambiguous]);+ expect(parsed.findings).toEqual([]);+ expect(parsed.excluded).toHaveLength(4);+ expect(parsed.excluded.every((item) => item.reason.includes("named"))).toBe(+ true,+ );+ expect(+ (await parse(envelope("sastFindings", [ambiguous]))).findings[0]!.evidence+ .source_data,+ ).toEqual(ambiguous);+});++test("repository mapping joins only repository.id, accepts supplied URLs, and rejects conflicts", async () => {+ const wrongJoin = {+ ...inventory,+ nodes: [+ {+ ...inventory.nodes[0],+ id: repository.id,+ repository: {+ id: "different-repository",+ name: repository.name,+ url: repositoryUrl,+ },+ },+ ],+ };+ const missing = await parse({+ data: {+ sastFindings: { nodes: [sast] },+ versionControlResources: wrongJoin,+ },+ });+ expect(missing.findings).toEqual([]);+ expect(missing.excluded[0]!.reason).toContain(+ "verified source repository URL",+ );+ const enriched = {+ ...sast,+ repository: { ...repository, url: repositoryUrl },+ };+ expect(+ (await parse(envelope("sastFindings", [enriched], false))).excluded,+ ).toEqual([]);+ const conflict = {+ ...sast,+ repository: { ...repository, url: "https://github.com/example/other" },+ };+ expect(+ (await parse(envelope("sastFindings", [conflict]))).excluded[0]!.reason,+ ).toContain("conflicting");+});++test("workload secrets and cloud configuration remain visible exclusions in a mixed explicit export", async () => {+ const workload = {+ ...secret,+ id: "workload",+ resource: { ...secret.resource, type: "VIRTUAL_MACHINE" },+ };+ const parsed = await parse({+ data: {+ versionControlResources: inventory,+ secretInstances: { nodes: [secret, workload] },+ configurationFindings: {+ nodes: [{ id: "configuration", name: "Example check" }],+ },+ },+ });+ expect(parsed.findings).toHaveLength(1);+ expect(parsed.excluded).toEqual([+ expect.objectContaining({+ source_finding_id: "workload",+ reason: expect.stringContaining("Workload secrets"),+ }),+ expect.objectContaining({+ source_finding_id: "configuration",+ reason: expect.stringContaining("Cloud configuration"),+ }),+ ]);+});++test("GraphQL errors, unfinished finding pages, and unfinished inventory stop parsing", async () => {+ await expect(+ parse({+ ...envelope("sastFindings", [sast]),+ errors: [{ message: "partial" }],+ }),+ ).rejects.toThrow("GraphQL errors");+ await expect(+ parse({+ data: {+ sastFindings: { nodes: [sast], pageInfo: { hasNextPage: true } },+ },+ }),+ ).rejects.toThrow("another page");+ await expect(+ parse({+ data: {+ sastFindings: { nodes: [sast] },+ versionControlResources: {+ ...inventory,+ pageInfo: { hasNextPage: true },+ },+ },+ }),+ ).rejects.toThrow("inventory has another page");+});++test("new adapters do not fabricate missing occurrence IDs, severity, or line ranges", async () => {+ const invalid = [+ { ...sast, id: null },+ { ...sast, severity: null },+ { ...sast, startLine: null },+ { ...sast, endLine: 9 },+ { ...sast, filePath: "../outside.ts" },+ ];+ const parsed = await parse(envelope("sastFindings", invalid));+ expect(parsed.findings).toEqual([]);+ expect(parsed.excluded).toHaveLength(invalid.length);+});++test.each([+ "schema:prod.json",+ "config:prod/schema.json",+ "config/schema:prod.json",+])(+ "Wiz preserves repository-relative colon path %s and original evidence",+ async (path) => {+ const finding = { ...sast, filePath: path };+ const parsed = await parse(envelope("sastFindings", [finding]));+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.evidence.locations).toEqual([+ { path, line: 10 },+ ]);+ expect(parsed.findings[0]!.evidence.source_data).toEqual(finding);+ },+);++test.each([+ "C:query.ts",+ "c:/query.ts",+ "D:\\query.ts",+ "/query.ts",+ "\\\\server\\query.ts",+ "../query.ts",+ "src/../query.ts",+])("external evidence rejects non-repository path %s", (path) => {+ expect(() =>+ validateExternalEvidence({+ title: "Synthetic evidence",+ severity: "high",+ locations: [{ path }],+ }),+ ).toThrow("repository-relative paths");+});++test("legacy evidence defaults retain their saved-submission bytes, including explicit null details", () => {+ const input = {+ title: "Legacy evidence",+ severity: "high",+ locations: [{ path: "package.json" }],+ packages: [{ name: "example-package" }],+ };+ const legacy = validateExternalEvidence(structuredClone(input));+ expect(hash("sha256", JSON.stringify(legacy))).toBe(+ "88f2d96656a5ad322d5f16fce7704366e359a8101d035b311a1917d4f6e31caf",+ );+ const withNull = validateExternalEvidence({+ ...structuredClone(input),+ details: null,+ });+ expect(withNull).toEqual(legacy);+ expect(withNull).not.toHaveProperty("details");+});++test("normalized JSONL retains explicit IDs, original evidence, and empty source text", async () => {+ const raw = { details: null, example: "raw evidence stays exact" };+ const payload = {+ source_finding_id: "explicit-identity",+ evidence: {+ title: "Explicit finding",+ severity: "high",+ source_data: raw,+ details: {+ kind: "sast",+ repository: { url: repositoryUrl },+ code: { snippet: " " },+ },+ },+ };+ const parsed = await parse([payload]);+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.source_finding_id).toBe("explicit-identity");+ expect(parsed.findings[0]!.evidence.source_data).toEqual(raw);+ expect(parsed.findings[0]!.evidence.details?.code?.snippet).toBe(" ");+});++test("new detail links and long source text follow the same Cloud constraints", async () => {+ const good = { ...sast, snippet: "é".repeat(32768) };+ const tooLong = { ...sast, id: "long", snippet: "é".repeat(32769) };+ const unsafeUrl = {+ ...sast,+ id: "unsafe",+ repository: { ...repository, url: "https://[email protected]/project" },+ };+ const parsed = await parse(envelope("sastFindings", [good, tooLong]));+ expect(parsed.findings).toHaveLength(1);+ expect(parsed.excluded[0]!.reason).toContain("65536 UTF-8 bytes");+ expect(+ (await parse(envelope("sastFindings", [unsafeUrl], false))).excluded[0]!+ .reason,+ ).toContain("without credentials");+});++async function cloudFixture(payload: unknown) {+ const f = await fixture(payload);+ const environment = {+ ...process.env,+ CODEX_HOME: join(f.root, "login"),+ CODEX_SECURITY_STATE_DIR: join(f.root, "state"),+ };+ await mkdir(environment.CODEX_HOME);+ await writeFile(+ join(environment.CODEX_HOME, "config.toml"),+ 'cli_auth_credentials_store = "file"\n',+ );+ await writeFile(+ join(environment.CODEX_HOME, "auth.json"),+ JSON.stringify({+ tokens: {+ access_token: "synthetic-token",+ account_id: "synthetic-account",+ },+ }),+ );+ const destination = {+ id: "cloud-repository",+ object: "security.repository",+ repo_connector_id: "github",+ url: repositoryUrl,+ default_branch: "main",+ reset_marker: "generation-1",+ import_environment_id: "environment-1",+ };+ const posts: FindingImportRequest[] = [];+ const calls: string[] = [];+ const reports = new Map<string, SourceReport>();+ const state: {+ failReadback: boolean;+ readbackDetails?: ExternalFindingEvidence["details"];+ readbackEvidence?: ExternalFindingEvidence;+ } = { failReadback: false };+ const transport = async (+ url: string,+ init: RequestInit,+ ): Promise<Response> => {+ calls.push(`${init.method} ${url}`);+ const target = new URL(url);+ const json = (body: unknown) =>+ new Response(JSON.stringify(body), {+ headers: { "Content-Type": "application/json" },+ });+ if (target.pathname.endsWith("/repositories"))+ return json({ data: [destination], has_more: false, next: null });+ if (target.pathname.endsWith("/source_reports")) {+ const report = reports.get(target.searchParams.get("source_finding_id")!);+ const summaries = report+ ? [+ {+ ...report,+ object: "security.source_report_summary",+ evidence: undefined,+ last_import: undefined,+ title: report.evidence.title,+ severity: report.evidence.severity,+ source_updated_at: report.evidence.source_updated_at,+ },+ ]+ : [];+ return json({ data: summaries, has_more: false, next: null });+ }+ if (target.pathname.includes("/source_reports/")) {+ if (state.failReadback)+ return new Response(+ JSON.stringify({ error: { message: "Readback unavailable" } }),+ { status: 503 },+ );+ const report = [...reports.values()].find(+ (item) => item.id === target.pathname.split("/").at(-1),+ );+ if (report && state.readbackEvidence)+ return json({ ...report, evidence: state.readbackEvidence });+ return json(+ report && state.readbackDetails+ ? {+ ...report,+ evidence: { ...report.evidence, details: state.readbackDetails },+ }+ : report,+ );+ }+ if (+ target.pathname.endsWith("/finding_imports") &&+ init.method === "POST"+ ) {+ const request = JSON.parse(String(init.body)) as FindingImportRequest;+ posts.push(request);+ const counts = { created: 0, updated: 0, unchanged: 0, error: 0 };+ const results = request.items.map((item) => {+ const previous = reports.get(item.source_finding_id);+ const outcome = previous+ ? JSON.stringify(previous.evidence) === JSON.stringify(item.evidence)+ ? "unchanged"+ : "updated"+ : "created";+ counts[outcome]++;+ const version =+ (previous?.version ?? 0) + (outcome === "unchanged" ? 0 : 1);+ const identity = hash("sha256", item.source_finding_id);+ const report: SourceReport = {+ id: `aif_${identity}`,+ repo_id: destination.id,+ repo_connector_id: destination.repo_connector_id,+ environment_id: "environment-1",+ canonical_finding_id:+ previous?.canonical_finding_id ?? `acf_${identity.slice(0, 32)}`,+ source: request.source,+ source_finding_id: item.source_finding_id,+ observation_id: `aio_${hash("sha256", `${identity}:${version}`)}`,+ version,+ evidence: item.evidence,+ assessment: { state: "not_assessed" },+ created_at: 1,+ updated_at: 1,+ };+ if (previous) report.id = previous.id;+ reports.set(item.source_finding_id, report);+ return {+ client_id: item.client_id,+ outcome,+ source_report_id: report.id,+ observation_id: report.observation_id,+ canonical_finding_id: report.canonical_finding_id,+ version,+ };+ });+ return json({+ id: request.request_id,+ repository: request.repository,+ source: request.source,+ actor: "synthetic-user",+ created_at: 1,+ item_count: request.items.length,+ counts,+ results,+ });+ }+ throw new Error(`Unexpected injected Cloud request ${init.method} ${url}`);+ };+ const options = {+ provider: "wiz" as const,+ sourceKey: "synthetic-tenant/wiz",+ repository: repositoryUrl,+ };+ const command = [+ "publish",+ "findings",+ f.file,+ "--to",+ "cloud",+ "--provider",+ "wiz",+ "--repository",+ repositoryUrl,+ "--source-key",+ options.sourceKey,+ "--format",+ "json",+ ];+ return {+ ...f,+ posts,+ calls,+ reports,+ state,+ destination,+ options,+ command,+ environment,+ deps: { environment, fetch: transport },+ cliDeps: { ...dependencies(), environment, cloudFetch: transport },+ };+}++for (const [root, record, kind] of [+ ["sastFindings", sast, "sast"],+ ["secretInstances", secret, "secret"],+ ["iacFindings", iac, "iac"],+] as const) {+ test(`CLI previews, publishes, and reimports ${kind} through injected transport without changing Codex assessment`, async () => {+ const f = await cloudFixture(envelope(root, [record]));+ const cli = createCliTest(main);+ expect(await cli.runCli([...f.command, "--dry-run"], f.cliDeps)).toBe(0);+ const preview = JSON.parse(cli.stdout.text());+ expect(preview.findings[0].evidence.details.kind).toBe(kind);+ expect(f.posts).toHaveLength(0);+ const upload = createCliTest(main);+ const exitCode = await upload.runCli([...f.command, "--yes"], f.cliDeps);+ expect(exitCode, upload.stdout.text() + upload.stderr.text()).toBe(0);+ expect(f.posts).toHaveLength(1);+ const first = f.reports.get(`${kind}:occurrence-1`)!;+ expect(first.assessment).toEqual({ state: "not_assessed" });+ expect(first.evidence.source_data).toEqual(record);+ const replay = await prepareExternalPublication(f.file, f.options, f.deps);+ expect((await replay.publish()).counts.unchanged).toBe(1);+ expect(f.reports.get(`${kind}:occurrence-1`)!.canonical_finding_id).toBe(+ first.canonical_finding_id,+ );+ const changed = { ...record, status: "RESOLVED" };+ await writeFile(f.file, JSON.stringify(envelope(root, [changed])));+ await (+ await prepareExternalPublication(f.file, f.options, f.deps)+ ).publish();+ expect(f.reports.get(`${kind}:occurrence-1`)!.assessment).toEqual({+ state: "not_assessed",+ });+ expect(f.reports.get(`${kind}:occurrence-1`)!.evidence.source_data).toEqual(+ changed,+ );+ });+}++test.each(["synchronous", "asynchronous"] as const)(+ "approved finding publication survives %s diagnostic stream failures",+ async (failure) => {+ const f = await cloudFixture(envelope("sastFindings", [sast]));+ const stdout = capture();+ const stderr = Object.assign(+ new Writable({+ write(_chunk, _encoding, callback) {+ callback(new Error("Synthetic diagnostic stream failure"));+ },+ }),+ { isTTY: true },+ );+ if (failure === "synchronous")+ stderr.write = () => {+ throw new Error("Synthetic diagnostic stream failure");+ };+ const code = await main(+ [...f.command.slice(0, -2), "--yes"],+ stdout.stream,+ stderr,+ f.cliDeps,+ );+ expect(code).toBe(0);+ expect(f.posts).toHaveLength(1);+ expect(f.reports.get("sast:occurrence-1")!.assessment).toEqual({+ state: "not_assessed",+ });+ expect(stdout.text()).toContain("1");+ },+);++test("a wrong source repository stops raw and normalized imports before source lookup or upload", async () => {+ const other = {+ ...sast,+ repository: { ...repository, url: "https://github.com/example/other" },+ };+ const f = await cloudFixture(envelope("sastFindings", [other], false));+ await expect(+ prepareExternalPublication(f.file, f.options, f.deps),+ ).rejects.toThrow("does not match the selected Cloud repository");+ expect(f.calls).toHaveLength(1);+ expect(f.posts).toEqual([]);+ const normalized = (await readVendorFindings(f.file)).findings;+ await writeFile(f.file, JSON.stringify(normalized));+ await expect(+ prepareExternalPublication(f.file, f.options, f.deps),+ ).rejects.toThrow("does not match");+ expect(f.posts).toEqual([]);+ expect(+ await readdir(join(f.root, "state")).catch(() => undefined),+ ).toBeUndefined();+});++test("saved typed requests resume by repository ID after a repository rename", async () => {+ const f = await cloudFixture(envelope("sastFindings", [sast]));+ const options = { ...f.options, repository: f.destination.id };+ f.state.failReadback = true;+ await expect(+ (await prepareExternalPublication(f.file, options, f.deps)).publish(),+ ).rejects.toThrow("Readback unavailable");+ expect(f.posts).toHaveLength(1);+ f.destination.url = "https://github.com/example/renamed";+ f.state.failReadback = false;+ const resumed = await prepareExternalPublication(f.file, options, f.deps);+ expect(resumed.preview.resumed).toBe(true);+ expect(resumed.preview.destination.url).toBe(f.destination.url);+ expect((await resumed.publish()).verified).toBe(1);+ expect(f.posts).toHaveLength(1);+ expect(+ f.reports.get("sast:occurrence-1")!.evidence.details!.repository!.url,+ ).toBe(repositoryUrl);+});++// Expected details were serialized by the canonical Cloud validation model.+// Keep that readback independent of the CLI validator so nullable defaults cannot+// be hidden by a transport that merely echoes the submitted evidence.+for (const golden of roundtripFixtures) {+ test(`sparse ${golden.name} evidence matches canonical Cloud readback`, async () => {+ const evidence = {+ title: "Synthetic normalized finding",+ severity: "high",+ details: golden.input,+ source_data: { id: golden.name, details: null },+ };+ const f = await cloudFixture([+ { source_finding_id: golden.name, evidence },+ ]);+ f.state.readbackDetails = structuredClone(golden.expected) as NonNullable<+ ExternalFindingEvidence["details"]+ >;+ const prepared = await prepareExternalPublication(+ f.file,+ f.options,+ f.deps,+ );+ expect(prepared.preview.findings[0]!.evidence.details).toEqual(+ f.state.readbackDetails,+ );+ expect((await prepared.publish()).verified).toBe(1);+ expect(f.posts[0]!.items[0]!.evidence.source_data).toEqual(+ evidence.source_data,+ );+ });+}++test("GitHub repository metadata accepts case variants without changing source URLs", async () => {+ const supplied = {+ ...sast,+ repository: {+ ...repository,+ url: "HTTPS://GITHUB.COM/Example/PROJECT.git/",+ },+ };+ const mixedInventory = {+ ...inventory,+ nodes: [+ ...inventory.nodes,+ {+ ...inventory.nodes[0]!,+ repository: {+ ...repository,+ url: "https://github.com/EXAMPLE/Project.git/",+ },+ },+ ],+ };+ const parsed = await parse({+ data: {+ sastFindings: { nodes: [supplied] },+ versionControlResources: mixedInventory,+ },+ });+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.evidence.source_data).toEqual(supplied);+ expect(parsed.findings[0]!.evidence.details!.repository!.url).toBe(+ supplied.repository.url,+ );+});++test.each([+ [+ "https://github.com/Example/Project.git/",+ "https://github.com/example/project",+ true,+ ],+ [+ "https://EXAMPLE.ghe.com/Team/Project.git/",+ "https://example.ghe.com/team/project",+ true,+ ],+ [+ "https://github.com/Example/Other.git/",+ "https://github.com/example/project",+ false,+ ],+ [+ "https://other.ghe.com/team/project",+ "https://example.ghe.com/team/project",+ false,+ ],+ [+ "https://github.example.test/Team/Project.git/",+ "https://github.example.test/team/project",+ true,+ ],+ [+ "http://github.com/example/project",+ "https://github.com/example/project",+ false,+ ],+ [+ "https://github.com:443/example/project",+ "https://github.com/example/project",+ false,+ ],+ [+ "https://example.ghe.com/Team/Project.GIT/",+ "https://example.ghe.com/team/project",+ false,+ ],+])(+ "repository URL binding preserves identity: %s to %s",+ async (sourceUrl, destinationUrl, matches) => {+ const record = { ...sast, repository: { ...repository, url: sourceUrl } };+ const f = await cloudFixture(envelope("sastFindings", [record], false));+ f.destination.url = destinationUrl;+ const options = { ...f.options, repository: f.destination.id };+ if (matches) {+ const publication = await prepareExternalPublication(+ f.file,+ options,+ f.deps,+ );+ expect((await publication.publish()).verified).toBe(1);+ expect(f.posts[0]!.items[0]!.evidence.source_data).toEqual(record);+ } else {+ await expect(+ prepareExternalPublication(f.file, options, f.deps),+ ).rejects.toThrow("does not match");+ expect(f.posts).toEqual([]);+ }+ },+);++test.each(["github.com", "example.ghe.com", "github.example.test"])(+ "Cloud GitHub repository selection accepts a URL case variant on %s",+ async (host) => {+ const url = "https://" + host + "/example/project";+ const record = { ...sast, repository: { ...repository, url } };+ const f = await cloudFixture(envelope("sastFindings", [record], false));+ f.destination.url = url;+ const prepared = await prepareExternalPublication(+ f.file,+ {+ ...f.options,+ repository: "HTTPS://" + host.toUpperCase() + "/Example/PROJECT.git/",+ },+ f.deps,+ );+ expect(prepared.preview.destination.id).toBe(f.destination.id);+ expect(f.posts).toEqual([]);+ },+);++test("custom GitHub Enterprise binding preserves branch case and exact source evidence", async () => {+ const record = {+ ...sast,+ repository: {+ ...repository,+ name: "Team/Project",+ url: "https://github.example.test/Team/Project.git/",+ },+ repositoryBranch: {+ id: "wiz-branch",+ name: "Team/Project/Feature/Parser/More",+ },+ };+ const f = await cloudFixture(envelope("sastFindings", [record], false));+ f.destination.url = "https://github.example.test/team/project";+ f.destination.repo_connector_id = "custom-github";+ const prepared = await prepareExternalPublication(+ f.file,+ { ...f.options, repository: f.destination.id },+ f.deps,+ );+ expect((await prepared.publish()).verified).toBe(1);+ const evidence = f.posts[0]!.items[0]!.evidence;+ expect(evidence.branch).toBe(record.repositoryBranch.name);+ expect(evidence.details!.repository!.url).toBe(record.repository.url);+ expect(evidence.source_data).toEqual(record);+});++test.each([+ ["sastFindings", "Team/Project", "team/project"],+ ["sastFindings", "team/project", "Team/Project"],+ ["secretInstances", "Team/Project", "team/project"],+ ["secretInstances", "team/project", "Team/Project"],+ ["iacFindings", "Team/Project", "team/project"],+ ["iacFindings", "team/project", "Team/Project"],+])(+ "%s custom GitHub URL-only branches preserve the supplied name (%s, %s)",+ async (collection, repositoryPath, qualifier) => {+ const sourceRepository = {+ id: "wiz-repository",+ url: `https://github.example.test/${repositoryPath}`,+ };+ const branch = {+ id: "wiz-branch",+ name: `${qualifier}/Feature/Parser/More`,+ };+ const record =+ collection === "secretInstances"+ ? {+ ...secret,+ resource: {+ ...secret.resource,+ name: branch.name,+ typedProperties: { repository: sourceRepository },+ },+ }+ : collection === "iacFindings"+ ? { ...iac, repository: sourceRepository, branch }+ : { ...sast, repository: sourceRepository, repositoryBranch: branch };+ const f = await cloudFixture(envelope(collection!, [record], false));+ f.destination.url = "https://github.example.test/team/project";+ const prepared = await prepareExternalPublication(+ f.file,+ { ...f.options, repository: f.destination.id },+ f.deps,+ );+ expect((await prepared.publish()).verified).toBe(1);+ const evidence = f.posts[0]!.items[0]!.evidence;+ expect(evidence.branch).toBe(branch.name);+ expect(evidence.details!.repository!.url).toBe(sourceRepository.url);+ expect(evidence.source_data).toEqual(record);+ },+);++test("unidentified source hosts still require exact supplied and inventory URL paths", async () => {+ const record = {+ ...sast,+ repository: {+ ...repository,+ url: "https://code.example.test/Team/Project",+ },+ };+ const parsed = await parse({+ data: {+ sastFindings: { nodes: [record] },+ versionControlResources: {+ nodes: [+ {+ id: "unidentified-branch",+ repository: {+ ...repository,+ url: "https://code.example.test/team/project",+ },+ },+ ],+ },+ },+ });+ expect(parsed.findings).toEqual([]);+ expect(parsed.excluded[0]!.reason).toContain("conflicting repository URLs");+});++test("Node reads a large complete named collection without a function argument limit", async () => {+ const count = 150_000;+ const records = Array.from({ length: count }, (_, index) => ({+ id: `vendor-${index}`,+ name: "CVE-2099-0001",+ detailedName: "example-package",+ severity: "HIGH",+ vulnerableAsset: { id: "synthetic-asset" },+ }));+ const f = await fixture(envelope("vulnerabilityFindings", records, false));+ // Run the actual parser under Node; Bun does not have the same argument limit.+ const bundle = await mkdtemp(join(import.meta.dir, "..", ".wiz-parser-"));+ directories.push(bundle);+ const runner = join(bundle, "large-input.mts");+ await writeFile(+ runner,+ `+ import { readVendorFindings } from "../src/wiz-findings.js";+ const parsed = await readVendorFindings(process.argv[2]!);+ console.log(JSON.stringify({+ read: parsed.read, ready: parsed.findings.length, excluded: parsed.excluded.length,+ first: parsed.findings[0]?.source_finding_id,+ last: parsed.findings.at(-1)?.source_finding_id,+ }));+ `,+ );+ const built = await Bun.build({+ entrypoints: [runner],+ outdir: bundle,+ target: "node",+ format: "esm",+ packages: "external",+ });+ expect(built.success).toBe(true);+ const child = Bun.spawn(+ [Bun.which("node")!, built.outputs[0]!.path, f.file],+ { stdout: "pipe", stderr: "pipe" },+ );+ const [exitCode, stdout, stderr] = await Promise.all([+ child.exited,+ new Response(child.stdout).text(),+ new Response(child.stderr).text(),+ ]);+ expect(exitCode, stderr).toBe(0);+ expect(JSON.parse(stdout)).toEqual({+ read: count,+ ready: count,+ excluded: 0,+ first: "vendor-0",+ last: `vendor-${count - 1}`,+ });+});++test.each(["migrate", "distinct", "duplicate"])(+ "Unicode readback resumes historical checkpoints (%s)",+ async (scenario) => {+ const input = {+ source_finding_id: "unicode-evidence",+ evidence: {+ title: "Unicode vendor metadata",+ severity: "high",+ source_data: { é: "precomposed", "e\u0301": "combining", Z: 1, a: 2 },+ },+ };+ const f = await cloudFixture([input]);+ const deps = {+ ...f.deps,+ environment: {+ ...f.environment,+ CODEX_SECURITY_CLOUD_BASE_URL: DEFAULT_CLOUD_BASE_URL,+ },+ };+ const prepared = await prepareExternalPublication(f.file, f.options, deps);+ f.state.failReadback = true;+ let failure: ExternalPublicationError | undefined;+ try {+ await prepared.publish();+ } catch (error) {+ expect(error).toBeInstanceOf(ExternalPublicationError);+ failure = error as ExternalPublicationError;+ }+ const pendingPath = failure!.result.savedSubmission!;+ const historical = JSON.parse(await readFile(pendingPath, "utf8"));+ delete historical.inputProjection;+ const saved = JSON.stringify(historical);+ await writeFile(pendingPath, saved);+ // Frozen from the original publisher's production checkpoint format.+ const historicalPath = join(+ f.environment.CODEX_SECURITY_STATE_DIR,+ "external-finding-publications",+ "ddeb8ec0be8765f89ef5aeb759dde7753d7ff72f8b8bb25f89a591b045ad40ae.pending.json",+ );+ expect(pendingPath).not.toBe(historicalPath);+ if (scenario !== "migrate") {+ const legacy = JSON.parse(saved);+ if (scenario === "distinct") {+ legacy.requests[0].request_id = "synthetic-older-request";+ legacy.receipts = [];+ }+ await writeFile(historicalPath, JSON.stringify(legacy));+ } else {+ await rename(pendingPath, historicalPath);+ }+ const evidence = structuredClone(prepared.preview.findings[0]!.evidence);+ evidence.source_data = Object.fromEntries(+ Object.entries(evidence.source_data!).reverse(),+ );+ f.state.readbackEvidence = evidence;+ f.state.failReadback = false;+ const retry = await prepareExternalPublication(f.file, f.options, deps);+ expect(retry.preview.resumed).toBe(true);+ expect(retry.preview.requests).toEqual(prepared.preview.requests);+ expect(await readFile(pendingPath, "utf8")).toBe(saved);+ expect(+ (+ await readdir(+ join(+ f.environment.CODEX_SECURITY_STATE_DIR,+ "external-finding-publications",+ ),+ )+ ).includes(historicalPath.split(/[\\/]/u).at(-1)!),+ ).toBe(scenario === "distinct");+ expect((await retry.publish()).verified).toBe(1);+ expect(f.posts).toHaveLength(1);+ expect(f.posts[0]!.items[0]!.evidence.source_data).toEqual(+ input.evidence.source_data,+ );+ if (scenario === "duplicate")+ expect(+ (await prepareExternalPublication(f.file, f.options, deps)).preview+ .resumed,+ ).toBe(false);+ },+);++test.each([+ {+ phase: "prepare",+ originalBase: DEFAULT_CLOUD_BASE_URL,+ targetBase: DEFAULT_CLOUD_BASE_URL,+ },+ {+ phase: "publish",+ originalBase: DEFAULT_CLOUD_BASE_URL,+ targetBase: DEFAULT_CLOUD_BASE_URL,+ },+ {+ phase: "prepare",+ originalBase: "https://cloud.example.test",+ targetBase: "https://cloud.example.test",+ },+ {+ phase: "prepare",+ originalBase: DEFAULT_CLOUD_BASE_URL,+ targetBase: "https://cloud.example.test",+ },+])(+ "unidentified legacy checkpoints stop before upload (%j)",+ async ({ phase, originalBase, targetBase }) => {+ const f = await cloudFixture([+ {+ source_finding_id: "legacy-locale-evidence",+ evidence: {+ title: "Original evidence",+ severity: "high",+ source_data: { z: 1, ä: 2, Z: 3, a: 4, é: 5 },+ },+ },+ ]);+ const originalDeps = {+ ...f.deps,+ environment: {+ ...f.environment,+ CODEX_SECURITY_CLOUD_BASE_URL: originalBase,+ },+ };+ const original = await prepareExternalPublication(+ f.file,+ f.options,+ originalDeps,+ );+ f.state.failReadback = true;+ let originalPath = "";+ try {+ await original.publish();+ } catch (error) {+ expect(error).toBeInstanceOf(ExternalPublicationError);+ originalPath = (error as ExternalPublicationError).result+ .savedSubmission!;+ }+ const saved = JSON.parse(await readFile(originalPath, "utf8"));+ delete saved.inputProjection;+ const serialized = JSON.stringify(saved);+ const identity = [+ ...(originalBase === DEFAULT_CLOUD_BASE_URL ? [] : [originalBase]),+ original.preview.accountId,+ original.preview.destination.id,+ original.preview.destination.repo_connector_id,+ original.preview.source,+ original.preview.findings,+ ];+ const historicalKey = (locale?: string) => {+ const compare = new Intl.Collator(locale).compare;+ return hash(+ "sha256",+ JSON.stringify(identity, (_key, child: unknown) =>+ child !== null && typeof child === "object" && !Array.isArray(child)+ ? Object.fromEntries(+ Object.entries(child).sort(([left], [right]) =>+ compare(left, right),+ ),+ )+ : child,+ ),+ );+ };+ const currentName = originalPath.split(/[\\/]/u).at(-1)!;+ const legacyKey = ["en-US", "sv-SE"]+ .map(historicalKey)+ .find(+ (key) =>+ key !== historicalKey() && `${key}.pending.json` !== currentName,+ );+ expect(legacyKey).toBeDefined();+ const legacyPath = join(+ f.environment.CODEX_SECURITY_STATE_DIR,+ "external-finding-publications",+ `${legacyKey}.pending.json`,+ );+ await rm(originalPath);+ const newer = f.reports.get("legacy-locale-evidence")!;+ newer.version += 1;+ newer.evidence.description = "Newer Cloud evidence";+ f.state.failReadback = false;+ const targetDeps = {+ ...f.deps,+ environment: {+ ...f.environment,+ CODEX_SECURITY_CLOUD_BASE_URL: targetBase,+ },+ };+ if (phase === "publish") {+ const fresh = await prepareExternalPublication(+ f.file,+ f.options,+ targetDeps,+ );+ await writeFile(legacyPath, serialized);+ await expect(fresh.publish()).rejects.toThrow(+ "original deployment and locale",+ );+ } else {+ await writeFile(legacyPath, serialized);+ await expect(+ prepareExternalPublication(f.file, f.options, targetDeps),+ ).rejects.toThrow("original deployment and locale");+ }+ expect(f.posts).toHaveLength(1);+ expect(newer.evidence.description).toBe("Newer Cloud evidence");+ expect(await readFile(legacyPath, "utf8")).toBe(serialized);+ },+);++test.each([+ "account",+ "repository",+ "source",+ "evidence",+ "projected",+ "invalid",+])(+ "unrelated checkpoints do not block a fresh publication (%s)",+ async (difference) => {+ const f = await cloudFixture([+ {+ source_finding_id: "scope-evidence",+ evidence: { title: "Synthetic scope evidence", severity: "high" },+ },+ ]);+ const prepared = await prepareExternalPublication(+ f.file,+ f.options,+ f.deps,+ );+ const saved: {+ accountId: string;+ requests: FindingImportRequest[];+ inputProjection?: { inputDigest: string; savedEvidenceDigest: string };+ } = {+ accountId: prepared.preview.accountId,+ requests: structuredClone(prepared.preview.requests),+ };+ if (difference === "account") saved.accountId = "another-account";+ if (difference === "repository")+ saved.requests[0]!.repository.id = "another-repository";+ if (difference === "source")+ saved.requests[0]!.source.source_key = "another-source";+ if (difference === "evidence")+ saved.requests[0]!.items[0]!.evidence.title = "Different evidence";+ if (difference === "projected")+ saved.inputProjection = {+ inputDigest: "another-deployment",+ savedEvidenceDigest: "another-deployment",+ };+ const directory = join(+ f.environment.CODEX_SECURITY_STATE_DIR,+ "external-finding-publications",+ );+ await mkdir(directory, { recursive: true, mode: 0o700 });+ const path = join(directory, `${"a".repeat(64)}.pending.json`);+ const serialized =+ difference === "invalid" ? "invalid JSON" : JSON.stringify(saved);+ await writeFile(path, serialized);+ const fresh = await prepareExternalPublication(f.file, f.options, f.deps);+ expect(fresh.preview.resumed).toBe(false);+ expect(await readFile(path, "utf8")).toBe(serialized);+ expect(f.posts).toHaveLength(0);+ },+);++test("Node resumes the same uncertain publication across locales and Unicode key order", async () => {+ const input = {+ source_finding_id: "locale-evidence",+ evidence: {+ title: "Synthetic Unicode metadata",+ severity: "high",+ source_data: { z: 1, ä: 2, é: "precomposed", "e\u0301": "combining" },+ },+ };+ const f = await cloudFixture([input]);+ const bundle = await mkdtemp(join(import.meta.dir, "..", ".wiz-locale-"));+ directories.push(bundle);+ const runner = join(bundle, "publication.mts");+ await writeFile(+ runner,+ `+ import { prepareExternalPublication } from "../src/external-findings-publish.js";+ // Select ICU collation explicitly so this also exercises both locales on+ // Windows hosts whose process default does not follow LANG.+ const collation = new Intl.Collator(process.argv[2]);+ String.prototype.localeCompare = function(other) {+ return collation.compare(String(this), other);+ };+ const prepared = await prepareExternalPublication(+ ${JSON.stringify(f.file)}, ${JSON.stringify(f.options)}, {+ environment: ${JSON.stringify({+ CODEX_HOME: f.environment.CODEX_HOME,+ CODEX_SECURITY_STATE_DIR: f.environment.CODEX_SECURITY_STATE_DIR,+ })},+ credentials: async () => ({ access_token: "synthetic-token", account_id: "synthetic-account" }),+ fetch: async (url, options) => {+ if (options.method === "POST") throw new Error("Synthetic uncertain upload");+ const body = new URL(url).pathname.endsWith("/repositories")+ ? { data: [${JSON.stringify(f.destination)}], has_more: false, next: null }+ : { data: [], has_more: false, next: null };+ return new Response(JSON.stringify(body));+ },+ },+ );+ try { await prepared.publish(); } catch (error) {+ console.log(JSON.stringify({+ locale: collation.resolvedOptions().locale,+ resumed: prepared.preview.resumed,+ requestId: prepared.preview.requests[0].request_id,+ savedSubmission: error.result.savedSubmission,+ }));+ }+ `,+ );+ const built = await Bun.build({+ entrypoints: [runner],+ outdir: bundle,+ target: "node",+ format: "esm",+ packages: "external",+ });+ expect(built.success).toBe(true);+ const run = async (locale: string) => {+ const child = Bun.spawn(+ [Bun.which("node")!, built.outputs[0]!.path, locale],+ {+ stdout: "pipe",+ stderr: "pipe",+ },+ );+ const [exitCode, stdout, stderr] = await Promise.all([+ child.exited,+ new Response(child.stdout).text(),+ new Response(child.stderr).text(),+ ]);+ expect(exitCode, stderr).toBe(0);+ return JSON.parse(stdout) as {+ locale: string;+ resumed: boolean;+ requestId: string;+ savedSubmission: string;+ };+ };+ const first = await run("en-US");+ expect(first.resumed).toBe(false);+ const second = await run("sv-SE");+ expect(second.locale).not.toBe(first.locale);+ expect(second.resumed).toBe(true);+ expect(second.requestId).toBe(first.requestId);+ expect(second.savedSubmission).toBe(first.savedSubmission);+ input.evidence.source_data = Object.fromEntries(+ Object.entries(input.evidence.source_data).reverse(),+ ) as typeof input.evidence.source_data;+ await writeFile(f.file, JSON.stringify([input]));+ const reordered = await run("en-US");+ expect(reordered.resumed).toBe(true);+ expect(reordered.requestId).toBe(first.requestId);+ expect(reordered.savedSubmission).toBe(first.savedSubmission);+});++for (const format of ["json", "jsonl"] as const) {+ test(`failed ${format} preparation preserves diagnostics under success-field filtering`, async () => {+ const f = await cloudFixture(envelope("sastFindings", [sast]));+ await rm(f.file);+ const cli = createCliTest(main);+ expect(+ await cli.runCli(+ [+ ...f.command.slice(0, -2),+ "--format",+ format,+ "--filter-output",+ "counts",+ "--yes",+ ],+ f.cliDeps,+ ),+ ).toBe(2);+ expect(JSON.parse(cli.stdout.text())).toMatchObject({+ status: "failed",+ error: expect.stringContaining("ENOENT"),+ });+ expect(f.calls).toEqual([]);+ });++ test(`failed ${format} full-output imports emit failure envelopes`, async () => {+ const f = await cloudFixture(envelope("sastFindings", [sast]));+ await writeFile(f.file, "{");+ const cli = createCliTest(main);+ expect(+ await cli.runCli(+ [+ ...f.command.slice(0, -2),+ "--format",+ format,+ "--full-output",+ "--yes",+ ],+ f.cliDeps,+ ),+ ).toBe(2);+ const output = JSON.parse(cli.stdout.text());+ expect(output.ok).toBe(false);+ expect(output.error.code).toBe("IMPORT_FAILED");+ expect(output.data.status).toBe("failed");+ expect(output.meta.command).toBe("publish findings");+ expect(f.calls).toEqual([]);+ });++ test(`interrupted ${format} full-output preserves acknowledged receipts and resumes`, async () => {+ const f = await cloudFixture(envelope("sastFindings", [sast]));+ f.state.failReadback = true;+ const command = [+ ...f.command.slice(0, -2),+ "--format",+ format,+ "--full-output",+ "--yes",+ ];+ const cli = createCliTest(main);+ expect(await cli.runCli(command, f.cliDeps)).toBe(2);+ const output = JSON.parse(cli.stdout.text());+ expect(output.ok).toBe(false);+ expect(output.error.code).toBe("IMPORT_FAILED");+ expect(output.data).toMatchObject({+ status: "interrupted",+ counts: { created: 1 },+ verified: 0,+ });+ expect(output.data.receipts).toHaveLength(1);+ expect(output.data.savedSubmission).toBeString();+ f.state.failReadback = false;+ const retry = createCliTest(main);+ expect(await retry.runCli(command, f.cliDeps)).toBe(0);+ expect(JSON.parse(retry.stdout.text())).toMatchObject({+ ok: true,+ data: { status: "complete", verified: 1 },+ });+ expect(f.posts).toHaveLength(1);+ });+}++test.each([undefined, "toon", "yaml", "md"])(+ "unsupported full-output format %s is rejected before reading or contacting Cloud",+ async (format) => {+ const f = await cloudFixture(envelope("sastFindings", [sast]));+ await rm(f.file);+ const cli = createCliTest(main);+ const command = [+ ...f.command.slice(0, -2),+ ...(format ? ["--format", format] : []),+ "--full-output",+ "--yes",+ ];+ expect(await cli.runCli(command, f.cliDeps)).toBe(2);+ expect(+ (cli.stdout.text() + cli.stderr.text()).replace(/\s+/g, " "),+ ).toContain("--format json or --format jsonl");+ expect(f.calls).toEqual([]);+ expect(f.posts).toEqual([]);+ },+);++for (const kind of ["sast", "secret", "iac"] as const) {+ test.each([+ [repositoryUrl, "example/project/feature/parser", null],+ [repositoryUrl, "example/project/fix", null],+ [+ "https://GitHub.com/Example/Project.git/",+ "EXAMPLE/PROJECT/Feature/Parser/More",+ null,+ ],+ [+ "https://GitHub.com/Example/Project.git/",+ "EXAMPLE/PROJECT.git/Feature/Parser/More",+ null,+ ],+ [repositoryUrl, "example/project.git/Feature/Parser", null],+ ["https://github.com/demo/demo", "demo/demo/Feature/Parser/More", "demo"],+ [+ "https://github.com/Demo/Demo.git/",+ "DEMO/DEMO.git/Feature/Parser/More",+ "demo",+ ],+ [+ "https://github.example.test/team/project",+ "PROJECT/Feature/Parser",+ "project",+ ],+ [repositoryUrl, "project/fix", "project"],+ [repositoryUrl, "other/project/fix", "other/project"],+ [repositoryUrl, "Feature/Parser", null],+ [repositoryUrl, "fix/example/project/Parser", null],+ [repositoryUrl, "example/project", null],+ ["https://github.com/", "example/project/feature/parser", null],+ ])(+ kind + " preserves the reported branch from %s: %s",+ async (url, branch, name) => {+ const repository = { url, ...(name ? { name } : {}) };+ const record =+ kind === "sast"+ ? {+ ...sast,+ repository,+ repositoryBranch: { id: "wiz-branch", name: branch },+ }+ : kind === "secret"+ ? {+ ...secret,+ resource: {+ ...secret.resource,+ name: branch,+ typedProperties: { repository },+ },+ }+ : {+ ...iac,+ repository,+ branch: { id: "wiz-branch", name: branch },+ };+ const root =+ kind === "sast"+ ? "sastFindings"+ : kind === "secret"+ ? "secretInstances"+ : "iacFindings";+ const parsed = await parse(envelope(root, [record], false));+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.evidence.branch).toBe(branch);+ expect(parsed.findings[0]!.evidence.details!.repository).toEqual({+ url,+ name,+ id: null,+ });+ expect(parsed.findings[0]!.evidence.source_data).toEqual(record);+ },+ );+}++// Synthetic nodes follow Wiz's documented VersionControlResources platform field.+const enterpriseUrl = "https://github.example.test/example/project";+function inventoryNode(platform: string | undefined, url = enterpriseUrl) {+ return {+ id: "wiz-inventory-node",+ type: "REPOSITORY_BRANCH",+ platform,+ repository: { id: repository.id, url },+ };+}++test.each([false, true])(+ "publication checkpoints survive optional inventory platform changes (%j)",+ async (withHint) => {+ const inventory = inventoryNode(+ withHint ? "GITHUB" : undefined,+ "https://github.example.test/Example/Project",+ );+ const payload = {+ data: {+ sastFindings: {+ nodes: [{ ...sast, repository: { id: repository.id } }],+ },+ versionControlResources: { nodes: [inventory] },+ },+ };+ const f = await cloudFixture(payload);+ f.destination.url = enterpriseUrl;+ const options = { ...f.options, repository: f.destination.id };+ const original = await prepareExternalPublication(f.file, options, f.deps);+ f.state.failReadback = true;+ await expect(original.publish()).rejects.toBeInstanceOf(+ ExternalPublicationError,+ );+ inventory.platform = withHint ? undefined : "GITHUB";+ await writeFile(f.file, JSON.stringify(payload));+ const retry = await prepareExternalPublication(f.file, options, f.deps);+ expect(retry.preview.findings).toEqual(original.preview.findings);+ expect(retry.preview.resumed).toBe(true);+ expect(retry.preview.requests).toEqual(original.preview.requests);+ const newer = f.reports.get("sast:occurrence-1")!;+ newer.version += 1;+ newer.evidence.description = "Newer Cloud evidence";+ f.state.failReadback = false;+ expect((await retry.publish()).verified).toBe(1);+ expect(f.posts).toHaveLength(1);+ expect(newer.evidence.description).toBe("Newer Cloud evidence");+ },+);++test.each(["project", "project/component"])(+ "inventory aliases preserve literal branch prefix %s in either row order",+ async (alias) => {+ const record = {+ ...sast,+ repository: { id: repository.id },+ repositoryBranch: {+ ...sast.repositoryBranch,+ name: `${alias.toUpperCase()}/Feature/Parser`,+ },+ };+ const nodes = ["example/project", "project", alias].map((name) => ({+ ...inventoryNode("GITHUB", repositoryUrl),+ repository: { ...repository, url: repositoryUrl, name },+ }));+ for (const selected of [nodes, [...nodes].reverse()]) {+ const parsed = await parse({+ data: {+ sastFindings: { nodes: [record] },+ versionControlResources: { nodes: selected },+ },+ });+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.evidence.branch).toBe(+ `${alias.toUpperCase()}/Feature/Parser`,+ );+ expect(parsed.findings[0]!.evidence.source_data).toEqual(record);+ }+ },+);++test("repository display names do not remove literal branch components", async () => {+ const record = {+ ...sast,+ repository: { id: repository.id, name: "project" },+ repositoryBranch: {+ ...sast.repositoryBranch,+ name: "project/component/Feature",+ },+ };+ const parsed = await parse({+ data: {+ sastFindings: { nodes: [record] },+ versionControlResources: {+ nodes: [+ {+ ...inventoryNode("GITHUB", repositoryUrl),+ repository: {+ ...repository,+ url: repositoryUrl,+ name: "project/component",+ },+ },+ ],+ },+ },+ });+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.evidence.branch).toBe("project/component/Feature");+});++for (const kind of ["sast", "secret", "iac"] as const) {+ test.each([false, true])(+ kind ++ " GITHUB inventory maps custom-host URLs and branches (supplied URL: %j)",+ async (withSourceUrl) => {+ const sourceUrl = "https://GITHUB.EXAMPLE.TEST/Example/PROJECT.git/";+ const sourceRepository = {+ id: repository.id,+ ...(withSourceUrl ? { url: sourceUrl } : {}),+ };+ const branch = {+ id: "wiz-branch",+ name: "EXAMPLE/PROJECT/Feature/Parser/More",+ };+ const record =+ kind === "secret"+ ? {+ ...secret,+ resource: {+ ...secret.resource,+ name: branch.name,+ typedProperties: { repository: sourceRepository },+ },+ }+ : {+ ...(kind === "sast" ? sast : iac),+ repository: sourceRepository,+ [kind === "sast" ? "repositoryBranch" : "branch"]: branch,+ };+ const root = {+ sast: "sastFindings",+ secret: "secretInstances",+ iac: "iacFindings",+ }[kind];+ const f = await cloudFixture({+ data: {+ [root]: { nodes: [record] },+ versionControlResources: {+ nodes: [+ {+ ...inventoryNode("GITHUB"),+ type: withSourceUrl ? "REPOSITORY_BRANCH" : "CI_WORKFLOW",+ },+ ],+ },+ },+ });+ f.destination.url = enterpriseUrl;+ const publication = await prepareExternalPublication(+ f.file,+ { ...f.options, repository: f.destination.id },+ f.deps,+ );+ expect((await publication.publish()).verified).toBe(1);+ const evidence = f.posts[0]!.items[0]!.evidence;+ expect(evidence.branch).toBe(branch.name);+ expect(evidence.details!.repository).toEqual({+ id: repository.id,+ name: null,+ url: withSourceUrl ? sourceUrl : enterpriseUrl,+ });+ expect(evidence.source_data).toEqual(record);+ },+ );+}++test.each(["GITLAB", "github"])(+ "inventory platform %s does not imply GitHub custom-host matching",+ async (platform) => {+ const record = {+ ...sast,+ repository: {+ ...repository,+ url: "https://github.example.test/Example/Project",+ },+ };+ const parsed = await parse({+ data: {+ sastFindings: { nodes: [record] },+ versionControlResources: { nodes: [inventoryNode(platform)] },+ },+ });+ expect(parsed.findings).toEqual([]);+ expect(parsed.excluded[0]!.reason).toContain("conflicting repository URLs");+ },+);++test.each([0, 1, 2])(+ "GITHUB inventory duplicate matching is independent of hint position %j",+ async (githubPosition) => {+ const urls = [+ "https://github.example.test/Example/Project.git/",+ "https://github.example.test/EXAMPLE/PROJECT",+ enterpriseUrl,+ ];+ const nodes = urls.map((url, index) =>+ inventoryNode(index === githubPosition ? "GITHUB" : undefined, url),+ );+ const record = {+ ...sast,+ repository: { id: repository.id },+ repositoryBranch: {+ id: "wiz-branch",+ name: "EXAMPLE/PROJECT/Feature/Parser",+ },+ };+ const parsed = await parse({+ data: {+ sastFindings: { nodes: [record] },+ versionControlResources: { nodes },+ },+ });+ expect(parsed.excluded).toEqual([]);+ expect(parsed.findings[0]!.evidence.branch).toBe(+ record.repositoryBranch.name,+ );+ expect(parsed.findings[0]!.evidence.details!.repository).toEqual({+ id: repository.id,+ name: null,+ url: urls[1]!,+ });+ expect(parsed.findings[0]!.evidence.source_data).toEqual(record);+ },+);++test("equivalent inventory rows preserve publication identity when reordered", async () => {+ const record = { ...sast, repository: { id: repository.id } };+ const nodes = [+ {+ ...inventoryNode("GITHUB"),+ repository: {+ ...repository,+ name: "Example/Project",+ url: "https://github.com/Example/Project.git",+ },+ },+ {+ ...inventoryNode(undefined),+ repository: { ...repository, url: repositoryUrl },+ },+ ];+ const payload = {+ data: {+ sastFindings: { nodes: [record] },+ versionControlResources: { nodes },+ },+ };+ const f = await cloudFixture(payload);+ const prepared = await prepareExternalPublication(f.file, f.options, f.deps);+ f.state.failReadback = true;+ await expect(prepared.publish()).rejects.toBeInstanceOf(+ ExternalPublicationError,+ );+ nodes.reverse();+ await writeFile(f.file, JSON.stringify(payload));+ const retry = await prepareExternalPublication(f.file, f.options, f.deps);+ expect(retry.preview.findings).toEqual(prepared.preview.findings);+ expect(retry.preview.findings[0]!.evidence.source_data).toEqual(record);+ expect(retry.preview.resumed).toBe(true);+ expect(retry.preview.requests[0]!.request_id).toBe(+ prepared.preview.requests[0]!.request_id,+ );+ f.state.failReadback = false;+ expect((await retry.publish()).verified).toBe(1);+ expect(f.posts).toHaveLength(1);+});++test.each(["raw", "normalized"])(+ "publication identity retains explicit branch changes (%s)",+ async (kind) => {+ const record = structuredClone(sast);+ const normalized = {+ source_finding_id: "explicit-branch",+ evidence: {+ title: "Synthetic finding",+ severity: "high",+ branch: "main",+ source_data: { id: "unchanged-source" },+ },+ };+ const input =+ kind === "raw" ? envelope("sastFindings", [record]) : [normalized];+ const f = await cloudFixture(input);+ const original = await prepareExternalPublication(+ f.file,+ f.options,+ f.deps,+ );+ f.state.failReadback = true;+ await expect(original.publish()).rejects.toBeInstanceOf(+ ExternalPublicationError,+ );+ if (kind === "raw")+ record.repositoryBranch.name = "example/project/changed";+ else normalized.evidence.branch = "changed";+ await writeFile(f.file, JSON.stringify(input));+ const changed = await prepareExternalPublication(f.file, f.options, f.deps);+ expect(changed.preview.resumed).toBe(false);+ expect(changed.preview.requests[0]!.request_id).not.toBe(+ original.preview.requests[0]!.request_id,+ );+ expect(changed.preview.findings[0]!.evidence.branch).toBe(+ kind === "raw" ? "example/project/changed" : "changed",+ );+ },+);++test.each([+ "resume",+ "reset",+ "coverage",+ "rebind",+ "prepend",+ "excluded",+ "qualifier",+])(+ "inventory normalization upgrades saved immutable requests and receipts (%s)",+ async (scenario) => {+ const record = {+ ...sast,+ vendorMetadata: { z: 1, ä: 2 },+ repository: { id: repository.id },+ ...(scenario === "qualifier"+ ? {+ repositoryBranch: {+ ...sast.repositoryBranch,+ name: "project/component/Feature",+ },+ }+ : {}),+ };+ const selected =+ scenario === "coverage"+ ? [+ { ...record, id: "already-ready", repository },+ { ...record, id: "newly-ready" },+ ]+ : scenario === "excluded"+ ? [+ record,+ {+ source_finding_id: "sast:occurrence-1",+ evidence: { title: "Excluded input", severity: "invalid" },+ },+ ]+ : [record];+ const nodes = [+ {+ ...inventoryNode("GITHUB"),+ repository: {+ ...repository,+ name:+ scenario === "qualifier" ? "project/component" : "Example/Project",+ url:+ scenario === "qualifier"+ ? repositoryUrl+ : "https://github.com/Example/Project.git",+ },+ },+ {+ ...inventoryNode("GITHUB"),+ repository: {+ ...repository,+ name:+ scenario === "coverage"+ ? "z".repeat(513)+ : scenario === "qualifier"+ ? "project"+ : repository.name,+ url: repositoryUrl,+ },+ },+ ];+ const payload = {+ data: {+ sastFindings: { nodes: selected },+ versionControlResources: { nodes },+ },+ };+ // The earlier mapper used the last inventory row. This single-row export+ // stages exactly that historical evidence with real publication receipts.+ const f = await cloudFixture({+ data: { ...payload.data, versionControlResources: { nodes: [nodes[1]] } },+ });+ const deps = {+ ...f.deps,+ environment: {+ ...f.environment,+ CODEX_SECURITY_CLOUD_BASE_URL: DEFAULT_CLOUD_BASE_URL,+ },+ };+ // Stage the old branch projection explicitly; new imports retain names.+ const historical = (await readVendorFindingsForPublication(f.file)).legacy;+ expect(historical.findings[0]!.evidence.branch).toBe(+ scenario === "qualifier" ? "component/Feature" : "feature/parser",+ );+ await writeFile(f.file, JSON.stringify(historical.findings));+ const original = await prepareExternalPublication(f.file, f.options, deps);+ f.state.failReadback = true;+ let originalPath = "";+ try {+ await original.publish();+ } catch (error) {+ expect(error).toBeInstanceOf(ExternalPublicationError);+ originalPath = (error as ExternalPublicationError).result+ .savedSubmission!;+ }+ const saved = JSON.parse(await readFile(originalPath, "utf8"));+ delete saved.inputProjection;+ await writeFile(originalPath, JSON.stringify(saved));+ expect(saved.receipts).toHaveLength(1);+ const identity = [+ original.preview.accountId,+ original.preview.destination.id,+ original.preview.destination.repo_connector_id,+ original.preview.source,+ original.preview.findings,+ ];+ // Reproduce the previous checkpoint encoding, before code-unit key ordering.+ const oldKey = hash(+ "sha256",+ JSON.stringify(identity, (_key, child) =>+ child !== null && typeof child === "object" && !Array.isArray(child)+ ? Object.fromEntries(+ Object.keys(child)+ .sort((left, right) => left.localeCompare(right))+ .map((key) => [key, child[key]]),+ )+ : child,+ ),+ );+ const oldPath = join(+ f.environment.CODEX_SECURITY_STATE_DIR,+ "external-finding-publications",+ `${oldKey}.pending.json`,+ );+ if (oldPath !== originalPath) await rename(originalPath, oldPath);+ await writeFile(f.file, JSON.stringify(payload));+ if (scenario === "coverage") {+ expect((await readVendorFindings(f.file)).findings).toHaveLength(2);+ await expect(+ prepareExternalPublication(f.file, f.options, deps),+ ).rejects.toThrow("selects different findings");+ expect(JSON.parse(await readFile(oldPath, "utf8"))).toEqual(saved);+ expect(f.posts).toHaveLength(1);+ return;+ }+ if (scenario === "reset") {+ f.destination.reset_marker = "generation-2";+ await expect(+ prepareExternalPublication(f.file, f.options, deps),+ ).rejects.toThrow("saved request was retired");+ await expect(readFile(oldPath, "utf8")).rejects.toMatchObject({+ code: "ENOENT",+ });+ expect(f.posts).toHaveLength(1);+ return;+ }+ const upgraded = await prepareExternalPublication(f.file, f.options, deps);+ expect(upgraded.preview.resumed).toBe(true);+ expect(upgraded.preview.requests).toEqual(original.preview.requests);+ expect(upgraded.preview.findings).toEqual(original.preview.findings);+ let migratedPath = "";+ try {+ await upgraded.publish();+ } catch (error) {+ expect(error).toBeInstanceOf(ExternalPublicationError);+ migratedPath = (error as ExternalPublicationError).result+ .savedSubmission!;+ }+ const migrated = await readFile(migratedPath, "utf8");+ const migratedData = JSON.parse(migrated);+ expect(migratedData.requests).toEqual(saved.requests);+ expect(migratedData.receipts).toEqual(saved.receipts);+ if (scenario !== "prepend" && scenario !== "excluded") nodes.reverse();+ await writeFile(f.file, JSON.stringify(payload));+ const reordered = await prepareExternalPublication(f.file, f.options, deps);+ expect(reordered.preview.resumed).toBe(true);+ expect(reordered.preview.requests).toEqual(original.preview.requests);+ migratedData.requests[0].items[0].evidence.description =+ "Modified saved evidence";+ await writeFile(migratedPath, JSON.stringify(migratedData));+ await expect(+ prepareExternalPublication(f.file, f.options, deps),+ ).rejects.toThrow("Saved import evidence");+ await writeFile(migratedPath, migrated);+ const incomplete = JSON.parse(migrated);+ delete incomplete.inputProjection.savedEvidenceDigest;+ await writeFile(migratedPath, JSON.stringify(incomplete));+ await expect(+ prepareExternalPublication(f.file, f.options, deps),+ ).rejects.toThrow("Saved import evidence");+ await writeFile(migratedPath, migrated);+ let replay = reordered;+ if (["rebind", "prepend", "excluded"].includes(scenario)) {+ nodes.unshift({+ ...nodes[1]!,+ repository: { ...nodes[1]!.repository, name: "EXAMPLE/PROJECT" },+ });+ await writeFile(f.file, JSON.stringify(payload));+ replay = await prepareExternalPublication(f.file, f.options, deps);+ expect(replay.preview.resumed).toBe(true);+ expect(replay.preview.requests).toEqual(original.preview.requests);+ expect(replay.preview.findings).toEqual(original.preview.findings);+ }+ const newer = f.reports.get("sast:occurrence-1")!;+ newer.version += 1;+ newer.evidence.description = "Newer Cloud evidence";+ f.state.failReadback = false;+ expect((await replay.publish()).verified).toBe(1);+ expect(f.posts).toHaveLength(1);+ expect(f.reports.get("sast:occurrence-1")!.evidence.description).toBe(+ "Newer Cloud evidence",+ );+ },+);++test.each([+ ["GITHUB", "GITLAB"],+ ["GITLAB", "GITHUB"],+])("inventory platform conflicts reject %s before %s", async (first, last) => {+ await expect(+ parse({+ data: {+ sastFindings: { nodes: [sast] },+ versionControlResources: {+ nodes: [first, undefined, last].map((platform) =>+ inventoryNode(platform),+ ),+ },+ },+ }),+ ).rejects.toThrow("conflicting platforms");+});++test.each([undefined, "GITLAB"])(+ "inventory duplicate URLs stay strict without GITHUB provenance: %j",+ async (platform) => {+ await expect(+ parse({+ data: {+ sastFindings: { nodes: [sast] },+ versionControlResources: {+ nodes: [+ inventoryNode(+ platform,+ "https://github.example.test/Example/Project",+ ),+ inventoryNode(platform),+ ],+ },+ },+ }),+ ).rejects.toThrow("conflicting URLs");+ },+);++test("GITHUB inventory provenance does not permit a different repository URL", async () => {+ await expect(+ parse({+ data: {+ sastFindings: { nodes: [sast] },+ versionControlResources: {+ nodes: [+ inventoryNode("GITHUB"),+ inventoryNode(+ "GITHUB",+ "https://github.example.test/example/other",+ ),+ ],+ },+ },+ }),+ ).rejects.toThrow("conflicting URLs");+});+test("concurrent legacy inventory resumers retain the acknowledged request after migration finishes", async () => {+ const name =+ "concurrent legacy inventory resumers retain the acknowledged request after migration finishes";+ const { runTestInSubprocess } = await import("./support/test-subprocess.js");+ if (runTestInSubprocess(import.meta.filename, name)) return;+ const fs = await import("node:fs/promises");+ const { spyOn } = await import("bun:test");+ const record = { ...sast, repository: { id: repository.id } };+ const nodes = [+ {+ ...inventoryNode("GITHUB"),+ repository: {+ ...repository,+ name: "Example/Project",+ url: "https://github.com/Example/Project.git",+ },+ },+ {+ ...inventoryNode("GITHUB"),+ repository: { ...repository, url: repositoryUrl },+ },+ ];+ const payload = {+ data: {+ sastFindings: { nodes: [record] },+ versionControlResources: { nodes },+ },+ };+ const f = await cloudFixture({+ data: { ...payload.data, versionControlResources: { nodes: [nodes[1]] } },+ });+ const deps = {+ ...f.deps,+ environment: {+ ...f.environment,+ CODEX_SECURITY_CLOUD_BASE_URL: DEFAULT_CLOUD_BASE_URL,+ },+ };+ const historical = await readVendorFindingsForPublication(f.file);+ await writeFile(f.file, JSON.stringify(historical.legacy.findings));+ const original = await prepareExternalPublication(f.file, f.options, deps);+ f.state.failReadback = true;+ let originalPath = "";+ try {+ await original.publish();+ } catch (error) {+ expect(error).toBeInstanceOf(ExternalPublicationError);+ originalPath = (error as ExternalPublicationError).result.savedSubmission!;+ }+ const saved = JSON.parse(await readFile(originalPath, "utf8"));+ expect(saved.receipts).toHaveLength(1);+ const identity = [+ original.preview.accountId,+ original.preview.destination.id,+ original.preview.destination.repo_connector_id,+ original.preview.source,+ ];+ const encode = (value: unknown, legacy: boolean) =>+ JSON.stringify(value, (_key, child) =>+ child !== null && typeof child === "object" && !Array.isArray(child)+ ? Object.fromEntries(+ Object.keys(child)+ .sort(+ legacy ? (left, right) => left.localeCompare(right) : undefined,+ )+ .map((key) => [key, child[key]]),+ )+ : child,+ );+ const directory = join(+ f.environment.CODEX_SECURITY_STATE_DIR,+ "external-finding-publications",+ );+ saved.inputProjection.inputDigest = hash(+ "sha256",+ encode(historical.legacyIdentity, false),+ );+ await writeFile(originalPath, JSON.stringify(saved));+ const oldKey = hash(+ "sha256",+ encode([...identity, original.preview.findings], true),+ );+ const oldPath = join(directory, `${oldKey}.pending.json`);+ if (oldPath !== originalPath) await rename(originalPath, oldPath);+ await writeFile(f.file, JSON.stringify(payload));+ const { currentIdentity } = await readVendorFindingsForPublication(f.file);+ const key = hash("sha256", encode([...identity, currentIdentity], false));+ const pendingPath = join(directory, `${key}.pending.json`);+ const lockPath = join(directory, `${key}.lock.sqlite`);+ expect(pendingPath).not.toBe(oldPath);+ const firstAtLock = Promise.withResolvers<void>();+ const secondAtLock = Promise.withResolvers<void>();+ const releaseSecond = Promise.withResolvers<void>();+ const originalLstat = fs.lstat;+ let lockEntries = 0;+ const metadata = spyOn(fs, "lstat").mockImplementation((async (+ ...args: Parameters<typeof fs.lstat>+ ) => {+ if (String(args[0]) === lockPath) {+ lockEntries += 1;+ if (lockEntries === 1) {+ firstAtLock.resolve();+ await secondAtLock.promise;+ } else if (lockEntries === 2) {+ secondAtLock.resolve();+ await releaseSecond.promise;+ }+ }+ return await originalLstat(...args);+ }) as typeof fs.lstat);+ let first: ReturnType<typeof prepareExternalPublication> | undefined;+ let second: ReturnType<typeof prepareExternalPublication> | undefined;+ try {+ first = prepareExternalPublication(f.file, f.options, deps);+ await firstAtLock.promise;+ second = prepareExternalPublication(f.file, f.options, deps);+ await secondAtLock.promise;+ const leading = await first;+ expect(leading.preview.resumed).toBe(true);+ expect(leading.preview.requests).toEqual(saved.requests);+ expect(JSON.parse(await readFile(pendingPath, "utf8")).receipts).toEqual(+ saved.receipts,+ );+ f.state.failReadback = false;+ expect((await leading.publish()).verified).toBe(1);+ await expect(readFile(pendingPath, "utf8")).rejects.toMatchObject({+ code: "ENOENT",+ });+ await expect(readFile(oldPath, "utf8")).rejects.toMatchObject({+ code: "ENOENT",+ });+ const newer = structuredClone(f.reports.get("sast:occurrence-1")!);+ newer.version += 1;+ newer.evidence.description =+ "Newer Cloud evidence after the first resumer completed";+ f.reports.set("sast:occurrence-1", newer);+ releaseSecond.resolve();+ const trailing = await second;+ const result = await trailing.publish();+ expect(f.posts).toHaveLength(1);+ expect(trailing.preview.resumed).toBe(true);+ expect(trailing.preview.requests).toEqual(saved.requests);+ expect(result.receipts).toEqual(saved.receipts);+ expect(result.verified).toBe(1);+ expect(f.reports.get("sast:occurrence-1")).toEqual(newer);+ } finally {+ secondAtLock.resolve();+ releaseSecond.resolve();+ await Promise.allSettled(+ [first, second].filter((value) => value !== undefined),+ );+ metadata.mockRestore();+ }+});++test("resume preview is derived from the saved upload evidence", async () => {+ const payload = {+ data: {+ sastFindings: { nodes: [{ ...sast, repository: { id: repository.id } }] },+ versionControlResources: {+ nodes: [+ {+ ...inventoryNode("GITHUB"),+ repository: {+ ...repository,+ url: repositoryUrl,+ name: "original-display-name",+ },+ },+ ],+ },+ },+ };+ const f = await cloudFixture(payload);+ const original = await prepareExternalPublication(f.file, f.options, f.deps);+ f.state.failReadback = true;+ await expect(original.publish()).rejects.toThrow("Readback unavailable");+ payload.data.versionControlResources.nodes[0]!.repository.name =+ "updated-display-name";+ await writeFile(f.file, JSON.stringify(payload));+ const resumed = await prepareExternalPublication(f.file, f.options, f.deps);+ expect(resumed.preview.resumed).toBe(true);+ expect(resumed.preview.requests).toEqual(original.preview.requests);+ expect(resumed.preview.findings[0]!.evidence).toEqual(+ resumed.preview.requests[0]!.items[0]!.evidence,+ );+});