node-opcua-client 2.189.0 → 2.191.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 (67) hide show
  1. package/dist/alarms_and_conditions/client_alarm_tools.d.ts.map +1 -1
  2. package/dist/alarms_and_conditions/client_alarm_tools.js +2 -1
  3. package/dist/alarms_and_conditions/client_alarm_tools.js.map +1 -1
  4. package/dist/client_monitored_item_toolbox.d.ts.map +1 -1
  5. package/dist/client_monitored_item_toolbox.js +8 -4
  6. package/dist/client_monitored_item_toolbox.js.map +1 -1
  7. package/dist/client_session_keepalive_manager.d.ts.map +1 -1
  8. package/dist/client_session_keepalive_manager.js +18 -12
  9. package/dist/client_session_keepalive_manager.js.map +1 -1
  10. package/dist/private/client_base_impl.d.ts +10 -1
  11. package/dist/private/client_base_impl.d.ts.map +1 -1
  12. package/dist/private/client_base_impl.js +188 -77
  13. package/dist/private/client_base_impl.js.map +1 -1
  14. package/dist/private/client_monitored_item_impl.d.ts.map +1 -1
  15. package/dist/private/client_monitored_item_impl.js +2 -1
  16. package/dist/private/client_monitored_item_impl.js.map +1 -1
  17. package/dist/private/client_publish_engine.d.ts.map +1 -1
  18. package/dist/private/client_publish_engine.js +16 -8
  19. package/dist/private/client_publish_engine.js.map +1 -1
  20. package/dist/private/client_session_impl.d.ts +21 -0
  21. package/dist/private/client_session_impl.d.ts.map +1 -1
  22. package/dist/private/client_session_impl.js +122 -57
  23. package/dist/private/client_session_impl.js.map +1 -1
  24. package/dist/private/client_subscription_impl.d.ts.map +1 -1
  25. package/dist/private/client_subscription_impl.js +27 -17
  26. package/dist/private/client_subscription_impl.js.map +1 -1
  27. package/dist/private/opcua_client_impl.d.ts.map +1 -1
  28. package/dist/private/opcua_client_impl.js +307 -29
  29. package/dist/private/opcua_client_impl.js.map +1 -1
  30. package/dist/private/reconnection/client_publish_engine_reconnection.d.ts.map +1 -1
  31. package/dist/private/reconnection/client_publish_engine_reconnection.js +6 -3
  32. package/dist/private/reconnection/client_publish_engine_reconnection.js.map +1 -1
  33. package/dist/private/reconnection/client_subscription_reconnection.d.ts.map +1 -1
  34. package/dist/private/reconnection/client_subscription_reconnection.js +6 -3
  35. package/dist/private/reconnection/client_subscription_reconnection.js.map +1 -1
  36. package/dist/private/reconnection/reconnection.d.ts.map +1 -1
  37. package/dist/private/reconnection/reconnection.js +6 -4
  38. package/dist/private/reconnection/reconnection.js.map +1 -1
  39. package/dist/private/verify_server_signature.d.ts +51 -0
  40. package/dist/private/verify_server_signature.d.ts.map +1 -0
  41. package/dist/private/verify_server_signature.js +76 -0
  42. package/dist/private/verify_server_signature.js.map +1 -0
  43. package/dist/reverse/client_reverse_connect.js +2 -2
  44. package/dist/reverse/client_reverse_connect.js.map +1 -1
  45. package/dist/tools/read_history_server_capabilities.js +6 -3
  46. package/dist/tools/read_history_server_capabilities.js.map +1 -1
  47. package/dist/verify.d.ts +6 -0
  48. package/dist/verify.d.ts.map +1 -1
  49. package/dist/verify.js +32 -10
  50. package/dist/verify.js.map +1 -1
  51. package/package.json +45 -45
  52. package/source/alarms_and_conditions/client_alarm_tools.ts +2 -1
  53. package/source/client_monitored_item_toolbox.ts +8 -4
  54. package/source/client_session_keepalive_manager.ts +18 -12
  55. package/source/private/client_base_impl.ts +206 -78
  56. package/source/private/client_monitored_item_impl.ts +2 -1
  57. package/source/private/client_publish_engine.ts +16 -8
  58. package/source/private/client_session_impl.ts +122 -57
  59. package/source/private/client_subscription_impl.ts +27 -17
  60. package/source/private/opcua_client_impl.ts +383 -29
  61. package/source/private/reconnection/client_publish_engine_reconnection.ts +6 -3
  62. package/source/private/reconnection/client_subscription_reconnection.ts +6 -3
  63. package/source/private/reconnection/reconnection.ts +6 -4
  64. package/source/private/verify_server_signature.ts +109 -0
  65. package/source/reverse/client_reverse_connect.ts +2 -2
  66. package/source/tools/read_history_server_capabilities.ts +6 -3
  67. package/source/verify.ts +34 -12
@@ -7,13 +7,13 @@ import { withLock } from "@ster5/global-mutex";
7
7
  import chalk from "chalk";
8
8
  import { assert } from "node-opcua-assert";
9
9
  import { getDefaultCertificateManager } from "node-opcua-certificate-manager";
10
- import { InMemoryCertificateStore, makeApplicationUrn, makeSubject, OPCUASecureObject, resolvePrivateKeyProviderIfNeeded } from "node-opcua-common";
10
+ import { getEcKeyOperationsFromProvider, InMemoryCertificateStore, makeApplicationUrn, makeSubject, OPCUASecureObject, OpaqueCertificateKeyPairProvider, resolvePrivateKeyProviderIfNeeded, selfSignedCertificateStartDate } from "node-opcua-common";
11
11
  import { PrivateKeyPassphraseRequiredError } from "node-opcua-crypto";
12
12
  import { exploreCertificate, makeSHA1Thumbprint, split_der } from "node-opcua-crypto/web";
13
13
  import { installPeriodicClockAdjustment, periodicClockAdjustment, uninstallPeriodicClockAdjustment } from "node-opcua-date-time";
14
14
  import { checkDebugFlag, make_debugLog, make_errorLog, make_warningLog } from "node-opcua-debug";
15
15
  import { getHostname } from "node-opcua-hostname";
16
- import { ClientSecureChannelLayer, coerceConnectionStrategy, coerceSecurityPolicy } from "node-opcua-secure-channel";
16
+ import { ClientSecureChannelLayer, coerceConnectionStrategy, coerceSecurityPolicy, getAsymmetricKeyType, getCryptoFactory, SecurityPolicy } from "node-opcua-secure-channel";
17
17
  import { FindServersOnNetworkRequest, FindServersOnNetworkResponse, FindServersRequest, FindServersResponse } from "node-opcua-service-discovery";
18
18
  import { ApplicationType, GetEndpointsRequest, GetEndpointsResponse } from "node-opcua-service-endpoints";
19
19
  import { coerceMessageSecurityMode, MessageSecurityMode, ServiceFault } from "node-opcua-service-secure-channel";
@@ -85,12 +85,13 @@ function __findEndpoint(endpointUrl, params, _callback) {
85
85
  masterClient.listeners("backoff").forEach((handler) => {
86
86
  client.on("backoff", handler);
87
87
  });
88
- /* c8 ignore next */
88
+ /* c8 ignore start */
89
89
  if (doDebug) {
90
90
  client.on("backoff", (retryCount, delay) => {
91
91
  debugLog("finding Endpoint => reconnecting ", " retry count", retryCount, " next attempt in ", delay / 1000, "seconds");
92
92
  });
93
93
  }
94
+ /* c8 ignore stop */
94
95
  client.connect(endpointUrl, (err) => {
95
96
  if (err) {
96
97
  err.message =
@@ -114,10 +115,11 @@ function __findEndpoint(endpointUrl, params, _callback) {
114
115
  err.message = `error in getEndpoints \n${err.message}`;
115
116
  return reject(err);
116
117
  }
117
- // c8 ignore next
118
+ /* c8 ignore start */
118
119
  if (!endpoints) {
119
120
  return reject(new Error("Internal Error"));
120
121
  }
122
+ /* c8 ignore stop */
121
123
  for (const endpoint of endpoints) {
122
124
  if (endpoint.securityMode === securityMode && endpoint.securityPolicyUri === securityPolicy) {
123
125
  if (selectedEndpoint) {
@@ -146,10 +148,11 @@ function __findEndpoint(endpointUrl, params, _callback) {
146
148
  " policy: " +
147
149
  securityPolicy.toString()));
148
150
  }
149
- // c8 ignore next
151
+ /* c8 ignore start */
150
152
  if (doDebug) {
151
153
  debugLog(chalk.bgWhite.red("xxxxxxxxxxxxxxxxxxxxx => selected EndPoint = "), selectedEndpoint.toString());
152
154
  }
155
+ /* c8 ignore stop */
153
156
  callback(null, { endpoints: allEndpoints, selectedEndpoint });
154
157
  })
155
158
  .catch((err) => {
@@ -164,29 +167,30 @@ function __findEndpoint(endpointUrl, params, _callback) {
164
167
  async function _verify_serverCertificate(certificateManager, serverCertificate) {
165
168
  const status = await certificateManager.checkCertificate(serverCertificate);
166
169
  if (!status.isGood()) {
167
- // c8 ignore next
170
+ /* c8 ignore start */
168
171
  if (doDebug) {
169
172
  // do it again for debug purposes
170
173
  const status1 = await certificateManager.verifyCertificate(serverCertificate);
171
174
  debugLog(status1);
172
175
  }
176
+ /* c8 ignore stop */
173
177
  warningLog("serverCertificate = ", makeCertificateThumbPrint(serverCertificate)?.toString("hex") || "none");
174
178
  warningLog("serverCertificate = ", serverCertificate.toString("base64"));
175
179
  throw new Error(`server Certificate verification failed with err ${status?.toString()}`);
176
180
  }
177
181
  }
178
182
  const forceEndpointDiscoveryOnConnect = !!parseInt(process.env.NODEOPCUA_CLIENT_FORCE_ENDPOINT_DISCOVERY || "0", 10);
179
- // c8 ignore next
183
+ /* c8 ignore next */
180
184
  doDebug && debugLog("forceEndpointDiscoveryOnConnect = ", forceEndpointDiscoveryOnConnect);
181
185
  class ClockAdjustment {
182
186
  constructor() {
183
- // c8 ignore next
187
+ /* c8 ignore next */
184
188
  doDebug && debugLog("installPeriodicClockAdjustment ", periodicClockAdjustment.timerInstallationCount);
185
189
  installPeriodicClockAdjustment();
186
190
  }
187
191
  dispose() {
188
192
  uninstallPeriodicClockAdjustment();
189
- // c8 ignore next
193
+ /* c8 ignore next */
190
194
  doDebug && debugLog("uninstallPeriodicClockAdjustment ", periodicClockAdjustment.timerInstallationCount);
191
195
  }
192
196
  }
@@ -303,6 +307,15 @@ export class ClientBaseImpl extends OPCUASecureObject {
303
307
  #holdsCertificateManagerReference = false;
304
308
  /** true when the caller supplied a certificateKeyPairProvider — the private-key resolution escape hatch. */
305
309
  #hasUserProvidedProvider = false;
310
+ /**
311
+ * The certificate chain and the key of this client for a security policy. It is there only
312
+ * when the client has a second certificate, for the family of key that its first certificate
313
+ * does not have: the SecureChannel then asks for the certificate of its policy. A client
314
+ * with one certificate has no such method, and nothing changes for it.
315
+ * Part of an Experimental feature: see `eccSecurityPolicies`.
316
+ * @internal
317
+ */
318
+ getApplicationIdentity;
306
319
  isUnusable() {
307
320
  return (this._internalState === "disconnected" ||
308
321
  this._internalState === "disconnecting" ||
@@ -328,10 +341,11 @@ export class ClientBaseImpl extends OPCUASecureObject {
328
341
  // "node:events" declaration and not exported.
329
342
  // biome-ignore lint/suspicious/noExplicitAny: must match EventEmitter#emit's rest parameter
330
343
  emit(eventName, ...others) {
331
- // c8 ignore next
344
+ /* c8 ignore start */
332
345
  if (doDebug) {
333
346
  debugLog(chalk.cyan(` Client ${this._instanceNumber} ${this.clientName} emitting `), chalk.magentaBright(eventName));
334
347
  }
348
+ /* c8 ignore stop */
335
349
  // @ts-expect-error
336
350
  return super.emit(eventName, ...others);
337
351
  }
@@ -413,30 +427,32 @@ export class ClientBaseImpl extends OPCUASecureObject {
413
427
  _cancel_reconnection(callback) {
414
428
  // _cancel_reconnection is invoked during disconnection
415
429
  // when we detect that a reconnection is in progress...
416
- // c8 ignore next
430
+ /* c8 ignore start */
417
431
  if (!this.isReconnecting) {
418
432
  warningLog("internal error: _cancel_reconnection should only be used when reconnecting is in progress");
419
433
  }
420
- // c8 ignore next
434
+ /* c8 ignore stop */
435
+ /* c8 ignore next */
421
436
  doDebug && debugLog("canceling reconnection : ", this.clientName);
422
437
  this._reconnectionIsCanceled = true;
423
- // c8 ignore next
438
+ /* c8 ignore start */
424
439
  if (!this._secureChannel) {
425
- // c8 ignore next
440
+ /* c8 ignore next */
426
441
  doDebug &&
427
442
  debugLog("_cancel_reconnection: Nothing to do for !", this.clientName, " because secure channel doesn't exist");
428
443
  return callback(); // nothing to do
429
444
  }
445
+ /* c8 ignore stop */
430
446
  this._secureChannel.abortConnection(( /*err?: Error*/) => {
431
447
  this._secureChannel = null;
432
448
  callback();
433
449
  });
434
450
  }
435
451
  _recreate_secure_channel(callback) {
436
- // c8 ignore next
452
+ /* c8 ignore next */
437
453
  doDebug && debugLog("_recreate_secure_channel... while internalState is", this._internalState);
438
454
  if (!this.knowsServerEndpoint) {
439
- // c8 ignore next
455
+ /* c8 ignore next */
440
456
  doDebug && debugLog("Cannot reconnect , server endpoint is unknown");
441
457
  callback(new Error("Cannot reconnect, server endpoint is unknown - this.knowsServerEndpoint = false"));
442
458
  return;
@@ -459,7 +475,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
459
475
  return callback(new Error(`Reconnection has been canceled - ${this.clientName}`));
460
476
  };
461
477
  const _failAndRetry = (err, message, callback) => {
462
- // c8 ignore next
478
+ /* c8 ignore next */
463
479
  doDebug && debugLog("failAndRetry; ", message);
464
480
  if (this._reconnectionIsCanceled) {
465
481
  return _when_reconnectionIsCanceled(callback);
@@ -475,13 +491,13 @@ export class ClientBaseImpl extends OPCUASecureObject {
475
491
  this.emit("after_reconnection", null); // send after callback
476
492
  assert(this._secureChannel, "expecting a secureChannel here ");
477
493
  // a new channel has be created and a new connection is established
478
- // c8 ignore next
494
+ /* c8 ignore next */
479
495
  doDebug && debugLog(chalk.bgWhite.red("ClientBaseImpl: RECONNECTED !!!"));
480
496
  this._setInternalState("reconnecting_newchannel_connected");
481
497
  return callback();
482
498
  };
483
499
  const _attempt_to_recreate_secure_channel = (callback) => {
484
- // c8 ignore next
500
+ /* c8 ignore next */
485
501
  doDebug && debugLog("attempt to recreate a new secure channel");
486
502
  if (this._reconnectionIsCanceled) {
487
503
  return _when_reconnectionIsCanceled(callback);
@@ -495,11 +511,12 @@ export class ClientBaseImpl extends OPCUASecureObject {
495
511
  assert(!this._secureChannel, "_attempt_to_recreate_secure_channel, expecting this._secureChannel not to exist");
496
512
  this._internal_create_secure_channel(infiniteConnectionRetry, (err) => {
497
513
  if (err) {
498
- // c8 ignore next
514
+ /* c8 ignore start */
499
515
  if (this._secureChannel) {
500
516
  const err = new Error("_internal_create_secure_channel failed, expecting this._secureChannel not to exist");
501
517
  return _when_internal_error(err, callback);
502
518
  }
519
+ /* c8 ignore stop */
503
520
  if (err.message.match(/ECONNREFUSED|ECONNABORTED|ETIMEDOUT/)) {
504
521
  return _failAndRetry(err, `create secure channel failed with ECONNREFUSED|ECONNABORTED|ETIMEDOUT\n${err.message}`, callback);
505
522
  }
@@ -560,9 +577,10 @@ export class ClientBaseImpl extends OPCUASecureObject {
560
577
  _internal_create_secure_channel(connectionStrategy, callback) {
561
578
  assert(this._secureChannel === null);
562
579
  assert(typeof this.endpointUrl === "string");
563
- // c8 ignore next
580
+ /* c8 ignore start */
564
581
  doDebug &&
565
582
  debugLog("_internal_create_secure_channel creating new ClientSecureChannelLayer _internalState =", this._internalState, this.clientName);
583
+ /* c8 ignore stop */
566
584
  const secureChannel = new ClientSecureChannelLayer({
567
585
  connectionStrategy,
568
586
  defaultSecureTokenLifetime: this.defaultSecureTokenLifetime,
@@ -587,13 +605,13 @@ export class ClientBaseImpl extends OPCUASecureObject {
587
605
  this.emit("secure_channel_created", secureChannel);
588
606
  const step2_openSecureChannel = () => {
589
607
  return new Promise((resolve, reject) => {
590
- // c8 ignore next
608
+ /* c8 ignore next */
591
609
  doDebug && debugLog("_internal_create_secure_channel before secureChannel.create");
592
610
  secureChannel.create(this.endpointUrl, (err) => {
593
- // c8 ignore next
611
+ /* c8 ignore next */
594
612
  doDebug && debugLog("_internal_create_secure_channel after secureChannel.create");
595
613
  if (!this._secureChannel) {
596
- // c8 ignore next
614
+ /* c8 ignore next */
597
615
  doDebug && debugLog("_secureChannel has been closed during the transaction !");
598
616
  return reject(new Error("Secure Channel Closed"));
599
617
  }
@@ -612,7 +630,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
612
630
  this._setInternalState("connecting");
613
631
  this.getEndpoints((err /*, endpoints?: EndpointDescription[]*/) => {
614
632
  if (!this._secureChannel) {
615
- // c8 ignore next
633
+ /* c8 ignore next */
616
634
  doDebug && debugLog("_secureChannel has been closed during the transaction ! (while getEndpoints)");
617
635
  return reject(new Error("Secure Channel Closed"));
618
636
  }
@@ -661,20 +679,22 @@ export class ClientBaseImpl extends OPCUASecureObject {
661
679
  // ip: await getIpAddresses(),
662
680
  outputFile: certificateFile,
663
681
  subject: makeSubject(applicationName, hostname),
664
- startDate: new Date(),
682
+ startDate: selfSignedCertificateStartDate(),
665
683
  validity: 365 * 10 // 10 years
666
684
  });
667
685
  }
668
- // c8 ignore next
686
+ /* c8 ignore start */
669
687
  if (!fs.existsSync(certificateFile)) {
670
688
  throw new Error(` cannot locate certificate file ${certificateFile}`);
671
689
  }
690
+ /* c8 ignore stop */
672
691
  }
673
692
  async createDefaultCertificate() {
674
- // c8 ignore next
693
+ /* c8 ignore start */
675
694
  if (this._inCreateDefaultCertificate) {
676
695
  errorLog("Internal error : re-entrancy in createDefaultCertificate!");
677
696
  }
697
+ /* c8 ignore stop */
678
698
  this._inCreateDefaultCertificate = true;
679
699
  if (!checkFileExistsAndIsNotEmpty(this.certificateFile)) {
680
700
  await withLock({ fileToLock: `${this.certificateFile}.mutex` }, async () => {
@@ -684,14 +704,15 @@ export class ClientBaseImpl extends OPCUASecureObject {
684
704
  }
685
705
  warningLog("Creating default certificate ... please wait");
686
706
  await ClientBaseImpl.createCertificate(this.clientCertificateManager, this.certificateFile, this.applicationName, this._getBuiltApplicationUri());
687
- // c8 ignore next
707
+ /* c8 ignore next */
688
708
  doDebug && debugLog("privateKey = ", this.privateKeyFile);
689
709
  if ("privateKey" in this.clientCertificateManager) {
690
- // c8 ignore next
710
+ /* c8 ignore start */
691
711
  doDebug &&
692
712
  debugLog(" = ", this.clientCertificateManager.privateKey);
713
+ /* c8 ignore stop */
693
714
  }
694
- // c8 ignore next
715
+ /* c8 ignore next */
695
716
  doDebug && debugLog("certificateFile = ", this.certificateFile);
696
717
  const _certificate = this.getCertificate();
697
718
  // Note: do NOT eagerly call this.getPrivateKey() here. A freshly
@@ -736,10 +757,11 @@ export class ClientBaseImpl extends OPCUASecureObject {
736
757
  const hasOpaqueKey = typeof this.clientCertificateManager.isPrivateKeyOpaque ===
737
758
  "function" &&
738
759
  this.clientCertificateManager.isPrivateKeyOpaque();
739
- // c8 ignore next
760
+ /* c8 ignore start */
740
761
  if (!hasOpaqueKey && !fs.existsSync(this.privateKeyFile)) {
741
762
  throw new Error(` cannot locate private key file ${this.privateKeyFile}`);
742
763
  }
764
+ /* c8 ignore stop */
743
765
  // Resolve the (possibly passphrase-encrypted) private key once,
744
766
  // asynchronously, and install it as this client's provider — so
745
767
  // that every later, synchronous getPrivateKey() call (secure
@@ -765,10 +787,84 @@ export class ClientBaseImpl extends OPCUASecureObject {
765
787
  // withLock2 internally, so an outer withLock2 would cause a deadlock
766
788
  // on the same file-based mutex.
767
789
  await performCertificateSanityCheck(this, "client", this.clientCertificateManager, this._getBuiltApplicationUri());
790
+ await this.#prepareCertificateForSecurityPolicy();
791
+ }
792
+ /**
793
+ * The security policy of this client needs a certificate with a key of its family. When the
794
+ * certificate of the client has a key of the other family, the certificate store gets one
795
+ * more slot (`OPCUACertificateManager.ensureSlot`): a private key, and a self-signed
796
+ * certificate when the slot has no certificate. The trust list is the same for both.
797
+ *
798
+ * Nothing is made for a client that has its key from `certificateKeyPairProvider`, or that
799
+ * has a certificate store with no slots: the SecureChannel then says which key is missing.
800
+ */
801
+ async #prepareCertificateForSecurityPolicy() {
802
+ this.getApplicationIdentity = undefined;
803
+ const cryptoFactory = this.securityPolicy === SecurityPolicy.None ? null : getCryptoFactory(this.securityPolicy);
804
+ const cm = this.clientCertificateManager;
805
+ if (!cryptoFactory ||
806
+ this.#hasUserProvidedProvider ||
807
+ this.certificateFile === "<in-memory>" ||
808
+ this.certificateFile === "<unknown>" ||
809
+ typeof cm.ensureSlot !== "function" ||
810
+ typeof cm.getSlot !== "function") {
811
+ return;
812
+ }
813
+ const family = getAsymmetricKeyType(cryptoFactory) === "ec" ? "ec" : "rsa";
814
+ let ownFamily = "rsa";
815
+ try {
816
+ ownFamily = getEcKeyOperationsFromProvider(this.getProvider()) ? "ec" : "rsa";
817
+ }
818
+ catch (_err) {
819
+ // a key that cannot be read now is taken as before, as an RSA key
820
+ }
821
+ if (family === ownFamily) {
822
+ return;
823
+ }
824
+ const slot = family === "ec"
825
+ ? await cm.ensureSlot("EccNistP256")
826
+ : (cm.getSlot("RsaSha256") ?? cm.getSlot("RsaMin") ?? (await cm.ensureSlot("RsaSha256")));
827
+ if ((await slot.getStatus()) === "empty") {
828
+ await withLock({ fileToLock: `${slot.certificateFile}.mutex` }, async () => {
829
+ if ((await slot.getStatus()) !== "empty") {
830
+ return;
831
+ }
832
+ const hostname = getHostname();
833
+ await slot.createSelfSignedCertificate({
834
+ applicationUri: this._getBuiltApplicationUri(),
835
+ dns: [hostname],
836
+ subject: makeSubject(this.applicationName, hostname),
837
+ startDate: selfSignedCertificateStartDate(),
838
+ validity: 365 * 10 // 10 years
839
+ });
840
+ warningLog(`[NODE-OPCUA-W42] a self-signed ${slot.certificateType} certificate was made for this client: ${slot.certificateFile}`);
841
+ });
842
+ }
843
+ // the operations of the key and not the key: this is also right for a slot whose key is
844
+ // not in this process (`keyOperations` of the slot)
845
+ const keyOperations = slot.getKeyOperations();
846
+ const provider = new OpaqueCertificateKeyPairProvider({
847
+ certificateFile: slot.certificateFile,
848
+ keyOperations,
849
+ keyMetadata: await keyOperations.getKeyMetadata()
850
+ });
851
+ // the same checks as for the first certificate: the key, the dates, the ApplicationUri
852
+ await performCertificateSanityCheck(provider, "client", this.clientCertificateManager, this._getBuiltApplicationUri());
853
+ this.getApplicationIdentity = (securityPolicy) => {
854
+ const factory = securityPolicy === SecurityPolicy.None ? null : getCryptoFactory(securityPolicy);
855
+ if (factory && (getAsymmetricKeyType(factory) === "ec" ? "ec" : "rsa") === family) {
856
+ return { certificateChain: provider.getCertificateChain(), keyOperations: provider.getKeyOperations() };
857
+ }
858
+ // no security, and the family of the first certificate
859
+ return {
860
+ certificateChain: this.getCertificateChain(),
861
+ keyOperations: getEcKeyOperationsFromProvider(this.getProvider()) ?? this.getKeyOperations()
862
+ };
863
+ };
768
864
  }
769
865
  _internalState = "uninitialized";
770
866
  _handleUnrecoverableConnectionFailure(err, callback) {
771
- // c8 ignore next
867
+ /* c8 ignore next */
772
868
  doDebug && debugLog(err.message);
773
869
  // Terminal connect failure: make sure the client is removed from the leak registry. A
774
870
  // synchronous throw out of _connectStep2 (e.g. an invalid SecureChannel config) lands here
@@ -780,7 +876,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
780
876
  callback(err);
781
877
  }
782
878
  _handleDisconnectionWhileConnecting(err, callback) {
783
- // c8 ignore next
879
+ /* c8 ignore next */
784
880
  doDebug && debugLog(err.message);
785
881
  // see _handleUnrecoverableConnectionFailure: idempotent unregister guards against a leaked
786
882
  // client when a connect attempt fails before the error-branch unregister runs.
@@ -790,7 +886,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
790
886
  callback(err);
791
887
  }
792
888
  _handleSuccessfulConnection(callback) {
793
- // c8 ignore next
889
+ /* c8 ignore next */
794
890
  doDebug && debugLog(" Connected successfully to ", this.endpointUrl);
795
891
  this.emit("connected");
796
892
  this._setInternalState("connected");
@@ -806,11 +902,12 @@ export class ClientBaseImpl extends OPCUASecureObject {
806
902
  return;
807
903
  }
808
904
  assert(typeof endpointUrl === "string" && endpointUrl.length > 0);
809
- // c8 ignore next
905
+ /* c8 ignore start */
810
906
  if (this._internalState !== "disconnected") {
811
907
  callback(new Error(`client#connect failed, as invalid internal state = ${this._internalState}`));
812
908
  return;
813
909
  }
910
+ /* c8 ignore stop */
814
911
  // prevent illegal call to connect
815
912
  if (this._secureChannel !== null) {
816
913
  setImmediate(() => callback(new Error("connect already called")));
@@ -820,14 +917,14 @@ export class ClientBaseImpl extends OPCUASecureObject {
820
917
  this._setInternalState("connecting");
821
918
  this.initializeCM()
822
919
  .then(() => {
823
- // c8 ignore next
920
+ /* c8 ignore next */
824
921
  doDebug && debugLog("ClientBaseImpl#connect ", endpointUrl, this.clientName);
825
922
  if (this._internalState === "disconnecting" || this._internalState === "disconnected") {
826
923
  return this._handleDisconnectionWhileConnecting(new Error("premature disconnection 1"), callback);
827
924
  }
828
925
  if (!this.serverCertificate &&
829
926
  (forceEndpointDiscoveryOnConnect || this.securityMode !== MessageSecurityMode.None)) {
830
- // c8 ignore next
927
+ /* c8 ignore next */
831
928
  doDebug && debugLog("Fetching certificates from endpoints");
832
929
  this.fetchServerCertificate(endpointUrl, (err, adjustedEndpointUrl) => {
833
930
  if (err) {
@@ -837,13 +934,14 @@ export class ClientBaseImpl extends OPCUASecureObject {
837
934
  return this._handleDisconnectionWhileConnecting(new Error("premature disconnection 2"), callback);
838
935
  }
839
936
  if (forceEndpointDiscoveryOnConnect) {
840
- // c8 ignore next
937
+ /* c8 ignore start */
841
938
  doDebug &&
842
939
  debugLog("connecting with adjusted endpoint : ", adjustedEndpointUrl, " was =", endpointUrl);
940
+ /* c8 ignore stop */
843
941
  this._connectStep2(adjustedEndpointUrl || "", callback);
844
942
  }
845
943
  else {
846
- // c8 ignore next
944
+ /* c8 ignore next */
847
945
  doDebug && debugLog("connecting with endpoint : ", endpointUrl);
848
946
  this._connectStep2(endpointUrl, callback);
849
947
  }
@@ -866,11 +964,12 @@ export class ClientBaseImpl extends OPCUASecureObject {
866
964
  callback(new Error("connectReverse expects a ClientReverseConnect instance"));
867
965
  return;
868
966
  }
869
- // c8 ignore next
967
+ /* c8 ignore start */
870
968
  if (this._internalState !== "disconnected") {
871
969
  callback(new Error(`client#connectReverse failed, as invalid internal state = ${this._internalState}`));
872
970
  return;
873
971
  }
972
+ /* c8 ignore stop */
874
973
  if (this._secureChannel !== null) {
875
974
  setImmediate(() => callback(new Error("connect already called")));
876
975
  return;
@@ -915,7 +1014,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
915
1014
  this._setInternalState("connecting");
916
1015
  this.initializeCM()
917
1016
  .then(() => {
918
- // c8 ignore next
1017
+ /* c8 ignore next */
919
1018
  doDebug && debugLog("ClientBaseImpl#connectReverse ", placeholderEndpointUrl, this.clientName);
920
1019
  if (this._internalState === "disconnecting" || this._internalState === "disconnected") {
921
1020
  return this._handleDisconnectionWhileConnecting(new Error("premature disconnection 1"), callback);
@@ -937,7 +1036,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
937
1036
  this.endpointUrl = endpointUrl;
938
1037
  this._clockAdjuster = this._clockAdjuster || new ClockAdjustment();
939
1038
  OPCUAClientBase.registry.register(this);
940
- // c8 ignore next
1039
+ /* c8 ignore next */
941
1040
  doDebug && debugLog("__connectStep2 ", this._internalState);
942
1041
  this._internal_create_secure_channel(this.connectionStrategy, (err) => {
943
1042
  if (!err) {
@@ -949,16 +1048,16 @@ export class ClientBaseImpl extends OPCUASecureObject {
949
1048
  this._clockAdjuster.dispose();
950
1049
  this._clockAdjuster = undefined;
951
1050
  }
952
- // c8 ignore next
1051
+ /* c8 ignore next */
953
1052
  doDebug && debugLog(chalk.red("SecureChannel creation has failed with error :", err.message));
954
1053
  if (err.message.match(/ECONNABORTED/)) {
955
- // c8 ignore next
1054
+ /* c8 ignore next */
956
1055
  doDebug && debugLog(chalk.yellow(`- The client cannot to :${endpointUrl}. Connection has been aborted.`));
957
1056
  err = new Error("The connection has been aborted");
958
1057
  this._handleUnrecoverableConnectionFailure(err, callback);
959
1058
  }
960
1059
  else if (err.message.match(/ECONNREF/)) {
961
- // c8 ignore next
1060
+ /* c8 ignore next */
962
1061
  doDebug && debugLog(chalk.yellow(`- The client cannot to :${endpointUrl}. Server is not reachable.`));
963
1062
  err = new Error(`The connection cannot be established with server ${endpointUrl} .\n` +
964
1063
  "Please check that the server is up and running or your network configuration.\n" +
@@ -1076,11 +1175,12 @@ export class ClientBaseImpl extends OPCUASecureObject {
1076
1175
  return;
1077
1176
  }
1078
1177
  this._serverEndpoints = [];
1079
- // c8 ignore next
1178
+ /* c8 ignore start */
1080
1179
  if (!response || !(response instanceof GetEndpointsResponse)) {
1081
1180
  callback(new Error("Internal Error"));
1082
1181
  return;
1083
1182
  }
1183
+ /* c8 ignore stop */
1084
1184
  if (response?.endpoints) {
1085
1185
  this._serverEndpoints = response.endpoints;
1086
1186
  }
@@ -1115,11 +1215,12 @@ export class ClientBaseImpl extends OPCUASecureObject {
1115
1215
  callback(err);
1116
1216
  return;
1117
1217
  }
1118
- /* c8 ignore next */
1218
+ /* c8 ignore start */
1119
1219
  if (!response || !(response instanceof FindServersResponse)) {
1120
1220
  callback(new Error("Internal Error"));
1121
1221
  return;
1122
1222
  }
1223
+ /* c8 ignore stop */
1123
1224
  response.servers = response.servers || [];
1124
1225
  callback(null, response.servers);
1125
1226
  });
@@ -1138,11 +1239,12 @@ export class ClientBaseImpl extends OPCUASecureObject {
1138
1239
  callback(err);
1139
1240
  return;
1140
1241
  }
1141
- /* c8 ignore next */
1242
+ /* c8 ignore start */
1142
1243
  if (!response || !(response instanceof FindServersOnNetworkResponse)) {
1143
1244
  callback(new Error("Internal Error"));
1144
1245
  return;
1145
1246
  }
1247
+ /* c8 ignore stop */
1146
1248
  response.servers = response.servers || [];
1147
1249
  callback(null, response.servers);
1148
1250
  });
@@ -1161,15 +1263,16 @@ export class ClientBaseImpl extends OPCUASecureObject {
1161
1263
  _closeSession(session, deleteSubscriptions, callback) {
1162
1264
  assert(typeof callback === "function");
1163
1265
  assert(typeof deleteSubscriptions === "boolean");
1164
- // c8 ignore next
1266
+ /* c8 ignore start */
1165
1267
  if (!this._secureChannel) {
1166
1268
  return callback(null); // new Error("no channel"));
1167
1269
  }
1270
+ /* c8 ignore stop */
1168
1271
  assert(this._secureChannel);
1169
1272
  if (!this._secureChannel.isValid()) {
1170
1273
  return callback(null);
1171
1274
  }
1172
- // c8 ignore next
1275
+ /* c8 ignore next */
1173
1276
  doDebug && debugLog(chalk.bgWhite.green("_closeSession ") + this._secureChannel.channelId);
1174
1277
  const request = new CloseSessionRequest({
1175
1278
  deleteSubscriptions
@@ -1221,7 +1324,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1221
1324
  if (typeof store.dispose !== "function")
1222
1325
  return;
1223
1326
  store.dispose().catch((err) => {
1224
- // c8 ignore next
1327
+ /* c8 ignore next */
1225
1328
  doDebug && debugLog("Error disposing clientCertificateManager", err.message);
1226
1329
  });
1227
1330
  }
@@ -1256,17 +1359,17 @@ export class ClientBaseImpl extends OPCUASecureObject {
1256
1359
  callback();
1257
1360
  return undefined;
1258
1361
  }
1259
- // c8 ignore next
1362
+ /* c8 ignore next */
1260
1363
  doDebug && debugLog("disconnecting client! (will set reconnectionIsCanceled to true");
1261
1364
  this._reconnectionIsCanceled = true;
1262
- // c8 ignore next
1365
+ /* c8 ignore next */
1263
1366
  doDebug && debugLog("ClientBaseImpl#disconnect", this.endpointUrl);
1264
1367
  if (this.isReconnecting && !this._reconnectionIsCanceled) {
1265
- // c8 ignore next
1368
+ /* c8 ignore next */
1266
1369
  doDebug && debugLog("ClientBaseImpl#disconnect called while reconnection is in progress");
1267
1370
  // let's abort the reconnection process
1268
1371
  this._cancel_reconnection((err) => {
1269
- // c8 ignore next
1372
+ /* c8 ignore next */
1270
1373
  doDebug && debugLog("ClientBaseImpl#disconnect reconnection has been canceled", this.applicationName);
1271
1374
  assert(!err, " why would this fail ?");
1272
1375
  // sessions cannot be cancelled properly and must be discarded.
@@ -1275,7 +1378,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1275
1378
  return undefined;
1276
1379
  }
1277
1380
  if (this._sessions.length && !this.keepPendingSessionsOnDisconnect) {
1278
- // c8 ignore next
1381
+ /* c8 ignore next */
1279
1382
  doDebug && debugLog("warning : disconnection : closing pending sessions");
1280
1383
  // disconnect has been called whereas living session exists
1281
1384
  // we need to close them first .... (unless keepPendingSessionsOnDisconnect)
@@ -1284,7 +1387,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1284
1387
  });
1285
1388
  return undefined;
1286
1389
  }
1287
- // c8 ignore next
1390
+ /* c8 ignore next */
1288
1391
  doDebug && debugLog("Disconnecting !");
1289
1392
  this._setInternalState("disconnecting");
1290
1393
  this.#releaseCertificateManager();
@@ -1305,7 +1408,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1305
1408
  if (this._secureChannel) {
1306
1409
  let tmpChannel = this._secureChannel;
1307
1410
  this._secureChannel = null;
1308
- // c8 ignore next
1411
+ /* c8 ignore next */
1309
1412
  doDebug && debugLog("Closing channel");
1310
1413
  tmpChannel.close(() => {
1311
1414
  this._secureChannel = tmpChannel;
@@ -1378,7 +1481,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1378
1481
  }
1379
1482
  fetchServerCertificate(endpointUrl, callback) {
1380
1483
  const discoveryUrl = this.discoveryUrl.length > 0 ? this.discoveryUrl : endpointUrl;
1381
- // c8 ignore next
1484
+ /* c8 ignore next */
1382
1485
  doDebug && debugLog("OPCUAClientImpl : getting serverCertificate");
1383
1486
  // we have not been given the serverCertificate but this certificate
1384
1487
  // is required as the connection is to be secured.
@@ -1418,12 +1521,13 @@ export class ClientBaseImpl extends OPCUASecureObject {
1418
1521
  callback(err);
1419
1522
  return;
1420
1523
  }
1421
- // c8 ignore next
1524
+ /* c8 ignore start */
1422
1525
  if (!result) {
1423
1526
  const err1 = new Error("internal error");
1424
1527
  callback(err1);
1425
1528
  return;
1426
1529
  }
1530
+ /* c8 ignore stop */
1427
1531
  const endpoint = result.selectedEndpoint;
1428
1532
  if (!endpoint) {
1429
1533
  // no matching end point can be found ...
@@ -1499,7 +1603,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1499
1603
  this._byteRead += this._secureChannel.bytesRead;
1500
1604
  this._transactionsPerformed += this._secureChannel.transactionsPerformed;
1501
1605
  this._timedOutRequestCount += this._secureChannel.timedOutRequestCount;
1502
- // c8 ignore next
1606
+ /* c8 ignore start */
1503
1607
  if (doDebug) {
1504
1608
  const h = `Client ${this._instanceNumber} ${this.clientName}`;
1505
1609
  debugLog(chalk.cyan(`${h} byteWritten = `), this._byteWritten);
@@ -1507,14 +1611,16 @@ export class ClientBaseImpl extends OPCUASecureObject {
1507
1611
  debugLog(chalk.cyan(`${h} transactions = `), this._transactionsPerformed);
1508
1612
  debugLog(chalk.cyan(`${h} timedOutRequestCount = `), this._timedOutRequestCount);
1509
1613
  }
1614
+ /* c8 ignore stop */
1510
1615
  }
1511
1616
  }
1512
1617
  _destroy_secure_channel() {
1513
1618
  if (this._secureChannel) {
1514
- // c8 ignore next
1619
+ /* c8 ignore start */
1515
1620
  if (doDebug) {
1516
1621
  debugLog(" DESTROYING SECURE CHANNEL (isTransactionInProgress ?", this._secureChannel.isTransactionInProgress(), ")");
1517
1622
  }
1623
+ /* c8 ignore stop */
1518
1624
  this._accumulate_statistics();
1519
1625
  const secureChannel = this._secureChannel;
1520
1626
  this._secureChannel = null;
@@ -1535,7 +1641,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1535
1641
  resolved = true;
1536
1642
  if (err) {
1537
1643
  const msg = session.authenticationToken ? session.authenticationToken.toString() : "";
1538
- // c8 ignore next
1644
+ /* c8 ignore next */
1539
1645
  doDebug && debugLog(` failing to close session ${msg}`);
1540
1646
  }
1541
1647
  resolve();
@@ -1545,14 +1651,15 @@ export class ClientBaseImpl extends OPCUASecureObject {
1545
1651
  };
1546
1652
  closeAll()
1547
1653
  .then(() => {
1548
- // c8 ignore next
1654
+ /* c8 ignore start */
1549
1655
  if (this._sessions.length > 0) {
1550
- // c8 ignore next
1656
+ /* c8 ignore next */
1551
1657
  doDebug &&
1552
1658
  debugLog(this._sessions
1553
1659
  .map((s) => (s.authenticationToken ? s.authenticationToken.toString() : ""))
1554
1660
  .join(" "));
1555
1661
  }
1662
+ /* c8 ignore stop */
1556
1663
  assert(this._sessions.length === 0, " failed to disconnect exiting sessions ");
1557
1664
  callback();
1558
1665
  })
@@ -1594,9 +1701,10 @@ export class ClientBaseImpl extends OPCUASecureObject {
1594
1701
  });
1595
1702
  secureChannel.on("lifetime_75", (token) => {
1596
1703
  // secureChannel requests a new token
1597
- // c8 ignore next
1704
+ /* c8 ignore start */
1598
1705
  doDebug &&
1599
1706
  debugLog("SecureChannel Security Token ", token.tokenId, "live time was =", token.revisedLifetime, " is about to expired , it's time to request a new token");
1707
+ /* c8 ignore stop */
1600
1708
  // forward message to upper level
1601
1709
  this.emit("lifetime_75", token);
1602
1710
  });
@@ -1608,7 +1716,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1608
1716
  if (err) {
1609
1717
  this._setInternalState("panic");
1610
1718
  }
1611
- // c8 ignore next
1719
+ /* c8 ignore next */
1612
1720
  doDebug && debugLog(chalk.yellow.bold(" ClientBaseImpl emitting close"), err?.message);
1613
1721
  this._destroy_secure_channel();
1614
1722
  if (!err || !this.reconnectOnFailure) {
@@ -1625,7 +1733,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1625
1733
  if (this.reconnectOnFailure &&
1626
1734
  this._internalState !== "reconnecting" &&
1627
1735
  this._internalState !== "reconnecting_newchannel_connected") {
1628
- // c8 ignore next
1736
+ /* c8 ignore next */
1629
1737
  doDebug && debugLog(" ClientBaseImpl emitting connection_lost");
1630
1738
  this._setInternalState("reconnecting");
1631
1739
  /**
@@ -1675,7 +1783,7 @@ export class ClientBaseImpl extends OPCUASecureObject {
1675
1783
  __innerRepairConnection() {
1676
1784
  if (this.isUnusable())
1677
1785
  return;
1678
- // c8 ignore next
1786
+ /* c8 ignore next */
1679
1787
  doDebug && debugLog("Entering _repairConnection ", this._internalState);
1680
1788
  if (this.#insideRepairConnection) {
1681
1789
  errorLog("_repairConnection already in progress internal state = ", this._internalState, "clientName =", this.clientName);
@@ -1684,13 +1792,13 @@ export class ClientBaseImpl extends OPCUASecureObject {
1684
1792
  }
1685
1793
  this.emit("repairConnectionStarted");
1686
1794
  this.#insideRepairConnection = true;
1687
- // c8 ignore next
1795
+ /* c8 ignore next */
1688
1796
  doDebug && debugLog("recreating new secure channel ", this._internalState);
1689
1797
  this._recreate_secure_channel((err1) => {
1690
- // c8 ignore next
1798
+ /* c8 ignore next */
1691
1799
  doDebug && debugLog("secureChannel#on(close) => _recreate_secure_channel returns ", err1 ? err1.message : "OK");
1692
1800
  if (err1) {
1693
- // c8 ignore next
1801
+ /* c8 ignore next */
1694
1802
  doDebug && debugLog("_recreate_secure_channel has failed: err = ", err1.message);
1695
1803
  this.emit("close", err1);
1696
1804
  this.#insideRepairConnection = false;
@@ -1708,17 +1816,19 @@ export class ClientBaseImpl extends OPCUASecureObject {
1708
1816
  return;
1709
1817
  this._finalReconnectionStep((err2) => {
1710
1818
  if (err2) {
1711
- // c8 ignore next
1819
+ /* c8 ignore start */
1712
1820
  if (doDebug) {
1713
1821
  debugLog("connection_reestablished has failed");
1714
1822
  debugLog("err= ", err2.message);
1715
1823
  }
1824
+ /* c8 ignore stop */
1716
1825
  // we still need to retry connecting here !!!
1717
- // c8 ignore next
1826
+ /* c8 ignore start */
1718
1827
  if (doDebug) {
1719
1828
  debugLog("Disconnected following reconnection failure", err2.message);
1720
1829
  debugLog(`I will retry OPCUA client reconnection in ${OPCUAClientBase.retryDelay / 1000} seconds`);
1721
1830
  }
1831
+ /* c8 ignore stop */
1722
1832
  this.#insideRepairConnection = false;
1723
1833
  this.#shouldRepairAgain = false;
1724
1834
  this._destroy_secure_channel();
@@ -1770,13 +1880,14 @@ class TmpClient extends ClientBaseImpl {
1770
1880
  super(options);
1771
1881
  }
1772
1882
  connect(endpoint, callback) {
1773
- // c8 ignore next
1883
+ /* c8 ignore next */
1774
1884
  doDebug && debugLog("connecting to TmpClient");
1775
- // c8 ignore next
1885
+ /* c8 ignore start */
1776
1886
  if (this._internalState !== "disconnected") {
1777
1887
  callback?.(new Error(`TmpClient#connect: invalid internal state = ${this._internalState}`));
1778
1888
  return;
1779
1889
  }
1890
+ /* c8 ignore stop */
1780
1891
  this._setInternalState("connecting");
1781
1892
  this._connectStep2(endpoint, (err) => {
1782
1893
  if (this.isUnusable()) {