@xkwdstore/agent 2.0.1

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/cli.js ADDED
@@ -0,0 +1,529 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * XKWDStore Agent — Terminal-only CLI (protocol v2).
6
+ *
7
+ * Replaces the desktop-agent distribution, pairing-code workflow, updater,
8
+ * and in-memory WebSocket ticket architecture with a simpler, safer
9
+ * terminal-first system.
10
+ *
11
+ * Usage:
12
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> start
13
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> status
14
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
15
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
16
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
17
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> version
18
+ *
19
+ * The agent runs only while the terminal process is running.
20
+ * Closing the terminal or pressing Ctrl+C stops the agent cleanly.
21
+ */
22
+
23
+ const crypto = require('crypto');
24
+ const os = require('os');
25
+ const path = require('path');
26
+
27
+ const CLI_VERSION = '2.0.1';
28
+ const PROTOCOL_VERSION = 2;
29
+
30
+ // ── Command parsing ──────────────────────────────────────────────────────────
31
+
32
+ function main() {
33
+ const args = process.argv.slice(2);
34
+ const command = args[0] || 'help';
35
+ const flags = {};
36
+ const positional = [];
37
+
38
+ for (let i = 1; i < args.length; i++) {
39
+ const arg = args[i];
40
+ if (arg.startsWith('--')) {
41
+ const key = arg.slice(2);
42
+ const next = args[i + 1];
43
+ if (next && !next.startsWith('--')) {
44
+ flags[key] = next;
45
+ i++;
46
+ } else {
47
+ flags[key] = true;
48
+ }
49
+ } else {
50
+ positional.push(arg);
51
+ }
52
+ }
53
+
54
+ const serverOrigin = flags.server ||
55
+ process.env.XKWDSTORE_SERVER ||
56
+ 'https://x.kwdstore.com';
57
+
58
+ switch (command) {
59
+ case 'start':
60
+ return start(serverOrigin, flags);
61
+ case 'status':
62
+ return status();
63
+ case 'logout':
64
+ return logout();
65
+ case 'revoke-local':
66
+ return revokeLocal();
67
+ case 'doctor':
68
+ return doctor(serverOrigin);
69
+ case 'version':
70
+ return version();
71
+ case 'help':
72
+ case '--help':
73
+ case '-h':
74
+ default:
75
+ return help();
76
+ }
77
+ }
78
+
79
+ // ── Commands ─────────────────────────────────────────────────────────────────
80
+
81
+ /**
82
+ * `xkwd-agent start` — the main runtime command.
83
+ */
84
+ async function start(serverOrigin, flags) {
85
+ console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
86
+ console.log(`Server: ${serverOrigin}`);
87
+ console.log();
88
+
89
+ // 1. Detect OS and architecture (for display)
90
+ const platform = os.platform();
91
+ const arch = os.arch();
92
+ const hostname = os.hostname();
93
+ console.log(`✓ Detected computer: ${hostname}`);
94
+ console.log(`✓ Platform: ${platform} ${arch}`);
95
+
96
+ // 2. Resolve system Chrome (fail clearly if missing)
97
+ const { resolveChromeOrFail } = require('./chromeDetector');
98
+ let chromePath, chromeVersion;
99
+ try {
100
+ const chrome = resolveChromeOrFail();
101
+ chromePath = chrome.chromePath;
102
+ chromeVersion = chrome.chromeVersion;
103
+ console.log(`✓ Chrome ${chromeVersion || 'detected'}: ${chromePath}`);
104
+ } catch (e) {
105
+ console.error(e.message);
106
+ process.exit(1);
107
+ }
108
+
109
+ // 3. Check compatibility with server (shared strict validator)
110
+ const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
111
+ try {
112
+ const compatResp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
113
+ const compat = validateCompatibilityResponse(compatResp);
114
+ if (compat.html) {
115
+ console.error('\n' + COMPAT_HTML_MESSAGE);
116
+ process.exit(1);
117
+ }
118
+ if (!compat.ok) {
119
+ console.error('\nServer compatibility check failed: ' + compat.reason + '.');
120
+ console.error('The agent will not start enrollment until the server is compatible.');
121
+ process.exit(1);
122
+ }
123
+ // compat.ok — enforce minimum agent version
124
+ const minVer = compat.body.minimumAgentVersion;
125
+ const recVer = compat.body.recommendedAgentVersion;
126
+ if (minVer && _compareVersions(CLI_VERSION, minVer) < 0) {
127
+ console.error(`\nThis agent version (${CLI_VERSION}) is no longer supported.`);
128
+ console.error(`\nRun:\n\n npx --yes @xkwdstore/agent@${recVer} start\n`);
129
+ process.exit(1);
130
+ }
131
+ } catch (e) {
132
+ console.error(`\nServer compatibility check failed: ${e.message}`);
133
+ console.error('The agent will not start enrollment until the server is reachable and compatible.');
134
+ process.exit(1);
135
+ }
136
+
137
+ // 4. Load or generate device key
138
+ const { getStoredDevice, getStoredPrivateKey, enroll } = require('./enrollmentClient');
139
+ const { isSecureStorageAvailable } = require('./deviceKeyStore');
140
+
141
+ if (!isSecureStorageAvailable()) {
142
+ console.error('Secure key storage is unavailable on this system.');
143
+ if (os.platform() === 'win32') {
144
+ console.error('On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available.');
145
+ } else {
146
+ console.error('On Linux, install gnome-keyring or seahorse (libsecret).');
147
+ }
148
+ console.error('The agent cannot run without secure key storage.');
149
+ process.exit(1);
150
+ }
151
+
152
+ let deviceMeta = getStoredDevice();
153
+ let privateKeyB64Url = await getStoredPrivateKey();
154
+
155
+ // 5. Authorize the device when needed (first run or revoked)
156
+ if (!deviceMeta || !privateKeyB64Url) {
157
+ console.log('\n✓ Device identity loaded securely');
158
+ try {
159
+ const result = await enroll(serverOrigin);
160
+ deviceMeta = require('./deviceKeyStore').loadMetadata();
161
+ privateKeyB64Url = await getStoredPrivateKey();
162
+ } catch (e) {
163
+ console.error(`\nEnrollment failed: ${e.message}`);
164
+ process.exit(1);
165
+ }
166
+ } else {
167
+ console.log(`✓ Device identity loaded securely`);
168
+ console.log(`✓ Device recognized: ${deviceMeta.deviceName}`);
169
+ }
170
+
171
+ // 6. Process lock (prevent duplicate instances)
172
+ const processLock = require('./processLock');
173
+ const lockResult = processLock.acquireLock({
174
+ deviceId: deviceMeta.deviceId,
175
+ deviceName: deviceMeta.deviceName,
176
+ });
177
+
178
+ if (!lockResult.acquired) {
179
+ if (flags.replace) {
180
+ console.log('\nAnother agent instance is running. Requesting takeover...');
181
+ const took = await processLock.requestTakeover(lockResult.existing);
182
+ if (!took) {
183
+ console.error('Could not stop the existing instance. Please close it manually.');
184
+ process.exit(1);
185
+ }
186
+ // Re-acquire the lock
187
+ const retryLock = processLock.acquireLock({
188
+ deviceId: deviceMeta.deviceId,
189
+ deviceName: deviceMeta.deviceName,
190
+ });
191
+ if (!retryLock.acquired) {
192
+ console.error('Could not acquire process lock after takeover.');
193
+ process.exit(1);
194
+ }
195
+ } else {
196
+ console.error('\nXKWDStore Agent is already running on this computer.');
197
+ console.error(`PID: ${lockResult.existing.pid}`);
198
+ console.error(`Started: ${lockResult.existing.startedAt}`);
199
+ console.error(`Device: ${lockResult.existing.deviceName || 'unknown'}`);
200
+ console.error('\nTo replace the running instance, use:');
201
+ console.error(' xkwd-agent start --replace');
202
+ process.exit(1);
203
+ }
204
+ }
205
+
206
+ // 7. Connect securely via WebSocket challenge-response
207
+ const { connectWebSocket } = require('./wsClient');
208
+ let ws;
209
+ try {
210
+ ws = await connectWebSocket({
211
+ serverOrigin,
212
+ deviceId: deviceMeta.deviceId,
213
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
214
+ privateKeyB64Url,
215
+ protocolVersion: PROTOCOL_VERSION,
216
+ });
217
+ } catch (e) {
218
+ console.error(`\nConnection failed: ${e.message}`);
219
+ processLock.releaseLock();
220
+ process.exit(1);
221
+ }
222
+
223
+ console.log('✓ Secure challenge passed');
224
+ console.log('✓ Connected');
225
+ console.log('\nAgent is running. Press Ctrl+C to stop.\n');
226
+
227
+ // 8. Set up browser session handler (delegates to existing session management)
228
+ const { setupSessionHandler, closeAllSessions, markDisconnected } = require('./sessionHandler');
229
+ const sessions = setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
230
+
231
+ // 8a. Fail-safe: an authenticated WebSocket closure is not a recoverable
232
+ // event in this release. The agent must stop accepting commands, close every
233
+ // active browser context (preserving profiles/cookies via the existing
234
+ // safe persistence path), clear the sessions map, release the process
235
+ // lock, print a clear terminal error, and exit non-zero. We deliberately
236
+ // prefer a safe exit over incomplete automatic reconnection here; a future
237
+ // reconnect implementation is allowed only if it rebinds the full session
238
+ // handler, reconciles every lease, and is covered by deterministic tests.
239
+ //
240
+ // Race guard: `shuttingDown` is set by the deliberate Ctrl+C/SIGTERM path
241
+ // BEFORE ws.close() is called, so the close event emitted during a
242
+ // deliberate shutdown does NOT run the unexpected-disconnect fail-safe.
243
+ // This prevents closeAllSessions() from being executed concurrently twice
244
+ // and processLock.releaseLock() from being called twice.
245
+ let disconnected = false;
246
+ let shuttingDown = false;
247
+ ws.on('close', (code, reason) => {
248
+ // If a deliberate shutdown is in progress, the close event is expected —
249
+ // do NOT run the unexpected-disconnect fail-safe.
250
+ if (shuttingDown) return;
251
+ if (disconnected) return;
252
+ disconnected = true;
253
+ markDisconnected();
254
+ const reasonStr = reason ? reason.toString() : '';
255
+ console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
256
+ console.error(' Closing all browser sessions and shutting down safely...');
257
+ closeAllSessions().then(({ closed }) => {
258
+ if (closed > 0) console.error(` Closed ${closed} browser session(s).`);
259
+ }).catch(() => {}).finally(() => {
260
+ try { ws.close(1000, 'Agent shutting down after disconnect'); } catch {}
261
+ processLock.releaseLock();
262
+ // 4003 = authentication failed (revoked/unknown key) — re-enroll required.
263
+ if (code === 4003) {
264
+ console.error('\n❌ Authentication failed. This device may be revoked.');
265
+ console.error(' Run `xkwd-agent logout` then `xkwd-agent start` to re-authorize.');
266
+ } else {
267
+ console.error('\nTo reconnect, run `xkwd-agent start` again.');
268
+ }
269
+ console.error('Agent stopped.');
270
+ process.exit(1);
271
+ });
272
+ });
273
+
274
+ // 9. Clean shutdown on Ctrl+C
275
+ async function shutdown(signal) {
276
+ if (shuttingDown) return;
277
+ shuttingDown = true;
278
+ console.log(`\n${signal} received. Shutting down...`);
279
+
280
+ // Stop accepting commands immediately.
281
+ markDisconnected();
282
+
283
+ // Close all browser sessions (preserves profiles/cookies via the
284
+ // existing safe persistence path).
285
+ try {
286
+ await closeAllSessions();
287
+ } catch {}
288
+
289
+ // Close WebSocket
290
+ try { ws.close(1000, 'Agent shutting down'); } catch {}
291
+
292
+ // Release lock
293
+ processLock.releaseLock();
294
+
295
+ process.exit(0);
296
+ }
297
+
298
+ process.on('SIGINT', () => shutdown('Ctrl+C'));
299
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
300
+ process.on('SIGHUP', () => shutdown('SIGHUP'));
301
+
302
+ // Also release the lock on uncaught exceptions
303
+ process.on('uncaughtException', (err) => {
304
+ console.error('Uncaught error:', err.message);
305
+ processLock.releaseLock();
306
+ process.exit(1);
307
+ });
308
+ }
309
+
310
+ /**
311
+ * `xkwd-agent status` — show device and connection status.
312
+ */
313
+ function status() {
314
+ const { getStoredDevice } = require('./enrollmentClient');
315
+ const { isSecureStorageAvailable } = require('./deviceKeyStore');
316
+ const processLock = require('./processLock');
317
+
318
+ const device = getStoredDevice();
319
+ const lock = processLock.readLock();
320
+
321
+ console.log(`XKWDStore Agent v${CLI_VERSION}\n`);
322
+
323
+ if (!device) {
324
+ console.log('Status: Not authorized');
325
+ console.log('Run `xkwd-agent start` to authorize this computer.');
326
+ return;
327
+ }
328
+
329
+ console.log(`Device ID: ${device.deviceId}`);
330
+ console.log(`Device name: ${device.deviceName}`);
331
+ console.log(`Server: ${device.serverOrigin || 'https://x.kwdstore.com'}`);
332
+ console.log(`Public-key fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
333
+ console.log(`Created: ${device.createdAt || 'unknown'}`);
334
+ console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available' : 'unavailable'}`);
335
+
336
+ if (lock) {
337
+ console.log(`\nAgent process: RUNNING (PID ${lock.pid})`);
338
+ console.log(`Started: ${lock.startedAt}`);
339
+ } else {
340
+ console.log('\nAgent process: not running');
341
+ }
342
+ }
343
+
344
+ /**
345
+ * `xkwd-agent logout` — delete local device identity (re-enrollment required).
346
+ */
347
+ async function logout() {
348
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
349
+ const processLock = require('./processLock');
350
+
351
+ const lock = processLock.readLock();
352
+ if (lock) {
353
+ console.error('Agent is currently running. Stop it first with Ctrl+C.');
354
+ process.exit(1);
355
+ }
356
+
357
+ await deletePrivateKey();
358
+ deleteMetadata();
359
+ console.log('Local device identity deleted.');
360
+ console.log('Run `xkwd-agent start` to re-authorize this computer.');
361
+ }
362
+
363
+ /**
364
+ * `xkwd-agent revoke-local` — same as logout but also clears the process lock.
365
+ */
366
+ async function revokeLocal() {
367
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
368
+ await deletePrivateKey();
369
+ deleteMetadata();
370
+ console.log('Local device identity and credentials revoked.');
371
+ console.log('The server-side device record should also be revoked from the dashboard.');
372
+ }
373
+
374
+ /**
375
+ * `xkwd-agent doctor` — diagnostic checks.
376
+ */
377
+ async function doctor(serverOrigin) {
378
+ console.log(`XKWDStore Agent v${CLI_VERSION} — Diagnostics\n`);
379
+
380
+ // Check Node version
381
+ const nodeVersion = process.versions.node;
382
+ const major = parseInt(nodeVersion.split('.')[0], 10);
383
+ console.log(`Node.js: ${nodeVersion} ${major >= 22 ? '✓' : '✗ (requires Node.js 22+)'}`);
384
+
385
+ // Check platform
386
+ console.log(`Platform: ${os.platform()} ${os.arch()}`);
387
+ console.log(`Hostname: ${os.hostname()}`);
388
+
389
+ // Check Chrome
390
+ try {
391
+ const { resolveChromeOrFail } = require('./chromeDetector');
392
+ const chrome = resolveChromeOrFail();
393
+ console.log(`Chrome: ${chrome.chromeVersion || 'detected'} ✓`);
394
+ } catch (e) {
395
+ console.log(`Chrome: ✗ (${e.message.split('\n')[0]})`);
396
+ }
397
+
398
+ // Check secure storage (real DPAPI + ACL probe on Windows)
399
+ const { isSecureStorageAvailable, getDataDir, probeWindowsStorage } = require('./deviceKeyStore');
400
+ const platform = os.platform();
401
+ if (platform === 'win32') {
402
+ console.log('Secure storage: probing real DPAPI + ACL stages...');
403
+ const probe = probeWindowsStorage();
404
+ console.log(` DPAPI Protect : ${probe.stages.protect ? '✓' : '✗'}`);
405
+ console.log(` DPAPI Unprotect: ${probe.stages.unprotect ? '✓' : '✗'}`);
406
+ console.log(` Windows SID : ${probe.stages.sidLookup ? '✓' : '✗'}`);
407
+ console.log(` ACL apply : ${probe.stages.aclApply ? '✓' : '✗'}`);
408
+ console.log(` ACL verify : ${probe.stages.aclVerify ? '✓' : '✗'}`);
409
+ console.log(`Secure storage: ${probe.ok ? 'available ✓' : 'unavailable ✗'}`);
410
+ if (!probe.ok && probe.detail) {
411
+ console.log(` Detail: ${probe.detail}`);
412
+ }
413
+ } else {
414
+ console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available ✓' : 'unavailable ✗'}`);
415
+ }
416
+
417
+ // Check data directory
418
+ const dataDir = getDataDir();
419
+ console.log(`Data directory: ${dataDir}`);
420
+
421
+ // Check device identity
422
+ const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
423
+ const device = getStoredDevice();
424
+ if (device) {
425
+ console.log(`Device ID: ${device.deviceId} ✓`);
426
+ const privateKey = await getStoredPrivateKey();
427
+ console.log(`Private key: ${privateKey ? 'stored ✓' : 'missing ✗'}`);
428
+ } else {
429
+ console.log('Device ID: not enrolled');
430
+ }
431
+
432
+ // Check server connectivity (shared strict validator)
433
+ try {
434
+ const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
435
+ const resp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
436
+ const compat = validateCompatibilityResponse(resp);
437
+ if (compat.html) {
438
+ console.log(`Server (${serverOrigin}): compatibility endpoint returned frontend ✗`);
439
+ console.log(' ' + COMPAT_HTML_MESSAGE);
440
+ } else if (compat.ok) {
441
+ console.log(`Server (${serverOrigin}): reachable ✓`);
442
+ console.log(` Protocol version: ${compat.body.protocolVersion}`);
443
+ console.log(` Min agent version: ${compat.body.minimumAgentVersion}`);
444
+ console.log(` Recommended agent version: ${compat.body.recommendedAgentVersion}`);
445
+ } else {
446
+ console.log(`Server (${serverOrigin}): compatibility check failed ✗`);
447
+ console.log(` Reason: ${compat.reason}`);
448
+ }
449
+ } catch (e) {
450
+ console.log(`Server (${serverOrigin}): unreachable ✗ (${e.message})`);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * `xkwd-agent version` — print version.
456
+ */
457
+ function version() {
458
+ console.log(`@xkwdstore/agent v${CLI_VERSION}`);
459
+ console.log(`Protocol version: ${PROTOCOL_VERSION}`);
460
+ console.log(`Node.js: ${process.versions.node}`);
461
+ }
462
+
463
+ /**
464
+ * `xkwd-agent help` — print help.
465
+ */
466
+ function help() {
467
+ console.log(`XKWDStore Agent v${CLI_VERSION}
468
+
469
+ Usage:
470
+ xkwd-agent <command> [options]
471
+
472
+ Commands:
473
+ start Start the agent (connects to server, runs browser sessions)
474
+ status Show device and connection status
475
+ logout Delete local device identity (requires re-authorization)
476
+ revoke-local Delete local device identity and credentials
477
+ doctor Run diagnostic checks
478
+ version Print version information
479
+ help Show this help
480
+
481
+ Options:
482
+ --server=<url> Server URL (default: https://x.kwdstore.com)
483
+ --replace Replace a running instance (safe takeover)
484
+
485
+ Examples:
486
+ xkwd-agent start
487
+ xkwd-agent start --replace
488
+ xkwd-agent status
489
+ xkwd-agent doctor
490
+
491
+ First run:
492
+ The agent will open your browser to authorize this computer.
493
+ No pairing code, email, or API key is required.
494
+
495
+ To stop:
496
+ Press Ctrl+C in the terminal.
497
+
498
+ Data location:
499
+ Windows: %LOCALAPPDATA%\\XKWDStore\\
500
+ macOS: ~/Library/Application Support/XKWDStore/
501
+ Linux: ~/.local/share/xkwdstore/
502
+
503
+ Requirements:
504
+ - Node.js 22 or later
505
+ - Google Chrome installed
506
+ `);
507
+ }
508
+
509
+ // ── Helpers ──────────────────────────────────────────────────────────────────
510
+
511
+ function _compareVersions(a, b) {
512
+ const pa = a.split('.').map(Number);
513
+ const pb = b.split('.').map(Number);
514
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
515
+ const va = pa[i] || 0;
516
+ const vb = pb[i] || 0;
517
+ if (va > vb) return 1;
518
+ if (va < vb) return -1;
519
+ }
520
+ return 0;
521
+ }
522
+
523
+ // ── Entry point ──────────────────────────────────────────────────────────────
524
+
525
+ if (require.main === module) {
526
+ main();
527
+ }
528
+
529
+ module.exports = { main, CLI_VERSION, PROTOCOL_VERSION };
@@ -0,0 +1,98 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Agent config persistence with protected long-lived credentials (Phase 10/11).
5
+ *
6
+ * The on-disk config.json NEVER contains a plaintext long-lived credential. The
7
+ * long-lived values — the legacy device token (pre-Phase-10) and the Phase 10
8
+ * rotating refresh credential — are protected at rest (see secretStore — DPAPI
9
+ * on Windows) and stored under `deviceTokenProtected` / `deviceRefreshProtected`.
10
+ * In memory, the config exposes `deviceToken` / `deviceRefresh` as plaintext for
11
+ * the connection logic; those fields are stripped before writing.
12
+ *
13
+ * The short-lived device access JWT (`deviceAccessToken`, ~15m) is low-value and
14
+ * short-lived, so it is stored as plaintext — its theft is bounded by its expiry
15
+ * and it is useless without the refresh credential that re-issues it.
16
+ *
17
+ * Legacy pre-Phase-11 configs that stored a plaintext `deviceToken` string are
18
+ * migrated transparently: loadConfig reads it into memory as plaintext, and the
19
+ * next saveConfig replaces it with a protected envelope.
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const { protectSecret, unprotectSecret } = require('./secretStore');
24
+
25
+ const DEFAULTS = {
26
+ serverUrl: null,
27
+ deviceToken: null, // legacy 365d JWT (pre-Phase-10 devices), kept until migration
28
+ deviceAccessToken: null, // short-lived two-level access JWT (Phase 10)
29
+ deviceRefresh: null, // long-lived rotating opaque refresh (Phase 10)
30
+ deviceId: null, // Phase 14: this device's immutable UUID (not a secret)
31
+ profileRoot: null,
32
+ browserChannel: 'chromium',
33
+ headless: false,
34
+ maxSessions: 5,
35
+ };
36
+
37
+ // Long-lived secrets that must be DPAPI-protected at rest. The short-lived
38
+ // access token is intentionally NOT in this list.
39
+ const PROTECTED_FIELDS = [
40
+ { plain: 'deviceToken', envelope: 'deviceTokenProtected' },
41
+ { plain: 'deviceRefresh', envelope: 'deviceRefreshProtected' },
42
+ ];
43
+
44
+ /**
45
+ * Load and return an in-memory config (plaintext long-lived credentials).
46
+ * Returns defaults if the file is missing or unreadable — credentials are null
47
+ * in that case.
48
+ */
49
+ function loadConfig(configPath) {
50
+ let raw;
51
+ try {
52
+ raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
53
+ } catch {
54
+ return { ...DEFAULTS };
55
+ }
56
+ const cfg = { ...DEFAULTS, ...raw };
57
+
58
+ for (const { plain, envelope } of PROTECTED_FIELDS) {
59
+ if (raw[envelope]) {
60
+ // Protected envelope → unwrap to plaintext in memory.
61
+ cfg[plain] = unprotectSecret(raw[envelope]);
62
+ } else if (typeof raw[plain] === 'string' && raw[plain]) {
63
+ // Legacy plaintext value — kept in memory, migrated to protected on save.
64
+ cfg[plain] = raw[plain];
65
+ } else {
66
+ cfg[plain] = null;
67
+ }
68
+ // Never carry the protected envelope (or a stale plaintext field) in memory.
69
+ delete cfg[envelope];
70
+ }
71
+
72
+ // deviceAccessToken is plaintext (short-lived). Coerce to null if absent.
73
+ if (typeof cfg.deviceAccessToken !== 'string' || !cfg.deviceAccessToken) {
74
+ cfg.deviceAccessToken = null;
75
+ }
76
+
77
+ return cfg;
78
+ }
79
+
80
+ /**
81
+ * Persist config. Long-lived credentials are protected and stored under their
82
+ * `*Protected` envelope keys; the plaintext fields are never written to disk.
83
+ */
84
+ function saveConfig(configPath, config) {
85
+ const persist = { ...config };
86
+ for (const { plain, envelope } of PROTECTED_FIELDS) {
87
+ if (persist[plain] && typeof persist[plain] === 'string') {
88
+ persist[envelope] = protectSecret(persist[plain]);
89
+ }
90
+ // Ensure the plaintext long-lived credential is never written to disk,
91
+ // whether or not one is present.
92
+ delete persist[plain];
93
+ }
94
+ // deviceAccessToken (short-lived) is written as plaintext by design.
95
+ fs.writeFileSync(configPath, JSON.stringify(persist, null, 2), 'utf8');
96
+ }
97
+
98
+ module.exports = { loadConfig, saveConfig, DEFAULTS };