micro509 0.10.0 → 0.12.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.
@@ -3,13 +3,13 @@ import { childrenOf as i, decodeBoolean as a, decodeIntegerNumber as o, decodeNo
3
3
  import { OIDS as m } from "../internal/asn1/oids2.js";
4
4
  import { failureResult as h, rethrowIfInvariant as g, successResult as _ } from "../result/result.js";
5
5
  import { pemDecodeOrThrow as v, splitPemBlocksOrThrow as y } from "../pem/pem.js";
6
- import { importSpkiDer as b, importSpkiDerOrThrow as x } from "../keys/keys.js";
7
- import { describePublicKeyAlgorithm as S, describeSignatureAlgorithm as C } from "../internal/crypto/algorithm-names.js";
8
- import { decodeIpAddress as w } from "../internal/shared/ip.js";
9
- import { parseDistributionPointReasonFlagsContent as T, parseKeyUsageExtension as E } from "../internal/x509/extension-bits.js";
10
- import { nameFieldKeyFromOid as D } from "../internal/x509/name-fields.js";
11
- import { parseAuthorityInfoAccessMethodOid as O, parseExtendedKeyUsageOid as k } from "./extensions.js";
12
- import { decodeAndApplyKnownExtension as A } from "../internal/x509/extension-registry.js";
6
+ import { derivePublicKey as b, exportSpkiDer as x, importSpkiDer as S, importSpkiDerOrThrow as C } from "../keys/keys.js";
7
+ import { describePublicKeyAlgorithm as w, describeSignatureAlgorithm as T } from "../internal/crypto/algorithm-names.js";
8
+ import { decodeIpAddress as E } from "../internal/shared/ip.js";
9
+ import { parseDistributionPointReasonFlagsContent as D, parseKeyUsageExtension as O } from "../internal/x509/extension-bits.js";
10
+ import { nameFieldKeyFromOid as k } from "../internal/x509/name-fields.js";
11
+ import { parseAuthorityInfoAccessMethodOid as A, parseExtendedKeyUsageOid as j } from "./extensions.js";
12
+ import { decodeAndApplyKnownExtension as M } from "../internal/x509/extension-registry.js";
13
13
  //#region src/x509/parse.ts
14
14
  /**
15
15
  * Certificate and CSR parse boundary.
@@ -22,7 +22,7 @@ import { decodeAndApplyKnownExtension as A } from "../internal/x509/extension-re
22
22
  * @module
23
23
  */
24
24
  /** Shared UTF-8 decoder for IA5String / UTF8String values. */
25
- const j = new TextDecoder();
25
+ const N = new TextDecoder();
26
26
  /**
27
27
  * Identity helper that narrows the type of a custom {@linkcode ExtensionDecoder} literal.
28
28
  *
@@ -70,10 +70,10 @@ function parseCertificateDerOrThrow(e, t) {
70
70
  notBefore: l.notBefore,
71
71
  notAfter: l.notAfter,
72
72
  signatureAlgorithmOid: h.oid,
73
- signatureAlgorithmName: C(h.oid, h.parametersDer),
73
+ signatureAlgorithmName: T(h.oid, h.parametersDer),
74
74
  ...h.parametersDer === void 0 ? {} : { signatureAlgorithmParametersDer: h.parametersDer },
75
75
  publicKeyAlgorithmOid: d.oid,
76
- publicKeyAlgorithmName: S(d.oid, d.parametersOid),
76
+ publicKeyAlgorithmName: w(d.oid, d.parametersOid),
77
77
  ...d.parametersDer === void 0 ? {} : { publicKeyAlgorithmParametersDer: d.parametersDer },
78
78
  ...d.parametersOid === void 0 ? {} : { publicKeyParametersOid: d.parametersOid },
79
79
  extensions: c.all,
@@ -195,6 +195,9 @@ function parseCertificatePemOrThrow(e, t) {
195
195
  * Expects a single `-----BEGIN CERTIFICATE-----` block. For bundles
196
196
  * containing multiple certificates, use {@linkcode parseCertificateChainPem}.
197
197
  *
198
+ * **Synchronous:** returns a {@linkcode ParseCertificateResult} directly. Do
199
+ * not `await` this function.
200
+ *
198
201
  * @param pem PEM string with a CERTIFICATE block.
199
202
  * @param options Custom extension decoders to apply during parsing.
200
203
  */
@@ -241,10 +244,10 @@ function parseCertificateSigningRequestDerOrThrow(e, t) {
241
244
  signatureValue: u(o),
242
245
  subject: parseName(e, s.subject),
243
246
  signatureAlgorithmOid: d.oid,
244
- signatureAlgorithmName: C(d.oid, d.parametersDer),
247
+ signatureAlgorithmName: T(d.oid, d.parametersDer),
245
248
  ...d.parametersDer === void 0 ? {} : { signatureAlgorithmParametersDer: d.parametersDer },
246
249
  publicKeyAlgorithmOid: l.oid,
247
- publicKeyAlgorithmName: S(l.oid, l.parametersOid),
250
+ publicKeyAlgorithmName: w(l.oid, l.parametersOid),
248
251
  ...l.parametersDer === void 0 ? {} : { publicKeyAlgorithmParametersDer: l.parametersDer },
249
252
  ...l.parametersOid === void 0 ? {} : { publicKeyParametersOid: l.parametersOid },
250
253
  requestedExtensions: c.all,
@@ -349,7 +352,7 @@ function parseCertificateSigningRequestPem(e, t) {
349
352
  * @see {@linkcode getSubjectPublicKey} for the non-throwing variant
350
353
  */
351
354
  function getSubjectPublicKeyOrThrow(e, t) {
352
- return x(e.subjectPublicKeyInfoDer, t);
355
+ return C(e.subjectPublicKeyInfoDer, t);
353
356
  }
354
357
  /**
355
358
  * Import the subject public key of a parsed certificate or CSR as a WebCrypto `CryptoKey`.
@@ -357,7 +360,130 @@ function getSubjectPublicKeyOrThrow(e, t) {
357
360
  * @see `getSubjectPublicKeyOrThrow` for the throwing variant
358
361
  */
359
362
  function getSubjectPublicKey(e, t) {
360
- return b(e.subjectPublicKeyInfoDer, t);
363
+ return S(e.subjectPublicKeyInfoDer, t);
364
+ }
365
+ /** Extract the AlgorithmIdentifier TLV from a SubjectPublicKeyInfo DER buffer. */
366
+ function subjectPublicKeyInfoAlgorithmDer(e) {
367
+ let t = f(r(e, { maxDepth: 64 })[0], "SubjectPublicKeyInfo algorithm");
368
+ return e.slice(t.start - t.headerLength, t.end);
369
+ }
370
+ /**
371
+ * Derive the public half of `privateKey`, export it as SPKI DER, and classify
372
+ * how it relates to a certificate's SubjectPublicKeyInfo. Single source of truth
373
+ * for {@linkcode certificateMatchesPrivateKey} and {@linkcode matchCertificatePrivateKey}.
374
+ *
375
+ * Equal SPKI bytes mean the key owns the certificate. When they differ, the
376
+ * AlgorithmIdentifier portions decide whether it is a same-algorithm key
377
+ * mismatch or a cross-algorithm (`key_type_mismatch`) one.
378
+ */
379
+ async function compareCertificateToPrivateKey(e, t) {
380
+ let n = await x(await b(t));
381
+ return optionalBytesEqual(n, e) ? "match" : optionalBytesEqual(subjectPublicKeyInfoAlgorithmDer(n), subjectPublicKeyInfoAlgorithmDer(e)) ? "key_mismatch" : "key_type_mismatch";
382
+ }
383
+ /**
384
+ * Check whether a certificate's subject public key belongs to a private key.
385
+ *
386
+ * Confirming that an uploaded private key actually matches the certificate it
387
+ * was submitted with is the first thing a key-intake or issuance endpoint must
388
+ * do. This derives the public half of `privateKey`, exports it as
389
+ * SubjectPublicKeyInfo DER, and compares those bytes against the certificate's
390
+ * own SubjectPublicKeyInfo — the canonical, algorithm-agnostic way to test key
391
+ * ownership. (Comparing JWKs field by field, or signing a probe and verifying
392
+ * it, are both more fragile.)
393
+ *
394
+ * A private key of a different type — e.g. an ECDSA key against an RSA
395
+ * certificate — simply produces different SPKI DER and returns `false`, so
396
+ * callers get a single boolean without branching on the kind of mismatch. Reach
397
+ * for {@linkcode matchCertificatePrivateKey} when you need the reason a match
398
+ * failed (or a typed failure instead of a thrown error) at a trust boundary.
399
+ *
400
+ * The comparison is over the exact DER encoding. A certificate whose
401
+ * SubjectPublicKeyInfo pins RSASSA-PSS parameters (rather than the plain
402
+ * `rsaEncryption` OID that WebCrypto emits) therefore will not match even for
403
+ * the same modulus; such certificates are rare in practice.
404
+ *
405
+ * @param certificate PEM string, DER bytes, or an already-parsed certificate.
406
+ * @param privateKey An extractable private `CryptoKey`.
407
+ * @returns `true` when the private key's public half matches the certificate's
408
+ * subject public key.
409
+ *
410
+ * @throws {Error} If `certificate` is malformed, or `privateKey` is not an
411
+ * extractable private key of a supported type (propagated from
412
+ * {@linkcode derivePublicKey}). Use {@linkcode matchCertificatePrivateKey} for a
413
+ * typed `Result` instead of thrown errors.
414
+ *
415
+ * @example
416
+ * ```ts
417
+ * const privateKey = await importPkcs8PemOrThrow(keyPem, { kind: 'ecdsa', curve: 'P-256' });
418
+ * if (!(await certificateMatchesPrivateKey(certificatePem, privateKey))) {
419
+ * throw new Error('uploaded key does not match the certificate');
420
+ * }
421
+ * ```
422
+ *
423
+ * @see {@linkcode matchCertificatePrivateKey} for the typed-`Result` variant with a mismatch reason
424
+ * @see {@linkcode getSubjectPublicKeyOrThrow} to obtain the certificate's public key directly
425
+ * @see {@linkcode derivePublicKey} for the private-to-public bridge this builds on
426
+ */
427
+ async function certificateMatchesPrivateKey(e, t) {
428
+ return await compareCertificateToPrivateKey(parseCertificateFromSource(e).subjectPublicKeyInfoDer, t) === "match";
429
+ }
430
+ /**
431
+ * Check whether a certificate's subject public key belongs to a private key,
432
+ * returning a typed {@linkcode MatchCertificatePrivateKeyResult}.
433
+ *
434
+ * The `Result`-returning companion to {@linkcode certificateMatchesPrivateKey}:
435
+ * where the boolean helper answers only "does it match?" (and throws on bad
436
+ * input), this surfaces the expected failures a key-intake or issuance endpoint
437
+ * meets on untrusted input as typed codes rather than exceptions — matching the
438
+ * house rule of returning `Result` for expected failures and throwing only for
439
+ * invariants. `ok: true` means the key owns the certificate; a failure carries
440
+ * one of:
441
+ *
442
+ * - `malformed_certificate` — `certificate` could not be parsed.
443
+ * - `unsupported_private_key` — `privateKey` is not an extractable private key
444
+ * of a supported type (from {@linkcode derivePublicKey}).
445
+ * - `key_type_mismatch` — the key is a different algorithm than the
446
+ * certificate's subject public key.
447
+ * - `key_mismatch` — the key is the right algorithm but a different key.
448
+ *
449
+ * As with {@linkcode certificateMatchesPrivateKey}, the comparison is over exact
450
+ * SPKI DER, so a certificate pinning RSASSA-PSS parameters reports
451
+ * `key_type_mismatch` against the `rsaEncryption` SPKI WebCrypto emits.
452
+ *
453
+ * @param certificate PEM string, DER bytes, or an already-parsed certificate.
454
+ * @param privateKey An extractable private `CryptoKey`.
455
+ * @returns A success when the key matches, or a typed failure otherwise.
456
+ *
457
+ * @example
458
+ * ```ts
459
+ * const result = await matchCertificatePrivateKey(certificatePem, privateKey);
460
+ * if (!result.ok) {
461
+ * // result.code is 'malformed_certificate' | 'unsupported_private_key'
462
+ * // | 'key_type_mismatch' | 'key_mismatch'
463
+ * throw new Error(`key does not match certificate: ${result.code}`);
464
+ * }
465
+ * ```
466
+ *
467
+ * @see {@linkcode certificateMatchesPrivateKey} for the plain-boolean variant
468
+ */
469
+ async function matchCertificatePrivateKey(e, t) {
470
+ let n;
471
+ try {
472
+ n = parseCertificateFromSource(e);
473
+ } catch (e) {
474
+ return g(e), h("malformed_certificate", e instanceof Error ? e.message : "Malformed certificate");
475
+ }
476
+ let r;
477
+ try {
478
+ r = await compareCertificateToPrivateKey(n.subjectPublicKeyInfoDer, t);
479
+ } catch (e) {
480
+ return g(e), h("unsupported_private_key", e instanceof Error ? e.message : "Unsupported private key");
481
+ }
482
+ switch (r) {
483
+ case "match": return _(void 0);
484
+ case "key_mismatch": return h("key_mismatch", "Private key does not match the certificate's subject public key");
485
+ case "key_type_mismatch": return h("key_type_mismatch", "Private key algorithm does not match the certificate's subject public key algorithm");
486
+ }
361
487
  }
362
488
  /**
363
489
  * Find a raw extension by OID within a parsed extension list.
@@ -461,7 +587,7 @@ function parseExtensionSequence(e, t, n) {
461
587
  critical: m,
462
588
  valueDer: new Uint8Array(g.value),
463
589
  valueHex: p(g.value)
464
- }), A(n, u, o, g.value);
590
+ }), M(n, u, o, g.value);
465
591
  }
466
592
  return {
467
593
  all: r,
@@ -491,7 +617,7 @@ function parseRelativeDistinguishedName(e, t) {
491
617
  function parseNameAttributeSet(e, t) {
492
618
  let n = [], r = {};
493
619
  for (let a of i(e, t)) {
494
- let t = i(e, a), o = c(f(t[0], "name OID").value), s = f(t[1], "name value"), u = D(o), d = l(s.tag, s.value), p = u === void 0 ? {
620
+ let t = i(e, a), o = c(f(t[0], "name OID").value), s = f(t[1], "name value"), u = k(o), d = l(s.tag, s.value), p = u === void 0 ? {
495
621
  oid: o,
496
622
  valueTag: s.tag,
497
623
  value: d
@@ -579,11 +705,11 @@ function parseBasicConstraints(e) {
579
705
  }
580
706
  /** @internal Decode the Key Usage BIT STRING extension value. */
581
707
  function parseKeyUsage(e) {
582
- return E(e);
708
+ return O(e);
583
709
  }
584
710
  /** @internal Decode the Extended Key Usage SEQUENCE OF OIDs. */
585
711
  function parseExtendedKeyUsage(e) {
586
- return i(e, f(n(e, { maxDepth: 64 }), "extendedKeyUsage sequence")).map((e) => k(c(e.value)));
712
+ return i(e, f(n(e, { maxDepth: 64 }), "extendedKeyUsage sequence")).map((e) => j(c(e.value)));
587
713
  }
588
714
  /** @internal Decode the Certificate Policies extension value. */
589
715
  function parseCertificatePolicies(e) {
@@ -706,6 +832,12 @@ function parseInhibitAnyPolicy(e) {
706
832
  function parseSubjectAltNames(e) {
707
833
  return i(e, f(n(e, { maxDepth: 64 }), "subjectAltName sequence")).map((t) => parseGeneralName(e, t));
708
834
  }
835
+ /** @internal Decode a bare DER-encoded X.501 Name, as carried in a `directoryName` GeneralName. */
836
+ function parseDistinguishedNameDer(e) {
837
+ let t = f(n(e, { maxDepth: 64 }), "distinguished name sequence");
838
+ if (t.tag !== 48) throw Error("distinguished name must use SEQUENCE");
839
+ return parseName(e, t);
840
+ }
709
841
  /** @internal Decode the Authority Information Access extension value. */
710
842
  function parseAuthorityInfoAccess(e) {
711
843
  let t = f(n(e, { maxDepth: 64 }), "authorityInfoAccess sequence");
@@ -720,8 +852,8 @@ function parseAuthorityInfoAccess(e) {
720
852
  if (r.tag !== 6) throw Error("authorityInfoAccess method must use OBJECT IDENTIFIER");
721
853
  if (a.tag !== 134) throw Error(`Unsupported authorityInfoAccess location tag: ${a.tag}`);
722
854
  return {
723
- method: O(c(r.value)),
724
- uri: j.decode(a.value)
855
+ method: A(c(r.value)),
856
+ uri: N.decode(a.value)
725
857
  };
726
858
  });
727
859
  }
@@ -755,7 +887,7 @@ function parseDistributionPointField(e, t, n) {
755
887
  return;
756
888
  case 129:
757
889
  if (n.reasons !== void 0) throw Error("DistributionPoint reasons must not repeat");
758
- n.reasons = T(t.value);
890
+ n.reasons = D(t.value);
759
891
  return;
760
892
  case 162:
761
893
  if (n.crlIssuer !== void 0) throw Error("DistributionPoint crlIssuer must not repeat");
@@ -798,19 +930,19 @@ function parseGeneralName(e, t) {
798
930
  }
799
931
  case 129: return {
800
932
  type: "email",
801
- value: j.decode(t.value)
933
+ value: N.decode(t.value)
802
934
  };
803
935
  case 130: return {
804
936
  type: "dns",
805
- value: j.decode(t.value)
937
+ value: N.decode(t.value)
806
938
  };
807
939
  case 134: return {
808
940
  type: "uri",
809
- value: j.decode(t.value)
941
+ value: N.decode(t.value)
810
942
  };
811
943
  case 135: return {
812
944
  type: "ip",
813
- value: w(t.value)
945
+ value: E(t.value)
814
946
  };
815
947
  case 164: return {
816
948
  type: "directoryName",
@@ -901,11 +1033,11 @@ function parseNameConstraintGeneralName(e, t) {
901
1033
  };
902
1034
  case 129: return {
903
1035
  type: "email",
904
- value: j.decode(t.value)
1036
+ value: N.decode(t.value)
905
1037
  };
906
1038
  case 130: return {
907
1039
  type: "dns",
908
- value: j.decode(t.value)
1040
+ value: N.decode(t.value)
909
1041
  };
910
1042
  case 163: return {
911
1043
  type: "x400Address",
@@ -913,7 +1045,7 @@ function parseNameConstraintGeneralName(e, t) {
913
1045
  };
914
1046
  case 134: return {
915
1047
  type: "uri",
916
- value: j.decode(t.value)
1048
+ value: N.decode(t.value)
917
1049
  };
918
1050
  case 135:
919
1051
  if (t.value.length === 8) return {
@@ -959,7 +1091,7 @@ function parseDisplayText(e) {
959
1091
  switch (e.tag) {
960
1092
  case 12:
961
1093
  case 22:
962
- case 26: return j.decode(e.value);
1094
+ case 26: return N.decode(e.value);
963
1095
  case 30: return decodeBmpString(e.value);
964
1096
  default: throw Error(`Unsupported DisplayText tag: ${e.tag}`);
965
1097
  }
@@ -1047,6 +1179,6 @@ function validateImplicitBitStringContent(e, t) {
1047
1179
  if (i & (1 << n) - 1) throw Error(`${t} BIT STRING must not set padding bits`);
1048
1180
  }
1049
1181
  //#endregion
1050
- export { decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, findExtension, getSubjectPublicKey, getSubjectPublicKeyOrThrow, parseAuthorityInfoAccess, parseAuthorityKeyIdentifier, parseBasicConstraints, parseCertificateChainPem, parseCertificateDer, parseCertificateDerOrThrow, parseCertificateFromSource, parseCertificatePem, parseCertificatePemOrThrow, parseCertificatePolicies, parseCertificateSigningRequestDer, parseCertificateSigningRequestDerOrThrow, parseCertificateSigningRequestPem, parseCertificateSigningRequestPemOrThrow, parseCertificatesFromSource, parseCrlDistributionPoints, parseExtendedKeyUsage, parseInhibitAnyPolicy, parseKeyUsage, parseNameConstraints, parsePolicyConstraints, parsePolicyMappings, parseSubjectAltNames };
1182
+ export { certificateMatchesPrivateKey, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, findExtension, getSubjectPublicKey, getSubjectPublicKeyOrThrow, matchCertificatePrivateKey, parseAuthorityInfoAccess, parseAuthorityKeyIdentifier, parseBasicConstraints, parseCertificateChainPem, parseCertificateDer, parseCertificateDerOrThrow, parseCertificateFromSource, parseCertificatePem, parseCertificatePemOrThrow, parseCertificatePolicies, parseCertificateSigningRequestDer, parseCertificateSigningRequestDerOrThrow, parseCertificateSigningRequestPem, parseCertificateSigningRequestPemOrThrow, parseCertificatesFromSource, parseCrlDistributionPoints, parseDistinguishedNameDer, parseExtendedKeyUsage, parseInhibitAnyPolicy, parseKeyUsage, parseNameConstraints, parsePolicyConstraints, parsePolicyMappings, parseSubjectAltNames };
1051
1183
 
1052
1184
  //# sourceMappingURL=parse.js.map