asyx 0.7.0 → 0.7.2

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
@@ -21,7 +21,7 @@ Agent writes code → dev server starts → asyx tunnel → share HTTPS link
21
21
  | Account + enroll | **You** (once per machine) | `asyx setup` after [registering](https://www.asyx.ai/register) |
22
22
  | Build / edit code | **Agent** | Implements the feature locally |
23
23
  | Start dev server | **Agent or you** | `npm run dev`, `vite`, `flask run`, etc. |
24
- | Open public URL | **Agent or you** (terminal) | `asyx tunnel --http --port <port>` |
24
+ | Open public URL | **Agent or you** (terminal) | `asyx tunnel --http --port <port> --to <your hostname>` |
25
25
  | Share the link | **You** | PR comment, Slack, email, client review |
26
26
 
27
27
  Enrollment is human-gated (browser verification) so prompts alone cannot open tunnels from an unbound machine. After `asyx setup`, your agent only needs the port and one tunnel command.
@@ -30,19 +30,19 @@ Enrollment is human-gated (browser verification) so prompts alone cannot open tu
30
30
 
31
31
  ```bash
32
32
  npm install -g asyx # 1. install (Node 18.17+)
33
- asyx setup # 2. enroll once — approve in the browser with the code shown
33
+ asyx setup # 2. enroll once — approve in the browser; it prints your hostname
34
34
  npm run dev # 3. start your app (note the port, often 3000 or 5173)
35
- asyx tunnel --http --port 3000 # 4. second terminal — copy the printed URL
35
+ asyx tunnel --http --port 3000 --to yourname.tunnel.asyx.ai # 4. second terminal
36
36
  ```
37
37
 
38
- Share `https://yourname.tunnel.asyx.ai`. Press `Ctrl+C` in the tunnel terminal when the demo ends.
38
+ Share `https://yourname.tunnel.asyx.ai`. Press `Ctrl+C` in the tunnel terminal when the demo ends. (`--to` names the address the tunnel serves; leave it out and the tunnel serves this device's default address, the one `asyx setup` printed. The console shows each address's ready-made commands.)
39
39
 
40
40
  Works with React, Next.js, Vite, Flask, FastAPI, Express, static sites, local LLM UIs—anything speaking HTTP on localhost.
41
41
 
42
42
  Prefer no global install?
43
43
 
44
44
  ```bash
45
- npx asyx@latest tunnel --http --port 3000
45
+ npx asyx@latest tunnel --http --port 3000 --to yourname.tunnel.asyx.ai
46
46
  ```
47
47
 
48
48
  ### Copy-paste for your agent
@@ -59,22 +59,24 @@ Prerequisites (human completes once per machine):
59
59
  show the approval link to the human; the human approves with the code shown.
60
60
 
61
61
  When a local HTTP server is running on PORT:
62
- 1. Run: asyx tunnel --http --port PORT
63
- 2. Return the https://*.tunnel.asyx.ai URL as "public_demo_url"
62
+ 1. Run: asyx tunnel --http --port PORT --to HOSTNAME
63
+ 2. Return https://HOSTNAME as "public_demo_url"
64
64
  3. Do NOT read, print, or commit ~/.asyx/ or any private.pem files
65
65
  4. Stop tunnel with Ctrl+C when the user says the demo is over
66
66
 
67
67
  If asyx setup was never run, tell the human to run it before tunneling.
68
+ If the tunnel exits with code 75, the address already has a tunnel of
69
+ that kind: report it to the human; do not add --replace unless told to.
68
70
  ```
69
71
 
70
- Replace `PORT` with the actual port (e.g. `3000`, `5173`, `8080`).
72
+ Replace `PORT` with the actual port (e.g. `3000`, `5173`, `8080`) and `HOSTNAME` with your address (e.g. `orders-api.tunnel.asyx.ai`: printed by `asyx setup` and shown in the console).
71
73
 
72
74
  ### Example Cursor prompt
73
75
 
74
76
  ```text
75
77
  Implement the settings page, run the dev server on port 3000, then run
76
- asyx tunnel --http --port 3000 and give me the public demo URL.
77
- I already ran asyx setup on this machine.
78
+ asyx tunnel --http --port 3000 --to orders-api.tunnel.asyx.ai
79
+ and give me the public demo URL. I already ran asyx setup on this machine.
78
80
  ```
79
81
 
80
82
  **Can the agent run the tunnel itself?** Yes—if your IDE grants terminal access and `asyx` is installed. Many teams run the tunnel command themselves for visibility.
@@ -108,9 +110,9 @@ asyx setup
108
110
  - Running `asyx setup` again on the same machine keeps the same device and hostname (it renews the certificate).
109
111
  - Run `asyx setup` on each host you want to trust—certificates are single-device.
110
112
 
111
- ### Device names and several devices
113
+ ### Addresses, devices and names
112
114
 
113
- Each device on your account has its own hostname under `tunnel.asyx.ai`. Your first device uses your account's name; each further device gets its own:
115
+ Hostnames and ports belong to your **account**, not to one computer. Any device you have set up can serve any address of your account: name it with `--to <hostname>`. Without `--to`, a device serves its **default address**, the hostname it got at setup (an app serves only its own address). Your first device uses your account's name; setting up a further device adds an address for it:
114
116
 
115
117
  ```bash
116
118
  asyx name check orders-api # is orders-api.tunnel.asyx.ai available? (no setup needed)
@@ -119,7 +121,7 @@ asyx setup --random # or a generated name such as quiet-otte
119
121
  asyx setup # or choose on the approval page (it proposes <machine>-<account>)
120
122
  ```
121
123
 
122
- Names use 3–30 characters: lowercase letters, digits and hyphens, starting and ending with a letter or digit. Some names are reserved. How many devices an account can have depends on its plan.
124
+ Names use 3–30 characters: lowercase letters, digits and hyphens, starting and ending with a letter or digit. Some names are reserved. How many devices and addresses an account can have depends on its plan.
123
125
 
124
126
  ### For agents and scripts: `--json` and exit codes
125
127
 
@@ -144,24 +146,24 @@ On failure the last line is `{"event":"error","error":"<code>",…}` (with `sugg
144
146
  ## HTTP tunnels (most common)
145
147
 
146
148
  ```bash
147
- asyx tunnel --http --port 3000
149
+ asyx tunnel --http --port 3000 --to orders-api.tunnel.asyx.ai
148
150
  ```
149
151
 
150
152
  - Forwards to your app on localhost (loopback only; works whether it listens on IPv4 `127.0.0.1` or IPv6 `::1`).
151
- - Prints your device's stable `https://<hostname>.tunnel.asyx.ai` URL.
153
+ - Prints the address's stable `https://<hostname>.tunnel.asyx.ai` URL (the same on every start, from any of your devices).
152
154
  - If your app stops answering, the tunnel stays up: the terminal says so, visitors see a "not reachable" page, and the terminal tells you when the app is answering again.
153
155
  - TLS and token refresh handled automatically; your app keeps its port.
154
156
  - If the connection drops (network loss, laptop wake, Asyx server maintenance), the CLI reconnects on its own and the same URL comes back.
155
157
 
156
- ### Private demos (Quickpass)
158
+ ### Private demos (QuickPass)
157
159
 
158
160
  For client-only or team-only previews—not open to the whole internet:
159
161
 
160
162
  ```bash
161
- asyx tunnel --http --port 3000 --secgroup reviewers
163
+ asyx tunnel --http --port 3000 --to orders-api.tunnel.asyx.ai --secgroup reviewers
162
164
  ```
163
165
 
164
- Guests enroll via Quickpass; the relay enforces membership. See https://www.asyx.ai/docs/quickpass
166
+ Guests enroll via QuickPass; the relay enforces membership. See https://www.asyx.ai/docs/quickpass
165
167
 
166
168
  ---
167
169
 
@@ -172,24 +174,27 @@ All tunnels are loopback-only. The CLI forwards to your existing listener—it n
172
174
  **TCP** — databases, SSH, games:
173
175
 
174
176
  ```bash
175
- asyx tunnel --tcp --port <targetPort> [--name <alias>] [--external-port <publicPort>]
177
+ asyx tunnel --tcp --port 5432 --to orders-api.tunnel.asyx.ai
178
+ asyx tunnel --tcp --port 5432 --to orders-api.tunnel.asyx.ai --external-port 10003 # a specific public port
176
179
  ```
177
180
 
178
181
  **UDP** — games, realtime apps:
179
182
 
180
183
  ```bash
181
- asyx tunnel --udp --port <targetPort> [--external-port <publicPort>]
184
+ asyx tunnel --udp --port 27015 --to orders-api.tunnel.asyx.ai [--external-port <publicPort>]
182
185
  ```
183
186
 
184
187
  **Minecraft** — shortcut with SRV record (players use hostname only):
185
188
 
186
189
  ```bash
187
- asyx tunnel --minecraft [--port 25565] [--name <alias>]
190
+ asyx tunnel --minecraft --to orders-api.tunnel.asyx.ai [--port 25565] [--name <alias>]
188
191
  ```
189
192
 
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>`).
193
+ **Public ports.** Your account has 10 TCP and 10 UDP public ports (its block). An address gets one of each kind the first time it opens a TCP or UDP tunnel and keeps it: every restart, from any of your devices, uses the same public port. `--external-port <p>` picks a specific port of your block for the address; a port that already belongs to another of your addresses is refused with its name. Ports are not released automatically.
191
194
 
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.
195
+ After a tunnel opens, the CLI prints the public hostname (and port for TCP/UDP) plus the local target (`tcp://127.0.0.1:<port>` or `udp://127.0.0.1:<port>`).
196
+
197
+ 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
198
 
194
199
  | Variable | Effect |
195
200
  | --- | --- |
@@ -202,12 +207,12 @@ If the connection of a TCP or UDP tunnel drops (network loss, Asyx server mainte
202
207
  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
208
 
204
209
  ```text
205
- ❌ smart.tunnel.asyx.ai already has an HTTP tunnel from this computer since 2:02 PM (serving localhost:8790).
210
+ ❌ orders-api.tunnel.asyx.ai already has an HTTP tunnel from this computer since 2:02 PM (serving localhost:3000).
206
211
  One address runs one HTTP tunnel at a time.
207
212
  Stop that tunnel first, or add --replace to take over.
208
213
  ```
209
214
 
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.
215
+ - **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
216
  - **`--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
217
  - **`--wait`** keeps trying every 30 seconds instead of exiting, for scripts that should start as soon as the address is free.
213
218
  - **`--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).
@@ -217,7 +222,7 @@ A refused tunnel and a replaced tunnel exit with code **75** ("try again later")
217
222
  **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
223
 
219
224
  ```bash
220
- asyx tunnel --http --port 8790 --to smart.tunnel.asyx.ai --wait
225
+ asyx tunnel --http --port 3000 --to orders-api.tunnel.asyx.ai --wait
221
226
  ```
222
227
 
223
228
  With systemd you can also skip the restart entirely with `RestartPreventExitStatus=75`.
@@ -233,15 +238,27 @@ asyx help # commands; asyx tunnel --help for tunnel options
233
238
  asyx --version
234
239
  asyx setup [--hostname <name> | --random] [--json]
235
240
  asyx name check <name> [--json]
236
- asyx tunnel --http --port <n> [--secgroup <slug>]
237
- asyx tunnel --tcp --port <n> [--name <alias>] [--external-port <p>]
238
- asyx tunnel --udp --port <n> [--external-port <p>]
239
- asyx tunnel --minecraft [--port <n>] [--name <alias>]
240
- # any tunnel: --to <hostname> --replace --wait --json
241
+ asyx tunnel --http --port <n> --to <hostname> [--secgroup <slug>]
242
+ asyx tunnel --tcp --port <n> --to <hostname> [--name <alias>] [--external-port <p>]
243
+ asyx tunnel --udp --port <n> --to <hostname> [--external-port <p>]
244
+ asyx tunnel --minecraft --to <hostname> [--port <n>] [--name <alias>]
245
+ # any tunnel: --replace --wait --json (without --to: this device's default address)
241
246
  ```
242
247
 
243
248
  ---
244
249
 
250
+ ## What's new in 0.7.2
251
+
252
+ **Refusals always come with words** — if the cloud refuses a tunnel with a reason this version does not know yet, the CLI now shows the explanation the cloud sends instead of only a code. A device whose setup is incomplete is told to run `asyx setup` again (or contact support), and the tunnel stops with exit code 1.
253
+
254
+ ## What's new in 0.7.1
255
+
256
+ **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.
257
+
258
+ **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.
259
+
260
+ **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.
261
+
245
262
  ## What's new in 0.7.0
246
263
 
247
264
  **`--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.
@@ -314,7 +331,7 @@ Changes since 0.6.1, in short: `--to`, one tunnel of each kind per address (`--r
314
331
  | Cursor + Asyx | https://www.asyx.ai/docs/cursor-asyx |
315
332
  | Agent checklist | https://www.asyx.ai/docs/ai-agent-checklist |
316
333
  | Expose localhost | https://www.asyx.ai/docs/expose-localhost |
317
- | Quickpass (guest access) | https://www.asyx.ai/docs/quickpass |
334
+ | QuickPass (guest access) | https://www.asyx.ai/docs/quickpass |
318
335
  | vs ngrok & Cloudflare | https://www.asyx.ai/docs/vs-ngrok-cloudflare |
319
336
 
320
337
  ---
@@ -325,14 +342,14 @@ Changes since 0.6.1, in short: `--to`, one tunnel of each kind per address (`--r
325
342
  - **Do not** tunnel database admin ports without authentication.
326
343
  - **Stop** the tunnel when the demo ends (`Ctrl+C`).
327
344
  - Treat the public URL as a temporary preview—not a production deploy.
328
- - Agents **cannot** enroll a device (`asyx setup` requires browser verification) or open tunnels from a machine that has not been set up.
345
+ - 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.
329
346
 
330
347
  ---
331
348
 
332
349
  ## Logging
333
350
 
334
351
  ```bash
335
- ASYX_LOG_LEVEL=debug asyx tunnel --http --port 3000
352
+ ASYX_LOG_LEVEL=debug asyx tunnel --http --port 3000 --to orders-api.tunnel.asyx.ai
336
353
  ```
337
354
 
338
355
  Levels: `error` | `warn` | `info` | `debug` (default `info`).
@@ -350,9 +367,11 @@ Levels: `error` | `warn` | `info` | `debug` (default `info`).
350
367
  | 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` |
351
368
  | Tunnel stops right after starting with `jwt_expired_before_refresh` | Your computer's clock is wrong; turn on automatic time and try again |
352
369
  | Tunnel URL 502 / unreachable | Dev server not running on the same port |
353
- | Link dies overnight | Expected—the tunnel lives only while the CLI runs and the machine is awake |
370
+ | 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 |
354
371
  | 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) |
355
- | External port rejected | `--external-port` must be inside your assigned 10-port block |
372
+ | External port rejected | `--external-port` must be inside your account's 10-port block and not belong to another of your addresses (the message names it) |
373
+ | "… is not an address of this account" | Check the `--to` hostname; it must be one of your account's addresses (see the console) |
374
+ | "This device is not set up for your account yet" | Run `asyx setup` again on that computer; if it persists, contact support@asyx.ai |
356
375
  | Windows: secure connection fails at startup | Re-run `asyx setup` to regenerate the device key |
357
376
 
358
377
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "Asyx tunnel CLI — secure localhost exposure (HTTP, TCP, UDP)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -58,9 +58,59 @@ export function printOpenReject({ code, reason, data }) {
58
58
  process.exit(1);
59
59
  return;
60
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
+ }
104
+ // Story 2.12 c3: should never happen; the coordinator sends the words (shown as sent), with ours as fallback.
105
+ case 'account_not_migrated': {
106
+ process.stderr.write(`${d.message || 'This device is not set up for your account yet. Run asyx setup again on this computer; if that does not help, contact support@asyx.ai.'}\n`);
107
+ process.exit(1);
108
+ return;
109
+ }
61
110
  default:
62
- // Not fatal: print and keep running (e.g. a refused renewal).
63
- process.stdout.write(`❌ Connection rejected${reason ? ` (${reason})` : ''}\n`);
111
+ // Not fatal: print and keep running (e.g. a refused renewal). Story 2.12: a message the coordinator
112
+ // sends with a reason this CLI does not know is shown rather than a bare code.
113
+ process.stdout.write(`❌ Connection rejected${reason ? ` (${reason})` : ''}${typeof d.message === 'string' && d.message ? `: ${d.message}` : ''}\n`);
64
114
  }
65
115
  }
66
116
 
@@ -34,22 +34,23 @@ export default async function tunnel(args = []) {
34
34
  if (parsed.help || args.length === 0) {
35
35
  logger.info("cli.help", {});
36
36
  process.stdout.write(`Usage:
37
- asyx tunnel --http --port <n> [--secgroup <slug>]
37
+ asyx tunnel --http --port <n> --to <hostname> [--secgroup <slug>]
38
38
  HTTP tunnel: a public HTTPS URL for a web app on localhost:<n>.
39
39
  --secgroup <slug> QuickPass security group; only its members can open the URL
40
40
 
41
- asyx tunnel --tcp --port <n> [--name <alias>] [--external-port <p>]
41
+ asyx tunnel --tcp --port <n> --to <hostname> [--name <alias>] [--external-port <p>]
42
42
  TCP tunnel: a public TCP port for a service on localhost:<n> (databases, SSH, games).
43
43
 
44
- asyx tunnel --udp --port <n> [--external-port <p>]
44
+ asyx tunnel --udp --port <n> --to <hostname> [--external-port <p>]
45
45
  UDP tunnel: a public UDP port for a service on localhost:<n> (games, realtime apps).
46
46
 
47
- asyx tunnel --minecraft [--port <n>] [--name <alias>]
47
+ asyx tunnel --minecraft --to <hostname> [--port <n>] [--name <alias>]
48
48
  Minecraft server (default port 25565); players connect with the hostname only.
49
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)
52
- --external-port <p> choose the public port inside your assigned 10-port block
50
+ --to <hostname> the address this tunnel serves, e.g. --to orders-api.tunnel.asyx.ai: any
51
+ address of your account; without it, this device's default address
52
+ --external-port <p> a specific public port of your account's 10-port block (it then belongs
53
+ to that address); without it, the address keeps its own port
53
54
  --replace take over this address's running tunnel of the same kind (it is told and stops)
54
55
  --wait if the address already runs this kind, keep trying every 30 s instead of exiting
55
56
  --json print refusals as JSON
@@ -565,6 +566,9 @@ async function httpTunnel(localPort, secGroupSlug) {
565
566
  onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
566
567
  });
567
568
  handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
569
+ // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
570
+ handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
571
+ 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`));
568
572
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
569
573
  handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
570
574
  handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
@@ -632,6 +636,8 @@ async function httpTunnel(localPort, secGroupSlug) {
632
636
  process.stderr.write("tunnel.close() timed out; forcing exit\n");
633
637
  process.exit(0);
634
638
  }, 3000);
639
+ // Story 3.13: say goodbye first (the lease closes at once); never waits more than 2 s
640
+ try { const bye = await handle.goodbye?.(2000); logger.debug('tunnel.goodbye', { result: bye }); } catch (e) { logger.debug('tunnel.goodbye.error', { error: e?.message }); }
635
641
  try {
636
642
  handle.tunnel.close();
637
643
  } catch (e) {
@@ -739,6 +745,9 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
739
745
  onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
740
746
  });
741
747
  handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
748
+ // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
749
+ handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
750
+ 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`));
742
751
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
743
752
  handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
744
753
  handle.on('control-fatal', ({ reason }) => {
@@ -882,6 +891,9 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
882
891
  onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
883
892
  });
884
893
  handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
894
+ // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
895
+ handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
896
+ 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`));
885
897
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
886
898
  handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
887
899
  handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
package/src/main.js CHANGED
@@ -39,9 +39,9 @@ Usage: asyx <command>
39
39
  asyx setup
40
40
  asyx setup --hostname orders-api (or --random; add --json for agents)
41
41
  asyx name check orders-api
42
- asyx tunnel --http --port 3000
43
- asyx tunnel --tcp --port 5432
44
- asyx tunnel --udp --port 27015
42
+ asyx tunnel --http --port 3000 --to orders-api.tunnel.asyx.ai
43
+ asyx tunnel --tcp --port 5432 --to orders-api.tunnel.asyx.ai
44
+ asyx tunnel --udp --port 27015 --to orders-api.tunnel.asyx.ai
45
45
 
46
46
  Options for each tunnel type: asyx tunnel --help
47
47
  Documentation: https://www.asyx.ai/docs
@@ -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';
@@ -45,9 +46,13 @@ export declare class HttpTunnelHandle extends LifecycleEmitter {
45
46
  mqttClient: any;
46
47
  /** Story 1.9: one id for this tunnel across its opens (a re-open is never "another tunnel"). */
47
48
  readonly tunnelSession: string;
49
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
50
+ readonly reopenLimiter: ReopenLimiter;
48
51
  core: any;
49
52
  assignment: Record<string, any> | null;
50
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'>;
51
56
  /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
52
57
  open(): Promise<HttpTunnelInfo>;
53
58
  /** Ask for a renewal now (SIGUSR2 in the CLI). */
@@ -7,6 +7,8 @@
7
7
  // open() rejects with ConnectionError control_plane_connect_failed | assignment_failed |
8
8
  // tunnel_connect_failed. The renewal callback (in-band reauth, reconnect fallback) is unchanged.
9
9
  import { randomUUID } from 'node:crypto';
10
+ import { sayGoodbye } from './goodbye.js'; // Story 3.13
11
+ import { ReopenLimiter, reopenPayload } from './reopen.js'; // Story 3.13
10
12
  import { LifecycleEmitter } from '../lifecycle.js';
11
13
  import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
12
14
  import { createControlPlaneSession } from '../control-plane/session.js';
@@ -42,12 +44,18 @@ export class HttpTunnelHandle extends LifecycleEmitter {
42
44
  mqttClient = null;
43
45
  /** Story 1.9: one id for this tunnel across its opens (a re-open is never "another tunnel"). */
44
46
  tunnelSession = randomUUID();
47
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
48
+ reopenLimiter = new ReopenLimiter();
45
49
  core = null;
46
50
  assignment = null;
47
51
  constructor(o) {
48
52
  super();
49
53
  this.opts = { secGroupSlug: null, ...o };
50
54
  }
55
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
56
+ async goodbye(timeoutMs = 2000) {
57
+ return sayGoodbye(this, timeoutMs);
58
+ }
51
59
  /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
52
60
  async open() {
53
61
  const { credentials, localPort, secGroupSlug, logger } = this.opts;
@@ -385,6 +393,8 @@ export class HttpTunnelHandle extends LifecycleEmitter {
385
393
  logger.debug('jwt.refresh.success', { method: 'reconnect', leaseId: newAssignment.leaseId });
386
394
  return expMs;
387
395
  };
396
+ // Story 3.13: set once the open request exists (below); used by the control plane and the tunnel.
397
+ const reopenRef = { fn: null };
388
398
  const cpSession = createControlPlaneSession({
389
399
  credentials,
390
400
  tunnelType: 'http',
@@ -398,6 +408,8 @@ export class HttpTunnelHandle extends LifecycleEmitter {
398
408
  }
399
409
  return r;
400
410
  },
411
+ onLeaseClosed: async () => { if (!reopenRef.fn)
412
+ throw new Error('reopen unavailable'); return reopenRef.fn(); }, // Story 3.13
401
413
  instanceIdRef,
402
414
  subscriptionReadyRef,
403
415
  getTunnel: () => tunnelInstanceRef.tunnel,
@@ -552,6 +564,47 @@ export class HttpTunnelHandle extends LifecycleEmitter {
552
564
  }
553
565
  // 8) Connect to the relay (was connectToRelay)
554
566
  const { HttpTunnel } = await import('../tunnel/http-tunnel.js');
567
+ // Story 3.13: a fresh open for the same address (same session, never --replace), then the tunnel takes
568
+ // the new token and relay and reconnects, as the renewal fallback does.
569
+ reopenRef.fn = async () => {
570
+ if (!this.reopenLimiter.allow()) {
571
+ this.emit('reopen_refused', { code: 'reopen_limit', details: { limit: 3, windowMin: 10 } });
572
+ throw new RefusedError('reopen_limit', 'reopened 3 times in 10 minutes', { details: { limit: 3, windowMin: 10 } });
573
+ }
574
+ const rid = randomUUID();
575
+ setExpectedRequestId(instanceId, rid);
576
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(reopenPayload(openPayload, rid, null)), qos: 1, retain: false });
577
+ let next;
578
+ try {
579
+ next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
580
+ }
581
+ catch (e) {
582
+ this.emit('reopen_refused', { code: e?.code || e?.reason || e?.data?.reason || 'refused', details: e?.details || e?.data || null });
583
+ throw e;
584
+ }
585
+ const { setAssignment: setA } = await import('../state/assignment.js');
586
+ setA(instanceId, next);
587
+ let expMs = null;
588
+ try {
589
+ expMs = JSON.parse(Buffer.from(String(next.jwt || '').split('.')[1] || '', 'base64url').toString()).exp * 1000 || null;
590
+ }
591
+ catch {
592
+ expMs = null;
593
+ }
594
+ const t = tunnelInstanceRef.tunnel;
595
+ if (t) {
596
+ t.jwt = next.jwt;
597
+ t.requestId = next.requestId;
598
+ t.relayUrl = next.relayUrl;
599
+ t.headers = { 'Authorization': `Bearer ${next.jwt}`, 'X-Asyx-DeviceId': deviceIdRef, 'X-Asyx-RequestId': next.requestId };
600
+ t.jwtMeta = { token: next.jwt, expMs };
601
+ await t._attemptConnect();
602
+ }
603
+ this.assignment = next;
604
+ logger.info('http.reopen.ok', { leaseId: next.leaseId, relayId: next.relayId });
605
+ this.emit('reopened', { leaseId: next.leaseId, relayId: next.relayId, publicPort: null });
606
+ return { exp: expMs, leaseId: next.leaseId };
607
+ };
555
608
  const tunnel = new HttpTunnel({
556
609
  relayUrl: assignment.relayUrl,
557
610
  jwt: assignment.jwt, // Use JWT as-is (no validation)
@@ -573,6 +626,13 @@ export class HttpTunnelHandle extends LifecycleEmitter {
573
626
  // used to print is a notice; the CLI keeps the exit code and the wording.
574
627
  onFatal: (code) => this.setState('closed', { error: new ConnectionError(code, `http tunnel ended: ${code}`, { details: { exitCode: 1 } }) }),
575
628
  onNotice: (code, details) => this.emit('notice', { code, ...details }),
629
+ onLeaseClosed: async () => { try {
630
+ await reopenRef.fn?.();
631
+ return true;
632
+ }
633
+ catch {
634
+ return false;
635
+ } }, // Story 3.13
576
636
  });
577
637
  tunnelInstanceRef.tunnel = tunnel;
578
638
  this.tunnel = tunnel;
@@ -0,0 +1,9 @@
1
+ export declare class ReopenLimiter {
2
+ private readonly max;
3
+ private readonly windowMs;
4
+ private times;
5
+ constructor(max?: number, windowMs?: number);
6
+ allow(now?: number): boolean;
7
+ }
8
+ /** The open request for a reopen: same address, port and session, never `replace`. */
9
+ export declare function reopenPayload(openPayload: Record<string, any>, requestId: string, publicPort: number | null | undefined): Record<string, any>;
@@ -0,0 +1,27 @@
1
+ // Story 3.13: a tunnel whose lease was closed while it is still meant to run opens a fresh tunnel on the
2
+ // same address (and TCP/UDP port), at most 3 times in 10 minutes; a reopen never carries --replace, so a
3
+ // tunnel that a newer one replaced is refused (address_in_use) instead of taking the address back.
4
+ export class ReopenLimiter {
5
+ max;
6
+ windowMs;
7
+ times = [];
8
+ constructor(max = 3, windowMs = 10 * 60_000) {
9
+ this.max = max;
10
+ this.windowMs = windowMs;
11
+ }
12
+ allow(now = Date.now()) {
13
+ this.times = this.times.filter((t) => now - t < this.windowMs);
14
+ if (this.times.length >= this.max)
15
+ return false;
16
+ this.times.push(now);
17
+ return true;
18
+ }
19
+ }
20
+ /** The open request for a reopen: same address, port and session, never `replace`. */
21
+ export function reopenPayload(openPayload, requestId, publicPort) {
22
+ const { replace, ...rest } = openPayload;
23
+ const again = { ...rest, requestId, reopen: true };
24
+ if (publicPort)
25
+ again.opts = { ...(rest.opts || {}), requestedExternalPort: publicPort };
26
+ return again;
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 { Logger } from '../types.js';
@@ -48,9 +49,13 @@ export declare class TcpTunnelHandle extends LifecycleEmitter {
48
49
  mqttClient: any;
49
50
  /** Story 1.9: one id for this tunnel across its opens. */
50
51
  readonly tunnelSession: string;
52
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
53
+ readonly reopenLimiter: ReopenLimiter;
51
54
  core: any;
52
55
  assignment: Record<string, any> | null;
53
56
  constructor(o: TcpTunnelOptions);
57
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
58
+ goodbye(timeoutMs?: number): Promise<'sent' | 'skipped' | 'timeout' | 'error'>;
54
59
  /** Connect the control plane, get a lease and open the data plane; rejects with a typed error. */
55
60
  open(): Promise<TcpTunnelInfo>;
56
61
  /** Close the data plane, then the control plane. */
@@ -11,6 +11,8 @@
11
11
  // tcp_port_block_exhausted_for_tenant | tcp_port_capacity_exhausted | tenant_tcp_lease_limit_reached
12
12
  // (details carry what the CLI prints: requestedPort, blockStart, blockEnd, relayId).
13
13
  import { randomUUID } from 'node:crypto';
14
+ import { ReopenLimiter, reopenPayload } from './reopen.js'; // Story 3.13
15
+ import { sayGoodbye } from './goodbye.js'; // Story 3.13
14
16
  import { LifecycleEmitter } from '../lifecycle.js';
15
17
  import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
16
18
  import { createControlPlaneSession } from '../control-plane/session.js';
@@ -22,12 +24,18 @@ export class TcpTunnelHandle extends LifecycleEmitter {
22
24
  mqttClient = null;
23
25
  /** Story 1.9: one id for this tunnel across its opens. */
24
26
  tunnelSession = randomUUID();
27
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
28
+ reopenLimiter = new ReopenLimiter();
25
29
  core = null;
26
30
  assignment = null;
27
31
  constructor(o) {
28
32
  super();
29
33
  this.opts = { serviceName: null, kind: null, requestedExternalPort: null, ...o };
30
34
  }
35
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
36
+ async goodbye(timeoutMs = 2000) {
37
+ return sayGoodbye(this, timeoutMs);
38
+ }
31
39
  /** Connect the control plane, get a lease and open the data plane; rejects with a typed error. */
32
40
  async open() {
33
41
  const { credentials, localPort, target, serviceName, kind, requestedExternalPort, logger } = this.opts;
@@ -237,6 +245,23 @@ export class TcpTunnelHandle extends LifecycleEmitter {
237
245
  metadata: { baseClientId, localPort, serviceName, kind, requestedExternalPort },
238
246
  logger,
239
247
  onRefreshLease,
248
+ // Story 3.13: a renewal that finds the lease closed reopens on the same port (limit and stop
249
+ // conditions in reassignSamePort); a refusal ends the tunnel as before.
250
+ onLeaseClosed: async () => {
251
+ const ok = await this.tunnel?.reopenAfterLeaseClosed?.();
252
+ if (!ok)
253
+ throw new Error('reopen refused');
254
+ const { getAssignment: getA } = await import('../state/assignment.js');
255
+ const a = getA(instanceIdRef.instanceId);
256
+ let exp = null;
257
+ try {
258
+ exp = JSON.parse(Buffer.from(String(a?.jwt || '').split('.')[1] || '', 'base64url').toString()).exp * 1000 || null;
259
+ }
260
+ catch {
261
+ exp = null;
262
+ }
263
+ return a?.leaseId ? { exp, leaseId: a.leaseId } : null;
264
+ },
240
265
  instanceIdRef,
241
266
  subscriptionReadyRef,
242
267
  trackSubscriptionReady: false, // TCP has never tracked it
@@ -400,12 +425,25 @@ export class TcpTunnelHandle extends LifecycleEmitter {
400
425
  const { setAssignment: setA, getAssignment: getA } = await import('../state/assignment.js');
401
426
  const cur = getA(instanceIdRef.instanceId) || assignment;
402
427
  const rid = randomUUID();
403
- const again = { ...openPayload, requestId: rid, opts: { ...(openPayload.opts || {}), requestedExternalPort: cur.publicPort ?? assignment.publicPort } };
428
+ if (!this.reopenLimiter.allow()) { // Story 3.13: at most 3 reopens in 10 minutes
429
+ this.emit('reopen_refused', { code: 'reopen_limit', details: { limit: 3, windowMin: 10 } });
430
+ throw new RefusedError('reopen_limit', 'reopened 3 times in 10 minutes', { details: { limit: 3, windowMin: 10 } });
431
+ }
432
+ const again = reopenPayload(openPayload, rid, cur.publicPort ?? assignment.publicPort); // never carries replace
404
433
  setExpectedRequestId(instanceIdRef.instanceId, rid);
405
434
  await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
406
- const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
435
+ let next;
436
+ try {
437
+ next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
438
+ }
439
+ catch (e) {
440
+ // Story 3.13: a refused reopen ends the tunnel and says why
441
+ this.emit('reopen_refused', { code: e?.code || e?.reason || e?.data?.reason || 'refused', details: e?.details || e?.data || null });
442
+ throw e;
443
+ }
407
444
  setA(instanceIdRef.instanceId, next);
408
445
  logger.info('tcp.reassign.ok', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
446
+ this.emit('reopened', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort }); // Story 3.13: one line for the user
409
447
  return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
410
448
  };
411
449
  }
@@ -522,6 +560,10 @@ export class TcpTunnelHandle extends LifecycleEmitter {
522
560
  }
523
561
  /** Close the data plane, then the control plane. */
524
562
  async close() {
563
+ try {
564
+ await this.goodbye(2000);
565
+ }
566
+ catch { /* Story 3.13: a goodbye never blocks a stop */ }
525
567
  try {
526
568
  this.tunnel?.close();
527
569
  }
@@ -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 { Logger } from '../types.js';
@@ -36,9 +37,13 @@ export declare class UdpTunnelHandle extends LifecycleEmitter {
36
37
  mqttClient: any;
37
38
  /** Story 1.9: one id for this tunnel across its opens. */
38
39
  readonly tunnelSession: string;
40
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
41
+ readonly reopenLimiter: ReopenLimiter;
39
42
  core: any;
40
43
  assignment: Record<string, any> | null;
41
44
  constructor(o: UdpTunnelOptions);
45
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
46
+ goodbye(timeoutMs?: number): Promise<'sent' | 'skipped' | 'timeout' | 'error'>;
42
47
  /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
43
48
  open(): Promise<UdpTunnelInfo>;
44
49
  /** Close the data plane, then the control plane. */
@@ -7,6 +7,8 @@
7
7
  // open() rejects with a ConnectionError whose code tells the caller what failed:
8
8
  // control_plane_connect_failed, udp_relay_unavailable, assignment_failed, tunnel_connect_failed.
9
9
  import { randomUUID } from 'node:crypto';
10
+ import { ReopenLimiter, reopenPayload } from './reopen.js'; // Story 3.13
11
+ import { sayGoodbye } from './goodbye.js'; // Story 3.13
10
12
  import { LifecycleEmitter } from '../lifecycle.js';
11
13
  import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
12
14
  import { createControlPlaneSession } from '../control-plane/session.js';
@@ -19,12 +21,18 @@ export class UdpTunnelHandle extends LifecycleEmitter {
19
21
  mqttClient = null;
20
22
  /** Story 1.9: one id for this tunnel across its opens. */
21
23
  tunnelSession = randomUUID();
24
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
25
+ reopenLimiter = new ReopenLimiter();
22
26
  core = null;
23
27
  assignment = null;
24
28
  constructor(o) {
25
29
  super();
26
30
  this.opts = { targetHost: '127.0.0.1', requestedExternalPort: null, ...o };
27
31
  }
32
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
33
+ async goodbye(timeoutMs = 2000) {
34
+ return sayGoodbye(this, timeoutMs);
35
+ }
28
36
  /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
29
37
  async open() {
30
38
  const { credentials, targetPort, targetHost, requestedExternalPort, logger } = this.opts;
@@ -110,6 +118,23 @@ export class UdpTunnelHandle extends LifecycleEmitter {
110
118
  metadata: { baseClientId, targetPort, targetHost, requestedExternalPort },
111
119
  logger,
112
120
  onRefreshLease,
121
+ // Story 3.13: a renewal that finds the lease closed reopens on the same port (limit and stop
122
+ // conditions in reassignSamePort); a refusal ends the tunnel as before.
123
+ onLeaseClosed: async () => {
124
+ const ok = await this.tunnel?.reopenAfterLeaseClosed?.();
125
+ if (!ok)
126
+ throw new Error('reopen refused');
127
+ const { getAssignment: getA } = await import('../state/assignment.js');
128
+ const a = getA(instanceIdRef.instanceId);
129
+ let exp = null;
130
+ try {
131
+ exp = JSON.parse(Buffer.from(String(a?.jwt || '').split('.')[1] || '', 'base64url').toString()).exp * 1000 || null;
132
+ }
133
+ catch {
134
+ exp = null;
135
+ }
136
+ return a?.leaseId ? { exp, leaseId: a.leaseId } : null;
137
+ },
113
138
  instanceIdRef,
114
139
  subscriptionReadyRef,
115
140
  verboseRotationLogs: false,
@@ -278,12 +303,25 @@ export class UdpTunnelHandle extends LifecycleEmitter {
278
303
  const { setAssignment: setA, getAssignment: getA } = await import('../state/assignment.js');
279
304
  const cur = getA(instanceIdRef.instanceId) || assignment;
280
305
  const rid = randomUUID();
281
- const again = { ...openPayload, requestId: rid, externalPort: cur.publicPort ?? assignment.publicPort };
306
+ if (!this.reopenLimiter.allow()) { // Story 3.13: at most 3 reopens in 10 minutes
307
+ this.emit('reopen_refused', { code: 'reopen_limit', details: { limit: 3, windowMin: 10 } });
308
+ throw new RefusedError('reopen_limit', 'reopened 3 times in 10 minutes', { details: { limit: 3, windowMin: 10 } });
309
+ }
310
+ const again = { ...reopenPayload(openPayload, rid, null), externalPort: cur.publicPort ?? assignment.publicPort }; // never carries replace
282
311
  setExpectedRequestId(instanceIdRef.instanceId, rid);
283
312
  await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
284
- const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
313
+ let next;
314
+ try {
315
+ next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
316
+ }
317
+ catch (e) {
318
+ // Story 3.13: a refused reopen ends the tunnel and says why
319
+ this.emit('reopen_refused', { code: e?.code || e?.reason || e?.data?.reason || 'refused', details: e?.details || e?.data || null });
320
+ throw e;
321
+ }
285
322
  setA(instanceIdRef.instanceId, next);
286
323
  logger.info('udp.reassign.ok', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
324
+ this.emit('reopened', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort }); // Story 3.13: one line for the user
287
325
  return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
288
326
  };
289
327
  }
@@ -381,6 +419,10 @@ export class UdpTunnelHandle extends LifecycleEmitter {
381
419
  }
382
420
  /** Close the data plane, then the control plane. */
383
421
  async close() {
422
+ try {
423
+ await this.goodbye(2000);
424
+ }
425
+ catch { /* Story 3.13: a goodbye never blocks a stop */ }
384
426
  try {
385
427
  this.tunnel?.close();
386
428
  }
@@ -228,6 +228,15 @@ const registry = {
228
228
  if (rejectAssignment(e.requestId, new RefusedError('address_in_use', 'a live tunnel of this kind already serves this address', { details: d })))
229
229
  return;
230
230
  }
231
+ // Story 3.13: a renewal (or reopen) refused because the lease is closed fails the request waiting
232
+ // for it with LEASE_CLOSED, so the tunnel reopens on the same address instead of printing a refusal.
233
+ if (code === 'lease_closed' && e.requestId) {
234
+ const { rejectAssignment } = await import('../../state/assignment.js');
235
+ const err = new RefusedError('lease_closed', 'the lease was closed', { details: d });
236
+ /** @type {any} */ (err).code = 'LEASE_CLOSED';
237
+ if (rejectAssignment(e.requestId, err))
238
+ return;
239
+ }
231
240
  const report = { code, reason: d.reason, fatal: FATAL_REJECT_CODES.has(code), data: d, instanceId };
232
241
  if (openRejectReporter) {
233
242
  await openRejectReporter(report);
@@ -1,6 +1,6 @@
1
1
  export const LOCAL_UNAVAILABLE_PAGE: "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Service not reachable</title></head><body style=\"font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#334155\"><h1 style=\"font-size:1.4rem;color:#0f172a\">This service is not reachable right now</h1><p>The tunnel is up, but the app behind it is not answering. It may be restarting; try again in a moment.</p></body></html>";
2
2
  export class HttpTunnel {
3
- constructor({ relayUrl, jwt, deviceId, requestId, localPort, log, coordinatorCore, coordinatorIngress, isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs, secGroupSlug, instanceId, onFatal, onNotice, requestSink, }: {
3
+ constructor({ relayUrl, jwt, deviceId, requestId, localPort, log, coordinatorCore, coordinatorIngress, isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs, secGroupSlug, instanceId, onFatal, onNotice, onLeaseClosed, requestSink, }: {
4
4
  relayUrl: any;
5
5
  jwt: any;
6
6
  deviceId: any;
@@ -18,10 +18,12 @@ export class HttpTunnel {
18
18
  instanceId?: any;
19
19
  onFatal?: any;
20
20
  onNotice?: any;
21
+ onLeaseClosed?: any;
21
22
  requestSink?: any;
22
23
  });
23
24
  requestSink: any;
24
25
  onFatal: any;
26
+ onLeaseClosed: any;
25
27
  onNotice: any;
26
28
  relayUrl: any;
27
29
  jwt: any;
@@ -80,11 +80,12 @@ export class HttpTunnel {
80
80
  instanceId = null,
81
81
  // Story 12.1 (c2): the core never exits or prints. onFatal(code) is called where the CLI used to
82
82
  // exit(1); onNotice(code, details) where it used to print. Without onFatal, a fatal condition throws.
83
- onFatal = null, onNotice = null,
83
+ onFatal = null, onNotice = null, onLeaseClosed = null, // Story 3.13: reopen after the relay closed this lease (4000 lease_closed)
84
84
  // Story 12.1 c3: where received requests go; defaults to the local service on localPort
85
85
  requestSink = null, }) {
86
86
  this.requestSink = requestSink || new LocalPortSink(localPort);
87
87
  this.onFatal = onFatal;
88
+ this.onLeaseClosed = onLeaseClosed;
88
89
  this.onNotice = onNotice;
89
90
  this.relayUrl = relayUrl;
90
91
  this.jwt = jwt; // Accept JWT as-is (no validation)
@@ -631,6 +632,13 @@ export class HttpTunnel {
631
632
  clearAllWaiters();
632
633
  // Clear single-flight guard
633
634
  this.reauthInFlight = null;
635
+ // Story 3.13: the relay closed this lease (the cloud closed it): reconnecting with the same token
636
+ // would be refused every time; reopen on the same address instead, or end saying why.
637
+ if (code === 4000 && reasonStr === 'lease_closed' && this.onLeaseClosed && this.shouldReconnect) {
638
+ this.onLeaseClosed().then((ok) => { if (!ok)
639
+ this._fatal('lease_closed_reopen_refused'); }).catch(() => this._fatal('lease_closed_reopen_refused'));
640
+ return;
641
+ }
634
642
  // CLI-IMG-WSReconnect: Schedule reconnect instead of exiting
635
643
  this.scheduleReconnect(code, reason);
636
644
  });
@@ -856,12 +864,14 @@ export class HttpTunnel {
856
864
  const ackPromise = this.coordinatorIngress.registerAwaiter((message) => {
857
865
  try {
858
866
  const parsed = message.payload;
859
- return parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
867
+ // Story 3.13: an open_reject for this renewal (lease_closed) is an answer too, not a timeout
868
+ return parsed && (parsed.type === 'open_ack' || parsed.type === 'open_reject') && parsed.requestId === refreshRequestId;
860
869
  }
861
870
  catch (e) {
862
871
  return false;
863
872
  }
864
873
  }, 10000);
874
+ let ackMsg = null; // Story 3.13: the renewal's answer (open_ack, or open_reject such as lease_closed)
865
875
  // CLI-IMG-MQTT-Resilience: Publish with retry logic and fallback
866
876
  try {
867
877
  // Publish the refresh request
@@ -874,9 +884,17 @@ export class HttpTunnel {
874
884
  this.log.info('jwt.refresh.request.sent', { refreshRequestId, retryCount: this.refreshAttempts });
875
885
  // Wait for new assignment with timeout handling
876
886
  try {
877
- await ackPromise;
887
+ ackMsg = await ackPromise;
878
888
  }
879
889
  catch (timeoutError) {
890
+ // Story 3.13: the coordinator says this lease is closed: reopen on the same address, or end saying why
891
+ if ((timeoutError?.code === 'LEASE_CLOSED' || timeoutError?.reason === 'lease_closed') && this.onLeaseClosed) {
892
+ this.log.warn('jwt.refresh.lease_closed', { retryCount: this.refreshAttempts });
893
+ const ok = await this.onLeaseClosed().catch(() => false);
894
+ if (!ok)
895
+ return this._fatal('lease_closed_reopen_refused');
896
+ return;
897
+ }
880
898
  this.log.warn('jwt.refresh.timeout', { retryCount: this.refreshAttempts, error: timeoutError.message });
881
899
  // CLI-IMG-MQTT-Resilience: Fallback to fresh tunnel when awaiter times out
882
900
  await this._fallbackToFreshTunnel();
@@ -890,6 +908,20 @@ export class HttpTunnel {
890
908
  await this._fallbackToFreshTunnel();
891
909
  return;
892
910
  }
911
+ // Story 3.13: the coordinator refused the renewal: a closed lease reopens on the same address
912
+ const rejected = ackMsg?.payload?.type === 'open_reject' ? ackMsg.payload : null;
913
+ if (rejected) {
914
+ const why = String(rejected.data?.reason || rejected.reason || '').toLowerCase();
915
+ if (why === 'lease_closed' && this.onLeaseClosed) {
916
+ this.log.warn('jwt.refresh.lease_closed', { retryCount: this.refreshAttempts });
917
+ const ok = await this.onLeaseClosed().catch(() => false);
918
+ if (!ok)
919
+ return this._fatal('lease_closed_reopen_refused');
920
+ return;
921
+ }
922
+ this.log.error('jwt.refresh.refused', { reason: why });
923
+ return this._fatal('refresh_refused', { reason: why });
924
+ }
893
925
  // TPB-12: Get the new assignment for this specific instance
894
926
  const newAssignment = getAssignment(this.instanceId);
895
927
  if (!newAssignment) {
@@ -84,6 +84,9 @@ export class TcpTunnel {
84
84
  startHeartbeat(): void;
85
85
  sendHeartbeat(): void;
86
86
  stopHeartbeat(): void;
87
+ /** Story 3.13: the coordinator said this lease is closed (at renewal): reopen exactly as on a relay
88
+ * close 4000 lease_closed (same port, new lease, then reconnect); resolves false when refused. */
89
+ reopenAfterLeaseClosed(): Promise<boolean>;
87
90
  }
88
91
  import WebSocket from 'ws';
89
92
  import { Reconnector } from './reconnect.js';
@@ -835,4 +835,22 @@ export class TcpTunnel {
835
835
  this.heartbeatTimer = null;
836
836
  }
837
837
  }
838
+ /** Story 3.13: the coordinator said this lease is closed (at renewal): reopen exactly as on a relay
839
+ * close 4000 lease_closed (same port, new lease, then reconnect); resolves false when refused. */
840
+ async reopenAfterLeaseClosed() {
841
+ if (this.closing || !this.reassign)
842
+ return false;
843
+ let got = false;
844
+ try {
845
+ got = await this.reconnector.onAuthFailure();
846
+ }
847
+ catch {
848
+ got = false;
849
+ }
850
+ if (got && !this.closing) {
851
+ this.reconnector.run('lease_closed_reassigned');
852
+ return true;
853
+ }
854
+ return false;
855
+ }
838
856
  }
@@ -85,6 +85,9 @@ export class UdpTunnel {
85
85
  stopFlowCleanup(): void;
86
86
  closeAllFlowSockets(): void;
87
87
  close(): void;
88
+ /** Story 3.13: the coordinator said this lease is closed (at renewal): reopen exactly as on a relay
89
+ * close 4000 lease_closed (same port, new lease, then reconnect); resolves false when refused. */
90
+ reopenAfterLeaseClosed(): Promise<boolean>;
88
91
  }
89
92
  import WebSocket from 'ws';
90
93
  import { Reconnector } from './reconnect.js';
@@ -734,4 +734,22 @@ export class UdpTunnel {
734
734
  this.ws.close();
735
735
  }
736
736
  }
737
+ /** Story 3.13: the coordinator said this lease is closed (at renewal): reopen exactly as on a relay
738
+ * close 4000 lease_closed (same port, new lease, then reconnect); resolves false when refused. */
739
+ async reopenAfterLeaseClosed() {
740
+ if (this.closing || !this.reassign)
741
+ return false;
742
+ let got = false;
743
+ try {
744
+ got = await this.reconnector.onAuthFailure();
745
+ }
746
+ catch {
747
+ got = false;
748
+ }
749
+ if (got && !this.closing) {
750
+ this.reconnector.run('lease_closed_reassigned');
751
+ return true;
752
+ }
753
+ return false;
754
+ }
737
755
  }