asyx 0.6.1 → 0.7.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.
Files changed (34) hide show
  1. package/README.md +56 -8
  2. package/package.json +2 -1
  3. package/src/commands/in-use-messages.js +64 -0
  4. package/src/commands/reject-messages.js +56 -0
  5. package/src/commands/tunnel.js +59 -0
  6. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +13 -0
  7. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +21 -0
  8. package/vendor/tunnel-core/dist/control-plane/session.d.ts +5 -0
  9. package/vendor/tunnel-core/dist/control-plane/session.js +2 -1
  10. package/vendor/tunnel-core/dist/flows/goodbye.d.ts +10 -0
  11. package/vendor/tunnel-core/dist/flows/goodbye.js +27 -0
  12. package/vendor/tunnel-core/dist/flows/http.d.ts +11 -0
  13. package/vendor/tunnel-core/dist/flows/http.js +84 -10
  14. package/vendor/tunnel-core/dist/flows/in-use.d.ts +27 -0
  15. package/vendor/tunnel-core/dist/flows/in-use.js +42 -0
  16. package/vendor/tunnel-core/dist/flows/reopen.d.ts +9 -0
  17. package/vendor/tunnel-core/dist/flows/reopen.js +27 -0
  18. package/vendor/tunnel-core/dist/flows/tcp.d.ts +11 -0
  19. package/vendor/tunnel-core/dist/flows/tcp.js +70 -11
  20. package/vendor/tunnel-core/dist/flows/udp.d.ts +11 -0
  21. package/vendor/tunnel-core/dist/flows/udp.js +70 -10
  22. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +132 -0
  23. package/vendor/tunnel-core/dist/lib/fingerprint.js +24 -1
  24. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +2 -0
  25. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +37 -0
  26. package/vendor/tunnel-core/dist/mqtt/events/index.js +2 -1
  27. package/vendor/tunnel-core/dist/state/assignment.d.ts +7 -0
  28. package/vendor/tunnel-core/dist/state/assignment.js +17 -0
  29. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +4 -1
  30. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +60 -12
  31. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +3 -0
  32. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +18 -0
  33. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +3 -0
  34. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +18 -0
package/README.md CHANGED
@@ -153,7 +153,7 @@ asyx tunnel --http --port 3000
153
153
  - TLS and token refresh handled automatically; your app keeps its port.
154
154
  - If the connection drops (network loss, laptop wake, Asyx server maintenance), the CLI reconnects on its own and the same URL comes back.
155
155
 
156
- ### Private demos (Quickpass)
156
+ ### Private demos (QuickPass)
157
157
 
158
158
  For client-only or team-only previews—not open to the whole internet:
159
159
 
@@ -161,7 +161,7 @@ For client-only or team-only previews—not open to the whole internet:
161
161
  asyx tunnel --http --port 3000 --secgroup reviewers
162
162
  ```
163
163
 
164
- Guests enroll via Quickpass; the relay enforces membership. See https://www.asyx.ai/docs/quickpass
164
+ Guests enroll via QuickPass; the relay enforces membership. See https://www.asyx.ai/docs/quickpass
165
165
 
166
166
  ---
167
167
 
@@ -189,7 +189,7 @@ asyx tunnel --minecraft [--port 25565] [--name <alias>]
189
189
 
190
190
  After a tunnel opens, the CLI prints the public `fqdn` (and port for TCP/UDP) plus the local target (`tcp://127.0.0.1:<port>` or `udp://127.0.0.1:<port>`).
191
191
 
192
- If the connection of a TCP or UDP tunnel drops (network loss, Asyx server maintenance, or Asyx moving your tunnel to another server), the CLI reconnects on its own and keeps the same hostname and public port. Visitor connections that were open at the moment of the drop end; new ones work as soon as the tunnel is back, usually within seconds. The CLI ends instead if the tunnel was closed by the service or opened elsewhere, or if it cannot reconnect for 15 minutes.
192
+ If the connection of a TCP or UDP tunnel drops (network loss, Asyx server maintenance, or Asyx moving your tunnel to another server), the CLI reconnects on its own and keeps the same hostname and public port. Visitor connections that were open at the moment of the drop end; new ones work as soon as the tunnel is back, usually within seconds. If the service closes the tunnel's lease while the CLI is still running (for example after the computer slept through it), the tunnel reopens on the same hostname and port by itself and says so. The CLI ends if another tunnel took the address over with `--replace`, if reopening is refused, or if it cannot reconnect for 15 minutes.
193
193
 
194
194
  | Variable | Effect |
195
195
  | --- | --- |
@@ -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
+ ❌ orders-api.tunnel.asyx.ai already has an HTTP tunnel from this computer since 2:02 PM (serving localhost:3000).
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 (it tells the service) 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 3000 --to orders-api.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,13 +237,34 @@ 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.1
245
+ ## What's new in 0.7.1
246
+
247
+ **Stopping a tunnel frees its address at once** — on Ctrl-C (or when a service manager stops it) the tunnel tells the cloud it is stopping, so its address and port are free for the next start right away instead of after the lease runs out. This never delays a stop by more than two seconds.
248
+
249
+ **A tunnel comes back by itself when its lease was closed** — if the cloud closes a running tunnel's lease (for example after the computer slept through it), the tunnel opens a fresh one on the same address and, for TCP and UDP, the same port, and prints one line saying so. It tries at most three times in ten minutes, never takes an address back from a newer tunnel that replaced it, and says why when reopening is refused.
250
+
251
+ **Clearer refusals for accounts with several addresses** — when an address is not on your account, your device has no default address, a port belongs to another address, all ports are assigned, or an address is suspended, the CLI says so in words and exits.
252
+
253
+ ## What's new in 0.7.0
254
+
255
+ **`--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.
218
256
 
219
- 0.6.1 is the 0.6 release; 0.6.0 was published with a packaging error and could not be installed.
257
+ **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).
258
+
259
+ **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.
260
+
261
+ **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.
262
+
263
+ **Quieter with several tunnels on one computer** — tunnels running side by side no longer print each other's replies as warnings.
264
+
265
+ 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.
266
+
267
+ ## What's new in 0.6.1
220
268
 
221
269
  **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.
222
270
 
@@ -274,7 +322,7 @@ asyx tunnel --minecraft [--port <n>] [--name <alias>]
274
322
  | Cursor + Asyx | https://www.asyx.ai/docs/cursor-asyx |
275
323
  | Agent checklist | https://www.asyx.ai/docs/ai-agent-checklist |
276
324
  | Expose localhost | https://www.asyx.ai/docs/expose-localhost |
277
- | Quickpass (guest access) | https://www.asyx.ai/docs/quickpass |
325
+ | QuickPass (guest access) | https://www.asyx.ai/docs/quickpass |
278
326
  | vs ngrok & Cloudflare | https://www.asyx.ai/docs/vs-ngrok-cloudflare |
279
327
 
280
328
  ---
@@ -285,7 +333,7 @@ asyx tunnel --minecraft [--port <n>] [--name <alias>]
285
333
  - **Do not** tunnel database admin ports without authentication.
286
334
  - **Stop** the tunnel when the demo ends (`Ctrl+C`).
287
335
  - Treat the public URL as a temporary preview—not a production deploy.
288
- - Agents **cannot** enroll a device (`asyx setup` requires browser verification) or open tunnels from a machine that has not been set up.
336
+ - Agents **cannot** complete enrollment on their own: `asyx setup` needs a person to approve it in the browser with the code from the terminal. Tunnels open only from a machine that has been set up.
289
337
 
290
338
  ---
291
339
 
@@ -310,7 +358,7 @@ Levels: `error` | `warn` | `info` | `debug` (default `info`).
310
358
  | Windows PowerShell: "running scripts is disabled on this system" | Run `asyx.cmd` instead of `asyx` (or use Command Prompt), or allow local scripts once: `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned` |
311
359
  | Tunnel stops right after starting with `jwt_expired_before_refresh` | Your computer's clock is wrong; turn on automatic time and try again |
312
360
  | Tunnel URL 502 / unreachable | Dev server not running on the same port |
313
- | Link dies overnight | Expected—the tunnel lives only while the CLI runs and the machine is awake |
361
+ | Link stops while the computer sleeps | Expected—the tunnel serves only while the CLI runs and the machine is awake; when it wakes, the tunnel reconnects (and reopens its lease if needed) on the same address |
314
362
  | TCP/UDP tunnel ended after an outage | It retries for 15 minutes, then exits; run the same command again (raise `ASYX_TUNNEL_RECONNECT_MAX_MS` for longer outages) |
315
363
  | External port rejected | `--external-port` must be inside your assigned 10-port block |
316
364
  | Windows: secure connection fails at startup | Re-run `asyx setup` to regenerate the device key |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
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,62 @@ 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
+ }
61
+ case 'lease_closed':
62
+ // Story 3.13: handled by reopening the tunnel (it prints its own line); nothing to say here.
63
+ return;
64
+ // Story 2.9: the account model's refusals. Each ends the open with code 1 and says what to do.
65
+ case 'target_not_in_account': {
66
+ const to = d.to || 'that address';
67
+ process.stderr.write(`${to} is not an address of this account. Check the name, or add it in the console (asyx.ai/console/tunnel).\n`);
68
+ process.exit(1);
69
+ return;
70
+ }
71
+ case 'no_default_address': {
72
+ const list = Array.isArray(d.addresses) && d.addresses.length ? ` Use --to with one of: ${d.addresses.join(', ')}.` : ' Add one in the console (asyx.ai/console/tunnel), then use --to.';
73
+ process.stderr.write(`This device has no default address.${list}\n`);
74
+ process.exit(1);
75
+ return;
76
+ }
77
+ case 'app_address_only': {
78
+ process.stderr.write(`An app can serve only its own address${d.hostname ? `, not ${d.hostname}` : ''}. Leave out --to, or run it from a device.\n`);
79
+ process.exit(1);
80
+ return;
81
+ }
82
+ case 'address_suspended': {
83
+ const what = d.scope === 'account' ? 'This account is suspended' : `${d.hostname || 'This address'} is suspended`;
84
+ process.stderr.write(`${what}${d.reason ? `: ${d.reason}` : ''}. Contact support@asyx.ai.\n`);
85
+ process.exit(1);
86
+ return;
87
+ }
88
+ case 'external_port_assigned_elsewhere': {
89
+ process.stderr.write(`Port ${d.requestedPort ?? ''} belongs to ${d.address || 'another address'} of this account. Use that address with --to, release the port in the console, or pick another port.\n`);
90
+ process.exit(1);
91
+ return;
92
+ }
93
+ case 'port_block_full': {
94
+ const where = d.assigned && typeof d.assigned === 'object' ? Object.entries(d.assigned).map(([p, a]) => `${p} → ${a}`).join(', ') : '';
95
+ process.stderr.write(`All 10 ${String(d.kind || '').toUpperCase()} ports of this account are assigned${where ? ` (${where})` : ''}. Release one in the console (asyx.ai/console/tunnel), then try again.\n`);
96
+ process.exit(1);
97
+ return;
98
+ }
99
+ case 'identity_inactive': {
100
+ process.stderr.write('This device or app has been revoked or removed from its account. Run asyx setup to set it up again.\n');
101
+ process.exit(1);
102
+ return;
103
+ }
48
104
  default:
49
105
  // Not fatal: print and keep running (e.g. a refused renewal).
50
106
  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,17 @@ 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
568
+ // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
569
+ handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
570
+ handle.on('reopen_refused', (r) => process.stderr.write(r?.code === 'reopen_limit' ? 'The tunnel was closed 3 times in 10 minutes; not reopening again. Start it again when you are ready.\n' : `The tunnel's lease was closed and reopening it was refused (${r?.code || 'refused'}).\n`));
527
571
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
528
572
  handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
529
573
  handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
@@ -555,6 +599,7 @@ async function httpTunnel(localPort, secGroupSlug) {
555
599
  try {
556
600
  await handle.open();
557
601
  } catch (error) {
602
+ if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
558
603
  switch (error.code) {
559
604
  case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
560
605
  case 'assignment_failed': break; // HTTP has always exited here without a message
@@ -590,6 +635,8 @@ async function httpTunnel(localPort, secGroupSlug) {
590
635
  process.stderr.write("tunnel.close() timed out; forcing exit\n");
591
636
  process.exit(0);
592
637
  }, 3000);
638
+ // Story 3.13: say goodbye first (the lease closes at once); never waits more than 2 s
639
+ try { const bye = await handle.goodbye?.(2000); logger.debug('tunnel.goodbye', { result: bye }); } catch (e) { logger.debug('tunnel.goodbye.error', { error: e?.message }); }
593
640
  try {
594
641
  handle.tunnel.close();
595
642
  } catch (e) {
@@ -686,6 +733,7 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
686
733
  // maps its error codes to the same messages and exit codes as before.
687
734
  const { createTcpTunnel } = await import("#tunnel-core/flows/tcp.js");
688
735
  const handle = createTcpTunnel({
736
+ waitIfInUse: tunnelOutput.wait === true, // Story 1.9
689
737
  credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
690
738
  localPort,
691
739
  target,
@@ -695,6 +743,10 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
695
743
  logger,
696
744
  onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
697
745
  });
746
+ handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
747
+ // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
748
+ handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
749
+ handle.on('reopen_refused', (r) => process.stderr.write(r?.code === 'reopen_limit' ? 'The tunnel was closed 3 times in 10 minutes; not reopening again. Start it again when you are ready.\n' : `The tunnel's lease was closed and reopening it was refused (${r?.code || 'refused'}).\n`));
698
750
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
699
751
  handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
700
752
  handle.on('control-fatal', ({ reason }) => {
@@ -737,6 +789,7 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
737
789
  try {
738
790
  await handle.open();
739
791
  } catch (error) {
792
+ if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
740
793
  const d = error.details || {};
741
794
  switch (error.code) {
742
795
  case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
@@ -828,6 +881,7 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
828
881
  // maps its error codes to the same messages and exit codes as before.
829
882
  const { createUdpTunnel } = await import("#tunnel-core/flows/udp.js");
830
883
  const handle = createUdpTunnel({
884
+ waitIfInUse: tunnelOutput.wait === true, // Story 1.9
831
885
  credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
832
886
  targetPort,
833
887
  targetHost,
@@ -835,6 +889,10 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
835
889
  logger,
836
890
  onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
837
891
  });
892
+ handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
893
+ // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
894
+ handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
895
+ handle.on('reopen_refused', (r) => process.stderr.write(r?.code === 'reopen_limit' ? 'The tunnel was closed 3 times in 10 minutes; not reopening again. Start it again when you are ready.\n' : `The tunnel's lease was closed and reopening it was refused (${r?.code || 'refused'}).\n`));
838
896
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
839
897
  handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
840
898
  handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
@@ -855,6 +913,7 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
855
913
  try {
856
914
  await handle.open();
857
915
  } catch (error) {
916
+ if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
858
917
  switch (error.code) {
859
918
  case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
860
919
  case 'udp_relay_unavailable': process.stderr.write(`❌ ${error.message}\n`); break;
@@ -9,6 +9,7 @@
9
9
  * @property {(client: any) => void | Promise<void>} [onConnected] - Called after successful connect
10
10
  * @property {(reason: string) => void} [onOffline] - Called when connection goes offline
11
11
  * @property {(reason: string, err?: unknown) => void} [onFatalError] - Called when we give up due to JWT expiry or unrecoverable error
12
+ * @property {() => Promise<{ exp: number | null, leaseId: string } | null>} [onLeaseClosed] - Story 3.13: reopen after a closed lease.
12
13
  * @property {() => Promise<number>} onRefreshLease - Async refresh function. Must publish the refresh request over MQTT and resolve with new exp (ms since epoch). Throw on hard failure.
13
14
  * @property {number} [refreshEarlySeconds] - Seconds before exp when we should start refresh (e.g. 0.75 * ttl, default: 675s for 15min TTL)
14
15
  * @property {number} [maxReconnectDelayMs] - Max reconnect delay in ms (default 5000)
@@ -29,6 +30,11 @@ export class MqttControlPlaneClient {
29
30
  onOffline: (reason: string) => void;
30
31
  onFatalError: (reason: string, err?: unknown) => void;
31
32
  onRefreshLease: () => Promise<number>;
33
+ /** Story 3.13: called when a renewal finds the lease closed; reopens and resolves { exp, leaseId } or throws. */
34
+ onLeaseClosed: () => Promise<{
35
+ exp: number | null;
36
+ leaseId: string;
37
+ } | null>;
32
38
  refreshEarlySeconds: number;
33
39
  maxReconnectDelayMs: number;
34
40
  mode: "unique" | "legacy";
@@ -229,6 +235,13 @@ export type MqttControlPlaneClientOptions = {
229
235
  * - Called when we give up due to JWT expiry or unrecoverable error
230
236
  */
231
237
  onFatalError?: (reason: string, err?: unknown) => void;
238
+ /**
239
+ * - Story 3.13: reopen after a closed lease.
240
+ */
241
+ onLeaseClosed?: () => Promise<{
242
+ exp: number | null;
243
+ leaseId: string;
244
+ } | null>;
232
245
  /**
233
246
  * - Async refresh function. Must publish the refresh request over MQTT and resolve with new exp (ms since epoch). Throw on hard failure.
234
247
  */
@@ -22,6 +22,7 @@ import { ulid } from 'ulid';
22
22
  * @property {(client: any) => void | Promise<void>} [onConnected] - Called after successful connect
23
23
  * @property {(reason: string) => void} [onOffline] - Called when connection goes offline
24
24
  * @property {(reason: string, err?: unknown) => void} [onFatalError] - Called when we give up due to JWT expiry or unrecoverable error
25
+ * @property {() => Promise<{ exp: number | null, leaseId: string } | null>} [onLeaseClosed] - Story 3.13: reopen after a closed lease.
25
26
  * @property {() => Promise<number>} onRefreshLease - Async refresh function. Must publish the refresh request over MQTT and resolve with new exp (ms since epoch). Throw on hard failure.
26
27
  * @property {number} [refreshEarlySeconds] - Seconds before exp when we should start refresh (e.g. 0.75 * ttl, default: 675s for 15min TTL)
27
28
  * @property {number} [maxReconnectDelayMs] - Max reconnect delay in ms (default 5000)
@@ -42,6 +43,8 @@ export class MqttControlPlaneClient {
42
43
  this.onOffline = opts.onOffline;
43
44
  this.onFatalError = opts.onFatalError;
44
45
  this.onRefreshLease = opts.onRefreshLease;
46
+ /** Story 3.13: called when a renewal finds the lease closed; reopens and resolves { exp, leaseId } or throws. */
47
+ this.onLeaseClosed = opts.onLeaseClosed || null;
45
48
  this.refreshEarlySeconds = opts.refreshEarlySeconds ?? 675; // 0.75 * 900s (15 min TTL)
46
49
  this.maxReconnectDelayMs = opts.maxReconnectDelayMs ?? 5000;
47
50
  this.mode = opts.mode || (process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique');
@@ -933,6 +936,24 @@ export class MqttControlPlaneClient {
933
936
  }
934
937
  }
935
938
  catch (err) {
939
+ // Story 3.13: the lease was closed while this tunnel is still meant to run: reopen on the same
940
+ // address and port (the flow enforces the limit and the stop conditions) instead of ending.
941
+ if ((err?.code === 'LEASE_CLOSED' || err?.reason === 'lease_closed') && this.onLeaseClosed) {
942
+ try {
943
+ const r = await this.onLeaseClosed();
944
+ this.refreshPending = false;
945
+ if (r?.leaseId)
946
+ this.currentLeaseId = r.leaseId;
947
+ if (r?.exp)
948
+ this.scheduleRefresh(r.exp, r.leaseId);
949
+ this.logger?.info?.('mqtt.control_plane.lease_reopened', { leaseId: r?.leaseId || null });
950
+ return;
951
+ }
952
+ catch (reopenErr) {
953
+ this.handleFatal('lease_closed_reopen_refused', reopenErr);
954
+ return;
955
+ }
956
+ }
936
957
  // If it's an offline-ish error, buffer and try after reconnect
937
958
  if (this.isOfflineError(err)) {
938
959
  this.refreshPending = true;
@@ -18,6 +18,11 @@ export interface ControlPlaneSessionOptions {
18
18
  logger: Logger;
19
19
  /** Protocol-specific renewal (stays with the caller for now). */
20
20
  onRefreshLease: () => Promise<number | null>;
21
+ /** Story 3.13: reopen after a closed lease; resolves the new lease or throws (ends the tunnel). */
22
+ onLeaseClosed?: () => Promise<{
23
+ exp: number | null;
24
+ leaseId: string;
25
+ } | null>;
21
26
  /** HTTP passes its tunnel when the assignment moves to a new instance id. */
22
27
  getTunnel?: () => unknown;
23
28
  /** HTTP and UDP track it; TCP never has. */
@@ -16,7 +16,7 @@ class SessionEvents extends EventEmitter {
16
16
  }
17
17
  }
18
18
  export function createControlPlaneSession(o) {
19
- const { credentials, tunnelType, metadata, logger, onRefreshLease, getTunnel = () => null, trackSubscriptionReady = true, reportOffline = true, verboseRotationLogs = true, keepaliveSec = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || '60', 10), mode = process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique', } = o;
19
+ const { credentials, tunnelType, metadata, logger, onRefreshLease, onLeaseClosed, getTunnel = () => null, trackSubscriptionReady = true, reportOffline = true, verboseRotationLogs = true, keepaliveSec = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || '60', 10), mode = process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique', } = o;
20
20
  const events = new SessionEvents();
21
21
  const baseClientId = credentials.clientId;
22
22
  // TPB-12: instanceId is the full MQTT client id; it changes when the client id rotates on reconnect
@@ -83,6 +83,7 @@ export function createControlPlaneSession(o) {
83
83
  events.emit('fatal', { reason, error: err });
84
84
  },
85
85
  onRefreshLease: onRefreshLease,
86
+ onLeaseClosed,
86
87
  };
87
88
  if (reportOffline) {
88
89
  callbacks.onOffline = (reason) => {
@@ -0,0 +1,10 @@
1
+ export interface GoodbyeHandle {
2
+ core: any;
3
+ assignment: Record<string, any> | null;
4
+ opts: {
5
+ credentials: {
6
+ clientId: string;
7
+ };
8
+ };
9
+ }
10
+ export declare function sayGoodbye(h: GoodbyeHandle, timeoutMs?: number): Promise<'sent' | 'skipped' | 'timeout' | 'error'>;
@@ -0,0 +1,27 @@
1
+ // Story 3.13: a tunnel that stops on purpose tells the cloud, so its lease is closed at once. The close is
2
+ // sent over the device's own certificate connection (the coordinator's 11.22 checks apply) on its cmd/open
3
+ // topic, and the stop waits at most `timeoutMs` for the broker to take it (QoS 1); a goodbye never delays
4
+ // a stop longer than that, and a stop without one falls back to Story 3.12 (expiry plus grace).
5
+ import { randomUUID } from 'node:crypto';
6
+ export async function sayGoodbye(h, timeoutMs = 2000) {
7
+ const leaseId = h?.assignment?.leaseId;
8
+ const clientId = h?.opts?.credentials?.clientId;
9
+ const core = h?.core;
10
+ if (!core || !leaseId || !clientId || typeof core.publish !== 'function')
11
+ return 'skipped';
12
+ const instanceId = (typeof core.getClientId === 'function' ? core.getClientId() : core.clientId) || undefined;
13
+ const payload = JSON.stringify({ type: 'close', requestId: `close-${randomUUID()}`, clientId, instanceId, leaseIds: [leaseId] });
14
+ let timer;
15
+ try {
16
+ const sent = core.publish({ topic: `asyx/tunnel/clients/${clientId}/cmd/open`, payload, qos: 1, retain: false }).then(() => 'sent');
17
+ const late = new Promise((r) => { timer = setTimeout(() => r('timeout'), timeoutMs); });
18
+ return await Promise.race([sent, late]);
19
+ }
20
+ catch {
21
+ return 'error';
22
+ }
23
+ finally {
24
+ if (timer)
25
+ clearTimeout(timer);
26
+ }
27
+ }
@@ -1,3 +1,4 @@
1
+ import { ReopenLimiter } from './reopen.js';
1
2
  import { LifecycleEmitter } from '../lifecycle.js';
2
3
  import type { ControlPlaneCredentials } from '../control-plane/session.js';
3
4
  import type { RequestSink } from '../tunnel/request-sink.js';
@@ -16,6 +17,10 @@ export interface HttpTunnelOptions {
16
17
  logger: Logger;
17
18
  /** Called with each observability line when ASYX_DEBUG=1 (the CLI prints them). */
18
19
  onObserve?: (line: string) => void;
20
+ /** Story 1.9: while a live tunnel of this kind serves the address, ask again every 30 s instead of failing. */
21
+ waitIfInUse?: boolean;
22
+ /** 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`. */
23
+ replace?: boolean;
19
24
  }
20
25
  /**
21
26
  * Sent with 'notice': something the user may want to know that does not end the tunnel, e.g.
@@ -39,9 +44,15 @@ export declare class HttpTunnelHandle extends LifecycleEmitter {
39
44
  };
40
45
  tunnel: any;
41
46
  mqttClient: any;
47
+ /** Story 1.9: one id for this tunnel across its opens (a re-open is never "another tunnel"). */
48
+ readonly tunnelSession: string;
49
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
50
+ readonly reopenLimiter: ReopenLimiter;
42
51
  core: any;
43
52
  assignment: Record<string, any> | null;
44
53
  constructor(o: HttpTunnelOptions);
54
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
55
+ goodbye(timeoutMs?: number): Promise<'sent' | 'skipped' | 'timeout' | 'error'>;
45
56
  /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
46
57
  open(): Promise<HttpTunnelInfo>;
47
58
  /** Ask for a renewal now (SIGUSR2 in the CLI). */