node-opcua-crypto-web 5.7.2 → 5.9.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.
@@ -548,6 +548,16 @@ type CaSignAlgorithm = {
548
548
  };
549
549
  } | {
550
550
  name: "ECDSA";
551
+ /**
552
+ * The curve the key lives on. Required, unlike in most WebCrypto
553
+ * signing parameters, because {@link webCryptoFromSigner} has to
554
+ * *import* the signer's public key, and `importKey` cannot infer a
555
+ * curve it was not given. Declaring it wrong is safe: the SPKI
556
+ * bytes returned by {@link CaSigner.getPublicKey} state the real
557
+ * curve, so the import fails rather than producing a key that
558
+ * signs into the void.
559
+ */
560
+ namedCurve: "P-256" | "P-384" | "P-521";
551
561
  hash: {
552
562
  name: "SHA-256" | "SHA-384" | "SHA-512";
553
563
  };
@@ -570,10 +580,48 @@ interface CaSigner {
570
580
  getPublicKey(): Promise<ArrayBuffer>;
571
581
  /**
572
582
  * Sign `tbs` (the to-be-signed bytes, e.g. a certificate or CRL's TBS
573
- * DER encoding) and return the raw signature bytes.
583
+ * DER encoding) and return the signature.
584
+ *
585
+ * The signature must be encoded the way `SubtleCrypto.sign` encodes it,
586
+ * because that is what the certificate generators are given and what
587
+ * they know how to re-encode:
588
+ *
589
+ * - **RSA** - the signature bytes, with nothing to decide.
590
+ * - **ECDSA** - the fixed-width `r || s` pair of IEEE P1363, *not* the
591
+ * `SEQUENCE { r, s }` of DER. Certificates carry the DER form, but the
592
+ * conversion is done downstream; a signer that returns DER here
593
+ * produces a certificate whose signature will not verify.
594
+ *
595
+ * That distinction matters for KMS-backed signers: Google Cloud KMS,
596
+ * AWS KMS and most PKCS#11 tokens return ECDSA signatures already in
597
+ * DER, so their adapters have to convert to `r || s` before returning.
598
+ * {@link ecdsaSignatureDerToP1363} does that conversion.
574
599
  */
575
600
  sign(tbs: Uint8Array): Promise<ArrayBuffer>;
576
601
  }
602
+ /**
603
+ * Convert a DER-encoded ECDSA signature, `SEQUENCE { INTEGER r, INTEGER s }`,
604
+ * into the fixed-width `r || s` form that WebCrypto - and therefore
605
+ * {@link CaSigner.sign} - is defined to return.
606
+ *
607
+ * Use it when adapting a signer that hands back DER, which is what Google
608
+ * Cloud KMS, AWS KMS and most PKCS#11 tokens do:
609
+ *
610
+ * ```ts
611
+ * async sign(tbs: Uint8Array): Promise<ArrayBuffer> {
612
+ * const { signature } = await kms.asymmetricSign({ name: keyName, digest: { sha256: await sha256(tbs) } });
613
+ * return ecdsaSignatureDerToP1363(signature, "P-256");
614
+ * }
615
+ * ```
616
+ *
617
+ * Passing an already-converted signature is not silently tolerated: `r || s`
618
+ * is not valid DER, so it is rejected rather than corrupted further.
619
+ *
620
+ * @param derSignature the signature as `SEQUENCE { r, s }`
621
+ * @param namedCurve the curve the signing key lives on, which fixes the
622
+ * width each coordinate is padded to
623
+ */
624
+ declare function ecdsaSignatureDerToP1363(derSignature: BufferSource, namedCurve: "P-256" | "P-384" | "P-521"): ArrayBuffer;
577
625
  /**
578
626
  * Adapts an in-process key pair (e.g. one produced by {@link generateKeyPair}
579
627
  * or read from disk via {@link pemToPrivateKey}) to the {@link CaSigner}
@@ -624,6 +672,8 @@ interface WebCryptoFromSigner {
624
672
  * that key ever existing as an in-process `CryptoKey`.
625
673
  */
626
674
  declare function webCryptoFromSigner(signer: CaSigner, baseCrypto?: Pick<Crypto, "subtle" | "getRandomValues">): Promise<WebCryptoFromSigner>;
675
+ /** True when `value` implements {@link CaSigner} rather than being a raw `CryptoKey`. */
676
+ declare function isCaSigner(value: CryptoKey | CaSigner): value is CaSigner;
627
677
  /** The `crypto`/`signingKey` pair a `@peculiar/x509` generator needs, resolved from either a raw key or a {@link CaSigner}. */
628
678
  interface ResolvedCaSigningKey {
629
679
  crypto: Crypto;
@@ -638,6 +688,28 @@ interface ResolvedCaSigningKey {
638
688
  * generation) need to branch on which kind of signing key they were given.
639
689
  */
640
690
  declare function resolveCaSigningKey(signingKey: CryptoKey | CaSigner, baseCrypto?: Pick<Crypto, "subtle" | "getRandomValues">): Promise<ResolvedCaSigningKey>;
691
+ /**
692
+ * What a `@peculiar/x509` generator needs when it must sign with a key AND
693
+ * embed that same key's public half — a CSR, or a self-signed certificate.
694
+ * {@link resolveCaSigningKey} is not enough there: it yields no public key.
695
+ */
696
+ interface ResolvedCaKeyPair {
697
+ crypto: Crypto;
698
+ keys: {
699
+ privateKey: CryptoKey;
700
+ publicKey: CryptoKey;
701
+ };
702
+ signingAlgorithm: CaSignAlgorithm;
703
+ }
704
+ /**
705
+ * Resolves a `CryptoKey | CaSigner` into the key pair and per-call `crypto`
706
+ * a CSR or self-signed-certificate generator needs.
707
+ *
708
+ * For a raw `CryptoKey` the public half is derived from the private one.
709
+ * For a {@link CaSigner} it comes from `getPublicKey()` — the only way to
710
+ * obtain it when the private key lives in an HSM and cannot be exported.
711
+ */
712
+ declare function resolveCaKeyPair(key: CryptoKey | CaSigner, baseCrypto?: Pick<Crypto, "subtle" | "getRandomValues">): Promise<ResolvedCaKeyPair>;
641
713
 
642
714
  /**
643
715
  * @param privateKeyInDerOrPem
@@ -657,8 +729,14 @@ declare function _coercePrivateKey(privateKey: unknown): Promise<KeyObject>;
657
729
  interface CreateCertificateFromCsrOptions {
658
730
  /** The CSR to sign, PEM or DER encoded. */
659
731
  csr: string | BufferSource;
660
- /** The issuing CA's subject, e.g. `"CN=MyCA"`. */
661
- issuerName: string;
732
+ /**
733
+ * The issuing CA's subject. Prefer passing the issuer's parsed
734
+ * `subjectName` (`X509Certificate.subjectName`, or the CSR's own for a
735
+ * self-signed root) over a string: re-parsing a string form can change
736
+ * the DER encoding, and an issuer that is not byte-identical to the
737
+ * issuer certificate's subject breaks chain building.
738
+ */
739
+ issuerName: x509.X509CertificateCreateParamsName;
662
740
  /** The issuing CA's public key, used to derive the Authority Key Identifier extension. */
663
741
  issuerPublicKey: PublicKeyType;
664
742
  /** The issuing CA's signing key — a raw key, or an HSM/KMS-backed {@link CaSigner}. */
@@ -691,7 +769,13 @@ declare function createCertificateFromCsr(options: CreateCertificateFromCsrOptio
691
769
  }>;
692
770
 
693
771
  interface CreateCertificateSigningRequestOptions {
694
- privateKey: CryptoKey;
772
+ /**
773
+ * The requester's key. A raw `CryptoKey`, or a {@link CaSigner} when the
774
+ * private key lives in an HSM/KMS and cannot be exported - the public
775
+ * half is then taken from `getPublicKey()` and the proof-of-possession
776
+ * signature is produced by `sign()`.
777
+ */
778
+ privateKey: CryptoKey | CaSigner;
695
779
  notBefore?: Date;
696
780
  notAfter?: Date;
697
781
  validity?: number;
@@ -714,8 +798,12 @@ interface CreateCrlEntryOptions {
714
798
  invalidity?: Date;
715
799
  }
716
800
  interface CreateCrlOptions {
717
- /** The issuing CA's subject, e.g. `"CN=MyCA"`. */
718
- issuerName: string;
801
+ /**
802
+ * The issuing CA's subject. Prefer the issuer certificate's parsed
803
+ * `subjectName` over a string: a CRL whose issuer is not byte-identical
804
+ * to the issuer certificate's subject will not be matched to it.
805
+ */
806
+ issuerName: x509.X509CertificateCreateParamsName;
719
807
  /** The issuing CA's public key, used to derive the Authority Key Identifier extension. */
720
808
  issuerPublicKey: PublicKeyType;
721
809
  /** The issuing CA's signing key — a raw key, or an HSM/KMS-backed {@link CaSigner}. */
@@ -952,4 +1040,4 @@ declare const asn1: {
952
1040
  readSignatureValueBin: typeof readSignatureValueBin;
953
1041
  };
954
1042
 
955
- export { type AttributeTypeAndValue, type AuthorityInformationAccess, type AuthorityKeyIdentifier, type BasicConstraints, type CaSignAlgorithm, type CaSigner, type Certificate, type CertificateExtension, type CertificateInfo, type CertificateInternals, type CertificatePEM, CertificatePurpose, type CertificateRevocationList, type CertificateRevocationListInfo, type CertificateSerialNumber, type CertificateSigningRequestInfo, type ComputeDerivedKeysOptions, type CreateCertificateFromCsrOptions, type CreateCrlEntryOptions, type CreateCrlOptions, type CreateSelfSignCertificateOptions, type DER, type DERContentType, type DerivedKeys, type DirectoryName, type DistinguishedNameAttribute, type ExtensionRequest, type Extensions, type KeyExportOptions, type KeyObject, LocalPrivateKeySigner, type Name, type Nonce, type PEM, PaddingAlgorithm, PfxIntegrityError, PfxMalformedError, Pkcs12UnsupportedAlgorithmError, type PrivateKey, type PrivateKeyInternals, type PrivateKeyPEM, PrivateKeyPassphraseRequiredError, type PublicKey, type PublicKeyLength, type PublicKeyPEM, RSA_PKCS1_OAEP_PADDING, RSA_PKCS1_PADDING, type ResolvedCaSigningKey, type RevocationExtensionsParams, type RevokedCertificate, type Signature, Subject, type SubjectAltName, type SubjectOptions, type SubjectPublicKey, type SubjectPublicKeyInfo, type TBSCertList, type TbsCertificate, type Validity, type VerifyChunkSignatureOptions, type VerifyMessageChunkSignatureOptions, type Version, type WebCryptoFromSigner, type X509ExtKeyUsage, type X509KeyUsage, type _VerifyStatus, _coercePrivateKey, asn1, buildAuthorityKeyIdentifierFromIssuer, buildCrlNumberExtension, buildRevocationExtensions, certificateMatchesPrivateKey, clearExploreCertificateCache, coerceCertificate, coerceCertificatePem, coercePEMorDerToPrivateKey, coercePrivateKeyPem, coercePublicKeyPem, coerceRsaPublicKeyPem, combine_der, computeDerivedKeys, computePaddingFooter, convertPEMtoDER, createCertificateFromCsr, createCertificateSigningRequest, createCrl, createPrivateKeyFromNodeJSCrypto, createSelfSignedCertificate, decryptBufferWithDerivedKeys, derToPrivateKey, encryptBufferWithDerivedKeys, exploreAsn1, exploreCertificate, exploreCertificateInfo, exploreCertificateRevocationList, exploreCertificateSigningRequest, explorePrivateKey, extractPublicKeyFromCertificate, extractPublicKeyFromCertificateSync, generateKeyPair, generatePrivateKey, getCrypto, hexDump, identifyDERContent, identifyPemType, isCrlIssuedByCertificate, isKeyObject, makeMessageChunkSignature, makeMessageChunkSignatureWithDerivedKeys, makePrivateKeyFromPem, makePrivateKeyThumbPrint, makePseudoRandomBuffer, makeSHA1Thumbprint, pemToPrivateKey, privateDecrypt, privateDecrypt_long, privateDecrypt_native, privateKeyToCryptoKey, privateKeyToPEM, publicEncrypt, publicEncrypt_long, publicEncrypt_native, publicKeyAndPrivateKeyMatches, readCertificationRequestInfo, readExtension, readNameForCrl, readTbsCertificate, reduceLength, removePadding, removeTrailingLF, resolveCaSigningKey, rsaLengthPrivateKey, rsaLengthPublicKey, rsaLengthRsaPublicKey, split_der, toPem, toPem2, verifyCertificateChain, verifyCertificateOrClrSignature, verifyCertificateRevocationListSignature, verifyCertificateSignature, verifyChunkSignature, verifyChunkSignatureWithDerivedKeys, verifyCrlIssuedByCertificate, verifyMessageChunkSignature, verify_certificate_der_structure, webCryptoFromSigner };
1043
+ export { type AttributeTypeAndValue, type AuthorityInformationAccess, type AuthorityKeyIdentifier, type BasicConstraints, type CaSignAlgorithm, type CaSigner, type Certificate, type CertificateExtension, type CertificateInfo, type CertificateInternals, type CertificatePEM, CertificatePurpose, type CertificateRevocationList, type CertificateRevocationListInfo, type CertificateSerialNumber, type CertificateSigningRequestInfo, type ComputeDerivedKeysOptions, type CreateCertificateFromCsrOptions, type CreateCrlEntryOptions, type CreateCrlOptions, type CreateSelfSignCertificateOptions, type DER, type DERContentType, type DerivedKeys, type DirectoryName, type DistinguishedNameAttribute, type ExtensionRequest, type Extensions, type KeyExportOptions, type KeyObject, LocalPrivateKeySigner, type Name, type Nonce, type PEM, PaddingAlgorithm, PfxIntegrityError, PfxMalformedError, Pkcs12UnsupportedAlgorithmError, type PrivateKey, type PrivateKeyInternals, type PrivateKeyPEM, PrivateKeyPassphraseRequiredError, type PublicKey, type PublicKeyLength, type PublicKeyPEM, RSA_PKCS1_OAEP_PADDING, RSA_PKCS1_PADDING, type ResolvedCaKeyPair, type ResolvedCaSigningKey, type RevocationExtensionsParams, type RevokedCertificate, type Signature, Subject, type SubjectAltName, type SubjectOptions, type SubjectPublicKey, type SubjectPublicKeyInfo, type TBSCertList, type TbsCertificate, type Validity, type VerifyChunkSignatureOptions, type VerifyMessageChunkSignatureOptions, type Version, type WebCryptoFromSigner, type X509ExtKeyUsage, type X509KeyUsage, type _VerifyStatus, _coercePrivateKey, asn1, buildAuthorityKeyIdentifierFromIssuer, buildCrlNumberExtension, buildRevocationExtensions, certificateMatchesPrivateKey, clearExploreCertificateCache, coerceCertificate, coerceCertificatePem, coercePEMorDerToPrivateKey, coercePrivateKeyPem, coercePublicKeyPem, coerceRsaPublicKeyPem, combine_der, computeDerivedKeys, computePaddingFooter, convertPEMtoDER, createCertificateFromCsr, createCertificateSigningRequest, createCrl, createPrivateKeyFromNodeJSCrypto, createSelfSignedCertificate, decryptBufferWithDerivedKeys, derToPrivateKey, ecdsaSignatureDerToP1363, encryptBufferWithDerivedKeys, exploreAsn1, exploreCertificate, exploreCertificateInfo, exploreCertificateRevocationList, exploreCertificateSigningRequest, explorePrivateKey, extractPublicKeyFromCertificate, extractPublicKeyFromCertificateSync, generateKeyPair, generatePrivateKey, getCrypto, hexDump, identifyDERContent, identifyPemType, isCaSigner, isCrlIssuedByCertificate, isKeyObject, makeMessageChunkSignature, makeMessageChunkSignatureWithDerivedKeys, makePrivateKeyFromPem, makePrivateKeyThumbPrint, makePseudoRandomBuffer, makeSHA1Thumbprint, pemToPrivateKey, privateDecrypt, privateDecrypt_long, privateDecrypt_native, privateKeyToCryptoKey, privateKeyToPEM, publicEncrypt, publicEncrypt_long, publicEncrypt_native, publicKeyAndPrivateKeyMatches, readCertificationRequestInfo, readExtension, readNameForCrl, readTbsCertificate, reduceLength, removePadding, removeTrailingLF, resolveCaKeyPair, resolveCaSigningKey, rsaLengthPrivateKey, rsaLengthPublicKey, rsaLengthRsaPublicKey, split_der, toPem, toPem2, verifyCertificateChain, verifyCertificateOrClrSignature, verifyCertificateRevocationListSignature, verifyCertificateSignature, verifyChunkSignature, verifyChunkSignatureWithDerivedKeys, verifyCrlIssuedByCertificate, verifyMessageChunkSignature, verify_certificate_der_structure, webCryptoFromSigner };
package/dist/index_web.js CHANGED
@@ -47656,6 +47656,21 @@ function exploreCertificateRevocationList(crl) {
47656
47656
  // ../node-opcua-crypto/source/verify_certificate_signature.ts
47657
47657
  init_inject_buffer();
47658
47658
  init_node_crypto_shim();
47659
+ var ECDSA_SIGNATURE_DIGESTS = {
47660
+ "1.2.840.10045.4.1": "sha1",
47661
+ "1.2.840.10045.4.3.1": "sha224",
47662
+ "1.2.840.10045.4.3.2": "sha256",
47663
+ "1.2.840.10045.4.3.3": "sha384",
47664
+ "1.2.840.10045.4.3.4": "sha512"
47665
+ };
47666
+ function digestForSignatureAlgorithm(identifier) {
47667
+ const ecdsaDigest = ECDSA_SIGNATURE_DIGESTS[identifier];
47668
+ if (ecdsaDigest) {
47669
+ return ecdsaDigest;
47670
+ }
47671
+ const named = /sha-?(1|224|256|384|512)/i.exec(identifier);
47672
+ return named ? `sha${named[1]}` : identifier;
47673
+ }
47659
47674
  function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
47660
47675
  const block_info = readTag(certificateOrCrl, 0);
47661
47676
  const blocks = readStruct(certificateOrCrl, block_info);
@@ -47664,7 +47679,7 @@ function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
47664
47679
  const signatureValue = readSignatureValueBin(certificateOrCrl, blocks[2]);
47665
47680
  const p = split_der(parentCertificate)[0];
47666
47681
  const certPem = toPem(p, "CERTIFICATE");
47667
- const verify = createVerify(signatureAlgorithm.identifier);
47682
+ const verify = createVerify(digestForSignatureAlgorithm(signatureAlgorithm.identifier));
47668
47683
  verify.update(bufferToBeSigned);
47669
47684
  verify.end();
47670
47685
  return verify.verify(certPem, signatureValue);
@@ -61727,6 +61742,118 @@ function buildCrlNumberExtension(crlNumber) {
61727
61742
 
61728
61743
  // ../node-opcua-crypto/source/x509/ca_signer.ts
61729
61744
  init_inject_buffer();
61745
+
61746
+ // ../node-opcua-crypto/source/x509/_build_public_key.ts
61747
+ init_inject_buffer();
61748
+ async function buildPublicKey(privateKey) {
61749
+ const crypto4 = getCrypto();
61750
+ const jwk = await crypto4.subtle.exportKey("jwk", privateKey);
61751
+ delete jwk.d;
61752
+ delete jwk.dp;
61753
+ delete jwk.dq;
61754
+ delete jwk.q;
61755
+ delete jwk.qi;
61756
+ jwk.key_ops = [
61757
+ "encrypt",
61758
+ "sign"
61759
+ // "wrapKey"
61760
+ ];
61761
+ const publicKey = await crypto4.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, true, [
61762
+ // "encrypt",
61763
+ // "sign",
61764
+ // "wrapKey",
61765
+ ]);
61766
+ return publicKey;
61767
+ }
61768
+
61769
+ // ../node-opcua-crypto/source/x509/ca_signer.ts
61770
+ var ECDSA_COORDINATE_BYTES = {
61771
+ "P-256": 32,
61772
+ "P-384": 48,
61773
+ // 521 bits is not a byte multiple, so each coordinate occupies 66 bytes
61774
+ "P-521": 66
61775
+ };
61776
+ function asBytes(source) {
61777
+ if (source instanceof Uint8Array) {
61778
+ return source;
61779
+ }
61780
+ if (ArrayBuffer.isView(source)) {
61781
+ return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
61782
+ }
61783
+ return new Uint8Array(source);
61784
+ }
61785
+ function readDerLength(bytes, cursor) {
61786
+ const first = bytes[cursor.offset++];
61787
+ if (first === void 0) {
61788
+ throw new Error("malformed ECDSA signature: truncated length");
61789
+ }
61790
+ if (first < 128) {
61791
+ return first;
61792
+ }
61793
+ const byteCount = first & 127;
61794
+ if (byteCount === 0 || byteCount > 4) {
61795
+ throw new Error(`malformed ECDSA signature: unsupported length encoding (0x${first.toString(16)})`);
61796
+ }
61797
+ let length = 0;
61798
+ for (let index = 0; index < byteCount; index++) {
61799
+ const byte = bytes[cursor.offset++];
61800
+ if (byte === void 0) {
61801
+ throw new Error("malformed ECDSA signature: truncated length");
61802
+ }
61803
+ length = length * 256 + byte;
61804
+ }
61805
+ return length;
61806
+ }
61807
+ function readDerInteger(bytes, cursor) {
61808
+ if (bytes[cursor.offset++] !== 2) {
61809
+ throw new Error("malformed ECDSA signature: expected an INTEGER");
61810
+ }
61811
+ const length = readDerLength(bytes, cursor);
61812
+ const end = cursor.offset + length;
61813
+ if (length === 0 || end > bytes.length) {
61814
+ throw new Error("malformed ECDSA signature: INTEGER runs past the end");
61815
+ }
61816
+ const value = bytes.subarray(cursor.offset, end);
61817
+ cursor.offset = end;
61818
+ return value;
61819
+ }
61820
+ function toFixedWidth(value, size, label) {
61821
+ let start = 0;
61822
+ while (start < value.length - 1 && value[start] === 0) {
61823
+ start++;
61824
+ }
61825
+ const magnitude = value.subarray(start);
61826
+ if (magnitude.length > size) {
61827
+ throw new Error(`malformed ECDSA signature: ${label} is ${magnitude.length} bytes, too long for a ${size * 8}-bit curve`);
61828
+ }
61829
+ const padded = new Uint8Array(size);
61830
+ padded.set(magnitude, size - magnitude.length);
61831
+ return padded;
61832
+ }
61833
+ function ecdsaSignatureDerToP1363(derSignature, namedCurve) {
61834
+ const size = ECDSA_COORDINATE_BYTES[namedCurve];
61835
+ if (size === void 0) {
61836
+ throw new Error(`unsupported curve ${namedCurve}`);
61837
+ }
61838
+ const bytes = asBytes(derSignature);
61839
+ const cursor = { offset: 0 };
61840
+ if (bytes[cursor.offset++] !== 48) {
61841
+ throw new Error("malformed ECDSA signature: expected a SEQUENCE (is it already in r||s form?)");
61842
+ }
61843
+ const sequenceLength = readDerLength(bytes, cursor);
61844
+ if (cursor.offset + sequenceLength !== bytes.length) {
61845
+ throw new Error("malformed ECDSA signature: SEQUENCE length does not match the data");
61846
+ }
61847
+ const r = toFixedWidth(readDerInteger(bytes, cursor), size, "r");
61848
+ const s = toFixedWidth(readDerInteger(bytes, cursor), size, "s");
61849
+ if (cursor.offset !== bytes.length) {
61850
+ throw new Error("malformed ECDSA signature: trailing data after s");
61851
+ }
61852
+ const p1363 = new Uint8Array(size * 2);
61853
+ p1363.set(r, 0);
61854
+ p1363.set(s, size);
61855
+ return p1363.buffer;
61856
+ }
61730
61857
  var LocalPrivateKeySigner = class {
61731
61858
  algorithm;
61732
61859
  #privateKey;
@@ -61790,6 +61917,21 @@ async function resolveCaSigningKey(signingKey, baseCrypto = getCrypto()) {
61790
61917
  }
61791
61918
  return { crypto: baseCrypto, signingKey };
61792
61919
  }
61920
+ async function resolveCaKeyPair(key, baseCrypto = getCrypto()) {
61921
+ if (isCaSigner(key)) {
61922
+ const adapted = await webCryptoFromSigner(key, baseCrypto);
61923
+ return {
61924
+ crypto: adapted.crypto,
61925
+ keys: { privateKey: adapted.privateKeyHandle, publicKey: adapted.publicKey },
61926
+ signingAlgorithm: key.algorithm
61927
+ };
61928
+ }
61929
+ return {
61930
+ crypto: baseCrypto,
61931
+ keys: { privateKey: key, publicKey: await buildPublicKey(key) },
61932
+ signingAlgorithm: { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }
61933
+ };
61934
+ }
61793
61935
 
61794
61936
  // ../node-opcua-crypto/source/x509/coerce_private_key.ts
61795
61937
  init_inject_buffer();
@@ -61918,6 +62060,18 @@ function getAttributes(purpose) {
61918
62060
  }
61919
62061
 
61920
62062
  // ../node-opcua-crypto/source/x509/create_certificate_from_csr.ts
62063
+ var keyUsageIssuedApplication = x509_es_exports.KeyUsageFlags.digitalSignature | x509_es_exports.KeyUsageFlags.nonRepudiation | x509_es_exports.KeyUsageFlags.keyEncipherment | x509_es_exports.KeyUsageFlags.dataEncipherment | x509_es_exports.KeyUsageFlags.keyAgreement;
62064
+ function getIssuedAttributes(purpose) {
62065
+ if (purpose === 1 /* ForCertificateAuthority */) {
62066
+ return getAttributes(purpose);
62067
+ }
62068
+ return {
62069
+ nsComment: "Certificate generated by Node-OPCUA Certificate utility V2",
62070
+ basicConstraints: new x509_es_exports.BasicConstraintsExtension(false, void 0, true),
62071
+ keyUsageExtension: [x509_es_exports.ExtendedKeyUsage.serverAuth, x509_es_exports.ExtendedKeyUsage.clientAuth],
62072
+ usages: keyUsageIssuedApplication
62073
+ };
62074
+ }
61921
62075
  async function createCertificateFromCsr(options) {
61922
62076
  const crypto4 = getCrypto();
61923
62077
  const csr = new x509_es_exports.Pkcs10CertificateRequest(options.csr);
@@ -61925,7 +62079,7 @@ async function createCertificateFromCsr(options) {
61925
62079
  if (!csrIsValid) {
61926
62080
  throw new Error("createCertificateFromCsr: the CSR signature does not verify \u2014 refusing to sign an unproven key");
61927
62081
  }
61928
- const { basicConstraints, keyUsageExtension, usages } = getAttributes(options.purpose);
62082
+ const { basicConstraints, keyUsageExtension, usages } = getIssuedAttributes(options.purpose);
61929
62083
  const alternativeNameExtensions = [];
61930
62084
  for (const d of options.dns ?? []) {
61931
62085
  alternativeNameExtensions.push({ type: "dns", value: d });
@@ -61938,11 +62092,17 @@ async function createCertificateFromCsr(options) {
61938
62092
  }
61939
62093
  const extensions = [
61940
62094
  basicConstraints,
61941
- new x509_es_exports.ExtendedKeyUsageExtension(keyUsageExtension, true),
62095
+ // RFC 5280 4.2.1.12: extendedKeyUsage SHALL contain at least one
62096
+ // KeyPurposeId. getAttributes yields an empty list for a CA
62097
+ // certificate, so emitting it unconditionally would produce an
62098
+ // empty critical extension that a strict validator must reject.
62099
+ ...keyUsageExtension.length > 0 ? [new x509_es_exports.ExtendedKeyUsageExtension(keyUsageExtension, true)] : [],
61942
62100
  new x509_es_exports.KeyUsagesExtension(usages, true),
61943
62101
  await x509_es_exports.SubjectKeyIdentifierExtension.create(csr.publicKey),
61944
62102
  await buildAuthorityKeyIdentifierFromIssuer(options.issuerPublicKey, crypto4),
61945
- new x509_es_exports.SubjectAlternativeNameExtension(alternativeNameExtensions),
62103
+ // an empty SubjectAlternativeName is an empty GeneralNames sequence,
62104
+ // which RFC 5280 4.2.1.6 does not permit - omit the extension instead
62105
+ ...alternativeNameExtensions.length > 0 ? [new x509_es_exports.SubjectAlternativeNameExtension(alternativeNameExtensions)] : [],
61946
62106
  ...options.revocation ? buildRevocationExtensions(options.revocation) : []
61947
62107
  ];
61948
62108
  const notBefore = options.notBefore ?? /* @__PURE__ */ new Date();
@@ -61968,31 +62128,6 @@ async function createCertificateFromCsr(options) {
61968
62128
 
61969
62129
  // ../node-opcua-crypto/source/x509/create_certificate_signing_request.ts
61970
62130
  init_inject_buffer();
61971
-
61972
- // ../node-opcua-crypto/source/x509/_build_public_key.ts
61973
- init_inject_buffer();
61974
- async function buildPublicKey(privateKey) {
61975
- const crypto4 = getCrypto();
61976
- const jwk = await crypto4.subtle.exportKey("jwk", privateKey);
61977
- delete jwk.d;
61978
- delete jwk.dp;
61979
- delete jwk.dq;
61980
- delete jwk.q;
61981
- delete jwk.qi;
61982
- jwk.key_ops = [
61983
- "encrypt",
61984
- "sign"
61985
- // "wrapKey"
61986
- ];
61987
- const publicKey = await crypto4.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, true, [
61988
- // "encrypt",
61989
- // "sign",
61990
- // "wrapKey",
61991
- ]);
61992
- return publicKey;
61993
- }
61994
-
61995
- // ../node-opcua-crypto/source/x509/create_certificate_signing_request.ts
61996
62131
  async function createCertificateSigningRequest({
61997
62132
  privateKey,
61998
62133
  subject,
@@ -62001,19 +62136,7 @@ async function createCertificateSigningRequest({
62001
62136
  applicationUri,
62002
62137
  purpose
62003
62138
  }) {
62004
- const crypto4 = getCrypto();
62005
- const modulusLength = 2048;
62006
- const alg = {
62007
- name: "RSASSA-PKCS1-v1_5",
62008
- hash: { name: "SHA-256" },
62009
- publicExponent: new Uint8Array([1, 0, 1]),
62010
- modulusLength
62011
- };
62012
- const publicKey = await buildPublicKey(privateKey);
62013
- const keys = {
62014
- privateKey,
62015
- publicKey
62016
- };
62139
+ const { crypto: crypto4, keys, signingAlgorithm } = await resolveCaKeyPair(privateKey);
62017
62140
  const alternativeNameExtensions = [];
62018
62141
  for (const d of dns ?? []) {
62019
62142
  alternativeNameExtensions.push({ type: "dns", value: d });
@@ -62032,7 +62155,7 @@ async function createCertificateSigningRequest({
62032
62155
  {
62033
62156
  name,
62034
62157
  keys,
62035
- signingAlgorithm: alg,
62158
+ signingAlgorithm,
62036
62159
  extensions: [
62037
62160
  basicConstraints,
62038
62161
  new x509_es_exports.KeyUsagesExtension(usages, true),
@@ -62136,7 +62259,8 @@ async function createSelfSignedCertificate({
62136
62259
  new x509_es_exports.Extension(ID_NETSCAPE_COMMENT, false, AsnConvert.serialize(AsnUtf8StringConverter.toASN(nsComment))),
62137
62260
  // new x509.BasicConstraintsExtension(true, 2, true),
62138
62261
  basicConstraints,
62139
- new x509_es_exports.ExtendedKeyUsageExtension(keyUsageExtension, true),
62262
+ // see RFC 5280 4.2.1.12 - an empty critical EKU is invalid
62263
+ ...keyUsageExtension.length > 0 ? [new x509_es_exports.ExtendedKeyUsageExtension(keyUsageExtension, true)] : [],
62140
62264
  new x509_es_exports.KeyUsagesExtension(usages, true),
62141
62265
  await x509_es_exports.SubjectKeyIdentifierExtension.create(keys.publicKey),
62142
62266
  await x509_es_exports.AuthorityKeyIdentifierExtension.create(keys.publicKey),
@@ -62409,6 +62533,7 @@ export {
62409
62533
  createSelfSignedCertificate,
62410
62534
  decryptBufferWithDerivedKeys,
62411
62535
  derToPrivateKey,
62536
+ ecdsaSignatureDerToP1363,
62412
62537
  encryptBufferWithDerivedKeys,
62413
62538
  exploreAsn1,
62414
62539
  exploreCertificate,
@@ -62424,6 +62549,7 @@ export {
62424
62549
  hexDump,
62425
62550
  identifyDERContent,
62426
62551
  identifyPemType,
62552
+ isCaSigner,
62427
62553
  isCrlIssuedByCertificate,
62428
62554
  isKeyObject,
62429
62555
  makeMessageChunkSignature,
@@ -62449,6 +62575,7 @@ export {
62449
62575
  reduceLength,
62450
62576
  removePadding,
62451
62577
  removeTrailingLF,
62578
+ resolveCaKeyPair,
62452
62579
  resolveCaSigningKey,
62453
62580
  rsaLengthPrivateKey,
62454
62581
  rsaLengthPublicKey,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-opcua-crypto-web",
3
- "version": "5.7.2",
3
+ "version": "5.9.0",
4
4
  "type": "module",
5
5
  "description": "Pre-bundled, zero-config browser build of node-opcua-crypto",
6
6
  "//why": "This package exists so node-opcua-crypto can stay lean for Node. The pre-bundled browser build inlines its polyfills (crypto-browserify, stream-browserify, ...) and weighs ~344 KB gzip - more than the entire node-opcua-crypto tarball. Shipping it there would make every Node consumer download a browser bundle they never import. Browser consumers install this package explicitly, or let node-opcua-crypto's \"browser\" export condition redirect to it (see node-opcua-crypto/browser/index.js).",
@@ -44,7 +44,7 @@
44
44
  "crypto-browserify": "^3.12.1",
45
45
  "esbuild": "^0.28.2",
46
46
  "events": "^3.3.0",
47
- "node-opcua-crypto": "^5.7.0",
47
+ "node-opcua-crypto": "^5.9.0",
48
48
  "path-browserify": "^1.0.1",
49
49
  "process": "^0.11.10",
50
50
  "stream-browserify": "^3.0.0",
@@ -67,5 +67,5 @@
67
67
  "LICENSE",
68
68
  "README.md"
69
69
  ],
70
- "gitHead": "1d0adf954c8c34cac820e05d982b029f05884e0c"
70
+ "gitHead": "e6021c6d3b602b24126b98cab2807df6786ad981"
71
71
  }