asyx 0.5.8 → 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.
Files changed (87) hide show
  1. package/README.md +103 -17
  2. package/SECURITY.md +5 -3
  3. package/package.json +15 -22
  4. package/src/commands/name.js +23 -0
  5. package/src/commands/reject-messages.js +54 -0
  6. package/src/commands/setup.js +98 -102
  7. package/src/commands/tunnel.js +304 -2316
  8. package/src/lib/naming.js +81 -0
  9. package/src/main.js +24 -6
  10. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +260 -0
  11. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +1088 -0
  12. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +79 -0
  13. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +138 -0
  14. package/vendor/tunnel-core/dist/control-plane/session.d.ts +50 -0
  15. package/vendor/tunnel-core/dist/control-plane/session.js +115 -0
  16. package/vendor/tunnel-core/dist/errors.d.ts +49 -0
  17. package/vendor/tunnel-core/dist/errors.js +53 -0
  18. package/vendor/tunnel-core/dist/flows/http.d.ts +50 -0
  19. package/vendor/tunnel-core/dist/flows/http.js +585 -0
  20. package/vendor/tunnel-core/dist/flows/tcp.d.ts +60 -0
  21. package/vendor/tunnel-core/dist/flows/tcp.js +546 -0
  22. package/vendor/tunnel-core/dist/flows/udp.d.ts +41 -0
  23. package/vendor/tunnel-core/dist/flows/udp.js +376 -0
  24. package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +2 -0
  25. package/vendor/tunnel-core/dist/lib/adapt-logger.js +6 -0
  26. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +13 -0
  27. package/vendor/tunnel-core/dist/lib/fingerprint.js +95 -0
  28. package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +27 -0
  29. package/vendor/tunnel-core/dist/lib/jwt-verifier.js +230 -0
  30. package/vendor/tunnel-core/dist/lib/logger.d.ts +9 -0
  31. package/vendor/tunnel-core/dist/lib/logger.js +58 -0
  32. package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +16 -0
  33. package/vendor/tunnel-core/dist/lib/refresh-helpers.js +66 -0
  34. package/vendor/tunnel-core/dist/lifecycle.d.ts +24 -0
  35. package/vendor/tunnel-core/dist/lifecycle.js +29 -0
  36. package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +56 -0
  37. package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +227 -0
  38. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +58 -0
  39. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +250 -0
  40. package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +1 -0
  41. package/vendor/tunnel-core/dist/mqtt/events/index.js +191 -0
  42. package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +498 -0
  43. package/vendor/tunnel-core/dist/mqtt/events/schemas.js +51 -0
  44. package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +63 -0
  45. package/vendor/tunnel-core/dist/mqtt/ingress.js +170 -0
  46. package/vendor/tunnel-core/dist/state/assignment.d.ts +122 -0
  47. package/vendor/tunnel-core/dist/state/assignment.js +322 -0
  48. package/vendor/tunnel-core/dist/state/instance-registry.d.ts +88 -0
  49. package/{src → vendor/tunnel-core/dist}/state/instance-registry.js +38 -53
  50. package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +43 -0
  51. package/vendor/tunnel-core/dist/tcp-v1/framing.js +157 -0
  52. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +137 -0
  53. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +1591 -0
  54. package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +13 -0
  55. package/{src → vendor/tunnel-core/dist}/tunnel/httpws-constants.js +5 -7
  56. package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +76 -0
  57. package/vendor/tunnel-core/dist/tunnel/reconnect.js +183 -0
  58. package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +40 -0
  59. package/vendor/tunnel-core/dist/tunnel/request-sink.js +39 -0
  60. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +89 -0
  61. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +838 -0
  62. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +90 -0
  63. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +737 -0
  64. package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +22 -0
  65. package/vendor/tunnel-core/dist/tunnel/ws-control.js +124 -0
  66. package/vendor/tunnel-core/dist/types.d.ts +24 -0
  67. package/vendor/tunnel-core/dist/types.js +2 -0
  68. package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +41 -0
  69. package/vendor/tunnel-core/dist/udp-v1/framing.js +158 -0
  70. package/vendor/tunnel-core/package.json +34 -0
  71. package/src/control-plane/MqttControlPlaneClient.js +0 -1196
  72. package/src/control-plane/MqttControlPlaneTransport.js +0 -150
  73. package/src/lib/fingerprint.js +0 -115
  74. package/src/lib/jwt-verifier.js +0 -260
  75. package/src/lib/logger.js +0 -62
  76. package/src/mqtt/awaiter-map.js +0 -247
  77. package/src/mqtt/events/handlers.js +0 -300
  78. package/src/mqtt/events/index.js +0 -222
  79. package/src/mqtt/events/schemas.js +0 -58
  80. package/src/mqtt/ingress.js +0 -182
  81. package/src/state/assignment.js +0 -333
  82. package/src/tcp-v1/framing.js +0 -203
  83. package/src/tunnel/http-tunnel.js +0 -1694
  84. package/src/tunnel/tcp-tunnel.js +0 -862
  85. package/src/tunnel/udp-tunnel.js +0 -708
  86. package/src/tunnel/ws-control.js +0 -135
  87. package/src/udp-v1/framing.js +0 -203
@@ -1,1694 +0,0 @@
1
- // HTTP Tunnel - Pure proxy mode with no JWT validation
2
- // Ported from client-mvp/src/tunnel.js with JWT validation stripped
3
- import WebSocket from 'ws';
4
- import http from 'http';
5
- import crypto from 'node:crypto';
6
- // CLI-REAUTH: Control frame helper for in-band reauth
7
- import { sendControlAndWaitAck, dispatchControlFrame, clearAllWaiters } from './ws-control.js';
8
-
9
- // S-3: Import HTTP-WS v2 protocol constants
10
- import {
11
- HTTPWS_V2_TARGET_CHUNK_BYTES,
12
- HTTPWS_V2_MAX_CHUNK_BYTES,
13
- HTTP_BODY_CHUNK
14
- } from './httpws-constants.js';
15
-
16
- const V2_THRESHOLD_BYTES = 8 * 1024 * 1024; // 8 MiB threshold for v2 selection
17
-
18
- const TUNNEL_DROP_HEADERS = new Set([
19
- 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
20
- 'te', 'trailers', 'transfer-encoding', 'upgrade',
21
- 'sec-websocket-key', 'sec-websocket-version',
22
- 'forwarded', 'x-forwarded-host'
23
- ]);
24
-
25
- function headersToObject(headers) {
26
- const out = {};
27
- if (Array.isArray(headers)) {
28
- for (const pair of headers) {
29
- if (!Array.isArray(pair) || pair.length < 2) continue;
30
- const name = String(pair[0]).toLowerCase();
31
- const value = pair[1];
32
- out[name] = Array.isArray(value) ? value.map((part) => String(part)).join(', ') : (value == null ? '' : String(value));
33
- }
34
- return out;
35
- }
36
- if (headers && typeof headers === 'object') {
37
- for (const [name, value] of Object.entries(headers)) {
38
- out[String(name).toLowerCase()] = value;
39
- }
40
- }
41
- return out;
42
- }
43
-
44
- function sanitizeLocalRequest(url, headers, bodyBuffer, localPort) {
45
- if (typeof url !== 'string' || !url.startsWith('/') || url.startsWith('//') || /[\r\n]/.test(url)) {
46
- return { error: 400 };
47
- }
48
- const source = headersToObject(headers);
49
- const out = {};
50
- for (const [name, value] of Object.entries(source)) {
51
- if (TUNNEL_DROP_HEADERS.has(name)) continue;
52
- if (/[\r\n]/.test(name)) return { error: 400 };
53
- const parts = Array.isArray(value) ? value : [value];
54
- if (parts.some((part) => typeof part === 'string' && /[\r\n]/.test(part))) {
55
- return { error: 400 };
56
- }
57
- out[name] = value;
58
- }
59
- const host = out.host == null ? '' : String(out.host);
60
- if (!host || /[\r\n]/.test(host)) {
61
- out.host = `localhost:${localPort}`;
62
- }
63
- delete out['transfer-encoding'];
64
- if (bodyBuffer && bodyBuffer.length > 0) {
65
- out['content-length'] = String(bodyBuffer.length);
66
- }
67
- return { path: url, headers: out };
68
- }
69
-
70
- export class HttpTunnel {
71
- constructor({
72
- relayUrl,
73
- jwt,
74
- deviceId,
75
- requestId,
76
- localPort,
77
- log,
78
- coordinatorCore,
79
- coordinatorIngress,
80
- // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
81
- isControlPlaneConnected = () => true,
82
- waitForControlPlane = () => Promise.resolve(),
83
- getLastMqttError = () => null, // QPA-CLI-02: Get last MQTT error for diagnostics
84
- getForceReconnect = () => null, // QPA-CLI-03: Get force reconnect function
85
- controlPlaneTimeoutMs = 60000,
86
- // QPA-04: QuickPass security group slug
87
- secGroupSlug = null,
88
- // TPB-12: Instance ID for per-instance assignment routing
89
- instanceId = null
90
- }) {
91
- this.relayUrl = relayUrl;
92
- this.jwt = jwt; // Accept JWT as-is (no validation)
93
- this.deviceId = deviceId;
94
- this.requestId = requestId;
95
- this.localPort = localPort;
96
- this.log = log;
97
- this.ws = null;
98
- // QPA-04: Store secGroupSlug for use in refresh payloads
99
- this.secGroupSlug = secGroupSlug;
100
- // TPB-12: Store instanceId for per-instance assignment lookups
101
- this.instanceId = instanceId;
102
-
103
- // CLI-IMG-WSReconnect: Coordinator connection for JWT refresh
104
- this.coordinatorCore = coordinatorCore;
105
- this.coordinatorIngress = coordinatorIngress;
106
-
107
- // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
108
- this.isControlPlaneConnected = isControlPlaneConnected;
109
- this.waitForControlPlane = waitForControlPlane;
110
- this.getLastMqttError = getLastMqttError; // QPA-CLI-02: Store helper to get last MQTT error
111
- this.getForceReconnect = getForceReconnect; // QPA-CLI-03: Store helper to force reconnect
112
- this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
113
-
114
- // CRT-Relay-E: Heartbeat properties
115
- this.heartbeatTimer = null;
116
- this.lastActivityMs = Date.now();
117
-
118
- // CLI-IMG-WSReconnect: Reconnect properties
119
- this.shouldReconnect = true;
120
- this.retryCount = 0;
121
- // CLI-IMG-Retry-Ceiling: Increase retry ceiling to 60 (configurable)
122
- this.maxRetries = parseInt(process.env.ASYX_TUNNEL_MAX_RETRIES || "60", 10);
123
- this.reconnectTimer = null;
124
- this.headers = null; // Store headers for reuse during reconnects
125
-
126
- // CLI-JWT-REFRESH: Refresh state machine
127
- // QPA-CLI-01: Extended states for resilience
128
- this.refreshState = 'idle'; // idle | pending | waiting_control_plane | retry_scheduled | fallback | failed
129
- this.refreshAttempts = 0;
130
- this.refreshMaxAttempts = parseInt(process.env.ASYX_TUNNEL_REFRESH_MAX_RETRIES || '3', 10);
131
- // QPA-CLI-01: Refresh supervisor state
132
- this.refreshRetryTimer = null;
133
- this.refreshDeadline = null; // JWT expiry deadline (expMs - safetyMargin)
134
- this.refreshRetryCount = 0;
135
- this.refreshRetryMaxDelay = 30000; // Max 30s between retries
136
-
137
- // CLI-RES-DPJWT-LEAD: Proactive refresh scheduling
138
- this.refreshTimer = null;
139
- this.jwtMeta = null; // { token, expMs } for lead window checks
140
- this.LEAD_MS = Number(process.env.ASYX_REFRESH_LEAD_MS || 180000); // 3 minutes (default), configurable via env
141
-
142
- // CLI-REAUTH: In-band reauth configuration
143
- this.reauthAckTimeoutMs = Number(process.env.CLI_REAUTH_ACK_TIMEOUT_MS || 3000); // 3 seconds default
144
- this.reauthInFlight = null; // Single-flight guard: Promise or null
145
-
146
- // S-0: Track negotiated HTTP-WS version
147
- this.httpWsVersion = null;
148
-
149
- // S-1: Track in-progress v2 responses (requestId -> { mode: 'v2', bufferedBytes: 0 })
150
- this.activeV2Responses = new Map();
151
- }
152
-
153
- // CLI-RES-DPJWT-LEAD: Safe JWT decode helper
154
- _decodeJwtExp(token) {
155
- try {
156
- if (!token || typeof token !== 'string') {
157
- return null;
158
- }
159
- const parts = token.split('.');
160
- if (parts.length !== 3) {
161
- return null;
162
- }
163
- // Base64URL decode the payload (second part)
164
- const payload = Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
165
- const parsed = JSON.parse(payload);
166
-
167
- if (!parsed.exp || typeof parsed.exp !== 'number') {
168
- return null;
169
- }
170
-
171
- const expMs = parsed.exp * 1000; // Convert to milliseconds
172
- const nowMs = Date.now();
173
- const issuedAtMs = parsed.iat ? parsed.iat * 1000 : null;
174
- const skewMs = expMs - nowMs;
175
-
176
- return { expMs, issuedAtMs, skewMs };
177
- } catch (err) {
178
- // Malformed JWT - return null to skip scheduling
179
- return null;
180
- }
181
- }
182
-
183
- // CLI-REAUTH: Extract JTI from JWT for prev hint
184
- _extractJti(token) {
185
- try {
186
- if (!token || typeof token !== 'string') {
187
- return null;
188
- }
189
- const parts = token.split('.');
190
- if (parts.length !== 3) {
191
- return null;
192
- }
193
- const payload = Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
194
- const parsed = JSON.parse(payload);
195
- return parsed.jti || null;
196
- } catch (err) {
197
- return null;
198
- }
199
- }
200
-
201
- // CLI-RES-DPJWT-LEAD: Schedule proactive refresh
202
- scheduleRefresh(token, context = 'unknown') {
203
- // Clear existing timer
204
- if (this.refreshTimer) {
205
- clearTimeout(this.refreshTimer);
206
- this.refreshTimer = null;
207
- }
208
-
209
- // Decode JWT to get exp
210
- const decoded = this._decodeJwtExp(token);
211
- if (!decoded) {
212
- this.log.warn('jwt.refresh.schedule.invalid_token', { context });
213
- return; // Skip scheduling for invalid tokens
214
- }
215
-
216
- const { expMs, issuedAtMs, skewMs } = decoded;
217
- const nowMs = Date.now();
218
-
219
- // CLI-RES-DPJWT-LEAD: Guard against short TTLs to prevent refresh loops
220
- const ttlMs = expMs - (issuedAtMs ?? expMs - this.LEAD_MS);
221
- if (ttlMs <= this.LEAD_MS) {
222
- const adjusted = Math.max(30000, Math.floor(ttlMs / 4));
223
- if (adjusted !== this.LEAD_MS) {
224
- this.log.warn('jwt.refresh.lead_adjusted', { context, originalLeadMs: this.LEAD_MS, adjustedLeadMs: adjusted, ttlMs });
225
- this.LEAD_MS = adjusted;
226
- }
227
- }
228
-
229
- // Check for clock skew warning (before determining refresh timing)
230
- if (skewMs < this.LEAD_MS) {
231
- this.log.warn('jwt.refresh.schedule.skew_warning', {
232
- expEpochMs: expMs,
233
- leadMs: this.LEAD_MS,
234
- skewMs,
235
- context
236
- });
237
- }
238
-
239
- // Clamp refreshAt to never precede "issued at" and add 30s final buffer
240
- const refreshAt = Math.min(
241
- expMs - this.LEAD_MS,
242
- issuedAtMs ? Math.max(issuedAtMs + 1000, expMs - this.LEAD_MS) : expMs - this.LEAD_MS,
243
- expMs - 30000 // Final 30s buffer
244
- );
245
-
246
- // Store JWT metadata for reconnect checks (before immediate check so _checkRefreshLeadWindow has accurate state)
247
- this.jwtMeta = { token, expMs };
248
-
249
- // Check if already in lead window
250
- if (nowMs >= refreshAt) {
251
- this.log.info('jwt.refresh.schedule.immediate', {
252
- expEpochMs: expMs,
253
- leadMs: this.LEAD_MS,
254
- refreshAtEpochMs: refreshAt,
255
- skewMs,
256
- context
257
- });
258
- // Trigger refresh immediately
259
- this.attemptJwtRefresh().catch(err => {
260
- this.log.error('jwt.refresh.immediate.failure', { error: err.message });
261
- });
262
- return;
263
- }
264
-
265
- // Schedule refresh
266
- const delayMs = refreshAt - nowMs;
267
- this.refreshTimer = setTimeout(() => {
268
- this.refreshTimer = null;
269
- this.log.info('jwt.refresh.schedule.trigger', {
270
- expEpochMs: expMs,
271
- leadMs: this.LEAD_MS,
272
- context: 'timer'
273
- });
274
- this.attemptJwtRefresh().catch(err => {
275
- this.log.error('jwt.refresh.scheduled.failure', { error: err.message });
276
- });
277
- }, delayMs);
278
-
279
- // Log scheduling
280
- this.log.info('jwt.refresh.schedule', {
281
- expEpochMs: expMs,
282
- leadMs: this.LEAD_MS,
283
- refreshAtEpochMs: refreshAt,
284
- skewMs,
285
- context
286
- });
287
- }
288
-
289
- // CLI-REAUTH: In-band reauth helper
290
- async reauthInBand(newJwt, prevJti, trigger = 'timer') {
291
- // Single-flight guard: if reauth already in progress, wait for it
292
- if (this.reauthInFlight) {
293
- return this.reauthInFlight;
294
- }
295
-
296
- const { getAssignment } = await import('../state/assignment.js');
297
- // TPB-12: Use instanceId for per-instance assignment lookup
298
- const assignment = getAssignment(this.instanceId);
299
-
300
- if (!assignment || !assignment.leaseId) {
301
- this.log.warn('jwt.reauth.error', { code: 'no_assignment', instanceId: this.instanceId });
302
- return false;
303
- }
304
-
305
- // Calculate lead seconds for logging
306
- const decoded = this._decodeJwtExp(newJwt);
307
- const leadSeconds = decoded ? Math.floor((decoded.expMs - Date.now()) / 1000) : undefined;
308
-
309
- // Build reauth payload
310
- const payload = JSON.stringify({
311
- op: 'reauth',
312
- leaseId: assignment.leaseId,
313
- jwt: newJwt,
314
- prev: { jti: prevJti || null }
315
- });
316
-
317
- this.log.info('jwt.reauth.scheduled', {
318
- leadSeconds,
319
- trigger,
320
- leaseId: assignment.leaseId
321
- });
322
-
323
- // Create and store the promise for single-flight guard
324
- const reauthPromise = (async () => {
325
- try {
326
- const ack = await sendControlAndWaitAck(this.ws, payload, 'reauth_ack', this.reauthAckTimeoutMs);
327
-
328
- if (ack?.status === 'ok') {
329
- // Update JWT and metadata
330
- this.jwt = newJwt;
331
- const expMs = ack.active?.exp ? ack.active.exp * 1000 : (decoded?.expMs || null);
332
- this.jwtMeta = { token: newJwt, expMs };
333
-
334
- // Update headers for future reconnects
335
- this.headers = {
336
- 'Authorization': `Bearer ${this.jwt}`,
337
- 'X-Asyx-DeviceId': this.deviceId,
338
- 'X-Asyx-RequestId': assignment.requestId
339
- };
340
-
341
- // Re-schedule next proactive refresh
342
- this.scheduleRefresh(this.jwt, 'reauth_success');
343
-
344
- const ackLeadSeconds = ack.active?.exp
345
- ? Math.floor((ack.active.exp * 1000 - Date.now()) / 1000)
346
- : leadSeconds;
347
-
348
- this.log.info('jwt.reauth.ok', {
349
- leadSeconds: ackLeadSeconds,
350
- exp: ack.active?.exp,
351
- relayId: assignment.relayId
352
- });
353
-
354
- return true;
355
- }
356
-
357
- // Error or timeout
358
- const errorCode = ack?.error || 'timeout';
359
- this.log.warn('jwt.reauth.error', {
360
- code: errorCode,
361
- retryCount: this.refreshAttempts
362
- });
363
-
364
- return false;
365
- } catch (error) {
366
- this.log.warn('jwt.reauth.error', {
367
- code: 'exception',
368
- error: error.message,
369
- retryCount: this.refreshAttempts
370
- });
371
- return false;
372
- } finally {
373
- // Clear guard when done
374
- if (this.reauthInFlight === reauthPromise) {
375
- this.reauthInFlight = null;
376
- }
377
- }
378
- })();
379
-
380
- this.reauthInFlight = reauthPromise;
381
- return reauthPromise;
382
- }
383
-
384
- // CLI-RES-DPJWT-LEAD: Check if refresh needed on reconnect
385
- _checkRefreshLeadWindow() {
386
- if (!this.jwtMeta || !this.jwtMeta.expMs) {
387
- return false;
388
- }
389
-
390
- const nowMs = Date.now();
391
- const { expMs } = this.jwtMeta;
392
-
393
- // Check if we're in the lead window
394
- if (nowMs + this.LEAD_MS >= expMs) {
395
- this.log.info('jwt.refresh.schedule.immediate', {
396
- expEpochMs: expMs,
397
- leadMs: this.LEAD_MS,
398
- refreshAtEpochMs: expMs - this.LEAD_MS,
399
- skewMs: expMs - nowMs,
400
- context: 'reconnect_lead_window'
401
- });
402
- // Trigger refresh before resuming
403
- this.attemptJwtRefresh().catch(err => {
404
- this.log.error('jwt.refresh.reconnect.failure', { error: err.message });
405
- });
406
- return true;
407
- }
408
-
409
- return false;
410
- }
411
-
412
- // CLI-IMG-Refresh-Guard: Ensure control-plane connectivity with timeout
413
- // CLI-RES-WAITFORCONNECT: Updated to use transport.waitForConnect() directly
414
- async _ensureControlPlane(reason, forceWait = false) {
415
- if (!forceWait && this.isControlPlaneConnected()) return true;
416
-
417
- // QPA-CLI-01: Log actual MQTT reason when control-plane is offline
418
- const mqttReason = this.isControlPlaneConnected() ? 'connected' : 'offline';
419
- this.log.warn({ reason, mqttReason }, "Control-plane offline, waiting for reconnect");
420
-
421
- try {
422
- // Use waitForControlPlane which internally calls transport.waitForConnect()
423
- await this.waitForControlPlane();
424
- // CLI-MQTT-UniqueID-CleanSession: Get session client ID from transport for logging
425
- const lastMqttError = this.getLastMqttError ? this.getLastMqttError() : null;
426
- const sessionClientId = lastMqttError?.clientId || 'unknown';
427
- this.log.info({ reason, sessionClientId }, "Control-plane reconnected");
428
- return true;
429
- } catch (err) {
430
- // QPA-CLI-02: Get last MQTT error for diagnostic information
431
- const lastMqttError = this.getLastMqttError ? this.getLastMqttError() : null;
432
- const mqttReasonCode = lastMqttError?.code;
433
- const mqttReason = lastMqttError?.reason || this._extractMqttReasonFromError(lastMqttError);
434
-
435
- // QPA-CLI-01: Extract and log actual MQTT reason from WaitForConnectError
436
- let mqttErrorReason = 'unknown';
437
- if (err.name === 'WaitForConnectError') {
438
- // WaitForConnectError has a 'reason' property: 'timeout' | 'terminated'
439
- mqttErrorReason = err.reason || 'timeout';
440
-
441
- // QPA-CLI-03: Force reconnect on timeout
442
- if (mqttErrorReason === 'timeout' && this.getForceReconnect) {
443
- const forceReconnect = this.getForceReconnect();
444
- if (forceReconnect) {
445
- this.log.info('mqtt.transport.force_reconnect.attempt', { reason, attempt: 1 });
446
- try {
447
- await forceReconnect();
448
- // Retry waitForControlPlane up to 3 times with 5s delay
449
- const maxRetries = 3;
450
- const retryDelayMs = 5000;
451
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
452
- try {
453
- await new Promise(resolve => setTimeout(resolve, retryDelayMs));
454
- await this.waitForControlPlane();
455
- this.log.info('mqtt.transport.force_reconnect.success', { reason, attempt });
456
- this.log.info({ reason }, "Control-plane reconnected after force reconnect");
457
- return true;
458
- } catch (retryErr) {
459
- if (attempt < maxRetries) {
460
- this.log.warn('mqtt.transport.force_reconnect.retry', { reason, attempt: attempt + 1, error: retryErr.message });
461
- } else {
462
- this.log.warn('mqtt.transport.force_reconnect.exhausted', { reason, attempts: maxRetries });
463
- }
464
- }
465
- }
466
- } catch (forceErr) {
467
- this.log.warn('mqtt.transport.force_reconnect.failed', { reason, error: forceErr.message });
468
- }
469
- }
470
- }
471
-
472
- // QPA-CLI-02: Include MQTT error details in log
473
- this.log.warn('mqtt.transport.wait_for_connect.failed', {
474
- reason,
475
- mqttReason: mqttErrorReason,
476
- mqttErrorCode: mqttReasonCode,
477
- mqttErrorReason: mqttReason,
478
- mqttEvent: lastMqttError?.event,
479
- error: err.message
480
- });
481
- // QPA-CLI-02: User-facing message includes MQTT reason if available
482
- let userMessage = `⚠️ Control-plane offline (${mqttErrorReason})`;
483
- if (mqttReason && mqttReason !== 'unknown') {
484
- userMessage += `. MQTT reason: ${mqttReason}`;
485
- }
486
- userMessage += `. Waiting for reconnect…\n`;
487
- process.stdout.write(userMessage);
488
- return false;
489
- }
490
- if (err.message === "control_plane_timeout") {
491
- // QPA-CLI-02: Include MQTT error details in timeout log
492
- this.log.warn('mqtt.transport.wait_for_connect.timeout', {
493
- reason,
494
- mqttErrorCode: mqttReasonCode,
495
- mqttErrorReason: mqttReason,
496
- mqttEvent: lastMqttError?.event
497
- });
498
- let userMessage = `⚠️ Control-plane offline (timeout)`;
499
- if (mqttReason && mqttReason !== 'unknown') {
500
- userMessage += `. MQTT reason: ${mqttReason}`;
501
- }
502
- userMessage += `. Waiting for reconnect…\n`;
503
- process.stdout.write(userMessage);
504
- return false;
505
- }
506
- throw err;
507
- }
508
- }
509
-
510
- // QPA-CLI-02: Extract human-readable MQTT reason from error object
511
- _extractMqttReasonFromError(mqttError) {
512
- if (!mqttError) return 'unknown';
513
- if (mqttError.reason) return mqttError.reason;
514
- if (mqttError.code) {
515
- const codeNum = typeof mqttError.code === 'string' ? parseInt(mqttError.code, 10) : mqttError.code;
516
- const reasonMap = {
517
- 4: 'bad_username_password',
518
- 5: 'identifier_in_use',
519
- 6: 'server_unavailable',
520
- 7: 'bad_username_password',
521
- 8: 'not_authorized'
522
- };
523
- return reasonMap[codeNum] || `code_${codeNum}`;
524
- }
525
- return 'unknown';
526
- }
527
-
528
- async open() {
529
- // CLI-IMG-WSReconnect: Start the connection process
530
- return this._attemptConnect();
531
- }
532
-
533
- async _attemptConnect() {
534
- return new Promise((resolve, reject) => {
535
- // CLI-IMG-WSReconnect: Store headers for reuse during reconnects
536
- if (!this.headers) {
537
- this.headers = {
538
- 'Authorization': `Bearer ${this.jwt}`,
539
- 'X-Asyx-DeviceId': this.deviceId,
540
- 'X-Asyx-RequestId': this.requestId
541
- };
542
- }
543
-
544
- // CLI-IMG-WSReconnect: Clean up previous WebSocket if exists
545
- if (this.ws) {
546
- this.ws.removeAllListeners();
547
- this.ws = null;
548
- }
549
-
550
- // Connect to relay with TLS (rejectUnauthorized: true by default)
551
- this.ws = new WebSocket(this.relayUrl, {
552
- headers: this.headers,
553
- rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1' // Allow dev override
554
- });
555
-
556
- this.ws.on('open', () => {
557
- this.log.info({ relayUrl: this.relayUrl, localPort: this.localPort }, 'Tunnel WS open - proxy mode active');
558
-
559
- // CLI-IMG-WSReconnect: Reset retry count on successful connection
560
- this.retryCount = 0;
561
-
562
- // S-0: Send hello frame for HTTP-WS v2 negotiation
563
- this._sendHello();
564
-
565
- // CLI-RES-DPJWT-LEAD: Check if refresh needed before resuming
566
- this._checkRefreshLeadWindow();
567
-
568
- // CRT-Relay-E: Start heartbeat timer after WebSocket opens
569
- this.startHeartbeat();
570
-
571
- resolve();
572
- });
573
-
574
- this.ws.on('message', (data, isBinary) => {
575
- // CRT-Relay-E: Update activity on any message
576
- this.lastActivityMs = Date.now();
577
-
578
- if (!isBinary) {
579
- try {
580
- const msg = JSON.parse(data.toString());
581
-
582
- // CLI-REAUTH: Dispatch control frames to waiter registry
583
- if (msg.op && typeof msg.op === 'string') {
584
- if (dispatchControlFrame(msg)) {
585
- // Control frame was dispatched to a waiter, don't process further
586
- return;
587
- }
588
- // Control frame but no waiters - ignore unknown ops
589
- this.log.debug('jwt.reauth.unknown_control', { op: msg.op });
590
- return;
591
- }
592
-
593
- // CRT-Relay-E: Handle heartbeat pong
594
- if (msg.t === 'pong') {
595
- this.log.debug('tunnel heartbeat pong received');
596
- return;
597
- }
598
-
599
- // S-0: Handle hello_ack for HTTP-WS v2 negotiation
600
- if (msg.type === 'hello_ack') {
601
- this._handleHelloAck(msg);
602
- return;
603
- }
604
-
605
- if (msg.type === 'ping') {
606
- this.ws.send(JSON.stringify({ type: 'pong' }));
607
- return;
608
- }
609
- if (msg.type === 'http_request' || msg.t === 'http_request') {
610
- this.handleHttpRequest(msg);
611
- return;
612
- }
613
- } catch (_) {}
614
- }
615
-
616
- // Handle binary messages that look like HTTP requests
617
- const dataStr = data.toString();
618
- if (dataStr.startsWith('GET ') || dataStr.startsWith('POST ') || dataStr.startsWith('PUT ') ||
619
- dataStr.startsWith('DELETE ') || dataStr.startsWith('PATCH ') || dataStr.startsWith('HEAD ') ||
620
- dataStr.startsWith('OPTIONS ')) {
621
- this.handleHttpRequestBuffer(Buffer.from(data));
622
- } else {
623
- // Ignore binary messages that look like HTTP responses
624
- this.log.debug('Ignoring binary message (likely HTTP response)');
625
- }
626
- });
627
-
628
- this.ws.on('close', (code, reason) => {
629
- // QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
630
- const reasonStr = reason?.toString() || '';
631
- const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
632
- if (isNormalClose) {
633
- this.log.debug({ code, reason: reasonStr }, 'Tunnel WS closed');
634
- } else {
635
- this.log.warn({ code, reason: reasonStr }, 'Tunnel WS closed');
636
- }
637
- // CRT-Relay-E: Stop heartbeat on close
638
- this.stopHeartbeat();
639
- // CLI-REAUTH: Cleanup control frame waiters on socket close
640
- clearAllWaiters();
641
- // Clear single-flight guard
642
- this.reauthInFlight = null;
643
-
644
- // CLI-IMG-WSReconnect: Schedule reconnect instead of exiting
645
- this.scheduleReconnect(code, reason);
646
- });
647
-
648
- this.ws.on('error', (err) => {
649
- this.log.error({ err }, 'Tunnel WS error');
650
- // CRT-Relay-E: Stop heartbeat on error
651
- this.stopHeartbeat();
652
-
653
- // CLI-IMG-WSReconnect: Handle connection errors with reconnect
654
- this.scheduleReconnect(null, err.message);
655
- });
656
- });
657
- }
658
-
659
- // CLI-IMG-WSReconnect: Reconnect scheduling and logic
660
- scheduleReconnect(code, reason) {
661
- // Check if we should reconnect
662
- if (!this.shouldReconnect) {
663
- this.log.info('Reconnect disabled, returning');
664
- return;
665
- }
666
-
667
- // CLI-IMG-Retry-Ceiling: Check retry limit with descriptive messaging
668
- if (this.retryCount >= this.maxRetries) {
669
- this.log.error(
670
- { retryCount: this.retryCount, maxRetries: this.maxRetries },
671
- "Control-plane reconnect attempts exhausted; please restart the CLI"
672
- );
673
- process.exit(1);
674
- }
675
-
676
- // Check for JWT expiration - attempt refresh instead of exiting
677
- // Handle both jwt_invalid (code 1000) and EJWT_EXPIRED (code 1008) cases
678
- const reasonStr = reason?.toString() || '';
679
- const lower = reasonStr.toLowerCase();
680
- const isJwtInvalid = code === 1000 && lower.includes('jwt_invalid');
681
- const isJwtExpired = code === 1008 && lower.includes('ejwt_expired');
682
-
683
- if (isJwtInvalid || isJwtExpired) {
684
- const triggerReason = isJwtInvalid ? 'jwt_invalid' : 'ejwt_expired';
685
- this.log.warn('jwt.refresh.trigger', { triggerReason, code, reason: reasonStr });
686
- this.attemptJwtRefresh();
687
- return;
688
- }
689
-
690
- // Calculate exponential backoff with jitter
691
- const baseDelay = Math.min(1000 * Math.pow(2, this.retryCount), 30000); // Max 30s
692
- const jitter = Math.random() * 0.4 - 0.2; // ±20% jitter
693
- const delay = Math.max(1000, Math.floor(baseDelay * (1 + jitter)));
694
-
695
- this.retryCount++;
696
-
697
- // QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
698
- const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
699
- if (isNormalClose) {
700
- this.log.debug({
701
- delay,
702
- retryCount: this.retryCount,
703
- maxRetries: this.maxRetries,
704
- code,
705
- reason: reasonStr
706
- }, 'Tunnel WS reconnect scheduled');
707
- } else {
708
- this.log.warn({
709
- delay,
710
- retryCount: this.retryCount,
711
- maxRetries: this.maxRetries,
712
- code,
713
- reason: reasonStr
714
- }, 'Tunnel WS reconnect scheduled');
715
- }
716
-
717
- // Schedule reconnect attempt
718
- this.reconnectTimer = setTimeout(() => {
719
- this.attemptReconnect();
720
- }, delay);
721
- }
722
-
723
- async attemptReconnect() {
724
- try {
725
- this.log.info({ retryCount: this.retryCount }, 'Attempting to reconnect...');
726
- await this._attemptConnect();
727
- this.log.info('Reconnected successfully');
728
-
729
- // CLI-IMG-WSReconnect: Clear reconnect timer on successful reconnect
730
- if (this.reconnectTimer) {
731
- clearTimeout(this.reconnectTimer);
732
- this.reconnectTimer = null;
733
- }
734
- } catch (error) {
735
- this.log.error({ error: error.message, retryCount: this.retryCount }, 'Reconnect attempt failed');
736
- // scheduleReconnect will be called from the error handler in _attemptConnect
737
- }
738
- }
739
-
740
- // QPA-CLI-01: Schedule retry with exponential backoff
741
- _scheduleRefreshRetry(reason) {
742
- // Clear any existing retry timer
743
- if (this.refreshRetryTimer) {
744
- clearTimeout(this.refreshRetryTimer);
745
- this.refreshRetryTimer = null;
746
- }
747
-
748
- // QPA-CLI-03: Check if we've exceeded the deadline AND MQTT is still offline
749
- if (this.refreshDeadline && Date.now() >= this.refreshDeadline) {
750
- // Only mark expired if control plane is still offline
751
- if (!this.isControlPlaneConnected()) {
752
- this.log.error('jwt.refresh.expired', {
753
- retryCount: this.refreshRetryCount,
754
- deadline: this.refreshDeadline,
755
- elapsed: Date.now() - (this.refreshDeadline - this.LEAD_MS)
756
- });
757
- this.refreshState = 'failed';
758
- process.stdout.write(`❌ JWT expired while control-plane was offline. Exiting.\n`);
759
- process.exit(1);
760
- } else {
761
- // Control plane came back, reset deadline and continue
762
- this.log.info('jwt.refresh.deadline_extended', {
763
- retryCount: this.refreshRetryCount,
764
- oldDeadline: this.refreshDeadline
765
- });
766
- // Extend deadline by another 90 seconds
767
- this.refreshDeadline = Date.now() + 90000;
768
- }
769
- }
770
-
771
- // Calculate exponential backoff delay
772
- this.refreshRetryCount += 1;
773
- const baseDelay = 5000; // 5 seconds
774
- const delayMs = Math.min(baseDelay * Math.pow(2, this.refreshRetryCount - 1), this.refreshRetryMaxDelay);
775
-
776
- this.log.info('jwt.refresh.delay', {
777
- reason: 'control_plane_offline',
778
- retryCount: this.refreshRetryCount,
779
- nextDelayMs: delayMs,
780
- deadline: this.refreshDeadline ? new Date(this.refreshDeadline).toISOString() : null
781
- });
782
-
783
- // QPA-CLI-01: Operator feedback
784
- process.stdout.write(`⚠️ QuickPass token refresh delayed – reconnecting control plane… (retry ${this.refreshRetryCount})\n`);
785
-
786
- this.refreshState = 'retry_scheduled';
787
- this.refreshRetryTimer = setTimeout(() => {
788
- this.refreshRetryTimer = null;
789
- // Retry the refresh
790
- this.attemptJwtRefresh().catch(err => {
791
- this.log.error('jwt.refresh.retry.failed', { error: err.message, retryCount: this.refreshRetryCount });
792
- });
793
- }, delayMs);
794
- }
795
-
796
- // QPA-CLI-01: Cancel scheduled retry (called when MQTT reconnects)
797
- _cancelRefreshRetry() {
798
- if (this.refreshRetryTimer) {
799
- clearTimeout(this.refreshRetryTimer);
800
- this.refreshRetryTimer = null;
801
- }
802
- if (this.refreshState === 'retry_scheduled' || this.refreshState === 'waiting_control_plane') {
803
- this.log.info('jwt.refresh.resumed', { retryCount: this.refreshRetryCount });
804
- this.refreshState = 'pending';
805
- }
806
- }
807
-
808
- // CLI-IMG-WSReconnect: JWT refresh logic
809
- async attemptJwtRefresh() {
810
- try {
811
- // QPA-CLI-01: Check if we've exceeded max attempts (only for actual refresh attempts, not retries)
812
- if (this.refreshAttempts >= this.refreshMaxAttempts && this.refreshState !== 'retry_scheduled' && this.refreshState !== 'waiting_control_plane') {
813
- this.log.error('jwt.refresh.exhausted', { retryCount: this.refreshAttempts });
814
- this.refreshState = 'failed';
815
- process.exit(1);
816
- }
817
-
818
- // QPA-CLI-01: Set refresh deadline on first attempt
819
- if (this.refreshState === 'idle' && this.jwtMeta?.expMs) {
820
- const safetyMargin = 90000; // QPA-CLI-03: Extended to 90 seconds safety margin
821
- this.refreshDeadline = this.jwtMeta.expMs - safetyMargin;
822
- this.refreshRetryCount = 0; // Reset retry count for new refresh cycle
823
- }
824
-
825
- this.refreshAttempts += 1;
826
- this.refreshState = 'pending';
827
- this.log.info('jwt.refresh.start', { retryCount: this.refreshAttempts });
828
-
829
- // QPA-CLI-01: Ensure control-plane connectivity with retry logic
830
- const ready = await this._ensureControlPlane("jwt_refresh");
831
- if (!ready) {
832
- // QPA-CLI-01: Instead of immediately falling back, schedule a retry
833
- this.refreshState = 'waiting_control_plane';
834
- this._scheduleRefreshRetry('control_plane_offline');
835
- return; // Keep tunnel running, retry will happen via timer
836
- }
837
-
838
- // QPA-CLI-01: Control-plane is ready, cancel any pending retry
839
- this._cancelRefreshRetry();
840
-
841
- // Check if we have coordinator connection
842
- if (!this.coordinatorCore || !this.coordinatorIngress) {
843
- this.log.error('jwt.refresh.no_coordinator');
844
- process.exit(1);
845
- }
846
-
847
- // Import assignment functions
848
- const { getAssignment } = await import('../state/assignment.js');
849
- const { getFpHash } = await import('../lib/fingerprint.js');
850
-
851
- // TPB-12: Get current assignment for this specific instance
852
- const currentAssignment = getAssignment(this.instanceId);
853
- if (!currentAssignment) {
854
- this.log.error('jwt.refresh.no_current_assignment', { instanceId: this.instanceId });
855
- process.exit(1);
856
- }
857
-
858
- // CRT-Lease-Refresh-ExtendTTL: Use refreshOf field to reuse existing lease
859
- const refreshRequestId = `refresh-${Date.now()}`; // New requestId for refresh
860
- const leaseId = currentAssignment.leaseId;
861
-
862
- if (!leaseId) {
863
- this.log.error('jwt.refresh.no_lease_id');
864
- process.exit(1);
865
- }
866
-
867
- // Get fingerprint for the refresh request
868
- const fingerprint = await getFpHash(this.deviceId);
869
-
870
- // Build refresh payload - use refreshOf field to reuse existing lease
871
- // CLI-RES-COORD-EVENTBRIDGE: Do NOT set reconnect: true for JWT refresh.
872
- // Reconnect is only for re-establishing after disconnection; refresh should only use refreshOf.
873
- const refreshPayload = {
874
- requestId: refreshRequestId, // New requestId for this refresh
875
- refreshOf: leaseId, // CLI-RES-COORD-EVENTBRIDGE: Tell coordinator to reuse this lease via refreshLease()
876
- // reconnect: true removed - this is JWT refresh, not reconnect
877
- proto: 'http',
878
- localPort: this.localPort,
879
- clientId: this.deviceId,
880
- ...fingerprint
881
- };
882
-
883
- // QPA-04: Include secGroupSlug in refresh payload if provided
884
- if (this.secGroupSlug) {
885
- refreshPayload.secGroupSlug = this.secGroupSlug;
886
- }
887
-
888
- // Set up topic for refresh request
889
- const cmdOpenTopic = `asyx/tunnel/clients/${this.deviceId}/cmd/open`;
890
-
891
- // Wait for open_ack with timeout
892
- const ackPromise = this.coordinatorIngress.registerAwaiter((message) => {
893
- try {
894
- const parsed = message.payload;
895
- return parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
896
- } catch (e) {
897
- return false;
898
- }
899
- }, 10000);
900
-
901
- // CLI-IMG-MQTT-Resilience: Publish with retry logic and fallback
902
- try {
903
- // Publish the refresh request
904
- await this.coordinatorCore.publish({
905
- topic: cmdOpenTopic,
906
- payload: JSON.stringify(refreshPayload),
907
- qos: 1,
908
- retain: false
909
- });
910
-
911
- this.log.info('jwt.refresh.request.sent', { refreshRequestId, retryCount: this.refreshAttempts });
912
-
913
- // Wait for new assignment with timeout handling
914
- try {
915
- await ackPromise;
916
- } catch (timeoutError) {
917
- this.log.warn('jwt.refresh.timeout', { retryCount: this.refreshAttempts, error: timeoutError.message });
918
- // CLI-IMG-MQTT-Resilience: Fallback to fresh tunnel when awaiter times out
919
- await this._fallbackToFreshTunnel();
920
- return;
921
- }
922
- } catch (publishError) {
923
- this.log.warn('jwt.refresh.publish_failed', { retryCount: this.refreshAttempts, error: publishError.message });
924
- await this._ensureControlPlane('jwt_refresh_retry', true);
925
- // CLI-IMG-MQTT-Resilience: Fallback to fresh tunnel when publish fails
926
- await this._fallbackToFreshTunnel();
927
- return;
928
- }
929
-
930
- // TPB-12: Get the new assignment for this specific instance
931
- const newAssignment = getAssignment(this.instanceId);
932
- if (!newAssignment) {
933
- this.log.error('jwt.refresh.no_new_assignment', { instanceId: this.instanceId });
934
- process.exit(1);
935
- }
936
-
937
- // CLI-REAUTH: Try in-band reauth if WebSocket is open, otherwise fallback to reconnect
938
- const prevJti = this.jwtMeta?.token ? this._extractJti(this.jwtMeta.token) : null;
939
- const newJwt = newAssignment.jwt;
940
-
941
- // Check if WebSocket is open and try in-band reauth
942
- if (this.ws && this.ws.readyState === 1) { // WebSocket.OPEN = 1
943
- // Start in-band reauth (guard is inside reauthInBand)
944
- try {
945
- const reauthSuccess = await this.reauthInBand(newJwt, prevJti, 'timer');
946
-
947
- if (reauthSuccess) {
948
- // In-band reauth succeeded - update assignment state and we're done
949
- // CLI-IMG-WSReconnect: Update tunnel state with new assignment
950
- this.requestId = newAssignment.requestId;
951
- this.relayUrl = newAssignment.relayUrl;
952
- this.headers = {
953
- 'Authorization': `Bearer ${this.jwt}`,
954
- 'X-Asyx-DeviceId': this.deviceId,
955
- 'X-Asyx-RequestId': this.requestId
956
- };
957
-
958
- // Record refresh timestamp and delta metrics
959
- const { recordRefresh } = await import('../state/assignment.js');
960
- const deltaMs = recordRefresh(this.instanceId, Date.now());
961
- this.log.info('jwt.refresh.delta', { deltaMs });
962
- this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'in_band' });
963
- // QPA-CLI-01: Reset retry state on success
964
- this.refreshState = 'idle';
965
- this.refreshAttempts = 0;
966
- this.refreshRetryCount = 0;
967
- this.refreshDeadline = null;
968
- this._cancelRefreshRetry();
969
- return; // Socket stayed open, no reconnect needed
970
- }
971
-
972
- // Reauth failed, fall through to reconnect
973
- this.log.info('jwt.reauth.fallback_reconnect', { retryCount: this.refreshAttempts });
974
- } catch (reauthError) {
975
- this.log.warn('jwt.reauth.exception', { error: reauthError.message });
976
- this.log.info('jwt.reauth.fallback_reconnect', { retryCount: this.refreshAttempts });
977
- // Fall through to reconnect
978
- }
979
- }
980
-
981
- // Fallback path: update state and reconnect with new JWT
982
- // CLI-IMG-WSReconnect: Update tunnel state with new assignment
983
- this.jwt = newJwt;
984
- this.requestId = newAssignment.requestId;
985
- this.relayUrl = newAssignment.relayUrl;
986
- this.headers = {
987
- 'Authorization': `Bearer ${this.jwt}`,
988
- 'X-Asyx-DeviceId': this.deviceId,
989
- 'X-Asyx-RequestId': newAssignment.requestId
990
- };
991
-
992
- // Record refresh timestamp and delta metrics
993
- const { recordRefresh } = await import('../state/assignment.js');
994
- const deltaMs = recordRefresh(this.instanceId, Date.now());
995
- this.log.info('jwt.refresh.delta', { deltaMs });
996
- this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'reconnect' });
997
- // QPA-CLI-01: Reset retry state on success
998
- this.refreshState = 'idle';
999
- this.refreshAttempts = 0;
1000
- this.refreshRetryCount = 0;
1001
- this.refreshDeadline = null;
1002
- this._cancelRefreshRetry();
1003
-
1004
- // CLI-RES-DPJWT-LEAD: Schedule next proactive refresh
1005
- this.scheduleRefresh(this.jwt, 'refresh_success');
1006
-
1007
- // Attempt reconnect with new JWT
1008
- await this._attemptConnect();
1009
-
1010
- } catch (error) {
1011
- this.log.error('jwt.refresh.failure', { error: error.message, retryCount: this.refreshAttempts });
1012
- this.refreshState = 'failed';
1013
- process.exit(1);
1014
- }
1015
- }
1016
-
1017
- // CLI-RES-REFRESH-FALLBACK: Lease-preserving fallback when refresh fails
1018
- // Reuses existing lease via refreshOf instead of creating a fresh tunnel
1019
- async _fallbackToFreshTunnel() {
1020
- this.refreshState = 'fallback';
1021
-
1022
- // TPB-12: Get current assignment for this specific instance
1023
- const { getAssignment } = await import('../state/assignment.js');
1024
- const currentAssignment = getAssignment(this.instanceId);
1025
-
1026
- if (!currentAssignment) {
1027
- this.log.error('jwt.refresh.fallback.no_assignment', { error: 'no_current_assignment', instanceId: this.instanceId });
1028
- process.exit(1);
1029
- }
1030
-
1031
- const leaseId = currentAssignment.leaseId;
1032
- const relayId = currentAssignment.relayId;
1033
-
1034
- if (!leaseId) {
1035
- this.log.error('jwt.refresh.fallback.no_lease_id', { error: 'lease_id_missing' });
1036
- process.exit(1);
1037
- }
1038
-
1039
- this.log.info('jwt.refresh.fallback.start', { reason: 'refresh_timeout_or_publish_failure', leaseId, relayId });
1040
-
1041
- // Retry loop with max attempts
1042
- let retryCount = 0;
1043
- const maxFallbackRetries = this.refreshMaxAttempts;
1044
-
1045
- while (retryCount < maxFallbackRetries) {
1046
- try {
1047
- // CLI-RES-REFRESH-FALLBACK: Control-plane gating before fallback
1048
- const ready = await this._ensureControlPlane('jwt_refresh_fallback');
1049
- if (!ready) {
1050
- this.log.warn('jwt.refresh.fallback.control_plane_timeout', { retryCount, leaseId });
1051
- try {
1052
- await this.waitForControlPlane();
1053
- this.log.info('jwt.refresh.fallback.control_plane_recovered', { leaseId });
1054
- } catch (waitError) {
1055
- // QPA-CLI-01: Instead of exiting, schedule a retry
1056
- this.log.warn('jwt.refresh.fallback.control_plane_wait_failed', {
1057
- error: waitError.message,
1058
- retryCount,
1059
- leaseId
1060
- });
1061
- // Schedule retry with backoff
1062
- this._scheduleRefreshRetry('fallback_control_plane_offline');
1063
- return; // Keep tunnel running, retry will happen via timer
1064
- }
1065
- }
1066
-
1067
- // CLI-RES-REFRESH-FALLBACK: Build lease-preserving refresh payload
1068
- const { getFpHash } = await import('../lib/fingerprint.js');
1069
- const fingerprint = await getFpHash(this.deviceId);
1070
- const refreshRequestId = `refresh-${Date.now()}`;
1071
-
1072
- const refreshPayload = {
1073
- requestId: refreshRequestId,
1074
- refreshOf: leaseId, // CLI-RES-REFRESH-FALLBACK: Reuse existing lease
1075
- reconnect: false, // This is a refresh, not a reconnect
1076
- proto: 'http',
1077
- localPort: this.localPort,
1078
- clientId: this.deviceId,
1079
- ...fingerprint
1080
- };
1081
-
1082
- // Set up topic for refresh request
1083
- const cmdOpenTopic = `asyx/tunnel/clients/${this.deviceId}/cmd/open`;
1084
-
1085
- // Wait for open_ack with timeout
1086
- const ackPromise = this.coordinatorIngress.registerAwaiter((message) => {
1087
- try {
1088
- const parsed = message.payload;
1089
- return parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
1090
- } catch (e) {
1091
- return false;
1092
- }
1093
- }, 10000);
1094
-
1095
- // CLI-RES-REFRESH-FALLBACK: Publish lease-preserving refresh request
1096
- try {
1097
- await this.coordinatorCore.publish({
1098
- topic: cmdOpenTopic,
1099
- payload: JSON.stringify(refreshPayload),
1100
- qos: 1,
1101
- retain: false
1102
- });
1103
-
1104
- this.log.info('jwt.refresh.fallback.request.sent', {
1105
- refreshRequestId,
1106
- leaseId,
1107
- relayId,
1108
- retryCount: retryCount + 1
1109
- });
1110
-
1111
- // Wait for open_ack with timeout handling
1112
- try {
1113
- await ackPromise;
1114
- } catch (timeoutError) {
1115
- retryCount++;
1116
- this.log.warn('jwt.refresh.fallback.timeout', {
1117
- retryCount,
1118
- leaseId,
1119
- error: timeoutError.message
1120
- });
1121
- if (retryCount >= maxFallbackRetries) {
1122
- this.log.error('jwt.refresh.fallback.failure', {
1123
- error: 'ack_timeout_exhausted',
1124
- retryCount,
1125
- leaseId
1126
- });
1127
- this.refreshState = 'failed';
1128
- process.exit(1);
1129
- }
1130
- continue; // Retry fallback
1131
- }
1132
- } catch (publishError) {
1133
- retryCount++;
1134
- this.log.warn('jwt.refresh.fallback.publish_failed', {
1135
- retryCount,
1136
- leaseId,
1137
- error: publishError.message
1138
- });
1139
- if (retryCount >= maxFallbackRetries) {
1140
- this.log.error('jwt.refresh.fallback.failure', {
1141
- error: 'publish_failed_exhausted',
1142
- retryCount,
1143
- leaseId
1144
- });
1145
- this.refreshState = 'failed';
1146
- process.exit(1);
1147
- }
1148
- // Wait briefly before retry
1149
- await new Promise(resolve => setTimeout(resolve, 1000));
1150
- continue;
1151
- }
1152
-
1153
- // TPB-12: Get the new assignment for this specific instance
1154
- const newAssignment = getAssignment(this.instanceId);
1155
- if (!newAssignment) {
1156
- retryCount++;
1157
- this.log.warn('jwt.refresh.fallback.no_new_assignment', { retryCount, leaseId, instanceId: this.instanceId });
1158
- if (retryCount >= maxFallbackRetries) {
1159
- this.log.error('jwt.refresh.fallback.failure', {
1160
- error: 'no_assignment_after_ack',
1161
- retryCount,
1162
- leaseId
1163
- });
1164
- this.refreshState = 'failed';
1165
- process.exit(1);
1166
- }
1167
- continue;
1168
- }
1169
-
1170
- // CLI-RES-REFRESH-FALLBACK: Update tunnel state with refreshed assignment
1171
- this.jwt = newAssignment.jwt;
1172
- this.requestId = newAssignment.requestId;
1173
- this.relayUrl = newAssignment.relayUrl;
1174
- this.headers = {
1175
- 'Authorization': `Bearer ${this.jwt}`,
1176
- 'X-Asyx-DeviceId': this.deviceId,
1177
- 'X-Asyx-RequestId': newAssignment.requestId
1178
- };
1179
-
1180
- // Record refresh delta for fallback path
1181
- const { recordRefresh } = await import('../state/assignment.js');
1182
- const deltaMs = recordRefresh(this.instanceId, Date.now());
1183
- this.log.info('jwt.refresh.delta', { deltaMs });
1184
- this.log.info('jwt.refresh.fallback.success', {
1185
- leaseId: newAssignment.leaseId || leaseId,
1186
- relayId: newAssignment.relayId || relayId,
1187
- deltaMs
1188
- });
1189
- this.refreshState = 'idle';
1190
- this.refreshAttempts = 0;
1191
-
1192
- // CLI-RES-DPJWT-LEAD: Schedule next proactive refresh
1193
- this.scheduleRefresh(this.jwt, 'fallback_success');
1194
-
1195
- // Reconnect WebSocket with refreshed JWT
1196
- await this._attemptConnect();
1197
-
1198
- // Success - exit retry loop
1199
- return;
1200
-
1201
- } catch (error) {
1202
- retryCount++;
1203
- this.log.warn('jwt.refresh.fallback.retry', {
1204
- error: error.message,
1205
- retryCount,
1206
- leaseId
1207
- });
1208
- if (retryCount >= maxFallbackRetries) {
1209
- this.log.error('jwt.refresh.fallback.failure', {
1210
- error: error.message,
1211
- retryCount,
1212
- leaseId
1213
- });
1214
- this.refreshState = 'failed';
1215
- process.exit(1);
1216
- }
1217
- // Brief delay before retry
1218
- await new Promise(resolve => setTimeout(resolve, 1000));
1219
- }
1220
- }
1221
- }
1222
-
1223
- sendTunnelError(requestId, status) {
1224
- const responseData = {
1225
- t: 'http_response',
1226
- rid: requestId,
1227
- s: status,
1228
- h: [['content-type', 'text/plain']],
1229
- b: ''
1230
- };
1231
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1232
- this.ws.send(JSON.stringify(responseData));
1233
- }
1234
- }
1235
-
1236
- handleHttpRequest(msg) {
1237
- // CRT-Relay-E: Update activity on HTTP request
1238
- this.lastActivityMs = Date.now();
1239
-
1240
- // Handle JSON-formatted HTTP request from relay (CRT-Relay-B compact format)
1241
- const { t, rid, m, u, h, b } = msg;
1242
-
1243
- // Extract fields from compact format
1244
- const requestId = rid;
1245
- const method = m;
1246
- const bodyBuffer = b ? Buffer.from(b, 'base64') : null;
1247
- const sanitized = sanitizeLocalRequest(u, h, bodyBuffer, this.localPort);
1248
- if (sanitized.error) {
1249
- this.sendTunnelError(requestId, sanitized.error);
1250
- return;
1251
- }
1252
- const url = sanitized.path;
1253
- const headers = sanitized.headers;
1254
-
1255
- // Forward to local HTTP server
1256
- const options = {
1257
- hostname: 'localhost',
1258
- port: this.localPort,
1259
- path: url,
1260
- method: method,
1261
- headers: headers
1262
- };
1263
-
1264
- let proxyReq;
1265
- try {
1266
- proxyReq = http.request(options, (proxyRes) => {
1267
- // S-1: Determine response mode at http_response_start
1268
- const contentLength = proxyRes.headers['content-length']
1269
- ? parseInt(proxyRes.headers['content-length'], 10)
1270
- : null;
1271
- const isChunked = proxyRes.headers['transfer-encoding']?.toLowerCase() === 'chunked';
1272
- const selectedMode = this._selectResponseMode(contentLength, isChunked);
1273
-
1274
- // S-1: Version guard - if v2 not negotiated, force v1
1275
- const useV2 = selectedMode === 'v2' && this._canUseV2();
1276
-
1277
- if (useV2) {
1278
- // S-1: V2 streaming path
1279
- this._handleV2Response(proxyRes, requestId);
1280
- } else {
1281
- // S-1: V1 single-frame path (existing behavior)
1282
- this._handleV1Response(proxyRes, requestId);
1283
- }
1284
- });
1285
-
1286
- // Handle connection errors to local service
1287
- proxyReq.on('error', (err) => {
1288
- if (err.code === 'ECONNREFUSED') {
1289
- this.log.error({ port: this.localPort }, 'Local service refused connection');
1290
- process.exit(1);
1291
- } else {
1292
- this.log.error({ err, requestId }, 'Proxy request error');
1293
- }
1294
- });
1295
-
1296
- if (bodyBuffer && bodyBuffer.length > 0) {
1297
- proxyReq.write(bodyBuffer);
1298
- }
1299
- proxyReq.end();
1300
- } catch (err) {
1301
- if (err && (err.code === 'ERR_INVALID_CHAR' || err.code === 'ERR_INVALID_HTTP_TOKEN')) {
1302
- this.sendTunnelError(requestId, 400);
1303
- return;
1304
- }
1305
- this.log.error({ err, requestId }, 'Proxy request error');
1306
- this.sendTunnelError(requestId, 502);
1307
- }
1308
- }
1309
-
1310
- handleHttpRequestBuffer(buffer) {
1311
- // Handle raw HTTP request buffer from relay
1312
- const httpString = buffer.toString();
1313
- const lines = httpString.split('\r\n');
1314
- const [method, rawUrl] = lines[0].split(' ');
1315
-
1316
- const parsedHeaders = {};
1317
- let bodyStart = 0;
1318
- for (let i = 1; i < lines.length; i++) {
1319
- if (lines[i] === '') {
1320
- bodyStart = i + 1;
1321
- break;
1322
- }
1323
- const [key, value] = lines[i].split(': ');
1324
- if (key) {
1325
- parsedHeaders[key.toLowerCase()] = value;
1326
- }
1327
- }
1328
-
1329
- const body = lines.slice(bodyStart).join('\r\n');
1330
- const bodyBuffer = Buffer.from(body);
1331
- const sanitized = sanitizeLocalRequest(rawUrl, parsedHeaders, bodyBuffer, this.localPort);
1332
- if (sanitized.error) {
1333
- this.log.warn({ method }, 'Rejected raw tunnel request');
1334
- return;
1335
- }
1336
-
1337
- // Forward to local HTTP server
1338
- const options = {
1339
- hostname: 'localhost',
1340
- port: this.localPort,
1341
- path: sanitized.path,
1342
- method: method,
1343
- headers: sanitized.headers
1344
- };
1345
-
1346
- let proxyReq;
1347
- try {
1348
- proxyReq = http.request(options, (proxyRes) => {
1349
- // Send response back to relay as binary
1350
- let responseBuffer = Buffer.from(`HTTP/1.1 ${proxyRes.statusCode} ${proxyRes.statusMessage}\r\n`);
1351
-
1352
- // Add headers
1353
- for (const [key, value] of Object.entries(proxyRes.headers)) {
1354
- responseBuffer = Buffer.concat([responseBuffer, Buffer.from(`${key}: ${value}\r\n`)]);
1355
- }
1356
- responseBuffer = Buffer.concat([responseBuffer, Buffer.from('\r\n')]);
1357
-
1358
- // Add body
1359
- proxyRes.on('data', chunk => {
1360
- responseBuffer = Buffer.concat([responseBuffer, chunk]);
1361
- });
1362
-
1363
- proxyRes.on('end', () => {
1364
- this.ws.send(responseBuffer);
1365
- });
1366
- });
1367
-
1368
- // Handle connection errors to local service
1369
- proxyReq.on('error', (err) => {
1370
- if (err.code === 'ECONNREFUSED') {
1371
- this.log.error({ port: this.localPort }, 'Local service refused connection');
1372
- process.exit(1);
1373
- } else {
1374
- this.log.error({ err }, 'Proxy request error (buffer mode)');
1375
- }
1376
- });
1377
-
1378
- if (body) {
1379
- proxyReq.write(body);
1380
- }
1381
- proxyReq.end();
1382
- } catch (err) {
1383
- if (err && (err.code === 'ERR_INVALID_CHAR' || err.code === 'ERR_INVALID_HTTP_TOKEN')) {
1384
- this.log.warn({ err }, 'Rejected raw tunnel request header');
1385
- return;
1386
- }
1387
- throw err;
1388
- }
1389
- }
1390
-
1391
- // S-0: Send hello frame for HTTP-WS v2 negotiation
1392
- _sendHello() {
1393
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1394
- this.log.warn('Cannot send hello: WebSocket not open');
1395
- return;
1396
- }
1397
-
1398
- const hello = {
1399
- type: 'hello',
1400
- protocols: {
1401
- httpWs: ['v2']
1402
- }
1403
- };
1404
-
1405
- this.ws.send(JSON.stringify(hello));
1406
- this.log.debug('Hello frame sent', { protocols: hello.protocols });
1407
- }
1408
-
1409
- // S-0: Handle hello_ack for HTTP-WS v2 negotiation
1410
- _handleHelloAck(helloAck) {
1411
- this.httpWsVersion = helloAck.protocols?.httpWs || null;
1412
- this.log.info('Hello ack received', { httpWsVersion: this.httpWsVersion });
1413
-
1414
- if (this.httpWsVersion !== 'v2') {
1415
- this.log.debug('HTTP-WS v2 not negotiated, will use v1 mode');
1416
- }
1417
- }
1418
-
1419
- // S-0: Check if HTTP-WS v2 can be used (guard for v2 frame sending)
1420
- // This method should be called before sending any HTTP_BODY_CHUNK (0x20) frames
1421
- // Returns true if v2 is negotiated, false otherwise (should fallback to v1)
1422
- _canUseV2() {
1423
- return this.httpWsVersion === 'v2';
1424
- }
1425
-
1426
- // S-1: Convert requestId string to 8-byte big-endian uint64 buffer
1427
- // Note: requestId is a UUID string, so we hash it deterministically to get 8 bytes
1428
- // Both CLI and relay use the same hash function for matching
1429
- _encodeRequestId(requestId) {
1430
- const hash = crypto.createHash('sha256').update(requestId).digest();
1431
- const buffer = Buffer.alloc(8);
1432
- hash.copy(buffer, 0, 0, 8);
1433
- // Buffer is already big-endian by default in Node.js
1434
- return buffer;
1435
- }
1436
-
1437
- // S-1: Determine response mode (v1 or v2) based on content-length and size
1438
- _selectResponseMode(contentLength, isChunked) {
1439
- // S-1: Use v2 if:
1440
- // - Content-Length >= 8 MiB, OR
1441
- // - Content-Length unknown/missing or TE: chunked, OR
1442
- // - Will cross 8 MiB threshold during buffering
1443
- if (isChunked || contentLength === null || contentLength === undefined) {
1444
- return 'v2'; // Unknown length or chunked - use v2
1445
- }
1446
- if (contentLength >= V2_THRESHOLD_BYTES) {
1447
- return 'v2'; // Large known size - use v2
1448
- }
1449
- return 'v1'; // Small known size - use v1
1450
- }
1451
-
1452
- // S-1: Send HTTP-WS v2 binary chunk frame
1453
- _sendV2Chunk(requestId, payload) {
1454
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1455
- this.log.warn('Cannot send v2 chunk: WebSocket not open', { requestId });
1456
- return false;
1457
- }
1458
-
1459
- // Encode frame: frameType (1 byte) + requestId (8 bytes) + payload
1460
- const requestIdBuffer = this._encodeRequestId(requestId);
1461
- const frame = Buffer.concat([
1462
- Buffer.from([HTTP_BODY_CHUNK]),
1463
- requestIdBuffer,
1464
- payload
1465
- ]);
1466
-
1467
- try {
1468
- this.ws.send(frame, { binary: true });
1469
- return true;
1470
- } catch (error) {
1471
- this.log.error('Failed to send v2 chunk', { requestId, error: error.message });
1472
- return false;
1473
- }
1474
- }
1475
-
1476
- // S-1: Chunk payload into v2-compliant sizes (64 KiB target, 256 KiB max)
1477
- _chunkPayload(payload) {
1478
- const chunks = [];
1479
- let offset = 0;
1480
-
1481
- while (offset < payload.length) {
1482
- // Target 64 KiB, but don't exceed 256 KiB
1483
- const remaining = payload.length - offset;
1484
- const chunkSize = Math.min(
1485
- HTTPWS_V2_TARGET_CHUNK_BYTES,
1486
- Math.min(remaining, HTTPWS_V2_MAX_CHUNK_BYTES)
1487
- );
1488
- chunks.push(payload.slice(offset, offset + chunkSize));
1489
- offset += chunkSize;
1490
- }
1491
-
1492
- return chunks;
1493
- }
1494
-
1495
- // S-1: Handle v2 streaming response
1496
- _handleV2Response(proxyRes, requestId) {
1497
- // Track this response as v2
1498
- this.activeV2Responses.set(requestId, { mode: 'v2', bufferedBytes: 0 });
1499
-
1500
- // Convert headers to array format
1501
- const headerArray = Object.entries(proxyRes.headers).map(([name, value]) => [name, value]);
1502
-
1503
- // S-1: Send http_response_start with mode: "stream"
1504
- const responseStart = {
1505
- type: 'http_response_start',
1506
- rid: requestId,
1507
- status: proxyRes.statusCode,
1508
- headers: headerArray,
1509
- mode: 'stream'
1510
- };
1511
-
1512
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1513
- this.log.warn('Cannot send v2 response: WebSocket not open', { requestId });
1514
- this.activeV2Responses.delete(requestId);
1515
- return;
1516
- }
1517
-
1518
- this.ws.send(JSON.stringify(responseStart));
1519
-
1520
- // S-1: Stream chunks as they arrive
1521
- let buffer = Buffer.alloc(0);
1522
- const flushBuffer = () => {
1523
- if (buffer.length === 0) return;
1524
-
1525
- const chunks = this._chunkPayload(buffer);
1526
- for (const chunk of chunks) {
1527
- if (!this._sendV2Chunk(requestId, chunk)) {
1528
- // Send failed, abort response
1529
- this.log.error('Failed to send v2 chunk, aborting response', { requestId });
1530
- this.activeV2Responses.delete(requestId);
1531
- return;
1532
- }
1533
- }
1534
- buffer = Buffer.alloc(0);
1535
- };
1536
-
1537
- proxyRes.on('data', (chunk) => {
1538
- // CRT-Relay-E: Update activity on HTTP response data
1539
- this.lastActivityMs = Date.now();
1540
-
1541
- // Accumulate chunk
1542
- buffer = Buffer.concat([buffer, chunk]);
1543
-
1544
- // Flush when buffer reaches target chunk size
1545
- if (buffer.length >= HTTPWS_V2_TARGET_CHUNK_BYTES) {
1546
- flushBuffer();
1547
- }
1548
- });
1549
-
1550
- proxyRes.on('end', () => {
1551
- // CRT-Relay-E: Update activity on HTTP response end
1552
- this.lastActivityMs = Date.now();
1553
-
1554
- // Flush any remaining data
1555
- flushBuffer();
1556
-
1557
- // S-1: Send http_response_end
1558
- const responseEnd = {
1559
- type: 'http_response_end',
1560
- rid: requestId
1561
- };
1562
-
1563
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1564
- this.ws.send(JSON.stringify(responseEnd));
1565
- }
1566
-
1567
- // Clean up tracking
1568
- this.activeV2Responses.delete(requestId);
1569
- });
1570
-
1571
- proxyRes.on('error', (error) => {
1572
- this.log.error('Error in v2 response stream', { requestId, error: error.message });
1573
- this.activeV2Responses.delete(requestId);
1574
- });
1575
- }
1576
-
1577
- // S-1: Handle v1 single-frame response (existing behavior)
1578
- _handleV1Response(proxyRes, requestId) {
1579
- const responseChunks = [];
1580
- let bufferedBytes = 0;
1581
-
1582
- proxyRes.on('data', (chunk) => {
1583
- responseChunks.push(chunk);
1584
- bufferedBytes += chunk.length;
1585
-
1586
- // S-1: If buffering for v1 crosses 8 MiB, abort and retry as v2
1587
- if (bufferedBytes >= V2_THRESHOLD_BYTES && this._canUseV2()) {
1588
- this.log.warn('V1 response exceeded 8 MiB threshold, aborting', { requestId, bufferedBytes });
1589
- // Note: In a real implementation, we'd need to abort the proxyRes stream
1590
- // For now, we'll continue with v1 but log the issue
1591
- // This is a limitation - we can't easily switch mid-stream
1592
- }
1593
- });
1594
-
1595
- proxyRes.on('end', () => {
1596
- // CRT-Relay-E: Update activity on HTTP response
1597
- this.lastActivityMs = Date.now();
1598
-
1599
- // Convert headers to array format and encode body as base64
1600
- const headerArray = Object.entries(proxyRes.headers).map(([name, value]) => [name, value]);
1601
- const bodyBuffer = Buffer.concat(responseChunks);
1602
- const bodyBase64 = bodyBuffer.length ? bodyBuffer.toString('base64') : '';
1603
-
1604
- const responseData = {
1605
- t: 'http_response',
1606
- rid: requestId, // Use the same rid from the request
1607
- s: proxyRes.statusCode,
1608
- h: headerArray,
1609
- b: bodyBase64
1610
- };
1611
-
1612
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1613
- this.ws.send(JSON.stringify(responseData));
1614
- }
1615
- });
1616
- }
1617
-
1618
- close() {
1619
- // CLI-IMG-WSReconnect: Disable reconnects and clear timer
1620
- this.shouldReconnect = false;
1621
- if (this.reconnectTimer) {
1622
- clearTimeout(this.reconnectTimer);
1623
- this.reconnectTimer = null;
1624
- }
1625
-
1626
- // CLI-RES-DPJWT-LEAD: Clear refresh timer to avoid leaks
1627
- if (this.refreshTimer) {
1628
- clearTimeout(this.refreshTimer);
1629
- this.refreshTimer = null;
1630
- }
1631
- // QPA-CLI-01: Clean up retry timer
1632
- if (this.refreshRetryTimer) {
1633
- clearTimeout(this.refreshRetryTimer);
1634
- this.refreshRetryTimer = null;
1635
- }
1636
-
1637
- // CLI-REAUTH: Cleanup control frame waiters
1638
- clearAllWaiters();
1639
- this.reauthInFlight = null;
1640
-
1641
- // CRT-Relay-E: Stop heartbeat before closing
1642
- this.stopHeartbeat();
1643
- if (this.ws) {
1644
- this.ws.close();
1645
- }
1646
- }
1647
-
1648
- // CRT-Relay-E: Heartbeat methods
1649
- getHeartbeatInterval() {
1650
- const interval = process.env.ASYX_TUNNEL_HEARTBEAT_SEC || '120';
1651
- const intervalMs = Number(interval) * 1000;
1652
- return intervalMs <= 0 ? Infinity : intervalMs;
1653
- }
1654
-
1655
- startHeartbeat() {
1656
- const interval = this.getHeartbeatInterval();
1657
- if (interval === Infinity) {
1658
- this.log.debug('Heartbeat disabled (ASYX_TUNNEL_HEARTBEAT_SEC <= 0)');
1659
- return;
1660
- }
1661
-
1662
- this.heartbeatTimer = setInterval(() => {
1663
- this.sendHeartbeat();
1664
- }, interval);
1665
-
1666
- this.log.debug({ interval }, 'tunnel heartbeat started');
1667
- }
1668
-
1669
- sendHeartbeat() {
1670
- // Guard against sending when WebSocket is not open
1671
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1672
- return;
1673
- }
1674
-
1675
- // Check if we should send heartbeat (respect real traffic)
1676
- const now = Date.now();
1677
- const timeSinceActivity = now - this.lastActivityMs;
1678
- const interval = this.getHeartbeatInterval();
1679
-
1680
- if (timeSinceActivity >= interval) {
1681
- this.ws.send(JSON.stringify({ t: 'ping' }));
1682
- this.lastActivityMs = now;
1683
- this.log.debug({ interval }, 'tunnel heartbeat ping sent');
1684
- }
1685
- }
1686
-
1687
- stopHeartbeat() {
1688
- if (this.heartbeatTimer) {
1689
- clearInterval(this.heartbeatTimer);
1690
- this.heartbeatTimer = null;
1691
- this.log.debug('tunnel heartbeat stopped');
1692
- }
1693
- }
1694
- }