node-opcua-server 2.70.3 → 2.71.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 (53) hide show
  1. package/dist/base_server.d.ts +110 -110
  2. package/dist/base_server.js +473 -473
  3. package/dist/factory.d.ts +12 -12
  4. package/dist/factory.js +23 -23
  5. package/dist/history_server_capabilities.d.ts +35 -35
  6. package/dist/history_server_capabilities.js +43 -43
  7. package/dist/i_channel_data.d.ts +13 -13
  8. package/dist/i_channel_data.js +2 -2
  9. package/dist/i_register_server_manager.d.ts +16 -16
  10. package/dist/i_register_server_manager.js +2 -2
  11. package/dist/i_server_side_publish_engine.d.ts +36 -36
  12. package/dist/i_server_side_publish_engine.js +49 -49
  13. package/dist/i_socket_data.d.ts +11 -11
  14. package/dist/i_socket_data.js +2 -2
  15. package/dist/index.d.ts +15 -15
  16. package/dist/index.js +31 -31
  17. package/dist/monitored_item.d.ts +177 -177
  18. package/dist/monitored_item.js +998 -998
  19. package/dist/node_sampler.d.ts +3 -3
  20. package/dist/node_sampler.js +75 -75
  21. package/dist/opcua_server.d.ts +647 -647
  22. package/dist/opcua_server.js +2385 -2385
  23. package/dist/queue.d.ts +11 -11
  24. package/dist/queue.js +71 -71
  25. package/dist/register_server_manager.d.ts +96 -96
  26. package/dist/register_server_manager.js +584 -584
  27. package/dist/register_server_manager_hidden.d.ts +17 -17
  28. package/dist/register_server_manager_hidden.js +27 -27
  29. package/dist/register_server_manager_mdns_only.d.ts +22 -22
  30. package/dist/register_server_manager_mdns_only.js +55 -55
  31. package/dist/server_capabilities.d.ts +61 -61
  32. package/dist/server_capabilities.js +108 -108
  33. package/dist/server_end_point.d.ts +183 -183
  34. package/dist/server_end_point.js +816 -816
  35. package/dist/server_engine.d.ts +316 -316
  36. package/dist/server_engine.js +1688 -1688
  37. package/dist/server_publish_engine.d.ts +112 -112
  38. package/dist/server_publish_engine.js +530 -530
  39. package/dist/server_publish_engine_for_orphan_subscriptions.d.ts +16 -16
  40. package/dist/server_publish_engine_for_orphan_subscriptions.js +49 -49
  41. package/dist/server_session.d.ts +181 -181
  42. package/dist/server_session.js +738 -738
  43. package/dist/server_subscription.d.ts +395 -395
  44. package/dist/server_subscription.js +1316 -1316
  45. package/dist/sessions_compatible_for_transfer.d.ts +2 -2
  46. package/dist/sessions_compatible_for_transfer.js +36 -36
  47. package/dist/user_manager.d.ts +32 -32
  48. package/dist/user_manager.js +74 -74
  49. package/dist/user_manager_ua.d.ts +3 -3
  50. package/dist/user_manager_ua.js +39 -39
  51. package/dist/validate_filter.d.ts +5 -5
  52. package/dist/validate_filter.js +60 -60
  53. package/package.json +46 -46
@@ -1,817 +1,817 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OPCUAServerEndPoint = void 0;
4
- /**
5
- * @module node-opcua-server
6
- */
7
- // tslint:disable:no-console
8
- const events_1 = require("events");
9
- const net = require("net");
10
- const chalk = require("chalk");
11
- const async = require("async");
12
- const node_opcua_assert_1 = require("node-opcua-assert");
13
- const node_opcua_crypto_1 = require("node-opcua-crypto");
14
- const node_opcua_debug_1 = require("node-opcua-debug");
15
- const node_opcua_hostname_1 = require("node-opcua-hostname");
16
- const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
17
- const node_opcua_service_endpoints_1 = require("node-opcua-service-endpoints");
18
- const node_opcua_service_endpoints_2 = require("node-opcua-service-endpoints");
19
- const node_opcua_service_endpoints_3 = require("node-opcua-service-endpoints");
20
- const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
21
- const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
22
- const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
23
- const default_transportProfileUri = "http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary";
24
- function extractSocketData(socket, reason) {
25
- const { bytesRead, bytesWritten, remoteAddress, remoteFamily, remotePort, localAddress, localPort } = socket;
26
- const data = {
27
- bytesRead,
28
- bytesWritten,
29
- localAddress,
30
- localPort,
31
- remoteAddress,
32
- remoteFamily,
33
- remotePort,
34
- timestamp: new Date(),
35
- reason
36
- };
37
- return data;
38
- }
39
- function extractChannelData(channel) {
40
- const { channelId, clientCertificate, clientNonce, clientSecurityHeader, securityHeader, securityMode, securityPolicy, timeout, transactionsCount } = channel;
41
- const channelData = {
42
- channelId,
43
- clientCertificate,
44
- clientNonce,
45
- clientSecurityHeader,
46
- securityHeader,
47
- securityMode,
48
- securityPolicy,
49
- timeout,
50
- transactionsCount
51
- };
52
- return channelData;
53
- }
54
- function dumpChannelInfo(channels) {
55
- function d(s) {
56
- return `[ status=${s.status} lastSeen=${s.clientLastContactTime.toFixed(0)}ms sessionName=${s.sessionName} timeout=${s.sessionTimeout} ]`;
57
- }
58
- function dumpChannel(channel) {
59
- var _a;
60
- console.log("------------------------------------------------------");
61
- console.log(" channelId = ", channel.channelId);
62
- console.log(" timeout = ", channel.timeout);
63
- console.log(" remoteAddress = ", channel.remoteAddress);
64
- console.log(" remotePort = ", channel.remotePort);
65
- console.log("");
66
- console.log(" bytesWritten = ", channel.bytesWritten);
67
- console.log(" bytesRead = ", channel.bytesRead);
68
- console.log(" sessions = ", Object.keys(channel.sessionTokens).length);
69
- console.log(Object.values(channel.sessionTokens).map(d).join("\n"));
70
- const socket = (_a = channel.transport) === null || _a === void 0 ? void 0 : _a._socket;
71
- if (!socket) {
72
- console.log(" SOCKET IS CLOSED");
73
- }
74
- }
75
- for (const channel of channels) {
76
- dumpChannel(channel);
77
- }
78
- console.log("------------------------------------------------------");
79
- }
80
- const emptyCertificate = Buffer.alloc(0);
81
- const emptyPrivateKeyPEM = "";
82
- let OPCUAServerEndPointCounter = 0;
83
- function getUniqueName(name, collection) {
84
- if (collection[name]) {
85
- let counter = 0;
86
- while (collection[name + "_" + counter.toString()]) {
87
- counter++;
88
- }
89
- name = name + "_" + counter.toString();
90
- collection[name] = 1;
91
- return name;
92
- }
93
- else {
94
- collection[name] = 1;
95
- return name;
96
- }
97
- }
98
- /**
99
- * OPCUAServerEndPoint a Server EndPoint.
100
- * A sever end point is listening to one port
101
- * note:
102
- * see OPCUA Release 1.03 part 4 page 108 7.1 ApplicationDescription
103
- */
104
- class OPCUAServerEndPoint extends events_1.EventEmitter {
105
- constructor(options) {
106
- super();
107
- this._started = false;
108
- this._counter = OPCUAServerEndPointCounter++;
109
- this._policy_deduplicator = {};
110
- (0, node_opcua_assert_1.assert)(!Object.prototype.hasOwnProperty.call(options, "certificate"), "expecting a certificateChain instead");
111
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(options, "certificateChain"), "expecting a certificateChain");
112
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(options, "privateKey"));
113
- this.certificateManager = options.certificateManager;
114
- options.port = options.port || 0;
115
- this.port = parseInt(options.port.toString(), 10);
116
- (0, node_opcua_assert_1.assert)(typeof this.port === "number");
117
- this._certificateChain = options.certificateChain;
118
- this._privateKey = options.privateKey;
119
- this._channels = {};
120
- this.defaultSecureTokenLifetime = options.defaultSecureTokenLifetime || 600000;
121
- this.maxConnections = options.maxConnections || 20;
122
- this.timeout = options.timeout || 30000;
123
- this._server = undefined;
124
- this._setup_server();
125
- this._endpoints = [];
126
- this.objectFactory = options.objectFactory;
127
- this.bytesWrittenInOldChannels = 0;
128
- this.bytesReadInOldChannels = 0;
129
- this.transactionsCountOldChannels = 0;
130
- this.securityTokenCountOldChannels = 0;
131
- this.serverInfo = options.serverInfo;
132
- (0, node_opcua_assert_1.assert)(this.serverInfo !== null && typeof this.serverInfo === "object");
133
- }
134
- dispose() {
135
- this._certificateChain = emptyCertificate;
136
- this._privateKey = emptyPrivateKeyPEM;
137
- (0, node_opcua_assert_1.assert)(Object.keys(this._channels).length === 0, "OPCUAServerEndPoint channels must have been deleted");
138
- this._channels = {};
139
- this.serverInfo = new node_opcua_service_endpoints_3.ApplicationDescription({});
140
- this._endpoints = [];
141
- (0, node_opcua_assert_1.assert)(this._endpoints.length === 0, "endpoints must have been deleted");
142
- this._endpoints = [];
143
- this._server = undefined;
144
- this._listen_callback = undefined;
145
- this.removeAllListeners();
146
- }
147
- toString() {
148
- const privateKey1 = (0, node_opcua_crypto_1.convertPEMtoDER)(this.getPrivateKey());
149
- const txt = " end point" +
150
- this._counter +
151
- " port = " +
152
- this.port +
153
- " l = " +
154
- this._endpoints.length +
155
- " " +
156
- (0, node_opcua_crypto_1.makeSHA1Thumbprint)(this.getCertificateChain()).toString("hex") +
157
- " " +
158
- (0, node_opcua_crypto_1.makeSHA1Thumbprint)(privateKey1).toString("hex");
159
- return txt;
160
- }
161
- getChannels() {
162
- return Object.values(this._channels);
163
- }
164
- /**
165
- * Returns the X509 DER form of the server certificate
166
- */
167
- getCertificate() {
168
- return (0, node_opcua_crypto_1.split_der)(this.getCertificateChain())[0];
169
- }
170
- /**
171
- * Returns the X509 DER form of the server certificate
172
- */
173
- getCertificateChain() {
174
- return this._certificateChain;
175
- }
176
- /**
177
- * the private key
178
- */
179
- getPrivateKey() {
180
- return this._privateKey;
181
- }
182
- /**
183
- * The number of active channel on this end point.
184
- */
185
- get currentChannelCount() {
186
- return Object.keys(this._channels).length;
187
- }
188
- /**
189
- * @method getEndpointDescription
190
- * @param securityMode
191
- * @param securityPolicy
192
- * @return endpoint_description {EndpointDescription|null}
193
- */
194
- getEndpointDescription(securityMode, securityPolicy, endpointUrl) {
195
- const endpoints = this.endpointDescriptions();
196
- const arr = endpoints.filter(matching_endpoint.bind(this, securityMode, securityPolicy, endpointUrl));
197
- if (endpointUrl && endpointUrl.length > 0 && !(arr.length === 0 || arr.length === 1)) {
198
- errorLog("Several matching endpoints have been found : ");
199
- for (const a of arr) {
200
- errorLog(" ", a.endpointUrl, node_opcua_secure_channel_1.MessageSecurityMode[securityMode], securityPolicy);
201
- }
202
- }
203
- return arr.length === 0 ? null : arr[0];
204
- }
205
- addEndpointDescription(securityMode, securityPolicy, options) {
206
- if (!options) {
207
- options = {
208
- hostname: (0, node_opcua_hostname_1.getFullyQualifiedDomainName)(),
209
- securityPolicies: [node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256]
210
- };
211
- }
212
- options.allowAnonymous = options.allowAnonymous === undefined ? true : options.allowAnonymous;
213
- // istanbul ignore next
214
- if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None && securityPolicy !== node_opcua_secure_channel_1.SecurityPolicy.None) {
215
- throw new Error(" invalid security ");
216
- }
217
- // istanbul ignore next
218
- if (securityMode !== node_opcua_secure_channel_1.MessageSecurityMode.None && securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
219
- throw new Error(" invalid security ");
220
- }
221
- //
222
- const port = this.port;
223
- // resource Path is a string added at the end of the url such as "/UA/Server"
224
- const resourcePath = (options.resourcePath || "").replace(/\\/g, "/");
225
- (0, node_opcua_assert_1.assert)(resourcePath.length === 0 || resourcePath.charAt(0) === "/", "resourcePath should start with /");
226
- const hostname = options.hostname || (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
227
- const endpointUrl = `opc.tcp://${hostname}:${port}${resourcePath}`;
228
- const endpoint_desc = this.getEndpointDescription(securityMode, securityPolicy, endpointUrl);
229
- // istanbul ignore next
230
- if (endpoint_desc) {
231
- throw new Error(" endpoint already exist");
232
- }
233
- // now build endpointUrl
234
- this._endpoints.push(_makeEndpointDescription({
235
- collection: this._policy_deduplicator,
236
- endpointUrl,
237
- hostname,
238
- port,
239
- server: this.serverInfo,
240
- serverCertificateChain: this.getCertificateChain(),
241
- securityMode,
242
- securityPolicy,
243
- allowAnonymous: options.allowAnonymous,
244
- allowUnsecurePassword: options.allowUnsecurePassword,
245
- resourcePath: options.resourcePath,
246
- restricted: !!options.restricted,
247
- securityPolicies: (options === null || options === void 0 ? void 0 : options.securityPolicies) || []
248
- }));
249
- }
250
- addRestrictedEndpointDescription(options) {
251
- options = Object.assign({}, options);
252
- options.restricted = true;
253
- return this.addEndpointDescription(node_opcua_secure_channel_1.MessageSecurityMode.None, node_opcua_secure_channel_1.SecurityPolicy.None, options);
254
- }
255
- addStandardEndpointDescriptions(options) {
256
- options = options || {};
257
- options.securityModes = options.securityModes || defaultSecurityModes;
258
- options.securityPolicies = options.securityPolicies || defaultSecurityPolicies;
259
- const defaultHostname = options.hostname || (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
260
- let hostnames = [defaultHostname];
261
- options.alternateHostname = options.alternateHostname || [];
262
- if (typeof options.alternateHostname === "string") {
263
- options.alternateHostname = [options.alternateHostname];
264
- }
265
- // remove duplicates if any (uniq)
266
- hostnames = [...new Set(hostnames.concat(options.alternateHostname))];
267
- for (const alternateHostname of hostnames) {
268
- const optionsE = options;
269
- optionsE.hostname = alternateHostname;
270
- if (options.securityModes.indexOf(node_opcua_secure_channel_1.MessageSecurityMode.None) >= 0) {
271
- this.addEndpointDescription(node_opcua_secure_channel_1.MessageSecurityMode.None, node_opcua_secure_channel_1.SecurityPolicy.None, optionsE);
272
- }
273
- else {
274
- if (!options.disableDiscovery) {
275
- this.addRestrictedEndpointDescription(optionsE);
276
- }
277
- }
278
- for (const securityMode of options.securityModes) {
279
- if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
280
- continue;
281
- }
282
- for (const securityPolicy of options.securityPolicies) {
283
- if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
284
- continue;
285
- }
286
- this.addEndpointDescription(securityMode, securityPolicy, optionsE);
287
- }
288
- }
289
- }
290
- }
291
- /**
292
- * returns the list of end point descriptions.
293
- */
294
- endpointDescriptions() {
295
- return this._endpoints;
296
- }
297
- /**
298
- * @method listen
299
- * @async
300
- */
301
- listen(callback) {
302
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
303
- (0, node_opcua_assert_1.assert)(!this._started, "OPCUAServerEndPoint is already listening");
304
- this._listen_callback = callback;
305
- this._server.on("error", (err) => {
306
- debugLog(chalk.red.bold(" error") + " port = " + this.port, err);
307
- this._started = false;
308
- this._end_listen(err);
309
- });
310
- this._server.on("listening", () => {
311
- debugLog("server is listening");
312
- });
313
- this._server.listen(this.port,
314
- /*"::",*/ (err) => {
315
- // 'listening' listener
316
- debugLog(chalk.green.bold("LISTENING TO PORT "), this.port, "err ", err);
317
- (0, node_opcua_assert_1.assert)(!err, " cannot listen to port ");
318
- this._started = true;
319
- this._end_listen();
320
- });
321
- }
322
- killClientSockets(callback) {
323
- for (const channel of this.getChannels()) {
324
- const hacked_channel = channel;
325
- if (hacked_channel.transport && hacked_channel.transport._socket) {
326
- // hacked_channel.transport._socket.close();
327
- hacked_channel.transport._socket.destroy();
328
- hacked_channel.transport._socket.emit("error", new Error("EPIPE"));
329
- }
330
- }
331
- callback();
332
- }
333
- suspendConnection(callback) {
334
- if (!this._started) {
335
- return callback(new Error("Connection already suspended !!"));
336
- }
337
- // Stops the server from accepting new connections and keeps existing connections.
338
- // (note from nodejs doc: This function is asynchronous, the server is finally closed
339
- // when all connections are ended and the server emits a 'close' event.
340
- // The optional callback will be called once the 'close' event occurs.
341
- // Unlike that event, it will be called with an Error as its only argument
342
- // if the server was not open when it was closed.
343
- this._server.close(() => {
344
- this._started = false;
345
- debugLog("Connection has been closed !" + this.port);
346
- });
347
- this._started = false;
348
- callback();
349
- }
350
- restoreConnection(callback) {
351
- this.listen(callback);
352
- }
353
- abruptlyInterruptChannels() {
354
- for (const channel of Object.values(this._channels)) {
355
- channel.abruptlyInterrupt();
356
- }
357
- }
358
- /**
359
- * @method shutdown
360
- * @async
361
- */
362
- shutdown(callback) {
363
- debugLog("OPCUAServerEndPoint#shutdown ");
364
- if (this._started) {
365
- // make sure we don't accept new connection any more ...
366
- this.suspendConnection(() => {
367
- // shutdown all opened channels ...
368
- const _channels = Object.values(this._channels);
369
- async.each(_channels, (channel, callback1) => {
370
- this.shutdown_channel(channel, callback1);
371
- }, (err) => {
372
- /* istanbul ignore next */
373
- if (!(Object.keys(this._channels).length === 0)) {
374
- errorLog(" Bad !");
375
- }
376
- (0, node_opcua_assert_1.assert)(Object.keys(this._channels).length === 0, "channel must have unregistered themselves");
377
- callback(err || undefined);
378
- });
379
- });
380
- }
381
- else {
382
- callback();
383
- }
384
- }
385
- /**
386
- * @method start
387
- * @async
388
- * @param callback
389
- */
390
- start(callback) {
391
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
392
- this.listen(callback);
393
- }
394
- get bytesWritten() {
395
- const channels = Object.values(this._channels);
396
- return (this.bytesWrittenInOldChannels +
397
- channels.reduce((accumulated, channel) => {
398
- return accumulated + channel.bytesWritten;
399
- }, 0));
400
- }
401
- get bytesRead() {
402
- const channels = Object.values(this._channels);
403
- return (this.bytesReadInOldChannels +
404
- channels.reduce((accumulated, channel) => {
405
- return accumulated + channel.bytesRead;
406
- }, 0));
407
- }
408
- get transactionsCount() {
409
- const channels = Object.values(this._channels);
410
- return (this.transactionsCountOldChannels +
411
- channels.reduce((accumulated, channel) => {
412
- return accumulated + channel.transactionsCount;
413
- }, 0));
414
- }
415
- get securityTokenCount() {
416
- const channels = Object.values(this._channels);
417
- return (this.securityTokenCountOldChannels +
418
- channels.reduce((accumulated, channel) => {
419
- return accumulated + channel.securityTokenCount;
420
- }, 0));
421
- }
422
- get activeChannelCount() {
423
- return Object.keys(this._channels).length;
424
- }
425
- _dump_statistics() {
426
- this._server.getConnections((err, count) => {
427
- debugLog(chalk.cyan("CONCURRENT CONNECTION = "), count);
428
- });
429
- debugLog(chalk.cyan("MAX CONNECTIONS = "), this._server.maxConnections);
430
- }
431
- _setup_server() {
432
- (0, node_opcua_assert_1.assert)(!this._server);
433
- this._server = net.createServer({ pauseOnConnect: true }, this._on_client_connection.bind(this));
434
- // xx console.log(" Server with max connections ", self.maxConnections);
435
- this._server.maxConnections = this.maxConnections + 1; // plus one extra
436
- this._listen_callback = undefined;
437
- this._server
438
- .on("connection", (socket) => {
439
- // istanbul ignore next
440
- if (doDebug) {
441
- this._dump_statistics();
442
- debugLog("server connected with : " + socket.remoteAddress + ":" + socket.remotePort);
443
- }
444
- })
445
- .on("close", () => {
446
- debugLog("server closed : all connections have ended");
447
- })
448
- .on("error", (err) => {
449
- // this could be because the port is already in use
450
- debugLog(chalk.red.bold("server error: "), err.message);
451
- });
452
- }
453
- _on_client_connection(socket) {
454
- // a client is attempting a connection on the socket
455
- socket.setNoDelay(true);
456
- debugLog("OPCUAServerEndPoint#_on_client_connection", this._started);
457
- if (!this._started) {
458
- debugLog(chalk.bgWhite.cyan("OPCUAServerEndPoint#_on_client_connection " +
459
- "SERVER END POINT IS PROBABLY SHUTTING DOWN !!! - Connection is refused"));
460
- socket.end();
461
- return;
462
- }
463
- const deny_connection = () => {
464
- console.log(chalk.bgWhite.cyan("OPCUAServerEndPoint#_on_client_connection " +
465
- "The maximum number of connection has been reached - Connection is refused"));
466
- const reason = "maxConnections reached (" + this.maxConnections + ")";
467
- const socketData = extractSocketData(socket, reason);
468
- this.emit("connectionRefused", socketData);
469
- socket.end();
470
- socket.destroy();
471
- };
472
- const establish_connection = () => {
473
- const nbConnections = Object.keys(this._channels).length;
474
- debugLog(" nbConnections ", nbConnections, " self._server.maxConnections", this._server.maxConnections, this.maxConnections);
475
- if (nbConnections >= this.maxConnections) {
476
- deny_connection();
477
- return;
478
- }
479
- debugLog("OPCUAServerEndPoint._on_client_connection successful => New Channel");
480
- const channel = new node_opcua_secure_channel_1.ServerSecureChannelLayer({
481
- defaultSecureTokenLifetime: this.defaultSecureTokenLifetime,
482
- // objectFactory: this.objectFactory,
483
- parent: this,
484
- timeout: this.timeout
485
- });
486
- debugLog("channel Timeout = >", channel.timeout);
487
- socket.resume();
488
- this._preregisterChannel(channel);
489
- channel.init(socket, (err) => {
490
- this._un_pre_registerChannel(channel);
491
- debugLog(chalk.yellow.bold("Channel#init done"), err);
492
- if (err) {
493
- const reason = "openSecureChannel has Failed " + err.message;
494
- const socketData = extractSocketData(socket, reason);
495
- const channelData = extractChannelData(channel);
496
- this.emit("openSecureChannelFailure", socketData, channelData);
497
- socket.end();
498
- socket.destroy();
499
- }
500
- else {
501
- debugLog("server receiving a client connection");
502
- this._registerChannel(channel);
503
- }
504
- });
505
- channel.on("message", (message) => {
506
- // forward
507
- this.emit("message", message, channel, this);
508
- });
509
- };
510
- // Each SecureChannel exists until it is explicitly closed or until the last token has expired and the overlap
511
- // period has elapsed. A Server application should limit the number of SecureChannels.
512
- // To protect against misbehaving Clients and denial of service attacks, the Server shall close the oldest
513
- // SecureChannel that has no Session assigned before reaching the maximum number of supported SecureChannels.
514
- this._prevent_DDOS_Attack(establish_connection, deny_connection);
515
- }
516
- _preregisterChannel(channel) {
517
- // _preregisterChannel is used to keep track of channel for which
518
- // that are in early stage of the hand shaking process.
519
- // e.g HEL/ACK and OpenSecureChannel may not have been received yet
520
- // as they will need to be interrupted when OPCUAServerEndPoint is closed
521
- (0, node_opcua_assert_1.assert)(this._started, "OPCUAServerEndPoint must be started");
522
- (0, node_opcua_assert_1.assert)(!Object.prototype.hasOwnProperty.call(this._channels, channel.hashKey), " channel already preregistered!");
523
- const channelPriv = channel;
524
- this._channels[channel.hashKey] = channelPriv;
525
- channelPriv._unpreregisterChannelEvent = () => {
526
- debugLog("Channel received an abort event during the preregistration phase");
527
- this._un_pre_registerChannel(channel);
528
- channel.dispose();
529
- };
530
- channel.on("abort", channelPriv._unpreregisterChannelEvent);
531
- }
532
- _un_pre_registerChannel(channel) {
533
- if (!this._channels[channel.hashKey]) {
534
- debugLog("Already un preregistered ?", channel.hashKey);
535
- return;
536
- }
537
- delete this._channels[channel.hashKey];
538
- const channelPriv = channel;
539
- if (typeof channelPriv._unpreregisterChannelEvent === "function") {
540
- channel.removeListener("abort", channelPriv._unpreregisterChannelEvent);
541
- channelPriv._unpreregisterChannelEvent = undefined;
542
- }
543
- }
544
- /**
545
- * @method _registerChannel
546
- * @param channel
547
- * @private
548
- */
549
- _registerChannel(channel) {
550
- if (this._started) {
551
- debugLog(chalk.red("_registerChannel = "), "channel.hashKey = ", channel.hashKey);
552
- (0, node_opcua_assert_1.assert)(!this._channels[channel.hashKey]);
553
- this._channels[channel.hashKey] = channel;
554
- /**
555
- * @event newChannel
556
- * @param channel
557
- */
558
- this.emit("newChannel", channel);
559
- channel.on("abort", () => {
560
- this._unregisterChannel(channel);
561
- });
562
- }
563
- else {
564
- debugLog("OPCUAServerEndPoint#_registerChannel called when end point is shutdown !");
565
- debugLog(" -> channel will be forcefully terminated");
566
- channel.close();
567
- channel.dispose();
568
- }
569
- }
570
- /**
571
- * @method _unregisterChannel
572
- * @param channel
573
- * @private
574
- */
575
- _unregisterChannel(channel) {
576
- debugLog("_un-registerChannel channel.hashKey", channel.hashKey);
577
- if (!Object.prototype.hasOwnProperty.call(this._channels, channel.hashKey)) {
578
- return;
579
- }
580
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(this._channels, channel.hashKey), "channel is not registered");
581
- /**
582
- * @event closeChannel
583
- * @param channel
584
- */
585
- this.emit("closeChannel", channel);
586
- // keep trace of statistics data from old channel for our own accumulated stats.
587
- this.bytesWrittenInOldChannels += channel.bytesWritten;
588
- this.bytesReadInOldChannels += channel.bytesRead;
589
- this.transactionsCountOldChannels += channel.transactionsCount;
590
- delete this._channels[channel.hashKey];
591
- // istanbul ignore next
592
- if (doDebug) {
593
- this._dump_statistics();
594
- debugLog("un-registering channel - Count = ", this.currentChannelCount);
595
- }
596
- /// channel.dispose();
597
- }
598
- _end_listen(err) {
599
- (0, node_opcua_assert_1.assert)(typeof this._listen_callback === "function");
600
- this._listen_callback(err);
601
- this._listen_callback = undefined;
602
- }
603
- /**
604
- * shutdown_channel
605
- * @param channel
606
- * @param inner_callback
607
- */
608
- shutdown_channel(channel, inner_callback) {
609
- (0, node_opcua_assert_1.assert)(typeof inner_callback === "function");
610
- channel.once("close", () => {
611
- // xx console.log(" ON CLOSED !!!!");
612
- });
613
- channel.close(() => {
614
- this._unregisterChannel(channel);
615
- setImmediate(inner_callback);
616
- });
617
- }
618
- /**
619
- * @private
620
- */
621
- _prevent_DDOS_Attack(establish_connection, deny_connection) {
622
- const nbConnections = this.activeChannelCount;
623
- if (nbConnections >= this.maxConnections) {
624
- // istanbul ignore next
625
- errorLog(chalk.bgRed.white("PREVENTING DDOS ATTACK => maxConnection =" + this.maxConnections));
626
- const unused_channels = this.getChannels().filter((channel1) => {
627
- return !channel1.isOpened && !channel1.hasSession;
628
- });
629
- if (unused_channels.length === 0) {
630
- // all channels are in used , we cannot get any
631
- errorLog("All channels are in used ! let cancel some");
632
- // istanbul ignore next
633
- if (doDebug) {
634
- console.log(" - all channels are used !!!!");
635
- dumpChannelInfo(this.getChannels());
636
- }
637
- setTimeout(deny_connection, 10);
638
- return;
639
- }
640
- // istanbul ignore next
641
- if (doDebug) {
642
- console.log(" - Unused channels that can be clobbered", unused_channels.map((channel1) => channel1.hashKey).join(" "));
643
- }
644
- const channel = unused_channels[0];
645
- errorLog("Closing channel ", channel.hashKey);
646
- channel.close(() => {
647
- // istanbul ignore next
648
- if (doDebug) {
649
- console.log(" _ Unused channel has been closed ", channel.hashKey);
650
- }
651
- this._unregisterChannel(channel);
652
- establish_connection();
653
- });
654
- }
655
- else {
656
- setImmediate(establish_connection);
657
- }
658
- }
659
- }
660
- exports.OPCUAServerEndPoint = OPCUAServerEndPoint;
661
- function estimateSecurityLevel(securityMode, securityPolicy) {
662
- if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
663
- return 1;
664
- }
665
- let offset = 100;
666
- if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.SignAndEncrypt) {
667
- offset = 200;
668
- }
669
- switch (securityPolicy) {
670
- case node_opcua_secure_channel_1.SecurityPolicy.Basic128:
671
- case node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15:
672
- case node_opcua_secure_channel_1.SecurityPolicy.Basic192:
673
- return 2; // deprecated => low
674
- case node_opcua_secure_channel_1.SecurityPolicy.Basic192Rsa15:
675
- return 3; // deprecated => low
676
- case node_opcua_secure_channel_1.SecurityPolicy.Basic256:
677
- return 4; // deprecated => low
678
- case node_opcua_secure_channel_1.SecurityPolicy.Basic256Rsa15:
679
- return 4 + offset;
680
- case node_opcua_secure_channel_1.SecurityPolicy.Aes128_Sha256_RsaOaep:
681
- return 5 + offset;
682
- case node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256:
683
- return 6 + offset;
684
- case node_opcua_secure_channel_1.SecurityPolicy.Aes256_Sha256_RsaPss:
685
- return 7 + offset;
686
- default:
687
- case node_opcua_secure_channel_1.SecurityPolicy.None:
688
- return 1;
689
- }
690
- }
691
- /**
692
- * @private
693
- */
694
- function _makeEndpointDescription(options) {
695
- (0, node_opcua_assert_1.assert)(isFinite(options.port), "expecting a valid port number");
696
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(options, "serverCertificateChain"));
697
- (0, node_opcua_assert_1.assert)(!Object.prototype.hasOwnProperty.call(options, "serverCertificate"));
698
- (0, node_opcua_assert_1.assert)(!!options.securityMode); // s.MessageSecurityMode
699
- (0, node_opcua_assert_1.assert)(!!options.securityPolicy);
700
- (0, node_opcua_assert_1.assert)(options.server !== null && typeof options.server === "object");
701
- (0, node_opcua_assert_1.assert)(!!options.hostname && typeof options.hostname === "string");
702
- (0, node_opcua_assert_1.assert)(typeof options.restricted === "boolean");
703
- const u = (n) => getUniqueName(n, options.collection);
704
- options.securityLevel =
705
- options.securityLevel === undefined
706
- ? estimateSecurityLevel(options.securityMode, options.securityPolicy)
707
- : options.securityLevel;
708
- (0, node_opcua_assert_1.assert)(isFinite(options.securityLevel), "expecting a valid securityLevel");
709
- const securityPolicyUri = (0, node_opcua_secure_channel_1.toURI)(options.securityPolicy);
710
- const userIdentityTokens = [];
711
- if (options.securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
712
- if (options.allowUnsecurePassword) {
713
- userIdentityTokens.push({
714
- policyId: u("username_unsecure"),
715
- tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
716
- issuedTokenType: null,
717
- issuerEndpointUrl: null,
718
- securityPolicyUri: null
719
- });
720
- }
721
- const a = (tokenType, securityPolicy, name) => {
722
- if (options.securityPolicies.indexOf(securityPolicy) >= 0) {
723
- userIdentityTokens.push({
724
- policyId: u(name),
725
- tokenType,
726
- issuedTokenType: null,
727
- issuerEndpointUrl: null,
728
- securityPolicyUri: securityPolicy
729
- });
730
- }
731
- };
732
- const onlyCertificateLessConnection = options.onlyCertificateLessConnection === undefined ? false : options.onlyCertificateLessConnection;
733
- if (!onlyCertificateLessConnection) {
734
- a(node_opcua_service_endpoints_1.UserTokenType.UserName, node_opcua_secure_channel_1.SecurityPolicy.Basic256, "username_basic256");
735
- a(node_opcua_service_endpoints_1.UserTokenType.UserName, node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15, "username_basic128Rsa15");
736
- a(node_opcua_service_endpoints_1.UserTokenType.UserName, node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256, "username_basic256Sha256");
737
- a(node_opcua_service_endpoints_1.UserTokenType.UserName, node_opcua_secure_channel_1.SecurityPolicy.Aes128_Sha256_RsaOaep, "username_aes128Sha256RsaOaep");
738
- // X509
739
- a(node_opcua_service_endpoints_1.UserTokenType.Certificate, node_opcua_secure_channel_1.SecurityPolicy.Basic256, "certificate_basic256");
740
- a(node_opcua_service_endpoints_1.UserTokenType.Certificate, node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15, "certificate_basic128Rsa15");
741
- a(node_opcua_service_endpoints_1.UserTokenType.Certificate, node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256, "certificate_basic256Sha256");
742
- a(node_opcua_service_endpoints_1.UserTokenType.Certificate, node_opcua_secure_channel_1.SecurityPolicy.Aes128_Sha256_RsaOaep, "certificate_aes128Sha256RsaOaep");
743
- }
744
- }
745
- else {
746
- // note:
747
- // when channel session security is not "None",
748
- // userIdentityTokens can be left to null.
749
- // in this case this mean that secure policy will be the same as connection security policy
750
- userIdentityTokens.push({
751
- policyId: u("usernamePassword"),
752
- tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
753
- issuedTokenType: null,
754
- issuerEndpointUrl: null,
755
- securityPolicyUri: null
756
- });
757
- userIdentityTokens.push({
758
- policyId: u("certificateX509"),
759
- tokenType: node_opcua_service_endpoints_1.UserTokenType.Certificate,
760
- issuedTokenType: null,
761
- issuerEndpointUrl: null,
762
- securityPolicyUri: null
763
- });
764
- }
765
- if (options.allowAnonymous) {
766
- userIdentityTokens.push({
767
- policyId: u("anonymous"),
768
- tokenType: node_opcua_service_endpoints_1.UserTokenType.Anonymous,
769
- issuedTokenType: null,
770
- issuerEndpointUrl: null,
771
- securityPolicyUri: null
772
- });
773
- }
774
- // return the endpoint object
775
- const endpoint = new node_opcua_service_endpoints_2.EndpointDescription({
776
- endpointUrl: options.endpointUrl,
777
- server: undefined,
778
- serverCertificate: options.serverCertificateChain,
779
- securityMode: options.securityMode,
780
- securityPolicyUri,
781
- userIdentityTokens,
782
- securityLevel: options.securityLevel,
783
- transportProfileUri: default_transportProfileUri
784
- });
785
- endpoint.__defineGetter__("endpointUrl", () => {
786
- return (0, node_opcua_hostname_1.resolveFullyQualifiedDomainName)(options.endpointUrl);
787
- });
788
- endpoint.server = options.server;
789
- endpoint.restricted = options.restricted;
790
- return endpoint;
791
- }
792
- /**
793
- * return true if the end point matches security mode and policy
794
- * @param endpoint
795
- * @param securityMode
796
- * @param securityPolicy
797
- * @internal
798
- *
799
- */
800
- function matching_endpoint(securityMode, securityPolicy, endpointUrl, endpoint) {
801
- (0, node_opcua_assert_1.assert)(endpoint instanceof node_opcua_service_endpoints_2.EndpointDescription);
802
- const endpoint_securityPolicy = (0, node_opcua_secure_channel_1.fromURI)(endpoint.securityPolicyUri);
803
- if (endpointUrl && endpoint.endpointUrl !== endpointUrl) {
804
- return false;
805
- }
806
- return endpoint.securityMode === securityMode && endpoint_securityPolicy === securityPolicy;
807
- }
808
- const defaultSecurityModes = [node_opcua_secure_channel_1.MessageSecurityMode.None, node_opcua_secure_channel_1.MessageSecurityMode.Sign, node_opcua_secure_channel_1.MessageSecurityMode.SignAndEncrypt];
809
- const defaultSecurityPolicies = [
810
- node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15,
811
- node_opcua_secure_channel_1.SecurityPolicy.Basic256,
812
- // xx UNUSED!! SecurityPolicy.Basic256Rsa15,
813
- node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256,
814
- node_opcua_secure_channel_1.SecurityPolicy.Aes128_Sha256_RsaOaep
815
- // NO USED YET SecurityPolicy.Aes256_Sha256_RsaPss
816
- ];
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OPCUAServerEndPoint = void 0;
4
+ /**
5
+ * @module node-opcua-server
6
+ */
7
+ // tslint:disable:no-console
8
+ const events_1 = require("events");
9
+ const net = require("net");
10
+ const chalk = require("chalk");
11
+ const async = require("async");
12
+ const node_opcua_assert_1 = require("node-opcua-assert");
13
+ const node_opcua_crypto_1 = require("node-opcua-crypto");
14
+ const node_opcua_debug_1 = require("node-opcua-debug");
15
+ const node_opcua_hostname_1 = require("node-opcua-hostname");
16
+ const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
17
+ const node_opcua_service_endpoints_1 = require("node-opcua-service-endpoints");
18
+ const node_opcua_service_endpoints_2 = require("node-opcua-service-endpoints");
19
+ const node_opcua_service_endpoints_3 = require("node-opcua-service-endpoints");
20
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
21
+ const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
22
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
23
+ const default_transportProfileUri = "http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary";
24
+ function extractSocketData(socket, reason) {
25
+ const { bytesRead, bytesWritten, remoteAddress, remoteFamily, remotePort, localAddress, localPort } = socket;
26
+ const data = {
27
+ bytesRead,
28
+ bytesWritten,
29
+ localAddress,
30
+ localPort,
31
+ remoteAddress,
32
+ remoteFamily,
33
+ remotePort,
34
+ timestamp: new Date(),
35
+ reason
36
+ };
37
+ return data;
38
+ }
39
+ function extractChannelData(channel) {
40
+ const { channelId, clientCertificate, clientNonce, clientSecurityHeader, securityHeader, securityMode, securityPolicy, timeout, transactionsCount } = channel;
41
+ const channelData = {
42
+ channelId,
43
+ clientCertificate,
44
+ clientNonce,
45
+ clientSecurityHeader,
46
+ securityHeader,
47
+ securityMode,
48
+ securityPolicy,
49
+ timeout,
50
+ transactionsCount
51
+ };
52
+ return channelData;
53
+ }
54
+ function dumpChannelInfo(channels) {
55
+ function d(s) {
56
+ return `[ status=${s.status} lastSeen=${s.clientLastContactTime.toFixed(0)}ms sessionName=${s.sessionName} timeout=${s.sessionTimeout} ]`;
57
+ }
58
+ function dumpChannel(channel) {
59
+ var _a;
60
+ console.log("------------------------------------------------------");
61
+ console.log(" channelId = ", channel.channelId);
62
+ console.log(" timeout = ", channel.timeout);
63
+ console.log(" remoteAddress = ", channel.remoteAddress);
64
+ console.log(" remotePort = ", channel.remotePort);
65
+ console.log("");
66
+ console.log(" bytesWritten = ", channel.bytesWritten);
67
+ console.log(" bytesRead = ", channel.bytesRead);
68
+ console.log(" sessions = ", Object.keys(channel.sessionTokens).length);
69
+ console.log(Object.values(channel.sessionTokens).map(d).join("\n"));
70
+ const socket = (_a = channel.transport) === null || _a === void 0 ? void 0 : _a._socket;
71
+ if (!socket) {
72
+ console.log(" SOCKET IS CLOSED");
73
+ }
74
+ }
75
+ for (const channel of channels) {
76
+ dumpChannel(channel);
77
+ }
78
+ console.log("------------------------------------------------------");
79
+ }
80
+ const emptyCertificate = Buffer.alloc(0);
81
+ const emptyPrivateKeyPEM = "";
82
+ let OPCUAServerEndPointCounter = 0;
83
+ function getUniqueName(name, collection) {
84
+ if (collection[name]) {
85
+ let counter = 0;
86
+ while (collection[name + "_" + counter.toString()]) {
87
+ counter++;
88
+ }
89
+ name = name + "_" + counter.toString();
90
+ collection[name] = 1;
91
+ return name;
92
+ }
93
+ else {
94
+ collection[name] = 1;
95
+ return name;
96
+ }
97
+ }
98
+ /**
99
+ * OPCUAServerEndPoint a Server EndPoint.
100
+ * A sever end point is listening to one port
101
+ * note:
102
+ * see OPCUA Release 1.03 part 4 page 108 7.1 ApplicationDescription
103
+ */
104
+ class OPCUAServerEndPoint extends events_1.EventEmitter {
105
+ constructor(options) {
106
+ super();
107
+ this._started = false;
108
+ this._counter = OPCUAServerEndPointCounter++;
109
+ this._policy_deduplicator = {};
110
+ (0, node_opcua_assert_1.assert)(!Object.prototype.hasOwnProperty.call(options, "certificate"), "expecting a certificateChain instead");
111
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(options, "certificateChain"), "expecting a certificateChain");
112
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(options, "privateKey"));
113
+ this.certificateManager = options.certificateManager;
114
+ options.port = options.port || 0;
115
+ this.port = parseInt(options.port.toString(), 10);
116
+ (0, node_opcua_assert_1.assert)(typeof this.port === "number");
117
+ this._certificateChain = options.certificateChain;
118
+ this._privateKey = options.privateKey;
119
+ this._channels = {};
120
+ this.defaultSecureTokenLifetime = options.defaultSecureTokenLifetime || 600000;
121
+ this.maxConnections = options.maxConnections || 20;
122
+ this.timeout = options.timeout || 30000;
123
+ this._server = undefined;
124
+ this._setup_server();
125
+ this._endpoints = [];
126
+ this.objectFactory = options.objectFactory;
127
+ this.bytesWrittenInOldChannels = 0;
128
+ this.bytesReadInOldChannels = 0;
129
+ this.transactionsCountOldChannels = 0;
130
+ this.securityTokenCountOldChannels = 0;
131
+ this.serverInfo = options.serverInfo;
132
+ (0, node_opcua_assert_1.assert)(this.serverInfo !== null && typeof this.serverInfo === "object");
133
+ }
134
+ dispose() {
135
+ this._certificateChain = emptyCertificate;
136
+ this._privateKey = emptyPrivateKeyPEM;
137
+ (0, node_opcua_assert_1.assert)(Object.keys(this._channels).length === 0, "OPCUAServerEndPoint channels must have been deleted");
138
+ this._channels = {};
139
+ this.serverInfo = new node_opcua_service_endpoints_3.ApplicationDescription({});
140
+ this._endpoints = [];
141
+ (0, node_opcua_assert_1.assert)(this._endpoints.length === 0, "endpoints must have been deleted");
142
+ this._endpoints = [];
143
+ this._server = undefined;
144
+ this._listen_callback = undefined;
145
+ this.removeAllListeners();
146
+ }
147
+ toString() {
148
+ const privateKey1 = (0, node_opcua_crypto_1.convertPEMtoDER)(this.getPrivateKey());
149
+ const txt = " end point" +
150
+ this._counter +
151
+ " port = " +
152
+ this.port +
153
+ " l = " +
154
+ this._endpoints.length +
155
+ " " +
156
+ (0, node_opcua_crypto_1.makeSHA1Thumbprint)(this.getCertificateChain()).toString("hex") +
157
+ " " +
158
+ (0, node_opcua_crypto_1.makeSHA1Thumbprint)(privateKey1).toString("hex");
159
+ return txt;
160
+ }
161
+ getChannels() {
162
+ return Object.values(this._channels);
163
+ }
164
+ /**
165
+ * Returns the X509 DER form of the server certificate
166
+ */
167
+ getCertificate() {
168
+ return (0, node_opcua_crypto_1.split_der)(this.getCertificateChain())[0];
169
+ }
170
+ /**
171
+ * Returns the X509 DER form of the server certificate
172
+ */
173
+ getCertificateChain() {
174
+ return this._certificateChain;
175
+ }
176
+ /**
177
+ * the private key
178
+ */
179
+ getPrivateKey() {
180
+ return this._privateKey;
181
+ }
182
+ /**
183
+ * The number of active channel on this end point.
184
+ */
185
+ get currentChannelCount() {
186
+ return Object.keys(this._channels).length;
187
+ }
188
+ /**
189
+ * @method getEndpointDescription
190
+ * @param securityMode
191
+ * @param securityPolicy
192
+ * @return endpoint_description {EndpointDescription|null}
193
+ */
194
+ getEndpointDescription(securityMode, securityPolicy, endpointUrl) {
195
+ const endpoints = this.endpointDescriptions();
196
+ const arr = endpoints.filter(matching_endpoint.bind(this, securityMode, securityPolicy, endpointUrl));
197
+ if (endpointUrl && endpointUrl.length > 0 && !(arr.length === 0 || arr.length === 1)) {
198
+ errorLog("Several matching endpoints have been found : ");
199
+ for (const a of arr) {
200
+ errorLog(" ", a.endpointUrl, node_opcua_secure_channel_1.MessageSecurityMode[securityMode], securityPolicy);
201
+ }
202
+ }
203
+ return arr.length === 0 ? null : arr[0];
204
+ }
205
+ addEndpointDescription(securityMode, securityPolicy, options) {
206
+ if (!options) {
207
+ options = {
208
+ hostname: (0, node_opcua_hostname_1.getFullyQualifiedDomainName)(),
209
+ securityPolicies: [node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256]
210
+ };
211
+ }
212
+ options.allowAnonymous = options.allowAnonymous === undefined ? true : options.allowAnonymous;
213
+ // istanbul ignore next
214
+ if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None && securityPolicy !== node_opcua_secure_channel_1.SecurityPolicy.None) {
215
+ throw new Error(" invalid security ");
216
+ }
217
+ // istanbul ignore next
218
+ if (securityMode !== node_opcua_secure_channel_1.MessageSecurityMode.None && securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
219
+ throw new Error(" invalid security ");
220
+ }
221
+ //
222
+ const port = this.port;
223
+ // resource Path is a string added at the end of the url such as "/UA/Server"
224
+ const resourcePath = (options.resourcePath || "").replace(/\\/g, "/");
225
+ (0, node_opcua_assert_1.assert)(resourcePath.length === 0 || resourcePath.charAt(0) === "/", "resourcePath should start with /");
226
+ const hostname = options.hostname || (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
227
+ const endpointUrl = `opc.tcp://${hostname}:${port}${resourcePath}`;
228
+ const endpoint_desc = this.getEndpointDescription(securityMode, securityPolicy, endpointUrl);
229
+ // istanbul ignore next
230
+ if (endpoint_desc) {
231
+ throw new Error(" endpoint already exist");
232
+ }
233
+ // now build endpointUrl
234
+ this._endpoints.push(_makeEndpointDescription({
235
+ collection: this._policy_deduplicator,
236
+ endpointUrl,
237
+ hostname,
238
+ port,
239
+ server: this.serverInfo,
240
+ serverCertificateChain: this.getCertificateChain(),
241
+ securityMode,
242
+ securityPolicy,
243
+ allowAnonymous: options.allowAnonymous,
244
+ allowUnsecurePassword: options.allowUnsecurePassword,
245
+ resourcePath: options.resourcePath,
246
+ restricted: !!options.restricted,
247
+ securityPolicies: (options === null || options === void 0 ? void 0 : options.securityPolicies) || []
248
+ }));
249
+ }
250
+ addRestrictedEndpointDescription(options) {
251
+ options = Object.assign({}, options);
252
+ options.restricted = true;
253
+ return this.addEndpointDescription(node_opcua_secure_channel_1.MessageSecurityMode.None, node_opcua_secure_channel_1.SecurityPolicy.None, options);
254
+ }
255
+ addStandardEndpointDescriptions(options) {
256
+ options = options || {};
257
+ options.securityModes = options.securityModes || defaultSecurityModes;
258
+ options.securityPolicies = options.securityPolicies || defaultSecurityPolicies;
259
+ const defaultHostname = options.hostname || (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
260
+ let hostnames = [defaultHostname];
261
+ options.alternateHostname = options.alternateHostname || [];
262
+ if (typeof options.alternateHostname === "string") {
263
+ options.alternateHostname = [options.alternateHostname];
264
+ }
265
+ // remove duplicates if any (uniq)
266
+ hostnames = [...new Set(hostnames.concat(options.alternateHostname))];
267
+ for (const alternateHostname of hostnames) {
268
+ const optionsE = options;
269
+ optionsE.hostname = alternateHostname;
270
+ if (options.securityModes.indexOf(node_opcua_secure_channel_1.MessageSecurityMode.None) >= 0) {
271
+ this.addEndpointDescription(node_opcua_secure_channel_1.MessageSecurityMode.None, node_opcua_secure_channel_1.SecurityPolicy.None, optionsE);
272
+ }
273
+ else {
274
+ if (!options.disableDiscovery) {
275
+ this.addRestrictedEndpointDescription(optionsE);
276
+ }
277
+ }
278
+ for (const securityMode of options.securityModes) {
279
+ if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
280
+ continue;
281
+ }
282
+ for (const securityPolicy of options.securityPolicies) {
283
+ if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
284
+ continue;
285
+ }
286
+ this.addEndpointDescription(securityMode, securityPolicy, optionsE);
287
+ }
288
+ }
289
+ }
290
+ }
291
+ /**
292
+ * returns the list of end point descriptions.
293
+ */
294
+ endpointDescriptions() {
295
+ return this._endpoints;
296
+ }
297
+ /**
298
+ * @method listen
299
+ * @async
300
+ */
301
+ listen(callback) {
302
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
303
+ (0, node_opcua_assert_1.assert)(!this._started, "OPCUAServerEndPoint is already listening");
304
+ this._listen_callback = callback;
305
+ this._server.on("error", (err) => {
306
+ debugLog(chalk.red.bold(" error") + " port = " + this.port, err);
307
+ this._started = false;
308
+ this._end_listen(err);
309
+ });
310
+ this._server.on("listening", () => {
311
+ debugLog("server is listening");
312
+ });
313
+ this._server.listen(this.port,
314
+ /*"::",*/ (err) => {
315
+ // 'listening' listener
316
+ debugLog(chalk.green.bold("LISTENING TO PORT "), this.port, "err ", err);
317
+ (0, node_opcua_assert_1.assert)(!err, " cannot listen to port ");
318
+ this._started = true;
319
+ this._end_listen();
320
+ });
321
+ }
322
+ killClientSockets(callback) {
323
+ for (const channel of this.getChannels()) {
324
+ const hacked_channel = channel;
325
+ if (hacked_channel.transport && hacked_channel.transport._socket) {
326
+ // hacked_channel.transport._socket.close();
327
+ hacked_channel.transport._socket.destroy();
328
+ hacked_channel.transport._socket.emit("error", new Error("EPIPE"));
329
+ }
330
+ }
331
+ callback();
332
+ }
333
+ suspendConnection(callback) {
334
+ if (!this._started) {
335
+ return callback(new Error("Connection already suspended !!"));
336
+ }
337
+ // Stops the server from accepting new connections and keeps existing connections.
338
+ // (note from nodejs doc: This function is asynchronous, the server is finally closed
339
+ // when all connections are ended and the server emits a 'close' event.
340
+ // The optional callback will be called once the 'close' event occurs.
341
+ // Unlike that event, it will be called with an Error as its only argument
342
+ // if the server was not open when it was closed.
343
+ this._server.close(() => {
344
+ this._started = false;
345
+ debugLog("Connection has been closed !" + this.port);
346
+ });
347
+ this._started = false;
348
+ callback();
349
+ }
350
+ restoreConnection(callback) {
351
+ this.listen(callback);
352
+ }
353
+ abruptlyInterruptChannels() {
354
+ for (const channel of Object.values(this._channels)) {
355
+ channel.abruptlyInterrupt();
356
+ }
357
+ }
358
+ /**
359
+ * @method shutdown
360
+ * @async
361
+ */
362
+ shutdown(callback) {
363
+ debugLog("OPCUAServerEndPoint#shutdown ");
364
+ if (this._started) {
365
+ // make sure we don't accept new connection any more ...
366
+ this.suspendConnection(() => {
367
+ // shutdown all opened channels ...
368
+ const _channels = Object.values(this._channels);
369
+ async.each(_channels, (channel, callback1) => {
370
+ this.shutdown_channel(channel, callback1);
371
+ }, (err) => {
372
+ /* istanbul ignore next */
373
+ if (!(Object.keys(this._channels).length === 0)) {
374
+ errorLog(" Bad !");
375
+ }
376
+ (0, node_opcua_assert_1.assert)(Object.keys(this._channels).length === 0, "channel must have unregistered themselves");
377
+ callback(err || undefined);
378
+ });
379
+ });
380
+ }
381
+ else {
382
+ callback();
383
+ }
384
+ }
385
+ /**
386
+ * @method start
387
+ * @async
388
+ * @param callback
389
+ */
390
+ start(callback) {
391
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
392
+ this.listen(callback);
393
+ }
394
+ get bytesWritten() {
395
+ const channels = Object.values(this._channels);
396
+ return (this.bytesWrittenInOldChannels +
397
+ channels.reduce((accumulated, channel) => {
398
+ return accumulated + channel.bytesWritten;
399
+ }, 0));
400
+ }
401
+ get bytesRead() {
402
+ const channels = Object.values(this._channels);
403
+ return (this.bytesReadInOldChannels +
404
+ channels.reduce((accumulated, channel) => {
405
+ return accumulated + channel.bytesRead;
406
+ }, 0));
407
+ }
408
+ get transactionsCount() {
409
+ const channels = Object.values(this._channels);
410
+ return (this.transactionsCountOldChannels +
411
+ channels.reduce((accumulated, channel) => {
412
+ return accumulated + channel.transactionsCount;
413
+ }, 0));
414
+ }
415
+ get securityTokenCount() {
416
+ const channels = Object.values(this._channels);
417
+ return (this.securityTokenCountOldChannels +
418
+ channels.reduce((accumulated, channel) => {
419
+ return accumulated + channel.securityTokenCount;
420
+ }, 0));
421
+ }
422
+ get activeChannelCount() {
423
+ return Object.keys(this._channels).length;
424
+ }
425
+ _dump_statistics() {
426
+ this._server.getConnections((err, count) => {
427
+ debugLog(chalk.cyan("CONCURRENT CONNECTION = "), count);
428
+ });
429
+ debugLog(chalk.cyan("MAX CONNECTIONS = "), this._server.maxConnections);
430
+ }
431
+ _setup_server() {
432
+ (0, node_opcua_assert_1.assert)(!this._server);
433
+ this._server = net.createServer({ pauseOnConnect: true }, this._on_client_connection.bind(this));
434
+ // xx console.log(" Server with max connections ", self.maxConnections);
435
+ this._server.maxConnections = this.maxConnections + 1; // plus one extra
436
+ this._listen_callback = undefined;
437
+ this._server
438
+ .on("connection", (socket) => {
439
+ // istanbul ignore next
440
+ if (doDebug) {
441
+ this._dump_statistics();
442
+ debugLog("server connected with : " + socket.remoteAddress + ":" + socket.remotePort);
443
+ }
444
+ })
445
+ .on("close", () => {
446
+ debugLog("server closed : all connections have ended");
447
+ })
448
+ .on("error", (err) => {
449
+ // this could be because the port is already in use
450
+ debugLog(chalk.red.bold("server error: "), err.message);
451
+ });
452
+ }
453
+ _on_client_connection(socket) {
454
+ // a client is attempting a connection on the socket
455
+ socket.setNoDelay(true);
456
+ debugLog("OPCUAServerEndPoint#_on_client_connection", this._started);
457
+ if (!this._started) {
458
+ debugLog(chalk.bgWhite.cyan("OPCUAServerEndPoint#_on_client_connection " +
459
+ "SERVER END POINT IS PROBABLY SHUTTING DOWN !!! - Connection is refused"));
460
+ socket.end();
461
+ return;
462
+ }
463
+ const deny_connection = () => {
464
+ console.log(chalk.bgWhite.cyan("OPCUAServerEndPoint#_on_client_connection " +
465
+ "The maximum number of connection has been reached - Connection is refused"));
466
+ const reason = "maxConnections reached (" + this.maxConnections + ")";
467
+ const socketData = extractSocketData(socket, reason);
468
+ this.emit("connectionRefused", socketData);
469
+ socket.end();
470
+ socket.destroy();
471
+ };
472
+ const establish_connection = () => {
473
+ const nbConnections = Object.keys(this._channels).length;
474
+ debugLog(" nbConnections ", nbConnections, " self._server.maxConnections", this._server.maxConnections, this.maxConnections);
475
+ if (nbConnections >= this.maxConnections) {
476
+ deny_connection();
477
+ return;
478
+ }
479
+ debugLog("OPCUAServerEndPoint._on_client_connection successful => New Channel");
480
+ const channel = new node_opcua_secure_channel_1.ServerSecureChannelLayer({
481
+ defaultSecureTokenLifetime: this.defaultSecureTokenLifetime,
482
+ // objectFactory: this.objectFactory,
483
+ parent: this,
484
+ timeout: this.timeout
485
+ });
486
+ debugLog("channel Timeout = >", channel.timeout);
487
+ socket.resume();
488
+ this._preregisterChannel(channel);
489
+ channel.init(socket, (err) => {
490
+ this._un_pre_registerChannel(channel);
491
+ debugLog(chalk.yellow.bold("Channel#init done"), err);
492
+ if (err) {
493
+ const reason = "openSecureChannel has Failed " + err.message;
494
+ const socketData = extractSocketData(socket, reason);
495
+ const channelData = extractChannelData(channel);
496
+ this.emit("openSecureChannelFailure", socketData, channelData);
497
+ socket.end();
498
+ socket.destroy();
499
+ }
500
+ else {
501
+ debugLog("server receiving a client connection");
502
+ this._registerChannel(channel);
503
+ }
504
+ });
505
+ channel.on("message", (message) => {
506
+ // forward
507
+ this.emit("message", message, channel, this);
508
+ });
509
+ };
510
+ // Each SecureChannel exists until it is explicitly closed or until the last token has expired and the overlap
511
+ // period has elapsed. A Server application should limit the number of SecureChannels.
512
+ // To protect against misbehaving Clients and denial of service attacks, the Server shall close the oldest
513
+ // SecureChannel that has no Session assigned before reaching the maximum number of supported SecureChannels.
514
+ this._prevent_DDOS_Attack(establish_connection, deny_connection);
515
+ }
516
+ _preregisterChannel(channel) {
517
+ // _preregisterChannel is used to keep track of channel for which
518
+ // that are in early stage of the hand shaking process.
519
+ // e.g HEL/ACK and OpenSecureChannel may not have been received yet
520
+ // as they will need to be interrupted when OPCUAServerEndPoint is closed
521
+ (0, node_opcua_assert_1.assert)(this._started, "OPCUAServerEndPoint must be started");
522
+ (0, node_opcua_assert_1.assert)(!Object.prototype.hasOwnProperty.call(this._channels, channel.hashKey), " channel already preregistered!");
523
+ const channelPriv = channel;
524
+ this._channels[channel.hashKey] = channelPriv;
525
+ channelPriv._unpreregisterChannelEvent = () => {
526
+ debugLog("Channel received an abort event during the preregistration phase");
527
+ this._un_pre_registerChannel(channel);
528
+ channel.dispose();
529
+ };
530
+ channel.on("abort", channelPriv._unpreregisterChannelEvent);
531
+ }
532
+ _un_pre_registerChannel(channel) {
533
+ if (!this._channels[channel.hashKey]) {
534
+ debugLog("Already un preregistered ?", channel.hashKey);
535
+ return;
536
+ }
537
+ delete this._channels[channel.hashKey];
538
+ const channelPriv = channel;
539
+ if (typeof channelPriv._unpreregisterChannelEvent === "function") {
540
+ channel.removeListener("abort", channelPriv._unpreregisterChannelEvent);
541
+ channelPriv._unpreregisterChannelEvent = undefined;
542
+ }
543
+ }
544
+ /**
545
+ * @method _registerChannel
546
+ * @param channel
547
+ * @private
548
+ */
549
+ _registerChannel(channel) {
550
+ if (this._started) {
551
+ debugLog(chalk.red("_registerChannel = "), "channel.hashKey = ", channel.hashKey);
552
+ (0, node_opcua_assert_1.assert)(!this._channels[channel.hashKey]);
553
+ this._channels[channel.hashKey] = channel;
554
+ /**
555
+ * @event newChannel
556
+ * @param channel
557
+ */
558
+ this.emit("newChannel", channel);
559
+ channel.on("abort", () => {
560
+ this._unregisterChannel(channel);
561
+ });
562
+ }
563
+ else {
564
+ debugLog("OPCUAServerEndPoint#_registerChannel called when end point is shutdown !");
565
+ debugLog(" -> channel will be forcefully terminated");
566
+ channel.close();
567
+ channel.dispose();
568
+ }
569
+ }
570
+ /**
571
+ * @method _unregisterChannel
572
+ * @param channel
573
+ * @private
574
+ */
575
+ _unregisterChannel(channel) {
576
+ debugLog("_un-registerChannel channel.hashKey", channel.hashKey);
577
+ if (!Object.prototype.hasOwnProperty.call(this._channels, channel.hashKey)) {
578
+ return;
579
+ }
580
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(this._channels, channel.hashKey), "channel is not registered");
581
+ /**
582
+ * @event closeChannel
583
+ * @param channel
584
+ */
585
+ this.emit("closeChannel", channel);
586
+ // keep trace of statistics data from old channel for our own accumulated stats.
587
+ this.bytesWrittenInOldChannels += channel.bytesWritten;
588
+ this.bytesReadInOldChannels += channel.bytesRead;
589
+ this.transactionsCountOldChannels += channel.transactionsCount;
590
+ delete this._channels[channel.hashKey];
591
+ // istanbul ignore next
592
+ if (doDebug) {
593
+ this._dump_statistics();
594
+ debugLog("un-registering channel - Count = ", this.currentChannelCount);
595
+ }
596
+ /// channel.dispose();
597
+ }
598
+ _end_listen(err) {
599
+ (0, node_opcua_assert_1.assert)(typeof this._listen_callback === "function");
600
+ this._listen_callback(err);
601
+ this._listen_callback = undefined;
602
+ }
603
+ /**
604
+ * shutdown_channel
605
+ * @param channel
606
+ * @param inner_callback
607
+ */
608
+ shutdown_channel(channel, inner_callback) {
609
+ (0, node_opcua_assert_1.assert)(typeof inner_callback === "function");
610
+ channel.once("close", () => {
611
+ // xx console.log(" ON CLOSED !!!!");
612
+ });
613
+ channel.close(() => {
614
+ this._unregisterChannel(channel);
615
+ setImmediate(inner_callback);
616
+ });
617
+ }
618
+ /**
619
+ * @private
620
+ */
621
+ _prevent_DDOS_Attack(establish_connection, deny_connection) {
622
+ const nbConnections = this.activeChannelCount;
623
+ if (nbConnections >= this.maxConnections) {
624
+ // istanbul ignore next
625
+ errorLog(chalk.bgRed.white("PREVENTING DDOS ATTACK => maxConnection =" + this.maxConnections));
626
+ const unused_channels = this.getChannels().filter((channel1) => {
627
+ return !channel1.isOpened && !channel1.hasSession;
628
+ });
629
+ if (unused_channels.length === 0) {
630
+ // all channels are in used , we cannot get any
631
+ errorLog("All channels are in used ! let cancel some");
632
+ // istanbul ignore next
633
+ if (doDebug) {
634
+ console.log(" - all channels are used !!!!");
635
+ dumpChannelInfo(this.getChannels());
636
+ }
637
+ setTimeout(deny_connection, 10);
638
+ return;
639
+ }
640
+ // istanbul ignore next
641
+ if (doDebug) {
642
+ console.log(" - Unused channels that can be clobbered", unused_channels.map((channel1) => channel1.hashKey).join(" "));
643
+ }
644
+ const channel = unused_channels[0];
645
+ errorLog("Closing channel ", channel.hashKey);
646
+ channel.close(() => {
647
+ // istanbul ignore next
648
+ if (doDebug) {
649
+ console.log(" _ Unused channel has been closed ", channel.hashKey);
650
+ }
651
+ this._unregisterChannel(channel);
652
+ establish_connection();
653
+ });
654
+ }
655
+ else {
656
+ setImmediate(establish_connection);
657
+ }
658
+ }
659
+ }
660
+ exports.OPCUAServerEndPoint = OPCUAServerEndPoint;
661
+ function estimateSecurityLevel(securityMode, securityPolicy) {
662
+ if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
663
+ return 1;
664
+ }
665
+ let offset = 100;
666
+ if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.SignAndEncrypt) {
667
+ offset = 200;
668
+ }
669
+ switch (securityPolicy) {
670
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic128:
671
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15:
672
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic192:
673
+ return 2; // deprecated => low
674
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic192Rsa15:
675
+ return 3; // deprecated => low
676
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic256:
677
+ return 4; // deprecated => low
678
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic256Rsa15:
679
+ return 4 + offset;
680
+ case node_opcua_secure_channel_1.SecurityPolicy.Aes128_Sha256_RsaOaep:
681
+ return 5 + offset;
682
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256:
683
+ return 6 + offset;
684
+ case node_opcua_secure_channel_1.SecurityPolicy.Aes256_Sha256_RsaPss:
685
+ return 7 + offset;
686
+ default:
687
+ case node_opcua_secure_channel_1.SecurityPolicy.None:
688
+ return 1;
689
+ }
690
+ }
691
+ /**
692
+ * @private
693
+ */
694
+ function _makeEndpointDescription(options) {
695
+ (0, node_opcua_assert_1.assert)(isFinite(options.port), "expecting a valid port number");
696
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(options, "serverCertificateChain"));
697
+ (0, node_opcua_assert_1.assert)(!Object.prototype.hasOwnProperty.call(options, "serverCertificate"));
698
+ (0, node_opcua_assert_1.assert)(!!options.securityMode); // s.MessageSecurityMode
699
+ (0, node_opcua_assert_1.assert)(!!options.securityPolicy);
700
+ (0, node_opcua_assert_1.assert)(options.server !== null && typeof options.server === "object");
701
+ (0, node_opcua_assert_1.assert)(!!options.hostname && typeof options.hostname === "string");
702
+ (0, node_opcua_assert_1.assert)(typeof options.restricted === "boolean");
703
+ const u = (n) => getUniqueName(n, options.collection);
704
+ options.securityLevel =
705
+ options.securityLevel === undefined
706
+ ? estimateSecurityLevel(options.securityMode, options.securityPolicy)
707
+ : options.securityLevel;
708
+ (0, node_opcua_assert_1.assert)(isFinite(options.securityLevel), "expecting a valid securityLevel");
709
+ const securityPolicyUri = (0, node_opcua_secure_channel_1.toURI)(options.securityPolicy);
710
+ const userIdentityTokens = [];
711
+ if (options.securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
712
+ if (options.allowUnsecurePassword) {
713
+ userIdentityTokens.push({
714
+ policyId: u("username_unsecure"),
715
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
716
+ issuedTokenType: null,
717
+ issuerEndpointUrl: null,
718
+ securityPolicyUri: null
719
+ });
720
+ }
721
+ const a = (tokenType, securityPolicy, name) => {
722
+ if (options.securityPolicies.indexOf(securityPolicy) >= 0) {
723
+ userIdentityTokens.push({
724
+ policyId: u(name),
725
+ tokenType,
726
+ issuedTokenType: null,
727
+ issuerEndpointUrl: null,
728
+ securityPolicyUri: securityPolicy
729
+ });
730
+ }
731
+ };
732
+ const onlyCertificateLessConnection = options.onlyCertificateLessConnection === undefined ? false : options.onlyCertificateLessConnection;
733
+ if (!onlyCertificateLessConnection) {
734
+ a(node_opcua_service_endpoints_1.UserTokenType.UserName, node_opcua_secure_channel_1.SecurityPolicy.Basic256, "username_basic256");
735
+ a(node_opcua_service_endpoints_1.UserTokenType.UserName, node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15, "username_basic128Rsa15");
736
+ a(node_opcua_service_endpoints_1.UserTokenType.UserName, node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256, "username_basic256Sha256");
737
+ a(node_opcua_service_endpoints_1.UserTokenType.UserName, node_opcua_secure_channel_1.SecurityPolicy.Aes128_Sha256_RsaOaep, "username_aes128Sha256RsaOaep");
738
+ // X509
739
+ a(node_opcua_service_endpoints_1.UserTokenType.Certificate, node_opcua_secure_channel_1.SecurityPolicy.Basic256, "certificate_basic256");
740
+ a(node_opcua_service_endpoints_1.UserTokenType.Certificate, node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15, "certificate_basic128Rsa15");
741
+ a(node_opcua_service_endpoints_1.UserTokenType.Certificate, node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256, "certificate_basic256Sha256");
742
+ a(node_opcua_service_endpoints_1.UserTokenType.Certificate, node_opcua_secure_channel_1.SecurityPolicy.Aes128_Sha256_RsaOaep, "certificate_aes128Sha256RsaOaep");
743
+ }
744
+ }
745
+ else {
746
+ // note:
747
+ // when channel session security is not "None",
748
+ // userIdentityTokens can be left to null.
749
+ // in this case this mean that secure policy will be the same as connection security policy
750
+ userIdentityTokens.push({
751
+ policyId: u("usernamePassword"),
752
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
753
+ issuedTokenType: null,
754
+ issuerEndpointUrl: null,
755
+ securityPolicyUri: null
756
+ });
757
+ userIdentityTokens.push({
758
+ policyId: u("certificateX509"),
759
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.Certificate,
760
+ issuedTokenType: null,
761
+ issuerEndpointUrl: null,
762
+ securityPolicyUri: null
763
+ });
764
+ }
765
+ if (options.allowAnonymous) {
766
+ userIdentityTokens.push({
767
+ policyId: u("anonymous"),
768
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.Anonymous,
769
+ issuedTokenType: null,
770
+ issuerEndpointUrl: null,
771
+ securityPolicyUri: null
772
+ });
773
+ }
774
+ // return the endpoint object
775
+ const endpoint = new node_opcua_service_endpoints_2.EndpointDescription({
776
+ endpointUrl: options.endpointUrl,
777
+ server: undefined,
778
+ serverCertificate: options.serverCertificateChain,
779
+ securityMode: options.securityMode,
780
+ securityPolicyUri,
781
+ userIdentityTokens,
782
+ securityLevel: options.securityLevel,
783
+ transportProfileUri: default_transportProfileUri
784
+ });
785
+ endpoint.__defineGetter__("endpointUrl", () => {
786
+ return (0, node_opcua_hostname_1.resolveFullyQualifiedDomainName)(options.endpointUrl);
787
+ });
788
+ endpoint.server = options.server;
789
+ endpoint.restricted = options.restricted;
790
+ return endpoint;
791
+ }
792
+ /**
793
+ * return true if the end point matches security mode and policy
794
+ * @param endpoint
795
+ * @param securityMode
796
+ * @param securityPolicy
797
+ * @internal
798
+ *
799
+ */
800
+ function matching_endpoint(securityMode, securityPolicy, endpointUrl, endpoint) {
801
+ (0, node_opcua_assert_1.assert)(endpoint instanceof node_opcua_service_endpoints_2.EndpointDescription);
802
+ const endpoint_securityPolicy = (0, node_opcua_secure_channel_1.fromURI)(endpoint.securityPolicyUri);
803
+ if (endpointUrl && endpoint.endpointUrl !== endpointUrl) {
804
+ return false;
805
+ }
806
+ return endpoint.securityMode === securityMode && endpoint_securityPolicy === securityPolicy;
807
+ }
808
+ const defaultSecurityModes = [node_opcua_secure_channel_1.MessageSecurityMode.None, node_opcua_secure_channel_1.MessageSecurityMode.Sign, node_opcua_secure_channel_1.MessageSecurityMode.SignAndEncrypt];
809
+ const defaultSecurityPolicies = [
810
+ node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15,
811
+ node_opcua_secure_channel_1.SecurityPolicy.Basic256,
812
+ // xx UNUSED!! SecurityPolicy.Basic256Rsa15,
813
+ node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256,
814
+ node_opcua_secure_channel_1.SecurityPolicy.Aes128_Sha256_RsaOaep
815
+ // NO USED YET SecurityPolicy.Aes256_Sha256_RsaPss
816
+ ];
817
817
  //# sourceMappingURL=server_end_point.js.map