@browsercore/tls 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -0
  3. package/dist/certificates/certificates.d.ts +78 -0
  4. package/dist/certificates/certificates.d.ts.map +1 -0
  5. package/dist/certificates/certificates.js +692 -0
  6. package/dist/certificates/certificates.js.map +1 -0
  7. package/dist/crypto/keySchedule.d.ts +65 -0
  8. package/dist/crypto/keySchedule.d.ts.map +1 -0
  9. package/dist/crypto/keySchedule.js +197 -0
  10. package/dist/crypto/keySchedule.js.map +1 -0
  11. package/dist/errors.d.ts +53 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +72 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/extensions/extensions.d.ts +89 -0
  16. package/dist/extensions/extensions.d.ts.map +1 -0
  17. package/dist/extensions/extensions.js +141 -0
  18. package/dist/extensions/extensions.js.map +1 -0
  19. package/dist/handshake/handshake.d.ts +98 -0
  20. package/dist/handshake/handshake.d.ts.map +1 -0
  21. package/dist/handshake/handshake.js +366 -0
  22. package/dist/handshake/handshake.js.map +1 -0
  23. package/dist/index.d.ts +24 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +18 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/profiles/profiles.d.ts +28 -0
  28. package/dist/profiles/profiles.d.ts.map +1 -0
  29. package/dist/profiles/profiles.js +68 -0
  30. package/dist/profiles/profiles.js.map +1 -0
  31. package/dist/record/record.d.ts +80 -0
  32. package/dist/record/record.d.ts.map +1 -0
  33. package/dist/record/record.js +135 -0
  34. package/dist/record/record.js.map +1 -0
  35. package/dist/tls.d.ts +56 -0
  36. package/dist/tls.d.ts.map +1 -0
  37. package/dist/tls.js +102 -0
  38. package/dist/tls.js.map +1 -0
  39. package/dist/types.d.ts +157 -0
  40. package/dist/types.d.ts.map +1 -0
  41. package/dist/types.js +12 -0
  42. package/dist/types.js.map +1 -0
  43. package/dist/utils.d.ts +15 -0
  44. package/dist/utils.d.ts.map +1 -0
  45. package/dist/utils.js +20 -0
  46. package/dist/utils.js.map +1 -0
  47. package/package.json +51 -0
@@ -0,0 +1,692 @@
1
+ /**
2
+ * X.509 certificate handling (RFC 8446 §4.4.2, RFC 5280).
3
+ *
4
+ * Parses DER-encoded certificates, validates hostnames against SAN/CN, and
5
+ * verifies certificate chains against trust anchors. The cryptographic
6
+ * signature verification itself is delegated to @browsercore/crypto — this module
7
+ * owns ASN.1 layout and validation policy only.
8
+ */
9
+ import { crypto } from "@browsercore/crypto";
10
+ import { TlsHandshakeError } from "../errors.js";
11
+ /** Read a single DER element as a span. Throws {@link TlsHandshakeError} on truncation. */
12
+ function readTlv(buf, pos) {
13
+ if (pos >= buf.length) {
14
+ throw new TlsHandshakeError("certificate", {
15
+ cause: new Error(`DER truncated at offset ${pos}`),
16
+ });
17
+ }
18
+ const start = pos;
19
+ const tagByte = buf[pos++];
20
+ // We only handle single-byte tags (tag number < 31); X.509 never uses the
21
+ // long form for the tags we care about.
22
+ if ((tagByte & 0x1f) === 0x1f) {
23
+ throw new TlsHandshakeError("certificate", {
24
+ cause: new Error("multi-byte DER tags are not supported"),
25
+ });
26
+ }
27
+ const constructed = (tagByte & 0x20) !== 0;
28
+ if (pos >= buf.length) {
29
+ throw new TlsHandshakeError("certificate", {
30
+ cause: new Error(`DER length truncated at offset ${pos}`),
31
+ });
32
+ }
33
+ const lengthByte = buf[pos++];
34
+ let valueStart;
35
+ let length;
36
+ if ((lengthByte & 0x80) === 0) {
37
+ // Short form: single-byte length.
38
+ length = lengthByte;
39
+ valueStart = pos;
40
+ }
41
+ else {
42
+ // Long form: the low 7 bits give the number of length bytes.
43
+ const numBytes = lengthByte & 0x7f;
44
+ if (numBytes === 0) {
45
+ throw new TlsHandshakeError("certificate", {
46
+ cause: new Error("indefinite-length DER encoding is not supported"),
47
+ });
48
+ }
49
+ if (numBytes > 4 || pos + numBytes > buf.length) {
50
+ throw new TlsHandshakeError("certificate", {
51
+ cause: new Error(`DER length field overflow at offset ${pos}`),
52
+ });
53
+ }
54
+ length = 0;
55
+ for (let i = 0; i < numBytes; i++) {
56
+ length = (length << 8) | buf[pos++];
57
+ }
58
+ valueStart = pos;
59
+ }
60
+ const end = valueStart + length;
61
+ if (end > buf.length) {
62
+ throw new TlsHandshakeError("certificate", {
63
+ cause: new Error(`DER value truncated: need ${length} bytes at ${valueStart}, have ${buf.length - valueStart}`),
64
+ });
65
+ }
66
+ return { tag: tagByte, constructed, start, valueStart, end };
67
+ }
68
+ /** Peek the tag byte at `pos` without consuming it. */
69
+ function peekTag(buf, pos) {
70
+ if (pos >= buf.length) {
71
+ throw new TlsHandshakeError("certificate", {
72
+ cause: new Error(`DER truncated while peeking tag at offset ${pos}`),
73
+ });
74
+ }
75
+ return buf[pos];
76
+ }
77
+ /** Parse a DER OID (without its tag/length) into its dotted-arc string. */
78
+ function parseOid(buf, start, end) {
79
+ if (start >= end) {
80
+ throw new TlsHandshakeError("certificate", {
81
+ cause: new Error("empty OID"),
82
+ });
83
+ }
84
+ // The first byte encodes the first two arcs: floor(first / 40), first % 40.
85
+ const first = buf[start];
86
+ const arcs = [Math.floor(first / 40), first % 40];
87
+ let i = start + 1;
88
+ while (i < end) {
89
+ // Subsequent arcs are base-128 with the high bit as a continuation flag.
90
+ let value = 0;
91
+ let b;
92
+ do {
93
+ if (i >= end) {
94
+ throw new TlsHandshakeError("certificate", {
95
+ cause: new Error("OID arc truncated"),
96
+ });
97
+ }
98
+ b = buf[i++];
99
+ // Guard against overflow on absurdly long arcs.
100
+ value = (value << 7) | (b & 0x7f);
101
+ } while ((b & 0x80) !== 0);
102
+ arcs.push(value);
103
+ }
104
+ return arcs.join(".");
105
+ }
106
+ /** Parse a DER AlgorithmIdentifier (SEQUENCE { OID, parameters? }) into its OID string. */
107
+ function parseAlgorithmIdentifierOid(buf, start) {
108
+ const seq = readTlv(buf, start);
109
+ if (seq.tag !== 0x30) {
110
+ throw new TlsHandshakeError("certificate", {
111
+ cause: new Error(`expected AlgorithmIdentifier SEQUENCE, got tag 0x${seq.tag.toString(16)}`),
112
+ });
113
+ }
114
+ if (seq.valueStart >= seq.end) {
115
+ throw new TlsHandshakeError("certificate", {
116
+ cause: new Error("empty AlgorithmIdentifier"),
117
+ });
118
+ }
119
+ const oidTlv = readTlv(buf, seq.valueStart);
120
+ if (oidTlv.tag !== 0x06) {
121
+ throw new TlsHandshakeError("certificate", {
122
+ cause: new Error(`expected OID in AlgorithmIdentifier, got tag 0x${oidTlv.tag.toString(16)}`),
123
+ });
124
+ }
125
+ return parseOid(buf, oidTlv.valueStart, oidTlv.end);
126
+ }
127
+ /**
128
+ * Parse a DER ASN.1 TIME (UTCTime 0x17 or GeneralizedTime 0x18) into epoch
129
+ * seconds. Handles the "...Z" UTC suffix; fractional seconds are ignored.
130
+ */
131
+ function parseTime(buf, start, end, tag) {
132
+ const textDecoder = new TextDecoder();
133
+ const str = textDecoder.decode(buf.subarray(start, end)).trim();
134
+ // UTCTime: YYMMDDHHMMSSZ. GeneralizedTime: YYYYMMDDHHMMSS[.fff]Z.
135
+ const isUtc = tag === 0x17;
136
+ if (str.length < (isUtc ? 11 : 13)) {
137
+ throw new TlsHandshakeError("certificate", {
138
+ cause: new Error(`ASN.1 TIME too short: "${str}"`),
139
+ });
140
+ }
141
+ const yearStr = str.slice(0, isUtc ? 2 : 4);
142
+ let year = Number.parseInt(yearStr, 10);
143
+ if (Number.isNaN(year)) {
144
+ throw new TlsHandshakeError("certificate", {
145
+ cause: new Error(`invalid year in ASN.1 TIME: "${str}"`),
146
+ });
147
+ }
148
+ if (isUtc) {
149
+ // RFC 5280: UTCTime years 50..99 => 1950..1999; 00..49 => 2000..2049.
150
+ year += year >= 50 ? 1900 : 2000;
151
+ }
152
+ const month = Number.parseInt(str.slice(isUtc ? 2 : 4, isUtc ? 4 : 6), 10) - 1;
153
+ const day = Number.parseInt(str.slice(isUtc ? 4 : 6, isUtc ? 6 : 8), 10);
154
+ const hour = Number.parseInt(str.slice(isUtc ? 6 : 8, isUtc ? 8 : 10), 10);
155
+ const minute = Number.parseInt(str.slice(isUtc ? 8 : 10, isUtc ? 10 : 12), 10);
156
+ const second = Number.parseInt(str.slice(isUtc ? 10 : 12, isUtc ? 12 : 14), 10);
157
+ // Date.UTC returns ms since epoch in UTC.
158
+ const ms = Date.UTC(year, month, day, hour, minute, second);
159
+ if (Number.isNaN(ms)) {
160
+ throw new TlsHandshakeError("certificate", {
161
+ cause: new Error(`invalid ASN.1 TIME: "${str}"`),
162
+ });
163
+ }
164
+ return Math.floor(ms / 1000);
165
+ }
166
+ /**
167
+ * Map an issuer signature-algorithm OID to our {@link SignatureScheme} union.
168
+ * Only the schemes we advertise are recognized; anything else throws.
169
+ */
170
+ function oidToSignatureScheme(oid) {
171
+ switch (oid) {
172
+ case "1.2.840.10045.4.3.2":
173
+ return "ecdsa_secp256r1_sha256";
174
+ case "1.2.840.10045.4.3.3":
175
+ return "ecdsa_secp384r1_sha384";
176
+ case "1.2.840.113549.1.1.11":
177
+ return "rsa_pkcs1_sha256";
178
+ case "1.2.840.113549.1.1.10":
179
+ // id-RSASSA-PSS: the hash is in the parameters; default to sha256.
180
+ return "rsa_pss_rsae_sha256";
181
+ default:
182
+ throw new TlsHandshakeError("certificate", {
183
+ cause: new Error(`unsupported signature algorithm OID: ${oid}`),
184
+ });
185
+ }
186
+ }
187
+ /**
188
+ * Parse a single DER-encoded X.509 certificate.
189
+ *
190
+ * Decodes the outer Certificate SEQUENCE into its TBSCertificate, signature
191
+ * algorithm, and signature value, then extracts the validation-relevant fields.
192
+ * `tbsBytes` is captured as the EXACT DER span of the TBSCertificate so that
193
+ * signature verification over it is byte-correct.
194
+ *
195
+ * Throws {@link TlsHandshakeError} with phase "certificate" on malformed input.
196
+ */
197
+ export function parseCertificate(buf) {
198
+ // Outer Certificate SEQUENCE.
199
+ const cert = readTlv(buf, 0);
200
+ if (cert.tag !== 0x30) {
201
+ throw new TlsHandshakeError("certificate", {
202
+ cause: new Error(`expected Certificate SEQUENCE, got tag 0x${cert.tag.toString(16)}`),
203
+ });
204
+ }
205
+ // First element: TBSCertificate. Capture its full DER span for verification.
206
+ if (cert.valueStart >= cert.end) {
207
+ throw new TlsHandshakeError("certificate", {
208
+ cause: new Error("empty Certificate"),
209
+ });
210
+ }
211
+ const tbs = readTlv(buf, cert.valueStart);
212
+ if (tbs.tag !== 0x30) {
213
+ throw new TlsHandshakeError("certificate", {
214
+ cause: new Error(`expected TBSCertificate SEQUENCE, got tag 0x${tbs.tag.toString(16)}`),
215
+ });
216
+ }
217
+ const tbsBytes = buf.subarray(tbs.start, tbs.end);
218
+ // Walk the TBSCertificate fields in order.
219
+ let o = tbs.valueStart;
220
+ // version [0] EXPLICIT — optional, context-constructed tag 0xA0.
221
+ if (peekTag(buf, o) === 0xa0) {
222
+ o = readTlv(buf, o).end;
223
+ }
224
+ // serialNumber INTEGER — skip.
225
+ o = readTlv(buf, o).end;
226
+ // signature AlgorithmIdentifier.
227
+ const signatureScheme = oidToSignatureScheme(parseAlgorithmIdentifierOid(buf, o));
228
+ o = readTlv(buf, o).end;
229
+ // issuer Name — skip past it but remember the span for the issuer string.
230
+ const issuerTlv = readTlv(buf, o);
231
+ const issuer = parseName(buf, issuerTlv.start, issuerTlv.end);
232
+ o = issuerTlv.end;
233
+ // validity SEQUENCE { notBefore, notAfter }.
234
+ const validity = readTlv(buf, o);
235
+ if (validity.tag !== 0x30) {
236
+ throw new TlsHandshakeError("certificate", {
237
+ cause: new Error(`expected validity SEQUENCE, got tag 0x${validity.tag.toString(16)}`),
238
+ });
239
+ }
240
+ let v = validity.valueStart;
241
+ const notBeforeTlv = readTlv(buf, v);
242
+ const notBefore = parseTime(buf, notBeforeTlv.valueStart, notBeforeTlv.end, notBeforeTlv.tag);
243
+ v = notBeforeTlv.end;
244
+ const notAfterTlv = readTlv(buf, v);
245
+ const notAfter = parseTime(buf, notAfterTlv.valueStart, notAfterTlv.end, notAfterTlv.tag);
246
+ o = validity.end;
247
+ // subject Name — skip (we only need CN for legacy hostname match).
248
+ const subjectTlv = readTlv(buf, o);
249
+ o = subjectTlv.end;
250
+ // subjectPublicKeyInfo — capture the full DER span.
251
+ const spkiTlv = readTlv(buf, o);
252
+ if (spkiTlv.tag !== 0x30) {
253
+ throw new TlsHandshakeError("certificate", {
254
+ cause: new Error(`expected subjectPublicKeyInfo SEQUENCE, got tag 0x${spkiTlv.tag.toString(16)}`),
255
+ });
256
+ }
257
+ const subjectPublicKeyInfo = buf.subarray(spkiTlv.start, spkiTlv.end);
258
+ o = spkiTlv.end;
259
+ // Optional trailing context tags: issuerUniqueID [1], subjectUniqueID [2],
260
+ // extensions [3]. Only [3] carries fields we care about.
261
+ let subjectAltNames = [];
262
+ let keyUsageDigitalSignature = false;
263
+ let keyUsageKeyEncipherment = false;
264
+ let isCa = false;
265
+ let commonName;
266
+ while (o < tbs.end) {
267
+ const tag = peekTag(buf, o);
268
+ if (tag === 0xa3) {
269
+ // extensions [3] EXPLICIT: a SEQUENCE OF Extension inside a [3] wrapper.
270
+ const extWrapper = readTlv(buf, o);
271
+ const extensions = parseExtensionsBlock(buf, extWrapper.valueStart, extWrapper.end);
272
+ for (const ext of extensions) {
273
+ switch (ext.oid) {
274
+ case "2.5.29.17":
275
+ subjectAltNames = parseSubjectAltNames(ext.value);
276
+ break;
277
+ case "2.5.29.15":
278
+ ({ digitalSignature: keyUsageDigitalSignature, keyEncipherment: keyUsageKeyEncipherment } =
279
+ parseKeyUsage(ext.value));
280
+ break;
281
+ case "2.5.29.19":
282
+ isCa = parseBasicConstraints(ext.value);
283
+ break;
284
+ case "2.5.29.35":
285
+ default:
286
+ break;
287
+ }
288
+ }
289
+ o = extWrapper.end;
290
+ }
291
+ else if (tag === 0xa1 || tag === 0xa2) {
292
+ // issuerUniqueID / subjectUniqueID — skip.
293
+ o = readTlv(buf, o).end;
294
+ }
295
+ else {
296
+ // Unknown trailing element — stop scanning.
297
+ break;
298
+ }
299
+ }
300
+ // Fall back to the subject's CN if no SAN DNS names were present.
301
+ if (subjectAltNames.length === 0) {
302
+ commonName = parseCommonName(buf, subjectTlv.start, subjectTlv.end);
303
+ }
304
+ // Outer signatureAlgorithm (skip) + signatureValue.
305
+ // The TBS signature OID is authoritative for the scheme; the outer one
306
+ // must match it but we don't re-derive the scheme from it here.
307
+ const signatureAlgorithmEnd = readTlv(buf, tbs.end).end;
308
+ const sigValueTlv = readTlv(buf, signatureAlgorithmEnd);
309
+ if (sigValueTlv.tag !== 0x03) {
310
+ throw new TlsHandshakeError("certificate", {
311
+ cause: new Error(`expected signatureValue BIT STRING, got tag 0x${sigValueTlv.tag.toString(16)}`),
312
+ });
313
+ }
314
+ // signatureValue is a BIT STRING: first content byte is the "unused bits" count.
315
+ const signatureValue = buf.subarray(sigValueTlv.valueStart + 1, sigValueTlv.end);
316
+ // Under exactOptionalPropertyTypes, an optional `?:` property must be omitted
317
+ // rather than set to undefined. Only attach `commonName` when we found one.
318
+ if (commonName !== undefined) {
319
+ return {
320
+ tbsBytes,
321
+ subjectPublicKeyInfo,
322
+ subjectAltNames: Object.freeze(subjectAltNames),
323
+ commonName,
324
+ notBefore,
325
+ notAfter,
326
+ keyUsageDigitalSignature,
327
+ keyUsageKeyEncipherment,
328
+ signatureScheme,
329
+ signatureValue,
330
+ issuer,
331
+ isCa,
332
+ };
333
+ }
334
+ return {
335
+ tbsBytes,
336
+ subjectPublicKeyInfo,
337
+ subjectAltNames: Object.freeze(subjectAltNames),
338
+ notBefore,
339
+ notAfter,
340
+ keyUsageDigitalSignature,
341
+ keyUsageKeyEncipherment,
342
+ signatureScheme,
343
+ signatureValue,
344
+ issuer,
345
+ isCa,
346
+ };
347
+ }
348
+ /**
349
+ * Parse the subject Name and return a readable DN string (RFC 2253-ish).
350
+ * Used only for the `issuer` field and debug-friendliness.
351
+ */
352
+ function parseName(buf, start, _end) {
353
+ void _end;
354
+ const seq = readTlv(buf, start);
355
+ if (seq.tag !== 0x30) {
356
+ return "";
357
+ }
358
+ const rdnParts = [];
359
+ let o = seq.valueStart;
360
+ const textDecoder = new TextDecoder();
361
+ while (o < seq.end) {
362
+ // Each RelativeDistinguishedName is a SET of AttributeTypeAndValue.
363
+ const setTlv = readTlv(buf, o);
364
+ if (setTlv.tag !== 0x31) {
365
+ break;
366
+ }
367
+ let p = setTlv.valueStart;
368
+ if (p >= setTlv.end) {
369
+ o = setTlv.end;
370
+ continue;
371
+ }
372
+ const atv = readTlv(buf, p);
373
+ if (atv.tag !== 0x30) {
374
+ o = setTlv.end;
375
+ continue;
376
+ }
377
+ const oidTlv = readTlv(buf, atv.valueStart);
378
+ const oid = parseOid(buf, oidTlv.valueStart, oidTlv.end);
379
+ const valueTlv = readTlv(buf, oidTlv.end);
380
+ const value = textDecoder.decode(buf.subarray(valueTlv.valueStart, valueTlv.end));
381
+ rdnParts.push(`${oid}=${value}`);
382
+ o = setTlv.end;
383
+ }
384
+ return rdnParts.join(", ");
385
+ }
386
+ /** Extract the CN (OID 2.5.4.3) from a subject Name, if present. */
387
+ function parseCommonName(buf, start, _end) {
388
+ void _end;
389
+ const seq = readTlv(buf, start);
390
+ if (seq.tag !== 0x30) {
391
+ return undefined;
392
+ }
393
+ let o = seq.valueStart;
394
+ const textDecoder = new TextDecoder();
395
+ while (o < seq.end) {
396
+ const setTlv = readTlv(buf, o);
397
+ if (setTlv.tag !== 0x31) {
398
+ break;
399
+ }
400
+ let p = setTlv.valueStart;
401
+ while (p < setTlv.end) {
402
+ const atv = readTlv(buf, p);
403
+ if (atv.tag !== 0x30) {
404
+ break;
405
+ }
406
+ const oidTlv = readTlv(buf, atv.valueStart);
407
+ const oid = parseOid(buf, oidTlv.valueStart, oidTlv.end);
408
+ if (oid === "2.5.4.3") {
409
+ const valueTlv = readTlv(buf, oidTlv.end);
410
+ return textDecoder.decode(buf.subarray(valueTlv.valueStart, valueTlv.end));
411
+ }
412
+ p = atv.end;
413
+ }
414
+ o = setTlv.end;
415
+ }
416
+ return undefined;
417
+ }
418
+ /**
419
+ * Parse the extensions block (SEQUENCE OF Extension) between `start` and `end`.
420
+ * Each extension is SEQUENCE { extnID OID, critical BOOLEAN?, extnValue OCTET STRING }.
421
+ */
422
+ function parseExtensionsBlock(buf, start, _end) {
423
+ void _end;
424
+ const seq = readTlv(buf, start);
425
+ if (seq.tag !== 0x30) {
426
+ throw new TlsHandshakeError("certificate", {
427
+ cause: new Error(`expected extensions SEQUENCE, got tag 0x${seq.tag.toString(16)}`),
428
+ });
429
+ }
430
+ const extensions = [];
431
+ let o = seq.valueStart;
432
+ while (o < seq.end) {
433
+ const ext = readTlv(buf, o);
434
+ if (ext.tag !== 0x30) {
435
+ break;
436
+ }
437
+ let p = ext.valueStart;
438
+ const oidTlv = readTlv(buf, p);
439
+ const oid = parseOid(buf, oidTlv.valueStart, oidTlv.end);
440
+ p = oidTlv.end;
441
+ // Optional critical BOOLEAN.
442
+ if (peekTag(buf, p) === 0x01) {
443
+ p = readTlv(buf, p).end;
444
+ }
445
+ const valueTlv = readTlv(buf, p);
446
+ if (valueTlv.tag !== 0x04) {
447
+ throw new TlsHandshakeError("certificate", {
448
+ cause: new Error(`expected extnValue OCTET STRING, got tag 0x${valueTlv.tag.toString(16)}`),
449
+ });
450
+ }
451
+ // The extnValue OCTET STRING *contains* the DER-encoded extension value.
452
+ extensions.push({ oid, value: buf.subarray(valueTlv.valueStart, valueTlv.end) });
453
+ o = ext.end;
454
+ }
455
+ return extensions;
456
+ }
457
+ /**
458
+ * Parse the SAN extension value (already unwrapped from its OCTET STRING).
459
+ * The value is a SEQUENCE OF GeneralName; we only extract dNSName entries
460
+ * (context tag [2]).
461
+ */
462
+ function parseSubjectAltNames(value) {
463
+ const seq = readTlv(value, 0);
464
+ if (seq.tag !== 0x30) {
465
+ return Object.freeze([]);
466
+ }
467
+ const names = [];
468
+ const textDecoder = new TextDecoder();
469
+ let o = seq.valueStart;
470
+ while (o < seq.end) {
471
+ const tlv = readTlv(value, o);
472
+ // GeneralName: context-specific tag. dNSName is [2] (0x82), iPAddress [7].
473
+ const tag = tlv.tag;
474
+ const tagClass = tag & 0xc0;
475
+ const tagNumber = tag & 0x1f;
476
+ if (tagClass === 0x80 && tagNumber === 2) {
477
+ names.push(textDecoder.decode(value.subarray(tlv.valueStart, tlv.end)));
478
+ }
479
+ o = tlv.end;
480
+ }
481
+ return Object.freeze(names);
482
+ }
483
+ /**
484
+ * Parse the KeyUsage extension value (unwrapped OCTET STRING holding a BIT
485
+ * STRING). Returns the digitalSignature (bit 0) and keyEncipherment (bit 2)
486
+ * flags.
487
+ */
488
+ function parseKeyUsage(value) {
489
+ const bitString = readTlv(value, 0);
490
+ if (bitString.tag !== 0x03) {
491
+ return { digitalSignature: false, keyEncipherment: false };
492
+ }
493
+ // BIT STRING content: first byte = number of unused bits; then the bits.
494
+ const content = value.subarray(bitString.valueStart, bitString.end);
495
+ if (content.length < 2) {
496
+ return { digitalSignature: false, keyEncipherment: false };
497
+ }
498
+ // Pack the used bits into an integer (big-endian bit order).
499
+ const usedBytes = content.subarray(1); // skip the unused-bits count.
500
+ let bits = 0;
501
+ for (const byte of usedBytes) {
502
+ bits = (bits << 8) | byte;
503
+ }
504
+ // The bits are left-aligned; the real bit 0 is the most significant bit of
505
+ // the first used byte. digitalSignature = bit 0, keyEncipherment = bit 2.
506
+ const totalBits = usedBytes.length * 8;
507
+ const bitPosition = (bitIndex) => totalBits - 1 - bitIndex;
508
+ const getBit = (index) => {
509
+ const pos = bitPosition(index);
510
+ const byteIndex = Math.floor(pos / 8);
511
+ const bitInByte = pos % 8;
512
+ return (usedBytes[byteIndex] & (1 << (7 - bitInByte))) !== 0;
513
+ };
514
+ return {
515
+ digitalSignature: getBit(0),
516
+ keyEncipherment: getBit(2),
517
+ };
518
+ }
519
+ /**
520
+ * Parse the BasicConstraints extension value (unwrapped OCTET STRING holding a
521
+ * SEQUENCE { cA BOOLEAN DEFAULT FALSE, pathLenConstraint INTEGER? }).
522
+ */
523
+ function parseBasicConstraints(value) {
524
+ const seq = readTlv(value, 0);
525
+ if (seq.tag !== 0x30 || seq.valueStart >= seq.end) {
526
+ return false;
527
+ }
528
+ if (peekTag(value, seq.valueStart) !== 0x01) {
529
+ return false;
530
+ }
531
+ const boolTlv = readTlv(value, seq.valueStart);
532
+ return value[boolTlv.valueStart] !== 0;
533
+ }
534
+ /**
535
+ * Validate that a certificate is valid for the given hostname per RFC 6125.
536
+ *
537
+ * If the cert carries SAN DNS names, one must match (wildcard-aware, matching
538
+ * a single left-most label and NOT crossing dots). Otherwise we fall back to
539
+ * the legacy CommonName. IP-literal SANs are not matched here (server certs
540
+ * virtually always use DNS names).
541
+ */
542
+ export function validateHostname(cert, hostname) {
543
+ const names = cert.subjectAltNames;
544
+ if (names.length > 0) {
545
+ return names.some((name) => matchDnsName(name, hostname));
546
+ }
547
+ if (cert.commonName !== undefined) {
548
+ return matchDnsName(cert.commonName, hostname);
549
+ }
550
+ return false;
551
+ }
552
+ /** Match a DNS name (possibly wildcard) against a concrete hostname (RFC 6125 §6.4.3). */
553
+ function matchDnsName(pattern, hostname) {
554
+ const p = pattern.trim().toLowerCase();
555
+ const h = hostname.trim().toLowerCase();
556
+ if (p.length === 0 || h.length === 0) {
557
+ return false;
558
+ }
559
+ // Wildcard: only a leading "*." matches a single non-empty left label.
560
+ if (p.startsWith("*.")) {
561
+ const suffix = p.slice(1); // e.g. ".example.com"
562
+ // The prefix before the suffix must be exactly one label (no dots).
563
+ const prefix = h.slice(0, h.length - suffix.length);
564
+ if (!h.endsWith(suffix)) {
565
+ return false;
566
+ }
567
+ return prefix.length > 0 && !prefix.includes(".");
568
+ }
569
+ return p === h;
570
+ }
571
+ /**
572
+ * Verify a certificate chain: each cert is signed by the next, the root is in
573
+ * the trust anchors, and the leaf is valid for the hostname and not expired.
574
+ *
575
+ * Signature verification is delegated to @browsercore/crypto. Throws
576
+ * {@link TlsHandshakeError} with phase "certificate" on any failure.
577
+ */
578
+ export async function verifyChain(chain, trustAnchors, hostname, now) {
579
+ const certs = [chain.leaf, ...chain.intermediates, chain.root];
580
+ // 1. Validity windows: every cert must currently be valid.
581
+ for (const cert of certs) {
582
+ if (now < cert.notBefore || now > cert.notAfter) {
583
+ throw new TlsHandshakeError("certificate", {
584
+ cause: new Error(`certificate ${cert.issuer} not valid at ${now} (valid ${cert.notBefore}..${cert.notAfter})`),
585
+ });
586
+ }
587
+ }
588
+ // 2. basicConstraints CA flags: every intermediate must be a CA. The root
589
+ // is authorized by the trust-anchor SPKI match (step 4), not by its own
590
+ // basicConstraints, so a self-signed trust anchor need not set cA.
591
+ for (const cert of chain.intermediates) {
592
+ if (!cert.isCa) {
593
+ throw new TlsHandshakeError("certificate", {
594
+ cause: new Error(`intermediate certificate ${cert.issuer} is missing basicConstraints cA`),
595
+ });
596
+ }
597
+ }
598
+ // 3. For each (subject, issuer) pair, verify the signature. The issuer's
599
+ // public key (SPKI) verifies the subject's signature over its TBSCertificate.
600
+ const subjects = [chain.leaf, ...chain.intermediates];
601
+ const issuers = [...chain.intermediates, chain.root];
602
+ for (let i = 0; i < subjects.length; i++) {
603
+ const subject = subjects[i];
604
+ const issuer = issuers[i];
605
+ const ok = await crypto.verifySignature(subject.signatureScheme, issuer.subjectPublicKeyInfo, subject.signatureValue, subject.tbsBytes);
606
+ if (!ok) {
607
+ throw new TlsHandshakeError("certificate", {
608
+ cause: new Error(`signature verification failed: ${subject.issuer} not signed by ${issuer.issuer}`),
609
+ });
610
+ }
611
+ }
612
+ // 4. The chain root's SPKI must match one of the trust anchors.
613
+ const rootTrusted = trustAnchors.some((ta) => constantTimeEqual(ta.subjectPublicKeyInfo, chain.root.subjectPublicKeyInfo));
614
+ if (!rootTrusted) {
615
+ throw new TlsHandshakeError("certificate", {
616
+ cause: new Error(`root certificate ${chain.root.issuer} does not match any trust anchor`),
617
+ });
618
+ }
619
+ // 5. Hostname validation against the leaf.
620
+ if (!validateHostname(chain.leaf, hostname)) {
621
+ throw new TlsHandshakeError("certificate", {
622
+ cause: new Error(`hostname "${hostname}" does not match leaf certificate`),
623
+ });
624
+ }
625
+ }
626
+ /** Parse a PEM block (base64 between BEGIN/END CERTIFICATE) into DER bytes. */
627
+ export function pemToDer(pem) {
628
+ const beginMarker = "-----BEGIN CERTIFICATE-----";
629
+ const endMarker = "-----END CERTIFICATE-----";
630
+ const begin = pem.indexOf(beginMarker);
631
+ const end = pem.indexOf(endMarker);
632
+ if (begin === -1 || end === -1 || end <= begin) {
633
+ throw new Error("pemToDer: missing BEGIN/END CERTIFICATE markers");
634
+ }
635
+ const body = pem.slice(begin + beginMarker.length, end);
636
+ // Strip all whitespace (newlines, spaces) and base64-decode.
637
+ const cleaned = body.replace(/\s+/g, "");
638
+ const binary = base64Decode(cleaned);
639
+ return new Uint8Array(binary);
640
+ }
641
+ // ---------------------------------------------------------------------------
642
+ // Small byte helpers.
643
+ // ---------------------------------------------------------------------------
644
+ /** Constant-time byte comparison (length-equal only; leaks length, not contents). */
645
+ function constantTimeEqual(a, b) {
646
+ if (a.length !== b.length) {
647
+ return false;
648
+ }
649
+ let diff = 0;
650
+ for (let i = 0; i < a.length; i++) {
651
+ diff |= a[i] ^ b[i];
652
+ }
653
+ return diff === 0;
654
+ }
655
+ /** Base64-decode a string into bytes (no node:crypto dependency). */
656
+ function base64Decode(input) {
657
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
658
+ const decodeTable = new Int16Array(128).fill(-1);
659
+ for (let i = 0; i < alphabet.length; i++) {
660
+ decodeTable[alphabet.charCodeAt(i)] = i;
661
+ }
662
+ // Strip padding to compute output length.
663
+ let padding = 0;
664
+ for (let i = input.length - 1; i >= 0; i--) {
665
+ if (input[i] === "=") {
666
+ padding++;
667
+ }
668
+ else {
669
+ break;
670
+ }
671
+ }
672
+ const cleanLen = input.length - padding;
673
+ const outLen = Math.floor((cleanLen * 6) / 8);
674
+ const out = new Uint8Array(outLen);
675
+ let buffer = 0;
676
+ let bitsCollected = 0;
677
+ let outIndex = 0;
678
+ for (let i = 0; i < cleanLen; i++) {
679
+ const value = decodeTable[input.charCodeAt(i)];
680
+ if (value < 0) {
681
+ continue; // skip any non-alphabet char (shouldn't happen post-clean)
682
+ }
683
+ buffer = (buffer << 6) | value;
684
+ bitsCollected += 6;
685
+ if (bitsCollected >= 8) {
686
+ bitsCollected -= 8;
687
+ out[outIndex++] = (buffer >> bitsCollected) & 0xff;
688
+ }
689
+ }
690
+ return out;
691
+ }
692
+ //# sourceMappingURL=certificates.js.map