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