asyx 0.7.0 → 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.
- package/README.md +17 -9
- package/package.json +1 -1
- package/src/commands/reject-messages.js +43 -0
- package/src/commands/tunnel.js +11 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +13 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +21 -0
- package/vendor/tunnel-core/dist/control-plane/session.d.ts +5 -0
- package/vendor/tunnel-core/dist/control-plane/session.js +2 -1
- package/vendor/tunnel-core/dist/flows/goodbye.d.ts +10 -0
- package/vendor/tunnel-core/dist/flows/goodbye.js +27 -0
- package/vendor/tunnel-core/dist/flows/http.d.ts +5 -0
- package/vendor/tunnel-core/dist/flows/http.js +60 -0
- package/vendor/tunnel-core/dist/flows/reopen.d.ts +9 -0
- package/vendor/tunnel-core/dist/flows/reopen.js +27 -0
- package/vendor/tunnel-core/dist/flows/tcp.d.ts +5 -0
- package/vendor/tunnel-core/dist/flows/tcp.js +44 -2
- package/vendor/tunnel-core/dist/flows/udp.d.ts +5 -0
- package/vendor/tunnel-core/dist/flows/udp.js +44 -2
- package/vendor/tunnel-core/dist/mqtt/events/handlers.js +9 -0
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +3 -1
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +35 -3
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +3 -0
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +18 -0
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +3 -0
- 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 (
|
|
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
|
|
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.
|
|
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
|
| --- | --- |
|
|
@@ -202,12 +202,12 @@ If the connection of a TCP or UDP tunnel drops (network loss, Asyx server mainte
|
|
|
202
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
203
|
|
|
204
204
|
```text
|
|
205
|
-
❌
|
|
205
|
+
❌ orders-api.tunnel.asyx.ai already has an HTTP tunnel from this computer since 2:02 PM (serving localhost:3000).
|
|
206
206
|
One address runs one HTTP tunnel at a time.
|
|
207
207
|
Stop that tunnel first, or add --replace to take over.
|
|
208
208
|
```
|
|
209
209
|
|
|
210
|
-
- **Restarting is fine.** When a tunnel stops or crashes, the address is free again within a second. If you restart faster than that on the same computer, the CLI waits up to 15 seconds for the old tunnel to close.
|
|
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
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
212
|
- **`--wait`** keeps trying every 30 seconds instead of exiting, for scripts that should start as soon as the address is free.
|
|
213
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).
|
|
@@ -217,7 +217,7 @@ A refused tunnel and a replaced tunnel exit with code **75** ("try again later")
|
|
|
217
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
218
|
|
|
219
219
|
```bash
|
|
220
|
-
asyx tunnel --http --port
|
|
220
|
+
asyx tunnel --http --port 3000 --to orders-api.tunnel.asyx.ai --wait
|
|
221
221
|
```
|
|
222
222
|
|
|
223
223
|
With systemd you can also skip the restart entirely with `RestartPreventExitStatus=75`.
|
|
@@ -242,6 +242,14 @@ asyx tunnel --minecraft [--port <n>] [--name <alias>]
|
|
|
242
242
|
|
|
243
243
|
---
|
|
244
244
|
|
|
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
|
+
|
|
245
253
|
## What's new in 0.7.0
|
|
246
254
|
|
|
247
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.
|
|
@@ -314,7 +322,7 @@ Changes since 0.6.1, in short: `--to`, one tunnel of each kind per address (`--r
|
|
|
314
322
|
| Cursor + Asyx | https://www.asyx.ai/docs/cursor-asyx |
|
|
315
323
|
| Agent checklist | https://www.asyx.ai/docs/ai-agent-checklist |
|
|
316
324
|
| Expose localhost | https://www.asyx.ai/docs/expose-localhost |
|
|
317
|
-
|
|
|
325
|
+
| QuickPass (guest access) | https://www.asyx.ai/docs/quickpass |
|
|
318
326
|
| vs ngrok & Cloudflare | https://www.asyx.ai/docs/vs-ngrok-cloudflare |
|
|
319
327
|
|
|
320
328
|
---
|
|
@@ -325,7 +333,7 @@ Changes since 0.6.1, in short: `--to`, one tunnel of each kind per address (`--r
|
|
|
325
333
|
- **Do not** tunnel database admin ports without authentication.
|
|
326
334
|
- **Stop** the tunnel when the demo ends (`Ctrl+C`).
|
|
327
335
|
- Treat the public URL as a temporary preview—not a production deploy.
|
|
328
|
-
- Agents **cannot**
|
|
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.
|
|
329
337
|
|
|
330
338
|
---
|
|
331
339
|
|
|
@@ -350,7 +358,7 @@ Levels: `error` | `warn` | `info` | `debug` (default `info`).
|
|
|
350
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` |
|
|
351
359
|
| Tunnel stops right after starting with `jwt_expired_before_refresh` | Your computer's clock is wrong; turn on automatic time and try again |
|
|
352
360
|
| Tunnel URL 502 / unreachable | Dev server not running on the same port |
|
|
353
|
-
| Link
|
|
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 |
|
|
354
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) |
|
|
355
363
|
| External port rejected | `--external-port` must be inside your assigned 10-port block |
|
|
356
364
|
| Windows: secure connection fails at startup | Re-run `asyx setup` to regenerate the device key |
|
package/package.json
CHANGED
|
@@ -58,6 +58,49 @@ 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
|
+
}
|
|
61
104
|
default:
|
|
62
105
|
// Not fatal: print and keep running (e.g. a refused renewal).
|
|
63
106
|
process.stdout.write(`❌ Connection rejected${reason ? ` (${reason})` : ''}\n`);
|
package/src/commands/tunnel.js
CHANGED
|
@@ -565,6 +565,9 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
565
565
|
onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
|
|
566
566
|
});
|
|
567
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`));
|
|
568
571
|
// QPA-CLI-11: Vault UX messaging - Control-plane sealed
|
|
569
572
|
handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
|
|
570
573
|
handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
|
|
@@ -632,6 +635,8 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
632
635
|
process.stderr.write("tunnel.close() timed out; forcing exit\n");
|
|
633
636
|
process.exit(0);
|
|
634
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 }); }
|
|
635
640
|
try {
|
|
636
641
|
handle.tunnel.close();
|
|
637
642
|
} catch (e) {
|
|
@@ -739,6 +744,9 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
739
744
|
onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
|
|
740
745
|
});
|
|
741
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`));
|
|
742
750
|
// QPA-CLI-11: Vault UX messaging - Control-plane sealed
|
|
743
751
|
handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
|
|
744
752
|
handle.on('control-fatal', ({ reason }) => {
|
|
@@ -882,6 +890,9 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
|
|
|
882
890
|
onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
|
|
883
891
|
});
|
|
884
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`));
|
|
885
896
|
// QPA-CLI-11: Vault UX messaging - Control-plane sealed
|
|
886
897
|
handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
|
|
887
898
|
handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|