asyx 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +42 -0
- package/bin/asyx.js +1 -1
- package/package.json +6 -3
- package/src/commands/account.js +80 -71
- package/src/commands/app.js +317 -151
- package/src/commands/in-use-messages.js +47 -48
- package/src/commands/mqtt-broker.js +36 -49
- package/src/commands/mqtt.js +111 -149
- package/src/commands/name.js +24 -22
- package/src/commands/reject-messages.js +123 -123
- package/src/commands/setup.js +107 -131
- package/src/commands/sts.js +45 -61
- package/src/commands/tunnel.js +853 -931
- package/src/commands/validate-target-host.js +36 -59
- package/src/lib/aws-iot-config.js +30 -0
- package/src/lib/certs.js +15 -18
- package/src/lib/csr.js +107 -182
- package/src/lib/device.js +26 -37
- package/src/lib/ids.js +1 -2
- package/src/lib/naming.js +74 -68
- package/src/lib/pairing.js +10 -11
- package/src/lib/shared-transport.js +5 -9
- package/src/main.js +63 -53
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +25 -287
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +0 -72
- package/vendor/tunnel-core/dist/control-plane/session.js +0 -20
- package/vendor/tunnel-core/dist/errors.js +0 -19
- package/vendor/tunnel-core/dist/flows/account.js +1 -6
- package/vendor/tunnel-core/dist/flows/goodbye.js +0 -4
- package/vendor/tunnel-core/dist/flows/http.js +24 -112
- package/vendor/tunnel-core/dist/flows/identity.js +11 -10
- package/vendor/tunnel-core/dist/flows/in-use.js +0 -6
- package/vendor/tunnel-core/dist/flows/reopen.js +0 -4
- package/vendor/tunnel-core/dist/flows/tcp.js +18 -84
- package/vendor/tunnel-core/dist/flows/udp.js +15 -52
- package/vendor/tunnel-core/dist/lib/fingerprint.js +38 -42
- package/vendor/tunnel-core/dist/lib/jwt-verifier.js +14 -67
- package/vendor/tunnel-core/dist/lib/logger.js +1 -9
- package/vendor/tunnel-core/dist/lib/refresh-helpers.js +1 -22
- package/vendor/tunnel-core/dist/lifecycle.js +1 -8
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +1 -53
- package/vendor/tunnel-core/dist/mqtt/events/handlers.js +10 -64
- package/vendor/tunnel-core/dist/mqtt/events/index.js +3 -36
- package/vendor/tunnel-core/dist/mqtt/events/schemas.js +0 -1
- package/vendor/tunnel-core/dist/mqtt/ingress.js +0 -60
- package/vendor/tunnel-core/dist/state/assignment.js +6 -122
- package/vendor/tunnel-core/dist/state/instance-registry.js +0 -63
- package/vendor/tunnel-core/dist/tcp-v1/framing.js +2 -64
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +64 -331
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.js +5 -14
- package/vendor/tunnel-core/dist/tunnel/reconnect.js +10 -50
- package/vendor/tunnel-core/dist/tunnel/request-sink.js +0 -16
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +32 -195
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +28 -153
- package/vendor/tunnel-core/dist/tunnel/ws-control.js +4 -39
- package/vendor/tunnel-core/dist/types.js +0 -2
- package/vendor/tunnel-core/dist/udp-v1/framing.js +2 -64
- package/vendor/tunnel-core/package.json +0 -25
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +0 -273
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +0 -79
- package/vendor/tunnel-core/dist/control-plane/session.d.ts +0 -55
- package/vendor/tunnel-core/dist/errors.d.ts +0 -49
- package/vendor/tunnel-core/dist/flows/account.d.ts +0 -24
- package/vendor/tunnel-core/dist/flows/goodbye.d.ts +0 -10
- package/vendor/tunnel-core/dist/flows/http.d.ts +0 -61
- package/vendor/tunnel-core/dist/flows/identity.d.ts +0 -23
- package/vendor/tunnel-core/dist/flows/in-use.d.ts +0 -27
- package/vendor/tunnel-core/dist/flows/reopen.d.ts +0 -9
- package/vendor/tunnel-core/dist/flows/tcp.d.ts +0 -85
- package/vendor/tunnel-core/dist/flows/udp.d.ts +0 -52
- package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +0 -2
- package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +0 -145
- package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +0 -27
- package/vendor/tunnel-core/dist/lib/logger.d.ts +0 -9
- package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +0 -16
- package/vendor/tunnel-core/dist/lifecycle.d.ts +0 -24
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +0 -56
- package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +0 -60
- package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +0 -1
- package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +0 -498
- package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +0 -63
- package/vendor/tunnel-core/dist/state/assignment.d.ts +0 -136
- package/vendor/tunnel-core/dist/state/instance-registry.d.ts +0 -88
- package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +0 -43
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +0 -140
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +0 -13
- package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +0 -76
- package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +0 -40
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +0 -92
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +0 -93
- package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +0 -22
- package/vendor/tunnel-core/dist/types.d.ts +0 -24
- package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +0 -41
|
@@ -1,13 +1,9 @@
|
|
|
1
|
-
// UDP Tunnel - udpWs-v1 protocol
|
|
2
|
-
// Handles UDP datagrams over WebSocket using udpWs-v1 framing
|
|
3
|
-
// UDP-S1: CLI – UDP entrypoint & WS connect
|
|
4
1
|
import WebSocket from 'ws';
|
|
5
2
|
import { Reconnector, reconnectEnabled, classifyDrop } from './reconnect.js';
|
|
6
3
|
import dgram from 'dgram';
|
|
7
4
|
import { FrameType, FRAME_HEADER_SIZE, encodeFrame, decodeFrame, validateFrame, UdpV1FramingError } from '../udp-v1/framing.js';
|
|
8
5
|
import { verifyAssignmentJWT, isJWKSAvailable } from '../lib/jwt-verifier.js';
|
|
9
6
|
export class UdpTunnel {
|
|
10
|
-
/** @returns {{ family: 'udp4' | 'udp6', address: string } | null} */
|
|
11
7
|
static selectDial(targetHost) {
|
|
12
8
|
const host = String(targetHost || '127.0.0.1').trim().toLowerCase();
|
|
13
9
|
if (host === 'localhost' || host === '127.0.0.1' || host.startsWith('127.')) {
|
|
@@ -18,70 +14,41 @@ export class UdpTunnel {
|
|
|
18
14
|
}
|
|
19
15
|
return null;
|
|
20
16
|
}
|
|
21
|
-
constructor({ relayUrl, jwt, deviceId, requestId, localPort = undefined,
|
|
22
|
-
targetHost, // UDP-S13: Target host (must be loopback)
|
|
23
|
-
targetPort, // UDP-S13: Target port (app's listening port)
|
|
24
|
-
leaseId, relayId, // AC5.1: Relay ID for JWT validation
|
|
25
|
-
log, coordinatorCore, coordinatorIngress,
|
|
26
|
-
// CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
|
|
27
|
-
isControlPlaneConnected = () => true, waitForControlPlane = () => Promise.resolve(), getLastMqttError = () => null, getForceReconnect = () => null, controlPlaneTimeoutMs = 60000,
|
|
28
|
-
// Story 11.2: newest assignment token for reconnects; falls back to the token
|
|
29
|
-
// the tunnel was opened with.
|
|
30
|
-
getJwt = null, reassign = null,
|
|
31
|
-
// Story 12.1 (c2): the core never exits; the owner passes exit(code). Without it, ending throws.
|
|
32
|
-
exit = /** @type {(code: number) => void} */ ((code) => { throw new Error(`tunnel ended (exit code ${code}) with no exit handler`); }), }) {
|
|
17
|
+
constructor({ relayUrl, jwt, deviceId, requestId, localPort = undefined, targetHost, targetPort, leaseId, relayId, log, coordinatorCore, coordinatorIngress, isControlPlaneConnected = () => true, waitForControlPlane = () => Promise.resolve(), getLastMqttError = () => null, getForceReconnect = () => null, controlPlaneTimeoutMs = 60000, getJwt = null, reassign = null, exit = ((code) => { throw new Error(`tunnel ended (exit code ${code}) with no exit handler`); }), }) {
|
|
33
18
|
this.relayUrl = relayUrl;
|
|
34
19
|
this.jwt = jwt;
|
|
35
20
|
this.getJwt = getJwt;
|
|
36
|
-
// Story 10.9: async () => ({ relayUrl, jwt, leaseId }) | null - a new assignment when the
|
|
37
|
-
// relay refuses the old one (the tenant was moved to another relay)
|
|
38
21
|
this.reassign = reassign;
|
|
39
22
|
this.exit = exit;
|
|
40
23
|
this.deviceId = deviceId;
|
|
41
24
|
this.requestId = requestId;
|
|
42
|
-
// UDP-S13: Use targetHost/targetPort (fallback to localPort for backward compatibility)
|
|
43
25
|
this.targetHost = targetHost || '127.0.0.1';
|
|
44
26
|
this.targetPort = targetPort || localPort;
|
|
45
27
|
const dial = UdpTunnel.selectDial(this.targetHost);
|
|
46
|
-
/** @type {'udp4' | 'udp6' | null} */
|
|
47
28
|
this.dialFamily = dial?.family || null;
|
|
48
29
|
this.dialAddress = dial?.address || null;
|
|
49
30
|
this.leaseId = leaseId;
|
|
50
|
-
this.relayId = relayId;
|
|
31
|
+
this.relayId = relayId;
|
|
51
32
|
this.log = log;
|
|
52
33
|
this.ws = null;
|
|
53
|
-
// UDP-S14: Per-flow sockets managed via flowMap (no single udpSocket)
|
|
54
|
-
// Coordinator connection
|
|
55
34
|
this.coordinatorCore = coordinatorCore;
|
|
56
35
|
this.coordinatorIngress = coordinatorIngress;
|
|
57
|
-
// CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
|
|
58
36
|
this.isControlPlaneConnected = isControlPlaneConnected;
|
|
59
37
|
this.waitForControlPlane = waitForControlPlane;
|
|
60
38
|
this.getLastMqttError = getLastMqttError;
|
|
61
39
|
this.getForceReconnect = getForceReconnect;
|
|
62
40
|
this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
this.flowMap = new Map(); // flowId -> { socket, lastSeen }
|
|
66
|
-
// Reverse mapping: socket -> flowId (for message handlers)
|
|
67
|
-
this.socketToFlowId = new WeakMap(); // socket -> flowId
|
|
68
|
-
// UDP-S1: Binary frame buffer for partial frames
|
|
41
|
+
this.flowMap = new Map();
|
|
42
|
+
this.socketToFlowId = new WeakMap();
|
|
69
43
|
this.frameBuffer = Buffer.alloc(0);
|
|
70
|
-
// UDP-S1: Protocol violation flag
|
|
71
44
|
this.protocolViolation = false;
|
|
72
|
-
|
|
73
|
-
this.
|
|
74
|
-
// UDP-S1: PING/PONG keepalive configuration (30 seconds default)
|
|
75
|
-
this.pingIntervalMs = parseInt(process.env.ASYX_UDP_PING_INTERVAL_MS || "30000", 10); // 30 seconds
|
|
45
|
+
this.idleTimeoutMs = parseInt(process.env.ASYX_UDP_IDLE_TIMEOUT_MS || "900000", 10);
|
|
46
|
+
this.pingIntervalMs = parseInt(process.env.ASYX_UDP_PING_INTERVAL_MS || "30000", 10);
|
|
76
47
|
this.pingTimer = null;
|
|
77
48
|
this.lastPongMs = Date.now();
|
|
78
|
-
|
|
79
|
-
this.flowIdleTimeoutMs = parseInt(process.env.ASYX_UDP_FLOW_IDLE_TIMEOUT_MS || "60000", 10); // 60 seconds
|
|
49
|
+
this.flowIdleTimeoutMs = parseInt(process.env.ASYX_UDP_FLOW_IDLE_TIMEOUT_MS || "60000", 10);
|
|
80
50
|
this.flowCleanupTimer = null;
|
|
81
|
-
|
|
82
|
-
// belong to one relay connection, so all flows and their sockets are discarded on a
|
|
83
|
-
// drop; a flow id reused by the relay after reconnecting can never reach an old socket.
|
|
84
|
-
this.closing = false; // set by close(): no reconnect
|
|
51
|
+
this.closing = false;
|
|
85
52
|
this.everOpened = false;
|
|
86
53
|
this.lastInboundMs = Date.now();
|
|
87
54
|
this.reconnectEnabled = reconnectEnabled();
|
|
@@ -99,7 +66,7 @@ export class UdpTunnel {
|
|
|
99
66
|
if (a.leaseId)
|
|
100
67
|
this.leaseId = a.leaseId;
|
|
101
68
|
if (a.relayId)
|
|
102
|
-
this.relayId = a.relayId;
|
|
69
|
+
this.relayId = a.relayId;
|
|
103
70
|
return true;
|
|
104
71
|
},
|
|
105
72
|
kind: 'udp',
|
|
@@ -115,41 +82,35 @@ export class UdpTunnel {
|
|
|
115
82
|
await this._attemptConnect();
|
|
116
83
|
}
|
|
117
84
|
async _attemptConnect() {
|
|
118
|
-
// Story 11.2: use the newest assignment token on every (re)connect
|
|
119
85
|
const freshJwt = this.getJwt ? this.getJwt() : null;
|
|
120
86
|
if (freshJwt)
|
|
121
87
|
this.jwt = freshJwt;
|
|
122
88
|
return new Promise((resolve, reject) => {
|
|
123
|
-
// UDP-S1: Validate relayUrl format
|
|
124
89
|
if (!this.relayUrl) {
|
|
125
|
-
const error =
|
|
90
|
+
const error = (new Error('UDP_RELAY_UNAVAILABLE: Missing relayUrl in assignment'));
|
|
126
91
|
error.code = 'UDP_RELAY_UNAVAILABLE';
|
|
127
92
|
this.log.error('udp.ws.missing_relayUrl', { relayUrl: this.relayUrl });
|
|
128
93
|
reject(error);
|
|
129
94
|
return;
|
|
130
95
|
}
|
|
131
|
-
// UDP-S1: Parse relayUrl and ensure it's for /udp endpoint
|
|
132
96
|
let wsUrl = this.relayUrl;
|
|
133
97
|
try {
|
|
134
98
|
const urlObj = new URL(this.relayUrl);
|
|
135
|
-
// Ensure path is /udp
|
|
136
99
|
if (!urlObj.pathname.includes('/udp')) {
|
|
137
100
|
this.log.warn('udp.ws.path_mismatch', {
|
|
138
101
|
relayUrl: this.relayUrl,
|
|
139
102
|
pathname: urlObj.pathname,
|
|
140
103
|
note: 'Expected /udp path, adjusting'
|
|
141
104
|
});
|
|
142
|
-
// Replace path with /udp
|
|
143
105
|
urlObj.pathname = '/udp';
|
|
144
106
|
wsUrl = urlObj.toString();
|
|
145
107
|
}
|
|
146
|
-
// Add leaseId and token query parameters if not present
|
|
147
108
|
if (this.leaseId && !urlObj.searchParams.has('leaseId')) {
|
|
148
109
|
urlObj.searchParams.set('leaseId', this.leaseId);
|
|
149
110
|
}
|
|
150
111
|
urlObj.searchParams.delete('token');
|
|
151
112
|
if (!this.jwt) {
|
|
152
|
-
const error =
|
|
113
|
+
const error = (new Error('UDP_RELAY_UNAVAILABLE: Missing JWT for UDP tunnel'));
|
|
153
114
|
error.code = 'UDP_RELAY_UNAVAILABLE';
|
|
154
115
|
reject(error);
|
|
155
116
|
return;
|
|
@@ -157,7 +118,7 @@ export class UdpTunnel {
|
|
|
157
118
|
wsUrl = urlObj.toString();
|
|
158
119
|
}
|
|
159
120
|
catch (urlError) {
|
|
160
|
-
const error =
|
|
121
|
+
const error = (new Error(`UDP_RELAY_UNAVAILABLE: Invalid relayUrl format: ${urlError.message}`));
|
|
161
122
|
error.code = 'UDP_RELAY_UNAVAILABLE';
|
|
162
123
|
this.log.error('udp.ws.invalid_relayUrl', {
|
|
163
124
|
relayUrl: this.relayUrl,
|
|
@@ -166,20 +127,12 @@ export class UdpTunnel {
|
|
|
166
127
|
reject(error);
|
|
167
128
|
return;
|
|
168
129
|
}
|
|
169
|
-
// UDP-S1: Validate JWT (AC1.4/AC5.1: signature verification and claim validation)
|
|
170
|
-
// AC1.4/AC5.1: Use JWKS verifier - fail fast if JWKS unavailable (same as TCP/HTTP)
|
|
171
|
-
// Enforces "no JWKS → no tunnel" policy
|
|
172
|
-
// Note: JWT verification is async, so we need to handle it inside an async IIFE
|
|
173
130
|
(async () => {
|
|
174
131
|
try {
|
|
175
|
-
// Story 11.2: a token already verified for this tunnel is not verified again on
|
|
176
|
-
// reconnect, so a reconnect does not depend on reaching the JWKS endpoint
|
|
177
132
|
if (this.verifiedJwt && this.verifiedJwt === this.jwt) {
|
|
178
133
|
this._setupWebSocketConnection(wsUrl, resolve, reject);
|
|
179
134
|
return;
|
|
180
135
|
}
|
|
181
|
-
// AC1.4/AC5.1: Verify JWT signature and claims using JWKS
|
|
182
|
-
// verifyAssignmentJWT will initialize JWKS on first call and fail fast if unavailable
|
|
183
136
|
const { verifyAssignmentJWT } = await import('../lib/jwt-verifier.js');
|
|
184
137
|
const payload = await verifyAssignmentJWT(this.jwt, {
|
|
185
138
|
relayId: this.relayId,
|
|
@@ -187,7 +140,6 @@ export class UdpTunnel {
|
|
|
187
140
|
tunnelMode: 'udpWs-v1',
|
|
188
141
|
leaseId: this.leaseId
|
|
189
142
|
});
|
|
190
|
-
// Verification successful - payload is already validated (signature + all claims)
|
|
191
143
|
this.log.debug('udp.jwt.verified', {
|
|
192
144
|
relayId: payload.relayId,
|
|
193
145
|
leaseId: payload.leaseId,
|
|
@@ -195,13 +147,10 @@ export class UdpTunnel {
|
|
|
195
147
|
tunnelMode: payload.tunnelMode
|
|
196
148
|
});
|
|
197
149
|
this.verifiedJwt = this.jwt;
|
|
198
|
-
// Continue with WebSocket connection setup after JWT verification
|
|
199
150
|
this._setupWebSocketConnection(wsUrl, resolve, reject);
|
|
200
151
|
}
|
|
201
152
|
catch (jwtError) {
|
|
202
|
-
|
|
203
|
-
// This includes: JWKS unavailable, signature invalid, claims mismatch, expired, etc.
|
|
204
|
-
const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`));
|
|
153
|
+
const error = (new Error(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`));
|
|
205
154
|
error.code = 'UDP_RELAY_UNAVAILABLE';
|
|
206
155
|
error.cause = jwtError;
|
|
207
156
|
this.log.error('udp.jwt.verification_failed', {
|
|
@@ -216,21 +165,19 @@ export class UdpTunnel {
|
|
|
216
165
|
});
|
|
217
166
|
}
|
|
218
167
|
_setupWebSocketConnection(wsUrl, resolve, reject) {
|
|
219
|
-
// Clean up previous WebSocket if exists
|
|
220
168
|
if (this.ws) {
|
|
221
169
|
const old = this.ws;
|
|
222
170
|
old.removeAllListeners();
|
|
223
|
-
old.on('error', () => { });
|
|
171
|
+
old.on('error', () => { });
|
|
224
172
|
this.ws = null;
|
|
225
173
|
}
|
|
226
|
-
// UDP-S1: Connect to relay with TLS (rejectUnauthorized: true by default)
|
|
227
174
|
const wsOptions = {
|
|
228
175
|
headers: {
|
|
229
176
|
'Authorization': `Bearer ${this.jwt}`,
|
|
230
177
|
'X-Asyx-DeviceId': this.deviceId,
|
|
231
178
|
'X-Asyx-RequestId': this.requestId
|
|
232
179
|
},
|
|
233
|
-
rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1',
|
|
180
|
+
rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1',
|
|
234
181
|
};
|
|
235
182
|
const ws = new WebSocket(wsUrl, wsOptions);
|
|
236
183
|
this.ws = ws;
|
|
@@ -243,24 +190,18 @@ export class UdpTunnel {
|
|
|
243
190
|
this.frameBuffer = Buffer.alloc(0);
|
|
244
191
|
this.lastInboundMs = Date.now();
|
|
245
192
|
this.log.info({ leaseId: this.leaseId, targetHost: this.targetHost, targetPort: this.targetPort }, 'udp.tunnel.ws.open');
|
|
246
|
-
// UDP-S1: Start PING keepalive timer
|
|
247
193
|
this.startPingKeepalive();
|
|
248
|
-
// UDP-S1: Start flow cleanup timer
|
|
249
194
|
this.startFlowCleanup();
|
|
250
|
-
// UDP-S14: Per-flow sockets are created on-demand in handleUdpDatagram
|
|
251
|
-
// No global socket initialization needed - each flowId gets its own socket
|
|
252
195
|
resolve();
|
|
253
196
|
});
|
|
254
197
|
ws.on('message', (data, isBinary) => {
|
|
255
198
|
this.lastInboundMs = Date.now();
|
|
256
|
-
// UDP-S1: All udpWs-v1 frames are binary
|
|
257
199
|
const isActuallyBinary = isBinary || Buffer.isBuffer(data);
|
|
258
200
|
if (isActuallyBinary) {
|
|
259
201
|
this.handleBinaryFrame(data);
|
|
260
202
|
return;
|
|
261
203
|
}
|
|
262
|
-
|
|
263
|
-
this.log.warn({ size: /** @type {any} */ (data).length, isBinary }, 'udp.text_frame_rejected', {
|
|
204
|
+
this.log.warn({ size: (data).length, isBinary }, 'udp.text_frame_rejected', {
|
|
264
205
|
note: 'UDP tunnel only accepts binary udpWs-v1 frames'
|
|
265
206
|
});
|
|
266
207
|
this.handleProtocolViolation(new UdpV1FramingError('Text frame received in UDP tunnel', 'INVALID_FRAME_TYPE'));
|
|
@@ -268,15 +209,13 @@ export class UdpTunnel {
|
|
|
268
209
|
ws.on('close', (code, reason) => {
|
|
269
210
|
const reasonStr = reason?.toString() || '';
|
|
270
211
|
if (!opened) {
|
|
271
|
-
|
|
272
|
-
const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`UDP_RELAY_UNAVAILABLE: WebSocket connection failed: ${failure?.message || `closed before open (code ${code})`}`));
|
|
212
|
+
const error = (new Error(`UDP_RELAY_UNAVAILABLE: WebSocket connection failed: ${failure?.message || `closed before open (code ${code})`}`));
|
|
273
213
|
error.code = 'UDP_RELAY_UNAVAILABLE';
|
|
274
214
|
error.closeCode = code;
|
|
275
215
|
error.cause = failure;
|
|
276
216
|
this.stopPingKeepalive();
|
|
277
217
|
this.stopFlowCleanup();
|
|
278
218
|
if (!this.everOpened) {
|
|
279
|
-
// First connect: unchanged behaviour, the CLI ends
|
|
280
219
|
this.log.error('UDP tunnel exiting due to WebSocket error');
|
|
281
220
|
this.exit(1);
|
|
282
221
|
}
|
|
@@ -285,13 +224,11 @@ export class UdpTunnel {
|
|
|
285
224
|
}
|
|
286
225
|
this._onDropped(code, reasonStr);
|
|
287
226
|
});
|
|
288
|
-
ws.on('error', (
|
|
289
|
-
// A 'close' event always follows; the decision is made there
|
|
227
|
+
ws.on('error', (err) => {
|
|
290
228
|
failure = err;
|
|
291
229
|
this.log.error({ err: err.message, code: err.code }, 'udp.tunnel.ws.error');
|
|
292
230
|
});
|
|
293
231
|
}
|
|
294
|
-
// Story 11.2: an established relay connection dropped
|
|
295
232
|
_onDropped(code, reasonStr) {
|
|
296
233
|
const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
|
|
297
234
|
if (isNormalClose) {
|
|
@@ -307,10 +244,6 @@ export class UdpTunnel {
|
|
|
307
244
|
if (this.closing)
|
|
308
245
|
return;
|
|
309
246
|
const verdict = classifyDrop(code, reasonStr);
|
|
310
|
-
// Story 10.9: a lease the relay closed (4000 lease_closed) may have been moved to another
|
|
311
|
-
// relay by an operator; ask the control plane once for a new assignment for the same port
|
|
312
|
-
// and continue there. If it refuses, the tunnel ends as before. lease_reconnected (another
|
|
313
|
-
// CLI took the lease) stays final.
|
|
314
247
|
if (this.reconnectEnabled && verdict.fatal && reasonStr === 'lease_closed' && this.reassign) {
|
|
315
248
|
this.log.warn({ code, reason: reasonStr }, 'udp.tunnel.lease_closed.reassigning');
|
|
316
249
|
this.reconnector.onAuthFailure().then((got) => {
|
|
@@ -330,17 +263,12 @@ export class UdpTunnel {
|
|
|
330
263
|
}
|
|
331
264
|
this.reconnector.run(verdict.reason);
|
|
332
265
|
}
|
|
333
|
-
// UDP-S1: Handle binary udpWs-v1 frames
|
|
334
266
|
handleBinaryFrame(data) {
|
|
335
|
-
// Append new data to frame buffer
|
|
336
267
|
this.frameBuffer = Buffer.concat([this.frameBuffer, Buffer.from(data)]);
|
|
337
|
-
// Process complete frames from buffer
|
|
338
268
|
while (this.frameBuffer.length >= FRAME_HEADER_SIZE) {
|
|
339
269
|
try {
|
|
340
270
|
const frame = decodeFrame(this.frameBuffer, 0);
|
|
341
|
-
// Remove consumed bytes from buffer
|
|
342
271
|
this.frameBuffer = this.frameBuffer.subarray(frame.consumed);
|
|
343
|
-
// Validate frame
|
|
344
272
|
try {
|
|
345
273
|
validateFrame(frame);
|
|
346
274
|
}
|
|
@@ -358,16 +286,13 @@ export class UdpTunnel {
|
|
|
358
286
|
}
|
|
359
287
|
throw err;
|
|
360
288
|
}
|
|
361
|
-
// Route frame by type
|
|
362
289
|
this.routeFrame(frame);
|
|
363
290
|
}
|
|
364
291
|
catch (err) {
|
|
365
292
|
if (err instanceof UdpV1FramingError) {
|
|
366
|
-
// Incomplete frame - wait for more data
|
|
367
293
|
if (err.code === 'INCOMPLETE_FRAME') {
|
|
368
|
-
break;
|
|
294
|
+
break;
|
|
369
295
|
}
|
|
370
|
-
// Other framing errors are protocol violations
|
|
371
296
|
this.log.error({
|
|
372
297
|
error: err.message,
|
|
373
298
|
code: err.code
|
|
@@ -375,14 +300,12 @@ export class UdpTunnel {
|
|
|
375
300
|
this.handleProtocolViolation(err);
|
|
376
301
|
return;
|
|
377
302
|
}
|
|
378
|
-
// Unexpected error
|
|
379
303
|
this.log.error({ error: err.message }, 'udp.frame_decode_error');
|
|
380
304
|
this.handleProtocolViolation(new UdpV1FramingError(`Frame decode error: ${err.message}`, 'DECODE_ERROR'));
|
|
381
305
|
return;
|
|
382
306
|
}
|
|
383
307
|
}
|
|
384
308
|
}
|
|
385
|
-
// UDP-S1: Route frame by type
|
|
386
309
|
routeFrame(frame) {
|
|
387
310
|
switch (frame.type) {
|
|
388
311
|
case FrameType.UDP_DGRAM:
|
|
@@ -398,38 +321,30 @@ export class UdpTunnel {
|
|
|
398
321
|
this.handlePong(frame);
|
|
399
322
|
break;
|
|
400
323
|
default:
|
|
401
|
-
// Unknown frame type - protocol violation
|
|
402
324
|
this.log.error({ frameType: frame.type }, 'udp.unknown_frame_type');
|
|
403
325
|
this.handleProtocolViolation(new UdpV1FramingError(`Unknown frame type: ${frame.type}`, 'UNKNOWN_FRAME_TYPE'));
|
|
404
326
|
}
|
|
405
327
|
}
|
|
406
|
-
// UDP-S1: Handle protocol violation - close tunnel
|
|
407
328
|
handleProtocolViolation(error) {
|
|
408
329
|
if (this.protocolViolation) {
|
|
409
|
-
return;
|
|
330
|
+
return;
|
|
410
331
|
}
|
|
411
332
|
this.protocolViolation = true;
|
|
412
333
|
this.log.error({
|
|
413
334
|
error: error.message,
|
|
414
335
|
code: error.code
|
|
415
336
|
}, 'udp.protocol_violation_closing_tunnel');
|
|
416
|
-
// Close UDP socket
|
|
417
337
|
this.closeAllFlowSockets();
|
|
418
|
-
// Close WebSocket connection; Story 11.2: the close event reconnects with fresh state
|
|
419
338
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
420
|
-
this.ws.close(1003, `Protocol violation: ${error.message}`);
|
|
339
|
+
this.ws.close(1003, `Protocol violation: ${error.message}`);
|
|
421
340
|
}
|
|
422
341
|
else if (this.ws) {
|
|
423
342
|
this.ws.terminate();
|
|
424
343
|
}
|
|
425
344
|
}
|
|
426
|
-
// UDP-S1: Handle UDP_DGRAM frame (datagram from relay)
|
|
427
|
-
// UDP-S13: Forward to targetHost:targetPort (app's listening port)
|
|
428
|
-
// UDP-S14: Use per-flow socket for correct return path routing
|
|
429
345
|
handleUdpDatagram(frame) {
|
|
430
346
|
const flowId = frame.flowId;
|
|
431
347
|
const now = Date.now();
|
|
432
|
-
// UDP-S14: Lookup or create per-flow socket
|
|
433
348
|
let flowState = this.flowMap.get(flowId);
|
|
434
349
|
let socket = flowState?.socket;
|
|
435
350
|
if (!socket) {
|
|
@@ -441,14 +356,10 @@ export class UdpTunnel {
|
|
|
441
356
|
}, 'udp.flow.dial.refused');
|
|
442
357
|
return;
|
|
443
358
|
}
|
|
444
|
-
// Create new per-flow socket for this flowId
|
|
445
359
|
socket = dgram.createSocket(this.dialFamily);
|
|
446
|
-
// UDP-S14: Store reverse mapping (socket -> flowId) for message handlers
|
|
447
360
|
this.socketToFlowId.set(socket, flowId);
|
|
448
|
-
// UDP-S14: Store socket in flowMap immediately (before bind completes)
|
|
449
361
|
flowState = { socket, lastSeen: now, connected: false, pendingPayload: frame.payload };
|
|
450
362
|
this.flowMap.set(flowId, flowState);
|
|
451
|
-
// Bind the ephemeral port on loopback, then connect, then listen.
|
|
452
363
|
socket.bind(0, this.dialAddress, () => {
|
|
453
364
|
const address = socket.address();
|
|
454
365
|
this.log.debug({
|
|
@@ -466,7 +377,6 @@ export class UdpTunnel {
|
|
|
466
377
|
}, 'udp.flow.socket.connected');
|
|
467
378
|
flowState.connected = true;
|
|
468
379
|
socket.on('message', (msg, rinfo) => {
|
|
469
|
-
// We know the flowId from the socket itself
|
|
470
380
|
const socketFlowId = this.socketToFlowId.get(socket);
|
|
471
381
|
if (socketFlowId === flowId) {
|
|
472
382
|
this.handleLocalDatagram(msg, rinfo, flowId);
|
|
@@ -485,7 +395,6 @@ export class UdpTunnel {
|
|
|
485
395
|
error: err.message,
|
|
486
396
|
code: err.code
|
|
487
397
|
}, 'udp.flow.socket.error');
|
|
488
|
-
// UDP-S13: If target app isn't listening, log clearly
|
|
489
398
|
if (err.code === 'ECONNREFUSED' || err.code === 'EHOSTUNREACH') {
|
|
490
399
|
this.log.warn({
|
|
491
400
|
flowId,
|
|
@@ -503,20 +412,15 @@ export class UdpTunnel {
|
|
|
503
412
|
});
|
|
504
413
|
}
|
|
505
414
|
else {
|
|
506
|
-
// Update lastSeen for existing flow
|
|
507
415
|
flowState.lastSeen = now;
|
|
508
|
-
// UDP-S13: Send payload using existing socket
|
|
509
|
-
// If socket is not yet connected, queue the payload
|
|
510
416
|
if (flowState.connected) {
|
|
511
417
|
this.sendDatagramToApp(socket, flowId, frame.payload);
|
|
512
418
|
}
|
|
513
419
|
else {
|
|
514
|
-
// Queue payload until socket is connected
|
|
515
420
|
flowState.pendingPayload = frame.payload;
|
|
516
421
|
}
|
|
517
422
|
}
|
|
518
423
|
}
|
|
519
|
-
// UDP-S13: Helper to send datagram to app on flow-specific socket
|
|
520
424
|
sendDatagramToApp(socket, flowId, payload) {
|
|
521
425
|
if (!socket || this.protocolViolation) {
|
|
522
426
|
return;
|
|
@@ -532,7 +436,6 @@ export class UdpTunnel {
|
|
|
532
436
|
}, 'udp.datagram.send_error');
|
|
533
437
|
}
|
|
534
438
|
else {
|
|
535
|
-
// UDP-S14: Log with flowId for tracking
|
|
536
439
|
this.log.debug({
|
|
537
440
|
flowId,
|
|
538
441
|
size: payload.length,
|
|
@@ -542,22 +445,17 @@ export class UdpTunnel {
|
|
|
542
445
|
}
|
|
543
446
|
});
|
|
544
447
|
}
|
|
545
|
-
// UDP-S1: Handle UDP_CLOSE frame (flow shutdown hint)
|
|
546
|
-
// UDP-S14: Close per-flow socket
|
|
547
448
|
handleUdpClose(frame) {
|
|
548
449
|
const flowId = frame.flowId;
|
|
549
450
|
this.log.debug({ flowId }, 'udp.flow.close');
|
|
550
|
-
// UDP-S14: Close and remove per-flow socket
|
|
551
451
|
const flowState = this.flowMap.get(flowId);
|
|
552
452
|
if (flowState?.socket) {
|
|
553
453
|
flowState.socket.close();
|
|
554
454
|
this.socketToFlowId.delete(flowState.socket);
|
|
555
455
|
this.log.debug({ flowId }, 'udp.flow.socket.closed');
|
|
556
456
|
}
|
|
557
|
-
// Remove flow from mapping
|
|
558
457
|
this.flowMap.delete(flowId);
|
|
559
458
|
}
|
|
560
|
-
// UDP-S1: Handle PING frame (respond with PONG)
|
|
561
459
|
handlePing(frame) {
|
|
562
460
|
this.lastPongMs = Date.now();
|
|
563
461
|
if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
|
|
@@ -565,7 +463,7 @@ export class UdpTunnel {
|
|
|
565
463
|
const pongFrame = encodeFrame({
|
|
566
464
|
type: FrameType.PONG,
|
|
567
465
|
flowId: 0,
|
|
568
|
-
payload: frame.payload
|
|
466
|
+
payload: frame.payload
|
|
569
467
|
});
|
|
570
468
|
this.ws.send(pongFrame, { binary: true });
|
|
571
469
|
}
|
|
@@ -574,38 +472,30 @@ export class UdpTunnel {
|
|
|
574
472
|
}
|
|
575
473
|
}
|
|
576
474
|
}
|
|
577
|
-
// UDP-S1: Handle PONG frame (update lastPongMs)
|
|
578
475
|
handlePong(frame) {
|
|
579
476
|
this.lastPongMs = Date.now();
|
|
580
477
|
}
|
|
581
|
-
// UDP-S13: Handle incoming datagram from app (via per-flow socket)
|
|
582
|
-
// Forward app responses to relay via WebSocket
|
|
583
|
-
// UDP-S14: flowId is known from the socket itself (per-flow socket architecture)
|
|
584
478
|
handleLocalDatagram(msg, rinfo, flowId) {
|
|
585
|
-
// UDP-S14: flowId is passed as parameter (we know it from the socket)
|
|
586
479
|
if (!flowId) {
|
|
587
480
|
this.log.error({
|
|
588
481
|
note: 'flowId not provided to handleLocalDatagram - this should not happen'
|
|
589
482
|
}, 'udp.datagram.flow_missing');
|
|
590
|
-
return;
|
|
483
|
+
return;
|
|
591
484
|
}
|
|
592
|
-
// UDP-S14: Verify flowId is still active
|
|
593
485
|
if (!this.flowMap.has(flowId)) {
|
|
594
486
|
this.log.warn({
|
|
595
487
|
flowId,
|
|
596
488
|
note: 'Received datagram on closed/evicted flow'
|
|
597
489
|
}, 'udp.datagram.flow_closed');
|
|
598
|
-
return;
|
|
490
|
+
return;
|
|
599
491
|
}
|
|
600
|
-
// UDP-S1: Validate datagram size (max 64 KiB)
|
|
601
492
|
if (msg.length > 65536) {
|
|
602
493
|
this.log.error({
|
|
603
494
|
size: msg.length,
|
|
604
495
|
maxSize: 65536
|
|
605
496
|
}, 'udp.datagram.oversize');
|
|
606
|
-
return;
|
|
497
|
+
return;
|
|
607
498
|
}
|
|
608
|
-
// UDP-S1: Encode as UDP_DGRAM frame and send over WS
|
|
609
499
|
if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
|
|
610
500
|
try {
|
|
611
501
|
const frame = encodeFrame({
|
|
@@ -614,8 +504,6 @@ export class UdpTunnel {
|
|
|
614
504
|
payload: msg
|
|
615
505
|
});
|
|
616
506
|
this.ws.send(frame, { binary: true });
|
|
617
|
-
// UDP-S14: Log with flowId for tracking return path
|
|
618
|
-
// UDP-S14: Log with flowId (known from per-flow socket)
|
|
619
507
|
this.log.debug({
|
|
620
508
|
flowId,
|
|
621
509
|
size: msg.length,
|
|
@@ -633,9 +521,8 @@ export class UdpTunnel {
|
|
|
633
521
|
}
|
|
634
522
|
}
|
|
635
523
|
}
|
|
636
|
-
// UDP-S1: Start PING keepalive timer
|
|
637
524
|
startPingKeepalive() {
|
|
638
|
-
this.stopPingKeepalive();
|
|
525
|
+
this.stopPingKeepalive();
|
|
639
526
|
if (this.pingIntervalMs <= 0) {
|
|
640
527
|
this.log.debug('PING keepalive disabled (ASYX_UDP_PING_INTERVAL_MS <= 0)');
|
|
641
528
|
return;
|
|
@@ -645,7 +532,6 @@ export class UdpTunnel {
|
|
|
645
532
|
}, this.pingIntervalMs);
|
|
646
533
|
this.log.debug({ interval: this.pingIntervalMs }, 'udp.ping.keepalive.started');
|
|
647
534
|
}
|
|
648
|
-
// UDP-S1: Stop PING keepalive timer
|
|
649
535
|
stopPingKeepalive() {
|
|
650
536
|
if (this.pingTimer) {
|
|
651
537
|
clearInterval(this.pingTimer);
|
|
@@ -653,13 +539,10 @@ export class UdpTunnel {
|
|
|
653
539
|
this.log.debug('udp.ping.keepalive.stopped');
|
|
654
540
|
}
|
|
655
541
|
}
|
|
656
|
-
// UDP-S1: Send PING frame
|
|
657
542
|
sendPing() {
|
|
658
543
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN || this.protocolViolation) {
|
|
659
544
|
return;
|
|
660
545
|
}
|
|
661
|
-
// Story 11.2: nothing received from the relay for three ping intervals means the
|
|
662
|
-
// connection is dead without a close; drop it so the tunnel reconnects
|
|
663
546
|
const silentMs = Date.now() - this.lastInboundMs;
|
|
664
547
|
if (silentMs > 3 * this.pingIntervalMs) {
|
|
665
548
|
this.log.warn({ silentMs }, 'udp.ws.liveness_timeout');
|
|
@@ -670,7 +553,7 @@ export class UdpTunnel {
|
|
|
670
553
|
const pingFrame = encodeFrame({
|
|
671
554
|
type: FrameType.PING,
|
|
672
555
|
flowId: 0,
|
|
673
|
-
payload: Buffer.from(Date.now().toString())
|
|
556
|
+
payload: Buffer.from(Date.now().toString())
|
|
674
557
|
});
|
|
675
558
|
this.ws.send(pingFrame, { binary: true });
|
|
676
559
|
}
|
|
@@ -678,12 +561,10 @@ export class UdpTunnel {
|
|
|
678
561
|
this.log.error({ error: err.message }, 'udp.ping.encode_error');
|
|
679
562
|
}
|
|
680
563
|
}
|
|
681
|
-
// UDP-S1: Start flow cleanup timer (evict idle flows)
|
|
682
564
|
startFlowCleanup() {
|
|
683
565
|
if (this.flowIdleTimeoutMs <= 0) {
|
|
684
566
|
return;
|
|
685
567
|
}
|
|
686
|
-
// Run cleanup every 30 seconds
|
|
687
568
|
this.flowCleanupTimer = setInterval(() => {
|
|
688
569
|
const now = Date.now();
|
|
689
570
|
const expiredFlows = [];
|
|
@@ -693,7 +574,6 @@ export class UdpTunnel {
|
|
|
693
574
|
}
|
|
694
575
|
}
|
|
695
576
|
for (const flowId of expiredFlows) {
|
|
696
|
-
// UDP-S14: Close per-flow socket before removing
|
|
697
577
|
const flowState = this.flowMap.get(flowId);
|
|
698
578
|
if (flowState?.socket) {
|
|
699
579
|
flowState.socket.close();
|
|
@@ -703,16 +583,14 @@ export class UdpTunnel {
|
|
|
703
583
|
this.flowMap.delete(flowId);
|
|
704
584
|
this.log.debug({ flowId }, 'udp.flow.idle_evicted');
|
|
705
585
|
}
|
|
706
|
-
}, 30000);
|
|
586
|
+
}, 30000);
|
|
707
587
|
}
|
|
708
|
-
// UDP-S1: Stop flow cleanup timer
|
|
709
588
|
stopFlowCleanup() {
|
|
710
589
|
if (this.flowCleanupTimer) {
|
|
711
590
|
clearInterval(this.flowCleanupTimer);
|
|
712
591
|
this.flowCleanupTimer = null;
|
|
713
592
|
}
|
|
714
593
|
}
|
|
715
|
-
// UDP-S14: Close all per-flow sockets
|
|
716
594
|
closeAllFlowSockets() {
|
|
717
595
|
for (const [flowId, flowState] of this.flowMap.entries()) {
|
|
718
596
|
if (flowState?.socket) {
|
|
@@ -724,7 +602,6 @@ export class UdpTunnel {
|
|
|
724
602
|
this.flowMap.clear();
|
|
725
603
|
}
|
|
726
604
|
close() {
|
|
727
|
-
// Story 11.2: a deliberate close does not reconnect
|
|
728
605
|
this.closing = true;
|
|
729
606
|
this.reconnector.stop();
|
|
730
607
|
this.stopPingKeepalive();
|
|
@@ -734,8 +611,6 @@ export class UdpTunnel {
|
|
|
734
611
|
this.ws.close();
|
|
735
612
|
}
|
|
736
613
|
}
|
|
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
614
|
async reopenAfterLeaseClosed() {
|
|
740
615
|
if (this.closing || !this.reassign)
|
|
741
616
|
return false;
|