asyx 0.5.9 → 0.6.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/README.md +71 -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,585 @@
|
|
|
1
|
+
// Story 12.1 (step 2b, sub-step 3; TypeScript in r3): the HTTP tunnel flow, moved from httpTunnel() and
|
|
2
|
+
// connectToRelay() 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-offline' { reason } / 'control-fatal' { reason, error }
|
|
5
|
+
// state events: 'opening', 'live', and a final 'closed' { error } when a reply ends the tunnel
|
|
6
|
+
// after it opened (SetupRequiredError, RefusedError, InternalError).
|
|
7
|
+
// open() rejects with ConnectionError control_plane_connect_failed | assignment_failed |
|
|
8
|
+
// tunnel_connect_failed. The renewal callback (in-band reauth, reconnect fallback) is unchanged.
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { LifecycleEmitter } from '../lifecycle.js';
|
|
11
|
+
import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
|
|
12
|
+
import { createControlPlaneSession } from '../control-plane/session.js';
|
|
13
|
+
import { publishRefreshRequestWithErrorHandling } from '../lib/refresh-helpers.js';
|
|
14
|
+
import { adaptLogger } from '../lib/adapt-logger.js';
|
|
15
|
+
export function scheduleInitialHttpRefresh(mqttClient, assignment, logger) {
|
|
16
|
+
if (mqttClient && assignment.jwt && assignment.leaseId) {
|
|
17
|
+
try {
|
|
18
|
+
const parts = assignment.jwt.split('.');
|
|
19
|
+
if (parts.length === 3) {
|
|
20
|
+
const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
21
|
+
const expMs = payload.exp ? payload.exp * 1000 : null;
|
|
22
|
+
if (expMs) {
|
|
23
|
+
mqttClient.scheduleRefresh(expMs, assignment.leaseId);
|
|
24
|
+
logger.debug('jwt.refresh.initial_scheduled', { expMs, leaseId: assignment.leaseId });
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
logger.warn('jwt.refresh.initial_failed', { reason: 'no_exp_in_jwt' });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
logger.warn('jwt.refresh.initial_failed', { reason: 'invalid_jwt_format' });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
logger.warn('jwt.refresh.initial_failed', { reason: 'jwt_decode_error', error: error.message });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export class HttpTunnelHandle extends LifecycleEmitter {
|
|
40
|
+
opts;
|
|
41
|
+
tunnel = null;
|
|
42
|
+
mqttClient = null;
|
|
43
|
+
core = null;
|
|
44
|
+
assignment = null;
|
|
45
|
+
constructor(o) {
|
|
46
|
+
super();
|
|
47
|
+
this.opts = { secGroupSlug: null, ...o };
|
|
48
|
+
}
|
|
49
|
+
/** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
|
|
50
|
+
async open() {
|
|
51
|
+
const { credentials, localPort, secGroupSlug, logger } = this.opts;
|
|
52
|
+
this.setState('opening');
|
|
53
|
+
const { MqttCore } = await import('@asyx/mqtt-core');
|
|
54
|
+
const { waitForAssignment } = await import('../state/assignment.js');
|
|
55
|
+
const { MqttControlPlaneTransport } = await import('../control-plane/MqttControlPlaneTransport.js');
|
|
56
|
+
const { MessageIngress } = await import('../mqtt/ingress.js');
|
|
57
|
+
const { dispatch: dispatchEvt } = await import('../mqtt/events/index.js');
|
|
58
|
+
// CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
|
|
59
|
+
const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || '60000', 10);
|
|
60
|
+
const baseClientId = credentials.clientId;
|
|
61
|
+
const instanceIdRef = { instanceId: null };
|
|
62
|
+
// QPA-CLI-01: tunnel reference for the reconnect hook and the renewal callback
|
|
63
|
+
const tunnelInstanceRef = { tunnel: null };
|
|
64
|
+
let coordinatorCoreRef = null;
|
|
65
|
+
let coordinatorIngressRef = null;
|
|
66
|
+
const deviceIdRef = credentials.clientId;
|
|
67
|
+
const localPortRef = localPort;
|
|
68
|
+
const secGroupSlugRef = secGroupSlug;
|
|
69
|
+
const subscriptionReadyRef = { ready: false };
|
|
70
|
+
let mqttClient;
|
|
71
|
+
const onRefreshLease = async () => {
|
|
72
|
+
if (!coordinatorCoreRef || !coordinatorIngressRef) {
|
|
73
|
+
throw new Error("Coordinator not available for refresh");
|
|
74
|
+
}
|
|
75
|
+
// TPB-12: Get instanceId from mqttClient (captured in closure)
|
|
76
|
+
const refreshInstanceId = mqttClient.getClientId();
|
|
77
|
+
const { getAssignment, readRefreshAssignment } = await import('../state/assignment.js');
|
|
78
|
+
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
79
|
+
// TPB-12: Get assignment for this specific instance
|
|
80
|
+
const currentAssignment = getAssignment(refreshInstanceId);
|
|
81
|
+
if (!currentAssignment) {
|
|
82
|
+
throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
|
|
83
|
+
}
|
|
84
|
+
const leaseId = currentAssignment.leaseId;
|
|
85
|
+
if (!leaseId) {
|
|
86
|
+
throw new Error("No leaseId in current assignment");
|
|
87
|
+
}
|
|
88
|
+
// Build refresh payload
|
|
89
|
+
const refreshRequestId = `refresh-${randomUUID()}` /* Defect 11.27: unique across processes (was Date.now()) */;
|
|
90
|
+
const fingerprint = await getFpHash(deviceIdRef);
|
|
91
|
+
// TPB-12: Include instanceId in refresh payload
|
|
92
|
+
const refreshPayload = {
|
|
93
|
+
requestId: refreshRequestId,
|
|
94
|
+
instanceId: refreshInstanceId, // TPB-12: Per-instance routing
|
|
95
|
+
refreshOf: leaseId,
|
|
96
|
+
proto: 'http',
|
|
97
|
+
localPort: localPortRef,
|
|
98
|
+
clientId: deviceIdRef,
|
|
99
|
+
...fingerprint
|
|
100
|
+
};
|
|
101
|
+
// QPA-04: Include secGroupSlug in refresh payload if provided
|
|
102
|
+
if (secGroupSlugRef) {
|
|
103
|
+
refreshPayload.secGroupSlug = secGroupSlugRef;
|
|
104
|
+
}
|
|
105
|
+
// Cancel any existing awaiters for this leaseId before starting a new refresh
|
|
106
|
+
// This prevents duplicate awaiters from accumulating when multiple refresh attempts happen
|
|
107
|
+
const ackTopic = `asyx/tunnel/clients/${deviceIdRef}/evt/ack`;
|
|
108
|
+
const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
|
|
109
|
+
// Test if this awaiter matches open_ack messages (likely a stale refresh awaiter)
|
|
110
|
+
try {
|
|
111
|
+
const testMessage = {
|
|
112
|
+
topic: ackTopic,
|
|
113
|
+
payload: { type: 'open_ack', requestId: 'test' }
|
|
114
|
+
};
|
|
115
|
+
// If the criteria matches open_ack messages, it's likely a refresh awaiter
|
|
116
|
+
const matches = awaiter.criteria(testMessage);
|
|
117
|
+
// Only cancel if it matches open_ack (we don't want to cancel other awaiters)
|
|
118
|
+
return matches;
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
if (cancelled > 0) {
|
|
125
|
+
logger.debug('jwt.refresh.awaiter.cancelled_stale', {
|
|
126
|
+
refreshRequestId,
|
|
127
|
+
cancelledCount: cancelled,
|
|
128
|
+
reason: 'new_refresh_starting'
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
// Wait for subscription to be ready before publishing (prevents race where ack is published before subscription is active)
|
|
132
|
+
// Only wait if subscription is not ready (e.g., after reconnect before resubscription completes)
|
|
133
|
+
if (!subscriptionReadyRef.ready) {
|
|
134
|
+
logger.debug('jwt.refresh.waiting_for_subscription', { refreshRequestId });
|
|
135
|
+
// Wait up to 2 seconds for subscription to be ready (should be immediate after subscribe() resolves)
|
|
136
|
+
const maxWait = 2000;
|
|
137
|
+
const startWait = Date.now();
|
|
138
|
+
while (!subscriptionReadyRef.ready && (Date.now() - startWait) < maxWait) {
|
|
139
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
140
|
+
}
|
|
141
|
+
if (!subscriptionReadyRef.ready) {
|
|
142
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
143
|
+
logger.debug('jwt.refresh.subscription_not_ready', { refreshRequestId, waited: Date.now() - startWait });
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
logger.debug('jwt.refresh.subscription_ready', { refreshRequestId, waited: Date.now() - startWait });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
// Set up topic and wait for ack
|
|
150
|
+
const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
|
|
151
|
+
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
|
|
152
|
+
// Log awaiter registration for debugging
|
|
153
|
+
logger.debug('jwt.refresh.awaiter.registered', {
|
|
154
|
+
refreshRequestId,
|
|
155
|
+
instanceId: refreshInstanceId,
|
|
156
|
+
tunnelType: 'http',
|
|
157
|
+
timeoutMs: ACK_TIMEOUT_MS,
|
|
158
|
+
expectedType: 'open_ack'
|
|
159
|
+
});
|
|
160
|
+
const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
|
|
161
|
+
try {
|
|
162
|
+
const parsed = message.payload;
|
|
163
|
+
const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
164
|
+
const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
|
|
165
|
+
// Log matching attempts for debugging
|
|
166
|
+
if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
|
|
167
|
+
logger.debug('jwt.refresh.awaiter.checking', {
|
|
168
|
+
refreshRequestId,
|
|
169
|
+
receivedRequestId: parsed.requestId,
|
|
170
|
+
receivedType: parsed.type,
|
|
171
|
+
isAck,
|
|
172
|
+
isReject,
|
|
173
|
+
topic: message.topic
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
// If we get a reject, throw an error so the awaiter rejects the promise
|
|
177
|
+
if (isReject) {
|
|
178
|
+
const reason = parsed.data?.reason || 'unknown';
|
|
179
|
+
if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
|
|
180
|
+
const leaseClosedError = new Error('Lease is closed and cannot be refreshed');
|
|
181
|
+
leaseClosedError.code = 'LEASE_CLOSED';
|
|
182
|
+
leaseClosedError.reason = reason;
|
|
183
|
+
throw leaseClosedError;
|
|
184
|
+
}
|
|
185
|
+
// For other reject reasons, also throw but with different code
|
|
186
|
+
const rejectError = new Error(`Refresh rejected: ${reason}`);
|
|
187
|
+
rejectError.code = 'REFRESH_REJECTED';
|
|
188
|
+
rejectError.reason = reason;
|
|
189
|
+
throw rejectError;
|
|
190
|
+
}
|
|
191
|
+
return isAck;
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
// If it's a lease_closed or refresh_rejected error, rethrow it
|
|
195
|
+
if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
|
|
196
|
+
throw e;
|
|
197
|
+
}
|
|
198
|
+
logger.debug('jwt.refresh.awaiter.criteria_error', {
|
|
199
|
+
refreshRequestId,
|
|
200
|
+
error: e.message
|
|
201
|
+
});
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
}, ACK_TIMEOUT_MS);
|
|
205
|
+
// Publish refresh request
|
|
206
|
+
// QPA-CLI-09: Catch ECONNRESET during publish to prevent fatal exit
|
|
207
|
+
const publishSuccess = await publishRefreshRequestWithErrorHandling(coordinatorCoreRef, cmdOpenTopic, refreshPayload, refreshRequestId, logger);
|
|
208
|
+
// If publish returned false, ECONNRESET was caught and buffered
|
|
209
|
+
// Throw an error that MqttControlPlaneClient recognizes as offline error
|
|
210
|
+
// This ensures refreshPending stays true and re-arm logic knows refresh is needed
|
|
211
|
+
// The error will be caught by MqttControlPlaneClient and buffered (not bubbled up)
|
|
212
|
+
if (publishSuccess === false) {
|
|
213
|
+
const bufferedError = new Error('Connection closed during refresh publish');
|
|
214
|
+
bufferedError.code = 'ECONNRESET';
|
|
215
|
+
throw bufferedError;
|
|
216
|
+
}
|
|
217
|
+
// Wait for ack with reconnect retry on timeout
|
|
218
|
+
let ackResult;
|
|
219
|
+
try {
|
|
220
|
+
ackResult = await ackPromise;
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
// Check if this is a lease_closed error - don't retry, treat as fatal
|
|
224
|
+
if (error.code === 'LEASE_CLOSED' || error.code === 'REFRESH_REJECTED') {
|
|
225
|
+
logger.error('jwt.refresh.rejected', {
|
|
226
|
+
reason: error.reason || 'unknown',
|
|
227
|
+
requestId: refreshRequestId,
|
|
228
|
+
action: 'fatal'
|
|
229
|
+
});
|
|
230
|
+
throw new Error(`Cannot refresh closed lease: ${error.reason || 'lease_closed'}`);
|
|
231
|
+
}
|
|
232
|
+
// Otherwise treat as timeout and retry
|
|
233
|
+
const timeoutError = error;
|
|
234
|
+
// QPA-CLI-07: On timeout, reconnect control-plane and retry once
|
|
235
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
236
|
+
logger.debug('jwt.refresh.timeout', {
|
|
237
|
+
error: timeoutError.message,
|
|
238
|
+
action: 'reconnect_and_retry',
|
|
239
|
+
requestId: refreshRequestId
|
|
240
|
+
});
|
|
241
|
+
// Cancel any existing awaiters for this requestId before retrying
|
|
242
|
+
// This prevents duplicate awaiters from accumulating when retrying
|
|
243
|
+
const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
|
|
244
|
+
// Test if this awaiter matches the same requestId
|
|
245
|
+
try {
|
|
246
|
+
// Create a test message to see if the awaiter's criteria would match
|
|
247
|
+
// We can't directly inspect the criteria, so we test it with a mock message
|
|
248
|
+
const testMessage = {
|
|
249
|
+
topic: `asyx/tunnel/clients/${deviceIdRef}/evt/ack`,
|
|
250
|
+
payload: { type: 'open_ack', requestId: refreshRequestId }
|
|
251
|
+
};
|
|
252
|
+
return awaiter.criteria(testMessage);
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
if (cancelled > 0) {
|
|
259
|
+
logger.debug('jwt.refresh.awaiter.cancelled_duplicates', {
|
|
260
|
+
refreshRequestId,
|
|
261
|
+
cancelledCount: cancelled
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
// Force reconnect to get fresh MQTT session
|
|
265
|
+
await mqttClient.forceReconnect('ack_timeout');
|
|
266
|
+
// Re-register awaiter with same timeout after reconnect; ack might already be queued
|
|
267
|
+
logger.debug('jwt.refresh.awaiter.retry_registered', {
|
|
268
|
+
refreshRequestId,
|
|
269
|
+
timeoutMs: ACK_TIMEOUT_MS
|
|
270
|
+
});
|
|
271
|
+
const retryAckPromise = coordinatorIngressRef.registerAwaiter((message) => {
|
|
272
|
+
try {
|
|
273
|
+
const parsed = message.payload;
|
|
274
|
+
const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
275
|
+
const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
|
|
276
|
+
// Log matching attempts for debugging
|
|
277
|
+
if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
|
|
278
|
+
logger.debug('jwt.refresh.awaiter.retry_checking', {
|
|
279
|
+
refreshRequestId,
|
|
280
|
+
receivedRequestId: parsed.requestId,
|
|
281
|
+
receivedType: parsed.type,
|
|
282
|
+
isAck,
|
|
283
|
+
isReject,
|
|
284
|
+
topic: message.topic
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
// If we get a reject, throw an error so the awaiter rejects the promise
|
|
288
|
+
if (isReject) {
|
|
289
|
+
const reason = parsed.data?.reason || 'unknown';
|
|
290
|
+
if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
|
|
291
|
+
const leaseClosedError = new Error('Lease is closed and cannot be refreshed');
|
|
292
|
+
leaseClosedError.code = 'LEASE_CLOSED';
|
|
293
|
+
leaseClosedError.reason = reason;
|
|
294
|
+
throw leaseClosedError;
|
|
295
|
+
}
|
|
296
|
+
// For other reject reasons, also throw but with different code
|
|
297
|
+
const rejectError = new Error(`Refresh rejected: ${reason}`);
|
|
298
|
+
rejectError.code = 'REFRESH_REJECTED';
|
|
299
|
+
rejectError.reason = reason;
|
|
300
|
+
throw rejectError;
|
|
301
|
+
}
|
|
302
|
+
return isAck;
|
|
303
|
+
}
|
|
304
|
+
catch (e) {
|
|
305
|
+
// If it's a lease_closed or refresh_rejected error, rethrow it
|
|
306
|
+
if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
|
|
307
|
+
throw e;
|
|
308
|
+
}
|
|
309
|
+
logger.debug('jwt.refresh.awaiter.retry_criteria_error', {
|
|
310
|
+
refreshRequestId,
|
|
311
|
+
error: e.message
|
|
312
|
+
});
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
}, ACK_TIMEOUT_MS);
|
|
316
|
+
try {
|
|
317
|
+
ackResult = await retryAckPromise;
|
|
318
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
319
|
+
logger.debug('jwt.refresh.timeout.retry_success', { requestId: refreshRequestId });
|
|
320
|
+
}
|
|
321
|
+
catch (retryError) {
|
|
322
|
+
// Check if this is a lease_closed error - don't retry, treat as fatal
|
|
323
|
+
if (retryError.code === 'LEASE_CLOSED' || retryError.code === 'REFRESH_REJECTED') {
|
|
324
|
+
logger.error('jwt.refresh.rejected.retry', {
|
|
325
|
+
reason: retryError.reason || 'unknown',
|
|
326
|
+
requestId: refreshRequestId,
|
|
327
|
+
action: 'fatal'
|
|
328
|
+
});
|
|
329
|
+
throw new Error(`Cannot refresh closed lease: ${retryError.reason || 'lease_closed'}`);
|
|
330
|
+
}
|
|
331
|
+
logger.error('jwt.refresh.timeout', {
|
|
332
|
+
error: retryError.message,
|
|
333
|
+
action: 'give_up',
|
|
334
|
+
requestId: refreshRequestId
|
|
335
|
+
});
|
|
336
|
+
throw new Error(`Refresh timeout after reconnect: ${retryError.message}`);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
// Get new assignment for this client id. An unkeyed read is null once
|
|
340
|
+
// rotation has left more than one map entry.
|
|
341
|
+
const { assignment: newAssignment, expMs } = readRefreshAssignment(refreshInstanceId);
|
|
342
|
+
const newJwt = newAssignment.jwt;
|
|
343
|
+
// QPA-CLI-05: Notify HttpTunnel that new JWT is available
|
|
344
|
+
// HttpTunnel will handle WebSocket update (in-band reauth or reconnect)
|
|
345
|
+
if (tunnelInstanceRef.tunnel) {
|
|
346
|
+
// Update HttpTunnel with new JWT and assignment
|
|
347
|
+
tunnelInstanceRef.tunnel.jwt = newJwt;
|
|
348
|
+
tunnelInstanceRef.tunnel.requestId = newAssignment.requestId;
|
|
349
|
+
tunnelInstanceRef.tunnel.relayUrl = newAssignment.relayUrl;
|
|
350
|
+
tunnelInstanceRef.tunnel.headers = {
|
|
351
|
+
'Authorization': `Bearer ${newJwt}`,
|
|
352
|
+
'X-Asyx-DeviceId': deviceIdRef,
|
|
353
|
+
'X-Asyx-RequestId': newAssignment.requestId
|
|
354
|
+
};
|
|
355
|
+
// Update jwtMeta for HttpTunnel
|
|
356
|
+
tunnelInstanceRef.tunnel.jwtMeta = { token: newJwt, expMs };
|
|
357
|
+
// Note: recordRefresh is called in http-tunnel.js after in-band reauth succeeds
|
|
358
|
+
// to avoid double-counting when refresh happens via in-band reauth
|
|
359
|
+
// Try in-band reauth if WebSocket is open
|
|
360
|
+
if (tunnelInstanceRef.tunnel.ws && tunnelInstanceRef.tunnel.ws.readyState === 1) {
|
|
361
|
+
const prevJti = tunnelInstanceRef.tunnel.jwtMeta?.token
|
|
362
|
+
? tunnelInstanceRef.tunnel._extractJti(tunnelInstanceRef.tunnel.jwtMeta.token)
|
|
363
|
+
: null;
|
|
364
|
+
try {
|
|
365
|
+
const reauthSuccess = await tunnelInstanceRef.tunnel.reauthInBand(newJwt, prevJti, 'timer');
|
|
366
|
+
if (reauthSuccess) {
|
|
367
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
368
|
+
logger.debug('jwt.refresh.success', { method: 'in_band', leaseId: newAssignment.leaseId });
|
|
369
|
+
return expMs;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
catch (reauthError) {
|
|
373
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
374
|
+
logger.debug('jwt.reauth.exception', { error: reauthError.message });
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
// Fallback to reconnect
|
|
378
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
379
|
+
logger.debug('jwt.refresh.reconnect', { leaseId: newAssignment.leaseId });
|
|
380
|
+
await tunnelInstanceRef.tunnel._attemptConnect();
|
|
381
|
+
}
|
|
382
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
383
|
+
logger.debug('jwt.refresh.success', { method: 'reconnect', leaseId: newAssignment.leaseId });
|
|
384
|
+
return expMs;
|
|
385
|
+
};
|
|
386
|
+
const cpSession = createControlPlaneSession({
|
|
387
|
+
credentials,
|
|
388
|
+
tunnelType: 'http',
|
|
389
|
+
metadata: { baseClientId, localPort, secGroupSlug },
|
|
390
|
+
logger,
|
|
391
|
+
onRefreshLease: async () => {
|
|
392
|
+
const r = await onRefreshLease();
|
|
393
|
+
if (r) {
|
|
394
|
+
this.setState('renewed', { expMs: r });
|
|
395
|
+
this.setState('live');
|
|
396
|
+
}
|
|
397
|
+
return r;
|
|
398
|
+
},
|
|
399
|
+
instanceIdRef,
|
|
400
|
+
subscriptionReadyRef,
|
|
401
|
+
getTunnel: () => tunnelInstanceRef.tunnel,
|
|
402
|
+
});
|
|
403
|
+
mqttClient = cpSession.mqttClient;
|
|
404
|
+
this.mqttClient = mqttClient;
|
|
405
|
+
cpSession.events.on('connected', (e) => this.emit('control-connected', e));
|
|
406
|
+
cpSession.events.on('offline', (e) => this.emit('control-offline', e));
|
|
407
|
+
cpSession.events.on('fatal', (e) => this.emit('control-fatal', e));
|
|
408
|
+
const transport = new MqttControlPlaneTransport(mqttClient);
|
|
409
|
+
const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
|
|
410
|
+
this.core = core;
|
|
411
|
+
// CLI-IMG-ControlPlane-Watchdog: helpers for HttpTunnel
|
|
412
|
+
const isControlPlaneConnected = () => mqttClient.isOnline();
|
|
413
|
+
const waitForControlPlane = () => {
|
|
414
|
+
if (mqttClient.isOnline())
|
|
415
|
+
return Promise.resolve();
|
|
416
|
+
const start = Date.now();
|
|
417
|
+
return new Promise((resolve, reject) => {
|
|
418
|
+
const interval = setInterval(() => {
|
|
419
|
+
if (mqttClient.isOnline()) {
|
|
420
|
+
clearInterval(interval);
|
|
421
|
+
resolve();
|
|
422
|
+
}
|
|
423
|
+
else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
|
|
424
|
+
clearInterval(interval);
|
|
425
|
+
reject(new Error('control_plane_timeout'));
|
|
426
|
+
}
|
|
427
|
+
}, 250);
|
|
428
|
+
});
|
|
429
|
+
};
|
|
430
|
+
const getLastMqttError = () => null;
|
|
431
|
+
const getForceReconnect = () => async () => {
|
|
432
|
+
if (!mqttClient.isOnline()) {
|
|
433
|
+
await mqttClient.disconnect();
|
|
434
|
+
await mqttClient.connect();
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
// 3) Connect to control plane
|
|
438
|
+
try {
|
|
439
|
+
await mqttClient.connect();
|
|
440
|
+
}
|
|
441
|
+
catch (e) {
|
|
442
|
+
logger.error('mqtt.connect.failed', { error: e?.message || String(e) });
|
|
443
|
+
throw new ConnectionError('control_plane_connect_failed', e?.message || String(e), { cause: e });
|
|
444
|
+
}
|
|
445
|
+
// TPB-12: instanceId is the full MQTT clientId after connection
|
|
446
|
+
instanceIdRef.instanceId = mqttClient.getClientId();
|
|
447
|
+
const instanceId = instanceIdRef.instanceId;
|
|
448
|
+
logger.debug('cli.instance.registered', { instanceId, tunnelType: 'http', baseClientId });
|
|
449
|
+
// 4) Topics (baseClientId, not the session client id, keeps topics stable)
|
|
450
|
+
const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
|
|
451
|
+
const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
|
|
452
|
+
await core.subscribe(evtWildcard, 0);
|
|
453
|
+
// subscribe() resolves only after the broker acknowledges
|
|
454
|
+
subscriptionReadyRef.ready = true;
|
|
455
|
+
// 5) Message ingress and dispatcher
|
|
456
|
+
const ingress = new MessageIngress({ maxAwaiters: 100, observability: process.env.ASYX_DEBUG === '1', logger, onObserve: this.opts.onObserve });
|
|
457
|
+
ingress.setDispatcher(dispatchEvt);
|
|
458
|
+
const { registerInstance, setExpectedRequestId } = await import('../state/instance-registry.js');
|
|
459
|
+
const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import('../state/assignment.js');
|
|
460
|
+
registerInstance(instanceId, {
|
|
461
|
+
tunnelType: 'http',
|
|
462
|
+
setAssignment: setAssignmentFn,
|
|
463
|
+
getAssignment: getAssignmentFn,
|
|
464
|
+
metadata: { baseClientId, localPort, secGroupSlug },
|
|
465
|
+
});
|
|
466
|
+
// QPA-CLI-05: coordinator references for the renewal callback
|
|
467
|
+
coordinatorCoreRef = core;
|
|
468
|
+
coordinatorIngressRef = ingress;
|
|
469
|
+
// A reply that ends the tunnel closes it with a typed error (the CLI used to print and exit here).
|
|
470
|
+
core.onMessage(async (m) => {
|
|
471
|
+
try {
|
|
472
|
+
await ingress.handleMessage(m);
|
|
473
|
+
}
|
|
474
|
+
catch (e) {
|
|
475
|
+
let error;
|
|
476
|
+
if (e && e.code === 'SETUP_REQUIRED')
|
|
477
|
+
error = new SetupRequiredError('setup_required', e.message, { cause: e });
|
|
478
|
+
else if (e && typeof e.code === 'string' && e.code.startsWith('ERROR_'))
|
|
479
|
+
error = new RefusedError(e.code, e.message, { cause: e });
|
|
480
|
+
else
|
|
481
|
+
error = new InternalError('unexpected', e?.message || String(e), { cause: e });
|
|
482
|
+
try {
|
|
483
|
+
await core.end();
|
|
484
|
+
}
|
|
485
|
+
catch { }
|
|
486
|
+
this.setState('closed', { error });
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
// 6) Publish cmd/open request
|
|
490
|
+
const requestId = randomUUID();
|
|
491
|
+
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
492
|
+
const fingerprint = await getFpHash(credentials.clientId);
|
|
493
|
+
// TPB-12: Track expected requestId for pre-assignment routing
|
|
494
|
+
setExpectedRequestId(instanceId, requestId);
|
|
495
|
+
const openPayload = {
|
|
496
|
+
requestId,
|
|
497
|
+
instanceId, // TPB-12: Per-instance routing
|
|
498
|
+
proto: 'http',
|
|
499
|
+
localPort,
|
|
500
|
+
clientId: credentials.clientId,
|
|
501
|
+
...fingerprint,
|
|
502
|
+
};
|
|
503
|
+
// QPA-04: Include secGroupSlug in cmd/open payload if provided
|
|
504
|
+
if (secGroupSlug)
|
|
505
|
+
openPayload.secGroupSlug = secGroupSlug;
|
|
506
|
+
await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(openPayload), qos: 1, retain: false });
|
|
507
|
+
logger.info('cli.cmd.open.sent', { requestId, instanceId, tunnelType: 'http' });
|
|
508
|
+
// 7) Wait for ack
|
|
509
|
+
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
|
|
510
|
+
let assignment;
|
|
511
|
+
try {
|
|
512
|
+
const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
|
|
513
|
+
logger.info('cli.ack.wait.start', { requestId });
|
|
514
|
+
assignment = await assignmentPromise;
|
|
515
|
+
logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'http' });
|
|
516
|
+
logger.info('cli.assignment.received', { relayId: assignment.relayId, instanceId, tunnelType: 'http' });
|
|
517
|
+
// TPB-12: Persist assignment using per-instance store
|
|
518
|
+
try {
|
|
519
|
+
const { setAssignment } = await import('../state/assignment.js');
|
|
520
|
+
const { clearExpectedRequestId } = await import('../state/instance-registry.js');
|
|
521
|
+
setAssignment(instanceId, assignment);
|
|
522
|
+
clearExpectedRequestId(instanceId);
|
|
523
|
+
}
|
|
524
|
+
catch { }
|
|
525
|
+
}
|
|
526
|
+
catch (error) {
|
|
527
|
+
logger.error('cli.ack.wait.failed', { error: error.message });
|
|
528
|
+
try {
|
|
529
|
+
const { clearExpectedRequestId } = await import('../state/instance-registry.js');
|
|
530
|
+
clearExpectedRequestId(instanceId);
|
|
531
|
+
}
|
|
532
|
+
catch { }
|
|
533
|
+
try {
|
|
534
|
+
await core.end();
|
|
535
|
+
}
|
|
536
|
+
catch { }
|
|
537
|
+
throw new ConnectionError('assignment_failed', error.message, { cause: error });
|
|
538
|
+
}
|
|
539
|
+
// 8) Connect to the relay (was connectToRelay)
|
|
540
|
+
const { HttpTunnel } = await import('../tunnel/http-tunnel.js');
|
|
541
|
+
const tunnel = new HttpTunnel({
|
|
542
|
+
relayUrl: assignment.relayUrl,
|
|
543
|
+
jwt: assignment.jwt, // Use JWT as-is (no validation)
|
|
544
|
+
deviceId: credentials.clientId,
|
|
545
|
+
requestId: assignment.requestId,
|
|
546
|
+
localPort,
|
|
547
|
+
coordinatorCore: core,
|
|
548
|
+
coordinatorIngress: ingress,
|
|
549
|
+
isControlPlaneConnected,
|
|
550
|
+
waitForControlPlane,
|
|
551
|
+
getLastMqttError,
|
|
552
|
+
getForceReconnect,
|
|
553
|
+
controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS,
|
|
554
|
+
secGroupSlug,
|
|
555
|
+
instanceId,
|
|
556
|
+
requestSink: this.opts.requestSink, // Story 12.1 c3: default LocalPortSink(localPort)
|
|
557
|
+
log: adaptLogger(logger),
|
|
558
|
+
// Story 12.1 (c2): where the tunnel used to exit(1) it now ends with a typed error, and what it
|
|
559
|
+
// used to print is a notice; the CLI keeps the exit code and the wording.
|
|
560
|
+
onFatal: (code) => this.setState('closed', { error: new ConnectionError(code, `http tunnel ended: ${code}`, { details: { exitCode: 1 } }) }),
|
|
561
|
+
onNotice: (code, details) => this.emit('notice', { code, ...details }),
|
|
562
|
+
});
|
|
563
|
+
tunnelInstanceRef.tunnel = tunnel;
|
|
564
|
+
this.tunnel = tunnel;
|
|
565
|
+
try {
|
|
566
|
+
await tunnel.open();
|
|
567
|
+
scheduleInitialHttpRefresh(mqttClient, assignment, logger);
|
|
568
|
+
logger.info('tunnel.active', { url: `http://localhost:${localPort}`, relayId: assignment.relayId, leaseMs: assignment.leaseMs });
|
|
569
|
+
}
|
|
570
|
+
catch (error) {
|
|
571
|
+
// As before: no cleanup here; the caller reports and exits.
|
|
572
|
+
logger.error('cli.tunnel.failed', { error: error.message });
|
|
573
|
+
throw new ConnectionError('tunnel_connect_failed', error.message, { cause: error });
|
|
574
|
+
}
|
|
575
|
+
this.assignment = assignment;
|
|
576
|
+
const info = { assignment, localPort, relayId: assignment.relayId, leaseMs: assignment.leaseMs, quickpassSlug: assignment.quickpassSlug };
|
|
577
|
+
this.setState('live', info);
|
|
578
|
+
return info;
|
|
579
|
+
}
|
|
580
|
+
/** Ask for a renewal now (SIGUSR2 in the CLI). */
|
|
581
|
+
attemptJwtRefresh() { return this.tunnel?.attemptJwtRefresh(); }
|
|
582
|
+
}
|
|
583
|
+
export function createHttpTunnel(opts) {
|
|
584
|
+
return new HttpTunnelHandle(opts);
|
|
585
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
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 TcpTunnelOptions {
|
|
5
|
+
credentials: ControlPlaneCredentials;
|
|
6
|
+
localPort: number;
|
|
7
|
+
/** "127.0.0.1:<port>" (TCP-S1). */
|
|
8
|
+
target: string;
|
|
9
|
+
/** Alias requested for the public hostname (e.g. for Minecraft). */
|
|
10
|
+
serviceName?: string | null;
|
|
11
|
+
/** Service kind, e.g. 'minecraft'. */
|
|
12
|
+
kind?: string | null;
|
|
13
|
+
/** A public port inside the tenant's block, or null for the coordinator's choice. */
|
|
14
|
+
requestedExternalPort?: number | null;
|
|
15
|
+
logger: Logger;
|
|
16
|
+
/** Called with each observability line when ASYX_DEBUG=1 (the CLI prints them). */
|
|
17
|
+
onObserve?: (line: string) => void;
|
|
18
|
+
}
|
|
19
|
+
/** Sent with 'assigned' when the coordinator's assignment arrives. */
|
|
20
|
+
export type TcpAssignedEvent = {
|
|
21
|
+
tcpAliasFqdn?: string;
|
|
22
|
+
srvProvisioned?: boolean;
|
|
23
|
+
srvFqdn?: string;
|
|
24
|
+
fqdn?: string;
|
|
25
|
+
publicPort?: number;
|
|
26
|
+
aliasRequestedButFailed?: boolean;
|
|
27
|
+
};
|
|
28
|
+
/** What open() resolves to and the 'live' state carries. */
|
|
29
|
+
export type TcpTunnelInfo = {
|
|
30
|
+
assignment: Record<string, any>;
|
|
31
|
+
localPort: number;
|
|
32
|
+
relayId: string;
|
|
33
|
+
publicPort?: number;
|
|
34
|
+
fqdn?: string;
|
|
35
|
+
leaseMs?: number;
|
|
36
|
+
};
|
|
37
|
+
export declare class TcpTunnelHandle extends LifecycleEmitter {
|
|
38
|
+
readonly opts: TcpTunnelOptions & {
|
|
39
|
+
serviceName: string | null;
|
|
40
|
+
kind: string | null;
|
|
41
|
+
requestedExternalPort: number | null;
|
|
42
|
+
};
|
|
43
|
+
tunnel: any;
|
|
44
|
+
mqttClient: any;
|
|
45
|
+
core: any;
|
|
46
|
+
assignment: Record<string, any> | null;
|
|
47
|
+
constructor(o: TcpTunnelOptions);
|
|
48
|
+
/** Connect the control plane, get a lease and open the data plane; rejects with a typed error. */
|
|
49
|
+
open(): Promise<TcpTunnelInfo>;
|
|
50
|
+
/** Close the data plane, then the control plane. */
|
|
51
|
+
close(): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* TPB-17: schedule the first TCP renewal from the assignment token's expiry (moved unchanged from
|
|
55
|
+
* connectToRelayTcp; exported so its behaviour can be tested on its own).
|
|
56
|
+
*/
|
|
57
|
+
export declare function scheduleInitialTcpRefresh(mqttClient: {
|
|
58
|
+
scheduleRefresh(expMs: number, leaseId: string): void;
|
|
59
|
+
} | null, assignment: Record<string, any>, logger: Logger): void;
|
|
60
|
+
export declare function createTcpTunnel(opts: TcpTunnelOptions): TcpTunnelHandle;
|