@xkwdstore/agent 2.0.2 → 2.0.4

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.
@@ -1,700 +1,947 @@
1
- 'use strict';
2
-
3
- /**
4
- * Phase 5 — Secure device key storage.
5
- *
6
- * Stores the Ed25519 private key using OS credential abstraction:
7
- * - Windows: DPAPI (current-user scope)
8
- * - macOS: Keychain (via `security` command)
9
- * - Linux: Secret Service / libsecret (via `secret-tool`)
10
- *
11
- * FAIL CLOSED when secure storage is unavailable. Do NOT silently fall back
12
- * to plaintext storage.
13
- *
14
- * The private key:
15
- * - never leaves the computer
16
- * - never appears in logs
17
- * - never appears in command arguments
18
- * - never appears in crash reports
19
- * - is never written to plaintext JSON
20
- *
21
- * Non-secret device metadata (deviceId, publicKey, publicKeyFingerprint,
22
- * deviceName) may be stored in a plaintext metadata file for convenience.
23
- */
24
-
25
- const crypto = require('crypto');
26
- const fs = require('fs');
27
- const path = require('path');
28
- const os = require('os');
29
-
30
- // ── Windows PowerShell 5.1 absolute path ─────────────────────────────────────
31
-
32
- /**
33
- * Resolve the absolute path to Windows PowerShell 5.1.
34
- *
35
- * Never use bare `powershell`, `powershell.exe`, or `pwsh` — those resolve via
36
- * PATH and can resolve to a Store PowerShell 7 executable whose output
37
- * encoding / assembly loading differs. Pinning System32\WindowsPowerShell\v1.0\
38
- * powershell.exe guarantees the DPAPI .NET assembly and the ACL cmdlets behave
39
- * identically across machines.
40
- *
41
- * Returns '' on non-Windows platforms.
42
- */
43
- function _powershellExe() {
44
- if (os.platform() !== 'win32') return 'powershell.exe';
45
- const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
46
- return path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
47
- }
48
-
49
- // ── Data directory resolution ────────────────────────────────────────────────
50
-
51
- /**
52
- * Resolve the standard application-data directory for XKWDStore.
53
- *
54
- * Windows: %LOCALAPPDATA%\XKWDStore\
55
- * macOS: ~/Library/Application Support/XKWDStore/
56
- * Linux: ${XDG_DATA_HOME:-~/.local/share}/xkwdstore/
57
- */
58
- 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');
65
- }
66
- // Linux / other Unix
67
- const xdg = process.env.XDG_DATA_HOME;
68
- return path.join(xdg || path.join(os.homedir(), '.local', 'share'), 'xkwdstore');
69
- }
70
-
71
- const DATA_DIR = getDataDir();
72
- const METADATA_FILE = path.join(DATA_DIR, 'device-metadata.json');
73
- const PROFILES_DIR = path.join(DATA_DIR, 'profiles');
74
- const LOGS_DIR = path.join(DATA_DIR, 'logs');
75
-
76
- // ── Key generation ───────────────────────────────────────────────────────────
77
-
78
- /**
79
- * Generate a new Ed25519 key pair.
80
- * @returns {object} { publicKey: Buffer (32 bytes raw), privateKey: Buffer (64 bytes raw),
81
- * publicKeyB64Url: string, privateKeyB64Url: string,
82
- * publicKeyFingerprint: string (SHA-256 hex) }
83
- */
84
- function generateKeyPair() {
85
- const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
86
-
87
- // Export as raw DER SPKI public key and PKCS8 private key
88
- const pubDer = publicKey.export({ type: 'spki', format: 'der' });
89
- const privDer = privateKey.export({ type: 'pkcs8', format: 'der' });
90
-
91
- // For Ed25519, the raw public key is the last 32 bytes of the SPKI DER
92
- // (the DER header is 12 bytes for Ed25519 SPKI).
93
- const pubRaw = pubDer.slice(-32);
94
-
95
- // For the private key, we store the full PKCS8 DER (base64url encoded).
96
- // This is more portable than raw bytes.
97
- const pubB64Url = pubRaw.toString('base64url');
98
- const privB64Url = privDer.toString('base64url');
99
-
100
- const fingerprint = crypto.createHash('sha256').update(pubRaw).digest('hex');
101
-
102
- return {
103
- publicKey: pubRaw,
104
- privateKey: privDer,
105
- publicKeyB64Url: pubB64Url,
106
- privateKeyB64Url: privB64Url,
107
- publicKeyFingerprint: fingerprint,
108
- };
109
- }
110
-
111
- /**
112
- * Load a private key from base64url PKCS8 DER and return a KeyObject.
113
- */
114
- function loadPrivateKeyFromDer(privateKeyB64Url) {
115
- const der = Buffer.from(privateKeyB64Url, 'base64url');
116
- return crypto.createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
117
- }
118
-
119
- /**
120
- * Sign a message with an Ed25519 private key.
121
- * @param {string|Buffer} privateKeyB64Url
122
- * @param {Buffer} message
123
- * @returns {string} signature as base64url
124
- */
125
- function signMessage(privateKeyB64Url, message) {
126
- const keyObj = loadPrivateKeyFromDer(privateKeyB64Url);
127
- const signature = crypto.sign(null, message, keyObj);
128
- return signature.toString('base64url');
129
- }
130
-
131
- // ── Secure storage backends ──────────────────────────────────────────────────
132
-
133
- const SERVICE_NAME = 'XKWDStoreAgent';
134
- const ACCOUNT_NAME = 'device-private-key';
135
-
136
- /**
137
- * Store the private key securely using the OS credential abstraction.
138
- * FAILS CLOSED — throws if secure storage is unavailable.
139
- */
140
- async function storePrivateKey(privateKeyB64Url) {
141
- const platform = os.platform();
142
-
143
- if (platform === 'win32') {
144
- return _storeWindows(privateKeyB64Url);
145
- }
146
- if (platform === 'darwin') {
147
- return _storeMacOS(privateKeyB64Url);
148
- }
149
- return _storeLinux(privateKeyB64Url);
150
- }
151
-
152
- /**
153
- * Retrieve the private key from secure storage.
154
- * FAILS CLOSED — returns null if secure storage is unavailable or key not found.
155
- */
156
- async function loadPrivateKey() {
157
- const platform = os.platform();
158
-
159
- if (platform === 'win32') {
160
- return _loadWindows();
161
- }
162
- if (platform === 'darwin') {
163
- return _loadMacOS();
164
- }
165
- return _loadLinux();
166
- }
167
-
168
- /**
169
- * Delete the private key from secure storage.
170
- */
171
- async function deletePrivateKey() {
172
- const platform = os.platform();
173
-
174
- if (platform === 'win32') {
175
- // DPAPI-protected file deletion
176
- const keyFile = path.join(DATA_DIR, '.device-key');
177
- try { if (fs.existsSync(keyFile)) fs.unlinkSync(keyFile); } catch {}
178
- return;
179
- }
180
- if (platform === 'darwin') {
181
- try {
182
- const { execFileSync } = require('child_process');
183
- execFileSync('security', ['delete-generic-password', '-s', SERVICE_NAME, '-a', ACCOUNT_NAME], {
184
- stdio: 'ignore',
185
- windowsHide: true,
186
- });
187
- } catch {}
188
- return;
189
- }
190
- // Linux
191
- try {
192
- const { execFileSync } = require('child_process');
193
- execFileSync('secret-tool', ['clear', 'service', SERVICE_NAME], {
194
- stdio: 'ignore',
195
- windowsHide: true,
196
- });
197
- } catch {}
198
- }
199
-
200
- // ── Windows: DPAPI (Defect 10 fix: pass secret via stdin, not argv) ──────────
201
-
202
- function _storeWindows(privateKeyB64Url, opts) {
203
- const { execFileSync } = require('child_process');
204
- // Defect 10: The secret is passed via STDIN, not in the command string.
205
- // The PowerShell script reads from stdin and feeds it to DPAPI.
206
- // The process command line never contains the private key.
207
- const ps =
208
- "$ErrorActionPreference='Stop'; " +
209
- "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
210
- "Add-Type -AssemblyName System.Security; " +
211
- "$in = [Console]::In.ReadToEnd(); " +
212
- "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in); " +
213
- "$b = [System.Security.Cryptography.ProtectedData]::Protect(" +
214
- "$bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
215
- "[Console]::Out.Write([Convert]::ToBase64String($b))";
216
-
217
- // Injectable stage functions (for deterministic testing). In production these
218
- // default to the real implementations.
219
- const applyAcl = (opts && opts.applyAcl) || _applyWindowsAclToDeviceKey;
220
- const verifyAcl = (opts && opts.verifyAcl) || _verifyWindowsAclForDeviceKey;
221
- const psExe = (opts && opts.psExe) || _powershellExe;
222
-
223
- let protected64;
224
- try {
225
- protected64 = execFileSync(psExe(),
226
- ['-NoProfile', '-NonInteractive', '-Command', ps],
227
- {
228
- windowsHide: true,
229
- encoding: 'utf8',
230
- timeout: 15000,
231
- input: privateKeyB64Url, // secret via stdin, NOT argv
232
- }
233
- ).trim();
234
- } catch (e) {
235
- throw new Error('SECURE_STORAGE_UNAVAILABLE: DPAPI protect stage failed (' +
236
- _safePowershellError(e) + ')');
237
- }
238
- if (!protected64) {
239
- throw new Error('SECURE_STORAGE_UNAVAILABLE: DPAPI protect stage returned empty output');
240
- }
241
-
242
- if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
243
-
244
- const keyFile = path.join(DATA_DIR, '.device-key');
245
- const tmpFile = path.join(DATA_DIR, `.device-key.tmp.${crypto.randomBytes(6).toString('hex')}`);
246
- try {
247
- fs.writeFileSync(tmpFile, JSON.stringify({ scheme: 'dpapi', value: protected64, v: 1 }), {
248
- encoding: 'utf8',
249
- });
250
- } catch (e) {
251
- try { if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile); } catch {}
252
- throw new Error('SECURE_STORAGE_UNAVAILABLE: device-key write stage failed (' +
253
- _safePowershellError(e) + ')');
254
- }
255
- // Rollback-safe replacement: never delete a previously valid .device-key on
256
- // failure. We back up the existing key, promote the candidate, and restore
257
- // the backup on any failure. Only the candidate (tmp) file is cleaned up.
258
- const hadExisting = fs.existsSync(keyFile);
259
- const backupFile = path.join(DATA_DIR, `.device-key.bak.${crypto.randomBytes(6).toString('hex')}`);
260
- try {
261
- applyAcl(tmpFile);
262
- if (hadExisting) {
263
- fs.renameSync(keyFile, backupFile);
264
- }
265
- fs.renameSync(tmpFile, keyFile);
266
- verifyAcl(keyFile);
267
- // Success — remove the backup if one was created.
268
- if (hadExisting) {
269
- try { if (fs.existsSync(backupFile)) fs.unlinkSync(backupFile); } catch {}
270
- }
271
- } catch (aclErr) {
272
- // Clean up the candidate only — never touch the prior valid key.
273
- try { if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile); } catch {}
274
- // Restore the prior key if we moved it aside. Only delete the unverified
275
- // keyFile when a backup exists to restore — if the failure happened before
276
- // the backup was created, keyFile is still the prior valid key and must be
277
- // left untouched.
278
- if (hadExisting && fs.existsSync(backupFile)) {
279
- try {
280
- if (fs.existsSync(keyFile)) fs.unlinkSync(keyFile);
281
- fs.renameSync(backupFile, keyFile);
282
- } catch {}
283
- } else if (!hadExisting) {
284
- // No prior key existed — remove any partially-promoted file so we don't
285
- // leave an unverified key on disk.
286
- try { if (fs.existsSync(keyFile)) fs.unlinkSync(keyFile); } catch {}
287
- }
288
- throw aclErr;
289
- }
290
- }
291
-
292
- function _loadWindows() {
293
- const { execFileSync } = require('child_process');
294
- const keyFile = path.join(DATA_DIR, '.device-key');
295
-
296
- if (!fs.existsSync(keyFile)) return null;
297
-
298
- try {
299
- if (process.env.DEVICE_KEY_VERIFY_ACL_ON_LOAD !== 'false') {
300
- _verifyWindowsAclForDeviceKey(keyFile);
301
- }
302
- const envelope = JSON.parse(fs.readFileSync(keyFile, 'utf8'));
303
- if (envelope.scheme !== 'dpapi' || !envelope.value) {
304
- throw new Error('Invalid key envelope');
305
- }
306
-
307
- // Defect 10: Pass the protected blob via stdin, not in the command string.
308
- const ps =
309
- "$ErrorActionPreference='Stop'; " +
310
- "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
311
- "Add-Type -AssemblyName System.Security; " +
312
- "$in = [Console]::In.ReadToEnd().Trim(); " +
313
- "$b = [System.Security.Cryptography.ProtectedData]::Unprotect(" +
314
- "[Convert]::FromBase64String($in), " +
315
- "$null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
316
- "[Console]::Out.Write([Convert]::ToBase64String($b))";
317
-
318
- const b64 = execFileSync(_powershellExe(),
319
- ['-NoProfile', '-NonInteractive', '-Command', ps],
320
- {
321
- windowsHide: true,
322
- encoding: 'utf8',
323
- timeout: 15000,
324
- input: envelope.value, // protected blob via stdin
325
- }
326
- ).trim();
327
-
328
- return Buffer.from(b64, 'base64').toString('utf8');
329
- } catch (e) {
330
- // Fail closed — do NOT fall back to plaintext
331
- return null;
332
- }
333
- }
334
-
335
- /**
336
- * Phase 8: Apply explicit Windows ACL to the device-key file.
337
- * Reuses the hardened ACL pattern from profilePath.js:
338
- * - Only current user, SYSTEM, and Administrators get Allow ACEs.
339
- * - Inheritance is disabled (protected DACL).
340
- * - Unexpected Allow ACEs (Everyone, Authenticated Users, BUILTIN\Users)
341
- * are removed.
342
- * - This is more robust than relying only on POSIX mode 0o600.
343
- */
344
- function _applyWindowsAclToDeviceKey(keyFile) {
345
- const { spawnSync } = require('child_process');
346
- const ownerSid = _currentWindowsUserSid();
347
- const aclScript = `
348
- $ErrorActionPreference = 'Stop'
349
- $path = '${keyFile.replace(/'/g, "''")}'
350
- $ownerSid = '${ownerSid}'
351
- $acl = New-Object System.Security.AccessControl.FileSecurity
352
- $acl.SetAccessRuleProtection($true, $false)
353
- $colRights = [System.Security.AccessControl.FileSystemRights]::FullControl
354
- $inhFlags = [System.Security.AccessControl.InheritanceFlags]::None
355
- $propFlags = [System.Security.AccessControl.PropagationFlags]::None
356
- $rule = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier($ownerSid)), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
357
- $acl.AddAccessRule($rule)
358
- $rule2 = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
359
- $acl.AddAccessRule($rule2)
360
- $rule3 = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18')), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
361
- $acl.AddAccessRule($rule3)
362
- [System.IO.File]::SetAccessControl($path, $acl)
363
- `;
364
- const apply = spawnSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', aclScript], {
365
- windowsHide: true, encoding: 'utf8', timeout: 10000,
366
- });
367
- if (apply.status !== 0 || (apply.stderr && apply.stderr.trim())) {
368
- throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL apply stage failed (' +
369
- _safePowershellError(apply) + ')');
370
- }
371
- _verifyWindowsAclForDeviceKey(keyFile, ownerSid);
372
- }
373
-
374
- function _currentWindowsUserSid() {
375
- const { spawnSync } = require('child_process');
376
- const ownerSidResult = spawnSync(_powershellExe(), [
377
- '-NoProfile', '-NonInteractive', '-Command',
378
- '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
379
- ], { windowsHide: true, encoding: 'utf8', timeout: 10000 });
380
- if (ownerSidResult.status !== 0 || (ownerSidResult.stderr && ownerSidResult.stderr.trim()) || !ownerSidResult.stdout.trim()) {
381
- throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows SID lookup stage failed (' +
382
- _safePowershellError(ownerSidResult) + ')');
383
- }
384
- return ownerSidResult.stdout.trim();
385
- }
386
-
387
- function _verifyWindowsAclForDeviceKey(keyFile, ownerSid) {
388
- const { spawnSync } = require('child_process');
389
- const currentSid = ownerSid || _currentWindowsUserSid();
390
- const verifyScript = `
391
- $ErrorActionPreference = 'Stop'
392
- $path = '${keyFile.replace(/'/g, "''")}'
393
- $ownerSid = '${currentSid}'
394
- $acl = (Get-Item -LiteralPath $path).GetAccessControl()
395
- $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])
396
- $allowed = @($ownerSid, 'S-1-5-18', 'S-1-5-32-544')
397
- $leaked = @()
398
- $ownerHasAccess = $false
399
- foreach ($rule in $rules) {
400
- $sid = $rule.IdentityReference.Value
401
- if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow) {
402
- if ($allowed -notcontains $sid) { $leaked += $sid }
403
- if ($sid -eq $ownerSid) { $ownerHasAccess = $true }
404
- }
405
- }
406
- @{
407
- areAccessRulesProtected = $acl.AreAccessRulesProtected
408
- leaked = ($leaked -join '|')
409
- ownerHasAccess = $ownerHasAccess
410
- } | ConvertTo-Json -Compress
411
- `;
412
- const verify = spawnSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', verifyScript], {
413
- windowsHide: true, encoding: 'utf8', timeout: 10000,
414
- });
415
- if (verify.status !== 0 || (verify.stderr && verify.stderr.trim())) {
416
- throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL read-back stage failed (' +
417
- _safePowershellError(verify) + ')');
418
- }
419
- let data;
420
- try { data = JSON.parse(verify.stdout.trim()); } catch {
421
- throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL read-back invalid');
422
- }
423
- const leaked = String(data.leaked || '').split('|').filter(Boolean);
424
- if (data.areAccessRulesProtected !== true || data.ownerHasAccess !== true || leaked.length > 0) {
425
- throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL verification stage failed');
426
- }
427
- return data;
428
- }
429
-
430
- // ── macOS: Keychain (Phase 8: fail closed — argv exposure) ──────────────────
431
- // The macOS `security` command requires the secret as a -w argument, which
432
- // puts it in the child-process argv. This violates the threat model.
433
- // Until a safe native Keychain integration exists (using stdin or a native
434
- // helper), macOS secure storage is UNSUPPORTED and fails closed.
435
-
436
- function _storeMacOS(_privateKeyB64Url) {
437
- throw new Error('SECURE_STORAGE_UNAVAILABLE: macOS Keychain storage is not yet supported. The macOS `security` command exposes the secret in process arguments. A native Keychain helper is required.');
438
- }
439
-
440
- function _loadMacOS() {
441
- // macOS storage is not supported — fail closed.
442
- return null;
443
- }
444
-
445
- // ── Linux: Secret Service / libsecret ────────────────────────────────────────
446
-
447
- function _storeLinux(privateKeyB64Url) {
448
- const { execFileSync } = require('child_process');
449
- try {
450
- // Use secret-tool if available
451
- execFileSync('secret-tool', ['store', '--label', 'XKWDStore Agent Device Key', 'service', SERVICE_NAME, 'account', ACCOUNT_NAME], {
452
- input: privateKeyB64Url,
453
- encoding: 'utf8',
454
- windowsHide: true,
455
- timeout: 10000,
456
- });
457
- } catch (e) {
458
- // Check if GNOME keyring file fallback is available
459
- // If secret-tool is not available, fail closed
460
- throw new Error('SECURE_STORAGE_UNAVAILABLE: Secret Service (libsecret) not available. Install seahorse or gnome-keyring.');
461
- }
462
- }
463
-
464
- function _loadLinux() {
465
- const { execFileSync } = require('child_process');
466
- try {
467
- const result = execFileSync('secret-tool', ['lookup', 'service', SERVICE_NAME, 'account', ACCOUNT_NAME], {
468
- encoding: 'utf8',
469
- windowsHide: true,
470
- timeout: 10000,
471
- }).trim();
472
- return result;
473
- } catch (e) {
474
- // Fail closed
475
- return null;
476
- }
477
- }
478
-
479
- // ── Device metadata (non-secret, plaintext) ──────────────────────────────────
480
-
481
- /**
482
- * Load non-secret device metadata from the plaintext metadata file.
483
- * This does NOT contain the private key.
484
- */
485
- function loadMetadata() {
486
- if (!fs.existsSync(METADATA_FILE)) return null;
487
- try {
488
- return JSON.parse(fs.readFileSync(METADATA_FILE, 'utf8'));
489
- } catch (_e) {
490
- return null;
491
- }
492
- }
493
-
494
- /**
495
- * Save non-secret device metadata.
496
- * @param {object} meta — { deviceId, publicKeyB64Url, publicKeyFingerprint, deviceName, serverOrigin }
497
- */
498
- function saveMetadata(meta) {
499
- if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
500
- // Ensure no private key accidentally ends up in metadata
501
- const safe = {
502
- deviceId: meta.deviceId,
503
- publicKeyB64Url: meta.publicKeyB64Url,
504
- publicKeyFingerprint: meta.publicKeyFingerprint,
505
- deviceName: meta.deviceName,
506
- serverOrigin: meta.serverOrigin,
507
- createdAt: meta.createdAt || new Date().toISOString(),
508
- };
509
- fs.writeFileSync(METADATA_FILE, JSON.stringify(safe, null, 2), {
510
- encoding: 'utf8',
511
- mode: 0o600,
512
- });
513
- }
514
-
515
- /**
516
- * Delete the metadata file.
517
- */
518
- function deleteMetadata() {
519
- try { if (fs.existsSync(METADATA_FILE)) fs.unlinkSync(METADATA_FILE); } catch {}
520
- }
521
-
522
- /**
523
- * Check if secure storage is available on this platform.
524
- * @returns {boolean}
525
- */
526
- function isSecureStorageAvailable() {
527
- const platform = os.platform();
528
- if (platform === 'win32') return true; // DPAPI is always available on Windows
529
- if (platform === 'darwin') return false; // Phase 8: macOS not supported (argv exposure)
530
- // Linux
531
- try {
532
- const { execFileSync } = require('child_process');
533
- execFileSync('which', ['secret-tool'], { stdio: 'ignore', windowsHide: true });
534
- return true;
535
- } catch { return false; }
536
- }
537
-
538
- // ── Windows PowerShell 5.1 absolute path (exported for tests/probe) ─────────
539
-
540
- /**
541
- * Reduce a child_process error to a short, safe stage message.
542
- * Never includes the private key (which is only ever on stdin).
543
- */
544
- function _safePowershellError(e) {
545
- if (!e) return 'unknown error';
546
- if (typeof e === 'string') return e.slice(0, 200);
547
- const msg = (e.message || e.stderr || '').toString();
548
- // Strip multi-line PowerShell noise, keep the first meaningful line.
549
- const first = String(msg).split(/\r?\n/).find(l => l.trim()) || 'powershell failed';
550
- return first.slice(0, 200);
551
- }
552
-
553
- /**
554
- * Non-destructive DPAPI + ACL storage probe (Windows only).
555
- *
556
- * Performs the same stages as a real key store WITHOUT persisting any key:
557
- * 1. DPAPI Protect — round-trips a throwaway nonce through PowerShell DPAPI.
558
- * 2. DPAPI Unprotect — reverses it and confirms the nonce matches.
559
- * 3. Windows SID lookup — resolves the current user SID.
560
- * 4. ACL application — writes a throwaway probe file and applies the ACL.
561
- * 5. ACL verification — reads back the ACL and confirms it is locked down.
562
- *
563
- * Returns { ok: boolean, stages: { protect, unprotect, sidLookup, aclApply, aclVerify }, detail?: string }.
564
- * The probe file is always deleted. Never throws — callers decide what to do.
565
- */
566
- function probeWindowsStorage() {
567
- const { execFileSync, spawnSync } = require('child_process');
568
- const stages = {
569
- protect: false,
570
- unprotect: false,
571
- sidLookup: false,
572
- aclApply: false,
573
- aclVerify: false,
574
- };
575
- if (os.platform() !== 'win32') {
576
- return { ok: false, stages, detail: 'probe is Windows-only' };
577
- }
578
- const nonce = crypto.randomBytes(16).toString('base64url');
579
- const psProtect =
580
- "$ErrorActionPreference='Stop'; " +
581
- "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
582
- "Add-Type -AssemblyName System.Security; " +
583
- "$in = [Console]::In.ReadToEnd(); " +
584
- "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in); " +
585
- "$b = [System.Security.Cryptography.ProtectedData]::Protect(" +
586
- "$bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
587
- "[Console]::Out.Write([Convert]::ToBase64String($b))";
588
- let protected64 = '';
589
- try {
590
- protected64 = execFileSync(_powershellExe(),
591
- ['-NoProfile', '-NonInteractive', '-Command', psProtect],
592
- { windowsHide: true, encoding: 'utf8', timeout: 15000, input: nonce }
593
- ).trim();
594
- stages.protect = !!protected64;
595
- } catch (e) {
596
- return { ok: false, stages, detail: 'DPAPI protect stage failed (' + _safePowershellError(e) + ')' };
597
- }
598
- const psUnprotect =
599
- "$ErrorActionPreference='Stop'; " +
600
- "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
601
- "Add-Type -AssemblyName System.Security; " +
602
- "$in = [Console]::In.ReadToEnd().Trim(); " +
603
- "$b = [System.Security.Cryptography.ProtectedData]::Unprotect(" +
604
- "[Convert]::FromBase64String($in), " +
605
- "$null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
606
- "[Console]::Out.Write([Convert]::ToBase64String($b))";
607
- try {
608
- const back = execFileSync(_powershellExe(),
609
- ['-NoProfile', '-NonInteractive', '-Command', psUnprotect],
610
- { windowsHide: true, encoding: 'utf8', timeout: 15000, input: protected64 }
611
- ).trim();
612
- stages.unprotect = Buffer.from(back, 'base64').toString('utf8') === nonce;
613
- } catch (e) {
614
- return { ok: false, stages, detail: 'DPAPI unprotect stage failed (' + _safePowershellError(e) + ')' };
615
- }
616
- let sid = '';
617
- try {
618
- const sidRes = spawnSync(_powershellExe(), [
619
- '-NoProfile', '-NonInteractive', '-Command',
620
- '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
621
- ], { windowsHide: true, encoding: 'utf8', timeout: 10000 });
622
- sid = (sidRes.stdout || '').trim();
623
- stages.sidLookup = !!sid && sidRes.status === 0;
624
- } catch (e) {
625
- return { ok: false, stages, detail: 'Windows SID lookup stage failed (' + _safePowershellError(e) + ')' };
626
- }
627
- if (!stages.sidLookup) {
628
- return { ok: false, stages, detail: 'Windows SID lookup stage returned empty' };
629
- }
630
- if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
631
- const probeFile = path.join(DATA_DIR, `.dpapi-probe.${crypto.randomBytes(6).toString('hex')}`);
632
- try {
633
- fs.writeFileSync(probeFile, Buffer.from('probe'));
634
- } catch (e) {
635
- return { ok: false, stages, detail: 'probe file write failed (' + _safePowershellError(e) + ')' };
636
- }
637
- try {
638
- const aclScript = `
639
- $ErrorActionPreference = 'Stop'
640
- $path = '${probeFile.replace(/'/g, "''")}'
641
- $ownerSid = '${sid}'
642
- $acl = New-Object System.Security.AccessControl.FileSecurity
643
- $acl.SetAccessRuleProtection($true, $false)
644
- $colRights = [System.Security.AccessControl.FileSystemRights]::FullControl
645
- $inhFlags = [System.Security.AccessControl.InheritanceFlags]::None
646
- $propFlags = [System.Security.AccessControl.PropagationFlags]::None
647
- $rule = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier($ownerSid)), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
648
- $acl.AddAccessRule($rule)
649
- $rule2 = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
650
- $acl.AddAccessRule($rule2)
651
- $rule3 = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18')), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
652
- $acl.AddAccessRule($rule3)
653
- [System.IO.File]::SetAccessControl($path, $acl)
654
- `;
655
- const apply = spawnSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', aclScript], {
656
- windowsHide: true, encoding: 'utf8', timeout: 10000,
657
- });
658
- stages.aclApply = apply.status === 0 && !(apply.stderr && apply.stderr.trim());
659
- } catch (e) {
660
- try { fs.unlinkSync(probeFile); } catch {}
661
- return { ok: false, stages, detail: 'ACL apply stage failed (' + _safePowershellError(e) + ')' };
662
- }
663
- try {
664
- const data = _verifyWindowsAclForDeviceKey(probeFile, sid);
665
- stages.aclVerify = data.areAccessRulesProtected === true &&
666
- data.ownerHasAccess === true &&
667
- String(data.leaked || '').split('|').filter(Boolean).length === 0;
668
- } catch (e) {
669
- try { fs.unlinkSync(probeFile); } catch {}
670
- return { ok: false, stages, detail: 'ACL verify stage failed (' + _safePowershellError(e) + ')' };
671
- } finally {
672
- try { if (fs.existsSync(probeFile)) fs.unlinkSync(probeFile); } catch {}
673
- }
674
- const ok = stages.protect && stages.unprotect && stages.sidLookup && stages.aclApply && stages.aclVerify;
675
- return { ok, stages, detail: ok ? 'all storage stages passed' : 'one or more storage stages failed' };
676
- }
677
-
678
- module.exports = {
679
- generateKeyPair,
680
- loadPrivateKeyFromDer,
681
- signMessage,
682
- storePrivateKey,
683
- loadPrivateKeyFromStorage: loadPrivateKey,
684
- deletePrivateKey,
685
- loadMetadata,
686
- saveMetadata,
687
- deleteMetadata,
688
- isSecureStorageAvailable,
689
- _applyWindowsAclToDeviceKey,
690
- _verifyWindowsAclForDeviceKey,
691
- _powershellExe,
692
- _safePowershellError,
693
- _storeWindows,
694
- probeWindowsStorage,
695
- getDataDir,
696
- DATA_DIR,
697
- PROFILES_DIR,
698
- LOGS_DIR,
699
- METADATA_FILE,
700
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * Phase 5 — Secure device key storage.
5
+ *
6
+ * Stores the Ed25519 private key using OS credential abstraction:
7
+ * - Windows: DPAPI (current-user scope)
8
+ * - macOS: Keychain (via `security` command)
9
+ * - Linux: Secret Service / libsecret (via `secret-tool`)
10
+ *
11
+ * FAIL CLOSED when secure storage is unavailable. Do NOT silently fall back
12
+ * to plaintext storage.
13
+ *
14
+ * The private key:
15
+ * - never leaves the computer
16
+ * - never appears in logs
17
+ * - never appears in command arguments
18
+ * - never appears in crash reports
19
+ * - is never written to plaintext JSON
20
+ *
21
+ * Non-secret device metadata (deviceId, publicKey, publicKeyFingerprint,
22
+ * deviceName) may be stored in a plaintext metadata file for convenience.
23
+ */
24
+
25
+ const crypto = require('crypto');
26
+ const fs = require('fs');
27
+ const path = require('path');
28
+ const os = require('os');
29
+
30
+ // ── Windows PowerShell 5.1 absolute path ─────────────────────────────────────
31
+
32
+ /**
33
+ * Resolve the absolute path to Windows PowerShell 5.1.
34
+ *
35
+ * Never use bare `powershell`, `powershell.exe`, or `pwsh` — those resolve via
36
+ * PATH and can resolve to a Store PowerShell 7 executable whose output
37
+ * encoding / assembly loading differs. Pinning System32\WindowsPowerShell\v1.0\
38
+ * powershell.exe guarantees the DPAPI .NET assembly and the ACL cmdlets behave
39
+ * identically across machines.
40
+ *
41
+ * Returns '' on non-Windows platforms.
42
+ */
43
+ function _powershellExe() {
44
+ if (os.platform() !== 'win32') return 'powershell.exe';
45
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
46
+ return path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
47
+ }
48
+
49
+ // ── Data directory resolution ────────────────────────────────────────────────
50
+
51
+ /**
52
+ * Resolve the standard application-data directory for XKWDStore.
53
+ *
54
+ * Windows: %LOCALAPPDATA%\XKWDStore\
55
+ * macOS: ~/Library/Application Support/XKWDStore/
56
+ * Linux: ${XDG_DATA_HOME:-~/.local/share}/xkwdstore/
57
+ */
58
+ 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');
65
+ }
66
+ // Linux / other Unix
67
+ const xdg = process.env.XDG_DATA_HOME;
68
+ return path.join(xdg || path.join(os.homedir(), '.local', 'share'), 'xkwdstore');
69
+ }
70
+
71
+ const DATA_DIR = getDataDir();
72
+
73
+ // ── Server-scoped identity directories ───────────────────────────────────────
74
+ //
75
+ // Device identities MUST be scoped per-server so that enrolling against
76
+ // localhost never overwrites or interferes with the production identity.
77
+ // We create a subdirectory under DATA_DIR/servers/<normalized-origin>/ for
78
+ // each server origin. The private key and metadata live inside that subdir.
79
+ //
80
+ // Legacy migration: if a device-metadata.json exists at the old top-level
81
+ // DATA_DIR location (pre-scoping), we migrate it to the scoped directory for
82
+ // the server origin it references. The legacy file is never deleted before
83
+ // the scoped copy is verified.
84
+
85
+ /**
86
+ * Normalize a server origin URL into a safe, deterministic, collision-resistant
87
+ * directory name.
88
+ *
89
+ * The FULL canonical origin identity is represented:
90
+ * - scheme (http vs https) is ALWAYS included — they never collide
91
+ * - hostname is normalized (lowercase)
92
+ * - effective port is included (explicit or default for the scheme)
93
+ * - trailing slash does not change identity
94
+ * - query/path/fragment do not create accidental alternate identities
95
+ *
96
+ * Format: <readable-prefix>-<sha256(canonicalOrigin)[0..16]>
97
+ *
98
+ * Examples:
99
+ * https://x.kwdstore.com → xkwdstore.com-https-a1b2c3d4e5f6a1b2
100
+ * https://x.kwdstore.com:443 → xkwdstore.com-https-a1b2c3d4e5f6a1b2 (same — 443 is default for https)
101
+ * https://x.kwdstore.com/ → xkwdstore.com-https-a1b2c3d4e5f6a1b2 (same — trailing slash ignored)
102
+ * http://x.kwdstore.com → xkwdstore.com-http-b3c4d5e6f7a8b3c4 (DIFFERENT from https)
103
+ * http://localhost:4100 → localhost-4100-http-c5d6e7f8a9b0c5d6
104
+ * http://localhost:4200 → localhost-4200-http-d6e7f8a9b0c1d6e7 (DIFFERENT port)
105
+ *
106
+ * The result is always a single path component (no slashes, no traversal).
107
+ */
108
+ function normalizeServerOrigin(serverOrigin) {
109
+ if (!serverOrigin || typeof serverOrigin !== 'string') {
110
+ return 'default-0000000000000000';
111
+ }
112
+ let parsed;
113
+ try {
114
+ parsed = new (require('url').URL)(serverOrigin);
115
+ } catch {
116
+ // Not a valid URL — hash it to avoid path traversal
117
+ const hash = crypto.createHash('sha256').update(String(serverOrigin)).digest('hex').slice(0, 16);
118
+ return 'unknown-' + hash;
119
+ }
120
+
121
+ // Build the canonical origin: scheme://hostname:effectivePort
122
+ // This is what `new URL(origin).origin` produces, but we compute it
123
+ // explicitly to ensure the port is always included in the hash input.
124
+ const scheme = parsed.protocol.replace(':', '').toLowerCase(); // 'http' or 'https'
125
+ const hostname = (parsed.hostname || 'unknown').toLowerCase();
126
+ // Effective port: explicit port, or default for the scheme
127
+ const effectivePort = parsed.port || (scheme === 'https' ? '443' : '80');
128
+
129
+ // Canonical origin string — used as the hash input
130
+ const canonicalOrigin = scheme + '://' + hostname + ':' + effectivePort;
131
+
132
+ // Readable prefix: hostname + port (if non-default) + scheme
133
+ // This makes the directory human-inspectable while the hash guarantees
134
+ // collision resistance.
135
+ const isDefaultPort = (scheme === 'https' && effectivePort === '443') ||
136
+ (scheme === 'http' && effectivePort === '80');
137
+ let prefix = hostname;
138
+ if (!isDefaultPort) prefix += '-' + effectivePort;
139
+ prefix += '-' + scheme;
140
+
141
+ // Sanitize prefix: only alphanumeric, dash, dot
142
+ prefix = prefix.replace(/[^a-zA-Z0-9.\-]/g, '');
143
+ if (!prefix) prefix = 'unknown';
144
+
145
+ // Hash of the canonical origin for collision resistance
146
+ const hash = crypto.createHash('sha256').update(canonicalOrigin).digest('hex').slice(0, 16);
147
+
148
+ return prefix + '-' + hash;
149
+ }
150
+
151
+ /**
152
+ * Resolve the server-scoped data directory for a given server origin.
153
+ *
154
+ * %LOCALAPPDATA%\XKWDStore\servers\<normalized-origin>\
155
+ *
156
+ * Creates the directory if it does not exist.
157
+ */
158
+ function getServerDataDir(serverOrigin) {
159
+ const label = normalizeServerOrigin(serverOrigin);
160
+ const dir = path.join(DATA_DIR, 'servers', label);
161
+ return dir;
162
+ }
163
+
164
+ /**
165
+ * Resolve the server-scoped metadata file path.
166
+ * If serverOrigin is provided, returns the scoped path.
167
+ * If serverOrigin is null/undefined, returns the legacy top-level path
168
+ * (for backward-compatible reads during migration).
169
+ */
170
+ function _metadataFile(serverOrigin) {
171
+ if (!serverOrigin) return path.join(DATA_DIR, 'device-metadata.json');
172
+ return path.join(getServerDataDir(serverOrigin), 'device-metadata.json');
173
+ }
174
+
175
+ /**
176
+ * Resolve the server-scoped private key file path.
177
+ * If serverOrigin is provided, returns the scoped path.
178
+ * If serverOrigin is null/undefined, returns the legacy top-level path.
179
+ */
180
+ function _keyFile(serverOrigin) {
181
+ if (!serverOrigin) return path.join(DATA_DIR, '.device-key');
182
+ return path.join(getServerDataDir(serverOrigin), '.device-key');
183
+ }
184
+
185
+ const METADATA_FILE = path.join(DATA_DIR, 'device-metadata.json');
186
+ const PROFILES_DIR = path.join(DATA_DIR, 'profiles');
187
+ const LOGS_DIR = path.join(DATA_DIR, 'logs');
188
+
189
+ // ── Legacy migration (server-scoping) ───────────────────────────────────────
190
+
191
+ /**
192
+ * Migrate a legacy top-level identity to the scoped directory for its
193
+ * serverOrigin. This is safe and idempotent:
194
+ * 1. Read legacy metadata (if it exists).
195
+ * 2. If the legacy file has a serverOrigin, and no scoped metadata exists
196
+ * for that origin, copy both the metadata and the private key to the
197
+ * scoped directory.
198
+ * 3. The legacy file is NEVER deleted — it stays as a backup until the
199
+ * user explicitly re-authorizes or logs out for that server.
200
+ *
201
+ * This function never throws — migration failure should not block startup.
202
+ */
203
+ function _migrateLegacyIdentity(serverOrigin) {
204
+ if (!serverOrigin) return;
205
+ try {
206
+ const legacyMetaFile = path.join(DATA_DIR, 'device-metadata.json');
207
+ const legacyKeyFile = path.join(DATA_DIR, '.device-key');
208
+ if (!fs.existsSync(legacyMetaFile)) return;
209
+
210
+ const legacyMeta = JSON.parse(fs.readFileSync(legacyMetaFile, 'utf8'));
211
+ if (!legacyMeta || !legacyMeta.serverOrigin) return;
212
+
213
+ // Only migrate if the legacy identity belongs to the SAME server origin
214
+ // (normalized comparison). We don't migrate a localhost identity into the
215
+ // production directory or vice versa.
216
+ const legacyLabel = normalizeServerOrigin(legacyMeta.serverOrigin);
217
+ const targetLabel = normalizeServerOrigin(serverOrigin);
218
+ if (legacyLabel !== targetLabel) return;
219
+
220
+ const scopedDir = getServerDataDir(serverOrigin);
221
+ const scopedMetaFile = path.join(scopedDir, 'device-metadata.json');
222
+ const scopedKeyFile = path.join(scopedDir, '.device-key');
223
+
224
+ // If the scoped metadata already exists, the migration was already done.
225
+ if (fs.existsSync(scopedMetaFile)) return;
226
+
227
+ // Ensure the scoped directory exists.
228
+ if (!fs.existsSync(scopedDir)) fs.mkdirSync(scopedDir, { recursive: true });
229
+
230
+ // Copy metadata (non-secret).
231
+ fs.copyFileSync(legacyMetaFile, scopedMetaFile);
232
+ fs.chmodSync(scopedMetaFile, 0o600);
233
+
234
+ // Copy private key if it exists.
235
+ if (fs.existsSync(legacyKeyFile)) {
236
+ fs.copyFileSync(legacyKeyFile, scopedKeyFile);
237
+ fs.chmodSync(scopedKeyFile, 0o600);
238
+ }
239
+ } catch {
240
+ // Migration failure is non-fatal — the legacy identity remains at top level.
241
+ }
242
+ }
243
+
244
+ // ── Key generation ───────────────────────────────────────────────────────────
245
+
246
+ /**
247
+ * Generate a new Ed25519 key pair.
248
+ * @returns {object} { publicKey: Buffer (32 bytes raw), privateKey: Buffer (64 bytes raw),
249
+ * publicKeyB64Url: string, privateKeyB64Url: string,
250
+ * publicKeyFingerprint: string (SHA-256 hex) }
251
+ */
252
+ function generateKeyPair() {
253
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
254
+
255
+ // Export as raw DER SPKI public key and PKCS8 private key
256
+ const pubDer = publicKey.export({ type: 'spki', format: 'der' });
257
+ const privDer = privateKey.export({ type: 'pkcs8', format: 'der' });
258
+
259
+ // For Ed25519, the raw public key is the last 32 bytes of the SPKI DER
260
+ // (the DER header is 12 bytes for Ed25519 SPKI).
261
+ const pubRaw = pubDer.slice(-32);
262
+
263
+ // For the private key, we store the full PKCS8 DER (base64url encoded).
264
+ // This is more portable than raw bytes.
265
+ const pubB64Url = pubRaw.toString('base64url');
266
+ const privB64Url = privDer.toString('base64url');
267
+
268
+ const fingerprint = crypto.createHash('sha256').update(pubRaw).digest('hex');
269
+
270
+ return {
271
+ publicKey: pubRaw,
272
+ privateKey: privDer,
273
+ publicKeyB64Url: pubB64Url,
274
+ privateKeyB64Url: privB64Url,
275
+ publicKeyFingerprint: fingerprint,
276
+ };
277
+ }
278
+
279
+ /**
280
+ * Load a private key from base64url PKCS8 DER and return a KeyObject.
281
+ */
282
+ function loadPrivateKeyFromDer(privateKeyB64Url) {
283
+ const der = Buffer.from(privateKeyB64Url, 'base64url');
284
+ return crypto.createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
285
+ }
286
+
287
+ /**
288
+ * Sign a message with an Ed25519 private key.
289
+ * @param {string|Buffer} privateKeyB64Url
290
+ * @param {Buffer} message
291
+ * @returns {string} signature as base64url
292
+ */
293
+ function signMessage(privateKeyB64Url, message) {
294
+ const keyObj = loadPrivateKeyFromDer(privateKeyB64Url);
295
+ const signature = crypto.sign(null, message, keyObj);
296
+ return signature.toString('base64url');
297
+ }
298
+
299
+ // ── Secure storage backends ──────────────────────────────────────────────────
300
+
301
+ const SERVICE_NAME = 'XKWDStoreAgent';
302
+ const ACCOUNT_NAME = 'device-private-key';
303
+
304
+ /**
305
+ * Store the private key securely using the OS credential abstraction.
306
+ * FAILS CLOSED — throws if secure storage is unavailable.
307
+ *
308
+ * @param {string} privateKeyB64Url
309
+ * @param {object} [opts] — optional settings
310
+ * @param {string} [opts.serverOrigin] — server origin for server-scoped storage
311
+ */
312
+ async function storePrivateKey(privateKeyB64Url, opts) {
313
+ const platform = os.platform();
314
+ const serverOrigin = opts && opts.serverOrigin;
315
+
316
+ if (platform === 'win32') {
317
+ return _storeWindows(privateKeyB64Url, { serverOrigin });
318
+ }
319
+ if (platform === 'darwin') {
320
+ return _storeMacOS(privateKeyB64Url);
321
+ }
322
+ return _storeLinux(privateKeyB64Url);
323
+ }
324
+
325
+ /**
326
+ * Retrieve the private key from secure storage.
327
+ * FAILS CLOSED — returns null if secure storage is unavailable or key not found.
328
+ *
329
+ * @param {object} [opts] — optional settings
330
+ * @param {string} [opts.serverOrigin] — server origin for server-scoped storage
331
+ */
332
+ async function loadPrivateKey(opts) {
333
+ const platform = os.platform();
334
+ const serverOrigin = opts && opts.serverOrigin;
335
+
336
+ if (platform === 'win32') {
337
+ return _loadWindows({ serverOrigin });
338
+ }
339
+ if (platform === 'darwin') {
340
+ return _loadMacOS();
341
+ }
342
+ return _loadLinux();
343
+ }
344
+
345
+ /**
346
+ * Delete the private key from secure storage.
347
+ *
348
+ * @param {object} [opts] — optional settings
349
+ * @param {string} [opts.serverOrigin] — server origin for server-scoped deletion.
350
+ * If null, deletes the legacy top-level key only.
351
+ */
352
+ async function deletePrivateKey(opts) {
353
+ const platform = os.platform();
354
+ const serverOrigin = opts && opts.serverOrigin;
355
+
356
+ 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 {}
361
+ }
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
+ return;
366
+ }
367
+ if (platform === 'darwin') {
368
+ try {
369
+ const { execFileSync } = require('child_process');
370
+ execFileSync('security', ['delete-generic-password', '-s', SERVICE_NAME, '-a', ACCOUNT_NAME], {
371
+ stdio: 'ignore',
372
+ windowsHide: true,
373
+ });
374
+ } catch {}
375
+ return;
376
+ }
377
+ // Linux
378
+ try {
379
+ const { execFileSync } = require('child_process');
380
+ execFileSync('secret-tool', ['clear', 'service', SERVICE_NAME], {
381
+ stdio: 'ignore',
382
+ windowsHide: true,
383
+ });
384
+ } catch {}
385
+ }
386
+
387
+ // ── Windows: DPAPI (Defect 10 fix: pass secret via stdin, not argv) ──────────
388
+
389
+ function _storeWindows(privateKeyB64Url, opts) {
390
+ const { execFileSync } = require('child_process');
391
+ // Defect 10: The secret is passed via STDIN, not in the command string.
392
+ // The PowerShell script reads from stdin and feeds it to DPAPI.
393
+ // The process command line never contains the private key.
394
+ const ps =
395
+ "$ErrorActionPreference='Stop'; " +
396
+ "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
397
+ "Add-Type -AssemblyName System.Security; " +
398
+ "$in = [Console]::In.ReadToEnd(); " +
399
+ "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in); " +
400
+ "$b = [System.Security.Cryptography.ProtectedData]::Protect(" +
401
+ "$bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
402
+ "[Console]::Out.Write([Convert]::ToBase64String($b))";
403
+
404
+ // Injectable stage functions (for deterministic testing). In production these
405
+ // default to the real implementations.
406
+ const applyAcl = (opts && opts.applyAcl) || _applyWindowsAclToDeviceKey;
407
+ const verifyAcl = (opts && opts.verifyAcl) || _verifyWindowsAclForDeviceKey;
408
+ const psExe = (opts && opts.psExe) || _powershellExe;
409
+ const serverOrigin = opts && opts.serverOrigin;
410
+
411
+ let protected64;
412
+ try {
413
+ protected64 = execFileSync(psExe(),
414
+ ['-NoProfile', '-NonInteractive', '-Command', ps],
415
+ {
416
+ windowsHide: true,
417
+ encoding: 'utf8',
418
+ timeout: 15000,
419
+ input: privateKeyB64Url, // secret via stdin, NOT argv
420
+ }
421
+ ).trim();
422
+ } catch (e) {
423
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: DPAPI protect stage failed (' +
424
+ _safePowershellError(e) + ')');
425
+ }
426
+ if (!protected64) {
427
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: DPAPI protect stage returned empty output');
428
+ }
429
+
430
+ // Server-scoped directory: create if needed.
431
+ const keyDir = serverOrigin ? getServerDataDir(serverOrigin) : DATA_DIR;
432
+ if (!fs.existsSync(keyDir)) fs.mkdirSync(keyDir, { recursive: true });
433
+
434
+ const keyFile = serverOrigin ? _keyFile(serverOrigin) : path.join(DATA_DIR, '.device-key');
435
+ const tmpFile = path.join(keyDir, `.device-key.tmp.${crypto.randomBytes(6).toString('hex')}`);
436
+ try {
437
+ fs.writeFileSync(tmpFile, JSON.stringify({ scheme: 'dpapi', value: protected64, v: 1 }), {
438
+ encoding: 'utf8',
439
+ });
440
+ } catch (e) {
441
+ try { if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile); } catch {}
442
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: device-key write stage failed (' +
443
+ _safePowershellError(e) + ')');
444
+ }
445
+ // Rollback-safe replacement: never delete a previously valid .device-key on
446
+ // failure. We back up the existing key, promote the candidate, and restore
447
+ // the backup on any failure. Only the candidate (tmp) file is cleaned up.
448
+ const hadExisting = fs.existsSync(keyFile);
449
+ const backupFile = path.join(keyDir, `.device-key.bak.${crypto.randomBytes(6).toString('hex')}`);
450
+ try {
451
+ applyAcl(tmpFile);
452
+ if (hadExisting) {
453
+ fs.renameSync(keyFile, backupFile);
454
+ }
455
+ fs.renameSync(tmpFile, keyFile);
456
+ verifyAcl(keyFile);
457
+ // Success — remove the backup if one was created.
458
+ if (hadExisting) {
459
+ try { if (fs.existsSync(backupFile)) fs.unlinkSync(backupFile); } catch {}
460
+ }
461
+ } catch (aclErr) {
462
+ // Clean up the candidate only — never touch the prior valid key.
463
+ try { if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile); } catch {}
464
+ // Restore the prior key if we moved it aside. Only delete the unverified
465
+ // keyFile when a backup exists to restore — if the failure happened before
466
+ // the backup was created, keyFile is still the prior valid key and must be
467
+ // left untouched.
468
+ if (hadExisting && fs.existsSync(backupFile)) {
469
+ try {
470
+ if (fs.existsSync(keyFile)) fs.unlinkSync(keyFile);
471
+ fs.renameSync(backupFile, keyFile);
472
+ } catch {}
473
+ } else if (!hadExisting) {
474
+ // No prior key existed — remove any partially-promoted file so we don't
475
+ // leave an unverified key on disk.
476
+ try { if (fs.existsSync(keyFile)) fs.unlinkSync(keyFile); } catch {}
477
+ }
478
+ throw aclErr;
479
+ }
480
+ }
481
+
482
+ function _loadWindows(opts) {
483
+ const { execFileSync } = require('child_process');
484
+ const serverOrigin = opts && opts.serverOrigin;
485
+
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');
490
+
491
+ let keyFile = null;
492
+ if (scopedKeyFile && fs.existsSync(scopedKeyFile)) {
493
+ keyFile = scopedKeyFile;
494
+ } else if (fs.existsSync(legacyKeyFile)) {
495
+ keyFile = legacyKeyFile;
496
+ }
497
+
498
+ if (!keyFile) return null;
499
+
500
+ try {
501
+ if (process.env.DEVICE_KEY_VERIFY_ACL_ON_LOAD !== 'false') {
502
+ _verifyWindowsAclForDeviceKey(keyFile);
503
+ }
504
+ const envelope = JSON.parse(fs.readFileSync(keyFile, 'utf8'));
505
+ if (envelope.scheme !== 'dpapi' || !envelope.value) {
506
+ throw new Error('Invalid key envelope');
507
+ }
508
+
509
+ // Defect 10: Pass the protected blob via stdin, not in the command string.
510
+ const ps =
511
+ "$ErrorActionPreference='Stop'; " +
512
+ "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
513
+ "Add-Type -AssemblyName System.Security; " +
514
+ "$in = [Console]::In.ReadToEnd().Trim(); " +
515
+ "$b = [System.Security.Cryptography.ProtectedData]::Unprotect(" +
516
+ "[Convert]::FromBase64String($in), " +
517
+ "$null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
518
+ "[Console]::Out.Write([Convert]::ToBase64String($b))";
519
+
520
+ const b64 = execFileSync(_powershellExe(),
521
+ ['-NoProfile', '-NonInteractive', '-Command', ps],
522
+ {
523
+ windowsHide: true,
524
+ encoding: 'utf8',
525
+ timeout: 15000,
526
+ input: envelope.value, // protected blob via stdin
527
+ }
528
+ ).trim();
529
+
530
+ return Buffer.from(b64, 'base64').toString('utf8');
531
+ } catch (e) {
532
+ // Fail closed — do NOT fall back to plaintext
533
+ return null;
534
+ }
535
+ }
536
+
537
+ /**
538
+ * Phase 8: Apply explicit Windows ACL to the device-key file.
539
+ * Reuses the hardened ACL pattern from profilePath.js:
540
+ * - Only current user, SYSTEM, and Administrators get Allow ACEs.
541
+ * - Inheritance is disabled (protected DACL).
542
+ * - Unexpected Allow ACEs (Everyone, Authenticated Users, BUILTIN\Users)
543
+ * are removed.
544
+ * - This is more robust than relying only on POSIX mode 0o600.
545
+ */
546
+ function _applyWindowsAclToDeviceKey(keyFile) {
547
+ const { spawnSync } = require('child_process');
548
+ const ownerSid = _currentWindowsUserSid();
549
+ const aclScript = `
550
+ $ErrorActionPreference = 'Stop'
551
+ $path = '${keyFile.replace(/'/g, "''")}'
552
+ $ownerSid = '${ownerSid}'
553
+ $acl = New-Object System.Security.AccessControl.FileSecurity
554
+ $acl.SetAccessRuleProtection($true, $false)
555
+ $colRights = [System.Security.AccessControl.FileSystemRights]::FullControl
556
+ $inhFlags = [System.Security.AccessControl.InheritanceFlags]::None
557
+ $propFlags = [System.Security.AccessControl.PropagationFlags]::None
558
+ $rule = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier($ownerSid)), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
559
+ $acl.AddAccessRule($rule)
560
+ $rule2 = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
561
+ $acl.AddAccessRule($rule2)
562
+ $rule3 = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18')), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
563
+ $acl.AddAccessRule($rule3)
564
+ [System.IO.File]::SetAccessControl($path, $acl)
565
+ `;
566
+ const apply = spawnSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', aclScript], {
567
+ windowsHide: true, encoding: 'utf8', timeout: 10000,
568
+ });
569
+ if (apply.status !== 0 || (apply.stderr && apply.stderr.trim())) {
570
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL apply stage failed (' +
571
+ _safePowershellError(apply) + ')');
572
+ }
573
+ _verifyWindowsAclForDeviceKey(keyFile, ownerSid);
574
+ }
575
+
576
+ function _currentWindowsUserSid() {
577
+ const { spawnSync } = require('child_process');
578
+ const ownerSidResult = spawnSync(_powershellExe(), [
579
+ '-NoProfile', '-NonInteractive', '-Command',
580
+ '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
581
+ ], { windowsHide: true, encoding: 'utf8', timeout: 10000 });
582
+ if (ownerSidResult.status !== 0 || (ownerSidResult.stderr && ownerSidResult.stderr.trim()) || !ownerSidResult.stdout.trim()) {
583
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows SID lookup stage failed (' +
584
+ _safePowershellError(ownerSidResult) + ')');
585
+ }
586
+ return ownerSidResult.stdout.trim();
587
+ }
588
+
589
+ function _verifyWindowsAclForDeviceKey(keyFile, ownerSid) {
590
+ const { spawnSync } = require('child_process');
591
+ const currentSid = ownerSid || _currentWindowsUserSid();
592
+ const verifyScript = `
593
+ $ErrorActionPreference = 'Stop'
594
+ $path = '${keyFile.replace(/'/g, "''")}'
595
+ $ownerSid = '${currentSid}'
596
+ $acl = (Get-Item -LiteralPath $path).GetAccessControl()
597
+ $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])
598
+ $allowed = @($ownerSid, 'S-1-5-18', 'S-1-5-32-544')
599
+ $leaked = @()
600
+ $ownerHasAccess = $false
601
+ foreach ($rule in $rules) {
602
+ $sid = $rule.IdentityReference.Value
603
+ if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow) {
604
+ if ($allowed -notcontains $sid) { $leaked += $sid }
605
+ if ($sid -eq $ownerSid) { $ownerHasAccess = $true }
606
+ }
607
+ }
608
+ @{
609
+ areAccessRulesProtected = $acl.AreAccessRulesProtected
610
+ leaked = ($leaked -join '|')
611
+ ownerHasAccess = $ownerHasAccess
612
+ } | ConvertTo-Json -Compress
613
+ `;
614
+ const verify = spawnSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', verifyScript], {
615
+ windowsHide: true, encoding: 'utf8', timeout: 10000,
616
+ });
617
+ if (verify.status !== 0 || (verify.stderr && verify.stderr.trim())) {
618
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL read-back stage failed (' +
619
+ _safePowershellError(verify) + ')');
620
+ }
621
+ let data;
622
+ try { data = JSON.parse(verify.stdout.trim()); } catch {
623
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: Windows device-key ACL read-back invalid');
624
+ }
625
+ 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');
628
+ }
629
+ return data;
630
+ }
631
+
632
+ // ── macOS: Keychain (Phase 8: fail closed — argv exposure) ──────────────────
633
+ // The macOS `security` command requires the secret as a -w argument, which
634
+ // puts it in the child-process argv. This violates the threat model.
635
+ // Until a safe native Keychain integration exists (using stdin or a native
636
+ // helper), macOS secure storage is UNSUPPORTED and fails closed.
637
+
638
+ function _storeMacOS(_privateKeyB64Url) {
639
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: macOS Keychain storage is not yet supported. The macOS `security` command exposes the secret in process arguments. A native Keychain helper is required.');
640
+ }
641
+
642
+ function _loadMacOS() {
643
+ // macOS storage is not supported — fail closed.
644
+ return null;
645
+ }
646
+
647
+ // ── Linux: Secret Service / libsecret ────────────────────────────────────────
648
+
649
+ function _storeLinux(privateKeyB64Url) {
650
+ const { execFileSync } = require('child_process');
651
+ try {
652
+ // Use secret-tool if available
653
+ execFileSync('secret-tool', ['store', '--label', 'XKWDStore Agent Device Key', 'service', SERVICE_NAME, 'account', ACCOUNT_NAME], {
654
+ input: privateKeyB64Url,
655
+ encoding: 'utf8',
656
+ windowsHide: true,
657
+ timeout: 10000,
658
+ });
659
+ } catch (e) {
660
+ // Check if GNOME keyring file fallback is available
661
+ // If secret-tool is not available, fail closed
662
+ throw new Error('SECURE_STORAGE_UNAVAILABLE: Secret Service (libsecret) not available. Install seahorse or gnome-keyring.');
663
+ }
664
+ }
665
+
666
+ function _loadLinux() {
667
+ const { execFileSync } = require('child_process');
668
+ try {
669
+ const result = execFileSync('secret-tool', ['lookup', 'service', SERVICE_NAME, 'account', ACCOUNT_NAME], {
670
+ encoding: 'utf8',
671
+ windowsHide: true,
672
+ timeout: 10000,
673
+ }).trim();
674
+ return result;
675
+ } catch (e) {
676
+ // Fail closed
677
+ return null;
678
+ }
679
+ }
680
+
681
+ // ── Device metadata (non-secret, plaintext) ──────────────────────────────────
682
+
683
+ /**
684
+ * Load non-secret device metadata from the plaintext metadata file.
685
+ * This does NOT contain the private key.
686
+ *
687
+ * @param {object} [opts] — optional settings
688
+ * @param {string} [opts.serverOrigin] — server origin for server-scoped metadata.
689
+ * If null, tries the legacy top-level file (for migration reads).
690
+ */
691
+ function loadMetadata(opts) {
692
+ const serverOrigin = opts && opts.serverOrigin;
693
+
694
+ // Try server-scoped metadata first
695
+ if (serverOrigin) {
696
+ _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;
703
+ }
704
+ }
705
+ }
706
+
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;
714
+ }
715
+ }
716
+
717
+ /**
718
+ * Save non-secret device metadata.
719
+ * @param {object} meta — { deviceId, publicKeyB64Url, publicKeyFingerprint, deviceName, serverOrigin }
720
+ * @param {object} [opts] — optional settings
721
+ * @param {string} [opts.serverOrigin] — server origin for server-scoped metadata.
722
+ * If null, saves to the legacy top-level file.
723
+ */
724
+ function saveMetadata(meta, opts) {
725
+ 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');
728
+
729
+ if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir, { recursive: true });
730
+
731
+ // Ensure no private key accidentally ends up in metadata
732
+ const safe = {
733
+ deviceId: meta.deviceId,
734
+ publicKeyB64Url: meta.publicKeyB64Url,
735
+ publicKeyFingerprint: meta.publicKeyFingerprint,
736
+ deviceName: meta.deviceName,
737
+ serverOrigin: meta.serverOrigin,
738
+ createdAt: meta.createdAt || new Date().toISOString(),
739
+ };
740
+ fs.writeFileSync(targetFile, JSON.stringify(safe, null, 2), {
741
+ encoding: 'utf8',
742
+ mode: 0o600,
743
+ });
744
+ }
745
+
746
+ /**
747
+ * Delete the metadata file.
748
+ *
749
+ * @param {object} [opts] — optional settings
750
+ * @param {string} [opts.serverOrigin] — server origin for server-scoped deletion.
751
+ * If null, deletes the legacy top-level file only.
752
+ */
753
+ function deleteMetadata(opts) {
754
+ const serverOrigin = opts && opts.serverOrigin;
755
+
756
+ if (serverOrigin) {
757
+ const scopedFile = _metadataFile(serverOrigin);
758
+ try { if (fs.existsSync(scopedFile)) fs.unlinkSync(scopedFile); } catch {}
759
+ }
760
+
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 {}
764
+ }
765
+
766
+ /**
767
+ * Check if secure storage is available on this platform.
768
+ * @returns {boolean}
769
+ */
770
+ function isSecureStorageAvailable() {
771
+ const platform = os.platform();
772
+ if (platform === 'win32') return true; // DPAPI is always available on Windows
773
+ if (platform === 'darwin') return false; // Phase 8: macOS not supported (argv exposure)
774
+ // Linux
775
+ try {
776
+ const { execFileSync } = require('child_process');
777
+ execFileSync('which', ['secret-tool'], { stdio: 'ignore', windowsHide: true });
778
+ return true;
779
+ } catch { return false; }
780
+ }
781
+
782
+ // ── Windows PowerShell 5.1 absolute path (exported for tests/probe) ─────────
783
+
784
+ /**
785
+ * Reduce a child_process error to a short, safe stage message.
786
+ * Never includes the private key (which is only ever on stdin).
787
+ */
788
+ function _safePowershellError(e) {
789
+ if (!e) return 'unknown error';
790
+ if (typeof e === 'string') return e.slice(0, 200);
791
+ const msg = (e.message || e.stderr || '').toString();
792
+ // Strip multi-line PowerShell noise, keep the first meaningful line.
793
+ const first = String(msg).split(/\r?\n/).find(l => l.trim()) || 'powershell failed';
794
+ return first.slice(0, 200);
795
+ }
796
+
797
+ /**
798
+ * Non-destructive DPAPI + ACL storage probe (Windows only).
799
+ *
800
+ * Performs the same stages as a real key store WITHOUT persisting any key:
801
+ * 1. DPAPI Protect — round-trips a throwaway nonce through PowerShell DPAPI.
802
+ * 2. DPAPI Unprotect — reverses it and confirms the nonce matches.
803
+ * 3. Windows SID lookup — resolves the current user SID.
804
+ * 4. ACL application — writes a throwaway probe file and applies the ACL.
805
+ * 5. ACL verification — reads back the ACL and confirms it is locked down.
806
+ *
807
+ * Returns { ok: boolean, stages: { protect, unprotect, sidLookup, aclApply, aclVerify }, detail?: string }.
808
+ * The probe file is always deleted. Never throws — callers decide what to do.
809
+ */
810
+ function probeWindowsStorage() {
811
+ const { execFileSync, spawnSync } = require('child_process');
812
+ const stages = {
813
+ protect: false,
814
+ unprotect: false,
815
+ sidLookup: false,
816
+ aclApply: false,
817
+ aclVerify: false,
818
+ };
819
+ if (os.platform() !== 'win32') {
820
+ return { ok: false, stages, detail: 'probe is Windows-only' };
821
+ }
822
+ const nonce = crypto.randomBytes(16).toString('base64url');
823
+ const psProtect =
824
+ "$ErrorActionPreference='Stop'; " +
825
+ "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
826
+ "Add-Type -AssemblyName System.Security; " +
827
+ "$in = [Console]::In.ReadToEnd(); " +
828
+ "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in); " +
829
+ "$b = [System.Security.Cryptography.ProtectedData]::Protect(" +
830
+ "$bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
831
+ "[Console]::Out.Write([Convert]::ToBase64String($b))";
832
+ let protected64 = '';
833
+ try {
834
+ protected64 = execFileSync(_powershellExe(),
835
+ ['-NoProfile', '-NonInteractive', '-Command', psProtect],
836
+ { windowsHide: true, encoding: 'utf8', timeout: 15000, input: nonce }
837
+ ).trim();
838
+ stages.protect = !!protected64;
839
+ } catch (e) {
840
+ return { ok: false, stages, detail: 'DPAPI protect stage failed (' + _safePowershellError(e) + ')' };
841
+ }
842
+ const psUnprotect =
843
+ "$ErrorActionPreference='Stop'; " +
844
+ "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
845
+ "Add-Type -AssemblyName System.Security; " +
846
+ "$in = [Console]::In.ReadToEnd().Trim(); " +
847
+ "$b = [System.Security.Cryptography.ProtectedData]::Unprotect(" +
848
+ "[Convert]::FromBase64String($in), " +
849
+ "$null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
850
+ "[Console]::Out.Write([Convert]::ToBase64String($b))";
851
+ try {
852
+ const back = execFileSync(_powershellExe(),
853
+ ['-NoProfile', '-NonInteractive', '-Command', psUnprotect],
854
+ { windowsHide: true, encoding: 'utf8', timeout: 15000, input: protected64 }
855
+ ).trim();
856
+ stages.unprotect = Buffer.from(back, 'base64').toString('utf8') === nonce;
857
+ } catch (e) {
858
+ return { ok: false, stages, detail: 'DPAPI unprotect stage failed (' + _safePowershellError(e) + ')' };
859
+ }
860
+ let sid = '';
861
+ try {
862
+ const sidRes = spawnSync(_powershellExe(), [
863
+ '-NoProfile', '-NonInteractive', '-Command',
864
+ '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
865
+ ], { windowsHide: true, encoding: 'utf8', timeout: 10000 });
866
+ sid = (sidRes.stdout || '').trim();
867
+ stages.sidLookup = !!sid && sidRes.status === 0;
868
+ } catch (e) {
869
+ return { ok: false, stages, detail: 'Windows SID lookup stage failed (' + _safePowershellError(e) + ')' };
870
+ }
871
+ if (!stages.sidLookup) {
872
+ return { ok: false, stages, detail: 'Windows SID lookup stage returned empty' };
873
+ }
874
+ if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
875
+ const probeFile = path.join(DATA_DIR, `.dpapi-probe.${crypto.randomBytes(6).toString('hex')}`);
876
+ try {
877
+ fs.writeFileSync(probeFile, Buffer.from('probe'));
878
+ } catch (e) {
879
+ return { ok: false, stages, detail: 'probe file write failed (' + _safePowershellError(e) + ')' };
880
+ }
881
+ try {
882
+ const aclScript = `
883
+ $ErrorActionPreference = 'Stop'
884
+ $path = '${probeFile.replace(/'/g, "''")}'
885
+ $ownerSid = '${sid}'
886
+ $acl = New-Object System.Security.AccessControl.FileSecurity
887
+ $acl.SetAccessRuleProtection($true, $false)
888
+ $colRights = [System.Security.AccessControl.FileSystemRights]::FullControl
889
+ $inhFlags = [System.Security.AccessControl.InheritanceFlags]::None
890
+ $propFlags = [System.Security.AccessControl.PropagationFlags]::None
891
+ $rule = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier($ownerSid)), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
892
+ $acl.AddAccessRule($rule)
893
+ $rule2 = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
894
+ $acl.AddAccessRule($rule2)
895
+ $rule3 = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18')), $colRights, $inhFlags, $propFlags, [System.Security.AccessControl.AccessControlType]::Allow)
896
+ $acl.AddAccessRule($rule3)
897
+ [System.IO.File]::SetAccessControl($path, $acl)
898
+ `;
899
+ const apply = spawnSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', aclScript], {
900
+ windowsHide: true, encoding: 'utf8', timeout: 10000,
901
+ });
902
+ stages.aclApply = apply.status === 0 && !(apply.stderr && apply.stderr.trim());
903
+ } catch (e) {
904
+ try { fs.unlinkSync(probeFile); } catch {}
905
+ return { ok: false, stages, detail: 'ACL apply stage failed (' + _safePowershellError(e) + ')' };
906
+ }
907
+ try {
908
+ const data = _verifyWindowsAclForDeviceKey(probeFile, sid);
909
+ stages.aclVerify = data.areAccessRulesProtected === true &&
910
+ data.ownerHasAccess === true &&
911
+ String(data.leaked || '').split('|').filter(Boolean).length === 0;
912
+ } catch (e) {
913
+ try { fs.unlinkSync(probeFile); } catch {}
914
+ return { ok: false, stages, detail: 'ACL verify stage failed (' + _safePowershellError(e) + ')' };
915
+ } finally {
916
+ try { if (fs.existsSync(probeFile)) fs.unlinkSync(probeFile); } catch {}
917
+ }
918
+ const ok = stages.protect && stages.unprotect && stages.sidLookup && stages.aclApply && stages.aclVerify;
919
+ return { ok, stages, detail: ok ? 'all storage stages passed' : 'one or more storage stages failed' };
920
+ }
921
+
922
+ module.exports = {
923
+ generateKeyPair,
924
+ loadPrivateKeyFromDer,
925
+ signMessage,
926
+ storePrivateKey,
927
+ loadPrivateKeyFromStorage: loadPrivateKey,
928
+ deletePrivateKey,
929
+ loadMetadata,
930
+ saveMetadata,
931
+ deleteMetadata,
932
+ isSecureStorageAvailable,
933
+ _applyWindowsAclToDeviceKey,
934
+ _verifyWindowsAclForDeviceKey,
935
+ _powershellExe,
936
+ _safePowershellError,
937
+ _storeWindows,
938
+ probeWindowsStorage,
939
+ getDataDir,
940
+ getServerDataDir,
941
+ normalizeServerOrigin,
942
+ _migrateLegacyIdentity,
943
+ DATA_DIR,
944
+ PROFILES_DIR,
945
+ LOGS_DIR,
946
+ METADATA_FILE,
947
+ };