fix(media): close the UDP candidate migration boundary
This commit is contained in:
1 parent
aadcba4e3b
commit
41ccbef68a
29 files changed
+548
-373
No files matched your search
+2
-2
@@ -18,8 +18,8 @@ MAX_ROOMS=1000
|
||||
MAX_VIEWERS_PER_ROOM=8
|
||||
# Experimental standard-WebRTC relay chains. Keep false outside measured tests.
|
||||
PEER_ASSISTED_MEDIA=false
|
||||
# Optional exact-room canary when peer assistance is true. Use comma-separated
|
||||
# positive numeric room IDs. Missing or empty means every room for compatibility.
|
||||
# Required exact-room canary when peer assistance is true. Use a non-empty,
|
||||
# comma-separated list of positive numeric room IDs; missing or blank fails startup.
|
||||
PEER_ASSISTED_ROOM_IDS=
|
||||
|
||||
# Optional automatic SFU fallback capacity. Set PEER_ASSISTED_MEDIA=true and
|
||||
|
||||
@@ -32,7 +32,7 @@ repository candidate deliberately replaces that contract: ordinary authenticated
|
||||
ICE contains only self-hosted STUN, LiveKit separately serves normally one or two
|
||||
SFU/UDP roots, and exhausted paths fail clearly after bounded recovery. Run it on
|
||||
an isolated instance for exact-room acceptance rather than retaining a same-process
|
||||
legacy transport branch. Optional generation-bound TURN for a selected exceptional
|
||||
old-release compatibility branch. Optional generation-bound TURN for a selected exceptional
|
||||
edge is not implemented and requires a separate evidence-backed change. HTTPS/WSS
|
||||
continues to use TLS/TCP independently.
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ listening-port=3478
|
||||
stun-only
|
||||
no-tcp
|
||||
no-tls
|
||||
no-dtls
|
||||
|
||||
# Keep automatic address selection on a single-homed public host. On a
|
||||
# multi-homed host, bind only the intended public interface.
|
||||
|
||||
@@ -10,6 +10,12 @@ rtc:
|
||||
# These media ports must be reached directly by clients. Port 7880 is only
|
||||
# for the same-host reverse proxy and must be denied by every public firewall.
|
||||
udp_port: 7882
|
||||
tcp_port: 0
|
||||
allow_tcp_fallback: false
|
||||
# Do not inherit LiveKit's public Google STUN defaults. This is the same
|
||||
# deployment-owned STUN-only listener advertised to ordinary peer edges.
|
||||
stun_servers:
|
||||
- stun.example.com:3478
|
||||
use_external_ip: true
|
||||
|
||||
room:
|
||||
@@ -22,5 +28,6 @@ logging:
|
||||
level: info
|
||||
pion_level: error
|
||||
|
||||
# ICE/TCP, external or embedded TURN, Redis, recording, ingress, egress, and
|
||||
# webhooks are omitted on purpose. This candidate is one process on one node.
|
||||
# External or embedded TURN, Redis, recording, ingress, egress, and webhooks are
|
||||
# omitted on purpose. ICE/TCP fallback is explicitly disabled above. This
|
||||
# candidate is one process on one node.
|
||||
@@ -37,9 +37,25 @@ server {
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
|
||||
# Optional LiveKit signaling for automatic SFU fallback. Set LIVEKIT_URL to
|
||||
# wss://share.bonfire.icu. Legacy clients use the exact /rtc endpoint.
|
||||
# Reject the retired unversioned LiveKit endpoint. Keep this exact location
|
||||
# out of logs because old URLs may still contain a short-lived join token.
|
||||
location = /rtc {
|
||||
access_log off;
|
||||
error_log /dev/null crit;
|
||||
return 404;
|
||||
}
|
||||
|
||||
# LiveKit client v0 validates this retired path before joining. Reject it
|
||||
# explicitly so the broader current-v1 proxy cannot accept an old SDK.
|
||||
location = /rtc/validate {
|
||||
access_log off;
|
||||
error_log /dev/null crit;
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Current LiveKit clients use v1 paths only. Set
|
||||
# LIVEKIT_URL to wss://share.bonfire.icu.
|
||||
location ^~ /rtc/v1 {
|
||||
# The WebSocket query contains a short-lived LiveKit join token. Do not
|
||||
# persist the request target in either access or error logs.
|
||||
access_log off;
|
||||
@@ -58,24 +74,11 @@ server {
|
||||
proxy_buffering off;
|
||||
}
|
||||
|
||||
# Current clients use versioned paths below /rtc/.
|
||||
# Reject any other retired or unknown LiveKit path without logging tokens.
|
||||
location ^~ /rtc/ {
|
||||
# The WebSocket query contains a short-lived LiveKit join token. Do not
|
||||
# persist the request target in either access or error logs.
|
||||
access_log off;
|
||||
error_log /dev/null crit;
|
||||
proxy_pass http://127.0.0.1:7880;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $screener_connection_upgrade;
|
||||
proxy_read_timeout 5h;
|
||||
proxy_send_timeout 5h;
|
||||
proxy_buffering off;
|
||||
return 404;
|
||||
}
|
||||
|
||||
location / {
|
||||
|
||||
@@ -44,13 +44,13 @@ cross-mode fallback as a product goal.
|
||||
The experiment is gated by `PEER_ASSISTED_MEDIA`, which defaults to `false`.
|
||||
Enabling it requires `MAX_VIEWERS_PER_ROOM` at or below eight; larger configured
|
||||
rooms fail configuration rather than silently running a different topology.
|
||||
An optional non-empty `PEER_ASSISTED_ROOM_IDS` deployment allowlist restricts
|
||||
the experiment to exact valid room IDs. Non-allowlisted rooms must use the
|
||||
legacy P2P authenticated wire, signaling, quality behavior, and lifecycle and
|
||||
must never enter `HybridMediaRouter`. Missing or empty retains the original
|
||||
all-room behavior when the experiment is enabled; isolated canaries therefore
|
||||
must provide at least one ID. Invalid, empty-list-entry, or duplicate values
|
||||
fail startup. This adds no UI, percentage rollout, or routing score.
|
||||
A required non-empty `PEER_ASSISTED_ROOM_IDS` deployment allowlist restricts
|
||||
the experiment to exact valid room IDs. Non-allowlisted rooms use the current
|
||||
ordinary P2P authenticated wire, signaling, quality behavior, and lifecycle and
|
||||
must never enter `HybridMediaRouter`. Missing, blank, invalid, empty-list-entry,
|
||||
or duplicate values fail startup when the experiment is enabled; there is no
|
||||
all-room fail-open. This exact-room gate is temporary validation scope and adds
|
||||
no UI, percentage rollout, or routing score.
|
||||
|
||||
The signaling server assigns two sticky, balanced chains with a deterministic
|
||||
breadth-first walk. The host has capacity for at most two children and each
|
||||
@@ -66,8 +66,10 @@ host's two-child limit is a hard invariant across join, reconnect,
|
||||
reparent, and recovery paths. If the deterministic topology has no connected
|
||||
eligible parent, the viewer remains admitted but waits without media until a
|
||||
slot becomes reachable; it must not create a third host connection.
|
||||
Each logical edge still uses its own ICE process and authenticated TURN fallback
|
||||
when direct connectivity is unavailable.
|
||||
Each logical edge still uses its own ICE process. In the repository candidate,
|
||||
ordinary edges receive only STUN and route exhaustion proceeds to the bounded
|
||||
SFU virtual parent or clear failure; the old production TURN behavior is not a
|
||||
same-process compatibility branch.
|
||||
|
||||
Every edge uses the existing standard WebRTC media path. A viewer receives the
|
||||
remote `MediaStream`, renders it, and sends those remote tracks through one new
|
||||
|
||||
@@ -81,20 +81,21 @@ one-host-peer-per-viewer P2P/TURN.
|
||||
The repository candidate now removes the old all-room coturn contract. Production
|
||||
requires STUN, ordinary authenticated ICE snapshots contain only STUN servers,
|
||||
and the protocol has no TURN credential expiry or refresh messages. The tracked
|
||||
LiveKit sample also omits ICE/TCP and every TURN service. The SFU controller still
|
||||
LiveKit sample explicitly sets `tcp_port: 0`, disables TCP fallback, supplies
|
||||
the deployment-owned STUN server, and configures no TURN service. The SFU controller still
|
||||
activates only after a peer edge exhausts recovery, so public transport and route
|
||||
admission remain unverified. Production `769de201f7cc` keeps its old coturn relay
|
||||
until an isolated candidate canary passes; rollback is release/instance based,
|
||||
not a permanent legacy branch in the new code.
|
||||
not a permanent old-release compatibility branch in the new code.
|
||||
|
||||
The repository also supports an optional strict `PEER_ASSISTED_ROOM_IDS`
|
||||
deployment allowlist. When non-empty, only exact listed room IDs enter the
|
||||
controller or receive optional LiveKit standby and grants. All other rooms
|
||||
retain the legacy P2P authentication shape and signaling/quality/lifecycle
|
||||
behavior. Missing or empty preserves the previous all-room behavior when
|
||||
`PEER_ASSISTED_MEDIA=true`; malformed or duplicate entries fail startup. The
|
||||
boundary is deployment-only and intentionally has no browser selector,
|
||||
percentage framework, or second router.
|
||||
The repository also requires a strict, non-empty `PEER_ASSISTED_ROOM_IDS`
|
||||
deployment allowlist whenever `PEER_ASSISTED_MEDIA=true`. Only exact listed room
|
||||
IDs enter the controller or receive optional LiveKit standby and grants. All
|
||||
other rooms retain the current ordinary P2P authentication shape and
|
||||
signaling/quality/lifecycle behavior. Missing, blank, malformed, or duplicate
|
||||
entries fail startup; there is no configuration state that enables all rooms. The boundary is a
|
||||
temporary deployment-only validation gate with no browser selector, percentage
|
||||
framework, or second router.
|
||||
|
||||
The implementation keeps the LiveKit dependency dormant unless the complete URL, API key,
|
||||
and API secret tuple is present together with `PEER_ASSISTED_MEDIA=true`. It
|
||||
@@ -393,7 +394,7 @@ record which boundary is actually configured and the UI must not claim E2EE.
|
||||
- In one process, non-allowlisted rooms preserve ordinary P2P route fields,
|
||||
directed signaling, quality rejection, stop/reconnect/delete semantics, and
|
||||
remain isolated from allowlisted peer/SFU state. All rooms receive the same
|
||||
process-wide STUN-only ordinary ICE contract; no legacy TURN branch exists.
|
||||
process-wide STUN-only ordinary ICE contract; no old-release TURN branch exists.
|
||||
- LiveKit/SFU UDP must pass CGNAT, double-NAT, hotspot, home-network, loss,
|
||||
rollback, and SFU-unavailable gates. Blocked UDP fails clearly within a
|
||||
bounded window. A future selected-edge TURN or media TCP implementation needs
|
||||
|
||||
+32
-26
@@ -58,10 +58,10 @@ should connect. A container can instead use `0.0.0.0` and enforce the intended
|
||||
boundary with port publishing rules or a host firewall.
|
||||
|
||||
The optional same-host LiveKit layout needs no additional public hostname:
|
||||
`LIVEKIT_URL=wss://share.example.com` and nginx forwards only the exact `/rtc`
|
||||
endpoint and paths below `/rtc/` to LiveKit. Its HTTP/WebSocket listener on TCP
|
||||
7880 is private to nginx, while WebRTC media reaches LiveKit directly on UDP
|
||||
7882.
|
||||
`LIVEKIT_URL=wss://share.example.com` and nginx proxies only current `/rtc/v1*`
|
||||
requests to LiveKit. Retired `/rtc` and `/rtc/validate` endpoints return 404
|
||||
without request-target logging. LiveKit's HTTP/WebSocket listener on TCP 7880 is
|
||||
private to nginx, while WebRTC media reaches LiveKit directly on UDP 7882.
|
||||
|
||||
## Candidate boundary and rollback
|
||||
|
||||
@@ -126,7 +126,8 @@ LIVEKIT_API_SECRET=<INDEPENDENT_SECRET_OF_AT_LEAST_32_BYTES>
|
||||
MAX_SFU_ROOTS_PER_ROOM=2
|
||||
```
|
||||
|
||||
`PEER_ASSISTED_ROOM_IDS` is the deployment canary boundary. A non-empty value
|
||||
`PEER_ASSISTED_ROOM_IDS` is the required deployment canary boundary whenever
|
||||
`PEER_ASSISTED_MEDIA=true`. Its non-empty value
|
||||
is a comma-separated set of exact positive numeric room IDs, using the same
|
||||
1-to-12-digit syntax as room authentication. Duplicate IDs, empty entries,
|
||||
leading zeroes, and malformed IDs fail startup. A non-empty allowlist requires
|
||||
@@ -134,10 +135,9 @@ leading zeroes, and malformed IDs fail startup. A non-empty allowlist requires
|
||||
authentication, routing, room quality state, or optional LiveKit fallback;
|
||||
every other room keeps ordinary P2P route fields and signaling behavior. The
|
||||
ordinary STUN-only ICE snapshot is process-wide; unlisted rooms do not retain
|
||||
the old TURN contract. Omitting the
|
||||
variable or leaving it empty deliberately preserves the earlier all-room
|
||||
behavior when peer assistance is enabled, so a canary deployment must set at
|
||||
least one exact ID. There is no browser control or percentage rollout.
|
||||
the old TURN contract. Omitting or blanking the variable fails startup rather
|
||||
than enabling every room. There is no browser control, percentage rollout, or
|
||||
all-room fail-open.
|
||||
|
||||
`ALLOWED_ORIGINS` must list exact `http` or `https` origins, never `*`.
|
||||
`ACCESS_PASSWORD` is optional: omit it or leave it empty for a public site. A
|
||||
@@ -171,8 +171,9 @@ second non-allowlisted room contains none of `mediaMode`, `qualitySettings`,
|
||||
answer, stop, reconnect, and room deletion in both rooms. Both rooms receive
|
||||
STUN-only ordinary ICE. Roll back by directing traffic to the unchanged old
|
||||
release; disabling `PEER_ASSISTED_MEDIA` only disables topology/SFU routing and
|
||||
does not restore the removed TURN wire. After acceptance, remove the allowlist
|
||||
to enable all rooms rather than retaining a permanent canary branch.
|
||||
does not restore the removed TURN wire. After acceptance, retire or replace the
|
||||
temporary exact-room gate in a separate coherent change; never clear the value
|
||||
to trigger an implicit all-room rollout.
|
||||
|
||||
When `ACCESS_PASSWORD` is configured, both host and viewer routes first show the
|
||||
same login gate. Only `POST /api/session` accepts the password in an
|
||||
@@ -228,9 +229,10 @@ access is acceptable or another trusted access layer exists.
|
||||
Production startup requires one to eight syntactically valid `stun:` URLs
|
||||
before the server listens. This validates shape only; it does not prove DNS,
|
||||
firewall, NAT mappings, or external STUN reachability. The current application
|
||||
does not read `TURN_URLS`, `TURN_SHARED_SECRET`, or
|
||||
`TURN_CREDENTIAL_TTL_SECONDS`; remove those obsolete values from the candidate
|
||||
environment instead of assuming they still enable compatibility.
|
||||
rejects `TURN_URLS`, `TURN_SHARED_SECRET`, or `TURN_CREDENTIAL_TTL_SECONDS` when
|
||||
any key is present, including with an empty value. Remove those obsolete keys
|
||||
from the candidate environment; startup fails instead of pretending they enable
|
||||
compatibility.
|
||||
|
||||
## HTTPS and WSS ingress
|
||||
|
||||
@@ -261,11 +263,10 @@ location / {
|
||||
The tracked
|
||||
[`share.bonfire.icu.conf.example`](../deploy/nginx/share.bonfire.icu.conf.example)
|
||||
follows this simple model and listens directly on public TCP 443. It does not
|
||||
need an SNI transport router. Its optional exact `/rtc` and `/rtc/` prefix
|
||||
locations preserve the LiveKit request URI and disable both access logging and
|
||||
request-line error logging. Legacy `/rtc?token=...` and current versioned
|
||||
requests carry a short-lived LiveKit JWT in the query string, so neither request
|
||||
target may fall through to the site's ordinary logs.
|
||||
need an SNI transport router. Exact `/rtc` and pinned-v0 `/rtc/validate` requests
|
||||
return 404 with access and request-line error logging disabled; only `/rtc/v1*`
|
||||
is proxied. Current versioned requests carry a short-lived LiveKit JWT in the
|
||||
query string, so no `/rtc*` target may fall through to the site's ordinary logs.
|
||||
|
||||
When Certbot manages the Web certificate, install the tracked
|
||||
[`reload-nginx.sh`](../deploy/certbot/reload-nginx.sh) as an executable under
|
||||
@@ -295,9 +296,11 @@ from its official release assets, generate an independent key pair with
|
||||
`/etc/livekit/keys.yaml`. Keep that file owned by the `livekit` service account
|
||||
with mode `0600`; put the same values in Screener's untracked process secrets.
|
||||
|
||||
The example deliberately omits Redis, ICE/TCP, and every recording, ingress,
|
||||
egress, webhook, external-TURN, and embedded-TURN service. Do not add Redis for
|
||||
this one-node workload.
|
||||
The example deliberately omits Redis and every recording, ingress, egress,
|
||||
webhook, external-TURN, and embedded-TURN service. It explicitly sets
|
||||
`tcp_port: 0` and `allow_tcp_fallback: false`, and points `stun_servers` at the
|
||||
deployment's self-hosted STUN listener so pinned LiveKit cannot inherit its
|
||||
default public Google STUN servers. Do not add Redis for this one-node workload.
|
||||
The service journal is the diagnostic log; keep its retention finite and access
|
||||
restricted. Never enable debug/Pion packet logging continuously or persist JWTs,
|
||||
SDP, ICE candidates, API secrets, or full `/rtc` and `/rtc/*` request targets.
|
||||
@@ -315,7 +318,8 @@ must be its only ingress. UDP 7882 is a direct media listener and must not be
|
||||
placed behind the HTTP reverse proxy. If the host is behind NAT, forward it
|
||||
without port translation and verify the advertised candidate from an external
|
||||
network. UDP-blocked networks are expected to fail clearly in this candidate;
|
||||
do not add `rtc.tcp_port` or TURN to make a canary pass silently.
|
||||
do not set `rtc.tcp_port` above zero, enable TCP fallback, or add TURN to make a
|
||||
canary pass silently.
|
||||
|
||||
## Self-hosted STUN
|
||||
|
||||
@@ -323,8 +327,10 @@ Copy [`deploy/coturn/turnserver.conf.example`](../deploy/coturn/turnserver.conf.
|
||||
to an untracked service-owned location and use the tracked
|
||||
[`coturn.service.example`](../deploy/systemd/coturn.service.example). The config
|
||||
uses coturn's documented `stun-only` mode, ignores every TURN allocation request,
|
||||
and disables TCP, TLS, and DTLS client listeners. It has no auth secret, user
|
||||
database, relay port range, certificate, quota, or TURN REST credential.
|
||||
and disables TCP and TLS client listeners. It has no auth secret, user database,
|
||||
relay port range, certificate, quota, or TURN REST credential. Pinned coturn
|
||||
4.17.2 deprecates `no-dtls`, so the tracked config does not use that obsolete
|
||||
switch or claim a separate DTLS listener gate.
|
||||
|
||||
On a single-homed public host, automatic listener selection is sufficient. On a
|
||||
multi-homed host, set `listening-ip` to the intended public interface. Open only
|
||||
@@ -359,7 +365,7 @@ Run these checks from real external networks before calling the deployment usabl
|
||||
ordinary direct UDP and host/relay downstream caps remain two/one.
|
||||
4. Block all UDP on one test client. Verify bounded ICE recovery ends in a clear
|
||||
connection failure, without an ICE/TCP, TURN/TCP, or long pseudo-connected
|
||||
path. The `?relay=1` diagnostic is expected to fail in this candidate.
|
||||
path. No force-relay product branch exists in this candidate.
|
||||
5. Exercise root departure, reconnect, SFU unavailable, route prepare rollback,
|
||||
stop, and source/profile changes. Unaffected subtrees must not migrate.
|
||||
6. Repeat at 1, 3, 5, and 8 viewers across representative consumer networks.
|
||||
|
||||
@@ -39,8 +39,8 @@ Last updated: 2026-08-19
|
||||
- Access uses optional `ACCESS_PASSWORD`, a 12-hour stateless HMAC HttpOnly Strict cookie, internal host token, role-bound signaling, Origin/payload checks, and no accounts/JWT/session map.
|
||||
- With `ROOM_DATABASE_PATH` and the password, SQLite stores room ID and host-token digest; links persist and room `1` survived deployment. Without it, rooms are temporary.
|
||||
- Production uses nginx, Node.js 24.19.0, and authenticated coturn 4.17.2 at `turn.bonfire.icu:3478`; public STUN, TURN/UDP, TURN/TCP, and relay-only traffic pass. TURN/TLS is off.
|
||||
- Candidate migration is process-wide: ordinary ICE is STUN-only, coturn disables TCP/TLS/DTLS, LiveKit 1.13.5 uses separate UDP participant ICE, and old TURN parser/signer/refresh/UI/SNI artifacts are gone. Old production is an isolated rollback.
|
||||
- The default-off ADR-0005 controller has no production peer/SFU configuration. `PEER_ASSISTED_ROOM_IDS` restricts exact canary rooms; unlisted rooms stay P2P and empty/missing means all.
|
||||
- Candidate migration is process-wide: ordinary ICE is STUN-only; coturn uses `stun-only`/`no-tcp`/`no-tls` without deprecated `no-dtls`; LiveKit 1.13.5 explicitly disables TCP fallback, uses deployment STUN and separate UDP participant ICE. Old TURN parser/signer/refresh/UI/SNI artifacts are gone; old production is isolated rollback.
|
||||
- The default-off ADR-0005 controller has no production peer/SFU configuration. Enabling it requires non-empty exact `PEER_ASSISTED_ROOM_IDS`; missing/blank fails startup and unlisted rooms use current ordinary P2P. `screener-v1` is the single signaling literal; mismatch terminates once with a refresh prompt.
|
||||
- When enabled, peer recovery precedes allowlisted SFU; session revisions prepare/commit/abort and active SFU gets one token refresh before failback. Browser relays re-encode; native sharing is outside product code.
|
||||
- Chrome 151/LiveKit localhost A/B cut failure-to-active/render from 1.481/2.257 seconds to 0.200/0.320; 31 new frames and 25 ms sampling kept host edges at two. It is headless synthetic 720p30 and includes SDK/network prewarm, not public-network evidence.
|
||||
- Draft native ladder #16/#18/#22/#23/#25/#28 has one bounded Chrome 720p30 loop: one WebCodecs object feeds two Pion/browser legs, applies an experiment-only minimum stock-GCC target, and recovers one isolated loss. It does not prove one hardware encode.
|
||||
|
||||
@@ -195,12 +195,14 @@ Production `769de201f7cc` remains the old baseline with coturn UDP/TCP. The
|
||||
repository candidate has crossed a clean config/wire boundary: production
|
||||
requires STUN, ordinary ICE snapshots contain only STUN servers, and no TURN
|
||||
credential or refresh message remains. The tracked coturn example is UDP
|
||||
`stun-only`; the LiveKit example exposes only ICE/UDP mux 7882 and configures no
|
||||
external or embedded TURN. Candidate validation and rollback use isolated
|
||||
instances rather than a process-wide legacy branch. HTTPS/WSS remains TLS/TCP.
|
||||
Coturn 4.17.2 documents `stun-only` as ignoring TURN requests and independently
|
||||
provides `no-tcp`, `no-tls`, and `no-dtls` listener switches. This makes coturn
|
||||
the explicit self-hosted STUN owner without retaining a relay allocation surface.
|
||||
`stun-only`; the LiveKit example exposes only ICE/UDP mux 7882, explicitly sets
|
||||
`tcp_port: 0` and `allow_tcp_fallback: false`, supplies the self-hosted STUN
|
||||
endpoint, and configures no external or embedded TURN. Candidate validation and rollback use isolated
|
||||
instances rather than a process-wide old-release compatibility branch. HTTPS/WSS remains TLS/TCP.
|
||||
Coturn 4.17.2 documents `stun-only` as ignoring TURN requests and provides
|
||||
`no-tcp` and `no-tls`; it marks `no-dtls` deprecated, so the tracked candidate
|
||||
does not use that switch. Coturn remains the explicit self-hosted STUN owner
|
||||
without a TURN allocation surface or reliance on public Google STUN.
|
||||
|
||||
No public port is selected by this decision. LiveKit documents ICE/UDP mux as
|
||||
optional and its pinned sample recommends a multi-port UDP mux range at least
|
||||
@@ -233,8 +235,8 @@ One bounded exact-room gate owns rollout evidence:
|
||||
8 and 12 Mbps with one and two roots. Record CPU seconds/GiB, RX/TX bytes,
|
||||
packets/s, RSS, host upload, p95/p99 forwarding latency, loss/recovery, and
|
||||
final decoded quality.
|
||||
2. Cover representative consumer networks on an isolated candidate with no
|
||||
`rtc.tcp_port` and no external or embedded TURN. Verify ordinary peers and
|
||||
2. Cover representative consumer networks on an isolated candidate with
|
||||
`rtc.tcp_port: 0`, `allow_tcp_fallback: false`, and no external or embedded TURN. Verify ordinary peers and
|
||||
SFU roots use UDP. Keep the old release on a separate rollback instance;
|
||||
`PEER_ASSISTED_ROOM_IDS` does not preserve old TURN wire for unlisted rooms.
|
||||
3. Block all UDP and show a bounded explicit failure rather than a long
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ unconfigured, so production remains one host connection per viewer and P2P/TURN.
|
||||
- ADR-0007 remains incomplete. A+B/C browser support and the reported case are unverified; the controller, `LOW`, and an authenticated SFU last-hop C generation are absent. Weak paths must share one `LOW`; fail closed protects `HIGH` only exceptionally, and an unreliable supported cohort fails acceptance.
|
||||
- Browser relays re-encode. ADR-0006 is no-go-unclassified: downstream checkpoints and two-edge/FIFO/TURN gates are absent. Spikes prove one WebCodecs object, not hardware; GCC+RTX is no-go and no-RTX weakens stats.
|
||||
- Browser fanout is host two/viewer one; any accepted endpoint relay stays capped at two downstream edges.
|
||||
- ADR-0005's candidate is process-wide STUN-only ordinary ICE plus separate LiveKit SFU/UDP and bounded failure, with no all-room TURN wire. It is default-off and lacks public gates; the old release is rollback.
|
||||
- ADR-0005's candidate is process-wide STUN-only ordinary ICE plus separate LiveKit SFU/UDP and bounded failure, with no all-room TURN wire. It is default-off; enabling it requires non-empty exact room IDs, and missing/blank fails startup. The old release is isolated rollback.
|
||||
- Pinned LiveKit 1.13.5 Dynacast enables all qualities at or below the room's maximum request, so a `HIGH` root is expected to keep `LOW` enabled. It remains a bounded rejection/verification spike, not evidence that on-demand `LOW` can stop.
|
||||
- The corrected standby smoke is localhost/headless/video-only; public DNS/TLS reuse, transport, audio, shaping, load, mobile, endurance, and sub-25 ms overlap remain open.
|
||||
|
||||
|
||||
+22
-16
@@ -2,11 +2,11 @@
|
||||
|
||||
## 2026-08-18 14:45
|
||||
|
||||
状态:已接受的首个 PoC 基线。本文不接受后续媒体拓扑;peer-assisted 仅由 ADR-0004 提议为独立实验。
|
||||
状态:首个 PoC 基线及其已接受扩展的当前设计。`769de201f7cc` 是仍在运行的旧 production P2P/TURN 基线;下文明确标注的 repository candidate 是隔离验证中的 STUN-only ordinary ICE、exact-room peer-assisted 与 LiveKit SFU/UDP,二者不是同进程兼容路径。
|
||||
|
||||
## 目标与边界
|
||||
|
||||
首个 PoC 验证一名分享者向小范围朋友进行低延迟游戏画面分享。观看端使用普通桌面或手机浏览器;媒体对每名观看者独立进行 ICE,能直连时走 P2P,只有失败的链路使用 coturn。房间默认最多八名观看者,可配置范围为 1 至 16;八人是接入默认值,不是未经真实 1:8 测试即可宣称的性能能力。
|
||||
产品面向一名分享者和小范围可信朋友的低延迟游戏画面分享。观看端使用普通桌面或手机浏览器;每条媒体边独立 ICE。旧 production 能直连时走 P2P、失败边使用 coturn;repository candidate 的普通边只接收自托管 STUN,peer 恢复耗尽后由 LiveKit ICE/UDP virtual parent 服务一至两个必要 roots,再失败则有界明确结束。房间默认最多八名观看者,可配置范围为 1 至 16;八人是接入默认值,不是未经真实 1:8 测试即可宣称的性能能力。
|
||||
|
||||
本阶段必须形成完整的最小纵向链路:
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
- 超过部署配置上限的观看者被明确拒绝,不静默超载;
|
||||
- 在代码、测试和真实浏览器验证完成前,不宣称达到延迟或画质目标。
|
||||
|
||||
本基线不实现账号数据库、通用业务数据库、Redis、SFU、simulcast/SVC、观看者转发树、语音聊天、Electron、原生捕获、PWA、录制、遥测平台或多地区调度。唯一持久化例外是可选的 `node:sqlite` 房间身份表。后续 SFU 与 peer-assisted 工作必须留在各自分支和 ADR 中,不能反向把实验复杂度预埋进该基线。
|
||||
首个基线不实现账号数据库、通用业务数据库、Redis、simulcast/SVC、语音聊天、Electron、原生捕获、PWA、录制、遥测平台或多地区调度。唯一持久化例外是可选的 `node:sqlite` 房间身份表。后来接受的 peer-assisted/SFU candidate 只通过 ADR-0004/0005 的现有窄 owner 扩展,不引入第二套路由器或通用优化框架。
|
||||
|
||||
## 技术栈决策
|
||||
|
||||
@@ -43,12 +43,14 @@ flowchart LR
|
||||
H[分享者 Web] -->|HTTPS: 建房| A[Node 应用服务]
|
||||
H <-->|WSS: 鉴权与信令| A
|
||||
V[观看者 Web 1..N] <-->|WSS: 鉴权与信令| A
|
||||
H <-->|每人独立 DTLS-SRTP P2P| V
|
||||
H -.仅失败链路.-> T[coturn]
|
||||
T -.加密媒体中继.-> V
|
||||
H <-->|ordinary direct/peer DTLS-SRTP UDP| V
|
||||
H -.peer 路径耗尽.-> S[LiveKit SFU/UDP virtual parent]
|
||||
S -.一至两个必要 roots.-> V
|
||||
H -.地址发现.-> T[coturn STUN-only]
|
||||
V -.地址发现.-> T
|
||||
```
|
||||
|
||||
每个观看者的候选检查和最终路径互不影响。同一房间可以同时存在 direct 和 relay 连接。中心房间服务不复制、解码或转发媒体。
|
||||
每个观看者的候选检查和最终路径互不影响。同一 candidate 房间可同时存在健康 direct/peer 子树与必要的 SFU roots;Node 房间服务不复制、解码或转发媒体,LiveKit 只在有界 root 路径上转发。
|
||||
|
||||
## 代码布局
|
||||
|
||||
@@ -183,7 +185,9 @@ SVC 是 simulcast 与 LiveKit/Dynacast 均未满足后的第三个标准候选
|
||||
## 媒体传输配置
|
||||
|
||||
当前仓库候选已经删除旧全房 TURN contract。`ServerConfig` 只接受
|
||||
`STUN_URLS`;生产缺失 STUN 启动即失败。`authenticated.iceConfig` 是静态
|
||||
`STUN_URLS`;已删除的 `TURN_URLS`、`TURN_SHARED_SECRET` 或
|
||||
`TURN_CREDENTIAL_TTL_SECONDS` 任一存在(包括空值)都会启动失败,避免部署
|
||||
误以为旧兼容配置仍生效。生产缺失 STUN 也启动失败。`authenticated.iceConfig` 是静态
|
||||
STUN snapshot,只含 `iceServers`,不含 TURN URL、username、credential、
|
||||
expiry 或 `relayAvailable`。信令协议也不再接受 `refresh-ice` 或发送
|
||||
`ice-config`;WebSocket 重连后的新 `authenticated` 自然取得当前 snapshot。
|
||||
@@ -191,9 +195,11 @@ expiry 或 `relayAvailable`。信令协议也不再接受 `refresh-ice` 或发
|
||||
普通 direct/peer `RTCPeerConnection` 与 LiveKit participant 是两个明确的
|
||||
ICE 域。普通边只消费 `authenticated.iceConfig`;SFU publisher/subscriber
|
||||
只消费 revision-bound `sfu-config {url, token}`,再由 LiveKit SDK 与服务端
|
||||
协商自己的 candidates。tracked LiveKit 配置只开放 UDP mux,不配置
|
||||
`rtc.tcp_port`、external TURN 或 embedded TURN。Node 应用不能替代部署
|
||||
验证来证明该 UDP listener 从公网可达。
|
||||
协商自己的 candidates。tracked LiveKit 配置只开放 UDP mux,显式使用
|
||||
`tcp_port: 0`、`allow_tcp_fallback: false` 和部署自托管 `stun_servers`,不配置
|
||||
external TURN 或 embedded TURN。Node 应用不能替代部署
|
||||
验证来证明该 UDP listener 从公网可达;自托管 `stun_servers` 也避免 pinned
|
||||
LiveKit 1.13.5 继承默认公共 Google STUN。
|
||||
|
||||
当前可执行梯级是 `direct/peer UDP -> SFU ICE/UDP -> failure`。Viewer 的
|
||||
现有两次有界 ICE restart/rebuild 后报告 route failure;router 先尝试局部
|
||||
@@ -203,7 +209,7 @@ reparent,再在 root budget 内准备 SFU,最终没有可行 route 时返回
|
||||
|
||||
旧 production release `769de201f7cc` 仍需要 coturn TURN/UDP+TCP。它作为
|
||||
独立旧实例保留到新 candidate canary 通过;新代码不根据 room allowlist
|
||||
保留 legacy TURN 分支。`PEER_ASSISTED_ROOM_IDS` 只灰度 topology/SFU route
|
||||
保留旧 release TURN 兼容分支。`PEER_ASSISTED_ROOM_IDS` 只灰度 topology/SFU route
|
||||
wire,进程内所有房间的 ordinary ICE 都是 STUN-only。因此验证与回滚必须
|
||||
使用隔离 candidate/旧实例,不能假设同进程未命中房间仍有旧 transport。
|
||||
|
||||
@@ -260,8 +266,8 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
|
||||
- 全站密码以定长摘要配合常量时间比较;access cookie 由服务端 HMAC 签名且不含账号或可查询的 session ID。host token 只保存摘要并以常量时间验证;认证和建房响应设置 `Cache-Control: no-store`。
|
||||
- HTTP body、WebSocket payload、总连接数、未鉴权连接数、输出缓冲、房间总数、观看人数和 candidate 缓存都有硬上限;无法解析的 upgrade request-target 在未鉴权边界返回 HTTP 400,不允许异常逃逸到进程顶层。
|
||||
- 应用日志不得主动记录 IP;反向代理、STUN 和 LiveKit 为提供网络服务必然可见源地址,部署时需设置最短必要留存与访问控制。
|
||||
- 自托管 coturn 必须启用 `stun-only` 并关闭 TCP、TLS 和 DTLS listeners;不得配置 relay port range、TURN auth secret 或匿名 TURN。未来 selected-edge TURN 由独立设计取代这份 STUN-only 配置,而不是在当前 wire 上加回全房 credential。
|
||||
- 分享者直连会向可信观看者暴露网络地址。需要隐藏 IP 时才提供强制 relay 诊断选项,并明确其服务器带宽成本。
|
||||
- 自托管 coturn 必须启用 `stun-only` 及 `no-tcp`/`no-tls`,不得配置 relay port range、TURN auth secret、证书或匿名 TURN;coturn 4.17.2 已弃用 `no-dtls`,tracked 配置不再使用它。未来 selected-edge TURN 由独立设计取代这份 STUN-only 配置,而不是在当前 wire 上加回全房 credential。
|
||||
- 分享者直连会向可信观看者暴露网络地址。当前 candidate 不保留 force-relay 产品分支;未来 selected-edge TURN 若被证据接受,配置、授权、UI 和测试必须原子引入。
|
||||
|
||||
## 验证计划
|
||||
|
||||
@@ -271,7 +277,7 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
|
||||
- RoomStore 的随机临时房间、TTL、host token 摘要验证、停止分享等待、默认八人上限、自定义 1 至 16 边界和超额拒绝;
|
||||
- SQLite 房间库从 `1` 自增、重启恢复、持久房间无过期时间、数据最小化、数据库路径无全站密码时启动失败;
|
||||
- STUN URL 严格校验、生产 STUN 必需、ordinary ICE 不含 username/credential、旧 `refresh-ice`/`ice-config` 被协议拒绝,以及 LiveKit `sfu-config` 独立边界;
|
||||
- 协议非法 JSON、未知消息、错误方向、跨房间目标和 payload 限制;
|
||||
- 单一 `screener-v1` 信令 literal、旧页面/新服务或新页面/旧服务 mismatch 的一次性刷新终态,以及协议非法 JSON、未知消息、错误方向、跨房间目标和 payload 限制;
|
||||
- 质量协议的 host 授权、严格字段与数值范围、last-wins、当前/未来 relay、已配置 SFU 和普通 P2P wire 兼容;sender 的四字段 requested/applied 读回、拒绝与持续受限提示;
|
||||
- HTTP/WS 集成:密码模式下 host/viewer gate、建房和 upgrade 只认 cookie 且无建房 Bearer 旁路;一名 host、多名 viewer、定向 offer/answer/candidate、连接上限、grace 内恢复、显式 restart/rebuild、离开和停止分享后的等待状态;
|
||||
- 客户端策略与 stats 解析:会话替换不重连,本地 TURN protocol 与 ICE protocol 分离,远端 TURN transport 保持未知;
|
||||
@@ -281,7 +287,7 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
|
||||
|
||||
- 同机双标签页与同 LAN direct;
|
||||
- 真实跨网络、同房间 direct/peer UDP + SFU/UDP root;
|
||||
- CGNAT、双 NAT、移动热点和普通家宽下使用隔离 candidate,LiveKit 显式关闭 TCP fallback 且不配置 TURN,验证 host 与 roots 使用 SFU/UDP;人为封锁 UDP 时必须有界明确失败。旧 production release 留在独立实例作为回滚,不在同进程保留 legacy transport;
|
||||
- CGNAT、双 NAT、移动热点和普通家宽下使用隔离 candidate,LiveKit 显式关闭 TCP fallback 且不配置 TURN,验证 host 与 roots 使用 SFU/UDP;人为封锁 UDP 时必须有界明确失败。旧 production release 留在独立实例作为回滚,不在同进程保留旧 transport;
|
||||
- Windows Chrome/Edge 的 tab/window/monitor 音轨有/无、同时语音通话和 video-only;Windows 11 原生候选另测 game process tree、通知、无渲染流与进程重启,Windows 10 记录明确不支持/未解决;
|
||||
- Android Chrome 与 iOS Safari 的播放手势、旋转、前后台和网络切换;
|
||||
- 一名分享者、八名异构观看者连续 30 分钟,同时记录较低人数基线、实际上行、编码负载和首帧时间。真实 1:8 未完成前不得把默认上限写成性能承诺。
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@
|
||||
|
||||
### P1 - 重要功能
|
||||
|
||||
- [ ] 实验路由按房间灰度:部署开启 `PEER_ASSISTED_MEDIA` 时可用严格的房间 ID allowlist 只让指定房间进入 peer-assisted 与已配置的 SFU 路径;未命中房间继续使用普通 P2P 拓扑及其质量拒绝、停止、重连和删除语义,但 STUN-only ordinary ICE 契约是进程级迁移,不为未命中房间保留旧 TURN wire。旧 production release 与新 candidate 必须用隔离实例验证和回滚,不能在产品代码建立长期双 transport 分支。缺失或空 allowlist 为兼容已有路由实验而表示全部房间,因此隔离灰度必须显式填写至少一个合法 ID;非法或重复配置启动即失败。该能力仅由部署控制,不增加 UI、用户选择、百分比发布或第二套路由器。
|
||||
- [ ] 实验路由按房间灰度:部署开启 `PEER_ASSISTED_MEDIA` 时必须同时提供非空、严格的房间 ID allowlist,只有指定房间进入 peer-assisted 与已配置的 SFU 路径;缺失、空值、非法或重复配置启动即失败,绝不 fail-open 为全房。未命中房间继续使用当前 ordinary P2P 拓扑及其质量拒绝、停止、重连和删除语义,但 STUN-only ordinary ICE 契约是进程级迁移,不为未命中房间保留旧 TURN wire。旧 production release 与新 candidate 必须用隔离实例验证和回滚,不能在产品代码建立长期双 transport 分支。exact-room 只服务本阶段验证;验收后以独立 coherent change 退役灰度边界,不能靠清空变量暗中放量。该能力不增加 UI、用户选择、百分比发布或第二套路由器。
|
||||
|
||||
- [ ] 质量控制扩展:推荐档位仍是默认入口;折叠高级区只允许 720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling,以及清晰/平衡/流畅三种偏好。直播中显式应用后才生效,避免滑杆产生连续控制流量。当前 Web 发送端不提供音频声道、采样率、Opus 码率、stereo、DTX 或 FEC 控件:display capture 未把声道和采样率定义为可移植控制,标准音频 `maxBitrate` 只是可能导致更低质量或停播的发送上限,其他项依赖 codec/fmtp 协商而没有可移植 sender setter。除非真实音频矩阵证明用户问题、标准 API 能应用并读回且实际结果可独立观测,否则不得为这些控件新增应用层 SDP munging 或用默认值制造伪控制。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。
|
||||
- [ ] 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。
|
||||
|
||||
@@ -11,6 +11,10 @@ import {
|
||||
type ScreenerServer,
|
||||
} from "../src/server/app";
|
||||
import { loadConfig } from "../src/server/config";
|
||||
import {
|
||||
RoomStore,
|
||||
type RoomStoreOptions,
|
||||
} from "../src/server/room-store";
|
||||
import {
|
||||
QUALITY_PROFILES,
|
||||
QUALITY_RESOLUTIONS,
|
||||
@@ -23,6 +27,21 @@ const PROFILE_SETTINGS = QUALITY_PROFILES;
|
||||
type ProfileId = QualityProfileId;
|
||||
type PageRole = "host" | "viewer";
|
||||
|
||||
class BenchmarkRoomStore extends RoomStore {
|
||||
constructor(
|
||||
options: RoomStoreOptions,
|
||||
private readonly exactPeerRooms: Set<string>,
|
||||
) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
override createRoom() {
|
||||
const room = super.createRoom();
|
||||
this.exactPeerRooms.add(room.roomId);
|
||||
return room;
|
||||
}
|
||||
}
|
||||
|
||||
export interface BenchmarkConfig {
|
||||
chromePath: string;
|
||||
viewerCounts: number[];
|
||||
@@ -1935,19 +1954,31 @@ export async function main(): Promise<number> {
|
||||
const debugPort = await reservePort();
|
||||
const baseUrl = `http://127.0.0.1:${appPort}`;
|
||||
profileDirectory = await mkdtemp(join(tmpdir(), "screener-peer-benchmark-"));
|
||||
const exactPeerRooms = new Set(["1"]);
|
||||
const serverConfig = loadConfig({
|
||||
NODE_ENV: "development",
|
||||
PORT: String(appPort),
|
||||
LISTEN_HOST: "127.0.0.1",
|
||||
PUBLIC_BASE_URL: baseUrl,
|
||||
ALLOWED_ORIGINS: baseUrl,
|
||||
ACCESS_PASSWORD: "",
|
||||
ROOM_DATABASE_PATH: "",
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: "1",
|
||||
MAX_VIEWERS_PER_ROOM: String(Math.max(...config.viewerCounts)),
|
||||
STUN_URLS: "",
|
||||
});
|
||||
serverConfig.peerAssistedRoomIds = exactPeerRooms;
|
||||
server = await createScreenerServer({
|
||||
config: loadConfig({
|
||||
NODE_ENV: "development",
|
||||
PORT: String(appPort),
|
||||
LISTEN_HOST: "127.0.0.1",
|
||||
PUBLIC_BASE_URL: baseUrl,
|
||||
ALLOWED_ORIGINS: baseUrl,
|
||||
ACCESS_PASSWORD: "",
|
||||
ROOM_DATABASE_PATH: "",
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
MAX_VIEWERS_PER_ROOM: String(Math.max(...config.viewerCounts)),
|
||||
STUN_URLS: "",
|
||||
}),
|
||||
config: serverConfig,
|
||||
roomStore: new BenchmarkRoomStore(
|
||||
{
|
||||
ttlMs: serverConfig.roomTtlMs,
|
||||
maxRooms: serverConfig.maxRooms,
|
||||
maxViewersPerRoom: serverConfig.maxViewersPerRoom,
|
||||
},
|
||||
exactPeerRooms,
|
||||
),
|
||||
});
|
||||
await server.listen(appPort, "127.0.0.1");
|
||||
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
import {
|
||||
decodeServerMessage,
|
||||
SIGNALING_PROTOCOL,
|
||||
type ClientMessage,
|
||||
type ServerMessage,
|
||||
} from "../../shared/protocol";
|
||||
import type { SignalConnectionState } from "../types";
|
||||
import { getSession } from "./api";
|
||||
|
||||
type WithoutType<T> = T extends { type: string } ? Omit<T, "type"> : never;
|
||||
type SignalingIdentity = WithoutType<
|
||||
type WithoutProtocolEnvelope<T> = T extends {
|
||||
type: string;
|
||||
protocol: string;
|
||||
}
|
||||
? Omit<T, "type" | "protocol">
|
||||
: never;
|
||||
type SignalingIdentity = WithoutProtocolEnvelope<
|
||||
Extract<ClientMessage, { type: "authenticate" }>
|
||||
>;
|
||||
|
||||
interface SignalingEvents {
|
||||
onMessage: (message: ServerMessage) => void;
|
||||
onStatus: (status: SignalConnectionState) => void;
|
||||
onProtocolError: (message: string) => void;
|
||||
onTerminated: (message: string) => void;
|
||||
onAccessRequired: () => void;
|
||||
}
|
||||
@@ -27,10 +32,14 @@ const FATAL_SIGNAL_ERRORS = new Set([
|
||||
"HOST_ALREADY_CONNECTED",
|
||||
]);
|
||||
const SESSION_REPLACED_CLOSE_CODE = 4001;
|
||||
const INVALID_MESSAGE_CLOSE_CODE = 1008;
|
||||
const PROTOCOL_REFRESH_MESSAGE = "页面版本已更新,请刷新后重试";
|
||||
const TERMINAL_SEND_TIMEOUT_MS = 15_000;
|
||||
|
||||
export function shouldReconnectSignaling(code: number): boolean {
|
||||
return code !== SESSION_REPLACED_CLOSE_CODE;
|
||||
return (
|
||||
code !== SESSION_REPLACED_CLOSE_CODE && code !== INVALID_MESSAGE_CLOSE_CODE
|
||||
);
|
||||
}
|
||||
|
||||
function signalUrl(): string {
|
||||
@@ -120,6 +129,7 @@ export class SignalingClient {
|
||||
}
|
||||
const authenticate: ClientMessage = {
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
...this.identity,
|
||||
};
|
||||
socket.send(JSON.stringify(authenticate));
|
||||
@@ -138,7 +148,16 @@ export class SignalingClient {
|
||||
try {
|
||||
message = decodeServerMessage(event.data);
|
||||
} catch {
|
||||
this.events.onProtocolError("信令服务返回了无法识别的消息");
|
||||
this.terminateForProtocolMismatch();
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
message.type === "error" &&
|
||||
message.code === "INVALID_MESSAGE" &&
|
||||
!this.authenticated
|
||||
) {
|
||||
this.terminateForProtocolMismatch();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -205,6 +224,11 @@ export class SignalingClient {
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private terminateForProtocolMismatch(): void {
|
||||
this.stop();
|
||||
this.events.onTerminated(PROTOCOL_REFRESH_MESSAGE);
|
||||
}
|
||||
|
||||
private checkAccess(): void {
|
||||
if (this.accessCheck) {
|
||||
return;
|
||||
|
||||
@@ -110,7 +110,6 @@ function closeAbandonedRoom(room: CreateRoomResponse): void {
|
||||
{
|
||||
onMessage: () => undefined,
|
||||
onStatus: () => undefined,
|
||||
onProtocolError: () => undefined,
|
||||
onTerminated: () => undefined,
|
||||
onAccessRequired: () => undefined,
|
||||
},
|
||||
@@ -127,10 +126,6 @@ interface HostPageProps {
|
||||
}
|
||||
|
||||
export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
|
||||
const forceRelay = useMemo(
|
||||
() => new URLSearchParams(window.location.search).get("relay") === "1",
|
||||
[],
|
||||
);
|
||||
const [qualitySettings, setQualitySettings] = useState<QualitySettings>(
|
||||
DEFAULT_QUALITY_SETTINGS,
|
||||
);
|
||||
@@ -613,7 +608,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
|
||||
}
|
||||
},
|
||||
},
|
||||
forceRelay,
|
||||
);
|
||||
peersRef.current.set(peerId, peer);
|
||||
let started: boolean;
|
||||
@@ -933,14 +927,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
|
||||
setSignalStatus(status);
|
||||
}
|
||||
},
|
||||
onProtocolError: (message) => {
|
||||
if (
|
||||
isCurrentGeneration(generation) &&
|
||||
signalRef.current === signal
|
||||
) {
|
||||
setNotice(message);
|
||||
}
|
||||
},
|
||||
onTerminated: (message) => {
|
||||
if (
|
||||
isCurrentGeneration(generation) &&
|
||||
@@ -1208,9 +1194,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
|
||||
: "尚未开始"}
|
||||
</p>
|
||||
</div>
|
||||
{showConnectionDetails && forceRelay && (
|
||||
<span className="diagnostic-badge">强制中继</span>
|
||||
)}
|
||||
{(phase === "live" || phase === "starting") && (
|
||||
<div className="broadcast-actions">
|
||||
{phase === "live" && (
|
||||
|
||||
@@ -60,10 +60,6 @@ type ViewerQualityEvidence = Extract<
|
||||
>;
|
||||
|
||||
export function ViewerPage({ roomId, onAuthorizationRequired }: ViewerPageProps) {
|
||||
const forceRelay = useMemo(
|
||||
() => new URLSearchParams(window.location.search).get("relay") === "1",
|
||||
[],
|
||||
);
|
||||
const [signalStatus, setSignalStatus] =
|
||||
useState<SignalConnectionState>("offline");
|
||||
const [statusText, setStatusText] = useState("正在连接");
|
||||
@@ -134,13 +130,6 @@ export function ViewerPage({ roomId, onAuthorizationRequired }: ViewerPageProps)
|
||||
setSignalStatus(status);
|
||||
}
|
||||
},
|
||||
onProtocolError: (message) => {
|
||||
if (active) {
|
||||
messageAuthority.invalidate();
|
||||
setSfuStandbyUrl(null);
|
||||
setStatusText(message);
|
||||
}
|
||||
},
|
||||
onTerminated: (message) => {
|
||||
if (!active) {
|
||||
return;
|
||||
@@ -234,7 +223,6 @@ export function ViewerPage({ roomId, onAuthorizationRequired }: ViewerPageProps)
|
||||
}
|
||||
},
|
||||
},
|
||||
forceRelay,
|
||||
);
|
||||
viewerRelay.setChild(currentAssignment.childPeerIds[0] ?? null);
|
||||
return viewerRelay;
|
||||
@@ -451,7 +439,6 @@ export function ViewerPage({ roomId, onAuthorizationRequired }: ViewerPageProps)
|
||||
return true;
|
||||
},
|
||||
},
|
||||
forceRelay,
|
||||
);
|
||||
peerRef.current = peer;
|
||||
return peer;
|
||||
@@ -688,7 +675,7 @@ export function ViewerPage({ roomId, onAuthorizationRequired }: ViewerPageProps)
|
||||
viewerRelay?.dispose();
|
||||
viewerRelay = null;
|
||||
};
|
||||
}, [forceRelay, onAuthorizationRequired, roomId]);
|
||||
}, [onAuthorizationRequired, roomId]);
|
||||
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
@@ -770,9 +757,6 @@ export function ViewerPage({ roomId, onAuthorizationRequired }: ViewerPageProps)
|
||||
<p className="section-meta">房间 {roomId}</p>
|
||||
</div>
|
||||
<div className="viewer-badges">
|
||||
{showConnectionDetails && forceRelay && (
|
||||
<span className="diagnostic-badge">强制中继</span>
|
||||
)}
|
||||
<PeerStatusBadge state={peerSnapshot?.connectionState ?? "waiting"} />
|
||||
{showConnectionDetails && (
|
||||
<PathBadge path={peerSnapshot?.metrics.path ?? "unknown"} />
|
||||
|
||||
@@ -83,11 +83,9 @@ export class HostPeer {
|
||||
private stream: MediaStream,
|
||||
private desiredProfile: QualityProfile,
|
||||
private readonly events: HostPeerEvents,
|
||||
private readonly forceRelay = false,
|
||||
) {
|
||||
this.connection = new RTCPeerConnection({
|
||||
iceServers: iceConfig.iceServers,
|
||||
iceTransportPolicy: forceRelay ? "relay" : "all",
|
||||
});
|
||||
this.snapshot = {
|
||||
peerId,
|
||||
@@ -254,7 +252,6 @@ export class HostPeer {
|
||||
try {
|
||||
this.connection.setConfiguration({
|
||||
iceServers: iceConfig.iceServers,
|
||||
iceTransportPolicy: this.forceRelay ? "relay" : "all",
|
||||
});
|
||||
} catch (error) {
|
||||
this.setError(error, "更新 ICE 配置失败");
|
||||
|
||||
@@ -56,7 +56,6 @@ export class ViewerPeer {
|
||||
constructor(
|
||||
iceConfig: IceConfig,
|
||||
private readonly events: ViewerPeerEvents,
|
||||
private readonly forceRelay = false,
|
||||
) {
|
||||
this.currentIceConfig = iceConfig;
|
||||
}
|
||||
@@ -172,7 +171,6 @@ export class ViewerPeer {
|
||||
try {
|
||||
this.connection.setConfiguration({
|
||||
iceServers: iceConfig.iceServers,
|
||||
iceTransportPolicy: this.forceRelay ? "relay" : "all",
|
||||
});
|
||||
} catch (error) {
|
||||
this.setError(error, "更新 ICE 配置失败");
|
||||
@@ -235,7 +233,6 @@ export class ViewerPeer {
|
||||
|
||||
const connection = new RTCPeerConnection({
|
||||
iceServers: this.currentIceConfig.iceServers,
|
||||
iceTransportPolicy: this.forceRelay ? "relay" : "all",
|
||||
});
|
||||
this.connection = connection;
|
||||
this.snapshot = {
|
||||
|
||||
@@ -20,7 +20,6 @@ export class ViewerRelay {
|
||||
private iceConfig: IceConfig,
|
||||
private desiredProfile: QualityProfile,
|
||||
private readonly events: ViewerRelayEvents,
|
||||
private readonly forceRelay = false,
|
||||
) {}
|
||||
|
||||
getSnapshot(): PeerSnapshot | null {
|
||||
@@ -218,7 +217,6 @@ export class ViewerRelay {
|
||||
}
|
||||
},
|
||||
},
|
||||
this.forceRelay,
|
||||
);
|
||||
this.peer = peer;
|
||||
void peer
|
||||
|
||||
+21
-64
@@ -2,6 +2,7 @@ import {
|
||||
MAX_ICE_SERVER_URLS,
|
||||
MAX_VIEWERS_PER_ROOM_LIMIT,
|
||||
roomCodeSchema,
|
||||
stunUrlSchema,
|
||||
} from "../shared/protocol.js";
|
||||
|
||||
export type RuntimeEnvironment = "development" | "test" | "production";
|
||||
@@ -13,6 +14,11 @@ const DEFAULT_MAX_VIEWERS_PER_ROOM = 8;
|
||||
const DEFAULT_MAX_SFU_ROOTS_PER_ROOM = 2;
|
||||
const MAX_SFU_ROOTS_PER_ROOM = 2;
|
||||
const VISIBLE_ASCII_PATTERN = /^[\x21-\x7e]+$/;
|
||||
const REMOVED_TURN_ENVIRONMENT_VARIABLES = [
|
||||
"TURN_URLS",
|
||||
"TURN_SHARED_SECRET",
|
||||
"TURN_CREDENTIAL_TTL_SECONDS",
|
||||
] as const;
|
||||
|
||||
export interface LiveKitFallbackConfig {
|
||||
url: string;
|
||||
@@ -173,17 +179,8 @@ function parseStunUrlList(value: string | undefined): string[] {
|
||||
throw new Error(`${name} must contain at most ${MAX_ICE_SERVER_URLS} URLs`);
|
||||
}
|
||||
return values.map((value) => {
|
||||
let protocol: string;
|
||||
try {
|
||||
protocol = new URL(value).protocol;
|
||||
} catch {
|
||||
throw new Error(`${name} contains an invalid URL`);
|
||||
}
|
||||
if (protocol !== "stun:") {
|
||||
throw new Error(`${name} contains an unsupported URL scheme`);
|
||||
}
|
||||
if (!parseStunEndpoint(value)) {
|
||||
throw new Error(`${name} contains an invalid ICE URL`);
|
||||
if (!stunUrlSchema.safeParse(value).success) {
|
||||
throw new Error(`${name} contains an invalid STUN URL`);
|
||||
}
|
||||
return value;
|
||||
});
|
||||
@@ -220,59 +217,6 @@ function parsePeerAssistedRoomIds(
|
||||
return roomIds;
|
||||
}
|
||||
|
||||
function parseStunEndpoint(value: string): boolean {
|
||||
const schemeSeparator = value.indexOf(":");
|
||||
if (schemeSeparator <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const scheme = value.slice(0, schemeSeparator).toLowerCase();
|
||||
if (scheme !== "stun") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const remainder = value.slice(schemeSeparator + 1);
|
||||
if (!remainder || remainder.includes("#")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (remainder.includes("?")) {
|
||||
return false;
|
||||
}
|
||||
const authorityText = remainder;
|
||||
if (
|
||||
!authorityText ||
|
||||
/[\\/\s]/.test(authorityText) ||
|
||||
authorityText.endsWith(":")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let authority: URL;
|
||||
try {
|
||||
authority = new URL(`http://${authorityText}`);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
!authority.hostname ||
|
||||
authority.username ||
|
||||
authority.password ||
|
||||
authority.pathname !== "/" ||
|
||||
authority.search ||
|
||||
authority.hash
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const port = authority.port ? Number(authority.port) : undefined;
|
||||
if (port === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function toOrigin(value: string): string {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
@@ -284,6 +228,14 @@ function toOrigin(value: string): string {
|
||||
export function loadConfig(
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
): ServerConfig {
|
||||
for (const name of REMOVED_TURN_ENVIRONMENT_VARIABLES) {
|
||||
if (Object.prototype.hasOwnProperty.call(environment, name)) {
|
||||
throw new Error(
|
||||
`${name} is no longer supported; ordinary ICE accepts STUN_URLS only`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const nodeEnv = parseEnvironment(environment.NODE_ENV);
|
||||
const port = parsePositiveInteger(environment.PORT, 8787, "PORT");
|
||||
if (port > 65_535) {
|
||||
@@ -341,6 +293,11 @@ export function loadConfig(
|
||||
"PEER_ASSISTED_ROOM_IDS requires PEER_ASSISTED_MEDIA=true",
|
||||
);
|
||||
}
|
||||
if (peerAssistedMedia && !peerAssistedRoomIds) {
|
||||
throw new Error(
|
||||
"PEER_ASSISTED_MEDIA=true requires non-empty PEER_ASSISTED_ROOM_IDS",
|
||||
);
|
||||
}
|
||||
if (livekitFallback && !peerAssistedMedia) {
|
||||
throw new Error("LiveKit fallback requires PEER_ASSISTED_MEDIA=true");
|
||||
}
|
||||
|
||||
+27
-16
@@ -8,6 +8,7 @@ import {
|
||||
DEFAULT_QUALITY_SETTINGS,
|
||||
MAX_SIGNAL_BYTES,
|
||||
MAX_VIEWER_QUALITY_EVIDENCE_BYTES,
|
||||
SIGNALING_PROTOCOL,
|
||||
VIEWER_QUALITY_EVIDENCE_INTERVAL_MS,
|
||||
decodeClientMessage,
|
||||
type ClientMessage,
|
||||
@@ -124,13 +125,15 @@ export class SignalingServer {
|
||||
if (options.sfuFallback && !options.peerAssistedMedia) {
|
||||
throw new Error("SFU fallback requires peer-assisted media");
|
||||
}
|
||||
if (
|
||||
options.peerAssistedRoomIds &&
|
||||
options.peerAssistedRoomIds.size > 0 &&
|
||||
!options.peerAssistedMedia
|
||||
) {
|
||||
if (options.peerAssistedRoomIds && !options.peerAssistedMedia) {
|
||||
throw new Error("Peer-assisted room IDs require peer-assisted media");
|
||||
}
|
||||
if (
|
||||
options.peerAssistedMedia &&
|
||||
(!options.peerAssistedRoomIds || options.peerAssistedRoomIds.size === 0)
|
||||
) {
|
||||
throw new Error("Peer-assisted media requires exact room IDs");
|
||||
}
|
||||
if (options.peerAssistedMedia) {
|
||||
this.hybridMediaRouter = new HybridMediaRouter({
|
||||
roomStore: options.roomStore,
|
||||
@@ -254,11 +257,25 @@ export class SignalingServer {
|
||||
}
|
||||
|
||||
private handleMessage(socket: WebSocket, encoded: string): void {
|
||||
const state = this.socketStates.get(socket);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
let message: ClientMessage;
|
||||
try {
|
||||
message = decodeClientMessage(encoded);
|
||||
} catch {
|
||||
this.rejectInvalidMessage(socket);
|
||||
if (!state.authenticated) {
|
||||
this.sendError(
|
||||
socket,
|
||||
"AUTH_REQUIRED",
|
||||
"页面版本已更新,请刷新后重试",
|
||||
);
|
||||
socket.close(4001, "Protocol mismatch");
|
||||
} else {
|
||||
this.rejectInvalidMessage(socket);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
@@ -269,10 +286,6 @@ export class SignalingServer {
|
||||
return;
|
||||
}
|
||||
|
||||
const state = this.socketStates.get(socket);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
if (!state.authenticated) {
|
||||
if (message.type !== "authenticate") {
|
||||
this.sendError(socket, "AUTH_REQUIRED", "Authenticate before sending messages");
|
||||
@@ -401,6 +414,7 @@ export class SignalingServer {
|
||||
|
||||
const authenticatedMessage = {
|
||||
type: "authenticated" as const,
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
role: participant.role,
|
||||
peerId: participant.peerId,
|
||||
roomExpiresAt: participant.expiresAt,
|
||||
@@ -409,7 +423,7 @@ export class SignalingServer {
|
||||
connectionId,
|
||||
viewerPeerIds: [...participant.viewerPeerIds],
|
||||
iceConfig: this.iceConfig(),
|
||||
};
|
||||
} satisfies Extract<ServerMessage, { type: "authenticated" }>;
|
||||
if (hybridState) {
|
||||
this.send(socket, {
|
||||
...authenticatedMessage,
|
||||
@@ -589,7 +603,6 @@ export class SignalingServer {
|
||||
this.handleViewerQualityEvidence(socket, authenticated, message);
|
||||
return;
|
||||
case "stop-sharing":
|
||||
case "close-room":
|
||||
if (authenticated.role !== "host") {
|
||||
this.sendError(socket, "FORBIDDEN", "Only the host may stop sharing");
|
||||
return;
|
||||
@@ -598,8 +611,7 @@ export class SignalingServer {
|
||||
authenticated.shareGeneration === null ||
|
||||
this.shareGenerationsByRoom.get(authenticated.roomId) !==
|
||||
authenticated.shareGeneration ||
|
||||
(message.type === "stop-sharing" &&
|
||||
message.shareGeneration !== undefined &&
|
||||
(message.shareGeneration !== undefined &&
|
||||
message.shareGeneration !== authenticated.shareGeneration)
|
||||
) {
|
||||
socket.close(4001, "Sharing generation replaced");
|
||||
@@ -1050,8 +1062,7 @@ export class SignalingServer {
|
||||
if (!this.hybridMediaRouter) {
|
||||
return false;
|
||||
}
|
||||
const allowlist = this.options.peerAssistedRoomIds;
|
||||
return !allowlist || allowlist.size === 0 || allowlist.has(roomId);
|
||||
return this.options.peerAssistedRoomIds?.has(roomId) ?? false;
|
||||
}
|
||||
|
||||
private hasConnectionCapacity(): boolean {
|
||||
|
||||
+41
-4
@@ -4,6 +4,7 @@ import { isCanonicalVideoCodecEvidence } from "./video-codec-evidence.js";
|
||||
|
||||
export const MAX_VIEWERS_PER_ROOM_LIMIT = 16;
|
||||
export const MAX_SIGNAL_BYTES = 64 * 1024;
|
||||
export const SIGNALING_PROTOCOL = "screener-v1";
|
||||
export const ROOM_CODE_LENGTH = 12;
|
||||
export const MAX_MEDIA_ROUTE_REVISION = Number.MAX_SAFE_INTEGER;
|
||||
export const MAX_SFU_TOKEN_LENGTH = 8 * 1024;
|
||||
@@ -88,11 +89,46 @@ export const relayDownstreamEdgesSchema = z.union([
|
||||
]);
|
||||
export type RelayDownstreamEdges = z.infer<typeof relayDownstreamEdgesSchema>;
|
||||
|
||||
const stunUrlSchema = z
|
||||
function isValidStunUrl(value: string): boolean {
|
||||
const schemeSeparator = value.indexOf(":");
|
||||
if (
|
||||
schemeSeparator <= 0 ||
|
||||
value.slice(0, schemeSeparator).toLowerCase() !== "stun"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const authorityText = value.slice(schemeSeparator + 1);
|
||||
if (
|
||||
!authorityText ||
|
||||
/[\\/\s?#]/.test(authorityText) ||
|
||||
authorityText.endsWith(":")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let authority: URL;
|
||||
try {
|
||||
authority = new URL(`http://${authorityText}`);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return Boolean(
|
||||
authority.hostname &&
|
||||
!authority.username &&
|
||||
!authority.password &&
|
||||
authority.pathname === "/" &&
|
||||
!authority.search &&
|
||||
!authority.hash &&
|
||||
(!authority.port || Number(authority.port) > 0),
|
||||
);
|
||||
}
|
||||
|
||||
export const stunUrlSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(512)
|
||||
.regex(/^stun:/i);
|
||||
.refine(isValidStunUrl, { message: "Invalid STUN URL" });
|
||||
|
||||
const iceServerSchema = z
|
||||
.object({
|
||||
@@ -281,6 +317,7 @@ const authenticateMessageSchema = z.discriminatedUnion("role", [
|
||||
z
|
||||
.object({
|
||||
type: z.literal("authenticate"),
|
||||
protocol: z.literal(SIGNALING_PROTOCOL),
|
||||
roomId: roomCodeSchema,
|
||||
role: z.literal("host"),
|
||||
token: tokenSchema,
|
||||
@@ -291,6 +328,7 @@ const authenticateMessageSchema = z.discriminatedUnion("role", [
|
||||
z
|
||||
.object({
|
||||
type: z.literal("authenticate"),
|
||||
protocol: z.literal(SIGNALING_PROTOCOL),
|
||||
roomId: roomCodeSchema,
|
||||
role: z.literal("viewer"),
|
||||
clientId: opaqueIdSchema,
|
||||
@@ -355,8 +393,6 @@ export const clientMessageSchema = z.union([
|
||||
shareGeneration: opaqueIdSchema.optional(),
|
||||
})
|
||||
.strict(),
|
||||
// Kept as a compatibility alias while previously deployed clients age out.
|
||||
z.object({ type: z.literal("close-room") }).strict(),
|
||||
z.object({ type: z.literal("abandon-room") }).strict(),
|
||||
]);
|
||||
export type ClientMessage = z.infer<typeof clientMessageSchema>;
|
||||
@@ -375,6 +411,7 @@ const errorCodeSchema = z.enum([
|
||||
|
||||
const authenticatedMessageShape = {
|
||||
type: z.literal("authenticated"),
|
||||
protocol: z.literal(SIGNALING_PROTOCOL),
|
||||
role: roleSchema,
|
||||
peerId: opaqueIdSchema,
|
||||
roomExpiresAt: z.string().datetime().nullable(),
|
||||
|
||||
@@ -203,9 +203,79 @@ describe("room codes", () => {
|
||||
describe("client signaling recovery policy", () => {
|
||||
it("does not reconnect a session that another tab replaced", () => {
|
||||
expect(shouldReconnectSignaling(4001)).toBe(false);
|
||||
expect(shouldReconnectSignaling(1008)).toBe(false);
|
||||
expect(shouldReconnectSignaling(1006)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
JSON.stringify({
|
||||
type: "error",
|
||||
code: "INVALID_MESSAGE",
|
||||
message: "Message is invalid",
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: "authenticated",
|
||||
role: "viewer",
|
||||
peerId: "viewer_12345678",
|
||||
roomExpiresAt: null,
|
||||
maxViewers: 8,
|
||||
hostOnline: true,
|
||||
connectionId: null,
|
||||
viewerPeerIds: [],
|
||||
iceConfig: { iceServers: [] },
|
||||
}),
|
||||
])("terminates once when an old server uses an incompatible protocol", (payload) => {
|
||||
const sockets: FakeWebSocket[] = [];
|
||||
class FakeWebSocket extends EventTarget {
|
||||
static readonly CLOSING = 2;
|
||||
readyState = 1;
|
||||
readonly send = vi.fn();
|
||||
readonly close = vi.fn();
|
||||
|
||||
constructor(readonly url: string) {
|
||||
super();
|
||||
sockets.push(this);
|
||||
}
|
||||
}
|
||||
vi.stubGlobal("WebSocket", FakeWebSocket);
|
||||
vi.stubGlobal("window", {
|
||||
location: new URL("https://share.test/r/123456789012"),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
});
|
||||
const onTerminated = vi.fn();
|
||||
const signal = new SignalingClient(
|
||||
{
|
||||
roomId: "123456789012",
|
||||
role: "viewer",
|
||||
clientId: "viewer-client",
|
||||
},
|
||||
{
|
||||
onMessage: () => undefined,
|
||||
onStatus: () => undefined,
|
||||
onTerminated,
|
||||
onAccessRequired: () => undefined,
|
||||
},
|
||||
);
|
||||
|
||||
signal.start();
|
||||
sockets[0]!.dispatchEvent(new Event("open"));
|
||||
expect(JSON.parse(String(sockets[0]!.send.mock.calls[0]![0]))).toMatchObject({
|
||||
type: "authenticate",
|
||||
protocol: "screener-v1",
|
||||
});
|
||||
const message = new Event("message");
|
||||
Object.defineProperty(message, "data", { value: payload });
|
||||
sockets[0]!.dispatchEvent(message);
|
||||
|
||||
expect(onTerminated).toHaveBeenCalledOnce();
|
||||
expect(onTerminated).toHaveBeenCalledWith(
|
||||
"页面版本已更新,请刷新后重试",
|
||||
);
|
||||
expect(sockets[0]!.close).toHaveBeenCalledOnce();
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("returns to the access gate after an unauthorized upgrade", async () => {
|
||||
const sockets: FakeWebSocket[] = [];
|
||||
class FakeWebSocket extends EventTarget {
|
||||
@@ -243,7 +313,6 @@ describe("client signaling recovery policy", () => {
|
||||
{
|
||||
onMessage: () => undefined,
|
||||
onStatus: (status) => statuses.push(status),
|
||||
onProtocolError: () => undefined,
|
||||
onTerminated: () => undefined,
|
||||
onAccessRequired,
|
||||
},
|
||||
|
||||
@@ -40,7 +40,7 @@ describe("peer-assisted client assignment", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves legacy viewer signaling untargeted", () => {
|
||||
it("leaves ordinary viewer signaling untargeted", () => {
|
||||
expect(viewerSignalMessage(false, "host_12345678", offer)).toEqual({
|
||||
type: "signal",
|
||||
payload: offer,
|
||||
|
||||
+28
-4
@@ -5,6 +5,7 @@ import {
|
||||
MAX_SFU_TOKEN_LENGTH,
|
||||
MAX_VIEWER_QUALITY_EVIDENCE_BYTES,
|
||||
MAX_VIEWERS_PER_ROOM_LIMIT,
|
||||
SIGNALING_PROTOCOL,
|
||||
clientMessageSchema,
|
||||
decodeClientMessage,
|
||||
participantRouteAssignmentSchema,
|
||||
@@ -60,17 +61,36 @@ describe("client signaling protocol", () => {
|
||||
decodeClientMessage(
|
||||
JSON.stringify({
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId,
|
||||
role: "viewer",
|
||||
clientId: "client_12345678",
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ type: "authenticate", role: "viewer" });
|
||||
expect(
|
||||
clientMessageSchema.safeParse({
|
||||
type: "authenticate",
|
||||
roomId,
|
||||
role: "viewer",
|
||||
clientId: "client_12345678",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
clientMessageSchema.safeParse({
|
||||
type: "authenticate",
|
||||
protocol: "screener-v0",
|
||||
roomId,
|
||||
role: "viewer",
|
||||
clientId: "client_12345678",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects unknown fields and malformed tokens", () => {
|
||||
const result = clientMessageSchema.safeParse({
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId,
|
||||
role: "host",
|
||||
token: "short",
|
||||
@@ -85,6 +105,7 @@ describe("client signaling protocol", () => {
|
||||
expect(
|
||||
clientMessageSchema.safeParse({
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId,
|
||||
role: "host",
|
||||
token,
|
||||
@@ -94,6 +115,7 @@ describe("client signaling protocol", () => {
|
||||
expect(
|
||||
clientMessageSchema.safeParse({
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId,
|
||||
role: "viewer",
|
||||
token,
|
||||
@@ -103,6 +125,7 @@ describe("client signaling protocol", () => {
|
||||
expect(
|
||||
clientMessageSchema.safeParse({
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId: "1",
|
||||
role: "viewer",
|
||||
clientId: "client_12345678",
|
||||
@@ -111,6 +134,7 @@ describe("client signaling protocol", () => {
|
||||
expect(
|
||||
clientMessageSchema.safeParse({
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId: "0123",
|
||||
role: "viewer",
|
||||
clientId: "client_12345678",
|
||||
@@ -119,6 +143,7 @@ describe("client signaling protocol", () => {
|
||||
expect(
|
||||
clientMessageSchema.safeParse({
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId: "1".repeat(13),
|
||||
role: "viewer",
|
||||
clientId: "client_12345678",
|
||||
@@ -165,7 +190,7 @@ describe("client signaling protocol", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts explicit and legacy sharing-stop messages", () => {
|
||||
it("accepts explicit sharing-stop and abandonment messages", () => {
|
||||
expect(clientMessageSchema.safeParse({ type: "stop-sharing" }).success).toBe(
|
||||
true,
|
||||
);
|
||||
@@ -178,6 +203,7 @@ describe("client signaling protocol", () => {
|
||||
expect(
|
||||
clientMessageSchema.safeParse({
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId,
|
||||
role: "host",
|
||||
token,
|
||||
@@ -185,9 +211,6 @@ describe("client signaling protocol", () => {
|
||||
shareGeneration: "share_generation_12345678",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(clientMessageSchema.safeParse({ type: "close-room" }).success).toBe(
|
||||
true,
|
||||
);
|
||||
expect(clientMessageSchema.safeParse({ type: "abandon-room" }).success).toBe(
|
||||
true,
|
||||
);
|
||||
@@ -425,6 +448,7 @@ describe("server signaling protocol", () => {
|
||||
function authenticatedMessage(maxViewers: number, viewerPeerIds: string[] = []) {
|
||||
return {
|
||||
type: "authenticated",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
role: "host",
|
||||
peerId: "host_12345678",
|
||||
roomExpiresAt: "2026-08-18T18:00:00.000Z",
|
||||
|
||||
+40
-13
@@ -19,6 +19,7 @@ describe("server configuration", () => {
|
||||
it("enables LiveKit fallback only for a complete credential tuple", () => {
|
||||
const config = loadConfig({
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: "1",
|
||||
LIVEKIT_URL: " ws://livekit.test:7880 ",
|
||||
LIVEKIT_API_KEY: " test-key ",
|
||||
LIVEKIT_API_SECRET: ` ${"s".repeat(32)} `,
|
||||
@@ -37,6 +38,7 @@ describe("server configuration", () => {
|
||||
(maxSfuRootsPerRoom) => {
|
||||
const config = loadConfig({
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: "1",
|
||||
LIVEKIT_URL: "wss://livekit.test",
|
||||
LIVEKIT_API_KEY: "test-key",
|
||||
LIVEKIT_API_SECRET: "s".repeat(32),
|
||||
@@ -103,6 +105,7 @@ describe("server configuration", () => {
|
||||
PUBLIC_BASE_URL: "https://share.test",
|
||||
STUN_URLS: "stun:stun.test:3478",
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: "1",
|
||||
LIVEKIT_URL: "ws://livekit.test:7880",
|
||||
LIVEKIT_API_KEY: "test-key",
|
||||
LIVEKIT_API_SECRET: "s".repeat(32),
|
||||
@@ -134,12 +137,14 @@ describe("server configuration", () => {
|
||||
{
|
||||
ACCESS_PASSWORD: "x".repeat(32),
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: "1",
|
||||
LIVEKIT_URL: "wss://livekit.test",
|
||||
LIVEKIT_API_KEY: "test-key",
|
||||
LIVEKIT_API_SECRET: "x".repeat(32),
|
||||
},
|
||||
{
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: "1",
|
||||
LIVEKIT_URL: "wss://livekit.test",
|
||||
LIVEKIT_API_KEY: "x".repeat(32),
|
||||
LIVEKIT_API_SECRET: "x".repeat(32),
|
||||
@@ -151,9 +156,12 @@ describe("server configuration", () => {
|
||||
});
|
||||
|
||||
it("requires an explicit boolean to enable peer-assisted media", () => {
|
||||
expect(loadConfig({ PEER_ASSISTED_MEDIA: "true" }).peerAssistedMedia).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
loadConfig({
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: "1",
|
||||
}).peerAssistedMedia,
|
||||
).toBe(true);
|
||||
expect(loadConfig({ PEER_ASSISTED_MEDIA: "false" }).peerAssistedMedia).toBe(
|
||||
false,
|
||||
);
|
||||
@@ -163,6 +171,7 @@ describe("server configuration", () => {
|
||||
expect(() =>
|
||||
loadConfig({
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: "1",
|
||||
MAX_VIEWERS_PER_ROOM: "9",
|
||||
}),
|
||||
).toThrow(
|
||||
@@ -170,19 +179,25 @@ describe("server configuration", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("parses an optional strict peer-assisted room allowlist", () => {
|
||||
it("requires and parses a strict peer-assisted room allowlist", () => {
|
||||
expect(
|
||||
loadConfig({
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: " 1,123456789012 ",
|
||||
}).peerAssistedRoomIds,
|
||||
).toEqual(new Set(["1", "123456789012"]));
|
||||
expect(
|
||||
loadConfig({
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: " ",
|
||||
}).peerAssistedRoomIds,
|
||||
).toBeUndefined();
|
||||
for (const peerAssistedRoomIds of [undefined, " "]) {
|
||||
expect(() =>
|
||||
loadConfig({
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
...(peerAssistedRoomIds === undefined
|
||||
? {}
|
||||
: { PEER_ASSISTED_ROOM_IDS: peerAssistedRoomIds }),
|
||||
}),
|
||||
).toThrow(
|
||||
"PEER_ASSISTED_MEDIA=true requires non-empty PEER_ASSISTED_ROOM_IDS",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("requires peer-assisted media for a non-empty room allowlist", () => {
|
||||
@@ -242,6 +257,7 @@ describe("server configuration", () => {
|
||||
PUBLIC_BASE_URL: "https://share.test",
|
||||
STUN_URLS: "stun:stun.test:3478",
|
||||
PEER_ASSISTED_MEDIA: "true",
|
||||
PEER_ASSISTED_ROOM_IDS: "1",
|
||||
LIVEKIT_URL: "wss://livekit.test",
|
||||
LIVEKIT_API_KEY: "test-key",
|
||||
LIVEKIT_API_SECRET: "s".repeat(32),
|
||||
@@ -279,21 +295,32 @@ describe("server configuration", () => {
|
||||
"stun:stun.test/path",
|
||||
"stun:stun.test?transport=udp",
|
||||
"stun:stun.test#fragment",
|
||||
"stun:",
|
||||
"stun:stun.test:",
|
||||
"stun:stun.test:0",
|
||||
"stun:user@stun.test:3478",
|
||||
])("rejects a malformed STUN URL: %s", (invalidUrl) => {
|
||||
expect(() => loadConfig({ STUN_URLS: invalidUrl })).toThrow(
|
||||
"STUN_URLS contains an invalid ICE URL",
|
||||
"STUN_URLS contains an invalid STUN URL",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects non-STUN schemes in the ordinary ICE configuration", () => {
|
||||
expect(() => loadConfig({ STUN_URLS: "turn:turn.test:3478" })).toThrow(
|
||||
"STUN_URLS contains an unsupported URL scheme",
|
||||
"STUN_URLS contains an invalid STUN URL",
|
||||
);
|
||||
expect(() => loadConfig({ STUN_URLS: "stuns:stun.test:5349" })).toThrow(
|
||||
"STUN_URLS contains an unsupported URL scheme",
|
||||
"STUN_URLS contains an invalid STUN URL",
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"TURN_URLS",
|
||||
"TURN_SHARED_SECRET",
|
||||
"TURN_CREDENTIAL_TTL_SECONDS",
|
||||
] as const)("rejects removed TURN configuration even when %s is blank", (name) => {
|
||||
expect(() => loadConfig({ [name]: "" })).toThrow(
|
||||
`${name} is no longer supported`,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -340,6 +340,7 @@ describe("server HTTP listener and health", () => {
|
||||
const baseUrl = await start(
|
||||
testConfig({
|
||||
peerAssistedMedia: true,
|
||||
peerAssistedRoomIds: new Set(["1"]),
|
||||
livekitFallback: {
|
||||
url: "ws://livekit.test:7880",
|
||||
apiKey: "test-key",
|
||||
|
||||
+123
-114
@@ -7,6 +7,7 @@ import WebSocket from "ws";
|
||||
import {
|
||||
MAX_SIGNAL_BYTES,
|
||||
MAX_VIEWER_QUALITY_EVIDENCE_BYTES,
|
||||
SIGNALING_PROTOCOL,
|
||||
decodeServerMessage,
|
||||
type Role,
|
||||
type ServerMessage,
|
||||
@@ -132,6 +133,7 @@ interface SignalHarness {
|
||||
webSocketUrl: string;
|
||||
roomStore: RoomStore;
|
||||
room: CreatedRoom;
|
||||
peerAssistedRoomIds?: Set<string>;
|
||||
}
|
||||
|
||||
function testConfig(): ServerConfig {
|
||||
@@ -159,7 +161,6 @@ async function startHarness(
|
||||
accessPassword?: string;
|
||||
persistent?: boolean;
|
||||
peerAssistedMedia?: boolean;
|
||||
peerAssistedPrimaryRoomOnly?: boolean;
|
||||
stunUrls?: readonly string[];
|
||||
now?: () => number;
|
||||
} = {},
|
||||
@@ -177,9 +178,10 @@ async function startHarness(
|
||||
database: overrides.persistent ? new RoomDatabase(":memory:") : undefined,
|
||||
});
|
||||
const room = roomStore.createRoom();
|
||||
if (overrides.peerAssistedPrimaryRoomOnly) {
|
||||
config.peerAssistedRoomIds = new Set([room.roomId]);
|
||||
}
|
||||
const peerAssistedRoomIds = config.peerAssistedMedia
|
||||
? new Set([room.roomId])
|
||||
: undefined;
|
||||
config.peerAssistedRoomIds = peerAssistedRoomIds;
|
||||
runningServer = await createScreenerServer({
|
||||
config,
|
||||
roomStore,
|
||||
@@ -199,6 +201,7 @@ async function startHarness(
|
||||
webSocketUrl: `ws://127.0.0.1:${port}/signal`,
|
||||
roomStore,
|
||||
room,
|
||||
peerAssistedRoomIds,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -239,7 +242,6 @@ async function startSfuHarness(options: {
|
||||
prepareTimeoutMs?: number;
|
||||
maxRoots?: number;
|
||||
viewerDisconnectGraceMs?: number;
|
||||
peerAssistedPrimaryRoomOnly?: boolean;
|
||||
stunUrls?: readonly string[];
|
||||
}): Promise<SignalHarness> {
|
||||
const roomStore = new RoomStore({
|
||||
@@ -248,6 +250,7 @@ async function startSfuHarness(options: {
|
||||
maxViewersPerRoom: 8,
|
||||
});
|
||||
const room = roomStore.createRoom();
|
||||
const peerAssistedRoomIds = new Set([room.roomId]);
|
||||
const httpServer = createServer((_request, response) => {
|
||||
response.statusCode = 404;
|
||||
response.end();
|
||||
@@ -256,9 +259,7 @@ async function startSfuHarness(options: {
|
||||
server: httpServer,
|
||||
roomStore,
|
||||
peerAssistedMedia: true,
|
||||
...(options.peerAssistedPrimaryRoomOnly
|
||||
? { peerAssistedRoomIds: new Set([room.roomId]) }
|
||||
: {}),
|
||||
peerAssistedRoomIds,
|
||||
sfuFallback: {
|
||||
url: "wss://sfu.example.test",
|
||||
tokenIssuer: options.tokenIssuer,
|
||||
@@ -305,6 +306,7 @@ async function startSfuHarness(options: {
|
||||
webSocketUrl: `ws://127.0.0.1:${port}/signal`,
|
||||
roomStore,
|
||||
room,
|
||||
peerAssistedRoomIds,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -382,8 +384,9 @@ async function authenticate(
|
||||
client.socket.send(
|
||||
JSON.stringify(
|
||||
role === "host"
|
||||
? {
|
||||
? {
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId: room.roomId,
|
||||
role,
|
||||
token: room.hostToken,
|
||||
@@ -392,6 +395,7 @@ async function authenticate(
|
||||
}
|
||||
: {
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId: room.roomId,
|
||||
role,
|
||||
clientId,
|
||||
@@ -915,10 +919,9 @@ describe("WebSocket signaling", () => {
|
||||
it("isolates the routing allowlist while ordinary ICE stays STUN-only", async () => {
|
||||
const harness = await startSfuHarness({
|
||||
tokenIssuer: { issueToken: async () => "unused-test-token" },
|
||||
peerAssistedPrimaryRoomOnly: true,
|
||||
stunUrls: ["stun:stun.example.test:3478"],
|
||||
});
|
||||
const legacyRoom = harness.roomStore.createRoom();
|
||||
const ordinaryRoom = harness.roomStore.createRoom();
|
||||
|
||||
const hybridHost = await openClient(harness.webSocketUrl);
|
||||
const hybridHostAuth = peerAssisted(
|
||||
@@ -934,108 +937,108 @@ describe("WebSocket signaling", () => {
|
||||
iceServers: [{ urls: ["stun:stun.example.test:3478"] }],
|
||||
});
|
||||
|
||||
const legacyHost = await openClient(harness.webSocketUrl);
|
||||
const legacyHostAuth = await authenticate(
|
||||
legacyHost,
|
||||
legacyRoom,
|
||||
const ordinaryHost = await openClient(harness.webSocketUrl);
|
||||
const ordinaryHostAuth = await authenticate(
|
||||
ordinaryHost,
|
||||
ordinaryRoom,
|
||||
"host",
|
||||
"legacy-host",
|
||||
"ordinary-host",
|
||||
);
|
||||
expect(Object.keys(legacyHostAuth).sort()).toEqual(
|
||||
expect(Object.keys(ordinaryHostAuth).sort()).toEqual(
|
||||
[
|
||||
"connectionId",
|
||||
"hostOnline",
|
||||
"iceConfig",
|
||||
"maxViewers",
|
||||
"peerId",
|
||||
"protocol",
|
||||
"role",
|
||||
"roomExpiresAt",
|
||||
"type",
|
||||
"viewerPeerIds",
|
||||
].sort(),
|
||||
);
|
||||
expect(legacyHostAuth.iceConfig).toEqual(hybridHostAuth.iceConfig);
|
||||
expect(ordinaryHostAuth.iceConfig).toEqual(hybridHostAuth.iceConfig);
|
||||
expect(
|
||||
legacyHostAuth.iceConfig.iceServers.every(
|
||||
ordinaryHostAuth.iceConfig.iceServers.every(
|
||||
(server) => !("username" in server) && !("credential" in server),
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const legacyViewer = await openClient(harness.webSocketUrl);
|
||||
const legacyViewerAuth = await authenticate(
|
||||
legacyViewer,
|
||||
legacyRoom,
|
||||
const ordinaryViewer = await openClient(harness.webSocketUrl);
|
||||
const ordinaryViewerAuth = await authenticate(
|
||||
ordinaryViewer,
|
||||
ordinaryRoom,
|
||||
"viewer",
|
||||
"legacy-viewer",
|
||||
"ordinary-viewer",
|
||||
);
|
||||
expect(Object.keys(legacyViewerAuth).sort()).toEqual(
|
||||
Object.keys(legacyHostAuth).sort(),
|
||||
expect(Object.keys(ordinaryViewerAuth).sort()).toEqual(
|
||||
Object.keys(ordinaryHostAuth).sort(),
|
||||
);
|
||||
expect(await legacyHost.inbox.next("peer-joined")).toEqual({
|
||||
expect(await ordinaryHost.inbox.next("peer-joined")).toEqual({
|
||||
type: "peer-joined",
|
||||
peerId: legacyViewerAuth.peerId,
|
||||
peerId: ordinaryViewerAuth.peerId,
|
||||
});
|
||||
|
||||
legacyHost.socket.send(
|
||||
ordinaryHost.socket.send(
|
||||
JSON.stringify({
|
||||
type: "signal",
|
||||
targetPeerId: legacyViewerAuth.peerId,
|
||||
targetPeerId: ordinaryViewerAuth.peerId,
|
||||
payload: {
|
||||
kind: "description",
|
||||
connectionId: "legacy-room-connection",
|
||||
connectionId: "ordinary-room-connection",
|
||||
description: { type: "offer", sdp: "v=0\r\n" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(await legacyViewer.inbox.next("signal")).toMatchObject({
|
||||
fromPeerId: legacyHostAuth.peerId,
|
||||
payload: { connectionId: "legacy-room-connection" },
|
||||
expect(await ordinaryViewer.inbox.next("signal")).toMatchObject({
|
||||
fromPeerId: ordinaryHostAuth.peerId,
|
||||
payload: { connectionId: "ordinary-room-connection" },
|
||||
});
|
||||
legacyViewer.socket.send(
|
||||
ordinaryViewer.socket.send(
|
||||
JSON.stringify({
|
||||
type: "signal",
|
||||
payload: {
|
||||
kind: "description",
|
||||
connectionId: "legacy-room-connection",
|
||||
connectionId: "ordinary-room-connection",
|
||||
description: { type: "answer", sdp: "v=0\r\n" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(await legacyHost.inbox.next("signal")).toMatchObject({
|
||||
fromPeerId: legacyViewerAuth.peerId,
|
||||
payload: { connectionId: "legacy-room-connection" },
|
||||
expect(await ordinaryHost.inbox.next("signal")).toMatchObject({
|
||||
fromPeerId: ordinaryViewerAuth.peerId,
|
||||
payload: { connectionId: "ordinary-room-connection" },
|
||||
});
|
||||
|
||||
legacyHost.socket.send(
|
||||
ordinaryHost.socket.send(
|
||||
JSON.stringify({
|
||||
type: "set-quality-settings",
|
||||
qualitySettings: balancedQualitySettings,
|
||||
}),
|
||||
);
|
||||
expect((await legacyHost.inbox.next("error")).code).toBe("FORBIDDEN");
|
||||
legacyViewer.socket.send(
|
||||
expect((await ordinaryHost.inbox.next("error")).code).toBe("FORBIDDEN");
|
||||
ordinaryViewer.socket.send(
|
||||
JSON.stringify({ type: "relay-capacity", downstreamEdges: 1 }),
|
||||
);
|
||||
expect((await legacyViewer.inbox.next("error")).code).toBe("FORBIDDEN");
|
||||
legacyViewer.socket.send(
|
||||
expect((await ordinaryViewer.inbox.next("error")).code).toBe("FORBIDDEN");
|
||||
ordinaryViewer.socket.send(
|
||||
JSON.stringify({ type: "refresh-sfu", revision: 0 }),
|
||||
);
|
||||
expect((await legacyViewer.inbox.next("error")).code).toBe("FORBIDDEN");
|
||||
expect((await ordinaryViewer.inbox.next("error")).code).toBe("FORBIDDEN");
|
||||
|
||||
await closeClient(legacyViewer);
|
||||
expect(await legacyHost.inbox.next("peer-left", 500)).toEqual({
|
||||
await closeClient(ordinaryViewer);
|
||||
expect(await ordinaryHost.inbox.next("peer-left", 500)).toEqual({
|
||||
type: "peer-left",
|
||||
peerId: legacyViewerAuth.peerId,
|
||||
peerId: ordinaryViewerAuth.peerId,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps allowlisted and legacy room lifecycles independent", async () => {
|
||||
it("keeps allowlisted and ordinary room lifecycles independent", async () => {
|
||||
const harness = await startHarness({
|
||||
peerAssistedMedia: true,
|
||||
peerAssistedPrimaryRoomOnly: true,
|
||||
viewerDisconnectGraceMs: 500,
|
||||
});
|
||||
const legacyRoom = harness.roomStore.createRoom();
|
||||
const ordinaryRoom = harness.roomStore.createRoom();
|
||||
|
||||
const hybridHost = await openClient(harness.webSocketUrl);
|
||||
const hybridHostAuth = peerAssisted(
|
||||
@@ -1059,34 +1062,34 @@ describe("WebSocket signaling", () => {
|
||||
);
|
||||
await hybridViewer.inbox.next("quality-settings");
|
||||
|
||||
const legacyHost = await openClient(harness.webSocketUrl);
|
||||
await authenticate(legacyHost, legacyRoom, "host", "lifecycle-legacy-host");
|
||||
const legacyViewer = await openClient(harness.webSocketUrl);
|
||||
const legacyViewerAuth = await authenticate(
|
||||
legacyViewer,
|
||||
legacyRoom,
|
||||
const ordinaryHost = await openClient(harness.webSocketUrl);
|
||||
await authenticate(ordinaryHost, ordinaryRoom, "host", "lifecycle-ordinary-host");
|
||||
const ordinaryViewer = await openClient(harness.webSocketUrl);
|
||||
const ordinaryViewerAuth = await authenticate(
|
||||
ordinaryViewer,
|
||||
ordinaryRoom,
|
||||
"viewer",
|
||||
"lifecycle-legacy-viewer",
|
||||
"lifecycle-ordinary-viewer",
|
||||
);
|
||||
await legacyHost.inbox.next("peer-joined");
|
||||
await ordinaryHost.inbox.next("peer-joined");
|
||||
|
||||
const hybridHostClosed = new Promise<number>((resolve) =>
|
||||
hybridHost.socket.once("close", (code) => resolve(code)),
|
||||
);
|
||||
const legacyHostClosed = new Promise<number>((resolve) =>
|
||||
legacyHost.socket.once("close", (code) => resolve(code)),
|
||||
const ordinaryHostClosed = new Promise<number>((resolve) =>
|
||||
ordinaryHost.socket.once("close", (code) => resolve(code)),
|
||||
);
|
||||
hybridHost.socket.send(JSON.stringify({ type: "stop-sharing" }));
|
||||
legacyHost.socket.send(JSON.stringify({ type: "stop-sharing" }));
|
||||
ordinaryHost.socket.send(JSON.stringify({ type: "stop-sharing" }));
|
||||
await hybridViewer.inbox.next("sharing-stopped");
|
||||
await hybridViewer.inbox.next("host-status");
|
||||
await legacyViewer.inbox.next("sharing-stopped");
|
||||
await legacyViewer.inbox.next("host-status");
|
||||
await ordinaryViewer.inbox.next("sharing-stopped");
|
||||
await ordinaryViewer.inbox.next("host-status");
|
||||
expect(await hybridHostClosed).toBe(1000);
|
||||
expect(await legacyHostClosed).toBe(1000);
|
||||
expect(await ordinaryHostClosed).toBe(1000);
|
||||
|
||||
await closeClient(hybridViewer);
|
||||
await closeClient(legacyViewer);
|
||||
await closeClient(ordinaryViewer);
|
||||
const resumedHybridViewer = await openClient(harness.webSocketUrl);
|
||||
const resumedHybridViewerAuth = peerAssisted(
|
||||
await authenticate(
|
||||
@@ -1101,17 +1104,17 @@ describe("WebSocket signaling", () => {
|
||||
connectionId: null,
|
||||
qualitySettings: lowQualitySettings,
|
||||
});
|
||||
const resumedLegacyViewer = await openClient(harness.webSocketUrl);
|
||||
const resumedLegacyViewerAuth = await authenticate(
|
||||
resumedLegacyViewer,
|
||||
legacyRoom,
|
||||
const resumedOrdinaryViewer = await openClient(harness.webSocketUrl);
|
||||
const resumedOrdinaryViewerAuth = await authenticate(
|
||||
resumedOrdinaryViewer,
|
||||
ordinaryRoom,
|
||||
"viewer",
|
||||
"lifecycle-legacy-viewer",
|
||||
"lifecycle-ordinary-viewer",
|
||||
);
|
||||
expect(resumedLegacyViewerAuth.peerId).toBe(legacyViewerAuth.peerId);
|
||||
expect(resumedLegacyViewerAuth.connectionId).toBeNull();
|
||||
expect("mediaMode" in resumedLegacyViewerAuth).toBe(false);
|
||||
expect("qualitySettings" in resumedLegacyViewerAuth).toBe(false);
|
||||
expect(resumedOrdinaryViewerAuth.peerId).toBe(ordinaryViewerAuth.peerId);
|
||||
expect(resumedOrdinaryViewerAuth.connectionId).toBeNull();
|
||||
expect("mediaMode" in resumedOrdinaryViewerAuth).toBe(false);
|
||||
expect("qualitySettings" in resumedOrdinaryViewerAuth).toBe(false);
|
||||
|
||||
const resumedHybridHost = await openClient(harness.webSocketUrl);
|
||||
const resumedHybridHostAuth = peerAssisted(
|
||||
@@ -1126,15 +1129,15 @@ describe("WebSocket signaling", () => {
|
||||
peerId: hybridHostAuth.peerId,
|
||||
qualitySettings: lowQualitySettings,
|
||||
});
|
||||
const resumedLegacyHost = await openClient(harness.webSocketUrl);
|
||||
const resumedLegacyHostAuth = await authenticate(
|
||||
resumedLegacyHost,
|
||||
legacyRoom,
|
||||
const resumedOrdinaryHost = await openClient(harness.webSocketUrl);
|
||||
const resumedOrdinaryHostAuth = await authenticate(
|
||||
resumedOrdinaryHost,
|
||||
ordinaryRoom,
|
||||
"host",
|
||||
"lifecycle-legacy-host",
|
||||
"lifecycle-ordinary-host",
|
||||
);
|
||||
expect(await resumedLegacyHost.inbox.next("peer-joined")).toMatchObject({
|
||||
peerId: resumedLegacyViewerAuth.peerId,
|
||||
expect(await resumedOrdinaryHost.inbox.next("peer-joined")).toMatchObject({
|
||||
peerId: resumedOrdinaryViewerAuth.peerId,
|
||||
});
|
||||
|
||||
resumedHybridHost.socket.send(JSON.stringify({ type: "abandon-room" }));
|
||||
@@ -1142,24 +1145,24 @@ describe("WebSocket signaling", () => {
|
||||
await resumedHybridViewer.inbox.next("room-closed");
|
||||
expect(harness.roomStore.size).toBe(1);
|
||||
|
||||
resumedLegacyHost.socket.send(
|
||||
resumedOrdinaryHost.socket.send(
|
||||
JSON.stringify({
|
||||
type: "signal",
|
||||
targetPeerId: resumedLegacyViewerAuth.peerId,
|
||||
targetPeerId: resumedOrdinaryViewerAuth.peerId,
|
||||
payload: {
|
||||
kind: "description",
|
||||
connectionId: "legacy-after-hybrid-delete",
|
||||
connectionId: "ordinary-after-hybrid-delete",
|
||||
description: { type: "offer", sdp: "v=0\r\n" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(await resumedLegacyViewer.inbox.next("signal")).toMatchObject({
|
||||
fromPeerId: resumedLegacyHostAuth.peerId,
|
||||
payload: { connectionId: "legacy-after-hybrid-delete" },
|
||||
expect(await resumedOrdinaryViewer.inbox.next("signal")).toMatchObject({
|
||||
fromPeerId: resumedOrdinaryHostAuth.peerId,
|
||||
payload: { connectionId: "ordinary-after-hybrid-delete" },
|
||||
});
|
||||
resumedLegacyHost.socket.send(JSON.stringify({ type: "abandon-room" }));
|
||||
await resumedLegacyHost.inbox.next("room-closed");
|
||||
await resumedLegacyViewer.inbox.next("room-closed");
|
||||
resumedOrdinaryHost.socket.send(JSON.stringify({ type: "abandon-room" }));
|
||||
await resumedOrdinaryHost.inbox.next("room-closed");
|
||||
await resumedOrdinaryViewer.inbox.next("room-closed");
|
||||
expect(harness.roomStore.size).toBe(0);
|
||||
});
|
||||
|
||||
@@ -1548,6 +1551,7 @@ describe("WebSocket signaling", () => {
|
||||
it("assigns a bounded peer relay tree and authorizes only direct media edges", async () => {
|
||||
const harness = await startHarness({ peerAssistedMedia: true });
|
||||
const secondRoom = harness.roomStore.createRoom();
|
||||
harness.peerAssistedRoomIds!.add(secondRoom.roomId);
|
||||
const host = await openClient(harness.webSocketUrl);
|
||||
const hostAuth = peerAssisted(
|
||||
await authenticate(host, harness.room, "host", "relay-host"),
|
||||
@@ -2636,6 +2640,7 @@ describe("WebSocket signaling", () => {
|
||||
});
|
||||
|
||||
const replacementRoom = harness.roomStore.createRoom();
|
||||
harness.peerAssistedRoomIds!.add(replacementRoom.roomId);
|
||||
const replacing = await prepareFallbackForTwoViewers(
|
||||
harness.webSocketUrl,
|
||||
replacementRoom,
|
||||
@@ -2706,6 +2711,7 @@ describe("WebSocket signaling", () => {
|
||||
expect(replacementRoot.socket.readyState).toBe(WebSocket.OPEN);
|
||||
|
||||
const prepareFailureRoom = harness.roomStore.createRoom();
|
||||
harness.peerAssistedRoomIds!.add(prepareFailureRoom.roomId);
|
||||
const prepareFailure = await prepareFallbackForTwoViewers(
|
||||
harness.webSocketUrl,
|
||||
prepareFailureRoom,
|
||||
@@ -3529,6 +3535,7 @@ describe("WebSocket signaling", () => {
|
||||
overflow.socket.send(
|
||||
JSON.stringify({
|
||||
type: "authenticate",
|
||||
protocol: SIGNALING_PROTOCOL,
|
||||
roomId: harness.room.roomId,
|
||||
role: "viewer",
|
||||
clientId: `viewer-client-${maxViewersPerRoom + 1}`,
|
||||
@@ -3549,29 +3556,6 @@ describe("WebSocket signaling", () => {
|
||||
expect(await stoppedHostClosed).toBe(1000);
|
||||
expect(harness.roomStore.size).toBe(1);
|
||||
|
||||
const legacyHost = await openClient(harness.webSocketUrl);
|
||||
await authenticate(
|
||||
legacyHost,
|
||||
harness.room,
|
||||
"host",
|
||||
"host-client-stable",
|
||||
);
|
||||
for (const viewer of viewers) {
|
||||
expect(await viewer.inbox.next("host-status")).toMatchObject({ online: true });
|
||||
}
|
||||
const legacyHostClosed = new Promise<number>((resolve) =>
|
||||
legacyHost.socket.once("close", (code) => resolve(code)),
|
||||
);
|
||||
legacyHost.socket.send(JSON.stringify({ type: "close-room" }));
|
||||
for (const viewer of viewers) {
|
||||
expect(await viewer.inbox.next("sharing-stopped")).toEqual({
|
||||
type: "sharing-stopped",
|
||||
});
|
||||
expect(await viewer.inbox.next("host-status")).toMatchObject({ online: false });
|
||||
}
|
||||
expect(await legacyHostClosed).toBe(1000);
|
||||
expect(harness.roomStore.size).toBe(1);
|
||||
|
||||
viewers[0]!.socket.send(JSON.stringify({ type: "abandon-room" }));
|
||||
expect((await viewers[0]!.inbox.next("error")).code).toBe("FORBIDDEN");
|
||||
expect(harness.roomStore.size).toBe(1);
|
||||
@@ -3626,6 +3610,31 @@ describe("WebSocket signaling", () => {
|
||||
expect(await closeCode).toBe(1009);
|
||||
});
|
||||
|
||||
it("terminates an old client protocol before authentication", async () => {
|
||||
const harness = await startHarness();
|
||||
const oldClient = await openClient(harness.webSocketUrl);
|
||||
const closed = new Promise<{ code: number; reason: string }>((resolve) =>
|
||||
oldClient.socket.once("close", (code, reason) =>
|
||||
resolve({ code, reason: reason.toString() }),
|
||||
),
|
||||
);
|
||||
|
||||
oldClient.socket.send(
|
||||
JSON.stringify({
|
||||
type: "authenticate",
|
||||
roomId: harness.room.roomId,
|
||||
role: "viewer",
|
||||
clientId: "old-client",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(await oldClient.inbox.next("error")).toMatchObject({
|
||||
code: "AUTH_REQUIRED",
|
||||
message: "页面版本已更新,请刷新后重试",
|
||||
});
|
||||
expect(await closed).toEqual({ code: 4001, reason: "Protocol mismatch" });
|
||||
});
|
||||
|
||||
it("rejects an invalid upgrade request target without stopping the server", async () => {
|
||||
const harness = await startHarness();
|
||||
const response = await rawUpgradeResponse(harness.webSocketUrl, "//[");
|
||||
|
||||
Reference in new issue
Block a user