asyx 0.3.3 → 0.5.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.
- package/README.md +19 -1
- package/SECURITY.md +2 -2
- package/package.json +10 -12
- package/src/commands/tunnel.js +75 -2
- package/src/main.js +0 -1
- package/src/mqtt/events/index.js +6 -1
- package/src/tunnel/http-tunnel.js +267 -24
- package/src/tunnel/httpws-constants.js +16 -0
package/README.md
CHANGED
|
@@ -2,7 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
Secure, device-bound tunnels for HTTP, TCP, and UDP. The CLI handles device auth, JWT refresh, and resilient control-plane connectivity so you can expose local services without managing relay infrastructure.
|
|
4
4
|
|
|
5
|
-
> Beta access is
|
|
5
|
+
> Beta access is open — create an account at https://www.asyx.ai/register (email + magic link; no invite code).
|
|
6
|
+
|
|
7
|
+
**Documentation:** https://www.asyx.ai/docs
|
|
8
|
+
|
|
9
|
+
| Guide | Link |
|
|
10
|
+
|-------|------|
|
|
11
|
+
| Getting started | https://www.asyx.ai/docs/getting-started |
|
|
12
|
+
| Publish in 60 seconds | https://www.asyx.ai/docs/publish-local-project |
|
|
13
|
+
| Expose localhost | https://www.asyx.ai/docs/expose-localhost |
|
|
14
|
+
| AI coding agents | https://www.asyx.ai/docs/ai-agents |
|
|
15
|
+
| Cursor + Asyx | https://www.asyx.ai/docs/cursor-asyx |
|
|
16
|
+
| vs ngrok & Cloudflare | https://www.asyx.ai/docs/vs-ngrok-cloudflare |
|
|
17
|
+
| Quickpass (guest access) | https://www.asyx.ai/docs/quickpass |
|
|
6
18
|
|
|
7
19
|
---
|
|
8
20
|
|
|
@@ -16,6 +28,12 @@ npm uninstall -g asyx # remove
|
|
|
16
28
|
|
|
17
29
|
---
|
|
18
30
|
|
|
31
|
+
## What's New in 0.4.0
|
|
32
|
+
|
|
33
|
+
**Improved large file downloads**: HTTP tunnels now automatically use streaming transport for large responses (8 MiB+ or unknown size). This enables reliable downloads of any size without hitting memory limits or connection timeouts. The switch happens automatically—no flags or configuration needed. Small responses continue to work exactly as before.
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
19
37
|
## 1. Set up the device (once per host)
|
|
20
38
|
```bash
|
|
21
39
|
asyx setup
|
package/SECURITY.md
CHANGED
|
@@ -10,8 +10,8 @@ Last updated: 2025-10-23
|
|
|
10
10
|
|
|
11
11
|
## Supported Builds
|
|
12
12
|
|
|
13
|
-
- The Asyx CLI is
|
|
14
|
-
-
|
|
13
|
+
- The Asyx CLI is in public beta. Only the latest published npm package receives security updates.
|
|
14
|
+
- Create an account at https://www.asyx.ai/register (email + magic link; no invite code). Subdomains are reserved during `asyx setup`.
|
|
15
15
|
|
|
16
16
|
## Device-Bound Credentials
|
|
17
17
|
|
package/package.json
CHANGED
|
@@ -1,23 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "asyx",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Asyx
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Asyx tunnel CLI — secure localhost exposure (HTTP, TCP, UDP)",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"homepage": "https://
|
|
8
|
-
"repository": {
|
|
9
|
-
"type": "git",
|
|
10
|
-
"url": "git+https://github.com/asyxai/tunnel.git"
|
|
11
|
-
},
|
|
7
|
+
"homepage": "https://www.asyx.ai/docs",
|
|
12
8
|
"bugs": {
|
|
13
|
-
"url": "https://
|
|
9
|
+
"url": "https://www.asyx.ai/docs",
|
|
10
|
+
"email": "security@asyx.ai"
|
|
14
11
|
},
|
|
15
12
|
"keywords": [
|
|
16
13
|
"asyx",
|
|
17
14
|
"cli",
|
|
18
15
|
"tunnel",
|
|
19
16
|
"mqtt",
|
|
20
|
-
"relay"
|
|
17
|
+
"relay",
|
|
18
|
+
"localhost",
|
|
19
|
+
"ngrok-alternative"
|
|
21
20
|
],
|
|
22
21
|
"bin": {
|
|
23
22
|
"asyx": "bin/asyx.js"
|
|
@@ -58,6 +57,7 @@
|
|
|
58
57
|
"src/state/instance-registry.js",
|
|
59
58
|
"src/tcp-v1/framing.js",
|
|
60
59
|
"src/tunnel/http-tunnel.js",
|
|
60
|
+
"src/tunnel/httpws-constants.js",
|
|
61
61
|
"src/tunnel/tcp-tunnel.js",
|
|
62
62
|
"src/tunnel/udp-tunnel.js",
|
|
63
63
|
"src/tunnel/ws-control.js",
|
|
@@ -67,16 +67,13 @@
|
|
|
67
67
|
"SECURITY.md"
|
|
68
68
|
],
|
|
69
69
|
"dependencies": {
|
|
70
|
-
"-": "^0.0.1",
|
|
71
70
|
"@asyx/mqtt-broker-aws": "^0.1.0",
|
|
72
71
|
"@asyx/mqtt-client": "^0.1.0",
|
|
73
72
|
"@peculiar/webcrypto": "^1.5.0",
|
|
74
73
|
"@peculiar/x509": "^1.14.0",
|
|
75
|
-
"asyx": "^0.1.3",
|
|
76
74
|
"chalk": "^5.3.0",
|
|
77
75
|
"hw-fingerprint": "^3.2.0",
|
|
78
76
|
"jose": "^5.10.0",
|
|
79
|
-
"node-fetch": "^3.3.2",
|
|
80
77
|
"open": "^9.1.0",
|
|
81
78
|
"ulid": "^2.4.0",
|
|
82
79
|
"ws": "^8.14.2",
|
|
@@ -88,6 +85,7 @@
|
|
|
88
85
|
"check": "node ./src/main.js --version",
|
|
89
86
|
"test": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand",
|
|
90
87
|
"test:ci": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand --forceExit",
|
|
88
|
+
"test:e2e:httpwsv2": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand --testPathIgnorePatterns=/node_modules/ --testMatch='**/test/e2e/**/*.e2e.test.js'",
|
|
91
89
|
"pack:verify": "node scripts/pack-verify.mjs",
|
|
92
90
|
"prepublishOnly": "npm run test:ci && npm run pack:verify",
|
|
93
91
|
"prepack": "node scripts/prepack.mjs",
|
package/src/commands/tunnel.js
CHANGED
|
@@ -225,21 +225,71 @@ export default async function tunnel(args = []) {
|
|
|
225
225
|
process.exit(2);
|
|
226
226
|
}
|
|
227
227
|
|
|
228
|
+
// UDP-S16: Helper to find closest matching flag for "did you mean" suggestions
|
|
229
|
+
function findClosestFlag(unknownFlag, knownFlags) {
|
|
230
|
+
// Normalize: convert underscores to dashes and lowercase
|
|
231
|
+
const normalize = (str) => str.replace(/_/g, '-').toLowerCase();
|
|
232
|
+
const normalizedUnknown = normalize(unknownFlag);
|
|
233
|
+
|
|
234
|
+
// Find exact match after normalization
|
|
235
|
+
for (const known of knownFlags) {
|
|
236
|
+
if (normalize(known) === normalizedUnknown) {
|
|
237
|
+
return known;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Find close match (contains normalized unknown or vice versa)
|
|
242
|
+
let closest = null;
|
|
243
|
+
for (const known of knownFlags) {
|
|
244
|
+
const normalizedKnown = normalize(known);
|
|
245
|
+
if (normalizedKnown.includes(normalizedUnknown) || normalizedUnknown.includes(normalizedKnown)) {
|
|
246
|
+
if (!closest || Math.abs(normalizedKnown.length - normalizedUnknown.length) < Math.abs(normalize(closest).length - normalizedUnknown.length)) {
|
|
247
|
+
closest = known;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return closest;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// UDP-S16: List of known flags for tunnel command
|
|
256
|
+
const KNOWN_TUNNEL_FLAGS = [
|
|
257
|
+
'--http',
|
|
258
|
+
'--tcp',
|
|
259
|
+
'--udp',
|
|
260
|
+
'--minecraft',
|
|
261
|
+
'--port',
|
|
262
|
+
'--name',
|
|
263
|
+
'--secgroup',
|
|
264
|
+
'--target-host',
|
|
265
|
+
'--external-port',
|
|
266
|
+
'--ext-port',
|
|
267
|
+
'--help',
|
|
268
|
+
'-h'
|
|
269
|
+
];
|
|
270
|
+
|
|
228
271
|
// Simple argument parser (minimist-like)
|
|
272
|
+
// UDP-S16: Enhanced with unknown flag detection
|
|
229
273
|
function parseArgs(args) {
|
|
230
274
|
const parsed = {};
|
|
275
|
+
const consumed = new Set(); // Track consumed argument indices
|
|
276
|
+
|
|
231
277
|
for (let i = 0; i < args.length; i++) {
|
|
278
|
+
if (consumed.has(i)) continue; // Skip already consumed arguments
|
|
279
|
+
|
|
232
280
|
const arg = args[i];
|
|
233
281
|
if (arg === '--http') {
|
|
234
282
|
parsed.http = true;
|
|
283
|
+
consumed.add(i);
|
|
235
284
|
} else if (arg === '--tcp') {
|
|
236
285
|
parsed.tcp = true;
|
|
286
|
+
consumed.add(i);
|
|
237
287
|
} else if (arg === '--udp') {
|
|
238
288
|
parsed.udp = true;
|
|
289
|
+
consumed.add(i);
|
|
239
290
|
} else if (arg === '--minecraft') {
|
|
240
291
|
parsed.minecraft = true;
|
|
241
|
-
|
|
242
|
-
parsed.minecraft = true;
|
|
292
|
+
consumed.add(i);
|
|
243
293
|
} else if (arg === '--port') {
|
|
244
294
|
if (i + 1 < args.length) {
|
|
245
295
|
const port = parseInt(args[i + 1], 10);
|
|
@@ -249,6 +299,8 @@ function parseArgs(args) {
|
|
|
249
299
|
process.exit(2);
|
|
250
300
|
}
|
|
251
301
|
parsed.port = port;
|
|
302
|
+
consumed.add(i);
|
|
303
|
+
consumed.add(i + 1);
|
|
252
304
|
i++; // Skip next argument as it's the port value
|
|
253
305
|
} else {
|
|
254
306
|
logger.error("cli.args.port_missing", {});
|
|
@@ -259,6 +311,8 @@ function parseArgs(args) {
|
|
|
259
311
|
// Optional service name for TCP mode
|
|
260
312
|
if (i + 1 < args.length) {
|
|
261
313
|
parsed.serviceName = args[i + 1];
|
|
314
|
+
consumed.add(i);
|
|
315
|
+
consumed.add(i + 1);
|
|
262
316
|
i++; // Skip next argument as it's the service name value
|
|
263
317
|
} else {
|
|
264
318
|
logger.error("cli.args.name_missing", {});
|
|
@@ -269,6 +323,8 @@ function parseArgs(args) {
|
|
|
269
323
|
// QPA-04: Parse --secgroup flag
|
|
270
324
|
if (i + 1 < args.length) {
|
|
271
325
|
parsed.secGroupSlug = args[i + 1];
|
|
326
|
+
consumed.add(i);
|
|
327
|
+
consumed.add(i + 1);
|
|
272
328
|
i++; // Skip next argument as it's the slug value
|
|
273
329
|
} else {
|
|
274
330
|
logger.error("cli.args.secgroup_missing", {});
|
|
@@ -279,6 +335,8 @@ function parseArgs(args) {
|
|
|
279
335
|
// UDP-S13: Parse --target-host flag (defaults to 127.0.0.1)
|
|
280
336
|
if (i + 1 < args.length) {
|
|
281
337
|
parsed.targetHost = args[i + 1];
|
|
338
|
+
consumed.add(i);
|
|
339
|
+
consumed.add(i + 1);
|
|
282
340
|
i++; // Skip next argument as it's the target host value
|
|
283
341
|
} else {
|
|
284
342
|
logger.error("cli.args.target_host_missing", {});
|
|
@@ -295,6 +353,8 @@ function parseArgs(args) {
|
|
|
295
353
|
process.exit(2);
|
|
296
354
|
}
|
|
297
355
|
parsed.externalPort = externalPort;
|
|
356
|
+
consumed.add(i);
|
|
357
|
+
consumed.add(i + 1);
|
|
298
358
|
i++; // Skip next argument as it's the external port value
|
|
299
359
|
} else {
|
|
300
360
|
logger.error("cli.args.external_port_missing", {});
|
|
@@ -303,7 +363,20 @@ function parseArgs(args) {
|
|
|
303
363
|
}
|
|
304
364
|
} else if (arg === '--help' || arg === '-h') {
|
|
305
365
|
parsed.help = true;
|
|
366
|
+
consumed.add(i);
|
|
367
|
+
} else if (arg.startsWith('--')) {
|
|
368
|
+
// UDP-S16: Unknown flag detected
|
|
369
|
+
const closest = findClosestFlag(arg, KNOWN_TUNNEL_FLAGS);
|
|
370
|
+
if (closest) {
|
|
371
|
+
// User-friendly error message only (no structured logging for user-facing errors)
|
|
372
|
+
process.stderr.write(`Error: Unknown option: ${arg}. Did you mean: ${closest}?\n`);
|
|
373
|
+
} else {
|
|
374
|
+
// User-friendly error message only (no structured logging for user-facing errors)
|
|
375
|
+
process.stderr.write(`Error: Unknown option: ${arg}\n`);
|
|
376
|
+
}
|
|
377
|
+
process.exit(1);
|
|
306
378
|
}
|
|
379
|
+
// Non-flag arguments (like "connect") are not consumed here and will be handled by the caller
|
|
307
380
|
}
|
|
308
381
|
return parsed;
|
|
309
382
|
}
|
package/src/main.js
CHANGED
|
@@ -42,7 +42,6 @@ async function run() {
|
|
|
42
42
|
} else if (cmd === "sts") {
|
|
43
43
|
cmdSts(process.argv.slice(2)).catch(handleFailure('STS'));
|
|
44
44
|
} else if (cmd === "mqtt") {
|
|
45
|
-
// Import and execute mqtt command
|
|
46
45
|
const { default: mqttCommand } = await import("./commands/mqtt.js");
|
|
47
46
|
mqttCommand().catch(handleFailure('MQTT'));
|
|
48
47
|
} else if (cmd === "tunnel") {
|
package/src/mqtt/events/index.js
CHANGED
|
@@ -201,7 +201,12 @@ export async function dispatch(parsedMessage) {
|
|
|
201
201
|
});
|
|
202
202
|
unmatchedEventLogged = true;
|
|
203
203
|
// Reset after 60 seconds to allow occasional logging
|
|
204
|
-
|
|
204
|
+
// Store timeout handle for potential cleanup (though module-level cleanup is rare)
|
|
205
|
+
const timeoutHandle = setTimeout(() => { unmatchedEventLogged = false; }, 60000);
|
|
206
|
+
// In test mode, unref the timeout so it doesn't keep the process alive
|
|
207
|
+
if (process.env.JEST_WORKER_ID !== undefined || process.env.NODE_ENV === 'test') {
|
|
208
|
+
timeoutHandle.unref();
|
|
209
|
+
}
|
|
205
210
|
}
|
|
206
211
|
return;
|
|
207
212
|
}
|
|
@@ -6,6 +6,15 @@ import crypto from 'node:crypto';
|
|
|
6
6
|
// CLI-REAUTH: Control frame helper for in-band reauth
|
|
7
7
|
import { sendControlAndWaitAck, dispatchControlFrame, clearAllWaiters } from './ws-control.js';
|
|
8
8
|
|
|
9
|
+
// S-3: Import HTTP-WS v2 protocol constants
|
|
10
|
+
import {
|
|
11
|
+
HTTPWS_V2_TARGET_CHUNK_BYTES,
|
|
12
|
+
HTTPWS_V2_MAX_CHUNK_BYTES,
|
|
13
|
+
HTTP_BODY_CHUNK
|
|
14
|
+
} from './httpws-constants.js';
|
|
15
|
+
|
|
16
|
+
const V2_THRESHOLD_BYTES = 8 * 1024 * 1024; // 8 MiB threshold for v2 selection
|
|
17
|
+
|
|
9
18
|
export class HttpTunnel {
|
|
10
19
|
constructor({
|
|
11
20
|
relayUrl,
|
|
@@ -81,6 +90,12 @@ export class HttpTunnel {
|
|
|
81
90
|
// CLI-REAUTH: In-band reauth configuration
|
|
82
91
|
this.reauthAckTimeoutMs = Number(process.env.CLI_REAUTH_ACK_TIMEOUT_MS || 3000); // 3 seconds default
|
|
83
92
|
this.reauthInFlight = null; // Single-flight guard: Promise or null
|
|
93
|
+
|
|
94
|
+
// S-0: Track negotiated HTTP-WS version
|
|
95
|
+
this.httpWsVersion = null;
|
|
96
|
+
|
|
97
|
+
// S-1: Track in-progress v2 responses (requestId -> { mode: 'v2', bufferedBytes: 0 })
|
|
98
|
+
this.activeV2Responses = new Map();
|
|
84
99
|
}
|
|
85
100
|
|
|
86
101
|
// CLI-RES-DPJWT-LEAD: Safe JWT decode helper
|
|
@@ -492,6 +507,9 @@ export class HttpTunnel {
|
|
|
492
507
|
// CLI-IMG-WSReconnect: Reset retry count on successful connection
|
|
493
508
|
this.retryCount = 0;
|
|
494
509
|
|
|
510
|
+
// S-0: Send hello frame for HTTP-WS v2 negotiation
|
|
511
|
+
this._sendHello();
|
|
512
|
+
|
|
495
513
|
// CLI-RES-DPJWT-LEAD: Check if refresh needed before resuming
|
|
496
514
|
this._checkRefreshLeadWindow();
|
|
497
515
|
|
|
@@ -526,6 +544,12 @@ export class HttpTunnel {
|
|
|
526
544
|
return;
|
|
527
545
|
}
|
|
528
546
|
|
|
547
|
+
// S-0: Handle hello_ack for HTTP-WS v2 negotiation
|
|
548
|
+
if (msg.type === 'hello_ack') {
|
|
549
|
+
this._handleHelloAck(msg);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
|
|
529
553
|
if (msg.type === 'ping') {
|
|
530
554
|
this.ws.send(JSON.stringify({ type: 'pong' }));
|
|
531
555
|
return;
|
|
@@ -1168,31 +1192,23 @@ export class HttpTunnel {
|
|
|
1168
1192
|
};
|
|
1169
1193
|
|
|
1170
1194
|
const proxyReq = http.request(options, (proxyRes) => {
|
|
1171
|
-
//
|
|
1172
|
-
const
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1195
|
+
// S-1: Determine response mode at http_response_start
|
|
1196
|
+
const contentLength = proxyRes.headers['content-length']
|
|
1197
|
+
? parseInt(proxyRes.headers['content-length'], 10)
|
|
1198
|
+
: null;
|
|
1199
|
+
const isChunked = proxyRes.headers['transfer-encoding']?.toLowerCase() === 'chunked';
|
|
1200
|
+
const selectedMode = this._selectResponseMode(contentLength, isChunked);
|
|
1176
1201
|
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
//
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
t: 'http_response',
|
|
1188
|
-
rid: requestId, // Use the same rid from the request
|
|
1189
|
-
s: proxyRes.statusCode,
|
|
1190
|
-
h: headerArray,
|
|
1191
|
-
b: bodyBase64
|
|
1192
|
-
};
|
|
1193
|
-
|
|
1194
|
-
this.ws.send(JSON.stringify(responseData));
|
|
1195
|
-
});
|
|
1202
|
+
// S-1: Version guard - if v2 not negotiated, force v1
|
|
1203
|
+
const useV2 = selectedMode === 'v2' && this._canUseV2();
|
|
1204
|
+
|
|
1205
|
+
if (useV2) {
|
|
1206
|
+
// S-1: V2 streaming path
|
|
1207
|
+
this._handleV2Response(proxyRes, requestId);
|
|
1208
|
+
} else {
|
|
1209
|
+
// S-1: V1 single-frame path (existing behavior)
|
|
1210
|
+
this._handleV1Response(proxyRes, requestId);
|
|
1211
|
+
}
|
|
1196
1212
|
});
|
|
1197
1213
|
|
|
1198
1214
|
// Handle connection errors to local service
|
|
@@ -1275,6 +1291,233 @@ export class HttpTunnel {
|
|
|
1275
1291
|
proxyReq.end();
|
|
1276
1292
|
}
|
|
1277
1293
|
|
|
1294
|
+
// S-0: Send hello frame for HTTP-WS v2 negotiation
|
|
1295
|
+
_sendHello() {
|
|
1296
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
1297
|
+
this.log.warn('Cannot send hello: WebSocket not open');
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
const hello = {
|
|
1302
|
+
type: 'hello',
|
|
1303
|
+
protocols: {
|
|
1304
|
+
httpWs: ['v2']
|
|
1305
|
+
}
|
|
1306
|
+
};
|
|
1307
|
+
|
|
1308
|
+
this.ws.send(JSON.stringify(hello));
|
|
1309
|
+
this.log.debug('Hello frame sent', { protocols: hello.protocols });
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
// S-0: Handle hello_ack for HTTP-WS v2 negotiation
|
|
1313
|
+
_handleHelloAck(helloAck) {
|
|
1314
|
+
this.httpWsVersion = helloAck.protocols?.httpWs || null;
|
|
1315
|
+
this.log.info('Hello ack received', { httpWsVersion: this.httpWsVersion });
|
|
1316
|
+
|
|
1317
|
+
if (this.httpWsVersion !== 'v2') {
|
|
1318
|
+
this.log.debug('HTTP-WS v2 not negotiated, will use v1 mode');
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
// S-0: Check if HTTP-WS v2 can be used (guard for v2 frame sending)
|
|
1323
|
+
// This method should be called before sending any HTTP_BODY_CHUNK (0x20) frames
|
|
1324
|
+
// Returns true if v2 is negotiated, false otherwise (should fallback to v1)
|
|
1325
|
+
_canUseV2() {
|
|
1326
|
+
return this.httpWsVersion === 'v2';
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
// S-1: Convert requestId string to 8-byte big-endian uint64 buffer
|
|
1330
|
+
// Note: requestId is a UUID string, so we hash it deterministically to get 8 bytes
|
|
1331
|
+
// Both CLI and relay use the same hash function for matching
|
|
1332
|
+
_encodeRequestId(requestId) {
|
|
1333
|
+
const hash = crypto.createHash('sha256').update(requestId).digest();
|
|
1334
|
+
const buffer = Buffer.alloc(8);
|
|
1335
|
+
hash.copy(buffer, 0, 0, 8);
|
|
1336
|
+
// Buffer is already big-endian by default in Node.js
|
|
1337
|
+
return buffer;
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
// S-1: Determine response mode (v1 or v2) based on content-length and size
|
|
1341
|
+
_selectResponseMode(contentLength, isChunked) {
|
|
1342
|
+
// S-1: Use v2 if:
|
|
1343
|
+
// - Content-Length >= 8 MiB, OR
|
|
1344
|
+
// - Content-Length unknown/missing or TE: chunked, OR
|
|
1345
|
+
// - Will cross 8 MiB threshold during buffering
|
|
1346
|
+
if (isChunked || contentLength === null || contentLength === undefined) {
|
|
1347
|
+
return 'v2'; // Unknown length or chunked - use v2
|
|
1348
|
+
}
|
|
1349
|
+
if (contentLength >= V2_THRESHOLD_BYTES) {
|
|
1350
|
+
return 'v2'; // Large known size - use v2
|
|
1351
|
+
}
|
|
1352
|
+
return 'v1'; // Small known size - use v1
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
// S-1: Send HTTP-WS v2 binary chunk frame
|
|
1356
|
+
_sendV2Chunk(requestId, payload) {
|
|
1357
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
1358
|
+
this.log.warn('Cannot send v2 chunk: WebSocket not open', { requestId });
|
|
1359
|
+
return false;
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
// Encode frame: frameType (1 byte) + requestId (8 bytes) + payload
|
|
1363
|
+
const requestIdBuffer = this._encodeRequestId(requestId);
|
|
1364
|
+
const frame = Buffer.concat([
|
|
1365
|
+
Buffer.from([HTTP_BODY_CHUNK]),
|
|
1366
|
+
requestIdBuffer,
|
|
1367
|
+
payload
|
|
1368
|
+
]);
|
|
1369
|
+
|
|
1370
|
+
try {
|
|
1371
|
+
this.ws.send(frame, { binary: true });
|
|
1372
|
+
return true;
|
|
1373
|
+
} catch (error) {
|
|
1374
|
+
this.log.error('Failed to send v2 chunk', { requestId, error: error.message });
|
|
1375
|
+
return false;
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
// S-1: Chunk payload into v2-compliant sizes (64 KiB target, 256 KiB max)
|
|
1380
|
+
_chunkPayload(payload) {
|
|
1381
|
+
const chunks = [];
|
|
1382
|
+
let offset = 0;
|
|
1383
|
+
|
|
1384
|
+
while (offset < payload.length) {
|
|
1385
|
+
// Target 64 KiB, but don't exceed 256 KiB
|
|
1386
|
+
const remaining = payload.length - offset;
|
|
1387
|
+
const chunkSize = Math.min(
|
|
1388
|
+
HTTPWS_V2_TARGET_CHUNK_BYTES,
|
|
1389
|
+
Math.min(remaining, HTTPWS_V2_MAX_CHUNK_BYTES)
|
|
1390
|
+
);
|
|
1391
|
+
chunks.push(payload.slice(offset, offset + chunkSize));
|
|
1392
|
+
offset += chunkSize;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
return chunks;
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
// S-1: Handle v2 streaming response
|
|
1399
|
+
_handleV2Response(proxyRes, requestId) {
|
|
1400
|
+
// Track this response as v2
|
|
1401
|
+
this.activeV2Responses.set(requestId, { mode: 'v2', bufferedBytes: 0 });
|
|
1402
|
+
|
|
1403
|
+
// Convert headers to array format
|
|
1404
|
+
const headerArray = Object.entries(proxyRes.headers).map(([name, value]) => [name, value]);
|
|
1405
|
+
|
|
1406
|
+
// S-1: Send http_response_start with mode: "stream"
|
|
1407
|
+
const responseStart = {
|
|
1408
|
+
type: 'http_response_start',
|
|
1409
|
+
rid: requestId,
|
|
1410
|
+
status: proxyRes.statusCode,
|
|
1411
|
+
headers: headerArray,
|
|
1412
|
+
mode: 'stream'
|
|
1413
|
+
};
|
|
1414
|
+
|
|
1415
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
1416
|
+
this.log.warn('Cannot send v2 response: WebSocket not open', { requestId });
|
|
1417
|
+
this.activeV2Responses.delete(requestId);
|
|
1418
|
+
return;
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
this.ws.send(JSON.stringify(responseStart));
|
|
1422
|
+
|
|
1423
|
+
// S-1: Stream chunks as they arrive
|
|
1424
|
+
let buffer = Buffer.alloc(0);
|
|
1425
|
+
const flushBuffer = () => {
|
|
1426
|
+
if (buffer.length === 0) return;
|
|
1427
|
+
|
|
1428
|
+
const chunks = this._chunkPayload(buffer);
|
|
1429
|
+
for (const chunk of chunks) {
|
|
1430
|
+
if (!this._sendV2Chunk(requestId, chunk)) {
|
|
1431
|
+
// Send failed, abort response
|
|
1432
|
+
this.log.error('Failed to send v2 chunk, aborting response', { requestId });
|
|
1433
|
+
this.activeV2Responses.delete(requestId);
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
buffer = Buffer.alloc(0);
|
|
1438
|
+
};
|
|
1439
|
+
|
|
1440
|
+
proxyRes.on('data', (chunk) => {
|
|
1441
|
+
// CRT-Relay-E: Update activity on HTTP response data
|
|
1442
|
+
this.lastActivityMs = Date.now();
|
|
1443
|
+
|
|
1444
|
+
// Accumulate chunk
|
|
1445
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
1446
|
+
|
|
1447
|
+
// Flush when buffer reaches target chunk size
|
|
1448
|
+
if (buffer.length >= HTTPWS_V2_TARGET_CHUNK_BYTES) {
|
|
1449
|
+
flushBuffer();
|
|
1450
|
+
}
|
|
1451
|
+
});
|
|
1452
|
+
|
|
1453
|
+
proxyRes.on('end', () => {
|
|
1454
|
+
// CRT-Relay-E: Update activity on HTTP response end
|
|
1455
|
+
this.lastActivityMs = Date.now();
|
|
1456
|
+
|
|
1457
|
+
// Flush any remaining data
|
|
1458
|
+
flushBuffer();
|
|
1459
|
+
|
|
1460
|
+
// S-1: Send http_response_end
|
|
1461
|
+
const responseEnd = {
|
|
1462
|
+
type: 'http_response_end',
|
|
1463
|
+
rid: requestId
|
|
1464
|
+
};
|
|
1465
|
+
|
|
1466
|
+
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
1467
|
+
this.ws.send(JSON.stringify(responseEnd));
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
// Clean up tracking
|
|
1471
|
+
this.activeV2Responses.delete(requestId);
|
|
1472
|
+
});
|
|
1473
|
+
|
|
1474
|
+
proxyRes.on('error', (error) => {
|
|
1475
|
+
this.log.error('Error in v2 response stream', { requestId, error: error.message });
|
|
1476
|
+
this.activeV2Responses.delete(requestId);
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
// S-1: Handle v1 single-frame response (existing behavior)
|
|
1481
|
+
_handleV1Response(proxyRes, requestId) {
|
|
1482
|
+
const responseChunks = [];
|
|
1483
|
+
let bufferedBytes = 0;
|
|
1484
|
+
|
|
1485
|
+
proxyRes.on('data', (chunk) => {
|
|
1486
|
+
responseChunks.push(chunk);
|
|
1487
|
+
bufferedBytes += chunk.length;
|
|
1488
|
+
|
|
1489
|
+
// S-1: If buffering for v1 crosses 8 MiB, abort and retry as v2
|
|
1490
|
+
if (bufferedBytes >= V2_THRESHOLD_BYTES && this._canUseV2()) {
|
|
1491
|
+
this.log.warn('V1 response exceeded 8 MiB threshold, aborting', { requestId, bufferedBytes });
|
|
1492
|
+
// Note: In a real implementation, we'd need to abort the proxyRes stream
|
|
1493
|
+
// For now, we'll continue with v1 but log the issue
|
|
1494
|
+
// This is a limitation - we can't easily switch mid-stream
|
|
1495
|
+
}
|
|
1496
|
+
});
|
|
1497
|
+
|
|
1498
|
+
proxyRes.on('end', () => {
|
|
1499
|
+
// CRT-Relay-E: Update activity on HTTP response
|
|
1500
|
+
this.lastActivityMs = Date.now();
|
|
1501
|
+
|
|
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
|
+
|
|
1507
|
+
const responseData = {
|
|
1508
|
+
t: 'http_response',
|
|
1509
|
+
rid: requestId, // Use the same rid from the request
|
|
1510
|
+
s: proxyRes.statusCode,
|
|
1511
|
+
h: headerArray,
|
|
1512
|
+
b: bodyBase64
|
|
1513
|
+
};
|
|
1514
|
+
|
|
1515
|
+
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
1516
|
+
this.ws.send(JSON.stringify(responseData));
|
|
1517
|
+
}
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1278
1521
|
close() {
|
|
1279
1522
|
// CLI-IMG-WSReconnect: Disable reconnects and clear timer
|
|
1280
1523
|
this.shouldReconnect = false;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP-WS v2 Protocol Constants
|
|
3
|
+
*
|
|
4
|
+
* These constants define the authoritative values for HTTP-WS v2 protocol
|
|
5
|
+
* implementation. They must match the values used by the relay server.
|
|
6
|
+
*
|
|
7
|
+
* @see relay/src/httpws-constants.js
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
// S-3: Protocol constants alignment
|
|
11
|
+
export const HTTPWS_V2_TARGET_CHUNK_BYTES = 65_536; // 64 KiB target chunk size
|
|
12
|
+
export const HTTPWS_V2_MAX_CHUNK_BYTES = 262_144; // 256 KiB hard maximum chunk size
|
|
13
|
+
export const HTTPWS_V2_PROTOCOL_ERROR_CLOSE_CODE = 1002; // WebSocket close code for protocol errors
|
|
14
|
+
export const HTTPWS_V2_PROTOCOL_ERROR_REASON = 'httpws_v2_without_negotiation'; // Close reason string
|
|
15
|
+
export const HTTP_BODY_CHUNK = 0x20; // Frame type for HTTP body chunks (v2)
|
|
16
|
+
|