micro509 0.18.0 → 0.19.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 (99) hide show
  1. package/CHANGELOG.md +88 -1
  2. package/dist/crypto/crypto.d.ts +11 -2
  3. package/dist/crypto/crypto.js +30 -17
  4. package/dist/crypto/crypto.js.map +1 -1
  5. package/dist/crypto.d.ts +2 -2
  6. package/dist/der/der.js.map +1 -1
  7. package/dist/index.d.ts +6 -5
  8. package/dist/internal/asn1/asn1.js +10 -2
  9. package/dist/internal/asn1/asn1.js.map +1 -1
  10. package/dist/internal/asn1/ber.js.map +1 -1
  11. package/dist/internal/asn1/decode-refusal.js.map +1 -1
  12. package/dist/internal/asn1/der.js.map +1 -1
  13. package/dist/internal/asn1/oids.js.map +1 -1
  14. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  15. package/dist/internal/crypto/ecdsa.js.map +1 -1
  16. package/dist/internal/crypto/hash.js.map +1 -1
  17. package/dist/internal/crypto/pbes2.js.map +1 -1
  18. package/dist/internal/crypto/prime-ec.js.map +1 -1
  19. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  20. package/dist/internal/crypto/sig-verify.d.ts +40 -0
  21. package/dist/internal/crypto/sig-verify.js +152 -65
  22. package/dist/internal/crypto/sig-verify.js.map +1 -1
  23. package/dist/internal/crypto/signing.js.map +1 -1
  24. package/dist/internal/jose/base64url.js.map +1 -1
  25. package/dist/internal/jose/json-data.js.map +1 -1
  26. package/dist/internal/jose/strict-json.js.map +1 -1
  27. package/dist/internal/shared/base64.js.map +1 -1
  28. package/dist/internal/shared/dn.js.map +1 -1
  29. package/dist/internal/shared/idna.js.map +1 -1
  30. package/dist/internal/shared/ip.js.map +1 -1
  31. package/dist/internal/shared/mailbox.js.map +1 -1
  32. package/dist/internal/shared/punycode.js.map +1 -1
  33. package/dist/internal/shared/uri-host.js.map +1 -1
  34. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  35. package/dist/internal/verify/policy-engine.js.map +1 -1
  36. package/dist/internal/verify/spki-distrust.js.map +1 -1
  37. package/dist/internal/verify/verify-path.js +222 -116
  38. package/dist/internal/verify/verify-path.js.map +1 -1
  39. package/dist/internal/x509/directory-name.js.map +1 -1
  40. package/dist/internal/x509/extension-bits.js.map +1 -1
  41. package/dist/internal/x509/extension-errors.js.map +1 -1
  42. package/dist/internal/x509/extension-registry.js.map +1 -1
  43. package/dist/internal/x509/general-name-profile.js.map +1 -1
  44. package/dist/internal/x509/general-name.js.map +1 -1
  45. package/dist/internal/x509/name-fields.js.map +1 -1
  46. package/dist/internal/x509/or-address.js.map +1 -1
  47. package/dist/jose/base64url.js.map +1 -1
  48. package/dist/jose/errors.js.map +1 -1
  49. package/dist/jose/jwe.js.map +1 -1
  50. package/dist/jose/jwks.js.map +1 -1
  51. package/dist/jose/jws.js.map +1 -1
  52. package/dist/jose/jwt.js.map +1 -1
  53. package/dist/jose/remote-jwks.js.map +1 -1
  54. package/dist/kdf/argon2-arithmetic.js.map +1 -1
  55. package/dist/kdf/argon2-core.js.map +1 -1
  56. package/dist/kdf/argon2-memory.js.map +1 -1
  57. package/dist/kdf/argon2-portable.js.map +1 -1
  58. package/dist/kdf/argon2.js.map +1 -1
  59. package/dist/keys/keys.js.map +1 -1
  60. package/dist/pem/pem.js.map +1 -1
  61. package/dist/pkcs/pfx.js.map +1 -1
  62. package/dist/pkcs/pkcs12-mac.js +1 -1
  63. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  64. package/dist/pkcs/pkcs7.d.ts +10 -0
  65. package/dist/pkcs/pkcs7.js +106 -88
  66. package/dist/pkcs/pkcs7.js.map +1 -1
  67. package/dist/result/result.js.map +1 -1
  68. package/dist/revocation/chain.d.ts +67 -13
  69. package/dist/revocation/chain.js +429 -301
  70. package/dist/revocation/chain.js.map +1 -1
  71. package/dist/revocation/crl.d.ts +65 -11
  72. package/dist/revocation/crl.js +492 -202
  73. package/dist/revocation/crl.js.map +1 -1
  74. package/dist/revocation/ocsp.d.ts +79 -24
  75. package/dist/revocation/ocsp.js +417 -231
  76. package/dist/revocation/ocsp.js.map +1 -1
  77. package/dist/revocation/revocation.d.ts +68 -13
  78. package/dist/revocation/revocation.js +194 -73
  79. package/dist/revocation/revocation.js.map +1 -1
  80. package/dist/revocation.d.ts +4 -4
  81. package/dist/ssh/ssh.js.map +1 -1
  82. package/dist/ssh/wire.js.map +1 -1
  83. package/dist/verify/identity.d.ts +2 -2
  84. package/dist/verify/identity.js +2 -2
  85. package/dist/verify/identity.js.map +1 -1
  86. package/dist/verify/verify.d.ts +84 -32
  87. package/dist/verify/verify.js +221 -171
  88. package/dist/verify/verify.js.map +1 -1
  89. package/dist/verify.d.ts +3 -2
  90. package/dist/x509/certificate.js.map +1 -1
  91. package/dist/x509/csr.js.map +1 -1
  92. package/dist/x509/extensions.js.map +1 -1
  93. package/dist/x509/fingerprint.js.map +1 -1
  94. package/dist/x509/name-text.js.map +1 -1
  95. package/dist/x509/name.js.map +1 -1
  96. package/dist/x509/parse.d.ts +6 -2
  97. package/dist/x509/parse.js +121 -121
  98. package/dist/x509/parse.js.map +1 -1
  99. package/package.json +11 -11
@@ -1 +1 @@
1
- {"version":3,"file":"certificate.js","names":["keyPair","input","generateKeyPair","subjectPublicKeyInfo","exportSpkiDer","authorityKeyIdentifier","authority","buildSubjectKeyIdentifier","issuerKeyIdentifier","signatureAlgorithm","getSignatureAlgorithm","validity","isNameInputEmpty","throwMicro509Error","subjectIsEmpty","extensions","buildCertificateExtensions","tbsCertificate","sequence","explicitContext","integerFromNumber","encodeAlgorithmIdentifier","encodeName","time","signatureValue","signBytes","bitString","parseCertificateFromSource","source","error","rethrowDecodeRefusal","DECODE_REFUSAL_CODES","pemEncode","der","base64Encode","notBefore","notAfter","out","date","days","serialNumber","integer","start","magnitude","first","serial","getCrypto"],"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 { DECODE_REFUSAL_CODES, rethrowDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\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 {\n\tbuildCertificateExtensions,\n\tbuildSubjectKeyIdentifier,\n\tissuerKeyIdentifier,\n} from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName, isNameInputEmpty } from '#micro509/x509/name';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateFromSource } from '#micro509/x509/parse';\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_certificate_invalid'\n\t| 'issuer_distinguished_name_empty'\n\t| 'serial_number_not_positive'\n\t| 'serial_number_too_long'\n\t| 'validity_date_invalid'\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 * Certificate of the issuer. Its subject key identifier becomes the\n\t * authority key identifier (RFC 5280 §4.2.1.1, §4.2.1.2). An issuer\n\t * certificate without one yields a key identifier derived from its public\n\t * key. Omit it to leave the authority key identifier out.\n\t */\n\treadonly issuerCertificate?: string | Uint8Array | ParsedCertificate;\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\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 issueCertificate(certificateInput, 'subject');\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: issuer.keyPair.privateKey,\n * \tissuerCertificate: issuer.certificate.der,\n * });\n * ```\n *\n * @param input Issuer, subject, key, validity, and extension settings.\n * @returns The encoded certificate material.\n */\nexport function createCertificate(input: CreateCertificateInput): Promise<CertificateMaterial> {\n\treturn issueCertificate(input, 'issuer');\n}\n\n/**\n * Signs a certificate whose authority key identifier comes from\n * `input.issuerCertificate`, or from its own subject key when `authority` is\n * `'subject'` (RFC 5280 §4.2.1.1).\n */\nasync function issueCertificate(\n\tinput: CreateCertificateInput,\n\tauthority: 'issuer' | 'subject',\n): Promise<CertificateMaterial> {\n\tconst subjectPublicKeyInfo = await exportSpkiDer(input.publicKey);\n\tconst authorityKeyIdentifier =\n\t\tauthority === 'subject'\n\t\t\t? buildSubjectKeyIdentifier(subjectPublicKeyInfo)\n\t\t\t: input.issuerCertificate === undefined\n\t\t\t\t? undefined\n\t\t\t\t: issuerKeyIdentifier(issuerCertificateOf(input.issuerCertificate));\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\tauthorityKeyIdentifier,\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/** The parsed issuer certificate of a certificate being built. */\nfunction issuerCertificateOf(source: string | Uint8Array | ParsedCertificate): ParsedCertificate {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\treturn throwMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'issuer_certificate_invalid',\n\t\t\t'issuerCertificate must be a PEM, DER or parsed certificate',\n\t\t);\n\t}\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 (Number.isNaN(notBefore.getTime()) || Number.isNaN(notAfter.getTime())) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'validity_date_invalid',\n\t\t\t'notBefore and notAfter must be valid dates',\n\t\t);\n\t}\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":";;;;;;;;;;;;;;;;;;;;;;;;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AA,GACpB,OAAOC,EAAQ,mBAAmB,CAAC;CAEpC,IAAIC,IAAQ;CACZ,OAAOA,IAAQF,EAAa,UAAUA,EAAaE,OAAW,IAC7D,KAAS;CAEV,IAAMC,IAAYH,EAAa,SAASE,CAAK,GACvCE,IAAQD,EAAU;CAaxB,OAZIC,MAAU,KAAA,KACb/B,EACC,8BACA,yCACD,GAEG8B,EAAU,SAAU,OAAS,OAAgB,MAChD9B,EACC,0BACA,wCACD,GAEM4B,EAAQE,CAAS;AACzB;;;;;;AAOA,SAAS,qBAAiC;CACzC,IAAME,IAASC,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC;CAM7D,OAJA,EAAO,MADOD,EAAO,MAAM,KACP,MACfA,EAAO,MAAM,OAAO,MACxB,EAAO,KAAK,IAENA;AACR"}
1
+ {"version":3,"file":"certificate.js","names":["rethrowDecodeRefusal","bitString","explicitContext","integer","integerFromNumber","sequence","time","encodeAlgorithmIdentifier","getSignatureAlgorithm","signBytes","getCrypto","base64Encode","exportSpkiDer","generateKeyPair","pemEncode","DECODE_REFUSAL_CODES","throwMicro509Error","buildCertificateExtensions","buildSubjectKeyIdentifier","issuerKeyIdentifier","encodeName","isNameInputEmpty","parseCertificateFromSource","input","keyPair","authority","subjectPublicKeyInfo","authorityKeyIdentifier","signatureAlgorithm","validity","subjectIsEmpty","extensions","tbsCertificate","signatureValue","source","error","der","notBefore","notAfter","date","days","out","serialNumber","start","magnitude","first","serial"],"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 { DECODE_REFUSAL_CODES, rethrowDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\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 {\n\tbuildCertificateExtensions,\n\tbuildSubjectKeyIdentifier,\n\tissuerKeyIdentifier,\n} from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName, isNameInputEmpty } from '#micro509/x509/name';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateFromSource } from '#micro509/x509/parse';\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_certificate_invalid'\n\t| 'issuer_distinguished_name_empty'\n\t| 'serial_number_not_positive'\n\t| 'serial_number_too_long'\n\t| 'validity_date_invalid'\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 * Certificate of the issuer. Its subject key identifier becomes the\n\t * authority key identifier (RFC 5280 §4.2.1.1, §4.2.1.2). An issuer\n\t * certificate without one yields a key identifier derived from its public\n\t * key. Omit it to leave the authority key identifier out.\n\t */\n\treadonly issuerCertificate?: string | Uint8Array | ParsedCertificate;\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\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 issueCertificate(certificateInput, 'subject');\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: issuer.keyPair.privateKey,\n * \tissuerCertificate: issuer.certificate.der,\n * });\n * ```\n *\n * @param input Issuer, subject, key, validity, and extension settings.\n * @returns The encoded certificate material.\n */\nexport function createCertificate(input: CreateCertificateInput): Promise<CertificateMaterial> {\n\treturn issueCertificate(input, 'issuer');\n}\n\n/**\n * Signs a certificate whose authority key identifier comes from\n * `input.issuerCertificate`, or from its own subject key when `authority` is\n * `'subject'` (RFC 5280 §4.2.1.1).\n */\nasync function issueCertificate(\n\tinput: CreateCertificateInput,\n\tauthority: 'issuer' | 'subject',\n): Promise<CertificateMaterial> {\n\tconst subjectPublicKeyInfo = await exportSpkiDer(input.publicKey);\n\tconst authorityKeyIdentifier =\n\t\tauthority === 'subject'\n\t\t\t? buildSubjectKeyIdentifier(subjectPublicKeyInfo)\n\t\t\t: input.issuerCertificate === undefined\n\t\t\t\t? undefined\n\t\t\t\t: issuerKeyIdentifier(issuerCertificateOf(input.issuerCertificate));\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\tauthorityKeyIdentifier,\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/** The parsed issuer certificate of a certificate being built. */\nfunction issuerCertificateOf(source: string | Uint8Array | ParsedCertificate): ParsedCertificate {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\treturn throwMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'issuer_certificate_invalid',\n\t\t\t'issuerCertificate must be a PEM, DER or parsed certificate',\n\t\t);\n\t}\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 (Number.isNaN(notBefore.getTime()) || Number.isNaN(notAfter.getTime())) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'validity_date_invalid',\n\t\t\t'notBefore and notAfter must be valid dates',\n\t\t);\n\t}\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkPA,eAAsB,4BACrBuB,GACuC;CACvC,IAAMC,IAAUD,EAAM,WAAY,MAAMV,EAAgBU,EAAM,SAAS;CAavE,OAAO;EAAE,aAAA,MAFiB,iBAAiB;GAT1C,QAAQA,EAAM;GACd,SAASA,EAAM;GACf,WAAWC,EAAQ;GACnB,kBAAkBA,EAA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KACb7B,EACC,8BACA,yCACD,GAEG4B,EAAU,SAAUC,OAAS,OAAgB,MAChD7B,EACC,0BACA,wCACD,GAEMb,EAAQyC,CAAS;AACzB;;;;;;AAOA,SAAS,qBAAiC;CACzC,IAAME,IAASpC,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC;CAM7D,OAJAoC,EAAO,MADOA,EAAO,MAAM,KACP,MACfA,EAAO,MAAM,OAAO,MACxBA,EAAO,KAAK,IAENA;AACR"}
@@ -1 +1 @@
1
- {"version":3,"file":"csr.js","names":["signatureAlgorithm","getSignatureAlgorithm","input","spki","exportSpkiDer","attributes","certificationRequestInfo","sequence","integerFromNumber","encodeName","implicitConstructedContext","concatBytes","normalizedSignature","signBytes","der","encodeAlgorithmIdentifier","bitString","pemEncode","base64Encode","builtExtensions","buildRequestedExtensions","extensions","objectIdentifier","OIDS","setOf"],"sources":["../../src/x509/csr.ts"],"sourcesContent":["/**\n * PKCS#10 Certificate Signing Request (CSR) creation.\n *\n * Builds a CSR from a subject name, WebCrypto key pair, and optional extensions,\n * producing DER, PEM, and base64 outputs.\n *\n * @module\n */\n\nimport {\n\tbitString,\n\tconcatBytes,\n\timplicitConstructedContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\tsequence,\n\tsetOf,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport { exportSpkiDer } from '#micro509/keys/keys';\nimport { pemEncode } from '#micro509/pem/pem';\nimport type { SignatureProfileInput } from '#micro509/x509/certificate';\nimport type { CertificateExtensionsInput } from '#micro509/x509/extensions';\nimport { buildRequestedExtensions } from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName } from '#micro509/x509/name';\n\nexport type * from '#micro509/x509/extensions';\nexport type * from '#micro509/x509/name';\n\n/** Input for {@linkcode createCertificateSigningRequest}. */\nexport interface CreateCsrInput {\n\t/** Distinguished name for the CSR subject (e.g. `{ commonName: 'example.com' }`). */\n\treadonly subject: NameInput;\n\t/** WebCrypto public key to embed in the CSR's SubjectPublicKeyInfo. */\n\treadonly publicKey: CryptoKey;\n\t/** WebCrypto private key used to self-sign the CSR (proves key possession). */\n\treadonly signerPrivateKey: CryptoKey;\n\t/** Requested X.509v3 extensions to include in the CSR attributes. */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/** Override the signature algorithm profile (hash, salt length, etc.). */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/** DER, PEM, and base64 encodings of a CSR produced by {@linkcode createCertificateSigningRequest}. */\nexport interface CsrMaterial {\n\t/** Raw DER-encoded PKCS#10 CertificationRequest. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored CSR (`-----BEGIN CERTIFICATE REQUEST-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/**\n * Creates a PKCS#10 Certificate Signing Request signed with the given private key.\n *\n * The CSR embeds the public key's SPKI, the subject name, and any requested extensions\n * as attributes. The signature proves possession of the private key.\n *\n * @example\n * ```ts\n * import { createCertificateSigningRequest } from 'micro509';\n *\n * const keyPair = await crypto.subtle.generateKey(\n * { name: 'ECDSA', namedCurve: 'P-256' },\n * true,\n * ['sign', 'verify'],\n * );\n * const csr = await createCertificateSigningRequest({\n * subject: { commonName: 'example.com' },\n * publicKey: keyPair.publicKey,\n * signerPrivateKey: keyPair.privateKey,\n * extensions: { subjectAltNames: [{ type: 'dns', value: 'example.com' }] },\n * });\n * console.log(csr.pem);\n * ```\n */\nexport async function createCertificateSigningRequest(input: CreateCsrInput): Promise<CsrMaterial> {\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey, input.signature);\n\tconst spki = await exportSpkiDer(input.publicKey);\n\tconst attributes = buildAttributes(input.extensions);\n\tconst certificationRequestInfo = sequence([\n\t\tintegerFromNumber(0),\n\t\tencodeName(input.subject),\n\t\tspki,\n\t\timplicitConstructedContext(0, concatBytes(attributes)),\n\t]);\n\tconst normalizedSignature = await signBytes(\n\t\tinput.signerPrivateKey,\n\t\tsignatureAlgorithm,\n\t\tcertificationRequestInfo,\n\t);\n\n\tconst der = sequence([\n\t\tcertificationRequestInfo,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(normalizedSignature),\n\t]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('CERTIFICATE REQUEST', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/** Encodes extensions into a CSR extensionRequest attribute, or returns empty. */\nfunction buildAttributes(extensions: CertificateExtensionsInput | undefined): Uint8Array[] {\n\tconst builtExtensions = buildRequestedExtensions(extensions);\n\tif (builtExtensions.length === 0) {\n\t\treturn [];\n\t}\n\treturn [sequence([objectIdentifier(OIDS.extensionRequest), setOf([sequence(builtExtensions)])])];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,eAAsB,gCAAgC,GAA6C;CAClG,IAAMA,IAAqBC,EAAsBC,EAAM,kBAAkBA,EAAM,SAAS,GAClFC,IAAO,MAAMC,EAAcF,EAAM,SAAS,GAC1CG,IAAa,gBAAgBH,EAAM,UAAU,GAC7CI,IAA2BC,EAAS;EACzCC,EAAkB,CAAC;EACnBC,EAAWP,EAAM,OAAO;EACxBC;EACAO,EAA2B,GAAGC,EAAYN,CAAU,CAAC;CACtD,CAAC,GACKO,IAAsB,MAAMC,EACjCX,EAAM,kBACNF,GACAM,CACD,GAEMQ,IAAMP,EAAS;EACpBD;EACAS,EAA0Bf,CAAkB;EAC5CgB,EAAUJ,CAAmB;CAC9B,CAAC;CACD,OAAO;EACN;EACA,KAAKK,EAAU,uBAAuBH,CAAG;EACzC,QAAQI,EAAaJ,CAAG;CACzB;AACD;;AAGA,SAAS,gBAAgB,GAAkE;CAC1F,IAAMK,IAAkBC,EAAyBC,CAAU;CAI3D,OAHIF,EAAgB,WAAW,IACvB,CAAC,IAEF,CAACZ,EAAS,CAACe,EAAiBC,EAAK,gBAAgB,GAAGC,EAAM,CAACjB,EAASY,CAAe,CAAC,CAAC,CAAC,CAAC,CAAC;AAChG"}
1
+ {"version":3,"file":"csr.js","names":["bitString","concatBytes","implicitConstructedContext","integerFromNumber","objectIdentifier","sequence","setOf","OIDS","encodeAlgorithmIdentifier","getSignatureAlgorithm","signBytes","base64Encode","exportSpkiDer","pemEncode","buildRequestedExtensions","encodeName","input","signatureAlgorithm","spki","attributes","certificationRequestInfo","normalizedSignature","der","extensions","builtExtensions"],"sources":["../../src/x509/csr.ts"],"sourcesContent":["/**\n * PKCS#10 Certificate Signing Request (CSR) creation.\n *\n * Builds a CSR from a subject name, WebCrypto key pair, and optional extensions,\n * producing DER, PEM, and base64 outputs.\n *\n * @module\n */\n\nimport {\n\tbitString,\n\tconcatBytes,\n\timplicitConstructedContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\tsequence,\n\tsetOf,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport { exportSpkiDer } from '#micro509/keys/keys';\nimport { pemEncode } from '#micro509/pem/pem';\nimport type { SignatureProfileInput } from '#micro509/x509/certificate';\nimport type { CertificateExtensionsInput } from '#micro509/x509/extensions';\nimport { buildRequestedExtensions } from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName } from '#micro509/x509/name';\n\nexport type * from '#micro509/x509/extensions';\nexport type * from '#micro509/x509/name';\n\n/** Input for {@linkcode createCertificateSigningRequest}. */\nexport interface CreateCsrInput {\n\t/** Distinguished name for the CSR subject (e.g. `{ commonName: 'example.com' }`). */\n\treadonly subject: NameInput;\n\t/** WebCrypto public key to embed in the CSR's SubjectPublicKeyInfo. */\n\treadonly publicKey: CryptoKey;\n\t/** WebCrypto private key used to self-sign the CSR (proves key possession). */\n\treadonly signerPrivateKey: CryptoKey;\n\t/** Requested X.509v3 extensions to include in the CSR attributes. */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/** Override the signature algorithm profile (hash, salt length, etc.). */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/** DER, PEM, and base64 encodings of a CSR produced by {@linkcode createCertificateSigningRequest}. */\nexport interface CsrMaterial {\n\t/** Raw DER-encoded PKCS#10 CertificationRequest. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored CSR (`-----BEGIN CERTIFICATE REQUEST-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/**\n * Creates a PKCS#10 Certificate Signing Request signed with the given private key.\n *\n * The CSR embeds the public key's SPKI, the subject name, and any requested extensions\n * as attributes. The signature proves possession of the private key.\n *\n * @example\n * ```ts\n * import { createCertificateSigningRequest } from 'micro509';\n *\n * const keyPair = await crypto.subtle.generateKey(\n * { name: 'ECDSA', namedCurve: 'P-256' },\n * true,\n * ['sign', 'verify'],\n * );\n * const csr = await createCertificateSigningRequest({\n * subject: { commonName: 'example.com' },\n * publicKey: keyPair.publicKey,\n * signerPrivateKey: keyPair.privateKey,\n * extensions: { subjectAltNames: [{ type: 'dns', value: 'example.com' }] },\n * });\n * console.log(csr.pem);\n * ```\n */\nexport async function createCertificateSigningRequest(input: CreateCsrInput): Promise<CsrMaterial> {\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey, input.signature);\n\tconst spki = await exportSpkiDer(input.publicKey);\n\tconst attributes = buildAttributes(input.extensions);\n\tconst certificationRequestInfo = sequence([\n\t\tintegerFromNumber(0),\n\t\tencodeName(input.subject),\n\t\tspki,\n\t\timplicitConstructedContext(0, concatBytes(attributes)),\n\t]);\n\tconst normalizedSignature = await signBytes(\n\t\tinput.signerPrivateKey,\n\t\tsignatureAlgorithm,\n\t\tcertificationRequestInfo,\n\t);\n\n\tconst der = sequence([\n\t\tcertificationRequestInfo,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(normalizedSignature),\n\t]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('CERTIFICATE REQUEST', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/** Encodes extensions into a CSR extensionRequest attribute, or returns empty. */\nfunction buildAttributes(extensions: CertificateExtensionsInput | undefined): Uint8Array[] {\n\tconst builtExtensions = buildRequestedExtensions(extensions);\n\tif (builtExtensions.length === 0) {\n\t\treturn [];\n\t}\n\treturn [sequence([objectIdentifier(OIDS.extensionRequest), setOf([sequence(builtExtensions)])])];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,eAAsB,gCAAgCgB,GAA6C;CAClG,IAAMC,IAAqBR,EAAsBO,EAAM,kBAAkBA,EAAM,SAAS,GAClFE,IAAO,MAAMN,EAAcI,EAAM,SAAS,GAC1CG,IAAa,gBAAgBH,EAAM,UAAU,GAC7CI,IAA2Bf,EAAS;EACzCF,EAAkB,CAAC;EACnBY,EAAWC,EAAM,OAAO;EACxBE;EACAhB,EAA2B,GAAGD,EAAYkB,CAAU,CAAC;CACtD,CAAC,GACKE,IAAsB,MAAMX,EACjCM,EAAM,kBACNC,GACAG,CACD,GAEME,IAAMjB,EAAS;EACpBe;EACAZ,EAA0BS,CAAkB;EAC5CjB,EAAUqB,CAAmB;CAC9B,CAAC;CACD,OAAO;EACNC;EACA,KAAKT,EAAU,uBAAuBS,CAAG;EACzC,QAAQX,EAAaW,CAAG;CACzB;AACD;;AAGA,SAAS,gBAAgBC,GAAkE;CAC1F,IAAMC,IAAkBV,EAAyBS,CAAU;CAI3D,OAHIC,EAAgB,WAAW,IACvB,CAAC,IAEF,CAACnB,EAAS,CAACD,EAAiBG,EAAK,gBAAgB,GAAGD,EAAM,CAACD,EAASmB,CAAe,CAAC,CAAC,CAAC,CAAC,CAAC;AAChG"}