@xkwdstore/agent 2.0.2 → 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 -253
- 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 -581
- 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/cli.js
CHANGED
|
@@ -1,529 +1,665 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
'use strict';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* XKWDStore Agent — Terminal-only CLI (protocol v2).
|
|
6
|
-
*
|
|
7
|
-
* Replaces the desktop-agent distribution, pairing-code workflow, updater,
|
|
8
|
-
* and in-memory WebSocket ticket architecture with a simpler, safer
|
|
9
|
-
* terminal-first system.
|
|
10
|
-
*
|
|
11
|
-
* Usage:
|
|
12
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> start
|
|
13
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> status
|
|
14
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
|
|
15
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
|
|
16
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
|
|
17
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> version
|
|
18
|
-
*
|
|
19
|
-
* The agent runs only while the terminal process is running.
|
|
20
|
-
* Closing the terminal or pressing Ctrl+C stops the agent cleanly.
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
const crypto = require('crypto');
|
|
24
|
-
const os = require('os');
|
|
25
|
-
const path = require('path');
|
|
26
|
-
|
|
27
|
-
const CLI_VERSION = '2.0.
|
|
28
|
-
const PROTOCOL_VERSION = 2;
|
|
29
|
-
|
|
30
|
-
// ── Command parsing ──────────────────────────────────────────────────────────
|
|
31
|
-
|
|
32
|
-
function main() {
|
|
33
|
-
const args = process.argv.slice(2);
|
|
34
|
-
const command = args[0] || 'help';
|
|
35
|
-
const flags = {};
|
|
36
|
-
const positional = [];
|
|
37
|
-
|
|
38
|
-
for (let i = 1; i < args.length; i++) {
|
|
39
|
-
const arg = args[i];
|
|
40
|
-
if (arg.startsWith('--')) {
|
|
41
|
-
const key = arg.slice(2);
|
|
42
|
-
const next = args[i + 1];
|
|
43
|
-
if (next && !next.startsWith('--')) {
|
|
44
|
-
flags[key] = next;
|
|
45
|
-
i++;
|
|
46
|
-
} else {
|
|
47
|
-
flags[key] = true;
|
|
48
|
-
}
|
|
49
|
-
} else {
|
|
50
|
-
positional.push(arg);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const serverOrigin = flags.server ||
|
|
55
|
-
process.env.XKWDSTORE_SERVER ||
|
|
56
|
-
'https://x.kwdstore.com';
|
|
57
|
-
|
|
58
|
-
switch (command) {
|
|
59
|
-
case 'start':
|
|
60
|
-
return start(serverOrigin, flags);
|
|
61
|
-
case 'status':
|
|
62
|
-
return status();
|
|
63
|
-
case 'logout':
|
|
64
|
-
return logout();
|
|
65
|
-
case 'revoke-local':
|
|
66
|
-
return revokeLocal();
|
|
67
|
-
case 'doctor':
|
|
68
|
-
return doctor(serverOrigin);
|
|
69
|
-
case 'version':
|
|
70
|
-
return version();
|
|
71
|
-
case 'help':
|
|
72
|
-
case '--help':
|
|
73
|
-
case '-h':
|
|
74
|
-
default:
|
|
75
|
-
return help();
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// ── Commands ─────────────────────────────────────────────────────────────────
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* `xkwd-agent start` — the main runtime command.
|
|
83
|
-
*/
|
|
84
|
-
async function start(serverOrigin, flags) {
|
|
85
|
-
console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
|
|
86
|
-
console.log(`Server: ${serverOrigin}`);
|
|
87
|
-
console.log();
|
|
88
|
-
|
|
89
|
-
// 1. Detect OS and architecture (for display)
|
|
90
|
-
const platform = os.platform();
|
|
91
|
-
const arch = os.arch();
|
|
92
|
-
const hostname = os.hostname();
|
|
93
|
-
console.log(`✓ Detected computer: ${hostname}`);
|
|
94
|
-
console.log(`✓ Platform: ${platform} ${arch}`);
|
|
95
|
-
|
|
96
|
-
// 2. Resolve system Chrome (fail clearly if missing)
|
|
97
|
-
const { resolveChromeOrFail } = require('./chromeDetector');
|
|
98
|
-
let chromePath, chromeVersion;
|
|
99
|
-
try {
|
|
100
|
-
const chrome = resolveChromeOrFail();
|
|
101
|
-
chromePath = chrome.chromePath;
|
|
102
|
-
chromeVersion = chrome.chromeVersion;
|
|
103
|
-
console.log(`✓ Chrome ${chromeVersion || 'detected'}: ${chromePath}`);
|
|
104
|
-
} catch (e) {
|
|
105
|
-
console.error(e.message);
|
|
106
|
-
process.exit(1);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// 3. Check compatibility with server (shared strict validator)
|
|
110
|
-
const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
|
|
111
|
-
try {
|
|
112
|
-
const compatResp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
|
|
113
|
-
const compat = validateCompatibilityResponse(compatResp);
|
|
114
|
-
if (compat.html) {
|
|
115
|
-
console.error('\n' + COMPAT_HTML_MESSAGE);
|
|
116
|
-
process.exit(1);
|
|
117
|
-
}
|
|
118
|
-
if (!compat.ok) {
|
|
119
|
-
console.error('\nServer compatibility check failed: ' + compat.reason + '.');
|
|
120
|
-
console.error('The agent will not start enrollment until the server is compatible.');
|
|
121
|
-
process.exit(1);
|
|
122
|
-
}
|
|
123
|
-
// compat.ok — enforce minimum agent version
|
|
124
|
-
const minVer = compat.body.minimumAgentVersion;
|
|
125
|
-
const recVer = compat.body.recommendedAgentVersion;
|
|
126
|
-
if (minVer && _compareVersions(CLI_VERSION, minVer) < 0) {
|
|
127
|
-
console.error(`\nThis agent version (${CLI_VERSION}) is no longer supported.`);
|
|
128
|
-
console.error(`\nRun:\n\n npx --yes @xkwdstore/agent@${recVer} start\n`);
|
|
129
|
-
process.exit(1);
|
|
130
|
-
}
|
|
131
|
-
} catch (e) {
|
|
132
|
-
console.error(`\nServer compatibility check failed: ${e.message}`);
|
|
133
|
-
console.error('The agent will not start enrollment until the server is reachable and compatible.');
|
|
134
|
-
process.exit(1);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// 4. Load or generate device key
|
|
138
|
-
const { getStoredDevice, getStoredPrivateKey, enroll } = require('./enrollmentClient');
|
|
139
|
-
const { isSecureStorageAvailable } = require('./deviceKeyStore');
|
|
140
|
-
|
|
141
|
-
if (!isSecureStorageAvailable()) {
|
|
142
|
-
console.error('Secure key storage is unavailable on this system.');
|
|
143
|
-
if (os.platform() === 'win32') {
|
|
144
|
-
console.error('On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available.');
|
|
145
|
-
} else {
|
|
146
|
-
console.error('On Linux, install gnome-keyring or seahorse (libsecret).');
|
|
147
|
-
}
|
|
148
|
-
console.error('The agent cannot run without secure key storage.');
|
|
149
|
-
process.exit(1);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
let deviceMeta = getStoredDevice();
|
|
153
|
-
let privateKeyB64Url = await getStoredPrivateKey();
|
|
154
|
-
|
|
155
|
-
// 5. Authorize the device when needed (first run or revoked)
|
|
156
|
-
if (!deviceMeta || !privateKeyB64Url) {
|
|
157
|
-
console.log('\n✓ Device identity loaded securely');
|
|
158
|
-
try {
|
|
159
|
-
const result = await enroll(serverOrigin, { chromePath });
|
|
160
|
-
deviceMeta = require('./deviceKeyStore').loadMetadata();
|
|
161
|
-
privateKeyB64Url = await getStoredPrivateKey();
|
|
162
|
-
} catch (e) {
|
|
163
|
-
console.error(`\nEnrollment failed: ${e.message}`);
|
|
164
|
-
process.exit(1);
|
|
165
|
-
}
|
|
166
|
-
} else {
|
|
167
|
-
console.log(`✓ Device identity loaded securely`);
|
|
168
|
-
console.log(`✓ Device recognized: ${deviceMeta.deviceName}`);
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// 6. Process lock (prevent duplicate instances)
|
|
172
|
-
const processLock = require('./processLock');
|
|
173
|
-
const lockResult = processLock.acquireLock({
|
|
174
|
-
deviceId: deviceMeta.deviceId,
|
|
175
|
-
deviceName: deviceMeta.deviceName,
|
|
176
|
-
});
|
|
177
|
-
|
|
178
|
-
if (!lockResult.acquired) {
|
|
179
|
-
if (flags.replace) {
|
|
180
|
-
console.log('\nAnother agent instance is running. Requesting takeover...');
|
|
181
|
-
const took = await processLock.requestTakeover(lockResult.existing);
|
|
182
|
-
if (!took) {
|
|
183
|
-
console.error('Could not stop the existing instance. Please close it manually.');
|
|
184
|
-
process.exit(1);
|
|
185
|
-
}
|
|
186
|
-
// Re-acquire the lock
|
|
187
|
-
const retryLock = processLock.acquireLock({
|
|
188
|
-
deviceId: deviceMeta.deviceId,
|
|
189
|
-
deviceName: deviceMeta.deviceName,
|
|
190
|
-
});
|
|
191
|
-
if (!retryLock.acquired) {
|
|
192
|
-
console.error('Could not acquire process lock after takeover.');
|
|
193
|
-
process.exit(1);
|
|
194
|
-
}
|
|
195
|
-
} else {
|
|
196
|
-
console.error('\nXKWDStore Agent is already running on this computer.');
|
|
197
|
-
console.error(`PID: ${lockResult.existing.pid}`);
|
|
198
|
-
console.error(`Started: ${lockResult.existing.startedAt}`);
|
|
199
|
-
console.error(`Device: ${lockResult.existing.deviceName || 'unknown'}`);
|
|
200
|
-
console.error('\nTo replace the running instance, use:');
|
|
201
|
-
console.error(' xkwd-agent start --replace');
|
|
202
|
-
process.exit(1);
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// 7. Connect securely via WebSocket challenge-response
|
|
207
|
-
|
|
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
|
-
|
|
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
|
-
const
|
|
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
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
//
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
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
|
-
const
|
|
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
|
-
}
|
|
449
|
-
}
|
|
450
|
-
console.log(
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
/**
|
|
455
|
-
* `xkwd-agent
|
|
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
|
-
The
|
|
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
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* XKWDStore Agent — Terminal-only CLI (protocol v2).
|
|
6
|
+
*
|
|
7
|
+
* Replaces the desktop-agent distribution, pairing-code workflow, updater,
|
|
8
|
+
* and in-memory WebSocket ticket architecture with a simpler, safer
|
|
9
|
+
* terminal-first system.
|
|
10
|
+
*
|
|
11
|
+
* Usage:
|
|
12
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> start
|
|
13
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> status
|
|
14
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
|
|
15
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
|
|
16
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
|
|
17
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> version
|
|
18
|
+
*
|
|
19
|
+
* The agent runs only while the terminal process is running.
|
|
20
|
+
* Closing the terminal or pressing Ctrl+C stops the agent cleanly.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const crypto = require('crypto');
|
|
24
|
+
const os = require('os');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
|
|
27
|
+
const CLI_VERSION = '2.0.3';
|
|
28
|
+
const PROTOCOL_VERSION = 2;
|
|
29
|
+
|
|
30
|
+
// ── Command parsing ──────────────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
function main() {
|
|
33
|
+
const args = process.argv.slice(2);
|
|
34
|
+
const command = args[0] || 'help';
|
|
35
|
+
const flags = {};
|
|
36
|
+
const positional = [];
|
|
37
|
+
|
|
38
|
+
for (let i = 1; i < args.length; i++) {
|
|
39
|
+
const arg = args[i];
|
|
40
|
+
if (arg.startsWith('--')) {
|
|
41
|
+
const key = arg.slice(2);
|
|
42
|
+
const next = args[i + 1];
|
|
43
|
+
if (next && !next.startsWith('--')) {
|
|
44
|
+
flags[key] = next;
|
|
45
|
+
i++;
|
|
46
|
+
} else {
|
|
47
|
+
flags[key] = true;
|
|
48
|
+
}
|
|
49
|
+
} else {
|
|
50
|
+
positional.push(arg);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const serverOrigin = flags.server ||
|
|
55
|
+
process.env.XKWDSTORE_SERVER ||
|
|
56
|
+
'https://x.kwdstore.com';
|
|
57
|
+
|
|
58
|
+
switch (command) {
|
|
59
|
+
case 'start':
|
|
60
|
+
return start(serverOrigin, flags);
|
|
61
|
+
case 'status':
|
|
62
|
+
return status();
|
|
63
|
+
case 'logout':
|
|
64
|
+
return logout();
|
|
65
|
+
case 'revoke-local':
|
|
66
|
+
return revokeLocal();
|
|
67
|
+
case 'doctor':
|
|
68
|
+
return doctor(serverOrigin);
|
|
69
|
+
case 'version':
|
|
70
|
+
return version();
|
|
71
|
+
case 'help':
|
|
72
|
+
case '--help':
|
|
73
|
+
case '-h':
|
|
74
|
+
default:
|
|
75
|
+
return help();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ── Commands ─────────────────────────────────────────────────────────────────
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* `xkwd-agent start` — the main runtime command.
|
|
83
|
+
*/
|
|
84
|
+
async function start(serverOrigin, flags) {
|
|
85
|
+
console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
|
|
86
|
+
console.log(`Server: ${serverOrigin}`);
|
|
87
|
+
console.log();
|
|
88
|
+
|
|
89
|
+
// 1. Detect OS and architecture (for display)
|
|
90
|
+
const platform = os.platform();
|
|
91
|
+
const arch = os.arch();
|
|
92
|
+
const hostname = os.hostname();
|
|
93
|
+
console.log(`✓ Detected computer: ${hostname}`);
|
|
94
|
+
console.log(`✓ Platform: ${platform} ${arch}`);
|
|
95
|
+
|
|
96
|
+
// 2. Resolve system Chrome (fail clearly if missing)
|
|
97
|
+
const { resolveChromeOrFail } = require('./chromeDetector');
|
|
98
|
+
let chromePath, chromeVersion;
|
|
99
|
+
try {
|
|
100
|
+
const chrome = resolveChromeOrFail();
|
|
101
|
+
chromePath = chrome.chromePath;
|
|
102
|
+
chromeVersion = chrome.chromeVersion;
|
|
103
|
+
console.log(`✓ Chrome ${chromeVersion || 'detected'}: ${chromePath}`);
|
|
104
|
+
} catch (e) {
|
|
105
|
+
console.error(e.message);
|
|
106
|
+
process.exit(1);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// 3. Check compatibility with server (shared strict validator)
|
|
110
|
+
const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
|
|
111
|
+
try {
|
|
112
|
+
const compatResp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
|
|
113
|
+
const compat = validateCompatibilityResponse(compatResp);
|
|
114
|
+
if (compat.html) {
|
|
115
|
+
console.error('\n' + COMPAT_HTML_MESSAGE);
|
|
116
|
+
process.exit(1);
|
|
117
|
+
}
|
|
118
|
+
if (!compat.ok) {
|
|
119
|
+
console.error('\nServer compatibility check failed: ' + compat.reason + '.');
|
|
120
|
+
console.error('The agent will not start enrollment until the server is compatible.');
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
// compat.ok — enforce minimum agent version
|
|
124
|
+
const minVer = compat.body.minimumAgentVersion;
|
|
125
|
+
const recVer = compat.body.recommendedAgentVersion;
|
|
126
|
+
if (minVer && _compareVersions(CLI_VERSION, minVer) < 0) {
|
|
127
|
+
console.error(`\nThis agent version (${CLI_VERSION}) is no longer supported.`);
|
|
128
|
+
console.error(`\nRun:\n\n npx --yes @xkwdstore/agent@${recVer} start\n`);
|
|
129
|
+
process.exit(1);
|
|
130
|
+
}
|
|
131
|
+
} catch (e) {
|
|
132
|
+
console.error(`\nServer compatibility check failed: ${e.message}`);
|
|
133
|
+
console.error('The agent will not start enrollment until the server is reachable and compatible.');
|
|
134
|
+
process.exit(1);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// 4. Load or generate device key (server-scoped: per-server identity)
|
|
138
|
+
const { getStoredDevice, getStoredPrivateKey, enroll } = require('./enrollmentClient');
|
|
139
|
+
const { isSecureStorageAvailable } = require('./deviceKeyStore');
|
|
140
|
+
|
|
141
|
+
if (!isSecureStorageAvailable()) {
|
|
142
|
+
console.error('Secure key storage is unavailable on this system.');
|
|
143
|
+
if (os.platform() === 'win32') {
|
|
144
|
+
console.error('On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available.');
|
|
145
|
+
} else {
|
|
146
|
+
console.error('On Linux, install gnome-keyring or seahorse (libsecret).');
|
|
147
|
+
}
|
|
148
|
+
console.error('The agent cannot run without secure key storage.');
|
|
149
|
+
process.exit(1);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let deviceMeta = getStoredDevice({ serverOrigin });
|
|
153
|
+
let privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
154
|
+
|
|
155
|
+
// 5. Authorize the device when needed (first run or revoked)
|
|
156
|
+
if (!deviceMeta || !privateKeyB64Url) {
|
|
157
|
+
console.log('\n✓ Device identity loaded securely');
|
|
158
|
+
try {
|
|
159
|
+
const result = await enroll(serverOrigin, { chromePath });
|
|
160
|
+
deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
|
|
161
|
+
privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
162
|
+
} catch (e) {
|
|
163
|
+
console.error(`\nEnrollment failed: ${e.message}`);
|
|
164
|
+
process.exit(1);
|
|
165
|
+
}
|
|
166
|
+
} else {
|
|
167
|
+
console.log(`✓ Device identity loaded securely`);
|
|
168
|
+
console.log(`✓ Device recognized: ${deviceMeta.deviceName}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// 6. Process lock (prevent duplicate instances)
|
|
172
|
+
const processLock = require('./processLock');
|
|
173
|
+
const lockResult = processLock.acquireLock({
|
|
174
|
+
deviceId: deviceMeta.deviceId,
|
|
175
|
+
deviceName: deviceMeta.deviceName,
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
if (!lockResult.acquired) {
|
|
179
|
+
if (flags.replace) {
|
|
180
|
+
console.log('\nAnother agent instance is running. Requesting takeover...');
|
|
181
|
+
const took = await processLock.requestTakeover(lockResult.existing);
|
|
182
|
+
if (!took) {
|
|
183
|
+
console.error('Could not stop the existing instance. Please close it manually.');
|
|
184
|
+
process.exit(1);
|
|
185
|
+
}
|
|
186
|
+
// Re-acquire the lock
|
|
187
|
+
const retryLock = processLock.acquireLock({
|
|
188
|
+
deviceId: deviceMeta.deviceId,
|
|
189
|
+
deviceName: deviceMeta.deviceName,
|
|
190
|
+
});
|
|
191
|
+
if (!retryLock.acquired) {
|
|
192
|
+
console.error('Could not acquire process lock after takeover.');
|
|
193
|
+
process.exit(1);
|
|
194
|
+
}
|
|
195
|
+
} else {
|
|
196
|
+
console.error('\nXKWDStore Agent is already running on this computer.');
|
|
197
|
+
console.error(`PID: ${lockResult.existing.pid}`);
|
|
198
|
+
console.error(`Started: ${lockResult.existing.startedAt}`);
|
|
199
|
+
console.error(`Device: ${lockResult.existing.deviceName || 'unknown'}`);
|
|
200
|
+
console.error('\nTo replace the running instance, use:');
|
|
201
|
+
console.error(' xkwd-agent start --replace');
|
|
202
|
+
process.exit(1);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// 7. Connect securely via WebSocket challenge-response
|
|
207
|
+
// 4003 auto-recovery: if the initial connection fails with 4003 (revoked/
|
|
208
|
+
// unknown device), the agent automatically performs a server-scoped
|
|
209
|
+
// re-enrollment and reconnects in the SAME process flow — the user does
|
|
210
|
+
// NOT need to type a second command. Only ONE auto-recovery attempt is
|
|
211
|
+
// allowed per startup to prevent infinite loops.
|
|
212
|
+
const { connectWebSocket } = require('./wsClient');
|
|
213
|
+
let ws;
|
|
214
|
+
let autoRecovered = false;
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
ws = await connectWebSocket({
|
|
218
|
+
serverOrigin,
|
|
219
|
+
deviceId: deviceMeta.deviceId,
|
|
220
|
+
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
221
|
+
privateKeyB64Url,
|
|
222
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
223
|
+
});
|
|
224
|
+
} catch (connectErr) {
|
|
225
|
+
// Check if this is a 4003 authentication failure (revoked/unknown device).
|
|
226
|
+
// The wsClient rejects with a message containing "Device authentication
|
|
227
|
+
// failed" for 4003 close codes, or the error may carry a .code property.
|
|
228
|
+
const isAuthFailure = _is4003Error(connectErr);
|
|
229
|
+
|
|
230
|
+
if (isAuthFailure && !autoRecovered) {
|
|
231
|
+
autoRecovered = true;
|
|
232
|
+
console.error('\n❌ Authentication failed (4003) — this device may be revoked.');
|
|
233
|
+
console.error(' Automatically re-authorizing for ' + serverOrigin + '...');
|
|
234
|
+
console.error(' (Other servers\' identities are NOT affected.)');
|
|
235
|
+
|
|
236
|
+
// Release the lock before re-enrollment (enrollment opens a browser)
|
|
237
|
+
processLock.releaseLock();
|
|
238
|
+
|
|
239
|
+
// Delete only this server's identity
|
|
240
|
+
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
241
|
+
await deletePrivateKey({ serverOrigin });
|
|
242
|
+
deleteMetadata({ serverOrigin });
|
|
243
|
+
console.error('✓ Old identity cleared for ' + serverOrigin);
|
|
244
|
+
|
|
245
|
+
// Re-enroll automatically (opens browser for approval)
|
|
246
|
+
console.log('\nOpening authorization page...');
|
|
247
|
+
try {
|
|
248
|
+
await enroll(serverOrigin, { chromePath });
|
|
249
|
+
deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
|
|
250
|
+
privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
251
|
+
|
|
252
|
+
if (!deviceMeta || !privateKeyB64Url) {
|
|
253
|
+
console.error('\n❌ Re-enrollment completed but identity could not be loaded.');
|
|
254
|
+
process.exit(1);
|
|
255
|
+
}
|
|
256
|
+
console.log('✓ New identity stored for ' + serverOrigin);
|
|
257
|
+
} catch (enrollErr) {
|
|
258
|
+
console.error(`\n❌ Automatic re-enrollment failed: ${enrollErr.message}`);
|
|
259
|
+
console.error(' Run `xkwd-agent start` again to retry manually.');
|
|
260
|
+
process.exit(1);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Re-acquire the process lock with the new device identity
|
|
264
|
+
const retryLock = processLock.acquireLock({
|
|
265
|
+
deviceId: deviceMeta.deviceId,
|
|
266
|
+
deviceName: deviceMeta.deviceName,
|
|
267
|
+
});
|
|
268
|
+
if (!retryLock.acquired) {
|
|
269
|
+
console.error('Could not acquire process lock after re-enrollment.');
|
|
270
|
+
if (flags.replace) {
|
|
271
|
+
const took = await processLock.requestTakeover(retryLock.existing);
|
|
272
|
+
if (!took) {
|
|
273
|
+
console.error('Could not stop the existing instance. Please close it manually.');
|
|
274
|
+
process.exit(1);
|
|
275
|
+
}
|
|
276
|
+
} else {
|
|
277
|
+
process.exit(1);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Attempt to reconnect with the new identity (only ONE retry)
|
|
282
|
+
try {
|
|
283
|
+
ws = await connectWebSocket({
|
|
284
|
+
serverOrigin,
|
|
285
|
+
deviceId: deviceMeta.deviceId,
|
|
286
|
+
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
287
|
+
privateKeyB64Url,
|
|
288
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
289
|
+
});
|
|
290
|
+
console.log('\n✓ Re-authorized and reconnected automatically.');
|
|
291
|
+
} catch (retryErr) {
|
|
292
|
+
if (_is4003Error(retryErr)) {
|
|
293
|
+
console.error('\n❌ Authentication failed again after re-enrollment.');
|
|
294
|
+
console.error(' The new device may not have been approved on the dashboard.');
|
|
295
|
+
console.error(' Run `xkwd-agent start` again after approving the device.');
|
|
296
|
+
} else {
|
|
297
|
+
console.error(`\n❌ Reconnection failed: ${retryErr.message}`);
|
|
298
|
+
console.error(' Run `xkwd-agent start` again to retry.');
|
|
299
|
+
}
|
|
300
|
+
processLock.releaseLock();
|
|
301
|
+
process.exit(1);
|
|
302
|
+
}
|
|
303
|
+
} else {
|
|
304
|
+
// Non-4003 error, or 4003 after auto-recovery already attempted
|
|
305
|
+
console.error(`\nConnection failed: ${connectErr.message}`);
|
|
306
|
+
if (isAuthFailure) {
|
|
307
|
+
console.error(' Automatic recovery was already attempted. Run `xkwd-agent start` again.');
|
|
308
|
+
}
|
|
309
|
+
processLock.releaseLock();
|
|
310
|
+
process.exit(1);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
console.log('✓ Secure challenge passed');
|
|
315
|
+
console.log('✓ Connected');
|
|
316
|
+
console.log('\nAgent is running. Press Ctrl+C to stop.\n');
|
|
317
|
+
|
|
318
|
+
// 8. Set up browser session handler (delegates to existing session management)
|
|
319
|
+
const { setupSessionHandler, closeAllSessions, markDisconnected } = require('./sessionHandler');
|
|
320
|
+
const sessions = setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
|
|
321
|
+
|
|
322
|
+
// 8a. Fail-safe: an authenticated WebSocket closure is not a recoverable
|
|
323
|
+
// event in this release. The agent must stop accepting commands, close every
|
|
324
|
+
// active browser context (preserving profiles/cookies via the existing
|
|
325
|
+
// safe persistence path), clear the sessions map, release the process
|
|
326
|
+
// lock, print a clear terminal error, and exit non-zero. We deliberately
|
|
327
|
+
// prefer a safe exit over incomplete automatic reconnection here; a future
|
|
328
|
+
// reconnect implementation is allowed only if it rebinds the full session
|
|
329
|
+
// handler, reconciles every lease, and is covered by deterministic tests.
|
|
330
|
+
//
|
|
331
|
+
// Race guard: `shuttingDown` is set by the deliberate Ctrl+C/SIGTERM path
|
|
332
|
+
// BEFORE ws.close() is called, so the close event emitted during a
|
|
333
|
+
// deliberate shutdown does NOT run the unexpected-disconnect fail-safe.
|
|
334
|
+
// This prevents closeAllSessions() from being executed concurrently twice
|
|
335
|
+
// and processLock.releaseLock() from being called twice.
|
|
336
|
+
let disconnected = false;
|
|
337
|
+
let shuttingDown = false;
|
|
338
|
+
ws.on('close', (code, reason) => {
|
|
339
|
+
// If a deliberate shutdown is in progress, the close event is expected —
|
|
340
|
+
// do NOT run the unexpected-disconnect fail-safe.
|
|
341
|
+
if (shuttingDown) return;
|
|
342
|
+
if (disconnected) return;
|
|
343
|
+
disconnected = true;
|
|
344
|
+
markDisconnected();
|
|
345
|
+
const reasonStr = reason ? reason.toString() : '';
|
|
346
|
+
console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
|
|
347
|
+
console.error(' Closing all browser sessions and shutting down safely...');
|
|
348
|
+
|
|
349
|
+
// 4003 = authentication failed (revoked/unknown key). Unlike the initial
|
|
350
|
+
// connect path, a 4003 on an ESTABLISHED connection means the device was
|
|
351
|
+
// revoked mid-session. The auto-recovery on initial connect handles the
|
|
352
|
+
// common case (stored revoked key at startup). For mid-session revocation,
|
|
353
|
+
// the agent exits with a clear message — the user should investigate.
|
|
354
|
+
const isAuthFailure = code === 4003;
|
|
355
|
+
|
|
356
|
+
closeAllSessions().then(({ closed }) => {
|
|
357
|
+
if (closed > 0) console.error(` Closed ${closed} browser session(s).`);
|
|
358
|
+
}).catch(() => {}).finally(() => {
|
|
359
|
+
try { ws.close(1000, 'Agent shutting down after disconnect'); } catch {}
|
|
360
|
+
processLock.releaseLock();
|
|
361
|
+
|
|
362
|
+
if (isAuthFailure) {
|
|
363
|
+
console.error('\n❌ Authentication failed — this device was revoked during the session.');
|
|
364
|
+
console.error(' The server-scoped identity for ' + serverOrigin + ' has been cleared.');
|
|
365
|
+
console.error(' Run `xkwd-agent start` again to re-authorize this computer.');
|
|
366
|
+
// Server-scoped cleanup so the next start re-enrolls
|
|
367
|
+
try {
|
|
368
|
+
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
369
|
+
deletePrivateKey({ serverOrigin });
|
|
370
|
+
deleteMetadata({ serverOrigin });
|
|
371
|
+
} catch {}
|
|
372
|
+
} else {
|
|
373
|
+
console.error('\nTo reconnect, run `xkwd-agent start` again.');
|
|
374
|
+
}
|
|
375
|
+
console.error('Agent stopped.');
|
|
376
|
+
process.exit(1);
|
|
377
|
+
});
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
// 9. Clean shutdown on Ctrl+C
|
|
381
|
+
async function shutdown(signal) {
|
|
382
|
+
if (shuttingDown) return;
|
|
383
|
+
shuttingDown = true;
|
|
384
|
+
console.log(`\n${signal} received. Shutting down...`);
|
|
385
|
+
|
|
386
|
+
// Stop accepting commands immediately.
|
|
387
|
+
markDisconnected();
|
|
388
|
+
|
|
389
|
+
// Close all browser sessions (preserves profiles/cookies via the
|
|
390
|
+
// existing safe persistence path).
|
|
391
|
+
try {
|
|
392
|
+
await closeAllSessions();
|
|
393
|
+
} catch {}
|
|
394
|
+
|
|
395
|
+
// Close WebSocket
|
|
396
|
+
try { ws.close(1000, 'Agent shutting down'); } catch {}
|
|
397
|
+
|
|
398
|
+
// Release lock
|
|
399
|
+
processLock.releaseLock();
|
|
400
|
+
|
|
401
|
+
process.exit(0);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
process.on('SIGINT', () => shutdown('Ctrl+C'));
|
|
405
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
406
|
+
process.on('SIGHUP', () => shutdown('SIGHUP'));
|
|
407
|
+
|
|
408
|
+
// Also release the lock on uncaught exceptions
|
|
409
|
+
process.on('uncaughtException', (err) => {
|
|
410
|
+
console.error('Uncaught error:', err.message);
|
|
411
|
+
processLock.releaseLock();
|
|
412
|
+
process.exit(1);
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* `xkwd-agent status` — show device and connection status.
|
|
418
|
+
*/
|
|
419
|
+
function status() {
|
|
420
|
+
const { getStoredDevice } = require('./enrollmentClient');
|
|
421
|
+
const { isSecureStorageAvailable } = require('./deviceKeyStore');
|
|
422
|
+
const processLock = require('./processLock');
|
|
423
|
+
|
|
424
|
+
const args = process.argv.slice(2);
|
|
425
|
+
const serverFlag = args.find(a => a.startsWith('--server='));
|
|
426
|
+
const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
|
|
427
|
+
|
|
428
|
+
const device = getStoredDevice({ serverOrigin });
|
|
429
|
+
const lock = processLock.readLock();
|
|
430
|
+
|
|
431
|
+
console.log(`XKWDStore Agent v${CLI_VERSION}\n`);
|
|
432
|
+
|
|
433
|
+
if (!device) {
|
|
434
|
+
console.log('Status: Not authorized');
|
|
435
|
+
console.log('Run `xkwd-agent start` to authorize this computer.');
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
console.log(`Device ID: ${device.deviceId}`);
|
|
440
|
+
console.log(`Device name: ${device.deviceName}`);
|
|
441
|
+
console.log(`Server: ${device.serverOrigin || 'https://x.kwdstore.com'}`);
|
|
442
|
+
console.log(`Public-key fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
|
|
443
|
+
console.log(`Created: ${device.createdAt || 'unknown'}`);
|
|
444
|
+
console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available' : 'unavailable'}`);
|
|
445
|
+
|
|
446
|
+
if (lock) {
|
|
447
|
+
console.log(`\nAgent process: RUNNING (PID ${lock.pid})`);
|
|
448
|
+
console.log(`Started: ${lock.startedAt}`);
|
|
449
|
+
} else {
|
|
450
|
+
console.log('\nAgent process: not running');
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* `xkwd-agent logout` — delete local device identity (re-enrollment required).
|
|
456
|
+
* Server-scoped: only deletes the identity for the specified server.
|
|
457
|
+
* Usage: xkwd-agent logout [--server=<url>]
|
|
458
|
+
*/
|
|
459
|
+
async function logout() {
|
|
460
|
+
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
461
|
+
const processLock = require('./processLock');
|
|
462
|
+
|
|
463
|
+
// Parse --server flag for scoped logout
|
|
464
|
+
const args = process.argv.slice(2);
|
|
465
|
+
const serverFlag = args.find(a => a.startsWith('--server='));
|
|
466
|
+
const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
|
|
467
|
+
|
|
468
|
+
const lock = processLock.readLock();
|
|
469
|
+
if (lock) {
|
|
470
|
+
console.error('Agent is currently running. Stop it first with Ctrl+C.');
|
|
471
|
+
process.exit(1);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
await deletePrivateKey({ serverOrigin });
|
|
475
|
+
deleteMetadata({ serverOrigin });
|
|
476
|
+
console.log(`Local device identity deleted for ${serverOrigin}.`);
|
|
477
|
+
console.log('Run `xkwd-agent start` to re-authorize this computer.');
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* `xkwd-agent revoke-local` — same as logout but also clears the process lock.
|
|
482
|
+
* Server-scoped: only deletes the identity for the specified server.
|
|
483
|
+
*/
|
|
484
|
+
async function revokeLocal() {
|
|
485
|
+
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
486
|
+
const args = process.argv.slice(2);
|
|
487
|
+
const serverFlag = args.find(a => a.startsWith('--server='));
|
|
488
|
+
const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
|
|
489
|
+
await deletePrivateKey({ serverOrigin });
|
|
490
|
+
deleteMetadata({ serverOrigin });
|
|
491
|
+
console.log(`Local device identity and credentials revoked for ${serverOrigin}.`);
|
|
492
|
+
console.log('The server-side device record should also be revoked from the dashboard.');
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* `xkwd-agent doctor` — diagnostic checks.
|
|
497
|
+
*/
|
|
498
|
+
async function doctor(serverOrigin) {
|
|
499
|
+
console.log(`XKWDStore Agent v${CLI_VERSION} — Diagnostics\n`);
|
|
500
|
+
|
|
501
|
+
// Check Node version
|
|
502
|
+
const nodeVersion = process.versions.node;
|
|
503
|
+
const major = parseInt(nodeVersion.split('.')[0], 10);
|
|
504
|
+
console.log(`Node.js: ${nodeVersion} ${major >= 22 ? '✓' : '✗ (requires Node.js 22+)'}`);
|
|
505
|
+
|
|
506
|
+
// Check platform
|
|
507
|
+
console.log(`Platform: ${os.platform()} ${os.arch()}`);
|
|
508
|
+
console.log(`Hostname: ${os.hostname()}`);
|
|
509
|
+
|
|
510
|
+
// Check Chrome
|
|
511
|
+
try {
|
|
512
|
+
const { resolveChromeOrFail } = require('./chromeDetector');
|
|
513
|
+
const chrome = resolveChromeOrFail();
|
|
514
|
+
console.log(`Chrome: ${chrome.chromeVersion || 'detected'} ✓`);
|
|
515
|
+
} catch (e) {
|
|
516
|
+
console.log(`Chrome: ✗ (${e.message.split('\n')[0]})`);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// Check secure storage (real DPAPI + ACL probe on Windows)
|
|
520
|
+
const { isSecureStorageAvailable, getDataDir, probeWindowsStorage } = require('./deviceKeyStore');
|
|
521
|
+
const platform = os.platform();
|
|
522
|
+
if (platform === 'win32') {
|
|
523
|
+
console.log('Secure storage: probing real DPAPI + ACL stages...');
|
|
524
|
+
const probe = probeWindowsStorage();
|
|
525
|
+
console.log(` DPAPI Protect : ${probe.stages.protect ? '✓' : '✗'}`);
|
|
526
|
+
console.log(` DPAPI Unprotect: ${probe.stages.unprotect ? '✓' : '✗'}`);
|
|
527
|
+
console.log(` Windows SID : ${probe.stages.sidLookup ? '✓' : '✗'}`);
|
|
528
|
+
console.log(` ACL apply : ${probe.stages.aclApply ? '✓' : '✗'}`);
|
|
529
|
+
console.log(` ACL verify : ${probe.stages.aclVerify ? '✓' : '✗'}`);
|
|
530
|
+
console.log(`Secure storage: ${probe.ok ? 'available ✓' : 'unavailable ✗'}`);
|
|
531
|
+
if (!probe.ok && probe.detail) {
|
|
532
|
+
console.log(` Detail: ${probe.detail}`);
|
|
533
|
+
}
|
|
534
|
+
} else {
|
|
535
|
+
console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available ✓' : 'unavailable ✗'}`);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// Check data directory
|
|
539
|
+
const dataDir = getDataDir();
|
|
540
|
+
console.log(`Data directory: ${dataDir}`);
|
|
541
|
+
|
|
542
|
+
// Check device identity (server-scoped)
|
|
543
|
+
const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
|
|
544
|
+
const device = getStoredDevice({ serverOrigin });
|
|
545
|
+
if (device) {
|
|
546
|
+
console.log(`Device ID: ${device.deviceId} ✓`);
|
|
547
|
+
const privateKey = await getStoredPrivateKey({ serverOrigin });
|
|
548
|
+
console.log(`Private key: ${privateKey ? 'stored ✓' : 'missing ✗'}`);
|
|
549
|
+
} else {
|
|
550
|
+
console.log('Device ID: not enrolled for this server');
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// Check server connectivity (shared strict validator)
|
|
554
|
+
try {
|
|
555
|
+
const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
|
|
556
|
+
const resp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
|
|
557
|
+
const compat = validateCompatibilityResponse(resp);
|
|
558
|
+
if (compat.html) {
|
|
559
|
+
console.log(`Server (${serverOrigin}): compatibility endpoint returned frontend ✗`);
|
|
560
|
+
console.log(' ' + COMPAT_HTML_MESSAGE);
|
|
561
|
+
} else if (compat.ok) {
|
|
562
|
+
console.log(`Server (${serverOrigin}): reachable ✓`);
|
|
563
|
+
console.log(` Protocol version: ${compat.body.protocolVersion}`);
|
|
564
|
+
console.log(` Min agent version: ${compat.body.minimumAgentVersion}`);
|
|
565
|
+
console.log(` Recommended agent version: ${compat.body.recommendedAgentVersion}`);
|
|
566
|
+
} else {
|
|
567
|
+
console.log(`Server (${serverOrigin}): compatibility check failed ✗`);
|
|
568
|
+
console.log(` Reason: ${compat.reason}`);
|
|
569
|
+
}
|
|
570
|
+
} catch (e) {
|
|
571
|
+
console.log(`Server (${serverOrigin}): unreachable ✗ (${e.message})`);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* `xkwd-agent version` — print version.
|
|
577
|
+
*/
|
|
578
|
+
function version() {
|
|
579
|
+
console.log(`@xkwdstore/agent v${CLI_VERSION}`);
|
|
580
|
+
console.log(`Protocol version: ${PROTOCOL_VERSION}`);
|
|
581
|
+
console.log(`Node.js: ${process.versions.node}`);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* `xkwd-agent help` — print help.
|
|
586
|
+
*/
|
|
587
|
+
function help() {
|
|
588
|
+
console.log(`XKWDStore Agent v${CLI_VERSION}
|
|
589
|
+
|
|
590
|
+
Usage:
|
|
591
|
+
xkwd-agent <command> [options]
|
|
592
|
+
|
|
593
|
+
Commands:
|
|
594
|
+
start Start the agent (connects to server, runs browser sessions)
|
|
595
|
+
status Show device and connection status
|
|
596
|
+
logout Delete local device identity (requires re-authorization)
|
|
597
|
+
revoke-local Delete local device identity and credentials
|
|
598
|
+
doctor Run diagnostic checks
|
|
599
|
+
version Print version information
|
|
600
|
+
help Show this help
|
|
601
|
+
|
|
602
|
+
Options:
|
|
603
|
+
--server=<url> Server URL (default: https://x.kwdstore.com)
|
|
604
|
+
--replace Replace a running instance (safe takeover)
|
|
605
|
+
|
|
606
|
+
Examples:
|
|
607
|
+
xkwd-agent start
|
|
608
|
+
xkwd-agent start --replace
|
|
609
|
+
xkwd-agent status
|
|
610
|
+
xkwd-agent doctor
|
|
611
|
+
|
|
612
|
+
First run:
|
|
613
|
+
The agent will open your browser to authorize this computer.
|
|
614
|
+
No pairing code, email, or API key is required.
|
|
615
|
+
|
|
616
|
+
To stop:
|
|
617
|
+
Press Ctrl+C in the terminal.
|
|
618
|
+
|
|
619
|
+
Data location:
|
|
620
|
+
Windows: %LOCALAPPDATA%\\XKWDStore\\
|
|
621
|
+
macOS: ~/Library/Application Support/XKWDStore/
|
|
622
|
+
Linux: ~/.local/share/xkwdstore/
|
|
623
|
+
|
|
624
|
+
Requirements:
|
|
625
|
+
- Node.js 22 or later
|
|
626
|
+
- Google Chrome installed
|
|
627
|
+
`);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* Detect whether a connection error is a 4003 authentication failure.
|
|
634
|
+
* The wsClient rejects with a message containing "Device authentication
|
|
635
|
+
* failed" when the server closes with code 4003. The error may also carry
|
|
636
|
+
* a .code property in some implementations.
|
|
637
|
+
*/
|
|
638
|
+
function _is4003Error(err) {
|
|
639
|
+
if (!err) return false;
|
|
640
|
+
const msg = (err.message || String(err)).toLowerCase();
|
|
641
|
+
if (err.code === 4003) return true;
|
|
642
|
+
if (msg.includes('device authentication failed')) return true;
|
|
643
|
+
if (msg.includes('4003')) return true;
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function _compareVersions(a, b) {
|
|
648
|
+
const pa = a.split('.').map(Number);
|
|
649
|
+
const pb = b.split('.').map(Number);
|
|
650
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
651
|
+
const va = pa[i] || 0;
|
|
652
|
+
const vb = pb[i] || 0;
|
|
653
|
+
if (va > vb) return 1;
|
|
654
|
+
if (va < vb) return -1;
|
|
655
|
+
}
|
|
656
|
+
return 0;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// ── Entry point ──────────────────────────────────────────────────────────────
|
|
660
|
+
|
|
661
|
+
if (require.main === module) {
|
|
662
|
+
main();
|
|
663
|
+
}
|
|
664
|
+
|
|
529
665
|
module.exports = { main, CLI_VERSION, PROTOCOL_VERSION };
|