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