@yarkivaev/scada 2.15.0 → 2.16.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.
- package/db/bootstrap/apply-hba.sh +11 -0
- package/db/bootstrap/entrypoint.sh +6 -0
- package/db/bootstrap/ownership.sql +18 -0
- package/db/bootstrap/zz-auth.sh +3 -0
- package/index.js +1 -0
- package/package.json +3 -2
- package/src/application/control/controller.js +2 -9
- package/src/application/control/periodicReconciliation.js +19 -0
- package/src/application/control/publishControlCatalog.js +25 -0
- package/src/application/control/reconcileStoredChoice.js +10 -0
- package/src/application/deploy/controlPlan.js +93 -0
- package/src/application/deploy/deploymentCommands.js +29 -0
- package/src/application/deploy/deploymentPlan.js +84 -0
- package/src/application/deploy/readDocumentFile.js +28 -0
- package/src/application/deploy/releases.js +14 -10
- package/src/infrastructure/deploy/applyHelmResources.js +17 -0
- package/src/infrastructure/deploy/bootstrapKubeStorage.js +28 -0
- package/src/infrastructure/deploy/deploymentChecks.js +68 -0
- package/src/infrastructure/deploy/deploymentPatch.js +36 -0
- package/src/infrastructure/deploy/executeChartDeployment.js +19 -0
- package/src/infrastructure/deploy/executeRelease.js +6 -2
- package/src/infrastructure/deploy/executeStagedDeployment.js +31 -0
- package/src/infrastructure/deploy/index.js +29 -0
- package/src/infrastructure/deploy/postgresBootstrap.js +79 -0
- package/src/infrastructure/deploy/reconcileDeployments.js +47 -0
- package/src/infrastructure/deploy/requestFromWorkload.js +30 -0
- package/src/infrastructure/deploy/verifyRuntimeCapabilities.js +34 -0
- package/src/infrastructure/management/kiosk/kiosk-browser.py +91 -0
- package/src/infrastructure/management/kiosk/kiosk-volume.sh +105 -0
- package/src/infrastructure/management/kiosk/listen.mjs.txt +14 -0
- package/src/infrastructure/management/kiosk/operateKiosk.js +74 -0
- package/src/infrastructure/management/kiosk/renderKioskResources.js +41 -0
- package/src/infrastructure/management/kiosk/shellArgument.js +4 -0
- package/src/infrastructure/management/kiosk/wait-x11.sh +1 -0
- package/src/infrastructure/management/kiosk/watchdog-liveness.sh +1 -0
- package/src/infrastructure/management/kiosk/watchdog-readiness.sh +1 -0
- package/src/infrastructure/management/kiosk/watchdog.sh +137 -0
- package/src/infrastructure/management/serveReconciliation.js +17 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import applyWhenChanged from './applyWhenChanged.js';
|
|
3
|
+
import { requireReleaseAction } from './executeRelease.js';
|
|
4
|
+
import executeStages from './executeStages.js';
|
|
5
|
+
|
|
6
|
+
function selected(plan, omit) {
|
|
7
|
+
if (omit.length === 0) { return plan; }
|
|
8
|
+
return { ...plan, stages: plan.stages.filter(({ id }) => { return !omit.includes(id); }) };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function stagePlans(plan, hooks) {
|
|
12
|
+
return plan.stages.map((stage) => {
|
|
13
|
+
return { ...stage, ...(Object.hasOwn(hooks, stage.id) ? hooks[stage.id] : {}) };
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Execute declared stages with guarded preparation and stage-specific application ports. */
|
|
18
|
+
export default function executeStagedDeployment(profile, execute = execFileSync) {
|
|
19
|
+
const { action = 'render', plan, prepare, omitStages = [], validateMutation, preflight, stageHooks, afterApply,
|
|
20
|
+
actions = {}, disabledActions = [] } = profile;
|
|
21
|
+
if (disabledActions.includes(action)) { throw new Error(`${plan.context} deployment disabled: target is offline`); }
|
|
22
|
+
const scoped = selected(plan, omitStages);
|
|
23
|
+
if (Object.hasOwn(actions, action)) { return actions[action](scoped, execute); }
|
|
24
|
+
requireReleaseAction(action);
|
|
25
|
+
const mutate = ['apply', 'adopt'].includes(action);
|
|
26
|
+
if (mutate) { validateMutation?.(scoped); }
|
|
27
|
+
const prepared = prepare ? selected(prepare(action, scoped), omitStages) : scoped;
|
|
28
|
+
if (action !== 'render') { preflight?.(prepared, action, mutate); }
|
|
29
|
+
const output = executeStages(stagePlans(prepared, stageHooks?.(prepared) ?? {}), action, applyWhenChanged(execute)).join('\n');
|
|
30
|
+
return mutate && afterApply ? `${output}\n${afterApply(prepared, execute)}` : output;
|
|
31
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export { collectorDeployment, deploymentContext, peerNodePort, retiredDeployments, stageFor } from '../../application/deploy/deploymentPlan.js';
|
|
2
|
+
export { collectorControlDeployment, deploymentResources, etcdMembership, versionedControlCatalog } from '../../application/deploy/controlPlan.js';
|
|
3
|
+
export { default as executeStagedDeployment } from './executeStagedDeployment.js';
|
|
4
|
+
export { default as executeChartDeployment } from './executeChartDeployment.js';
|
|
5
|
+
export { requireWorkloadEnvironment, validateDeploymentEvidence, verifyPostgresReadiness, waitForJob } from './deploymentChecks.js';
|
|
6
|
+
export { default as publishControlCatalog } from '../../application/control/publishControlCatalog.js';
|
|
7
|
+
export { default as deploymentPatch } from './deploymentPatch.js';
|
|
8
|
+
export { default as reconcileDeployments } from './reconcileDeployments.js';
|
|
9
|
+
export { default as serveReconciliation } from '../management/serveReconciliation.js';
|
|
10
|
+
export { default as reconcileStoredChoice } from '../../application/control/reconcileStoredChoice.js';
|
|
11
|
+
export { default as operateKiosk } from '../management/kiosk/operateKiosk.js';
|
|
12
|
+
export { default as bootstrapKubeStorage } from './bootstrapKubeStorage.js';
|
|
13
|
+
export { default as verifyRuntimeCapabilities } from './verifyRuntimeCapabilities.js';
|
|
14
|
+
export { postgresBootstrapObjects, postgresRuntimeRoleJob } from './postgresBootstrap.js';
|
|
15
|
+
export { default as deploymentCommands } from '../../application/deploy/deploymentCommands.js';
|
|
16
|
+
export { default as readDocumentFile, selectDeploymentPhase } from '../../application/deploy/readDocumentFile.js';
|
|
17
|
+
export { default as applyHelmResources } from './applyHelmResources.js';
|
|
18
|
+
export { default as requestFromWorkload } from './requestFromWorkload.js';
|
|
19
|
+
export { default as renderKioskResources } from '../management/kiosk/renderKioskResources.js';
|
|
20
|
+
export { default as freezeDeploymentDocument } from '../../application/deploy/frozen.js';
|
|
21
|
+
export { default as readDocument } from '../../application/deploy/readDocument.js';
|
|
22
|
+
export { default as expand } from '../../application/deploy/expand.js';
|
|
23
|
+
export { deploymentKube, readKube, verifyKubeNode, preserveKubeRestart } from './deploymentKube.js';
|
|
24
|
+
export { default as executeRelease } from './executeRelease.js';
|
|
25
|
+
export { default as verifyCollectorCoverage } from './verifyCollectorCoverage.js';
|
|
26
|
+
export { default as verifyPeerBrokerPerimeter } from './verifyPeerBrokerPerimeter.js';
|
|
27
|
+
export { default as preflightKubeStorage } from './preflightKubeStorage.js';
|
|
28
|
+
export { default as applyWhenChanged } from './applyWhenChanged.js';
|
|
29
|
+
export { default as prepareKubePrerequisites } from './prepareKubePrerequisites.js';
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { isIP } from 'node:net';
|
|
4
|
+
|
|
5
|
+
const databaseAssets = new URL('../../../db/', import.meta.url);
|
|
6
|
+
|
|
7
|
+
function asset(name) {
|
|
8
|
+
return readFileSync(new URL(name, databaseAssets), 'utf8');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function authData(podCidrs) {
|
|
12
|
+
const allowed = podCidrs.map((cidr) => {
|
|
13
|
+
const [address, bits, extra] = cidr.split('/');
|
|
14
|
+
const version = isIP(address);
|
|
15
|
+
const prefix = Number(bits);
|
|
16
|
+
if (extra !== undefined || !version || !Number.isInteger(prefix) || prefix < 1 || prefix > (version === 4 ? 32 : 128)) {
|
|
17
|
+
throw new Error('Invalid target pod CIDR');
|
|
18
|
+
}
|
|
19
|
+
return `host all all ${cidr} scram-sha-256`;
|
|
20
|
+
});
|
|
21
|
+
return {
|
|
22
|
+
'pg_hba.conf.fragment': ['# DSL target pod CIDRs', ...allowed, 'host all all 0.0.0.0/0 reject', 'host all all ::/0 reject', ''].join('\n'),
|
|
23
|
+
'entrypoint.sh': asset('bootstrap/entrypoint.sh'),
|
|
24
|
+
'apply-hba.sh': asset('bootstrap/apply-hba.sh')
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function schemaData(ownerRole, runtimeRole) {
|
|
29
|
+
const roles = [ownerRole, runtimeRole];
|
|
30
|
+
if (ownerRole === runtimeRole || roles.some((role) => { return typeof role !== 'string' || !/^[a-z_][a-z0-9_]{0,62}$/u.test(role); })) {
|
|
31
|
+
throw new TypeError('Invalid PostgreSQL bootstrap roles');
|
|
32
|
+
}
|
|
33
|
+
const ownership = asset('bootstrap/ownership.sql')
|
|
34
|
+
.replaceAll('@RUNTIME_ROLE@', runtimeRole).replaceAll('@OWNER_ROLE@', ownerRole);
|
|
35
|
+
const grants = asset('migrations/C0002__central_revoke_delete.sql').replaceAll('supervisor_sink', runtimeRole);
|
|
36
|
+
const sql = [
|
|
37
|
+
asset('migrations/V0001__baseline.sql'), asset('migrations/V0002__sink_extension_tables.sql'),
|
|
38
|
+
ownership, grants
|
|
39
|
+
].map((part) => { return part.trimEnd(); }).join('\n\n');
|
|
40
|
+
return { 'schema.sql': `${sql}\n`, 'zz-auth.sh': asset('bootstrap/zz-auth.sh') };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Render PostgreSQL bootstrap ConfigMaps using an installation's names and CIDRs. */
|
|
44
|
+
export function postgresBootstrapObjects({ namespace, authConfigMap, schemaConfigMap, ownerRole, runtimeRole }, podCidrs = []) {
|
|
45
|
+
return [
|
|
46
|
+
{ apiVersion: 'v1', kind: 'ConfigMap', metadata: { name: authConfigMap, namespace }, data: authData(podCidrs) },
|
|
47
|
+
{ apiVersion: 'v1', kind: 'ConfigMap', metadata: { name: schemaConfigMap, namespace }, data: schemaData(ownerRole, runtimeRole) }
|
|
48
|
+
];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function roleContainer({ image, command, credentials, resources }) {
|
|
52
|
+
return {
|
|
53
|
+
name: 'runtime-role', image, command,
|
|
54
|
+
env: ['POSTGRES_URL', 'POSTGRES_ADMIN_URL'].map((key) => {
|
|
55
|
+
return { name: key, valueFrom: { secretKeyRef: { name: credentials, key } } };
|
|
56
|
+
}),
|
|
57
|
+
resources: resources ?? { requests: { cpu: '10m', memory: '64Mi' }, limits: { cpu: '250m', memory: '256Mi' } },
|
|
58
|
+
securityContext: { allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: { drop: ['ALL'] } }
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Bind the runtime-role setup job to a selected application image and Secret. */
|
|
63
|
+
export function postgresRuntimeRoleJob(settings) {
|
|
64
|
+
const { namespace, namePrefix, image, pullSecret } = settings;
|
|
65
|
+
const revision = createHash('sha256').update(image).digest('hex').slice(0, 12);
|
|
66
|
+
return {
|
|
67
|
+
apiVersion: 'batch/v1', kind: 'Job', metadata: { name: `${namePrefix}-${revision}`, namespace },
|
|
68
|
+
spec: {
|
|
69
|
+
backoffLimit: 4, activeDeadlineSeconds: 300,
|
|
70
|
+
template: {
|
|
71
|
+
spec: {
|
|
72
|
+
restartPolicy: 'OnFailure', automountServiceAccountToken: false,
|
|
73
|
+
imagePullSecrets: [{ name: pullSecret }], securityContext: { runAsNonRoot: true, runAsUser: 1000 },
|
|
74
|
+
containers: [roleContainer(settings)]
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import kubeServiceAccount from '../management/kubeServiceAccount.js';
|
|
2
|
+
|
|
3
|
+
const patchJson = 'application/json-patch+json';
|
|
4
|
+
const dnsName = /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u;
|
|
5
|
+
|
|
6
|
+
function validName(name) {
|
|
7
|
+
if (typeof name !== 'string' || !dnsName.test(name)) { throw new TypeError('Invalid Kubernetes deployment target'); }
|
|
8
|
+
return name;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function guards(body) {
|
|
12
|
+
const version = body.metadata?.resourceVersion;
|
|
13
|
+
if (typeof version !== 'string' || !version) { throw new Error('Missing Kubernetes resource version'); }
|
|
14
|
+
return [{ op: 'test', path: '/metadata/resourceVersion', value: version }];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function concurrentEdit({ status, body }) {
|
|
18
|
+
return status === 409 || (status === 422 && /test failed/u.test(body));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Recompute a bounded JSON patch from the live Deployment before each mutation. */
|
|
22
|
+
export default function reconcileDeployments({
|
|
23
|
+
namespace, exchange = kubeServiceAccount('https://kubernetes.default.svc'), maxChanges = 5, onPatch
|
|
24
|
+
}) {
|
|
25
|
+
const prefix = `/apis/apps/v1/namespaces/${validName(namespace)}/deployments`;
|
|
26
|
+
function resource(name) { return `${prefix}/${validName(name)}`; }
|
|
27
|
+
async function get(name) {
|
|
28
|
+
const result = await exchange('GET', resource(name));
|
|
29
|
+
if (result.status === 404) { return null; }
|
|
30
|
+
if (result.status !== 200) { throw new Error(`Kubernetes read failed for ${name} with HTTP ${result.status}`); }
|
|
31
|
+
return JSON.parse(result.body);
|
|
32
|
+
}
|
|
33
|
+
async function apply(step, operation) {
|
|
34
|
+
for (let i = 0; i < maxChanges; i += 1) {
|
|
35
|
+
// Read after each attempted patch to incorporate concurrent changes.
|
|
36
|
+
// eslint-disable-next-line no-await-in-loop
|
|
37
|
+
const body = await get(step.name);
|
|
38
|
+
const patch = body && operation(body, step);
|
|
39
|
+
if (!patch) { return; }
|
|
40
|
+
// eslint-disable-next-line no-await-in-loop
|
|
41
|
+
const result = await exchange('PATCH', resource(step.name), [...guards(body), patch], patchJson);
|
|
42
|
+
if (result.status >= 200 && result.status < 300) { onPatch?.(step, patch); }
|
|
43
|
+
else if (!concurrentEdit(result)) { throw new Error(`Kubernetes patch failed for ${step.name} with HTTP ${result.status}`); }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return { get, apply };
|
|
47
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const requestProgram = `
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
const { url, method, tokenEnv, configuration, body, requireApplied } = JSON.parse(readFileSync(0, 'utf8'));
|
|
4
|
+
if (configuration) {
|
|
5
|
+
const file = process.env[configuration.pathEnv] || configuration.defaultPath;
|
|
6
|
+
const deployed = JSON.parse(readFileSync(file, 'utf8'));
|
|
7
|
+
if (JSON.stringify(deployed) !== JSON.stringify(configuration.expected)) {
|
|
8
|
+
throw new Error(configuration.mismatch);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
const headers = { 'content-type': 'application/json', authorization: 'Bearer ' + process.env[tokenEnv] };
|
|
12
|
+
const response = await fetch(url, { method, headers, redirect: 'error', ...(body !== undefined && { body: JSON.stringify(body) }) });
|
|
13
|
+
const result = await response.text();
|
|
14
|
+
if (!response.ok || (requireApplied && JSON.parse(result).applied !== true)) {
|
|
15
|
+
process.stderr.write(result + '\\n');
|
|
16
|
+
process.exitCode = 1;
|
|
17
|
+
} else {
|
|
18
|
+
process.stdout.write(result + '\\n');
|
|
19
|
+
}
|
|
20
|
+
`;
|
|
21
|
+
|
|
22
|
+
/** Send a protected loopback request inside a running workload with optional config fencing. */
|
|
23
|
+
export default function requestFromWorkload(kube, { workload, url, method, tokenEnv, configuration, body, requireApplied }) {
|
|
24
|
+
const parsed = new URL(url);
|
|
25
|
+
if (parsed.protocol !== 'http:' || parsed.hostname !== '127.0.0.1' || parsed.username || parsed.password) {
|
|
26
|
+
throw new TypeError('Workload request requires an HTTP loopback endpoint');
|
|
27
|
+
}
|
|
28
|
+
const input = JSON.stringify({ url, method, tokenEnv, configuration, body, requireApplied });
|
|
29
|
+
return kube(['exec', '-i', workload, '--', 'node', '--input-type=module', '-e', requestProgram], input);
|
|
30
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
function capabilities({ image, role, entrypoint, args = [] }, subject, execute) {
|
|
4
|
+
let result;
|
|
5
|
+
try {
|
|
6
|
+
const options = { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 120000 };
|
|
7
|
+
const output = execute('docker', ['run', '--rm', '--read-only', '--network=none', '--tmpfs', '/tmp', '--entrypoint', entrypoint, image, ...args], options);
|
|
8
|
+
result = JSON.parse(String(output));
|
|
9
|
+
} catch {
|
|
10
|
+
throw new Error(`Unable to verify ${subject} ${role} candidate`);
|
|
11
|
+
}
|
|
12
|
+
return result;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Probe isolated runtime images and require common capabilities declared by the profile. */
|
|
16
|
+
export default function verifyRuntimeCapabilities({ candidates, required, match, subject = 'runtime',
|
|
17
|
+
mismatch = 'Runtime candidates must support the same protocol' }, execute = execFileSync) {
|
|
18
|
+
const results = new Map();
|
|
19
|
+
for (const candidate of candidates) {
|
|
20
|
+
const result = capabilities(candidate, subject, execute);
|
|
21
|
+
if (result?.role !== candidate.role || !Array.isArray(result.historyProtocols)
|
|
22
|
+
|| required.some((protocol) => { return !result.historyProtocols.includes(protocol); })) {
|
|
23
|
+
throw new Error(`Incompatible ${subject} ${candidate.role} candidate`);
|
|
24
|
+
}
|
|
25
|
+
results.set(candidate.role, result.historyProtocols);
|
|
26
|
+
}
|
|
27
|
+
if (match) {
|
|
28
|
+
const preferred = match.roles.map((role) => {
|
|
29
|
+
if (!results.has(role)) { throw new Error(`Missing runtime candidate role ${role}`); }
|
|
30
|
+
return match.preference.find((protocol) => { return results.get(role).includes(protocol); });
|
|
31
|
+
});
|
|
32
|
+
if (new Set(preferred).size !== 1) { throw new Error(mismatch); }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -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 @@
|
|
|
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
|