@torrent-tv/proxy 2.107.69 → 2.107.71
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 +3 -2
- package/routes/encode-input/get.js +10 -8
- package/routes/media/get.js +14 -31
- package/routes/stream/get.js +21 -30
- package/scripts/install-native.sh +128 -0
- package/services/server/byte-range-reply.js +68 -0
- package/utils/parse-range.js +41 -17
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@torrent-tv/proxy",
|
|
3
|
-
"version": "2.107.
|
|
3
|
+
"version": "2.107.71",
|
|
4
4
|
"description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"repository": {
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
"services/",
|
|
25
25
|
"store/",
|
|
26
26
|
"utils/",
|
|
27
|
-
"server.js"
|
|
27
|
+
"server.js",
|
|
28
|
+
"scripts/install-native.sh"
|
|
28
29
|
],
|
|
29
30
|
"scripts": {
|
|
30
31
|
"start": "node ./bin/cli.js",
|
|
@@ -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,128 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# Builds and checks the proxy's two native modules in an installed proxy:
|
|
3
|
+
# node-datachannel (WebRTC) and utp-native (our fork, uTP to peers). Every
|
|
4
|
+
# image that installs the proxy runs this one script after its install with
|
|
5
|
+
# `--ignore-scripts` (torrent-tv/meta#302).
|
|
6
|
+
#
|
|
7
|
+
# sh scripts/install-native.sh <package dir>
|
|
8
|
+
#
|
|
9
|
+
# <package dir> holds the installed proxy: its package.json and node_modules/.
|
|
10
|
+
# INSTALL_NATIVE_RETRY_DELAY is the wait in seconds between node-datachannel
|
|
11
|
+
# attempts (default 10). npm and node are taken from PATH, and every npm call
|
|
12
|
+
# runs in the package directory, never with --global.
|
|
13
|
+
|
|
14
|
+
set -eu
|
|
15
|
+
|
|
16
|
+
usage() {
|
|
17
|
+
echo "usage: install-native.sh <package dir>" >&2
|
|
18
|
+
echo " <package dir> holds the installed proxy (package.json and node_modules/)" >&2
|
|
19
|
+
exit 2
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
fatal() {
|
|
23
|
+
echo "FATAL: install-native: $*" >&2
|
|
24
|
+
exit 1
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
# Prints a field of a JSON file, or `undefined` when it is absent.
|
|
28
|
+
# json_field <file> <key> [<key>...]
|
|
29
|
+
json_field() {
|
|
30
|
+
node -e '
|
|
31
|
+
const [file, ...keys] = process.argv.slice(1);
|
|
32
|
+
let value = JSON.parse(require("node:fs").readFileSync(file, "utf8"));
|
|
33
|
+
for (const key of keys) value = value === null || typeof value !== "object" ? undefined : value[key];
|
|
34
|
+
process.stdout.write(String(value));
|
|
35
|
+
' "$@"
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
[ "$#" -eq 1 ] || usage
|
|
39
|
+
[ -f "$1/package.json" ] || usage
|
|
40
|
+
cd "$1"
|
|
41
|
+
package_dir=$(pwd)
|
|
42
|
+
|
|
43
|
+
# 1. Node floor, as the package states it in engines.node.
|
|
44
|
+
engines=$(json_field package.json engines node)
|
|
45
|
+
case $engines in
|
|
46
|
+
">="*) floor=${engines#>=} ;;
|
|
47
|
+
*) floor= ;;
|
|
48
|
+
esac
|
|
49
|
+
case $floor in
|
|
50
|
+
"" | *[!0-9]*) fatal "engines.node must be \">=N\", found $engines" ;;
|
|
51
|
+
esac
|
|
52
|
+
version=$(node -p process.versions.node)
|
|
53
|
+
major=${version%%.*}
|
|
54
|
+
case $major in
|
|
55
|
+
"" | *[!0-9]*) fatal "cannot read the running Node version: $version" ;;
|
|
56
|
+
esac
|
|
57
|
+
if [ "$major" -lt "$floor" ]; then
|
|
58
|
+
fatal "this proxy requires Node $floor or newer; found v$version"
|
|
59
|
+
fi
|
|
60
|
+
echo "install-native: node v$version (floor $floor)"
|
|
61
|
+
|
|
62
|
+
# 2. node-datachannel fetches a prebuilt binary; one failed request ends the
|
|
63
|
+
# rebuild, so it is tried up to five times. Without the binary the proxy has no
|
|
64
|
+
# WebRTC.
|
|
65
|
+
delay=${INSTALL_NATIVE_RETRY_DELAY:-10}
|
|
66
|
+
attempt=1
|
|
67
|
+
while ! npm rebuild node-datachannel; do
|
|
68
|
+
if [ "$attempt" -ge 5 ]; then
|
|
69
|
+
break
|
|
70
|
+
fi
|
|
71
|
+
echo "install-native: node-datachannel attempt $attempt of 5 failed; retrying in ${delay}s" >&2
|
|
72
|
+
sleep "$delay"
|
|
73
|
+
attempt=$((attempt + 1))
|
|
74
|
+
done
|
|
75
|
+
binary_found=
|
|
76
|
+
for binary in node_modules/node-datachannel/build/Release/*.node; do
|
|
77
|
+
if [ -f "$binary" ]; then
|
|
78
|
+
binary_found=1
|
|
79
|
+
fi
|
|
80
|
+
done
|
|
81
|
+
[ -n "$binary_found" ] || fatal "node-datachannel has no native binary; the proxy would have no WebRTC"
|
|
82
|
+
|
|
83
|
+
# 3. The proxy pins our utp-native fork through overrides.
|
|
84
|
+
spec=$(json_field package.json overrides utp-native)
|
|
85
|
+
case $spec in
|
|
86
|
+
"npm:@torrent-tv/utp-native@"*) ;;
|
|
87
|
+
*) fatal "the proxy pins no utp-native build of ours: $spec" ;;
|
|
88
|
+
esac
|
|
89
|
+
echo "utp-native: the proxy pins $spec"
|
|
90
|
+
|
|
91
|
+
# 4. Ours at the top. A global install ignores overrides, so the top copy may
|
|
92
|
+
# be missing or foreign; after `npm ci` it is already ours.
|
|
93
|
+
top=
|
|
94
|
+
if [ -f node_modules/utp-native/package.json ]; then
|
|
95
|
+
top=$(json_field node_modules/utp-native/package.json name)
|
|
96
|
+
fi
|
|
97
|
+
if [ "$top" != "@torrent-tv/utp-native" ]; then
|
|
98
|
+
npm install --omit=dev --ignore-scripts --no-save --no-audit --no-fund "utp-native@$spec"
|
|
99
|
+
fi
|
|
100
|
+
|
|
101
|
+
# 5. Nested copies are removed, so every require of utp-native reaches ours.
|
|
102
|
+
find node_modules -mindepth 3 -type d -name utp-native -prune -exec rm -rf {} +
|
|
103
|
+
|
|
104
|
+
# 6. Source build, best effort: without it peers are reached over TCP only.
|
|
105
|
+
if ! npm_config_build_from_source=true npm rebuild utp-native; then
|
|
106
|
+
echo "WARNING: utp-native build failed; peer connections stay TCP-only" >&2
|
|
107
|
+
fi
|
|
108
|
+
|
|
109
|
+
# 7. Provenance: every utp_native.node belongs to our package.
|
|
110
|
+
find node_modules -type d -name obj.target -prune -o \
|
|
111
|
+
-type f -path "*/build/Release/utp_native.node" -print |
|
|
112
|
+
while IFS= read -r binary; do
|
|
113
|
+
owner=$(dirname "$(dirname "$(dirname "$binary")")")
|
|
114
|
+
name=undefined
|
|
115
|
+
if [ -f "$owner/package.json" ]; then
|
|
116
|
+
name=$(json_field "$owner/package.json" name)
|
|
117
|
+
fi
|
|
118
|
+
if [ "$name" != "@torrent-tv/utp-native" ]; then
|
|
119
|
+
fatal "$package_dir/$binary is not our build"
|
|
120
|
+
fi
|
|
121
|
+
echo "utp-native: our build at $package_dir/$binary"
|
|
122
|
+
done
|
|
123
|
+
|
|
124
|
+
# 8. Clean-up: the intermediate build files are not shipped.
|
|
125
|
+
find node_modules -type d \( -path "*/build/Release/obj.target" -o -path "*/build/Release/.deps" \) \
|
|
126
|
+
-prune -exec rm -rf {} +
|
|
127
|
+
|
|
128
|
+
exit 0
|
|
@@ -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
|
+
}
|
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
|
}
|