asyx 0.5.7 → 0.5.9

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.
@@ -14,6 +14,64 @@ import {
14
14
  } from './httpws-constants.js';
15
15
 
16
16
  const V2_THRESHOLD_BYTES = 8 * 1024 * 1024; // 8 MiB threshold for v2 selection
17
+ // Defect 11.9: the relay accepts WebSocket messages up to 16 MiB (wsProxy maxPayload); a larger
18
+ // one closes the whole tunnel (1009). A v1 response frame carries the body in base64.
19
+ const RELAY_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
20
+ const V1_MAX_FRAME_BYTES = RELAY_MAX_MESSAGE_BYTES - 64 * 1024; // headroom for JSON and headers
21
+ const HELLO_RETRY_MS = 3000;
22
+ const HELLO_MAX_ATTEMPTS = 3;
23
+
24
+ const TUNNEL_DROP_HEADERS = new Set([
25
+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
26
+ 'te', 'trailers', 'transfer-encoding', 'upgrade',
27
+ 'sec-websocket-key', 'sec-websocket-version',
28
+ 'forwarded', 'x-forwarded-host'
29
+ ]);
30
+
31
+ function headersToObject(headers) {
32
+ const out = {};
33
+ if (Array.isArray(headers)) {
34
+ for (const pair of headers) {
35
+ if (!Array.isArray(pair) || pair.length < 2) continue;
36
+ const name = String(pair[0]).toLowerCase();
37
+ const value = pair[1];
38
+ out[name] = Array.isArray(value) ? value.map((part) => String(part)).join(', ') : (value == null ? '' : String(value));
39
+ }
40
+ return out;
41
+ }
42
+ if (headers && typeof headers === 'object') {
43
+ for (const [name, value] of Object.entries(headers)) {
44
+ out[String(name).toLowerCase()] = value;
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+
50
+ function sanitizeLocalRequest(url, headers, bodyBuffer, localPort) {
51
+ if (typeof url !== 'string' || !url.startsWith('/') || url.startsWith('//') || /[\r\n]/.test(url)) {
52
+ return { error: 400 };
53
+ }
54
+ const source = headersToObject(headers);
55
+ const out = {};
56
+ for (const [name, value] of Object.entries(source)) {
57
+ if (TUNNEL_DROP_HEADERS.has(name)) continue;
58
+ if (/[\r\n]/.test(name)) return { error: 400 };
59
+ const parts = Array.isArray(value) ? value : [value];
60
+ if (parts.some((part) => typeof part === 'string' && /[\r\n]/.test(part))) {
61
+ return { error: 400 };
62
+ }
63
+ out[name] = value;
64
+ }
65
+ const host = out.host == null ? '' : String(out.host);
66
+ if (!host || /[\r\n]/.test(host)) {
67
+ out.host = `localhost:${localPort}`;
68
+ }
69
+ delete out['transfer-encoding'];
70
+ if (bodyBuffer && bodyBuffer.length > 0) {
71
+ out['content-length'] = String(bodyBuffer.length);
72
+ }
73
+ return { path: url, headers: out };
74
+ }
17
75
 
18
76
  export class HttpTunnel {
19
77
  constructor({
@@ -491,7 +549,12 @@ export class HttpTunnel {
491
549
 
492
550
  // CLI-IMG-WSReconnect: Clean up previous WebSocket if exists
493
551
  if (this.ws) {
494
- this.ws.removeAllListeners();
552
+ const old = this.ws;
553
+ old.removeAllListeners();
554
+ // Defect 11.10: a late error from the replaced socket must not crash the CLI
555
+ // (an 'error' event with no listener is thrown by Node)
556
+ old.on('error', () => {});
557
+ try { if (old.readyState === WebSocket.OPEN || old.readyState === WebSocket.CONNECTING) old.terminate?.(); } catch (_) {}
495
558
  this.ws = null;
496
559
  }
497
560
 
@@ -507,7 +570,11 @@ export class HttpTunnel {
507
570
  // CLI-IMG-WSReconnect: Reset retry count on successful connection
508
571
  this.retryCount = 0;
509
572
 
510
- // S-0: Send hello frame for HTTP-WS v2 negotiation
573
+ // S-0: Send hello frame for HTTP-WS v2 negotiation. Defect 11.9: negotiation is per
574
+ // connection (the relay checks it per connection), so forget the previous result
575
+ // and resend the hello until it is acknowledged.
576
+ this.httpWsVersion = null;
577
+ this._helloAttempts = 0;
511
578
  this._sendHello();
512
579
 
513
580
  // CLI-RES-DPJWT-LEAD: Check if refresh needed before resuming
@@ -612,6 +679,13 @@ export class HttpTunnel {
612
679
  return;
613
680
  }
614
681
 
682
+ // Defect 11.10: 'error' and 'close' both fire for one failed attempt; schedule once, so the
683
+ // backoff advances one step per attempt and two connects never race each other
684
+ if (this.reconnectTimer) {
685
+ this.log.debug({ code, reason }, 'Reconnect already scheduled');
686
+ return;
687
+ }
688
+
615
689
  // CLI-IMG-Retry-Ceiling: Check retry limit with descriptive messaging
616
690
  if (this.retryCount >= this.maxRetries) {
617
691
  this.log.error(
@@ -664,6 +738,7 @@ export class HttpTunnel {
664
738
 
665
739
  // Schedule reconnect attempt
666
740
  this.reconnectTimer = setTimeout(() => {
741
+ this.reconnectTimer = null;
667
742
  this.attemptReconnect();
668
743
  }, delay);
669
744
  }
@@ -1168,6 +1243,19 @@ export class HttpTunnel {
1168
1243
  }
1169
1244
  }
1170
1245
 
1246
+ sendTunnelError(requestId, status) {
1247
+ const responseData = {
1248
+ t: 'http_response',
1249
+ rid: requestId,
1250
+ s: status,
1251
+ h: [['content-type', 'text/plain']],
1252
+ b: ''
1253
+ };
1254
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1255
+ this.ws.send(JSON.stringify(responseData));
1256
+ }
1257
+ }
1258
+
1171
1259
  handleHttpRequest(msg) {
1172
1260
  // CRT-Relay-E: Update activity on HTTP request
1173
1261
  this.lastActivityMs = Date.now();
@@ -1178,9 +1266,14 @@ export class HttpTunnel {
1178
1266
  // Extract fields from compact format
1179
1267
  const requestId = rid;
1180
1268
  const method = m;
1181
- const url = u;
1182
- const headers = h;
1183
1269
  const bodyBuffer = b ? Buffer.from(b, 'base64') : null;
1270
+ const sanitized = sanitizeLocalRequest(u, h, bodyBuffer, this.localPort);
1271
+ if (sanitized.error) {
1272
+ this.sendTunnelError(requestId, sanitized.error);
1273
+ return;
1274
+ }
1275
+ const url = sanitized.path;
1276
+ const headers = sanitized.headers;
1184
1277
 
1185
1278
  // Forward to local HTTP server
1186
1279
  const options = {
@@ -1191,7 +1284,9 @@ export class HttpTunnel {
1191
1284
  headers: headers
1192
1285
  };
1193
1286
 
1194
- const proxyReq = http.request(options, (proxyRes) => {
1287
+ let proxyReq;
1288
+ try {
1289
+ proxyReq = http.request(options, (proxyRes) => {
1195
1290
  // S-1: Determine response mode at http_response_start
1196
1291
  const contentLength = proxyRes.headers['content-length']
1197
1292
  ? parseInt(proxyRes.headers['content-length'], 10)
@@ -1225,15 +1320,23 @@ export class HttpTunnel {
1225
1320
  proxyReq.write(bodyBuffer);
1226
1321
  }
1227
1322
  proxyReq.end();
1323
+ } catch (err) {
1324
+ if (err && (err.code === 'ERR_INVALID_CHAR' || err.code === 'ERR_INVALID_HTTP_TOKEN')) {
1325
+ this.sendTunnelError(requestId, 400);
1326
+ return;
1327
+ }
1328
+ this.log.error({ err, requestId }, 'Proxy request error');
1329
+ this.sendTunnelError(requestId, 502);
1330
+ }
1228
1331
  }
1229
1332
 
1230
1333
  handleHttpRequestBuffer(buffer) {
1231
1334
  // Handle raw HTTP request buffer from relay
1232
1335
  const httpString = buffer.toString();
1233
1336
  const lines = httpString.split('\r\n');
1234
- const [method, url, version] = lines[0].split(' ');
1337
+ const [method, rawUrl] = lines[0].split(' ');
1235
1338
 
1236
- const headers = {};
1339
+ const parsedHeaders = {};
1237
1340
  let bodyStart = 0;
1238
1341
  for (let i = 1; i < lines.length; i++) {
1239
1342
  if (lines[i] === '') {
@@ -1241,21 +1344,31 @@ export class HttpTunnel {
1241
1344
  break;
1242
1345
  }
1243
1346
  const [key, value] = lines[i].split(': ');
1244
- headers[key.toLowerCase()] = value;
1347
+ if (key) {
1348
+ parsedHeaders[key.toLowerCase()] = value;
1349
+ }
1245
1350
  }
1246
1351
 
1247
1352
  const body = lines.slice(bodyStart).join('\r\n');
1353
+ const bodyBuffer = Buffer.from(body);
1354
+ const sanitized = sanitizeLocalRequest(rawUrl, parsedHeaders, bodyBuffer, this.localPort);
1355
+ if (sanitized.error) {
1356
+ this.log.warn({ method }, 'Rejected raw tunnel request');
1357
+ return;
1358
+ }
1248
1359
 
1249
1360
  // Forward to local HTTP server
1250
1361
  const options = {
1251
1362
  hostname: 'localhost',
1252
1363
  port: this.localPort,
1253
- path: url,
1364
+ path: sanitized.path,
1254
1365
  method: method,
1255
- headers: headers
1366
+ headers: sanitized.headers
1256
1367
  };
1257
1368
 
1258
- const proxyReq = http.request(options, (proxyRes) => {
1369
+ let proxyReq;
1370
+ try {
1371
+ proxyReq = http.request(options, (proxyRes) => {
1259
1372
  // Send response back to relay as binary
1260
1373
  let responseBuffer = Buffer.from(`HTTP/1.1 ${proxyRes.statusCode} ${proxyRes.statusMessage}\r\n`);
1261
1374
 
@@ -1289,6 +1402,13 @@ export class HttpTunnel {
1289
1402
  proxyReq.write(body);
1290
1403
  }
1291
1404
  proxyReq.end();
1405
+ } catch (err) {
1406
+ if (err && (err.code === 'ERR_INVALID_CHAR' || err.code === 'ERR_INVALID_HTTP_TOKEN')) {
1407
+ this.log.warn({ err }, 'Rejected raw tunnel request header');
1408
+ return;
1409
+ }
1410
+ throw err;
1411
+ }
1292
1412
  }
1293
1413
 
1294
1414
  // S-0: Send hello frame for HTTP-WS v2 negotiation
@@ -1307,10 +1427,24 @@ export class HttpTunnel {
1307
1427
 
1308
1428
  this.ws.send(JSON.stringify(hello));
1309
1429
  this.log.debug('Hello frame sent', { protocols: hello.protocols });
1430
+ // Defect 11.9: if no hello_ack arrives (the relay lost it), offer again
1431
+ this._helloAttempts = (this._helloAttempts || 0) + 1;
1432
+ if (this._helloTimer) clearTimeout(this._helloTimer);
1433
+ if (this._helloAttempts < HELLO_MAX_ATTEMPTS) {
1434
+ const ws = this.ws;
1435
+ this._helloTimer = setTimeout(() => {
1436
+ this._helloTimer = null;
1437
+ if (this.httpWsVersion || this.ws !== ws || ws.readyState !== WebSocket.OPEN) return;
1438
+ this.log.warn('hello.no_ack.resending', { attempt: this._helloAttempts + 1 });
1439
+ this._sendHello();
1440
+ }, HELLO_RETRY_MS);
1441
+ if (this._helloTimer.unref) this._helloTimer.unref();
1442
+ }
1310
1443
  }
1311
1444
 
1312
1445
  // S-0: Handle hello_ack for HTTP-WS v2 negotiation
1313
1446
  _handleHelloAck(helloAck) {
1447
+ if (this._helloTimer) { clearTimeout(this._helloTimer); this._helloTimer = null; }
1314
1448
  this.httpWsVersion = helloAck.protocols?.httpWs || null;
1315
1449
  this.log.info('Hello ack received', { httpWsVersion: this.httpWsVersion });
1316
1450
 
@@ -1511,9 +1645,16 @@ export class HttpTunnel {
1511
1645
  h: headerArray,
1512
1646
  b: bodyBase64
1513
1647
  };
1514
-
1648
+ const frame = JSON.stringify(responseData);
1649
+ // Defect 11.9: never send a message the relay refuses; it would close the whole tunnel.
1650
+ // Fail only this request (502) instead.
1651
+ if (Buffer.byteLength(frame) > V1_MAX_FRAME_BYTES) {
1652
+ this.log.error('v1.response.too_large', { requestId, bodyBytes: bodyBuffer.length, frameBytes: Buffer.byteLength(frame), httpWsVersion: this.httpWsVersion });
1653
+ this.sendTunnelError(requestId, 502);
1654
+ return;
1655
+ }
1515
1656
  if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1516
- this.ws.send(JSON.stringify(responseData));
1657
+ this.ws.send(frame);
1517
1658
  }
1518
1659
  });
1519
1660
  }
@@ -0,0 +1,182 @@
1
+ // Story 11.2: reconnect for TCP and UDP tunnels.
2
+ //
3
+ // When the relay connection of an established TCP or UDP tunnel drops, the tunnel
4
+ // reconnects to the same relay and lease with the newest assignment token instead
5
+ // of ending the CLI. Everything bound to the old connection (TCP streams and their
6
+ // local sockets, UDP flows and their sockets, partial frames) is discarded first,
7
+ // so traffic from before the drop can never be delivered on the new connection.
8
+ //
9
+ // Settings (environment):
10
+ // ASYX_TUNNEL_RECONNECT=0 disable (the tunnel ends on a drop, as before)
11
+ // ASYX_TUNNEL_RECONNECT_MAX_MS give up after this long without a connection (default 15 min)
12
+ // ASYX_TUNNEL_RECONNECT_MAX_DELAY_MS longest wait between attempts (default 5000)
13
+
14
+ export const DEFAULT_INITIAL_DELAY_MS = 250;
15
+ export const DEFAULT_MAX_DELAY_MS = 5000;
16
+ export const DEFAULT_MAX_OUTAGE_MS = 15 * 60 * 1000;
17
+ export const DEFAULT_MAX_AUTH_FAILURES = 3;
18
+
19
+ export function reconnectEnabled(env = process.env) {
20
+ return env.ASYX_TUNNEL_RECONNECT !== '0';
21
+ }
22
+
23
+ function envInt(env, name, fallback) {
24
+ const v = parseInt(env[name] ?? '', 10);
25
+ return Number.isFinite(v) && v > 0 ? v : fallback;
26
+ }
27
+
28
+ /**
29
+ * Decide what an established connection's close means.
30
+ * Close code 4000 is the relay's application code: "lease_closed" (the control plane
31
+ * ended the lease) and "lease_reconnected" (another connection took the lease over)
32
+ * must not be fought; anything else (relay restart, network loss, 1006, 1001, 1011,
33
+ * protocol errors) is retried.
34
+ */
35
+ export function classifyDrop(code, reason) {
36
+ const r = String(reason || '');
37
+ if (code === 4000 && r === 'lease_closed') return { fatal: true, reason: 'lease_closed' };
38
+ if (code === 4000 && r === 'lease_reconnected') return { fatal: true, reason: 'replaced_by_another_connection' };
39
+ return { fatal: false, reason: `ws_close_${code}` };
40
+ }
41
+
42
+ /** HTTP status from a ws handshake error ("Unexpected server response: 403"). */
43
+ export function httpStatusOf(err) {
44
+ if (!err) return null;
45
+ if (Number.isInteger(err.httpStatus)) return err.httpStatus;
46
+ const m = /Unexpected server response: (\d{3})/.exec(err.message || '');
47
+ return m ? Number(m[1]) : null;
48
+ }
49
+
50
+ /**
51
+ * Decide what a failed reconnect attempt means.
52
+ * 401/403 and token verification failures are counted as authorization failures
53
+ * (the token expired or the lease was closed); a few in a row end the tunnel.
54
+ * 409 means the relay still holds the old connection for the lease; retry.
55
+ * 400 means the request itself is malformed; retrying cannot help.
56
+ */
57
+ export function classifyFailure(err) {
58
+ const status = httpStatusOf(err);
59
+ if (status === 400) return { fatal: true, auth: false, reason: 'bad_request' };
60
+ if (status === 401 || status === 403) return { fatal: false, auth: true, reason: `http_${status}` };
61
+ if (err && err.code === 'UDP_RELAY_UNAVAILABLE' && /JWT verification failed/.test(err.message || '')) {
62
+ // Failing to fetch the JWKS (network) is not a token problem: keep retrying
63
+ const cause = err.cause || {};
64
+ const fetchProblem = /JWKS|fetch|timeout|ECONN|ENOTFOUND|EAI_AGAIN|network/i.test(`${cause.code || ''} ${cause.message || ''}`)
65
+ && !/expired|signature|claim/i.test(`${cause.code || ''} ${cause.message || ''}`);
66
+ if (fetchProblem) return { fatal: false, auth: false, reason: 'jwks_unavailable' };
67
+ return { fatal: false, auth: true, reason: 'token_verification_failed' };
68
+ }
69
+ return { fatal: false, auth: false, reason: status ? `http_${status}` : (err?.code || 'connect_failed') };
70
+ }
71
+
72
+ /** Seconds-since-epoch exp claim of a JWT, or null. */
73
+ export function jwtExp(jwt) {
74
+ try {
75
+ const part = String(jwt).split('.')[1];
76
+ const payload = JSON.parse(Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
77
+ return typeof payload.exp === 'number' ? payload.exp : null;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Runs the reconnect loop for one tunnel.
85
+ * connect(): Promise resolving when a new connection is open, rejecting otherwise.
86
+ * onGiveUp(reason): called once if the tunnel cannot be reconnected.
87
+ * onAuthFailure(): optional (Story 10.9). Called on the first authorization failure of a
88
+ * streak; it may fetch a new assignment (for example after the tenant moved to another
89
+ * relay, where the old token's relay no longer matches). If it returns true, the streak
90
+ * is reset and the next attempt uses the new assignment at once.
91
+ */
92
+ export class Reconnector {
93
+ constructor({
94
+ kind,
95
+ log,
96
+ connect,
97
+ onGiveUp,
98
+ env = process.env,
99
+ initialDelayMs = DEFAULT_INITIAL_DELAY_MS,
100
+ maxDelayMs = envInt(env, 'ASYX_TUNNEL_RECONNECT_MAX_DELAY_MS', DEFAULT_MAX_DELAY_MS),
101
+ maxOutageMs = envInt(env, 'ASYX_TUNNEL_RECONNECT_MAX_MS', DEFAULT_MAX_OUTAGE_MS),
102
+ maxAuthFailures = DEFAULT_MAX_AUTH_FAILURES,
103
+ onAuthFailure = null,
104
+ now = () => Date.now(),
105
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
106
+ }) {
107
+ Object.assign(this, { kind, log, connect, onGiveUp, initialDelayMs, maxDelayMs, maxOutageMs, maxAuthFailures, onAuthFailure, now, sleep });
108
+ this.running = false;
109
+ this.stopped = false;
110
+ this.reconnects = 0;
111
+ }
112
+
113
+ stop() {
114
+ this.stopped = true;
115
+ }
116
+
117
+ delayFor(attempt) {
118
+ return Math.min(this.maxDelayMs, this.initialDelayMs * 2 ** attempt);
119
+ }
120
+
121
+ /** Start reconnecting after a drop. Resolves when connected, given up or stopped. */
122
+ async run(dropReason) {
123
+ if (this.running || this.stopped) return;
124
+ this.running = true;
125
+ const started = this.now();
126
+ let authFailures = 0;
127
+ let reassigned = false;
128
+ this.log.warn({ kind: this.kind, reason: dropReason }, `${this.kind}.reconnect.start`);
129
+ try {
130
+ for (let attempt = 0; ; attempt++) {
131
+ if (!reassigned) await this.sleep(this.delayFor(attempt));
132
+ reassigned = false;
133
+ if (this.stopped) return;
134
+ const outageMs = this.now() - started;
135
+ if (outageMs > this.maxOutageMs) {
136
+ this.giveUp('outage_limit', { outageMs, attempts: attempt });
137
+ return;
138
+ }
139
+ try {
140
+ await this.connect();
141
+ this.reconnects += 1;
142
+ this.log.info({ kind: this.kind, attempts: attempt + 1, outageMs: this.now() - started, reconnects: this.reconnects },
143
+ `${this.kind}.reconnect.ok`);
144
+ return;
145
+ } catch (err) {
146
+ if (this.stopped) return;
147
+ const verdict = classifyFailure(err);
148
+ this.log.warn({ kind: this.kind, attempt: attempt + 1, reason: verdict.reason, error: err?.message },
149
+ `${this.kind}.reconnect.attempt_failed`);
150
+ if (verdict.fatal) {
151
+ this.giveUp(verdict.reason, { attempts: attempt + 1 });
152
+ return;
153
+ }
154
+ authFailures = verdict.auth ? authFailures + 1 : 0;
155
+ if (authFailures === 1 && this.onAuthFailure) {
156
+ let got = false;
157
+ try { got = await this.onAuthFailure(); } catch (e) {
158
+ this.log.warn({ kind: this.kind, error: e?.message }, `${this.kind}.reconnect.reassign_failed`);
159
+ }
160
+ if (got) {
161
+ this.log.info({ kind: this.kind, attempt: attempt + 1 }, `${this.kind}.reconnect.reassigned`);
162
+ authFailures = 0;
163
+ reassigned = true;
164
+ continue;
165
+ }
166
+ }
167
+ if (authFailures >= this.maxAuthFailures) {
168
+ this.giveUp(`${verdict.reason}_repeated`, { attempts: attempt + 1 });
169
+ return;
170
+ }
171
+ }
172
+ }
173
+ } finally {
174
+ this.running = false;
175
+ }
176
+ }
177
+
178
+ giveUp(reason, extra = {}) {
179
+ this.log.error({ kind: this.kind, reason, ...extra }, `${this.kind}.reconnect.gave_up`);
180
+ this.onGiveUp(reason);
181
+ }
182
+ }