@xkwdstore/agent 2.1.1 → 2.1.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 +4 -4
- package/package.json +41 -65
- package/scripts/install-machine-agent.ps1 +41 -7
- package/scripts/worker-entry.js +1 -1
- package/src/brokerConnectionSupervisor.js +263 -0
- package/src/cli.js +1108 -1108
- package/src/ed25519Codec.js +158 -0
- package/src/index.js +2013 -0
- package/src/updater.js +578 -0
package/src/cli.js
CHANGED
|
@@ -1,1109 +1,1109 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
'use strict';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* XKWDStore Agent — Terminal-only CLI (protocol v2).
|
|
6
|
-
*
|
|
7
|
-
* Replaces the desktop-agent distribution, pairing-code workflow, updater,
|
|
8
|
-
* and in-memory WebSocket ticket architecture with a simpler, safer
|
|
9
|
-
* terminal-first system.
|
|
10
|
-
*
|
|
11
|
-
* Usage:
|
|
12
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> start
|
|
13
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> status
|
|
14
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
|
|
15
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
|
|
16
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
|
|
17
|
-
* npx --yes @xkwdstore/agent@<PINNED_VERSION> version
|
|
18
|
-
*
|
|
19
|
-
* The agent runs only while the terminal process is running.
|
|
20
|
-
* Closing the terminal or pressing Ctrl+C stops the agent cleanly.
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
const crypto = require('crypto');
|
|
24
|
-
const os = require('os');
|
|
25
|
-
const path = require('path');
|
|
26
|
-
|
|
27
|
-
const CLI_VERSION = '2.1.
|
|
28
|
-
const PROTOCOL_VERSION = 2;
|
|
29
|
-
|
|
30
|
-
// ── Command parsing ──────────────────────────────────────────────────────────
|
|
31
|
-
|
|
32
|
-
function main() {
|
|
33
|
-
const args = process.argv.slice(2);
|
|
34
|
-
const command = args[0] || 'help';
|
|
35
|
-
const flags = {};
|
|
36
|
-
const positional = [];
|
|
37
|
-
|
|
38
|
-
for (let i = 1; i < args.length; i++) {
|
|
39
|
-
const arg = args[i];
|
|
40
|
-
if (arg.startsWith('--')) {
|
|
41
|
-
const key = arg.slice(2);
|
|
42
|
-
const next = args[i + 1];
|
|
43
|
-
if (next && !next.startsWith('--')) {
|
|
44
|
-
flags[key] = next;
|
|
45
|
-
i++;
|
|
46
|
-
} else {
|
|
47
|
-
flags[key] = true;
|
|
48
|
-
}
|
|
49
|
-
} else {
|
|
50
|
-
positional.push(arg);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const serverOrigin = flags.server ||
|
|
55
|
-
process.env.XKWDSTORE_SERVER ||
|
|
56
|
-
'https://x.kwdstore.com';
|
|
57
|
-
|
|
58
|
-
switch (command) {
|
|
59
|
-
case 'start':
|
|
60
|
-
return start(serverOrigin, flags);
|
|
61
|
-
case 'status':
|
|
62
|
-
return status();
|
|
63
|
-
case 'logout':
|
|
64
|
-
return logout();
|
|
65
|
-
case 'revoke-local':
|
|
66
|
-
return revokeLocal();
|
|
67
|
-
case 'doctor':
|
|
68
|
-
return doctor(serverOrigin);
|
|
69
|
-
case 'machine':
|
|
70
|
-
return machine(positional);
|
|
71
|
-
case 'service':
|
|
72
|
-
return service(serverOrigin, flags);
|
|
73
|
-
case 'key-probe': {
|
|
74
|
-
// Diagnostics: report whether the machine credential can be decrypted in
|
|
75
|
-
// THIS process context (e.g. from the LocalSystem service) WITHOUT
|
|
76
|
-
// printing any secret. Used by the elevated lifecycle gate.
|
|
77
|
-
(async () => {
|
|
78
|
-
const fs = require('fs');
|
|
79
|
-
const path = require('path');
|
|
80
|
-
const { loadMetadata, loadPrivateKeyFromStorage, getMachineRoot, _identitySourceRoots, _serversDirFor } = require('./deviceKeyStore');
|
|
81
|
-
const { normalizeServerOrigin } = require('./deviceKeyStore');
|
|
82
|
-
const meta = loadMetadata({ serverOrigin });
|
|
83
|
-
const out = {
|
|
84
|
-
context: { user: require('os').userInfo().username, platform: os.platform(), pid: process.pid },
|
|
85
|
-
machineRoot: getMachineRoot(),
|
|
86
|
-
deviceId: meta ? meta.deviceId : null,
|
|
87
|
-
privateKeyDecryptable: false,
|
|
88
|
-
stages: {},
|
|
89
|
-
error: '',
|
|
90
|
-
};
|
|
91
|
-
// Stage 1: locate the key file the loader would use.
|
|
92
|
-
let keyFile = null;
|
|
93
|
-
try {
|
|
94
|
-
const roots = _identitySourceRoots();
|
|
95
|
-
const label = normalizeServerOrigin(serverOrigin);
|
|
96
|
-
const candidates = [];
|
|
97
|
-
for (const r of [roots.source, roots.target]) {
|
|
98
|
-
if (r) candidates.push(path.join(_serversDirFor(r), label, '.device-key'));
|
|
99
|
-
}
|
|
100
|
-
for (const r of [roots.source, roots.target]) { if (r) candidates.push(path.join(r, '.device-key')); }
|
|
101
|
-
out.stages.candidates = candidates;
|
|
102
|
-
for (const c of candidates) { if (fs.existsSync(c)) { keyFile = c; break; } }
|
|
103
|
-
out.stages.keyFile = keyFile;
|
|
104
|
-
out.stages.keyReadable = keyFile ? (() => { try { fs.accessSync(keyFile, fs.constants.R_OK); return true; } catch { return false; } })() : false;
|
|
105
|
-
if (keyFile) {
|
|
106
|
-
try {
|
|
107
|
-
const env = JSON.parse(fs.readFileSync(keyFile, 'utf8'));
|
|
108
|
-
out.stages.envelopeScheme = env.scheme;
|
|
109
|
-
out.stages.envelopeScope = env.scope || '(v1/unscoped)';
|
|
110
|
-
out.stages.envelopeV = env.v;
|
|
111
|
-
} catch (e) { out.stages.envelopeError = (e && e.message) || 'parse'; }
|
|
112
|
-
}
|
|
113
|
-
} catch (e) { out.stages.locateError = (e && e.message) || 'locate'; }
|
|
114
|
-
// Stage 2: full loader (includes ACL verify).
|
|
115
|
-
try { out.privateKeyDecryptable = !!(await loadPrivateKeyFromStorage({ serverOrigin })); } catch (e) { out.error = (e && e.message) || 'error'; }
|
|
116
|
-
console.log(JSON.stringify(out));
|
|
117
|
-
})().catch((e) => { console.error(JSON.stringify({ error: (e && e.message) || 'fatal' })); process.exit(1); });
|
|
118
|
-
return;
|
|
119
|
-
}
|
|
120
|
-
case 'version':
|
|
121
|
-
return version();
|
|
122
|
-
case 'help':
|
|
123
|
-
case '--help':
|
|
124
|
-
case '-h':
|
|
125
|
-
default:
|
|
126
|
-
return help();
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// ── Commands ─────────────────────────────────────────────────────────────────
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* `xkwd-agent start` — the main runtime command.
|
|
134
|
-
*/
|
|
135
|
-
async function start(serverOrigin, flags) {
|
|
136
|
-
console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
|
|
137
|
-
console.log(`Server: ${serverOrigin}`);
|
|
138
|
-
|
|
139
|
-
// 0. Machine-wide state: create the ProgramData layout and adopt any
|
|
140
|
-
// pre-2.1.0 per-user identity ONCE (copy, never move). The device identity
|
|
141
|
-
// therefore belongs to the MACHINE, not to the current Windows user.
|
|
142
|
-
try {
|
|
143
|
-
const machineState = require('./machineState');
|
|
144
|
-
const init = machineState.initializeMachineState();
|
|
145
|
-
console.log(`✓ Machine state: ${init.root}`);
|
|
146
|
-
if (init.adopted && init.deviceId) {
|
|
147
|
-
console.log(`✓ Adopted existing device identity: ${init.deviceId}`);
|
|
148
|
-
}
|
|
149
|
-
} catch (e) {
|
|
150
|
-
console.error(`Machine state initialization failed: ${(e && e.message) || 'unknown'}`);
|
|
151
|
-
process.exit(1);
|
|
152
|
-
}
|
|
153
|
-
console.log();
|
|
154
|
-
|
|
155
|
-
// 1. Detect OS and architecture (for display)
|
|
156
|
-
const platform = os.platform();
|
|
157
|
-
const arch = os.arch();
|
|
158
|
-
const hostname = os.hostname();
|
|
159
|
-
console.log(`✓ Detected computer: ${hostname}`);
|
|
160
|
-
console.log(`✓ Platform: ${platform} ${arch}`);
|
|
161
|
-
|
|
162
|
-
// 2. Resolve system Chrome (fail clearly if missing)
|
|
163
|
-
const { resolveChromeOrFail } = require('./chromeDetector');
|
|
164
|
-
let chromePath, chromeVersion;
|
|
165
|
-
try {
|
|
166
|
-
const chrome = resolveChromeOrFail();
|
|
167
|
-
chromePath = chrome.chromePath;
|
|
168
|
-
chromeVersion = chrome.chromeVersion;
|
|
169
|
-
console.log(`✓ Chrome ${chromeVersion || 'detected'}: ${chromePath}`);
|
|
170
|
-
} catch (e) {
|
|
171
|
-
console.error(e.message);
|
|
172
|
-
process.exit(1);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
// 3. Check compatibility with server (shared strict validator)
|
|
176
|
-
const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
|
|
177
|
-
try {
|
|
178
|
-
const compatResp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
|
|
179
|
-
const compat = validateCompatibilityResponse(compatResp);
|
|
180
|
-
if (compat.html) {
|
|
181
|
-
console.error('\n' + COMPAT_HTML_MESSAGE);
|
|
182
|
-
process.exit(1);
|
|
183
|
-
}
|
|
184
|
-
if (!compat.ok) {
|
|
185
|
-
console.error('\nServer compatibility check failed: ' + compat.reason + '.');
|
|
186
|
-
console.error('The agent will not start enrollment until the server is compatible.');
|
|
187
|
-
process.exit(1);
|
|
188
|
-
}
|
|
189
|
-
// NOTE: the server's declared `capabilities` are INFORMATIONAL. They are
|
|
190
|
-
// never a reason to refuse a server — a server that does not advertise the
|
|
191
|
-
// profile-identity capability may still supply the identity tuple, and every
|
|
192
|
-
// currently-deployed backend omits the field. A missing capability must not
|
|
193
|
-
// block startup (see validateCompatibilityResponse).
|
|
194
|
-
// compat.ok — enforce minimum agent version
|
|
195
|
-
const minVer = compat.body.minimumAgentVersion;
|
|
196
|
-
const recVer = compat.body.recommendedAgentVersion;
|
|
197
|
-
if (minVer && _compareVersions(CLI_VERSION, minVer) < 0) {
|
|
198
|
-
console.error(`\nThis agent version (${CLI_VERSION}) is no longer supported.`);
|
|
199
|
-
console.error(`\nRun:\n\n npx --yes @xkwdstore/agent@${recVer} start\n`);
|
|
200
|
-
process.exit(1);
|
|
201
|
-
}
|
|
202
|
-
} catch (e) {
|
|
203
|
-
console.error(`\nServer compatibility check failed: ${e.message}`);
|
|
204
|
-
console.error('The agent will not start enrollment until the server is reachable and compatible.');
|
|
205
|
-
process.exit(1);
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// 4. Load or generate device key (server-scoped: per-server identity)
|
|
209
|
-
const { getStoredDevice, getStoredPrivateKey, enroll } = require('./enrollmentClient');
|
|
210
|
-
const { isSecureStorageAvailable } = require('./deviceKeyStore');
|
|
211
|
-
|
|
212
|
-
if (!isSecureStorageAvailable()) {
|
|
213
|
-
console.error('Secure key storage is unavailable on this system.');
|
|
214
|
-
if (os.platform() === 'win32') {
|
|
215
|
-
console.error('On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available.');
|
|
216
|
-
} else {
|
|
217
|
-
console.error('On Linux, install gnome-keyring or seahorse (libsecret).');
|
|
218
|
-
}
|
|
219
|
-
console.error('The agent cannot run without secure key storage.');
|
|
220
|
-
process.exit(1);
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
let deviceMeta = getStoredDevice({ serverOrigin });
|
|
224
|
-
let privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
225
|
-
|
|
226
|
-
// 5. Authorize the device when needed (first run or revoked)
|
|
227
|
-
if (!deviceMeta || !privateKeyB64Url) {
|
|
228
|
-
console.log('\n✓ Device identity loaded securely');
|
|
229
|
-
try {
|
|
230
|
-
const result = await enroll(serverOrigin, { chromePath });
|
|
231
|
-
deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
|
|
232
|
-
privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
233
|
-
} catch (e) {
|
|
234
|
-
console.error(`\nEnrollment failed: ${e.message}`);
|
|
235
|
-
process.exit(1);
|
|
236
|
-
}
|
|
237
|
-
} else {
|
|
238
|
-
console.log(`✓ Device identity loaded securely`);
|
|
239
|
-
console.log(`✓ Device recognized: ${deviceMeta.deviceName}`);
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// 6. Process lock (prevent duplicate instances)
|
|
243
|
-
const processLock = require('./processLock');
|
|
244
|
-
const lockResult = processLock.acquireLock({
|
|
245
|
-
deviceId: deviceMeta.deviceId,
|
|
246
|
-
deviceName: deviceMeta.deviceName,
|
|
247
|
-
});
|
|
248
|
-
|
|
249
|
-
if (!lockResult.acquired) {
|
|
250
|
-
if (flags.replace) {
|
|
251
|
-
console.log('\nAnother agent instance is running. Requesting takeover...');
|
|
252
|
-
const took = await processLock.requestTakeover(lockResult.existing);
|
|
253
|
-
if (!took) {
|
|
254
|
-
console.error('Could not stop the existing instance. Please close it manually.');
|
|
255
|
-
process.exit(1);
|
|
256
|
-
}
|
|
257
|
-
// Re-acquire the lock
|
|
258
|
-
const retryLock = processLock.acquireLock({
|
|
259
|
-
deviceId: deviceMeta.deviceId,
|
|
260
|
-
deviceName: deviceMeta.deviceName,
|
|
261
|
-
});
|
|
262
|
-
if (!retryLock.acquired) {
|
|
263
|
-
console.error('Could not acquire process lock after takeover.');
|
|
264
|
-
process.exit(1);
|
|
265
|
-
}
|
|
266
|
-
} else {
|
|
267
|
-
console.error('\nXKWDStore Agent is already running on this computer.');
|
|
268
|
-
console.error(`PID: ${lockResult.existing.pid}`);
|
|
269
|
-
console.error(`Started: ${lockResult.existing.startedAt}`);
|
|
270
|
-
console.error(`Device: ${lockResult.existing.deviceName || 'unknown'}`);
|
|
271
|
-
console.error('\nTo replace the running instance, use:');
|
|
272
|
-
console.error(' xkwd-agent start --replace');
|
|
273
|
-
process.exit(1);
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// 7. Connect securely via WebSocket challenge-response
|
|
278
|
-
// 4003 auto-recovery: if the initial connection fails with 4003 (revoked/
|
|
279
|
-
// unknown device), the agent automatically performs a server-scoped
|
|
280
|
-
// re-enrollment and reconnects in the SAME process flow — the user does
|
|
281
|
-
// NOT need to type a second command. Only ONE auto-recovery attempt is
|
|
282
|
-
// allowed per startup to prevent infinite loops.
|
|
283
|
-
const { connectWebSocket } = require('./wsClient');
|
|
284
|
-
let ws;
|
|
285
|
-
let autoRecovered = false;
|
|
286
|
-
|
|
287
|
-
try {
|
|
288
|
-
ws = await connectWebSocket({
|
|
289
|
-
serverOrigin,
|
|
290
|
-
deviceId: deviceMeta.deviceId,
|
|
291
|
-
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
292
|
-
privateKeyB64Url,
|
|
293
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
294
|
-
});
|
|
295
|
-
} catch (connectErr) {
|
|
296
|
-
// Check if this is a 4003 authentication failure (revoked/unknown device).
|
|
297
|
-
// The wsClient rejects with a message containing "Device authentication
|
|
298
|
-
// failed" for 4003 close codes, or the error may carry a .code property.
|
|
299
|
-
const isAuthFailure = _is4003Error(connectErr);
|
|
300
|
-
|
|
301
|
-
if (isAuthFailure && !autoRecovered) {
|
|
302
|
-
autoRecovered = true;
|
|
303
|
-
console.error('\n❌ Authentication failed (4003) — this device may be revoked.');
|
|
304
|
-
console.error(' Automatically re-authorizing for ' + serverOrigin + '...');
|
|
305
|
-
console.error(' (Other servers\' identities are NOT affected.)');
|
|
306
|
-
|
|
307
|
-
// Release the lock before re-enrollment (enrollment opens a browser)
|
|
308
|
-
processLock.releaseLock();
|
|
309
|
-
|
|
310
|
-
// Delete only this server's identity
|
|
311
|
-
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
312
|
-
await deletePrivateKey({ serverOrigin });
|
|
313
|
-
deleteMetadata({ serverOrigin });
|
|
314
|
-
console.error('✓ Old identity cleared for ' + serverOrigin);
|
|
315
|
-
|
|
316
|
-
// Re-enroll automatically (opens browser for approval)
|
|
317
|
-
console.log('\nOpening authorization page...');
|
|
318
|
-
try {
|
|
319
|
-
await enroll(serverOrigin, { chromePath });
|
|
320
|
-
deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
|
|
321
|
-
privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
322
|
-
|
|
323
|
-
if (!deviceMeta || !privateKeyB64Url) {
|
|
324
|
-
console.error('\n❌ Re-enrollment completed but identity could not be loaded.');
|
|
325
|
-
process.exit(1);
|
|
326
|
-
}
|
|
327
|
-
console.log('✓ New identity stored for ' + serverOrigin);
|
|
328
|
-
} catch (enrollErr) {
|
|
329
|
-
console.error(`\n❌ Automatic re-enrollment failed: ${enrollErr.message}`);
|
|
330
|
-
console.error(' Run `xkwd-agent start` again to retry manually.');
|
|
331
|
-
process.exit(1);
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
// Re-acquire the process lock with the new device identity
|
|
335
|
-
const retryLock = processLock.acquireLock({
|
|
336
|
-
deviceId: deviceMeta.deviceId,
|
|
337
|
-
deviceName: deviceMeta.deviceName,
|
|
338
|
-
});
|
|
339
|
-
if (!retryLock.acquired) {
|
|
340
|
-
console.error('Could not acquire process lock after re-enrollment.');
|
|
341
|
-
if (flags.replace) {
|
|
342
|
-
const took = await processLock.requestTakeover(retryLock.existing);
|
|
343
|
-
if (!took) {
|
|
344
|
-
console.error('Could not stop the existing instance. Please close it manually.');
|
|
345
|
-
process.exit(1);
|
|
346
|
-
}
|
|
347
|
-
} else {
|
|
348
|
-
process.exit(1);
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
// Attempt to reconnect with the new identity (only ONE retry)
|
|
353
|
-
try {
|
|
354
|
-
ws = await connectWebSocket({
|
|
355
|
-
serverOrigin,
|
|
356
|
-
deviceId: deviceMeta.deviceId,
|
|
357
|
-
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
358
|
-
privateKeyB64Url,
|
|
359
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
360
|
-
});
|
|
361
|
-
console.log('\n✓ Re-authorized and reconnected automatically.');
|
|
362
|
-
} catch (retryErr) {
|
|
363
|
-
if (_is4003Error(retryErr)) {
|
|
364
|
-
console.error('\n❌ Authentication failed again after re-enrollment.');
|
|
365
|
-
console.error(' The new device may not have been approved on the dashboard.');
|
|
366
|
-
console.error(' Run `xkwd-agent start` again after approving the device.');
|
|
367
|
-
} else {
|
|
368
|
-
console.error(`\n❌ Reconnection failed: ${retryErr.message}`);
|
|
369
|
-
console.error(' Run `xkwd-agent start` again to retry.');
|
|
370
|
-
}
|
|
371
|
-
processLock.releaseLock();
|
|
372
|
-
process.exit(1);
|
|
373
|
-
}
|
|
374
|
-
} else {
|
|
375
|
-
// Non-4003 error, or 4003 after auto-recovery already attempted
|
|
376
|
-
console.error(`\nConnection failed: ${connectErr.message}`);
|
|
377
|
-
if (isAuthFailure) {
|
|
378
|
-
console.error(' Automatic recovery was already attempted. Run `xkwd-agent start` again.');
|
|
379
|
-
}
|
|
380
|
-
processLock.releaseLock();
|
|
381
|
-
process.exit(1);
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
console.log('✓ Secure challenge passed');
|
|
386
|
-
console.log('✓ Connected');
|
|
387
|
-
console.log('\nAgent is running. Press Ctrl+C to stop.\n');
|
|
388
|
-
|
|
389
|
-
// Keep SQLite-style registry state honest: the handler owns session
|
|
390
|
-
// registration; ensure the machine runtime dir exists before the first launch.
|
|
391
|
-
try {
|
|
392
|
-
const ms = require('./machineState');
|
|
393
|
-
ms.ensureMachineLayout();
|
|
394
|
-
} catch { /* best-effort */ }
|
|
395
|
-
|
|
396
|
-
// 8. Set up browser session handler (delegates to existing session management)
|
|
397
|
-
const { setupSessionHandler, closeAllSessions, markDisconnected, recoverOrphanedSessions } = require('./sessionHandler');
|
|
398
|
-
|
|
399
|
-
// 2.1.0 F1: crash recovery. A previous agent process may have left an
|
|
400
|
-
// Agent-OWNED Chromium behind (it is alive but unmanaged). Release the stale
|
|
401
|
-
// LOCAL locks for those proven-owned sessions so the accounts are not blocked
|
|
402
|
-
// on this device. The SERVER durable lease is authoritative and is NOT touched
|
|
403
|
-
// here — server recovery (recovery-probe / reconcile) still governs it.
|
|
404
|
-
try {
|
|
405
|
-
const recovery = recoverOrphanedSessions();
|
|
406
|
-
if (recovery.orphans > 0) {
|
|
407
|
-
console.log(`ℹ️ Crash recovery: found ${recovery.orphans} Agent-owned orphaned browser(s); released ${recovery.released} local lock(s).`);
|
|
408
|
-
}
|
|
409
|
-
} catch { /* never block startup on recovery */ }
|
|
410
|
-
|
|
411
|
-
const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
|
|
412
|
-
|
|
413
|
-
// 8a. Disconnect handling — the SAME reconnect supervisor as the machine
|
|
414
|
-
// `service` broker. The foreground agent adopts the already-authenticated
|
|
415
|
-
// socket; the supervisor owns every subsequent (re)connect, guaranteeing one
|
|
416
|
-
// timer / one attempt / one live socket, with unbounded self-healing that uses
|
|
417
|
-
// the SAME enrolled identity (transport recovery only, never a new identity).
|
|
418
|
-
//
|
|
419
|
-
// Interactive-path policy preserved:
|
|
420
|
-
// - server-initiated restart (1000 'agent-restart' / 4002 'Server-initiated
|
|
421
|
-
// restart'): rebind WITHOUT touching local browsers — the server reconciles
|
|
422
|
-
// leases from our sessions-report after reconnect.
|
|
423
|
-
// - any OTHER close: mark disconnected + close all browser contexts (profiles
|
|
424
|
-
// persist), then reconnect.
|
|
425
|
-
// - 4003 revoked mid-session: clear THIS server's identity and stop (explicit
|
|
426
|
-
// re-authorization) — the supervisor NEVER regenerates identity.
|
|
427
|
-
const _isRestartClose = (code, reasonStr) =>
|
|
428
|
-
(code === 1000 && /agent-restart/i.test(reasonStr))
|
|
429
|
-
|| (code === 4002 && /server-initiated restart/i.test(reasonStr));
|
|
430
|
-
|
|
431
|
-
const supervisor = createBrokerConnectionSupervisor({
|
|
432
|
-
connect: () => connectWebSocket({
|
|
433
|
-
serverOrigin,
|
|
434
|
-
deviceId: deviceMeta.deviceId,
|
|
435
|
-
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
436
|
-
privateKeyB64Url,
|
|
437
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
438
|
-
}),
|
|
439
|
-
onConnected: (socket) => { setupSessionHandler(socket, { chromePath, deviceMeta, serverOrigin }); },
|
|
440
|
-
onDisconnected: async ({ code, reason }) => {
|
|
441
|
-
const reasonStr = reason || '';
|
|
442
|
-
if (_isRestartClose(code, reasonStr)) {
|
|
443
|
-
console.log('\nℹ️ Server requested a connection restart. Reconnecting (browser sessions stay open)...');
|
|
444
|
-
return; // keep local browsers; the server reconciles leases
|
|
445
|
-
}
|
|
446
|
-
console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
|
|
447
|
-
console.error(' Closing all browser sessions and reconnecting safely...');
|
|
448
|
-
markDisconnected();
|
|
449
|
-
try { await closeAllSessions(); } catch { }
|
|
450
|
-
},
|
|
451
|
-
onAuthRejected: () => {
|
|
452
|
-
// 4003: the credential is dead. Do NOT regenerate identity automatically.
|
|
453
|
-
console.error('\n❌ Authentication failed — this device was revoked.');
|
|
454
|
-
console.error(' Run `xkwd-agent start` again to re-authorize this computer.');
|
|
455
|
-
try {
|
|
456
|
-
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
457
|
-
deletePrivateKey({ serverOrigin });
|
|
458
|
-
deleteMetadata({ serverOrigin });
|
|
459
|
-
} catch { }
|
|
460
|
-
processLock.releaseLock();
|
|
461
|
-
process.exit(1);
|
|
462
|
-
},
|
|
463
|
-
onExhausted: () => {
|
|
464
|
-
console.error('\n❌ Could not reconnect. Run `xkwd-agent start` again.');
|
|
465
|
-
processLock.releaseLock();
|
|
466
|
-
process.exit(1);
|
|
467
|
-
},
|
|
468
|
-
maxAttempts: 10,
|
|
469
|
-
log: (m) => { try { console.log(m); } catch { } },
|
|
470
|
-
});
|
|
471
|
-
supervisor.adopt(ws);
|
|
472
|
-
|
|
473
|
-
// Deliberate-shutdown guard (set before closing anything, so a close emitted
|
|
474
|
-
// during shutdown cannot trigger a reconnect).
|
|
475
|
-
let shuttingDown = false;
|
|
476
|
-
|
|
477
|
-
// 9. Clean shutdown on Ctrl+C
|
|
478
|
-
async function shutdown(signal) {
|
|
479
|
-
if (shuttingDown) return;
|
|
480
|
-
shuttingDown = true;
|
|
481
|
-
console.log(`\n${signal} received. Shutting down...`);
|
|
482
|
-
|
|
483
|
-
// Stop reconnecting FIRST so no retry can start after shutdown begins.
|
|
484
|
-
try { supervisor.stop(); } catch { }
|
|
485
|
-
|
|
486
|
-
// Stop accepting commands immediately.
|
|
487
|
-
markDisconnected();
|
|
488
|
-
|
|
489
|
-
// Close all browser sessions (preserves profiles/cookies via the
|
|
490
|
-
// existing safe persistence path).
|
|
491
|
-
try {
|
|
492
|
-
await closeAllSessions();
|
|
493
|
-
} catch {}
|
|
494
|
-
|
|
495
|
-
// Release lock
|
|
496
|
-
processLock.releaseLock();
|
|
497
|
-
|
|
498
|
-
process.exit(0);
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
process.on('SIGINT', () => shutdown('Ctrl+C'));
|
|
502
|
-
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
503
|
-
process.on('SIGHUP', () => shutdown('SIGHUP'));
|
|
504
|
-
|
|
505
|
-
// Also release the lock on uncaught exceptions
|
|
506
|
-
process.on('uncaughtException', (err) => {
|
|
507
|
-
console.error('Uncaught error:', err.message);
|
|
508
|
-
processLock.releaseLock();
|
|
509
|
-
process.exit(1);
|
|
510
|
-
});
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
/**
|
|
514
|
-
* `xkwd-agent status` — show device and connection status.
|
|
515
|
-
*/
|
|
516
|
-
function status() {
|
|
517
|
-
const { getStoredDevice } = require('./enrollmentClient');
|
|
518
|
-
const { isSecureStorageAvailable } = require('./deviceKeyStore');
|
|
519
|
-
const processLock = require('./processLock');
|
|
520
|
-
|
|
521
|
-
const args = process.argv.slice(2);
|
|
522
|
-
const serverFlag = args.find(a => a.startsWith('--server='));
|
|
523
|
-
const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
|
|
524
|
-
|
|
525
|
-
const device = getStoredDevice({ serverOrigin });
|
|
526
|
-
const lock = processLock.readLock();
|
|
527
|
-
|
|
528
|
-
console.log(`XKWDStore Agent v${CLI_VERSION}\n`);
|
|
529
|
-
|
|
530
|
-
const machineState = require('./machineState');
|
|
531
|
-
console.log(`Machine root: ${machineState.getMachineRoot()}`);
|
|
532
|
-
console.log(`Machine identity: ${machineState.hasMachineIdentity() ? 'present' : 'not yet adopted'}\n`);
|
|
533
|
-
|
|
534
|
-
if (!device) {
|
|
535
|
-
console.log('Status: Not authorized');
|
|
536
|
-
console.log('Run `xkwd-agent start` to authorize this computer.');
|
|
537
|
-
return;
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
console.log(`Device ID: ${device.deviceId}`);
|
|
541
|
-
console.log(`Device name: ${device.deviceName}`);
|
|
542
|
-
console.log(`Server: ${device.serverOrigin || 'https://x.kwdstore.com'}`);
|
|
543
|
-
console.log(`Public-key fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
|
|
544
|
-
console.log(`Created: ${device.createdAt || 'unknown'}`);
|
|
545
|
-
console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available' : 'unavailable'}`);
|
|
546
|
-
|
|
547
|
-
if (lock) {
|
|
548
|
-
console.log(`\nAgent process: RUNNING (PID ${lock.pid})`);
|
|
549
|
-
console.log(`Started: ${lock.startedAt}`);
|
|
550
|
-
} else {
|
|
551
|
-
console.log('\nAgent process: not running');
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
/**
|
|
556
|
-
* `xkwd-agent logout` — delete local device identity (re-enrollment required).
|
|
557
|
-
* Server-scoped: only deletes the identity for the specified server.
|
|
558
|
-
* Usage: xkwd-agent logout [--server=<url>]
|
|
559
|
-
*/
|
|
560
|
-
async function logout() {
|
|
561
|
-
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
562
|
-
const processLock = require('./processLock');
|
|
563
|
-
|
|
564
|
-
// Parse --server flag for scoped logout
|
|
565
|
-
const args = process.argv.slice(2);
|
|
566
|
-
const serverFlag = args.find(a => a.startsWith('--server='));
|
|
567
|
-
const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
|
|
568
|
-
|
|
569
|
-
const lock = processLock.readLock();
|
|
570
|
-
if (lock) {
|
|
571
|
-
console.error('Agent is currently running. Stop it first with Ctrl+C.');
|
|
572
|
-
process.exit(1);
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
await deletePrivateKey({ serverOrigin });
|
|
576
|
-
deleteMetadata({ serverOrigin });
|
|
577
|
-
console.log(`Local device identity deleted for ${serverOrigin}.`);
|
|
578
|
-
console.log('Run `xkwd-agent start` to re-authorize this computer.');
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
/**
|
|
582
|
-
* `xkwd-agent revoke-local` — same as logout but also clears the process lock.
|
|
583
|
-
* Server-scoped: only deletes the identity for the specified server.
|
|
584
|
-
*/
|
|
585
|
-
async function revokeLocal() {
|
|
586
|
-
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
587
|
-
const args = process.argv.slice(2);
|
|
588
|
-
const serverFlag = args.find(a => a.startsWith('--server='));
|
|
589
|
-
const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
|
|
590
|
-
await deletePrivateKey({ serverOrigin });
|
|
591
|
-
deleteMetadata({ serverOrigin });
|
|
592
|
-
console.log(`Local device identity and credentials revoked for ${serverOrigin}.`);
|
|
593
|
-
console.log('The server-side device record should also be revoked from the dashboard.');
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
/**
|
|
597
|
-
* `xkwd-agent machine` — machine-wide state operations (2.1.0).
|
|
598
|
-
*
|
|
599
|
-
* machine status — root, layout, identity presence, migration state
|
|
600
|
-
* machine adopt — run the one-time per-user → machine migration now
|
|
601
|
-
* machine harden — (Windows) apply + verify the restrictive DACL on the
|
|
602
|
-
* machine state directories
|
|
603
|
-
*/
|
|
604
|
-
async function machine(args) {
|
|
605
|
-
const machineState = require('./machineState');
|
|
606
|
-
const { getMachineRoot, getLegacyDataDir, applyMachineStateAcls } = require('./deviceKeyStore');
|
|
607
|
-
const action = (Array.isArray(args) && args[0]) || 'status';
|
|
608
|
-
|
|
609
|
-
if (action === 'status' || action === 'info') {
|
|
610
|
-
const report = machineState.migrationReport();
|
|
611
|
-
console.log(`XKWDStore Agent v${CLI_VERSION} — Machine state\n`);
|
|
612
|
-
console.log(`Machine root (device identity lives here): ${report.newLocation}`);
|
|
613
|
-
console.log(` exists: ${report.machinePresent ? 'yes' : 'no'}`);
|
|
614
|
-
console.log(` identity present: ${machineState.hasMachineIdentity() ? 'yes' : 'no'}`);
|
|
615
|
-
console.log(`Legacy per-user root (migration source): ${report.oldLocation}`);
|
|
616
|
-
console.log(` exists: ${report.legacyPresent ? 'yes' : 'no'}`);
|
|
617
|
-
console.log(`Started: ${report.machinePresent ? 'yes' : 'no'}`);
|
|
618
|
-
if (report.marker) {
|
|
619
|
-
console.log(`Migration: ${report.marker.adoption || 'complete'} at ${report.marker.migratedAt}`);
|
|
620
|
-
console.log(` device id(s): ${(report.marker.deviceIds || []).join(', ') || '(none)'}`);
|
|
621
|
-
} else {
|
|
622
|
-
console.log('Migration: not required (no legacy identity found) or not yet run');
|
|
623
|
-
}
|
|
624
|
-
console.log(`Rollback supported: ${report.rollbackSupported ? 'yes' : 'no'}`);
|
|
625
|
-
console.log(` ${report.rollbackInstruction}`);
|
|
626
|
-
return;
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
if (action === 'adopt') {
|
|
630
|
-
const result = machineState.initializeMachineState();
|
|
631
|
-
console.log(`Machine root: ${result.root}`);
|
|
632
|
-
console.log(result.adopted
|
|
633
|
-
? `Adopted legacy per-user state (device id: ${result.deviceId || 'preserved'}).`
|
|
634
|
-
: `No adoption needed (${result.reason}).`);
|
|
635
|
-
return;
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
if (action === 'harden') {
|
|
639
|
-
if (os.platform() !== 'win32') {
|
|
640
|
-
console.log('Machine-state ACL hardening is Windows-only; nothing to do.');
|
|
641
|
-
return;
|
|
642
|
-
}
|
|
643
|
-
const applied = applyMachineStateAcls({});
|
|
644
|
-
console.log(`Applied and verified restrictive ACLs on ${applied.length} machine-state director${applied.length === 1 ? 'y' : 'ies'}:`);
|
|
645
|
-
for (const p of applied) console.log(` ${p}`);
|
|
646
|
-
return;
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
console.error(`Unknown machine action: ${action}`);
|
|
650
|
-
console.error('Usage: xkwd-agent machine [status|adopt|harden]');
|
|
651
|
-
process.exit(1);
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
/**
|
|
655
|
-
* `xkwd-agent service` — the BROKER entry point (2.1.0).
|
|
656
|
-
*
|
|
657
|
-
* Runs the machine-wide broker that a Windows Service hosts. Responsibilities:
|
|
658
|
-
* - acquire the machine-wide named mutex (exactly one broker)
|
|
659
|
-
* - own the machine identity + device private key
|
|
660
|
-
* - own the server WebSocket connection, leases, and session registry
|
|
661
|
-
* - spawn an interactive Browser Worker in the active desktop session
|
|
662
|
-
* - relay TYPED browser commands to the worker over a loopback-only channel
|
|
663
|
-
*
|
|
664
|
-
* It never launches Chromium itself. It is silent by design (the service host
|
|
665
|
-
* provides no desktop). For foreground diagnostics, `start` runs a broker+worker
|
|
666
|
-
* pair in this same session.
|
|
667
|
-
*/
|
|
668
|
-
async function service(serverOrigin, flags) {
|
|
669
|
-
const machineLock = require('./machineLock');
|
|
670
|
-
const machineState = require('./machineState');
|
|
671
|
-
|
|
672
|
-
// 1. machine-wide broker uniqueness (authoritative on Windows).
|
|
673
|
-
const lock = machineLock.acquireMachineBrokerLock();
|
|
674
|
-
if (!lock.acquired) {
|
|
675
|
-
console.error(`Another machine broker already holds the lock (${lock.primitive}): ${lock.detail}`);
|
|
676
|
-
process.exit(3);
|
|
677
|
-
}
|
|
678
|
-
// Hold it for the process lifetime via a dedicated holder process.
|
|
679
|
-
const holder = machineLock.startMutexHolder();
|
|
680
|
-
if (!holder.ok) {
|
|
681
|
-
console.error(`Could not hold the machine broker lock: ${holder.detail}`);
|
|
682
|
-
process.exit(3);
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
// 2. machine state + identity (broker owns the credential).
|
|
686
|
-
try { machineState.initializeMachineState(); } catch { }
|
|
687
|
-
|
|
688
|
-
console.log(`XKWDStore Agent broker v${CLI_VERSION} (machine-wide)`);
|
|
689
|
-
console.log(`Machine root: ${machineState.getMachineRoot()}`);
|
|
690
|
-
console.log(`Broker lock: ${lock.detail}`);
|
|
691
|
-
|
|
692
|
-
// 3. connect to the server (broker owns the WebSocket).
|
|
693
|
-
// `--offline` (test-lifecycle only) skips the server connection so the service
|
|
694
|
-
// host / mutex / identity can be proven without a live enrollment. Production
|
|
695
|
-
// always connects.
|
|
696
|
-
const offline = !!flags.offline;
|
|
697
|
-
let ws = null;
|
|
698
|
-
if (offline) {
|
|
699
|
-
console.log('Broker running OFFLINE (lifecycle test mode; no server connection)');
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
if (offline) {
|
|
703
|
-
// Prove identity loads and the broker stays alive; keep the mutex held.
|
|
704
|
-
const meta = (() => { try { return require('./deviceKeyStore').loadMetadata({ serverOrigin }); } catch { return null; } })();
|
|
705
|
-
console.log(`Broker identity: ${meta && meta.deviceId ? meta.deviceId : '(none)'}`);
|
|
706
|
-
|
|
707
|
-
// --probe-worker: open the bridge, launch the interactive worker, and report
|
|
708
|
-
// the worker's Windows session id so the Session-0 -> interactive-session
|
|
709
|
-
// launch is PROVEN with a real process. Lifecycle-test only.
|
|
710
|
-
if (flags['probe-worker']) {
|
|
711
|
-
const bridge = require('./brokerWorkerBridge');
|
|
712
|
-
const token = bridge.newChannelToken();
|
|
713
|
-
const channel = await bridge.openBrokerChannel({ token });
|
|
714
|
-
console.log(`probe: bridge port ${channel.port}`);
|
|
715
|
-
const child = _spawnInteractiveWorker({ port: channel.port, token });
|
|
716
|
-
const deadline = Date.now() + 20000;
|
|
717
|
-
while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 150)); }
|
|
718
|
-
console.log(`probe: worker connected=${channel.connected}`);
|
|
719
|
-
console.log(`probe: activeConsoleSession=${_activeConsoleSession()} workerSession=${typeof child.session === 'number' ? child.session : 'n/a'}`);
|
|
720
|
-
try {
|
|
721
|
-
const st = await channel.call('getStatus', {}, 10000);
|
|
722
|
-
console.log('probe: worker status ' + JSON.stringify(st));
|
|
723
|
-
} catch (e) {
|
|
724
|
-
console.log('probe: worker status error ' + ((e && e.message) || 'unknown'));
|
|
725
|
-
}
|
|
726
|
-
// Give the harness time to inspect the worker process, then stop it.
|
|
727
|
-
await new Promise((r) => setTimeout(r, 12000));
|
|
728
|
-
try { await channel.call('shutdown', {}, 5000); } catch { }
|
|
729
|
-
try { channel.close(); } catch { }
|
|
730
|
-
console.log('probe: done');
|
|
731
|
-
machineLock.releaseMachineBrokerLock();
|
|
732
|
-
process.exit(0);
|
|
733
|
-
}
|
|
734
|
-
|
|
735
|
-
console.log('Broker alive; holding the machine lock. Ctrl+C to stop.');
|
|
736
|
-
const t = setInterval(() => {
|
|
737
|
-
try { console.log('broker heartbeat ' + new Date().toISOString()); } catch { }
|
|
738
|
-
}, 15000);
|
|
739
|
-
t.unref();
|
|
740
|
-
await new Promise(() => { }); // run until killed
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
// 4. spawn one interactive worker and route typed commands to it.
|
|
744
|
-
const bridge = require('./brokerWorkerBridge');
|
|
745
|
-
const token = bridge.newChannelToken();
|
|
746
|
-
const channel = await bridge.openBrokerChannel({ token });
|
|
747
|
-
const sessionHandler = require('./sessionHandler');
|
|
748
|
-
|
|
749
|
-
// The broker does NOT launch Chromium: it forwards startSession/stopSession to
|
|
750
|
-
// the worker. A worker is SESSION-BOUND: it is launched into the currently
|
|
751
|
-
// ACTIVE console session and is DISPOSABLE — a worker left over from a previous
|
|
752
|
-
// user (e.g. after a fast user switch) must NEVER serve a new session's job.
|
|
753
|
-
let worker = null;
|
|
754
|
-
let workerSession = -1;
|
|
755
|
-
async function ensureWorker() {
|
|
756
|
-
const active = _activeConsoleSession();
|
|
757
|
-
// Reuse the connected worker ONLY when it is in the CURRENT active session.
|
|
758
|
-
// On a change of active session the stale worker is torn down first (see the
|
|
759
|
-
// pure `shouldReplaceWorker` truth table).
|
|
760
|
-
const replace = bridge.shouldReplaceWorker({ connected: channel.connected, workerSession, activeSession: active });
|
|
761
|
-
if (!replace) return;
|
|
762
|
-
if (channel.connected) {
|
|
763
|
-
try { console.log(`worker session ${workerSession} != active ${active}; replacing the worker`); } catch { }
|
|
764
|
-
try { await channel.call('shutdown', {}, 5000); } catch { }
|
|
765
|
-
try { channel.dropWorker(); } catch { }
|
|
766
|
-
try { if (worker && worker.child) worker.child.kill(); } catch { }
|
|
767
|
-
workerSession = -1;
|
|
768
|
-
// Give the channel a moment to clear the old worker.
|
|
769
|
-
await new Promise((r) => setTimeout(r, 300));
|
|
770
|
-
}
|
|
771
|
-
worker = _spawnInteractiveWorker({ port: channel.port, token });
|
|
772
|
-
const deadline = Date.now() + 15000;
|
|
773
|
-
while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 100)); }
|
|
774
|
-
if (!channel.connected) throw new Error('interactive worker did not attach');
|
|
775
|
-
// The launcher reports the target session on its stdout; wait briefly for it.
|
|
776
|
-
const sdeadline = Date.now() + 3000;
|
|
777
|
-
while (workerSession === -1 && Date.now() < sdeadline) {
|
|
778
|
-
workerSession = typeof worker.session === 'number' ? worker.session : -1;
|
|
779
|
-
if (workerSession === -1) await new Promise((r) => setTimeout(r, 100));
|
|
780
|
-
}
|
|
781
|
-
try { console.log(`worker attached (session=${workerSession}, active=${active})`); } catch { }
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
const { setupSessionHandler, closeAllSessions, markDisconnected } = sessionHandler;
|
|
785
|
-
const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
|
|
786
|
-
|
|
787
|
-
// 4a. ONE reconnect supervisor owns the production WebSocket lifecycle so a
|
|
788
|
-
// transient network/DNS/TLS/backend/WS/heartbeat loss reconnects with the
|
|
789
|
-
// SAME enrolled identity — no manual restart, no re-pair, no new key. Retries
|
|
790
|
-
// are UNBOUNDED for the machine service (a long-lived broker must self-heal);
|
|
791
|
-
// the supervisor preserves exactly one timer / one attempt / one socket.
|
|
792
|
-
const _bindSessionHandler = (socket) => setupSessionHandler(socket, {
|
|
793
|
-
// The broker has no chromePath: all browser work goes through the worker.
|
|
794
|
-
chromePath: null,
|
|
795
|
-
deviceMeta: require('./deviceKeyStore').loadMetadata({ serverOrigin }) || {},
|
|
796
|
-
serverOrigin,
|
|
797
|
-
// 2.1.0: route browser commands through the worker bridge.
|
|
798
|
-
workerBridge: {
|
|
799
|
-
ensureWorker,
|
|
800
|
-
call: (command, payload) => channel.call(command, payload),
|
|
801
|
-
},
|
|
802
|
-
});
|
|
803
|
-
|
|
804
|
-
const supervisor = createBrokerConnectionSupervisor({
|
|
805
|
-
connect: () => _brokerConnect(serverOrigin),
|
|
806
|
-
// Rebind the FULL session handler on every (re)connect; the server drives
|
|
807
|
-
// lease reconciliation from our sessions-report (protocol v2).
|
|
808
|
-
onConnected: (socket) => { _bindSessionHandler(socket); },
|
|
809
|
-
// On a REAL disconnect stop accepting remote commands. Durable leases are
|
|
810
|
-
// server-owned and are NOT released locally — the server reconciles them
|
|
811
|
-
// after we reconnect.
|
|
812
|
-
onDisconnected: () => { try { markDisconnected(); } catch { } },
|
|
813
|
-
// Auth/identity rejection: stay running and retry conservatively. NEVER
|
|
814
|
-
// delete the credential or mint a new identity here.
|
|
815
|
-
onAuthRejected: () => { try { console.error('[broker] authentication/identity rejected; identity preserved, retrying conservatively'); } catch { } },
|
|
816
|
-
log: (m) => { try { console.log(m); } catch { } },
|
|
817
|
-
});
|
|
818
|
-
console.log(`Broker connecting to ${serverOrigin} ...`);
|
|
819
|
-
Promise.resolve(supervisor.start()).catch(() => {});
|
|
820
|
-
|
|
821
|
-
async function shutdown(signal) {
|
|
822
|
-
console.log(`\n${signal} received. Broker shutting down...`);
|
|
823
|
-
// Stop reconnecting FIRST so no retry can start after shutdown begins.
|
|
824
|
-
try { supervisor.stop(); } catch { }
|
|
825
|
-
try { await channel.call('shutdown', {}, 5000); } catch { }
|
|
826
|
-
try { if (worker) worker.kill(); } catch { }
|
|
827
|
-
try { channel.close(); } catch { }
|
|
828
|
-
try { await closeAllSessions(); } catch { }
|
|
829
|
-
machineLock.releaseMachineBrokerLock();
|
|
830
|
-
process.exit(0);
|
|
831
|
-
}
|
|
832
|
-
process.on('SIGINT', () => shutdown('Ctrl+C'));
|
|
833
|
-
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
834
|
-
}
|
|
835
|
-
|
|
836
|
-
/** The currently ACTIVE Windows console session id, via the compiled launcher's
|
|
837
|
-
* `-Query` mode. Returns -1 when it cannot be determined (fail-safe). */
|
|
838
|
-
function _activeConsoleSession() {
|
|
839
|
-
try {
|
|
840
|
-
const path = require('path');
|
|
841
|
-
const fs = require('fs');
|
|
842
|
-
const { execFileSync } = require('child_process');
|
|
843
|
-
const machineRoot = require('./machineState').getMachineRoot();
|
|
844
|
-
const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
|
|
845
|
-
if (os.platform() !== 'win32' || !fs.existsSync(launcherExe)) return -1;
|
|
846
|
-
const out = execFileSync(launcherExe, ['-Query'], { encoding: 'utf8', windowsHide: true, timeout: 5000 }).trim();
|
|
847
|
-
const m = /SESSION=(-?\d+)/.exec(out);
|
|
848
|
-
return m ? parseInt(m[1], 10) : -1;
|
|
849
|
-
} catch { return -1; }
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
/** Spawn an interactive browser worker into the ACTIVE INTERACTIVE session.
|
|
853
|
-
*
|
|
854
|
-
* The broker runs as a Session-0 service, which has no desktop. A plain
|
|
855
|
-
* child_process.spawn would create the worker (and its Chromium) in Session 0,
|
|
856
|
-
* where no browser can be shown. When the broker is in Session 0 we therefore
|
|
857
|
-
* launch the worker via the compiled session launcher (CreateProcessAsUser with
|
|
858
|
-
* the active console session's user token). When the broker already runs in an
|
|
859
|
-
* interactive session (foreground `start`), a direct spawn is equivalent.
|
|
860
|
-
*
|
|
861
|
-
* Returns { child, session } where `session` is the Windows session the worker
|
|
862
|
-
* was launched into (or -1 when unknown). The broker records this so it never
|
|
863
|
-
* reuses a worker from a session that is no longer the active console session.
|
|
864
|
-
*/
|
|
865
|
-
function _spawnInteractiveWorker({ port, token }) {
|
|
866
|
-
const { spawn } = require('child_process');
|
|
867
|
-
const path = require('path');
|
|
868
|
-
const fs = require('fs');
|
|
869
|
-
const workerScript = path.join(__dirname, 'worker.js');
|
|
870
|
-
const workerArgs = ['--port', String(port), '--token', token];
|
|
871
|
-
|
|
872
|
-
const machineRoot = require('./machineState').getMachineRoot();
|
|
873
|
-
const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
|
|
874
|
-
|
|
875
|
-
if (os.platform() === 'win32' && fs.existsSync(launcherExe)) {
|
|
876
|
-
// Launch into the active interactive session. The launcher prints
|
|
877
|
-
// `LAUNCHED pid=N session=S`; capture it so the worker is session-bound.
|
|
878
|
-
const logDir = path.join(machineRoot, 'logs');
|
|
879
|
-
try { fs.mkdirSync(logDir, { recursive: true }); } catch { }
|
|
880
|
-
const outLog = path.join(logDir, 'worker.out.log');
|
|
881
|
-
const errLog = path.join(logDir, 'worker.err.log');
|
|
882
|
-
const child = spawn(launcherExe, [
|
|
883
|
-
'-Exe', process.execPath,
|
|
884
|
-
'-Args', '"' + workerScript + '" ' + workerArgs.join(' '),
|
|
885
|
-
'-Cwd', __dirname,
|
|
886
|
-
'-Out', outLog,
|
|
887
|
-
'-Err', errLog,
|
|
888
|
-
], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
889
|
-
let session = -1;
|
|
890
|
-
let buf = '';
|
|
891
|
-
try {
|
|
892
|
-
child.stdout.on('data', (d) => {
|
|
893
|
-
buf += d.toString();
|
|
894
|
-
const m = /session=(-?\d+)/.exec(buf);
|
|
895
|
-
if (m) session = parseInt(m[1], 10);
|
|
896
|
-
});
|
|
897
|
-
} catch { }
|
|
898
|
-
return { child, get session() { return session; } };
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
// Interactive/foreground fallback: the broker is already in the right session.
|
|
902
|
-
const child = spawn(process.execPath, [workerScript, ...workerArgs], {
|
|
903
|
-
detached: false,
|
|
904
|
-
stdio: ['ignore', 'inherit', 'inherit'],
|
|
905
|
-
windowsHide: true,
|
|
906
|
-
});
|
|
907
|
-
return { child, session: _activeConsoleSession() };
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
/** Connect the broker's WebSocket using the machine credential. */
|
|
911
|
-
async function _brokerConnect(serverOrigin) {
|
|
912
|
-
const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
|
|
913
|
-
const deviceMeta = getStoredDevice({ serverOrigin });
|
|
914
|
-
const privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
915
|
-
if (!deviceMeta || !privateKeyB64Url) {
|
|
916
|
-
throw new Error('device is not enrolled; run `xkwd-agent start` once to authorize this machine');
|
|
917
|
-
}
|
|
918
|
-
const { connectWebSocket } = require('./wsClient');
|
|
919
|
-
return connectWebSocket({
|
|
920
|
-
serverOrigin,
|
|
921
|
-
deviceId: deviceMeta.deviceId,
|
|
922
|
-
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
923
|
-
privateKeyB64Url,
|
|
924
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
925
|
-
});
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
/**
|
|
929
|
-
* `xkwd-agent doctor` — diagnostic checks.
|
|
930
|
-
*/
|
|
931
|
-
async function doctor(serverOrigin) {
|
|
932
|
-
console.log(`XKWDStore Agent v${CLI_VERSION} — Diagnostics\n`);
|
|
933
|
-
|
|
934
|
-
// Check Node version
|
|
935
|
-
const nodeVersion = process.versions.node;
|
|
936
|
-
const major = parseInt(nodeVersion.split('.')[0], 10);
|
|
937
|
-
console.log(`Node.js: ${nodeVersion} ${major >= 22 ? '✓' : '✗ (requires Node.js 22+)'}`);
|
|
938
|
-
|
|
939
|
-
// Check platform
|
|
940
|
-
console.log(`Platform: ${os.platform()} ${os.arch()}`);
|
|
941
|
-
console.log(`Hostname: ${os.hostname()}`);
|
|
942
|
-
|
|
943
|
-
// Check Chrome
|
|
944
|
-
try {
|
|
945
|
-
const { resolveChromeOrFail } = require('./chromeDetector');
|
|
946
|
-
const chrome = resolveChromeOrFail();
|
|
947
|
-
console.log(`Chrome: ${chrome.chromeVersion || 'detected'} ✓`);
|
|
948
|
-
} catch (e) {
|
|
949
|
-
console.log(`Chrome: ✗ (${e.message.split('\n')[0]})`);
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
// Check secure storage (real DPAPI + ACL probe on Windows)
|
|
953
|
-
const { isSecureStorageAvailable, getDataDir, probeWindowsStorage } = require('./deviceKeyStore');
|
|
954
|
-
const platform = os.platform();
|
|
955
|
-
if (platform === 'win32') {
|
|
956
|
-
console.log('Secure storage: probing real DPAPI + ACL stages...');
|
|
957
|
-
const probe = probeWindowsStorage();
|
|
958
|
-
console.log(` DPAPI Protect : ${probe.stages.protect ? '✓' : '✗'}`);
|
|
959
|
-
console.log(` DPAPI Unprotect: ${probe.stages.unprotect ? '✓' : '✗'}`);
|
|
960
|
-
console.log(` Windows SID : ${probe.stages.sidLookup ? '✓' : '✗'}`);
|
|
961
|
-
console.log(` ACL apply : ${probe.stages.aclApply ? '✓' : '✗'}`);
|
|
962
|
-
console.log(` ACL verify : ${probe.stages.aclVerify ? '✓' : '✗'}`);
|
|
963
|
-
console.log(`Secure storage: ${probe.ok ? 'available ✓' : 'unavailable ✗'}`);
|
|
964
|
-
if (!probe.ok && probe.detail) {
|
|
965
|
-
console.log(` Detail: ${probe.detail}`);
|
|
966
|
-
}
|
|
967
|
-
} else {
|
|
968
|
-
console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available ✓' : 'unavailable ✗'}`);
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
// Check data directory (machine-wide since 2.1.0)
|
|
972
|
-
const dataDir = getDataDir();
|
|
973
|
-
const legacyDir = require('./deviceKeyStore').getLegacyDataDir();
|
|
974
|
-
console.log(`Machine state root: ${dataDir}`);
|
|
975
|
-
console.log(`Legacy per-user root: ${legacyDir}`);
|
|
976
|
-
const machineState = require('./machineState');
|
|
977
|
-
console.log(`Machine identity present: ${machineState.hasMachineIdentity() ? '✓' : '(none yet)'}`);
|
|
978
|
-
|
|
979
|
-
// Check device identity (server-scoped)
|
|
980
|
-
const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
|
|
981
|
-
const device = getStoredDevice({ serverOrigin });
|
|
982
|
-
if (device) {
|
|
983
|
-
console.log(`Device ID: ${device.deviceId} ✓`);
|
|
984
|
-
const privateKey = await getStoredPrivateKey({ serverOrigin });
|
|
985
|
-
console.log(`Private key: ${privateKey ? 'stored ✓' : 'missing ✗'}`);
|
|
986
|
-
} else {
|
|
987
|
-
console.log('Device ID: not enrolled for this server');
|
|
988
|
-
}
|
|
989
|
-
|
|
990
|
-
// Check server connectivity (shared strict validator)
|
|
991
|
-
try {
|
|
992
|
-
const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
|
|
993
|
-
const resp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
|
|
994
|
-
const compat = validateCompatibilityResponse(resp);
|
|
995
|
-
if (compat.html) {
|
|
996
|
-
console.log(`Server (${serverOrigin}): compatibility endpoint returned frontend ✗`);
|
|
997
|
-
console.log(' ' + COMPAT_HTML_MESSAGE);
|
|
998
|
-
} else if (compat.ok) {
|
|
999
|
-
console.log(`Server (${serverOrigin}): reachable ✓`);
|
|
1000
|
-
console.log(` Protocol version: ${compat.body.protocolVersion}`);
|
|
1001
|
-
console.log(` Min agent version: ${compat.body.minimumAgentVersion}`);
|
|
1002
|
-
console.log(` Recommended agent version: ${compat.body.recommendedAgentVersion}`);
|
|
1003
|
-
} else {
|
|
1004
|
-
console.log(`Server (${serverOrigin}): compatibility check failed ✗`);
|
|
1005
|
-
console.log(` Reason: ${compat.reason}`);
|
|
1006
|
-
}
|
|
1007
|
-
} catch (e) {
|
|
1008
|
-
console.log(`Server (${serverOrigin}): unreachable ✗ (${e.message})`);
|
|
1009
|
-
}
|
|
1010
|
-
}
|
|
1011
|
-
|
|
1012
|
-
/**
|
|
1013
|
-
* `xkwd-agent version` — print version.
|
|
1014
|
-
*/
|
|
1015
|
-
function version() {
|
|
1016
|
-
console.log(`@xkwdstore/agent v${CLI_VERSION}`);
|
|
1017
|
-
console.log(`Protocol version: ${PROTOCOL_VERSION}`);
|
|
1018
|
-
console.log(`Node.js: ${process.versions.node}`);
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
/**
|
|
1022
|
-
* `xkwd-agent help` — print help.
|
|
1023
|
-
*/
|
|
1024
|
-
function help() {
|
|
1025
|
-
console.log(`XKWDStore Agent v${CLI_VERSION}
|
|
1026
|
-
|
|
1027
|
-
Usage:
|
|
1028
|
-
xkwd-agent <command> [options]
|
|
1029
|
-
|
|
1030
|
-
Commands:
|
|
1031
|
-
start Start the agent (connects to server, runs browser sessions)
|
|
1032
|
-
status Show device and connection status
|
|
1033
|
-
logout Delete local device identity (requires re-authorization)
|
|
1034
|
-
revoke-local Delete local device identity and credentials
|
|
1035
|
-
machine Machine-wide state: status | adopt | harden
|
|
1036
|
-
service Run the machine-wide broker (Windows Service host; silent)
|
|
1037
|
-
doctor Run diagnostic checks
|
|
1038
|
-
version Print version information
|
|
1039
|
-
help Show this help
|
|
1040
|
-
|
|
1041
|
-
Options:
|
|
1042
|
-
--server=<url> Server URL (default: https://x.kwdstore.com)
|
|
1043
|
-
--replace Replace a running instance (safe takeover)
|
|
1044
|
-
|
|
1045
|
-
Examples:
|
|
1046
|
-
xkwd-agent start
|
|
1047
|
-
xkwd-agent start --replace
|
|
1048
|
-
xkwd-agent status
|
|
1049
|
-
xkwd-agent machine status
|
|
1050
|
-
xkwd-agent doctor
|
|
1051
|
-
|
|
1052
|
-
First run:
|
|
1053
|
-
The agent will open your browser to authorize this computer.
|
|
1054
|
-
No pairing code, email, or API key is required.
|
|
1055
|
-
|
|
1056
|
-
To stop:
|
|
1057
|
-
Press Ctrl+C in the terminal.
|
|
1058
|
-
|
|
1059
|
-
Data location (machine-wide, shared by every Windows user on this PC):
|
|
1060
|
-
Windows: %ProgramData%\\XKWDStore\\Agent\\
|
|
1061
|
-
Linux: ${'{XDG_DATA_HOME:-~/.local/share}/xkwdstore/'}
|
|
1062
|
-
macOS: unsupported (fails closed)
|
|
1063
|
-
|
|
1064
|
-
Device identity belongs to the MACHINE. Changing the Windows user or the
|
|
1065
|
-
TW-manager preferred device does NOT create a second device identity.
|
|
1066
|
-
A pre-2.1.0 per-user install is adopted once (copy, never move).
|
|
1067
|
-
|
|
1068
|
-
Requirements:
|
|
1069
|
-
- Node.js 22 or later
|
|
1070
|
-
- Google Chrome installed
|
|
1071
|
-
`);
|
|
1072
|
-
}
|
|
1073
|
-
|
|
1074
|
-
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
1075
|
-
|
|
1076
|
-
/**
|
|
1077
|
-
* Detect whether a connection error is a 4003 authentication failure.
|
|
1078
|
-
* The wsClient rejects with a message containing "Device authentication
|
|
1079
|
-
* failed" when the server closes with code 4003. The error may also carry
|
|
1080
|
-
* a .code property in some implementations.
|
|
1081
|
-
*/
|
|
1082
|
-
function _is4003Error(err) {
|
|
1083
|
-
if (!err) return false;
|
|
1084
|
-
const msg = (err.message || String(err)).toLowerCase();
|
|
1085
|
-
if (err.code === 4003) return true;
|
|
1086
|
-
if (msg.includes('device authentication failed')) return true;
|
|
1087
|
-
if (msg.includes('4003')) return true;
|
|
1088
|
-
return false;
|
|
1089
|
-
}
|
|
1090
|
-
|
|
1091
|
-
function _compareVersions(a, b) {
|
|
1092
|
-
const pa = a.split('.').map(Number);
|
|
1093
|
-
const pb = b.split('.').map(Number);
|
|
1094
|
-
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
1095
|
-
const va = pa[i] || 0;
|
|
1096
|
-
const vb = pb[i] || 0;
|
|
1097
|
-
if (va > vb) return 1;
|
|
1098
|
-
if (va < vb) return -1;
|
|
1099
|
-
}
|
|
1100
|
-
return 0;
|
|
1101
|
-
}
|
|
1102
|
-
|
|
1103
|
-
// ── Entry point ──────────────────────────────────────────────────────────────
|
|
1104
|
-
|
|
1105
|
-
if (require.main === module) {
|
|
1106
|
-
main();
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* XKWDStore Agent — Terminal-only CLI (protocol v2).
|
|
6
|
+
*
|
|
7
|
+
* Replaces the desktop-agent distribution, pairing-code workflow, updater,
|
|
8
|
+
* and in-memory WebSocket ticket architecture with a simpler, safer
|
|
9
|
+
* terminal-first system.
|
|
10
|
+
*
|
|
11
|
+
* Usage:
|
|
12
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> start
|
|
13
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> status
|
|
14
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
|
|
15
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
|
|
16
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
|
|
17
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> version
|
|
18
|
+
*
|
|
19
|
+
* The agent runs only while the terminal process is running.
|
|
20
|
+
* Closing the terminal or pressing Ctrl+C stops the agent cleanly.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const crypto = require('crypto');
|
|
24
|
+
const os = require('os');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
|
|
27
|
+
const CLI_VERSION = '2.1.3';
|
|
28
|
+
const PROTOCOL_VERSION = 2;
|
|
29
|
+
|
|
30
|
+
// ── Command parsing ──────────────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
function main() {
|
|
33
|
+
const args = process.argv.slice(2);
|
|
34
|
+
const command = args[0] || 'help';
|
|
35
|
+
const flags = {};
|
|
36
|
+
const positional = [];
|
|
37
|
+
|
|
38
|
+
for (let i = 1; i < args.length; i++) {
|
|
39
|
+
const arg = args[i];
|
|
40
|
+
if (arg.startsWith('--')) {
|
|
41
|
+
const key = arg.slice(2);
|
|
42
|
+
const next = args[i + 1];
|
|
43
|
+
if (next && !next.startsWith('--')) {
|
|
44
|
+
flags[key] = next;
|
|
45
|
+
i++;
|
|
46
|
+
} else {
|
|
47
|
+
flags[key] = true;
|
|
48
|
+
}
|
|
49
|
+
} else {
|
|
50
|
+
positional.push(arg);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const serverOrigin = flags.server ||
|
|
55
|
+
process.env.XKWDSTORE_SERVER ||
|
|
56
|
+
'https://x.kwdstore.com';
|
|
57
|
+
|
|
58
|
+
switch (command) {
|
|
59
|
+
case 'start':
|
|
60
|
+
return start(serverOrigin, flags);
|
|
61
|
+
case 'status':
|
|
62
|
+
return status();
|
|
63
|
+
case 'logout':
|
|
64
|
+
return logout();
|
|
65
|
+
case 'revoke-local':
|
|
66
|
+
return revokeLocal();
|
|
67
|
+
case 'doctor':
|
|
68
|
+
return doctor(serverOrigin);
|
|
69
|
+
case 'machine':
|
|
70
|
+
return machine(positional);
|
|
71
|
+
case 'service':
|
|
72
|
+
return service(serverOrigin, flags);
|
|
73
|
+
case 'key-probe': {
|
|
74
|
+
// Diagnostics: report whether the machine credential can be decrypted in
|
|
75
|
+
// THIS process context (e.g. from the LocalSystem service) WITHOUT
|
|
76
|
+
// printing any secret. Used by the elevated lifecycle gate.
|
|
77
|
+
(async () => {
|
|
78
|
+
const fs = require('fs');
|
|
79
|
+
const path = require('path');
|
|
80
|
+
const { loadMetadata, loadPrivateKeyFromStorage, getMachineRoot, _identitySourceRoots, _serversDirFor } = require('./deviceKeyStore');
|
|
81
|
+
const { normalizeServerOrigin } = require('./deviceKeyStore');
|
|
82
|
+
const meta = loadMetadata({ serverOrigin });
|
|
83
|
+
const out = {
|
|
84
|
+
context: { user: require('os').userInfo().username, platform: os.platform(), pid: process.pid },
|
|
85
|
+
machineRoot: getMachineRoot(),
|
|
86
|
+
deviceId: meta ? meta.deviceId : null,
|
|
87
|
+
privateKeyDecryptable: false,
|
|
88
|
+
stages: {},
|
|
89
|
+
error: '',
|
|
90
|
+
};
|
|
91
|
+
// Stage 1: locate the key file the loader would use.
|
|
92
|
+
let keyFile = null;
|
|
93
|
+
try {
|
|
94
|
+
const roots = _identitySourceRoots();
|
|
95
|
+
const label = normalizeServerOrigin(serverOrigin);
|
|
96
|
+
const candidates = [];
|
|
97
|
+
for (const r of [roots.source, roots.target]) {
|
|
98
|
+
if (r) candidates.push(path.join(_serversDirFor(r), label, '.device-key'));
|
|
99
|
+
}
|
|
100
|
+
for (const r of [roots.source, roots.target]) { if (r) candidates.push(path.join(r, '.device-key')); }
|
|
101
|
+
out.stages.candidates = candidates;
|
|
102
|
+
for (const c of candidates) { if (fs.existsSync(c)) { keyFile = c; break; } }
|
|
103
|
+
out.stages.keyFile = keyFile;
|
|
104
|
+
out.stages.keyReadable = keyFile ? (() => { try { fs.accessSync(keyFile, fs.constants.R_OK); return true; } catch { return false; } })() : false;
|
|
105
|
+
if (keyFile) {
|
|
106
|
+
try {
|
|
107
|
+
const env = JSON.parse(fs.readFileSync(keyFile, 'utf8'));
|
|
108
|
+
out.stages.envelopeScheme = env.scheme;
|
|
109
|
+
out.stages.envelopeScope = env.scope || '(v1/unscoped)';
|
|
110
|
+
out.stages.envelopeV = env.v;
|
|
111
|
+
} catch (e) { out.stages.envelopeError = (e && e.message) || 'parse'; }
|
|
112
|
+
}
|
|
113
|
+
} catch (e) { out.stages.locateError = (e && e.message) || 'locate'; }
|
|
114
|
+
// Stage 2: full loader (includes ACL verify).
|
|
115
|
+
try { out.privateKeyDecryptable = !!(await loadPrivateKeyFromStorage({ serverOrigin })); } catch (e) { out.error = (e && e.message) || 'error'; }
|
|
116
|
+
console.log(JSON.stringify(out));
|
|
117
|
+
})().catch((e) => { console.error(JSON.stringify({ error: (e && e.message) || 'fatal' })); process.exit(1); });
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
case 'version':
|
|
121
|
+
return version();
|
|
122
|
+
case 'help':
|
|
123
|
+
case '--help':
|
|
124
|
+
case '-h':
|
|
125
|
+
default:
|
|
126
|
+
return help();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ── Commands ─────────────────────────────────────────────────────────────────
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* `xkwd-agent start` — the main runtime command.
|
|
134
|
+
*/
|
|
135
|
+
async function start(serverOrigin, flags) {
|
|
136
|
+
console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
|
|
137
|
+
console.log(`Server: ${serverOrigin}`);
|
|
138
|
+
|
|
139
|
+
// 0. Machine-wide state: create the ProgramData layout and adopt any
|
|
140
|
+
// pre-2.1.0 per-user identity ONCE (copy, never move). The device identity
|
|
141
|
+
// therefore belongs to the MACHINE, not to the current Windows user.
|
|
142
|
+
try {
|
|
143
|
+
const machineState = require('./machineState');
|
|
144
|
+
const init = machineState.initializeMachineState();
|
|
145
|
+
console.log(`✓ Machine state: ${init.root}`);
|
|
146
|
+
if (init.adopted && init.deviceId) {
|
|
147
|
+
console.log(`✓ Adopted existing device identity: ${init.deviceId}`);
|
|
148
|
+
}
|
|
149
|
+
} catch (e) {
|
|
150
|
+
console.error(`Machine state initialization failed: ${(e && e.message) || 'unknown'}`);
|
|
151
|
+
process.exit(1);
|
|
152
|
+
}
|
|
153
|
+
console.log();
|
|
154
|
+
|
|
155
|
+
// 1. Detect OS and architecture (for display)
|
|
156
|
+
const platform = os.platform();
|
|
157
|
+
const arch = os.arch();
|
|
158
|
+
const hostname = os.hostname();
|
|
159
|
+
console.log(`✓ Detected computer: ${hostname}`);
|
|
160
|
+
console.log(`✓ Platform: ${platform} ${arch}`);
|
|
161
|
+
|
|
162
|
+
// 2. Resolve system Chrome (fail clearly if missing)
|
|
163
|
+
const { resolveChromeOrFail } = require('./chromeDetector');
|
|
164
|
+
let chromePath, chromeVersion;
|
|
165
|
+
try {
|
|
166
|
+
const chrome = resolveChromeOrFail();
|
|
167
|
+
chromePath = chrome.chromePath;
|
|
168
|
+
chromeVersion = chrome.chromeVersion;
|
|
169
|
+
console.log(`✓ Chrome ${chromeVersion || 'detected'}: ${chromePath}`);
|
|
170
|
+
} catch (e) {
|
|
171
|
+
console.error(e.message);
|
|
172
|
+
process.exit(1);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// 3. Check compatibility with server (shared strict validator)
|
|
176
|
+
const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
|
|
177
|
+
try {
|
|
178
|
+
const compatResp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
|
|
179
|
+
const compat = validateCompatibilityResponse(compatResp);
|
|
180
|
+
if (compat.html) {
|
|
181
|
+
console.error('\n' + COMPAT_HTML_MESSAGE);
|
|
182
|
+
process.exit(1);
|
|
183
|
+
}
|
|
184
|
+
if (!compat.ok) {
|
|
185
|
+
console.error('\nServer compatibility check failed: ' + compat.reason + '.');
|
|
186
|
+
console.error('The agent will not start enrollment until the server is compatible.');
|
|
187
|
+
process.exit(1);
|
|
188
|
+
}
|
|
189
|
+
// NOTE: the server's declared `capabilities` are INFORMATIONAL. They are
|
|
190
|
+
// never a reason to refuse a server — a server that does not advertise the
|
|
191
|
+
// profile-identity capability may still supply the identity tuple, and every
|
|
192
|
+
// currently-deployed backend omits the field. A missing capability must not
|
|
193
|
+
// block startup (see validateCompatibilityResponse).
|
|
194
|
+
// compat.ok — enforce minimum agent version
|
|
195
|
+
const minVer = compat.body.minimumAgentVersion;
|
|
196
|
+
const recVer = compat.body.recommendedAgentVersion;
|
|
197
|
+
if (minVer && _compareVersions(CLI_VERSION, minVer) < 0) {
|
|
198
|
+
console.error(`\nThis agent version (${CLI_VERSION}) is no longer supported.`);
|
|
199
|
+
console.error(`\nRun:\n\n npx --yes @xkwdstore/agent@${recVer} start\n`);
|
|
200
|
+
process.exit(1);
|
|
201
|
+
}
|
|
202
|
+
} catch (e) {
|
|
203
|
+
console.error(`\nServer compatibility check failed: ${e.message}`);
|
|
204
|
+
console.error('The agent will not start enrollment until the server is reachable and compatible.');
|
|
205
|
+
process.exit(1);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// 4. Load or generate device key (server-scoped: per-server identity)
|
|
209
|
+
const { getStoredDevice, getStoredPrivateKey, enroll } = require('./enrollmentClient');
|
|
210
|
+
const { isSecureStorageAvailable } = require('./deviceKeyStore');
|
|
211
|
+
|
|
212
|
+
if (!isSecureStorageAvailable()) {
|
|
213
|
+
console.error('Secure key storage is unavailable on this system.');
|
|
214
|
+
if (os.platform() === 'win32') {
|
|
215
|
+
console.error('On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available.');
|
|
216
|
+
} else {
|
|
217
|
+
console.error('On Linux, install gnome-keyring or seahorse (libsecret).');
|
|
218
|
+
}
|
|
219
|
+
console.error('The agent cannot run without secure key storage.');
|
|
220
|
+
process.exit(1);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let deviceMeta = getStoredDevice({ serverOrigin });
|
|
224
|
+
let privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
225
|
+
|
|
226
|
+
// 5. Authorize the device when needed (first run or revoked)
|
|
227
|
+
if (!deviceMeta || !privateKeyB64Url) {
|
|
228
|
+
console.log('\n✓ Device identity loaded securely');
|
|
229
|
+
try {
|
|
230
|
+
const result = await enroll(serverOrigin, { chromePath });
|
|
231
|
+
deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
|
|
232
|
+
privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
233
|
+
} catch (e) {
|
|
234
|
+
console.error(`\nEnrollment failed: ${e.message}`);
|
|
235
|
+
process.exit(1);
|
|
236
|
+
}
|
|
237
|
+
} else {
|
|
238
|
+
console.log(`✓ Device identity loaded securely`);
|
|
239
|
+
console.log(`✓ Device recognized: ${deviceMeta.deviceName}`);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 6. Process lock (prevent duplicate instances)
|
|
243
|
+
const processLock = require('./processLock');
|
|
244
|
+
const lockResult = processLock.acquireLock({
|
|
245
|
+
deviceId: deviceMeta.deviceId,
|
|
246
|
+
deviceName: deviceMeta.deviceName,
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
if (!lockResult.acquired) {
|
|
250
|
+
if (flags.replace) {
|
|
251
|
+
console.log('\nAnother agent instance is running. Requesting takeover...');
|
|
252
|
+
const took = await processLock.requestTakeover(lockResult.existing);
|
|
253
|
+
if (!took) {
|
|
254
|
+
console.error('Could not stop the existing instance. Please close it manually.');
|
|
255
|
+
process.exit(1);
|
|
256
|
+
}
|
|
257
|
+
// Re-acquire the lock
|
|
258
|
+
const retryLock = processLock.acquireLock({
|
|
259
|
+
deviceId: deviceMeta.deviceId,
|
|
260
|
+
deviceName: deviceMeta.deviceName,
|
|
261
|
+
});
|
|
262
|
+
if (!retryLock.acquired) {
|
|
263
|
+
console.error('Could not acquire process lock after takeover.');
|
|
264
|
+
process.exit(1);
|
|
265
|
+
}
|
|
266
|
+
} else {
|
|
267
|
+
console.error('\nXKWDStore Agent is already running on this computer.');
|
|
268
|
+
console.error(`PID: ${lockResult.existing.pid}`);
|
|
269
|
+
console.error(`Started: ${lockResult.existing.startedAt}`);
|
|
270
|
+
console.error(`Device: ${lockResult.existing.deviceName || 'unknown'}`);
|
|
271
|
+
console.error('\nTo replace the running instance, use:');
|
|
272
|
+
console.error(' xkwd-agent start --replace');
|
|
273
|
+
process.exit(1);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// 7. Connect securely via WebSocket challenge-response
|
|
278
|
+
// 4003 auto-recovery: if the initial connection fails with 4003 (revoked/
|
|
279
|
+
// unknown device), the agent automatically performs a server-scoped
|
|
280
|
+
// re-enrollment and reconnects in the SAME process flow — the user does
|
|
281
|
+
// NOT need to type a second command. Only ONE auto-recovery attempt is
|
|
282
|
+
// allowed per startup to prevent infinite loops.
|
|
283
|
+
const { connectWebSocket } = require('./wsClient');
|
|
284
|
+
let ws;
|
|
285
|
+
let autoRecovered = false;
|
|
286
|
+
|
|
287
|
+
try {
|
|
288
|
+
ws = await connectWebSocket({
|
|
289
|
+
serverOrigin,
|
|
290
|
+
deviceId: deviceMeta.deviceId,
|
|
291
|
+
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
292
|
+
privateKeyB64Url,
|
|
293
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
294
|
+
});
|
|
295
|
+
} catch (connectErr) {
|
|
296
|
+
// Check if this is a 4003 authentication failure (revoked/unknown device).
|
|
297
|
+
// The wsClient rejects with a message containing "Device authentication
|
|
298
|
+
// failed" for 4003 close codes, or the error may carry a .code property.
|
|
299
|
+
const isAuthFailure = _is4003Error(connectErr);
|
|
300
|
+
|
|
301
|
+
if (isAuthFailure && !autoRecovered) {
|
|
302
|
+
autoRecovered = true;
|
|
303
|
+
console.error('\n❌ Authentication failed (4003) — this device may be revoked.');
|
|
304
|
+
console.error(' Automatically re-authorizing for ' + serverOrigin + '...');
|
|
305
|
+
console.error(' (Other servers\' identities are NOT affected.)');
|
|
306
|
+
|
|
307
|
+
// Release the lock before re-enrollment (enrollment opens a browser)
|
|
308
|
+
processLock.releaseLock();
|
|
309
|
+
|
|
310
|
+
// Delete only this server's identity
|
|
311
|
+
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
312
|
+
await deletePrivateKey({ serverOrigin });
|
|
313
|
+
deleteMetadata({ serverOrigin });
|
|
314
|
+
console.error('✓ Old identity cleared for ' + serverOrigin);
|
|
315
|
+
|
|
316
|
+
// Re-enroll automatically (opens browser for approval)
|
|
317
|
+
console.log('\nOpening authorization page...');
|
|
318
|
+
try {
|
|
319
|
+
await enroll(serverOrigin, { chromePath });
|
|
320
|
+
deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
|
|
321
|
+
privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
322
|
+
|
|
323
|
+
if (!deviceMeta || !privateKeyB64Url) {
|
|
324
|
+
console.error('\n❌ Re-enrollment completed but identity could not be loaded.');
|
|
325
|
+
process.exit(1);
|
|
326
|
+
}
|
|
327
|
+
console.log('✓ New identity stored for ' + serverOrigin);
|
|
328
|
+
} catch (enrollErr) {
|
|
329
|
+
console.error(`\n❌ Automatic re-enrollment failed: ${enrollErr.message}`);
|
|
330
|
+
console.error(' Run `xkwd-agent start` again to retry manually.');
|
|
331
|
+
process.exit(1);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Re-acquire the process lock with the new device identity
|
|
335
|
+
const retryLock = processLock.acquireLock({
|
|
336
|
+
deviceId: deviceMeta.deviceId,
|
|
337
|
+
deviceName: deviceMeta.deviceName,
|
|
338
|
+
});
|
|
339
|
+
if (!retryLock.acquired) {
|
|
340
|
+
console.error('Could not acquire process lock after re-enrollment.');
|
|
341
|
+
if (flags.replace) {
|
|
342
|
+
const took = await processLock.requestTakeover(retryLock.existing);
|
|
343
|
+
if (!took) {
|
|
344
|
+
console.error('Could not stop the existing instance. Please close it manually.');
|
|
345
|
+
process.exit(1);
|
|
346
|
+
}
|
|
347
|
+
} else {
|
|
348
|
+
process.exit(1);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Attempt to reconnect with the new identity (only ONE retry)
|
|
353
|
+
try {
|
|
354
|
+
ws = await connectWebSocket({
|
|
355
|
+
serverOrigin,
|
|
356
|
+
deviceId: deviceMeta.deviceId,
|
|
357
|
+
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
358
|
+
privateKeyB64Url,
|
|
359
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
360
|
+
});
|
|
361
|
+
console.log('\n✓ Re-authorized and reconnected automatically.');
|
|
362
|
+
} catch (retryErr) {
|
|
363
|
+
if (_is4003Error(retryErr)) {
|
|
364
|
+
console.error('\n❌ Authentication failed again after re-enrollment.');
|
|
365
|
+
console.error(' The new device may not have been approved on the dashboard.');
|
|
366
|
+
console.error(' Run `xkwd-agent start` again after approving the device.');
|
|
367
|
+
} else {
|
|
368
|
+
console.error(`\n❌ Reconnection failed: ${retryErr.message}`);
|
|
369
|
+
console.error(' Run `xkwd-agent start` again to retry.');
|
|
370
|
+
}
|
|
371
|
+
processLock.releaseLock();
|
|
372
|
+
process.exit(1);
|
|
373
|
+
}
|
|
374
|
+
} else {
|
|
375
|
+
// Non-4003 error, or 4003 after auto-recovery already attempted
|
|
376
|
+
console.error(`\nConnection failed: ${connectErr.message}`);
|
|
377
|
+
if (isAuthFailure) {
|
|
378
|
+
console.error(' Automatic recovery was already attempted. Run `xkwd-agent start` again.');
|
|
379
|
+
}
|
|
380
|
+
processLock.releaseLock();
|
|
381
|
+
process.exit(1);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
console.log('✓ Secure challenge passed');
|
|
386
|
+
console.log('✓ Connected');
|
|
387
|
+
console.log('\nAgent is running. Press Ctrl+C to stop.\n');
|
|
388
|
+
|
|
389
|
+
// Keep SQLite-style registry state honest: the handler owns session
|
|
390
|
+
// registration; ensure the machine runtime dir exists before the first launch.
|
|
391
|
+
try {
|
|
392
|
+
const ms = require('./machineState');
|
|
393
|
+
ms.ensureMachineLayout();
|
|
394
|
+
} catch { /* best-effort */ }
|
|
395
|
+
|
|
396
|
+
// 8. Set up browser session handler (delegates to existing session management)
|
|
397
|
+
const { setupSessionHandler, closeAllSessions, markDisconnected, recoverOrphanedSessions } = require('./sessionHandler');
|
|
398
|
+
|
|
399
|
+
// 2.1.0 F1: crash recovery. A previous agent process may have left an
|
|
400
|
+
// Agent-OWNED Chromium behind (it is alive but unmanaged). Release the stale
|
|
401
|
+
// LOCAL locks for those proven-owned sessions so the accounts are not blocked
|
|
402
|
+
// on this device. The SERVER durable lease is authoritative and is NOT touched
|
|
403
|
+
// here — server recovery (recovery-probe / reconcile) still governs it.
|
|
404
|
+
try {
|
|
405
|
+
const recovery = recoverOrphanedSessions();
|
|
406
|
+
if (recovery.orphans > 0) {
|
|
407
|
+
console.log(`ℹ️ Crash recovery: found ${recovery.orphans} Agent-owned orphaned browser(s); released ${recovery.released} local lock(s).`);
|
|
408
|
+
}
|
|
409
|
+
} catch { /* never block startup on recovery */ }
|
|
410
|
+
|
|
411
|
+
const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
|
|
412
|
+
|
|
413
|
+
// 8a. Disconnect handling — the SAME reconnect supervisor as the machine
|
|
414
|
+
// `service` broker. The foreground agent adopts the already-authenticated
|
|
415
|
+
// socket; the supervisor owns every subsequent (re)connect, guaranteeing one
|
|
416
|
+
// timer / one attempt / one live socket, with unbounded self-healing that uses
|
|
417
|
+
// the SAME enrolled identity (transport recovery only, never a new identity).
|
|
418
|
+
//
|
|
419
|
+
// Interactive-path policy preserved:
|
|
420
|
+
// - server-initiated restart (1000 'agent-restart' / 4002 'Server-initiated
|
|
421
|
+
// restart'): rebind WITHOUT touching local browsers — the server reconciles
|
|
422
|
+
// leases from our sessions-report after reconnect.
|
|
423
|
+
// - any OTHER close: mark disconnected + close all browser contexts (profiles
|
|
424
|
+
// persist), then reconnect.
|
|
425
|
+
// - 4003 revoked mid-session: clear THIS server's identity and stop (explicit
|
|
426
|
+
// re-authorization) — the supervisor NEVER regenerates identity.
|
|
427
|
+
const _isRestartClose = (code, reasonStr) =>
|
|
428
|
+
(code === 1000 && /agent-restart/i.test(reasonStr))
|
|
429
|
+
|| (code === 4002 && /server-initiated restart/i.test(reasonStr));
|
|
430
|
+
|
|
431
|
+
const supervisor = createBrokerConnectionSupervisor({
|
|
432
|
+
connect: () => connectWebSocket({
|
|
433
|
+
serverOrigin,
|
|
434
|
+
deviceId: deviceMeta.deviceId,
|
|
435
|
+
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
436
|
+
privateKeyB64Url,
|
|
437
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
438
|
+
}),
|
|
439
|
+
onConnected: (socket) => { setupSessionHandler(socket, { chromePath, deviceMeta, serverOrigin }); },
|
|
440
|
+
onDisconnected: async ({ code, reason }) => {
|
|
441
|
+
const reasonStr = reason || '';
|
|
442
|
+
if (_isRestartClose(code, reasonStr)) {
|
|
443
|
+
console.log('\nℹ️ Server requested a connection restart. Reconnecting (browser sessions stay open)...');
|
|
444
|
+
return; // keep local browsers; the server reconciles leases
|
|
445
|
+
}
|
|
446
|
+
console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
|
|
447
|
+
console.error(' Closing all browser sessions and reconnecting safely...');
|
|
448
|
+
markDisconnected();
|
|
449
|
+
try { await closeAllSessions(); } catch { }
|
|
450
|
+
},
|
|
451
|
+
onAuthRejected: () => {
|
|
452
|
+
// 4003: the credential is dead. Do NOT regenerate identity automatically.
|
|
453
|
+
console.error('\n❌ Authentication failed — this device was revoked.');
|
|
454
|
+
console.error(' Run `xkwd-agent start` again to re-authorize this computer.');
|
|
455
|
+
try {
|
|
456
|
+
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
457
|
+
deletePrivateKey({ serverOrigin });
|
|
458
|
+
deleteMetadata({ serverOrigin });
|
|
459
|
+
} catch { }
|
|
460
|
+
processLock.releaseLock();
|
|
461
|
+
process.exit(1);
|
|
462
|
+
},
|
|
463
|
+
onExhausted: () => {
|
|
464
|
+
console.error('\n❌ Could not reconnect. Run `xkwd-agent start` again.');
|
|
465
|
+
processLock.releaseLock();
|
|
466
|
+
process.exit(1);
|
|
467
|
+
},
|
|
468
|
+
maxAttempts: 10,
|
|
469
|
+
log: (m) => { try { console.log(m); } catch { } },
|
|
470
|
+
});
|
|
471
|
+
supervisor.adopt(ws);
|
|
472
|
+
|
|
473
|
+
// Deliberate-shutdown guard (set before closing anything, so a close emitted
|
|
474
|
+
// during shutdown cannot trigger a reconnect).
|
|
475
|
+
let shuttingDown = false;
|
|
476
|
+
|
|
477
|
+
// 9. Clean shutdown on Ctrl+C
|
|
478
|
+
async function shutdown(signal) {
|
|
479
|
+
if (shuttingDown) return;
|
|
480
|
+
shuttingDown = true;
|
|
481
|
+
console.log(`\n${signal} received. Shutting down...`);
|
|
482
|
+
|
|
483
|
+
// Stop reconnecting FIRST so no retry can start after shutdown begins.
|
|
484
|
+
try { supervisor.stop(); } catch { }
|
|
485
|
+
|
|
486
|
+
// Stop accepting commands immediately.
|
|
487
|
+
markDisconnected();
|
|
488
|
+
|
|
489
|
+
// Close all browser sessions (preserves profiles/cookies via the
|
|
490
|
+
// existing safe persistence path).
|
|
491
|
+
try {
|
|
492
|
+
await closeAllSessions();
|
|
493
|
+
} catch {}
|
|
494
|
+
|
|
495
|
+
// Release lock
|
|
496
|
+
processLock.releaseLock();
|
|
497
|
+
|
|
498
|
+
process.exit(0);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
process.on('SIGINT', () => shutdown('Ctrl+C'));
|
|
502
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
503
|
+
process.on('SIGHUP', () => shutdown('SIGHUP'));
|
|
504
|
+
|
|
505
|
+
// Also release the lock on uncaught exceptions
|
|
506
|
+
process.on('uncaughtException', (err) => {
|
|
507
|
+
console.error('Uncaught error:', err.message);
|
|
508
|
+
processLock.releaseLock();
|
|
509
|
+
process.exit(1);
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* `xkwd-agent status` — show device and connection status.
|
|
515
|
+
*/
|
|
516
|
+
function status() {
|
|
517
|
+
const { getStoredDevice } = require('./enrollmentClient');
|
|
518
|
+
const { isSecureStorageAvailable } = require('./deviceKeyStore');
|
|
519
|
+
const processLock = require('./processLock');
|
|
520
|
+
|
|
521
|
+
const args = process.argv.slice(2);
|
|
522
|
+
const serverFlag = args.find(a => a.startsWith('--server='));
|
|
523
|
+
const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
|
|
524
|
+
|
|
525
|
+
const device = getStoredDevice({ serverOrigin });
|
|
526
|
+
const lock = processLock.readLock();
|
|
527
|
+
|
|
528
|
+
console.log(`XKWDStore Agent v${CLI_VERSION}\n`);
|
|
529
|
+
|
|
530
|
+
const machineState = require('./machineState');
|
|
531
|
+
console.log(`Machine root: ${machineState.getMachineRoot()}`);
|
|
532
|
+
console.log(`Machine identity: ${machineState.hasMachineIdentity() ? 'present' : 'not yet adopted'}\n`);
|
|
533
|
+
|
|
534
|
+
if (!device) {
|
|
535
|
+
console.log('Status: Not authorized');
|
|
536
|
+
console.log('Run `xkwd-agent start` to authorize this computer.');
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
console.log(`Device ID: ${device.deviceId}`);
|
|
541
|
+
console.log(`Device name: ${device.deviceName}`);
|
|
542
|
+
console.log(`Server: ${device.serverOrigin || 'https://x.kwdstore.com'}`);
|
|
543
|
+
console.log(`Public-key fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
|
|
544
|
+
console.log(`Created: ${device.createdAt || 'unknown'}`);
|
|
545
|
+
console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available' : 'unavailable'}`);
|
|
546
|
+
|
|
547
|
+
if (lock) {
|
|
548
|
+
console.log(`\nAgent process: RUNNING (PID ${lock.pid})`);
|
|
549
|
+
console.log(`Started: ${lock.startedAt}`);
|
|
550
|
+
} else {
|
|
551
|
+
console.log('\nAgent process: not running');
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* `xkwd-agent logout` — delete local device identity (re-enrollment required).
|
|
557
|
+
* Server-scoped: only deletes the identity for the specified server.
|
|
558
|
+
* Usage: xkwd-agent logout [--server=<url>]
|
|
559
|
+
*/
|
|
560
|
+
async function logout() {
|
|
561
|
+
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
562
|
+
const processLock = require('./processLock');
|
|
563
|
+
|
|
564
|
+
// Parse --server flag for scoped logout
|
|
565
|
+
const args = process.argv.slice(2);
|
|
566
|
+
const serverFlag = args.find(a => a.startsWith('--server='));
|
|
567
|
+
const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
|
|
568
|
+
|
|
569
|
+
const lock = processLock.readLock();
|
|
570
|
+
if (lock) {
|
|
571
|
+
console.error('Agent is currently running. Stop it first with Ctrl+C.');
|
|
572
|
+
process.exit(1);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
await deletePrivateKey({ serverOrigin });
|
|
576
|
+
deleteMetadata({ serverOrigin });
|
|
577
|
+
console.log(`Local device identity deleted for ${serverOrigin}.`);
|
|
578
|
+
console.log('Run `xkwd-agent start` to re-authorize this computer.');
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* `xkwd-agent revoke-local` — same as logout but also clears the process lock.
|
|
583
|
+
* Server-scoped: only deletes the identity for the specified server.
|
|
584
|
+
*/
|
|
585
|
+
async function revokeLocal() {
|
|
586
|
+
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
587
|
+
const args = process.argv.slice(2);
|
|
588
|
+
const serverFlag = args.find(a => a.startsWith('--server='));
|
|
589
|
+
const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
|
|
590
|
+
await deletePrivateKey({ serverOrigin });
|
|
591
|
+
deleteMetadata({ serverOrigin });
|
|
592
|
+
console.log(`Local device identity and credentials revoked for ${serverOrigin}.`);
|
|
593
|
+
console.log('The server-side device record should also be revoked from the dashboard.');
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* `xkwd-agent machine` — machine-wide state operations (2.1.0).
|
|
598
|
+
*
|
|
599
|
+
* machine status — root, layout, identity presence, migration state
|
|
600
|
+
* machine adopt — run the one-time per-user → machine migration now
|
|
601
|
+
* machine harden — (Windows) apply + verify the restrictive DACL on the
|
|
602
|
+
* machine state directories
|
|
603
|
+
*/
|
|
604
|
+
async function machine(args) {
|
|
605
|
+
const machineState = require('./machineState');
|
|
606
|
+
const { getMachineRoot, getLegacyDataDir, applyMachineStateAcls } = require('./deviceKeyStore');
|
|
607
|
+
const action = (Array.isArray(args) && args[0]) || 'status';
|
|
608
|
+
|
|
609
|
+
if (action === 'status' || action === 'info') {
|
|
610
|
+
const report = machineState.migrationReport();
|
|
611
|
+
console.log(`XKWDStore Agent v${CLI_VERSION} — Machine state\n`);
|
|
612
|
+
console.log(`Machine root (device identity lives here): ${report.newLocation}`);
|
|
613
|
+
console.log(` exists: ${report.machinePresent ? 'yes' : 'no'}`);
|
|
614
|
+
console.log(` identity present: ${machineState.hasMachineIdentity() ? 'yes' : 'no'}`);
|
|
615
|
+
console.log(`Legacy per-user root (migration source): ${report.oldLocation}`);
|
|
616
|
+
console.log(` exists: ${report.legacyPresent ? 'yes' : 'no'}`);
|
|
617
|
+
console.log(`Started: ${report.machinePresent ? 'yes' : 'no'}`);
|
|
618
|
+
if (report.marker) {
|
|
619
|
+
console.log(`Migration: ${report.marker.adoption || 'complete'} at ${report.marker.migratedAt}`);
|
|
620
|
+
console.log(` device id(s): ${(report.marker.deviceIds || []).join(', ') || '(none)'}`);
|
|
621
|
+
} else {
|
|
622
|
+
console.log('Migration: not required (no legacy identity found) or not yet run');
|
|
623
|
+
}
|
|
624
|
+
console.log(`Rollback supported: ${report.rollbackSupported ? 'yes' : 'no'}`);
|
|
625
|
+
console.log(` ${report.rollbackInstruction}`);
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
if (action === 'adopt') {
|
|
630
|
+
const result = machineState.initializeMachineState();
|
|
631
|
+
console.log(`Machine root: ${result.root}`);
|
|
632
|
+
console.log(result.adopted
|
|
633
|
+
? `Adopted legacy per-user state (device id: ${result.deviceId || 'preserved'}).`
|
|
634
|
+
: `No adoption needed (${result.reason}).`);
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
if (action === 'harden') {
|
|
639
|
+
if (os.platform() !== 'win32') {
|
|
640
|
+
console.log('Machine-state ACL hardening is Windows-only; nothing to do.');
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
const applied = applyMachineStateAcls({});
|
|
644
|
+
console.log(`Applied and verified restrictive ACLs on ${applied.length} machine-state director${applied.length === 1 ? 'y' : 'ies'}:`);
|
|
645
|
+
for (const p of applied) console.log(` ${p}`);
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
console.error(`Unknown machine action: ${action}`);
|
|
650
|
+
console.error('Usage: xkwd-agent machine [status|adopt|harden]');
|
|
651
|
+
process.exit(1);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* `xkwd-agent service` — the BROKER entry point (2.1.0).
|
|
656
|
+
*
|
|
657
|
+
* Runs the machine-wide broker that a Windows Service hosts. Responsibilities:
|
|
658
|
+
* - acquire the machine-wide named mutex (exactly one broker)
|
|
659
|
+
* - own the machine identity + device private key
|
|
660
|
+
* - own the server WebSocket connection, leases, and session registry
|
|
661
|
+
* - spawn an interactive Browser Worker in the active desktop session
|
|
662
|
+
* - relay TYPED browser commands to the worker over a loopback-only channel
|
|
663
|
+
*
|
|
664
|
+
* It never launches Chromium itself. It is silent by design (the service host
|
|
665
|
+
* provides no desktop). For foreground diagnostics, `start` runs a broker+worker
|
|
666
|
+
* pair in this same session.
|
|
667
|
+
*/
|
|
668
|
+
async function service(serverOrigin, flags) {
|
|
669
|
+
const machineLock = require('./machineLock');
|
|
670
|
+
const machineState = require('./machineState');
|
|
671
|
+
|
|
672
|
+
// 1. machine-wide broker uniqueness (authoritative on Windows).
|
|
673
|
+
const lock = machineLock.acquireMachineBrokerLock();
|
|
674
|
+
if (!lock.acquired) {
|
|
675
|
+
console.error(`Another machine broker already holds the lock (${lock.primitive}): ${lock.detail}`);
|
|
676
|
+
process.exit(3);
|
|
677
|
+
}
|
|
678
|
+
// Hold it for the process lifetime via a dedicated holder process.
|
|
679
|
+
const holder = machineLock.startMutexHolder();
|
|
680
|
+
if (!holder.ok) {
|
|
681
|
+
console.error(`Could not hold the machine broker lock: ${holder.detail}`);
|
|
682
|
+
process.exit(3);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// 2. machine state + identity (broker owns the credential).
|
|
686
|
+
try { machineState.initializeMachineState(); } catch { }
|
|
687
|
+
|
|
688
|
+
console.log(`XKWDStore Agent broker v${CLI_VERSION} (machine-wide)`);
|
|
689
|
+
console.log(`Machine root: ${machineState.getMachineRoot()}`);
|
|
690
|
+
console.log(`Broker lock: ${lock.detail}`);
|
|
691
|
+
|
|
692
|
+
// 3. connect to the server (broker owns the WebSocket).
|
|
693
|
+
// `--offline` (test-lifecycle only) skips the server connection so the service
|
|
694
|
+
// host / mutex / identity can be proven without a live enrollment. Production
|
|
695
|
+
// always connects.
|
|
696
|
+
const offline = !!flags.offline;
|
|
697
|
+
let ws = null;
|
|
698
|
+
if (offline) {
|
|
699
|
+
console.log('Broker running OFFLINE (lifecycle test mode; no server connection)');
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
if (offline) {
|
|
703
|
+
// Prove identity loads and the broker stays alive; keep the mutex held.
|
|
704
|
+
const meta = (() => { try { return require('./deviceKeyStore').loadMetadata({ serverOrigin }); } catch { return null; } })();
|
|
705
|
+
console.log(`Broker identity: ${meta && meta.deviceId ? meta.deviceId : '(none)'}`);
|
|
706
|
+
|
|
707
|
+
// --probe-worker: open the bridge, launch the interactive worker, and report
|
|
708
|
+
// the worker's Windows session id so the Session-0 -> interactive-session
|
|
709
|
+
// launch is PROVEN with a real process. Lifecycle-test only.
|
|
710
|
+
if (flags['probe-worker']) {
|
|
711
|
+
const bridge = require('./brokerWorkerBridge');
|
|
712
|
+
const token = bridge.newChannelToken();
|
|
713
|
+
const channel = await bridge.openBrokerChannel({ token });
|
|
714
|
+
console.log(`probe: bridge port ${channel.port}`);
|
|
715
|
+
const child = _spawnInteractiveWorker({ port: channel.port, token });
|
|
716
|
+
const deadline = Date.now() + 20000;
|
|
717
|
+
while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 150)); }
|
|
718
|
+
console.log(`probe: worker connected=${channel.connected}`);
|
|
719
|
+
console.log(`probe: activeConsoleSession=${_activeConsoleSession()} workerSession=${typeof child.session === 'number' ? child.session : 'n/a'}`);
|
|
720
|
+
try {
|
|
721
|
+
const st = await channel.call('getStatus', {}, 10000);
|
|
722
|
+
console.log('probe: worker status ' + JSON.stringify(st));
|
|
723
|
+
} catch (e) {
|
|
724
|
+
console.log('probe: worker status error ' + ((e && e.message) || 'unknown'));
|
|
725
|
+
}
|
|
726
|
+
// Give the harness time to inspect the worker process, then stop it.
|
|
727
|
+
await new Promise((r) => setTimeout(r, 12000));
|
|
728
|
+
try { await channel.call('shutdown', {}, 5000); } catch { }
|
|
729
|
+
try { channel.close(); } catch { }
|
|
730
|
+
console.log('probe: done');
|
|
731
|
+
machineLock.releaseMachineBrokerLock();
|
|
732
|
+
process.exit(0);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
console.log('Broker alive; holding the machine lock. Ctrl+C to stop.');
|
|
736
|
+
const t = setInterval(() => {
|
|
737
|
+
try { console.log('broker heartbeat ' + new Date().toISOString()); } catch { }
|
|
738
|
+
}, 15000);
|
|
739
|
+
t.unref();
|
|
740
|
+
await new Promise(() => { }); // run until killed
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// 4. spawn one interactive worker and route typed commands to it.
|
|
744
|
+
const bridge = require('./brokerWorkerBridge');
|
|
745
|
+
const token = bridge.newChannelToken();
|
|
746
|
+
const channel = await bridge.openBrokerChannel({ token });
|
|
747
|
+
const sessionHandler = require('./sessionHandler');
|
|
748
|
+
|
|
749
|
+
// The broker does NOT launch Chromium: it forwards startSession/stopSession to
|
|
750
|
+
// the worker. A worker is SESSION-BOUND: it is launched into the currently
|
|
751
|
+
// ACTIVE console session and is DISPOSABLE — a worker left over from a previous
|
|
752
|
+
// user (e.g. after a fast user switch) must NEVER serve a new session's job.
|
|
753
|
+
let worker = null;
|
|
754
|
+
let workerSession = -1;
|
|
755
|
+
async function ensureWorker() {
|
|
756
|
+
const active = _activeConsoleSession();
|
|
757
|
+
// Reuse the connected worker ONLY when it is in the CURRENT active session.
|
|
758
|
+
// On a change of active session the stale worker is torn down first (see the
|
|
759
|
+
// pure `shouldReplaceWorker` truth table).
|
|
760
|
+
const replace = bridge.shouldReplaceWorker({ connected: channel.connected, workerSession, activeSession: active });
|
|
761
|
+
if (!replace) return;
|
|
762
|
+
if (channel.connected) {
|
|
763
|
+
try { console.log(`worker session ${workerSession} != active ${active}; replacing the worker`); } catch { }
|
|
764
|
+
try { await channel.call('shutdown', {}, 5000); } catch { }
|
|
765
|
+
try { channel.dropWorker(); } catch { }
|
|
766
|
+
try { if (worker && worker.child) worker.child.kill(); } catch { }
|
|
767
|
+
workerSession = -1;
|
|
768
|
+
// Give the channel a moment to clear the old worker.
|
|
769
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
770
|
+
}
|
|
771
|
+
worker = _spawnInteractiveWorker({ port: channel.port, token });
|
|
772
|
+
const deadline = Date.now() + 15000;
|
|
773
|
+
while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 100)); }
|
|
774
|
+
if (!channel.connected) throw new Error('interactive worker did not attach');
|
|
775
|
+
// The launcher reports the target session on its stdout; wait briefly for it.
|
|
776
|
+
const sdeadline = Date.now() + 3000;
|
|
777
|
+
while (workerSession === -1 && Date.now() < sdeadline) {
|
|
778
|
+
workerSession = typeof worker.session === 'number' ? worker.session : -1;
|
|
779
|
+
if (workerSession === -1) await new Promise((r) => setTimeout(r, 100));
|
|
780
|
+
}
|
|
781
|
+
try { console.log(`worker attached (session=${workerSession}, active=${active})`); } catch { }
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
const { setupSessionHandler, closeAllSessions, markDisconnected } = sessionHandler;
|
|
785
|
+
const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
|
|
786
|
+
|
|
787
|
+
// 4a. ONE reconnect supervisor owns the production WebSocket lifecycle so a
|
|
788
|
+
// transient network/DNS/TLS/backend/WS/heartbeat loss reconnects with the
|
|
789
|
+
// SAME enrolled identity — no manual restart, no re-pair, no new key. Retries
|
|
790
|
+
// are UNBOUNDED for the machine service (a long-lived broker must self-heal);
|
|
791
|
+
// the supervisor preserves exactly one timer / one attempt / one socket.
|
|
792
|
+
const _bindSessionHandler = (socket) => setupSessionHandler(socket, {
|
|
793
|
+
// The broker has no chromePath: all browser work goes through the worker.
|
|
794
|
+
chromePath: null,
|
|
795
|
+
deviceMeta: require('./deviceKeyStore').loadMetadata({ serverOrigin }) || {},
|
|
796
|
+
serverOrigin,
|
|
797
|
+
// 2.1.0: route browser commands through the worker bridge.
|
|
798
|
+
workerBridge: {
|
|
799
|
+
ensureWorker,
|
|
800
|
+
call: (command, payload) => channel.call(command, payload),
|
|
801
|
+
},
|
|
802
|
+
});
|
|
803
|
+
|
|
804
|
+
const supervisor = createBrokerConnectionSupervisor({
|
|
805
|
+
connect: () => _brokerConnect(serverOrigin),
|
|
806
|
+
// Rebind the FULL session handler on every (re)connect; the server drives
|
|
807
|
+
// lease reconciliation from our sessions-report (protocol v2).
|
|
808
|
+
onConnected: (socket) => { _bindSessionHandler(socket); },
|
|
809
|
+
// On a REAL disconnect stop accepting remote commands. Durable leases are
|
|
810
|
+
// server-owned and are NOT released locally — the server reconciles them
|
|
811
|
+
// after we reconnect.
|
|
812
|
+
onDisconnected: () => { try { markDisconnected(); } catch { } },
|
|
813
|
+
// Auth/identity rejection: stay running and retry conservatively. NEVER
|
|
814
|
+
// delete the credential or mint a new identity here.
|
|
815
|
+
onAuthRejected: () => { try { console.error('[broker] authentication/identity rejected; identity preserved, retrying conservatively'); } catch { } },
|
|
816
|
+
log: (m) => { try { console.log(m); } catch { } },
|
|
817
|
+
});
|
|
818
|
+
console.log(`Broker connecting to ${serverOrigin} ...`);
|
|
819
|
+
Promise.resolve(supervisor.start()).catch(() => {});
|
|
820
|
+
|
|
821
|
+
async function shutdown(signal) {
|
|
822
|
+
console.log(`\n${signal} received. Broker shutting down...`);
|
|
823
|
+
// Stop reconnecting FIRST so no retry can start after shutdown begins.
|
|
824
|
+
try { supervisor.stop(); } catch { }
|
|
825
|
+
try { await channel.call('shutdown', {}, 5000); } catch { }
|
|
826
|
+
try { if (worker) worker.kill(); } catch { }
|
|
827
|
+
try { channel.close(); } catch { }
|
|
828
|
+
try { await closeAllSessions(); } catch { }
|
|
829
|
+
machineLock.releaseMachineBrokerLock();
|
|
830
|
+
process.exit(0);
|
|
831
|
+
}
|
|
832
|
+
process.on('SIGINT', () => shutdown('Ctrl+C'));
|
|
833
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** The currently ACTIVE Windows console session id, via the compiled launcher's
|
|
837
|
+
* `-Query` mode. Returns -1 when it cannot be determined (fail-safe). */
|
|
838
|
+
function _activeConsoleSession() {
|
|
839
|
+
try {
|
|
840
|
+
const path = require('path');
|
|
841
|
+
const fs = require('fs');
|
|
842
|
+
const { execFileSync } = require('child_process');
|
|
843
|
+
const machineRoot = require('./machineState').getMachineRoot();
|
|
844
|
+
const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
|
|
845
|
+
if (os.platform() !== 'win32' || !fs.existsSync(launcherExe)) return -1;
|
|
846
|
+
const out = execFileSync(launcherExe, ['-Query'], { encoding: 'utf8', windowsHide: true, timeout: 5000 }).trim();
|
|
847
|
+
const m = /SESSION=(-?\d+)/.exec(out);
|
|
848
|
+
return m ? parseInt(m[1], 10) : -1;
|
|
849
|
+
} catch { return -1; }
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/** Spawn an interactive browser worker into the ACTIVE INTERACTIVE session.
|
|
853
|
+
*
|
|
854
|
+
* The broker runs as a Session-0 service, which has no desktop. A plain
|
|
855
|
+
* child_process.spawn would create the worker (and its Chromium) in Session 0,
|
|
856
|
+
* where no browser can be shown. When the broker is in Session 0 we therefore
|
|
857
|
+
* launch the worker via the compiled session launcher (CreateProcessAsUser with
|
|
858
|
+
* the active console session's user token). When the broker already runs in an
|
|
859
|
+
* interactive session (foreground `start`), a direct spawn is equivalent.
|
|
860
|
+
*
|
|
861
|
+
* Returns { child, session } where `session` is the Windows session the worker
|
|
862
|
+
* was launched into (or -1 when unknown). The broker records this so it never
|
|
863
|
+
* reuses a worker from a session that is no longer the active console session.
|
|
864
|
+
*/
|
|
865
|
+
function _spawnInteractiveWorker({ port, token }) {
|
|
866
|
+
const { spawn } = require('child_process');
|
|
867
|
+
const path = require('path');
|
|
868
|
+
const fs = require('fs');
|
|
869
|
+
const workerScript = path.join(__dirname, 'worker.js');
|
|
870
|
+
const workerArgs = ['--port', String(port), '--token', token];
|
|
871
|
+
|
|
872
|
+
const machineRoot = require('./machineState').getMachineRoot();
|
|
873
|
+
const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
|
|
874
|
+
|
|
875
|
+
if (os.platform() === 'win32' && fs.existsSync(launcherExe)) {
|
|
876
|
+
// Launch into the active interactive session. The launcher prints
|
|
877
|
+
// `LAUNCHED pid=N session=S`; capture it so the worker is session-bound.
|
|
878
|
+
const logDir = path.join(machineRoot, 'logs');
|
|
879
|
+
try { fs.mkdirSync(logDir, { recursive: true }); } catch { }
|
|
880
|
+
const outLog = path.join(logDir, 'worker.out.log');
|
|
881
|
+
const errLog = path.join(logDir, 'worker.err.log');
|
|
882
|
+
const child = spawn(launcherExe, [
|
|
883
|
+
'-Exe', process.execPath,
|
|
884
|
+
'-Args', '"' + workerScript + '" ' + workerArgs.join(' '),
|
|
885
|
+
'-Cwd', __dirname,
|
|
886
|
+
'-Out', outLog,
|
|
887
|
+
'-Err', errLog,
|
|
888
|
+
], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
889
|
+
let session = -1;
|
|
890
|
+
let buf = '';
|
|
891
|
+
try {
|
|
892
|
+
child.stdout.on('data', (d) => {
|
|
893
|
+
buf += d.toString();
|
|
894
|
+
const m = /session=(-?\d+)/.exec(buf);
|
|
895
|
+
if (m) session = parseInt(m[1], 10);
|
|
896
|
+
});
|
|
897
|
+
} catch { }
|
|
898
|
+
return { child, get session() { return session; } };
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// Interactive/foreground fallback: the broker is already in the right session.
|
|
902
|
+
const child = spawn(process.execPath, [workerScript, ...workerArgs], {
|
|
903
|
+
detached: false,
|
|
904
|
+
stdio: ['ignore', 'inherit', 'inherit'],
|
|
905
|
+
windowsHide: true,
|
|
906
|
+
});
|
|
907
|
+
return { child, session: _activeConsoleSession() };
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/** Connect the broker's WebSocket using the machine credential. */
|
|
911
|
+
async function _brokerConnect(serverOrigin) {
|
|
912
|
+
const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
|
|
913
|
+
const deviceMeta = getStoredDevice({ serverOrigin });
|
|
914
|
+
const privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
|
|
915
|
+
if (!deviceMeta || !privateKeyB64Url) {
|
|
916
|
+
throw new Error('device is not enrolled; run `xkwd-agent start` once to authorize this machine');
|
|
917
|
+
}
|
|
918
|
+
const { connectWebSocket } = require('./wsClient');
|
|
919
|
+
return connectWebSocket({
|
|
920
|
+
serverOrigin,
|
|
921
|
+
deviceId: deviceMeta.deviceId,
|
|
922
|
+
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
923
|
+
privateKeyB64Url,
|
|
924
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* `xkwd-agent doctor` — diagnostic checks.
|
|
930
|
+
*/
|
|
931
|
+
async function doctor(serverOrigin) {
|
|
932
|
+
console.log(`XKWDStore Agent v${CLI_VERSION} — Diagnostics\n`);
|
|
933
|
+
|
|
934
|
+
// Check Node version
|
|
935
|
+
const nodeVersion = process.versions.node;
|
|
936
|
+
const major = parseInt(nodeVersion.split('.')[0], 10);
|
|
937
|
+
console.log(`Node.js: ${nodeVersion} ${major >= 22 ? '✓' : '✗ (requires Node.js 22+)'}`);
|
|
938
|
+
|
|
939
|
+
// Check platform
|
|
940
|
+
console.log(`Platform: ${os.platform()} ${os.arch()}`);
|
|
941
|
+
console.log(`Hostname: ${os.hostname()}`);
|
|
942
|
+
|
|
943
|
+
// Check Chrome
|
|
944
|
+
try {
|
|
945
|
+
const { resolveChromeOrFail } = require('./chromeDetector');
|
|
946
|
+
const chrome = resolveChromeOrFail();
|
|
947
|
+
console.log(`Chrome: ${chrome.chromeVersion || 'detected'} ✓`);
|
|
948
|
+
} catch (e) {
|
|
949
|
+
console.log(`Chrome: ✗ (${e.message.split('\n')[0]})`);
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
// Check secure storage (real DPAPI + ACL probe on Windows)
|
|
953
|
+
const { isSecureStorageAvailable, getDataDir, probeWindowsStorage } = require('./deviceKeyStore');
|
|
954
|
+
const platform = os.platform();
|
|
955
|
+
if (platform === 'win32') {
|
|
956
|
+
console.log('Secure storage: probing real DPAPI + ACL stages...');
|
|
957
|
+
const probe = probeWindowsStorage();
|
|
958
|
+
console.log(` DPAPI Protect : ${probe.stages.protect ? '✓' : '✗'}`);
|
|
959
|
+
console.log(` DPAPI Unprotect: ${probe.stages.unprotect ? '✓' : '✗'}`);
|
|
960
|
+
console.log(` Windows SID : ${probe.stages.sidLookup ? '✓' : '✗'}`);
|
|
961
|
+
console.log(` ACL apply : ${probe.stages.aclApply ? '✓' : '✗'}`);
|
|
962
|
+
console.log(` ACL verify : ${probe.stages.aclVerify ? '✓' : '✗'}`);
|
|
963
|
+
console.log(`Secure storage: ${probe.ok ? 'available ✓' : 'unavailable ✗'}`);
|
|
964
|
+
if (!probe.ok && probe.detail) {
|
|
965
|
+
console.log(` Detail: ${probe.detail}`);
|
|
966
|
+
}
|
|
967
|
+
} else {
|
|
968
|
+
console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available ✓' : 'unavailable ✗'}`);
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// Check data directory (machine-wide since 2.1.0)
|
|
972
|
+
const dataDir = getDataDir();
|
|
973
|
+
const legacyDir = require('./deviceKeyStore').getLegacyDataDir();
|
|
974
|
+
console.log(`Machine state root: ${dataDir}`);
|
|
975
|
+
console.log(`Legacy per-user root: ${legacyDir}`);
|
|
976
|
+
const machineState = require('./machineState');
|
|
977
|
+
console.log(`Machine identity present: ${machineState.hasMachineIdentity() ? '✓' : '(none yet)'}`);
|
|
978
|
+
|
|
979
|
+
// Check device identity (server-scoped)
|
|
980
|
+
const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
|
|
981
|
+
const device = getStoredDevice({ serverOrigin });
|
|
982
|
+
if (device) {
|
|
983
|
+
console.log(`Device ID: ${device.deviceId} ✓`);
|
|
984
|
+
const privateKey = await getStoredPrivateKey({ serverOrigin });
|
|
985
|
+
console.log(`Private key: ${privateKey ? 'stored ✓' : 'missing ✗'}`);
|
|
986
|
+
} else {
|
|
987
|
+
console.log('Device ID: not enrolled for this server');
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// Check server connectivity (shared strict validator)
|
|
991
|
+
try {
|
|
992
|
+
const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
|
|
993
|
+
const resp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
|
|
994
|
+
const compat = validateCompatibilityResponse(resp);
|
|
995
|
+
if (compat.html) {
|
|
996
|
+
console.log(`Server (${serverOrigin}): compatibility endpoint returned frontend ✗`);
|
|
997
|
+
console.log(' ' + COMPAT_HTML_MESSAGE);
|
|
998
|
+
} else if (compat.ok) {
|
|
999
|
+
console.log(`Server (${serverOrigin}): reachable ✓`);
|
|
1000
|
+
console.log(` Protocol version: ${compat.body.protocolVersion}`);
|
|
1001
|
+
console.log(` Min agent version: ${compat.body.minimumAgentVersion}`);
|
|
1002
|
+
console.log(` Recommended agent version: ${compat.body.recommendedAgentVersion}`);
|
|
1003
|
+
} else {
|
|
1004
|
+
console.log(`Server (${serverOrigin}): compatibility check failed ✗`);
|
|
1005
|
+
console.log(` Reason: ${compat.reason}`);
|
|
1006
|
+
}
|
|
1007
|
+
} catch (e) {
|
|
1008
|
+
console.log(`Server (${serverOrigin}): unreachable ✗ (${e.message})`);
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/**
|
|
1013
|
+
* `xkwd-agent version` — print version.
|
|
1014
|
+
*/
|
|
1015
|
+
function version() {
|
|
1016
|
+
console.log(`@xkwdstore/agent v${CLI_VERSION}`);
|
|
1017
|
+
console.log(`Protocol version: ${PROTOCOL_VERSION}`);
|
|
1018
|
+
console.log(`Node.js: ${process.versions.node}`);
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/**
|
|
1022
|
+
* `xkwd-agent help` — print help.
|
|
1023
|
+
*/
|
|
1024
|
+
function help() {
|
|
1025
|
+
console.log(`XKWDStore Agent v${CLI_VERSION}
|
|
1026
|
+
|
|
1027
|
+
Usage:
|
|
1028
|
+
xkwd-agent <command> [options]
|
|
1029
|
+
|
|
1030
|
+
Commands:
|
|
1031
|
+
start Start the agent (connects to server, runs browser sessions)
|
|
1032
|
+
status Show device and connection status
|
|
1033
|
+
logout Delete local device identity (requires re-authorization)
|
|
1034
|
+
revoke-local Delete local device identity and credentials
|
|
1035
|
+
machine Machine-wide state: status | adopt | harden
|
|
1036
|
+
service Run the machine-wide broker (Windows Service host; silent)
|
|
1037
|
+
doctor Run diagnostic checks
|
|
1038
|
+
version Print version information
|
|
1039
|
+
help Show this help
|
|
1040
|
+
|
|
1041
|
+
Options:
|
|
1042
|
+
--server=<url> Server URL (default: https://x.kwdstore.com)
|
|
1043
|
+
--replace Replace a running instance (safe takeover)
|
|
1044
|
+
|
|
1045
|
+
Examples:
|
|
1046
|
+
xkwd-agent start
|
|
1047
|
+
xkwd-agent start --replace
|
|
1048
|
+
xkwd-agent status
|
|
1049
|
+
xkwd-agent machine status
|
|
1050
|
+
xkwd-agent doctor
|
|
1051
|
+
|
|
1052
|
+
First run:
|
|
1053
|
+
The agent will open your browser to authorize this computer.
|
|
1054
|
+
No pairing code, email, or API key is required.
|
|
1055
|
+
|
|
1056
|
+
To stop:
|
|
1057
|
+
Press Ctrl+C in the terminal.
|
|
1058
|
+
|
|
1059
|
+
Data location (machine-wide, shared by every Windows user on this PC):
|
|
1060
|
+
Windows: %ProgramData%\\XKWDStore\\Agent\\
|
|
1061
|
+
Linux: ${'{XDG_DATA_HOME:-~/.local/share}/xkwdstore/'}
|
|
1062
|
+
macOS: unsupported (fails closed)
|
|
1063
|
+
|
|
1064
|
+
Device identity belongs to the MACHINE. Changing the Windows user or the
|
|
1065
|
+
TW-manager preferred device does NOT create a second device identity.
|
|
1066
|
+
A pre-2.1.0 per-user install is adopted once (copy, never move).
|
|
1067
|
+
|
|
1068
|
+
Requirements:
|
|
1069
|
+
- Node.js 22 or later
|
|
1070
|
+
- Google Chrome installed
|
|
1071
|
+
`);
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
1075
|
+
|
|
1076
|
+
/**
|
|
1077
|
+
* Detect whether a connection error is a 4003 authentication failure.
|
|
1078
|
+
* The wsClient rejects with a message containing "Device authentication
|
|
1079
|
+
* failed" when the server closes with code 4003. The error may also carry
|
|
1080
|
+
* a .code property in some implementations.
|
|
1081
|
+
*/
|
|
1082
|
+
function _is4003Error(err) {
|
|
1083
|
+
if (!err) return false;
|
|
1084
|
+
const msg = (err.message || String(err)).toLowerCase();
|
|
1085
|
+
if (err.code === 4003) return true;
|
|
1086
|
+
if (msg.includes('device authentication failed')) return true;
|
|
1087
|
+
if (msg.includes('4003')) return true;
|
|
1088
|
+
return false;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
function _compareVersions(a, b) {
|
|
1092
|
+
const pa = a.split('.').map(Number);
|
|
1093
|
+
const pb = b.split('.').map(Number);
|
|
1094
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
1095
|
+
const va = pa[i] || 0;
|
|
1096
|
+
const vb = pb[i] || 0;
|
|
1097
|
+
if (va > vb) return 1;
|
|
1098
|
+
if (va < vb) return -1;
|
|
1099
|
+
}
|
|
1100
|
+
return 0;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
// ── Entry point ──────────────────────────────────────────────────────────────
|
|
1104
|
+
|
|
1105
|
+
if (require.main === module) {
|
|
1106
|
+
main();
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
1109
|
module.exports = { main, CLI_VERSION, PROTOCOL_VERSION };
|