surfcad-mcp 0.2.0 → 0.2.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.
@@ -7,11 +7,32 @@ import { PAIR_MSG } from '../relayMessages.mjs';
7
7
  import { isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
8
8
 
9
9
  /**
10
- * @typedef {{ send: (data: string) => void, close: () => void, on: (event: string, cb: (...args: unknown[]) => void) => void, remoteAddress?: string, origin?: string }} RelaySocket
10
+ * @typedef {{
11
+ * send: (data: string) => void,
12
+ * close: () => void,
13
+ * on: (event: string, cb: (...args: unknown[]) => void) => void,
14
+ * ping?: () => void,
15
+ * terminate?: () => void,
16
+ * remoteAddress?: string,
17
+ * origin?: string,
18
+ * }} RelaySocket
19
+ * @typedef {'info' | 'warn'} RelayLogLevel
11
20
  */
12
21
 
22
+ /** Opaque secrets (tab key, resume key) are random URL-safe strings. */
23
+ const SECRET_RE = /^[A-Za-z0-9_-]{16,128}$/;
24
+
25
+ /** How long a dropped tab keeps its pairing code so a squatter cannot take it. */
26
+ export const DEFAULT_TAB_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000;
27
+ /** How often expired reservations are swept from the Map (unref'd timer). */
28
+ export const DEFAULT_TAB_RESERVATION_SWEEP_MS = 60 * 1000;
29
+
13
30
  function sendJson(socket, payload) {
14
- socket.send(JSON.stringify(payload));
31
+ try {
32
+ socket.send(JSON.stringify(payload));
33
+ } catch {
34
+ /* socket already gone */
35
+ }
15
36
  }
16
37
 
17
38
  function parseMessage(raw) {
@@ -25,6 +46,26 @@ function parseMessage(raw) {
25
46
  }
26
47
  }
27
48
 
49
+ function secretOrNull(value) {
50
+ return typeof value === 'string' && SECRET_RE.test(value) ? value : null;
51
+ }
52
+
53
+ /**
54
+ * Logs must never carry a full pairing code: keep the first two characters.
55
+ * @param {string} token
56
+ */
57
+ export function redactToken(token) {
58
+ const t = String(token || '');
59
+ if (!t) return '-';
60
+ return `${t.slice(0, 2)}${'*'.repeat(Math.max(2, t.length - 2))}`;
61
+ }
62
+
63
+ function closeReason(code, reason) {
64
+ const text = reason == null ? '' : String(reason);
65
+ if (code == null) return 'socket_closed';
66
+ return text ? `socket_closed code=${code} (${text.slice(0, 80)})` : `socket_closed code=${code}`;
67
+ }
68
+
28
69
  /**
29
70
  * @param {RelaySocket} socket
30
71
  * @param {string} code
@@ -36,29 +77,105 @@ function refuse(socket, code, message) {
36
77
  }
37
78
 
38
79
  /**
39
- * @param {{ onLog?: (line: string) => void }} [opts]
80
+ * @param {{
81
+ * onLog?: (line: string, level: RelayLogLevel) => void,
82
+ * reservationTtlMs?: number,
83
+ * reservationSweepMs?: number,
84
+ * }} [opts]
40
85
  */
41
86
  export function createAgentBridgeRelayHub(opts = {}) {
42
- const log = (line) => { opts.onLog?.(line); };
87
+ /** @param {string} line @param {RelayLogLevel} [level] */
88
+ const log = (line, level = 'info') => { opts.onLog?.(line, level); };
89
+ const reservationTtlMs = opts.reservationTtlMs ?? DEFAULT_TAB_RESERVATION_TTL_MS;
90
+ const reservationSweepMs = opts.reservationSweepMs ?? DEFAULT_TAB_RESERVATION_SWEEP_MS;
43
91
 
44
- /** @type {Map<string, { socket: RelaySocket, token: string, pairedPeer: RelaySocket | null, pendingPeer: RelaySocket | null }>} */
92
+ /**
93
+ * @type {Map<string, {
94
+ * socket: RelaySocket | null,
95
+ * token: string,
96
+ * tabKey: string | null,
97
+ * resumeKey: string | null,
98
+ * resumeTabKey: string | null,
99
+ * pairedPeer: RelaySocket | null,
100
+ * pendingPeer: RelaySocket | null,
101
+ * reservedAt: number | null,
102
+ * }>}
103
+ */
45
104
  const tabsByToken = new Map();
46
105
  /** @type {Map<RelaySocket, { role: 'tab' | 'peer', token: string }>} */
47
106
  const socketMeta = new Map();
107
+ /** @type {Map<RelaySocket, { alive: boolean, dropReason: string | null }>} */
108
+ const liveness = new Map();
109
+
110
+ function closePeer(peer) {
111
+ socketMeta.delete(peer);
112
+ try { peer.close(); } catch { /* gone */ }
113
+ }
114
+
115
+ function reservationExpired(tab) {
116
+ return tab.socket == null
117
+ && tab.reservedAt != null
118
+ && (Date.now() - tab.reservedAt) > reservationTtlMs;
119
+ }
48
120
 
49
- function dropTab(token) {
121
+ function liveTab(token) {
122
+ const tab = tabsByToken.get(token);
123
+ if (!tab) return null;
124
+ if (reservationExpired(tab)) {
125
+ tabsByToken.delete(token);
126
+ return null;
127
+ }
128
+ return tab;
129
+ }
130
+
131
+ function sweepExpiredReservations() {
132
+ for (const [token, tab] of tabsByToken) {
133
+ if (reservationExpired(tab)) tabsByToken.delete(token);
134
+ }
135
+ }
136
+
137
+ const sweepTimer = reservationSweepMs > 0
138
+ ? setInterval(sweepExpiredReservations, reservationSweepMs)
139
+ : null;
140
+ if (typeof sweepTimer?.unref === 'function') sweepTimer.unref();
141
+
142
+ function emptyEntry(token, extra = {}) {
143
+ return {
144
+ socket: null,
145
+ token,
146
+ tabKey: extra.tabKey ?? null,
147
+ resumeKey: extra.resumeKey ?? null,
148
+ resumeTabKey: extra.resumeTabKey ?? extra.tabKey ?? null,
149
+ pairedPeer: null,
150
+ pendingPeer: null,
151
+ reservedAt: extra.reservedAt ?? null,
152
+ };
153
+ }
154
+
155
+ function dropTab(token, reason) {
50
156
  const tab = tabsByToken.get(token);
51
157
  if (!tab) return;
52
- tabsByToken.delete(token);
158
+ if (tab.socket) socketMeta.delete(tab.socket);
159
+ const peerState = tab.pairedPeer ? 'paired' : (tab.pendingPeer ? 'pending' : 'none');
160
+ log(`tab dropped token=${redactToken(token)} reason=${reason} peer=${peerState}`, 'warn');
53
161
  if (tab.pairedPeer) {
54
- sendJson(tab.pairedPeer, { type: PAIR_MSG.UNPAIRED, reason: 'tab_disconnected' });
55
- socketMeta.delete(tab.pairedPeer);
162
+ sendJson(tab.pairedPeer, { type: PAIR_MSG.UNPAIRED, reason: 'tab_disconnected', detail: reason });
163
+ closePeer(tab.pairedPeer);
56
164
  }
57
165
  if (tab.pendingPeer) {
58
166
  sendJson(tab.pendingPeer, { type: PAIR_MSG.ERROR, code: 'pair_cancelled', message: 'Tab disconnected' });
59
- socketMeta.delete(tab.pendingPeer);
167
+ closePeer(tab.pendingPeer);
168
+ }
169
+ if (tab.tabKey) {
170
+ tabsByToken.set(token, emptyEntry(token, {
171
+ tabKey: tab.tabKey,
172
+ resumeKey: tab.resumeKey,
173
+ resumeTabKey: tab.resumeTabKey || tab.tabKey,
174
+ reservedAt: Date.now(),
175
+ }));
176
+ return;
60
177
  }
61
- socketMeta.delete(tab.socket);
178
+ tabsByToken.delete(token);
62
179
  }
63
180
 
64
181
  function unpair(token, reason = 'disconnect') {
@@ -66,10 +183,10 @@ export function createAgentBridgeRelayHub(opts = {}) {
66
183
  if (!tab || !tab.pairedPeer) return;
67
184
  const peer = tab.pairedPeer;
68
185
  tab.pairedPeer = null;
186
+ log(`pairing ended token=${redactToken(token)} reason=${reason}`, 'warn');
69
187
  sendJson(tab.socket, { type: PAIR_MSG.UNPAIRED, reason });
70
188
  sendJson(peer, { type: PAIR_MSG.UNPAIRED, reason });
71
- socketMeta.delete(peer);
72
- try { peer.close(); } catch { /* gone */ }
189
+ closePeer(peer);
73
190
  }
74
191
 
75
192
  /**
@@ -86,7 +203,12 @@ export function createAgentBridgeRelayHub(opts = {}) {
86
203
  return;
87
204
  }
88
205
 
206
+ const live = { alive: true, dropReason: null };
207
+ if (typeof socket.ping === 'function') liveness.set(socket, live);
208
+ socket.on('pong', () => { live.alive = true; });
209
+
89
210
  socket.on('message', (raw) => {
211
+ live.alive = true;
90
212
  const msg = parseMessage(typeof raw === 'string' ? raw : String(raw));
91
213
  if (!msg || typeof msg !== 'object') {
92
214
  refuse(socket, 'bad_message', 'Expected JSON object');
@@ -104,14 +226,38 @@ export function createAgentBridgeRelayHub(opts = {}) {
104
226
  refuse(socket, 'bad_token', 'register_tab requires token');
105
227
  return;
106
228
  }
107
- const existing = tabsByToken.get(token);
229
+ const tabKey = secretOrNull(msg.tabKey);
230
+ const existing = liveTab(token);
108
231
  if (existing) {
109
- refuse(socket, 'token_in_use', 'Another tab is already advertising this pairing code');
232
+ // A reconnecting tab can beat the heartbeat to its own stale socket;
233
+ // only the tab that registered the code knows its tabKey. After a
234
+ // drop the entry is a reservation (socket null) for that same key.
235
+ if (!tabKey || existing.tabKey !== tabKey) {
236
+ refuse(socket, 'token_in_use', 'Another tab is already advertising this pairing code');
237
+ return;
238
+ }
239
+ const stale = existing.socket;
240
+ // Closing the bridge window is a user action: the tab sends
241
+ // forgetResume so the same MCP client cannot silent-resume.
242
+ const forgetResume = msg.forgetResume === true;
243
+ const kept = {
244
+ tabKey: existing.tabKey,
245
+ resumeKey: forgetResume ? null : existing.resumeKey,
246
+ resumeTabKey: existing.resumeTabKey || existing.tabKey,
247
+ };
248
+ if (stale && stale !== socket) {
249
+ dropTab(token, 'replaced_by_reconnect');
250
+ liveness.delete(stale);
251
+ try { (stale.terminate || stale.close).call(stale); } catch { /* gone */ }
252
+ }
253
+ tabsByToken.set(token, { ...emptyEntry(token, kept), socket });
254
+ socketMeta.set(socket, { role: 'tab', token });
255
+ log(`tab registered token=${redactToken(token)} (reconnect)`);
110
256
  return;
111
257
  }
112
- tabsByToken.set(token, { socket, token, pairedPeer: null, pendingPeer: null });
258
+ tabsByToken.set(token, { ...emptyEntry(token, { tabKey }), socket });
113
259
  socketMeta.set(socket, { role: 'tab', token });
114
- log(`tab registered token=${token}`);
260
+ log(`tab registered token=${redactToken(token)}`);
115
261
  return;
116
262
  }
117
263
 
@@ -121,8 +267,8 @@ export function createAgentBridgeRelayHub(opts = {}) {
121
267
  return;
122
268
  }
123
269
  const token = typeof msg.token === 'string' ? msg.token.trim().toUpperCase() : '';
124
- const tab = tabsByToken.get(token);
125
- if (!tab) {
270
+ const tab = liveTab(token);
271
+ if (!tab || !tab.socket) {
126
272
  refuse(socket, 'unknown_token', 'No SurfCAD tab is advertising this pairing code');
127
273
  return;
128
274
  }
@@ -134,10 +280,27 @@ export function createAgentBridgeRelayHub(opts = {}) {
134
280
  refuse(socket, 'pair_pending', 'Tab is already reviewing another pairing request');
135
281
  return;
136
282
  }
137
- tab.pendingPeer = socket;
283
+ const offered = secretOrNull(msg.resume);
284
+ const silentResume = Boolean(
285
+ offered
286
+ && tab.resumeKey
287
+ && offered === tab.resumeKey
288
+ && tab.tabKey
289
+ && tab.resumeTabKey
290
+ && tab.tabKey === tab.resumeTabKey,
291
+ );
138
292
  socketMeta.set(socket, { role: 'peer', token });
293
+ if (silentResume) {
294
+ tab.pendingPeer = null;
295
+ tab.pairedPeer = socket;
296
+ sendJson(tab.socket, { type: PAIR_MSG.PAIRED, token, resume: true });
297
+ sendJson(socket, { type: PAIR_MSG.PAIRED, token, resumeKey: tab.resumeKey });
298
+ log(`paired token=${redactToken(token)} (resume)`);
299
+ return;
300
+ }
301
+ tab.pendingPeer = socket;
139
302
  sendJson(tab.socket, { type: PAIR_MSG.PAIR_REQUEST, token });
140
- log(`pair request token=${token}`);
303
+ log(`pair request token=${redactToken(token)}`);
141
304
  return;
142
305
  }
143
306
 
@@ -146,7 +309,7 @@ export function createAgentBridgeRelayHub(opts = {}) {
146
309
  return;
147
310
  }
148
311
 
149
- const tab = tabsByToken.get(meta.token);
312
+ const tab = liveTab(meta.token);
150
313
  if (!tab) {
151
314
  refuse(socket, 'session_gone', 'Pairing session ended');
152
315
  return;
@@ -162,11 +325,16 @@ export function createAgentBridgeRelayHub(opts = {}) {
162
325
  sendJson(socket, { type: PAIR_MSG.ERROR, code: 'no_request', message: 'No pairing request to approve' });
163
326
  return;
164
327
  }
328
+ const resumeKey = secretOrNull(msg.resumeKey);
165
329
  tab.pendingPeer = null;
166
330
  tab.pairedPeer = peer;
331
+ tab.resumeKey = resumeKey;
332
+ tab.resumeTabKey = tab.tabKey;
167
333
  sendJson(socket, { type: PAIR_MSG.PAIRED, token: meta.token });
168
- sendJson(peer, { type: PAIR_MSG.PAIRED, token: meta.token });
169
- log(`paired token=${meta.token}`);
334
+ sendJson(peer, resumeKey
335
+ ? { type: PAIR_MSG.PAIRED, token: meta.token, resumeKey }
336
+ : { type: PAIR_MSG.PAIRED, token: meta.token });
337
+ log(`paired token=${redactToken(meta.token)}`);
170
338
  return;
171
339
  }
172
340
 
@@ -179,8 +347,7 @@ export function createAgentBridgeRelayHub(opts = {}) {
179
347
  tab.pendingPeer = null;
180
348
  if (peer) {
181
349
  sendJson(peer, { type: PAIR_MSG.ERROR, code: 'pair_rejected', message: 'Pairing rejected in SurfCAD' });
182
- socketMeta.delete(peer);
183
- try { peer.close(); } catch { /* gone */ }
350
+ closePeer(peer);
184
351
  }
185
352
  return;
186
353
  }
@@ -219,17 +386,19 @@ export function createAgentBridgeRelayHub(opts = {}) {
219
386
  refuse(socket, 'unknown_type', `Unknown message type: ${msg.type}`);
220
387
  });
221
388
 
222
- socket.on('close', () => {
389
+ socket.on('close', (code, reason) => {
390
+ liveness.delete(socket);
223
391
  const m = socketMeta.get(socket);
224
392
  if (!m) return;
393
+ const why = live.dropReason || closeReason(code, reason);
225
394
  const tabEntry = tabsByToken.get(m.token);
226
395
  if (!tabEntry) {
227
396
  socketMeta.delete(socket);
228
397
  return;
229
398
  }
230
399
  if (m.role === 'tab') {
231
- dropTab(m.token);
232
- log(`tab closed token=${m.token}`);
400
+ if (tabEntry.socket === socket) dropTab(m.token, why);
401
+ else socketMeta.delete(socket);
233
402
  return;
234
403
  }
235
404
  if (tabEntry.pendingPeer === socket) {
@@ -238,26 +407,53 @@ export function createAgentBridgeRelayHub(opts = {}) {
238
407
  return;
239
408
  }
240
409
  if (tabEntry.pairedPeer === socket) {
241
- unpair(m.token, 'peer_disconnected');
410
+ unpair(m.token, live.dropReason ? `peer_${live.dropReason}` : 'peer_disconnected');
242
411
  }
243
412
  socketMeta.delete(socket);
244
413
  });
245
414
  }
246
415
 
416
+ /**
417
+ * One heartbeat sweep: terminate sockets that did not answer the previous
418
+ * ping, then ping the rest. Call every `heartbeatMs`.
419
+ */
420
+ function heartbeat() {
421
+ for (const [socket, live] of liveness) {
422
+ if (!live.alive) {
423
+ live.dropReason = 'heartbeat_timeout';
424
+ liveness.delete(socket);
425
+ try { (socket.terminate || socket.close).call(socket); } catch { /* gone */ }
426
+ continue;
427
+ }
428
+ live.alive = false;
429
+ try { socket.ping?.(); } catch { /* gone; next sweep terminates */ }
430
+ }
431
+ }
432
+
247
433
  function disconnectToken(token) {
248
- const tab = tabsByToken.get(token);
434
+ const tab = liveTab(token);
249
435
  if (!tab) return;
250
436
  unpair(token, 'tab_disconnect');
251
437
  try { tab.socket.close(); } catch { /* gone */ }
252
- dropTab(token);
438
+ dropTab(token, 'disconnect_requested');
439
+ }
440
+
441
+ function dispose() {
442
+ if (sweepTimer) clearInterval(sweepTimer);
253
443
  }
254
444
 
255
445
  return {
256
446
  attachSocket,
257
447
  disconnectToken,
448
+ heartbeat,
449
+ dispose,
258
450
  /** @param {string} token */
259
451
  hasTab(token) {
260
- return tabsByToken.has(token);
452
+ return liveTab(token) != null;
453
+ },
454
+ /** @param {string} token */
455
+ isPaired(token) {
456
+ return liveTab(token)?.pairedPeer != null;
261
457
  },
262
458
  PAIR_MSG,
263
459
  };
@@ -1,13 +1,15 @@
1
1
  /**
2
2
  * Loopback HTTP/WebSocket server for the M1 agent-bridge relay.
3
3
  * Binds 127.0.0.1 only. Handles CORS / Private Network Access preflight for
4
- * https://surfcad.com → ws://127.0.0.1 upgrades.
4
+ * https://surfcad.com → ws://127.0.0.1 upgrades, and serves the `/bridge`
5
+ * popup page for browsers that block that upgrade (Safari).
5
6
  */
6
7
 
7
8
  import { createServer } from 'node:http';
8
9
  import { WebSocket, WebSocketServer } from 'ws';
9
10
  import { createAgentBridgeRelayHub } from './relayHub.mjs';
10
- import { isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
11
+ import { extraAllowedOrigins, isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
12
+ import { handleBridgeRequest } from './bridgePage.mjs';
11
13
 
12
14
  export const DEFAULT_RELAY_PORT = 17341;
13
15
 
@@ -65,19 +67,39 @@ export function probeRelayAtUrl(url, timeoutMs = 1500) {
65
67
  });
66
68
  }
67
69
 
70
+ export const DEFAULT_HEARTBEAT_MS = 5000;
71
+
72
+ function parseHeartbeatMs(value) {
73
+ const n = Number(value);
74
+ return Number.isFinite(n) && n >= 50 ? n : DEFAULT_HEARTBEAT_MS;
75
+ }
76
+
77
+ /**
78
+ * Drops and heartbeat timeouts always go to stderr (stdout is the MCP stdio
79
+ * channel); routine pairing lines only with SURFCAD_AGENT_BRIDGE_WS_VERBOSE=1.
80
+ *
81
+ * @param {string} line
82
+ * @param {'info' | 'warn'} [level]
83
+ */
84
+ export function defaultRelayLog(line, level = 'info') {
85
+ if (level !== 'warn' && process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE !== '1') return;
86
+ console.error(`${new Date().toISOString()} [surfcad-relay] ${level === 'warn' ? 'WARN ' : ''}${line}`);
87
+ }
88
+
68
89
  /**
69
- * @param {{ port?: number, host?: string, onReady?: (url: string) => void, onLog?: (line: string) => void }} [options]
90
+ * @param {{
91
+ * port?: number,
92
+ * host?: string,
93
+ * heartbeatMs?: number,
94
+ * onReady?: (url: string) => void,
95
+ * onLog?: (line: string, level: 'info' | 'warn') => void,
96
+ * }} [options]
70
97
  */
71
98
  export function startAgentBridgeRelay(options = {}) {
72
99
  const host = options.host || '127.0.0.1';
73
100
  const port = options.port ?? parsePort(process.env.SURFCAD_AGENT_BRIDGE_WS_PORT);
74
- const hub = createAgentBridgeRelayHub({
75
- onLog: options.onLog || ((line) => {
76
- if (process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE === '1') {
77
- console.log(`[agent-bridge-ws] ${line}`);
78
- }
79
- }),
80
- });
101
+ const heartbeatMs = options.heartbeatMs ?? parseHeartbeatMs(process.env.SURFCAD_AGENT_BRIDGE_HEARTBEAT_MS);
102
+ const hub = createAgentBridgeRelayHub({ onLog: options.onLog || defaultRelayLog });
81
103
 
82
104
  const server = createServer((req, res) => {
83
105
  const origin = req.headers.origin;
@@ -99,6 +121,12 @@ export function startAgentBridgeRelay(options = {}) {
99
121
  return;
100
122
  }
101
123
 
124
+ const bound = server.address();
125
+ const boundPort = bound && typeof bound === 'object' ? bound.port : port;
126
+ if (handleBridgeRequest(req, res, { port: boundPort, extraOrigins: [...extraAllowedOrigins()] })) {
127
+ return;
128
+ }
129
+
102
130
  res.writeHead(404, cors);
103
131
  res.end();
104
132
  });
@@ -130,13 +158,26 @@ export function startAgentBridgeRelay(options = {}) {
130
158
  hub.attachSocket({
131
159
  send: (data) => { ws.send(data); },
132
160
  close: () => { ws.close(); },
133
- on: (event, cb) => { ws.on(event, cb); },
161
+ ping: () => { ws.ping(); },
162
+ terminate: () => { ws.terminate(); },
163
+ on: (event, cb) => {
164
+ if (event === 'close') {
165
+ ws.on('close', (code, reason) => cb(code, reason?.toString?.() || ''));
166
+ return;
167
+ }
168
+ ws.on(event, cb);
169
+ },
134
170
  remoteAddress: remote,
135
171
  origin,
136
172
  });
137
173
  });
138
174
  });
139
175
 
176
+ const heartbeatTimer = setInterval(() => { hub.heartbeat(); }, heartbeatMs);
177
+ if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
178
+ wss.on('close', () => { clearInterval(heartbeatTimer); });
179
+ server.on('close', () => { clearInterval(heartbeatTimer); });
180
+
140
181
  return new Promise((resolve, reject) => {
141
182
  server.listen(port, host, () => {
142
183
  const bound = server.address();
@@ -194,6 +235,7 @@ export async function ensureAgentBridgeRelay(options = {}) {
194
235
  * @param {{ server?: import('node:http').Server | null, wss?: import('ws').WebSocketServer | null, port?: number, ownsServer?: boolean } | null | undefined} relay
195
236
  */
196
237
  export function stopAgentBridgeRelay(relay) {
238
+ relay?.hub?.dispose?.();
197
239
  if (!relay || !relay.ownsServer) {
198
240
  return Promise.resolve();
199
241
  }
@@ -202,6 +244,9 @@ export function stopAgentBridgeRelay(relay) {
202
244
  const wss = relay.wss;
203
245
  const server = relay.server;
204
246
  if (wss) {
247
+ for (const client of wss.clients) {
248
+ try { client.terminate(); } catch { /* gone */ }
249
+ }
205
250
  wss.close(() => {
206
251
  if (server) server.close(finish);
207
252
  else finish();
package/src/errors.mjs CHANGED
@@ -1,10 +1,14 @@
1
+ export const RECONNECT_HINT = 'Open SurfCAD in Chrome and keep the tab open; it will reconnect.';
2
+
1
3
  /**
2
- * @param {{ code?: string, message?: string, details?: unknown }} err
4
+ * @param {{ code?: string, message?: string, details?: unknown, hint?: string, retryable?: boolean }} err
3
5
  */
4
6
  export function formatBridgeError(err) {
5
7
  const code = err?.code || 'bridge_error';
6
8
  const message = err?.message || 'Bridge call failed';
7
9
  const payload = { code, message };
10
+ if (err?.hint) payload.hint = err.hint;
11
+ if (err?.retryable !== undefined) payload.retryable = err.retryable;
8
12
  if (err?.details !== undefined) payload.details = err.details;
9
13
  return payload;
10
14
  }
@@ -13,9 +17,28 @@ export function notPairedError() {
13
17
  return {
14
18
  code: 'not_paired',
15
19
  message: 'Not paired to a SurfCAD tab. Set SURFCAD_PAIRING_CODE or call the pair tool, then click Allow in the app.',
20
+ hint: pairingEnvHint(),
16
21
  };
17
22
  }
18
23
 
24
+ /**
25
+ * @param {string} [reason]
26
+ */
27
+ export function pairingLostError(reason) {
28
+ const why = reason ? ` (${reason})` : '';
29
+ return Object.assign(
30
+ new Error(`Lost the connection to the SurfCAD tab${why}. Reconnecting in the background; retry in a few seconds.`),
31
+ { code: 'pairing_lost', hint: RECONNECT_HINT, retryable: true },
32
+ );
33
+ }
34
+
35
+ export function pairPendingError() {
36
+ return Object.assign(
37
+ new Error('Waiting for Allow in SurfCAD. Click Allow in the app, then retry.'),
38
+ { code: 'pair_pending', hint: 'The pairing request is still open in the SurfCAD tab.', retryable: true },
39
+ );
40
+ }
41
+
19
42
  export function pairingEnvHint() {
20
43
  return 'Copy the 6-character code from SurfCAD → Local agent → Show pairing code.';
21
44
  }
@@ -5,20 +5,30 @@ import { WebSocket } from 'ws';
5
5
  import { PAIR_MSG } from './relayMessages.mjs';
6
6
 
7
7
  /**
8
+ * Resolves once the tab approves. `resume` is the key the tab handed out on
9
+ * the previous approval; the hub matches it for that tabKey and auto-pairs
10
+ * without putting the secret on PAIR_REQUEST.
11
+ *
8
12
  * @param {string} url
9
13
  * @param {string} token
10
- * @returns {Promise<WebSocket>}
14
+ * @param {{ resume?: string | null }} [options]
15
+ * @returns {Promise<{ ws: WebSocket, resumeKey: string | null }>}
11
16
  */
12
- export function connectPeer(url, token) {
17
+ export function connectPeer(url, token, options = {}) {
13
18
  return new Promise((resolve, reject) => {
14
19
  const ws = new WebSocket(url);
20
+ let settled = false;
15
21
  const fail = (err) => {
22
+ if (settled) return;
23
+ settled = true;
16
24
  ws.removeAllListeners('message');
17
25
  try { ws.close(); } catch { /* noop */ }
18
26
  reject(err instanceof Error ? err : new Error(String(err)));
19
27
  };
20
28
  ws.once('open', () => {
21
- ws.send(JSON.stringify({ type: PAIR_MSG.PAIR, token: token.trim().toUpperCase() }));
29
+ const pair = { type: PAIR_MSG.PAIR, token: token.trim().toUpperCase() };
30
+ if (options.resume) pair.resume = options.resume;
31
+ ws.send(JSON.stringify(pair));
22
32
  });
23
33
  ws.on('message', (raw) => {
24
34
  let msg;
@@ -29,14 +39,25 @@ export function connectPeer(url, token) {
29
39
  return;
30
40
  }
31
41
  if (msg?.type === PAIR_MSG.PAIRED) {
42
+ settled = true;
32
43
  ws.removeAllListeners('message');
33
- resolve(ws);
44
+ ws.removeAllListeners('close');
45
+ resolve({ ws, resumeKey: typeof msg.resumeKey === 'string' ? msg.resumeKey : null });
34
46
  return;
35
47
  }
36
48
  if (msg?.type === PAIR_MSG.ERROR || (msg?.code && !msg?.id)) {
37
- fail(new Error(msg.message || msg.code || 'Pairing failed'));
49
+ fail(Object.assign(new Error(msg.message || msg.code || 'Pairing failed'), {
50
+ code: typeof msg.code === 'string' ? msg.code : 'pair_failed',
51
+ }));
38
52
  }
39
53
  });
40
- ws.once('error', fail);
54
+ ws.once('error', (err) => {
55
+ fail(Object.assign(err instanceof Error ? err : new Error(String(err)), {
56
+ code: err?.code === 'ECONNREFUSED' ? 'relay_unreachable' : (err?.code || 'relay_error'),
57
+ }));
58
+ });
59
+ ws.once('close', () => {
60
+ fail(Object.assign(new Error('Relay closed the connection before pairing finished'), { code: 'pair_cancelled' }));
61
+ });
41
62
  });
42
63
  }