asyx 0.6.0 → 0.7.0

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 CHANGED
@@ -197,6 +197,33 @@ If the connection of a TCP or UDP tunnel drops (network loss, Asyx server mainte
197
197
  | `ASYX_TUNNEL_RECONNECT_MAX_MS` | Give up after this long without a connection (default 15 minutes) |
198
198
  | `ASYX_TUNNEL_RECONNECT_MAX_DELAY_MS` | Longest wait between attempts (default 5 seconds) |
199
199
 
200
+ ### One tunnel of each kind per address
201
+
202
+ An address runs one HTTP, one TCP and one UDP tunnel at a time. If you start a second tunnel of the same kind for an address that already has a live one — from a second terminal or from another computer — it is refused with the reason, and the running tunnel is not affected:
203
+
204
+ ```text
205
+ ❌ smart.tunnel.asyx.ai already has an HTTP tunnel from this computer since 2:02 PM (serving localhost:8790).
206
+ One address runs one HTTP tunnel at a time.
207
+ Stop that tunnel first, or add --replace to take over.
208
+ ```
209
+
210
+ - **Restarting is fine.** When a tunnel stops or crashes, the address is free again within a second. If you restart faster than that on the same computer, the CLI waits up to 15 seconds for the old tunnel to close.
211
+ - **`--replace`** takes over on purpose (for example when you move a service to another computer). The old tunnel is told who replaced it, stops, and does not reconnect.
212
+ - **`--wait`** keeps trying every 30 seconds instead of exiting, for scripts that should start as soon as the address is free.
213
+ - **`--json`** prints the refusal as `{"error":"address_in_use","kind","hostname","since","machine","sameComputer","localPort","retryable"}` (and `{"error":"replaced",…}` for a tunnel that was taken over).
214
+
215
+ A refused tunnel and a replaced tunnel exit with code **75** ("try again later").
216
+
217
+ **Running a tunnel as a service** (launchd, systemd, a Windows service): add `--wait`. A tunnel started while the address is busy then waits instead of exiting, and if another computer takes the address over with `--replace`, the restarted service waits quietly instead of taking it back — two computers never fight over an address.
218
+
219
+ ```bash
220
+ asyx tunnel --http --port 8790 --to smart.tunnel.asyx.ai --wait
221
+ ```
222
+
223
+ With systemd you can also skip the restart entirely with `RestartPreventExitStatus=75`.
224
+
225
+ Messages name the other computer by its name; they never contain an IP address.
226
+
200
227
  ---
201
228
 
202
229
  ## Command quick reference
@@ -210,11 +237,26 @@ asyx tunnel --http --port <n> [--secgroup <slug>]
210
237
  asyx tunnel --tcp --port <n> [--name <alias>] [--external-port <p>]
211
238
  asyx tunnel --udp --port <n> [--external-port <p>]
212
239
  asyx tunnel --minecraft [--port <n>] [--name <alias>]
240
+ # any tunnel: --to <hostname> --replace --wait --json
213
241
  ```
214
242
 
215
243
  ---
216
244
 
217
- ## What's new in 0.6.0
245
+ ## What's new in 0.7.0
246
+
247
+ **`--to <hostname>`** — every tunnel can name the address it serves, so the console shows a different command for each address and TCP/UDP always use that address's own public port.
248
+
249
+ **One tunnel of each kind per address, with a clear answer** — a second tunnel of the same kind is refused with where the running one is, since when and what it serves, instead of silently taking the address over. `--replace` takes over on purpose (the old tunnel is told and stops), `--wait` keeps trying, and both refusals exit with code 75. See [One tunnel of each kind per address](#one-tunnel-of-each-kind-per-address).
250
+
251
+ **HTTP tunnels recover from a dead connection in about two minutes** — an HTTP tunnel now checks its relay connection every 30 seconds, as TCP and UDP tunnels do, and reconnects when the relay stops answering. Before, a connection that died without a close could leave visitors seeing errors for several minutes. `ASYX_TUNNEL_HEARTBEAT_SEC` changes the interval; `0` turns the check off.
252
+
253
+ **Restarting keeps your TCP/UDP port** — stopping and starting a TCP or UDP tunnel for the same address gives it the same public port again, with or without `--to`. A stopped tunnel's lease is closed promptly, so its address and port are free for the next start.
254
+
255
+ **Quieter with several tunnels on one computer** — tunnels running side by side no longer print each other's replies as warnings.
256
+
257
+ Changes since 0.6.1, in short: `--to`, one tunnel of each kind per address (`--replace`, `--wait`, exit code 75, `--json` refusals), the 30-second HTTP connection check, ports kept across restarts, and quieter output. Everything from 0.6.1 below is still included.
258
+
259
+ ## What's new in 0.6.1
218
260
 
219
261
  **Several devices, each with its own name** — every device on your account gets its own hostname. Pick it with `asyx setup --hostname <name>`, get a generated one with `--random`, or choose it on the approval page, which proposes `<machine>-<account>` and checks names as you type.
220
262
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Asyx tunnel CLI — secure localhost exposure (HTTP, TCP, UDP)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -29,6 +29,7 @@
29
29
  "files": [
30
30
  "bin/",
31
31
  "src/commands/.gitkeep",
32
+ "src/commands/in-use-messages.js",
32
33
  "src/commands/mqtt-broker.js",
33
34
  "src/commands/mqtt.js",
34
35
  "src/commands/name.js",
@@ -0,0 +1,64 @@
1
+ // Story 1.9 r2: what the CLI says when an address already runs a tunnel of this kind, while it waits,
2
+ // and when a newer tunnel took the address over. Never an IP address. Exit code 75 (EX_TEMPFAIL:
3
+ // "try again later") so a service manager can be told not to restart on it.
4
+ import { setReplacedReporter } from '#tunnel-core/mqtt/events/handlers.js';
5
+
6
+ export const EXIT_IN_USE = 75;
7
+ export const tunnelOutput = { json: false, kindFlag: null, rerun: null };
8
+
9
+ function clock(iso) {
10
+ if (!iso) return null;
11
+ const t = new Date(iso);
12
+ if (Number.isNaN(t.getTime())) return null;
13
+ const hm = t.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
14
+ return t.toDateString() === new Date().toDateString() ? hm : `${t.toLocaleDateString([], { day: 'numeric', month: 'short' })} ${hm}`;
15
+ }
16
+
17
+ /** The refusal as lines of text (exported for tests). */
18
+ export function inUseText(d = {}, { rerun = null } = {}) {
19
+ const kind = String(d.kind || 'this').toUpperCase();
20
+ const where = d.sameComputer ? 'this computer' : (d.machine ? `${d.machine}` : 'another connection');
21
+ const since = clock(d.since);
22
+ const serving = d.localPort ? ` (serving localhost:${d.localPort})` : '';
23
+ const addr = d.hostname || 'This address';
24
+ const lines = [
25
+ `${addr} already has a${kind === 'HTTP' ? 'n' : ''} ${kind} tunnel from ${where}${since ? ` since ${since}` : ''}${serving}.`,
26
+ `One address runs one ${kind} tunnel at a time.`,
27
+ ];
28
+ if (d.sameComputer) lines.push('Stop that tunnel first, or add --replace to take over.');
29
+ else lines.push('If you moved this address on purpose, add --replace to take over. If that computer just lost its network, the address frees up within a minute; add --wait to keep trying.');
30
+ if (rerun) lines.push(` ${rerun} --replace`);
31
+ return lines.join('\n');
32
+ }
33
+
34
+ export function exitInUse(d = {}) {
35
+ if (tunnelOutput.json) {
36
+ process.stdout.write(JSON.stringify({ error: 'address_in_use', kind: d.kind ?? null, hostname: d.hostname ?? null, since: d.since ?? null, machine: d.machine ?? null, sameComputer: d.sameComputer === true, localPort: d.localPort ?? null, retryable: true }) + '\n');
37
+ } else {
38
+ process.stderr.write(`❌ ${inUseText(d, { rerun: tunnelOutput.rerun })}\n`);
39
+ }
40
+ process.exit(EXIT_IN_USE);
41
+ }
42
+
43
+ let lastWaitKey = '';
44
+ export function printWaiting({ details = {}, delayMs, sameComputer }) {
45
+ const key = `${sameComputer}|${details.machine}|${details.since}`;
46
+ if (key === lastWaitKey) return; // one line per change
47
+ lastWaitKey = key;
48
+ if (sameComputer) process.stdout.write('⏳ Waiting for the previous tunnel on this computer to close…\n');
49
+ else process.stdout.write(`⏳ ${details.hostname || 'The address'} is in use by ${details.machine || 'another connection'}; trying again every ${Math.round(delayMs / 1000)} s (--wait). Press Ctrl+C to stop.\n`);
50
+ }
51
+
52
+ /** The text when a newer tunnel took this address over (exported for tests). */
53
+ export function replacedText(r = {}) {
54
+ const at = clock(r.at) || 'just now';
55
+ const kind = r.kind ? String(r.kind).toUpperCase() + ' ' : '';
56
+ const by = r.by ? ` from ${r.by}` : '';
57
+ return `This ${kind}tunnel was taken over at ${at} by a new tunnel${by} for the same address (--replace). It has stopped and will not reconnect.`;
58
+ }
59
+
60
+ setReplacedReporter((r) => {
61
+ if (tunnelOutput.json) process.stdout.write(JSON.stringify({ error: 'replaced', kind: r.kind ?? null, at: r.at ?? null, by: r.by ?? null }) + '\n');
62
+ else process.stderr.write(`❌ ${replacedText(r)}\n`);
63
+ process.exit(EXIT_IN_USE);
64
+ });
@@ -45,6 +45,19 @@ export function printOpenReject({ code, reason, data }) {
45
45
  process.exit(1);
46
46
  return;
47
47
  }
48
+ case 'target_not_this_device': {
49
+ // Story 4.10 r3
50
+ const to = d.to || 'that address';
51
+ const mine = d.hostname ? ` This computer serves ${d.hostname}.` : '';
52
+ process.stderr.write(`This computer can't serve ${to}.${mine} Run the command on the computer that owns ${to}, or change --to.\n`);
53
+ process.exit(1);
54
+ return;
55
+ }
56
+ case 'external_port_mismatch': {
57
+ process.stderr.write(`--external-port ${d.requested ?? ''} does not match this address's public port ${d.port ?? ''}. Leave --external-port out when you use --to.\n`);
58
+ process.exit(1);
59
+ return;
60
+ }
48
61
  default:
49
62
  // Not fatal: print and keep running (e.g. a refused renewal).
50
63
  process.stdout.write(`❌ Connection rejected${reason ? ` (${reason})` : ''}\n`);
@@ -11,6 +11,7 @@ import { dispatch as dispatchEvt } from "#tunnel-core/mqtt/events/index.js";
11
11
  import { MessageIngress } from "#tunnel-core/mqtt/ingress.js";
12
12
  import { getDeviceJsonPath } from "../lib/device.js";
13
13
  import './reject-messages.js'; // Story 12.1: the CLI's wording for coordinator refusals
14
+ import { exitInUse, printWaiting, tunnelOutput } from './in-use-messages.js'; // Story 1.9
14
15
  import { createControlPlaneSession } from '#tunnel-core/control-plane/session.js';
15
16
  import { publishRefreshRequestWithErrorHandling, jwtExpOf } from '#tunnel-core/lib/refresh-helpers.js';
16
17
  // Re-exported for existing tests that import it from here.
@@ -46,7 +47,16 @@ export default async function tunnel(args = []) {
46
47
  asyx tunnel --minecraft [--port <n>] [--name <alias>]
47
48
  Minecraft server (default port 25565); players connect with the hostname only.
48
49
 
50
+ --to <hostname> the address this tunnel serves, e.g. --to orders-api.tunnel.asyx.ai
51
+ (must belong to this computer; TCP/UDP then use that address's own port)
49
52
  --external-port <p> choose the public port inside your assigned 10-port block
53
+ --replace take over this address's running tunnel of the same kind (it is told and stops)
54
+ --wait if the address already runs this kind, keep trying every 30 s instead of exiting
55
+ --json print refusals as JSON
56
+
57
+ One address runs one HTTP, one TCP and one UDP tunnel at a time. A second tunnel of
58
+ the same kind is refused with the reason and exit code 75 (also when a tunnel is
59
+ taken over by --replace), so a service manager can be told not to restart on it.
50
60
 
51
61
  Tunnels forward to 127.0.0.1 only and reconnect on their own after a network or
52
62
  server interruption. Press Ctrl+C to stop. Docs: https://www.asyx.ai/docs
@@ -54,6 +64,14 @@ server interruption. Press Ctrl+C to stop. Docs: https://www.asyx.ai/docs
54
64
  return;
55
65
  }
56
66
 
67
+ // Story 4.10 r3: every open and refresh request carries the target (see tunnel-core requestFields).
68
+ if (parsed.to) process.env.ASYX_TUNNEL_TO = parsed.to;
69
+ // Story 1.9: --replace takes over a live tunnel of this kind for the address; --wait keeps trying.
70
+ if (parsed.replace) process.env.ASYX_TUNNEL_REPLACE = '1';
71
+ tunnelOutput.json = parsed.json === true;
72
+ tunnelOutput.wait = parsed.wait === true;
73
+ tunnelOutput.rerun = parsed.replace ? null : `asyx ${['tunnel', ...args.filter((a) => a !== '--wait' && a !== '--json')].join(' ')}`;
74
+
57
75
  // Handle legacy connect command
58
76
  if (args[0] === "connect") return connect();
59
77
 
@@ -214,6 +232,10 @@ const KNOWN_TUNNEL_FLAGS = [
214
232
  '--port',
215
233
  '--name',
216
234
  '--secgroup',
235
+ '--to',
236
+ '--replace',
237
+ '--wait',
238
+ '--json',
217
239
  '--target-host',
218
240
  '--external-port',
219
241
  '--ext-port',
@@ -272,6 +294,23 @@ function parseArgs(args) {
272
294
  process.stderr.write("Error: --name requires a service name\n");
273
295
  process.exit(2);
274
296
  }
297
+ } else if (arg === '--replace' || arg === '--wait' || arg === '--json') {
298
+ // Story 1.9: take over a live tunnel of this kind / keep trying while the address is in use / JSON errors
299
+ parsed[arg.slice(2)] = true;
300
+ consumed.add(i);
301
+ } else if (arg === '--to') {
302
+ // Story 4.10 r3: the address this tunnel serves (must be this computer's address).
303
+ const v = args[i + 1];
304
+ const host = v ? String(v).trim().toLowerCase().replace(/^[a-z]+:\/\//, '').replace(/[/?#].*$/, '').replace(/\.$/, '') : '';
305
+ if (!host || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/.test(host)) {
306
+ logger.error("cli.args.to_invalid", {});
307
+ process.stderr.write("Error: --to needs a hostname, for example --to orders-api.tunnel.asyx.ai\n");
308
+ process.exit(2);
309
+ }
310
+ parsed.to = host;
311
+ consumed.add(i);
312
+ consumed.add(i + 1);
313
+ i++;
275
314
  } else if (arg === '--secgroup') {
276
315
  // QPA-04: Parse --secgroup flag
277
316
  if (i + 1 < args.length) {
@@ -518,12 +557,14 @@ async function httpTunnel(localPort, secGroupSlug) {
518
557
  // maps its error codes to the same messages and exit codes as before.
519
558
  const { createHttpTunnel } = await import("#tunnel-core/flows/http.js");
520
559
  const handle = createHttpTunnel({
560
+ waitIfInUse: tunnelOutput.wait === true, // Story 1.9
521
561
  credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
522
562
  localPort,
523
563
  secGroupSlug,
524
564
  logger,
525
565
  onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
526
566
  });
567
+ handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
527
568
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
528
569
  handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
529
570
  handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
@@ -555,6 +596,7 @@ async function httpTunnel(localPort, secGroupSlug) {
555
596
  try {
556
597
  await handle.open();
557
598
  } catch (error) {
599
+ if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
558
600
  switch (error.code) {
559
601
  case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
560
602
  case 'assignment_failed': break; // HTTP has always exited here without a message
@@ -686,6 +728,7 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
686
728
  // maps its error codes to the same messages and exit codes as before.
687
729
  const { createTcpTunnel } = await import("#tunnel-core/flows/tcp.js");
688
730
  const handle = createTcpTunnel({
731
+ waitIfInUse: tunnelOutput.wait === true, // Story 1.9
689
732
  credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
690
733
  localPort,
691
734
  target,
@@ -695,6 +738,7 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
695
738
  logger,
696
739
  onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
697
740
  });
741
+ handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
698
742
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
699
743
  handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
700
744
  handle.on('control-fatal', ({ reason }) => {
@@ -737,6 +781,7 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
737
781
  try {
738
782
  await handle.open();
739
783
  } catch (error) {
784
+ if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
740
785
  const d = error.details || {};
741
786
  switch (error.code) {
742
787
  case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
@@ -828,6 +873,7 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
828
873
  // maps its error codes to the same messages and exit codes as before.
829
874
  const { createUdpTunnel } = await import("#tunnel-core/flows/udp.js");
830
875
  const handle = createUdpTunnel({
876
+ waitIfInUse: tunnelOutput.wait === true, // Story 1.9
831
877
  credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
832
878
  targetPort,
833
879
  targetHost,
@@ -835,6 +881,7 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
835
881
  logger,
836
882
  onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
837
883
  });
884
+ handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
838
885
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
839
886
  handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
840
887
  handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
@@ -855,6 +902,7 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
855
902
  try {
856
903
  await handle.open();
857
904
  } catch (error) {
905
+ if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
858
906
  switch (error.code) {
859
907
  case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
860
908
  case 'udp_relay_unavailable': process.stderr.write(`❌ ${error.message}\n`); break;
@@ -16,6 +16,10 @@ export interface HttpTunnelOptions {
16
16
  logger: Logger;
17
17
  /** Called with each observability line when ASYX_DEBUG=1 (the CLI prints them). */
18
18
  onObserve?: (line: string) => void;
19
+ /** Story 1.9: while a live tunnel of this kind serves the address, ask again every 30 s instead of failing. */
20
+ waitIfInUse?: boolean;
21
+ /** Story 1.9: take over this address's live tunnel of the same kind (the old one is told and stops), like `asyx tunnel --replace`. */
22
+ replace?: boolean;
19
23
  }
20
24
  /**
21
25
  * Sent with 'notice': something the user may want to know that does not end the tunnel, e.g.
@@ -39,6 +43,8 @@ export declare class HttpTunnelHandle extends LifecycleEmitter {
39
43
  };
40
44
  tunnel: any;
41
45
  mqttClient: any;
46
+ /** Story 1.9: one id for this tunnel across its opens (a re-open is never "another tunnel"). */
47
+ readonly tunnelSession: string;
42
48
  core: any;
43
49
  assignment: Record<string, any> | null;
44
50
  constructor(o: HttpTunnelOptions);
@@ -40,6 +40,8 @@ export class HttpTunnelHandle extends LifecycleEmitter {
40
40
  opts;
41
41
  tunnel = null;
42
42
  mqttClient = null;
43
+ /** Story 1.9: one id for this tunnel across its opens (a re-open is never "another tunnel"). */
44
+ tunnelSession = randomUUID();
43
45
  core = null;
44
46
  assignment = null;
45
47
  constructor(o) {
@@ -486,32 +488,42 @@ export class HttpTunnelHandle extends LifecycleEmitter {
486
488
  this.setState('closed', { error });
487
489
  }
488
490
  });
489
- // 6) Publish cmd/open request
490
- const requestId = randomUUID();
491
+ // 6) Publish cmd/open request (Story 1.9: asked again while the address is in use, see in-use.ts)
492
+ let requestId = '';
491
493
  const { getFpHash } = await import('../lib/fingerprint.js');
492
494
  const fingerprint = await getFpHash(credentials.clientId);
493
- // TPB-12: Track expected requestId for pre-assignment routing
494
- setExpectedRequestId(instanceId, requestId);
495
495
  const openPayload = {
496
- requestId,
497
496
  instanceId, // TPB-12: Per-instance routing
498
497
  proto: 'http',
499
498
  localPort,
500
499
  clientId: credentials.clientId,
500
+ tunnelSession: this.tunnelSession, // Story 1.9: the same tunnel opening again is never "another tunnel"
501
501
  ...fingerprint,
502
502
  };
503
+ if (this.opts.replace === true)
504
+ openPayload.replace = true; // Story 1.9 (SDK form of --replace)
503
505
  // QPA-04: Include secGroupSlug in cmd/open payload if provided
504
506
  if (secGroupSlug)
505
507
  openPayload.secGroupSlug = secGroupSlug;
506
- await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(openPayload), qos: 1, retain: false });
507
- logger.info('cli.cmd.open.sent', { requestId, instanceId, tunnelType: 'http' });
508
508
  // 7) Wait for ack
509
509
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
510
510
  let assignment;
511
511
  try {
512
- const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
513
- logger.info('cli.ack.wait.start', { requestId });
514
- assignment = await assignmentPromise;
512
+ const { openUntilFree } = await import('./in-use.js');
513
+ const opened = await openUntilFree({
514
+ send: async (rid) => {
515
+ requestId = rid;
516
+ // TPB-12: Track expected requestId for pre-assignment routing
517
+ setExpectedRequestId(instanceId, rid);
518
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify({ requestId: rid, ...openPayload }), qos: 1, retain: false });
519
+ logger.info('cli.cmd.open.sent', { requestId: rid, instanceId, tunnelType: 'http' });
520
+ logger.info('cli.ack.wait.start', { requestId: rid });
521
+ },
522
+ wait: (rid) => waitForAssignment(rid, ACK_TIMEOUT_MS),
523
+ waitIfInUse: this.opts.waitIfInUse === true,
524
+ onWaiting: (info) => this.emit('notice', { code: 'address_in_use_waiting', ...info }),
525
+ });
526
+ assignment = opened.assignment;
515
527
  logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'http' });
516
528
  logger.info('cli.assignment.received', { relayId: assignment.relayId, instanceId, tunnelType: 'http' });
517
529
  // TPB-12: Persist assignment using per-instance store
@@ -534,6 +546,8 @@ export class HttpTunnelHandle extends LifecycleEmitter {
534
546
  await core.end();
535
547
  }
536
548
  catch { }
549
+ if (error?.code === 'address_in_use')
550
+ throw error; // Story 1.9: the caller reports why, with the details
537
551
  throw new ConnectionError('assignment_failed', error.message, { cause: error });
538
552
  }
539
553
  // 8) Connect to the relay (was connectToRelay)
@@ -0,0 +1,27 @@
1
+ export declare const SAME_COMPUTER_WAIT_MS = 15000;
2
+ export declare const SAME_COMPUTER_STEP_MS = 3000;
3
+ export declare const WAIT_STEP_MS = 30000;
4
+ export type InUseDetails = Record<string, unknown> & {
5
+ sameComputer?: boolean;
6
+ };
7
+ /** How long to wait before asking again, or null to give up (the caller reports the refusal). */
8
+ export declare function inUseDelay(details: InUseDetails | undefined, firstAt: number, now: number, waitIfInUse: boolean): number | null;
9
+ export interface OpenUntilFreeOptions<T> {
10
+ /** publish a cmd/open with this requestId */
11
+ send: (requestId: string) => Promise<void>;
12
+ /** wait for the assignment of this requestId */
13
+ wait: (requestId: string) => Promise<T>;
14
+ waitIfInUse?: boolean;
15
+ onWaiting?: (info: {
16
+ details: InUseDetails;
17
+ delayMs: number;
18
+ sameComputer: boolean;
19
+ attempt: number;
20
+ }) => void;
21
+ sleep?: (ms: number) => Promise<void>;
22
+ now?: () => number;
23
+ }
24
+ export declare function openUntilFree<T>(o: OpenUntilFreeOptions<T>): Promise<{
25
+ assignment: T;
26
+ requestId: string;
27
+ }>;
@@ -0,0 +1,42 @@
1
+ // Story 1.9: an address runs one tunnel of each kind. When the coordinator answers address_in_use,
2
+ // the open fails with RefusedError('address_in_use', { details }). On the same computer (a restart
3
+ // that beat the old connection's offline notice) the open asks again every 3 s for up to 15 s; with
4
+ // waitIfInUse (`asyx tunnel --wait`) it asks again every 30 s until the address is free. Every retry
5
+ // travels over the same MQTT connection; nothing new is opened.
6
+ import { randomUUID } from 'node:crypto';
7
+ export const SAME_COMPUTER_WAIT_MS = 15_000;
8
+ export const SAME_COMPUTER_STEP_MS = 3_000;
9
+ export const WAIT_STEP_MS = 30_000;
10
+ /** How long to wait before asking again, or null to give up (the caller reports the refusal). */
11
+ export function inUseDelay(details, firstAt, now, waitIfInUse) {
12
+ if (details?.sameComputer === true && now - firstAt < SAME_COMPUTER_WAIT_MS)
13
+ return SAME_COMPUTER_STEP_MS;
14
+ if (waitIfInUse)
15
+ return WAIT_STEP_MS;
16
+ return null;
17
+ }
18
+ export async function openUntilFree(o) {
19
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
20
+ const now = o.now ?? Date.now;
21
+ let firstAt = 0;
22
+ for (let attempt = 1;; attempt++) {
23
+ const requestId = randomUUID();
24
+ await o.send(requestId);
25
+ try {
26
+ return { assignment: await o.wait(requestId), requestId };
27
+ }
28
+ catch (e) {
29
+ if (e?.code !== 'address_in_use')
30
+ throw e;
31
+ const t = now();
32
+ if (!firstAt)
33
+ firstAt = t;
34
+ const details = (e.details || {});
35
+ const delayMs = inUseDelay(details, firstAt, t, o.waitIfInUse === true);
36
+ if (delayMs === null)
37
+ throw e;
38
+ o.onWaiting?.({ details, delayMs, sameComputer: details.sameComputer === true, attempt });
39
+ await sleep(delayMs);
40
+ }
41
+ }
42
+ }
@@ -15,6 +15,10 @@ export interface TcpTunnelOptions {
15
15
  logger: Logger;
16
16
  /** Called with each observability line when ASYX_DEBUG=1 (the CLI prints them). */
17
17
  onObserve?: (line: string) => void;
18
+ /** Story 1.9: while a live tunnel of this kind serves the address, ask again every 30 s instead of failing. */
19
+ waitIfInUse?: boolean;
20
+ /** Story 1.9: take over this address's live tunnel of the same kind (the old one is told and stops), like `asyx tunnel --replace`. */
21
+ replace?: boolean;
18
22
  }
19
23
  /** Sent with 'assigned' when the coordinator's assignment arrives. */
20
24
  export type TcpAssignedEvent = {
@@ -42,6 +46,8 @@ export declare class TcpTunnelHandle extends LifecycleEmitter {
42
46
  };
43
47
  tunnel: any;
44
48
  mqttClient: any;
49
+ /** Story 1.9: one id for this tunnel across its opens. */
50
+ readonly tunnelSession: string;
45
51
  core: any;
46
52
  assignment: Record<string, any> | null;
47
53
  constructor(o: TcpTunnelOptions);
@@ -20,6 +20,8 @@ export class TcpTunnelHandle extends LifecycleEmitter {
20
20
  opts;
21
21
  tunnel = null;
22
22
  mqttClient = null;
23
+ /** Story 1.9: one id for this tunnel across its opens. */
24
+ tunnelSession = randomUUID();
23
25
  core = null;
24
26
  assignment = null;
25
27
  constructor(o) {
@@ -322,20 +324,20 @@ export class TcpTunnelHandle extends LifecycleEmitter {
322
324
  }
323
325
  });
324
326
  // 6) Publish cmd/open request with TCP protocol
325
- const requestId = randomUUID();
327
+ let requestId = '';
326
328
  const { getFpHash } = await import('../lib/fingerprint.js');
327
329
  const fingerprint = await getFpHash(credentials.clientId);
328
- // TPB-12: Track expected requestId for pre-assignment routing (before coordinator sends instanceId)
329
- setExpectedRequestId(instanceId, requestId);
330
330
  // TCP-S2 / E3-S8 / TPB-12: TCP cmd/open payload
331
331
  const openPayload = {
332
- requestId,
333
332
  instanceId, // TPB-12: Per-instance routing
333
+ tunnelSession: this.tunnelSession, // Story 1.9: a re-open is never "another tunnel"
334
334
  proto: 'tcp',
335
335
  target, // "127.0.0.1:<port>" from TCP-S1
336
336
  clientId: credentials.clientId,
337
337
  ...fingerprint,
338
338
  };
339
+ if (this.opts.replace === true)
340
+ openPayload.replace = true; // Story 1.9 (SDK form of --replace)
339
341
  openPayload.opts = { preferredPort: null };
340
342
  if (serviceName)
341
343
  openPayload.opts.name = serviceName;
@@ -345,16 +347,24 @@ export class TcpTunnelHandle extends LifecycleEmitter {
345
347
  if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
346
348
  openPayload.opts.requestedExternalPort = requestedExternalPort;
347
349
  }
348
- await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(openPayload), qos: 1, retain: false });
349
- logger.info('cli.cmd.open.sent', { requestId, instanceId, tunnelType: 'tcp', protocol: 'tcp', target });
350
350
  // 7) Wait for ack and assignment
351
351
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
352
352
  let assignment;
353
353
  let reassignSamePort;
354
354
  try {
355
- const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
356
- logger.info('cli.ack.wait.start', { requestId });
357
- assignment = await assignmentPromise;
355
+ const { openUntilFree } = await import('./in-use.js');
356
+ const opened = await openUntilFree({
357
+ send: async (rid) => {
358
+ requestId = rid;
359
+ setExpectedRequestId(instanceId, rid);
360
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify({ requestId: rid, ...openPayload }), qos: 1, retain: false });
361
+ logger.info('cli.cmd.open.sent', { requestId: rid, instanceId, tunnelType: 'tcp', protocol: 'tcp', target });
362
+ },
363
+ wait: (rid) => waitForAssignment(rid, ACK_TIMEOUT_MS),
364
+ waitIfInUse: this.opts.waitIfInUse === true,
365
+ onWaiting: (info) => this.emit('notice', { code: 'address_in_use_waiting', ...info }),
366
+ });
367
+ assignment = opened.assignment;
358
368
  logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'tcp' });
359
369
  logger.info('cli.assignment.received', { relayId: assignment.relayId, leaseId: assignment.leaseId, instanceId, tunnelType: 'tcp', tcpAliasFqdn: assignment.tcpAliasFqdn, publicPort: assignment.publicPort });
360
370
  // TPB-12: Persist assignment using per-instance store
@@ -400,6 +410,13 @@ export class TcpTunnelHandle extends LifecycleEmitter {
400
410
  };
401
411
  }
402
412
  catch (error) {
413
+ if (error?.code === 'address_in_use') {
414
+ try {
415
+ await core.end();
416
+ }
417
+ catch { }
418
+ throw error;
419
+ } // Story 1.9
403
420
  // TCP-S3 / TPB-03B: coordinator error codes, reported as refusals with what the CLI prints
404
421
  const errorCode = error.code || error.reason || error.data?.reason;
405
422
  const lc = String(errorCode || '').toLowerCase();
@@ -12,6 +12,10 @@ export interface UdpTunnelOptions {
12
12
  logger: Logger;
13
13
  /** Called with each observability line when ASYX_DEBUG=1 (the CLI prints them). */
14
14
  onObserve?: (line: string) => void;
15
+ /** Story 1.9: while a live tunnel of this kind serves the address, ask again every 30 s instead of failing. */
16
+ waitIfInUse?: boolean;
17
+ /** Story 1.9: take over this address's live tunnel of the same kind (the old one is told and stops), like `asyx tunnel --replace`. */
18
+ replace?: boolean;
15
19
  }
16
20
  /** What open() resolves to and the 'live' state carries. */
17
21
  export type UdpTunnelInfo = {
@@ -30,6 +34,8 @@ export declare class UdpTunnelHandle extends LifecycleEmitter {
30
34
  };
31
35
  tunnel: any;
32
36
  mqttClient: any;
37
+ /** Story 1.9: one id for this tunnel across its opens. */
38
+ readonly tunnelSession: string;
33
39
  core: any;
34
40
  assignment: Record<string, any> | null;
35
41
  constructor(o: UdpTunnelOptions);
@@ -17,6 +17,8 @@ export class UdpTunnelHandle extends LifecycleEmitter {
17
17
  opts;
18
18
  tunnel = null;
19
19
  mqttClient = null;
20
+ /** Story 1.9: one id for this tunnel across its opens. */
21
+ tunnelSession = randomUUID();
20
22
  core = null;
21
23
  assignment = null;
22
24
  constructor(o) {
@@ -196,13 +198,12 @@ export class UdpTunnelHandle extends LifecycleEmitter {
196
198
  }
197
199
  });
198
200
  // 6) Publish cmd/open request with UDP protocol
199
- const requestId = randomUUID();
201
+ let requestId = '';
200
202
  const { getFpHash } = await import('../lib/fingerprint.js');
201
203
  const fingerprint = await getFpHash(credentials.clientId);
202
- setExpectedRequestId(instanceId, requestId);
203
204
  const openPayload = {
204
- requestId,
205
205
  instanceId, // TPB-12: Per-instance routing
206
+ tunnelSession: this.tunnelSession, // Story 1.9: a re-open is never "another tunnel"
206
207
  protocol: 'udp',
207
208
  tunnelMode: 'udpWs-v1',
208
209
  port: targetPort, // UDP-S13: the app's listening port
@@ -212,19 +213,29 @@ export class UdpTunnelHandle extends LifecycleEmitter {
212
213
  tenantId: 'tunnel', // AC1.2: v4.1 validation phase uses literal "tunnel" as tenantId
213
214
  ...fingerprint,
214
215
  };
216
+ if (this.opts.replace === true)
217
+ openPayload.replace = true; // Story 1.9 (SDK form of --replace)
215
218
  if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
216
219
  openPayload.externalPort = requestedExternalPort;
217
220
  }
218
- await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(openPayload), qos: 1, retain: false });
219
- logger.info('cli.cmd.open.sent', { requestId, instanceId, tunnelType: 'udp', protocol: 'udp', tunnelMode: 'udpWs-v1' });
220
221
  // 7) Wait for ack and assignment
221
222
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
222
223
  let assignment;
223
224
  let reassignSamePort;
224
225
  try {
225
- const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
226
- logger.info('cli.ack.wait.start', { requestId });
227
- assignment = await assignmentPromise;
226
+ const { openUntilFree } = await import('./in-use.js');
227
+ const opened = await openUntilFree({
228
+ send: async (rid) => {
229
+ requestId = rid;
230
+ setExpectedRequestId(instanceId, rid);
231
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify({ requestId: rid, ...openPayload }), qos: 1, retain: false });
232
+ logger.info('cli.cmd.open.sent', { requestId: rid, instanceId, tunnelType: 'udp', protocol: 'udp', tunnelMode: 'udpWs-v1' });
233
+ },
234
+ wait: (rid) => waitForAssignment(rid, ACK_TIMEOUT_MS),
235
+ waitIfInUse: this.opts.waitIfInUse === true,
236
+ onWaiting: (info) => this.emit('notice', { code: 'address_in_use_waiting', ...info }),
237
+ });
238
+ assignment = opened.assignment;
228
239
  logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'udp' });
229
240
  logger.info('cli.assignment.received', { relayId: assignment.relayId, leaseId: assignment.leaseId, instanceId, tunnelType: 'udp', publicPort: assignment.publicPort });
230
241
  // UDP-S1: Validate assignment (AC1.4/AC5.1)
@@ -277,6 +288,13 @@ export class UdpTunnelHandle extends LifecycleEmitter {
277
288
  };
278
289
  }
279
290
  catch (error) {
291
+ if (error?.code === 'address_in_use') {
292
+ try {
293
+ await core.end();
294
+ }
295
+ catch { }
296
+ throw error;
297
+ } // Story 1.9
280
298
  logger.error('cli.ack.wait.failed', { error: error.message, errorCode: error.code, instanceId, tunnelType: 'udp' });
281
299
  if (error.code === 'udp_relay_unavailable') {
282
300
  try {
@@ -1,10 +1,142 @@
1
1
  export function getFpHash(clientId: any): Promise<{
2
+ replace: boolean;
3
+ host: string;
4
+ to: string;
2
5
  clientVersion: string;
3
6
  fpv: string;
4
7
  fph: string;
5
8
  alg: string;
6
9
  lib: string;
7
10
  } | {
11
+ replace?: undefined;
12
+ host: string;
13
+ to: string;
14
+ clientVersion: string;
15
+ fpv: string;
16
+ fph: string;
17
+ alg: string;
18
+ lib: string;
19
+ } | {
20
+ replace: boolean;
21
+ host?: undefined;
22
+ to: string;
23
+ clientVersion: string;
24
+ fpv: string;
25
+ fph: string;
26
+ alg: string;
27
+ lib: string;
28
+ } | {
29
+ replace?: undefined;
30
+ host?: undefined;
31
+ to: string;
32
+ clientVersion: string;
33
+ fpv: string;
34
+ fph: string;
35
+ alg: string;
36
+ lib: string;
37
+ } | {
38
+ replace: boolean;
39
+ host: string;
40
+ to?: undefined;
41
+ clientVersion: string;
42
+ fpv: string;
43
+ fph: string;
44
+ alg: string;
45
+ lib: string;
46
+ } | {
47
+ replace?: undefined;
48
+ host: string;
49
+ to?: undefined;
50
+ clientVersion: string;
51
+ fpv: string;
52
+ fph: string;
53
+ alg: string;
54
+ lib: string;
55
+ } | {
56
+ replace: boolean;
57
+ host?: undefined;
58
+ to?: undefined;
59
+ clientVersion: string;
60
+ fpv: string;
61
+ fph: string;
62
+ alg: string;
63
+ lib: string;
64
+ } | {
65
+ replace?: undefined;
66
+ host?: undefined;
67
+ to?: undefined;
68
+ clientVersion: string;
69
+ fpv: string;
70
+ fph: string;
71
+ alg: string;
72
+ lib: string;
73
+ } | {
74
+ replace: boolean;
75
+ host: string;
76
+ to: string;
77
+ clientVersion?: undefined;
78
+ fpv: string;
79
+ fph: string;
80
+ alg: string;
81
+ lib: string;
82
+ } | {
83
+ replace?: undefined;
84
+ host: string;
85
+ to: string;
86
+ clientVersion?: undefined;
87
+ fpv: string;
88
+ fph: string;
89
+ alg: string;
90
+ lib: string;
91
+ } | {
92
+ replace: boolean;
93
+ host?: undefined;
94
+ to: string;
95
+ clientVersion?: undefined;
96
+ fpv: string;
97
+ fph: string;
98
+ alg: string;
99
+ lib: string;
100
+ } | {
101
+ replace?: undefined;
102
+ host?: undefined;
103
+ to: string;
104
+ clientVersion?: undefined;
105
+ fpv: string;
106
+ fph: string;
107
+ alg: string;
108
+ lib: string;
109
+ } | {
110
+ replace: boolean;
111
+ host: string;
112
+ to?: undefined;
113
+ clientVersion?: undefined;
114
+ fpv: string;
115
+ fph: string;
116
+ alg: string;
117
+ lib: string;
118
+ } | {
119
+ replace?: undefined;
120
+ host: string;
121
+ to?: undefined;
122
+ clientVersion?: undefined;
123
+ fpv: string;
124
+ fph: string;
125
+ alg: string;
126
+ lib: string;
127
+ } | {
128
+ replace: boolean;
129
+ host?: undefined;
130
+ to?: undefined;
131
+ clientVersion?: undefined;
132
+ fpv: string;
133
+ fph: string;
134
+ alg: string;
135
+ lib: string;
136
+ } | {
137
+ replace?: undefined;
138
+ host?: undefined;
139
+ to?: undefined;
8
140
  clientVersion?: undefined;
9
141
  fpv: string;
10
142
  fph: string;
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { getFingerprintingInfo } from 'hw-fingerprint';
8
8
  import { createHash } from 'node:crypto';
9
+ import os from 'node:os';
9
10
  /**
10
11
  * Safe hardware attributes that don't trigger macOS privacy warnings.
11
12
  * Based on analysis of hw-fingerprint library behavior.
@@ -69,8 +70,30 @@ function versionField() {
69
70
  const v = (process.env.ASYX_CLIENT_VERSION || '').trim();
70
71
  return /^[0-9A-Za-z.@+-]{1,40}$/.test(v) ? { clientVersion: v } : {};
71
72
  }
73
+ // Story 4.10 r3: the address the tunnel serves (`asyx tunnel --to <hostname>`), sent on every
74
+ // open/refresh/reconnect so the coordinator can refuse a tunnel for an address this device does not serve.
75
+ function targetField() {
76
+ const v = (process.env.ASYX_TUNNEL_TO || '').trim().toLowerCase();
77
+ return /^[a-z0-9.-]{3,253}$/.test(v) ? { to: v } : {};
78
+ }
79
+ // Story 1.9: the computer's name (so a refusal can say where the running tunnel is; never an IP
80
+ // address) and whether this open may take over a live tunnel of the same kind (`--replace`).
81
+ function hostField() {
82
+ let h = '';
83
+ try {
84
+ h = (process.env.ASYX_HOST_NAME || os.hostname() || '').trim();
85
+ }
86
+ catch {
87
+ h = '';
88
+ }
89
+ h = h.replace(/\.local$/i, '').replace(/[^\w .'()-]/g, '').slice(0, 64);
90
+ return h ? { host: h } : {};
91
+ }
92
+ function replaceField() {
93
+ return process.env.ASYX_TUNNEL_REPLACE === '1' ? { replace: true } : {};
94
+ }
72
95
  export async function getFpHash(clientId) {
73
- return { ...(await fingerprintFields(clientId)), ...versionField() };
96
+ return { ...(await fingerprintFields(clientId)), ...versionField(), ...targetField(), ...hostField(), ...replaceField() };
74
97
  }
75
98
  async function fingerprintFields(clientId) {
76
99
  try {
@@ -1,3 +1,5 @@
1
+ /** Story 1.9: how "this tunnel was taken over by a newer one" is reported (the CLI prints and exits 75). */
2
+ export function setReplacedReporter(fn: any): void;
1
3
  /** Register how open rejections are reported to the user (the CLI does; the SDK uses errors). */
2
4
  export function setOpenRejectReporter(fn: any): void;
3
5
  export function getHandler(type: any): any;
@@ -9,6 +9,9 @@ export const FATAL_REJECT_CODES = new Set([
9
9
  'tcp_port_block_exhausted', 'tcp_port_capacity_exhausted', 'tenant_tcp_lease_limit_reached',
10
10
  ]);
11
11
  let openRejectReporter = null;
12
+ let replacedReporter = null;
13
+ /** Story 1.9: how "this tunnel was taken over by a newer one" is reported (the CLI prints and exits 75). */
14
+ export function setReplacedReporter(fn) { replacedReporter = fn; }
12
15
  /** Register how open rejections are reported to the user (the CLI does; the SDK uses errors). */
13
16
  export function setOpenRejectReporter(fn) { openRejectReporter = fn; }
14
17
  /**
@@ -218,6 +221,13 @@ const registry = {
218
221
  }
219
222
  }
220
223
  const code = String(d.reason || 'refused').toLowerCase();
224
+ // Story 1.9: a live tunnel of this kind already serves the address. The open that asked fails with
225
+ // a RefusedError carrying the details; the flow decides whether to wait and ask again.
226
+ if (code === 'address_in_use' && e.requestId) {
227
+ const { rejectAssignment } = await import('../../state/assignment.js');
228
+ if (rejectAssignment(e.requestId, new RefusedError('address_in_use', 'a live tunnel of this kind already serves this address', { details: d })))
229
+ return;
230
+ }
221
231
  const report = { code, reason: d.reason, fatal: FATAL_REJECT_CODES.has(code), data: d, instanceId };
222
232
  if (openRejectReporter) {
223
233
  await openRejectReporter(report);
@@ -226,6 +236,24 @@ const registry = {
226
236
  if (report.fatal)
227
237
  throw new RefusedError(code, `coordinator refused the open: ${d.reason}`, { details: d });
228
238
  },
239
+ // Story 1.9: a newer tunnel took this address over with --replace. Only the tunnel whose lease was
240
+ // replaced reacts (routed by instanceId/leaseId); it stops and does not reconnect.
241
+ async replaced(e) {
242
+ const d = e.data || {};
243
+ const ctx = e._instanceContext;
244
+ const mine = ctx?.getAssignment?.(e._instanceId);
245
+ if (!d.leaseId || mine?.leaseId !== d.leaseId)
246
+ return; // only the tunnel holding that lease (a new one has none yet)
247
+ const report = { code: 'replaced', at: d.at || null, by: d.by || null, kind: d.kind || null, hostname: d.hostname || null, instanceId: e._instanceId || null };
248
+ if (replacedReporter) {
249
+ await replacedReporter(report);
250
+ return;
251
+ }
252
+ const err = /** @type {Error & { code?: string, details?: unknown }} */ (new Error('this tunnel was taken over by a newer tunnel for the same address'));
253
+ err.code = 'ERROR_REPLACED';
254
+ err.details = report;
255
+ throw err;
256
+ },
229
257
  async error(e) {
230
258
  const d = e.data || {};
231
259
  const err = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(d.msg || "Command failed"));
@@ -74,7 +74,8 @@ export async function dispatch(parsedMessage) {
74
74
  // their renewal ids collided.
75
75
  // Only log/drop if all fallbacks failed
76
76
  if (!targetInstanceId) {
77
- logger.warn('evt.instance.unknown', {
77
+ // 0.7.0: debug, not warn — with several tunnels on one computer every tunnel sees the others' replies.
78
+ logger.debug('evt.instance.unknown', {
78
79
  instanceId,
79
80
  leaseId,
80
81
  eventType: evt.type,
@@ -105,6 +105,13 @@ export function hasAssignment(instanceId: string): boolean;
105
105
  * @returns {Promise<Object>} resolves with the assignment snapshot
106
106
  */
107
107
  export function waitForAssignment(requestId: string, timeoutMs?: number): Promise<any>;
108
+ /**
109
+ * Story 1.9: fail the open waiting for requestId with `error` (e.g. address_in_use), so the flow can
110
+ * decide to wait and ask again instead of timing out. Returns true when someone was waiting.
111
+ * @param {string} requestId
112
+ * @param {Error} error
113
+ */
114
+ export function rejectAssignment(requestId: string, error: Error): boolean;
108
115
  /**
109
116
  * Get assignment metadata (without JWT for logging)
110
117
  * TPB-12: Per-instance metadata retrieval
@@ -264,6 +264,23 @@ export function waitForAssignment(requestId, timeoutMs = 10000) {
264
264
  }
265
265
  });
266
266
  }
267
+ /**
268
+ * Story 1.9: fail the open waiting for requestId with `error` (e.g. address_in_use), so the flow can
269
+ * decide to wait and ask again instead of timing out. Returns true when someone was waiting.
270
+ * @param {string} requestId
271
+ * @param {Error} error
272
+ */
273
+ export function rejectAssignment(requestId, error) {
274
+ const queue = assignmentWaiters.get(requestId);
275
+ if (!queue || queue.length === 0)
276
+ return false;
277
+ assignmentWaiters.delete(requestId);
278
+ for (const entry of queue) {
279
+ clearTimeout(entry.timer);
280
+ entry.reject(error);
281
+ }
282
+ return true;
283
+ }
267
284
  /**
268
285
  * Get assignment metadata (without JWT for logging)
269
286
  * TPB-12: Per-instance metadata retrieval
@@ -109,6 +109,7 @@ export class HttpTunnel {
109
109
  open(): Promise<any>;
110
110
  _attemptConnect(): Promise<any>;
111
111
  _helloAttempts: any;
112
+ lastInboundMs: number;
112
113
  scheduleReconnect(code: any, reason: any): any;
113
114
  attemptReconnect(): Promise<void>;
114
115
  _scheduleRefreshRetry(reason: any): any;
@@ -562,9 +562,13 @@ export class HttpTunnel {
562
562
  this.startHeartbeat();
563
563
  resolve();
564
564
  });
565
+ // Story 3.11: anything from the relay, including the pong the WebSocket protocol
566
+ // requires in answer to a ping, proves the connection is alive
567
+ this.ws.on('pong', () => { this.lastInboundMs = Date.now(); });
565
568
  this.ws.on('message', (data, isBinary) => {
566
569
  // CRT-Relay-E: Update activity on any message
567
570
  this.lastActivityMs = Date.now();
571
+ this.lastInboundMs = this.lastActivityMs;
568
572
  if (!isBinary) {
569
573
  try {
570
574
  const msg = JSON.parse(data.toString());
@@ -1549,18 +1553,24 @@ export class HttpTunnel {
1549
1553
  this.ws.close();
1550
1554
  }
1551
1555
  }
1552
- // CRT-Relay-E: Heartbeat methods
1556
+ // CRT-Relay-E / Story 3.11: Heartbeat methods. Every interval (30 s by default) the tunnel
1557
+ // sends a WebSocket protocol ping, which the relay's WebSocket library answers by itself, so
1558
+ // relays in the field need no change. Nothing received for three intervals means the
1559
+ // connection died without a close: terminate it so the close handler reconnects (as the
1560
+ // TCP and UDP tunnels do, Story 11.2), instead of waiting minutes for a write to fail.
1553
1561
  getHeartbeatInterval() {
1554
- const interval = process.env.ASYX_TUNNEL_HEARTBEAT_SEC || '120';
1562
+ const interval = process.env.ASYX_TUNNEL_HEARTBEAT_SEC || '30';
1555
1563
  const intervalMs = Number(interval) * 1000;
1556
- return intervalMs <= 0 ? Infinity : intervalMs;
1564
+ return !(intervalMs > 0) ? Infinity : intervalMs;
1557
1565
  }
1558
1566
  startHeartbeat() {
1567
+ this.stopHeartbeat();
1559
1568
  const interval = this.getHeartbeatInterval();
1560
1569
  if (interval === Infinity) {
1561
1570
  this.log.debug('Heartbeat disabled (ASYX_TUNNEL_HEARTBEAT_SEC <= 0)');
1562
1571
  return;
1563
1572
  }
1573
+ this.lastInboundMs = Date.now();
1564
1574
  this.heartbeatTimer = setInterval(() => {
1565
1575
  this.sendHeartbeat();
1566
1576
  }, interval);
@@ -1571,15 +1581,21 @@ export class HttpTunnel {
1571
1581
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1572
1582
  return;
1573
1583
  }
1574
- // Check if we should send heartbeat (respect real traffic)
1575
- const now = Date.now();
1576
- const timeSinceActivity = now - this.lastActivityMs;
1577
1584
  const interval = this.getHeartbeatInterval();
1578
- if (timeSinceActivity >= interval) {
1579
- this.ws.send(JSON.stringify({ t: 'ping' }));
1580
- this.lastActivityMs = now;
1585
+ const silentMs = Date.now() - (this.lastInboundMs || 0);
1586
+ if (silentMs > 3 * interval) {
1587
+ this.log.warn({ silentMs }, 'http.ws.liveness_timeout');
1588
+ this.stopHeartbeat();
1589
+ this.ws.terminate();
1590
+ return;
1591
+ }
1592
+ try {
1593
+ this.ws.ping();
1581
1594
  this.log.debug({ interval }, 'tunnel heartbeat ping sent');
1582
1595
  }
1596
+ catch (err) {
1597
+ this.log.debug({ err: err?.message }, 'tunnel heartbeat ping failed');
1598
+ }
1583
1599
  }
1584
1600
  stopHeartbeat() {
1585
1601
  if (this.heartbeatTimer) {