@xkwdstore/agent 2.0.1 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +251 -244
- package/package.json +54 -54
- package/src/actions/comment.js +137 -137
- package/src/actions/dbc.js +149 -149
- package/src/actions/follow.js +82 -82
- package/src/actions/helpers.js +753 -753
- package/src/actions/index.js +94 -94
- package/src/actions/like.js +244 -244
- package/src/actions/session.js +1610 -1610
- package/src/actions/tweet.js +90 -90
- package/src/challengeCodec.js +31 -31
- package/src/chromeDetector.js +154 -154
- package/src/cli.js +664 -528
- package/src/configStore.js +97 -97
- package/src/deviceKeyStore.js +947 -700
- package/src/enrollmentClient.js +588 -445
- package/src/fingerprint.js +261 -261
- package/src/fingerprintStore.js +125 -125
- package/src/leaseClient.js +84 -84
- package/src/processLock.js +148 -148
- package/src/profilePath.js +1116 -1116
- package/src/proxyEgress.js +338 -338
- package/src/proxyPolicy.js +76 -76
- package/src/secretStore.js +132 -132
- package/src/sessionHandler.js +618 -452
- package/src/stealth.js +1250 -1250
- package/src/wsClient.js +233 -233
package/src/deviceKeyStore.js
CHANGED
|
@@ -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
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
//
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
if (
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
//
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
const
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
$
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
$
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
//
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
//
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
const
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
const
|
|
548
|
-
|
|
549
|
-
const
|
|
550
|
-
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
}
|
|
578
|
-
const
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
windowsHide: true,
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
} catch (e) {
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
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
|
+
};
|