@yarkivaev/scada 2.17.0 → 2.19.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 (132) hide show
  1. package/index.js +14 -2
  2. package/package.json +5 -2
  3. package/src/application/cycleTimelineFetch.js +56 -0
  4. package/src/application/deploy/collectorSourcePlan.js +97 -0
  5. package/src/application/deploy/compileCollectorTasks.js +31 -0
  6. package/src/application/deploy/compileControlCatalog.js +66 -0
  7. package/src/application/deploy/controlPlan.js +16 -0
  8. package/src/application/deploy/controlPlaneConfiguration.js +62 -0
  9. package/src/application/deploy/controlReaderSpecs.js +37 -0
  10. package/src/application/deploy/edgeDescriptors.js +31 -0
  11. package/src/application/deploy/fieldbusSourcePlan.js +79 -0
  12. package/src/application/deploy/liveReleaseOverlay.js +17 -0
  13. package/src/application/deploy/plantBindingProfile.js +24 -0
  14. package/src/application/deploy/projectControlPlane.js +48 -0
  15. package/src/application/deploy/projectTopology.js +41 -0
  16. package/src/application/deploy/topologyGraph.js +81 -0
  17. package/src/application/edgeOperatorCatalog.js +9 -7
  18. package/src/application/mcp/analyticsMcpPort.js +20 -0
  19. package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
  20. package/src/application/mcp/analyticsTextContent.js +13 -0
  21. package/src/application/mcp/plantReadPorts.js +168 -0
  22. package/src/application/mcp/textContentCatalog.js +7 -0
  23. package/src/application/operationPrefixes.js +67 -0
  24. package/src/application/operatorCatalogView.js +8 -0
  25. package/src/application/projectPlantShops.js +17 -0
  26. package/src/application/runtime/collectorDslManifest.js +44 -0
  27. package/src/application/runtime/collectorLaunch.js +34 -0
  28. package/src/application/runtime/collectorOptions.js +21 -0
  29. package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
  30. package/src/application/runtime/embeddedCollectors.js +6 -0
  31. package/src/application/runtime/index.js +7 -1
  32. package/src/application/runtime/pagedDelivery.js +87 -0
  33. package/src/application/runtime/resolveSecrets.js +9 -0
  34. package/src/application/siteOperatorCatalog.js +8 -7
  35. package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
  36. package/src/application/siteRuntime/cutoverOperations.js +25 -0
  37. package/src/application/siteRuntime/databaseMigrations.js +27 -0
  38. package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
  39. package/src/application/siteRuntime/history.js +29 -0
  40. package/src/application/siteRuntime/index.js +16 -0
  41. package/src/application/siteRuntime/measurementTopic.js +9 -0
  42. package/src/application/siteRuntime/operationFederation.js +15 -0
  43. package/src/application/siteRuntime/operationSnapshot.js +18 -0
  44. package/src/application/siteRuntime/operatorField.js +49 -0
  45. package/src/application/siteRuntime/operatorUpdates.js +37 -0
  46. package/src/application/siteRuntime/telemetry.js +31 -0
  47. package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
  48. package/src/application/timelineMetrics.js +36 -0
  49. package/src/domain/timeline/cyclePhases.js +191 -0
  50. package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
  51. package/src/infrastructure/deploy/brokerReplicaTopology.js +34 -12
  52. package/src/infrastructure/deploy/brokerSecurity.js +89 -0
  53. package/src/infrastructure/deploy/brokerSecurityInput.js +85 -0
  54. package/src/infrastructure/deploy/brokerTopology.js +125 -0
  55. package/src/infrastructure/deploy/centralTelemetry.js +51 -0
  56. package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
  57. package/src/infrastructure/deploy/collectorChartPlan.js +68 -0
  58. package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
  59. package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
  60. package/src/infrastructure/deploy/configuredClassification.js +74 -0
  61. package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
  62. package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
  63. package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
  64. package/src/infrastructure/deploy/configuredHistorySeed.js +54 -0
  65. package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -0
  66. package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
  67. package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
  68. package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
  69. package/src/infrastructure/deploy/databaseSecurity.js +39 -0
  70. package/src/infrastructure/deploy/deploymentRecovery.js +49 -0
  71. package/src/infrastructure/deploy/deploymentTemplate.js +67 -0
  72. package/src/infrastructure/deploy/executeConfiguredChartDeployment.js +65 -0
  73. package/src/infrastructure/deploy/executeManagedDeployment.js +46 -0
  74. package/src/infrastructure/deploy/highAvailability/brokerOwnership.js +19 -0
  75. package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +61 -0
  76. package/src/infrastructure/deploy/highAvailability/classifyFederation.js +57 -0
  77. package/src/infrastructure/deploy/highAvailability/classifyGate.js +114 -0
  78. package/src/infrastructure/deploy/highAvailability/classifyLoop.js +139 -0
  79. package/src/infrastructure/deploy/highAvailability/classifyShovels.js +70 -0
  80. package/src/infrastructure/deploy/highAvailability/classifyWatermark.js +45 -0
  81. package/src/infrastructure/deploy/highAvailability/compileClassifierRules.js +21 -0
  82. package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
  83. package/src/infrastructure/deploy/highAvailability/controllerReconcile.js +14 -0
  84. package/src/infrastructure/deploy/highAvailability/historyReceiver.js +49 -0
  85. package/src/infrastructure/deploy/highAvailability/historyWatermark.js +42 -0
  86. package/src/infrastructure/deploy/highAvailability/index.js +15 -0
  87. package/src/infrastructure/deploy/highAvailability/reconcileBrokerThroughController.js +18 -0
  88. package/src/infrastructure/deploy/highAvailability/reconciliationBundle.js +28 -0
  89. package/src/infrastructure/deploy/highAvailability/segmentAdmit.js +24 -0
  90. package/src/infrastructure/deploy/highAvailability/segmentPublish.js +27 -0
  91. package/src/infrastructure/deploy/highAvailability/supervisorReplica.js +36 -0
  92. package/src/infrastructure/deploy/index.js +46 -2
  93. package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
  94. package/src/infrastructure/deploy/projectClassification.js +42 -0
  95. package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
  96. package/src/infrastructure/deploy/securityPolicy.js +16 -0
  97. package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
  98. package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
  99. package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
  100. package/src/infrastructure/http/edge/attachClassify.js +30 -0
  101. package/src/infrastructure/http/edge/classifyProxy.js +72 -0
  102. package/src/infrastructure/http/edge/classifyRecord.js +32 -0
  103. package/src/infrastructure/http/edge/classifyRouting.js +14 -0
  104. package/src/infrastructure/http/edge/siteAccess.js +7 -0
  105. package/src/infrastructure/http/edge/writeGuard.js +84 -0
  106. package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
  107. package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
  108. package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
  109. package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
  110. package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
  111. package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
  112. package/src/infrastructure/ingest/telemetry/centralPolicy.js +29 -8
  113. package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
  114. package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
  115. package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
  116. package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
  117. package/src/infrastructure/mdmesh/index.js +5 -0
  118. package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
  119. package/src/infrastructure/mdmesh/publishApk.js +30 -0
  120. package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
  121. package/src/infrastructure/opcua/projectSources.js +36 -0
  122. package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
  123. package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
  124. package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
  125. package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
  126. package/src/infrastructure/streams/boundedTextFrames.js +27 -0
  127. package/src/infrastructure/streams/framedSerialSource.js +25 -0
  128. package/src/infrastructure/streams/index.js +5 -0
  129. package/src/infrastructure/streams/namedSerialDevices.js +26 -0
  130. package/src/infrastructure/streams/serialLine.js +26 -0
  131. package/src/infrastructure/streams/watchCurrentReading.js +31 -0
  132. package/src/infrastructure/streams/windowPublication.js +73 -0
@@ -0,0 +1,84 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ import { errorResponse } from '@yarkivaev/simple-server';
3
+
4
+ function strongProxyToken(value) {
5
+ return typeof value === 'string' && value.length === 64 && /^[a-fA-F0-9]{64}$/u.test(value);
6
+ }
7
+
8
+ /** Explicit rollout gate: legacy callers retain current behavior until enabled. */
9
+ export function proxyPolicy(environment = process.env) {
10
+ const required = environment.SCADA_TRUSTED_PROXY_REQUIRED ?? 'false';
11
+ if (!['true','false'].includes(required)) { throw new Error('SCADA_TRUSTED_PROXY_REQUIRED must be true or false'); }
12
+ const token = environment.SCADA_TRUSTED_PROXY_TOKEN || '';
13
+ if (required === 'true' && !strongProxyToken(token)) {
14
+ throw new Error('SCADA_TRUSTED_PROXY_TOKEN must contain 64 hexadecimal characters');
15
+ }
16
+ return {required:required === 'true',token};
17
+ }
18
+
19
+ function identityTrusted(headers, policy) {
20
+ if (!policy.required) { return true; }
21
+ const presented = headers['x-scada-proxy-token'];
22
+ return strongProxyToken(presented)
23
+ && timingSafeEqual(Buffer.from(presented),Buffer.from(policy.token));
24
+ }
25
+
26
+ export function trustedGroups(headers, policy) {
27
+ return identityTrusted(headers,policy) ? headers['remote-groups'] || '' : '';
28
+ }
29
+
30
+ function sanitizeIdentity(headers, policy) {
31
+ if (!identityTrusted(headers,policy)) {
32
+ for (const header of ['remote-groups','remote-user','remote-email','remote-name']) { delete headers[header]; }
33
+ }
34
+ }
35
+
36
+ /** Build authorization for configured groups and an optional service bearer. */
37
+ export default function writeGuard(roles) {
38
+ const roleSet = new Set(roles);
39
+ function granted(groups) {
40
+ return String(groups || '').split(',').some((group) => { return roleSet.has(group.trim()); });
41
+ }
42
+
43
+ /**
44
+ * Returns whether this method and caller may change plant state.
45
+ *
46
+ * @param {string} method - HTTP method
47
+ * @param {string} groups - Remote-Groups header
48
+ * @param {string} authorization - Authorization header
49
+ * @param {string} serviceToken - expected bearer for owner-routed writes
50
+ * @returns {boolean} true when the call may proceed
51
+ */
52
+ function allowsMutation(method, groups, authorization, serviceToken) {
53
+ if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') {
54
+ return true;
55
+ }
56
+ if (granted(groups)) {
57
+ return true;
58
+ }
59
+ return Boolean(serviceToken) && authorization === `Bearer ${serviceToken}`;
60
+ }
61
+
62
+ /**
63
+ * Replaces the plant server request listener with the write role check.
64
+ *
65
+ * @param {object} httpServer - Node HTTP server from plantServer
66
+ * @param {object} api - plant API with handle()
67
+ * @param {string} serviceToken - bearer accepted for service writes
68
+ */
69
+ function installWriteGuard(httpServer, api, serviceToken, environment = process.env) {
70
+ const policy = proxyPolicy(environment);
71
+ httpServer.removeAllListeners('request');
72
+ httpServer.on('request', (req, res) => {
73
+ sanitizeIdentity(req.headers,policy);
74
+ const groups = trustedGroups(req.headers,policy);
75
+ const authorization = req.headers.authorization || '';
76
+ if (allowsMutation(req.method, groups, authorization, serviceToken)) {
77
+ api.handle(req, res);
78
+ return;
79
+ }
80
+ errorResponse('FORBIDDEN', `write role required for ${req.method}`, 403).send(res);
81
+ });
82
+ }
83
+ return { granted, allowsMutation, installWriteGuard };
84
+ }
@@ -0,0 +1,18 @@
1
+ import { jsonResponse, route } from '@yarkivaev/simple-server';
2
+ import machineInPlant from '../../../../application/machineInPlant.js';
3
+
4
+ export function operationRange(query) {
5
+ return { ...(query.from && { from: new Date(query.from) }), ...(query.to && { to: new Date(query.to) }) };
6
+ }
7
+
8
+ /** Read a fixed operation kind through its application projection. */
9
+ export default function machineOperationList(path, plant, { kind, project }) {
10
+ return route('GET', path, async (req, res, { machineId }, query) => {
11
+ if (!machineInPlant(plant, machineId) || !plant.operations) {
12
+ jsonResponse({ items: [] }).send(res);
13
+ return;
14
+ }
15
+ const rows = await plant.operations.listForMachine(machineId, kind, operationRange(query));
16
+ jsonResponse({ items: rows.map(project) }).send(res);
17
+ });
18
+ }
@@ -5,16 +5,7 @@ import operationWrites from './operationWrites.js';
5
5
  import httpOperations from '../../../messaging/ownership/httpOperations.js';
6
6
  import { jsonResponse, route, sendRouteError } from '@yarkivaev/simple-server';
7
7
 
8
- function parseRange(query) {
9
- const range = {};
10
- if (query.from) {
11
- range.from = new Date(query.from);
12
- }
13
- if (query.to) {
14
- range.to = new Date(query.to);
15
- }
16
- return range;
17
- }
8
+ import { operationRange } from './machineOperationList.js';
18
9
 
19
10
  function resolveKinds(query) {
20
11
  if (query.kinds) {
@@ -45,7 +36,7 @@ async function listLocal(plant, machineId, query) {
45
36
  const rows = await plant.operations.listForMachine(
46
37
  machineId,
47
38
  resolveKinds(query),
48
- parseRange(query)
39
+ operationRange(query)
49
40
  );
50
41
  return { items: rows.map(operationJson) };
51
42
  }
@@ -141,3 +141,28 @@ export default function operatorRoute(basePath, provider, logger) {
141
141
  })
142
142
  ];
143
143
  }
144
+
145
+ function fieldFromBody(parsed, field, validate) {
146
+ if (!parsed || typeof parsed !== 'object') {
147
+ throw routeFailure('BAD_REQUEST', 'operator body must be a JSON object', 400);
148
+ }
149
+ if (!Object.hasOwn(parsed, field)) {
150
+ throw routeFailure('BAD_REQUEST', `operator body must include ${field}`, 400);
151
+ }
152
+ return { [field]: validate(parsed[field]) };
153
+ }
154
+
155
+ /** Add a PATCH route for a separately managed operator field. */
156
+ export function operatorFieldRoute(basePath, provider, { field, validate }, logger) {
157
+ return [route('PATCH', `${basePath}/operators/:id`, async (req, res, params) => {
158
+ try {
159
+ const fields = fieldFromBody(JSON.parse(await readBody(req)), field, validate);
160
+ const updated = await provider.update(params.id, fields);
161
+ jsonResponse(operatorJson(updated)).send(res);
162
+ } catch (error) {
163
+ if (sendKnown(res, error)) { return; }
164
+ report(logger, `PATCH ${basePath}/operators/${params.id} failed: ${error?.message || 'unknown error'}`, error);
165
+ sendRouteError(res, error);
166
+ }
167
+ })];
168
+ }
@@ -1,42 +1,30 @@
1
1
  import operationJson from '../json/operationJson.js';
2
2
  import { route, sseResponse } from '@yarkivaev/simple-server';
3
3
 
4
- /**
5
- * Operations SSE route for plant-wide create, update, and delete events.
6
- *
7
- * @param {string} basePath - base URL path
8
- * @param {object} plant - plant domain object
9
- * @param {function} clock - time provider
10
- * @returns {array} route objects
11
- *
12
- * @example
13
- * operationStream('/api/v1', plant, clock);
14
- */
4
+ /** Serve operation events with one heartbeat and subscription per connection. */
5
+ export function operationEvents(path, plant, clock, { names, project, filter = () => { return true; }, available = () => { return true; } }) {
6
+ return route('GET', path, (req, res, params) => {
7
+ const sse = sseResponse(res, clock);
8
+ sse.heartbeat();
9
+ if (!plant.operations || !available(params)) {
10
+ sse.close();
11
+ return;
12
+ }
13
+ const subscription = plant.operations.stream(({ type, operation }) => {
14
+ if (!operation || !filter(operation, params)) { return; }
15
+ if (Object.hasOwn(names, type)) { sse.emit(names[type], project(operation)); }
16
+ });
17
+ const heartbeat = setInterval(() => { sse.heartbeat(); }, 30000);
18
+ req.on('close', () => {
19
+ clearInterval(heartbeat);
20
+ subscription.cancel();
21
+ });
22
+ });
23
+ }
24
+
25
+ /** Plant-wide create, update, and delete events. */
15
26
  export default function operationStream(basePath, plant, clock) {
16
- return [
17
- route('GET', `${basePath}/operations/stream`, (req, res) => {
18
- const sse = sseResponse(res, clock);
19
- sse.heartbeat();
20
- if (!plant.operations) {
21
- sse.close();
22
- return;
23
- }
24
- const subscription = plant.operations.stream((event) => {
25
- if (event.type === 'created' && event.operation) {
26
- sse.emit('operation_created', operationJson(event.operation));
27
- } else if (event.type === 'updated' && event.operation) {
28
- sse.emit('operation_updated', operationJson(event.operation));
29
- } else if (event.type === 'deleted' && event.operation) {
30
- sse.emit('operation_deleted', operationJson(event.operation));
31
- }
32
- });
33
- const heartbeat = setInterval(() => {
34
- sse.heartbeat();
35
- }, 30000);
36
- req.on('close', () => {
37
- clearInterval(heartbeat);
38
- subscription.cancel();
39
- });
40
- })
41
- ];
27
+ return [operationEvents(`${basePath}/operations/stream`, plant, clock, {
28
+ names: { created: 'operation_created', updated: 'operation_updated', deleted: 'operation_deleted' }, project: operationJson
29
+ })];
42
30
  }
@@ -1,3 +1,7 @@
1
+ import serialLine from '../../streams/serialLine.js';
2
+
3
+ export { serialLine as parseModbusLineFormat };
4
+
1
5
  /**
2
6
  * Parses Modbus device connection specs from MODBUS_DEVICES entries.
3
7
  *
@@ -9,33 +13,6 @@
9
13
  * parseModbusDeviceSpec('m-2:192.0.2.11:502');
10
14
  */
11
15
 
12
- /**
13
- * Parses serial line format such as 8N1 into modbus-serial options.
14
- *
15
- * @param {string} line - Data bits, parity letter, stop bits (e.g. 8N1)
16
- * @returns {object} dataBits, parity, stopBits
17
- */
18
- export function parseModbusLineFormat(line) {
19
- if (typeof line !== 'string' || line.length !== 3) {
20
- throw new Error(`Serial line format must be three characters such as 8N1, got: ${line}`);
21
- }
22
- const dataBits = parseInt(line.charAt(0), 10);
23
- const parityLetter = line.charAt(1).toUpperCase();
24
- const stopBits = parseInt(line.charAt(2), 10);
25
- let parity = '';
26
- if (parityLetter === 'N') {
27
- parity = 'none';
28
- } else if (parityLetter === 'E') {
29
- parity = 'even';
30
- } else if (parityLetter === 'O') {
31
- parity = 'odd';
32
- }
33
- if (parity.length === 0 || Number.isNaN(dataBits) || Number.isNaN(stopBits)) {
34
- throw new Error(`Serial line format must be such as 8N1, got: ${line}`);
35
- }
36
- return { dataBits, parity, stopBits };
37
- }
38
-
39
16
  /**
40
17
  * Parses RTU device spec parts into connection parameters.
41
18
  *
@@ -65,7 +42,7 @@ function parseRtuDeviceSpec(spec, parts) {
65
42
  serial: {
66
43
  baudRate,
67
44
  slaveId,
68
- ...parseModbusLineFormat(line)
45
+ ...serialLine(line)
69
46
  }
70
47
  };
71
48
  }
@@ -57,7 +57,7 @@ function placed(order, first, second) {
57
57
  * @param {number} second - second register in the window
58
58
  * @returns {number} decoded float
59
59
  */
60
- function floatOf(order, first, second) {
60
+ export function modbusFloat(order, first, second) {
61
61
  const pair = placed(order, first, second);
62
62
  const buffer = new ArrayBuffer(4);
63
63
  const view = new DataView(buffer);
@@ -86,5 +86,5 @@ export function decodePoint(point, origin, registers) {
86
86
  if (parsed.order === orders.uint16) {
87
87
  return registers[index];
88
88
  }
89
- return floatOf(parsed.order, registers[index], registers[index + 1]);
89
+ return modbusFloat(parsed.order, registers[index], registers[index + 1]);
90
90
  }
@@ -1,3 +1,5 @@
1
+ export const centralTelemetryVersion = 4;
2
+
1
3
  function keys(value, allowed) {
2
4
  if (!value || typeof value !== 'object' || Array.isArray(value)
3
5
  || Object.keys(value).some((key) => { return !allowed.includes(key); })) {
@@ -22,20 +24,20 @@ export function centralRule(value, fallback = ruleDefaults) {
22
24
  }
23
25
  return rule;
24
26
  }
25
- /** Native point storage with a bounded immutable archive. */
26
- export default function centralPolicy(input = {}) {
27
- const config = typeof input === 'string' ? JSON.parse(input) : input;
27
+ function parsePolicy(config, strict = false) {
28
28
  keys(config, ['enabled', 'default', 'topics', 'queue', 'queueMaxBytes', 'maxPendingBatches', 'batchSize']);
29
- if (config.enabled !== undefined && typeof config.enabled !== 'boolean') { throw new TypeError('Invalid central policy enabled'); }
29
+ if ((strict || config.enabled !== undefined) && typeof config.enabled !== 'boolean') { throw new TypeError('Invalid central policy enabled'); }
30
30
  keys(config.default ?? {}, CENTRAL_RULE_FIELDS);
31
31
  const defaults = centralRule(config.default ?? {});
32
- if (!Array.isArray(config.topics ?? [])) { throw new TypeError('Invalid central policy topics'); }
32
+ const entries = config.topics === undefined || (!strict && config.topics === null) ? [] : config.topics;
33
+ if (!Array.isArray(entries)) { throw new TypeError('Invalid central policy topics'); }
33
34
  const topics = new Map();
34
- (config.topics ?? []).forEach((entry) => {
35
+ entries.forEach((entry) => {
35
36
  keys(entry, ['topic', ...CENTRAL_RULE_FIELDS]);
36
37
  if (typeof entry.topic !== 'string' || !entry.topic || entry.topic.length > 1024
37
38
  // eslint-disable-next-line no-control-regex
38
- || /[\s\u0000-\u001f\u007f#+*]/u.test(entry.topic) || topics.has(entry.topic)) {
39
+ || /[\s\u0000-\u001f\u007f#+*]/u.test(entry.topic) || topics.has(entry.topic)
40
+ || (strict && /[\p{Cc}{}]/u.test(entry.topic))) {
39
41
  throw new TypeError('Invalid or duplicate central policy topic');
40
42
  }
41
43
  topics.set(entry.topic, centralRule(entry, defaults));
@@ -44,8 +46,27 @@ export default function centralPolicy(input = {}) {
44
46
  if (typeof queue !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,254}$/u.test(queue) || queue.startsWith('amq.')) {
45
47
  throw new TypeError('Invalid central policy queue');
46
48
  }
47
- return { enabled: config.enabled === true, queue, forTopic(topic) { return topics.get(topic) ?? defaults; },
49
+ return { enabled: config.enabled === true, defaults, topics, queue,
48
50
  queueMaxBytes: positive(config.queueMaxBytes ?? 1073741824, 'queue bytes'),
49
51
  maxPendingBatches: positive(config.maxPendingBatches ?? 100000, 'pending batches', 2147483647),
50
52
  batchSize: positive(config.batchSize ?? 500, 'batch size', 1000) };
51
53
  }
54
+
55
+
56
+ function serializedRule({ compactWindowMs, maxGapMs, ...rest }) {
57
+ return { compactWindowMs, maxGapMs, ...rest };
58
+ }
59
+
60
+ /** Normalize and validate the policy object serialized into deployment values and collector specs. */
61
+ export function normalizeCentralPolicy(config) {
62
+ const { enabled, defaults, topics, ...options } = parsePolicy(config, true);
63
+ return { enabled, default: serializedRule(defaults),
64
+ topics: [...topics].map(([topic, rule]) => { return { topic, ...serializedRule(rule) }; }), ...options };
65
+ }
66
+
67
+ /** Native point storage with a bounded immutable archive. */
68
+ export default function centralPolicy(input = {}) {
69
+ const config = typeof input === 'string' ? JSON.parse(input) : input;
70
+ const { enabled, defaults, topics, queue, ...limits } = parsePolicy(config);
71
+ return { enabled, queue, forTopic(topic) { return topics.get(topic) ?? defaults; }, ...limits };
72
+ }
@@ -0,0 +1,60 @@
1
+ import { createHash } from 'node:crypto';
2
+ import operateRemote from './operateKiosk.js';
3
+ import renderResources from './renderKioskResources.js';
4
+
5
+ const restartAnnotation = 'kubectl.kubernetes.io/restartedAt';
6
+
7
+ function between(value, minimum, maximum) {
8
+ return Number.isInteger(value) && value >= minimum && value <= maximum;
9
+ }
10
+
11
+ function checkSettings(config) {
12
+ if (!config || !/^[a-z_][a-z0-9_-]*$/u.test(config.audioUser ?? '') || !between(config.volumePercent, 0, 100)
13
+ || !between(config.audioCard, 0, 32) || !between(config.debugPort, 1, 65535)) {
14
+ throw new TypeError('Invalid kiosk audio/browser settings');
15
+ }
16
+ }
17
+
18
+ function browserTarget(host, nodeAddress, config, policy, targetPattern) {
19
+ const match = targetPattern.exec(host ?? '');
20
+ if (!match) { throw new TypeError('Exact kiosk target required'); }
21
+ checkSettings(config);
22
+ const url = new URL(config.url.replace('{number}', match[1]));
23
+ if (url.protocol !== 'http:' || !['localhost', '127.0.0.1', nodeAddress].includes(url.hostname)
24
+ || url.username || url.password || url.port !== policy.port || url.hash
25
+ || (url.search && url.search !== policy.query.replace('{number}', match[1])) || !/^[\w/.-]*$/u.test(url.pathname)) {
26
+ throw new TypeError('Invalid kiosk HMI URL');
27
+ }
28
+ if (!/^\d{1,3}(?:\.\d{1,3}){3}$/u.test(nodeAddress ?? '')) { throw new TypeError('Invalid kiosk node address'); }
29
+ return { ...config, url: url.href, host, nodeAddress };
30
+ }
31
+
32
+ function browserObjects(plan, declaration, policy) {
33
+ const objects = renderResources(declaration);
34
+ for (const object of objects.filter(({ kind }) => { return kind === 'DaemonSet'; })) {
35
+ const pod = object.spec.template.metadata;
36
+ for (const metadata of [object.metadata, pod]) {
37
+ metadata.labels = { ...metadata.labels, [policy.workloadLabel]: plan.host };
38
+ }
39
+ delete pod.annotations?.[restartAnnotation];
40
+ }
41
+ objects.find(({ metadata }) => { return metadata.name === policy.urlConfigMap; }).data.url = plan.url;
42
+ const browser = objects.find(({ metadata }) => { return metadata.name === policy.browser; });
43
+ browser.spec.template.metadata.annotations[policy.checksumAnnotation] = createHash('sha256').update(plan.url).digest('hex');
44
+ return objects;
45
+ }
46
+
47
+ /** Project the declared browser resources and connect per-installation SSH credentials. */
48
+ export default function kioskDeployment(policy, declaration) {
49
+ const targetPattern = new RegExp(policy.targetPattern, 'u');
50
+ return {
51
+ kioskPlan(host, nodeAddress, config) { return browserTarget(host, nodeAddress, config, policy, targetPattern); },
52
+ kioskObjects(plan) { return browserObjects(plan, declaration, policy); },
53
+ operateKiosk(plan, action, execute, environment = process.env) {
54
+ const ssh = Object.fromEntries(Object.entries(policy.sshEnvironment ?? {}).map(([key, name]) => {
55
+ return [key, environment[name]];
56
+ }));
57
+ return operateRemote(plan, action, { execute, environment, ssh });
58
+ }
59
+ };
60
+ }
@@ -0,0 +1,19 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { mdmeshPasswordHash } from './bootstrapMdmeshCredentials.js';
5
+
6
+ /** Restore the declared native administrator before its release job runs. */
7
+ export default function adminReconciliation(plan, kube, policy) {
8
+ if (!plan.values.admin) { return; }
9
+ const { password } = plan.values.admin;
10
+ const hash = mdmeshPasswordHash(password);
11
+ const data = { ADMIN_PASSWORD: Buffer.from(password).toString('base64'), ADMIN_PASSWORD_HASH: Buffer.from(hash).toString('base64') };
12
+ const directory = mkdtempSync(path.join(tmpdir(), 'hmi-admin-'));
13
+ try {
14
+ const file = path.join(directory, 'patch.json');
15
+ writeFileSync(file, JSON.stringify({ data }), { mode: 0o600 });
16
+ kube(['patch', 'secret', plan.values.secret, '--type=merge', `--patch-file=${file}`]);
17
+ } finally { rmSync(directory, { recursive: true, force: true }); }
18
+ kube(['delete', 'job', '-l', policy.selector, '--ignore-not-found=true', '--wait=true', '--timeout=60s']);
19
+ }
@@ -0,0 +1,47 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+
4
+ export function mdmeshPasswordHash(input) {
5
+ return createHash('sha1').update(`${createHash('md5').update(input).digest('hex').toUpperCase()}5YdSYHyg2U`).digest('hex');
6
+ }
7
+
8
+ function password() { return randomBytes(32).toString('base64url'); }
9
+
10
+ function connectionSecret(name, namespace, declared) {
11
+ const admin = declared?.password || password();
12
+ const api = password();
13
+ const monitor = password();
14
+ const values = {
15
+ DB_USER: 'mdmesh', DB_PASSWORD: password(), HASH_SECRET: randomBytes(32).toString('hex'), JWT_SECRET: randomBytes(64).toString('hex'),
16
+ ADMIN_PASSWORD: admin, ADMIN_PASSWORD_HASH: mdmeshPasswordHash(admin), ADMIN_RESET_TOKEN: randomBytes(20).toString('hex'),
17
+ API_LOGIN: 'hmi-controller', API_PASSWORD: api, API_PASSWORD_HASH: mdmeshPasswordHash(api),
18
+ MONITOR_LOGIN: 'hmi-monitor', MONITOR_PASSWORD: monitor, MONITOR_PASSWORD_HASH: mdmeshPasswordHash(monitor), CONTROL_TOKEN: password()
19
+ };
20
+ return { apiVersion: 'v1', kind: 'Secret', metadata: { name, namespace }, type: 'Opaque',
21
+ data: Object.fromEntries(Object.entries(values).map(([key, value]) => { return [key, Buffer.from(value).toString('base64')]; })) };
22
+ }
23
+
24
+ function registrySecret(name, namespace, registryFile, policy) {
25
+ if (!registryFile) { throw new Error('HMI bootstrap requires a dedicated read-only registry credential file'); }
26
+ const config = JSON.parse(readFileSync(registryFile, 'utf8'));
27
+ const token = new RegExp(policy.registryIdentityPattern, 'u');
28
+ const entries = Object.entries(config.auths || {});
29
+ if (!entries.length || entries.some(([repository, value]) => {
30
+ return !policy.registryRepositories.includes(repository) || !token.test(Buffer.from(value.auth || '', 'base64').toString())
31
+ || Object.keys(value).some((key) => { return key !== 'auth'; });
32
+ })) { throw new Error('HMI registry credentials require project-scoped deploy tokens'); }
33
+ const data = Buffer.from(JSON.stringify({ auths: Object.fromEntries(entries) })).toString('base64');
34
+ return { apiVersion: 'v1', kind: 'Secret', metadata: { name, namespace }, type: 'kubernetes.io/dockerconfigjson',
35
+ data: { '.dockerconfigjson': data } };
36
+ }
37
+
38
+ /** Initialize absent MDMesh and registry credentials without replacing existing passwords. */
39
+ export default function bootstrapMdmeshCredentials(plan, kube, policy, registryFile = process.env[policy.registryFileEnvironment]) {
40
+ const { namespace, values } = plan;
41
+ function apply(object) { kube(['apply', '--server-side', `--field-manager=${policy.fieldManager}`, '-f', '-'], JSON.stringify(object)); }
42
+ function missing(name) { return !kube(['get', 'secret', name, '--ignore-not-found', '-o', 'name']).trim(); }
43
+ apply({ apiVersion: 'v1', kind: 'Namespace', metadata: { name: namespace } });
44
+ if (missing(values.secret)) { apply(connectionSecret(values.secret, namespace, values.admin)); }
45
+ if (missing(values.pullSecret)) { apply(registrySecret(values.pullSecret, namespace, registryFile, policy)); }
46
+ return { namespace, credentialSecret: values.secret };
47
+ }
@@ -0,0 +1,17 @@
1
+ import requestFromWorkload from '../deploy/requestFromWorkload.js';
2
+
3
+ /** Route controller operations to the running workload with catalog and target validation. */
4
+ export default function controllerOperation(action, plan, kube, device, policy) {
5
+ const operation = Object.hasOwn(policy.actions, action) && policy.actions[action];
6
+ if (!operation) { throw new Error('Unknown HMI operation'); }
7
+ const { catalog } = plan.values;
8
+ if (operation.device && !catalog.devices.some(({ id }) => { return id === device; })) {
9
+ throw new Error('HMI action requires a declared tablet');
10
+ }
11
+ return requestFromWorkload(kube, {
12
+ workload: policy.workload, url: `${policy.baseUrl}/${operation.path}`, method: operation.method,
13
+ tokenEnv: policy.tokenEnv, configuration: { ...policy.configuration, expected: catalog },
14
+ body: operation.device ? { device, action } : undefined,
15
+ requireApplied: operation.requireApplied === true
16
+ });
17
+ }
@@ -6,3 +6,8 @@ export { default as hmiReconcile } from './hmiReconcile.js';
6
6
  export { default as hmiRuntime } from './hmiRuntime.js';
7
7
  export { default as mdmeshClient } from './mdmeshClient.js';
8
8
  export { default as hmiPlan } from './hmiPlan.js';
9
+ export { default as mdmeshServerRelease } from './mdmeshServerRelease.js';
10
+ export { default as bootstrapMdmeshCredentials } from './bootstrapMdmeshCredentials.js';
11
+ export { default as adminReconciliation } from './adminReconciliation.js';
12
+ export { default as controllerOperation } from './controllerOperation.js';
13
+ export { default as publishApk } from './publishApk.js';
@@ -0,0 +1,58 @@
1
+ import deploymentTemplate from '../deploy/deploymentTemplate.js';
2
+
3
+ function label(value, context) {
4
+ if (typeof value !== 'string' || value.length > 63 || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(value)) {
5
+ throw new Error(`Invalid HMI ${context}`);
6
+ }
7
+ }
8
+
9
+ function databaseSettings({ postgresNamespace, postgresHost }, namespace) {
10
+ label(postgresNamespace, 'database namespace');
11
+ const database = postgresHost?.split('.');
12
+ if (postgresNamespace === namespace || database?.length !== 5 || database[1] !== postgresNamespace || database.slice(2).join('.') !== 'svc.cluster.local') {
13
+ throw new Error('HMI database must use a cluster Service outside its namespace');
14
+ }
15
+ label(database[0], 'database service');
16
+ }
17
+
18
+ function authenticationSettings({ authentication }, { namespace, authenticationProvider }) {
19
+ if (authentication?.provider !== authenticationProvider || authentication.namespace === namespace) {
20
+ throw new Error('HMI authentication must remain outside the application namespace');
21
+ }
22
+ label(authentication.namespace, 'authentication namespace');
23
+ if (new URL(authentication.portalUrl).protocol !== 'https:') { throw new Error('HMI authentication requires HTTPS'); }
24
+ }
25
+
26
+ function imageSettings(values) {
27
+ for (const key of ['serverImage', 'webImage', 'supervisorImage']) {
28
+ if (typeof values[key] !== 'string' || !/@sha256:[a-f0-9]{64}$/u.test(values[key])) {
29
+ throw new Error(`HMI ${key} requires an immutable digest`);
30
+ }
31
+ }
32
+ if (values.publicConsole?.enabled && !/@sha256:[a-f0-9]{64}$/u.test(values.publicConsole.image || '')) {
33
+ throw new Error('HMI public console requires an immutable digest');
34
+ }
35
+ }
36
+
37
+ function settings(values, policy) {
38
+ const url = new URL(values.baseUrl);
39
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') {
40
+ throw new Error('HMI orchestrator requires a public HTTPS origin');
41
+ }
42
+ imageSettings(values);
43
+ for (const key of ['secret', 'pullSecret']) { label(values[key], key); }
44
+ if (values.admin && (values.admin.login !== 'admin' || typeof values.admin.password !== 'string' || !values.admin.password.length)) {
45
+ throw new Error('Managed MDMesh administrator requires login admin and a nonempty password');
46
+ }
47
+ authenticationSettings(values, policy);
48
+ databaseSettings(values, policy.namespace);
49
+ }
50
+
51
+ /** Compile an isolated MDMesh release from the supplied catalog and service policy. */
52
+ export default function mdmeshServerRelease(target, catalog, values, policy) {
53
+ if (catalog.namespace !== policy.namespace) { throw new Error(`HMI workloads require their dedicated ${policy.namespace} namespace`); }
54
+ settings(values, policy);
55
+ return { context: target, namespace: catalog.namespace, release: deploymentTemplate(policy.release, { target }),
56
+ chart: policy.chart, fieldManager: policy.fieldManager,
57
+ values: { ...values, platformResources: false, catalog, planJSON: JSON.stringify(catalog) } };
58
+ }
@@ -0,0 +1,30 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import deploymentTemplate from '../deploy/deploymentTemplate.js';
5
+
6
+ function validatedArtifact(plan, device, artifact) {
7
+ const target = plan.values.catalog.devices.find(({ id }) => { return id === device; })?.application?.apk;
8
+ const filename = target && path.basename(new URL(target.url).pathname);
9
+ if (!filename || !/^[a-z0-9-]+\.apk$/u.test(filename)) { throw new Error('HMI publishing requires a declared APK'); }
10
+ if (createHash('sha256').update(readFileSync(artifact)).digest('hex') !== target.sha256) {
11
+ throw new Error('HMI APK does not match its DSL SHA-256');
12
+ }
13
+ return { filename, sha256: target.sha256 };
14
+ }
15
+
16
+ /** Copy a pinned APK to a declared volume via a temporary Pod and verify before publication. */
17
+ export default function publishApk(plan, device, artifact, kube, policy) {
18
+ const { filename, sha256 } = validatedArtifact(plan, device, artifact);
19
+ const { podName: name } = policy;
20
+ const { directory } = policy;
21
+ if (!/^\/[a-z0-9-]+(?:\/[a-z0-9-]+)*$/u.test(directory)) { throw new TypeError('Invalid APK volume path'); }
22
+ const pod = deploymentTemplate(policy.pod, { name, values: plan.values });
23
+ kube(['create', '-f', '-'], JSON.stringify(pod));
24
+ try {
25
+ kube(['wait', '--for=condition=Ready', `pod/${name}`, '--timeout=120s']);
26
+ kube(['cp', artifact, `${name}:/tmp/artifact.apk`]);
27
+ return kube(['exec', name, '--', 'sh', '-ec',
28
+ `printf '%s /tmp/artifact.apk\\n' '${sha256}' | sha256sum -c -; mkdir -p ${directory}; cp /tmp/artifact.apk ${directory}/${filename}.tmp; chmod 644 ${directory}/${filename}.tmp; mv ${directory}/${filename}.tmp ${directory}/${filename}`]);
29
+ } finally { kube(['delete', 'pod', name, '--wait=true', '--timeout=30s']); }
30
+ }
@@ -1,3 +1,13 @@
1
+ /** AMQP 0-9-1 forwarder with persistent messages, supporting queues and exchanges. */
2
+ export function brokerShovel({ name, sourceUri, queue, destinationUri, exchange, destinationQueue, reconnectDelay, vhost = '/' }) {
3
+ return { vhost, component: 'shovel', name, value: {
4
+ 'src-protocol': 'amqp091', 'src-uri': sourceUri, 'src-queue': queue,
5
+ 'dest-protocol': 'amqp091', 'dest-uri': destinationUri,
6
+ ...(destinationQueue === undefined ? { 'dest-exchange': exchange } : { 'dest-queue': destinationQueue }),
7
+ 'reconnect-delay': reconnectDelay, 'dest-publish-properties': { delivery_mode: 2 }
8
+ } };
9
+ }
10
+
1
11
  /** Builds durable topic exchanges, queues and AMQP 0-9-1 outboxes for one virtual host. */
2
12
  export default function rabbitmqDefinitions({ vhost, users = [], permissions = [], exchanges = [],
3
13
  queues = [], bindings = [], outboxes = [] }) {
@@ -13,12 +23,8 @@ export default function rabbitmqDefinitions({ vhost, users = [], permissions = [
13
23
  return { source, vhost, destination, destination_type: 'queue', routing_key: key, arguments: {} };
14
24
  }),
15
25
  parameters: outboxes.filter(({ shovel }) => { return shovel; }).map(({ queue, shovel }) => {
16
- return { vhost, component: 'shovel', name: shovel.name, value: {
17
- 'src-protocol': 'amqp091', 'src-uri': shovel.sourceUri, 'src-queue': queue,
18
- 'dest-protocol': 'amqp091', 'dest-uri': shovel.destinationUri,
19
- 'dest-exchange': shovel.destinationExchange, 'reconnect-delay': shovel.reconnectDelay,
20
- 'dest-publish-properties': { delivery_mode: 2 }
21
- } };
26
+ const { name, sourceUri, destinationUri, destinationExchange, reconnectDelay } = shovel;
27
+ return brokerShovel({ name, vhost, queue, sourceUri, destinationUri, exchange: destinationExchange, reconnectDelay });
22
28
  })
23
29
  };
24
30
  }