@openai/codex-security 0.5.1 → 0.6.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 +86 -2
- 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/scripts/workbench_finding_workflows.py +2 -0
- package/_bundled_plugin/shared/workbench-migrations.json +16 -0
- package/_bundled_plugin/skills/fix-finding/SKILL.md +16 -8
- package/_bundled_plugin/skills/publish-findings/SKILL.md +130 -0
- package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +6 -0
- package/_bundled_plugin/skills/verify-fix/SKILL.md +4 -2
- package/dist/api.d.ts +3 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +76 -38
- package/dist/api.js.map +1 -1
- package/dist/classify-severity-records.d.ts +5 -2
- package/dist/classify-severity-records.d.ts.map +1 -1
- package/dist/classify-severity-records.js +40 -34
- package/dist/classify-severity-records.js.map +1 -1
- package/dist/classify-severity.d.ts +5 -1
- package/dist/classify-severity.d.ts.map +1 -1
- package/dist/classify-severity.js +20 -30
- package/dist/classify-severity.js.map +1 -1
- package/dist/cli-help.d.ts.map +1 -1
- package/dist/cli-help.js +1 -0
- package/dist/cli-help.js.map +1 -1
- package/dist/cli.d.ts +7 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +412 -14
- package/dist/cli.js.map +1 -1
- package/dist/cloud-endpoint.d.ts +6 -0
- package/dist/cloud-endpoint.d.ts.map +1 -0
- package/dist/cloud-endpoint.js +51 -0
- package/dist/cloud-endpoint.js.map +1 -0
- package/dist/cloud-publish.d.ts.map +1 -1
- package/dist/cloud-publish.js +7 -5
- package/dist/cloud-publish.js.map +1 -1
- package/dist/default-severity-rubric.d.ts +3 -0
- package/dist/default-severity-rubric.d.ts.map +1 -0
- package/dist/default-severity-rubric.js +67 -0
- package/dist/default-severity-rubric.js.map +1 -0
- package/dist/endor-findings.d.ts +7 -0
- package/dist/endor-findings.d.ts.map +1 -0
- package/dist/endor-findings.js +233 -0
- package/dist/endor-findings.js.map +1 -0
- package/dist/external-findings-import.d.ts +5 -0
- package/dist/external-findings-import.d.ts.map +1 -0
- package/dist/external-findings-import.js +38 -0
- package/dist/external-findings-import.js.map +1 -0
- package/dist/external-findings-local.d.ts +63 -0
- package/dist/external-findings-local.d.ts.map +1 -0
- package/dist/external-findings-local.js +337 -0
- package/dist/external-findings-local.js.map +1 -0
- package/dist/external-findings-publish.d.ts +73 -0
- package/dist/external-findings-publish.d.ts.map +1 -0
- package/dist/external-findings-publish.js +713 -0
- package/dist/external-findings-publish.js.map +1 -0
- package/dist/external-findings-read.d.ts +6 -0
- package/dist/external-findings-read.d.ts.map +1 -0
- package/dist/external-findings-read.js +88 -0
- package/dist/external-findings-read.js.map +1 -0
- package/dist/external-findings.d.ts +21 -0
- package/dist/external-findings.d.ts.map +1 -0
- package/dist/external-findings.js +2 -0
- package/dist/external-findings.js.map +1 -0
- package/dist/external-import-contract.d.ts +13 -0
- package/dist/external-import-contract.d.ts.map +1 -0
- package/dist/external-import-contract.js +254 -0
- package/dist/external-import-contract.js.map +1 -0
- package/dist/external-import-models.d.ts +362 -0
- package/dist/external-import-models.d.ts.map +1 -0
- package/dist/external-import-models.js +3 -0
- package/dist/external-import-models.js.map +1 -0
- package/dist/finding-workflow.d.ts +1 -1
- package/dist/finding-workflow.d.ts.map +1 -1
- package/dist/finding-workflow.js +2 -1
- package/dist/finding-workflow.js.map +1 -1
- package/dist/github-advisories.d.ts +386 -0
- package/dist/github-advisories.d.ts.map +1 -0
- package/dist/github-advisories.js +131 -0
- package/dist/github-advisories.js.map +1 -0
- package/dist/github-findings.d.ts +10 -0
- package/dist/github-findings.d.ts.map +1 -0
- package/dist/github-findings.js +256 -0
- package/dist/github-findings.js.map +1 -0
- package/dist/hosted-remediation-protocol.d.ts +2 -1
- package/dist/hosted-remediation-protocol.d.ts.map +1 -1
- package/dist/hosted-remediation-protocol.js +17 -11
- package/dist/hosted-remediation-protocol.js.map +1 -1
- package/dist/hosted-remediation.d.ts +4 -0
- package/dist/hosted-remediation.d.ts.map +1 -1
- package/dist/hosted-remediation.js +3 -1
- package/dist/hosted-remediation.js.map +1 -1
- package/dist/hosted-scan.d.ts +16 -0
- package/dist/hosted-scan.d.ts.map +1 -1
- package/dist/hosted-scan.js +14 -2
- package/dist/hosted-scan.js.map +1 -1
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -0
- package/dist/index.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 +2 -0
- package/dist/project-config.js.map +1 -1
- package/dist/remediation.d.ts +6 -0
- package/dist/remediation.d.ts.map +1 -1
- package/dist/remediation.js +16 -5
- package/dist/remediation.js.map +1 -1
- package/dist/result.d.ts +4 -0
- package/dist/result.d.ts.map +1 -1
- package/dist/result.js +10 -0
- package/dist/result.js.map +1 -1
- package/dist/runtime.d.ts +1 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +3 -1
- package/dist/runtime.js.map +1 -1
- package/dist/scan-owner-suggestions.d.ts +8 -0
- package/dist/scan-owner-suggestions.d.ts.map +1 -0
- package/dist/scan-owner-suggestions.js +33 -0
- package/dist/scan-owner-suggestions.js.map +1 -0
- package/dist/scan-settings.d.ts +1 -0
- package/dist/scan-settings.d.ts.map +1 -1
- package/dist/scan-settings.js +4 -0
- package/dist/scan-settings.js.map +1 -1
- package/dist/scanner-import.d.ts +20 -0
- package/dist/scanner-import.d.ts.map +1 -0
- package/dist/scanner-import.js +204 -0
- package/dist/scanner-import.js.map +1 -0
- package/dist/security-policy-diff.d.ts +2 -0
- package/dist/security-policy-diff.d.ts.map +1 -0
- package/dist/security-policy-diff.js +197 -0
- package/dist/security-policy-diff.js.map +1 -0
- package/dist/security-policy.d.ts +7 -3
- package/dist/security-policy.d.ts.map +1 -1
- package/dist/security-policy.js +10 -56
- package/dist/security-policy.js.map +1 -1
- package/dist/semgrep-findings.d.ts +9 -0
- package/dist/semgrep-findings.d.ts.map +1 -0
- package/dist/semgrep-findings.js +293 -0
- package/dist/semgrep-findings.js.map +1 -0
- package/dist/severity-review.d.ts +3 -0
- package/dist/severity-review.d.ts.map +1 -1
- package/dist/severity-review.js +19 -0
- package/dist/severity-review.js.map +1 -1
- package/dist/severity-store.js +7 -2
- package/dist/severity-store.js.map +1 -1
- package/dist/snyk-findings.d.ts +9 -0
- package/dist/snyk-findings.d.ts.map +1 -0
- package/dist/snyk-findings.js +349 -0
- package/dist/snyk-findings.js.map +1 -0
- package/dist/targets.d.ts +2 -2
- package/dist/targets.d.ts.map +1 -1
- package/dist/targets.js +12 -2
- package/dist/targets.js.map +1 -1
- package/dist/wiz-csv.d.ts +8 -0
- package/dist/wiz-csv.d.ts.map +1 -0
- package/dist/wiz-csv.js +116 -0
- package/dist/wiz-csv.js.map +1 -0
- package/dist/wiz-findings.d.ts +4 -0
- package/dist/wiz-findings.d.ts.map +1 -0
- package/dist/wiz-findings.js +460 -0
- package/dist/wiz-findings.js.map +1 -0
- package/docs/classify-severity-records.md +28 -10
- package/docs/cli.md +702 -31
- package/docs/hosted-remediation.md +24 -7
- package/docs/hosted-scans.md +12 -0
- package/package.json +6 -4
- package/schemas/external-findings.schema.json +1421 -0
- package/schemas/project-config.schema.json +4 -0
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const DEFAULT_CLOUD_BASE_URL = "https://chatgpt.com/backend-api/aardvark";
|
|
2
|
+
/** Custom deployments can serve their UI separately from the authenticated API. */
|
|
3
|
+
export declare function cloudFindingsUrl(environment: NodeJS.ProcessEnv, repositoryId: string): string | undefined;
|
|
4
|
+
/** Resolve the deployment once so discovery, writes, and retries share a host. */
|
|
5
|
+
export declare function cloudBaseUrl(environment: NodeJS.ProcessEnv): string;
|
|
6
|
+
//# sourceMappingURL=cloud-endpoint.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloud-endpoint.d.ts","sourceRoot":"","sources":["../src/cloud-endpoint.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,sBAAsB,6CACS,CAAC;AAK7C,mFAAmF;AACnF,wBAAgB,gBAAgB,CAC9B,WAAW,EAAE,MAAM,CAAC,UAAU,EAC9B,YAAY,EAAE,MAAM,GACnB,MAAM,GAAG,SAAS,CAuBpB;AAED,kFAAkF;AAClF,wBAAgB,YAAY,CAAC,WAAW,EAAE,MAAM,CAAC,UAAU,GAAG,MAAM,CA+BnE"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { isIP } from "node:net";
|
|
2
|
+
import { CodexSecurityError } from "./errors.js";
|
|
3
|
+
export const DEFAULT_CLOUD_BASE_URL = "https://chatgpt.com/backend-api/aardvark";
|
|
4
|
+
const CLOUD_APP_PATH = "/mcp-app/connector_openai_defense_factory/open_defense_factory";
|
|
5
|
+
/** Custom deployments can serve their UI separately from the authenticated API. */
|
|
6
|
+
export function cloudFindingsUrl(environment, repositoryId) {
|
|
7
|
+
const configured = environment["CODEX_SECURITY_CLOUD_WEB_URL"];
|
|
8
|
+
const api = new URL(cloudBaseUrl(environment));
|
|
9
|
+
const hosted = api.href === DEFAULT_CLOUD_BASE_URL;
|
|
10
|
+
if (configured === undefined && !hosted)
|
|
11
|
+
return undefined;
|
|
12
|
+
let url;
|
|
13
|
+
try {
|
|
14
|
+
url = new URL(configured?.trim() ?? `${api.origin}${CLOUD_APP_PATH}`);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
throw new CodexSecurityError("CODEX_SECURITY_CLOUD_WEB_URL must be an absolute HTTP(S) Cloud app URL.");
|
|
18
|
+
}
|
|
19
|
+
if (!["https:", "http:"].includes(url.protocol) ||
|
|
20
|
+
url.username ||
|
|
21
|
+
url.password)
|
|
22
|
+
throw new CodexSecurityError("CODEX_SECURITY_CLOUD_WEB_URL must be an HTTP(S) Cloud app URL without credentials.");
|
|
23
|
+
url.hash = `/repositories/${encodeURIComponent(repositoryId)}/findings`;
|
|
24
|
+
return url.href;
|
|
25
|
+
}
|
|
26
|
+
/** Resolve the deployment once so discovery, writes, and retries share a host. */
|
|
27
|
+
export function cloudBaseUrl(environment) {
|
|
28
|
+
const configured = environment["CODEX_SECURITY_CLOUD_BASE_URL"];
|
|
29
|
+
if (configured === undefined)
|
|
30
|
+
return DEFAULT_CLOUD_BASE_URL;
|
|
31
|
+
let url;
|
|
32
|
+
try {
|
|
33
|
+
url = new URL(configured.trim());
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new CodexSecurityError("CODEX_SECURITY_CLOUD_BASE_URL must be an absolute HTTP(S) Cloud API base URL.");
|
|
37
|
+
}
|
|
38
|
+
if (!["https:", "http:"].includes(url.protocol) ||
|
|
39
|
+
url.username ||
|
|
40
|
+
url.password ||
|
|
41
|
+
url.search ||
|
|
42
|
+
url.hash)
|
|
43
|
+
throw new CodexSecurityError("CODEX_SECURITY_CLOUD_BASE_URL must be an HTTP(S) Cloud API base URL without credentials, a query, or a fragment.");
|
|
44
|
+
if (url.protocol === "http:" &&
|
|
45
|
+
url.hostname !== "localhost" &&
|
|
46
|
+
url.hostname !== "[::1]" &&
|
|
47
|
+
!(isIP(url.hostname) === 4 && url.hostname.startsWith("127.")))
|
|
48
|
+
throw new CodexSecurityError("CODEX_SECURITY_CLOUD_BASE_URL requires HTTPS for remote Cloud APIs; HTTP is supported only for loopback development.");
|
|
49
|
+
return url.href.replace(/\/+$/u, "");
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=cloud-endpoint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloud-endpoint.js","sour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,GAAG,WAAW,CAAC,+BAA+B,CAAC,CAAC;IAChE,IAAI,UAAU,KAAK,SAAS;QAAE,OAAO,sBAAsB,CAAC;IAC5D,IAAI,GAAQ,CAAC;IACb,IAAI,CAAC;QACH,GAAG,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC;IACnC,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,kBAAkB,CAC1B,+EAA+E,CAChF,CAAC;IACJ,CAAC;IACD,IACE,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC3C,GAAG,CAAC,QAAQ;QACZ,GAAG,CAAC,QAAQ;QACZ,GAAG,CAAC,MAAM;QACV,GAAG,CAAC,IAAI;QAER,MAAM,IAAI,kBAAkB,CAC1B,kHAAkH,CACnH,CAAC;IACJ,IACE,GAAG,CAAC,QAAQ,KAAK,OAAO;QACxB,GAAG,CAAC,QAAQ,KAAK,WAAW;QAC5B,GAAG,CAAC,QAAQ,KAAK,OAAO;QACxB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QAE9D,MAAM,IAAI,kBAAkB,CAC1B,sHAAsH,CACvH,CAAC;IACJ,OAAO,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import { isIP } from \"node:net\";\nimport { CodexSecurityError } from \"./errors.js\";\n\nexport const DEFAULT_CLOUD_BASE_URL =\n \"https://chatgpt.com/backend-api/aardvark\";\n\nconst CLOUD_APP_PATH =\n \"/mcp-app/connector_openai_defense_factory/open_defense_factory\";\n\n/** Custom deployments can serve their UI separately from the authenticated API. */\nexport function cloudFindingsUrl(\n environment: NodeJS.ProcessEnv,\n repositoryId: string,\n): string | undefined {\n const configured = environment[\"CODEX_SECURITY_CLOUD_WEB_URL\"];\n const api = new URL(cloudBaseUrl(environment));\n const hosted = api.href === DEFAULT_CLOUD_BASE_URL;\n if (configured === undefined && !hosted) return undefined;\n let url: URL;\n try {\n url = new URL(configured?.trim() ?? `${api.origin}${CLOUD_APP_PATH}`);\n } catch {\n throw new CodexSecurityError(\n \"CODEX_SECURITY_CLOUD_WEB_URL must be an absolute HTTP(S) Cloud app URL.\",\n );\n }\n if (\n ![\"https:\", \"http:\"].includes(url.protocol) ||\n url.username ||\n url.password\n )\n throw new CodexSecurityError(\n \"CODEX_SECURITY_CLOUD_WEB_URL must be an HTTP(S) Cloud app URL without credentials.\",\n );\n url.hash = `/repositories/${encodeURIComponent(repositoryId)}/findings`;\n return url.href;\n}\n\n/** Resolve the deployment once so discovery, writes, and retries share a host. */\nexport function cloudBaseUrl(environment: NodeJS.ProcessEnv): string {\n const configured = environment[\"CODEX_SECURITY_CLOUD_BASE_URL\"];\n if (configured === undefined) return DEFAULT_CLOUD_BASE_URL;\n let url: URL;\n try {\n url = new URL(configured.trim());\n } catch {\n throw new CodexSecurityError(\n \"CODEX_SECURITY_CLOUD_BASE_URL must be an absolute HTTP(S) Cloud API base URL.\",\n );\n }\n if (\n ![\"https:\", \"http:\"].includes(url.protocol) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n )\n throw new CodexSecurityError(\n \"CODEX_SECURITY_CLOUD_BASE_URL must be an HTTP(S) Cloud API base URL without credentials, a query, or a fragment.\",\n );\n if (\n url.protocol === \"http:\" &&\n url.hostname !== \"localhost\" &&\n url.hostname !== \"[::1]\" &&\n !(isIP(url.hostname) === 4 && url.hostname.startsWith(\"127.\"))\n )\n throw new CodexSecurityError(\n \"CODEX_SECURITY_CLOUD_BASE_URL requires HTTPS for remote Cloud APIs; HTTP is supported only for loopback development.\",\n );\n return url.href.replace(/\\/+$/u, \"\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloud-publish.d.ts","sourceRoot":"","sources":["../src/cloud-publish.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,OAAO,EAAgB,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"cloud-publish.d.ts","sourceRoot":"","sources":["../src/cloud-publish.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,OAAO,EAAgB,MAAM,aAAa,CAAC;AAkCzD,MAAM,WAAW,sBAAsB;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAC;CACtB;AAED,UAAU,4BAA4B;IACpC,WAAW,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IAChC,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;IACjE,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,wBAAsB,kBAAkB,CACtC,aAAa,EAAE,MAAM,EACrB,YAAY,GAAE,4BAA4B,GAAG;IAC3C,cAAc,CAAC,EAAE,MAAM,CAAC;CACpB,GACL,OAAO,CAAC,sBAAsB,CAAC,CAYjC;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,MAAM,EACf,YAAY,GAAE,4BAAiC,GAC9C,OAAO,CAAC,sBAAsB,CAAC,CA6FjC"}
|
package/dist/cloud-publish.js
CHANGED
|
@@ -8,7 +8,7 @@ import { AuthenticationRequiredError, CodexSecurityError, errorMessage, } from "
|
|
|
8
8
|
import { CSV_TARGET_ID, bindImportedFindings, csvRowFinding, parseFindingsCsv, } from "./findings-import.js";
|
|
9
9
|
import { bundledPluginRoot, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, expandHome, } from "./runtime.js";
|
|
10
10
|
import { VERSION } from "./version.js";
|
|
11
|
-
|
|
11
|
+
import { cloudBaseUrl } from "./cloud-endpoint.js";
|
|
12
12
|
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.";
|
|
13
13
|
const credentialsSchema = z.object({
|
|
14
14
|
auth_mode: z.literal("chatgpt").optional(),
|
|
@@ -126,9 +126,10 @@ async function publishCloudPayload(scan, findings, dependencies) {
|
|
|
126
126
|
findings,
|
|
127
127
|
};
|
|
128
128
|
}
|
|
129
|
-
const
|
|
130
|
-
const publishUrl =
|
|
131
|
-
|
|
129
|
+
const environment = dependencies.environment ?? process.env;
|
|
130
|
+
const publishUrl = environment["CODEX_SECURITY_CLOUD_PUBLISH_URL"]?.trim() ||
|
|
131
|
+
`${cloudBaseUrl(environment)}/cli/findings`;
|
|
132
|
+
const credentials = await readCloudCredentials(environment);
|
|
132
133
|
const timeout = AbortSignal.timeout(30_000);
|
|
133
134
|
const signal = dependencies.signal
|
|
134
135
|
? AbortSignal.any([dependencies.signal, timeout])
|
|
@@ -188,7 +189,8 @@ async function publishCloudPayload(scan, findings, dependencies) {
|
|
|
188
189
|
findingCount: receipt.data.finding_count,
|
|
189
190
|
};
|
|
190
191
|
}
|
|
191
|
-
|
|
192
|
+
/** @internal Shared sign-in for local Cloud publishers. */
|
|
193
|
+
export async function readCloudCredentials(environment) {
|
|
192
194
|
const configuredHome = environment["CODEX_HOME"];
|
|
193
195
|
let home = expandHome(configuredHome?.trim() ? configuredHome : "~/.codex", environment);
|
|
194
196
|
let requireFileStorage = true;
|
|
@@ -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,kBAA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AAE,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"]}
|
|
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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iB,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\";\nimport { cloudBaseUrl } from \"./cloud-endpoint.js\";\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 environment = dependencies.environment ?? process.env;\n const publishUrl =\n environment[\"CODEX_SECURITY_CLOUD_PUBLISH_URL\"]?.trim() ||\n `${cloudBaseUrl(environment)}/cli/findings`;\n const credentials = await readCloudCredentials(environment);\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\n/** @internal Shared sign-in for local Cloud publishers. */\nexport async 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"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** Built into the CLI and SDK so classification needs no external policy file. */
|
|
2
|
+
export declare const defaultSeverityRubric = "# Severity guidance\n\nJudge the attacker's actual starting access, the security boundary crossed, and\nthe additional unauthorized harm. Use the supplied report and evidence; do not\nperform new validation. Keep confidence separate from severity and identify the\nmissing fact that could change the assessment. Missing proof alone does not\nestablish that a broader attack is impossible; do not invent an attack path or\ndowngrade merely because exploitation was not demonstrated.\n\n## Critical\n\nReserve Critical for consequential, strongly supported compromise meeting all\nthree conditions:\n- Access: an unauthenticated internet attacker, ordinary external user, or\n publicly admitted untrusted workload can exploit the interface without\n employee-only access, an invitation, an approved business relationship, or\n compromise of a trusted supplier.\n- Impact: crossing an important security boundary enables consequential access\n to protected data, privileged actions, meaningful code execution, workload\n escape, or comparable compromise of the affected system.\n- Evidence: demonstrated exploitation or strong source-backed validation\n establishes the complete attack path.\n\nSecond-order attacks can qualify: an external attacker plants data that a trusted\nuser or system later processes, causing consequential unauthorized access or\nprivileged actions.\n\n## High\n\nAssign High when a realistic, evidenced path gives a lower-trust attacker a\nsubstantial unauthorized capability they did not already possess. Internal\nusers, partners, invited collaborators, and admitted untrusted workloads can\nqualify; unauthenticated internet access is not required. Consequences include\nsensitive customer or business data or reusable credentials, account takeover,\nmeaningful cross-tenant access or actions as another user, control of production\nworkloads or deployments, privileged identities, encryption keys or important\nisolation boundaries, or significant repeatable disruption of a critical or\nshared service. A dangerous function, production label, internal access, or the\nexistence of a privileged credential alone is insufficient: identify the\nlower-trust actor, boundary crossing, and consequential new capability.\n\n## Medium\n\nAssign Medium to a credible vulnerability with concretely bounded impact, such\nas nonsecret operational information, narrow unauthorized changes, contained\ndisruption of a noncritical service, or isolated development or staging systems\nwithout a consequential pivot. A fully demonstrated vulnerability can still be\nMedium. Base a downgrade on verified constraints, not on an assumption that\nmissing evidence rules out broader harm.\n\n## Low\n\nAssign Low to a supported security weakness with minor additional unauthorized\nharm and verified limits on its scope, sensitivity, or duration, such as a small\ninformation exposure with little security value or a narrowly contained nuisance.\nDo not use Low as a substitute for uncertainty about a potentially serious path.\n\n## Informational\n\nAssign Informational to a hardening opportunity or observation for which the\nsupplied evidence establishes no additional unauthorized capability or security\nimpact. Explain why it is informational rather than treating missing proof of\nexploitation as proof of safety. Administrative records that do not describe a\nsecurity finding may be excluded; exclusion is distinct from severity.\n";
|
|
3
|
+
//# sourceMappingURL=default-severity-rubric.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"default-severity-rubric.d.ts","sourceRoot":"","sources":["../src/default-severity-rubric.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,eAAO,MAAM,qBAAqB,m4GAgEjC,CAAC"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** Built into the CLI and SDK so classification needs no external policy file. */
|
|
2
|
+
export const defaultSeverityRubric = `# Severity guidance
|
|
3
|
+
|
|
4
|
+
Judge the attacker's actual starting access, the security boundary crossed, and
|
|
5
|
+
the additional unauthorized harm. Use the supplied report and evidence; do not
|
|
6
|
+
perform new validation. Keep confidence separate from severity and identify the
|
|
7
|
+
missing fact that could change the assessment. Missing proof alone does not
|
|
8
|
+
establish that a broader attack is impossible; do not invent an attack path or
|
|
9
|
+
downgrade merely because exploitation was not demonstrated.
|
|
10
|
+
|
|
11
|
+
## Critical
|
|
12
|
+
|
|
13
|
+
Reserve Critical for consequential, strongly supported compromise meeting all
|
|
14
|
+
three conditions:
|
|
15
|
+
- Access: an unauthenticated internet attacker, ordinary external user, or
|
|
16
|
+
publicly admitted untrusted workload can exploit the interface without
|
|
17
|
+
employee-only access, an invitation, an approved business relationship, or
|
|
18
|
+
compromise of a trusted supplier.
|
|
19
|
+
- Impact: crossing an important security boundary enables consequential access
|
|
20
|
+
to protected data, privileged actions, meaningful code execution, workload
|
|
21
|
+
escape, or comparable compromise of the affected system.
|
|
22
|
+
- Evidence: demonstrated exploitation or strong source-backed validation
|
|
23
|
+
establishes the complete attack path.
|
|
24
|
+
|
|
25
|
+
Second-order attacks can qualify: an external attacker plants data that a trusted
|
|
26
|
+
user or system later processes, causing consequential unauthorized access or
|
|
27
|
+
privileged actions.
|
|
28
|
+
|
|
29
|
+
## High
|
|
30
|
+
|
|
31
|
+
Assign High when a realistic, evidenced path gives a lower-trust attacker a
|
|
32
|
+
substantial unauthorized capability they did not already possess. Internal
|
|
33
|
+
users, partners, invited collaborators, and admitted untrusted workloads can
|
|
34
|
+
qualify; unauthenticated internet access is not required. Consequences include
|
|
35
|
+
sensitive customer or business data or reusable credentials, account takeover,
|
|
36
|
+
meaningful cross-tenant access or actions as another user, control of production
|
|
37
|
+
workloads or deployments, privileged identities, encryption keys or important
|
|
38
|
+
isolation boundaries, or significant repeatable disruption of a critical or
|
|
39
|
+
shared service. A dangerous function, production label, internal access, or the
|
|
40
|
+
existence of a privileged credential alone is insufficient: identify the
|
|
41
|
+
lower-trust actor, boundary crossing, and consequential new capability.
|
|
42
|
+
|
|
43
|
+
## Medium
|
|
44
|
+
|
|
45
|
+
Assign Medium to a credible vulnerability with concretely bounded impact, such
|
|
46
|
+
as nonsecret operational information, narrow unauthorized changes, contained
|
|
47
|
+
disruption of a noncritical service, or isolated development or staging systems
|
|
48
|
+
without a consequential pivot. A fully demonstrated vulnerability can still be
|
|
49
|
+
Medium. Base a downgrade on verified constraints, not on an assumption that
|
|
50
|
+
missing evidence rules out broader harm.
|
|
51
|
+
|
|
52
|
+
## Low
|
|
53
|
+
|
|
54
|
+
Assign Low to a supported security weakness with minor additional unauthorized
|
|
55
|
+
harm and verified limits on its scope, sensitivity, or duration, such as a small
|
|
56
|
+
information exposure with little security value or a narrowly contained nuisance.
|
|
57
|
+
Do not use Low as a substitute for uncertainty about a potentially serious path.
|
|
58
|
+
|
|
59
|
+
## Informational
|
|
60
|
+
|
|
61
|
+
Assign Informational to a hardening opportunity or observation for which the
|
|
62
|
+
supplied evidence establishes no additional unauthorized capability or security
|
|
63
|
+
impact. Explain why it is informational rather than treating missing proof of
|
|
64
|
+
exploitation as proof of safety. Administrative records that do not describe a
|
|
65
|
+
security finding may be excluded; exclusion is distinct from severity.
|
|
66
|
+
`;
|
|
67
|
+
//# sourceMappingURL=default-severity-rubric.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"default-severity-rubric.js","sourceRoot":"","sources":["../src/default-severity-rubric.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgEpC,CAAC","sourcesContent":["/** Built into the CLI and SDK so classification needs no external policy file. */\nexport const defaultSeverityRubric = `# Severity guidance\n\nJudge the attacker's actual starting access, the security boundary crossed, and\nthe additional unauthorized harm. Use the supplied report and evidence; do not\nperform new validation. Keep confidence separate from severity and identify the\nmissing fact that could change the assessment. Missing proof alone does not\nestablish that a broader attack is impossible; do not invent an attack path or\ndowngrade merely because exploitation was not demonstrated.\n\n## Critical\n\nReserve Critical for consequential, strongly supported compromise meeting all\nthree conditions:\n- Access: an unauthenticated internet attacker, ordinary external user, or\n publicly admitted untrusted workload can exploit the interface without\n employee-only access, an invitation, an approved business relationship, or\n compromise of a trusted supplier.\n- Impact: crossing an important security boundary enables consequential access\n to protected data, privileged actions, meaningful code execution, workload\n escape, or comparable compromise of the affected system.\n- Evidence: demonstrated exploitation or strong source-backed validation\n establishes the complete attack path.\n\nSecond-order attacks can qualify: an external attacker plants data that a trusted\nuser or system later processes, causing consequential unauthorized access or\nprivileged actions.\n\n## High\n\nAssign High when a realistic, evidenced path gives a lower-trust attacker a\nsubstantial unauthorized capability they did not already possess. Internal\nusers, partners, invited collaborators, and admitted untrusted workloads can\nqualify; unauthenticated internet access is not required. Consequences include\nsensitive customer or business data or reusable credentials, account takeover,\nmeaningful cross-tenant access or actions as another user, control of production\nworkloads or deployments, privileged identities, encryption keys or important\nisolation boundaries, or significant repeatable disruption of a critical or\nshared service. A dangerous function, production label, internal access, or the\nexistence of a privileged credential alone is insufficient: identify the\nlower-trust actor, boundary crossing, and consequential new capability.\n\n## Medium\n\nAssign Medium to a credible vulnerability with concretely bounded impact, such\nas nonsecret operational information, narrow unauthorized changes, contained\ndisruption of a noncritical service, or isolated development or staging systems\nwithout a consequential pivot. A fully demonstrated vulnerability can still be\nMedium. Base a downgrade on verified constraints, not on an assumption that\nmissing evidence rules out broader harm.\n\n## Low\n\nAssign Low to a supported security weakness with minor additional unauthorized\nharm and verified limits on its scope, sensitivity, or duration, such as a small\ninformation exposure with little security value or a narrowly contained nuisance.\nDo not use Low as a substitute for uncertainty about a potentially serious path.\n\n## Informational\n\nAssign Informational to a hardening opportunity or observation for which the\nsupplied evidence establishes no additional unauthorized capability or security\nimpact. Explain why it is informational rather than treating missing proof of\nexploitation as proof of safety. Administrative records that do not describe a\nsecurity finding may be excluded; exclusion is distinct from severity.\n`;\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ExternalFindings } from "./external-findings.js";
|
|
2
|
+
/** Saved Endor Finding objects, an array, or an unmasked ListFindingsResponse. */
|
|
3
|
+
export declare function normalizeEndorFindings(input: unknown): ExternalFindings;
|
|
4
|
+
/** Endor's documented SARIF producer uses properties.finding-uuid, not its rule name. */
|
|
5
|
+
export declare function normalizeEndorSarif(input: unknown): ExternalFindings;
|
|
6
|
+
export declare function readEndorFindings(path: string): Promise<ExternalFindings>;
|
|
7
|
+
//# sourceMappingURL=endor-findings.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endor-findings.d.ts","sourceRoot":"","sources":["../src/endor-findings.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AA+B/D,kFAAkF;AAClF,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,gBAAgB,CA6IvE;AAED,yFAAyF;AACzF,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,gBAAgB,CAuKpE;AAED,wBAAsB,iBAAiB,CACrC,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,gBAAgB,CAAC,CAE3B"}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { validateExternalEvidence } from "./external-import-contract.js";
|
|
2
|
+
import { isRecord } from "./record.js";
|
|
3
|
+
import { array, hasSarifExternalPropertyReferences, normalizeRecords, readScannerJson, record, relativePath, requiredText, sarifRunContextForResult, strings, text, } from "./scanner-import.js";
|
|
4
|
+
/** @internal Repository claims retained in the adapter's original SARIF context. */
|
|
5
|
+
export function endorRepositoryUrls(sourceData) {
|
|
6
|
+
if (!isRecord(sourceData))
|
|
7
|
+
return [];
|
|
8
|
+
const run = sourceData["runContext"];
|
|
9
|
+
if (run == null)
|
|
10
|
+
return [];
|
|
11
|
+
return array(record(run, "Endor run context")["versionControlProvenance"] ?? [], "Endor version control provenance").map((entry) => requiredText(record(entry, "Endor repository provenance")["repositoryUri"], "Endor repository URI"));
|
|
12
|
+
}
|
|
13
|
+
/** Saved Endor Finding objects, an array, or an unmasked ListFindingsResponse. */
|
|
14
|
+
export function normalizeEndorFindings(input) {
|
|
15
|
+
const root = Array.isArray(input) ? null : record(input, "Endor report");
|
|
16
|
+
if (root?.["version"] === "2.1.0" && root["runs"] !== undefined)
|
|
17
|
+
return normalizeEndorSarif(root);
|
|
18
|
+
const list = root?.["list"] === undefined ? null : record(root["list"], "Endor list");
|
|
19
|
+
if (list) {
|
|
20
|
+
const response = record(list["response"] ?? {}, "Endor list response");
|
|
21
|
+
const token = response["next_page_token"];
|
|
22
|
+
if (text(response["next_page_id"]) ||
|
|
23
|
+
(token != null && token !== 0 && token !== "0" && token !== "")) {
|
|
24
|
+
throw new Error("The Endor list response has another page. Supply a complete export or an explicitly selected array.");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const values = list
|
|
28
|
+
? array(list["objects"] ?? [], "Endor list.objects")
|
|
29
|
+
: Array.isArray(input)
|
|
30
|
+
? input
|
|
31
|
+
: [input];
|
|
32
|
+
return normalizeRecords(values, (value, id) => {
|
|
33
|
+
const finding = record(value, "Endor finding");
|
|
34
|
+
const meta = record(finding["meta"], "Endor meta");
|
|
35
|
+
const spec = record(finding["spec"], "Endor spec");
|
|
36
|
+
requiredText(spec["project_uuid"], "Endor project_uuid");
|
|
37
|
+
const name = text(spec["target_dependency_name"]);
|
|
38
|
+
const paths = [
|
|
39
|
+
...new Set(strings(spec["dependency_file_paths"])
|
|
40
|
+
.map(relativePath)
|
|
41
|
+
.filter((p) => p !== null)),
|
|
42
|
+
];
|
|
43
|
+
const metadata = record(spec["finding_metadata"] ?? {}, "Endor finding_metadata");
|
|
44
|
+
const codeLocations = ["sast_data", "ai_sast_data"].flatMap((field) => {
|
|
45
|
+
const data = record(metadata[field] ?? {}, `Endor ${field}`);
|
|
46
|
+
const location = record(data["location"] ?? {}, `Endor ${field} location`);
|
|
47
|
+
const path = relativePath(location["relative_path"]);
|
|
48
|
+
if (path === null)
|
|
49
|
+
return [];
|
|
50
|
+
const line = location["start_line"];
|
|
51
|
+
return [
|
|
52
|
+
{
|
|
53
|
+
path,
|
|
54
|
+
line: typeof line === "number" && Number.isSafeInteger(line) && line > 0
|
|
55
|
+
? line
|
|
56
|
+
: null,
|
|
57
|
+
},
|
|
58
|
+
];
|
|
59
|
+
});
|
|
60
|
+
const locations = [
|
|
61
|
+
...paths
|
|
62
|
+
.filter((path) => !codeLocations.some((location) => location.path === path))
|
|
63
|
+
.map((path) => ({ path })),
|
|
64
|
+
...new Map(codeLocations.map((location) => [JSON.stringify(location), location])).values(),
|
|
65
|
+
];
|
|
66
|
+
const vulnerability = record(metadata["vulnerability"] ?? {}, "Endor vulnerability");
|
|
67
|
+
const advisory = text(record(vulnerability["meta"] ?? {}, "Vulnerability meta")["name"]);
|
|
68
|
+
const aliases = strings(record(vulnerability["spec"] ?? {}, "Vulnerability spec")["aliases"]);
|
|
69
|
+
const level = text(spec["level"])
|
|
70
|
+
?.replace(/^FINDING_LEVEL_/u, "")
|
|
71
|
+
.toLowerCase();
|
|
72
|
+
const severity = level && ["critical", "high", "medium", "low"].includes(level)
|
|
73
|
+
? level
|
|
74
|
+
: "unknown";
|
|
75
|
+
// A recommended version can refer to an introducing dependency; retain it in source_data.
|
|
76
|
+
const packages = name
|
|
77
|
+
? (paths.length ? paths : [null]).map((path) => ({
|
|
78
|
+
name,
|
|
79
|
+
ecosystem: text(spec["ecosystem"])
|
|
80
|
+
?.replace(/^ECOSYSTEM_/u, "")
|
|
81
|
+
.toLowerCase() ?? null,
|
|
82
|
+
installed_version: text(spec["target_dependency_version"]),
|
|
83
|
+
manifest_path: path,
|
|
84
|
+
fixed_versions: [],
|
|
85
|
+
}))
|
|
86
|
+
: [];
|
|
87
|
+
const context = record(finding["context"] ?? {}, "Endor context");
|
|
88
|
+
const updated = text(meta["update_time"]);
|
|
89
|
+
return {
|
|
90
|
+
source_finding_id: id,
|
|
91
|
+
evidence: validateExternalEvidence({
|
|
92
|
+
title: requiredText(meta["name"], "Endor finding title"),
|
|
93
|
+
description: [
|
|
94
|
+
text(spec["summary"]),
|
|
95
|
+
text(spec["explanation"]),
|
|
96
|
+
text(spec["remediation"]),
|
|
97
|
+
]
|
|
98
|
+
.filter(Boolean)
|
|
99
|
+
.join("\n\n") || text(meta["description"]),
|
|
100
|
+
severity,
|
|
101
|
+
branch: context["type"] === "CONTEXT_TYPE_REF" ? text(context["id"]) : null,
|
|
102
|
+
code_revision: text(record(spec["source_code_version"] ?? {}, "Endor source code version")["sha"]),
|
|
103
|
+
source_updated_at: updated === null ? null : Math.floor(Date.parse(updated) / 1000),
|
|
104
|
+
advisory_ids: [
|
|
105
|
+
...new Set([...(advisory ? [advisory] : []), ...aliases]),
|
|
106
|
+
],
|
|
107
|
+
packages,
|
|
108
|
+
locations,
|
|
109
|
+
source_data: structuredClone(finding),
|
|
110
|
+
}),
|
|
111
|
+
};
|
|
112
|
+
}, (value) => requiredText(record(value, "Endor finding")["uuid"], "Endor finding uuid"));
|
|
113
|
+
}
|
|
114
|
+
/** Endor's documented SARIF producer uses properties.finding-uuid, not its rule name. */
|
|
115
|
+
export function normalizeEndorSarif(input) {
|
|
116
|
+
const document = record(input, "Endor SARIF");
|
|
117
|
+
if (document["version"] !== "2.1.0")
|
|
118
|
+
throw new Error("Expected Endor SARIF 2.1.0.");
|
|
119
|
+
const entries = array(document["runs"], "SARIF runs").flatMap((value) => {
|
|
120
|
+
const run = record(value, "SARIF run");
|
|
121
|
+
const tool = record(run["tool"], "SARIF tool");
|
|
122
|
+
const driver = record(tool["driver"], "SARIF driver");
|
|
123
|
+
if (driver["name"] !== "endorctl")
|
|
124
|
+
throw new Error("Expected the endorctl SARIF producer.");
|
|
125
|
+
if (hasSarifExternalPropertyReferences(run["externalPropertyFileReferences"]))
|
|
126
|
+
throw new Error("Use a self-contained Endor SARIF report.");
|
|
127
|
+
const rules = array(driver["rules"] ?? [], "Endor rules").map((r) => record(r, "Endor rule"));
|
|
128
|
+
const rulesById = new Map();
|
|
129
|
+
for (const [index, rule] of rules.entries()) {
|
|
130
|
+
const id = rule["id"];
|
|
131
|
+
rulesById.set(id, rulesById.has(id) ? null : { rule, index });
|
|
132
|
+
}
|
|
133
|
+
const { runs: _runs, ...documentContext } = document;
|
|
134
|
+
const { results: _results, tool: _tool, ...runContext } = run;
|
|
135
|
+
const { rules: _rules, ...driverContext } = driver;
|
|
136
|
+
const { driver: _driver, ...toolContext } = tool;
|
|
137
|
+
return array(run["results"] ?? [], "Endor results").map((result) => ({
|
|
138
|
+
result,
|
|
139
|
+
rulesById,
|
|
140
|
+
documentContext,
|
|
141
|
+
runContext,
|
|
142
|
+
driverContext,
|
|
143
|
+
toolContext,
|
|
144
|
+
}));
|
|
145
|
+
});
|
|
146
|
+
return normalizeRecords(entries, ({ result: value, rulesById, ...context }, id) => {
|
|
147
|
+
const result = record(value, "Endor result");
|
|
148
|
+
const properties = record(result["properties"], "Endor result properties");
|
|
149
|
+
requiredText(properties["project-uuid"], "Endor project-uuid");
|
|
150
|
+
const ruleId = requiredText(result["ruleId"], "Endor ruleId");
|
|
151
|
+
const selectedRule = rulesById.get(ruleId);
|
|
152
|
+
if (!selectedRule)
|
|
153
|
+
throw new Error("Endor result must reference exactly one rule in its run.");
|
|
154
|
+
const { rule, index: ruleIndex } = selectedRule;
|
|
155
|
+
if (result["ruleIndex"] !== undefined &&
|
|
156
|
+
result["ruleIndex"] !== ruleIndex)
|
|
157
|
+
throw new Error("Endor ruleIndex and ruleId disagree.");
|
|
158
|
+
if (result["rule"] !== undefined) {
|
|
159
|
+
const reference = record(result["rule"], "Endor rule reference");
|
|
160
|
+
if (reference["toolComponent"] !== undefined ||
|
|
161
|
+
(reference["id"] !== undefined && reference["id"] !== ruleId) ||
|
|
162
|
+
(reference["index"] !== undefined &&
|
|
163
|
+
reference["index"] !== ruleIndex) ||
|
|
164
|
+
(reference["guid"] !== undefined &&
|
|
165
|
+
reference["guid"] !== rule["guid"]))
|
|
166
|
+
throw new Error("Inconsistent or external Endor rule reference.");
|
|
167
|
+
}
|
|
168
|
+
const message = record(result["message"], "Endor message");
|
|
169
|
+
const short = record(rule["shortDescription"] ?? {}, "Endor shortDescription");
|
|
170
|
+
const full = record(rule["fullDescription"] ?? {}, "Endor fullDescription");
|
|
171
|
+
const help = record(rule["help"] ?? {}, "Endor help");
|
|
172
|
+
const hasCodeLocations = strings(properties["categories"]).some((category) => category === "SAST" || category === "SECRETS");
|
|
173
|
+
const locations = array(result["locations"] ?? [], "Endor locations").flatMap((v) => {
|
|
174
|
+
const physical = record(record(v, "Endor location")["physicalLocation"] ?? {}, "Physical location");
|
|
175
|
+
const artifact = record(physical["artifactLocation"] ?? {}, "Artifact location");
|
|
176
|
+
if (artifact["index"] !== undefined ||
|
|
177
|
+
artifact["uriBaseId"] !== undefined)
|
|
178
|
+
return [];
|
|
179
|
+
const uri = text(artifact["uri"]);
|
|
180
|
+
if (uri === null || /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(uri))
|
|
181
|
+
return [];
|
|
182
|
+
let path;
|
|
183
|
+
try {
|
|
184
|
+
path = relativePath(decodeURIComponent(uri));
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
return [];
|
|
188
|
+
}
|
|
189
|
+
if (path === null)
|
|
190
|
+
return [];
|
|
191
|
+
const line = hasCodeLocations
|
|
192
|
+
? record(physical["region"] ?? {}, "Endor region")["startLine"]
|
|
193
|
+
: null;
|
|
194
|
+
return [
|
|
195
|
+
{
|
|
196
|
+
path,
|
|
197
|
+
line: typeof line === "number" && Number.isSafeInteger(line) && line > 0
|
|
198
|
+
? line
|
|
199
|
+
: null,
|
|
200
|
+
},
|
|
201
|
+
];
|
|
202
|
+
});
|
|
203
|
+
return {
|
|
204
|
+
source_finding_id: id,
|
|
205
|
+
evidence: validateExternalEvidence({
|
|
206
|
+
title: text(short["text"]) ?? text(rule["name"]) ?? ruleId,
|
|
207
|
+
url: text(properties["finding-url"]),
|
|
208
|
+
description: [
|
|
209
|
+
text(message["markdown"]) ?? text(message["text"]),
|
|
210
|
+
text(full["text"]),
|
|
211
|
+
text(help["markdown"]) ?? text(help["text"]),
|
|
212
|
+
]
|
|
213
|
+
.filter(Boolean)
|
|
214
|
+
.join("\n\n"),
|
|
215
|
+
// Diagnostic level and CVSS are not Endor's finding severity. Keep both as source evidence.
|
|
216
|
+
severity: "unknown",
|
|
217
|
+
locations: [
|
|
218
|
+
...new Map(locations.map((location) => [JSON.stringify(location), location])).values(),
|
|
219
|
+
],
|
|
220
|
+
source_data: structuredClone({
|
|
221
|
+
...context,
|
|
222
|
+
runContext: sarifRunContextForResult(context.runContext, result, rule, context.documentContext, context.driverContext, context.toolContext),
|
|
223
|
+
rule,
|
|
224
|
+
result,
|
|
225
|
+
}),
|
|
226
|
+
}),
|
|
227
|
+
};
|
|
228
|
+
}, ({ result }) => requiredText(record(record(result, "Endor result")["properties"], "Endor result properties")["finding-uuid"], "Endor finding-uuid"));
|
|
229
|
+
}
|
|
230
|
+
export async function readEndorFindings(path) {
|
|
231
|
+
return normalizeEndorFindings(await readScannerJson(path));
|
|
232
|
+
}
|
|
233
|
+
//# sourceMappingURL=endor-findings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endor-findings.js","sourceRoot":"","sources":["../src/endor-findings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EACL,KAAK,EACL,kCAAkC,EAClC,gBAAgB,EAChB,eAAe,EACf,MAAM,EACN,YAAY,EACZ,YAAY,EACZ,wBAAwB,EACxB,OAAO,EACP,IAAI,GACL,MAAM,qB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AE;iBACX;gBACD,WAAW,EAAE,eAAe,CAAC;oBAC3B,GAAG,OAAO;oBACV,UAAU,EAAE,wBAAwB,CAClC,OAAO,CAAC,UAAU,EAClB,MAAM,EACN,IAAI,EACJ,OAAO,CAAC,eAAe,EACvB,OAAO,CAAC,aAAa,EACrB,OAAO,CAAC,WAAW,CACpB;oBACD,IAAI;oBACJ,MAAM;iBACP,CAAC;aACH,CAAC;SACH,CAAC;IACJ,CAAC,EACD,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CACb,YAAY,CACV,MAAM,CACJ,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,YAAY,CAAC,EAC5C,yBAAyB,CAC1B,CAAC,cAAc,CAAC,EACjB,oBAAoB,CACrB,CACJ,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,IAAY;IAEZ,OAAO,sBAAsB,CAAC,MAAM,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { validateExternalEvidence } from \"./external-import-contract.js\";\nimport type { ExternalFindings } from \"./external-findings.js\";\nimport { isRecord } from \"./record.js\";\nimport {\n array,\n hasSarifExternalPropertyReferences,\n normalizeRecords,\n readScannerJson,\n record,\n relativePath,\n requiredText,\n sarifRunContextForResult,\n strings,\n text,\n} from \"./scanner-import.js\";\n\n/** @internal Repository claims retained in the adapter's original SARIF context. */\nexport function endorRepositoryUrls(sourceData: unknown): string[] {\n if (!isRecord(sourceData)) return [];\n const run = sourceData[\"runContext\"];\n if (run == null) return [];\n return array(\n record(run, \"Endor run context\")[\"versionControlProvenance\"] ?? [],\n \"Endor version control provenance\",\n ).map((entry) =>\n requiredText(\n record(entry, \"Endor repository provenance\")[\"repositoryUri\"],\n \"Endor repository URI\",\n ),\n );\n}\n\n/** Saved Endor Finding objects, an array, or an unmasked ListFindingsResponse. */\nexport function normalizeEndorFindings(input: unknown): ExternalFindings {\n const root = Array.isArray(input) ? null : record(input, \"Endor report\");\n if (root?.[\"version\"] === \"2.1.0\" && root[\"runs\"] !== undefined)\n return normalizeEndorSarif(root);\n const list =\n root?.[\"list\"] === undefined ? null : record(root[\"list\"], \"Endor list\");\n if (list) {\n const response = record(list[\"response\"] ?? {}, \"Endor list response\");\n const token = response[\"next_page_token\"];\n if (\n text(response[\"next_page_id\"]) ||\n (token != null && token !== 0 && token !== \"0\" && token !== \"\")\n ) {\n throw new Error(\n \"The Endor list response has another page. Supply a complete export or an explicitly selected array.\",\n );\n }\n }\n const values = list\n ? array(list[\"objects\"] ?? [], \"Endor list.objects\")\n : Array.isArray(input)\n ? input\n : [input];\n return normalizeRecords(\n values,\n (value, id) => {\n const finding = record(value, \"Endor finding\");\n const meta = record(finding[\"meta\"], \"Endor meta\");\n const spec = record(finding[\"spec\"], \"Endor spec\");\n requiredText(spec[\"project_uuid\"], \"Endor project_uuid\");\n const name = text(spec[\"target_dependency_name\"]);\n const paths = [\n ...new Set(\n strings(spec[\"dependency_file_paths\"])\n .map(relativePath)\n .filter((p): p is string => p !== null),\n ),\n ];\n const metadata = record(\n spec[\"finding_metadata\"] ?? {},\n \"Endor finding_metadata\",\n );\n const codeLocations = [\"sast_data\", \"ai_sast_data\"].flatMap((field) => {\n const data = record(metadata[field] ?? {}, `Endor ${field}`);\n const location = record(\n data[\"location\"] ?? {},\n `Endor ${field} location`,\n );\n const path = relativePath(location[\"relative_path\"]);\n if (path === null) return [];\n const line = location[\"start_line\"];\n return [\n {\n path,\n line:\n typeof line === \"number\" && Number.isSafeInteger(line) && line > 0\n ? line\n : null,\n },\n ];\n });\n const locations = [\n ...paths\n .filter(\n (path) => !codeLocations.some((location) => location.path === path),\n )\n .map((path) => ({ path })),\n ...new Map(\n codeLocations.map((location) => [JSON.stringify(location), location]),\n ).values(),\n ];\n const vulnerability = record(\n metadata[\"vulnerability\"] ?? {},\n \"Endor vulnerability\",\n );\n const advisory = text(\n record(vulnerability[\"meta\"] ?? {}, \"Vulnerability meta\")[\"name\"],\n );\n const aliases = strings(\n record(vulnerability[\"spec\"] ?? {}, \"Vulnerability spec\")[\"aliases\"],\n );\n const level = text(spec[\"level\"])\n ?.replace(/^FINDING_LEVEL_/u, \"\")\n .toLowerCase();\n const severity =\n level && [\"critical\", \"high\", \"medium\", \"low\"].includes(level)\n ? level\n : \"unknown\";\n // A recommended version can refer to an introducing dependency; retain it in source_data.\n const packages = name\n ? (paths.length ? paths : [null]).map((path) => ({\n name,\n ecosystem:\n text(spec[\"ecosystem\"])\n ?.replace(/^ECOSYSTEM_/u, \"\")\n .toLowerCase() ?? null,\n installed_version: text(spec[\"target_dependency_version\"]),\n manifest_path: path,\n fixed_versions: [],\n }))\n : [];\n const context = record(finding[\"context\"] ?? {}, \"Endor context\");\n const updated = text(meta[\"update_time\"]);\n return {\n source_finding_id: id,\n evidence: validateExternalEvidence({\n title: requiredText(meta[\"name\"], \"Endor finding title\"),\n description:\n [\n text(spec[\"summary\"]),\n text(spec[\"explanation\"]),\n text(spec[\"remediation\"]),\n ]\n .filter(Boolean)\n .join(\"\\n\\n\") || text(meta[\"description\"]),\n severity,\n branch:\n context[\"type\"] === \"CONTEXT_TYPE_REF\" ? text(context[\"id\"]) : null,\n code_revision: text(\n record(\n spec[\"source_code_version\"] ?? {},\n \"Endor source code version\",\n )[\"sha\"],\n ),\n source_updated_at:\n updated === null ? null : Math.floor(Date.parse(updated) / 1000),\n advisory_ids: [\n ...new Set([...(advisory ? [advisory] : []), ...aliases]),\n ],\n packages,\n locations,\n source_data: structuredClone(finding),\n }),\n };\n },\n (value) =>\n requiredText(\n record(value, \"Endor finding\")[\"uuid\"],\n \"Endor finding uuid\",\n ),\n );\n}\n\n/** Endor's documented SARIF producer uses properties.finding-uuid, not its rule name. */\nexport function normalizeEndorSarif(input: unknown): ExternalFindings {\n const document = record(input, \"Endor SARIF\");\n if (document[\"version\"] !== \"2.1.0\")\n throw new Error(\"Expected Endor SARIF 2.1.0.\");\n const entries = array(document[\"runs\"], \"SARIF runs\").flatMap((value) => {\n const run = record(value, \"SARIF run\");\n const tool = record(run[\"tool\"], \"SARIF tool\");\n const driver = record(tool[\"driver\"], \"SARIF driver\");\n if (driver[\"name\"] !== \"endorctl\")\n throw new Error(\"Expected the endorctl SARIF producer.\");\n if (\n hasSarifExternalPropertyReferences(run[\"externalPropertyFileReferences\"])\n )\n throw new Error(\"Use a self-contained Endor SARIF report.\");\n const rules = array(driver[\"rules\"] ?? [], \"Endor rules\").map((r) =>\n record(r, \"Endor rule\"),\n );\n const rulesById = new Map<\n unknown,\n { rule: Record<string, unknown>; index: number } | null\n >();\n for (const [index, rule] of rules.entries()) {\n const id = rule[\"id\"];\n rulesById.set(id, rulesById.has(id) ? null : { rule, index });\n }\n const { runs: _runs, ...documentContext } = document;\n const { results: _results, tool: _tool, ...runContext } = run;\n const { rules: _rules, ...driverContext } = driver;\n const { driver: _driver, ...toolContext } = tool;\n return array(run[\"results\"] ?? [], \"Endor results\").map((result) => ({\n result,\n rulesById,\n documentContext,\n runContext,\n driverContext,\n toolContext,\n }));\n });\n return normalizeRecords(\n entries,\n ({ result: value, rulesById, ...context }, id) => {\n const result = record(value, \"Endor result\");\n const properties = record(\n result[\"properties\"],\n \"Endor result properties\",\n );\n requiredText(properties[\"project-uuid\"], \"Endor project-uuid\");\n const ruleId = requiredText(result[\"ruleId\"], \"Endor ruleId\");\n const selectedRule = rulesById.get(ruleId);\n if (!selectedRule)\n throw new Error(\n \"Endor result must reference exactly one rule in its run.\",\n );\n const { rule, index: ruleIndex } = selectedRule;\n if (\n result[\"ruleIndex\"] !== undefined &&\n result[\"ruleIndex\"] !== ruleIndex\n )\n throw new Error(\"Endor ruleIndex and ruleId disagree.\");\n if (result[\"rule\"] !== undefined) {\n const reference = record(result[\"rule\"], \"Endor rule reference\");\n if (\n reference[\"toolComponent\"] !== undefined ||\n (reference[\"id\"] !== undefined && reference[\"id\"] !== ruleId) ||\n (reference[\"index\"] !== undefined &&\n reference[\"index\"] !== ruleIndex) ||\n (reference[\"guid\"] !== undefined &&\n reference[\"guid\"] !== rule[\"guid\"])\n )\n throw new Error(\"Inconsistent or external Endor rule reference.\");\n }\n const message = record(result[\"message\"], \"Endor message\");\n const short = record(\n rule[\"shortDescription\"] ?? {},\n \"Endor shortDescription\",\n );\n const full = record(\n rule[\"fullDescription\"] ?? {},\n \"Endor fullDescription\",\n );\n const help = record(rule[\"help\"] ?? {}, \"Endor help\");\n const hasCodeLocations = strings(properties[\"categories\"]).some(\n (category) => category === \"SAST\" || category === \"SECRETS\",\n );\n const locations = array(\n result[\"locations\"] ?? [],\n \"Endor locations\",\n ).flatMap((v) => {\n const physical = record(\n record(v, \"Endor location\")[\"physicalLocation\"] ?? {},\n \"Physical location\",\n );\n const artifact = record(\n physical[\"artifactLocation\"] ?? {},\n \"Artifact location\",\n );\n if (\n artifact[\"index\"] !== undefined ||\n artifact[\"uriBaseId\"] !== undefined\n )\n return [];\n const uri = text(artifact[\"uri\"]);\n if (uri === null || /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(uri)) return [];\n let path: string | null;\n try {\n path = relativePath(decodeURIComponent(uri));\n } catch {\n return [];\n }\n if (path === null) return [];\n const line = hasCodeLocations\n ? record(physical[\"region\"] ?? {}, \"Endor region\")[\"startLine\"]\n : null;\n return [\n {\n path,\n line:\n typeof line === \"number\" && Number.isSafeInteger(line) && line > 0\n ? line\n : null,\n },\n ];\n });\n return {\n source_finding_id: id,\n evidence: validateExternalEvidence({\n title: text(short[\"text\"]) ?? text(rule[\"name\"]) ?? ruleId,\n url: text(properties[\"finding-url\"]),\n description: [\n text(message[\"markdown\"]) ?? text(message[\"text\"]),\n text(full[\"text\"]),\n text(help[\"markdown\"]) ?? text(help[\"text\"]),\n ]\n .filter(Boolean)\n .join(\"\\n\\n\"),\n // Diagnostic level and CVSS are not Endor's finding severity. Keep both as source evidence.\n severity: \"unknown\",\n locations: [\n ...new Map(\n locations.map((location) => [JSON.stringify(location), location]),\n ).values(),\n ],\n source_data: structuredClone({\n ...context,\n runContext: sarifRunContextForResult(\n context.runContext,\n result,\n rule,\n context.documentContext,\n context.driverContext,\n context.toolContext,\n ),\n rule,\n result,\n }),\n }),\n };\n },\n ({ result }) =>\n requiredText(\n record(\n record(result, \"Endor result\")[\"properties\"],\n \"Endor result properties\",\n )[\"finding-uuid\"],\n \"Endor finding-uuid\",\n ),\n );\n}\n\nexport async function readEndorFindings(\n path: string,\n): Promise<ExternalFindings> {\n return normalizeEndorFindings(await readScannerJson(path));\n}\n"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { ExternalPublicationOptions } from "./external-findings-publish.js";
|
|
2
|
+
import { type LocalExternalImportDependencies } from "./external-findings-local.js";
|
|
3
|
+
/** Read an installed vendor format and prepare it for the local workbench. */
|
|
4
|
+
export declare function prepareLocalExternalImport(path: string, options: ExternalPublicationOptions, dependencies?: LocalExternalImportDependencies): Promise<import("./external-findings-local.js").PreparedLocalExternalImport>;
|
|
5
|
+
//# sourceMappingURL=external-findings-import.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"external-findings-import.d.ts","sourceRoot":"","sources":["../src/external-findings-import.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAMjF,OAAO,EAEL,KAAK,+BAA+B,EACrC,MAAM,8BAA8B,CAAC;AAGtC,8EAA8E;AAC9E,wBAAsB,0BAA0B,CAC9C,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,0BAA0B,EACnC,YAAY,GAAE,+BAAoC,+EAwCnD"}
|