@openai/codex-security 0.1.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/LICENSE +201 -0
- package/README.md +306 -0
- package/_bundled_plugin/.app.json +20 -0
- package/_bundled_plugin/.codex-plugin/plugin.json +41 -0
- package/_bundled_plugin/.mcp.json +20 -0
- package/_bundled_plugin/assets/logo.png +0 -0
- package/_bundled_plugin/examples/completed-scan/coverage.json +22 -0
- package/_bundled_plugin/examples/completed-scan/findings.json +51 -0
- package/_bundled_plugin/examples/completed-scan/scan-manifest.json +43 -0
- package/_bundled_plugin/mcp/mcp-app.html.br +0 -0
- package/_bundled_plugin/mcp/server.mjs +24 -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/preflight/capability-profiles.toml +179 -0
- package/_bundled_plugin/references/config-preflight.md +115 -0
- package/_bundled_plugin/references/final-report.md +205 -0
- package/_bundled_plugin/references/finding-detail-fields.md +162 -0
- package/_bundled_plugin/references/sarif-adapter.md +26 -0
- package/_bundled_plugin/references/scan-artifacts.md +116 -0
- package/_bundled_plugin/references/scan-contract.md +164 -0
- package/_bundled_plugin/references/security-guidance.md +15 -0
- package/_bundled_plugin/references/shared-hard-rules.md +15 -0
- package/_bundled_plugin/references/static-finding-assessment.md +75 -0
- package/_bundled_plugin/schemas/coverage.schema.json +228 -0
- package/_bundled_plugin/schemas/findings.schema.json +359 -0
- package/_bundled_plugin/schemas/scan-manifest.schema.json +332 -0
- package/_bundled_plugin/scripts/config_preflight.py +901 -0
- package/_bundled_plugin/scripts/deep_scan_config.py +108 -0
- package/_bundled_plugin/scripts/deep_scan_workbench.py +1547 -0
- package/_bundled_plugin/scripts/filesystem_identity.py +30 -0
- package/_bundled_plugin/scripts/finalize_scan_contract.py +2208 -0
- package/_bundled_plugin/scripts/finding_preview.py +270 -0
- package/_bundled_plugin/scripts/generate_rank_input.py +1013 -0
- package/_bundled_plugin/scripts/normalize_candidates.py +320 -0
- package/_bundled_plugin/scripts/rank_preview.py +968 -0
- package/_bundled_plugin/scripts/report_projection.py +844 -0
- package/_bundled_plugin/scripts/resolve_security_md.py +158 -0
- package/_bundled_plugin/scripts/snapshot_sqlite.py +26 -0
- package/_bundled_plugin/scripts/validate_report_format.py +138 -0
- package/_bundled_plugin/scripts/validate_scan_contract.py +108 -0
- package/_bundled_plugin/scripts/validate_tracking_source.py +92 -0
- package/_bundled_plugin/scripts/windows_scan_local_files.py +612 -0
- package/_bundled_plugin/scripts/workbench/__init__.py +1 -0
- package/_bundled_plugin/scripts/workbench/handoff.py +238 -0
- package/_bundled_plugin/scripts/workbench_cli.py +325 -0
- package/_bundled_plugin/scripts/workbench_constants.py +81 -0
- package/_bundled_plugin/scripts/workbench_db.py +3728 -0
- package/_bundled_plugin/scripts/workbench_native_indexes.py +242 -0
- package/_bundled_plugin/scripts/workbench_progress.py +226 -0
- package/_bundled_plugin/scripts/workbench_remediation.py +125 -0
- package/_bundled_plugin/scripts/workbench_scan_history.py +829 -0
- package/_bundled_plugin/scripts/workbench_scan_start.py +149 -0
- package/_bundled_plugin/scripts/workbench_schema.py +714 -0
- package/_bundled_plugin/scripts/workbench_source_excerpt.py +99 -0
- package/_bundled_plugin/scripts/workbench_target.py +469 -0
- package/_bundled_plugin/scripts/workbench_target_state.py +63 -0
- package/_bundled_plugin/scripts/workbench_validation.py +294 -0
- package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +117 -0
- package/_bundled_plugin/skills/attack-path-analysis/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/attack-path-analysis/references/attack-path-facts.md +76 -0
- package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +153 -0
- package/_bundled_plugin/skills/deep-security-scan/SKILL.md +166 -0
- package/_bundled_plugin/skills/deep-security-scan/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/define-security-policy/SKILL.md +93 -0
- package/_bundled_plugin/skills/define-security-policy/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/finding-discovery/SKILL.md +155 -0
- package/_bundled_plugin/skills/finding-discovery/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/fix-finding/SKILL.md +112 -0
- package/_bundled_plugin/skills/fix-finding/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/propose-security-hardening/SKILL.md +240 -0
- package/_bundled_plugin/skills/propose-security-hardening/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/propose-security-hardening/references/proposal-format.md +424 -0
- package/_bundled_plugin/skills/security-diff-scan/SKILL.md +167 -0
- package/_bundled_plugin/skills/security-diff-scan/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/security-scan/SKILL.md +42 -0
- package/_bundled_plugin/skills/security-scan/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/security-scan/references/repository-wide-scan.md +48 -0
- package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +85 -0
- package/_bundled_plugin/skills/threat-model/SKILL.md +59 -0
- package/_bundled_plugin/skills/threat-model/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/threat-model/references/threat-model-guidance.md +48 -0
- package/_bundled_plugin/skills/track-findings/SKILL.md +222 -0
- package/_bundled_plugin/skills/track-findings/agents/openai.yaml +6 -0
- package/_bundled_plugin/skills/track-findings/references/github-security-advisories.md +54 -0
- package/_bundled_plugin/skills/track-findings/references/jira.md +77 -0
- package/_bundled_plugin/skills/triage-finding/SKILL.md +342 -0
- package/_bundled_plugin/skills/triage-finding/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/triage-finding/references/github-rest-intake.md +168 -0
- package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +62 -0
- package/_bundled_plugin/skills/triage-finding/references/triage-result-contract.md +108 -0
- package/_bundled_plugin/skills/validation/SKILL.md +110 -0
- package/_bundled_plugin/skills/validation/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/validation/references/validation-guidance.md +122 -0
- package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +263 -0
- package/_bundled_plugin/skills/vulnerability-writeup/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +104 -0
- package/bin/codex-security.mjs +26 -0
- package/dist/api.d.ts +112 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +1051 -0
- package/dist/api.js.map +1 -0
- package/dist/auth.d.ts +29 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +246 -0
- package/dist/auth.js.map +1 -0
- package/dist/bulk-scan-discovery.d.ts +35 -0
- package/dist/bulk-scan-discovery.d.ts.map +1 -0
- package/dist/bulk-scan-discovery.js +217 -0
- package/dist/bulk-scan-discovery.js.map +1 -0
- package/dist/cli.d.ts +67 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +2128 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +19 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +199 -0
- package/dist/config.js.map +1 -0
- package/dist/contract.d.ts +21 -0
- package/dist/contract.d.ts.map +1 -0
- package/dist/contract.js +848 -0
- package/dist/contract.js.map +1 -0
- package/dist/cost.d.ts +30 -0
- package/dist/cost.d.ts.map +1 -0
- package/dist/cost.js +280 -0
- package/dist/cost.js.map +1 -0
- package/dist/errors.d.ts +38 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +52 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/knowledge-base.d.ts +7 -0
- package/dist/knowledge-base.d.ts.map +1 -0
- package/dist/knowledge-base.js +181 -0
- package/dist/knowledge-base.js.map +1 -0
- package/dist/models.d.ts +231 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +3 -0
- package/dist/models.js.map +1 -0
- package/dist/multiscan.d.ts +30 -0
- package/dist/multiscan.d.ts.map +1 -0
- package/dist/multiscan.js +397 -0
- package/dist/multiscan.js.map +1 -0
- package/dist/result.d.ts +39 -0
- package/dist/result.d.ts.map +1 -0
- package/dist/result.js +71 -0
- package/dist/result.js.map +1 -0
- package/dist/runtime.d.ts +69 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +997 -0
- package/dist/runtime.js.map +1 -0
- package/dist/scan-comparison.d.ts +42 -0
- package/dist/scan-comparison.d.ts.map +1 -0
- package/dist/scan-comparison.js +153 -0
- package/dist/scan-comparison.js.map +1 -0
- package/dist/scan-history-renderer.d.ts +13 -0
- package/dist/scan-history-renderer.d.ts.map +1 -0
- package/dist/scan-history-renderer.js +297 -0
- package/dist/scan-history-renderer.js.map +1 -0
- package/dist/targets.d.ts +39 -0
- package/dist/targets.d.ts.map +1 -0
- package/dist/targets.js +295 -0
- package/dist/targets.js.map +1 -0
- package/dist/trusted-executable.d.ts +6 -0
- package/dist/trusted-executable.d.ts.map +1 -0
- package/dist/trusted-executable.js +77 -0
- package/dist/trusted-executable.js.map +1 -0
- package/dist/version.d.ts +6 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +42 -0
- package/dist/version.js.map +1 -0
- package/dist/worker-progress.d.ts +13 -0
- package/dist/worker-progress.d.ts.map +1 -0
- package/dist/worker-progress.js +113 -0
- package/dist/worker-progress.js.map +1 -0
- package/package.json +74 -0
package/dist/contract.js
ADDED
|
@@ -0,0 +1,848 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { lstat, open, realpath } from "node:fs/promises";
|
|
4
|
+
import { dirname, isAbsolute, join, posix, relative, resolve, sep, } from "node:path";
|
|
5
|
+
import Ajv2020 from "ajv/dist/2020.js";
|
|
6
|
+
import { ContractValidationError } from "./errors.js";
|
|
7
|
+
const DOCUMENTS = {
|
|
8
|
+
"scan-manifest.json": "scan-manifest.schema.json",
|
|
9
|
+
"findings.json": "findings.schema.json",
|
|
10
|
+
"coverage.json": "coverage.schema.json",
|
|
11
|
+
};
|
|
12
|
+
const PRODUCER_NAME = "codex-security-plugin";
|
|
13
|
+
const MAX_CONTRACT_DOCUMENT_BYTES = {
|
|
14
|
+
"scan-manifest.json": 16 * 1024 * 1024,
|
|
15
|
+
"findings.json": 128 * 1024 * 1024,
|
|
16
|
+
"coverage.json": 32 * 1024 * 1024,
|
|
17
|
+
};
|
|
18
|
+
const MAX_SCHEMA_DOCUMENT_BYTES = 4 * 1024 * 1024;
|
|
19
|
+
const DOCUMENT_READ_CHUNK_BYTES = 64 * 1024;
|
|
20
|
+
const MAX_JSON_DEPTH = 256;
|
|
21
|
+
const MAX_SCHEMA_NODES = 8192;
|
|
22
|
+
const MAX_SCHEMA_COLLECTION_ENTRIES = 4096;
|
|
23
|
+
const MAX_SCHEMA_APPLICATOR_EDGES = 128;
|
|
24
|
+
const SAFE_SCHEMA_ERROR_PROPERTIES = new Set([
|
|
25
|
+
"scan",
|
|
26
|
+
"target",
|
|
27
|
+
"remote",
|
|
28
|
+
"completedAt",
|
|
29
|
+
"sealedAt",
|
|
30
|
+
"artifacts",
|
|
31
|
+
"findings",
|
|
32
|
+
"coverage",
|
|
33
|
+
"scope",
|
|
34
|
+
]);
|
|
35
|
+
const SAFE_SCHEMA_PATTERNS = new Set([
|
|
36
|
+
"^(?![^:/?#]+://[^/?#]*@)[^?#]+$",
|
|
37
|
+
"^codex-security-snapshot/v1:sha256:[a-f0-9]{64}$",
|
|
38
|
+
"^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\).+$",
|
|
39
|
+
"^[a-f0-9]{64}$",
|
|
40
|
+
"^(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)artifacts/.+$",
|
|
41
|
+
"^csf_[a-f0-9]{24}$",
|
|
42
|
+
"^occ_[a-f0-9]{24}$",
|
|
43
|
+
"^[a-z0-9][a-z0-9._/-]*$",
|
|
44
|
+
"^codex-security/v1:sha256:[a-f0-9]{64}$",
|
|
45
|
+
"^findings/([a-z0-9][a-z0-9._-]*)/\\1\\.md$",
|
|
46
|
+
]);
|
|
47
|
+
export async function loadContract(scanDirectory, options) {
|
|
48
|
+
const scanRoot = await requireScanRoot(scanDirectory, options.signal);
|
|
49
|
+
const scanDir = scanRoot.path;
|
|
50
|
+
const documentDigests = new Map();
|
|
51
|
+
const payloads = {
|
|
52
|
+
"scan-manifest.json": await readScanJson(scanDir, "scan-manifest.json", documentDigests, options.signal, scanRoot),
|
|
53
|
+
"findings.json": await readScanJson(scanDir, "findings.json", documentDigests, options.signal, scanRoot),
|
|
54
|
+
"coverage.json": await readScanJson(scanDir, "coverage.json", documentDigests, options.signal, scanRoot),
|
|
55
|
+
};
|
|
56
|
+
throwIfAborted(options.signal);
|
|
57
|
+
const ajv = createValidator();
|
|
58
|
+
for (const [filename, schemaName] of Object.entries(DOCUMENTS)) {
|
|
59
|
+
const schema = await readJson(join(options.pluginRoot, "schemas", schemaName), options.signal);
|
|
60
|
+
requireSchemaComplexity(schema, schemaName);
|
|
61
|
+
let validate;
|
|
62
|
+
try {
|
|
63
|
+
validate = ajv.compile(schema);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throw new ContractValidationError(`${schemaName}: invalid JSON Schema.`);
|
|
67
|
+
}
|
|
68
|
+
const payload = payloads[filename];
|
|
69
|
+
let valid;
|
|
70
|
+
try {
|
|
71
|
+
const result = validate(payload);
|
|
72
|
+
if (typeof result !== "boolean") {
|
|
73
|
+
throw new Error("asynchronous JSON Schema validation is unsupported");
|
|
74
|
+
}
|
|
75
|
+
valid = result;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
throw new ContractValidationError(`${schemaName}: invalid JSON Schema.`);
|
|
79
|
+
}
|
|
80
|
+
if (!valid) {
|
|
81
|
+
throw schemaError(filename, validate.errors ?? []);
|
|
82
|
+
}
|
|
83
|
+
throwIfAborted(options.signal);
|
|
84
|
+
}
|
|
85
|
+
const manifest = payloads["scan-manifest.json"];
|
|
86
|
+
const findings = payloads["findings.json"];
|
|
87
|
+
const coverage = payloads["coverage.json"];
|
|
88
|
+
if (findings.scanId !== manifest.scan.id ||
|
|
89
|
+
coverage.scanId !== manifest.scan.id) {
|
|
90
|
+
throw new ContractValidationError("Canonical contract scan IDs do not match.");
|
|
91
|
+
}
|
|
92
|
+
if (!sameArray(coverage.includePaths, manifest.scan.scope.includePaths)) {
|
|
93
|
+
throw new ContractValidationError("Coverage include paths do not match the manifest scope.");
|
|
94
|
+
}
|
|
95
|
+
if (!sameArray(coverage.excludePaths, manifest.scan.scope.excludePaths)) {
|
|
96
|
+
throw new ContractValidationError("Coverage exclude paths do not match the manifest scope.");
|
|
97
|
+
}
|
|
98
|
+
validateCanonicalContract(manifest, findings);
|
|
99
|
+
await validateSeal(scanDir, manifest, findings, coverage, documentDigests, options.signal, scanRoot);
|
|
100
|
+
if (options.expectation !== undefined) {
|
|
101
|
+
validateExpectation(manifest, coverage, options.expectation);
|
|
102
|
+
}
|
|
103
|
+
await verifyScanRoot(scanRoot, options.signal);
|
|
104
|
+
return { manifest, findings, coverage };
|
|
105
|
+
}
|
|
106
|
+
function validateCanonicalContract(manifest, findings) {
|
|
107
|
+
const remote = manifest.scan.target.remote;
|
|
108
|
+
if (remote !== undefined) {
|
|
109
|
+
const authority = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]+)/.exec(remote)?.[1];
|
|
110
|
+
if (remote.includes("\\") || authority === undefined) {
|
|
111
|
+
throw new ContractValidationError("scan.target.remote: expected a sanitized canonical absolute URL.");
|
|
112
|
+
}
|
|
113
|
+
if (authority.includes("@")) {
|
|
114
|
+
throw new ContractValidationError("scan.target.remote: remote URL must not contain credentials, query, or fragment.");
|
|
115
|
+
}
|
|
116
|
+
let parsed;
|
|
117
|
+
try {
|
|
118
|
+
parsed = new URL(remote);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
throw new ContractValidationError("scan.target.remote: expected a sanitized canonical absolute URL.", { cause: error });
|
|
122
|
+
}
|
|
123
|
+
if (parsed.protocol.length === 0 || parsed.host.length === 0) {
|
|
124
|
+
throw new ContractValidationError("scan.target.remote: expected a sanitized canonical absolute URL.");
|
|
125
|
+
}
|
|
126
|
+
if (parsed.username.length > 0 ||
|
|
127
|
+
parsed.password.length > 0 ||
|
|
128
|
+
parsed.search.length > 0 ||
|
|
129
|
+
parsed.hash.length > 0) {
|
|
130
|
+
throw new ContractValidationError("scan.target.remote: remote URL must not contain credentials, query, or fragment.");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
for (const field of ["includePaths", "excludePaths"]) {
|
|
134
|
+
for (const [index, value] of manifest.scan.scope[field].entries()) {
|
|
135
|
+
try {
|
|
136
|
+
safeScopePath(value);
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
throw new ContractValidationError(`manifest.scan.scope.${field}[${index}]: expected a safe repository-relative POSIX path.`, { cause: error });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
for (const [findingIndex, finding] of findings.findings.entries()) {
|
|
144
|
+
const context = `findings.findings[${findingIndex}]`;
|
|
145
|
+
for (const [locationIndex, location] of finding.locations.entries()) {
|
|
146
|
+
const locationContext = `${context}.locations[${locationIndex}]`;
|
|
147
|
+
try {
|
|
148
|
+
safeRelativePath(location.path, `${locationContext}.path`);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
throw new ContractValidationError(`${locationContext}.path: expected a safe repository-relative POSIX path.`, { cause: error });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const fingerprint = `codex-security/v1:sha256:${sha256Text([
|
|
155
|
+
"codex-security/v1",
|
|
156
|
+
manifest.scan.target.targetId,
|
|
157
|
+
finding.ruleId,
|
|
158
|
+
finding.identity.anchor,
|
|
159
|
+
finding.identity.instance ?? "",
|
|
160
|
+
].join("\0"))}`;
|
|
161
|
+
const findingId = `csf_${sha256Text(fingerprint).slice(0, 24)}`;
|
|
162
|
+
const occurrenceId = `occ_${sha256Text([manifest.scan.id, fingerprint].join("\0")).slice(0, 24)}`;
|
|
163
|
+
if (finding.findingId !== findingId) {
|
|
164
|
+
throw new ContractValidationError(`${context}.findingId: does not match derived fingerprint identity.`);
|
|
165
|
+
}
|
|
166
|
+
if (finding.occurrenceId !== occurrenceId) {
|
|
167
|
+
throw new ContractValidationError(`${context}.occurrenceId: does not match scan occurrence identity.`);
|
|
168
|
+
}
|
|
169
|
+
if (finding.fingerprints.primary !== fingerprint) {
|
|
170
|
+
throw new ContractValidationError(`${context}.fingerprints: does not match derived fingerprint.`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function sha256Text(value) {
|
|
175
|
+
return createHash("sha256").update(value, "utf8").digest("hex");
|
|
176
|
+
}
|
|
177
|
+
export async function requireScanFile(scanDirectory, relativePath, context, signal) {
|
|
178
|
+
return (await requireCheckedScanFile(scanDirectory, relativePath, context, signal)).path;
|
|
179
|
+
}
|
|
180
|
+
async function requireCheckedScanFile(scanDirectory, relativePath, context, signal, expectedRoot) {
|
|
181
|
+
const checkedRoot = await requireScanRoot(scanDirectory, signal);
|
|
182
|
+
const scanDir = checkedRoot.path;
|
|
183
|
+
throwIfAborted(signal);
|
|
184
|
+
const safePath = safeRelativePath(relativePath, context);
|
|
185
|
+
const parts = safePath.split("/");
|
|
186
|
+
let current = scanDir;
|
|
187
|
+
try {
|
|
188
|
+
const rootMetadata = checkedRoot.metadata;
|
|
189
|
+
if (expectedRoot !== undefined &&
|
|
190
|
+
(scanDir !== expectedRoot.path ||
|
|
191
|
+
rootMetadata.dev !== expectedRoot.metadata.dev ||
|
|
192
|
+
rootMetadata.ino !== expectedRoot.metadata.ino)) {
|
|
193
|
+
throw new Error("scan directory changed while reading");
|
|
194
|
+
}
|
|
195
|
+
const parents = [{ path: scanDir, metadata: rootMetadata }];
|
|
196
|
+
throwIfAborted(signal);
|
|
197
|
+
if (!parents[0].metadata.isDirectory() ||
|
|
198
|
+
parents[0].metadata.isSymbolicLink()) {
|
|
199
|
+
throw new Error("unsafe scan directory");
|
|
200
|
+
}
|
|
201
|
+
for (const part of parts.slice(0, -1)) {
|
|
202
|
+
current = join(current, part);
|
|
203
|
+
const metadata = await lstat(current);
|
|
204
|
+
throwIfAborted(signal);
|
|
205
|
+
if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
|
|
206
|
+
throw new Error("unsafe parent");
|
|
207
|
+
}
|
|
208
|
+
parents.push({ path: current, metadata });
|
|
209
|
+
}
|
|
210
|
+
const path = join(scanDir, ...parts);
|
|
211
|
+
const metadata = await lstat(path);
|
|
212
|
+
throwIfAborted(signal);
|
|
213
|
+
if (metadata.isSymbolicLink() || !metadata.isFile()) {
|
|
214
|
+
throw new ContractValidationError(`${context}: expected a regular non-symlink file.`);
|
|
215
|
+
}
|
|
216
|
+
const canonical = await realpath(path);
|
|
217
|
+
throwIfAborted(signal);
|
|
218
|
+
if (!isContained(scanDir, canonical)) {
|
|
219
|
+
throw new Error("outside scan directory");
|
|
220
|
+
}
|
|
221
|
+
return { path, metadata, parents };
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
throwIfAborted(signal);
|
|
225
|
+
if (error instanceof ContractValidationError) {
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
throw new ContractValidationError(`${context}: expected a file inside the scan directory.`, {
|
|
229
|
+
cause: error,
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async function validateSeal(scanDir, manifest, findings, coverage, documentDigests, signal, expectedRoot) {
|
|
234
|
+
const scan = manifest.scan;
|
|
235
|
+
if (scan.sealedAt !== scan.completedAt) {
|
|
236
|
+
throw new ContractValidationError("Manifest sealedAt must match completedAt.");
|
|
237
|
+
}
|
|
238
|
+
const artifactPaths = new Set();
|
|
239
|
+
for (const [index, artifact] of scan.artifacts.entries()) {
|
|
240
|
+
throwIfAborted(signal);
|
|
241
|
+
const context = `manifest.scan.artifacts[${index}]`;
|
|
242
|
+
const normalized = safeRelativePath(artifact.path, `${context}.path`);
|
|
243
|
+
if (artifactPaths.has(normalized)) {
|
|
244
|
+
throw new ContractValidationError(`${context}.path: duplicate artifact path.`);
|
|
245
|
+
}
|
|
246
|
+
artifactPaths.add(normalized);
|
|
247
|
+
const digest = documentDigests.get(normalized) ??
|
|
248
|
+
(await sha256ScanFile(scanDir, normalized, context, signal, expectedRoot));
|
|
249
|
+
if (digest !== artifact.sha256) {
|
|
250
|
+
throw new ContractValidationError(`${context}: sealed artifact changed or is missing.`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
for (const surface of coverage.surfaces) {
|
|
254
|
+
for (const receipt of surface.receiptRefs) {
|
|
255
|
+
throwIfAborted(signal);
|
|
256
|
+
const normalized = safeRelativePath(receipt, "coverage receipt");
|
|
257
|
+
if (!normalized.startsWith("artifacts/")) {
|
|
258
|
+
throw new ContractValidationError(`Coverage receipt must be under artifacts/: ${receipt}`);
|
|
259
|
+
}
|
|
260
|
+
if (!artifactPaths.has(normalized)) {
|
|
261
|
+
throw new ContractValidationError(`Coverage receipt is missing from sealed artifacts: ${receipt}`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
for (const [index, finding] of findings.findings.entries()) {
|
|
266
|
+
const writeup = finding.writeup;
|
|
267
|
+
if (writeup === undefined)
|
|
268
|
+
continue;
|
|
269
|
+
const file = await openCheckedScanFile(scanDir, writeup.reportPath, `findings[${index}].writeup.reportPath`, signal, expectedRoot);
|
|
270
|
+
await file.close();
|
|
271
|
+
}
|
|
272
|
+
const hardening = manifest.scan.hardening;
|
|
273
|
+
if (hardening !== undefined) {
|
|
274
|
+
const file = await openCheckedScanFile(scanDir, hardening.portfolioPath, "manifest.scan.hardening.portfolioPath", signal, expectedRoot);
|
|
275
|
+
await file.close();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
function validateExpectation(manifest, coverage, expectation) {
|
|
279
|
+
const scan = manifest.scan;
|
|
280
|
+
if (scan.producer.name !== PRODUCER_NAME) {
|
|
281
|
+
throw new ContractValidationError(`Manifest producer must be ${PRODUCER_NAME}, got ${scan.producer.name}.`);
|
|
282
|
+
}
|
|
283
|
+
if (scan.producer.version !== expectation.pluginVersion) {
|
|
284
|
+
throw new ContractValidationError("Manifest producer version does not match the installed Codex Security plugin.");
|
|
285
|
+
}
|
|
286
|
+
const expectedMode = expectedCoverageMode(expectation.target, expectation.mode);
|
|
287
|
+
if (coverage.mode !== expectedMode) {
|
|
288
|
+
throw new ContractValidationError(`Coverage mode must be ${expectedMode}, got ${coverage.mode}.`);
|
|
289
|
+
}
|
|
290
|
+
const target = scan.target;
|
|
291
|
+
const requested = expectation.target;
|
|
292
|
+
if (requested.kind === "refs" || requested.kind === "working_tree") {
|
|
293
|
+
if (target.kind !== "git_diff") {
|
|
294
|
+
throw new ContractValidationError("Diff scan manifest target must be git_diff.");
|
|
295
|
+
}
|
|
296
|
+
if (target.baseRevision !== requested.base) {
|
|
297
|
+
throw new ContractValidationError("Diff scan base revision does not match the request.");
|
|
298
|
+
}
|
|
299
|
+
if (target.headRevision !== requested.head) {
|
|
300
|
+
throw new ContractValidationError("Diff scan head revision does not match the request.");
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
else if (expectation.repositoryRevision === null) {
|
|
304
|
+
if (target.kind !== "directory_snapshot") {
|
|
305
|
+
throw new ContractValidationError("Unversioned scan manifest target must be directory_snapshot.");
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
if (target.kind !== "git_revision" && target.kind !== "git_worktree") {
|
|
310
|
+
throw new ContractValidationError("Repository scan manifest target must be Git-backed.");
|
|
311
|
+
}
|
|
312
|
+
if (target.revision !== expectation.repositoryRevision) {
|
|
313
|
+
throw new ContractValidationError("Scan target revision does not match the repository.");
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (requested.kind === "paths") {
|
|
317
|
+
const actual = scan.scope.includePaths.map(safeScopePath);
|
|
318
|
+
if (actual.length !== new Set(actual).size ||
|
|
319
|
+
!sameSet(new Set(actual), new Set(requested.paths))) {
|
|
320
|
+
throw new ContractValidationError("Manifest include paths do not match the requested path target.");
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function expectedCoverageMode(target, mode) {
|
|
325
|
+
if (target.kind === "paths")
|
|
326
|
+
return "scoped_path";
|
|
327
|
+
if (target.kind === "refs")
|
|
328
|
+
return "branch_diff";
|
|
329
|
+
if (target.kind === "working_tree")
|
|
330
|
+
return "working_tree";
|
|
331
|
+
return mode === "deep" ? "deep_repository" : "repository";
|
|
332
|
+
}
|
|
333
|
+
async function requireScanRoot(scanDirectory, signal) {
|
|
334
|
+
throwIfAborted(signal);
|
|
335
|
+
const absolute = resolve(scanDirectory);
|
|
336
|
+
try {
|
|
337
|
+
const metadata = await lstat(absolute);
|
|
338
|
+
throwIfAborted(signal);
|
|
339
|
+
const canonical = await realpath(absolute);
|
|
340
|
+
throwIfAborted(signal);
|
|
341
|
+
const current = await lstat(absolute);
|
|
342
|
+
throwIfAborted(signal);
|
|
343
|
+
const returned = await lstat(canonical);
|
|
344
|
+
throwIfAborted(signal);
|
|
345
|
+
if (!metadata.isDirectory() ||
|
|
346
|
+
metadata.isSymbolicLink() ||
|
|
347
|
+
!current.isDirectory() ||
|
|
348
|
+
current.isSymbolicLink() ||
|
|
349
|
+
metadata.dev !== current.dev ||
|
|
350
|
+
metadata.ino !== current.ino ||
|
|
351
|
+
!returned.isDirectory() ||
|
|
352
|
+
returned.isSymbolicLink() ||
|
|
353
|
+
metadata.dev !== returned.dev ||
|
|
354
|
+
metadata.ino !== returned.ino) {
|
|
355
|
+
throw new Error("not a directory");
|
|
356
|
+
}
|
|
357
|
+
return { path: canonical, metadata: returned };
|
|
358
|
+
}
|
|
359
|
+
catch (error) {
|
|
360
|
+
throwIfAborted(signal);
|
|
361
|
+
throw new ContractValidationError("Scan directory must be an existing non-symlink directory.", { cause: error });
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
async function verifyScanRoot(root, signal) {
|
|
365
|
+
try {
|
|
366
|
+
const current = await lstat(root.path);
|
|
367
|
+
throwIfAborted(signal);
|
|
368
|
+
if (!current.isDirectory() ||
|
|
369
|
+
current.isSymbolicLink() ||
|
|
370
|
+
current.dev !== root.metadata.dev ||
|
|
371
|
+
current.ino !== root.metadata.ino) {
|
|
372
|
+
throw new Error("scan directory changed while reading");
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
catch (error) {
|
|
376
|
+
throwIfAborted(signal);
|
|
377
|
+
throw new ContractValidationError("Scan directory changed while reading the canonical contract.", { cause: error });
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
function safeRelativePath(value, context) {
|
|
381
|
+
const parts = value.split("/");
|
|
382
|
+
if (value.length === 0 ||
|
|
383
|
+
!isWellFormedUnicode(value) ||
|
|
384
|
+
value === "." ||
|
|
385
|
+
value.startsWith("/") ||
|
|
386
|
+
/^[A-Za-z]:/.test(value) ||
|
|
387
|
+
parts.includes("..") ||
|
|
388
|
+
value.includes("\\") ||
|
|
389
|
+
value.includes("\0") ||
|
|
390
|
+
parts.some((part) => part.includes(":"))) {
|
|
391
|
+
throw new ContractValidationError(`${context}: expected a safe scan-relative POSIX path.`);
|
|
392
|
+
}
|
|
393
|
+
const normalized = posix.normalize(value).replace(/\/+$/, "");
|
|
394
|
+
if (normalized === "." ||
|
|
395
|
+
normalized.startsWith("../") ||
|
|
396
|
+
isAbsolute(normalized)) {
|
|
397
|
+
throw new ContractValidationError(`${context}: expected a safe scan-relative POSIX path.`);
|
|
398
|
+
}
|
|
399
|
+
return normalized;
|
|
400
|
+
}
|
|
401
|
+
function safeScopePath(value) {
|
|
402
|
+
return value === "."
|
|
403
|
+
? value
|
|
404
|
+
: safeRelativePath(value, "manifest scope include path");
|
|
405
|
+
}
|
|
406
|
+
async function readScanJson(scanDir, relativePath, documentDigests, signal, expectedRoot) {
|
|
407
|
+
const file = await openCheckedScanFile(scanDir, relativePath, relativePath, signal, expectedRoot);
|
|
408
|
+
try {
|
|
409
|
+
const bytes = await readBoundedDocument(file, join(scanDir, relativePath), MAX_CONTRACT_DOCUMENT_BYTES[relativePath], signal);
|
|
410
|
+
documentDigests.set(relativePath, createHash("sha256").update(bytes).digest("hex"));
|
|
411
|
+
return parseJson(join(scanDir, relativePath), bytes);
|
|
412
|
+
}
|
|
413
|
+
catch (error) {
|
|
414
|
+
throwIfAborted(signal);
|
|
415
|
+
if (error instanceof ContractValidationError)
|
|
416
|
+
throw error;
|
|
417
|
+
throw new ContractValidationError(`${join(scanDir, relativePath)}: unreadable JSON document.`, { cause: error });
|
|
418
|
+
}
|
|
419
|
+
finally {
|
|
420
|
+
await file.close();
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
async function readJson(path, signal) {
|
|
424
|
+
let bytes;
|
|
425
|
+
let file;
|
|
426
|
+
try {
|
|
427
|
+
const parent = dirname(path);
|
|
428
|
+
const parentMetadata = await lstat(parent);
|
|
429
|
+
const metadata = await lstat(path);
|
|
430
|
+
throwIfAborted(signal);
|
|
431
|
+
if (!parentMetadata.isDirectory() ||
|
|
432
|
+
parentMetadata.isSymbolicLink() ||
|
|
433
|
+
!metadata.isFile() ||
|
|
434
|
+
metadata.isSymbolicLink()) {
|
|
435
|
+
throw new Error("not a regular schema file");
|
|
436
|
+
}
|
|
437
|
+
file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
438
|
+
const opened = await file.stat();
|
|
439
|
+
const currentParent = await lstat(parent);
|
|
440
|
+
const current = await lstat(path);
|
|
441
|
+
throwIfAborted(signal);
|
|
442
|
+
if (!opened.isFile() ||
|
|
443
|
+
opened.dev !== metadata.dev ||
|
|
444
|
+
opened.ino !== metadata.ino ||
|
|
445
|
+
!currentParent.isDirectory() ||
|
|
446
|
+
currentParent.isSymbolicLink() ||
|
|
447
|
+
currentParent.dev !== parentMetadata.dev ||
|
|
448
|
+
currentParent.ino !== parentMetadata.ino ||
|
|
449
|
+
!current.isFile() ||
|
|
450
|
+
current.isSymbolicLink() ||
|
|
451
|
+
current.dev !== metadata.dev ||
|
|
452
|
+
current.ino !== metadata.ino) {
|
|
453
|
+
throw new Error("schema file changed before reading");
|
|
454
|
+
}
|
|
455
|
+
bytes = await readBoundedDocument(file, path, MAX_SCHEMA_DOCUMENT_BYTES, signal);
|
|
456
|
+
}
|
|
457
|
+
catch (error) {
|
|
458
|
+
throwIfAborted(signal);
|
|
459
|
+
if (error instanceof ContractValidationError)
|
|
460
|
+
throw error;
|
|
461
|
+
if (nodeErrorCode(error) === "ENOENT") {
|
|
462
|
+
throw new ContractValidationError(`Missing required contract document: ${path}`);
|
|
463
|
+
}
|
|
464
|
+
throw new ContractValidationError(`${path}: unreadable JSON document.`, {
|
|
465
|
+
cause: error,
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
finally {
|
|
469
|
+
await file?.close();
|
|
470
|
+
}
|
|
471
|
+
return parseJson(path, bytes);
|
|
472
|
+
}
|
|
473
|
+
async function requireDocumentSize(file, path, maximum, signal) {
|
|
474
|
+
const metadata = await file.stat();
|
|
475
|
+
throwIfAborted(signal);
|
|
476
|
+
if (metadata.size > maximum) {
|
|
477
|
+
throw new ContractValidationError(`${path}: JSON document exceeds the ${maximum}-byte limit.`);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
async function readBoundedDocument(file, path, maximum, signal) {
|
|
481
|
+
await requireDocumentSize(file, path, maximum, signal);
|
|
482
|
+
const chunks = [];
|
|
483
|
+
let length = 0;
|
|
484
|
+
let exhausted = false;
|
|
485
|
+
while (length <= maximum && !exhausted) {
|
|
486
|
+
const chunk = Buffer.allocUnsafe(Math.min(DOCUMENT_READ_CHUNK_BYTES, maximum + 1 - length));
|
|
487
|
+
let offset = 0;
|
|
488
|
+
while (offset < chunk.byteLength) {
|
|
489
|
+
throwIfAborted(signal);
|
|
490
|
+
const result = await file.read(chunk, offset, chunk.byteLength - offset, length);
|
|
491
|
+
throwIfAborted(signal);
|
|
492
|
+
if (result.bytesRead === 0) {
|
|
493
|
+
exhausted = true;
|
|
494
|
+
break;
|
|
495
|
+
}
|
|
496
|
+
offset += result.bytesRead;
|
|
497
|
+
length += result.bytesRead;
|
|
498
|
+
if (length > maximum) {
|
|
499
|
+
throw new ContractValidationError(`${path}: JSON document exceeds the ${maximum}-byte limit.`);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
if (offset > 0)
|
|
503
|
+
chunks.push(chunk.subarray(0, offset));
|
|
504
|
+
}
|
|
505
|
+
return Buffer.concat(chunks, length);
|
|
506
|
+
}
|
|
507
|
+
function parseJson(path, bytes) {
|
|
508
|
+
let text;
|
|
509
|
+
try {
|
|
510
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
511
|
+
}
|
|
512
|
+
catch (error) {
|
|
513
|
+
throw new ContractValidationError(`${path}: unreadable JSON document.`, {
|
|
514
|
+
cause: error,
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
requireJsonNesting(text, path);
|
|
518
|
+
let payload;
|
|
519
|
+
try {
|
|
520
|
+
payload = JSON.parse(text);
|
|
521
|
+
}
|
|
522
|
+
catch (error) {
|
|
523
|
+
throw new ContractValidationError(`${path}: invalid JSON: ${String(error)}`, { cause: error });
|
|
524
|
+
}
|
|
525
|
+
if (!isRecord(payload)) {
|
|
526
|
+
throw new ContractValidationError(`${path}: expected a JSON object.`);
|
|
527
|
+
}
|
|
528
|
+
validateParsedJson(payload, path);
|
|
529
|
+
return payload;
|
|
530
|
+
}
|
|
531
|
+
function requireJsonNesting(text, path) {
|
|
532
|
+
let depth = 0;
|
|
533
|
+
let inString = false;
|
|
534
|
+
let escaped = false;
|
|
535
|
+
for (const character of text) {
|
|
536
|
+
if (inString) {
|
|
537
|
+
if (escaped)
|
|
538
|
+
escaped = false;
|
|
539
|
+
else if (character === "\\")
|
|
540
|
+
escaped = true;
|
|
541
|
+
else if (character === '"')
|
|
542
|
+
inString = false;
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (character === '"')
|
|
546
|
+
inString = true;
|
|
547
|
+
else if (character === "{" || character === "[") {
|
|
548
|
+
depth += 1;
|
|
549
|
+
if (depth > MAX_JSON_DEPTH + 1) {
|
|
550
|
+
throw new ContractValidationError(`${path}: JSON document exceeds the ${MAX_JSON_DEPTH}-level nesting limit.`);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
else if (character === "}" || character === "]")
|
|
554
|
+
depth -= 1;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
function validateParsedJson(value, context, depth = 0) {
|
|
558
|
+
if (depth > MAX_JSON_DEPTH) {
|
|
559
|
+
throw new ContractValidationError(`${context}: JSON document exceeds the ${MAX_JSON_DEPTH}-level nesting limit.`);
|
|
560
|
+
}
|
|
561
|
+
if (typeof value === "number") {
|
|
562
|
+
if (!Number.isFinite(value)) {
|
|
563
|
+
throw new ContractValidationError(`${context}: non-finite JSON numbers are not supported.`);
|
|
564
|
+
}
|
|
565
|
+
if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
|
|
566
|
+
throw new ContractValidationError(`${context}: unsafe integer-valued JSON numbers are not supported.`);
|
|
567
|
+
}
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
if (typeof value === "string") {
|
|
571
|
+
if (!isWellFormedUnicode(value)) {
|
|
572
|
+
throw new ContractValidationError(`${context}: expected well-formed Unicode JSON strings.`);
|
|
573
|
+
}
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
if (Array.isArray(value)) {
|
|
577
|
+
for (const [index, item] of value.entries()) {
|
|
578
|
+
validateParsedJson(item, `${context}[${index}]`, depth + 1);
|
|
579
|
+
}
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
if (isRecord(value)) {
|
|
583
|
+
for (const [key, item] of Object.entries(value)) {
|
|
584
|
+
if (!isWellFormedUnicode(key)) {
|
|
585
|
+
throw new ContractValidationError(`${context}: expected well-formed Unicode JSON keys.`);
|
|
586
|
+
}
|
|
587
|
+
validateParsedJson(item, `${context}.<property>`, depth + 1);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
function isWellFormedUnicode(value) {
|
|
592
|
+
return Buffer.from(value, "utf8").toString("utf8") === value;
|
|
593
|
+
}
|
|
594
|
+
function createValidator() {
|
|
595
|
+
// The plugin schemas are the immutable v0 contract. They are valid Draft
|
|
596
|
+
// 2020-12 but intentionally omit redundant local `type` keywords that Ajv's
|
|
597
|
+
// optional strict-schema linter requires.
|
|
598
|
+
const ajv = new Ajv2020({ allErrors: false, strict: false });
|
|
599
|
+
ajv.addFormat("date-time", {
|
|
600
|
+
type: "string",
|
|
601
|
+
validate: validRfc3339DateTime,
|
|
602
|
+
});
|
|
603
|
+
return ajv;
|
|
604
|
+
}
|
|
605
|
+
function requireSchemaComplexity(schema, schemaName) {
|
|
606
|
+
const pending = [
|
|
607
|
+
{ value: schema, isSchema: true },
|
|
608
|
+
];
|
|
609
|
+
let nodes = 0;
|
|
610
|
+
let applicatorEdges = 0;
|
|
611
|
+
while (pending.length > 0) {
|
|
612
|
+
const current = pending.pop();
|
|
613
|
+
const value = current.value;
|
|
614
|
+
nodes += 1;
|
|
615
|
+
if (nodes > MAX_SCHEMA_NODES) {
|
|
616
|
+
throw new ContractValidationError(`${schemaName}: JSON Schema exceeds the ${MAX_SCHEMA_NODES}-node complexity limit.`);
|
|
617
|
+
}
|
|
618
|
+
if (Array.isArray(value)) {
|
|
619
|
+
if (value.length > MAX_SCHEMA_COLLECTION_ENTRIES) {
|
|
620
|
+
throw new ContractValidationError(`${schemaName}: JSON Schema exceeds the ${MAX_SCHEMA_COLLECTION_ENTRIES}-entry collection limit.`);
|
|
621
|
+
}
|
|
622
|
+
for (const child of value) {
|
|
623
|
+
pending.push({ value: child, isSchema: current.isSchema });
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
else if (isRecord(value)) {
|
|
627
|
+
const entries = Object.entries(value);
|
|
628
|
+
if (entries.length > MAX_SCHEMA_COLLECTION_ENTRIES) {
|
|
629
|
+
throw new ContractValidationError(`${schemaName}: JSON Schema exceeds the ${MAX_SCHEMA_COLLECTION_ENTRIES}-entry collection limit.`);
|
|
630
|
+
}
|
|
631
|
+
for (const [keyword, child] of entries) {
|
|
632
|
+
if (!current.isSchema) {
|
|
633
|
+
pending.push({ value: child, isSchema: false });
|
|
634
|
+
continue;
|
|
635
|
+
}
|
|
636
|
+
if (keyword === "$async" ||
|
|
637
|
+
keyword === "$ref" ||
|
|
638
|
+
keyword === "$dynamicRef" ||
|
|
639
|
+
keyword === "$recursiveRef" ||
|
|
640
|
+
keyword === "prefixItems" ||
|
|
641
|
+
keyword === "patternProperties" ||
|
|
642
|
+
keyword === "propertyNames" ||
|
|
643
|
+
keyword === "dependentSchemas" ||
|
|
644
|
+
keyword === "dependencies" ||
|
|
645
|
+
keyword === "uniqueItems") {
|
|
646
|
+
throw new ContractValidationError(`${schemaName}: unsupported JSON Schema keyword.`);
|
|
647
|
+
}
|
|
648
|
+
let edges = 0;
|
|
649
|
+
if ((keyword === "allOf" || keyword === "anyOf" || keyword === "oneOf") &&
|
|
650
|
+
Array.isArray(child)) {
|
|
651
|
+
edges = child.length;
|
|
652
|
+
}
|
|
653
|
+
else if ((keyword === "if" ||
|
|
654
|
+
keyword === "then" ||
|
|
655
|
+
keyword === "else" ||
|
|
656
|
+
keyword === "not" ||
|
|
657
|
+
keyword === "items" ||
|
|
658
|
+
keyword === "contains" ||
|
|
659
|
+
keyword === "additionalProperties" ||
|
|
660
|
+
keyword === "unevaluatedProperties" ||
|
|
661
|
+
keyword === "unevaluatedItems") &&
|
|
662
|
+
(typeof child === "boolean" || isRecord(child))) {
|
|
663
|
+
edges = 1;
|
|
664
|
+
}
|
|
665
|
+
else if ((keyword === "properties" ||
|
|
666
|
+
keyword === "$defs" ||
|
|
667
|
+
keyword === "definitions") &&
|
|
668
|
+
isRecord(child)) {
|
|
669
|
+
edges = Object.keys(child).length;
|
|
670
|
+
}
|
|
671
|
+
applicatorEdges += edges;
|
|
672
|
+
if (applicatorEdges > MAX_SCHEMA_APPLICATOR_EDGES) {
|
|
673
|
+
throw new ContractValidationError(`${schemaName}: JSON Schema exceeds the ${MAX_SCHEMA_APPLICATOR_EDGES}-edge applicator limit.`);
|
|
674
|
+
}
|
|
675
|
+
if (keyword === "pattern" &&
|
|
676
|
+
typeof child === "string" &&
|
|
677
|
+
!SAFE_SCHEMA_PATTERNS.has(child)) {
|
|
678
|
+
throw new ContractValidationError(`${schemaName}: unsupported JSON Schema pattern.`);
|
|
679
|
+
}
|
|
680
|
+
if ((keyword === "properties" ||
|
|
681
|
+
keyword === "$defs" ||
|
|
682
|
+
keyword === "definitions") &&
|
|
683
|
+
isRecord(child)) {
|
|
684
|
+
const schemas = Object.values(child);
|
|
685
|
+
if (schemas.length > MAX_SCHEMA_COLLECTION_ENTRIES) {
|
|
686
|
+
throw new ContractValidationError(`${schemaName}: JSON Schema exceeds the ${MAX_SCHEMA_COLLECTION_ENTRIES}-entry collection limit.`);
|
|
687
|
+
}
|
|
688
|
+
for (const childSchema of schemas) {
|
|
689
|
+
pending.push({ value: childSchema, isSchema: true });
|
|
690
|
+
}
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
const isSchema = keyword !== "const" &&
|
|
694
|
+
keyword !== "enum" &&
|
|
695
|
+
keyword !== "default" &&
|
|
696
|
+
keyword !== "examples" &&
|
|
697
|
+
keyword !== "dependentRequired";
|
|
698
|
+
pending.push({ value: child, isSchema });
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
async function sha256ScanFile(scanDir, relativePath, context, signal, expectedRoot) {
|
|
704
|
+
const file = await openCheckedScanFile(scanDir, relativePath, context, signal, expectedRoot);
|
|
705
|
+
try {
|
|
706
|
+
throwIfAborted(signal);
|
|
707
|
+
const digest = createHash("sha256");
|
|
708
|
+
for await (const chunk of file.createReadStream({
|
|
709
|
+
signal,
|
|
710
|
+
autoClose: false,
|
|
711
|
+
})) {
|
|
712
|
+
digest.update(chunk);
|
|
713
|
+
}
|
|
714
|
+
throwIfAborted(signal);
|
|
715
|
+
return digest.digest("hex");
|
|
716
|
+
}
|
|
717
|
+
finally {
|
|
718
|
+
await file.close();
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
async function openCheckedScanFile(scanDir, relativePath, context, signal, expectedRoot) {
|
|
722
|
+
const checked = await requireCheckedScanFile(scanDir, relativePath, context, signal, expectedRoot);
|
|
723
|
+
let file;
|
|
724
|
+
try {
|
|
725
|
+
file = await open(checked.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
726
|
+
const opened = await file.stat();
|
|
727
|
+
throwIfAborted(signal);
|
|
728
|
+
if (!opened.isFile() ||
|
|
729
|
+
opened.dev !== checked.metadata.dev ||
|
|
730
|
+
opened.ino !== checked.metadata.ino) {
|
|
731
|
+
throw new ContractValidationError(`${context}: expected the checked regular file.`);
|
|
732
|
+
}
|
|
733
|
+
for (const parent of checked.parents) {
|
|
734
|
+
const current = await lstat(parent.path);
|
|
735
|
+
throwIfAborted(signal);
|
|
736
|
+
if (!current.isDirectory() ||
|
|
737
|
+
current.isSymbolicLink() ||
|
|
738
|
+
current.dev !== parent.metadata.dev ||
|
|
739
|
+
current.ino !== parent.metadata.ino) {
|
|
740
|
+
throw new ContractValidationError(`${context}: checked parent changed before opening the file.`);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
const current = await lstat(checked.path);
|
|
744
|
+
throwIfAborted(signal);
|
|
745
|
+
if (!current.isFile() ||
|
|
746
|
+
current.isSymbolicLink() ||
|
|
747
|
+
current.dev !== checked.metadata.dev ||
|
|
748
|
+
current.ino !== checked.metadata.ino) {
|
|
749
|
+
throw new ContractValidationError(`${context}: checked file changed before reading.`);
|
|
750
|
+
}
|
|
751
|
+
return file;
|
|
752
|
+
}
|
|
753
|
+
catch (error) {
|
|
754
|
+
await file?.close();
|
|
755
|
+
throwIfAborted(signal);
|
|
756
|
+
if (error instanceof ContractValidationError)
|
|
757
|
+
throw error;
|
|
758
|
+
throw new ContractValidationError(`${context}: unable to open the checked regular file.`, { cause: error });
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
function throwIfAborted(signal) {
|
|
762
|
+
if (!signal?.aborted)
|
|
763
|
+
return;
|
|
764
|
+
throw (signal.reason ??
|
|
765
|
+
new DOMException("The operation was aborted.", "AbortError"));
|
|
766
|
+
}
|
|
767
|
+
function validRfc3339DateTime(value) {
|
|
768
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i.exec(value);
|
|
769
|
+
if (match === null)
|
|
770
|
+
return false;
|
|
771
|
+
const year = Number(match[1]);
|
|
772
|
+
const month = Number(match[2]);
|
|
773
|
+
const day = Number(match[3]);
|
|
774
|
+
const hour = Number(match[4]);
|
|
775
|
+
const minute = Number(match[5]);
|
|
776
|
+
const second = Number(match[6]);
|
|
777
|
+
const offsetHour = Number(match[7] ?? 0);
|
|
778
|
+
const offsetMinute = Number(match[8] ?? 0);
|
|
779
|
+
if (year < 1 ||
|
|
780
|
+
month < 1 ||
|
|
781
|
+
month > 12 ||
|
|
782
|
+
day < 1 ||
|
|
783
|
+
hour > 23 ||
|
|
784
|
+
minute > 59 ||
|
|
785
|
+
second > 59 ||
|
|
786
|
+
offsetHour > 23 ||
|
|
787
|
+
offsetMinute > 59) {
|
|
788
|
+
return false;
|
|
789
|
+
}
|
|
790
|
+
const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
791
|
+
const daysInMonth = [
|
|
792
|
+
31,
|
|
793
|
+
leapYear ? 29 : 28,
|
|
794
|
+
31,
|
|
795
|
+
30,
|
|
796
|
+
31,
|
|
797
|
+
30,
|
|
798
|
+
31,
|
|
799
|
+
31,
|
|
800
|
+
30,
|
|
801
|
+
31,
|
|
802
|
+
30,
|
|
803
|
+
31,
|
|
804
|
+
][month - 1];
|
|
805
|
+
return day <= daysInMonth;
|
|
806
|
+
}
|
|
807
|
+
function schemaError(filename, errors) {
|
|
808
|
+
const first = errors[0];
|
|
809
|
+
const segments = first?.instancePath.split("/").filter(Boolean) ?? [];
|
|
810
|
+
const location = segments.length === 0
|
|
811
|
+
? "<root>"
|
|
812
|
+
: segments
|
|
813
|
+
.slice(0, MAX_JSON_DEPTH)
|
|
814
|
+
.map((segment) => {
|
|
815
|
+
if (/^(?:0|[1-9]\d{0,9})$/.test(segment))
|
|
816
|
+
return segment;
|
|
817
|
+
return SAFE_SCHEMA_ERROR_PROPERTIES.has(segment)
|
|
818
|
+
? segment
|
|
819
|
+
: "<property>";
|
|
820
|
+
})
|
|
821
|
+
.join(".");
|
|
822
|
+
const keyword = first?.keyword ?? "unknown";
|
|
823
|
+
const count = errors.length;
|
|
824
|
+
const format = first?.params["format"];
|
|
825
|
+
const detail = keyword === "format" && format === "date-time" ? "; date-time" : "";
|
|
826
|
+
return new ContractValidationError(`${filename}:${location}: schema validation failed (${keyword}${detail}; ${count} ${count === 1 ? "error" : "errors"}).`);
|
|
827
|
+
}
|
|
828
|
+
function sameArray(left, right) {
|
|
829
|
+
return (left.length === right.length &&
|
|
830
|
+
left.every((value, index) => value === right[index]));
|
|
831
|
+
}
|
|
832
|
+
function sameSet(left, right) {
|
|
833
|
+
return (left.size === right.size && [...left].every((value) => right.has(value)));
|
|
834
|
+
}
|
|
835
|
+
function isContained(root, candidate) {
|
|
836
|
+
const child = relative(root, candidate);
|
|
837
|
+
return (child === "" ||
|
|
838
|
+
(child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute(child)));
|
|
839
|
+
}
|
|
840
|
+
function isRecord(value) {
|
|
841
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
842
|
+
}
|
|
843
|
+
function nodeErrorCode(error) {
|
|
844
|
+
return typeof error === "object" && error !== null && "code" in error
|
|
845
|
+
? String(error.code)
|
|
846
|
+
: undefined;
|
|
847
|
+
}
|
|
848
|
+
//# sourceMappingURL=contract.js.map
|