@craswitch/mcp-server 0.0.0-stage → 2.0.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.
@@ -0,0 +1,909 @@
1
+ /**
2
+ * EU CRA Article 14 ENISA Single Reporting Platform (SRP) draft dossier generator,
3
+ * schema validator, and graceful fallback builder.
4
+ *
5
+ * IMPORTANT: CRA-Switch NEVER auto-submits notifications to ENISA. Every generated
6
+ * artifact embeds LEGAL_DISCLAIMER and ENISA_SRP_PORTAL_URL for manual vendor review.
7
+ */
8
+
9
+ import { ENISA_SRP_PORTAL_URL, LEGAL_DISCLAIMER, SCHEMA_VERSIONS } from './types.js';
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+ const VALID_STAGES = new Set ([
83
+ 'early_warning_24h',
84
+ 'detailed_notification_72h',
85
+ 'final_report_14d',
86
+ ]);
87
+
88
+ const HOUR_MS = 60 * 60 * 1000;
89
+ const DAY_MS = 24 * HOUR_MS;
90
+
91
+ export function escapeXml(value ) {
92
+ return value
93
+ .replace(/&/g, '&')
94
+ .replace(/</g, '&lt;')
95
+ .replace(/>/g, '&gt;')
96
+ .replace(/"/g, '&quot;')
97
+ .replace(/'/g, '&apos;');
98
+ }
99
+
100
+ function normalizeRepoInput(repo )
101
+
102
+
103
+
104
+ {
105
+ if (typeof repo === 'string') {
106
+ const parts = repo.split('/').filter((s) => s.length > 0);
107
+ return {
108
+ forge: 'github',
109
+ owner: parts[0] ?? '',
110
+ repoName: parts.slice(1).join('/'),
111
+ };
112
+ }
113
+ return {
114
+ forge: repo.forge ?? 'github',
115
+ owner: (repo.owner ?? '').trim(),
116
+ repoName: (repo.repo ?? repo.name ?? '').trim(),
117
+ };
118
+ }
119
+
120
+ function normalizeReleaseInput(
121
+ release ,
122
+ owner ,
123
+ repoName ,
124
+ )
125
+
126
+
127
+
128
+
129
+
130
+
131
+ {
132
+ const nowIso = new Date().toISOString();
133
+ if (typeof release === 'string') {
134
+ const tag = release.trim();
135
+ const base = 'https://craswitch.dev';
136
+ return {
137
+ releaseTag: tag,
138
+ awareAt: nowIso,
139
+ generatedAt: nowIso,
140
+ sbomRef: `${base}/api/v1/sbom/${owner}/${repoName}/${encodeURIComponent(tag)}`,
141
+ vexRef: `${base}/.well-known/vex.json?repo=${owner}/${repoName}`,
142
+ };
143
+ }
144
+
145
+ const base = (release.baseUrl ?? 'https://craswitch.dev').replace(/\/+$/, '');
146
+ const tag = (release.releaseTag ?? '').trim();
147
+ const awareAt = release.awareAt ?? nowIso;
148
+ const generatedAt = release.generatedAt ?? nowIso;
149
+ return {
150
+ releaseTag: tag,
151
+ awareAt,
152
+ generatedAt,
153
+ sbomRef:
154
+ release.sbomRef ?? `${base}/api/v1/sbom/${owner}/${repoName}/${encodeURIComponent(tag)}`,
155
+ vexRef: release.vexRef ?? `${base}/.well-known/vex.json?repo=${owner}/${repoName}`,
156
+ remediationResolvedAt: release.remediationResolvedAt,
157
+ };
158
+ }
159
+
160
+ function stageHeading(stage ) {
161
+ switch (stage) {
162
+ case 'early_warning_24h':
163
+ return 'Stage 1: Early Warning Notification (Article 14(2)(a) — within 24 hours)';
164
+ case 'detailed_notification_72h':
165
+ return 'Stage 2: Vulnerability Notification (Article 14(2)(b) — within 72 hours)';
166
+ case 'final_report_14d':
167
+ return 'Stage 3: Final Report (Article 14(2)(c) — within 14 days of corrective measure)';
168
+ }
169
+ }
170
+
171
+ function sanitizeXmlComment(text ) {
172
+ // XML 1.0 forbids `--` anywhere inside comments and trailing `-` before `-->`
173
+ return escapeXml(text).replace(/-{2,}/g, (run) => run.split('').join(' ')).replace(/-+$/g, '');
174
+ }
175
+
176
+ function buildXmlDraft(dossier , fallbackNotes ) {
177
+ const fallbackComment =
178
+ dossier.fallbackMode && fallbackNotes && fallbackNotes.length > 0
179
+ ? ` <!-- FALLBACK MODE ACTIVE: ${sanitizeXmlComment(fallbackNotes.join('; '))} -->\n`
180
+ : '';
181
+
182
+ const sourcesXml = dossier.vulnerability.sources
183
+ .map((s) => ` <Source>${escapeXml(s)}</Source>`)
184
+ .join('\n');
185
+ const purlsXml = dossier.vulnerability.matchedPurls
186
+ .map((p) => ` <Purl>${escapeXml(p)}</Purl>`)
187
+ .join('\n');
188
+ const refsXml = dossier.vulnerability.references
189
+ .map((r) => ` <Reference>${escapeXml(r)}</Reference>`)
190
+ .join('\n');
191
+
192
+ return [
193
+ '<?xml version="1.0" encoding="UTF-8"?>',
194
+ `<EnisaCraSrpDraft schemaVersion="${escapeXml(dossier.schemaVersion)}" stage="${escapeXml(dossier.stage)}" fallbackMode="${dossier.fallbackMode ? 'true' : 'false'}" autoSubmitted="false">`,
195
+ fallbackComment.trimEnd(),
196
+ ` <GeneratedAt>${escapeXml(dossier.generatedAt)}</GeneratedAt>`,
197
+ ` <SubmissionPortal>${escapeXml(dossier.submissionUrl)}</SubmissionPortal>`,
198
+ ` <LegalDisclaimer>${escapeXml(dossier.legalDisclaimer)}</LegalDisclaimer>`,
199
+ ' <Deadlines>',
200
+ ` <AwareAt>${escapeXml(dossier.deadlines.awareAt)}</AwareAt>`,
201
+ ` <EarlyWarningDueAt>${escapeXml(dossier.deadlines.earlyWarningDueAt)}</EarlyWarningDueAt>`,
202
+ ` <DetailedNotificationDueAt>${escapeXml(dossier.deadlines.detailedNotificationDueAt)}</DetailedNotificationDueAt>`,
203
+ ...(dossier.deadlines.finalReportDueAt
204
+ ? [` <FinalReportDueAt>${escapeXml(dossier.deadlines.finalReportDueAt)}</FinalReportDueAt>`]
205
+ : []),
206
+ ' </Deadlines>',
207
+ ' <Product>',
208
+ ` <Forge>${escapeXml(dossier.product.forge)}</Forge>`,
209
+ ` <Owner>${escapeXml(dossier.product.owner)}</Owner>`,
210
+ ` <Repository>${escapeXml(dossier.product.repo)}</Repository>`,
211
+ ` <ReleaseTag>${escapeXml(dossier.product.releaseTag)}</ReleaseTag>`,
212
+ ` <SbomRef>${escapeXml(dossier.product.sbomRef)}</SbomRef>`,
213
+ ` <VexRef>${escapeXml(dossier.product.vexRef)}</VexRef>`,
214
+ ' </Product>',
215
+ ' <Vulnerability activelyExploited="true">',
216
+ ` <VulnId>${escapeXml(dossier.vulnerability.vulnId)}</VulnId>`,
217
+ ...(dossier.vulnerability.cveId
218
+ ? [` <CveId>${escapeXml(dossier.vulnerability.cveId)}</CveId>`]
219
+ : []),
220
+ ...(dossier.vulnerability.euvdId
221
+ ? [` <EuvdId>${escapeXml(dossier.vulnerability.euvdId)}</EuvdId>`]
222
+ : []),
223
+ ` <Summary>${escapeXml(dossier.vulnerability.summary)}</Summary>`,
224
+ ' <Sources>',
225
+ sourcesXml,
226
+ ' </Sources>',
227
+ ' <MatchedComponents>',
228
+ purlsXml,
229
+ ' </MatchedComponents>',
230
+ ' <References>',
231
+ refsXml,
232
+ ' </References>',
233
+ ' </Vulnerability>',
234
+ '</EnisaCraSrpDraft>',
235
+ ]
236
+ .filter((line) => line.length > 0)
237
+ .join('\n');
238
+ }
239
+
240
+ function buildMarkdownChecklist(
241
+ dossier ,
242
+ fallbackNotes ,
243
+ ) {
244
+ const stageTasks = {
245
+ early_warning_24h: [
246
+ '- [ ] Confirm whether the matched production component is reachable in your shipped artifact.',
247
+ '- [ ] Identify EU Member States where the affected product version has been made available.',
248
+ '- [ ] If NOT exploitable, commit a `.cra-vex.json` `not_affected` justification to suppress the alert and publish signed OpenVEX.',
249
+ `- [ ] If exploitable, log into the ENISA Single Reporting Platform (${ENISA_SRP_PORTAL_URL}) and manually submit the 24h Early Warning before \`${dossier.deadlines.earlyWarningDueAt}\`.`,
250
+ ],
251
+ detailed_notification_72h: [
252
+ '- [ ] Document vulnerability severity, exploit vector, and initial impact assessment.',
253
+ '- [ ] Attach CycloneDX 1.6 SBOM and signed OpenVEX document (`/.well-known/vex.json`).',
254
+ '- [ ] Describe temporary mitigations or corrective patches under development.',
255
+ `- [ ] Manually submit the 72h Detailed Vulnerability Notification at ${ENISA_SRP_PORTAL_URL} before \`${dossier.deadlines.detailedNotificationDueAt}\`.`,
256
+ ],
257
+ final_report_14d: [
258
+ '- [ ] Confirm patch/remediation release tag and customer notification date.',
259
+ '- [ ] Document root cause, severity assessment, and any available indicators of compromise (IoCs).',
260
+ '- [ ] Update `.cra-vex.json` / release SBOM to reflect `fixed` status.',
261
+ `- [ ] Manually submit the 14-day Final Report at ${ENISA_SRP_PORTAL_URL} before \`${dossier.deadlines.finalReportDueAt ?? '14 days post-remediation'}\`.`,
262
+ ],
263
+ };
264
+
265
+ const lines = [
266
+ `# EU CRA Article 14 Draft Dossier — ${dossier.vulnerability.vulnId}`,
267
+ '',
268
+ `> **${stageHeading(dossier.stage)}**`,
269
+ '> **MANUAL SUBMISSION REQUIRED — NEVER AUTO-FILED BY CRA-SWITCH**',
270
+ '',
271
+ `> ${dossier.legalDisclaimer}`,
272
+ '',
273
+ ];
274
+
275
+ if (dossier.fallbackMode) {
276
+ lines.push(
277
+ '## Schema Fallback Notice',
278
+ '',
279
+ 'Primary ENISA SRP schema validation detected incomplete metadata; this dossier was rendered in **safe fallback mode** so your 24h notification clock is never blocked.',
280
+ ...(fallbackNotes && fallbackNotes.length > 0
281
+ ? ['', ...fallbackNotes.map((n) => `- ${n}`)]
282
+ : []),
283
+ '',
284
+ );
285
+ }
286
+
287
+ lines.push(
288
+ '## Statutory Deadlines (EU Cyber Resilience Act Art. 14)',
289
+ '',
290
+ `- **Awareness Timestamp:** \`${dossier.deadlines.awareAt}\``,
291
+ `- **24h Early Warning Due:** \`${dossier.deadlines.earlyWarningDueAt}\``,
292
+ `- **72h Detailed Notification Due:** \`${dossier.deadlines.detailedNotificationDueAt}\``,
293
+ ...(dossier.deadlines.finalReportDueAt
294
+ ? [`- **14d Final Report Due:** \`${dossier.deadlines.finalReportDueAt}\``]
295
+ : []),
296
+ `- **Official ENISA SRP Portal:** ${dossier.submissionUrl}`,
297
+ '',
298
+ '## Affected Product',
299
+ '',
300
+ `- **Repository:** \`${dossier.product.owner}/${dossier.product.repo}\` (${dossier.product.forge})`,
301
+ `- **Release Tag:** \`${dossier.product.releaseTag}\``,
302
+ `- **CycloneDX 1.6 SBOM:** ${dossier.product.sbomRef}`,
303
+ `- **Signed OpenVEX:** ${dossier.product.vexRef}`,
304
+ '',
305
+ '## Actively Exploited Vulnerability',
306
+ '',
307
+ `- **Primary ID:** \`${dossier.vulnerability.vulnId}\``,
308
+ ...(dossier.vulnerability.cveId ? [`- **CVE:** \`${dossier.vulnerability.cveId}\``] : []),
309
+ ...(dossier.vulnerability.euvdId ? [`- **ENISA EUVD:** \`${dossier.vulnerability.euvdId}\``] : []),
310
+ `- **Intel Sources:** ${dossier.vulnerability.sources.join(', ')}`,
311
+ `- **Summary:** ${dossier.vulnerability.summary}`,
312
+ '',
313
+ '### Matched Production PURLs',
314
+ '',
315
+ ...dossier.vulnerability.matchedPurls.map((p) => `- \`${p}\``),
316
+ '',
317
+ '## Operator Action Checklist',
318
+ '',
319
+ ...stageTasks[dossier.stage],
320
+ '',
321
+ );
322
+
323
+ if (dossier.vulnerability.references.length > 0) {
324
+ lines.push(
325
+ '## References',
326
+ '',
327
+ ...dossier.vulnerability.references.map((r) => `- ${r}`),
328
+ '',
329
+ );
330
+ }
331
+
332
+ return lines.join('\n');
333
+ }
334
+
335
+ function stageReportTypeLabel(stage ) {
336
+ switch (stage) {
337
+ case 'early_warning_24h':
338
+ return 'Early Warning (Article 14(2)(a) — 24h)';
339
+ case 'detailed_notification_72h':
340
+ return 'Vulnerability Notification (Article 14(2)(b) — 72h)';
341
+ case 'final_report_14d':
342
+ return 'Final Report (Article 14(2)(c) — 14d)';
343
+ }
344
+ }
345
+
346
+ function buildWebFormWorksheet(
347
+ core ,
348
+ opts ,
349
+ ) {
350
+ const states =
351
+ opts?.euMemberStatesDistributed && opts.euMemberStatesDistributed.length > 0
352
+ ? Array.from(new Set(opts.euMemberStatesDistributed.map((s) => s.trim().toUpperCase()).filter(Boolean)))
353
+ : ['EU (Confirm specific Member States before submission)'];
354
+ const confirmedAt = opts?.confirmedAt ?? core.deadlines.awareAt;
355
+ const confirmedMs = Date.parse(confirmedAt);
356
+ const detectedAt = opts?.detectedAt ?? confirmedAt;
357
+ const crossBorderImpact =
358
+ opts?.crossBorderImpact ?? (states.length > 1 || states[0]?.startsWith('EU') === true);
359
+
360
+ return {
361
+ reportType: stageReportTypeLabel(core.stage),
362
+ coordinatorCsirt: opts?.coordinatorCsirt?.trim() || 'DESIGNATED-NATIONAL-CSIRT (confirm in SRP)',
363
+ euMemberStatesDistributed: states,
364
+ productIdentifier: `${core.product.owner}/${core.product.repo}`,
365
+ releaseVersion: core.product.releaseTag,
366
+ affectedPurls: [...core.vulnerability.matchedPurls],
367
+ detectedAt,
368
+ confirmedAt,
369
+ suspectedMaliciousExploitation: opts?.suspectedMaliciousExploitation ?? true,
370
+ crossBorderImpact,
371
+ sensitivityFlags:
372
+ opts?.sensitivityFlags && opts.sensitivityFlags.length > 0
373
+ ? [...opts.sensitivityFlags]
374
+ : ['TLP:AMBER', 'CRA-ART14-CONFIDENTIAL'],
375
+ mitigationStatus:
376
+ opts?.mitigationStatus?.trim() ||
377
+ 'Under active remediation — verify patch availability or publish signed OpenVEX mitigation.',
378
+ statutoryDeadlines: {
379
+ earlyWarning24h: core.deadlines.earlyWarningDueAt,
380
+ detailedNotification72h: core.deadlines.detailedNotificationDueAt,
381
+ finalReport14d:
382
+ core.deadlines.finalReportDueAt ??
383
+ (Number.isNaN(confirmedMs) ? '' : new Date(confirmedMs + 14 * DAY_MS).toISOString()),
384
+ },
385
+ };
386
+ }
387
+
388
+ function buildWebFormWorksheetMarkdown(
389
+ worksheet ,
390
+ vulnId ,
391
+ ) {
392
+ return [
393
+ `# ENISA SRP 1:1 Manual Web-Form Copy-Paste Worksheet — ${vulnId}`,
394
+ '',
395
+ `> **Portal URL (EU Login + MFA required):** ${ENISA_SRP_PORTAL_URL}`,
396
+ '> **CRA-Switch NEVER auto-submits notifications to ENISA.** Copy each verified field below into the official SRP form.',
397
+ '',
398
+ '| ENISA SRP Web-Form Field | Value to Paste |',
399
+ '|---|---|',
400
+ `| **Report Type** | ${worksheet.reportType} |`,
401
+ `| **Coordinator CSIRT** | \`${worksheet.coordinatorCsirt}\` |`,
402
+ `| **EU Member States Distributed** | ${worksheet.euMemberStatesDistributed.join(', ')} |`,
403
+ `| **Product Identifier** | \`${worksheet.productIdentifier}\` |`,
404
+ `| **Release / Version** | \`${worksheet.releaseVersion}\` |`,
405
+ `| **Vulnerability ID** | \`${vulnId}\` |`,
406
+ `| **Detected At (Internal Triage)** | \`${worksheet.detectedAt}\` |`,
407
+ `| **Confirmed At (Statutory Clock Start)** | \`${worksheet.confirmedAt}\` |`,
408
+ `| **Suspected Unlawful / Malicious Exploitation** | ${worksheet.suspectedMaliciousExploitation ? 'Yes' : 'No'} |`,
409
+ `| **Cross-Border EU Impact** | ${worksheet.crossBorderImpact ? 'Yes' : 'No'} |`,
410
+ `| **Sensitivity / Handling Flags** | ${worksheet.sensitivityFlags.join(', ')} |`,
411
+ `| **Mitigation / Patch Status** | ${worksheet.mitigationStatus} |`,
412
+ `| **24h Early Warning Deadline** | \`${worksheet.statutoryDeadlines.earlyWarning24h}\` |`,
413
+ `| **72h Detailed Notification Deadline** | \`${worksheet.statutoryDeadlines.detailedNotification72h}\` |`,
414
+ `| **14d Final Report Deadline** | \`${worksheet.statutoryDeadlines.finalReport14d}\` |`,
415
+ '',
416
+ '## Affected Production PURLs',
417
+ '',
418
+ ...worksheet.affectedPurls.map((p) => `- \`${p}\``),
419
+ '',
420
+ `> ${LEGAL_DISCLAIMER}`,
421
+ ].join('\n');
422
+ }
423
+
424
+ function buildArticle14_8Advisory(
425
+ worksheet ,
426
+ vuln ,
427
+ product ,
428
+ severity = 'high',
429
+ ) {
430
+ const idLabel = vuln.cveId ?? vuln.vulnId;
431
+ const purlBullets = worksheet.affectedPurls.map((p) => `- \`${p}\``).join('\n');
432
+ const refBullets = vuln.references.map((r) => `- ${r}`).join('\n');
433
+
434
+ const markdown = [
435
+ `# Security Advisory (EU CRA Article 14(8)) — ${worksheet.productIdentifier} (${worksheet.releaseVersion})`,
436
+ '',
437
+ `**Vulnerability:** \`${idLabel}\` `,
438
+ `**Severity:** \`${severity.toUpperCase()}\` `,
439
+ `**Confirmed Exploitation Status:** Confirmed under EU CRA Article 14 triage (\`${worksheet.confirmedAt}\`) `,
440
+ `**Mitigation Status:** ${worksheet.mitigationStatus}`,
441
+ '',
442
+ '## Summary',
443
+ '',
444
+ vuln.summary,
445
+ '',
446
+ '## Affected Product & Components',
447
+ '',
448
+ `- **Product:** \`${worksheet.productIdentifier}\` version \`${worksheet.releaseVersion}\``,
449
+ `- **Affected EU Member States:** ${worksheet.euMemberStatesDistributed.join(', ')}`,
450
+ `- **Signed OpenVEX Feed:** ${product.vexRef}`,
451
+ `- **CycloneDX 1.6 SBOM:** ${product.sbomRef}`,
452
+ '',
453
+ '### Affected Production PURLs',
454
+ '',
455
+ purlBullets || '- (See attached SBOM)',
456
+ '',
457
+ '## Recommended Customer Actions',
458
+ '',
459
+ '1. Upgrade immediately once the patched release is published or apply the documented mitigating controls.',
460
+ `2. Verify machine-readable exploitability status via our Ed25519-signed OpenVEX feed: ${product.vexRef}`,
461
+ '3. Contact our security team if you require additional EU CRA Article 14(8) remediation guidance.',
462
+ ...(refBullets ? ['', '## References', '', refBullets] : []),
463
+ '',
464
+ `> ${LEGAL_DISCLAIMER}`,
465
+ ].join('\n');
466
+
467
+ const emailSubject = `[Security Advisory / EU CRA Art. 14(8)] ${worksheet.productIdentifier} ${worksheet.releaseVersion} — ${idLabel}`;
468
+ const emailBody = [
469
+ `Hello,`,
470
+ '',
471
+ `Pursuant to EU Cyber Resilience Act Article 14(8), we are notifying impacted users of an actively exploited vulnerability (${idLabel}) confirmed in ${worksheet.productIdentifier} ${worksheet.releaseVersion}.`,
472
+ '',
473
+ `Summary: ${vuln.summary}`,
474
+ `Mitigation Status: ${worksheet.mitigationStatus}`,
475
+ `Confirmed At: ${worksheet.confirmedAt}`,
476
+ '',
477
+ 'Affected Components:',
478
+ ...worksheet.affectedPurls.map((p) => ` - ${p}`),
479
+ '',
480
+ `Machine-Readable Signed OpenVEX: ${product.vexRef}`,
481
+ `CycloneDX 1.6 SBOM: ${product.sbomRef}`,
482
+ '',
483
+ 'Please review the recommended mitigation steps and upgrade as soon as the fixed release is available.',
484
+ '',
485
+ LEGAL_DISCLAIMER,
486
+ ].join('\n');
487
+
488
+ const ghsaPayload = {
489
+ summary: `${worksheet.productIdentifier} ${worksheet.releaseVersion}: Actively exploited vulnerability (${idLabel})`,
490
+ description: markdown,
491
+ severity,
492
+ ...(vuln.cveId ? { cve_id: vuln.cveId } : {}),
493
+ };
494
+
495
+ return {
496
+ markdown,
497
+ emailSubject,
498
+ emailBody,
499
+ ghsaPayload,
500
+ };
501
+ }
502
+
503
+ function assembleDossier(
504
+ core ,
505
+ fallbackNotes ,
506
+ opts ,
507
+ ) {
508
+ const webFormWorksheet = buildWebFormWorksheet(core, opts);
509
+ const webFormWorksheetMarkdown = buildWebFormWorksheetMarkdown(
510
+ webFormWorksheet,
511
+ core.vulnerability.vulnId,
512
+ );
513
+ const article14_8Advisory = buildArticle14_8Advisory(
514
+ webFormWorksheet,
515
+ core.vulnerability,
516
+ core.product,
517
+ opts?.severity ?? 'high',
518
+ );
519
+ return {
520
+ ...core,
521
+ xmlDraft: buildXmlDraft(core, fallbackNotes),
522
+ markdownChecklist: buildMarkdownChecklist(core, fallbackNotes),
523
+ webFormWorksheet,
524
+ webFormWorksheetMarkdown,
525
+ article14_8Advisory,
526
+ };
527
+ }
528
+
529
+ function isValidIsoTimestamp(val ) {
530
+ return typeof val === 'string' && val.trim().length > 0 && !Number.isNaN(Date.parse(val));
531
+ }
532
+
533
+ /**
534
+ * Validates an ENISA SRP Article 14 draft dossier against CRA-Switch schema requirements.
535
+ */
536
+ export function validateEnisaDossier(dossier ) {
537
+ const errors = [];
538
+ if (!dossier || typeof dossier !== 'object') {
539
+ return { valid: false, errors: ['Dossier must be an object'] };
540
+ }
541
+ const d = dossier ;
542
+
543
+ if (typeof d.schemaVersion !== 'string' || d.schemaVersion.trim().length === 0) {
544
+ errors.push('schemaVersion is required');
545
+ }
546
+ if (typeof d.stage !== 'string' || !VALID_STAGES.has(d.stage )) {
547
+ errors.push(`Invalid stage: ${String(d.stage)}`);
548
+ }
549
+ if (!isValidIsoTimestamp(d.generatedAt)) {
550
+ errors.push('generatedAt must be a valid ISO-8601 timestamp');
551
+ }
552
+
553
+ const deadlines = d.deadlines ;
554
+ if (!deadlines || typeof deadlines !== 'object') {
555
+ errors.push('deadlines object is required');
556
+ } else {
557
+ if (!isValidIsoTimestamp(deadlines.awareAt)) errors.push('deadlines.awareAt must be valid ISO-8601');
558
+ if (!isValidIsoTimestamp(deadlines.earlyWarningDueAt)) {
559
+ errors.push('deadlines.earlyWarningDueAt must be valid ISO-8601');
560
+ }
561
+ if (!isValidIsoTimestamp(deadlines.detailedNotificationDueAt)) {
562
+ errors.push('deadlines.detailedNotificationDueAt must be valid ISO-8601');
563
+ }
564
+ }
565
+
566
+ const product = d.product ;
567
+ if (!product || typeof product !== 'object') {
568
+ errors.push('product object is required');
569
+ } else {
570
+ if (typeof product.owner !== 'string' || product.owner.trim().length === 0) {
571
+ errors.push('product.owner is required');
572
+ }
573
+ if (typeof product.repo !== 'string' || product.repo.trim().length === 0) {
574
+ errors.push('product.repo is required');
575
+ }
576
+ if (typeof product.releaseTag !== 'string' || product.releaseTag.trim().length === 0) {
577
+ errors.push('product.releaseTag is required');
578
+ }
579
+ if (typeof product.sbomRef !== 'string' || product.sbomRef.trim().length === 0) {
580
+ errors.push('product.sbomRef is required');
581
+ }
582
+ if (typeof product.vexRef !== 'string' || product.vexRef.trim().length === 0) {
583
+ errors.push('product.vexRef is required');
584
+ }
585
+ }
586
+
587
+ const vuln = d.vulnerability ;
588
+ if (!vuln || typeof vuln !== 'object') {
589
+ errors.push('vulnerability object is required');
590
+ } else {
591
+ if (typeof vuln.vulnId !== 'string' || vuln.vulnId.trim().length === 0) {
592
+ errors.push('vulnerability.vulnId is required');
593
+ }
594
+ if (!Array.isArray(vuln.sources) || vuln.sources.length === 0) {
595
+ errors.push('vulnerability.sources must be a non-empty array');
596
+ }
597
+ if (!Array.isArray(vuln.matchedPurls) || vuln.matchedPurls.length === 0) {
598
+ errors.push('vulnerability.matchedPurls must be a non-empty array');
599
+ }
600
+ if (vuln.activelyExploited !== true) {
601
+ errors.push('vulnerability.activelyExploited must be true');
602
+ }
603
+ }
604
+
605
+ if (typeof d.legalDisclaimer !== 'string' || !d.legalDisclaimer.includes('NOT LEGAL ADVICE')) {
606
+ errors.push('legalDisclaimer must include mandatory non-legal-advice notice');
607
+ }
608
+ if (d.submissionUrl !== ENISA_SRP_PORTAL_URL) {
609
+ errors.push(`submissionUrl must equal ${ENISA_SRP_PORTAL_URL}`);
610
+ }
611
+ if (typeof d.markdownChecklist !== 'string' || !d.markdownChecklist.includes(ENISA_SRP_PORTAL_URL)) {
612
+ errors.push('markdownChecklist must be non-empty and reference ENISA_SRP_PORTAL_URL');
613
+ }
614
+ if (
615
+ typeof d.xmlDraft !== 'string' ||
616
+ !d.xmlDraft.includes('<?xml') ||
617
+ !d.xmlDraft.includes('autoSubmitted="false"') ||
618
+ !d.xmlDraft.includes('</EnisaCraSrpDraft>')
619
+ ) {
620
+ errors.push('xmlDraft must be well-formed XML with autoSubmitted="false"');
621
+ }
622
+
623
+ return { valid: errors.length === 0, errors };
624
+ }
625
+
626
+ /**
627
+ * Graceful fallback builder guaranteed to produce a schema-valid ENISA SRP draft dossier
628
+ * even when upstream metadata is incomplete or schema checks fail.
629
+ */
630
+ function extractDossierOptions(
631
+ release ,
632
+ options ,
633
+ ) {
634
+ const fromRelease = typeof release === 'string' ? {} : release;
635
+ return {
636
+ coordinatorCsirt: options?.coordinatorCsirt ?? fromRelease.coordinatorCsirt,
637
+ euMemberStatesDistributed:
638
+ options?.euMemberStatesDistributed ?? fromRelease.euMemberStatesDistributed,
639
+ detectedAt: options?.detectedAt ?? fromRelease.detectedAt,
640
+ confirmedAt: options?.confirmedAt ?? fromRelease.confirmedAt,
641
+ mitigationStatus: options?.mitigationStatus ?? fromRelease.mitigationStatus,
642
+ suspectedMaliciousExploitation:
643
+ options?.suspectedMaliciousExploitation ?? fromRelease.suspectedMaliciousExploitation,
644
+ crossBorderImpact: options?.crossBorderImpact ?? fromRelease.crossBorderImpact,
645
+ sensitivityFlags: options?.sensitivityFlags ?? fromRelease.sensitivityFlags,
646
+ severity: options?.severity ?? fromRelease.severity,
647
+ };
648
+ }
649
+
650
+ export function buildFallbackEnisaDossier(
651
+ stage ,
652
+ repo ,
653
+ release ,
654
+ match ,
655
+ validationErrors = [],
656
+ options ,
657
+ ) {
658
+ const safeStage = VALID_STAGES.has(stage) ? stage : 'early_warning_24h';
659
+ const normRepo = normalizeRepoInput(repo);
660
+ const owner = normRepo.owner || 'unknown-org';
661
+ const repoName = normRepo.repoName || 'unknown-repo';
662
+ const normRel = normalizeReleaseInput(release, owner, repoName);
663
+ const mergedOpts = extractDossierOptions(release, options);
664
+
665
+ const nowIso = new Date().toISOString();
666
+ const baseClock = mergedOpts.confirmedAt ?? normRel.awareAt;
667
+ const awareMs = Date.parse(baseClock);
668
+ const safeAwareMs = Number.isNaN(awareMs) ? Date.now() : awareMs;
669
+ const awareAt = new Date(safeAwareMs).toISOString();
670
+ const generatedAt = isValidIsoTimestamp(normRel.generatedAt) ? normRel.generatedAt : nowIso;
671
+ const remMs = normRel.remediationResolvedAt ? Date.parse(normRel.remediationResolvedAt) : NaN;
672
+ const finalBaseMs = Number.isNaN(remMs) ? safeAwareMs : remMs;
673
+
674
+ const matchedPurls =
675
+ Array.isArray(match.matchedComponents) && match.matchedComponents.length > 0
676
+ ? match.matchedComponents.map((c) => c.purl).filter((p) => p.length > 0)
677
+ : [`pkg:github/${owner}/${repoName}@${normRel.releaseTag || 'unknown'}`];
678
+
679
+ const sources =
680
+ Array.isArray(match.sources) && match.sources.length > 0 ? match.sources : ['cisa_kev'];
681
+
682
+ const vulnId = (match.vulnId ?? match.cveId ?? match.euvdId ?? 'UNKNOWN-VULN').trim() || 'UNKNOWN-VULN';
683
+
684
+ const core = {
685
+ schemaVersion: SCHEMA_VERSIONS.enisaSrp,
686
+ fallbackMode: true,
687
+ stage: safeStage,
688
+ generatedAt,
689
+ deadlines: {
690
+ awareAt,
691
+ earlyWarningDueAt: new Date(safeAwareMs + 24 * HOUR_MS).toISOString(),
692
+ detailedNotificationDueAt: new Date(safeAwareMs + 72 * HOUR_MS).toISOString(),
693
+ finalReportDueAt: new Date(finalBaseMs + 14 * DAY_MS).toISOString(),
694
+ },
695
+ product: {
696
+ forge: normRepo.forge,
697
+ owner,
698
+ repo: repoName,
699
+ releaseTag: normRel.releaseTag || 'untagged',
700
+ sbomRef: normRel.sbomRef,
701
+ vexRef: normRel.vexRef,
702
+ },
703
+ vulnerability: {
704
+ vulnId,
705
+ ...(match.cveId ? { cveId: match.cveId } : {}),
706
+ ...(match.euvdId ? { euvdId: match.euvdId } : {}),
707
+ sources,
708
+ matchedPurls,
709
+ summary:
710
+ match.summary && match.summary.trim().length > 0
711
+ ? match.summary.trim()
712
+ : 'Actively exploited vulnerability flagged by CRA-Switch fallback builder.',
713
+ references:
714
+ Array.isArray(match.references) && match.references.length > 0
715
+ ? match.references
716
+ : [ENISA_SRP_PORTAL_URL],
717
+ activelyExploited: true,
718
+ },
719
+ legalDisclaimer: LEGAL_DISCLAIMER,
720
+ submissionUrl: ENISA_SRP_PORTAL_URL,
721
+ };
722
+
723
+ const safeOpts = {
724
+ ...mergedOpts,
725
+ confirmedAt: awareAt,
726
+ ...(mergedOpts.detectedAt && Number.isNaN(Date.parse(mergedOpts.detectedAt))
727
+ ? { detectedAt: awareAt }
728
+ : {}),
729
+ };
730
+
731
+ return assembleDossier(core, validationErrors, safeOpts);
732
+ }
733
+
734
+ /**
735
+ * Generates an EU CRA Article 14 ENISA SRP draft dossier (JSON + XML + Markdown checklist
736
+ * + 1:1 ENISA SRP Web-Form Worksheet + parallel Article 14(8) Customer Advisory).
737
+ * Automatically runs `validateEnisaDossier` and invokes `buildFallbackEnisaDossier` if
738
+ * any schema check fails so an operator's 24h window is never blocked.
739
+ */
740
+ export function generateEnisaDossier(
741
+ stage ,
742
+ repo ,
743
+ release ,
744
+ match ,
745
+ options ,
746
+ ) {
747
+ const normRepo = normalizeRepoInput(repo);
748
+ const normRel = normalizeReleaseInput(release, normRepo.owner, normRepo.repoName);
749
+ const mergedOpts = extractDossierOptions(release, options);
750
+
751
+ const effectiveAwareAt = mergedOpts.confirmedAt ?? normRel.awareAt;
752
+ const awareMs = Date.parse(effectiveAwareAt);
753
+ const remMs = normRel.remediationResolvedAt ? Date.parse(normRel.remediationResolvedAt) : NaN;
754
+ const finalBaseMs = Number.isNaN(remMs) ? awareMs : remMs;
755
+
756
+ const core = {
757
+ schemaVersion: SCHEMA_VERSIONS.enisaSrp,
758
+ fallbackMode: false,
759
+ stage,
760
+ generatedAt: normRel.generatedAt,
761
+ deadlines: {
762
+ awareAt: effectiveAwareAt,
763
+ earlyWarningDueAt: Number.isNaN(awareMs)
764
+ ? ''
765
+ : new Date(awareMs + 24 * HOUR_MS).toISOString(),
766
+ detailedNotificationDueAt: Number.isNaN(awareMs)
767
+ ? ''
768
+ : new Date(awareMs + 72 * HOUR_MS).toISOString(),
769
+ finalReportDueAt: Number.isNaN(finalBaseMs)
770
+ ? undefined
771
+ : new Date(finalBaseMs + 14 * DAY_MS).toISOString(),
772
+ },
773
+ product: {
774
+ forge: normRepo.forge,
775
+ owner: normRepo.owner,
776
+ repo: normRepo.repoName,
777
+ releaseTag: normRel.releaseTag,
778
+ sbomRef: normRel.sbomRef,
779
+ vexRef: normRel.vexRef,
780
+ },
781
+ vulnerability: {
782
+ vulnId: match.vulnId,
783
+ ...(match.cveId ? { cveId: match.cveId } : {}),
784
+ ...(match.euvdId ? { euvdId: match.euvdId } : {}),
785
+ sources: match.sources,
786
+ matchedPurls: match.matchedComponents.map((c) => c.purl),
787
+ summary: match.summary,
788
+ references: match.references,
789
+ activelyExploited: true,
790
+ },
791
+ legalDisclaimer: LEGAL_DISCLAIMER,
792
+ submissionUrl: ENISA_SRP_PORTAL_URL,
793
+ };
794
+
795
+ const dossier = assembleDossier(core, undefined, mergedOpts);
796
+ const check = validateEnisaDossier(dossier);
797
+ if (!check.valid) {
798
+ return buildFallbackEnisaDossier(stage, repo, release, match, check.errors, mergedOpts);
799
+ }
800
+ return dossier;
801
+ }
802
+
803
+ /**
804
+ * Standalone 1:1 ENISA SRP Web-Form Worksheet + Article 14(8) Customer Advisory generator
805
+ * for `/tools/enisa-srp-builder` and MCP `craswitch_draft_enisa_srp`.
806
+ */
807
+ export function generateEnisaWorksheetStandalone(
808
+ input ,
809
+ ) {
810
+ const cveId = input.cveId.trim().toUpperCase();
811
+ const stage =
812
+ input.stage && VALID_STAGES.has(input.stage) ? input.stage : 'early_warning_24h';
813
+ const confirmedMs = Date.parse(input.confirmedAt);
814
+ const safeConfirmedMs = Number.isNaN(confirmedMs) ? Date.now() : confirmedMs;
815
+ const confirmedAt = new Date(safeConfirmedMs).toISOString();
816
+ const detectedAt =
817
+ input.detectedAt && !Number.isNaN(Date.parse(input.detectedAt))
818
+ ? new Date(Date.parse(input.detectedAt)).toISOString()
819
+ : confirmedAt;
820
+
821
+ const productRaw = (input.productName ?? 'vendor/product').trim() || 'vendor/product';
822
+ const [owner, repo] = productRaw.includes('/')
823
+ ? [productRaw.slice(0, productRaw.indexOf('/')), productRaw.slice(productRaw.indexOf('/') + 1)]
824
+ : ['vendor', productRaw];
825
+ const releaseVersion = (input.releaseVersion ?? 'v1.0.0').trim() || 'v1.0.0';
826
+
827
+ const affectedPurls =
828
+ input.affectedPurls && input.affectedPurls.length > 0
829
+ ? input.affectedPurls.map((p) => p.trim()).filter(Boolean)
830
+ : [`pkg:github/${owner}/${repo}@${releaseVersion}`];
831
+
832
+ const base = 'https://craswitch.dev';
833
+ const sbomRef =
834
+ input.sbomRef ?? `${base}/api/v1/sbom/${owner}/${repo}/${encodeURIComponent(releaseVersion)}`;
835
+ const vexRef = input.vexRef ?? `${base}/.well-known/vex.json?repo=${owner}/${repo}`;
836
+
837
+ const core = {
838
+ schemaVersion: SCHEMA_VERSIONS.enisaSrp,
839
+ fallbackMode: false,
840
+ stage,
841
+ generatedAt: new Date().toISOString(),
842
+ deadlines: {
843
+ awareAt: confirmedAt,
844
+ earlyWarningDueAt: new Date(safeConfirmedMs + 24 * HOUR_MS).toISOString(),
845
+ detailedNotificationDueAt: new Date(safeConfirmedMs + 72 * HOUR_MS).toISOString(),
846
+ finalReportDueAt: new Date(safeConfirmedMs + 14 * DAY_MS).toISOString(),
847
+ },
848
+ product: {
849
+ forge: 'github',
850
+ owner,
851
+ repo,
852
+ releaseTag: releaseVersion,
853
+ sbomRef,
854
+ vexRef,
855
+ },
856
+ vulnerability: {
857
+ vulnId: cveId,
858
+ ...(cveId.startsWith('CVE-') ? { cveId } : {}),
859
+ sources: ['cisa_kev'],
860
+ matchedPurls: affectedPurls,
861
+ summary:
862
+ input.summary?.trim() ||
863
+ `Confirmed actively exploited vulnerability ${cveId} affecting ${owner}/${repo} ${releaseVersion}.`,
864
+ references: cveId.startsWith('CVE-')
865
+ ? [`https://nvd.nist.gov/vuln/detail/${cveId}`, ENISA_SRP_PORTAL_URL]
866
+ : [ENISA_SRP_PORTAL_URL],
867
+ activelyExploited: true,
868
+ },
869
+ legalDisclaimer: LEGAL_DISCLAIMER,
870
+ submissionUrl: ENISA_SRP_PORTAL_URL,
871
+ };
872
+
873
+ const opts = {
874
+ coordinatorCsirt: input.coordinatorCsirt,
875
+ euMemberStatesDistributed: input.memberStates,
876
+ detectedAt,
877
+ confirmedAt,
878
+ mitigationStatus: input.mitigationStatus,
879
+ suspectedMaliciousExploitation: input.suspectedMaliciousExploitation,
880
+ crossBorderImpact: input.crossBorderImpact,
881
+ sensitivityFlags: input.sensitivityFlags,
882
+ severity: input.severity,
883
+ };
884
+
885
+ const webFormWorksheet = buildWebFormWorksheet(core, opts);
886
+ const webFormWorksheetMarkdown = buildWebFormWorksheetMarkdown(webFormWorksheet, cveId);
887
+ const article14_8Advisory = buildArticle14_8Advisory(
888
+ webFormWorksheet,
889
+ core.vulnerability,
890
+ core.product,
891
+ opts.severity ?? 'high',
892
+ );
893
+
894
+ return {
895
+ webFormWorksheet,
896
+ webFormWorksheetMarkdown,
897
+ article14_8Advisory,
898
+ submissionUrl: ENISA_SRP_PORTAL_URL,
899
+ legalDisclaimer: LEGAL_DISCLAIMER,
900
+ };
901
+ }
902
+
903
+ /**
904
+ * Formats an ENISA SRP dossier as pretty-printed JSON (without redundant inline xml/md bloat
905
+ * when callers want pure JSON, or full object preserved).
906
+ */
907
+ export function formatEnisaDossierJson(dossier ) {
908
+ return JSON.stringify(dossier, null, 2);
909
+ }