@torrent-tv/proxy 2.107.68 → 2.107.70
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 +3 -4
- package/package.json +1 -1
- package/routes/encode-input/get.js +10 -8
- package/routes/media/get.js +14 -31
- package/routes/stream/get.js +21 -30
- package/services/server/byte-range-reply.js +68 -0
- package/services/transport/data-channel-handler.js +22 -47
- package/services/transport/loopback-forward.js +83 -0
- package/services/transport/tunnel-client.js +0 -93
- package/utils/parse-range.js +41 -17
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
|
|
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
|
|
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
|
|
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,5 +1,6 @@
|
|
|
1
1
|
import { parseRange } from "../../utils/parse-range.js";
|
|
2
2
|
import { Readable } from "node:stream";
|
|
3
|
+
import { replyHead, replyUnsatisfiable } from "../../services/server/byte-range-reply.js";
|
|
3
4
|
|
|
4
5
|
/** FFmpeg reads only original byte ranges already owned by its live run. */
|
|
5
6
|
export async function handleEncodeInputGet(req, reply, { inputOf, refused = () => {}, noteFirstInputBytes = () => {} }) {
|
|
@@ -10,16 +11,17 @@ export async function handleEncodeInputGet(req, reply, { inputOf, refused = () =
|
|
|
10
11
|
const input = inputOf(token);
|
|
11
12
|
const length = input?.lengthOf(fileIndex);
|
|
12
13
|
if (!Number.isSafeInteger(length) || length <= 0) return reply.code(404).send();
|
|
13
|
-
reply.header("Accept-Ranges", "bytes");
|
|
14
|
-
reply.header("Content-Type", "application/octet-stream");
|
|
15
14
|
if (req.method === "HEAD") {
|
|
16
|
-
reply
|
|
17
|
-
reply.raw.writeHead(200, { "Accept-Ranges": "bytes", "Content-Type": "application/octet-stream", "Content-Length": String(length) });
|
|
18
|
-
reply.raw.end();
|
|
19
|
-
return;
|
|
15
|
+
return replyHead(reply, { "Accept-Ranges": "bytes", "Content-Type": "application/octet-stream", "Content-Length": String(length) });
|
|
20
16
|
}
|
|
21
|
-
const
|
|
22
|
-
if (
|
|
17
|
+
const parsed = parseRange(req.headers.range, length);
|
|
18
|
+
if (parsed.kind === "unsatisfiable") return replyUnsatisfiable(reply, length);
|
|
19
|
+
reply.header("Accept-Ranges", "bytes");
|
|
20
|
+
reply.header("Content-Type", "application/octet-stream");
|
|
21
|
+
// No range (FFmpeg always sends one), several, or one that is not valid is
|
|
22
|
+
// read as from byte 0. The answer is 206 whatever the request: it runs to the
|
|
23
|
+
// end of the admitted range (`held.end`), never to the end of the file.
|
|
24
|
+
const range = parsed.kind === "range" ? parsed : { start: 0, end: length - 1 };
|
|
23
25
|
// The answer runs to the end of the admitted range the read starts in, which
|
|
24
26
|
// is what keeps FFmpeg inside the bytes the run holds. A shorter answer is
|
|
25
27
|
// not continued by every FFmpeg: measured, 8.1.2 and 9.0.2 send a new
|
package/routes/media/get.js
CHANGED
|
@@ -1,19 +1,6 @@
|
|
|
1
1
|
import { Readable } from "node:stream";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
if (!header) return { start: 0, end: length - 1 };
|
|
5
|
-
const match = /^bytes=(\d*)-(\d*)$/.exec(header);
|
|
6
|
-
if (!match || (!match[1] && !match[2])) return null;
|
|
7
|
-
if (!match[1]) {
|
|
8
|
-
const suffix = Number(match[2]);
|
|
9
|
-
if (!Number.isSafeInteger(suffix) || suffix <= 0) return null;
|
|
10
|
-
return { start: Math.max(0, length - suffix), end: length - 1 };
|
|
11
|
-
}
|
|
12
|
-
const start = Number(match[1]);
|
|
13
|
-
const end = match[2] ? Number(match[2]) : length - 1;
|
|
14
|
-
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start >= length || end < start) return null;
|
|
15
|
-
return { start, end: Math.min(end, length - 1) };
|
|
16
|
-
}
|
|
2
|
+
import { parseRange } from "../../utils/parse-range.js";
|
|
3
|
+
import { rangeHeaders, replyHead, replyUnsatisfiable } from "../../services/server/byte-range-reply.js";
|
|
17
4
|
|
|
18
5
|
/** Serve existing downloaded bytes without creating source demand. */
|
|
19
6
|
export async function handleMediaGet(req, reply, { torrentPool, onMissing = () => {} }) {
|
|
@@ -28,22 +15,21 @@ export async function handleMediaGet(req, reply, { torrentPool, onMissing = () =
|
|
|
28
15
|
if (!file || !(file.length > 0)) {
|
|
29
16
|
return reply.code(404).send({ error: "Media file is not available." });
|
|
30
17
|
}
|
|
31
|
-
const rangeHeader = req.headers?.range;
|
|
32
|
-
const range = mediaRange(rangeHeader, file.length);
|
|
33
|
-
if (!range || range.start >= file.length) {
|
|
34
|
-
reply.header("Content-Range", `bytes */${file.length}`);
|
|
35
|
-
return reply.code(416).send({ error: "Invalid media byte range." });
|
|
36
|
-
}
|
|
37
18
|
const portion = Number(torrent.pieceLength);
|
|
38
19
|
if (!Number.isSafeInteger(portion) || portion <= 0) {
|
|
39
20
|
return reply.code(500).send({ error: "Source piece length is unavailable." });
|
|
40
21
|
}
|
|
41
22
|
if (req.method === "HEAD") {
|
|
42
|
-
reply
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
23
|
+
return replyHead(reply, {
|
|
24
|
+
"Accept-Ranges": "bytes",
|
|
25
|
+
"Content-Type": "application/octet-stream",
|
|
26
|
+
"Content-Length": String(file.length)
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
// Range applies to GET only (RFC 9110 §14.2): HEAD answered above ignores it.
|
|
30
|
+
const parsed = parseRange(req.headers?.range, file.length);
|
|
31
|
+
if (parsed.kind === "unsatisfiable") return replyUnsatisfiable(reply, file.length);
|
|
32
|
+
const range = parsed.kind === "range" ? parsed : { start: 0, end: file.length - 1 };
|
|
47
33
|
const missing = (start, end) => {
|
|
48
34
|
onMissing({ sourceKey, fileIndex, start, end, requestId: req.query?.readId ?? req.id });
|
|
49
35
|
const error = new Error(`Media bytes ${start}-${end} have not arrived.`);
|
|
@@ -59,12 +45,9 @@ export async function handleMediaGet(req, reply, { torrentPool, onMissing = () =
|
|
|
59
45
|
}
|
|
60
46
|
reply.header("Accept-Ranges", "bytes");
|
|
61
47
|
reply.header("Content-Type", "application/octet-stream");
|
|
62
|
-
reply.header("Content-Length", String(range.end - range.start + 1));
|
|
63
48
|
reply.header("Cache-Control", "no-store");
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
reply.header("Content-Range", `bytes ${range.start}-${range.end}/${file.length}`);
|
|
67
|
-
}
|
|
49
|
+
reply.code(parsed.kind === "range" ? 206 : 200);
|
|
50
|
+
reply.headers(rangeHeaders(parsed, file.length));
|
|
68
51
|
async function* bytes() {
|
|
69
52
|
yield first;
|
|
70
53
|
for (let start = firstEnd + 1; start <= range.end;) {
|
package/routes/stream/get.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
import { open } from "node:fs/promises";
|
|
10
10
|
import { Readable } from "node:stream";
|
|
11
11
|
import { parseRange } from "../../utils/parse-range.js";
|
|
12
|
+
import { rangeHeaders, replyHead, replyUnsatisfiable, writeRawHead } from "../../services/server/byte-range-reply.js";
|
|
12
13
|
import { logger } from "../../utils/logger.js";
|
|
13
14
|
|
|
14
15
|
/**
|
|
@@ -197,29 +198,28 @@ async function writeFromWholeFile(raw, read, from, end, onWritten) {
|
|
|
197
198
|
*/
|
|
198
199
|
function serveWholeFile(req, reply, file, read) {
|
|
199
200
|
const disposition = `inline; filename*=UTF-8''${encodeURIComponent(file.name)}`;
|
|
201
|
+
const range = parseRange(req.headers.range, file.length);
|
|
202
|
+
if (range.kind === "unsatisfiable") {
|
|
203
|
+
void read.release().catch(() => undefined);
|
|
204
|
+
return replyUnsatisfiable(reply, file.length);
|
|
205
|
+
}
|
|
200
206
|
reply.header("Accept-Ranges", "bytes");
|
|
201
207
|
reply.header("Content-Type", "application/octet-stream");
|
|
202
208
|
reply.header("Content-Disposition", disposition);
|
|
203
|
-
const range = parseRange(req.headers.range, file.length);
|
|
204
209
|
if (file.length === 0) {
|
|
205
210
|
reply.header("Content-Length", "0");
|
|
206
211
|
void read.release().catch(() => undefined);
|
|
207
212
|
return reply.send(Readable.from([]));
|
|
208
213
|
}
|
|
209
|
-
const start = range
|
|
210
|
-
const end = range
|
|
214
|
+
const start = range.kind === "range" ? range.start : 0;
|
|
215
|
+
const end = range.kind === "range" ? range.end : file.length - 1;
|
|
211
216
|
const stream = read.stream(start, end, () => {});
|
|
212
217
|
if (!stream) {
|
|
213
218
|
void read.release().catch(() => undefined);
|
|
214
219
|
return null;
|
|
215
220
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
} else {
|
|
219
|
-
reply.code(206);
|
|
220
|
-
reply.header("Content-Length", String(end - start + 1));
|
|
221
|
-
reply.header("Content-Range", `bytes ${start}-${end}/${file.length}`);
|
|
222
|
-
}
|
|
221
|
+
reply.code(range.kind === "range" ? 206 : 200);
|
|
222
|
+
reply.headers(rangeHeaders(range, file.length));
|
|
223
223
|
void read.release().catch(() => undefined);
|
|
224
224
|
try {
|
|
225
225
|
return reply.send(stream);
|
|
@@ -260,15 +260,12 @@ export async function handleStreamGet(req, reply, { sourceRegistry, torrentPool,
|
|
|
260
260
|
}
|
|
261
261
|
if (handle) {
|
|
262
262
|
await handle.close();
|
|
263
|
-
reply
|
|
264
|
-
reply.raw.writeHead(200, {
|
|
263
|
+
return replyHead(reply, {
|
|
265
264
|
"Accept-Ranges": "bytes",
|
|
266
265
|
"Content-Type": "application/octet-stream",
|
|
267
266
|
"Content-Length": String(whole.length),
|
|
268
267
|
"Content-Disposition": `inline; filename*=UTF-8''${encodeURIComponent(whole.name)}`
|
|
269
268
|
});
|
|
270
|
-
reply.raw.end();
|
|
271
|
-
return;
|
|
272
269
|
}
|
|
273
270
|
} else {
|
|
274
271
|
const read = await acquireWholeFileRead(torrentPool, sourceKey, fileIndex, whole.length);
|
|
@@ -306,26 +303,22 @@ export async function handleStreamGet(req, reply, { sourceRegistry, torrentPool,
|
|
|
306
303
|
// returned headers in 23 ms and then held the connection until its 15 s
|
|
307
304
|
// timeout, which is where the 73 s transcode-session create went.
|
|
308
305
|
if (req.method === "HEAD") {
|
|
309
|
-
//
|
|
310
|
-
//
|
|
311
|
-
|
|
312
|
-
// very request and treats 0 as "no index available", silently falling back
|
|
313
|
-
// to an invented segment grid. Hijacking leaves the response to us, and
|
|
314
|
-
// Node omits the body for HEAD by itself.
|
|
315
|
-
reply.hijack();
|
|
316
|
-
reply.raw.writeHead(200, {
|
|
306
|
+
// The keyframe index asks for the file size with this very request, so
|
|
307
|
+
// the answer must keep the true length: see `replyHead`.
|
|
308
|
+
return replyHead(reply, {
|
|
317
309
|
"Accept-Ranges": "bytes",
|
|
318
310
|
"Content-Type": "application/octet-stream",
|
|
319
311
|
"Content-Length": String(file.length),
|
|
320
312
|
"Content-Disposition": `inline; filename*=UTF-8''${encodeURIComponent(file.name)}`
|
|
321
313
|
});
|
|
322
|
-
reply.raw.end();
|
|
323
|
-
return;
|
|
324
314
|
}
|
|
325
315
|
|
|
326
316
|
const range = parseRange(req.headers.range, file.length);
|
|
327
|
-
|
|
328
|
-
|
|
317
|
+
if (range.kind === "unsatisfiable") {
|
|
318
|
+
return replyUnsatisfiable(reply, file.length);
|
|
319
|
+
}
|
|
320
|
+
const start = range.kind === "range" ? range.start : 0;
|
|
321
|
+
const end = range.kind === "range" ? range.end : file.length - 1;
|
|
329
322
|
const contentLength = end - start + 1;
|
|
330
323
|
|
|
331
324
|
// Written straight out of the torrent's shared memory when that is available:
|
|
@@ -348,13 +341,11 @@ export async function handleStreamGet(req, reply, { sourceRegistry, torrentPool,
|
|
|
348
341
|
: null;
|
|
349
342
|
|
|
350
343
|
if (fragments) {
|
|
351
|
-
reply.
|
|
352
|
-
reply.raw.writeHead(range ? 206 : 200, {
|
|
344
|
+
writeRawHead(reply, range.kind === "range" ? 206 : 200, {
|
|
353
345
|
"Accept-Ranges": "bytes",
|
|
354
346
|
"Content-Type": "application/octet-stream",
|
|
355
|
-
"Content-Length": String(contentLength),
|
|
356
347
|
"Content-Disposition": `inline; filename*=UTF-8''${encodeURIComponent(file.name)}`,
|
|
357
|
-
...(range
|
|
348
|
+
...rangeHeaders(range, file.length)
|
|
358
349
|
});
|
|
359
350
|
|
|
360
351
|
// A client that goes away mid-response must stop the read, or pieces keep
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The one way the proxy's HTTP routes answer a byte-range request, for
|
|
3
|
+
* a range read by `utils/parse-range.js`. Every answer keeps the headers set
|
|
4
|
+
* by hooks (`@fastify/cors`, `Access-Control-Allow-Private-Network`).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { Readable } from "node:stream";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Headers for a `whole` or `range` result: `Content-Length`, and
|
|
11
|
+
* `Content-Range` for a range.
|
|
12
|
+
*
|
|
13
|
+
* @param {{ kind: "whole" } | { kind: "range", start: number, end: number }} range
|
|
14
|
+
* @param {number} length - Size of the representation in bytes.
|
|
15
|
+
* @returns {Record<string, string>}
|
|
16
|
+
*/
|
|
17
|
+
export function rangeHeaders(range, length) {
|
|
18
|
+
if (range.kind !== "range") return { "Content-Length": String(length) };
|
|
19
|
+
return {
|
|
20
|
+
"Content-Length": String(range.end - range.start + 1),
|
|
21
|
+
"Content-Range": `bytes ${range.start}-${range.end}/${length}`
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Answer 416 for an unsatisfiable range, through `reply.send` so hook headers stay.
|
|
27
|
+
*
|
|
28
|
+
* @param {import("fastify").FastifyReply} reply
|
|
29
|
+
* @param {number} length - Size of the representation in bytes.
|
|
30
|
+
*/
|
|
31
|
+
export function replyUnsatisfiable(reply, length) {
|
|
32
|
+
return reply.code(416).header("Content-Range", `bytes */${length}`)
|
|
33
|
+
.send({ error: "The requested byte range is not satisfiable." });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Answer HEAD with 200 and `headers`, which carry the true `Content-Length`.
|
|
38
|
+
*
|
|
39
|
+
* The payload is an EMPTY STREAM, not nothing: for a payload of `undefined`
|
|
40
|
+
* the HEAD route Fastify generates from a GET sets `content-length: 0`, and
|
|
41
|
+
* the keyframe index asks for the file size with this very request and reads
|
|
42
|
+
* 0 as "no index available". An explicit length is left alone for a stream.
|
|
43
|
+
*
|
|
44
|
+
* @param {import("fastify").FastifyReply} reply
|
|
45
|
+
* @param {Record<string, string>} headers
|
|
46
|
+
*/
|
|
47
|
+
export function replyHead(reply, headers) {
|
|
48
|
+
return reply.code(200).headers(headers).send(Readable.from([]));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The one raw head write: the response is taken from Fastify and its head is
|
|
53
|
+
* written from the headers already set on `reply` (hook headers included)
|
|
54
|
+
* plus `headers`. Only for an answer whose body is written by hand, where
|
|
55
|
+
* only a write callback says when a piece may be released.
|
|
56
|
+
*
|
|
57
|
+
* @param {import("fastify").FastifyReply} reply
|
|
58
|
+
* @param {number} status
|
|
59
|
+
* @param {Record<string, string>} headers
|
|
60
|
+
*/
|
|
61
|
+
export function writeRawHead(reply, status, headers) {
|
|
62
|
+
// Keyed in lower case, as `getHeaders()` keys them, so that a header named
|
|
63
|
+
// in both is written once, with the value given here.
|
|
64
|
+
const head = { ...reply.getHeaders() };
|
|
65
|
+
for (const [name, value] of Object.entries(headers)) head[name.toLowerCase()] = value;
|
|
66
|
+
reply.hijack();
|
|
67
|
+
reply.raw.writeHead(status, head);
|
|
68
|
+
}
|
|
@@ -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 {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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 >
|
|
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 >
|
|
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
|
-
*
|
|
1166
|
-
*
|
|
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
|
|
1230
|
+
response = await forwardToLoopback({
|
|
1231
|
+
port: proxyPort,
|
|
1232
|
+
requestId,
|
|
1238
1233
|
method,
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
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.
|
package/utils/parse-range.js
CHANGED
|
@@ -1,25 +1,49 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file HTTP Range header
|
|
2
|
+
* @file The one reading of an HTTP `Range` header (RFC 9110 §14.1.2, §14.2;
|
|
3
|
+
* one range only).
|
|
3
4
|
*/
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
|
-
*
|
|
7
|
-
|
|
7
|
+
* @typedef {{ kind: "whole" } | { kind: "range", start: number, end: number } | { kind: "unsatisfiable" }} ParsedRange
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const WHOLE = Object.freeze({ kind: "whole" });
|
|
11
|
+
const UNSATISFIABLE = Object.freeze({ kind: "unsatisfiable" });
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Read a `Range` header against the length of the representation it asks for.
|
|
8
15
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
16
|
+
* - `whole`: no header, another unit, several ranges, or invalid syntax — the
|
|
17
|
+
* header is ignored, as RFC 9110 allows.
|
|
18
|
+
* - `range`: one inclusive range, `0 <= start <= end <= length - 1`; an end
|
|
19
|
+
* past the last byte is clamped, `bytes=-N` is the last N bytes.
|
|
20
|
+
* - `unsatisfiable`: a valid range that holds no byte of the representation.
|
|
21
|
+
*
|
|
22
|
+
* @param {unknown} header - Value of the `Range` request header.
|
|
23
|
+
* @param {number} length - Size of the representation in bytes (a non-negative safe integer).
|
|
24
|
+
* @returns {ParsedRange}
|
|
13
25
|
*/
|
|
14
|
-
export function parseRange(
|
|
15
|
-
if (
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
26
|
+
export function parseRange(header, length) {
|
|
27
|
+
if (typeof header !== "string") return WHOLE;
|
|
28
|
+
const equals = header.indexOf("=");
|
|
29
|
+
if (equals < 0) return WHOLE;
|
|
30
|
+
if (header.slice(0, equals).trim().toLowerCase() !== "bytes") return WHOLE;
|
|
31
|
+
const spec = header.slice(equals + 1).trim();
|
|
32
|
+
if (spec.includes(",")) return WHOLE;
|
|
33
|
+
const match = /^(\d*)-(\d*)$/.exec(spec);
|
|
34
|
+
if (!match || (!match[1] && !match[2])) return WHOLE;
|
|
35
|
+
|
|
36
|
+
if (!match[1]) {
|
|
37
|
+
const suffix = Number(match[2]);
|
|
38
|
+
if (!Number.isSafeInteger(suffix)) return WHOLE;
|
|
39
|
+
if (suffix === 0 || length === 0) return UNSATISFIABLE;
|
|
40
|
+
return { kind: "range", start: Math.max(0, length - suffix), end: length - 1 };
|
|
23
41
|
}
|
|
24
|
-
|
|
42
|
+
|
|
43
|
+
const start = Number(match[1]);
|
|
44
|
+
const end = match[2] ? Number(match[2]) : null;
|
|
45
|
+
if (!Number.isSafeInteger(start) || (end !== null && !Number.isSafeInteger(end))) return WHOLE;
|
|
46
|
+
if (end !== null && end < start) return WHOLE;
|
|
47
|
+
if (start >= length) return UNSATISFIABLE;
|
|
48
|
+
return { kind: "range", start, end: end === null ? length - 1 : Math.min(end, length - 1) };
|
|
25
49
|
}
|