@torrent-tv/proxy 2.107.69 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.107.69",
3
+ "version": "2.107.70",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -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.hijack();
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 range = parseRange(req.headers.range, length);
22
- if (!range || range.start >= length) return reply.code(416).header("Content-Range", `bytes */${length}`).send();
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
@@ -1,19 +1,6 @@
1
1
  import { Readable } from "node:stream";
2
-
3
- function mediaRange(header, length) {
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.header("Accept-Ranges", "bytes");
43
- reply.header("Content-Length", String(file.length));
44
- reply.header("Content-Type", "application/octet-stream");
45
- return reply.send();
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
- if (rangeHeader) {
65
- reply.code(206);
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;) {
@@ -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?.start ?? 0;
210
- const end = range?.end ?? file.length - 1;
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
- if (!range) {
217
- reply.header("Content-Length", String(file.length));
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.hijack();
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
- // Written to the raw response on purpose. Answering through `reply.send()`
310
- // with no payload makes Fastify set `content-length: 0`, which is worse
311
- // than useless here: the keyframe index asks for the file size with this
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
- const start = range ? range.start : 0;
328
- const end = range ? range.end : file.length - 1;
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.hijack();
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 ? { "Content-Range": `bytes ${start}-${end}/${file.length}` } : {})
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
+ }
@@ -1,25 +1,49 @@
1
1
  /**
2
- * @file HTTP Range header parser.
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
- * Parse an HTTP `Range` header value into a byte range clamped to the file size.
7
- * Only the `bytes=<start>-<end>` form is supported.
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
- * @param {string | undefined} rangeHeader - Value of the `Range` request header.
10
- * @param {number} fileLength - Total file size in bytes.
11
- * @returns {{ start: number, end: number } | null} Byte range, or `null` if the
12
- * header is absent, malformed, or uses an unsupported unit.
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(rangeHeader, fileLength) {
15
- if (!rangeHeader || !rangeHeader.startsWith("bytes=")) {
16
- return null;
17
- }
18
- const [startRaw, endRaw] = rangeHeader.slice("bytes=".length).split("-");
19
- const start = startRaw.length > 0 ? Number(startRaw) : 0;
20
- const end = endRaw && endRaw.length > 0 ? Number(endRaw) : fileLength - 1;
21
- if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start) {
22
- return null;
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
- return { start, end: Math.min(end, fileLength - 1) };
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
  }