micro509 0.10.0 → 0.11.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,
@@ -241,10 +241,10 @@ function parseCertificateSigningRequestDerOrThrow(e, t) {
241
241
  signatureValue: u(o),
242
242
  subject: parseName(e, s.subject),
243
243
  signatureAlgorithmOid: d.oid,
244
- signatureAlgorithmName: C(d.oid, d.parametersDer),
244
+ signatureAlgorithmName: T(d.oid, d.parametersDer),
245
245
  ...d.parametersDer === void 0 ? {} : { signatureAlgorithmParametersDer: d.parametersDer },
246
246
  publicKeyAlgorithmOid: l.oid,
247
- publicKeyAlgorithmName: S(l.oid, l.parametersOid),
247
+ publicKeyAlgorithmName: w(l.oid, l.parametersOid),
248
248
  ...l.parametersDer === void 0 ? {} : { publicKeyAlgorithmParametersDer: l.parametersDer },
249
249
  ...l.parametersOid === void 0 ? {} : { publicKeyParametersOid: l.parametersOid },
250
250
  requestedExtensions: c.all,
@@ -349,7 +349,7 @@ function parseCertificateSigningRequestPem(e, t) {
349
349
  * @see {@linkcode getSubjectPublicKey} for the non-throwing variant
350
350
  */
351
351
  function getSubjectPublicKeyOrThrow(e, t) {
352
- return x(e.subjectPublicKeyInfoDer, t);
352
+ return C(e.subjectPublicKeyInfoDer, t);
353
353
  }
354
354
  /**
355
355
  * Import the subject public key of a parsed certificate or CSR as a WebCrypto `CryptoKey`.
@@ -357,7 +357,130 @@ function getSubjectPublicKeyOrThrow(e, t) {
357
357
  * @see `getSubjectPublicKeyOrThrow` for the throwing variant
358
358
  */
359
359
  function getSubjectPublicKey(e, t) {
360
- return b(e.subjectPublicKeyInfoDer, t);
360
+ return S(e.subjectPublicKeyInfoDer, t);
361
+ }
362
+ /** Extract the AlgorithmIdentifier TLV from a SubjectPublicKeyInfo DER buffer. */
363
+ function subjectPublicKeyInfoAlgorithmDer(e) {
364
+ let t = f(r(e, { maxDepth: 64 })[0], "SubjectPublicKeyInfo algorithm");
365
+ return e.slice(t.start - t.headerLength, t.end);
366
+ }
367
+ /**
368
+ * Derive the public half of `privateKey`, export it as SPKI DER, and classify
369
+ * how it relates to a certificate's SubjectPublicKeyInfo. Single source of truth
370
+ * for {@linkcode certificateMatchesPrivateKey} and {@linkcode matchCertificatePrivateKey}.
371
+ *
372
+ * Equal SPKI bytes mean the key owns the certificate. When they differ, the
373
+ * AlgorithmIdentifier portions decide whether it is a same-algorithm key
374
+ * mismatch or a cross-algorithm (`key_type_mismatch`) one.
375
+ */
376
+ async function compareCertificateToPrivateKey(e, t) {
377
+ let n = await x(await b(t));
378
+ return optionalBytesEqual(n, e) ? "match" : optionalBytesEqual(subjectPublicKeyInfoAlgorithmDer(n), subjectPublicKeyInfoAlgorithmDer(e)) ? "key_mismatch" : "key_type_mismatch";
379
+ }
380
+ /**
381
+ * Check whether a certificate's subject public key belongs to a private key.
382
+ *
383
+ * Confirming that an uploaded private key actually matches the certificate it
384
+ * was submitted with is the first thing a key-intake or issuance endpoint must
385
+ * do. This derives the public half of `privateKey`, exports it as
386
+ * SubjectPublicKeyInfo DER, and compares those bytes against the certificate's
387
+ * own SubjectPublicKeyInfo — the canonical, algorithm-agnostic way to test key
388
+ * ownership. (Comparing JWKs field by field, or signing a probe and verifying
389
+ * it, are both more fragile.)
390
+ *
391
+ * A private key of a different type — e.g. an ECDSA key against an RSA
392
+ * certificate — simply produces different SPKI DER and returns `false`, so
393
+ * callers get a single boolean without branching on the kind of mismatch. Reach
394
+ * for {@linkcode matchCertificatePrivateKey} when you need the reason a match
395
+ * failed (or a typed failure instead of a thrown error) at a trust boundary.
396
+ *
397
+ * The comparison is over the exact DER encoding. A certificate whose
398
+ * SubjectPublicKeyInfo pins RSASSA-PSS parameters (rather than the plain
399
+ * `rsaEncryption` OID that WebCrypto emits) therefore will not match even for
400
+ * the same modulus; such certificates are rare in practice.
401
+ *
402
+ * @param certificate PEM string, DER bytes, or an already-parsed certificate.
403
+ * @param privateKey An extractable private `CryptoKey`.
404
+ * @returns `true` when the private key's public half matches the certificate's
405
+ * subject public key.
406
+ *
407
+ * @throws {Error} If `certificate` is malformed, or `privateKey` is not an
408
+ * extractable private key of a supported type (propagated from
409
+ * {@linkcode derivePublicKey}). Use {@linkcode matchCertificatePrivateKey} for a
410
+ * typed `Result` instead of thrown errors.
411
+ *
412
+ * @example
413
+ * ```ts
414
+ * const privateKey = await importPkcs8PemOrThrow(keyPem, { kind: 'ecdsa', curve: 'P-256' });
415
+ * if (!(await certificateMatchesPrivateKey(certificatePem, privateKey))) {
416
+ * throw new Error('uploaded key does not match the certificate');
417
+ * }
418
+ * ```
419
+ *
420
+ * @see {@linkcode matchCertificatePrivateKey} for the typed-`Result` variant with a mismatch reason
421
+ * @see {@linkcode getSubjectPublicKeyOrThrow} to obtain the certificate's public key directly
422
+ * @see {@linkcode derivePublicKey} for the private-to-public bridge this builds on
423
+ */
424
+ async function certificateMatchesPrivateKey(e, t) {
425
+ return await compareCertificateToPrivateKey(parseCertificateFromSource(e).subjectPublicKeyInfoDer, t) === "match";
426
+ }
427
+ /**
428
+ * Check whether a certificate's subject public key belongs to a private key,
429
+ * returning a typed {@linkcode MatchCertificatePrivateKeyResult}.
430
+ *
431
+ * The `Result`-returning companion to {@linkcode certificateMatchesPrivateKey}:
432
+ * where the boolean helper answers only "does it match?" (and throws on bad
433
+ * input), this surfaces the expected failures a key-intake or issuance endpoint
434
+ * meets on untrusted input as typed codes rather than exceptions — matching the
435
+ * house rule of returning `Result` for expected failures and throwing only for
436
+ * invariants. `ok: true` means the key owns the certificate; a failure carries
437
+ * one of:
438
+ *
439
+ * - `malformed_certificate` — `certificate` could not be parsed.
440
+ * - `unsupported_private_key` — `privateKey` is not an extractable private key
441
+ * of a supported type (from {@linkcode derivePublicKey}).
442
+ * - `key_type_mismatch` — the key is a different algorithm than the
443
+ * certificate's subject public key.
444
+ * - `key_mismatch` — the key is the right algorithm but a different key.
445
+ *
446
+ * As with {@linkcode certificateMatchesPrivateKey}, the comparison is over exact
447
+ * SPKI DER, so a certificate pinning RSASSA-PSS parameters reports
448
+ * `key_type_mismatch` against the `rsaEncryption` SPKI WebCrypto emits.
449
+ *
450
+ * @param certificate PEM string, DER bytes, or an already-parsed certificate.
451
+ * @param privateKey An extractable private `CryptoKey`.
452
+ * @returns A success when the key matches, or a typed failure otherwise.
453
+ *
454
+ * @example
455
+ * ```ts
456
+ * const result = await matchCertificatePrivateKey(certificatePem, privateKey);
457
+ * if (!result.ok) {
458
+ * // result.code is 'malformed_certificate' | 'unsupported_private_key'
459
+ * // | 'key_type_mismatch' | 'key_mismatch'
460
+ * throw new Error(`key does not match certificate: ${result.code}`);
461
+ * }
462
+ * ```
463
+ *
464
+ * @see {@linkcode certificateMatchesPrivateKey} for the plain-boolean variant
465
+ */
466
+ async function matchCertificatePrivateKey(e, t) {
467
+ let n;
468
+ try {
469
+ n = parseCertificateFromSource(e);
470
+ } catch (e) {
471
+ return g(e), h("malformed_certificate", e instanceof Error ? e.message : "Malformed certificate");
472
+ }
473
+ let r;
474
+ try {
475
+ r = await compareCertificateToPrivateKey(n.subjectPublicKeyInfoDer, t);
476
+ } catch (e) {
477
+ return g(e), h("unsupported_private_key", e instanceof Error ? e.message : "Unsupported private key");
478
+ }
479
+ switch (r) {
480
+ case "match": return _(void 0);
481
+ case "key_mismatch": return h("key_mismatch", "Private key does not match the certificate's subject public key");
482
+ case "key_type_mismatch": return h("key_type_mismatch", "Private key algorithm does not match the certificate's subject public key algorithm");
483
+ }
361
484
  }
362
485
  /**
363
486
  * Find a raw extension by OID within a parsed extension list.
@@ -461,7 +584,7 @@ function parseExtensionSequence(e, t, n) {
461
584
  critical: m,
462
585
  valueDer: new Uint8Array(g.value),
463
586
  valueHex: p(g.value)
464
- }), A(n, u, o, g.value);
587
+ }), M(n, u, o, g.value);
465
588
  }
466
589
  return {
467
590
  all: r,
@@ -491,7 +614,7 @@ function parseRelativeDistinguishedName(e, t) {
491
614
  function parseNameAttributeSet(e, t) {
492
615
  let n = [], r = {};
493
616
  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 ? {
617
+ 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
618
  oid: o,
496
619
  valueTag: s.tag,
497
620
  value: d
@@ -579,11 +702,11 @@ function parseBasicConstraints(e) {
579
702
  }
580
703
  /** @internal Decode the Key Usage BIT STRING extension value. */
581
704
  function parseKeyUsage(e) {
582
- return E(e);
705
+ return O(e);
583
706
  }
584
707
  /** @internal Decode the Extended Key Usage SEQUENCE OF OIDs. */
585
708
  function parseExtendedKeyUsage(e) {
586
- return i(e, f(n(e, { maxDepth: 64 }), "extendedKeyUsage sequence")).map((e) => k(c(e.value)));
709
+ return i(e, f(n(e, { maxDepth: 64 }), "extendedKeyUsage sequence")).map((e) => j(c(e.value)));
587
710
  }
588
711
  /** @internal Decode the Certificate Policies extension value. */
589
712
  function parseCertificatePolicies(e) {
@@ -720,8 +843,8 @@ function parseAuthorityInfoAccess(e) {
720
843
  if (r.tag !== 6) throw Error("authorityInfoAccess method must use OBJECT IDENTIFIER");
721
844
  if (a.tag !== 134) throw Error(`Unsupported authorityInfoAccess location tag: ${a.tag}`);
722
845
  return {
723
- method: O(c(r.value)),
724
- uri: j.decode(a.value)
846
+ method: A(c(r.value)),
847
+ uri: N.decode(a.value)
725
848
  };
726
849
  });
727
850
  }
@@ -755,7 +878,7 @@ function parseDistributionPointField(e, t, n) {
755
878
  return;
756
879
  case 129:
757
880
  if (n.reasons !== void 0) throw Error("DistributionPoint reasons must not repeat");
758
- n.reasons = T(t.value);
881
+ n.reasons = D(t.value);
759
882
  return;
760
883
  case 162:
761
884
  if (n.crlIssuer !== void 0) throw Error("DistributionPoint crlIssuer must not repeat");
@@ -798,19 +921,19 @@ function parseGeneralName(e, t) {
798
921
  }
799
922
  case 129: return {
800
923
  type: "email",
801
- value: j.decode(t.value)
924
+ value: N.decode(t.value)
802
925
  };
803
926
  case 130: return {
804
927
  type: "dns",
805
- value: j.decode(t.value)
928
+ value: N.decode(t.value)
806
929
  };
807
930
  case 134: return {
808
931
  type: "uri",
809
- value: j.decode(t.value)
932
+ value: N.decode(t.value)
810
933
  };
811
934
  case 135: return {
812
935
  type: "ip",
813
- value: w(t.value)
936
+ value: E(t.value)
814
937
  };
815
938
  case 164: return {
816
939
  type: "directoryName",
@@ -901,11 +1024,11 @@ function parseNameConstraintGeneralName(e, t) {
901
1024
  };
902
1025
  case 129: return {
903
1026
  type: "email",
904
- value: j.decode(t.value)
1027
+ value: N.decode(t.value)
905
1028
  };
906
1029
  case 130: return {
907
1030
  type: "dns",
908
- value: j.decode(t.value)
1031
+ value: N.decode(t.value)
909
1032
  };
910
1033
  case 163: return {
911
1034
  type: "x400Address",
@@ -913,7 +1036,7 @@ function parseNameConstraintGeneralName(e, t) {
913
1036
  };
914
1037
  case 134: return {
915
1038
  type: "uri",
916
- value: j.decode(t.value)
1039
+ value: N.decode(t.value)
917
1040
  };
918
1041
  case 135:
919
1042
  if (t.value.length === 8) return {
@@ -959,7 +1082,7 @@ function parseDisplayText(e) {
959
1082
  switch (e.tag) {
960
1083
  case 12:
961
1084
  case 22:
962
- case 26: return j.decode(e.value);
1085
+ case 26: return N.decode(e.value);
963
1086
  case 30: return decodeBmpString(e.value);
964
1087
  default: throw Error(`Unsupported DisplayText tag: ${e.tag}`);
965
1088
  }
@@ -1047,6 +1170,6 @@ function validateImplicitBitStringContent(e, t) {
1047
1170
  if (i & (1 << n) - 1) throw Error(`${t} BIT STRING must not set padding bits`);
1048
1171
  }
1049
1172
  //#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 };
1173
+ 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, parseExtendedKeyUsage, parseInhibitAnyPolicy, parseKeyUsage, parseNameConstraints, parsePolicyConstraints, parsePolicyMappings, parseSubjectAltNames };
1051
1174
 
1052
1175
  //# sourceMappingURL=parse.js.map