asyx 0.5.9 → 0.6.1

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