@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,350 @@
1
+ /**
2
+ * Customer-Owned Immutable 10-Year Evidence Packager (EU CRA Article 13/14).
3
+ * Produces deterministic, canonically hashed evidence bundles with Ed25519 signatures
4
+ * and RFC 3161 / Sigstore-compatible timestamp attestation envelopes (zero external deps).
5
+ */
6
+
7
+ import { LEGAL_DISCLAIMER } from './types.js';
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+ import {
18
+ base64ToBytes,
19
+ base64UrlToBytes,
20
+ bytesToBase64Url,
21
+ canonicalJson,
22
+ sha256Hex,
23
+ utf8ToBytes,
24
+ } from './crypto-utils.js';
25
+
26
+ export const EVIDENCE_BUNDLE_SCHEMA_VERSION = 'cra-evidence-bundle-v2' ;
27
+
28
+ // ASN.1 DER SPKI 12-byte prefix for raw 32-byte Ed25519 public keys
29
+ const ED25519_SPKI_PREFIX = new Uint8Array([
30
+ 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
31
+ ]);
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+ function makeFile(path , contentType , content ) {
48
+ const bytes = utf8ToBytes(content);
49
+ return {
50
+ path,
51
+ contentType,
52
+ sha256: sha256Hex(bytes),
53
+ byteLength: bytes.byteLength,
54
+ content,
55
+ };
56
+ }
57
+
58
+ function hexToBytes(hex ) {
59
+ const clean = hex.trim().toLowerCase();
60
+ if (clean.length % 2 !== 0 || !/^[0-9a-f]+$/.test(clean)) {
61
+ throw new Error('Invalid hex digest for RFC 3161 request');
62
+ }
63
+ const out = new Uint8Array(clean.length / 2);
64
+ for (let i = 0; i < out.length; i++) {
65
+ out[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);
66
+ }
67
+ return out;
68
+ }
69
+
70
+ /**
71
+ * Builds a standards-compliant ASN.1 DER RFC 3161 `TimeStampReq` for a SHA-256 hex digest
72
+ * (OID 2.16.840.1.101.3.4.2.1, version 1, certReq = TRUE) suitable for POSTing to an
73
+ * RFC 3161 TSA (e.g. FreeTSA / DigiCert TSA) with `Content-Type: application/timestamp-query`.
74
+ */
75
+ export function buildRfc3161RequestDer(sha256DigestHex ) {
76
+ const digest = hexToBytes(sha256DigestHex);
77
+ if (digest.byteLength !== 32) {
78
+ throw new Error(`Expected 32-byte SHA-256 digest, got ${digest.byteLength} bytes`);
79
+ }
80
+ // DER structure:
81
+ // SEQUENCE {
82
+ // INTEGER 1 (version)
83
+ // SEQUENCE (MessageImprint) {
84
+ // SEQUENCE (AlgorithmIdentifier: sha256 + NULL)
85
+ // 06 09 60 86 48 01 65 03 04 02 01 05 00
86
+ // OCTET STRING (32 bytes)
87
+ // }
88
+ // BOOLEAN TRUE (certReq) -> 01 01 ff
89
+ // }
90
+ const prefix = new Uint8Array([
91
+ 0x30, 0x39, // SEQUENCE (57 bytes)
92
+ 0x02, 0x01, 0x01, // INTEGER 1
93
+ 0x30, 0x31, // SEQUENCE (49 bytes) MessageImprint
94
+ 0x30, 0x0d, // SEQUENCE (13 bytes) AlgorithmIdentifier
95
+ 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OID sha256
96
+ 0x05, 0x00, // NULL
97
+ 0x04, 0x20, // OCTET STRING (32 bytes)
98
+ ]);
99
+ const suffix = new Uint8Array([0x01, 0x01, 0xff]); // BOOLEAN TRUE (certReq)
100
+
101
+ const out = new Uint8Array(prefix.length + digest.length + suffix.length);
102
+ out.set(prefix, 0);
103
+ out.set(digest, prefix.length);
104
+ out.set(suffix, prefix.length + digest.length);
105
+ return out;
106
+ }
107
+
108
+ async function importSigningKey(privateKey ) {
109
+ if (typeof privateKey !== 'string') {
110
+ return crypto.subtle.importKey('jwk', privateKey, { name: 'Ed25519' }, false, ['sign']);
111
+ }
112
+ const trimmed = privateKey.trim();
113
+ if (trimmed.startsWith('{')) {
114
+ return crypto.subtle.importKey('jwk', JSON.parse(trimmed) , { name: 'Ed25519' }, false, [
115
+ 'sign',
116
+ ]);
117
+ }
118
+ return crypto.subtle.importKey('pkcs8', base64ToBytes(trimmed), { name: 'Ed25519' }, false, ['sign']);
119
+ }
120
+
121
+ async function importVerifyKey(publicKey ) {
122
+ if (typeof publicKey !== 'string') {
123
+ return crypto.subtle.importKey('jwk', publicKey, { name: 'Ed25519' }, false, ['verify']);
124
+ }
125
+ const trimmed = publicKey.trim();
126
+ if (trimmed.startsWith('{')) {
127
+ return crypto.subtle.importKey('jwk', JSON.parse(trimmed) , { name: 'Ed25519' }, false, [
128
+ 'verify',
129
+ ]);
130
+ }
131
+ const raw = trimmed.startsWith('ed25519:') ? trimmed.slice('ed25519:'.length) : trimmed;
132
+ const bytes = base64ToBytes(raw);
133
+ const spki =
134
+ bytes.length === 32
135
+ ? (() => {
136
+ const buf = new Uint8Array(ED25519_SPKI_PREFIX.length + 32);
137
+ buf.set(ED25519_SPKI_PREFIX, 0);
138
+ buf.set(bytes, ED25519_SPKI_PREFIX.length);
139
+ return buf;
140
+ })()
141
+ : bytes;
142
+ return crypto.subtle.importKey('spki', spki, { name: 'Ed25519' }, false, ['verify']);
143
+ }
144
+
145
+ function buildManifestPayload(
146
+ schemaVersion ,
147
+ repoFullName ,
148
+ releaseTag ,
149
+ createdAt ,
150
+ files ,
151
+ ) {
152
+ return canonicalJson({
153
+ schemaVersion,
154
+ repoFullName,
155
+ releaseTag,
156
+ createdAt,
157
+ files: files.map((f) => ({
158
+ path: f.path,
159
+ contentType: f.contentType,
160
+ sha256: f.sha256,
161
+ byteLength: f.byteLength,
162
+ })),
163
+ });
164
+ }
165
+
166
+ /**
167
+ * Packages a deterministic, immutable EU CRA evidence bundle containing SBOM, OpenVEX,
168
+ * triage audit log, ENISA SRP 1:1 worksheet, and Article 14(8) customer advisory with
169
+ * per-file SHA-256 hashes, canonical manifest hash, optional Ed25519 signature, and
170
+ * RFC 3161 / Sigstore-compatible timestamp attestation envelope.
171
+ */
172
+ export async function buildEvidenceBundle(
173
+ input ,
174
+ ) {
175
+ const createdAt = input.generatedAt ?? new Date().toISOString();
176
+ const triageEvents = [...(input.triageEvents ?? [])].sort((a, b) =>
177
+ `${a.triagedAt}:${a.vulnerabilityId}`.localeCompare(`${b.triagedAt}:${b.vulnerabilityId}`),
178
+ );
179
+ const dossiers = input.dossiers ?? [];
180
+
181
+ const sbomContent = JSON.stringify(input.sbom, null, 2) + '\n';
182
+ const vexContent = JSON.stringify(input.vex, null, 2) + '\n';
183
+ const triageLogContent =
184
+ JSON.stringify(
185
+ {
186
+ schemaVersion: EVIDENCE_BUNDLE_SCHEMA_VERSION,
187
+ repo: input.repo,
188
+ releaseTag: input.releaseTag,
189
+ generatedAt: createdAt,
190
+ triageEvents,
191
+ },
192
+ null,
193
+ 2,
194
+ ) + '\n';
195
+
196
+ const srpWorksheetContent =
197
+ dossiers.length > 0
198
+ ? dossiers
199
+ .map(
200
+ (d) =>
201
+ d.webFormWorksheetMarkdown ??
202
+ d.markdownChecklist,
203
+ )
204
+ .join('\n\n---\n\n') + '\n'
205
+ : [
206
+ `# ENISA SRP 1:1 Worksheet — ${input.repo} (${input.releaseTag})`,
207
+ '',
208
+ `Generated at \`${createdAt}\`. Zero confirmed actively exploited vulnerabilities at bundle creation time; no ENISA Article 14 notification required.`,
209
+ '',
210
+ `> ${LEGAL_DISCLAIMER}`,
211
+ '',
212
+ ].join('\n');
213
+
214
+ const art14_8Content =
215
+ dossiers.length > 0
216
+ ? dossiers
217
+ .map(
218
+ (d) =>
219
+ d.article14_8Advisory?.markdown ??
220
+ `# Article 14(8) Advisory — ${d.vulnerability.vulnId}\n\n${d.vulnerability.summary}`,
221
+ )
222
+ .join('\n\n---\n\n') + '\n'
223
+ : [
224
+ `# EU CRA Article 14(8) Customer Advisory — ${input.repo} (${input.releaseTag})`,
225
+ '',
226
+ `Generated at \`${createdAt}\`. No customer security advisory required at bundle creation time.`,
227
+ '',
228
+ `> ${LEGAL_DISCLAIMER}`,
229
+ '',
230
+ ].join('\n');
231
+
232
+ const files = [
233
+ makeFile('art14-8-advisory.md', 'text/markdown; charset=utf-8', art14_8Content),
234
+ makeFile('sbom.cdx.json', 'application/vnd.cyclonedx+json; charset=utf-8', sbomContent),
235
+ makeFile('srp-worksheet.md', 'text/markdown; charset=utf-8', srpWorksheetContent),
236
+ makeFile('triage-log.json', 'application/json; charset=utf-8', triageLogContent),
237
+ makeFile('vex.json', 'application/vnd.openvex+json; charset=utf-8', vexContent),
238
+ ];
239
+
240
+ const manifestPayload = buildManifestPayload(
241
+ EVIDENCE_BUNDLE_SCHEMA_VERSION,
242
+ input.repo,
243
+ input.releaseTag,
244
+ createdAt,
245
+ files,
246
+ );
247
+ const manifestSha256 = sha256Hex(manifestPayload);
248
+ const bundleId = `evb_${manifestSha256.slice(0, 16)}`;
249
+
250
+ let signature ;
251
+ if (input.privateKeyB64 && input.keyId) {
252
+ const signingKey = await importSigningKey(input.privateKeyB64);
253
+ const sigBuf = await crypto.subtle.sign('Ed25519', signingKey, utf8ToBytes(manifestPayload));
254
+ signature = {
255
+ algorithm: 'Ed25519',
256
+ keyId: input.keyId,
257
+ value: bytesToBase64Url(new Uint8Array(sigBuf)),
258
+ signedAt: createdAt,
259
+ };
260
+ }
261
+
262
+ // Only attach `rfc3161TokenBase64` when an actual TSA TimeStampResp token was provided
263
+ // (never populate an unsent TimeStampReq as if it were a signed TSA token).
264
+ const rfc3161TokenBase64 =
265
+ input.rfc3161TokenBase64 && input.rfc3161TokenBase64.trim().length > 0
266
+ ? input.rfc3161TokenBase64.trim()
267
+ : undefined;
268
+
269
+ return {
270
+ bundleId,
271
+ schemaVersion: EVIDENCE_BUNDLE_SCHEMA_VERSION,
272
+ createdAt,
273
+ repoFullName: input.repo,
274
+ releaseTag: input.releaseTag,
275
+ files,
276
+ manifestSha256,
277
+ ...(signature ? { signature } : {}),
278
+ ...(rfc3161TokenBase64 ? { rfc3161TokenBase64 } : {}),
279
+ ...(input.tsaUrl ? { tsaUrl: input.tsaUrl } : {}),
280
+ };
281
+ }
282
+
283
+ /**
284
+ * Verifies an EvidenceBundle's per-file SHA-256 digests, canonical manifest SHA-256,
285
+ * and (if signed) Ed25519 signature over the canonical manifest.
286
+ */
287
+ export async function verifyEvidenceBundle(
288
+ bundle ,
289
+ publicKeyB64 ,
290
+ ) {
291
+ const errors = [];
292
+
293
+ for (const file of bundle.files) {
294
+ const bytes = utf8ToBytes(file.content);
295
+ const actualHash = sha256Hex(bytes);
296
+ if (actualHash !== file.sha256) {
297
+ errors.push(`File hash mismatch for ${file.path}`);
298
+ }
299
+ if (bytes.byteLength !== file.byteLength) {
300
+ errors.push(`File byteLength mismatch for ${file.path}`);
301
+ }
302
+ }
303
+
304
+ const manifestPayload = buildManifestPayload(
305
+ bundle.schemaVersion,
306
+ bundle.repoFullName,
307
+ bundle.releaseTag,
308
+ bundle.createdAt,
309
+ bundle.files,
310
+ );
311
+ const expectedManifestSha = sha256Hex(manifestPayload);
312
+ if (expectedManifestSha !== bundle.manifestSha256) {
313
+ errors.push('Manifest SHA-256 mismatch');
314
+ }
315
+
316
+ if (!bundle.signature) {
317
+ if (publicKeyB64 !== undefined) {
318
+ errors.push('Missing Ed25519 signature on evidence bundle (public key supplied for verification)');
319
+ }
320
+ } else {
321
+ try {
322
+ const keySource =
323
+ publicKeyB64 !== undefined
324
+ ? publicKeyB64
325
+ : bundle.signature.keyId.startsWith('ed25519:')
326
+ ? bundle.signature.keyId
327
+ : null;
328
+ if (!keySource) {
329
+ errors.push('Cannot resolve public key for bundle signature verification');
330
+ } else {
331
+ const key = await importVerifyKey(keySource);
332
+ const ok = await crypto.subtle.verify(
333
+ 'Ed25519',
334
+ key,
335
+ base64UrlToBytes(bundle.signature.value),
336
+ utf8ToBytes(manifestPayload),
337
+ );
338
+ if (!ok) {
339
+ errors.push('Invalid Ed25519 signature on evidence bundle manifest');
340
+ }
341
+ }
342
+ } catch (err) {
343
+ errors.push(
344
+ `Evidence bundle signature verification failed: ${err instanceof Error ? err.message : String(err)}`,
345
+ );
346
+ }
347
+ }
348
+
349
+ return { valid: errors.length === 0, errors };
350
+ }