@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.
@@ -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 { URL } = require('url');
22
- const { execSync, spawn } = require('child_process');
23
- const os = require('os');
24
- const path = require('path');
25
-
26
- const { generateKeyPair, storePrivateKey, saveMetadata, loadPrivateKeyFromStorage, loadMetadata } = require('./deviceKeyStore');
27
- const { resolveChromeOrFail } = require('./chromeDetector');
28
-
29
- /**
30
- * Open a URL in the default browser (Defect 11 fix: no shell interpolation).
31
- * Uses spawn/execFile with argument arrays — no shell, no command injection.
32
- * Validates: protocol is HTTPS in production, origin matches configured server,
33
- * path is the expected authorization path, no control characters.
34
- */
35
- function openBrowser(url) {
36
- // Validate the URL before opening.
37
- if (!_isSafeAuthUrl(url)) {
38
- console.log('\nCould not open browser automatically. Open this URL manually:');
39
- console.log(` ${url}`);
40
- return false;
41
- }
42
-
43
- const platform = os.platform();
44
- try {
45
- if (platform === 'win32') {
46
- // Use spawn with argument array — no shell, no interpolation.
47
- spawn('cmd.exe', ['/c', 'start', '', url], {
48
- stdio: 'ignore',
49
- windowsHide: true,
50
- detached: true,
51
- }).unref();
52
- } else if (platform === 'darwin') {
53
- spawn('open', [url], { stdio: 'ignore', detached: true }).unref();
54
- } else {
55
- spawn('xdg-open', [url], { stdio: 'ignore', detached: true }).unref();
56
- }
57
- return true;
58
- } catch {
59
- return false;
60
- }
61
- }
62
-
63
- /**
64
- * Validate that a URL is safe to open in the browser (Defect 11).
65
- * - Protocol must be HTTPS in production.
66
- * - Origin must match the configured XKWDStore server.
67
- * - Path must be the expected authorization path.
68
- * - No control characters (newline, carriage return, etc.).
69
- * - Request ID and fragment token have strict formats.
70
- */
71
- function _isSafeAuthUrl(url) {
72
- if (typeof url !== 'string' || url.length === 0) return false;
73
- // Reject control characters.
74
- if (/[\x00-\x1f\x7f]/.test(url)) return false;
75
- // Reject shell metacharacters that could be interpreted.
76
- if (/[;&|`$]/.test(url)) return false;
77
-
78
- let parsed;
79
- try {
80
- parsed = new URL(url);
81
- } catch {
82
- return false;
83
- }
84
-
85
- // Protocol must be HTTPS in production.
86
- if (parsed.protocol !== 'https:' && process.env.NODE_ENV === 'production') {
87
- return false;
88
- }
89
- if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
90
- return false;
91
- }
92
-
93
- // Path must be the expected authorization path.
94
- if (parsed.pathname !== '/dashboard/authorize-device') {
95
- return false;
96
- }
97
-
98
- // Fragment must contain request=<uuid>&approval=<token> with strict formats.
99
- const hash = parsed.hash || '';
100
- if (!hash.startsWith('#request=')) return false;
101
- const params = new URLSearchParams(hash.slice(1));
102
- const requestId = params.get('request');
103
- const approval = params.get('approval');
104
- 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)) {
105
- return false;
106
- }
107
- if (!approval || !/^[A-Za-z0-9_-]+$/.test(approval)) {
108
- return false;
109
- }
110
-
111
- return true;
112
- }
113
-
114
- /**
115
- * Make an HTTP/HTTPS request and return the parsed JSON response.
116
- */
117
- function _request(method, url, body, headers) {
118
- return new Promise((resolve, reject) => {
119
- const parsed = new URL(url);
120
- const isHttps = parsed.protocol === 'https:';
121
- const lib = isHttps ? https : http;
122
-
123
- const options = {
124
- method,
125
- hostname: parsed.hostname,
126
- port: parsed.port || (isHttps ? 443 : 80),
127
- path: parsed.pathname + parsed.search,
128
- headers: {
129
- 'Content-Type': 'application/json',
130
- ...headers,
131
- },
132
- timeout: 15000,
133
- };
134
-
135
- const reqBody = body ? JSON.stringify(body) : null;
136
- if (reqBody) {
137
- options.headers['Content-Length'] = Buffer.byteLength(reqBody);
138
- }
139
-
140
- const req = lib.request(options, (res) => {
141
- let data = '';
142
- res.on('data', (chunk) => { data += chunk; });
143
- res.on('end', () => {
144
- const contentType = res.headers && res.headers['content-type'];
145
- // Reject HTML/SPA responses instead of misparsing them as JSON.
146
- if (_isHtmlResponse(data, contentType)) {
147
- resolve({ status: res.statusCode, contentType, body: { error: 'Server returned HTML instead of JSON (compatibility endpoint not deployed)', html: true } });
148
- return;
149
- }
150
- try {
151
- const json = JSON.parse(data);
152
- resolve({ status: res.statusCode, contentType, body: json });
153
- } catch (_e) {
154
- resolve({ status: res.statusCode, contentType, body: { error: 'Invalid JSON response' } });
155
- }
156
- });
157
- });
158
-
159
- req.on('error', reject);
160
- req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); });
161
-
162
- if (reqBody) req.write(reqBody);
163
- req.end();
164
- });
165
- }
166
-
167
- /**
168
- * Detect an HTML/SPA compatibility response.
169
- * Servers that serve a React SPA on unknown API routes return HTML with a 200
170
- * status. Treat that as a hard compatibility failure — never as a valid JSON
171
- * response with undefined fields.
172
- */
173
- function _isHtmlResponse(data, contentType) {
174
- const ct = String(contentType || '').toLowerCase();
175
- if (ct.includes('text/html')) return true;
176
- const body = String(data || '').trimStart().slice(0, 512).toLowerCase();
177
- return body.startsWith('<!doctype html>') || body.startsWith('<html');
178
- }
179
-
180
- /**
181
- * Shared strict compatibility validator (Protocol-v2 contract).
182
- *
183
- * Both `start` and `doctor` must use this single validator so the contract is
184
- * enforced identically everywhere. Requires:
185
- * - HTTP status 200
186
- * - application/json Content-Type
187
- * - plain non-array object body
188
- * - protocolVersion === 2
189
- * - non-empty minimumAgentVersion
190
- * - non-empty recommendedAgentVersion
191
- *
192
- * Never prints the HTML body or undefined values. For HTML/SPA responses it
193
- * returns { ok: false, html: true } and the caller prints the exact required
194
- * message.
195
- *
196
- * @param {object} resp — { status, body, contentType }
197
- * @returns {object} { ok: boolean, html?: boolean, reason?: string, body?: object }
198
- */
199
- function validateCompatibilityResponse(resp) {
200
- if (!resp || typeof resp !== 'object') {
201
- return { ok: false, reason: 'no response' };
202
- }
203
- // HTML/SPA detection takes priority — a text/html Content-Type or an explicit
204
- // html marker means the frontend was served instead of the API. Never inspect
205
- // body fields in this case.
206
- const ct = String(resp.contentType || '').toLowerCase();
207
- if (ct.includes('text/html') || resp.html || (resp.body && resp.body.html)) {
208
- return { ok: false, html: true };
209
- }
210
- if (resp.status !== 200) {
211
- return { ok: false, reason: 'unexpected status ' + resp.status };
212
- }
213
- if (!ct.includes('application/json')) {
214
- return { ok: false, reason: 'non-JSON Content-Type (' + (ct || 'missing') + ')' };
215
- }
216
- const body = resp.body;
217
- if (!body || typeof body !== 'object' || Array.isArray(body)) {
218
- return { ok: false, reason: 'body is not a plain object' };
219
- }
220
- if (body.protocolVersion !== 2) {
221
- return { ok: false, reason: 'missing or unsupported protocolVersion' };
222
- }
223
- if (!body.minimumAgentVersion || typeof body.minimumAgentVersion !== 'string') {
224
- return { ok: false, reason: 'missing minimumAgentVersion' };
225
- }
226
- if (!body.recommendedAgentVersion || typeof body.recommendedAgentVersion !== 'string') {
227
- return { ok: false, reason: 'missing recommendedAgentVersion' };
228
- }
229
- return { ok: true, body };
230
- }
231
-
232
- /**
233
- * The exact message to print for an HTML/SPA compatibility response.
234
- * Never print the HTML body or undefined values.
235
- */
236
- const COMPAT_HTML_MESSAGE =
237
- 'Server compatibility endpoint returned the frontend application instead of ' +
238
- 'Protocol-v2 JSON. The backend deployment or reverse-proxy routing for ' +
239
- '/api/agent/* is not active.';
240
-
241
- /**
242
- * Collect device metadata for the enrollment request.
243
- */
244
- function collectDeviceMetadata() {
245
- const platform = os.platform();
246
- const arch = os.arch();
247
- const hostname = os.hostname();
248
- const username = os.userInfo().username;
249
-
250
- // Detect Chrome version
251
- let chromeVersion = null;
252
- try {
253
- const { chromePath, chromeVersion: ver } = resolveChromeOrFail();
254
- chromeVersion = ver;
255
- } catch {
256
- // Chrome missing — will be reported separately
257
- }
258
-
259
- // Defect 12 fix: Generate a random local salt once, stored as non-secret
260
- // local metadata. The salt is NOT a credential — it just prevents the
261
- // machine fingerprint from being a trivially reproducible hash of public
262
- // attributes. The user can reset it by deleting the salt file.
263
- const crypto = require('crypto');
264
- const fs = require('fs');
265
- const { getDataDir } = require('./deviceKeyStore');
266
- const saltFile = path.join(getDataDir(), '.machine-salt');
267
- let salt;
268
- try {
269
- if (fs.existsSync(saltFile)) {
270
- salt = fs.readFileSync(saltFile, 'utf8').trim();
271
- }
272
- if (!salt || salt.length < 32) {
273
- salt = crypto.randomBytes(32).toString('base64url');
274
- if (!fs.existsSync(getDataDir())) fs.mkdirSync(getDataDir(), { recursive: true });
275
- fs.writeFileSync(saltFile, salt, { encoding: 'utf8', mode: 0o600 });
276
- }
277
- } catch {
278
- // If we can't read/write the salt, use a random ephemeral one.
279
- salt = crypto.randomBytes(32).toString('base64url');
280
- }
281
-
282
- // Hash only minimal attributes with the local salt (NOT a credential).
283
- // Avoid raw OS username when unnecessary — use hostname + platform + arch.
284
- const machineId = [hostname, platform, arch].join('|');
285
- const machineFingerprintHash = crypto
286
- .createHash('sha256')
287
- .update(salt + ':' + machineId)
288
- .digest('hex');
289
-
290
- return {
291
- deviceName: hostname,
292
- platform: platform === 'win32' ? 'Windows' : platform === 'darwin' ? 'macOS' : 'Linux',
293
- architecture: arch,
294
- chromeVersion,
295
- machineFingerprintHash,
296
- };
297
- }
298
-
299
- /**
300
- * Run the first-run enrollment flow.
301
- *
302
- * @param {string} serverOrigin — e.g. 'https://x.kwdstore.com'
303
- * @returns {object} { deviceId, deviceCertificate } on success
304
- */
305
- async function enroll(serverOrigin) {
306
- // 1. Generate Ed25519 key pair
307
- const keyPair = generateKeyPair();
308
-
309
- // 2. Store the private key securely (fail closed)
310
- try {
311
- await storePrivateKey(keyPair.privateKeyB64Url);
312
- } catch (e) {
313
- const platform = os.platform();
314
- const guidance = platform === 'win32'
315
- ? 'On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available for the current user.'
316
- : 'On Linux, install gnome-keyring or seahorse (libsecret).';
317
- throw new Error(
318
- 'Secure key storage is unavailable on this system.\n' +
319
- 'The private key cannot be stored safely.\n' +
320
- guidance + '\n' +
321
- 'Error: ' + e.message
322
- );
323
- }
324
-
325
- // 3. Collect device metadata
326
- const deviceMeta = collectDeviceMetadata();
327
-
328
- // 4. Start enrollment
329
- console.log('\nThis computer is not authorized yet.\n');
330
- console.log('Generating device key pair...');
331
- console.log(` Public-key fingerprint: ${keyPair.publicKeyFingerprint.slice(0, 4)}…${keyPair.publicKeyFingerprint.slice(-4)}`);
332
-
333
- const startResponse = await _request('POST', `${serverOrigin}/api/agent/enrollment/start`, {
334
- publicKey: keyPair.publicKeyB64Url,
335
- publicKeyFingerprint: keyPair.publicKeyFingerprint,
336
- deviceName: deviceMeta.deviceName,
337
- platform: deviceMeta.platform,
338
- architecture: deviceMeta.architecture,
339
- chromeVersion: deviceMeta.chromeVersion,
340
- machineFingerprintHash: deviceMeta.machineFingerprintHash,
341
- });
342
-
343
- if (startResponse.status !== 200) {
344
- throw new Error(`Enrollment start failed: ${startResponse.body.error || 'Unknown error'}`);
345
- }
346
-
347
- const { requestId, pollSecret, authorizationUrl, expiresAt } = startResponse.body;
348
-
349
- // 5. Open the authorization URL in the browser
350
- console.log('\nOpening XKWDStore in your browser...');
351
- console.log('Sign in and approve:');
352
- console.log(` Device: ${deviceMeta.deviceName}`);
353
- console.log(` Platform: ${deviceMeta.platform} ${deviceMeta.architecture}`);
354
- console.log(` Chrome: ${deviceMeta.chromeVersion || 'not detected'}`);
355
- console.log(` Public-key fingerprint: ${keyPair.publicKeyFingerprint.slice(0, 4)}…${keyPair.publicKeyFingerprint.slice(-4)}`);
356
-
357
- const opened = openBrowser(authorizationUrl);
358
- if (!opened) {
359
- console.log('\nCould not open browser automatically. Open this URL manually:');
360
- console.log(` ${authorizationUrl}`);
361
- }
362
-
363
- // 6. Poll for approval
364
- console.log('\nWaiting for approval...');
365
-
366
- const pollInterval = 3000; // 3 seconds
367
- const maxPollTime = (startResponse.body.expiresIn || 600) * 1000;
368
- const startTime = Date.now();
369
-
370
- while (Date.now() - startTime < maxPollTime) {
371
- await new Promise(resolve => setTimeout(resolve, pollInterval));
372
-
373
- const statusResponse = await _request(
374
- 'GET',
375
- `${serverOrigin}/api/agent/enrollment/${requestId}/status`,
376
- null,
377
- { 'X-Enrollment-Secret': pollSecret },
378
- );
379
-
380
- if (statusResponse.status !== 200) {
381
- // Could be rate-limited or temporary — keep polling
382
- continue;
383
- }
384
-
385
- const status = statusResponse.body;
386
-
387
- if (status.state === 'approved') {
388
- // 7. Save device metadata (non-secret)
389
- saveMetadata({
390
- deviceId: status.deviceId,
391
- publicKeyB64Url: keyPair.publicKeyB64Url,
392
- publicKeyFingerprint: keyPair.publicKeyFingerprint,
393
- deviceName: deviceMeta.deviceName,
394
- serverOrigin,
395
- });
396
-
397
- console.log('✓ Computer authorized');
398
- console.log(`✓ Device ID: ${status.deviceId}`);
399
-
400
- return {
401
- deviceId: status.deviceId,
402
- deviceCertificate: status.deviceCertificate,
403
- };
404
- }
405
-
406
- if (status.state === 'denied') {
407
- throw new Error('Enrollment request was denied by the account owner.');
408
- }
409
-
410
- if (status.state === 'expired') {
411
- throw new Error('Enrollment request has expired. Please run the command again.');
412
- }
413
-
414
- // Still pending — keep polling
415
- }
416
-
417
- throw new Error('Enrollment timed out. Please run the command again.');
418
- }
419
-
420
- /**
421
- * Check if this device is already enrolled.
422
- * @returns {object|null} device metadata or null
423
- */
424
- function getStoredDevice() {
425
- return loadMetadata();
426
- }
427
-
428
- /**
429
- * Get the stored private key for signing challenges.
430
- * @returns {string|null} private key base64url or null
431
- */
432
- async function getStoredPrivateKey() {
433
- return await loadPrivateKeyFromStorage();
434
- }
435
-
436
- module.exports = {
437
- enroll,
438
- getStoredDevice,
439
- getStoredPrivateKey,
440
- openBrowser,
441
- collectDeviceMetadata,
442
- _request,
443
- _isHtmlResponse,
444
- validateCompatibilityResponse,
445
- COMPAT_HTML_MESSAGE,
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
  };