@torrent-tv/proxy 2.9.34 → 2.9.36
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/CHANGELOG.md +5 -0
- package/openspec/changes/chunked-request-bodies/design.md +81 -0
- package/openspec/changes/chunked-request-bodies/proposal.md +53 -0
- package/openspec/changes/chunked-request-bodies/specs/chunked-request-bodies/spec.md +30 -0
- package/openspec/changes/chunked-request-bodies/tasks.md +40 -0
- package/package.json +1 -1
- package/services/data-channel-handler.js +147 -14
- package/services/webrtc-manager.js +13 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
## 2.9.35
|
|
2
|
+
|
|
3
|
+
- **New**: Chunked request bodies over the data channel (OpenSpec change `chunked-request-bodies`). Large request bodies — notably the source registration, whose body is the base64 `.torrent` (hundreds of KB for a multi-season pack) — now arrive as bounded binary frames (the response-frame layout) announced by a `request-start` message, and are reassembled and run through the same path as a single-message request. Bounded: 32 MB per-body cap, a 60 s TTL for incomplete bodies, an abort frame that drops partial state at once, and all per-channel state freed on channel close. This removes the single-message size ceiling symmetrically with responses (which already stream in chunks). Logged as `body=<bytes> bytes (chunked)`.
|
|
4
|
+
- **Fix**: Large torrents (many files / seasons) no longer fail with "Trying to send message larger than max-message-size" when a file is picked. The browser sends the source registration body — the base64-encoded `.torrent` — in a single data-channel message; a big multi-season pack's `.torrent` carries thousands of piece hashes (e.g. Poirot, 13 seasons: 420 KB → ~560 KB base64), exceeding libdatachannel's default advertised limit of 256 KB, so the browser's `channel.send()` threw. The proxy now advertises a 16 MB `a=max-message-size`, so a large single send still works while already-open tabs run the old bundle. Verified the SDP now carries `a=max-message-size:16777216` (was `262144`).
|
|
5
|
+
|
|
1
6
|
## 2.9.34
|
|
2
7
|
|
|
3
8
|
- **New**: Cold-start reduction (OpenSpec change `cold-start`). Creating a transcode session no longer runs a second full ffmpeg input scan: the playback planner caches the media info (duration/resolution/fps/start-time/HDR) parsed from the probe it already ran, and `createSession` reuses it (falling back to its own probe only when the cache cannot serve — e.g. after a restart, or a missing critical field). The banner parsers now live in a shared `ffmpeg-banner.js` so both sides parse identically. Once a plan probe succeeds the proxy also warms the START of the file body (~16 MB, fire-and-forget) so the first segment's encode reads downloaded data instead of waiting on pieces. Session startup is now measurable in the log: `cold-start <id>: media-info=<ms> (cached|probed) keyframes=<ms|skipped> create-total=<ms>` and, once per session, `cold-start <id>: first-segment ready +<ms>`.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Design: Chunked request bodies (proxy side)
|
|
2
|
+
|
|
3
|
+
Written to be executed as specified — the wire format, constants, limits
|
|
4
|
+
and do-NOT list are normative. Read before coding:
|
|
5
|
+
|
|
6
|
+
- `services/data-channel-handler.js`: the whole file — the wire-protocol
|
|
7
|
+
doc comment (~lines 9–37), `handleChannel` (onMessage string handling),
|
|
8
|
+
`handleRequest`, `sendChunk` (the response frame writer whose layout the
|
|
9
|
+
request frames mirror), `send`.
|
|
10
|
+
|
|
11
|
+
## Wire protocol (additions)
|
|
12
|
+
|
|
13
|
+
Existing messages are UNCHANGED. New:
|
|
14
|
+
|
|
15
|
+
Browser → Proxy, announcing a chunked request:
|
|
16
|
+
{ type: "request-start", requestId, method, path, query, headers,
|
|
17
|
+
bodyBytes } // bodyBytes = exact total body size in bytes
|
|
18
|
+
|
|
19
|
+
Browser → Proxy, body frames (BINARY messages — today the proxy only
|
|
20
|
+
ever receives strings, so binary is unambiguous):
|
|
21
|
+
byte 0 flags bit 0: done (last frame)
|
|
22
|
+
bit 1: aborted (drop this request, no reply)
|
|
23
|
+
byte 1 idLen requestId length in bytes
|
|
24
|
+
bytes 2..2+N requestId (ASCII)
|
|
25
|
+
bytes 2+N.. payload raw body bytes (UTF-8 of the body string;
|
|
26
|
+
may be empty on a done/abort frame)
|
|
27
|
+
|
|
28
|
+
Identical layout to the response frames (`sendChunk`) — one mental model,
|
|
29
|
+
and the browser already has a parser for it (its builder mirrors it).
|
|
30
|
+
|
|
31
|
+
No capability negotiation: POC, single-proxy pool, lockstep releases
|
|
32
|
+
(proxy first, then server). The 16 MB `maxMessageSize` advertisement in
|
|
33
|
+
webrtc-manager.js (pending 2.9.35) stays as a one-line transition cover
|
|
34
|
+
for tabs still running the single-send bundle.
|
|
35
|
+
|
|
36
|
+
## Constants
|
|
37
|
+
|
|
38
|
+
PROXY_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024
|
|
39
|
+
PARTIAL_REQUEST_TTL_MS = 60_000
|
|
40
|
+
|
|
41
|
+
## Assembly (all state per channel, inside `handleChannel`'s closure)
|
|
42
|
+
|
|
43
|
+
const partials = new Map(); // requestId → { meta, chunks: [], receivedBytes, timer }
|
|
44
|
+
|
|
45
|
+
- `request-start`: validate like a legacy request (same path allowlist —
|
|
46
|
+
run the SAME validation before accepting the body; reject with
|
|
47
|
+
`response-error` immediately on a bad path). Reject `bodyBytes` >
|
|
48
|
+
PROXY_MAX_REQUEST_BODY_BYTES with `response-error` "Request body too
|
|
49
|
+
large." and do NOT create state. Otherwise store `{ meta, chunks: [],
|
|
50
|
+
receivedBytes: 0 }` and arm the TTL timer.
|
|
51
|
+
- Binary frame: parse header; unknown requestId → ignore (stale/aborted).
|
|
52
|
+
bit 1 (aborted) → clear timer, delete entry, no reply. Append payload,
|
|
53
|
+
add to receivedBytes; receivedBytes > bodyBytes (or > the cap) →
|
|
54
|
+
`response-error` + drop. bit 0 (done): concat chunks → body string via
|
|
55
|
+
`Buffer.concat(...).toString("utf8")`; receivedBytes !== bodyBytes →
|
|
56
|
+
`response-error` "Request body size mismatch." and drop; else clear
|
|
57
|
+
timer, delete entry, and execute through the SAME code path a legacy
|
|
58
|
+
`request` message takes (factor `handleRequest` so both entry points
|
|
59
|
+
call one function with `{requestId, method, path, query, headers, body}`).
|
|
60
|
+
- TTL fire: delete entry, log
|
|
61
|
+
`[dc] Session …: dropped stale partial request <id8> (<receivedBytes>B)`.
|
|
62
|
+
- `channel.onClosed`: clear ALL timers and the map (extend the existing
|
|
63
|
+
handler — do not replace its logging).
|
|
64
|
+
|
|
65
|
+
## Logging
|
|
66
|
+
|
|
67
|
+
Chunked request execution logs the SAME `[dc] <method> <path>` line as
|
|
68
|
+
legacy, with `body=<bytes> bytes (chunked)`.
|
|
69
|
+
|
|
70
|
+
## Rules — do NOT
|
|
71
|
+
|
|
72
|
+
- Do NOT change the legacy `{type:"request"}` handling, the response
|
|
73
|
+
framing, ping/pong, or the path allowlist semantics.
|
|
74
|
+
- Do NOT add capability/version negotiation — POC decision, revisit only
|
|
75
|
+
when the pool has independently-updated proxies.
|
|
76
|
+
- Do NOT revert the 16 MB `maxMessageSize` advertisement (pending 2.9.35).
|
|
77
|
+
- Do NOT hold partial bodies beyond the TTL or channel lifetime; no global
|
|
78
|
+
(cross-channel) state.
|
|
79
|
+
- Do NOT create a new proxy version: fold into the pending 2.9.35
|
|
80
|
+
CHANGELOG entry (accumulate bullets, per the versioning rules) and the
|
|
81
|
+
pending addon 0.2.56 entry.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Proposal: Chunked request bodies over the data channel (proxy side)
|
|
2
|
+
|
|
3
|
+
## Why
|
|
4
|
+
|
|
5
|
+
The browser sends every request as ONE data-channel message, body included.
|
|
6
|
+
Registering a source carries the base64-encoded `.torrent` as that body — a
|
|
7
|
+
big multi-season pack (Poirot, 13 seasons: 420 KB `.torrent` → ~560 KB
|
|
8
|
+
base64) exceeded libdatachannel's default advertised `a=max-message-size`
|
|
9
|
+
of 256 KB, so the browser's `send()` threw "Trying to send message larger
|
|
10
|
+
than max-message-size" and playback dead-ended.
|
|
11
|
+
|
|
12
|
+
The committed-but-unpublished stopgap (advertise 16 MB, pending 2.9.35)
|
|
13
|
+
lifts the ceiling but keeps the flaw: any single-message body still has a
|
|
14
|
+
hard cap, and a large message is buffered whole on both ends. Responses
|
|
15
|
+
already solved this properly — they stream as small binary frames. Requests
|
|
16
|
+
should be symmetric.
|
|
17
|
+
|
|
18
|
+
## What Changes
|
|
19
|
+
|
|
20
|
+
- **Inbound binary body frames.** The proxy accepts request bodies as
|
|
21
|
+
binary frames with EXACTLY the response-frame layout
|
|
22
|
+
(`[flags][idLen][requestId][payload]`, bit 0 = done; new bit 1 = aborted),
|
|
23
|
+
announced by a new `{type:"request-start", …, bodyBytes}` control message.
|
|
24
|
+
On the done frame the assembled body runs through the SAME request
|
|
25
|
+
execution path as a legacy request. Bounded: per-body cap 32 MB, partial
|
|
26
|
+
bodies dropped after a 60 s TTL or an abort frame, all per-channel state
|
|
27
|
+
freed on channel close.
|
|
28
|
+
- **No capability negotiation.** POC: the pool is one proxy, released in
|
|
29
|
+
lockstep with the site (proxy first, then server). The browser just uses
|
|
30
|
+
chunked frames for large bodies; this proxy just understands them.
|
|
31
|
+
- **The 16 MB `max-message-size` advertisement (pending 2.9.35) stays** —
|
|
32
|
+
a single config value, no logic: it covers the transition window while
|
|
33
|
+
already-open tabs still run the single-send bundle.
|
|
34
|
+
- **Observability**: the `[dc]` request log line reports chunked bodies
|
|
35
|
+
(`body=<bytes> bytes (chunked)`).
|
|
36
|
+
|
|
37
|
+
Browser-side counterpart (chunk writer, threshold, backpressure, abort) is
|
|
38
|
+
the server repo's `chunked-request-bodies` change. Release order: proxy
|
|
39
|
+
(with addon bump) FIRST, then server.
|
|
40
|
+
|
|
41
|
+
## Capabilities
|
|
42
|
+
|
|
43
|
+
### New Capabilities
|
|
44
|
+
|
|
45
|
+
- `chunked-request-bodies`: request-body transport over the data channel.
|
|
46
|
+
|
|
47
|
+
## Impact
|
|
48
|
+
|
|
49
|
+
- `services/data-channel-handler.js` — binary inbound frame parsing;
|
|
50
|
+
per-channel partial-body assembly with caps/TTL; `request-start`
|
|
51
|
+
handling; shared execution path.
|
|
52
|
+
- Release: folds into the PENDING proxy 2.9.35 (extend its CHANGELOG entry;
|
|
53
|
+
do not create a new version) + ha-addon 0.2.56 (same rule).
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# chunked-request-bodies — delta spec (proxy)
|
|
2
|
+
|
|
3
|
+
## ADDED Requirements
|
|
4
|
+
|
|
5
|
+
### Requirement: Request bodies arrive in bounded binary chunks
|
|
6
|
+
|
|
7
|
+
The proxy SHALL accept a request whose body is delivered as binary frames
|
|
8
|
+
(mirroring the response-frame layout) announced by a `request-start`
|
|
9
|
+
control message, assemble it, and execute it through the same path as a
|
|
10
|
+
single-message request. Assembly SHALL be bounded: a per-body byte cap, a
|
|
11
|
+
TTL for incomplete bodies, an abort flag that drops the partial state, and
|
|
12
|
+
release of all partial state when the channel closes. Legacy single-message
|
|
13
|
+
requests SHALL keep working unchanged.
|
|
14
|
+
|
|
15
|
+
#### Scenario: Large .torrent registration
|
|
16
|
+
- **WHEN** the browser registers a multi-season torrent whose base64 body
|
|
17
|
+
exceeds any single-message limit
|
|
18
|
+
- **THEN** the body arrives in frames, the source registers, and the
|
|
19
|
+
response streams back exactly as for a small request
|
|
20
|
+
|
|
21
|
+
#### Scenario: Oversized or inconsistent body
|
|
22
|
+
- **WHEN** the announced or delivered size exceeds the cap, or the
|
|
23
|
+
delivered bytes do not match the announcement
|
|
24
|
+
- **THEN** the proxy replies with a response-error for that request and
|
|
25
|
+
drops the partial state; the channel and other requests are unaffected
|
|
26
|
+
|
|
27
|
+
#### Scenario: Sender vanishes mid-body
|
|
28
|
+
- **WHEN** frames stop arriving (tab closed, aborted without a frame)
|
|
29
|
+
- **THEN** the partial body is dropped after the TTL (or immediately on
|
|
30
|
+
channel close) and its memory is released
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Tasks: Chunked request bodies (proxy side)
|
|
2
|
+
|
|
3
|
+
Execute in order; design.md is normative. Read the code regions listed at
|
|
4
|
+
its top first.
|
|
5
|
+
|
|
6
|
+
## 1. Implementation
|
|
7
|
+
|
|
8
|
+
- [ ] 1.1 `data-channel-handler.js`: factor the execution tail of
|
|
9
|
+
`handleRequest` so a legacy `request` message and an assembled
|
|
10
|
+
chunked request run the SAME function. `node --check`.
|
|
11
|
+
- [ ] 1.2 `request-start` + binary inbound frames + per-channel assembly
|
|
12
|
+
with cap (32 MB), size-mismatch check, abort flag (bit 1), TTL
|
|
13
|
+
(60 s), cleanup on channel close. Unknown-requestId frames ignored.
|
|
14
|
+
- [ ] 1.3 Logging: `body=<bytes> bytes (chunked)` on execution; stale-drop
|
|
15
|
+
line on TTL.
|
|
16
|
+
|
|
17
|
+
## 2. Verification
|
|
18
|
+
|
|
19
|
+
- [ ] 2.1 Node loopback test (two node-datachannel PeerConnections in one
|
|
20
|
+
script, like the SDP test): drive a request-start + 64 KB frames of a
|
|
21
|
+
~600 KB body through a real channel into a handler instance wired to
|
|
22
|
+
a stub local server; assert the assembled body bytes match and a
|
|
23
|
+
response comes back. Also: abort frame → no reply, state dropped;
|
|
24
|
+
oversized announcement → response-error.
|
|
25
|
+
- [ ] 2.2 Legacy regression: single-message request path byte-identical
|
|
26
|
+
behaviour (run an existing small request through both entry points).
|
|
27
|
+
- [ ] 2.3 E2E (after the server-side change lands in preview): local stack
|
|
28
|
+
— preview server + local proxy (`node bin/cli.js --server-url
|
|
29
|
+
ws://localhost:8080`), register the real Poirot `.torrent`
|
|
30
|
+
(C:\Users\AntonNemtsev\Downloads\Пуаро_….torrent, ~560 KB base64)
|
|
31
|
+
via the UI; plan returns; `[dc] … body=… (chunked)` in the proxy log.
|
|
32
|
+
|
|
33
|
+
## 3. Release
|
|
34
|
+
|
|
35
|
+
- [ ] 3.1 EXTEND the pending 2.9.35 CHANGELOG entry (do not bump again) and
|
|
36
|
+
the pending addon 0.2.56 entry.
|
|
37
|
+
- [ ] 3.2 `npm run patch` in proxy (publishes 2.9.35), push addon bump,
|
|
38
|
+
update the addon in HA; verify `Starting @torrent-tv/proxy v2.9.35`
|
|
39
|
+
in the addon log. Proxy FIRST, then addon, then the server-side
|
|
40
|
+
change releases independently.
|
package/package.json
CHANGED
|
@@ -95,35 +95,149 @@ export function createDataChannelHandler({ proxyPort, onLog }) {
|
|
|
95
95
|
* @returns {void}
|
|
96
96
|
*/
|
|
97
97
|
function handleChannel(sessionId, channel) {
|
|
98
|
-
|
|
98
|
+
const tag = sessionId.slice(0, 8);
|
|
99
|
+
log(`[dc] Session ${tag}: channel open`);
|
|
100
|
+
|
|
101
|
+
// Partial chunked-request bodies in flight on THIS channel, keyed by
|
|
102
|
+
// requestId. Each entry buffers frames until the done frame, then runs the
|
|
103
|
+
// assembled request through the same path as a single-message request.
|
|
104
|
+
/** @type {Map<string, { meta: object, chunks: Buffer[], receivedBytes: number, bodyBytes: number, timer: ReturnType<typeof setTimeout> }>} */
|
|
105
|
+
const partials = new Map();
|
|
106
|
+
|
|
107
|
+
const dropPartial = (requestId) => {
|
|
108
|
+
const entry = partials.get(requestId);
|
|
109
|
+
if (entry) {
|
|
110
|
+
clearTimeout(entry.timer);
|
|
111
|
+
partials.delete(requestId);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Begin assembling a chunked request. Validates the path and size up front
|
|
117
|
+
* so an invalid or oversized request never buffers a body.
|
|
118
|
+
*
|
|
119
|
+
* @param {any} message - The `request-start` control message.
|
|
120
|
+
*/
|
|
121
|
+
const startPartialRequest = (message) => {
|
|
122
|
+
const { requestId, method, path, query, headers, bodyBytes } = message ?? {};
|
|
123
|
+
if (typeof requestId !== "string" || requestId.length === 0) {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (!isValidRequestPath(path)) {
|
|
127
|
+
send(channel, { type: "response-error", requestId, error: "Invalid request path." });
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (!Number.isInteger(bodyBytes) || bodyBytes < 0 || bodyBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
|
|
131
|
+
send(channel, { type: "response-error", requestId, error: "Request body too large." });
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
dropPartial(requestId); // replace any stale entry with the same id
|
|
135
|
+
const timer = setTimeout(() => {
|
|
136
|
+
const entry = partials.get(requestId);
|
|
137
|
+
partials.delete(requestId);
|
|
138
|
+
log(`[dc] Session ${tag}: dropped stale partial request ${requestId.slice(0, 8)} (${entry?.receivedBytes ?? 0}B)`);
|
|
139
|
+
}, PARTIAL_REQUEST_TTL_MS);
|
|
140
|
+
partials.set(requestId, {
|
|
141
|
+
meta: { requestId, method, path, query, headers },
|
|
142
|
+
chunks: [],
|
|
143
|
+
receivedBytes: 0,
|
|
144
|
+
bodyBytes,
|
|
145
|
+
timer
|
|
146
|
+
});
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Handle a binary body frame for a chunked request.
|
|
151
|
+
* Layout: [flags(1)][idLen(1)][requestId(ASCII)][payload].
|
|
152
|
+
*
|
|
153
|
+
* @param {Buffer} buf
|
|
154
|
+
*/
|
|
155
|
+
const handleBodyFrame = (buf) => {
|
|
156
|
+
if (buf.length < 2) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const flags = buf[0];
|
|
160
|
+
const idLen = buf[1];
|
|
161
|
+
if (buf.length < 2 + idLen) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const requestId = buf.toString("ascii", 2, 2 + idLen);
|
|
165
|
+
const entry = partials.get(requestId);
|
|
166
|
+
if (!entry) {
|
|
167
|
+
return; // stale / already-dropped / aborted
|
|
168
|
+
}
|
|
169
|
+
if (flags & 2) {
|
|
170
|
+
// Aborted by the browser — drop silently, no reply.
|
|
171
|
+
dropPartial(requestId);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (buf.length > 2 + idLen) {
|
|
175
|
+
const payload = buf.subarray(2 + idLen);
|
|
176
|
+
entry.chunks.push(Buffer.from(payload));
|
|
177
|
+
entry.receivedBytes += payload.length;
|
|
178
|
+
}
|
|
179
|
+
if (entry.receivedBytes > entry.bodyBytes || entry.receivedBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
|
|
180
|
+
dropPartial(requestId);
|
|
181
|
+
send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (flags & 1) {
|
|
185
|
+
// Done frame — assemble and execute.
|
|
186
|
+
dropPartial(requestId);
|
|
187
|
+
if (entry.receivedBytes !== entry.bodyBytes) {
|
|
188
|
+
send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const body = Buffer.concat(entry.chunks).toString("utf8");
|
|
192
|
+
void handleRequest(channel, { ...entry.meta, body }, true).catch((error) => {
|
|
193
|
+
log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
};
|
|
99
197
|
|
|
100
198
|
channel.onMessage((raw) => {
|
|
101
|
-
|
|
199
|
+
// Binary messages are chunked-request body frames; the proxy otherwise
|
|
200
|
+
// only ever receives JSON strings, so the type discriminates cleanly.
|
|
201
|
+
if (typeof raw !== "string") {
|
|
202
|
+
handleBodyFrame(Buffer.isBuffer(raw) ? raw : Buffer.from(raw));
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** @type {DataChannelRequest | { type: string, id?: string }} */
|
|
102
207
|
let message;
|
|
103
208
|
try {
|
|
104
|
-
message = JSON.parse(
|
|
209
|
+
message = JSON.parse(raw);
|
|
105
210
|
} catch {
|
|
106
211
|
return;
|
|
107
212
|
}
|
|
108
213
|
|
|
109
214
|
if (message.type === "request") {
|
|
110
215
|
void handleRequest(channel, message).catch((error) => {
|
|
111
|
-
log(`[dc] Session ${
|
|
216
|
+
log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
|
|
112
217
|
});
|
|
113
218
|
return;
|
|
114
219
|
}
|
|
115
220
|
|
|
221
|
+
if (message.type === "request-start") {
|
|
222
|
+
startPartialRequest(message);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
116
226
|
if (message.type === "ping") {
|
|
117
227
|
send(channel, { type: "pong", id: message.id });
|
|
118
228
|
}
|
|
119
229
|
});
|
|
120
230
|
|
|
121
231
|
channel.onClosed(() => {
|
|
122
|
-
|
|
232
|
+
for (const entry of partials.values()) {
|
|
233
|
+
clearTimeout(entry.timer);
|
|
234
|
+
}
|
|
235
|
+
partials.clear();
|
|
236
|
+
log(`[dc] Session ${tag}: channel closed`);
|
|
123
237
|
});
|
|
124
238
|
|
|
125
239
|
channel.onError((err) => {
|
|
126
|
-
log(`[dc] Session ${
|
|
240
|
+
log(`[dc] Session ${tag}: channel error: ${err}`);
|
|
127
241
|
});
|
|
128
242
|
}
|
|
129
243
|
|
|
@@ -138,24 +252,22 @@ export function createDataChannelHandler({ proxyPort, onLog }) {
|
|
|
138
252
|
* @param {DataChannelRequest} req
|
|
139
253
|
* @returns {Promise<void>}
|
|
140
254
|
*/
|
|
141
|
-
async function handleRequest(channel, req) {
|
|
255
|
+
async function handleRequest(channel, req, viaChunks = false) {
|
|
142
256
|
const { requestId, method, path, query, headers: forwardedHeaders, body } = req;
|
|
143
257
|
|
|
144
258
|
// Reject paths that are not absolute, contain traversal sequences, or
|
|
145
259
|
// do not start with a known proxy route prefix. All valid browser-side
|
|
146
260
|
// requests use /api/*, /stream, /transcode/*, /health, or /healthz.
|
|
147
|
-
if (
|
|
148
|
-
typeof path !== "string" ||
|
|
149
|
-
!path.startsWith("/") ||
|
|
150
|
-
path.includes("..") ||
|
|
151
|
-
!PATH_ALLOWLIST_RE.test(path)
|
|
152
|
-
) {
|
|
261
|
+
if (!isValidRequestPath(path)) {
|
|
153
262
|
send(channel, { type: "response-error", requestId, error: "Invalid request path." });
|
|
154
263
|
return;
|
|
155
264
|
}
|
|
156
265
|
|
|
157
266
|
const queryInfo = query ? `?${query}` : "";
|
|
158
|
-
const bodyInfo =
|
|
267
|
+
const bodyInfo =
|
|
268
|
+
body != null && typeof body === "string" && body.length > 0
|
|
269
|
+
? ` body=${body.length} bytes${viaChunks ? " (chunked)" : ""}`
|
|
270
|
+
: "";
|
|
159
271
|
log(`[dc] ${method} ${path}${queryInfo}${bodyInfo}`);
|
|
160
272
|
|
|
161
273
|
const targetUrl = `http://127.0.0.1:${proxyPort}${path}${query ? `?${query}` : ""}`;
|
|
@@ -328,6 +440,27 @@ export function createDataChannelHandler({ proxyPort, onLog }) {
|
|
|
328
440
|
*/
|
|
329
441
|
const PATH_ALLOWLIST_RE = /^(?:\/api\/|\/stream(?:$|\?)|\/?transcode\/|\/health(?:z)?(?:$|\?))/;
|
|
330
442
|
|
|
443
|
+
/**
|
|
444
|
+
* True when `path` is an absolute, traversal-free path on a known proxy route.
|
|
445
|
+
* Shared by the single-message and chunked request entry points.
|
|
446
|
+
*
|
|
447
|
+
* @param {unknown} path
|
|
448
|
+
* @returns {boolean}
|
|
449
|
+
*/
|
|
450
|
+
function isValidRequestPath(path) {
|
|
451
|
+
return (
|
|
452
|
+
typeof path === "string" &&
|
|
453
|
+
path.startsWith("/") &&
|
|
454
|
+
!path.includes("..") &&
|
|
455
|
+
PATH_ALLOWLIST_RE.test(path)
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** Max assembled size of a chunked request body (guards proxy memory). */
|
|
460
|
+
const PROXY_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024;
|
|
461
|
+
/** Drop an incomplete chunked body if no further frame arrives within this window. */
|
|
462
|
+
const PARTIAL_REQUEST_TTL_MS = 60_000;
|
|
463
|
+
|
|
331
464
|
/** Pause sending body chunks once the channel buffer exceeds this many bytes. */
|
|
332
465
|
const DC_BUFFER_HIGH_WATER = 8 * 1024 * 1024;
|
|
333
466
|
/** Resume sending once the channel buffer drains to this many bytes. */
|
|
@@ -25,6 +25,18 @@ const ICE_SERVERS = ["stun:stun.l.google.com:19302", "stun:stun.cloudflare.com:3
|
|
|
25
25
|
// values without bloating the SDP.
|
|
26
26
|
const PORT_PREDICTION_WINDOW = 16;
|
|
27
27
|
|
|
28
|
+
// Max size of a single data-channel message the proxy advertises (SDP
|
|
29
|
+
// `a=max-message-size`) and will accept. The browser caps `channel.send()` at
|
|
30
|
+
// the REMOTE's advertised value, so this is what lets the browser send a large
|
|
31
|
+
// request body in one message — notably registering a source, whose body is
|
|
32
|
+
// the base64-encoded .torrent. A big multi-season pack's .torrent (thousands of
|
|
33
|
+
// piece hashes) can be hundreds of KB (e.g. Poirot: 420 KB → ~560 KB base64),
|
|
34
|
+
// which exceeds libdatachannel's ~256 KB default and made `send()` throw
|
|
35
|
+
// "message larger than max-message-size". 16 MB is a generous ceiling (memory
|
|
36
|
+
// is allocated per actual message, not reserved). Responses (proxy→browser)
|
|
37
|
+
// are already safe — they stream in small reader-sized chunks.
|
|
38
|
+
const MAX_DC_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
39
|
+
|
|
28
40
|
/**
|
|
29
41
|
* Build predicted srflx ICE candidates for a symmetric NAT.
|
|
30
42
|
*
|
|
@@ -195,7 +207,7 @@ export function createWebRtcManager({ sendSignal, onDataChannel, onLog, udpPort,
|
|
|
195
207
|
}
|
|
196
208
|
|
|
197
209
|
// Base PeerConnection config shared by every session.
|
|
198
|
-
const pcConfig = { iceServers: ICE_SERVERS };
|
|
210
|
+
const pcConfig = { iceServers: ICE_SERVERS, maxMessageSize: MAX_DC_MESSAGE_BYTES };
|
|
199
211
|
|
|
200
212
|
// Single-port UDP mux: create ONE persistent listener that owns the shared
|
|
201
213
|
// UDP socket for the proxy's whole lifetime, then have every PeerConnection
|