@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/enrollmentClient.js
CHANGED
|
@@ -1,446 +1,589 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Phase 6 — Enrollment client (first-run authorization).
|
|
5
|
-
*
|
|
6
|
-
* Handles the no-code first-run authorization flow:
|
|
7
|
-
* 1. CLI generates Ed25519 key pair locally.
|
|
8
|
-
* 2. CLI calls POST /api/agent/enrollment/start with the public key.
|
|
9
|
-
* 3. Server returns requestId + authorizationUrl.
|
|
10
|
-
* 4. CLI opens the authorization URL in the default browser.
|
|
11
|
-
* 5. User signs into x.kwdstore.com and approves the computer.
|
|
12
|
-
* 6. CLI polls GET /api/agent/enrollment/:requestId/status.
|
|
13
|
-
* 7. Server binds the account to the public key.
|
|
14
|
-
* 8. CLI receives deviceId + server-signed device certificate.
|
|
15
|
-
*
|
|
16
|
-
* The user never types or copies a pairing code, email, or API key.
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
const https = require('https');
|
|
20
|
-
const http = require('http');
|
|
21
|
-
const
|
|
22
|
-
const {
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
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
|
-
if (!
|
|
227
|
-
return
|
|
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
|
-
|
|
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
|
-
const
|
|
368
|
-
const
|
|
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
|
-
*
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Phase 6 — Enrollment client (first-run authorization).
|
|
5
|
+
*
|
|
6
|
+
* Handles the no-code first-run authorization flow:
|
|
7
|
+
* 1. CLI generates Ed25519 key pair locally.
|
|
8
|
+
* 2. CLI calls POST /api/agent/enrollment/start with the public key.
|
|
9
|
+
* 3. Server returns requestId + authorizationUrl.
|
|
10
|
+
* 4. CLI opens the authorization URL in the default browser.
|
|
11
|
+
* 5. User signs into x.kwdstore.com and approves the computer.
|
|
12
|
+
* 6. CLI polls GET /api/agent/enrollment/:requestId/status.
|
|
13
|
+
* 7. Server binds the account to the public key.
|
|
14
|
+
* 8. CLI receives deviceId + server-signed device certificate.
|
|
15
|
+
*
|
|
16
|
+
* The user never types or copies a pairing code, email, or API key.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const https = require('https');
|
|
20
|
+
const http = require('http');
|
|
21
|
+
const fs = require('fs');
|
|
22
|
+
const { URL } = require('url');
|
|
23
|
+
const { execSync, spawn } = require('child_process');
|
|
24
|
+
const os = require('os');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
|
|
27
|
+
const { generateKeyPair, storePrivateKey, saveMetadata, loadPrivateKeyFromStorage, loadMetadata } = require('./deviceKeyStore');
|
|
28
|
+
const { resolveChromeOrFail } = require('./chromeDetector');
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Open a URL in the browser (Defect 11 fix: no shell interpolation).
|
|
32
|
+
*
|
|
33
|
+
* Prefers launching the already-detected Chrome executable directly with
|
|
34
|
+
* child_process.spawn and an argument array — no shell, no cmd.exe, no
|
|
35
|
+
* PowerShell process launcher, no command injection. The URL (which
|
|
36
|
+
* legitimately contains &, ?, #, =) is passed as a single separate argument,
|
|
37
|
+
* so shell metacharacters in the URL can never be interpreted as shell syntax.
|
|
38
|
+
*
|
|
39
|
+
* If a detected Chrome path is provided, it is used directly. If direct
|
|
40
|
+
* Chrome launch fails (or no Chrome path is available), the OS default
|
|
41
|
+
* browser opener is tried as a safe fallback (still via spawn argument
|
|
42
|
+
* arrays, never via a constructed shell string). If that also fails, the
|
|
43
|
+
* manual URL is printed exactly once.
|
|
44
|
+
*
|
|
45
|
+
* This function is ASYNCHRONOUS. child_process.spawn can return a ChildProcess
|
|
46
|
+
* and then emit an asynchronous 'error' event if the process cannot actually
|
|
47
|
+
* be started (e.g. ENOENT, EACCES). We wait for the 'spawn' event (process
|
|
48
|
+
* actually started) before treating the launch as successful, and wait for
|
|
49
|
+
* the 'error' event to detect a genuine launch failure and fall through to
|
|
50
|
+
* the fallback. No unhandled 'error' event is left on any ChildProcess.
|
|
51
|
+
*
|
|
52
|
+
* @param {string} url — the authorization URL to open
|
|
53
|
+
* @param {object} [opts] — optional settings
|
|
54
|
+
* @param {string} [opts.chromePath] — already-detected Chrome executable path
|
|
55
|
+
* @returns {Promise<boolean>} true if a browser launched successfully,
|
|
56
|
+
* false if all launch attempts failed (manual URL
|
|
57
|
+
* printed exactly once)
|
|
58
|
+
*/
|
|
59
|
+
async function openBrowser(url, opts) {
|
|
60
|
+
opts = opts || {};
|
|
61
|
+
const chromePath = opts.chromePath || null;
|
|
62
|
+
const platform = os.platform();
|
|
63
|
+
|
|
64
|
+
// Validate the URL before opening. _isSafeAuthUrl allows legitimate URL
|
|
65
|
+
// characters (& ? # =) that appear in the authorization fragment; it only
|
|
66
|
+
// rejects control characters and genuinely dangerous shell metacharacters
|
|
67
|
+
// (; | ` $) that have no place in an HTTPS authorization URL.
|
|
68
|
+
if (!_isSafeAuthUrl(url)) {
|
|
69
|
+
console.log('\nCould not open browser automatically. Open this URL now to approve this computer:');
|
|
70
|
+
console.log(` ${url}`);
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 1. Preferred path: launch the already-detected Chrome executable directly.
|
|
75
|
+
// The URL is a single separate spawn argument — never reconstructed into
|
|
76
|
+
// a shell string — so &, ?, #, = cannot become shell syntax.
|
|
77
|
+
if (chromePath && fs.existsSync(chromePath)) {
|
|
78
|
+
const launched = await spawnAndConfirm(chromePath, [url], {
|
|
79
|
+
stdio: 'ignore',
|
|
80
|
+
detached: true,
|
|
81
|
+
windowsHide: false,
|
|
82
|
+
});
|
|
83
|
+
if (launched) return true;
|
|
84
|
+
// Fall through to the OS default-browser fallback below.
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// 2. Safe fallback: OS default browser opener, still via spawn argument
|
|
88
|
+
// arrays (no shell:true, no constructed command string).
|
|
89
|
+
let fallbackCmd, fallbackArgs;
|
|
90
|
+
if (platform === 'win32') {
|
|
91
|
+
// explorer.exe opens the URL in the registered default browser. It does
|
|
92
|
+
// not interpret & as a command separator when the URL is a separate
|
|
93
|
+
// spawn argument (no shell). This avoids cmd.exe entirely.
|
|
94
|
+
fallbackCmd = 'explorer.exe';
|
|
95
|
+
fallbackArgs = [url];
|
|
96
|
+
} else if (platform === 'darwin') {
|
|
97
|
+
fallbackCmd = 'open';
|
|
98
|
+
fallbackArgs = [url];
|
|
99
|
+
} else {
|
|
100
|
+
fallbackCmd = 'xdg-open';
|
|
101
|
+
fallbackArgs = [url];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const fallbackLaunched = await spawnAndConfirm(fallbackCmd, fallbackArgs, {
|
|
105
|
+
stdio: 'ignore',
|
|
106
|
+
detached: true,
|
|
107
|
+
windowsHide: false,
|
|
108
|
+
});
|
|
109
|
+
if (fallbackLaunched) return true;
|
|
110
|
+
|
|
111
|
+
// 3. All launch attempts failed — print the manual URL exactly once.
|
|
112
|
+
console.log('\nCould not open browser automatically. Open this URL now to approve this computer:');
|
|
113
|
+
console.log(` ${url}`);
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Spawn a process and confirm it actually started via the 'spawn' event.
|
|
119
|
+
*
|
|
120
|
+
* child_process.spawn can return a ChildProcess synchronously and then emit
|
|
121
|
+
* an asynchronous 'error' event if the process cannot be started. This helper
|
|
122
|
+
* resolves true only when the 'spawn' event fires (the OS actually started
|
|
123
|
+
* the process), and false on a synchronous throw or an asynchronous 'error'.
|
|
124
|
+
* The ChildProcess is always unref()'d so the parent can exit independently.
|
|
125
|
+
* No unhandled 'error' listener is left behind — the promise settles exactly
|
|
126
|
+
* once and the listeners are removed.
|
|
127
|
+
*
|
|
128
|
+
* @param {string} command - executable to launch
|
|
129
|
+
* @param {string[]} args - argument array (URL is a separate element)
|
|
130
|
+
* @param {object} options - spawn options (never shell:true)
|
|
131
|
+
* @returns {Promise<boolean>} true if the process started, false if it failed
|
|
132
|
+
*/
|
|
133
|
+
function spawnAndConfirm(command, args, options) {
|
|
134
|
+
return new Promise((resolve) => {
|
|
135
|
+
let settled = false;
|
|
136
|
+
const settle = (result) => {
|
|
137
|
+
if (settled) return;
|
|
138
|
+
settled = true;
|
|
139
|
+
resolve(result);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
let child;
|
|
143
|
+
try {
|
|
144
|
+
child = spawn(command, args, options);
|
|
145
|
+
} catch {
|
|
146
|
+
settle(false);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// 'spawn' fires when the process is successfully spawned (Node >=16).
|
|
151
|
+
child.once('spawn', () => {
|
|
152
|
+
child.unref();
|
|
153
|
+
settle(true);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
// 'error' fires if the process could not be spawned (ENOENT, EACCES, …)
|
|
157
|
+
// or could not send a message. We remove the 'spawn' listener to avoid
|
|
158
|
+
// leaving a dangling listener that would never fire.
|
|
159
|
+
child.once('error', () => {
|
|
160
|
+
settle(false);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// Safety: if neither event fires within a short window (e.g. on an old
|
|
164
|
+
// Node version that does not emit 'spawn'), resolve true as a best-effort
|
|
165
|
+
// so we do not hang indefinitely. unref the child first.
|
|
166
|
+
setTimeout(() => {
|
|
167
|
+
settle(true);
|
|
168
|
+
try { child.unref(); } catch {}
|
|
169
|
+
}, 1000).unref();
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Validate that a URL is safe to open in the browser (Defect 11).
|
|
175
|
+
* - Protocol must be HTTPS in production.
|
|
176
|
+
* - Origin must match the configured XKWDStore server.
|
|
177
|
+
* - Path must be the expected authorization path.
|
|
178
|
+
* - No control characters (newline, carriage return, etc.).
|
|
179
|
+
* - No shell separators (; | ` and $ when used as a command-prefix char) that
|
|
180
|
+
* could be interpreted by cmd.exe. Legitimate URL characters (& ? # =) are
|
|
181
|
+
* ALLOWED — they are normal query/fragment delimiters and, because the URL
|
|
182
|
+
* is passed as a separate spawn argument with no shell, they can never be
|
|
183
|
+
* interpreted as shell syntax.
|
|
184
|
+
* - Request ID and fragment token have strict formats.
|
|
185
|
+
*/
|
|
186
|
+
function _isSafeAuthUrl(url) {
|
|
187
|
+
if (typeof url !== 'string' || url.length === 0) return false;
|
|
188
|
+
// Reject control characters.
|
|
189
|
+
if (/[\x00-\x1f\x7f]/.test(url)) return false;
|
|
190
|
+
// Reject genuinely dangerous shell metacharacters that have no legitimate
|
|
191
|
+
// place in an HTTPS authorization URL. `;` is a cmd.exe command separator,
|
|
192
|
+
// `|` is a pipe, backtick is PowerShell subexpression, and a leading `$`
|
|
193
|
+
// is PowerShell variable syntax. We reject these but allow & ? # = which
|
|
194
|
+
// are normal URL delimiters in the authorization fragment.
|
|
195
|
+
if (/[;|`]/.test(url)) return false;
|
|
196
|
+
// Reject a leading-$ or PowerShell-style $(...) subexpression. A bare `$`
|
|
197
|
+
// inside a base64url token is not produced by this flow.
|
|
198
|
+
if (/\$\(|\$ENV:|\$\{/.test(url)) return false;
|
|
199
|
+
|
|
200
|
+
let parsed;
|
|
201
|
+
try {
|
|
202
|
+
parsed = new URL(url);
|
|
203
|
+
} catch {
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Protocol must be HTTPS in production.
|
|
208
|
+
if (parsed.protocol !== 'https:' && process.env.NODE_ENV === 'production') {
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Path must be the expected authorization path.
|
|
216
|
+
if (parsed.pathname !== '/dashboard/authorize-device') {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Fragment must contain request=<uuid>&approval=<token> with strict formats.
|
|
221
|
+
const hash = parsed.hash || '';
|
|
222
|
+
if (!hash.startsWith('#request=')) return false;
|
|
223
|
+
const params = new URLSearchParams(hash.slice(1));
|
|
224
|
+
const requestId = params.get('request');
|
|
225
|
+
const approval = params.get('approval');
|
|
226
|
+
if (!requestId || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(requestId)) {
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
if (!approval || !/^[A-Za-z0-9_-]+$/.test(approval)) {
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Make an HTTP/HTTPS request and return the parsed JSON response.
|
|
238
|
+
*/
|
|
239
|
+
function _request(method, url, body, headers) {
|
|
240
|
+
return new Promise((resolve, reject) => {
|
|
241
|
+
const parsed = new URL(url);
|
|
242
|
+
const isHttps = parsed.protocol === 'https:';
|
|
243
|
+
const lib = isHttps ? https : http;
|
|
244
|
+
|
|
245
|
+
const options = {
|
|
246
|
+
method,
|
|
247
|
+
hostname: parsed.hostname,
|
|
248
|
+
port: parsed.port || (isHttps ? 443 : 80),
|
|
249
|
+
path: parsed.pathname + parsed.search,
|
|
250
|
+
headers: {
|
|
251
|
+
'Content-Type': 'application/json',
|
|
252
|
+
...headers,
|
|
253
|
+
},
|
|
254
|
+
timeout: 15000,
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const reqBody = body ? JSON.stringify(body) : null;
|
|
258
|
+
if (reqBody) {
|
|
259
|
+
options.headers['Content-Length'] = Buffer.byteLength(reqBody);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const req = lib.request(options, (res) => {
|
|
263
|
+
let data = '';
|
|
264
|
+
res.on('data', (chunk) => { data += chunk; });
|
|
265
|
+
res.on('end', () => {
|
|
266
|
+
const contentType = res.headers && res.headers['content-type'];
|
|
267
|
+
// Reject HTML/SPA responses instead of misparsing them as JSON.
|
|
268
|
+
if (_isHtmlResponse(data, contentType)) {
|
|
269
|
+
resolve({ status: res.statusCode, contentType, body: { error: 'Server returned HTML instead of JSON (compatibility endpoint not deployed)', html: true } });
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
try {
|
|
273
|
+
const json = JSON.parse(data);
|
|
274
|
+
resolve({ status: res.statusCode, contentType, body: json });
|
|
275
|
+
} catch (_e) {
|
|
276
|
+
resolve({ status: res.statusCode, contentType, body: { error: 'Invalid JSON response' } });
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
req.on('error', reject);
|
|
282
|
+
req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); });
|
|
283
|
+
|
|
284
|
+
if (reqBody) req.write(reqBody);
|
|
285
|
+
req.end();
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Detect an HTML/SPA compatibility response.
|
|
291
|
+
* Servers that serve a React SPA on unknown API routes return HTML with a 200
|
|
292
|
+
* status. Treat that as a hard compatibility failure — never as a valid JSON
|
|
293
|
+
* response with undefined fields.
|
|
294
|
+
*/
|
|
295
|
+
function _isHtmlResponse(data, contentType) {
|
|
296
|
+
const ct = String(contentType || '').toLowerCase();
|
|
297
|
+
if (ct.includes('text/html')) return true;
|
|
298
|
+
const body = String(data || '').trimStart().slice(0, 512).toLowerCase();
|
|
299
|
+
return body.startsWith('<!doctype html>') || body.startsWith('<html');
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Shared strict compatibility validator (Protocol-v2 contract).
|
|
304
|
+
*
|
|
305
|
+
* Both `start` and `doctor` must use this single validator so the contract is
|
|
306
|
+
* enforced identically everywhere. Requires:
|
|
307
|
+
* - HTTP status 200
|
|
308
|
+
* - application/json Content-Type
|
|
309
|
+
* - plain non-array object body
|
|
310
|
+
* - protocolVersion === 2
|
|
311
|
+
* - non-empty minimumAgentVersion
|
|
312
|
+
* - non-empty recommendedAgentVersion
|
|
313
|
+
*
|
|
314
|
+
* Never prints the HTML body or undefined values. For HTML/SPA responses it
|
|
315
|
+
* returns { ok: false, html: true } and the caller prints the exact required
|
|
316
|
+
* message.
|
|
317
|
+
*
|
|
318
|
+
* @param {object} resp — { status, body, contentType }
|
|
319
|
+
* @returns {object} { ok: boolean, html?: boolean, reason?: string, body?: object }
|
|
320
|
+
*/
|
|
321
|
+
function validateCompatibilityResponse(resp) {
|
|
322
|
+
if (!resp || typeof resp !== 'object') {
|
|
323
|
+
return { ok: false, reason: 'no response' };
|
|
324
|
+
}
|
|
325
|
+
// HTML/SPA detection takes priority — a text/html Content-Type or an explicit
|
|
326
|
+
// html marker means the frontend was served instead of the API. Never inspect
|
|
327
|
+
// body fields in this case.
|
|
328
|
+
const ct = String(resp.contentType || '').toLowerCase();
|
|
329
|
+
if (ct.includes('text/html') || resp.html || (resp.body && resp.body.html)) {
|
|
330
|
+
return { ok: false, html: true };
|
|
331
|
+
}
|
|
332
|
+
if (resp.status !== 200) {
|
|
333
|
+
return { ok: false, reason: 'unexpected status ' + resp.status };
|
|
334
|
+
}
|
|
335
|
+
if (!ct.includes('application/json')) {
|
|
336
|
+
return { ok: false, reason: 'non-JSON Content-Type (' + (ct || 'missing') + ')' };
|
|
337
|
+
}
|
|
338
|
+
const body = resp.body;
|
|
339
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
340
|
+
return { ok: false, reason: 'body is not a plain object' };
|
|
341
|
+
}
|
|
342
|
+
if (body.protocolVersion !== 2) {
|
|
343
|
+
return { ok: false, reason: 'missing or unsupported protocolVersion' };
|
|
344
|
+
}
|
|
345
|
+
if (!body.minimumAgentVersion || typeof body.minimumAgentVersion !== 'string') {
|
|
346
|
+
return { ok: false, reason: 'missing minimumAgentVersion' };
|
|
347
|
+
}
|
|
348
|
+
if (!body.recommendedAgentVersion || typeof body.recommendedAgentVersion !== 'string') {
|
|
349
|
+
return { ok: false, reason: 'missing recommendedAgentVersion' };
|
|
350
|
+
}
|
|
351
|
+
return { ok: true, body };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* The exact message to print for an HTML/SPA compatibility response.
|
|
356
|
+
* Never print the HTML body or undefined values.
|
|
357
|
+
*/
|
|
358
|
+
const COMPAT_HTML_MESSAGE =
|
|
359
|
+
'Server compatibility endpoint returned the frontend application instead of ' +
|
|
360
|
+
'Protocol-v2 JSON. The backend deployment or reverse-proxy routing for ' +
|
|
361
|
+
'/api/agent/* is not active.';
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Collect device metadata for the enrollment request.
|
|
365
|
+
*/
|
|
366
|
+
function collectDeviceMetadata() {
|
|
367
|
+
const platform = os.platform();
|
|
368
|
+
const arch = os.arch();
|
|
369
|
+
const hostname = os.hostname();
|
|
370
|
+
const username = os.userInfo().username;
|
|
371
|
+
|
|
372
|
+
// Detect Chrome version
|
|
373
|
+
let chromeVersion = null;
|
|
374
|
+
try {
|
|
375
|
+
const { chromePath, chromeVersion: ver } = resolveChromeOrFail();
|
|
376
|
+
chromeVersion = ver;
|
|
377
|
+
} catch {
|
|
378
|
+
// Chrome missing — will be reported separately
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Defect 12 fix: Generate a random local salt once, stored as non-secret
|
|
382
|
+
// local metadata. The salt is NOT a credential — it just prevents the
|
|
383
|
+
// machine fingerprint from being a trivially reproducible hash of public
|
|
384
|
+
// attributes. The user can reset it by deleting the salt file.
|
|
385
|
+
const crypto = require('crypto');
|
|
386
|
+
const fs = require('fs');
|
|
387
|
+
const { getDataDir } = require('./deviceKeyStore');
|
|
388
|
+
const saltFile = path.join(getDataDir(), '.machine-salt');
|
|
389
|
+
let salt;
|
|
390
|
+
try {
|
|
391
|
+
if (fs.existsSync(saltFile)) {
|
|
392
|
+
salt = fs.readFileSync(saltFile, 'utf8').trim();
|
|
393
|
+
}
|
|
394
|
+
if (!salt || salt.length < 32) {
|
|
395
|
+
salt = crypto.randomBytes(32).toString('base64url');
|
|
396
|
+
if (!fs.existsSync(getDataDir())) fs.mkdirSync(getDataDir(), { recursive: true });
|
|
397
|
+
fs.writeFileSync(saltFile, salt, { encoding: 'utf8', mode: 0o600 });
|
|
398
|
+
}
|
|
399
|
+
} catch {
|
|
400
|
+
// If we can't read/write the salt, use a random ephemeral one.
|
|
401
|
+
salt = crypto.randomBytes(32).toString('base64url');
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Hash only minimal attributes with the local salt (NOT a credential).
|
|
405
|
+
// Avoid raw OS username when unnecessary — use hostname + platform + arch.
|
|
406
|
+
const machineId = [hostname, platform, arch].join('|');
|
|
407
|
+
const machineFingerprintHash = crypto
|
|
408
|
+
.createHash('sha256')
|
|
409
|
+
.update(salt + ':' + machineId)
|
|
410
|
+
.digest('hex');
|
|
411
|
+
|
|
412
|
+
return {
|
|
413
|
+
deviceName: hostname,
|
|
414
|
+
platform: platform === 'win32' ? 'Windows' : platform === 'darwin' ? 'macOS' : 'Linux',
|
|
415
|
+
architecture: arch,
|
|
416
|
+
chromeVersion,
|
|
417
|
+
machineFingerprintHash,
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Run the first-run enrollment flow.
|
|
423
|
+
*
|
|
424
|
+
* @param {string} serverOrigin — e.g. 'https://x.kwdstore.com'
|
|
425
|
+
* @param {object} [opts] — optional settings
|
|
426
|
+
* @param {string} [opts.chromePath] — already-detected Chrome executable path,
|
|
427
|
+
* reused for the authorization-browser launch (no second lookup)
|
|
428
|
+
* @returns {object} { deviceId, deviceCertificate } on success
|
|
429
|
+
*/
|
|
430
|
+
async function enroll(serverOrigin, opts) {
|
|
431
|
+
opts = opts || {};
|
|
432
|
+
const chromePath = opts.chromePath || null;
|
|
433
|
+
|
|
434
|
+
// 1. Generate Ed25519 key pair
|
|
435
|
+
const keyPair = generateKeyPair();
|
|
436
|
+
|
|
437
|
+
// 2. Store the private key securely (fail closed)
|
|
438
|
+
// Server-scoped: the key is stored in a per-server directory so that
|
|
439
|
+
// localhost and production identities never interfere.
|
|
440
|
+
try {
|
|
441
|
+
await storePrivateKey(keyPair.privateKeyB64Url, { serverOrigin });
|
|
442
|
+
} catch (e) {
|
|
443
|
+
const platform = os.platform();
|
|
444
|
+
const guidance = platform === 'win32'
|
|
445
|
+
? 'On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available for the current user.'
|
|
446
|
+
: 'On Linux, install gnome-keyring or seahorse (libsecret).';
|
|
447
|
+
throw new Error(
|
|
448
|
+
'Secure key storage is unavailable on this system.\n' +
|
|
449
|
+
'The private key cannot be stored safely.\n' +
|
|
450
|
+
guidance + '\n' +
|
|
451
|
+
'Error: ' + e.message
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// 3. Collect device metadata
|
|
456
|
+
const deviceMeta = collectDeviceMetadata();
|
|
457
|
+
|
|
458
|
+
// 4. Start enrollment
|
|
459
|
+
console.log('\nThis computer is not authorized yet.\n');
|
|
460
|
+
console.log('Generating device key pair...');
|
|
461
|
+
console.log(` Public-key fingerprint: ${keyPair.publicKeyFingerprint.slice(0, 4)}…${keyPair.publicKeyFingerprint.slice(-4)}`);
|
|
462
|
+
|
|
463
|
+
const startResponse = await _request('POST', `${serverOrigin}/api/agent/enrollment/start`, {
|
|
464
|
+
publicKey: keyPair.publicKeyB64Url,
|
|
465
|
+
publicKeyFingerprint: keyPair.publicKeyFingerprint,
|
|
466
|
+
deviceName: deviceMeta.deviceName,
|
|
467
|
+
platform: deviceMeta.platform,
|
|
468
|
+
architecture: deviceMeta.architecture,
|
|
469
|
+
chromeVersion: deviceMeta.chromeVersion,
|
|
470
|
+
machineFingerprintHash: deviceMeta.machineFingerprintHash,
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
if (startResponse.status !== 200) {
|
|
474
|
+
throw new Error(`Enrollment start failed: ${startResponse.body.error || 'Unknown error'}`);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const { requestId, pollSecret, authorizationUrl, expiresAt } = startResponse.body;
|
|
478
|
+
|
|
479
|
+
// 5. Open the authorization URL in the browser
|
|
480
|
+
console.log('\nOpening XKWDStore in your browser...');
|
|
481
|
+
console.log('Sign in and approve:');
|
|
482
|
+
console.log(` Device: ${deviceMeta.deviceName}`);
|
|
483
|
+
console.log(` Platform: ${deviceMeta.platform} ${deviceMeta.architecture}`);
|
|
484
|
+
console.log(` Chrome: ${deviceMeta.chromeVersion || 'not detected'}`);
|
|
485
|
+
console.log(` Public-key fingerprint: ${keyPair.publicKeyFingerprint.slice(0, 4)}…${keyPair.publicKeyFingerprint.slice(-4)}`);
|
|
486
|
+
|
|
487
|
+
// openBrowser prints the manual-URL fallback exactly once when all launch
|
|
488
|
+
// attempts fail (including the URL-validation-failed case). Do NOT print a
|
|
489
|
+
// second fallback here — that was the source of the duplicate message.
|
|
490
|
+
// await ensures we don't race the polling loop against an in-flight launch,
|
|
491
|
+
// but the polling loop continues regardless of whether the browser opened.
|
|
492
|
+
await openBrowser(authorizationUrl, { chromePath });
|
|
493
|
+
|
|
494
|
+
// 6. Poll for approval
|
|
495
|
+
console.log('\nWaiting for approval...');
|
|
496
|
+
|
|
497
|
+
const pollInterval = 3000; // 3 seconds
|
|
498
|
+
const maxPollTime = (startResponse.body.expiresIn || 600) * 1000;
|
|
499
|
+
const startTime = Date.now();
|
|
500
|
+
|
|
501
|
+
while (Date.now() - startTime < maxPollTime) {
|
|
502
|
+
await new Promise(resolve => setTimeout(resolve, pollInterval));
|
|
503
|
+
|
|
504
|
+
const statusResponse = await _request(
|
|
505
|
+
'GET',
|
|
506
|
+
`${serverOrigin}/api/agent/enrollment/${requestId}/status`,
|
|
507
|
+
null,
|
|
508
|
+
{ 'X-Enrollment-Secret': pollSecret },
|
|
509
|
+
);
|
|
510
|
+
|
|
511
|
+
if (statusResponse.status !== 200) {
|
|
512
|
+
// Could be rate-limited or temporary — keep polling
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const status = statusResponse.body;
|
|
517
|
+
|
|
518
|
+
if (status.state === 'approved') {
|
|
519
|
+
// 7. Save device metadata (non-secret, server-scoped)
|
|
520
|
+
saveMetadata({
|
|
521
|
+
deviceId: status.deviceId,
|
|
522
|
+
publicKeyB64Url: keyPair.publicKeyB64Url,
|
|
523
|
+
publicKeyFingerprint: keyPair.publicKeyFingerprint,
|
|
524
|
+
deviceName: deviceMeta.deviceName,
|
|
525
|
+
serverOrigin,
|
|
526
|
+
}, { serverOrigin });
|
|
527
|
+
|
|
528
|
+
console.log('✓ Computer authorized');
|
|
529
|
+
console.log(`✓ Device ID: ${status.deviceId}`);
|
|
530
|
+
|
|
531
|
+
return {
|
|
532
|
+
deviceId: status.deviceId,
|
|
533
|
+
deviceCertificate: status.deviceCertificate,
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
if (status.state === 'denied') {
|
|
538
|
+
throw new Error('Enrollment request was denied by the account owner.');
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
if (status.state === 'expired') {
|
|
542
|
+
throw new Error(
|
|
543
|
+
'The authorization request expired because approval was not completed in time. ' +
|
|
544
|
+
'Please run the command again.'
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// Still pending — keep polling
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
throw new Error(
|
|
552
|
+
'The authorization request expired because approval was not completed in time. ' +
|
|
553
|
+
'Please run the command again.'
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Check if this device is already enrolled.
|
|
559
|
+
* @param {object} [opts] — optional settings
|
|
560
|
+
* @param {string} [opts.serverOrigin] — server origin for server-scoped lookup.
|
|
561
|
+
* If null, tries the legacy top-level file (backward compatible).
|
|
562
|
+
* @returns {object|null} device metadata or null
|
|
563
|
+
*/
|
|
564
|
+
function getStoredDevice(opts) {
|
|
565
|
+
return loadMetadata(opts);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Get the stored private key for signing challenges.
|
|
570
|
+
* @param {object} [opts] — optional settings
|
|
571
|
+
* @param {string} [opts.serverOrigin] — server origin for server-scoped lookup.
|
|
572
|
+
* @returns {string|null} private key base64url or null
|
|
573
|
+
*/
|
|
574
|
+
async function getStoredPrivateKey(opts) {
|
|
575
|
+
return await loadPrivateKeyFromStorage(opts);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
module.exports = {
|
|
579
|
+
enroll,
|
|
580
|
+
getStoredDevice,
|
|
581
|
+
getStoredPrivateKey,
|
|
582
|
+
openBrowser,
|
|
583
|
+
spawnAndConfirm,
|
|
584
|
+
collectDeviceMetadata,
|
|
585
|
+
_request,
|
|
586
|
+
_isHtmlResponse,
|
|
587
|
+
validateCompatibilityResponse,
|
|
588
|
+
COMPAT_HTML_MESSAGE,
|
|
446
589
|
};
|