asyx 0.5.8 → 0.5.9
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 +33 -9
- package/package.json +4 -1
- package/src/commands/tunnel.js +153 -19
- package/src/main.js +16 -6
- package/src/mqtt/events/handlers.js +1 -1
- package/src/tunnel/http-tunnel.js +48 -4
- package/src/tunnel/reconnect.js +182 -0
- package/src/tunnel/tcp-tunnel.js +133 -51
- package/src/tunnel/udp-tunnel.js +138 -33
package/README.md
CHANGED
|
@@ -114,7 +114,8 @@ asyx tunnel --http --port 3000
|
|
|
114
114
|
|
|
115
115
|
- Forwards to `127.0.0.1:3000` (loopback only).
|
|
116
116
|
- Prints your stable `https://<subdomain>.tunnel.asyx.ai` URL.
|
|
117
|
-
- TLS and
|
|
117
|
+
- TLS and token refresh handled automatically; your app keeps its port.
|
|
118
|
+
- If the connection drops (network loss, laptop wake, Asyx server maintenance), the CLI reconnects on its own and the same URL comes back.
|
|
118
119
|
|
|
119
120
|
### Private demos (Quickpass)
|
|
120
121
|
|
|
@@ -152,11 +153,21 @@ asyx tunnel --minecraft [--port 25565] [--name <alias>]
|
|
|
152
153
|
|
|
153
154
|
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>`).
|
|
154
155
|
|
|
156
|
+
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.
|
|
157
|
+
|
|
158
|
+
| Variable | Effect |
|
|
159
|
+
| --- | --- |
|
|
160
|
+
| `ASYX_TUNNEL_RECONNECT=0` | Turn reconnecting off (the tunnel ends on a drop) |
|
|
161
|
+
| `ASYX_TUNNEL_RECONNECT_MAX_MS` | Give up after this long without a connection (default 15 minutes) |
|
|
162
|
+
| `ASYX_TUNNEL_RECONNECT_MAX_DELAY_MS` | Longest wait between attempts (default 5 seconds) |
|
|
163
|
+
|
|
155
164
|
---
|
|
156
165
|
|
|
157
166
|
## Command quick reference
|
|
158
167
|
|
|
159
168
|
```bash
|
|
169
|
+
asyx help # commands; asyx tunnel --help for tunnel options
|
|
170
|
+
asyx --version
|
|
160
171
|
asyx setup
|
|
161
172
|
asyx tunnel --http --port <n> [--secgroup <slug>]
|
|
162
173
|
asyx tunnel --tcp --port <n> [--name <alias>] [--external-port <p>]
|
|
@@ -166,15 +177,27 @@ asyx tunnel --minecraft [--port <n>] [--name <alias>]
|
|
|
166
177
|
|
|
167
178
|
---
|
|
168
179
|
|
|
169
|
-
## What's new in 0.5.
|
|
180
|
+
## What's new in 0.5.9
|
|
181
|
+
|
|
182
|
+
**TCP and UDP tunnels reconnect on their own** — after a network drop or Asyx server maintenance, TCP and UDP tunnels come back with the same hostname and public port, without rerunning the CLI. Previously they ended and had to be started again. See [Other tunnel types](#other-tunnel-types) for the settings.
|
|
183
|
+
|
|
184
|
+
**Tunnels follow when Asyx moves them** — Asyx can move your tunnel to another server (to balance load or during maintenance). HTTP, TCP and UDP tunnels reconnect to the new server by themselves; your URL, hostname and ports stay the same.
|
|
185
|
+
|
|
186
|
+
**HTTP tunnels ride out server restarts** — an HTTP tunnel no longer crashes or waits 30 seconds when its server restarts; it reconnects within seconds. Very large responses that cannot be relayed now fail only that request (502) instead of closing the whole tunnel.
|
|
187
|
+
|
|
188
|
+
**Clean installs** — every package the CLI loads is now declared, so installs with strict package managers (and nested npm installs) work.
|
|
189
|
+
|
|
190
|
+
**Clearer help** — `asyx help` / `asyx --help` and `asyx tunnel --help` list the commands and options with examples.
|
|
191
|
+
|
|
192
|
+
## Earlier in 0.5.x
|
|
170
193
|
|
|
171
|
-
**DNS outage keeps the tunnel up (0.5.7)** — if the
|
|
194
|
+
**DNS outage keeps the tunnel up (0.5.7)** — if the service hostname fails to resolve, the CLI waits and retries instead of exiting.
|
|
172
195
|
|
|
173
|
-
**Refresh after a control
|
|
196
|
+
**Refresh after a control reconnect (0.5.6)** — if the control connection drops and reconnects, the next token refresh keeps the tunnel up instead of exiting.
|
|
174
197
|
|
|
175
|
-
**Reconnect after a DNS blip (0.5.5)** — if the network drops before the
|
|
198
|
+
**Reconnect after a DNS blip (0.5.5)** — if the network drops before the secure control connection is established, the CLI stays up and retries.
|
|
176
199
|
|
|
177
|
-
**Tunnel-only CLI (0.5.0)** — npm ships tunnel commands only: `setup
|
|
200
|
+
**Tunnel-only CLI (0.5.0)** — npm ships the tunnel commands only: `setup` and `tunnel`. Focused on secure localhost exposure (HTTP, TCP, UDP). Docs at https://www.asyx.ai/docs
|
|
178
201
|
|
|
179
202
|
**Reliable global install (0.5.2)** — `asyx setup` uses Node's built-in Web Crypto. `npm install -g asyx` works on Node 18+ without module-resolution errors.
|
|
180
203
|
|
|
@@ -224,16 +247,17 @@ Levels: `error` | `warn` | `info` | `debug` (default `info`).
|
|
|
224
247
|
| `asyx: command not found` | `npm install -g asyx` or `npx asyx@latest` |
|
|
225
248
|
| Setup browser did not open | Run `asyx setup` again; open the printed URL manually |
|
|
226
249
|
| Tunnel URL 502 / unreachable | Dev server not running on the same port |
|
|
227
|
-
| Link dies overnight | Expected—tunnel
|
|
250
|
+
| Link dies overnight | Expected—the tunnel lives only while the CLI runs and the machine is awake |
|
|
251
|
+
| 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) |
|
|
228
252
|
| External port rejected | `--external-port` must be inside your assigned 10-port block |
|
|
229
|
-
| Windows
|
|
253
|
+
| Windows: secure connection fails at startup | Re-run `asyx setup` to regenerate the device key |
|
|
230
254
|
|
|
231
255
|
---
|
|
232
256
|
|
|
233
257
|
## Security
|
|
234
258
|
|
|
235
259
|
- Device-bound identity per host; hardware fingerprint hashed locally.
|
|
236
|
-
- Mutual TLS
|
|
260
|
+
- Mutual TLS with a per-device certificate; short-lived signed tunnel tokens.
|
|
237
261
|
- Forward-only proxy—your app stays isolated; no direct inbound to your host.
|
|
238
262
|
- Report issues: [security@asyx.ai](mailto:security@asyx.ai)
|
|
239
263
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "asyx",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.9",
|
|
4
4
|
"description": "Asyx tunnel CLI — secure localhost exposure (HTTP, TCP, UDP)",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -58,6 +58,7 @@
|
|
|
58
58
|
"src/tcp-v1/framing.js",
|
|
59
59
|
"src/tunnel/http-tunnel.js",
|
|
60
60
|
"src/tunnel/httpws-constants.js",
|
|
61
|
+
"src/tunnel/reconnect.js",
|
|
61
62
|
"src/tunnel/tcp-tunnel.js",
|
|
62
63
|
"src/tunnel/udp-tunnel.js",
|
|
63
64
|
"src/tunnel/ws-control.js",
|
|
@@ -69,10 +70,12 @@
|
|
|
69
70
|
"dependencies": {
|
|
70
71
|
"@asyx/mqtt-broker-aws": "^0.1.0",
|
|
71
72
|
"@asyx/mqtt-client": "^0.1.0",
|
|
73
|
+
"@asyx/mqtt-core": "^0.1.0",
|
|
72
74
|
"@peculiar/x509": "^1.14.0",
|
|
73
75
|
"chalk": "^5.3.0",
|
|
74
76
|
"hw-fingerprint": "^3.2.0",
|
|
75
77
|
"jose": "^5.10.0",
|
|
78
|
+
"mqtt": "^5.3.4",
|
|
76
79
|
"open": "^9.1.0",
|
|
77
80
|
"ulid": "^2.4.0",
|
|
78
81
|
"ws": "^8.14.2",
|
package/src/commands/tunnel.js
CHANGED
|
@@ -78,9 +78,11 @@ export async function publishRefreshRequestWithErrorHandling(
|
|
|
78
78
|
|
|
79
79
|
export default async function tunnel(args = []) {
|
|
80
80
|
// Device credential guard - use same path resolution as device.js
|
|
81
|
+
// (help works before enrollment)
|
|
81
82
|
const deviceJsonPath = getDeviceJsonPath();
|
|
82
|
-
|
|
83
|
-
|
|
83
|
+
const wantsHelp = args.includes('--help') || args.includes('-h');
|
|
84
|
+
if (!wantsHelp) await access(deviceJsonPath, fsConstants.F_OK).catch(() => {
|
|
85
|
+
console.error('This machine is not set up yet. Run "asyx setup" first (it opens your browser once), then run this command again.');
|
|
84
86
|
process.exit(2);
|
|
85
87
|
});
|
|
86
88
|
|
|
@@ -89,15 +91,25 @@ export default async function tunnel(args = []) {
|
|
|
89
91
|
|
|
90
92
|
if (parsed.help || args.length === 0) {
|
|
91
93
|
logger.info("cli.help", {});
|
|
92
|
-
process.stdout.write(`
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
94
|
+
process.stdout.write(`Usage:
|
|
95
|
+
asyx tunnel --http --port <n> [--secgroup <slug>]
|
|
96
|
+
HTTP tunnel: a public HTTPS URL for a web app on localhost:<n>.
|
|
97
|
+
--secgroup <slug> QuickPass security group; only its members can open the URL
|
|
98
|
+
|
|
99
|
+
asyx tunnel --tcp --port <n> [--name <alias>] [--external-port <p>]
|
|
100
|
+
TCP tunnel: a public TCP port for a service on localhost:<n> (databases, SSH, games).
|
|
101
|
+
|
|
102
|
+
asyx tunnel --udp --port <n> [--external-port <p>]
|
|
103
|
+
UDP tunnel: a public UDP port for a service on localhost:<n> (games, realtime apps).
|
|
104
|
+
|
|
105
|
+
asyx tunnel --minecraft [--port <n>] [--name <alias>]
|
|
106
|
+
Minecraft server (default port 25565); players connect with the hostname only.
|
|
107
|
+
|
|
108
|
+
--external-port <p> choose the public port inside your assigned 10-port block
|
|
109
|
+
|
|
110
|
+
Tunnels forward to 127.0.0.1 only and reconnect on their own after a network or
|
|
111
|
+
server interruption. Press Ctrl+C to stop. Docs: https://www.asyx.ai/docs
|
|
112
|
+
`);
|
|
101
113
|
return;
|
|
102
114
|
}
|
|
103
115
|
|
|
@@ -2100,6 +2112,23 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
2100
2112
|
});
|
|
2101
2113
|
}
|
|
2102
2114
|
|
|
2115
|
+
|
|
2116
|
+
// Story 10.9: if the relay refuses this assignment on a reconnect (the tenant was moved to
|
|
2117
|
+
// another relay, so the token's relay no longer matches), open again for the same public
|
|
2118
|
+
// port; the control plane places the new lease on the tenant's current relay.
|
|
2119
|
+
const reassignSamePort = async () => {
|
|
2120
|
+
const { setAssignment: setA, getAssignment: getA } = await import("../state/assignment.js");
|
|
2121
|
+
const cur = getA(instanceIdRef.instanceId) || assignment;
|
|
2122
|
+
const rid = crypto.randomUUID();
|
|
2123
|
+
const again = { ...openPayload, requestId: rid, opts: { ...(openPayload.opts || {}), requestedExternalPort: cur.publicPort ?? assignment.publicPort } };
|
|
2124
|
+
setExpectedRequestId(instanceIdRef.instanceId, rid);
|
|
2125
|
+
await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
|
|
2126
|
+
const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
|
|
2127
|
+
setA(instanceIdRef.instanceId, next);
|
|
2128
|
+
logger.info("tcp.reassign.ok", { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
|
|
2129
|
+
return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
|
|
2130
|
+
};
|
|
2131
|
+
|
|
2103
2132
|
// TCP-S4: Connect to relay using TcpTunnel for data-plane readiness
|
|
2104
2133
|
await connectToRelayTcp(
|
|
2105
2134
|
assignment,
|
|
@@ -2109,7 +2138,8 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
2109
2138
|
ingress,
|
|
2110
2139
|
{ isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
|
|
2111
2140
|
tunnelInstanceRef, // QPA-CLI-01: Shared reference - tunnel will be stored here
|
|
2112
|
-
mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
|
|
2141
|
+
mqttClient, // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
|
|
2142
|
+
reassignSamePort
|
|
2113
2143
|
);
|
|
2114
2144
|
|
|
2115
2145
|
} catch (error) {
|
|
@@ -2193,14 +2223,19 @@ export async function connectToRelayTcp(
|
|
|
2193
2223
|
coordinatorIngress,
|
|
2194
2224
|
controlPlaneHelpers,
|
|
2195
2225
|
tunnelInstanceRef, // QPA-CLI-01: Pass reference to store tunnel instance
|
|
2196
|
-
mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
|
|
2226
|
+
mqttClient, // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
|
|
2227
|
+
reassign = null // Story 10.9: new assignment after a relay refuses the old one
|
|
2197
2228
|
) {
|
|
2198
2229
|
// Import TCP tunnel logic
|
|
2199
2230
|
const { TcpTunnel } = await import("../tunnel/tcp-tunnel.js");
|
|
2231
|
+
const { getAssignment: getStoredAssignment } = await import("../state/assignment.js");
|
|
2200
2232
|
|
|
2201
2233
|
const tunnel = new TcpTunnel({
|
|
2202
2234
|
relayUrl: assignment.relayUrl,
|
|
2203
2235
|
jwt: assignment.jwt, // Use JWT as-is (no validation)
|
|
2236
|
+
// Story 11.2: reconnects use the newest token (kept fresh by the TPB-17 refresh)
|
|
2237
|
+
getJwt: () => (mqttClient ? getStoredAssignment(mqttClient.getClientId())?.jwt : null) || null,
|
|
2238
|
+
reassign,
|
|
2204
2239
|
deviceId,
|
|
2205
2240
|
requestId: assignment.requestId,
|
|
2206
2241
|
localPort,
|
|
@@ -2494,11 +2529,66 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
|
|
|
2494
2529
|
process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
|
|
2495
2530
|
process.exit(1);
|
|
2496
2531
|
},
|
|
2497
|
-
//
|
|
2532
|
+
// Story 11.2: UDP refresh (control plane UDP-S3), so a reconnect after the first
|
|
2533
|
+
// token expires still has a valid token. Same flow as TCP (TPB-17); failures are
|
|
2534
|
+
// non-fatal: the open tunnel keeps running.
|
|
2498
2535
|
onRefreshLease: async () => {
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2536
|
+
if (!coordinatorCoreRef || !coordinatorIngressRef) {
|
|
2537
|
+
throw new Error("Coordinator not available for refresh");
|
|
2538
|
+
}
|
|
2539
|
+
const refreshInstanceId = mqttClient.getClientId();
|
|
2540
|
+
const { getAssignment } = await import('../state/assignment.js');
|
|
2541
|
+
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
2542
|
+
const currentAssignment = getAssignment(refreshInstanceId);
|
|
2543
|
+
if (!currentAssignment?.leaseId) {
|
|
2544
|
+
throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
|
|
2545
|
+
}
|
|
2546
|
+
const refreshRequestId = `refresh-${Date.now()}`;
|
|
2547
|
+
const fingerprint = await getFpHash(deviceIdRef);
|
|
2548
|
+
const refreshPayload = {
|
|
2549
|
+
requestId: refreshRequestId,
|
|
2550
|
+
instanceId: refreshInstanceId,
|
|
2551
|
+
refreshOf: currentAssignment.leaseId,
|
|
2552
|
+
proto: 'udp',
|
|
2553
|
+
protocol: 'udp',
|
|
2554
|
+
tunnelMode: 'udpWs-v1',
|
|
2555
|
+
targetHost: targetHostRef,
|
|
2556
|
+
targetPort: targetPortRef,
|
|
2557
|
+
clientId: deviceIdRef,
|
|
2558
|
+
...fingerprint
|
|
2559
|
+
};
|
|
2560
|
+
const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
|
|
2561
|
+
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
|
|
2562
|
+
const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
|
|
2563
|
+
const parsed = message.payload;
|
|
2564
|
+
if (parsed && parsed.requestId === refreshRequestId && parsed.type === 'open_reject') {
|
|
2565
|
+
const rejectError = new Error(`Refresh rejected: ${parsed.data?.reason || 'unknown'}`);
|
|
2566
|
+
rejectError.code = 'REFRESH_REJECTED';
|
|
2567
|
+
throw rejectError;
|
|
2568
|
+
}
|
|
2569
|
+
return !!parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
2570
|
+
}, ACK_TIMEOUT_MS);
|
|
2571
|
+
const publishSuccess = await publishRefreshRequestWithErrorHandling(
|
|
2572
|
+
coordinatorCoreRef, cmdOpenTopic, refreshPayload, refreshRequestId, logger);
|
|
2573
|
+
if (publishSuccess === false) {
|
|
2574
|
+
const bufferedError = new Error('Connection closed during refresh publish');
|
|
2575
|
+
bufferedError.code = 'ECONNRESET';
|
|
2576
|
+
throw bufferedError;
|
|
2577
|
+
}
|
|
2578
|
+
try {
|
|
2579
|
+
await ackPromise;
|
|
2580
|
+
} catch (error) {
|
|
2581
|
+
logger.warn('udp.refresh.failed', { error: error.message, requestId: refreshRequestId, action: 'non_fatal_continue' });
|
|
2582
|
+
return null;
|
|
2583
|
+
}
|
|
2584
|
+
// The open_ack handler stored the new assignment for this instance
|
|
2585
|
+
const exp = jwtExpOf(getAssignment(refreshInstanceId)?.jwt);
|
|
2586
|
+
if (!exp) {
|
|
2587
|
+
logger.warn('udp.refresh.no_exp', { requestId: refreshRequestId });
|
|
2588
|
+
return null;
|
|
2589
|
+
}
|
|
2590
|
+
logger.debug('udp.refresh.success', { leaseId: currentAssignment.leaseId, expMs: exp * 1000, requestId: refreshRequestId });
|
|
2591
|
+
return exp * 1000;
|
|
2502
2592
|
},
|
|
2503
2593
|
});
|
|
2504
2594
|
|
|
@@ -2740,6 +2830,23 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
|
|
|
2740
2830
|
clearExpectedRequestId(instanceId);
|
|
2741
2831
|
} catch {}
|
|
2742
2832
|
|
|
2833
|
+
|
|
2834
|
+
// Story 10.9: if the relay refuses this assignment on a reconnect (the tenant was moved to
|
|
2835
|
+
// another relay, so the token's relay no longer matches), open again for the same public
|
|
2836
|
+
// port; the control plane places the new lease on the tenant's current relay.
|
|
2837
|
+
const reassignSamePort = async () => {
|
|
2838
|
+
const { setAssignment: setA, getAssignment: getA } = await import("../state/assignment.js");
|
|
2839
|
+
const cur = getA(instanceIdRef.instanceId) || assignment;
|
|
2840
|
+
const rid = crypto.randomUUID();
|
|
2841
|
+
const again = { ...openPayload, requestId: rid, externalPort: cur.publicPort ?? assignment.publicPort };
|
|
2842
|
+
setExpectedRequestId(instanceIdRef.instanceId, rid);
|
|
2843
|
+
await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
|
|
2844
|
+
const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
|
|
2845
|
+
setA(instanceIdRef.instanceId, next);
|
|
2846
|
+
logger.info("udp.reassign.ok", { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
|
|
2847
|
+
return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
|
|
2848
|
+
};
|
|
2849
|
+
|
|
2743
2850
|
// UDP-S1: Connect to relay using UdpTunnel
|
|
2744
2851
|
// UDP-S13: Pass targetHost and targetPort (not localPort that we bind to)
|
|
2745
2852
|
await connectToRelayUdp(
|
|
@@ -2752,7 +2859,8 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
|
|
|
2752
2859
|
{ isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
|
|
2753
2860
|
tunnelInstanceRef,
|
|
2754
2861
|
mqttClient,
|
|
2755
|
-
instanceId
|
|
2862
|
+
instanceId,
|
|
2863
|
+
reassignSamePort
|
|
2756
2864
|
);
|
|
2757
2865
|
|
|
2758
2866
|
} catch (error) {
|
|
@@ -2788,14 +2896,22 @@ export async function connectToRelayUdp(
|
|
|
2788
2896
|
controlPlaneHelpers,
|
|
2789
2897
|
tunnelInstanceRef,
|
|
2790
2898
|
mqttClient,
|
|
2791
|
-
instanceId = null
|
|
2899
|
+
instanceId = null,
|
|
2900
|
+
reassign = null // Story 10.9: new assignment after a relay refuses the old one
|
|
2792
2901
|
) {
|
|
2793
2902
|
// Import UDP tunnel logic
|
|
2794
2903
|
const { UdpTunnel } = await import("../tunnel/udp-tunnel.js");
|
|
2904
|
+
const { getAssignment: getStoredAssignment } = await import("../state/assignment.js");
|
|
2795
2905
|
|
|
2796
2906
|
const tunnel = new UdpTunnel({
|
|
2907
|
+
reassign,
|
|
2797
2908
|
relayUrl: assignment.relayUrl,
|
|
2798
2909
|
jwt: assignment.assignmentJwt || assignment.jwt, // UDP-S1: Use assignmentJwt if available
|
|
2910
|
+
// Story 11.2: reconnects use the newest token (kept fresh by the UDP refresh)
|
|
2911
|
+
getJwt: () => {
|
|
2912
|
+
const stored = instanceId ? getStoredAssignment(instanceId) : null;
|
|
2913
|
+
return stored?.assignmentJwt || stored?.jwt || null;
|
|
2914
|
+
},
|
|
2799
2915
|
deviceId,
|
|
2800
2916
|
requestId: assignment.requestId,
|
|
2801
2917
|
targetHost, // UDP-S13: Target host (must be loopback)
|
|
@@ -2836,6 +2952,13 @@ export async function connectToRelayUdp(
|
|
|
2836
2952
|
|
|
2837
2953
|
try {
|
|
2838
2954
|
await tunnel.open();
|
|
2955
|
+
|
|
2956
|
+
// Story 11.2: schedule the first proactive token refresh (as TCP, TPB-17)
|
|
2957
|
+
const firstExp = jwtExpOf(assignment.assignmentJwt || assignment.jwt);
|
|
2958
|
+
if (mqttClient && firstExp && assignment.leaseId) {
|
|
2959
|
+
mqttClient.scheduleRefresh(firstExp * 1000, assignment.leaseId);
|
|
2960
|
+
logger.debug('udp.refresh.initial_scheduled', { expMs: firstExp * 1000, leaseId: assignment.leaseId });
|
|
2961
|
+
}
|
|
2839
2962
|
|
|
2840
2963
|
// UDP-S1: Log tunnel active
|
|
2841
2964
|
// UDP-S13: Use targetHost and targetPort (not localPort)
|
|
@@ -2929,3 +3052,14 @@ export async function connectToRelayUdp(
|
|
|
2929
3052
|
}
|
|
2930
3053
|
|
|
2931
3054
|
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
|
|
3055
|
+
|
|
3056
|
+
// Story 11.2: exp claim (seconds) of an assignment token, or null
|
|
3057
|
+
function jwtExpOf(jwt) {
|
|
3058
|
+
try {
|
|
3059
|
+
const part = String(jwt).split('.')[1];
|
|
3060
|
+
const payload = JSON.parse(Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
3061
|
+
return typeof payload.exp === 'number' ? payload.exp : null;
|
|
3062
|
+
} catch {
|
|
3063
|
+
return null;
|
|
3064
|
+
}
|
|
3065
|
+
}
|
package/src/main.js
CHANGED
|
@@ -22,14 +22,24 @@ const handleFailure = (label) => (err) => {
|
|
|
22
22
|
|
|
23
23
|
async function run() {
|
|
24
24
|
const cmd = process.argv[2];
|
|
25
|
-
if (!cmd || cmd === "help") {
|
|
26
|
-
console.log(`asyx
|
|
25
|
+
if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") {
|
|
26
|
+
console.log(`asyx ${CLI_VERSION}
|
|
27
|
+
|
|
28
|
+
Usage: asyx <command>
|
|
27
29
|
|
|
28
30
|
Commands:
|
|
31
|
+
setup Enroll this machine (opens your browser once)
|
|
32
|
+
tunnel Open an HTTP, TCP or UDP tunnel to a local port
|
|
29
33
|
help Show this help
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
34
|
+
|
|
35
|
+
Examples:
|
|
36
|
+
asyx setup
|
|
37
|
+
asyx tunnel --http --port 3000
|
|
38
|
+
asyx tunnel --tcp --port 5432
|
|
39
|
+
asyx tunnel --udp --port 27015
|
|
40
|
+
|
|
41
|
+
Options for each tunnel type: asyx tunnel --help
|
|
42
|
+
Documentation: https://www.asyx.ai/docs
|
|
33
43
|
`);
|
|
34
44
|
process.exit(0);
|
|
35
45
|
}
|
|
@@ -48,7 +58,7 @@ async function run() {
|
|
|
48
58
|
const { default: tunnelCommand } = await import("./commands/tunnel.js");
|
|
49
59
|
tunnelCommand(process.argv.slice(3)).catch(handleFailure('Tunnel'));
|
|
50
60
|
} else {
|
|
51
|
-
console.log(`Unknown command: ${cmd}
|
|
61
|
+
console.log(`Unknown command: ${cmd}\nRun "asyx help" for the list of commands.`);
|
|
52
62
|
process.exit(1);
|
|
53
63
|
}
|
|
54
64
|
}
|
|
@@ -92,7 +92,7 @@ const registry = {
|
|
|
92
92
|
const isUdpTunnel = data.assignment?.tunnelMode === 'udpWs-v1' ||
|
|
93
93
|
data.assignment?.protocol === 'udp' ||
|
|
94
94
|
instanceContext.tunnelType === 'udp';
|
|
95
|
-
// Always override path for TCP/UDP tunnels, regardless of what
|
|
95
|
+
// Always override path for TCP/UDP tunnels, regardless of what the control plane returns
|
|
96
96
|
let path;
|
|
97
97
|
if (isUdpTunnel) {
|
|
98
98
|
path = '/udp';
|
|
@@ -14,6 +14,12 @@ import {
|
|
|
14
14
|
} from './httpws-constants.js';
|
|
15
15
|
|
|
16
16
|
const V2_THRESHOLD_BYTES = 8 * 1024 * 1024; // 8 MiB threshold for v2 selection
|
|
17
|
+
// Defect 11.9: the relay accepts WebSocket messages up to 16 MiB (wsProxy maxPayload); a larger
|
|
18
|
+
// one closes the whole tunnel (1009). A v1 response frame carries the body in base64.
|
|
19
|
+
const RELAY_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
20
|
+
const V1_MAX_FRAME_BYTES = RELAY_MAX_MESSAGE_BYTES - 64 * 1024; // headroom for JSON and headers
|
|
21
|
+
const HELLO_RETRY_MS = 3000;
|
|
22
|
+
const HELLO_MAX_ATTEMPTS = 3;
|
|
17
23
|
|
|
18
24
|
const TUNNEL_DROP_HEADERS = new Set([
|
|
19
25
|
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
|
|
@@ -543,7 +549,12 @@ export class HttpTunnel {
|
|
|
543
549
|
|
|
544
550
|
// CLI-IMG-WSReconnect: Clean up previous WebSocket if exists
|
|
545
551
|
if (this.ws) {
|
|
546
|
-
this.ws
|
|
552
|
+
const old = this.ws;
|
|
553
|
+
old.removeAllListeners();
|
|
554
|
+
// Defect 11.10: a late error from the replaced socket must not crash the CLI
|
|
555
|
+
// (an 'error' event with no listener is thrown by Node)
|
|
556
|
+
old.on('error', () => {});
|
|
557
|
+
try { if (old.readyState === WebSocket.OPEN || old.readyState === WebSocket.CONNECTING) old.terminate?.(); } catch (_) {}
|
|
547
558
|
this.ws = null;
|
|
548
559
|
}
|
|
549
560
|
|
|
@@ -559,7 +570,11 @@ export class HttpTunnel {
|
|
|
559
570
|
// CLI-IMG-WSReconnect: Reset retry count on successful connection
|
|
560
571
|
this.retryCount = 0;
|
|
561
572
|
|
|
562
|
-
// S-0: Send hello frame for HTTP-WS v2 negotiation
|
|
573
|
+
// S-0: Send hello frame for HTTP-WS v2 negotiation. Defect 11.9: negotiation is per
|
|
574
|
+
// connection (the relay checks it per connection), so forget the previous result
|
|
575
|
+
// and resend the hello until it is acknowledged.
|
|
576
|
+
this.httpWsVersion = null;
|
|
577
|
+
this._helloAttempts = 0;
|
|
563
578
|
this._sendHello();
|
|
564
579
|
|
|
565
580
|
// CLI-RES-DPJWT-LEAD: Check if refresh needed before resuming
|
|
@@ -664,6 +679,13 @@ export class HttpTunnel {
|
|
|
664
679
|
return;
|
|
665
680
|
}
|
|
666
681
|
|
|
682
|
+
// Defect 11.10: 'error' and 'close' both fire for one failed attempt; schedule once, so the
|
|
683
|
+
// backoff advances one step per attempt and two connects never race each other
|
|
684
|
+
if (this.reconnectTimer) {
|
|
685
|
+
this.log.debug({ code, reason }, 'Reconnect already scheduled');
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
|
|
667
689
|
// CLI-IMG-Retry-Ceiling: Check retry limit with descriptive messaging
|
|
668
690
|
if (this.retryCount >= this.maxRetries) {
|
|
669
691
|
this.log.error(
|
|
@@ -716,6 +738,7 @@ export class HttpTunnel {
|
|
|
716
738
|
|
|
717
739
|
// Schedule reconnect attempt
|
|
718
740
|
this.reconnectTimer = setTimeout(() => {
|
|
741
|
+
this.reconnectTimer = null;
|
|
719
742
|
this.attemptReconnect();
|
|
720
743
|
}, delay);
|
|
721
744
|
}
|
|
@@ -1404,10 +1427,24 @@ export class HttpTunnel {
|
|
|
1404
1427
|
|
|
1405
1428
|
this.ws.send(JSON.stringify(hello));
|
|
1406
1429
|
this.log.debug('Hello frame sent', { protocols: hello.protocols });
|
|
1430
|
+
// Defect 11.9: if no hello_ack arrives (the relay lost it), offer again
|
|
1431
|
+
this._helloAttempts = (this._helloAttempts || 0) + 1;
|
|
1432
|
+
if (this._helloTimer) clearTimeout(this._helloTimer);
|
|
1433
|
+
if (this._helloAttempts < HELLO_MAX_ATTEMPTS) {
|
|
1434
|
+
const ws = this.ws;
|
|
1435
|
+
this._helloTimer = setTimeout(() => {
|
|
1436
|
+
this._helloTimer = null;
|
|
1437
|
+
if (this.httpWsVersion || this.ws !== ws || ws.readyState !== WebSocket.OPEN) return;
|
|
1438
|
+
this.log.warn('hello.no_ack.resending', { attempt: this._helloAttempts + 1 });
|
|
1439
|
+
this._sendHello();
|
|
1440
|
+
}, HELLO_RETRY_MS);
|
|
1441
|
+
if (this._helloTimer.unref) this._helloTimer.unref();
|
|
1442
|
+
}
|
|
1407
1443
|
}
|
|
1408
1444
|
|
|
1409
1445
|
// S-0: Handle hello_ack for HTTP-WS v2 negotiation
|
|
1410
1446
|
_handleHelloAck(helloAck) {
|
|
1447
|
+
if (this._helloTimer) { clearTimeout(this._helloTimer); this._helloTimer = null; }
|
|
1411
1448
|
this.httpWsVersion = helloAck.protocols?.httpWs || null;
|
|
1412
1449
|
this.log.info('Hello ack received', { httpWsVersion: this.httpWsVersion });
|
|
1413
1450
|
|
|
@@ -1608,9 +1645,16 @@ export class HttpTunnel {
|
|
|
1608
1645
|
h: headerArray,
|
|
1609
1646
|
b: bodyBase64
|
|
1610
1647
|
};
|
|
1611
|
-
|
|
1648
|
+
const frame = JSON.stringify(responseData);
|
|
1649
|
+
// Defect 11.9: never send a message the relay refuses; it would close the whole tunnel.
|
|
1650
|
+
// Fail only this request (502) instead.
|
|
1651
|
+
if (Buffer.byteLength(frame) > V1_MAX_FRAME_BYTES) {
|
|
1652
|
+
this.log.error('v1.response.too_large', { requestId, bodyBytes: bodyBuffer.length, frameBytes: Buffer.byteLength(frame), httpWsVersion: this.httpWsVersion });
|
|
1653
|
+
this.sendTunnelError(requestId, 502);
|
|
1654
|
+
return;
|
|
1655
|
+
}
|
|
1612
1656
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
1613
|
-
this.ws.send(
|
|
1657
|
+
this.ws.send(frame);
|
|
1614
1658
|
}
|
|
1615
1659
|
});
|
|
1616
1660
|
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Story 11.2: reconnect for TCP and UDP tunnels.
|
|
2
|
+
//
|
|
3
|
+
// When the relay connection of an established TCP or UDP tunnel drops, the tunnel
|
|
4
|
+
// reconnects to the same relay and lease with the newest assignment token instead
|
|
5
|
+
// of ending the CLI. Everything bound to the old connection (TCP streams and their
|
|
6
|
+
// local sockets, UDP flows and their sockets, partial frames) is discarded first,
|
|
7
|
+
// so traffic from before the drop can never be delivered on the new connection.
|
|
8
|
+
//
|
|
9
|
+
// Settings (environment):
|
|
10
|
+
// ASYX_TUNNEL_RECONNECT=0 disable (the tunnel ends on a drop, as before)
|
|
11
|
+
// ASYX_TUNNEL_RECONNECT_MAX_MS give up after this long without a connection (default 15 min)
|
|
12
|
+
// ASYX_TUNNEL_RECONNECT_MAX_DELAY_MS longest wait between attempts (default 5000)
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_INITIAL_DELAY_MS = 250;
|
|
15
|
+
export const DEFAULT_MAX_DELAY_MS = 5000;
|
|
16
|
+
export const DEFAULT_MAX_OUTAGE_MS = 15 * 60 * 1000;
|
|
17
|
+
export const DEFAULT_MAX_AUTH_FAILURES = 3;
|
|
18
|
+
|
|
19
|
+
export function reconnectEnabled(env = process.env) {
|
|
20
|
+
return env.ASYX_TUNNEL_RECONNECT !== '0';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function envInt(env, name, fallback) {
|
|
24
|
+
const v = parseInt(env[name] ?? '', 10);
|
|
25
|
+
return Number.isFinite(v) && v > 0 ? v : fallback;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Decide what an established connection's close means.
|
|
30
|
+
* Close code 4000 is the relay's application code: "lease_closed" (the control plane
|
|
31
|
+
* ended the lease) and "lease_reconnected" (another connection took the lease over)
|
|
32
|
+
* must not be fought; anything else (relay restart, network loss, 1006, 1001, 1011,
|
|
33
|
+
* protocol errors) is retried.
|
|
34
|
+
*/
|
|
35
|
+
export function classifyDrop(code, reason) {
|
|
36
|
+
const r = String(reason || '');
|
|
37
|
+
if (code === 4000 && r === 'lease_closed') return { fatal: true, reason: 'lease_closed' };
|
|
38
|
+
if (code === 4000 && r === 'lease_reconnected') return { fatal: true, reason: 'replaced_by_another_connection' };
|
|
39
|
+
return { fatal: false, reason: `ws_close_${code}` };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** HTTP status from a ws handshake error ("Unexpected server response: 403"). */
|
|
43
|
+
export function httpStatusOf(err) {
|
|
44
|
+
if (!err) return null;
|
|
45
|
+
if (Number.isInteger(err.httpStatus)) return err.httpStatus;
|
|
46
|
+
const m = /Unexpected server response: (\d{3})/.exec(err.message || '');
|
|
47
|
+
return m ? Number(m[1]) : null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Decide what a failed reconnect attempt means.
|
|
52
|
+
* 401/403 and token verification failures are counted as authorization failures
|
|
53
|
+
* (the token expired or the lease was closed); a few in a row end the tunnel.
|
|
54
|
+
* 409 means the relay still holds the old connection for the lease; retry.
|
|
55
|
+
* 400 means the request itself is malformed; retrying cannot help.
|
|
56
|
+
*/
|
|
57
|
+
export function classifyFailure(err) {
|
|
58
|
+
const status = httpStatusOf(err);
|
|
59
|
+
if (status === 400) return { fatal: true, auth: false, reason: 'bad_request' };
|
|
60
|
+
if (status === 401 || status === 403) return { fatal: false, auth: true, reason: `http_${status}` };
|
|
61
|
+
if (err && err.code === 'UDP_RELAY_UNAVAILABLE' && /JWT verification failed/.test(err.message || '')) {
|
|
62
|
+
// Failing to fetch the JWKS (network) is not a token problem: keep retrying
|
|
63
|
+
const cause = err.cause || {};
|
|
64
|
+
const fetchProblem = /JWKS|fetch|timeout|ECONN|ENOTFOUND|EAI_AGAIN|network/i.test(`${cause.code || ''} ${cause.message || ''}`)
|
|
65
|
+
&& !/expired|signature|claim/i.test(`${cause.code || ''} ${cause.message || ''}`);
|
|
66
|
+
if (fetchProblem) return { fatal: false, auth: false, reason: 'jwks_unavailable' };
|
|
67
|
+
return { fatal: false, auth: true, reason: 'token_verification_failed' };
|
|
68
|
+
}
|
|
69
|
+
return { fatal: false, auth: false, reason: status ? `http_${status}` : (err?.code || 'connect_failed') };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Seconds-since-epoch exp claim of a JWT, or null. */
|
|
73
|
+
export function jwtExp(jwt) {
|
|
74
|
+
try {
|
|
75
|
+
const part = String(jwt).split('.')[1];
|
|
76
|
+
const payload = JSON.parse(Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
77
|
+
return typeof payload.exp === 'number' ? payload.exp : null;
|
|
78
|
+
} catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Runs the reconnect loop for one tunnel.
|
|
85
|
+
* connect(): Promise resolving when a new connection is open, rejecting otherwise.
|
|
86
|
+
* onGiveUp(reason): called once if the tunnel cannot be reconnected.
|
|
87
|
+
* onAuthFailure(): optional (Story 10.9). Called on the first authorization failure of a
|
|
88
|
+
* streak; it may fetch a new assignment (for example after the tenant moved to another
|
|
89
|
+
* relay, where the old token's relay no longer matches). If it returns true, the streak
|
|
90
|
+
* is reset and the next attempt uses the new assignment at once.
|
|
91
|
+
*/
|
|
92
|
+
export class Reconnector {
|
|
93
|
+
constructor({
|
|
94
|
+
kind,
|
|
95
|
+
log,
|
|
96
|
+
connect,
|
|
97
|
+
onGiveUp,
|
|
98
|
+
env = process.env,
|
|
99
|
+
initialDelayMs = DEFAULT_INITIAL_DELAY_MS,
|
|
100
|
+
maxDelayMs = envInt(env, 'ASYX_TUNNEL_RECONNECT_MAX_DELAY_MS', DEFAULT_MAX_DELAY_MS),
|
|
101
|
+
maxOutageMs = envInt(env, 'ASYX_TUNNEL_RECONNECT_MAX_MS', DEFAULT_MAX_OUTAGE_MS),
|
|
102
|
+
maxAuthFailures = DEFAULT_MAX_AUTH_FAILURES,
|
|
103
|
+
onAuthFailure = null,
|
|
104
|
+
now = () => Date.now(),
|
|
105
|
+
sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
106
|
+
}) {
|
|
107
|
+
Object.assign(this, { kind, log, connect, onGiveUp, initialDelayMs, maxDelayMs, maxOutageMs, maxAuthFailures, onAuthFailure, now, sleep });
|
|
108
|
+
this.running = false;
|
|
109
|
+
this.stopped = false;
|
|
110
|
+
this.reconnects = 0;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
stop() {
|
|
114
|
+
this.stopped = true;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
delayFor(attempt) {
|
|
118
|
+
return Math.min(this.maxDelayMs, this.initialDelayMs * 2 ** attempt);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Start reconnecting after a drop. Resolves when connected, given up or stopped. */
|
|
122
|
+
async run(dropReason) {
|
|
123
|
+
if (this.running || this.stopped) return;
|
|
124
|
+
this.running = true;
|
|
125
|
+
const started = this.now();
|
|
126
|
+
let authFailures = 0;
|
|
127
|
+
let reassigned = false;
|
|
128
|
+
this.log.warn({ kind: this.kind, reason: dropReason }, `${this.kind}.reconnect.start`);
|
|
129
|
+
try {
|
|
130
|
+
for (let attempt = 0; ; attempt++) {
|
|
131
|
+
if (!reassigned) await this.sleep(this.delayFor(attempt));
|
|
132
|
+
reassigned = false;
|
|
133
|
+
if (this.stopped) return;
|
|
134
|
+
const outageMs = this.now() - started;
|
|
135
|
+
if (outageMs > this.maxOutageMs) {
|
|
136
|
+
this.giveUp('outage_limit', { outageMs, attempts: attempt });
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
await this.connect();
|
|
141
|
+
this.reconnects += 1;
|
|
142
|
+
this.log.info({ kind: this.kind, attempts: attempt + 1, outageMs: this.now() - started, reconnects: this.reconnects },
|
|
143
|
+
`${this.kind}.reconnect.ok`);
|
|
144
|
+
return;
|
|
145
|
+
} catch (err) {
|
|
146
|
+
if (this.stopped) return;
|
|
147
|
+
const verdict = classifyFailure(err);
|
|
148
|
+
this.log.warn({ kind: this.kind, attempt: attempt + 1, reason: verdict.reason, error: err?.message },
|
|
149
|
+
`${this.kind}.reconnect.attempt_failed`);
|
|
150
|
+
if (verdict.fatal) {
|
|
151
|
+
this.giveUp(verdict.reason, { attempts: attempt + 1 });
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
authFailures = verdict.auth ? authFailures + 1 : 0;
|
|
155
|
+
if (authFailures === 1 && this.onAuthFailure) {
|
|
156
|
+
let got = false;
|
|
157
|
+
try { got = await this.onAuthFailure(); } catch (e) {
|
|
158
|
+
this.log.warn({ kind: this.kind, error: e?.message }, `${this.kind}.reconnect.reassign_failed`);
|
|
159
|
+
}
|
|
160
|
+
if (got) {
|
|
161
|
+
this.log.info({ kind: this.kind, attempt: attempt + 1 }, `${this.kind}.reconnect.reassigned`);
|
|
162
|
+
authFailures = 0;
|
|
163
|
+
reassigned = true;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (authFailures >= this.maxAuthFailures) {
|
|
168
|
+
this.giveUp(`${verdict.reason}_repeated`, { attempts: attempt + 1 });
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
} finally {
|
|
174
|
+
this.running = false;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
giveUp(reason, extra = {}) {
|
|
179
|
+
this.log.error({ kind: this.kind, reason, ...extra }, `${this.kind}.reconnect.gave_up`);
|
|
180
|
+
this.onGiveUp(reason);
|
|
181
|
+
}
|
|
182
|
+
}
|
package/src/tunnel/tcp-tunnel.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Mirrors HttpTunnel structure but handles TCP streams instead of HTTP requests
|
|
3
3
|
// TCP-S5: Uses binary tcp-v1 framing protocol
|
|
4
4
|
import WebSocket from 'ws';
|
|
5
|
+
import { Reconnector, reconnectEnabled, classifyDrop } from './reconnect.js';
|
|
5
6
|
import net from 'net';
|
|
6
7
|
import crypto from 'node:crypto';
|
|
7
8
|
// CLI-REAUTH: Control frame helper for in-band reauth
|
|
@@ -26,9 +27,19 @@ export class TcpTunnel {
|
|
|
26
27
|
getLastMqttError = () => null, // QPA-CLI-02: Get last MQTT error for diagnostics
|
|
27
28
|
getForceReconnect = () => null, // QPA-CLI-03: Get force reconnect function
|
|
28
29
|
controlPlaneTimeoutMs = 60000,
|
|
30
|
+
// Story 11.2: newest assignment token for reconnects (the tunnel command keeps it
|
|
31
|
+
// refreshed, TPB-17); falls back to the token the tunnel was opened with.
|
|
32
|
+
getJwt = null,
|
|
33
|
+
reassign = null,
|
|
34
|
+
exit = (code) => process.exit(code),
|
|
29
35
|
}) {
|
|
30
36
|
this.relayUrl = relayUrl;
|
|
31
37
|
this.jwt = jwt; // Accept JWT as-is (no validation)
|
|
38
|
+
this.getJwt = getJwt;
|
|
39
|
+
// Story 10.9: async () => ({ relayUrl, jwt, leaseId }) | null - a new assignment when the
|
|
40
|
+
// relay refuses the old one (the tenant was moved to another relay)
|
|
41
|
+
this.reassign = reassign;
|
|
42
|
+
this.exit = exit;
|
|
32
43
|
this.deviceId = deviceId;
|
|
33
44
|
this.requestId = requestId;
|
|
34
45
|
this.localPort = localPort;
|
|
@@ -36,7 +47,7 @@ export class TcpTunnel {
|
|
|
36
47
|
this.log = log;
|
|
37
48
|
this.ws = null;
|
|
38
49
|
|
|
39
|
-
// Coordinator connection
|
|
50
|
+
// Coordinator connection
|
|
40
51
|
this.coordinatorCore = coordinatorCore;
|
|
41
52
|
this.coordinatorIngress = coordinatorIngress;
|
|
42
53
|
|
|
@@ -51,9 +62,34 @@ export class TcpTunnel {
|
|
|
51
62
|
this.heartbeatTimer = null;
|
|
52
63
|
this.lastActivityMs = Date.now();
|
|
53
64
|
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
|
|
65
|
+
// Story 11.2: when the relay connection drops, active visitor connections end
|
|
66
|
+
// (their streams lived on that connection) and the tunnel reconnects to the same
|
|
67
|
+
// lease, so new visitor connections work again without rerunning the CLI.
|
|
68
|
+
this.headers = null; // Headers of the current WebSocket connection
|
|
69
|
+
this.closing = false; // set by close(): no reconnect
|
|
70
|
+
this.everOpened = false;
|
|
71
|
+
this.lastInboundMs = Date.now();
|
|
72
|
+
this.reconnectEnabled = reconnectEnabled();
|
|
73
|
+
this.reconnector = new Reconnector({
|
|
74
|
+
onAuthFailure: async () => {
|
|
75
|
+
if (!this.reassign) return false;
|
|
76
|
+
const a = await this.reassign();
|
|
77
|
+
if (!a || !a.jwt) return false;
|
|
78
|
+
this.log.info({ leaseId: a.leaseId, relayUrl: a.relayUrl }, 'tcp.tunnel.reassigned');
|
|
79
|
+
this.jwt = a.jwt;
|
|
80
|
+
if (a.relayUrl) this.relayUrl = a.relayUrl;
|
|
81
|
+
if (a.leaseId) this.leaseId = a.leaseId;
|
|
82
|
+
if (a.relayId) this.relayId = a.relayId; // the new relay (UDP checks tokens against it)
|
|
83
|
+
return true;
|
|
84
|
+
},
|
|
85
|
+
kind: 'tcp',
|
|
86
|
+
log: this.log,
|
|
87
|
+
connect: () => this._attemptConnect(),
|
|
88
|
+
onGiveUp: (reason) => {
|
|
89
|
+
this.log.info({ reason }, 'TCP tunnel exiting: relay connection could not be restored');
|
|
90
|
+
this.exit(1);
|
|
91
|
+
},
|
|
92
|
+
});
|
|
57
93
|
|
|
58
94
|
// TCP-S5: Active TCP stream connections (keyed by numeric streamId)
|
|
59
95
|
this.activeStreams = new Map(); // streamId (number) -> { localSocket, idleTimer, lastActivity }
|
|
@@ -77,8 +113,6 @@ export class TcpTunnel {
|
|
|
77
113
|
this.tcpKeepalive = process.env.ASYX_TCP_KEEPALIVE !== '0'; // Enabled by default
|
|
78
114
|
this.tcpKeepaliveInitialDelay = parseInt(process.env.ASYX_TCP_KEEPALIVE_INITIAL_DELAY_MS || "60000", 10); // 60 seconds
|
|
79
115
|
|
|
80
|
-
// TCP tunnels do NOT support JWT refresh or in-band reauth (unlike HTTP tunnels)
|
|
81
|
-
// These properties are not used but kept for potential future implementation
|
|
82
116
|
}
|
|
83
117
|
|
|
84
118
|
async open() {
|
|
@@ -87,18 +121,20 @@ export class TcpTunnel {
|
|
|
87
121
|
|
|
88
122
|
async _attemptConnect() {
|
|
89
123
|
return new Promise((resolve, reject) => {
|
|
90
|
-
//
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
}
|
|
124
|
+
// Story 11.2: use the newest assignment token on every (re)connect
|
|
125
|
+
const freshJwt = this.getJwt ? this.getJwt() : null;
|
|
126
|
+
if (freshJwt) this.jwt = freshJwt;
|
|
127
|
+
this.headers = {
|
|
128
|
+
'Authorization': `Bearer ${this.jwt}`,
|
|
129
|
+
'X-Asyx-DeviceId': this.deviceId,
|
|
130
|
+
'X-Asyx-RequestId': this.requestId
|
|
131
|
+
};
|
|
98
132
|
|
|
99
133
|
// Clean up previous WebSocket if exists
|
|
100
134
|
if (this.ws) {
|
|
101
|
-
this.ws
|
|
135
|
+
const old = this.ws;
|
|
136
|
+
old.removeAllListeners();
|
|
137
|
+
old.on('error', () => {}); // a late error from the old socket must not crash the CLI
|
|
102
138
|
this.ws = null;
|
|
103
139
|
}
|
|
104
140
|
|
|
@@ -132,13 +168,19 @@ export class TcpTunnel {
|
|
|
132
168
|
// TCP-S5: Request tcp-v1 subprotocol
|
|
133
169
|
protocol: 'tcp-v1'
|
|
134
170
|
};
|
|
135
|
-
|
|
171
|
+
const ws = new WebSocket(wsUrl, wsOptions);
|
|
172
|
+
this.ws = ws;
|
|
173
|
+
let opened = false;
|
|
174
|
+
let failure = null;
|
|
136
175
|
|
|
137
|
-
|
|
176
|
+
ws.on('open', () => {
|
|
177
|
+
opened = true;
|
|
178
|
+
this.everOpened = true;
|
|
179
|
+
this.protocolViolation = false;
|
|
180
|
+
this.frameBuffer = Buffer.alloc(0);
|
|
181
|
+
this.lastInboundMs = Date.now();
|
|
138
182
|
this.log.info({ relayUrl: this.relayUrl, localPort: this.localPort }, 'Tunnel WS open - TCP proxy mode active');
|
|
139
183
|
|
|
140
|
-
// Connection successful
|
|
141
|
-
|
|
142
184
|
// TCP-S5: Start PING keepalive timer after WebSocket opens
|
|
143
185
|
// NOTE: Do NOT start legacy JSON heartbeat for TCP - relay only accepts binary tcp-v1 frames
|
|
144
186
|
this.startPingKeepalive();
|
|
@@ -146,9 +188,10 @@ export class TcpTunnel {
|
|
|
146
188
|
resolve();
|
|
147
189
|
});
|
|
148
190
|
|
|
149
|
-
|
|
191
|
+
ws.on('message', (data, isBinary) => {
|
|
150
192
|
// CRT-Relay-E: Update activity on any message
|
|
151
193
|
this.lastActivityMs = Date.now();
|
|
194
|
+
this.lastInboundMs = this.lastActivityMs;
|
|
152
195
|
|
|
153
196
|
// TCP-S5: All tcp-v1 frames are binary - relay only accepts binary frames
|
|
154
197
|
// Note: ws library may pass Buffer for binary, but isBinary flag should be true
|
|
@@ -170,41 +213,71 @@ export class TcpTunnel {
|
|
|
170
213
|
// Do not process text frames - they will cause protocol violations on the relay
|
|
171
214
|
});
|
|
172
215
|
|
|
173
|
-
|
|
174
|
-
// QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
|
|
216
|
+
ws.on('close', (code, reason) => {
|
|
175
217
|
const reasonStr = reason?.toString() || '';
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
this.
|
|
218
|
+
if (!opened) {
|
|
219
|
+
// The connection attempt failed before it opened
|
|
220
|
+
const err = failure || new Error(`WebSocket closed before open (code ${code})`);
|
|
221
|
+
err.closeCode = code;
|
|
222
|
+
this.stopPingKeepalive();
|
|
223
|
+
if (!this.everOpened) {
|
|
224
|
+
// First connect: unchanged behaviour, the CLI ends
|
|
225
|
+
this.log.info('TCP tunnel exiting due to WebSocket error');
|
|
226
|
+
this.exit(1);
|
|
227
|
+
}
|
|
228
|
+
reject(err);
|
|
229
|
+
return;
|
|
181
230
|
}
|
|
182
|
-
|
|
183
|
-
this.stopPingKeepalive();
|
|
184
|
-
// TCP-S5: No JSON control frames for TCP - no cleanup needed
|
|
185
|
-
// CLI-REAUTH: Control frames disabled for TCP tunnels (binary-only protocol)
|
|
186
|
-
|
|
187
|
-
// TCP-S4: Close all active TCP streams on WebSocket close
|
|
188
|
-
this.closeAllStreams();
|
|
189
|
-
|
|
190
|
-
// TCP tunnels exit on WebSocket close (unlike HTTP tunnels which have JWT refresh)
|
|
191
|
-
// Reconnecting would break active TCP connections and create new leaseId conflicts
|
|
192
|
-
this.log.info('TCP tunnel exiting due to WebSocket close');
|
|
193
|
-
process.exit(1);
|
|
231
|
+
this._onDropped(code, reasonStr);
|
|
194
232
|
});
|
|
195
233
|
|
|
196
|
-
|
|
234
|
+
ws.on('error', (err) => {
|
|
235
|
+
// A 'close' event always follows; the decision is made there
|
|
236
|
+
failure = err;
|
|
197
237
|
this.log.error({ err }, 'Tunnel WS error');
|
|
198
|
-
// TCP-S5: Stop PING keepalive on error
|
|
199
238
|
this.stopPingKeepalive();
|
|
200
|
-
|
|
201
|
-
// TCP tunnels exit on WebSocket error (unlike HTTP tunnels which have JWT refresh)
|
|
202
|
-
this.log.info('TCP tunnel exiting due to WebSocket error');
|
|
203
|
-
process.exit(1);
|
|
204
239
|
});
|
|
205
240
|
});
|
|
206
241
|
}
|
|
207
242
|
|
|
243
|
+
// Story 11.2: an established relay connection dropped
|
|
244
|
+
_onDropped(code, reasonStr) {
|
|
245
|
+
// QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
|
|
246
|
+
const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
|
|
247
|
+
if (isNormalClose) {
|
|
248
|
+
this.log.debug({ code, reason: reasonStr }, 'Tunnel WS closed');
|
|
249
|
+
} else {
|
|
250
|
+
this.log.warn({ code, reason: reasonStr }, 'Tunnel WS closed');
|
|
251
|
+
}
|
|
252
|
+
this.stopPingKeepalive();
|
|
253
|
+
// TCP-S4: visitor connections lived on the dropped connection; end them all and
|
|
254
|
+
// discard partial frames so nothing from before the drop reaches the new one
|
|
255
|
+
this.closeAllStreams();
|
|
256
|
+
this.frameBuffer = Buffer.alloc(0);
|
|
257
|
+
|
|
258
|
+
if (this.closing) return;
|
|
259
|
+
const verdict = classifyDrop(code, reasonStr);
|
|
260
|
+
// Story 10.9: a lease the relay closed (4000 lease_closed) may have been moved to another
|
|
261
|
+
// relay by an operator; ask the control plane once for a new assignment for the same port
|
|
262
|
+
// and continue there. If it refuses, the tunnel ends as before. lease_reconnected (another
|
|
263
|
+
// CLI took the lease) stays final.
|
|
264
|
+
if (this.reconnectEnabled && verdict.fatal && reasonStr === 'lease_closed' && this.reassign) {
|
|
265
|
+
this.log.warn({ code, reason: reasonStr }, 'tcp.tunnel.lease_closed.reassigning');
|
|
266
|
+
this.reconnector.onAuthFailure().then((got) => {
|
|
267
|
+
if (got && !this.closing) { this.reconnector.run('lease_closed_reassigned'); return; }
|
|
268
|
+
this.log.info({ reason: verdict.reason }, 'TCP tunnel exiting due to WebSocket close');
|
|
269
|
+
this.exit(1);
|
|
270
|
+
}).catch(() => this.exit(1));
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (!this.reconnectEnabled || verdict.fatal) {
|
|
274
|
+
this.log.info({ reason: verdict.reason }, 'TCP tunnel exiting due to WebSocket close');
|
|
275
|
+
this.exit(1);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
this.reconnector.run(verdict.reason);
|
|
279
|
+
}
|
|
280
|
+
|
|
208
281
|
// TCP-S5: Handle binary tcp-v1 frames
|
|
209
282
|
handleBinaryFrame(data) {
|
|
210
283
|
// Append new data to frame buffer
|
|
@@ -310,7 +383,7 @@ export class TcpTunnel {
|
|
|
310
383
|
this.ws.close(1003, `Protocol violation: ${error.message}`); // 1003 = Unsupported Data
|
|
311
384
|
}
|
|
312
385
|
|
|
313
|
-
//
|
|
386
|
+
// Story 11.2: the close event reconnects with fresh state
|
|
314
387
|
}
|
|
315
388
|
|
|
316
389
|
// TCP-S5: Handle STREAM_OPEN frame
|
|
@@ -723,6 +796,7 @@ export class TcpTunnel {
|
|
|
723
796
|
|
|
724
797
|
// TCP-S5: Start PING keepalive timer (parity with relay)
|
|
725
798
|
startPingKeepalive() {
|
|
799
|
+
this.stopPingKeepalive(); // never two timers after a reconnect
|
|
726
800
|
if (this.pingIntervalMs <= 0) {
|
|
727
801
|
this.log.debug('PING keepalive disabled (ASYX_TCP_PING_INTERVAL_MS <= 0)');
|
|
728
802
|
return;
|
|
@@ -750,6 +824,16 @@ export class TcpTunnel {
|
|
|
750
824
|
return;
|
|
751
825
|
}
|
|
752
826
|
|
|
827
|
+
// Story 11.2: nothing received from the relay for three ping intervals means the
|
|
828
|
+
// connection is dead without a close (for example a lost network path); drop it so
|
|
829
|
+
// the tunnel reconnects instead of waiting for TCP to time out
|
|
830
|
+
const silentMs = Date.now() - this.lastInboundMs;
|
|
831
|
+
if (silentMs > 3 * this.pingIntervalMs) {
|
|
832
|
+
this.log.warn({ silentMs }, 'tcp.ws.liveness_timeout');
|
|
833
|
+
this.ws.terminate();
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
|
|
753
837
|
try {
|
|
754
838
|
const pingFrame = encodeFrame({
|
|
755
839
|
type: FrameType.PING,
|
|
@@ -804,12 +888,10 @@ export class TcpTunnel {
|
|
|
804
888
|
}
|
|
805
889
|
}
|
|
806
890
|
|
|
807
|
-
// TCP tunnels do NOT support reconnect (removed - was causing issues with active connections)
|
|
808
|
-
// HTTP tunnels have JWT refresh, so they can reconnect safely
|
|
809
|
-
// TCP tunnels exit on WebSocket close to avoid breaking active TCP streams
|
|
810
|
-
|
|
811
891
|
close() {
|
|
812
|
-
//
|
|
892
|
+
// Story 11.2: a deliberate close does not reconnect
|
|
893
|
+
this.closing = true;
|
|
894
|
+
this.reconnector.stop();
|
|
813
895
|
|
|
814
896
|
// TCP-S5: Stop PING keepalive
|
|
815
897
|
this.stopPingKeepalive();
|
package/src/tunnel/udp-tunnel.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Handles UDP datagrams over WebSocket using udpWs-v1 framing
|
|
3
3
|
// UDP-S1: CLI – UDP entrypoint & WS connect
|
|
4
4
|
import WebSocket from 'ws';
|
|
5
|
+
import { Reconnector, reconnectEnabled, classifyDrop } from './reconnect.js';
|
|
5
6
|
import dgram from 'dgram';
|
|
6
7
|
import { FrameType, FRAME_HEADER_SIZE, encodeFrame, decodeFrame, validateFrame, UdpV1FramingError } from '../udp-v1/framing.js';
|
|
7
8
|
import { verifyAssignmentJWT, isJWKSAvailable } from '../lib/jwt-verifier.js';
|
|
@@ -37,9 +38,19 @@ export class UdpTunnel {
|
|
|
37
38
|
getLastMqttError = () => null,
|
|
38
39
|
getForceReconnect = () => null,
|
|
39
40
|
controlPlaneTimeoutMs = 60000,
|
|
41
|
+
// Story 11.2: newest assignment token for reconnects; falls back to the token
|
|
42
|
+
// the tunnel was opened with.
|
|
43
|
+
getJwt = null,
|
|
44
|
+
reassign = null,
|
|
45
|
+
exit = (code) => process.exit(code),
|
|
40
46
|
}) {
|
|
41
47
|
this.relayUrl = relayUrl;
|
|
42
48
|
this.jwt = jwt;
|
|
49
|
+
this.getJwt = getJwt;
|
|
50
|
+
// Story 10.9: async () => ({ relayUrl, jwt, leaseId }) | null - a new assignment when the
|
|
51
|
+
// relay refuses the old one (the tenant was moved to another relay)
|
|
52
|
+
this.reassign = reassign;
|
|
53
|
+
this.exit = exit;
|
|
43
54
|
this.deviceId = deviceId;
|
|
44
55
|
this.requestId = requestId;
|
|
45
56
|
// UDP-S13: Use targetHost/targetPort (fallback to localPort for backward compatibility)
|
|
@@ -54,7 +65,7 @@ export class UdpTunnel {
|
|
|
54
65
|
this.ws = null;
|
|
55
66
|
// UDP-S14: Per-flow sockets managed via flowMap (no single udpSocket)
|
|
56
67
|
|
|
57
|
-
// Coordinator connection
|
|
68
|
+
// Coordinator connection
|
|
58
69
|
this.coordinatorCore = coordinatorCore;
|
|
59
70
|
this.coordinatorIngress = coordinatorIngress;
|
|
60
71
|
|
|
@@ -88,6 +99,34 @@ export class UdpTunnel {
|
|
|
88
99
|
// UDP-S1: Flow idle timeout (60-300 seconds per protocol spec)
|
|
89
100
|
this.flowIdleTimeoutMs = parseInt(process.env.ASYX_UDP_FLOW_IDLE_TIMEOUT_MS || "60000", 10); // 60 seconds
|
|
90
101
|
this.flowCleanupTimer = null;
|
|
102
|
+
|
|
103
|
+
// Story 11.2: reconnect to the same lease when the relay connection drops. Flow ids
|
|
104
|
+
// belong to one relay connection, so all flows and their sockets are discarded on a
|
|
105
|
+
// drop; a flow id reused by the relay after reconnecting can never reach an old socket.
|
|
106
|
+
this.closing = false; // set by close(): no reconnect
|
|
107
|
+
this.everOpened = false;
|
|
108
|
+
this.lastInboundMs = Date.now();
|
|
109
|
+
this.reconnectEnabled = reconnectEnabled();
|
|
110
|
+
this.reconnector = new Reconnector({
|
|
111
|
+
onAuthFailure: async () => {
|
|
112
|
+
if (!this.reassign) return false;
|
|
113
|
+
const a = await this.reassign();
|
|
114
|
+
if (!a || !a.jwt) return false;
|
|
115
|
+
this.log.info({ leaseId: a.leaseId, relayUrl: a.relayUrl }, 'udp.tunnel.reassigned');
|
|
116
|
+
this.jwt = a.jwt;
|
|
117
|
+
if (a.relayUrl) this.relayUrl = a.relayUrl;
|
|
118
|
+
if (a.leaseId) this.leaseId = a.leaseId;
|
|
119
|
+
if (a.relayId) this.relayId = a.relayId; // the new relay (UDP checks tokens against it)
|
|
120
|
+
return true;
|
|
121
|
+
},
|
|
122
|
+
kind: 'udp',
|
|
123
|
+
log: this.log,
|
|
124
|
+
connect: () => this._attemptConnect(),
|
|
125
|
+
onGiveUp: (reason) => {
|
|
126
|
+
this.log.info({ reason }, 'UDP tunnel exiting: relay connection could not be restored');
|
|
127
|
+
this.exit(1);
|
|
128
|
+
},
|
|
129
|
+
});
|
|
91
130
|
}
|
|
92
131
|
|
|
93
132
|
async open() {
|
|
@@ -95,6 +134,9 @@ export class UdpTunnel {
|
|
|
95
134
|
}
|
|
96
135
|
|
|
97
136
|
async _attemptConnect() {
|
|
137
|
+
// Story 11.2: use the newest assignment token on every (re)connect
|
|
138
|
+
const freshJwt = this.getJwt ? this.getJwt() : null;
|
|
139
|
+
if (freshJwt) this.jwt = freshJwt;
|
|
98
140
|
return new Promise((resolve, reject) => {
|
|
99
141
|
// UDP-S1: Validate relayUrl format
|
|
100
142
|
if (!this.relayUrl) {
|
|
@@ -150,6 +192,12 @@ export class UdpTunnel {
|
|
|
150
192
|
// Note: JWT verification is async, so we need to handle it inside an async IIFE
|
|
151
193
|
(async () => {
|
|
152
194
|
try {
|
|
195
|
+
// Story 11.2: a token already verified for this tunnel is not verified again on
|
|
196
|
+
// reconnect, so a reconnect does not depend on reaching the JWKS endpoint
|
|
197
|
+
if (this.verifiedJwt && this.verifiedJwt === this.jwt) {
|
|
198
|
+
this._setupWebSocketConnection(wsUrl, resolve, reject);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
153
201
|
// AC1.4/AC5.1: Verify JWT signature and claims using JWKS
|
|
154
202
|
// verifyAssignmentJWT will initialize JWKS on first call and fail fast if unavailable
|
|
155
203
|
const { verifyAssignmentJWT } = await import('../lib/jwt-verifier.js');
|
|
@@ -168,6 +216,7 @@ export class UdpTunnel {
|
|
|
168
216
|
tunnelMode: payload.tunnelMode
|
|
169
217
|
});
|
|
170
218
|
|
|
219
|
+
this.verifiedJwt = this.jwt;
|
|
171
220
|
// Continue with WebSocket connection setup after JWT verification
|
|
172
221
|
this._setupWebSocketConnection(wsUrl, resolve, reject);
|
|
173
222
|
} catch (jwtError) {
|
|
@@ -175,6 +224,7 @@ export class UdpTunnel {
|
|
|
175
224
|
// This includes: JWKS unavailable, signature invalid, claims mismatch, expired, etc.
|
|
176
225
|
const error = new Error(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`);
|
|
177
226
|
error.code = 'UDP_RELAY_UNAVAILABLE';
|
|
227
|
+
error.cause = jwtError;
|
|
178
228
|
this.log.error('udp.jwt.verification_failed', {
|
|
179
229
|
error: jwtError.message,
|
|
180
230
|
code: jwtError.code,
|
|
@@ -190,7 +240,9 @@ export class UdpTunnel {
|
|
|
190
240
|
_setupWebSocketConnection(wsUrl, resolve, reject) {
|
|
191
241
|
// Clean up previous WebSocket if exists
|
|
192
242
|
if (this.ws) {
|
|
193
|
-
this.ws
|
|
243
|
+
const old = this.ws;
|
|
244
|
+
old.removeAllListeners();
|
|
245
|
+
old.on('error', () => {}); // a late error from the old socket must not crash the CLI
|
|
194
246
|
this.ws = null;
|
|
195
247
|
}
|
|
196
248
|
|
|
@@ -203,9 +255,17 @@ export class UdpTunnel {
|
|
|
203
255
|
},
|
|
204
256
|
rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1', // Allow dev override
|
|
205
257
|
};
|
|
206
|
-
|
|
258
|
+
const ws = new WebSocket(wsUrl, wsOptions);
|
|
259
|
+
this.ws = ws;
|
|
260
|
+
let opened = false;
|
|
261
|
+
let failure = null;
|
|
207
262
|
|
|
208
|
-
|
|
263
|
+
ws.on('open', () => {
|
|
264
|
+
opened = true;
|
|
265
|
+
this.everOpened = true;
|
|
266
|
+
this.protocolViolation = false;
|
|
267
|
+
this.frameBuffer = Buffer.alloc(0);
|
|
268
|
+
this.lastInboundMs = Date.now();
|
|
209
269
|
this.log.info({ leaseId: this.leaseId, targetHost: this.targetHost, targetPort: this.targetPort }, 'udp.tunnel.ws.open');
|
|
210
270
|
|
|
211
271
|
// UDP-S1: Start PING keepalive timer
|
|
@@ -220,7 +280,8 @@ export class UdpTunnel {
|
|
|
220
280
|
resolve();
|
|
221
281
|
});
|
|
222
282
|
|
|
223
|
-
|
|
283
|
+
ws.on('message', (data, isBinary) => {
|
|
284
|
+
this.lastInboundMs = Date.now();
|
|
224
285
|
// UDP-S1: All udpWs-v1 frames are binary
|
|
225
286
|
const isActuallyBinary = isBinary || Buffer.isBuffer(data);
|
|
226
287
|
|
|
@@ -238,38 +299,70 @@ export class UdpTunnel {
|
|
|
238
299
|
);
|
|
239
300
|
});
|
|
240
301
|
|
|
241
|
-
|
|
302
|
+
ws.on('close', (code, reason) => {
|
|
242
303
|
const reasonStr = reason?.toString() || '';
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
304
|
+
if (!opened) {
|
|
305
|
+
// The connection attempt failed before it opened
|
|
306
|
+
const error = new Error(`UDP_RELAY_UNAVAILABLE: WebSocket connection failed: ${failure?.message || `closed before open (code ${code})`}`);
|
|
307
|
+
error.code = 'UDP_RELAY_UNAVAILABLE';
|
|
308
|
+
error.closeCode = code;
|
|
309
|
+
error.cause = failure;
|
|
310
|
+
this.stopPingKeepalive();
|
|
311
|
+
this.stopFlowCleanup();
|
|
312
|
+
if (!this.everOpened) {
|
|
313
|
+
// First connect: unchanged behaviour, the CLI ends
|
|
314
|
+
this.log.error('UDP tunnel exiting due to WebSocket error');
|
|
315
|
+
this.exit(1);
|
|
316
|
+
}
|
|
317
|
+
reject(error);
|
|
318
|
+
return;
|
|
248
319
|
}
|
|
249
|
-
|
|
250
|
-
this.stopPingKeepalive();
|
|
251
|
-
this.stopFlowCleanup();
|
|
252
|
-
this.closeAllFlowSockets();
|
|
253
|
-
|
|
254
|
-
// UDP-S1: Exit on WS close (no reconnect loop)
|
|
255
|
-
this.log.info('UDP tunnel exiting due to WebSocket close');
|
|
256
|
-
process.exit(1);
|
|
320
|
+
this._onDropped(code, reasonStr);
|
|
257
321
|
});
|
|
258
322
|
|
|
259
|
-
|
|
323
|
+
ws.on('error', (err) => {
|
|
324
|
+
// A 'close' event always follows; the decision is made there
|
|
325
|
+
failure = err;
|
|
260
326
|
this.log.error({ err: err.message, code: err.code }, 'udp.tunnel.ws.error');
|
|
261
|
-
this.stopPingKeepalive();
|
|
262
|
-
this.stopFlowCleanup();
|
|
263
|
-
this.closeAllFlowSockets();
|
|
264
|
-
|
|
265
|
-
// UDP-S1: Exit on WS error (no reconnect loop)
|
|
266
|
-
const error = new Error(`UDP_RELAY_UNAVAILABLE: WebSocket connection failed: ${err.message}`);
|
|
267
|
-
error.code = 'UDP_RELAY_UNAVAILABLE';
|
|
268
|
-
this.log.error('UDP tunnel exiting due to WebSocket error');
|
|
269
|
-
process.exit(1);
|
|
270
327
|
});
|
|
271
328
|
}
|
|
272
329
|
|
|
330
|
+
// Story 11.2: an established relay connection dropped
|
|
331
|
+
_onDropped(code, reasonStr) {
|
|
332
|
+
const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
|
|
333
|
+
if (isNormalClose) {
|
|
334
|
+
this.log.debug({ code, reason: reasonStr }, 'udp.tunnel.ws.closed');
|
|
335
|
+
} else {
|
|
336
|
+
this.log.warn({ code, reason: reasonStr }, 'udp.tunnel.ws.closed');
|
|
337
|
+
}
|
|
338
|
+
this.stopPingKeepalive();
|
|
339
|
+
this.stopFlowCleanup();
|
|
340
|
+
this.closeAllFlowSockets();
|
|
341
|
+
this.frameBuffer = Buffer.alloc(0);
|
|
342
|
+
|
|
343
|
+
if (this.closing) return;
|
|
344
|
+
const verdict = classifyDrop(code, reasonStr);
|
|
345
|
+
// Story 10.9: a lease the relay closed (4000 lease_closed) may have been moved to another
|
|
346
|
+
// relay by an operator; ask the control plane once for a new assignment for the same port
|
|
347
|
+
// and continue there. If it refuses, the tunnel ends as before. lease_reconnected (another
|
|
348
|
+
// CLI took the lease) stays final.
|
|
349
|
+
if (this.reconnectEnabled && verdict.fatal && reasonStr === 'lease_closed' && this.reassign) {
|
|
350
|
+
this.log.warn({ code, reason: reasonStr }, 'udp.tunnel.lease_closed.reassigning');
|
|
351
|
+
this.reconnector.onAuthFailure().then((got) => {
|
|
352
|
+
if (got && !this.closing) { this.reconnector.run('lease_closed_reassigned'); return; }
|
|
353
|
+
this.log.info({ reason: verdict.reason }, 'UDP tunnel exiting due to WebSocket close');
|
|
354
|
+
this.exit(1);
|
|
355
|
+
}).catch(() => this.exit(1));
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (!this.reconnectEnabled || verdict.fatal) {
|
|
359
|
+
this.log.info({ reason: verdict.reason }, 'UDP tunnel exiting due to WebSocket close');
|
|
360
|
+
this.exit(1);
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
this.reconnector.run(verdict.reason);
|
|
364
|
+
}
|
|
365
|
+
|
|
273
366
|
// UDP-S1: Handle binary udpWs-v1 frames
|
|
274
367
|
handleBinaryFrame(data) {
|
|
275
368
|
// Append new data to frame buffer
|
|
@@ -364,13 +457,12 @@ export class UdpTunnel {
|
|
|
364
457
|
// Close UDP socket
|
|
365
458
|
this.closeAllFlowSockets();
|
|
366
459
|
|
|
367
|
-
// Close WebSocket connection
|
|
460
|
+
// Close WebSocket connection; Story 11.2: the close event reconnects with fresh state
|
|
368
461
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
369
462
|
this.ws.close(1003, `Protocol violation: ${error.message}`); // 1003 = Unsupported Data
|
|
463
|
+
} else if (this.ws) {
|
|
464
|
+
this.ws.terminate();
|
|
370
465
|
}
|
|
371
|
-
|
|
372
|
-
// Protocol violation - exit (UDP tunnels don't support reconnect)
|
|
373
|
-
process.exit(1);
|
|
374
466
|
}
|
|
375
467
|
|
|
376
468
|
// UDP-S1: Handle UDP_DGRAM frame (datagram from relay)
|
|
@@ -606,6 +698,7 @@ export class UdpTunnel {
|
|
|
606
698
|
|
|
607
699
|
// UDP-S1: Start PING keepalive timer
|
|
608
700
|
startPingKeepalive() {
|
|
701
|
+
this.stopPingKeepalive(); // never two timers after a reconnect
|
|
609
702
|
if (this.pingIntervalMs <= 0) {
|
|
610
703
|
this.log.debug('PING keepalive disabled (ASYX_UDP_PING_INTERVAL_MS <= 0)');
|
|
611
704
|
return;
|
|
@@ -633,6 +726,15 @@ export class UdpTunnel {
|
|
|
633
726
|
return;
|
|
634
727
|
}
|
|
635
728
|
|
|
729
|
+
// Story 11.2: nothing received from the relay for three ping intervals means the
|
|
730
|
+
// connection is dead without a close; drop it so the tunnel reconnects
|
|
731
|
+
const silentMs = Date.now() - this.lastInboundMs;
|
|
732
|
+
if (silentMs > 3 * this.pingIntervalMs) {
|
|
733
|
+
this.log.warn({ silentMs }, 'udp.ws.liveness_timeout');
|
|
734
|
+
this.ws.terminate();
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
|
|
636
738
|
try {
|
|
637
739
|
const pingFrame = encodeFrame({
|
|
638
740
|
type: FrameType.PING,
|
|
@@ -697,6 +799,9 @@ export class UdpTunnel {
|
|
|
697
799
|
}
|
|
698
800
|
|
|
699
801
|
close() {
|
|
802
|
+
// Story 11.2: a deliberate close does not reconnect
|
|
803
|
+
this.closing = true;
|
|
804
|
+
this.reconnector.stop();
|
|
700
805
|
this.stopPingKeepalive();
|
|
701
806
|
this.stopFlowCleanup();
|
|
702
807
|
this.closeAllFlowSockets();
|