@xkwdstore/agent 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ 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
+ };