@yarkivaev/scada 2.15.0 → 2.17.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 (47) hide show
  1. package/db/bootstrap/apply-hba.sh +11 -0
  2. package/db/bootstrap/entrypoint.sh +6 -0
  3. package/db/bootstrap/ownership.sql +18 -0
  4. package/db/bootstrap/zz-auth.sh +3 -0
  5. package/index.js +1 -0
  6. package/package.json +3 -2
  7. package/src/application/control/controller.js +2 -9
  8. package/src/application/control/periodicReconciliation.js +19 -0
  9. package/src/application/control/publishControlCatalog.js +25 -0
  10. package/src/application/control/reconcileStoredChoice.js +10 -0
  11. package/src/application/deploy/controlPlacement.js +71 -0
  12. package/src/application/deploy/controlPlan.js +124 -0
  13. package/src/application/deploy/deploymentCommands.js +29 -0
  14. package/src/application/deploy/deploymentPlan.js +84 -0
  15. package/src/application/deploy/readDeploymentDocument.js +25 -0
  16. package/src/application/deploy/readDocumentFile.js +28 -0
  17. package/src/application/deploy/releases.js +14 -10
  18. package/src/infrastructure/deploy/applyHelmResources.js +17 -0
  19. package/src/infrastructure/deploy/bootstrapKubeStorage.js +28 -0
  20. package/src/infrastructure/deploy/brokerReplicaTopology.js +75 -0
  21. package/src/infrastructure/deploy/buildDeploymentStages.js +23 -0
  22. package/src/infrastructure/deploy/compileDeploymentHooks.js +48 -0
  23. package/src/infrastructure/deploy/deploymentChecks.js +68 -0
  24. package/src/infrastructure/deploy/deploymentPatch.js +36 -0
  25. package/src/infrastructure/deploy/executeChartDeployment.js +19 -0
  26. package/src/infrastructure/deploy/executeRelease.js +6 -2
  27. package/src/infrastructure/deploy/executeStagedDeployment.js +31 -0
  28. package/src/infrastructure/deploy/index.js +36 -0
  29. package/src/infrastructure/deploy/postgresBootstrap.js +79 -0
  30. package/src/infrastructure/deploy/reconcileDeployments.js +47 -0
  31. package/src/infrastructure/deploy/requestFromWorkload.js +30 -0
  32. package/src/infrastructure/deploy/stagedStoragePreflight.js +72 -0
  33. package/src/infrastructure/deploy/validateStagedDeploymentEvidence.js +16 -0
  34. package/src/infrastructure/deploy/verifyRuntimeCapabilities.js +34 -0
  35. package/src/infrastructure/management/kiosk/kiosk-browser.py +91 -0
  36. package/src/infrastructure/management/kiosk/kiosk-volume.sh +105 -0
  37. package/src/infrastructure/management/kiosk/listen.mjs.txt +14 -0
  38. package/src/infrastructure/management/kiosk/operateKiosk.js +74 -0
  39. package/src/infrastructure/management/kiosk/renderKioskResources.js +41 -0
  40. package/src/infrastructure/management/kiosk/shellArgument.js +4 -0
  41. package/src/infrastructure/management/kiosk/wait-x11.sh +1 -0
  42. package/src/infrastructure/management/kiosk/watchdog-liveness.sh +1 -0
  43. package/src/infrastructure/management/kiosk/watchdog-readiness.sh +1 -0
  44. package/src/infrastructure/management/kiosk/watchdog.sh +137 -0
  45. package/src/infrastructure/management/serveReconciliation.js +17 -0
  46. package/src/infrastructure/mdmesh/hmiPlan.js +123 -0
  47. package/src/infrastructure/mdmesh/index.js +1 -0
@@ -0,0 +1,91 @@
1
+ """Operate only the declared kiosk HMI page over loopback CDP; no external packages."""
2
+ import base64
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import socket
7
+ import struct
8
+ import sys
9
+ import time
10
+ import urllib.request
11
+ from urllib.parse import urlparse
12
+
13
+
14
+ def target(tabs, expected):
15
+ matches = [tab for tab in tabs if tab.get('type') == 'page'
16
+ and tab.get('url', '').split('#')[0] == expected
17
+ and tab.get('webSocketDebuggerUrl')]
18
+ if len(matches) != 1:
19
+ raise RuntimeError('Expected exactly one declared HMI page')
20
+ return matches[0]
21
+
22
+
23
+ def receive(sock, size):
24
+ data = b''
25
+ while len(data) < size:
26
+ chunk = sock.recv(size - len(data))
27
+ if not chunk:
28
+ raise RuntimeError('CDP connection closed')
29
+ data += chunk
30
+ return data
31
+
32
+
33
+ def reload_page(ws_url, port):
34
+ parsed = urlparse(ws_url)
35
+ if parsed.scheme != 'ws' or parsed.hostname not in ['127.0.0.1', 'localhost'] or parsed.port != port:
36
+ raise RuntimeError('CDP websocket must remain on declared loopback port')
37
+ with socket.create_connection(('127.0.0.1', port), timeout=5) as sock:
38
+ key = base64.b64encode(os.urandom(16)).decode()
39
+ request = (f'GET {parsed.path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n'
40
+ f'Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n'
41
+ 'Sec-WebSocket-Version: 13\r\n\r\n')
42
+ sock.sendall(request.encode())
43
+ header = b''
44
+ while not header.endswith(b'\r\n\r\n'):
45
+ header += receive(sock, 1)
46
+ if len(header) > 16384:
47
+ raise RuntimeError('CDP handshake too large')
48
+ accept = base64.b64encode(hashlib.sha1((key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').encode()).digest())
49
+ if b' 101 ' not in header.split(b'\r\n')[0] or accept not in header:
50
+ raise RuntimeError('CDP handshake rejected')
51
+ payload = json.dumps({'id': 1, 'method': 'Page.reload', 'params': {'ignoreCache': True}}).encode()
52
+ mask = os.urandom(4)
53
+ sock.sendall(bytes([0x81, 0x80 | len(payload)]) + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))
54
+ deadline = time.monotonic() + 10
55
+ while time.monotonic() < deadline:
56
+ frame = receive(sock, 2)
57
+ length = frame[1] & 127
58
+ if length == 126:
59
+ length = struct.unpack('!H', receive(sock, 2))[0]
60
+ elif length == 127:
61
+ length = struct.unpack('!Q', receive(sock, 8))[0]
62
+ if length > 1048576 or frame[1] & 128:
63
+ raise RuntimeError('Invalid CDP frame')
64
+ data = receive(sock, length)
65
+ opcode = frame[0] & 15
66
+ if opcode == 8:
67
+ raise RuntimeError('CDP closed before reload confirmation')
68
+ if opcode != 1:
69
+ continue
70
+ reply = json.loads(data)
71
+ if reply.get('id') == 1:
72
+ if 'error' in reply:
73
+ raise RuntimeError('CDP rejected Page.reload')
74
+ return
75
+ raise RuntimeError('CDP reload reply timed out')
76
+
77
+
78
+ def main(action, port, expected):
79
+ if action not in ['check', 'reload']:
80
+ raise ValueError('Unknown browser action')
81
+ # Ignore proxy environment: browser control never leaves loopback.
82
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
83
+ with opener.open(f'http://127.0.0.1:{port}/json/list', timeout=5) as response:
84
+ page = target(json.load(response), expected)
85
+ if action == 'reload':
86
+ reload_page(page['webSocketDebuggerUrl'], port)
87
+ print(f'Kiosk browser {action} verified')
88
+
89
+
90
+ if __name__ == '__main__':
91
+ main(sys.argv[1], int(sys.argv[2]), sys.argv[3])
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env bash
2
+ # Set and verify kiosk speaker volume.
3
+ #
4
+ # Env:
5
+ # VOLUME_PERCENT — integer 0-100 (required)
6
+ # KIOSK_USER — PipeWire session user (default kiosk)
7
+ # AMIXER_CMD — amixer binary (default amixer)
8
+ # AMIXER_CARD — ALSA card index (default 0)
9
+ # WPCTL_CMD — wpctl binary (default wpctl)
10
+ # ID_CMD — id binary (default id)
11
+ # PULSE_SOCKET — override Pulse native socket path
12
+ #
13
+ # Usage: kiosk-volume.sh
14
+ set -eu
15
+ set -o pipefail
16
+
17
+ percent="${VOLUME_PERCENT:-}"
18
+ case "$percent" in
19
+ ''|*[!0-9]*)
20
+ echo "VOLUME_PERCENT must be an integer 0-100, got '${percent}'" >&2
21
+ exit 2
22
+ ;;
23
+ esac
24
+ if [ "$percent" -gt 100 ]; then
25
+ echo "VOLUME_PERCENT must be an integer 0-100, got '${percent}'" >&2
26
+ exit 2
27
+ fi
28
+
29
+ amixer="${AMIXER_CMD:-amixer}"
30
+ card="${AMIXER_CARD:-0}"
31
+ wpctl="${WPCTL_CMD:-wpctl}"
32
+ idcmd="${ID_CMD:-id}"
33
+ user="${KIOSK_USER:-kiosk}"
34
+
35
+ action="${KIOSK_AUDIO_ACTION:-check}"
36
+ case "$action" in check|apply) ;; *) echo "Invalid audio action" >&2; exit 2 ;; esac
37
+ if [ "$action" = apply ]; then
38
+ "$amixer" -q -c "$card" sset Master "${percent}%" unmute
39
+ fi
40
+ mixer="$("$amixer" -c "$card" sget Master)"
41
+ found=0
42
+ while IFS= read -r line; do
43
+ case "$line" in
44
+ *Playback*'['*'%]'*|*'['*'%]'*'[on]'*|*'['*'%]'*'[off]'*)
45
+ case "$line" in
46
+ *Mono:*|*'Front '*:*|*Playback*)
47
+ found=1
48
+ case "$line" in
49
+ *"[$percent%]"*'[on]'*|*'[on]'*"[$percent%]")
50
+ ;;
51
+ *)
52
+ echo "ALSA Master is not ${percent}% unmuted: ${line}" >&2
53
+ echo "$mixer" >&2
54
+ exit 1
55
+ ;;
56
+ esac
57
+ ;;
58
+ esac
59
+ ;;
60
+ esac
61
+ done <<EOF
62
+ $mixer
63
+ EOF
64
+ if [ "$found" -eq 0 ]; then
65
+ echo "ALSA Master has no Playback percent reading" >&2
66
+ echo "$mixer" >&2
67
+ exit 1
68
+ fi
69
+
70
+ uid="$("$idcmd" -u "$user")"
71
+ runtime="/run/user/${uid}"
72
+ socket="${PULSE_SOCKET:-${runtime}/pulse/native}"
73
+ if [ ! -S "$socket" ]; then
74
+ echo "Pulse socket is missing at ${socket}" >&2
75
+ exit 1
76
+ fi
77
+
78
+ export XDG_RUNTIME_DIR="$runtime"
79
+ if [ "$action" = apply ]; then
80
+ "$wpctl" set-volume @DEFAULT_AUDIO_SINK@ "${percent}%"
81
+ "$wpctl" set-mute @DEFAULT_AUDIO_SINK@ 0
82
+ fi
83
+ vol="$("$wpctl" get-volume @DEFAULT_AUDIO_SINK@)"
84
+ level="$(printf '%s\n' "$vol" | awk '/Volume:/{print $2; exit}')"
85
+ if [ -z "$level" ]; then
86
+ echo "PipeWire sink has no volume reading: ${vol}" >&2
87
+ exit 1
88
+ fi
89
+ if ! awk -v got="$level" -v p="$percent" 'BEGIN {
90
+ want = p / 100
91
+ diff = got - want
92
+ if (diff < 0) diff = -diff
93
+ exit (diff < 0.015) ? 0 : 1
94
+ }'; then
95
+ echo "PipeWire sink is not ${percent}%: ${vol}" >&2
96
+ exit 1
97
+ fi
98
+ case "$vol" in
99
+ *MUTED*)
100
+ echo "PipeWire sink is still muted: ${vol}" >&2
101
+ exit 1
102
+ ;;
103
+ esac
104
+
105
+ printf "Kiosk audio verified: %s%%, unmuted\n" "$percent"
@@ -0,0 +1,14 @@
1
+ import net from 'node:net';
2
+ const host = process.env.HOST_IP;
3
+ const port = Number(process.env.CDP_PORT || '9222');
4
+ net.createServer((client) => {
5
+ const up = net.connect(port, '127.0.0.1');
6
+ client.pipe(up);
7
+ up.pipe(client);
8
+ const stop = () => {
9
+ client.destroy();
10
+ up.destroy();
11
+ };
12
+ client.on('error', stop);
13
+ up.on('error', stop);
14
+ }).listen(port, host);
@@ -0,0 +1,74 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { isIP } from 'node:net';
4
+ import shellArgument from './shellArgument.js';
5
+
6
+ const audio = new URL('./kiosk-volume.sh', import.meta.url);
7
+ const browser = new URL('./kiosk-browser.py', import.meta.url);
8
+
9
+ function credential(file, encoding) {
10
+ if (!file) { return null; }
11
+ const value = readFileSync(file, 'utf8').trimEnd();
12
+ return encoding === 'base64' ? Buffer.from(value, 'base64').toString('utf8') : value;
13
+ }
14
+
15
+ function between(value, min, max) {
16
+ return Number.isInteger(value) && value >= min && value <= max;
17
+ }
18
+
19
+ function validate(plan, action) {
20
+ if (!['check', 'apply', 'reload'].includes(action)) { throw new TypeError('Unknown kiosk action'); }
21
+ if (!/^[a-z0-9][a-z0-9._-]*$/iu.test(plan.host) || !isIP(plan.nodeAddress)
22
+ || !/^[a-z_][a-z0-9_-]*$/u.test(plan.audioUser)
23
+ || !between(plan.volumePercent, 0, 100) || !between(plan.audioCard, 0, 32)
24
+ || !between(plan.debugPort, 1, 65535)) {
25
+ throw new TypeError('Invalid kiosk target or device settings');
26
+ }
27
+ const url = new URL(plan.url);
28
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash) {
29
+ throw new TypeError('Invalid kiosk page URL');
30
+ }
31
+ return url.href;
32
+ }
33
+
34
+ function ssh(host, { passwordFile, encoding, config, knownHosts }, execute, environment) {
35
+ const password = credential(passwordFile, encoding);
36
+ const program = password === null ? 'ssh' : 'sshpass';
37
+ const args = [
38
+ ...(password === null ? [] : ['-e', 'ssh']),
39
+ ...(config ? ['-F', config] : []),
40
+ ...(knownHosts ? ['-o', `UserKnownHostsFile=${knownHosts}`, '-o', 'StrictHostKeyChecking=yes'] : []),
41
+ '-o', `BatchMode=${password === null ? 'yes' : 'no'}`, '-o', 'NumberOfPasswordPrompts=1',
42
+ '-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=5', '-o', 'ServerAliveCountMax=2', host
43
+ ];
44
+ return function remote(command, input) {
45
+ return String(execute(program, [...args, command], {
46
+ encoding: 'utf8', timeout: 45000, input,
47
+ env: { ...environment, ...(password !== null && { SSHPASS: password }) }
48
+ }));
49
+ };
50
+ }
51
+
52
+ function audioResult(remote, plan, action, settings) {
53
+ const password = credential(settings.sudoPasswordFile, settings.encoding);
54
+ if (password?.includes('\n')) { throw new Error('Multiline sudo credential is not supported'); }
55
+ const env = `env KIOSK_AUDIO_ACTION=${action} VOLUME_PERCENT=${plan.volumePercent} KIOSK_USER=${plan.audioUser} AMIXER_CARD=${plan.audioCard}`;
56
+ const source = readFileSync(audio, 'utf8');
57
+ if (password === null) { return remote(`sudo -n ${env} bash -s`, source); }
58
+ // Keep the credential out of the command and outside the shell source.
59
+ return remote(`bash -c 'IFS= read -r scada_password; scada_script=$(cat); printf "%s\\n" "$scada_password" | sudo -k -S -p "" ${env} bash -c "$scada_script"'`,
60
+ `${password}\n${source}`);
61
+ }
62
+
63
+ /** Check the declared host before operating its local mixer or browser. */
64
+ export default function operateKiosk(plan, action, { execute = execFileSync, environment = process.env, ssh: settings = {} } = {}) {
65
+ const url = validate(plan, action);
66
+ const remote = ssh(plan.host, settings, execute, environment);
67
+ if (!remote('hostname -I').trim().split(/\s+/u).includes(plan.nodeAddress)) {
68
+ throw new Error('Kiosk host identity differs from DSL target');
69
+ }
70
+ const results = [];
71
+ if (action !== 'reload') { results.push(audioResult(remote, plan, action, settings)); }
72
+ results.push(remote(`python3 - ${action === 'reload' ? 'reload' : 'check'} ${plan.debugPort} ${shellArgument(url)}`, readFileSync(browser, 'utf8')));
73
+ return results.join('\n');
74
+ }
@@ -0,0 +1,41 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import shellArgument from './shellArgument.js';
3
+
4
+ const assets = new Map([
5
+ ['watchdog.sh', './watchdog.sh'],
6
+ ['listen.mjs', './listen.mjs.txt'],
7
+ ['watchdog-liveness.sh', './watchdog-liveness.sh'],
8
+ ['watchdog-readiness.sh', './watchdog-readiness.sh'],
9
+ ['wait-x11.sh', './wait-x11.sh']
10
+ ]);
11
+
12
+ function asset(name) {
13
+ const filename = assets.get(name);
14
+ if (!filename) { throw new TypeError(`Unknown kiosk asset: ${name}`); }
15
+ return readFileSync(new URL(filename, import.meta.url), 'utf8');
16
+ }
17
+
18
+ function argument(value) {
19
+ if (typeof value !== 'string' || value.includes('\0')) { throw new TypeError('Invalid kiosk argument'); }
20
+ return /^[\w/:.,=+@-]+$/u.test(value) ? value : shellArgument(value);
21
+ }
22
+
23
+ function launch({ executable, args, urlEnvironment }) {
24
+ if (typeof executable !== 'string' || !executable.startsWith('/') || !Array.isArray(args)
25
+ || typeof urlEnvironment !== 'string' || !/^[A-Za-z_]\w*$/u.test(urlEnvironment)) {
26
+ throw new TypeError('Invalid kiosk executable declaration');
27
+ }
28
+ return `exec ${[executable, ...args].map(argument).join(' ')} "$${urlEnvironment}"\n`;
29
+ }
30
+
31
+ /** Materialize packaged kiosk scripts and a declared browser launch in Kubernetes objects. */
32
+ export default function renderKioskResources(value) {
33
+ if (Array.isArray(value)) { return value.map(renderKioskResources); }
34
+ if (value === null || typeof value !== 'object') { return value; }
35
+ const keys = Object.keys(value);
36
+ if (keys.length === 1 && keys[0] === 'kioskAsset') { return asset(value.kioskAsset); }
37
+ if (keys.length === 1 && keys[0] === 'kioskLaunch') { return launch(value.kioskLaunch); }
38
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => {
39
+ return [key, renderKioskResources(item)];
40
+ }));
41
+ }
@@ -0,0 +1,4 @@
1
+ /** Encode a single value as a literal argument for a POSIX shell. */
2
+ export default function shellArgument(value) {
3
+ return `'${value.replaceAll("'", "'\"'\"'")}'`;
4
+ }
@@ -0,0 +1 @@
1
+ for i in $(seq 1 300); do test -S "/tmp/.X11-unix/X0" && exit 0; sleep 2; done; echo "wait-x11: no socket /tmp/.X11-unix/X0 after $(( 300 * 2 ))s"; ls -la /tmp/.X11-unix 2>&1 || ls -la /tmp 2>&1 || true; exit 1
@@ -0,0 +1 @@
1
+ test -f /tmp/watchdog-ok && test $(($(date +%s) - $(stat -c %Y /tmp/watchdog-ok 2>/dev/null || echo 0))) -lt 165
@@ -0,0 +1 @@
1
+ test -f /tmp/watchdog-ok
@@ -0,0 +1,137 @@
1
+ #!/bin/sh
2
+ logts() {
3
+ date -Iseconds 2>/dev/null || date
4
+ }
5
+ try_kill() {
6
+ if [ "${WATCHDOG_KILL:-0}" != "1" ]; then
7
+ return
8
+ fi
9
+ if [ -z "${KIOSK_CHROMIUM_USER_DATA:-}" ]; then
10
+ return
11
+ fi
12
+ ts=$(logts)
13
+ pat="chromium.*--user-data-dir=${KIOSK_CHROMIUM_USER_DATA}"
14
+ for pid in $(pgrep -f "$pat" 2>/dev/null); do
15
+ echo "${ts} watchdog kill_TERM pid=${pid}" >&2
16
+ kill -TERM "$pid" 2>/dev/null || true
17
+ done
18
+ }
19
+ die_immediate() {
20
+ ts=$(logts)
21
+ echo "${ts} watchdog $1" >&2
22
+ try_kill
23
+ exit 1
24
+ }
25
+ WATCHDOG_INTERVAL="${WATCHDOG_INTERVAL:-30}"
26
+ WATCHDOG_TIMEOUT="${WATCHDOG_TIMEOUT:-5}"
27
+ WATCHDOG_STARTUP_MAX_WAIT="${WATCHDOG_STARTUP_MAX_WAIT:-120}"
28
+ WATCHDOG_UNHEALTHY_STREAK="${WATCHDOG_UNHEALTHY_STREAK:-3}"
29
+ CDP_PORT="${CDP_PORT:-9222}"
30
+ BASE="http://127.0.0.1:${CDP_PORT}"
31
+ LAST_REASON=""
32
+ tier2_url_has_origin() {
33
+ o=$1
34
+ if printf '%s' "${list}" | grep -qF "\"url\":\"${o}"; then
35
+ return 0
36
+ fi
37
+ if printf '%s' "${list}" | grep -qF "\"url\": \"${o}"; then
38
+ return 0
39
+ fi
40
+ return 1
41
+ }
42
+ wait_cdp_ready() {
43
+ step=2
44
+ elapsed=0
45
+ while [ "${elapsed}" -lt "${WATCHDOG_STARTUP_MAX_WAIT}" ]; do
46
+ if wget -qO- -T "${WATCHDOG_TIMEOUT}" "${BASE}/json/version" >/dev/null 2>&1; then
47
+ echo "$(logts) watchdog startup_cdp_ok elapsed=${elapsed}s" >&2
48
+ return 0
49
+ fi
50
+ sleep "${step}"
51
+ elapsed=$((elapsed + step))
52
+ done
53
+ echo "$(logts) watchdog startup_cdp_timeout wait=${WATCHDOG_STARTUP_MAX_WAIT}s" >&2
54
+ exit 1
55
+ }
56
+ one_check() {
57
+ LAST_REASON=""
58
+ list=$(wget -qO- -T "${WATCHDOG_TIMEOUT}" "${BASE}/json/list") || {
59
+ LAST_REASON=list_fetch_fail
60
+ return 1
61
+ }
62
+ case ${list} in
63
+ *chrome-error://chromewebdata/*)
64
+ LAST_REASON=tier1_chrome_error
65
+ return 2
66
+ ;;
67
+ *chrome://crash*)
68
+ LAST_REASON=tier1_chrome_crash
69
+ return 2
70
+ ;;
71
+ *chrome://kill*)
72
+ LAST_REASON=tier1_chrome_kill
73
+ return 2
74
+ ;;
75
+ esac
76
+ if [ -n "${KIOSK_PAGE_ORIGIN:-}" ]; then
77
+ case ${list} in
78
+ *'"type":"page"'*|*'"type": "page"'*) ;;
79
+ *)
80
+ LAST_REASON=tier2_no_page_target
81
+ return 1
82
+ ;;
83
+ esac
84
+ if tier2_url_has_origin "${KIOSK_PAGE_ORIGIN}"; then
85
+ :
86
+ elif [ -n "${KIOSK_PAGE_ORIGIN_ALT:-}" ] && tier2_url_has_origin "${KIOSK_PAGE_ORIGIN_ALT}"; then
87
+ :
88
+ else
89
+ LAST_REASON=tier2_hmi_origin_not_in_targets
90
+ return 1
91
+ fi
92
+ fi
93
+ ver=$(wget -qO- -T "${WATCHDOG_TIMEOUT}" "${BASE}/json/version") || {
94
+ LAST_REASON=cdp_version_fetch_fail
95
+ return 1
96
+ }
97
+ case ${ver} in
98
+ *'"Browser"'*) ;;
99
+ *)
100
+ LAST_REASON=cdp_version_no_browser_field
101
+ return 1
102
+ ;;
103
+ esac
104
+ case ${ver} in
105
+ *Chromium*|*Chrome*) ;;
106
+ *)
107
+ LAST_REASON=cdp_version_not_chromium
108
+ return 1
109
+ ;;
110
+ esac
111
+ return 0
112
+ }
113
+ wait_cdp_ready
114
+ streak=0
115
+ while true; do
116
+ one_check
117
+ rc=$?
118
+ if [ "${rc}" -eq 0 ]; then
119
+ streak=0
120
+ ts=$(logts)
121
+ echo "${ts} watchdog ok list_tier1_tier2 version_ok" >&2
122
+ touch /tmp/watchdog-ok
123
+ sleep "${WATCHDOG_INTERVAL}"
124
+ elif [ "${rc}" -eq 2 ]; then
125
+ die_immediate "reason=${LAST_REASON}"
126
+ else
127
+ streak=$((streak + 1))
128
+ ts=$(logts)
129
+ echo "${ts} watchdog soft_fail streak=${streak} reason=${LAST_REASON}" >&2
130
+ if [ "${streak}" -ge "${WATCHDOG_UNHEALTHY_STREAK}" ]; then
131
+ echo "${ts} watchdog streak_exceeded exiting" >&2
132
+ try_kill
133
+ exit 1
134
+ fi
135
+ sleep "${WATCHDOG_INTERVAL}"
136
+ fi
137
+ done
@@ -0,0 +1,17 @@
1
+ import { createServer } from 'node:http';
2
+ import periodicReconciliation from '../../application/control/periodicReconciliation.js';
3
+
4
+ /** Serve a control API while polling its independent reconciliation. */
5
+ export default function serveReconciliation({ run, respond, port, host, intervalMs = 5000, onError }) {
6
+ const server = createServer(respond);
7
+ server.listen(port, host);
8
+ const loop = periodicReconciliation(run, { intervalMs, onError });
9
+ let stopping;
10
+ return {
11
+ address() { return server.address(); },
12
+ stop() {
13
+ stopping ??= Promise.all([loop.stop(), new Promise((resolve) => { server.close(resolve); })]);
14
+ return stopping;
15
+ }
16
+ };
17
+ }
@@ -0,0 +1,123 @@
1
+ import paths from '../../application/deploy/paths.js';
2
+
3
+ function record(value, context) {
4
+ if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new TypeError(`HMI ${context} must be an object`); }
5
+ return value;
6
+ }
7
+
8
+ function text(value, context) {
9
+ if (typeof value !== 'string' || !value.trim()) { throw new TypeError(`HMI ${context} must be a nonempty string`); }
10
+ return value;
11
+ }
12
+
13
+ function credentials(value) {
14
+ Object.entries(value).forEach(([key, entry]) => {
15
+ if (/password|secret|token|credential|command/iu.test(key)) { throw new TypeError(`HMI catalog cannot embed ${key}`); }
16
+ if (entry && typeof entry === 'object') { credentials(entry); }
17
+ });
18
+ }
19
+
20
+ function moduleFor(servers, id) {
21
+ const server = servers.find((entry) => { return entry.id === id; });
22
+ const module = server?.modules?.mdmesh;
23
+ if (!module || module.enabled !== true) { throw new TypeError(`HMI server ${id} requires enabled mdmesh module`); }
24
+ if (typeof module.namespace !== 'string' || module.namespace.length > 63
25
+ || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(module.namespace)) {
26
+ throw new TypeError(`HMI server ${id} requires a DNS namespace`);
27
+ }
28
+ return module;
29
+ }
30
+
31
+ function profilesFor(profiles) {
32
+ Object.entries(record(profiles, 'profiles')).forEach(([id, profile]) => {
33
+ record(profile, `profile ${id}`);
34
+ if (!['landscape', 'portrait'].includes(profile.orientation)) { throw new TypeError(`HMI profile ${id} has invalid orientation`); }
35
+ ['kiosk', 'keepScreenOnWhileCharging', 'alarmSound'].forEach((key) => {
36
+ if (typeof profile[key] !== 'boolean') { throw new TypeError(`HMI profile ${id} requires boolean ${key}`); }
37
+ });
38
+ });
39
+ return profiles;
40
+ }
41
+
42
+ function unique(value, seen, context) {
43
+ text(value, context);
44
+ if (seen.has(value)) { throw new TypeError(`HMI duplicate ${context} ${value}`); }
45
+ seen.add(value);
46
+ }
47
+
48
+ function artifactFor(apk, { packageName, downloadPrefix }) {
49
+ if (apk.package !== packageName || !/^\d+\.\d+\.\d+$/u.test(apk.version)
50
+ || !Number.isSafeInteger(apk.versionCode) || apk.versionCode < 1 || !/^[a-f0-9]{64}$/u.test(apk.sha256)) { throw new TypeError('HMI APK requires a package, version and SHA-256'); }
51
+ const url = new URL(apk.url);
52
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash
53
+ || (!url.pathname.startsWith(downloadPrefix) || !/^[a-z0-9-]+\.apk$/u.test(url.pathname.slice(downloadPrefix.length)))) { throw new TypeError('HMI APK requires its dedicated HTTPS download path'); }
54
+ if (apk.retire && (!Array.isArray(apk.retire) || apk.retire.some((pkg) => { return typeof pkg !== 'string' || !pkg.startsWith(`${packageName}.`) || !/^[a-z][a-z0-9_]*$/u.test(pkg.slice(packageName.length + 1)); }))) {
55
+ throw new TypeError('HMI APK retire list requires former machine packages');
56
+ }
57
+ }
58
+
59
+ function applicationFor(device, policy) {
60
+ const app = device.application;
61
+ if (!Object.hasOwn(app, 'autoStart')) { return; }
62
+ if (typeof app.autoStart !== 'boolean') { throw new TypeError('HMI autoStart must be boolean'); }
63
+ if (!app.autoStart) { return; }
64
+ const href = new URL(policy.address(app.href));
65
+ if (href.searchParams.get('machine') !== device.machine) { throw new TypeError('HMI autoStart requires a matching machine URL'); }
66
+ artifactFor(record(app.apk, 'application APK'), policy);
67
+ }
68
+
69
+ function shared(devices) {
70
+ const apks = devices.filter((device) => { return device.application.autoStart; }).map((device) => { return device.application.apk; });
71
+ if (apks.some((apk) => { return ['package', 'version', 'versionCode', 'url', 'sha256'].some((key) => { return apk[key] !== apks[0][key]; }); })) {
72
+ throw new TypeError('HMI autoStart devices must share one APK');
73
+ }
74
+ }
75
+
76
+ function binding(device, document, machines, profiles, policy) {
77
+ record(device, 'device');
78
+ record(device.orchestrator, `device ${device.id} orchestrator`);
79
+ record(device.application, `device ${device.id} application`);
80
+ if (device.orchestrator.module !== 'mdmesh') { throw new TypeError(`HMI device ${device.id} requires mdmesh orchestrator`); }
81
+ moduleFor(document.servers, device.orchestrator.server);
82
+ if (!document.servers.some((server) => { return server.id === device.application.server; })) {
83
+ throw new TypeError(`HMI device ${device.id} references unknown application server ${device.application.server}`);
84
+ }
85
+ applicationFor(device, policy);
86
+ if (device.application.autoStart && !profiles[device.profile]?.kiosk) { throw new TypeError('Automatic HMI requires a kiosk profile'); }
87
+ if (!Object.hasOwn(profiles, device.profile)) { throw new TypeError(`HMI device ${device.id} references unknown profile ${device.profile}`); }
88
+ if (!machines.has(device.machine) || device.application.machine !== device.machine) {
89
+ throw new TypeError(`HMI device ${device.id} requires a matching namespace machine ${device.machine}`);
90
+ }
91
+ }
92
+
93
+ function devicesFor(catalog) {
94
+ if (!Array.isArray(catalog.devices)) { throw new TypeError('HMI devices must be an array'); }
95
+ if (catalog.apk === undefined) { return catalog.devices; }
96
+ const apk = record(catalog.apk, 'shared APK');
97
+ return catalog.devices.map((device) => {
98
+ if (device?.application?.autoStart !== true) { return device; }
99
+ const app = device.application;
100
+ const override = app.apk === undefined ? {} : record(app.apk, 'application APK');
101
+ return { ...device, application: { ...app, apk: { ...apk, ...override } } };
102
+ });
103
+ }
104
+
105
+ /** Validate the complete declarative tablet catalog before selecting one orchestrator server. */
106
+ export default function hmiPlan(serverId, document, policy) {
107
+ const catalog = record(document.hmi, 'catalog');
108
+ credentials(catalog);
109
+ const profiles = profilesFor(catalog.profiles);
110
+ const module = moduleFor(document.servers || [], serverId);
111
+ const machines = new Set(paths(document).filter((name) => { return name.split('/').length === 3; }).map((name) => { return name.split('/').at(-1); }));
112
+ const identifiers = new Set();
113
+ const references = new Set();
114
+ const devices = devicesFor(catalog);
115
+ devices.forEach((device) => {
116
+ binding(device, document, machines, profiles, policy);
117
+ unique(device.id, identifiers, 'device id');
118
+ if (Object.hasOwn(device, 'deviceRef')) { unique(device.deviceRef, references, 'device reference'); }
119
+ });
120
+ shared(devices);
121
+ return { server: serverId, namespace: module.namespace, profiles,
122
+ devices: devices.filter((device) => { return device.orchestrator.server === serverId; }) };
123
+ }
@@ -5,3 +5,4 @@ export { default as hmiMonitor, metrics } from './hmiMonitor.js';
5
5
  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
+ export { default as hmiPlan } from './hmiPlan.js';