simcast-host 0.0.0-stage → 0.9.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,121 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { DEFAULT_PORT } from '../common.js';
6
+
7
+ export const agentHome = process.env.SIMCAST_HOME || path.join(os.homedir(), '.simcast');
8
+ export const agentConfigFile = path.join(agentHome, 'agent.json');
9
+
10
+ // base64url can start with "-", which a command line reads as an option, so
11
+ // draw again until it doesn't.
12
+ export function newToken() {
13
+ let token;
14
+ do token = crypto.randomBytes(24).toString('base64url');
15
+ while (token.startsWith('-'));
16
+ return token;
17
+ }
18
+
19
+ // agent.json. Keys:
20
+ // - port
21
+ // - agentId: the Mac's identity, 16 random bytes in base64url (created at first start)
22
+ // - adminToken: for the Mac-local /admin API, 24 random bytes (created at first start)
23
+ // - bonjour: advertise with dns-sd (default true)
24
+ // - extraPath (see readAgentConfigSafe)
25
+ export function loadAgentConfig() {
26
+ const file = agentConfigFile;
27
+ fs.mkdirSync(agentHome, { recursive: true });
28
+ let cfg = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
29
+ let changed = false;
30
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) {
31
+ cfg = { port: DEFAULT_PORT };
32
+ changed = true;
33
+ }
34
+ if (typeof cfg.agentId !== 'string' || !cfg.agentId) {
35
+ cfg.agentId = crypto.randomBytes(16).toString('base64url');
36
+ changed = true;
37
+ }
38
+ if (typeof cfg.adminToken !== 'string' || !cfg.adminToken) {
39
+ cfg.adminToken = newToken();
40
+ changed = true;
41
+ }
42
+ if (cfg.bonjour === undefined) {
43
+ cfg.bonjour = true;
44
+ changed = true;
45
+ }
46
+ if (changed) saveAgentConfig(cfg);
47
+ return cfg;
48
+ }
49
+
50
+ // Writes agent.json (0600) through a temp file, so a reader never sees half of it.
51
+ export function saveAgentConfig(cfg) {
52
+ fs.mkdirSync(agentHome, { recursive: true });
53
+ const tmp = `${agentConfigFile}.${process.pid}.tmp`;
54
+ fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { mode: 0o600 });
55
+ try { fs.chmodSync(tmp, 0o600); } catch { /* not on Windows */ }
56
+ fs.renameSync(tmp, agentConfigFile);
57
+ }
58
+
59
+ // The Mac's name for pairing, /health and Bonjour: macinfo.computerName()
60
+ // (`scutil --get ComputerName`), else os.hostname() without ".local". Asked
61
+ // once per process (a promise).
62
+ const hostName = () => os.hostname().replace(/\.local$/i, '') || 'Mac';
63
+ let macNameAsked = null;
64
+ let macNameKnown = null;
65
+ export function macName() {
66
+ macNameAsked ??= (async () => {
67
+ let name = null;
68
+ try {
69
+ // macinfo.js imports exec.js, which imports this module: load it when first needed.
70
+ const { computerName } = await import('./macinfo.js');
71
+ name = await computerName();
72
+ } catch { /* no scutil */ }
73
+ macNameKnown = String(name || '').replace(/[\r\n]/g, ' ').trim().slice(0, 63) || hostName();
74
+ return macNameKnown;
75
+ })();
76
+ return macNameAsked;
77
+ }
78
+
79
+ // macName() without waiting: the answer once known, else the hostname.
80
+ export const macNameNow = () => macNameKnown || hostName();
81
+
82
+ // For readers that must not create agent.json or a token as a side effect
83
+ // (agentEnv, CLI checks). Missing or unreadable means {}. Optional keys:
84
+ // extraPath, a PATH-style string or an array of folders put first on the agent's PATH.
85
+ export function readAgentConfigSafe() {
86
+ try {
87
+ const cfg = JSON.parse(fs.readFileSync(agentConfigFile, 'utf8'));
88
+ return cfg && typeof cfg === 'object' ? cfg : {};
89
+ } catch {
90
+ return {};
91
+ }
92
+ }
93
+
94
+ export function projectPaths(id) {
95
+ const base = path.join(agentHome, 'projects', id);
96
+ return {
97
+ base,
98
+ src: path.join(base, 'src'),
99
+ derived: path.join(base, 'DerivedData'),
100
+ builds: path.join(base, 'builds'),
101
+ logs: path.join(base, 'logs'),
102
+ state: path.join(base, 'state.json'),
103
+ };
104
+ }
105
+
106
+ export function loadState(id) {
107
+ const p = projectPaths(id);
108
+ try {
109
+ return JSON.parse(fs.readFileSync(p.state, 'utf8'));
110
+ } catch {
111
+ return { manifest: {}, pending: [], lockHash: null, lastRun: null };
112
+ }
113
+ }
114
+
115
+ export function saveState(id, state) {
116
+ const p = projectPaths(id);
117
+ fs.mkdirSync(p.base, { recursive: true });
118
+ const tmp = `${p.state}.tmp`;
119
+ fs.writeFileSync(tmp, JSON.stringify(state));
120
+ fs.renameSync(tmp, p.state);
121
+ }
@@ -0,0 +1,464 @@
1
+ // The tunnel (docs/protocol.md, "Tunnel"): each PC holds one /tunnel control
2
+ // WebSocket; the agent listens on the Mac's 127.0.0.1 and ::1 for the PC's
3
+ // ports, and every accepted TCP connection becomes one PC-opened
4
+ // GET /tunnel/data?id= upgraded to a raw TCP stream (Upgrade: simcast-tcp).
5
+ // The agent never opens a connection to the PC.
6
+ //
7
+ // State, per PC (by client id):
8
+ // control the live /tunnel WebSocket, or null (lost: the grace runs)
9
+ // ports port -> { port, pcPort, macPort, name, servers, listening, error, connections }
10
+ // pending accepted Mac-side sockets, paused, waiting for their data stream
11
+ // streams joined pairs { mac, pc } (the Mac-side socket and the upgraded one)
12
+ // A PC's entry lives while it has a control connection or is in its grace.
13
+ import crypto from 'node:crypto';
14
+ import net from 'node:net';
15
+ import { PROTOCOL, VERSION, heartbeat } from '../common.js';
16
+ import * as awake from './awake.js';
17
+
18
+ // Limits (plan 2.6).
19
+ export const MAX_PORTS = 16;
20
+ export const MAX_CONNECTIONS = 256; // waiting or open, per PC
21
+ export const PENDING_MS = 5000; // an accepted connection waits this long for its data stream
22
+ export const GRACE_MS = 10000; // listeners stay up this long after the control connection is lost
23
+ // Test-only: macPort = port + offset (0 in real use).
24
+ export const portOffset = () => Number(process.env.SIMCAST_TUNNEL_PORT_OFFSET) || 0;
25
+ // Test-only: shorter timers (SIMCAST_TUNNEL_PENDING_MS, SIMCAST_TUNNEL_GRACE_MS).
26
+ const msFromEnv = (name, fallback) => {
27
+ const ms = Number(process.env[name]);
28
+ return Number.isFinite(ms) && ms > 0 ? ms : fallback;
29
+ };
30
+ const pendingMs = () => msFromEnv('SIMCAST_TUNNEL_PENDING_MS', PENDING_MS);
31
+ const graceMs = () => msFromEnv('SIMCAST_TUNNEL_GRACE_MS', GRACE_MS);
32
+
33
+ const UPGRADE = 'simcast-tcp';
34
+ const EXPIRED_KEEP_MS = 60_000; // an expired id answers 410 (not 404) this long
35
+ const EXPIRED_MAX = 4096;
36
+
37
+ const log = (msg) => console.log(`[${new Date().toISOString()}] tunnel: ${msg}`);
38
+
39
+ const pcs = new Map(); // client id -> PC state
40
+ const pendingById = new Map(); // id -> pending entry (of any PC)
41
+ const expired = new Map(); // id -> { clientId, at }
42
+ let agentPort = null; // learnt from the control connection's socket
43
+
44
+ function pcFor(client) {
45
+ let pc = pcs.get(client.id);
46
+ if (!pc) {
47
+ pc = { id: client.id, name: client.name, control: null, ports: new Map(), pending: new Set(), streams: new Set(), graceTimer: null, queue: Promise.resolve(), closed: false, limitLogged: false };
48
+ pcs.set(client.id, pc);
49
+ }
50
+ pc.name = client.name || pc.name;
51
+ return pc;
52
+ }
53
+
54
+ function send(ctl, msg) {
55
+ if (!ctl || ctl.ws.readyState !== 1) return;
56
+ try { ctl.ws.send(JSON.stringify(msg)); } catch { /* closing */ }
57
+ }
58
+
59
+ // A reset (RST) when the socket still has a connection, else a plain destroy.
60
+ function reset(socket) {
61
+ if (!socket || socket.destroyed) return;
62
+ try {
63
+ socket.resetAndDestroy();
64
+ } catch {
65
+ socket.destroy();
66
+ }
67
+ }
68
+
69
+ function remember(id, clientId) {
70
+ const now = Date.now();
71
+ expired.set(id, { clientId, at: now });
72
+ if (expired.size > EXPIRED_MAX) {
73
+ for (const [key, v] of expired) {
74
+ if (expired.size <= EXPIRED_MAX / 2 && now - v.at < EXPIRED_KEEP_MS) break;
75
+ expired.delete(key);
76
+ }
77
+ }
78
+ }
79
+
80
+ // ---- the control connection ------------------------------------------------
81
+
82
+ // A PC's /tunnel control WebSocket, after the upgrade passed the auth checks.
83
+ // `client` is { id, name }; `protocol` is the negotiated protocol for the hello.
84
+ // `agentPort` (optional) is the agent's own port, else taken from the socket.
85
+ // A newer /tunnel from the same PC closes this one with 4009 and takes over its
86
+ // listeners, pending connections and streams. Heartbeat as /session.
87
+ export function attachControl(ws, client, { protocol = PROTOCOL, agentPort: port } = {}) {
88
+ agentPort = Number(port) || ws._socket?.localPort || agentPort;
89
+ const pc = pcFor(client);
90
+ pc.closed = false;
91
+ const old = pc.control;
92
+ const ctl = { ws };
93
+ pc.control = ctl;
94
+ if (pc.graceTimer) {
95
+ clearTimeout(pc.graceTimer);
96
+ pc.graceTimer = null;
97
+ log(`${pc.name} is back`);
98
+ } else if (old) {
99
+ log(`${pc.name} opened a new tunnel; closing the old one`);
100
+ } else {
101
+ log(`${pc.name} connected`);
102
+ }
103
+ if (old) {
104
+ try { old.ws.close(4009, 'Replaced by a newer tunnel from this PC'); } catch { /* gone */ }
105
+ }
106
+
107
+ heartbeat(ws);
108
+ ws.on('error', () => {});
109
+ ws.on('message', (data, isBinary) => onMessage(pc, ctl, data, isBinary));
110
+ ws.on('close', () => {
111
+ if (pc.control !== ctl) return; // replaced, or closed by closeFor
112
+ pc.control = null;
113
+ lost(pc);
114
+ });
115
+
116
+ send(ctl, { t: 'hello', version: VERSION, protocol });
117
+ send(ctl, portsMessage(pc));
118
+ // Connections that waited (during the grace, or announced to a replaced
119
+ // control) are announced to this one.
120
+ for (const entry of pc.pending) announce(entry);
121
+ }
122
+
123
+ function lost(pc) {
124
+ const ms = graceMs();
125
+ log(`${pc.name} lost its tunnel; keeping its ports for ${Math.round(ms / 1000)} s`);
126
+ pc.graceTimer = setTimeout(() => {
127
+ pc.graceTimer = null;
128
+ if (pc.control) return;
129
+ log(`${pc.name}'s tunnel didn't come back; closing its ports`);
130
+ teardown(pc);
131
+ }, ms);
132
+ pc.graceTimer.unref();
133
+ }
134
+
135
+ function onMessage(pc, ctl, data, isBinary) {
136
+ if (pc.control !== ctl) return;
137
+ let msg;
138
+ try {
139
+ if (isBinary) throw new Error('binary');
140
+ msg = JSON.parse(data.toString('utf8'));
141
+ } catch {
142
+ return send(ctl, { t: 'error', msg: 'Messages on /tunnel are JSON text.' });
143
+ }
144
+ if (!msg || typeof msg !== 'object' || typeof msg.t !== 'string') return send(ctl, { t: 'error', msg: 'A message needs a type in "t".' });
145
+ if (msg.t === 'ports') {
146
+ pc.queue = pc.queue.then(() => reconcile(pc, msg.ports)).catch((err) => log(`ports: ${err.message}`));
147
+ } else if (msg.t === 'refused') {
148
+ const entry = pendingById.get(String(msg.id));
149
+ if (entry && entry.pc === pc) fail(entry, typeof msg.msg === 'string' ? msg.msg.slice(0, 200) : null);
150
+ }
151
+ // Unknown types are ignored (newer PCs).
152
+ }
153
+
154
+ // ---- ports -----------------------------------------------------------------
155
+
156
+ const validPort = (v) => Number.isInteger(v) && v >= 1 && v <= 65535;
157
+
158
+ function portsMessage(pc) {
159
+ return {
160
+ t: 'ports',
161
+ ports: [...pc.ports.values()].map(({ port, pcPort, macPort, listening: up, error }) => (
162
+ up ? { port, pcPort, macPort, listening: true } : { port, pcPort, macPort, listening: false, error })),
163
+ };
164
+ }
165
+
166
+ // The PC's whole wanted set: opens new ports, closes removed ones (their open
167
+ // connections keep going), retries ports that failed, then reports.
168
+ async function reconcile(pc, list) {
169
+ if (pc.closed) return;
170
+ const errors = [];
171
+ const wanted = new Map();
172
+ if (!Array.isArray(list)) {
173
+ errors.push('"ports" must be a list.');
174
+ } else {
175
+ for (const item of list) {
176
+ const port = Number(item?.port);
177
+ const pcPort = item?.pcPort === undefined ? port : Number(item.pcPort);
178
+ if (!validPort(port) || !validPort(pcPort)) {
179
+ errors.push(`Not a port: ${JSON.stringify(item?.port ?? item)}.`);
180
+ continue;
181
+ }
182
+ if (wanted.has(port)) continue;
183
+ if (wanted.size >= MAX_PORTS) {
184
+ errors.push(`At most ${MAX_PORTS} ports can be tunnelled; port ${port} was left out.`);
185
+ continue;
186
+ }
187
+ wanted.set(port, { port, pcPort, name: typeof item.name === 'string' ? item.name.slice(0, 20) : 'reverse' });
188
+ }
189
+ }
190
+ for (const msg of errors) send(pc.control, { t: 'error', msg });
191
+ if (!Array.isArray(list)) return;
192
+
193
+ for (const [port, p] of pc.ports) {
194
+ if (wanted.has(port)) continue;
195
+ pc.ports.delete(port);
196
+ closePort(p);
197
+ log(`${pc.name}: closed port ${p.macPort}`);
198
+ }
199
+ const opening = [];
200
+ for (const want of wanted.values()) {
201
+ const p = pc.ports.get(want.port);
202
+ if (p) {
203
+ p.pcPort = want.pcPort;
204
+ p.name = want.name;
205
+ if (!p.listening) opening.push(openPort(pc, p));
206
+ } else {
207
+ const fresh = { ...want, macPort: want.port + portOffset(), servers: [], listening: false, error: null, connections: 0, closed: false };
208
+ pc.ports.set(want.port, fresh);
209
+ opening.push(openPort(pc, fresh));
210
+ }
211
+ }
212
+ await Promise.all(opening);
213
+ if (!pc.closed) send(pc.control, portsMessage(pc));
214
+ }
215
+
216
+ function closePort(p) {
217
+ p.closed = true;
218
+ p.listening = false;
219
+ for (const s of p.servers) s.close();
220
+ p.servers = [];
221
+ }
222
+
223
+ function listen(server, host, port) {
224
+ return new Promise((resolve, reject) => {
225
+ const onError = (err) => reject(err);
226
+ server.once('error', onError);
227
+ server.listen({ host, port, exclusive: true }, () => {
228
+ server.off('error', onError);
229
+ server.on('error', (err) => log(`listener ${host}:${port}: ${err.message}`));
230
+ resolve();
231
+ });
232
+ });
233
+ }
234
+
235
+ // macOS lets a socket bind 127.0.0.1:<p> while another program listens on
236
+ // *:<p> (Node sets SO_REUSEADDR), so EADDRINUSE alone misses a Metro already
237
+ // running on the Mac. A quick connect finds it. Not on other systems: there the
238
+ // bind fails as it should, and Windows takes about a second to refuse.
239
+ function answers(port) {
240
+ if (process.platform !== 'darwin') return Promise.resolve(false);
241
+ return new Promise((resolve) => {
242
+ const s = net.connect({ host: '127.0.0.1', port });
243
+ const done = (yes) => { s.destroy(); resolve(yes); };
244
+ s.setTimeout(300, () => done(false));
245
+ s.once('connect', () => done(true));
246
+ s.once('error', () => done(false));
247
+ });
248
+ }
249
+
250
+ const errorText = (macPort, err) => (
251
+ err.code === 'EADDRINUSE' ? `Port ${macPort} is in use on the Mac.`
252
+ : err.code === 'EACCES' ? 'Ports below 1024 can\'t be used on the Mac.'
253
+ : `Port ${macPort} can't be used on the Mac (${err.code || err.message}).`);
254
+
255
+ async function openPort(pc, p) {
256
+ const { port, macPort } = p;
257
+ p.error = null;
258
+ if (port < 1024 || macPort < 1024) p.error = 'Ports below 1024 can\'t be used on the Mac.';
259
+ else if (macPort > 65535) p.error = `Port ${macPort} can't be used on the Mac.`;
260
+ else if (macPort === agentPort) p.error = `Port ${macPort} is the simcast agent's own port.`;
261
+ else if (await answers(macPort)) p.error = `Port ${macPort} is in use on the Mac.`;
262
+ if (p.error) {
263
+ log(`${pc.name}: port ${macPort}: ${p.error}`);
264
+ return;
265
+ }
266
+ const make = () => net.createServer({ pauseOnConnect: true, allowHalfOpen: true }, (sock) => accept(pc, p, sock));
267
+ const v4 = make();
268
+ try {
269
+ await listen(v4, '127.0.0.1', macPort);
270
+ } catch (err) {
271
+ p.error = errorText(macPort, err);
272
+ log(`${pc.name}: port ${macPort}: ${p.error}`);
273
+ return;
274
+ }
275
+ const servers = [v4];
276
+ const v6 = make();
277
+ try {
278
+ await listen(v6, '::1', macPort);
279
+ servers.push(v6);
280
+ } catch (err) {
281
+ // No IPv6 loopback on this Mac (EADDRNOTAVAIL; EAFNOSUPPORT without IPv6 at all).
282
+ if (err.code !== 'EADDRNOTAVAIL' && err.code !== 'EAFNOSUPPORT') {
283
+ v4.close();
284
+ p.error = errorText(macPort, err);
285
+ log(`${pc.name}: port ${macPort} on ::1: ${p.error}`);
286
+ return;
287
+ }
288
+ }
289
+ if (p.closed || pc.closed) { // removed or torn down while listening
290
+ for (const s of servers) s.close();
291
+ return;
292
+ }
293
+ p.servers = servers;
294
+ p.listening = true;
295
+ log(`${pc.name}: localhost:${macPort} on the Mac -> port ${p.pcPort} on the PC`);
296
+ }
297
+
298
+ // ---- connections -----------------------------------------------------------
299
+
300
+ function accept(pc, p, sock) {
301
+ sock.on('error', () => {}); // handled by the stream or the pending entry
302
+ if (pc.closed || pc.pending.size + pc.streams.size >= MAX_CONNECTIONS) {
303
+ if (!pc.limitLogged) log(`${pc.name}: ${MAX_CONNECTIONS} tunnel connections already; refusing more`);
304
+ pc.limitLogged = true;
305
+ sock.destroy();
306
+ return;
307
+ }
308
+ pc.limitLogged = false;
309
+ const entry = { id: crypto.randomBytes(16).toString('base64url'), pc, port: p, sock, timer: null, announcedTo: null };
310
+ pc.pending.add(entry);
311
+ pendingById.set(entry.id, entry);
312
+ p.connections++;
313
+ entry.timer = setTimeout(() => fail(entry, null), pendingMs());
314
+ entry.timer.unref();
315
+ // The Mac-side program gave up before the PC answered.
316
+ sock.once('close', () => { if (pendingById.get(entry.id) === entry) drop(entry); });
317
+ if (pc.control) announce(entry);
318
+ }
319
+
320
+ function announce(entry) {
321
+ const ctl = entry.pc.control;
322
+ if (!ctl || entry.announcedTo === ctl) return;
323
+ entry.announcedTo = ctl;
324
+ send(ctl, { t: 'open', id: entry.id, port: entry.port.macPort, pcPort: entry.port.pcPort });
325
+ }
326
+
327
+ // Takes a pending entry out (the id then answers 410).
328
+ function drop(entry) {
329
+ clearTimeout(entry.timer);
330
+ pendingById.delete(entry.id);
331
+ entry.pc.pending.delete(entry);
332
+ entry.port.connections--;
333
+ remember(entry.id, entry.pc.id);
334
+ }
335
+
336
+ // No data stream in time, or the PC said its port didn't answer.
337
+ function fail(entry, msg) {
338
+ if (pendingById.get(entry.id) !== entry) return;
339
+ drop(entry);
340
+ reset(entry.sock);
341
+ log(`PC's port ${entry.port.pcPort} didn't answer${msg ? ` (${msg})` : ''}`);
342
+ }
343
+
344
+ function refuse(socket, status, msg) {
345
+ socket.write(`HTTP/1.1 ${status}\r\nx-simcast-error: ${encodeURIComponent(msg)}\r\nConnection: close\r\n\r\n`);
346
+ socket.destroy();
347
+ }
348
+
349
+ // GET /tunnel/data?id=<id> with Upgrade: simcast-tcp, after the auth checks
350
+ // (`client` is the PC; the id must belong to a pending connection of that PC,
351
+ // else 404, or 410 once it expired). Answers 101 and joins `socket` (with
352
+ // `head` written first) to the waiting Mac-side connection. Never goes through
353
+ // the WebSocket server.
354
+ export function handleData(req, socket, head, client) {
355
+ socket.on('error', () => {});
356
+ const id = new URL(req.url, 'http://agent').searchParams.get('id') || '';
357
+ const entry = pendingById.get(id);
358
+ if (!entry || entry.pc.id !== client?.id) {
359
+ // Another PC's id is unknown to this one: 404, the same as a made-up id.
360
+ const gone = expired.get(id);
361
+ if (client && gone?.clientId === client.id && Date.now() - gone.at < EXPIRED_KEEP_MS) return refuse(socket, '410 Gone', 'This tunnel connection has expired.');
362
+ return refuse(socket, '404 Not Found', 'No such tunnel connection.');
363
+ }
364
+ if (String(req.headers.upgrade || '').toLowerCase() !== UPGRADE) {
365
+ return refuse(socket, '400 Bad Request', `A tunnel data stream needs "Upgrade: ${UPGRADE}".`);
366
+ }
367
+ const { pc, port: p, sock: mac } = entry;
368
+ clearTimeout(entry.timer);
369
+ pendingById.delete(id);
370
+ pc.pending.delete(entry);
371
+ remember(id, pc.id); // a second upgrade for the same id gets 410
372
+
373
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: ${UPGRADE}\r\n\r\n`);
374
+ socket.setNoDelay(true);
375
+ mac.setNoDelay(true);
376
+ const stream = { mac, pc: socket, release: awake.hold('tunnel') };
377
+ pc.streams.add(stream);
378
+ let open = 2;
379
+ const closed = () => {
380
+ if (--open) return;
381
+ stream.release();
382
+ pc.streams.delete(stream);
383
+ p.connections--;
384
+ };
385
+ join(mac, socket, closed);
386
+ if (head?.length) mac.write(head);
387
+ mac.resume();
388
+ }
389
+
390
+ // Pipes both ways. A FIN becomes end() on the other side (pipe's default, with
391
+ // allowHalfOpen on both); an error, or a close before both directions ended
392
+ // cleanly, becomes a reset of the other side.
393
+ function join(a, b, onClose) {
394
+ for (const [from, to] of [[a, b], [b, a]]) {
395
+ from.pipe(to);
396
+ from.on('error', () => reset(to));
397
+ from.once('close', () => {
398
+ if (!(from.readableEnded && from.writableFinished)) reset(to);
399
+ onClose();
400
+ });
401
+ }
402
+ }
403
+
404
+ // ---- queries and shutdown --------------------------------------------------
405
+
406
+ // GET /tunnel/ports for one PC: { connected, ports: [{ port, pcPort, macPort,
407
+ // listening, error?, connections }] }.
408
+ export function portsFor(clientId) {
409
+ const pc = pcs.get(clientId);
410
+ if (!pc) return { connected: false, ports: [] };
411
+ return {
412
+ connected: !!pc.control,
413
+ ports: [...pc.ports.values()].map(({ port, pcPort, macPort, listening: up, error, connections }) => (
414
+ up ? { port, pcPort, macPort, listening: true, connections } : { port, pcPort, macPort, listening: false, error, connections })),
415
+ };
416
+ }
417
+
418
+ // Whether a Mac port is listening for any PC's tunnel (the recipe's
419
+ // ctx.tunnel.listening(port), for the Metro warning).
420
+ export function listening(port) {
421
+ const n = Number(port);
422
+ for (const pc of pcs.values()) {
423
+ for (const p of pc.ports.values()) if (p.listening && p.macPort === n) return true;
424
+ }
425
+ return false;
426
+ }
427
+
428
+ // Everything of one PC: listeners, pending connections (reset), streams.
429
+ function teardown(pc) {
430
+ pc.closed = true;
431
+ if (pc.graceTimer) clearTimeout(pc.graceTimer);
432
+ pc.graceTimer = null;
433
+ for (const p of pc.ports.values()) closePort(p);
434
+ pc.ports.clear();
435
+ for (const entry of [...pc.pending]) {
436
+ drop(entry);
437
+ reset(entry.sock);
438
+ }
439
+ for (const s of [...pc.streams]) {
440
+ reset(s.mac);
441
+ reset(s.pc);
442
+ }
443
+ if (pcs.get(pc.id) === pc) pcs.delete(pc.id);
444
+ }
445
+
446
+ // Closes one PC's tunnel at once: the control WebSocket with `code` and
447
+ // `reason` (4001 unpaired, 4003 taken over), its listeners, its pending and
448
+ // open data streams.
449
+ export function closeFor(clientId, code, reason) {
450
+ const pc = pcs.get(clientId);
451
+ if (!pc) return;
452
+ const ctl = pc.control;
453
+ pc.control = null;
454
+ if (ctl) {
455
+ try { ctl.ws.close(code, String(reason || '').slice(0, 120)); } catch { /* gone */ }
456
+ }
457
+ log(`${pc.name}: tunnel closed (${code})`);
458
+ teardown(pc);
459
+ }
460
+
461
+ // Agent shutdown: closes every listener and stream (1001 to the control sockets).
462
+ export function stopAll() {
463
+ for (const id of [...pcs.keys()]) closeFor(id, 1001, 'agent stopping');
464
+ }