@xkwdstore/agent 2.0.1

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