micro509 0.12.0 → 0.14.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 (123) hide show
  1. package/README.md +78 -30
  2. package/dist/crypto/crypto.d.ts +73 -0
  3. package/dist/crypto/crypto.js +74 -0
  4. package/dist/crypto/crypto.js.map +1 -0
  5. package/dist/crypto.d.ts +4 -0
  6. package/dist/crypto.js +2 -0
  7. package/dist/der/der.d.ts +127 -0
  8. package/dist/der/der.js +171 -0
  9. package/dist/der/der.js.map +1 -0
  10. package/dist/der.d.ts +4 -0
  11. package/dist/der.js +4 -0
  12. package/dist/index.d.ts +13 -9
  13. package/dist/index.js +17 -15
  14. package/dist/internal/asn1/asn1.d.ts +20 -0
  15. package/dist/internal/asn1/asn1.js +80 -37
  16. package/dist/internal/asn1/asn1.js.map +1 -1
  17. package/dist/internal/asn1/der.d.ts +173 -0
  18. package/dist/internal/asn1/der.js +116 -38
  19. package/dist/internal/asn1/der.js.map +1 -1
  20. package/dist/internal/asn1/oids.js +7 -1
  21. package/dist/internal/asn1/oids2.js +9 -2
  22. package/dist/internal/asn1/oids2.js.map +1 -1
  23. package/dist/internal/crypto/algorithm-names.js +4 -0
  24. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  25. package/dist/internal/crypto/pbes2.d.ts +38 -0
  26. package/dist/internal/crypto/pbes2.js +9 -10
  27. package/dist/internal/crypto/pbes2.js.map +1 -1
  28. package/dist/internal/crypto/rsa-pss.js +2 -0
  29. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  30. package/dist/internal/crypto/sig-verify.d.ts +31 -0
  31. package/dist/internal/crypto/sig-verify.js +10 -8
  32. package/dist/internal/crypto/sig-verify.js.map +1 -1
  33. package/dist/internal/shared/base64.js +7 -1
  34. package/dist/internal/shared/base64.js.map +1 -1
  35. package/dist/internal/shared/dn.d.ts +16 -0
  36. package/dist/internal/shared/dn.js +149 -12
  37. package/dist/internal/shared/dn.js.map +1 -1
  38. package/dist/internal/shared/ip.d.ts +69 -0
  39. package/dist/internal/shared/ip.js +18 -1
  40. package/dist/internal/shared/ip.js.map +1 -1
  41. package/dist/internal/shared/rfc3454-tables.js +1782 -0
  42. package/dist/internal/shared/rfc3454-tables.js.map +1 -0
  43. package/dist/internal/verify/name-constraints-engine.js +47 -15
  44. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  45. package/dist/internal/verify/policy-engine.js +85 -94
  46. package/dist/internal/verify/policy-engine.js.map +1 -1
  47. package/dist/internal/verify/verify-path.d.ts +7 -0
  48. package/dist/internal/verify/verify-path.js +49 -45
  49. package/dist/internal/verify/verify-path.js.map +1 -1
  50. package/dist/internal/x509/directory-name.js +24 -0
  51. package/dist/internal/x509/directory-name.js.map +1 -0
  52. package/dist/internal/x509/extension-bits.js +14 -11
  53. package/dist/internal/x509/extension-bits.js.map +1 -1
  54. package/dist/internal/x509/extension-errors.d.ts +6 -0
  55. package/dist/internal/x509/extension-errors.js +20 -0
  56. package/dist/internal/x509/extension-errors.js.map +1 -0
  57. package/dist/internal/x509/extension-registry.js +113 -55
  58. package/dist/internal/x509/extension-registry.js.map +1 -1
  59. package/dist/internal/x509/general-name-tags.js +28 -0
  60. package/dist/internal/x509/general-name-tags.js.map +1 -0
  61. package/dist/internal/x509/general-name.js +97 -0
  62. package/dist/internal/x509/general-name.js.map +1 -0
  63. package/dist/internal/x509/name-fields.js +20 -10
  64. package/dist/internal/x509/name-fields.js.map +1 -1
  65. package/dist/keys/keys.d.ts +16 -2
  66. package/dist/keys/keys.js +311 -170
  67. package/dist/keys/keys.js.map +1 -1
  68. package/dist/keys.d.ts +3 -2
  69. package/dist/keys.js +3 -2
  70. package/dist/pem/pem.d.ts +3 -2
  71. package/dist/pem/pem.js +112 -30
  72. package/dist/pem/pem.js.map +1 -1
  73. package/dist/pkcs/pkcs12-mac.js +3 -3
  74. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  75. package/dist/pkcs/pkcs7.d.ts +85 -21
  76. package/dist/pkcs/pkcs7.js +261 -186
  77. package/dist/pkcs/pkcs7.js.map +1 -1
  78. package/dist/pkcs.d.ts +2 -2
  79. package/dist/result/result.d.ts +18 -10
  80. package/dist/result/result.js +20 -12
  81. package/dist/result/result.js.map +1 -1
  82. package/dist/result.d.ts +2 -2
  83. package/dist/result.js +2 -2
  84. package/dist/revocation/chain.js +154 -103
  85. package/dist/revocation/chain.js.map +1 -1
  86. package/dist/revocation/crl.d.ts +13 -2
  87. package/dist/revocation/crl.js +415 -236
  88. package/dist/revocation/crl.js.map +1 -1
  89. package/dist/revocation/ocsp.d.ts +58 -17
  90. package/dist/revocation/ocsp.js +186 -174
  91. package/dist/revocation/ocsp.js.map +1 -1
  92. package/dist/revocation/revocation.d.ts +4 -4
  93. package/dist/revocation/revocation.js +48 -30
  94. package/dist/revocation/revocation.js.map +1 -1
  95. package/dist/revocation.d.ts +4 -4
  96. package/dist/revocation.js +5 -5
  97. package/dist/verify/identity.d.ts +2 -1
  98. package/dist/verify/identity.js +2 -1
  99. package/dist/verify/identity.js.map +1 -1
  100. package/dist/verify/policy.d.ts +6 -1
  101. package/dist/verify/verify.d.ts +18 -3
  102. package/dist/verify/verify.js +66 -41
  103. package/dist/verify/verify.js.map +1 -1
  104. package/dist/verify.d.ts +2 -1
  105. package/dist/verify.js +4 -3
  106. package/dist/x509/certificate.d.ts +36 -13
  107. package/dist/x509/certificate.js +36 -19
  108. package/dist/x509/certificate.js.map +1 -1
  109. package/dist/x509/csr.d.ts +6 -3
  110. package/dist/x509/extensions.d.ts +59 -22
  111. package/dist/x509/extensions.js +384 -117
  112. package/dist/x509/extensions.js.map +1 -1
  113. package/dist/x509/name-text.js +2 -0
  114. package/dist/x509/name-text.js.map +1 -1
  115. package/dist/x509/name.d.ts +8 -5
  116. package/dist/x509/name.js +17 -12
  117. package/dist/x509/name.js.map +1 -1
  118. package/dist/x509/parse.d.ts +104 -18
  119. package/dist/x509/parse.js +127 -163
  120. package/dist/x509/parse.js.map +1 -1
  121. package/dist/x509.d.ts +8 -5
  122. package/dist/x509.js +10 -8
  123. package/package.json +52 -34
@@ -1,11 +1,12 @@
1
1
  import { bitString as e, explicitContext as t, integer as n, integerFromNumber as r, sequence as i, time as a } from "../internal/asn1/der.js";
2
2
  import { getCrypto as o } from "../internal/crypto/webcrypto.js";
3
3
  import { base64Encode as s } from "../internal/shared/base64.js";
4
- import { pemEncode as c } from "../pem/pem.js";
5
- import { exportSpkiDer as l, generateKeyPair as u } from "../keys/keys.js";
6
- import { encodeName as d, isNameInputEmpty as f } from "./name.js";
7
- import { buildCertificateExtensions as p } from "./extensions.js";
8
- import { encodeAlgorithmIdentifier as m, getSignatureAlgorithm as h, signBytes as g } from "../internal/crypto/signing.js";
4
+ import { throwMicro509Error as c } from "../result/result.js";
5
+ import { pemEncode as l } from "../pem/pem.js";
6
+ import { exportSpkiDer as u, generateKeyPair as d } from "../keys/keys.js";
7
+ import { encodeName as f, isNameInputEmpty as p } from "./name.js";
8
+ import { buildCertificateExtensions as m } from "./extensions.js";
9
+ import { encodeAlgorithmIdentifier as h, getSignatureAlgorithm as g, signBytes as _ } from "../internal/crypto/signing.js";
9
10
  //#region src/x509/certificate.ts
10
11
  /**
11
12
  * Create X.509 certificates from typed names, extensions, and WebCrypto keys.
@@ -34,7 +35,7 @@ import { encodeAlgorithmIdentifier as m, getSignatureAlgorithm as h, signBytes a
34
35
  * @returns The certificate plus the key pair used to sign it.
35
36
  */
36
37
  async function createSelfSignedCertificate(e) {
37
- let t = e.keyPair ?? await u(e.algorithm);
38
+ let t = e.keyPair ?? await d(e.algorithm);
38
39
  return {
39
40
  certificate: await createCertificate({
40
41
  issuer: e.subject,
@@ -72,20 +73,22 @@ async function createSelfSignedCertificate(e) {
72
73
  * @param input Issuer, subject, key, validity, and extension settings.
73
74
  * @returns The encoded certificate material.
74
75
  */
75
- async function createCertificate(o) {
76
- let s = await l(o.publicKey), c = o.issuerPublicKey ? await l(o.issuerPublicKey) : void 0, u = h(o.signerPrivateKey, o.signature), _ = resolveValidity(o.validity), v = f(o.subject), y = p(s, c, o.extensions, v), b = i([
76
+ async function createCertificate(n) {
77
+ let o = await u(n.publicKey), s = n.issuerPublicKey ? await u(n.issuerPublicKey) : void 0, l = g(n.signerPrivateKey, n.signature), d = resolveValidity(n.validity);
78
+ p(n.issuer) && c("issuer_distinguished_name_empty", "issuer must be a non-empty distinguished name");
79
+ let v = p(n.subject), y = m(o, s, n.extensions, v), b = i([
77
80
  t(0, r(2)),
78
- n(o.serialNumber ?? randomSerialNumber()),
79
- m(u),
80
- d(o.issuer),
81
- i([a(_.notBefore), a(_.notAfter)]),
82
- d(o.subject),
83
- s,
81
+ encodeSerialNumber(n.serialNumber),
82
+ h(l),
83
+ f(n.issuer),
84
+ i([a(d.notBefore), a(d.notAfter)]),
85
+ f(n.subject),
86
+ o,
84
87
  t(3, i(y))
85
- ]), x = await g(o.signerPrivateKey, u, b);
88
+ ]), x = await _(n.signerPrivateKey, l, b);
86
89
  return materializeCertificate(i([
87
90
  b,
88
- m(u),
91
+ h(l),
89
92
  e(x)
90
93
  ]));
91
94
  }
@@ -98,7 +101,7 @@ async function createCertificate(o) {
98
101
  function materializeCertificate(e) {
99
102
  return {
100
103
  der: e,
101
- pem: c("CERTIFICATE", e),
104
+ pem: l("CERTIFICATE", e),
102
105
  base64: s(e)
103
106
  };
104
107
  }
@@ -110,8 +113,7 @@ function materializeCertificate(e) {
110
113
  */
111
114
  function resolveValidity(e) {
112
115
  let t = e?.notBefore ?? /* @__PURE__ */ new Date(), n = e?.notAfter ?? addDays(t, e?.days ?? 30);
113
- if (n.getTime() <= t.getTime()) throw Error("notAfter must be after notBefore");
114
- return {
116
+ return n.getTime() <= t.getTime() && c("validity_not_after_before_not_before", "notAfter must be after notBefore"), {
115
117
  notBefore: t,
116
118
  notAfter: n
117
119
  };
@@ -128,6 +130,21 @@ function addDays(e, t) {
128
130
  return n.setUTCDate(n.getUTCDate() + t), n;
129
131
  }
130
132
  /**
133
+ * Encode a certificate serial number as a DER INTEGER.
134
+ *
135
+ * @param serialNumber Serial number bytes, big-endian; a random one is generated when omitted.
136
+ * @returns The DER INTEGER element.
137
+ * @throws a `ResultError` with code `serial_number_not_positive` or
138
+ * `serial_number_too_long` when RFC 5280 §4.1.2.2 forbids the value.
139
+ */
140
+ function encodeSerialNumber(e) {
141
+ if (e === void 0) return n(randomSerialNumber());
142
+ let t = 0;
143
+ for (; t < e.length && e[t] === 0;) t += 1;
144
+ let r = e.subarray(t), i = r[0];
145
+ return i === void 0 && c("serial_number_not_positive", "serialNumber must be a positive integer"), r.length + +(i >= 128) > 20 && c("serial_number_too_long", "serialNumber must not exceed 20 octets"), n(r);
146
+ }
147
+ /**
131
148
  * Generate a random positive serial number suitable for certificate issuance.
132
149
  *
133
150
  * @returns A 16-byte positive serial number.
@@ -1 +1 @@
1
- {"version":3,"file":"certificate.js","names":[],"sources":["../../src/x509/certificate.ts"],"sourcesContent":["/**\n * Create X.509 certificates from typed names, extensions, and WebCrypto keys.\n *\n * Use this module to issue a certificate from an existing issuer key pair or to\n * generate a self-signed certificate in one step.\n *\n * @module\n */\n\nimport {\n\tbitString,\n\texplicitContext,\n\tinteger,\n\tintegerFromNumber,\n\tsequence,\n\ttime,\n} from '#micro509/internal/asn1/der';\nimport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\n\nexport type { SignatureProfileInput };\n\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport type { KeyAlgorithmInput, KeyPairMaterial } from '#micro509/keys/keys';\nimport { exportSpkiDer, generateKeyPair } from '#micro509/keys/keys';\nimport { pemEncode } from '#micro509/pem/pem';\nimport type { CertificateExtensionsInput } from '#micro509/x509/extensions';\nimport { buildCertificateExtensions } from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName, isNameInputEmpty } from '#micro509/x509/name';\n\nexport type * from '#micro509/x509/extensions';\nexport type * from '#micro509/x509/name';\n\n/**\n * Configures the certificate validity window.\n *\n * If `notAfter` is omitted, it is derived from `notBefore` plus `days`. If both\n * `notAfter` and `days` are omitted, the certificate is valid for 30 days.\n */\nexport interface ValidityInput {\n\t/**\n\t * Start of the validity window.\n\t *\n\t * Defaults to the current time.\n\t */\n\treadonly notBefore?: Date;\n\t/**\n\t * End of the validity window.\n\t *\n\t * Must be later than `notBefore`.\n\t */\n\treadonly notAfter?: Date;\n\t/**\n\t * Number of days to add to `notBefore` when `notAfter` is omitted.\n\t */\n\treadonly days?: number;\n}\n\n/**\n * Input for {@linkcode createCertificate}.\n */\nexport interface CreateCertificateInput {\n\t/**\n\t * Issuer distinguished name.\n\t */\n\treadonly issuer: NameInput;\n\t/**\n\t * Subject distinguished name.\n\t */\n\treadonly subject: NameInput;\n\t/**\n\t * Subject public key to encode into the certificate.\n\t */\n\treadonly publicKey: CryptoKey;\n\t/**\n\t * Private key used to sign the certificate.\n\t */\n\treadonly signerPrivateKey: CryptoKey;\n\t/**\n\t * Issuer public key.\n\t *\n\t * Provide this when extension builders need issuer key material, such as\n\t * authority key identifier derivation.\n\t */\n\treadonly issuerPublicKey?: CryptoKey;\n\t/**\n\t * Validity window configuration.\n\t */\n\treadonly validity?: ValidityInput;\n\t/**\n\t * DER integer bytes for the certificate serial number.\n\t *\n\t * When omitted, a random positive 16-byte serial number is generated.\n\t */\n\treadonly serialNumber?: Uint8Array;\n\t/**\n\t * X.509 extensions to encode into the certificate.\n\t */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/**\n\t * Signature algorithm override.\n\t *\n\t * When omitted, the library selects a compatible profile from the signing\n\t * key.\n\t */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/**\n * Input for {@linkcode createSelfSignedCertificate}.\n */\nexport interface CreateSelfSignedCertificateInput {\n\t/**\n\t * Subject distinguished name used as both subject and issuer.\n\t */\n\treadonly subject: NameInput;\n\t/**\n\t * Key generation parameters.\n\t *\n\t * Ignored when `keyPair` is provided.\n\t */\n\treadonly algorithm?: KeyAlgorithmInput;\n\t/**\n\t * Existing key pair to reuse for both subject and issuer.\n\t *\n\t * When omitted, a new key pair is generated.\n\t */\n\treadonly keyPair?: KeyPairMaterial;\n\t/**\n\t * Validity window configuration.\n\t */\n\treadonly validity?: ValidityInput;\n\t/**\n\t * DER integer bytes for the certificate serial number.\n\t */\n\treadonly serialNumber?: Uint8Array;\n\t/**\n\t * X.509 extensions to encode into the certificate.\n\t */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/**\n\t * Signature algorithm override.\n\t */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/**\n * Encoded certificate material in common interchange formats.\n */\nexport interface CertificateMaterial {\n\t/**\n\t * DER-encoded certificate bytes.\n\t */\n\treadonly der: Uint8Array;\n\t/**\n\t * PEM-encoded certificate.\n\t */\n\treadonly pem: string;\n\t/**\n\t * Base64 encoding of {@linkcode der} without PEM armor.\n\t */\n\treadonly base64: string;\n}\n\n/**\n * Result returned by {@linkcode createSelfSignedCertificate}.\n */\nexport interface SelfSignedCertificateResult {\n\t/**\n\t * Encoded certificate outputs.\n\t */\n\treadonly certificate: CertificateMaterial;\n\t/**\n\t * Key pair used to issue the certificate.\n\t */\n\treadonly keyPair: KeyPairMaterial;\n}\n\n/**\n * Create a self-signed certificate.\n *\n * Reuses `input.keyPair` when provided; otherwise generates a new key pair from\n * `input.algorithm`. The returned certificate uses `input.subject` as both\n * issuer and subject.\n *\n * @example\n * ```ts\n * const { certificate, keyPair } = await createSelfSignedCertificate({\n * \tsubject: { commonName: 'example.com' },\n * \talgorithm: { kind: 'ecdsa', curve: 'P-256' },\n * });\n * ```\n *\n * @param input Certificate subject, key, validity, and extension settings.\n * @returns The certificate plus the key pair used to sign it.\n */\nexport async function createSelfSignedCertificate(\n\tinput: CreateSelfSignedCertificateInput,\n): Promise<SelfSignedCertificateResult> {\n\tconst keyPair = input.keyPair ?? (await generateKeyPair(input.algorithm));\n\tconst certificateInput = {\n\t\tissuer: input.subject,\n\t\tsubject: input.subject,\n\t\tpublicKey: keyPair.publicKey,\n\t\tsignerPrivateKey: keyPair.privateKey,\n\t\tissuerPublicKey: keyPair.publicKey,\n\t\t...(input.validity !== undefined ? { validity: input.validity } : {}),\n\t\t...(input.serialNumber !== undefined ? { serialNumber: input.serialNumber } : {}),\n\t\t...(input.extensions !== undefined ? { extensions: input.extensions } : {}),\n\t\t...(input.signature !== undefined ? { signature: input.signature } : {}),\n\t} satisfies CreateCertificateInput;\n\tconst certificate = await createCertificate(certificateInput);\n\n\treturn { certificate, keyPair };\n}\n\n/**\n * Create an X.509 certificate signed by `input.signerPrivateKey`.\n *\n * The certificate encodes `input.subject`, `input.publicKey`, and any supplied\n * extensions. When `serialNumber` is omitted, a random positive serial number is\n * generated. When `validity` is omitted, the certificate is valid from now for\n * 30 days.\n *\n * @example\n * ```ts\n * const certificate = await createCertificate({\n * \tissuer: { commonName: 'Example Root CA' },\n * \tsubject: { commonName: 'example.com' },\n * \tpublicKey: leafKeys.publicKey,\n * \tsignerPrivateKey: issuerKeys.privateKey,\n * \tissuerPublicKey: issuerKeys.publicKey,\n * });\n * ```\n *\n * @param input Issuer, subject, key, validity, and extension settings.\n * @returns The encoded certificate material.\n */\nexport async function createCertificate(\n\tinput: CreateCertificateInput,\n): Promise<CertificateMaterial> {\n\tconst subjectPublicKeyInfo = await exportSpkiDer(input.publicKey);\n\tconst issuerPublicKeyInfo = input.issuerPublicKey\n\t\t? await exportSpkiDer(input.issuerPublicKey)\n\t\t: undefined;\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey, input.signature);\n\tconst validity = resolveValidity(input.validity);\n\tconst subjectIsEmpty = isNameInputEmpty(input.subject);\n\tconst extensions = buildCertificateExtensions(\n\t\tsubjectPublicKeyInfo,\n\t\tissuerPublicKeyInfo,\n\t\tinput.extensions,\n\t\tsubjectIsEmpty,\n\t);\n\tconst tbsCertificate = sequence([\n\t\texplicitContext(0, integerFromNumber(2)),\n\t\tinteger(input.serialNumber ?? randomSerialNumber()),\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tencodeName(input.issuer),\n\t\tsequence([time(validity.notBefore), time(validity.notAfter)]),\n\t\tencodeName(input.subject),\n\t\tsubjectPublicKeyInfo,\n\t\texplicitContext(3, sequence(extensions)),\n\t]);\n\n\tconst signatureValue = await signBytes(\n\t\tinput.signerPrivateKey,\n\t\tsignatureAlgorithm,\n\t\ttbsCertificate,\n\t);\n\tconst certificateDer = sequence([\n\t\ttbsCertificate,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(signatureValue),\n\t]);\n\n\treturn materializeCertificate(certificateDer);\n}\n\n/**\n * Convert DER bytes into all exported certificate encodings.\n *\n * @param der DER-encoded certificate bytes.\n * @returns DER, PEM, and base64 views of the same certificate.\n */\nfunction materializeCertificate(der: Uint8Array): CertificateMaterial {\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('CERTIFICATE', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/**\n * Normalized validity window used during certificate creation.\n */\ninterface ResolvedValidity {\n\t/**\n\t * Start of the validity window.\n\t */\n\treadonly notBefore: Date;\n\t/**\n\t * End of the validity window.\n\t */\n\treadonly notAfter: Date;\n}\n\n/**\n * Resolve defaults for a certificate validity window.\n *\n * @param input Optional validity settings.\n * @returns A concrete `notBefore` and `notAfter` pair.\n */\nfunction resolveValidity(input: ValidityInput | undefined): ResolvedValidity {\n\tconst notBefore = input?.notBefore ?? new Date();\n\tconst notAfter = input?.notAfter ?? addDays(notBefore, input?.days ?? 30);\n\tif (notAfter.getTime() <= notBefore.getTime()) {\n\t\tthrow new Error('notAfter must be after notBefore');\n\t}\n\treturn { notBefore, notAfter };\n}\n\n/**\n * Return a new date offset by a whole number of UTC days.\n *\n * @param date Base date.\n * @param days Number of days to add.\n * @returns The shifted date.\n */\nfunction addDays(date: Date, days: number): Date {\n\tconst out = new Date(date.getTime());\n\tout.setUTCDate(out.getUTCDate() + days);\n\treturn out;\n}\n\n/**\n * Generate a random positive serial number suitable for certificate issuance.\n *\n * @returns A 16-byte positive serial number.\n */\nfunction randomSerialNumber(): Uint8Array {\n\tconst serial = getCrypto().getRandomValues(new Uint8Array(16));\n\tconst first = serial[0] ?? 0;\n\tserial[0] = first & 0x7f;\n\tif ((serial[0] ?? 0) === 0) {\n\t\tserial[0] = 1;\n\t}\n\treturn serial;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,eAAsB,4BACrB,GACuC;CACvC,IAAM,IAAU,EAAM,WAAY,MAAM,EAAgB,EAAM,SAAS;CAcvE,OAAO;EAAE,aAAA,MAFiB,kBAAkB;GAV3C,QAAQ,EAAM;GACd,SAAS,EAAM;GACf,WAAW,EAAQ;GACnB,kBAAkB,EAAQ;GAC1B,iBAAiB,EAAQ;GACzB,GAAI,EAAM,aAAa,KAAA,IAA2C,CAAC,IAAhC,EAAE,UAAU,EAAM,SAAS;GAC9D,GAAI,EAAM,iBAAiB,KAAA,IAAmD,CAAC,IAAxC,EAAE,cAAc,EAAM,aAAa;GAC1E,GAAI,EAAM,eAAe,KAAA,IAA+C,CAAC,IAApC,EAAE,YAAY,EAAM,WAAW;GACpE,GAAI,EAAM,cAAc,KAAA,IAA6C,CAAC,IAAlC,EAAE,WAAW,EAAM,UAAU;EAEP,CAAC;EAEtC;CAAQ;AAC/B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,eAAsB,kBACrB,GAC+B;CAC/B,IAAM,IAAuB,MAAM,EAAc,EAAM,SAAS,GAC1D,IAAsB,EAAM,kBAC/B,MAAM,EAAc,EAAM,eAAe,IACzC,KAAA,GACG,IAAqB,EAAsB,EAAM,kBAAkB,EAAM,SAAS,GAClF,IAAW,gBAAgB,EAAM,QAAQ,GACzC,IAAiB,EAAiB,EAAM,OAAO,GAC/C,IAAa,EAClB,GACA,GACA,EAAM,YACN,CACD,GACM,IAAiB,EAAS;EAC/B,EAAgB,GAAG,EAAkB,CAAC,CAAC;EACvC,EAAQ,EAAM,gBAAgB,mBAAmB,CAAC;EAClD,EAA0B,CAAkB;EAC5C,EAAW,EAAM,MAAM;EACvB,EAAS,CAAC,EAAK,EAAS,SAAS,GAAG,EAAK,EAAS,QAAQ,CAAC,CAAC;EAC5D,EAAW,EAAM,OAAO;EACxB;EACA,EAAgB,GAAG,EAAS,CAAU,CAAC;CACxC,CAAC,GAEK,IAAiB,MAAM,EAC5B,EAAM,kBACN,GACA,CACD;CAOA,OAAO,uBANgB,EAAS;EAC/B;EACA,EAA0B,CAAkB;EAC5C,EAAU,CAAc;CACzB,CAE2C,CAAC;AAC7C;;;;;;;AAQA,SAAS,uBAAuB,GAAsC;CACrE,OAAO;EACN;EACA,KAAK,EAAU,eAAe,CAAG;EACjC,QAAQ,EAAa,CAAG;CACzB;AACD;;;;;;;AAsBA,SAAS,gBAAgB,GAAoD;CAC5E,IAAM,IAAY,GAAO,6BAAa,IAAI,KAAK,GACzC,IAAW,GAAO,YAAY,QAAQ,GAAW,GAAO,QAAQ,EAAE;CACxE,IAAI,EAAS,QAAQ,KAAK,EAAU,QAAQ,GAC3C,MAAU,MAAM,kCAAkC;CAEnD,OAAO;EAAE;EAAW;CAAS;AAC9B;;;;;;;;AASA,SAAS,QAAQ,GAAY,GAAoB;CAChD,IAAM,IAAM,IAAI,KAAK,EAAK,QAAQ,CAAC;CAEnC,OADA,EAAI,WAAW,EAAI,WAAW,IAAI,CAAI,GAC/B;AACR;;;;;;AAOA,SAAS,qBAAiC;CACzC,IAAM,IAAS,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC;CAM7D,OAJA,EAAO,MADO,EAAO,MAAM,KACP,MACf,EAAO,MAAM,OAAO,MACxB,EAAO,KAAK,IAEN;AACR"}
1
+ {"version":3,"file":"certificate.js","names":[],"sources":["../../src/x509/certificate.ts"],"sourcesContent":["/**\n * Create X.509 certificates from typed names, extensions, and WebCrypto keys.\n *\n * Use this module to issue a certificate from an existing issuer key pair or to\n * generate a self-signed certificate in one step.\n *\n * @module\n */\n\nimport {\n\tbitString,\n\texplicitContext,\n\tinteger,\n\tintegerFromNumber,\n\tsequence,\n\ttime,\n} from '#micro509/internal/asn1/der';\nimport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\n\nexport type { SignatureProfileInput };\n\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport type { KeyAlgorithmInput, KeyPairMaterial } from '#micro509/keys/keys';\nimport { exportSpkiDer, generateKeyPair } from '#micro509/keys/keys';\nimport { pemEncode } from '#micro509/pem/pem';\nimport { throwMicro509Error } from '#micro509/result/result';\nimport type { CertificateExtensionsInput } from '#micro509/x509/extensions';\nimport { buildCertificateExtensions } from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName, isNameInputEmpty } from '#micro509/x509/name';\n\nexport type * from '#micro509/x509/extensions';\nexport type * from '#micro509/x509/name';\n\n/** Machine-readable reason a certificate builder rejected its construction input. */\nexport type CreateCertificateErrorCode =\n\t| 'issuer_distinguished_name_empty'\n\t| 'serial_number_not_positive'\n\t| 'serial_number_too_long'\n\t| 'validity_not_after_before_not_before';\n\n/**\n * Configures the certificate validity window.\n *\n * If `notAfter` is omitted, it is derived from `notBefore` plus `days`. If both\n * `notAfter` and `days` are omitted, the certificate is valid for 30 days.\n */\nexport interface ValidityInput {\n\t/**\n\t * Start of the validity window.\n\t *\n\t * Defaults to the current time.\n\t */\n\treadonly notBefore?: Date;\n\t/**\n\t * End of the validity window.\n\t *\n\t * Must be later than `notBefore`.\n\t */\n\treadonly notAfter?: Date;\n\t/**\n\t * Number of days to add to `notBefore` when `notAfter` is omitted.\n\t */\n\treadonly days?: number;\n}\n\n/**\n * Input for {@linkcode createCertificate}.\n */\nexport interface CreateCertificateInput {\n\t/**\n\t * Issuer distinguished name.\n\t */\n\treadonly issuer: NameInput;\n\t/**\n\t * Subject distinguished name.\n\t */\n\treadonly subject: NameInput;\n\t/**\n\t * Subject public key to encode into the certificate.\n\t */\n\treadonly publicKey: CryptoKey;\n\t/**\n\t * Private key used to sign the certificate.\n\t */\n\treadonly signerPrivateKey: CryptoKey;\n\t/**\n\t * Issuer public key.\n\t *\n\t * Provide this when extension builders need issuer key material, such as\n\t * authority key identifier derivation.\n\t */\n\treadonly issuerPublicKey?: CryptoKey;\n\t/**\n\t * Validity window configuration.\n\t */\n\treadonly validity?: ValidityInput;\n\t/**\n\t * DER integer bytes for the certificate serial number.\n\t *\n\t * RFC 5280 §4.1.2.2 requires a positive value of at most 20 octets.\n\t * When omitted, a random positive 16-byte serial number is generated.\n\t */\n\treadonly serialNumber?: Uint8Array;\n\t/**\n\t * X.509 extensions to encode into the certificate.\n\t */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/**\n\t * Signature algorithm override.\n\t *\n\t * When omitted, the library selects a compatible profile from the signing\n\t * key.\n\t */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/**\n * Input for {@linkcode createSelfSignedCertificate}.\n */\nexport type CreateSelfSignedCertificateInput = CreateSelfSignedCertificateBase &\n\tSelfSignedKeySource;\n\n/**\n * Where {@linkcode createSelfSignedCertificate} gets its key pair.\n *\n * Supplying `keyPair` makes `algorithm` unreachable, since generation is skipped.\n */\nexport type SelfSignedKeySource =\n\t| {\n\t\t\t/**\n\t\t\t * Existing key pair to reuse for both subject and issuer.\n\t\t\t */\n\t\t\treadonly keyPair: KeyPairMaterial;\n\t\t\t/**\n\t\t\t * Unavailable in this variant; the supplied `keyPair` is used as-is.\n\t\t\t */\n\t\t\treadonly algorithm?: never;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * Generate a new key pair for both subject and issuer.\n\t\t\t */\n\t\t\treadonly keyPair?: never;\n\t\t\t/**\n\t\t\t * Key generation parameters. Defaults to the {@linkcode generateKeyPair} default.\n\t\t\t */\n\t\t\treadonly algorithm?: KeyAlgorithmInput;\n\t };\n\n/** Fields common to both {@linkcode SelfSignedKeySource} variants. */\nexport interface CreateSelfSignedCertificateBase {\n\t/**\n\t * Subject distinguished name used as both subject and issuer.\n\t */\n\treadonly subject: NameInput;\n\t/**\n\t * Validity window configuration.\n\t */\n\treadonly validity?: ValidityInput;\n\t/**\n\t * DER integer bytes for the certificate serial number.\n\t *\n\t * RFC 5280 §4.1.2.2 requires a positive value of at most 20 octets.\n\t * When omitted, a random positive 16-byte serial number is generated.\n\t */\n\treadonly serialNumber?: Uint8Array;\n\t/**\n\t * X.509 extensions to encode into the certificate.\n\t */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/**\n\t * Signature algorithm override.\n\t */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/**\n * Encoded certificate material in common interchange formats.\n */\nexport interface CertificateMaterial {\n\t/**\n\t * DER-encoded certificate bytes.\n\t */\n\treadonly der: Uint8Array;\n\t/**\n\t * PEM-encoded certificate.\n\t */\n\treadonly pem: string;\n\t/**\n\t * Base64 encoding of {@linkcode der} without PEM armor.\n\t */\n\treadonly base64: string;\n}\n\n/**\n * Result returned by {@linkcode createSelfSignedCertificate}.\n */\nexport interface SelfSignedCertificateResult {\n\t/**\n\t * Encoded certificate outputs.\n\t */\n\treadonly certificate: CertificateMaterial;\n\t/**\n\t * Key pair used to issue the certificate.\n\t */\n\treadonly keyPair: KeyPairMaterial;\n}\n\n/**\n * Create a self-signed certificate.\n *\n * Reuses `input.keyPair` when provided; otherwise generates a new key pair from\n * `input.algorithm`. The returned certificate uses `input.subject` as both\n * issuer and subject.\n *\n * @example\n * ```ts\n * const { certificate, keyPair } = await createSelfSignedCertificate({\n * \tsubject: { commonName: 'example.com' },\n * \talgorithm: { kind: 'ecdsa', curve: 'P-256' },\n * });\n * ```\n *\n * @param input Certificate subject, key, validity, and extension settings.\n * @returns The certificate plus the key pair used to sign it.\n */\nexport async function createSelfSignedCertificate(\n\tinput: CreateSelfSignedCertificateInput,\n): Promise<SelfSignedCertificateResult> {\n\tconst keyPair = input.keyPair ?? (await generateKeyPair(input.algorithm));\n\tconst certificateInput = {\n\t\tissuer: input.subject,\n\t\tsubject: input.subject,\n\t\tpublicKey: keyPair.publicKey,\n\t\tsignerPrivateKey: keyPair.privateKey,\n\t\tissuerPublicKey: keyPair.publicKey,\n\t\t...(input.validity !== undefined ? { validity: input.validity } : {}),\n\t\t...(input.serialNumber !== undefined ? { serialNumber: input.serialNumber } : {}),\n\t\t...(input.extensions !== undefined ? { extensions: input.extensions } : {}),\n\t\t...(input.signature !== undefined ? { signature: input.signature } : {}),\n\t} satisfies CreateCertificateInput;\n\tconst certificate = await createCertificate(certificateInput);\n\n\treturn { certificate, keyPair };\n}\n\n/**\n * Create an X.509 certificate signed by `input.signerPrivateKey`.\n *\n * The certificate encodes `input.subject`, `input.publicKey`, and any supplied\n * extensions. When `serialNumber` is omitted, a random positive serial number is\n * generated. When `validity` is omitted, the certificate is valid from now for\n * 30 days.\n *\n * @example\n * ```ts\n * const certificate = await createCertificate({\n * \tissuer: { commonName: 'Example Root CA' },\n * \tsubject: { commonName: 'example.com' },\n * \tpublicKey: leafKeys.publicKey,\n * \tsignerPrivateKey: issuerKeys.privateKey,\n * \tissuerPublicKey: issuerKeys.publicKey,\n * });\n * ```\n *\n * @param input Issuer, subject, key, validity, and extension settings.\n * @returns The encoded certificate material.\n */\nexport async function createCertificate(\n\tinput: CreateCertificateInput,\n): Promise<CertificateMaterial> {\n\tconst subjectPublicKeyInfo = await exportSpkiDer(input.publicKey);\n\tconst issuerPublicKeyInfo = input.issuerPublicKey\n\t\t? await exportSpkiDer(input.issuerPublicKey)\n\t\t: undefined;\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey, input.signature);\n\tconst validity = resolveValidity(input.validity);\n\tif (isNameInputEmpty(input.issuer)) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'issuer_distinguished_name_empty',\n\t\t\t'issuer must be a non-empty distinguished name',\n\t\t);\n\t}\n\tconst subjectIsEmpty = isNameInputEmpty(input.subject);\n\tconst extensions = buildCertificateExtensions(\n\t\tsubjectPublicKeyInfo,\n\t\tissuerPublicKeyInfo,\n\t\tinput.extensions,\n\t\tsubjectIsEmpty,\n\t);\n\tconst tbsCertificate = sequence([\n\t\texplicitContext(0, integerFromNumber(2)),\n\t\tencodeSerialNumber(input.serialNumber),\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tencodeName(input.issuer),\n\t\tsequence([time(validity.notBefore), time(validity.notAfter)]),\n\t\tencodeName(input.subject),\n\t\tsubjectPublicKeyInfo,\n\t\texplicitContext(3, sequence(extensions)),\n\t]);\n\n\tconst signatureValue = await signBytes(\n\t\tinput.signerPrivateKey,\n\t\tsignatureAlgorithm,\n\t\ttbsCertificate,\n\t);\n\tconst certificateDer = sequence([\n\t\ttbsCertificate,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(signatureValue),\n\t]);\n\n\treturn materializeCertificate(certificateDer);\n}\n\n/**\n * Convert DER bytes into all exported certificate encodings.\n *\n * @param der DER-encoded certificate bytes.\n * @returns DER, PEM, and base64 views of the same certificate.\n */\nfunction materializeCertificate(der: Uint8Array): CertificateMaterial {\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('CERTIFICATE', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/**\n * Normalized validity window used during certificate creation.\n */\ninterface ResolvedValidity {\n\t/**\n\t * Start of the validity window.\n\t */\n\treadonly notBefore: Date;\n\t/**\n\t * End of the validity window.\n\t */\n\treadonly notAfter: Date;\n}\n\n/**\n * Resolve defaults for a certificate validity window.\n *\n * @param input Optional validity settings.\n * @returns A concrete `notBefore` and `notAfter` pair.\n */\nfunction resolveValidity(input: ValidityInput | undefined): ResolvedValidity {\n\tconst notBefore = input?.notBefore ?? new Date();\n\tconst notAfter = input?.notAfter ?? addDays(notBefore, input?.days ?? 30);\n\tif (notAfter.getTime() <= notBefore.getTime()) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'validity_not_after_before_not_before',\n\t\t\t'notAfter must be after notBefore',\n\t\t);\n\t}\n\treturn { notBefore, notAfter };\n}\n\n/**\n * Return a new date offset by a whole number of UTC days.\n *\n * @param date Base date.\n * @param days Number of days to add.\n * @returns The shifted date.\n */\nfunction addDays(date: Date, days: number): Date {\n\tconst out = new Date(date.getTime());\n\tout.setUTCDate(out.getUTCDate() + days);\n\treturn out;\n}\n\n/** RFC 5280 §4.1.2.2: conforming CAs must not use serial numbers longer than this. */\nconst SERIAL_NUMBER_MAX_OCTETS = 20;\n\n/**\n * Encode a certificate serial number as a DER INTEGER.\n *\n * @param serialNumber Serial number bytes, big-endian; a random one is generated when omitted.\n * @returns The DER INTEGER element.\n * @throws a `ResultError` with code `serial_number_not_positive` or\n * `serial_number_too_long` when RFC 5280 §4.1.2.2 forbids the value.\n */\nfunction encodeSerialNumber(serialNumber: Uint8Array | undefined): Uint8Array {\n\tif (serialNumber === undefined) {\n\t\treturn integer(randomSerialNumber());\n\t}\n\tlet start = 0;\n\twhile (start < serialNumber.length && serialNumber[start] === 0) {\n\t\tstart += 1;\n\t}\n\tconst magnitude = serialNumber.subarray(start);\n\tconst first = magnitude[0];\n\tif (first === undefined) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'serial_number_not_positive',\n\t\t\t'serialNumber must be a positive integer',\n\t\t);\n\t}\n\tif (magnitude.length + (first >= 0x80 ? 1 : 0) > SERIAL_NUMBER_MAX_OCTETS) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'serial_number_too_long',\n\t\t\t`serialNumber must not exceed ${String(SERIAL_NUMBER_MAX_OCTETS)} octets`,\n\t\t);\n\t}\n\treturn integer(magnitude);\n}\n\n/**\n * Generate a random positive serial number suitable for certificate issuance.\n *\n * @returns A 16-byte positive serial number.\n */\nfunction randomSerialNumber(): Uint8Array {\n\tconst serial = getCrypto().getRandomValues(new Uint8Array(16));\n\tconst first = serial[0] ?? 0;\n\tserial[0] = first & 0x7f;\n\tif ((serial[0] ?? 0) === 0) {\n\t\tserial[0] = 1;\n\t}\n\treturn serial;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyOA,eAAsB,4BACrB,GACuC;CACvC,IAAM,IAAU,EAAM,WAAY,MAAM,EAAgB,EAAM,SAAS;CAcvE,OAAO;EAAE,aAAA,MAFiB,kBAAkB;GAV3C,QAAQ,EAAM;GACd,SAAS,EAAM;GACf,WAAW,EAAQ;GACnB,kBAAkB,EAAQ;GAC1B,iBAAiB,EAAQ;GACzB,GAAI,EAAM,aAAa,KAAA,IAA2C,CAAC,IAAhC,EAAE,UAAU,EAAM,SAAS;GAC9D,GAAI,EAAM,iBAAiB,KAAA,IAAmD,CAAC,IAAxC,EAAE,cAAc,EAAM,aAAa;GAC1E,GAAI,EAAM,eAAe,KAAA,IAA+C,CAAC,IAApC,EAAE,YAAY,EAAM,WAAW;GACpE,GAAI,EAAM,cAAc,KAAA,IAA6C,CAAC,IAAlC,EAAE,WAAW,EAAM,UAAU;EAEP,CAAC;EAEtC;CAAQ;AAC/B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,eAAsB,kBACrB,GAC+B;CAC/B,IAAM,IAAuB,MAAM,EAAc,EAAM,SAAS,GAC1D,IAAsB,EAAM,kBAC/B,MAAM,EAAc,EAAM,eAAe,IACzC,KAAA,GACG,IAAqB,EAAsB,EAAM,kBAAkB,EAAM,SAAS,GAClF,IAAW,gBAAgB,EAAM,QAAQ;CAC/C,AAAI,EAAiB,EAAM,MAAM,KAChC,EACC,mCACA,+CACD;CAED,IAAM,IAAiB,EAAiB,EAAM,OAAO,GAC/C,IAAa,EAClB,GACA,GACA,EAAM,YACN,CACD,GACM,IAAiB,EAAS;EAC/B,EAAgB,GAAG,EAAkB,CAAC,CAAC;EACvC,mBAAmB,EAAM,YAAY;EACrC,EAA0B,CAAkB;EAC5C,EAAW,EAAM,MAAM;EACvB,EAAS,CAAC,EAAK,EAAS,SAAS,GAAG,EAAK,EAAS,QAAQ,CAAC,CAAC;EAC5D,EAAW,EAAM,OAAO;EACxB;EACA,EAAgB,GAAG,EAAS,CAAU,CAAC;CACxC,CAAC,GAEK,IAAiB,MAAM,EAC5B,EAAM,kBACN,GACA,CACD;CAOA,OAAO,uBANgB,EAAS;EAC/B;EACA,EAA0B,CAAkB;EAC5C,EAAU,CAAc;CACzB,CAE2C,CAAC;AAC7C;;;;;;;AAQA,SAAS,uBAAuB,GAAsC;CACrE,OAAO;EACN;EACA,KAAK,EAAU,eAAe,CAAG;EACjC,QAAQ,EAAa,CAAG;CACzB;AACD;;;;;;;AAsBA,SAAS,gBAAgB,GAAoD;CAC5E,IAAM,IAAY,GAAO,6BAAa,IAAI,KAAK,GACzC,IAAW,GAAO,YAAY,QAAQ,GAAW,GAAO,QAAQ,EAAE;CAOxE,OANI,EAAS,QAAQ,KAAK,EAAU,QAAQ,KAC3C,EACC,wCACA,kCACD,GAEM;EAAE;EAAW;CAAS;AAC9B;;;;;;;;AASA,SAAS,QAAQ,GAAY,GAAoB;CAChD,IAAM,IAAM,IAAI,KAAK,EAAK,QAAQ,CAAC;CAEnC,OADA,EAAI,WAAW,EAAI,WAAW,IAAI,CAAI,GAC/B;AACR;;;;;;;;;AAaA,SAAS,mBAAmB,GAAkD;CAC7E,IAAI,MAAiB,KAAA,GACpB,OAAO,EAAQ,mBAAmB,CAAC;CAEpC,IAAI,IAAQ;CACZ,OAAO,IAAQ,EAAa,UAAU,EAAa,OAAW,IAC7D,KAAS;CAEV,IAAM,IAAY,EAAa,SAAS,CAAK,GACvC,IAAQ,EAAU;CAaxB,OAZI,MAAU,KAAA,KACb,EACC,8BACA,yCACD,GAEG,EAAU,SAAU,OAAS,OAAgB,MAChD,EACC,0BACA,wCACD,GAEM,EAAQ,CAAS;AACzB;;;;;;AAOA,SAAS,qBAAiC;CACzC,IAAM,IAAS,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC;CAM7D,OAJA,EAAO,MADO,EAAO,MAAM,KACP,MACf,EAAO,MAAM,OAAO,MACxB,EAAO,KAAK,IAEN;AACR"}
@@ -1,6 +1,9 @@
1
- import { NameAttribute, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
2
- import { AuthorityInfoAccessMethod, AuthorityInformationAccess, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, buildCertificateExtensions, buildRequestedExtensions, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid } from "./extensions.js";
3
1
  import { SignatureProfileInput } from "../internal/crypto/signing.js";
2
+ import { canonicalDnKey, compareDistinguishedNames, isWithinDirectoryNameSubtree } from "../internal/shared/dn.js";
3
+ import { NameAttribute, NameEncoderErrorCode, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
4
+ import { ExtensionEncoderErrorCode } from "../internal/x509/extension-errors.js";
5
+ import { allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes } from "../internal/shared/ip.js";
6
+ import { AuthorityInfoAccessMethod, AuthorityInformationAccess, AuthorityInformationAccessInput, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, buildCertificateExtensions, buildRequestedExtensions, buildSubjectKeyIdentifier, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid } from "./extensions.js";
4
7
  //#region src/x509/csr.d.ts
5
8
  /** Input for {@linkcode createCertificateSigningRequest}. */
6
9
  interface CreateCsrInput {
@@ -50,5 +53,5 @@ interface CsrMaterial {
50
53
  */
51
54
  declare function createCertificateSigningRequest(input: CreateCsrInput): Promise<CsrMaterial>;
52
55
  //#endregion
53
- export { type AuthorityInfoAccessMethod, type AuthorityInformationAccess, type BasicConstraints, type CertificateExtensionsInput, type CertificatePolicies, type CpsPolicyQualifierInfo, CreateCsrInput, CsrMaterial, type CustomAuthorityInfoAccessMethod, type CustomExtendedKeyUsage, type CustomExtension, type CustomPolicyQualifierInfo, type DistributionPoint, type DistributionPointName, type DistributionPointReason, type ExtendedKeyUsage, type GeneralName, type GeneralSubtree, type InhibitAnyPolicy, type IssuingDistributionPoint, type IssuingDistributionPointBase, type IssuingDistributionPointForAttributeCerts, type IssuingDistributionPointForCaCerts, type IssuingDistributionPointForUserCerts, type KeyUsage, type KnownAuthorityInfoAccessMethod, type KnownExtendedKeyUsage, type NameConstraintForm, type NameConstraints, type NameInput, type NameObject, type ParsedBitFlags, type ParsedNameConstraintForm, type PolicyConstraints, type PolicyInformation, type PolicyMapping, type PolicyMappings, type PolicyNoticeReference, type PolicyQualifierInfo, type SubjectAltName, type UnsupportedNameConstraintForm, type UserNoticePolicyQualifierInfo, type buildCertificateExtensions, type buildRequestedExtensions, createCertificateSigningRequest, type encodeAuthorityInfoAccess, type encodeBasicConstraints, type encodeCertificatePolicies, type encodeCrlDistributionPoints, type encodeExtendedKeyUsage, type encodeExtension, type encodeInhibitAnyPolicy, type encodeKeyUsage, type encodeName, type encodeNameConstraints, type encodePolicyConstraints, type encodePolicyMappings, type encodeRelativeDistinguishedName, type encodeSubjectAltName, type getAuthorityInfoAccessMethodOid, type getExtendedKeyUsageOid, type parseAuthorityInfoAccessMethodOid, type parseExtendedKeyUsageOid };
56
+ export { type AuthorityInfoAccessMethod, type AuthorityInformationAccess, type AuthorityInformationAccessInput, type BasicConstraints, type CertificateExtensionsInput, type CertificatePolicies, type CpsPolicyQualifierInfo, CreateCsrInput, CsrMaterial, type CustomAuthorityInfoAccessMethod, type CustomExtendedKeyUsage, type CustomExtension, type CustomPolicyQualifierInfo, type DistributionPoint, type DistributionPointName, type DistributionPointReason, type ExtendedKeyUsage, type ExtensionEncoderErrorCode, type GeneralName, type GeneralSubtree, type InhibitAnyPolicy, type IssuingDistributionPoint, type IssuingDistributionPointBase, type IssuingDistributionPointForAttributeCerts, type IssuingDistributionPointForCaCerts, type IssuingDistributionPointForUserCerts, type KeyUsage, type KnownAuthorityInfoAccessMethod, type KnownExtendedKeyUsage, type NameConstraintForm, type NameConstraints, type NameEncoderErrorCode, type NameInput, type NameObject, type ParsedBitFlags, type ParsedNameConstraintForm, type PolicyConstraints, type PolicyInformation, type PolicyMapping, type PolicyMappings, type PolicyNoticeReference, type PolicyQualifierInfo, type SubjectAltName, type UnsupportedNameConstraintForm, type UserNoticePolicyQualifierInfo, type allOnesMaskForIpAddress, type buildCertificateExtensions, type buildRequestedExtensions, type buildSubjectKeyIdentifier, type canonicalDnKey, type compareDistinguishedNames, createCertificateSigningRequest, type decodeIpAddress, type encodeAuthorityInfoAccess, type encodeBasicConstraints, type encodeCertificatePolicies, type encodeCrlDistributionPoints, type encodeExtendedKeyUsage, type encodeExtension, type encodeInhibitAnyPolicy, type encodeKeyUsage, type encodeName, type encodeNameConstraints, type encodePolicyConstraints, type encodePolicyMappings, type encodeRelativeDistinguishedName, type encodeSubjectAltName, type getAuthorityInfoAccessMethodOid, type getExtendedKeyUsageOid, type isWithinDirectoryNameSubtree, type normalizeIpAddress, type parseAuthorityInfoAccessMethodOid, type parseExtendedKeyUsageOid, type parseIpAddressToBytes };
54
57
  //# sourceMappingURL=csr.d.ts.map
@@ -1,12 +1,15 @@
1
1
  import { NameAttribute, NameFieldKey, RelativeDistinguishedNameInput } from "./name.js";
2
+ import { ExtensionEncoderErrorCode } from "../internal/x509/extension-errors.js";
3
+ import { allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes } from "../internal/shared/ip.js";
2
4
  //#region src/x509/extensions.d.ts
3
5
  /**
4
6
  * A decoded BIT STRING flag set.
5
7
  *
6
8
  * `flags` contains the recognized flag values with any non-zero padding bits
7
9
  * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding
8
- * had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero.
9
- * Verification layers can use this signal to reject non-conformant encodings.
10
+ * had non-zero bits in positions that DER ({@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1}) requires to be zero.
11
+ * Extension flag decoding rejects such encodings, so parsed extension values
12
+ * always report `false`.
10
13
  */
11
14
  interface ParsedBitFlags<T extends string> {
12
15
  /** Decoded flag values, padding bits masked. */
@@ -42,7 +45,7 @@ type SubjectAltName = {
42
45
  } | {
43
46
  /** Email address (rfc822Name [1]). */
44
47
  readonly type: "email";
45
- /** RFC 822 mailbox, e.g. `"admin@example.com"`. */
48
+ /** RFC 2821 §4.1.2 Mailbox (`Local-part@Domain`), e.g. `"admin@example.com"`. */
46
49
  readonly value: string;
47
50
  } | {
48
51
  /** URI (uniformResourceIdentifier [6]). */
@@ -75,16 +78,21 @@ type GeneralName = SubjectAltName;
75
78
  */
76
79
  type DistributionPointReason = "keyCompromise" | "cACompromise" | "affiliationChanged" | "superseded" | "cessationOfOperation" | "certificateHold" | "privilegeWithdrawn" | "aACompromise";
77
80
  /**
78
- * Name component of a CRL Distribution Point (RFC 5280 §4.2.1.13).
79
- *
80
- * Supply exactly one of `fullName` or `relativeName`.
81
+ * Name component of a CRL Distribution Point, mirroring RFC 5280 §4.2.1.13
82
+ * `DistributionPointName ::= CHOICE { fullName [0] GeneralNames,
83
+ * nameRelativeToCRLIssuer [1] RelativeDistinguishedName }`.
81
84
  */
82
- interface DistributionPointName {
85
+ type DistributionPointName = {
86
+ /** The `fullName [0]` alternative. */
87
+ readonly type: "fullName";
83
88
  /** Absolute {@linkcode GeneralName}(s) identifying the distribution point (usually a URI). */
84
- readonly fullName?: readonly GeneralName[];
85
- /** Name relative to the issuer's DN; mutually exclusive with `fullName`. */
86
- readonly relativeName?: RelativeDistinguishedNameInput;
87
- }
89
+ readonly fullName: readonly GeneralName[];
90
+ } | {
91
+ /** The `nameRelativeToCRLIssuer [1]` alternative. */
92
+ readonly type: "relativeName";
93
+ /** Name relative to the issuer's DN. */
94
+ readonly relativeName: RelativeDistinguishedNameInput;
95
+ };
88
96
  /**
89
97
  * Input for a single CRL Distribution Point (RFC 5280 §4.2.1.13).
90
98
  *
@@ -262,11 +270,12 @@ interface PolicyConstraints {
262
270
  /**
263
271
  * RFC 5280 §4.2.1.14 Inhibit anyPolicy.
264
272
  *
265
- * After `skipCerts` additional certificates in the path, the special
266
- * anyPolicy OID is no longer considered a match.
273
+ * After `skipCerts` additional non-self-issued certificates in the path, the
274
+ * special anyPolicy OID is no longer considered a match, except when it
275
+ * appears in an intermediate self-issued CA certificate.
267
276
  */
268
277
  interface InhibitAnyPolicy {
269
- /** Number of additional certificates before anyPolicy stops being valid. */
278
+ /** Number of additional non-self-issued certificates before anyPolicy stops being valid. */
270
279
  readonly skipCerts: number;
271
280
  }
272
281
  /**
@@ -296,8 +305,8 @@ interface CertificateExtensionsInput {
296
305
  readonly policyConstraints?: PolicyConstraints;
297
306
  /** Inhibit anyPolicy skip-certs threshold. */
298
307
  readonly inhibitAnyPolicy?: InhibitAnyPolicy;
299
- /** Authority Information Access — OCSP responder and CA issuer URIs. */
300
- readonly authorityInfoAccess?: readonly AuthorityInformationAccess[];
308
+ /** Authority Information Access — OCSP responder and CA issuer locations. */
309
+ readonly authorityInfoAccess?: readonly AuthorityInformationAccessInput[];
301
310
  /** CRL Distribution Points — where to check revocation status. */
302
311
  readonly crlDistributionPoints?: readonly DistributionPoint[];
303
312
  /** Arbitrary extensions not covered by the built-in fields. */
@@ -463,9 +472,30 @@ interface AuthorityInformationAccess {
463
472
  readonly type: "oid";
464
473
  readonly value: string;
465
474
  };
466
- /** URI where the resource can be fetched. */
467
- readonly uri: string;
475
+ /** accessLocation GeneralName where the resource is available (usually a URI). */
476
+ readonly location: GeneralName;
468
477
  }
478
+ /**
479
+ * Builder input for one Authority Information Access entry.
480
+ *
481
+ * Parsed AIA locations stay broad ({@linkcode AuthorityInformationAccess}), but
482
+ * an `'ocsp'` entry must supply a URI location, since RFC 6960 §3.1 defines the
483
+ * `id-ad-ocsp` location as a URI; `directoryName` is defined for `caIssuers`.
484
+ */
485
+ type AuthorityInformationAccessInput = {
486
+ /** OCSP responder access method. */
487
+ readonly method: "ocsp";
488
+ /** OCSP responder URI (RFC 6960 §3.1). */
489
+ readonly location: {
490
+ readonly type: "uri";
491
+ readonly value: string;
492
+ };
493
+ } | {
494
+ /** caIssuers or a custom access method. */
495
+ readonly method: "caIssuers" | CustomAuthorityInfoAccessMethod;
496
+ /** Any accessLocation GeneralName. */
497
+ readonly location: GeneralName;
498
+ };
469
499
  /** Well-known Extended Key Usage purpose strings (RFC 5280 §4.2.1.12). */
470
500
  type KnownExtendedKeyUsage = "serverAuth" | "clientAuth" | "codeSigning" | "emailProtection" | "timeStamping" | "ocspSigning";
471
501
  /** Extended Key Usage purpose identified by a custom OID. */
@@ -490,8 +520,8 @@ type ExtendedKeyUsage = "serverAuth" | "clientAuth" | "codeSigning" | "emailProt
490
520
  * @param subjectPublicKeyInfo DER-encoded SPKI of the subject.
491
521
  * @param issuerPublicKeyInfo DER-encoded SPKI of the issuer, or `undefined` for self-signed.
492
522
  * @param input Optional extension configuration.
493
- * @param subjectIsEmpty Whether the certificate subject DN is empty. When `true`, the
494
- * subjectAltName extension is marked critical per RFC 5280 §4.2.1.6.
523
+ * @param subjectIsEmpty Whether the certificate subject DN is empty. When `true`, a
524
+ * subjectAltName extension is required and marked critical per RFC 5280 §4.2.1.6.
495
525
  * @returns Array of DER-encoded Extension SEQUENCEs.
496
526
  */
497
527
  declare function buildCertificateExtensions(subjectPublicKeyInfo: Uint8Array, issuerPublicKeyInfo: Uint8Array | undefined, input: CertificateExtensionsInput | undefined, subjectIsEmpty?: boolean): Uint8Array[];
@@ -542,7 +572,7 @@ declare function encodeExtendedKeyUsage(usages: readonly ExtendedKeyUsage[]): Ui
542
572
  *
543
573
  * @param entries AIA entries (OCSP, caIssuers, or custom) to encode.
544
574
  */
545
- declare function encodeAuthorityInfoAccess(entries: readonly AuthorityInformationAccess[]): Uint8Array;
575
+ declare function encodeAuthorityInfoAccess(entries: readonly AuthorityInformationAccessInput[]): Uint8Array;
546
576
  /**
547
577
  * DER-encode a CRL Distribution Points SEQUENCE.
548
578
  *
@@ -603,6 +633,13 @@ declare function getAuthorityInfoAccessMethodOid(method: AuthorityInfoAccessMeth
603
633
  * Returns `'ocsp'` or `'caIssuers'` for recognized OIDs, or `{ type: 'oid', value }` otherwise.
604
634
  */
605
635
  declare function parseAuthorityInfoAccessMethodOid(oid: string): AuthorityInfoAccessMethod;
636
+ /**
637
+ * Computes a key identifier from a DER `SubjectPublicKeyInfo` using method (1)
638
+ * of RFC 5280 §4.2.1.2: "the 160-bit SHA-1 hash of the value of the BIT STRING
639
+ * subjectPublicKey (excluding the tag, length, and number of unused bits)".
640
+ * A parsed certificate carries the input as `subjectPublicKeyInfoDer`.
641
+ */
642
+ declare function buildSubjectKeyIdentifier(subjectPublicKeyInfo: Uint8Array): Uint8Array;
606
643
  //#endregion
607
- export { AuthorityInfoAccessMethod, AuthorityInformationAccess, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, buildCertificateExtensions, buildRequestedExtensions, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid };
644
+ export { AuthorityInfoAccessMethod, AuthorityInformationAccess, AuthorityInformationAccessInput, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, type ExtensionEncoderErrorCode, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, allOnesMaskForIpAddress, buildCertificateExtensions, buildRequestedExtensions, buildSubjectKeyIdentifier, decodeIpAddress, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, normalizeIpAddress, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid, parseIpAddressToBytes };
608
645
  //# sourceMappingURL=extensions.d.ts.map