@torrent-tv/proxy 2.107.68 → 2.107.69

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 CHANGED
@@ -7,7 +7,7 @@ A lightweight Node.js service that streams torrent content to browsers via a dir
7
7
  - Browsers cannot consume torrents directly.
8
8
  - This service exposes torrent files through HTTP (`/stream`) with Range support, and through a WebRTC data channel for NAT-traversed streaming.
9
9
  - It can transcode audio (or video + audio) to HLS on demand so the browser can always play the content regardless of codec support.
10
- - It registers itself in an external registry server and maintains a persistent tunnel WebSocket so the server can route browser requests and WebRTC signals to it.
10
+ - It registers itself in an external registry server and maintains a persistent tunnel WebSocket so the server can route WebRTC signals to it. Browser requests reach the proxy only over the WebRTC data channel.
11
11
 
12
12
  ## Architecture Overview
13
13
 
@@ -58,13 +58,12 @@ graph TB
58
58
  Opens one persistent WebSocket to the registry server's `/ws/proxy-tunnel` endpoint on startup.
59
59
  Reconnects automatically with back-off on unexpected close.
60
60
 
61
- Handles three inbound message types from the server:
61
+ Handles these inbound message types from the server (any other type is ignored):
62
62
 
63
63
  | Message type | What the proxy does |
64
64
  |---|---|
65
65
  | `health-request` | Calls `HealthCollector`, sends `health-response` back through tunnel |
66
66
  | `signal` | Forwards SDP offer or ICE candidate to `WebRtcManager` |
67
- | `relay-request` | Fetches the path from local Fastify, streams `relay-response` back |
68
67
 
69
68
  ### WebRtcManager
70
69
 
@@ -93,7 +92,7 @@ sequenceDiagram
93
92
 
94
93
  ### DataChannelHandler
95
94
 
96
- Receives JSON `request` messages over the data channel and dispatches them to the proxy's local Fastify server. Responses are streamed back as base64 `response-chunk` messages.
95
+ Receives JSON `request` messages over the data channel and forwards them to the proxy's local Fastify server through `services/transport/loopback-forward.js`, the one place a relayed request becomes a loopback HTTP call: it refuses paths outside the browser routes (`/api/*`, `/stream`, `/transcode/*`, `/health(z)`) and bodies over 32 MiB before opening a connection. Responses are streamed back as base64 `response-chunk` messages.
97
96
 
98
97
  **Wire protocol (browser ↔ proxy):**
99
98
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.107.68",
3
+ "version": "2.107.69",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -39,18 +39,17 @@
39
39
  * ```
40
40
  * Control messages stay JSON strings so the browser can distinguish them from
41
41
  * body frames by message type (string vs ArrayBuffer).
42
- *
43
- * The protocol mirrors the tunnel relay protocol so both transports share
44
- * the same mental model and the same browser-side `WebRtcProxy` implementation.
45
42
  */
46
43
 
47
44
  /** @import { DataChannel } from 'node-datachannel' */
48
45
 
49
46
  import { createDeliveryProbe, PROBE_INTERVAL_MS } from "./delivery-probe.js";
50
- import { Agent } from "undici";
51
-
52
- // Route availability and caller cancellation determine media request lifetime.
53
- const loopbackDispatcher = new Agent({ headersTimeout: 0, bodyTimeout: 0 });
47
+ import {
48
+ forwardToLoopback,
49
+ isValidRequestPath,
50
+ LoopbackRefusal,
51
+ MAX_REQUEST_BODY_BYTES
52
+ } from "./loopback-forward.js";
54
53
 
55
54
  /**
56
55
  * Configuration for the data channel handler.
@@ -985,7 +984,7 @@ export function createDataChannelHandler({
985
984
  send(channel, { type: "response-error", requestId, error: "Invalid request path." });
986
985
  return;
987
986
  }
988
- if (!Number.isInteger(bodyBytes) || bodyBytes < 0 || bodyBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
987
+ if (!Number.isInteger(bodyBytes) || bodyBytes < 0 || bodyBytes > MAX_REQUEST_BODY_BYTES) {
989
988
  send(channel, { type: "response-error", requestId, error: "Request body too large." });
990
989
  return;
991
990
  }
@@ -1034,7 +1033,7 @@ export function createDataChannelHandler({
1034
1033
  entry.chunks.push(Buffer.from(payload));
1035
1034
  entry.receivedBytes += payload.length;
1036
1035
  }
1037
- if (entry.receivedBytes > entry.bodyBytes || entry.receivedBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
1036
+ if (entry.receivedBytes > entry.bodyBytes || entry.receivedBytes > MAX_REQUEST_BODY_BYTES) {
1038
1037
  dropPartial(requestId);
1039
1038
  send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
1040
1039
  return;
@@ -1162,8 +1161,9 @@ export function createDataChannelHandler({
1162
1161
  * Fetch a resource from the local proxy HTTP server and stream the response
1163
1162
  * back to the browser over the data channel.
1164
1163
  *
1165
- * The `Host` header is rewritten to `127.0.0.1:{proxyPort}` so that Fastify
1166
- * routes the request correctly regardless of what the browser sent.
1164
+ * `forwardToLoopback` refuses paths outside the browser routes and oversized
1165
+ * bodies, and rewrites the `Host` header to `127.0.0.1:{proxyPort}` so that
1166
+ * Fastify routes the request correctly regardless of what the browser sent.
1167
1167
  *
1168
1168
  * @param {DataChannel} channel
1169
1169
  * @param {DataChannelRequest} req
@@ -1214,13 +1214,6 @@ export function createDataChannelHandler({
1214
1214
  : "";
1215
1215
  log(`[dc] ${method} ${path}${queryInfo}${bodyInfo}`);
1216
1216
 
1217
- const targetUrl = `http://127.0.0.1:${proxyPort}${path}${query ? `?${query}` : ""}`;
1218
- const requestHeaders = {
1219
- ...(forwardedHeaders ?? {}),
1220
- host: `127.0.0.1:${proxyPort}`,
1221
- "x-ttv-forwarded-request-id": requestId
1222
- };
1223
-
1224
1217
  let response;
1225
1218
  // [net-debug] TEMPORARY: time spent in the local fetch (waiting for the
1226
1219
  // route to return a response — e.g. long-polling until an HLS segment is
@@ -1234,15 +1227,21 @@ export function createDataChannelHandler({
1234
1227
  `atMs=${fetchStartedAtMonotonic.toFixed(3)}`);
1235
1228
  }
1236
1229
  try {
1237
- response = await fetch(targetUrl, {
1230
+ response = await forwardToLoopback({
1231
+ port: proxyPort,
1232
+ requestId,
1238
1233
  method,
1239
- headers: requestHeaders,
1240
- body: body != null ? body : undefined,
1241
- redirect: "manual",
1242
- dispatcher: loopbackDispatcher,
1234
+ path,
1235
+ query,
1236
+ headers: forwardedHeaders,
1237
+ body,
1243
1238
  signal
1244
1239
  });
1245
1240
  } catch (fetchError) {
1241
+ if (fetchError instanceof LoopbackRefusal) {
1242
+ send(channel, { type: "response-error", requestId, error: fetchError.message });
1243
+ return;
1244
+ }
1246
1245
  if (signal.aborted) return;
1247
1246
  log(`[dc] ${method} ${path}${queryInfo} → error: ${fetchError?.message ?? String(fetchError)}`);
1248
1247
  send(channel, { type: "response-error", requestId, error: fetchError?.message ?? String(fetchError) });
@@ -1508,30 +1507,6 @@ export function createDataChannelHandler({
1508
1507
  };
1509
1508
  }
1510
1509
 
1511
- /**
1512
- * Allowed path prefixes for data-channel requests.
1513
- * Only the known proxy API and streaming routes are accepted.
1514
- */
1515
- const PATH_ALLOWLIST_RE = /^(?:\/api\/|\/stream(?:$|\?)|\/?transcode\/|\/health(?:z)?(?:$|\?))/;
1516
-
1517
- /**
1518
- * True when `path` is an absolute, traversal-free path on a known proxy route.
1519
- * Shared by the single-message and chunked request entry points.
1520
- *
1521
- * @param {unknown} path
1522
- * @returns {boolean}
1523
- */
1524
- function isValidRequestPath(path) {
1525
- return (
1526
- typeof path === "string" &&
1527
- path.startsWith("/") &&
1528
- !path.includes("..") &&
1529
- PATH_ALLOWLIST_RE.test(path)
1530
- );
1531
- }
1532
-
1533
- /** Max assembled size of a chunked request body (guards proxy memory). */
1534
- const PROXY_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024;
1535
1510
  /** Drop an incomplete chunked body if no further frame arrives within this window. */
1536
1511
  const PARTIAL_REQUEST_TTL_MS = 60_000;
1537
1512
 
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @file The one place a relayed request becomes an HTTP call to the proxy's own
3
+ * Fastify server on 127.0.0.1.
4
+ *
5
+ * Every forwarded request arrives at the local server from the loopback
6
+ * address, so routes that trust loopback callers (`/encode-input/*`, `/media`)
7
+ * would accept it. The path allowlist and the body cap here keep a relayed
8
+ * request to the routes the browser uses and to a bounded size, and both are
9
+ * checked before any connection is opened.
10
+ */
11
+
12
+ import { Agent } from "undici";
13
+
14
+ /** Max size of a forwarded request body, in bytes (32 MiB). */
15
+ export const MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024;
16
+
17
+ /**
18
+ * The routes the browser uses: /api/*, /stream, /transcode/*, /health, /healthz.
19
+ * See docs/browser-proxy-contract.md.
20
+ */
21
+ const PATH_ALLOWLIST_RE = /^(?:\/api\/|\/stream(?:$|\?)|\/?transcode\/|\/health(?:z)?(?:$|\?))/;
22
+
23
+ // Route availability and caller cancellation determine media request lifetime:
24
+ // a held segment request waits for ffmpeg as long as the route says, so undici
25
+ // must not cut it off with its default 300 s header or body timeout.
26
+ const loopbackDispatcher = new Agent({ headersTimeout: 0, bodyTimeout: 0 });
27
+
28
+ /**
29
+ * True when `path` is an absolute, traversal-free path on a browser route.
30
+ *
31
+ * @param {unknown} path
32
+ * @returns {boolean}
33
+ */
34
+ export function isValidRequestPath(path) {
35
+ return (
36
+ typeof path === "string" &&
37
+ path.startsWith("/") &&
38
+ !path.includes("..") &&
39
+ PATH_ALLOWLIST_RE.test(path)
40
+ );
41
+ }
42
+
43
+ /** Thrown before any connection is opened when a request is refused. */
44
+ export class LoopbackRefusal extends Error {
45
+ /** @param {string} message */
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = "LoopbackRefusal";
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Forward one relayed request to the local proxy server.
54
+ *
55
+ * @param {object} request
56
+ * @param {number} request.port local Fastify port
57
+ * @param {string} request.requestId sent as x-ttv-forwarded-request-id
58
+ * @param {string} request.method
59
+ * @param {string} request.path
60
+ * @param {string} [request.query] without the leading "?"
61
+ * @param {Record<string, string>} [request.headers]
62
+ * @param {string | Buffer | null} [request.body]
63
+ * @param {AbortSignal} request.signal
64
+ * @returns {Promise<Response>} the undici fetch Response, unread
65
+ */
66
+ export async function forwardToLoopback({ port, requestId, method, path, query, headers, body, signal }) {
67
+ if (!isValidRequestPath(path)) throw new LoopbackRefusal("Invalid request path.");
68
+ if (body != null && Buffer.byteLength(body) > MAX_REQUEST_BODY_BYTES) {
69
+ throw new LoopbackRefusal("Request body too large.");
70
+ }
71
+ return fetch(`http://127.0.0.1:${port}${path}${query ? `?${query}` : ""}`, {
72
+ method,
73
+ headers: {
74
+ ...(headers ?? {}),
75
+ host: `127.0.0.1:${port}`,
76
+ "x-ttv-forwarded-request-id": requestId
77
+ },
78
+ body: body != null ? body : undefined,
79
+ redirect: "manual",
80
+ dispatcher: loopbackDispatcher,
81
+ signal
82
+ });
83
+ }
@@ -3,7 +3,6 @@
3
3
  *
4
4
  * The proxy opens one persistent connection on startup. Through it the
5
5
  * server can:
6
- * - relay browser HTTP requests to the proxy's local Fastify server, and
7
6
  * - forward WebRTC signalling messages (offers, ICE candidates) between
8
7
  * the browser and the proxy's WebRTC manager.
9
8
  *
@@ -65,19 +64,6 @@ import { WebSocket } from "ws";
65
64
  * @property {string} [mid] - SDP media ID associated with the candidate.
66
65
  */
67
66
 
68
- /**
69
- * A relay request sent by the server — asking the proxy to perform a local
70
- * HTTP fetch and stream the response back through the tunnel.
71
- *
72
- * @typedef {Object} TunnelRelayRequest
73
- * @property {string} requestId - Unique ID that ties request → response chunks.
74
- * @property {string} method - HTTP method (GET, POST, etc.).
75
- * @property {string} path - Request path on the local proxy (e.g. "/health").
76
- * @property {string} query - Raw query string without the leading "?".
77
- * @property {Record<string, string>} headers - Headers forwarded from the browser.
78
- * @property {string | null} body - Serialised request body, or null.
79
- */
80
-
81
67
  /**
82
68
  * The object returned by {@link createTunnelClient}.
83
69
  *
@@ -257,13 +243,6 @@ export function createTunnelClient({
257
243
  return;
258
244
  }
259
245
 
260
- if (message.type === "request") {
261
- void handleRelayRequest(message, connection).catch((error) => {
262
- log(`Tunnel relay error: ${error?.message ?? error}`);
263
- });
264
- return;
265
- }
266
-
267
246
  // WebRTC signalling: server forwards a signal from a browser session.
268
247
  if (message.type === "signal") {
269
248
  if (typeof message.sessionId === "string" && message.signal && typeof onSignal === "function") {
@@ -369,66 +348,6 @@ export function createTunnelClient({
369
348
  }, RECONNECT_DELAY_MS);
370
349
  }
371
350
 
372
- /**
373
- * Fetch a resource from the local Fastify server and stream the response
374
- * back to the registry server chunk-by-chunk over the WebSocket.
375
- *
376
- * @param {TunnelRelayRequest} relayRequest
377
- * @param {WebSocket} over - The connection the request arrived on, which
378
- * the response goes back over.
379
- * @returns {Promise<void>}
380
- */
381
- async function handleRelayRequest(relayRequest, over) {
382
- const { requestId, method, path, query, headers: forwardedHeaders, body } = relayRequest;
383
- const targetUrl = `http://127.0.0.1:${proxyPort}${path}` + (query ? `?${query}` : "");
384
- const requestHeaders = { ...(forwardedHeaders ?? {}), host: `127.0.0.1:${proxyPort}` };
385
-
386
- let response;
387
- try {
388
- response = await fetch(targetUrl, {
389
- method,
390
- headers: requestHeaders,
391
- body: body != null ? body : undefined,
392
- redirect: "manual"
393
- });
394
- } catch (fetchError) {
395
- sendError(requestId, fetchError?.message ?? String(fetchError), over);
396
- return;
397
- }
398
-
399
- /** @type {Record<string, string>} */
400
- const responseHeaders = {};
401
- for (const [headerName, headerValue] of response.headers.entries()) {
402
- responseHeaders[headerName] = headerValue;
403
- }
404
-
405
- send({ type: "response-start", requestId, status: response.status, headers: responseHeaders }, over);
406
-
407
- if (!response.body) {
408
- send({ type: "response-chunk", requestId, data: "", done: true }, over);
409
- return;
410
- }
411
-
412
- try {
413
- const reader = response.body.getReader();
414
- while (true) {
415
- const { done, value } = await reader.read();
416
- if (done) {
417
- send({ type: "response-chunk", requestId, data: "", done: true }, over);
418
- break;
419
- }
420
- send({
421
- type: "response-chunk",
422
- requestId,
423
- data: Buffer.from(value).toString("base64"),
424
- done: false
425
- }, over);
426
- }
427
- } catch {
428
- send({ type: "response-chunk", requestId, data: "", done: true }, over);
429
- }
430
- }
431
-
432
351
  /**
433
352
  * Serialise a message to JSON and send it through the WebSocket if open.
434
353
  *
@@ -448,18 +367,6 @@ export function createTunnelClient({
448
367
  }
449
368
  }
450
369
 
451
- /**
452
- * Send a `response-error` frame for a given relay request.
453
- *
454
- * @param {string} requestId
455
- * @param {string} errorMessage
456
- * @param {WebSocket} over - The connection the request arrived on.
457
- * @returns {void}
458
- */
459
- function sendError(requestId, errorMessage, over) {
460
- send({ type: "response-error", requestId, error: errorMessage }, over);
461
- }
462
-
463
370
  return {
464
371
  /**
465
372
  * Start the tunnel. Connects immediately and auto-reconnects on drop.