@xkwdstore/agent 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,234 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Phase 8 — WebSocket client with Ed25519 challenge-response authentication.
5
+ *
6
+ * Connects to the server's protocol v2 WebSocket endpoint.
7
+ * No ticket, no query params, no credentials in the URL.
8
+ *
9
+ * Flow:
10
+ * 1. Connect to wss://server/ws/local-agent-v2 (no query params).
11
+ * 2. Receive auth-challenge.
12
+ * 3. Sign the canonical challenge payload with Ed25519 private key.
13
+ * 4. Send auth-response.
14
+ * 5. Receive authenticated frame (or connection closed with 4003).
15
+ */
16
+
17
+ const WebSocket = require('ws');
18
+ const { canonicalChallengeInput } = require('./challengeCodec');
19
+ const { signMessage } = require('./deviceKeyStore');
20
+
21
+ /**
22
+ * The single authoritative version source is package.json. The User-Agent is
23
+ * derived from it (never hard-coded) so the binary always reports the package
24
+ * version. We require the package metadata lazily and cache it.
25
+ */
26
+ let _pkgVersion = null;
27
+ function _agentVersion() {
28
+ if (_pkgVersion) return _pkgVersion;
29
+ try {
30
+ // package.json sits at the package root; src/ is one level down.
31
+ _pkgVersion = require('../package.json').version || '0.0.0';
32
+ } catch {
33
+ _pkgVersion = '0.0.0';
34
+ }
35
+ return _pkgVersion;
36
+ }
37
+
38
+ function _userAgent() {
39
+ return `XKWDStore-Agent/${_agentVersion()} (${process.platform}; ${process.arch})`;
40
+ }
41
+
42
+ /**
43
+ * Connect to the server's protocol v2 WebSocket.
44
+ *
45
+ * @param {object} opts
46
+ * @param {string} opts.serverOrigin — e.g. 'https://x.kwdstore.com'
47
+ * @param {string} opts.deviceId
48
+ * @param {string} opts.publicKeyFingerprint
49
+ * @param {string} opts.privateKeyB64Url
50
+ * @param {number} opts.protocolVersion
51
+ * @returns {Promise<WebSocket>} resolved when authenticated, rejected on failure
52
+ */
53
+ function connectWebSocket(opts) {
54
+ return new Promise((resolve, reject) => {
55
+ const wsUrl = opts.serverOrigin.replace(/^http/, 'ws') + '/ws/local-agent-v2';
56
+
57
+ const ws = new WebSocket(wsUrl, {
58
+ headers: {
59
+ 'User-Agent': _userAgent(),
60
+ },
61
+ // No credentials in the URL — auth happens on the WS.
62
+ handshakeTimeout: 15000,
63
+ });
64
+
65
+ let authTimeout;
66
+
67
+ const cleanup = () => {
68
+ if (authTimeout) clearTimeout(authTimeout);
69
+ };
70
+
71
+ ws.on('open', () => {
72
+ // Set an auth timeout — if we don't get authenticated within 60s, give up.
73
+ authTimeout = setTimeout(() => {
74
+ try { ws.close(4003, 'Auth timeout'); } catch {}
75
+ reject(new Error('Authentication timed out'));
76
+ }, 60000);
77
+ });
78
+
79
+ ws.on('message', (data, isBinary) => {
80
+ if (isBinary) return;
81
+
82
+ let msg;
83
+ try {
84
+ msg = JSON.parse(data.toString('utf8'));
85
+ } catch {
86
+ return;
87
+ }
88
+
89
+ if (msg.type === 'auth-challenge') {
90
+ // Build the canonical input and sign it
91
+ const canonicalInput = canonicalChallengeInput({
92
+ protocolVersion: msg.protocolVersion,
93
+ connectionId: msg.connectionId,
94
+ nonce: msg.nonce,
95
+ issuedAt: msg.issuedAt,
96
+ expiresAt: msg.expiresAt,
97
+ serverOrigin: msg.serverOrigin,
98
+ deviceId: opts.deviceId,
99
+ publicKeyFingerprint: opts.publicKeyFingerprint,
100
+ });
101
+
102
+ const signature = signMessage(opts.privateKeyB64Url, canonicalInput);
103
+
104
+ // Send the auth response
105
+ ws.send(JSON.stringify({
106
+ type: 'auth-response',
107
+ protocolVersion: msg.protocolVersion,
108
+ deviceId: opts.deviceId,
109
+ publicKeyFingerprint: opts.publicKeyFingerprint,
110
+ signature,
111
+ }));
112
+ return;
113
+ }
114
+
115
+ if (msg.type === 'authenticated') {
116
+ cleanup();
117
+ resolve(ws);
118
+ return;
119
+ }
120
+
121
+ // Other messages are handled by the session handler after auth.
122
+ // Forward them if a handler is set.
123
+ if (ws._messageHandler) {
124
+ ws._messageHandler(msg);
125
+ }
126
+ });
127
+
128
+ ws.on('close', (code, reason) => {
129
+ cleanup();
130
+ if (code === 4003) {
131
+ reject(new Error('Device authentication failed'));
132
+ } else if (code === 1006) {
133
+ reject(new Error('Connection closed unexpectedly'));
134
+ } else {
135
+ reject(new Error(`Connection closed: ${code} ${reason || ''}`));
136
+ }
137
+ });
138
+
139
+ ws.on('error', (err) => {
140
+ cleanup();
141
+ reject(new Error(`WebSocket error: ${err.message}`));
142
+ });
143
+ });
144
+ }
145
+
146
+ /**
147
+ * Defect 14 — Connect with automatic reconnection.
148
+ *
149
+ * Implements:
150
+ * - exponential backoff with jitter;
151
+ * - a fresh challenge on every reconnect (no re-enrollment for network loss);
152
+ * - re-enrollment only for unknown/revoked key (4003 close code);
153
+ * - bounded retries (max 10 attempts, max 60s delay);
154
+ * - clean shutdown via the returned controller.
155
+ *
156
+ * @param {object} opts — same as connectWebSocket
157
+ * @param {function} onDisconnect — called when the connection drops (before reconnect)
158
+ * @param {function} onReconnect — called when reconnection succeeds
159
+ * @returns {object} { ws: Promise<WebSocket>, shutdown: function }
160
+ */
161
+ function connectWithReconnect(opts, onDisconnect, onReconnect) {
162
+ let attempt = 0;
163
+ let shuttingDown = false;
164
+ let currentWs = null;
165
+
166
+ const MAX_RETRIES = 10;
167
+ const BASE_DELAY_MS = 1000;
168
+ const MAX_DELAY_MS = 60000;
169
+
170
+ function _delay() {
171
+ const exponential = Math.min(BASE_DELAY_MS * Math.pow(2, attempt), MAX_DELAY_MS);
172
+ const jitter = Math.random() * 1000;
173
+ return exponential + jitter;
174
+ }
175
+
176
+ async function _connect() {
177
+ while (!shuttingDown && attempt < MAX_RETRIES) {
178
+ try {
179
+ const ws = await connectWebSocket(opts);
180
+ currentWs = ws;
181
+ attempt = 0; // Reset on successful connection
182
+
183
+ // Set up disconnect handler for reconnection.
184
+ ws.on('close', (code) => {
185
+ if (shuttingDown) return;
186
+ currentWs = null;
187
+
188
+ // 4003 = auth failure (revoked/unknown key) — do NOT reconnect.
189
+ if (code === 4003) {
190
+ if (onDisconnect) onDisconnect(new Error('Device authentication failed (revoked or unknown key)'), true);
191
+ return;
192
+ }
193
+
194
+ if (onDisconnect) onDisconnect(new Error(`Connection closed: ${code}`), false);
195
+
196
+ // Reconnect with backoff.
197
+ attempt++;
198
+ if (attempt < MAX_RETRIES) {
199
+ const delay = _delay();
200
+ setTimeout(() => _connect(), delay);
201
+ }
202
+ });
203
+
204
+ if (onReconnect) onReconnect(ws);
205
+ return ws;
206
+ } catch (err) {
207
+ attempt++;
208
+ if (attempt >= MAX_RETRIES) {
209
+ throw new Error(`Max reconnection attempts reached: ${err.message}`);
210
+ }
211
+ // 4003 = auth failure — do NOT reconnect.
212
+ if (err.message.includes('Device authentication failed')) {
213
+ throw err;
214
+ }
215
+ const delay = _delay();
216
+ await new Promise(r => setTimeout(r, delay));
217
+ }
218
+ }
219
+ }
220
+
221
+ const wsPromise = _connect();
222
+
223
+ return {
224
+ ws: wsPromise,
225
+ shutdown: () => {
226
+ shuttingDown = true;
227
+ if (currentWs) {
228
+ try { currentWs.close(1000, 'Agent shutting down'); } catch {}
229
+ }
230
+ },
231
+ };
232
+ }
233
+
234
+ module.exports = { connectWebSocket, connectWithReconnect, _agentVersion, _userAgent };