@xkwdstore/agent 2.1.1 → 2.1.3

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/src/updater.js ADDED
@@ -0,0 +1,578 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Auto-updater for XKWDStore Agent.
5
+ *
6
+ * Polls a manifest.json hosted on GitHub (raw.githubusercontent.com) every
7
+ * CHECK_INTERVAL_MS. When a newer version is published, downloads the new
8
+ * .exe from GitHub Releases, verifies SHA256, writes a swapper script, then
9
+ * exits the current process. The swapper:
10
+ * 1. waits for this process to fully exit
11
+ * 2. copies the new .exe over the running one
12
+ * 3. relaunches the new xkwdstore-agent.exe
13
+ *
14
+ * The manifest + .exe are served from GitHub (CDN-cached, no VPS bandwidth).
15
+ * The VPS is only used for the WebSocket command channel.
16
+ *
17
+ * Designed to run inside the pkg-packaged .exe. Does not self-modify the
18
+ * running binary — uses an external swapper script for the atomic swap.
19
+ */
20
+
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const os = require('os');
24
+ const { spawn, spawnSync } = require('child_process');
25
+
26
+ const WIN_NO_WINDOW = 0x08000000;
27
+
28
+ function spawnHidden(command, args, options = {}) {
29
+ return spawn(command, args, {
30
+ detached: true,
31
+ stdio: 'ignore',
32
+ windowsHide: true,
33
+ ...(process.platform === 'win32' ? { creationFlags: WIN_NO_WINDOW } : {}),
34
+ ...options,
35
+ });
36
+ }
37
+
38
+ /** Hidden PID wait for Windows swapper scripts (avoids visible `find "PID"` cmd windows). */
39
+ function windowsWaitPidBlock(pid) {
40
+ return `powershell -NoProfile -WindowStyle Hidden -Command "while (Get-Process -Id ${pid} -ErrorAction SilentlyContinue) { Start-Sleep -Seconds 1 }"\r`;
41
+ }
42
+
43
+ function windowsRelaunchExe(exePath) {
44
+ const escaped = exePath.replace(/'/g, "''");
45
+ return `powershell -NoProfile -WindowStyle Hidden -Command "Start-Process -FilePath '${escaped}' -WindowStyle Hidden"\r`;
46
+ }
47
+ const https = require('https');
48
+ const http = require('http');
49
+ const zlib = require('zlib');
50
+
51
+ const CHECK_INTERVAL_MS = 30 * 60 * 1000; // poll every 30 min (was 5 min — too aggressive caused restart loops)
52
+ const DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000; // 5 min per download attempt
53
+ const MAX_REDIRECTS = 5;
54
+ const RESTART_COOLDOWN_MS = 10 * 60 * 1000; // 10 minutes between auto-restarts to prevent loops
55
+ const UPDATE_COOLDOWN_MS = 30 * 60 * 1000; // 30 minutes between auto-updates to prevent restart loops
56
+
57
+ let _pollHandle = null;
58
+ let _config = null;
59
+ let _agentDir = null;
60
+ let _onShutdownRequest = null;
61
+ let _restartCallback = null; // Called when agent should restart itself
62
+ let _wsConnected = false; // Track WebSocket connection state
63
+ let _lastUpdateAt = 0; // Track last update time to prevent loops
64
+
65
+ function log(...args) { console.log(`[updater]`, ...args); }
66
+
67
+ /**
68
+ * Check if we recently applied an update (to prevent update loops).
69
+ * Persists to disk so it survives across agent processes.
70
+ */
71
+ function recentlyUpdated() {
72
+ // Check in-memory first
73
+ if (Date.now() - _lastUpdateAt < UPDATE_COOLDOWN_MS) return true;
74
+ // Check disk (survives restarts)
75
+ try {
76
+ const stateFile = path.join(os.homedir(), '.xkwdstore-agent', 'last-update.txt');
77
+ if (!fs.existsSync(stateFile)) return false;
78
+ const lastUpdate = parseInt(fs.readFileSync(stateFile, 'utf8').trim(), 10);
79
+ if (isNaN(lastUpdate)) return false;
80
+ return Date.now() - lastUpdate < UPDATE_COOLDOWN_MS;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ function recordUpdateTime() {
87
+ _lastUpdateAt = Date.now();
88
+ try {
89
+ const stateFile = path.join(os.homedir(), '.xkwdstore-agent', 'last-update.txt');
90
+ fs.writeFileSync(stateFile, String(Date.now()), 'utf8');
91
+ } catch {}
92
+ }
93
+
94
+ /**
95
+ * Called by the main agent to notify the updater of WebSocket connection state.
96
+ * When connected, updates are skipped to avoid unnecessary restarts.
97
+ */
98
+ function setWsConnected(connected) {
99
+ _wsConnected = connected;
100
+ }
101
+
102
+ /**
103
+ * Check if we recently restarted (to prevent restart loops).
104
+ * Persists restart time to disk so it survives across agent processes.
105
+ */
106
+ function recentlyRestarted() {
107
+ try {
108
+ const stateFile = path.join(os.homedir(), '.xkwdstore-agent', 'last-restart.txt');
109
+ if (!fs.existsSync(stateFile)) return false;
110
+ const lastRestart = parseInt(fs.readFileSync(stateFile, 'utf8').trim(), 10);
111
+ if (isNaN(lastRestart)) return false;
112
+ return Date.now() - lastRestart < RESTART_COOLDOWN_MS;
113
+ } catch {
114
+ return false;
115
+ }
116
+ }
117
+
118
+ function recordRestartTime() {
119
+ try {
120
+ const stateFile = path.join(os.homedir(), '.xkwdstore-agent', 'last-restart.txt');
121
+ fs.writeFileSync(stateFile, String(Date.now()), 'utf8');
122
+ } catch {}
123
+ }
124
+
125
+ /**
126
+ * Start polling for updates.
127
+ * @param {object} opts
128
+ * @param {string} opts.serverUrl e.g. 'wss://x.kwdstore.com' (used for WS only)
129
+ * @param {string} opts.agentDir Folder containing the running .exe (where we swap)
130
+ * @param {function} opts.onShutdownRequest Called when update is ready; should call process.exit
131
+ * @param {function} opts.onRestartRequest Called when agent should restart itself (e.g. on repeated WS failures)
132
+ */
133
+ function start({ serverUrl, agentDir, onShutdownRequest, onRestartRequest }) {
134
+ if (!agentDir) {
135
+ log('Not starting — agentDir missing');
136
+ return;
137
+ }
138
+ _agentDir = agentDir;
139
+ _onShutdownRequest = onShutdownRequest;
140
+ _restartCallback = onRestartRequest || null;
141
+
142
+ // The manifest is hosted on the PUBLIC TW-manager-install repo (raw URL).
143
+ // This is critical: the main TW-manager repo is PRIVATE, so its raw URLs
144
+ // return 404 for unauthenticated users. The agent running on a user's PC
145
+ // has no GitHub token, so it must poll the public repo.
146
+ const GITHUB_MANIFEST_URL = 'https://raw.githubusercontent.com/EssaGhazwani/TW-manager-install/main/manifest.json';
147
+ _config = { manifestUrl: GITHUB_MANIFEST_URL };
148
+
149
+ if (_pollHandle) clearInterval(_pollHandle);
150
+ // First check after 60s (give agent time to connect to WebSocket first)
151
+ setTimeout(() => checkForUpdate().catch(e => log('update check failed:', e.message)), 60 * 1000);
152
+ _pollHandle = setInterval(() => checkForUpdate().catch(e => log('update check failed:', e.message)), CHECK_INTERVAL_MS);
153
+ log(`Polling ${GITHUB_MANIFEST_URL} every ${Math.round(CHECK_INTERVAL_MS / 1000 / 60)} min (skips when WS connected or recently updated)`);
154
+ }
155
+
156
+ /**
157
+ * Called by the main agent when WebSocket fails repeatedly (e.g. 502 errors).
158
+ * Forces an immediate update check + applies any pending update.
159
+ * If no update is available, triggers a self-restart to recover from the bad state.
160
+ */
161
+ async function forceCheckAndRestart(reason) {
162
+ // Prevent restart loops: if we restarted in the last 10 minutes, skip
163
+ if (recentlyRestarted()) {
164
+ log(`Skipping restart — already restarted within last ${RESTART_COOLDOWN_MS / 60000} minutes (reason: ${reason})`);
165
+ return;
166
+ }
167
+ // Also skip if we recently applied an update (give it time to work)
168
+ if (recentlyUpdated()) {
169
+ log(`Skipping restart — recently updated within last ${UPDATE_COOLDOWN_MS / 60000} minutes (reason: ${reason})`);
170
+ return;
171
+ }
172
+ log(`Force update check triggered: ${reason}`);
173
+ try {
174
+ const manifest = await fetchJson(_config.manifestUrl);
175
+ if (manifest && manifest.version) {
176
+ const current = currentInstalledVersion();
177
+ if (current && String(manifest.version) > String(current)) {
178
+ log(`Update available: ${current} → ${manifest.version} — applying now`);
179
+ await applyUpdate(manifest);
180
+ return;
181
+ }
182
+ }
183
+ } catch (e) {
184
+ log(`Force check failed: ${e.message}`);
185
+ }
186
+
187
+ // No update available — trigger a self-restart to recover from bad state
188
+ log('No update available — triggering self-restart to recover');
189
+ recordRestartTime();
190
+ triggerSelfRestart();
191
+ }
192
+
193
+ /**
194
+ * Trigger a self-restart of the agent without downloading anything.
195
+ * Used when WebSocket is stuck in a bad state (e.g. repeated 502 errors)
196
+ * and we need a clean restart to recover.
197
+ */
198
+ function triggerSelfRestart() {
199
+ // Prevent restart loops
200
+ if (recentlyRestarted()) {
201
+ log(`Skipping self-restart — already restarted within last ${RESTART_COOLDOWN_MS / 60000} minutes`);
202
+ return;
203
+ }
204
+ recordRestartTime();
205
+ const isWin = os.platform() === 'win32';
206
+ const pid = process.pid;
207
+ const exeName = isWin ? 'xkwdstore-agent.exe' : 'xkwdstore-agent';
208
+ const currentExe = path.join(_agentDir, exeName);
209
+ const restartScript = isWin
210
+ ? path.join(_agentDir, '..', '.xkwdstore-restart.bat')
211
+ : path.join(_agentDir, '..', '.xkwdstore-restart.sh');
212
+
213
+ if (isWin) {
214
+ const bat = `@echo off\r
215
+ setlocal\r
216
+ set "TARGET=${currentExe}"\r
217
+ echo [xkwdstore-restarter] Waiting for agent PID ${pid} to exit...\r
218
+ ${windowsWaitPidBlock(pid)}echo [xkwdstore-restarter] Relaunching agent...\r
219
+ ${windowsRelaunchExe(currentExe)}del "%~f0"\r
220
+ endlocal\r
221
+ `;
222
+ try {
223
+ fs.writeFileSync(restartScript, bat);
224
+ log(`Starting restarter: ${restartScript}`);
225
+ spawnHidden('cmd.exe', ['/c', restartScript]).unref();
226
+ } catch (e) {
227
+ log(`Failed to write restart script: ${e.message}`);
228
+ }
229
+ } else {
230
+ const sh = `#!/bin/sh
231
+ while kill -0 ${pid} 2>/dev/null; do sleep 1; done
232
+ nohup "${currentExe}" >/dev/null 2>&1 &
233
+ rm -f "$0"
234
+ `;
235
+ try {
236
+ fs.writeFileSync(restartScript, sh);
237
+ fs.chmodSync(restartScript, 0o755);
238
+ log(`Starting restarter: ${restartScript}`);
239
+ spawnHidden('/bin/sh', [restartScript]).unref();
240
+ } catch (e) {
241
+ log(`Failed to write restart script: ${e.message}`);
242
+ }
243
+ }
244
+
245
+ // Exit the current process so the new one can take over
246
+ setTimeout(() => {
247
+ log('Exiting for self-restart');
248
+ if (_onShutdownRequest) _onShutdownRequest();
249
+ else process.exit(0);
250
+ }, 1000);
251
+ }
252
+
253
+ function stop() {
254
+ if (_pollHandle) { clearInterval(_pollHandle); _pollHandle = null; }
255
+ }
256
+
257
+ /**
258
+ * Read this agent's version from the manifest.json inside the agent folder.
259
+ * (Written by the packaging script — see scripts/package-ci.js write packageVersion().)
260
+ * Falls back to environment variable or '0' if unknown.
261
+ */
262
+ function currentInstalledVersion() {
263
+ try {
264
+ const versionFile = path.join(_agentDir, 'VERSION');
265
+ if (fs.existsSync(versionFile)) {
266
+ return fs.readFileSync(versionFile, 'utf8').trim();
267
+ }
268
+ } catch {}
269
+ return process.env.AGENT_VERSION || null;
270
+ }
271
+
272
+ async function fetchJson(url, timeoutMs = 15000) {
273
+ return new Promise((resolve, reject) => {
274
+ const startTime = Date.now();
275
+ const doReq = (u, redirectsLeft) => {
276
+ const lib = u.startsWith('https') ? https : http;
277
+ const req = lib.get(u, { timeout: timeoutMs }, (resp) => {
278
+ if (resp.statusCode >= 300 && resp.statusCode < 400 && resp.headers.location) {
279
+ if (redirectsLeft <= 0) return reject(new Error('Too many redirects'));
280
+ return doReq(resp.headers.location, redirectsLeft - 1);
281
+ }
282
+ if (resp.statusCode !== 200) {
283
+ return reject(new Error(`HTTP ${resp.statusCode} for ${u}`));
284
+ }
285
+ let body = '';
286
+ resp.on('data', d => body += d);
287
+ resp.on('end', () => {
288
+ try { resolve(JSON.parse(body)); } catch (e) { reject(e); }
289
+ });
290
+ });
291
+ req.on('error', reject);
292
+ req.on('timeout', () => { req.destroy(); reject(new Error('Request timed out')); });
293
+ };
294
+ doReq(url, MAX_REDIRECTS);
295
+ });
296
+ }
297
+
298
+ async function downloadFile(url, destPath, expectedSha256) {
299
+ return new Promise((resolve, reject) => {
300
+ const tmpPath = destPath + '.part';
301
+ const file = fs.createWriteStream(tmpPath);
302
+ const doReq = (u, redirectsLeft) => {
303
+ const lib = u.startsWith('https') ? https : http;
304
+ const req = lib.get(u, { timeout: DOWNLOAD_TIMEOUT_MS }, (resp) => {
305
+ if (resp.statusCode >= 300 && resp.statusCode < 400 && resp.headers.location) {
306
+ if (redirectsLeft <= 0) return reject(new Error('Too many redirects'));
307
+ resp.destroy();
308
+ return doReq(resp.headers.location, redirectsLeft - 1);
309
+ }
310
+ if (resp.statusCode !== 200) {
311
+ return reject(new Error(`HTTP ${resp.statusCode}`));
312
+ }
313
+ resp.pipe(file);
314
+ file.on('finish', () => file.close(async () => {
315
+ // Verify SHA256 if provided
316
+ if (expectedSha256) {
317
+ const crypto = require('crypto');
318
+ const buf = fs.readFileSync(tmpPath);
319
+ const actualSha = crypto.createHash('sha256').update(buf).digest('hex');
320
+ if (actualSha !== expectedSha256) {
321
+ fs.unlinkSync(tmpPath);
322
+ return reject(new Error(`SHA256 mismatch (expected ${expectedSha256.slice(0,8)}, got ${actualSha.slice(0,8)})`));
323
+ }
324
+ log(`SHA256 verified: ${actualSha.slice(0, 16)}…`);
325
+ }
326
+ fs.renameSync(tmpPath, destPath);
327
+ resolve(destPath);
328
+ }));
329
+ });
330
+ req.on('error', reject);
331
+ req.on('timeout', () => { req.destroy(); reject(new Error('Download timed out')); });
332
+ };
333
+ doReq(url, MAX_REDIRECTS);
334
+ });
335
+ }
336
+
337
+ async function checkForUpdate() {
338
+ if (!_config) return;
339
+
340
+ // ── Skip update check if WebSocket is connected (agent is working fine) ──
341
+ // Only check for updates when the agent is idle or disconnected.
342
+ // This prevents the agent from restarting while it's actively working.
343
+ if (_wsConnected) {
344
+ return; // Silent skip — don't even log to avoid noise
345
+ }
346
+
347
+ // ── Skip if we recently applied an update (prevent update loops) ──
348
+ if (recentlyUpdated()) {
349
+ return; // Silent skip
350
+ }
351
+
352
+ let manifest;
353
+ try {
354
+ manifest = await fetchJson(_config.manifestUrl);
355
+ } catch (e) {
356
+ log(`manifest fetch failed (will retry): ${e.message}`);
357
+ return;
358
+ }
359
+ if (!manifest || !manifest.version) return;
360
+
361
+ const current = currentInstalledVersion();
362
+ if (!current) {
363
+ log('Skipping update check — installed VERSION is unknown');
364
+ return;
365
+ }
366
+ if (String(manifest.version) <= String(current)) return;
367
+
368
+ log(`Update available: ${current} → ${manifest.version} (released ${manifest.releasedAt})`);
369
+ await applyUpdate(manifest);
370
+ }
371
+
372
+ async function applyUpdate(manifest) {
373
+ // Record update time to prevent update loops
374
+ recordUpdateTime();
375
+
376
+ const downloadUrl = manifest.downloadUrl.startsWith('http')
377
+ ? manifest.downloadUrl
378
+ : `https://github.com/EssaGhazwani/TW-manager-install/releases/download/agent-latest/${manifest.downloadUrl}`;
379
+
380
+ const stagingDir = path.join(_agentDir, '..', '.xkwdstore-agent-staging');
381
+ fs.mkdirSync(stagingDir, { recursive: true });
382
+
383
+ // The manifest from GitHub always points to a standalone .exe
384
+ const exeName = os.platform() === 'win32' ? 'xkwdstore-agent.exe' : 'xkwdstore-agent';
385
+ const newExePath = path.join(stagingDir, `xkwdstore-agent-${manifest.version}${os.platform() === 'win32' ? '.exe' : ''}`);
386
+ log(`Downloading ${downloadUrl} → ${newExePath}`);
387
+ await downloadFile(downloadUrl, newExePath, manifest.sha256);
388
+
389
+ // Persist the version label
390
+ try { fs.writeFileSync(path.join(stagingDir, 'VERSION'), String(manifest.version)); } catch {}
391
+
392
+ // Write swapper that replaces the running .exe with the new one
393
+ writeSwapperAndExitExe(newExePath, manifest);
394
+ }
395
+
396
+ /**
397
+ * Minimal ZIP extractor using Node's built-in zlib.
398
+ * Handles Store (0) + Deflate (8) ZIP methods, which covers .exe + .zip
399
+ * packaging. No external npm dependency.
400
+ */
401
+ function extractZip(zipPath, destDir) {
402
+ const buf = fs.readFileSync(zipPath);
403
+ // Find End-of-Central-Directory signature
404
+ let eocd = -1;
405
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
406
+ if (buf[i] === 0x50 && buf[i + 1] === 0x4b && buf[i + 2] === 0x05 && buf[i + 3] === 0x06) {
407
+ eocd = i;
408
+ break;
409
+ }
410
+ }
411
+ if (eocd === -1) throw new Error('Not a valid ZIP (no EOCD)');
412
+
413
+ const cdOffset = buf.readUInt32LE(eocd + 16);
414
+ const cdEntries = buf.readUInt16LE(eocd + 10);
415
+
416
+ let pos = cdOffset;
417
+ for (let i = 0; i < cdEntries; i++) {
418
+ if (buf.readUInt32LE(pos) !== 0x02014b50) throw new Error(`Bad central directory entry at ${pos}`);
419
+ const compMethod = buf.readUInt16LE(pos + 10);
420
+ const compSize = buf.readUInt32LE(pos + 20);
421
+ const uncompSize = buf.readUInt32LE(pos + 24);
422
+ const nameLen = buf.readUInt16LE(pos + 28);
423
+ const extraLen = buf.readUInt16LE(pos + 30);
424
+ const commentLen = buf.readUInt16LE(pos + 32);
425
+ const localHeaderOffset = buf.readUInt32LE(pos + 42);
426
+ const name = buf.slice(pos + 46, pos + 46 + nameLen).toString('utf8');
427
+ pos += 46 + nameLen + extraLen + commentLen;
428
+
429
+ const lhNameLen = buf.readUInt16LE(localHeaderOffset + 26);
430
+ const lhExtraLen = buf.readUInt16LE(localHeaderOffset + 28);
431
+ const dataStart = localHeaderOffset + 30 + lhNameLen + lhExtraLen;
432
+
433
+ if (name.endsWith('/')) {
434
+ fs.mkdirSync(path.join(destDir, name), { recursive: true });
435
+ continue;
436
+ }
437
+
438
+ const filePath = path.join(destDir, name);
439
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
440
+
441
+ let content;
442
+ if (compMethod === 0) {
443
+ content = buf.slice(dataStart, dataStart + compSize);
444
+ } else if (compMethod === 8) {
445
+ content = zlib.inflateRawSync(buf.slice(dataStart, dataStart + compSize));
446
+ } else {
447
+ throw new Error(`Unsupported ZIP compression method ${compMethod} for ${name}`);
448
+ }
449
+ fs.writeFileSync(filePath, content);
450
+ }
451
+ }
452
+
453
+ /**
454
+ * Write the swapper script and exit the current process. The swapper:
455
+ * - waits until our process exits
456
+ * - renames agentDir → agentDir.old-<ts>
457
+ * - renames staging/unpacked → agentDir
458
+ * - relaunches xkwdstore-agent.exe from new folder
459
+ * - deletes agentDir.old-<ts> in background
460
+ */
461
+ function writeSwapperAndExit(unpackedDir, manifest) {
462
+ const isWin = os.platform() === 'win32';
463
+ const pid = process.pid;
464
+ const backupDir = `${_agentDir}.old-${Date.now()}`;
465
+ const exeName = isWin ? 'xkwdstore-agent.exe' : 'xkwdstore-agent';
466
+ const newExe = path.join(_agentDir, exeName);
467
+ const launcherScript = isWin ? path.join(_agentDir, '..', '.xkwdstore-update.bat')
468
+ : path.join(_agentDir, '..', '.xkwdstore-update.sh');
469
+
470
+ if (isWin) {
471
+ const bat = `@echo off\r
472
+ setlocal\r
473
+ set "TARGET=${_agentDir}"\r
474
+ set "BACKUP=${backupDir}"\r
475
+ set "UNPACKED=${unpackedDir}"\r
476
+ set "EXE=${newExe}"\r
477
+ echo [xkwdstore-updater] Waiting for agent PID ${pid} to exit...\r
478
+ ${windowsWaitPidBlock(pid)}echo [xkwdstore-updater] Swapping folder...\r
479
+ ren "%TARGET%" "%~n0.old" 2>NUL\r
480
+ move /Y "%TARGET%" "%BACKUP%" 2>NUL\r
481
+ move /Y "%UNPACKED%" "%TARGET%"\r
482
+ echo [xkwdstore-updater] Relaunching agent...\r
483
+ ${windowsRelaunchExe(newExe)}echo [xkwdstore-updater] Cleaning up old folder in background...\r
484
+ rd /s /q "%BACKUP%" >NUL 2>&1\r
485
+ del "%~f0"\r
486
+ endlocal\r
487
+ `;
488
+ fs.writeFileSync(launcherScript, bat);
489
+ log(`Starting updater: ${launcherScript}`);
490
+ // Detached spawn — fire and forget
491
+ spawnHidden('cmd.exe', ['/c', launcherScript]).unref();
492
+ } else {
493
+ const sh = `#!/bin/sh
494
+ # xkwdstore-updater
495
+ while kill -0 ${pid} 2>/dev/null; do sleep 1; done
496
+ echo "[xkwdstore-updater] Swapping folder..."
497
+ mv "${_agentDir}" "${backupDir}"
498
+ mv "${unpackedDir}" "${_agentDir}"
499
+ chmod +x "${newExe}"
500
+ echo "[xkwdstore-updater] Relaunching agent..."
501
+ nohup "${newExe}" >/dev/null 2>&1 &
502
+ rm -rf "${backupDir}" >/dev/null 2>&1
503
+ rm -f "$0"
504
+ `;
505
+ fs.writeFileSync(launcherScript, sh);
506
+ fs.chmodSync(launcherScript, 0o755);
507
+ log(`Starting updater: ${launcherScript}`);
508
+ spawn('/bin/sh', [launcherScript], { detached: true, stdio: 'ignore' }).unref();
509
+ }
510
+
511
+ log('Update staged. Calling shutdown to allow swap-and-relaunch.');
512
+ if (_onShutdownRequest) _onShutdownRequest();
513
+ else process.exit(0);
514
+ }
515
+
516
+ /**
517
+ * Write a swapper script for a standalone .exe update (no zip).
518
+ * The swapper:
519
+ * - waits until our process exits
520
+ * - copies the new .exe over the running one
521
+ * - writes the VERSION file
522
+ * - relaunches the new .exe
523
+ * - deletes the staging file
524
+ */
525
+ function writeSwapperAndExitExe(newExePath, manifest) {
526
+ const isWin = os.platform() === 'win32';
527
+ const pid = process.pid;
528
+ const exeName = isWin ? 'xkwdstore-agent.exe' : 'xkwdstore-agent';
529
+ const currentExe = path.join(_agentDir, exeName);
530
+ const versionFile = path.join(_agentDir, 'VERSION');
531
+ const launcherScript = isWin ? path.join(_agentDir, '..', '.xkwdstore-update.bat')
532
+ : path.join(_agentDir, '..', '.xkwdstore-update.sh');
533
+
534
+ if (isWin) {
535
+ const bat = `@echo off\r
536
+ setlocal\r
537
+ set "TARGET=${currentExe}"\r
538
+ set "NEWEXE=${newExePath}"\r
539
+ set "VERSION=${manifest.version}"\r
540
+ set "VERSIONFILE=${versionFile}"\r
541
+ echo [xkwdstore-updater] Waiting for agent PID ${pid} to exit...\r
542
+ ${windowsWaitPidBlock(pid)}echo [xkwdstore-updater] Replacing .exe...\r
543
+ copy /Y "%NEWEXE%" "%TARGET%"\r
544
+ <nul set /p=%VERSION%> "%VERSIONFILE%"\r
545
+ echo [xkwdstore-updater] Relaunching agent...\r
546
+ ${windowsRelaunchExe(currentExe)}echo [xkwdstore-updater] Cleaning up...\r
547
+ del "%NEWEXE%" 2>NUL\r
548
+ del "%~f0"\r
549
+ endlocal\r
550
+ `;
551
+ fs.writeFileSync(launcherScript, bat);
552
+ log(`Starting updater: ${launcherScript}`);
553
+ spawnHidden('cmd.exe', ['/c', launcherScript]).unref();
554
+ } else {
555
+ const sh = `#!/bin/sh
556
+ # xkwdstore-updater (exe)
557
+ while kill -0 ${pid} 2>/dev/null; do sleep 1; done
558
+ echo "[xkwdstore-updater] Replacing executable..."
559
+ cp "${newExePath}" "${currentExe}"
560
+ chmod +x "${currentExe}"
561
+ echo "${manifest.version}" > "${versionFile}"
562
+ echo "[xkwdstore-updater] Relaunching agent..."
563
+ nohup "${currentExe}" >/dev/null 2>&1 &
564
+ rm -f "${newExePath}"
565
+ rm -f "$0"
566
+ `;
567
+ fs.writeFileSync(launcherScript, sh);
568
+ fs.chmodSync(launcherScript, 0o755);
569
+ log(`Starting updater: ${launcherScript}`);
570
+ spawn('/bin/sh', [launcherScript], { detached: true, stdio: 'ignore' }).unref();
571
+ }
572
+
573
+ log('Update staged (.exe). Calling shutdown to allow swap-and-relaunch.');
574
+ if (_onShutdownRequest) _onShutdownRequest();
575
+ else process.exit(0);
576
+ }
577
+
578
+ module.exports = { start, stop, forceCheckAndRestart, triggerSelfRestart, setWsConnected };