coldpin 0.0.0-stage → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/ACCESSIBILITY.md +17 -0
  2. package/CHANGELOG.md +89 -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 +35 -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,895 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { readCappedRegularFileSync } from "../core/path-confinement.mjs";
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+ import { ENGINE_VERSION } from "../types.mjs";
25
+ import {
26
+ escapeMarkdownCell,
27
+ isSafeNpmBinName,
28
+ isSafeNpmPackageName,
29
+ isSafeNpmVersion,
30
+ LIFECYCLE_HOOKS,
31
+ sanitizeUntrustedText,
32
+ } from "../analysis/static-triage.mjs";
33
+
34
+ export function verdictToExitCode(verdict ) {
35
+ switch (verdict) {
36
+ case "VERIFIED_CLEAN_WITHIN_SCOPE":
37
+ return 0;
38
+ case "QUARANTINE_SUSPICIOUS":
39
+ case "UNVERIFIABLE_UNKNOWN":
40
+ return 2;
41
+ case "MALICIOUS_INDICATORS_FOUND":
42
+ return 3;
43
+ }
44
+ }
45
+
46
+ export function computeDeterministicVerdict(params
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+ )
57
+
58
+
59
+
60
+ {
61
+ const policy_observations = [];
62
+
63
+ // Policy checks: org allow/deny, license block, CVE/KEV gates
64
+ const orgLower = params.orgOrScope.toLowerCase();
65
+ if (params.policy.denied_orgs.includes(orgLower)) {
66
+ policy_observations.push({
67
+ code: "POLICY_ORG_DENIED",
68
+ severity: "HIGH",
69
+ path: "<policy>",
70
+ detail: `Organization/scope '${params.orgOrScope}' is listed in policy.denied_orgs.`,
71
+ });
72
+ }
73
+ if (params.policy.allowed_orgs.length > 0 && !params.policy.allowed_orgs.includes(orgLower)) {
74
+ policy_observations.push({
75
+ code: "POLICY_ORG_NOT_ALLOWED",
76
+ severity: "HIGH",
77
+ path: "<policy>",
78
+ detail: `Organization/scope '${params.orgOrScope}' is not on policy.allowed_orgs.`,
79
+ });
80
+ }
81
+ if (params.policy.blocked_licenses.some((b) => b.toLowerCase() === params.license.toLowerCase())) {
82
+ policy_observations.push({
83
+ code: "POLICY_LICENSE_BLOCKED",
84
+ severity: "HIGH",
85
+ path: "<policy>",
86
+ detail: `License '${params.license}' is blocked by enterprise policy.`,
87
+ });
88
+ }
89
+
90
+ for (const adv of params.advisories) {
91
+ if (adv.is_malicious) {
92
+ policy_observations.push({
93
+ code: "OSV_MALICIOUS_PACKAGE_ADVISORY",
94
+ severity: "CRITICAL",
95
+ path: "<threat-intel>",
96
+ attack_id: "T1195.002",
97
+ detail: `${adv.id}: ${adv.summary}`,
98
+ });
99
+ } else if (params.policy.block_on_kev && adv.kev) {
100
+ policy_observations.push({
101
+ code: "POLICY_CISA_KEV_BLOCK",
102
+ severity: "HIGH",
103
+ path: "<threat-intel>",
104
+ detail: `${adv.id} is listed in CISA KEV: ${adv.summary}`,
105
+ });
106
+ } else if (params.policy.block_on_critical_cve && adv.severity === "CRITICAL") {
107
+ policy_observations.push({
108
+ code: "POLICY_CRITICAL_CVE_BLOCK",
109
+ severity: "HIGH",
110
+ path: "<threat-intel>",
111
+ detail: `${adv.id} (CRITICAL): ${adv.summary}`,
112
+ });
113
+ } else if (params.policy.block_on_high_cve && adv.severity === "HIGH") {
114
+ policy_observations.push({
115
+ code: "POLICY_HIGH_CVE_BLOCK",
116
+ severity: "HIGH",
117
+ path: "<threat-intel>",
118
+ detail: `${adv.id} (HIGH): ${adv.summary}`,
119
+ });
120
+ }
121
+ }
122
+
123
+ const allObs = [
124
+ ...params.unpack.observations,
125
+ ...params.triage.observations,
126
+ ...params.parity.observations,
127
+ ...params.registryObservations,
128
+ ...policy_observations,
129
+ ];
130
+
131
+ // 1. MALICIOUS_INDICATORS_FOUND (deterministic hard block)
132
+ const hasCritical = allObs.some((o) => o.severity === "CRITICAL");
133
+ if (hasCritical) {
134
+ return {
135
+ verdict: "MALICIOUS_INDICATORS_FOUND",
136
+ recommended_action: "SWITCH_TO_ALTERNATIVE",
137
+ policy_observations,
138
+ };
139
+ }
140
+
141
+ // 2. QUARANTINE_SUSPICIOUS (high risk, obfuscation, lifecycle hooks, cooldown, policy gates)
142
+ const hasSuspicious = allObs.some(
143
+ (o) =>
144
+ o.severity === "HIGH" ||
145
+ o.code === "LIFECYCLE_HOOK_PRESENT" ||
146
+ o.code === "RELEASE_COOLDOWN_QUARANTINE",
147
+ );
148
+ if (hasSuspicious || params.triage.has_obfuscation) {
149
+ return {
150
+ verdict: "QUARANTINE_SUSPICIOUS",
151
+ recommended_action: "BLOCK_NO_SAFE_PATH",
152
+ policy_observations,
153
+ };
154
+ }
155
+
156
+ // 3. UNVERIFIABLE_UNKNOWN (incomplete coverage, cap hit, skipped files, corrupt/missing manifest, native/WASM without REA, OSV unavailable, strict policy missing proof)
157
+ const effectiveProvStatus =
158
+ params.parity.provenance_status ?? (params.parity.provenance_attested ? "sigstore_verified" : "none");
159
+ const strictProvenanceGap =
160
+ params.policy.require_provenance &&
161
+ (!params.parity.provenance_attested || effectiveProvStatus !== "sigstore_verified");
162
+ const strictSourceGap = params.policy.require_source_link && params.parity.tier === "SOURCE_UNLINKED";
163
+ const incompleteCoverage =
164
+ params.triage.files_skipped > 0 ||
165
+ params.unpack.unknowns.some((u) => u.startsWith("ARCHIVE_UNSUPPORTED_TYPEFLAG")) ||
166
+ params.triage.unknowns.some(
167
+ (u) =>
168
+ u.startsWith("MANIFEST_MISSING") ||
169
+ u.startsWith("MANIFEST_PARSE_ERROR") ||
170
+ u.startsWith("FILE_SIZE_CAP_SKIPPED"),
171
+ );
172
+ const intelUnavailable = params.offlineUnknowns.some(
173
+ (u) =>
174
+ u.startsWith("OFFLINE_INTEL_SKIPPED") ||
175
+ u.startsWith("OSV_API_UNAVAILABLE") ||
176
+ u.startsWith("OSV_API_ERROR"),
177
+ );
178
+ if (
179
+ !params.unpack.ok ||
180
+ params.unpack.halted_by_cap ||
181
+ params.triage.has_native_or_wasm ||
182
+ incompleteCoverage ||
183
+ strictProvenanceGap ||
184
+ strictSourceGap ||
185
+ intelUnavailable
186
+ ) {
187
+ return {
188
+ verdict: "UNVERIFIABLE_UNKNOWN",
189
+ recommended_action: "BLOCK_NO_SAFE_PATH",
190
+ policy_observations,
191
+ };
192
+ }
193
+
194
+ // 4. VERIFIED_CLEAN_WITHIN_SCOPE
195
+ return {
196
+ verdict: "VERIFIED_CLEAN_WITHIN_SCOPE",
197
+ recommended_action: "USE_PINNED_LATEST",
198
+ policy_observations,
199
+ };
200
+ }
201
+
202
+ export function buildPinnedExecution(params
203
+
204
+
205
+
206
+
207
+
208
+ ) {
209
+ const bin = params.bin_names[0] ?? (params.package_name.includes("/") ? params.package_name.slice(params.package_name.indexOf("/") + 1) : params.package_name);
210
+ if (params.verdict !== "VERIFIED_CLEAN_WITHIN_SCOPE") {
211
+ return {
212
+ command: null,
213
+ exact_version: params.version,
214
+ tarball_sha512: params.tarball_sha512,
215
+ bin_name: bin,
216
+ caveat: `Execution command suppressed because verdict is ${params.verdict}.`,
217
+ };
218
+ }
219
+ if (!isSafeNpmPackageName(params.package_name) || !isSafeNpmVersion(params.version) || !isSafeNpmBinName(bin)) {
220
+ return {
221
+ command: null,
222
+ exact_version: sanitizeUntrustedText(params.version, 64),
223
+ tarball_sha512: params.tarball_sha512,
224
+ bin_name: sanitizeUntrustedText(bin, 64),
225
+ caveat: "Execution command suppressed because package name, version, or bin key contains shell-unsafe characters.",
226
+ };
227
+ }
228
+ return {
229
+ command: `npx --yes --ignore-scripts --package=${params.package_name}@${params.version} -- ${bin}`,
230
+ exact_version: params.version,
231
+ tarball_sha512: params.tarball_sha512,
232
+ bin_name: bin,
233
+ caveat:
234
+ "Stock npx pins top-level version and disables install scripts, but cannot enforce SHA-512 integrity or transitive lockfiles at runtime. Verify dist.integrity and isolate transitives for regulated builds.",
235
+ };
236
+ }
237
+
238
+ const CONTAINMENT_STEPS = [
239
+ "1. Disconnect affected host/runner from production networks if package was installed without --ignore-scripts.",
240
+ "2. Immediately rotate exposed tokens: ~/.npmrc, GitHub PATs, SSH keys, AWS/GCP/Azure credentials, and .env secrets.",
241
+ "3. Preserve shell history, npm cache, and process/DNS logs before wiping node_modules (chain of custody).",
242
+ "4. Notify Security/SOC immediately (evaluate India CERT-In 6h / EU NIS2 24h / CRA 24h / GDPR 72h reporting clocks).",
243
+ ];
244
+
245
+ function escapeRegExp(s ) {
246
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
247
+ }
248
+
249
+ function matchPnpmLock(content , packageName ) {
250
+ // Matches pnpm lockfile v6/v9 entries like: " /bad-cli@1.2.3:" or " '@org/bad@1.2.3':" or " bad-cli@1.2.3:"
251
+ const esc = escapeRegExp(packageName);
252
+ const re = new RegExp(`(?:^|\\n)\\s*['"]?/?${esc}@([0-9][^\\s:'"()]+)`, "m");
253
+ const m = re.exec(content);
254
+ return m?.[1] ?? null;
255
+ }
256
+
257
+ function matchYarnLock(content , packageName ) {
258
+ // Matches Yarn classic & Berry blocks (including @npm: protocol and comma-separated multi-specifier headers):
259
+ // "@org/bad@^1.0.0": / "@org/bad@npm:^1.0.0": / "foo@^1.0.0", "@org/bad@npm:^1.0.0":
260
+ const esc = escapeRegExp(packageName);
261
+ const headerRe = new RegExp(`(?:^|\\n)[^\\n]*(?:^|[\\s,'"])${esc}@(?:npm:)?[^\\n]+:(?:\\r?\\n)([\\s\\S]{0,320})`, "m");
262
+ const m = headerRe.exec(content);
263
+ if (!m?.[1]) return null;
264
+ const verMatch = /^\s+version[:\s]+['"]?([^\s'"]+)/m.exec(m[1]);
265
+ return verMatch?.[1] ?? null;
266
+ }
267
+
268
+ export function checkLocalWorkspaceCompromised(
269
+ cwd ,
270
+ packageName ,
271
+ verdict ,
272
+ ) {
273
+ if (verdict !== "MALICIOUS_INDICATORS_FOUND") return undefined;
274
+
275
+ const MAX_LOCKFILE_BYTES = 25 * 1024 * 1024;
276
+
277
+ // 1. npm package-lock.json (lockfileVersion 1, 2, 3 — top-level AND nested node_modules)
278
+ const npmLockPath = join(cwd, "package-lock.json");
279
+ if (existsSync(npmLockPath)) {
280
+ try {
281
+ const raw = JSON.parse(readCappedRegularFileSync(npmLockPath, MAX_LOCKFILE_BYTES).toString("utf8"))
282
+
283
+
284
+ ;
285
+ const directKey = `node_modules/${packageName}`;
286
+ const nestedSuffix = `/node_modules/${packageName}`;
287
+ let matchedVer = raw.packages?.[directKey]?.version ?? raw.dependencies?.[packageName]?.version;
288
+ if (!matchedVer && raw.packages) {
289
+ for (const [k, entry] of Object.entries(raw.packages)) {
290
+ if ((k === directKey || k.endsWith(nestedSuffix)) && entry?.version) {
291
+ matchedVer = entry.version;
292
+ break;
293
+ }
294
+ }
295
+ }
296
+ if (!matchedVer && raw.dependencies) {
297
+ for (const dep of Object.values(raw.dependencies)) {
298
+ const nested = dep?.dependencies?.[packageName]?.version;
299
+ if (nested) {
300
+ matchedVer = nested;
301
+ break;
302
+ }
303
+ }
304
+ }
305
+ if (matchedVer) {
306
+ return {
307
+ lockfile_path: npmLockPath,
308
+ lockfile_kind: "package-lock.json",
309
+ matched_version: matchedVer,
310
+ containment_steps: [...CONTAINMENT_STEPS],
311
+ };
312
+ }
313
+ } catch {
314
+ // Continue checking other lockfile ecosystems
315
+ }
316
+ }
317
+
318
+ // 2. pnpm-lock.yaml
319
+ const pnpmLockPath = join(cwd, "pnpm-lock.yaml");
320
+ if (existsSync(pnpmLockPath)) {
321
+ try {
322
+ const matchedVer = matchPnpmLock(readCappedRegularFileSync(pnpmLockPath, MAX_LOCKFILE_BYTES).toString("utf8"), packageName);
323
+ if (matchedVer) {
324
+ return {
325
+ lockfile_path: pnpmLockPath,
326
+ lockfile_kind: "pnpm-lock.yaml",
327
+ matched_version: matchedVer,
328
+ containment_steps: [...CONTAINMENT_STEPS],
329
+ };
330
+ }
331
+ } catch {
332
+ // Ignore unreadable or oversized lockfile
333
+ }
334
+ }
335
+
336
+ // 3. yarn.lock
337
+ const yarnLockPath = join(cwd, "yarn.lock");
338
+ if (existsSync(yarnLockPath)) {
339
+ try {
340
+ const matchedVer = matchYarnLock(readCappedRegularFileSync(yarnLockPath, MAX_LOCKFILE_BYTES).toString("utf8"), packageName);
341
+ if (matchedVer) {
342
+ return {
343
+ lockfile_path: yarnLockPath,
344
+ lockfile_kind: "yarn.lock",
345
+ matched_version: matchedVer,
346
+ containment_steps: [...CONTAINMENT_STEPS],
347
+ };
348
+ }
349
+ } catch {
350
+ // Ignore unreadable lockfile
351
+ }
352
+ }
353
+
354
+ return undefined;
355
+ }
356
+
357
+ export function buildReaEscalationPlan(params
358
+
359
+
360
+
361
+ ) {
362
+ const steps = [];
363
+ const seen = new Set ();
364
+
365
+ for (const obs of params.triage.observations) {
366
+ if (obs.code === "NATIVE_OR_WASM_ARTIFACT") {
367
+ const isWasm = obs.path.toLowerCase().endsWith(".wasm") || obs.detail.includes("WebAssembly");
368
+ const tool = isWasm
369
+ ? "inspect_wasm_artifact"
370
+ : "open_binary -> inspect_artifact / inspect_binary_layout -> close_binary";
371
+ const key = `${obs.path}|${tool}`;
372
+ if (!seen.has(key)) {
373
+ seen.add(key);
374
+ steps.push({
375
+ path: obs.path,
376
+ signal: obs.code,
377
+ recommended_tool: tool,
378
+ rationale: obs.detail,
379
+ });
380
+ }
381
+ } else if (obs.code === "HIGH_ENTROPY_OBFUSCATION" || obs.code === "OBFUSCATED_DYNAMIC_EXEC") {
382
+ const tool = "analyze_javascript_application (detail='summary') / recover_javascript_sources";
383
+ const key = `${obs.path}|${tool}`;
384
+ if (!seen.has(key)) {
385
+ seen.add(key);
386
+ steps.push({
387
+ path: obs.path,
388
+ signal: obs.code,
389
+ recommended_tool: tool,
390
+ rationale: obs.detail,
391
+ });
392
+ }
393
+ }
394
+ }
395
+
396
+ if (params.parity.tier === "TARBALL_SOURCE_DRIFT") {
397
+ steps.push({
398
+ path: "<tarball vs gitHead>",
399
+ signal: "TARBALL_SOURCE_DRIFT",
400
+ recommended_tool: "compare_application_versions",
401
+ rationale: "Published tarball diverges from Git source commit; compare structurally across versions via REA.",
402
+ });
403
+ }
404
+
405
+ if (steps.length === 0) return undefined;
406
+ return {
407
+ required: true,
408
+ rea_available_on_host: params.host_capabilities.rea_cli_available,
409
+ bootstrap_prohibition:
410
+ "Never run 'npx -y rea-agents' to bootstrap REA; invoke REA only through a pre-registered MCP server or pre-installed binary.",
411
+ steps,
412
+ };
413
+ }
414
+
415
+ export function assembleInspectionReport(params
416
+
417
+
418
+
419
+
420
+
421
+
422
+
423
+
424
+
425
+
426
+
427
+
428
+
429
+
430
+
431
+
432
+
433
+
434
+
435
+
436
+ ) {
437
+ const verdictRes = computeDeterministicVerdict({
438
+ unpack: params.unpack,
439
+ triage: params.triage,
440
+ parity: params.parity,
441
+ advisories: params.advisories,
442
+ registryObservations: params.registryObservations,
443
+ policy: params.policy,
444
+ orgOrScope: params.org_or_scope,
445
+ license: params.license,
446
+ offlineUnknowns: params.registryUnknowns,
447
+ });
448
+
449
+ const evidence = [
450
+ {
451
+ evidence_id: `ev_t0_${params.unpack.tarball_sha512.slice(7, 19)}`,
452
+ source: "tier0_intel",
453
+ artifact_sha512: params.unpack.tarball_sha512,
454
+ observations: [...params.registryObservations, ...verdictRes.policy_observations],
455
+ inferences: [],
456
+ unknowns: params.registryUnknowns,
457
+ coverage: {
458
+ files_inspected: 0,
459
+ files_skipped: 0,
460
+ rea_invoked: false,
461
+ transitive_checked: params.transitive_checked ?? false,
462
+ },
463
+ },
464
+ {
465
+ evidence_id: `ev_t1_unpack_${params.unpack.tarball_sha512.slice(7, 19)}`,
466
+ source: "tier1_unpack",
467
+ artifact_sha512: params.unpack.tarball_sha512,
468
+ observations: params.unpack.observations,
469
+ inferences: [],
470
+ unknowns: params.unpack.unknowns,
471
+ coverage: {
472
+ files_inspected: params.unpack.entries.length,
473
+ files_skipped: 0,
474
+ rea_invoked: false,
475
+ transitive_checked: false,
476
+ },
477
+ },
478
+ {
479
+ evidence_id: `ev_t1_static_${params.triage.ruleset_sha256.slice(0, 12)}`,
480
+ source: "tier1_static",
481
+ artifact_sha512: params.unpack.tarball_sha512,
482
+ observations: params.triage.observations,
483
+ inferences: params.triage.inferences,
484
+ unknowns: params.triage.unknowns,
485
+ coverage: {
486
+ files_inspected: params.triage.files_inspected,
487
+ files_skipped: params.triage.files_skipped,
488
+ rea_invoked: false,
489
+ transitive_checked: false,
490
+ },
491
+ },
492
+ {
493
+ evidence_id: `ev_t1_parity_${(params.parity.git_head ?? "unlinked").slice(0, 12)}`,
494
+ source: "tier1_parity",
495
+ artifact_sha512: params.unpack.tarball_sha512,
496
+ commit_sha: params.parity.git_head,
497
+ observations: params.parity.observations,
498
+ inferences: [],
499
+ unknowns: params.parity.unknowns,
500
+ coverage: {
501
+ files_inspected: params.unpack.entries.length,
502
+ files_skipped: 0,
503
+ rea_invoked: false,
504
+ transitive_checked: false,
505
+ },
506
+ },
507
+ ];
508
+
509
+ const lifecycleScripts = Object.keys(params.triage.manifest?.scripts ?? {}).filter((k) =>
510
+ LIFECYCLE_HOOKS.has(k.toLowerCase()),
511
+ );
512
+
513
+ const pinned_execution = buildPinnedExecution({
514
+ package_name: params.package_name,
515
+ version: params.version,
516
+ bin_names: params.bin_names,
517
+ tarball_sha512: params.unpack.tarball_sha512,
518
+ verdict: verdictRes.verdict,
519
+ });
520
+
521
+ const local_workspace_compromised = checkLocalWorkspaceCompromised(
522
+ params.cwd,
523
+ params.package_name,
524
+ verdictRes.verdict,
525
+ );
526
+
527
+ const rea_escalation_plan = buildReaEscalationPlan({
528
+ triage: params.triage,
529
+ parity: params.parity,
530
+ host_capabilities: params.host_capabilities,
531
+ });
532
+
533
+ const effectiveProvenanceStatus =
534
+ params.parity.provenance_status ?? (params.parity.provenance_attested ? "sigstore_verified" : "none");
535
+
536
+ return {
537
+ schema_version: "1",
538
+ generated_at_utc: new Date().toISOString(),
539
+ title: {
540
+ package_name: params.package_name,
541
+ version: params.version,
542
+ org_or_scope: params.org_or_scope,
543
+ creator: sanitizeUntrustedText(params.creator, 80),
544
+ category_tags: params.category_tags.map((c) => sanitizeUntrustedText(c, 40)),
545
+ commit_sha: params.parity.git_head,
546
+ },
547
+ info: {
548
+ summary: sanitizeUntrustedText(params.summary, 200),
549
+ license: sanitizeUntrustedText(params.license, 60),
550
+ published_at: params.published_at,
551
+ weekly_downloads: params.weekly_downloads,
552
+ has_bin: params.bin_names.length > 0,
553
+ bin_names: params.bin_names,
554
+ lifecycle_scripts: lifecycleScripts,
555
+ direct_dependency_count: Object.keys(params.triage.manifest?.dependencies ?? {}).length,
556
+ parity_tier: params.parity.tier,
557
+ provenance_attested: params.parity.provenance_attested && effectiveProvenanceStatus === "sigstore_verified",
558
+ provenance_status: effectiveProvenanceStatus,
559
+ ...(params.parity.provenance_url ? { provenance_url: params.parity.provenance_url } : {}),
560
+ },
561
+ verdict: verdictRes.verdict,
562
+ recommended_action: verdictRes.recommended_action,
563
+ pinned_execution,
564
+ advisories: params.advisories,
565
+ evidence,
566
+ iocs: params.triage.iocs,
567
+ ...(rea_escalation_plan ? { rea_escalation_plan } : {}),
568
+ local_workspace_compromised,
569
+ host_capabilities: params.host_capabilities,
570
+ };
571
+ }
572
+
573
+ export function formatInspectionMarkdownCard(report ) {
574
+ const allObs = report.evidence.flatMap((e) => e.observations);
575
+ const allInf = report.evidence.flatMap((e) => e.inferences);
576
+ const allUnk = report.evidence.flatMap((e) => e.unknowns);
577
+
578
+ const lines = [
579
+ `# Title: \`${escapeMarkdownCell(report.title.package_name, 100)}@${escapeMarkdownCell(report.title.version, 48)}\``,
580
+ "",
581
+ `- **Verdict:** \`${report.verdict}\``,
582
+ `- **Recommended Action:** \`${report.recommended_action}\``,
583
+ `- **Org / Scope:** \`${escapeMarkdownCell(report.title.org_or_scope, 64)}\` | **Creator:** ${escapeMarkdownCell(report.title.creator, 80)}`,
584
+ `- **Category Tags:** ${report.title.category_tags.length ? report.title.category_tags.map((t) => `\`${escapeMarkdownCell(t, 40)}\``).join(", ") : "none"}`,
585
+ `- **Commit SHA:** ${report.title.commit_sha ? `\`${escapeMarkdownCell(report.title.commit_sha, 48)}\`` : "`unlinked`"}`,
586
+ "",
587
+ "## Info",
588
+ `- **Summary:** ${sanitizeUntrustedText(report.info.summary, 200) || "(no description)"}`,
589
+ `- **License:** \`${escapeMarkdownCell(report.info.license, 60)}\` | **Direct Dependencies:** ${report.info.direct_dependency_count}`,
590
+ `- **Binaries:** ${report.info.bin_names.length ? report.info.bin_names.map((b) => `\`${escapeMarkdownCell(b, 64)}\``).join(", ") : "none"} | **Lifecycle Hooks:** ${report.info.lifecycle_scripts.length ? report.info.lifecycle_scripts.map((s) => `\`${escapeMarkdownCell(s, 32)}\``).join(", ") : "none"}`,
591
+ `- **Tarball Parity Tier:** \`${report.info.parity_tier}\` | **npm Provenance:** \`${report.info.provenance_status}\` (sigstore_verified=\`${report.info.provenance_attested}\`)`,
592
+ `- **Verified SHA-512:** \`${report.pinned_execution.tarball_sha512 ?? "unavailable"}\``,
593
+ "",
594
+ "## Safe Execution Command",
595
+ report.pinned_execution.command
596
+ ? `\`\`\`bash\n${report.pinned_execution.command}\n\`\`\``
597
+ : "_Blocked — no runnable command emitted._",
598
+ `> Caveat: ${report.pinned_execution.caveat}`,
599
+ "",
600
+ "## Evidence Summary",
601
+ `- **Evidence IDs:** ${report.evidence.map((e) => `\`${e.evidence_id}\``).join(", ")}`,
602
+ ];
603
+
604
+ if (allObs.length > 0) {
605
+ lines.push("", "### Observations", "| Severity | Code | Location | Framework | Detail |", "|---|---|---|---|---|");
606
+ for (const o of allObs) {
607
+ const fw = [o.attack_id, o.atlas_id].filter(Boolean).join(" / ") || "-";
608
+ const loc = o.line ? `${o.path}:${o.line}` : o.path;
609
+ lines.push(`| \`${o.severity}\` | \`${o.code}\` | \`${escapeMarkdownCell(loc, 90)}\` | \`${fw}\` | ${escapeMarkdownCell(o.detail, 160)} |`);
610
+ }
611
+ } else {
612
+ lines.push("- **Observations:** No malicious or suspicious static indicators observed within inspected scope.");
613
+ }
614
+
615
+ if (allInf.length > 0) {
616
+ lines.push("", "### Inferences");
617
+ for (const inf of allInf) lines.push(`- ${sanitizeUntrustedText(inf, 240)}`);
618
+ }
619
+
620
+ if (allUnk.length > 0) {
621
+ lines.push("", "### Unknowns & Coverage Bounds");
622
+ for (const unk of allUnk) lines.push(`- ${sanitizeUntrustedText(unk, 240)}`);
623
+ }
624
+
625
+ if (report.rea_escalation_plan) {
626
+ lines.push(
627
+ "",
628
+ "### REA Tier-2 Escalation Plan",
629
+ `- **REA Available on Host:** \`${report.rea_escalation_plan.rea_available_on_host}\``,
630
+ `- **Policy:** ${report.rea_escalation_plan.bootstrap_prohibition}`,
631
+ "| Artifact | Signal | Recommended REA Tool | Rationale |",
632
+ "|---|---|---|---|",
633
+ );
634
+ for (const step of report.rea_escalation_plan.steps) {
635
+ lines.push(
636
+ `| \`${escapeMarkdownCell(step.path, 80)}\` | \`${step.signal}\` | \`${step.recommended_tool}\` | ${escapeMarkdownCell(step.rationale, 140)} |`,
637
+ );
638
+ }
639
+ }
640
+
641
+ if (report.iocs.length > 0) {
642
+ lines.push("", "### Defanged IOCs", "| Kind | Value | TLP | Confidence | Source |", "|---|---|---|---|---|");
643
+ for (const ioc of report.iocs.slice(0, 20)) {
644
+ lines.push(
645
+ `| \`${ioc.kind}\` | \`${escapeMarkdownCell(ioc.value, 120)}\` | \`${ioc.tlp}\` | \`${ioc.confidence}\` | \`${escapeMarkdownCell(ioc.source_path, 90)}\` |`,
646
+ );
647
+ }
648
+ }
649
+
650
+ if (report.local_workspace_compromised) {
651
+ lines.push(
652
+ "",
653
+ "## URGENT: Local Workspace Compromise Match",
654
+ `Detected \`${report.title.package_name}@${report.local_workspace_compromised.matched_version}\` inside \`${report.local_workspace_compromised.lockfile_path}\`.`,
655
+ ...report.local_workspace_compromised.containment_steps.map((s) => `- ${s}`),
656
+ );
657
+ }
658
+
659
+ return lines.join("\n");
660
+ }
661
+
662
+ export function formatDiscoveryMarkdown(list ) {
663
+ const lines = [
664
+ `# npx Discovery Directory: \`${list.query || "*"}\``,
665
+ `- **Registry Route:** \`${list.registry_route}\` | **Filters:** org=\`${list.filters.org ?? "*"}\`, creator=\`${list.filters.creator ?? "*"}\`, category=\`${list.filters.category ?? "*"}\``,
666
+ "",
667
+ ];
668
+ if (list.candidates.length > 0) {
669
+ lines.push("| Title (`pkg@ver`) | Org / Creator | License | Preview Verdict | Info |");
670
+ lines.push("|---|---|---|---|---|");
671
+ for (const c of list.candidates) {
672
+ lines.push(
673
+ `| \`${escapeMarkdownCell(c.package_name, 80)}@${escapeMarkdownCell(c.version, 32)}\` | \`${escapeMarkdownCell(c.org_or_scope, 40)}\` / ${escapeMarkdownCell(c.creator, 40)} | \`${escapeMarkdownCell(c.license, 30)}\` | \`${c.verdict_preview}\` | ${escapeMarkdownCell(c.summary, 160)} |`,
674
+ );
675
+ }
676
+ } else {
677
+ lines.push("_No matching candidates passed policy filters._");
678
+ }
679
+ if (list.blocked_candidates.length > 0) {
680
+ lines.push("", "### Policy-Blocked Candidates");
681
+ for (const b of list.blocked_candidates) {
682
+ lines.push(`- \`${escapeMarkdownCell(b.package_name, 80)}\`: ${sanitizeUntrustedText(b.reason, 200)}`);
683
+ }
684
+ }
685
+ if (list.unknowns.length > 0) {
686
+ lines.push("", "### Unknowns");
687
+ for (const u of list.unknowns) lines.push(`- ${sanitizeUntrustedText(u, 240)}`);
688
+ }
689
+ return lines.join("\n");
690
+ }
691
+
692
+ export function formatAnchorMarkdown(decision ) {
693
+ const lines = [
694
+ `# Safe Anchor Resolution: \`${escapeMarkdownCell(decision.package_name, 100)}\``,
695
+ `- **Recommended Action:** \`${decision.recommended_action}\``,
696
+ `- **Compromised Latest:** ${sanitizeUntrustedText(decision.compromised_latest.reason, 220)}`,
697
+ `- **Patient-Zero Commit SHA:** ${decision.compromised_latest.patient_zero_sha ? `\`${decision.compromised_latest.patient_zero_sha}\`` : "`unknown`"}`,
698
+ ];
699
+ if (decision.safe_anchor) {
700
+ const anchorProvStatus =
701
+ decision.safe_anchor.provenance_status ?? (decision.safe_anchor.provenance_attested ? "sigstore_verified" : "none");
702
+ lines.push(
703
+ "",
704
+ "## Safe Anchor Candidate",
705
+ `- **Commit SHA:** ${decision.safe_anchor.commit_sha ? `\`${decision.safe_anchor.commit_sha}\`` : "`none`"}`,
706
+ `- **Mapped npm Version:** ${decision.safe_anchor.version ? `\`${escapeMarkdownCell(decision.safe_anchor.version, 48)}\`` : "`none`"}`,
707
+ `- **Verified SHA-512:** ${decision.safe_anchor.tarball_sha512 ? `\`${decision.safe_anchor.tarball_sha512}\`` : "`none`"}`,
708
+ `- **npm Provenance:** \`${anchorProvStatus}\` (sigstore_verified=\`${decision.safe_anchor.provenance_attested}\`)`,
709
+ `- **Residual Advisories:** ${decision.safe_anchor.residual_advisories.length}`,
710
+ decision.safe_anchor.pinned_execution.command
711
+ ? `\`\`\`bash\n${decision.safe_anchor.pinned_execution.command}\n\`\`\``
712
+ : `> ${decision.safe_anchor.pinned_execution.caveat}`,
713
+ );
714
+ }
715
+ if (decision.alternatives.length > 0) {
716
+ lines.push("", "## Vetted Alternatives");
717
+ for (const alt of decision.alternatives) {
718
+ lines.push(
719
+ `- \`${escapeMarkdownCell(alt.package_name, 80)}@${escapeMarkdownCell(alt.version, 32)}\` (\`${alt.verdict}\`) — ${sanitizeUntrustedText(alt.reason, 180)}`,
720
+ );
721
+ }
722
+ }
723
+ if (decision.inspected_commits.length > 0) {
724
+ lines.push("", "## Commit History Walk", "| Commit | Date | Verdict | Changed | Cache Hits | Findings | Subject |", "|---|---|---|---|---|---|---|");
725
+ for (const c of decision.inspected_commits.slice(0, 15)) {
726
+ lines.push(
727
+ `| \`${c.commit_sha.slice(0, 10)}\` | ${c.committed_at_utc.slice(0, 10)} | \`${c.verdict}\` | ${c.changed_blobs} | ${c.cache_hits} | ${c.observations_count} | ${escapeMarkdownCell(c.subject, 100)} |`,
728
+ );
729
+ }
730
+ }
731
+ if (decision.unknowns.length > 0) {
732
+ lines.push("", "## Unknowns");
733
+ for (const u of decision.unknowns) lines.push(`- ${sanitizeUntrustedText(u, 240)}`);
734
+ }
735
+ return lines.join("\n");
736
+ }
737
+
738
+ /**
739
+ * Valid SARIF 2.1.0 output for GitHub Code Scanning / enterprise CI dashboards.
740
+ */
741
+ export function formatSarif210(report ) {
742
+ const allObs = report.evidence.flatMap((e) => e.observations);
743
+ const rulesMap = new Map ();
744
+
745
+ for (const o of allObs) {
746
+ if (!rulesMap.has(o.code)) {
747
+ rulesMap.set(o.code, {
748
+ id: o.code,
749
+ name: o.code,
750
+ shortDescription: { text: o.code.replaceAll("_", " ") },
751
+ properties: {
752
+ tags: [o.attack_id, o.atlas_id].filter(Boolean),
753
+ },
754
+ });
755
+ }
756
+ }
757
+
758
+ const levelFor = (sev ) => {
759
+ if (sev === "CRITICAL" || sev === "HIGH") return "error";
760
+ if (sev === "MEDIUM") return "warning";
761
+ return "note";
762
+ };
763
+
764
+ return {
765
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
766
+ version: "2.1.0",
767
+ runs: [
768
+ {
769
+ tool: {
770
+ driver: {
771
+ name: "coldpin",
772
+ version: ENGINE_VERSION,
773
+ informationUri: "https://github.com/hynko431/Coldpin-npx-Safe-Finder",
774
+ rules: Array.from(rulesMap.values()),
775
+ },
776
+ },
777
+ results: allObs.map((o) => ({
778
+ ruleId: o.code,
779
+ level: levelFor(o.severity),
780
+ message: { text: o.detail },
781
+ locations: [
782
+ {
783
+ physicalLocation: {
784
+ artifactLocation: { uri: o.path },
785
+ ...(o.line ? { region: { startLine: o.line } } : {}),
786
+ },
787
+ },
788
+ ],
789
+ properties: {
790
+ severity: o.severity,
791
+ verdict: report.verdict,
792
+ attack_id: o.attack_id,
793
+ atlas_id: o.atlas_id,
794
+ },
795
+ })),
796
+ },
797
+ ],
798
+ };
799
+ }
800
+
801
+ /**
802
+ * CycloneDX 1.5 SBOM + VEX JSON emitter for EU CRA / NIST SSDF / SOC 2 supply-chain evidence.
803
+ */
804
+ export function formatCycloneDxSbom(
805
+ report ,
806
+ directDependencies ,
807
+ ) {
808
+ const encodePurlName = (name ) =>
809
+ name.startsWith("@") ? `%40${encodeURIComponent(name.slice(1)).replace(/%2F/gi, "/")}` : encodeURIComponent(name);
810
+ const purl = `pkg:npm/${encodePurlName(report.title.package_name)}@${encodeURIComponent(report.title.version)}`;
811
+ const sha512Hex = report.pinned_execution.tarball_sha512?.startsWith("sha512-")
812
+ ? Buffer.from(report.pinned_execution.tarball_sha512.slice("sha512-".length), "base64").toString("hex")
813
+ : undefined;
814
+
815
+ const rootComponent = {
816
+ type: "library",
817
+ "bom-ref": purl,
818
+ name: report.title.package_name,
819
+ version: report.title.version,
820
+ purl,
821
+ licenses: report.info.license !== "UNKNOWN" ? [{ license: { id: report.info.license } }] : [],
822
+ hashes: sha512Hex ? [{ alg: "SHA-512", content: sha512Hex }] : [],
823
+ properties: [
824
+ { name: "coldpin:verdict", value: report.verdict },
825
+ { name: "coldpin:parity-tier", value: report.info.parity_tier },
826
+ { name: "coldpin:provenance-attested", value: String(report.info.provenance_attested) },
827
+ { name: "coldpin:provenance-status", value: report.info.provenance_status },
828
+ ...(report.title.commit_sha ? [{ name: "coldpin:commit-sha", value: report.title.commit_sha }] : []),
829
+ ],
830
+ };
831
+
832
+ const depEntries = Object.entries(directDependencies ?? {});
833
+ const depRefByName = new Map ();
834
+ const depComponents = depEntries.map(([depName, depRange]) => {
835
+ const depRef = `pkg:npm/${encodePurlName(depName)}@${encodeURIComponent(depRange)}`;
836
+ depRefByName.set(depName, depRef);
837
+ return {
838
+ type: "library",
839
+ "bom-ref": depRef,
840
+ name: depName,
841
+ version: depRange,
842
+ purl: depRef,
843
+ };
844
+ });
845
+
846
+ const vulnerabilities = report.advisories.map((adv) => {
847
+ const affectedRef =
848
+ adv.package_name === report.title.package_name
849
+ ? purl
850
+ : (depRefByName.get(adv.package_name) ?? purl);
851
+ return {
852
+ id: adv.id,
853
+ source: { name: adv.is_malicious ? "OpenSSF Malicious Packages" : "OSV", url: "https://api.osv.dev" },
854
+ description: adv.summary,
855
+ ratings: [
856
+ {
857
+ severity: adv.severity.toLowerCase(),
858
+ method: adv.is_malicious ? "other" : "CVSSv31",
859
+ },
860
+ ],
861
+ analysis: {
862
+ state: adv.is_malicious || adv.kev ? "exploitable" : "in_triage",
863
+ detail: adv.is_malicious
864
+ ? "OpenSSF MAL-* malicious package advisory matched inspected package."
865
+ : adv.kev
866
+ ? "Listed in CISA Known Exploited Vulnerabilities (KEV)."
867
+ : "Matched OSV advisory; review impact against policy.",
868
+ },
869
+ affects: [{ ref: affectedRef }],
870
+ };
871
+ });
872
+
873
+ return {
874
+ bomFormat: "CycloneDX",
875
+ specVersion: "1.5",
876
+ serialNumber: `urn:uuid:${randomUUID()}`,
877
+ version: 1,
878
+ metadata: {
879
+ timestamp: report.generated_at_utc,
880
+ tools: [{ vendor: "coldpin", name: "coldpin", version: ENGINE_VERSION }],
881
+ component: rootComponent,
882
+ },
883
+ components: [rootComponent, ...depComponents],
884
+ dependencies: [
885
+ {
886
+ ref: purl,
887
+ dependsOn: depComponents.map((d) => d["bom-ref"]),
888
+ },
889
+ ],
890
+ ...(vulnerabilities.length > 0 ? { vulnerabilities } : {}),
891
+ };
892
+ }
893
+
894
+
895
+ //# sourceURL=verdict/engine-and-formatters.ts