asyx 0.5.9 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -9
- package/SECURITY.md +5 -3
- package/package.json +13 -23
- package/src/commands/name.js +23 -0
- package/src/commands/reject-messages.js +54 -0
- package/src/commands/setup.js +98 -102
- package/src/commands/tunnel.js +279 -2425
- package/src/lib/naming.js +81 -0
- package/src/main.js +9 -1
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +260 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +1088 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +79 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +138 -0
- package/vendor/tunnel-core/dist/control-plane/session.d.ts +50 -0
- package/vendor/tunnel-core/dist/control-plane/session.js +115 -0
- package/vendor/tunnel-core/dist/errors.d.ts +49 -0
- package/vendor/tunnel-core/dist/errors.js +53 -0
- package/vendor/tunnel-core/dist/flows/http.d.ts +50 -0
- package/vendor/tunnel-core/dist/flows/http.js +585 -0
- package/vendor/tunnel-core/dist/flows/tcp.d.ts +60 -0
- package/vendor/tunnel-core/dist/flows/tcp.js +546 -0
- package/vendor/tunnel-core/dist/flows/udp.d.ts +41 -0
- package/vendor/tunnel-core/dist/flows/udp.js +376 -0
- package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +2 -0
- package/vendor/tunnel-core/dist/lib/adapt-logger.js +6 -0
- package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +13 -0
- package/vendor/tunnel-core/dist/lib/fingerprint.js +95 -0
- package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +27 -0
- package/vendor/tunnel-core/dist/lib/jwt-verifier.js +230 -0
- package/vendor/tunnel-core/dist/lib/logger.d.ts +9 -0
- package/vendor/tunnel-core/dist/lib/logger.js +58 -0
- package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +16 -0
- package/vendor/tunnel-core/dist/lib/refresh-helpers.js +66 -0
- package/vendor/tunnel-core/dist/lifecycle.d.ts +24 -0
- package/vendor/tunnel-core/dist/lifecycle.js +29 -0
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +56 -0
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +227 -0
- package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +58 -0
- package/vendor/tunnel-core/dist/mqtt/events/handlers.js +250 -0
- package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +1 -0
- package/vendor/tunnel-core/dist/mqtt/events/index.js +191 -0
- package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +498 -0
- package/vendor/tunnel-core/dist/mqtt/events/schemas.js +51 -0
- package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +63 -0
- package/vendor/tunnel-core/dist/mqtt/ingress.js +170 -0
- package/vendor/tunnel-core/dist/state/assignment.d.ts +122 -0
- package/vendor/tunnel-core/dist/state/assignment.js +322 -0
- package/vendor/tunnel-core/dist/state/instance-registry.d.ts +88 -0
- package/{src → vendor/tunnel-core/dist}/state/instance-registry.js +38 -53
- package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +43 -0
- package/vendor/tunnel-core/dist/tcp-v1/framing.js +157 -0
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +137 -0
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +1591 -0
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +13 -0
- package/{src → vendor/tunnel-core/dist}/tunnel/httpws-constants.js +5 -7
- package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +76 -0
- package/vendor/tunnel-core/dist/tunnel/reconnect.js +183 -0
- package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +40 -0
- package/vendor/tunnel-core/dist/tunnel/request-sink.js +39 -0
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +89 -0
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +838 -0
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +90 -0
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +737 -0
- package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +22 -0
- package/vendor/tunnel-core/dist/tunnel/ws-control.js +124 -0
- package/vendor/tunnel-core/dist/types.d.ts +24 -0
- package/vendor/tunnel-core/dist/types.js +2 -0
- package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +41 -0
- package/vendor/tunnel-core/dist/udp-v1/framing.js +158 -0
- package/vendor/tunnel-core/package.json +34 -0
- package/src/control-plane/MqttControlPlaneClient.js +0 -1196
- package/src/control-plane/MqttControlPlaneTransport.js +0 -150
- package/src/lib/fingerprint.js +0 -115
- package/src/lib/jwt-verifier.js +0 -260
- package/src/lib/logger.js +0 -62
- package/src/mqtt/awaiter-map.js +0 -247
- package/src/mqtt/events/handlers.js +0 -300
- package/src/mqtt/events/index.js +0 -222
- package/src/mqtt/events/schemas.js +0 -58
- package/src/mqtt/ingress.js +0 -182
- package/src/state/assignment.js +0 -333
- package/src/tcp-v1/framing.js +0 -203
- package/src/tunnel/http-tunnel.js +0 -1738
- package/src/tunnel/reconnect.js +0 -182
- package/src/tunnel/tcp-tunnel.js +0 -944
- package/src/tunnel/udp-tunnel.js +0 -813
- package/src/tunnel/ws-control.js +0 -135
- package/src/udp-v1/framing.js +0 -203
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
// Story 12.1 (step 2b, sub-step 3; TypeScript in r3): the TCP tunnel flow, moved from tcpTunnel() and
|
|
2
|
+
// connectToRelayTcp() in clients/asyx/src/commands/tunnel.js. Behaviour is unchanged; what the CLI
|
|
3
|
+
// printed or exited on is now an event or a typed error, and the CLI maps both to its old wording:
|
|
4
|
+
// 'control-connected' / 'control-fatal' (TCP has never reported a lost control-plane connection)
|
|
5
|
+
// 'assigned' { tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed }
|
|
6
|
+
// when the coordinator's assignment arrives (the CLI prints where the server is reachable)
|
|
7
|
+
// state events: 'opening', 'live', 'renewed', and a final 'closed' { error } when a reply ends
|
|
8
|
+
// the tunnel after it opened (SetupRequiredError, RefusedError, InternalError).
|
|
9
|
+
// open() rejects with: ConnectionError control_plane_connect_failed | assignment_failed |
|
|
10
|
+
// tunnel_connect_failed, or RefusedError tcp_port_out_of_block | tcp_port_already_in_use |
|
|
11
|
+
// tcp_port_block_exhausted_for_tenant | tcp_port_capacity_exhausted | tenant_tcp_lease_limit_reached
|
|
12
|
+
// (details carry what the CLI prints: requestedPort, blockStart, blockEnd, relayId).
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
import { LifecycleEmitter } from '../lifecycle.js';
|
|
15
|
+
import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
|
|
16
|
+
import { createControlPlaneSession } from '../control-plane/session.js';
|
|
17
|
+
import { publishRefreshRequestWithErrorHandling } from '../lib/refresh-helpers.js';
|
|
18
|
+
import { adaptLogger } from '../lib/adapt-logger.js';
|
|
19
|
+
export class TcpTunnelHandle extends LifecycleEmitter {
|
|
20
|
+
opts;
|
|
21
|
+
tunnel = null;
|
|
22
|
+
mqttClient = null;
|
|
23
|
+
core = null;
|
|
24
|
+
assignment = null;
|
|
25
|
+
constructor(o) {
|
|
26
|
+
super();
|
|
27
|
+
this.opts = { serviceName: null, kind: null, requestedExternalPort: null, ...o };
|
|
28
|
+
}
|
|
29
|
+
/** Connect the control plane, get a lease and open the data plane; rejects with a typed error. */
|
|
30
|
+
async open() {
|
|
31
|
+
const { credentials, localPort, target, serviceName, kind, requestedExternalPort, logger } = this.opts;
|
|
32
|
+
this.setState('opening');
|
|
33
|
+
const { MqttCore } = await import('@asyx/mqtt-core');
|
|
34
|
+
const { waitForAssignment } = await import('../state/assignment.js');
|
|
35
|
+
const { MqttControlPlaneTransport } = await import('../control-plane/MqttControlPlaneTransport.js');
|
|
36
|
+
const { MessageIngress } = await import('../mqtt/ingress.js');
|
|
37
|
+
const { dispatch: dispatchEvt } = await import('../mqtt/events/index.js');
|
|
38
|
+
// CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
|
|
39
|
+
const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || '60000', 10);
|
|
40
|
+
const baseClientId = credentials.clientId;
|
|
41
|
+
const instanceIdRef = { instanceId: null };
|
|
42
|
+
// TPB-17: coordinator references for the renewal callback
|
|
43
|
+
let coordinatorCoreRef = null;
|
|
44
|
+
let coordinatorIngressRef = null;
|
|
45
|
+
const deviceIdRef = credentials.clientId;
|
|
46
|
+
const localPortRef = localPort;
|
|
47
|
+
const subscriptionReadyRef = { ready: false };
|
|
48
|
+
let mqttClient;
|
|
49
|
+
const onRefreshLease = async () => {
|
|
50
|
+
if (!coordinatorCoreRef || !coordinatorIngressRef) {
|
|
51
|
+
throw new Error("Coordinator not available for refresh");
|
|
52
|
+
}
|
|
53
|
+
// TPB-12: Get instanceId from mqttClient (captured in closure)
|
|
54
|
+
const refreshInstanceId = mqttClient.getClientId();
|
|
55
|
+
const { getAssignment } = await import('../state/assignment.js');
|
|
56
|
+
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
57
|
+
// TPB-12: Get assignment for this specific instance
|
|
58
|
+
const currentAssignment = getAssignment(refreshInstanceId);
|
|
59
|
+
if (!currentAssignment) {
|
|
60
|
+
throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
|
|
61
|
+
}
|
|
62
|
+
const leaseId = currentAssignment.leaseId;
|
|
63
|
+
if (!leaseId) {
|
|
64
|
+
throw new Error("No leaseId in current assignment");
|
|
65
|
+
}
|
|
66
|
+
// Build refresh payload
|
|
67
|
+
const refreshRequestId = `refresh-${randomUUID()}` /* Defect 11.27: unique across processes (was Date.now()) */;
|
|
68
|
+
const fingerprint = await getFpHash(deviceIdRef);
|
|
69
|
+
// TPB-17: Include instanceId and proto:"tcp" in refresh payload
|
|
70
|
+
const refreshPayload = {
|
|
71
|
+
requestId: refreshRequestId,
|
|
72
|
+
instanceId: refreshInstanceId, // TPB-12: Per-instance routing
|
|
73
|
+
refreshOf: leaseId,
|
|
74
|
+
proto: 'tcp', // TPB-17: TCP protocol identifier
|
|
75
|
+
localPort: localPortRef,
|
|
76
|
+
clientId: deviceIdRef,
|
|
77
|
+
...fingerprint
|
|
78
|
+
};
|
|
79
|
+
// Cancel any existing awaiters for this leaseId before starting a new refresh
|
|
80
|
+
const ackTopic = `asyx/tunnel/clients/${deviceIdRef}/evt/ack`;
|
|
81
|
+
const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
|
|
82
|
+
try {
|
|
83
|
+
const testMessage = {
|
|
84
|
+
topic: ackTopic,
|
|
85
|
+
payload: { type: 'open_ack', requestId: 'test' }
|
|
86
|
+
};
|
|
87
|
+
return awaiter.criteria(testMessage);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
if (cancelled > 0) {
|
|
94
|
+
logger.debug('jwt.refresh.awaiter.cancelled_stale', {
|
|
95
|
+
refreshRequestId,
|
|
96
|
+
cancelledCount: cancelled,
|
|
97
|
+
reason: 'new_refresh_starting'
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
// Wait for subscription to be ready before publishing
|
|
101
|
+
if (!subscriptionReadyRef.ready) {
|
|
102
|
+
logger.debug('jwt.refresh.waiting_for_subscription', { refreshRequestId });
|
|
103
|
+
const maxWait = 2000;
|
|
104
|
+
const startWait = Date.now();
|
|
105
|
+
while (!subscriptionReadyRef.ready && (Date.now() - startWait) < maxWait) {
|
|
106
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
107
|
+
}
|
|
108
|
+
if (!subscriptionReadyRef.ready) {
|
|
109
|
+
logger.debug('jwt.refresh.subscription_not_ready', { refreshRequestId, waited: Date.now() - startWait });
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
logger.debug('jwt.refresh.subscription_ready', { refreshRequestId, waited: Date.now() - startWait });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
// Set up topic and wait for ack
|
|
116
|
+
const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
|
|
117
|
+
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
|
|
118
|
+
logger.debug('jwt.refresh.awaiter.registered', {
|
|
119
|
+
refreshRequestId,
|
|
120
|
+
instanceId: refreshInstanceId,
|
|
121
|
+
tunnelType: 'tcp',
|
|
122
|
+
timeoutMs: ACK_TIMEOUT_MS,
|
|
123
|
+
expectedType: 'open_ack'
|
|
124
|
+
});
|
|
125
|
+
const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
|
|
126
|
+
try {
|
|
127
|
+
const parsed = message.payload;
|
|
128
|
+
const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
129
|
+
const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
|
|
130
|
+
if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
|
|
131
|
+
logger.debug('jwt.refresh.awaiter.checking', {
|
|
132
|
+
refreshRequestId,
|
|
133
|
+
receivedRequestId: parsed.requestId,
|
|
134
|
+
receivedType: parsed.type,
|
|
135
|
+
isAck,
|
|
136
|
+
isReject,
|
|
137
|
+
topic: message.topic
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
// TPB-17: For TCP, refresh failures are non-fatal (tunnel continues until WS closes)
|
|
141
|
+
// But we still throw on lease_closed/REFRESH_REJECTED to let MqttControlPlaneClient handle it
|
|
142
|
+
if (isReject) {
|
|
143
|
+
const reason = parsed.data?.reason || 'unknown';
|
|
144
|
+
if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
|
|
145
|
+
const leaseClosedError = new Error('Lease is closed and cannot be refreshed');
|
|
146
|
+
leaseClosedError.code = 'LEASE_CLOSED';
|
|
147
|
+
leaseClosedError.reason = reason;
|
|
148
|
+
throw leaseClosedError;
|
|
149
|
+
}
|
|
150
|
+
const rejectError = new Error(`Refresh rejected: ${reason}`);
|
|
151
|
+
rejectError.code = 'REFRESH_REJECTED';
|
|
152
|
+
rejectError.reason = reason;
|
|
153
|
+
throw rejectError;
|
|
154
|
+
}
|
|
155
|
+
return isAck;
|
|
156
|
+
}
|
|
157
|
+
catch (e) {
|
|
158
|
+
if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
|
|
159
|
+
throw e;
|
|
160
|
+
}
|
|
161
|
+
logger.debug('jwt.refresh.awaiter.criteria_error', {
|
|
162
|
+
refreshRequestId,
|
|
163
|
+
error: e.message
|
|
164
|
+
});
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
}, ACK_TIMEOUT_MS);
|
|
168
|
+
// Publish refresh request
|
|
169
|
+
const publishSuccess = await publishRefreshRequestWithErrorHandling(coordinatorCoreRef, cmdOpenTopic, refreshPayload, refreshRequestId, logger);
|
|
170
|
+
if (publishSuccess === false) {
|
|
171
|
+
const bufferedError = new Error('Connection closed during refresh publish');
|
|
172
|
+
bufferedError.code = 'ECONNRESET';
|
|
173
|
+
throw bufferedError;
|
|
174
|
+
}
|
|
175
|
+
// Wait for ack (non-fatal for TCP - tunnel continues on failure)
|
|
176
|
+
let ackResult;
|
|
177
|
+
try {
|
|
178
|
+
ackResult = await ackPromise;
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
// TPB-17: For TCP, refresh failures are non-fatal
|
|
182
|
+
// Log and return null to indicate refresh failed, but don't throw
|
|
183
|
+
// The tunnel will continue until WebSocket closes naturally
|
|
184
|
+
if (error.code === 'LEASE_CLOSED' || error.code === 'REFRESH_REJECTED') {
|
|
185
|
+
logger.warn('tcp.refresh.rejected', {
|
|
186
|
+
reason: error.reason || 'unknown',
|
|
187
|
+
requestId: refreshRequestId,
|
|
188
|
+
action: 'non_fatal_continue'
|
|
189
|
+
});
|
|
190
|
+
// Return null to indicate refresh failed, but don't throw (non-fatal)
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
// Timeout or other errors - also non-fatal for TCP
|
|
194
|
+
logger.warn('tcp.refresh.timeout', {
|
|
195
|
+
error: error.message,
|
|
196
|
+
requestId: refreshRequestId,
|
|
197
|
+
action: 'non_fatal_continue'
|
|
198
|
+
});
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
// Get new assignment (updated by open_ack handler)
|
|
202
|
+
const newAssignment = getAssignment(refreshInstanceId);
|
|
203
|
+
if (!newAssignment) {
|
|
204
|
+
logger.warn('tcp.refresh.no_assignment', { requestId: refreshRequestId });
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
// Extract expiration from new JWT
|
|
208
|
+
const newJwt = newAssignment.jwt;
|
|
209
|
+
const parts = newJwt.split('.');
|
|
210
|
+
if (parts.length !== 3) {
|
|
211
|
+
logger.warn('tcp.refresh.invalid_jwt', { requestId: refreshRequestId });
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
215
|
+
const expMs = payload.exp ? payload.exp * 1000 : null;
|
|
216
|
+
if (!expMs) {
|
|
217
|
+
logger.warn('tcp.refresh.no_exp', { requestId: refreshRequestId });
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
// TPB-17: TCP refresh updates assignment/JWT for reconnect use
|
|
221
|
+
// No data-plane reauth needed (TCP uses TCP-v1 framing, not WebSocket auth)
|
|
222
|
+
// The assignment is already updated by the open_ack handler
|
|
223
|
+
logger.debug('tcp.refresh.success', {
|
|
224
|
+
leaseId: newAssignment.leaseId,
|
|
225
|
+
expMs,
|
|
226
|
+
requestId: refreshRequestId
|
|
227
|
+
});
|
|
228
|
+
this.setState('renewed', { leaseId: newAssignment.leaseId, expMs });
|
|
229
|
+
this.setState('live');
|
|
230
|
+
return expMs;
|
|
231
|
+
};
|
|
232
|
+
const cpSession = createControlPlaneSession({
|
|
233
|
+
credentials,
|
|
234
|
+
tunnelType: 'tcp',
|
|
235
|
+
metadata: { baseClientId, localPort, serviceName, kind, requestedExternalPort },
|
|
236
|
+
logger,
|
|
237
|
+
onRefreshLease,
|
|
238
|
+
instanceIdRef,
|
|
239
|
+
subscriptionReadyRef,
|
|
240
|
+
trackSubscriptionReady: false, // TCP has never tracked it
|
|
241
|
+
reportOffline: false, // TCP has never reported a lost control-plane connection
|
|
242
|
+
});
|
|
243
|
+
mqttClient = cpSession.mqttClient;
|
|
244
|
+
this.mqttClient = mqttClient;
|
|
245
|
+
cpSession.events.on('connected', (e) => this.emit('control-connected', e));
|
|
246
|
+
cpSession.events.on('fatal', (e) => this.emit('control-fatal', e));
|
|
247
|
+
const transport = new MqttControlPlaneTransport(mqttClient);
|
|
248
|
+
const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
|
|
249
|
+
this.core = core;
|
|
250
|
+
const isControlPlaneConnected = () => mqttClient.isOnline();
|
|
251
|
+
const waitForControlPlane = () => {
|
|
252
|
+
if (mqttClient.isOnline())
|
|
253
|
+
return Promise.resolve();
|
|
254
|
+
const start = Date.now();
|
|
255
|
+
return new Promise((resolve, reject) => {
|
|
256
|
+
const interval = setInterval(() => {
|
|
257
|
+
if (mqttClient.isOnline()) {
|
|
258
|
+
clearInterval(interval);
|
|
259
|
+
resolve();
|
|
260
|
+
}
|
|
261
|
+
else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
|
|
262
|
+
clearInterval(interval);
|
|
263
|
+
reject(new Error('control_plane_timeout'));
|
|
264
|
+
}
|
|
265
|
+
}, 250);
|
|
266
|
+
});
|
|
267
|
+
};
|
|
268
|
+
const getLastMqttError = () => null;
|
|
269
|
+
const getForceReconnect = () => async () => {
|
|
270
|
+
if (!mqttClient.isOnline()) {
|
|
271
|
+
await mqttClient.disconnect();
|
|
272
|
+
await mqttClient.connect();
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
// 3) Connect to control plane
|
|
276
|
+
try {
|
|
277
|
+
await mqttClient.connect();
|
|
278
|
+
}
|
|
279
|
+
catch (e) {
|
|
280
|
+
logger.error('mqtt.connect.failed', { error: e?.message || String(e) });
|
|
281
|
+
throw new ConnectionError('control_plane_connect_failed', e?.message || String(e), { cause: e });
|
|
282
|
+
}
|
|
283
|
+
// TPB-12: instanceId is the full MQTT clientId after connection
|
|
284
|
+
instanceIdRef.instanceId = mqttClient.getClientId();
|
|
285
|
+
const instanceId = instanceIdRef.instanceId;
|
|
286
|
+
logger.debug('cli.instance.registered', { instanceId, tunnelType: 'tcp', baseClientId });
|
|
287
|
+
// 4) Topics
|
|
288
|
+
const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
|
|
289
|
+
const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
|
|
290
|
+
await core.subscribe(evtWildcard, 0);
|
|
291
|
+
// 5) Message ingress and dispatcher
|
|
292
|
+
const ingress = new MessageIngress({ maxAwaiters: 100, observability: process.env.ASYX_DEBUG === '1', logger, onObserve: this.opts.onObserve });
|
|
293
|
+
ingress.setDispatcher(dispatchEvt);
|
|
294
|
+
const { registerInstance, setExpectedRequestId } = await import('../state/instance-registry.js');
|
|
295
|
+
const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import('../state/assignment.js');
|
|
296
|
+
registerInstance(instanceId, {
|
|
297
|
+
tunnelType: 'tcp',
|
|
298
|
+
setAssignment: setAssignmentFn,
|
|
299
|
+
getAssignment: getAssignmentFn,
|
|
300
|
+
metadata: { baseClientId, localPort, serviceName, kind, requestedExternalPort },
|
|
301
|
+
});
|
|
302
|
+
coordinatorCoreRef = core;
|
|
303
|
+
coordinatorIngressRef = ingress;
|
|
304
|
+
// A reply that ends the tunnel closes it with a typed error (the CLI used to print and exit here).
|
|
305
|
+
core.onMessage(async (m) => {
|
|
306
|
+
try {
|
|
307
|
+
await ingress.handleMessage(m);
|
|
308
|
+
}
|
|
309
|
+
catch (e) {
|
|
310
|
+
let error;
|
|
311
|
+
if (e && e.code === 'SETUP_REQUIRED')
|
|
312
|
+
error = new SetupRequiredError('setup_required', e.message, { cause: e });
|
|
313
|
+
else if (e && typeof e.code === 'string' && e.code.startsWith('ERROR_'))
|
|
314
|
+
error = new RefusedError(e.code, e.message, { cause: e });
|
|
315
|
+
else
|
|
316
|
+
error = new InternalError('unexpected', e?.message || String(e), { cause: e });
|
|
317
|
+
try {
|
|
318
|
+
await core.end();
|
|
319
|
+
}
|
|
320
|
+
catch { }
|
|
321
|
+
this.setState('closed', { error });
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
// 6) Publish cmd/open request with TCP protocol
|
|
325
|
+
const requestId = randomUUID();
|
|
326
|
+
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
327
|
+
const fingerprint = await getFpHash(credentials.clientId);
|
|
328
|
+
// TPB-12: Track expected requestId for pre-assignment routing (before coordinator sends instanceId)
|
|
329
|
+
setExpectedRequestId(instanceId, requestId);
|
|
330
|
+
// TCP-S2 / E3-S8 / TPB-12: TCP cmd/open payload
|
|
331
|
+
const openPayload = {
|
|
332
|
+
requestId,
|
|
333
|
+
instanceId, // TPB-12: Per-instance routing
|
|
334
|
+
proto: 'tcp',
|
|
335
|
+
target, // "127.0.0.1:<port>" from TCP-S1
|
|
336
|
+
clientId: credentials.clientId,
|
|
337
|
+
...fingerprint,
|
|
338
|
+
};
|
|
339
|
+
openPayload.opts = { preferredPort: null };
|
|
340
|
+
if (serviceName)
|
|
341
|
+
openPayload.opts.name = serviceName;
|
|
342
|
+
if (kind)
|
|
343
|
+
openPayload.opts.kind = kind;
|
|
344
|
+
// TPB-03B: Include requestedExternalPort in opts (null if omitted)
|
|
345
|
+
if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
|
|
346
|
+
openPayload.opts.requestedExternalPort = requestedExternalPort;
|
|
347
|
+
}
|
|
348
|
+
await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(openPayload), qos: 1, retain: false });
|
|
349
|
+
logger.info('cli.cmd.open.sent', { requestId, instanceId, tunnelType: 'tcp', protocol: 'tcp', target });
|
|
350
|
+
// 7) Wait for ack and assignment
|
|
351
|
+
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
|
|
352
|
+
let assignment;
|
|
353
|
+
let reassignSamePort;
|
|
354
|
+
try {
|
|
355
|
+
const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
|
|
356
|
+
logger.info('cli.ack.wait.start', { requestId });
|
|
357
|
+
assignment = await assignmentPromise;
|
|
358
|
+
logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'tcp' });
|
|
359
|
+
logger.info('cli.assignment.received', { relayId: assignment.relayId, leaseId: assignment.leaseId, instanceId, tunnelType: 'tcp', tcpAliasFqdn: assignment.tcpAliasFqdn, publicPort: assignment.publicPort });
|
|
360
|
+
// TPB-12: Persist assignment using per-instance store
|
|
361
|
+
try {
|
|
362
|
+
const { setAssignment } = await import('../state/assignment.js');
|
|
363
|
+
const { clearExpectedRequestId } = await import('../state/instance-registry.js');
|
|
364
|
+
setAssignment(instanceId, assignment);
|
|
365
|
+
clearExpectedRequestId(instanceId);
|
|
366
|
+
}
|
|
367
|
+
catch { }
|
|
368
|
+
// TCP-S3: Handle warnings array (alias unavailable)
|
|
369
|
+
const warnings = assignment.warnings || [];
|
|
370
|
+
const aliasRequestedButFailed = warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some((w) => w.code === 'TCP_ALIAS_UNAVAILABLE');
|
|
371
|
+
if (aliasRequestedButFailed) {
|
|
372
|
+
logger.warn('tcp.alias.unavailable', { requestId, fqdn: assignment.fqdn, publicPort: assignment.publicPort });
|
|
373
|
+
}
|
|
374
|
+
// TCP-S3 / E3-S8: where the server is reachable (the CLI prints it)
|
|
375
|
+
const tcpAliasFqdn = assignment.tcpAliasFqdn;
|
|
376
|
+
this.emit('assigned', {
|
|
377
|
+
tcpAliasFqdn,
|
|
378
|
+
srvProvisioned: assignment.srvProvisioned === true,
|
|
379
|
+
srvFqdn: assignment.srvFqdn || null,
|
|
380
|
+
fqdn: assignment.fqdn,
|
|
381
|
+
publicPort: assignment.publicPort,
|
|
382
|
+
aliasRequestedButFailed,
|
|
383
|
+
});
|
|
384
|
+
if (tcpAliasFqdn) {
|
|
385
|
+
logger.debug('tcp.alias.ready', { requestId, tcpAliasFqdn, fqdn: assignment.fqdn, publicPort: assignment.publicPort });
|
|
386
|
+
}
|
|
387
|
+
// Story 10.9: if the relay refuses this assignment on a reconnect (the tenant moved), open
|
|
388
|
+
// again for the same public port; the control plane places the lease on the current relay.
|
|
389
|
+
reassignSamePort = async () => {
|
|
390
|
+
const { setAssignment: setA, getAssignment: getA } = await import('../state/assignment.js');
|
|
391
|
+
const cur = getA(instanceIdRef.instanceId) || assignment;
|
|
392
|
+
const rid = randomUUID();
|
|
393
|
+
const again = { ...openPayload, requestId: rid, opts: { ...(openPayload.opts || {}), requestedExternalPort: cur.publicPort ?? assignment.publicPort } };
|
|
394
|
+
setExpectedRequestId(instanceIdRef.instanceId, rid);
|
|
395
|
+
await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
|
|
396
|
+
const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
|
|
397
|
+
setA(instanceIdRef.instanceId, next);
|
|
398
|
+
logger.info('tcp.reassign.ok', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
|
|
399
|
+
return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
catch (error) {
|
|
403
|
+
// TCP-S3 / TPB-03B: coordinator error codes, reported as refusals with what the CLI prints
|
|
404
|
+
const errorCode = error.code || error.reason || error.data?.reason;
|
|
405
|
+
const lc = String(errorCode || '').toLowerCase();
|
|
406
|
+
const refused = (code, details, logMsg) => {
|
|
407
|
+
logger.error(logMsg, { error: error.message, ...details });
|
|
408
|
+
return new RefusedError(code, error.message, { cause: error, details });
|
|
409
|
+
};
|
|
410
|
+
let refusal = null;
|
|
411
|
+
if (lc === 'tcp_port_out_of_block') {
|
|
412
|
+
refusal = refused('tcp_port_out_of_block', {
|
|
413
|
+
requestedPort: error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X',
|
|
414
|
+
blockStart: error.blockStart || error.data?.blockStart || 'A',
|
|
415
|
+
blockEnd: error.blockEnd || error.data?.blockEnd || 'B',
|
|
416
|
+
}, 'cli.tcp.error.port_out_of_block');
|
|
417
|
+
}
|
|
418
|
+
else if (lc === 'tcp_port_already_in_use') {
|
|
419
|
+
refusal = refused('tcp_port_already_in_use', {
|
|
420
|
+
requestedPort: error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X',
|
|
421
|
+
}, 'cli.tcp.error.port_already_in_use');
|
|
422
|
+
}
|
|
423
|
+
else if (lc === 'tcp_port_block_exhausted_for_tenant' || lc === 'tcp_port_block_exhausted') {
|
|
424
|
+
refusal = refused(lc, {
|
|
425
|
+
blockStart: error.blockStart || error.data?.blockStart || 'A',
|
|
426
|
+
blockEnd: error.blockEnd || error.data?.blockEnd || 'B',
|
|
427
|
+
}, 'cli.tcp.error.block_exhausted');
|
|
428
|
+
}
|
|
429
|
+
else if (lc === 'tcp_port_capacity_exhausted') {
|
|
430
|
+
refusal = refused('tcp_port_capacity_exhausted', {}, 'cli.tcp.error.capacity_exhausted');
|
|
431
|
+
}
|
|
432
|
+
else if (lc === 'tenant_tcp_lease_limit_reached') {
|
|
433
|
+
refusal = refused('tenant_tcp_lease_limit_reached', { relayId: error.relayId || error.data?.relayId || 'unknown' }, 'cli.tcp.error.lease_limit');
|
|
434
|
+
}
|
|
435
|
+
if (refusal) {
|
|
436
|
+
try {
|
|
437
|
+
await core.end();
|
|
438
|
+
}
|
|
439
|
+
catch { }
|
|
440
|
+
throw refusal;
|
|
441
|
+
}
|
|
442
|
+
// Generic error handling
|
|
443
|
+
logger.error('cli.ack.wait.failed', { error: error.message, errorCode, instanceId, tunnelType: 'tcp' });
|
|
444
|
+
try {
|
|
445
|
+
const { clearExpectedRequestId } = await import('../state/instance-registry.js');
|
|
446
|
+
clearExpectedRequestId(instanceId);
|
|
447
|
+
}
|
|
448
|
+
catch { }
|
|
449
|
+
try {
|
|
450
|
+
await core.end();
|
|
451
|
+
}
|
|
452
|
+
catch { }
|
|
453
|
+
throw new ConnectionError('assignment_failed', error.message, { cause: error });
|
|
454
|
+
}
|
|
455
|
+
// TCP-S4: Connect to the relay (was connectToRelayTcp)
|
|
456
|
+
const { TcpTunnel } = await import('../tunnel/tcp-tunnel.js');
|
|
457
|
+
const { getAssignment: getStoredAssignment } = await import('../state/assignment.js');
|
|
458
|
+
const tunnel = new TcpTunnel({
|
|
459
|
+
relayUrl: assignment.relayUrl,
|
|
460
|
+
jwt: assignment.jwt, // Use JWT as-is (no validation)
|
|
461
|
+
getJwt: () => (mqttClient ? getStoredAssignment(mqttClient.getClientId())?.jwt : null) || null,
|
|
462
|
+
reassign: reassignSamePort,
|
|
463
|
+
deviceId: credentials.clientId,
|
|
464
|
+
requestId: assignment.requestId,
|
|
465
|
+
localPort,
|
|
466
|
+
leaseId: assignment.leaseId, // E3-S3: leaseId for TCP relay WebSocket query parameters
|
|
467
|
+
coordinatorCore: core,
|
|
468
|
+
coordinatorIngress: ingress,
|
|
469
|
+
isControlPlaneConnected,
|
|
470
|
+
waitForControlPlane,
|
|
471
|
+
getLastMqttError,
|
|
472
|
+
getForceReconnect,
|
|
473
|
+
controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS,
|
|
474
|
+
log: adaptLogger(logger),
|
|
475
|
+
// Story 12.1 (c2): where the tunnel used to exit, it now ends with a typed error; the CLI exits
|
|
476
|
+
// with the same code (silently, as before).
|
|
477
|
+
exit: (code) => this.setState('closed', { error: new ConnectionError('tunnel_ended', `tunnel ended (exit code ${code})`, { details: { exitCode: code } }) }),
|
|
478
|
+
});
|
|
479
|
+
this.tunnel = tunnel;
|
|
480
|
+
try {
|
|
481
|
+
await tunnel.open();
|
|
482
|
+
scheduleInitialTcpRefresh(mqttClient, assignment, logger);
|
|
483
|
+
logger.info('tunnel.active', { target: `tcp://127.0.0.1:${localPort}`, relayId: assignment.relayId, leaseMs: assignment.leaseMs });
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
logger.error('tunnel.open.failed', { error: error.message });
|
|
487
|
+
try {
|
|
488
|
+
tunnel.close();
|
|
489
|
+
}
|
|
490
|
+
catch (e) {
|
|
491
|
+
logger.debug('tunnel.close.error', { error: e.message });
|
|
492
|
+
}
|
|
493
|
+
try {
|
|
494
|
+
await mqttClient.disconnect();
|
|
495
|
+
}
|
|
496
|
+
catch (e) {
|
|
497
|
+
logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
|
|
498
|
+
}
|
|
499
|
+
throw new ConnectionError('tunnel_connect_failed', error.message, { cause: error });
|
|
500
|
+
}
|
|
501
|
+
this.assignment = assignment;
|
|
502
|
+
const info = { assignment, localPort, relayId: assignment.relayId, publicPort: assignment.publicPort, fqdn: assignment.fqdn, leaseMs: assignment.leaseMs };
|
|
503
|
+
this.setState('live', info);
|
|
504
|
+
return info;
|
|
505
|
+
}
|
|
506
|
+
/** Close the data plane, then the control plane. */
|
|
507
|
+
async close() {
|
|
508
|
+
try {
|
|
509
|
+
this.tunnel?.close();
|
|
510
|
+
}
|
|
511
|
+
finally {
|
|
512
|
+
await this.mqttClient?.disconnect();
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* TPB-17: schedule the first TCP renewal from the assignment token's expiry (moved unchanged from
|
|
518
|
+
* connectToRelayTcp; exported so its behaviour can be tested on its own).
|
|
519
|
+
*/
|
|
520
|
+
export function scheduleInitialTcpRefresh(mqttClient, assignment, logger) {
|
|
521
|
+
if (mqttClient && assignment.jwt && assignment.leaseId) {
|
|
522
|
+
try {
|
|
523
|
+
const parts = assignment.jwt.split('.');
|
|
524
|
+
if (parts.length === 3) {
|
|
525
|
+
const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
526
|
+
const expMs = payload.exp ? payload.exp * 1000 : null;
|
|
527
|
+
if (expMs) {
|
|
528
|
+
mqttClient.scheduleRefresh(expMs, assignment.leaseId);
|
|
529
|
+
logger.debug('tcp.refresh.initial_scheduled', { expMs, leaseId: assignment.leaseId });
|
|
530
|
+
}
|
|
531
|
+
else {
|
|
532
|
+
logger.warn('tcp.refresh.initial_failed', { reason: 'no_exp_in_jwt' });
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
else {
|
|
536
|
+
logger.warn('tcp.refresh.initial_failed', { reason: 'invalid_jwt_format' });
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
catch (error) {
|
|
540
|
+
logger.warn('tcp.refresh.initial_failed', { reason: 'jwt_decode_error', error: error.message });
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
export function createTcpTunnel(opts) {
|
|
545
|
+
return new TcpTunnelHandle(opts);
|
|
546
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { LifecycleEmitter } from '../lifecycle.js';
|
|
2
|
+
import type { ControlPlaneCredentials } from '../control-plane/session.js';
|
|
3
|
+
import type { Logger } from '../types.js';
|
|
4
|
+
export interface UdpTunnelOptions {
|
|
5
|
+
credentials: ControlPlaneCredentials;
|
|
6
|
+
/** The local app's port (UDP-S13: not a port the CLI binds). */
|
|
7
|
+
targetPort: number;
|
|
8
|
+
/** Must be loopback; default 127.0.0.1. */
|
|
9
|
+
targetHost?: string;
|
|
10
|
+
/** A public port inside the tenant's block, or null for the coordinator's choice. */
|
|
11
|
+
requestedExternalPort?: number | null;
|
|
12
|
+
logger: Logger;
|
|
13
|
+
/** Called with each observability line when ASYX_DEBUG=1 (the CLI prints them). */
|
|
14
|
+
onObserve?: (line: string) => void;
|
|
15
|
+
}
|
|
16
|
+
/** What open() resolves to and the 'live' state carries. */
|
|
17
|
+
export type UdpTunnelInfo = {
|
|
18
|
+
assignment: Record<string, any>;
|
|
19
|
+
targetHost: string;
|
|
20
|
+
targetPort: number;
|
|
21
|
+
relayId: string;
|
|
22
|
+
publicPort?: number;
|
|
23
|
+
fqdn?: string;
|
|
24
|
+
leaseMs?: number;
|
|
25
|
+
};
|
|
26
|
+
export declare class UdpTunnelHandle extends LifecycleEmitter {
|
|
27
|
+
readonly opts: UdpTunnelOptions & {
|
|
28
|
+
targetHost: string;
|
|
29
|
+
requestedExternalPort: number | null;
|
|
30
|
+
};
|
|
31
|
+
tunnel: any;
|
|
32
|
+
mqttClient: any;
|
|
33
|
+
core: any;
|
|
34
|
+
assignment: Record<string, any> | null;
|
|
35
|
+
constructor(o: UdpTunnelOptions);
|
|
36
|
+
/** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
|
|
37
|
+
open(): Promise<UdpTunnelInfo>;
|
|
38
|
+
/** Close the data plane, then the control plane. */
|
|
39
|
+
close(): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
export declare function createUdpTunnel(opts: UdpTunnelOptions): UdpTunnelHandle;
|