node-opcua-server 2.51.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 (100) hide show
  1. package/.mocharc.yml +10 -0
  2. package/LICENSE +20 -0
  3. package/dist/base_server.d.ts +110 -0
  4. package/dist/base_server.js +476 -0
  5. package/dist/base_server.js.map +1 -0
  6. package/dist/factory.d.ts +10 -0
  7. package/dist/factory.js +24 -0
  8. package/dist/factory.js.map +1 -0
  9. package/dist/history_server_capabilities.d.ts +35 -0
  10. package/dist/history_server_capabilities.js +44 -0
  11. package/dist/history_server_capabilities.js.map +1 -0
  12. package/dist/i_channel_data.d.ts +13 -0
  13. package/dist/i_channel_data.js +3 -0
  14. package/dist/i_channel_data.js.map +1 -0
  15. package/dist/i_register_server_manager.d.ts +16 -0
  16. package/dist/i_register_server_manager.js +3 -0
  17. package/dist/i_register_server_manager.js.map +1 -0
  18. package/dist/i_server_side_publish_engine.d.ts +36 -0
  19. package/dist/i_server_side_publish_engine.js +50 -0
  20. package/dist/i_server_side_publish_engine.js.map +1 -0
  21. package/dist/i_socket_data.d.ts +11 -0
  22. package/dist/i_socket_data.js +3 -0
  23. package/dist/i_socket_data.js.map +1 -0
  24. package/dist/index.d.ts +14 -0
  25. package/dist/index.js +27 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/monitored_item.d.ts +173 -0
  28. package/dist/monitored_item.js +1006 -0
  29. package/dist/monitored_item.js.map +1 -0
  30. package/dist/node_sampler.d.ts +3 -0
  31. package/dist/node_sampler.js +76 -0
  32. package/dist/node_sampler.js.map +1 -0
  33. package/dist/opcua_server.d.ts +668 -0
  34. package/dist/opcua_server.js +2407 -0
  35. package/dist/opcua_server.js.map +1 -0
  36. package/dist/queue.d.ts +11 -0
  37. package/dist/queue.js +71 -0
  38. package/dist/queue.js.map +1 -0
  39. package/dist/register_server_manager.d.ts +92 -0
  40. package/dist/register_server_manager.js +574 -0
  41. package/dist/register_server_manager.js.map +1 -0
  42. package/dist/register_server_manager_hidden.d.ts +17 -0
  43. package/dist/register_server_manager_hidden.js +28 -0
  44. package/dist/register_server_manager_hidden.js.map +1 -0
  45. package/dist/register_server_manager_mdns_only.d.ts +19 -0
  46. package/dist/register_server_manager_mdns_only.js +58 -0
  47. package/dist/register_server_manager_mdns_only.js.map +1 -0
  48. package/dist/server_capabilities.d.ts +61 -0
  49. package/dist/server_capabilities.js +109 -0
  50. package/dist/server_capabilities.js.map +1 -0
  51. package/dist/server_end_point.d.ts +180 -0
  52. package/dist/server_end_point.js +825 -0
  53. package/dist/server_end_point.js.map +1 -0
  54. package/dist/server_engine.d.ts +311 -0
  55. package/dist/server_engine.js +1659 -0
  56. package/dist/server_engine.js.map +1 -0
  57. package/dist/server_publish_engine.d.ts +109 -0
  58. package/dist/server_publish_engine.js +531 -0
  59. package/dist/server_publish_engine.js.map +1 -0
  60. package/dist/server_publish_engine_for_orphan_subscriptions.d.ts +16 -0
  61. package/dist/server_publish_engine_for_orphan_subscriptions.js +50 -0
  62. package/dist/server_publish_engine_for_orphan_subscriptions.js.map +1 -0
  63. package/dist/server_session.d.ts +176 -0
  64. package/dist/server_session.js +734 -0
  65. package/dist/server_session.js.map +1 -0
  66. package/dist/server_subscription.d.ts +393 -0
  67. package/dist/server_subscription.js +1313 -0
  68. package/dist/server_subscription.js.map +1 -0
  69. package/dist/sessions_compatible_for_transfer.d.ts +2 -0
  70. package/dist/sessions_compatible_for_transfer.js +36 -0
  71. package/dist/sessions_compatible_for_transfer.js.map +1 -0
  72. package/dist/validate_filter.d.ts +5 -0
  73. package/dist/validate_filter.js +64 -0
  74. package/dist/validate_filter.js.map +1 -0
  75. package/package.json +88 -0
  76. package/source/base_server.ts +617 -0
  77. package/source/factory.ts +25 -0
  78. package/source/history_server_capabilities.ts +75 -0
  79. package/source/i_channel_data.ts +17 -0
  80. package/source/i_register_server_manager.ts +24 -0
  81. package/source/i_server_side_publish_engine.ts +77 -0
  82. package/source/i_socket_data.ts +11 -0
  83. package/source/index.ts +14 -0
  84. package/source/monitored_item.ts +1303 -0
  85. package/source/node_sampler.ts +82 -0
  86. package/source/opcua_server.ts +3742 -0
  87. package/source/queue.ts +73 -0
  88. package/source/register_server_manager.ts +744 -0
  89. package/source/register_server_manager_hidden.ts +33 -0
  90. package/source/register_server_manager_mdns_only.ts +69 -0
  91. package/source/server_capabilities.ts +177 -0
  92. package/source/server_end_point.ts +1182 -0
  93. package/source/server_engine.ts +2167 -0
  94. package/source/server_publish_engine.ts +657 -0
  95. package/source/server_publish_engine_for_orphan_subscriptions.ts +52 -0
  96. package/source/server_session.ts +931 -0
  97. package/source/server_subscription.ts +1792 -0
  98. package/source/sessions_compatible_for_transfer.ts +33 -0
  99. package/source/validate_filter.ts +86 -0
  100. package/test_helpers/create_certificates.js +1 -0
@@ -0,0 +1,2407 @@
1
+ "use strict";
2
+ /**
3
+ * @module node-opcua-server
4
+ */
5
+ // tslint:disable:no-console
6
+ // tslint:disable:max-line-length
7
+ // tslint:disable:unified-signatures
8
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
+ return new (P || (P = Promise))(function (resolve, reject) {
11
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
15
+ });
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.OPCUAServer = exports.RegisterServerMethod = void 0;
19
+ const crypto = require("crypto");
20
+ const util_1 = require("util");
21
+ const async = require("async");
22
+ const chalk = require("chalk");
23
+ const node_opcua_hostname_1 = require("node-opcua-hostname");
24
+ const node_opcua_assert_1 = require("node-opcua-assert");
25
+ const utils = require("node-opcua-utils");
26
+ const node_opcua_address_space_1 = require("node-opcua-address-space");
27
+ const node_opcua_certificate_manager_1 = require("node-opcua-certificate-manager");
28
+ const node_opcua_common_1 = require("node-opcua-common");
29
+ const node_opcua_crypto_1 = require("node-opcua-crypto");
30
+ const node_opcua_data_model_1 = require("node-opcua-data-model");
31
+ const node_opcua_data_value_1 = require("node-opcua-data-value");
32
+ const node_opcua_debug_1 = require("node-opcua-debug");
33
+ const node_opcua_object_registry_1 = require("node-opcua-object-registry");
34
+ const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
35
+ const node_opcua_service_browse_1 = require("node-opcua-service-browse");
36
+ const node_opcua_service_call_1 = require("node-opcua-service-call");
37
+ const node_opcua_service_endpoints_1 = require("node-opcua-service-endpoints");
38
+ const node_opcua_service_history_1 = require("node-opcua-service-history");
39
+ const node_opcua_service_node_management_1 = require("node-opcua-service-node-management");
40
+ const node_opcua_service_query_1 = require("node-opcua-service-query");
41
+ const node_opcua_service_read_1 = require("node-opcua-service-read");
42
+ const node_opcua_service_register_node_1 = require("node-opcua-service-register-node");
43
+ const node_opcua_service_session_1 = require("node-opcua-service-session");
44
+ const node_opcua_service_subscription_1 = require("node-opcua-service-subscription");
45
+ const node_opcua_service_translate_browse_path_1 = require("node-opcua-service-translate-browse-path");
46
+ const node_opcua_service_write_1 = require("node-opcua-service-write");
47
+ const node_opcua_status_code_1 = require("node-opcua-status-code");
48
+ const node_opcua_types_1 = require("node-opcua-types");
49
+ const node_opcua_variant_1 = require("node-opcua-variant");
50
+ const node_opcua_variant_2 = require("node-opcua-variant");
51
+ const node_opcua_utils_1 = require("node-opcua-utils");
52
+ const base_server_1 = require("./base_server");
53
+ const factory_1 = require("./factory");
54
+ const monitored_item_1 = require("./monitored_item");
55
+ const register_server_manager_1 = require("./register_server_manager");
56
+ const register_server_manager_hidden_1 = require("./register_server_manager_hidden");
57
+ const register_server_manager_mdns_only_1 = require("./register_server_manager_mdns_only");
58
+ const server_end_point_1 = require("./server_end_point");
59
+ const server_engine_1 = require("./server_engine");
60
+ function isSubscriptionIdInvalid(subscriptionId) {
61
+ return subscriptionId < 0 || subscriptionId >= 0xffffffff;
62
+ }
63
+ // tslint:disable-next-line:no-var-requires
64
+ const package_info = require("../package.json");
65
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
66
+ const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
67
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
68
+ const default_maxAllowedSessionNumber = 10;
69
+ const default_maxConnectionsPerEndpoint = 10;
70
+ function g_sendError(channel, message, ResponseClass, statusCode) {
71
+ const response = new ResponseClass({
72
+ responseHeader: { serviceResult: statusCode }
73
+ });
74
+ return channel.send_response("MSG", response, message);
75
+ }
76
+ const default_build_info = {
77
+ manufacturerName: "NodeOPCUA : MIT Licence ( see http://node-opcua.github.io/)",
78
+ productName: "NodeOPCUA-Server",
79
+ productUri: null,
80
+ softwareVersion: package_info.version,
81
+ buildNumber: "0",
82
+ buildDate: new Date(2020, 1, 1)
83
+ // xx buildDate: fs.statSync(package_json_file).mtime
84
+ };
85
+ const minSessionTimeout = 100; // 100 milliseconds
86
+ const defaultSessionTimeout = 1000 * 30; // 30 seconds
87
+ const maxSessionTimeout = 1000 * 60 * 50; // 50 minutes
88
+ function _adjust_session_timeout(sessionTimeout) {
89
+ let revisedSessionTimeout = sessionTimeout || defaultSessionTimeout;
90
+ revisedSessionTimeout = Math.min(revisedSessionTimeout, maxSessionTimeout);
91
+ revisedSessionTimeout = Math.max(revisedSessionTimeout, minSessionTimeout);
92
+ return revisedSessionTimeout;
93
+ }
94
+ function channel_has_session(channel, session) {
95
+ if (session.channel === channel) {
96
+ (0, node_opcua_assert_1.assert)(channel.sessionTokens.hasOwnProperty(session.authenticationToken.toString()));
97
+ return true;
98
+ }
99
+ return false;
100
+ }
101
+ function moveSessionToChannel(session, channel) {
102
+ debugLog("moveSessionToChannel sessionId", session.nodeId, " channelId=", channel.channelId);
103
+ if (session.publishEngine) {
104
+ session.publishEngine.cancelPendingPublishRequestBeforeChannelChange();
105
+ }
106
+ session._detach_channel();
107
+ session._attach_channel(channel);
108
+ (0, node_opcua_assert_1.assert)(session.channel.channelId === channel.channelId);
109
+ }
110
+ function _attempt_to_close_some_old_unactivated_session(server) {
111
+ return __awaiter(this, void 0, void 0, function* () {
112
+ const session = server.engine.getOldestUnactivatedSession();
113
+ if (session) {
114
+ yield server.engine.closeSession(session.authenticationToken, false, "Forcing");
115
+ }
116
+ });
117
+ }
118
+ function getRequiredEndpointInfo(endpoint) {
119
+ (0, node_opcua_assert_1.assert)(endpoint instanceof node_opcua_types_1.EndpointDescription);
120
+ // It is recommended that Servers only include the server.applicationUri, endpointUrl, securityMode,
121
+ // securityPolicyUri, userIdentityTokens, transportProfileUri and securityLevel with all
122
+ // other parameters set to null. Only the recommended parameters shall be verified by
123
+ // the client.
124
+ const e = new node_opcua_types_1.EndpointDescription({
125
+ endpointUrl: endpoint.endpointUrl,
126
+ securityLevel: endpoint.securityLevel,
127
+ securityMode: endpoint.securityMode,
128
+ securityPolicyUri: endpoint.securityPolicyUri,
129
+ server: {
130
+ applicationUri: endpoint.server.applicationUri,
131
+ applicationType: endpoint.server.applicationType,
132
+ applicationName: endpoint.server.applicationName
133
+ // ... to be continued after verifying what fields are actually needed
134
+ },
135
+ transportProfileUri: endpoint.transportProfileUri,
136
+ userIdentityTokens: endpoint.userIdentityTokens
137
+ });
138
+ // reduce even further by explicitly setting unwanted members to null
139
+ e.server.productUri = null;
140
+ e.server.applicationName = null;
141
+ // xx e.server.applicationType = null as any;
142
+ e.server.gatewayServerUri = null;
143
+ e.server.discoveryProfileUri = null;
144
+ e.server.discoveryUrls = null;
145
+ e.serverCertificate = null;
146
+ return e;
147
+ }
148
+ // serverUri String This value is only specified if the EndpointDescription has a gatewayServerUri.
149
+ // This value is the applicationUri from the EndpointDescription which is the applicationUri for the
150
+ // underlying Server. The type EndpointDescription is defined in 7.10.
151
+ function _serverEndpointsForCreateSessionResponse(server, endpointUrl, serverUri) {
152
+ serverUri = null; // unused then
153
+ // The Server shall return a set of EndpointDescriptions available for the serverUri specified in the request.
154
+ // It is recommended that Servers only include the endpointUrl, securityMode,
155
+ // securityPolicyUri, userIdentityTokens, transportProfileUri and securityLevel with all other parameters
156
+ // set to null. Only the recommended parameters shall be verified by the client.
157
+ return server
158
+ ._get_endpoints(endpointUrl)
159
+ .filter((e) => !e.restricted) // remove restricted endpoints
160
+ .filter((e) => (0, node_opcua_utils_1.matchUri)(e.endpointUrl, endpointUrl))
161
+ .map(getRequiredEndpointInfo);
162
+ }
163
+ function adjustSecurityPolicy(channel, userTokenPolicy_securityPolicyUri) {
164
+ // check that userIdentityToken
165
+ let securityPolicy = (0, node_opcua_secure_channel_1.fromURI)(userTokenPolicy_securityPolicyUri);
166
+ // if the security policy is not specified we use the session security policy
167
+ if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.Invalid) {
168
+ securityPolicy = (0, node_opcua_secure_channel_1.fromURI)(channel.clientSecurityHeader.securityPolicyUri);
169
+ (0, node_opcua_assert_1.assert)(securityPolicy !== node_opcua_secure_channel_1.SecurityPolicy.Invalid);
170
+ }
171
+ return securityPolicy;
172
+ }
173
+ function findUserTokenByPolicy(endpoint_description, userTokenType, policyId) {
174
+ (0, node_opcua_assert_1.assert)(endpoint_description instanceof node_opcua_types_1.EndpointDescription);
175
+ const r = endpoint_description.userIdentityTokens.filter((userIdentity) => userIdentity.tokenType === userTokenType && (!policyId || userIdentity.policyId === policyId));
176
+ return r.length === 0 ? null : r[0];
177
+ }
178
+ function findUserTokenPolicy(endpoint_description, userTokenType) {
179
+ (0, node_opcua_assert_1.assert)(endpoint_description instanceof node_opcua_types_1.EndpointDescription);
180
+ const r = endpoint_description.userIdentityTokens.filter((userIdentity) => {
181
+ (0, node_opcua_assert_1.assert)(userIdentity.tokenType !== undefined);
182
+ return userIdentity.tokenType === userTokenType;
183
+ });
184
+ return r.length === 0 ? null : r[0];
185
+ }
186
+ function createAnonymousIdentityToken(endpoint_desc) {
187
+ (0, node_opcua_assert_1.assert)(endpoint_desc instanceof node_opcua_types_1.EndpointDescription);
188
+ const userTokenPolicy = findUserTokenPolicy(endpoint_desc, node_opcua_service_endpoints_1.UserTokenType.Anonymous);
189
+ if (!userTokenPolicy) {
190
+ throw new Error("Cannot find ANONYMOUS user token policy in end point description");
191
+ }
192
+ return new node_opcua_service_session_1.AnonymousIdentityToken({ policyId: userTokenPolicy.policyId });
193
+ }
194
+ function sameIdentityToken(token1, token2) {
195
+ if (token1 instanceof node_opcua_service_session_1.UserNameIdentityToken) {
196
+ if (!(token2 instanceof node_opcua_service_session_1.UserNameIdentityToken)) {
197
+ return false;
198
+ }
199
+ if (token1.userName !== token2.userName) {
200
+ return false;
201
+ }
202
+ if (token1.password.toString("hex") !== token2.password.toString("hex")) {
203
+ return false;
204
+ }
205
+ }
206
+ else if (token1 instanceof node_opcua_service_session_1.AnonymousIdentityToken) {
207
+ if (!(token2 instanceof node_opcua_service_session_1.AnonymousIdentityToken)) {
208
+ return false;
209
+ }
210
+ if (token1.policyId !== token2.policyId) {
211
+ return false;
212
+ }
213
+ return true;
214
+ }
215
+ (0, node_opcua_assert_1.assert)(false, " Not implemented yet");
216
+ return false;
217
+ }
218
+ function getTokenType(userIdentityToken) {
219
+ if (userIdentityToken instanceof node_opcua_service_session_1.AnonymousIdentityToken) {
220
+ return node_opcua_service_endpoints_1.UserTokenType.Anonymous;
221
+ }
222
+ else if (userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken) {
223
+ return node_opcua_service_endpoints_1.UserTokenType.UserName;
224
+ }
225
+ else if (userIdentityToken instanceof node_opcua_types_1.IssuedIdentityToken) {
226
+ return node_opcua_service_endpoints_1.UserTokenType.IssuedToken;
227
+ }
228
+ else if (userIdentityToken instanceof node_opcua_service_session_1.X509IdentityToken) {
229
+ return node_opcua_service_endpoints_1.UserTokenType.Certificate;
230
+ }
231
+ return node_opcua_service_endpoints_1.UserTokenType.Invalid;
232
+ }
233
+ function thumbprint(certificate) {
234
+ return certificate ? certificate.toString("base64") : "";
235
+ }
236
+ /*=== private
237
+ *
238
+ * perform the read operation on a given node for a monitored item.
239
+ * this method DOES NOT apply to Variable Values attribute
240
+ *
241
+ * @param self
242
+ * @param oldValue
243
+ * @param node
244
+ * @param itemToMonitor
245
+ * @private
246
+ */
247
+ function monitoredItem_read_and_record_value(self, context, oldValue, node, itemToMonitor, callback) {
248
+ (0, node_opcua_assert_1.assert)(self instanceof monitored_item_1.MonitoredItem);
249
+ (0, node_opcua_assert_1.assert)(oldValue instanceof node_opcua_data_value_1.DataValue);
250
+ (0, node_opcua_assert_1.assert)(itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value);
251
+ const dataValue = node.readAttribute(context, itemToMonitor.attributeId, itemToMonitor.indexRange, itemToMonitor.dataEncoding);
252
+ callback(null, dataValue);
253
+ }
254
+ /*== private
255
+ * @method monitoredItem_read_and_record_value_async
256
+ * this method applies to Variable Values attribute
257
+ * @param self
258
+ * @param oldValue
259
+ * @param node
260
+ * @param itemToMonitor
261
+ * @private
262
+ */
263
+ function monitoredItem_read_and_record_value_async(self, context, oldValue, node, itemToMonitor, callback) {
264
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
265
+ (0, node_opcua_assert_1.assert)(itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value);
266
+ (0, node_opcua_assert_1.assert)(self instanceof monitored_item_1.MonitoredItem);
267
+ (0, node_opcua_assert_1.assert)(oldValue instanceof node_opcua_data_value_1.DataValue);
268
+ // do it asynchronously ( this is only valid for value attributes )
269
+ (0, node_opcua_assert_1.assert)(itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value);
270
+ node.readValueAsync(context, (err, dataValue) => {
271
+ callback(err, dataValue);
272
+ });
273
+ }
274
+ function build_scanning_node_function(context, addressSpace, monitoredItem, itemToMonitor) {
275
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
276
+ (0, node_opcua_assert_1.assert)(itemToMonitor instanceof node_opcua_service_read_1.ReadValueId);
277
+ const node = addressSpace.findNode(itemToMonitor.nodeId);
278
+ /* istanbul ignore next */
279
+ if (!node) {
280
+ errorLog(" INVALID NODE ID , ", itemToMonitor.nodeId.toString());
281
+ (0, node_opcua_debug_1.dump)(itemToMonitor);
282
+ return (oldData, callback) => {
283
+ callback(null, new node_opcua_data_value_1.DataValue({
284
+ statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown,
285
+ value: { dataType: node_opcua_variant_1.DataType.Null, value: 0 }
286
+ }));
287
+ };
288
+ }
289
+ ///// !!monitoredItem.setNode(node);
290
+ if (itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value) {
291
+ const monitoredItem_read_and_record_value_func = itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value && typeof node.readValueAsync === "function"
292
+ ? monitoredItem_read_and_record_value_async
293
+ : monitoredItem_read_and_record_value;
294
+ return function func(oldDataValue, callback) {
295
+ (0, node_opcua_assert_1.assert)(this instanceof monitored_item_1.MonitoredItem);
296
+ (0, node_opcua_assert_1.assert)(oldDataValue instanceof node_opcua_data_value_1.DataValue);
297
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
298
+ monitoredItem_read_and_record_value_func(this, context, oldDataValue, node, itemToMonitor, callback);
299
+ };
300
+ }
301
+ else {
302
+ // Attributes, other than the Value Attribute, are only monitored for a change in value.
303
+ // The filter is not used for these Attributes. Any change in value for these Attributes
304
+ // causes a Notification to be generated.
305
+ // only record value when it has changed
306
+ return function func(oldDataValue, callback) {
307
+ const self = this;
308
+ (0, node_opcua_assert_1.assert)(self instanceof monitored_item_1.MonitoredItem);
309
+ (0, node_opcua_assert_1.assert)(oldDataValue instanceof node_opcua_data_value_1.DataValue);
310
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
311
+ const newDataValue = node.readAttribute(null, itemToMonitor.attributeId);
312
+ callback(null, newDataValue);
313
+ };
314
+ }
315
+ }
316
+ function prepareMonitoredItem(context, addressSpace, monitoredItem) {
317
+ const itemToMonitor = monitoredItem.itemToMonitor;
318
+ const readNodeFunc = build_scanning_node_function(context, addressSpace, monitoredItem, itemToMonitor);
319
+ monitoredItem.samplingFunc = readNodeFunc;
320
+ }
321
+ function isMonitoringModeValid(monitoringMode) {
322
+ (0, node_opcua_assert_1.assert)(node_opcua_types_1.MonitoringMode.Invalid !== undefined);
323
+ return monitoringMode !== node_opcua_types_1.MonitoringMode.Invalid && monitoringMode <= node_opcua_types_1.MonitoringMode.Reporting;
324
+ }
325
+ function _installRegisterServerManager(self) {
326
+ (0, node_opcua_assert_1.assert)(self instanceof OPCUAServer);
327
+ (0, node_opcua_assert_1.assert)(!self.registerServerManager);
328
+ /* istanbul ignore next */
329
+ if (!self.registerServerMethod) {
330
+ throw new Error("Internal Error");
331
+ }
332
+ switch (self.registerServerMethod) {
333
+ case RegisterServerMethod.HIDDEN:
334
+ self.registerServerManager = new register_server_manager_hidden_1.RegisterServerManagerHidden({
335
+ server: self
336
+ });
337
+ break;
338
+ case RegisterServerMethod.MDNS:
339
+ self.registerServerManager = new register_server_manager_mdns_only_1.RegisterServerManagerMDNSONLY({
340
+ server: self
341
+ });
342
+ break;
343
+ case RegisterServerMethod.LDS:
344
+ self.registerServerManager = new register_server_manager_1.RegisterServerManager({
345
+ discoveryServerEndpointUrl: self.discoveryServerEndpointUrl,
346
+ server: self
347
+ });
348
+ break;
349
+ /* istanbul ignore next */
350
+ default:
351
+ throw new Error("Invalid switch");
352
+ }
353
+ self.registerServerManager.on("serverRegistrationPending", () => {
354
+ /**
355
+ * emitted when the server is trying to registered the LDS
356
+ * but when the connection to the lds has failed
357
+ * serverRegistrationPending is sent when the backoff signal of the
358
+ * connection process is raised
359
+ * @event serverRegistrationPending
360
+ */
361
+ debugLog("serverRegistrationPending");
362
+ self.emit("serverRegistrationPending");
363
+ });
364
+ self.registerServerManager.on("serverRegistered", () => {
365
+ /**
366
+ * emitted when the server is successfully registered to the LDS
367
+ * @event serverRegistered
368
+ */
369
+ debugLog("serverRegistered");
370
+ self.emit("serverRegistered");
371
+ });
372
+ self.registerServerManager.on("serverRegistrationRenewed", () => {
373
+ /**
374
+ * emitted when the server has successfully renewed its registration to the LDS
375
+ * @event serverRegistrationRenewed
376
+ */
377
+ debugLog("serverRegistrationRenewed");
378
+ self.emit("serverRegistrationRenewed");
379
+ });
380
+ self.registerServerManager.on("serverUnregistered", () => {
381
+ debugLog("serverUnregistered");
382
+ /**
383
+ * emitted when the server is successfully unregistered to the LDS
384
+ * ( for instance during shutdown)
385
+ * @event serverUnregistered
386
+ */
387
+ self.emit("serverUnregistered");
388
+ });
389
+ }
390
+ var RegisterServerMethod;
391
+ (function (RegisterServerMethod) {
392
+ RegisterServerMethod[RegisterServerMethod["HIDDEN"] = 1] = "HIDDEN";
393
+ RegisterServerMethod[RegisterServerMethod["MDNS"] = 2] = "MDNS";
394
+ RegisterServerMethod[RegisterServerMethod["LDS"] = 3] = "LDS"; // the server registers itself to the LDS or LDS-ME (Local Discovery Server)
395
+ })(RegisterServerMethod = exports.RegisterServerMethod || (exports.RegisterServerMethod = {}));
396
+ const g_requestExactEndpointUrl = !!process.env.NODEOPCUA_SERVER_REQUEST_EXACT_ENDPOINT_URL;
397
+ /**
398
+ *
399
+ */
400
+ class OPCUAServer extends base_server_1.OPCUABaseServer {
401
+ constructor(options) {
402
+ super(options);
403
+ /**
404
+ * false if anonymous connection are not allowed
405
+ */
406
+ this.allowAnonymous = false;
407
+ options = options || {};
408
+ this.options = options;
409
+ /**
410
+ * @property maxAllowedSessionNumber
411
+ */
412
+ this.maxAllowedSessionNumber = options.maxAllowedSessionNumber || default_maxAllowedSessionNumber;
413
+ /**
414
+ * @property maxConnectionsPerEndpoint
415
+ */
416
+ this.maxConnectionsPerEndpoint = options.maxConnectionsPerEndpoint || default_maxConnectionsPerEndpoint;
417
+ // build Info
418
+ const buildInfo = Object.assign(Object.assign({}, default_build_info), options.buildInfo);
419
+ // repair product name
420
+ buildInfo.productUri = buildInfo.productUri || this.serverInfo.productUri;
421
+ this.serverInfo.productUri = this.serverInfo.productUri || buildInfo.productUri;
422
+ this.userManager = options.userManager || {};
423
+ if (typeof this.userManager.isValidUser !== "function") {
424
+ this.userManager.isValidUser = ( /*userName,password*/) => {
425
+ return false;
426
+ };
427
+ }
428
+ options.allowAnonymous = options.allowAnonymous === undefined ? true : !!options.allowAnonymous;
429
+ /**
430
+ * @property allowAnonymous
431
+ */
432
+ this.allowAnonymous = options.allowAnonymous;
433
+ this.discoveryServerEndpointUrl = options.discoveryServerEndpointUrl || "opc.tcp://%FQDN%:4840";
434
+ (0, node_opcua_assert_1.assert)(typeof this.discoveryServerEndpointUrl === "string");
435
+ this.serverInfo.applicationType = node_opcua_service_endpoints_1.ApplicationType.Server;
436
+ this.capabilitiesForMDNS = options.capabilitiesForMDNS || ["NA"];
437
+ this.registerServerMethod = options.registerServerMethod || RegisterServerMethod.HIDDEN;
438
+ _installRegisterServerManager(this);
439
+ if (!options.userCertificateManager) {
440
+ this.userCertificateManager = (0, node_opcua_certificate_manager_1.getDefaultCertificateManager)("UserPKI");
441
+ }
442
+ else {
443
+ this.userCertificateManager = options.userCertificateManager;
444
+ }
445
+ // note: we need to delay initialization of endpoint as certain resources
446
+ // such as %FQDN% might not be ready yet at this stage
447
+ this._delayInit = () => __awaiter(this, void 0, void 0, function* () {
448
+ /* istanbul ignore next */
449
+ if (!options) {
450
+ throw new Error("Internal Error");
451
+ }
452
+ // to check => this.serverInfo.applicationName = this.serverInfo.productName || buildInfo.productName;
453
+ // note: applicationUri is handled in a special way
454
+ this.engine = new server_engine_1.ServerEngine({
455
+ applicationUri: () => this.serverInfo.applicationUri,
456
+ buildInfo,
457
+ isAuditing: options.isAuditing,
458
+ serverCapabilities: options.serverCapabilities
459
+ });
460
+ this.objectFactory = new factory_1.Factory(this.engine);
461
+ const endpointDefinitions = options.alternateEndpoints || [];
462
+ const hostname = (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
463
+ endpointDefinitions.push({
464
+ port: options.port || 26543,
465
+ allowAnonymous: options.allowAnonymous,
466
+ alternateHostname: options.alternateHostname,
467
+ disableDiscovery: options.disableDiscovery,
468
+ hostname: options.hostname || hostname,
469
+ securityModes: options.securityModes,
470
+ securityPolicies: options.securityPolicies
471
+ });
472
+ // todo should self.serverInfo.productUri match self.engine.buildInfo.productUri ?
473
+ for (const endpointOptions of endpointDefinitions) {
474
+ const endPoint = this.createEndpointDescriptions(options, endpointOptions);
475
+ this.endpoints.push(endPoint);
476
+ endPoint.on("message", (message, channel) => {
477
+ this.on_request(message, channel);
478
+ });
479
+ endPoint.on("error", (err) => {
480
+ errorLog("OPCUAServer endpoint error", err);
481
+ // set serverState to ServerState.Failed;
482
+ this.engine.setServerState(node_opcua_common_1.ServerState.Failed);
483
+ this.shutdown(() => {
484
+ /* empty */
485
+ });
486
+ });
487
+ }
488
+ });
489
+ }
490
+ /**
491
+ * total number of bytes written by the server since startup
492
+ */
493
+ get bytesWritten() {
494
+ return this.endpoints.reduce((accumulated, endpoint) => {
495
+ return accumulated + endpoint.bytesWritten;
496
+ }, 0);
497
+ }
498
+ /**
499
+ * total number of bytes read by the server since startup
500
+ */
501
+ get bytesRead() {
502
+ return this.endpoints.reduce((accumulated, endpoint) => {
503
+ return accumulated + endpoint.bytesRead;
504
+ }, 0);
505
+ }
506
+ /**
507
+ * Number of transactions processed by the server since startup
508
+ */
509
+ get transactionsCount() {
510
+ return this.endpoints.reduce((accumulated, endpoint) => {
511
+ return accumulated + endpoint.transactionsCount;
512
+ }, 0);
513
+ }
514
+ /**
515
+ * The server build info
516
+ */
517
+ get buildInfo() {
518
+ return this.engine.buildInfo;
519
+ }
520
+ /**
521
+ * the number of connected channel on all existing end points
522
+ */
523
+ get currentChannelCount() {
524
+ // TODO : move to base
525
+ const self = this;
526
+ return self.endpoints.reduce((currentValue, endPoint) => {
527
+ return currentValue + endPoint.currentChannelCount;
528
+ }, 0);
529
+ }
530
+ /**
531
+ * The number of active subscriptions from all sessions
532
+ */
533
+ get currentSubscriptionCount() {
534
+ return this.engine ? this.engine.currentSubscriptionCount : 0;
535
+ }
536
+ /**
537
+ * the number of session activation requests that have been rejected
538
+ */
539
+ get rejectedSessionCount() {
540
+ return this.engine ? this.engine.rejectedSessionCount : 0;
541
+ }
542
+ /**
543
+ * the number of request that have been rejected
544
+ */
545
+ get rejectedRequestsCount() {
546
+ return this.engine ? this.engine.rejectedRequestsCount : 0;
547
+ }
548
+ /**
549
+ * the number of sessions that have been aborted
550
+ */
551
+ get sessionAbortCount() {
552
+ return this.engine ? this.engine.sessionAbortCount : 0;
553
+ }
554
+ /**
555
+ * the publishing interval count
556
+ */
557
+ get publishingIntervalCount() {
558
+ return this.engine ? this.engine.publishingIntervalCount : 0;
559
+ }
560
+ /**
561
+ * the number of sessions currently active
562
+ */
563
+ get currentSessionCount() {
564
+ return this.engine ? this.engine.currentSessionCount : 0;
565
+ }
566
+ /**
567
+ * true if the server has been initialized
568
+ *
569
+ */
570
+ get initialized() {
571
+ return this.engine && this.engine.addressSpace !== null;
572
+ }
573
+ /**
574
+ * is the server auditing ?
575
+ */
576
+ get isAuditing() {
577
+ return this.engine ? this.engine.isAuditing : false;
578
+ }
579
+ initialize(...args) {
580
+ const done = args[0];
581
+ (0, node_opcua_assert_1.assert)(!this.initialized, "server is already initialized"); // already initialized ?
582
+ this._preInitTask.push(() => __awaiter(this, void 0, void 0, function* () {
583
+ /* istanbul ignore else */
584
+ if (this._delayInit) {
585
+ yield this._delayInit();
586
+ this._delayInit = undefined;
587
+ }
588
+ }));
589
+ this.performPreInitialization()
590
+ .then(() => {
591
+ OPCUAServer.registry.register(this);
592
+ this.engine.initialize(this.options, () => {
593
+ setImmediate(() => {
594
+ this.emit("post_initialize");
595
+ done();
596
+ });
597
+ });
598
+ })
599
+ .catch((err) => {
600
+ done(err);
601
+ });
602
+ }
603
+ start(...args) {
604
+ const done = args[0];
605
+ const tasks = [];
606
+ tasks.push((0, util_1.callbackify)(node_opcua_hostname_1.extractFullyQualifiedDomainName));
607
+ if (!this.initialized) {
608
+ tasks.push((callback) => {
609
+ this.initialize(callback);
610
+ });
611
+ }
612
+ tasks.push((callback) => {
613
+ super.start((err) => {
614
+ if (err) {
615
+ this.shutdown((/*err2*/ err2) => {
616
+ callback(err);
617
+ });
618
+ }
619
+ else {
620
+ // we start the registration process asynchronously
621
+ // as we want to make server immediately available
622
+ this.registerServerManager.start(() => {
623
+ /* empty */
624
+ });
625
+ setImmediate(callback);
626
+ }
627
+ });
628
+ });
629
+ async.series(tasks, done);
630
+ }
631
+ shutdown(...args) {
632
+ const timeout = args.length === 1 ? OPCUAServer.defaultShutdownTimeout : args[0];
633
+ const callback = (args.length === 1 ? args[0] : args[1]);
634
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
635
+ debugLog("OPCUAServer#shutdown (timeout = ", timeout, ")");
636
+ /* istanbul ignore next */
637
+ if (!this.engine) {
638
+ return callback();
639
+ }
640
+ (0, node_opcua_assert_1.assert)(this.engine);
641
+ if (!this.engine.isStarted()) {
642
+ // server may have been shot down already , or may have fail to start !!
643
+ const err = new Error("OPCUAServer#shutdown failure ! server doesn't seems to be started yet");
644
+ return callback(err);
645
+ }
646
+ this.userCertificateManager.dispose();
647
+ this.engine.setServerState(node_opcua_common_1.ServerState.Shutdown);
648
+ const shutdownTime = new Date(Date.now() + timeout);
649
+ this.engine.setShutdownTime(shutdownTime);
650
+ debugLog("OPCUAServer is now unregistering itself from the discovery server " + this.buildInfo);
651
+ this.registerServerManager.stop((err) => {
652
+ debugLog("OPCUAServer unregistered from discovery server", err);
653
+ setTimeout(() => {
654
+ this.engine.shutdown();
655
+ debugLog("OPCUAServer#shutdown: started");
656
+ base_server_1.OPCUABaseServer.prototype.shutdown.call(this, (err1) => {
657
+ debugLog("OPCUAServer#shutdown: completed");
658
+ this.dispose();
659
+ callback(err1);
660
+ });
661
+ }, timeout);
662
+ });
663
+ }
664
+ dispose() {
665
+ for (const endpoint of this.endpoints) {
666
+ endpoint.dispose();
667
+ }
668
+ this.endpoints = [];
669
+ this.removeAllListeners();
670
+ if (this.registerServerManager) {
671
+ this.registerServerManager.dispose();
672
+ this.registerServerManager = undefined;
673
+ }
674
+ OPCUAServer.registry.unregister(this);
675
+ /* istanbul ignore next */
676
+ if (this.engine) {
677
+ this.engine.dispose();
678
+ }
679
+ }
680
+ raiseEvent(eventType, options) {
681
+ /* istanbul ignore next */
682
+ if (!this.engine.addressSpace) {
683
+ errorLog("addressSpace missing");
684
+ return;
685
+ }
686
+ const server = this.engine.addressSpace.findNode("Server");
687
+ /* istanbul ignore next */
688
+ if (!server) {
689
+ // xx throw new Error("OPCUAServer#raiseEvent : cannot find Server object");
690
+ return;
691
+ }
692
+ let eventTypeNode = eventType;
693
+ if (typeof eventType === "string") {
694
+ eventTypeNode = this.engine.addressSpace.findEventType(eventType);
695
+ }
696
+ /* istanbul ignore else */
697
+ if (eventTypeNode) {
698
+ return server.raiseEvent(eventTypeNode, options);
699
+ }
700
+ else {
701
+ console.warn(" cannot find event type ", eventType);
702
+ }
703
+ }
704
+ /**
705
+ * create and register a new session
706
+ * @internal
707
+ */
708
+ createSession(options) {
709
+ /* istanbul ignore next */
710
+ if (!this.engine) {
711
+ throw new Error("Internal Error");
712
+ }
713
+ return this.engine.createSession(options);
714
+ }
715
+ /**
716
+ * retrieve a session by authentication token
717
+ * @internal
718
+ */
719
+ getSession(authenticationToken, activeOnly) {
720
+ return this.engine ? this.engine.getSession(authenticationToken, activeOnly) : null;
721
+ }
722
+ /**
723
+ *
724
+ * @param channel
725
+ * @param clientCertificate
726
+ * @param clientNonce
727
+ * @internal
728
+ */
729
+ computeServerSignature(channel, clientCertificate, clientNonce) {
730
+ return (0, node_opcua_secure_channel_1.computeSignature)(clientCertificate, clientNonce, this.getPrivateKey(), channel.messageBuilder.securityPolicy);
731
+ }
732
+ /**
733
+ *
734
+ * @param session
735
+ * @param channel
736
+ * @param clientSignature
737
+ * @internal
738
+ */
739
+ verifyClientSignature(session, channel, clientSignature) {
740
+ const clientCertificate = channel.receiverCertificate;
741
+ const securityPolicy = channel.messageBuilder.securityPolicy;
742
+ const serverCertificate = this.getCertificate();
743
+ const result = (0, node_opcua_secure_channel_1.verifySignature)(serverCertificate, session.nonce, clientSignature, clientCertificate, securityPolicy);
744
+ return result;
745
+ }
746
+ isValidUserNameIdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback) {
747
+ (0, node_opcua_assert_1.assert)(userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken);
748
+ const securityPolicy = adjustSecurityPolicy(channel, userTokenPolicy.securityPolicyUri);
749
+ if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
750
+ return callback(null, node_opcua_status_code_1.StatusCodes.Good);
751
+ }
752
+ const cryptoFactory = (0, node_opcua_secure_channel_1.getCryptoFactory)(securityPolicy);
753
+ /* istanbul ignore next */
754
+ if (!cryptoFactory) {
755
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected);
756
+ }
757
+ /* istanbul ignore next */
758
+ if (userIdentityToken.encryptionAlgorithm !== cryptoFactory.asymmetricEncryptionAlgorithm) {
759
+ errorLog("invalid encryptionAlgorithm");
760
+ errorLog("userTokenPolicy", userTokenPolicy.toString());
761
+ errorLog("userTokenPolicy", userIdentityToken.toString());
762
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid);
763
+ }
764
+ const userName = userIdentityToken.userName;
765
+ const password = userIdentityToken.password;
766
+ if (!userName || !password) {
767
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid);
768
+ }
769
+ return callback(null, node_opcua_status_code_1.StatusCodes.Good);
770
+ }
771
+ isValidX509IdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback) {
772
+ (0, node_opcua_assert_1.assert)(userIdentityToken instanceof node_opcua_service_session_1.X509IdentityToken);
773
+ (0, node_opcua_assert_1.assert)(callback instanceof Function);
774
+ const securityPolicy = adjustSecurityPolicy(channel, userTokenPolicy.securityPolicyUri);
775
+ const cryptoFactory = (0, node_opcua_secure_channel_1.getCryptoFactory)(securityPolicy);
776
+ /* istanbul ignore next */
777
+ if (!cryptoFactory) {
778
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected);
779
+ }
780
+ if (!userTokenSignature || !userTokenSignature.signature) {
781
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadUserSignatureInvalid);
782
+ }
783
+ if (userIdentityToken.policyId !== userTokenPolicy.policyId) {
784
+ errorLog("invalid encryptionAlgorithm");
785
+ errorLog("userTokenPolicy", userTokenPolicy.toString());
786
+ errorLog("userTokenPolicy", userIdentityToken.toString());
787
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected);
788
+ }
789
+ const certificate = userIdentityToken.certificateData; /* as Certificate*/
790
+ const nonce = session.nonce;
791
+ const serverCertificate = this.getCertificate();
792
+ (0, node_opcua_assert_1.assert)(serverCertificate instanceof Buffer);
793
+ (0, node_opcua_assert_1.assert)(certificate instanceof Buffer, "expecting certificate to be a Buffer");
794
+ (0, node_opcua_assert_1.assert)(nonce instanceof Buffer, "expecting nonce to be a Buffer");
795
+ (0, node_opcua_assert_1.assert)(userTokenSignature.signature instanceof Buffer, "expecting userTokenSignature to be a Buffer");
796
+ // verify proof of possession by checking certificate signature & server nonce correctness
797
+ if (!(0, node_opcua_secure_channel_1.verifySignature)(serverCertificate, nonce, userTokenSignature, certificate, securityPolicy)) {
798
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadUserSignatureInvalid);
799
+ }
800
+ // verify if certificate is Valid
801
+ this.userCertificateManager.checkCertificate(certificate, (err, certificateStatus) => {
802
+ /* istanbul ignore next */
803
+ if (err) {
804
+ return callback(err);
805
+ }
806
+ if (node_opcua_status_code_1.StatusCodes.BadCertificateUntrusted === certificateStatus ||
807
+ node_opcua_status_code_1.StatusCodes.BadCertificateTimeInvalid === certificateStatus ||
808
+ node_opcua_status_code_1.StatusCodes.BadCertificateIssuerTimeInvalid === certificateStatus ||
809
+ node_opcua_status_code_1.StatusCodes.BadCertificateIssuerUseNotAllowed === certificateStatus ||
810
+ node_opcua_status_code_1.StatusCodes.BadCertificateIssuerRevocationUnknown === certificateStatus ||
811
+ node_opcua_status_code_1.StatusCodes.BadCertificateRevocationUnknown === certificateStatus ||
812
+ node_opcua_status_code_1.StatusCodes.BadCertificateRevoked === certificateStatus ||
813
+ node_opcua_status_code_1.StatusCodes.BadCertificateUseNotAllowed === certificateStatus ||
814
+ node_opcua_status_code_1.StatusCodes.BadSecurityChecksFailed === certificateStatus ||
815
+ node_opcua_status_code_1.StatusCodes.Good !== certificateStatus) {
816
+ debugLog("isValidX509IdentityToken => certificateStatus = ", certificateStatus === null || certificateStatus === void 0 ? void 0 : certificateStatus.toString());
817
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenRejected);
818
+ }
819
+ if (node_opcua_status_code_1.StatusCodes.Good !== certificateStatus) {
820
+ (0, node_opcua_assert_1.assert)(certificateStatus instanceof node_opcua_status_code_1.StatusCode);
821
+ return callback(null, certificateStatus);
822
+ // return callback(null, StatusCodes.BadIdentityTokenInvalid);
823
+ }
824
+ // verify if certificate is truster or rejected
825
+ // todo: StatusCodes.BadCertificateUntrusted
826
+ // store untrusted certificate to rejected folder
827
+ // todo:
828
+ return callback(null, node_opcua_status_code_1.StatusCodes.Good);
829
+ });
830
+ }
831
+ /**
832
+ * @internal
833
+ */
834
+ userNameIdentityTokenAuthenticateUser(channel, session, userTokenPolicy, userIdentityToken, callback) {
835
+ (0, node_opcua_assert_1.assert)(userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken);
836
+ // assert(this.isValidUserNameIdentityToken(channel, session, userTokenPolicy, userIdentityToken));
837
+ const securityPolicy = adjustSecurityPolicy(channel, userTokenPolicy.securityPolicyUri);
838
+ const userName = userIdentityToken.userName;
839
+ let password = userIdentityToken.password;
840
+ // decrypt password if necessary
841
+ if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
842
+ // not good, password was sent in clear text ...
843
+ password = password.toString();
844
+ }
845
+ else {
846
+ const serverPrivateKey = this.getPrivateKey();
847
+ const serverNonce = session.nonce;
848
+ (0, node_opcua_assert_1.assert)(serverNonce instanceof Buffer);
849
+ const cryptoFactory = (0, node_opcua_secure_channel_1.getCryptoFactory)(securityPolicy);
850
+ /* istanbul ignore next */
851
+ if (!cryptoFactory) {
852
+ return callback(new Error(" Unsupported security Policy"));
853
+ }
854
+ const buff = cryptoFactory.asymmetricDecrypt(password, serverPrivateKey);
855
+ // server certificate may be invalid and asymmetricDecrypt may fail
856
+ if (!buff || buff.length < 4) {
857
+ async.setImmediate(() => callback(null, false));
858
+ return;
859
+ }
860
+ const length = buff.readUInt32LE(0) - serverNonce.length;
861
+ password = buff.slice(4, 4 + length).toString("utf-8");
862
+ }
863
+ if (typeof this.userManager.isValidUserAsync === "function") {
864
+ this.userManager.isValidUserAsync.call(session, userName, password, callback);
865
+ }
866
+ else {
867
+ const authorized = this.userManager.isValidUser.call(session, userName, password);
868
+ async.setImmediate(() => callback(null, authorized));
869
+ }
870
+ }
871
+ /**
872
+ * @internal
873
+ */
874
+ isValidUserIdentityToken(channel, session, userIdentityToken, userTokenSignature, endpointDescription, callback) {
875
+ (0, node_opcua_assert_1.assert)(callback instanceof Function);
876
+ /* istanbul ignore next */
877
+ if (!userIdentityToken) {
878
+ throw new Error("Invalid token");
879
+ }
880
+ const userTokenType = getTokenType(userIdentityToken);
881
+ const userTokenPolicy = findUserTokenByPolicy(endpointDescription, userTokenType, userIdentityToken.policyId);
882
+ if (!userTokenPolicy) {
883
+ // cannot find token with this policyId
884
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid);
885
+ }
886
+ //
887
+ if (userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken) {
888
+ return this.isValidUserNameIdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback);
889
+ }
890
+ if (userIdentityToken instanceof node_opcua_service_session_1.X509IdentityToken) {
891
+ return this.isValidX509IdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback);
892
+ }
893
+ return callback(null, node_opcua_status_code_1.StatusCodes.Good);
894
+ }
895
+ /**
896
+ *
897
+ * @internal
898
+ * @param channel
899
+ * @param session
900
+ * @param userIdentityToken
901
+ * @param callback
902
+ * @returns {*}
903
+ */
904
+ isUserAuthorized(channel, session, userIdentityToken, callback) {
905
+ (0, node_opcua_assert_1.assert)(userIdentityToken);
906
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
907
+ const userTokenType = getTokenType(userIdentityToken);
908
+ const userTokenPolicy = findUserTokenByPolicy(session.getEndpointDescription(), userTokenType, userIdentityToken.policyId);
909
+ (0, node_opcua_assert_1.assert)(userTokenPolicy);
910
+ // find if a userToken exists
911
+ if (userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken) {
912
+ return this.userNameIdentityTokenAuthenticateUser(channel, session, userTokenPolicy, userIdentityToken, callback);
913
+ }
914
+ async.setImmediate(callback.bind(null, null, true));
915
+ }
916
+ makeServerNonce() {
917
+ return crypto.randomBytes(32);
918
+ }
919
+ // session services
920
+ _on_CreateSessionRequest(message, channel) {
921
+ return __awaiter(this, void 0, void 0, function* () {
922
+ const server = this;
923
+ const request = message.request;
924
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_session_1.CreateSessionRequest);
925
+ function rejectConnection(statusCode) {
926
+ server.engine.incrementSecurityRejectedSessionCount();
927
+ const response1 = new node_opcua_service_session_1.CreateSessionResponse({
928
+ responseHeader: { serviceResult: statusCode }
929
+ });
930
+ channel.send_response("MSG", response1, message);
931
+ // and close !
932
+ }
933
+ // From OPCUA V1.03 Part 4 5.6.2 CreateSession
934
+ // A Server application should limit the number of Sessions. To protect against misbehaving Clients and denial
935
+ // of service attacks, the Server shall close the oldest Session that is not activated before reaching the
936
+ // maximum number of supported Sessions
937
+ if (server.currentSessionCount >= server.maxAllowedSessionNumber) {
938
+ yield _attempt_to_close_some_old_unactivated_session(server);
939
+ }
940
+ // check if session count hasn't reach the maximum allowed sessions
941
+ if (server.currentSessionCount >= server.maxAllowedSessionNumber) {
942
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadTooManySessions);
943
+ }
944
+ // Release 1.03 OPC Unified Architecture, Part 4 page 24 - CreateSession Parameters
945
+ // client should prove a sessionName
946
+ // Session name is a Human readable string that identifies the Session. The Server makes this name and the
947
+ // sessionId visible in its AddressSpace for diagnostic purposes. The Client should provide a name that is
948
+ // unique for the instance of the Client.
949
+ // If this parameter is not specified the Server shall assign a value.
950
+ if (utils.isNullOrUndefined(request.sessionName)) {
951
+ // see also #198
952
+ // let's the server assign a sessionName for this lazy client.
953
+ debugLog("assigning OPCUAServer.fallbackSessionName because client's sessionName is null ", OPCUAServer.fallbackSessionName);
954
+ request.sessionName = OPCUAServer.fallbackSessionName;
955
+ }
956
+ // Duration Requested maximum number of milliseconds that a Session should remain open without activity.
957
+ // If the Client fails to issue a Service request within this interval, then the Server shall automatically
958
+ // terminate the Client Session.
959
+ const revisedSessionTimeout = _adjust_session_timeout(request.requestedSessionTimeout);
960
+ // Release 1.02 page 27 OPC Unified Architecture, Part 4: CreateSession.clientNonce
961
+ // A random number that should never be used in any other request. This number shall have a minimum length of 32
962
+ // bytes. Profiles may increase the required length. The Server shall use this value to prove possession of
963
+ // its application instance Certificate in the response.
964
+ if (!request.clientNonce || request.clientNonce.length < 32) {
965
+ if (channel.securityMode !== node_opcua_secure_channel_1.MessageSecurityMode.None) {
966
+ errorLog(chalk.red("SERVER with secure connection: Missing or invalid client Nonce "), request.clientNonce && request.clientNonce.toString("hex"));
967
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadNonceInvalid);
968
+ }
969
+ }
970
+ if ((0, node_opcua_secure_channel_1.nonceAlreadyBeenUsed)(request.clientNonce)) {
971
+ errorLog(chalk.red("SERVER with secure connection: None has already been used"), request.clientNonce && request.clientNonce.toString("hex"));
972
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadNonceInvalid);
973
+ }
974
+ function validate_applicationUri(applicationUri, clientCertificate) {
975
+ // if session is insecure there is no need to check certificate information
976
+ if (channel.securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
977
+ return true; // assume correct
978
+ }
979
+ if (!clientCertificate || clientCertificate.length === 0) {
980
+ return true; // can't check
981
+ }
982
+ const e = (0, node_opcua_crypto_1.exploreCertificate)(clientCertificate);
983
+ const applicationUriFromCert = e.tbsCertificate.extensions.subjectAltName.uniformResourceIdentifier[0];
984
+ /* istanbul ignore next */
985
+ if (applicationUriFromCert !== applicationUri) {
986
+ errorLog("BadCertificateUriInvalid!");
987
+ errorLog("applicationUri = ", applicationUri);
988
+ errorLog("applicationUriFromCert = ", applicationUriFromCert);
989
+ }
990
+ return applicationUriFromCert === applicationUri;
991
+ }
992
+ // check application spoofing
993
+ // check if applicationUri in createSessionRequest matches applicationUri in client Certificate
994
+ if (!validate_applicationUri(request.clientDescription.applicationUri, request.clientCertificate)) {
995
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadCertificateUriInvalid);
996
+ }
997
+ function validate_security_endpoint(channel1) {
998
+ debugLog("validate_security_endpoint = ", request.endpointUrl);
999
+ let endpoints = server._get_endpoints(request.endpointUrl);
1000
+ // endpointUrl String The network address that the Client used to access the Session Endpoint.
1001
+ // The HostName portion of the URL should be one of the HostNames for the application that are
1002
+ // specified in the Server’s ApplicationInstanceCertificate (see 7.2). The Server shall raise an
1003
+ // AuditUrlMismatchEventType event if the URL does not match the Server’s HostNames.
1004
+ // AuditUrlMismatchEventType event type is defined in Part 5.
1005
+ // The Server uses this information for diagnostics and to determine the set of
1006
+ // EndpointDescriptions to return in the response.
1007
+ // ToDo: check endpointUrl validity and emit an AuditUrlMismatchEventType event if not
1008
+ if (endpoints.length === 0) {
1009
+ // we have a UrlMismatch here
1010
+ const ua_server = server.engine.addressSpace.rootFolder.objects.server;
1011
+ ua_server.raiseEvent("AuditUrlMismatchEventType", {
1012
+ endpointUrl: { dataType: node_opcua_variant_1.DataType.String, value: request.endpointUrl }
1013
+ });
1014
+ debugLog("Cannot find endpoint in available endpoints with endpointUri", request.endpointUrl);
1015
+ if (OPCUAServer.requestExactEndpointUrl) {
1016
+ return { errCode: node_opcua_status_code_1.StatusCodes.BadServiceUnsupported };
1017
+ }
1018
+ else {
1019
+ endpoints = server._get_endpoints(null);
1020
+ }
1021
+ }
1022
+ // ignore restricted endpoints
1023
+ endpoints = endpoints.filter((e) => !e.restricted);
1024
+ const endpoints_matching_security_mode = endpoints.filter((e) => {
1025
+ return e.securityMode === channel1.securityMode;
1026
+ });
1027
+ if (endpoints_matching_security_mode.length === 0) {
1028
+ return { errCode: node_opcua_status_code_1.StatusCodes.BadSecurityModeRejected };
1029
+ }
1030
+ const endpoints_matching_security_policy = endpoints_matching_security_mode.filter((e) => {
1031
+ return e.securityPolicyUri === channel1.securityHeader.securityPolicyUri;
1032
+ });
1033
+ if (endpoints_matching_security_policy.length === 0) {
1034
+ return { errCode: node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected };
1035
+ }
1036
+ if (endpoints_matching_security_policy.length !== 1) {
1037
+ debugLog("endpoints_matching_security_policy= ", endpoints_matching_security_policy.length);
1038
+ }
1039
+ return { errCode: node_opcua_status_code_1.StatusCodes.Good, endpoint: endpoints_matching_security_policy[0] };
1040
+ }
1041
+ const { errCode, endpoint } = validate_security_endpoint(channel);
1042
+ if (errCode !== node_opcua_status_code_1.StatusCodes.Good) {
1043
+ return rejectConnection(errCode);
1044
+ }
1045
+ // see Release 1.02 27 OPC Unified Architecture, Part 4
1046
+ const session = server.createSession({
1047
+ clientDescription: request.clientDescription,
1048
+ sessionTimeout: revisedSessionTimeout
1049
+ });
1050
+ session.endpoint = endpoint;
1051
+ (0, node_opcua_assert_1.assert)(session);
1052
+ (0, node_opcua_assert_1.assert)(session.sessionTimeout === revisedSessionTimeout);
1053
+ session.clientDescription = request.clientDescription;
1054
+ session.sessionName = request.sessionName || "<unknown session name>";
1055
+ // Depending upon on the SecurityPolicy and the SecurityMode of the SecureChannel, the exchange of
1056
+ // ApplicationInstanceCertificates and Nonces may be optional and the signatures may be empty. See
1057
+ // Part 7 for the definition of SecurityPolicies and the handling of these parameters
1058
+ // serverNonce:
1059
+ // A random number that should never be used in any other request.
1060
+ // This number shall have a minimum length of 32 bytes.
1061
+ // The Client shall use this value to prove possession of its application instance
1062
+ // Certificate in the ActivateSession request.
1063
+ // This value may also be used to prove possession of the userIdentityToken it
1064
+ // specified in the ActivateSession request.
1065
+ //
1066
+ // ( this serverNonce will only be used up to the _on_ActivateSessionRequest
1067
+ // where a new nonce will be created)
1068
+ session.nonce = server.makeServerNonce();
1069
+ session.channelId = channel.channelId;
1070
+ session._attach_channel(channel);
1071
+ const serverCertificateChain = server.getCertificateChain();
1072
+ const hasEncryption = true;
1073
+ // If the securityPolicyUri is None and none of the UserTokenPolicies requires encryption
1074
+ if (session.channel.securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
1075
+ // ToDo: Check that none of our insecure endpoint has a a UserTokenPolicy that require encryption
1076
+ // and set hasEncryption = false under this condition
1077
+ }
1078
+ const response = new node_opcua_service_session_1.CreateSessionResponse({
1079
+ // A identifier which uniquely identifies the session.
1080
+ sessionId: session.nodeId,
1081
+ // A unique identifier assigned by the Server to the Session.
1082
+ // The token used to authenticate the client in subsequent requests.
1083
+ authenticationToken: session.authenticationToken,
1084
+ revisedSessionTimeout,
1085
+ serverNonce: session.nonce,
1086
+ // serverCertificate: type ApplicationServerCertificate
1087
+ // The application instance Certificate issued to the Server.
1088
+ // A Server shall prove possession by using the private key to sign the Nonce provided
1089
+ // by the Client in the request. The Client shall verify that this Certificate is the same as
1090
+ // the one it used to create the SecureChannel.
1091
+ // The ApplicationInstanceCertificate type is defined in OpCUA 1.03 part 4 - $7.2 page 108
1092
+ // If the securityPolicyUri is None and none of the UserTokenPolicies requires
1093
+ // encryption, the Server shall not send an ApplicationInstanceCertificate and the Client
1094
+ // shall ignore the ApplicationInstanceCertificate.
1095
+ serverCertificate: hasEncryption ? serverCertificateChain : undefined,
1096
+ // The endpoints provided by the server.
1097
+ // The Server shall return a set of EndpointDescriptions available for the serverUri
1098
+ // specified in the request.[...]
1099
+ // The Client shall verify this list with the list from a Discovery Endpoint if it used a Discovery
1100
+ // Endpoint to fetch the EndpointDescriptions.
1101
+ // It is recommended that Servers only include the endpointUrl, securityMode,
1102
+ // securityPolicyUri, userIdentityTokens, transportProfileUri and securityLevel with all
1103
+ // other parameters set to null. Only the recommended parameters shall be verified by
1104
+ // the client.
1105
+ serverEndpoints: _serverEndpointsForCreateSessionResponse(server, session.endpoint.endpointUrl, request.serverUri),
1106
+ // This parameter is deprecated and the array shall be empty.
1107
+ serverSoftwareCertificates: null,
1108
+ // This is a signature generated with the private key associated with the
1109
+ // serverCertificate. This parameter is calculated by appending the clientNonce to the
1110
+ // clientCertificate and signing the resulting sequence of bytes.
1111
+ // The SignatureAlgorithm shall be the AsymmetricSignatureAlgorithm specified in the
1112
+ // SecurityPolicy for the Endpoint.
1113
+ // The SignatureData type is defined in 7.30.
1114
+ serverSignature: server.computeServerSignature(channel, request.clientCertificate, request.clientNonce),
1115
+ // The maximum message size accepted by the server
1116
+ // The Client Communication Stack should return a Bad_RequestTooLarge error to the
1117
+ // application if a request message exceeds this limit.
1118
+ // The value zero indicates that this parameter is not used.
1119
+ maxRequestMessageSize: 0x4000000
1120
+ });
1121
+ server.emit("create_session", session);
1122
+ session.on("session_closed", (session1, deleteSubscriptions, reason) => {
1123
+ (0, node_opcua_assert_1.assert)(typeof reason === "string");
1124
+ if (server.isAuditing) {
1125
+ (0, node_opcua_assert_1.assert)(reason === "Timeout" || reason === "Terminated" || reason === "CloseSession" || reason === "Forcing");
1126
+ const sourceName = "Session/" + reason;
1127
+ server.raiseEvent("AuditSessionEventType", {
1128
+ /* part 5 - 6.4.3 AuditEventType */
1129
+ actionTimeStamp: { dataType: "DateTime", value: new Date() },
1130
+ status: { dataType: "Boolean", value: true },
1131
+ serverId: { dataType: "String", value: "" },
1132
+ // ClientAuditEntryId contains the human-readable AuditEntryId defined in Part 3.
1133
+ clientAuditEntryId: { dataType: "String", value: "" },
1134
+ // The ClientUserId identifies the user of the client requesting an action. The ClientUserId can be
1135
+ // obtained from the UserIdentityToken passed in the ActivateSession call.
1136
+ clientUserId: { dataType: "String", value: "" },
1137
+ sourceName: { dataType: "String", value: sourceName },
1138
+ /* part 5 - 6.4.7 AuditSessionEventType */
1139
+ sessionId: { dataType: "NodeId", value: session1.nodeId }
1140
+ });
1141
+ }
1142
+ server.emit("session_closed", session1, deleteSubscriptions);
1143
+ });
1144
+ if (server.isAuditing) {
1145
+ // ------------------------------------------------------------------------------------------------------
1146
+ server.raiseEvent("AuditCreateSessionEventType", {
1147
+ /* part 5 - 6.4.3 AuditEventType */
1148
+ actionTimeStamp: { dataType: "DateTime", value: new Date() },
1149
+ status: { dataType: "Boolean", value: true },
1150
+ serverId: { dataType: "String", value: "" },
1151
+ // ClientAuditEntryId contains the human-readable AuditEntryId defined in Part 3.
1152
+ clientAuditEntryId: { dataType: "String", value: "" },
1153
+ // The ClientUserId identifies the user of the client requesting an action. The ClientUserId can be
1154
+ // obtained from the UserIdentityToken passed in the ActivateSession call.
1155
+ clientUserId: { dataType: "String", value: "" },
1156
+ sourceName: { dataType: "String", value: "Session/CreateSession" },
1157
+ /* part 5 - 6.4.7 AuditSessionEventType */
1158
+ sessionId: { dataType: "NodeId", value: session.nodeId },
1159
+ /* part 5 - 6.4.8 AuditCreateSessionEventType */
1160
+ // SecureChannelId shall uniquely identify the SecureChannel. The application shall use the same
1161
+ // identifier in all AuditEvents related to the Session Service Set (AuditCreateSessionEventType,
1162
+ // AuditActivateSessionEventType and their subtypes) and the SecureChannel Service Set
1163
+ // (AuditChannelEventType and its subtypes
1164
+ secureChannelId: { dataType: "String", value: session.channel.channelId.toString() },
1165
+ // Duration
1166
+ revisedSessionTimeout: { dataType: "Duration", value: session.sessionTimeout },
1167
+ // clientCertificate
1168
+ clientCertificate: { dataType: "ByteString", value: session.channel.clientCertificate },
1169
+ // clientCertificateThumbprint
1170
+ clientCertificateThumbprint: {
1171
+ dataType: "ByteString",
1172
+ value: thumbprint(session.channel.clientCertificate)
1173
+ }
1174
+ });
1175
+ }
1176
+ // -----------------------------------------------------------------------------------------------------------
1177
+ (0, node_opcua_assert_1.assert)(response.authenticationToken);
1178
+ channel.send_response("MSG", response, message);
1179
+ });
1180
+ }
1181
+ // TODO : implement this:
1182
+ //
1183
+ // When the ActivateSession Service is called for the first time then the Server shall reject the request
1184
+ // if the SecureChannel is not same as the one associated with the CreateSession request.
1185
+ // Subsequent calls to ActivateSession may be associated with different SecureChannels. If this is the
1186
+ // case then the Server shall verify that the Certificate the Client used to create the new
1187
+ // SecureChannel is the same as the Certificate used to create the original SecureChannel. In addition,
1188
+ // the Server shall verify that the Client supplied a UserIdentityToken that is identical to the token
1189
+ // currently associated with the Session. Once the Server accepts the new SecureChannel it shall
1190
+ // reject requests sent via the old SecureChannel.
1191
+ /**
1192
+ *
1193
+ * @method _on_ActivateSessionRequest
1194
+ * @private
1195
+ *
1196
+ *
1197
+ */
1198
+ _on_ActivateSessionRequest(message, channel) {
1199
+ const server = this;
1200
+ const request = message.request;
1201
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_session_1.ActivateSessionRequest);
1202
+ // get session from authenticationToken
1203
+ const authenticationToken = request.requestHeader.authenticationToken;
1204
+ const session = server.getSession(authenticationToken);
1205
+ function rejectConnection(statusCode) {
1206
+ if (statusCode === node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid) {
1207
+ server.engine.incrementRejectedSessionCount();
1208
+ }
1209
+ else {
1210
+ server.engine.incrementRejectedSessionCount();
1211
+ server.engine.incrementSecurityRejectedSessionCount();
1212
+ }
1213
+ const response1 = new node_opcua_service_session_1.ActivateSessionResponse({ responseHeader: { serviceResult: statusCode } });
1214
+ channel.send_response("MSG", response1, message);
1215
+ // and close !
1216
+ }
1217
+ let response;
1218
+ /* istanbul ignore next */
1219
+ if (!session) {
1220
+ // this may happen when the server has been restarted and a client tries to reconnect, thinking
1221
+ // that the previous session may still be active
1222
+ debugLog(chalk.yellow.bold(" Bad Session in _on_ActivateSessionRequest"), authenticationToken.toString());
1223
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1224
+ }
1225
+ // tslint:disable-next-line: no-unused-expression
1226
+ session.keepAlive ? session.keepAlive() : void 0;
1227
+ // OpcUA 1.02 part 3 $5.6.3.1 ActiveSession Set page 29
1228
+ // When the ActivateSession Service is called f or the first time then the Server shall reject the request
1229
+ // if the SecureChannel is not same as the one associated with the CreateSession request.
1230
+ if (session.status === "new") {
1231
+ // xx if (channel.session_nonce !== session.nonce) {
1232
+ if (!channel_has_session(channel, session)) {
1233
+ // it looks like session activation is being using a channel that is not the
1234
+ // one that have been used to create the session
1235
+ errorLog(" channel.sessionTokens === " + Object.keys(channel.sessionTokens).join(" "));
1236
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadSessionNotActivated);
1237
+ }
1238
+ }
1239
+ // OpcUA 1.02 part 3 $5.6.3.1 ActiveSession Set page 29
1240
+ // ... Subsequent calls to ActivateSession may be associated with different SecureChannels. If this is the
1241
+ // case then the Server shall verify that the Certificate the Client used to create the new
1242
+ // SecureChannel is the same as the Certificate used to create the original SecureChannel.
1243
+ if (session.status === "active") {
1244
+ if (session.channel.channelId !== channel.channelId) {
1245
+ warningLog(" Session ", session.sessionName, " is being transferred from channel", chalk.cyan(session.channel.channelId.toString()), " to channel ", chalk.cyan(channel.channelId.toString()));
1246
+ // session is being reassigned to a new Channel,
1247
+ // we shall verify that the certificate used to create the Session is the same as the current
1248
+ // channel certificate.
1249
+ const old_channel_cert_thumbprint = thumbprint(session.channel.clientCertificate);
1250
+ const new_channel_cert_thumbprint = thumbprint(channel.clientCertificate);
1251
+ if (old_channel_cert_thumbprint !== new_channel_cert_thumbprint) {
1252
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadNoValidCertificates); // not sure about this code !
1253
+ }
1254
+ // ... In addition the Server shall verify that the Client supplied a UserIdentityToken that is
1255
+ // identical to the token currently associated with the Session reassign session to new channel.
1256
+ if (!sameIdentityToken(session.userIdentityToken, request.userIdentityToken)) {
1257
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadIdentityChangeNotSupported); // not sure about this code !
1258
+ }
1259
+ }
1260
+ moveSessionToChannel(session, channel);
1261
+ }
1262
+ else if (session.status === "screwed") {
1263
+ // session has been used before being activated => this should be detected and session should be dismissed.
1264
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadSessionClosed);
1265
+ }
1266
+ else if (session.status === "closed") {
1267
+ warningLog(chalk.yellow.bold(" Bad Session Closed in _on_ActivateSessionRequest"), authenticationToken.toString());
1268
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadSessionClosed);
1269
+ }
1270
+ // verify clientSignature provided by the client
1271
+ if (!server.verifyClientSignature(session, channel, request.clientSignature)) {
1272
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadApplicationSignatureInvalid);
1273
+ }
1274
+ // userIdentityToken may be missing , assume anonymous access then
1275
+ request.userIdentityToken = request.userIdentityToken || createAnonymousIdentityToken(session.endpoint);
1276
+ // check request.userIdentityToken is correct ( expected type and correctly formed)
1277
+ server.isValidUserIdentityToken(channel, session, request.userIdentityToken, request.userTokenSignature, session.endpoint, (err, statusCode) => {
1278
+ if (statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
1279
+ /* istanbul ignore next */
1280
+ if (!(statusCode && statusCode instanceof node_opcua_status_code_1.StatusCode)) {
1281
+ const a = 23;
1282
+ }
1283
+ (0, node_opcua_assert_1.assert)(statusCode && statusCode instanceof node_opcua_status_code_1.StatusCode, "expecting statusCode");
1284
+ return rejectConnection(statusCode);
1285
+ }
1286
+ session.userIdentityToken = request.userIdentityToken;
1287
+ // check if user access is granted
1288
+ server.isUserAuthorized(channel, session, request.userIdentityToken, (err1, authorized) => {
1289
+ /* istanbul ignore next */
1290
+ if (err1) {
1291
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadInternalError);
1292
+ }
1293
+ if (!authorized) {
1294
+ return rejectConnection(node_opcua_status_code_1.StatusCodes.BadUserAccessDenied);
1295
+ }
1296
+ else {
1297
+ // extract : OPC UA part 4 - 5.6.3
1298
+ // Once used, a serverNonce cannot be used again. For that reason, the Server returns a new
1299
+ // serverNonce each time the ActivateSession Service is called.
1300
+ session.nonce = server.makeServerNonce();
1301
+ session.status = "active";
1302
+ response = new node_opcua_service_session_1.ActivateSessionResponse({ serverNonce: session.nonce });
1303
+ channel.send_response("MSG", response, message);
1304
+ const userIdentityTokenPasswordRemoved = (userIdentityToken) => {
1305
+ const a = userIdentityToken.clone();
1306
+ // remove password
1307
+ a.password = "*************";
1308
+ return a;
1309
+ };
1310
+ // send OPCUA Event Notification
1311
+ // see part 5 : 6.4.3 AuditEventType
1312
+ // 6.4.7 AuditSessionEventType
1313
+ // 6.4.10 AuditActivateSessionEventType
1314
+ (0, node_opcua_assert_1.assert)(session.nodeId); // sessionId
1315
+ // xx assert(session.channel.clientCertificate instanceof Buffer);
1316
+ (0, node_opcua_assert_1.assert)(session.sessionTimeout > 0);
1317
+ if (server.isAuditing) {
1318
+ server.raiseEvent("AuditActivateSessionEventType", {
1319
+ /* part 5 - 6.4.3 AuditEventType */
1320
+ actionTimeStamp: { dataType: "DateTime", value: new Date() },
1321
+ status: { dataType: "Boolean", value: true },
1322
+ serverId: { dataType: "String", value: "" },
1323
+ // ClientAuditEntryId contains the human-readable AuditEntryId defined in Part 3.
1324
+ clientAuditEntryId: { dataType: "String", value: "" },
1325
+ // The ClientUserId identifies the user of the client requesting an action.
1326
+ // The ClientUserId can be obtained from the UserIdentityToken passed in the
1327
+ // ActivateSession call.
1328
+ clientUserId: { dataType: "String", value: "cc" },
1329
+ sourceName: { dataType: "String", value: "Session/ActivateSession" },
1330
+ /* part 5 - 6.4.7 AuditSessionEventType */
1331
+ sessionId: { dataType: "NodeId", value: session.nodeId },
1332
+ /* part 5 - 6.4.10 AuditActivateSessionEventType */
1333
+ clientSoftwareCertificates: {
1334
+ arrayType: node_opcua_variant_2.VariantArrayType.Array,
1335
+ dataType: "ExtensionObject" /* SignedSoftwareCertificate */,
1336
+ value: []
1337
+ },
1338
+ // UserIdentityToken reflects the userIdentityToken parameter of the ActivateSession
1339
+ // Service call.
1340
+ // For Username/Password tokens the password should NOT be included.
1341
+ userIdentityToken: {
1342
+ dataType: "ExtensionObject" /* UserIdentityToken */,
1343
+ value: userIdentityTokenPasswordRemoved(session.userIdentityToken)
1344
+ },
1345
+ // SecureChannelId shall uniquely identify the SecureChannel. The application shall
1346
+ // use the same identifier in all AuditEvents related to the Session Service Set
1347
+ // (AuditCreateSessionEventType, AuditActivateSessionEventType and their subtypes) and
1348
+ // the SecureChannel Service Set (AuditChannelEventType and its subtypes).
1349
+ secureChannelId: { dataType: "String", value: session.channel.channelId.toString() }
1350
+ });
1351
+ }
1352
+ server.emit("session_activated", session, userIdentityTokenPasswordRemoved);
1353
+ }
1354
+ });
1355
+ });
1356
+ }
1357
+ prepare(message, channel) {
1358
+ const server = this;
1359
+ const request = message.request;
1360
+ // --- check that session is correct
1361
+ const authenticationToken = request.requestHeader.authenticationToken;
1362
+ const session = server.getSession(authenticationToken, /*activeOnly*/ true);
1363
+ if (!session) {
1364
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid;
1365
+ return;
1366
+ }
1367
+ message.session = session;
1368
+ // --- check that provided session matches session attached to channel
1369
+ if (channel.channelId !== session.channelId) {
1370
+ if (!(request instanceof node_opcua_service_session_1.ActivateSessionRequest)) {
1371
+ errorLog(chalk.red.bgWhite("ERROR: channel.channelId !== session.channelId"), channel.channelId, session.channelId);
1372
+ }
1373
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.BadSecureChannelIdInvalid;
1374
+ }
1375
+ else if (channel_has_session(channel, session)) {
1376
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.Good;
1377
+ }
1378
+ else {
1379
+ // session ma y have been moved to a different channel
1380
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.BadSecureChannelIdInvalid;
1381
+ }
1382
+ }
1383
+ /**
1384
+ * ensure that action is performed on a valid session object,
1385
+ * @method _apply_on_SessionObject
1386
+ * @param ResponseClass the constructor of the response Class
1387
+ * @param message
1388
+ * @param channel
1389
+ * @param action_to_perform
1390
+ * @param action_to_perform.session {ServerSession}
1391
+ * @param action_to_perform.sendResponse
1392
+ * @param action_to_perform.sendResponse.response
1393
+ * @param action_to_perform.sendError
1394
+ * @param action_to_perform.sendError.statusCode
1395
+ * @param action_to_perform.sendError.diagnostics
1396
+ *
1397
+ * @private
1398
+ */
1399
+ _apply_on_SessionObject(ResponseClass, message, channel, action_to_perform) {
1400
+ return __awaiter(this, void 0, void 0, function* () {
1401
+ (0, node_opcua_assert_1.assert)(typeof action_to_perform === "function");
1402
+ function sendResponse(response1) {
1403
+ try {
1404
+ (0, node_opcua_assert_1.assert)(response1 instanceof ResponseClass);
1405
+ if (message.session) {
1406
+ const counterName = ResponseClass.name.replace("Response", "");
1407
+ message.session.incrementRequestTotalCounter(counterName);
1408
+ }
1409
+ return channel.send_response("MSG", response1, message);
1410
+ }
1411
+ catch (err) {
1412
+ if (err instanceof Error) {
1413
+ // istanbul ignore next
1414
+ errorLog("Internal error in issuing response\nplease contact support@sterfive.com", message.request.toString(), "\n", response1.toString());
1415
+ }
1416
+ // istanbul ignore next
1417
+ throw err;
1418
+ }
1419
+ }
1420
+ function sendError(statusCode) {
1421
+ if (message.session) {
1422
+ message.session.incrementRequestErrorCounter(ResponseClass.name.replace("Response", ""));
1423
+ }
1424
+ return g_sendError(channel, message, ResponseClass, statusCode);
1425
+ }
1426
+ let response;
1427
+ /* istanbul ignore next */
1428
+ if (!message.session || message.session_statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
1429
+ const errMessage = "INVALID SESSION !! ";
1430
+ response = new ResponseClass({ responseHeader: { serviceResult: message.session_statusCode } });
1431
+ debugLog(chalk.red.bold(errMessage), chalk.yellow(message.session_statusCode.toString()), response.constructor.name);
1432
+ return sendResponse(response);
1433
+ }
1434
+ (0, node_opcua_assert_1.assert)(message.session_statusCode === node_opcua_status_code_1.StatusCodes.Good);
1435
+ // OPC UA Specification 1.02 part 4 page 26
1436
+ // When a Session is terminated, all outstanding requests on the Session are aborted and
1437
+ // Bad_SessionClosed StatusCodes are returned to the Client. In addition, the Server deletes the entry
1438
+ // for the Client from its SessionDiagnostics Array Variable and notifies any other Clients who were
1439
+ // subscribed to this entry.
1440
+ if (message.session.status === "closed") {
1441
+ // note : use StatusCodes.BadSessionClosed , for pending message for this session
1442
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1443
+ }
1444
+ if (message.session.status === "new") {
1445
+ // mark session as being screwed ! so it cannot be activated anymore
1446
+ message.session.status = "screwed";
1447
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSessionNotActivated);
1448
+ }
1449
+ if (message.session.status !== "active") {
1450
+ // mark session as being screwed ! so it cannot be activated anymore
1451
+ message.session.status = "screwed";
1452
+ // note : use StatusCodes.BadSessionClosed , for pending message for this session
1453
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1454
+ }
1455
+ // lets also reset the session watchdog so it doesn't
1456
+ // (Sessions are terminated by the Server automatically if the Client fails to issue a Service
1457
+ // request on the Session within the timeout period negotiated by the Server in the
1458
+ // CreateSession Service response. )
1459
+ if (message.session.keepAlive) {
1460
+ (0, node_opcua_assert_1.assert)(typeof message.session.keepAlive === "function");
1461
+ message.session.keepAlive();
1462
+ }
1463
+ message.session.incrementTotalRequestCount();
1464
+ yield action_to_perform(message.session, sendResponse, sendError);
1465
+ });
1466
+ }
1467
+ /**
1468
+ * @method _apply_on_Subscription
1469
+ * @param ResponseClass
1470
+ * @param message
1471
+ * @param channel
1472
+ * @param action_to_perform
1473
+ * @private
1474
+ */
1475
+ _apply_on_Subscription(ResponseClass, message, channel, action_to_perform) {
1476
+ return __awaiter(this, void 0, void 0, function* () {
1477
+ (0, node_opcua_assert_1.assert)(typeof action_to_perform === "function");
1478
+ const request = message.request;
1479
+ (0, node_opcua_assert_1.assert)(request.hasOwnProperty("subscriptionId"));
1480
+ this._apply_on_SessionObject(ResponseClass, message, channel, (session, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1481
+ const subscription = session.getSubscription(request.subscriptionId);
1482
+ if (!subscription) {
1483
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid);
1484
+ }
1485
+ subscription.resetLifeTimeAndKeepAliveCounters();
1486
+ yield action_to_perform(session, subscription, sendResponse, sendError);
1487
+ }));
1488
+ });
1489
+ }
1490
+ /**
1491
+ * @method _apply_on_SubscriptionIds
1492
+ * @param ResponseClass
1493
+ * @param message
1494
+ * @param channel
1495
+ * @param action_to_perform
1496
+ * @private
1497
+ */
1498
+ _apply_on_SubscriptionIds(ResponseClass, message, channel, action_to_perform) {
1499
+ (0, node_opcua_assert_1.assert)(typeof action_to_perform === "function");
1500
+ const request = message.request;
1501
+ (0, node_opcua_assert_1.assert)(request.hasOwnProperty("subscriptionIds"));
1502
+ this._apply_on_SessionObject(ResponseClass, message, channel, (session, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1503
+ const subscriptionIds = request.subscriptionIds;
1504
+ if (!request.subscriptionIds || request.subscriptionIds.length === 0) {
1505
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1506
+ }
1507
+ // if (request.subscriptionIds.length > OPCUAServer.MAX_SUBSCRIPTION) {
1508
+ // return sendError(StatusCodes.BadTooManyOperations);
1509
+ // }
1510
+ const results = subscriptionIds.map((subscriptionId) => action_to_perform(session, subscriptionId));
1511
+ // resolve potential pending promises ....
1512
+ for (let i = 0; i < results.length; i++) {
1513
+ if (results[i].then) {
1514
+ results[i] = yield results[i];
1515
+ }
1516
+ }
1517
+ const response = new ResponseClass({
1518
+ responseHeader: {
1519
+ serviceResult: request.subscriptionIds.length > OPCUAServer.MAX_SUBSCRIPTION
1520
+ ? node_opcua_status_code_1.StatusCodes.BadTooManyOperations
1521
+ : node_opcua_status_code_1.StatusCodes.Good
1522
+ },
1523
+ results
1524
+ });
1525
+ sendResponse(response);
1526
+ }));
1527
+ }
1528
+ /**
1529
+ * @method _apply_on_Subscriptions
1530
+ * @param ResponseClass
1531
+ * @param message
1532
+ * @param channel
1533
+ * @param action_to_perform
1534
+ * @private
1535
+ */
1536
+ _apply_on_Subscriptions(ResponseClass, message, channel, action_to_perform) {
1537
+ this._apply_on_SubscriptionIds(ResponseClass, message, channel, (session, subscriptionId) => __awaiter(this, void 0, void 0, function* () {
1538
+ /* istanbul ignore next */
1539
+ if (isSubscriptionIdInvalid(subscriptionId)) {
1540
+ return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
1541
+ }
1542
+ const subscription = session.getSubscription(subscriptionId);
1543
+ if (!subscription) {
1544
+ return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
1545
+ }
1546
+ return action_to_perform(session, subscription);
1547
+ }));
1548
+ }
1549
+ _closeSession(authenticationToken, deleteSubscriptions, reason) {
1550
+ return __awaiter(this, void 0, void 0, function* () {
1551
+ const server = this;
1552
+ //
1553
+ if (deleteSubscriptions && this.options.onDeleteMonitoredItem) {
1554
+ const session = this.getSession(authenticationToken);
1555
+ if (session) {
1556
+ const subscriptions = session.publishEngine.subscriptions;
1557
+ for (const subscription of subscriptions) {
1558
+ yield subscription.applyOnMonitoredItem(this.options.onDeleteMonitoredItem.bind(null, subscription));
1559
+ }
1560
+ }
1561
+ }
1562
+ yield server.engine.closeSession(authenticationToken, deleteSubscriptions, reason);
1563
+ });
1564
+ }
1565
+ /**
1566
+ * @method _on_CloseSessionRequest
1567
+ * @param message
1568
+ * @param channel
1569
+ * @private
1570
+ */
1571
+ _on_CloseSessionRequest(message, channel) {
1572
+ const server = this;
1573
+ const request = message.request;
1574
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_session_1.CloseSessionRequest);
1575
+ let response;
1576
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.Good;
1577
+ function sendError(statusCode) {
1578
+ return g_sendError(channel, message, node_opcua_service_session_1.CloseSessionResponse, statusCode);
1579
+ }
1580
+ function sendResponse(response1) {
1581
+ channel.send_response("MSG", response1, message);
1582
+ }
1583
+ // do not use _apply_on_SessionObject
1584
+ // this._apply_on_SessionObject(CloseSessionResponse, message, channel, function (session) {
1585
+ // });
1586
+ const session = message.session;
1587
+ if (!session) {
1588
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1589
+ }
1590
+ // session has been created but not activated !
1591
+ const wasNotActivated = session.status === "new";
1592
+ (() => __awaiter(this, void 0, void 0, function* () {
1593
+ yield this._closeSession(request.requestHeader.authenticationToken, request.deleteSubscriptions, "CloseSession");
1594
+ // if (false && wasNotActivated) {
1595
+ // return sendError(StatusCodes.BadSessionNotActivated);
1596
+ // }
1597
+ response = new node_opcua_service_session_1.CloseSessionResponse({});
1598
+ sendResponse(response);
1599
+ }))();
1600
+ }
1601
+ // browse services
1602
+ /**
1603
+ * @method _on_BrowseRequest
1604
+ * @param message
1605
+ * @param channel
1606
+ * @private
1607
+ */
1608
+ _on_BrowseRequest(message, channel) {
1609
+ const server = this;
1610
+ const request = message.request;
1611
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_browse_1.BrowseRequest);
1612
+ const diagnostic = {};
1613
+ this._apply_on_SessionObject(node_opcua_service_browse_1.BrowseResponse, message, channel, (session, sendResponse, sendError) => {
1614
+ let response;
1615
+ // test view
1616
+ if (request.view && !request.view.viewId.isEmpty()) {
1617
+ let theView = server.engine.addressSpace.findNode(request.view.viewId);
1618
+ if (theView && theView.nodeClass !== node_opcua_data_model_1.NodeClass.View) {
1619
+ // Error: theView is not a View
1620
+ diagnostic.localizedText = { text: "Expecting a view here" };
1621
+ theView = null;
1622
+ }
1623
+ if (!theView) {
1624
+ return sendError(node_opcua_status_code_1.StatusCodes.BadViewIdUnknown);
1625
+ }
1626
+ }
1627
+ if (!request.nodesToBrowse || request.nodesToBrowse.length === 0) {
1628
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1629
+ }
1630
+ if (server.engine.serverCapabilities.operationLimits.maxNodesPerBrowse > 0) {
1631
+ if (request.nodesToBrowse.length > server.engine.serverCapabilities.operationLimits.maxNodesPerBrowse) {
1632
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1633
+ }
1634
+ }
1635
+ // limit results to requestedMaxReferencesPerNode further so it never exceed a too big number
1636
+ const requestedMaxReferencesPerNode = Math.min(9876, request.requestedMaxReferencesPerNode);
1637
+ (0, node_opcua_assert_1.assert)(request.nodesToBrowse[0].schema.name === "BrowseDescription");
1638
+ const context = new node_opcua_address_space_1.SessionContext({ session, server });
1639
+ const f = (0, util_1.callbackify)(server.engine.browseWithAutomaticExpansion).bind(server.engine);
1640
+ f(request.nodesToBrowse, context, (err, results) => {
1641
+ // istanbul ignore next
1642
+ if (!results) {
1643
+ throw new Error("internal error : " + (err === null || err === void 0 ? void 0 : err.message));
1644
+ }
1645
+ (0, node_opcua_assert_1.assert)(results[0].schema.name === "BrowseResult");
1646
+ // handle continuation point and requestedMaxReferencesPerNode
1647
+ const maxBrowseContinuationPoints = server.engine.serverCapabilities.maxBrowseContinuationPoints;
1648
+ results = results.map((result) => {
1649
+ (0, node_opcua_assert_1.assert)(!result.continuationPoint);
1650
+ // istanbul ignore next
1651
+ if (!session.continuationPointManager) {
1652
+ return new node_opcua_types_1.BrowseResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNoContinuationPoints });
1653
+ }
1654
+ if (session.continuationPointManager.hasReachMaximum(maxBrowseContinuationPoints)) {
1655
+ return new node_opcua_types_1.BrowseResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNoContinuationPoints });
1656
+ }
1657
+ const truncatedResult = session.continuationPointManager.register(requestedMaxReferencesPerNode, result.references || []);
1658
+ (0, node_opcua_assert_1.assert)(truncatedResult.statusCode === node_opcua_status_code_1.StatusCodes.Good);
1659
+ truncatedResult.statusCode = result.statusCode;
1660
+ return new node_opcua_types_1.BrowseResult(truncatedResult);
1661
+ });
1662
+ response = new node_opcua_service_browse_1.BrowseResponse({
1663
+ diagnosticInfos: undefined,
1664
+ results
1665
+ });
1666
+ sendResponse(response);
1667
+ });
1668
+ });
1669
+ }
1670
+ /**
1671
+ * @method _on_BrowseNextRequest
1672
+ * @param message
1673
+ * @param channel
1674
+ * @private
1675
+ */
1676
+ _on_BrowseNextRequest(message, channel) {
1677
+ const request = message.request;
1678
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_browse_1.BrowseNextRequest);
1679
+ this._apply_on_SessionObject(node_opcua_service_browse_1.BrowseNextResponse, message, channel, (session, sendResponse, sendError) => {
1680
+ let response;
1681
+ if (!request.continuationPoints || request.continuationPoints.length === 0) {
1682
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1683
+ }
1684
+ // A Boolean parameter with the following values:
1685
+ let results;
1686
+ if (request.releaseContinuationPoints) {
1687
+ // releaseContinuationPoints = TRUE
1688
+ // passed continuationPoints shall be reset to free resources in
1689
+ // the Server. The continuation points are released and the results
1690
+ // and diagnosticInfos arrays are empty.
1691
+ results = request.continuationPoints.map((continuationPoint) => {
1692
+ return session.continuationPointManager.cancel(continuationPoint);
1693
+ });
1694
+ }
1695
+ else {
1696
+ // let extract data from continuation points
1697
+ // releaseContinuationPoints = FALSE
1698
+ // passed continuationPoints shall be used to get the next set of
1699
+ // browse information.
1700
+ results = request.continuationPoints.map((continuationPoint) => {
1701
+ return session.continuationPointManager.getNext(continuationPoint);
1702
+ });
1703
+ }
1704
+ response = new node_opcua_service_browse_1.BrowseNextResponse({
1705
+ diagnosticInfos: undefined,
1706
+ results
1707
+ });
1708
+ sendResponse(response);
1709
+ });
1710
+ }
1711
+ // read services
1712
+ _on_ReadRequest(message, channel) {
1713
+ const server = this;
1714
+ const request = message.request;
1715
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_read_1.ReadRequest);
1716
+ this._apply_on_SessionObject(node_opcua_service_read_1.ReadResponse, message, channel, (session, sendResponse, sendError) => {
1717
+ const context = new node_opcua_address_space_1.SessionContext({ session, server });
1718
+ let response;
1719
+ let results = [];
1720
+ const timestampsToReturn = request.timestampsToReturn;
1721
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1722
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1723
+ }
1724
+ if (request.maxAge < 0) {
1725
+ return sendError(node_opcua_status_code_1.StatusCodes.BadMaxAgeInvalid);
1726
+ }
1727
+ request.nodesToRead = request.nodesToRead || [];
1728
+ if (!request.nodesToRead || request.nodesToRead.length <= 0) {
1729
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1730
+ }
1731
+ (0, node_opcua_assert_1.assert)(request.nodesToRead[0].schema.name === "ReadValueId");
1732
+ // limit size of nodesToRead array to maxNodesPerRead
1733
+ if (server.engine.serverCapabilities.operationLimits.maxNodesPerRead > 0) {
1734
+ if (request.nodesToRead.length > server.engine.serverCapabilities.operationLimits.maxNodesPerRead) {
1735
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1736
+ }
1737
+ }
1738
+ // proceed with registered nodes alias resolution
1739
+ for (const nodeToRead of request.nodesToRead) {
1740
+ nodeToRead.nodeId = session.resolveRegisteredNode(nodeToRead.nodeId);
1741
+ }
1742
+ // ask for a refresh of asynchronous variables
1743
+ server.engine.refreshValues(request.nodesToRead, request.maxAge, (err) => {
1744
+ (0, node_opcua_assert_1.assert)(!err, " error not handled here , fix me");
1745
+ results = server.engine.read(context, request);
1746
+ (0, node_opcua_assert_1.assert)(results[0].schema.name === "DataValue");
1747
+ (0, node_opcua_assert_1.assert)(results.length === request.nodesToRead.length);
1748
+ response = new node_opcua_service_read_1.ReadResponse({
1749
+ diagnosticInfos: undefined,
1750
+ results: undefined
1751
+ });
1752
+ // set it here for performance
1753
+ response.results = results;
1754
+ (0, node_opcua_assert_1.assert)(response.diagnosticInfos.length === 0);
1755
+ sendResponse(response);
1756
+ });
1757
+ });
1758
+ }
1759
+ // read services
1760
+ _on_HistoryReadRequest(message, channel) {
1761
+ const server = this;
1762
+ const request = message.request;
1763
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_history_1.HistoryReadRequest);
1764
+ this._apply_on_SessionObject(node_opcua_service_history_1.HistoryReadResponse, message, channel, (session, sendResponse, sendError) => {
1765
+ let response;
1766
+ const timestampsToReturn = request.timestampsToReturn;
1767
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1768
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1769
+ }
1770
+ request.nodesToRead = request.nodesToRead || [];
1771
+ if (!request.nodesToRead || request.nodesToRead.length <= 0) {
1772
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1773
+ }
1774
+ (0, node_opcua_assert_1.assert)(request.nodesToRead[0].schema.name === "HistoryReadValueId");
1775
+ // limit size of nodesToRead array to maxNodesPerRead
1776
+ if (server.engine.serverCapabilities.operationLimits.maxNodesPerRead > 0) {
1777
+ if (request.nodesToRead.length > server.engine.serverCapabilities.operationLimits.maxNodesPerRead) {
1778
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1779
+ }
1780
+ }
1781
+ // todo : handle
1782
+ if (server.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadData > 0) {
1783
+ if (request.nodesToRead.length > server.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadData) {
1784
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1785
+ }
1786
+ }
1787
+ if (server.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadEvents > 0) {
1788
+ if (request.nodesToRead.length > server.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadEvents) {
1789
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1790
+ }
1791
+ }
1792
+ const context = new node_opcua_address_space_1.SessionContext({ session, server });
1793
+ // ask for a refresh of asynchronous variables
1794
+ server.engine.refreshValues(request.nodesToRead, 0, (err) => {
1795
+ (0, node_opcua_assert_1.assert)(!err, " error not handled here , fix me"); // TODO
1796
+ server.engine.historyRead(context, request, (err1, results) => {
1797
+ if (err1) {
1798
+ return sendError(node_opcua_status_code_1.StatusCodes.BadHistoryOperationInvalid);
1799
+ }
1800
+ if (!results) {
1801
+ return sendError(node_opcua_status_code_1.StatusCodes.BadHistoryOperationInvalid);
1802
+ }
1803
+ (0, node_opcua_assert_1.assert)(results[0].schema.name === "HistoryReadResult");
1804
+ (0, node_opcua_assert_1.assert)(results.length === request.nodesToRead.length);
1805
+ response = new node_opcua_service_history_1.HistoryReadResponse({
1806
+ diagnosticInfos: undefined,
1807
+ results
1808
+ });
1809
+ (0, node_opcua_assert_1.assert)(response.diagnosticInfos.length === 0);
1810
+ sendResponse(response);
1811
+ });
1812
+ });
1813
+ });
1814
+ }
1815
+ /*
1816
+ // write services
1817
+ // OPCUA Specification 1.02 Part 3 : 5.10.4 Write
1818
+ // This Service is used to write values to one or more Attributes of one or more Nodes. For constructed
1819
+ // Attribute values whose elements are indexed, such as an array, this Service allows Clients to write
1820
+ // the entire set of indexed values as a composite, to write individual elements or to write ranges of
1821
+ // elements of the composite.
1822
+ // The values are written to the data source, such as a device, and the Service does not return until it writes
1823
+ // the values or determines that the value cannot be written. In certain cases, the Server will successfully
1824
+ // to an intermediate system or Server, and will not know if the data source was updated properly. In these cases,
1825
+ // the Server should report a success code that indicates that the write was not verified.
1826
+ // In the cases where the Server is able to verify that it has successfully written to the data source,
1827
+ // it reports an unconditional success.
1828
+ */
1829
+ _on_WriteRequest(message, channel) {
1830
+ const server = this;
1831
+ const request = message.request;
1832
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_write_1.WriteRequest);
1833
+ (0, node_opcua_assert_1.assert)(!request.nodesToWrite || Array.isArray(request.nodesToWrite));
1834
+ this._apply_on_SessionObject(node_opcua_service_write_1.WriteResponse, message, channel, (session, sendResponse, sendError) => {
1835
+ let response;
1836
+ if (!request.nodesToWrite || request.nodesToWrite.length === 0) {
1837
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1838
+ }
1839
+ if (server.engine.serverCapabilities.operationLimits.maxNodesPerWrite > 0) {
1840
+ if (request.nodesToWrite.length > server.engine.serverCapabilities.operationLimits.maxNodesPerWrite) {
1841
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1842
+ }
1843
+ }
1844
+ // proceed with registered nodes alias resolution
1845
+ for (const nodeToWrite of request.nodesToWrite) {
1846
+ nodeToWrite.nodeId = session.resolveRegisteredNode(nodeToWrite.nodeId);
1847
+ }
1848
+ const context = new node_opcua_address_space_1.SessionContext({ session, server });
1849
+ (0, node_opcua_assert_1.assert)(request.nodesToWrite[0].schema.name === "WriteValue");
1850
+ server.engine.write(context, request.nodesToWrite, (err, results) => {
1851
+ (0, node_opcua_assert_1.assert)(!err);
1852
+ (0, node_opcua_assert_1.assert)(Array.isArray(results));
1853
+ (0, node_opcua_assert_1.assert)(results.length === request.nodesToWrite.length);
1854
+ response = new node_opcua_service_write_1.WriteResponse({
1855
+ diagnosticInfos: undefined,
1856
+ results
1857
+ });
1858
+ sendResponse(response);
1859
+ });
1860
+ });
1861
+ }
1862
+ // subscription services
1863
+ _on_CreateSubscriptionRequest(message, channel) {
1864
+ const server = this;
1865
+ const engine = server.engine;
1866
+ const addressSpace = engine.addressSpace;
1867
+ const request = message.request;
1868
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.CreateSubscriptionRequest);
1869
+ this._apply_on_SessionObject(node_opcua_service_subscription_1.CreateSubscriptionResponse, message, channel, (session, sendResponse, sendError) => {
1870
+ const context = new node_opcua_address_space_1.SessionContext({ session, server });
1871
+ if (session.currentSubscriptionCount >= OPCUAServer.MAX_SUBSCRIPTION) {
1872
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManySubscriptions);
1873
+ }
1874
+ const subscription = session.createSubscription(request);
1875
+ subscription.on("monitoredItem", (monitoredItem) => {
1876
+ prepareMonitoredItem(context, addressSpace, monitoredItem);
1877
+ });
1878
+ const response = new node_opcua_service_subscription_1.CreateSubscriptionResponse({
1879
+ revisedLifetimeCount: subscription.lifeTimeCount,
1880
+ revisedMaxKeepAliveCount: subscription.maxKeepAliveCount,
1881
+ revisedPublishingInterval: subscription.publishingInterval,
1882
+ subscriptionId: subscription.id
1883
+ });
1884
+ sendResponse(response);
1885
+ });
1886
+ }
1887
+ _on_DeleteSubscriptionsRequest(message, channel) {
1888
+ const server = this;
1889
+ const request = message.request;
1890
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.DeleteSubscriptionsRequest);
1891
+ this._apply_on_SubscriptionIds(node_opcua_service_subscription_1.DeleteSubscriptionsResponse, message, channel, (session, subscriptionId) => __awaiter(this, void 0, void 0, function* () {
1892
+ let subscription = server.engine.findOrphanSubscription(subscriptionId);
1893
+ // istanbul ignore next
1894
+ if (subscription) {
1895
+ warningLog("Deleting an orphan subscription", subscriptionId);
1896
+ yield this._beforeDeleteSubscription(subscription);
1897
+ return server.engine.deleteOrphanSubscription(subscription);
1898
+ }
1899
+ subscription = session.getSubscription(subscriptionId);
1900
+ if (subscription) {
1901
+ yield this._beforeDeleteSubscription(subscription);
1902
+ }
1903
+ return session.deleteSubscription(subscriptionId);
1904
+ }));
1905
+ }
1906
+ _on_TransferSubscriptionsRequest(message, channel) {
1907
+ //
1908
+ // sendInitialValue Boolean
1909
+ // A Boolean parameter with the following values:
1910
+ // TRUE the first Publish response(s) after the TransferSubscriptions call shall
1911
+ // contain the current values of all Monitored Items in the Subscription where
1912
+ // the Monitoring Mode is set to Reporting.
1913
+ // FALSE the first Publish response after the TransferSubscriptions call shall contain only the value
1914
+ // changes since the last Publish response was sent.
1915
+ // This parameter only applies to MonitoredItems used for monitoring Attribute changes.
1916
+ //
1917
+ const server = this;
1918
+ const engine = server.engine;
1919
+ const request = message.request;
1920
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.TransferSubscriptionsRequest);
1921
+ this._apply_on_SubscriptionIds(node_opcua_service_subscription_1.TransferSubscriptionsResponse, message, channel, (session, subscriptionId) => __awaiter(this, void 0, void 0, function* () { return yield engine.transferSubscription(session, subscriptionId, request.sendInitialValues); }));
1922
+ }
1923
+ _on_CreateMonitoredItemsRequest(message, channel) {
1924
+ const server = this;
1925
+ const engine = server.engine;
1926
+ const addressSpace = engine.addressSpace;
1927
+ const request = message.request;
1928
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.CreateMonitoredItemsRequest);
1929
+ this._apply_on_Subscription(node_opcua_service_subscription_1.CreateMonitoredItemsResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1930
+ const timestampsToReturn = request.timestampsToReturn;
1931
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1932
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1933
+ }
1934
+ if (!request.itemsToCreate || request.itemsToCreate.length === 0) {
1935
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1936
+ }
1937
+ if (server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
1938
+ if (request.itemsToCreate.length > server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
1939
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1940
+ }
1941
+ }
1942
+ const options = this.options;
1943
+ let results = [];
1944
+ if (options.onCreateMonitoredItem) {
1945
+ const resultsPromise = request.itemsToCreate.map((monitoredItemCreateRequest) => __awaiter(this, void 0, void 0, function* () {
1946
+ const { monitoredItem, createResult } = subscription.preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest);
1947
+ if (monitoredItem) {
1948
+ yield options.onCreateMonitoredItem(subscription, monitoredItem);
1949
+ subscription.postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult);
1950
+ }
1951
+ return createResult;
1952
+ }));
1953
+ results = yield Promise.all(resultsPromise);
1954
+ }
1955
+ else {
1956
+ results = request.itemsToCreate.map((monitoredItemCreateRequest) => {
1957
+ const { monitoredItem, createResult } = subscription.preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest);
1958
+ if (monitoredItem) {
1959
+ subscription.postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult);
1960
+ }
1961
+ return createResult;
1962
+ });
1963
+ }
1964
+ const response = new node_opcua_service_subscription_1.CreateMonitoredItemsResponse({
1965
+ responseHeader: { serviceResult: node_opcua_status_code_1.StatusCodes.Good },
1966
+ results
1967
+ // ,diagnosticInfos: []
1968
+ });
1969
+ sendResponse(response);
1970
+ }));
1971
+ }
1972
+ _on_ModifySubscriptionRequest(message, channel) {
1973
+ const request = message.request;
1974
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.ModifySubscriptionRequest);
1975
+ this._apply_on_Subscription(node_opcua_service_subscription_1.ModifySubscriptionResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1976
+ subscription.modify(request);
1977
+ const response = new node_opcua_service_subscription_1.ModifySubscriptionResponse({
1978
+ revisedLifetimeCount: subscription.lifeTimeCount,
1979
+ revisedMaxKeepAliveCount: subscription.maxKeepAliveCount,
1980
+ revisedPublishingInterval: subscription.publishingInterval
1981
+ });
1982
+ sendResponse(response);
1983
+ }));
1984
+ }
1985
+ _on_ModifyMonitoredItemsRequest(message, channel) {
1986
+ const server = this;
1987
+ const request = message.request;
1988
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.ModifyMonitoredItemsRequest);
1989
+ this._apply_on_Subscription(node_opcua_service_subscription_1.ModifyMonitoredItemsResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1990
+ const timestampsToReturn = request.timestampsToReturn;
1991
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1992
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1993
+ }
1994
+ if (!request.itemsToModify || request.itemsToModify.length === 0) {
1995
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1996
+ }
1997
+ /* istanbul ignore next */
1998
+ if (server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
1999
+ if (request.itemsToModify.length > server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2000
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2001
+ }
2002
+ }
2003
+ const itemsToModify = request.itemsToModify; // MonitoredItemModifyRequest
2004
+ function modifyMonitoredItem(item) {
2005
+ const monitoredItemId = item.monitoredItemId;
2006
+ const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
2007
+ if (!monitoredItem) {
2008
+ return new node_opcua_service_subscription_1.MonitoredItemModifyResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid });
2009
+ }
2010
+ // adjust samplingInterval if === -1
2011
+ if (item.requestedParameters.samplingInterval === -1) {
2012
+ item.requestedParameters.samplingInterval = subscription.publishingInterval;
2013
+ }
2014
+ return monitoredItem.modify(timestampsToReturn, item.requestedParameters);
2015
+ }
2016
+ const results = itemsToModify.map(modifyMonitoredItem);
2017
+ const response = new node_opcua_service_subscription_1.ModifyMonitoredItemsResponse({
2018
+ results
2019
+ });
2020
+ sendResponse(response);
2021
+ }));
2022
+ }
2023
+ _on_PublishRequest(message, channel) {
2024
+ const request = message.request;
2025
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.PublishRequest);
2026
+ this._apply_on_SessionObject(node_opcua_service_subscription_1.PublishResponse, message, channel, (session, sendResponse, sendError) => {
2027
+ (0, node_opcua_assert_1.assert)(session);
2028
+ (0, node_opcua_assert_1.assert)(session.publishEngine); // server.publishEngine doesn't exists, OPCUAServer has probably shut down already
2029
+ session.publishEngine._on_PublishRequest(request, (request1, response) => {
2030
+ sendResponse(response);
2031
+ });
2032
+ });
2033
+ }
2034
+ _on_SetPublishingModeRequest(message, channel) {
2035
+ const request = message.request;
2036
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.SetPublishingModeRequest);
2037
+ const publishingEnabled = request.publishingEnabled;
2038
+ this._apply_on_Subscriptions(node_opcua_service_subscription_1.SetPublishingModeResponse, message, channel, (session, subscription) => __awaiter(this, void 0, void 0, function* () {
2039
+ return subscription.setPublishingMode(publishingEnabled);
2040
+ }));
2041
+ }
2042
+ _on_DeleteMonitoredItemsRequest(message, channel) {
2043
+ const server = this;
2044
+ const request = message.request;
2045
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.DeleteMonitoredItemsRequest);
2046
+ this._apply_on_Subscription(node_opcua_service_subscription_1.DeleteMonitoredItemsResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2047
+ /* istanbul ignore next */
2048
+ if (!request.monitoredItemIds || request.monitoredItemIds.length === 0) {
2049
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2050
+ }
2051
+ /* istanbul ignore next */
2052
+ if (server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
2053
+ if (request.monitoredItemIds.length > server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2054
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2055
+ }
2056
+ }
2057
+ const resultsPromises = request.monitoredItemIds.map((monitoredItemId) => __awaiter(this, void 0, void 0, function* () {
2058
+ if (this.options.onDeleteMonitoredItem) {
2059
+ const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
2060
+ if (monitoredItem) {
2061
+ yield this.options.onDeleteMonitoredItem(subscription, monitoredItem);
2062
+ }
2063
+ }
2064
+ return subscription.removeMonitoredItem(monitoredItemId);
2065
+ }));
2066
+ try {
2067
+ const results = yield Promise.all(resultsPromises);
2068
+ const response = new node_opcua_service_subscription_1.DeleteMonitoredItemsResponse({
2069
+ diagnosticInfos: undefined,
2070
+ results
2071
+ });
2072
+ sendResponse(response);
2073
+ }
2074
+ catch (err) {
2075
+ console.log(err);
2076
+ return sendError(node_opcua_status_code_1.StatusCodes.BadInternalError);
2077
+ }
2078
+ }));
2079
+ }
2080
+ _on_SetTriggeringRequest(message, channel) {
2081
+ const server = this;
2082
+ const request = message.request;
2083
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.SetTriggeringRequest);
2084
+ this._apply_on_Subscription(node_opcua_service_subscription_1.SetTriggeringResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2085
+ /* */
2086
+ const { triggeringItemId, linksToAdd, linksToRemove } = request;
2087
+ /**
2088
+ * The MaxMonitoredItemsPerCall Property indicates
2089
+ * [...]
2090
+ * • the maximum size of the sum of the linksToAdd and linksToRemove arrays when a
2091
+ * Client calls the SetTriggering Service.
2092
+ *
2093
+ */
2094
+ const maxElements = (linksToAdd ? linksToAdd.length : 0) + (linksToRemove ? linksToRemove.length : 0);
2095
+ if (server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
2096
+ if (maxElements > server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2097
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2098
+ }
2099
+ }
2100
+ const { addResults, removeResults, statusCode } = subscription.setTriggering(triggeringItemId, linksToAdd, linksToRemove);
2101
+ const response = new node_opcua_service_subscription_1.SetTriggeringResponse({
2102
+ responseHeader: { serviceResult: statusCode },
2103
+ addResults,
2104
+ removeResults,
2105
+ addDiagnosticInfos: null,
2106
+ removeDiagnosticInfos: null
2107
+ });
2108
+ sendResponse(response);
2109
+ }));
2110
+ }
2111
+ _beforeDeleteSubscription(subscription) {
2112
+ return __awaiter(this, void 0, void 0, function* () {
2113
+ if (!this.options.onDeleteMonitoredItem) {
2114
+ return;
2115
+ }
2116
+ yield subscription.applyOnMonitoredItem(this.options.onDeleteMonitoredItem.bind(null, subscription));
2117
+ });
2118
+ }
2119
+ _on_RepublishRequest(message, channel) {
2120
+ const request = message.request;
2121
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.RepublishRequest);
2122
+ this._apply_on_Subscription(node_opcua_service_subscription_1.RepublishResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2123
+ // update diagnostic counter
2124
+ subscription.subscriptionDiagnostics.republishRequestCount += 1;
2125
+ subscription.subscriptionDiagnostics.republishMessageRequestCount += 1;
2126
+ const retransmitSequenceNumber = request.retransmitSequenceNumber;
2127
+ const notificationMessage = subscription.getMessageForSequenceNumber(retransmitSequenceNumber);
2128
+ if (!notificationMessage) {
2129
+ return sendError(node_opcua_status_code_1.StatusCodes.BadMessageNotAvailable);
2130
+ }
2131
+ const response = new node_opcua_service_subscription_1.RepublishResponse({
2132
+ notificationMessage,
2133
+ responseHeader: {
2134
+ serviceResult: node_opcua_status_code_1.StatusCodes.Good
2135
+ }
2136
+ });
2137
+ // update diagnostic counter
2138
+ subscription.subscriptionDiagnostics.republishMessageCount += 1;
2139
+ sendResponse(response);
2140
+ }));
2141
+ }
2142
+ // Bad_NothingToDo
2143
+ // Bad_TooManyOperations
2144
+ // Bad_SubscriptionIdInvalid
2145
+ // Bad_MonitoringModeInvalid
2146
+ _on_SetMonitoringModeRequest(message, channel) {
2147
+ const server = this;
2148
+ const request = message.request;
2149
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.SetMonitoringModeRequest);
2150
+ this._apply_on_Subscription(node_opcua_service_subscription_1.SetMonitoringModeResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2151
+ /* istanbul ignore next */
2152
+ if (!request.monitoredItemIds || request.monitoredItemIds.length === 0) {
2153
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2154
+ }
2155
+ /* istanbul ignore next */
2156
+ if (server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
2157
+ if (request.monitoredItemIds.length > server.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2158
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2159
+ }
2160
+ }
2161
+ const monitoringMode = request.monitoringMode;
2162
+ if (!isMonitoringModeValid(monitoringMode)) {
2163
+ return sendError(node_opcua_status_code_1.StatusCodes.BadMonitoringModeInvalid);
2164
+ }
2165
+ const results = request.monitoredItemIds.map((monitoredItemId) => {
2166
+ const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
2167
+ if (!monitoredItem) {
2168
+ return node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid;
2169
+ }
2170
+ monitoredItem.setMonitoringMode(monitoringMode);
2171
+ return node_opcua_status_code_1.StatusCodes.Good;
2172
+ });
2173
+ const response = new node_opcua_service_subscription_1.SetMonitoringModeResponse({
2174
+ results
2175
+ });
2176
+ sendResponse(response);
2177
+ }));
2178
+ }
2179
+ // _on_TranslateBrowsePathsToNodeIds service
2180
+ _on_TranslateBrowsePathsToNodeIdsRequest(message, channel) {
2181
+ const request = message.request;
2182
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsRequest);
2183
+ const server = this;
2184
+ this._apply_on_SessionObject(node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsResponse, message, channel, (session, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2185
+ if (!request.browsePaths || request.browsePaths.length === 0) {
2186
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2187
+ }
2188
+ if (server.engine.serverCapabilities.operationLimits.maxNodesPerTranslateBrowsePathsToNodeIds > 0) {
2189
+ if (request.browsePaths.length >
2190
+ server.engine.serverCapabilities.operationLimits.maxNodesPerTranslateBrowsePathsToNodeIds) {
2191
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2192
+ }
2193
+ }
2194
+ const browsePathsResults = request.browsePaths.map((browsePath) => server.engine.browsePath(browsePath));
2195
+ const response = new node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsResponse({
2196
+ diagnosticInfos: null,
2197
+ results: browsePathsResults
2198
+ });
2199
+ sendResponse(response);
2200
+ }));
2201
+ }
2202
+ // Call Service Result Codes
2203
+ // Symbolic Id Description
2204
+ // Bad_NothingToDo See Table 165 for the description of this result code.
2205
+ // Bad_TooManyOperations See Table 165 for the description of this result code.
2206
+ //
2207
+ _on_CallRequest(message, channel) {
2208
+ const server = this;
2209
+ const request = message.request;
2210
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_call_1.CallRequest);
2211
+ this._apply_on_SessionObject(node_opcua_service_call_1.CallResponse, message, channel, (session, sendResponse, sendError) => {
2212
+ let response;
2213
+ if (!request.methodsToCall || request.methodsToCall.length === 0) {
2214
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2215
+ }
2216
+ // the MaxNodesPerMethodCall Property indicates the maximum size of the methodsToCall array when
2217
+ // a Client calls the Call Service.
2218
+ let maxNodesPerMethodCall = server.engine.serverCapabilities.operationLimits.maxNodesPerMethodCall;
2219
+ maxNodesPerMethodCall = maxNodesPerMethodCall <= 0 ? 1000 : maxNodesPerMethodCall;
2220
+ if (request.methodsToCall.length > maxNodesPerMethodCall) {
2221
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2222
+ }
2223
+ /* jshint validthis: true */
2224
+ const addressSpace = server.engine.addressSpace;
2225
+ const context = new node_opcua_address_space_1.SessionContext({ session, server });
2226
+ async.map(request.methodsToCall, node_opcua_address_space_1.callMethodHelper.bind(null, context, addressSpace), (err, results) => {
2227
+ /* istanbul ignore next */
2228
+ if (err) {
2229
+ errorLog("ERROR in method Call !! ", err);
2230
+ }
2231
+ (0, node_opcua_assert_1.assert)(Array.isArray(results));
2232
+ response = new node_opcua_service_call_1.CallResponse({
2233
+ results: results
2234
+ });
2235
+ sendResponse(response);
2236
+ });
2237
+ });
2238
+ }
2239
+ _on_RegisterNodesRequest(message, channel) {
2240
+ const server = this;
2241
+ const request = message.request;
2242
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_register_node_1.RegisterNodesRequest);
2243
+ this._apply_on_SessionObject(node_opcua_service_register_node_1.RegisterNodesResponse, message, channel, (session, sendResponse, sendError) => {
2244
+ let response;
2245
+ if (!request.nodesToRegister || request.nodesToRegister.length === 0) {
2246
+ response = new node_opcua_service_register_node_1.RegisterNodesResponse({ responseHeader: { serviceResult: node_opcua_status_code_1.StatusCodes.BadNothingToDo } });
2247
+ return sendResponse(response);
2248
+ }
2249
+ if (server.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes > 0) {
2250
+ if (request.nodesToRegister.length > server.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes) {
2251
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2252
+ }
2253
+ }
2254
+ // A list of NodeIds which the Client shall use for subsequent access operations. The
2255
+ // size and order of this list matches the size and order of the nodesToRegister
2256
+ // request parameter.
2257
+ // The Server may return the NodeId from the request or a new (an alias) NodeId. It
2258
+ // is recommended that the Server return a numeric NodeIds for aliasing.
2259
+ // In case no optimization is supported for a Node, the Server shall return the
2260
+ // NodeId from the request.
2261
+ const registeredNodeIds = request.nodesToRegister.map((nodeId) => session.registerNode(nodeId));
2262
+ response = new node_opcua_service_register_node_1.RegisterNodesResponse({
2263
+ registeredNodeIds
2264
+ });
2265
+ sendResponse(response);
2266
+ });
2267
+ }
2268
+ _on_UnregisterNodesRequest(message, channel) {
2269
+ const server = this;
2270
+ const request = message.request;
2271
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_register_node_1.UnregisterNodesRequest);
2272
+ this._apply_on_SessionObject(node_opcua_service_register_node_1.UnregisterNodesResponse, message, channel, (session, sendResponse, sendError) => {
2273
+ let response;
2274
+ request.nodesToUnregister = request.nodesToUnregister || [];
2275
+ if (!request.nodesToUnregister || request.nodesToUnregister.length === 0) {
2276
+ response = new node_opcua_service_register_node_1.UnregisterNodesResponse({ responseHeader: { serviceResult: node_opcua_status_code_1.StatusCodes.BadNothingToDo } });
2277
+ return sendResponse(response);
2278
+ }
2279
+ if (server.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes > 0) {
2280
+ if (request.nodesToUnregister.length > server.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes) {
2281
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2282
+ }
2283
+ }
2284
+ request.nodesToUnregister.map((nodeId) => session.unRegisterNode(nodeId));
2285
+ response = new node_opcua_service_register_node_1.UnregisterNodesResponse({});
2286
+ sendResponse(response);
2287
+ });
2288
+ }
2289
+ /* istanbul ignore next */
2290
+ _on_Cancel(message, channel) {
2291
+ return g_sendError(channel, message, node_opcua_types_1.CancelResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2292
+ }
2293
+ // NodeManagement Service Set Overview
2294
+ // This Service Set defines Services to add and delete AddressSpace Nodes and References between them. All added
2295
+ // Nodes continue to exist in the AddressSpace even if the Client that created them disconnects from the Server.
2296
+ //
2297
+ /* istanbul ignore next */
2298
+ _on_AddNodes(message, channel) {
2299
+ return g_sendError(channel, message, node_opcua_service_node_management_1.AddNodesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2300
+ }
2301
+ /* istanbul ignore next */
2302
+ _on_AddReferences(message, channel) {
2303
+ return g_sendError(channel, message, node_opcua_service_node_management_1.AddReferencesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2304
+ }
2305
+ /* istanbul ignore next */
2306
+ _on_DeleteNodes(message, channel) {
2307
+ return g_sendError(channel, message, node_opcua_service_node_management_1.DeleteNodesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2308
+ }
2309
+ /* istanbul ignore next */
2310
+ _on_DeleteReferences(message, channel) {
2311
+ return g_sendError(channel, message, node_opcua_service_node_management_1.DeleteReferencesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2312
+ }
2313
+ // Query Service
2314
+ /* istanbul ignore next */
2315
+ _on_QueryFirst(message, channel) {
2316
+ return g_sendError(channel, message, node_opcua_service_query_1.QueryFirstResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2317
+ }
2318
+ /* istanbul ignore next */
2319
+ _on_QueryNext(message, channel) {
2320
+ return g_sendError(channel, message, node_opcua_service_query_1.QueryNextResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2321
+ }
2322
+ /* istanbul ignore next */
2323
+ _on_HistoryUpdate(message, channel) {
2324
+ return g_sendError(channel, message, node_opcua_service_history_1.HistoryUpdateResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2325
+ }
2326
+ createEndpoint(port1, serverOptions) {
2327
+ // add the tcp/ip endpoint with no security
2328
+ const endPoint = new server_end_point_1.OPCUAServerEndPoint({
2329
+ port: port1,
2330
+ certificateManager: this.serverCertificateManager,
2331
+ certificateChain: this.getCertificateChain(),
2332
+ privateKey: this.getPrivateKey(),
2333
+ defaultSecureTokenLifetime: serverOptions.defaultSecureTokenLifetime || 600000,
2334
+ timeout: serverOptions.timeout || 3 * 60 * 1000,
2335
+ maxConnections: this.maxConnectionsPerEndpoint,
2336
+ objectFactory: this.objectFactory,
2337
+ serverInfo: this.serverInfo
2338
+ });
2339
+ return endPoint;
2340
+ }
2341
+ createEndpointDescriptions(serverOption, endpointOptions) {
2342
+ /* istanbul ignore next */
2343
+ if (!endpointOptions) {
2344
+ throw new Error("internal error");
2345
+ }
2346
+ const hostname = (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
2347
+ endpointOptions.hostname = endpointOptions.hostname || hostname;
2348
+ endpointOptions.port = endpointOptions.port || 26543;
2349
+ /* istanbul ignore next */
2350
+ if (!Object.prototype.hasOwnProperty.call(endpointOptions, "port") ||
2351
+ !isFinite(endpointOptions.port) ||
2352
+ typeof endpointOptions.port !== "number") {
2353
+ throw new Error("expecting a valid port (number)");
2354
+ }
2355
+ const port = Number(endpointOptions.port || 0);
2356
+ const endPoint = this.createEndpoint(port, serverOption);
2357
+ endpointOptions.alternateHostname = endpointOptions.alternateHostname || [];
2358
+ const alternateHostname = endpointOptions.alternateHostname instanceof Array
2359
+ ? endpointOptions.alternateHostname
2360
+ : [endpointOptions.alternateHostname];
2361
+ const allowAnonymous = endpointOptions.allowAnonymous === undefined ? true : !!endpointOptions.allowAnonymous;
2362
+ endPoint.addStandardEndpointDescriptions({
2363
+ allowAnonymous,
2364
+ securityModes: endpointOptions.securityModes,
2365
+ securityPolicies: endpointOptions.securityPolicies,
2366
+ hostname: endpointOptions.hostname,
2367
+ alternateHostname,
2368
+ disableDiscovery: !!endpointOptions.disableDiscovery,
2369
+ // xx hostname,
2370
+ resourcePath: serverOption.resourcePath || ""
2371
+ });
2372
+ return endPoint;
2373
+ }
2374
+ initializeCM() {
2375
+ const _super = Object.create(null, {
2376
+ initializeCM: { get: () => super.initializeCM }
2377
+ });
2378
+ return __awaiter(this, void 0, void 0, function* () {
2379
+ yield _super.initializeCM.call(this);
2380
+ yield this.userCertificateManager.initialize();
2381
+ });
2382
+ }
2383
+ }
2384
+ exports.OPCUAServer = OPCUAServer;
2385
+ OPCUAServer.defaultShutdownTimeout = 100; // 250 ms
2386
+ /**
2387
+ * if requestExactEndpointUrl is set to true the server will only accept createSession that have a endpointUrl that strictly matches
2388
+ * one of the provided endpoint.
2389
+ * This mean that if the server expose a endpoint with url such as opc.tcp://MYHOSTNAME:1234, client will not be able to reach the server
2390
+ * with the ip address of the server.
2391
+ * requestExactEndpointUrl = true => emulates the Prosys Server behavior
2392
+ * requestExactEndpointUrl = false => emulates the Unified Automation behavior.
2393
+ */
2394
+ OPCUAServer.requestExactEndpointUrl = g_requestExactEndpointUrl;
2395
+ OPCUAServer.registry = new node_opcua_object_registry_1.ObjectRegistry();
2396
+ OPCUAServer.fallbackSessionName = "Client didn't provide a meaningful sessionName ...";
2397
+ /**
2398
+ * the maximum number of subscription that can be created per server
2399
+ */
2400
+ OPCUAServer.MAX_SUBSCRIPTION = 50;
2401
+ // tslint:disable:no-var-requires
2402
+ const thenify = require("thenify");
2403
+ const opts = { multiArgs: false };
2404
+ OPCUAServer.prototype.start = thenify.withCallback(OPCUAServer.prototype.start, opts);
2405
+ OPCUAServer.prototype.initialize = thenify.withCallback(OPCUAServer.prototype.initialize, opts);
2406
+ OPCUAServer.prototype.shutdown = thenify.withCallback(OPCUAServer.prototype.shutdown, opts);
2407
+ //# sourceMappingURL=opcua_server.js.map