iobroker.eos-admin 9.0.20 → 9.0.21

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 (84) hide show
  1. package/NEXOWATT_EOS_BUILD_INFO.json +3 -3
  2. package/README.md +5 -3
  3. package/adminWww/.vite/manifest.json +39 -39
  4. package/adminWww/NEXOWATT_EOS_FRONTEND_MANIFEST.json +107 -107
  5. package/adminWww/assets/{AdapterUpdateDialog-CRD3XVom.js → AdapterUpdateDialog-Dxl_b7Op.js} +1 -1
  6. package/adminWww/assets/{Adapters-Cuf0X0CU.js → Adapters-CVKKhXmI.js} +1 -1
  7. package/adminWww/assets/{ConfigManager-B8ycQt1C.js → ConfigManager-Bf6nTAkL.js} +1 -1
  8. package/adminWww/assets/{Enums-CctVCgZX.js → Enums-CJHVJY7t.js} +1 -1
  9. package/adminWww/assets/{Fields-onm4DfoO.js → Fields-DWHbZKvm.js} +1 -1
  10. package/adminWww/assets/{Files-OLP3Rwc7.js → Files-a6owMTXA.js} +1 -1
  11. package/adminWww/assets/{Hosts-C31oqMcW.js → Hosts-LtEMeXpV.js} +1 -1
  12. package/adminWww/assets/{Instances-DFdvJ9pa.js → Instances-DhChziA1.js} +1 -1
  13. package/adminWww/assets/{Intro-DvsFJxU0.js → Intro-Cyq9gVDC.js} +1 -1
  14. package/adminWww/assets/{Logs-Zqg2Bqv6.js → Logs-wcramXsg.js} +1 -1
  15. package/adminWww/assets/{Objects-CpWZp6yp.js → Objects-DINVHd_e.js} +1 -1
  16. package/adminWww/assets/{Overview-BsKUo298.js → Overview-DK4R41zR.js} +1 -1
  17. package/adminWww/assets/{State-D_xwlhhb.js → State-DcEACXzL.js} +1 -1
  18. package/adminWww/assets/{UsedResources-C79N6yZx.js → UsedResources-C1LcM0Rb.js} +1 -1
  19. package/adminWww/assets/{Users-WgC0O8P0.js → Users-DvDdSyDY.js} +1 -1
  20. package/adminWww/assets/{bootstrap-BcfBoIoa.js → bootstrap-Dbj_GbnP.js} +3 -3
  21. package/adminWww/assets/{hostInit-B7bBV7cH.js → hostInit-BNFIx0-f.js} +1 -1
  22. package/adminWww/assets/{icons-material-D1JYmRTj.js → icons-material-DVbdXNgr.js} +1 -1
  23. package/adminWww/assets/{index-DbiuoDjo.js → index-CoKP1NSA.js} +2 -2
  24. package/adminWww/assets/{installSVGRenderer-BAY-Pzp-.js → installSVGRenderer-CMvku1F1.js} +1 -1
  25. package/adminWww/assets/{mf-entry-bootstrap-0-33384c20.js → mf-entry-bootstrap-0-ac330bce.js} +2 -2
  26. package/adminWww/index.html +23 -23
  27. package/adminWww/mf-manifest.json +1 -1
  28. package/adminWww/mf-stats.json +1 -1
  29. package/adminWww/remoteEntry-eos-9.0.21.js +12 -0
  30. package/adminWww/remoteEntry.js +1 -1
  31. package/build/lib/eosCustomerUpdateHttp.js +203 -0
  32. package/build/lib/eosCustomerUpdateHttp.js.map +1 -0
  33. package/build/lib/eosCustomerUpdateTransport.js +472 -0
  34. package/build/lib/eosCustomerUpdateTransport.js.map +1 -0
  35. package/build/lib/eosCustomerUpdateWorker.js +567 -0
  36. package/build/lib/eosCustomerUpdateWorker.js.map +1 -0
  37. package/build/lib/eosCustomerUpdates.js +631 -0
  38. package/build/lib/eosCustomerUpdates.js.map +1 -0
  39. package/build/lib/eosModuleConfigStore.js +12 -1
  40. package/build/lib/eosModuleConfigStore.js.map +1 -1
  41. package/build/lib/eosModuleHost.js +41 -26
  42. package/build/lib/eosModuleHost.js.map +1 -1
  43. package/build/lib/eosModuleHttp.js +8 -2
  44. package/build/lib/eosModuleHttp.js.map +1 -1
  45. package/build/lib/eosUpdateSnapshot.js +290 -0
  46. package/build/lib/eosUpdateSnapshot.js.map +1 -0
  47. package/build/lib/eosUploadGuard.js +124 -81
  48. package/build/lib/eosUploadGuard.js.map +1 -1
  49. package/build/lib/web.js +80 -0
  50. package/build/lib/web.js.map +1 -1
  51. package/io-package.json +8 -8
  52. package/modules/backup/admin/index.js +4 -1
  53. package/modules/devices/admin/host-bridge.js +5 -1
  54. package/modules/devices/lib/deviceRuntime.js +27 -4
  55. package/modules/devices/lib/drivers/mqtt.js +204 -82
  56. package/modules/devices/lib/drivers/mqttPendingOperations.js +119 -0
  57. package/modules/devices/test/mqttCommandLifecycle.test.js +255 -0
  58. package/modules/devices/test/mqttResourceBounds.test.js +98 -0
  59. package/modules/devices/test/mqttRuntimeSession.test.js +109 -0
  60. package/modules/devices/tsconfig.mqtt-lifecycle.json +20 -0
  61. package/modules/eebus/admin/index.js +6 -3
  62. package/package.json +4 -4
  63. package/release-manifests/unified/build-environment.cdx.json +6 -6
  64. package/release-manifests/unified/files.json +363 -95
  65. package/release-manifests/unified/frontend.cdx.json +6 -6
  66. package/release-manifests/unified/installer.cdx.json +6 -6
  67. package/release-manifests/unified/obsolete-admin-assets.json +66 -0
  68. package/release-manifests/unified/runtime.cdx.json +25 -25
  69. package/release-manifests/unified/validation.json +15 -15
  70. package/tools/eos-release-manifest.cjs +3 -3
  71. package/ui/docs/security/eslint-reviewed-findings.json +83 -27
  72. package/ui/ems/engine.js +14 -3
  73. package/ui/ems/modules/tariff-provider.js +34 -10
  74. package/ui/ems/services/tariff-provider-registry.js +18 -8
  75. package/ui/io-package.json +1 -1
  76. package/ui/main.js +65 -34
  77. package/ui/package.json +1 -1
  78. package/ui/www/app.js +3 -2
  79. package/ui/www/eos-updates.css +15 -0
  80. package/ui/www/eos-updates.js +351 -0
  81. package/ui/www/index.html +2 -0
  82. package/ui/www/manifest.webmanifest +3 -3
  83. package/ui/www/settings.html +34 -0
  84. package/adminWww/remoteEntry-eos-9.0.20.js +0 -12
@@ -0,0 +1,631 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EosCustomerUpdates = void 0;
7
+ exports.preservesUpdateConfiguration = preservesUpdateConfiguration;
8
+ /**
9
+ * NexoWatt Quellcode-Erklärung (DE)
10
+ * Aufgabe: Bietet angemeldeten EOS-Kunden einen ausschließlich auf EOS begrenzten, ausdrücklich gestarteten Updateablauf.
11
+ * Daten und Wirkung: Prüft die npm-Version, Registry-Signatur und Paketbytes, sichert die eigene Konfiguration verschlüsselt und startet einen festen Wartungsarbeiter. Globale Konten, Repositories und fremde Adapter bleiben unberührt.
12
+ * Bei Änderungen: Rechte am letzten Wirkungspunkt, Neustart-/Abbruchfälle, private Dateien und Konfigurationserhalt mit den HTTP- und Arbeitertests gemeinsam prüfen.
13
+ */
14
+ const node_crypto_1 = require("node:crypto");
15
+ const node_fs_1 = require("node:fs");
16
+ const promises_1 = require("node:fs/promises");
17
+ const node_path_1 = require("node:path");
18
+ const node_child_process_1 = require("node:child_process");
19
+ const node_perf_hooks_1 = require("node:perf_hooks");
20
+ const semver_1 = __importDefault(require("semver"));
21
+ const eosCustomerUpdateTransport_1 = require("./eosCustomerUpdateTransport");
22
+ const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
23
+ const MAX_SNAPSHOT_BYTES = 8 * 1024 * 1024;
24
+ const CACHE_MS = 6 * 60 * 60 * 1000;
25
+ const CHECK_COOLDOWN_MS = 60000;
26
+ const PLAN_MS = 10 * 60 * 1000;
27
+ const hash = (value) => (0, node_crypto_1.createHash)('sha256').update(value).digest('hex');
28
+ const safeReason = (error) => error instanceof Error && /^EOS_UPDATE_[A-Z_]{1,64}$/.test(error.message) ? error.message : 'EOS_UPDATE_FAILED';
29
+ /** Existing configured values must survive; a new release may add previously absent defaults. */
30
+ function preservesUpdateConfiguration(before, after) {
31
+ let visited = 0;
32
+ const same = (oldValue, newValue, depth) => {
33
+ if (++visited > 200000 || depth > 64) {
34
+ return false;
35
+ }
36
+ if (oldValue === null || typeof oldValue !== 'object') {
37
+ return Object.is(oldValue, newValue);
38
+ }
39
+ if (Array.isArray(oldValue)) {
40
+ return (Array.isArray(newValue) &&
41
+ oldValue.length === newValue.length &&
42
+ oldValue.every((item, index) => same(item, newValue[index], depth + 1)));
43
+ }
44
+ if (!(0, eosCustomerUpdateTransport_1.isRecord)(oldValue) || !(0, eosCustomerUpdateTransport_1.isRecord)(newValue)) {
45
+ return false;
46
+ }
47
+ return Object.keys(oldValue).every(key => Object.prototype.hasOwnProperty.call(newValue, key) && same(oldValue[key], newValue[key], depth + 1));
48
+ };
49
+ return same(before, after, 0);
50
+ }
51
+ /** Private, same-instance files never contain a client-supplied path or executable. */
52
+ async function privateDirectory(path) {
53
+ await (0, promises_1.mkdir)(path, { mode: 0o700 });
54
+ await checkPrivateDirectory(path);
55
+ }
56
+ async function checkPrivateDirectory(path) {
57
+ const info = await (0, promises_1.lstat)(path);
58
+ if (!info.isDirectory() ||
59
+ info.isSymbolicLink() ||
60
+ info.uid !== process.getuid?.() ||
61
+ (info.mode & 0o077) !== 0 ||
62
+ (await (0, promises_1.realpath)(path)) !== path) {
63
+ throw (0, eosCustomerUpdateTransport_1.updateError)('PRIVATE_STORAGE');
64
+ }
65
+ }
66
+ async function privateRead(path, maximum) {
67
+ const handle = await (0, promises_1.open)(path, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW);
68
+ try {
69
+ const info = await handle.stat();
70
+ if (!info.isFile() ||
71
+ info.uid !== process.getuid?.() ||
72
+ (info.mode & 0o077) !== 0 ||
73
+ info.size > maximum ||
74
+ info.nlink !== 1) {
75
+ throw (0, eosCustomerUpdateTransport_1.updateError)('PRIVATE_STORAGE');
76
+ }
77
+ const chunks = [];
78
+ let length = 0;
79
+ for (;;) {
80
+ const chunk = Buffer.alloc(Math.min(65536, maximum - length + 1));
81
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
82
+ if (!bytesRead) {
83
+ break;
84
+ }
85
+ length += bytesRead;
86
+ if (length > maximum) {
87
+ throw (0, eosCustomerUpdateTransport_1.updateError)('PRIVATE_STORAGE');
88
+ }
89
+ chunks.push(chunk.subarray(0, bytesRead));
90
+ }
91
+ return Buffer.concat(chunks, length);
92
+ }
93
+ finally {
94
+ await handle.close();
95
+ }
96
+ }
97
+ async function privateWrite(path, data) {
98
+ const temporary = `${path}.${(0, node_crypto_1.randomUUID)()}.tmp`;
99
+ const handle = await (0, promises_1.open)(temporary, node_fs_1.constants.O_WRONLY | node_fs_1.constants.O_CREAT | node_fs_1.constants.O_EXCL | node_fs_1.constants.O_NOFOLLOW, 0o600);
100
+ try {
101
+ await handle.writeFile(data);
102
+ await handle.sync();
103
+ }
104
+ finally {
105
+ await handle.close();
106
+ }
107
+ try {
108
+ await (0, promises_1.rename)(temporary, path);
109
+ const directory = await (0, promises_1.open)((0, node_path_1.dirname)(path), node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_DIRECTORY | node_fs_1.constants.O_NOFOLLOW);
110
+ try {
111
+ await directory.sync();
112
+ }
113
+ finally {
114
+ await directory.close();
115
+ }
116
+ }
117
+ finally {
118
+ await (0, promises_1.rm)(temporary, { force: true });
119
+ }
120
+ }
121
+ class EosCustomerUpdates {
122
+ options;
123
+ fetchResource;
124
+ directory;
125
+ ready;
126
+ stopped = false;
127
+ operation = null;
128
+ externalAbort = null;
129
+ candidate = null;
130
+ checkedAt = null;
131
+ lastAttemptMonotonic = -Infinity;
132
+ state = 'checking';
133
+ reason = null;
134
+ plan = null;
135
+ activeId = null;
136
+ activeFingerprint = null;
137
+ activeVersion = null;
138
+ activeCreatedAt = 0;
139
+ activeStarted = false;
140
+ initializationFailed = false;
141
+ receiptOperation = null;
142
+ constructor(options) {
143
+ if (!/^eos-admin\.\d{1,4}$/.test(options.namespace) ||
144
+ !(0, eosCustomerUpdateTransport_1.stableVersion)(options.currentVersion) ||
145
+ !semver_1.default.valid(options.nodeVersion) ||
146
+ [options.packageDir, options.controllerDir, options.dataDir].some(path => !(0, node_path_1.isAbsolute)(path) || path !== (0, node_path_1.resolve)(path))) {
147
+ throw (0, eosCustomerUpdateTransport_1.updateError)('CONFIGURATION');
148
+ }
149
+ this.options = options;
150
+ this.fetchResource = options.fetchResource || eosCustomerUpdateTransport_1.fetchUpdateResource;
151
+ this.directory = (0, node_path_1.join)(options.dataDir, 'customer-updates');
152
+ this.ready = this.initialize().catch(error => {
153
+ this.initializationFailed = true;
154
+ this.state = 'failed';
155
+ this.reason = safeReason(error);
156
+ });
157
+ }
158
+ async initialize() {
159
+ if (process.platform !== 'linux' || !process.getuid || process.getuid() === 0) {
160
+ this.state = 'incompatible';
161
+ this.reason = 'EOS_UPDATE_PLATFORM_UNSUPPORTED';
162
+ return;
163
+ }
164
+ try {
165
+ await privateDirectory(this.directory);
166
+ }
167
+ catch (error) {
168
+ if (!(0, eosCustomerUpdateTransport_1.isRecord)(error) || error.code !== 'EEXIST') {
169
+ throw error;
170
+ }
171
+ await checkPrivateDirectory(this.directory);
172
+ }
173
+ let active;
174
+ try {
175
+ active = JSON.parse((await privateRead((0, node_path_1.join)(this.directory, 'active.json'), 4096)).toString('utf8'));
176
+ }
177
+ catch (error) {
178
+ if ((0, eosCustomerUpdateTransport_1.isRecord)(error) && error.code === 'ENOENT') {
179
+ return;
180
+ }
181
+ throw error;
182
+ }
183
+ if (!(0, eosCustomerUpdateTransport_1.isRecord)(active) ||
184
+ active.schema !== 1 ||
185
+ typeof active.id !== 'string' ||
186
+ !UUID.test(active.id) ||
187
+ active.namespace !== this.options.namespace ||
188
+ !(0, eosCustomerUpdateTransport_1.stableVersion)(active.version) ||
189
+ typeof active.configurationFingerprint !== 'string' ||
190
+ !/^[a-f0-9]{64}$/.test(active.configurationFingerprint) ||
191
+ typeof active.createdAt !== 'number' ||
192
+ !Number.isSafeInteger(active.createdAt) ||
193
+ active.createdAt <= 0 ||
194
+ !['prepared', 'started', 'completed', 'failed-safe'].includes(String(active.phase))) {
195
+ throw (0, eosCustomerUpdateTransport_1.updateError)('RECEIPT');
196
+ }
197
+ this.activeId = active.id;
198
+ this.activeVersion = active.version;
199
+ this.activeCreatedAt = active.createdAt;
200
+ this.activeFingerprint = active.configurationFingerprint;
201
+ this.activeStarted = active.phase === 'started';
202
+ this.state =
203
+ active.phase === 'started'
204
+ ? 'installing'
205
+ : active.phase === 'completed'
206
+ ? 'installed'
207
+ : active.phase === 'failed-safe'
208
+ ? 'failed'
209
+ : 'interrupted';
210
+ this.reason =
211
+ active.phase === 'prepared'
212
+ ? 'EOS_UPDATE_PREPARATION_INTERRUPTED'
213
+ : active.phase === 'failed-safe'
214
+ ? typeof active.reason === 'string' && /^EOS_UPDATE_[A-Z_]{1,64}$/.test(active.reason)
215
+ ? active.reason
216
+ : 'EOS_UPDATE_WORKER_FAILED'
217
+ : null;
218
+ if (active.phase === 'completed' || active.phase === 'failed-safe') {
219
+ this.lastAttemptMonotonic = node_perf_hooks_1.performance.now();
220
+ }
221
+ }
222
+ assertRunning() {
223
+ if (this.stopped) {
224
+ throw (0, eosCustomerUpdateTransport_1.updateError)('STOPPED');
225
+ }
226
+ }
227
+ view() {
228
+ const plan = this.plan;
229
+ return {
230
+ installedVersion: this.options.currentVersion,
231
+ availableVersion: this.candidate?.version || this.activeVersion,
232
+ checkedAt: this.checkedAt,
233
+ source: 'npm-latest',
234
+ state: this.state,
235
+ canStart: this.state === 'prepared' && !!plan && plan.expiresMonotonic > node_perf_hooks_1.performance.now() && !this.stopped,
236
+ reason: this.reason,
237
+ ...(plan ? { planId: plan.id, expiresAt: plan.expiresAt } : {}),
238
+ ...(this.activeId ? { jobId: this.activeId } : {}),
239
+ };
240
+ }
241
+ stop() {
242
+ this.stopped = true;
243
+ this.externalAbort?.abort();
244
+ this.externalAbort = null;
245
+ this.plan = null;
246
+ // A launched, bounded maintenance worker must survive the adapter stop it requested.
247
+ }
248
+ async status() {
249
+ await this.ready;
250
+ if (this.initializationFailed || this.reason === 'EOS_UPDATE_PLATFORM_UNSUPPORTED') {
251
+ return this.view();
252
+ }
253
+ if (this.activeId && this.activeStarted && !this.receiptOperation) {
254
+ const operation = this.refreshReceipt();
255
+ this.receiptOperation = operation;
256
+ try {
257
+ await operation;
258
+ }
259
+ finally {
260
+ if (this.receiptOperation === operation) {
261
+ this.receiptOperation = null;
262
+ }
263
+ }
264
+ }
265
+ if (!this.operation && !this.activeStarted && node_perf_hooks_1.performance.now() - this.lastAttemptMonotonic >= CACHE_MS) {
266
+ return this.check();
267
+ }
268
+ if (this.plan && this.plan.expiresMonotonic <= node_perf_hooks_1.performance.now()) {
269
+ this.plan = null;
270
+ this.state = 'available';
271
+ this.reason = 'EOS_UPDATE_PLAN_EXPIRED';
272
+ }
273
+ return this.view();
274
+ }
275
+ check() {
276
+ return this.exclusive(async () => {
277
+ if (this.activeStarted || this.state === 'prepared') {
278
+ return this.view();
279
+ }
280
+ if (node_perf_hooks_1.performance.now() - this.lastAttemptMonotonic < CHECK_COOLDOWN_MS) {
281
+ return this.view();
282
+ }
283
+ this.lastAttemptMonotonic = node_perf_hooks_1.performance.now();
284
+ this.state = 'checking';
285
+ this.reason = null;
286
+ try {
287
+ const candidate = await this.external(async (signal) => (0, eosCustomerUpdateTransport_1.parseCandidate)(await this.fetchResource(eosCustomerUpdateTransport_1.UPDATE_METADATA_URL, 128 * 1024, signal), this.options.currentVersion, this.options.nodeVersion));
288
+ this.assertRunning();
289
+ this.candidate = candidate;
290
+ this.checkedAt = Date.now();
291
+ this.state = semver_1.default.gt(candidate.version, this.options.currentVersion) ? 'available' : 'current';
292
+ }
293
+ catch (error) {
294
+ this.reason = safeReason(error);
295
+ this.state = this.reason === 'EOS_UPDATE_INCOMPATIBLE' ? 'incompatible' : 'offline';
296
+ }
297
+ return this.view();
298
+ });
299
+ }
300
+ prepare(version, authorize) {
301
+ return this.exclusive(async () => {
302
+ if (this.activeStarted) {
303
+ throw (0, eosCustomerUpdateTransport_1.updateError)('BUSY');
304
+ }
305
+ if (!(0, eosCustomerUpdateTransport_1.stableVersion)(version) ||
306
+ !semver_1.default.gt(version, this.options.currentVersion) ||
307
+ !this.candidate ||
308
+ this.candidate.version !== version ||
309
+ !this.checkedAt ||
310
+ Date.now() - this.checkedAt > CACHE_MS) {
311
+ throw (0, eosCustomerUpdateTransport_1.updateError)('VERSION_CHANGED');
312
+ }
313
+ await this.assertHost();
314
+ await this.authorize(authorize);
315
+ await this.pruneOldJobs();
316
+ this.state = 'preparing';
317
+ this.reason = null;
318
+ this.plan = null;
319
+ const id = (0, node_crypto_1.randomUUID)(), directory = (0, node_path_1.join)(this.directory, id);
320
+ await privateDirectory(directory);
321
+ try {
322
+ const candidate = this.candidate;
323
+ const archive = await this.external(async (signal) => {
324
+ const [metadata, keys] = await Promise.all([
325
+ this.fetchResource(eosCustomerUpdateTransport_1.UPDATE_METADATA_URL, 128 * 1024, signal),
326
+ this.fetchResource(eosCustomerUpdateTransport_1.UPDATE_KEYS_URL, 32 * 1024, signal),
327
+ ]);
328
+ const fresh = (0, eosCustomerUpdateTransport_1.parseCandidate)(metadata, this.options.currentVersion, this.options.nodeVersion);
329
+ if (fresh.version !== candidate.version || fresh.integrity !== candidate.integrity) {
330
+ throw (0, eosCustomerUpdateTransport_1.updateError)('VERSION_CHANGED');
331
+ }
332
+ (0, eosCustomerUpdateTransport_1.verifyRegistrySignature)(fresh, keys, Date.now());
333
+ const data = await this.fetchResource(fresh.tarball, eosCustomerUpdateTransport_1.UPDATE_MAX_ARCHIVE_BYTES, signal);
334
+ (0, eosCustomerUpdateTransport_1.verifyArchiveIntegrity)(data, fresh.integrity);
335
+ return data;
336
+ });
337
+ this.assertRunning();
338
+ await privateWrite((0, node_path_1.join)(directory, 'release.tgz'), archive);
339
+ const archiveInfo = await this.external(signal => (0, eosCustomerUpdateTransport_1.inspectUpdateArchive)((0, node_path_1.join)(directory, 'release.tgz'), candidate, signal));
340
+ const files = archiveInfo.files.filter(file => file.path !== 'io-package.json');
341
+ if (!files.some(file => file.path === 'build/main.js')) {
342
+ throw (0, eosCustomerUpdateTransport_1.updateError)('ARCHIVE_IDENTITY');
343
+ }
344
+ const snapshot = await this.snapshot();
345
+ const encrypted = this.options.encryptSnapshot(snapshot);
346
+ if (typeof encrypted !== 'string' ||
347
+ !encrypted ||
348
+ encrypted === snapshot ||
349
+ Buffer.byteLength(encrypted) > MAX_SNAPSHOT_BYTES * 3) {
350
+ throw (0, eosCustomerUpdateTransport_1.updateError)('SNAPSHOT_ENCRYPTION');
351
+ }
352
+ const savedSnapshot = JSON.stringify({ schema: 1, namespace: this.options.namespace, encrypted });
353
+ await privateWrite((0, node_path_1.join)(directory, 'configuration.enc.json'), savedSnapshot);
354
+ const createdAt = Date.now();
355
+ const job = {
356
+ schema: 1,
357
+ id,
358
+ namespace: this.options.namespace,
359
+ fromVersion: this.options.currentVersion,
360
+ toVersion: version,
361
+ packageDir: this.options.packageDir,
362
+ controllerDir: this.options.controllerDir,
363
+ archiveIntegrity: candidate.integrity,
364
+ manifestSha256: hash(JSON.stringify(files)),
365
+ files,
366
+ snapshotSha256: hash(savedSnapshot),
367
+ createdAt,
368
+ enabledInstances: [this.options.namespace],
369
+ };
370
+ await this.authorize(authorize);
371
+ this.plan = {
372
+ id,
373
+ version,
374
+ expiresAt: createdAt + PLAN_MS,
375
+ expiresMonotonic: node_perf_hooks_1.performance.now() + PLAN_MS,
376
+ configurationFingerprint: hash(snapshot),
377
+ job,
378
+ };
379
+ this.activeId = id;
380
+ this.activeVersion = version;
381
+ this.activeCreatedAt = createdAt;
382
+ this.activeFingerprint = hash(snapshot);
383
+ await this.persistActive('prepared');
384
+ this.state = 'prepared';
385
+ return this.view();
386
+ }
387
+ catch (error) {
388
+ this.state = 'failed';
389
+ this.reason = safeReason(error);
390
+ await (0, promises_1.rm)(directory, { recursive: true, force: true }).catch(() => undefined);
391
+ throw error;
392
+ }
393
+ });
394
+ }
395
+ start(planId, authorize) {
396
+ return this.exclusive(async () => {
397
+ const plan = this.plan;
398
+ if (!plan ||
399
+ this.state !== 'prepared' ||
400
+ !UUID.test(planId) ||
401
+ plan.id !== planId ||
402
+ plan.expiresMonotonic <= node_perf_hooks_1.performance.now()) {
403
+ throw (0, eosCustomerUpdateTransport_1.updateError)('PLAN_EXPIRED');
404
+ }
405
+ await this.assertHost();
406
+ await this.authorize(authorize);
407
+ if (hash(await this.snapshot()) !== plan.configurationFingerprint) {
408
+ throw (0, eosCustomerUpdateTransport_1.updateError)('CONFIGURATION_CHANGED');
409
+ }
410
+ const directory = (0, node_path_1.join)(this.directory, plan.id);
411
+ await checkPrivateDirectory(directory);
412
+ await privateWrite((0, node_path_1.join)(directory, 'job.json'), JSON.stringify(plan.job));
413
+ const workerSource = (0, node_path_1.join)(this.options.packageDir, 'build', 'lib', 'eosCustomerUpdateWorker.js');
414
+ const worker = await (0, promises_1.readFile)(workerSource);
415
+ if (worker.length < 100 || worker.length > 256 * 1024) {
416
+ throw (0, eosCustomerUpdateTransport_1.updateError)('WORKER');
417
+ }
418
+ await privateWrite((0, node_path_1.join)(directory, 'worker.cjs'), worker);
419
+ // Durable before spawn: a crash at this boundary is never replayed automatically.
420
+ this.activeCreatedAt = Date.now();
421
+ await this.persistActive('started');
422
+ this.activeStarted = true;
423
+ try {
424
+ await this.authorize(authorize);
425
+ }
426
+ catch (error) {
427
+ // No worker has been spawned: this is a known pre-effect rejection.
428
+ this.activeStarted = false;
429
+ await this.persistActive('prepared');
430
+ throw error;
431
+ }
432
+ this.state = 'installing';
433
+ this.reason = null;
434
+ this.plan = null;
435
+ await new Promise((resolveStart, rejectStart) => {
436
+ const child = (0, node_child_process_1.spawn)(process.execPath, [(0, node_path_1.join)(directory, 'worker.cjs'), directory], {
437
+ cwd: directory,
438
+ detached: true,
439
+ stdio: 'ignore',
440
+ shell: false,
441
+ env: {
442
+ PATH: process.env.PATH || '/usr/bin:/bin',
443
+ HOME: process.env.HOME || this.options.dataDir,
444
+ LANG: 'C.UTF-8',
445
+ },
446
+ });
447
+ child.once('spawn', () => {
448
+ child.unref();
449
+ resolveStart();
450
+ });
451
+ child.once('error', () => rejectStart((0, eosCustomerUpdateTransport_1.updateError)('WORKER_START')));
452
+ }).catch(error => {
453
+ this.state = 'failed';
454
+ this.reason = safeReason(error);
455
+ throw error;
456
+ });
457
+ return this.view();
458
+ });
459
+ }
460
+ async external(task) {
461
+ this.assertRunning();
462
+ const controller = new AbortController();
463
+ this.externalAbort = controller;
464
+ const timer = setTimeout(() => controller.abort(), 5000);
465
+ timer.unref();
466
+ try {
467
+ return await task(controller.signal);
468
+ }
469
+ finally {
470
+ clearTimeout(timer);
471
+ if (this.externalAbort === controller) {
472
+ this.externalAbort = null;
473
+ }
474
+ }
475
+ }
476
+ exclusive(task) {
477
+ if (this.operation) {
478
+ return Promise.reject((0, eosCustomerUpdateTransport_1.updateError)('BUSY'));
479
+ }
480
+ const promise = (async () => {
481
+ await this.ready;
482
+ this.assertRunning();
483
+ if (this.initializationFailed) {
484
+ throw (0, eosCustomerUpdateTransport_1.updateError)('PRIVATE_STORAGE');
485
+ }
486
+ if (process.platform !== 'linux' || !process.getuid || process.getuid() === 0) {
487
+ throw (0, eosCustomerUpdateTransport_1.updateError)('PLATFORM_UNSUPPORTED');
488
+ }
489
+ await checkPrivateDirectory(this.directory);
490
+ return task();
491
+ })();
492
+ this.operation = promise;
493
+ void promise
494
+ .finally(() => {
495
+ if (this.operation === promise) {
496
+ this.operation = null;
497
+ }
498
+ })
499
+ .catch(() => undefined);
500
+ return promise;
501
+ }
502
+ async authorize(authorize) {
503
+ this.assertRunning();
504
+ if ((await authorize()) !== true) {
505
+ throw (0, eosCustomerUpdateTransport_1.updateError)('AUTHORIZATION');
506
+ }
507
+ this.assertRunning();
508
+ }
509
+ async assertHost() {
510
+ const instances = await this.options.readHostInstances();
511
+ this.assertRunning();
512
+ if (instances.length !== 1 ||
513
+ instances[0]?.namespace !== this.options.namespace ||
514
+ instances[0].enabled !== true) {
515
+ throw (0, eosCustomerUpdateTransport_1.updateError)('MULTI_INSTANCE');
516
+ }
517
+ const controller = JSON.parse(await (0, promises_1.readFile)((0, node_path_1.join)(this.options.controllerDir, 'package.json'), 'utf8'));
518
+ if (!(0, eosCustomerUpdateTransport_1.isRecord)(controller) || controller.name !== 'iobroker.js-controller' || controller.version !== '7.2.5') {
519
+ throw (0, eosCustomerUpdateTransport_1.updateError)('CONTROLLER_UNSUPPORTED');
520
+ }
521
+ }
522
+ async snapshot() {
523
+ this.assertRunning();
524
+ const snapshot = JSON.stringify(await this.options.readConfigurationSnapshot());
525
+ this.assertRunning();
526
+ if (typeof snapshot !== 'string' || snapshot.length < 2 || Buffer.byteLength(snapshot) > MAX_SNAPSHOT_BYTES) {
527
+ throw (0, eosCustomerUpdateTransport_1.updateError)('SNAPSHOT_SIZE');
528
+ }
529
+ return snapshot;
530
+ }
531
+ async persistActive(phase) {
532
+ await privateWrite((0, node_path_1.join)(this.directory, 'active.json'), JSON.stringify({
533
+ schema: 1,
534
+ id: this.activeId,
535
+ namespace: this.options.namespace,
536
+ version: this.activeVersion,
537
+ configurationFingerprint: this.activeFingerprint,
538
+ createdAt: this.activeCreatedAt,
539
+ phase,
540
+ reason: this.reason,
541
+ }));
542
+ }
543
+ async refreshReceipt() {
544
+ if (!this.activeId) {
545
+ return;
546
+ }
547
+ let result;
548
+ try {
549
+ result = JSON.parse((await privateRead((0, node_path_1.join)(this.directory, this.activeId, 'result.json'), 4096)).toString('utf8'));
550
+ }
551
+ catch (error) {
552
+ if ((0, eosCustomerUpdateTransport_1.isRecord)(error) && error.code === 'ENOENT' && Date.now() - this.activeCreatedAt < PLAN_MS) {
553
+ return;
554
+ }
555
+ this.state = 'interrupted';
556
+ this.reason = 'EOS_UPDATE_RESULT_UNAVAILABLE';
557
+ return;
558
+ }
559
+ if (!(0, eosCustomerUpdateTransport_1.isRecord)(result) ||
560
+ result.schema !== 1 ||
561
+ result.id !== this.activeId ||
562
+ result.namespace !== this.options.namespace ||
563
+ result.toVersion !== this.activeVersion) {
564
+ this.state = 'interrupted';
565
+ this.reason = 'EOS_UPDATE_RECEIPT';
566
+ return;
567
+ }
568
+ if (result.status === 'running') {
569
+ if (Date.now() - this.activeCreatedAt > PLAN_MS) {
570
+ this.state = 'interrupted';
571
+ this.reason = 'EOS_UPDATE_RESULT_TIMEOUT';
572
+ }
573
+ return;
574
+ }
575
+ if (result.status !== 'succeeded') {
576
+ this.state = result.status === 'failed' ? 'failed' : 'interrupted';
577
+ this.reason =
578
+ typeof result.error === 'string' && /^EOS_UPDATE_[A-Z_]{1,64}$/.test(result.error)
579
+ ? result.error
580
+ : 'EOS_UPDATE_WORKER_FAILED';
581
+ if (result.status === 'failed' && (result.phase === 'validate' || result.recovery === 'restored-old')) {
582
+ await this.persistActive('failed-safe');
583
+ this.activeStarted = false;
584
+ this.lastAttemptMonotonic = node_perf_hooks_1.performance.now();
585
+ }
586
+ return;
587
+ }
588
+ if (this.options.currentVersion !== this.activeVersion) {
589
+ this.reason = 'EOS_UPDATE_RESTART_PENDING';
590
+ return;
591
+ }
592
+ try {
593
+ const saved = JSON.parse((await privateRead((0, node_path_1.join)(this.directory, this.activeId, 'configuration.enc.json'), MAX_SNAPSHOT_BYTES * 3 + 1024)).toString('utf8'));
594
+ if (!(0, eosCustomerUpdateTransport_1.isRecord)(saved) ||
595
+ saved.schema !== 1 ||
596
+ saved.namespace !== this.options.namespace ||
597
+ typeof saved.encrypted !== 'string') {
598
+ throw (0, eosCustomerUpdateTransport_1.updateError)('SNAPSHOT_FORMAT');
599
+ }
600
+ const original = JSON.parse(this.options.decryptSnapshot(saved.encrypted));
601
+ const present = JSON.parse(await this.snapshot());
602
+ if (!preservesUpdateConfiguration(original, present)) {
603
+ throw (0, eosCustomerUpdateTransport_1.updateError)('CONFIGURATION_CHANGED');
604
+ }
605
+ await this.persistActive('completed');
606
+ this.state = 'installed';
607
+ this.reason = null;
608
+ this.activeStarted = false;
609
+ this.lastAttemptMonotonic = node_perf_hooks_1.performance.now();
610
+ }
611
+ catch (error) {
612
+ this.state = 'interrupted';
613
+ this.reason = safeReason(error);
614
+ }
615
+ }
616
+ async pruneOldJobs() {
617
+ const entries = await (0, promises_1.readdir)(this.directory, { withFileTypes: true });
618
+ const jobs = await Promise.all(entries
619
+ .filter(entry => UUID.test(entry.name) && entry.isDirectory() && entry.name !== this.activeId)
620
+ .map(async (entry) => ({
621
+ path: (0, node_path_1.join)(this.directory, entry.name),
622
+ modified: (await (0, promises_1.lstat)((0, node_path_1.join)(this.directory, entry.name))).mtimeMs,
623
+ })));
624
+ jobs.sort((a, b) => b.modified - a.modified);
625
+ for (const job of jobs.slice(2)) {
626
+ await (0, promises_1.rm)(job.path, { recursive: true, force: true });
627
+ }
628
+ }
629
+ }
630
+ exports.EosCustomerUpdates = EosCustomerUpdates;
631
+ //# sourceMappingURL=eosCustomerUpdates.js.map