node-opcua-crypto-web 5.5.0 → 5.7.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.
@@ -1,5 +1,8 @@
1
1
  import __crypto, { KeyLike } from 'node:crypto';
2
+ import { Crypto as Crypto$1 } from '@peculiar/webcrypto';
2
3
  import * as x509 from '@peculiar/x509';
4
+ import { PublicKeyType, X509CrlReason } from '@peculiar/x509';
5
+ export { x509 };
3
6
 
4
7
  declare const createPrivateKeyFromNodeJSCrypto: typeof __crypto.createPrivateKey;
5
8
  type KeyFormat = "pem" | "der" | "jwk";
@@ -26,6 +29,42 @@ type PrivateKey = {
26
29
  hidden: KeyObject;
27
30
  };
28
31
  type PublicKey = KeyObject;
32
+ /**
33
+ * Thrown when a private key is encrypted (PKCS#8 `ENCRYPTED PRIVATE KEY`)
34
+ * and the caller did not supply a passphrase to decrypt it. Reading an
35
+ * encrypted key without a passphrase always fails closed — it never falls
36
+ * back to treating the key as unencrypted or skipping it.
37
+ */
38
+ declare class PrivateKeyPassphraseRequiredError extends Error {
39
+ constructor(message?: string);
40
+ }
41
+ /**
42
+ * PKCS#12 integrity check failed: the password is wrong, or the file has
43
+ * been corrupted or tampered with. Raised on a `MacData` HMAC mismatch and
44
+ * on a bag-decryption failure (both are the observable symptom of a wrong
45
+ * password; PKCS#12 does not let the two be distinguished reliably).
46
+ */
47
+ declare class PfxIntegrityError extends Error {
48
+ constructor(message?: string);
49
+ }
50
+ /**
51
+ * The PKCS#12 file parsed and (where applicable) decrypted correctly, but
52
+ * is not a bundle this API can represent — for example it carries no
53
+ * private key, or no certificate. Distinct from {@link PfxIntegrityError}:
54
+ * the password was fine; the content is what is missing or malformed.
55
+ */
56
+ declare class PfxMalformedError extends Error {
57
+ constructor(message: string);
58
+ }
59
+ /**
60
+ * The PKCS#12 file uses an encryption or digest algorithm this build does
61
+ * not implement (for example the legacy RC2-40 PBE scheme, which neither
62
+ * WebCrypto nor a default Node build exposes). Not a data error — the file
63
+ * may be perfectly valid; it just needs a capability this code lacks.
64
+ */
65
+ declare class Pkcs12UnsupportedAlgorithmError extends Error {
66
+ constructor(message: string);
67
+ }
29
68
  type Nonce = Buffer;
30
69
  type PEM = string;
31
70
  type DER = Buffer;
@@ -469,13 +508,188 @@ declare function verifyCertificateChain(certificateChain: Certificate[]): Promis
469
508
  reason: string;
470
509
  }>;
471
510
 
472
- declare function coercePEMorDerToPrivateKey(privateKeyInDerOrPem: string | Buffer): PrivateKey;
511
+ declare function getCrypto(): Crypto$1 | typeof __crypto;
512
+
513
+ /**
514
+ * Authority Key Identifier extension identifying the issuer by its public
515
+ * key (`keyid`), matching what {@link createSelfSignedCertificate} already
516
+ * does for the self-signed case, and what openssl's
517
+ * `authorityKeyIdentifier = keyid:always` produces for the issued case.
518
+ */
519
+ declare function buildAuthorityKeyIdentifierFromIssuer(issuerPublicKey: PublicKeyType, crypto?: Crypto): Promise<x509.AuthorityKeyIdentifierExtension>;
520
+ /** Opt-in CRL Distribution Point / Authority Info Access URLs for a certificate. */
521
+ interface RevocationExtensionsParams {
522
+ crlDistributionUrl?: string;
523
+ ocspResponderUrl?: string;
524
+ caIssuersUrl?: string;
525
+ }
526
+ /**
527
+ * Builds the CDP (`crlDistributionUrl`) and AIA (`ocspResponderUrl` /
528
+ * `caIssuersUrl`) extensions for a certificate, mirroring the
529
+ * `$ENV::CDP_URL` / `$ENV::AIA_VALUE` opt-in extensions the openssl-backed
530
+ * CA templates emit. Each extension is included only when at least one of
531
+ * its values is set.
532
+ */
533
+ declare function buildRevocationExtensions(params: RevocationExtensionsParams): x509.Extension[];
534
+ /** The CRL Number extension (RFC 5280 §5.2.3), a plain monotonically-increasing counter. */
535
+ declare function buildCrlNumberExtension(crlNumber: number | bigint): x509.Extension;
536
+
537
+ /**
538
+ * The signing algorithm a {@link CaSigner} operates under. This travels with
539
+ * the signer rather than being inferred from a key, because an HSM/KMS-backed
540
+ * signer (e.g. Google Cloud KMS) exposes no key material to inspect — only a
541
+ * public key and a `sign` operation whose algorithm the caller must already
542
+ * know.
543
+ */
544
+ type CaSignAlgorithm = {
545
+ name: "RSASSA-PKCS1-v1_5";
546
+ hash: {
547
+ name: "SHA-256" | "SHA-384" | "SHA-512";
548
+ };
549
+ } | {
550
+ name: "ECDSA";
551
+ hash: {
552
+ name: "SHA-256" | "SHA-384" | "SHA-512";
553
+ };
554
+ };
555
+ /**
556
+ * Abstraction over "something that can produce a certificate/CRL signature",
557
+ * without ever exposing private key material.
558
+ *
559
+ * This is deliberately shaped after Google Cloud KMS (and similar HSM APIs):
560
+ * the caller builds the to-be-signed bytes locally and hands them to
561
+ * {@link sign}; the signer never returns, and this interface never asks for,
562
+ * the private key itself. A local PEM/DER key is adapted to this interface
563
+ * via {@link LocalPrivateKeySigner}; a KMS key is adapted by wrapping its
564
+ * `getPublicKey` / `asymmetricSign` calls the same way.
565
+ */
566
+ interface CaSigner {
567
+ /** The algorithm this signer signs with — declared, not inferred. */
568
+ readonly algorithm: CaSignAlgorithm;
569
+ /** The public key, SPKI-encoded DER. */
570
+ getPublicKey(): Promise<ArrayBuffer>;
571
+ /**
572
+ * Sign `tbs` (the to-be-signed bytes, e.g. a certificate or CRL's TBS
573
+ * DER encoding) and return the raw signature bytes.
574
+ */
575
+ sign(tbs: Uint8Array): Promise<ArrayBuffer>;
576
+ }
577
+ /**
578
+ * Adapts an in-process key pair (e.g. one produced by {@link generateKeyPair}
579
+ * or read from disk via {@link pemToPrivateKey}) to the {@link CaSigner}
580
+ * interface, so CA-signing code only ever has to know about one signer
581
+ * shape regardless of whether the key lives on disk or in an HSM.
582
+ */
583
+ declare class LocalPrivateKeySigner implements CaSigner {
584
+ #private;
585
+ readonly algorithm: CaSignAlgorithm;
586
+ constructor(keys: {
587
+ privateKey: CryptoKey;
588
+ publicKey: CryptoKey;
589
+ }, algorithm: CaSignAlgorithm, crypto?: Pick<Crypto, "subtle">);
590
+ getPublicKey(): Promise<ArrayBuffer>;
591
+ sign(tbs: Uint8Array): Promise<ArrayBuffer>;
592
+ }
593
+ /**
594
+ * A `Crypto`-shaped object plus the key handles needed to drive
595
+ * `@peculiar/x509`'s certificate/CSR/CRL generators against a {@link CaSigner}
596
+ * instead of a real in-process private key.
597
+ */
598
+ interface WebCryptoFromSigner {
599
+ /**
600
+ * Pass this as the generator's per-call `crypto` argument (every
601
+ * `@peculiar/x509` generator accepts one). Every member other than
602
+ * `subtle.sign` is delegated to the underlying crypto provider
603
+ * unchanged; `subtle.sign`, when called with {@link privateKeyHandle},
604
+ * is routed to `signer.sign(...)` instead of touching any private key
605
+ * material.
606
+ */
607
+ crypto: Crypto;
608
+ /**
609
+ * An opaque placeholder to pass as `keys.privateKey` to a generator.
610
+ * It carries no key material — it exists only so `crypto.subtle.sign`
611
+ * has something to recognize and route to the signer. Never pass it to
612
+ * anything other than the paired {@link crypto} object.
613
+ */
614
+ privateKeyHandle: CryptoKey;
615
+ /** The signer's public key, imported as a real, usable `CryptoKey`. */
616
+ publicKey: CryptoKey;
617
+ }
618
+ /**
619
+ * Build a `Crypto`-shaped adapter that routes signing through `signer`
620
+ * while delegating everything else (hashing, key import/export, random
621
+ * bytes) to `baseCrypto`. This lets `@peculiar/x509`'s certificate, CSR and
622
+ * CRL generators — which all accept crypto as a per-call argument rather
623
+ * than only a process-global one — sign with an HSM/KMS-backed key without
624
+ * that key ever existing as an in-process `CryptoKey`.
625
+ */
626
+ declare function webCryptoFromSigner(signer: CaSigner, baseCrypto?: Pick<Crypto, "subtle" | "getRandomValues">): Promise<WebCryptoFromSigner>;
627
+ /** The `crypto`/`signingKey` pair a `@peculiar/x509` generator needs, resolved from either a raw key or a {@link CaSigner}. */
628
+ interface ResolvedCaSigningKey {
629
+ crypto: Crypto;
630
+ signingKey: CryptoKey;
631
+ }
632
+ /**
633
+ * Resolves a `CryptoKey | CaSigner` union into the `{ crypto, signingKey }`
634
+ * pair a `@peculiar/x509` generator's `signingKey`/per-call `crypto`
635
+ * arguments need — a raw `CryptoKey` is passed through unchanged against
636
+ * `baseCrypto`; a {@link CaSigner} is adapted via {@link webCryptoFromSigner}.
637
+ * This is the single place CA-signing primitives (certificate, CSR, CRL
638
+ * generation) need to branch on which kind of signing key they were given.
639
+ */
640
+ declare function resolveCaSigningKey(signingKey: CryptoKey | CaSigner, baseCrypto?: Pick<Crypto, "subtle" | "getRandomValues">): Promise<ResolvedCaSigningKey>;
641
+
642
+ /**
643
+ * @param privateKeyInDerOrPem
644
+ * @param passphrase — required if the PEM is an encrypted PKCS#8 key
645
+ * (`-----BEGIN ENCRYPTED PRIVATE KEY-----`). Throws
646
+ * {@link PrivateKeyPassphraseRequiredError} if the key is encrypted and
647
+ * no passphrase is supplied. Unencrypted input is unaffected by this
648
+ * parameter.
649
+ */
650
+ declare function coercePEMorDerToPrivateKey(privateKeyInDerOrPem: string | Buffer, passphrase?: string | Buffer): PrivateKey;
473
651
  /**
474
652
  *
475
653
  * @private
476
654
  */
477
655
  declare function _coercePrivateKey(privateKey: unknown): Promise<KeyObject>;
478
656
 
657
+ interface CreateCertificateFromCsrOptions {
658
+ /** The CSR to sign, PEM or DER encoded. */
659
+ csr: string | BufferSource;
660
+ /** The issuing CA's subject, e.g. `"CN=MyCA"`. */
661
+ issuerName: string;
662
+ /** The issuing CA's public key, used to derive the Authority Key Identifier extension. */
663
+ issuerPublicKey: PublicKeyType;
664
+ /** The issuing CA's signing key — a raw key, or an HSM/KMS-backed {@link CaSigner}. */
665
+ signingKey: CryptoKey | CaSigner;
666
+ signingAlgorithm: CaSignAlgorithm;
667
+ /** Hexadecimal serial number. If omitted, a random one is generated. */
668
+ serialNumber?: string;
669
+ notBefore?: Date;
670
+ notAfter?: Date;
671
+ /** Validity in days from `notBefore`, used when `notAfter` is not given. Default 365. */
672
+ validity?: number;
673
+ purpose: CertificatePurpose;
674
+ dns?: string[];
675
+ ip?: string[];
676
+ applicationUri?: string;
677
+ revocation?: RevocationExtensionsParams;
678
+ }
679
+ /**
680
+ * Signs a certificate signing request with a CA key, producing an
681
+ * end-entity or subordinate-CA certificate — the primitive a native
682
+ * (non-openssl) `CaBackend` needs for `signCertificateRequest` and
683
+ * `signSubordinateCsr`.
684
+ *
685
+ * The CSR's own signature is always verified first: a CA must never sign a
686
+ * public key without proof the requester holds the matching private key.
687
+ */
688
+ declare function createCertificateFromCsr(options: CreateCertificateFromCsrOptions): Promise<{
689
+ cert: string;
690
+ der: ArrayBuffer;
691
+ }>;
692
+
479
693
  interface CreateCertificateSigningRequestOptions {
480
694
  privateKey: CryptoKey;
481
695
  notBefore?: Date;
@@ -492,6 +706,37 @@ declare function createCertificateSigningRequest({ privateKey, subject, dns, ip,
492
706
  der: x509.Pkcs10CertificateRequest;
493
707
  }>;
494
708
 
709
+ interface CreateCrlEntryOptions {
710
+ /** Hexadecimal serial number of the revoked certificate. */
711
+ serialNumber: string;
712
+ revocationDate?: Date;
713
+ reason?: X509CrlReason;
714
+ invalidity?: Date;
715
+ }
716
+ interface CreateCrlOptions {
717
+ /** The issuing CA's subject, e.g. `"CN=MyCA"`. */
718
+ issuerName: string;
719
+ /** The issuing CA's public key, used to derive the Authority Key Identifier extension. */
720
+ issuerPublicKey: PublicKeyType;
721
+ /** The issuing CA's signing key — a raw key, or an HSM/KMS-backed {@link CaSigner}. */
722
+ signingKey: CryptoKey | CaSigner;
723
+ signingAlgorithm: CaSignAlgorithm;
724
+ /** Monotonically increasing CRL number (RFC 5280 §5.2.3). */
725
+ crlNumber: number | bigint;
726
+ thisUpdate?: Date;
727
+ /** Default: 30 days after `thisUpdate`. */
728
+ nextUpdate?: Date;
729
+ entries: CreateCrlEntryOptions[];
730
+ }
731
+ /**
732
+ * Builds and signs a Certificate Revocation List — the primitive a native
733
+ * (non-openssl) `CaBackend` needs for `revoke`/`regenerateCrl`.
734
+ */
735
+ declare function createCrl(options: CreateCrlOptions): Promise<{
736
+ crl: string;
737
+ der: ArrayBuffer;
738
+ }>;
739
+
495
740
  declare function generateKeyPair(modulusLength?: 1024 | 2048 | 3072 | 4096): Promise<CryptoKeyPair>;
496
741
  /**
497
742
  * generate a pair of private/public keys of length 1024,2048, 3072, or 4096 bits
@@ -608,6 +853,15 @@ declare function rsaLengthPrivateKey(key: PrivateKey): number;
608
853
  */
609
854
  declare function toPem2(raw_key: Buffer | string | KeyObject | PrivateKey, pem: string): string;
610
855
  declare function coercePrivateKeyPem(privateKey: PrivateKey): PrivateKeyPEM;
856
+ /**
857
+ * Bridges the Node-side {@link PrivateKey} envelope (from
858
+ * {@link readPrivateKey}/{@link readPrivateKeyAsync}, disk + optional
859
+ * passphrase) into a WebCrypto `CryptoKey`, so code that wants to hand a
860
+ * key to a `@peculiar/x509` generator — or wrap it in a
861
+ * {@link LocalPrivateKeySigner} — only has to deal with one key type. A
862
+ * `CryptoKey` passed in is returned unchanged.
863
+ */
864
+ declare function privateKeyToCryptoKey(key: PrivateKey | CryptoKey): Promise<CryptoKey>;
611
865
  declare function coercePublicKeyPem(publicKey: PublicKey | PublicKeyPEM): PublicKeyPEM;
612
866
  declare function coerceRsaPublicKeyPem(publicKey: PublicKey | KeyObject | PublicKeyPEM): PublicKeyPEM;
613
867
  declare function rsaLengthPublicKey(key: PublicKeyPEM | PublicKey): number;
@@ -698,4 +952,4 @@ declare const asn1: {
698
952
  readSignatureValueBin: typeof readSignatureValueBin;
699
953
  };
700
954
 
701
- export { type AttributeTypeAndValue, type AuthorityInformationAccess, type AuthorityKeyIdentifier, type BasicConstraints, type Certificate, type CertificateExtension, type CertificateInfo, type CertificateInternals, type CertificatePEM, CertificatePurpose, type CertificateRevocationList, type CertificateRevocationListInfo, type CertificateSerialNumber, type CertificateSigningRequestInfo, type ComputeDerivedKeysOptions, type CreateSelfSignCertificateOptions, type DER, type DERContentType, type DerivedKeys, type DirectoryName, type DistinguishedNameAttribute, type ExtensionRequest, type Extensions, type KeyObject, type Name, type Nonce, type PEM, PaddingAlgorithm, type PrivateKey, type PrivateKeyInternals, type PrivateKeyPEM, type PublicKey, type PublicKeyLength, type PublicKeyPEM, RSA_PKCS1_OAEP_PADDING, RSA_PKCS1_PADDING, 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 X509ExtKeyUsage, type X509KeyUsage, type _VerifyStatus, _coercePrivateKey, asn1, certificateMatchesPrivateKey, clearExploreCertificateCache, coerceCertificate, coerceCertificatePem, coercePEMorDerToPrivateKey, coercePrivateKeyPem, coercePublicKeyPem, coerceRsaPublicKeyPem, combine_der, computeDerivedKeys, computePaddingFooter, convertPEMtoDER, createCertificateSigningRequest, createPrivateKeyFromNodeJSCrypto, createSelfSignedCertificate, decryptBufferWithDerivedKeys, derToPrivateKey, encryptBufferWithDerivedKeys, exploreAsn1, exploreCertificate, exploreCertificateInfo, exploreCertificateRevocationList, exploreCertificateSigningRequest, explorePrivateKey, extractPublicKeyFromCertificate, extractPublicKeyFromCertificateSync, generateKeyPair, generatePrivateKey, hexDump, identifyDERContent, identifyPemType, isCrlIssuedByCertificate, isKeyObject, makeMessageChunkSignature, makeMessageChunkSignatureWithDerivedKeys, makePrivateKeyFromPem, makePrivateKeyThumbPrint, makePseudoRandomBuffer, makeSHA1Thumbprint, pemToPrivateKey, privateDecrypt, privateDecrypt_long, privateDecrypt_native, privateKeyToPEM, publicEncrypt, publicEncrypt_long, publicEncrypt_native, publicKeyAndPrivateKeyMatches, readCertificationRequestInfo, readExtension, readNameForCrl, readTbsCertificate, reduceLength, removePadding, removeTrailingLF, rsaLengthPrivateKey, rsaLengthPublicKey, rsaLengthRsaPublicKey, split_der, toPem, toPem2, verifyCertificateChain, verifyCertificateOrClrSignature, verifyCertificateRevocationListSignature, verifyCertificateSignature, verifyChunkSignature, verifyChunkSignatureWithDerivedKeys, verifyCrlIssuedByCertificate, verifyMessageChunkSignature, verify_certificate_der_structure };
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 };