asyx 0.0.2 → 0.1.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.
@@ -0,0 +1,1131 @@
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
+ export class HttpTunnel {
10
+ constructor({
11
+ relayUrl,
12
+ jwt,
13
+ deviceId,
14
+ requestId,
15
+ localPort,
16
+ log,
17
+ coordinatorCore,
18
+ coordinatorIngress,
19
+ // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
20
+ isControlPlaneConnected = () => true,
21
+ waitForControlPlane = () => Promise.resolve(),
22
+ controlPlaneTimeoutMs = 60000
23
+ }) {
24
+ this.relayUrl = relayUrl;
25
+ this.jwt = jwt; // Accept JWT as-is (no validation)
26
+ this.deviceId = deviceId;
27
+ this.requestId = requestId;
28
+ this.localPort = localPort;
29
+ this.log = log;
30
+ this.ws = null;
31
+
32
+ // CLI-IMG-WSReconnect: Coordinator connection for JWT refresh
33
+ this.coordinatorCore = coordinatorCore;
34
+ this.coordinatorIngress = coordinatorIngress;
35
+
36
+ // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
37
+ this.isControlPlaneConnected = isControlPlaneConnected;
38
+ this.waitForControlPlane = waitForControlPlane;
39
+ this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
40
+
41
+ // CRT-Relay-E: Heartbeat properties
42
+ this.heartbeatTimer = null;
43
+ this.lastActivityMs = Date.now();
44
+
45
+ // CLI-IMG-WSReconnect: Reconnect properties
46
+ this.shouldReconnect = true;
47
+ this.retryCount = 0;
48
+ // CLI-IMG-Retry-Ceiling: Increase retry ceiling to 60 (configurable)
49
+ this.maxRetries = parseInt(process.env.ASYX_TUNNEL_MAX_RETRIES || "60", 10);
50
+ this.reconnectTimer = null;
51
+ this.headers = null; // Store headers for reuse during reconnects
52
+
53
+ // CLI-JWT-REFRESH: Refresh state machine
54
+ this.refreshState = 'idle'; // idle | pending | fallback | failed
55
+ this.refreshAttempts = 0;
56
+ this.refreshMaxAttempts = parseInt(process.env.ASYX_TUNNEL_REFRESH_MAX_RETRIES || '3', 10);
57
+
58
+ // CLI-RES-DPJWT-LEAD: Proactive refresh scheduling
59
+ this.refreshTimer = null;
60
+ this.jwtMeta = null; // { token, expMs } for lead window checks
61
+ this.LEAD_MS = Number(process.env.ASYX_REFRESH_LEAD_MS || 180000); // 3 minutes (default), configurable via env
62
+
63
+ // CLI-REAUTH: In-band reauth configuration
64
+ this.reauthAckTimeoutMs = Number(process.env.CLI_REAUTH_ACK_TIMEOUT_MS || 3000); // 3 seconds default
65
+ this.reauthInFlight = null; // Single-flight guard: Promise or null
66
+ }
67
+
68
+ // CLI-RES-DPJWT-LEAD: Safe JWT decode helper
69
+ _decodeJwtExp(token) {
70
+ try {
71
+ if (!token || typeof token !== 'string') {
72
+ return null;
73
+ }
74
+ const parts = token.split('.');
75
+ if (parts.length !== 3) {
76
+ return null;
77
+ }
78
+ // Base64URL decode the payload (second part)
79
+ const payload = Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
80
+ const parsed = JSON.parse(payload);
81
+
82
+ if (!parsed.exp || typeof parsed.exp !== 'number') {
83
+ return null;
84
+ }
85
+
86
+ const expMs = parsed.exp * 1000; // Convert to milliseconds
87
+ const nowMs = Date.now();
88
+ const issuedAtMs = parsed.iat ? parsed.iat * 1000 : null;
89
+ const skewMs = expMs - nowMs;
90
+
91
+ return { expMs, issuedAtMs, skewMs };
92
+ } catch (err) {
93
+ // Malformed JWT - return null to skip scheduling
94
+ return null;
95
+ }
96
+ }
97
+
98
+ // CLI-REAUTH: Extract JTI from JWT for prev hint
99
+ _extractJti(token) {
100
+ try {
101
+ if (!token || typeof token !== 'string') {
102
+ return null;
103
+ }
104
+ const parts = token.split('.');
105
+ if (parts.length !== 3) {
106
+ return null;
107
+ }
108
+ const payload = Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
109
+ const parsed = JSON.parse(payload);
110
+ return parsed.jti || null;
111
+ } catch (err) {
112
+ return null;
113
+ }
114
+ }
115
+
116
+ // CLI-RES-DPJWT-LEAD: Schedule proactive refresh
117
+ scheduleRefresh(token, context = 'unknown') {
118
+ // Clear existing timer
119
+ if (this.refreshTimer) {
120
+ clearTimeout(this.refreshTimer);
121
+ this.refreshTimer = null;
122
+ }
123
+
124
+ // Decode JWT to get exp
125
+ const decoded = this._decodeJwtExp(token);
126
+ if (!decoded) {
127
+ this.log.warn('jwt.refresh.schedule.invalid_token', { context });
128
+ return; // Skip scheduling for invalid tokens
129
+ }
130
+
131
+ const { expMs, issuedAtMs, skewMs } = decoded;
132
+ const nowMs = Date.now();
133
+
134
+ // CLI-RES-DPJWT-LEAD: Guard against short TTLs to prevent refresh loops
135
+ const ttlMs = expMs - (issuedAtMs ?? expMs - this.LEAD_MS);
136
+ if (ttlMs <= this.LEAD_MS) {
137
+ const adjusted = Math.max(30000, Math.floor(ttlMs / 4));
138
+ if (adjusted !== this.LEAD_MS) {
139
+ this.log.warn('jwt.refresh.lead_adjusted', { context, originalLeadMs: this.LEAD_MS, adjustedLeadMs: adjusted, ttlMs });
140
+ this.LEAD_MS = adjusted;
141
+ }
142
+ }
143
+
144
+ // Check for clock skew warning (before determining refresh timing)
145
+ if (skewMs < this.LEAD_MS) {
146
+ this.log.warn('jwt.refresh.schedule.skew_warning', {
147
+ expEpochMs: expMs,
148
+ leadMs: this.LEAD_MS,
149
+ skewMs,
150
+ context
151
+ });
152
+ }
153
+
154
+ // Clamp refreshAt to never precede "issued at" and add 30s final buffer
155
+ const refreshAt = Math.min(
156
+ expMs - this.LEAD_MS,
157
+ issuedAtMs ? Math.max(issuedAtMs + 1000, expMs - this.LEAD_MS) : expMs - this.LEAD_MS,
158
+ expMs - 30000 // Final 30s buffer
159
+ );
160
+
161
+ // Store JWT metadata for reconnect checks (before immediate check so _checkRefreshLeadWindow has accurate state)
162
+ this.jwtMeta = { token, expMs };
163
+
164
+ // Check if already in lead window
165
+ if (nowMs >= refreshAt) {
166
+ this.log.info('jwt.refresh.schedule.immediate', {
167
+ expEpochMs: expMs,
168
+ leadMs: this.LEAD_MS,
169
+ refreshAtEpochMs: refreshAt,
170
+ skewMs,
171
+ context
172
+ });
173
+ // Trigger refresh immediately
174
+ this.attemptJwtRefresh().catch(err => {
175
+ this.log.error('jwt.refresh.immediate.failure', { error: err.message });
176
+ });
177
+ return;
178
+ }
179
+
180
+ // Schedule refresh
181
+ const delayMs = refreshAt - nowMs;
182
+ this.refreshTimer = setTimeout(() => {
183
+ this.refreshTimer = null;
184
+ this.log.info('jwt.refresh.schedule.trigger', {
185
+ expEpochMs: expMs,
186
+ leadMs: this.LEAD_MS,
187
+ context: 'timer'
188
+ });
189
+ this.attemptJwtRefresh().catch(err => {
190
+ this.log.error('jwt.refresh.scheduled.failure', { error: err.message });
191
+ });
192
+ }, delayMs);
193
+
194
+ // Log scheduling
195
+ this.log.info('jwt.refresh.schedule', {
196
+ expEpochMs: expMs,
197
+ leadMs: this.LEAD_MS,
198
+ refreshAtEpochMs: refreshAt,
199
+ skewMs,
200
+ context
201
+ });
202
+ }
203
+
204
+ // CLI-REAUTH: In-band reauth helper
205
+ async reauthInBand(newJwt, prevJti, trigger = 'timer') {
206
+ // Single-flight guard: if reauth already in progress, wait for it
207
+ if (this.reauthInFlight) {
208
+ return this.reauthInFlight;
209
+ }
210
+
211
+ const { getAssignment } = await import('../state/assignment.js');
212
+ const assignment = getAssignment();
213
+
214
+ if (!assignment || !assignment.leaseId) {
215
+ this.log.warn('jwt.reauth.error', { code: 'no_assignment' });
216
+ return false;
217
+ }
218
+
219
+ // Calculate lead seconds for logging
220
+ const decoded = this._decodeJwtExp(newJwt);
221
+ const leadSeconds = decoded ? Math.floor((decoded.expMs - Date.now()) / 1000) : undefined;
222
+
223
+ // Build reauth payload
224
+ const payload = JSON.stringify({
225
+ op: 'reauth',
226
+ leaseId: assignment.leaseId,
227
+ jwt: newJwt,
228
+ prev: { jti: prevJti || null }
229
+ });
230
+
231
+ this.log.info('jwt.reauth.scheduled', {
232
+ leadSeconds,
233
+ trigger,
234
+ leaseId: assignment.leaseId
235
+ });
236
+
237
+ // Create and store the promise for single-flight guard
238
+ const reauthPromise = (async () => {
239
+ try {
240
+ const ack = await sendControlAndWaitAck(this.ws, payload, 'reauth_ack', this.reauthAckTimeoutMs);
241
+
242
+ if (ack?.status === 'ok') {
243
+ // Update JWT and metadata
244
+ this.jwt = newJwt;
245
+ const expMs = ack.active?.exp ? ack.active.exp * 1000 : (decoded?.expMs || null);
246
+ this.jwtMeta = { token: newJwt, expMs };
247
+
248
+ // Update headers for future reconnects
249
+ this.headers = {
250
+ 'Authorization': `Bearer ${this.jwt}`,
251
+ 'X-Asyx-DeviceId': this.deviceId,
252
+ 'X-Asyx-RequestId': assignment.requestId
253
+ };
254
+
255
+ // Re-schedule next proactive refresh
256
+ this.scheduleRefresh(this.jwt, 'reauth_success');
257
+
258
+ const ackLeadSeconds = ack.active?.exp
259
+ ? Math.floor((ack.active.exp * 1000 - Date.now()) / 1000)
260
+ : leadSeconds;
261
+
262
+ this.log.info('jwt.reauth.ok', {
263
+ leadSeconds: ackLeadSeconds,
264
+ exp: ack.active?.exp,
265
+ relayId: assignment.relayId
266
+ });
267
+
268
+ return true;
269
+ }
270
+
271
+ // Error or timeout
272
+ const errorCode = ack?.error || 'timeout';
273
+ this.log.warn('jwt.reauth.error', {
274
+ code: errorCode,
275
+ retryCount: this.refreshAttempts
276
+ });
277
+
278
+ return false;
279
+ } catch (error) {
280
+ this.log.warn('jwt.reauth.error', {
281
+ code: 'exception',
282
+ error: error.message,
283
+ retryCount: this.refreshAttempts
284
+ });
285
+ return false;
286
+ } finally {
287
+ // Clear guard when done
288
+ if (this.reauthInFlight === reauthPromise) {
289
+ this.reauthInFlight = null;
290
+ }
291
+ }
292
+ })();
293
+
294
+ this.reauthInFlight = reauthPromise;
295
+ return reauthPromise;
296
+ }
297
+
298
+ // CLI-RES-DPJWT-LEAD: Check if refresh needed on reconnect
299
+ _checkRefreshLeadWindow() {
300
+ if (!this.jwtMeta || !this.jwtMeta.expMs) {
301
+ return false;
302
+ }
303
+
304
+ const nowMs = Date.now();
305
+ const { expMs } = this.jwtMeta;
306
+
307
+ // Check if we're in the lead window
308
+ if (nowMs + this.LEAD_MS >= expMs) {
309
+ this.log.info('jwt.refresh.schedule.immediate', {
310
+ expEpochMs: expMs,
311
+ leadMs: this.LEAD_MS,
312
+ refreshAtEpochMs: expMs - this.LEAD_MS,
313
+ skewMs: expMs - nowMs,
314
+ context: 'reconnect_lead_window'
315
+ });
316
+ // Trigger refresh before resuming
317
+ this.attemptJwtRefresh().catch(err => {
318
+ this.log.error('jwt.refresh.reconnect.failure', { error: err.message });
319
+ });
320
+ return true;
321
+ }
322
+
323
+ return false;
324
+ }
325
+
326
+ // CLI-IMG-Refresh-Guard: Ensure control-plane connectivity with timeout
327
+ // CLI-RES-WAITFORCONNECT: Updated to use transport.waitForConnect() directly
328
+ async _ensureControlPlane(reason, forceWait = false) {
329
+ if (!forceWait && this.isControlPlaneConnected()) return true;
330
+
331
+ this.log.warn({ reason }, "Control-plane offline, waiting for reconnect");
332
+
333
+ try {
334
+ // Use waitForControlPlane which internally calls transport.waitForConnect()
335
+ await this.waitForControlPlane();
336
+ this.log.info({ reason }, "Control-plane reconnected");
337
+ return true;
338
+ } catch (err) {
339
+ // Handle WaitForConnectError (timeout or terminated)
340
+ if (err.name === 'WaitForConnectError') {
341
+ this.log.warn('mqtt.transport.wait_for_connect.timeout', { reason, error: err.message });
342
+ return false;
343
+ }
344
+ if (err.message === "control_plane_timeout") {
345
+ this.log.warn({ reason }, "Control-plane reconnect timed out");
346
+ return false;
347
+ }
348
+ throw err;
349
+ }
350
+ }
351
+
352
+ async open() {
353
+ // CLI-IMG-WSReconnect: Start the connection process
354
+ return this._attemptConnect();
355
+ }
356
+
357
+ async _attemptConnect() {
358
+ return new Promise((resolve, reject) => {
359
+ // CLI-IMG-WSReconnect: Store headers for reuse during reconnects
360
+ if (!this.headers) {
361
+ this.headers = {
362
+ 'Authorization': `Bearer ${this.jwt}`,
363
+ 'X-Asyx-DeviceId': this.deviceId,
364
+ 'X-Asyx-RequestId': this.requestId
365
+ };
366
+ }
367
+
368
+ // CLI-IMG-WSReconnect: Clean up previous WebSocket if exists
369
+ if (this.ws) {
370
+ this.ws.removeAllListeners();
371
+ this.ws = null;
372
+ }
373
+
374
+ // Connect to relay with TLS (rejectUnauthorized: true by default)
375
+ this.ws = new WebSocket(this.relayUrl, {
376
+ headers: this.headers,
377
+ rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1' // Allow dev override
378
+ });
379
+
380
+ this.ws.on('open', () => {
381
+ this.log.info({ relayUrl: this.relayUrl, localPort: this.localPort }, 'Tunnel WS open - proxy mode active');
382
+
383
+ // CLI-IMG-WSReconnect: Reset retry count on successful connection
384
+ this.retryCount = 0;
385
+
386
+ // CLI-RES-DPJWT-LEAD: Check if refresh needed before resuming
387
+ this._checkRefreshLeadWindow();
388
+
389
+ // CRT-Relay-E: Start heartbeat timer after WebSocket opens
390
+ this.startHeartbeat();
391
+
392
+ resolve();
393
+ });
394
+
395
+ this.ws.on('message', (data, isBinary) => {
396
+ // CRT-Relay-E: Update activity on any message
397
+ this.lastActivityMs = Date.now();
398
+
399
+ if (!isBinary) {
400
+ try {
401
+ const msg = JSON.parse(data.toString());
402
+
403
+ // CLI-REAUTH: Dispatch control frames to waiter registry
404
+ if (msg.op && typeof msg.op === 'string') {
405
+ if (dispatchControlFrame(msg)) {
406
+ // Control frame was dispatched to a waiter, don't process further
407
+ return;
408
+ }
409
+ // Control frame but no waiters - ignore unknown ops
410
+ this.log.debug('jwt.reauth.unknown_control', { op: msg.op });
411
+ return;
412
+ }
413
+
414
+ // CRT-Relay-E: Handle heartbeat pong
415
+ if (msg.t === 'pong') {
416
+ this.log.debug('tunnel heartbeat pong received');
417
+ return;
418
+ }
419
+
420
+ if (msg.type === 'ping') {
421
+ this.ws.send(JSON.stringify({ type: 'pong' }));
422
+ return;
423
+ }
424
+ if (msg.type === 'http_request' || msg.t === 'http_request') {
425
+ this.handleHttpRequest(msg);
426
+ return;
427
+ }
428
+ } catch (_) {}
429
+ }
430
+
431
+ // Handle binary messages that look like HTTP requests
432
+ const dataStr = data.toString();
433
+ if (dataStr.startsWith('GET ') || dataStr.startsWith('POST ') || dataStr.startsWith('PUT ') ||
434
+ dataStr.startsWith('DELETE ') || dataStr.startsWith('PATCH ') || dataStr.startsWith('HEAD ') ||
435
+ dataStr.startsWith('OPTIONS ')) {
436
+ this.handleHttpRequestBuffer(Buffer.from(data));
437
+ } else {
438
+ // Ignore binary messages that look like HTTP responses
439
+ this.log.debug('Ignoring binary message (likely HTTP response)');
440
+ }
441
+ });
442
+
443
+ this.ws.on('close', (code, reason) => {
444
+ this.log.warn({ code, reason: reason?.toString() }, 'Tunnel WS closed');
445
+ // CRT-Relay-E: Stop heartbeat on close
446
+ this.stopHeartbeat();
447
+ // CLI-REAUTH: Cleanup control frame waiters on socket close
448
+ clearAllWaiters();
449
+ // Clear single-flight guard
450
+ this.reauthInFlight = null;
451
+
452
+ // CLI-IMG-WSReconnect: Schedule reconnect instead of exiting
453
+ this.scheduleReconnect(code, reason);
454
+ });
455
+
456
+ this.ws.on('error', (err) => {
457
+ this.log.error({ err }, 'Tunnel WS error');
458
+ // CRT-Relay-E: Stop heartbeat on error
459
+ this.stopHeartbeat();
460
+
461
+ // CLI-IMG-WSReconnect: Handle connection errors with reconnect
462
+ this.scheduleReconnect(null, err.message);
463
+ });
464
+ });
465
+ }
466
+
467
+ // CLI-IMG-WSReconnect: Reconnect scheduling and logic
468
+ scheduleReconnect(code, reason) {
469
+ // Check if we should reconnect
470
+ if (!this.shouldReconnect) {
471
+ this.log.info('Reconnect disabled, returning');
472
+ return;
473
+ }
474
+
475
+ // CLI-IMG-Retry-Ceiling: Check retry limit with descriptive messaging
476
+ if (this.retryCount >= this.maxRetries) {
477
+ this.log.error(
478
+ { retryCount: this.retryCount, maxRetries: this.maxRetries },
479
+ "Control-plane reconnect attempts exhausted; please restart the CLI"
480
+ );
481
+ process.exit(1);
482
+ }
483
+
484
+ // Check for JWT expiration - attempt refresh instead of exiting
485
+ // Handle both jwt_invalid (code 1000) and EJWT_EXPIRED (code 1008) cases
486
+ const reasonStr = reason?.toString() || '';
487
+ const lower = reasonStr.toLowerCase();
488
+ const isJwtInvalid = code === 1000 && lower.includes('jwt_invalid');
489
+ const isJwtExpired = code === 1008 && lower.includes('ejwt_expired');
490
+
491
+ if (isJwtInvalid || isJwtExpired) {
492
+ const triggerReason = isJwtInvalid ? 'jwt_invalid' : 'ejwt_expired';
493
+ this.log.warn('jwt.refresh.trigger', { triggerReason, code, reason: reasonStr });
494
+ this.attemptJwtRefresh();
495
+ return;
496
+ }
497
+
498
+ // Calculate exponential backoff with jitter
499
+ const baseDelay = Math.min(1000 * Math.pow(2, this.retryCount), 30000); // Max 30s
500
+ const jitter = Math.random() * 0.4 - 0.2; // ±20% jitter
501
+ const delay = Math.max(1000, Math.floor(baseDelay * (1 + jitter)));
502
+
503
+ this.retryCount++;
504
+
505
+ this.log.warn({
506
+ delay,
507
+ retryCount: this.retryCount,
508
+ maxRetries: this.maxRetries,
509
+ code,
510
+ reason: reason?.toString()
511
+ }, 'Tunnel WS reconnect scheduled');
512
+
513
+ // Schedule reconnect attempt
514
+ this.reconnectTimer = setTimeout(() => {
515
+ this.attemptReconnect();
516
+ }, delay);
517
+ }
518
+
519
+ async attemptReconnect() {
520
+ try {
521
+ this.log.info({ retryCount: this.retryCount }, 'Attempting to reconnect...');
522
+ await this._attemptConnect();
523
+ this.log.info('Reconnected successfully');
524
+
525
+ // CLI-IMG-WSReconnect: Clear reconnect timer on successful reconnect
526
+ if (this.reconnectTimer) {
527
+ clearTimeout(this.reconnectTimer);
528
+ this.reconnectTimer = null;
529
+ }
530
+ } catch (error) {
531
+ this.log.error({ error: error.message, retryCount: this.retryCount }, 'Reconnect attempt failed');
532
+ // scheduleReconnect will be called from the error handler in _attemptConnect
533
+ }
534
+ }
535
+
536
+ // CLI-IMG-WSReconnect: JWT refresh logic
537
+ async attemptJwtRefresh() {
538
+ try {
539
+ if (this.refreshAttempts >= this.refreshMaxAttempts) {
540
+ this.log.error('jwt.refresh.exhausted', { retryCount: this.refreshAttempts });
541
+ this.refreshState = 'failed';
542
+ process.exit(1);
543
+ }
544
+
545
+ this.refreshAttempts += 1;
546
+ this.refreshState = 'pending';
547
+ this.log.info('jwt.refresh.start', { retryCount: this.refreshAttempts });
548
+
549
+ // CLI-IMG-Refresh-Guard: Ensure control-plane connectivity before refresh
550
+ const ready = await this._ensureControlPlane("jwt_refresh");
551
+ if (!ready) {
552
+ this.log.warn('jwt.refresh.control_plane_timeout', { retryCount: this.refreshAttempts });
553
+ await this._fallbackToFreshTunnel();
554
+ return;
555
+ }
556
+
557
+ // Check if we have coordinator connection
558
+ if (!this.coordinatorCore || !this.coordinatorIngress) {
559
+ this.log.error('jwt.refresh.no_coordinator');
560
+ process.exit(1);
561
+ }
562
+
563
+ // Import assignment functions
564
+ const { getAssignment } = await import('../state/assignment.js');
565
+ const { getFpHash } = await import('../lib/fingerprint.js');
566
+
567
+ // Get current assignment to reuse lease
568
+ const currentAssignment = getAssignment();
569
+ if (!currentAssignment) {
570
+ this.log.error('jwt.refresh.no_current_assignment');
571
+ process.exit(1);
572
+ }
573
+
574
+ // CRT-Lease-Refresh-ExtendTTL: Use refreshOf field to reuse existing lease
575
+ const refreshRequestId = `refresh-${Date.now()}`; // New requestId for refresh
576
+ const leaseId = currentAssignment.leaseId;
577
+
578
+ if (!leaseId) {
579
+ this.log.error('jwt.refresh.no_lease_id');
580
+ process.exit(1);
581
+ }
582
+
583
+ // Get fingerprint for the refresh request
584
+ const fingerprint = await getFpHash(this.deviceId);
585
+
586
+ // Build refresh payload - use refreshOf field to reuse existing lease
587
+ // CLI-RES-COORD-EVENTBRIDGE: Do NOT set reconnect: true for JWT refresh.
588
+ // Reconnect is only for re-establishing after disconnection; refresh should only use refreshOf.
589
+ const refreshPayload = {
590
+ requestId: refreshRequestId, // New requestId for this refresh
591
+ refreshOf: leaseId, // CLI-RES-COORD-EVENTBRIDGE: Tell coordinator to reuse this lease via refreshLease()
592
+ // reconnect: true removed - this is JWT refresh, not reconnect
593
+ proto: 'http',
594
+ localPort: this.localPort,
595
+ clientId: this.deviceId,
596
+ ...fingerprint
597
+ };
598
+
599
+ // Set up topic for refresh request
600
+ const cmdOpenTopic = `asyx/tunnel/clients/${this.deviceId}/cmd/open`;
601
+
602
+ // Wait for open_ack with timeout
603
+ const ackPromise = this.coordinatorIngress.registerAwaiter((message) => {
604
+ try {
605
+ const parsed = message.payload;
606
+ return parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
607
+ } catch (e) {
608
+ return false;
609
+ }
610
+ }, 10000);
611
+
612
+ // CLI-IMG-MQTT-Resilience: Publish with retry logic and fallback
613
+ try {
614
+ // Publish the refresh request
615
+ await this.coordinatorCore.publish({
616
+ topic: cmdOpenTopic,
617
+ payload: JSON.stringify(refreshPayload),
618
+ qos: 1,
619
+ retain: false
620
+ });
621
+
622
+ this.log.info('jwt.refresh.request.sent', { refreshRequestId, retryCount: this.refreshAttempts });
623
+
624
+ // Wait for new assignment with timeout handling
625
+ try {
626
+ await ackPromise;
627
+ } catch (timeoutError) {
628
+ this.log.warn('jwt.refresh.timeout', { retryCount: this.refreshAttempts, error: timeoutError.message });
629
+ // CLI-IMG-MQTT-Resilience: Fallback to fresh tunnel when awaiter times out
630
+ await this._fallbackToFreshTunnel();
631
+ return;
632
+ }
633
+ } catch (publishError) {
634
+ this.log.warn('jwt.refresh.publish_failed', { retryCount: this.refreshAttempts, error: publishError.message });
635
+ await this._ensureControlPlane('jwt_refresh_retry', true);
636
+ // CLI-IMG-MQTT-Resilience: Fallback to fresh tunnel when publish fails
637
+ await this._fallbackToFreshTunnel();
638
+ return;
639
+ }
640
+
641
+ // Get the new assignment
642
+ const newAssignment = getAssignment();
643
+ if (!newAssignment) {
644
+ this.log.error('jwt.refresh.no_new_assignment');
645
+ process.exit(1);
646
+ }
647
+
648
+ // CLI-REAUTH: Try in-band reauth if WebSocket is open, otherwise fallback to reconnect
649
+ const prevJti = this.jwtMeta?.token ? this._extractJti(this.jwtMeta.token) : null;
650
+ const newJwt = newAssignment.jwt;
651
+
652
+ // Check if WebSocket is open and try in-band reauth
653
+ if (this.ws && this.ws.readyState === 1) { // WebSocket.OPEN = 1
654
+ // Start in-band reauth (guard is inside reauthInBand)
655
+ try {
656
+ const reauthSuccess = await this.reauthInBand(newJwt, prevJti, 'timer');
657
+
658
+ if (reauthSuccess) {
659
+ // In-band reauth succeeded - update assignment state and we're done
660
+ // CLI-IMG-WSReconnect: Update tunnel state with new assignment
661
+ this.requestId = newAssignment.requestId;
662
+ this.relayUrl = newAssignment.relayUrl;
663
+ this.headers = {
664
+ 'Authorization': `Bearer ${this.jwt}`,
665
+ 'X-Asyx-DeviceId': this.deviceId,
666
+ 'X-Asyx-RequestId': this.requestId
667
+ };
668
+
669
+ // Record refresh timestamp and delta metrics
670
+ const { recordRefresh } = await import('../state/assignment.js');
671
+ const deltaMs = recordRefresh(Date.now());
672
+ this.log.info('jwt.refresh.delta', { deltaMs });
673
+ this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'in_band' });
674
+ this.refreshState = 'idle';
675
+ this.refreshAttempts = 0;
676
+ return; // Socket stayed open, no reconnect needed
677
+ }
678
+
679
+ // Reauth failed, fall through to reconnect
680
+ this.log.info('jwt.reauth.fallback_reconnect', { retryCount: this.refreshAttempts });
681
+ } catch (reauthError) {
682
+ this.log.warn('jwt.reauth.exception', { error: reauthError.message });
683
+ this.log.info('jwt.reauth.fallback_reconnect', { retryCount: this.refreshAttempts });
684
+ // Fall through to reconnect
685
+ }
686
+ }
687
+
688
+ // Fallback path: update state and reconnect with new JWT
689
+ // CLI-IMG-WSReconnect: Update tunnel state with new assignment
690
+ this.jwt = newJwt;
691
+ this.requestId = newAssignment.requestId;
692
+ this.relayUrl = newAssignment.relayUrl;
693
+ this.headers = {
694
+ 'Authorization': `Bearer ${this.jwt}`,
695
+ 'X-Asyx-DeviceId': this.deviceId,
696
+ 'X-Asyx-RequestId': newAssignment.requestId
697
+ };
698
+
699
+ // Record refresh timestamp and delta metrics
700
+ const { recordRefresh } = await import('../state/assignment.js');
701
+ const deltaMs = recordRefresh(Date.now());
702
+ this.log.info('jwt.refresh.delta', { deltaMs });
703
+ this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'reconnect' });
704
+ this.refreshState = 'idle';
705
+ this.refreshAttempts = 0;
706
+
707
+ // CLI-RES-DPJWT-LEAD: Schedule next proactive refresh
708
+ this.scheduleRefresh(this.jwt, 'refresh_success');
709
+
710
+ // Attempt reconnect with new JWT
711
+ await this._attemptConnect();
712
+
713
+ } catch (error) {
714
+ this.log.error('jwt.refresh.failure', { error: error.message, retryCount: this.refreshAttempts });
715
+ this.refreshState = 'failed';
716
+ process.exit(1);
717
+ }
718
+ }
719
+
720
+ // CLI-RES-REFRESH-FALLBACK: Lease-preserving fallback when refresh fails
721
+ // Reuses existing lease via refreshOf instead of creating a fresh tunnel
722
+ async _fallbackToFreshTunnel() {
723
+ this.refreshState = 'fallback';
724
+
725
+ // Get current assignment to extract leaseId for reuse
726
+ const { getAssignment } = await import('../state/assignment.js');
727
+ const currentAssignment = getAssignment();
728
+
729
+ if (!currentAssignment) {
730
+ this.log.error('jwt.refresh.fallback.no_assignment', { error: 'no_current_assignment' });
731
+ process.exit(1);
732
+ }
733
+
734
+ const leaseId = currentAssignment.leaseId;
735
+ const relayId = currentAssignment.relayId;
736
+
737
+ if (!leaseId) {
738
+ this.log.error('jwt.refresh.fallback.no_lease_id', { error: 'lease_id_missing' });
739
+ process.exit(1);
740
+ }
741
+
742
+ this.log.info('jwt.refresh.fallback.start', { reason: 'refresh_timeout_or_publish_failure', leaseId, relayId });
743
+
744
+ // Retry loop with max attempts
745
+ let retryCount = 0;
746
+ const maxFallbackRetries = this.refreshMaxAttempts;
747
+
748
+ while (retryCount < maxFallbackRetries) {
749
+ try {
750
+ // CLI-RES-REFRESH-FALLBACK: Control-plane gating before fallback
751
+ const ready = await this._ensureControlPlane('jwt_refresh_fallback');
752
+ if (!ready) {
753
+ this.log.warn('jwt.refresh.fallback.control_plane_timeout', { retryCount, leaseId });
754
+ try {
755
+ await this.waitForControlPlane();
756
+ this.log.info('jwt.refresh.fallback.control_plane_recovered', { leaseId });
757
+ } catch (waitError) {
758
+ retryCount++;
759
+ if (retryCount >= maxFallbackRetries) {
760
+ this.log.error('jwt.refresh.fallback.failure', {
761
+ error: waitError.message,
762
+ reason: 'control_plane_timeout_exhausted',
763
+ retryCount,
764
+ leaseId
765
+ });
766
+ this.refreshState = 'failed';
767
+ process.exit(1);
768
+ }
769
+ continue; // Retry fallback after brief delay
770
+ }
771
+ }
772
+
773
+ // CLI-RES-REFRESH-FALLBACK: Build lease-preserving refresh payload
774
+ const { getFpHash } = await import('../lib/fingerprint.js');
775
+ const fingerprint = await getFpHash(this.deviceId);
776
+ const refreshRequestId = `refresh-${Date.now()}`;
777
+
778
+ const refreshPayload = {
779
+ requestId: refreshRequestId,
780
+ refreshOf: leaseId, // CLI-RES-REFRESH-FALLBACK: Reuse existing lease
781
+ reconnect: false, // This is a refresh, not a reconnect
782
+ proto: 'http',
783
+ localPort: this.localPort,
784
+ clientId: this.deviceId,
785
+ ...fingerprint
786
+ };
787
+
788
+ // Set up topic for refresh request
789
+ const cmdOpenTopic = `asyx/tunnel/clients/${this.deviceId}/cmd/open`;
790
+
791
+ // Wait for open_ack with timeout
792
+ const ackPromise = this.coordinatorIngress.registerAwaiter((message) => {
793
+ try {
794
+ const parsed = message.payload;
795
+ return parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
796
+ } catch (e) {
797
+ return false;
798
+ }
799
+ }, 10000);
800
+
801
+ // CLI-RES-REFRESH-FALLBACK: Publish lease-preserving refresh request
802
+ try {
803
+ await this.coordinatorCore.publish({
804
+ topic: cmdOpenTopic,
805
+ payload: JSON.stringify(refreshPayload),
806
+ qos: 1,
807
+ retain: false
808
+ });
809
+
810
+ this.log.info('jwt.refresh.fallback.request.sent', {
811
+ refreshRequestId,
812
+ leaseId,
813
+ relayId,
814
+ retryCount: retryCount + 1
815
+ });
816
+
817
+ // Wait for open_ack with timeout handling
818
+ try {
819
+ await ackPromise;
820
+ } catch (timeoutError) {
821
+ retryCount++;
822
+ this.log.warn('jwt.refresh.fallback.timeout', {
823
+ retryCount,
824
+ leaseId,
825
+ error: timeoutError.message
826
+ });
827
+ if (retryCount >= maxFallbackRetries) {
828
+ this.log.error('jwt.refresh.fallback.failure', {
829
+ error: 'ack_timeout_exhausted',
830
+ retryCount,
831
+ leaseId
832
+ });
833
+ this.refreshState = 'failed';
834
+ process.exit(1);
835
+ }
836
+ continue; // Retry fallback
837
+ }
838
+ } catch (publishError) {
839
+ retryCount++;
840
+ this.log.warn('jwt.refresh.fallback.publish_failed', {
841
+ retryCount,
842
+ leaseId,
843
+ error: publishError.message
844
+ });
845
+ if (retryCount >= maxFallbackRetries) {
846
+ this.log.error('jwt.refresh.fallback.failure', {
847
+ error: 'publish_failed_exhausted',
848
+ retryCount,
849
+ leaseId
850
+ });
851
+ this.refreshState = 'failed';
852
+ process.exit(1);
853
+ }
854
+ // Wait briefly before retry
855
+ await new Promise(resolve => setTimeout(resolve, 1000));
856
+ continue;
857
+ }
858
+
859
+ // Get the new assignment (with refreshed JWT but same leaseId)
860
+ const newAssignment = getAssignment();
861
+ if (!newAssignment) {
862
+ retryCount++;
863
+ this.log.warn('jwt.refresh.fallback.no_new_assignment', { retryCount, leaseId });
864
+ if (retryCount >= maxFallbackRetries) {
865
+ this.log.error('jwt.refresh.fallback.failure', {
866
+ error: 'no_assignment_after_ack',
867
+ retryCount,
868
+ leaseId
869
+ });
870
+ this.refreshState = 'failed';
871
+ process.exit(1);
872
+ }
873
+ continue;
874
+ }
875
+
876
+ // CLI-RES-REFRESH-FALLBACK: Update tunnel state with refreshed assignment
877
+ this.jwt = newAssignment.jwt;
878
+ this.requestId = newAssignment.requestId;
879
+ this.relayUrl = newAssignment.relayUrl;
880
+ this.headers = {
881
+ 'Authorization': `Bearer ${this.jwt}`,
882
+ 'X-Asyx-DeviceId': this.deviceId,
883
+ 'X-Asyx-RequestId': newAssignment.requestId
884
+ };
885
+
886
+ // Record refresh delta for fallback path
887
+ const { recordRefresh } = await import('../state/assignment.js');
888
+ const deltaMs = recordRefresh(Date.now());
889
+ this.log.info('jwt.refresh.delta', { deltaMs });
890
+ this.log.info('jwt.refresh.fallback.success', {
891
+ leaseId: newAssignment.leaseId || leaseId,
892
+ relayId: newAssignment.relayId || relayId,
893
+ deltaMs
894
+ });
895
+ this.refreshState = 'idle';
896
+ this.refreshAttempts = 0;
897
+
898
+ // CLI-RES-DPJWT-LEAD: Schedule next proactive refresh
899
+ this.scheduleRefresh(this.jwt, 'fallback_success');
900
+
901
+ // Reconnect WebSocket with refreshed JWT
902
+ await this._attemptConnect();
903
+
904
+ // Success - exit retry loop
905
+ return;
906
+
907
+ } catch (error) {
908
+ retryCount++;
909
+ this.log.warn('jwt.refresh.fallback.retry', {
910
+ error: error.message,
911
+ retryCount,
912
+ leaseId
913
+ });
914
+ if (retryCount >= maxFallbackRetries) {
915
+ this.log.error('jwt.refresh.fallback.failure', {
916
+ error: error.message,
917
+ retryCount,
918
+ leaseId
919
+ });
920
+ this.refreshState = 'failed';
921
+ process.exit(1);
922
+ }
923
+ // Brief delay before retry
924
+ await new Promise(resolve => setTimeout(resolve, 1000));
925
+ }
926
+ }
927
+ }
928
+
929
+ handleHttpRequest(msg) {
930
+ // CRT-Relay-E: Update activity on HTTP request
931
+ this.lastActivityMs = Date.now();
932
+
933
+ // Handle JSON-formatted HTTP request from relay (CRT-Relay-B compact format)
934
+ const { t, rid, m, u, h, b } = msg;
935
+
936
+ // Extract fields from compact format
937
+ const requestId = rid;
938
+ const method = m;
939
+ const url = u;
940
+ const headers = h;
941
+ const bodyBuffer = b ? Buffer.from(b, 'base64') : null;
942
+
943
+ // Forward to local HTTP server
944
+ const options = {
945
+ hostname: 'localhost',
946
+ port: this.localPort,
947
+ path: url,
948
+ method: method,
949
+ headers: headers
950
+ };
951
+
952
+ const proxyReq = http.request(options, (proxyRes) => {
953
+ // Send response back to relay using CRT-Relay-B compact format
954
+ const responseChunks = [];
955
+ proxyRes.on('data', chunk => {
956
+ responseChunks.push(chunk);
957
+ });
958
+
959
+ proxyRes.on('end', () => {
960
+ // CRT-Relay-E: Update activity on HTTP response
961
+ this.lastActivityMs = Date.now();
962
+
963
+ // Convert headers to array format and encode body as base64
964
+ const headerArray = Object.entries(proxyRes.headers).map(([name, value]) => [name, value]);
965
+ const bodyBuffer = Buffer.concat(responseChunks);
966
+ const bodyBase64 = bodyBuffer.length ? bodyBuffer.toString('base64') : '';
967
+
968
+ const responseData = {
969
+ t: 'http_response',
970
+ rid: requestId, // Use the same rid from the request
971
+ s: proxyRes.statusCode,
972
+ h: headerArray,
973
+ b: bodyBase64
974
+ };
975
+
976
+ this.ws.send(JSON.stringify(responseData));
977
+ });
978
+ });
979
+
980
+ // Handle connection errors to local service
981
+ proxyReq.on('error', (err) => {
982
+ if (err.code === 'ECONNREFUSED') {
983
+ this.log.error({ port: this.localPort }, 'Local service refused connection');
984
+ process.exit(1);
985
+ } else {
986
+ this.log.error({ err, requestId }, 'Proxy request error');
987
+ }
988
+ });
989
+
990
+ if (bodyBuffer && bodyBuffer.length > 0) {
991
+ proxyReq.write(bodyBuffer);
992
+ }
993
+ proxyReq.end();
994
+ }
995
+
996
+ handleHttpRequestBuffer(buffer) {
997
+ // Handle raw HTTP request buffer from relay
998
+ const httpString = buffer.toString();
999
+ const lines = httpString.split('\r\n');
1000
+ const [method, url, version] = lines[0].split(' ');
1001
+
1002
+ const headers = {};
1003
+ let bodyStart = 0;
1004
+ for (let i = 1; i < lines.length; i++) {
1005
+ if (lines[i] === '') {
1006
+ bodyStart = i + 1;
1007
+ break;
1008
+ }
1009
+ const [key, value] = lines[i].split(': ');
1010
+ headers[key.toLowerCase()] = value;
1011
+ }
1012
+
1013
+ const body = lines.slice(bodyStart).join('\r\n');
1014
+
1015
+ // Forward to local HTTP server
1016
+ const options = {
1017
+ hostname: 'localhost',
1018
+ port: this.localPort,
1019
+ path: url,
1020
+ method: method,
1021
+ headers: headers
1022
+ };
1023
+
1024
+ const proxyReq = http.request(options, (proxyRes) => {
1025
+ // Send response back to relay as binary
1026
+ let responseBuffer = Buffer.from(`HTTP/1.1 ${proxyRes.statusCode} ${proxyRes.statusMessage}\r\n`);
1027
+
1028
+ // Add headers
1029
+ for (const [key, value] of Object.entries(proxyRes.headers)) {
1030
+ responseBuffer = Buffer.concat([responseBuffer, Buffer.from(`${key}: ${value}\r\n`)]);
1031
+ }
1032
+ responseBuffer = Buffer.concat([responseBuffer, Buffer.from('\r\n')]);
1033
+
1034
+ // Add body
1035
+ proxyRes.on('data', chunk => {
1036
+ responseBuffer = Buffer.concat([responseBuffer, chunk]);
1037
+ });
1038
+
1039
+ proxyRes.on('end', () => {
1040
+ this.ws.send(responseBuffer);
1041
+ });
1042
+ });
1043
+
1044
+ // Handle connection errors to local service
1045
+ proxyReq.on('error', (err) => {
1046
+ if (err.code === 'ECONNREFUSED') {
1047
+ this.log.error({ port: this.localPort }, 'Local service refused connection');
1048
+ process.exit(1);
1049
+ } else {
1050
+ this.log.error({ err }, 'Proxy request error (buffer mode)');
1051
+ }
1052
+ });
1053
+
1054
+ if (body) {
1055
+ proxyReq.write(body);
1056
+ }
1057
+ proxyReq.end();
1058
+ }
1059
+
1060
+ close() {
1061
+ // CLI-IMG-WSReconnect: Disable reconnects and clear timer
1062
+ this.shouldReconnect = false;
1063
+ if (this.reconnectTimer) {
1064
+ clearTimeout(this.reconnectTimer);
1065
+ this.reconnectTimer = null;
1066
+ }
1067
+
1068
+ // CLI-RES-DPJWT-LEAD: Clear refresh timer to avoid leaks
1069
+ if (this.refreshTimer) {
1070
+ clearTimeout(this.refreshTimer);
1071
+ this.refreshTimer = null;
1072
+ }
1073
+
1074
+ // CLI-REAUTH: Cleanup control frame waiters
1075
+ clearAllWaiters();
1076
+ this.reauthInFlight = null;
1077
+
1078
+ // CRT-Relay-E: Stop heartbeat before closing
1079
+ this.stopHeartbeat();
1080
+ if (this.ws) {
1081
+ this.ws.close();
1082
+ }
1083
+ }
1084
+
1085
+ // CRT-Relay-E: Heartbeat methods
1086
+ getHeartbeatInterval() {
1087
+ const interval = process.env.ASYX_TUNNEL_HEARTBEAT_SEC || '120';
1088
+ const intervalMs = Number(interval) * 1000;
1089
+ return intervalMs <= 0 ? Infinity : intervalMs;
1090
+ }
1091
+
1092
+ startHeartbeat() {
1093
+ const interval = this.getHeartbeatInterval();
1094
+ if (interval === Infinity) {
1095
+ this.log.debug('Heartbeat disabled (ASYX_TUNNEL_HEARTBEAT_SEC <= 0)');
1096
+ return;
1097
+ }
1098
+
1099
+ this.heartbeatTimer = setInterval(() => {
1100
+ this.sendHeartbeat();
1101
+ }, interval);
1102
+
1103
+ this.log.debug({ interval }, 'tunnel heartbeat started');
1104
+ }
1105
+
1106
+ sendHeartbeat() {
1107
+ // Guard against sending when WebSocket is not open
1108
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1109
+ return;
1110
+ }
1111
+
1112
+ // Check if we should send heartbeat (respect real traffic)
1113
+ const now = Date.now();
1114
+ const timeSinceActivity = now - this.lastActivityMs;
1115
+ const interval = this.getHeartbeatInterval();
1116
+
1117
+ if (timeSinceActivity >= interval) {
1118
+ this.ws.send(JSON.stringify({ t: 'ping' }));
1119
+ this.lastActivityMs = now;
1120
+ this.log.debug({ interval }, 'tunnel heartbeat ping sent');
1121
+ }
1122
+ }
1123
+
1124
+ stopHeartbeat() {
1125
+ if (this.heartbeatTimer) {
1126
+ clearInterval(this.heartbeatTimer);
1127
+ this.heartbeatTimer = null;
1128
+ this.log.debug('tunnel heartbeat stopped');
1129
+ }
1130
+ }
1131
+ }