asyx 0.5.9 → 0.6.0

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