@openai/codex-security 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -9
- package/_bundled_plugin/.mcp.json +1 -0
- package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
- package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
- package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
- package/_bundled_plugin/references/core-scan.md +2 -0
- package/_bundled_plugin/references/final-report.md +5 -1
- package/_bundled_plugin/references/investigation-time-budget.md +11 -0
- package/_bundled_plugin/references/sarif-adapter.md +1 -0
- package/_bundled_plugin/references/scan-prologue.md +2 -6
- package/_bundled_plugin/references/scan-runtime.md +15 -0
- package/_bundled_plugin/references/threat-model.md +2 -0
- package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +5 -1
- package/_bundled_plugin/scripts/deep_scan_workbench.py +7 -0
- package/_bundled_plugin/scripts/finalize_scan_contract.py +80 -43
- package/_bundled_plugin/scripts/finding_preview.py +5 -3
- package/_bundled_plugin/scripts/generate_rank_input.py +1 -0
- package/_bundled_plugin/scripts/launch_codex_security_mcp +39 -4
- package/_bundled_plugin/scripts/snapshot_sqlite.py +7 -0
- package/_bundled_plugin/scripts/windows_scan_local_files.py +43 -1
- package/_bundled_plugin/scripts/workbench_cli.py +0 -3
- package/_bundled_plugin/scripts/workbench_constants.py +4 -0
- package/_bundled_plugin/scripts/workbench_db.py +56 -33
- package/_bundled_plugin/scripts/workbench_progress.py +0 -50
- package/_bundled_plugin/scripts/workbench_scan_history.py +3 -2
- package/_bundled_plugin/scripts/workbench_scan_start.py +12 -4
- package/_bundled_plugin/scripts/workbench_scan_usage.py +190 -30
- package/_bundled_plugin/scripts/workbench_schema.py +1 -1
- package/_bundled_plugin/scripts/workbench_source_excerpt.py +74 -51
- package/_bundled_plugin/scripts/workbench_source_scopes.py +388 -0
- package/_bundled_plugin/scripts/workbench_target.py +7 -5
- package/_bundled_plugin/scripts/workbench_validation.py +37 -1
- package/_bundled_plugin/shared/workbench-history-repairs.json +19 -0
- package/_bundled_plugin/shared/workbench-migrations.json +5 -0
- package/_bundled_plugin/skills/deep-security-scan/SKILL.md +1 -1
- package/_bundled_plugin/skills/security-diff-scan/SKILL.md +4 -2
- package/_bundled_plugin/skills/security-scan/SKILL.md +3 -1
- package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +2 -2
- package/dist/api.d.ts +3 -2
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +54 -36
- package/dist/api.js.map +1 -1
- package/dist/artifact-export.d.ts +2 -1
- package/dist/artifact-export.d.ts.map +1 -1
- package/dist/artifact-export.js +38 -23
- package/dist/artifact-export.js.map +1 -1
- package/dist/classify-severity-records.d.ts +76 -0
- package/dist/classify-severity-records.d.ts.map +1 -0
- package/dist/classify-severity-records.js +141 -0
- package/dist/classify-severity-records.js.map +1 -0
- package/dist/classify-severity.d.ts +1 -23
- package/dist/classify-severity.d.ts.map +1 -1
- package/dist/classify-severity.js +3 -24
- package/dist/classify-severity.js.map +1 -1
- package/dist/cli-help.d.ts.map +1 -1
- package/dist/cli-help.js +2 -0
- package/dist/cli-help.js.map +1 -1
- package/dist/cli.d.ts +4 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +136 -147
- package/dist/cli.js.map +1 -1
- package/dist/cloud-publish.js +1 -1
- package/dist/cloud-publish.js.map +1 -1
- package/dist/codex-sdk-environment.js +1 -1
- package/dist/codex-sdk-environment.js.map +1 -1
- package/dist/config.d.ts +12 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +10 -4
- package/dist/config.js.map +1 -1
- package/dist/contract.d.ts +5 -0
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js +65 -17
- package/dist/contract.js.map +1 -1
- package/dist/cost-model.d.ts.map +1 -1
- package/dist/cost-model.js +7 -2
- package/dist/cost-model.js.map +1 -1
- package/dist/custom-validation-prompt.js +3 -3
- package/dist/custom-validation-prompt.js.map +1 -1
- package/dist/deduplication/deduplication-prompts.d.ts +1 -1
- package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
- package/dist/deduplication/deduplication-prompts.js +2 -2
- package/dist/deduplication/deduplication-prompts.js.map +1 -1
- package/dist/deduplication/records.js +1 -1
- package/dist/deduplication/records.js.map +1 -1
- package/dist/deduplication/scan.d.ts.map +1 -1
- package/dist/deduplication/scan.js +10 -9
- package/dist/deduplication/scan.js.map +1 -1
- package/dist/deep-config.d.ts +4 -1
- package/dist/deep-config.d.ts.map +1 -1
- package/dist/deep-config.js +21 -1
- package/dist/deep-config.js.map +1 -1
- package/dist/findings-import.d.ts +1 -1
- package/dist/findings-import.d.ts.map +1 -1
- package/dist/findings-import.js +3 -3
- package/dist/findings-import.js.map +1 -1
- package/dist/git-remote.d.ts +10 -0
- package/dist/git-remote.d.ts.map +1 -0
- package/dist/git-remote.js +24 -0
- package/dist/git-remote.js.map +1 -0
- package/dist/github.d.ts.map +1 -1
- package/dist/github.js +5 -7
- package/dist/github.js.map +1 -1
- package/dist/host-protocol.js +1 -1
- package/dist/host-protocol.js.map +1 -1
- package/dist/host-records-protocol.d.ts +15 -0
- package/dist/host-records-protocol.d.ts.map +1 -0
- package/dist/host-records-protocol.js +15 -0
- package/dist/host-records-protocol.js.map +1 -0
- package/dist/hosted-scan.d.ts +1 -6
- package/dist/hosted-scan.d.ts.map +1 -1
- package/dist/hosted-scan.js +2 -2
- package/dist/hosted-scan.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/knowledge-base.d.ts.map +1 -1
- package/dist/knowledge-base.js +87 -7
- package/dist/knowledge-base.js.map +1 -1
- package/dist/multiscan.d.ts.map +1 -1
- package/dist/multiscan.js +62 -28
- package/dist/multiscan.js.map +1 -1
- package/dist/patch-publication.d.ts +26 -0
- package/dist/patch-publication.d.ts.map +1 -0
- package/dist/patch-publication.js +105 -0
- package/dist/patch-publication.js.map +1 -0
- package/dist/patch-tui.d.ts.map +1 -1
- package/dist/patch-tui.js +4 -1
- package/dist/patch-tui.js.map +1 -1
- package/dist/project-config-schema.d.ts +2 -0
- package/dist/project-config-schema.d.ts.map +1 -1
- package/dist/project-config-schema.js +1 -0
- package/dist/project-config-schema.js.map +1 -1
- package/dist/project-config.d.ts +1 -0
- package/dist/project-config.d.ts.map +1 -1
- package/dist/project-config.js +16 -6
- package/dist/project-config.js.map +1 -1
- package/dist/publication.d.ts.map +1 -1
- package/dist/publication.js +135 -19
- package/dist/publication.js.map +1 -1
- package/dist/publish.d.ts.map +1 -1
- package/dist/publish.js +39 -25
- package/dist/publish.js.map +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +83 -22
- package/dist/runtime.js.map +1 -1
- package/dist/scan-settings.d.ts +1 -0
- package/dist/scan-settings.d.ts.map +1 -1
- package/dist/scan-settings.js +7 -1
- package/dist/scan-settings.js.map +1 -1
- package/dist/scan-time-budget.d.ts +9 -0
- package/dist/scan-time-budget.d.ts.map +1 -0
- package/dist/scan-time-budget.js +16 -0
- package/dist/scan-time-budget.js.map +1 -0
- package/dist/severity-review.d.ts +29 -0
- package/dist/severity-review.d.ts.map +1 -0
- package/dist/severity-review.js +47 -0
- package/dist/severity-review.js.map +1 -0
- package/dist/validation-records.d.ts +38 -0
- package/dist/validation-records.d.ts.map +1 -0
- package/dist/validation-records.js +76 -0
- package/dist/validation-records.js.map +1 -0
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +4 -2
- package/dist/version.js.map +1 -1
- package/dist/worker-progress.d.ts +2 -6
- package/dist/worker-progress.d.ts.map +1 -1
- package/dist/worker-progress.js +1 -43
- package/dist/worker-progress.js.map +1 -1
- package/docs/classify-severity-records.md +89 -0
- package/docs/cli.md +269 -33
- package/docs/validate-records.md +69 -0
- package/package.json +12 -10
- package/schemas/project-config.schema.json +7 -1
- package/_bundled_plugin/preflight/capability-profiles.toml +0 -76
- package/_bundled_plugin/references/config-preflight.md +0 -93
- package/_bundled_plugin/references/desktop-config-preflight.md +0 -11
- package/_bundled_plugin/scripts/config_preflight.py +0 -911
package/dist/cloud-publish.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
import { z } from "
|
|
4
|
+
import { z } from "zod";
|
|
5
5
|
import { parse as parseToml } from "smol-toml";
|
|
6
6
|
import { loadContract, sha256Text as sha256 } from "./contract.js";
|
|
7
7
|
import { AuthenticationRequiredError, CodexSecurityError, errorMessage, } from "./errors.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloud-publish.js","sourceRoot":"","sources":["../src/cloud-publish.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,UAAU,IAAI,MAAM,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,YAAY,GACb,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,aAAa,EACb,oBAAoB,EACpB,aAAa,EACb,gBAAgB,GACjB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,iBAAiB,EACjB,0CAA0C,EAC1C,2BAA2B,EAC3B,qCAAqC,EACrC,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,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/promises\";\nimport { join } from \"node:path\";\nimport { z } from \"incur\";\nimport { parse as parseToml } from \"smol-toml\";\nimport { loadContract, sha256Text as sha256 } from \"./contract.js\";\nimport {\n AuthenticationRequiredError,\n CodexSecurityError,\n errorMessage,\n} from \"./errors.js\";\nimport type { Finding, ScanManifest } from \"./models.js\";\nimport {\n CSV_TARGET_ID,\n bindImportedFindings,\n csvRowFinding,\n parseFindingsCsv,\n} from \"./findings-import.js\";\nimport {\n bundledPluginRoot,\n codexSecurityCredentialAllowsAmbientImport,\n codexSecurityCredentialHome,\n codexSecurityHasStoredFileCredentials,\n expandHome,\n} from \"./runtime.js\";\nimport { VERSION } from \"./version.js\";\n\nconst CLOUD_PUBLISH_URL =\n \"https://chatgpt.com/backend-api/aardvark/cli/findings\";\nconst CHATGPT_LOGIN_REQUIRED =\n \"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.\";\n\nconst credentialsSchema = z.object({\n auth_mode: z.literal(\"chatgpt\").optional(),\n OPENAI_API_KEY: z.null().optional(),\n tokens: z.object({\n access_token: z.string().trim().min(1),\n account_id: z.string().trim().min(1),\n }),\n});\n\nconst receiptSchema = z.object({\n status: z.literal(\"accepted\"),\n finding_ids: z.array(z.string().min(1)),\n finding_count: z.number().int().positive(),\n});\n\nexport interface CloudPublicationResult {\n scanId: string;\n findingIds: string[];\n findingCount: number;\n dryRun?: true;\n findings?: Finding[];\n}\n\ninterface CloudPublicationDependencies {\n environment?: NodeJS.ProcessEnv;\n fetch?: (url: string, options: RequestInit) => Promise<Response>;\n signal?: AbortSignal;\n dryRun?: boolean;\n}\n\nexport async function publishScanToCloud(\n scanDirectory: string,\n dependencies: CloudPublicationDependencies & {\n expectedScanId?: string;\n } = {},\n): Promise<CloudPublicationResult> {\n const { manifest, findings } = await loadContract(scanDirectory, {\n pluginRoot: await bundledPluginRoot(),\n signal: dependencies.signal,\n expectedScanId: dependencies.expectedScanId,\n });\n if (findings.findings.length === 0) {\n throw new CodexSecurityError(\n \"The completed scan has no findings to publish.\",\n );\n }\n return publishCloudPayload(manifest.scan, findings.findings, dependencies);\n}\n\nexport async function publishFindingsCsvToCloud(\n csvPath: string,\n dependencies: CloudPublicationDependencies = {},\n): Promise<CloudPublicationResult> {\n dependencies.signal?.throwIfAborted();\n let source: string;\n try {\n source = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n await readFile(csvPath),\n );\n } catch (error) {\n throw new CodexSecurityError(\n `Could not read findings CSV. ${errorMessage(error)}`,\n { cause: error },\n );\n }\n dependencies.signal?.throwIfAborted();\n const rows = parseFindingsCsv(source);\n if (rows.length === 0) {\n throw new CodexSecurityError(\n \"Findings CSV must contain at least one finding.\",\n );\n }\n const digest = sha256(source);\n const scanId = `scan_csv_${sha256(\n [\"codex-security-csv-import/v1\", VERSION, source].join(\"\\0\"),\n ).slice(0, 24)}`;\n const findings = bindImportedFindings(\n rows.map(csvRowFinding),\n \"csv\",\n scanId,\n CSV_TARGET_ID,\n );\n const timestamp = \"1970-01-01T00:00:00.000Z\";\n const findingsDocument = JSON.stringify({\n documentType: \"codex-security.findings\",\n schemaVersion: \"1.0\",\n scanId,\n findings,\n });\n const coverageDocument = JSON.stringify({\n documentType: \"codex-security.coverage\",\n schemaVersion: \"1.0\",\n scanId,\n mode: \"repository\",\n inventoryStrategy: \"custom\",\n includePaths: [\".\"],\n excludePaths: [],\n surfaces: findings.map((finding) => ({\n id: finding.occurrenceId,\n label: finding.title,\n disposition: \"reported\",\n receiptRefs: [],\n })),\n explicitExclusions: [],\n deferred: [],\n });\n const scan: ScanManifest[\"scan\"] = {\n id: scanId,\n producer: { name: \"codex-security-cli\", version: VERSION },\n status: \"completed\",\n startedAt: timestamp,\n completedAt: timestamp,\n sealedAt: timestamp,\n target: {\n kind: \"directory_snapshot\",\n targetId: CSV_TARGET_ID,\n displayName: \"findings.csv\",\n snapshotDigest: `codex-security-snapshot/v1:sha256:${digest}`,\n },\n scope: {\n includePaths: [\".\"],\n excludePaths: [],\n summary: \"Findings imported from a Codex Security CSV export.\",\n },\n coverageRef: \"coverage.json\",\n findingsRef: \"findings.json\",\n artifacts: [\n {\n path: \"findings.json\",\n sha256: sha256(findingsDocument),\n mediaType: \"application/json\",\n },\n {\n path: \"coverage.json\",\n sha256: sha256(coverageDocument),\n mediaType: \"application/json\",\n },\n {\n path: \"findings.csv\",\n sha256: digest,\n mediaType: \"text/csv\",\n },\n ],\n };\n return publishCloudPayload(scan, findings, dependencies);\n}\n\nasync function publishCloudPayload(\n scan: ScanManifest[\"scan\"],\n findings: Finding[],\n dependencies: CloudPublicationDependencies,\n): Promise<CloudPublicationResult> {\n dependencies.signal?.throwIfAborted();\n if (dependencies.dryRun) {\n return {\n scanId: scan.id,\n findingIds: [],\n findingCount: findings.length,\n dryRun: true,\n findings,\n };\n }\n const credentials = await readCloudCredentials(\n dependencies.environment ?? process.env,\n );\n const publishUrl =\n dependencies.environment?.[\"CODEX_SECURITY_CLOUD_PUBLISH_URL\"]?.trim() ||\n CLOUD_PUBLISH_URL;\n const timeout = AbortSignal.timeout(30_000);\n const signal = dependencies.signal\n ? AbortSignal.any([dependencies.signal, timeout])\n : timeout;\n let response: Response;\n try {\n response = await (dependencies.fetch ?? globalThis.fetch)(publishUrl, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credentials.access_token}`,\n \"ChatGPT-Account-ID\": credentials.account_id,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n },\n body: JSON.stringify({\n schemaVersion: \"1.0\",\n scan,\n findings,\n }),\n redirect: \"error\",\n signal,\n });\n } catch {\n dependencies.signal?.throwIfAborted();\n // A lost response does not establish whether the server accepted the POST.\n throw new CodexSecurityError(\n \"Cloud publication was not confirmed. The request was not retried; check whether it was accepted before submitting again.\",\n );\n }\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n const detail =\n response.status === 401\n ? \"Sign in with ChatGPT again before retrying.\"\n : response.status === 403\n ? \"The signed-in account is not authorized to publish to Cloud.\"\n : response.status === 404\n ? \"Cloud publication is not available for this account or deployment.\"\n : \"The request was not retried.\";\n throw new CodexSecurityError(\n `Cloud publication failed (HTTP ${response.status}). ${detail}`,\n );\n }\n const receipt = receiptSchema.safeParse(\n await response.json().catch(() => {\n dependencies.signal?.throwIfAborted();\n return undefined;\n }),\n );\n // Cloud assigns opaque IDs in request order, so they cannot be compared to\n // local finding IDs. The authenticated response must still preserve the\n // submitted count and return one distinct observation for each finding.\n if (\n (response.status !== 200 && response.status !== 201) ||\n !receipt.success ||\n receipt.data.finding_count !== findings.length ||\n receipt.data.finding_ids.length !== findings.length ||\n new Set(receipt.data.finding_ids).size !== receipt.data.finding_ids.length\n ) {\n throw new CodexSecurityError(\n \"Cloud publication returned an invalid acceptance receipt. Check whether the request was accepted before submitting again.\",\n );\n }\n return {\n scanId: scan.id,\n findingIds: receipt.data.finding_ids,\n findingCount: receipt.data.finding_count,\n };\n}\n\nasync function readCloudCredentials(environment: NodeJS.ProcessEnv) {\n const configuredHome = environment[\"CODEX_HOME\"];\n let home = expandHome(\n configuredHome?.trim() ? configuredHome : \"~/.codex\",\n environment,\n );\n let requireFileStorage = true;\n const dedicatedHome = codexSecurityCredentialHome(environment);\n if (existsSync(dedicatedHome)) {\n if (!(await codexSecurityCredentialAllowsAmbientImport(dedicatedHome))) {\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n }\n if (await codexSecurityHasStoredFileCredentials(dedicatedHome)) {\n home = dedicatedHome;\n requireFileStorage = false;\n } else if (existsSync(join(dedicatedHome, \"config.toml\"))) {\n // Do not silently switch accounts when the dedicated login may be in a keyring.\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n }\n }\n if (requireFileStorage) {\n let credentialStorage: unknown;\n try {\n credentialStorage = parseToml(\n await readFile(join(home, \"config.toml\"), \"utf8\"),\n )[\"cli_auth_credentials_store\"];\n } catch {\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n }\n // File presence is not proof that it is the active ambient login:\n // automatic or keyring storage can leave auth.json for another account.\n if (credentialStorage !== \"file\") {\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n }\n }\n try {\n const credentials = credentialsSchema.safeParse(\n JSON.parse(await readFile(join(home, \"auth.json\"), \"utf8\")),\n );\n if (credentials.success) return credentials.data.tokens;\n } catch {\n // Parsing and filesystem diagnostics must not reflect credential contents.\n }\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cloud-publish.js","sourceRoot":"","sources":["../src/cloud-publish.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,UAAU,IAAI,MAAM,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,YAAY,GACb,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,aAAa,EACb,oBAAoB,EACpB,aAAa,EACb,gBAAgB,GACjB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,iBAAiB,EACjB,0CAA0C,EAC1C,2BAA2B,EAC3B,qCAAqC,EACrC,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEvC,MAAM,iBAAiB,GACrB,uDAAuD,CAAC;AAC1D,MAAM,sBAAsB,GAC1B,qKAAqK,CAAC;AAExK,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACjC,SAAS,EAAE,CAAC,CAAC,OAAO,C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,EAAE,aAAa,CAAC,CAAC,EAAE,CAAC;YAC1D,gFAAgF;YAChF,MAAM,IAAI,2BAA2B,CAAC,sBAAsB,CAAC,CAAC;QAChE,CAAC;IACH,CAAC;IACD,IAAI,kBAAkB,EAAE,CAAC;QACvB,IAAI,iBAA0B,CAAC;QAC/B,IAAI,CAAC;YACH,iBAAiB,GAAG,SAAS,CAC3B,MAAM,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,aAAa,CAAC,EAAE,MAAM,CAAC,CAClD,CAAC,4BAA4B,CAAC,CAAC;QAClC,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,2BAA2B,CAAC,sBAAsB,CAAC,CAAC;QAChE,CAAC;QACD,kEAAkE;QAClE,wEAAwE;QACxE,IAAI,iBAAiB,KAAK,MAAM,EAAE,CAAC;YACjC,MAAM,IAAI,2BAA2B,CAAC,sBAAsB,CAAC,CAAC;QAChE,CAAC;IACH,CAAC;IACD,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,iBAAiB,CAAC,SAAS,CAC7C,IAAI,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,EAAE,MAAM,CAAC,CAAC,CAC5D,CAAC;QACF,IAAI,WAAW,CAAC,OAAO;YAAE,OAAO,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC;IAC1D,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;IAC7E,CAAC;IACD,MAAM,IAAI,2BAA2B,CAAC,sBAAsB,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\nimport { parse as parseToml } from \"smol-toml\";\nimport { loadContract, sha256Text as sha256 } from \"./contract.js\";\nimport {\n AuthenticationRequiredError,\n CodexSecurityError,\n errorMessage,\n} from \"./errors.js\";\nimport type { Finding, ScanManifest } from \"./models.js\";\nimport {\n CSV_TARGET_ID,\n bindImportedFindings,\n csvRowFinding,\n parseFindingsCsv,\n} from \"./findings-import.js\";\nimport {\n bundledPluginRoot,\n codexSecurityCredentialAllowsAmbientImport,\n codexSecurityCredentialHome,\n codexSecurityHasStoredFileCredentials,\n expandHome,\n} from \"./runtime.js\";\nimport { VERSION } from \"./version.js\";\n\nconst CLOUD_PUBLISH_URL =\n \"https://chatgpt.com/backend-api/aardvark/cli/findings\";\nconst CHATGPT_LOGIN_REQUIRED =\n \"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.\";\n\nconst credentialsSchema = z.object({\n auth_mode: z.literal(\"chatgpt\").optional(),\n OPENAI_API_KEY: z.null().optional(),\n tokens: z.object({\n access_token: z.string().trim().min(1),\n account_id: z.string().trim().min(1),\n }),\n});\n\nconst receiptSchema = z.object({\n status: z.literal(\"accepted\"),\n finding_ids: z.array(z.string().min(1)),\n finding_count: z.number().int().positive(),\n});\n\nexport interface CloudPublicationResult {\n scanId: string;\n findingIds: string[];\n findingCount: number;\n dryRun?: true;\n findings?: Finding[];\n}\n\ninterface CloudPublicationDependencies {\n environment?: NodeJS.ProcessEnv;\n fetch?: (url: string, options: RequestInit) => Promise<Response>;\n signal?: AbortSignal;\n dryRun?: boolean;\n}\n\nexport async function publishScanToCloud(\n scanDirectory: string,\n dependencies: CloudPublicationDependencies & {\n expectedScanId?: string;\n } = {},\n): Promise<CloudPublicationResult> {\n const { manifest, findings } = await loadContract(scanDirectory, {\n pluginRoot: await bundledPluginRoot(),\n signal: dependencies.signal,\n expectedScanId: dependencies.expectedScanId,\n });\n if (findings.findings.length === 0) {\n throw new CodexSecurityError(\n \"The completed scan has no findings to publish.\",\n );\n }\n return publishCloudPayload(manifest.scan, findings.findings, dependencies);\n}\n\nexport async function publishFindingsCsvToCloud(\n csvPath: string,\n dependencies: CloudPublicationDependencies = {},\n): Promise<CloudPublicationResult> {\n dependencies.signal?.throwIfAborted();\n let source: string;\n try {\n source = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n await readFile(csvPath),\n );\n } catch (error) {\n throw new CodexSecurityError(\n `Could not read findings CSV. ${errorMessage(error)}`,\n { cause: error },\n );\n }\n dependencies.signal?.throwIfAborted();\n const rows = parseFindingsCsv(source);\n if (rows.length === 0) {\n throw new CodexSecurityError(\n \"Findings CSV must contain at least one finding.\",\n );\n }\n const digest = sha256(source);\n const scanId = `scan_csv_${sha256(\n [\"codex-security-csv-import/v1\", VERSION, source].join(\"\\0\"),\n ).slice(0, 24)}`;\n const findings = bindImportedFindings(\n rows.map(csvRowFinding),\n \"csv\",\n scanId,\n CSV_TARGET_ID,\n );\n const timestamp = \"1970-01-01T00:00:00.000Z\";\n const findingsDocument = JSON.stringify({\n documentType: \"codex-security.findings\",\n schemaVersion: \"1.0\",\n scanId,\n findings,\n });\n const coverageDocument = JSON.stringify({\n documentType: \"codex-security.coverage\",\n schemaVersion: \"1.0\",\n scanId,\n mode: \"repository\",\n inventoryStrategy: \"custom\",\n includePaths: [\".\"],\n excludePaths: [],\n surfaces: findings.map((finding) => ({\n id: finding.occurrenceId,\n label: finding.title,\n disposition: \"reported\",\n receiptRefs: [],\n })),\n explicitExclusions: [],\n deferred: [],\n });\n const scan: ScanManifest[\"scan\"] = {\n id: scanId,\n producer: { name: \"codex-security-cli\", version: VERSION },\n status: \"completed\",\n startedAt: timestamp,\n completedAt: timestamp,\n sealedAt: timestamp,\n target: {\n kind: \"directory_snapshot\",\n targetId: CSV_TARGET_ID,\n displayName: \"findings.csv\",\n snapshotDigest: `codex-security-snapshot/v1:sha256:${digest}`,\n },\n scope: {\n includePaths: [\".\"],\n excludePaths: [],\n summary: \"Findings imported from a Codex Security CSV export.\",\n },\n coverageRef: \"coverage.json\",\n findingsRef: \"findings.json\",\n artifacts: [\n {\n path: \"findings.json\",\n sha256: sha256(findingsDocument),\n mediaType: \"application/json\",\n },\n {\n path: \"coverage.json\",\n sha256: sha256(coverageDocument),\n mediaType: \"application/json\",\n },\n {\n path: \"findings.csv\",\n sha256: digest,\n mediaType: \"text/csv\",\n },\n ],\n };\n return publishCloudPayload(scan, findings, dependencies);\n}\n\nasync function publishCloudPayload(\n scan: ScanManifest[\"scan\"],\n findings: Finding[],\n dependencies: CloudPublicationDependencies,\n): Promise<CloudPublicationResult> {\n dependencies.signal?.throwIfAborted();\n if (dependencies.dryRun) {\n return {\n scanId: scan.id,\n findingIds: [],\n findingCount: findings.length,\n dryRun: true,\n findings,\n };\n }\n const credentials = await readCloudCredentials(\n dependencies.environment ?? process.env,\n );\n const publishUrl =\n dependencies.environment?.[\"CODEX_SECURITY_CLOUD_PUBLISH_URL\"]?.trim() ||\n CLOUD_PUBLISH_URL;\n const timeout = AbortSignal.timeout(30_000);\n const signal = dependencies.signal\n ? AbortSignal.any([dependencies.signal, timeout])\n : timeout;\n let response: Response;\n try {\n response = await (dependencies.fetch ?? globalThis.fetch)(publishUrl, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credentials.access_token}`,\n \"ChatGPT-Account-ID\": credentials.account_id,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n },\n body: JSON.stringify({\n schemaVersion: \"1.0\",\n scan,\n findings,\n }),\n redirect: \"error\",\n signal,\n });\n } catch {\n dependencies.signal?.throwIfAborted();\n // A lost response does not establish whether the server accepted the POST.\n throw new CodexSecurityError(\n \"Cloud publication was not confirmed. The request was not retried; check whether it was accepted before submitting again.\",\n );\n }\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n const detail =\n response.status === 401\n ? \"Sign in with ChatGPT again before retrying.\"\n : response.status === 403\n ? \"The signed-in account is not authorized to publish to Cloud.\"\n : response.status === 404\n ? \"Cloud publication is not available for this account or deployment.\"\n : \"The request was not retried.\";\n throw new CodexSecurityError(\n `Cloud publication failed (HTTP ${response.status}). ${detail}`,\n );\n }\n const receipt = receiptSchema.safeParse(\n await response.json().catch(() => {\n dependencies.signal?.throwIfAborted();\n return undefined;\n }),\n );\n // Cloud assigns opaque IDs in request order, so they cannot be compared to\n // local finding IDs. The authenticated response must still preserve the\n // submitted count and return one distinct observation for each finding.\n if (\n (response.status !== 200 && response.status !== 201) ||\n !receipt.success ||\n receipt.data.finding_count !== findings.length ||\n receipt.data.finding_ids.length !== findings.length ||\n new Set(receipt.data.finding_ids).size !== receipt.data.finding_ids.length\n ) {\n throw new CodexSecurityError(\n \"Cloud publication returned an invalid acceptance receipt. Check whether the request was accepted before submitting again.\",\n );\n }\n return {\n scanId: scan.id,\n findingIds: receipt.data.finding_ids,\n findingCount: receipt.data.finding_count,\n };\n}\n\nasync function readCloudCredentials(environment: NodeJS.ProcessEnv) {\n const configuredHome = environment[\"CODEX_HOME\"];\n let home = expandHome(\n configuredHome?.trim() ? configuredHome : \"~/.codex\",\n environment,\n );\n let requireFileStorage = true;\n const dedicatedHome = codexSecurityCredentialHome(environment);\n if (existsSync(dedicatedHome)) {\n if (!(await codexSecurityCredentialAllowsAmbientImport(dedicatedHome))) {\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n }\n if (await codexSecurityHasStoredFileCredentials(dedicatedHome)) {\n home = dedicatedHome;\n requireFileStorage = false;\n } else if (existsSync(join(dedicatedHome, \"config.toml\"))) {\n // Do not silently switch accounts when the dedicated login may be in a keyring.\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n }\n }\n if (requireFileStorage) {\n let credentialStorage: unknown;\n try {\n credentialStorage = parseToml(\n await readFile(join(home, \"config.toml\"), \"utf8\"),\n )[\"cli_auth_credentials_store\"];\n } catch {\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n }\n // File presence is not proof that it is the active ambient login:\n // automatic or keyring storage can leave auth.json for another account.\n if (credentialStorage !== \"file\") {\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n }\n }\n try {\n const credentials = credentialsSchema.safeParse(\n JSON.parse(await readFile(join(home, \"auth.json\"), \"utf8\")),\n );\n if (credentials.success) return credentials.data.tokens;\n } catch {\n // Parsing and filesystem diagnostics must not reflect credential contents.\n }\n throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);\n}\n"]}
|
|
@@ -6,7 +6,7 @@ export function bundledCodexSdkEnvironment(command, environment) {
|
|
|
6
6
|
// An SDK executable override disables its bundled-tool PATH setup.
|
|
7
7
|
let toolsDirectory;
|
|
8
8
|
try {
|
|
9
|
-
toolsDirectory = join(dirname(realpathSync.native(
|
|
9
|
+
toolsDirectory = join(dirname(dirname(realpathSync.native(command))), "codex-path");
|
|
10
10
|
if (!statSync(toolsDirectory).isDirectory())
|
|
11
11
|
return environment;
|
|
12
12
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codex-sdk-environment.js","sourceRoot":"","sources":["../src/codex-sdk-environment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,MAAM,UAAU,0BAA0B,CACxC,OAAe,EACf,WAAmC;IAEnC,mEAAmE;IACnE,IAAI,cAAsB,CAAC;IAC3B,IAAI,CAAC;QACH,cAAc,GAAG,IAAI,CACnB,OAAO,CAAC,
|
|
1
|
+
{"version":3,"file":"codex-sdk-environment.js","sourceRoot":"","sources":["../src/codex-sdk-environment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC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AC,CAAC,QAAQ,CAAC;IACrE,MAAM,YAAY,GAAG,GAAG,YAAY,IAAI,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,oBAAoB,EAAE,CAAC;IACnJ,MAAM,MAAM,GAAG,WAAW,CAAC,MAAM,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAC9D,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,CAAC,CACxE,CAAC;IACF,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;IACpD,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC;IACxE,IAAI,OAAO,GAAG,IAAI,CAAC,UAAU,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC;IAClD,IAAI,gBAAgB,KAAK,SAAS,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;QACxD,OAAO,GAAG,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;IAClD,IAAI,MAAM,KAAK,SAAS,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;QACjD,MAAM,IAAI,oBAAoB,CAC5B,OAAO,WAAW,qKAAqK,CACxL,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { existsSync, readdirSync, realpathSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { delimiter, dirname, join } from \"node:path\";\nimport { PluginBootstrapError } from \"./errors.js\";\n\nexport function bundledCodexSdkEnvironment(\n command: string,\n environment: Record<string, string>,\n): Record<string, string> {\n // An SDK executable override disables its bundled-tool PATH setup.\n let toolsDirectory: string;\n try {\n toolsDirectory = join(\n dirname(dirname(realpathSync.native(command))),\n \"codex-path\",\n );\n if (!statSync(toolsDirectory).isDirectory()) return environment;\n } catch {\n return environment;\n }\n const result = { ...environment };\n const pathKeys = Object.keys(result).filter((key) =>\n process.platform === \"win32\"\n ? key.toLowerCase() === \"path\"\n : key === \"PATH\",\n );\n const pathKey = pathKeys.includes(\"Path\")\n ? \"Path\"\n : (pathKeys.at(-1) ?? \"PATH\");\n for (const key of pathKeys) {\n if (key !== pathKey) delete result[key];\n }\n const entries = (result[pathKey] ?? \"\")\n .split(delimiter)\n .filter((entry) => entry.length > 0 && entry !== toolsDirectory);\n result[pathKey] = [toolsDirectory, ...entries].join(delimiter);\n return result;\n}\n\nexport function resolveBundledCodexExecutable(\n codexPackageJson?: string,\n): string {\n const platform = process.platform === \"android\" ? \"linux\" : process.platform;\n const packageName = `@openai/codex-${platform}-${process.arch}`;\n let packageJson: string;\n let legacyVendor = false;\n try {\n const selectedPackageJson =\n codexPackageJson ??\n createRequire(import.meta.url).resolve(\"@openai/codex/package.json\");\n try {\n packageJson = createRequire(selectedPackageJson).resolve(\n `${packageName}/package.json`,\n );\n } catch (error) {\n if (codexPackageJson === undefined) throw error;\n packageJson = selectedPackageJson;\n legacyVendor = true;\n }\n } catch (error) {\n throw new PluginBootstrapError(\n `The bundled Codex executable could not be resolved from ${packageName}. Reinstall @openai/codex with optional dependencies enabled, or set CODEX_CLI_PATH to an installed Codex executable.`,\n { cause: error },\n );\n }\n const vendor = join(dirname(packageJson), \"vendor\");\n const architecture = process.arch === \"arm64\" ? \"aarch64\" : \"x86_64\";\n const legacyTarget = `${architecture}-${platform === \"darwin\" ? \"apple-darwin\" : platform === \"win32\" ? \"pc-windows-msvc\" : \"unknown-linux-musl\"}`;\n const target = readdirSync(vendor, { withFileTypes: true }).find(\n (entry) =>\n entry.isDirectory() && (!legacyVendor || entry.name === legacyTarget),\n );\n const targetRoot = join(vendor, target?.name ?? \"\");\n const binaryName = process.platform === \"win32\" ? \"codex.exe\" : \"codex\";\n let command = join(targetRoot, \"bin\", binaryName);\n if (codexPackageJson !== undefined && !existsSync(command))\n command = join(targetRoot, \"codex\", binaryName);\n if (target === undefined || !existsSync(command)) {\n throw new PluginBootstrapError(\n `The ${packageName} package does not contain the Codex executable. Reinstall @openai/codex with optional dependencies enabled, or set CODEX_CLI_PATH to an installed Codex executable.`,\n );\n }\n return command;\n}\n"]}
|
package/dist/config.d.ts
CHANGED
|
@@ -24,6 +24,12 @@ export declare const FIREWORKS_CODEX_PROVIDER: {
|
|
|
24
24
|
readonly env_key: "FIREWORKS_API_KEY";
|
|
25
25
|
readonly wire_api: "responses";
|
|
26
26
|
};
|
|
27
|
+
export declare const CHEAPERINFERENCE_CODEX_PROVIDER: {
|
|
28
|
+
readonly name: "Cheaper Inference";
|
|
29
|
+
readonly base_url: "https://api.cheaperinference.com/v1";
|
|
30
|
+
readonly env_key: "CHEAPER_INFERENCE_API_KEY";
|
|
31
|
+
readonly wire_api: "responses";
|
|
32
|
+
};
|
|
27
33
|
export declare const EXTERNAL_CODEX_PROVIDERS: {
|
|
28
34
|
readonly openrouter: {
|
|
29
35
|
readonly name: "OpenRouter";
|
|
@@ -37,6 +43,12 @@ export declare const EXTERNAL_CODEX_PROVIDERS: {
|
|
|
37
43
|
readonly env_key: "FIREWORKS_API_KEY";
|
|
38
44
|
readonly wire_api: "responses";
|
|
39
45
|
};
|
|
46
|
+
readonly cheaperinference: {
|
|
47
|
+
readonly name: "Cheaper Inference";
|
|
48
|
+
readonly base_url: "https://api.cheaperinference.com/v1";
|
|
49
|
+
readonly env_key: "CHEAPER_INFERENCE_API_KEY";
|
|
50
|
+
readonly wire_api: "responses";
|
|
51
|
+
};
|
|
40
52
|
};
|
|
41
53
|
export type ExternalModelProvider = keyof typeof EXTERNAL_CODEX_PROVIDERS;
|
|
42
54
|
export declare function isExternalModelProvider(provider: unknown): provider is ExternalModelProvider;
|
package/dist/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAC7D,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,SAAS,EAAE,GAAG,UAAU,CAAC;AACjE,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1B;AAED,MAAM,WAAW,mBAAmB;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,UAAU,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,sBAAsB;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,eAAe,EAAE,MAAM,CAAC;CACzB;AAED,eAAO,MAAM,yBAAyB;mBAC9B,YAAY;uBACR,8BAA8B;sBAC/B,oBAAoB;uBACnB,WAAW;CACQ,CAAC;AAEhC,eAAO,MAAM,wBAAwB;mBAC7B,cAAc;uBACV,uCAAuC;sBACxC,mBAAmB;uBAClB,WAAW;CACQ,CAAC;AAEhC,eAAO,MAAM,wBAAwB;aACnC,UAAU;
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAC7D,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,SAAS,EAAE,GAAG,UAAU,CAAC;AACjE,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1B;AAED,MAAM,WAAW,mBAAmB;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,UAAU,CAA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GAAG,YAAY,CAKxB;AAgBD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU,CAMlE;AAsBD,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,mBAAmB,GAC1B,OAAO,CAAC,UAAU,CAAC,CAkErB;AA2BD,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,IAAI,CAAC,CA8Bf;AAmED,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,UAAU,EAChB,SAAS,EAAE,UAAU,GACpB,UAAU,CAIZ"}
|
package/dist/config.js
CHANGED
|
@@ -15,9 +15,16 @@ export const FIREWORKS_CODEX_PROVIDER = {
|
|
|
15
15
|
env_key: "FIREWORKS_API_KEY",
|
|
16
16
|
wire_api: "responses",
|
|
17
17
|
};
|
|
18
|
+
export const CHEAPERINFERENCE_CODEX_PROVIDER = {
|
|
19
|
+
name: "Cheaper Inference",
|
|
20
|
+
base_url: "https://api.cheaperinference.com/v1",
|
|
21
|
+
env_key: "CHEAPER_INFERENCE_API_KEY",
|
|
22
|
+
wire_api: "responses",
|
|
23
|
+
};
|
|
18
24
|
export const EXTERNAL_CODEX_PROVIDERS = {
|
|
19
25
|
openrouter: OPENROUTER_CODEX_PROVIDER,
|
|
20
26
|
fireworks: FIREWORKS_CODEX_PROVIDER,
|
|
27
|
+
cheaperinference: CHEAPERINFERENCE_CODEX_PROVIDER,
|
|
21
28
|
};
|
|
22
29
|
export function isExternalModelProvider(provider) {
|
|
23
30
|
return (typeof provider === "string" &&
|
|
@@ -123,10 +130,9 @@ export function inlineToml(value) {
|
|
|
123
130
|
return stringify({ value }).slice("value = ".length).trim();
|
|
124
131
|
}
|
|
125
132
|
export function scanApprovalPolicy(config) {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
: "on-request";
|
|
133
|
+
const configured = selectedScanProfile(config)?.["approval_policy"] ??
|
|
134
|
+
config["approval_policy"];
|
|
135
|
+
return configured === "never" ? "never" : "on-request";
|
|
130
136
|
}
|
|
131
137
|
function selectedScanProfile(config) {
|
|
132
138
|
const profileName = config["profile"];
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEnD,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAmBjD,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACvC,IAAI,EAAE,YAAY;IAClB,QAAQ,EAAE,8BAA8B;IACxC,OAAO,EAAE,oBAAoB;IAC7B,QAAQ,EAAE,WAAW;CACQ,CAAC;AAEhC,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,IAAI,EAAE,cAAc;IACpB,QAAQ,EAAE,uCAAuC;IACjD,OAAO,EAAE,mBAAmB;IAC5B,QAAQ,EAAE,WAAW;CACQ,CAAC;AAEhC,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,UAAU,EAAE,yBAAyB;IACrC,SAAS,EAAE,wBAAwB;CAC3B,CAAC;AAIX,MAAM,UAAU,uBAAuB,CACrC,QAAiB;IAEjB,OAAO,CACL,OAAO,QAAQ,KAAK,QAAQ;QAC5B,MAAM,CAAC,MAAM,CAAC,wBAAwB,EAAE,QAAQ,CAAC,CAClD,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,oBAAoB,GAAyB,MAAM,CAAC,MAAM,CAAC;IACtE,eAAe,EAAE,YAAY;IAC7B,kBAAkB,EAAE,a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";\nimport { dirname, join, resolve } from \"node:path\";\nimport type { CyberAccessProgram } from \"@openai/codex-sdk\";\nimport { parse, stringify } from \"smol-toml\";\nimport { ConfigurationError } from \"./errors.js\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | JsonObject;\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\nexport interface CodexSecurityConfig {\n pluginPath?: string;\n codexOverrides?: JsonObject;\n pythonPath?: string;\n}\n\nexport interface ScanModelConfiguration {\n model: string;\n reasoningEffort: string;\n}\n\nexport const OPENROUTER_CODEX_PROVIDER = {\n name: \"OpenRouter\",\n base_url: \"https://openrouter.ai/api/v1\",\n env_key: \"OPENROUTER_API_KEY\",\n wire_api: \"responses\",\n} as const satisfies JsonObject;\n\nexport const FIREWORKS_CODEX_PROVIDER = {\n name: \"Fireworks AI\",\n base_url: \"https://api.fireworks.ai/inference/v1\",\n env_key: \"FIREWORKS_API_KEY\",\n wire_api: \"responses\",\n} as const satisfies JsonObject;\n\nexport const EXTERNAL_CODEX_PROVIDERS = {\n openrouter: OPENROUTER_CODEX_PROVIDER,\n fireworks: FIREWORKS_CODEX_PROVIDER,\n} as const;\n\nexport type ExternalModelProvider = keyof typeof EXTERNAL_CODEX_PROVIDERS;\n\nexport function isExternalModelProvider(\n provider: unknown,\n): provider is ExternalModelProvider {\n return (\n typeof provider === \"string\" &&\n Object.hasOwn(EXTERNAL_CODEX_PROVIDERS, provider)\n );\n}\n\nexport const DEFAULT_CODEX_CONFIG: Readonly<JsonObject> = Object.freeze({\n approval_policy: \"on-request\",\n approvals_reviewer: \"auto_review\",\n cli_auth_credentials_store: \"auto\",\n model: \"gpt-5.6-sol\",\n model_reasoning_effort: \"xhigh\",\n model_reasoning_summary: \"detailed\",\n show_raw_agent_reasoning: true,\n features: Object.freeze({\n plugins: true,\n goals: true,\n multi_agent_v2: Object.freeze({\n enabled: true,\n max_concurrent_threads_per_session: 9,\n }),\n }),\n // Credential read denials require the elevated Windows sandbox backend.\n windows: Object.freeze({\n sandbox: \"elevated\",\n }),\n});\n\nexport function scanModelConfiguration(\n config: Readonly<JsonObject>,\n): ScanModelConfiguration {\n const selectedProfile = selectedScanProfile(config);\n const model = scanModel(config);\n if (typeof model !== \"string\" || model.trim().length === 0) {\n throw new ConfigurationError(\n \"The configured Codex model must be a nonempty string.\",\n );\n }\n const reasoningEffort =\n selectedProfile?.[\"model_reasoning_effort\"] ??\n config[\"model_reasoning_effort\"];\n if (\n typeof reasoningEffort !== \"string\" ||\n reasoningEffort.trim().length === 0\n ) {\n throw new ConfigurationError(\n \"The configured Codex reasoning effort must be a nonempty string.\",\n );\n }\n return { model, reasoningEffort };\n}\n\nexport function scanModel(config: Readonly<JsonObject>): unknown {\n const selectedProfile = selectedScanProfile(config);\n return selectedProfile?.[\"model\"] ?? config[\"model\"];\n}\n\nexport function scanModelProvider(config: Readonly<JsonObject>): unknown {\n const selectedProfile = selectedScanProfile(config);\n return selectedProfile?.[\"model_provider\"] ?? config[\"model_provider\"];\n}\n\n/** @internal Native Codex validates the auth table, including invalid selections. */\nexport function hasCommandAuth(config: Readonly<JsonObject>): boolean {\n const selected = scanModelProvider(config);\n const providers = resolveCodexProfile(config)[\"model_providers\"];\n const provider =\n typeof selected === \"string\" && isObject(providers)\n ? providers[selected]\n : undefined;\n return isObject(provider) && provider[\"auth\"] != null;\n}\n\n/** @internal Keep host-side helpers independent of the source checkout. */\nexport function resolveCommandAuthConfig(\n config: JsonObject,\n home: string,\n): JsonObject {\n const resolved = structuredClone(config);\n const providers = resolveCodexProfile(resolved)[\"model_providers\"];\n if (isObject(providers)) {\n (selectedScanProfile(resolved) ?? resolved)[\"model_providers\"] = providers;\n for (const provider of Object.values(providers)) {\n if (!isObject(provider) || !isObject(provider[\"auth\"])) continue;\n const auth = provider[\"auth\"];\n const cwd = auth[\"cwd\"];\n if (\n cwd == null ||\n (typeof cwd === \"string\" && !/^~(?:[/\\\\]|$)/u.test(cwd))\n ) {\n auth[\"cwd\"] = resolve(home, cwd ?? \".\");\n }\n }\n }\n return resolved;\n}\n\n/** @internal CLI dotted keys cannot represent provider IDs containing dots. */\nexport function modelProviderConfigOverride(config: JsonObject): string[] {\n return config[\"model_providers\"] == null\n ? []\n : [`model_providers=${inlineToml(config[\"model_providers\"])}`];\n}\n\n/** @internal Resolve settings; literal-key tables use native file layers. */\nexport function structuredCodexConfig(config: JsonObject = {}): JsonObject {\n const structured = resolveCodexProfile(config);\n delete structured[\"projects\"];\n delete structured[\"permissions\"];\n delete structured[\"model_providers\"];\n return structured;\n}\n\n/** @internal Serialize one Codex CLI override value without flattening its keys. */\nexport function inlineToml(value: JsonValue): string {\n if (value === null)\n throw new ConfigurationError(\n \"Codex TOML overrides cannot contain null values.\",\n );\n if (Array.isArray(value)) return `[${value.map(inlineToml).join(\",\")}]`;\n if (isObject(value)) {\n return `{${Object.entries(value)\n .filter(([, item]) => item !== null)\n .map(([key, item]) => `${JSON.stringify(key)}=${inlineToml(item)}`)\n .join(\",\")}}`;\n }\n return stringify({ value }).slice(\"value = \".length).trim();\n}\n\nexport function scanApprovalPolicy(\n config: Readonly<JsonObject>,\n): \"never\" | \"on-request\" {\n return config[\"approval_policy\"] === \"never\" ||\n selectedScanProfile(config)?.[\"approval_policy\"] === \"never\"\n ? \"never\"\n : \"on-request\";\n}\n\nfunction selectedScanProfile(\n config: Readonly<JsonObject>,\n): Record<string, JsonValue> | undefined {\n const profileName = config[\"profile\"];\n const profiles = config[\"profiles\"];\n const configuredProfile =\n typeof profileName === \"string\" &&\n isObject(profiles) &&\n Object.hasOwn(profiles, profileName)\n ? profiles[profileName]\n : undefined;\n return isObject(configuredProfile) ? configuredProfile : undefined;\n}\n\nexport function resolveCodexProfile(config: JsonObject): JsonObject {\n const normalized = parse(stringify(config)) as JsonObject;\n const resolved = deepMerge(normalized, selectedScanProfile(normalized) ?? {});\n delete resolved[\"profile\"];\n delete resolved[\"profiles\"];\n return resolved;\n}\n\n/** @internal */\nexport function scanCyberAccessConfig(\n config: JsonObject,\n program: CyberAccessProgram | undefined,\n): JsonObject {\n if (program === undefined) return config;\n const resolved = resolveCodexProfile(config);\n const features = isObject(resolved[\"features\"]) ? resolved[\"features\"] : {};\n return {\n ...config,\n features: {\n ...(isObject(config[\"features\"]) ? config[\"features\"] : {}),\n // Explicit selections opt in to upstream API-key support. Keep a user's\n // explicit disable so Codex can report it instead of silently dropping it.\n api_key_cyber_access_programs:\n features[\"api_key_cyber_access_programs\"] ?? true,\n },\n };\n}\n\nexport async function mergedCodexConfig(\n config: CodexSecurityConfig,\n): Promise<JsonObject> {\n if (config.codexOverrides !== undefined && !isObject(config.codexOverrides)) {\n throw new ConfigurationError(\"codexOverrides must be an object.\");\n }\n validateOverrideKeys(config.codexOverrides ?? {});\n const overrides = structuredClone(config.codexOverrides ?? {});\n validateOverrides(overrides);\n const agents = overrides[\"agents\"];\n if (isObject(agents) && \"max_threads\" in agents) {\n throw new ConfigurationError(\n \"The selected Codex Security plugin requires native multi-agent v2; \" +\n \"agents.max_threads is a legacy v1 setting. Use \" +\n \"features.multi_agent_v2.max_concurrent_threads_per_session instead.\",\n );\n }\n const features = overrides[\"features\"];\n if (isObject(features) && \"multi_agent_v2\" in features) {\n const multiAgentV2 = features[\"multi_agent_v2\"];\n if (!isObject(multiAgentV2)) {\n throw new ConfigurationError(\n \"The selected Codex Security plugin requires native multi-agent v2; \" +\n \"features.multi_agent_v2 must remain a table with enabled = true.\",\n );\n }\n if (\"enabled\" in multiAgentV2 && multiAgentV2[\"enabled\"] !== true) {\n throw new ConfigurationError(\n \"The selected Codex Security plugin requires native multi-agent v2; \" +\n \"features.multi_agent_v2.enabled cannot be disabled.\",\n );\n }\n }\n\n const profiles = Object.entries(\n (overrides[\"profiles\"] ?? {}) as Record<string, JsonObject>,\n );\n for (const [name, profile] of profiles) {\n const profileAgents = profile[\"agents\"];\n if (isObject(profileAgents) && \"max_threads\" in profileAgents) {\n throw new ConfigurationError(\n `The selected Codex Security plugin requires native multi-agent v2; profile ${name} agents.max_threads is a legacy v1 setting.`,\n );\n }\n const profileFeatures = profile[\"features\"];\n if (!isObject(profileFeatures) || !(\"multi_agent_v2\" in profileFeatures)) {\n continue;\n }\n const profileV2 = profileFeatures[\"multi_agent_v2\"];\n if (\n !isObject(profileV2) ||\n (\"enabled\" in profileV2 && profileV2[\"enabled\"] !== true)\n ) {\n throw new ConfigurationError(\n `The selected Codex Security plugin requires native multi-agent v2; profile ${name} features.multi_agent_v2 cannot be disabled.`,\n );\n }\n }\n normalizeLegacyWindowsSandboxOverride(overrides);\n for (const [, profile] of profiles) {\n normalizeLegacyWindowsSandboxOverride(profile);\n }\n const defaults: JsonObject = structuredClone(DEFAULT_CODEX_CONFIG);\n if (scanModelProvider(overrides) === \"amazon-bedrock\") {\n // Bedrock models can reject reasoning.summary before the scan starts.\n defaults[\"model_reasoning_summary\"] = \"none\";\n }\n return deepMerge(defaults, overrides);\n}\n\n/** @internal Preserve existing native Windows backend selections. */\nexport function normalizeLegacyWindowsSandboxOverride(\n overrides: JsonObject,\n): void {\n const features = overrides[\"features\"];\n if (!isObject(features)) {\n return;\n }\n const elevated = features[\"elevated_windows_sandbox\"];\n if (typeof elevated !== \"boolean\") {\n return;\n }\n const windows = overrides[\"windows\"];\n if (\n windows !== undefined &&\n (!isObject(windows) || Object.hasOwn(windows, \"sandbox\"))\n ) {\n return;\n }\n overrides[\"windows\"] = {\n ...(isObject(windows) ? windows : {}),\n sandbox: elevated ? \"elevated\" : \"unelevated\",\n };\n}\n\nexport async function writeCodexConfig(\n path: string,\n config: JsonObject,\n): Promise<void> {\n const parent = dirname(path);\n await mkdir(parent, { recursive: true, mode: 0o700 });\n let contents: string;\n try {\n contents = stringify(config);\n } catch (error) {\n throw new ConfigurationError(\"Invalid Codex configuration.\", {\n cause: error,\n });\n }\n const temporary = join(parent, `.${randomUUID()}.config.toml.tmp`);\n let created = false;\n try {\n const handle = await open(temporary, \"wx\", 0o600);\n created = true;\n try {\n await handle.chmod(0o600);\n await handle.writeFile(contents, \"utf8\");\n await handle.sync();\n } finally {\n await handle.close();\n }\n await rename(temporary, path);\n created = false;\n } finally {\n if (created) {\n await unlink(temporary).catch(() => undefined);\n }\n }\n}\n\nfunction validateOverrideKeys(value: JsonValue): void {\n if (Array.isArray(value)) {\n for (const item of value) validateOverrideKeys(item);\n return;\n }\n if (!isObject(value)) return;\n for (const [key, item] of Object.entries(value)) {\n if ([\"__proto__\", \"constructor\", \"prototype\"].includes(key)) {\n throw new ConfigurationError(`Invalid Codex override key: ${key}.`);\n }\n validateOverrideKeys(item);\n }\n}\n\nfunction validateOverrides(overrides: JsonObject): void {\n if (\"plugins\" in overrides || \"marketplaces\" in overrides) {\n throw new ConfigurationError(\n \"Codex Security owns plugin loading configuration.\",\n );\n }\n const features = overrides[\"features\"];\n if (\"features\" in overrides && !isObject(features)) {\n throw new ConfigurationError(\n \"Codex override features must be a TOML table.\",\n );\n }\n if (isObject(features) && \"plugins\" in features) {\n throw new ConfigurationError(\n \"Codex Security owns plugin loading configuration.\",\n );\n }\n const profiles = overrides[\"profiles\"];\n if (profiles === undefined) {\n return;\n }\n if (!isObject(profiles)) {\n throw new ConfigurationError(\n \"Codex override profiles must be TOML tables.\",\n );\n }\n for (const [name, profile] of Object.entries(profiles)) {\n if (!isObject(profile)) {\n throw new ConfigurationError(\n `Codex override profile ${name} must be a TOML table.`,\n );\n }\n if (\"plugins\" in profile || \"marketplaces\" in profile) {\n throw new ConfigurationError(\n `Codex Security owns plugin loading configuration in profile ${name}.`,\n );\n }\n const profileFeatures = profile[\"features\"];\n if (profileFeatures !== undefined && !isObject(profileFeatures)) {\n throw new ConfigurationError(\n `Codex override profile ${name} features must be a TOML table.`,\n );\n }\n if (isObject(profileFeatures) && \"plugins\" in profileFeatures) {\n throw new ConfigurationError(\n `Codex Security owns plugin loading configuration in profile ${name}.`,\n );\n }\n }\n}\n\nexport function mergeCodexOverrides(\n base: JsonObject,\n overrides: JsonObject,\n): JsonObject {\n validateOverrideKeys(base);\n validateOverrideKeys(overrides);\n return deepMerge(structuredClone(base), overrides);\n}\n\n/** @internal */\nexport function deepMerge(base: JsonObject, overrides: JsonObject): JsonObject {\n for (const [key, value] of Object.entries(overrides)) {\n const existing = Object.hasOwn(base, key) ? base[key] : undefined;\n base[key] =\n isObject(value) && isObject(existing)\n ? deepMerge({ ...existing }, value)\n : structuredClone(value);\n }\n return base;\n}\n\nfunction isObject(value: unknown): value is Record<string, JsonValue> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEnD,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAmBjD,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACvC,IAAI,EAAE,YAAY;IAClB,QAAQ,EAAE,8BAA8B;IACxC,OAAO,EAAE,oBAAoB;IAC7B,QAAQ,EAAE,WAAW;CACQ,CAAC;AAEhC,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,IAAI,EAAE,cAAc;IACpB,QAAQ,EAAE,uCAAuC;IACjD,OAAO,EAAE,mBAAmB;IAC5B,QAAQ,EAAE,WAAW;CACQ,CAAC;AAEhC,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC7C,IAAI,EAAE,mBAAmB;IACzB,QAAQ,EAAE,qCAAqC;IAC/C,OAAO,EAAE,2BAA2B;IACpC,QA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K,CAAC,CAAC;IAC/B,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACxE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAC9D,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { mkdir, open, rename, unlink } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport type { CyberAccessProgram } from \"@openai/codex-sdk\";\nimport { parse, stringify } from \"smol-toml\";\nimport { ConfigurationError } from \"./errors.js\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | JsonObject;\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\nexport interface CodexSecurityConfig {\n pluginPath?: string;\n codexOverrides?: JsonObject;\n pythonPath?: string;\n}\n\nexport interface ScanModelConfiguration {\n model: string;\n reasoningEffort: string;\n}\n\nexport const OPENROUTER_CODEX_PROVIDER = {\n name: \"OpenRouter\",\n base_url: \"https://openrouter.ai/api/v1\",\n env_key: \"OPENROUTER_API_KEY\",\n wire_api: \"responses\",\n} as const satisfies JsonObject;\n\nexport const FIREWORKS_CODEX_PROVIDER = {\n name: \"Fireworks AI\",\n base_url: \"https://api.fireworks.ai/inference/v1\",\n env_key: \"FIREWORKS_API_KEY\",\n wire_api: \"responses\",\n} as const satisfies JsonObject;\n\nexport const CHEAPERINFERENCE_CODEX_PROVIDER = {\n name: \"Cheaper Inference\",\n base_url: \"https://api.cheaperinference.com/v1\",\n env_key: \"CHEAPER_INFERENCE_API_KEY\",\n wire_api: \"responses\",\n} as const satisfies JsonObject;\n\nexport const EXTERNAL_CODEX_PROVIDERS = {\n openrouter: OPENROUTER_CODEX_PROVIDER,\n fireworks: FIREWORKS_CODEX_PROVIDER,\n cheaperinference: CHEAPERINFERENCE_CODEX_PROVIDER,\n} as const;\n\nexport type ExternalModelProvider = keyof typeof EXTERNAL_CODEX_PROVIDERS;\n\nexport function isExternalModelProvider(\n provider: unknown,\n): provider is ExternalModelProvider {\n return (\n typeof provider === \"string\" &&\n Object.hasOwn(EXTERNAL_CODEX_PROVIDERS, provider)\n );\n}\n\nexport const DEFAULT_CODEX_CONFIG: Readonly<JsonObject> = Object.freeze({\n approval_policy: \"on-request\",\n approvals_reviewer: \"auto_review\",\n cli_auth_credentials_store: \"auto\",\n model: \"gpt-5.6-sol\",\n model_reasoning_effort: \"xhigh\",\n model_reasoning_summary: \"detailed\",\n show_raw_agent_reasoning: true,\n features: Object.freeze({\n plugins: true,\n goals: true,\n multi_agent_v2: Object.freeze({\n enabled: true,\n max_concurrent_threads_per_session: 9,\n }),\n }),\n // Credential read denials require the elevated Windows sandbox backend.\n windows: Object.freeze({\n sandbox: \"elevated\",\n }),\n});\n\nexport function scanModelConfiguration(\n config: Readonly<JsonObject>,\n): ScanModelConfiguration {\n const selectedProfile = selectedScanProfile(config);\n const model = scanModel(config);\n if (typeof model !== \"string\" || model.trim().length === 0) {\n throw new ConfigurationError(\n \"The configured Codex model must be a nonempty string.\",\n );\n }\n const reasoningEffort =\n selectedProfile?.[\"model_reasoning_effort\"] ??\n config[\"model_reasoning_effort\"];\n if (\n typeof reasoningEffort !== \"string\" ||\n reasoningEffort.trim().length === 0\n ) {\n throw new ConfigurationError(\n \"The configured Codex reasoning effort must be a nonempty string.\",\n );\n }\n return { model, reasoningEffort };\n}\n\nexport function scanModel(config: Readonly<JsonObject>): unknown {\n const selectedProfile = selectedScanProfile(config);\n return selectedProfile?.[\"model\"] ?? config[\"model\"];\n}\n\nexport function scanModelProvider(config: Readonly<JsonObject>): unknown {\n const selectedProfile = selectedScanProfile(config);\n return selectedProfile?.[\"model_provider\"] ?? config[\"model_provider\"];\n}\n\n/** @internal Native Codex validates the auth table, including invalid selections. */\nexport function hasCommandAuth(config: Readonly<JsonObject>): boolean {\n const selected = scanModelProvider(config);\n const providers = resolveCodexProfile(config)[\"model_providers\"];\n const provider =\n typeof selected === \"string\" && isObject(providers)\n ? providers[selected]\n : undefined;\n return isObject(provider) && provider[\"auth\"] != null;\n}\n\n/** @internal Keep host-side helpers independent of the source checkout. */\nexport function resolveCommandAuthConfig(\n config: JsonObject,\n home: string,\n): JsonObject {\n const resolved = structuredClone(config);\n const providers = resolveCodexProfile(resolved)[\"model_providers\"];\n if (isObject(providers)) {\n (selectedScanProfile(resolved) ?? resolved)[\"model_providers\"] = providers;\n for (const provider of Object.values(providers)) {\n if (!isObject(provider) || !isObject(provider[\"auth\"])) continue;\n const auth = provider[\"auth\"];\n const cwd = auth[\"cwd\"];\n if (\n cwd == null ||\n (typeof cwd === \"string\" && !/^~(?:[/\\\\]|$)/u.test(cwd))\n ) {\n auth[\"cwd\"] = resolve(home, cwd ?? \".\");\n }\n }\n }\n return resolved;\n}\n\n/** @internal CLI dotted keys cannot represent provider IDs containing dots. */\nexport function modelProviderConfigOverride(config: JsonObject): string[] {\n return config[\"model_providers\"] == null\n ? []\n : [`model_providers=${inlineToml(config[\"model_providers\"])}`];\n}\n\n/** @internal Resolve settings; literal-key tables use native file layers. */\nexport function structuredCodexConfig(config: JsonObject = {}): JsonObject {\n const structured = resolveCodexProfile(config);\n delete structured[\"projects\"];\n delete structured[\"permissions\"];\n delete structured[\"model_providers\"];\n return structured;\n}\n\n/** @internal Serialize one Codex CLI override value without flattening its keys. */\nexport function inlineToml(value: JsonValue): string {\n if (value === null)\n throw new ConfigurationError(\n \"Codex TOML overrides cannot contain null values.\",\n );\n if (Array.isArray(value)) return `[${value.map(inlineToml).join(\",\")}]`;\n if (isObject(value)) {\n return `{${Object.entries(value)\n .filter(([, item]) => item !== null)\n .map(([key, item]) => `${JSON.stringify(key)}=${inlineToml(item)}`)\n .join(\",\")}}`;\n }\n return stringify({ value }).slice(\"value = \".length).trim();\n}\n\nexport function scanApprovalPolicy(\n config: Readonly<JsonObject>,\n): \"never\" | \"on-request\" {\n const configured =\n selectedScanProfile(config)?.[\"approval_policy\"] ??\n config[\"approval_policy\"];\n return configured === \"never\" ? \"never\" : \"on-request\";\n}\n\nfunction selectedScanProfile(\n config: Readonly<JsonObject>,\n): Record<string, JsonValue> | undefined {\n const profileName = config[\"profile\"];\n const profiles = config[\"profiles\"];\n const configuredProfile =\n typeof profileName === \"string\" &&\n isObject(profiles) &&\n Object.hasOwn(profiles, profileName)\n ? profiles[profileName]\n : undefined;\n return isObject(configuredProfile) ? configuredProfile : undefined;\n}\n\nexport function resolveCodexProfile(config: JsonObject): JsonObject {\n const normalized = parse(stringify(config)) as JsonObject;\n const resolved = deepMerge(normalized, selectedScanProfile(normalized) ?? {});\n delete resolved[\"profile\"];\n delete resolved[\"profiles\"];\n return resolved;\n}\n\n/** @internal */\nexport function scanCyberAccessConfig(\n config: JsonObject,\n program: CyberAccessProgram | undefined,\n): JsonObject {\n if (program === undefined) return config;\n const resolved = resolveCodexProfile(config);\n const features = isObject(resolved[\"features\"]) ? resolved[\"features\"] : {};\n return {\n ...config,\n features: {\n ...(isObject(config[\"features\"]) ? config[\"features\"] : {}),\n // Explicit selections opt in to upstream API-key support. Keep a user's\n // explicit disable so Codex can report it instead of silently dropping it.\n api_key_cyber_access_programs:\n features[\"api_key_cyber_access_programs\"] ?? true,\n },\n };\n}\n\nexport async function mergedCodexConfig(\n config: CodexSecurityConfig,\n): Promise<JsonObject> {\n if (config.codexOverrides !== undefined && !isObject(config.codexOverrides)) {\n throw new ConfigurationError(\"codexOverrides must be an object.\");\n }\n validateOverrideKeys(config.codexOverrides ?? {});\n const overrides = structuredClone(config.codexOverrides ?? {});\n validateOverrides(overrides);\n const agents = overrides[\"agents\"];\n if (isObject(agents) && \"max_threads\" in agents) {\n throw new ConfigurationError(\n \"The selected Codex Security plugin requires native multi-agent v2; \" +\n \"agents.max_threads is a legacy v1 setting. Use \" +\n \"features.multi_agent_v2.max_concurrent_threads_per_session instead.\",\n );\n }\n const features = overrides[\"features\"];\n if (isObject(features) && \"multi_agent_v2\" in features) {\n const multiAgentV2 = features[\"multi_agent_v2\"];\n if (!isObject(multiAgentV2)) {\n throw new ConfigurationError(\n \"The selected Codex Security plugin requires native multi-agent v2; \" +\n \"features.multi_agent_v2 must remain a table with enabled = true.\",\n );\n }\n if (\"enabled\" in multiAgentV2 && multiAgentV2[\"enabled\"] !== true) {\n throw new ConfigurationError(\n \"The selected Codex Security plugin requires native multi-agent v2; \" +\n \"features.multi_agent_v2.enabled cannot be disabled.\",\n );\n }\n }\n\n const profiles = Object.entries(\n (overrides[\"profiles\"] ?? {}) as Record<string, JsonObject>,\n );\n for (const [name, profile] of profiles) {\n const profileAgents = profile[\"agents\"];\n if (isObject(profileAgents) && \"max_threads\" in profileAgents) {\n throw new ConfigurationError(\n `The selected Codex Security plugin requires native multi-agent v2; profile ${name} agents.max_threads is a legacy v1 setting.`,\n );\n }\n const profileFeatures = profile[\"features\"];\n if (!isObject(profileFeatures) || !(\"multi_agent_v2\" in profileFeatures)) {\n continue;\n }\n const profileV2 = profileFeatures[\"multi_agent_v2\"];\n if (\n !isObject(profileV2) ||\n (\"enabled\" in profileV2 && profileV2[\"enabled\"] !== true)\n ) {\n throw new ConfigurationError(\n `The selected Codex Security plugin requires native multi-agent v2; profile ${name} features.multi_agent_v2 cannot be disabled.`,\n );\n }\n }\n normalizeLegacyWindowsSandboxOverride(overrides);\n for (const [, profile] of profiles) {\n normalizeLegacyWindowsSandboxOverride(profile);\n }\n const defaults: JsonObject = structuredClone(DEFAULT_CODEX_CONFIG);\n if (scanModelProvider(overrides) === \"amazon-bedrock\") {\n // Bedrock models can reject reasoning.summary before the scan starts.\n defaults[\"model_reasoning_summary\"] = \"none\";\n }\n return deepMerge(defaults, overrides);\n}\n\n/** @internal Preserve existing native Windows backend selections. */\nexport function normalizeLegacyWindowsSandboxOverride(\n overrides: JsonObject,\n): void {\n const features = overrides[\"features\"];\n if (!isObject(features)) {\n return;\n }\n const elevated = features[\"elevated_windows_sandbox\"];\n if (typeof elevated !== \"boolean\") {\n return;\n }\n const windows = overrides[\"windows\"];\n if (\n windows !== undefined &&\n (!isObject(windows) || Object.hasOwn(windows, \"sandbox\"))\n ) {\n return;\n }\n overrides[\"windows\"] = {\n ...(isObject(windows) ? windows : {}),\n sandbox: elevated ? \"elevated\" : \"unelevated\",\n };\n}\n\nexport async function writeCodexConfig(\n path: string,\n config: JsonObject,\n): Promise<void> {\n const parent = dirname(path);\n await mkdir(parent, { recursive: true, mode: 0o700 });\n let contents: string;\n try {\n contents = stringify(config);\n } catch (error) {\n throw new ConfigurationError(\"Invalid Codex configuration.\", {\n cause: error,\n });\n }\n const temporary = join(parent, `.${randomUUID()}.config.toml.tmp`);\n let created = false;\n try {\n const handle = await open(temporary, \"wx\", 0o600);\n created = true;\n try {\n await handle.chmod(0o600);\n await handle.writeFile(contents, \"utf8\");\n await handle.sync();\n } finally {\n await handle.close();\n }\n await rename(temporary, path);\n created = false;\n } finally {\n if (created) {\n await unlink(temporary).catch(() => undefined);\n }\n }\n}\n\nfunction validateOverrideKeys(value: JsonValue): void {\n if (Array.isArray(value)) {\n for (const item of value) validateOverrideKeys(item);\n return;\n }\n if (!isObject(value)) return;\n for (const [key, item] of Object.entries(value)) {\n if ([\"__proto__\", \"constructor\", \"prototype\"].includes(key)) {\n throw new ConfigurationError(`Invalid Codex override key: ${key}.`);\n }\n validateOverrideKeys(item);\n }\n}\n\nfunction validateOverrides(overrides: JsonObject): void {\n if (\"plugins\" in overrides || \"marketplaces\" in overrides) {\n throw new ConfigurationError(\n \"Codex Security owns plugin loading configuration.\",\n );\n }\n const features = overrides[\"features\"];\n if (\"features\" in overrides && !isObject(features)) {\n throw new ConfigurationError(\n \"Codex override features must be a TOML table.\",\n );\n }\n if (isObject(features) && \"plugins\" in features) {\n throw new ConfigurationError(\n \"Codex Security owns plugin loading configuration.\",\n );\n }\n const profiles = overrides[\"profiles\"];\n if (profiles === undefined) {\n return;\n }\n if (!isObject(profiles)) {\n throw new ConfigurationError(\n \"Codex override profiles must be TOML tables.\",\n );\n }\n for (const [name, profile] of Object.entries(profiles)) {\n if (!isObject(profile)) {\n throw new ConfigurationError(\n `Codex override profile ${name} must be a TOML table.`,\n );\n }\n if (\"plugins\" in profile || \"marketplaces\" in profile) {\n throw new ConfigurationError(\n `Codex Security owns plugin loading configuration in profile ${name}.`,\n );\n }\n const profileFeatures = profile[\"features\"];\n if (profileFeatures !== undefined && !isObject(profileFeatures)) {\n throw new ConfigurationError(\n `Codex override profile ${name} features must be a TOML table.`,\n );\n }\n if (isObject(profileFeatures) && \"plugins\" in profileFeatures) {\n throw new ConfigurationError(\n `Codex Security owns plugin loading configuration in profile ${name}.`,\n );\n }\n }\n}\n\nexport function mergeCodexOverrides(\n base: JsonObject,\n overrides: JsonObject,\n): JsonObject {\n validateOverrideKeys(base);\n validateOverrideKeys(overrides);\n return deepMerge(structuredClone(base), overrides);\n}\n\n/** @internal */\nexport function deepMerge(base: JsonObject, overrides: JsonObject): JsonObject {\n for (const [key, value] of Object.entries(overrides)) {\n const existing = Object.hasOwn(base, key) ? base[key] : undefined;\n base[key] =\n isObject(value) && isObject(existing)\n ? deepMerge({ ...existing }, value)\n : structuredClone(value);\n }\n return base;\n}\n\nfunction isObject(value: unknown): value is Record<string, JsonValue> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"]}
|
package/dist/contract.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type BigIntStats, type Stats } from "node:fs";
|
|
2
2
|
import { type FileHandle } from "node:fs/promises";
|
|
3
|
+
import { ContractValidationError } from "./errors.js";
|
|
3
4
|
import type { CoverageDocument, Finding, FindingsDocument, ScanManifest } from "./models.js";
|
|
4
5
|
import type { NormalizedTarget, ScanMode } from "./targets.js";
|
|
5
6
|
export interface ScanExpectation {
|
|
@@ -14,6 +15,8 @@ export interface LoadedContract {
|
|
|
14
15
|
findings: FindingsDocument;
|
|
15
16
|
coverage: CoverageDocument;
|
|
16
17
|
}
|
|
18
|
+
export declare class ContractSchemaError extends ContractValidationError {
|
|
19
|
+
}
|
|
17
20
|
type LoadContractOptions = {
|
|
18
21
|
pluginRoot: string;
|
|
19
22
|
expectedScanId?: string;
|
|
@@ -26,6 +29,8 @@ export declare function loadContractWithScanDirectory(scanDirectory: string, opt
|
|
|
26
29
|
contract: LoadedContract;
|
|
27
30
|
scanDirectory: string;
|
|
28
31
|
}>;
|
|
32
|
+
/** Match the producer's Python str.strip without changing saved text. */
|
|
33
|
+
export declare function hasRequiredFindingText(value: string): boolean;
|
|
29
34
|
export declare function requireScanFile(scanDirectory: string, relativePath: string, context: string, signal?: AbortSignal): Promise<string>;
|
|
30
35
|
export declare function readScanFile(scanDirectory: string, relativePath: string, context: string, signal?: AbortSignal): Promise<Buffer>;
|
|
31
36
|
export declare function safeScopePath(value: string): string;
|
package/dist/contract.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAGA,OAAO,EAAa,KAAK,WAAW,EAAE,KAAK,KAAK,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAKL,KAAK,UAAU,EAChB,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAGA,OAAO,EAAa,KAAK,WAAW,EAAE,KAAK,KAAK,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAKL,KAAK,UAAU,EAChB,MAAM,kBAAkB,CAAC;AAI1B,OAAO,EACL,uBAAuB,EAGxB,MA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,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,CAAC,CAIjB;AAED,wBAAsB,YAAY,CAChC,aAAa,EAAE,MAAM,EACrB,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,CAAC,CAYjB;AA+WD,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAInD;AA0PD,wBAAsB,qBAAqB,CACzC,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,GAAG,WAAW,EAAE,KAAK,GAAG,KAAK,CAAC,CAAA;CAAE,EAC7E,MAAM,EAAE,IAAI,CAAC,KAAK,GAAG,WAAW,EAAE,KAAK,GAAG,KAAK,CAAC,EAChD,QAAQ,GAAE,MAAM,CAAC,QAA2B,EAC5C,aAAa,GAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,UAAU,CAAQ,GACzE,OAAO,CAAC,OAAO,CAAC,CA+BlB;AA0CD,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,OAAO,CAAC,UAAU,CAAC;;;;;;;;;;QAiBzB,SAAS,EAAE,mBAAmB;QAC9B,OAAO;;EAGZ"}
|
package/dist/contract.js
CHANGED
|
@@ -6,7 +6,7 @@ import { lstat, open, readFile, realpath, } from "node:fs/promises";
|
|
|
6
6
|
import { isAbsolute, join, posix, resolve } from "node:path";
|
|
7
7
|
import Ajv2020 from "ajv/dist/2020.js";
|
|
8
8
|
import { regexes } from "zod";
|
|
9
|
-
import { ContractValidationError, abortReason } from "./errors.js";
|
|
9
|
+
import { ContractValidationError, abortReason, errorMessage, } from "./errors.js";
|
|
10
10
|
import { isRecord } from "./record.js";
|
|
11
11
|
import { requirePrivateOutputDirectory, requireSecureOutputAncestry, } from "./runtime.js";
|
|
12
12
|
import { isWithin as isContained } from "./trusted-executable.js";
|
|
@@ -17,10 +17,13 @@ const DOCUMENTS = {
|
|
|
17
17
|
"coverage.json": "coverage.schema.json",
|
|
18
18
|
};
|
|
19
19
|
const PRODUCER_NAME = "codex-security-plugin";
|
|
20
|
+
export class ContractSchemaError extends ContractValidationError {
|
|
21
|
+
}
|
|
20
22
|
export async function loadContract(scanDirectory, options) {
|
|
21
23
|
return (await loadContractWithScanDirectory(scanDirectory, options)).contract;
|
|
22
24
|
}
|
|
23
25
|
export async function loadContractWithScanDirectory(scanDirectory, options) {
|
|
26
|
+
const validators = await loadContractValidators(options.pluginRoot, options.signal);
|
|
24
27
|
const scanRoot = await requireScanRoot(scanDirectory, options.signal);
|
|
25
28
|
const scanDir = scanRoot.path;
|
|
26
29
|
const documentDigests = new Map();
|
|
@@ -29,17 +32,10 @@ export async function loadContractWithScanDirectory(scanDirectory, options) {
|
|
|
29
32
|
payloads[filename] = await readScanJson(scanDir, filename, documentDigests, options.signal, scanRoot);
|
|
30
33
|
}
|
|
31
34
|
throwIfAborted(options.signal);
|
|
32
|
-
|
|
33
|
-
// 2020-12 but intentionally omit redundant local `type` keywords that Ajv's
|
|
34
|
-
// optional strict-schema linter requires.
|
|
35
|
-
const ajv = new Ajv2020({ allErrors: false, strict: false }).addFormat("date-time", { type: "string", validate: validRfc3339DateTime });
|
|
36
|
-
for (const [filename, schemaName] of Object.entries(DOCUMENTS)) {
|
|
37
|
-
const schema = await readJson(join(options.pluginRoot, "schemas", schemaName), options.signal);
|
|
38
|
-
let validate;
|
|
35
|
+
for (const { filename, schemaName, validate } of validators) {
|
|
39
36
|
let payload;
|
|
40
37
|
let valid;
|
|
41
38
|
try {
|
|
42
|
-
validate = ajv.compile(schema);
|
|
43
39
|
payload = payloads[filename];
|
|
44
40
|
const validatePayload = (payload) => {
|
|
45
41
|
const result = validate(payload);
|
|
@@ -55,7 +51,7 @@ export async function loadContractWithScanDirectory(scanDirectory, options) {
|
|
|
55
51
|
}
|
|
56
52
|
}
|
|
57
53
|
catch {
|
|
58
|
-
throw new
|
|
54
|
+
throw new ContractSchemaError(`${schemaName}: invalid JSON Schema.`);
|
|
59
55
|
}
|
|
60
56
|
if (!valid) {
|
|
61
57
|
throw schemaError(filename, validate.errors ?? []);
|
|
@@ -80,7 +76,7 @@ export async function loadContractWithScanDirectory(scanDirectory, options) {
|
|
|
80
76
|
if (!sameArray(coverage.excludePaths, manifest.scan.scope.excludePaths)) {
|
|
81
77
|
throw new ContractValidationError("Coverage exclude paths do not match the manifest scope.");
|
|
82
78
|
}
|
|
83
|
-
validateCanonicalContract(manifest, findings);
|
|
79
|
+
validateCanonicalContract(manifest, findings, coverage);
|
|
84
80
|
await validateSeal(scanDir, manifest, findings, coverage, documentDigests, options.signal, scanRoot);
|
|
85
81
|
if (options.expectation !== undefined) {
|
|
86
82
|
validateExpectation(manifest, coverage, options.expectation, options.workbenchValidated === true);
|
|
@@ -104,7 +100,11 @@ function normalizePersistedFindings(payload) {
|
|
|
104
100
|
}
|
|
105
101
|
return compatible;
|
|
106
102
|
}
|
|
107
|
-
|
|
103
|
+
/** Match the producer's Python str.strip without changing saved text. */
|
|
104
|
+
export function hasRequiredFindingText(value) {
|
|
105
|
+
return !/^[\p{White_Space}\u001c-\u001f]*$/u.test(value);
|
|
106
|
+
}
|
|
107
|
+
function validateCanonicalContract(manifest, findings, coverage) {
|
|
108
108
|
const remote = manifest.scan.target.remote;
|
|
109
109
|
if (remote !== undefined) {
|
|
110
110
|
const authority = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]+)/.exec(remote)?.[1];
|
|
@@ -141,6 +141,17 @@ function validateCanonicalContract(manifest, findings) {
|
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
|
+
for (const [index, deferred] of coverage.deferred.entries()) {
|
|
145
|
+
for (const [pathIndex, path] of (deferred.paths ?? []).entries()) {
|
|
146
|
+
const context = `coverage.deferred[${index}].paths[${pathIndex}]`;
|
|
147
|
+
try {
|
|
148
|
+
safeRelativePath(path, context, true);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
throw new ContractValidationError(`${context}: expected a safe repository-relative POSIX path.`, { cause: error });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
144
155
|
const findingIds = new Set();
|
|
145
156
|
for (const [findingIndex, finding] of findings.findings.entries()) {
|
|
146
157
|
const context = `findings.findings[${findingIndex}]`;
|
|
@@ -159,8 +170,7 @@ function validateCanonicalContract(manifest, findings) {
|
|
|
159
170
|
? []
|
|
160
171
|
: [["severity.scoringSystem", finding.severity.scoringSystem]]),
|
|
161
172
|
]) {
|
|
162
|
-
|
|
163
|
-
if (/^[\p{White_Space}\u001c-\u001f]*$/u.test(value ?? "")) {
|
|
173
|
+
if (!hasRequiredFindingText(value ?? "")) {
|
|
164
174
|
throw new ContractValidationError(`${context}.${field}: expected a non-empty string.`);
|
|
165
175
|
}
|
|
166
176
|
}
|
|
@@ -176,6 +186,15 @@ function validateCanonicalContract(manifest, findings) {
|
|
|
176
186
|
throw new ContractValidationError(`${locationContext}.endLine: expected an integer >= startLine.`);
|
|
177
187
|
}
|
|
178
188
|
}
|
|
189
|
+
for (const [evidenceIndex, evidence] of (finding.codeEvidence ?? []).entries()) {
|
|
190
|
+
const evidenceContext = `${context}.codeEvidence[${evidenceIndex}].path`;
|
|
191
|
+
try {
|
|
192
|
+
safeRelativePath(evidence.path, evidenceContext);
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
throw new ContractValidationError(`${evidenceContext}: expected a safe repository-relative POSIX path.`, { cause: error });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
179
198
|
const { findingId, occurrenceId, fingerprints } = deriveFindingIdentity(manifest.scan.id, manifest.scan.target.targetId, finding.ruleId, finding.identity);
|
|
180
199
|
if (finding.findingId !== findingId) {
|
|
181
200
|
throw new ContractValidationError(`${context}.findingId: does not match derived fingerprint identity.`);
|
|
@@ -419,11 +438,11 @@ async function verifyScanRoot(root, signal) {
|
|
|
419
438
|
throw new ContractValidationError("Scan directory changed while reading the canonical contract.", { cause: error });
|
|
420
439
|
}
|
|
421
440
|
}
|
|
422
|
-
function safeRelativePath(value, context) {
|
|
441
|
+
function safeRelativePath(value, context, allowDot = false) {
|
|
423
442
|
const parts = value.split("/");
|
|
424
443
|
if (value.length === 0 ||
|
|
425
444
|
Buffer.from(value, "utf8").toString("utf8") !== value ||
|
|
426
|
-
value === "." ||
|
|
445
|
+
(!allowDot && value === ".") ||
|
|
427
446
|
value.startsWith("/") ||
|
|
428
447
|
/^[A-Za-z]:/.test(value) ||
|
|
429
448
|
parts.includes("..") ||
|
|
@@ -432,7 +451,7 @@ function safeRelativePath(value, context) {
|
|
|
432
451
|
throw new ContractValidationError(`${context}: expected a safe scan-relative POSIX path.`);
|
|
433
452
|
}
|
|
434
453
|
const normalized = posix.normalize(value).replace(/\/+$/, "");
|
|
435
|
-
if (normalized === "." ||
|
|
454
|
+
if ((!allowDot && normalized === ".") ||
|
|
436
455
|
normalized.startsWith("../") ||
|
|
437
456
|
isAbsolute(normalized)) {
|
|
438
457
|
throw new ContractValidationError(`${context}: expected a safe scan-relative POSIX path.`);
|
|
@@ -539,6 +558,35 @@ function validateParsedJson(value, context) {
|
|
|
539
558
|
}
|
|
540
559
|
}
|
|
541
560
|
}
|
|
561
|
+
async function loadContractValidators(pluginRoot, signal) {
|
|
562
|
+
// The plugin schemas are the immutable v0 contract. They are valid Draft
|
|
563
|
+
// 2020-12 but intentionally omit redundant local `type` keywords that Ajv's
|
|
564
|
+
// optional strict-schema linter requires.
|
|
565
|
+
const ajv = new Ajv2020({ allErrors: false, strict: false });
|
|
566
|
+
ajv.addFormat("date-time", {
|
|
567
|
+
type: "string",
|
|
568
|
+
validate: validRfc3339DateTime,
|
|
569
|
+
});
|
|
570
|
+
const validators = [];
|
|
571
|
+
for (const [filename, schemaName] of Object.entries(DOCUMENTS)) {
|
|
572
|
+
const schema = await readJson(join(pluginRoot, "schemas", schemaName), signal).catch((error) => {
|
|
573
|
+
throwIfAborted(signal);
|
|
574
|
+
throw new ContractSchemaError(errorMessage(error), { cause: error });
|
|
575
|
+
});
|
|
576
|
+
try {
|
|
577
|
+
const validate = ajv.compile(schema);
|
|
578
|
+
if ("$async" in validate && validate.$async === true) {
|
|
579
|
+
throw new Error("asynchronous JSON Schema validation is unsupported");
|
|
580
|
+
}
|
|
581
|
+
validators.push({ filename, schemaName, validate });
|
|
582
|
+
}
|
|
583
|
+
catch {
|
|
584
|
+
throw new ContractSchemaError(`${schemaName}: invalid JSON Schema.`);
|
|
585
|
+
}
|
|
586
|
+
throwIfAborted(signal);
|
|
587
|
+
}
|
|
588
|
+
return validators;
|
|
589
|
+
}
|
|
542
590
|
async function sha256ScanFile(scanDir, relativePath, context, signal, expectedRoot) {
|
|
543
591
|
const file = await openCheckedScanFile(scanDir, relativePath, context, signal, expectedRoot);
|
|
544
592
|
try {
|