asyx 0.10.1 → 0.11.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/AGENTS.md +42 -0
- package/bin/asyx.js +1 -1
- package/package.json +8 -2
- 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 -932
- package/src/commands/validate-target-host.js +36 -59
- package/src/lib/aws-iot-config.js +26 -24
- 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 +17 -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 +22 -74
- 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,17 +1,11 @@
|
|
|
1
|
-
// HTTP Tunnel - Pure proxy mode with no JWT validation
|
|
2
|
-
// Ported from client-mvp/src/tunnel.js with JWT validation stripped
|
|
3
1
|
import WebSocket from 'ws';
|
|
4
2
|
import crypto from 'node:crypto';
|
|
5
|
-
// CLI-REAUTH: Control frame helper for in-band reauth
|
|
6
3
|
import { sendControlAndWaitAck, dispatchControlFrame, clearAllWaiters } from './ws-control.js';
|
|
7
4
|
import { LocalPortSink } from './request-sink.js';
|
|
8
|
-
// S-3: Import HTTP-WS v2 protocol constants
|
|
9
5
|
import { HTTPWS_V2_TARGET_CHUNK_BYTES, HTTPWS_V2_MAX_CHUNK_BYTES, HTTP_BODY_CHUNK } from './httpws-constants.js';
|
|
10
|
-
const V2_THRESHOLD_BYTES = 8 * 1024 * 1024;
|
|
11
|
-
// Defect 11.9: the relay accepts WebSocket messages up to 16 MiB (wsProxy maxPayload); a larger
|
|
12
|
-
// one closes the whole tunnel (1009). A v1 response frame carries the body in base64.
|
|
6
|
+
const V2_THRESHOLD_BYTES = 8 * 1024 * 1024;
|
|
13
7
|
const RELAY_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
14
|
-
const V1_MAX_FRAME_BYTES = RELAY_MAX_MESSAGE_BYTES - 64 * 1024;
|
|
8
|
+
const V1_MAX_FRAME_BYTES = RELAY_MAX_MESSAGE_BYTES - 64 * 1024;
|
|
15
9
|
const HELLO_RETRY_MS = 3000;
|
|
16
10
|
const HELLO_MAX_ATTEMPTS = 3;
|
|
17
11
|
const TUNNEL_DROP_HEADERS = new Set([
|
|
@@ -66,80 +60,51 @@ function sanitizeLocalRequest(url, headers, bodyBuffer, localPort) {
|
|
|
66
60
|
}
|
|
67
61
|
return { path: url, headers: out };
|
|
68
62
|
}
|
|
69
|
-
// Story 3.8: what a visitor sees while the tunnel owner's local service is down or restarting.
|
|
70
63
|
export const LOCAL_UNAVAILABLE_PAGE = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Service not reachable</title></head><body style="font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#334155"><h1 style="font-size:1.4rem;color:#0f172a">This service is not reachable right now</h1><p>The tunnel is up, but the app behind it is not answering. It may be restarting; try again in a moment.</p></body></html>';
|
|
71
64
|
export class HttpTunnel {
|
|
72
|
-
constructor({ relayUrl, jwt, deviceId, requestId, localPort, log, coordinatorCore, coordinatorIngress,
|
|
73
|
-
// CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
|
|
74
|
-
isControlPlaneConnected = () => true, waitForControlPlane = () => Promise.resolve(), getLastMqttError = () => null, // QPA-CLI-02: Get last MQTT error for diagnostics
|
|
75
|
-
getForceReconnect = () => null, // QPA-CLI-03: Get force reconnect function
|
|
76
|
-
controlPlaneTimeoutMs = 60000,
|
|
77
|
-
// QPA-04: QuickPass security group slug
|
|
78
|
-
secGroupSlug = null,
|
|
79
|
-
// TPB-12: Instance ID for per-instance assignment routing
|
|
80
|
-
instanceId = null,
|
|
81
|
-
// Story 12.1 (c2): the core never exits or prints. onFatal(code) is called where the CLI used to
|
|
82
|
-
// exit(1); onNotice(code, details) where it used to print. Without onFatal, a fatal condition throws.
|
|
83
|
-
onFatal = null, onNotice = null, onLeaseClosed = null, // Story 3.13: reopen after the relay closed this lease (4000 lease_closed)
|
|
84
|
-
// Story 12.1 c3: where received requests go; defaults to the local service on localPort
|
|
85
|
-
requestSink = null, }) {
|
|
65
|
+
constructor({ relayUrl, jwt, deviceId, requestId, localPort, log, coordinatorCore, coordinatorIngress, isControlPlaneConnected = () => true, waitForControlPlane = () => Promise.resolve(), getLastMqttError = () => null, getForceReconnect = () => null, controlPlaneTimeoutMs = 60000, secGroupSlug = null, instanceId = null, onFatal = null, onNotice = null, onLeaseClosed = null, requestSink = null, }) {
|
|
86
66
|
this.requestSink = requestSink || new LocalPortSink(localPort);
|
|
87
67
|
this.onFatal = onFatal;
|
|
88
68
|
this.onLeaseClosed = onLeaseClosed;
|
|
89
69
|
this.onNotice = onNotice;
|
|
90
70
|
this.relayUrl = relayUrl;
|
|
91
|
-
this.jwt = jwt;
|
|
71
|
+
this.jwt = jwt;
|
|
92
72
|
this.deviceId = deviceId;
|
|
93
73
|
this.requestId = requestId;
|
|
94
74
|
this.localPort = localPort;
|
|
95
75
|
this.log = log;
|
|
96
76
|
this.ws = null;
|
|
97
|
-
// QPA-04: Store secGroupSlug for use in refresh payloads
|
|
98
77
|
this.secGroupSlug = secGroupSlug;
|
|
99
|
-
// TPB-12: Store instanceId for per-instance assignment lookups
|
|
100
78
|
this.instanceId = instanceId;
|
|
101
|
-
// CLI-IMG-WSReconnect: Coordinator connection for JWT refresh
|
|
102
79
|
this.coordinatorCore = coordinatorCore;
|
|
103
80
|
this.coordinatorIngress = coordinatorIngress;
|
|
104
|
-
// CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
|
|
105
81
|
this.isControlPlaneConnected = isControlPlaneConnected;
|
|
106
82
|
this.waitForControlPlane = waitForControlPlane;
|
|
107
|
-
this.getLastMqttError = getLastMqttError;
|
|
108
|
-
this.getForceReconnect = getForceReconnect;
|
|
83
|
+
this.getLastMqttError = getLastMqttError;
|
|
84
|
+
this.getForceReconnect = getForceReconnect;
|
|
109
85
|
this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
|
|
110
|
-
// CRT-Relay-E: Heartbeat properties
|
|
111
86
|
this.heartbeatTimer = null;
|
|
112
87
|
this.lastActivityMs = Date.now();
|
|
113
|
-
// CLI-IMG-WSReconnect: Reconnect properties
|
|
114
88
|
this.shouldReconnect = true;
|
|
115
89
|
this.retryCount = 0;
|
|
116
|
-
// CLI-IMG-Retry-Ceiling: Increase retry ceiling to 60 (configurable)
|
|
117
90
|
this.maxRetries = parseInt(process.env.ASYX_TUNNEL_MAX_RETRIES || "60", 10);
|
|
118
91
|
this.reconnectTimer = null;
|
|
119
|
-
this.headers = null;
|
|
120
|
-
|
|
121
|
-
// QPA-CLI-01: Extended states for resilience
|
|
122
|
-
this.refreshState = 'idle'; // idle | pending | waiting_control_plane | retry_scheduled | fallback | failed
|
|
92
|
+
this.headers = null;
|
|
93
|
+
this.refreshState = 'idle';
|
|
123
94
|
this.refreshAttempts = 0;
|
|
124
95
|
this.refreshMaxAttempts = parseInt(process.env.ASYX_TUNNEL_REFRESH_MAX_RETRIES || '3', 10);
|
|
125
|
-
// QPA-CLI-01: Refresh supervisor state
|
|
126
96
|
this.refreshRetryTimer = null;
|
|
127
|
-
this.refreshDeadline = null;
|
|
97
|
+
this.refreshDeadline = null;
|
|
128
98
|
this.refreshRetryCount = 0;
|
|
129
|
-
this.refreshRetryMaxDelay = 30000;
|
|
130
|
-
// CLI-RES-DPJWT-LEAD: Proactive refresh scheduling
|
|
99
|
+
this.refreshRetryMaxDelay = 30000;
|
|
131
100
|
this.refreshTimer = null;
|
|
132
|
-
this.jwtMeta = null;
|
|
133
|
-
this.LEAD_MS = Number(process.env.ASYX_REFRESH_LEAD_MS || 180000);
|
|
134
|
-
|
|
135
|
-
this.
|
|
136
|
-
this.reauthInFlight = null; // Single-flight guard: Promise or null
|
|
137
|
-
// S-0: Track negotiated HTTP-WS version
|
|
101
|
+
this.jwtMeta = null;
|
|
102
|
+
this.LEAD_MS = Number(process.env.ASYX_REFRESH_LEAD_MS || 180000);
|
|
103
|
+
this.reauthAckTimeoutMs = Number(process.env.CLI_REAUTH_ACK_TIMEOUT_MS || 3000);
|
|
104
|
+
this.reauthInFlight = null;
|
|
138
105
|
this.httpWsVersion = null;
|
|
139
|
-
// S-1: Track in-progress v2 responses (requestId -> { mode: 'v2', bufferedBytes: 0 })
|
|
140
106
|
this.activeV2Responses = new Map();
|
|
141
107
|
}
|
|
142
|
-
// CLI-RES-DPJWT-LEAD: Safe JWT decode helper
|
|
143
108
|
_decodeJwtExp(token) {
|
|
144
109
|
try {
|
|
145
110
|
if (!token || typeof token !== 'string') {
|
|
@@ -149,24 +114,21 @@ export class HttpTunnel {
|
|
|
149
114
|
if (parts.length !== 3) {
|
|
150
115
|
return null;
|
|
151
116
|
}
|
|
152
|
-
// Base64URL decode the payload (second part)
|
|
153
117
|
const payload = Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
|
|
154
118
|
const parsed = JSON.parse(payload);
|
|
155
119
|
if (!parsed.exp || typeof parsed.exp !== 'number') {
|
|
156
120
|
return null;
|
|
157
121
|
}
|
|
158
|
-
const expMs = parsed.exp * 1000;
|
|
122
|
+
const expMs = parsed.exp * 1000;
|
|
159
123
|
const nowMs = Date.now();
|
|
160
124
|
const issuedAtMs = parsed.iat ? parsed.iat * 1000 : null;
|
|
161
125
|
const skewMs = expMs - nowMs;
|
|
162
126
|
return { expMs, issuedAtMs, skewMs };
|
|
163
127
|
}
|
|
164
128
|
catch (err) {
|
|
165
|
-
// Malformed JWT - return null to skip scheduling
|
|
166
129
|
return null;
|
|
167
130
|
}
|
|
168
131
|
}
|
|
169
|
-
// CLI-REAUTH: Extract JTI from JWT for prev hint
|
|
170
132
|
_extractJti(token) {
|
|
171
133
|
try {
|
|
172
134
|
if (!token || typeof token !== 'string') {
|
|
@@ -184,22 +146,18 @@ export class HttpTunnel {
|
|
|
184
146
|
return null;
|
|
185
147
|
}
|
|
186
148
|
}
|
|
187
|
-
// CLI-RES-DPJWT-LEAD: Schedule proactive refresh
|
|
188
149
|
scheduleRefresh(token, context = 'unknown') {
|
|
189
|
-
// Clear existing timer
|
|
190
150
|
if (this.refreshTimer) {
|
|
191
151
|
clearTimeout(this.refreshTimer);
|
|
192
152
|
this.refreshTimer = null;
|
|
193
153
|
}
|
|
194
|
-
// Decode JWT to get exp
|
|
195
154
|
const decoded = this._decodeJwtExp(token);
|
|
196
155
|
if (!decoded) {
|
|
197
156
|
this.log.warn('jwt.refresh.schedule.invalid_token', { context });
|
|
198
|
-
return;
|
|
157
|
+
return;
|
|
199
158
|
}
|
|
200
159
|
const { expMs, issuedAtMs, skewMs } = decoded;
|
|
201
160
|
const nowMs = Date.now();
|
|
202
|
-
// CLI-RES-DPJWT-LEAD: Guard against short TTLs to prevent refresh loops
|
|
203
161
|
const ttlMs = expMs - (issuedAtMs ?? expMs - this.LEAD_MS);
|
|
204
162
|
if (ttlMs <= this.LEAD_MS) {
|
|
205
163
|
const adjusted = Math.max(30000, Math.floor(ttlMs / 4));
|
|
@@ -208,7 +166,6 @@ export class HttpTunnel {
|
|
|
208
166
|
this.LEAD_MS = adjusted;
|
|
209
167
|
}
|
|
210
168
|
}
|
|
211
|
-
// Check for clock skew warning (before determining refresh timing)
|
|
212
169
|
if (skewMs < this.LEAD_MS) {
|
|
213
170
|
this.log.warn('jwt.refresh.schedule.skew_warning', {
|
|
214
171
|
expEpochMs: expMs,
|
|
@@ -217,12 +174,8 @@ export class HttpTunnel {
|
|
|
217
174
|
context
|
|
218
175
|
});
|
|
219
176
|
}
|
|
220
|
-
|
|
221
|
-
const refreshAt = Math.min(expMs - this.LEAD_MS, issuedAtMs ? Math.max(issuedAtMs + 1000, expMs - this.LEAD_MS) : expMs - this.LEAD_MS, expMs - 30000 // Final 30s buffer
|
|
222
|
-
);
|
|
223
|
-
// Store JWT metadata for reconnect checks (before immediate check so _checkRefreshLeadWindow has accurate state)
|
|
177
|
+
const refreshAt = Math.min(expMs - this.LEAD_MS, issuedAtMs ? Math.max(issuedAtMs + 1000, expMs - this.LEAD_MS) : expMs - this.LEAD_MS, expMs - 30000);
|
|
224
178
|
this.jwtMeta = { token, expMs };
|
|
225
|
-
// Check if already in lead window
|
|
226
179
|
if (nowMs >= refreshAt) {
|
|
227
180
|
this.log.info('jwt.refresh.schedule.immediate', {
|
|
228
181
|
expEpochMs: expMs,
|
|
@@ -231,13 +184,11 @@ export class HttpTunnel {
|
|
|
231
184
|
skewMs,
|
|
232
185
|
context
|
|
233
186
|
});
|
|
234
|
-
// Trigger refresh immediately
|
|
235
187
|
this.attemptJwtRefresh().catch(err => {
|
|
236
188
|
this.log.error('jwt.refresh.immediate.failure', { error: err.message });
|
|
237
189
|
});
|
|
238
190
|
return;
|
|
239
191
|
}
|
|
240
|
-
// Schedule refresh
|
|
241
192
|
const delayMs = refreshAt - nowMs;
|
|
242
193
|
this.refreshTimer = setTimeout(() => {
|
|
243
194
|
this.refreshTimer = null;
|
|
@@ -250,7 +201,6 @@ export class HttpTunnel {
|
|
|
250
201
|
this.log.error('jwt.refresh.scheduled.failure', { error: err.message });
|
|
251
202
|
});
|
|
252
203
|
}, delayMs);
|
|
253
|
-
// Log scheduling
|
|
254
204
|
this.log.info('jwt.refresh.schedule', {
|
|
255
205
|
expEpochMs: expMs,
|
|
256
206
|
leadMs: this.LEAD_MS,
|
|
@@ -259,23 +209,18 @@ export class HttpTunnel {
|
|
|
259
209
|
context
|
|
260
210
|
});
|
|
261
211
|
}
|
|
262
|
-
// CLI-REAUTH: In-band reauth helper
|
|
263
212
|
async reauthInBand(newJwt, prevJti, trigger = 'timer') {
|
|
264
|
-
// Single-flight guard: if reauth already in progress, wait for it
|
|
265
213
|
if (this.reauthInFlight) {
|
|
266
214
|
return this.reauthInFlight;
|
|
267
215
|
}
|
|
268
216
|
const { getAssignment } = await import('../state/assignment.js');
|
|
269
|
-
// TPB-12: Use instanceId for per-instance assignment lookup
|
|
270
217
|
const assignment = getAssignment(this.instanceId);
|
|
271
218
|
if (!assignment || !assignment.leaseId) {
|
|
272
219
|
this.log.warn('jwt.reauth.error', { code: 'no_assignment', instanceId: this.instanceId });
|
|
273
220
|
return false;
|
|
274
221
|
}
|
|
275
|
-
// Calculate lead seconds for logging
|
|
276
222
|
const decoded = this._decodeJwtExp(newJwt);
|
|
277
223
|
const leadSeconds = decoded ? Math.floor((decoded.expMs - Date.now()) / 1000) : undefined;
|
|
278
|
-
// Build reauth payload
|
|
279
224
|
const payload = JSON.stringify({
|
|
280
225
|
op: 'reauth',
|
|
281
226
|
leaseId: assignment.leaseId,
|
|
@@ -287,22 +232,18 @@ export class HttpTunnel {
|
|
|
287
232
|
trigger,
|
|
288
233
|
leaseId: assignment.leaseId
|
|
289
234
|
});
|
|
290
|
-
// Create and store the promise for single-flight guard
|
|
291
235
|
const reauthPromise = (async () => {
|
|
292
236
|
try {
|
|
293
237
|
const ack = await sendControlAndWaitAck(this.ws, payload, 'reauth_ack', this.reauthAckTimeoutMs);
|
|
294
238
|
if (ack?.status === 'ok') {
|
|
295
|
-
// Update JWT and metadata
|
|
296
239
|
this.jwt = newJwt;
|
|
297
240
|
const expMs = ack.active?.exp ? ack.active.exp * 1000 : (decoded?.expMs || null);
|
|
298
241
|
this.jwtMeta = { token: newJwt, expMs };
|
|
299
|
-
// Update headers for future reconnects
|
|
300
242
|
this.headers = {
|
|
301
243
|
'Authorization': `Bearer ${this.jwt}`,
|
|
302
244
|
'X-Asyx-DeviceId': this.deviceId,
|
|
303
245
|
'X-Asyx-RequestId': assignment.requestId
|
|
304
246
|
};
|
|
305
|
-
// Re-schedule next proactive refresh
|
|
306
247
|
this.scheduleRefresh(this.jwt, 'reauth_success');
|
|
307
248
|
const ackLeadSeconds = ack.active?.exp
|
|
308
249
|
? Math.floor((ack.active.exp * 1000 - Date.now()) / 1000)
|
|
@@ -314,7 +255,6 @@ export class HttpTunnel {
|
|
|
314
255
|
});
|
|
315
256
|
return true;
|
|
316
257
|
}
|
|
317
|
-
// Error or timeout
|
|
318
258
|
const errorCode = ack?.error || 'timeout';
|
|
319
259
|
this.log.warn('jwt.reauth.error', {
|
|
320
260
|
code: errorCode,
|
|
@@ -331,7 +271,6 @@ export class HttpTunnel {
|
|
|
331
271
|
return false;
|
|
332
272
|
}
|
|
333
273
|
finally {
|
|
334
|
-
// Clear guard when done
|
|
335
274
|
if (this.reauthInFlight === reauthPromise) {
|
|
336
275
|
this.reauthInFlight = null;
|
|
337
276
|
}
|
|
@@ -340,14 +279,12 @@ export class HttpTunnel {
|
|
|
340
279
|
this.reauthInFlight = reauthPromise;
|
|
341
280
|
return reauthPromise;
|
|
342
281
|
}
|
|
343
|
-
// CLI-RES-DPJWT-LEAD: Check if refresh needed on reconnect
|
|
344
282
|
_checkRefreshLeadWindow() {
|
|
345
283
|
if (!this.jwtMeta || !this.jwtMeta.expMs) {
|
|
346
284
|
return false;
|
|
347
285
|
}
|
|
348
286
|
const nowMs = Date.now();
|
|
349
287
|
const { expMs } = this.jwtMeta;
|
|
350
|
-
// Check if we're in the lead window
|
|
351
288
|
if (nowMs + this.LEAD_MS >= expMs) {
|
|
352
289
|
this.log.info('jwt.refresh.schedule.immediate', {
|
|
353
290
|
expEpochMs: expMs,
|
|
@@ -356,7 +293,6 @@ export class HttpTunnel {
|
|
|
356
293
|
skewMs: expMs - nowMs,
|
|
357
294
|
context: 'reconnect_lead_window'
|
|
358
295
|
});
|
|
359
|
-
// Trigger refresh before resuming
|
|
360
296
|
this.attemptJwtRefresh().catch(err => {
|
|
361
297
|
this.log.error('jwt.refresh.reconnect.failure', { error: err.message });
|
|
362
298
|
});
|
|
@@ -364,41 +300,31 @@ export class HttpTunnel {
|
|
|
364
300
|
}
|
|
365
301
|
return false;
|
|
366
302
|
}
|
|
367
|
-
// CLI-IMG-Refresh-Guard: Ensure control-plane connectivity with timeout
|
|
368
|
-
// CLI-RES-WAITFORCONNECT: Updated to use transport.waitForConnect() directly
|
|
369
303
|
async _ensureControlPlane(reason, forceWait = false) {
|
|
370
304
|
if (!forceWait && this.isControlPlaneConnected())
|
|
371
305
|
return true;
|
|
372
|
-
// QPA-CLI-01: Log actual MQTT reason when control-plane is offline
|
|
373
306
|
const mqttReason = this.isControlPlaneConnected() ? 'connected' : 'offline';
|
|
374
307
|
this.log.warn({ reason, mqttReason }, "Control-plane offline, waiting for reconnect");
|
|
375
308
|
try {
|
|
376
|
-
// Use waitForControlPlane which internally calls transport.waitForConnect()
|
|
377
309
|
await this.waitForControlPlane();
|
|
378
|
-
// CLI-MQTT-UniqueID-CleanSession: Get session client ID from transport for logging
|
|
379
310
|
const lastMqttError = this.getLastMqttError ? this.getLastMqttError() : null;
|
|
380
311
|
const sessionClientId = lastMqttError?.clientId || 'unknown';
|
|
381
312
|
this.log.info({ reason, sessionClientId }, "Control-plane reconnected");
|
|
382
313
|
return true;
|
|
383
314
|
}
|
|
384
315
|
catch (err) {
|
|
385
|
-
// QPA-CLI-02: Get last MQTT error for diagnostic information
|
|
386
316
|
const lastMqttError = this.getLastMqttError ? this.getLastMqttError() : null;
|
|
387
317
|
const mqttReasonCode = lastMqttError?.code;
|
|
388
318
|
const mqttReason = lastMqttError?.reason || this._extractMqttReasonFromError(lastMqttError);
|
|
389
|
-
// QPA-CLI-01: Extract and log actual MQTT reason from WaitForConnectError
|
|
390
319
|
let mqttErrorReason = 'unknown';
|
|
391
320
|
if (err.name === 'WaitForConnectError') {
|
|
392
|
-
// WaitForConnectError has a 'reason' property: 'timeout' | 'terminated'
|
|
393
321
|
mqttErrorReason = err.reason || 'timeout';
|
|
394
|
-
// QPA-CLI-03: Force reconnect on timeout
|
|
395
322
|
if (mqttErrorReason === 'timeout' && this.getForceReconnect) {
|
|
396
323
|
const forceReconnect = this.getForceReconnect();
|
|
397
324
|
if (forceReconnect) {
|
|
398
325
|
this.log.info('mqtt.transport.force_reconnect.attempt', { reason, attempt: 1 });
|
|
399
326
|
try {
|
|
400
327
|
await forceReconnect();
|
|
401
|
-
// Retry waitForControlPlane up to 3 times with 5s delay
|
|
402
328
|
const maxRetries = 3;
|
|
403
329
|
const retryDelayMs = 5000;
|
|
404
330
|
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
@@ -424,7 +350,6 @@ export class HttpTunnel {
|
|
|
424
350
|
}
|
|
425
351
|
}
|
|
426
352
|
}
|
|
427
|
-
// QPA-CLI-02: Include MQTT error details in log
|
|
428
353
|
this.log.warn('mqtt.transport.wait_for_connect.failed', {
|
|
429
354
|
reason,
|
|
430
355
|
mqttReason: mqttErrorReason,
|
|
@@ -433,24 +358,22 @@ export class HttpTunnel {
|
|
|
433
358
|
mqttEvent: lastMqttError?.event,
|
|
434
359
|
error: err.message
|
|
435
360
|
});
|
|
436
|
-
this._notice('control_plane_offline', { reason: mqttErrorReason, mqttReason });
|
|
361
|
+
this._notice('control_plane_offline', { reason: mqttErrorReason, mqttReason });
|
|
437
362
|
return false;
|
|
438
363
|
}
|
|
439
364
|
if (err.message === "control_plane_timeout") {
|
|
440
|
-
// QPA-CLI-02: Include MQTT error details in timeout log
|
|
441
365
|
this.log.warn('mqtt.transport.wait_for_connect.timeout', {
|
|
442
366
|
reason,
|
|
443
367
|
mqttErrorCode: mqttReasonCode,
|
|
444
368
|
mqttErrorReason: mqttReason,
|
|
445
369
|
mqttEvent: lastMqttError?.event
|
|
446
370
|
});
|
|
447
|
-
this._notice('control_plane_timeout', { mqttReason });
|
|
371
|
+
this._notice('control_plane_timeout', { mqttReason });
|
|
448
372
|
return false;
|
|
449
373
|
}
|
|
450
374
|
throw err;
|
|
451
375
|
}
|
|
452
376
|
}
|
|
453
|
-
// QPA-CLI-02: Extract human-readable MQTT reason from error object
|
|
454
377
|
_extractMqttReasonFromError(mqttError) {
|
|
455
378
|
if (!mqttError)
|
|
456
379
|
return 'unknown';
|
|
@@ -469,7 +392,6 @@ export class HttpTunnel {
|
|
|
469
392
|
}
|
|
470
393
|
return 'unknown';
|
|
471
394
|
}
|
|
472
|
-
/** Story 12.1: report a fatal condition (formerly process.exit(1)) to the owner of the tunnel. */
|
|
473
395
|
_fatal(code, details = {}) {
|
|
474
396
|
if (this.onFatal) {
|
|
475
397
|
this.onFatal(code, details);
|
|
@@ -477,14 +399,10 @@ export class HttpTunnel {
|
|
|
477
399
|
}
|
|
478
400
|
throw new Error(`http tunnel ended: ${code}`);
|
|
479
401
|
}
|
|
480
|
-
/** Story 12.1: a message for the user (formerly printed here); the caller decides the wording. */
|
|
481
402
|
_notice(code, details = {}) {
|
|
482
403
|
if (this.onNotice)
|
|
483
404
|
this.onNotice(code, details);
|
|
484
405
|
}
|
|
485
|
-
// Story 3.8: the local service may be down or restarting. A request that cannot reach it gets a
|
|
486
|
-
// 502 page and the tunnel stays up; the caller hears once when the service becomes unreachable
|
|
487
|
-
// and once when it answers again (no notice or error log per request).
|
|
488
406
|
_localUnreachable(err) {
|
|
489
407
|
if (this.localServiceDown) {
|
|
490
408
|
this.log.debug({ port: this.localPort, code: err?.code }, 'local_service.still_unreachable');
|
|
@@ -501,7 +419,6 @@ export class HttpTunnel {
|
|
|
501
419
|
this.log.info({ port: this.localPort }, 'local_service.back');
|
|
502
420
|
this._notice('local_service_back', { port: this.localPort });
|
|
503
421
|
}
|
|
504
|
-
/** Story 3.8: the visitor's answer when the local service cannot be reached. */
|
|
505
422
|
sendLocalUnavailable(requestId) {
|
|
506
423
|
const responseData = {
|
|
507
424
|
t: 'http_response',
|
|
@@ -515,12 +432,10 @@ export class HttpTunnel {
|
|
|
515
432
|
}
|
|
516
433
|
}
|
|
517
434
|
async open() {
|
|
518
|
-
// CLI-IMG-WSReconnect: Start the connection process
|
|
519
435
|
return this._attemptConnect();
|
|
520
436
|
}
|
|
521
437
|
async _attemptConnect() {
|
|
522
438
|
return new Promise((resolve, reject) => {
|
|
523
|
-
// CLI-IMG-WSReconnect: Store headers for reuse during reconnects
|
|
524
439
|
if (!this.headers) {
|
|
525
440
|
this.headers = {
|
|
526
441
|
'Authorization': `Bearer ${this.jwt}`,
|
|
@@ -528,12 +443,9 @@ export class HttpTunnel {
|
|
|
528
443
|
'X-Asyx-RequestId': this.requestId
|
|
529
444
|
};
|
|
530
445
|
}
|
|
531
|
-
// CLI-IMG-WSReconnect: Clean up previous WebSocket if exists
|
|
532
446
|
if (this.ws) {
|
|
533
447
|
const old = this.ws;
|
|
534
448
|
old.removeAllListeners();
|
|
535
|
-
// Defect 11.10: a late error from the replaced socket must not crash the CLI
|
|
536
|
-
// (an 'error' event with no listener is thrown by Node)
|
|
537
449
|
old.on('error', () => { });
|
|
538
450
|
try {
|
|
539
451
|
if (old.readyState === WebSocket.OPEN || old.readyState === WebSocket.CONNECTING)
|
|
@@ -542,53 +454,38 @@ export class HttpTunnel {
|
|
|
542
454
|
catch (_) { }
|
|
543
455
|
this.ws = null;
|
|
544
456
|
}
|
|
545
|
-
// Connect to relay with TLS (rejectUnauthorized: true by default)
|
|
546
457
|
this.ws = new WebSocket(this.relayUrl, {
|
|
547
458
|
headers: this.headers,
|
|
548
|
-
rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1'
|
|
459
|
+
rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1'
|
|
549
460
|
});
|
|
550
461
|
this.ws.on('open', () => {
|
|
551
462
|
this.log.info({ relayUrl: this.relayUrl, localPort: this.localPort }, 'Tunnel WS open - proxy mode active');
|
|
552
|
-
// CLI-IMG-WSReconnect: Reset retry count on successful connection
|
|
553
463
|
this.retryCount = 0;
|
|
554
|
-
// S-0: Send hello frame for HTTP-WS v2 negotiation. Defect 11.9: negotiation is per
|
|
555
|
-
// connection (the relay checks it per connection), so forget the previous result
|
|
556
|
-
// and resend the hello until it is acknowledged.
|
|
557
464
|
this.httpWsVersion = null;
|
|
558
465
|
this._helloAttempts = 0;
|
|
559
466
|
this._sendHello();
|
|
560
|
-
// CLI-RES-DPJWT-LEAD: Check if refresh needed before resuming
|
|
561
467
|
this._checkRefreshLeadWindow();
|
|
562
|
-
// CRT-Relay-E: Start heartbeat timer after WebSocket opens
|
|
563
468
|
this.startHeartbeat();
|
|
564
469
|
resolve();
|
|
565
470
|
});
|
|
566
|
-
// Story 3.11: anything from the relay, including the pong the WebSocket protocol
|
|
567
|
-
// requires in answer to a ping, proves the connection is alive
|
|
568
471
|
this.ws.on('pong', () => { this.lastInboundMs = Date.now(); });
|
|
569
472
|
this.ws.on('message', (data, isBinary) => {
|
|
570
|
-
// CRT-Relay-E: Update activity on any message
|
|
571
473
|
this.lastActivityMs = Date.now();
|
|
572
474
|
this.lastInboundMs = this.lastActivityMs;
|
|
573
475
|
if (!isBinary) {
|
|
574
476
|
try {
|
|
575
477
|
const msg = JSON.parse(data.toString());
|
|
576
|
-
// CLI-REAUTH: Dispatch control frames to waiter registry
|
|
577
478
|
if (msg.op && typeof msg.op === 'string') {
|
|
578
479
|
if (dispatchControlFrame(msg)) {
|
|
579
|
-
// Control frame was dispatched to a waiter, don't process further
|
|
580
480
|
return;
|
|
581
481
|
}
|
|
582
|
-
// Control frame but no waiters - ignore unknown ops
|
|
583
482
|
this.log.debug('jwt.reauth.unknown_control', { op: msg.op });
|
|
584
483
|
return;
|
|
585
484
|
}
|
|
586
|
-
// CRT-Relay-E: Handle heartbeat pong
|
|
587
485
|
if (msg.t === 'pong') {
|
|
588
486
|
this.log.debug('tunnel heartbeat pong received');
|
|
589
487
|
return;
|
|
590
488
|
}
|
|
591
|
-
// S-0: Handle hello_ack for HTTP-WS v2 negotiation
|
|
592
489
|
if (msg.type === 'hello_ack') {
|
|
593
490
|
this._handleHelloAck(msg);
|
|
594
491
|
return;
|
|
@@ -604,20 +501,17 @@ export class HttpTunnel {
|
|
|
604
501
|
}
|
|
605
502
|
catch (_) { }
|
|
606
503
|
}
|
|
607
|
-
// Handle binary messages that look like HTTP requests
|
|
608
504
|
const dataStr = data.toString();
|
|
609
505
|
if (dataStr.startsWith('GET ') || dataStr.startsWith('POST ') || dataStr.startsWith('PUT ') ||
|
|
610
506
|
dataStr.startsWith('DELETE ') || dataStr.startsWith('PATCH ') || dataStr.startsWith('HEAD ') ||
|
|
611
507
|
dataStr.startsWith('OPTIONS ')) {
|
|
612
|
-
this.handleHttpRequestBuffer(Buffer.from(
|
|
508
|
+
this.handleHttpRequestBuffer(Buffer.from((data)));
|
|
613
509
|
}
|
|
614
510
|
else {
|
|
615
|
-
// Ignore binary messages that look like HTTP responses
|
|
616
511
|
this.log.debug('Ignoring binary message (likely HTTP response)');
|
|
617
512
|
}
|
|
618
513
|
});
|
|
619
514
|
this.ws.on('close', (code, reason) => {
|
|
620
|
-
// QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
|
|
621
515
|
const reasonStr = reason?.toString() || '';
|
|
622
516
|
const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
|
|
623
517
|
if (isNormalClose) {
|
|
@@ -626,51 +520,38 @@ export class HttpTunnel {
|
|
|
626
520
|
else {
|
|
627
521
|
this.log.warn({ code, reason: reasonStr }, 'Tunnel WS closed');
|
|
628
522
|
}
|
|
629
|
-
// CRT-Relay-E: Stop heartbeat on close
|
|
630
523
|
this.stopHeartbeat();
|
|
631
|
-
// CLI-REAUTH: Cleanup control frame waiters on socket close
|
|
632
524
|
clearAllWaiters();
|
|
633
|
-
// Clear single-flight guard
|
|
634
525
|
this.reauthInFlight = null;
|
|
635
|
-
// Story 3.13: the relay closed this lease (the cloud closed it): reconnecting with the same token
|
|
636
|
-
// would be refused every time; reopen on the same address instead, or end saying why.
|
|
637
526
|
if (code === 4000 && reasonStr === 'lease_closed' && this.onLeaseClosed && this.shouldReconnect) {
|
|
638
|
-
this.onLeaseClosed().then((ok) => {
|
|
639
|
-
|
|
527
|
+
this.onLeaseClosed().then((ok) => {
|
|
528
|
+
if (!ok)
|
|
529
|
+
this._fatal('lease_closed_reopen_refused');
|
|
530
|
+
}).catch(() => this._fatal('lease_closed_reopen_refused'));
|
|
640
531
|
return;
|
|
641
532
|
}
|
|
642
|
-
// CLI-IMG-WSReconnect: Schedule reconnect instead of exiting
|
|
643
533
|
this.scheduleReconnect(code, reason);
|
|
644
534
|
});
|
|
645
535
|
this.ws.on('error', (err) => {
|
|
646
536
|
this.log.error({ err }, 'Tunnel WS error');
|
|
647
|
-
// CRT-Relay-E: Stop heartbeat on error
|
|
648
537
|
this.stopHeartbeat();
|
|
649
|
-
// CLI-IMG-WSReconnect: Handle connection errors with reconnect
|
|
650
538
|
this.scheduleReconnect(null, err.message);
|
|
651
539
|
});
|
|
652
540
|
});
|
|
653
541
|
}
|
|
654
|
-
// CLI-IMG-WSReconnect: Reconnect scheduling and logic
|
|
655
542
|
scheduleReconnect(code, reason) {
|
|
656
|
-
// Check if we should reconnect
|
|
657
543
|
if (!this.shouldReconnect) {
|
|
658
544
|
this.log.info('Reconnect disabled, returning');
|
|
659
545
|
return;
|
|
660
546
|
}
|
|
661
|
-
// Defect 11.10: 'error' and 'close' both fire for one failed attempt; schedule once, so the
|
|
662
|
-
// backoff advances one step per attempt and two connects never race each other
|
|
663
547
|
if (this.reconnectTimer) {
|
|
664
548
|
this.log.debug({ code, reason }, 'Reconnect already scheduled');
|
|
665
549
|
return;
|
|
666
550
|
}
|
|
667
|
-
// CLI-IMG-Retry-Ceiling: Check retry limit with descriptive messaging
|
|
668
551
|
if (this.retryCount >= this.maxRetries) {
|
|
669
552
|
this.log.error({ retryCount: this.retryCount, maxRetries: this.maxRetries }, "Control-plane reconnect attempts exhausted; please restart the CLI");
|
|
670
|
-
return this._fatal('reconnect_exhausted');
|
|
553
|
+
return this._fatal('reconnect_exhausted');
|
|
671
554
|
}
|
|
672
|
-
// Check for JWT expiration - attempt refresh instead of exiting
|
|
673
|
-
// Handle both jwt_invalid (code 1000) and EJWT_EXPIRED (code 1008) cases
|
|
674
555
|
const reasonStr = reason?.toString() || '';
|
|
675
556
|
const lower = reasonStr.toLowerCase();
|
|
676
557
|
const isJwtInvalid = code === 1000 && lower.includes('jwt_invalid');
|
|
@@ -681,12 +562,10 @@ export class HttpTunnel {
|
|
|
681
562
|
this.attemptJwtRefresh();
|
|
682
563
|
return;
|
|
683
564
|
}
|
|
684
|
-
|
|
685
|
-
const
|
|
686
|
-
const jitter = Math.random() * 0.4 - 0.2; // ±20% jitter
|
|
565
|
+
const baseDelay = Math.min(1000 * Math.pow(2, this.retryCount), 30000);
|
|
566
|
+
const jitter = Math.random() * 0.4 - 0.2;
|
|
687
567
|
const delay = Math.max(1000, Math.floor(baseDelay * (1 + jitter)));
|
|
688
568
|
this.retryCount++;
|
|
689
|
-
// QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
|
|
690
569
|
const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
|
|
691
570
|
if (isNormalClose) {
|
|
692
571
|
this.log.debug({
|
|
@@ -706,7 +585,6 @@ export class HttpTunnel {
|
|
|
706
585
|
reason: reasonStr
|
|
707
586
|
}, 'Tunnel WS reconnect scheduled');
|
|
708
587
|
}
|
|
709
|
-
// Schedule reconnect attempt
|
|
710
588
|
this.reconnectTimer = setTimeout(() => {
|
|
711
589
|
this.reconnectTimer = null;
|
|
712
590
|
this.attemptReconnect();
|
|
@@ -717,7 +595,6 @@ export class HttpTunnel {
|
|
|
717
595
|
this.log.info({ retryCount: this.retryCount }, 'Attempting to reconnect...');
|
|
718
596
|
await this._attemptConnect();
|
|
719
597
|
this.log.info('Reconnected successfully');
|
|
720
|
-
// CLI-IMG-WSReconnect: Clear reconnect timer on successful reconnect
|
|
721
598
|
if (this.reconnectTimer) {
|
|
722
599
|
clearTimeout(this.reconnectTimer);
|
|
723
600
|
this.reconnectTimer = null;
|
|
@@ -725,19 +602,14 @@ export class HttpTunnel {
|
|
|
725
602
|
}
|
|
726
603
|
catch (error) {
|
|
727
604
|
this.log.error({ error: error.message, retryCount: this.retryCount }, 'Reconnect attempt failed');
|
|
728
|
-
// scheduleReconnect will be called from the error handler in _attemptConnect
|
|
729
605
|
}
|
|
730
606
|
}
|
|
731
|
-
// QPA-CLI-01: Schedule retry with exponential backoff
|
|
732
607
|
_scheduleRefreshRetry(reason) {
|
|
733
|
-
// Clear any existing retry timer
|
|
734
608
|
if (this.refreshRetryTimer) {
|
|
735
609
|
clearTimeout(this.refreshRetryTimer);
|
|
736
610
|
this.refreshRetryTimer = null;
|
|
737
611
|
}
|
|
738
|
-
// QPA-CLI-03: Check if we've exceeded the deadline AND MQTT is still offline
|
|
739
612
|
if (this.refreshDeadline && Date.now() >= this.refreshDeadline) {
|
|
740
|
-
// Only mark expired if control plane is still offline
|
|
741
613
|
if (!this.isControlPlaneConnected()) {
|
|
742
614
|
this.log.error('jwt.refresh.expired', {
|
|
743
615
|
retryCount: this.refreshRetryCount,
|
|
@@ -745,22 +617,19 @@ export class HttpTunnel {
|
|
|
745
617
|
elapsed: Date.now() - (this.refreshDeadline - this.LEAD_MS)
|
|
746
618
|
});
|
|
747
619
|
this.refreshState = 'failed';
|
|
748
|
-
this._notice('jwt_expired_offline');
|
|
749
|
-
return this._fatal('jwt_expired_offline');
|
|
620
|
+
this._notice('jwt_expired_offline');
|
|
621
|
+
return this._fatal('jwt_expired_offline');
|
|
750
622
|
}
|
|
751
623
|
else {
|
|
752
|
-
// Control plane came back, reset deadline and continue
|
|
753
624
|
this.log.info('jwt.refresh.deadline_extended', {
|
|
754
625
|
retryCount: this.refreshRetryCount,
|
|
755
626
|
oldDeadline: this.refreshDeadline
|
|
756
627
|
});
|
|
757
|
-
// Extend deadline by another 90 seconds
|
|
758
628
|
this.refreshDeadline = Date.now() + 90000;
|
|
759
629
|
}
|
|
760
630
|
}
|
|
761
|
-
// Calculate exponential backoff delay
|
|
762
631
|
this.refreshRetryCount += 1;
|
|
763
|
-
const baseDelay = 5000;
|
|
632
|
+
const baseDelay = 5000;
|
|
764
633
|
const delayMs = Math.min(baseDelay * Math.pow(2, this.refreshRetryCount - 1), this.refreshRetryMaxDelay);
|
|
765
634
|
this.log.info('jwt.refresh.delay', {
|
|
766
635
|
reason: 'control_plane_offline',
|
|
@@ -768,18 +637,15 @@ export class HttpTunnel {
|
|
|
768
637
|
nextDelayMs: delayMs,
|
|
769
638
|
deadline: this.refreshDeadline ? new Date(this.refreshDeadline).toISOString() : null
|
|
770
639
|
});
|
|
771
|
-
|
|
772
|
-
this._notice('quickpass_refresh_delayed', { retry: this.refreshRetryCount }); // Story 12.1: the CLI prints it
|
|
640
|
+
this._notice('quickpass_refresh_delayed', { retry: this.refreshRetryCount });
|
|
773
641
|
this.refreshState = 'retry_scheduled';
|
|
774
642
|
this.refreshRetryTimer = setTimeout(() => {
|
|
775
643
|
this.refreshRetryTimer = null;
|
|
776
|
-
// Retry the refresh
|
|
777
644
|
this.attemptJwtRefresh().catch(err => {
|
|
778
645
|
this.log.error('jwt.refresh.retry.failed', { error: err.message, retryCount: this.refreshRetryCount });
|
|
779
646
|
});
|
|
780
647
|
}, delayMs);
|
|
781
648
|
}
|
|
782
|
-
// QPA-CLI-01: Cancel scheduled retry (called when MQTT reconnects)
|
|
783
649
|
_cancelRefreshRetry() {
|
|
784
650
|
if (this.refreshRetryTimer) {
|
|
785
651
|
clearTimeout(this.refreshRetryTimer);
|
|
@@ -790,91 +656,69 @@ export class HttpTunnel {
|
|
|
790
656
|
this.refreshState = 'pending';
|
|
791
657
|
}
|
|
792
658
|
}
|
|
793
|
-
// CLI-IMG-WSReconnect: JWT refresh logic
|
|
794
659
|
async attemptJwtRefresh() {
|
|
795
660
|
try {
|
|
796
|
-
// QPA-CLI-01: Check if we've exceeded max attempts (only for actual refresh attempts, not retries)
|
|
797
661
|
if (this.refreshAttempts >= this.refreshMaxAttempts && this.refreshState !== 'retry_scheduled' && this.refreshState !== 'waiting_control_plane') {
|
|
798
662
|
this.log.error('jwt.refresh.exhausted', { retryCount: this.refreshAttempts });
|
|
799
663
|
this.refreshState = 'failed';
|
|
800
|
-
return this._fatal('refresh_exhausted');
|
|
664
|
+
return this._fatal('refresh_exhausted');
|
|
801
665
|
}
|
|
802
|
-
// QPA-CLI-01: Set refresh deadline on first attempt
|
|
803
666
|
if (this.refreshState === 'idle' && this.jwtMeta?.expMs) {
|
|
804
|
-
const safetyMargin = 90000;
|
|
667
|
+
const safetyMargin = 90000;
|
|
805
668
|
this.refreshDeadline = this.jwtMeta.expMs - safetyMargin;
|
|
806
|
-
this.refreshRetryCount = 0;
|
|
669
|
+
this.refreshRetryCount = 0;
|
|
807
670
|
}
|
|
808
671
|
this.refreshAttempts += 1;
|
|
809
672
|
this.refreshState = 'pending';
|
|
810
673
|
this.log.info('jwt.refresh.start', { retryCount: this.refreshAttempts });
|
|
811
|
-
// QPA-CLI-01: Ensure control-plane connectivity with retry logic
|
|
812
674
|
const ready = await this._ensureControlPlane("jwt_refresh");
|
|
813
675
|
if (!ready) {
|
|
814
|
-
// QPA-CLI-01: Instead of immediately falling back, schedule a retry
|
|
815
676
|
this.refreshState = 'waiting_control_plane';
|
|
816
677
|
this._scheduleRefreshRetry('control_plane_offline');
|
|
817
|
-
return;
|
|
678
|
+
return;
|
|
818
679
|
}
|
|
819
|
-
// QPA-CLI-01: Control-plane is ready, cancel any pending retry
|
|
820
680
|
this._cancelRefreshRetry();
|
|
821
|
-
// Check if we have coordinator connection
|
|
822
681
|
if (!this.coordinatorCore || !this.coordinatorIngress) {
|
|
823
682
|
this.log.error('jwt.refresh.no_coordinator');
|
|
824
|
-
return this._fatal('refresh_no_coordinator');
|
|
683
|
+
return this._fatal('refresh_no_coordinator');
|
|
825
684
|
}
|
|
826
|
-
// Import assignment functions
|
|
827
685
|
const { getAssignment } = await import('../state/assignment.js');
|
|
828
686
|
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
829
|
-
// TPB-12: Get current assignment for this specific instance
|
|
830
687
|
const currentAssignment = getAssignment(this.instanceId);
|
|
831
688
|
if (!currentAssignment) {
|
|
832
689
|
this.log.error('jwt.refresh.no_current_assignment', { instanceId: this.instanceId });
|
|
833
|
-
return this._fatal('refresh_no_current_assignment');
|
|
690
|
+
return this._fatal('refresh_no_current_assignment');
|
|
834
691
|
}
|
|
835
|
-
|
|
836
|
-
const refreshRequestId = `refresh-${crypto.randomUUID()}` /* Defect 11.27: unique across processes (was Date.now()) */; // New requestId for refresh
|
|
692
|
+
const refreshRequestId = `refresh-${crypto.randomUUID()}`;
|
|
837
693
|
const leaseId = currentAssignment.leaseId;
|
|
838
694
|
if (!leaseId) {
|
|
839
695
|
this.log.error('jwt.refresh.no_lease_id');
|
|
840
|
-
return this._fatal('refresh_no_lease_id');
|
|
696
|
+
return this._fatal('refresh_no_lease_id');
|
|
841
697
|
}
|
|
842
|
-
// Get fingerprint for the refresh request
|
|
843
698
|
const fingerprint = await getFpHash(this.deviceId);
|
|
844
|
-
// Build refresh payload - use refreshOf field to reuse existing lease
|
|
845
|
-
// CLI-RES-COORD-EVENTBRIDGE: Do NOT set reconnect: true for JWT refresh.
|
|
846
|
-
// Reconnect is only for re-establishing after disconnection; refresh should only use refreshOf.
|
|
847
|
-
/** @type {Record<string, any>} */
|
|
848
699
|
const refreshPayload = {
|
|
849
|
-
requestId: refreshRequestId,
|
|
850
|
-
refreshOf: leaseId,
|
|
851
|
-
// reconnect: true removed - this is JWT refresh, not reconnect
|
|
700
|
+
requestId: refreshRequestId,
|
|
701
|
+
refreshOf: leaseId,
|
|
852
702
|
proto: 'http',
|
|
853
703
|
localPort: this.localPort,
|
|
854
704
|
clientId: this.deviceId,
|
|
855
705
|
...fingerprint
|
|
856
706
|
};
|
|
857
|
-
// QPA-04: Include secGroupSlug in refresh payload if provided
|
|
858
707
|
if (this.secGroupSlug) {
|
|
859
708
|
refreshPayload.secGroupSlug = this.secGroupSlug;
|
|
860
709
|
}
|
|
861
|
-
// Set up topic for refresh request
|
|
862
710
|
const cmdOpenTopic = `asyx/tunnel/clients/${this.deviceId}/cmd/open`;
|
|
863
|
-
// Wait for open_ack with timeout
|
|
864
711
|
const ackPromise = this.coordinatorIngress.registerAwaiter((message) => {
|
|
865
712
|
try {
|
|
866
713
|
const parsed = message.payload;
|
|
867
|
-
// Story 3.13: an open_reject for this renewal (lease_closed) is an answer too, not a timeout
|
|
868
714
|
return parsed && (parsed.type === 'open_ack' || parsed.type === 'open_reject') && parsed.requestId === refreshRequestId;
|
|
869
715
|
}
|
|
870
716
|
catch (e) {
|
|
871
717
|
return false;
|
|
872
718
|
}
|
|
873
719
|
}, 10000);
|
|
874
|
-
let ackMsg = null;
|
|
875
|
-
// CLI-IMG-MQTT-Resilience: Publish with retry logic and fallback
|
|
720
|
+
let ackMsg = null;
|
|
876
721
|
try {
|
|
877
|
-
// Publish the refresh request
|
|
878
722
|
await this.coordinatorCore.publish({
|
|
879
723
|
topic: cmdOpenTopic,
|
|
880
724
|
payload: JSON.stringify(refreshPayload),
|
|
@@ -882,12 +726,10 @@ export class HttpTunnel {
|
|
|
882
726
|
retain: false
|
|
883
727
|
});
|
|
884
728
|
this.log.info('jwt.refresh.request.sent', { refreshRequestId, retryCount: this.refreshAttempts });
|
|
885
|
-
// Wait for new assignment with timeout handling
|
|
886
729
|
try {
|
|
887
730
|
ackMsg = await ackPromise;
|
|
888
731
|
}
|
|
889
732
|
catch (timeoutError) {
|
|
890
|
-
// Story 3.13: the coordinator says this lease is closed: reopen on the same address, or end saying why
|
|
891
733
|
if ((timeoutError?.code === 'LEASE_CLOSED' || timeoutError?.reason === 'lease_closed') && this.onLeaseClosed) {
|
|
892
734
|
this.log.warn('jwt.refresh.lease_closed', { retryCount: this.refreshAttempts });
|
|
893
735
|
const ok = await this.onLeaseClosed().catch(() => false);
|
|
@@ -896,7 +738,6 @@ export class HttpTunnel {
|
|
|
896
738
|
return;
|
|
897
739
|
}
|
|
898
740
|
this.log.warn('jwt.refresh.timeout', { retryCount: this.refreshAttempts, error: timeoutError.message });
|
|
899
|
-
// CLI-IMG-MQTT-Resilience: Fallback to fresh tunnel when awaiter times out
|
|
900
741
|
await this._fallbackToFreshTunnel();
|
|
901
742
|
return;
|
|
902
743
|
}
|
|
@@ -904,11 +745,9 @@ export class HttpTunnel {
|
|
|
904
745
|
catch (publishError) {
|
|
905
746
|
this.log.warn('jwt.refresh.publish_failed', { retryCount: this.refreshAttempts, error: publishError.message });
|
|
906
747
|
await this._ensureControlPlane('jwt_refresh_retry', true);
|
|
907
|
-
// CLI-IMG-MQTT-Resilience: Fallback to fresh tunnel when publish fails
|
|
908
748
|
await this._fallbackToFreshTunnel();
|
|
909
749
|
return;
|
|
910
750
|
}
|
|
911
|
-
// Story 3.13: the coordinator refused the renewal: a closed lease reopens on the same address
|
|
912
751
|
const rejected = ackMsg?.payload?.type === 'open_reject' ? ackMsg.payload : null;
|
|
913
752
|
if (rejected) {
|
|
914
753
|
const why = String(rejected.data?.reason || rejected.reason || '').toLowerCase();
|
|
@@ -922,23 +761,17 @@ export class HttpTunnel {
|
|
|
922
761
|
this.log.error('jwt.refresh.refused', { reason: why });
|
|
923
762
|
return this._fatal('refresh_refused', { reason: why });
|
|
924
763
|
}
|
|
925
|
-
// TPB-12: Get the new assignment for this specific instance
|
|
926
764
|
const newAssignment = getAssignment(this.instanceId);
|
|
927
765
|
if (!newAssignment) {
|
|
928
766
|
this.log.error('jwt.refresh.no_new_assignment', { instanceId: this.instanceId });
|
|
929
|
-
return this._fatal('refresh_no_new_assignment');
|
|
767
|
+
return this._fatal('refresh_no_new_assignment');
|
|
930
768
|
}
|
|
931
|
-
// CLI-REAUTH: Try in-band reauth if WebSocket is open, otherwise fallback to reconnect
|
|
932
769
|
const prevJti = this.jwtMeta?.token ? this._extractJti(this.jwtMeta.token) : null;
|
|
933
770
|
const newJwt = newAssignment.jwt;
|
|
934
|
-
|
|
935
|
-
if (this.ws && this.ws.readyState === 1) { // WebSocket.OPEN = 1
|
|
936
|
-
// Start in-band reauth (guard is inside reauthInBand)
|
|
771
|
+
if (this.ws && this.ws.readyState === 1) {
|
|
937
772
|
try {
|
|
938
773
|
const reauthSuccess = await this.reauthInBand(newJwt, prevJti, 'timer');
|
|
939
774
|
if (reauthSuccess) {
|
|
940
|
-
// In-band reauth succeeded - update assignment state and we're done
|
|
941
|
-
// CLI-IMG-WSReconnect: Update tunnel state with new assignment
|
|
942
775
|
this.requestId = newAssignment.requestId;
|
|
943
776
|
this.relayUrl = newAssignment.relayUrl;
|
|
944
777
|
this.headers = {
|
|
@@ -946,30 +779,24 @@ export class HttpTunnel {
|
|
|
946
779
|
'X-Asyx-DeviceId': this.deviceId,
|
|
947
780
|
'X-Asyx-RequestId': this.requestId
|
|
948
781
|
};
|
|
949
|
-
// Record refresh timestamp and delta metrics
|
|
950
782
|
const { recordRefresh } = await import('../state/assignment.js');
|
|
951
783
|
const deltaMs = recordRefresh(this.instanceId, Date.now());
|
|
952
784
|
this.log.info('jwt.refresh.delta', { deltaMs });
|
|
953
785
|
this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'in_band' });
|
|
954
|
-
// QPA-CLI-01: Reset retry state on success
|
|
955
786
|
this.refreshState = 'idle';
|
|
956
787
|
this.refreshAttempts = 0;
|
|
957
788
|
this.refreshRetryCount = 0;
|
|
958
789
|
this.refreshDeadline = null;
|
|
959
790
|
this._cancelRefreshRetry();
|
|
960
|
-
return;
|
|
791
|
+
return;
|
|
961
792
|
}
|
|
962
|
-
// Reauth failed, fall through to reconnect
|
|
963
793
|
this.log.info('jwt.reauth.fallback_reconnect', { retryCount: this.refreshAttempts });
|
|
964
794
|
}
|
|
965
795
|
catch (reauthError) {
|
|
966
796
|
this.log.warn('jwt.reauth.exception', { error: reauthError.message });
|
|
967
797
|
this.log.info('jwt.reauth.fallback_reconnect', { retryCount: this.refreshAttempts });
|
|
968
|
-
// Fall through to reconnect
|
|
969
798
|
}
|
|
970
799
|
}
|
|
971
|
-
// Fallback path: update state and reconnect with new JWT
|
|
972
|
-
// CLI-IMG-WSReconnect: Update tunnel state with new assignment
|
|
973
800
|
this.jwt = newJwt;
|
|
974
801
|
this.requestId = newAssignment.requestId;
|
|
975
802
|
this.relayUrl = newAssignment.relayUrl;
|
|
@@ -978,52 +805,43 @@ export class HttpTunnel {
|
|
|
978
805
|
'X-Asyx-DeviceId': this.deviceId,
|
|
979
806
|
'X-Asyx-RequestId': newAssignment.requestId
|
|
980
807
|
};
|
|
981
|
-
// Record refresh timestamp and delta metrics
|
|
982
808
|
const { recordRefresh } = await import('../state/assignment.js');
|
|
983
809
|
const deltaMs = recordRefresh(this.instanceId, Date.now());
|
|
984
810
|
this.log.info('jwt.refresh.delta', { deltaMs });
|
|
985
811
|
this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'reconnect' });
|
|
986
|
-
// QPA-CLI-01: Reset retry state on success
|
|
987
812
|
this.refreshState = 'idle';
|
|
988
813
|
this.refreshAttempts = 0;
|
|
989
814
|
this.refreshRetryCount = 0;
|
|
990
815
|
this.refreshDeadline = null;
|
|
991
816
|
this._cancelRefreshRetry();
|
|
992
|
-
// CLI-RES-DPJWT-LEAD: Schedule next proactive refresh
|
|
993
817
|
this.scheduleRefresh(this.jwt, 'refresh_success');
|
|
994
|
-
// Attempt reconnect with new JWT
|
|
995
818
|
await this._attemptConnect();
|
|
996
819
|
}
|
|
997
820
|
catch (error) {
|
|
998
821
|
this.log.error('jwt.refresh.failure', { error: error.message, retryCount: this.refreshAttempts });
|
|
999
822
|
this.refreshState = 'failed';
|
|
1000
|
-
return this._fatal('refresh_failed');
|
|
823
|
+
return this._fatal('refresh_failed');
|
|
1001
824
|
}
|
|
1002
825
|
}
|
|
1003
|
-
// CLI-RES-REFRESH-FALLBACK: Lease-preserving fallback when refresh fails
|
|
1004
|
-
// Reuses existing lease via refreshOf instead of creating a fresh tunnel
|
|
1005
826
|
async _fallbackToFreshTunnel() {
|
|
1006
827
|
this.refreshState = 'fallback';
|
|
1007
|
-
// TPB-12: Get current assignment for this specific instance
|
|
1008
828
|
const { getAssignment } = await import('../state/assignment.js');
|
|
1009
829
|
const currentAssignment = getAssignment(this.instanceId);
|
|
1010
830
|
if (!currentAssignment) {
|
|
1011
831
|
this.log.error('jwt.refresh.fallback.no_assignment', { error: 'no_current_assignment', instanceId: this.instanceId });
|
|
1012
|
-
return this._fatal('refresh_fallback_no_assignment');
|
|
832
|
+
return this._fatal('refresh_fallback_no_assignment');
|
|
1013
833
|
}
|
|
1014
834
|
const leaseId = currentAssignment.leaseId;
|
|
1015
835
|
const relayId = currentAssignment.relayId;
|
|
1016
836
|
if (!leaseId) {
|
|
1017
837
|
this.log.error('jwt.refresh.fallback.no_lease_id', { error: 'lease_id_missing' });
|
|
1018
|
-
return this._fatal('refresh_fallback_no_lease_id');
|
|
838
|
+
return this._fatal('refresh_fallback_no_lease_id');
|
|
1019
839
|
}
|
|
1020
840
|
this.log.info('jwt.refresh.fallback.start', { reason: 'refresh_timeout_or_publish_failure', leaseId, relayId });
|
|
1021
|
-
// Retry loop with max attempts
|
|
1022
841
|
let retryCount = 0;
|
|
1023
842
|
const maxFallbackRetries = this.refreshMaxAttempts;
|
|
1024
843
|
while (retryCount < maxFallbackRetries) {
|
|
1025
844
|
try {
|
|
1026
|
-
// CLI-RES-REFRESH-FALLBACK: Control-plane gating before fallback
|
|
1027
845
|
const ready = await this._ensureControlPlane('jwt_refresh_fallback');
|
|
1028
846
|
if (!ready) {
|
|
1029
847
|
this.log.warn('jwt.refresh.fallback.control_plane_timeout', { retryCount, leaseId });
|
|
@@ -1032,33 +850,28 @@ export class HttpTunnel {
|
|
|
1032
850
|
this.log.info('jwt.refresh.fallback.control_plane_recovered', { leaseId });
|
|
1033
851
|
}
|
|
1034
852
|
catch (waitError) {
|
|
1035
|
-
// QPA-CLI-01: Instead of exiting, schedule a retry
|
|
1036
853
|
this.log.warn('jwt.refresh.fallback.control_plane_wait_failed', {
|
|
1037
854
|
error: waitError.message,
|
|
1038
855
|
retryCount,
|
|
1039
856
|
leaseId
|
|
1040
857
|
});
|
|
1041
|
-
// Schedule retry with backoff
|
|
1042
858
|
this._scheduleRefreshRetry('fallback_control_plane_offline');
|
|
1043
|
-
return;
|
|
859
|
+
return;
|
|
1044
860
|
}
|
|
1045
861
|
}
|
|
1046
|
-
// CLI-RES-REFRESH-FALLBACK: Build lease-preserving refresh payload
|
|
1047
862
|
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
1048
863
|
const fingerprint = await getFpHash(this.deviceId);
|
|
1049
|
-
const refreshRequestId = `refresh-${crypto.randomUUID()}
|
|
864
|
+
const refreshRequestId = `refresh-${crypto.randomUUID()}`;
|
|
1050
865
|
const refreshPayload = {
|
|
1051
866
|
requestId: refreshRequestId,
|
|
1052
|
-
refreshOf: leaseId,
|
|
1053
|
-
reconnect: false,
|
|
867
|
+
refreshOf: leaseId,
|
|
868
|
+
reconnect: false,
|
|
1054
869
|
proto: 'http',
|
|
1055
870
|
localPort: this.localPort,
|
|
1056
871
|
clientId: this.deviceId,
|
|
1057
872
|
...fingerprint
|
|
1058
873
|
};
|
|
1059
|
-
// Set up topic for refresh request
|
|
1060
874
|
const cmdOpenTopic = `asyx/tunnel/clients/${this.deviceId}/cmd/open`;
|
|
1061
|
-
// Wait for open_ack with timeout
|
|
1062
875
|
const ackPromise = this.coordinatorIngress.registerAwaiter((message) => {
|
|
1063
876
|
try {
|
|
1064
877
|
const parsed = message.payload;
|
|
@@ -1068,7 +881,6 @@ export class HttpTunnel {
|
|
|
1068
881
|
return false;
|
|
1069
882
|
}
|
|
1070
883
|
}, 10000);
|
|
1071
|
-
// CLI-RES-REFRESH-FALLBACK: Publish lease-preserving refresh request
|
|
1072
884
|
try {
|
|
1073
885
|
await this.coordinatorCore.publish({
|
|
1074
886
|
topic: cmdOpenTopic,
|
|
@@ -1082,7 +894,6 @@ export class HttpTunnel {
|
|
|
1082
894
|
relayId,
|
|
1083
895
|
retryCount: retryCount + 1
|
|
1084
896
|
});
|
|
1085
|
-
// Wait for open_ack with timeout handling
|
|
1086
897
|
try {
|
|
1087
898
|
await ackPromise;
|
|
1088
899
|
}
|
|
@@ -1100,9 +911,9 @@ export class HttpTunnel {
|
|
|
1100
911
|
leaseId
|
|
1101
912
|
});
|
|
1102
913
|
this.refreshState = 'failed';
|
|
1103
|
-
return this._fatal('refresh_fallback_failed');
|
|
914
|
+
return this._fatal('refresh_fallback_failed');
|
|
1104
915
|
}
|
|
1105
|
-
continue;
|
|
916
|
+
continue;
|
|
1106
917
|
}
|
|
1107
918
|
}
|
|
1108
919
|
catch (publishError) {
|
|
@@ -1119,13 +930,11 @@ export class HttpTunnel {
|
|
|
1119
930
|
leaseId
|
|
1120
931
|
});
|
|
1121
932
|
this.refreshState = 'failed';
|
|
1122
|
-
return this._fatal('refresh_fallback_failed');
|
|
933
|
+
return this._fatal('refresh_fallback_failed');
|
|
1123
934
|
}
|
|
1124
|
-
// Wait briefly before retry
|
|
1125
935
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
1126
936
|
continue;
|
|
1127
937
|
}
|
|
1128
|
-
// TPB-12: Get the new assignment for this specific instance
|
|
1129
938
|
const newAssignment = getAssignment(this.instanceId);
|
|
1130
939
|
if (!newAssignment) {
|
|
1131
940
|
retryCount++;
|
|
@@ -1137,11 +946,10 @@ export class HttpTunnel {
|
|
|
1137
946
|
leaseId
|
|
1138
947
|
});
|
|
1139
948
|
this.refreshState = 'failed';
|
|
1140
|
-
return this._fatal('refresh_fallback_failed');
|
|
949
|
+
return this._fatal('refresh_fallback_failed');
|
|
1141
950
|
}
|
|
1142
951
|
continue;
|
|
1143
952
|
}
|
|
1144
|
-
// CLI-RES-REFRESH-FALLBACK: Update tunnel state with refreshed assignment
|
|
1145
953
|
this.jwt = newAssignment.jwt;
|
|
1146
954
|
this.requestId = newAssignment.requestId;
|
|
1147
955
|
this.relayUrl = newAssignment.relayUrl;
|
|
@@ -1150,7 +958,6 @@ export class HttpTunnel {
|
|
|
1150
958
|
'X-Asyx-DeviceId': this.deviceId,
|
|
1151
959
|
'X-Asyx-RequestId': newAssignment.requestId
|
|
1152
960
|
};
|
|
1153
|
-
// Record refresh delta for fallback path
|
|
1154
961
|
const { recordRefresh } = await import('../state/assignment.js');
|
|
1155
962
|
const deltaMs = recordRefresh(this.instanceId, Date.now());
|
|
1156
963
|
this.log.info('jwt.refresh.delta', { deltaMs });
|
|
@@ -1161,11 +968,8 @@ export class HttpTunnel {
|
|
|
1161
968
|
});
|
|
1162
969
|
this.refreshState = 'idle';
|
|
1163
970
|
this.refreshAttempts = 0;
|
|
1164
|
-
// CLI-RES-DPJWT-LEAD: Schedule next proactive refresh
|
|
1165
971
|
this.scheduleRefresh(this.jwt, 'fallback_success');
|
|
1166
|
-
// Reconnect WebSocket with refreshed JWT
|
|
1167
972
|
await this._attemptConnect();
|
|
1168
|
-
// Success - exit retry loop
|
|
1169
973
|
return;
|
|
1170
974
|
}
|
|
1171
975
|
catch (error) {
|
|
@@ -1182,9 +986,8 @@ export class HttpTunnel {
|
|
|
1182
986
|
leaseId
|
|
1183
987
|
});
|
|
1184
988
|
this.refreshState = 'failed';
|
|
1185
|
-
return this._fatal('refresh_fallback_failed');
|
|
989
|
+
return this._fatal('refresh_fallback_failed');
|
|
1186
990
|
}
|
|
1187
|
-
// Brief delay before retry
|
|
1188
991
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
1189
992
|
}
|
|
1190
993
|
}
|
|
@@ -1202,11 +1005,8 @@ export class HttpTunnel {
|
|
|
1202
1005
|
}
|
|
1203
1006
|
}
|
|
1204
1007
|
handleHttpRequest(msg) {
|
|
1205
|
-
// CRT-Relay-E: Update activity on HTTP request
|
|
1206
1008
|
this.lastActivityMs = Date.now();
|
|
1207
|
-
// Handle JSON-formatted HTTP request from relay (CRT-Relay-B compact format)
|
|
1208
1009
|
const { t, rid, m, u, h, b } = msg;
|
|
1209
|
-
// Extract fields from compact format
|
|
1210
1010
|
const requestId = rid;
|
|
1211
1011
|
const method = m;
|
|
1212
1012
|
const bodyBuffer = b ? Buffer.from(b, 'base64') : null;
|
|
@@ -1217,35 +1017,27 @@ export class HttpTunnel {
|
|
|
1217
1017
|
}
|
|
1218
1018
|
const url = sanitized.path;
|
|
1219
1019
|
const headers = sanitized.headers;
|
|
1220
|
-
// Forward through the request sink (Story 12.1 c3; LocalPortSink = the local HTTP server)
|
|
1221
1020
|
const options = { path: url, method, headers };
|
|
1222
1021
|
let proxyReq;
|
|
1223
|
-
let localAnswered = false;
|
|
1022
|
+
let localAnswered = false;
|
|
1224
1023
|
try {
|
|
1225
1024
|
proxyReq = this.requestSink.request(options, (proxyRes) => {
|
|
1226
1025
|
localAnswered = true;
|
|
1227
1026
|
this._localReachable();
|
|
1228
|
-
// S-1: Determine response mode at http_response_start
|
|
1229
1027
|
const contentLength = proxyRes.headers['content-length']
|
|
1230
1028
|
? parseInt(proxyRes.headers['content-length'], 10)
|
|
1231
1029
|
: null;
|
|
1232
1030
|
const isChunked = proxyRes.headers['transfer-encoding']?.toLowerCase() === 'chunked';
|
|
1233
1031
|
const selectedMode = this._selectResponseMode(contentLength, isChunked);
|
|
1234
|
-
// S-1: Version guard - if v2 not negotiated, force v1
|
|
1235
1032
|
const useV2 = selectedMode === 'v2' && this._canUseV2();
|
|
1236
1033
|
if (useV2) {
|
|
1237
|
-
// S-1: V2 streaming path
|
|
1238
1034
|
this._handleV2Response(proxyRes, requestId);
|
|
1239
1035
|
}
|
|
1240
1036
|
else {
|
|
1241
|
-
// S-1: V1 single-frame path (existing behavior)
|
|
1242
1037
|
this._handleV1Response(proxyRes, requestId);
|
|
1243
1038
|
}
|
|
1244
1039
|
});
|
|
1245
|
-
// Handle connection errors to local service
|
|
1246
1040
|
proxyReq.on('error', (err) => {
|
|
1247
|
-
// Story 3.8 (was: exit on ECONNREFUSED, no answer for other errors): if the local service
|
|
1248
|
-
// never answered, the visitor gets a 502 page and the tunnel stays up.
|
|
1249
1041
|
if (!localAnswered) {
|
|
1250
1042
|
this._localUnreachable(err);
|
|
1251
1043
|
this.sendLocalUnavailable(requestId);
|
|
@@ -1269,7 +1061,6 @@ export class HttpTunnel {
|
|
|
1269
1061
|
}
|
|
1270
1062
|
}
|
|
1271
1063
|
handleHttpRequestBuffer(buffer) {
|
|
1272
|
-
// Handle raw HTTP request buffer from relay
|
|
1273
1064
|
const httpString = buffer.toString();
|
|
1274
1065
|
const lines = httpString.split('\r\n');
|
|
1275
1066
|
const [method, rawUrl] = lines[0].split(' ');
|
|
@@ -1292,22 +1083,18 @@ export class HttpTunnel {
|
|
|
1292
1083
|
this.log.warn({ method }, 'Rejected raw tunnel request');
|
|
1293
1084
|
return;
|
|
1294
1085
|
}
|
|
1295
|
-
// Forward through the request sink (Story 12.1 c3; LocalPortSink = the local HTTP server)
|
|
1296
1086
|
const options = { path: sanitized.path, method, headers: sanitized.headers };
|
|
1297
1087
|
let proxyReq;
|
|
1298
|
-
let localAnswered = false;
|
|
1088
|
+
let localAnswered = false;
|
|
1299
1089
|
try {
|
|
1300
1090
|
proxyReq = this.requestSink.request(options, (proxyRes) => {
|
|
1301
1091
|
localAnswered = true;
|
|
1302
1092
|
this._localReachable();
|
|
1303
|
-
// Send response back to relay as binary
|
|
1304
1093
|
let responseBuffer = Buffer.from(`HTTP/1.1 ${proxyRes.statusCode} ${proxyRes.statusMessage}\r\n`);
|
|
1305
|
-
// Add headers
|
|
1306
1094
|
for (const [key, value] of Object.entries(proxyRes.headers)) {
|
|
1307
1095
|
responseBuffer = Buffer.concat([responseBuffer, Buffer.from(`${key}: ${value}\r\n`)]);
|
|
1308
1096
|
}
|
|
1309
1097
|
responseBuffer = Buffer.concat([responseBuffer, Buffer.from('\r\n')]);
|
|
1310
|
-
// Add body
|
|
1311
1098
|
proxyRes.on('data', chunk => {
|
|
1312
1099
|
responseBuffer = Buffer.concat([responseBuffer, chunk]);
|
|
1313
1100
|
});
|
|
@@ -1315,9 +1102,7 @@ export class HttpTunnel {
|
|
|
1315
1102
|
this.ws.send(responseBuffer);
|
|
1316
1103
|
});
|
|
1317
1104
|
});
|
|
1318
|
-
// Handle connection errors to local service
|
|
1319
1105
|
proxyReq.on('error', (err) => {
|
|
1320
|
-
// Story 3.8: same as the JSON path, answered as a raw HTTP response.
|
|
1321
1106
|
if (!localAnswered) {
|
|
1322
1107
|
this._localUnreachable(err);
|
|
1323
1108
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
@@ -1342,7 +1127,6 @@ export class HttpTunnel {
|
|
|
1342
1127
|
throw err;
|
|
1343
1128
|
}
|
|
1344
1129
|
}
|
|
1345
|
-
// S-0: Send hello frame for HTTP-WS v2 negotiation
|
|
1346
1130
|
_sendHello() {
|
|
1347
1131
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
1348
1132
|
this.log.warn('Cannot send hello: WebSocket not open');
|
|
@@ -1356,7 +1140,6 @@ export class HttpTunnel {
|
|
|
1356
1140
|
};
|
|
1357
1141
|
this.ws.send(JSON.stringify(hello));
|
|
1358
1142
|
this.log.debug('Hello frame sent', { protocols: hello.protocols });
|
|
1359
|
-
// Defect 11.9: if no hello_ack arrives (the relay lost it), offer again
|
|
1360
1143
|
this._helloAttempts = (this._helloAttempts || 0) + 1;
|
|
1361
1144
|
if (this._helloTimer)
|
|
1362
1145
|
clearTimeout(this._helloTimer);
|
|
@@ -1373,7 +1156,6 @@ export class HttpTunnel {
|
|
|
1373
1156
|
this._helloTimer.unref();
|
|
1374
1157
|
}
|
|
1375
1158
|
}
|
|
1376
|
-
// S-0: Handle hello_ack for HTTP-WS v2 negotiation
|
|
1377
1159
|
_handleHelloAck(helloAck) {
|
|
1378
1160
|
if (this._helloTimer) {
|
|
1379
1161
|
clearTimeout(this._helloTimer);
|
|
@@ -1385,43 +1167,29 @@ export class HttpTunnel {
|
|
|
1385
1167
|
this.log.debug('HTTP-WS v2 not negotiated, will use v1 mode');
|
|
1386
1168
|
}
|
|
1387
1169
|
}
|
|
1388
|
-
// S-0: Check if HTTP-WS v2 can be used (guard for v2 frame sending)
|
|
1389
|
-
// This method should be called before sending any HTTP_BODY_CHUNK (0x20) frames
|
|
1390
|
-
// Returns true if v2 is negotiated, false otherwise (should fallback to v1)
|
|
1391
1170
|
_canUseV2() {
|
|
1392
1171
|
return this.httpWsVersion === 'v2';
|
|
1393
1172
|
}
|
|
1394
|
-
// S-1: Convert requestId string to 8-byte big-endian uint64 buffer
|
|
1395
|
-
// Note: requestId is a UUID string, so we hash it deterministically to get 8 bytes
|
|
1396
|
-
// Both CLI and relay use the same hash function for matching
|
|
1397
1173
|
_encodeRequestId(requestId) {
|
|
1398
1174
|
const hash = crypto.createHash('sha256').update(requestId).digest();
|
|
1399
1175
|
const buffer = Buffer.alloc(8);
|
|
1400
1176
|
hash.copy(buffer, 0, 0, 8);
|
|
1401
|
-
// Buffer is already big-endian by default in Node.js
|
|
1402
1177
|
return buffer;
|
|
1403
1178
|
}
|
|
1404
|
-
// S-1: Determine response mode (v1 or v2) based on content-length and size
|
|
1405
1179
|
_selectResponseMode(contentLength, isChunked) {
|
|
1406
|
-
// S-1: Use v2 if:
|
|
1407
|
-
// - Content-Length >= 8 MiB, OR
|
|
1408
|
-
// - Content-Length unknown/missing or TE: chunked, OR
|
|
1409
|
-
// - Will cross 8 MiB threshold during buffering
|
|
1410
1180
|
if (isChunked || contentLength === null || contentLength === undefined) {
|
|
1411
|
-
return 'v2';
|
|
1181
|
+
return 'v2';
|
|
1412
1182
|
}
|
|
1413
1183
|
if (contentLength >= V2_THRESHOLD_BYTES) {
|
|
1414
|
-
return 'v2';
|
|
1184
|
+
return 'v2';
|
|
1415
1185
|
}
|
|
1416
|
-
return 'v1';
|
|
1186
|
+
return 'v1';
|
|
1417
1187
|
}
|
|
1418
|
-
// S-1: Send HTTP-WS v2 binary chunk frame
|
|
1419
1188
|
_sendV2Chunk(requestId, payload) {
|
|
1420
1189
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
1421
1190
|
this.log.warn('Cannot send v2 chunk: WebSocket not open', { requestId });
|
|
1422
1191
|
return false;
|
|
1423
1192
|
}
|
|
1424
|
-
// Encode frame: frameType (1 byte) + requestId (8 bytes) + payload
|
|
1425
1193
|
const requestIdBuffer = this._encodeRequestId(requestId);
|
|
1426
1194
|
const frame = Buffer.concat([
|
|
1427
1195
|
Buffer.from([HTTP_BODY_CHUNK]),
|
|
@@ -1437,12 +1205,10 @@ export class HttpTunnel {
|
|
|
1437
1205
|
return false;
|
|
1438
1206
|
}
|
|
1439
1207
|
}
|
|
1440
|
-
// S-1: Chunk payload into v2-compliant sizes (64 KiB target, 256 KiB max)
|
|
1441
1208
|
_chunkPayload(payload) {
|
|
1442
1209
|
const chunks = [];
|
|
1443
1210
|
let offset = 0;
|
|
1444
1211
|
while (offset < payload.length) {
|
|
1445
|
-
// Target 64 KiB, but don't exceed 256 KiB
|
|
1446
1212
|
const remaining = payload.length - offset;
|
|
1447
1213
|
const chunkSize = Math.min(HTTPWS_V2_TARGET_CHUNK_BYTES, Math.min(remaining, HTTPWS_V2_MAX_CHUNK_BYTES));
|
|
1448
1214
|
chunks.push(payload.slice(offset, offset + chunkSize));
|
|
@@ -1450,13 +1216,9 @@ export class HttpTunnel {
|
|
|
1450
1216
|
}
|
|
1451
1217
|
return chunks;
|
|
1452
1218
|
}
|
|
1453
|
-
// S-1: Handle v2 streaming response
|
|
1454
1219
|
_handleV2Response(proxyRes, requestId) {
|
|
1455
|
-
// Track this response as v2
|
|
1456
1220
|
this.activeV2Responses.set(requestId, { mode: 'v2', bufferedBytes: 0 });
|
|
1457
|
-
// Convert headers to array format
|
|
1458
1221
|
const headerArray = Object.entries(proxyRes.headers).map(([name, value]) => [name, value]);
|
|
1459
|
-
// S-1: Send http_response_start with mode: "stream"
|
|
1460
1222
|
const responseStart = {
|
|
1461
1223
|
type: 'http_response_start',
|
|
1462
1224
|
rid: requestId,
|
|
@@ -1470,7 +1232,6 @@ export class HttpTunnel {
|
|
|
1470
1232
|
return;
|
|
1471
1233
|
}
|
|
1472
1234
|
this.ws.send(JSON.stringify(responseStart));
|
|
1473
|
-
// S-1: Stream chunks as they arrive
|
|
1474
1235
|
let buffer = Buffer.alloc(0);
|
|
1475
1236
|
const flushBuffer = () => {
|
|
1476
1237
|
if (buffer.length === 0)
|
|
@@ -1478,7 +1239,6 @@ export class HttpTunnel {
|
|
|
1478
1239
|
const chunks = this._chunkPayload(buffer);
|
|
1479
1240
|
for (const chunk of chunks) {
|
|
1480
1241
|
if (!this._sendV2Chunk(requestId, chunk)) {
|
|
1481
|
-
// Send failed, abort response
|
|
1482
1242
|
this.log.error('Failed to send v2 chunk, aborting response', { requestId });
|
|
1483
1243
|
this.activeV2Responses.delete(requestId);
|
|
1484
1244
|
return;
|
|
@@ -1487,21 +1247,15 @@ export class HttpTunnel {
|
|
|
1487
1247
|
buffer = Buffer.alloc(0);
|
|
1488
1248
|
};
|
|
1489
1249
|
proxyRes.on('data', (chunk) => {
|
|
1490
|
-
// CRT-Relay-E: Update activity on HTTP response data
|
|
1491
1250
|
this.lastActivityMs = Date.now();
|
|
1492
|
-
// Accumulate chunk
|
|
1493
1251
|
buffer = Buffer.concat([buffer, chunk]);
|
|
1494
|
-
// Flush when buffer reaches target chunk size
|
|
1495
1252
|
if (buffer.length >= HTTPWS_V2_TARGET_CHUNK_BYTES) {
|
|
1496
1253
|
flushBuffer();
|
|
1497
1254
|
}
|
|
1498
1255
|
});
|
|
1499
1256
|
proxyRes.on('end', () => {
|
|
1500
|
-
// CRT-Relay-E: Update activity on HTTP response end
|
|
1501
1257
|
this.lastActivityMs = Date.now();
|
|
1502
|
-
// Flush any remaining data
|
|
1503
1258
|
flushBuffer();
|
|
1504
|
-
// S-1: Send http_response_end
|
|
1505
1259
|
const responseEnd = {
|
|
1506
1260
|
type: 'http_response_end',
|
|
1507
1261
|
rid: requestId
|
|
@@ -1509,7 +1263,6 @@ export class HttpTunnel {
|
|
|
1509
1263
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
1510
1264
|
this.ws.send(JSON.stringify(responseEnd));
|
|
1511
1265
|
}
|
|
1512
|
-
// Clean up tracking
|
|
1513
1266
|
this.activeV2Responses.delete(requestId);
|
|
1514
1267
|
});
|
|
1515
1268
|
proxyRes.on('error', (error) => {
|
|
@@ -1517,38 +1270,29 @@ export class HttpTunnel {
|
|
|
1517
1270
|
this.activeV2Responses.delete(requestId);
|
|
1518
1271
|
});
|
|
1519
1272
|
}
|
|
1520
|
-
// S-1: Handle v1 single-frame response (existing behavior)
|
|
1521
1273
|
_handleV1Response(proxyRes, requestId) {
|
|
1522
1274
|
const responseChunks = [];
|
|
1523
1275
|
let bufferedBytes = 0;
|
|
1524
1276
|
proxyRes.on('data', (chunk) => {
|
|
1525
1277
|
responseChunks.push(chunk);
|
|
1526
1278
|
bufferedBytes += chunk.length;
|
|
1527
|
-
// S-1: If buffering for v1 crosses 8 MiB, abort and retry as v2
|
|
1528
1279
|
if (bufferedBytes >= V2_THRESHOLD_BYTES && this._canUseV2()) {
|
|
1529
1280
|
this.log.warn('V1 response exceeded 8 MiB threshold, aborting', { requestId, bufferedBytes });
|
|
1530
|
-
// Note: In a real implementation, we'd need to abort the proxyRes stream
|
|
1531
|
-
// For now, we'll continue with v1 but log the issue
|
|
1532
|
-
// This is a limitation - we can't easily switch mid-stream
|
|
1533
1281
|
}
|
|
1534
1282
|
});
|
|
1535
1283
|
proxyRes.on('end', () => {
|
|
1536
|
-
// CRT-Relay-E: Update activity on HTTP response
|
|
1537
1284
|
this.lastActivityMs = Date.now();
|
|
1538
|
-
// Convert headers to array format and encode body as base64
|
|
1539
1285
|
const headerArray = Object.entries(proxyRes.headers).map(([name, value]) => [name, value]);
|
|
1540
1286
|
const bodyBuffer = Buffer.concat(responseChunks);
|
|
1541
1287
|
const bodyBase64 = bodyBuffer.length ? bodyBuffer.toString('base64') : '';
|
|
1542
1288
|
const responseData = {
|
|
1543
1289
|
t: 'http_response',
|
|
1544
|
-
rid: requestId,
|
|
1290
|
+
rid: requestId,
|
|
1545
1291
|
s: proxyRes.statusCode,
|
|
1546
1292
|
h: headerArray,
|
|
1547
1293
|
b: bodyBase64
|
|
1548
1294
|
};
|
|
1549
1295
|
const frame = JSON.stringify(responseData);
|
|
1550
|
-
// Defect 11.9: never send a message the relay refuses; it would close the whole tunnel.
|
|
1551
|
-
// Fail only this request (502) instead.
|
|
1552
1296
|
if (Buffer.byteLength(frame) > V1_MAX_FRAME_BYTES) {
|
|
1553
1297
|
this.log.error('v1.response.too_large', { requestId, bodyBytes: bodyBuffer.length, frameBytes: Buffer.byteLength(frame), httpWsVersion: this.httpWsVersion });
|
|
1554
1298
|
this.sendTunnelError(requestId, 502);
|
|
@@ -1560,36 +1304,26 @@ export class HttpTunnel {
|
|
|
1560
1304
|
});
|
|
1561
1305
|
}
|
|
1562
1306
|
close() {
|
|
1563
|
-
// CLI-IMG-WSReconnect: Disable reconnects and clear timer
|
|
1564
1307
|
this.shouldReconnect = false;
|
|
1565
1308
|
if (this.reconnectTimer) {
|
|
1566
1309
|
clearTimeout(this.reconnectTimer);
|
|
1567
1310
|
this.reconnectTimer = null;
|
|
1568
1311
|
}
|
|
1569
|
-
// CLI-RES-DPJWT-LEAD: Clear refresh timer to avoid leaks
|
|
1570
1312
|
if (this.refreshTimer) {
|
|
1571
1313
|
clearTimeout(this.refreshTimer);
|
|
1572
1314
|
this.refreshTimer = null;
|
|
1573
1315
|
}
|
|
1574
|
-
// QPA-CLI-01: Clean up retry timer
|
|
1575
1316
|
if (this.refreshRetryTimer) {
|
|
1576
1317
|
clearTimeout(this.refreshRetryTimer);
|
|
1577
1318
|
this.refreshRetryTimer = null;
|
|
1578
1319
|
}
|
|
1579
|
-
// CLI-REAUTH: Cleanup control frame waiters
|
|
1580
1320
|
clearAllWaiters();
|
|
1581
1321
|
this.reauthInFlight = null;
|
|
1582
|
-
// CRT-Relay-E: Stop heartbeat before closing
|
|
1583
1322
|
this.stopHeartbeat();
|
|
1584
1323
|
if (this.ws) {
|
|
1585
1324
|
this.ws.close();
|
|
1586
1325
|
}
|
|
1587
1326
|
}
|
|
1588
|
-
// CRT-Relay-E / Story 3.11: Heartbeat methods. Every interval (30 s by default) the tunnel
|
|
1589
|
-
// sends a WebSocket protocol ping, which the relay's WebSocket library answers by itself, so
|
|
1590
|
-
// relays in the field need no change. Nothing received for three intervals means the
|
|
1591
|
-
// connection died without a close: terminate it so the close handler reconnects (as the
|
|
1592
|
-
// TCP and UDP tunnels do, Story 11.2), instead of waiting minutes for a write to fail.
|
|
1593
1327
|
getHeartbeatInterval() {
|
|
1594
1328
|
const interval = process.env.ASYX_TUNNEL_HEARTBEAT_SEC || '30';
|
|
1595
1329
|
const intervalMs = Number(interval) * 1000;
|
|
@@ -1609,7 +1343,6 @@ export class HttpTunnel {
|
|
|
1609
1343
|
this.log.debug({ interval }, 'tunnel heartbeat started');
|
|
1610
1344
|
}
|
|
1611
1345
|
sendHeartbeat() {
|
|
1612
|
-
// Guard against sending when WebSocket is not open
|
|
1613
1346
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
1614
1347
|
return;
|
|
1615
1348
|
}
|