@xkwdstore/agent 2.0.7 → 2.1.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.
@@ -48,25 +48,54 @@ function _powershellExe() {
48
48
 
49
49
  // ── Data directory resolution ────────────────────────────────────────────────
50
50
 
51
+ const machineState = require('./machineState');
52
+
51
53
  /**
52
- * Resolve the standard application-data directory for XKWDStore.
54
+ * Resolve the durable agent data root.
55
+ *
56
+ * 2.1.0 — MACHINE SCOPE. The root is now the machine-wide ProgramData layout
57
+ * (see machineState.js): `%ProgramData%\XKWDStore\Agent\`. Device identity
58
+ * therefore belongs to the MACHINE, not to the Windows user that happens to be
59
+ * logged in: switching Windows users (or the TW-manager preferred device) no
60
+ * longer mints a second device identity for one physical PC.
53
61
  *
54
- * Windows: %LOCALAPPDATA%\XKWDStore\
55
- * macOS: ~/Library/Application Support/XKWDStore/
56
- * Linux: ${XDG_DATA_HOME:-~/.local/share}/xkwdstore/
62
+ * Windows: %ProgramData%\XKWDStore\Agent\
63
+ * Linux: ${XDG_DATA_HOME:-~/.local/share}/xkwdstore/ (dev/CI; see override)
64
+ * macOS: unsupported (fails closed)
65
+ *
66
+ * `XKWDSTORE_MACHINE_ROOT` overrides the root for hermetic tests and portable
67
+ * installs. The legacy per-user root is migrated FROM (copy, never move) by
68
+ * machineState.adoptLegacyState(); it remains readable as a fallback so an
69
+ * env-locked test/dev machine that still only has per-user state keeps working.
57
70
  */
58
71
  function getDataDir() {
59
- const platform = os.platform();
60
- if (platform === 'win32') {
61
- return path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'XKWDStore');
62
- }
63
- if (platform === 'darwin') {
64
- return path.join(os.homedir(), 'Library', 'Application Support', 'XKWDStore');
72
+ return machineState.getMachineRoot();
73
+ }
74
+
75
+ /** The pre-2.1.0 per-user root (read-only fallback + migration source). */
76
+ function getLegacyDataDir() {
77
+ return machineState.getLegacyUserRoot();
78
+ }
79
+
80
+ /** The machine-wide root (ProgramData). */
81
+ function getMachineRoot() {
82
+ return machineState.getMachineRoot();
83
+ }
84
+
85
+ // One-time machine adoption, executed at module load so every consumer
86
+ // (identity, credentials, profiles, logs) resolves the durable root. Best-effort
87
+ // and idempotent: a failure leaves the legacy tree intact and usable.
88
+ let _machineInit = null;
89
+ function _initMachineState() {
90
+ if (_machineInit) return _machineInit;
91
+ try {
92
+ _machineInit = machineState.initializeMachineState();
93
+ } catch (e) {
94
+ _machineInit = { root: machineState.getMachineRoot(), adopted: false, reason: 'init-failed: ' + ((e && e.message) || 'unknown'), deviceId: null };
65
95
  }
66
- // Linux / other Unix
67
- const xdg = process.env.XDG_DATA_HOME;
68
- return path.join(xdg || path.join(os.homedir(), '.local', 'share'), 'xkwdstore');
96
+ return _machineInit;
69
97
  }
98
+ _initMachineState();
70
99
 
71
100
  const DATA_DIR = getDataDir();
72
101
 
@@ -151,14 +180,14 @@ function normalizeServerOrigin(serverOrigin) {
151
180
  /**
152
181
  * Resolve the server-scoped data directory for a given server origin.
153
182
  *
154
- * %LOCALAPPDATA%\XKWDStore\servers\<normalized-origin>\
155
- *
156
- * Creates the directory if it does not exist.
183
+ * 2.1.0 — resolves under the WRITE target (the machine root). The pre-2.1.0
184
+ * layout `%LOCALAPPDATA%\XKWDStore\servers\<normalized-origin>\` is the
185
+ * migration source and remains readable via loadMetadata()/_loadWindows().
157
186
  */
158
187
  function getServerDataDir(serverOrigin) {
159
188
  const label = normalizeServerOrigin(serverOrigin);
160
- const dir = path.join(DATA_DIR, 'servers', label);
161
- return dir;
189
+ const { target } = _identitySourceRoots();
190
+ return path.join(_serversDirFor(target), label);
162
191
  }
163
192
 
164
193
  /**
@@ -186,6 +215,62 @@ const METADATA_FILE = path.join(DATA_DIR, 'device-metadata.json');
186
215
  const PROFILES_DIR = path.join(DATA_DIR, 'profiles');
187
216
  const LOGS_DIR = path.join(DATA_DIR, 'logs');
188
217
 
218
+ /**
219
+ * Resolve which root is the READ source for identity, and which is the WRITE
220
+ * target. Normally both are the machine root. When the machine root has no
221
+ * identity yet but the legacy per-user root does (e.g. adoption failed, or an
222
+ * env-locked dev/CI machine), reads fall back to the legacy root so an
223
+ * existing deviceId is never orphaned and a NEW identity is never minted over
224
+ * a valid one.
225
+ */
226
+ function _identitySourceRoots() {
227
+ const machine = getMachineRoot();
228
+ const legacy = getLegacyDataDir();
229
+ if (path.resolve(machine) === path.resolve(legacy)) {
230
+ return { source: machine, target: machine };
231
+ }
232
+ // The machine layout keeps server identities under state/servers/ (see
233
+ // machineState.paths.serverStates); the legacy per-user layout used servers/.
234
+ const machineServersDir = machineState.paths.serverStates;
235
+ const legacyServersDir = path.join(legacy, 'servers');
236
+ const machineHasTopLevel = fs.existsSync(path.join(machine, 'device-metadata.json'));
237
+
238
+ const _hasScoped = (dir) => {
239
+ try {
240
+ if (!fs.existsSync(dir)) return false;
241
+ return fs.readdirSync(dir).some((n) => {
242
+ try { return fs.existsSync(path.join(dir, n, 'device-metadata.json')); } catch { return false; }
243
+ });
244
+ } catch { return false; }
245
+ };
246
+ const machineHasScoped = _hasScoped(machineServersDir);
247
+ const legacyHasScoped = _hasScoped(legacyServersDir);
248
+ const legacyHasTopLevel = fs.existsSync(path.join(legacy, 'device-metadata.json'));
249
+
250
+ // Machine root already holds an identity (scoped or top-level) → it is the
251
+ // single source; never mix in legacy state.
252
+ if (machineHasScoped || machineHasTopLevel) {
253
+ return { source: machine, target: machine };
254
+ }
255
+ if (legacyHasScoped || legacyHasTopLevel) {
256
+ // Nothing on the machine yet but a legacy identity exists: READ legacy (so
257
+ // adoption can preserve its deviceId) and WRITE the result to the machine
258
+ // root, making the next run fully machine-scoped.
259
+ return { source: legacy, target: machine };
260
+ }
261
+ return { source: machine, target: machine };
262
+ }
263
+
264
+ /**
265
+ * The servers/ directory that holds server-scoped identities for a given root.
266
+ * The machine root uses state/servers; the legacy root uses servers.
267
+ */
268
+ function _serversDirFor(root) {
269
+ return path.resolve(root) === path.resolve(getMachineRoot())
270
+ ? machineState.paths.serverStates
271
+ : path.join(root, 'servers');
272
+ }
273
+
189
274
  // ── Legacy migration (server-scoping) ───────────────────────────────────────
190
275
 
191
276
  /**
@@ -198,13 +283,18 @@ const LOGS_DIR = path.join(DATA_DIR, 'logs');
198
283
  * 3. The legacy file is NEVER deleted — it stays as a backup until the
199
284
  * user explicitly re-authorizes or logs out for that server.
200
285
  *
286
+ * 2.1.0 — the source root may be EITHER the machine root (ProgramData) or the
287
+ * legacy per-user root, because a machine that has not yet adopted per-user
288
+ * state must still find its identity. Both are probed; the machine root wins.
289
+ *
201
290
  * This function never throws — migration failure should not block startup.
202
291
  */
203
292
  function _migrateLegacyIdentity(serverOrigin) {
204
293
  if (!serverOrigin) return;
294
+ const roots = _identitySourceRoots();
205
295
  try {
206
- const legacyMetaFile = path.join(DATA_DIR, 'device-metadata.json');
207
- const legacyKeyFile = path.join(DATA_DIR, '.device-key');
296
+ const legacyMetaFile = path.join(roots.source, 'device-metadata.json');
297
+ const legacyKeyFile = path.join(roots.source, '.device-key');
208
298
  if (!fs.existsSync(legacyMetaFile)) return;
209
299
 
210
300
  const legacyMeta = JSON.parse(fs.readFileSync(legacyMetaFile, 'utf8'));
@@ -220,7 +310,6 @@ function _migrateLegacyIdentity(serverOrigin) {
220
310
  const scopedDir = getServerDataDir(serverOrigin);
221
311
  const scopedMetaFile = path.join(scopedDir, 'device-metadata.json');
222
312
  const scopedKeyFile = path.join(scopedDir, '.device-key');
223
-
224
313
  // If the scoped metadata already exists, the migration was already done.
225
314
  if (fs.existsSync(scopedMetaFile)) return;
226
315
 
@@ -354,14 +443,17 @@ async function deletePrivateKey(opts) {
354
443
  const serverOrigin = opts && opts.serverOrigin;
355
444
 
356
445
  if (platform === 'win32') {
357
- // Delete scoped key if serverOrigin is provided
358
- if (serverOrigin) {
359
- const keyFile = _keyFile(serverOrigin);
360
- try { if (fs.existsSync(keyFile)) fs.unlinkSync(keyFile); } catch {}
446
+ // Delete scoped + top-level key on BOTH the machine root and the legacy
447
+ // per-user root — a logout must not leave a usable identity behind on the
448
+ // other root, where a later run could resurrect it.
449
+ for (const root of _allRoots()) {
450
+ if (serverOrigin) {
451
+ const keyFile = path.join(_serversDirFor(root), normalizeServerOrigin(serverOrigin), '.device-key');
452
+ try { if (fs.existsSync(keyFile)) fs.unlinkSync(keyFile); } catch {}
453
+ }
454
+ const legacyKeyFile = path.join(root, '.device-key');
455
+ try { if (fs.existsSync(legacyKeyFile)) fs.unlinkSync(legacyKeyFile); } catch {}
361
456
  }
362
- // Also delete legacy top-level key
363
- const legacyKeyFile = path.join(DATA_DIR, '.device-key');
364
- try { if (fs.existsSync(legacyKeyFile)) fs.unlinkSync(legacyKeyFile); } catch {}
365
457
  return;
366
458
  }
367
459
  if (platform === 'darwin') {
@@ -386,11 +478,44 @@ async function deletePrivateKey(opts) {
386
478
 
387
479
  // ── Windows: DPAPI (Defect 10 fix: pass secret via stdin, not argv) ──────────
388
480
 
481
+ /**
482
+ * DPAPI scope policy (2.1.0).
483
+ *
484
+ * CurrentUser — decryptable only by the SAME Windows user on the same machine.
485
+ * This ties the machine credential to one Windows account, so a
486
+ * broker running under a service identity or a DIFFERENT Windows
487
+ * user cannot read it.
488
+ * LocalMachine — decryptable by any process on the machine that has READ access
489
+ * to the encrypted blob. This is what makes the credential usable
490
+ * by a machine-wide broker regardless of which Windows user is
491
+ * logged in, PROVIDED the blob's ACL restricts read to the
492
+ * broker's identity (owner + Administrators + SYSTEM).
493
+ *
494
+ * The scope is recorded IN the envelope so load() never guesses: a CurrentUser
495
+ * blob is decrypted as CurrentUser and a LocalMachine blob as LocalMachine.
496
+ *
497
+ * Default remains CurrentUser for backward compatibility with existing installs;
498
+ * the machine-wide service model selects LocalMachine via XKWDSTORE_DPAPI_SCOPE
499
+ * (and the installer sets it for the service install).
500
+ *
501
+ * THREAT MODEL (documented, not hand-waved): with LocalMachine scope, an
502
+ * administrator/SYSTEM can always recover the secret (they can take ownership).
503
+ * The protection is against ORDINARY OTHER USERS: without read access to the
504
+ * file, they cannot obtain the ciphertext to submit for decryption, and the ACL
505
+ * is verified to deny broad principals. This is the same trust boundary as the
506
+ * profile ACLs (another local admin is out of scope).
507
+ */
508
+ function _dpapiScopeName() {
509
+ const raw = String(process.env.XKWDSTORE_DPAPI_SCOPE || '').trim().toLowerCase();
510
+ return raw === 'localmachine' ? 'LocalMachine' : 'CurrentUser';
511
+ }
512
+
389
513
  function _storeWindows(privateKeyB64Url, opts) {
390
514
  const { execFileSync } = require('child_process');
391
515
  // Defect 10: The secret is passed via STDIN, not in the command string.
392
516
  // The PowerShell script reads from stdin and feeds it to DPAPI.
393
517
  // The process command line never contains the private key.
518
+ const scope = _dpapiScopeName();
394
519
  const ps =
395
520
  "$ErrorActionPreference='Stop'; " +
396
521
  "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
@@ -398,7 +523,7 @@ function _storeWindows(privateKeyB64Url, opts) {
398
523
  "$in = [Console]::In.ReadToEnd(); " +
399
524
  "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in); " +
400
525
  "$b = [System.Security.Cryptography.ProtectedData]::Protect(" +
401
- "$bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
526
+ "$bytes, $null, [System.Security.Cryptography.DataProtectionScope]::" + scope + "); " +
402
527
  "[Console]::Out.Write([Convert]::ToBase64String($b))";
403
528
 
404
529
  // Injectable stage functions (for deterministic testing). In production these
@@ -434,7 +559,7 @@ function _storeWindows(privateKeyB64Url, opts) {
434
559
  const keyFile = serverOrigin ? _keyFile(serverOrigin) : path.join(DATA_DIR, '.device-key');
435
560
  const tmpFile = path.join(keyDir, `.device-key.tmp.${crypto.randomBytes(6).toString('hex')}`);
436
561
  try {
437
- fs.writeFileSync(tmpFile, JSON.stringify({ scheme: 'dpapi', value: protected64, v: 1 }), {
562
+ fs.writeFileSync(tmpFile, JSON.stringify({ scheme: 'dpapi', scope, value: protected64, v: 2 }), {
438
563
  encoding: 'utf8',
439
564
  });
440
565
  } catch (e) {
@@ -483,16 +608,23 @@ function _loadWindows(opts) {
483
608
  const { execFileSync } = require('child_process');
484
609
  const serverOrigin = opts && opts.serverOrigin;
485
610
 
486
- // Try the server-scoped key file first. If it doesn't exist, try the legacy
487
- // top-level key file (for migration). If neither exists, return null.
488
- const scopedKeyFile = serverOrigin ? _keyFile(serverOrigin) : null;
489
- const legacyKeyFile = path.join(DATA_DIR, '.device-key');
611
+ // Try the server-scoped key file first, on BOTH roots (machine root first,
612
+ // then the legacy per-user root as a migration fallback). If neither exists,
613
+ // try the top-level key file on both roots. If none exist, return null.
614
+ const { source, target } = _identitySourceRoots();
615
+ const readRoots = [source];
616
+ if (path.resolve(source) !== path.resolve(target)) readRoots.push(target);
617
+
618
+ const candidates = [];
619
+ if (serverOrigin) {
620
+ const label = normalizeServerOrigin(serverOrigin);
621
+ for (const root of readRoots) candidates.push(path.join(_serversDirFor(root), label, '.device-key'));
622
+ }
623
+ for (const root of readRoots) candidates.push(path.join(root, '.device-key'));
490
624
 
491
625
  let keyFile = null;
492
- if (scopedKeyFile && fs.existsSync(scopedKeyFile)) {
493
- keyFile = scopedKeyFile;
494
- } else if (fs.existsSync(legacyKeyFile)) {
495
- keyFile = legacyKeyFile;
626
+ for (const c of candidates) {
627
+ if (fs.existsSync(c)) { keyFile = c; break; }
496
628
  }
497
629
 
498
630
  if (!keyFile) return null;
@@ -505,6 +637,10 @@ function _loadWindows(opts) {
505
637
  if (envelope.scheme !== 'dpapi' || !envelope.value) {
506
638
  throw new Error('Invalid key envelope');
507
639
  }
640
+ // Honor the RECORDED scope. A v1 envelope (no scope) was written with
641
+ // CurrentUser, so it decrypts as CurrentUser; a v2 envelope records the
642
+ // exact scope it was protected with.
643
+ const scope = envelope.scope === 'LocalMachine' ? 'LocalMachine' : 'CurrentUser';
508
644
 
509
645
  // Defect 10: Pass the protected blob via stdin, not in the command string.
510
646
  const ps =
@@ -514,7 +650,7 @@ function _loadWindows(opts) {
514
650
  "$in = [Console]::In.ReadToEnd().Trim(); " +
515
651
  "$b = [System.Security.Cryptography.ProtectedData]::Unprotect(" +
516
652
  "[Convert]::FromBase64String($in), " +
517
- "$null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
653
+ "$null, [System.Security.Cryptography.DataProtectionScope]::" + scope + "); " +
518
654
  "[Console]::Out.Write([Convert]::ToBase64String($b))";
519
655
 
520
656
  const b64 = execFileSync(_powershellExe(),
@@ -529,11 +665,94 @@ function _loadWindows(opts) {
529
665
 
530
666
  return Buffer.from(b64, 'base64').toString('utf8');
531
667
  } catch (e) {
532
- // Fail closed — do NOT fall back to plaintext
668
+ // Fail closed — do NOT fall back to plaintext. But make the reason VISIBLE:
669
+ // a silent null hid a real ACL-verify failure in the LocalSystem service
670
+ // context. The message carries no secret (stage/code only).
671
+ try {
672
+ const why = (e && e.message) ? String(e.message).slice(0, 200) : 'unknown';
673
+ process.stderr.write(`[deviceKeyStore] windows key load failed for ${keyFile}: ${why}\n`);
674
+ } catch { /* logging must never break the load path */ }
533
675
  return null;
534
676
  }
535
677
  }
536
678
 
679
+ /**
680
+ * Re-protect an EXISTING Windows device-key under a different DPAPI scope
681
+ * (2.1.0 machine-wide service model).
682
+ *
683
+ * WHY: a legacy/adopted identity is a v1 CurrentUser blob. The machine-wide
684
+ * broker runs as a service identity (LocalSystem), which cannot decrypt a
685
+ * CurrentUser blob. The installer (running elevated as the OWNER user, who CAN
686
+ * decrypt the CurrentUser blob) calls this to re-protect the SAME key material
687
+ * under LocalMachine scope WITHOUT changing the key itself — so the deviceId and
688
+ * pairing are preserved and the service broker can use the machine identity.
689
+ *
690
+ * SAFETY: does nothing if the blob is already LocalMachine. The re-protected
691
+ * blob is written to a temp file, the ACL is applied + verified BEFORE the atomic
692
+ * rename, and a rollback restores the prior blob on any failure — so the machine
693
+ * identity is never left unreadable.
694
+ *
695
+ * @param {object} opts — { serverOrigin, targetScope, keyFile }
696
+ * @returns {{ ok:boolean, changed:boolean, from:string, to:string, detail:string }}
697
+ */
698
+ function rescopeWindowsKey(opts = {}) {
699
+ if (os.platform() !== 'win32') return { ok: false, changed: false, from: '', to: '', detail: 'Windows-only' };
700
+ const targetScope = opts.targetScope === 'CurrentUser' ? 'CurrentUser' : 'LocalMachine';
701
+ const keyFile = opts.keyFile || (opts.serverOrigin ? _keyFile(opts.serverOrigin) : path.join(DATA_DIR, '.device-key'));
702
+ if (!keyFile || !fs.existsSync(keyFile)) return { ok: false, changed: false, from: '', to: '', detail: 'no key file at ' + keyFile };
703
+
704
+ let envelope;
705
+ try { envelope = JSON.parse(fs.readFileSync(keyFile, 'utf8')); } catch { return { ok: false, changed: false, from: '', to: '', detail: 'unreadable envelope' }; }
706
+ if (!envelope || envelope.scheme !== 'dpapi' || !envelope.value) return { ok: false, changed: false, from: '', to: '', detail: 'not a dpapi envelope' };
707
+
708
+ const fromScope = envelope.scope === 'LocalMachine' ? 'LocalMachine' : 'CurrentUser';
709
+ if (fromScope === targetScope) return { ok: true, changed: false, from: fromScope, to: targetScope, detail: 'already ' + targetScope };
710
+
711
+ // 1. Decrypt under the RECORDED scope (the owner user can do this).
712
+ const { execFileSync } = require('child_process');
713
+ const unprotect = (blob, scope) => {
714
+ const ps = "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.Encoding]::ASCII; Add-Type -AssemblyName System.Security; " +
715
+ "$in=[Console]::In.ReadToEnd().Trim(); $b=[System.Security.Cryptography.ProtectedData]::Unprotect([Convert]::FromBase64String($in),$null,[System.Security.Cryptography.DataProtectionScope]::" + scope + "); [Console]::Out.Write([Convert]::ToBase64String($b))";
716
+ return execFileSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', ps], { windowsHide: true, encoding: 'utf8', timeout: 15000, input: blob }).trim();
717
+ };
718
+ const protect = (plain, scope) => {
719
+ const ps = "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.Encoding]::ASCII; Add-Type -AssemblyName System.Security; " +
720
+ "$in=[Console]::In.ReadToEnd(); $b=[System.Security.Cryptography.ProtectedData]::Protect([System.Text.Encoding]::UTF8.GetBytes($in),$null,[System.Security.Cryptography.DataProtectionScope]::" + scope + "); [Console]::Out.Write([Convert]::ToBase64String($b))";
721
+ return execFileSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', ps], { windowsHide: true, encoding: 'utf8', timeout: 15000, input: plain }).trim();
722
+ };
723
+
724
+ let plain;
725
+ try { plain = Buffer.from(unprotect(envelope.value, fromScope), 'base64').toString('utf8'); }
726
+ catch (e) { return { ok: false, changed: false, from: fromScope, to: targetScope, detail: 'decrypt under ' + fromScope + ' failed: ' + _safePowershellError(e) }; }
727
+ if (!plain) return { ok: false, changed: false, from: fromScope, to: targetScope, detail: 'decrypt produced empty' };
728
+
729
+ let protected64;
730
+ try { protected64 = protect(plain, targetScope); }
731
+ catch (e) { return { ok: false, changed: false, from: fromScope, to: targetScope, detail: 'protect under ' + targetScope + ' failed: ' + _safePowershellError(e) }; }
732
+ if (!protected64) return { ok: false, changed: false, from: fromScope, to: targetScope, detail: 'protect produced empty' };
733
+
734
+ // 2. Atomic, ACL-verified, rollback-safe replacement.
735
+ const dir = path.dirname(keyFile);
736
+ const tmp = path.join(dir, `.device-key.rescope.${crypto.randomBytes(6).toString('hex')}`);
737
+ const bak = path.join(dir, `.device-key.bak.${crypto.randomBytes(6).toString('hex')}`);
738
+ try {
739
+ fs.writeFileSync(tmp, JSON.stringify({ scheme: 'dpapi', scope: targetScope, value: protected64, v: 2 }), { encoding: 'utf8', mode: 0o600 });
740
+ _applyWindowsAclToDeviceKey(tmp);
741
+ fs.renameSync(keyFile, bak);
742
+ fs.renameSync(tmp, keyFile);
743
+ _verifyWindowsAclForDeviceKey(keyFile);
744
+ // Verify the re-protected key DECRYPTS under the target scope before we keep it.
745
+ const verifyPlain = Buffer.from(unprotect(protected64, targetScope), 'base64').toString('utf8');
746
+ if (verifyPlain !== plain) throw new Error('re-protected key does not round-trip');
747
+ try { fs.unlinkSync(bak); } catch { }
748
+ return { ok: true, changed: true, from: fromScope, to: targetScope, detail: 're-protected under ' + targetScope };
749
+ } catch (e) {
750
+ try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch { }
751
+ try { if (fs.existsSync(bak)) { if (fs.existsSync(keyFile)) fs.unlinkSync(keyFile); fs.renameSync(bak, keyFile); } } catch { }
752
+ return { ok: false, changed: false, from: fromScope, to: targetScope, detail: 'rescope failed: ' + ((e && e.message) || 'unknown') };
753
+ }
754
+ }
755
+
537
756
  /**
538
757
  * Phase 8: Apply explicit Windows ACL to the device-key file.
539
758
  * Reuses the hardened ACL pattern from profilePath.js:
@@ -586,29 +805,142 @@ function _currentWindowsUserSid() {
586
805
  return ownerSidResult.stdout.trim();
587
806
  }
588
807
 
808
+ /**
809
+ * Apply the restrictive DACL to EVERY machine-wide state directory that holds
810
+ * sensitive material (identity, credentials, config, state, runtime, logs).
811
+ *
812
+ * WHY: the machine root lives under ProgramData, which is world-readable by
813
+ * default on Windows. The device private key, the protected config credentials,
814
+ * and the browser profiles must not be readable by an unrelated local Windows
815
+ * user. The device-key FILE gets its own strict ACL in _applyWindowsAclToDeviceKey;
816
+ * this locks down the CONTAINERS so a newly created file cannot inherit a broad
817
+ * ACE, and so an attacker cannot enumerate/replace the directory contents.
818
+ *
819
+ * Fail-closed: any stage that cannot apply or verify the ACL throws
820
+ * SECURE_STORAGE_UNAVAILABLE, exactly like the key-file ACL path.
821
+ *
822
+ * @param {object} [opts] — injectable stages for deterministic tests
823
+ * @param {string} [opts.root] — override the machine root
824
+ * @returns {string[]} the directories whose ACL was applied + verified
825
+ */
826
+ function applyMachineStateAcls(opts = {}) {
827
+ if (os.platform() !== 'win32') return [];
828
+ const root = opts.root || getMachineRoot();
829
+ const ownerSid = opts.ownerSid || _currentWindowsUserSid();
830
+ const { spawnSync } = require('child_process');
831
+ const applied = [];
832
+ const targets = [
833
+ root,
834
+ path.join(root, 'config'),
835
+ path.join(root, 'identity'),
836
+ path.join(root, 'credentials'),
837
+ path.join(root, 'logs'),
838
+ path.join(root, 'runtime'),
839
+ path.join(root, 'state'),
840
+ path.join(root, 'launcher'),
841
+ path.join(root, 'state', 'profiles'),
842
+ path.join(root, 'state', 'servers'),
843
+ ];
844
+ for (const target of targets) {
845
+ try { if (!fs.existsSync(target)) continue; } catch { continue; }
846
+ // Only directories exist at this point; treat everything as a container so
847
+ // the ACE is inheritable (OI)(CI).
848
+ const aclScript = `
849
+ $ErrorActionPreference = 'Stop'
850
+ $path = '${String(target).replace(/'/g, "''")}'
851
+ $ownerSid = '${ownerSid}'
852
+ $acl = New-Object System.Security.AccessControl.DirectorySecurity
853
+ $acl.SetAccessRuleProtection($true, $false)
854
+ $rights = [System.Security.AccessControl.FileSystemRights]::FullControl
855
+ $inh = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
856
+ $prop = [System.Security.AccessControl.PropagationFlags]::None
857
+ foreach ($sid in @($ownerSid, 'S-1-5-32-544', 'S-1-5-18')) {
858
+ $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
859
+ (New-Object System.Security.Principal.SecurityIdentifier($sid)), $rights, $inh, $prop,
860
+ [System.Security.AccessControl.AccessControlType]::Allow)
861
+ $acl.AddAccessRule($rule)
862
+ }
863
+ (Get-Item -LiteralPath $path).SetAccessControl($acl)
864
+ `;
865
+ const apply = spawnSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', aclScript], {
866
+ windowsHide: true, encoding: 'utf8', timeout: 15000,
867
+ });
868
+ if (apply.status !== 0 || (apply.stderr && apply.stderr.trim())) {
869
+ // icacls fallback (some Windows Server builds reject the .NET path).
870
+ const user = os.userInfo().username;
871
+ const fb = spawnSync('icacls', [target, '/inheritance:r', '/grant:r', `${user}:(OI)(CI)F`], { windowsHide: true });
872
+ if (fb.status !== 0) {
873
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: machine state ACL apply stage failed for ' +
874
+ target + ' (' + _safePowershellError(apply) + ')');
875
+ }
876
+ }
877
+ // Verify: are rules protected + no broad principal retains Allow access.
878
+ const verifyScript = `
879
+ $ErrorActionPreference = 'Stop'
880
+ $path = '${String(target).replace(/'/g, "''")}'
881
+ $allowed = @('${ownerSid}','S-1-5-32-544','S-1-5-18')
882
+ $acl = (Get-Item -LiteralPath $path).GetAccessControl()
883
+ $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])
884
+ $leaked = @()
885
+ foreach ($rule in $rules) {
886
+ if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow) {
887
+ $sid = $rule.IdentityReference.Value
888
+ if ($allowed -notcontains $sid) { $leaked += $sid }
889
+ }
890
+ }
891
+ @{ protected = $acl.AreAccessRulesProtected; leaked = ($leaked -join '|') } | ConvertTo-Json -Compress
892
+ `;
893
+ const verify = spawnSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', verifyScript], {
894
+ windowsHide: true, encoding: 'utf8', timeout: 10000,
895
+ });
896
+ if (verify.status !== 0 || (verify.stderr && verify.stderr.trim())) {
897
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: machine state ACL read-back stage failed for ' +
898
+ target + ' (' + _safePowershellError(verify) + ')');
899
+ }
900
+ let data;
901
+ try { data = JSON.parse(verify.stdout.trim()); } catch {
902
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: machine state ACL read-back invalid for ' + target);
903
+ }
904
+ const leaked = String(data.leaked || '').split('|').filter(Boolean);
905
+ if (data.protected !== true || leaked.length > 0) {
906
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: machine state ACL verification failed for ' +
907
+ target + ' (leaked: ' + leaked.join(',') + ')');
908
+ }
909
+ applied.push(target);
910
+ }
911
+ return applied;
912
+ }
913
+
589
914
  function _verifyWindowsAclForDeviceKey(keyFile, ownerSid) {
590
915
  const { spawnSync } = require('child_process');
591
916
  const currentSid = ownerSid || _currentWindowsUserSid();
592
917
  const verifyScript = `
593
918
  $ErrorActionPreference = 'Stop'
594
919
  $path = '${keyFile.replace(/'/g, "''")}'
595
- $ownerSid = '${currentSid}'
920
+ $currentSid = '${currentSid}'
921
+ # A MACHINE-WIDE key is shared by the broker (SYSTEM), the local
922
+ # administrators, and the installing owner. Which concrete owner SID is on the
923
+ # ACL varies by who installed it, so the security property is NOT "the current
924
+ # process is the owner"; it is: the DACL is protected, a trusted machine
925
+ # principal has access, and NO BROAD PRINCIPAL (which any ordinary local user
926
+ # would match) has access.
927
+ $trusted = @('S-1-5-18', 'S-1-5-32-544', $currentSid)
928
+ $forbiddenBroad = @('S-1-1-0', 'S-1-5-32-545', 'S-1-5-11', 'S-1-5-32-546') # Everyone, Users, Authenticated Users, Guests
596
929
  $acl = (Get-Item -LiteralPath $path).GetAccessControl()
597
930
  $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])
598
- $allowed = @($ownerSid, 'S-1-5-18', 'S-1-5-32-544')
599
931
  $leaked = @()
600
- $ownerHasAccess = $false
932
+ $trustedHasAccess = $false
601
933
  foreach ($rule in $rules) {
602
934
  $sid = $rule.IdentityReference.Value
603
935
  if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow) {
604
- if ($allowed -notcontains $sid) { $leaked += $sid }
605
- if ($sid -eq $ownerSid) { $ownerHasAccess = $true }
936
+ if ($forbiddenBroad -contains $sid) { $leaked += $sid }
937
+ if ($trusted -contains $sid) { $trustedHasAccess = $true }
606
938
  }
607
939
  }
608
940
  @{
609
941
  areAccessRulesProtected = $acl.AreAccessRulesProtected
610
942
  leaked = ($leaked -join '|')
611
- ownerHasAccess = $ownerHasAccess
943
+ trustedHasAccess = $trustedHasAccess
612
944
  } | ConvertTo-Json -Compress
613
945
  `;
614
946
  const verify = spawnSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', verifyScript], {
@@ -623,8 +955,10 @@ function _verifyWindowsAclForDeviceKey(keyFile, ownerSid) {
623
955
  throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL read-back invalid');
624
956
  }
625
957
  const leaked = String(data.leaked || '').split('|').filter(Boolean);
626
- if (data.areAccessRulesProtected !== true || data.ownerHasAccess !== true || leaked.length > 0) {
627
- throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL verification stage failed');
958
+ if (data.areAccessRulesProtected !== true || data.trustedHasAccess !== true || leaked.length > 0) {
959
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL verification stage failed' +
960
+ ' [protected=' + data.areAccessRulesProtected + ' trustedHasAccess=' + data.trustedHasAccess +
961
+ ' leaked=' + (leaked.join(',') || 'none') + ']');
628
962
  }
629
963
  return data;
630
964
  }
@@ -691,27 +1025,45 @@ function _loadLinux() {
691
1025
  function loadMetadata(opts) {
692
1026
  const serverOrigin = opts && opts.serverOrigin;
693
1027
 
694
- // Try server-scoped metadata first
1028
+ // Try server-scoped metadata first (from whichever root currently owns the
1029
+ // identity — machine root preferred, legacy per-user as a migration fallback).
695
1030
  if (serverOrigin) {
696
1031
  _migrateLegacyIdentity(serverOrigin);
697
- const scopedFile = _metadataFile(serverOrigin);
698
- if (fs.existsSync(scopedFile)) {
699
- try {
700
- return JSON.parse(fs.readFileSync(scopedFile, 'utf8'));
701
- } catch (_e) {
702
- return null;
1032
+ for (const root of _metadataReadRoots()) {
1033
+ const scopedFile = path.join(_serversDirFor(root), normalizeServerOrigin(serverOrigin), 'device-metadata.json');
1034
+ if (fs.existsSync(scopedFile)) {
1035
+ try {
1036
+ return JSON.parse(fs.readFileSync(scopedFile, 'utf8'));
1037
+ } catch (_e) {
1038
+ return null;
1039
+ }
703
1040
  }
704
1041
  }
705
1042
  }
706
1043
 
707
- // Fall back to legacy top-level metadata
708
- const legacyFile = path.join(DATA_DIR, 'device-metadata.json');
709
- if (!fs.existsSync(legacyFile)) return null;
710
- try {
711
- return JSON.parse(fs.readFileSync(legacyFile, 'utf8'));
712
- } catch (_e) {
713
- return null;
1044
+ // Fall back to top-level metadata on either root.
1045
+ for (const root of _metadataReadRoots()) {
1046
+ const legacyFile = path.join(root, 'device-metadata.json');
1047
+ if (!fs.existsSync(legacyFile)) continue;
1048
+ try {
1049
+ return JSON.parse(fs.readFileSync(legacyFile, 'utf8'));
1050
+ } catch (_e) {
1051
+ return null;
1052
+ }
714
1053
  }
1054
+ return null;
1055
+ }
1056
+
1057
+ /**
1058
+ * Ordered roots to probe when READING identity: the root that currently owns
1059
+ * the identity first, then the other one. This keeps a pre-adoption legacy
1060
+ * identity visible without ever writing a second identity.
1061
+ */
1062
+ function _metadataReadRoots() {
1063
+ const { source, target } = _identitySourceRoots();
1064
+ const roots = [source];
1065
+ if (path.resolve(source) !== path.resolve(target)) roots.push(target);
1066
+ return roots;
715
1067
  }
716
1068
 
717
1069
  /**
@@ -723,8 +1075,12 @@ function loadMetadata(opts) {
723
1075
  */
724
1076
  function saveMetadata(meta, opts) {
725
1077
  const serverOrigin = opts && opts.serverOrigin || meta && meta.serverOrigin;
726
- const targetDir = serverOrigin ? getServerDataDir(serverOrigin) : DATA_DIR;
727
- const targetFile = serverOrigin ? _metadataFile(serverOrigin) : path.join(DATA_DIR, 'device-metadata.json');
1078
+ // WRITE target is the machine root (may differ from the legacy read source).
1079
+ const { target } = _identitySourceRoots();
1080
+ const targetDir = serverOrigin ? path.join(_serversDirFor(target), normalizeServerOrigin(serverOrigin)) : target;
1081
+ const targetFile = serverOrigin
1082
+ ? path.join(targetDir, 'device-metadata.json')
1083
+ : path.join(target, 'device-metadata.json');
728
1084
 
729
1085
  if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir, { recursive: true });
730
1086
 
@@ -753,14 +1109,26 @@ function saveMetadata(meta, opts) {
753
1109
  function deleteMetadata(opts) {
754
1110
  const serverOrigin = opts && opts.serverOrigin;
755
1111
 
756
- if (serverOrigin) {
757
- const scopedFile = _metadataFile(serverOrigin);
758
- try { if (fs.existsSync(scopedFile)) fs.unlinkSync(scopedFile); } catch {}
1112
+ for (const root of _allRoots()) {
1113
+ if (serverOrigin) {
1114
+ const scopedFile = path.join(_serversDirFor(root), normalizeServerOrigin(serverOrigin), 'device-metadata.json');
1115
+ try { if (fs.existsSync(scopedFile)) fs.unlinkSync(scopedFile); } catch {}
1116
+ }
1117
+ const legacyFile = path.join(root, 'device-metadata.json');
1118
+ try { if (fs.existsSync(legacyFile)) fs.unlinkSync(legacyFile); } catch {}
759
1119
  }
1120
+ }
760
1121
 
761
- // Also delete legacy top-level metadata
762
- const legacyFile = path.join(DATA_DIR, 'device-metadata.json');
763
- try { if (fs.existsSync(legacyFile)) fs.unlinkSync(legacyFile); } catch {}
1122
+ /**
1123
+ * Both state roots (machine + legacy per-user), de-duplicated. Used for
1124
+ * destructive identity operations so a logout cannot leave a live identity on
1125
+ * the root the agent no longer writes to.
1126
+ */
1127
+ function _allRoots() {
1128
+ const machine = getMachineRoot();
1129
+ const legacy = getLegacyDataDir();
1130
+ if (path.resolve(machine) === path.resolve(legacy)) return [machine];
1131
+ return [machine, legacy];
764
1132
  }
765
1133
 
766
1134
  /**
@@ -907,7 +1275,7 @@ function probeWindowsStorage() {
907
1275
  try {
908
1276
  const data = _verifyWindowsAclForDeviceKey(probeFile, sid);
909
1277
  stages.aclVerify = data.areAccessRulesProtected === true &&
910
- data.ownerHasAccess === true &&
1278
+ data.trustedHasAccess === true &&
911
1279
  String(data.leaked || '').split('|').filter(Boolean).length === 0;
912
1280
  } catch (e) {
913
1281
  try { fs.unlinkSync(probeFile); } catch {}
@@ -937,9 +1305,16 @@ module.exports = {
937
1305
  _storeWindows,
938
1306
  probeWindowsStorage,
939
1307
  getDataDir,
1308
+ getLegacyDataDir,
1309
+ getMachineRoot,
940
1310
  getServerDataDir,
941
1311
  normalizeServerOrigin,
942
1312
  _migrateLegacyIdentity,
1313
+ _identitySourceRoots,
1314
+ _serversDirFor,
1315
+ _machineInit: () => _machineInit,
1316
+ applyMachineStateAcls,
1317
+ rescopeWindowsKey,
943
1318
  DATA_DIR,
944
1319
  PROFILES_DIR,
945
1320
  LOGS_DIR,