coldpin 0.0.0-stage → 1.5.1

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.
Files changed (102) hide show
  1. package/ACCESSIBILITY.md +17 -0
  2. package/CHANGELOG.md +97 -0
  3. package/CONTRIBUTING.md +36 -0
  4. package/LICENSE +98 -0
  5. package/MAINTENANCE.md +33 -0
  6. package/README.md +142 -2
  7. package/SECURITY.md +34 -0
  8. package/TESTING.md +26 -0
  9. package/agents/coldpin-auditor.md +47 -0
  10. package/agents/coldpin-compliance.md +38 -0
  11. package/agents/coldpin-confusion-auditor.md +38 -0
  12. package/agents/coldpin-discoverer.md +37 -0
  13. package/agents/coldpin-forensics.md +38 -0
  14. package/agents/coldpin-inspector.md +37 -0
  15. package/agents/coldpin-manifest-auditor.md +38 -0
  16. package/assets/icon.svg +7 -0
  17. package/catalog/mcp-schema-pin.json +14 -0
  18. package/catalog/plugin.oms.sig +19 -0
  19. package/catalog/sigma/npx-suspicious-child-process-linux.yml +54 -0
  20. package/catalog/sigma/npx-suspicious-child-process.yml +49 -0
  21. package/catalog/triage-rules.json +104 -0
  22. package/docs/assets/readme-header.svg +21 -0
  23. package/docs/designs/SITEMAP.md +14 -0
  24. package/docs/designs/coldpin.md +68 -0
  25. package/docs/fact-ledger.md +36 -0
  26. package/docs/faq.md +31 -0
  27. package/docs/getting_started.md +62 -0
  28. package/docs/harnesses.md +45 -0
  29. package/docs/privacy.md +27 -0
  30. package/docs/verification/skill-inspector-self-audit.md +33 -0
  31. package/examples/.coldpin.policy.example.json +27 -0
  32. package/examples/.npmrc.example +8 -0
  33. package/examples/mcp_config.private-registry.example.json +42 -0
  34. package/hooks.json +47 -0
  35. package/lib/analysis/parity-and-bisect.mjs +1371 -0
  36. package/lib/analysis/static-triage.mjs +4572 -0
  37. package/lib/cache/sqlite-store.mjs +251 -0
  38. package/lib/cli.mjs +427 -0
  39. package/lib/compliance/audit-log.mjs +357 -0
  40. package/lib/config/policy.mjs +780 -0
  41. package/lib/core/path-confinement.mjs +289 -0
  42. package/lib/core/workflows.mjs +1205 -0
  43. package/lib/discovery/slopsquat-guard.mjs +289 -0
  44. package/lib/hook.mjs +1038 -0
  45. package/lib/intel/registry-osv.mjs +1681 -0
  46. package/lib/mcp/report-store.mjs +175 -0
  47. package/lib/mcp/server.mjs +1387 -0
  48. package/lib/mcp/stdio-transport.mjs +289 -0
  49. package/lib/mcp/tool-catalog.mjs +273 -0
  50. package/lib/mcp/types.mjs +95 -0
  51. package/lib/mcp.mjs +19 -0
  52. package/lib/quarantine/safe-unpack.mjs +568 -0
  53. package/lib/types.mjs +383 -0
  54. package/lib/verdict/engine-and-formatters.mjs +895 -0
  55. package/mcp_config.json +21 -0
  56. package/package.json +71 -3
  57. package/plugin.json +54 -0
  58. package/rules/AGENTS.md +18 -0
  59. package/rules/coldpin-incident-checklist.md +18 -0
  60. package/rules/coldpin-manifest-guard.md +14 -0
  61. package/server.json +38 -0
  62. package/skills/coldpin/BENCHMARK.md +166 -0
  63. package/skills/coldpin/SKILL.md +110 -0
  64. package/skills/coldpin/TEST.md +13 -0
  65. package/skills/coldpin/agents/openai.yaml +6 -0
  66. package/skills/coldpin/assets/icon.svg +7 -0
  67. package/skills/coldpin/assets/runtime-contract.yaml +105 -0
  68. package/skills/coldpin/evals/evals.json +60 -0
  69. package/skills/coldpin/references/aspect-compliance-audit.md +27 -0
  70. package/skills/coldpin/references/aspect-discovery.md +26 -0
  71. package/skills/coldpin/references/aspect-forensics-rea.md +26 -0
  72. package/skills/coldpin/references/aspect-inspection.md +26 -0
  73. package/skills/coldpin/references/aspect-manifest-confusion.md +26 -0
  74. package/skills/coldpin/references/enterprise-policy-schema.md +65 -0
  75. package/skills/coldpin/references/evidence-card-spec.md +27 -0
  76. package/skills/coldpin/references/rea-integration-playbook.md +34 -0
  77. package/skills/coldpin/references/threat-taxonomy.md +35 -0
  78. package/skills/coldpin/skill-card.md +62 -0
  79. package/skills/coldpin/skill.oms.sig +19 -0
  80. package/skills/coldpin/test_scenarios.yaml +61 -0
  81. package/skills/coldpin-audit/SKILL.md +39 -0
  82. package/skills/coldpin-incident/SKILL.md +37 -0
  83. package/src/analysis/parity-and-bisect.ts +1368 -0
  84. package/src/analysis/static-triage.ts +4569 -0
  85. package/src/cache/sqlite-store.ts +248 -0
  86. package/src/cli.ts +424 -0
  87. package/src/compliance/audit-log.ts +354 -0
  88. package/src/config/policy.ts +777 -0
  89. package/src/core/path-confinement.ts +286 -0
  90. package/src/core/workflows.ts +1202 -0
  91. package/src/discovery/slopsquat-guard.ts +286 -0
  92. package/src/hook.ts +1035 -0
  93. package/src/intel/registry-osv.ts +1678 -0
  94. package/src/mcp/report-store.ts +172 -0
  95. package/src/mcp/server.ts +1384 -0
  96. package/src/mcp/stdio-transport.ts +286 -0
  97. package/src/mcp/tool-catalog.ts +270 -0
  98. package/src/mcp/types.ts +92 -0
  99. package/src/mcp.ts +16 -0
  100. package/src/quarantine/safe-unpack.ts +565 -0
  101. package/src/types.ts +380 -0
  102. package/src/verdict/engine-and-formatters.ts +892 -0
@@ -0,0 +1,1681 @@
1
+ import { createHash, createPublicKey, verify as cryptoVerify, X509Certificate } from "node:crypto";
2
+ import { lookup as dnsLookup } from "node:dns/promises";
3
+ import { existsSync } from "node:fs";
4
+ import { isIP } from "node:net";
5
+ import { dirname, resolve } from "node:path";
6
+ import { SingleFlight, } from "../cache/sqlite-store.mjs";
7
+ import {
8
+ isPublicNpmRegistryUrl,
9
+ loadNpmrc,
10
+ routeDiscoveryQuery,
11
+
12
+ } from "../config/policy.mjs";
13
+ import { openReadCappedFile, redactHomePath } from "../core/path-confinement.mjs";
14
+ import {
15
+ ENGINE_VERSION,
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+ } from "../types.mjs";
27
+ import { sanitizeUntrustedText } from "../analysis/static-triage.mjs";
28
+ import { evaluateSlopsquatAndCooldown } from "../discovery/slopsquat-guard.mjs";
29
+
30
+ const USER_AGENT = `coldpin/${ENGINE_VERSION}`;
31
+ const osvDetailFlight = new SingleFlight ();
32
+ const versionMetaFlight = new SingleFlight
33
+
34
+
35
+
36
+
37
+ ();
38
+ const tarballFlight = new SingleFlight ();
39
+ const MAX_PACKUMENT_JSON_BYTES = 25 * 1024 * 1024;
40
+ const MAX_SMALL_JSON_BYTES = 4 * 1024 * 1024;
41
+ const MAX_MANIFEST_BYTES = 2 * 1024 * 1024;
42
+
43
+ function hashAuthScope(token ) {
44
+ return createHash("sha256").update(token ?? "anon").digest("hex").slice(0, 16);
45
+ }
46
+
47
+ const BLOCKED_METADATA_HOSTS = new Set([
48
+ "169.254.169.254",
49
+ "100.100.100.200",
50
+ "metadata.google.internal",
51
+ "metadata.goog",
52
+ "fd00:ec2::254",
53
+ ]);
54
+ const MAX_REDIRECT_HOPS = 5;
55
+
56
+ function decodeMappedIpv4(host ) {
57
+ if (!host.startsWith("::ffff:")) return null;
58
+ const mapped = host.slice("::ffff:".length);
59
+ if (mapped.includes(".")) return mapped;
60
+ const parts = mapped.split(":");
61
+ if (parts.length !== 2) return null;
62
+ const hi = Number.parseInt(parts[0] , 16);
63
+ const lo = Number.parseInt(parts[1] , 16);
64
+ if (!Number.isFinite(hi) || !Number.isFinite(lo)) return null;
65
+ return `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`;
66
+ }
67
+
68
+ function parseIpv4Octets(ip ) {
69
+ const parts = ip.split(".");
70
+ if (parts.length !== 4) return null;
71
+ const nums = parts.map((p) => (/^\d+$/.test(p) ? Number(p) : -1));
72
+ if (nums.some((n) => n < 0 || n > 255)) return null;
73
+ return [nums[0] , nums[1] , nums[2] , nums[3] ];
74
+ }
75
+
76
+ export function isPrivateOrReservedIpv4(ip ) {
77
+ const oct = parseIpv4Octets(ip);
78
+ if (!oct) return false;
79
+ const [a, b] = oct;
80
+ if (a === 0) return true; // 0.0.0.0/8 unspecified
81
+ if (a === 10) return true; // 10.0.0.0/8 RFC1918
82
+ if (a === 100 && b >= 64 && b <= 127) return true; // 100.64.0.0/10 CGNAT
83
+ if (a === 127) return true; // 127.0.0.0/8 loopback
84
+ if (a === 169 && b === 254) return true; // 169.254.0.0/16 link-local / IMDS
85
+ if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12 RFC1918
86
+ if (a === 192 && b === 168) return true; // 192.168.0.0/16 RFC1918
87
+ return false;
88
+ }
89
+
90
+ function isMetadataOrLinkLocalHost(rawHost ) {
91
+ const host = rawHost.toLowerCase().replace(/^\[|\]$/g, "");
92
+ if (BLOCKED_METADATA_HOSTS.has(host) || host.startsWith("169.254.")) return true;
93
+ if (/^fe[89ab][0-9a-f]:/.test(host)) return true;
94
+ const mappedV4 = decodeMappedIpv4(host);
95
+ if (mappedV4) {
96
+ return BLOCKED_METADATA_HOSTS.has(mappedV4) || mappedV4.startsWith("169.254.");
97
+ }
98
+ return false;
99
+ }
100
+
101
+ function isLoopbackHost(rawHost ) {
102
+ const host = rawHost.toLowerCase().replace(/^\[|\]$/g, "");
103
+ if (
104
+ host === "localhost" ||
105
+ host.endsWith(".localhost") ||
106
+ host.startsWith("127.") ||
107
+ host.startsWith("0.") ||
108
+ host === "0.0.0.0" ||
109
+ host === "::1" ||
110
+ host === "::" ||
111
+ host === "0:0:0:0:0:0:0:1" ||
112
+ host === "0:0:0:0:0:0:0:0"
113
+ ) {
114
+ return true;
115
+ }
116
+ const mappedV4 = decodeMappedIpv4(host);
117
+ return Boolean(mappedV4 && (mappedV4.startsWith("127.") || mappedV4.startsWith("0.")));
118
+ }
119
+
120
+ export function isPrivateOrReservedIp(rawHost ) {
121
+ const host = rawHost.toLowerCase().replace(/^\[|\]$/g, "");
122
+ if (isMetadataOrLinkLocalHost(host) || isLoopbackHost(host)) return true;
123
+ if (isPrivateOrReservedIpv4(host)) return true;
124
+ if (/^f[cd][0-9a-f]{2}:/.test(host)) return true; // IPv6 ULA fc00::/7
125
+ const mappedV4 = decodeMappedIpv4(host);
126
+ if (mappedV4 && isPrivateOrReservedIpv4(mappedV4)) return true;
127
+ return false;
128
+ }
129
+
130
+ function isPublicOsvUrl(rawUrl ) {
131
+ try {
132
+ return new URL(rawUrl).hostname.toLowerCase() === "api.osv.dev";
133
+ } catch {
134
+ return true;
135
+ }
136
+ }
137
+
138
+ export function validateOutboundUrl(
139
+ rawUrl ,
140
+ allowPlainHttpForExplicitOrigin ,
141
+ allowedPrivateOrigin ,
142
+ ) {
143
+ let parsed ;
144
+ try {
145
+ parsed = new URL(rawUrl);
146
+ } catch {
147
+ return { ok: false, error: `Malformed URL: ${rawUrl}` };
148
+ }
149
+ if (parsed.username || parsed.password) {
150
+ return { ok: false, error: "Rejected outbound URL containing embedded credentials/userinfo." };
151
+ }
152
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
153
+ if (isMetadataOrLinkLocalHost(host)) {
154
+ return { ok: false, error: `Blocked link-local/cloud metadata host '${host}' (SSRF defense).` };
155
+ }
156
+ const matchesExplicitHttp = Boolean(allowPlainHttpForExplicitOrigin && parsed.origin === allowPlainHttpForExplicitOrigin);
157
+ const matchesExplicitPrivate =
158
+ matchesExplicitHttp || Boolean(allowedPrivateOrigin && parsed.origin === allowedPrivateOrigin);
159
+
160
+ if (isLoopbackHost(host) && !matchesExplicitPrivate) {
161
+ return { ok: false, error: `Blocked loopback/unspecified host '${host}' (SSRF defense).` };
162
+ }
163
+ if (isIP(host) !== 0 && isPrivateOrReservedIp(host) && !matchesExplicitPrivate) {
164
+ return { ok: false, error: `Blocked private/reserved IP host '${host}' (SSRF defense).` };
165
+ }
166
+ if (parsed.protocol === "https:") {
167
+ return { ok: true, parsed };
168
+ }
169
+ if (parsed.protocol === "http:" && matchesExplicitHttp) {
170
+ return { ok: true, parsed };
171
+ }
172
+ return {
173
+ ok: false,
174
+ error: `Rejected non-HTTPS outbound URL '${parsed.protocol}//${parsed.host}'.`,
175
+ };
176
+ }
177
+
178
+ async function verifyDnsNotSsrf(
179
+ host ,
180
+ allowPrivateTarget ,
181
+ ) {
182
+ if (isIP(host) !== 0) return { ok: true };
183
+ try {
184
+ const records = await dnsLookup(host, { all: true });
185
+ for (const rec of records) {
186
+ if (isMetadataOrLinkLocalHost(rec.address)) {
187
+ return { ok: false, error: `DNS resolved '${host}' to blocked metadata/link-local address '${rec.address}'.` };
188
+ }
189
+ if (!allowPrivateTarget && isPrivateOrReservedIp(rec.address)) {
190
+ return { ok: false, error: `DNS resolved '${host}' to blocked private/reserved address '${rec.address}'.` };
191
+ }
192
+ }
193
+ return { ok: true };
194
+ } catch (err) {
195
+ return { ok: false, error: `DNS lookup failed for '${host}': ${err instanceof Error ? err.message : String(err)}` };
196
+ }
197
+ }
198
+
199
+ export async function readResponseBytesCapped(
200
+ res ,
201
+ maxBytes ,
202
+ label ,
203
+ ) {
204
+ const contentLen = Number.parseInt(res.headers.get("content-length") ?? "", 10);
205
+ if (Number.isFinite(contentLen) && contentLen > maxBytes) {
206
+ return { ok: false, error: `${label} content-length (${contentLen}) exceeded limit (${maxBytes} bytes)` };
207
+ }
208
+ if (!res.body) return { ok: false, error: `Empty ${label} response body` };
209
+ const chunks = [];
210
+ let total = 0;
211
+ const reader = res.body.getReader();
212
+ while (true) {
213
+ const { done, value } = await reader.read();
214
+ if (done) break;
215
+ if (value) {
216
+ total += value.byteLength;
217
+ if (total > maxBytes) {
218
+ await reader.cancel();
219
+ return { ok: false, error: `${label} response exceeded limit (${maxBytes} bytes)` };
220
+ }
221
+ chunks.push(Buffer.from(value));
222
+ }
223
+ }
224
+ return { ok: true, buffer: Buffer.concat(chunks, total) };
225
+ }
226
+
227
+ export async function fetchWithSafeRedirects(params
228
+
229
+
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+ ) {
238
+ const method = params.method ?? "GET";
239
+ let currentUrl = params.url;
240
+ for (let hop = 0; hop <= MAX_REDIRECT_HOPS; hop++) {
241
+ const check = validateOutboundUrl(currentUrl, params.allowPlainHttpOrigin, params.allowedPrivateOrigin);
242
+ if (!check.ok || !check.parsed) {
243
+ return { ok: false, error: check.error };
244
+ }
245
+ const host = check.parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
246
+ const allowPrivateTarget =
247
+ Boolean(params.allowPlainHttpOrigin && check.parsed.origin === params.allowPlainHttpOrigin) ||
248
+ Boolean(params.allowedPrivateOrigin && check.parsed.origin === params.allowedPrivateOrigin);
249
+ const dnsCheck = await verifyDnsNotSsrf(host, allowPrivateTarget);
250
+ if (!dnsCheck.ok) {
251
+ return { ok: false, error: dnsCheck.error };
252
+ }
253
+
254
+ const reqHeaders = { connection: "close" };
255
+ // Strip sensitive credential headers case-insensitively before setting origin-scoped HTTPS-only auth (CWE-200)
256
+ for (const [k, v] of Object.entries(params.headers)) {
257
+ const kl = k.toLowerCase();
258
+ if (kl === "authorization" || kl === "proxy-authorization" || kl === "cookie") continue;
259
+ reqHeaders[k] = v;
260
+ }
261
+ // Security [MCP-09]: strictly require HTTPS + exact origin match before attaching Bearer token
262
+ if (
263
+ params.authToken &&
264
+ params.allowedAuthOrigin &&
265
+ check.parsed.protocol === "https:" &&
266
+ check.parsed.origin === params.allowedAuthOrigin
267
+ ) {
268
+ reqHeaders["authorization"] = `Bearer ${params.authToken}`;
269
+ }
270
+
271
+ const res = await fetch(currentUrl, {
272
+ method,
273
+ headers: reqHeaders,
274
+ ...(method === "POST" && params.body !== undefined ? { body: params.body } : {}),
275
+ redirect: "manual",
276
+ signal: params.signal,
277
+ });
278
+
279
+ if (res.status >= 300 && res.status < 400) {
280
+ if (method === "POST") {
281
+ return { ok: false, error: `Refused HTTP ${res.status} redirect on POST request.` };
282
+ }
283
+ const location = res.headers.get("location");
284
+ if (!location) return { ok: false, error: `Redirect HTTP ${res.status} without Location header` };
285
+ try {
286
+ currentUrl = new URL(location, currentUrl).toString();
287
+ } catch {
288
+ return { ok: false, error: "Invalid redirect Location URL" };
289
+ }
290
+ continue;
291
+ }
292
+
293
+ return { ok: true, response: res };
294
+ }
295
+ return { ok: false, error: `Exceeded max redirect hops (${MAX_REDIRECT_HOPS})` };
296
+ }
297
+
298
+
299
+
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+
316
+
317
+
318
+
319
+
320
+
321
+
322
+
323
+
324
+
325
+
326
+
327
+
328
+
329
+
330
+
331
+
332
+
333
+
334
+
335
+
336
+
337
+
338
+
339
+
340
+
341
+
342
+
343
+
344
+
345
+
346
+
347
+
348
+
349
+
350
+
351
+
352
+
353
+ function encodePkgName(name ) {
354
+ return name.startsWith("@") ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name);
355
+ }
356
+
357
+ function extractLicense(raw ) {
358
+ if (typeof raw === "string" && raw.trim()) return raw.trim();
359
+ if (raw && typeof raw === "object" && "type" in raw && typeof (raw ).type === "string") {
360
+ return (raw ).type;
361
+ }
362
+ return "UNKNOWN";
363
+ }
364
+
365
+ function extractCreator(raw ) {
366
+ if (typeof raw === "string" && raw.trim()) return sanitizeUntrustedText(raw, 80);
367
+ if (raw && typeof raw === "object" && "name" in raw && typeof (raw ).name === "string") {
368
+ return sanitizeUntrustedText((raw ).name, 80);
369
+ }
370
+ return "unknown";
371
+ }
372
+
373
+ function extractRepo(raw ) {
374
+ if (typeof raw === "string") return { url: raw };
375
+ if (raw && typeof raw === "object") {
376
+ const obj = raw ;
377
+ return {
378
+ url: typeof obj.url === "string" ? obj.url : undefined,
379
+ directory: typeof obj.directory === "string" ? obj.directory : undefined,
380
+ };
381
+ }
382
+ return {};
383
+ }
384
+
385
+ function extractBinNames(pkgName , rawBin ) {
386
+ if (typeof rawBin === "string") {
387
+ const bare = pkgName.includes("/") ? pkgName.slice(pkgName.indexOf("/") + 1) : pkgName;
388
+ return [bare];
389
+ }
390
+ if (rawBin && typeof rawBin === "object" && !Array.isArray(rawBin)) {
391
+ return Object.keys(rawBin );
392
+ }
393
+ return [];
394
+ }
395
+
396
+ function extractProvenanceUrl(versionObj ) {
397
+ const dist = versionObj["dist"];
398
+ if (!dist || typeof dist !== "object") return undefined;
399
+ const attestations = (dist )["attestations"];
400
+ if (!attestations || typeof attestations !== "object") return undefined;
401
+ const url = (attestations )["url"];
402
+ return typeof url === "string" && url.trim().length > 0 ? url.trim() : undefined;
403
+ }
404
+
405
+ function sriOrHexToSha512Hex(raw ) {
406
+ const trimmed = raw.trim();
407
+ if (trimmed.startsWith("sha512-")) {
408
+ const buf = Buffer.from(trimmed.slice("sha512-".length), "base64");
409
+ return buf.length === 64 ? buf.toString("hex").toLowerCase() : null;
410
+ }
411
+ if (/^[0-9a-f]{128}$/i.test(trimmed)) {
412
+ return trimmed.toLowerCase();
413
+ }
414
+ return null;
415
+ }
416
+
417
+ function parseNpmPurl(subjectName ) {
418
+ if (!subjectName.startsWith("pkg:npm/")) return null;
419
+ let rest = subjectName.slice("pkg:npm/".length);
420
+ const qIdx = rest.indexOf("?");
421
+ if (qIdx !== -1) rest = rest.slice(0, qIdx);
422
+ const hIdx = rest.indexOf("#");
423
+ if (hIdx !== -1) rest = rest.slice(0, hIdx);
424
+ if (!rest) return null;
425
+
426
+ const atIdx = rest.lastIndexOf("@");
427
+ const rawName = atIdx > 0 ? rest.slice(0, atIdx) : rest;
428
+ const rawVersion = atIdx > 0 ? rest.slice(atIdx + 1) : undefined;
429
+ let decodedName ;
430
+ try {
431
+ decodedName = decodeURIComponent(rawName);
432
+ } catch {
433
+ decodedName = rawName.replace(/^%40/i, "@").replace(/%2f/gi, "/");
434
+ }
435
+ if (!decodedName) return null;
436
+ let decodedVersion ;
437
+ if (rawVersion && rawVersion.length > 0) {
438
+ try {
439
+ decodedVersion = decodeURIComponent(rawVersion);
440
+ } catch {
441
+ decodedVersion = rawVersion;
442
+ }
443
+ }
444
+ return { name: decodedName, ...(decodedVersion ? { version: decodedVersion } : {}) };
445
+ }
446
+
447
+ function dssePae(payloadType , payloadBytes ) {
448
+ const ptBuf = Buffer.from(payloadType, "utf8");
449
+ return Buffer.concat([
450
+ Buffer.from(`DSSEv1 ${ptBuf.length} `, "utf8"),
451
+ ptBuf,
452
+ Buffer.from(` ${payloadBytes.length} `, "utf8"),
453
+ payloadBytes,
454
+ ]);
455
+ }
456
+
457
+ /**
458
+ * Locally inspects an npm Sigstore/SLSA attestation document against the downloaded tarball SHA-512.
459
+ * Epistemic boundary:
460
+ * - Verifies in-toto Statement subject SHA-512 + npm PURL package/version identity binding and verifies
461
+ * the DSSE signature against the bundled leaf X.509 certificate (or explicit publicKeyPem).
462
+ * - NEVER sets `provenance_attested: true` without Sigstore Fulcio CA chain + Rekor TUF root
463
+ * verification; returns `dsse_leaf_verified_unanchored` with an explicit trust-root unknown instead.
464
+ * - Flags tampered subject digests, mismatched package/version PURLs, or invalid DSSE signatures as CRITICAL.
465
+ */
466
+ export function verifyNpmAttestationPayload(
467
+ doc ,
468
+ expectedTarballSha512 ,
469
+ expectedPackageName ,
470
+ provenanceUrl ,
471
+ expectedPackageVersion ,
472
+ ) {
473
+ const observations = [];
474
+ const unknowns = [];
475
+ const expectedHex = sriOrHexToSha512Hex(expectedTarballSha512);
476
+ if (!expectedHex) {
477
+ unknowns.push("PROVENANCE_CRYPTO_UNVERIFIED: could not normalize expected tarball SHA-512 for attestation comparison.");
478
+ return { status: "metadata_url_only", provenance_url: provenanceUrl, provenance_attested: false, observations, unknowns };
479
+ }
480
+
481
+ let slsaBundle = null;
482
+ let declaredPredicateType ;
483
+
484
+ if (doc && typeof doc === "object") {
485
+ const obj = doc ;
486
+ if (Array.isArray(obj["attestations"])) {
487
+ for (const item of obj["attestations"]) {
488
+ if (!item || typeof item !== "object") continue;
489
+ const rec = item ;
490
+ const pt = typeof rec["predicateType"] === "string" ? rec["predicateType"] : "";
491
+ if (pt.startsWith("https://slsa.dev/provenance/") && rec["bundle"] && typeof rec["bundle"] === "object") {
492
+ slsaBundle = rec["bundle"] ;
493
+ declaredPredicateType = pt;
494
+ break;
495
+ }
496
+ }
497
+ } else if (obj["dsseEnvelope"] && typeof obj["dsseEnvelope"] === "object") {
498
+ slsaBundle = obj;
499
+ }
500
+ }
501
+
502
+ if (!slsaBundle) {
503
+ unknowns.push(
504
+ "PROVENANCE_CRYPTO_UNVERIFIED: registry attestation endpoint returned no SLSA provenance bundle; Sigstore/SLSA provenance is NOT verified.",
505
+ );
506
+ return { status: "metadata_url_only", provenance_url: provenanceUrl, provenance_attested: false, observations, unknowns };
507
+ }
508
+
509
+ const envelope = slsaBundle["dsseEnvelope"];
510
+ if (!envelope || typeof envelope !== "object") {
511
+ observations.push({
512
+ code: "PROVENANCE_DSSE_SIGNATURE_INVALID",
513
+ severity: "CRITICAL",
514
+ path: "<attestation>",
515
+ attack_id: "T1195.002",
516
+ detail: "npm SLSA attestation bundle is missing a valid dsseEnvelope.",
517
+ });
518
+ return { status: "verification_failed", provenance_url: provenanceUrl, provenance_attested: false, observations, unknowns };
519
+ }
520
+
521
+ const envObj = envelope ;
522
+ const payloadType = typeof envObj["payloadType"] === "string" ? envObj["payloadType"] : "";
523
+ const payloadB64 = typeof envObj["payload"] === "string" ? envObj["payload"] : "";
524
+ const signatures = Array.isArray(envObj["signatures"]) ? (envObj["signatures"] ) : [];
525
+ const sigEntries = signatures
526
+ .map((s) => (s && typeof s === "object" && typeof s["sig"] === "string" ? String(s["sig"]).trim() : ""))
527
+ .filter((s) => s.length > 0);
528
+
529
+ if (payloadType !== "application/vnd.in-toto+json" || !payloadB64 || sigEntries.length === 0) {
530
+ observations.push({
531
+ code: "PROVENANCE_DSSE_SIGNATURE_INVALID",
532
+ severity: "CRITICAL",
533
+ path: "<attestation>",
534
+ attack_id: "T1195.002",
535
+ detail: `Invalid or incomplete DSSE envelope (payloadType='${sanitizeUntrustedText(payloadType, 64)}').`,
536
+ });
537
+ return { status: "verification_failed", provenance_url: provenanceUrl, provenance_attested: false, observations, unknowns };
538
+ }
539
+
540
+ const payloadBytes = Buffer.from(payloadB64, "base64");
541
+ let statement ;
542
+ try {
543
+ const parsed = JSON.parse(payloadBytes.toString("utf8"));
544
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
545
+ throw new Error("Statement is not a JSON object");
546
+ }
547
+ statement = parsed ;
548
+ } catch {
549
+ observations.push({
550
+ code: "PROVENANCE_DSSE_SIGNATURE_INVALID",
551
+ severity: "CRITICAL",
552
+ path: "<attestation>",
553
+ attack_id: "T1195.002",
554
+ detail: "Failed to parse base64-encoded in-toto Statement JSON inside DSSE envelope.",
555
+ });
556
+ return { status: "verification_failed", provenance_url: provenanceUrl, provenance_attested: false, observations, unknowns };
557
+ }
558
+
559
+ const stmtType = typeof statement["_type"] === "string" ? statement["_type"] : "";
560
+ const stmtPredicateType = typeof statement["predicateType"] === "string" ? statement["predicateType"] : declaredPredicateType;
561
+ if (
562
+ (stmtType !== "https://in-toto.io/Statement/v1" && stmtType !== "https://in-toto.io/Statement/v0.1") ||
563
+ !stmtPredicateType?.startsWith("https://slsa.dev/provenance/")
564
+ ) {
565
+ observations.push({
566
+ code: "PROVENANCE_DSSE_SIGNATURE_INVALID",
567
+ severity: "CRITICAL",
568
+ path: "<attestation>",
569
+ attack_id: "T1195.002",
570
+ detail: `Unexpected in-toto statement _type ('${sanitizeUntrustedText(stmtType, 48)}') or predicateType ('${sanitizeUntrustedText(stmtPredicateType ?? "", 64)}').`,
571
+ });
572
+ return { status: "verification_failed", provenance_url: provenanceUrl, provenance_attested: false, observations, unknowns };
573
+ }
574
+
575
+ const subjects = Array.isArray(statement["subject"]) ? (statement["subject"] ) : [];
576
+ const matchedSubject = subjects.find((s) => {
577
+ const dig = s?.["digest"];
578
+ if (!dig || typeof dig !== "object") return false;
579
+ const sha512 = (dig )["sha512"];
580
+ return typeof sha512 === "string" && sha512.toLowerCase() === expectedHex;
581
+ });
582
+
583
+ if (!matchedSubject) {
584
+ observations.push({
585
+ code: "PROVENANCE_DIGEST_MISMATCH",
586
+ severity: "CRITICAL",
587
+ path: "<attestation>",
588
+ attack_id: "T1195.002",
589
+ detail: "SLSA attestation subject SHA-512 does not match the verified tarball digest.",
590
+ });
591
+ return {
592
+ status: "verification_failed",
593
+ provenance_url: provenanceUrl,
594
+ provenance_attested: false,
595
+ predicate_type: stmtPredicateType,
596
+ observations,
597
+ unknowns,
598
+ };
599
+ }
600
+
601
+ if (expectedPackageName) {
602
+ const rawSubName = typeof matchedSubject["name"] === "string" ? matchedSubject["name"].trim() : "";
603
+ const parsedPurl = rawSubName ? parseNpmPurl(rawSubName) : null;
604
+ if (!parsedPurl) {
605
+ observations.push({
606
+ code: "PROVENANCE_DIGEST_MISMATCH",
607
+ severity: "CRITICAL",
608
+ path: "<attestation>",
609
+ attack_id: "T1195.002",
610
+ detail: `SLSA attestation subject name '${sanitizeUntrustedText(rawSubName || "<missing>", 80)}' is not a valid npm PURL for inspected package '${sanitizeUntrustedText(expectedPackageName, 80)}'.`,
611
+ });
612
+ return {
613
+ status: "verification_failed",
614
+ provenance_url: provenanceUrl,
615
+ provenance_attested: false,
616
+ predicate_type: stmtPredicateType,
617
+ observations,
618
+ unknowns,
619
+ };
620
+ }
621
+ if (parsedPurl.name.toLowerCase() !== expectedPackageName.toLowerCase()) {
622
+ observations.push({
623
+ code: "PROVENANCE_DIGEST_MISMATCH",
624
+ severity: "CRITICAL",
625
+ path: "<attestation>",
626
+ attack_id: "T1195.002",
627
+ detail: `SLSA attestation subject package '${sanitizeUntrustedText(parsedPurl.name, 80)}' does not match inspected package '${sanitizeUntrustedText(expectedPackageName, 80)}'.`,
628
+ });
629
+ return {
630
+ status: "verification_failed",
631
+ provenance_url: provenanceUrl,
632
+ provenance_attested: false,
633
+ predicate_type: stmtPredicateType,
634
+ observations,
635
+ unknowns,
636
+ };
637
+ }
638
+ if (expectedPackageVersion && parsedPurl.version && parsedPurl.version !== expectedPackageVersion) {
639
+ observations.push({
640
+ code: "PROVENANCE_DIGEST_MISMATCH",
641
+ severity: "CRITICAL",
642
+ path: "<attestation>",
643
+ attack_id: "T1195.002",
644
+ detail: `SLSA attestation subject version '${sanitizeUntrustedText(parsedPurl.version, 48)}' does not match inspected version '${sanitizeUntrustedText(expectedPackageVersion, 48)}'.`,
645
+ });
646
+ return {
647
+ status: "verification_failed",
648
+ provenance_url: provenanceUrl,
649
+ provenance_attested: false,
650
+ predicate_type: stmtPredicateType,
651
+ observations,
652
+ unknowns,
653
+ };
654
+ }
655
+ }
656
+
657
+ // Extract optional SLSA v1 / v0.2 metadata for transparency
658
+ const pred = (statement["predicate"] && typeof statement["predicate"] === "object"
659
+ ? (statement["predicate"] )
660
+ : {}) ;
661
+ const runDetails = pred["runDetails"] ;
662
+ const builderObj = (runDetails?.["builder"] ?? pred["builder"]) ;
663
+ const builderId = typeof builderObj?.["id"] === "string" ? sanitizeUntrustedText(builderObj["id"], 120) : undefined;
664
+ const buildDef = pred["buildDefinition"] ;
665
+ const extParams = buildDef?.["externalParameters"] ;
666
+ const workflow = extParams?.["workflow"] ;
667
+ const invocation = pred["invocation"] ;
668
+ const configSource = invocation?.["configSource"] ;
669
+ const sourceRepoRaw =
670
+ typeof workflow?.["repository"] === "string"
671
+ ? workflow["repository"]
672
+ : typeof configSource?.["uri"] === "string"
673
+ ? configSource["uri"]
674
+ : undefined;
675
+ const sourceRepo = sourceRepoRaw ? sanitizeUntrustedText(sourceRepoRaw, 140) : undefined;
676
+ const resolvedDeps = Array.isArray(buildDef?.["resolvedDependencies"])
677
+ ? (buildDef["resolvedDependencies"] )
678
+ : [];
679
+ const firstDepDigest = resolvedDeps[0]?.["digest"] ;
680
+ const cfgDigest = configSource?.["digest"] ;
681
+ const sourceCommit =
682
+ typeof firstDepDigest?.["gitCommit"] === "string"
683
+ ? sanitizeUntrustedText(firstDepDigest["gitCommit"], 48)
684
+ : typeof firstDepDigest?.["sha1"] === "string"
685
+ ? sanitizeUntrustedText(firstDepDigest["sha1"], 48)
686
+ : typeof cfgDigest?.["sha1"] === "string"
687
+ ? sanitizeUntrustedText(cfgDigest["sha1"], 48)
688
+ : undefined;
689
+
690
+ // Verify DSSE signature against bundled leaf X.509 certificate or public key
691
+ const vm = (slsaBundle["verificationMaterial"] && typeof slsaBundle["verificationMaterial"] === "object"
692
+ ? (slsaBundle["verificationMaterial"] )
693
+ : {}) ;
694
+ const hasRekorTlog = Array.isArray(vm["tlogEntries"]) && vm["tlogEntries"].length > 0;
695
+
696
+ let leafCertRawB64 ;
697
+ const certObj = vm["certificate"] ;
698
+ if (typeof certObj?.["rawBytes"] === "string") {
699
+ leafCertRawB64 = certObj["rawBytes"];
700
+ } else {
701
+ const chainObj = vm["x509CertificateChain"] ;
702
+ const certs = Array.isArray(chainObj?.["certificates"]) ? (chainObj["certificates"] ) : [];
703
+ if (typeof certs[0]?.["rawBytes"] === "string") {
704
+ leafCertRawB64 = certs[0]["rawBytes"];
705
+ }
706
+ }
707
+ const pubKeyPem = typeof vm["publicKeyPem"] === "string" ? vm["publicKeyPem"] : undefined;
708
+
709
+ if (!leafCertRawB64 && !pubKeyPem) {
710
+ unknowns.push(
711
+ "PROVENANCE_CRYPTO_UNVERIFIED: SLSA subject SHA-512 matched tarball, but verificationMaterial omitted a certificate/public key; DSSE signature and Sigstore trust root were NOT verified.",
712
+ );
713
+ return {
714
+ status: "metadata_url_only",
715
+ provenance_url: provenanceUrl,
716
+ provenance_attested: false,
717
+ predicate_type: stmtPredicateType,
718
+ builder_id: builderId,
719
+ source_repo: sourceRepo,
720
+ source_commit: sourceCommit,
721
+ has_rekor_tlog_entry: hasRekorTlog,
722
+ observations,
723
+ unknowns,
724
+ };
725
+ }
726
+
727
+ let sigValid = false;
728
+ try {
729
+ const pubKey = leafCertRawB64
730
+ ? new X509Certificate(Buffer.from(leafCertRawB64, "base64")).publicKey
731
+ : createPublicKey(pubKeyPem );
732
+ const keyType = pubKey.asymmetricKeyType;
733
+ const curve = pubKey.asymmetricKeyDetails?.namedCurve;
734
+ const hashAlg =
735
+ keyType === "ed25519" || keyType === "ed448"
736
+ ? null
737
+ : curve === "secp384r1"
738
+ ? "sha384"
739
+ : curve === "secp521r1"
740
+ ? "sha512"
741
+ : "sha256";
742
+ const pae = dssePae(payloadType, payloadBytes);
743
+ for (const sigB64 of sigEntries) {
744
+ if (cryptoVerify(hashAlg, pae, pubKey, Buffer.from(sigB64, "base64"))) {
745
+ sigValid = true;
746
+ break;
747
+ }
748
+ }
749
+ } catch {
750
+ sigValid = false;
751
+ }
752
+
753
+ if (!sigValid) {
754
+ observations.push({
755
+ code: "PROVENANCE_DSSE_SIGNATURE_INVALID",
756
+ severity: "CRITICAL",
757
+ path: "<attestation>",
758
+ attack_id: "T1195.002",
759
+ detail: "SLSA DSSE envelope signature failed cryptographic verification against the bundled certificate/key.",
760
+ });
761
+ return {
762
+ status: "verification_failed",
763
+ provenance_url: provenanceUrl,
764
+ provenance_attested: false,
765
+ predicate_type: stmtPredicateType,
766
+ builder_id: builderId,
767
+ source_repo: sourceRepo,
768
+ source_commit: sourceCommit,
769
+ has_rekor_tlog_entry: hasRekorTlog,
770
+ observations,
771
+ unknowns,
772
+ };
773
+ }
774
+
775
+ unknowns.push(
776
+ "PROVENANCE_TRUST_ROOT_UNVERIFIED: SLSA DSSE signature verified against bundled leaf certificate and subject SHA-512 matched tarball, but Sigstore Fulcio CA chain and Rekor transparency-log proofs were NOT verified locally (no embedded Sigstore TUF trusted_root). Run 'npm audit signatures' or cosign for full cryptographic verification.",
777
+ );
778
+ return {
779
+ status: "dsse_leaf_verified_unanchored",
780
+ provenance_url: provenanceUrl,
781
+ provenance_attested: false,
782
+ predicate_type: stmtPredicateType,
783
+ builder_id: builderId,
784
+ source_repo: sourceRepo,
785
+ source_commit: sourceCommit,
786
+ has_rekor_tlog_entry: hasRekorTlog,
787
+ observations,
788
+ unknowns,
789
+ };
790
+ }
791
+
792
+ export async function inspectNpmAttestationBundle(params
793
+
794
+
795
+
796
+
797
+
798
+
799
+
800
+
801
+ ) {
802
+ // Enforce private-scope non-leakage: never fetch public npmjs.org or off-registry attestation URLs for private scopes
803
+ if (params.route === "private") {
804
+ let attOrigin ;
805
+ try {
806
+ attOrigin = new URL(params.attestationUrl).origin;
807
+ } catch {
808
+ attOrigin = undefined;
809
+ }
810
+ if (
811
+ isPublicNpmRegistryUrl(params.attestationUrl) ||
812
+ (params.allowedAuthOrigin && attOrigin !== params.allowedAuthOrigin)
813
+ ) {
814
+ return {
815
+ status: "metadata_url_only",
816
+ provenance_url: params.attestationUrl,
817
+ provenance_attested: false,
818
+ observations: [],
819
+ unknowns: [
820
+ "PRIVATE_SCOPE_PROVENANCE_FETCH_SUPPRESSED: skipped off-origin/public dist.attestations.url fetch to prevent internal package metadata leakage.",
821
+ ],
822
+ };
823
+ }
824
+ }
825
+ const MAX_ATTESTATION_BYTES = 2 * 1024 * 1024;
826
+ const controller = new AbortController();
827
+ const timer = setTimeout(() => controller.abort(), params.timeoutMs ?? 10000);
828
+ try {
829
+ let allowHttpOrigin ;
830
+ if (params.allowedAuthOrigin && params.allowedAuthOrigin.startsWith("http://")) {
831
+ allowHttpOrigin = params.allowedAuthOrigin;
832
+ }
833
+ const fetched = await fetchWithSafeRedirects({
834
+ url: params.attestationUrl,
835
+ headers: { "user-agent": USER_AGENT, accept: "application/json" },
836
+ authToken: params.authToken,
837
+ allowedAuthOrigin: params.allowedAuthOrigin,
838
+ allowPlainHttpOrigin: allowHttpOrigin,
839
+ allowedPrivateOrigin: params.allowedAuthOrigin,
840
+ signal: controller.signal,
841
+ });
842
+ if (!fetched.ok || !fetched.response) {
843
+ return {
844
+ status: "metadata_url_only",
845
+ provenance_url: params.attestationUrl,
846
+ provenance_attested: false,
847
+ observations: [],
848
+ unknowns: [
849
+ `PROVENANCE_ATTESTATION_FETCH_FAILED: registry metadata advertised dist.attestations.url, but fetching the attestation bundle failed (${fetched.error ?? "network error"}); Sigstore/SLSA provenance is NOT verified.`,
850
+ ],
851
+ };
852
+ }
853
+ const res = fetched.response;
854
+ if (!res.ok) {
855
+ return {
856
+ status: "metadata_url_only",
857
+ provenance_url: params.attestationUrl,
858
+ provenance_attested: false,
859
+ observations: [],
860
+ unknowns: [
861
+ `PROVENANCE_ATTESTATION_FETCH_FAILED: registry metadata advertised dist.attestations.url, but endpoint returned HTTP ${res.status}; Sigstore/SLSA provenance is NOT verified.`,
862
+ ],
863
+ };
864
+ }
865
+ const readRes = await readResponseBytesCapped(res, MAX_ATTESTATION_BYTES, "Attestation");
866
+ if (!readRes.ok) {
867
+ return {
868
+ status: "metadata_url_only",
869
+ provenance_url: params.attestationUrl,
870
+ provenance_attested: false,
871
+ observations: [],
872
+ unknowns: [
873
+ `PROVENANCE_ATTESTATION_FETCH_FAILED: ${readRes.error}; Sigstore/SLSA provenance is NOT verified.`,
874
+ ],
875
+ };
876
+ }
877
+ let parsed ;
878
+ try {
879
+ parsed = JSON.parse(readRes.buffer.toString("utf8"));
880
+ } catch {
881
+ return {
882
+ status: "metadata_url_only",
883
+ provenance_url: params.attestationUrl,
884
+ provenance_attested: false,
885
+ observations: [],
886
+ unknowns: [
887
+ "PROVENANCE_ATTESTATION_FETCH_FAILED: attestation endpoint returned malformed JSON; Sigstore/SLSA provenance is NOT verified.",
888
+ ],
889
+ };
890
+ }
891
+ return verifyNpmAttestationPayload(
892
+ parsed,
893
+ params.expectedTarballSha512,
894
+ params.expectedPackageName,
895
+ params.attestationUrl,
896
+ params.expectedPackageVersion,
897
+ );
898
+ } catch (err) {
899
+ return {
900
+ status: "metadata_url_only",
901
+ provenance_url: params.attestationUrl,
902
+ provenance_attested: false,
903
+ observations: [],
904
+ unknowns: [
905
+ `PROVENANCE_ATTESTATION_FETCH_FAILED: ${err instanceof Error ? err.message : String(err)}; Sigstore/SLSA provenance is NOT verified.`,
906
+ ],
907
+ };
908
+ } finally {
909
+ clearTimeout(timer);
910
+ }
911
+ }
912
+
913
+ async function fetchJsonWithTimeout (
914
+ url ,
915
+ headers ,
916
+ timeoutMs = 12000,
917
+ auth ,
918
+ opts
919
+
920
+
921
+
922
+ ,
923
+ ) {
924
+ const controller = new AbortController();
925
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
926
+ try {
927
+ // Security [MCP-09]: never auto-set allowPlainHttpOrigin from untrusted `url`;
928
+ // only honor explicit server/policy-configured origins passed by caller.
929
+ const fetched = await fetchWithSafeRedirects({
930
+ url,
931
+ headers,
932
+ authToken: auth?.token,
933
+ allowedAuthOrigin: auth?.allowedOrigin,
934
+ allowPlainHttpOrigin: opts?.allowPlainHttpOrigin,
935
+ allowedPrivateOrigin: opts?.allowedPrivateOrigin,
936
+ signal: controller.signal,
937
+ });
938
+ if (!fetched.ok || !fetched.response) {
939
+ return { ok: false, status: 0, error: fetched.error ?? "fetch failed" };
940
+ }
941
+ const res = fetched.response;
942
+ if (!res.ok) return { ok: false, status: res.status, error: `HTTP ${res.status}` };
943
+ const maxBytes = opts?.maxBytes ?? MAX_SMALL_JSON_BYTES;
944
+ const readRes = await readResponseBytesCapped(res, maxBytes, "JSON");
945
+ if (!readRes.ok) {
946
+ return { ok: false, status: res.status, error: readRes.error };
947
+ }
948
+ const data = JSON.parse(readRes.buffer.toString("utf8")) ;
949
+ return { ok: true, status: res.status, data };
950
+ } catch (err) {
951
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
952
+ } finally {
953
+ clearTimeout(timer);
954
+ }
955
+ }
956
+
957
+ export async function fetchTarballBuffer(
958
+ tarballUrl ,
959
+ maxBytes ,
960
+ authToken ,
961
+ timeoutMs = 20000,
962
+ allowedAuthOrigin ,
963
+ callerSignal ,
964
+ ) {
965
+ const flightKey = `${tarballUrl}|${maxBytes}|${hashAuthScope(authToken)}`;
966
+ try {
967
+ const shared = await tarballFlight.run(
968
+ flightKey,
969
+ async () => {
970
+ const controller = new AbortController();
971
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
972
+ try {
973
+ const allowHttpOrigin =
974
+ allowedAuthOrigin && allowedAuthOrigin.startsWith("http://") ? allowedAuthOrigin : undefined;
975
+ const fetched = await fetchWithSafeRedirects({
976
+ url: tarballUrl,
977
+ headers: { "user-agent": USER_AGENT },
978
+ authToken,
979
+ allowedAuthOrigin,
980
+ allowPlainHttpOrigin: allowHttpOrigin,
981
+ allowedPrivateOrigin: allowedAuthOrigin,
982
+ signal: controller.signal,
983
+ });
984
+ if (!fetched.ok || !fetched.response) {
985
+ return { ok: false, error: fetched.error ?? "Failed downloading tarball" };
986
+ }
987
+ const res = fetched.response;
988
+ if (!res.ok) return { ok: false, error: `HTTP ${res.status} downloading tarball` };
989
+ const readRes = await readResponseBytesCapped(res, maxBytes, "Tarball");
990
+ if (!readRes.ok) return { ok: false, error: readRes.error };
991
+ return { ok: true, buffer: readRes.buffer };
992
+ } catch (err) {
993
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
994
+ } finally {
995
+ clearTimeout(timer);
996
+ }
997
+ },
998
+ callerSignal,
999
+ );
1000
+ // Return an isolated Buffer copy to each waiter so mutations cannot leak across concurrent requests
1001
+ if (shared.ok && shared.buffer) {
1002
+ return { ok: true, buffer: Buffer.from(shared.buffer) };
1003
+ }
1004
+ return shared;
1005
+ } catch (err) {
1006
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
1007
+ }
1008
+ }
1009
+
1010
+ export async function fetchVersionMetadata(params
1011
+
1012
+
1013
+
1014
+
1015
+
1016
+ ) {
1017
+ const flightKey = `${params.registry_url}|${params.package_name}|${params.version ?? "latest"}|${hashAuthScope(params.auth_token)}`;
1018
+ try {
1019
+ return await versionMetaFlight.run(
1020
+ flightKey,
1021
+ async () => {
1022
+ const headers = {
1023
+ "user-agent": USER_AGENT,
1024
+ accept: "application/json",
1025
+ };
1026
+ let parsedReg ;
1027
+ try {
1028
+ parsedReg = new URL(params.registry_url);
1029
+ } catch {
1030
+ return { ok: false, error: `Invalid registry URL: ${params.registry_url}` };
1031
+ }
1032
+ const registryOrigin = parsedReg.origin;
1033
+ const allowHttpOrigin = parsedReg.protocol === "http:" ? registryOrigin : undefined;
1034
+ const auth = params.auth_token ? { token: params.auth_token, allowedOrigin: registryOrigin } : undefined;
1035
+ const netOpts = {
1036
+ maxBytes: MAX_PACKUMENT_JSON_BYTES,
1037
+ allowPlainHttpOrigin: allowHttpOrigin,
1038
+ allowedPrivateOrigin: registryOrigin,
1039
+ };
1040
+
1041
+ const baseUrl = `${params.registry_url}/${encodePkgName(params.package_name)}`;
1042
+ // Fetch packument first so time[ver] (cooldown), time.created (slopsquat age), dist-tags, and release history
1043
+ // are ALWAYS preserved even when an explicit @version is inspected!
1044
+ const res = await fetchJsonWithTimeout (baseUrl, headers, 12000, auth, netOpts);
1045
+
1046
+ if (res.ok && res.data) {
1047
+ const doc = res.data;
1048
+ const distTags = (doc["dist-tags"] ?? {}) ;
1049
+ const versions = (doc["versions"] ?? {}) ;
1050
+ const timeMap = (doc["time"] ?? {}) ;
1051
+ const latestVer = distTags["latest"];
1052
+ const requestedVer =
1053
+ params.version && params.version !== "latest"
1054
+ ? (versions[params.version] ? params.version : distTags[params.version])
1055
+ : latestVer;
1056
+
1057
+ const buildMeta = (ver , vObj ) => {
1058
+ const dist = (vObj["dist"] ?? {}) ;
1059
+ const repo = extractRepo(vObj["repository"] ?? doc["repository"]);
1060
+ const provUrl = extractProvenanceUrl(vObj);
1061
+ return {
1062
+ name: String(vObj["name"] ?? params.package_name),
1063
+ version: ver,
1064
+ tarball_url: String(dist["tarball"] ?? ""),
1065
+ integrity: typeof dist["integrity"] === "string" ? dist["integrity"] : undefined,
1066
+ git_head: typeof vObj["gitHead"] === "string" ? vObj["gitHead"] : undefined,
1067
+ repository_url: repo.url,
1068
+ repository_directory: repo.directory,
1069
+ // Packument dist.attestations.url alone is unverified metadata, never cryptographic Sigstore attestation
1070
+ provenance_attested: false,
1071
+ provenance_status: provUrl ? "metadata_url_only" : "none",
1072
+ provenance_url: provUrl,
1073
+ published_at: timeMap[ver],
1074
+ created_at: timeMap["created"],
1075
+ license: extractLicense(vObj["license"] ?? doc["license"]),
1076
+ creator: extractCreator(vObj["author"] ?? vObj["_npmUser"]),
1077
+ description: sanitizeUntrustedText(String(vObj["description"] ?? doc["description"] ?? ""), 220),
1078
+ keywords: Array.isArray(vObj["keywords"] ?? doc["keywords"])
1079
+ ? ((vObj["keywords"] ?? doc["keywords"]) )
1080
+ .filter((k) => typeof k === "string")
1081
+ .slice(0, 10)
1082
+ : [],
1083
+ scripts:
1084
+ vObj["scripts"] && typeof vObj["scripts"] === "object"
1085
+ ? (vObj["scripts"] )
1086
+ : {},
1087
+ dependencies:
1088
+ vObj["dependencies"] && typeof vObj["dependencies"] === "object"
1089
+ ? (vObj["dependencies"] )
1090
+ : {},
1091
+ optional_dependencies:
1092
+ vObj["optionalDependencies"] && typeof vObj["optionalDependencies"] === "object"
1093
+ ? (vObj["optionalDependencies"] )
1094
+ : {},
1095
+ bin_names: extractBinNames(params.package_name, vObj["bin"]),
1096
+ };
1097
+ };
1098
+
1099
+ if (requestedVer && versions[requestedVer]) {
1100
+ const targetMeta = buildMeta(requestedVer, versions[requestedVer] );
1101
+ const latestMeta = latestVer && versions[latestVer] ? buildMeta(latestVer, versions[latestVer] ) : targetMeta;
1102
+ const versionsDesc = Object.entries(versions)
1103
+ .map(([ver, vObj]) => {
1104
+ const dist = (vObj["dist"] ?? {}) ;
1105
+ const provUrl = extractProvenanceUrl(vObj);
1106
+ return {
1107
+ version: ver,
1108
+ published_at: timeMap[ver],
1109
+ tarball_url: String(dist["tarball"] ?? ""),
1110
+ integrity: typeof dist["integrity"] === "string" ? dist["integrity"] : undefined,
1111
+ git_head: typeof vObj["gitHead"] === "string" ? vObj["gitHead"] : undefined,
1112
+ provenance_attested: false,
1113
+ provenance_status: provUrl ? ("metadata_url_only" ) : ("none" ),
1114
+ provenance_url: provUrl,
1115
+ dependencies:
1116
+ vObj["dependencies"] && typeof vObj["dependencies"] === "object"
1117
+ ? (vObj["dependencies"] )
1118
+ : {},
1119
+ optional_dependencies:
1120
+ vObj["optionalDependencies"] && typeof vObj["optionalDependencies"] === "object"
1121
+ ? (vObj["optionalDependencies"] )
1122
+ : {},
1123
+ };
1124
+ })
1125
+ .sort((a, b) => Date.parse(b.published_at ?? "0") - Date.parse(a.published_at ?? "0"))
1126
+ .slice(0, 30);
1127
+
1128
+ return {
1129
+ ok: true,
1130
+ meta: targetMeta,
1131
+ packument: {
1132
+ name: latestMeta.name,
1133
+ latest_version: latestVer ?? requestedVer,
1134
+ created_at: timeMap["created"],
1135
+ versions_desc: versionsDesc,
1136
+ latest_meta: latestMeta,
1137
+ },
1138
+ };
1139
+ }
1140
+ }
1141
+
1142
+ // Fallback to single-version endpoint if packument omitted the explicit version or returned error
1143
+ if (params.version && params.version !== "latest") {
1144
+ const singleUrl = `${baseUrl}/${encodeURIComponent(params.version)}`;
1145
+ const single = await fetchJsonWithTimeout (singleUrl, headers, 12000, auth, netOpts);
1146
+ if (!single.ok || !single.data) {
1147
+ return { ok: false, error: single.error ?? res.error ?? "Failed to fetch version metadata" };
1148
+ }
1149
+ const vObj = single.data;
1150
+ const dist = (vObj["dist"] ?? {}) ;
1151
+ const repo = extractRepo(vObj["repository"]);
1152
+ const provUrl = extractProvenanceUrl(vObj);
1153
+ const meta = {
1154
+ name: String(vObj["name"] ?? params.package_name),
1155
+ version: String(vObj["version"] ?? params.version),
1156
+ tarball_url: String(dist["tarball"] ?? ""),
1157
+ integrity: typeof dist["integrity"] === "string" ? dist["integrity"] : undefined,
1158
+ git_head: typeof vObj["gitHead"] === "string" ? vObj["gitHead"] : undefined,
1159
+ repository_url: repo.url,
1160
+ repository_directory: repo.directory,
1161
+ provenance_attested: false,
1162
+ provenance_status: provUrl ? "metadata_url_only" : "none",
1163
+ provenance_url: provUrl,
1164
+ license: extractLicense(vObj["license"]),
1165
+ creator: extractCreator(vObj["author"] ?? vObj["_npmUser"]),
1166
+ description: sanitizeUntrustedText(String(vObj["description"] ?? ""), 220),
1167
+ keywords: Array.isArray(vObj["keywords"])
1168
+ ? vObj["keywords"].filter((k) => typeof k === "string").slice(0, 10)
1169
+ : [],
1170
+ scripts:
1171
+ vObj["scripts"] && typeof vObj["scripts"] === "object"
1172
+ ? (vObj["scripts"] )
1173
+ : {},
1174
+ dependencies:
1175
+ vObj["dependencies"] && typeof vObj["dependencies"] === "object"
1176
+ ? (vObj["dependencies"] )
1177
+ : {},
1178
+ optional_dependencies:
1179
+ vObj["optionalDependencies"] && typeof vObj["optionalDependencies"] === "object"
1180
+ ? (vObj["optionalDependencies"] )
1181
+ : {},
1182
+ bin_names: extractBinNames(params.package_name, vObj["bin"]),
1183
+ };
1184
+ return { ok: true, meta };
1185
+ }
1186
+
1187
+ return { ok: false, error: res.error ?? `No 'latest' version found for ${params.package_name}` };
1188
+ },
1189
+ params.signal,
1190
+ );
1191
+ } catch (err) {
1192
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
1193
+ }
1194
+ }
1195
+
1196
+ function mapOsvSeverity(vuln ) {
1197
+ const id = String(vuln["id"] ?? "");
1198
+ if (id.startsWith("MAL-")) return "CRITICAL";
1199
+ const dbSpec = vuln["database_specific"] ;
1200
+ const sevStr = String(dbSpec?.["severity"] ?? "").toUpperCase();
1201
+ if (sevStr === "CRITICAL") return "CRITICAL";
1202
+ if (sevStr === "HIGH") return "HIGH";
1203
+ if (sevStr === "MODERATE" || sevStr === "MEDIUM") return "MEDIUM";
1204
+ if (sevStr === "LOW") return "LOW";
1205
+ return "HIGH";
1206
+ }
1207
+
1208
+ export async function queryOsvAdvisories(params
1209
+
1210
+
1211
+
1212
+
1213
+ ) {
1214
+ const unknowns = [];
1215
+ if (params.policy.offline_mode) {
1216
+ unknowns.push("OFFLINE_INTEL_SKIPPED: OSV/OpenSSF MAL-* lookup skipped in offline mode.");
1217
+ return { advisories: [], unknowns };
1218
+ }
1219
+ const osvBaseUrl = (params.policy.osv_api_url || "https://api.osv.dev").replace(/\/+$/, "");
1220
+ if (params.route === "private" && isPublicOsvUrl(osvBaseUrl)) {
1221
+ unknowns.push("PRIVATE_SCOPE_OSV_SUPPRESSED: skipped public api.osv.dev query to prevent internal package name leakage.");
1222
+ return { advisories: [], unknowns };
1223
+ }
1224
+ if (params.packages.length === 0) return { advisories: [], unknowns };
1225
+
1226
+ let osvConfiguredOrigin ;
1227
+ let osvExplicitHttpOrigin ;
1228
+ try {
1229
+ const parsedOsv = new URL(osvBaseUrl);
1230
+ osvConfiguredOrigin = parsedOsv.origin;
1231
+ if (parsedOsv.protocol === "http:") osvExplicitHttpOrigin = parsedOsv.origin;
1232
+ } catch {
1233
+ unknowns.push(`OSV_API_ERROR: invalid osv_api_url '${osvBaseUrl}'`);
1234
+ return { advisories: [], unknowns };
1235
+ }
1236
+ const batchUrl = `${osvBaseUrl}/v1/querybatch`;
1237
+ const batchCheck = validateOutboundUrl(batchUrl, osvExplicitHttpOrigin, osvConfiguredOrigin);
1238
+ if (!batchCheck.ok) {
1239
+ unknowns.push(`OSV_API_ERROR: ${batchCheck.error ?? "rejected OSV URL"}`);
1240
+ return { advisories: [], unknowns };
1241
+ }
1242
+
1243
+ // Security [MCP-13]: namespace BOTH batch and detail OSV cache/SingleFlight keys by sha256(osvBaseUrl)
1244
+ const osvNs = createHash("sha256").update(osvBaseUrl).digest("hex").slice(0, 16);
1245
+ const advisories = [];
1246
+ const toQuery = [];
1247
+
1248
+ for (const p of params.packages) {
1249
+ const key = `osv:${osvNs}:npm:${p.name}@${p.version ?? "*"}`;
1250
+ const cached = params.cache?.getThreatIntel (key);
1251
+ if (cached && !cached.stale) {
1252
+ advisories.push(...cached.data);
1253
+ } else {
1254
+ toQuery.push({ ...p, key });
1255
+ }
1256
+ }
1257
+
1258
+ if (toQuery.length === 0) return { advisories, unknowns };
1259
+
1260
+ const controller = new AbortController();
1261
+ const timer = setTimeout(() => controller.abort(), 12000);
1262
+ try {
1263
+ const fetched = await fetchWithSafeRedirects({
1264
+ url: batchUrl,
1265
+ method: "POST",
1266
+ headers: { "content-type": "application/json", "user-agent": USER_AGENT },
1267
+ body: JSON.stringify({
1268
+ queries: toQuery.map((q) => ({
1269
+ package: { ecosystem: "npm", name: q.name },
1270
+ ...(q.version ? { version: q.version } : {}),
1271
+ })),
1272
+ }),
1273
+ allowPlainHttpOrigin: osvExplicitHttpOrigin,
1274
+ allowedPrivateOrigin: osvConfiguredOrigin,
1275
+ signal: controller.signal,
1276
+ });
1277
+ if (!fetched.ok || !fetched.response) {
1278
+ unknowns.push(`OSV_API_UNAVAILABLE: ${fetched.error ?? "fetch failed"}`);
1279
+ return { advisories, unknowns };
1280
+ }
1281
+ const res = fetched.response;
1282
+ if (!res.ok) {
1283
+ unknowns.push(`OSV_API_UNAVAILABLE: HTTP ${res.status}`);
1284
+ return { advisories, unknowns };
1285
+ }
1286
+ const readRes = await readResponseBytesCapped(res, MAX_SMALL_JSON_BYTES, "OSV batch");
1287
+ if (!readRes.ok) {
1288
+ unknowns.push(`OSV_API_ERROR: ${readRes.error}`);
1289
+ return { advisories, unknowns };
1290
+ }
1291
+ const body = JSON.parse(readRes.buffer.toString("utf8"))
1292
+
1293
+ ;
1294
+ const results = body.results ?? [];
1295
+
1296
+ for (let i = 0; i < toQuery.length; i++) {
1297
+ const q = toQuery[i] ;
1298
+ const vulns = results[i]?.vulns ?? [];
1299
+ const pkgAdvisories = [];
1300
+
1301
+ // Fetch detail for up to 10 vulns per package to bound API fan-out
1302
+ for (const v of vulns.slice(0, 10)) {
1303
+ const vid = v.id;
1304
+ if (!vid) continue;
1305
+ const detailKey = `osv-vuln:${osvNs}:${vid}`;
1306
+ const cachedDetail = params.cache?.getThreatIntel (detailKey);
1307
+ let detailObj = cachedDetail && !cachedDetail.stale ? cachedDetail.data : undefined;
1308
+ if (!detailObj) {
1309
+ detailObj = await osvDetailFlight.run(detailKey, async () => {
1310
+ const detRes = await fetchJsonWithTimeout (
1311
+ `${osvBaseUrl}/v1/vulns/${encodeURIComponent(vid)}`,
1312
+ { "user-agent": USER_AGENT },
1313
+ 8000,
1314
+ undefined,
1315
+ {
1316
+ maxBytes: MAX_SMALL_JSON_BYTES,
1317
+ allowPlainHttpOrigin: osvExplicitHttpOrigin,
1318
+ allowedPrivateOrigin: osvConfiguredOrigin,
1319
+ },
1320
+ );
1321
+ if (detRes.ok && detRes.data) {
1322
+ params.cache?.putThreatIntel({
1323
+ intel_key: detailKey,
1324
+ source: "osv",
1325
+ payload: detRes.data,
1326
+ ttl_seconds: params.policy.intel_ttl_seconds,
1327
+ });
1328
+ return detRes.data;
1329
+ }
1330
+ return undefined;
1331
+ });
1332
+ }
1333
+ const isMal = vid.startsWith("MAL-");
1334
+ const dbSpec = detailObj?.["database_specific"] ;
1335
+ const kev = Boolean(dbSpec?.["cisa_kev"] || String(detailObj?.["summary"] ?? "").toLowerCase().includes("known exploited"));
1336
+ pkgAdvisories.push({
1337
+ id: vid,
1338
+ is_malicious: isMal,
1339
+ severity: detailObj ? mapOsvSeverity(detailObj) : isMal ? "CRITICAL" : "HIGH",
1340
+ kev,
1341
+ summary: sanitizeUntrustedText(String(detailObj?.["summary"] ?? (isMal ? "OpenSSF Malicious Package advisory" : "OSV advisory")), 160),
1342
+ package_name: q.name,
1343
+ affected_version: q.version,
1344
+ });
1345
+ }
1346
+
1347
+ params.cache?.putThreatIntel({
1348
+ intel_key: q.key,
1349
+ source: "osv",
1350
+ payload: pkgAdvisories,
1351
+ ttl_seconds: params.policy.intel_ttl_seconds,
1352
+ });
1353
+ advisories.push(...pkgAdvisories);
1354
+ }
1355
+ } catch (err) {
1356
+ unknowns.push(`OSV_API_ERROR: ${err instanceof Error ? err.message : String(err)}`);
1357
+ } finally {
1358
+ clearTimeout(timer);
1359
+ }
1360
+
1361
+ return { advisories, unknowns };
1362
+ }
1363
+
1364
+ export async function discoverPackages(params
1365
+
1366
+
1367
+
1368
+
1369
+
1370
+
1371
+
1372
+
1373
+ ) {
1374
+ const unknowns = [];
1375
+ const candidates = [];
1376
+ const blocked_candidates = [];
1377
+
1378
+ const routeTarget = params.org ? (params.org.startsWith("@") ? params.org : `@${params.org}`) : params.query;
1379
+ const routing = routeDiscoveryQuery(params.query, params.org, params.policy, params.npmrc, {
1380
+ creator: params.creator,
1381
+ category: params.category,
1382
+ });
1383
+ if (
1384
+ routing.route === "blocked_typo" ||
1385
+ routing.route === "blocked_unconfigured" ||
1386
+ routing.route === "blocked_secret"
1387
+ ) {
1388
+ return {
1389
+ schema_version: "1",
1390
+ query: params.query,
1391
+ filters: { org: params.org, creator: params.creator, category: params.category },
1392
+ registry_route: "private",
1393
+ candidates: [],
1394
+ blocked_candidates: [{ package_name: routing.matched_scope_or_prefix ?? routeTarget, reason: routing.reason }],
1395
+ unknowns: [routing.reason],
1396
+ };
1397
+ }
1398
+
1399
+ if (params.policy.offline_mode) {
1400
+ unknowns.push("OFFLINE_MODE: live registry discovery disabled.");
1401
+ return {
1402
+ schema_version: "1",
1403
+ query: params.query,
1404
+ filters: { org: params.org, creator: params.creator, category: params.category },
1405
+ registry_route: routing.route,
1406
+ candidates: [],
1407
+ blocked_candidates: [],
1408
+ unknowns,
1409
+ };
1410
+ }
1411
+
1412
+ const terms = [];
1413
+ if (params.query.trim()) terms.push(params.query.trim());
1414
+ if (params.org) terms.push(`scope:${params.org.replace(/^@/, "")}`);
1415
+ if (params.creator) terms.push(`maintainer:${params.creator}`);
1416
+ if (params.category) terms.push(`keywords:${params.category}`);
1417
+
1418
+ const searchText = terms.join(" ").trim();
1419
+ const rawLimit = typeof params.limit === "number" && Number.isFinite(params.limit) ? Math.floor(params.limit) : 10;
1420
+ const size = Math.min(Math.max(rawLimit, 1), 25);
1421
+ const searchUrl = `${routing.registry_url}/-/v1/search?text=${encodeURIComponent(searchText)}&size=${size}`;
1422
+ const headers = { "user-agent": USER_AGENT };
1423
+ let searchOrigin ;
1424
+ let searchAllowHttpOrigin ;
1425
+ try {
1426
+ const parsedSearch = new URL(routing.registry_url);
1427
+ searchOrigin = parsedSearch.origin;
1428
+ if (parsedSearch.protocol === "http:") searchAllowHttpOrigin = parsedSearch.origin;
1429
+ } catch {
1430
+ searchOrigin = undefined;
1431
+ }
1432
+
1433
+ const res = await fetchJsonWithTimeout (
1434
+ searchUrl,
1435
+ headers,
1436
+ 12000,
1437
+ routing.auth_token && searchOrigin ? { token: routing.auth_token, allowedOrigin: searchOrigin } : undefined,
1438
+ {
1439
+ maxBytes: MAX_SMALL_JSON_BYTES,
1440
+ allowPlainHttpOrigin: searchAllowHttpOrigin,
1441
+ allowedPrivateOrigin: searchOrigin,
1442
+ },
1443
+ );
1444
+ if (!res.ok || !res.data) {
1445
+ unknowns.push(`DISCOVERY_SEARCH_FAILED: ${res.error ?? "upstream registry error"}`);
1446
+ return {
1447
+ schema_version: "1",
1448
+ query: params.query,
1449
+ filters: { org: params.org, creator: params.creator, category: params.category },
1450
+ registry_route: routing.route,
1451
+ candidates: [],
1452
+ blocked_candidates: [],
1453
+ unknowns,
1454
+ };
1455
+ }
1456
+
1457
+ for (const item of res.data.objects ?? []) {
1458
+ const pkg = item.package;
1459
+ if (!pkg || typeof pkg["name"] !== "string") continue;
1460
+ const pkgName = pkg["name"];
1461
+ const version = String(pkg["version"] ?? "0.0.0");
1462
+ const scope = pkgName.startsWith("@") ? pkgName.slice(0, pkgName.indexOf("/")) : "unscoped";
1463
+ const scopeLower = scope.toLowerCase();
1464
+ const license = extractLicense(pkg["license"]);
1465
+
1466
+ if (params.policy.denied_orgs.includes(scopeLower)) {
1467
+ blocked_candidates.push({ package_name: pkgName, reason: `Org/scope '${scope}' is on policy denied_orgs list.` });
1468
+ continue;
1469
+ }
1470
+ if (params.policy.allowed_orgs.length > 0 && !params.policy.allowed_orgs.includes(scopeLower)) {
1471
+ blocked_candidates.push({ package_name: pkgName, reason: `Org/scope '${scope}' is not on policy allowed_orgs list.` });
1472
+ continue;
1473
+ }
1474
+ if (params.policy.blocked_licenses.some((b) => b.toLowerCase() === license.toLowerCase())) {
1475
+ blocked_candidates.push({ package_name: pkgName, reason: `License '${license}' is blocked by enterprise policy.` });
1476
+ continue;
1477
+ }
1478
+
1479
+ const squatWarnings = evaluateSlopsquatAndCooldown({
1480
+ package_name: pkgName,
1481
+ version_published_at_iso: typeof pkg["date"] === "string" ? pkg["date"] : undefined,
1482
+ has_lifecycle_scripts: false,
1483
+ policy: params.policy,
1484
+ });
1485
+
1486
+ const hasCritSquat = squatWarnings.some((o) => o.severity === "CRITICAL");
1487
+ const hasWarnSquat = squatWarnings.length > 0;
1488
+
1489
+ candidates.push({
1490
+ package_name: pkgName,
1491
+ version,
1492
+ org_or_scope: scope,
1493
+ creator: extractCreator(pkg["publisher"] ?? pkg["author"]),
1494
+ summary: sanitizeUntrustedText(String(pkg["description"] ?? ""), 180),
1495
+ license,
1496
+ keywords: Array.isArray(pkg["keywords"])
1497
+ ? pkg["keywords"].filter((k) => typeof k === "string").slice(0, 8)
1498
+ : [],
1499
+ published_at: typeof pkg["date"] === "string" ? pkg["date"] : undefined,
1500
+ squat_warnings: squatWarnings,
1501
+ verdict_preview: hasCritSquat
1502
+ ? "MALICIOUS_INDICATORS_FOUND"
1503
+ : hasWarnSquat
1504
+ ? "QUARANTINE_SUSPICIOUS"
1505
+ : "UNVERIFIABLE_UNKNOWN",
1506
+ });
1507
+ }
1508
+
1509
+ // Batch-check returned candidates against OSV/OpenSSF MAL-* (public route or configured internal OSV mirror)
1510
+ if (candidates.length > 0) {
1511
+ const osvRes = await queryOsvAdvisories({
1512
+ packages: candidates.map((c) => ({ name: c.package_name, version: c.version })),
1513
+ policy: params.policy,
1514
+ cache: params.cache,
1515
+ route: routing.route,
1516
+ });
1517
+ if (osvRes.unknowns.length > 0) unknowns.push(...osvRes.unknowns);
1518
+ for (const adv of osvRes.advisories) {
1519
+ const cand = candidates.find((c) => c.package_name === adv.package_name);
1520
+ if (!cand) continue;
1521
+ if (adv.is_malicious) {
1522
+ cand.verdict_preview = "MALICIOUS_INDICATORS_FOUND";
1523
+ cand.squat_warnings.push({
1524
+ code: "OSV_MALICIOUS_PACKAGE_ADVISORY",
1525
+ severity: "CRITICAL",
1526
+ path: "<threat-intel>",
1527
+ attack_id: "T1195.002",
1528
+ detail: `${adv.id}: ${adv.summary}`,
1529
+ });
1530
+ } else if (
1531
+ cand.verdict_preview !== "MALICIOUS_INDICATORS_FOUND" &&
1532
+ ((params.policy.block_on_kev && adv.kev) ||
1533
+ (params.policy.block_on_critical_cve && adv.severity === "CRITICAL") ||
1534
+ (params.policy.block_on_high_cve && adv.severity === "HIGH"))
1535
+ ) {
1536
+ cand.verdict_preview = "QUARANTINE_SUSPICIOUS";
1537
+ }
1538
+ }
1539
+ }
1540
+
1541
+ return {
1542
+ schema_version: "1",
1543
+ query: params.query,
1544
+ filters: { org: params.org, creator: params.creator, category: params.category },
1545
+ registry_route: routing.route,
1546
+ candidates,
1547
+ blocked_candidates,
1548
+ unknowns,
1549
+ };
1550
+ }
1551
+
1552
+ /**
1553
+ * Dependency Confusion Audit (`T1195.001`):
1554
+ * Inspects local package.json + .npmrc + policy for unpinned private scopes
1555
+ * or unscoped internal prefixes vulnerable to public registry shadowing.
1556
+ */
1557
+ export async function auditDependencyConfusion(params
1558
+
1559
+
1560
+
1561
+
1562
+
1563
+ ) {
1564
+ const manifestPath = resolve(params.manifestPath ?? resolve(params.cwd, "package.json"));
1565
+ const npmrc = loadNpmrc(dirname(manifestPath));
1566
+ const displayManifestPath = params.redactHomePaths ? redactHomePath(manifestPath) : manifestPath;
1567
+ const displayNpmrcPaths = params.redactHomePaths
1568
+ ? npmrc.paths_loaded.map((p) => redactHomePath(p))
1569
+ : npmrc.paths_loaded;
1570
+ const findings = [];
1571
+ const unknowns = [];
1572
+
1573
+ if (!existsSync(manifestPath)) {
1574
+ return {
1575
+ schema_version: "1",
1576
+ manifest_path: displayManifestPath,
1577
+ npmrc_paths: displayNpmrcPaths,
1578
+ findings: [],
1579
+ passed: false,
1580
+ unknowns: [`Manifest not found at ${displayManifestPath}`],
1581
+ };
1582
+ }
1583
+
1584
+ let pkg ;
1585
+ try {
1586
+ const rawBuf = await openReadCappedFile(manifestPath, MAX_MANIFEST_BYTES);
1587
+ pkg = JSON.parse(rawBuf.toString("utf8"))
1588
+
1589
+ ;
1590
+ } catch (err) {
1591
+ return {
1592
+ schema_version: "1",
1593
+ manifest_path: displayManifestPath,
1594
+ npmrc_paths: displayNpmrcPaths,
1595
+ findings: [],
1596
+ passed: false,
1597
+ unknowns: [`MANIFEST_PARSE_ERROR: failed to parse ${displayManifestPath}: ${err instanceof Error ? err.message : String(err)}`],
1598
+ };
1599
+ }
1600
+
1601
+ const allDeps = {
1602
+ ...(pkg.dependencies ?? {}),
1603
+ ...(pkg.optionalDependencies ?? {}),
1604
+ ...(pkg.devDependencies ?? {}),
1605
+ ...(pkg.peerDependencies ?? {}),
1606
+ };
1607
+
1608
+ for (const [depName, range] of Object.entries(allDeps)) {
1609
+ const lower = depName.toLowerCase();
1610
+ const isScoped = lower.startsWith("@");
1611
+ const scope = isScoped ? lower.slice(0, lower.indexOf("/")) : undefined;
1612
+
1613
+ if (scope && params.policy.private_scopes.includes(scope)) {
1614
+ const pinnedUrl = npmrc.scoped_registries[scope] ?? params.policy.private_registries[scope];
1615
+ if (!pinnedUrl || isPublicNpmRegistryUrl(pinnedUrl)) {
1616
+ findings.push({
1617
+ package_name: depName,
1618
+ declared_range: range,
1619
+ issue: "UNPINNED_PRIVATE_SCOPE",
1620
+ severity: "CRITICAL",
1621
+ detail: `Private scope '${scope}' is declared in policy but not pinned to a private registry in .npmrc.`,
1622
+ remediation: `Add '${scope}:registry=https://<your-private-registry>/' to project .npmrc.`,
1623
+ });
1624
+ }
1625
+ continue;
1626
+ }
1627
+
1628
+ const matchedPrefix = params.policy.private_prefixes.find((pref) => lower.startsWith(pref));
1629
+ if (!isScoped && matchedPrefix) {
1630
+ findings.push({
1631
+ package_name: depName,
1632
+ declared_range: range,
1633
+ issue: "UNSCOPED_PRIVATE_PREFIX",
1634
+ severity: "HIGH",
1635
+ detail: `Unscoped internal package '${depName}' (prefix '${matchedPrefix}') is vulnerable to public npm substitution (T1195.001).`,
1636
+ remediation: `Migrate '${depName}' into an organization scope pinned in .npmrc or reserve a placeholder package.`,
1637
+ });
1638
+
1639
+ if (params.checkPublicClaimability && !params.policy.offline_mode) {
1640
+ const probe = await fetchJsonWithTimeout (
1641
+ `https://registry.npmjs.org/${encodePkgName(depName)}`,
1642
+ { "user-agent": USER_AGENT, accept: "application/vnd.npm.install-v1+json" },
1643
+ 6000,
1644
+ undefined,
1645
+ { maxBytes: MAX_SMALL_JSON_BYTES },
1646
+ );
1647
+ if (probe.status === 404) {
1648
+ findings.push({
1649
+ package_name: depName,
1650
+ declared_range: range,
1651
+ issue: "CLAIMABLE_ON_PUBLIC_NPM",
1652
+ severity: "CRITICAL",
1653
+ detail: `Unscoped internal name '${depName}' returned HTTP 404 on public npmjs.org and is immediately claimable by an attacker.`,
1654
+ remediation: `Pin registry strictly to a non-merging private proxy and reserve or scope '${depName}'.`,
1655
+ });
1656
+ } else if (probe.ok) {
1657
+ findings.push({
1658
+ package_name: depName,
1659
+ declared_range: range,
1660
+ issue: "PUBLIC_SHADOW_EXISTS",
1661
+ severity: "CRITICAL",
1662
+ detail: `Unscoped internal name '${depName}' already exists on public npmjs.org; verify ownership immediately.`,
1663
+ remediation: `Verify publisher ownership on npmjs.org and isolate internal resolution via .npmrc.`,
1664
+ });
1665
+ }
1666
+ }
1667
+ }
1668
+ }
1669
+
1670
+ return {
1671
+ schema_version: "1",
1672
+ manifest_path: displayManifestPath,
1673
+ npmrc_paths: displayNpmrcPaths,
1674
+ findings,
1675
+ passed: findings.length === 0 && unknowns.length === 0,
1676
+ unknowns,
1677
+ };
1678
+ }
1679
+
1680
+
1681
+ //# sourceURL=intel/registry-osv.ts