Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
refactor: unify Go runtime and audited frontend
AAAda47189fc3ed
diff --git a/.env.example b/.env.exampleindex 0d907997..3a1220a5 100644--- a/.env.example+++ b/.env.example@@ -17,17 +17,15 @@ ROOM_LEASE_SECONDS=86400# activation requires a verified writable directory and database recovery procedure.ROOM_DATABASE_PATH=MAX_VIEWERS_PER_ROOM=8-# Bounded standard-WebRTC relay/SFU controller for every room when true.-# Keep false outside measured tests.-PEER_ASSISTED_MEDIA=false+# Bounded standard-WebRTC relay/SFU controller is active for every room.# One steady outbound media-copy capacity for every non-server endpoint.# A peer child or Host SFU publication consumes one copy. Valid values: 1, 2, 3.ENDPOINT_MEDIA_COPY_CAPACITY=2# During pre-release route canaries, this enables sanitized room/ordinal events.-# NODE_DEBUG=screener-route+# SCREENER_DEBUG=route-# Optional automatic SFU fallback. Set PEER_ASSISTED_MEDIA=true and supply all-# four values together; leaving them empty keeps LiveKit completely dormant.+# Optional automatic SFU fallback. Supply all four values together; leaving them+# empty keeps LiveKit completely dormant.# Ingress uses the 9000-room code capacity; egress uses that capacity times the# configured per-room Viewer admission.# Production requires wss and an independent API secret of 32+ bytes.@@ -45,12 +43,18 @@ STUN_URLS=# from the first STUN_URLS endpoint on UDP 3478.NAT_PREDICTION_ENABLED=false+# Development example (two processes): Vite serves the Browser on 8787 and+# proxies /api, /healthz and /signal to the Go server on 8788. Keep+# PUBLIC_BASE_URL and ALLOWED_ORIGINS on the Browser origin above.+# SCREENER_ENV=development+# PORT=8788+# Minimal production example (use independent untracked secrets):+# SCREENER_ENV=production# SITE_ACCESS_PASSWORD=replace-with-an-independent-access-key# STUN_URLS=stun:stun.example.com:3478# NAT_PREDICTION_ENABLED=true-# Automatic SFU fallback (requires PEER_ASSISTED_MEDIA=true and does not-# replace STUN above):+# Automatic SFU fallback (does not replace STUN above):# LIVEKIT_URL=wss://share.example.com# LIVEKIT_API_URL=http://127.0.0.1:7880# LIVEKIT_API_KEY=replace-with-a-livekit-api-keydiff --git a/.github/workflows/repository-hygiene.yml b/.github/workflows/repository-hygiene.ymlindex e8180330..94b2709f 100644--- a/.github/workflows/repository-hygiene.yml+++ b/.github/workflows/repository-hygiene.yml@@ -58,16 +58,20 @@ jobs:LICENSE \licenses \index.html \- native/client \+ cmd \+ internal \+ native \+ go.mod \+ go.sum \package.json \package-lock.json \public \src \tsconfig.json \tsconfig.app.json \- tsconfig.server.json \vite.config.ts \scripts/assemble-client.mjs \+ scripts/archive-tool.mjs \scripts/client-icons.mjs \scripts/package-app-release.mjs \scripts/package-licenses.mjs \@@ -81,17 +85,18 @@ jobs:fifiecho "run=$run_client" >> "$GITHUB_OUTPUT"+ - name: Install dependencies+ run: npm ci+ # The Go build embeds internal/server/webassets/dist, so Vite runs first.+ - name: Build the Browser client+ run: npm run build:client- name: Set up Go- if: steps.client-scope.outputs.run == 'true'uses: actions/setup-go@v6with:go-version: 1.26.6- cache-dependency-path: native/client/go.sum- - name: Check Screener Client- if: steps.client-scope.outputs.run == 'true'+ cache-dependency-path: go.sum+ - name: Check Go corerun: npm run check:client-core- - name: Install dependencies- run: npm ci- name: Type-check, test, and buildrun: npm run check@@ -110,6 +115,11 @@ jobs:with:node-version-file: .node-versioncache: npm+ - name: Set up Go+ uses: actions/setup-go@v6+ with:+ go-version: 1.26.6+ cache-dependency-path: go.sum- name: Install dependenciesrun: npm ci- name: Package application release@@ -148,11 +158,17 @@ jobs:uses: actions/setup-node@v6with:node-version-file: .node-version+ cache: npm- name: Set up Gouses: actions/setup-go@v6with:go-version: 1.26.6- cache-dependency-path: native/client/go.sum+ cache-dependency-path: go.sum+ # scripts/assemble-client.mjs runs `npm run build:client` for the Web+ # assets the Client binary embeds, so Vite and the license inputs must be+ # installed here too.+ - name: Install dependencies+ run: npm ci- name: Install Linux native capture dependenciesif: matrix.target == 'linux-amd64'run: >-diff --git a/.gitignore b/.gitignoreindex d81af04f..5645796d 100644--- a/.gitignore+++ b/.gitignore@@ -14,7 +14,10 @@ node_modules/public/third-party-licenses.txtbuild/coverage/-dist/+/dist/+!internal/server/webassets/dist/+internal/server/webassets/dist/*+!internal/server/webassets/dist/.gitkeepbenchmark-results/.cache/*.sqlitediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 49a6108c..06b87e8a 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -61,11 +61,12 @@ Clean up worktrees and branches only after semantic review and integration are c## Verification Entrypoints-- `npm run check` owns deterministic Web/Server type-check, unit, and build- acceptance.+- `npm run check` owns deterministic Web type-check, unit, and build acceptance.- `npm run check:client` owns Go formatting, unit tests, vet, three-platform- builds, and the Windows capture compile/probe when run on Windows. CI invokes- these same package commands rather than rebuilding their steps in YAML.+ builds, and the Windows capture compile/probe when run on Windows. The server+ core is Go, so its acceptance runs here. It builds the Vite client first when+ that output is missing, because both binaries embed it. CI invokes these same+ package commands rather than rebuilding their steps in YAML.- `gate:*` commands are explicit physical or network acceptance. They must useisolated profiles, bounded deadlines, shared cleanup helpers, and a structuredresult. A manual diagnostic may locate a failure, but is not retained as passdiff --git a/README.md b/README.mdindex c0411256..535a6ae2 100644--- a/README.md+++ b/README.md@@ -11,8 +11,8 @@ this README intentionally does not mirror release details.## Screener Client-The Client opens the same interface in your system browser. The Windows package-includes its runtime; you do not need to install Node.js separately.+The Client opens the same interface in your system browser. The package is one+self-contained executable.- **Local:** share with devices on the same LAN.- **Public link:** send an ordinary invitation link. Cloudflare Quick Tunnel@@ -33,13 +33,19 @@ site-access password. This does not change access rules on a saved Site.## Local Development-Node.js 24 and npm 11 are required.+Node.js 24, npm 11, and Go 1.26 are required.```shnpm cinpm run dev```+In a second terminal, run the application server that the dev server proxies:++```sh+PORT=8788 PUBLIC_BASE_URL=http://localhost:8787 go run ./cmd/screener-server+```+Open `http://localhost:8787`. The development server listens on `0.0.0.0`, so aphone on the same LAN may use `http://<computer-lan-ip>:8787`. Screen capturemust remain on `localhost` or HTTPS. Set `PUBLIC_BASE_URL` and@@ -55,6 +61,7 @@ Run complete automated validation with:```shnpm run check+npm run check:client```## Documentationdiff --git a/native/client/README.md b/cmd/screener-client/README.mdsimilarity index 93%rename from native/client/README.mdrename to cmd/screener-client/README.mdindex b8640139..87226fcb 100644--- a/native/client/README.md+++ b/cmd/screener-client/README.md@@ -77,7 +77,7 @@ falling back to ASCII without color support or in very narrow windows.Visual mode depicts the selected mode and startup state with small scenes;the television rests with one eye closed and occasionally winks while idle.Press `o` to reopen the Browser, or `q` / Ctrl+C to end Local-rooms and stop the bundled server and temporary public link. Plain-text output+rooms and stop the local server and temporary public link. Plain-text outputuses Ctrl+C. A Site-loaded Browser tab does not own the Client process.For one-link Internet sharing, open the Client launcher, choose **Public invite**,@@ -88,13 +88,13 @@ control availability or SFU fallback matters.## Development+The binary embeds the Browser assets, so build them before running it:+```sh-cd native/client+npm run build:clientgo test ./...go vet ./...-go run ./cmd/screener-client \- --node /path/to/node \- --app /path/to/Screener+go run ./cmd/screener-client```The repository-level entry used locally and by CI is:@@ -127,15 +127,14 @@ available even when this machine has no accepted native capture encoder.## PackagingBuild one application release, then assemble a platform Client from that exact-descriptor and a matching platform Node executable. Native capture and the-public-link sidecar are explicit package inputs:+descriptor. Native capture and the public-link sidecar are explicit package+inputs:```shnode scripts/package-app-release.mjs /outside/repository/app-releaseSCREENER_GO=/path/to/go \node scripts/assemble-client.mjs \/outside/repository/app-release/screener-<sha>.release.json \- /path/to/node \/outside/repository/Screener-Client \--target windows-amd64 \--capture /outside/repository/screener-client-capture.exe \@@ -143,8 +142,8 @@ SCREENER_GO=/path/to/go \```Supported targets are `windows-amd64`, `linux-amd64`, and `darwin-arm64`.-`--target` controls the Go cross-build and packaged executable names; the Node,-capture, and tunnel inputs must already match that target. Each target accepts+`--target` controls the Go cross-build and packaged executable names; the+capture and tunnel inputs must already match that target. Each target acceptsits matching native-capture input.The result contains:@@ -152,16 +151,15 @@ The result contains:```textscreener-client[.exe]REVISION-runtime/node/node[.exe]+LICENSE+THIRD-PARTY-NOTICES.txtruntime/native/screener-client-capture[.exe] # supported native-media packagesruntime/tunnel/cloudflared[.exe] # packages that support --link-app/REVISION-app/dist-app/node_modules```-The Client executable and application must contain the same full Git revision.-No compatibility reader accepts a mismatched private build.+The executable embeds the Browser assets of the consumed application release and+carries that same full Git revision as the package `REVISION`. No compatibility+reader accepts a mismatched private build.The Windows Client embeds the shared Screener mark through the`cmd/screener-client/screener_windows_amd64.syso` resource; the platform@@ -189,8 +187,6 @@ is POSIX; use equivalent variables on Windows.SCREENER_CLIENT_LOCAL_GATE=true \CHROME_PATH=/path/to/chrome \SCREENER_CLIENT_EXE=/path/to/screener-client \-SCREENER_CLIENT_NODE=/path/to/node \-SCREENER_CLIENT_APP=/path/to/app \SCREENER_CLIENT_GATE_LAN_ADDRESS=192.168.1.10 \npm run gate:client-local@@ -201,6 +197,7 @@ npm run probe:client-loopbackSCREENER_CLIENT_MEDIA_GATE=true \CHROME_PATH=/path/to/chrome \+SCREENER_CLIENT_GATE_STUN_URLS=stun:<stun-host>:3478 \npm run gate:client-mediaSCREENER_CLIENT_NATIVE_HOST_GATE=true \@@ -216,7 +213,7 @@ SCREENER_REMOTE_HOST=<public-test-host> \SCREENER_REMOTE_USER=<ssh-user> \SCREENER_REMOTE_SSH_KEY=/path/to/key \SCREENER_CLIENT_GATE_STUN_URLS=stun:<stun-host>:3478 \-npm run gate:client-cross-nat+npm run gate:client-native-hostSCREENER_CLIENT_NATIVE_HOST_GATE=true \SCREENER_CLIENT_LINK_MEDIA_GATE=true \@@ -226,7 +223,7 @@ SCREENER_CLOUDFLARED=/path/to/cloudflared \SCREENER_REMOTE_HOST=<public-test-host> \SCREENER_REMOTE_USER=<ssh-user> \SCREENER_REMOTE_SSH_KEY=/path/to/key \-npm run gate:client-link-media+npm run gate:client-native-hostSCREENER_CLIENT_LINK_GATE=true \SCREENER_GO=/path/to/go \diff --git a/native/client/cmd/screener-client/main.go b/cmd/screener-client/main.gosimilarity index 79%rename from native/client/cmd/screener-client/main.gorename to cmd/screener-client/main.goindex c1769802..f43f051d 100644--- a/native/client/cmd/screener-client/main.go+++ b/cmd/screener-client/main.go@@ -1,3 +1,8 @@+// Command screener-client is the self-contained Screener Client: it opens a+// configured Screener Site, or runs the Local room authority in-process+// (--local / --link) together with the loopback capability service and the+// native media edge. Flags select the mode; clientapp owns every mode's+// lifecycle.package mainimport (@@ -8,7 +13,7 @@ import ("os/signal""syscall"- "github.com/TNTcraftHIM/Screener/native/client/internal/clientapp"+ "github.com/TNTcraftHIM/Screener/internal/client/clientapp")func main() {@@ -20,8 +25,6 @@ func main() {})flag.BoolVar(&options.Local, "local", false, "use the self-contained Local room authority")flag.BoolVar(&options.Link, "link", false, "create one public Viewer invitation link")- flag.StringVar(&options.NodePath, "node", "", "path to the bundled Node runtime")- flag.StringVar(&options.AppDirectory, "app", "", "path to the bundled Screener application")flag.StringVar(&options.CaptureProcess, "capture-process", "", "path to the platform native capture process")flag.StringVar(&options.TunnelProcess, "tunnel-process", "", "path to the packaged public tunnel process")flag.StringVar(&options.ConfigPath, "config", "", "path to the Client configuration file")diff --git a/native/client/cmd/screener-client/screener.ico b/cmd/screener-client/screener.icosimilarity index 100%rename from native/client/cmd/screener-client/screener.icorename to cmd/screener-client/screener.icodiff --git a/native/client/cmd/screener-client/screener_windows_amd64.syso b/cmd/screener-client/screener_windows_amd64.sysosimilarity index 100%rename from native/client/cmd/screener-client/screener_windows_amd64.sysorename to cmd/screener-client/screener_windows_amd64.sysodiff --git a/native/client/cmd/screener-peer-gate/main.go b/cmd/screener-peer-gate/main.gosimilarity index 99%rename from native/client/cmd/screener-peer-gate/main.gorename to cmd/screener-peer-gate/main.goindex 30d47322..998d8bf9 100644--- a/native/client/cmd/screener-peer-gate/main.go+++ b/cmd/screener-peer-gate/main.go@@ -20,7 +20,7 @@ import ()const (- signalingProtocol = "screener-v20"+ signalingProtocol = "screener-v21"maxPendingCandidates = 64)diff --git a/native/client/cmd/screener-peer-gate/main_test.go b/cmd/screener-peer-gate/main_test.gosimilarity index 100%rename from native/client/cmd/screener-peer-gate/main_test.gorename to cmd/screener-peer-gate/main_test.godiff --git a/cmd/screener-server/main.go b/cmd/screener-server/main.gonew file mode 100644index 00000000..0dd4fdec--- /dev/null+++ b/cmd/screener-server/main.go@@ -0,0 +1,168 @@+// Command screener-server is the Hosted Screener entry point: it loads the+// environment, serves the embedded Browser UI together with the signaling and+// room API, and stops on SIGINT or SIGTERM. It replaces src/server/index.ts.+//+// Two maintenance modes exit without serving: --check-config validates the+// environment (the release wrapper runs it as the service user before cutover)+// and --check-release compares the deployed revision with the latest published+// release (see release.go).+package main++import (+ "context"+ "errors"+ "flag"+ "fmt"+ "io/fs"+ "log/slog"+ "os"+ "os/signal"+ "strings"+ "syscall"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/app"+ "github.com/TNTcraftHIM/Screener/internal/server/config"+ "github.com/TNTcraftHIM/Screener/internal/server/webassets"+)++// shutdownTimeout bounds the ordered stop (signaling, listener, room store).+// systemd's tracked TimeoutStopSec is 20s, so the process must be gone first.+const shutdownTimeout = 15 * time.Second++// environmentFile is read from the working directory, which systemd pins to the+// release directory. Hosted keeps its real values in the service secret store.+const environmentFile = ".env"++// BuildRevision is the full Git revision the release packager links in with+// -ldflags. It matches the REVISION file shipped beside the binary and is+// reported at startup so one journal line identifies the running release.+var BuildRevision = "development"++func main() {+ checkConfig := flag.Bool("check-config", false, "validate the environment and exit")+ checkRelease := flag.Bool("check-release", false,+ "report whether a newer published release exists and exit")+ currentFile := flag.String("current-file", "",+ "path to the deployed REVISION file read by --check-release")+ apiURL := flag.String("api-url", defaultReleaseAPIURL,+ "release metadata endpoint used by --check-release")+ flag.Parse()++ if err := loadEnvironmentFile(environmentFile); err != nil {+ fail(err)+ }+ switch {+ case *checkRelease:+ os.Exit(checkDeployedRelease(context.Background(), *currentFile, *apiURL, os.Stdout))+ case *checkConfig:+ if _, err := config.Load(environment()); err != nil {+ fail(err)+ }+ fmt.Println("config=ok")+ default:+ if err := serve(); err != nil {+ fail(err)+ }+ }+}++func fail(err error) {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+}++// serve runs the application until the first SIGINT or SIGTERM, then stops it+// with Close rather than End: Hosted rooms are leased in the database and must+// survive a restart (DECISIONS D6).+func serve() error {+ configuration, err := config.Load(environment())+ if err != nil {+ return err+ }+ server, err := app.New(app.Options{+ Config: configuration,+ Assets: webassets.FS(),+ Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)),+ })+ if err != nil {+ return err+ }+ // Startup does not take the stop signal: index.ts registered its SIGINT and+ // SIGTERM handlers only after `await server.listen()` resolved, so a stop+ // during the LiveKit reconciliation ended the process by the signal's+ // default disposition. Cancelling startup instead would abort it and exit+ // non-zero, which systemd records as a failed unit. Each LiveKit call keeps+ // its own 5 s bound (D1).+ port, err := server.Listen(context.Background())+ if err != nil {+ return err+ }+ fmt.Printf("Screener %s is listening on %s:%d; public URL %s\n",+ BuildRevision, configuration.ListenHost, port, config.Origin(configuration.PublicBaseURL))++ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()+ <-ctx.Done()+ shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)+ defer cancel()+ return server.Close(shutdownCtx)+}++// environment is the process environment in the form config.Load expects.+func environment() map[string]string {+ values := make(map[string]string)+ for _, entry := range os.Environ() {+ if name, value, found := strings.Cut(entry, "="); found {+ values[name] = value+ }+ }+ return values+}++// loadEnvironmentFile ports the src/server/index.ts loadEnvFile() call: an+// absent file is the ordinary case and every other read failure stops startup.+// Like Node, a name the process already carries is never overwritten, so a+// systemd EnvironmentFile still wins over a stale file in the release+// directory. The accepted syntax is DECISIONS D8: KEY=value lines, whole-line+// '#' comments, an optional 'export ' prefix, and a single- or double-quoted+// value. Quoted values keep their content verbatim; nothing is expanded.+func loadEnvironmentFile(name string) error {+ content, err := os.ReadFile(name)+ if errors.Is(err, fs.ErrNotExist) {+ return nil+ }+ if err != nil {+ return err+ }+ for _, line := range strings.Split(string(content), "\n") {+ line = strings.TrimSpace(line)+ line = strings.TrimSpace(strings.TrimPrefix(line, "export "))+ if line == "" || strings.HasPrefix(line, "#") {+ continue+ }+ key, value, assigned := strings.Cut(line, "=")+ key = strings.TrimSpace(key)+ if !assigned || key == "" {+ continue+ }+ if _, present := os.LookupEnv(key); present {+ continue+ }+ if err := os.Setenv(key, unquote(strings.TrimSpace(value))); err != nil {+ return err+ }+ }+ return nil+}++// unquote removes one matching pair of surrounding single or double quotes.+func unquote(value string) string {+ if len(value) < 2 || value[0] != value[len(value)-1] {+ return value+ }+ if value[0] != '"' && value[0] != '\'' {+ return value+ }+ return value[1 : len(value)-1]+}diff --git a/cmd/screener-server/main_test.go b/cmd/screener-server/main_test.gonew file mode 100644index 00000000..9bef26db--- /dev/null+++ b/cmd/screener-server/main_test.go@@ -0,0 +1,67 @@+package main++import (+ "os"+ "path/filepath"+ "testing"+)++func TestLoadEnvironmentFileFillsOnlyAbsentVariables(t *testing.T) {+ t.Setenv("SCREENER_TEST_PRESET", "from-the-service")+ path := filepath.Join(t.TempDir(), ".env")+ content := "# Application\n" ++ "SCREENER_TEST_PRESET=from-the-file\n" ++ "export SCREENER_TEST_EXPORTED=exported\n" ++ " SCREENER_TEST_QUOTED = \"a b#c\" \n" ++ "SCREENER_TEST_SINGLE=' padded '\n" ++ "SCREENER_TEST_EMPTY=\n" ++ "SCREENER_TEST_MARK=has#hash\n" ++ "\n" ++ "not an assignment\n" ++ "#SCREENER_TEST_COMMENTED=never\r\n" ++ "SCREENER_TEST_LAST=tail"+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {+ t.Fatal(err)+ }+ // Setenv registers the restore, Unsetenv makes the name absent for the run.+ for _, name := range []string{+ "SCREENER_TEST_EXPORTED", "SCREENER_TEST_QUOTED", "SCREENER_TEST_SINGLE",+ "SCREENER_TEST_EMPTY", "SCREENER_TEST_MARK", "SCREENER_TEST_COMMENTED",+ "SCREENER_TEST_LAST",+ } {+ t.Setenv(name, "absent")+ os.Unsetenv(name)+ }++ if err := loadEnvironmentFile(path); err != nil {+ t.Fatal(err)+ }+ for name, want := range map[string]string{+ // A variable the service already supplies is never replaced.+ "SCREENER_TEST_PRESET": "from-the-service",+ "SCREENER_TEST_EXPORTED": "exported",+ "SCREENER_TEST_QUOTED": "a b#c",+ "SCREENER_TEST_SINGLE": " padded ",+ "SCREENER_TEST_EMPTY": "",+ "SCREENER_TEST_MARK": "has#hash",+ "SCREENER_TEST_LAST": "tail",+ } {+ if got, present := os.LookupEnv(name); !present || got != want {+ t.Errorf("%s = %q, present %t; want %q", name, got, present, want)+ }+ }+ if value, present := os.LookupEnv("SCREENER_TEST_COMMENTED"); present {+ t.Errorf("commented assignment was applied as %q", value)+ }+}++func TestLoadEnvironmentFileIgnoresOnlyAMissingFile(t *testing.T) {+ directory := t.TempDir()+ if err := loadEnvironmentFile(filepath.Join(directory, ".env")); err != nil {+ t.Fatalf("a missing environment file must not stop startup: %v", err)+ }+ // A directory in place of the file is a read failure, not an absent file.+ if err := loadEnvironmentFile(directory); err == nil {+ t.Fatal("an unreadable environment file was ignored")+ }+}diff --git a/cmd/screener-server/release.go b/cmd/screener-server/release.gonew file mode 100644index 00000000..9b1aeec9--- /dev/null+++ b/cmd/screener-server/release.go@@ -0,0 +1,242 @@+package main++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "os"+ "regexp"+ "strings"+ "time"+)++// defaultReleaseAPIURL is DEFAULT_RELEASE_API_URL: the same published release+// contract the Browser update notice uses (src/client/lib/release-update.ts).+const defaultReleaseAPIURL = "https://api.github.com/repos/TNTcraftHIM/Screener/releases/latest"++// Exit codes are UPDATE_EXIT_CODES. deploy/check-release.sh forwards them, so a+// checker failure stays distinguishable from "an update exists".+const (+ exitUpToDate = 0+ exitUpdateAvailable = 10+ exitUpdateUnavailable = 20+ // exitUsage is the exit code parseArguments set when --current-file was+ // missing. Without it a forgotten argument reads as an unavailable check.+ exitUsage = 2+)++// releaseUsage is the usage string parseArguments threw, with this binary's+// name in place of the script's.+const releaseUsage = "Usage: screener-server --check-release --current-file <REVISION> [--api-url <URL>]"++const (+ // releaseTimeout bounds the whole check; an operator runs it interactively.+ releaseTimeout = 5 * time.Second+ // releasePathPrefix is RELEASE_PATH_PREFIX: the only accepted release page.+ releasePathPrefix = "/TNTcraftHIM/Screener/releases/tag/"+ releaseHost = "github.com"+ releaseAPIHost = "api.github.com"+)++// fullRevisionPattern is FULL_REVISION applied to an already lowercased value,+// which is why the JavaScript case-insensitive flag has no counterpart here.+var fullRevisionPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)++// Release status values are the "status" field of the printed JSON line, which+// deploy/check-release.sh reads; each maps to one exit code above.+const (+ statusUpToDate = "up-to-date"+ statusUpdateAvailable = "update-available"+ statusUnavailable = "unavailable"+)++// releaseResult is the single JSON line the checker prints. Field order is the+// JSON.stringify order of the ported object, and the pointers are the nulls: a+// value the check could not establish is present and null, never omitted.+type releaseResult struct {+ Status string `json:"status"`+ CurrentRevision *string `json:"currentRevision"`+ LatestRevision *string `json:"latestRevision"`+ ReleaseURL *string `json:"releaseUrl"`+}++// checkDeployedRelease is the --check-release entry point. It writes one JSON+// line and returns the process exit code. An unreadable revision file is an+// unavailable check rather than an update, which is what the ported script's+// silently swallowed read failure meant; an absent --current-file is a usage+// error, which is what parseArguments made it.+func checkDeployedRelease(ctx context.Context, currentFile, apiURL string, out io.Writer) int {+ if currentFile == "" {+ fmt.Fprintln(os.Stderr, releaseUsage)+ return exitUsage+ }+ current := ""+ if content, err := os.ReadFile(currentFile); err == nil {+ current = string(content)+ }+ result := checkRelease(ctx, current, apiURL, os.Getenv("GITHUB_TOKEN"))+ encoder := json.NewEncoder(out)+ encoder.SetEscapeHTML(false)+ if err := encoder.Encode(result); err != nil {+ return exitUpdateUnavailable+ }+ switch result.Status {+ case statusUpdateAvailable:+ return exitUpdateAvailable+ case statusUpToDate:+ return exitUpToDate+ default:+ return exitUpdateUnavailable+ }+}++// checkRelease ports checkRelease. Every failure - an unusable current+// revision, an unusable endpoint, a redirect, a timeout, a non-2xx reply or+// metadata that fails validation - collapses to the same unavailable result:+// the checker never guesses that an update exists.+func checkRelease(ctx context.Context, currentRevision, apiURL, token string) releaseResult {+ current := normalizeRevision(currentRevision)+ if current == "" {+ return unavailableResult(currentRevision)+ }+ endpoint, err := url.Parse(apiURL)+ if err != nil || (endpoint.Scheme != "https" && endpoint.Scheme != "http") {+ return unavailableResult(current)+ }++ ctx, cancel := context.WithTimeout(ctx, releaseTimeout)+ defer cancel()+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)+ if err != nil {+ return unavailableResult(current)+ }+ request.Header.Set("Accept", "application/vnd.github+json")+ request.Header.Set("X-GitHub-Api-Version", "2022-11-28")+ request.Header.Set("User-Agent", "Screener-release-check")+ if authorizesGitHub(endpoint, token) {+ request.Header.Set("Authorization", "Bearer "+strings.TrimSpace(token))+ }++ client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error {+ // The ported redirect: "error" policy. A moved release endpoint is not+ // followed, so the Authorization header cannot travel to another origin.+ return errors.New("release endpoint redirected")+ }}+ response, err := client.Do(request)+ if err != nil {+ return unavailableResult(current)+ }+ defer response.Body.Close()+ if response.StatusCode < 200 || response.StatusCode > 299 {+ return unavailableResult(current)+ }+ body, err := io.ReadAll(response.Body)+ if err != nil {+ return unavailableResult(current)+ }+ latest, releaseURL, ok := parseReleaseMetadata(body)+ if !ok {+ return unavailableResult(current)+ }+ status := statusUpdateAvailable+ if latest == current {+ status = statusUpToDate+ }+ return releaseResult{+ Status: status,+ CurrentRevision: ¤t,+ LatestRevision: &latest,+ ReleaseURL: &releaseURL,+ }+}++// authorizesGitHub reports whether the operator token may be sent to endpoint.+// A fixture, mirror or plaintext endpoint must never receive it, which is why+// the scheme and the host are both part of the rule.+func authorizesGitHub(endpoint *url.URL, token string) bool {+ return endpoint.Scheme == "https" &&+ strings.ToLower(endpoint.Hostname()) == releaseAPIHost &&+ strings.TrimSpace(token) != ""+}++// unavailableResult is unavailableResult: the current revision is reported when+// it is well formed and null otherwise.+func unavailableResult(currentRevision string) releaseResult {+ return releaseResult{Status: statusUnavailable, CurrentRevision: revisionOrNull(currentRevision)}+}++func revisionOrNull(value string) *string {+ revision := normalizeRevision(value)+ if revision == "" {+ return nil+ }+ return &revision+}++// normalizeRevision ports normalizeRevision, returning "" where it returned+// null: only a full 40-hex commit identifies a release.+func normalizeRevision(value string) string {+ revision := strings.ToLower(strings.TrimSpace(value))+ if !fullRevisionPattern.MatchString(revision) {+ return ""+ }+ return revision+}++// releaseMetadata is the subset of the GitHub release payload that is read.+// A tag_name or html_url of another type fails to decode, which is the+// rejection the JavaScript reached through typeof. Deviation: the JavaScript+// tested `draft === true`, so it read a draft of another type as "not a+// draft"; here such a payload fails to decode and the check reports+// unavailable. Only stricter, and a release payload the checker cannot+// understand must never be reported as an update.+type releaseMetadata struct {+ TagName *string `json:"tag_name"`+ HTMLURL *string `json:"html_url"`+ Draft *bool `json:"draft"`+ Prerelease *bool `json:"prerelease"`+}++// parseReleaseMetadata ports parseReleaseMetadata. It accepts one shape only: a+// published, non-draft release whose tag is a full commit revision and whose+// page is exactly https://github.com/TNTcraftHIM/Screener/releases/tag/<that+// revision> with no credentials, port, query or fragment. The returned URL is+// rebuilt from the validated parts so nothing unverified reaches the operator.+func parseReleaseMetadata(payload []byte) (revision string, releaseURL string, ok bool) {+ var metadata releaseMetadata+ if err := json.Unmarshal(payload, &metadata); err != nil {+ return "", "", false+ }+ if (metadata.Draft != nil && *metadata.Draft) ||+ (metadata.Prerelease != nil && *metadata.Prerelease) {+ return "", "", false+ }+ if metadata.TagName == nil || metadata.HTMLURL == nil {+ return "", "", false+ }+ revision = normalizeRevision(*metadata.TagName)+ if revision == "" {+ return "", "", false+ }+ parsed, err := url.Parse(*metadata.HTMLURL)+ if err != nil || parsed.Scheme != "https" ||+ strings.ToLower(parsed.Hostname()) != releaseHost || parsed.User != nil ||+ parsed.Port() != "" || parsed.RawQuery != "" || parsed.Fragment != "" {+ return "", "", false+ }+ // The escaped path is compared, so an encoded separator such as %2F cannot+ // smuggle another path past the prefix the way the decoded form would.+ path := parsed.EscapedPath()+ if !strings.HasPrefix(path, releasePathPrefix) {+ return "", "", false+ }+ tag, err := url.PathUnescape(strings.TrimPrefix(path, releasePathPrefix))+ if err != nil || normalizeRevision(tag) != revision {+ return "", "", false+ }+ return revision, "https://" + releaseHost + path, true+}diff --git a/cmd/screener-server/release_test.go b/cmd/screener-server/release_test.gonew file mode 100644index 00000000..9725425f--- /dev/null+++ b/cmd/screener-server/release_test.go@@ -0,0 +1,329 @@+package main++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++const (+ deployedRevision = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ latestRevision = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"+ latestReleaseURL = "https://github.com/TNTcraftHIM/Screener/releases/tag/" + latestRevision+ latestRelease = `{"tag_name":"` + latestRevision + `","html_url":"` + latestReleaseURL + `"}`+)++func TestParseReleaseMetadataAcceptsOnlyTheStrictReleaseIdentity(t *testing.T) {+ tagged := func(page string) string {+ return `{"tag_name":"` + latestRevision + `","html_url":"` + page + `"}`+ }+ testCases := []struct {+ name string+ payload string+ revision string+ url string+ }{+ {"published release", latestRelease, latestRevision, latestReleaseURL},+ {+ "uppercase tag normalizes",+ `{"tag_name":"` + strings.ToUpper(latestRevision) + `","html_url":"` + latestReleaseURL + `"}`,+ latestRevision, latestReleaseURL,+ },+ {"short tag", `{"tag_name":"short","html_url":"` + latestReleaseURL + `"}`, "", ""},+ {"other host", tagged("https://evil.example"), "", ""},+ {+ "userinfo",+ tagged("https://[email protected]/TNTcraftHIM/Screener/releases/tag/" + latestRevision),+ "", "",+ },+ {+ "port",+ tagged("https://github.com:8443/TNTcraftHIM/Screener/releases/tag/" + latestRevision),+ "", "",+ },+ {+ "plaintext page",+ tagged("http://github.com/TNTcraftHIM/Screener/releases/tag/" + latestRevision),+ "", "",+ },+ {"query", tagged(latestReleaseURL + "?asset=1"), "", ""},+ {"fragment", tagged(latestReleaseURL + "#assets"), "", ""},+ {+ "encoded path separator",+ tagged("https://github.com/TNTcraftHIM%2FScreener/releases/tag/" + latestRevision),+ "", "",+ },+ {+ "page tag disagrees with the release tag",+ tagged("https://github.com/TNTcraftHIM/Screener/releases/tag/" + deployedRevision),+ "", "",+ },+ {+ "draft",+ `{"tag_name":"` + latestRevision + `","html_url":"` + latestReleaseURL + `","draft":true}`,+ "", "",+ },+ {+ "prerelease",+ `{"tag_name":"` + latestRevision + `","html_url":"` + latestReleaseURL + `","prerelease":true}`,+ "", "",+ },+ {"missing page", `{"tag_name":"` + latestRevision + `"}`, "", ""},+ {"array payload", `[]`, "", ""},+ {"not an object", `"released"`, "", ""},+ {"not json", `nonsense`, "", ""},+ }+ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ revision, releaseURL, ok := parseReleaseMetadata([]byte(testCase.payload))+ if ok != (testCase.revision != "") || revision != testCase.revision ||+ releaseURL != testCase.url {+ t.Fatalf("parseReleaseMetadata(%s) = %q, %q, %t; want %q, %q",+ testCase.payload, revision, releaseURL, ok, testCase.revision, testCase.url)+ }+ })+ }+}++func TestCheckReleaseReportsTheDeployedComparison(t *testing.T) {+ testCases := []struct {+ name string+ current string+ status int+ body string+ wantStatus string+ wantCurrent string+ wantLatest string+ wantReleaseURL string+ wantRequestSent bool+ }{+ {+ name: "newer release", current: deployedRevision, status: http.StatusOK,+ body: latestRelease, wantStatus: "update-available", wantCurrent: deployedRevision,+ wantLatest: latestRevision, wantReleaseURL: latestReleaseURL, wantRequestSent: true,+ },+ {+ name: "same release", current: latestRevision, status: http.StatusOK,+ body: latestRelease, wantStatus: "up-to-date", wantCurrent: latestRevision,+ wantLatest: latestRevision, wantReleaseURL: latestReleaseURL, wantRequestSent: true,+ },+ {+ name: "endpoint unavailable", current: deployedRevision,+ status: http.StatusServiceUnavailable, body: "offline",+ wantStatus: "unavailable", wantCurrent: deployedRevision, wantRequestSent: true,+ },+ {+ name: "unusable metadata", current: deployedRevision, status: http.StatusOK,+ body: `{"tag_name":"v1","html_url":"https://evil.example"}`,+ // The published page failed validation, so no update is claimed.+ wantStatus: "unavailable", wantCurrent: deployedRevision, wantRequestSent: true,+ },+ {+ name: "deployed revision is not a release", current: "development",+ status: http.StatusOK, body: latestRelease,+ // No request at all: the check cannot compare an unknown deployment.+ wantStatus: "unavailable", wantCurrent: "", wantRequestSent: false,+ },+ }+ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ requested := false+ server := httptest.NewServer(http.HandlerFunc(+ func(writer http.ResponseWriter, request *http.Request) {+ requested = true+ if got := request.Header.Get("Accept"); got != "application/vnd.github+json" {+ t.Errorf("Accept = %q", got)+ }+ if got := request.Header.Get("X-GitHub-Api-Version"); got != "2022-11-28" {+ t.Errorf("X-GitHub-Api-Version = %q", got)+ }+ if got := request.Header.Get("User-Agent"); got != "Screener-release-check" {+ t.Errorf("User-Agent = %q", got)+ }+ writer.WriteHeader(testCase.status)+ _, _ = writer.Write([]byte(testCase.body))+ }))+ defer server.Close()++ result := checkRelease(t.Context(), testCase.current, server.URL, "")+ if requested != testCase.wantRequestSent {+ t.Fatalf("endpoint requested = %t; want %t", requested, testCase.wantRequestSent)+ }+ assertResult(t, result, testCase.wantStatus, testCase.wantCurrent,+ testCase.wantLatest, testCase.wantReleaseURL)+ })+ }+}++func TestCheckReleaseFailsClosedWithoutAUsableEndpoint(t *testing.T) {+ redirect := httptest.NewServer(http.HandlerFunc(+ func(writer http.ResponseWriter, request *http.Request) {+ http.Redirect(writer, request, "https://evil.example/releases", http.StatusFound)+ }))+ defer redirect.Close()+ reachable := httptest.NewServer(http.HandlerFunc(+ func(writer http.ResponseWriter, _ *http.Request) {+ _, _ = writer.Write([]byte(latestRelease))+ }))+ defer reachable.Close()++ cancelled, cancel := context.WithCancel(t.Context())+ cancel()+ testCases := []struct {+ name string+ ctx context.Context+ apiURL string+ }{+ {"redirected endpoint", t.Context(), redirect.URL},+ {"unsupported scheme", t.Context(), "file:///etc/passwd"},+ {"relative endpoint", t.Context(), "releases/latest"},+ {"cancelled check", cancelled, reachable.URL},+ }+ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ result := checkRelease(testCase.ctx, deployedRevision, testCase.apiURL, "")+ assertResult(t, result, "unavailable", deployedRevision, "", "")+ })+ }+}++func TestOperatorTokenReachesGitHubOnly(t *testing.T) {+ endpoints := []struct {+ name string+ url string+ token string+ authorized bool+ }{+ {"github api", defaultReleaseAPIURL, "operator-token", true},+ {"github api with padded token", defaultReleaseAPIURL, " operator-token ", true},+ {"github api without a token", defaultReleaseAPIURL, " ", false},+ {"plaintext github api", "http://api.github.com/repos", "operator-token", false},+ {"release host", "https://github.com/repos", "operator-token", false},+ {"local fixture", "http://127.0.0.1:8787/releases/latest", "operator-token", false},+ {"lookalike host", "https://api.github.com.evil.example/x", "operator-token", false},+ }+ for _, endpoint := range endpoints {+ t.Run(endpoint.name, func(t *testing.T) {+ parsed, err := url.Parse(endpoint.url)+ if err != nil {+ t.Fatal(err)+ }+ if got := authorizesGitHub(parsed, endpoint.token); got != endpoint.authorized {+ t.Fatalf("authorizesGitHub(%q) = %t; want %t",+ endpoint.url, got, endpoint.authorized)+ }+ })+ }++ var received http.Header+ fixture := httptest.NewServer(http.HandlerFunc(+ func(writer http.ResponseWriter, request *http.Request) {+ received = request.Header.Clone()+ _, _ = writer.Write([]byte(latestRelease))+ }))+ defer fixture.Close()+ checkRelease(t.Context(), deployedRevision, fixture.URL, "fixture-secret")+ if authorization := received.Get("Authorization"); authorization != "" {+ t.Fatalf("fixture endpoint received %q", authorization)+ }+}++func TestCheckDeployedReleasePrintsOneLineAndTheOperatorExitCode(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(+ func(writer http.ResponseWriter, _ *http.Request) {+ _, _ = writer.Write([]byte(latestRelease))+ }))+ defer server.Close()++ testCases := []struct {+ name string+ revision string+ wantCode int+ wantJSON string+ }{+ {+ "update available", deployedRevision + "\n", exitUpdateAvailable,+ `{"status":"update-available","currentRevision":"` + deployedRevision ++ `","latestRevision":"` + latestRevision ++ `","releaseUrl":"` + latestReleaseURL + `"}`,+ },+ {+ "up to date", latestRevision, exitUpToDate,+ `{"status":"up-to-date","currentRevision":"` + latestRevision ++ `","latestRevision":"` + latestRevision ++ `","releaseUrl":"` + latestReleaseURL + `"}`,+ },+ {+ "unreadable deployment", "", exitUpdateUnavailable,+ `{"status":"unavailable","currentRevision":null,` ++ `"latestRevision":null,"releaseUrl":null}`,+ },+ }+ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ currentFile := filepath.Join(t.TempDir(), "REVISION")+ if testCase.revision != "" {+ if err := os.WriteFile(currentFile, []byte(testCase.revision), 0o600); err != nil {+ t.Fatal(err)+ }+ }+ var out bytes.Buffer+ code := checkDeployedRelease(t.Context(), currentFile, server.URL, &out)+ if code != testCase.wantCode || out.String() != testCase.wantJSON+"\n" {+ t.Fatalf("checkDeployedRelease = %d, %q; want %d, %q",+ code, out.String(), testCase.wantCode, testCase.wantJSON+"\n")+ }+ })+ }+}++// assertResult compares the whole result through its JSON form so a value that+// must be null is distinguished from one that is merely empty.+func assertResult(t *testing.T, result releaseResult, status, current, latest, releaseURL string) {+ t.Helper()+ payload, err := json.Marshal(result)+ if err != nil {+ t.Fatal(err)+ }+ expected, err := json.Marshal(releaseResult{+ Status: status,+ CurrentRevision: reported(current),+ LatestRevision: reported(latest),+ ReleaseURL: reported(releaseURL),+ })+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(payload, expected) {+ t.Fatalf("result = %s; want %s", payload, expected)+ }+}++// reported turns the empty test expectation into the JSON null the result uses.+func reported(value string) *string {+ if value == "" {+ return nil+ }+ return &value+}++// release-update.mjs parseArguments threw the usage string and set+// process.exitCode = 2 when --current-file was absent, so the operator could+// tell a forgotten argument from a check that could not reach GitHub.+func TestCheckDeployedReleaseWithoutACurrentFileIsAUsageError(t *testing.T) {+ var out bytes.Buffer+ code := checkDeployedRelease(context.Background(), "", defaultReleaseAPIURL, &out)+ if code != exitUsage {+ t.Fatalf("exit code = %d, want %d", code, exitUsage)+ }+ if out.Len() != 0 {+ t.Fatalf("a usage error wrote %q, want no result line", out.String())+ }+}diff --git a/deploy/check-release.sh b/deploy/check-release.shindex ca72f060..7a82b942 100644--- a/deploy/check-release.sh+++ b/deploy/check-release.sh@@ -6,13 +6,6 @@ if [ "$#" -gt 1 ]; thenexit 2fi-repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"-node="${SCREENER_NODE:-/usr/local/bin/node}"current_file="${1:-/opt/screener/current/REVISION}"-if [ ! -x "$node" ]; then- printf 'Node runtime is unavailable: %s\n' "$node" >&2- exit 2-fi-arguments=("$repo_root/scripts/release-update.mjs" "--current-file" "$current_file")-exec "$node" "${arguments[@]}"+exec /opt/screener/current/screener-server --check-release --current-file "$current_file"diff --git a/deploy/release-app.sh b/deploy/release-app.shindex 2cf2c91b..8a6dd5fb 100644--- a/deploy/release-app.sh+++ b/deploy/release-app.sh@@ -7,8 +7,6 @@ if [ "$#" -ne 1 ]; thenexit 2fi-node='/usr/local/bin/node'-npm='/usr/local/bin/npm'upload_root='/opt/screener/uploads'release_root='/opt/screener/releases'current='/opt/screener/current'@@ -23,26 +21,20 @@ old_release=''test "$(dirname -- "$descriptor")" = "$upload_root"[[ "$public_origin" =~ ^https://[A-Za-z0-9.-]+(:[0-9]+)?$ ]]-IFS=$'\t' read -r revision release_id artifact_name artifact_sha manifest_name manifest_sha file_count main_asset < <(- "$node" --input-type=module --eval '- import { readFileSync } from "node:fs";- const value = JSON.parse(readFileSync(process.argv[1], "utf8"));- const fields = [- value.revision,- value.releaseId,- value.artifact,- value.artifactSha256,- value.manifest,- value.manifestSha256,- value.fileCount,- value.mainAsset,- ];- if (value.schema !== 1 || fields.some((field) =>- !["string", "number"].includes(typeof field) || String(field).includes("\t") || String(field).includes("\n")- )) process.exit(2);- process.stdout.write(fields.join("\t") + "\n");- ' "$descriptor"-)+# The descriptor is JSON.stringify(descriptor, null, 2): one field per line.+descriptor_text() {+ sed -n "s|^ \"$1\": \"\([A-Za-z0-9._/-]*\)\",\{0,1\}\$|\1|p" "$descriptor"+}++grep -qx ' "schema": 1,' "$descriptor"+revision="$(descriptor_text revision)"+release_id="$(descriptor_text releaseId)"+artifact_name="$(descriptor_text artifact)"+artifact_sha="$(descriptor_text artifactSha256)"+manifest_name="$(descriptor_text manifest)"+manifest_sha="$(descriptor_text manifestSha256)"+file_count="$(sed -n 's|^ "fileCount": \([0-9]\{1,\}\),\{0,1\}$|\1|p' "$descriptor")"+main_asset="$(descriptor_text mainAsset)"[[ "$revision" =~ ^[0-9a-f]{40}$ ]][[ "$release_id" =~ ^[0-9a-f]{7}$ ]]@@ -126,6 +118,7 @@ recover() {systemctl start screener.service || ok=0wait_for_health || ok=0fi+ rm -f -- "${current}.${release_id}-$$" "${current}.recover-${release_id}-$$" || ok=0if [ "$ok" -eq 1 ]; thencleanup_release || ok=0fi@@ -148,8 +141,6 @@ trap 'code=$?; if [ "$code" -ne 0 ]; then recover "$code"; fi' EXITexec 9>"$lock"flock -n 9-test -x "$node"-test -x "$npm"old_release="$(readlink -f -- "$current")"test "$(dirname -- "$old_release")" = "$release_root"test -d "$old_release"@@ -174,7 +165,7 @@ while IFS= read -r raw_entry; doesaccase "$entry" in/*|*\\*) printf 'invalid archive entry: %s\n' "$raw_entry" >&2; exit 41 ;;- LICENSE|REVISION|package.json|package-lock.json|dist|dist/client|dist/server|dist/client/*|dist/server/*) ;;+ LICENSE|REVISION|THIRD-PARTY-NOTICES.txt|screener-server) ;;*) printf 'unexpected archive entry: %s\n' "$raw_entry" >&2; exit 42 ;;esacdone < <(tar -tzf "$artifact")@@ -184,115 +175,50 @@ test "$(dirname -- "$(realpath -m -- "$stage")")" = "$release_root"chmod 0755 "$stage"tar --no-same-owner --no-same-permissions -xzf "$artifact" -C "$stage"-STAGE="$stage" MANIFEST="$manifest" FILE_COUNT="$file_count" REVISION="$revision" "$node" --input-type=module <<'NODE'-import { createHash } from 'node:crypto';-import { lstat, readFile, readdir } from 'node:fs/promises';-import { join, relative, sep } from 'node:path';--const stage = process.env.STAGE;-const text = await readFile(process.env.MANIFEST, 'utf8');-if (!text.endsWith('\n')) process.exit(61);-const lines = text.slice(0, -1).split('\n');-const expected = new Map();-for (const line of lines) {- const fields = line.split('\t');- if (fields.length !== 3 || !/^[0-9a-f]{64}$/.test(fields[0]) || !/^\d+$/.test(fields[1])) process.exit(62);- const path = fields[2];- if (!/^(LICENSE|REVISION|package(-lock)?\.json|dist\/(client|server)\/[A-Za-z0-9._/-]+)$/.test(path)) process.exit(63);- if (path.split('/').some((part) => part === '' || part === '.' || part === '..') || expected.has(path)) process.exit(64);- expected.set(path, { hash: fields[0], size: Number(fields[1]) });-}-if (expected.size !== Number(process.env.FILE_COUNT)) process.exit(65);--const actual = new Map();-const identities = new Set();-const pending = [stage];-while (pending.length) {- const directory = pending.pop();- for (const entry of await readdir(directory, { withFileTypes: true })) {- const absolute = join(directory, entry.name);- const metadata = await lstat(absolute);- if (metadata.isSymbolicLink()) process.exit(66);- if (metadata.isDirectory()) {- pending.push(absolute);- } else if (metadata.isFile()) {- const identity = `${metadata.dev}:${metadata.ino}`;- if (identities.has(identity)) process.exit(67);- identities.add(identity);- const path = relative(stage, absolute).split(sep).join('/');- const body = await readFile(absolute);- actual.set(path, { hash: createHash('sha256').update(body).digest('hex'), size: body.length });- } else process.exit(68);- }-}-if (actual.size !== expected.size) process.exit(69);-for (const [path, record] of expected) {- const found = actual.get(path);- if (!found || found.hash !== record.hash || found.size !== record.size) process.exit(70);-}-if ((await readFile(join(stage, 'REVISION'), 'ascii')) !== `${process.env.REVISION}\n`) process.exit(71);-console.log(`artifact_manifest=ok files=${actual.size} revision=${process.env.REVISION}`);-NODE+tab=$'\t'+if [ -n "$(tail -c 1 "$manifest")" ]; then exit 61; fi+if grep -qEv "^[0-9a-f]{64}${tab}[0-9]+${tab}[^${tab}]*$" "$manifest"; then exit 62; fi+if grep -qEv "^[0-9a-f]{64}${tab}[0-9]+${tab}(LICENSE|REVISION|THIRD-PARTY-NOTICES\.txt|screener-server)$" "$manifest"; then exit 63; fi+if [ -n "$(cut -f3 "$manifest" | sort | uniq -d)" ]; then exit 64; fi+if [ "$(wc -l < "$manifest")" -ne "$file_count" ]; then exit 65; fi+if [ -n "$(find "$stage" -type l)" ]; then exit 66; fi+if [ -n "$(find "$stage" -type f -printf '%D:%i\n' | sort | uniq -d)" ]; then exit 67; fi+if [ -n "$(find "$stage" ! -type f ! -type d ! -type l)" ]; then exit 68; fi+if [ "$(find "$stage" -type f | wc -l)" -ne "$file_count" ]; then exit 69; fi+if ! awk -F'\t' '{ printf "%s %s\n", $1, $3 }' "$manifest" | (cd "$stage" && sha256sum -c --strict --quiet -); then exit 70; fi+while IFS="$tab" read -r _ size path; do+ test "$(stat -c '%s' "$stage/$path")" = "$size" || exit 70+done < "$manifest"+if [ "$(cat "$stage/REVISION")" != "$revision" ]; then exit 71; fi+printf 'artifact_manifest=ok files=%s revision=%s\n' "$file_count" "$revision"-test -f "$stage/dist/client/$main_asset"-test -f "$stage/dist/server/server/index.js"-find "$stage/dist" -type d -exec chmod 0755 {} +-find "$stage/dist" -type f -exec chmod 0644 {} +-chmod 0644 "$stage/LICENSE" "$stage/REVISION" "$stage/package.json" "$stage/package-lock.json"+# Set the mode before testing it: an archive packaged on a host without an+# executable bit (Windows) records 0644, and the release owns the bit here.+chmod 0755 "$stage/screener-server"+test -x "$stage/screener-server"+chmod 0644 "$stage/LICENSE" "$stage/REVISION" "$stage/THIRD-PARTY-NOTICES.txt"+# Runs as the service user under the manager (no sudo/polkit round trip) so a+# binary or environment file the service cannot use fails here, before cutover.systemd-run \- --unit="screener-deps-${release_id}" \+ --uid=screener \+ --gid=screener \--wait \--collect \--quiet \--service-type=exec \- --property="WorkingDirectory=$stage" \- --property='CPUQuota=30%' \- --property='MemoryHigh=160M' \- --property='MemoryMax=256M' \- --property='MemorySwapMax=0' \- --property='RuntimeMaxSec=120s' \- "$npm" ci --omit=dev --ignore-scripts --no-audit --no-fund--previous_directory="$PWD"-cd "$stage"-sudo -u screener "$node" --input-type=module --eval "await Promise.all([import('sirv'), import('ws'), import('zod'), import('livekit-server-sdk'), import('./dist/server/server/config.js')]);"-"$node" --env-file=/etc/screener/screener.env --input-type=module --eval "import { loadConfig } from './dist/server/server/config.js'; loadConfig(process.env);"-cd "$previous_directory"+ --property='EnvironmentFile=/etc/screener/screener.env' \+ --property='Environment=SCREENER_ENV=production' \+ --property='RuntimeMaxSec=20s' \+ "$stage/screener-server" --check-config-OLD_RELEASE="$old_release" NEW_RELEASE="$stage" "$node" --input-type=module <<'NODE'-import { lstatSync, readdirSync } from 'node:fs';-import { join } from 'node:path';-function collect(root) {- const identities = new Set();- const pending = [root];- while (pending.length) {- const directory = pending.pop();- for (const name of readdirSync(directory)) {- const path = join(directory, name);- const metadata = lstatSync(path);- if (metadata.isSymbolicLink()) continue;- if (metadata.isDirectory()) pending.push(path);- else if (metadata.isFile()) identities.add(`${metadata.dev}:${metadata.ino}`);- }- }- return identities;-}-const oldFiles = collect(process.env.OLD_RELEASE);-const newFiles = collect(process.env.NEW_RELEASE);-let intersection = 0;-for (const identity of newFiles) if (oldFiles.has(identity)) intersection += 1;-if (intersection !== 0) process.exit(80);-console.log(`release_inode_intersection=0 new_regular_files=${newFiles.size}`);-NODE+if [ -n "$(comm -12 <(find "$old_release" -type f -printf '%D:%i\n' | sort -u) <(find "$stage" -type f -printf '%D:%i\n' | sort -u))" ]; then+ exit 80+fi+printf 'release_inode_intersection=0 new_regular_files=%s\n' \+ "$(find "$stage" -type f -printf '%D:%i\n' | sort -u | wc -l)"-old_asset="$(OLD_RELEASE="$old_release" "$node" --input-type=module --eval '- import { readFileSync } from "node:fs";- const html = readFileSync(`${process.env.OLD_RELEASE}/dist/client/index.html`, "utf8");- const match = html.match(/<script[^>]+src="\/(assets\/index-[A-Za-z0-9_-]+\.js)"/);- if (!match) process.exit(2);- process.stdout.write(match[1]);-')"+old_asset="$(curl -fsS --max-time 5 http://127.0.0.1:8787/ | grep -oE 'assets/index-[A-Za-z0-9_-]+\.js' | sed -n 1p)"release_owned=1mv -- "$stage" "$release"@@ -337,7 +263,7 @@ if [ "$old_asset" != "$main_asset" ]; thenfitest -z "$(journalctl -u screener.service --since "$cutover_since" -p warning --no-pager --output=cat)"-asset_sha="$(sha256sum "$release/dist/client/$main_asset" | awk '{print $1}')"+asset_sha="$(curl -fsS --max-time 8 "$public_origin/$main_asset" | sha256sum | awk '{print $1}')"release_owned=0cutover_started=0trap - ERR HUP INT TERM EXITdiff --git a/deploy/systemd/screener.service.example b/deploy/systemd/screener.service.exampleindex 425ab614..4c408d89 100644--- a/deploy/systemd/screener.service.example+++ b/deploy/systemd/screener.service.example@@ -9,8 +9,9 @@ Type=simpleUser=screenerGroup=screenerWorkingDirectory=/opt/screener/current+Environment=SCREENER_ENV=productionEnvironmentFile=/etc/screener/screener.env-ExecStart=/usr/local/bin/node dist/server/server/index.js+ExecStart=/opt/screener/current/screener-serverRestart=on-failureRestartSec=3sTimeoutStopSec=20sdiff --git a/docs/README.md b/docs/README.mdindex 9026ea78..f333a8b4 100644--- a/docs/README.md+++ b/docs/README.md@@ -51,6 +51,8 @@ ordinary implementation and UI detail.Client encoded fanout.- [ADR-0010](./adr/0010-cross-platform-client-runtime.md): cross-platform Clientruntime and self-contained package boundary.+- [ADR-0012](./adr/0012-shared-go-backend-core.md): one shared Go backend core+ for Hosted and Client, amending part of ADR-0010.## Evidence@@ -77,6 +79,12 @@ Rooms and repository practice:- [Cross-restart room recovery](./research/cross-restart-room-recovery.md)- [Agent context governance](./research/agent-context-governance.md)+Backend structure:++- [Server consolidation](./research/server-consolidation.md): Go core ownership+ and its acceptance checklist+- [Backend audit and refactor preparation](./research/backend-audit-1b01048.md)+Research records verified facts, measurements, assumptions, licenses, andremaining evidence boundaries. It does not own current product behavior or workpriority.diff --git a/docs/adr/0002-memory-resident-protected-rooms.md b/docs/adr/0002-memory-resident-protected-rooms.mdindex a2bb8905..4a837cec 100644--- a/docs/adr/0002-memory-resident-protected-rooms.md+++ b/docs/adr/0002-memory-resident-protected-rooms.md@@ -48,7 +48,7 @@ Stable mode stores only `roomId`, Host-token digest, Viewer-grant digest,authorization generation, code-entry policy, optional password verifier, anddormant lease deadline. It never stores raw tokens, grants, or passwords.-The schema is one exact current version using built-in `node:sqlite`, one+The schema is one exact current version on an embedded SQLite driver, oneconnection, one writer, and transactional room mutations. An unknown schema,wrong application identity, corrupt row, inaccessible path, or second ownerfails startup before signaling or LiveKit mutation. This private pre-release@@ -139,6 +139,7 @@ returns `ROOM_ACCESS_DENIED`.## Decision Sources- [Node.js SQLite](https://nodejs.org/docs/latest-v24.x/api/sqlite.html)+- [`modernc.org/sqlite` driver](https://pkg.go.dev/modernc.org/sqlite)- [SQLite transactional guarantees](https://www.sqlite.org/transactional.html)- [SQLite locking mode](https://sqlite.org/pragma.html#pragma_locking_mode)- [LiveKit reconnect behavior](https://docs.livekit.io/intro/basics/connect/#network-changes-and-reconnection)diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.mdindex 74a9ea31..2d2a354c 100644--- a/docs/adr/0005-automatic-hybrid-media-routing.md+++ b/docs/adr/0005-automatic-hybrid-media-routing.md@@ -18,6 +18,10 @@ physical evidence is in the routing research documents.## Decision+Hosted and Local always use this controller. The former rollout switch and+separate Host-star authority are removed; SFU availability is still selected by+configuration and the room's privacy policy, not by another routing mode.+### One Capacity RuleEvery non-server endpoint uses one server-authoritative steady outbound media-diff --git a/docs/adr/0009-optional-nat-prediction.md b/docs/adr/0009-optional-nat-prediction.mdindex 96f91986..e90c2941 100644--- a/docs/adr/0009-optional-nat-prediction.md+++ b/docs/adr/0009-optional-nat-prediction.md@@ -58,11 +58,12 @@ connection acquisition reuses the route controller's existing opportunity ledgerthe remaining attempts behind a working SFU route. A new connection canprovide another mapping opportunity, not guaranteed independent randomness:in particular, Native connections may retain the same shared UDP socket.- When prediction is enabled, that route-owned Browser P2P edge may also use- the existing bounded automatic-recovery budget (two ICE restarts) before- reporting the edge failed. Each restart creates a fresh ICE gathering- generation without adding a route candidate, SFU fallback, or second retry- state; unsuccessful recovery follows the normal route-failed path.+ A committed Browser P2P edge uses its existing two-request automatic-recovery+ budget: first ICE restart on the same connection, then connection rebuild.+ Recovery does not choose a new parent or add a route candidate; unsuccessful+ recovery follows the normal route-failed path. A prepared candidate remains owned by the route+ operation and is reported failed to that operation instead of starting a+ separate ICE-restart loop.## Consequencesdiff --git a/docs/adr/0010-cross-platform-client-runtime.md b/docs/adr/0010-cross-platform-client-runtime.mdindex 0823d1f2..b194ff02 100644--- a/docs/adr/0010-cross-platform-client-runtime.md+++ b/docs/adr/0010-cross-platform-client-runtime.md@@ -2,6 +2,10 @@- Status: accepted capability-provider architecture and native endpoint media boundary- Date: 2026-09-05+- Superseded in part: items 1, 5, 7, 12 (its supervisor sentence), 13, 14, and+ the local-package consequence were amended in place by+ [ADR-0012](./0012-shared-go-backend-core.md), which replaced the TypeScript+ server with one shared Go core. Every other item stands as written.## Context@@ -22,10 +26,11 @@ topologies and makes a saved Site unavailable while another room source runs.## Decision-1. The TypeScript/Node core remains the sole owner of HTTP, room authority,- admission, signaling, and routing in every deployment. A future local package- runs that same server and the same built Browser assets with local- configuration; Go does not reimplement the product core.+1. One shared core is the sole owner of HTTP, room authority, admission,+ signaling, and routing in every deployment. The local package runs that same+ core and the same built Browser assets with local configuration; no+ deployment gets a second product core. Its implementation is owned by+ [ADR-0012](./0012-shared-go-backend-core.md).2. The packaged product is Screener Client. Its Go process is the cross-platformentry and native capability provider. It starts `/health` and one `/control`WebSocket on IPv4 loopback within ports `39721` through `39730` before room-@@ -45,11 +50,12 @@ topologies and makes a saved Site unavailable while another room source runs.native action, reuses it across successive media generations, and closes itwith the page; a picker, share, or room source does not own the socket. TheBrowser forwards current signaling and remains the participant.-5. A platform package contains the Go entry, a pinned Node runtime, and the same- server/client build used by Hosted Screener. It may also carry one process-- isolated capture binary and the pinned `cloudflared` sidecar. The Go entry- supervises child processes with bounded lifetime. Platform packaging is- metadata around that entry, not another long-running wrapper or UI.+5. A platform package contains one Go executable carrying the same core and+ embedded Browser assets used by Hosted Screener. It may also carry one+ process-isolated capture binary and the pinned `cloudflared` sidecar. Those+ sidecars are the only supervised children and keep their bounded lifetime.+ Platform packaging is metadata around that entry, not another long-running+ wrapper or UI.6. The system Browser remains the UI. Browser extensions, userscripts, Electron,Tauri, and resident services need new evidence before they can replace thissmaller boundary. A Client-opened Site stores a non-secret opt-in at that@@ -59,8 +65,9 @@ topologies and makes a saved Site unavailable while another room source runs.Client again.7. A self-contained Local deployment serves reachable LAN peers without acentral Screener service. Its explicit `--link` mode starts one accountless- Cloudflare Quick Tunnel for the same Node HTTP/WebSocket surface, injects the- resulting HTTPS origin before Node starts, and otherwise retains the same+ Cloudflare Quick Tunnel for the same HTTP/WebSocket surface, applies the+ resulting HTTPS origin to the local server configuration before that server+ starts listening, and otherwise retains the samememory RoomStore, Browser UI, Viewer grant, signaling, and route controller.The Host sends the ordinary invitation link and the Viewer needs only aBrowser. Cloudflare terminates this temporary control path; WebRTC media stays@@ -133,19 +140,21 @@ topologies and makes a saved Site unavailable while another room source runs.origin. Friends use the existing room invitation grant. No Client-specificroom authorization system is added.12. Local authority shutdown first ends every in-memory room through the current- `room-closed` path, then closes signaling and HTTP. The Go supervisor closes- Node stdin, waits, and applies one bounded process timeout. It does not- restart a vanished authority.-13. Client assembly consumes the immutable Web/Server application release from- the same full Git revision and an explicit supported target. The Go binary,- matching target Node runtime, and `app/REVISION` form one package; revision- mismatch fails rather than loading a stale private contract. Client-scoped- pull requests build every target and must start the assembled Local authority,- pass `/healthz`, and stop it cleanly before the candidate is accepted.-14. The root package manifest is the single build/runtime dependency contract:- Browser-only libraries stay in `devDependencies`, while release and Client- assembly install the same manifest with `--omit=dev` for the server runtime.- No second Client dependency list or post-install package surgery is used.+ `room-closed` path, then closes signaling and HTTP. The Client cancels the+ server context, calls that end-then-close sequence under one bounded+ timeout, and only then closes the public tunnel and the loopback service. It+ does not restart a vanished authority.+13. Client assembly consumes the immutable application release from the same full+ Git revision and an explicit supported target. The Go binary embeds that+ release's built Browser assets and the package `REVISION` records the same+ revision; a revision mismatch fails rather than loading a stale private+ contract. Client-scoped pull requests build every+ target and must start the assembled Local authority, pass `/healthz`, and+ stop it cleanly before the candidate is accepted.+14. The root package manifest is the single dependency contract for the Browser+ bundle and repository tooling. No host installs packages to run Screener, so+ the manifest has no runtime half, and no second Client dependency list or+ post-install package surgery is used.## Consequences@@ -153,9 +162,10 @@ Hosted and Local operation share one product contract and one route model. TheGo runtime acts as an optional capability provider when an activated Site orLocal page discovers it, but it is not a second room product. A mixed room doesnot expose endpoint implementation to routing policy. The runtime stays small until a-proven native capability needs a protocol field. The local package may contain-two internal processes while presenting one user entry; the supervisor, not a-compatibility protocol, owns their lifetime.+proven native capability needs a protocol field. The local package presents one+user entry and runs its room authority inside that same process; only the+optional capture and tunnel sidecars remain supervised children, and that entry,+not a compatibility protocol, owns their lifetime.Windows gates prove loopback discovery, Local static startup, automatic Hostaccess, LAN invitation construction, a three-Viewer Browser relay tree, twodiff --git a/docs/adr/0012-shared-go-backend-core.md b/docs/adr/0012-shared-go-backend-core.mdnew file mode 100644index 00000000..d17c50c5--- /dev/null+++ b/docs/adr/0012-shared-go-backend-core.md@@ -0,0 +1,111 @@+# ADR-0012: Shared Go Backend Core++- Status: accepted+- Date: 2026-09-06++## Context++One TypeScript/Node server owned HTTP, room authority, admission, signaling, and+routing. Hosted and Local composed the same application from it, and the packaged+Client supervised it as a Node child beside a pinned runtime and an extracted+application tree. [ADR-0010](./0010-cross-platform-client-runtime.md) accepted+that shape because a second implementation of rooms, signaling, or routing would+make the two deployments diverge without improving the media path.++That boundary is paid for in every deployment. The Client package carries a+language runtime and an installed dependency tree beside its Go entry, a+production host needs Node and npm to install and validate a release, and one+user entry runs two processes whose lifetime a supervisor owns. The Client+already owns a Go process, Pion media, and its capture sidecars, so the second+runtime buys only the existing server code.++Replacing that server is acceptable only if the result stays one implementation:+the same wire contract, the same room semantics, the same persistent schema, and+the same Browser build.++## Decision++1. One Go module at the repository root owns the product core.+ `cmd/screener-server` (Hosted) and `cmd/screener-client` (Client) are entry+ points over the same `internal/server` packages and own only their defaults,+ reachability, and lifecycle policy. Neither reimplements rooms, admission,+ signaling, or routing. The TypeScript server, its bundled runtime, the process+ supervisor, and the Client's runtime/application selection flags are deleted in+ the same boundary.+2. The Browser UI stays React/TypeScript. Node, npm, Vite, vitest, and `tsx`+ remain build and gate tooling and stop being a runtime requirement on any+ deployment or end-user host. `src/shared/protocol.ts` remains the Browser+ schema owner; one checked-in wire fixture is replayed by both a TypeScript and+ a Go test instead of hand-maintained parallel validation rules.+3. Both binaries serve the same built Browser assets embedded through+ `internal/server/webassets`. A binary built without those assets serves the+ API only rather than reading a second asset path, so every packaging and+ acceptance entry point runs the Vite build before the Go build.+4. One mutex in the signaling server guards every room, session, share, route,+ and SFU-ledger mutation, reproducing Node's single thread instead of+ per-object locks. Room-touching HTTP handlers, WebSocket handlers, and timer+ callbacks all acquire it, and the route controller decides beneath it without+ locking or performing I/O. This is a recorded ceiling whose upgrade path is+ per-room locks, not a throughput claim.+5. Every place the TypeScript code awaited I/O - password derivation, LiveKit+ calls, token issue - releases that lock, performs the work, reacquires the+ lock, and revalidates exactly the session, share, connection, publication,+ operation, and revision identities the TypeScript code checked after that+ await. Insertion-ordered structures preserve the JavaScript `Map` iteration+ order that participant, candidate, and timer decisions depend on. Room writes+ stay synchronous inside the lock and keep the current fail-fast storage+ policy: an unrecoverable authority write ends the process instead of+ continuing on divergent state.+6. LiveKit access uses the standard library: HS256 participant and service tokens+ plus Twirp JSON RoomService calls over `net/http`, with the current grants,+ bounded per-request timeout, per-managed-room serialization, and not-found+ rule. No LiveKit SDK is added.+7. Room persistence uses the pure-Go `modernc.org/sqlite` driver over the schema,+ pragmas, single exclusive connection, and recovery accepted in+ [ADR-0002](./0002-memory-resident-protected-rooms.md). Both storage modes,+ their validation, and their failure policy are unchanged, and no build+ requires a C toolchain.+8. The port changes no contract. Signaling stays `screener-v21`, the Client+ loopback stays v8, capture framing stays v4, and the HTTP API, cookies, error+ codes, and close codes keep their exact shapes. No compatibility alias, dual+ reader, or migration is added for a change of implementation language.++## Consequences++- The Client is one process. Room authority, the loopback capability service, and+ native media share it, so a panic in the server ends the Local session exactly+ as a crashed Node child did, and the capability service no longer survives a+ failed room authority. Hosted exits non-zero and systemd restarts it; nothing+ restarts a vanished authority in place.+- Package and runtime cost falls in three places: the Client package loses its+ bundled runtime and dependency tree, the application release becomes the server+ binary with its notices and revision, and a production host installs no+ packages during a release. One Windows 11 before/after run measured cold start+ to healthy 160 ms to 81 ms, idle resident memory 73.7 MiB to 10.4 MiB, and+ shipped Hosted bytes ~106.7 MB to ~14.0 MB; the+ [consolidation research](../research/server-consolidation.md) owns the method+ and the full table. Throughput and latency were not measured, and the port+ changes no media path.+- Release-time configuration validation and the operator update check are+ maintenance modes of the deployed binary, so the release wrapper and the+ production host need no Node; [deployment](../deployment.md) owns their exact+ commands.+- Development runs two processes: the Vite dev server for the Browser bundle and+ the Go application server behind it. The [README](../../README.md) owns those+ commands.+- ADR-0010 items 1, 5, 7, 12 (its supervisor sentence), 13, 14, and its+ two-internal-process consequence are superseded and amended in place. The rest+ of ADR-0010 - loopback control contract, capability boundary, native media+ adapters, launcher, and Local composition - is unchanged.+- Go is the only server implementation. A second room, signaling, persistence, or+ route-controller implementation stays out of the repository.++## Primary Sources++- [Go module layout](https://go.dev/doc/modules/layout)+- [Go `embed`](https://pkg.go.dev/embed)+- [`coder/websocket`](https://pkg.go.dev/github.com/coder/websocket)+- [`modernc.org/sqlite`](https://pkg.go.dev/modernc.org/sqlite)+- [LiveKit tokens and grants](https://docs.livekit.io/frontends/reference/tokens-grants/)+- [LiveKit RoomService API](https://docs.livekit.io/reference/other/roomservice-api/)+- [Server consolidation research](../research/server-consolidation.md)diff --git a/docs/deployment.md b/docs/deployment.mdindex 72eec727..7e1e92ad 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -15,8 +15,8 @@ do not call this wrapper generic.## Release Boundary-A routine application release changes only the built Screener client/server and-its independent runtime dependency tree. It does not change infrastructure,+A routine application release changes only the built Screener server binary and+the Browser assets it embeds. It does not change infrastructure,service units, proxy/firewall rules, secrets, LiveKit/coturn configuration, orpersistent room state.@@ -30,7 +30,7 @@ backup; Git and immutable artifacts own history.## Build Host-Start from a clean exact revision with Node.js 24 and npm 11:+Start from a clean exact revision with Node.js 24, npm 11, and Go 1.26:```shnpm ci@@ -38,36 +38,37 @@ npm run checknode scripts/package-app-release.mjs <output-directory-outside-repository>```-The packager refuses a dirty tree, builds from that exact revision, records the+The packager refuses a dirty tree, builds the Browser assets and the+linux/amd64 server binary from that exact revision without cgo, records thefull revision, emits a runtime archive plus path/size/SHA-256 manifest and release descriptor, and-extracts its own artifact to verify it. Upload the archive, manifest, and-descriptor together to `/opt/screener/uploads`.+extracts its own artifact to verify it. The archive contains exactly+`screener-server`, `LICENSE`, `THIRD-PARTY-NOTICES.txt`, and `REVISION`. Upload+the archive, manifest, and descriptor together to `/opt/screener/uploads`.The same application descriptor is also the Client assembly input. On each-target platform, provide that platform's Node executable and Go toolchain:+target platform, provide that platform's Go toolchain:```shSCREENER_GO=/path/to/go node scripts/assemble-client.mjs \/outside/repository/app-release/screener-<revision>.release.json \- /path/to/node \/outside/repository/Screener-Client \--target windows-amd64 \--capture /path/to/platform-capture \--tunnel /path/to/cloudflared```-Assembly refuses a dirty or different revision and emits one directory with-the Client executable, pinned Node runtime, application release, selected-sidecars, production dependencies, and matching `REVISION`. Its required target+Assembly refuses a dirty or different revision and emits one directory with the+Client executable, the Browser assets taken from that release and embedded in+it, the selected sidecars, notices, and matching `REVISION`. Its required targetis one of `windows-amd64`, `linux-amd64`, or `darwin-arm64`; every supplied-runtime must match it. It does not create an installer, auto-updater, release-tag, or compatibility bundle.+binary input must match it. It does not create an installer, auto-updater,+release tag, or compatibility bundle.The platform package also carries its native presentation metadata: Windowsembeds the icon in the Go executable, Linux emits a freedesktop desktop entryunder `share/`, and macOS emits a thin `.app` launcher with an ICNS resource.-The latter two are packaging metadata only and do not duplicate the Client or-Node runtime.+The latter two are packaging metadata only and do not duplicate the Client+executable.CI and local release-candidate builds use the same wrapper on the target'snative operating system:@@ -94,8 +95,8 @@ archive and its SHA-256 file; Actions retains candidates for 14 days. This isautomatic build output, not a tag, public GitHub Release, or deployment.Do not build or run the full repository check on a constrained production host.-The release wrapper installs only production dependencies in a transient,-CPU/memory/time-bounded unit.+That host runs only the packaged binary and needs no Node, npm, or dependency+install.## Update Check@@ -115,10 +116,11 @@ as no notice. It never downloads, replaces, or interrupts a running share.An operator can perform the corresponding read-only Server check:```sh-SCREENER_NODE=/usr/local/bin/node bash deploy/check-release.sh+bash deploy/check-release.sh```-The command reads `/opt/screener/current/REVISION` and prints one JSON result.+The script runs the deployed binary's release check, which reads+`/opt/screener/current/REVISION` and prints one JSON result.Exit status `0` means the deployed revision is current, `10` means a newerrelease is available, and `20` means the check could not establish a validrelease identity. For a private repository, inject a short-lived `GITHUB_TOKEN`@@ -128,6 +130,14 @@ state. A different current-revision file may be supplied as its only argument.## Atomic Cutover+### First Go cutover prerequisite++The release wrapper is an application updater, not a systemd installer. Before+the first Go release, install and reload the tracked unit as described in the+[self-hosting cutover procedure](./operations/self-hosting.md#first-go-service-cutover).+Do not mix the new Go binary with the old Node unit or an environment file that+still sets `NODE_ENV`.+Run the tracked server entry with the uploaded descriptor:```sh@@ -142,14 +152,14 @@ The wrapper:manifest, current release, required services, and public origin;2. rejects unexpected archive paths, links, file types, or duplicate inodes;3. extracts to a new release directory and verifies every file hash and size;-4. installs an independent `node_modules` tree under resource limits and checks- runtime imports plus production configuration;+4. validates production configuration by running the packaged binary's+ configuration check as the service user under a bounded runtime;5. proves the old and new releases share no regular-file inode;6. atomically switches `/opt/screener/current`, starts the service, and pollsbounded local/public health; and7. restores the exact prior symlink and service when cutover or health fails.-Never hard-link dependency trees or recursively mutate permissions before the+Never hard-link release files or recursively mutate permissions before theinode audit: metadata changes would violate both releases. Expected servicestates should be read as data (`systemctl show`), not used as bare commands understrict-shell error traps.diff --git a/docs/operations/self-hosting.md b/docs/operations/self-hosting.mdindex 78113982..8f2d0039 100644--- a/docs/operations/self-hosting.md+++ b/docs/operations/self-hosting.md@@ -15,8 +15,8 @@ Browser <--------- DTLS-SRTP/UDP ----------> LiveKit :7882Screener -------- private RoomService -----> LiveKit :7880```-The tracked public baseline uses Node.js 24, nginx, a valid Web TLS-certificate, time synchronization, coturn 4.17.2 or a newer patched release,+The tracked public baseline uses nginx, a valid Web TLS certificate, time+synchronization, coturn 4.17.2 or a newer patched release,and LiveKit Server 1.13.6. LiveKit is required for the accepted SFU fallbackand tracked release wrapper. Keep the accepted patch pinned until itsreplacement passes the same Browser/SFU acceptance boundary.@@ -44,7 +44,8 @@ domains, certificates, users, and resource limits required by the host.## Initial Setup1. Configure DNS and TLS for the Web origin and STUN name.-2. Install Node.js, nginx, coturn, and the pinned LiveKit Server patch.+2. Install nginx, coturn, and the pinned LiveKit Server patch. The Screener+ release is one static binary and needs no language runtime.3. Create an unprivileged `screener` service account, `/opt/screener/releases`,`/opt/screener/uploads`, and an access-restricted environment file.4. Provision one verified initial immutable release and atomically point@@ -62,6 +63,33 @@ domains, certificates, users, and resource limits required by the host.8. Start coturn and LiveKit before Screener, then nginx. The LiveKitreadiness drop-in waits for its private control listener before Screener.+### First Go service cutover++The tracked unit starts the Go binary. A Node-to-Go deployment is a one-time+infrastructure transaction, not a routine application update: its failure path+must restore the old unit and environment before starting the prior release.+Prepare and verify that recovery before installing the unit:++```sh+sudo install -o root -g root -m 0644 \+ deploy/systemd/screener.service.example \+ /etc/systemd/system/screener.service+sudo systemctl daemon-reload+sudo systemctl show screener.service -p ExecStart -p Environment --no-pager+```++The output must show `/opt/screener/current/screener-server` and+`SCREENER_ENV=production`. The staged environment removes `NODE_ENV` and+`PEER_ASSISTED_MEDIA`, and replaces route `NODE_DEBUG` with `SCREENER_DEBUG=route`.+Keep credentials, ports, capacity and media configuration unchanged. Do not+restart the old release using the Go unit. The routine release wrapper owns+only application-symlink recovery; it does not install or restore systemd units.++The first-cutover transaction retains the previous unit, environment and closed+SQLite files, applies unit/environment plus release together, and restores those+exact values on failure before reloading systemd and restarting Node. After a+successful Go cutover, later application releases use the ordinary wrapper.+LiveKit must be dedicated to this Screener application, set`room.auto_create: false`, and expose its control listener only to the proxy andapplication host. Screener binds its own listener before touching LiveKit,diff --git a/docs/product/presentation-lifecycle.md b/docs/product/presentation-lifecycle.mdindex a9f293a8..4e1ccae1 100644--- a/docs/product/presentation-lifecycle.md+++ b/docs/product/presentation-lifecycle.md@@ -79,7 +79,9 @@ by one presentation reducer. Older route or media generations cannot overwritethe current result, and raw server errors are never rendered directly.The room route revision orders control messages; it is not a Viewer media-identity. A Viewer frame belongs to its local media generation and remains+identity. Reauthentication replaces the route snapshot authoritatively, even if+a replacement controller restarted revision numbering; ordinary updates remain+monotonic within that authority. A Viewer frame belongs to its local media generation and remainscurrent across unrelated graph revisions until that exact binding is replaced,invalidated, or terminally failed. Pending candidates never own the primarybadge, status line, or overlay while committed media remains proved. Thosediff --git a/docs/product/routing-transport.md b/docs/product/routing-transport.mdindex bc74b52d..96adaf1b 100644--- a/docs/product/routing-transport.md+++ b/docs/product/routing-transport.md@@ -16,9 +16,8 @@ owns ports and [self-hosting](../operations/self-hosting.md) owns service setup.- SFU-fed and peer-fed Viewers may both serve as ordinary peer parents.- A route ends in usable media, explicit bounded waiting, or clear failure.-The flagship deployment enables the all-room controller. A lightweight-deployment may disable peer assistance and keep only bounded direct Host edges;-it does not gain another transport or compatibility protocol.+Every deployment uses this controller. Omitting LiveKit keeps the same bounded+P2P graph without its SFU fallback; there is no separate Host-star mode.## Per-Share Route Policy@@ -98,10 +97,11 @@ begins only after that exact candidate commits as the active route.When NAT traversal is enabled, another operation may use the remainingconnection-attempt budget after rollback. The waiting display uses the actualserver-issued attempt ordinal; it never counts time as an attempted connection.-When NAT prediction is enabled, a route-owned P2P candidate may also use its-existing bounded automatic-recovery budget (two ICE restarts) before it reports-that failure; each restart creates a fresh mapping generation without reopening-the route candidate or introducing a second reconciliation loop.+Committed Browser P2P recovery first restarts ICE on the same connection, then+rebuilds that connection if necessary, within the existing two-request budget.+It does not require NAT prediction or reopen the route candidate. A prepared+candidate instead follows its current route operation's failure path, without+an independent restart loop.When a newly committed Host-root Viewer exposes unused downstream capacity whileanother Host root has at least two direct children, the same background operation maydiff --git a/docs/project-memory.md b/docs/project-memory.mdindex 0c16cd36..a33ed4bc 100644--- a/docs/project-memory.md+++ b/docs/project-memory.md@@ -1,16 +1,19 @@# Project Memory-Last updated: 2026-09-05+Last updated: 2026-09-06Screener is private, low-latency game screen sharing for one Host and up to 20authenticated friends. The current product surface is Web Host, Web Viewer, andBrowser relay; desktop and mobile Browsers are Viewer targets. It is not a-public broadcast service. Source includes a cross-platform Client that reuses-the TypeScript product core in a self-contained Local deployment or opens one-configured Site through the system Browser. Its Go entry presents Local,-temporary public-link, and saved-Site choices on every launch, starts one process--level loopback capability service, supervises Local Node when selected, and owns-the explicit native media path chosen in the same Web UI. Room source and media+public broadcast service. Hosted and Client run one shared Go core+([ADR-0012](./adr/0012-shared-go-backend-core.md)); Node and Vite build the+Browser UI and are not a runtime. Source includes a cross-platform Client that+runs that same core in a self-contained Local deployment or opens one configured+Site through the system Browser. Its single Go process presents Local, temporary+public-link, and saved-Site choices on every launch, starts one process-level+loopback capability service, owns the Local room authority in-process when+selected, and owns the explicit native media path chosen in the same Web UI.+Room source and mediaimplementation are independent: a topology may mix Browser and Native peerswithout changing participant, signaling, capacity, or route identity. NativeHost and H.264/VP8 Viewer receive/relay adapters share the same Pion media edge;@@ -84,7 +87,7 @@ implementation and routine UI detail.## Current Snapshot-Canonical source uses the strict `screener-v20` Browser/server contract with+The audit candidate uses the strict `screener-v21` Browser/server contract withcommitted media readiness, bounded candidate-relative progress and one-shotHost-root convergence. It retains optional SQLite room authority and theH.264/VP8 sender gate. [Status](./status.md) owns the compact current executiondiff --git a/docs/reference/configuration.md b/docs/reference/configuration.mdindex 8e83b2d5..9448871a 100644--- a/docs/reference/configuration.md+++ b/docs/reference/configuration.md@@ -1,14 +1,14 @@# Configuration And PortsThe tracked [`.env.example`](../../.env.example) is the executable schema-companion; `src/server/config.ts` is validation truth. Keep real values in the+companion; `internal/server/config` is validation truth. Keep real values in theservice secret store or an untracked access-restricted environment file.## Application Environment| Variable | Contract || --- | --- |-| `NODE_ENV` | `production` enables production-only validation. |+| `SCREENER_ENV` | `development` or `production`, default `development`; required for every server deployment: `production` enables production-only validation and the `Secure` site-access cookie. || `LISTEN_HOST` | Defaults to `0.0.0.0`; bare-metal production normally uses `127.0.0.1`. || `PORT` | Positive TCP port, default `8787`; the tracked release wrapper supports only that default. || `PUBLIC_BASE_URL` | Exact public HTTP(S) origin; production requires HTTPS. |@@ -17,13 +17,11 @@ service secret store or an untracked access-restricted environment file.| `ROOM_LEASE_SECONDS` | Positive dormant lease, default `86400`; active Host prevents expiry. || `ROOM_DATABASE_PATH` | Optional absolute SQLite file path; unset selects memory mode. || `MAX_VIEWERS_PER_ROOM` | `1..20`, default `8`. |-| `PEER_ASSISTED_MEDIA` | Enables the all-room bounded Peer/SFU controller. || `ENDPOINT_MEDIA_COPY_CAPACITY` | Shared endpoint steady-copy cap `1..3`, default `2`. || `STUN_URLS` | Comma-separated `stun:` URLs; at least one is required in production. || `NAT_PREDICTION_ENABLED` | Optional bounded NAT prediction capability, default `false`; requires an ordinary `STUN_URLS` endpoint on UDP 3478 plus reachable same-host UDP 3479/3480 listeners. |-Automatic SFU fallback is enabled only when `PEER_ASSISTED_MEDIA=true` and all-four values below are present:+Automatic SFU fallback is enabled when all four values below are present:| Variable | Contract || --- | --- |@@ -37,13 +35,15 @@ another. LiveKit tokens are short-lived media credentials and do not provideapplication E2EE.Removed access, room TTL, endpoint-tier, room-rollout, and TURN variables fail-startup even when blank. The private deployment is upgraded atomically; there-are no compatibility aliases or dual configuration readers.+startup even when blank. A present `NODE_ENV` fails the same way, so a stale+environment file cannot silently drop a deployment out of production. The+private deployment is upgraded atomically; there are no compatibility aliases or+dual configuration readers.-During pre-release route canaries, standard Node `NODE_DEBUG=screener-route`-enables sanitized room and participant-ordinal events. It records route reasons,-candidates, revisions, quality states and commit/failure outcomes, but not raw-Peer IDs, SDP, ICE candidates, tokens or media credentials.+During pre-release route canaries, `SCREENER_DEBUG=route` enables sanitized room+and participant-ordinal events. It records route reasons, candidates, revisions,+quality states and commit/failure outcomes, but not raw Peer IDs, SDP, ICE+candidates, tokens or media credentials.## Public And Private Portsdiff --git a/docs/research/backend-audit-1b01048.md b/docs/research/backend-audit-1b01048.mdnew file mode 100644index 00000000..5cbf629a--- /dev/null+++ b/docs/research/backend-audit-1b01048.md@@ -0,0 +1,106 @@+# Backend Audit Reconciliation++- Reviewed: 2026-09-06+- External evidence baseline: `1b01048e558cfa69b2c8216e658374d06037bfe4`.+- Integration baseline: `d3232cfd2929eafc94a0e3f003cd2bcdcd47089c`.+- Scope: verified lifecycle fixes and removal of the optional Host-star route.+ This is not the Go server rewrite or a new physical-media acceptance claim.++The external package contains 244 raw claims, not 244 confirmed defects.+Its handoff, source patch, and machine-readable findings remain external+evidence. This document records the independent reconciliation; the+[TODO ledger](../todo.md) alone owns remaining work.++## Accepted Corrections++- A quality candidate rejected before preparation consumes its existing+ opportunity, preventing an identical prepare/deny loop.+- Disposing a Native media bridge settles its pending start. Native relay+ callbacks bind the actual peer, including prepared children.+- A failed Native pause remains paused locally; a failed resume returns to the+ paused intent. No new pause protocol or parallel state owner is introduced.+- Prepared Native receive deadlines follow the server operation. Viewer teardown+ retires pending candidates and their recovery timers; terminal signaling+ teardown uses its existing stop owner.+- Authentication is an authoritative route snapshot, even when a replacement+ controller restarts revision numbering. Ordinary route updates retain their+ monotonic fence; session and media identities still reject stale callbacks.+- Only explicit `committed: true` publishes a newly committed connection+ identity. Stop-sharing presence is emitted after graph teardown.+- Room expiry and explicit abandonment share termination cleanup. Shutdown+ closes Vite before its shared listener and attempts every SFU drain even when+ one fails. Hosted shutdown reports failure explicitly.+- Native Receiver creation releases its unused GCC observer-map entry. Local+ startup rejects an already occupied health port; this is a duplicate-instance+ guard, not atomic socket handoff or cryptographic process identity.+- Native control keeps one reader, a bounded queue, and serial handling so socket+ close can cancel an outstanding system-picker operation. Explicit share close+ is a clean end; natural capture-process EOF still needs cause attribution.+- Gates use current loopback constants and explicit test STUN configuration.+ Packagers reject in-repository output. Deployment templates specify production+ mode and failed cutover cleanup removes its temporary links.+- Hygiene skips only GitHub's all-zero base SHA; a missing nonzero commit remains+ an error. Uncalled exports and obsolete gate aliases are removed.++## Resolved Decisions++The owner removed `PEER_ASSISTED_MEDIA`. Hosted and Local now use the same+bounded graph controller; absent LiveKit configuration still means P2P-only+service. Room privacy and topology-optimization controls remain independent.+The old environment variable must be removed before the next deployment.+There is no Host-star compatibility path to port. Removing the unused+authentication fields requires the coordinated private `screener-v21` release;+rollback to the prior server must also restore its environment configuration.++[ADR-0009](../adr/0009-optional-nat-prediction.md) distinguishes server-owned+three-attempt NAT acquisition from active Browser edge recovery. Active recovery+first restarts ICE, then rebuilds the connection if needed. Uncommitted candidates+return failure to their route operation; the unreachable extra local restart+branch was removed. Neither kind of restart guarantees a new NAT mapping.++The Client launch marker remains origin activation, not proof that the process+is alive. One failed discovery can mean contention or a permission delay, so+automatically deleting the marker would break the accepted saved-Site workflow.+Browser capture remains available in the existing picker.++## Claims Not Adopted Wholesale++- Catching every SQLite exception and continuing is not a complete recovery+ strategy: failed disconnect persistence can leave an active room indefinitely.+ Keep failure observable; design storage failure handling with its authority,+ rather than adding scattered catch-and-continue guards.+- A Local public invitation URL does not identify the transport used by a LAN+ visitor. Cookie issuance must support both HTTP LAN and HTTPS public access;+ globally dropping Secure or trusting arbitrary forwarded headers is not an+ acceptable shortcut.+- Audio capture can end silently while video continues. Ending healthy video is+ not accepted as the fix; explicit audio availability/recovery needs a coherent+ media contract. Native prepared-bridge fallback likewise needs a shared+ session-level failure owner, not a per-candidate flag that is immediately lost.+- Registering Receivers with Engine, deduplicating media ledgers, splitting page+ owners, and replacing full graph snapshots are refactor candidates, not proven+ present-day leaks or measured performance wins.+- No replacement media pipeline, custom scoring, periodic retries, TURN, IDL+ framework, compatibility readers, or new revision namespace was accepted.++## Refactor Direction++The [consolidation research](./server-consolidation.md) owns the shared Go module+layout that replaced the single TypeScript backend. Hosted and Local preserve+one graph/operation owner, with the Node runtime and superseded server packaging+removed in that same boundary.+Browser UI and native capture adapters are reuse boundaries, not rewrite targets.++Use the current behavioral tests as an oracle, not a requirement to preserve+private class structure. Extract cohesive packages without duplicating mutable+state; neither a file split nor one interface per old file is inherently an+improvement. Measure package size, startup, memory, and contract parity.++## Sources++- [WebRTC restartICE](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-restartice)+ defines ICE restart, not a promise of different network mappings.+- [coder/websocket](https://pkg.go.dev/github.com/coder/websocket)+ documents the connection read and cancellation contract.+- [Go module layout](https://go.dev/doc/modules/layout)+ supports multiple commands and shared internal packages.diff --git a/docs/research/cross-platform-client-runtime.md b/docs/research/cross-platform-client-runtime.mdindex cdcb7631..dbe2692f 100644--- a/docs/research/cross-platform-client-runtime.md+++ b/docs/research/cross-platform-client-runtime.md@@ -25,7 +25,7 @@ Chromium UI separate from a native voice/media module and updater. Oopz shipsFlutter, a second WebView, FFmpeg, Agora RTC, and Tencent LiteAV together; thatstack is substantially larger and duplicates media ownership. Screener followsthe first two products' process separation but not their UI runtimes, and avoids-Oopz's parallel RTC stacks: one Go supervisor, one Pion media core, and one thin+Oopz's parallel RTC stacks: one Go process, one Pion media core, and one thinsystem capture sidecar per platform remain sufficient. No binary code or privateapplication data was copied or inspected.@@ -49,25 +49,20 @@ credentials or route policy; those stay in the Browser/server protocol.## Client Composition-The existing TypeScript server owns the room and route contract. A local package-therefore composes three artifacts behind one user entry:--```text-screener-client-runtime/node-app/dist-```--The Client's Go entry starts and supervises the pinned Node runtime in Local-mode; Node serves the same Screener application with explicit local-configuration. In Site mode the system Browser opens the saved Site while the-same Go process remains its loopback native-media owner. The system Browser-remains the UI.+The Client and Hosted Screener run the same server core, so the local package is+one executable carrying the built Browser assets plus the optional capture and+tunnel sidecars; [the Client README](../../cmd/screener-client/README.md) owns+that layout. In Local mode the Client runs the server in its own process with+explicit local configuration. In Site mode it starts no server, and the system+Browser opens the saved Site while the same process remains its loopback+native-media owner. The system Browser remains the UI.Official Go process APIs require every started child to be waited and provide a-bounded `WaitDelay` for cancellation and stuck I/O. The current supervisor uses-stdin EOF for graceful Node shutdown, waits for the child, and does not restart-it. Windows is physically exercised; macOS and Linux remain package gates.+bounded `WaitDelay` for cancellation and stuck I/O. That guidance now covers the+capture and cloudflared sidecars only: the room authority is no longer a child+process, and Local shutdown is one bounded in-process sequence that ends rooms+before closing signaling and HTTP. Windows is physically exercised; macOS and+Linux remain package gates.## Local And Hosted Reachability@@ -77,12 +72,13 @@ its `loopback-network` permission; without that permission the cross-originrequest was blocked. The gate checks both expected outcomes.A self-contained LAN room uses a localhost Host URL and a selected LAN IPv4-Viewer URL backed by the same local TypeScript process. The Client persists an+Viewer URL backed by the same local Client process. The Client persists anoptional user-chosen access password and passes it only to its Host page in aconsumed fragment; a blank value leaves the Local site open. Explicit `--link`mode launches the packaged Cloudflare QuickTunnel against that same local HTTP server and supplies its random HTTPS origin-to Node before startup. The public path therefore reuses the exact frontend,+to the local server configuration before it starts listening. The public path+therefore reuses the exact frontend,WebSocket signaling, RoomStore, and Viewer grant instead of adding a rendezvousor second client protocol. Cloudflare carries control traffic; WebRTC media usespublic STUN and remains P2P-only.@@ -111,6 +107,12 @@ result selects one UI runtime; it does not create parallel products.## Current Evidence+The runs below are pre-port evidence: they exercised the package that bundled a+Node runtime and an extracted application tree. Their capture, discovery, media,+and network results still apply; every package composition, startup, and+shutdown claim must be re-verified on the single-binary Client before that build+is accepted.+On Windows with Chrome for Testing 151.0.7922.138:- the Local Client started its built static application and reached `/healthz`;diff --git a/docs/research/cross-restart-room-recovery.md b/docs/research/cross-restart-room-recovery.mdindex 031e0bde..f5752b2f 100644--- a/docs/research/cross-restart-room-recovery.md+++ b/docs/research/cross-restart-room-recovery.md@@ -68,7 +68,7 @@ truth path.## Storage And Deployment Boundary-The accepted implementation uses built-in Node `node:sqlite`, one exact schema,+The accepted implementation uses one embedded SQLite driver, one exact schema,one process connection and transactional low-frequency room writes. No ORM,event table, stats writer, compatibility reader or migration chain is added.Unknown schema, wrong application identity, corrupt row, inaccessible file or a@@ -96,6 +96,7 @@ restoring one later requires an explicit credential-invalidating decision.## Primary Sources- [Node.js SQLite](https://nodejs.org/docs/latest-v24.x/api/sqlite.html)+- [`modernc.org/sqlite` driver](https://pkg.go.dev/modernc.org/sqlite)- [SQLite transactional guarantees](https://www.sqlite.org/transactional.html)- [SQLite locking mode](https://sqlite.org/pragma.html#pragma_locking_mode)- [LiveKit reconnect behavior](https://docs.livekit.io/intro/basics/connect/#network-changes-and-reconnection)diff --git a/docs/research/server-consolidation.md b/docs/research/server-consolidation.mdindex 0dc234c9..eee7ede7 100644--- a/docs/research/server-consolidation.md+++ b/docs/research/server-consolidation.md@@ -1,50 +1,46 @@# Server Consolidation-- Reviewed: 2026-09-05-- Status: design candidate for the phase after Browser/Client acceptance+- Reviewed: 2026-09-06+- Status: implemented in the candidate; the acceptance list below is the+ remaining boundary- Scope: one shared Go backend for Hosted and self-contained Client operation## Current Ownership-Hosted [`index.ts`](../../src/server/index.ts) and Local-[`local-index.ts`](../../src/server/local-index.ts) already compose the same-[`createScreenerServer`](../../src/server/app.ts). The Go-[`clientapp`](../../native/client/internal/clientapp/app.go) supervises that Node-process and supplies native media; it does not duplicate room or route authority.-Consolidation replaces this sole backend rather than merging two implementations.--[`RoomStore`](../../src/server/room-store.ts) owns room authority and participants;-[`RoomDatabase`](../../src/server/room-database.ts) persists only access and lease-material. [`RoomRouteController`](../../src/server/room-route-controller.ts)-decides graph transitions without network I/O;-[`HybridMediaRouter`](../../src/server/hybrid-media-router.ts) executes signaling-and SFU effects. These are useful boundaries, not duplication to remove.--## Preparatory Simplification--1. Unify room termination cleanup. `SignalingServer.closeRoom` and `expireRooms`- in [`signaling.ts`](../../src/server/signaling.ts) delete the same timers,- connection evidence, share state and router resources before closing sockets.- Use one cleanup owner with the existing termination reason as input.-2. Remove the Hybrid connection-ID mirror. `connectionIdsByViewer` is populated- through router callbacks, then `handleViewerQualityEvidence` checks that map- and `resolveActiveViewerMediaEdge` again. Derive the Hybrid identity from the- committed edge; retain the evidence gate's own last-observation identity.- Cover reauthentication and in-place connection adoption before removing the- callbacks. The ordinary routing mode remains a separate consumer until its- product decision is made.+`cmd/screener-server` (Hosted) and `cmd/screener-client` (Client) compose the+same application from `internal/server` and own only their defaults,+reachability, and lifecycle policy. Within that scope `protocol` owns wire types,+strict decoding, and shared scalars; `config` owns environment validation plus+the Hosted and Local compositions; `room` owns room authority, participants, and+the SQLite database; `route` decides graph transitions without I/O; `signal`+executes signaling and SFU effects under one lock; `sfu` owns admission, LiveKit+room control, and token issue; `app` owns HTTP composition, site access, static+assets, and lifecycle; and `webassets` carries the embedded Browser bundle.+`internal/client` keeps the native, launcher, and platform boundaries and+supervises no server process. These are useful boundaries, not duplication to+remove.++## Structural Simplification++1. Room expiry and abandonment share one `terminateRoom` path in `signal`.+ Preserve the distinct semantics of stopping a share, ending a room, and+ restarting a persistent server.+2. The Hybrid connection-ID mirror is gone. The viewer-quality evidence path+ and the active media-edge lookup read the connection identity from the+ committed edge, and the evidence gate keeps its own last-observation+ identity; router tests cover in-place connection adoption during a rebuild+ and exact direct/peer-relayed evidence sources.These are structural simplifications, not reproduced functional failures.+The [audit reconciliation](./backend-audit-1b01048.md) separates verified fixes+from disputed recommendations. Its external staged plan is not an instruction+to perform extractions for their own sake.## Product Choice-`PEER_ASSISTED_MEDIA=false` remains a documented, default configuration in-[`.env.example`](../../.env.example). It owns a separate Host-star path in-`SignalingServer`, including child admission and SDP-answer readiness; Local and-production use the graph controller. Decide whether this mode still belongs to-the product before translating it. If automatic Peer topology is universal,-remove the switch and ordinary path together; otherwise retain its explicit-contract; this reachable mode is not dead code.+The graph controller is now universal. The former rollout switch and ordinary+Host-star signaling path were removed together, so Hosted and Local+share one route authority and LiveKit remains an optional fallback of that graph.## Target Composition@@ -54,14 +50,13 @@ cmd/screener-server -> shared server applicationcmd/screener-client -> shared server application + launcher + native mediainternal/server -> rooms, routing, HTTP/signaling, persistence, SFU adaptersinternal/client -> current native and platform boundaries-one React/Vite static artifact+one React/Vite static artifact -> embedded in both binaries```Use packages for cohesive owners and files for local concerns. Do not introducea framework layer per file, a second product API, or a multi-module build.-Move the existing `native/client` Go module into the common scope during the-migration. Hosted and Local construct the same validated application options;-entry points own their defaults, reachability and lifecycle policy.+Hosted and Local construct the same validated application options; entry points+own their defaults, reachability and lifecycle policy.Each room keeps one serialized state owner. Go HTTP/WebSocket handlers must notmutate room, share and route maps independently. Run password derivation and@@ -72,16 +67,19 @@ unrelated locks around each map.## Reusable Components-- Use standard [`net/http`](https://pkg.go.dev/net/http) and- [`embed`](https://pkg.go.dev/embed) for HTTP and built assets.-- Reuse the Client's [`coder/websocket`](https://pkg.go.dev/github.com/coder/websocket)- for signaling and the official [LiveKit Go SDK](https://github.com/livekit/server-sdk-go)- for room control and tokens.-- Keep the current SQLite schema and transactions. Compare a small- [`modernc.org/sqlite`](https://pkg.go.dev/modernc.org/sqlite) build/runtime gate- against package and locking needs before selecting a driver; no ORM is needed.-- Follow [Go's shared `internal` and multiple `cmd` guidance](https://go.dev/doc/modules/layout).- Retain current Pion, capture sidecars and control-tunnel ownership.+- Standard [`net/http`](https://pkg.go.dev/net/http) and+ [`embed`](https://pkg.go.dev/embed) serve HTTP and the built assets.+- Signaling reuses the Client's+ [`coder/websocket`](https://pkg.go.dev/github.com/coder/websocket).+- LiveKit room control and tokens use the standard library only: HS256 JWTs and+ Twirp JSON requests. The official+ [LiveKit Go SDK](https://github.com/livekit/server-sdk-go) adds a large module+ and license surface for a handful of call shapes and is not used.+- Room persistence keeps the current schema and transactions on the pure-Go+ [`modernc.org/sqlite`](https://pkg.go.dev/modernc.org/sqlite) driver, which+ builds without cgo and holds one exclusive connection; no ORM is needed.+- The layout follows [Go's shared `internal` and multiple `cmd` guidance](https://go.dev/doc/modules/layout).+ Pion, capture sidecars and control-tunnel ownership are unchanged.## Minimum Acceptance@@ -92,9 +90,40 @@ rollback, including stale asynchronous completions. Preserve short-lived SFUauthority and release resources only after physical drain confirmation.Use the same Browser contract scenarios against Hosted and Local, plus one-physical mixed Browser/Client media flow. Measure package size, startup and idle-memory before and after. Keep one strict wire contract and one schema owner;-avoid hand-maintained parallel TypeScript/Go validation rules. Retire the Node-server, bundled runtime, supervisor and old packaging paths in the same accepted+physical mixed Browser/Client media flow. Package size, startup and idle memory+are measured below. Keep one strict wire contract and one schema owner;+avoid hand-maintained parallel TypeScript/Go validation rules. The Node server,+bundled runtime, supervisor and old packaging paths retire in this same acceptedintegration boundary, preserving [ADR-0005](../adr/0005-automatic-hybrid-media-routing.md)-and [ADR-0010](../adr/0010-cross-platform-client-runtime.md).+and [ADR-0010](../adr/0010-cross-platform-client-runtime.md) as amended by+[ADR-0012](../adr/0012-shared-go-backend-core.md).++## Measured Before And After++One machine, 2026-09-06: Windows 11, Node 24.15.0, Go 1.26.6. A script spawned+each server with the same production configuration (`PORT=18787`, HTTPS public+origin, site-access password, one STUN URL, loopback listen host), polled+`/healthz` every 10 ms until `{"status":"ok"}`, waited 5 s idle, sampled+resident memory through PowerShell `WorkingSet64`, then killed the process.+Five runs per side; the median is reported. Before is the Node baseline at tag+`baseline-b20fd88`; after is `screener-server` under the same script.++| metric | before | after |+| --- | ---: | ---: |+| cold start to healthy | 160 ms | 81 ms |+| idle resident memory | 77,242,368 B | 10,928,128 B |+| shipped Hosted bytes | ~106.7 MB | ~14.0 MB |++The before total is the Node runtime (91,694,408 B), the production+`node_modules` tree (12,640,469 B in 1,513 files), `dist/client` (1,492,721 B)+and `dist/server` (856,898 B). The after total is the linux/amd64+`screener-server` built with `-s -w` and embedded assets (13,983,906 B) plus its+notices and `REVISION`. For reference, the windows/amd64 binaries are+14,276,608 B (`screener-server`) and 22,703,104 B (`screener-client`, which also+carries Pion and the terminal UI); the Client package additionally drops the+Node runtime and dependency tree it used to ship beside its Go executable.++The first two starts of a freshly built binary took 469 ms and 336 ms, which is+consistent with on-access antivirus scanning of a new executable; the median+above is the steady state. Not measured: throughput or latency under load, which+this port does not change, and the Linux deployment host.diff --git a/docs/status.md b/docs/status.mdindex 8f8e3b34..45d05aea 100644--- a/docs/status.md+++ b/docs/status.md@@ -1,14 +1,15 @@# Current Status-Last updated: 2026-09-05+Last updated: 2026-09-06This is the current execution index. Git history owns completed timelines;[verification status](./verification-status.md) owns evidence boundaries.-## Production+## Last Production Postflight-- `https://share.bonfire.icu` runs the strict `screener-v19` Browser/server- contract. Exact revision, release, artifact, manifest, and asset identity are+- The pre-Go postflight at `https://share.bonfire.icu` verified the strict+ `screener-v19` Browser/server contract. Current revision, release, artifact,+ manifest, and asset identity areretained by the immutable release descriptor, runtime `REVISION`, anddeployment record rather than copied into this source snapshot.- The latest scoped postflight found public health and the immutable Browser@@ -26,7 +27,7 @@ This is the current execution index. Git history owns completed timelines;- Public media listeners remain STUN-only UDP 3478 and LiveKit UDP 7882.Production enables optional NAT prediction with self-hosted STUN-only UDP3479 and 3480; ordinary `STUN_URLS` and media routes remain unchanged. Web- ingress is TCP 80/443; Node 8787 and LiveKit control/signaling 7880 are+ ingress is TCP 80/443; Screener 8787 and LiveKit control/signaling 7880 areprivate. TURN, ICE/TCP, media TCP, TLS relay, port 5349, and relay ranges aredisabled.- Browser video uses the content-independent H.264 sender gate with VP8@@ -50,11 +51,14 @@ This is the current execution index. Git history owns completed timelines;## Current Source-- Canonical source uses the strict `screener-v20` Browser/server contract.- Optional SQLite stable authority, non-expiring local preferred code, atomic- room replacement and the Host codec selector remain implemented; production- selects stable storage. Graceful restart, crash, timeout and network loss use- one reconnect state. LiveKit room teardown cannot stop Host-owned capture.+- Source uses the strict `screener-v21` Browser/server contract and one+ shared Go server core for Hosted and Client; the graph controller is universal+ and the Host-star configuration and wire path are removed. Optional SQLite+ stable authority, non-expiring+ local preferred code, atomic room replacement and the Host codec selector+ remain implemented; production selects stable storage. Graceful restart, crash,+ timeout and network loss use one reconnect state. LiveKit room teardown cannot+ stop Host-owned capture.- One event-driven controller owns the committed graph and one room-serial childoperation. Initial direct acquisition uses a five-second foreground window;exact transport-connected progress may retain that candidate through the@@ -82,9 +86,8 @@ This is the current execution index. Git history owns completed timelines;Enabled acquisition now shares a three-attempt budget in the route controller,across foreground P2P and background direct continuation. Viewer progressreflects actual candidate creation; quality trials retain their prior budget.- candidate and selected-path logs retain anonymous- `ordinary | predicted | unknown` provenance. Ordinary candidates and SFU- fallback remain unchanged.+ Candidate and selected-path logs retain anonymous `ordinary | predicted |+ unknown` provenance. Ordinary candidates and SFU fallback remain unchanged.- Every direct, Browser-relay, and Host SFU video sender owns one clone of itssource track; the original remains presentation and source authority only.Replacement, rollback, unpublish, physical LiveKit sender recreation, and@@ -145,14 +148,11 @@ This is the current execution index. Git history owns completed timelines;capture path remain unrun on a physical Mac. The Linux package now includes athin Portal/PipeWire/GStreamer hardware-H.264 capture adapter and passes itscompile, probe, package, startup, and shutdown checks; real desktop capture,- system audio, and recovery remain unproved. Client-scoped pull requests build- and run the scripted Local smoke on all three candidates before merge; a- validated `main` push emits them as short-lived Actions artifacts. One-link- mode preserves the Host Local authority while exposing its ordinary invitation- and HTTP/WebSocket control path through a session-scoped Quick Tunnel. An- independent Linux Pion Viewer- has received that native media over a direct ICE pair; remote Browser media- remains unproved. Site and one-link native shares also make one bounded+ system audio, and recovery remain unproved. One-link mode preserves the Host+ Local authority while exposing its ordinary invitation and HTTP/WebSocket+ control path through a session-scoped Quick Tunnel. An independent Linux Pion+ Viewer has received that native media over a direct ICE pair; remote Browser+ media remains unproved. Site and one-link native shares also make one boundedbest-effort PCP/UPnP/NAT-PMP mapping and Pion Universal-UDP-mux STUN discoveryon their media socket. A public-link run delivered 35 H.264 packets to anindependent Linux Viewer; no predicted-path win is yet claimed.@@ -186,13 +186,16 @@ This is the current execution index. Git history owns completed timelines;the deployment tree provides a read-only operator check against the same full-SHA release identity. Neither installs or interrupts a running share.-## Current Hold+## Release AcceptanceClient acceptance remains open for the reported Windows 10 display startup andgame-specific source behavior. Windows 11 display, minimized-source recovery,live presets and source-switch checks pass, but do not establish those reportsas resolved. NAT acquisition has controller and signaling coverage, not a new-public-network success-rate claim. Its added prepare progress field requires a-coordinated private-wire release: old strict pages cannot consume it safely.-Native codec and capability fields likewise require the matching bundled UI.-Production is unchanged; [TODO](./todo.md) owns acceptance and release work.+public-network success-rate claim. The candidate removes the Host-star+configuration and wire shape under `screener-v21` and moves the server to Go.+The authorized cutover needs matching Web/Client builds, the updated unit file+that replaces `NODE_ENV` with `SCREENER_ENV` before the first Go release,+an active-session check, and configuration restoration on rollback. The actual+deployment result belongs to its release record; [TODO](./todo.md) owns+remaining device/network acceptance.diff --git a/docs/todo.md b/docs/todo.mdindex 6f09563b..737138e7 100644--- a/docs/todo.md+++ b/docs/todo.md@@ -1,12 +1,18 @@# Current TODO Ledger-Last reviewed: 2026-09-05+Last reviewed: 2026-09-06Only **Now** is executable. Observations, old branches, experiments, and parkedtopics are not implementation authority.## Now+The returned Go core and frontend fixes are reconciled on the integration+candidate. The owner authorized hygiene cleanup, matched Server/Client builds,+one squash PR and a controlled deployment. Complete the existing checks and+first-Go unit/environment rollback before cutover. Device/network checks below+remain evidence gaps, not claims established by compilation or local loopback.+1. **Client physical acceptance.** Physically validate macOS and Linuxcapture/audio/recovery, a decoded public-link Browser Viewer, and a NAT caserescued beyond ordinary STUN, plus one mixed Browser/Native Viewer relay.@@ -25,8 +31,9 @@ topics are not implementation authority.4. **NAT acquisition and release acceptance.** Validate the implemented boundedthree-attempt owner on restricted Browser/Native pairs; a new connection doesnot guarantee a different NAT mapping. The added prepare progress field is- incompatible with old strict pages. Obtain owner approval for the coordinated- Web/Server/Client update and its active-share impact before merging/deploying;+ incompatible with old strict pages. The owner authorized the coordinated+ Web/Server/Client update; check active sessions before the cutover and+ retain the previous unit/environment alongside the application rollback;do not mix the new field into an ongoing old-version share.5. **Native codec acceptance.** Windows Native VP8 and Auto-selected H264 nowpass real Browser playback, live presets, paused changes and source-switch@@ -103,8 +110,8 @@ topics are not implementation authority.recommending either as a default for other deployments. Measure benefit ofthe implemented three-attempt budget before increasing it or claiming thatindependent connection attempts are independent NAT mappings.-14. **Unresolved route-state ownership claims.** Reopen lower-revision- reauthentication, active SFU failure during an unrelated prepare, and+14. **Unresolved route-state ownership claims.** Reopen active SFU failure+ during an unrelated prepare andmulti-child relay-evidence ownership only from an exact current-wirereproduction. Do not add a second revision namespace, parallel failurestate, or generalized evidence map from static possibility alone.@@ -119,17 +126,27 @@ topics are not implementation authority.explicit distribution work; do not add automatic install, containerself-update, Watchtower, compatibility ranges, or active-share interruptionbefore distribution and rollback evidence requires them.-16. **Go server consolidation.** Revisit replacing the sole TypeScript/Node- server owner with Go only after the Client feature and physical acceptance- boundaries are complete. First measure package, startup, and maintenance- gains. If accepted, migrate Hosted and Local together and delete the Node- server in the same boundary; do not create or retain two room, signaling,- persistence, or route-controller implementations. The- [consolidation draft](./research/server-consolidation.md) identifies the two- preparatory simplifications, the routing-mode product choice, and the shared- module and concurrency model; implementation follows Client acceptance.+16. **Go server consolidation.** Done in the candidate under+ [ADR-0012](./adr/0012-shared-go-backend-core.md): Hosted and Client share one+ Go core and the Node server, bundled runtime, and supervisor are deleted. Do+ not create or retain two room, signaling, persistence, or route-controller+ implementations. Package size, startup, and idle memory are measured in the+ [consolidation research](./research/server-consolidation.md). Remaining+ acceptance: rerun the physical Client and Browser-contract gates on this+ build, and sequence the deployment cutover, installing the updated unit,+ which replaces `NODE_ENV=production` with `SCREENER_ENV=production`, before+ the first Go release, then proving the release wrapper on a host without+ Node.17. **Opt-in diagnostics.** Replace ad hoc console logging with an explicitClient/Server debug option and bounded diagnostic export. Include revision,runtime state and sanitized capture/connection events; exclude credentials,media and raw process memory by default. A compressed feedback bundle needsdeliberate collection and retention, not automatic uploads.+18. **Remaining audit behavior.** During the owning refactor, reproduce and+ resolve optional Local-password cookies across HTTP LAN/HTTPS public origins;+ audio-process failure without stopping healthy video; natural capture EOF+ attribution; and Native prepared-bridge failure that must disable Native+ for the current Viewer session before retrying. Storage I/O failure needs+ an authority-consistent recovery policy, not catch-and-continue guards.+ The Local duplicate-launch guard is the in-process listener bind itself;+ it refuses a second Client on the same port and hands nothing over.diff --git a/docs/verification-status.md b/docs/verification-status.mdindex c04bd9fd..d5496749 100644--- a/docs/verification-status.md+++ b/docs/verification-status.md@@ -73,9 +73,15 @@ page retention, or capture keepalive. See## Screener ClientThe Go Client has unit coverage for persistent Local/Site configuration, LAN-address selection, Browser launch commands, bounded Node supervision, its-loopback port/Origin/Host/session contract, and exact package revision. The same-source cross-builds for Windows amd64, macOS arm64, and Linux amd64.+address selection, Browser launch commands, and its loopback+port/Origin/Host/session contract. The same source cross-builds for Windows+amd64, macOS arm64, and Linux amd64.++Every packaged-Client result in this section is pre-port evidence from the+package that bundled a Node runtime and an application tree. Capture, media,+discovery, and network results remain applicable; package assembly, startup, and+shutdown claims must be re-verified on the single-binary Client before it is+accepted.On Windows, Chrome 151.0.7922.175 completed the built Local page'sfragment access, Host surface, LAN invitation, and clean Client/Node/Browser@@ -83,9 +89,9 @@ shutdown. A separate synthetic run formed a P2P-only Host-plus-three-Viewer treewith one Browser relay and advancing frames at every Viewer. The Hosted Sitecompleted v8 loopback `hello`/`ping` after CDP granted `loopback-network`; withoutthat permission Chrome blocked it as expected.-The current clean-revision Windows package assembled with Node 24.19.0 passed the-package checks recorded for that revision; changing `app/REVISION` made it fail-before opening a listener. Its fresh Site loopback gate closed the Client,+The pre-port clean-revision Windows package assembled with Node 24.19.0 passed+the package checks recorded for that revision; changing `app/REVISION` made it+fail before opening a listener. Its fresh Site loopback gate closed the Client,Browser, port, and temporary profile.The same explicit-target assembly produced a Linux amd64 package that ran itsbundled Node application and loopback runtime on an independent Ubuntu host.@@ -158,10 +164,11 @@ retained image, and exited cleanly. The Native Host crash gate also terminated tClient process and observed the Host return to its start-share control withinthe bounded check. These results cover the current Windows build only.-The same clean revision assembled into a self-contained Windows package with a-matching Node runtime, application tree, and native capture process. Chrome 151-passed the package's Local startup gate and both Site loopback-permission arms;-revision mismatch remains fail-closed before a listener starts.+That same pre-port clean revision assembled into a self-contained Windows package+with a matching Node runtime, application tree, and native capture process.+Chrome 151 passed the package's Local startup gate and both Site+loopback-permission arms; revision mismatch remains fail-closed before a listener+starts.## Interpretation Rulesdiff --git a/native/client/go.mod b/go.modsimilarity index 81%rename from native/client/go.modrename to go.modindex 3c5bcadc..afbed38b 100644--- a/native/client/go.mod+++ b/go.mod@@ -1,4 +1,4 @@-module github.com/TNTcraftHIM/Screener/native/client+module github.com/TNTcraftHIM/Screenergo 1.25.0@@ -19,6 +19,9 @@ require (github.com/pion/stun/v3 v3.1.6github.com/pion/webrtc/v4 v4.2.18github.com/thesyncim/gopus v0.1.1+ golang.org/x/crypto v0.48.0+ golang.org/x/text v0.41.0+ modernc.org/sqlite v1.58.0)require (@@ -27,6 +30,7 @@ require (github.com/charmbracelet/x/windows v0.2.2 // indirectgithub.com/clipperhouse/displaywidth v0.11.0 // indirectgithub.com/clipperhouse/uax29/v2 v2.7.0 // indirect+ github.com/dustin/go-humanize v1.0.1 // indirectgithub.com/google/gopacket v1.1.19 // indirectgithub.com/google/uuid v1.6.0 // indirectgithub.com/huin/goupnp v1.2.0 // indirect@@ -34,8 +38,10 @@ require (github.com/koron/go-ssdp v0.0.4 // indirectgithub.com/libp2p/go-netroute v0.2.1 // indirectgithub.com/lucasb-eyer/go-colorful v1.4.1 // indirect+ github.com/mattn/go-isatty v0.0.24 // indirectgithub.com/mattn/go-runewidth v0.0.24 // indirectgithub.com/muesli/cancelreader v0.2.2 // indirect+ github.com/ncruces/go-strftime v1.0.0 // indirectgithub.com/pion/datachannel v1.6.2 // indirectgithub.com/pion/dtls/v3 v3.1.5 // indirectgithub.com/pion/mdns/v2 v2.1.0 // indirect@@ -44,12 +50,15 @@ require (github.com/pion/srtp/v3 v3.0.12 // indirectgithub.com/pion/transport/v4 v4.0.2 // indirectgithub.com/pion/turn/v5 v5.0.12 // indirect+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirectgithub.com/rivo/uniseg v0.4.7 // indirectgithub.com/wlynxg/anet v0.0.5 // indirectgithub.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect- golang.org/x/crypto v0.48.0 // indirectgolang.org/x/net v0.50.0 // indirectgolang.org/x/sync v0.22.0 // indirectgolang.org/x/sys v0.47.0 // indirectgolang.org/x/time v0.14.0 // indirect+ modernc.org/libc v1.75.6 // indirect+ modernc.org/mathutil v1.7.1 // indirect+ modernc.org/memory v1.12.1 // indirect)diff --git a/native/client/go.sum b/go.sumsimilarity index 74%rename from native/client/go.sumrename to go.sumindex f0cffcdc..6a7419ad 100644--- a/native/client/go.sum+++ b/go.sum@@ -26,10 +26,16 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUgithub.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=github.com/huin/goupnp v1.2.0 h1:uOKW26NG1hsSSbXIZ1IR7XP9Gjd1U8pnLaCMgntmkmY=github.com/huin/goupnp v1.2.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8=github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7BdWus=@@ -40,10 +46,14 @@ github.com/libp2p/go-netroute v0.2.1 h1:V8kVrpD8GK0Riv15/7VN6RbUQ3URNZVosw7H2v9tgithub.com/libp2p/go-netroute v0.2.1/go.mod h1:hraioZr0fhBjG0ZRXJJ6Zj2IVEVNx6tDTFQfSmcq7mQ=github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=+github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=+github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU=github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=github.com/netbirdio/go-nat v0.0.0-20260821095157-6b2c8c5c74e8 h1:pBxXEsxcsO3qVUND//5j1kelYlO57x5IrRviNF0+0iA=github.com/netbirdio/go-nat v0.0.0-20260821095157-6b2c8c5c74e8/go.mod h1:mFViabv4PpnoDw9w7W21a7xux6APA4q7KQZRsv4BCl8=github.com/pion/datachannel v1.6.2 h1:7EXQ8TH3vTouBUdRWYbcX2edSx9Yj6k5zl5P+qyxEPc=@@ -82,6 +92,8 @@ github.com/pion/webrtc/v4 v4.2.18 h1:smA/3g6Gy4RohM0VIZ5KKY/12TQbxv3XFgpUMyb2EUIgithub.com/pion/webrtc/v4 v4.2.18/go.mod h1:vmzi6s+rvhoIuT94DPqivB+0xJXs9rG4QRD+4MgBtlY=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=@@ -100,6 +112,8 @@ golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEMgolang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=+golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=+golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=@@ -113,9 +127,41 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wgolang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=+golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=+golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=+golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=+golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=+modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=+modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w=+modernc.org/ccgo/v4 v4.35.0/go.mod h1:qrVGs9S3Sr2Ztcg9ve+kTAYMp5a3YvWjo+SoN06kJ5I=+modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=+modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=+modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=+modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=+modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=+modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=+modernc.org/libc v1.75.6 h1:yKk8qo+Di4gkmvRboK8ocCqH22FiUCR6jRy2OwtCRus=+modernc.org/libc v1.75.6/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ=+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=+modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=+modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=+modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=+modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=+modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=+modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=+modernc.org/sqlite v1.58.0 h1:38u40/bwkfM7f0Myhosl+SEMltSDxnGdQf8o6Kjmys0=+modernc.org/sqlite v1.58.0/go.mod h1:rsD2CckafgObKC4DhBlGBf+RiHxkc3hINGt1Xw32tVY=+modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=+modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=diff --git a/native/client/internal/browser/open.go b/internal/client/browser/open.gosimilarity index 100%rename from native/client/internal/browser/open.gorename to internal/client/browser/open.godiff --git a/native/client/internal/browser/open_test.go b/internal/client/browser/open_test.gosimilarity index 100%rename from native/client/internal/browser/open_test.gorename to internal/client/browser/open_test.godiff --git a/native/client/internal/clientapp/app.go b/internal/client/clientapp/app.gosimilarity index 71%rename from native/client/internal/clientapp/app.gorename to internal/client/clientapp/app.goindex 9d60d25b..4b175050 100644--- a/native/client/internal/clientapp/app.go+++ b/internal/client/clientapp/app.go@@ -5,22 +5,25 @@ import ("encoding/json""errors""fmt"- "io"+ "log/slog"+ "net"+ "net/http""net/url"- "os""path/filepath"- "runtime""strings"+ "time"- "github.com/TNTcraftHIM/Screener/native/client/internal/browser"- "github.com/TNTcraftHIM/Screener/native/client/internal/clientconfig"- "github.com/TNTcraftHIM/Screener/native/client/internal/lan"- "github.com/TNTcraftHIM/Screener/native/client/internal/launcher"- "github.com/TNTcraftHIM/Screener/native/client/internal/loopback"- "github.com/TNTcraftHIM/Screener/native/client/internal/nativecapture"- "github.com/TNTcraftHIM/Screener/native/client/internal/nativecontrol"- "github.com/TNTcraftHIM/Screener/native/client/internal/publictunnel"- "github.com/TNTcraftHIM/Screener/native/client/internal/supervisor"+ "github.com/TNTcraftHIM/Screener/internal/client/browser"+ "github.com/TNTcraftHIM/Screener/internal/client/clientconfig"+ "github.com/TNTcraftHIM/Screener/internal/client/lan"+ "github.com/TNTcraftHIM/Screener/internal/client/launcher"+ "github.com/TNTcraftHIM/Screener/internal/client/loopback"+ "github.com/TNTcraftHIM/Screener/internal/client/nativecapture"+ "github.com/TNTcraftHIM/Screener/internal/client/nativecontrol"+ "github.com/TNTcraftHIM/Screener/internal/client/publictunnel"+ serverapp "github.com/TNTcraftHIM/Screener/internal/server/app"+ serverconfig "github.com/TNTcraftHIM/Screener/internal/server/config"+ "github.com/TNTcraftHIM/Screener/internal/server/webassets")const (@@ -28,6 +31,10 @@ const (publicSTUNURL = "stun:stun.cloudflare.com:3478"publicNATPredictionSTUNURLA = "stun:stun.miwifi.com:3478"publicNATPredictionSTUNURLB = "stun:stun.chat.bilibili.com:3478"+ // localShutdownTimeout bounds the ordered Local stop. The packaged smoke+ // allows 10 s between the stop request and the exit, so it stays well+ // inside that budget.+ localShutdownTimeout = 5 * time.Second)var BuildRevision = "development"@@ -37,8 +44,6 @@ type Options struct {SiteSet boolLocal boolLink bool- NodePath string- AppDirectory stringConfigPath stringLANAddress stringPort int@@ -114,7 +119,7 @@ func runConfigured(client *loopback.Server,) error {if config.Site != "" && !options.Local && !options.Link {- return runSite(ctx, config.Site, options, client)+ return runSite(config.Site, options, client)}return runLocal(ctx, options, config, client)}@@ -126,13 +131,9 @@ func runLauncher(config clientconfig.Config,client *loopback.Server,) error {- _, appDirectory, err := packagePaths(options.NodePath, options.AppDirectory)- if err != nil {- return err- }launch, err := launcher.Start(ctx,- filepath.Join(appDirectory, "dist", "client"),+ webassets.FS(),config.Site,BuildRevision,config.LocalAccessPassword,@@ -246,9 +247,10 @@ func validateMode(options Options) error {return nil}-func runSite(ctx context.Context, site string, options Options,- client *loopback.Server,-) error {+// runSite opens the configured Screener Site in the Browser and waits for the+// loopback server, which is the only thing this mode owns. It takes no context:+// cancellation reaches it through client.Done().+func runSite(site string, options Options, client *loopback.Server) error {var err errorlaunchURL := clientLaunchURL(site)view := consoleView{mode: "site", state: "starting", entry: launchURL}@@ -287,10 +289,6 @@ func runLocal(ctx context.Context, options Options, config clientconfig.Config,if err != nil {return err}- nodePath, appDirectory, err := packagePaths(options.NodePath, options.AppDirectory)- if err != nil {- return err- }var tunnel *publictunnel.ProcesspublicOrigin := ""if options.Link {@@ -306,42 +304,43 @@ func runLocal(ctx context.Context, options Options, config clientconfig.Config,publicOrigin = tunnel.Origin()}- entry := filepath.Join(appDirectory, "dist", "server", "server", "local-index.js")- stunURLs := []string(nil)- natPredictionStunURLs := []string(nil)- if options.Link {- stunURLs = []string{publicSTUNURL}- natPredictionStunURLs = []string{- publicNATPredictionSTUNURLA,- publicNATPredictionSTUNURLB,- }+ stunURLs, natPredictionStunURLs := localSTUNURLs(options.Link)+ localConfig, err := serverconfig.Local(serverconfig.LocalOptions{+ Port: options.Port,+ PublicAddress: selectedAddress,+ PublicOrigin: publicOrigin,+ AllowedAddresses: addresses,+ SiteAccessPassword: config.LocalAccessPassword,+ STUNURLs: stunURLs,+ NATPredictionSTUNURLs: natPredictionStunURLs,+ })+ if err != nil {+ return err}- var stdout, stderr io.Writer = os.Stdout, os.Stderr- if !options.console.machine {- stdout, stderr = io.Discard, options.console.logWriter()- }- localServer, err := supervisor.Start(ctx, supervisor.Command{- Path: nodePath,- Args: []string{entry},- Directory: appDirectory,- Environment: localEnvironment(- options.Port,- selectedAddress,- addresses,- config.LocalAccessPassword,- stunURLs,- natPredictionStunURLs,- publicOrigin,- ),- Stdout: stdout,- Stderr: stderr,- HealthURL: fmt.Sprintf("http://127.0.0.1:%d/healthz", options.Port),+ localServer, err := serverapp.New(serverapp.Options{+ Config: localConfig,+ Assets: webassets.FS(),+ // Machine mode inherits stderr; the interactive console shows server+ // diagnostics in its log pane, as the Node child's stderr did.+ Logger: slog.New(slog.NewTextHandler(options.console.logWriter(), nil)),})if err != nil {return err}- defer localServer.Close()+ if _, err = localServer.Listen(ctx); err != nil {+ // Binding the Local port is the duplicate-launch guard, and now an+ // atomic one: a second Client on the same port loses the bind instead+ // of racing the first for the room authority.+ var bindErr *net.OpError+ if errors.As(err, &bindErr) && bindErr.Op == "listen" {+ return fmt.Errorf("local server port is unavailable: %w", err)+ }+ return err+ }+ defer func() { _ = endLocalServer(localServer) }()+ // The readiness lines follow the listener, which the packaged smoke and the+ // public-link gate both read from stdout before they probe the port.if options.console.machine {if config.LocalAccessPassword == "" {fmt.Println("Local access: open")@@ -377,12 +376,7 @@ func runLocal(ctx context.Context, options Options, config clientconfig.Config,select {case <-ctx.Done():- return localServer.Close()- case <-localServer.Done():- if err = localServer.Err(); err != nil {- return errors.New("Screener Client local server stopped unexpectedly")- }- return nil+ return endLocalServer(localServer)case err = <-client.Done():if err != nil {return errors.New("Screener Client runtime stopped unexpectedly")@@ -471,40 +465,34 @@ func discoverNativeMedia(ctx context.Context, configuredPath string) nativeRunti}}-func packagePaths(nodePath, appDirectory string) (string, string, error) {- root := ""- if strings.TrimSpace(nodePath) == "" || strings.TrimSpace(appDirectory) == "" {- executable, err := os.Executable()- if err != nil {- return "", "", errors.New("Screener Client package location is unavailable")- }- root = filepath.Dir(executable)- }- if strings.TrimSpace(nodePath) == "" {- nodeName := "node"- if runtime.GOOS == "windows" {- nodeName += ".exe"- }- nodePath = filepath.Join(root, "runtime", "node", nodeName)- }- if strings.TrimSpace(appDirectory) == "" {- appDirectory = filepath.Join(root, "app")- }- nodePath = filepath.Clean(nodePath)- appDirectory = filepath.Clean(appDirectory)- if _, err := os.Stat(nodePath); err != nil {- return "", "", errors.New("bundled Node runtime is unavailable")- }- if _, err := os.Stat(filepath.Join(appDirectory, "dist", "server", "server", "local-index.js")); err != nil {- return "", "", errors.New("bundled Screener application is unavailable")- }- if BuildRevision != "development" {- revision, err := os.ReadFile(filepath.Join(appDirectory, "REVISION"))- if err != nil || strings.TrimSpace(string(revision)) != BuildRevision {- return "", "", errors.New("Client and application revisions do not match")- }+// localSTUNURLs is the Local room authority's ICE configuration. Only --link+// has a public path, so only --link configures public STUN and the bounded NAT+// prediction survey. The lists are literals on purpose: a gate that sets+// STUN_URLS is configuring the Client's own Pion edge, and that value must not+// reach the room server (which is why serverconfig.Local reads no environment).+func localSTUNURLs(link bool) (stunURLs []string, natPredictionSTUNURLs []string) {+ if !link {+ return nil, nil+ }+ return []string{publicSTUNURL},+ []string{publicNATPredictionSTUNURLA, publicNATPredictionSTUNURLB}+}++// endLocalServer is step 1 of the ADR-0010 item 12 unwind: every room ends,+// signaling closes, the listener drains and the room store closes, all before+// the tunnel and the loopback server go away. serverapp.End is memoised, so the+// deferred call after an explicit stop is a no-op. A serve loop or a drain that+// was already stopping reports http.ErrServerClosed or context.Canceled;+// neither is a Client failure, and Run turns any error into exit status 1,+// which is exactly what the packaged smoke fails on.+func endLocalServer(server *serverapp.Server) error {+ ctx, cancel := context.WithTimeout(context.Background(), localShutdownTimeout)+ defer cancel()+ err := server.End(ctx)+ if errors.Is(err, http.ErrServerClosed) || errors.Is(err, context.Canceled) {+ return nil}- return nodePath, appDirectory, nil+ return err}func tunnelExecutable(configured string) string {@@ -514,38 +502,6 @@ func tunnelExecutable(configured string) string {return publictunnel.PackagedExecutable()}-func localEnvironment(- port int,- publicAddress string,- addresses []string,- password string,- stunURLs []string,- natPredictionStunURLs []string,- publicOrigin string,-) []string {- overrides := map[string]string{- "SCREENER_CLIENT_PORT": fmt.Sprint(port),- "SCREENER_CLIENT_LAN_ADDRESS": publicAddress,- "SCREENER_CLIENT_ALLOWED_LAN_ADDRESSES": strings.Join(addresses, ","),- "SCREENER_CLIENT_LOCAL_PASSWORD": password,- "SCREENER_CLIENT_PUBLIC_ORIGIN": publicOrigin,- "STUN_URLS": strings.Join(stunURLs, ","),- "SCREENER_CLIENT_NAT_PREDICTION_STUN_URLS": strings.Join(natPredictionStunURLs, ","),- }- result := make([]string, 0, len(os.Environ())+len(overrides))- for _, entry := range os.Environ() {- name, _, found := strings.Cut(entry, "=")- if _, replaced := overrides[name]; found && replaced {- continue- }- result = append(result, entry)- }- for name, value := range overrides {- result = append(result, name+"="+value)- }- return result-}-func printEndpoint(endpoint loopback.Endpoint) error {payload, err := json.Marshal(endpoint)if err != nil {diff --git a/internal/client/clientapp/app_test.go b/internal/client/clientapp/app_test.gonew file mode 100644index 00000000..56ebb182--- /dev/null+++ b/internal/client/clientapp/app_test.go@@ -0,0 +1,137 @@+package clientapp++import (+ "net/url"+ "slices"+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/client/clientconfig"+ serverconfig "github.com/TNTcraftHIM/Screener/internal/server/config"+)++func TestClientLaunchURLMarksThePageWithoutChangingOrigin(t *testing.T) {+ value := clientLaunchURL("https://share.example/")+ parsed, err := url.Parse(value)+ if err != nil || parsed.Scheme != "https" || parsed.Host != "share.example" ||+ parsed.RawQuery != "" {+ t.Fatalf("launch URL = %q, %v", value, err)+ }+ fragment, err := url.ParseQuery(parsed.Fragment)+ if err != nil || fragment.Get("screener-client") != "1" {+ t.Fatalf("Client launch fragment = %q, %v", parsed.Fragment, err)+ }+}++func TestMissingCaptureKeepsViewerControlAvailable(t *testing.T) {+ native := discoverNativeMedia(t.Context(), "missing-capture-process")+ if native.capabilities.Video || native.capabilities.HardwareH264 {+ t.Fatalf("missing native capture = %+v", native)+ }+ control := native.controlFactory()()+ if control == nil {+ t.Fatal("missing capture disabled the native Viewer control")+ }+ _ = control.Close()+}++func TestLaunchURLPreservesLocalAccessInsideThePrivateFragment(t *testing.T) {+ value := clientLaunchURL("http://localhost:8787/#client-access=secret")+ parsed, err := url.Parse(value)+ if err != nil || parsed.RawQuery != "" {+ t.Fatalf("local native launch URL = %q, %v", value, err)+ }+ fragment, err := url.ParseQuery(parsed.Fragment)+ if err != nil || fragment.Get("client-access") != "secret" ||+ fragment.Get("screener-client") != "1" {+ t.Fatalf("local native launch fragment = %q, %v", parsed.Fragment, err)+ }+}++func TestLaunchURLEncodesAndClearsOptionalLocalAccess(t *testing.T) {+ value := clientLaunchURLWithLocalAccess(+ "http://localhost:8787/#retained=yes&client-access=old",+ "a+b&c?d=e",+ )+ parsed, err := url.Parse(value)+ if err != nil {+ t.Fatal(err)+ }+ fragment, err := url.ParseQuery(parsed.Fragment)+ if err != nil || fragment.Get("client-access") != "a+b&c?d=e" ||+ fragment.Get("screener-client") != "1" || fragment.Get("retained") != "yes" {+ t.Fatalf("encoded local launch fragment = %q, %v", parsed.Fragment, err)+ }++ open := clientLaunchURLWithLocalAccess("http://localhost:8787/#client-access=old", "")+ parsed, err = url.Parse(open)+ if err != nil {+ t.Fatal(err)+ }+ fragment, err = url.ParseQuery(parsed.Fragment)+ if err != nil || fragment.Get("client-access") != "" || fragment.Get("screener-client") != "1" {+ t.Fatalf("open local launch fragment = %q, %v", parsed.Fragment, err)+ }+}++func TestLinkModeKeepsOneLocalAuthority(t *testing.T) {+ config := clientconfig.Config{+ Version: 1,+ LocalAccessPassword: "abcdefghijklmnopqrstuvwxyzABCDEF",+ Site: "https://example.test",+ }+ selected, err := applyMode(config, Options{Link: true})+ if err != nil || selected.Site != config.Site {+ t.Fatalf("link mode = %+v, %v", selected, err)+ }+ if err = validateMode(Options{Link: true, SiteSet: true}); err == nil {+ t.Fatal("link mode accepted a separate Site")+ }+ if err = validateMode(Options{Link: true, Local: true}); err == nil {+ t.Fatal("link mode accepted a second Local selector")+ }+}++// The Local room authority owns its ICE configuration: a STUN_URLS meant for+// the Client's own Pion edge must not reach it, and only --link is public.+func TestLocalServerOwnsItsSTUNConfiguration(t *testing.T) {+ t.Setenv("STUN_URLS", "stun:inherited.example:3478")+ for _, testCase := range []struct {+ name string+ link bool+ stunURLs []string+ natPredictionSTUNURLs []string+ }{+ {name: "local"},+ {+ name: "link", link: true,+ stunURLs: []string{publicSTUNURL},+ natPredictionSTUNURLs: []string{+ publicNATPredictionSTUNURLA, publicNATPredictionSTUNURLB,+ },+ },+ } {+ t.Run(testCase.name, func(t *testing.T) {+ stunURLs, natPredictionSTUNURLs := localSTUNURLs(testCase.link)+ if !slices.Equal(stunURLs, testCase.stunURLs) ||+ !slices.Equal(natPredictionSTUNURLs, testCase.natPredictionSTUNURLs) {+ t.Fatalf("Local STUN selection = %v, %v", stunURLs, natPredictionSTUNURLs)+ }+ config, err := serverconfig.Local(serverconfig.LocalOptions{+ Port: 8787,+ PublicAddress: "192.168.1.2",+ AllowedAddresses: []string{"192.168.1.2"},+ SiteAccessPassword: "abcdefghijklmnopqrstuvwxyzABCDEF",+ STUNURLs: stunURLs,+ NATPredictionSTUNURLs: natPredictionSTUNURLs,+ })+ if err != nil {+ t.Fatal(err)+ }+ if !slices.Equal(config.STUNURLs, testCase.stunURLs) ||+ config.NATPredictionEnabled != testCase.link {+ t.Fatalf("Local server config = %v, NAT prediction %t",+ config.STUNURLs, config.NATPredictionEnabled)+ }+ })+ }+}diff --git a/native/client/internal/clientapp/console.go b/internal/client/clientapp/console.gosimilarity index 99%rename from native/client/internal/clientapp/console.gorename to internal/client/clientapp/console.goindex f7a2fb8f..d6915cdd 100644--- a/native/client/internal/clientapp/console.go+++ b/internal/client/clientapp/console.go@@ -13,7 +13,7 @@ import (tea "charm.land/bubbletea/v2""charm.land/lipgloss/v2"- "github.com/TNTcraftHIM/Screener/native/client/internal/browser"+ "github.com/TNTcraftHIM/Screener/internal/client/browser""github.com/charmbracelet/colorprofile""github.com/charmbracelet/x/ansi""github.com/charmbracelet/x/term"diff --git a/native/client/internal/clientapp/console_test.go b/internal/client/clientapp/console_test.gosimilarity index 100%rename from native/client/internal/clientapp/console_test.gorename to internal/client/clientapp/console_test.godiff --git a/native/client/internal/clientconfig/config.go b/internal/client/clientconfig/config.gosimilarity index 100%rename from native/client/internal/clientconfig/config.gorename to internal/client/clientconfig/config.godiff --git a/native/client/internal/clientconfig/config_test.go b/internal/client/clientconfig/config_test.gosimilarity index 100%rename from native/client/internal/clientconfig/config_test.gorename to internal/client/clientconfig/config_test.godiff --git a/native/client/internal/lan/addresses.go b/internal/client/lan/addresses.gosimilarity index 100%rename from native/client/internal/lan/addresses.gorename to internal/client/lan/addresses.godiff --git a/native/client/internal/lan/addresses_test.go b/internal/client/lan/addresses_test.gosimilarity index 100%rename from native/client/internal/lan/addresses_test.gorename to internal/client/lan/addresses_test.godiff --git a/native/client/internal/launcher/server.go b/internal/client/launcher/server.gosimilarity index 90%rename from native/client/internal/launcher/server.gorename to internal/client/launcher/server.goindex 695ed2ea..7a5a82dd 100644--- a/native/client/internal/launcher/server.go+++ b/internal/client/launcher/server.go@@ -5,21 +5,23 @@ import ("encoding/json""errors""io"+ "io/fs""net""net/http""net/url"- "os"- "path/filepath""strings""sync""time"- "github.com/TNTcraftHIM/Screener/native/client/internal/clientconfig"+ "github.com/TNTcraftHIM/Screener/internal/client/clientconfig")const (maxRequestBytes = 2 << 10shutdownTimeout = 2 * time.Second+ // launcherIndex is the Browser entry document. /client serves it directly+ // because that route belongs to the client-side router, not to the assets.+ launcherIndex = "index.html")type Mode string@@ -42,8 +44,8 @@ type Server struct {cancel context.CancelFunclistener net.ListenerhttpServer *http.Server+ assets fs.FSstatic http.Handler- indexPath stringsite stringlocalAccessPassword stringrevision string@@ -63,7 +65,10 @@ type Server struct {handledOnce sync.Once}-func Start(parent context.Context, staticDirectory, site, revision, localAccessPassword string) (*Server, error) {+// Start serves the launcher page and its API on a loopback port. assets is the+// built Browser UI, which the Client embeds; a nil file system means the binary+// carries no build and the launcher cannot run.+func Start(parent context.Context, assets fs.FS, site, revision, localAccessPassword string) (*Server, error) {if parent == nil {parent = context.Background()}@@ -76,8 +81,10 @@ func Start(parent context.Context, staticDirectory, site, revision, localAccessPif err != nil {return nil, errors.New("Client launcher local access password is invalid")}- indexPath := filepath.Join(staticDirectory, "index.html")- if metadata, err := os.Stat(indexPath); err != nil || !metadata.Mode().IsRegular() {+ if assets == nil {+ return nil, errors.New("Client launcher assets are unavailable")+ }+ if metadata, err := fs.Stat(assets, launcherIndex); err != nil || !metadata.Mode().IsRegular() {return nil, errors.New("Client launcher assets are unavailable")}listener, err := net.Listen("tcp4", "127.0.0.1:0")@@ -89,8 +96,8 @@ func Start(parent context.Context, staticDirectory, site, revision, localAccessPctx: ctx,cancel: cancel,listener: listener,- static: http.FileServer(http.Dir(staticDirectory)),- indexPath: indexPath,+ assets: assets,+ static: http.FileServer(http.FS(assets)),site: site,localAccessPassword: normalizedPassword,revision: strings.TrimSpace(revision),@@ -179,7 +186,7 @@ func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Requreturn}response.Header().Set("Cache-Control", "no-store")- http.ServeFile(response, request, server.indexPath)+ http.ServeFileFS(response, request, server.assets, launcherIndex)default:server.static.ServeHTTP(response, request)}diff --git a/native/client/internal/launcher/server_test.go b/internal/client/launcher/server_test.gosimilarity index 90%rename from native/client/internal/launcher/server_test.gorename to internal/client/launcher/server_test.goindex b5864447..a2b52e56 100644--- a/native/client/internal/launcher/server_test.go+++ b/internal/client/launcher/server_test.go@@ -3,14 +3,21 @@ package launcherimport ("bytes""encoding/json"+ "io/fs""net/http"- "os"- "path/filepath""strings""testing"+ "testing/fstest""time")+// clientAssets stands in for the embedded Vite build the Client ships.+func clientAssets() fs.FS {+ return fstest.MapFS{+ "index.html": {Data: []byte("<!doctype html><html><body>client</body></html>")},+ }+}+func TestLauncherServesStateAndCompletesOneSelection(t *testing.T) {server := startFixture(t, "https://share.example")origin := strings.TrimSuffix(server.URL(), "/client")@@ -140,19 +147,21 @@ func TestLauncherCarriesAndNormalizesAnOptionalLocalPassword(t *testing.T) {}func TestLauncherRejectsAnInvalidSavedSite(t *testing.T) {- directory := t.TempDir()- if err := os.WriteFile(- filepath.Join(directory, "index.html"),- []byte("client"),- 0o600,- ); err != nil {- t.Fatal(err)- }- if _, err := Start(t.Context(), directory, "https://example.test/path", "", ""); err == nil {+ if _, err := Start(t.Context(), clientAssets(), "https://example.test/path", "", ""); err == nil {t.Fatal("launcher accepted a Site path")}}+// A binary built without the Browser build has nothing to launch.+func TestLauncherRequiresTheEmbeddedBrowserBuild(t *testing.T) {+ if _, err := Start(t.Context(), nil, "", "", ""); err == nil {+ t.Fatal("launcher started without embedded assets")+ }+ if _, err := Start(t.Context(), fstest.MapFS{}, "", "", ""); err == nil {+ t.Fatal("launcher started without an index document")+ }+}+func TestLauncherRejectsInvalidSelections(t *testing.T) {for name, payload := range map[string]string{"unknown": `{"mode":"other","language":"en"}`,@@ -245,15 +254,7 @@ func startFixtureWithRevisionAndPassword(site, revision, password string,) *Server {t.Helper()- directory := t.TempDir()- if err := os.WriteFile(- filepath.Join(directory, "index.html"),- []byte("<!doctype html><html><body>client</body></html>"),- 0o600,- ); err != nil {- t.Fatal(err)- }- server, err := Start(t.Context(), directory, site, revision, password)+ server, err := Start(t.Context(), clientAssets(), site, revision, password)if err != nil {t.Fatal(err)}diff --git a/native/client/internal/loopback/protocol.go b/internal/client/loopback/protocol.gosimilarity index 100%rename from native/client/internal/loopback/protocol.gorename to internal/client/loopback/protocol.godiff --git a/native/client/internal/loopback/protocol_test.go b/internal/client/loopback/protocol_test.gosimilarity index 100%rename from native/client/internal/loopback/protocol_test.gorename to internal/client/loopback/protocol_test.godiff --git a/native/client/internal/loopback/server.go b/internal/client/loopback/server.gosimilarity index 95%rename from native/client/internal/loopback/server.gorename to internal/client/loopback/server.goindex df1649fa..02ecb913 100644--- a/native/client/internal/loopback/server.go+++ b/internal/client/loopback/server.go@@ -24,6 +24,7 @@ const (instanceTokenBytes = 32helloTimeout = 5 * time.SecondshutdownTimeout = 2 * time.Second+ controlQueueSize = 64 // MaxControlMessageBytes * 64 = 16 MiB worst-case.)type Options struct {@@ -262,6 +263,7 @@ func (server *Server) handleControl(response http.ResponseWriter, request *http.}server.setConnection(connection)defer server.releaseConnection(connection)+ defer connection.CloseNow()connection.SetReadLimit(MaxControlMessageBytes)helloContext, cancelHello := context.WithTimeout(server.ctx, helloTimeout)@@ -320,11 +322,30 @@ func (server *Server) handleControl(response http.ResponseWriter, request *http.}}()}+ reads := make(chan []byte, controlQueueSize)+ go func() {+ for {+ messageType, payload, readErr := connection.Read(controlContext)+ if readErr != nil || messageType != websocket.MessageText {+ cancelControl()+ return+ }+ select {+ case reads <- payload:+ case <-controlContext.Done():+ return+ default:+ cancelControl()+ return+ }+ }+ }()for {- messageType, payload, err = connection.Read(controlContext)- if err != nil || messageType != websocket.MessageText {- closeControl(connection, "control frame required")+ select {+ case <-controlContext.Done():return+ case payload = <-reads:+ messageType = websocket.MessageText}message, err = decodeEnvelope(payload)if err != nil {diff --git a/native/client/internal/loopback/server_test.go b/internal/client/loopback/server_test.gosimilarity index 75%rename from native/client/internal/loopback/server_test.gorename to internal/client/loopback/server_test.goindex ea14c015..eba05032 100644--- a/native/client/internal/loopback/server_test.go+++ b/internal/client/loopback/server_test.go@@ -4,10 +4,12 @@ import ("context""encoding/json""errors"+ "fmt""net""net/http""strconv""strings"+ "sync""testing""time"@@ -213,6 +215,107 @@ func TestControlSessionSharesOneBoundedSocketForResponsesAndEvents(t *testing.T)}}+func TestControlClosesTheSocketWhenItsReaderRejectsAFrame(t *testing.T) {+ server := startTestServer(t, testOrigin)+ connection := dialControl(t, server.Endpoint(), server.Endpoint().InstanceToken, testOrigin)+ defer connection.CloseNow()+ writeControl(t, connection, requestJSON("request_hello", "hello"))+ var ready controlMessage+ readControl(t, connection, &ready)+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)+ defer cancel()+ if err := connection.Write(ctx, websocket.MessageBinary, []byte("invalid")); err != nil {+ t.Fatal(err)+ }+ if _, _, err := connection.Read(ctx); err == nil || ctx.Err() != nil {+ t.Fatalf("server did not close its rejected control socket: %v", err)+ }+}++func TestControlCloseCancelsAHandlerWaitingForPicker(t *testing.T) {+ extension := &blockingControlSession{+ startedSignal: make(chan struct{}),+ closedSignal: make(chan struct{}),+ }+ server := startTestServerWithOptions(t, Options{+ AllowedOrigins: []string{testOrigin},+ NewControl: func() ControlSession {+ return extension+ },+ })+ connection := dialControl(t, server.Endpoint(), server.Endpoint().InstanceToken, testOrigin)+ writeControl(t, connection, requestJSON("request_hello", "hello"))+ var ready controlMessage+ readControl(t, connection, &ready)+ writeControl(t, connection, requestJSON("request_extension", "extension"))+ select {+ case <-extension.startedSignal:+ case <-time.After(time.Second):+ t.Fatal("control handler did not start")+ }+ connection.CloseNow()+ select {+ case <-extension.closedSignal:+ case <-time.After(time.Second):+ t.Fatal("closing the control socket did not release the picker handler")+ }++ deadline := time.Now().Add(time.Second)+ for {+ second, response, err := websocket.Dial(context.Background(),+ websocketURL(server.Endpoint())+"/control", &websocket.DialOptions{+ HTTPHeader: http.Header{"Origin": []string{testOrigin}},+ Subprotocols: []string{ControlSubprotocol + "." + server.Endpoint().InstanceToken},+ })+ if err == nil {+ second.CloseNow()+ return+ }+ if response != nil && response.Body != nil {+ response.Body.Close()+ }+ if time.Now().After(deadline) {+ t.Fatalf("control session was not released: %v", err)+ }+ time.Sleep(10 * time.Millisecond)+ }+}++func TestControlSessionProcessesARequestBurstInOrder(t *testing.T) {+ extension := &testControlSession{+ events: make(chan any, 1),+ closed: make(chan struct{}),+ }+ server := startTestServerWithOptions(t, Options{+ AllowedOrigins: []string{testOrigin},+ NewControl: func() ControlSession {+ return extension+ },+ })+ connection := dialControl(t, server.Endpoint(), server.Endpoint().InstanceToken, testOrigin)+ defer connection.CloseNow()+ writeControl(t, connection, requestJSON("request_hello", "hello"))+ var ready controlMessage+ readControl(t, connection, &ready)+ const burst = 32+ for index := 0; index < burst; index++ {+ writeControl(t, connection, requestJSON(+ fmt.Sprintf("request_extension_%d", index), "extension",+ ))+ }+ seen := make(map[string]bool, burst)+ for len(seen) < burst {+ var response controlMessage+ readControl(t, connection, &response)+ seen[response.ID] = true+ }+ for index := 0; index < burst; index++ {+ if !seen[fmt.Sprintf("request_extension_%d", index)] {+ t.Fatalf("request %d was not processed", index)+ }+ }+}+func TestStartAlwaysBindsToIPv4Loopback(t *testing.T) {server := startTestServer(t, testOrigin)host, _, err := net.SplitHostPort(server.Endpoint().Host)@@ -341,6 +444,28 @@ type testControlSession struct {closed chan struct{}}+type blockingControlSession struct {+ started sync.Once+ closed sync.Once+ startedSignal chan struct{}+ closedSignal chan struct{}+}++func (session *blockingControlSession) Handle(ctx context.Context, _ []byte) (any, error) {+ session.started.Do(func() { close(session.startedSignal) })+ <-ctx.Done()+ return nil, ctx.Err()+}++func (session *blockingControlSession) Events() <-chan any {+ return nil+}++func (session *blockingControlSession) Close() error {+ session.closed.Do(func() { close(session.closedSignal) })+ return nil+}+func (session *testControlSession) Handle(_ context.Context, payload []byte) (any, error) {message, err := decodeEnvelope(payload)if err != nil || message.Type != "extension" {diff --git a/native/client/internal/mediaedge/audio.go b/internal/client/mediaedge/audio.gosimilarity index 98%rename from native/client/internal/mediaedge/audio.gorename to internal/client/mediaedge/audio.goindex 9ac7da63..2b8dec3a 100644--- a/native/client/internal/mediaedge/audio.go+++ b/internal/client/mediaedge/audio.go@@ -6,7 +6,7 @@ import ("sync/atomic""time"- "github.com/TNTcraftHIM/Screener/native/client/internal/nativeaudio"+ "github.com/TNTcraftHIM/Screener/internal/client/nativeaudio""github.com/pion/rtp""github.com/pion/webrtc/v4""github.com/pion/webrtc/v4/pkg/media"diff --git a/native/client/internal/mediaedge/candidate_gathering.go b/internal/client/mediaedge/candidate_gathering.gosimilarity index 100%rename from native/client/internal/mediaedge/candidate_gathering.gorename to internal/client/mediaedge/candidate_gathering.godiff --git a/native/client/internal/mediaedge/edge.go b/internal/client/mediaedge/edge.gosimilarity index 100%rename from native/client/internal/mediaedge/edge.gorename to internal/client/mediaedge/edge.godiff --git a/native/client/internal/mediaedge/edge_test.go b/internal/client/mediaedge/edge_test.gosimilarity index 99%rename from native/client/internal/mediaedge/edge_test.gorename to internal/client/mediaedge/edge_test.goindex 3287d408..fb8dba95 100644--- a/native/client/internal/mediaedge/edge_test.go+++ b/internal/client/mediaedge/edge_test.go@@ -7,7 +7,7 @@ import ("testing""time"- "github.com/TNTcraftHIM/Screener/native/client/internal/nativeaudio"+ "github.com/TNTcraftHIM/Screener/internal/client/nativeaudio""github.com/pion/interceptor""github.com/pion/logging""github.com/pion/rtcp"diff --git a/native/client/internal/mediaedge/engine.go b/internal/client/mediaedge/engine.gosimilarity index 99%rename from native/client/internal/mediaedge/engine.gorename to internal/client/mediaedge/engine.goindex 240a72cd..bb443624 100644--- a/native/client/internal/mediaedge/engine.go+++ b/internal/client/mediaedge/engine.go@@ -9,7 +9,7 @@ import ("sync""time"- "github.com/TNTcraftHIM/Screener/native/client/internal/portmapping"+ "github.com/TNTcraftHIM/Screener/internal/client/portmapping""github.com/pion/ice/v4""github.com/pion/interceptor""github.com/pion/logging"diff --git a/native/client/internal/mediaedge/quality.go b/internal/client/mediaedge/quality.gosimilarity index 100%rename from native/client/internal/mediaedge/quality.gorename to internal/client/mediaedge/quality.godiff --git a/native/client/internal/mediaedge/quality_test.go b/internal/client/mediaedge/quality_test.gosimilarity index 100%rename from native/client/internal/mediaedge/quality_test.gorename to internal/client/mediaedge/quality_test.godiff --git a/native/client/internal/mediaedge/receiver.go b/internal/client/mediaedge/receiver.gosimilarity index 99%rename from native/client/internal/mediaedge/receiver.gorename to internal/client/mediaedge/receiver.goindex 000237c0..9d945347 100644--- a/native/client/internal/mediaedge/receiver.go+++ b/internal/client/mediaedge/receiver.go@@ -54,6 +54,7 @@ func (engine *Engine) NewReceiver(options ReceiverOptions) (*Receiver, webrtc.Seif err != nil {return nil, webrtc.SessionDescription{}, err}+ _ = engine.bandwidth.take(connection.ID())if err = connection.SetRemoteDescription(options.Offer); err != nil {_ = connection.Close()return nil, webrtc.SessionDescription{}, errdiff --git a/native/client/internal/mediaedge/receiver_test.go b/internal/client/mediaedge/receiver_test.gosimilarity index 95%rename from native/client/internal/mediaedge/receiver_test.gorename to internal/client/mediaedge/receiver_test.goindex 9241b84f..c5c4c183 100644--- a/native/client/internal/mediaedge/receiver_test.go+++ b/internal/client/mediaedge/receiver_test.go@@ -39,10 +39,19 @@ func TestReceiverCodecMatchesTheSingleNegotiatedAnswer(t *testing.T) {if err != nil {t.Fatal(err)}+ engine.bandwidth.mu.Lock()+ pendingBefore := len(engine.bandwidth.pending)+ engine.bandwidth.mu.Unlock()receiver, answer, err := engine.NewReceiver(ReceiverOptions{Offer: offer, EdgeCapacity: 1})if err != nil {t.Fatal(err)}+ engine.bandwidth.mu.Lock()+ pendingObservers := len(engine.bandwidth.pending)+ engine.bandwidth.mu.Unlock()+ if pendingObservers != pendingBefore {+ t.Fatalf("receiver changed pending bandwidth observers from %d to %d", pendingBefore, pendingObservers)+ }t.Cleanup(func() { _ = receiver.Close() })if receiver.Codec() != want || !strings.Contains(strings.ToLower(answer.SDP), want+"/90000") ||(strings.Contains(strings.ToLower(answer.SDP), "vp8/90000") && strings.Contains(strings.ToLower(answer.SDP), "h264/90000")) {diff --git a/native/client/internal/mediaedge/source.go b/internal/client/mediaedge/source.gosimilarity index 100%rename from native/client/internal/mediaedge/source.gorename to internal/client/mediaedge/source.godiff --git a/native/client/internal/nativeaudio/encoder.go b/internal/client/nativeaudio/encoder.gosimilarity index 100%rename from native/client/internal/nativeaudio/encoder.gorename to internal/client/nativeaudio/encoder.godiff --git a/native/client/internal/nativeaudio/encoder_test.go b/internal/client/nativeaudio/encoder_test.gosimilarity index 100%rename from native/client/internal/nativeaudio/encoder_test.gorename to internal/client/nativeaudio/encoder_test.godiff --git a/native/client/internal/nativecapture/json.go b/internal/client/nativecapture/json.gosimilarity index 100%rename from native/client/internal/nativecapture/json.gorename to internal/client/nativecapture/json.godiff --git a/native/client/internal/nativecapture/probe.go b/internal/client/nativecapture/probe.gosimilarity index 100%rename from native/client/internal/nativecapture/probe.gorename to internal/client/nativecapture/probe.godiff --git a/native/client/internal/nativecapture/probe_test.go b/internal/client/nativecapture/probe_test.gosimilarity index 100%rename from native/client/internal/nativecapture/probe_test.gorename to internal/client/nativecapture/probe_test.godiff --git a/native/client/internal/nativecapture/process_other.go b/internal/client/nativecapture/process_other.gosimilarity index 100%rename from native/client/internal/nativecapture/process_other.gorename to internal/client/nativecapture/process_other.godiff --git a/native/client/internal/nativecapture/process_windows.go b/internal/client/nativecapture/process_windows.gosimilarity index 100%rename from native/client/internal/nativecapture/process_windows.gorename to internal/client/nativecapture/process_windows.godiff --git a/native/client/internal/nativecapture/protocol.go b/internal/client/nativecapture/protocol.gosimilarity index 100%rename from native/client/internal/nativecapture/protocol.gorename to internal/client/nativecapture/protocol.godiff --git a/native/client/internal/nativecapture/protocol_test.go b/internal/client/nativecapture/protocol_test.gosimilarity index 100%rename from native/client/internal/nativecapture/protocol_test.gorename to internal/client/nativecapture/protocol_test.godiff --git a/native/client/internal/nativecapture/stream.go b/internal/client/nativecapture/stream.gosimilarity index 100%rename from native/client/internal/nativecapture/stream.gorename to internal/client/nativecapture/stream.godiff --git a/native/client/internal/nativecontrol/session.go b/internal/client/nativecontrol/session.gosimilarity index 97%rename from native/client/internal/nativecontrol/session.gorename to internal/client/nativecontrol/session.goindex d6a38313..8841fcd3 100644--- a/native/client/internal/nativecontrol/session.go+++ b/internal/client/nativecontrol/session.go@@ -14,10 +14,10 @@ import ("sync""unicode"- "github.com/TNTcraftHIM/Screener/native/client/internal/loopback"- "github.com/TNTcraftHIM/Screener/native/client/internal/nativecapture"- "github.com/TNTcraftHIM/Screener/native/client/internal/nativehost"- "github.com/TNTcraftHIM/Screener/native/client/internal/nativeviewer"+ "github.com/TNTcraftHIM/Screener/internal/client/loopback"+ "github.com/TNTcraftHIM/Screener/internal/client/nativecapture"+ "github.com/TNTcraftHIM/Screener/internal/client/nativehost"+ "github.com/TNTcraftHIM/Screener/internal/client/nativeviewer""github.com/pion/webrtc/v4")@@ -78,7 +78,7 @@ func (session *Session) Events() <-chan any {return session.events}-func (session *Session) Handle(_ context.Context, payload []byte) (any, error) {+func (session *Session) Handle(ctx context.Context, payload []byte) (any, error) {var envelope requestEnvelopeif err := decodeEnvelope(payload, &envelope); err != nil {return nil, err@@ -137,7 +137,7 @@ func (session *Session) Handle(_ context.Context, payload []byte) (any, error) {!validQualitySettings(request.Profile) {return nil, errors.New("native start-share request is invalid")}- return session.startShare(envelope, request)+ return session.startShare(ctx, envelope, request)case "update-share":var request updateShareRequestif err := decodeStrict(payload, &request); err != nil ||@@ -171,7 +171,7 @@ func (session *Session) Handle(_ context.Context, payload []byte) (any, error) {audio := request.Audio && session.capabilities.Summary().AudioFor(request.Source.Kind,)- if err := host.ReplaceSource(nativecapture.VideoOptions{+ if err := host.ReplaceSource(ctx, nativecapture.VideoOptions{Target: request.Source,AdapterIndex: request.AdapterIndex,EncoderIndex: request.EncoderIndex,@@ -341,6 +341,7 @@ func (session *Session) Close() error {}func (session *Session) startShare(+ ctx context.Context,envelope requestEnvelope,request startShareRequest,) (any, error) {@@ -351,7 +352,7 @@ func (session *Session) startShare(}session.mu.Unlock()profile := nativeQualityProfile(request.Profile)- host, err := nativehost.Start(session.ctx, nativehost.Options{+ host, err := nativehost.Start(ctx, nativehost.Options{ShareID: request.ShareID,CaptureProcess: session.captureProcess,Video: nativecapture.VideoOptions{diff --git a/native/client/internal/nativecontrol/session_test.go b/internal/client/nativecontrol/session_test.gosimilarity index 97%rename from native/client/internal/nativecontrol/session_test.gorename to internal/client/nativecontrol/session_test.goindex a31d0583..71cce83e 100644--- a/native/client/internal/nativecontrol/session_test.go+++ b/internal/client/nativecontrol/session_test.go@@ -3,8 +3,8 @@ package nativecontrolimport ("testing"- "github.com/TNTcraftHIM/Screener/native/client/internal/loopback"- "github.com/TNTcraftHIM/Screener/native/client/internal/nativecapture"+ "github.com/TNTcraftHIM/Screener/internal/client/loopback"+ "github.com/TNTcraftHIM/Screener/internal/client/nativecapture")func TestSTUNURLsUseTheCurrentBoundedWire(t *testing.T) {diff --git a/native/client/internal/nativecontrol/wire.go b/internal/client/nativecontrol/wire.gosimilarity index 99%rename from native/client/internal/nativecontrol/wire.gorename to internal/client/nativecontrol/wire.goindex 442726e6..922e0daf 100644--- a/native/client/internal/nativecontrol/wire.go+++ b/internal/client/nativecontrol/wire.go@@ -1,7 +1,7 @@package nativecontrolimport (- "github.com/TNTcraftHIM/Screener/native/client/internal/nativecapture"+ "github.com/TNTcraftHIM/Screener/internal/client/nativecapture""github.com/pion/webrtc/v4")diff --git a/native/client/internal/nativehost/profile.go b/internal/client/nativehost/profile.gosimilarity index 79%rename from native/client/internal/nativehost/profile.gorename to internal/client/nativehost/profile.goindex 5b85e0e2..7c790376 100644--- a/native/client/internal/nativehost/profile.go+++ b/internal/client/nativehost/profile.go@@ -1,6 +1,6 @@package nativehost-import "github.com/TNTcraftHIM/Screener/native/client/internal/nativecapture"+import "github.com/TNTcraftHIM/Screener/internal/client/nativecapture"type QualityProfile struct {Video nativecapture.VideoProfilediff --git a/native/client/internal/nativehost/session.go b/internal/client/nativehost/session.gosimilarity index 97%rename from native/client/internal/nativehost/session.gorename to internal/client/nativehost/session.goindex 6b89f7b6..621fa9cd 100644--- a/native/client/internal/nativehost/session.go+++ b/internal/client/nativehost/session.go@@ -11,8 +11,8 @@ import ("time""unicode/utf8"- "github.com/TNTcraftHIM/Screener/native/client/internal/mediaedge"- "github.com/TNTcraftHIM/Screener/native/client/internal/nativecapture"+ "github.com/TNTcraftHIM/Screener/internal/client/mediaedge"+ "github.com/TNTcraftHIM/Screener/internal/client/nativecapture""github.com/pion/webrtc/v4")@@ -333,7 +333,7 @@ func (session *Session) UpdateProfile(profile QualityProfile) error {return nil}- replacement, state, err := session.prepareVideo(options)+ replacement, state, err := session.prepareVideo(session.ctx, options)if err != nil {return err}@@ -355,6 +355,7 @@ func (session *Session) UpdateProfile(profile QualityProfile) error {}func (session *Session) ReplaceSource(+ ctx context.Context,options nativecapture.VideoOptions,audioEnabled bool,) error {@@ -375,14 +376,14 @@ func (session *Session) ReplaceSource(}options.Profile = profile.Videooptions.RestoreToken = ""- replacement, state, err := session.prepareVideo(options)+ replacement, state, err := session.prepareVideo(ctx, options)if err != nil {return err}var replacementAudio *nativecapture.Streamif hasAudio {replacementAudio, err = startAudioCapture(- session.ctx,+ ctx,session.captureProcess,options.Target,)@@ -413,10 +414,11 @@ func startAudioCapture(}func (session *Session) prepareVideo(+ ctx context.Context,options nativecapture.VideoOptions,) (*nativecapture.Stream, CaptureState, error) {replacement, err := nativecapture.StartVideo(- session.ctx,+ ctx,session.captureProcess,options,)@@ -424,7 +426,7 @@ func (session *Session) prepareVideo(return nil, CaptureState{}, errors.New("native capture could not start")}state, err := waitForCaptureProfile(- session.ctx,+ ctx,replacement,options.Profile,options.Codec,@@ -559,6 +561,14 @@ func (session *Session) run() {}()}result := <-videoDone+ session.mu.Lock()+ closed := session.closed+ session.mu.Unlock()+ if closed {+ // An explicit Close is a clean end, even if closing the capture process+ // made the video reader return an error.+ result = nil+ }session.cancel()session.mu.Lock()audioStream := session.audioStreamdiff --git a/native/client/internal/nativehost/session_test.go b/internal/client/nativehost/session_test.gosimilarity index 100%rename from native/client/internal/nativehost/session_test.gorename to internal/client/nativehost/session_test.godiff --git a/native/client/internal/nativeviewer/session.go b/internal/client/nativeviewer/session.gosimilarity index 99%rename from native/client/internal/nativeviewer/session.gorename to internal/client/nativeviewer/session.goindex aaab69e5..84ecd43f 100644--- a/native/client/internal/nativeviewer/session.go+++ b/internal/client/nativeviewer/session.go@@ -6,7 +6,7 @@ import ("sync""time"- "github.com/TNTcraftHIM/Screener/native/client/internal/mediaedge"+ "github.com/TNTcraftHIM/Screener/internal/client/mediaedge""github.com/pion/webrtc/v4")diff --git a/native/client/internal/portmapping/mapping.go b/internal/client/portmapping/mapping.gosimilarity index 100%rename from native/client/internal/portmapping/mapping.gorename to internal/client/portmapping/mapping.godiff --git a/native/client/internal/portmapping/mapping_test.go b/internal/client/portmapping/mapping_test.gosimilarity index 100%rename from native/client/internal/portmapping/mapping_test.gorename to internal/client/portmapping/mapping_test.godiff --git a/native/client/internal/publictunnel/process.go b/internal/client/publictunnel/process.gosimilarity index 100%rename from native/client/internal/publictunnel/process.gorename to internal/client/publictunnel/process.godiff --git a/native/client/internal/publictunnel/process_other.go b/internal/client/publictunnel/process_other.gosimilarity index 100%rename from native/client/internal/publictunnel/process_other.gorename to internal/client/publictunnel/process_other.godiff --git a/native/client/internal/publictunnel/process_test.go b/internal/client/publictunnel/process_test.gosimilarity index 100%rename from native/client/internal/publictunnel/process_test.gorename to internal/client/publictunnel/process_test.godiff --git a/native/client/internal/publictunnel/process_windows.go b/internal/client/publictunnel/process_windows.gosimilarity index 100%rename from native/client/internal/publictunnel/process_windows.gorename to internal/client/publictunnel/process_windows.godiff --git a/internal/server/app/access.go b/internal/server/app/access.gonew file mode 100644index 00000000..2a4b30aa--- /dev/null+++ b/internal/server/app/access.go@@ -0,0 +1,179 @@+package app++import (+ "crypto/hmac"+ "crypto/sha256"+ "crypto/subtle"+ "encoding/base64"+ "errors"+ "regexp"+ "strconv"+ "strings"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// Ported from src/server/access-session.ts.+const (+ defaultSessionTTLSeconds = 24 * 60 * 60+ cookieVersion = "v1"+)++var (+ // TS: /^\d+$/ over the expiry segment.+ accessExpiresPattern = regexp.MustCompile(`^[0-9]+$`)+ // TS: /^[A-Za-z0-9_-]{43}$/ — base64url of a 32-byte HMAC, unpadded.+ accessSignaturePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)+)++// siteAccessOptions mirrors SiteAccessOptions in access-session.ts.+type siteAccessOptions struct {+ // Password empty means site access is not required.+ Password string+ // Secure selects the __Host- cookie name and appends the Secure attribute.+ Secure bool+ // Now returns Unix milliseconds; nil uses the wall clock.+ Now func() int64+ // TTLSeconds of 0 stands for TS's absent `ttlSeconds`, i.e. 24 hours.+ TTLSeconds int+}++// siteAccessGate issues and verifies the stateless site-access cookie.+type siteAccessGate struct {+ password string+ secure bool+ now func() int64+ ttlSeconds int+}++// newSiteAccess mirrors the SiteAccess constructor, including its TTL check.+func newSiteAccess(options siteAccessOptions) (*siteAccessGate, error) {+ ttlSeconds := options.TTLSeconds+ if ttlSeconds == 0 {+ ttlSeconds = defaultSessionTTLSeconds+ }+ // TS: !Number.isSafeInteger(ttlSeconds) || ttlSeconds <= 0.+ if ttlSeconds < 0 || int64(ttlSeconds) > protocol.MaxSafeInteger {+ return nil, errors.New("Access session TTL must be a positive integer")+ }+ now := options.Now+ if now == nil {+ now = func() int64 { return time.Now().UnixMilli() }+ }+ return &siteAccessGate{+ password: options.Password,+ secure: options.Secure,+ now: now,+ ttlSeconds: ttlSeconds,+ }, nil+}++// required reports whether a password is configured.+func (a *siteAccessGate) required() bool {+ return a.password != ""+}++// passwordMatches mirrors passwordMatches: an unset password accepts anything,+// a set password needs a non-empty exact match.+func (a *siteAccessGate) passwordMatches(value string) bool {+ return !a.required() || (value != "" && secretMatches(value, a.password))+}++// isAuthenticated mirrors isAuthenticated over a raw Cookie request header.+func (a *siteAccessGate) isAuthenticated(cookieHeader string) bool {+ if !a.required() {+ return true+ }+ value := readCookie(cookieHeader, a.cookieName())+ if value == "" {+ return false+ }+ // TS: const [version, expiresText, signature, ...extra] = value.split(".")+ // Fewer than three segments fail the two regexes below (an absent segment+ // is tested as ""), more than three fill `extra`.+ segments := strings.Split(value, ".")+ if len(segments) != 3 ||+ segments[0] != cookieVersion ||+ !accessExpiresPattern.MatchString(segments[1]) ||+ !accessSignaturePattern.MatchString(segments[2]) {+ return false+ }+ // TS: Number(expiresText) then Number.isSafeInteger. The segment is all+ // digits, so only an out-of-range value can fail here.+ expiresAt, err := strconv.ParseInt(segments[1], 10, 64)+ if err != nil || expiresAt > protocol.MaxSafeInteger {+ return false+ }+ if expiresAt <= floorSeconds(a.now()) {+ return false+ }+ // Sign the received text, not a re-rendered payload.+ return secretMatches(segments[2], a.sign(segments[0]+"."+segments[1]))+}++// createCookie mirrors createCookie and returns the Set-Cookie header value,+// or "" where TS returned undefined (site access is not required).+func (a *siteAccessGate) createCookie() string {+ if !a.required() {+ return ""+ }+ expiresAt := floorSeconds(a.now()) + int64(a.ttlSeconds)+ payload := cookieVersion + "." + strconv.FormatInt(expiresAt, 10)+ value := payload + "." + a.sign(payload)+ // Attribute order is the TS array order; the app writes it verbatim.+ attributes := []string{+ a.cookieName() + "=" + value,+ "Path=/",+ "Max-Age=" + strconv.Itoa(a.ttlSeconds),+ "HttpOnly",+ "SameSite=Strict",+ }+ if a.secure {+ attributes = append(attributes, "Secure")+ }+ return strings.Join(attributes, "; ")+}++func (a *siteAccessGate) cookieName() string {+ if a.secure {+ return "__Host-screener-site-access"+ }+ return "screener-site-access"+}++func (a *siteAccessGate) sign(payload string) string {+ mac := hmac.New(sha256.New, []byte(a.password))+ mac.Write([]byte(payload))+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))+}++// floorSeconds is Math.floor(milliseconds / 1000); Go's integer division+// truncates toward zero, so negative clocks need the adjustment.+func floorSeconds(milliseconds int64) int64 {+ seconds := milliseconds / 1_000+ if milliseconds < 0 && milliseconds%1_000 != 0 {+ seconds--+ }+ return seconds+}++// readCookie mirrors the TS reader: the first part whose trimmed name matches+// wins, and an empty value counts as absent.+func readCookie(header string, name string) string {+ for _, part := range strings.Split(header, ";") {+ separator := strings.IndexByte(part, '=')+ if separator != -1 && strings.TrimSpace(part[:separator]) == name {+ return strings.TrimSpace(part[separator+1:])+ }+ }+ return ""+}++// secretMatches compares through SHA-256 digests so the comparison is constant+// time regardless of length, exactly as the TS helper does.+func secretMatches(actual string, expected string) bool {+ actualDigest := sha256.Sum256([]byte(actual))+ expectedDigest := sha256.Sum256([]byte(expected))+ return subtle.ConstantTimeCompare(actualDigest[:], expectedDigest[:]) == 1+}diff --git a/internal/server/app/access_test.go b/internal/server/app/access_test.gonew file mode 100644index 00000000..5f6cc88f--- /dev/null+++ b/internal/server/app/access_test.go@@ -0,0 +1,284 @@+package app++import (+ "strings"+ "testing"+)++const testAccessPassword = "instance-access-password"++// newTestAccess builds a siteAccessGate over a mutable clock, mirroring the+// `now: () => now` injection used by tests/server-http.test.ts.+func newTestAccess(t *testing.T, options siteAccessOptions) *siteAccessGate {+ t.Helper()+ access, err := newSiteAccess(options)+ if err != nil {+ t.Fatalf("newSiteAccess: %v", err)+ }+ return access+}++// cookiePair is the test helper of the same name: the `name=value` pair of a+// Set-Cookie header, which is what a browser sends back.+func cookiePair(t *testing.T, setCookie string) string {+ t.Helper()+ if setCookie == "" {+ t.Fatal("expected a Set-Cookie value")+ }+ return strings.SplitN(setCookie, ";", 2)[0]+}++// Ports "reports status and issues a stateless 24-hour cookie".+func TestSiteAccessIssuesStatelessDayLongCookie(t *testing.T) {+ now := int64(1_000)+ access := newTestAccess(t, siteAccessOptions{+ Password: testAccessPassword,+ Now: func() int64 { return now },+ })++ if !access.required() {+ t.Fatal("a configured password must make site access required")+ }+ if access.isAuthenticated("") {+ t.Fatal("a request without a cookie must not be authenticated")+ }+ if access.passwordMatches("wrong-password") {+ t.Fatal("a wrong password must be rejected")+ }+ if !access.passwordMatches(testAccessPassword) {+ t.Fatal("the configured password must be accepted")+ }++ setCookie := access.createCookie()+ if want := "screener-site-access=v1."; !strings.Contains(setCookie, want) {+ t.Fatalf("Set-Cookie %q does not contain %q", setCookie, want)+ }+ for _, attribute := range []string{"Path=/", "Max-Age=86400", "HttpOnly", "SameSite=Strict"} {+ if !strings.Contains(setCookie, attribute) {+ t.Fatalf("Set-Cookie %q is missing %q", setCookie, attribute)+ }+ }+ if strings.Contains(setCookie, "Secure") {+ t.Fatalf("Set-Cookie %q must not be Secure without HTTPS", setCookie)+ }+ if strings.Contains(setCookie, testAccessPassword) {+ t.Fatal("Set-Cookie must never carry the access password")+ }++ if !access.isAuthenticated(cookiePair(t, setCookie)) {+ t.Fatal("the freshly issued cookie must authenticate")+ }+}++// Ports the exact attribute order of createCookie, which app.ts writes verbatim+// into the Set-Cookie header.+func TestSiteAccessCookieAttributeOrder(t *testing.T) {+ insecure := newTestAccess(t, siteAccessOptions{+ Password: testAccessPassword,+ Now: func() int64 { return 1_000 },+ TTLSeconds: 12,+ })+ secure := newTestAccess(t, siteAccessOptions{+ Password: testAccessPassword,+ Secure: true,+ Now: func() int64 { return 1_000 },+ TTLSeconds: 12,+ })++ signature := strings.Split(cookiePair(t, insecure.createCookie()), ".")[2]+ if len(signature) != 43 {+ t.Fatalf("signature %q is %d characters, want 43 (base64url, no padding)", signature, len(signature))+ }++ // now = 1000 ms -> floor(1) + 12 = 13 seconds.+ wantValue := "v1.13." + signature+ want := "screener-site-access=" + wantValue ++ "; Path=/; Max-Age=12; HttpOnly; SameSite=Strict"+ if got := insecure.createCookie(); got != want {+ t.Fatalf("CreateCookie() = %q, want %q", got, want)+ }+ wantSecure := "__Host-screener-site-access=" + wantValue ++ "; Path=/; Max-Age=12; HttpOnly; SameSite=Strict; Secure"+ if got := secure.createCookie(); got != wantSecure {+ t.Fatalf("secure CreateCookie() = %q, want %q", got, wantSecure)+ }+}++// Ports "uses a secure __Host- cookie for production HTTPS".+func TestSiteAccessUsesHostPrefixedCookieWhenSecure(t *testing.T) {+ access := newTestAccess(t, siteAccessOptions{+ Password: testAccessPassword,+ Secure: true,+ Now: func() int64 { return 1_000 },+ })+ setCookie := access.createCookie()++ for _, attribute := range []string{+ "__Host-screener-site-access=", "Secure", "HttpOnly", "SameSite=Strict", "Path=/",+ } {+ if !strings.Contains(setCookie, attribute) {+ t.Fatalf("Set-Cookie %q is missing %q", setCookie, attribute)+ }+ }+ if strings.Contains(setCookie, "Domain=") {+ t.Fatalf("Set-Cookie %q must not carry a Domain for a __Host- cookie", setCookie)+ }+ if !access.isAuthenticated(cookiePair(t, setCookie)) {+ t.Fatal("the secure cookie must authenticate under its own name")+ }+ // The cookie name is part of the signed identity only through the lookup;+ // an insecure instance never finds a __Host- cookie.+ insecure := newTestAccess(t, siteAccessOptions{+ Password: testAccessPassword,+ Now: func() int64 { return 1_000 },+ })+ if insecure.isAuthenticated(cookiePair(t, setCookie)) {+ t.Fatal("the insecure instance must not read the __Host- cookie")+ }+}++// Ports "renews an authenticated cookie across successive idle deadlines".+func TestSiteAccessRenewsAcrossSuccessiveIdleDeadlines(t *testing.T) {+ now := int64(1_000)+ access := newTestAccess(t, siteAccessOptions{+ Password: testAccessPassword,+ Now: func() int64 { return now },+ TTLSeconds: 12,+ })++ originalCookie := cookiePair(t, access.createCookie())++ now = 7_000+ if !access.isAuthenticated(originalCookie) {+ t.Fatal("the original cookie must still be valid at 7s")+ }+ firstRenewedCookie := cookiePair(t, access.createCookie())+ if firstRenewedCookie == originalCookie {+ t.Fatal("a renewal at a later second must produce a different cookie")+ }++ now = 13_000+ if access.isAuthenticated(originalCookie) {+ t.Fatal("the original cookie must expire 12s after it was issued")+ }+ if !access.isAuthenticated(firstRenewedCookie) {+ t.Fatal("the first renewal must still be valid at 13s")+ }+ secondRenewedCookie := cookiePair(t, access.createCookie())+ if secondRenewedCookie == firstRenewedCookie {+ t.Fatal("the second renewal must differ from the first")+ }++ now = 20_000+ if access.isAuthenticated(firstRenewedCookie) {+ t.Fatal("the first renewal must expire 12s after it was issued")+ }+ if !access.isAuthenticated(secondRenewedCookie) {+ t.Fatal("the second renewal must still be valid at 20s")+ }+}++// Ports "rejects an expired or modified cookie" plus the parsing rules the HTTP+// scenarios only reach indirectly.+func TestSiteAccessRejectsExpiredOrTamperedCookies(t *testing.T) {+ now := int64(1_000)+ access := newTestAccess(t, siteAccessOptions{+ Password: testAccessPassword,+ Now: func() int64 { return now },+ TTLSeconds: 1,+ })+ cookie := cookiePair(t, access.createCookie())+ value := strings.SplitN(cookie, "=", 2)[1]+ segments := strings.Split(value, ".")++ if access.isAuthenticated(cookie + "x") {+ t.Fatal("an appended character must invalidate the signature")+ }++ other := newTestAccess(t, siteAccessOptions{+ Password: "another-access-password",+ Now: func() int64 { return now },+ TTLSeconds: 1,+ })+ if other.isAuthenticated(cookie) {+ t.Fatal("a cookie signed with a different password must be rejected")+ }++ // Expiry is compared against floor(now / 1000): 2000 ms is second 2 and the+ // cookie expires at second 2, so `expiresAt <= now` rejects it.+ now = 2_000+ if access.isAuthenticated(cookie) {+ t.Fatal("an expired cookie must be rejected")+ }+ now = 1_000++ name := strings.SplitN(cookie, "=", 2)[0]+ for _, testCase := range []struct {+ name string+ cookie string+ }{+ {"no cookie header", ""},+ {"different cookie name", "other=" + value},+ {"empty value", name + "="},+ {"no equals sign", name},+ {"wrong version", name + "=v2." + segments[1] + "." + segments[2]},+ {"missing version", name + "=" + segments[1] + "." + segments[2]},+ {"extra segment", name + "=" + value + ".extra"},+ {"non-digit expiry", name + "=v1.1e3." + segments[2]},+ {"signed expiry", name + "=v1.+42." + segments[2]},+ {"empty expiry", name + "=v1.." + segments[2]},+ {"short signature", name + "=v1." + segments[1] + "." + segments[2][:42]},+ {"long signature", name + "=v1." + segments[1] + "." + segments[2] + "A"},+ {"padded signature", name + "=v1." + segments[1] + "." + segments[2][:42] + "="},+ {"unsafe expiry", name + "=v1.9007199254740992." + segments[2]},+ } {+ if access.isAuthenticated(testCase.cookie) {+ t.Errorf("%s: %q must not authenticate", testCase.name, testCase.cookie)+ }+ }++ // Surrounding cookies and whitespace are tolerated, as the TS reader is.+ for _, header := range []string{+ "a=1; " + cookie + "; b=2",+ "a=1;" + cookie,+ " " + name + " = " + value + " ",+ } {+ if !access.isAuthenticated(header) {+ t.Errorf("Cookie header %q must authenticate", header)+ }+ }+}++// Ports "is immediately authenticated when the access password is empty".+func TestSiteAccessWithoutPassword(t *testing.T) {+ access := newTestAccess(t, siteAccessOptions{Now: func() int64 { return 1_000 }})++ if access.required() {+ t.Fatal("an empty password must not require site access")+ }+ if !access.isAuthenticated("") {+ t.Fatal("every request must be authenticated without a password")+ }+ if !access.isAuthenticated("screener-site-access=nonsense") {+ t.Fatal("a bogus cookie must not matter without a password")+ }+ if !access.passwordMatches("") || !access.passwordMatches("anything") {+ t.Fatal("passwordMatches must be true without a password")+ }+ if got := access.createCookie(); got != "" {+ t.Fatalf("CreateCookie() = %q, want \"\" (TS returned undefined)", got)+ }+}++func TestNewSiteAccessTTLValidation(t *testing.T) {+ if _, err := newSiteAccess(siteAccessOptions{Password: testAccessPassword, TTLSeconds: -1}); err == nil {+ t.Fatal("a negative TTL must be rejected")+ }+ access := newTestAccess(t, siteAccessOptions{+ Password: testAccessPassword,+ Now: func() int64 { return 0 },+ })+ if !strings.Contains(access.createCookie(), "Max-Age=86400") {+ t.Fatal("an unset TTL must default to 24 hours")+ }+}diff --git a/internal/server/app/app.go b/internal/server/app/app.gonew file mode 100644index 00000000..88b639ba--- /dev/null+++ b/internal/server/app/app.go@@ -0,0 +1,429 @@+// Package app ports src/server/app.ts: the HTTP composition, the startup and+// shutdown lifecycle, and the request router. access.go ports+// src/server/access-session.ts and static.go the sirv frontend handler.+//+// # Locking+//+// signal.Server owns the one mutex that guards the room store, the media router+// and every session. This package never takes it: everything a request can+// mutate goes through the signaling server. Server.mu below guards only this+// struct's own lifecycle bookkeeping.+//+// The lock order is one-directional: Server.mu may be held while the signaling+// mutex is taken (reconcile calls signal.New under it, and signal.New locks the+// server it is still building), never the reverse. Nothing reachable under the+// signaling mutex may take Server.mu, which is why the one callback this+// package hands to signal, SiteAccessAtUpgrade, only reads the lock-free+// site-access gate. Keep it that way or the two locks can deadlock.+package app++import (+ "context"+ "errors"+ "fmt"+ "io/fs"+ "log/slog"+ "net"+ "net/http"+ "strconv"+ "sync"+ "sync/atomic"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/config"+ "github.com/TNTcraftHIM/Screener/internal/server/room"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+ "github.com/TNTcraftHIM/Screener/internal/server/signal"+)++// Node HTTP server settings of app.ts, mapped in map section 3.3 / D11.+const (+ requestTimeout = 10 * time.Second // httpServer.requestTimeout+ headersTimeout = 15 * time.Second // httpServer.headersTimeout+ keepAliveTimeout = 5 * time.Second // httpServer.keepAliveTimeout+)++// Options is CreateServerOptions. Every zero value means the TS `undefined`.+type Options struct {+ // Config is the loaded server configuration; cmd owns config.Load / Local.+ Config config.Config+ // Assets is the built Browser UI. A nil FS serves the API only, which is+ // the TS frontend mode "none"; webassets.FS() returns nil the same way+ // when no build was embedded (D3).+ Assets fs.FS+ // Now returns Unix milliseconds; nil uses the wall clock.+ Now func() int64+ // Logger receives the request-failure record; nil uses slog.Default().+ Logger *slog.Logger++ AuthenticationTimeoutMs int+ ViewerDisconnectGraceMs int+ HeartbeatIntervalMs int+ CleanupIntervalMs int+ MaxSignalConnections int+ MaxUnauthenticatedSignalConnections int+ SiteAccessTTLSeconds int++ // SFUTokenIssuer and SFURoomControl replace the LiveKit implementations+ // this package would otherwise construct from Config.LiveKit.+ SFUTokenIssuer sfu.TokenIssuer+ SFURoomControl sfu.RoomControl+ // AfterFunc is the signaling timer factory (D5); nil uses time.AfterFunc.+ AfterFunc func(time.Duration, func()) func() bool+ // RoomStore replaces the store this package would build from Config.+ RoomStore *room.Store+}++// Server is ScreenerServer.+type Server struct {+ config config.Config+ store *room.Store+ siteAccess *siteAccessGate+ frontend http.Handler+ logger *slog.Logger+ // roomControl is nil without a LiveKit fallback; it is the only startup+ // reconciliation step (A12).+ roomControl sfu.RoomControl+ signalOptions signal.Options+ httpServer *http.Server+ // listener is nil until Listen binds. It is written before startupDone is+ // closed and read only after that channel settles, so it needs no lock.+ listener net.Listener++ // acceptingTraffic and signaling are the two closure variables app.ts+ // flipped together; both are read by request goroutines without a lock and+ // written under mu (hazard 13).+ acceptingTraffic atomic.Bool+ signaling atomic.Pointer[signal.Server]++ mu sync.Mutex+ closing bool+ startupRequested bool+ // startupDone is closed when listen settles, which is what shutdown awaits+ // so the listener stays owned until an in-flight startup finishes (A6).+ startupDone chan struct{}++ shutdownOnce sync.Once+ shutdownErr error+}++// New is createScreenerServer minus the listening: it builds the SFU fallback,+// the room store, the site-access issuer, the frontend handler and the HTTP+// server, none of which performs I/O.+func New(options Options) (*Server, error) {+ configuration := options.Config+ now := options.Now+ if now == nil {+ now = func() int64 { return time.Now().UnixMilli() }+ }+ logger := options.Logger+ if logger == nil {+ logger = slog.Default()+ }++ roomControl, fallback, err := newSfuFallback(options)+ if err != nil {+ return nil, err+ }+ store, err := newRoomStore(options, now)+ if err != nil {+ return nil, err+ }++ siteAccess, err := newSiteAccess(siteAccessOptions{+ Password: configuration.SiteAccessPassword,+ Secure: configuration.Env == config.EnvironmentProduction &&+ configuration.PublicBaseURL.Scheme == "https",+ Now: now,+ TTLSeconds: options.SiteAccessTTLSeconds,+ })+ if err != nil {+ return nil, err+ }++ server := &Server{+ config: configuration,+ store: store,+ siteAccess: siteAccess,+ logger: logger,+ roomControl: roomControl,+ startupDone: make(chan struct{}),+ }+ if options.Assets != nil {+ server.frontend = staticHandler(options.Assets, http.HandlerFunc(notFoundJSON))+ }+ server.signalOptions = signal.Options{+ Store: store,+ EndpointMediaCopyCapacity: configuration.EndpointMediaCopyCapacity,+ SfuFallback: fallback,+ Ice: config.IceConfig(configuration),+ // The TS signaling server read natPredictionEnabled off the same+ // `ice` options object it forwarded; the Go IceConfig is already the+ // wire shape, so the capability travels beside it.+ NATPredictionEnabled: configuration.NATPredictionEnabled,+ AllowedOrigins: configuration.AllowedOrigins,+ SiteAccessAtUpgrade: func(request *http.Request) bool {+ return siteAccess.isAuthenticated(cookieHeader(request))+ },+ PublicBaseURL: configuration.PublicBaseURL,+ Now: now,+ AuthenticationTimeoutMs: options.AuthenticationTimeoutMs,+ ViewerDisconnectGraceMs: options.ViewerDisconnectGraceMs,+ HeartbeatIntervalMs: options.HeartbeatIntervalMs,+ CleanupIntervalMs: options.CleanupIntervalMs,+ MaxConnections: options.MaxSignalConnections,+ MaxUnauthenticatedConnections: options.MaxUnauthenticatedSignalConnections,+ AfterFunc: options.AfterFunc,+ Logger: logger,+ }+ server.httpServer = &http.Server{+ Handler: server,+ ReadHeaderTimeout: headersTimeout,+ ReadTimeout: requestTimeout,+ IdleTimeout: keepAliveTimeout,+ // No WriteTimeout: Node had none, and it would cut long downloads.+ }+ return server, nil+}++// newSfuFallback builds the LiveKit half of createScreenerServer. Without a+// LiveKit fallback in the configuration both results are nil and the signaling+// server runs peer-only. The returned RoomControl is also kept by the caller,+// because it is the one startup reconciliation step (A12).+func newSfuFallback(options Options) (sfu.RoomControl, *signal.SfuFallback, error) {+ livekit := options.Config.LiveKit+ if livekit == nil {+ return nil, nil, nil+ }+ roomControl := options.SFURoomControl+ if roomControl == nil {+ control, err := sfu.NewLiveKitRoomControl(sfu.LiveKitRoomControlOptions{+ APIURL: livekit.APIURL,+ APIKey: livekit.APIKey,+ APISecret: livekit.APISecret,+ MaxViewersPerRoom: options.Config.MaxViewersPerRoom,+ })+ if err != nil {+ return nil, nil, err+ }+ roomControl = control+ }+ tokenIssuer := options.SFUTokenIssuer+ if tokenIssuer == nil {+ issuer, err := sfu.NewLiveKitTokenIssuer(sfu.LiveKitTokenIssuerOptions{+ APIKey: livekit.APIKey,+ APISecret: livekit.APISecret,+ MaxViewersPerRoom: options.Config.MaxViewersPerRoom,+ })+ if err != nil {+ return nil, nil, err+ }+ tokenIssuer = issuer+ }+ return roomControl, &signal.SfuFallback{+ URL: livekit.URL,+ TokenIssuer: tokenIssuer,+ Admission: sfu.NewAdmission(sfu.AdmissionOptions{+ IngressCapacity: room.Capacity,+ EgressCapacity: room.Capacity * options.Config.MaxViewersPerRoom,+ }),+ RoomControl: roomControl,+ }, nil+}++// newRoomStore builds the room store createScreenerServer would otherwise take+// from Options.RoomStore. An empty RoomDatabasePath is the memory-only mode.+func newRoomStore(options Options, now func() int64) (*room.Store, error) {+ if options.RoomStore != nil {+ return options.RoomStore, nil+ }+ var database *room.Database+ if options.Config.RoomDatabasePath != "" {+ // The file is opened by store.Initialize, not here: a failed bind must+ // leave no database behind.+ opened, err := room.NewDatabase(options.Config.RoomDatabasePath)+ if err != nil {+ return nil, err+ }+ database = opened+ }+ return room.New(room.Options{+ LeaseMs: options.Config.RoomLeaseMs,+ MaxRooms: room.Capacity,+ MaxViewersPerRoom: options.Config.MaxViewersPerRoom,+ Database: database,+ Now: now,+ })+}++// Handler is the composed router, exposed so a host process can mount it.+func (s *Server) Handler() http.Handler { return s }++// Store is ScreenerServer.roomStore. The signaling server's mutex guards it, so+// callers outside that lock may only read it while no request is in flight.+func (s *Server) Store() *room.Store { return s.store }++// Listen binds the configured address, then reconciles the stable authority and+// LiveKit, and only then starts accepting traffic. It returns the bound port,+// which is the actual one when Config.Port is 0.+func (s *Server) Listen(ctx context.Context) (int, error) {+ s.mu.Lock()+ if s.startupRequested {+ s.mu.Unlock()+ return 0, errors.New("Screener server startup was already requested")+ }+ if s.closing {+ s.mu.Unlock()+ return 0, errors.New("Screener server is closing")+ }+ s.startupRequested = true+ s.mu.Unlock()++ // Deferred: a rejected startupOperation still settled, so shutdown's wait+ // on it ended (app.ts:219). A panic escaping start() must likewise release+ // the latch, or every later Close blocks on it for good.+ defer close(s.startupDone)+ return s.start(ctx)+}++func (s *Server) start(ctx context.Context) (int, error) {+ // A11: bind first. A listener owned by another process must fail before+ // the room database is opened and before LiveKit is called at all.+ address := net.JoinHostPort(s.config.ListenHost, strconv.Itoa(s.config.Port))+ listener, err := net.Listen("tcp", address)+ if err != nil {+ return 0, err+ }+ s.listener = listener+ go func() {+ // bindHttpServer removed its "error" listener once the server was+ // listening (app.ts:315-333), so a later listener failure ended the+ // Node process. Serve only returns something other than+ // ErrServerClosed on a permanent accept failure, which nothing here+ // causes; report it rather than serving nothing in silence.+ if err := s.httpServer.Serve(listener); !errors.Is(err, http.ErrServerClosed) {+ s.logger.Error("Screener HTTP server stopped unexpectedly", "error", err)+ }+ }()+ port := listener.Addr().(*net.TCPAddr).Port++ if err := s.reconcile(ctx); err != nil {+ // A13: give the database and the listener back before reporting.+ var cleanup []error+ if closeErr := s.store.Close(); closeErr != nil {+ cleanup = append(cleanup, closeErr)+ }+ if closeErr := s.stopServing(ctx); closeErr != nil {+ cleanup = append(cleanup, closeErr)+ }+ if len(cleanup) > 0 {+ return 0, fmt.Errorf("Screener startup reconciliation failed: %w",+ errors.Join(append([]error{err}, cleanup...)...))+ }+ return 0, err+ }+ return port, nil+}++// stopServing is closeHttpServer. Shutdown stops accepting and drains, but it+// can lose the race against the Serve goroutine registering the listener, in+// which case it returns without having closed the bound socket; closing the+// listener afterwards makes the port release synchronous. A second close of an+// already closed listener is a no-op error nobody reported in TS either, so+// only Shutdown's error is returned.+func (s *Server) stopServing(ctx context.Context) error {+ err := s.httpServer.Shutdown(ctx)+ if s.listener != nil {+ _ = s.listener.Close()+ }+ return err+}++// reconcile is the body of the TS startup try block: the store recovers its+// stable authority synchronously, LiveKit reconciliation is the one await+// (A12), and traffic starts only if no shutdown began while it ran.+func (s *Server) reconcile(ctx context.Context) error {+ if err := s.store.Initialize(); err != nil {+ return err+ }+ if s.roomControl != nil {+ if err := s.roomControl.Initialize(ctx); err != nil {+ return err+ }+ }+ // Holding mu across the check and the two stores is what made the TS+ // single thread safe here: a shutdown that already set closing must never+ // see traffic re-enabled behind it.+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.closing {+ return nil+ }+ signaling, err := signal.New(s.signalOptions)+ if err != nil {+ return err+ }+ s.signaling.Store(signaling)+ s.acceptingTraffic.Store(true)+ return nil+}++// Close stops accepting traffic, closes the signaling server, the listener and+// the room store, and leaves the rooms in place. Hosted restarts use it.+func (s *Server) Close(ctx context.Context) error {+ return s.shutdown(ctx, false)+}++// End is Close preceded by ending every room. The Client uses it, because its+// authority dies with the process.+func (s *Server) End(ctx context.Context) error {+ return s.shutdown(ctx, true)+}++// shutdown is memoised exactly as the TS shutdownOperation was: the second+// caller joins the first and gets its result, whichever entry point it used.+func (s *Server) shutdown(ctx context.Context, endRooms bool) error {+ s.shutdownOnce.Do(func() { s.shutdownErr = s.runShutdown(ctx, endRooms) })+ return s.shutdownErr+}++func (s *Server) runShutdown(ctx context.Context, endRooms bool) error {+ // O35: stop traffic, mark closing, then wait for an in-flight startup.+ s.mu.Lock()+ s.acceptingTraffic.Store(false)+ s.closing = true+ awaitStartup := s.startupRequested+ s.mu.Unlock()+ if awaitStartup {+ // A6: the listen caller owns the startup error; shutdown only waits.+ <-s.startupDone+ }++ var failures []error+ signaling := s.signaling.Load()+ if endRooms {+ failures = append(failures, s.endAllRooms(signaling))+ }+ if signaling != nil {+ failures = append(failures, signaling.Close(ctx))+ }+ // The signaling server must be closed before the listener: its connections+ // live on it.+ failures = append(failures, s.stopServing(ctx))+ failures = append(failures, s.store.Close())+ if joined := errors.Join(failures...); joined != nil {+ return fmt.Errorf("Screener server shutdown failed: %w", joined)+ }+ return nil+}++// endAllRooms is the TS `signaling ? signaling.endAllRooms() :+// roomStore.abandonAllRooms()`: without a signaling server nobody is connected,+// so the store can be closed down directly.+func (s *Server) endAllRooms(signaling *signal.Server) error {+ if signaling != nil {+ return signaling.EndAllRooms()+ }+ _, err := s.store.AbandonAllRooms()+ return err+}diff --git a/internal/server/app/app_test.go b/internal/server/app/app_test.gonew file mode 100644index 00000000..df95d0d0--- /dev/null+++ b/internal/server/app/app_test.go@@ -0,0 +1,1577 @@+package app++import (+ "bytes"+ "context"+ "database/sql"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "testing/fstest"+ "time"++ "github.com/coder/websocket"+ _ "modernc.org/sqlite"++ "github.com/TNTcraftHIM/Screener/internal/server/config"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+ "github.com/TNTcraftHIM/Screener/internal/server/room"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu/sfutest"+)++// The scenarios below are ported from tests/server-http.test.ts.++const allowedOrigin = "http://allowed.test"++// setCookiePattern is the exact attribute order access-session.ts emits and+// app.ts writes verbatim.+var setCookiePattern = regexp.MustCompile(+ `^screener-site-access=v1\.[0-9]+\.[A-Za-z0-9_-]{43}; Path=/; Max-Age=86400; HttpOnly; SameSite=Strict$`)++var secureSetCookiePattern = regexp.MustCompile(+ `^__Host-screener-site-access=v1\.[0-9]+\.[A-Za-z0-9_-]{43}; Path=/; Max-Age=86400; HttpOnly; SameSite=Strict; Secure$`)++type fakeTokenIssuer struct{}++func (fakeTokenIssuer) IssueToken(sfu.TokenRequest) (string, error) {+ return "unused-test-token", nil+}++func testConfig(t *testing.T) config.Config {+ t.Helper()+ publicBaseURL, err := url.Parse("https://share.example.test")+ if err != nil {+ t.Fatalf("url.Parse: %v", err)+ }+ return config.Config{+ Env: config.EnvironmentDevelopment,+ Port: 0,+ ListenHost: "127.0.0.1",+ PublicBaseURL: publicBaseURL,+ AllowedOrigins: map[string]struct{}{allowedOrigin: {}},+ SiteAccessPassword: testAccessPassword,+ RoomLeaseMs: 86_400_000,+ MaxViewersPerRoom: 8,+ EndpointMediaCopyCapacity: 2,+ NATPredictionEnabled: false,+ }+}++func livekitFallback() *config.LiveKitFallback {+ return &config.LiveKitFallback{+ URL: "ws://livekit.test:7880",+ APIURL: "http://127.0.0.1:7880",+ APIKey: "test-key",+ APISecret: strings.Repeat("s", 32),+ }+}++// newServer builds a server without listening. It mirrors the TS harness: the+// heartbeat and cleanup intervals are pushed out of the way and a fake room+// control is injected whenever a LiveKit fallback is configured.+func newServer(t *testing.T, options Options) *Server {+ t.Helper()+ if options.Config.PublicBaseURL == nil {+ options.Config = testConfig(t)+ }+ if options.HeartbeatIntervalMs == 0 {+ options.HeartbeatIntervalMs = 60_000+ }+ if options.CleanupIntervalMs == 0 {+ options.CleanupIntervalMs = 60_000+ }+ if options.Config.LiveKit != nil {+ if options.SFURoomControl == nil {+ options.SFURoomControl = sfutest.New()+ }+ if options.SFUTokenIssuer == nil {+ options.SFUTokenIssuer = fakeTokenIssuer{}+ }+ }+ server, err := New(options)+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ t.Cleanup(func() { _ = server.Close(context.Background()) })+ return server+}++type harness struct {+ *Server+ t *testing.T+ baseURL string+ client *http.Client+}++func start(t *testing.T, options Options) *harness {+ t.Helper()+ server := newServer(t, options)+ port, err := server.Listen(context.Background())+ if err != nil {+ t.Fatalf("Listen: %v", err)+ }+ return &harness{Server: server, t: t, baseURL: baseURL(port), client: testClient(t)}+}++func baseURL(port int) string { return fmt.Sprintf("http://127.0.0.1:%d", port) }++// testClient never reuses a connection, so a closed server never leaves a+// pooled socket behind for the next test.+func testClient(t *testing.T) *http.Client {+ t.Helper()+ transport := &http.Transport{DisableKeepAlives: true}+ t.Cleanup(transport.CloseIdleConnections)+ return &http.Client{Transport: transport, Timeout: 30 * time.Second}+}++// freePort reserves and releases a port so a test can know the listen address+// before Listen returns. The window is a few microseconds on a test machine.+func freePort(t *testing.T) int {+ t.Helper()+ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("net.Listen: %v", err)+ }+ port := listener.Addr().(*net.TCPAddr).Port+ if err := listener.Close(); err != nil {+ t.Fatalf("close probe listener: %v", err)+ }+ return port+}++type reply struct {+ t *testing.T+ status int+ header http.Header+ body string+}++type requestOption func(*http.Request)++func withOrigin(origin string) requestOption {+ return func(request *http.Request) { request.Header.Set("Origin", origin) }+}++func withCookie(cookie string) requestOption {+ return func(request *http.Request) {+ if cookie != "" {+ request.Header.Set("Cookie", cookie)+ }+ }+}++func withBearer(token string) requestOption {+ return func(request *http.Request) {+ if token != "" {+ request.Header.Set("Authorization", "Bearer "+token)+ }+ }+}++func withBody(contentType, payload string) requestOption {+ return func(request *http.Request) {+ if contentType != "" {+ request.Header.Set("Content-Type", contentType)+ }+ request.Body = io.NopCloser(strings.NewReader(payload))+ request.ContentLength = int64(len(payload))+ }+}++func withJSON(payload string) requestOption {+ return withBody("application/json", payload)+}++func (h *harness) do(method, path string, options ...requestOption) reply {+ h.t.Helper()+ return send(h.t, h.client, method, h.baseURL+path, options...)+}++func send(+ t *testing.T,+ client *http.Client,+ method, target string,+ options ...requestOption,+) reply {+ t.Helper()+ request, err := http.NewRequest(method, target, nil)+ if err != nil {+ t.Fatalf("http.NewRequest: %v", err)+ }+ for _, option := range options {+ option(request)+ }+ response, err := client.Do(request)+ if err != nil {+ t.Fatalf("%s %s: %v", method, target, err)+ }+ defer response.Body.Close()+ body, err := io.ReadAll(response.Body)+ if err != nil {+ t.Fatalf("read body: %v", err)+ }+ return reply{t: t, status: response.StatusCode, header: response.Header, body: string(body)}+}++func (r reply) expect(status int, body string) reply {+ r.t.Helper()+ if r.status != status {+ r.t.Fatalf("status = %d, want %d (body %s)", r.status, status, r.body)+ }+ if r.body != body {+ r.t.Fatalf("body = %s, want %s", r.body, body)+ }+ return r+}++func (r reply) expectStatus(status int) reply {+ r.t.Helper()+ if r.status != status {+ r.t.Fatalf("status = %d, want %d (body %s)", r.status, status, r.body)+ }+ return r+}++func (r reply) expectHeader(name, want string) reply {+ r.t.Helper()+ if got := r.header.Get(name); got != want {+ r.t.Fatalf("header %s = %q, want %q", name, got, want)+ }+ return r+}++func (r reply) room() protocol.CreateRoomResponse {+ r.t.Helper()+ var created protocol.CreateRoomResponse+ if err := json.Unmarshal([]byte(r.body), &created); err != nil {+ r.t.Fatalf("decode CreateRoomResponse from %s: %v", r.body, err)+ }+ return created+}++// login is the TS login(): a POST with the site password as a bearer token.+func (h *harness) login() reply {+ h.t.Helper()+ return h.do(http.MethodPost, "/api/site-access",+ withBearer(testAccessPassword), withOrigin(allowedOrigin))+}++func (h *harness) cookie() string {+ h.t.Helper()+ response := h.login().expectStatus(http.StatusOK)+ return cookiePair(h.t, response.header.Get("Set-Cookie"))+}++type roomRequest struct {+ cookie string+ codeEntryPolicy string+ password *string+ preferredRoomID string+}++func (h *harness) createRoom(request roomRequest) reply {+ h.t.Helper()+ policy := request.codeEntryPolicy+ if policy == "" {+ policy = "open"+ }+ fields := []string{fmt.Sprintf("%q:%q", "codeEntryPolicy", policy)}+ if request.password != nil {+ fields = append(fields, fmt.Sprintf("%q:%q", "roomPassword", *request.password))+ }+ if request.preferredRoomID != "" {+ fields = append(fields, fmt.Sprintf("%q:%q", "preferredRoomId", request.preferredRoomID))+ }+ return h.do(http.MethodPost, "/api/rooms",+ withOrigin(allowedOrigin), withCookie(request.cookie),+ withJSON("{"+strings.Join(fields, ",")+"}"))+}++type accessRequest struct {+ roomID string+ hostToken string+ body string+ cookie string+ origin string+ method string+}++func (h *harness) updateRoomAccess(request accessRequest) reply {+ h.t.Helper()+ method := request.method+ if method == "" {+ method = http.MethodPost+ }+ origin := request.origin+ if origin == "" {+ origin = allowedOrigin+ }+ options := []requestOption{+ withOrigin(origin), withCookie(request.cookie), withBearer(request.hostToken),+ }+ if method == http.MethodPost {+ options = append(options, withJSON(request.body))+ }+ return h.do(method, "/api/rooms/"+request.roomID+"/access", options...)+}++func (h *harness) replaceRoom(roomID, hostToken, body, cookie string) reply {+ h.t.Helper()+ return h.do(http.MethodPost, "/api/rooms/"+roomID+"/replacement",+ withOrigin(allowedOrigin), withCookie(cookie), withBearer(hostToken),+ withJSON(body))+}++func waitFor(t *testing.T, what string, condition func() bool) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for !condition() {+ if time.Now().After(deadline) {+ t.Fatalf("timed out waiting for %s", what)+ }+ time.Sleep(2 * time.Millisecond)+ }+}++func assertPortFree(t *testing.T, port int) {+ t.Helper()+ listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))+ if err != nil {+ t.Fatalf("port %d is still owned: %v", port, err)+ }+ _ = listener.Close()+}++// expectGoroutinesSettled is the close tests' stand-in for the race detector+// (unavailable without cgo): the listener's Serve loop, the signaling+// goroutines and the timers must all have exited once Close (or a failed+// Listen) returns, so the count returns to what it was before New.+func expectGoroutinesSettled(t *testing.T, before int) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for runtime.NumGoroutine() > before {+ if time.Now().After(deadline) {+ stacks := make([]byte, 1<<20)+ t.Fatalf("goroutines: %d before, %d after close\n%s",+ before, runtime.NumGoroutine(), stacks[:runtime.Stack(stacks, true)])+ }+ time.Sleep(2 * time.Millisecond)+ }+}++// --- runtime capabilities -------------------------------------------------++func TestCapabilitiesKeepNATPredictionAbsentByDefault(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})++ server.do(http.MethodGet, "/api/capabilities").+ expect(http.StatusOK, `{"natPrediction":false}`)+}++func TestCapabilitiesReportOptionalNATPredictionWithoutExposingConfiguration(t *testing.T) {+ configuration := testConfig(t)+ configuration.STUNURLs = []string{"stun:share.example.test:3478"}+ configuration.NATPredictionEnabled = true+ server := start(t, Options{Config: configuration})++ server.do(http.MethodGet, "/api/capabilities").+ expect(http.StatusOK, `{"natPrediction":true}`).+ expectHeader("Cache-Control", "no-store").+ expectHeader("X-Content-Type-Options", "nosniff")++ server.do(http.MethodPost, "/api/capabilities").+ expect(http.StatusMethodNotAllowed, `{"error":"Method not allowed"}`).+ expectHeader("Allow", "GET")+}++// --- site access ----------------------------------------------------------++func TestSiteAccessReportsStatusAndIssuesStatelessDayLongCookie(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})++ server.do(http.MethodGet, "/api/site-access").+ expect(http.StatusOK, `{"required":true,"authenticated":false}`).+ expectHeader("Cache-Control", "no-store").+ expectHeader("Set-Cookie", "")++ server.do(http.MethodPost, "/api/site-access",+ withBearer("wrong-password"), withOrigin(allowedOrigin)).+ expect(http.StatusUnauthorized, `{"error":"Unauthorized"}`).+ expectHeader("Set-Cookie", "").+ expectHeader("WWW-Authenticate", "Bearer")++ authenticated := server.login().+ expect(http.StatusOK, `{"required":true,"authenticated":true}`)+ setCookie := authenticated.header.Get("Set-Cookie")+ if !setCookiePattern.MatchString(setCookie) {+ t.Fatalf("Set-Cookie = %q, want %v", setCookie, setCookiePattern)+ }+ if strings.Contains(setCookie, testAccessPassword) {+ t.Fatal("Set-Cookie leaked the site access password")+ }+ cookie := cookiePair(t, setCookie)++ server.do(http.MethodPost, "/api/site-access",+ withBearer("wrong-password"), withCookie(cookie), withOrigin(allowedOrigin)).+ expect(http.StatusUnauthorized, `{"error":"Unauthorized"}`).+ expectHeader("Set-Cookie", "")++ status := server.do(http.MethodGet, "/api/site-access", withCookie(cookie)).+ expect(http.StatusOK, `{"required":true,"authenticated":true}`)+ if !setCookiePattern.MatchString(status.header.Get("Set-Cookie")) {+ t.Fatalf("renewal Set-Cookie = %q", status.header.Get("Set-Cookie"))+ }+}++func TestSiteAccessRenewsAnAuthenticatedCookieAcrossIdleDeadlines(t *testing.T) {+ var now atomic.Int64+ now.Store(1_000)+ server := start(t, Options{+ Config: testConfig(t),+ Now: now.Load,+ SiteAccessTTLSeconds: 12,+ })+ original := cookiePair(t, server.login().header.Get("Set-Cookie"))++ now.Store(7_000)+ firstRenewed := cookiePair(t, server.do(+ http.MethodGet, "/api/site-access", withCookie(original)).+ header.Get("Set-Cookie"))+ if firstRenewed == original {+ t.Fatal("renewal reissued the same cookie")+ }++ now.Store(13_000)+ server.do(http.MethodGet, "/api/site-access", withCookie(original)).+ expect(http.StatusOK, `{"required":true,"authenticated":false}`).+ expectHeader("Set-Cookie", "")++ secondRenewed := cookiePair(t, server.do(+ http.MethodGet, "/api/site-access", withCookie(firstRenewed)).+ header.Get("Set-Cookie"))+ if secondRenewed == firstRenewed {+ t.Fatal("second renewal reissued the same cookie")+ }++ now.Store(20_000)+ server.do(http.MethodGet, "/api/site-access", withCookie(firstRenewed)).+ expect(http.StatusOK, `{"required":true,"authenticated":false}`).+ expectHeader("Set-Cookie", "")+ active := server.do(http.MethodGet, "/api/site-access", withCookie(secondRenewed)).+ expect(http.StatusOK, `{"required":true,"authenticated":true}`)+ if active.header.Get("Set-Cookie") == "" {+ t.Fatal("an active cookie was not renewed")+ }+}++func TestSiteAccessUsesASecureHostCookieForProductionHTTPS(t *testing.T) {+ configuration := testConfig(t)+ configuration.Env = config.EnvironmentProduction+ server := start(t, Options{Config: configuration})++ setCookie := server.login().expectStatus(http.StatusOK).header.Get("Set-Cookie")+ if !secureSetCookiePattern.MatchString(setCookie) {+ t.Fatalf("Set-Cookie = %q, want %v", setCookie, secureSetCookiePattern)+ }+ if strings.Contains(setCookie, "Domain=") {+ t.Fatalf("Set-Cookie = %q must not scope a domain", setCookie)+ }+}++func TestSiteAccessRequiresAnAllowedOriginAndAnEmptyLoginBody(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})+ forbidden := `{"error":"Forbidden"}`++ server.do(http.MethodPost, "/api/site-access", withBearer(testAccessPassword)).+ expect(http.StatusForbidden, forbidden)+ server.do(http.MethodPost, "/api/site-access",+ withBearer(testAccessPassword), withOrigin("https://foreign.test")).+ expect(http.StatusForbidden, forbidden)+ server.do(http.MethodPost, "/api/site-access",+ withBearer(testAccessPassword), withOrigin(allowedOrigin+"/path")).+ expect(http.StatusForbidden, forbidden)+ server.do(http.MethodPost, "/api/site-access",+ withBearer(testAccessPassword), withOrigin(allowedOrigin),+ withBody("text/plain;charset=UTF-8", "{}")).+ expect(http.StatusBadRequest, `{"error":"Request body is not accepted"}`)++ server.do(http.MethodDelete, "/api/site-access", withOrigin(allowedOrigin)).+ expect(http.StatusMethodNotAllowed, `{"error":"Method not allowed"}`).+ expectHeader("Allow", "GET, POST")+}++func TestSiteAccessRejectsAnExpiredOrModifiedCookie(t *testing.T) {+ var now atomic.Int64+ now.Store(1_000)+ server := start(t, Options{+ Config: testConfig(t),+ Now: now.Load,+ SiteAccessTTLSeconds: 1,+ })+ cookie := cookiePair(t, server.login().header.Get("Set-Cookie"))++ server.do(http.MethodGet, "/api/site-access", withCookie(cookie+"x")).+ expect(http.StatusOK, `{"required":true,"authenticated":false}`)++ now.Store(2_000)+ server.do(http.MethodGet, "/api/site-access", withCookie(cookie)).+ expect(http.StatusOK, `{"required":true,"authenticated":false}`)+}++func TestSiteAccessIsImmediateWhenTheAccessPasswordIsEmpty(t *testing.T) {+ configuration := testConfig(t)+ configuration.SiteAccessPassword = ""+ server := start(t, Options{Config: configuration})++ server.do(http.MethodGet, "/api/site-access").+ expect(http.StatusOK, `{"required":false,"authenticated":true}`).+ expectHeader("Set-Cookie", "")+ server.do(http.MethodPost, "/api/site-access", withOrigin(allowedOrigin)).+ expect(http.StatusOK, `{"required":false,"authenticated":true}`).+ expectHeader("Set-Cookie", "")+}++// --- room HTTP API --------------------------------------------------------++func TestRoomCreationRequiresALoggedInBrowser(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})++ server.createRoom(roomRequest{}).+ expect(http.StatusUnauthorized, `{"error":"Unauthorized"}`).+ expectHeader("WWW-Authenticate", "")++ // Hazard 12: the site password as a bearer token is not a browser session.+ server.do(http.MethodPost, "/api/rooms",+ withOrigin(allowedOrigin), withBearer(testAccessPassword),+ withJSON(`{"codeEntryPolicy":"open"}`)).+ expect(http.StatusUnauthorized, `{"error":"Unauthorized"}`)+}++func TestRoomCreationIssuesAnIndependentFragmentOnlyViewerGrant(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})++ response := server.createRoom(roomRequest{cookie: server.cookie()}).+ expectStatus(http.StatusCreated).+ expectHeader("Cache-Control", "no-store").+ expectHeader("X-Content-Type-Options", "nosniff")+ created := response.room()++ if !regexp.MustCompile(`^[1-9][0-9]{3}$`).MatchString(created.RoomID) {+ t.Fatalf("roomId = %q", created.RoomID)+ }+ invite, err := url.Parse(created.InviteURL)+ if err != nil {+ t.Fatalf("url.Parse(inviteUrl): %v", err)+ }+ if config.Origin(invite) != "https://share.example.test" {+ t.Fatalf("invite origin = %q", config.Origin(invite))+ }+ if invite.Path != "/r/"+created.RoomID {+ t.Fatalf("invite path = %q", invite.Path)+ }+ if !regexp.MustCompile(`^v=[A-Za-z0-9_-]{21}[AQgw]$`).MatchString(invite.Fragment) {+ t.Fatalf("invite fragment = %q", invite.Fragment)+ }+ if invite.RawQuery != "" {+ t.Fatalf("invite query = %q", invite.RawQuery)+ }+ if created.CodeEntryPolicy != "open" {+ t.Fatalf("codeEntryPolicy = %q", created.CodeEntryPolicy)+ }+ if created.ExpiresAt == nil || *created.ExpiresAt == "" {+ t.Fatal("expiresAt is missing")+ }+ if created.RoomLeaseSeconds != 86_400 {+ t.Fatalf("roomLeaseSeconds = %d", created.RoomLeaseSeconds)+ }+ // The response carries no viewer grant expiry and no ICE configuration.+ var raw map[string]json.RawMessage+ if err := json.Unmarshal([]byte(response.body), &raw); err != nil {+ t.Fatalf("decode body: %v", err)+ }+ for _, absent := range []string{"viewerGrantExpiresAt", "iceConfig", "viewerGrant"} {+ if _, present := raw[absent]; present {+ t.Fatalf("response exposes %q", absent)+ }+ }+}++func TestRoomCreationPassesTheSharedViewerCeilingToRoomAdmission(t *testing.T) {+ configuration := testConfig(t)+ configuration.SiteAccessPassword = ""+ configuration.MaxViewersPerRoom = protocol.MaxViewersPerRoomLimit+ server := start(t, Options{Config: configuration})++ server.createRoom(roomRequest{}).expectStatus(http.StatusCreated)+ if got := server.Store().MaxViewersPerRoom(); got != protocol.MaxViewersPerRoomLimit {+ t.Fatalf("maxViewersPerRoom = %d, want %d", got, protocol.MaxViewersPerRoomLimit)+ }+}++func TestRoomCreationCreatesPrivateRoomsWithOptionalPasswordsAtomically(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})+ cookie := server.cookie()+ password := "room-password"++ withPassword := server.createRoom(roomRequest{+ cookie: cookie, codeEntryPolicy: "private", password: &password,+ }).expectStatus(http.StatusCreated).room()+ if withPassword.CodeEntryPolicy != "private" {+ t.Fatalf("codeEntryPolicy = %q", withPassword.CodeEntryPolicy)+ }++ withoutPassword := server.createRoom(roomRequest{+ cookie: cookie, codeEntryPolicy: "private",+ }).expectStatus(http.StatusCreated).room()+ if withoutPassword.CodeEntryPolicy != "private" {+ t.Fatalf("codeEntryPolicy = %q", withoutPassword.CodeEntryPolicy)+ }+}++func TestRoomCreationAllowsExplicitOpenCreationWithoutSiteAccess(t *testing.T) {+ configuration := testConfig(t)+ configuration.SiteAccessPassword = ""+ server := start(t, Options{Config: configuration})++ created := server.createRoom(roomRequest{codeEntryPolicy: "open"}).+ expectStatus(http.StatusCreated).room()+ if created.CodeEntryPolicy != "open" {+ t.Fatalf("codeEntryPolicy = %q", created.CodeEntryPolicy)+ }+ if !strings.Contains(created.InviteURL, "#v=") {+ t.Fatalf("inviteUrl = %q", created.InviteURL)+ }+}++func TestRoomCreationAllocatesUniqueFourDigitCodesConcurrently(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})+ cookie := server.cookie()++ var wait sync.WaitGroup+ created := make([]protocol.CreateRoomResponse, 2)+ for index := range created {+ wait.Add(1)+ go func() {+ defer wait.Done()+ created[index] = server.createRoom(roomRequest{cookie: cookie}).+ expectStatus(http.StatusCreated).room()+ }()+ }+ wait.Wait()++ if created[0].RoomID == created[1].RoomID {+ t.Fatalf("both rooms took the code %q", created[0].RoomID)+ }+ for _, room := range created {+ if room.ExpiresAt == nil {+ t.Fatal("expiresAt is null")+ }+ }+}++func TestRoomCreationReusesAFreePreferredCodeAndNeverReplacesAnOccupiedRoom(t *testing.T) {+ configuration := testConfig(t)+ configuration.RoomLeaseMs = 90_000+ server := start(t, Options{Config: configuration})+ cookie := server.cookie()++ preferred := server.createRoom(roomRequest{cookie: cookie, preferredRoomID: "4321"}).+ expectStatus(http.StatusCreated).room()+ fallback := server.createRoom(roomRequest{cookie: cookie, preferredRoomID: "4321"}).+ expectStatus(http.StatusCreated).room()++ if preferred.RoomID != "4321" {+ t.Fatalf("preferred roomId = %q", preferred.RoomID)+ }+ if preferred.RoomLeaseSeconds != 90 {+ t.Fatalf("roomLeaseSeconds = %d", preferred.RoomLeaseSeconds)+ }+ if fallback.RoomID == "4321" {+ t.Fatal("the occupied preferred code was handed out twice")+ }+ if fallback.HostToken == preferred.HostToken {+ t.Fatal("the fallback room reused the Host token")+ }+}++func TestRoomReplacementReplacesAuthorityAndClosesOldMembership(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})+ cookie := server.cookie()+ password := "old-password"+ original := server.createRoom(roomRequest{+ cookie: cookie, codeEntryPolicy: "private",+ password: &password, preferredRoomID: "4321",+ }).expectStatus(http.StatusCreated).room()++ store := server.Store()+ host, err := store.ConnectParticipant(room.ConnectParticipantInput{+ RoomID: original.RoomID, Role: protocol.RoleHost, Token: original.HostToken,+ ClientID: "host-client", SessionID: "host-session",+ })+ if err != nil {+ t.Fatalf("connect host: %v", err)+ }+ invite, err := url.Parse(original.InviteURL)+ if err != nil {+ t.Fatalf("url.Parse(inviteUrl): %v", err)+ }+ if _, err := store.ConnectParticipant(room.ConnectParticipantInput{+ RoomID: original.RoomID, Role: protocol.RoleViewer,+ ViewerGrant: strings.TrimPrefix(invite.Fragment, "v="),+ ClientID: "viewer-client", SessionID: "viewer-session",+ }); err != nil {+ t.Fatalf("connect viewer: %v", err)+ }++ server.replaceRoom(original.RoomID, original.HostToken,+ `{"codeEntryPolicy":"open"}`, "").+ expect(http.StatusUnauthorized, `{"error":"Unauthorized"}`)++ replacement := server.replaceRoom(original.RoomID, original.HostToken,+ `{"codeEntryPolicy":"private","roomPassword":"new-password"}`, cookie).+ expectStatus(http.StatusCreated).room()++ if replacement.RoomID == original.RoomID {+ t.Fatal("the replacement kept the old room code")+ }+ if replacement.CodeEntryPolicy != "private" {+ t.Fatalf("codeEntryPolicy = %q", replacement.CodeEntryPolicy)+ }+ if _, connected := store.GetConnectedHost(original.RoomID); connected {+ t.Fatal("the old Host is still connected")+ }+ if viewers := store.GetConnectedViewers(original.RoomID); len(viewers) != 0 {+ t.Fatalf("old viewers = %v", viewers)+ }+ if _, err := store.ConnectParticipant(room.ConnectParticipantInput{+ RoomID: original.RoomID, Role: protocol.RoleHost, Token: original.HostToken,+ ClientID: "old-host", SessionID: "old-session",+ }); roomErrorCode(err) != room.CodeInvalidToken {+ t.Fatalf("reconnect error = %v, want INVALID_TOKEN", err)+ }+ if host.PeerID == "" {+ t.Fatal("the replaced Host never had a peer id")+ }+}++// TestRoomMutationFailuresMapToTheHTTPTable covers the two TS cases that used+// vi.spyOn to make RoomStore reject: "keeps valid Host authority on a transient+// replacement rejection" (ROOM_ACCESS_DENIED) and "maps a busy password gate to+// 503 for every HTTP mutation" (ROOM_BUSY on all three). Go cannot monkey patch+// a concrete *room.Store, and neither code is reachable from HTTP without a+// racing second mutation, so the pure mapping functions the three routes share+// are driven directly instead; that the store leaves the authority intact when+// it rejects is the room package's own contract.+func TestRoomMutationFailuresMapToTheHTTPTable(t *testing.T) {+ otherError := errors.New("storage failed")+ cases := []struct {+ name string+ mapper func(error) (int, string, bool)+ err error+ status int+ message string+ mapped bool+ }{+ {"replacement limit", replacementFailure, &room.Error{Code: room.CodeRoomLimit}, 503, "Room capacity reached", true},+ {"replacement denied", replacementFailure, &room.Error{Code: room.CodeRoomAccessDenied}, 503, "Room replacement unavailable", true},+ {"replacement busy", replacementFailure, &room.Error{Code: room.CodeRoomBusy}, 503, "Room replacement unavailable", true},+ {"replacement token", replacementFailure, &room.Error{Code: room.CodeInvalidToken}, 404, "Room not found", true},+ {"replacement missing", replacementFailure, &room.Error{Code: room.CodeRoomNotFound}, 404, "Room not found", true},+ {"replacement expired", replacementFailure, &room.Error{Code: room.CodeRoomExpired}, 404, "Room not found", true},+ {"replacement full", replacementFailure, &room.Error{Code: room.CodeRoomFull}, 0, "", false},+ {"replacement other", replacementFailure, otherError, 0, "", false},+ {"access busy", accessFailure, &room.Error{Code: room.CodeRoomBusy}, 503, "Room access update unavailable", true},+ {"access denied", accessFailure, &room.Error{Code: room.CodeRoomAccessDenied}, 409, "Room access update rejected", true},+ {"access token", accessFailure, &room.Error{Code: room.CodeInvalidToken}, 404, "Room not found", true},+ {"access limit", accessFailure, &room.Error{Code: room.CodeRoomLimit}, 404, "Room not found", true},+ {"access other", accessFailure, otherError, 0, "", false},+ {"creation limit", creationFailure, &room.Error{Code: room.CodeRoomLimit}, 503, "Room capacity reached", true},+ {"creation busy", creationFailure, &room.Error{Code: room.CodeRoomBusy}, 503, "Room creation unavailable", true},+ {"creation token", creationFailure, &room.Error{Code: room.CodeInvalidToken}, 400, "Invalid room request", true},+ {"creation denied", creationFailure, &room.Error{Code: room.CodeRoomAccessDenied}, 0, "", false},+ {"creation other", creationFailure, otherError, 0, "", false},+ }+ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ status, message, mapped := testCase.mapper(testCase.err)+ if status != testCase.status || message != testCase.message || mapped != testCase.mapped {+ t.Fatalf("got (%d, %q, %t), want (%d, %q, %t)",+ status, message, mapped,+ testCase.status, testCase.message, testCase.mapped)+ }+ })+ }+ // A wrapped store error still maps: the routes use errors.As.+ if status, _, mapped := creationFailure(+ fmt.Errorf("create: %w", &room.Error{Code: room.CodeRoomLimit}),+ ); !mapped || status != 503 {+ t.Fatalf("wrapped ROOM_LIMIT mapped=%t status=%d", mapped, status)+ }+}++func TestRoomAccessManagesADormantRoomWithoutStartingSharingOrRenewing(t *testing.T) {+ var now atomic.Int64+ configuration := testConfig(t)+ configuration.RoomLeaseMs = 1_000+ server := start(t, Options{Config: configuration, Now: now.Load})+ cookie := server.cookie()+ created := server.createRoom(roomRequest{cookie: cookie}).+ expectStatus(http.StatusCreated).room()+ now.Store(900)++ server.updateRoomAccess(accessRequest{+ roomID: created.RoomID, hostToken: created.HostToken, cookie: cookie,+ body: `{"action":"set-code-entry-policy","policy":"private"}`,+ }).+ expect(http.StatusOK,+ `{"type":"code-entry-policy-updated","codeEntryPolicy":"private","viewerPasswordEnabled":false}`).+ expectHeader("Cache-Control", "no-store")++ server.updateRoomAccess(accessRequest{+ roomID: created.RoomID, hostToken: created.HostToken, cookie: cookie,+ body: `{"action":"set-viewer-password","password":"room-password"}`,+ }).expect(http.StatusOK, `{"type":"viewer-password-updated","enabled":true}`)++ server.updateRoomAccess(accessRequest{+ roomID: created.RoomID, hostToken: created.HostToken, cookie: cookie,+ body: `{"action":"set-viewer-password","password":null}`,+ }).expect(http.StatusOK, `{"type":"viewer-password-updated","enabled":false}`)++ rotated := server.updateRoomAccess(accessRequest{+ roomID: created.RoomID, hostToken: created.HostToken, cookie: cookie,+ body: `{"action":"rotate-viewer-grant"}`,+ }).expectStatus(http.StatusOK)+ var rotatedBody struct {+ Type string `json:"type"`+ ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`+ InviteURL *string `json:"inviteUrl"`+ }+ if err := json.Unmarshal([]byte(rotated.body), &rotatedBody); err != nil {+ t.Fatalf("decode rotation: %v", err)+ }+ if rotatedBody.Type != "viewer-grant-updated" || rotatedBody.InviteURL == nil {+ t.Fatalf("rotation body = %s", rotated.body)+ }+ if !regexp.MustCompile(`#v=[A-Za-z0-9_-]{22}$`).MatchString(*rotatedBody.InviteURL) {+ t.Fatalf("rotated inviteUrl = %q", *rotatedBody.InviteURL)+ }++ revoked := server.updateRoomAccess(accessRequest{+ roomID: created.RoomID, hostToken: created.HostToken, cookie: cookie,+ body: `{"action":"revoke-viewer-grant"}`,+ }).expectStatus(http.StatusOK)+ if !strings.Contains(revoked.body, `"inviteUrl":null`) ||+ !strings.Contains(revoked.body, `"type":"viewer-grant-updated"`) {+ t.Fatalf("revocation body = %s", revoked.body)+ }+ if _, connected := server.Store().GetConnectedHost(created.RoomID); connected {+ t.Fatal("managing access started a sharing session")+ }++ now.Store(1_001)+ expired, err := server.Store().ExpireRooms(1_001)+ if err != nil {+ t.Fatalf("ExpireRooms: %v", err)+ }+ found := false+ for _, closed := range expired {+ if closed.RoomID == created.RoomID {+ found = true+ }+ }+ if !found {+ t.Fatalf("access management renewed the lease; expired = %v", expired)+ }+}++func TestRoomAccessRequiresSameOriginSiteAccessAndTheExactHostToken(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})+ cookie := server.cookie()+ first := server.createRoom(roomRequest{cookie: cookie}).+ expectStatus(http.StatusCreated).room()+ second := server.createRoom(roomRequest{cookie: cookie}).+ expectStatus(http.StatusCreated).room()+ rotate := `{"action":"rotate-viewer-grant"}`++ server.updateRoomAccess(accessRequest{+ roomID: first.RoomID, hostToken: first.HostToken, body: rotate,+ }).expect(http.StatusUnauthorized, `{"error":"Unauthorized"}`)++ server.updateRoomAccess(accessRequest{+ roomID: first.RoomID, hostToken: first.HostToken, body: rotate,+ cookie: cookie, origin: "https://foreign.test",+ }).expect(http.StatusForbidden, `{"error":"Forbidden"}`)++ server.updateRoomAccess(accessRequest{+ roomID: first.RoomID, body: rotate, cookie: cookie,+ }).expect(http.StatusNotFound, `{"error":"Room not found"}`)++ server.updateRoomAccess(accessRequest{+ roomID: first.RoomID, hostToken: "wrong-token", body: rotate, cookie: cookie,+ }).expect(http.StatusNotFound, `{"error":"Room not found"}`)++ server.updateRoomAccess(accessRequest{+ roomID: first.RoomID, hostToken: second.HostToken, body: rotate, cookie: cookie,+ }).expect(http.StatusNotFound, `{"error":"Room not found"}`)++ server.updateRoomAccess(accessRequest{+ roomID: first.RoomID, hostToken: first.HostToken, cookie: cookie,+ body: `{"action":"unknown"}`,+ }).expect(http.StatusBadRequest, `{"error":"Invalid room access request"}`)++ server.updateRoomAccess(accessRequest{+ roomID: first.RoomID, hostToken: first.HostToken, body: rotate,+ cookie: cookie, method: http.MethodGet,+ }).+ expect(http.StatusMethodNotAllowed, `{"error":"Method not allowed"}`).+ expectHeader("Allow", "POST")+}++func TestRoomCreationRejectsMalformedRequestsAndForeignBrowserOrigins(t *testing.T) {+ configuration := testConfig(t)+ configuration.SiteAccessPassword = ""+ server := start(t, Options{Config: configuration})++ server.do(http.MethodPost, "/api/rooms", withOrigin(allowedOrigin), withJSON("{}")).+ expect(http.StatusBadRequest, `{"error":"Invalid room request"}`)++ server.do(http.MethodPost, "/api/rooms",+ withOrigin("https://foreign.test"), withJSON(`{"codeEntryPolicy":"open"}`)).+ expect(http.StatusForbidden, `{"error":"Forbidden"}`)++ // An oversized or non-JSON body is the same 400.+ server.do(http.MethodPost, "/api/rooms", withOrigin(allowedOrigin),+ withJSON(`{"codeEntryPolicy":"open","preferredRoomId":"`+strings.Repeat("1", 1_024)+`"}`)).+ expect(http.StatusBadRequest, `{"error":"Invalid room request"}`)+ server.do(http.MethodPost, "/api/rooms", withOrigin(allowedOrigin),+ withBody("text/plain", `{"codeEntryPolicy":"open"}`)).+ expect(http.StatusBadRequest, `{"error":"Invalid room request"}`)++ server.do(http.MethodGet, "/api/rooms", withOrigin(allowedOrigin)).+ expect(http.StatusMethodNotAllowed, `{"error":"Method not allowed"}`).+ expectHeader("Allow", "POST")+}++func TestRoomCreationReturnsServiceUnavailableAtTheGlobalRoomBound(t *testing.T) {+ configuration := testConfig(t)+ configuration.SiteAccessPassword = ""+ store, err := room.New(room.Options{+ LeaseMs: 86_400_000, MaxRooms: 1, MaxViewersPerRoom: 8,+ })+ if err != nil {+ t.Fatalf("room.New: %v", err)+ }+ server := start(t, Options{Config: configuration, RoomStore: store})++ server.createRoom(roomRequest{}).expectStatus(http.StatusCreated)+ server.createRoom(roomRequest{}).+ expect(http.StatusServiceUnavailable, `{"error":"Room capacity reached"}`)+}++// --- server HTTP listener and health --------------------------------------++func TestServesAnExplicitStaticFrontendIndependentlyOfTheEnvironment(t *testing.T) {+ assets := fstest.MapFS{+ "index.html": &fstest.MapFile{Data: []byte("<main>local-static</main>")},+ "assets/app.js": &fstest.MapFile{+ Data: []byte("export const marker = 1;\n"),+ },+ }+ server := start(t, Options{Config: testConfig(t), Assets: assets})++ server.do(http.MethodGet, "/local-route").+ expect(http.StatusOK, "<main>local-static</main>").+ expectHeader("Content-Type", "text/html;charset=utf-8").+ expectHeader("X-Content-Type-Options", "nosniff").+ expectHeader("Referrer-Policy", "no-referrer")++ server.do(http.MethodGet, "/assets/app.js").+ expect(http.StatusOK, "export const marker = 1;\n").+ expectHeader("Content-Type", "text/javascript")++ // /api/** never falls through to the frontend.+ server.do(http.MethodGet, "/api/unknown").+ expect(http.StatusNotFound, `{"error":"Not found"}`).+ expectHeader("Cache-Control", "no-store")+ // A missing asset with an extension keeps the JSON 404.+ server.do(http.MethodGet, "/assets/missing.js").+ expect(http.StatusNotFound, `{"error":"Not found"}`)+}++func TestApiOnlyCompositionAnswersJSONNotFound(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})++ server.do(http.MethodGet, "/local-route").+ expect(http.StatusNotFound, `{"error":"Not found"}`).+ expectHeader("Cache-Control", "")+ server.do(http.MethodGet, "/api/unknown").+ expect(http.StatusNotFound, `{"error":"Not found"}`).+ expectHeader("Cache-Control", "no-store").+ expectHeader("X-Content-Type-Options", "")+}++func TestRestoresStableRoomAuthorityAcrossAnApplicationRestart(t *testing.T) {+ databasePath := filepath.Join(t.TempDir(), "rooms.sqlite")+ var now atomic.Int64+ now.Store(100)+ configuration := testConfig(t)+ configuration.SiteAccessPassword = ""+ configuration.RoomDatabasePath = databasePath+ configuration.RoomLeaseMs = 1_000++ first := start(t, Options{Config: configuration, Now: now.Load})+ created := first.createRoom(roomRequest{codeEntryPolicy: "private"}).+ expectStatus(http.StatusCreated).room()+ if err := first.Close(context.Background()); err != nil {+ t.Fatalf("close first: %v", err)+ }++ now.Store(200)+ second := start(t, Options{Config: configuration, Now: now.Load})+ if size := second.Store().Size(); size != 1 {+ t.Fatalf("restored room count = %d, want 1", size)+ }+ second.updateRoomAccess(accessRequest{+ roomID: created.RoomID, hostToken: created.HostToken,+ body: `{"action":"set-code-entry-policy","policy":"open"}`,+ }).expect(http.StatusOK,+ `{"type":"code-entry-policy-updated","codeEntryPolicy":"open","viewerPasswordEnabled":false}`)+}++func TestStartsWithAnInjectedOptionalSFUTokenIssuer(t *testing.T) {+ configuration := testConfig(t)+ configuration.LiveKit = livekitFallback()+ server := start(t, Options{Config: configuration, SFUTokenIssuer: fakeTokenIssuer{}})++ server.do(http.MethodGet, "/healthz").expect(http.StatusOK, `{"status":"ok"}`)+}++func TestClearsAStaleManagedLiveKitRoomBeforeServingTraffic(t *testing.T) {+ roomControl := sfutest.New()+ roomControl.SeedRoom(sfu.ResourceFence{+ RoomID: "42",+ ShareGeneration: "stale_share_generation",+ PublicationGeneration: "stale_publication_generation",+ }, "host", "viewer:stale")+ configuration := testConfig(t)+ configuration.LiveKit = livekitFallback()+ server := start(t, Options{Config: configuration, SFURoomControl: roomControl})++ if calls := roomControl.InitializeCalls(); calls != 1 {+ t.Fatalf("initialize calls = %d, want 1", calls)+ }+ if deleted := roomControl.StartupDeletedRoomNames(); len(deleted) != 1 {+ t.Fatalf("startup deleted rooms = %v, want one", deleted)+ }+ if count := roomControl.RoomCount(); count != 0 {+ t.Fatalf("live rooms = %d, want 0", count)+ }+ server.do(http.MethodGet, "/healthz").expect(http.StatusOK, `{"status":"ok"}`)+}++func TestBindsTheApplicationListenerBeforeLiveKitReconciliation(t *testing.T) {+ roomControl := sfutest.New()+ barrier := make(chan struct{})+ roomControl.SetInitializeBarrier(barrier)+ port := freePort(t)+ configuration := testConfig(t)+ configuration.Port = port+ configuration.LiveKit = livekitFallback()+ server := newServer(t, Options{Config: configuration, SFURoomControl: roomControl})+ client := testClient(t)++ listening := make(chan error, 1)+ go func() {+ bound, err := server.Listen(context.Background())+ if err == nil && bound != port {+ err = fmt.Errorf("bound port %d, want %d", bound, port)+ }+ listening <- err+ }()+ waitFor(t, "LiveKit reconciliation to start",+ func() bool { return roomControl.InitializeCalls() == 1 })++ // Hazard 13: the listener is bound but no traffic is accepted yet.+ send(t, client, http.MethodGet, baseURL(port)+"/healthz").+ expect(http.StatusServiceUnavailable, `{"error":"Service starting"}`).+ expectHeader("Retry-After", "1").+ expectHeader("Cache-Control", "no-store")+ // The /signal upgrade is not served either.+ send(t, client, http.MethodGet, baseURL(port)+"/signal",+ withOrigin(allowedOrigin),+ func(request *http.Request) {+ request.Header.Set("Connection", "Upgrade")+ request.Header.Set("Upgrade", "websocket")+ request.Header.Set("Sec-WebSocket-Version", "13")+ request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")+ }).+ expect(http.StatusServiceUnavailable, `{"error":"Service starting"}`)++ close(barrier)+ if err := <-listening; err != nil {+ t.Fatalf("Listen: %v", err)+ }+ send(t, client, http.MethodGet, baseURL(port)+"/healthz").+ expect(http.StatusOK, `{"status":"ok"}`)+}++func TestMakesNoLiveKitCallWhenAnotherProcessOwnsTheListener(t *testing.T) {+ owner := start(t, Options{Config: testConfig(t)})+ ownerPort := ownerBoundPort(t, owner)++ databasePath := filepath.Join(t.TempDir(), "missing-parent", "rooms.sqlite")+ roomControl := sfutest.New()+ configuration := testConfig(t)+ configuration.Port = ownerPort+ configuration.RoomDatabasePath = databasePath+ configuration.LiveKit = livekitFallback()+ contender := newServer(t, Options{Config: configuration, SFURoomControl: roomControl})++ // The TS test asserted the EADDRINUSE code; Windows reports WSAEADDRINUSE,+ // which errors.Is does not fold into syscall.EADDRINUSE, so the contract+ // asserted here is the one that matters: the bind failed, nothing was+ // reconciled, and the owner still holds the port.+ _, err := contender.Listen(context.Background())+ if err == nil {+ t.Fatal("the contender bound a port another process owns")+ }+ var addressError *net.OpError+ if !errors.As(err, &addressError) || addressError.Op != "listen" {+ t.Fatalf("Listen error = %v, want a listen failure", err)+ }+ if calls := roomControl.InitializeCalls(); calls != 0 {+ t.Fatalf("initialize calls = %d, want 0", calls)+ }+ if _, statErr := os.Stat(databasePath); !os.IsNotExist(statErr) {+ t.Fatalf("the room database was created: %v", statErr)+ }+ owner.do(http.MethodGet, "/healthz").expect(http.StatusOK, `{"status":"ok"}`)+}++// ownerBoundPort re-reads the port a started harness listens on.+func ownerBoundPort(t *testing.T, server *harness) int {+ t.Helper()+ parsed, err := url.Parse(server.baseURL)+ if err != nil {+ t.Fatalf("url.Parse: %v", err)+ }+ port := 0+ if _, err := fmt.Sscanf(parsed.Port(), "%d", &port); err != nil {+ t.Fatalf("parse port: %v", err)+ }+ return port+}++func TestRejectsASecondDatabaseOwnerBeforeLiveKitReconciliation(t *testing.T) {+ databasePath := filepath.Join(t.TempDir(), "rooms.sqlite")+ ownerConfig := testConfig(t)+ ownerConfig.RoomDatabasePath = databasePath+ start(t, Options{Config: ownerConfig})++ roomControl := sfutest.New()+ contenderConfig := testConfig(t)+ contenderConfig.Port = freePort(t)+ contenderConfig.RoomDatabasePath = databasePath+ contenderConfig.LiveKit = livekitFallback()+ contender := newServer(t, Options{Config: contenderConfig, SFURoomControl: roomControl})++ _, err := contender.Listen(context.Background())+ if err == nil || !strings.Contains(strings.ToLower(err.Error()), "locked") {+ t.Fatalf("Listen error = %v, want a locked database", err)+ }+ if calls := roomControl.InitializeCalls(); calls != 0 {+ t.Fatalf("initialize calls = %d, want 0", calls)+ }+ assertPortFree(t, contenderConfig.Port)+}++func TestRejectsAMismatchedDatabaseBeforeLiveKitReconciliation(t *testing.T) {+ databasePath := filepath.Join(t.TempDir(), "rooms.sqlite")+ raw, err := sql.Open("sqlite", "file:"+filepath.ToSlash(databasePath))+ if err != nil {+ t.Fatalf("sql.Open: %v", err)+ }+ if _, err := raw.Exec("CREATE TABLE unrelated(value TEXT) STRICT"); err != nil {+ t.Fatalf("seed unrelated schema: %v", err)+ }+ if err := raw.Close(); err != nil {+ t.Fatalf("close raw database: %v", err)+ }++ roomControl := sfutest.New()+ configuration := testConfig(t)+ configuration.Port = freePort(t)+ configuration.RoomDatabasePath = databasePath+ configuration.LiveKit = livekitFallback()+ server := newServer(t, Options{Config: configuration, SFURoomControl: roomControl})++ _, err = server.Listen(context.Background())+ if err == nil ||+ !strings.Contains(err.Error(), "Room database application identity does not match") {+ t.Fatalf("Listen error = %v", err)+ }+ if calls := roomControl.InitializeCalls(); calls != 0 {+ t.Fatalf("initialize calls = %d, want 0", calls)+ }+ assertPortFree(t, configuration.Port)+}++func TestRejectsAnInaccessibleDatabasePathBeforeLiveKitReconciliation(t *testing.T) {+ databasePath := filepath.Join(t.TempDir(), "missing-parent", "rooms.sqlite")+ roomControl := sfutest.New()+ configuration := testConfig(t)+ configuration.Port = freePort(t)+ configuration.RoomDatabasePath = databasePath+ configuration.LiveKit = livekitFallback()+ server := newServer(t, Options{Config: configuration, SFURoomControl: roomControl})++ if _, err := server.Listen(context.Background()); err == nil {+ t.Fatal("Listen accepted an unreachable database path")+ }+ if calls := roomControl.InitializeCalls(); calls != 0 {+ t.Fatalf("initialize calls = %d, want 0", calls)+ }+ if _, err := os.Stat(databasePath); !os.IsNotExist(err) {+ t.Fatalf("the room database was created: %v", err)+ }+ assertPortFree(t, configuration.Port)+}++func TestHoldsListenerOwnershipUntilAnInFlightStartupSettles(t *testing.T) {+ before := runtime.NumGoroutine()+ roomControl := sfutest.New()+ barrier := make(chan struct{})+ roomControl.SetInitializeBarrier(barrier)+ port := freePort(t)+ configuration := testConfig(t)+ configuration.Port = port+ configuration.LiveKit = livekitFallback()+ server := newServer(t, Options{Config: configuration, SFURoomControl: roomControl})++ listening := make(chan int, 1)+ go func() {+ bound, err := server.Listen(context.Background())+ if err != nil {+ bound = -1+ }+ listening <- bound+ }()+ waitFor(t, "LiveKit reconciliation to start",+ func() bool { return roomControl.InitializeCalls() == 1 })++ var closed atomic.Bool+ closing := make(chan error, 1)+ go func() {+ err := server.Close(context.Background())+ closed.Store(true)+ closing <- err+ }()+ time.Sleep(20 * time.Millisecond)+ if closed.Load() {+ t.Fatal("Close returned while startup was still in flight")+ }+ // A14: the listener is still owned, so a contender cannot take the port.+ if listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)); err == nil {+ _ = listener.Close()+ t.Fatal("the listener was released before startup settled")+ }++ close(barrier)+ if bound := <-listening; bound != port {+ t.Fatalf("Listen returned %d, want %d", bound, port)+ }+ if err := <-closing; err != nil {+ t.Fatalf("Close: %v", err)+ }+ if !closed.Load() {+ t.Fatal("Close never settled")+ }+ assertPortFree(t, port)+ expectGoroutinesSettled(t, before)+}++func TestClosesTheListenerWhenLiveKitStartupReconciliationFails(t *testing.T) {+ before := runtime.NumGoroutine()+ roomControl := sfutest.New()+ roomControl.SetInitializeError(errors.New("startup reconciliation failed"))+ port := freePort(t)+ configuration := testConfig(t)+ configuration.Port = port+ configuration.LiveKit = livekitFallback()+ server := newServer(t, Options{Config: configuration, SFURoomControl: roomControl})++ _, err := server.Listen(context.Background())+ if err == nil || !strings.Contains(err.Error(), "startup reconciliation failed") {+ t.Fatalf("Listen error = %v", err)+ }+ if calls := roomControl.InitializeCalls(); calls != 1 {+ t.Fatalf("initialize calls = %d, want 1", calls)+ }+ assertPortFree(t, port)+ expectGoroutinesSettled(t, before)+}++func TestUsesTheConfiguredListenHostByDefault(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})++ if !strings.HasPrefix(server.baseURL, "http://127.0.0.1:") {+ t.Fatalf("listen address = %q", server.baseURL)+ }+ server.do(http.MethodGet, "/healthz").expect(http.StatusOK, `{"status":"ok"}`)+}++func TestReportsProcessLivenessWithoutAccessChecks(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})++ server.do(http.MethodGet, "/healthz", withOrigin("https://foreign.test")).+ expect(http.StatusOK, `{"status":"ok"}`).+ expectHeader("Cache-Control", "no-store").+ expectHeader("Content-Type", "application/json; charset=utf-8")+}++func TestOnlyAcceptsGETHealthChecks(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})++ server.do(http.MethodPost, "/healthz").+ expect(http.StatusMethodNotAllowed, `{"error":"Method not allowed"}`).+ expectHeader("Allow", "GET").+ expectHeader("Cache-Control", "no-store")+}++func TestListenIsSingleShotAndRefusedAfterClose(t *testing.T) {+ before := runtime.NumGoroutine()+ server := start(t, Options{Config: testConfig(t)})++ if _, err := server.Listen(context.Background()); err == nil ||+ err.Error() != "Screener server startup was already requested" {+ t.Fatalf("second Listen error = %v", err)+ }+ if err := server.Close(context.Background()); err != nil {+ t.Fatalf("Close: %v", err)+ }+ expectGoroutinesSettled(t, before)++ fresh := newServer(t, Options{Config: testConfig(t)})+ if err := fresh.Close(context.Background()); err != nil {+ t.Fatalf("Close before Listen: %v", err)+ }+ if _, err := fresh.Listen(context.Background()); err == nil ||+ err.Error() != "Screener server is closing" {+ t.Fatalf("Listen after Close error = %v", err)+ }+}++// --- request failures and server settings ---------------------------------++// The createServer .catch of app.ts: a handler that throws answers 500 and the+// record carries the method and the path only (D11).+func TestRequestFailureAnswers500AndLogsMethodAndPathOnly(t *testing.T) {+ var logged bytes.Buffer+ server := newServer(t, Options{+ Config: testConfig(t),+ Logger: slog.New(slog.NewTextHandler(&logged, nil)),+ })+ server.frontend = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {+ panic("viewer-grant-that-must-not-be-logged")+ })+ server.acceptingTraffic.Store(true)++ recorder := httptest.NewRecorder()+ server.ServeHTTP(recorder,+ httptest.NewRequest(http.MethodGet, "/boom?grant=viewer-grant-that-must-not-be-logged", nil))++ if recorder.Code != http.StatusInternalServerError {+ t.Fatalf("status = %d, want 500", recorder.Code)+ }+ if body := recorder.Body.String(); body != `{"error":"Internal server error"}` {+ t.Fatalf("body = %s", body)+ }+ record := logged.String()+ if !strings.Contains(record, "HTTP request failed") ||+ !strings.Contains(record, "method=GET") ||+ !strings.Contains(record, "path=/boom") {+ t.Fatalf("log record = %q", record)+ }+ if strings.Contains(record, "viewer-grant-that-must-not-be-logged") {+ t.Fatalf("the failure log leaked the request: %q", record)+ }+}++// A failure after the response started destroyed the socket in Node; in Go the+// equivalent is http.ErrAbortHandler, which net/http turns into a silent close.+func TestRequestFailureAfterTheResponseStartedAbortsTheConnection(t *testing.T) {+ server := newServer(t, Options{+ Config: testConfig(t),+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ server.frontend = http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {+ writer.WriteHeader(http.StatusOK)+ panic("late failure")+ })+ server.acceptingTraffic.Store(true)++ defer func() {+ if recovered := recover(); recovered != http.ErrAbortHandler {+ t.Fatalf("recovered = %v, want http.ErrAbortHandler", recovered)+ }+ }()+ server.ServeHTTP(httptest.NewRecorder(),+ httptest.NewRequest(http.MethodGet, "/late", nil))+ t.Fatal("ServeHTTP returned instead of aborting the connection")+}++// The three Node HTTP server settings of map section 3.3 / D11, and the write+// deadline Node never had.+func TestHTTPServerKeepsTheNodeTimeouts(t *testing.T) {+ server := newServer(t, Options{Config: testConfig(t)})++ if got := server.httpServer.ReadHeaderTimeout; got != 15*time.Second {+ t.Fatalf("ReadHeaderTimeout = %v, want headersTimeout 15s", got)+ }+ if got := server.httpServer.ReadTimeout; got != 10*time.Second {+ t.Fatalf("ReadTimeout = %v, want requestTimeout 10s", got)+ }+ if got := server.httpServer.IdleTimeout; got != 5*time.Second {+ t.Fatalf("IdleTimeout = %v, want keepAliveTimeout 5s", got)+ }+ if got := server.httpServer.WriteTimeout; got != 0 {+ t.Fatalf("WriteTimeout = %v, want none", got)+ }+}++// The upgrade dispatch of ServeHTTP: Node handed every Connection: Upgrade+// request to the signaling server's own listener, which owns the whole+// rejection ladder, and a plain GET of the same path stayed an ordinary+// request. It is also the only cover for the response wrapper being+// unwrappable to the http.Hijacker websocket.Accept needs.+func TestSignalUpgradeIsDispatchedToTheSignalingServer(t *testing.T) {+ server := start(t, Options{Config: testConfig(t)})+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ // websocket.Dial refuses a client with a Timeout, so the harness client+ // cannot be reused here.+ client := &http.Client{Transport: &http.Transport{DisableKeepAlives: true}}+ target := "ws" + strings.TrimPrefix(server.baseURL, "http") + "/signal"++ connection, _, err := websocket.Dial(ctx, target, &websocket.DialOptions{+ HTTPClient: client,+ HTTPHeader: http.Header{"Origin": []string{allowedOrigin}},+ })+ if err != nil {+ t.Fatalf("upgrade /signal: %v", err)+ }+ if err := connection.Close(websocket.StatusNormalClosure, ""); err != nil {+ t.Fatalf("close signal connection: %v", err)+ }++ if _, _, err := websocket.Dial(ctx, target, &websocket.DialOptions{+ HTTPClient: client,+ HTTPHeader: http.Header{"Origin": []string{"https://foreign.test"}},+ }); err == nil {+ t.Fatal("a foreign origin completed the upgrade")+ }++ server.do(http.MethodGet, "/signal").+ expect(http.StatusNotFound, `{"error":"Not found"}`)+}++// --- startup failures the TypeScript could not have ------------------------++// panickingRoomControl is a reconciliation step that fails with a panic rather+// than an error, which is what a nil dereference inside a future startup step+// would look like.+type panickingRoomControl struct{ sfu.RoomControl }++func (panickingRoomControl) Initialize(context.Context) error {+ panic(errors.New("startup reconciliation panicked"))+}++// app.ts:219 awaited startupOperation inside a try/catch, so a rejected+// startup still settled the promise shutdown waited on. A panic out of start()+// must release the same latch.+func TestShutdownIsNotBlockedByAStartupThatPanicked(t *testing.T) {+ configuration := testConfig(t)+ configuration.LiveKit = livekitFallback()+ server, err := New(Options{+ Config: configuration,+ SFURoomControl: panickingRoomControl{},+ SFUTokenIssuer: fakeTokenIssuer{},+ HeartbeatIntervalMs: 60_000,+ CleanupIntervalMs: 60_000,+ })+ if err != nil {+ t.Fatalf("New: %v", err)+ }++ func() {+ defer func() {+ if recovered := recover(); recovered == nil {+ t.Fatal("Listen swallowed the startup panic")+ }+ }()+ _, _ = server.Listen(context.Background())+ }()++ closed := make(chan error, 1)+ go func() { closed <- server.Close(context.Background()) }()+ select {+ case <-closed:+ case <-time.After(5 * time.Second):+ t.Fatal("Close blocked on the startup latch after a panicking startup")+ }+}++// syncBuffer collects log records written from the Serve goroutine.+type syncBuffer struct {+ mu sync.Mutex+ records bytes.Buffer+}++func (buffer *syncBuffer) Write(record []byte) (int, error) {+ buffer.mu.Lock()+ defer buffer.mu.Unlock()+ return buffer.records.Write(record)+}++func (buffer *syncBuffer) String() string {+ buffer.mu.Lock()+ defer buffer.mu.Unlock()+ return buffer.records.String()+}++// Node ended the process when the listening server raised, because+// bindHttpServer had already removed its "error" handler. Serve's error must+// at least reach the operator instead of leaving nothing serving in silence.+func TestReportsAListenerThatDiesWhileServing(t *testing.T) {+ var logged syncBuffer+ server := newServer(t, Options{+ Config: testConfig(t),+ Logger: slog.New(slog.NewTextHandler(&logged, nil)),+ })+ if _, err := server.Listen(context.Background()); err != nil {+ t.Fatalf("Listen: %v", err)+ }++ // Out of band: no Shutdown, so Serve returns a real accept failure.+ if err := server.listener.Close(); err != nil {+ t.Fatalf("close the listener: %v", err)+ }+ waitFor(t, "the serve failure to be reported", func() bool {+ return strings.Contains(logged.String(), "Screener HTTP server stopped unexpectedly")+ })+}diff --git a/internal/server/app/json.go b/internal/server/app/json.gonew file mode 100644index 00000000..736a28d0--- /dev/null+++ b/internal/server/app/json.go@@ -0,0 +1,148 @@+package app++import (+ "bytes"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "strconv"+ "strings"+)++// Request and response helpers ported from src/server/app.ts.++// maxJSONRequestBytes is the readJsonBody(request, 1_024) budget every JSON+// route shares.+const maxJSONRequestBytes = 1024++// errorBody is the { error } shape every failing route answers with.+type errorBody struct {+ Error string `json:"error"`+}++// healthBody is the /healthz payload.+type healthBody struct {+ Status string `json:"status"`+}++// siteAccessBody is siteAccessStatus(); the key order is the TS literal's.+type siteAccessBody struct {+ Required bool `json:"required"`+ Authenticated bool `json:"authenticated"`+}++// sendJSON always sets the exact Content-Length and the charset, as app.ts did.+// Encoding one of this package's own values cannot fail, so a marshal error is+// a programming error and reaches the recover wrapper.+func sendJSON(writer http.ResponseWriter, status int, body any) {+ var buffer bytes.Buffer+ encoder := json.NewEncoder(&buffer)+ // D9: JSON.stringify does not escape HTML either.+ encoder.SetEscapeHTML(false)+ if err := encoder.Encode(body); err != nil {+ panic(err)+ }+ encoded := bytes.TrimSuffix(buffer.Bytes(), []byte("\n"))+ header := writer.Header()+ header.Set("Content-Type", "application/json; charset=utf-8")+ header.Set("Content-Length", strconv.Itoa(len(encoded)))+ writer.WriteHeader(status)+ _, _ = writer.Write(encoded)+}++// readJSONBody ports readJsonBody: the content type must be exactly+// application/json once its parameters are cut, the body must be at most 1024+// bytes and must not be empty. Every failure collapses to the route's 400, so+// the messages only exist to keep the TS reasons readable.+func readJSONBody(request *http.Request) ([]byte, error) {+ contentType, _, _ := strings.Cut(request.Header.Get("Content-Type"), ";")+ if strings.TrimSpace(contentType) != "application/json" {+ return nil, errors.New("Request content type must be application/json")+ }+ body, err := io.ReadAll(io.LimitReader(request.Body, maxJSONRequestBytes+1))+ if err != nil {+ return nil, err+ }+ if len(body) > maxJSONRequestBytes {+ return nil, errors.New("Request body is too large")+ }+ if len(body) == 0 {+ return nil, errors.New("Request body is required")+ }+ return body, nil+}++// hasRequestBody ports hasRequestBody. net/http parses Content-Length and moves+// Transfer-Encoding out of Header, so a chunked body is ContentLength -1 and an+// unparseable length never reaches a handler at all.+func hasRequestBody(request *http.Request) bool {+ return len(request.TransferEncoding) > 0 || request.ContentLength != 0+}++// requestPath is the WHATWG `url.pathname` app.ts routed and logged on. It is+// the escaped path on purpose: `new URL()` does not percent-decode, so+// "/api%2frooms" must not reach the /api/rooms route.+//+// Deviation: `new URL()` also resolves "." and ".." segments, which net/http+// leaves in the path. "/x/../api/rooms" therefore reaches the frontend handler+// here where TypeScript routed it to room creation. Only stricter: a raw path+// that already names a route still matches, so nothing can slip past an origin,+// cookie or token check that way.+func requestPath(request *http.Request) string {+ return request.URL.EscapedPath()+}++// cookieHeader rebuilds the single Cookie header value the Node parser handed+// to access-session.ts; Go keeps repeated Cookie headers apart.+func cookieHeader(request *http.Request) string {+ return strings.Join(request.Header.Values("Cookie"), "; ")+}++// bearerToken ports readBearerToken: the prefix is case sensitive and an empty+// token counts as absent.+func bearerToken(request *http.Request) string {+ authorization := request.Header.Get("Authorization")+ if !strings.HasPrefix(authorization, "Bearer ") {+ return ""+ }+ return strings.TrimPrefix(authorization, "Bearer ")+}++// isUpgradeRequest reproduces the condition under which Node emitted "upgrade"+// instead of "request": the parser needs both a Connection: upgrade token and+// an Upgrade header. The SignalingServer, not this router, owns the rejection+// ladder for a path or query that is not exactly /signal.+func isUpgradeRequest(request *http.Request) bool {+ if request.Header.Get("Upgrade") == "" {+ return false+ }+ for _, token := range strings.Split(request.Header.Get("Connection"), ",") {+ if strings.EqualFold(strings.TrimSpace(token), "upgrade") {+ return true+ }+ }+ return false+}++// responseRecorder tracks response.headersSent so the recover wrapper can pick+// between the JSON 500 and destroying the connection, as app.ts did.+type responseRecorder struct {+ http.ResponseWriter+ wrote bool+}++func (recorder *responseRecorder) WriteHeader(status int) {+ recorder.wrote = true+ recorder.ResponseWriter.WriteHeader(status)+}++func (recorder *responseRecorder) Write(data []byte) (int, error) {+ recorder.wrote = true+ return recorder.ResponseWriter.Write(data)+}++// Unwrap lets http.ResponseController reach the real writer's Flush and Hijack.+func (recorder *responseRecorder) Unwrap() http.ResponseWriter {+ return recorder.ResponseWriter+}diff --git a/internal/server/app/routes.go b/internal/server/app/routes.gonew file mode 100644index 00000000..d1a73728--- /dev/null+++ b/internal/server/app/routes.go@@ -0,0 +1,442 @@+package app++import (+ "errors"+ "net/http"+ "net/url"+ "regexp"+ "strings"++ "github.com/TNTcraftHIM/Screener/internal/server/config"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+ "github.com/TNTcraftHIM/Screener/internal/server/room"+ "github.com/TNTcraftHIM/Screener/internal/server/signal"+)++// The request router of src/server/app.ts. Route order is a contract (map+// section 4.3, O34): the first match wins and the /api/ catch-all sits after+// every concrete route.++var (+ roomReplacementPath = regexp.MustCompile(`^/api/rooms/([1-9][0-9]{3})/replacement$`)+ roomAccessPath = regexp.MustCompile(`^/api/rooms/([1-9][0-9]{3})/access$`)+)++// ServeHTTP is the createServer request listener of app.ts.+func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {+ recorder := &responseRecorder{ResponseWriter: writer}+ defer func() {+ recovered := recover()+ if recovered == nil {+ return+ }+ if recovered == http.ErrAbortHandler {+ panic(recovered)+ }+ // TS: console.error("HTTP request failed", {method, path, error}).+ // D11 keeps the method and the path only.+ s.requestFailed(recorder, request)+ }()++ if !s.acceptingTraffic.Load() {+ // Hazard 13: no traffic at all until the SignalingServer exists, so+ // /healthz answers 503 while LiveKit reconciliation runs.+ recorder.Header().Set("Cache-Control", "no-store")+ recorder.Header().Set("Retry-After", "1")+ sendJSON(recorder, http.StatusServiceUnavailable, errorBody{"Service starting"})+ return+ }+ signaling := s.signaling.Load()+ if isUpgradeRequest(request) {+ // Node routed every upgrade to the SignalingServer's "upgrade"+ // listener, which was attached only while traffic was accepted.+ signaling.ServeHTTP(recorder, request)+ return+ }+ s.route(recorder, request, signaling)+}++func (s *Server) route(+ writer http.ResponseWriter,+ request *http.Request,+ signaling *signal.Server,+) {+ path := requestPath(request)++ if path == "/healthz" {+ writer.Header().Set("Cache-Control", "no-store")+ if !allowMethod(writer, request, http.MethodGet) {+ return+ }+ sendJSON(writer, http.StatusOK, healthBody{"ok"})+ return+ }++ if path == "/api/capabilities" {+ noStoreJSON(writer)+ if !allowMethod(writer, request, http.MethodGet) {+ return+ }+ sendJSON(writer, http.StatusOK, protocol.RuntimeCapabilities{+ NatPrediction: s.config.NATPredictionEnabled,+ })+ return+ }++ if path == "/api/site-access" {+ s.handleSiteAccess(writer, request)+ return+ }++ if match := roomReplacementPath.FindStringSubmatch(path); match != nil {+ s.handleRoomReplacement(writer, request, signaling, match[1])+ return+ }++ if match := roomAccessPath.FindStringSubmatch(path); match != nil {+ s.handleRoomAccess(writer, request, signaling, match[1])+ return+ }++ if path == "/api/rooms" {+ s.handleRoomCreation(writer, request, signaling)+ return+ }++ if strings.HasPrefix(path, "/api/") {+ // The catch-all sets no nosniff header; only the concrete routes do.+ writer.Header().Set("Cache-Control", "no-store")+ sendJSON(writer, http.StatusNotFound, errorBody{"Not found"})+ return+ }++ if s.frontend != nil {+ s.frontend.ServeHTTP(writer, request)+ return+ }+ notFoundJSON(writer, request)+}++// notFoundJSON is the fallthrough app.ts handed to sirv as its next()+// callback and used when no frontend is composed at all.+func notFoundJSON(writer http.ResponseWriter, _ *http.Request) {+ sendJSON(writer, http.StatusNotFound, errorBody{"Not found"})+}++// noStoreJSON sets the two headers every /api route sets before its method+// check, so a 405 carries them too.+func noStoreJSON(writer http.ResponseWriter) {+ writer.Header().Set("Cache-Control", "no-store")+ writer.Header().Set("X-Content-Type-Options", "nosniff")+}++// allowMethod answers the 405 row of the HTTP table, Allow header included.+func allowMethod(writer http.ResponseWriter, request *http.Request, allowed string) bool {+ if request.Method == allowed {+ return true+ }+ writer.Header().Set("Allow", allowed)+ sendJSON(writer, http.StatusMethodNotAllowed, errorBody{"Method not allowed"})+ return false+}++// handleSiteAccess is handleSiteAccessRequest of app.ts.+func (s *Server) handleSiteAccess(writer http.ResponseWriter, request *http.Request) {+ noStoreJSON(writer)++ if request.Method == http.MethodGet {+ status := siteAccessBody{+ Required: s.siteAccess.required(),+ Authenticated: s.siteAccess.isAuthenticated(cookieHeader(request)),+ }+ if status.Required && status.Authenticated {+ // The Set-Cookie value is written verbatim, in the TS attribute+ // order (D11).+ writer.Header().Set("Set-Cookie", s.siteAccess.createCookie())+ }+ sendJSON(writer, http.StatusOK, status)+ return+ }++ if request.Method != http.MethodPost {+ writer.Header().Set("Allow", "GET, POST")+ sendJSON(writer, http.StatusMethodNotAllowed, errorBody{"Method not allowed"})+ return+ }++ if !s.allowedRequestOrigin(request) {+ sendJSON(writer, http.StatusForbidden, errorBody{"Forbidden"})+ return+ }+ if hasRequestBody(request) {+ sendJSON(writer, http.StatusBadRequest, errorBody{"Request body is not accepted"})+ return+ }+ if !s.siteAccess.required() {+ sendJSON(writer, http.StatusOK, siteAccessBody{Required: false, Authenticated: true})+ return+ }+ if provided := bearerToken(request); provided == "" || !s.siteAccess.passwordMatches(provided) {+ writer.Header().Set("WWW-Authenticate", "Bearer")+ sendJSON(writer, http.StatusUnauthorized, errorBody{"Unauthorized"})+ return+ }+ writer.Header().Set("Set-Cookie", s.siteAccess.createCookie())+ sendJSON(writer, http.StatusOK, siteAccessBody{Required: true, Authenticated: true})+}++func (s *Server) handleRoomReplacement(+ writer http.ResponseWriter,+ request *http.Request,+ signaling *signal.Server,+ roomID string,+) {+ noStoreJSON(writer)+ if !allowMethod(writer, request, http.MethodPost) {+ return+ }+ hostToken, authorized := s.authorizedRoomHostToken(writer, request)+ if !authorized {+ return+ }+ body, err := readJSONBody(request)+ var parsed protocol.ReplaceRoomRequest+ if err == nil {+ parsed, err = protocol.DecodeReplaceRoomRequest(body)+ }+ if err != nil {+ sendJSON(writer, http.StatusBadRequest, errorBody{"Invalid room replacement request"})+ return+ }+ if signaling == nil {+ sendJSON(writer, http.StatusServiceUnavailable, errorBody{"Service unavailable"})+ return+ }+ created, err := signaling.ReplaceRoom(+ roomID,+ hostToken,+ parsed.CodeEntryPolicy,+ parsed.RoomPassword.Value,+ )+ if err != nil {+ if status, message, mapped := replacementFailure(err); mapped {+ sendJSON(writer, status, errorBody{message})+ return+ }+ s.requestFailed(writer, request)+ return+ }+ sendJSON(writer, http.StatusCreated, s.createRoomResponse(created))+}++func (s *Server) handleRoomAccess(+ writer http.ResponseWriter,+ request *http.Request,+ signaling *signal.Server,+ roomID string,+) {+ noStoreJSON(writer)+ if !allowMethod(writer, request, http.MethodPost) {+ return+ }+ hostToken, authorized := s.authorizedRoomHostToken(writer, request)+ if !authorized {+ return+ }+ body, err := readJSONBody(request)+ var parsed protocol.RoomAccessUpdateRequest+ if err == nil {+ parsed, err = protocol.DecodeRoomAccessUpdateRequest(body)+ }+ if err != nil {+ sendJSON(writer, http.StatusBadRequest, errorBody{"Invalid room access request"})+ return+ }+ if signaling == nil {+ sendJSON(writer, http.StatusServiceUnavailable, errorBody{"Service unavailable"})+ return+ }+ updated, err := signaling.UpdateRoomAccess(roomID, hostToken, parsed)+ if err != nil {+ if status, message, mapped := accessFailure(err); mapped {+ sendJSON(writer, status, errorBody{message})+ return+ }+ s.requestFailed(writer, request)+ return+ }+ sendJSON(writer, http.StatusOK, updated)+}++func (s *Server) handleRoomCreation(+ writer http.ResponseWriter,+ request *http.Request,+ signaling *signal.Server,+) {+ noStoreJSON(writer)+ if !allowMethod(writer, request, http.MethodPost) {+ return+ }+ if !s.allowedRequestOrigin(request) {+ sendJSON(writer, http.StatusForbidden, errorBody{"Forbidden"})+ return+ }+ // Hazard 12: the cookie is the only room-creation credential. A+ // `Bearer <site password>` header must still be 401.+ if !s.roomCreationAuthorized(request) {+ sendJSON(writer, http.StatusUnauthorized, errorBody{"Unauthorized"})+ return+ }+ body, err := readJSONBody(request)+ var parsed protocol.CreateRoomRequest+ if err == nil {+ parsed, err = protocol.DecodeCreateRoomRequest(body)+ }+ if err != nil {+ sendJSON(writer, http.StatusBadRequest, errorBody{"Invalid room request"})+ return+ }+ // TS called roomStore.createRoom directly; the store is now guarded by the+ // signaling server's global mutex, so creation goes through it. There is+ // no `signaling == nil` answer here, because app.ts had no getSignaling()+ // check on this route: reconcile stores the signaling server before it+ // sets acceptingTraffic and never clears it again, so reaching a handler+ // at all means the pointer is set (the two sibling room routes keep their+ // 503 only because the TypeScript had one).+ created, err := signaling.CreateRoom(+ parsed.CodeEntryPolicy,+ parsed.RoomPassword.Value,+ parsed.PreferredRoomID,+ )+ if err != nil {+ if status, message, mapped := creationFailure(err); mapped {+ sendJSON(writer, status, errorBody{message})+ return+ }+ s.requestFailed(writer, request)+ return+ }+ sendJSON(writer, http.StatusCreated, s.createRoomResponse(created))+}++// authorizedRoomHostToken of app.ts: origin, then site access, then the bearer+// Host token, each with its own terminal response.+func (s *Server) authorizedRoomHostToken(+ writer http.ResponseWriter,+ request *http.Request,+) (string, bool) {+ if !s.allowedRequestOrigin(request) {+ sendJSON(writer, http.StatusForbidden, errorBody{"Forbidden"})+ return "", false+ }+ if !s.roomCreationAuthorized(request) {+ sendJSON(writer, http.StatusUnauthorized, errorBody{"Unauthorized"})+ return "", false+ }+ hostToken := bearerToken(request)+ if hostToken == "" {+ // An absent Host token is indistinguishable from a wrong one.+ sendJSON(writer, http.StatusNotFound, errorBody{"Room not found"})+ return "", false+ }+ return hostToken, true+}++// allowedRequestOrigin ports isStrictlyAllowedRequestOrigin: the header must be+// present, must parse, must be exactly its own serialised origin (so+// "http://allowed.test/path" is refused) and must be configured.+func (s *Server) allowedRequestOrigin(request *http.Request) bool {+ origin := request.Header.Get("Origin")+ if origin == "" {+ return false+ }+ parsed, err := url.Parse(origin)+ if err != nil || config.Origin(parsed) != origin {+ return false+ }+ _, allowed := s.config.AllowedOrigins[origin]+ return allowed+}++// roomCreationAuthorized ports isRoomCreationAuthorized.+func (s *Server) roomCreationAuthorized(request *http.Request) bool {+ return !s.siteAccess.required() || s.siteAccess.isAuthenticated(cookieHeader(request))+}++// createRoomResponse of app.ts. signal.InviteURL is the one owner of the invite+// URL shape; the rotated-grant notification on the signaling side uses it too.+func (s *Server) createRoomResponse(created room.CreatedRoom) protocol.CreateRoomResponse {+ return protocol.CreateRoomResponse{+ RoomID: created.RoomID,+ HostToken: created.HostToken,+ InviteURL: signal.InviteURL(s.config.PublicBaseURL, created.RoomID, created.ViewerGrant),+ CodeEntryPolicy: created.CodeEntryPolicy,+ ExpiresAt: created.ExpiresAt,+ // The lease is configured in whole seconds; TS divided by 1000 into a+ // JS number and the response schema declares an integer.+ RoomLeaseSeconds: protocol.Int(s.config.RoomLeaseMs / 1_000),+ }+}++// requestFailed is the createServer .catch: log the method and the path only —+// never a body, header, token or grant (D11) — then answer 500 unless the+// response already started, where Node destroyed the socket.+func (s *Server) requestFailed(writer http.ResponseWriter, request *http.Request) {+ s.logger.Error("HTTP request failed",+ "method", request.Method, "path", requestPath(request))+ if recorder, ok := writer.(*responseRecorder); ok && recorder.wrote {+ panic(http.ErrAbortHandler)+ }+ sendJSON(writer, http.StatusInternalServerError, errorBody{"Internal server error"})+}++// roomErrorCode returns the RoomStoreError code, or "" when err is not one.+func roomErrorCode(err error) room.ErrorCode {+ var roomError *room.Error+ if errors.As(err, &roomError) {+ return roomError.Code+ }+ return ""+}++// replacementFailure maps replaceRoom errors; an unmapped error rethrows into+// the 500 handler, as the TS `throw error` did.+func replacementFailure(err error) (int, string, bool) {+ switch roomErrorCode(err) {+ case room.CodeRoomLimit:+ return http.StatusServiceUnavailable, "Room capacity reached", true+ case room.CodeRoomAccessDenied, room.CodeRoomBusy:+ return http.StatusServiceUnavailable, "Room replacement unavailable", true+ case room.CodeInvalidToken, room.CodeRoomNotFound, room.CodeRoomExpired:+ return http.StatusNotFound, "Room not found", true+ }+ return 0, "", false+}++// accessFailure maps updateRoomAccess errors. Unlike the other two tables,+// every remaining RoomStoreError is a 404; only a non-store error rethrows.+func accessFailure(err error) (int, string, bool) {+ switch code := roomErrorCode(err); code {+ case "":+ return 0, "", false+ case room.CodeRoomBusy:+ return http.StatusServiceUnavailable, "Room access update unavailable", true+ case room.CodeRoomAccessDenied:+ return http.StatusConflict, "Room access update rejected", true+ default:+ return http.StatusNotFound, "Room not found", true+ }+}++// creationFailure maps createRoom errors.+func creationFailure(err error) (int, string, bool) {+ switch roomErrorCode(err) {+ case room.CodeRoomLimit:+ return http.StatusServiceUnavailable, "Room capacity reached", true+ case room.CodeRoomBusy:+ return http.StatusServiceUnavailable, "Room creation unavailable", true+ case room.CodeInvalidToken:+ return http.StatusBadRequest, "Invalid room request", true+ }+ return 0, "", false+}diff --git a/internal/server/app/static.go b/internal/server/app/static.gonew file mode 100644index 00000000..0e15f9a2--- /dev/null+++ b/internal/server/app/static.go@@ -0,0 +1,162 @@+package app++import (+ "io"+ "io/fs"+ "net/http"+ "path"+ "strings"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// staticContentTypes freezes mrmime's answers for the extensions a Vite build+// of this repo can emit. Go's mime.TypeByExtension overlays the Windows+// registry or /etc/mime.types, so the served Content-Type would otherwise+// depend on the machine; with X-Content-Type-Options: nosniff a wrong type on a+// font or a webmanifest is user visible. See evidence/runtime.md section 4.2.+var staticContentTypes = map[string]string{+ ".html": "text/html;charset=utf-8", // sirv appends ";charset=utf-8" with no space+ ".htm": "text/html;charset=utf-8",+ ".js": "text/javascript",+ ".mjs": "text/javascript",+ ".css": "text/css",+ ".json": "application/json",+ ".map": "application/json",+ ".txt": "text/plain",+ ".svg": "image/svg+xml",+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".webp": "image/webp",+ ".gif": "image/gif",+ ".avif": "image/avif",+ ".woff": "font/woff",+ ".woff2": "font/woff2",+ ".ttf": "font/ttf",+ ".otf": "font/otf",+ ".wasm": "application/wasm",+ ".webmanifest": "application/manifest+json",+ ".bin": "application/octet-stream",+ ".xml": "text/xml",+ ".ico": "", // mrmime has no .ico, so sirv sends an EMPTY Content-Type+}++// staticHandler reproduces `sirv(directory, { single: true, setHeaders })` as+// src/server/app.ts used it, over an fs.FS instead of a directory walk.+// notFound is the app's JSON 404, which sirv reached through its next()+// callback. Verified against [email protected] in evidence/runtime.md section 4.4.+func staticHandler(assets fs.FS, notFound http.Handler) http.Handler {+ return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {+ // sirv never inspects req.method: app.ts routes /healthz and /api/**+ // first, so everything else reaches the frontend handler as-is.+ cleaned := path.Clean("/" + request.URL.Path)+ name := strings.TrimPrefix(cleaned, "/")++ serve := func(candidate string) bool {+ // path.Clean already dropped any "..", and totalist never indexed a+ // dot-prefixed segment, so neither can be served.+ if candidate == "" || hasDotSegment(candidate) {+ return false+ }+ file, err := assets.Open(candidate)+ if err != nil {+ return false+ }+ defer file.Close()+ info, err := file.Stat()+ if err != nil || info.IsDir() {+ return false+ }+ seeker, ok := file.(io.ReadSeeker)+ if !ok {+ return false+ }+ // app.ts setHeaders.+ writer.Header().Set("X-Content-Type-Options", "nosniff")+ writer.Header().Set("Referrer-Policy", "no-referrer")+ // Set Content-Type explicitly, possibly to "", so ServeContent+ // never sniffs; the empty name keeps it from guessing either.+ writer.Header()["Content-Type"] = []string{staticContentTypes[strings.ToLower(path.Ext(candidate))]}+ // embed.FS reports a zero ModTime, so no Last-Modified is emitted+ // and no conditional request is honoured. sirv sends+ // Last-Modified but never answers 304 either; do not fabricate one.+ http.ServeContent(writer, request, "", info.ModTime(), seeker)+ return true+ }++ // sirv strips a trailing "/" before the lookup, and its FILES map holds+ // files only, so "/assets/" can never hit a file.+ if !strings.HasSuffix(request.URL.Path, "/") && serve(name) {+ return+ }+ // opts.single: fall back to index.html unless the request matches one+ // of sirv's two default ignores.+ if !looksLikeFile(cleaned) && !strings.Contains(cleaned, "/.well-known") {+ if serve("index.html") {+ return+ }+ }+ notFound.ServeHTTP(writer, request)+ })+}++// hasDotSegment reports whether any path segment starts with '.', reproducing+// totalist's filter `!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)` together+// with the `/\.well-known[\\+\/]/` exemption that runs before it.+func hasDotSegment(name string) bool {+ if strings.Contains(name, ".well-known/") {+ return false+ }+ for _, segment := range strings.Split(name, "/") {+ if strings.HasPrefix(segment, ".") {+ return true+ }+ }+ return false+}++// looksLikeFile ports sirv's default "any extn" ignore,+// /[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/. Because the character class excludes+// "/" and the match is anchored at the end, only the last path segment can+// match: it must contain a dot with a non-empty [A-Za-z0-9_] extension after+// it, and everything before that dot must be in the class. The class is+// ASCII-only, so "/文件.js" and "/café.css" are NOT ignored and do get the+// index.html fallback.+func looksLikeFile(pathname string) bool {+ slash := strings.LastIndexByte(pathname, '/')+ if slash < 0 {+ return false+ }+ segment := pathname[slash+1:]+ dot := strings.LastIndexByte(segment, '.')+ if dot <= 0 || dot == len(segment)-1 {+ return false+ }+ for _, character := range segment[:dot] { // [A-Za-z\s\d~$._-]+ switch {+ case character >= 'A' && character <= 'Z',+ character >= 'a' && character <= 'z',+ character >= '0' && character <= '9',+ character == '~', character == '$', character == '.',+ character == '_', character == '-',+ // URL paths are percent-decoded before this test, so a non-ASCII+ // space can genuinely reach it; protocol owns the JavaScript+ // whitespace class.+ protocol.IsJSWhitespace(character):+ default:+ return false+ }+ }+ for _, character := range segment[dot+1:] { // \w++ switch {+ case character >= 'A' && character <= 'Z',+ character >= 'a' && character <= 'z',+ character >= '0' && character <= '9',+ character == '_':+ default:+ return false+ }+ }+ return true+}diff --git a/internal/server/app/static_test.go b/internal/server/app/static_test.gonew file mode 100644index 00000000..f769732a--- /dev/null+++ b/internal/server/app/static_test.go@@ -0,0 +1,227 @@+package app++import (+ "bytes"+ "io"+ "io/fs"+ "net/http"+ "net/http/httptest"+ "testing"+ "testing/fstest"+)++const staticNotFoundBody = `{"error":"Not found"}`++// staticNotFound is app.ts's `sendJson(response, 404, { error: "Not found" })`,+// the next() callback sirv fell through to.+var staticNotFound = http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {+ writer.Header().Set("Content-Type", "application/json; charset=utf-8")+ writer.WriteHeader(http.StatusNotFound)+ io.WriteString(writer, staticNotFoundBody)+})++// staticFixture mirrors the tree evidence/runtime.md served through real+// [email protected], byte lengths included, so the parity table below is comparable.+func staticFixture() fs.FS {+ filled := func(size int) *fstest.MapFile {+ return &fstest.MapFile{Data: bytes.Repeat([]byte("x"), size)}+ }+ return fstest.MapFS{+ "index.html": filled(100),+ "assets/app.js": filled(20),+ "assets/app.css": filled(15),+ "third-party-licenses.txt": filled(21),+ "favicon.svg": filled(41),+ "fonts/inter.woff2": filled(300),+ "manifest.webmanifest": filled(19),+ "data.json": filled(7),+ "nomime.bin": filled(64),+ "noext": filled(23),+ ".gitkeep": filled(0),+ ".vite/manifest.json": filled(7),+ ".well-known/x.txt": filled(10),+ }+}++// TestStaticHandlerMatchesSirv replays the 26-row parity table measured against+// [email protected] in evidence/runtime.md section 4.4.+func TestStaticHandlerMatchesSirv(t *testing.T) {+ handler := staticHandler(staticFixture(), staticNotFound)++ const html = "text/html;charset=utf-8"+ for _, testCase := range []struct {+ method string+ path string+ headerName string+ headerValue string+ status int+ contentType string+ contentLength string+ contentRange string+ bodyLength int+ }{+ {method: "GET", path: "/", status: 200, contentType: html, contentLength: "100", bodyLength: 100},+ {method: "GET", path: "/index.html", status: 200, contentType: html, contentLength: "100", bodyLength: 100},+ {method: "GET", path: "/host", status: 200, contentType: html, contentLength: "100", bodyLength: 100},+ {method: "GET", path: "/room/1234", status: 200, contentType: html, contentLength: "100", bodyLength: 100},+ {method: "GET", path: "/assets/app.js", status: 200, contentType: "text/javascript", contentLength: "20", bodyLength: 20},+ {method: "GET", path: "/assets/app.css", status: 200, contentType: "text/css", contentLength: "15", bodyLength: 15},+ {method: "GET", path: "/third-party-licenses.txt", status: 200, contentType: "text/plain", contentLength: "21", bodyLength: 21},+ {method: "GET", path: "/favicon.svg", status: 200, contentType: "image/svg+xml", contentLength: "41", bodyLength: 41},+ {method: "GET", path: "/fonts/inter.woff2", status: 200, contentType: "font/woff2", contentLength: "300", bodyLength: 300},+ {method: "GET", path: "/manifest.webmanifest", status: 200, contentType: "application/manifest+json", contentLength: "19", bodyLength: 19},+ {method: "GET", path: "/data.json", status: 200, contentType: "application/json", contentLength: "7", bodyLength: 7},+ {method: "GET", path: "/nomime.bin", status: 200, contentType: "application/octet-stream", contentLength: "64", bodyLength: 64},+ // mrmime knows no extension here, so sirv sends an empty Content-Type.+ {method: "GET", path: "/noext", status: 200, contentType: "", contentLength: "23", bodyLength: 23},+ {method: "GET", path: "/assets/missing.js", status: 404, contentType: "application/json; charset=utf-8", bodyLength: len(staticNotFoundBody)},+ {method: "GET", path: "/missing.css", status: 404, contentType: "application/json; charset=utf-8", bodyLength: len(staticNotFoundBody)},+ {method: "GET", path: "/.well-known/x.txt", status: 200, contentType: "text/plain", contentLength: "10", bodyLength: 10},+ // The dotfile is not in sirv's FILES and does not match the "any extn"+ // ignore, so it falls back to index.html.+ {method: "GET", path: "/.gitkeep", status: 200, contentType: html, contentLength: "100", bodyLength: 100},+ {method: "GET", path: "/.vite/manifest.json", status: 404, contentType: "application/json; charset=utf-8", bodyLength: len(staticNotFoundBody)},+ {method: "GET", path: "/assets", status: 200, contentType: html, contentLength: "100", bodyLength: 100},+ {method: "GET", path: "/assets/", status: 200, contentType: html, contentLength: "100", bodyLength: 100},+ {method: "HEAD", path: "/index.html", status: 200, contentType: html, contentLength: "100", bodyLength: 0},+ {+ method: "GET", path: "/index.html", headerName: "Range", headerValue: "bytes=0-9",+ status: 206, contentType: html, contentLength: "10", contentRange: "bytes 0-9/100", bodyLength: 10,+ },+ {+ method: "GET", path: "/index.html", headerName: "Accept", headerValue: "application/json",+ status: 200, contentType: html, contentLength: "100", bodyLength: 100,+ },+ {method: "GET", path: "/../go.mod", status: 404, contentType: "application/json; charset=utf-8", bodyLength: len(staticNotFoundBody)},+ // sirv ignores req.method entirely; app.ts routes /api/** first.+ {method: "POST", path: "/", status: 200, contentType: html, contentLength: "100", bodyLength: 100},+ // The "any extn" class is ASCII-only, so this is not ignored.+ {method: "GET", path: "/文件.js", status: 200, contentType: html, contentLength: "100", bodyLength: 100},+ } {+ request := httptest.NewRequest(testCase.method, testCase.path, nil)+ if testCase.headerName != "" {+ request.Header.Set(testCase.headerName, testCase.headerValue)+ }+ recorder := httptest.NewRecorder()+ handler.ServeHTTP(recorder, request)++ label := testCase.method + " " + testCase.path+ if recorder.Code != testCase.status {+ t.Errorf("%s: status = %d, want %d", label, recorder.Code, testCase.status)+ }+ contentType, present := recorder.Header()["Content-Type"]+ if !present {+ t.Errorf("%s: Content-Type header is absent", label)+ } else if len(contentType) != 1 || contentType[0] != testCase.contentType {+ t.Errorf("%s: Content-Type = %q, want [%q]", label, contentType, testCase.contentType)+ }+ if got := recorder.Header().Get("Content-Length"); testCase.contentLength != "" && got != testCase.contentLength {+ t.Errorf("%s: Content-Length = %q, want %q", label, got, testCase.contentLength)+ }+ if got := recorder.Header().Get("Content-Range"); got != testCase.contentRange {+ t.Errorf("%s: Content-Range = %q, want %q", label, got, testCase.contentRange)+ }+ if got := recorder.Body.Len(); got != testCase.bodyLength {+ t.Errorf("%s: body length = %d, want %d", label, got, testCase.bodyLength)+ }+ // sirv never emits either, and a fabricated Last-Modified would add+ // 304 responses Node never sent.+ if got := recorder.Header().Get("Last-Modified"); got != "" {+ t.Errorf("%s: unexpected Last-Modified %q", label, got)+ }+ if got := recorder.Header().Get("Cache-Control"); got != "" {+ t.Errorf("%s: unexpected Cache-Control %q", label, got)+ }+ if got := recorder.Header().Get("Etag"); got != "" {+ t.Errorf("%s: unexpected ETag %q", label, got)+ }+ // app.ts setHeaders runs for served files only, not for the JSON 404.+ wantSecurityHeaders := testCase.status != http.StatusNotFound+ for header, want := range map[string]string{+ "X-Content-Type-Options": "nosniff",+ "Referrer-Policy": "no-referrer",+ } {+ got := recorder.Header().Get(header)+ if wantSecurityHeaders && got != want {+ t.Errorf("%s: %s = %q, want %q", label, header, got, want)+ }+ if !wantSecurityHeaders && got != "" {+ t.Errorf("%s: unexpected %s %q on the 404", label, header, got)+ }+ }+ }+}++func TestStaticHandlerRefusesTraversal(t *testing.T) {+ handler := staticHandler(staticFixture(), staticNotFound)++ for _, target := range []string{+ "/../go.mod", "/../../go.mod", "/assets/../../go.mod",+ "/..%2fgo.mod", "/./../package.json", "//../go.mod",+ } {+ recorder := httptest.NewRecorder()+ handler.ServeHTTP(recorder, httptest.NewRequest("GET", target, nil))+ if recorder.Code != http.StatusNotFound {+ t.Errorf("GET %s: status = %d, want 404", target, recorder.Code)+ }+ }+}++func TestStaticHandlerWithoutIndexHTML(t *testing.T) {+ // The former frontend mode "none": nothing can be served, everything 404s.+ handler := staticHandler(fstest.MapFS{".gitkeep": &fstest.MapFile{}}, staticNotFound)++ for _, target := range []string{"/", "/host", "/assets/app.js", "/.gitkeep"} {+ recorder := httptest.NewRecorder()+ handler.ServeHTTP(recorder, httptest.NewRequest("GET", target, nil))+ if recorder.Code != http.StatusNotFound {+ t.Errorf("GET %s: status = %d, want 404", target, recorder.Code)+ }+ }+}++// TestLooksLikeFileMatchesSirvIgnore replays the Node oracle for sirv's+// "any extn" ignore recorded in evidence/runtime.md section 4.1.+func TestLooksLikeFileMatchesSirvIgnore(t *testing.T) {+ for pathname, want := range map[string]bool{+ "/": false,+ "/host": false,+ "/room/1234": false,+ "/assets": false,+ "/assets/": false,+ "/index.html": true,+ "/assets/index-abc123.js": true,+ "/a.b.c.js": true,+ "/favicon.ico": true,+ "/my file.txt": true,+ "/.gitkeep": false,+ "/x.": false,+ "/.env": false,+ "/a.b-c": false,+ "/文件.js": false,+ "/café.css": false,+ "/v1.2/thing": false,+ } {+ if got := looksLikeFile(pathname); got != want {+ t.Errorf("looksLikeFile(%q) = %v, want %v", pathname, got, want)+ }+ }+}++func TestHasDotSegment(t *testing.T) {+ for name, want := range map[string]bool{+ "index.html": false,+ "assets/app.js": false,+ ".gitkeep": true,+ ".vite/manifest.json": true,+ "assets/.hidden": true,+ ".well-known/x.txt": false,+ "deep/.well-known/x.txt": false,+ "well-known/x.txt": false,+ ".well-knownish/file.txt": true,+ } {+ if got := hasDotSegment(name); got != want {+ t.Errorf("hasDotSegment(%q) = %v, want %v", name, got, want)+ }+ }+}diff --git a/internal/server/config/config.go b/internal/server/config/config.gonew file mode 100644index 00000000..8f38a2c5--- /dev/null+++ b/internal/server/config/config.go@@ -0,0 +1,538 @@+// Package config ports src/server/config.ts, src/server/local-config.ts and+// src/server/ice.ts: the Hosted environment contract, the Client's local+// composition, and the ICE configuration derived from either. It performs no+// I/O; the caller supplies the environment as a map.+package config++import (+ "errors"+ "fmt"+ "math"+ "net/url"+ "path/filepath"+ "regexp"+ "strconv"+ "strings"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// Environment ports RuntimeEnvironment. DECISIONS D8 renames NODE_ENV to+// SCREENER_ENV and drops "test".+type Environment string++// The two accepted SCREENER_ENV values.+const (+ EnvironmentDevelopment Environment = "development"+ EnvironmentProduction Environment = "production"+)++// Bounds and defaults from src/server/config.ts.+const (+ minSiteAccessPasswordBytes = 8+ maxSiteAccessPasswordBytes = 128+ minLiveKitAPISecretBytes = 32+ defaultMaxViewersPerRoom = 8+ defaultRoomLeaseSeconds = 86_400+ defaultPort = 8787+ maxPort = 65_535+)++// VISIBLE_ASCII_PATTERN.+var visibleASCIIPattern = regexp.MustCompile(`^[\x21-\x7e]+$`)++const removedTurnReason = "ordinary ICE accepts STUN_URLS only"++// removedEnvironmentVariables ports REMOVED_ENVIRONMENT_VARIABLES together with+// the two names the TypeScript checked separately, and NODE_ENV (DECISIONS D8:+// a stale unit file must not fail open). An empty reason takes the TURN default.+// The order is the report order when several removed names are present.+var removedEnvironmentVariables = []struct{ name, reason string }{+ {"TURN_URLS", ""},+ {"TURN_SHARED_SECRET", ""},+ {"TURN_CREDENTIAL_TTL_SECONDS", ""},+ {"PEER_ICE_TURN_URLS", ""},+ {"PEER_ICE_TURN_SHARED_SECRET", ""},+ {"PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS", ""},+ {"SELECTED_EDGE_TURN_URLS", ""},+ {"SELECTED_EDGE_TURN_SHARED_SECRET", ""},+ {"SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS", ""},+ {"SELECTED_EDGE_TURN_ALLOCATION_CAPACITY", ""},+ {"PEER_ASSISTED_ROOM_IDS", "peer-assisted media applies to every room"},+ {"PEER_ASSISTED_MEDIA", "peer-assisted media is always enabled"},+ {"HOST_ADMISSION_PASSWORD", "use SITE_ACCESS_PASSWORD"},+ {"MAX_PEER_RELAY_DOWNSTREAM_EDGES", "use ENDPOINT_MEDIA_COPY_CAPACITY"},+ {"ROOM_TTL_SECONDS", "use ROOM_LEASE_SECONDS"},+ {"ACCESS_PASSWORD", "use SITE_ACCESS_PASSWORD"},+ {"NODE_ENV", "use SCREENER_ENV"},+}++// LiveKitFallback ports LiveKitFallbackConfig. URL and APIURL are serialised+// WHATWG origins.+type LiveKitFallback struct {+ URL string+ APIURL string+ APIKey string+ APISecret string+}++// Config ports ServerConfig. Fields the TypeScript left `undefined` are the+// zero value here: an empty SiteAccessPassword means site access is open, an+// empty RoomDatabasePath means memory mode, and a nil LiveKit means no SFU+// fallback.+type Config struct {+ Env Environment+ Port int+ ListenHost string+ PublicBaseURL *url.URL+ // AllowedOrigins is a membership test only; Go map order is not observable+ // here (src/server/app.ts only ever calls `allowedOrigins.has(origin)`).+ AllowedOrigins map[string]struct{}+ SiteAccessPassword string+ RoomDatabasePath string+ RoomLeaseMs int64+ MaxViewersPerRoom int+ EndpointMediaCopyCapacity int+ LiveKit *LiveKitFallback+ STUNURLs []string+ NATPredictionEnabled bool+ // NATPredictionSTUNURLs is nil where the TypeScript left it `undefined`,+ // which IceConfig distinguishes from a configured empty list.+ NATPredictionSTUNURLs []string+}++// Load ports loadConfig. env is the whole process environment: cmd passes+// os.Environ() as a map, tests pass a literal. A key present with an empty+// value is `""` in TypeScript too, so presence is the only distinction that+// needs the two-value lookup.+func Load(env map[string]string) (Config, error) {+ for _, removed := range removedEnvironmentVariables {+ if _, present := env[removed.name]; present {+ reason := removed.reason+ if reason == "" {+ reason = removedTurnReason+ }+ return Config{}, fmt.Errorf("%s is no longer supported; %s", removed.name, reason)+ }+ }++ environment, err := parseEnvironment(env)+ if err != nil {+ return Config{}, err+ }+ port, err := parsePositiveInteger(env["PORT"], defaultPort, "PORT")+ if err != nil {+ return Config{}, err+ }+ if port > maxPort {+ return Config{}, fmt.Errorf("PORT must be at most %d", maxPort)+ }+ listenHost := strings.TrimFunc(env["LISTEN_HOST"], protocol.IsJSWhitespace)+ if listenHost == "" {+ listenHost = "0.0.0.0"+ }++ // TS: environment.PUBLIC_BASE_URL ?? `http://localhost:${port}` — only an+ // absent variable takes the default.+ rawPublicBaseURL, present := env["PUBLIC_BASE_URL"]+ if !present {+ rawPublicBaseURL = fmt.Sprintf("http://localhost:%d", port)+ }+ publicBaseURL, err := parseOriginURL(rawPublicBaseURL, "PUBLIC_BASE_URL", "http", "https")+ if err != nil {+ return Config{}, err+ }+ if environment == EnvironmentProduction && publicBaseURL.Scheme != "https" {+ return Config{}, errors.New("PUBLIC_BASE_URL must use https in production")+ }++ siteAccessPassword := env["SITE_ACCESS_PASSWORD"]+ roomDatabasePath, err := parseRoomDatabasePath(env["ROOM_DATABASE_PATH"])+ if err != nil {+ return Config{}, err+ }+ stunURLs, err := parseStunURLList(env["STUN_URLS"], "STUN_URLS")+ if err != nil {+ return Config{}, err+ }+ natPredictionEnabled, err := parseBoolean(env["NAT_PREDICTION_ENABLED"], "NAT_PREDICTION_ENABLED")+ if err != nil {+ return Config{}, err+ }+ if natPredictionEnabled && len(NATPredictionStunURLs(stunURLs)) == 0 {+ return Config{}, errors.New("NAT_PREDICTION_ENABLED requires a STUN_URLS entry on UDP 3478")+ }+ if natPredictionEnabled &&+ len(stunURLs)+protocol.MaxNatPredictionAuxiliaryStunURLs > protocol.MaxIceServerURLs {+ return Config{}, fmt.Errorf(+ "STUN_URLS must contain at most %d URLs when NAT_PREDICTION_ENABLED=true",+ protocol.MaxIceServerURLs-protocol.MaxNatPredictionAuxiliaryStunURLs)+ }+ maxViewersPerRoom, err := parseBoundedInteger(env["MAX_VIEWERS_PER_ROOM"],+ defaultMaxViewersPerRoom, "MAX_VIEWERS_PER_ROOM", 1, protocol.MaxViewersPerRoomLimit)+ if err != nil {+ return Config{}, err+ }+ endpointMediaCopyCapacity, err := parseBoundedInteger(env["ENDPOINT_MEDIA_COPY_CAPACITY"],+ protocol.DefaultEndpointMediaCopyCapacity, "ENDPOINT_MEDIA_COPY_CAPACITY",+ 1, protocol.MaxEndpointMediaCopyCapacity)+ if err != nil {+ return Config{}, err+ }+ liveKit, err := parseLiveKitFallback(env, environment)+ if err != nil {+ return Config{}, err+ }++ secrets := make([]string, 0, 3)+ if siteAccessPassword != "" {+ secrets = append(secrets, siteAccessPassword)+ }+ if liveKit != nil {+ secrets = append(secrets, liveKit.APIKey, liveKit.APISecret)+ }+ distinct := make(map[string]struct{}, len(secrets))+ for _, secret := range secrets {+ distinct[secret] = struct{}{}+ }+ if len(distinct) != len(secrets) {+ return Config{}, errors.New(+ "SITE_ACCESS_PASSWORD, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must use independent values")+ }+ // Buffer.byteLength is the UTF-8 length, which is len() in Go. The pattern+ // already restricts the value to one byte per character.+ if siteAccessPassword != "" &&+ (!visibleASCIIPattern.MatchString(siteAccessPassword) ||+ len(siteAccessPassword) < minSiteAccessPasswordBytes ||+ len(siteAccessPassword) > maxSiteAccessPasswordBytes) {+ return Config{}, fmt.Errorf("SITE_ACCESS_PASSWORD must contain %d to %d visible ASCII bytes",+ minSiteAccessPasswordBytes, maxSiteAccessPasswordBytes)+ }+ if environment == EnvironmentProduction && siteAccessPassword == "" {+ return Config{}, errors.New("SITE_ACCESS_PASSWORD is required in production")+ }+ if environment == EnvironmentProduction && len(stunURLs) == 0 {+ return Config{}, errors.New("STUN is required in production")+ }++ // ALLOWED_ORIGINS and ROOM_LEASE_SECONDS are validated inside the returned+ // object literal, i.e. after every check above; keep that order.+ allowedOrigins, err := parseOrigins(env["ALLOWED_ORIGINS"], Origin(publicBaseURL))+ if err != nil {+ return Config{}, err+ }+ roomLeaseSeconds, err := parsePositiveInteger(env["ROOM_LEASE_SECONDS"],+ defaultRoomLeaseSeconds, "ROOM_LEASE_SECONDS")+ if err != nil {+ return Config{}, err+ }++ return Config{+ Env: environment,+ Port: int(port),+ ListenHost: listenHost,+ PublicBaseURL: publicBaseURL,+ AllowedOrigins: allowedOrigins,+ SiteAccessPassword: siteAccessPassword,+ RoomDatabasePath: roomDatabasePath,+ RoomLeaseMs: roomLeaseSeconds * 1_000,+ MaxViewersPerRoom: int(maxViewersPerRoom),+ EndpointMediaCopyCapacity: int(endpointMediaCopyCapacity),+ LiveKit: liveKit,+ STUNURLs: stunURLs,+ NATPredictionEnabled: natPredictionEnabled,+ }, nil+}++// parseEnvironment ports parseEnvironment for SCREENER_ENV.+func parseEnvironment(env map[string]string) (Environment, error) {+ // TS: value ?? "development" — a present empty value is not nullish and so+ // reaches the check below.+ value, present := env["SCREENER_ENV"]+ if !present {+ return EnvironmentDevelopment, nil+ }+ switch Environment(value) {+ case EnvironmentDevelopment, EnvironmentProduction:+ return Environment(value), nil+ }+ return "", errors.New("SCREENER_ENV must be development or production")+}++// parseBoolean ports parseBoolean; every caller used a false fallback.+func parseBoolean(value string, name string) (bool, error) {+ switch value {+ case "", "false":+ return false, nil+ case "true":+ return true, nil+ }+ return false, fmt.Errorf("%s must be true or false", name)+}++// parsePositiveInteger ports parsePositiveInteger, including Number.isSafeInteger.+func parsePositiveInteger(value string, fallback int64, name string) (int64, error) {+ if value == "" {+ return fallback, nil+ }+ number, ok := jsNumber(value)+ if !ok || number != math.Trunc(number) || number <= 0 || number > protocol.MaxSafeInteger {+ return 0, fmt.Errorf("%s must be a positive integer", name)+ }+ return int64(number), nil+}++// parseBoundedInteger ports parseBoundedInteger.+func parseBoundedInteger(value string, fallback int64, name string, minimum, maximum int64) (int64, error) {+ parsed, err := parsePositiveInteger(value, fallback, name)+ if err != nil {+ return 0, err+ }+ if parsed < minimum || parsed > maximum {+ return 0, fmt.Errorf("%s must be between %d and %d", name, minimum, maximum)+ }+ return parsed, nil+}++// parseRoomDatabasePath ports parseRoomDatabasePath. DECISIONS D8: absoluteness+// is filepath.IsAbs, which differs from Node's path.isAbsolute on Windows,+// where "/var/lib/screener/rooms.sqlite" is relative to the current volume and+// is therefore rejected here. Hosted runs on Linux.+func parseRoomDatabasePath(value string) (string, error) {+ path := strings.TrimFunc(value, protocol.IsJSWhitespace)+ if path == "" {+ return "", nil+ }+ if path == ":memory:" || strings.ContainsRune(path, 0) || !filepath.IsAbs(path) {+ return "", errors.New("ROOM_DATABASE_PATH must be an absolute file path")+ }+ return path, nil+}++// parseLiveKitFallback ports parseLiveKitFallback.+func parseLiveKitFallback(env map[string]string, environment Environment) (*LiveKitFallback, error) {+ rawURL := strings.TrimFunc(env["LIVEKIT_URL"], protocol.IsJSWhitespace)+ rawAPIURL := strings.TrimFunc(env["LIVEKIT_API_URL"], protocol.IsJSWhitespace)+ apiKey := strings.TrimFunc(env["LIVEKIT_API_KEY"], protocol.IsJSWhitespace)+ apiSecret := strings.TrimFunc(env["LIVEKIT_API_SECRET"], protocol.IsJSWhitespace)++ configured := 0+ for _, value := range []string{rawURL, rawAPIURL, apiKey, apiSecret} {+ if value != "" {+ configured+++ }+ }+ if configured == 0 {+ return nil, nil+ }+ if configured != 4 {+ return nil, errors.New(+ "LIVEKIT_URL, LIVEKIT_API_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must be configured together")+ }+ if len(apiSecret) < minLiveKitAPISecretBytes {+ return nil, fmt.Errorf("LIVEKIT_API_SECRET must contain at least %d bytes", minLiveKitAPISecretBytes)+ }++ parsedURL, err := parseOriginURL(rawURL, "LIVEKIT_URL", "ws", "wss")+ if err != nil {+ return nil, err+ }+ if environment == EnvironmentProduction && parsedURL.Scheme != "wss" {+ return nil, errors.New("LIVEKIT_URL must use wss in production")+ }+ parsedAPIURL, err := parseOriginURL(rawAPIURL, "LIVEKIT_API_URL", "http", "https")+ if err != nil {+ return nil, err+ }+ if environment == EnvironmentProduction && parsedAPIURL.Scheme != "https" &&+ !isLoopbackHostname(parsedAPIURL.Hostname()) {+ return nil, errors.New("LIVEKIT_API_URL must use https or loopback in production")+ }+ return &LiveKitFallback{+ URL: Origin(parsedURL),+ APIURL: Origin(parsedAPIURL),+ APIKey: apiKey,+ APISecret: apiSecret,+ }, nil+}++// isLoopbackHostname ports isLoopbackHostname. url.URL.Hostname strips the IPv6+// brackets, so only the unbracketed "::1" can actually match here.+func isLoopbackHostname(hostname string) bool {+ return hostname == "localhost" || hostname == "127.0.0.1" ||+ hostname == "[::1]" || hostname == "::1"+}++// parseURLList ports parseUrlList.+func parseURLList(value string, name string) ([]string, error) {+ if strings.TrimFunc(value, protocol.IsJSWhitespace) == "" {+ return nil, nil+ }+ entries := strings.Split(value, ",")+ list := make([]string, 0, len(entries))+ for _, entry := range entries {+ trimmed := strings.TrimFunc(entry, protocol.IsJSWhitespace)+ if trimmed == "" {+ return nil, fmt.Errorf("%s contains an empty URL", name)+ }+ list = append(list, trimmed)+ }+ return list, nil+}++// parseStunURLList ports parseStunUrlList. The TypeScript `maximum` parameter+// was only ever the default.+func parseStunURLList(value string, name string) ([]string, error) {+ values, err := parseURLList(value, name)+ if err != nil {+ return nil, err+ }+ if len(values) > protocol.MaxIceServerURLs {+ return nil, fmt.Errorf("%s must contain at most %d URLs", name, protocol.MaxIceServerURLs)+ }+ for _, value := range values {+ if !protocol.ValidStunURLValue(value) {+ return nil, fmt.Errorf("%s contains an invalid STUN URL", name)+ }+ }+ return values, nil+}++// parseOrigins ports parseOrigins.+func parseOrigins(value string, fallback string) (map[string]struct{}, error) {+ origins, err := parseURLList(value, "ALLOWED_ORIGINS")+ if err != nil {+ return nil, err+ }+ if len(origins) == 0 {+ origins = []string{fallback}+ }+ set := make(map[string]struct{}, len(origins))+ for _, entry := range origins {+ origin, err := toOrigin(entry)+ if err != nil {+ return nil, err+ }+ set[origin] = struct{}{}+ }+ return set, nil+}++// toOrigin ports toOrigin. The TypeScript let an unparsable entry escape as a+// raw TypeError from `new URL`; it fails startup here with a message instead.+func toOrigin(value string) (string, error) {+ parsed, err := url.Parse(value)+ if err != nil || parsed.Scheme == "" || parsed.Host == "" {+ return "", errors.New("Allowed origins must be valid http or https URLs")+ }+ if parsed.Scheme != "http" && parsed.Scheme != "https" {+ return "", errors.New("Allowed origins must use http or https")+ }+ return Origin(parsed), nil+}++// parseOriginURL ports the `new URL` + protocol + shape ladder that+// PUBLIC_BASE_URL, LIVEKIT_URL and LIVEKIT_API_URL each repeat, and returns the+// WHATWG-normalised URL (lowercase host, default port removed, path "/").+func parseOriginURL(value, name, scheme, alternative string) (*url.URL, error) {+ parsed, err := url.Parse(value)+ // net/url accepts relative references and opaque URLs that the WHATWG+ // parser rejects (or, for "wss:host", repairs); require both parts.+ if err != nil || parsed.Scheme == "" || parsed.Host == "" {+ return nil, fmt.Errorf("%s must be a valid %s or %s origin", name, scheme, alternative)+ }+ if parsed.Scheme != scheme && parsed.Scheme != alternative {+ return nil, fmt.Errorf("%s must use %s or %s", name, scheme, alternative)+ }+ // TS: url.username || url.password || url.pathname !== "/" || url.search ||+ // url.hash. WHATWG reports "/" for an empty path, which net/url leaves "".+ if hasUserinfo(parsed) || (parsed.Path != "" && parsed.Path != "/") ||+ parsed.RawQuery != "" || parsed.Fragment != "" {+ return nil, fmt.Errorf(+ "%s must be an origin without credentials, path, query, or fragment", name)+ }+ return &url.URL{Scheme: parsed.Scheme, Host: normalizedHost(parsed), Path: "/"}, nil+}++// hasUserinfo ports `url.username || url.password`: WHATWG reports empty+// strings for "https://@host" and "https://:@host", where net/url reports a+// non-nil (but empty) Userinfo.+func hasUserinfo(parsed *url.URL) bool {+ if parsed.User == nil {+ return false+ }+ password, _ := parsed.User.Password()+ return parsed.User.Username() != "" || password != ""+}++// Origin ports the WHATWG URL `origin` getter for the http/https/ws/wss schemes+// this package accepts: new URL("https://Example.com:443/").origin is+// "https://example.com". It is exported so app and cmd can compare request+// origins without a second copy of the rule.+func Origin(parsed *url.URL) string {+ return parsed.Scheme + "://" + normalizedHost(parsed)+}++// normalizedHost lowercases the host, keeps an IPv6 literal bracketed and drops+// a port equal to the scheme default. Non-ASCII hosts are not IDNA-encoded, so+// they keep the form they were configured with.+func normalizedHost(parsed *url.URL) string {+ host := strings.ToLower(parsed.Hostname())+ if strings.Contains(host, ":") {+ host = "[" + host + "]"+ }+ // WHATWG parses the port as a number, so "0443" and "443" are both default.+ if number, err := strconv.Atoi(parsed.Port()); err == nil {+ if port := strconv.Itoa(number); port != defaultSchemePort(parsed.Scheme) {+ host += ":" + port+ }+ }+ return host+}++func defaultSchemePort(scheme string) string {+ switch scheme {+ case "http", "ws":+ return "80"+ case "https", "wss":+ return "443"+ }+ return ""+}++// decimalNumberPattern is the StrDecimalLiteral grammar Number(string) accepts.+var decimalNumberPattern = regexp.MustCompile(+ `^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$`)++// jsNumber ports Number(string). The second result is false where JavaScript+// yields NaN; values JavaScript renders as Infinity are reported as NaN too,+// because every caller rejects them through Number.isSafeInteger anyway.+func jsNumber(value string) (float64, bool) {+ text := strings.TrimFunc(value, protocol.IsJSWhitespace)+ if text == "" {+ return 0, true // Number("") and Number(" ") are 0.+ }+ if len(text) > 2 && text[0] == '0' {+ if base := numericBase(text[1]); base != 0 {+ number, err := strconv.ParseUint(text[2:], base, 64)+ return float64(number), err == nil+ }+ }+ if !decimalNumberPattern.MatchString(text) {+ return 0, false+ }+ number, err := strconv.ParseFloat(text, 64)+ return number, err == nil+}++func numericBase(marker byte) int {+ switch marker {+ case 'x', 'X':+ return 16+ case 'o', 'O':+ return 8+ case 'b', 'B':+ return 2+ }+ return 0+}diff --git a/internal/server/config/config_test.go b/internal/server/config/config_test.gonew file mode 100644index 00000000..ee6ebf1f--- /dev/null+++ b/internal/server/config/config_test.go@@ -0,0 +1,558 @@+package config++import (+ "fmt"+ "maps"+ "path/filepath"+ "reflect"+ "slices"+ "strconv"+ "strings"+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// Ported from tests/server-config.test.ts.++// env merges the given maps, later keys winning, so a case can extend a base.+func env(parts ...map[string]string) map[string]string {+ merged := map[string]string{}+ for _, part := range parts {+ maps.Copy(merged, part)+ }+ return merged+}++var (+ liveKitAdmission = map[string]string{"LIVEKIT_API_URL": "https://livekit-api.test"}+ liveKitSecret = strings.Repeat("s", 32)+ productionBase = map[string]string{+ "SCREENER_ENV": "production",+ "PUBLIC_BASE_URL": "https://share.test",+ "SITE_ACCESS_PASSWORD": "host-password-12",+ "STUN_URLS": "stun:stun.test:3478",+ }+)++func stunList(count int, prefix string) string {+ urls := make([]string, 0, count)+ for index := range count {+ urls = append(urls, fmt.Sprintf("stun:%s-%d.test:3478", prefix, index))+ }+ return strings.Join(urls, ",")+}++func mustLoad(t *testing.T, environment map[string]string) Config {+ t.Helper()+ config, err := Load(environment)+ if err != nil {+ t.Fatalf("Load: unexpected error %v", err)+ }+ return config+}++func TestLoadDevelopmentDefaults(t *testing.T) {+ config := mustLoad(t, map[string]string{"SCREENER_ENV": "development", "PORT": "9123"})++ if config.Env != EnvironmentDevelopment {+ t.Errorf("Env = %q", config.Env)+ }+ if config.ListenHost != "0.0.0.0" {+ t.Errorf("ListenHost = %q", config.ListenHost)+ }+ if got := config.PublicBaseURL.String(); got != "http://localhost:9123/" {+ t.Errorf("PublicBaseURL = %q", got)+ }+ want := map[string]struct{}{"http://localhost:9123": {}}+ if !reflect.DeepEqual(config.AllowedOrigins, want) {+ t.Errorf("AllowedOrigins = %v", config.AllowedOrigins)+ }+ if config.RoomDatabasePath != "" {+ t.Errorf("RoomDatabasePath = %q", config.RoomDatabasePath)+ }+ if len(config.STUNURLs) != 0 {+ t.Errorf("STUNURLs = %v", config.STUNURLs)+ }+ if config.NATPredictionEnabled {+ t.Error("NATPredictionEnabled = true")+ }+ if config.NATPredictionSTUNURLs != nil {+ t.Errorf("NATPredictionSTUNURLs = %v, want nil (TS left it undefined)", config.NATPredictionSTUNURLs)+ }+ if config.MaxViewersPerRoom != 8 {+ t.Errorf("MaxViewersPerRoom = %d", config.MaxViewersPerRoom)+ }+ if config.EndpointMediaCopyCapacity != 2 {+ t.Errorf("EndpointMediaCopyCapacity = %d", config.EndpointMediaCopyCapacity)+ }+ if config.LiveKit != nil {+ t.Errorf("LiveKit = %+v", config.LiveKit)+ }+ if config.RoomLeaseMs != 86_400_000 {+ t.Errorf("RoomLeaseMs = %d", config.RoomLeaseMs)+ }+ if config.SiteAccessPassword != "" {+ t.Error("SiteAccessPassword is set")+ }+}++func TestLoadLiveKitTuple(t *testing.T) {+ config := mustLoad(t, map[string]string{+ "LIVEKIT_URL": " ws://livekit.test:7880 ",+ "LIVEKIT_API_URL": " http://livekit.test:7880 ",+ "LIVEKIT_API_KEY": " test-key ",+ "LIVEKIT_API_SECRET": " " + liveKitSecret + " ",+ })+ want := LiveKitFallback{+ URL: "ws://livekit.test:7880",+ APIURL: "http://livekit.test:7880",+ APIKey: "test-key",+ APISecret: liveKitSecret,+ }+ if config.LiveKit == nil || *config.LiveKit != want {+ t.Errorf("LiveKit = %+v, want %+v", config.LiveKit, want)+ }+}++func TestLoadAccepts(t *testing.T) {+ developmentPath, err := filepath.Abs(filepath.Join("state", "rooms.sqlite"))+ if err != nil {+ t.Fatalf("Abs: %v", err)+ }+ productionPath, err := filepath.Abs(filepath.Join("production-state", "rooms.sqlite"))+ if err != nil {+ t.Fatalf("Abs: %v", err)+ }++ cases := []struct {+ name string+ env map[string]string+ check func(*testing.T, Config)+ }{+ {"default viewer limit", map[string]string{}, func(t *testing.T, c Config) {+ if c.MaxViewersPerRoom != 8 {+ t.Errorf("MaxViewersPerRoom = %d", c.MaxViewersPerRoom)+ }+ }},+ {"viewer limit lower boundary", map[string]string{"MAX_VIEWERS_PER_ROOM": "1"},+ func(t *testing.T, c Config) {+ if c.MaxViewersPerRoom != 1 {+ t.Errorf("MaxViewersPerRoom = %d", c.MaxViewersPerRoom)+ }+ }},+ {"viewer limit ceiling",+ map[string]string{"MAX_VIEWERS_PER_ROOM": strconv.Itoa(protocol.MaxViewersPerRoomLimit)},+ func(t *testing.T, c Config) {+ if c.MaxViewersPerRoom != protocol.MaxViewersPerRoomLimit {+ t.Errorf("MaxViewersPerRoom = %d", c.MaxViewersPerRoom)+ }+ }},+ {"copy capacity 1", map[string]string{"ENDPOINT_MEDIA_COPY_CAPACITY": "1"},+ func(t *testing.T, c Config) {+ if c.EndpointMediaCopyCapacity != 1 {+ t.Errorf("EndpointMediaCopyCapacity = %d", c.EndpointMediaCopyCapacity)+ }+ }},+ {"copy capacity 2", map[string]string{"ENDPOINT_MEDIA_COPY_CAPACITY": "2"},+ func(t *testing.T, c Config) {+ if c.EndpointMediaCopyCapacity != 2 {+ t.Errorf("EndpointMediaCopyCapacity = %d", c.EndpointMediaCopyCapacity)+ }+ }},+ {"copy capacity 3", map[string]string{"ENDPOINT_MEDIA_COPY_CAPACITY": "3"},+ func(t *testing.T, c Config) {+ if c.EndpointMediaCopyCapacity != 3 {+ t.Errorf("EndpointMediaCopyCapacity = %d", c.EndpointMediaCopyCapacity)+ }+ }},+ {"explicit loopback listen host", map[string]string{"LISTEN_HOST": " 127.0.0.1 "},+ func(t *testing.T, c Config) {+ if c.ListenHost != "127.0.0.1" {+ t.Errorf("ListenHost = %q", c.ListenHost)+ }+ }},+ {"production STUN", productionBase, func(t *testing.T, c Config) {+ if !slices.Equal(c.STUNURLs, []string{"stun:stun.test:3478"}) {+ t.Errorf("STUNURLs = %v", c.STUNURLs)+ }+ }},+ {"production site access password",+ env(productionBase, map[string]string{"SITE_ACCESS_PASSWORD": "easy-key"}),+ func(t *testing.T, c Config) {+ if c.SiteAccessPassword != "easy-key" {+ t.Errorf("SiteAccessPassword = %q", c.SiteAccessPassword)+ }+ }},+ {"STUN-only production with LiveKit", env(productionBase, liveKitAdmission, map[string]string{+ "LIVEKIT_URL": "wss://livekit.test",+ "LIVEKIT_API_KEY": "test-key",+ "LIVEKIT_API_SECRET": liveKitSecret,+ }), func(t *testing.T, c Config) {+ if c.LiveKit == nil || c.LiveKit.URL != "wss://livekit.test" {+ t.Errorf("LiveKit = %+v", c.LiveKit)+ }+ }},+ {"production loopback LiveKit control", env(productionBase, map[string]string{+ "LIVEKIT_URL": "wss://livekit.test",+ "LIVEKIT_API_URL": "http://127.0.0.1:7880",+ "LIVEKIT_API_KEY": "test-key",+ "LIVEKIT_API_SECRET": liveKitSecret,+ }), func(t *testing.T, c Config) {+ if c.LiveKit == nil || c.LiveKit.APIURL != "http://127.0.0.1:7880" {+ t.Errorf("LiveKit = %+v", c.LiveKit)+ }+ }},+ {"uppercase STUN scheme and IPv6 host", map[string]string{"STUN_URLS": "STUN:[2001:db8::1]:3478"},+ func(t *testing.T, c Config) {+ if !slices.Equal(c.STUNURLs, []string{"STUN:[2001:db8::1]:3478"}) {+ t.Errorf("STUNURLs = %v", c.STUNURLs)+ }+ }},+ {"NAT prediction with a base listener", map[string]string{+ "STUN_URLS": "stun:share.test:3478",+ "NAT_PREDICTION_ENABLED": "true",+ }, func(t *testing.T, c Config) {+ if !c.NATPredictionEnabled {+ t.Error("NATPredictionEnabled = false")+ }+ }},+ {"room lease default", map[string]string{}, func(t *testing.T, c Config) {+ if c.RoomLeaseMs != 86_400_000 {+ t.Errorf("RoomLeaseMs = %d", c.RoomLeaseMs)+ }+ }},+ {"room lease override", map[string]string{"ROOM_LEASE_SECONDS": "3600"},+ func(t *testing.T, c Config) {+ if c.RoomLeaseMs != 3_600_000 {+ t.Errorf("RoomLeaseMs = %d", c.RoomLeaseMs)+ }+ }},+ {"file-backed room authority in development",+ map[string]string{"ROOM_DATABASE_PATH": " " + developmentPath + " "},+ func(t *testing.T, c Config) {+ if c.RoomDatabasePath != developmentPath {+ t.Errorf("RoomDatabasePath = %q", c.RoomDatabasePath)+ }+ }},+ {"blank room database path", map[string]string{"ROOM_DATABASE_PATH": ""},+ func(t *testing.T, c Config) {+ if c.RoomDatabasePath != "" {+ t.Errorf("RoomDatabasePath = %q", c.RoomDatabasePath)+ }+ }},+ {"file-backed room authority in production",+ env(productionBase, map[string]string{"ROOM_DATABASE_PATH": productionPath}),+ func(t *testing.T, c Config) {+ if c.RoomDatabasePath != productionPath {+ t.Errorf("RoomDatabasePath = %q", c.RoomDatabasePath)+ }+ }},+ {"allowed origins are normalised",+ map[string]string{"ALLOWED_ORIGINS": " https://Example.com:443/path , http://a.test:80 "},+ func(t *testing.T, c Config) {+ want := map[string]struct{}{"https://example.com": {}, "http://a.test": {}}+ if !reflect.DeepEqual(c.AllowedOrigins, want) {+ t.Errorf("AllowedOrigins = %v", c.AllowedOrigins)+ }+ }},+ // Number(string) coercion, which the TS parsers inherited.+ {"port with surrounding whitespace", map[string]string{"PORT": " 9123 "},+ func(t *testing.T, c Config) {+ if c.Port != 9123 {+ t.Errorf("Port = %d", c.Port)+ }+ }},+ {"hexadecimal port", map[string]string{"PORT": "0x1F5B"}, func(t *testing.T, c Config) {+ if c.Port != 8027 {+ t.Errorf("Port = %d", c.Port)+ }+ }},+ {"exponent room lease", map[string]string{"ROOM_LEASE_SECONDS": "1e3"},+ func(t *testing.T, c Config) {+ if c.RoomLeaseMs != 1_000_000 {+ t.Errorf("RoomLeaseMs = %d", c.RoomLeaseMs)+ }+ }},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ testCase.check(t, mustLoad(t, testCase.env))+ })+ }+}++func TestLoadRejects(t *testing.T) {+ cases := []struct {+ name string+ env map[string]string+ want string+ }{+ // Partial LiveKit credential tuples.+ {"only LiveKit URL", map[string]string{"LIVEKIT_URL": "wss://livekit.test"},+ "LIVEKIT_URL, LIVEKIT_API_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must be configured together"},+ {"only LiveKit control URL", liveKitAdmission,+ "LIVEKIT_URL, LIVEKIT_API_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must be configured together"},+ {"only LiveKit key", map[string]string{"LIVEKIT_API_KEY": "test-key"},+ "must be configured together"},+ {"only LiveKit secret", map[string]string{"LIVEKIT_API_SECRET": liveKitSecret},+ "must be configured together"},+ {"LiveKit without secret", env(liveKitAdmission, map[string]string{+ "LIVEKIT_URL": "wss://livekit.test", "LIVEKIT_API_KEY": "test-key",+ }), "must be configured together"},++ // Invalid LiveKit media origins.+ {"LiveKit https scheme", liveKitURL("https://livekit.test"), "LIVEKIT_URL must use ws or wss"},+ {"LiveKit credentials", liveKitURL("wss://user:[email protected]"),+ "LIVEKIT_URL must be an origin without credentials, path, query, or fragment"},+ {"LiveKit path", liveKitURL("wss://livekit.test/rtc"), "LIVEKIT_URL must be an origin"},+ {"LiveKit query", liveKitURL("wss://livekit.test?token=value"), "LIVEKIT_URL must be an origin"},+ {"LiveKit fragment", liveKitURL("wss://livekit.test#fragment"), "LIVEKIT_URL must be an origin"},+ {"LiveKit not a URL", liveKitURL("livekit.test"), "LIVEKIT_URL must be a valid ws or wss origin"},+ {"LiveKit ws in production", env(productionBase, liveKitAdmission, map[string]string{+ "LIVEKIT_URL": "ws://livekit.test:7880", "LIVEKIT_API_KEY": "test-key",+ "LIVEKIT_API_SECRET": liveKitSecret,+ }), "LIVEKIT_URL must use wss in production"},++ // Invalid LiveKit control origins.+ {"control ws scheme", liveKitAPIURL("ws://livekit-api.test"), "LIVEKIT_API_URL must use http or https"},+ {"control credentials", liveKitAPIURL("http://user:[email protected]"),+ "LIVEKIT_API_URL must be an origin without credentials, path, query, or fragment"},+ {"control path", liveKitAPIURL("http://livekit-api.test/rtc"), "LIVEKIT_API_URL must be an origin"},+ {"control query", liveKitAPIURL("http://livekit-api.test?token=value"), "LIVEKIT_API_URL must be an origin"},+ {"control fragment", liveKitAPIURL("http://livekit-api.test#fragment"), "LIVEKIT_API_URL must be an origin"},+ {"control not a URL", liveKitAPIURL("livekit-api.test"),+ "LIVEKIT_API_URL must be a valid http or https origin"},+ {"control plaintext in production", env(productionBase, map[string]string{+ "LIVEKIT_URL": "wss://livekit.test", "LIVEKIT_API_URL": "http://livekit-api.test:7880",+ "LIVEKIT_API_KEY": "test-key", "LIVEKIT_API_SECRET": liveKitSecret,+ }), "must use https or loopback"},+ {"short LiveKit secret", env(liveKitAdmission, map[string]string{+ "LIVEKIT_URL": "wss://livekit.test", "LIVEKIT_API_KEY": "test-key",+ "LIVEKIT_API_SECRET": "too-short",+ }), "LIVEKIT_API_SECRET must contain at least 32 bytes"},++ // Reused infrastructure secrets.+ {"site password reused as LiveKit secret", env(liveKitAdmission, map[string]string{+ "SITE_ACCESS_PASSWORD": strings.Repeat("x", 32), "LIVEKIT_URL": "wss://livekit.test",+ "LIVEKIT_API_KEY": "test-key", "LIVEKIT_API_SECRET": strings.Repeat("x", 32),+ }), "must use independent values"},+ {"LiveKit key reused as LiveKit secret", env(liveKitAdmission, map[string]string{+ "LIVEKIT_URL": "wss://livekit.test", "LIVEKIT_API_KEY": strings.Repeat("x", 32),+ "LIVEKIT_API_SECRET": strings.Repeat("x", 32),+ }), "must use independent values"},++ // Bounded integers.+ {"viewer limit above ceiling",+ map[string]string{"MAX_VIEWERS_PER_ROOM": strconv.Itoa(protocol.MaxViewersPerRoomLimit + 1)},+ "MAX_VIEWERS_PER_ROOM must be between 1 and 20"},+ {"viewer limit zero", map[string]string{"MAX_VIEWERS_PER_ROOM": "0"},+ "MAX_VIEWERS_PER_ROOM must be a positive integer"},+ {"fractional viewer limit", map[string]string{"MAX_VIEWERS_PER_ROOM": "1.5"},+ "MAX_VIEWERS_PER_ROOM must be a positive integer"},+ {"copy capacity zero", map[string]string{"ENDPOINT_MEDIA_COPY_CAPACITY": "0"},+ "ENDPOINT_MEDIA_COPY_CAPACITY must be a positive integer"},+ {"copy capacity above ceiling", map[string]string{"ENDPOINT_MEDIA_COPY_CAPACITY": "4"},+ "ENDPOINT_MEDIA_COPY_CAPACITY must be between 1 and 3"},+ {"fractional copy capacity", map[string]string{"ENDPOINT_MEDIA_COPY_CAPACITY": "1.5"},+ "ENDPOINT_MEDIA_COPY_CAPACITY must be a positive integer"},+ {"zero room lease", map[string]string{"ROOM_LEASE_SECONDS": "0"},+ "ROOM_LEASE_SECONDS must be a positive integer"},+ {"port zero", map[string]string{"PORT": "0"}, "PORT must be a positive integer"},+ {"port not a number", map[string]string{"PORT": "eight"}, "PORT must be a positive integer"},+ {"port above the TCP ceiling", map[string]string{"PORT": "65536"}, "PORT must be at most 65535"},++ // Public base URL.+ {"public base URL credentials", map[string]string{"PUBLIC_BASE_URL": "https://user:[email protected]"},+ "PUBLIC_BASE_URL must be an origin"},+ {"public base URL path", map[string]string{"PUBLIC_BASE_URL": "https://share.test/path"},+ "PUBLIC_BASE_URL must be an origin"},+ {"public base URL query", map[string]string{"PUBLIC_BASE_URL": "https://share.test?query=1"},+ "PUBLIC_BASE_URL must be an origin"},+ {"public base URL fragment", map[string]string{"PUBLIC_BASE_URL": "https://share.test#fragment"},+ "PUBLIC_BASE_URL must be an origin"},+ {"public base URL scheme", map[string]string{"PUBLIC_BASE_URL": "ftp://share.test"},+ "PUBLIC_BASE_URL must use http or https"},+ {"blank public base URL", map[string]string{"PUBLIC_BASE_URL": ""},+ "PUBLIC_BASE_URL must be a valid http or https origin"},+ {"plaintext public base URL in production", env(productionBase, map[string]string{+ "PUBLIC_BASE_URL": "http://share.test",+ }), "PUBLIC_BASE_URL must use https in production"},++ // Allowed origins.+ {"allowed origin scheme", map[string]string{"ALLOWED_ORIGINS": "ftp://share.test"},+ "Allowed origins must use http or https"},+ {"unparsable allowed origin", map[string]string{"ALLOWED_ORIGINS": "share.test"},+ "Allowed origins must be valid http or https URLs"},+ {"empty allowed origin entry", map[string]string{"ALLOWED_ORIGINS": "https://a.test,,https://b.test"},+ "ALLOWED_ORIGINS contains an empty URL"},++ // Production requirements.+ {"production without STUN", map[string]string{+ "SCREENER_ENV": "production", "PUBLIC_BASE_URL": "https://share.test",+ "SITE_ACCESS_PASSWORD": "host-password-12",+ }, "STUN is required in production"},+ {"production without a site password", map[string]string{+ "SCREENER_ENV": "production", "PUBLIC_BASE_URL": "https://share.test",+ "STUN_URLS": "stun:stun.test:3478",+ }, "SITE_ACCESS_PASSWORD is required in production"},++ // Site access password bounds (UTF-8 bytes).+ {"site password too short", map[string]string{"SITE_ACCESS_PASSWORD": strings.Repeat("x", 7)},+ "SITE_ACCESS_PASSWORD must contain 8 to 128 visible ASCII bytes"},+ {"site password outside ASCII", map[string]string{"SITE_ACCESS_PASSWORD": "密码密码密码密码"},+ "SITE_ACCESS_PASSWORD must contain 8 to 128 visible ASCII bytes"},+ {"site password with spaces", map[string]string{"SITE_ACCESS_PASSWORD": "contains spaces"},+ "SITE_ACCESS_PASSWORD must contain 8 to 128 visible ASCII bytes"},+ {"site password too long", map[string]string{"SITE_ACCESS_PASSWORD": strings.Repeat("x", 129)},+ "SITE_ACCESS_PASSWORD must contain 8 to 128 visible ASCII bytes"},++ // STUN lists.+ {"STUN path", map[string]string{"STUN_URLS": "stun:stun.test/path"},+ "STUN_URLS contains an invalid STUN URL"},+ {"STUN query", map[string]string{"STUN_URLS": "stun:stun.test?transport=udp"},+ "STUN_URLS contains an invalid STUN URL"},+ {"STUN fragment", map[string]string{"STUN_URLS": "stun:stun.test#fragment"},+ "STUN_URLS contains an invalid STUN URL"},+ {"STUN without authority", map[string]string{"STUN_URLS": "stun:"},+ "STUN_URLS contains an invalid STUN URL"},+ {"STUN with an empty port", map[string]string{"STUN_URLS": "stun:stun.test:"},+ "STUN_URLS contains an invalid STUN URL"},+ {"STUN port zero", map[string]string{"STUN_URLS": "stun:stun.test:0"},+ "STUN_URLS contains an invalid STUN URL"},+ {"STUN userinfo", map[string]string{"STUN_URLS": "stun:[email protected]:3478"},+ "STUN_URLS contains an invalid STUN URL"},+ {"TURN scheme", map[string]string{"STUN_URLS": "turn:turn.test:3478"},+ "STUN_URLS contains an invalid STUN URL"},+ {"STUNS scheme", map[string]string{"STUN_URLS": "stuns:stun.test:5349"},+ "STUN_URLS contains an invalid STUN URL"},+ {"empty STUN entry", map[string]string{"STUN_URLS": "stun:a.test:3478,,stun:b.test:3478"},+ "STUN_URLS contains an empty URL"},+ {"too many STUN URLs", map[string]string{"STUN_URLS": stunList(9, "stun")},+ "STUN_URLS must contain at most 8 URLs"},+ {"no NAT prediction slots", map[string]string{+ "STUN_URLS": stunList(7, "ordinary"), "NAT_PREDICTION_ENABLED": "true",+ }, "STUN_URLS must contain at most 6 URLs when NAT_PREDICTION_ENABLED=true"},++ // NAT prediction.+ {"NAT prediction without STUN", map[string]string{"NAT_PREDICTION_ENABLED": "true"},+ "NAT_PREDICTION_ENABLED requires a STUN_URLS entry on UDP 3478"},+ {"NAT prediction off the base port", map[string]string{+ "STUN_URLS": "stun:share.test:5349", "NAT_PREDICTION_ENABLED": "true",+ }, "NAT_PREDICTION_ENABLED requires a STUN_URLS entry on UDP 3478"},+ {"NAT prediction not a boolean", map[string]string{"NAT_PREDICTION_ENABLED": "sometimes"},+ "NAT_PREDICTION_ENABLED must be true or false"},++ // Room database path.+ {"memory room database path", map[string]string{"ROOM_DATABASE_PATH": ":memory:"},+ "ROOM_DATABASE_PATH must be an absolute file path"},+ {"room database path with a NUL", map[string]string{"ROOM_DATABASE_PATH": "rooms\x00.sqlite"},+ "ROOM_DATABASE_PATH must be an absolute file path"},+ {"bare room database file name", map[string]string{"ROOM_DATABASE_PATH": "rooms.sqlite"},+ "ROOM_DATABASE_PATH must be an absolute file path"},+ {"relative room database path", map[string]string{"ROOM_DATABASE_PATH": "./state/rooms.sqlite"},+ "ROOM_DATABASE_PATH must be an absolute file path"},++ // Runtime environment (DECISIONS D8).+ {"NODE_ENV is removed", map[string]string{"NODE_ENV": "production"},+ "NODE_ENV is no longer supported; use SCREENER_ENV"},+ {"blank NODE_ENV is removed", map[string]string{"NODE_ENV": ""},+ "NODE_ENV is no longer supported; use SCREENER_ENV"},+ {"test environment is gone", map[string]string{"SCREENER_ENV": "test"},+ "SCREENER_ENV must be development or production"},+ {"blank environment", map[string]string{"SCREENER_ENV": ""},+ "SCREENER_ENV must be development or production"},++ // Removed variables carrying their own replacement.+ {"removed relay downstream setting", map[string]string{"MAX_PEER_RELAY_DOWNSTREAM_EDGES": "2"},+ "MAX_PEER_RELAY_DOWNSTREAM_EDGES is no longer supported; use ENDPOINT_MEDIA_COPY_CAPACITY"},+ {"removed room rollout setting", map[string]string{"PEER_ASSISTED_ROOM_IDS": "1"},+ "PEER_ASSISTED_ROOM_IDS is no longer supported; peer-assisted media applies to every room"},+ {"removed peer-assisted toggle", map[string]string{"PEER_ASSISTED_MEDIA": "true"},+ "PEER_ASSISTED_MEDIA is no longer supported; peer-assisted media is always enabled"},+ {"removed room TTL", map[string]string{"ROOM_TTL_SECONDS": ""},+ "ROOM_TTL_SECONDS is no longer supported; use ROOM_LEASE_SECONDS"},+ {"removed access password", map[string]string{"ACCESS_PASSWORD": "legacy-password"},+ "ACCESS_PASSWORD is no longer supported; use SITE_ACCESS_PASSWORD"},+ {"blank access password", map[string]string{"ACCESS_PASSWORD": ""},+ "ACCESS_PASSWORD is no longer supported; use SITE_ACCESS_PASSWORD"},+ {"removed host admission password", map[string]string{"HOST_ADMISSION_PASSWORD": "legacy-password"},+ "HOST_ADMISSION_PASSWORD is no longer supported; use SITE_ACCESS_PASSWORD"},+ {"blank host admission password", map[string]string{"HOST_ADMISSION_PASSWORD": ""},+ "HOST_ADMISSION_PASSWORD is no longer supported; use SITE_ACCESS_PASSWORD"},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ _, err := Load(testCase.env)+ if err == nil {+ t.Fatalf("Load: want error containing %q", testCase.want)+ }+ if !strings.Contains(err.Error(), testCase.want) {+ t.Errorf("Load: error %q, want it to contain %q", err, testCase.want)+ }+ })+ }+}++// TestLoadRejectsRemovedTurnVariables covers the ten TURN names that share the+// default reason, blank included.+func TestLoadRejectsRemovedTurnVariables(t *testing.T) {+ names := []string{+ "TURN_URLS", "TURN_SHARED_SECRET", "TURN_CREDENTIAL_TTL_SECONDS",+ "PEER_ICE_TURN_URLS", "PEER_ICE_TURN_SHARED_SECRET",+ "PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS", "SELECTED_EDGE_TURN_URLS",+ "SELECTED_EDGE_TURN_SHARED_SECRET", "SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS",+ "SELECTED_EDGE_TURN_ALLOCATION_CAPACITY",+ }+ for _, name := range names {+ t.Run(name, func(t *testing.T) {+ _, err := Load(map[string]string{name: ""})+ want := name + " is no longer supported; ordinary ICE accepts STUN_URLS only"+ if err == nil || err.Error() != want {+ t.Errorf("Load: error %v, want %q", err, want)+ }+ })+ }+}++func TestOrigin(t *testing.T) {+ cases := []struct{ raw, scheme, alternative, want string }{+ {"https://Example.com:443/", "http", "https", "https://example.com"},+ {"http://Example.com:80", "http", "https", "http://example.com"},+ {"https://share.test:0443", "http", "https", "https://share.test"},+ {"http://localhost:9123", "http", "https", "http://localhost:9123"},+ {"wss://LiveKit.test:443", "ws", "wss", "wss://livekit.test"},+ {"ws://livekit.test:7880", "ws", "wss", "ws://livekit.test:7880"},+ {"https://[2001:DB8::1]:8443", "http", "https", "https://[2001:db8::1]:8443"},+ {"http://[::1]:7880", "http", "https", "http://[::1]:7880"},+ }+ for _, testCase := range cases {+ t.Run(testCase.raw, func(t *testing.T) {+ parsed, err := parseOriginURL(testCase.raw, "TEST", testCase.scheme, testCase.alternative)+ if err != nil {+ t.Fatalf("parseOriginURL: %v", err)+ }+ if got := Origin(parsed); got != testCase.want {+ t.Errorf("Origin = %q, want %q", got, testCase.want)+ }+ if got := parsed.String(); got != testCase.want+"/" {+ t.Errorf("String = %q, want %q", got, testCase.want+"/")+ }+ })+ }+}++func liveKitURL(value string) map[string]string {+ return env(liveKitAdmission, map[string]string{+ "LIVEKIT_URL": value, "LIVEKIT_API_KEY": "test-key", "LIVEKIT_API_SECRET": liveKitSecret,+ })+}++func liveKitAPIURL(value string) map[string]string {+ return map[string]string{+ "LIVEKIT_URL": "wss://livekit.test", "LIVEKIT_API_URL": value,+ "LIVEKIT_API_KEY": "test-key", "LIVEKIT_API_SECRET": liveKitSecret,+ }+}diff --git a/internal/server/config/ice.go b/internal/server/config/ice.gonew file mode 100644index 00000000..aafa8316--- /dev/null+++ b/internal/server/config/ice.go@@ -0,0 +1,81 @@+package config++import (+ "fmt"+ "net/url"+ "strconv"+ "strings"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// Ported from src/server/ice.ts.+const natPredictionBasePort = 3478++// natPredictionAuxiliaryPorts are NAT_PREDICTION_AUXILIARY_PORTS: the two+// listeners a NAT-prediction STUN deployment binds beside the base port, whose+// answers reveal the peer's port-allocation stride.+var natPredictionAuxiliaryPorts = [...]int{natPredictionBasePort + 1, natPredictionBasePort + 2}++// NATPredictionStunURLs ports natPredictionStunUrls: the two auxiliary+// listeners derived from the first ordinary STUN authority on UDP 3478.+func NATPredictionStunURLs(stunURLs []string) []string {+ for _, stunURL := range stunURLs {+ // TS: stunUrl.slice(stunUrl.indexOf(":") + 1) — a URL without a colon+ // keeps its whole text, which then fails to yield a host below.+ authorityText := stunURL[strings.IndexByte(stunURL, ':')+1:]+ authority, err := url.Parse("http://" + authorityText)+ if err != nil || authority.Hostname() == "" {+ continue+ }+ port := authority.Port()+ // The WHATWG parser drops a port equal to the scheme default, so+ // "stun:host:80" reaches the TypeScript's `: NAT_PREDICTION_BASE_PORT`+ // fallback and counts as a base listener.+ if port == defaultSchemePort("http") {+ port = ""+ }+ if port != "" {+ number, err := strconv.Atoi(port)+ if err != nil || number != natPredictionBasePort {+ continue+ }+ }+ // WHATWG lowercases the host and keeps an IPv6 literal bracketed;+ // url.URL.Hostname strips the brackets, so put them back.+ hostname := strings.ToLower(authority.Hostname())+ if strings.Contains(hostname, ":") {+ hostname = "[" + hostname + "]"+ }+ derived := make([]string, 0, len(natPredictionAuxiliaryPorts))+ for _, auxiliaryPort := range natPredictionAuxiliaryPorts {+ derived = append(derived, fmt.Sprintf("stun:%s:%d", hostname, auxiliaryPort))+ }+ return derived+ }+ return nil+}++// IceConfig ports createIceConfig.+func IceConfig(c Config) protocol.IceConfig {+ // TS: options.natPredictionStunUrls ?? natPredictionStunUrls(stunUrls). A+ // configured empty list (Local without prediction) is kept as-is; only an+ // absent one is derived, so nil and empty differ here.+ prediction := c.NATPredictionSTUNURLs+ if prediction == nil {+ prediction = NATPredictionStunURLs(c.STUNURLs)+ }+ config := protocol.IceConfig{+ IceServers: []protocol.IceServer{},+ NatPredictionStunURLs: []string{},+ }+ if len(c.STUNURLs) > 0 {+ config.IceServers = []protocol.IceServer{+ {URLs: protocol.IceServerURLList(append([]string{}, c.STUNURLs...)...)},+ }+ }+ if c.NATPredictionEnabled {+ config.NatPredictionStunURLs = append([]string{}, prediction...)+ }+ return config+}diff --git a/internal/server/config/ice_test.go b/internal/server/config/ice_test.gonew file mode 100644index 00000000..21e05a06--- /dev/null+++ b/internal/server/config/ice_test.go@@ -0,0 +1,136 @@+package config++import (+ "encoding/json"+ "slices"+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// Ported from tests/ice.test.ts.++func TestIceConfig(t *testing.T) {+ cases := []struct {+ name string+ config Config+ want string+ }{+ {+ name: "returns only the configured STUN servers",+ config: Config{+ STUNURLs: []string{"stun:stun-a.example.test:3478", "stun:stun-b.example.test:3478"},+ NATPredictionEnabled: true,+ NATPredictionSTUNURLs: []string{+ "stun:survey-a.example.test:3478", "stun:survey-b.example.test:3478",+ },+ },+ want: `{"iceServers":[{"urls":["stun:stun-a.example.test:3478",` ++ `"stun:stun-b.example.test:3478"]}],"natPredictionStunUrls":` ++ `["stun:survey-a.example.test:3478","stun:survey-b.example.test:3478"]}`,+ },+ {+ name: "keeps local development explicit when STUN is absent",+ config: Config{},+ want: `{"iceServers":[],"natPredictionStunUrls":[]}`,+ },+ {+ name: "does not expose auxiliary listeners when the capability is disabled",+ config: Config{STUNURLs: []string{"stun:share.example.test:3478"}},+ want: `{"iceServers":[{"urls":["stun:share.example.test:3478"]}],` ++ `"natPredictionStunUrls":[]}`,+ },+ {+ name: "derives auxiliary listeners from an IPv6 STUN authority",+ config: Config{+ STUNURLs: []string{"STUN:[2001:db8::1]:3478"},+ NATPredictionEnabled: true,+ },+ want: `{"iceServers":[{"urls":["STUN:[2001:db8::1]:3478"]}],` ++ `"natPredictionStunUrls":["stun:[2001:db8::1]:3479","stun:[2001:db8::1]:3480"]}`,+ },+ {+ // TS: `options.natPredictionStunUrls ?? natPredictionStunUrls(...)`+ // keeps a configured empty list instead of deriving one.+ name: "keeps a configured empty prediction list",+ config: Config{+ STUNURLs: []string{"stun:share.example.test:3478"},+ NATPredictionEnabled: true,+ NATPredictionSTUNURLs: []string{},+ },+ want: `{"iceServers":[{"urls":["stun:share.example.test:3478"]}],` ++ `"natPredictionStunUrls":[]}`,+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ encoded, err := json.Marshal(IceConfig(testCase.config))+ if err != nil {+ t.Fatalf("Marshal: %v", err)+ }+ if string(encoded) != testCase.want {+ t.Errorf("IceConfig = %s, want %s", encoded, testCase.want)+ }+ })+ }+}++func TestIceConfigDoesNotAliasTheConfiguration(t *testing.T) {+ config := Config{+ STUNURLs: []string{"stun:a.test:3478"},+ NATPredictionEnabled: true,+ NATPredictionSTUNURLs: []string{"stun:a.test:3479", "stun:a.test:3480"},+ }+ derived := IceConfig(config)+ derived.IceServers[0].URLs.List[0] = "stun:mutated.test:3478"+ derived.NatPredictionStunURLs[0] = "stun:mutated.test:3479"+ if config.STUNURLs[0] != "stun:a.test:3478" || config.NATPredictionSTUNURLs[0] != "stun:a.test:3479" {+ t.Errorf("IceConfig shares its slices with the Config: %v %v",+ config.STUNURLs, config.NATPredictionSTUNURLs)+ }+}++func TestNATPredictionStunURLs(t *testing.T) {+ cases := []struct {+ name string+ stunURLs []string+ want []string+ }{+ {"no URLs", nil, nil},+ {"implicit base port", []string{"stun:share.test"},+ []string{"stun:share.test:3479", "stun:share.test:3480"}},+ {"explicit base port", []string{"stun:share.test:3478"},+ []string{"stun:share.test:3479", "stun:share.test:3480"}},+ {"leading zeros in the port", []string{"stun:share.test:03478"},+ []string{"stun:share.test:3479", "stun:share.test:3480"}},+ // WHATWG drops a port equal to the scheme default, so "http://host:80"+ // reports no port and the TS fallback treats it as 3478.+ {"HTTP default port reads as the base port", []string{"stun:share.test:80"},+ []string{"stun:share.test:3479", "stun:share.test:3480"}},+ {"uppercase scheme and host", []string{"STUN:Share.TEST:3478"},+ []string{"stun:share.test:3479", "stun:share.test:3480"}},+ {"IPv6 authority", []string{"stun:[2001:DB8::1]:3478"},+ []string{"stun:[2001:db8::1]:3479", "stun:[2001:db8::1]:3480"}},+ {"first base listener wins",+ []string{"stun:a.test:5349", "stun:b.test:3478", "stun:c.test:3478"},+ []string{"stun:b.test:3479", "stun:b.test:3480"}},+ {"no base listener", []string{"stun:a.test:5349", "stun:b.test:19302"}, nil},+ // TS: indexOf(":") is -1, so the whole text becomes the authority.+ {"no scheme separator", []string{"sharetest"},+ []string{"stun:sharetest:3479", "stun:sharetest:3480"}},+ {"no authority", []string{"stun:"}, nil},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ got := NATPredictionStunURLs(testCase.stunURLs)+ if !slices.Equal(got, testCase.want) {+ t.Errorf("NATPredictionStunURLs = %v, want %v", got, testCase.want)+ }+ if len(got) > protocol.MaxNatPredictionAuxiliaryStunURLs {+ t.Errorf("NATPredictionStunURLs returned %d URLs", len(got))+ }+ })+ }+}diff --git a/internal/server/config/local.go b/internal/server/config/local.gonew file mode 100644index 00000000..3576152c--- /dev/null+++ b/internal/server/config/local.go@@ -0,0 +1,151 @@+package config++import (+ "errors"+ "fmt"+ "net"+ "net/url"+ "regexp"+ "slices"+ "strings"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// Ported from src/server/local-config.ts.+const localRoomLeaseMs = 24 * 60 * 60 * 1_000++// localPasswordPattern is VISIBLE_ASCII_PATTERN from local-config.ts. Because+// it admits one byte per character the TypeScript's extra Buffer.byteLength+// bounds are already implied by {8,128}.+var localPasswordPattern = regexp.MustCompile(`^[\x21-\x7e]{8,128}$`)++// LocalOptions ports LocalServerConfigOptions. loadLocalServerConfig, the+// environment form, went away with the Node child process, so Local never+// reads the process environment.+type LocalOptions struct {+ // Port of 0 selects the default 8787, as TypeScript's absent `port` did.+ // An explicit 0 is indistinguishable from absent here, where TypeScript+ // rejected it; 0 is not a usable port either way.+ Port int+ PublicAddress string+ PublicOrigin string+ AllowedAddresses []string+ SiteAccessPassword string+ STUNURLs []string+ NATPredictionSTUNURLs []string+}++// Local ports createLocalServerConfig.+func Local(options LocalOptions) (Config, error) {+ port := options.Port+ if port == 0 {+ port = defaultPort+ }+ if port < 1 || port > maxPort {+ return Config{}, fmt.Errorf("Local server port must be an integer between 1 and %d", maxPort)+ }+ publicAddress, err := localIPv4(options.PublicAddress, "public address")+ if err != nil {+ return Config{}, err+ }+ if publicAddress == "0.0.0.0" || strings.HasPrefix(publicAddress, "127.") {+ return Config{}, errors.New("Local server public address must be reachable from the LAN")+ }+ siteAccessPassword := strings.TrimFunc(options.SiteAccessPassword, protocol.IsJSWhitespace)+ if siteAccessPassword != "" && !localPasswordPattern.MatchString(siteAccessPassword) {+ return Config{}, errors.New("Local access password must contain 8 to 128 visible ASCII bytes")+ }++ allowedAddresses := []string{publicAddress}+ for _, address := range options.AllowedAddresses {+ normalized, err := localIPv4(address, "allowed address")+ if err != nil {+ return Config{}, err+ }+ if !slices.Contains(allowedAddresses, normalized) {+ allowedAddresses = append(allowedAddresses, normalized)+ }+ }++ // TS spreads `?? []`, so both lists are always arrays; keeping them non-nil+ // is what tells IceConfig that NAT prediction URLs were configured.+ stunURLs := append([]string{}, options.STUNURLs...)+ natPredictionSTUNURLs := append([]string{}, options.NATPredictionSTUNURLs...)+ if len(stunURLs)+len(natPredictionSTUNURLs) > protocol.MaxIceServerURLs ||+ !allValidStunURLs(stunURLs) ||+ !allValidStunURLs(natPredictionSTUNURLs) ||+ (len(natPredictionSTUNURLs) != 0 &&+ len(natPredictionSTUNURLs) != protocol.MaxNatPredictionAuxiliaryStunURLs) ||+ (len(natPredictionSTUNURLs) > 0 && len(stunURLs) == 0) {+ return Config{}, errors.New("Local STUN URLs are invalid")+ }++ // TS builds these with a template string, so a non-default port is always+ // spelled out and port 80 would produce "http://host:80", which is not the+ // serialised origin. Kept as-is: Local never runs on 80.+ origin := func(host string) string { return fmt.Sprintf("http://%s:%d", host, port) }+ publicBaseURL := &url.URL{Scheme: "http", Host: fmt.Sprintf("%s:%d", publicAddress, port), Path: "/"}+ if options.PublicOrigin != "" {+ publicBaseURL, err = publicHTTPSOrigin(options.PublicOrigin)+ if err != nil {+ return Config{}, err+ }+ }++ allowedOrigins := map[string]struct{}{+ origin("localhost"): {},+ origin("127.0.0.1"): {},+ }+ for _, address := range allowedAddresses {+ allowedOrigins[origin(address)] = struct{}{}+ }+ allowedOrigins[Origin(publicBaseURL)] = struct{}{}++ return Config{+ Env: EnvironmentProduction,+ Port: port,+ ListenHost: "0.0.0.0",+ PublicBaseURL: publicBaseURL,+ AllowedOrigins: allowedOrigins,+ SiteAccessPassword: siteAccessPassword,+ RoomLeaseMs: localRoomLeaseMs,+ MaxViewersPerRoom: protocol.MaxViewersPerRoomLimit,+ EndpointMediaCopyCapacity: protocol.DefaultEndpointMediaCopyCapacity,+ STUNURLs: stunURLs,+ NATPredictionEnabled: len(natPredictionSTUNURLs) == protocol.MaxNatPredictionAuxiliaryStunURLs,+ NATPredictionSTUNURLs: natPredictionSTUNURLs,+ }, nil+}++func allValidStunURLs(values []string) bool {+ for _, value := range values {+ if !protocol.ValidStunURLValue(value) {+ return false+ }+ }+ return true+}++// publicHTTPSOrigin ports publicHTTPSOrigin: every failure shares one message.+func publicHTTPSOrigin(value string) (*url.URL, error) {+ parsed, err := url.Parse(value)+ if err != nil || parsed.Scheme != "https" || parsed.Host == "" ||+ hasUserinfo(parsed) || (parsed.Path != "" && parsed.Path != "/") ||+ parsed.RawQuery != "" || parsed.Fragment != "" {+ return nil, errors.New("Local public origin must be an HTTPS origin")+ }+ return &url.URL{Scheme: "https", Host: normalizedHost(parsed), Path: "/"}, nil+}++// localIPv4 ports localIPv4. Node's isIP(value) === 4 accepts only a dotted+// quad, so an IPv4-mapped IPv6 literal such as "::ffff:192.168.1.10" — which+// net.ParseIP(...).To4() does resolve — is rejected here as well.+func localIPv4(value string, name string) (string, error) {+ address := strings.TrimFunc(value, protocol.IsJSWhitespace)+ parsed := net.ParseIP(address)+ if parsed == nil || parsed.To4() == nil || strings.ContainsRune(address, ':') {+ return "", fmt.Errorf("Local server %s must be an IPv4 address", name)+ }+ return address, nil+}diff --git a/internal/server/config/local_test.go b/internal/server/config/local_test.gonew file mode 100644index 00000000..6c7251d4--- /dev/null+++ b/internal/server/config/local_test.go@@ -0,0 +1,210 @@+package config++import (+ "reflect"+ "slices"+ "strings"+ "testing"+)++// Ported from tests/local-server-config.test.ts. The environment form,+// loadLocalServerConfig, went away with the Node child process, so its scenario+// is expressed through LocalOptions here.++func mustLocal(t *testing.T, options LocalOptions) Config {+ t.Helper()+ config, err := Local(options)+ if err != nil {+ t.Fatalf("Local: unexpected error %v", err)+ }+ return config+}++func TestLocalMapsClientInputs(t *testing.T) {+ config := mustLocal(t, LocalOptions{+ Port: 9123,+ PublicAddress: "192.168.1.10",+ AllowedAddresses: []string{"10.0.0.8", "192.168.1.10"},+ SiteAccessPassword: "local-access-password",+ })++ if config.Env != EnvironmentProduction {+ t.Errorf("Env = %q", config.Env)+ }+ if config.Port != 9123 {+ t.Errorf("Port = %d", config.Port)+ }+ if config.ListenHost != "0.0.0.0" {+ t.Errorf("ListenHost = %q", config.ListenHost)+ }+ if config.SiteAccessPassword != "local-access-password" {+ t.Errorf("SiteAccessPassword = %q", config.SiteAccessPassword)+ }+ if config.RoomLeaseMs != 86_400_000 {+ t.Errorf("RoomLeaseMs = %d", config.RoomLeaseMs)+ }+ if config.MaxViewersPerRoom != 20 {+ t.Errorf("MaxViewersPerRoom = %d", config.MaxViewersPerRoom)+ }+ if config.EndpointMediaCopyCapacity != 2 {+ t.Errorf("EndpointMediaCopyCapacity = %d", config.EndpointMediaCopyCapacity)+ }+ if len(config.STUNURLs) != 0 {+ t.Errorf("STUNURLs = %v", config.STUNURLs)+ }+ if config.NATPredictionEnabled {+ t.Error("NATPredictionEnabled = true")+ }+ if got := config.PublicBaseURL.String(); got != "http://192.168.1.10:9123/" {+ t.Errorf("PublicBaseURL = %q", got)+ }+ want := map[string]struct{}{+ "http://localhost:9123": {},+ "http://127.0.0.1:9123": {},+ "http://192.168.1.10:9123": {},+ "http://10.0.0.8:9123": {},+ }+ if !reflect.DeepEqual(config.AllowedOrigins, want) {+ t.Errorf("AllowedOrigins = %v, want %v", config.AllowedOrigins, want)+ }+ if config.LiveKit != nil {+ t.Errorf("LiveKit = %+v", config.LiveKit)+ }+ if config.RoomDatabasePath != "" {+ t.Errorf("RoomDatabasePath = %q", config.RoomDatabasePath)+ }+}++func TestLocalTunnelledClient(t *testing.T) {+ config := mustLocal(t, LocalOptions{+ Port: 9234,+ PublicAddress: "192.168.50.4",+ AllowedAddresses: []string{"192.168.50.4", "10.10.0.4"},+ SiteAccessPassword: "persistent-local-password",+ PublicOrigin: "https://small-bright-room.trycloudflare.com",+ STUNURLs: []string{"stun:stun.example:3478", "stun:stun.example:3479"},+ NATPredictionSTUNURLs: []string{"stun:survey-a.example:3478", "stun:survey-b.example:3478"},+ })++ if config.Port != 9234 {+ t.Errorf("Port = %d", config.Port)+ }+ if got := Origin(config.PublicBaseURL); got != "https://small-bright-room.trycloudflare.com" {+ t.Errorf("public origin = %q", got)+ }+ for _, origin := range []string{+ "https://small-bright-room.trycloudflare.com", "http://10.10.0.4:9234",+ } {+ if _, ok := config.AllowedOrigins[origin]; !ok {+ t.Errorf("AllowedOrigins is missing %q: %v", origin, config.AllowedOrigins)+ }+ }+ if !slices.Equal(config.STUNURLs, []string{"stun:stun.example:3478", "stun:stun.example:3479"}) {+ t.Errorf("STUNURLs = %v", config.STUNURLs)+ }+ if !config.NATPredictionEnabled {+ t.Error("NATPredictionEnabled = false")+ }+ if !slices.Equal(config.NATPredictionSTUNURLs,+ []string{"stun:survey-a.example:3478", "stun:survey-b.example:3478"}) {+ t.Errorf("NATPredictionSTUNURLs = %v", config.NATPredictionSTUNURLs)+ }+}++func TestLocalDefaults(t *testing.T) {+ config := mustLocal(t, LocalOptions{PublicAddress: "192.168.1.10"})++ if config.SiteAccessPassword != "" {+ t.Errorf("SiteAccessPassword = %q, want the open site", config.SiteAccessPassword)+ }+ if config.Port != 8787 {+ t.Errorf("Port = %d, want the 8787 default", config.Port)+ }+ if got := Origin(config.PublicBaseURL); got != "http://192.168.1.10:8787" {+ t.Errorf("public origin = %q", got)+ }+ // A configured (empty) prediction list stays non-nil so IceConfig does not+ // derive one, which is TS's `?? []` spread.+ if config.NATPredictionSTUNURLs == nil {+ t.Error("NATPredictionSTUNURLs = nil, want an empty configured list")+ }+}++func TestLocalRejects(t *testing.T) {+ cases := []struct {+ name string+ options LocalOptions+ want string+ }{+ {"hostname public address", LocalOptions{PublicAddress: "localhost",+ SiteAccessPassword: "valid-password"},+ "Local server public address must be an IPv4 address"},+ {"IPv6 public address", LocalOptions{PublicAddress: "::ffff:192.168.1.10"},+ "Local server public address must be an IPv4 address"},+ {"loopback public address", LocalOptions{PublicAddress: "127.0.0.1",+ SiteAccessPassword: "valid-password"},+ "Local server public address must be reachable from the LAN"},+ {"unspecified public address", LocalOptions{PublicAddress: "0.0.0.0",+ SiteAccessPassword: "valid-password"},+ "Local server public address must be reachable from the LAN"},+ {"short password", LocalOptions{PublicAddress: "192.168.1.2", SiteAccessPassword: "short"},+ "Local access password must contain 8 to 128 visible ASCII bytes"},+ {"password outside ASCII", LocalOptions{PublicAddress: "192.168.1.2",+ SiteAccessPassword: "密码密码密码密码"},+ "Local access password must contain 8 to 128 visible ASCII bytes"},+ {"long password", LocalOptions{PublicAddress: "192.168.1.2",+ SiteAccessPassword: strings.Repeat("x", 129)},+ "Local access password must contain 8 to 128 visible ASCII bytes"},+ {"port above the TCP ceiling", LocalOptions{Port: 70_000, PublicAddress: "192.168.1.2"},+ "Local server port must be an integer between 1 and 65535"},+ {"negative port", LocalOptions{Port: -1, PublicAddress: "192.168.1.2"},+ "Local server port must be an integer between 1 and 65535"},+ {"hostname allowed address", LocalOptions{PublicAddress: "192.168.1.2",+ AllowedAddresses: []string{"share.local"}},+ "Local server allowed address must be an IPv4 address"},+ {"plaintext public origin", LocalOptions{PublicAddress: "192.168.1.2",+ PublicOrigin: "http://public.example", SiteAccessPassword: "valid-password"},+ "Local public origin must be an HTTPS origin"},+ {"public origin with a path", LocalOptions{PublicAddress: "192.168.1.2",+ PublicOrigin: "https://public.example/path", SiteAccessPassword: "valid-password"},+ "Local public origin must be an HTTPS origin"},+ {"public origin with userinfo", LocalOptions{PublicAddress: "192.168.1.2",+ PublicOrigin: "https://[email protected]", SiteAccessPassword: "valid-password"},+ "Local public origin must be an HTTPS origin"},+ {"unparsable public origin", LocalOptions{PublicAddress: "192.168.1.2",+ PublicOrigin: "public.example"},+ "Local public origin must be an HTTPS origin"},+ {"invalid STUN URL", LocalOptions{PublicAddress: "192.168.1.2",+ STUNURLs: []string{"turn:turn.test:3478"}},+ "Local STUN URLs are invalid"},+ {"invalid prediction STUN URL", LocalOptions{PublicAddress: "192.168.1.2",+ STUNURLs: []string{"stun:a.test:3478"},+ NATPredictionSTUNURLs: []string{"stun:a.test:3479", "stuns:b.test:3480"}},+ "Local STUN URLs are invalid"},+ {"single prediction STUN URL", LocalOptions{PublicAddress: "192.168.1.2",+ STUNURLs: []string{"stun:a.test:3478"}, NATPredictionSTUNURLs: []string{"stun:a.test:3479"}},+ "Local STUN URLs are invalid"},+ {"prediction without ordinary STUN", LocalOptions{PublicAddress: "192.168.1.2",+ NATPredictionSTUNURLs: []string{"stun:a.test:3479", "stun:a.test:3480"}},+ "Local STUN URLs are invalid"},+ {"more ICE URLs than the wire carries", LocalOptions{PublicAddress: "192.168.1.2",+ STUNURLs: []string{+ "stun:a.test:3478", "stun:b.test:3478", "stun:c.test:3478", "stun:d.test:3478",+ "stun:e.test:3478", "stun:f.test:3478", "stun:g.test:3478",+ },+ NATPredictionSTUNURLs: []string{"stun:a.test:3479", "stun:a.test:3480"}},+ "Local STUN URLs are invalid"},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ _, err := Local(testCase.options)+ if err == nil {+ t.Fatalf("Local: want error containing %q", testCase.want)+ }+ if !strings.Contains(err.Error(), testCase.want) {+ t.Errorf("Local: error %q, want it to contain %q", err, testCase.want)+ }+ })+ }+}diff --git a/internal/server/ordered/map.go b/internal/server/ordered/map.gonew file mode 100644index 00000000..78033cce--- /dev/null+++ b/internal/server/ordered/map.go@@ -0,0 +1,154 @@+// Package ordered provides an insertion-ordered map with the iteration+// semantics of a JavaScript Map. The TypeScript server relied on those+// semantics wherever it iterated a Map or Set: wire-visible participant order,+// candidate ordering, round-robin state, and delete-during-iteration loops.+package ordered++import "iter"++type entry[K comparable, V any] struct {+ key K+ value V+ deleted bool+}++// Map keeps keys in first-insertion order. Set on an existing key keeps its+// position; MoveToBack reproduces the JavaScript delete-then-set idiom.+// Iteration is live: an entry deleted before it is visited is skipped and an+// entry appended during iteration is visited, exactly like a JavaScript Map.+// The zero value is ready to use.+type Map[K comparable, V any] struct {+ entries []entry[K, V]+ index map[K]int+ deleted int+ iterating int+}++// Len reports the number of live entries.+func (m *Map[K, V]) Len() int { return len(m.index) }++// Get returns the value for key and whether it is present.+func (m *Map[K, V]) Get(key K) (V, bool) {+ if position, ok := m.index[key]; ok {+ return m.entries[position].value, true+ }+ var zero V+ return zero, false+}++// Has reports whether key is present.+func (m *Map[K, V]) Has(key K) bool {+ _, ok := m.index[key]+ return ok+}++// Set stores value under key, keeping the existing position when the key is+// already present and appending otherwise.+func (m *Map[K, V]) Set(key K, value V) {+ if position, ok := m.index[key]; ok {+ m.entries[position].value = value+ return+ }+ if m.index == nil {+ m.index = make(map[K]int)+ }+ m.index[key] = len(m.entries)+ m.entries = append(m.entries, entry[K, V]{key: key, value: value})+}++// MoveToBack re-inserts key at the end, as JavaScript `map.delete(k);+// map.set(k, v)` does. It is a plain Set when the key is absent.+func (m *Map[K, V]) MoveToBack(key K, value V) {+ m.Delete(key)+ m.Set(key, value)+}++// Delete removes key and reports whether it was present.+func (m *Map[K, V]) Delete(key K) bool {+ position, ok := m.index[key]+ if !ok {+ return false+ }+ delete(m.index, key)+ var zero V+ m.entries[position].value = zero+ m.entries[position].deleted = true+ m.deleted+++ m.compact()+ return true+}++// Clear removes every entry. Dropping the index before compacting is safe+// because every entry is now a tombstone, so compact writes no index entry.+func (m *Map[K, V]) Clear() {+ for position := range m.entries {+ if !m.entries[position].deleted {+ var zero V+ m.entries[position].value = zero+ m.entries[position].deleted = true+ m.deleted+++ }+ }+ m.index = nil+ m.compact()+}++// Keys returns a snapshot of the live keys in order.+func (m *Map[K, V]) Keys() []K {+ keys := make([]K, 0, len(m.index))+ for _, current := range m.entries {+ if !current.deleted {+ keys = append(keys, current.key)+ }+ }+ return keys+}++// Values returns a snapshot of the live values in order.+func (m *Map[K, V]) Values() []V {+ values := make([]V, 0, len(m.index))+ for _, current := range m.entries {+ if !current.deleted {+ values = append(values, current.value)+ }+ }+ return values+}++// All iterates live entries in order with JavaScript Map semantics. Mutating+// the map inside the loop is allowed.+func (m *Map[K, V]) All() iter.Seq2[K, V] {+ return func(yield func(K, V) bool) {+ m.iterating+++ defer func() {+ m.iterating--+ m.compact()+ }()+ for position := 0; position < len(m.entries); position++ {+ current := m.entries[position]+ if current.deleted {+ continue+ }+ if !yield(current.key, current.value) {+ return+ }+ }+ }+}++// compact drops tombstones once they dominate, but never while an iteration+// is walking the entry slice.+func (m *Map[K, V]) compact() {+ if m.iterating > 0 || m.deleted == 0 || m.deleted*2 < len(m.entries) {+ return+ }+ live := make([]entry[K, V], 0, len(m.index))+ for _, current := range m.entries {+ if !current.deleted {+ m.index[current.key] = len(live)+ live = append(live, current)+ }+ }+ m.entries = live+ m.deleted = 0+}diff --git a/internal/server/ordered/map_test.go b/internal/server/ordered/map_test.gonew file mode 100644index 00000000..c149cc69--- /dev/null+++ b/internal/server/ordered/map_test.go@@ -0,0 +1,79 @@+package ordered++import (+ "slices"+ "testing"+)++func TestMapKeepsInsertionOrderAndPositionOnSet(t *testing.T) {+ var m Map[string, int]+ m.Set("a", 1)+ m.Set("b", 2)+ m.Set("c", 3)+ m.Set("a", 10)+ if got := m.Keys(); !slices.Equal(got, []string{"a", "b", "c"}) {+ t.Fatalf("keys = %v", got)+ }+ if got := m.Values(); !slices.Equal(got, []int{10, 2, 3}) {+ t.Fatalf("values = %v", got)+ }+ m.MoveToBack("a", 11)+ if got := m.Keys(); !slices.Equal(got, []string{"b", "c", "a"}) {+ t.Fatalf("keys after MoveToBack = %v", got)+ }+ if value, ok := m.Get("a"); !ok || value != 11 || m.Len() != 3 {+ t.Fatalf("get a = %v %v len %d", value, ok, m.Len())+ }+}++func TestMapLiveIterationSkipsDeletedAndVisitsAppended(t *testing.T) {+ var m Map[string, int]+ for _, key := range []string{"a", "b", "c", "d"} {+ m.Set(key, len(key))+ }+ var visited []string+ for key := range m.All() {+ visited = append(visited, key)+ switch key {+ case "a":+ m.Delete("c") // deleted before its turn: skipped, like a JS Map+ case "b":+ m.Set("e", 1) // appended during iteration: visited+ }+ }+ if !slices.Equal(visited, []string{"a", "b", "d", "e"}) {+ t.Fatalf("visited = %v", visited)+ }+ if got := m.Keys(); !slices.Equal(got, []string{"a", "b", "d", "e"}) {+ t.Fatalf("keys = %v", got)+ }+}++func TestMapCompactionPreservesOrderAndIndex(t *testing.T) {+ var m Map[int, int]+ for index := 0; index < 100; index++ {+ m.Set(index, index)+ }+ for index := 0; index < 100; index += 2 {+ m.Delete(index)+ }+ if m.Len() != 50 || len(m.entries) > 60 {+ t.Fatalf("len %d entries %d", m.Len(), len(m.entries))+ }+ for index := 1; index < 100; index += 2 {+ if value, ok := m.Get(index); !ok || value != index {+ t.Fatalf("get %d = %v %v", index, value, ok)+ }+ }+ keys := m.Keys()+ if keys[0] != 1 || keys[49] != 99 || !slices.IsSorted(keys) {+ t.Fatalf("keys = %v", keys)+ }+ if m.Delete(1000) {+ t.Fatal("deleting an absent key must report false")+ }+ m.Clear()+ if m.Len() != 0 || len(m.Keys()) != 0 {+ t.Fatal("clear must empty the map")+ }+}diff --git a/internal/server/protocol/client.go b/internal/server/protocol/client.gonew file mode 100644index 00000000..b53f3078--- /dev/null+++ b/internal/server/protocol/client.go@@ -0,0 +1,698 @@+package protocol++import (+ "errors"+ "fmt"+)++// ClientMessage is one member of clientMessageSchema. The interface is sealed:+// only the message structs in this file implement it.+type ClientMessage interface {+ isClientMessage()+}++// AuthenticateHostMessage is the host member of authenticateMessageSchema.+type AuthenticateHostMessage struct {+ Type string `json:"type"`+ Protocol string `json:"protocol"`+ RoomID string `json:"roomId"`+ Role Role `json:"role"`+ Token string `json:"token"`+ ClientID string `json:"clientId"`+ ShareGeneration string `json:"shareGeneration,omitempty"`+ SharingPaused *bool `json:"sharingPaused,omitempty"`+ QualitySettings *QualitySettings `json:"qualitySettings,omitempty"`+ RoutePolicy RoutePolicy `json:"routePolicy"`+ ViewerPresence bool `json:"viewerPresence,omitempty"`+ DisplayName *DisplayName `json:"displayName,omitempty"`+}++// AuthenticateViewerMessage is the viewer member of authenticateMessageSchema.+type AuthenticateViewerMessage struct {+ Type string `json:"type"`+ Protocol string `json:"protocol"`+ RoomID string `json:"roomId"`+ Role Role `json:"role"`+ ClientID string `json:"clientId"`+ ViewerGrant string `json:"viewerGrant,omitempty"`+ ViewerPassword string `json:"viewerPassword,omitempty"`+ DisplayName *DisplayName `json:"displayName,omitempty"`+ ViewerPresence bool `json:"viewerPresence,omitempty"`+}++// SignalingChallengeMessage is { type: "signaling-challenge", sequence }.+type SignalingChallengeMessage struct {+ Type string `json:"type"`+ Sequence Int `json:"sequence"`+}++// ClientSignalMessage is the client "signal" message.+type ClientSignalMessage struct {+ Type string `json:"type"`+ TargetPeerID string `json:"targetPeerId,omitempty"`+ Payload SignalPayload `json:"payload"`+}++// ClientRestartRequestMessage is the client "restart-request" message.+type ClientRestartRequestMessage struct {+ Type string `json:"type"`+ TargetPeerID string `json:"targetPeerId,omitempty"`+ ConnectionID string `json:"connectionId"`+ Rebuild bool `json:"rebuild"`+}++// SetQualitySettingsMessage is { type: "set-quality-settings", qualitySettings }.+type SetQualitySettingsMessage struct {+ Type string `json:"type"`+ QualitySettings QualitySettings `json:"qualitySettings"`+}++// RelayCapacityMessage is { type: "relay-capacity", downstreamEdges }.+type RelayCapacityMessage struct {+ Type string `json:"type"`+ DownstreamEdges Int `json:"downstreamEdges"`+}++// RouteReadyMessage is { type: "route-ready", revision, phase, qualityApproved? }.+type RouteReadyMessage struct {+ Type string `json:"type"`+ Revision Int `json:"revision"`+ Phase string `json:"phase"`+ QualityApproved bool `json:"qualityApproved,omitempty"`+}++// RouteTransportConnectedMessage is the "route-transport-connected" message.+type RouteTransportConnectedMessage struct {+ Type string `json:"type"`+ Revision Int `json:"revision"`+ ConnectionID string `json:"connectionId"`+}++// RouteMediaUnavailableMessage is the "route-media-unavailable" message.+type RouteMediaUnavailableMessage struct {+ Type string `json:"type"`+ Revision Int `json:"revision"`+}++// RouteFailedMessage is { type: "route-failed", revision, phase, connectionId }.+type RouteFailedMessage struct {+ Type string `json:"type"`+ Revision Int `json:"revision"`+ Phase string `json:"phase"`+ ConnectionID *string `json:"connectionId"`+}++// RefreshSfuMessage is { type: "refresh-sfu", revision }.+type RefreshSfuMessage struct {+ Type string `json:"type"`+ Revision Int `json:"revision"`+}++// RequestRouteDiagnosticMessage is { type: "request-route-diagnostic" }.+type RequestRouteDiagnosticMessage struct {+ Type string `json:"type"`+}++// ViewerQualityEvidenceMessage is viewerQualityEvidenceMessageSchema.+type ViewerQualityEvidenceMessage struct {+ Type string `json:"type"`+ Guard ViewerQualityEvidenceGuard `json:"guard"`+ Sequence Int `json:"sequence"`+ WindowMs Int `json:"windowMs"`+ Metrics ViewerQualityEvidenceMetrics `json:"metrics"`+}++// SenderQualityEvidenceMessage is senderQualityEvidenceMessageSchema.+type SenderQualityEvidenceMessage struct {+ Type string `json:"type"`+ ChildPeerID string `json:"childPeerId"`+ ConnectionID string `json:"connectionId"`+ RtpStatsID *string `json:"rtpStatsId"`+ TrackIdentifier *string `json:"trackIdentifier"`+ SampleTimestampMs *Num `json:"sampleTimestampMs"`+ RouteRevision Int `json:"routeRevision"`+ State string `json:"state"`+ Diagnostics SenderQualityDiagnostics `json:"diagnostics"`+}++// SfuPublisherQualityEvidenceMessage is+// sfuPublisherQualityEvidenceMessageSchema.+type SfuPublisherQualityEvidenceMessage struct {+ Type string `json:"type"`+ PublicationGeneration string `json:"publicationGeneration"`+ RouteRevision Int `json:"routeRevision"`+ State string `json:"state"`+ SampleTimestampMs *Num `json:"sampleTimestampMs"`+ Diagnostics SenderQualityDiagnostics `json:"diagnostics"`+}++// ResetSenderQualityMessage is { type: "reset-sender-quality" }.+type ResetSenderQualityMessage struct {+ Type string `json:"type"`+}++// SetDisplayNameMessage is { type: "set-display-name", displayName }.+type SetDisplayNameMessage struct {+ Type string `json:"type"`+ DisplayName DisplayName `json:"displayName"`+}++// SetSharingPausedMessage is { type: "set-sharing-paused", shareGeneration, paused }.+type SetSharingPausedMessage struct {+ Type string `json:"type"`+ ShareGeneration string `json:"shareGeneration"`+ Paused bool `json:"paused"`+}++// StopSharingMessage is { type: "stop-sharing", shareGeneration? }.+type StopSharingMessage struct {+ Type string `json:"type"`+ ShareGeneration string `json:"shareGeneration,omitempty"`+}++// AbandonRoomMessage is { type: "abandon-room" }.+type AbandonRoomMessage struct {+ Type string `json:"type"`+}++func (AuthenticateHostMessage) isClientMessage() {}+func (AuthenticateViewerMessage) isClientMessage() {}+func (SignalingChallengeMessage) isClientMessage() {}+func (ClientSignalMessage) isClientMessage() {}+func (ClientRestartRequestMessage) isClientMessage() {}+func (SetQualitySettingsMessage) isClientMessage() {}+func (RelayCapacityMessage) isClientMessage() {}+func (RouteReadyMessage) isClientMessage() {}+func (RouteTransportConnectedMessage) isClientMessage() {}+func (RouteMediaUnavailableMessage) isClientMessage() {}+func (RouteFailedMessage) isClientMessage() {}+func (RefreshSfuMessage) isClientMessage() {}+func (RequestRouteDiagnosticMessage) isClientMessage() {}+func (ViewerQualityEvidenceMessage) isClientMessage() {}+func (SenderQualityEvidenceMessage) isClientMessage() {}+func (SfuPublisherQualityEvidenceMessage) isClientMessage() {}+func (ResetSenderQualityMessage) isClientMessage() {}+func (SetDisplayNameMessage) isClientMessage() {}+func (SetSharingPausedMessage) isClientMessage() {}+func (StopSharingMessage) isClientMessage() {}+func (AbandonRoomMessage) isClientMessage() {}++// DecodeClientMessage ports decodeClientMessage: JSON.parse followed by+// clientMessageSchema.parse. Every member of the union carries a distinct+// `type` literal, so the union is resolved by that key.+func DecodeClientMessage(data []byte) (ClientMessage, error) {+ messageType, err := typeOf(data, "type")+ if err != nil {+ return nil, err+ }+ switch messageType {+ case "authenticate":+ return decodeAuthenticate(data)+ case "signaling-challenge":+ return decodeSignalingChallenge(data)+ case "signal":+ return decodeClientSignal(data)+ case "restart-request":+ return decodeClientRestartRequest(data)+ case "set-quality-settings":+ return decodeSetQualitySettings(data)+ case "relay-capacity":+ return decodeRelayCapacity(data)+ case "route-ready":+ return decodeRouteReady(data)+ case "route-transport-connected":+ return decodeRouteTransportConnected(data)+ case "route-media-unavailable":+ return decodeRouteMediaUnavailable(data)+ case "route-failed":+ return decodeRouteFailed(data)+ case "refresh-sfu":+ return decodeRefreshSfu(data)+ case "request-route-diagnostic":+ return decodeEmptyClientMessage(data, RequestRouteDiagnosticMessage{Type: messageType})+ case "viewer-quality-evidence":+ return decodeViewerQualityEvidence(data)+ case "sender-quality-evidence":+ return decodeSenderQualityEvidence(data)+ case "sfu-publisher-quality-evidence":+ return decodeSfuPublisherQualityEvidence(data)+ case "reset-sender-quality":+ return decodeEmptyClientMessage(data, ResetSenderQualityMessage{Type: messageType})+ case "set-display-name":+ return decodeSetDisplayName(data)+ case "set-sharing-paused":+ return decodeSetSharingPaused(data)+ case "stop-sharing":+ return decodeStopSharing(data)+ case "abandon-room":+ return decodeEmptyClientMessage(data, AbandonRoomMessage{Type: messageType})+ }+ return nil, fmt.Errorf("unknown client message type %q", messageType)+}++func decodeEmptyClientMessage(data []byte, message ClientMessage) (ClientMessage, error) {+ var body struct {+ Type string `json:"type"`+ }+ present, err := decodeObject(data, &body)+ if err != nil {+ return nil, err+ }+ if err := present.require("type"); err != nil {+ return nil, err+ }+ return message, nil+}++func decodeAuthenticate(data []byte) (ClientMessage, error) {+ role, err := typeOf(data, "role")+ if err != nil {+ return nil, err+ }+ switch role {+ case RoleHost:+ var message AuthenticateHostMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "protocol", "roomId", "role", "token", "clientId"); err != nil {+ return nil, err+ }+ if err := present.optional("shareGeneration", "sharingPaused", "qualitySettings",+ "routePolicy", "viewerPresence", "displayName"); err != nil {+ return nil, err+ }+ if message.Protocol != SignalingProtocol {+ return nil, errors.New("protocol is not the current signaling generation")+ }+ if !ValidRoomCode(message.RoomID) {+ return nil, errors.New("roomId is not a room code")+ }+ if !ValidToken(message.Token) {+ return nil, errors.New("token is malformed")+ }+ if !ValidOpaqueID(message.ClientID) {+ return nil, errors.New("clientId is not an opaque id")+ }+ if present.has("shareGeneration") && !ValidOpaqueID(message.ShareGeneration) {+ return nil, errors.New("shareGeneration is not an opaque id")+ }+ if present.has("viewerPresence") && !message.ViewerPresence {+ return nil, errors.New("viewerPresence must be true when present")+ }+ if !present.has("routePolicy") {+ message.RoutePolicy = DefaultRoutePolicy+ }+ return message, nil+ case RoleViewer:+ var message AuthenticateViewerMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "protocol", "roomId", "role", "clientId"); err != nil {+ return nil, err+ }+ if err := present.optional(+ "viewerGrant", "viewerPassword", "displayName", "viewerPresence"); err != nil {+ return nil, err+ }+ if message.Protocol != SignalingProtocol {+ return nil, errors.New("protocol is not the current signaling generation")+ }+ if !ValidRoomCode(message.RoomID) {+ return nil, errors.New("roomId is not a room code")+ }+ if !ValidOpaqueID(message.ClientID) {+ return nil, errors.New("clientId is not an opaque id")+ }+ if present.has("viewerGrant") && !ValidViewerGrant(message.ViewerGrant) {+ return nil, errors.New("viewerGrant is malformed")+ }+ if present.has("viewerPassword") && !ValidViewerPassword(message.ViewerPassword) {+ return nil, errors.New("viewerPassword is malformed")+ }+ if present.has("viewerPresence") && !message.ViewerPresence {+ return nil, errors.New("viewerPresence must be true when present")+ }+ return message, nil+ }+ return nil, fmt.Errorf("unknown authenticate role %q", role)+}++func decodeSignalingChallenge(data []byte) (ClientMessage, error) {+ var message SignalingChallengeMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "sequence"); err != nil {+ return nil, err+ }+ if !inRangeInt(message.Sequence, 0, MaxSafeInteger) {+ return nil, errors.New("sequence is out of range")+ }+ return message, nil+}++func decodeClientSignal(data []byte) (ClientMessage, error) {+ var message ClientSignalMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "payload"); err != nil {+ return nil, err+ }+ if err := present.optional("targetPeerId"); err != nil {+ return nil, err+ }+ if present.has("targetPeerId") && !ValidOpaqueID(message.TargetPeerID) {+ return nil, errors.New("targetPeerId is not an opaque id")+ }+ return message, nil+}++func decodeClientRestartRequest(data []byte) (ClientMessage, error) {+ var message ClientRestartRequestMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "connectionId", "rebuild"); err != nil {+ return nil, err+ }+ if err := present.optional("targetPeerId"); err != nil {+ return nil, err+ }+ if present.has("targetPeerId") && !ValidOpaqueID(message.TargetPeerID) {+ return nil, errors.New("targetPeerId is not an opaque id")+ }+ if !ValidOpaqueID(message.ConnectionID) {+ return nil, errors.New("connectionId is not an opaque id")+ }+ return message, nil+}++func decodeSetQualitySettings(data []byte) (ClientMessage, error) {+ var message SetQualitySettingsMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "qualitySettings"); err != nil {+ return nil, err+ }+ return message, nil+}++func decodeRelayCapacity(data []byte) (ClientMessage, error) {+ var message RelayCapacityMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "downstreamEdges"); err != nil {+ return nil, err+ }+ if !inRangeInt(message.DownstreamEdges, 0, MaxEndpointMediaCopyCapacity) {+ return nil, errors.New("downstreamEdges is out of range")+ }+ return message, nil+}++func decodeRouteReady(data []byte) (ClientMessage, error) {+ var message RouteReadyMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "revision", "phase"); err != nil {+ return nil, err+ }+ if err := present.optional("qualityApproved"); err != nil {+ return nil, err+ }+ if !validRevision(message.Revision) {+ return nil, errors.New("revision is out of range")+ }+ if !enumOf(message.Phase, mediaRoutePhases...) {+ return nil, fmt.Errorf("unknown phase %q", message.Phase)+ }+ if present.has("qualityApproved") && !message.QualityApproved {+ return nil, errors.New("qualityApproved must be true when present")+ }+ return message, nil+}++func decodeRouteTransportConnected(data []byte) (ClientMessage, error) {+ var message RouteTransportConnectedMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "revision", "connectionId"); err != nil {+ return nil, err+ }+ if !validRevision(message.Revision) {+ return nil, errors.New("revision is out of range")+ }+ if !ValidOpaqueID(message.ConnectionID) {+ return nil, errors.New("connectionId is not an opaque id")+ }+ return message, nil+}++func decodeRouteMediaUnavailable(data []byte) (ClientMessage, error) {+ var message RouteMediaUnavailableMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "revision"); err != nil {+ return nil, err+ }+ if !validRevision(message.Revision) {+ return nil, errors.New("revision is out of range")+ }+ return message, nil+}++func decodeRouteFailed(data []byte) (ClientMessage, error) {+ var message RouteFailedMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "revision", "phase"); err != nil {+ return nil, err+ }+ if err := present.requireNullable("connectionId"); err != nil {+ return nil, err+ }+ if !validRevision(message.Revision) {+ return nil, errors.New("revision is out of range")+ }+ if !enumOf(message.Phase, mediaRoutePhases...) {+ return nil, fmt.Errorf("unknown phase %q", message.Phase)+ }+ if message.ConnectionID != nil && !ValidOpaqueID(*message.ConnectionID) {+ return nil, errors.New("connectionId is not an opaque id")+ }+ return message, nil+}++func decodeRefreshSfu(data []byte) (ClientMessage, error) {+ var message RefreshSfuMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "revision"); err != nil {+ return nil, err+ }+ if !validRevision(message.Revision) {+ return nil, errors.New("revision is out of range")+ }+ return message, nil+}++func decodeViewerQualityEvidence(data []byte) (ClientMessage, error) {+ var message ViewerQualityEvidenceMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "guard", "sequence", "windowMs", "metrics"); err != nil {+ return nil, err+ }+ if err := validateEvidenceWindow(message.Sequence, message.WindowMs); err != nil {+ return nil, err+ }+ return message, nil+}++func validateEvidenceWindow(sequence, windowMs Int) error {+ if !inRangeInt(sequence, 0, MaxSafeInteger) {+ return errors.New("sequence is out of range")+ }+ if !inRangeInt(windowMs, 1_000, 5_000) {+ return errors.New("windowMs is out of range")+ }+ return nil+}++func decodeSenderQualityEvidence(data []byte) (ClientMessage, error) {+ var message SenderQualityEvidenceMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "childPeerId", "connectionId", "routeRevision",+ "state", "diagnostics"); err != nil {+ return nil, err+ }+ if err := present.requireNullable(+ "rtpStatsId", "trackIdentifier", "sampleTimestampMs"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(message.ChildPeerID) || !ValidOpaqueID(message.ConnectionID) {+ return nil, errors.New("sender quality evidence ids are not opaque ids")+ }+ if err := boundedIdentity(message.RtpStatsID, "rtpStatsId"); err != nil {+ return nil, err+ }+ if err := boundedIdentity(message.TrackIdentifier, "trackIdentifier"); err != nil {+ return nil, err+ }+ if message.SampleTimestampMs != nil &&+ !inRangeNum(*message.SampleTimestampMs, 0, MaxSafeInteger) {+ return nil, errors.New("sampleTimestampMs is out of range")+ }+ if !validRevision(message.RouteRevision) {+ return nil, errors.New("routeRevision is out of range")+ }+ if !enumOf(message.State, senderQualityStates...) {+ return nil, fmt.Errorf("unknown sender quality state %q", message.State)+ }+ // superRefine: known sender quality needs exact RTP identity.+ if message.State != "unknown" &&+ (message.RtpStatsID == nil || message.TrackIdentifier == nil ||+ message.SampleTimestampMs == nil) {+ return nil, errors.New("Known sender quality needs exact RTP identity")+ }+ if err := senderQualityReasonMatchesState(+ message.State, message.Diagnostics.Reason,+ "Sender quality reason must match its native state"); err != nil {+ return nil, err+ }+ return message, nil+}++func decodeSfuPublisherQualityEvidence(data []byte) (ClientMessage, error) {+ var message SfuPublisherQualityEvidenceMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require(+ "type", "publicationGeneration", "routeRevision", "state", "diagnostics"); err != nil {+ return nil, err+ }+ if err := present.requireNullable("sampleTimestampMs"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(message.PublicationGeneration) {+ return nil, errors.New("publicationGeneration is not an opaque id")+ }+ if !validRevision(message.RouteRevision) {+ return nil, errors.New("routeRevision is out of range")+ }+ if !enumOf(message.State, senderQualityStates...) {+ return nil, fmt.Errorf("unknown sfu publisher quality state %q", message.State)+ }+ if message.SampleTimestampMs != nil &&+ !inRangeNum(*message.SampleTimestampMs, 0, MaxSafeInteger) {+ return nil, errors.New("sampleTimestampMs is out of range")+ }+ // superRefine: known SFU publisher quality needs an exact sample.+ if message.State != "unknown" && message.SampleTimestampMs == nil {+ return nil, errors.New("Known SFU publisher quality needs an exact sample")+ }+ if err := senderQualityReasonMatchesState(+ message.State, message.Diagnostics.Reason,+ "SFU publisher reason must match its native state"); err != nil {+ return nil, err+ }+ return message, nil+}++func senderQualityReasonMatchesState(state string, reason *string, message string) error {+ value := ""+ if reason != nil {+ value = *reason+ }+ invalid := (state == "healthy" && value != "none") ||+ (state == "degraded" && value != "bandwidth" && value != "cpu") ||+ (state == "unknown" && reason != nil)+ if invalid {+ return errors.New(message)+ }+ return nil+}++func boundedIdentity(value *string, key string) error {+ if value == nil {+ return nil+ }+ if length := UTF16Length(*value); length < 1 || length > 256 {+ return fmt.Errorf("%s length is out of range", key)+ }+ return nil+}++func decodeSetDisplayName(data []byte) (ClientMessage, error) {+ var message SetDisplayNameMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "displayName"); err != nil {+ return nil, err+ }+ return message, nil+}++func decodeSetSharingPaused(data []byte) (ClientMessage, error) {+ var message SetSharingPausedMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "shareGeneration", "paused"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(message.ShareGeneration) {+ return nil, errors.New("shareGeneration is not an opaque id")+ }+ return message, nil+}++func decodeStopSharing(data []byte) (ClientMessage, error) {+ var message StopSharingMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type"); err != nil {+ return nil, err+ }+ if err := present.optional("shareGeneration"); err != nil {+ return nil, err+ }+ if present.has("shareGeneration") && !ValidOpaqueID(message.ShareGeneration) {+ return nil, errors.New("shareGeneration is not an opaque id")+ }+ return message, nil+}diff --git a/internal/server/protocol/codec.go b/internal/server/protocol/codec.gonew file mode 100644index 00000000..60381cac--- /dev/null+++ b/internal/server/protocol/codec.go@@ -0,0 +1,206 @@+package protocol++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "math"+)++// fields holds the raw members of one JSON object. Validation reads it to tell+// "absent" from "null" the way zod's .optional() / .nullable() pair does, which+// encoding/json alone cannot express. Duplicate keys collapse to the last+// occurrence, matching JSON.parse.+type fields map[string]json.RawMessage++// decodeObject decodes one strict (zod `.strict()`) object: unknown keys are+// rejected and the raw member map is returned for presence checks.+func decodeObject(data []byte, target any) (fields, error) {+ var raw fields+ if err := json.Unmarshal(data, &raw); err != nil {+ return nil, err+ }+ // JSON.parse keeps only the last occurrence of a duplicate key, so the+ // earlier ones must never reach the strict decode. Re-encoding the member+ // map drops them.+ // ponytail: one extra marshal per object; skip it behind a duplicate-key+ // scan if signaling ever shows up in a profile.+ canonical, err := json.Marshal(raw)+ if err != nil {+ return nil, err+ }+ decoder := json.NewDecoder(bytes.NewReader(canonical))+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(target); err != nil {+ return nil, err+ }+ return raw, nil+}++// marshalJSON encodes without HTML escaping, because JSON.stringify leaves+// "<", ">" and "&" alone and display names may carry them. The encoder's+// trailing newline is dropped.+func marshalJSON(value any) ([]byte, error) {+ var buffer bytes.Buffer+ encoder := json.NewEncoder(&buffer)+ encoder.SetEscapeHTML(false)+ if err := encoder.Encode(value); err != nil {+ return nil, err+ }+ return bytes.TrimSuffix(buffer.Bytes(), []byte("\n")), nil+}++func (f fields) has(key string) bool {+ _, ok := f[key]+ return ok+}++func (f fields) isNull(key string) bool {+ raw, ok := f[key]+ return ok && string(bytes.TrimSpace(raw)) == "null"+}++// require mirrors a plain required zod field: present and not null.+func (f fields) require(keys ...string) error {+ for _, key := range keys {+ if !f.has(key) {+ return fmt.Errorf("%s is required", key)+ }+ if f.isNull(key) {+ return fmt.Errorf("%s must not be null", key)+ }+ }+ return nil+}++// requireNullable mirrors `.nullable()` without `.optional()`: the key must be+// present but may be null.+func (f fields) requireNullable(keys ...string) error {+ for _, key := range keys {+ if !f.has(key) {+ return fmt.Errorf("%s is required", key)+ }+ }+ return nil+}++// optional mirrors `.optional()` without `.nullable()`: null is rejected, an+// absent key is not.+func (f fields) optional(keys ...string) error {+ for _, key := range keys {+ if f.isNull(key) {+ return fmt.Errorf("%s must not be null", key)+ }+ }+ return nil+}++// Int is a JSON number restricted to an integral value, mirroring zod's+// z.number().int(): 5.0 is an integer, 5.5 is not, and values outside the safe+// integer range are rejected (zod 4 rejects them too, and every `.int()` field+// in the contract is bounded by MAX_SAFE_INTEGER anyway).+type Int int64++// UnmarshalJSON implements json.Unmarshaler.+func (v *Int) UnmarshalJSON(data []byte) error {+ var number float64+ if err := json.Unmarshal(data, &number); err != nil {+ return err+ }+ if math.IsNaN(number) || math.IsInf(number, 0) ||+ number != math.Trunc(number) ||+ number < -MaxSafeInteger || number > MaxSafeInteger {+ return fmt.Errorf("%s is not a safe integer", string(data))+ }+ *v = Int(number)+ return nil+}++// Num is a JSON number restricted to a finite value, mirroring zod's+// z.number().finite().+type Num float64++// UnmarshalJSON implements json.Unmarshaler.+func (v *Num) UnmarshalJSON(data []byte) error {+ var number float64+ if err := json.Unmarshal(data, &number); err != nil {+ return err+ }+ if math.IsNaN(number) || math.IsInf(number, 0) {+ return fmt.Errorf("%s is not finite", string(data))+ }+ *v = Num(number)+ return nil+}++// Nullable carries a value that is both `.nullable()` and `.optional()`, so the+// three wire states (absent, null, value) survive a decode/encode round trip.+type Nullable[T any] struct {+ Set bool+ Value *T+}++// IsZero reports whether the key was absent, so `omitzero` drops it.+func (n Nullable[T]) IsZero() bool { return !n.Set }++// MarshalJSON implements json.Marshaler.+func (n Nullable[T]) MarshalJSON() ([]byte, error) {+ if n.Value == nil {+ return []byte("null"), nil+ }+ return marshalJSON(*n.Value)+}++// UnmarshalJSON implements json.Unmarshaler.+func (n *Nullable[T]) UnmarshalJSON(data []byte) error {+ n.Set = true+ n.Value = nil+ if string(bytes.TrimSpace(data)) == "null" {+ return nil+ }+ var value T+ if err := json.Unmarshal(data, &value); err != nil {+ return err+ }+ n.Value = &value+ return nil+}++// errUnknownVariant is the shared "no union member matched" failure.+var errUnknownVariant = errors.New("no matching message variant")++func enumOf(value string, allowed ...string) bool {+ for _, candidate := range allowed {+ if value == candidate {+ return true+ }+ }+ return false+}++func inRangeInt(value Int, minimum, maximum int64) bool {+ return int64(value) >= minimum && int64(value) <= maximum+}++func inRangeNum(value Num, minimum, maximum float64) bool {+ return float64(value) >= minimum && float64(value) <= maximum+}++// typeOf reads the union discriminator without imposing strictness, the way+// zod tries each member of z.union / z.discriminatedUnion.+func typeOf(data []byte, key string) (string, error) {+ var probe map[string]json.RawMessage+ if err := json.Unmarshal(data, &probe); err != nil {+ return "", err+ }+ raw, ok := probe[key]+ if !ok {+ return "", errUnknownVariant+ }+ var value string+ if err := json.Unmarshal(raw, &value); err != nil {+ return "", errUnknownVariant+ }+ return value, nil+}diff --git a/internal/server/protocol/constants.go b/internal/server/protocol/constants.gonew file mode 100644index 00000000..9315642f--- /dev/null+++ b/internal/server/protocol/constants.go@@ -0,0 +1,75 @@+// Package protocol is the Go owner of the Screener wire contract. It mirrors+// src/shared/protocol.ts (zod schemas) plus the four shared scalar helpers+// (media-copy-accounting.ts, nat-candidate.ts, packet-loss.ts,+// video-codec-evidence.ts). The package performs no I/O and imports nothing+// from other internal packages.+package protocol++// MaxSafeInteger is JavaScript's Number.MAX_SAFE_INTEGER.+const MaxSafeInteger = 9007199254740991++// Limits and identifiers mirrored from src/shared/protocol.ts.+const (+ MaxViewersPerRoomLimit = 20+ MaxParticipantsPerRoomLimit = MaxViewersPerRoomLimit + 1+ MaxSignalBytes = 64 * 1024+ SignalingProtocol = "screener-v21"+ RoomCodeLength = 4+ MaxMediaRouteRevision = MaxSafeInteger+ MaxSfuTokenLength = 8 * 1024+ MaxIceServerURLs = 8++ MaxNatPredictionAuxiliaryStunURLs = 2++ MaxViewerQualityEvidenceBytes = 2 * 1024+ ViewerQualityEvidenceIntervalMs = 2_000+ ViewerQualityEvidenceExpiryMs = 5_000+ PersistentNativeEdgeDegradedWindows = 3++ MaxDisplayNameCodePoints = 24+ DefaultViewerDisplayName = "观众"+ DefaultHostDisplayNamePrefix = "分享者"++ MinViewerPasswordLength = 1+ MaxViewerPasswordLength = 64++ // MaxStunURLLength is stunUrlSchema's .max(512), in UTF-16 code units.+ MaxStunURLLength = 512+)++// Endpoint media copy accounting bounds, from src/shared/media-copy-accounting.ts.+const (+ DefaultEndpointMediaCopyCapacity = 2+ MaxEndpointMediaCopyCapacity = 3+)++// SignalCloseCode is one of SIGNAL_CLOSE_CODES.+type SignalCloseCode int++// SIGNAL_CLOSE_CODES.+const (+ SignalCloseServiceRestart SignalCloseCode = 1012+ SignalCloseSessionReplaced SignalCloseCode = 4001+ SignalCloseClientReconnect SignalCloseCode = 4002+ SignalCloseAuthenticationFailed SignalCloseCode = 4003+ SignalCloseViewerAccessRevoked SignalCloseCode = 4004+)++// NatTraversalPaths mirrors NAT_TRAVERSAL_PATHS in src/shared/nat-candidate.ts.+var NatTraversalPaths = [...]string{"unknown", "ordinary", "predicted"}++// DefaultQualitySettings mirrors DEFAULT_QUALITY_SETTINGS.+var DefaultQualitySettings = QualitySettings{+ Resolution: "1080p",+ MaxFramerate: 30,+ MaxBitrate: 5_000_000,+ DegradationPreference: "balanced",+ ScreenAudioQuality: "music",+}++// DefaultRoutePolicy mirrors DEFAULT_ROUTE_POLICY.+var DefaultRoutePolicy = RoutePolicy{+ PeerOnly: false,+ TopologyOptimization: true,+ NatPrediction: false,+}diff --git a/internal/server/protocol/contract_test.go b/internal/server/protocol/contract_test.gonew file mode 100644index 00000000..b72438fb--- /dev/null+++ b/internal/server/protocol/contract_test.go@@ -0,0 +1,659 @@+package protocol++import (+ "bytes"+ "encoding/json"+ "fmt"+ "strings"+ "testing"+)++// member is one JSON object key with its raw encoded value, so the tests can+// reproduce the exact wire shapes from tests/protocol.test.ts (including key+// presence, which a Go map cannot express).+type member struct {+ key string+ raw string+}++func object(members []member) []byte {+ var builder strings.Builder+ builder.WriteByte('{')+ for index, entry := range members {+ if index > 0 {+ builder.WriteByte(',')+ }+ fmt.Fprintf(&builder, "%q:%s", entry.key, entry.raw)+ }+ builder.WriteByte('}')+ return []byte(builder.String())+}++func with(base []member, changes ...member) []member {+ out := append([]member(nil), base...)+ for _, change := range changes {+ replaced := false+ for index := range out {+ if out[index].key == change.key {+ out[index] = change+ replaced = true+ break+ }+ }+ if !replaced {+ out = append(out, change)+ }+ }+ return out+}++func drop(base []member, keys ...string) []member {+ out := make([]member, 0, len(base))+ for _, entry := range base {+ remove := false+ for _, key := range keys {+ if entry.key == key {+ remove = true+ }+ }+ if !remove {+ out = append(out, entry)+ }+ }+ return out+}++const (+ testAssignmentNone = `{"upstream":{"kind":"none"},"childPeerIds":[],` ++ `"sfuPublicationGeneration":null}`+ testQualitySettings = `{"resolution":"1080p","maxFramerate":60,"maxBitrate":8000000,` ++ `"degradationPreference":"maintain-resolution"}`+ testRoutePolicy = `{"peerOnly":false,"topologyOptimization":true,"natPrediction":false}`+ testIceConfig = `{"iceServers":[],"natPredictionStunUrls":[]}`+)++func authenticatedHost() []member {+ return []member{+ {"type", `"authenticated"`},+ {"protocol", `"screener-v21"`},+ {"peerId", `"host_12345678"`},+ {"roomExpiresAt", `"2026-08-18T18:00:00.000Z"`},+ {"maxViewers", `8`},+ {"endpointMediaCopyCapacity", `2`},+ {"hostOnline", `true`},+ {"connectionId", `null`},+ {"iceConfig", testIceConfig},+ {"routePolicy", testRoutePolicy},+ {"codeEntryPolicy", `"open"`},+ {"viewerAuthorizationGeneration", `"viewer_generation_12345678"`},+ {"mediaMode", `"peer-assisted"`},+ {"shareGeneration", `"share_generation_12345678"`},+ {"routeRevision", `0`},+ {"routeAssignment", testAssignmentNone},+ {"qualitySettings", testQualitySettings},+ {"role", `"host"`},+ {"viewerPasswordEnabled", `false`},+ }+}++func assertServerMessage(t *testing.T, name string, data []byte, want bool) {+ t.Helper()+ t.Run(name, func(t *testing.T) {+ _, err := DecodeServerMessage(data)+ if want && err != nil {+ t.Fatalf("expected %s to decode, got %v", data, err)+ }+ if !want && err == nil {+ t.Fatalf("expected %s to be rejected", data)+ }+ })+}++func assertClientMessage(t *testing.T, name string, data []byte, want bool) {+ t.Helper()+ t.Run(name, func(t *testing.T) {+ _, err := DecodeClientMessage(data)+ if want && err != nil {+ t.Fatalf("expected %s to decode, got %v", data, err)+ }+ if !want && err == nil {+ t.Fatalf("expected %s to be rejected", data)+ }+ })+}++// "accepts dynamic viewer limits within the protocol boundary" and+// "rejects viewer limit %s outside the protocol boundary".+func TestAuthenticatedViewerLimits(t *testing.T) {+ for _, sample := range []struct {+ raw string+ want bool+ }{{`1`, true}, {`8`, true}, {`20`, true}, {`0`, false}, {`1.5`, false}, {`21`, false}} {+ assertServerMessage(t, "maxViewers "+sample.raw,+ object(with(authenticatedHost(), member{"maxViewers", sample.raw})), sample.want)+ }+}++// "requires the authenticated endpoint capacity to be 1, 2, or 3".+func TestAuthenticatedEndpointCapacity(t *testing.T) {+ for _, sample := range []struct {+ raw string+ want bool+ }{{`1`, true}, {`2`, true}, {`3`, true}, {`0`, false}, {`4`, false}, {`1.5`, false}} {+ assertServerMessage(t, "capacity "+sample.raw,+ object(with(authenticatedHost(),+ member{"endpointMediaCopyCapacity", sample.raw})), sample.want)+ }+ assertServerMessage(t, "capacity absent",+ object(drop(authenticatedHost(), "endpointMediaCopyCapacity")), false)+}++// "scopes password configuration state to authenticated Hosts".+func TestAuthenticatedPasswordStateIsHostScoped(t *testing.T) {+ assertServerMessage(t, "host carries the flag", object(authenticatedHost()), true)+ assertServerMessage(t, "host without the flag",+ object(drop(authenticatedHost(), "viewerPasswordEnabled")), false)++ viewer := drop(with(authenticatedHost(),+ member{"role", `"viewer"`}, member{"peerId", `"viewer_12345678"`}),+ "viewerPasswordEnabled")+ assertServerMessage(t, "viewer without the flag", object(viewer), true)+ assertServerMessage(t, "viewer with the flag",+ object(with(viewer, member{"viewerPasswordEnabled", `true`})), false)+ assertServerMessage(t, "viewer with hostPaused",+ object(with(viewer, member{"hostPaused", `true`})), true)+}++// "represents persistent rooms without a room expiry" and the revision bound.+func TestAuthenticatedRoomLifetimeAndRevision(t *testing.T) {+ assertServerMessage(t, "no expiry",+ object(with(authenticatedHost(), member{"roomExpiresAt", `null`})), true)+ assertServerMessage(t, "revision at the ceiling",+ object(with(authenticatedHost(), member{"routeRevision", `9007199254740991`})), true)+ assertServerMessage(t, "revision past the ceiling",+ object(with(authenticatedHost(), member{"routeRevision", `9007199254740992`})), false)+ assertServerMessage(t, "absent route assignment",+ object(drop(authenticatedHost(), "routeAssignment")), false)+ assertServerMessage(t, "absent media mode",+ object(drop(authenticatedHost(), "mediaMode")), false)+ assertServerMessage(t, "sfu standby url",+ object(with(authenticatedHost(),+ member{"sfuStandbyUrl", `"wss://sfu.example.test"`})), true)+ assertServerMessage(t, "sfu standby url over https",+ object(with(authenticatedHost(),+ member{"sfuStandbyUrl", `"https://sfu.example.test"`})), false)+ assertServerMessage(t, "quality settings past the bitrate ceiling",+ object(with(authenticatedHost(), member{"qualitySettings",+ `{"resolution":"1080p","maxFramerate":60,"maxBitrate":20000000,` ++ `"degradationPreference":"maintain-resolution"}`})), false)+}++// "accepts only STUN URLs in the authenticated peer ICE config" and+// "requires the v20 NAT observation configuration".+func TestAuthenticatedIceConfig(t *testing.T) {+ for _, sample := range []struct {+ name string+ raw string+ want bool+ }{+ {"empty", `{"iceServers":[],"natPredictionStunUrls":[]}`, true},+ {"one stun url", `{"iceServers":[{"urls":"stun:stun.example.test:3478"}],` ++ `"natPredictionStunUrls":[]}`, true},+ {"a list of stun urls", `{"iceServers":[{"urls":["stun:a.example.test:3478",` ++ `"stun:b.example.test:3478"]}],"natPredictionStunUrls":[]}`, true},+ {"missing nat prediction urls", `{"iceServers":[]}`, false},+ {"turn url", `{"iceServers":[{"urls":"turn:relay.example.test:3478?transport=udp"}],` ++ `"natPredictionStunUrls":[]}`, false},+ {"turn credentials", `{"iceServers":[{"urls":"turn:relay.example.test:3478",` ++ `"username":"1787076000","credential":"credential"}],` ++ `"natPredictionStunUrls":[]}`, false},+ {"stuns url", `{"iceServers":[{"urls":"stuns:stun.example.test:5349"}],` ++ `"natPredictionStunUrls":[]}`, false},+ {"too many nat prediction urls", `{"iceServers":[],"natPredictionStunUrls":` ++ `["stun:a.example.test:3478","stun:b.example.test:3478",` ++ `"stun:c.example.test:3478"]}`, false},+ } {+ assertServerMessage(t, "iceConfig "+sample.name,+ object(with(authenticatedHost(), member{"iceConfig", sample.raw})), sample.want)+ }+}++// "keeps Viewer route status as a strict crossed union".+func TestRouteStatusCrossedUnion(t *testing.T) {+ for _, sample := range []struct {+ name string+ raw string+ want bool+ }{+ {"waiting on admission",+ `{"type":"route-status","revision":3,"state":"waiting","reason":"sfu-admission"}`, true},+ {"failed on exhaustion",+ `{"type":"route-status","revision":4,"state":"failed","reason":"route-exhausted"}`, true},+ {"waiting on exhaustion",+ `{"type":"route-status","revision":3,"state":"waiting","reason":"route-exhausted"}`, false},+ {"failed on admission",+ `{"type":"route-status","revision":3,"state":"failed","reason":"sfu-admission"}`, false},+ {"with a retry hint",+ `{"type":"route-status","revision":3,"state":"waiting","reason":"sfu-admission",` ++ `"retryAfterMs":1000}`, false},+ {"with a peer id",+ `{"type":"route-status","revision":3,"state":"waiting","reason":"sfu-admission",` ++ `"peerId":"private-peer-id"}`, false},+ } {+ assertServerMessage(t, sample.name, []byte(sample.raw), sample.want)+ }+}++// "accepts a strict, unique and bounded Viewer presence snapshot".+func TestViewerPresence(t *testing.T) {+ const viewer = `{"role":"viewer","peerId":"viewer_12345678","displayName":"小明",` ++ `"upstream":{"kind":"peer","peerId":"viewer_parent_12345678"}}`+ for _, sample := range []struct {+ name string+ raw string+ want bool+ }{+ {"sfu upstream with mediaReady",+ `{"type":"viewer-presence","viewers":[{"role":"viewer","peerId":"viewer_12345678",` ++ `"displayName":"小明","upstream":{"kind":"sfu"},"mediaReady":true}]}`, true},+ {"mediaReady false", `{"type":"viewer-presence","viewers":[{"role":"viewer",` ++ `"peerId":"viewer_12345678","displayName":"小明",` ++ `"upstream":{"kind":"peer","peerId":"viewer_parent_12345678"},` ++ `"mediaReady":false}]}`, false},+ {"duplicate peer ids",+ `{"type":"viewer-presence","viewers":[` + viewer + `,` + viewer + `]}`, false},+ {"leaked topology", `{"type":"viewer-presence","viewers":[{"role":"viewer",` ++ `"peerId":"viewer_12345678","displayName":"小明",` ++ `"upstream":{"kind":"none"},"mediaTopology":"peer-relay"}]}`, false},+ {"leaked address", `{"type":"viewer-presence","viewers":[{"role":"viewer",` ++ `"peerId":"viewer_12345678","displayName":"小明",` ++ `"upstream":{"kind":"none"},"ip":"203.0.113.1"}]}`, false},+ {"host entry", `{"type":"viewer-presence","viewers":[` + viewer + `,` ++ `{"role":"host","peerId":"host_12345678","displayName":"分享者",` ++ `"upstream":{"kind":"none"}}]}`, true},+ {"host entry with an upstream", `{"type":"viewer-presence","viewers":[` ++ `{"role":"host","peerId":"host_12345678","displayName":"分享者",` ++ `"upstream":{"kind":"sfu"}}]}`, false},+ {"host entry with mediaReady", `{"type":"viewer-presence","viewers":[` ++ `{"role":"host","peerId":"host_12345678","displayName":"分享者",` ++ `"upstream":{"kind":"none"},"mediaReady":true}]}`, false},+ } {+ assertServerMessage(t, sample.name, []byte(sample.raw), sample.want)+ }+}++func TestViewerPresenceConstructors(t *testing.T) {+ host := HostPresenceEntry("host_12345678", "分享者")+ if host.Upstream != NoUpstream() || host.MediaReady {+ t.Fatalf("host presence entry must carry {kind:\"none\"} and no mediaReady: %+v", host)+ }+ encoded, err := marshalJSON(NewViewerPresenceEntry(+ "viewer_12345678", "小明", SfuUpstream(), false))+ if err != nil {+ t.Fatal(err)+ }+ if bytes.Contains(encoded, []byte("mediaReady")) {+ t.Fatalf("mediaReady must be omitted when false: %s", encoded)+ }+ encoded, err = marshalJSON(NewViewerPresenceEntry(+ "viewer_12345678", "小明", SfuUpstream(), true))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Contains(encoded, []byte(`"mediaReady":true`)) {+ t.Fatalf("mediaReady must be emitted when true: %s", encoded)+ }+}++// "accepts only the privacy-safe route snapshot payload" plus the superRefine.+func TestRouteDiagnosticSnapshot(t *testing.T) {+ const childOne = `{"ordinal":1,"parent":{"kind":"host"},"effectiveCapacity":2,` ++ `"childCount":1,"demandAgeMs":100,"queueWaitMs":10,"candidateStartMs":20,` ++ `"firstDecodedFrameMs":80,"finalMs":80,"finalRoute":"direct","rejectionBucket":"none",` ++ `"quality":{"eligibleWindows":3,"eligibleDurationMs":6000,"freezeWindows":1,` ++ `"freezeCount":1,"freezeDurationMs":250,"pauseCount":0,"pauseDurationMs":0}}`+ childTwo := func(parent string) string {+ return `{"ordinal":2,"parent":` + parent + `,"effectiveCapacity":0,"childCount":0,` ++ `"demandAgeMs":90,"queueWaitMs":null,"candidateStartMs":null,` ++ `"firstDecodedFrameMs":null,"finalMs":null,"finalRoute":"waiting",` ++ `"rejectionBucket":"sfu-admission","quality":null}`+ }+ snapshot := func(children, operation string) []byte {+ return []byte(`{"type":"route-diagnostic-snapshot","snapshot":{"children":` ++ children + `,"operation":` + operation + `}}`)+ }+ const operation = `{"childOrdinal":2,"reason":"join","stage":"admission",` ++ `"cursor":1,"candidateCount":2}`++ assertServerMessage(t, "full snapshot",+ snapshot(`[`+childOne+`,`+childTwo(`{"kind":"viewer","ordinal":1}`)+`]`, operation), true)+ assertServerMessage(t, "empty snapshot", snapshot(`[]`, `null`), true)+ assertServerMessage(t, "leaked peer id",+ []byte(`{"type":"route-diagnostic-snapshot","snapshot":{"children":[],`++ `"operation":null,"peerId":"viewer_private_12345678"}}`), false)+ assertServerMessage(t, "leaked connection id",+ snapshot(`[{"ordinal":1,"parent":{"kind":"host"},"effectiveCapacity":2,"childCount":1,`++ `"demandAgeMs":100,"queueWaitMs":10,"candidateStartMs":20,`++ `"firstDecodedFrameMs":80,"finalMs":80,"finalRoute":"direct",`++ `"rejectionBucket":"none","quality":null,`++ `"connectionId":"connection_private_12345678"}]`, `null`), false)+ assertServerMessage(t, "negative freeze count",+ snapshot(`[{"ordinal":1,"parent":{"kind":"host"},"effectiveCapacity":2,"childCount":1,`++ `"demandAgeMs":100,"queueWaitMs":10,"candidateStartMs":20,`++ `"firstDecodedFrameMs":80,"finalMs":80,"finalRoute":"direct",`++ `"rejectionBucket":"none","quality":{"eligibleWindows":3,`++ `"eligibleDurationMs":6000,"freezeWindows":1,"freezeCount":-1,`++ `"freezeDurationMs":250,"pauseCount":0,"pauseDurationMs":0}}]`, `null`), false)+ assertServerMessage(t, "self parent",+ snapshot(`[`+childOne+`,`+childTwo(`{"kind":"viewer","ordinal":2}`)+`]`, `null`), false)+ assertServerMessage(t, "unknown parent ordinal",+ snapshot(`[`+childOne+`,`+childTwo(`{"kind":"viewer","ordinal":7}`)+`]`, `null`), false)+ assertServerMessage(t, "duplicate ordinals",+ snapshot(`[`+childOne+`,`+childOne+`]`, `null`), false)+ assertServerMessage(t, "operation names an absent child",+ snapshot(`[`+childOne+`]`, operation), false)+ assertServerMessage(t, "cursor past the candidate count",+ snapshot(`[`+childOne+`,`+childTwo(`{"kind":"viewer","ordinal":1}`)+`]`,+ `{"childOrdinal":2,"reason":"join","stage":"admission","cursor":2,`++ `"candidateCount":2}`), false)+ assertServerMessage(t, "raw rejection bucket on the operation",+ snapshot(`[`+childOne+`,`+childTwo(`{"kind":"viewer","ordinal":1}`)+`]`,+ `{"childOrdinal":2,"reason":"join","stage":"admission","cursor":1,`++ `"candidateCount":2,"rejectionBucket":"raw-error"}`), false)+ assertServerMessage(t, "parent ordinal on a host parent",+ snapshot(`[{"ordinal":1,"parent":{"kind":"host","ordinal":1},"effectiveCapacity":2,`++ `"childCount":1,"demandAgeMs":null,"queueWaitMs":null,"candidateStartMs":null,`++ `"firstDecodedFrameMs":null,"finalMs":null,"finalRoute":"direct",`++ `"rejectionBucket":"none","quality":null}]`, `null`), false)+}++// "keeps route messages strict alongside the single authenticated mode" and+// "accepts every bounded hybrid upstream shape".+func TestParticipantRouteAssignment(t *testing.T) {+ routeUpdate := func(assignment string) []byte {+ return []byte(`{"type":"route-update","revision":9,"phase":"active","assignment":` ++ assignment + `}`)+ }+ for _, sample := range []struct {+ name string+ assignment string+ want bool+ }{+ {"no upstream", testAssignmentNone, true},+ {"peer upstream", `{"upstream":{"kind":"peer","peerId":"parent_12345678"},` ++ `"childPeerIds":["child_12345678","child_87654321"],` ++ `"sfuPublicationGeneration":null}`, true},+ {"sfu upstream", `{"upstream":{"kind":"sfu"},"childPeerIds":[],` ++ `"sfuPublicationGeneration":"generation_12345678"}`, true},+ {"sfu upstream without a generation", `{"upstream":{"kind":"sfu"},` ++ `"childPeerIds":[],"sfuPublicationGeneration":null}`, false},+ {"peer upstream owning a generation",+ `{"upstream":{"kind":"peer","peerId":"parent_12345678"},"childPeerIds":[],` ++ `"sfuPublicationGeneration":"generation_12345678"}`, false},+ {"too many children", `{"upstream":{"kind":"none"},"childPeerIds":` ++ `["child_12345678","child_87654321","child_third_1234","child_overflow_1"],` ++ `"sfuPublicationGeneration":null}`, false},+ {"duplicate children", `{"upstream":{"kind":"none"},` ++ `"childPeerIds":["child_12345678","child_12345678"],` ++ `"sfuPublicationGeneration":null}`, false},+ {"absent generation key", `{"upstream":{"kind":"none"},"childPeerIds":[]}`, false},+ {"peer id on a none upstream", `{"upstream":{"kind":"none",` ++ `"peerId":"parent_12345678"},"childPeerIds":[],` ++ `"sfuPublicationGeneration":null}`, false},+ } {+ assertServerMessage(t, "assignment "+sample.name,+ routeUpdate(sample.assignment), sample.want)+ }++ assertServerMessage(t, "prepare without a candidate",+ []byte(`{"type":"route-update","revision":9,"phase":"prepare","assignment":`++ testAssignmentNone+`}`), false)+ assertServerMessage(t, "active with a candidate",+ []byte(`{"type":"route-update","revision":9,"phase":"active","assignment":`++ testAssignmentNone+`,"candidate":{"childPeerId":"child_12345678",`++ `"connectionId":"connection_12345678","transport":"direct","qualityProbe":false}}`),+ false)+ assertServerMessage(t, "prepare with a room-wide field",+ []byte(`{"type":"route-update","revision":9,"phase":"prepare","assignment":`++ testAssignmentNone+`,"roomAssignments":[]}`), false)+}++// "accepts only bounded connection-attempt progress on a prepared route".+func TestPreparedRouteCandidate(t *testing.T) {+ prepared := func(candidate string) []byte {+ return []byte(`{"type":"route-update","revision":9,"phase":"prepare","assignment":` ++ testAssignmentNone + `,"candidate":` + candidate + `}`)+ }+ const base = `"childPeerId":"child_12345678","connectionId":"connection_12345678",` ++ `"transport":"direct","qualityProbe":false`+ for _, sample := range []struct {+ attempt string+ want bool+ }{+ {`{"current":1,"total":3}`, true},+ {`{"current":2,"total":3}`, true},+ {`{"current":3,"total":3}`, true},+ {`{"current":0,"total":3}`, false},+ {`{"current":4,"total":3}`, false},+ {`{"current":1,"total":4}`, false},+ {`{"current":1.5,"total":3}`, false},+ } {+ assertServerMessage(t, "connectionAttempt "+sample.attempt,+ prepared(`{`+base+`,"connectionAttempt":`+sample.attempt+`}`), sample.want)+ }+ assertServerMessage(t, "candidate without an attempt", prepared(`{`+base+`}`), true)+ assertServerMessage(t, "candidate with an unknown key",+ prepared(`{`+base+`,"unexpected":null}`), false)+ assertServerMessage(t, "candidate with a null attempt",+ prepared(`{`+base+`,"connectionAttempt":null}`), false)+}++// "accepts only canonical server-derived viewer evidence envelopes" and+// "keeps route messages strict" for sfu-config.+func TestForwardedEvidenceAndSfuConfig(t *testing.T) {+ const metrics = `{"natTraversalPath":"ordinary","width":null,"height":null,` ++ `"framesPerSecond":null,"bitrateKbps":null,"packetsReceivedDelta":null,` ++ `"packetsLostDelta":null,"rttMs":null,"jitterMs":null,"framesDecodedDelta":null,` ++ `"framesDroppedDelta":null,"decodeMsPerFrame":null,"freezeCountDelta":null,` ++ `"freezeDurationMsDelta":null,"pauseCountDelta":null,"pauseDurationMsDelta":null,` ++ `"codec":null,"codecProfile":null,"codecParameters":null,"audioBitrateKbps":null,` ++ `"audioPacketLossPercent":null,"audioJitterMs":null,"audioVideoPlayoutDeltaMs":null,` ++ `"videoJitterBufferDelayMs":null,"audioJitterBufferDelayMs":null,` ++ `"audioConcealedSamplesPercent":null,"audioConcealmentEventsDelta":null,` ++ `"audioCodec":null}`+ forwarded := func(extra string, upstream string) []byte {+ return []byte(`{"type":"viewer-quality-evidence","viewerPeerId":"viewer_12345678",` ++ `"upstream":` + upstream + `,"guard":{"connectionId":"connection_12345678",` ++ `"routeRevision":0,"presentationEpoch":0},"sequence":0,"windowMs":2000,` ++ `"metrics":` + metrics + extra + `}`)+ }+ assertServerMessage(t, "peer upstream",+ forwarded("", `{"kind":"peer","peerId":"host_12345678"}`), true)+ assertServerMessage(t, "sfu upstream", forwarded("", `{"kind":"sfu"}`), true)+ assertServerMessage(t, "no upstream", forwarded("", `{"kind":"none"}`), false)+ assertServerMessage(t, "leaked room id",+ forwarded(`,"roomId":"1234"`, `{"kind":"sfu"}`), false)+ assertServerMessage(t, "missing upstream",+ []byte(`{"type":"viewer-quality-evidence","viewerPeerId":"viewer_12345678",`++ `"guard":{"connectionId":"connection_12345678","routeRevision":0,`++ `"presentationEpoch":0},"sequence":0,"windowMs":2000,"metrics":`+metrics+`}`), false)++ assertServerMessage(t, "sfu config",+ []byte(`{"type":"sfu-config","revision":9,"url":"wss://sfu.example.test",`++ `"token":"header.payload.signature"}`), true)+ assertServerMessage(t, "sfu config with an oversized token",+ []byte(`{"type":"sfu-config","revision":9,"url":"wss://sfu.example.test","token":"`++ repeat("x", MaxSfuTokenLength+1)+`"}`), false)+}++// zod's z.number().int() accepts an integral JSON number in any spelling.+func TestIntAcceptsIntegralNumberForms(t *testing.T) {+ for _, sample := range []struct {+ raw string+ want bool+ }{+ {`7`, true}, {`7.0`, true}, {`7e0`, true}, {`1e3`, true},+ {`7.5`, false}, {`"7"`, false}, {`true`, false},+ } {+ assertClientMessage(t, "revision "+sample.raw,+ []byte(`{"type":"route-media-unavailable","revision":`+sample.raw+`}`), sample.want)+ }+}++// JSON.parse keeps the last occurrence of a duplicate key.+func TestDuplicateKeysKeepTheLastOccurrence(t *testing.T) {+ message, err := DecodeClientMessage(+ []byte(`{"type":"relay-capacity","downstreamEdges":9,"downstreamEdges":2}`))+ if err != nil {+ t.Fatalf("the last occurrence must win: %v", err)+ }+ if capacity, ok := message.(RelayCapacityMessage); !ok || capacity.DownstreamEdges != 2 {+ t.Fatalf("decoded %#v, want downstreamEdges 2", message)+ }+ if _, err := DecodeClientMessage(+ []byte(`{"type":"relay-capacity","downstreamEdges":2,"downstreamEdges":9}`)); err == nil {+ t.Fatal("the last occurrence must be the one validated")+ }+ // A duplicated object is replaced, not merged.+ if _, err := DecodeClientMessage(+ []byte(`{"type":"set-quality-settings","qualitySettings":{"resolution":"480p"},` ++ `"qualitySettings":` + testQualitySettings + `}`)); err != nil {+ t.Fatalf("a duplicated object must be replaced wholesale: %v", err)+ }+}++// JSON.stringify does not escape "<", ">" or "&"; display names may hold them.+func TestEncodeServerMessageDoesNotEscapeHTML(t *testing.T) {+ encoded, err := EncodeServerMessage(ViewerPresenceMessage{+ Type: "viewer-presence",+ Viewers: []ParticipantPresenceEntry{+ HostPresenceEntry("host_12345678", "a<b>&c"),+ },+ })+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Contains(encoded, []byte(`"displayName":"a<b>&c"`)) {+ t.Fatalf("display name must survive unescaped: %s", encoded)+ }+ if bytes.HasSuffix(encoded, []byte("\n")) {+ t.Fatalf("the encoder newline must be dropped: %q", encoded)+ }+}++// Empty collections encode as [] the way the TypeScript literals do.+func TestEncodeServerMessageEmitsEmptyArrays(t *testing.T) {+ encoded, err := EncodeServerMessage(ViewerPresenceMessage{Type: "viewer-presence"})+ if err != nil {+ t.Fatal(err)+ }+ if string(encoded) != `{"type":"viewer-presence","viewers":[]}` {+ t.Fatalf("got %s", encoded)+ }+ encoded, err = EncodeServerMessage(RouteDiagnosticSnapshotMessage{+ Type: "route-diagnostic-snapshot"})+ if err != nil {+ t.Fatal(err)+ }+ if string(encoded) !=+ `{"type":"route-diagnostic-snapshot","snapshot":{"children":[],"operation":null}}` {+ t.Fatalf("got %s", encoded)+ }+}++// The authenticated key order follows the object literal in signaling.ts.+func TestAuthenticatedKeyOrder(t *testing.T) {+ standby := "wss://sfu.example.test"+ paused := true+ encoded, err := EncodeServerMessage(AuthenticatedViewerMessage{+ Type: "authenticated", Protocol: SignalingProtocol, PeerID: "viewer_12345678",+ MaxViewers: 8, EndpointMediaCopyCapacity: 2, HostOnline: true, HostPaused: &paused,+ IceConfig: IceConfig{}, RoutePolicy: DefaultRoutePolicy, CodeEntryPolicy: CodeEntryOpen,+ ViewerAuthorizationGeneration: "viewer_generation_12345678",+ MediaMode: "peer-assisted", RouteRevision: 0,+ QualitySettings: DefaultQualitySettings, SfuStandbyURL: &standby, Role: RoleViewer,+ })+ if err != nil {+ t.Fatal(err)+ }+ var order []string+ decoder := json.NewDecoder(bytes.NewReader(encoded))+ if _, err := decoder.Token(); err != nil {+ t.Fatal(err)+ }+ for decoder.More() {+ key, err := decoder.Token()+ if err != nil {+ t.Fatal(err)+ }+ order = append(order, key.(string))+ var skip json.RawMessage+ if err := decoder.Decode(&skip); err != nil {+ t.Fatal(err)+ }+ }+ want := []string{+ "type", "protocol", "peerId", "roomExpiresAt", "maxViewers",+ "endpointMediaCopyCapacity", "hostOnline", "hostPaused", "connectionId",+ "iceConfig", "routePolicy", "codeEntryPolicy", "viewerAuthorizationGeneration",+ "mediaMode", "shareGeneration", "routeRevision", "routeAssignment",+ "qualitySettings", "sfuStandbyUrl", "role",+ }+ if strings.Join(order, ",") != strings.Join(want, ",") {+ t.Fatalf("key order\n got: %v\nwant: %v", order, want)+ }+}++// Optional keys reject an explicit null; nullable keys reject absence.+func TestOptionalAndNullableAreExact(t *testing.T) {+ for _, sample := range []struct {+ name string+ raw string+ want bool+ }{+ {"null optional shareGeneration",+ `{"type":"stop-sharing","shareGeneration":null}`, false},+ {"absent optional shareGeneration", `{"type":"stop-sharing"}`, true},+ {"null optional targetPeerId",+ `{"type":"restart-request","targetPeerId":null,` ++ `"connectionId":"connection_12345678","rebuild":true}`, false},+ {"null optional qualityApproved",+ `{"type":"route-ready","revision":1,"phase":"prepare","qualityApproved":null}`, false},+ {"null nullable connectionId",+ `{"type":"route-failed","revision":1,"phase":"active","connectionId":null}`, true},+ {"absent nullable connectionId",+ `{"type":"route-failed","revision":1,"phase":"active"}`, false},+ } {+ assertClientMessage(t, sample.name, []byte(sample.raw), sample.want)+ }+}++// A host authenticate without routePolicy takes DEFAULT_ROUTE_POLICY.+func TestAuthenticateAppliesTheRoutePolicyDefault(t *testing.T) {+ message, err := DecodeClientMessage([]byte(+ `{"type":"authenticate","protocol":"screener-v21","roomId":"1234","role":"host",` ++ `"token":"` + repeat("a", 43) + `","clientId":"client_12345678"}`))+ if err != nil {+ t.Fatal(err)+ }+ host, ok := message.(AuthenticateHostMessage)+ if !ok {+ t.Fatalf("decoded %#v, want AuthenticateHostMessage", message)+ }+ if host.RoutePolicy != DefaultRoutePolicy {+ t.Fatalf("routePolicy = %+v, want %+v", host.RoutePolicy, DefaultRoutePolicy)+ }+}++// The sealed unions accept nothing outside their own message structs.+func TestDecodeRejectsUnknownEnvelopes(t *testing.T) {+ for _, raw := range []string{`{}`, `[]`, `null`, `"authenticate"`, `{"type":42}`,+ `{"type":"unknown"}`, `{"kind":"signal"}`} {+ if _, err := DecodeClientMessage([]byte(raw)); err == nil {+ t.Errorf("client decode accepted %s", raw)+ }+ if _, err := DecodeServerMessage([]byte(raw)); err == nil {+ t.Errorf("server decode accepted %s", raw)+ }+ }+}diff --git a/internal/server/protocol/fixture_test.go b/internal/server/protocol/fixture_test.gonew file mode 100644index 00000000..caade3d2--- /dev/null+++ b/internal/server/protocol/fixture_test.go@@ -0,0 +1,149 @@+package protocol++import (+ "encoding/json"+ "os"+ "path/filepath"+ "reflect"+ "testing"+)++// The fixture is the single owner of the cross-language wire samples;+// tests/protocol-fixture.test.ts replays the same file against the zod schemas.+const fixturePath = "../../../tests/fixtures/wire-samples.json"++type wireFixture struct {+ Constants map[string]any `json:"constants"`+ ClientMessages []struct {+ Name string `json:"name"`+ Schema string `json:"schema"`+ JSON string `json:"json"`+ Valid bool `json:"valid"`+ } `json:"clientMessages"`+ ServerMessages []struct {+ Name string `json:"name"`+ JSON string `json:"json"`+ } `json:"serverMessages"`+}++func loadFixture(t *testing.T) wireFixture {+ t.Helper()+ raw, err := os.ReadFile(filepath.FromSlash(fixturePath))+ if err != nil {+ t.Fatalf("read fixture: %v", err)+ }+ var fixture wireFixture+ if err := json.Unmarshal(raw, &fixture); err != nil {+ t.Fatalf("parse fixture: %v", err)+ }+ return fixture+}++func TestFixtureConstants(t *testing.T) {+ fixture := loadFixture(t)+ expected := map[string]any{+ "signalingProtocol": SignalingProtocol,+ "maxViewersPerRoomLimit": float64(MaxViewersPerRoomLimit),+ "maxParticipantsPerRoomLimit": float64(MaxParticipantsPerRoomLimit),+ "maxSignalBytes": float64(MaxSignalBytes),+ "roomCodeLength": float64(RoomCodeLength),+ "maxMediaRouteRevision": float64(MaxMediaRouteRevision),+ "maxSfuTokenLength": float64(MaxSfuTokenLength),+ "maxIceServerUrls": float64(MaxIceServerURLs),+ "maxNatPredictionAuxiliaryStunUrls": float64(MaxNatPredictionAuxiliaryStunURLs),+ "maxViewerQualityEvidenceBytes": float64(MaxViewerQualityEvidenceBytes),+ "viewerQualityEvidenceIntervalMs": float64(ViewerQualityEvidenceIntervalMs),+ "viewerQualityEvidenceExpiryMs": float64(ViewerQualityEvidenceExpiryMs),+ "persistentNativeEdgeDegradedWindows": float64(PersistentNativeEdgeDegradedWindows),+ "maxDisplayNameCodePoints": float64(MaxDisplayNameCodePoints),+ "defaultViewerDisplayName": DefaultViewerDisplayName,+ "defaultHostDisplayNamePrefix": DefaultHostDisplayNamePrefix,+ "minViewerPasswordLength": float64(MinViewerPasswordLength),+ "maxViewerPasswordLength": float64(MaxViewerPasswordLength),+ "defaultEndpointMediaCopyCapacity": float64(DefaultEndpointMediaCopyCapacity),+ "maxEndpointMediaCopyCapacity": float64(MaxEndpointMediaCopyCapacity),+ "signalCloseCodeServiceRestart": float64(SignalCloseServiceRestart),+ "signalCloseCodeSessionReplaced": float64(SignalCloseSessionReplaced),+ "signalCloseCodeClientReconnect": float64(SignalCloseClientReconnect),+ "signalCloseCodeAuthenticationFailed": float64(SignalCloseAuthenticationFailed),+ "signalCloseCodeViewerAccessRevoked": float64(SignalCloseViewerAccessRevoked),+ "defaultQualitySettings": jsonValue(t, DefaultQualitySettings),+ "defaultRoutePolicy": jsonValue(t, DefaultRoutePolicy),+ }+ if !reflect.DeepEqual(fixture.Constants, expected) {+ t.Fatalf("constants mismatch\n got: %#v\nwant: %#v", fixture.Constants, expected)+ }+}++func TestFixtureClientSamples(t *testing.T) {+ fixture := loadFixture(t)+ if len(fixture.ClientMessages) == 0 {+ t.Fatal("fixture carries no client samples")+ }+ for _, sample := range fixture.ClientMessages {+ t.Run(sample.Name, func(t *testing.T) {+ var err error+ switch sample.Schema {+ case "client":+ _, err = DecodeClientMessage([]byte(sample.JSON))+ case "createRoomRequest":+ _, err = DecodeCreateRoomRequest([]byte(sample.JSON))+ case "replaceRoomRequest":+ _, err = DecodeReplaceRoomRequest([]byte(sample.JSON))+ case "roomAccessUpdateRequest":+ _, err = DecodeRoomAccessUpdateRequest([]byte(sample.JSON))+ default:+ t.Fatalf("unknown fixture schema %q", sample.Schema)+ }+ if sample.Valid && err != nil {+ t.Fatalf("expected the sample to decode, got %v", err)+ }+ if !sample.Valid && err == nil {+ t.Fatal("expected the sample to be rejected")+ }+ })+ }+}++func TestFixtureServerSamplesRoundTrip(t *testing.T) {+ fixture := loadFixture(t)+ if len(fixture.ServerMessages) == 0 {+ t.Fatal("fixture carries no server samples")+ }+ for _, sample := range fixture.ServerMessages {+ t.Run(sample.Name, func(t *testing.T) {+ message, err := DecodeServerMessage([]byte(sample.JSON))+ if err != nil {+ t.Fatalf("decode: %v", err)+ }+ encoded, err := EncodeServerMessage(message)+ if err != nil {+ t.Fatalf("encode: %v", err)+ }+ var want, got any+ if err := json.Unmarshal([]byte(sample.JSON), &want); err != nil {+ t.Fatalf("parse sample: %v", err)+ }+ if err := json.Unmarshal(encoded, &got); err != nil {+ t.Fatalf("parse re-encoded message: %v", err)+ }+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("round trip changed the message\n got: %s\nwant: %s",+ encoded, sample.JSON)+ }+ })+ }+}++func jsonValue(t *testing.T, value any) any {+ t.Helper()+ encoded, err := json.Marshal(value)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ var decoded any+ if err := json.Unmarshal(encoded, &decoded); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ return decoded+}diff --git a/internal/server/protocol/helpers.go b/internal/server/protocol/helpers.gonew file mode 100644index 00000000..923172a4--- /dev/null+++ b/internal/server/protocol/helpers.go@@ -0,0 +1,201 @@+package protocol++import (+ "errors"+ "regexp"+ "slices"+ "strings"+)++// ---------------------------------------------------------------------------+// src/shared/media-copy-accounting.ts+// ---------------------------------------------------------------------------++// EndpointMediaCopyPhase is EndpointMediaCopyPhase.+type EndpointMediaCopyPhase string++// Endpoint media copy phases.+const (+ EndpointMediaCopySteady EndpointMediaCopyPhase = "steady"+ EndpointMediaCopyTransition EndpointMediaCopyPhase = "transition"+)++// ErrEndpointMediaCopyCapacity is the assertEndpointMediaCopyCapacity throw.+var ErrEndpointMediaCopyCapacity = errors.New(+ "Endpoint media copy capacity must be 1, 2, or 3")++// EndpointMediaCopyLimit ports endpointMediaCopyLimit. It panics on an invalid+// capacity, which is where the TypeScript throws.+func EndpointMediaCopyLimit(capacity int, phase EndpointMediaCopyPhase) int {+ if err := AssertEndpointMediaCopyCapacity(capacity); err != nil {+ panic(err)+ }+ if phase == EndpointMediaCopySteady {+ return capacity+ }+ return min(capacity+1, MaxEndpointMediaCopyCapacity)+}++// EndpointMediaCopyCountFits ports endpointMediaCopyCountFits.+func EndpointMediaCopyCountFits(count, capacity int, phase EndpointMediaCopyPhase) bool {+ return count >= 0 &&+ IsEndpointMediaCopyCapacity(capacity) &&+ count <= EndpointMediaCopyLimit(capacity, phase)+}++// IsEndpointMediaCopyCapacity ports isEndpointMediaCopyCapacity. The+// TypeScript Number.isSafeInteger guard is implicit in Go's int.+func IsEndpointMediaCopyCapacity(capacity int) bool {+ return capacity >= 1 && capacity <= MaxEndpointMediaCopyCapacity+}++// AssertEndpointMediaCopyCapacity ports assertEndpointMediaCopyCapacity.+func AssertEndpointMediaCopyCapacity(capacity int) error {+ if !IsEndpointMediaCopyCapacity(capacity) {+ return ErrEndpointMediaCopyCapacity+ }+ return nil+}++// ---------------------------------------------------------------------------+// src/shared/nat-candidate.ts+// ---------------------------------------------------------------------------++// CandidateSignalOrigin is CandidateSignalOrigin.+type CandidateSignalOrigin string++// Candidate signal origins.+const (+ CandidateOriginEnd CandidateSignalOrigin = "end"+ CandidateOriginOrdinary CandidateSignalOrigin = "ordinary"+ CandidateOriginPredicted CandidateSignalOrigin = "predicted"+)++// The JavaScript \s class, spelled out because Go's \s is ASCII only.+var predictedCandidatePattern = regexp.MustCompile(+ `(?i)^candidate:s[pm][0-9]+[\t\n\v\f\r \x{00a0}\x{1680}\x{2000}-\x{200a}` ++ `\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}\x{feff}]`)++// CandidateSignalOriginOf ports candidateSignalOrigin. An empty string stands+// in for the TypeScript null (both yield "end").+func CandidateSignalOriginOf(candidate string) CandidateSignalOrigin {+ if strings.TrimFunc(candidate, IsJSWhitespace) == "" {+ return CandidateOriginEnd+ }+ if predictedCandidatePattern.MatchString(candidate) {+ return CandidateOriginPredicted+ }+ return CandidateOriginOrdinary+}++// ---------------------------------------------------------------------------+// src/shared/packet-loss.ts+// ---------------------------------------------------------------------------++// PacketLossPercentFromDeltas ports packetLossPercentFromDeltas. A nil+// argument is the TypeScript null; ok is false where it returns null.+func PacketLossPercentFromDeltas(packetsReceivedDelta, packetsLostDelta *float64) (float64, bool) {+ if packetsReceivedDelta == nil || packetsLostDelta == nil ||+ *packetsReceivedDelta < 0 || *packetsLostDelta < 0 {+ return 0, false+ }+ packetDelta := *packetsReceivedDelta + *packetsLostDelta+ if packetDelta <= 0 {+ return 0, false+ }+ return (*packetsLostDelta / packetDelta) * 100, true+}++// ---------------------------------------------------------------------------+// src/shared/video-codec-evidence.ts+// ---------------------------------------------------------------------------++type codecParameterRule struct {+ profileKey string+ parameterKeys []string+ validators map[string]*regexp.Regexp+}++var videoCodecParameterRules = map[string]codecParameterRule{+ "video/h264": {+ profileKey: "profile-level-id",+ parameterKeys: []string{"packetization-mode", "level-asymmetry-allowed"},+ validators: map[string]*regexp.Regexp{+ "profile-level-id": regexp.MustCompile(`^[0-9a-f]{6}$`),+ "packetization-mode": regexp.MustCompile(`^[0-2]$`),+ "level-asymmetry-allowed": regexp.MustCompile(`^[01]$`),+ },+ },+ "video/vp9": {+ profileKey: "profile-id",+ parameterKeys: []string{"max-fr", "max-fs"},+ validators: map[string]*regexp.Regexp{+ "profile-id": regexp.MustCompile(`^[0-3]$`),+ "max-fr": regexp.MustCompile(`^[1-9][0-9]{0,9}$`),+ "max-fs": regexp.MustCompile(`^[1-9][0-9]{0,9}$`),+ },+ },+ "video/vp8": {+ profileKey: "",+ parameterKeys: []string{"max-fr", "max-fs"},+ validators: map[string]*regexp.Regexp{+ "max-fr": regexp.MustCompile(`^[1-9][0-9]{0,9}$`),+ "max-fs": regexp.MustCompile(`^[1-9][0-9]{0,9}$`),+ },+ },+ "video/av1": {+ profileKey: "profile",+ parameterKeys: []string{"level-idx", "tier"},+ validators: map[string]*regexp.Regexp{+ "profile": regexp.MustCompile(`^[0-2]$`),+ "level-idx": regexp.MustCompile(`^(?:[0-9]|[12][0-9]|3[01])$`),+ "tier": regexp.MustCompile(`^[01]$`),+ },+ },+}++var videoMimeTypePattern = regexp.MustCompile(`(?i)^video/[A-Za-z0-9.+-]{1,32}$`)++// IsCanonicalVideoCodecEvidence ports isCanonicalVideoCodecEvidence. Empty+// strings are the TypeScript nulls; the schema rejects a genuinely empty codec+// string before this refine runs.+func IsCanonicalVideoCodecEvidence(codec, codecProfile, codecParameters string) bool {+ rule, ok := videoCodecParameterRules[strings.ToLower(codec)]+ if codec == "" || !ok {+ return codecProfile == "" && codecParameters == ""+ }+ profileKeys := []string{}+ if rule.profileKey != "" {+ profileKeys = append(profileKeys, rule.profileKey)+ }+ return canonicalValuesMatch(codecProfile, profileKeys, rule.validators) &&+ canonicalValuesMatch(codecParameters, rule.parameterKeys, rule.validators)+}++func canonicalValuesMatch(+ encoded string, orderedKeys []string, validators map[string]*regexp.Regexp,+) bool {+ if encoded == "" {+ return true+ }+ segments := strings.Split(encoded, "; ")+ if len(segments) > len(orderedKeys) {+ return false+ }+ previousKeyIndex := -1+ for _, segment := range segments {+ separator := strings.Index(segment, "=")+ key, candidate := "", ""+ if separator >= 1 {+ key, candidate = segment[:separator], segment[separator+1:]+ }+ keyIndex := slices.Index(orderedKeys, key)+ validator, known := validators[key]+ if keyIndex <= previousKeyIndex || keyIndex < 0 ||+ !known || !validator.MatchString(candidate) {+ return false+ }+ previousKeyIndex = keyIndex+ }+ return true+}diff --git a/internal/server/protocol/helpers_test.go b/internal/server/protocol/helpers_test.gonew file mode 100644index 00000000..2dcdc767--- /dev/null+++ b/internal/server/protocol/helpers_test.go@@ -0,0 +1,108 @@+package protocol++import "testing"++func TestEndpointMediaCopyLimits(t *testing.T) {+ for _, sample := range []struct {+ capacity, steady, transition int+ }{{1, 1, 2}, {2, 2, 3}, {3, 3, 3}} {+ if got := EndpointMediaCopyLimit(sample.capacity, EndpointMediaCopySteady); got != sample.steady {+ t.Errorf("steady limit for %d = %d, want %d", sample.capacity, got, sample.steady)+ }+ if got := EndpointMediaCopyLimit(sample.capacity, EndpointMediaCopyTransition); got != sample.transition {+ t.Errorf("transition limit for %d = %d, want %d", sample.capacity, got, sample.transition)+ }+ if !EndpointMediaCopyCountFits(sample.transition, sample.capacity, EndpointMediaCopyTransition) {+ t.Errorf("%d copies must fit capacity %d in transition", sample.transition, sample.capacity)+ }+ if EndpointMediaCopyCountFits(sample.transition+1, sample.capacity, EndpointMediaCopyTransition) {+ t.Errorf("%d copies must not fit capacity %d in transition",+ sample.transition+1, sample.capacity)+ }+ }+}++func TestEndpointMediaCopyCapacityGuards(t *testing.T) {+ for _, capacity := range []int{0, 4, -1} {+ if err := AssertEndpointMediaCopyCapacity(capacity); err == nil {+ t.Errorf("capacity %d must be rejected", capacity)+ }+ }+ // An unavailable runtime capacity returns false instead of throwing.+ if EndpointMediaCopyCountFits(0, 0, EndpointMediaCopySteady) {+ t.Error("a zero capacity must never fit")+ }+}++// Ported from tests/nat-candidate.test.ts.+func TestNatCandidateDiagnostics(t *testing.T) {+ for _, sample := range []struct {+ candidate string+ want CandidateSignalOrigin+ }{+ {"", CandidateOriginEnd},+ {" ", CandidateOriginEnd},+ {"candidate:sp2 1 udp 1 203.0.113.1 50000 typ srflx", CandidateOriginPredicted},+ {"candidate:base 1 udp 1 203.0.113.1 50000 typ srflx", CandidateOriginOrdinary},+ } {+ if got := CandidateSignalOriginOf(sample.candidate); got != sample.want {+ t.Errorf("CandidateSignalOriginOf(%q) = %q, want %q",+ sample.candidate, got, sample.want)+ }+ }+}++// Ported from tests/packet-loss.test.ts ("keeps receive-side delta validation").+func TestPacketLossPercentFromDeltas(t *testing.T) {+ number := func(value float64) *float64 { return &value }+ for _, sample := range []struct {+ name string+ received, lost *float64+ want float64+ ok bool+ }{+ {"ninety received and ten lost", number(90), number(10), 10, true},+ {"no packets at all", number(0), number(0), 0, false},+ {"missing received delta", nil, number(1), 0, false},+ {"negative lost delta", number(10), number(-1), 0, false},+ } {+ t.Run(sample.name, func(t *testing.T) {+ got, ok := PacketLossPercentFromDeltas(sample.received, sample.lost)+ if ok != sample.ok || (ok && got != sample.want) {+ t.Fatalf("PacketLossPercentFromDeltas = (%v, %v), want (%v, %v)",+ got, ok, sample.want, sample.ok)+ }+ })+ }+}++// Ported from the codec cases in tests/protocol.test.ts.+func TestIsCanonicalVideoCodecEvidence(t *testing.T) {+ for _, sample := range []struct {+ codec, profile, parameters string+ want bool+ }{+ {"video/H264", "profile-level-id=42e01f",+ "packetization-mode=1; level-asymmetry-allowed=1", true},+ {"video/VP8", "", "max-fr=60; max-fs=8160", true},+ {"video/VP9", "profile-id=2", "max-fs=8160", true},+ {"video/AV1", "profile=1", "level-idx=31; tier=0", true},+ {"video/unknown", "", "", true},+ {"", "", "", true},+ {"video/unknown", "profile=1", "", false},+ {"video/H264", "device-id=deadbeef", "", false},+ {"video/H264", "", "sprop-parameter-sets=deadbeef", false},+ // Order is part of the canonical form.+ {"video/H264", "", "level-asymmetry-allowed=1; packetization-mode=1", false},+ // A duplicate key exceeds the ordered key budget.+ {"video/VP8", "", "max-fr=60; max-fr=60", false},+ {"video/AV1", "profile=3", "", false},+ } {+ t.Run(sample.codec+"|"+sample.profile+"|"+sample.parameters, func(t *testing.T) {+ got := IsCanonicalVideoCodecEvidence(sample.codec, sample.profile, sample.parameters)+ if got != sample.want {+ t.Fatalf("IsCanonicalVideoCodecEvidence = %v, want %v", got, sample.want)+ }+ })+ }+}diff --git a/internal/server/protocol/http.go b/internal/server/protocol/http.gonew file mode 100644index 00000000..37b1b6b7--- /dev/null+++ b/internal/server/protocol/http.go@@ -0,0 +1,197 @@+package protocol++import (+ "errors"+ "fmt"+)++// CreateRoomRequest mirrors createRoomRequestSchema.+type CreateRoomRequest struct {+ CodeEntryPolicy CodeEntryPolicy `json:"codeEntryPolicy"`+ RoomPassword Nullable[string] `json:"roomPassword,omitzero"`+ PreferredRoomID string `json:"preferredRoomId,omitempty"`+}++// DecodeCreateRoomRequest parses createRoomRequestSchema.+func DecodeCreateRoomRequest(data []byte) (CreateRoomRequest, error) {+ var request CreateRoomRequest+ present, err := decodeObject(data, &request)+ if err != nil {+ return CreateRoomRequest{}, err+ }+ if err := present.require("codeEntryPolicy"); err != nil {+ return CreateRoomRequest{}, err+ }+ if err := present.optional("preferredRoomId"); err != nil {+ return CreateRoomRequest{}, err+ }+ if !enumOf(request.CodeEntryPolicy, CodeEntryOpen, CodeEntryPrivate) {+ return CreateRoomRequest{}, fmt.Errorf(+ "unknown codeEntryPolicy %q", request.CodeEntryPolicy)+ }+ if request.RoomPassword.Value != nil && !ValidViewerPassword(*request.RoomPassword.Value) {+ return CreateRoomRequest{}, errors.New("roomPassword is malformed")+ }+ if present.has("preferredRoomId") && !ValidRoomCode(request.PreferredRoomID) {+ return CreateRoomRequest{}, errors.New("preferredRoomId is not a room code")+ }+ return request, nil+}++// ReplaceRoomRequest mirrors replaceRoomRequestSchema.+type ReplaceRoomRequest struct {+ CodeEntryPolicy CodeEntryPolicy `json:"codeEntryPolicy"`+ RoomPassword Nullable[string] `json:"roomPassword,omitzero"`+}++// DecodeReplaceRoomRequest parses replaceRoomRequestSchema.+func DecodeReplaceRoomRequest(data []byte) (ReplaceRoomRequest, error) {+ var request ReplaceRoomRequest+ present, err := decodeObject(data, &request)+ if err != nil {+ return ReplaceRoomRequest{}, err+ }+ if err := present.require("codeEntryPolicy"); err != nil {+ return ReplaceRoomRequest{}, err+ }+ if !enumOf(request.CodeEntryPolicy, CodeEntryOpen, CodeEntryPrivate) {+ return ReplaceRoomRequest{}, fmt.Errorf(+ "unknown codeEntryPolicy %q", request.CodeEntryPolicy)+ }+ if request.RoomPassword.Value != nil && !ValidViewerPassword(*request.RoomPassword.Value) {+ return ReplaceRoomRequest{}, errors.New("roomPassword is malformed")+ }+ return request, nil+}++// RoomAccessUpdateRequest is one member of roomAccessUpdateRequestSchema.+type RoomAccessUpdateRequest interface {+ isRoomAccessUpdateRequest()+}++// SetCodeEntryPolicyRequest is action "set-code-entry-policy".+type SetCodeEntryPolicyRequest struct {+ Action string `json:"action"`+ Policy CodeEntryPolicy `json:"policy"`+}++// RotateViewerGrantRequest is action "rotate-viewer-grant".+type RotateViewerGrantRequest struct {+ Action string `json:"action"`+}++// RevokeViewerGrantRequest is action "revoke-viewer-grant".+type RevokeViewerGrantRequest struct {+ Action string `json:"action"`+}++// SetViewerPasswordRequest is action "set-viewer-password".+type SetViewerPasswordRequest struct {+ Action string `json:"action"`+ Password *string `json:"password"`+}++func (SetCodeEntryPolicyRequest) isRoomAccessUpdateRequest() {}+func (RotateViewerGrantRequest) isRoomAccessUpdateRequest() {}+func (RevokeViewerGrantRequest) isRoomAccessUpdateRequest() {}+func (SetViewerPasswordRequest) isRoomAccessUpdateRequest() {}++// DecodeRoomAccessUpdateRequest parses roomAccessUpdateRequestSchema.+func DecodeRoomAccessUpdateRequest(data []byte) (RoomAccessUpdateRequest, error) {+ action, err := typeOf(data, "action")+ if err != nil {+ return nil, err+ }+ switch action {+ case "set-code-entry-policy":+ var request SetCodeEntryPolicyRequest+ present, err := decodeObject(data, &request)+ if err != nil {+ return nil, err+ }+ if err := present.require("action", "policy"); err != nil {+ return nil, err+ }+ if !enumOf(request.Policy, CodeEntryOpen, CodeEntryPrivate) {+ return nil, fmt.Errorf("unknown policy %q", request.Policy)+ }+ return request, nil+ case "rotate-viewer-grant":+ var request RotateViewerGrantRequest+ present, err := decodeObject(data, &request)+ if err != nil {+ return nil, err+ }+ if err := present.require("action"); err != nil {+ return nil, err+ }+ return request, nil+ case "revoke-viewer-grant":+ var request RevokeViewerGrantRequest+ present, err := decodeObject(data, &request)+ if err != nil {+ return nil, err+ }+ if err := present.require("action"); err != nil {+ return nil, err+ }+ return request, nil+ case "set-viewer-password":+ var request SetViewerPasswordRequest+ present, err := decodeObject(data, &request)+ if err != nil {+ return nil, err+ }+ if err := present.require("action"); err != nil {+ return nil, err+ }+ if err := present.requireNullable("password"); err != nil {+ return nil, err+ }+ if request.Password != nil && !ValidViewerPassword(*request.Password) {+ return nil, errors.New("password is malformed")+ }+ return request, nil+ }+ return nil, fmt.Errorf("unknown room access action %q", action)+}++// CreateRoomResponse mirrors createRoomResponseSchema.+type CreateRoomResponse struct {+ RoomID string `json:"roomId"`+ HostToken string `json:"hostToken"`+ InviteURL string `json:"inviteUrl"`+ CodeEntryPolicy CodeEntryPolicy `json:"codeEntryPolicy"`+ ExpiresAt *string `json:"expiresAt"`+ RoomLeaseSeconds Int `json:"roomLeaseSeconds"`+}++// RoomAccessUpdateResponse is one member of roomAccessUpdateResponseSchema.+type RoomAccessUpdateResponse interface {+ isRoomAccessUpdateResponse()+}++// CodeEntryPolicyUpdatedResponse is type "code-entry-policy-updated".+type CodeEntryPolicyUpdatedResponse struct {+ Type string `json:"type"`+ CodeEntryPolicy CodeEntryPolicy `json:"codeEntryPolicy"`+ ViewerPasswordEnabled bool `json:"viewerPasswordEnabled"`+}++// ViewerGrantUpdatedResponse is type "viewer-grant-updated". InviteURL is nil+// for the explicit null a revoke returns.+type ViewerGrantUpdatedResponse struct {+ Type string `json:"type"`+ ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`+ InviteURL *string `json:"inviteUrl"`+}++// ViewerPasswordUpdatedResponse is type "viewer-password-updated".+type ViewerPasswordUpdatedResponse struct {+ Type string `json:"type"`+ Enabled bool `json:"enabled"`+}++func (CodeEntryPolicyUpdatedResponse) isRoomAccessUpdateResponse() {}+func (ViewerGrantUpdatedResponse) isRoomAccessUpdateResponse() {}+func (ViewerPasswordUpdatedResponse) isRoomAccessUpdateResponse() {}diff --git a/internal/server/protocol/scalars.go b/internal/server/protocol/scalars.gonew file mode 100644index 00000000..0f16624e--- /dev/null+++ b/internal/server/protocol/scalars.go@@ -0,0 +1,401 @@+package protocol++import (+ "encoding/json"+ "errors"+ "net/url"+ "regexp"+ "strconv"+ "strings"+ "unicode"+ "unicode/utf8"++ "golang.org/x/text/unicode/norm"+)++// UTF16Length counts UTF-16 code units, which is what zod's string .min/.max/+// .length and String.prototype.length measure: not bytes, not code points.+// It is the single owner of that measurement for the server packages.+func UTF16Length(value string) int {+ length := 0+ for _, character := range value {+ if character > 0xffff {+ length += 2+ } else {+ length+++ }+ }+ return length+}++// IsJSWhitespace matches the JavaScript regular-expression \s class, which is+// also what String.prototype.trim and Number(string) strip. It is the single+// owner of that predicate for the server packages.+func IsJSWhitespace(character rune) bool {+ switch character {+ case '\t', '\n', '\v', '\f', '\r', ' ',+ 0x00a0, 0x1680, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, 0xfeff:+ return true+ }+ return character >= 0x2000 && character <= 0x200a+}++var (+ opaqueIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)+ roomCodePattern = regexp.MustCompile(`^[1-9][0-9]*$`)+ viewerGrantPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{21}[AQgw]$`)+ viewerPasswordPattern = regexp.MustCompile(`^[\x21-\x7e]+$`)+)++// ValidOpaqueID mirrors opaqueIdSchema: 8..128 code units of [A-Za-z0-9_-].+func ValidOpaqueID(value string) bool {+ length := UTF16Length(value)+ return length >= 8 && length <= 128 && opaqueIDPattern.MatchString(value)+}++// ValidToken mirrors tokenSchema: 32..128 code units of [A-Za-z0-9_-].+func ValidToken(value string) bool {+ length := UTF16Length(value)+ return length >= 32 && length <= 128 && opaqueIDPattern.MatchString(value)+}++// ValidRoomCode mirrors roomCodeSchema.+func ValidRoomCode(value string) bool {+ return UTF16Length(value) == RoomCodeLength && roomCodePattern.MatchString(value)+}++// ValidViewerGrant mirrors viewerGrantSchema.+func ValidViewerGrant(value string) bool {+ return UTF16Length(value) == 22 && viewerGrantPattern.MatchString(value)+}++// ValidViewerPassword mirrors viewerPasswordSchema.+func ValidViewerPassword(value string) bool {+ length := UTF16Length(value)+ return length >= MinViewerPasswordLength &&+ length <= MaxViewerPasswordLength &&+ viewerPasswordPattern.MatchString(value)+}++// ValidLiveKitWebSocketURL mirrors liveKitWebSocketUrlSchema.+func ValidLiveKitWebSocketURL(value string) bool {+ if UTF16Length(value) > 2048 {+ return false+ }+ parsed, err := url.Parse(value)+ if err != nil || parsed.Host == "" {+ return false+ }+ scheme := strings.ToLower(parsed.Scheme)+ return scheme == "ws" || scheme == "wss"+}++// isoDateTimePattern mirrors z.string().datetime(): an RFC 3339 UTC instant+// with a "Z" designator and no offset.+var isoDateTimePattern = regexp.MustCompile(+ `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$`)++// ValidISODateTime reports whether value is a zod `.datetime()` string.+func ValidISODateTime(value string) bool {+ return isoDateTimePattern.MatchString(value)+}++// forbiddenDisplayNameCharacters is FORBIDDEN_DISPLAY_NAME_CHARACTERS from+// src/shared/protocol.ts.+var forbiddenDisplayNameCharacters = regexp.MustCompile(+ `[\p{Cc}\p{Zl}\p{Zp}\x{061c}\x{200b}\x{200e}\x{200f}\x{202a}-\x{202e}` ++ `\x{2060}\x{2066}-\x{2069}\x{feff}]`)++// NormalizeDisplayName ports normalizeDisplayName. The second result is false+// where the TypeScript returns null.+func NormalizeDisplayName(value string) (string, bool) {+ if forbiddenDisplayNameCharacters.MatchString(value) {+ return "", false+ }+ // The TypeScript rejects code points in D800..DFFF, which a JavaScript+ // string can hold as an unpaired surrogate. A Go string can only carry one+ // as invalid UTF-8 (WTF-8), so utf8.ValidString is the exact analogue.+ if !utf8.ValidString(value) {+ return "", false+ }++ normalized := collapseUnicodeSpaces(+ strings.TrimFunc(norm.NFC.String(value), isUnicodeSpaceSeparator))+ count := utf8.RuneCountInString(normalized)+ if count < 1 || count > MaxDisplayNameCodePoints {+ return "", false+ }+ return normalized, true+}++// isUnicodeSpaceSeparator matches \p{Zs}. Every other character trimmed by+// JavaScript's String.prototype.trim (Cc, Zl, Zp, FEFF) is already forbidden+// above, so trimming Zs alone is equivalent here.+func isUnicodeSpaceSeparator(character rune) bool {+ return unicode.Is(unicode.Zs, character)+}++// collapseUnicodeSpaces implements .replace(/\p{Zs}+/gu, " ").+func collapseUnicodeSpaces(value string) string {+ var builder strings.Builder+ pendingSpace := false+ for _, character := range value {+ if isUnicodeSpaceSeparator(character) {+ pendingSpace = true+ continue+ }+ if pendingSpace {+ builder.WriteByte(' ')+ pendingSpace = false+ }+ builder.WriteRune(character)+ }+ if pendingSpace {+ builder.WriteByte(' ')+ }+ return builder.String()+}++// DisplayName mirrors displayNameSchema: 1..96 UTF-16 code units that+// normalizeDisplayName leaves unchanged.+type DisplayName string++// UnmarshalJSON implements json.Unmarshaler.+func (d *DisplayName) UnmarshalJSON(data []byte) error {+ // encoding/json folds an unpaired \uD800-\uDFFF escape to U+FFFD, so the+ // raw token is the only place the TypeScript surrogate rejection is still+ // observable.+ if hasUnpairedSurrogateEscape(data) {+ return errors.New("displayName contains an unpaired surrogate")+ }+ var value string+ if err := json.Unmarshal(data, &value); err != nil {+ return err+ }+ if !ValidDisplayName(value) {+ return errors.New("display name must be canonical")+ }+ *d = DisplayName(value)+ return nil+}++// ValidDisplayName mirrors displayNameSchema's bounds and canonical refine.+func ValidDisplayName(value string) bool {+ length := UTF16Length(value)+ if length < 1 || length > MaxDisplayNameCodePoints*4 {+ return false+ }+ normalized, ok := NormalizeDisplayName(value)+ return ok && normalized == value+}++func hasUnpairedSurrogateEscape(token []byte) bool {+ text := string(token)+ for index := 0; index+6 <= len(text); index++ {+ if text[index] != '\\' || text[index+1] != 'u' {+ continue+ }+ unit, err := strconv.ParseUint(text[index+2:index+6], 16, 32)+ if err != nil {+ continue+ }+ switch {+ case unit >= 0xd800 && unit <= 0xdbff:+ if index+12 > len(text) || text[index+6] != '\\' || text[index+7] != 'u' {+ return true+ }+ low, err := strconv.ParseUint(text[index+8:index+12], 16, 32)+ if err != nil || low < 0xdc00 || low > 0xdfff {+ return true+ }+ index += 11+ case unit >= 0xdc00 && unit <= 0xdfff:+ return true+ }+ }+ return false+}++// ValidStunURL ports isValidStunUrl from src/shared/protocol.ts. The+// TypeScript feeds "http://<authority>" to the WHATWG URL parser; net/url is+// more permissive in several places, so the extra checks below restore the+// WHATWG answers (see stun_test.go for the recorded comparisons).+func ValidStunURL(value string) bool {+ separator := strings.IndexByte(value, ':')+ if separator <= 0 || !asciiEqualFold(value[:separator], "stun") {+ return false+ }++ authority := value[separator+1:]+ if authority == "" || strings.HasSuffix(authority, ":") {+ return false+ }+ for _, character := range authority {+ if character == '\\' || character == '/' || character == '?' ||+ character == '#' || IsJSWhitespace(character) {+ return false+ }+ }++ parsed, err := url.Parse("http://" + authority)+ if err != nil {+ return false+ }+ // WHATWG reports an empty username/password for "@host" and ":@host";+ // net/url reports a non-nil Userinfo, so compare the parts, not the pointer.+ if parsed.User != nil {+ if parsed.User.Username() != "" {+ return false+ }+ if password, _ := parsed.User.Password(); password != "" {+ return false+ }+ }+ if hostname := parsed.Hostname(); hostname == "" || !validWHATWGHost(parsed.Host, hostname) {+ return false+ }+ if port := parsed.Port(); port != "" {+ // net/url accepts any digit run; WHATWG fails above 65535.+ number, err := strconv.Atoi(port)+ if err != nil || number <= 0 || number > 65535 {+ return false+ }+ }+ // net/url leaves Path empty where WHATWG reports "/". The authority scan+ // above already rejected "/", "?" and "#", so these are belt and braces.+ return (parsed.Path == "" || parsed.Path == "/") &&+ parsed.RawQuery == "" && parsed.Fragment == ""+}++func asciiEqualFold(left, right string) bool {+ if len(left) != len(right) {+ return false+ }+ for index := 0; index < len(left); index++ {+ if asciiLower(left[index]) != asciiLower(right[index]) {+ return false+ }+ }+ return true+}++func asciiLower(character byte) byte {+ if character >= 'A' && character <= 'Z' {+ return character + 'a' - 'A'+ }+ return character+}++// forbiddenDomainCodePoints is the WHATWG "forbidden domain code point" set+// minus the characters the authority scan already rejected.+const forbiddenDomainCodePoints = " #/:<>?@[\\]^|%"++func validWHATWGHost(rawHost, hostname string) bool {+ if strings.HasPrefix(rawHost, "[") {+ // net/url accepts "[1.2.3.4]" and IPv6 zone identifiers; the WHATWG+ // IPv6 parser accepts neither.+ return strings.Contains(hostname, ":") && !strings.Contains(hostname, "%")+ }+ for _, character := range hostname {+ if character <= 0x1f || character == 0x7f ||+ strings.ContainsRune(forbiddenDomainCodePoints, character) {+ return false+ }+ }+ if hostEndsInNumber(hostname) {+ return validIPv4Host(hostname)+ }+ return true+}++// hostEndsInNumber implements the WHATWG "ends in a number" checker.+func hostEndsInNumber(host string) bool {+ parts := strings.Split(host, ".")+ if len(parts) > 1 && parts[len(parts)-1] == "" {+ parts = parts[:len(parts)-1]+ }+ last := parts[len(parts)-1]+ if last != "" && isASCIIDigits(last) {+ return true+ }+ _, ok := parseIPv4Number(last)+ return ok+}++// validIPv4Host implements the WHATWG IPv4 parser's failure conditions.+func validIPv4Host(host string) bool {+ parts := strings.Split(host, ".")+ if len(parts) > 1 && parts[len(parts)-1] == "" {+ parts = parts[:len(parts)-1]+ }+ if len(parts) > 4 {+ return false+ }+ numbers := make([]uint64, 0, len(parts))+ for _, part := range parts {+ number, ok := parseIPv4Number(part)+ if !ok {+ return false+ }+ numbers = append(numbers, number)+ }+ for _, number := range numbers[:len(numbers)-1] {+ if number > 255 {+ return false+ }+ }+ limit := uint64(1)+ for index := 0; index < 5-len(numbers); index++ {+ limit *= 256+ }+ return numbers[len(numbers)-1] < limit+}++// parseIPv4Number implements the WHATWG IPv4 number parser (decimal, 0-octal+// and 0x-hexadecimal forms).+func parseIPv4Number(input string) (uint64, bool) {+ if input == "" {+ return 0, false+ }+ radix := 10+ switch {+ case len(input) >= 2 && (strings.HasPrefix(input, "0x") || strings.HasPrefix(input, "0X")):+ input, radix = input[2:], 16+ case len(input) >= 2 && input[0] == '0':+ input, radix = input[1:], 8+ }+ if input == "" {+ return 0, true+ }+ for index := 0; index < len(input); index++ {+ if radixDigit(input[index]) >= radix {+ return 0, false+ }+ }+ number, err := strconv.ParseUint(input, radix, 64)+ if err != nil {+ return 0, false+ }+ return number, true+}++func radixDigit(character byte) int {+ switch {+ case character >= '0' && character <= '9':+ return int(character - '0')+ case character >= 'a' && character <= 'f':+ return int(character-'a') + 10+ case character >= 'A' && character <= 'F':+ return int(character-'A') + 10+ }+ return 99+}++func isASCIIDigits(value string) bool {+ for index := 0; index < len(value); index++ {+ if value[index] < '0' || value[index] > '9' {+ return false+ }+ }+ return true+}diff --git a/internal/server/protocol/scalars_test.go b/internal/server/protocol/scalars_test.gonew file mode 100644index 00000000..2fb33467--- /dev/null+++ b/internal/server/protocol/scalars_test.go@@ -0,0 +1,207 @@+package protocol++import "testing"++func TestUTF16Len(t *testing.T) {+ // zod's string bounds count UTF-16 code units, so an astral code point+ // counts as two.+ for _, sample := range []struct {+ value string+ want int+ }{+ {"", 0},+ {"abc", 3},+ {"名", 1},+ {"\U0001f469", 2},+ {"\U0001f469\u200d\U0001f4bb", 5},+ } {+ if got := UTF16Length(sample.value); got != sample.want {+ t.Errorf("UTF16Length(%q) = %d, want %d", sample.value, got, sample.want)+ }+ }+}++func TestNormalizeDisplayName(t *testing.T) {+ for _, sample := range []struct {+ name string+ value string+ want string+ ok bool+ }{+ {"composes and collapses", " Café 朋友 ",+ "Café 朋友", true},+ {"keeps a zero width joiner sequence",+ "玩家 \U0001f469\u200d\U0001f4bb",+ "玩家 \U0001f469\u200d\U0001f4bb", true},+ {"accepts the code point limit",+ repeat("名", MaxDisplayNameCodePoints),+ repeat("名", MaxDisplayNameCodePoints), true},+ {"rejects one code point past the limit",+ repeat("名", MaxDisplayNameCodePoints+1), "", false},+ {"rejects a control character", "a\nb", "", false},+ {"rejects a bidi override", "a\u202eb", "", false},+ {"rejects a byte order mark", "a\ufeffb", "", false},+ {"rejects a zero width space", "a\u200bb", "", false},+ {"rejects an unpaired surrogate", "a\xed\xa0\x80b", "", false},+ {"rejects an all-space name", " ", "", false},+ } {+ t.Run(sample.name, func(t *testing.T) {+ got, ok := NormalizeDisplayName(sample.value)+ if ok != sample.ok || got != sample.want {+ t.Fatalf("NormalizeDisplayName(%q) = (%q, %v), want (%q, %v)",+ sample.value, got, ok, sample.want, sample.ok)+ }+ })+ }+}++func TestValidDisplayNameRequiresCanonicalForm(t *testing.T) {+ if ValidDisplayName(" Café ") {+ t.Error("a non-canonical display name must not validate")+ }+ if !ValidDisplayName("Café 朋友") {+ t.Error("a canonical display name must validate")+ }+ if ValidDisplayName("") {+ t.Error("an empty display name must not validate")+ }+}++func TestDisplayNameRejectsSurrogateEscapes(t *testing.T) {+ // encoding/json folds an unpaired escape to U+FFFD, so the raw token is the+ // only place the TypeScript surrogate rejection stays observable.+ var name DisplayName+ if err := name.UnmarshalJSON([]byte(`"a\ud800b"`)); err == nil {+ t.Fatal("an unpaired high surrogate escape must be rejected")+ }+ if err := name.UnmarshalJSON([]byte(`"a\udc00b"`)); err == nil {+ t.Fatal("an unpaired low surrogate escape must be rejected")+ }+ if err := name.UnmarshalJSON([]byte(`"a😀b"`)); err != nil {+ t.Fatalf("a surrogate pair escape must be accepted: %v", err)+ }+}++func TestScalarValidators(t *testing.T) {+ for _, sample := range []struct {+ name string+ valid func(string) bool+ value string+ want bool+ }{+ {"opaque id at floor", ValidOpaqueID, "abcdefgh", true},+ {"opaque id below floor", ValidOpaqueID, "abcdefg", false},+ {"opaque id with punctuation", ValidOpaqueID, "abcdefg.", false},+ {"opaque id at ceiling", ValidOpaqueID, repeat("a", 128), true},+ {"opaque id past ceiling", ValidOpaqueID, repeat("a", 129), false},+ {"token at floor", ValidToken, repeat("a", 32), true},+ {"token below floor", ValidToken, repeat("a", 31), false},+ {"token past ceiling", ValidToken, repeat("a", 129), false},+ {"room code", ValidRoomCode, "1234", true},+ {"room code with leading zero", ValidRoomCode, "0123", false},+ {"room code too long", ValidRoomCode, "12345", false},+ {"room code too short", ValidRoomCode, "123", false},+ {"viewer grant", ValidViewerGrant, repeat("b", 21) + "g", true},+ {"viewer grant short", ValidViewerGrant, repeat("b", 21), false},+ {"viewer grant long", ValidViewerGrant, repeat("b", 23), false},+ {"viewer grant padded", ValidViewerGrant, repeat("b", 21) + "=", false},+ {"viewer grant off alphabet tail", ValidViewerGrant, repeat("b", 21) + "b", false},+ {"viewer password minimal", ValidViewerPassword, "x", true},+ {"viewer password simple", ValidViewerPassword, "simple-password", true},+ {"viewer password empty", ValidViewerPassword, "", false},+ {"viewer password with space", ValidViewerPassword, "contains space", false},+ {"viewer password with newline", ValidViewerPassword, "line\nbreak", false},+ {"viewer password past ceiling", ValidViewerPassword,+ repeat("x", MaxViewerPasswordLength+1), false},+ {"livekit url", ValidLiveKitWebSocketURL, "wss://sfu.example.test", true},+ {"livekit url plain ws", ValidLiveKitWebSocketURL, "ws://127.0.0.1:7880", true},+ {"livekit url https", ValidLiveKitWebSocketURL, "https://sfu.example.test", false},+ {"livekit url relative", ValidLiveKitWebSocketURL, "/signal", false},+ } {+ t.Run(sample.name, func(t *testing.T) {+ if got := sample.valid(sample.value); got != sample.want {+ t.Fatalf("validator(%q) = %v, want %v", sample.value, got, sample.want)+ }+ })+ }+}++// TestValidStunURL records the WHATWG answers isValidStunUrl produces in the+// browser. The cases marked "net/url divergence" are the ones where Go's+// parser alone would disagree.+func TestValidStunURL(t *testing.T) {+ for _, sample := range []struct {+ value string+ want bool+ }{+ // tests/server-config.test.ts and tests/protocol.test.ts.+ {"stun:stun.test:3478", true},+ {"stun:share.test:5349", true},+ {"STUN:[2001:db8::1]:3478", true},+ {"stun:stun.test", true},+ {"stun:stun.test/path", false},+ {"stun:stun.test?transport=udp", false},+ {"stun:stun.test#fragment", false},+ {"stun:", false},+ {"stun:stun.test:", false},+ {"stun:stun.test:0", false},+ {"stun:[email protected]:3478", false},+ {"turn:turn.test:3478", false},+ {"stuns:stun.test:5349", false},+ {"stun:relay.example.test:3478?transport=udp", false},++ // net/url divergence: it accepts ports above 65535.+ {"stun:stun.test:65535", true},+ {"stun:stun.test:65536", false},+ {"stun:stun.test:99999", false},+ // net/url divergence: it accepts "<", ">" and "]" in a host name.+ {"stun:a<b:3478", false},+ {"stun:a>b:3478", false},+ {"stun:a]b:3478", false},+ {"stun:a|b:3478", false},+ {"stun:a^b:3478", false},+ // net/url divergence: it does not run the WHATWG IPv4 parser.+ {"stun:999.999.999.999", false},+ {"stun:1.2.3.4.5", false},+ {"stun:09.1", false},+ {"stun:1.2.3.256", false},+ {"stun:1.2.3.4", true},+ {"stun:1.2.3.4.", true},+ {"stun:0300.0250.0.1", true},+ {"stun:0x7f.1", true},+ {"stun:123", true},+ // net/url divergence: it accepts "[1.2.3.4]" and IPv6 zone ids.+ {"stun:[1.2.3.4]", false},+ {"stun:[notanip]:3478", false},+ {"stun:[2001:db8::1", false},+ {"stun:[::1]", true},+ // WHATWG treats empty userinfo as absent.+ {"stun:@stun.test:3478", true},+ {"stun::@stun.test:3478", true},+ {"stun::[email protected]:3478", false},+ {"stun:user:@stun.test:3478", false},+ // A host is mandatory and the authority scan rejects the framing+ // characters before net/url ever sees them.+ {"stun::3478", false},+ {"stun:stun.test:+3478", false},+ {"stun:stun.test:34a78", false},+ {"stun:stun test:3478", false},+ {"stun:stun.test\\path", false},+ {"stun:a_b.test", true},+ {"stun:stun.test:03478", true},+ } {+ t.Run(sample.value, func(t *testing.T) {+ if got := ValidStunURL(sample.value); got != sample.want {+ t.Fatalf("ValidStunURL(%q) = %v, want %v", sample.value, got, sample.want)+ }+ })+ }+}++func repeat(value string, count int) string {+ out := make([]byte, 0, len(value)*count)+ for index := 0; index < count; index++ {+ out = append(out, value...)+ }+ return string(out)+}diff --git a/internal/server/protocol/server.go b/internal/server/protocol/server.gonew file mode 100644index 00000000..c54c1dd3--- /dev/null+++ b/internal/server/protocol/server.go@@ -0,0 +1,691 @@+package protocol++import (+ "errors"+ "fmt"+)++// ServerMessage is one member of serverMessageSchema. The interface is sealed:+// only the message structs in this file implement it.+type ServerMessage interface {+ isServerMessage()+}++// AuthenticatedHostMessage is the host member of authenticatedMessageSchema.+// The field order is the emission order of the object literal in+// src/server/signaling.ts (`role` and `viewerPasswordEnabled` are appended+// after the shared base spread).+type AuthenticatedHostMessage struct {+ Type string `json:"type"`+ Protocol string `json:"protocol"`+ PeerID string `json:"peerId"`+ RoomExpiresAt *string `json:"roomExpiresAt"`+ MaxViewers Int `json:"maxViewers"`+ EndpointMediaCopyCapacity Int `json:"endpointMediaCopyCapacity"`+ HostOnline bool `json:"hostOnline"`+ HostPaused *bool `json:"hostPaused,omitempty"`+ ConnectionID *string `json:"connectionId"`+ IceConfig IceConfig `json:"iceConfig"`+ RoutePolicy RoutePolicy `json:"routePolicy"`+ CodeEntryPolicy CodeEntryPolicy `json:"codeEntryPolicy"`+ ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`+ MediaMode string `json:"mediaMode"`+ ShareGeneration *string `json:"shareGeneration"`+ RouteRevision Int `json:"routeRevision"`+ RouteAssignment ParticipantRouteAssignment `json:"routeAssignment"`+ QualitySettings QualitySettings `json:"qualitySettings"`+ SfuStandbyURL *string `json:"sfuStandbyUrl,omitempty"`+ Role Role `json:"role"`+ ViewerPasswordEnabled bool `json:"viewerPasswordEnabled"`+}++// AuthenticatedViewerMessage is the viewer member of+// authenticatedMessageSchema.+type AuthenticatedViewerMessage struct {+ Type string `json:"type"`+ Protocol string `json:"protocol"`+ PeerID string `json:"peerId"`+ RoomExpiresAt *string `json:"roomExpiresAt"`+ MaxViewers Int `json:"maxViewers"`+ EndpointMediaCopyCapacity Int `json:"endpointMediaCopyCapacity"`+ HostOnline bool `json:"hostOnline"`+ HostPaused *bool `json:"hostPaused,omitempty"`+ ConnectionID *string `json:"connectionId"`+ IceConfig IceConfig `json:"iceConfig"`+ RoutePolicy RoutePolicy `json:"routePolicy"`+ CodeEntryPolicy CodeEntryPolicy `json:"codeEntryPolicy"`+ ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`+ MediaMode string `json:"mediaMode"`+ ShareGeneration *string `json:"shareGeneration"`+ RouteRevision Int `json:"routeRevision"`+ RouteAssignment ParticipantRouteAssignment `json:"routeAssignment"`+ QualitySettings QualitySettings `json:"qualitySettings"`+ SfuStandbyURL *string `json:"sfuStandbyUrl,omitempty"`+ Role Role `json:"role"`+}++// SignalingChallengeResponseMessage is the challenge echo.+type SignalingChallengeResponseMessage struct {+ Type string `json:"type"`+ Sequence Int `json:"sequence"`+}++// ServerSignalMessage is the forwarded "signal" message.+type ServerSignalMessage struct {+ Type string `json:"type"`+ FromPeerID string `json:"fromPeerId"`+ Payload SignalPayload `json:"payload"`+}++// ServerRestartRequestMessage is the forwarded "restart-request" message.+type ServerRestartRequestMessage struct {+ Type string `json:"type"`+ FromPeerID string `json:"fromPeerId"`+ ConnectionID string `json:"connectionId"`+ Rebuild bool `json:"rebuild"`+}++// RouteUpdatePrepareMessage is the phase "prepare" member of route-update.+type RouteUpdatePrepareMessage struct {+ Type string `json:"type"`+ Revision Int `json:"revision"`+ Phase string `json:"phase"`+ Assignment ParticipantRouteAssignment `json:"assignment"`+ Candidate PreparedRouteCandidate `json:"candidate"`+}++// RouteUpdateActiveMessage is the phase "active" member of route-update.+type RouteUpdateActiveMessage struct {+ Type string `json:"type"`+ Revision Int `json:"revision"`+ Phase string `json:"phase"`+ Assignment ParticipantRouteAssignment `json:"assignment"`+}++// RouteStatusMessage is the crossed (state, reason) union: "waiting" pairs+// with "sfu-admission" and "failed" pairs with "route-exhausted".+type RouteStatusMessage struct {+ Type string `json:"type"`+ Revision Int `json:"revision"`+ State string `json:"state"`+ Reason string `json:"reason"`+}++// RouteDiagnosticSnapshotMessage carries the privacy-safe route snapshot.+type RouteDiagnosticSnapshotMessage struct {+ Type string `json:"type"`+ Snapshot RouteDiagnosticSnapshot `json:"snapshot"`+}++// SfuConfigMessage carries a LiveKit URL and a short-lived token.+type SfuConfigMessage struct {+ Type string `json:"type"`+ Revision Int `json:"revision"`+ URL string `json:"url"`+ Token string `json:"token"`+}++// QualitySettingsMessage broadcasts the host's quality settings.+type QualitySettingsMessage struct {+ Type string `json:"type"`+ QualitySettings QualitySettings `json:"qualitySettings"`+}++// RoutePolicyMessage broadcasts the host's route policy.+type RoutePolicyMessage struct {+ Type string `json:"type"`+ ShareGeneration string `json:"shareGeneration"`+ RoutePolicy RoutePolicy `json:"routePolicy"`+ SfuStandbyURL *string `json:"sfuStandbyUrl,omitempty"`+}++// PauseSharingSourceMessage asks the host to pause its capture source.+type PauseSharingSourceMessage struct {+ Type string `json:"type"`+ ShareGeneration string `json:"shareGeneration"`+}++// ServerViewerQualityEvidenceMessage is the forwarded evidence envelope.+type ServerViewerQualityEvidenceMessage struct {+ Type string `json:"type"`+ ViewerPeerID string `json:"viewerPeerId"`+ Upstream MediaRouteUpstream `json:"upstream"`+ Guard ViewerQualityEvidenceGuard `json:"guard"`+ Sequence Int `json:"sequence"`+ WindowMs Int `json:"windowMs"`+ Metrics ViewerQualityEvidenceMetrics `json:"metrics"`+}++// HostStatusMessage reports host presence and pause state.+type HostStatusMessage struct {+ Type string `json:"type"`+ Online bool `json:"online"`+ Paused bool `json:"paused"`+}++// ViewerPresenceMessage carries the ordered participant roster.+type ViewerPresenceMessage struct {+ Type string `json:"type"`+ Viewers []ParticipantPresenceEntry `json:"viewers"`+}++// MarshalJSON implements json.Marshaler.+func (v ViewerPresenceMessage) MarshalJSON() ([]byte, error) {+ type raw ViewerPresenceMessage+ value := raw(v)+ if value.Viewers == nil {+ value.Viewers = []ParticipantPresenceEntry{}+ }+ return marshalJSON(value)+}++// ViewerGrantRevokedMessage announces a superseded viewer authorization.+type ViewerGrantRevokedMessage struct {+ Type string `json:"type"`+ ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`+}++// SharingStoppedMessage is { type: "sharing-stopped" }.+type SharingStoppedMessage struct {+ Type string `json:"type"`+}++// RoomClosedMessage is { type: "room-closed", reason }.+type RoomClosedMessage struct {+ Type string `json:"type"`+ Reason string `json:"reason"`+}++// ErrorMessage is { type: "error", code, message }.+type ErrorMessage struct {+ Type string `json:"type"`+ Code string `json:"code"`+ Message string `json:"message"`+}++func (AuthenticatedHostMessage) isServerMessage() {}+func (AuthenticatedViewerMessage) isServerMessage() {}+func (SignalingChallengeResponseMessage) isServerMessage() {}+func (ServerSignalMessage) isServerMessage() {}+func (ServerRestartRequestMessage) isServerMessage() {}+func (RouteUpdatePrepareMessage) isServerMessage() {}+func (RouteUpdateActiveMessage) isServerMessage() {}+func (RouteStatusMessage) isServerMessage() {}+func (RouteDiagnosticSnapshotMessage) isServerMessage() {}+func (SfuConfigMessage) isServerMessage() {}+func (QualitySettingsMessage) isServerMessage() {}+func (RoutePolicyMessage) isServerMessage() {}+func (PauseSharingSourceMessage) isServerMessage() {}+func (ServerViewerQualityEvidenceMessage) isServerMessage() {}+func (HostStatusMessage) isServerMessage() {}+func (ViewerPresenceMessage) isServerMessage() {}+func (ViewerGrantRevokedMessage) isServerMessage() {}+func (SharingStoppedMessage) isServerMessage() {}+func (RoomClosedMessage) isServerMessage() {}+func (ErrorMessage) isServerMessage() {}++// EncodeServerMessage serializes one server message with the key order of the+// TypeScript object literal that produces it.+func EncodeServerMessage(message ServerMessage) ([]byte, error) {+ return marshalJSON(message)+}++// DecodeServerMessage ports decodeServerMessage. The server never reads its+// own messages in production; this exists so the shared wire fixture can be+// replayed from Go.+func DecodeServerMessage(data []byte) (ServerMessage, error) {+ messageType, err := typeOf(data, "type")+ if err != nil {+ return nil, err+ }+ switch messageType {+ case "authenticated":+ return decodeAuthenticated(data)+ case "signaling-challenge-response":+ return decodeChallengeResponse(data)+ case "signal":+ return decodeServerSignal(data)+ case "restart-request":+ return decodeServerRestartRequest(data)+ case "route-update":+ return decodeRouteUpdate(data)+ case "route-status":+ return decodeRouteStatus(data)+ case "route-diagnostic-snapshot":+ return decodeRouteDiagnosticSnapshotMessage(data)+ case "sfu-config":+ return decodeSfuConfig(data)+ case "quality-settings":+ return decodeQualitySettingsMessage(data)+ case "route-policy":+ return decodeRoutePolicyMessage(data)+ case "pause-sharing-source":+ return decodePauseSharingSource(data)+ case "viewer-quality-evidence":+ return decodeServerViewerQualityEvidence(data)+ case "host-status":+ return decodeHostStatus(data)+ case "viewer-presence":+ return decodeViewerPresence(data)+ case "viewer-grant-revoked":+ return decodeViewerGrantRevoked(data)+ case "sharing-stopped":+ return decodeEmptyServerMessage(data, SharingStoppedMessage{Type: messageType})+ case "room-closed":+ return decodeRoomClosed(data)+ case "error":+ return decodeErrorMessage(data)+ }+ return nil, fmt.Errorf("unknown server message type %q", messageType)+}++func decodeEmptyServerMessage(data []byte, message ServerMessage) (ServerMessage, error) {+ var body struct {+ Type string `json:"type"`+ }+ present, err := decodeObject(data, &body)+ if err != nil {+ return nil, err+ }+ if err := present.require("type"); err != nil {+ return nil, err+ }+ return message, nil+}++func validateAuthenticatedBase(+ present fields,+ protocol string, peerID string, roomExpiresAt *string,+ maxViewers, endpointCapacity Int, connectionID *string,+ codeEntryPolicy, viewerAuthorizationGeneration, mediaMode string,+ shareGeneration *string, routeRevision Int, sfuStandbyURL *string,+) error {+ if err := present.require("type", "protocol", "peerId", "maxViewers",+ "endpointMediaCopyCapacity", "hostOnline", "iceConfig", "codeEntryPolicy",+ "viewerAuthorizationGeneration", "mediaMode", "routeRevision",+ "routeAssignment", "qualitySettings", "role"); err != nil {+ return err+ }+ if err := present.requireNullable(+ "roomExpiresAt", "connectionId", "shareGeneration"); err != nil {+ return err+ }+ if err := present.optional("hostPaused", "routePolicy", "sfuStandbyUrl"); err != nil {+ return err+ }+ if protocol != SignalingProtocol {+ return errors.New("protocol is not the current signaling generation")+ }+ if !ValidOpaqueID(peerID) {+ return errors.New("peerId is not an opaque id")+ }+ if roomExpiresAt != nil && !ValidISODateTime(*roomExpiresAt) {+ return errors.New("roomExpiresAt is not an ISO instant")+ }+ if !inRangeInt(maxViewers, 1, MaxViewersPerRoomLimit) {+ return errors.New("maxViewers is out of range")+ }+ if !inRangeInt(endpointCapacity, 1, MaxEndpointMediaCopyCapacity) {+ return errors.New("endpointMediaCopyCapacity is out of range")+ }+ if connectionID != nil && !ValidOpaqueID(*connectionID) {+ return errors.New("connectionId is not an opaque id")+ }+ if !enumOf(codeEntryPolicy, CodeEntryOpen, CodeEntryPrivate) {+ return fmt.Errorf("unknown codeEntryPolicy %q", codeEntryPolicy)+ }+ if !ValidOpaqueID(viewerAuthorizationGeneration) {+ return errors.New("viewerAuthorizationGeneration is not an opaque id")+ }+ if mediaMode != "peer-assisted" {+ return errors.New("mediaMode must be peer-assisted")+ }+ if shareGeneration != nil && !ValidOpaqueID(*shareGeneration) {+ return errors.New("shareGeneration is not an opaque id")+ }+ if !validRevision(routeRevision) {+ return errors.New("routeRevision is out of range")+ }+ if sfuStandbyURL != nil && !ValidLiveKitWebSocketURL(*sfuStandbyURL) {+ return errors.New("sfuStandbyUrl is not a LiveKit WebSocket URL")+ }+ return nil+}++func decodeAuthenticated(data []byte) (ServerMessage, error) {+ role, err := typeOf(data, "role")+ if err != nil {+ return nil, err+ }+ switch role {+ case RoleHost:+ var message AuthenticatedHostMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("viewerPasswordEnabled"); err != nil {+ return nil, err+ }+ if err := validateAuthenticatedBase(present, message.Protocol, message.PeerID,+ message.RoomExpiresAt, message.MaxViewers, message.EndpointMediaCopyCapacity,+ message.ConnectionID, message.CodeEntryPolicy,+ message.ViewerAuthorizationGeneration, message.MediaMode,+ message.ShareGeneration, message.RouteRevision, message.SfuStandbyURL); err != nil {+ return nil, err+ }+ if !present.has("routePolicy") {+ message.RoutePolicy = DefaultRoutePolicy+ }+ return message, nil+ case RoleViewer:+ var message AuthenticatedViewerMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := validateAuthenticatedBase(present, message.Protocol, message.PeerID,+ message.RoomExpiresAt, message.MaxViewers, message.EndpointMediaCopyCapacity,+ message.ConnectionID, message.CodeEntryPolicy,+ message.ViewerAuthorizationGeneration, message.MediaMode,+ message.ShareGeneration, message.RouteRevision, message.SfuStandbyURL); err != nil {+ return nil, err+ }+ if !present.has("routePolicy") {+ message.RoutePolicy = DefaultRoutePolicy+ }+ return message, nil+ }+ return nil, fmt.Errorf("unknown authenticated role %q", role)+}++func decodeChallengeResponse(data []byte) (ServerMessage, error) {+ var message SignalingChallengeResponseMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "sequence"); err != nil {+ return nil, err+ }+ if !inRangeInt(message.Sequence, 0, MaxSafeInteger) {+ return nil, errors.New("sequence is out of range")+ }+ return message, nil+}++func decodeServerSignal(data []byte) (ServerMessage, error) {+ var message ServerSignalMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "fromPeerId", "payload"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(message.FromPeerID) {+ return nil, errors.New("fromPeerId is not an opaque id")+ }+ return message, nil+}++func decodeServerRestartRequest(data []byte) (ServerMessage, error) {+ var message ServerRestartRequestMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "fromPeerId", "connectionId", "rebuild"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(message.FromPeerID) || !ValidOpaqueID(message.ConnectionID) {+ return nil, errors.New("restart-request ids are not opaque ids")+ }+ return message, nil+}++func decodeRouteUpdate(data []byte) (ServerMessage, error) {+ phase, err := typeOf(data, "phase")+ if err != nil {+ return nil, err+ }+ switch phase {+ case "prepare":+ var message RouteUpdatePrepareMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require(+ "type", "revision", "phase", "assignment", "candidate"); err != nil {+ return nil, err+ }+ if !validRevision(message.Revision) {+ return nil, errors.New("revision is out of range")+ }+ return message, nil+ case "active":+ var message RouteUpdateActiveMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "revision", "phase", "assignment"); err != nil {+ return nil, err+ }+ if !validRevision(message.Revision) {+ return nil, errors.New("revision is out of range")+ }+ return message, nil+ }+ return nil, fmt.Errorf("unknown route-update phase %q", phase)+}++func decodeRouteStatus(data []byte) (ServerMessage, error) {+ var message RouteStatusMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "revision", "state", "reason"); err != nil {+ return nil, err+ }+ if !validRevision(message.Revision) {+ return nil, errors.New("revision is out of range")+ }+ switch {+ case message.State == "waiting" && message.Reason == "sfu-admission":+ case message.State == "failed" && message.Reason == "route-exhausted":+ default:+ return nil, fmt.Errorf(+ "route-status pairs state %q with reason %q", message.State, message.Reason)+ }+ return message, nil+}++func decodeRouteDiagnosticSnapshotMessage(data []byte) (ServerMessage, error) {+ var message RouteDiagnosticSnapshotMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "snapshot"); err != nil {+ return nil, err+ }+ return message, nil+}++func decodeSfuConfig(data []byte) (ServerMessage, error) {+ var message SfuConfigMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "revision", "url", "token"); err != nil {+ return nil, err+ }+ if !validRevision(message.Revision) {+ return nil, errors.New("revision is out of range")+ }+ if !ValidLiveKitWebSocketURL(message.URL) {+ return nil, errors.New("url is not a LiveKit WebSocket URL")+ }+ if length := UTF16Length(message.Token); length < 1 || length > MaxSfuTokenLength {+ return nil, errors.New("token length is out of range")+ }+ return message, nil+}++func decodeQualitySettingsMessage(data []byte) (ServerMessage, error) {+ var message QualitySettingsMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "qualitySettings"); err != nil {+ return nil, err+ }+ return message, nil+}++func decodeRoutePolicyMessage(data []byte) (ServerMessage, error) {+ var message RoutePolicyMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "shareGeneration", "routePolicy"); err != nil {+ return nil, err+ }+ if err := present.optional("sfuStandbyUrl"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(message.ShareGeneration) {+ return nil, errors.New("shareGeneration is not an opaque id")+ }+ if message.SfuStandbyURL != nil && !ValidLiveKitWebSocketURL(*message.SfuStandbyURL) {+ return nil, errors.New("sfuStandbyUrl is not a LiveKit WebSocket URL")+ }+ return message, nil+}++func decodePauseSharingSource(data []byte) (ServerMessage, error) {+ var message PauseSharingSourceMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "shareGeneration"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(message.ShareGeneration) {+ return nil, errors.New("shareGeneration is not an opaque id")+ }+ return message, nil+}++func decodeServerViewerQualityEvidence(data []byte) (ServerMessage, error) {+ var message ServerViewerQualityEvidenceMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "viewerPeerId", "upstream", "guard",+ "sequence", "windowMs", "metrics"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(message.ViewerPeerID) {+ return nil, errors.New("viewerPeerId is not an opaque id")+ }+ // The forwarded envelope narrows the upstream to the active variants.+ if message.Upstream.Kind != "peer" && message.Upstream.Kind != "sfu" {+ return nil, errors.New("forwarded evidence upstream must be peer or sfu")+ }+ if err := validateEvidenceWindow(message.Sequence, message.WindowMs); err != nil {+ return nil, err+ }+ return message, nil+}++func decodeHostStatus(data []byte) (ServerMessage, error) {+ var message HostStatusMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "online", "paused"); err != nil {+ return nil, err+ }+ return message, nil+}++func decodeViewerPresence(data []byte) (ServerMessage, error) {+ var message ViewerPresenceMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "viewers"); err != nil {+ return nil, err+ }+ if len(message.Viewers) > MaxParticipantsPerRoomLimit {+ return nil, errors.New("viewer presence holds too many entries")+ }+ // superRefine: viewer presence peer IDs must be unique.+ seen := make(map[string]struct{}, len(message.Viewers))+ for _, viewer := range message.Viewers {+ if _, duplicate := seen[viewer.PeerID]; duplicate {+ return nil, errors.New("Viewer presence peer IDs must be unique")+ }+ seen[viewer.PeerID] = struct{}{}+ }+ return message, nil+}++func decodeViewerGrantRevoked(data []byte) (ServerMessage, error) {+ var message ViewerGrantRevokedMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "viewerAuthorizationGeneration"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(message.ViewerAuthorizationGeneration) {+ return nil, errors.New("viewerAuthorizationGeneration is not an opaque id")+ }+ return message, nil+}++func decodeRoomClosed(data []byte) (ServerMessage, error) {+ var message RoomClosedMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "reason"); err != nil {+ return nil, err+ }+ if !enumOf(message.Reason, "host-ended", "expired") {+ return nil, fmt.Errorf("unknown room-closed reason %q", message.Reason)+ }+ return message, nil+}++func decodeErrorMessage(data []byte) (ServerMessage, error) {+ var message ErrorMessage+ present, err := decodeObject(data, &message)+ if err != nil {+ return nil, err+ }+ if err := present.require("type", "code", "message"); err != nil {+ return nil, err+ }+ if !enumOf(message.Code, errorCodes...) {+ return nil, fmt.Errorf("unknown error code %q", message.Code)+ }+ if length := UTF16Length(message.Message); length < 1 || length > 256 {+ return nil, errors.New("error message length is out of range")+ }+ return message, nil+}diff --git a/internal/server/protocol/types.go b/internal/server/protocol/types.gonew file mode 100644index 00000000..25a5f07b--- /dev/null+++ b/internal/server/protocol/types.go@@ -0,0 +1,1089 @@+package protocol++import (+ "encoding/json"+ "errors"+ "fmt"+ "regexp"+)++// Role mirrors roleSchema.+type Role = string++// Roles.+const (+ RoleHost Role = "host"+ RoleViewer Role = "viewer"+)++// CodeEntryPolicy mirrors codeEntryPolicySchema.+type CodeEntryPolicy = string++// Code entry policies.+const (+ CodeEntryOpen CodeEntryPolicy = "open"+ CodeEntryPrivate CodeEntryPolicy = "private"+)++// Codec evidence patterns from viewerQualityEvidenceMetricsSchema.+var (+ codecProfilePattern = regexp.MustCompile(`^[a-z0-9-]+=[a-z0-9]+$`)+ codecParametersPattern = regexp.MustCompile(+ `^[a-z0-9-]+=[a-z0-9]+(?:; [a-z0-9-]+=[a-z0-9]+)*$`)+ audioMimeTypePattern = regexp.MustCompile(`(?i)^audio/[A-Za-z0-9.+-]{1,32}$`)+)++// Enumerations mirrored from src/shared/protocol.ts.+var (+ qualityResolutions = []string{"480p", "720p", "1080p", "1440p"}+ degradationPreferences = []string{"maintain-resolution", "balanced", "maintain-framerate"}+ screenAudioQualities = []string{"saver", "music", "very-high"}+ mediaRoutePhases = []string{"prepare", "active"}+ routeDemandReasons = []string{"join", "edge-unavailable", "parent-departed", "capacity-reduction", "sfu-bootstrap", "direct-convergence", "quality-convergence", "root-convergence"}+ routeDiagnosticFinalRoutes = []string{"direct", "sfu", "waiting", "failed"}+ routeDiagnosticBuckets = []string{"none", "stale", "endpoint-capacity", "sfu-admission", "candidate-failed", "first-frame-timeout", "operation-deadline", "aborted"}+ routeDiagnosticStages = []string{"admission", "first-frame", "quality-proof"}+ senderQualityStates = []string{"unknown", "healthy", "degraded"}+ senderQualityDegradedReasons = []string{"none", "bandwidth", "cpu"}+ errorCodes = []string{"AUTH_REQUIRED", "INVALID_MESSAGE", "INVALID_TOKEN", "ROOM_ACCESS_DENIED", "ROOM_NOT_FOUND", "ROOM_EXPIRED", "ROOM_FULL", "HOST_ALREADY_CONNECTED", "PEER_NOT_FOUND", "FORBIDDEN", "SERVER_ERROR"}+)++func validRevision(revision Int) bool {+ return inRangeInt(revision, 0, MaxMediaRouteRevision)+}++// ---------------------------------------------------------------------------+// mediaRouteUpstreamSchema+// ---------------------------------------------------------------------------++// MediaRouteUpstream mirrors mediaRouteUpstreamSchema.+type MediaRouteUpstream struct {+ Kind string `json:"kind"`+ PeerID string `json:"peerId,omitempty"`+}++// NoUpstream builds { kind: "none" }.+func NoUpstream() MediaRouteUpstream { return MediaRouteUpstream{Kind: "none"} }++// PeerUpstream builds { kind: "peer", peerId }.+func PeerUpstream(peerID string) MediaRouteUpstream {+ return MediaRouteUpstream{Kind: "peer", PeerID: peerID}+}++// SfuUpstream builds { kind: "sfu" }.+func SfuUpstream() MediaRouteUpstream { return MediaRouteUpstream{Kind: "sfu"} }++// UnmarshalJSON implements json.Unmarshaler.+func (v *MediaRouteUpstream) UnmarshalJSON(data []byte) error {+ *v = MediaRouteUpstream{}+ type raw MediaRouteUpstream+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("kind"); err != nil {+ return err+ }+ switch v.Kind {+ case "none", "sfu":+ if present.has("peerId") {+ return fmt.Errorf("upstream %q must not carry peerId", v.Kind)+ }+ case "peer":+ if err := present.require("peerId"); err != nil {+ return err+ }+ if !ValidOpaqueID(v.PeerID) {+ return errors.New("upstream peerId is not an opaque id")+ }+ default:+ return fmt.Errorf("unknown upstream kind %q", v.Kind)+ }+ return nil+}++// ---------------------------------------------------------------------------+// qualitySettingsSchema / routePolicySchema / runtimeCapabilitiesSchema+// ---------------------------------------------------------------------------++// QualitySettings mirrors qualitySettingsSchema.+type QualitySettings struct {+ Resolution string `json:"resolution"`+ MaxFramerate Int `json:"maxFramerate"`+ MaxBitrate Int `json:"maxBitrate"`+ DegradationPreference string `json:"degradationPreference"`+ ScreenAudioQuality string `json:"screenAudioQuality,omitempty"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *QualitySettings) UnmarshalJSON(data []byte) error {+ *v = QualitySettings{}+ type raw QualitySettings+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require(+ "resolution", "maxFramerate", "maxBitrate", "degradationPreference"); err != nil {+ return err+ }+ if err := present.optional("screenAudioQuality"); err != nil {+ return err+ }+ if !enumOf(v.Resolution, qualityResolutions...) {+ return fmt.Errorf("unknown resolution %q", v.Resolution)+ }+ if !inRangeInt(v.MaxFramerate, 15, 60) {+ return errors.New("maxFramerate is out of range")+ }+ if !inRangeInt(v.MaxBitrate, 2_000_000, 12_000_000) {+ return errors.New("maxBitrate is out of range")+ }+ if !enumOf(v.DegradationPreference, degradationPreferences...) {+ return fmt.Errorf("unknown degradationPreference %q", v.DegradationPreference)+ }+ if present.has("screenAudioQuality") && !enumOf(v.ScreenAudioQuality, screenAudioQualities...) {+ return fmt.Errorf("unknown screenAudioQuality %q", v.ScreenAudioQuality)+ }+ return nil+}++// RoutePolicy mirrors routePolicySchema.+type RoutePolicy struct {+ PeerOnly bool `json:"peerOnly"`+ TopologyOptimization bool `json:"topologyOptimization"`+ NatPrediction bool `json:"natPrediction"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *RoutePolicy) UnmarshalJSON(data []byte) error {+ *v = RoutePolicy{}+ type raw RoutePolicy+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ return present.require("peerOnly", "topologyOptimization", "natPrediction")+}++// RuntimeCapabilities mirrors runtimeCapabilitiesSchema.+type RuntimeCapabilities struct {+ NatPrediction bool `json:"natPrediction"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *RuntimeCapabilities) UnmarshalJSON(data []byte) error {+ *v = RuntimeCapabilities{}+ type raw RuntimeCapabilities+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ return present.require("natPrediction")+}++// ---------------------------------------------------------------------------+// iceConfigSchema+// ---------------------------------------------------------------------------++// IceServerURLs mirrors z.union([stunUrlSchema, z.array(stunUrlSchema)]).+type IceServerURLs struct {+ Single string+ List []string+}++// IceServerURLList builds the array form.+func IceServerURLList(urls ...string) IceServerURLs {+ if urls == nil {+ urls = []string{}+ }+ return IceServerURLs{List: urls}+}++// MarshalJSON implements json.Marshaler.+func (v IceServerURLs) MarshalJSON() ([]byte, error) {+ if v.List != nil {+ return marshalJSON(v.List)+ }+ return marshalJSON(v.Single)+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *IceServerURLs) UnmarshalJSON(data []byte) error {+ *v = IceServerURLs{}+ if len(data) > 0 && data[0] == '[' {+ var list []string+ if err := json.Unmarshal(data, &list); err != nil {+ return err+ }+ if len(list) < 1 || len(list) > MaxIceServerURLs {+ return errors.New("iceServers[].urls length is out of range")+ }+ for _, url := range list {+ if !ValidStunURLValue(url) {+ return errors.New("Invalid STUN URL")+ }+ }+ v.List = list+ return nil+ }+ var single string+ if err := json.Unmarshal(data, &single); err != nil {+ return err+ }+ if !ValidStunURLValue(single) {+ return errors.New("Invalid STUN URL")+ }+ v.Single = single+ return nil+}++// ValidStunURLValue mirrors stunUrlSchema: 1..512 UTF-16 code units plus+// isValidStunUrl. It is the single owner of that bound; config validates+// STUN_URLS and the Client's local STUN list through it.+func ValidStunURLValue(value string) bool {+ length := UTF16Length(value)+ return length >= 1 && length <= MaxStunURLLength && ValidStunURL(value)+}++// IceServer mirrors iceServerSchema.+type IceServer struct {+ URLs IceServerURLs `json:"urls"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *IceServer) UnmarshalJSON(data []byte) error {+ *v = IceServer{}+ type raw IceServer+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ return present.require("urls")+}++// IceConfig mirrors iceConfigSchema.+type IceConfig struct {+ IceServers []IceServer `json:"iceServers"`+ NatPredictionStunURLs []string `json:"natPredictionStunUrls"`+}++// MarshalJSON implements json.Marshaler.+func (v IceConfig) MarshalJSON() ([]byte, error) {+ type raw IceConfig+ value := raw(v)+ if value.IceServers == nil {+ value.IceServers = []IceServer{}+ }+ if value.NatPredictionStunURLs == nil {+ value.NatPredictionStunURLs = []string{}+ }+ return marshalJSON(value)+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *IceConfig) UnmarshalJSON(data []byte) error {+ *v = IceConfig{}+ type raw IceConfig+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("iceServers", "natPredictionStunUrls"); err != nil {+ return err+ }+ if len(v.IceServers) > 8 {+ return errors.New("iceServers holds too many entries")+ }+ if len(v.NatPredictionStunURLs) > MaxNatPredictionAuxiliaryStunURLs {+ return errors.New("natPredictionStunUrls holds too many entries")+ }+ for _, url := range v.NatPredictionStunURLs {+ if !ValidStunURLValue(url) {+ return errors.New("Invalid STUN URL")+ }+ }+ return nil+}++// ---------------------------------------------------------------------------+// signalPayloadSchema+// ---------------------------------------------------------------------------++// SessionDescription mirrors sessionDescriptionSchema.+type SessionDescription struct {+ Type string `json:"type"`+ SDP string `json:"sdp"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *SessionDescription) UnmarshalJSON(data []byte) error {+ *v = SessionDescription{}+ type raw SessionDescription+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("type", "sdp"); err != nil {+ return err+ }+ if !enumOf(v.Type, "offer", "answer") {+ return fmt.Errorf("unknown description type %q", v.Type)+ }+ if length := UTF16Length(v.SDP); length < 1 || length > 48*1024 {+ return errors.New("sdp length is out of range")+ }+ return nil+}++// IceCandidate mirrors iceCandidateSchema.+type IceCandidate struct {+ Candidate string `json:"candidate"`+ SDPMid Nullable[string] `json:"sdpMid,omitzero"`+ SDPMLineIndex Nullable[Int] `json:"sdpMLineIndex,omitzero"`+ UsernameFragment Nullable[string] `json:"usernameFragment,omitzero"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *IceCandidate) UnmarshalJSON(data []byte) error {+ *v = IceCandidate{}+ type raw IceCandidate+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("candidate"); err != nil {+ return err+ }+ if UTF16Length(v.Candidate) > 4096 {+ return errors.New("candidate is too long")+ }+ if v.SDPMid.Value != nil && UTF16Length(*v.SDPMid.Value) > 128 {+ return errors.New("sdpMid is too long")+ }+ if v.SDPMLineIndex.Value != nil && !inRangeInt(*v.SDPMLineIndex.Value, 0, 255) {+ return errors.New("sdpMLineIndex is out of range")+ }+ if v.UsernameFragment.Value != nil && UTF16Length(*v.UsernameFragment.Value) > 256 {+ return errors.New("usernameFragment is too long")+ }+ return nil+}++// SignalPayload mirrors signalPayloadSchema. Candidate is nil for the JSON+// null the "candidate" variant requires.+type SignalPayload struct {+ Kind string+ ConnectionID string+ Description *SessionDescription+ Candidate *IceCandidate+}++// MarshalJSON implements json.Marshaler.+func (v SignalPayload) MarshalJSON() ([]byte, error) {+ if v.Kind == "description" {+ return marshalJSON(struct {+ Kind string `json:"kind"`+ ConnectionID string `json:"connectionId"`+ Description *SessionDescription `json:"description"`+ }{v.Kind, v.ConnectionID, v.Description})+ }+ return marshalJSON(struct {+ Kind string `json:"kind"`+ ConnectionID string `json:"connectionId"`+ Candidate *IceCandidate `json:"candidate"`+ }{v.Kind, v.ConnectionID, v.Candidate})+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *SignalPayload) UnmarshalJSON(data []byte) error {+ *v = SignalPayload{}+ kind, err := typeOf(data, "kind")+ if err != nil {+ return err+ }+ switch kind {+ case "description":+ var body struct {+ Kind string `json:"kind"`+ ConnectionID string `json:"connectionId"`+ Description *SessionDescription `json:"description"`+ }+ present, err := decodeObject(data, &body)+ if err != nil {+ return err+ }+ if err := present.require("kind", "connectionId", "description"); err != nil {+ return err+ }+ if !ValidOpaqueID(body.ConnectionID) {+ return errors.New("connectionId is not an opaque id")+ }+ *v = SignalPayload{Kind: kind, ConnectionID: body.ConnectionID, Description: body.Description}+ return nil+ case "candidate":+ var body struct {+ Kind string `json:"kind"`+ ConnectionID string `json:"connectionId"`+ Candidate *IceCandidate `json:"candidate"`+ }+ present, err := decodeObject(data, &body)+ if err != nil {+ return err+ }+ if err := present.require("kind", "connectionId"); err != nil {+ return err+ }+ if err := present.requireNullable("candidate"); err != nil {+ return err+ }+ if !ValidOpaqueID(body.ConnectionID) {+ return errors.New("connectionId is not an opaque id")+ }+ *v = SignalPayload{Kind: kind, ConnectionID: body.ConnectionID, Candidate: body.Candidate}+ return nil+ }+ return fmt.Errorf("unknown signal payload kind %q", kind)+}++// ---------------------------------------------------------------------------+// preparedRouteCandidateSchema / participantRouteAssignmentSchema+// ---------------------------------------------------------------------------++// ConnectionAttempt mirrors preparedRouteCandidateSchema.connectionAttempt.+type ConnectionAttempt struct {+ Current Int `json:"current"`+ Total Int `json:"total"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *ConnectionAttempt) UnmarshalJSON(data []byte) error {+ *v = ConnectionAttempt{}+ type raw ConnectionAttempt+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("current", "total"); err != nil {+ return err+ }+ if !inRangeInt(v.Current, 1, 3) {+ return errors.New("connectionAttempt.current is out of range")+ }+ if v.Total != 3 {+ return errors.New("connectionAttempt.total must be 3")+ }+ return nil+}++// PreparedRouteCandidate mirrors preparedRouteCandidateSchema.+type PreparedRouteCandidate struct {+ ChildPeerID string `json:"childPeerId"`+ ConnectionID string `json:"connectionId"`+ Transport string `json:"transport"`+ QualityProbe bool `json:"qualityProbe"`+ ConnectionAttempt *ConnectionAttempt `json:"connectionAttempt,omitempty"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *PreparedRouteCandidate) UnmarshalJSON(data []byte) error {+ *v = PreparedRouteCandidate{}+ type raw PreparedRouteCandidate+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require(+ "childPeerId", "connectionId", "transport", "qualityProbe"); err != nil {+ return err+ }+ if err := present.optional("connectionAttempt"); err != nil {+ return err+ }+ if !ValidOpaqueID(v.ChildPeerID) || !ValidOpaqueID(v.ConnectionID) {+ return errors.New("prepared route candidate ids are not opaque ids")+ }+ if !enumOf(v.Transport, "direct", "sfu") {+ return fmt.Errorf("unknown transport %q", v.Transport)+ }+ return nil+}++// ParticipantRouteAssignment mirrors participantRouteAssignmentSchema.+type ParticipantRouteAssignment struct {+ Upstream MediaRouteUpstream `json:"upstream"`+ ChildPeerIDs []string `json:"childPeerIds"`+ SfuPublicationGeneration *string `json:"sfuPublicationGeneration"`+}++// MarshalJSON implements json.Marshaler.+func (v ParticipantRouteAssignment) MarshalJSON() ([]byte, error) {+ type raw ParticipantRouteAssignment+ value := raw(v)+ if value.ChildPeerIDs == nil {+ value.ChildPeerIDs = []string{}+ }+ return marshalJSON(value)+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *ParticipantRouteAssignment) UnmarshalJSON(data []byte) error {+ *v = ParticipantRouteAssignment{}+ type raw ParticipantRouteAssignment+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("upstream", "childPeerIds"); err != nil {+ return err+ }+ if err := present.requireNullable("sfuPublicationGeneration"); err != nil {+ return err+ }+ if len(v.ChildPeerIDs) > MaxEndpointMediaCopyCapacity {+ return errors.New("childPeerIds holds too many entries")+ }+ seen := make(map[string]struct{}, len(v.ChildPeerIDs))+ for _, peerID := range v.ChildPeerIDs {+ if !ValidOpaqueID(peerID) {+ return errors.New("childPeerIds holds a non-opaque id")+ }+ if _, duplicate := seen[peerID]; duplicate {+ return errors.New("childPeerIds must be unique")+ }+ seen[peerID] = struct{}{}+ }+ if v.SfuPublicationGeneration != nil && !ValidOpaqueID(*v.SfuPublicationGeneration) {+ return errors.New("sfuPublicationGeneration is not an opaque id")+ }+ // superRefine: an SFU upstream requires its publication generation and a+ // peer upstream cannot own one.+ if v.Upstream.Kind == "sfu" && v.SfuPublicationGeneration == nil {+ return errors.New("An SFU upstream requires its publication generation")+ }+ if v.Upstream.Kind == "peer" && v.SfuPublicationGeneration != nil {+ return errors.New("A peer upstream cannot own an SFU publication generation")+ }+ return nil+}++// ---------------------------------------------------------------------------+// routeDiagnosticSnapshotSchema+// ---------------------------------------------------------------------------++// RouteDiagnosticParent mirrors routeDiagnosticParentSchema.+type RouteDiagnosticParent struct {+ Kind string `json:"kind"`+ Ordinal Int `json:"ordinal,omitempty"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *RouteDiagnosticParent) UnmarshalJSON(data []byte) error {+ *v = RouteDiagnosticParent{}+ type raw RouteDiagnosticParent+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("kind"); err != nil {+ return err+ }+ switch v.Kind {+ case "none", "host", "sfu":+ if present.has("ordinal") {+ return fmt.Errorf("route diagnostic parent %q must not carry ordinal", v.Kind)+ }+ case "viewer":+ if err := present.require("ordinal"); err != nil {+ return err+ }+ if !inRangeInt(v.Ordinal, 1, MaxViewersPerRoomLimit) {+ return errors.New("route diagnostic parent ordinal is out of range")+ }+ default:+ return fmt.Errorf("unknown route diagnostic parent kind %q", v.Kind)+ }+ return nil+}++// RouteDiagnosticQuality mirrors routeDiagnosticQualitySchema.+type RouteDiagnosticQuality struct {+ EligibleWindows Int `json:"eligibleWindows"`+ EligibleDurationMs Int `json:"eligibleDurationMs"`+ FreezeWindows Int `json:"freezeWindows"`+ FreezeCount Int `json:"freezeCount"`+ FreezeDurationMs Int `json:"freezeDurationMs"`+ PauseCount Int `json:"pauseCount"`+ PauseDurationMs Int `json:"pauseDurationMs"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *RouteDiagnosticQuality) UnmarshalJSON(data []byte) error {+ *v = RouteDiagnosticQuality{}+ type raw RouteDiagnosticQuality+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("eligibleWindows", "eligibleDurationMs", "freezeWindows",+ "freezeCount", "freezeDurationMs", "pauseCount", "pauseDurationMs"); err != nil {+ return err+ }+ for _, value := range []Int{v.EligibleWindows, v.EligibleDurationMs, v.FreezeWindows,+ v.FreezeCount, v.FreezeDurationMs, v.PauseCount, v.PauseDurationMs} {+ if !inRangeInt(value, 0, MaxSafeInteger) {+ return errors.New("route diagnostic quality value is out of range")+ }+ }+ return nil+}++// RouteDiagnosticChild mirrors routeDiagnosticChildSchema.+type RouteDiagnosticChild struct {+ Ordinal Int `json:"ordinal"`+ Parent RouteDiagnosticParent `json:"parent"`+ EffectiveCapacity Int `json:"effectiveCapacity"`+ ChildCount Int `json:"childCount"`+ DemandAgeMs *Int `json:"demandAgeMs"`+ QueueWaitMs *Int `json:"queueWaitMs"`+ CandidateStartMs *Int `json:"candidateStartMs"`+ FirstDecodedFrameMs *Int `json:"firstDecodedFrameMs"`+ FinalMs *Int `json:"finalMs"`+ FinalRoute string `json:"finalRoute"`+ RejectionBucket string `json:"rejectionBucket"`+ Quality *RouteDiagnosticQuality `json:"quality"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *RouteDiagnosticChild) UnmarshalJSON(data []byte) error {+ *v = RouteDiagnosticChild{}+ type raw RouteDiagnosticChild+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("ordinal", "parent", "effectiveCapacity", "childCount",+ "finalRoute", "rejectionBucket"); err != nil {+ return err+ }+ if err := present.requireNullable("demandAgeMs", "queueWaitMs", "candidateStartMs",+ "firstDecodedFrameMs", "finalMs", "quality"); err != nil {+ return err+ }+ if !inRangeInt(v.Ordinal, 1, MaxViewersPerRoomLimit) {+ return errors.New("route diagnostic ordinal is out of range")+ }+ if !inRangeInt(v.EffectiveCapacity, 0, MaxEndpointMediaCopyCapacity) ||+ !inRangeInt(v.ChildCount, 0, MaxEndpointMediaCopyCapacity) {+ return errors.New("route diagnostic capacity is out of range")+ }+ for _, duration := range []*Int{v.DemandAgeMs, v.QueueWaitMs, v.CandidateStartMs,+ v.FirstDecodedFrameMs, v.FinalMs} {+ if duration != nil && !inRangeInt(*duration, 0, MaxSafeInteger) {+ return errors.New("route diagnostic duration is out of range")+ }+ }+ if !enumOf(v.FinalRoute, routeDiagnosticFinalRoutes...) {+ return fmt.Errorf("unknown finalRoute %q", v.FinalRoute)+ }+ if !enumOf(v.RejectionBucket, routeDiagnosticBuckets...) {+ return fmt.Errorf("unknown rejectionBucket %q", v.RejectionBucket)+ }+ return nil+}++// RouteDiagnosticOperation mirrors routeDiagnosticOperationSchema.+type RouteDiagnosticOperation struct {+ ChildOrdinal Int `json:"childOrdinal"`+ Reason string `json:"reason"`+ Stage string `json:"stage"`+ Cursor Int `json:"cursor"`+ CandidateCount Int `json:"candidateCount"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *RouteDiagnosticOperation) UnmarshalJSON(data []byte) error {+ *v = RouteDiagnosticOperation{}+ type raw RouteDiagnosticOperation+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require(+ "childOrdinal", "reason", "stage", "cursor", "candidateCount"); err != nil {+ return err+ }+ if !inRangeInt(v.ChildOrdinal, 1, MaxViewersPerRoomLimit) {+ return errors.New("route diagnostic childOrdinal is out of range")+ }+ if !enumOf(v.Reason, routeDemandReasons...) {+ return fmt.Errorf("unknown route demand reason %q", v.Reason)+ }+ if !enumOf(v.Stage, routeDiagnosticStages...) {+ return fmt.Errorf("unknown route diagnostic stage %q", v.Stage)+ }+ if !inRangeInt(v.Cursor, 0, MaxViewersPerRoomLimit) {+ return errors.New("route diagnostic cursor is out of range")+ }+ if !inRangeInt(v.CandidateCount, 1, MaxViewersPerRoomLimit+1) {+ return errors.New("route diagnostic candidateCount is out of range")+ }+ return nil+}++// RouteDiagnosticSnapshot mirrors routeDiagnosticSnapshotSchema.+type RouteDiagnosticSnapshot struct {+ Children []RouteDiagnosticChild `json:"children"`+ Operation *RouteDiagnosticOperation `json:"operation"`+}++// MarshalJSON implements json.Marshaler.+func (v RouteDiagnosticSnapshot) MarshalJSON() ([]byte, error) {+ type raw RouteDiagnosticSnapshot+ value := raw(v)+ if value.Children == nil {+ value.Children = []RouteDiagnosticChild{}+ }+ return marshalJSON(value)+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *RouteDiagnosticSnapshot) UnmarshalJSON(data []byte) error {+ *v = RouteDiagnosticSnapshot{}+ type raw RouteDiagnosticSnapshot+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("children"); err != nil {+ return err+ }+ if err := present.requireNullable("operation"); err != nil {+ return err+ }+ if len(v.Children) > MaxViewersPerRoomLimit {+ return errors.New("route diagnostic snapshot holds too many children")+ }+ // superRefine: unique ordinals, resolvable viewer parents, and an+ // operation that names a present child with a cursor inside its candidates.+ ordinals := make(map[Int]struct{}, len(v.Children))+ for _, child := range v.Children {+ ordinals[child.Ordinal] = struct{}{}+ }+ if len(ordinals) != len(v.Children) {+ return errors.New("Route diagnostic ordinals must be unique")+ }+ for _, child := range v.Children {+ if child.Parent.Kind != "viewer" {+ continue+ }+ if _, ok := ordinals[child.Parent.Ordinal]; !ok || child.Parent.Ordinal == child.Ordinal {+ return errors.New("Route diagnostic parent ordinal is invalid")+ }+ }+ if v.Operation != nil {+ if _, ok := ordinals[v.Operation.ChildOrdinal]; !ok ||+ v.Operation.Cursor >= v.Operation.CandidateCount {+ return errors.New("Route diagnostic operation is invalid")+ }+ }+ return nil+}++// ---------------------------------------------------------------------------+// participantPresenceEntrySchema+// ---------------------------------------------------------------------------++// ParticipantPresenceEntry mirrors participantPresenceEntrySchema. The viewer+// variant is viewerPresenceEntrySchema.+type ParticipantPresenceEntry struct {+ Role Role `json:"role"`+ PeerID string `json:"peerId"`+ DisplayName DisplayName `json:"displayName"`+ Upstream MediaRouteUpstream `json:"upstream"`+ MediaReady bool `json:"mediaReady,omitempty"`+}++// HostPresenceEntry builds the host entry, whose upstream is always+// { kind: "none" } and which never carries mediaReady.+func HostPresenceEntry(peerID string, displayName DisplayName) ParticipantPresenceEntry {+ return ParticipantPresenceEntry{+ Role: RoleHost, PeerID: peerID, DisplayName: displayName, Upstream: NoUpstream(),+ }+}++// NewViewerPresenceEntry builds a viewer entry; mediaReady is emitted only+// when true, matching `...(mediaReady ? { mediaReady: true } : {})`.+func NewViewerPresenceEntry(+ peerID string, displayName DisplayName, upstream MediaRouteUpstream, mediaReady bool,+) ParticipantPresenceEntry {+ return ParticipantPresenceEntry{+ Role: RoleViewer, PeerID: peerID, DisplayName: displayName,+ Upstream: upstream, MediaReady: mediaReady,+ }+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *ParticipantPresenceEntry) UnmarshalJSON(data []byte) error {+ *v = ParticipantPresenceEntry{}+ type raw ParticipantPresenceEntry+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("role", "peerId", "displayName", "upstream"); err != nil {+ return err+ }+ if !ValidOpaqueID(v.PeerID) {+ return errors.New("presence peerId is not an opaque id")+ }+ switch v.Role {+ case RoleHost:+ if present.has("mediaReady") {+ return errors.New("host presence must not carry mediaReady")+ }+ if v.Upstream.Kind != "none" {+ return errors.New("host presence upstream must be none")+ }+ case RoleViewer:+ if err := present.optional("mediaReady"); err != nil {+ return err+ }+ if present.has("mediaReady") && !v.MediaReady {+ return errors.New("mediaReady must be true when present")+ }+ default:+ return fmt.Errorf("unknown presence role %q", v.Role)+ }+ return nil+}++// ---------------------------------------------------------------------------+// viewerQualityEvidenceMetricsSchema / senderQualityDiagnosticsSchema+// ---------------------------------------------------------------------------++// ViewerQualityEvidenceGuard mirrors viewerQualityEvidenceGuardSchema.+type ViewerQualityEvidenceGuard struct {+ ConnectionID string `json:"connectionId"`+ RouteRevision Int `json:"routeRevision"`+ PresentationEpoch Int `json:"presentationEpoch"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *ViewerQualityEvidenceGuard) UnmarshalJSON(data []byte) error {+ *v = ViewerQualityEvidenceGuard{}+ type raw ViewerQualityEvidenceGuard+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("connectionId", "routeRevision", "presentationEpoch"); err != nil {+ return err+ }+ if !ValidOpaqueID(v.ConnectionID) {+ return errors.New("guard connectionId is not an opaque id")+ }+ if !validRevision(v.RouteRevision) {+ return errors.New("guard routeRevision is out of range")+ }+ if !inRangeInt(v.PresentationEpoch, 0, MaxSafeInteger) {+ return errors.New("guard presentationEpoch is out of range")+ }+ return nil+}++// ViewerQualityEvidenceMetrics mirrors viewerQualityEvidenceMetricsSchema.+type ViewerQualityEvidenceMetrics struct {+ NatTraversalPath string `json:"natTraversalPath"`+ Width *Int `json:"width"`+ Height *Int `json:"height"`+ FramesPerSecond *Num `json:"framesPerSecond"`+ BitrateKbps *Num `json:"bitrateKbps"`+ PacketsReceivedDelta *Int `json:"packetsReceivedDelta"`+ PacketsLostDelta *Int `json:"packetsLostDelta"`+ RttMs *Num `json:"rttMs"`+ JitterMs *Num `json:"jitterMs"`+ FramesDecodedDelta *Int `json:"framesDecodedDelta"`+ FramesDroppedDelta *Int `json:"framesDroppedDelta"`+ DecodeMsPerFrame *Num `json:"decodeMsPerFrame"`+ FreezeCountDelta *Int `json:"freezeCountDelta"`+ FreezeDurationMsDelta *Num `json:"freezeDurationMsDelta"`+ PauseCountDelta *Int `json:"pauseCountDelta"`+ PauseDurationMsDelta *Num `json:"pauseDurationMsDelta"`+ Codec *string `json:"codec"`+ CodecProfile *string `json:"codecProfile"`+ CodecParameters *string `json:"codecParameters"`+ AudioBitrateKbps *Num `json:"audioBitrateKbps"`+ AudioPacketLossPercent *Num `json:"audioPacketLossPercent"`+ AudioJitterMs *Num `json:"audioJitterMs"`+ AudioVideoPlayoutDeltaMs *Num `json:"audioVideoPlayoutDeltaMs"`+ VideoJitterBufferDelayMs *Num `json:"videoJitterBufferDelayMs"`+ AudioJitterBufferDelayMs *Num `json:"audioJitterBufferDelayMs"`+ AudioConcealedSamplesPercent *Num `json:"audioConcealedSamplesPercent"`+ AudioConcealmentEventsDelta *Int `json:"audioConcealmentEventsDelta"`+ AudioCodec *string `json:"audioCodec"`+}++var viewerQualityEvidenceMetricKeys = []string{+ "natTraversalPath", "width", "height", "framesPerSecond", "bitrateKbps",+ "packetsReceivedDelta", "packetsLostDelta", "rttMs", "jitterMs",+ "framesDecodedDelta", "framesDroppedDelta", "decodeMsPerFrame",+ "freezeCountDelta", "freezeDurationMsDelta", "pauseCountDelta",+ "pauseDurationMsDelta", "codec", "codecProfile", "codecParameters",+ "audioBitrateKbps", "audioPacketLossPercent", "audioJitterMs",+ "audioVideoPlayoutDeltaMs", "videoJitterBufferDelayMs",+ "audioJitterBufferDelayMs", "audioConcealedSamplesPercent",+ "audioConcealmentEventsDelta", "audioCodec",+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *ViewerQualityEvidenceMetrics) UnmarshalJSON(data []byte) error {+ *v = ViewerQualityEvidenceMetrics{}+ type raw ViewerQualityEvidenceMetrics+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.requireNullable(viewerQualityEvidenceMetricKeys...); err != nil {+ return err+ }+ if err := present.require("natTraversalPath"); err != nil {+ return err+ }+ if !enumOf(v.NatTraversalPath, NatTraversalPaths[:]...) {+ return fmt.Errorf("unknown natTraversalPath %q", v.NatTraversalPath)+ }+ for _, bound := range []struct {+ value *Int+ minimum, maximum int64+ }{+ {v.Width, 1, 16_384}, {v.Height, 1, 16_384},+ {v.PacketsReceivedDelta, 0, 1_000_000}, {v.PacketsLostDelta, 0, 1_000_000},+ {v.FramesDecodedDelta, 0, 10_000}, {v.FramesDroppedDelta, 0, 10_000},+ {v.FreezeCountDelta, 0, MaxSafeInteger}, {v.PauseCountDelta, 0, MaxSafeInteger},+ {v.AudioConcealmentEventsDelta, 0, 10_000},+ } {+ if bound.value != nil && !inRangeInt(*bound.value, bound.minimum, bound.maximum) {+ return errors.New("viewer quality evidence integer is out of range")+ }+ }+ for _, bound := range []struct {+ value *Num+ minimum, maximum float64+ }{+ {v.FramesPerSecond, 0, 240}, {v.BitrateKbps, 0, 100_000},+ {v.RttMs, 0, 60_000}, {v.JitterMs, 0, 60_000},+ {v.DecodeMsPerFrame, 0, 60_000},+ {v.FreezeDurationMsDelta, 0, MaxSafeInteger},+ {v.PauseDurationMsDelta, 0, MaxSafeInteger},+ {v.AudioBitrateKbps, 0, 10_000}, {v.AudioPacketLossPercent, 0, 100},+ {v.AudioJitterMs, 0, 60_000},+ {v.AudioVideoPlayoutDeltaMs, -60_000, 60_000},+ {v.VideoJitterBufferDelayMs, 0, 60_000}, {v.AudioJitterBufferDelayMs, 0, 60_000},+ {v.AudioConcealedSamplesPercent, 0, 100},+ } {+ if bound.value != nil && !inRangeNum(*bound.value, bound.minimum, bound.maximum) {+ return errors.New("viewer quality evidence number is out of range")+ }+ }+ if v.Codec != nil && (UTF16Length(*v.Codec) > 64 || !videoMimeTypePattern.MatchString(*v.Codec)) {+ return errors.New("codec is not a video mime type")+ }+ if v.CodecProfile != nil &&+ (UTF16Length(*v.CodecProfile) > 64 || !codecProfilePattern.MatchString(*v.CodecProfile)) {+ return errors.New("codecProfile is malformed")+ }+ if v.CodecParameters != nil &&+ (UTF16Length(*v.CodecParameters) > 128 ||+ !codecParametersPattern.MatchString(*v.CodecParameters)) {+ return errors.New("codecParameters is malformed")+ }+ if v.AudioCodec != nil &&+ (UTF16Length(*v.AudioCodec) > 64 || !audioMimeTypePattern.MatchString(*v.AudioCodec)) {+ return errors.New("audioCodec is not an audio mime type")+ }+ // refine: dimensions travel together.+ if (v.Width == nil) != (v.Height == nil) {+ return errors.New("Viewer quality dimensions must be present together")+ }+ // refine: codec evidence must be canonical.+ if !IsCanonicalVideoCodecEvidence(+ derefString(v.Codec), derefString(v.CodecProfile), derefString(v.CodecParameters)) {+ return errors.New("Viewer codec evidence is not canonical")+ }+ return nil+}++func derefString(value *string) string {+ if value == nil {+ return ""+ }+ return *value+}++// SenderQualityDiagnostics mirrors senderQualityDiagnosticsSchema.+type SenderQualityDiagnostics struct {+ NatTraversalPath string `json:"natTraversalPath"`+ Reason *string `json:"reason"`+ FramesPerSecond *Num `json:"framesPerSecond"`+ BitrateKbps *Num `json:"bitrateKbps"`+ CaptureFramesPerSecond Nullable[Num] `json:"captureFramesPerSecond,omitzero"`+ MediaSourceFramesPerSecond Nullable[Num] `json:"mediaSourceFramesPerSecond,omitzero"`+ Width Nullable[Int] `json:"width,omitzero"`+ Height Nullable[Int] `json:"height,omitzero"`+ VideoEncodingCount Nullable[Int] `json:"videoEncodingCount,omitzero"`+ ActiveVideoEncodingCount Nullable[Int] `json:"activeVideoEncodingCount,omitzero"`+ AvailableOutgoingKbps Nullable[Num] `json:"availableOutgoingKbps,omitzero"`+ RttMs Nullable[Num] `json:"rttMs,omitzero"`+ PacketLossPercent Nullable[Num] `json:"packetLossPercent,omitzero"`+}++// UnmarshalJSON implements json.Unmarshaler.+func (v *SenderQualityDiagnostics) UnmarshalJSON(data []byte) error {+ *v = SenderQualityDiagnostics{}+ type raw SenderQualityDiagnostics+ present, err := decodeObject(data, (*raw)(v))+ if err != nil {+ return err+ }+ if err := present.require("natTraversalPath"); err != nil {+ return err+ }+ if err := present.requireNullable(+ "reason", "framesPerSecond", "bitrateKbps"); err != nil {+ return err+ }+ if !enumOf(v.NatTraversalPath, NatTraversalPaths[:]...) {+ return fmt.Errorf("unknown natTraversalPath %q", v.NatTraversalPath)+ }+ if v.Reason != nil && !enumOf(*v.Reason, senderQualityDegradedReasons...) {+ return fmt.Errorf("unknown sender quality reason %q", *v.Reason)+ }+ for _, bound := range []struct {+ value *Num+ minimum, maximum float64+ }{+ {v.FramesPerSecond, 0, 240}, {v.BitrateKbps, 0, 100_000},+ {v.CaptureFramesPerSecond.Value, 0, 240},+ {v.MediaSourceFramesPerSecond.Value, 0, 240},+ {v.AvailableOutgoingKbps.Value, 0, 100_000},+ {v.RttMs.Value, 0, 60_000}, {v.PacketLossPercent.Value, 0, 100},+ } {+ if bound.value != nil && !inRangeNum(*bound.value, bound.minimum, bound.maximum) {+ return errors.New("sender quality diagnostic number is out of range")+ }+ }+ for _, bound := range []struct {+ value *Int+ maximum int64+ }{+ {v.Width.Value, 16_384}, {v.Height.Value, 16_384},+ {v.VideoEncodingCount.Value, MaxSafeInteger},+ {v.ActiveVideoEncodingCount.Value, MaxSafeInteger},+ } {+ if bound.value != nil && !inRangeInt(*bound.value, 0, bound.maximum) {+ return errors.New("sender quality diagnostic integer is out of range")+ }+ }+ return nil+}diff --git a/internal/server/room/compat_test.go b/internal/server/room/compat_test.gonew file mode 100644index 00000000..6275cd7d--- /dev/null+++ b/internal/server/room/compat_test.go@@ -0,0 +1,155 @@+package room++import (+ "bytes"+ "os"+ "path/filepath"+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// testdata/node-rooms.db was written once by node:sqlite (DatabaseSync) with+// the schema of src/server/room-database.ts and two synthetic rooms: 4321 is+// active (NULL lease) with a 48-byte password material, 5678 is dormant with a+// lease of 1000 ms. No real token, grant or password is involved. The extension+// is .db because .gitignore excludes *.sqlite repository-wide.+func copyNodeFixture(t *testing.T) string {+ t.Helper()+ fixture, err := os.ReadFile(filepath.Join("testdata", "node-rooms.db"))+ if err != nil {+ t.Fatalf("read fixture: %v", err)+ }+ path := filepath.Join(t.TempDir(), "rooms.sqlite")+ if err := os.WriteFile(path, fixture, 0o600); err != nil {+ t.Fatalf("write fixture copy: %v", err)+ }+ return path+}++func openFixture(t *testing.T, startupNowMs, activeLeaseExpiresAtMs int64) []StoredRoomAuthority {+ t.Helper()+ database, err := NewDatabase(copyNodeFixture(t))+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ t.Cleanup(func() { _ = database.Close() })+ restored, err := database.Initialize(startupNowMs, activeLeaseExpiresAtMs)+ if err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ return restored+}++func TestRecoversANodeWrittenDatabase(t *testing.T) {+ restored := openFixture(t, 5_000, 6_000)+ if len(restored) != 1 {+ t.Fatalf("restored %d rooms, want 1 (the dormant room was due at 1000)", len(restored))+ }+ room := restored[0]+ if room.RoomID != "4321" || room.CodeEntryPolicy != protocol.CodeEntryPrivate {+ t.Fatalf("restored %+v", room)+ }+ if room.LeaseExpiresAtMs == nil || *room.LeaseExpiresAtMs != 6_000 {+ t.Fatalf("active room lease = %v, want the startup lease 6000", room.LeaseExpiresAtMs)+ }+ if !bytes.Equal(room.HostTokenDigest, bytes.Repeat([]byte{0x11}, 32)) ||+ !bytes.Equal(room.ViewerGrantDigest, bytes.Repeat([]byte{0x22}, 32)) {+ t.Fatal("digests did not survive the Node round trip")+ }+ if room.ViewerAuthorizationGeneration != "MzMzMzMzMzMzMzMzMzMzMw" {+ t.Fatalf("generation = %q", room.ViewerAuthorizationGeneration)+ }+ if !bytes.Equal(room.ViewerPasswordMaterial, bytes.Repeat([]byte{0x44}, 48)) {+ t.Fatalf("password material = %d bytes", len(room.ViewerPasswordMaterial))+ }+}++func TestKeepsADormantNodeWrittenDeadline(t *testing.T) {+ restored := openFixture(t, 500, 1_500)+ if len(restored) != 2 {+ t.Fatalf("restored %d rooms, want 2", len(restored))+ }+ // readStoredRooms orders by room_id.+ if restored[0].RoomID != "4321" || restored[0].LeaseExpiresAtMs == nil ||+ *restored[0].LeaseExpiresAtMs != 1_500 {+ t.Fatalf("active room = %+v", restored[0])+ }+ if restored[1].RoomID != "5678" || restored[1].LeaseExpiresAtMs == nil ||+ *restored[1].LeaseExpiresAtMs != 1_000 {+ t.Fatalf("dormant room = %+v", restored[1])+ }+ if restored[1].ViewerPasswordMaterial != nil {+ t.Fatalf("dormant room material = %v, want nil", restored[1].ViewerPasswordMaterial)+ }+}++func TestStoreRestoresANodeWrittenDatabase(t *testing.T) {+ testClock := &clock{nowMs: 5_000}+ store := stableStore(t, copyNodeFixture(t), testClock, Options{LeaseMs: 1_000})+ if store.Size() != 1 {+ t.Fatalf("size = %d, want 1", store.Size())+ }+ // The recovered room holds the startup lease: 5000 + 1000.+ testClock.nowMs = 6_001+ expired, err := store.ExpireRooms(testClock.nowMs)+ if err != nil {+ t.Fatalf("ExpireRooms: %v", err)+ }+ if len(expired) != 1 || expired[0].RoomID != "4321" {+ t.Fatalf("expired = %+v", expired)+ }+}++// TestSchemaTextMatchesTheNodeFixture proves the CREATE TABLE text this package+// executes is byte for byte the one src/server/room-database.ts executed.+func TestSchemaTextMatchesTheNodeFixture(t *testing.T) {+ path := databasePath(t)+ database, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ if _, err := database.Initialize(0, 1_000); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ if err := database.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ created := readSchemaText(t, path)+ fixture := readSchemaText(t, copyNodeFixture(t))+ if created.sql != fixture.sql {+ t.Fatalf("schema text differs\n go: %q\n node: %q", created.sql, fixture.sql)+ }+ if created.applicationID != fixture.applicationID ||+ created.applicationID != roomDatabaseApplicationID {+ t.Fatalf("application_id go=%d node=%d", created.applicationID, fixture.applicationID)+ }+ if created.userVersion != fixture.userVersion ||+ created.userVersion != roomDatabaseSchemaVersion {+ t.Fatalf("user_version go=%d node=%d", created.userVersion, fixture.userVersion)+ }+}++type schemaText struct {+ sql string+ applicationID int64+ userVersion int64+}++func readSchemaText(t *testing.T, path string) schemaText {+ t.Helper()+ raw := rawDatabase(t, path)+ var text schemaText+ if err := raw.QueryRow(+ "SELECT sql FROM sqlite_schema WHERE name = 'rooms'").Scan(&text.sql); err != nil {+ t.Fatalf("read schema: %v", err)+ }+ if err := raw.QueryRow("PRAGMA application_id").Scan(&text.applicationID); err != nil {+ t.Fatalf("read application_id: %v", err)+ }+ if err := raw.QueryRow("PRAGMA user_version").Scan(&text.userVersion); err != nil {+ t.Fatalf("read user_version: %v", err)+ }+ return text+}diff --git a/internal/server/room/database.go b/internal/server/room/database.gonew file mode 100644index 00000000..c411410c--- /dev/null+++ b/internal/server/room/database.go@@ -0,0 +1,786 @@+package room++import (+ "context"+ "database/sql"+ "encoding/base64"+ "errors"+ "fmt"+ "path/filepath"+ "strings"++ // The pure-Go driver: the port must build with CGO_ENABLED=0 (D2).+ _ "modernc.org/sqlite"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// roomDatabaseApplicationID and roomDatabaseSchemaVersion are the+// APPLICATION_ID / SCHEMA_VERSION of src/server/room-database.ts, checked on+// open so another SQLite file cannot be adopted as the room authority. The ID+// is ASCII "SCRN"; roomSchema below repeats it in decimal because that literal+// has to match the TypeScript statement text byte for byte.+const (+ roomDatabaseApplicationID = 0x5343524e+ roomDatabaseSchemaVersion = 1+)++// roomSchema is the exact text src/server/room-database.ts executes, so a file+// created here and one created by the TypeScript hold the same sqlite_schema.+const roomSchema = `+ CREATE TABLE rooms (+ room_id TEXT PRIMARY KEY NOT NULL+ CHECK (room_id GLOB '[1-9][0-9][0-9][0-9]'),+ host_token_digest BLOB NOT NULL+ CHECK (typeof(host_token_digest) = 'blob' AND length(host_token_digest) = 32),+ viewer_grant_digest BLOB NOT NULL+ CHECK (typeof(viewer_grant_digest) = 'blob' AND length(viewer_grant_digest) = 32),+ viewer_authorization_generation TEXT NOT NULL+ CHECK (+ length(viewer_authorization_generation) = 22 AND+ viewer_authorization_generation NOT GLOB '*[^A-Za-z0-9_-]*'+ ),+ code_entry_policy TEXT NOT NULL+ CHECK (code_entry_policy IN ('open', 'private')),+ viewer_password_material BLOB NULL+ CHECK (+ viewer_password_material IS NULL OR+ (typeof(viewer_password_material) = 'blob' AND length(viewer_password_material) = 48)+ ),+ lease_expires_at_ms INTEGER NULL+ CHECK (+ lease_expires_at_ms IS NULL OR+ (lease_expires_at_ms > 0 AND lease_expires_at_ms <= 9007199254740991)+ )+ ) STRICT;+ PRAGMA application_id = 1396920910;+ PRAGMA user_version = 1;+ `++const selectStoredRooms = `SELECT+ room_id,+ host_token_digest,+ viewer_grant_digest,+ viewer_authorization_generation,+ code_entry_policy,+ viewer_password_material,+ lease_expires_at_ms+ FROM rooms+ ORDER BY room_id`++const insertStoredRoom = `INSERT INTO rooms (+ room_id,+ host_token_digest,+ viewer_grant_digest,+ viewer_authorization_generation,+ code_entry_policy,+ viewer_password_material,+ lease_expires_at_ms+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`++const deleteRoomStatement = "DELETE FROM rooms WHERE room_id = ? AND host_token_digest = ?"++// StoredRoomAuthority is StoredRoomAuthority. A nil ViewerPasswordMaterial and+// a nil LeaseExpiresAtMs are the TypeScript nulls.+type StoredRoomAuthority struct {+ RoomID string+ HostTokenDigest []byte+ ViewerGrantDigest []byte+ ViewerAuthorizationGeneration string+ CodeEntryPolicy protocol.CodeEntryPolicy+ ViewerPasswordMaterial []byte+ LeaseExpiresAtMs *int64+}++// RoomIdentity is the {roomId, hostTokenDigest} pair deleteRooms takes.+type RoomIdentity struct {+ RoomID string+ HostTokenDigest []byte+}++// Database is RoomDatabase: the SQLite stable authority. It holds one+// connection for its lifetime, because `PRAGMA locking_mode = EXCLUSIVE` is a+// connection property that a recycled pool connection would silently drop (D2).+type Database struct {+ path string+ db *sql.DB+ conn *sql.Conn+ // inTransaction reproduces DatabaseSync.isTransaction, which the driver+ // does not expose; the ROLLBACK guard depends on it.+ inTransaction bool+}++// NewDatabase is the RoomDatabase constructor.+func NewDatabase(path string) (*Database, error) {+ if path == "" || path == ":memory:" {+ return nil, errors.New("Room database path must identify a file")+ }+ return &Database{path: path}, nil+}++// Initialize opens the file, takes the exclusive lock, creates or verifies the+// schema and recovers the stored rooms: rooms whose lease has passed are+// deleted and rooms that were active at shutdown take activeLeaseExpiresAtMs.+func (d *Database) Initialize(+ startupNowMs, activeLeaseExpiresAtMs int64,+) (restored []StoredRoomAuthority, err error) {+ if d.conn != nil {+ return nil, errors.New("Room database is already initialized")+ }+ if err := assertTimestamp(startupNowMs, "Room database startup time", true); err != nil {+ return nil, err+ }+ if err := assertTimestamp(+ activeLeaseExpiresAtMs, "Room database active-room lease deadline", false); err != nil {+ return nil, err+ }+ if activeLeaseExpiresAtMs <= startupNowMs {+ return nil, errors.New(+ "Room database active-room lease deadline must be in the future")+ }++ // `new DatabaseSync(this.path, { timeout: 0 })`: a lock conflict must fail+ // immediately instead of waiting.+ db, err := sql.Open("sqlite", "file:"+uriPath(d.path)+"?_pragma=busy_timeout(0)")+ if err != nil {+ return nil, err+ }+ db.SetMaxOpenConns(1)+ db.SetMaxIdleConns(1)+ db.SetConnMaxLifetime(0)+ db.SetConnMaxIdleTime(0)+ conn, err := db.Conn(context.Background())+ if err != nil {+ _ = db.Close()+ return nil, err+ }+ d.db, d.conn = db, conn+ defer func() {+ if err != nil {+ d.closeHandles()+ }+ }()++ // The pragma answers "exclusive" even when another process owns the file;+ // the BEGIN EXCLUSIVE below is what actually takes the lock.+ var lockingMode string+ if err = d.conn.QueryRowContext(+ context.Background(), "PRAGMA main.locking_mode = EXCLUSIVE").Scan(&lockingMode); err != nil {+ return nil, err+ }+ if lockingMode != "exclusive" {+ return nil, errors.New("Room database could not acquire exclusive locking mode")+ }+ if err = d.begin("BEGIN EXCLUSIVE"); err != nil {+ return nil, err+ }+ restored, err = d.recover(startupNowMs, activeLeaseExpiresAtMs)+ if err != nil {+ d.rollbackIfNeeded()+ return nil, err+ }+ if err = d.finish("COMMIT"); err != nil {+ d.rollbackIfNeeded()+ return nil, err+ }+ return restored, nil+}++// uriPath is the literal path `new DatabaseSync(this.path)` opened, written for+// the driver's URI DSN: the driver splits on the first `?` and SQLite decodes+// `%HH` and stops at `#`, so those three characters are escaped.+func uriPath(path string) string {+ return strings.NewReplacer("%", "%25", "#", "%23", "?", "%3F").Replace(filepath.ToSlash(path))+}++func (d *Database) recover(+ startupNowMs, activeLeaseExpiresAtMs int64,+) ([]StoredRoomAuthority, error) {+ if err := d.ensureExactSchema(); err != nil {+ return nil, err+ }+ if err := d.assertDatabaseIntegrity(); err != nil {+ return nil, err+ }+ stored, err := d.readStoredRooms()+ if err != nil {+ return nil, err+ }+ expiredCount, activeCount := 0, 0+ for _, room := range stored {+ switch {+ case room.LeaseExpiresAtMs == nil:+ activeCount+++ case *room.LeaseExpiresAtMs <= startupNowMs:+ expiredCount+++ }+ }++ deleted, err := d.exec(+ `DELETE FROM rooms+ WHERE lease_expires_at_ms IS NOT NULL+ AND lease_expires_at_ms <= ?`, startupNowMs)+ if err != nil {+ return nil, err+ }+ if deleted != int64(expiredCount) {+ return nil, errors.New("Room database expiry cleanup changed an unexpected row count")+ }++ converted, err := d.exec(+ `UPDATE rooms+ SET lease_expires_at_ms = ?+ WHERE lease_expires_at_ms IS NULL`, activeLeaseExpiresAtMs)+ if err != nil {+ return nil, err+ }+ if converted != int64(activeCount) {+ return nil, errors.New("Room database active-room recovery changed an unexpected row count")+ }++ restored := make([]StoredRoomAuthority, 0, len(stored))+ for _, room := range stored {+ if room.LeaseExpiresAtMs != nil && *room.LeaseExpiresAtMs <= startupNowMs {+ continue+ }+ if room.LeaseExpiresAtMs == nil {+ lease := activeLeaseExpiresAtMs+ room.LeaseExpiresAtMs = &lease+ }+ restored = append(restored, room)+ }+ return restored, nil+}++// InsertRoom is insertRoom.+func (d *Database) InsertRoom(room StoredRoomAuthority) error {+ if err := assertStoredRoom(room); err != nil {+ return err+ }+ return d.transaction(func() error {+ changes, err := d.exec(insertStoredRoom,+ room.RoomID,+ room.HostTokenDigest,+ room.ViewerGrantDigest,+ room.ViewerAuthorizationGeneration,+ room.CodeEntryPolicy,+ room.ViewerPasswordMaterial,+ room.LeaseExpiresAtMs)+ if err != nil {+ return err+ }+ return assertSingleChange(changes, "insert")+ })+}++// SetLeaseDeadline is setLeaseDeadline; a nil deadline marks the room active.+func (d *Database) SetLeaseDeadline(+ roomID string, hostTokenDigest []byte, leaseExpiresAtMs *int64,+) error {+ if err := assertRoomIdentity(roomID, hostTokenDigest); err != nil {+ return err+ }+ if leaseExpiresAtMs != nil {+ if err := assertTimestamp(*leaseExpiresAtMs, "Room lease deadline", false); err != nil {+ return err+ }+ }+ return d.transaction(func() error {+ changes, err := d.exec(+ `UPDATE rooms+ SET lease_expires_at_ms = ?+ WHERE room_id = ? AND host_token_digest = ?`,+ leaseExpiresAtMs, roomID, hostTokenDigest)+ if err != nil {+ return err+ }+ return assertSingleChange(changes, "lease update")+ })+}++// SetViewerPassword is setViewerPassword; nil material clears the password.+func (d *Database) SetViewerPassword(+ roomID string, hostTokenDigest, viewerPasswordMaterial []byte,+) error {+ if err := assertRoomIdentity(roomID, hostTokenDigest); err != nil {+ return err+ }+ if err := assertPasswordMaterial(viewerPasswordMaterial); err != nil {+ return err+ }+ return d.transaction(func() error {+ changes, err := d.exec(+ `UPDATE rooms+ SET viewer_password_material = ?+ WHERE room_id = ? AND host_token_digest = ?`,+ viewerPasswordMaterial, roomID, hostTokenDigest)+ if err != nil {+ return err+ }+ return assertSingleChange(changes, "password update")+ })+}++// SetCodeEntryPolicy is setCodeEntryPolicy.+func (d *Database) SetCodeEntryPolicy(+ roomID string, hostTokenDigest []byte, codeEntryPolicy protocol.CodeEntryPolicy,+) error {+ if err := assertRoomIdentity(roomID, hostTokenDigest); err != nil {+ return err+ }+ if !validCodeEntryPolicy(codeEntryPolicy) {+ return errors.New("Room code-entry policy is invalid")+ }+ return d.transaction(func() error {+ changes, err := d.exec(+ `UPDATE rooms+ SET code_entry_policy = ?+ WHERE room_id = ? AND host_token_digest = ?`,+ codeEntryPolicy, roomID, hostTokenDigest)+ if err != nil {+ return err+ }+ return assertSingleChange(changes, "code-entry policy update")+ })+}++// SetViewerGrant is setViewerGrant.+func (d *Database) SetViewerGrant(+ roomID string, hostTokenDigest, viewerGrantDigest []byte,+ viewerAuthorizationGeneration string,+) error {+ if err := assertRoomIdentity(roomID, hostTokenDigest); err != nil {+ return err+ }+ if err := assertDigest(viewerGrantDigest, "Viewer grant"); err != nil {+ return err+ }+ if err := assertAuthorizationGeneration(viewerAuthorizationGeneration); err != nil {+ return err+ }+ return d.transaction(func() error {+ changes, err := d.exec(+ `UPDATE rooms+ SET viewer_grant_digest = ?,+ viewer_authorization_generation = ?+ WHERE room_id = ? AND host_token_digest = ?`,+ viewerGrantDigest, viewerAuthorizationGeneration, roomID, hostTokenDigest)+ if err != nil {+ return err+ }+ return assertSingleChange(changes, "Viewer grant update")+ })+}++// DeleteRoom is deleteRoom.+func (d *Database) DeleteRoom(roomID string, hostTokenDigest []byte) error {+ return d.DeleteRooms([]RoomIdentity{{RoomID: roomID, HostTokenDigest: hostTokenDigest}})+}++// DeleteRooms is deleteRooms: one transaction, and any room whose authority no+// longer matches rolls the whole batch back.+func (d *Database) DeleteRooms(rooms []RoomIdentity) error {+ for _, room := range rooms {+ if err := assertRoomIdentity(room.RoomID, room.HostTokenDigest); err != nil {+ return err+ }+ }+ if len(rooms) == 0 {+ return nil+ }+ return d.transaction(func() error {+ for _, room := range rooms {+ changes, err := d.exec(deleteRoomStatement, room.RoomID, room.HostTokenDigest)+ if err != nil {+ return err+ }+ if err := assertSingleChange(changes, "delete"); err != nil {+ return err+ }+ }+ return nil+ })+}++// ReplaceRoom is replaceRoom: the new room and the removal of the old one are+// one authority transition.+func (d *Database) ReplaceRoom(+ oldRoomID string, oldHostTokenDigest []byte, replacement StoredRoomAuthority,+) error {+ if err := assertRoomIdentity(oldRoomID, oldHostTokenDigest); err != nil {+ return err+ }+ if err := assertStoredRoom(replacement); err != nil {+ return err+ }+ if replacement.RoomID == oldRoomID {+ return errors.New("Replacement room ID must be different")+ }+ return d.transaction(func() error {+ inserted, err := d.exec(insertStoredRoom,+ replacement.RoomID,+ replacement.HostTokenDigest,+ replacement.ViewerGrantDigest,+ replacement.ViewerAuthorizationGeneration,+ replacement.CodeEntryPolicy,+ replacement.ViewerPasswordMaterial,+ replacement.LeaseExpiresAtMs)+ if err != nil {+ return err+ }+ if err := assertSingleChange(inserted, "replacement insert"); err != nil {+ return err+ }+ deleted, err := d.exec(deleteRoomStatement, oldRoomID, oldHostTokenDigest)+ if err != nil {+ return err+ }+ return assertSingleChange(deleted, "replacement delete")+ })+}++// Close closes the connection; it is safe on a database that never opened one.+func (d *Database) Close() error {+ return d.closeHandles()+}++func (d *Database) closeHandles() error {+ conn, db := d.conn, d.db+ d.conn, d.db, d.inTransaction = nil, nil, false+ var connError error+ if conn != nil {+ connError = conn.Close()+ }+ if db != nil {+ if err := db.Close(); err != nil {+ return err+ }+ }+ return connError+}++func (d *Database) ensureExactSchema() error {+ applicationID, err := d.readPragmaInteger("application_id")+ if err != nil {+ return err+ }+ schemaVersion, err := d.readPragmaInteger("user_version")+ if err != nil {+ return err+ }+ schemaObjects, err := d.readSchemaObjects()+ if err != nil {+ return err+ }++ if applicationID == 0 && schemaVersion == 0 && len(schemaObjects) == 0 {+ _, err := d.conn.ExecContext(context.Background(), roomSchema)+ return err+ }++ if applicationID != roomDatabaseApplicationID {+ return errors.New("Room database application identity does not match")+ }+ if schemaVersion != roomDatabaseSchemaVersion {+ return errors.New("Room database schema version does not match")+ }+ if len(schemaObjects) != 1 ||+ schemaObjects[0][0] != "table" || schemaObjects[0][1] != "rooms" {+ return errors.New("Room database schema objects do not match")+ }+ return d.assertExactColumns()+}++func (d *Database) readSchemaObjects() ([][2]string, error) {+ rows, err := d.conn.QueryContext(context.Background(),+ `SELECT type, name+ FROM sqlite_schema+ WHERE name NOT LIKE 'sqlite_%'+ ORDER BY type, name`)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var objects [][2]string+ for rows.Next() {+ var object [2]string+ if err := rows.Scan(&object[0], &object[1]); err != nil {+ return nil, err+ }+ objects = append(objects, object)+ }+ return objects, rows.Err()+}++func (d *Database) assertDatabaseIntegrity() error {+ rows, err := d.conn.QueryContext(context.Background(), "PRAGMA quick_check")+ if err != nil {+ return err+ }+ defer rows.Close()+ var results []string+ for rows.Next() {+ var result string+ if err := rows.Scan(&result); err != nil {+ return err+ }+ results = append(results, result)+ }+ if err := rows.Err(); err != nil {+ return err+ }+ if len(results) != 1 || results[0] != "ok" {+ return errors.New("Room database integrity check failed")+ }+ return nil+}++func (d *Database) assertExactColumns() error {+ expected := [...]struct {+ name string+ columnType string+ notNull int+ primaryKey int+ }{+ {"room_id", "TEXT", 1, 1},+ {"host_token_digest", "BLOB", 1, 0},+ {"viewer_grant_digest", "BLOB", 1, 0},+ {"viewer_authorization_generation", "TEXT", 1, 0},+ {"code_entry_policy", "TEXT", 1, 0},+ {"viewer_password_material", "BLOB", 0, 0},+ {"lease_expires_at_ms", "INTEGER", 0, 0},+ }+ rows, err := d.conn.QueryContext(context.Background(), "PRAGMA table_info(rooms)")+ if err != nil {+ return err+ }+ defer rows.Close()+ index := 0+ for rows.Next() {+ var (+ cid int+ name string+ columnType string+ notNull int+ defaultValue sql.NullString+ primaryKey int+ )+ if err := rows.Scan(+ &cid, &name, &columnType, ¬Null, &defaultValue, &primaryKey); err != nil {+ return err+ }+ if index >= len(expected) || name != expected[index].name ||+ columnType != expected[index].columnType ||+ notNull != expected[index].notNull ||+ primaryKey != expected[index].primaryKey {+ return errors.New("Room database columns do not match the current schema")+ }+ index+++ }+ if err := rows.Err(); err != nil {+ return err+ }+ if index != len(expected) {+ return errors.New("Room database columns do not match the current schema")+ }+ return nil+}++func (d *Database) readStoredRooms() ([]StoredRoomAuthority, error) {+ rows, err := d.conn.QueryContext(context.Background(), selectStoredRooms)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var stored []StoredRoomAuthority+ for rows.Next() {+ var (+ room StoredRoomAuthority+ policy string+ lease sql.NullInt64+ material []byte+ )+ if err := rows.Scan(+ &room.RoomID,+ &room.HostTokenDigest,+ &room.ViewerGrantDigest,+ &room.ViewerAuthorizationGeneration,+ &policy,+ &material,+ &lease); err != nil {+ return nil, err+ }+ if err := readDigest(room.HostTokenDigest, "Host token"); err != nil {+ return nil, err+ }+ if err := readDigest(room.ViewerGrantDigest, "Viewer grant"); err != nil {+ return nil, err+ }+ if !validCodeEntryPolicy(policy) {+ return nil, errors.New("Room database contains an invalid code-entry policy")+ }+ room.CodeEntryPolicy = policy+ if material != nil {+ if len(material) != viewerPasswordMaterialBytes {+ return nil, errors.New("Room database contains invalid Viewer password material")+ }+ room.ViewerPasswordMaterial = material+ }+ if lease.Valid {+ if lease.Int64 <= 0 || lease.Int64 > protocol.MaxSafeInteger {+ return nil, errors.New("Room database contains an invalid lease deadline")+ }+ room.LeaseExpiresAtMs = &lease.Int64+ }+ if err := assertStoredRoom(room); err != nil {+ return nil, err+ }+ stored = append(stored, room)+ }+ return stored, rows.Err()+}++func (d *Database) readPragmaInteger(name string) (int64, error) {+ var value int64+ if err := d.conn.QueryRowContext(+ context.Background(), "PRAGMA "+name).Scan(&value); err != nil {+ return 0, fmt.Errorf("Room database %s is invalid", name)+ }+ if value < -protocol.MaxSafeInteger || value > protocol.MaxSafeInteger {+ return 0, fmt.Errorf("Room database %s is invalid", name)+ }+ return value, nil+}++func (d *Database) transaction(operation func() error) error {+ if d.conn == nil {+ return errors.New("Room database is not initialized")+ }+ if err := d.begin("BEGIN IMMEDIATE"); err != nil {+ return err+ }+ if err := operation(); err != nil {+ d.rollbackIfNeeded()+ return err+ }+ if err := d.finish("COMMIT"); err != nil {+ d.rollbackIfNeeded()+ return err+ }+ return nil+}++func (d *Database) begin(statement string) error {+ if _, err := d.conn.ExecContext(context.Background(), statement); err != nil {+ return err+ }+ d.inTransaction = true+ return nil+}++func (d *Database) finish(statement string) error {+ if _, err := d.conn.ExecContext(context.Background(), statement); err != nil {+ return err+ }+ d.inTransaction = false+ return nil+}++// rollbackIfNeeded is `if (database.isTransaction) database.exec("ROLLBACK")`:+// a ROLLBACK with no active transaction is itself an error.+func (d *Database) rollbackIfNeeded() {+ if d.inTransaction {+ _ = d.finish("ROLLBACK")+ }+}++func (d *Database) exec(query string, args ...any) (int64, error) {+ result, err := d.conn.ExecContext(context.Background(), query, args...)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected()+}++func assertStoredRoom(room StoredRoomAuthority) error {+ if !protocol.ValidRoomCode(room.RoomID) {+ return errors.New("Room database contains an invalid room ID")+ }+ if err := assertDigest(room.HostTokenDigest, "Host token"); err != nil {+ return err+ }+ if err := assertDigest(room.ViewerGrantDigest, "Viewer grant"); err != nil {+ return err+ }+ if err := assertAuthorizationGeneration(room.ViewerAuthorizationGeneration); err != nil {+ return err+ }+ if !validCodeEntryPolicy(room.CodeEntryPolicy) {+ return errors.New("Room database contains an invalid code-entry policy")+ }+ if err := assertPasswordMaterial(room.ViewerPasswordMaterial); err != nil {+ return err+ }+ if room.LeaseExpiresAtMs != nil {+ return assertTimestamp(*room.LeaseExpiresAtMs, "Room database lease deadline", false)+ }+ return nil+}++func assertRoomIdentity(roomID string, hostTokenDigest []byte) error {+ if !protocol.ValidRoomCode(roomID) {+ return errors.New("Room ID is invalid")+ }+ return assertDigest(hostTokenDigest, "Host token")+}++func readDigest(value []byte, name string) error {+ if len(value) != 32 {+ return fmt.Errorf("Room database contains an invalid %s digest", name)+ }+ return nil+}++func assertDigest(value []byte, name string) error {+ if len(value) != 32 {+ return fmt.Errorf("%s digest must contain 32 bytes", name)+ }+ return nil+}++func assertPasswordMaterial(value []byte) error {+ if value != nil && len(value) != viewerPasswordMaterialBytes {+ return errors.New("Viewer password material must contain 48 bytes")+ }+ return nil+}++func assertAuthorizationGeneration(value string) error {+ decoded, err := base64.RawURLEncoding.DecodeString(value)+ if err != nil || len(decoded) != 16 ||+ base64.RawURLEncoding.EncodeToString(decoded) != value {+ return errors.New("Viewer authorization generation is invalid")+ }+ return nil+}++// assertTimestamp is the TypeScript Number.isSafeInteger guard: SQLite STRICT+// accepts an integral REAL and a numeric TEXT in an INTEGER column, so the+// range check has to stay on this side.+func assertTimestamp(value int64, name string, allowZero bool) error {+ if value > protocol.MaxSafeInteger || (allowZero && value < 0) || (!allowZero && value <= 0) {+ return fmt.Errorf("%s must be a safe positive integer", name)+ }+ return nil+}++func assertSingleChange(changes int64, operation string) error {+ if changes != 1 {+ return fmt.Errorf("Room database %s did not match current authority", operation)+ }+ return nil+}++func validCodeEntryPolicy(policy protocol.CodeEntryPolicy) bool {+ return policy == protocol.CodeEntryOpen || policy == protocol.CodeEntryPrivate+}diff --git a/internal/server/room/database_test.go b/internal/server/room/database_test.gonew file mode 100644index 00000000..1f864ba3--- /dev/null+++ b/internal/server/room/database_test.go@@ -0,0 +1,684 @@+package room++import (+ "bytes"+ "crypto/sha256"+ "database/sql"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// The scenarios below are ported from tests/room-database.test.ts.++func databasePath(t *testing.T) string {+ t.Helper()+ // t.TempDir registers its removal before any store cleanup below, so the+ // database is always closed first; Windows will not remove an open file.+ return filepath.Join(t.TempDir(), "rooms.sqlite")+}++func stableStore(t *testing.T, path string, testClock *clock, options Options) *Store {+ t.Helper()+ database, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ if options.LeaseMs == 0 {+ options.LeaseMs = 1_000+ }+ if options.MaxRooms == 0 {+ options.MaxRooms = 8+ }+ options.MaxViewersPerRoom = 8+ options.Database = database+ options.Now = func() int64 { return testClock.nowMs }+ store, err := New(options)+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ t.Cleanup(func() { _ = store.Close() })+ if err := store.Initialize(); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ return store+}++func rawDatabase(t *testing.T, path string) *sql.DB {+ t.Helper()+ database, err := sql.Open("sqlite", "file:"+filepath.ToSlash(path))+ if err != nil {+ t.Fatalf("sql.Open: %v", err)+ }+ t.Cleanup(func() { _ = database.Close() })+ return database+}++func rawExec(t *testing.T, path, statement string) {+ t.Helper()+ if _, err := rawDatabase(t, path).Exec(statement); err != nil {+ t.Fatalf("raw exec %q: %v", statement, err)+ }+}++func dbViewerInput(roomID, sessionID, viewerGrant string) ConnectParticipantInput {+ input := viewerInput(roomID, sessionID, viewerGrant)+ input.ClientID = "client-" + sessionID+ return input+}++func TestDoesNotPersistARoomWhenPasswordDerivationIsBusy(t *testing.T) {+ path := databasePath(t)+ testClock := &clock{nowMs: 1_000}+ first := stableStore(t, path, testClock, Options{MaxRooms: 1})++ withSaturatedGate(t, first, func() {+ _, err := tryCreateRoom(first, protocol.CodeEntryPrivate, "room-password", "4321")+ expectCode(t, err, CodeRoomBusy)+ })+ if first.Size() != 0 {+ t.Fatalf("size = %d, want 0", first.Size())+ }+ if err := first.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ second := stableStore(t, path, testClock, Options{MaxRooms: 1})+ if second.Size() != 0 {+ t.Fatalf("restored size = %d, want 0", second.Size())+ }+ if created := createRoom(t, second, protocol.CodeEntryPrivate, "", "4321"); created.RoomID != "4321" {+ t.Fatalf("room = %q, want 4321", created.RoomID)+ }+}++func TestRestoresTheExactAuthorityAggregateWithoutParticipants(t *testing.T) {+ path := databasePath(t)+ testClock := &clock{nowMs: 1_000}+ first := stableStore(t, path, testClock, Options{})+ room := createRoom(t, first, protocol.CodeEntryOpen, "", "4321")+ if _, err := first.SetCodeEntryPolicy(+ room.RoomID, protocol.CodeEntryPrivate, room.HostToken); err != nil {+ t.Fatalf("SetCodeEntryPolicy: %v", err)+ }+ if _, err := trySetViewerPassword(+ first, room.RoomID, "room-password", room.HostToken); err != nil {+ t.Fatalf("SetViewerPassword: %v", err)+ }+ rotated, err := first.SetViewerGrant(room.RoomID, "rotate", room.HostToken)+ if err != nil {+ t.Fatalf("SetViewerGrant: %v", err)+ }+ host := mustConnect(t, first, hostInput(room.RoomID, room.HostToken))+ oldViewer := mustConnect(t, first, dbViewerInput(room.RoomID, "old-viewer", rotated.ViewerGrant))+ if connected, ok := first.GetConnectedHost(room.RoomID); !ok || connected.PeerID != host.PeerID {+ t.Fatalf("host = %+v %v", connected, ok)+ }+ if _, ok := first.GetConnectedViewer(room.RoomID, oldViewer.PeerID); !ok {+ t.Fatal("viewer is not connected")+ }+ if err := first.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ testClock.nowMs = 2_000+ second := stableStore(t, path, testClock, Options{})+ if second.Size() != 1 {+ t.Fatalf("restored size = %d, want 1", second.Size())+ }+ if _, ok := second.GetConnectedHost(room.RoomID); ok {+ t.Fatal("a restored room reported a connected host")+ }+ if viewers := second.GetConnectedViewers(room.RoomID); len(viewers) != 0 {+ t.Fatalf("restored viewers = %+v", viewers)+ }+ _, err = second.ConnectParticipant(dbViewerInput(room.RoomID, "revoked-grant", room.ViewerGrant))+ expectCode(t, err, CodeInvalidToken)++ granted := mustConnect(t, second, dbViewerInput(room.RoomID, "current-grant", rotated.ViewerGrant))+ if granted.ExpiresAt == nil || *granted.ExpiresAt != "1970-01-01T00:00:03.000Z" {+ t.Fatalf("expiresAt = %v", granted.ExpiresAt)+ }+ if granted.ViewerAuthorizationGeneration != rotated.ViewerAuthorizationGeneration {+ t.Fatalf("generation = %q, want %q",+ granted.ViewerAuthorizationGeneration, rotated.ViewerAuthorizationGeneration)+ }+ connected, err := tryConnectViewerWithPassword(second, ConnectViewerWithPasswordInput{+ RoomID: room.RoomID,+ Password: "room-password",+ ClientID: "password-client",+ SessionID: "password-session",+ }, nil)+ if err != nil || connected.CodeEntryPolicy != protocol.CodeEntryPrivate {+ t.Fatalf("password login = %+v, %v", connected, err)+ }+ _, err = second.ConnectParticipant(hostInput(room.RoomID, "wrong-token"))+ expectCode(t, err, CodeInvalidToken)+ resumed := mustConnect(t, second, hostInput(room.RoomID, room.HostToken, "recovered-host"))+ if resumed.ExpiresAt != nil {+ t.Fatalf("resumed expiresAt = %v, want null", *resumed.ExpiresAt)+ }+ if err := second.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ raw := rawDatabase(t, path)+ rows, err := raw.Query("SELECT * FROM rooms")+ if err != nil {+ t.Fatalf("raw query: %v", err)+ }+ defer rows.Close()+ columns, err := rows.Columns()+ if err != nil {+ t.Fatalf("Columns: %v", err)+ }+ want := []string{+ "room_id", "host_token_digest", "viewer_grant_digest",+ "viewer_authorization_generation", "code_entry_policy",+ "viewer_password_material", "lease_expires_at_ms",+ }+ if strings.Join(columns, ",") != strings.Join(want, ",") {+ t.Fatalf("columns = %v", columns)+ }+ if !rows.Next() {+ t.Fatal("no stored room")+ }+ var (+ roomID string+ hostDigest []byte+ grantDigest []byte+ generation string+ policy string+ material []byte+ leaseExpiresAtMs sql.NullInt64+ )+ if err := rows.Scan(&roomID, &hostDigest, &grantDigest, &generation, &policy,+ &material, &leaseExpiresAtMs); err != nil {+ t.Fatalf("Scan: %v", err)+ }+ hostTokenDigest := sha256.Sum256([]byte(room.HostToken))+ if !bytes.Equal(hostDigest, hostTokenDigest[:]) {+ t.Fatal("stored Host token digest does not match")+ }+ grantTokenDigest := sha256.Sum256([]byte(rotated.ViewerGrant))+ if !bytes.Equal(grantDigest, grantTokenDigest[:]) {+ t.Fatal("stored Viewer grant digest does not match")+ }+ if len(material) != 48 {+ t.Fatalf("password material = %d bytes, want 48", len(material))+ }+ // Nothing reversible is stored: no token, grant or password appears.+ stored := roomID + generation + policy + string(hostDigest) + string(grantDigest) + string(material)+ for _, secret := range []string{room.HostToken, rotated.ViewerGrant, "room-password"} {+ if strings.Contains(stored, secret) {+ t.Fatal("a credential was stored verbatim")+ }+ }+}++func TestConvertsAnActiveMarkerOnceAndPreservesDormantDeadlines(t *testing.T) {+ path := databasePath(t)+ testClock := &clock{nowMs: 100}+ first := stableStore(t, path, testClock, Options{})+ room := createRoom(t, first, protocol.CodeEntryOpen, "", "5678")+ mustConnect(t, first, hostInput(room.RoomID, room.HostToken))+ if err := first.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ testClock.nowMs = 500+ second := stableStore(t, path, testClock, Options{})+ firstRestart := mustConnect(t, second, dbViewerInput(room.RoomID, "first-restart", room.ViewerGrant))+ if firstRestart.ExpiresAt == nil || *firstRestart.ExpiresAt != "1970-01-01T00:00:01.500Z" {+ t.Fatalf("expiresAt = %v", firstRestart.ExpiresAt)+ }+ if err := second.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ testClock.nowMs = 700+ third := stableStore(t, path, testClock, Options{})+ secondRestart := mustConnect(t, third, dbViewerInput(room.RoomID, "second-restart", room.ViewerGrant))+ if secondRestart.ExpiresAt == nil || *secondRestart.ExpiresAt != "1970-01-01T00:00:01.500Z" {+ t.Fatalf("expiresAt = %v", secondRestart.ExpiresAt)+ }+ if err := third.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ testClock.nowMs = 1_501+ fourth := stableStore(t, path, testClock, Options{})+ if fourth.Size() != 0 {+ t.Fatalf("size = %d, want 0", fourth.Size())+ }+ replacement := createRoom(t, fourth, protocol.CodeEntryOpen, "", room.RoomID)+ if replacement.RoomID != room.RoomID {+ t.Fatalf("replacement room = %q", replacement.RoomID)+ }+ _, err := fourth.ConnectParticipant(hostInput(room.RoomID, room.HostToken))+ expectCode(t, err, CodeInvalidToken)+ _, err = fourth.ConnectParticipant(dbViewerInput(room.RoomID, "stale-grant", room.ViewerGrant))+ expectCode(t, err, CodeInvalidToken)+}++func TestPreservesTheExactHostDisconnectDeadline(t *testing.T) {+ path := databasePath(t)+ testClock := &clock{nowMs: 100}+ first := stableStore(t, path, testClock, Options{})+ room := createRoom(t, first, protocol.CodeEntryOpen, "", "5890")+ host := mustConnect(t, first, hostInput(room.RoomID, room.HostToken))+ testClock.nowMs = 250+ if _, err := first.DisconnectParticipant(room.RoomID, host.PeerID, "host-session"); err != nil {+ t.Fatalf("DisconnectParticipant: %v", err)+ }+ if err := first.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ testClock.nowMs = 500+ second := stableStore(t, path, testClock, Options{})+ dormant := mustConnect(t, second, dbViewerInput(room.RoomID, "dormant-viewer", room.ViewerGrant))+ if dormant.ExpiresAt == nil || *dormant.ExpiresAt != "1970-01-01T00:00:01.250Z" {+ t.Fatalf("expiresAt = %v", dormant.ExpiresAt)+ }+}++func TestPersistsExplicitRoomDeletionBeforeRecyclingItsCode(t *testing.T) {+ path := databasePath(t)+ testClock := &clock{nowMs: 10}+ first := stableStore(t, path, testClock, Options{})+ room := createRoom(t, first, protocol.CodeEntryOpen, "", "6789")+ closed, err := first.AbandonRoom(room.RoomID)+ if err != nil || closed == nil || closed.RoomID != room.RoomID {+ t.Fatalf("AbandonRoom = %v, %v", closed, err)+ }+ if err := first.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ second := stableStore(t, path, testClock, Options{})+ if second.Size() != 0 {+ t.Fatalf("size = %d, want 0", second.Size())+ }+ replacement := createRoom(t, second, protocol.CodeEntryOpen, "", room.RoomID)+ if replacement.RoomID != room.RoomID {+ t.Fatalf("replacement room = %q", replacement.RoomID)+ }+ if replacement.HostToken == room.HostToken || replacement.ViewerGrant == room.ViewerGrant {+ t.Fatal("the recycled code kept the old credentials")+ }+}++func TestRollsBackABatchExpiryWhenAnyAuthorityIsStale(t *testing.T) {+ path := databasePath(t)+ testClock := &clock{nowMs: 10}+ first := stableStore(t, path, testClock, Options{})+ createRoom(t, first, protocol.CodeEntryOpen, "", "4321")+ createRoom(t, first, protocol.CodeEntryOpen, "", "5678")+ if err := first.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ database, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ restored, err := database.Initialize(testClock.nowMs, 1_010)+ if err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ if len(restored) != 2 {+ t.Fatalf("restored %d rooms, want 2", len(restored))+ }+ err = database.DeleteRooms([]RoomIdentity{+ {RoomID: restored[0].RoomID, HostTokenDigest: restored[0].HostTokenDigest},+ {RoomID: restored[1].RoomID, HostTokenDigest: make([]byte, 32)},+ })+ if err == nil || err.Error() != "Room database delete did not match current authority" {+ t.Fatalf("DeleteRooms: %v", err)+ }+ if err := database.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ second := stableStore(t, path, testClock, Options{})+ if second.Size() != 2 {+ t.Fatalf("size = %d, want 2", second.Size())+ }+}++func TestPersistsRoomReplacementAsOneAuthorityTransition(t *testing.T) {+ path := databasePath(t)+ testClock := &clock{nowMs: 10}+ first := stableStore(t, path, testClock, Options{})+ original := createRoom(t, first, protocol.CodeEntryOpen, "", "4321")+ replacement, err := tryReplaceRoom(+ first, original.RoomID, original.HostToken, protocol.CodeEntryPrivate, "new-password")+ if err != nil {+ t.Fatalf("ReplaceRoom: %v", err)+ }+ if err := first.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ second := stableStore(t, path, testClock, Options{})+ if second.Size() != 1 {+ t.Fatalf("size = %d, want 1", second.Size())+ }+ _, err = second.ConnectParticipant(hostInput(original.RoomID, original.HostToken))+ expectCode(t, err, CodeInvalidToken)+ connected := mustConnect(t, second, dbViewerInput(+ replacement.Created.RoomID, "replacement-viewer", replacement.Created.ViewerGrant))+ if connected.RoomID != replacement.Created.RoomID {+ t.Fatalf("viewer joined %q", connected.RoomID)+ }+ withPassword, err := tryConnectViewerWithPassword(second, ConnectViewerWithPasswordInput{+ RoomID: replacement.Created.RoomID,+ Password: "new-password",+ ClientID: "password-viewer",+ SessionID: "password-session",+ }, nil)+ if err != nil || withPassword.RoomID != replacement.Created.RoomID {+ t.Fatalf("password login = %+v, %v", withPassword, err)+ }+}++// TestOpensThePathWithURIReservedCharactersLiterally: `new DatabaseSync(path)`+// opened the literal path, while the driver's DSN is a URI in which `%41`+// decodes to `A` and `#` ends the file name; the file must still be the+// configured one, and the busy-timeout pragma must survive the escaping.+func TestOpensThePathWithURIReservedCharactersLiterally(t *testing.T) {+ testClock := &clock{nowMs: 10}+ path := filepath.Join(t.TempDir(), "rooms%41#1.sqlite")+ first := stableStore(t, path, testClock, Options{})+ createRoom(t, first, protocol.CodeEntryOpen, "", "4321")+ if err := first.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+ if _, err := os.Stat(path); err != nil {+ t.Fatalf("the configured file was not the one opened: %v", err)+ }+ if second := stableStore(t, path, testClock, Options{}); second.Size() != 1 {+ t.Fatalf("restored size = %d, want 1", second.Size())+ }+}++func TestRejectsAnotherOwnerOfTheSameDatabase(t *testing.T) {+ path := databasePath(t)+ first, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ if _, err := first.Initialize(0, 1_000); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ contender, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ _, err = contender.Initialize(0, 1_000)+ if err == nil || !strings.Contains(strings.ToLower(err.Error()), "locked") {+ t.Fatalf("contender Initialize = %v, want a lock failure", err)+ }+ if err := contender.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+ if err := first.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ successor, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ restored, err := successor.Initialize(0, 1_000)+ if err != nil || len(restored) != 0 {+ t.Fatalf("successor Initialize = %v, %v", restored, err)+ }+ if err := successor.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+}++func TestRejectsAnUnknownDatabaseIdentity(t *testing.T) {+ for _, testCase := range []struct{ name, mutation string }{+ {"application identity", "PRAGMA application_id = 1"},+ {"schema version", "PRAGMA user_version = 2"},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ path := databasePath(t)+ initial, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ if _, err := initial.Initialize(0, 1_000); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ if err := initial.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+ rawExec(t, path, testCase.mutation)++ reopened, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ _, err = reopened.Initialize(0, 1_000)+ if err == nil || !strings.Contains(err.Error(), "does not match") {+ t.Fatalf("Initialize = %v", err)+ }+ if err := reopened.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+ })+ }+}++func TestRejectsAnAlteredCurrentVersionSchema(t *testing.T) {+ path := databasePath(t)+ initial, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ if _, err := initial.Initialize(0, 1_000); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ if err := initial.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+ rawExec(t, path, "ALTER TABLE rooms ADD COLUMN unexpected TEXT")++ reopened, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ _, err = reopened.Initialize(0, 1_000)+ if err == nil || err.Error() != "Room database columns do not match the current schema" {+ t.Fatalf("Initialize = %v", err)+ }+ if err := reopened.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+}++func TestRejectsCorruptAuthorityRows(t *testing.T) {+ path := databasePath(t)+ testClock := &clock{nowMs: 100}+ initial := stableStore(t, path, testClock, Options{})+ createRoom(t, initial, protocol.CodeEntryOpen, "", "7890")+ if err := initial.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }++ raw := rawDatabase(t, path)+ if _, err := raw.Exec("PRAGMA ignore_check_constraints = ON"); err != nil {+ t.Fatalf("raw pragma: %v", err)+ }+ if _, err := raw.Exec("UPDATE rooms SET host_token_digest = zeroblob(31)"); err != nil {+ t.Fatalf("raw update: %v", err)+ }+ if err := raw.Close(); err != nil {+ t.Fatalf("raw close: %v", err)+ }++ database, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ reopened, err := New(Options{+ LeaseMs: 1_000,+ MaxRooms: 8,+ MaxViewersPerRoom: 8,+ Now: func() int64 { return testClock.nowMs },+ Database: database,+ })+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ // The oracle accepts either rejection: this SQLite build reports the broken+ // row from PRAGMA quick_check before the digest length assertion runs.+ err = reopened.Initialize()+ if err == nil || (!strings.Contains(err.Error(), "Host token") &&+ !strings.Contains(err.Error(), "integrity")) {+ t.Fatalf("Initialize = %v", err)+ }+ if err := reopened.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+}++// TestRejectsInvalidAuthorityArguments keeps the assertions the TypeScript ran+// before touching SQLite: STRICT would accept an integral REAL or a numeric+// TEXT timestamp, and a caller mistake must not reach the file at all.+func TestRejectsInvalidAuthorityArguments(t *testing.T) {+ valid := StoredRoomAuthority{+ RoomID: "1234",+ HostTokenDigest: make([]byte, 32),+ ViewerGrantDigest: make([]byte, 32),+ ViewerAuthorizationGeneration: "MzMzMzMzMzMzMzMzMzMzMw",+ CodeEntryPolicy: protocol.CodeEntryOpen,+ }+ lease := int64(protocol.MaxSafeInteger + 1)+ shortDigest := make([]byte, 31)+ for _, testCase := range []struct {+ name string+ run func(*Database) error+ want string+ }{+ {"room ID", func(d *Database) error {+ room := valid+ room.RoomID = "0123"+ return d.InsertRoom(room)+ }, "Room database contains an invalid room ID"},+ {"host digest", func(d *Database) error {+ room := valid+ room.HostTokenDigest = shortDigest+ return d.InsertRoom(room)+ }, "Host token digest must contain 32 bytes"},+ {"grant digest", func(d *Database) error {+ room := valid+ room.ViewerGrantDigest = shortDigest+ return d.InsertRoom(room)+ }, "Viewer grant digest must contain 32 bytes"},+ {"generation", func(d *Database) error {+ room := valid+ room.ViewerAuthorizationGeneration = "MzMzMzMzMzMzMzMzMzMzMw=="+ return d.InsertRoom(room)+ }, "Viewer authorization generation is invalid"},+ {"policy", func(d *Database) error {+ room := valid+ room.CodeEntryPolicy = "public"+ return d.InsertRoom(room)+ }, "Room database contains an invalid code-entry policy"},+ {"password material", func(d *Database) error {+ room := valid+ room.ViewerPasswordMaterial = make([]byte, 47)+ return d.InsertRoom(room)+ }, "Viewer password material must contain 48 bytes"},+ {"lease deadline", func(d *Database) error {+ room := valid+ room.LeaseExpiresAtMs = &lease+ return d.InsertRoom(room)+ }, "Room database lease deadline must be a safe positive integer"},+ {"identity", func(d *Database) error {+ return d.SetLeaseDeadline("123", make([]byte, 32), nil)+ }, "Room ID is invalid"},+ {"update policy", func(d *Database) error {+ return d.SetCodeEntryPolicy("1234", make([]byte, 32), "public")+ }, "Room code-entry policy is invalid"},+ {"replacement identity", func(d *Database) error {+ return d.ReplaceRoom("1234", make([]byte, 32), valid)+ }, "Replacement room ID must be different"},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ database, err := NewDatabase(databasePath(t))+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ if _, err := database.Initialize(0, 1_000); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ defer func() { _ = database.Close() }()+ if err := testCase.run(database); err == nil || err.Error() != testCase.want {+ t.Fatalf("error = %v, want %q", err, testCase.want)+ }+ })+ }+}++func TestRejectsAMemoryDatabasePath(t *testing.T) {+ for _, path := range []string{"", ":memory:"} {+ if _, err := NewDatabase(path); err == nil ||+ err.Error() != "Room database path must identify a file" {+ t.Fatalf("NewDatabase(%q) = %v", path, err)+ }+ }+}++func TestRejectsASecondInitialize(t *testing.T) {+ path := databasePath(t)+ database, err := NewDatabase(path)+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ if _, err := database.Initialize(0, 1_000); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ if _, err := database.Initialize(0, 1_000); err == nil ||+ err.Error() != "Room database is already initialized" {+ t.Fatalf("second Initialize = %v", err)+ }+ if err := database.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+ if err := database.InsertRoom(StoredRoomAuthority{+ RoomID: "1234",+ HostTokenDigest: make([]byte, 32),+ ViewerGrantDigest: make([]byte, 32),+ ViewerAuthorizationGeneration: "MzMzMzMzMzMzMzMzMzMzMw",+ CodeEntryPolicy: protocol.CodeEntryOpen,+ }); err == nil || err.Error() != "Room database is not initialized" {+ t.Fatalf("InsertRoom after Close = %v", err)+ }+}++func TestRejectsAnActiveLeaseThatIsNotInTheFuture(t *testing.T) {+ database, err := NewDatabase(databasePath(t))+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ if _, err := database.Initialize(1_000, 1_000); err == nil ||+ err.Error() != "Room database active-room lease deadline must be in the future" {+ t.Fatalf("Initialize = %v", err)+ }+ if _, err := database.Initialize(-1, 1_000); err == nil ||+ err.Error() != "Room database startup time must be a safe positive integer" {+ t.Fatalf("Initialize = %v", err)+ }+ if err := database.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+}diff --git a/internal/server/room/doc.go b/internal/server/room/doc.gonew file mode 100644index 00000000..84d73cb3--- /dev/null+++ b/internal/server/room/doc.go@@ -0,0 +1,88 @@+// Package room ports the room authority: src/server/room-store.ts (rooms,+// participants, room codes, viewer credentials, the four-digit code pool) and+// src/server/room-database.ts (the SQLite stable authority). Every mutation+// writes SQLite before memory and returns the write error unchanged; there is+// no catch-and-continue anywhere, exactly as in the TypeScript.+//+// # Locking+//+// Store has no mutex. The signaling layer's single global lock guards it, which+// is what Node's single thread did: nothing interleaved except at an await. The+// caller must hold that lock for every method below except the two derive+// methods, which run the password KDF and must NOT be called under the lock.+//+// The TypeScript methods that await the KDF are split into a locked "begin",+// an unlocked derive, and a locked "commit" so that the guards the TypeScript+// re-ran after its await are re-run here after the relock, in the same order.+// The commit takes the derive result as (material, derived error) because the+// TypeScript inspected the gate outcome (busy/cancelled) only after re-reading+// the room: forward both values unchanged and the commit reproduces the order.+//+// POST /api/rooms (createRoom):+//+// mu.Lock()+// lease, err := store.BeginCreateRoom() // ROOM_LIMIT + lease deadline, pre-KDF+// if err != nil { mu.Unlock(); return err }+// var material []byte+// var derived error+// if password != "" {+// mu.Unlock()+// material, derived = store.DeriveViewerPasswordMaterial(password, nil)+// mu.Lock()+// }+// created, err := store.CreateRoom(policy, material, derived, preferredRoomID, lease)+// mu.Unlock()+//+// replaceRoom and set-viewer-password (the mayStart closure is the TypeScript+// `rooms.get(roomId) === current && verifyDigest(hostToken, ...)`; it runs on+// the derive goroutine, so it takes the lock itself):+//+// mu.Lock()+// current, err := store.HostManagedRoom(roomID, hostToken) // may fail INVALID_TOKEN/ROOM_EXPIRED+// if err != nil { mu.Unlock(); return err }+// var material []byte+// var derived error+// if password != "" {+// mu.Unlock()+// material, derived = store.DeriveViewerPasswordMaterial(password, func() bool {+// mu.Lock()+// defer mu.Unlock()+// return store.HostStillOwnsRoom(roomID, hostToken, current)+// })+// mu.Lock()+// }+// replaced, err := store.ReplaceRoom(roomID, hostToken, policy, material, derived, current)+// mu.Unlock()+//+// Viewer password login (signaling authenticate). mayConnect is the TypeScript+// closure `!closing && socketStates.get(socket) === state && !state.revoked &&+// !state.authenticated && socket.readyState === OPEN`. It is evaluated twice,+// once on the derive goroutine (gate admission) and once under the lock inside+// the commit, so the caller needs both a locking and a non-locking form of the+// same predicate:+//+// mu.Lock()+// salt, expected, ref, err := store.ViewerPasswordChallenge(input.RoomID)+// mu.Unlock()+// if err != nil { return err } // not initialized+// derivedKey, err := store.DeriveViewerPassword(input.Password, salt, func() bool {+// mu.Lock()+// defer mu.Unlock()+// return mayConnectLocked()+// })+// mu.Lock()+// if err != nil { mu.Unlock(); return err } // ROOM_BUSY or INVALID_TOKEN+// participant, err := store.ConnectViewerWithPassword(+// input, derivedKey, expected, ref, mayConnectLocked)+// mu.Unlock()+//+// The room reference handed back by HostManagedRoom and ViewerPasswordChallenge+// is only ever compared for pointer identity, reproducing the TypeScript+// `currentRoom !== room` checks that detect a room replaced while the KDF ran.+// Holding it across the unlock is safe: an abandoned room is dropped from the+// map, never mutated into another room.+//+// Options.Random is called both under the caller's lock and from the derive+// goroutine (the 16-byte salt), so it must be safe for concurrent use;+// crypto/rand is.+package roomdiff --git a/internal/server/room/password.go b/internal/server/room/password.gonew file mode 100644index 00000000..cae24c6f--- /dev/null+++ b/internal/server/room/password.go@@ -0,0 +1,145 @@+package room++import (+ "errors"+ "slices"+ "sync"++ "golang.org/x/crypto/scrypt"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++const (+ viewerPasswordSaltBytes = 16+ viewerPasswordVerifierBytes = 32+ viewerPasswordMaterialBytes = viewerPasswordSaltBytes + viewerPasswordVerifierBytes++ viewerPasswordScryptN = 16_384+ viewerPasswordScryptR = 8+ viewerPasswordScryptP = 1++ // AsyncGate bounds from src/server/room-store.ts (DECISIONS D11): scrypt at+ // N=16384 costs ~16 MiB and tens of milliseconds, so two concurrent+ // derivations bound the memory and CPU a room burst can claim, and sixteen+ // waiters bound the queue before the next caller is told ROOM_BUSY.+ gateActiveLimit = 2+ gatePendingLimit = 16+)++// errDerivationCancelled is the AsyncGate "cancelled" outcome. Callers never+// inspect it: they hand it to the commit method, which maps it the way the+// TypeScript call site did.+var errDerivationCancelled = errors.New("password derivation was cancelled")++// isGateOutcome reports whether err is one of the two AsyncGate outcomes rather+// than a thrown error. The TypeScript returned busy and cancelled as values,+// which its post-await checks inspected after re-reading the room; everything+// else threw out of the await.+func isGateOutcome(err error) bool {+ return errors.Is(err, errDerivationCancelled) || hasCode(err, CodeRoomBusy)+}++// DeriveViewerPasswordMaterial is createViewerPasswordMaterial: it validates the+// password, draws a fresh salt and returns salt||verifier. Call it WITHOUT the+// caller's lock held and hand both results to CreateRoom, ReplaceRoom or+// SetViewerPassword unchanged; those reproduce the TypeScript order in which a+// busy or cancelled outcome is turned into an error. mayStart may be nil, which+// is the TypeScript default of `() => true`.+func (s *Store) DeriveViewerPasswordMaterial(+ password string, mayStart func() bool,+) ([]byte, error) {+ if !protocol.ValidViewerPassword(password) {+ return nil, codeError(CodeInvalidToken)+ }+ salt := s.random(viewerPasswordSaltBytes)+ if len(salt) != viewerPasswordSaltBytes {+ return nil, errors.New("Viewer password salt source must return 16 bytes")+ }+ verifier, err := s.deriveViewerPassword(password, salt, mayStart)+ if err != nil {+ return nil, err+ }+ return slices.Concat(salt, verifier), nil+}++// DeriveViewerPassword is the unlocked middle of connectViewerWithPassword: it+// derives the verifier for the salt ViewerPasswordChallenge returned. Unlike+// DeriveViewerPasswordMaterial it maps both gate outcomes itself, because the+// TypeScript threw them immediately after the await, before re-reading the room.+func (s *Store) DeriveViewerPassword(+ password string, salt []byte, mayConnect func() bool,+) ([]byte, error) {+ if !protocol.ValidViewerPassword(password) {+ return nil, codeError(CodeInvalidToken)+ }+ derived, err := s.deriveViewerPassword(password, salt, mayConnect)+ if errors.Is(err, errDerivationCancelled) {+ return nil, codeError(CodeInvalidToken)+ }+ return derived, err+}++func (s *Store) deriveViewerPassword(+ password string, salt []byte, mayStart func() bool,+) ([]byte, error) {+ return s.gate.run(mayStart, func() ([]byte, error) {+ return scrypt.Key([]byte(password), salt,+ viewerPasswordScryptN, viewerPasswordScryptR, viewerPasswordScryptP,+ viewerPasswordVerifierBytes)+ })+}++// gate is AsyncGate: at most limit derivations run at once and at most+// pendingLimit wait, first in first out. A saturated gate answers ROOM_BUSY.+type gate struct {+ mu sync.Mutex+ active int+ waiters []chan struct{}+ limit int+ pendingLimit int+}++func (g *gate) run(mayStart func() bool, task func() ([]byte, error)) ([]byte, error) {+ if !g.acquire() {+ return nil, codeError(CodeRoomBusy)+ }+ defer g.release()+ if mayStart != nil && !mayStart() {+ return nil, errDerivationCancelled+ }+ return task()+}++func (g *gate) acquire() bool {+ g.mu.Lock()+ if g.active < g.limit {+ g.active+++ g.mu.Unlock()+ return true+ }+ if len(g.waiters) >= g.pendingLimit {+ g.mu.Unlock()+ return false+ }+ wake := make(chan struct{})+ g.waiters = append(g.waiters, wake)+ g.mu.Unlock()+ <-wake+ return true+}++// release hands the slot to the first waiter instead of decrementing, which is+// what `const next = this.waiters.shift(); if (next) { next(); return; }` did.+func (g *gate) release() {+ g.mu.Lock()+ if len(g.waiters) > 0 {+ wake := g.waiters[0]+ g.waiters = g.waiters[1:]+ g.mu.Unlock()+ close(wake)+ return+ }+ g.active--+ g.mu.Unlock()+}diff --git a/internal/server/room/store.go b/internal/server/room/store.gonew file mode 100644index 00000000..607c86db--- /dev/null+++ b/internal/server/room/store.go@@ -0,0 +1,1199 @@+package room++import (+ "bytes"+ "crypto/rand"+ "crypto/sha256"+ "crypto/subtle"+ "encoding/base64"+ "encoding/binary"+ "errors"+ "fmt"+ "math"+ "slices"+ "strconv"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// Capacity is ROOM_CAPACITY: every four-digit room code.+const Capacity = 9_000++const roomCodeFirst = 1_000++// ErrorCode is RoomStoreErrorCode.+type ErrorCode string++// The RoomStoreErrorCode set.+const (+ CodeInvalidToken ErrorCode = "INVALID_TOKEN"+ CodeRoomAccessDenied ErrorCode = "ROOM_ACCESS_DENIED"+ CodeRoomBusy ErrorCode = "ROOM_BUSY"+ CodeRoomNotFound ErrorCode = "ROOM_NOT_FOUND"+ CodeRoomExpired ErrorCode = "ROOM_EXPIRED"+ CodeRoomFull ErrorCode = "ROOM_FULL"+ CodeHostAlreadyConnected ErrorCode = "HOST_ALREADY_CONNECTED"+ CodeRoomLimit ErrorCode = "ROOM_LIMIT"+)++// Error is RoomStoreError. Its message is the code, as `super(code)` made it.+type Error struct {+ Code ErrorCode+}++// Error returns the code, which is the message `super(code)` produced.+func (e *Error) Error() string { return string(e.Code) }++func codeError(code ErrorCode) error { return &Error{Code: code} }++func hasCode(err error, code ErrorCode) bool {+ var roomError *Error+ return errors.As(err, &roomError) && roomError.Code == code+}++// admittedBy values.+const (+ admittedByGrant = "grant"+ admittedByCode = "code"+)++type participant struct {+ clientID string+ peerID string+ // sessionID is "" where the TypeScript left sessionId undefined. Session+ // IDs are opaque IDs of at least 8 characters, so "" cannot collide.+ sessionID string+ admittedBy string+}++// Room is one room's authority plus its participants. It has no exported+// members: callers hold the pointer only to compare identity across the+// unlocked password derivation, as the TypeScript compared room objects.+type Room struct {+ roomID string+ hostTokenDigest []byte+ viewerGrantDigest []byte+ viewerPasswordMaterial []byte+ viewerAuthorizationGeneration string+ codeEntryPolicy protocol.CodeEntryPolicy+ sharingActive bool+ leaseExpiresAtMs *int64+ host *participant+ // ordering: JS Map insertion order decides viewer presence order, the+ // closed-session list and the router's participant order.+ viewers ordered.Map[string, *participant]+}++// CreatedRoom is CreatedRoom. ViewerGrant is "" where the TypeScript had null.+type CreatedRoom struct {+ RoomID string+ HostToken string+ CodeEntryPolicy protocol.CodeEntryPolicy+ ViewerGrant string+ ExpiresAt *string+}++// ConnectParticipantInput is ConnectParticipantInput; Token is read for a host+// and ViewerGrant for a viewer, "" meaning the key was absent.+type ConnectParticipantInput struct {+ RoomID string+ Role protocol.Role+ Token string+ ViewerGrant string+ ClientID string+ SessionID string+}++// ConnectViewerWithPasswordInput is ConnectViewerWithPasswordInput. Password is+// consumed by the caller's DeriveViewerPassword call, not by the commit.+type ConnectViewerWithPasswordInput struct {+ RoomID string+ Password string+ ClientID string+ SessionID string+}++// ConnectedParticipant is ConnectedParticipant. ReplacedSessionID is "" where+// the TypeScript omitted replacedSessionId.+type ConnectedParticipant struct {+ RoomID string+ Role protocol.Role+ PeerID string+ ExpiresAt *string+ HostOnline bool+ ReplacedSessionID string+ CodeEntryPolicy protocol.CodeEntryPolicy+ ViewerPasswordEnabled bool+ ViewerAuthorizationGeneration string+}++// DisconnectedParticipant is DisconnectedParticipant.+type DisconnectedParticipant struct {+ RoomID string+ Role protocol.Role+ PeerID string+}++// ConnectedPeer is ConnectedPeer.+type ConnectedPeer struct {+ PeerID string+ SessionID string+}++// ClosedRoom is ClosedRoom.+type ClosedRoom struct {+ RoomID string+ SessionIDs []string+}++// ReplacedRoom is ReplacedRoom.+type ReplacedRoom struct {+ Created CreatedRoom+ Closed ClosedRoom+}++// RevokedViewer is RevokedViewer; SessionID is "" where the TypeScript omitted+// sessionId.+type RevokedViewer struct {+ PeerID string+ SessionID string+}++// ViewerGrantUpdate is ViewerGrantUpdate. ViewerGrant is "" for a revoke.+type ViewerGrantUpdate struct {+ ViewerGrant string+ ViewerAuthorizationGeneration string+ PreviousViewerAuthorizationGeneration string+ RevokedViewers []RevokedViewer+}++// CodeEntryUpdate is CodeEntryUpdate.+type CodeEntryUpdate struct {+ CodeEntryPolicy protocol.CodeEntryPolicy+ ViewerPasswordEnabled bool+}++// Options is RoomStoreOptions.+type Options struct {+ LeaseMs int64+ MaxRooms int+ MaxViewersPerRoom int+ Database *Database+ Now func() int64+ Random func(size int) []byte+}++// Store is RoomStore. See the package comment for the locking contract.+type Store struct {+ // ordering: JS Map insertion order decides AbandonAllRooms/ExpireRooms.+ rooms ordered.Map[string, *Room]+ freeRoomCodes []string+ now func() int64+ random func(size int) []byte+ database *Database+ initialized bool+ leaseMs int64+ maxRooms int+ maxViewersPerRoom int+ // gate is per store; the TypeScript module-level gate was shared by every+ // RoomStore in a process, of which there was one (D11).+ gate gate+}++// New is the RoomStore constructor; the TypeScript threw where this returns an+// error.+func New(options Options) (*Store, error) {+ if options.LeaseMs <= 0 || options.LeaseMs > protocol.MaxSafeInteger {+ return nil, errors.New("Room lease must be a positive integer")+ }+ if options.MaxRooms <= 0 || options.MaxRooms > Capacity {+ return nil, fmt.Errorf("Room limit must be an integer between 1 and %d", Capacity)+ }+ if options.MaxViewersPerRoom <= 0 ||+ options.MaxViewersPerRoom > protocol.MaxViewersPerRoomLimit {+ return nil, fmt.Errorf(+ "Room viewer limit must be an integer between 1 and %d",+ protocol.MaxViewersPerRoomLimit)+ }+ store := &Store{+ freeRoomCodes: make([]string, Capacity),+ now: options.Now,+ random: options.Random,+ database: options.Database,+ initialized: options.Database == nil,+ leaseMs: options.LeaseMs,+ maxRooms: options.MaxRooms,+ maxViewersPerRoom: options.MaxViewersPerRoom,+ gate: gate{limit: gateActiveLimit, pendingLimit: gatePendingLimit},+ }+ for index := range store.freeRoomCodes {+ store.freeRoomCodes[index] = strconv.Itoa(roomCodeFirst + index)+ }+ if store.now == nil {+ store.now = func() int64 { return time.Now().UnixMilli() }+ }+ if store.random == nil {+ store.random = cryptoRandom+ }+ return store, nil+}++func cryptoRandom(size int) []byte {+ value := make([]byte, size)+ // crypto/rand.Read never fails; it panics if the operating system source does.+ _, _ = rand.Read(value)+ return value+}++// MaxViewersPerRoom is the readonly RoomStore field of the same name.+func (s *Store) MaxViewersPerRoom() int { return s.maxViewersPerRoom }++// Size is the `size` getter.+func (s *Store) Size() int { return s.rooms.Len() }++// Close closes the database.+func (s *Store) Close() error {+ if s.database == nil {+ return nil+ }+ return s.database.Close()+}++// Initialize recovers the stable authority. It is a no-op without a database.+func (s *Store) Initialize() error {+ if s.initialized {+ return nil+ }+ if s.database == nil {+ s.initialized = true+ return nil+ }+ if err := s.restore(s.now()); err != nil {+ s.rooms.Clear()+ _ = s.database.Close()+ return err+ }+ s.initialized = true+ return nil+}++func (s *Store) restore(startupNowMs int64) error {+ lease, err := s.leaseDeadline(startupNowMs)+ if err != nil {+ return err+ }+ storedRooms, err := s.database.Initialize(startupNowMs, lease)+ if err != nil {+ return err+ }+ if len(storedRooms) > s.maxRooms {+ return errors.New("Room database exceeds the configured room limit")+ }+ roomIDs := make(map[string]struct{}, len(storedRooms))+ for _, stored := range storedRooms {+ roomIDs[stored.RoomID] = struct{}{}+ }+ if len(roomIDs) != len(storedRooms) {+ return errors.New("Room database contains duplicate room IDs")+ }+ for _, stored := range storedRooms {+ s.rooms.Set(stored.RoomID, &Room{+ roomID: stored.RoomID,+ hostTokenDigest: bytes.Clone(stored.HostTokenDigest),+ viewerGrantDigest: bytes.Clone(stored.ViewerGrantDigest),+ viewerPasswordMaterial: bytes.Clone(stored.ViewerPasswordMaterial),+ viewerAuthorizationGeneration: stored.ViewerAuthorizationGeneration,+ codeEntryPolicy: stored.CodeEntryPolicy,+ sharingActive: false,+ leaseExpiresAtMs: stored.LeaseExpiresAtMs,+ })+ }+ available := s.freeRoomCodes[:0]+ for _, code := range s.freeRoomCodes {+ if _, taken := roomIDs[code]; !taken {+ available = append(available, code)+ }+ }+ s.freeRoomCodes = available+ return nil+}++// BeginCreateRoom runs the part of createRoom that precedes the password+// derivation: the room limit and the lease deadline, which the TypeScript took+// from the clock before awaiting the KDF. Pass the deadline to CreateRoom.+func (s *Store) BeginCreateRoom() (leaseExpiresAtMs int64, err error) {+ if err := s.ensureInitialized(); err != nil {+ return 0, err+ }+ if s.rooms.Len() >= s.maxRooms {+ return 0, codeError(CodeRoomLimit)+ }+ return s.leaseDeadline(s.now())+}++// CreateRoom is the commit half of createRoom. material and derived are the+// results of DeriveViewerPasswordMaterial (both zero when no password was+// given) and leaseExpiresAtMs comes from BeginCreateRoom.+func (s *Store) CreateRoom(+ policy protocol.CodeEntryPolicy,+ material []byte,+ derived error,+ preferredRoomID string,+ leaseExpiresAtMs int64,+) (CreatedRoom, error) {+ // createViewerPasswordMaterial threw before any of the checks below.+ if derived != nil && !isGateOutcome(derived) {+ return CreatedRoom{}, derived+ }+ if err := s.ensureInitialized(); err != nil {+ return CreatedRoom{}, err+ }+ if s.rooms.Len() >= s.maxRooms {+ return CreatedRoom{}, codeError(CodeRoomLimit)+ }+ if hasCode(derived, CodeRoomBusy) {+ return CreatedRoom{}, codeError(CodeRoomBusy)+ }+ if errors.Is(derived, errDerivationCancelled) {+ return CreatedRoom{}, errors.New("Room creation password derivation was cancelled")+ }+ roomID, err := s.takeRoomCode(preferredRoomID)+ if err != nil {+ return CreatedRoom{}, err+ }+ room, created, err := s.newRoom(roomID, policy, material, leaseExpiresAtMs)+ if err == nil {+ err = s.writeDatabase(func() error { return s.database.InsertRoom(storedRoomAuthority(room)) })+ }+ if err != nil {+ s.releaseRoomCode(roomID)+ return CreatedRoom{}, err+ }+ s.rooms.Set(roomID, room)+ return created, nil+}++// HostManagedRoom is getHostManagedRoom: the room the exact Host token owns.+// It is the pre-KDF half of replaceRoom and setViewerPassword.+func (s *Store) HostManagedRoom(roomID, hostToken string) (*Room, error) {+ if err := s.ensureInitialized(); err != nil {+ return nil, err+ }+ return s.getHostManagedRoom(roomID, hostToken)+}++// HostStillOwnsRoom is the mayStart closure replaceRoom and setViewerPassword+// hand to the KDF gate: the room must still be the same object and the token+// must still own it. Call it with the lock held.+func (s *Store) HostStillOwnsRoom(roomID, hostToken string, current *Room) bool {+ room, ok := s.rooms.Get(roomID)+ return ok && room == current && verifyDigest(hostToken, room.hostTokenDigest)+}++// ReplaceRoom is the commit half of replaceRoom. current is the room+// HostManagedRoom returned before the derivation.+func (s *Store) ReplaceRoom(+ roomID, hostToken string,+ policy protocol.CodeEntryPolicy,+ material []byte,+ derived error,+ current *Room,+) (ReplacedRoom, error) {+ // createViewerPasswordMaterial threw before the second getHostManagedRoom.+ if derived != nil && !isGateOutcome(derived) {+ return ReplacedRoom{}, derived+ }+ if err := s.ensureInitialized(); err != nil {+ return ReplacedRoom{}, err+ }+ owned, err := s.getHostManagedRoom(roomID, hostToken)+ if err != nil {+ return ReplacedRoom{}, err+ }+ if owned != current || errors.Is(derived, errDerivationCancelled) {+ return ReplacedRoom{}, codeError(CodeRoomAccessDenied)+ }+ if hasCode(derived, CodeRoomBusy) {+ return ReplacedRoom{}, codeError(CodeRoomBusy)+ }++ replacementRoomID, err := s.takeRoomCode("")+ if err != nil {+ return ReplacedRoom{}, err+ }+ replaced, err := s.replaceRoom(roomID, replacementRoomID, policy, material, current)+ if err != nil {+ s.releaseRoomCode(replacementRoomID)+ return ReplacedRoom{}, err+ }+ return replaced, nil+}++func (s *Store) replaceRoom(+ roomID, replacementRoomID string,+ policy protocol.CodeEntryPolicy,+ material []byte,+ current *Room,+) (ReplacedRoom, error) {+ leaseExpiresAtMs, err := s.leaseDeadline(s.now())+ if err != nil {+ return ReplacedRoom{}, err+ }+ room, created, err := s.newRoom(replacementRoomID, policy, material, leaseExpiresAtMs)+ if err != nil {+ return ReplacedRoom{}, err+ }+ err = s.writeDatabase(func() error {+ return s.database.ReplaceRoom(roomID, current.hostTokenDigest, storedRoomAuthority(room))+ })+ if err != nil {+ return ReplacedRoom{}, err+ }+ closed := ClosedRoom{RoomID: roomID, SessionIDs: connectedSessionIDs(current)}+ s.rooms.Delete(roomID)+ s.rooms.Set(replacementRoomID, room)+ s.releaseRoomCode(roomID)+ return ReplacedRoom{Created: created, Closed: closed}, nil+}++// SetViewerPassword is the commit half of setViewerPassword; it reports whether+// a password is now set. current is the room HostManagedRoom returned before+// the derivation.+func (s *Store) SetViewerPassword(+ roomID, hostToken string,+ material []byte,+ derived error,+ current *Room,+) (bool, error) {+ // createViewerPasswordMaterial threw before the second getHostManagedRoom.+ if derived != nil && !isGateOutcome(derived) {+ return false, derived+ }+ if err := s.ensureInitialized(); err != nil {+ return false, err+ }+ currentRoom, err := s.getHostManagedRoom(roomID, hostToken)+ if err != nil {+ return false, err+ }+ if currentRoom != current || errors.Is(derived, errDerivationCancelled) {+ return false, codeError(CodeRoomAccessDenied)+ }+ if hasCode(derived, CodeRoomBusy) {+ return false, codeError(CodeRoomBusy)+ }+ err = s.writeDatabase(func() error {+ return s.database.SetViewerPassword(roomID, currentRoom.hostTokenDigest, material)+ })+ if err != nil {+ return false, err+ }+ currentRoom.viewerPasswordMaterial = material+ return material != nil, nil+}++// SetCodeEntryPolicy is setCodeEntryPolicy.+func (s *Store) SetCodeEntryPolicy(+ roomID string,+ policy protocol.CodeEntryPolicy,+ hostToken string,+) (CodeEntryUpdate, error) {+ if err := s.ensureInitialized(); err != nil {+ return CodeEntryUpdate{}, err+ }+ room, err := s.getHostManagedRoom(roomID, hostToken)+ if err != nil {+ return CodeEntryUpdate{}, err+ }+ err = s.writeDatabase(func() error {+ return s.database.SetCodeEntryPolicy(roomID, room.hostTokenDigest, policy)+ })+ if err != nil {+ return CodeEntryUpdate{}, err+ }+ room.codeEntryPolicy = policy+ return CodeEntryUpdate{+ CodeEntryPolicy: policy,+ ViewerPasswordEnabled: room.viewerPasswordMaterial != nil,+ }, nil+}++// SetViewerGrant is setViewerGrant; action is "rotate" or "revoke".+func (s *Store) SetViewerGrant(+ roomID, action, hostToken string,+) (ViewerGrantUpdate, error) {+ if err := s.ensureInitialized(); err != nil {+ return ViewerGrantUpdate{}, err+ }+ room, err := s.getHostManagedRoom(roomID, hostToken)+ if err != nil {+ return ViewerGrantUpdate{}, err+ }+ previousGeneration := room.viewerAuthorizationGeneration+ viewerGrant := ""+ if action == "rotate" {+ if viewerGrant, err = s.createViewerGrant(); err != nil {+ return ViewerGrantUpdate{}, err+ }+ }++ var revokedViewers []RevokedViewer+ for _, viewer := range room.viewers.Values() {+ if viewer.admittedBy == admittedByGrant {+ revokedViewers = append(revokedViewers, RevokedViewer{+ PeerID: viewer.peerID,+ SessionID: viewer.sessionID,+ })+ }+ }+ var viewerGrantDigest []byte+ if viewerGrant != "" {+ viewerGrantDigest = digest(viewerGrant)+ } else {+ if viewerGrantDigest, err = s.randomDigest(); err != nil {+ return ViewerGrantUpdate{}, err+ }+ }+ generation, err := s.newAuthorizationGeneration()+ if err != nil {+ return ViewerGrantUpdate{}, err+ }+ err = s.writeDatabase(func() error {+ return s.database.SetViewerGrant(+ roomID, room.hostTokenDigest, viewerGrantDigest, generation)+ })+ if err != nil {+ return ViewerGrantUpdate{}, err+ }+ room.viewerGrantDigest = viewerGrantDigest+ room.viewerAuthorizationGeneration = generation+ // ordering: delete during iteration, which a JS Map allows.+ for clientID, viewer := range room.viewers.All() {+ if viewer.admittedBy == admittedByGrant {+ room.viewers.Delete(clientID)+ }+ }+ return ViewerGrantUpdate{+ ViewerGrant: viewerGrant,+ ViewerAuthorizationGeneration: room.viewerAuthorizationGeneration,+ PreviousViewerAuthorizationGeneration: previousGeneration,+ RevokedViewers: revokedViewers,+ }, nil+}++// ConnectParticipant is connectParticipant.+func (s *Store) ConnectParticipant(input ConnectParticipantInput) (ConnectedParticipant, error) {+ if err := s.ensureInitialized(); err != nil {+ return ConnectedParticipant{}, err+ }+ room, err := s.getAvailableRoom(input.RoomID)+ if err != nil {+ if input.Role == protocol.RoleViewer && input.ViewerGrant == "" &&+ (hasCode(err, CodeInvalidToken) || hasCode(err, CodeRoomExpired)) {+ return ConnectedParticipant{}, codeError(CodeRoomNotFound)+ }+ return ConnectedParticipant{}, err+ }+ if input.Role == protocol.RoleHost {+ if !verifyDigest(input.Token, room.hostTokenDigest) {+ return ConnectedParticipant{}, codeError(CodeInvalidToken)+ }+ return s.connectHost(room, input)+ }++ if input.ViewerGrant != "" {+ if !viewerGrantIsValid(room, input.ViewerGrant) {+ return ConnectedParticipant{}, codeError(CodeInvalidToken)+ }+ return s.connectViewer(room, input.ClientID, input.SessionID, admittedByGrant)+ }+ if room.codeEntryPolicy != protocol.CodeEntryOpen {+ return ConnectedParticipant{}, codeError(CodeInvalidToken)+ }+ return s.connectViewer(room, input.ClientID, input.SessionID, admittedByCode)+}++// ViewerGrantMayEnter is viewerGrantMayEnter.+func (s *Store) ViewerGrantMayEnter(roomID, grant string) (bool, error) {+ if err := s.ensureInitialized(); err != nil {+ return false, err+ }+ room, err := s.getAvailableRoom(roomID)+ if err != nil {+ var roomError *Error+ if errors.As(err, &roomError) {+ return false, nil+ }+ return false, err+ }+ return viewerGrantIsValid(room, grant), nil+}++// ViewerPasswordChallenge is the locked first half of connectViewerWithPassword:+// it returns the salt to derive against, a copy of the material to compare with+// and the room reference to re-check afterwards. A missing room, an expired+// room and a room without a private password all answer with the same 48 zero+// bytes so the derivation cost does not reveal which. The only error is the+// `ensureInitialized()` the TypeScript ran before the password check.+func (s *Store) ViewerPasswordChallenge(+ roomID string,+) (salt, expectedMaterial []byte, room *Room, err error) {+ if err := s.ensureInitialized(); err != nil {+ return nil, nil, nil, err+ }+ found, err := s.getAvailableRoom(roomID)+ if err != nil {+ found = nil+ }+ expectedMaterial = make([]byte, viewerPasswordMaterialBytes)+ if found != nil && found.codeEntryPolicy == protocol.CodeEntryPrivate &&+ found.viewerPasswordMaterial != nil {+ copy(expectedMaterial, found.viewerPasswordMaterial)+ }+ return expectedMaterial[:viewerPasswordSaltBytes], expectedMaterial, found, nil+}++// ConnectViewerWithPassword is the commit half of connectViewerWithPassword.+// derived is the DeriveViewerPassword result; expectedMaterial and room come+// from ViewerPasswordChallenge; mayConnect is evaluated with the lock held.+func (s *Store) ConnectViewerWithPassword(+ input ConnectViewerWithPasswordInput,+ derived, expectedMaterial []byte,+ room *Room,+ mayConnect func() bool,+) (ConnectedParticipant, error) {+ if err := s.ensureInitialized(); err != nil {+ return ConnectedParticipant{}, err+ }+ matches := subtle.ConstantTimeCompare(+ derived, expectedMaterial[viewerPasswordSaltBytes:]) == 1++ currentRoom, err := s.getAvailableRoom(input.RoomID)+ if err != nil {+ var roomError *Error+ if errors.As(err, &roomError) {+ return ConnectedParticipant{}, codeError(CodeRoomNotFound)+ }+ return ConnectedParticipant{}, err+ }+ if room == nil || currentRoom != room ||+ currentRoom.codeEntryPolicy != protocol.CodeEntryPrivate ||+ currentRoom.viewerPasswordMaterial == nil ||+ !matches ||+ subtle.ConstantTimeCompare(currentRoom.viewerPasswordMaterial, expectedMaterial) != 1 ||+ !mayConnect() {+ return ConnectedParticipant{}, codeError(CodeInvalidToken)+ }+ connected, err := s.connectViewer(+ currentRoom, input.ClientID, input.SessionID, admittedByCode)+ if hasCode(err, CodeRoomFull) {+ return ConnectedParticipant{}, codeError(CodeInvalidToken)+ }+ return connected, err+}++// DisconnectParticipant is disconnectParticipant; it returns nil where the+// TypeScript returned undefined.+func (s *Store) DisconnectParticipant(+ roomID, peerID, sessionID string,+) (*DisconnectedParticipant, error) {+ if err := s.ensureInitialized(); err != nil {+ return nil, err+ }+ room, ok := s.rooms.Get(roomID)+ if !ok {+ return nil, nil+ }++ if room.host != nil && room.host.peerID == peerID {+ if room.host.sessionID != sessionID {+ return nil, nil+ }+ leaseExpiresAtMs, err := s.leaseDeadline(s.now())+ if err != nil {+ return nil, err+ }+ err = s.writeDatabase(func() error {+ return s.database.SetLeaseDeadline(roomID, room.hostTokenDigest, &leaseExpiresAtMs)+ })+ if err != nil {+ return nil, err+ }+ room.host.sessionID = ""+ room.sharingActive = false+ room.leaseExpiresAtMs = &leaseExpiresAtMs+ return &DisconnectedParticipant{+ RoomID: roomID, Role: protocol.RoleHost, PeerID: peerID}, nil+ }++ viewer := findViewerByPeerID(room, peerID)+ if viewer == nil || viewer.sessionID != sessionID {+ return nil, nil+ }+ viewer.sessionID = ""+ return &DisconnectedParticipant{+ RoomID: roomID, Role: protocol.RoleViewer, PeerID: peerID}, nil+}++// RemoveDisconnectedViewer is removeDisconnectedViewer.+func (s *Store) RemoveDisconnectedViewer(roomID, peerID string) bool {+ room, ok := s.rooms.Get(roomID)+ if !ok {+ return false+ }+ viewer := findViewerByPeerID(room, peerID)+ if viewer == nil || viewer.sessionID != "" {+ return false+ }+ return room.viewers.Delete(viewer.clientID)+}++// GetConnectedHost is getConnectedHost.+func (s *Store) GetConnectedHost(roomID string) (ConnectedPeer, bool) {+ room, ok := s.rooms.Get(roomID)+ if !ok || room.host == nil || room.host.sessionID == "" {+ return ConnectedPeer{}, false+ }+ return ConnectedPeer{PeerID: room.host.peerID, SessionID: room.host.sessionID}, true+}++// GetConnectedViewer is getConnectedViewer.+func (s *Store) GetConnectedViewer(roomID, peerID string) (ConnectedPeer, bool) {+ room, ok := s.rooms.Get(roomID)+ if !ok {+ return ConnectedPeer{}, false+ }+ viewer := findViewerByPeerID(room, peerID)+ if viewer == nil || viewer.sessionID == "" {+ return ConnectedPeer{}, false+ }+ return ConnectedPeer{PeerID: peerID, SessionID: viewer.sessionID}, true+}++// GetViewerPeerIDs is getViewerPeerIds, in viewer insertion order.+func (s *Store) GetViewerPeerIDs(roomID string) []string {+ room, ok := s.rooms.Get(roomID)+ if !ok {+ return nil+ }+ peerIDs := make([]string, 0, room.viewers.Len())+ for _, viewer := range room.viewers.Values() {+ peerIDs = append(peerIDs, viewer.peerID)+ }+ return peerIDs+}++// GetConnectedViewers is getConnectedViewers, in viewer insertion order.+func (s *Store) GetConnectedViewers(roomID string) []ConnectedPeer {+ room, ok := s.rooms.Get(roomID)+ if !ok {+ return nil+ }+ var connected []ConnectedPeer+ for _, viewer := range room.viewers.Values() {+ if viewer.sessionID != "" {+ connected = append(connected, ConnectedPeer{+ PeerID: viewer.peerID, SessionID: viewer.sessionID})+ }+ }+ return connected+}++// AbandonRoom is abandonRoom; it returns nil where the TypeScript returned+// undefined.+func (s *Store) AbandonRoom(roomID string) (*ClosedRoom, error) {+ if err := s.ensureInitialized(); err != nil {+ return nil, err+ }+ room, ok := s.rooms.Get(roomID)+ if !ok {+ return nil, nil+ }+ sessionIDs := connectedSessionIDs(room)+ err := s.writeDatabase(func() error {+ return s.database.DeleteRoom(roomID, room.hostTokenDigest)+ })+ if err != nil {+ return nil, err+ }+ s.rooms.Delete(roomID)+ s.releaseRoomCode(roomID)+ return &ClosedRoom{RoomID: roomID, SessionIDs: sessionIDs}, nil+}++// AbandonAllRooms is abandonAllRooms, in room insertion order.+func (s *Store) AbandonAllRooms() ([]ClosedRoom, error) {+ if err := s.ensureInitialized(); err != nil {+ return nil, err+ }+ var closedRooms []ClosedRoom+ for _, roomID := range s.rooms.Keys() {+ closed, err := s.AbandonRoom(roomID)+ if err != nil {+ return nil, err+ }+ if closed != nil {+ closedRooms = append(closedRooms, *closed)+ }+ }+ return closedRooms, nil+}++// ExpireRooms is expireRooms, in room insertion order. The TypeScript defaulted+// nowMs to the injected clock; every caller passed it explicitly.+func (s *Store) ExpireRooms(nowMs int64) ([]ClosedRoom, error) {+ if err := s.ensureInitialized(); err != nil {+ return nil, err+ }+ var expiredIDs []string+ var identities []RoomIdentity+ var expired []ClosedRoom+ for roomID, room := range s.rooms.All() {+ if !roomIsExpired(room, nowMs) {+ continue+ }+ expiredIDs = append(expiredIDs, roomID)+ identities = append(identities, RoomIdentity{+ RoomID: roomID, HostTokenDigest: room.hostTokenDigest})+ expired = append(expired, ClosedRoom{+ RoomID: roomID, SessionIDs: connectedSessionIDs(room)})+ }+ if err := s.writeDatabase(func() error { return s.database.DeleteRooms(identities) }); err != nil {+ return nil, err+ }+ for _, roomID := range expiredIDs {+ s.rooms.Delete(roomID)+ s.releaseRoomCode(roomID)+ }+ return expired, nil+}++func (s *Store) connectHost(+ room *Room, input ConnectParticipantInput,+) (ConnectedParticipant, error) {+ current := room.host+ if current != nil && current.sessionID != "" && current.clientID != input.ClientID {+ return ConnectedParticipant{}, codeError(CodeHostAlreadyConnected)+ }++ joining := current+ if current == nil || current.clientID != input.ClientID {+ peerID, err := s.newPeerID(room)+ if err != nil {+ return ConnectedParticipant{}, err+ }+ joining = &participant{+ clientID: input.ClientID, peerID: peerID, admittedBy: admittedByCode}+ }+ replacedSessionID := joining.sessionID+ err := s.writeDatabase(func() error {+ return s.database.SetLeaseDeadline(room.roomID, room.hostTokenDigest, nil)+ })+ if err != nil {+ return ConnectedParticipant{}, err+ }+ joining.sessionID = input.SessionID+ room.host = joining+ room.sharingActive = true+ room.leaseExpiresAtMs = nil++ return connectedParticipant(+ room, joining.peerID, protocol.RoleHost, replacedSessionID, input.SessionID), nil+}++func (s *Store) connectViewer(+ room *Room, clientID, sessionID, admittedBy string,+) (ConnectedParticipant, error) {+ joining, ok := room.viewers.Get(clientID)+ if !ok && room.viewers.Len() >= s.maxViewersPerRoom {+ return ConnectedParticipant{}, codeError(CodeRoomFull)+ }+ if !ok {+ peerID, err := s.newPeerID(room)+ if err != nil {+ return ConnectedParticipant{}, err+ }+ joining = &participant{clientID: clientID, peerID: peerID, admittedBy: admittedBy}+ }+ replacedSessionID := joining.sessionID+ joining.sessionID = sessionID+ joining.admittedBy = admittedBy+ // ordering: Map.set keeps the position of an existing key.+ room.viewers.Set(clientID, joining)+ return connectedParticipant(+ room, joining.peerID, protocol.RoleViewer, replacedSessionID, sessionID), nil+}++func connectedParticipant(+ room *Room, peerID string, role protocol.Role, replacedSessionID, sessionID string,+) ConnectedParticipant {+ if replacedSessionID == sessionID {+ replacedSessionID = ""+ }+ return ConnectedParticipant{+ RoomID: room.roomID,+ Role: role,+ PeerID: peerID,+ ExpiresAt: formatExpiresAt(room.leaseExpiresAtMs),+ HostOnline: room.host != nil && room.host.sessionID != "",+ ReplacedSessionID: replacedSessionID,+ CodeEntryPolicy: room.codeEntryPolicy,+ ViewerPasswordEnabled: room.viewerPasswordMaterial != nil,+ ViewerAuthorizationGeneration: room.viewerAuthorizationGeneration,+ }+}++func (s *Store) getAvailableRoom(roomID string) (*Room, error) {+ room, ok := s.rooms.Get(roomID)+ if !ok {+ return nil, codeError(CodeInvalidToken)+ }+ if roomIsExpired(room, s.now()) {+ return nil, codeError(CodeRoomExpired)+ }+ return room, nil+}++func (s *Store) getHostManagedRoom(roomID, hostToken string) (*Room, error) {+ room, err := s.getAvailableRoom(roomID)+ if err != nil {+ return nil, err+ }+ if !verifyDigest(hostToken, room.hostTokenDigest) {+ return nil, codeError(CodeInvalidToken)+ }+ return room, nil+}++func (s *Store) newPeerID(room *Room) (string, error) {+ return s.uniqueID(16, func(candidate string) bool {+ if room.host != nil && room.host.peerID == candidate {+ return true+ }+ for _, viewer := range room.viewers.Values() {+ if viewer.peerID == candidate {+ return true+ }+ }+ return false+ })+}++func (s *Store) takeRoomCode(preferredRoomID string) (string, error) {+ if len(s.freeRoomCodes) == 0 {+ return "", codeError(CodeRoomLimit)+ }+ if preferredRoomID != "" {+ if index := slices.Index(s.freeRoomCodes, preferredRoomID); index >= 0 {+ return s.takeRoomCodeAt(index), nil+ }+ }+ index, err := uniformIndex(len(s.freeRoomCodes), s.random)+ if err != nil {+ return "", err+ }+ return s.takeRoomCodeAt(index), nil+}++// uniformIndex draws a uniform index below count from 8 random bytes, rejecting+// the values above the largest multiple of count. The TypeScript computed the+// limit in BigInt as 2^64 - 2^64 % count; (MaxUint64 % count + 1) % count is+// the same remainder without the uint64 wrap at a power-of-two count (D11).+func uniformIndex(count int, random func(size int) []byte) (int, error) {+ span := uint64(count)+ remainder := (math.MaxUint64%span + 1) % span+ for attempt := 0; attempt < 16; attempt++ {+ value := random(8)+ if len(value) != 8 {+ return 0, errors.New("Room code random source must return 8 bytes")+ }+ if remainder != 0 &&+ binary.BigEndian.Uint64(value) >= math.MaxUint64-remainder+1 {+ continue+ }+ return int(binary.BigEndian.Uint64(value) % span), nil+ }+ return 0, errors.New("Unable to select a room code uniformly")+}++// takeRoomCodeAt removes the code at index by swapping the last code into it.+func (s *Store) takeRoomCodeAt(index int) string {+ roomID := s.freeRoomCodes[index]+ last := len(s.freeRoomCodes) - 1+ lastRoomID := s.freeRoomCodes[last]+ s.freeRoomCodes = s.freeRoomCodes[:last]+ if index < last {+ s.freeRoomCodes[index] = lastRoomID+ }+ return roomID+}++func (s *Store) releaseRoomCode(roomID string) {+ s.freeRoomCodes = append(s.freeRoomCodes, roomID)+}++func (s *Store) uniqueID(size int, exists func(candidate string) bool) (string, error) {+ for attempt := 0; attempt < 8; attempt++ {+ value := s.random(size)+ if len(value) != size {+ return "", fmt.Errorf("Identifier random source must return %d bytes", size)+ }+ candidate := base64.RawURLEncoding.EncodeToString(value)+ if !exists(candidate) {+ return candidate, nil+ }+ }+ return "", errors.New("Unable to allocate a unique identifier")+}++func viewerGrantIsValid(room *Room, grant string) bool {+ if grant == "" || !protocol.ValidViewerGrant(grant) {+ return false+ }+ return verifyDigest(grant, room.viewerGrantDigest)+}++func (s *Store) createViewerGrant() (string, error) {+ secret := s.random(16)+ if len(secret) != 16 {+ return "", errors.New("Viewer grant random source must return 16 bytes")+ }+ return base64.RawURLEncoding.EncodeToString(secret), nil+}++func (s *Store) newRoom(+ roomID string,+ policy protocol.CodeEntryPolicy,+ material []byte,+ leaseExpiresAtMs int64,+) (*Room, CreatedRoom, error) {+ hostTokenBytes := s.random(32)+ if len(hostTokenBytes) != 32 {+ return nil, CreatedRoom{}, errors.New("Host token random source must return 32 bytes")+ }+ hostToken := base64.RawURLEncoding.EncodeToString(hostTokenBytes)+ viewerGrant, err := s.createViewerGrant()+ if err != nil {+ return nil, CreatedRoom{}, err+ }+ generation, err := s.newAuthorizationGeneration()+ if err != nil {+ return nil, CreatedRoom{}, err+ }+ room := &Room{+ roomID: roomID,+ hostTokenDigest: digest(hostToken),+ viewerGrantDigest: digest(viewerGrant),+ viewerPasswordMaterial: material,+ viewerAuthorizationGeneration: generation,+ codeEntryPolicy: policy,+ sharingActive: false,+ leaseExpiresAtMs: &leaseExpiresAtMs,+ }+ return room, CreatedRoom{+ RoomID: roomID,+ HostToken: hostToken,+ CodeEntryPolicy: policy,+ ViewerGrant: viewerGrant,+ ExpiresAt: formatExpiresAt(&leaseExpiresAtMs),+ }, nil+}++func (s *Store) randomDigest() ([]byte, error) {+ value := s.random(32)+ if len(value) != 32 {+ return nil, errors.New("Viewer grant random source must return 32 bytes")+ }+ return bytes.Clone(value), nil+}++func (s *Store) newAuthorizationGeneration() (string, error) {+ value := s.random(16)+ if len(value) != 16 {+ return "", errors.New("Authorization generation random source must return 16 bytes")+ }+ return base64.RawURLEncoding.EncodeToString(value), nil+}++func (s *Store) leaseDeadline(nowMs int64) (int64, error) {+ deadline := nowMs + s.leaseMs+ if deadline <= nowMs || deadline > protocol.MaxSafeInteger ||+ deadline < -protocol.MaxSafeInteger {+ return 0, errors.New("Room lease deadline exceeds the supported time range")+ }+ return deadline, nil+}++func (s *Store) ensureInitialized() error {+ if !s.initialized {+ return errors.New("RoomStore stable authority is not initialized")+ }+ return nil+}++// writeDatabase runs a stable-authority write when a database is configured,+// which is the TypeScript `this.options.database?.write(...)`.+func (s *Store) writeDatabase(write func() error) error {+ if s.database == nil {+ return nil+ }+ return write()+}++func storedRoomAuthority(room *Room) StoredRoomAuthority {+ return StoredRoomAuthority{+ RoomID: room.roomID,+ HostTokenDigest: room.hostTokenDigest,+ ViewerGrantDigest: room.viewerGrantDigest,+ ViewerAuthorizationGeneration: room.viewerAuthorizationGeneration,+ CodeEntryPolicy: room.codeEntryPolicy,+ ViewerPasswordMaterial: room.viewerPasswordMaterial,+ LeaseExpiresAtMs: room.leaseExpiresAtMs,+ }+}++func roomIsExpired(room *Room, nowMs int64) bool {+ return !room.sharingActive && room.leaseExpiresAtMs != nil &&+ *room.leaseExpiresAtMs <= nowMs+}++func formatExpiresAt(expiresAtMs *int64) *string {+ if expiresAtMs == nil {+ return nil+ }+ value := time.UnixMilli(*expiresAtMs).UTC().Format("2006-01-02T15:04:05.000Z")+ return &value+}++func findViewerByPeerID(room *Room, peerID string) *participant {+ for _, viewer := range room.viewers.Values() {+ if viewer.peerID == peerID {+ return viewer+ }+ }+ return nil+}++func connectedSessionIDs(room *Room) []string {+ var sessionIDs []string+ if room.host != nil && room.host.sessionID != "" {+ sessionIDs = append(sessionIDs, room.host.sessionID)+ }+ for _, viewer := range room.viewers.Values() {+ if viewer.sessionID != "" {+ sessionIDs = append(sessionIDs, viewer.sessionID)+ }+ }+ return sessionIDs+}++func digest(value string) []byte {+ sum := sha256.Sum256([]byte(value))+ return sum[:]+}++func verifyDigest(value string, expectedDigest []byte) bool {+ return subtle.ConstantTimeCompare(digest(value), expectedDigest) == 1+}diff --git a/internal/server/room/store_test.go b/internal/server/room/store_test.gonew file mode 100644index 00000000..78caa463--- /dev/null+++ b/internal/server/room/store_test.go@@ -0,0 +1,1045 @@+package room++import (+ "bytes"+ "errors"+ "regexp"+ "strconv"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// The scenarios below are ported from tests/room-store.test.ts.++type clock struct{ nowMs int64 }++func newStore(t *testing.T, options Options) (*Store, *clock) {+ t.Helper()+ testClock := &clock{}+ if options.LeaseMs == 0 {+ options.LeaseMs = 1_000+ }+ if options.MaxRooms == 0 {+ options.MaxRooms = 2+ }+ if options.MaxViewersPerRoom == 0 {+ options.MaxViewersPerRoom = 2+ }+ options.Now = func() int64 { return testClock.nowMs }+ store, err := New(options)+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ if err := store.Initialize(); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ t.Cleanup(func() { _ = store.Close() })+ return store, testClock+}++func constantRandom(value func(size int) byte) func(size int) []byte {+ return func(size int) []byte { return bytes.Repeat([]byte{value(size)}, size) }+}++// tryCreateRoom runs the locked/unlocked/locked createRoom sequence the package+// comment documents.+func tryCreateRoom(+ store *Store, policy protocol.CodeEntryPolicy, password, preferredRoomID string,+) (CreatedRoom, error) {+ lease, err := store.BeginCreateRoom()+ if err != nil {+ return CreatedRoom{}, err+ }+ var material []byte+ var derived error+ if password != "" {+ material, derived = store.DeriveViewerPasswordMaterial(password, nil)+ }+ return store.CreateRoom(policy, material, derived, preferredRoomID, lease)+}++func createRoom(+ t *testing.T, store *Store, policy protocol.CodeEntryPolicy, password, preferredRoomID string,+) CreatedRoom {+ t.Helper()+ created, err := tryCreateRoom(store, policy, password, preferredRoomID)+ if err != nil {+ t.Fatalf("CreateRoom: %v", err)+ }+ return created+}++func tryReplaceRoom(+ store *Store, roomID, hostToken string, policy protocol.CodeEntryPolicy, password string,+) (ReplacedRoom, error) {+ current, err := store.HostManagedRoom(roomID, hostToken)+ if err != nil {+ return ReplacedRoom{}, err+ }+ var material []byte+ var derived error+ if password != "" {+ material, derived = store.DeriveViewerPasswordMaterial(password, func() bool {+ return store.HostStillOwnsRoom(roomID, hostToken, current)+ })+ }+ return store.ReplaceRoom(roomID, hostToken, policy, material, derived, current)+}++func trySetViewerPassword(store *Store, roomID, password, hostToken string) (bool, error) {+ current, err := store.HostManagedRoom(roomID, hostToken)+ if err != nil {+ return false, err+ }+ var material []byte+ var derived error+ if password != "" {+ material, derived = store.DeriveViewerPasswordMaterial(password, func() bool {+ return store.HostStillOwnsRoom(roomID, hostToken, current)+ })+ }+ return store.SetViewerPassword(roomID, hostToken, material, derived, current)+}++func tryConnectViewerWithPassword(+ store *Store, input ConnectViewerWithPasswordInput, mayConnect func() bool,+) (ConnectedParticipant, error) {+ if mayConnect == nil {+ mayConnect = func() bool { return true }+ }+ salt, expectedMaterial, room, err := store.ViewerPasswordChallenge(input.RoomID)+ if err != nil {+ return ConnectedParticipant{}, err+ }+ derived, err := store.DeriveViewerPassword(input.Password, salt, mayConnect)+ if err != nil {+ return ConnectedParticipant{}, err+ }+ return store.ConnectViewerWithPassword(input, derived, expectedMaterial, room, mayConnect)+}++func hostInput(roomID, hostToken string, sessionID ...string) ConnectParticipantInput {+ session := "host-session"+ if len(sessionID) > 0 {+ session = sessionID[0]+ }+ return ConnectParticipantInput{+ RoomID: roomID,+ Role: protocol.RoleHost,+ Token: hostToken,+ ClientID: "host-client",+ SessionID: session,+ }+}++func viewerInput(roomID, sessionID, viewerGrant string) ConnectParticipantInput {+ return ConnectParticipantInput{+ RoomID: roomID,+ Role: protocol.RoleViewer,+ ViewerGrant: viewerGrant,+ ClientID: "viewer-" + sessionID,+ SessionID: sessionID,+ }+}++func expectCode(t *testing.T, err error, code ErrorCode) {+ t.Helper()+ if !hasCode(err, code) {+ t.Fatalf("expected %s, got %v", code, err)+ }+}++func mustConnect(t *testing.T, store *Store, input ConnectParticipantInput) ConnectedParticipant {+ t.Helper()+ connected, err := store.ConnectParticipant(input)+ if err != nil {+ t.Fatalf("ConnectParticipant: %v", err)+ }+ return connected+}++var roomCodePattern = regexp.MustCompile(`^[1-9][0-9]{3}$`)+var viewerGrantPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{21}[AQgw]$`)++func TestAllocatesEveryFreeRoomCodeAndRecyclesReleases(t *testing.T) {+ store, _ := newStore(t, Options{+ MaxRooms: Capacity,+ Random: constantRandom(func(int) byte { return 0 }),+ })++ rooms := make([]CreatedRoom, 0, Capacity)+ seen := make(map[string]struct{}, Capacity)+ for index := 0; index < Capacity; index++ {+ created := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ if !roomCodePattern.MatchString(created.RoomID) {+ t.Fatalf("room code %q is not four digits", created.RoomID)+ }+ seen[created.RoomID] = struct{}{}+ rooms = append(rooms, created)+ }+ if len(seen) != Capacity {+ t.Fatalf("allocated %d distinct codes, want %d", len(seen), Capacity)+ }+ if _, err := tryCreateRoom(store, protocol.CodeEntryOpen, "", ""); !hasCode(err, CodeRoomLimit) {+ t.Fatalf("expected ROOM_LIMIT, got %v", err)+ }++ released := rooms[4_321].RoomID+ closed, err := store.AbandonRoom(released)+ if err != nil || closed == nil || closed.RoomID != released {+ t.Fatalf("AbandonRoom(%s) = %v, %v", released, closed, err)+ }+ if created := createRoom(t, store, protocol.CodeEntryOpen, "", ""); created.RoomID != released {+ t.Fatalf("recycled code = %q, want %q", created.RoomID, released)+ }+}++func TestUsesAFreePreferredCodeAndFallsBack(t *testing.T) {+ store, _ := newStore(t, Options{MaxRooms: 3})++ preferred := createRoom(t, store, protocol.CodeEntryOpen, "", "4321")+ fallback := createRoom(t, store, protocol.CodeEntryOpen, "", "4321")++ if preferred.RoomID != "4321" {+ t.Fatalf("preferred code = %q", preferred.RoomID)+ }+ if fallback.RoomID == "4321" {+ t.Fatal("fallback reused the occupied preferred code")+ }+ if closed, err := store.AbandonRoom("4321"); err != nil || closed.RoomID != "4321" {+ t.Fatalf("AbandonRoom = %v, %v", closed, err)+ }+ if again := createRoom(t, store, protocol.CodeEntryOpen, "", "4321"); again.RoomID != "4321" {+ t.Fatalf("released preferred code = %q", again.RoomID)+ }+}++func TestAbandonsEveryCurrentRoomAsOneShutdown(t *testing.T) {+ store, _ := newStore(t, Options{MaxRooms: 3})+ first := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ second := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ mustConnect(t, store, hostInput(first.RoomID, first.HostToken))++ closed, err := store.AbandonAllRooms()+ if err != nil {+ t.Fatalf("AbandonAllRooms: %v", err)+ }+ if len(closed) != 2 {+ t.Fatalf("closed %d rooms, want 2", len(closed))+ }+ // Room insertion order is contract: the JS Map iterated in creation order.+ if closed[0].RoomID != first.RoomID || closed[1].RoomID != second.RoomID {+ t.Fatalf("closed order = %q, %q", closed[0].RoomID, closed[1].RoomID)+ }+ if len(closed[0].SessionIDs) != 1 || closed[0].SessionIDs[0] != "host-session" {+ t.Fatalf("closed sessions = %v", closed[0].SessionIDs)+ }+ if len(closed[1].SessionIDs) != 0 {+ t.Fatalf("second room sessions = %v", closed[1].SessionIDs)+ }+ if store.Size() != 0 {+ t.Fatalf("size = %d, want 0", store.Size())+ }+}++func TestAtomicallyReplacesARoomWithDifferentAuthority(t *testing.T) {+ store, _ := newStore(t, Options{})+ original := createRoom(t, store, protocol.CodeEntryPrivate, "old-password", "4321")+ host := mustConnect(t, store, hostInput(original.RoomID, original.HostToken))+ mustConnect(t, store, viewerInput(original.RoomID, "viewer-session", original.ViewerGrant))++ _, err := tryReplaceRoom(+ store, original.RoomID, original.HostToken, protocol.CodeEntryPrivate, "bad password")+ expectCode(t, err, CodeInvalidToken)+ if connected, ok := store.GetConnectedHost(original.RoomID); !ok || connected.PeerID != host.PeerID {+ t.Fatalf("host lost after a rejected replacement: %v %v", connected, ok)+ }++ replacement, err := tryReplaceRoom(+ store, original.RoomID, original.HostToken, protocol.CodeEntryPrivate, "new-password")+ if err != nil {+ t.Fatalf("ReplaceRoom: %v", err)+ }+ if replacement.Created.RoomID == original.RoomID {+ t.Fatal("replacement reused the room code")+ }+ if replacement.Closed.RoomID != original.RoomID ||+ len(replacement.Closed.SessionIDs) != 2 ||+ replacement.Closed.SessionIDs[0] != "host-session" ||+ replacement.Closed.SessionIDs[1] != "viewer-session" {+ t.Fatalf("closed = %+v", replacement.Closed)+ }+ _, err = store.ConnectParticipant(hostInput(original.RoomID, original.HostToken))+ expectCode(t, err, CodeInvalidToken)+ connected := mustConnect(t, store, viewerInput(+ replacement.Created.RoomID, "new-viewer-session", replacement.Created.ViewerGrant))+ if connected.RoomID != replacement.Created.RoomID {+ t.Fatalf("viewer joined %q", connected.RoomID)+ }+ withPassword, err := tryConnectViewerWithPassword(store, ConnectViewerWithPasswordInput{+ RoomID: replacement.Created.RoomID,+ Password: "new-password",+ ClientID: "password-viewer",+ SessionID: "password-session",+ }, nil)+ if err != nil || withPassword.RoomID != replacement.Created.RoomID {+ t.Fatalf("password login after replacement: %+v %v", withPassword, err)+ }+}++func TestRejectsRoomLimitsBeyondTheCodeSpace(t *testing.T) {+ _, err := New(Options{LeaseMs: 1_000, MaxRooms: Capacity + 1, MaxViewersPerRoom: 2})+ if err == nil || err.Error() != "Room limit must be an integer between 1 and 9000" {+ t.Fatalf("New: %v", err)+ }+}++func TestKeepsActiveSharingAliveAndRenewsOnlyWithTheExactHostToken(t *testing.T) {+ store, testClock := newStore(t, Options{LeaseMs: 1_000})+ room := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ host := mustConnect(t, store, hostInput(room.RoomID, room.HostToken))++ testClock.nowMs = 2_000+ if expired, err := store.ExpireRooms(testClock.nowMs); err != nil || len(expired) != 0 {+ t.Fatalf("ExpireRooms while sharing = %v, %v", expired, err)+ }++ if _, err := store.DisconnectParticipant(room.RoomID, host.PeerID, "host-session"); err != nil {+ t.Fatalf("DisconnectParticipant: %v", err)+ }+ testClock.nowMs = 2_500+ if expired, err := store.ExpireRooms(testClock.nowMs); err != nil || len(expired) != 0 {+ t.Fatalf("ExpireRooms inside the lease = %v, %v", expired, err)+ }++ _, err := store.ConnectParticipant(hostInput(room.RoomID, "wrong-token"))+ expectCode(t, err, CodeInvalidToken)+ resumed := mustConnect(t, store, hostInput(room.RoomID, room.HostToken, "host-session-2"))+ if resumed.ExpiresAt != nil {+ t.Fatalf("resumed expiresAt = %v, want null", *resumed.ExpiresAt)+ }++ if _, err := store.DisconnectParticipant(+ room.RoomID, resumed.PeerID, "host-session-2"); err != nil {+ t.Fatalf("DisconnectParticipant: %v", err)+ }+ mustConnect(t, store, viewerInput(room.RoomID, "viewer-session", room.ViewerGrant))+ testClock.nowMs = 3_501+ expired, err := store.ExpireRooms(testClock.nowMs)+ if err != nil || len(expired) != 1 {+ t.Fatalf("ExpireRooms after the lease = %v, %v", expired, err)+ }+ _, err = store.ConnectParticipant(hostInput(room.RoomID, room.HostToken, "late-host"))+ expectCode(t, err, CodeInvalidToken)+}++func TestManagesDormantAccessWithTheExactHostTokenWithoutRenewing(t *testing.T) {+ store, testClock := newStore(t, Options{LeaseMs: 1_000})+ room := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ otherRoom := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ testClock.nowMs = 900++ _, err := trySetViewerPassword(store, room.RoomID, "room-password", "wrong-token")+ expectCode(t, err, CodeInvalidToken)+ _, err = store.SetCodeEntryPolicy(room.RoomID, protocol.CodeEntryPrivate, otherRoom.HostToken)+ expectCode(t, err, CodeInvalidToken)++ update, err := store.SetCodeEntryPolicy(+ room.RoomID, protocol.CodeEntryPrivate, room.HostToken)+ if err != nil || update.CodeEntryPolicy != protocol.CodeEntryPrivate ||+ update.ViewerPasswordEnabled {+ t.Fatalf("SetCodeEntryPolicy = %+v, %v", update, err)+ }+ if enabled, err := trySetViewerPassword(+ store, room.RoomID, "room-password", room.HostToken); err != nil || !enabled {+ t.Fatalf("SetViewerPassword = %v, %v", enabled, err)+ }+ if enabled, err := trySetViewerPassword(+ store, room.RoomID, "", room.HostToken); err != nil || enabled {+ t.Fatalf("cleared SetViewerPassword = %v, %v", enabled, err)+ }+ grant, err := store.SetViewerGrant(room.RoomID, "rotate", room.HostToken)+ if err != nil || !viewerGrantPattern.MatchString(grant.ViewerGrant) {+ t.Fatalf("SetViewerGrant = %+v, %v", grant, err)+ }+ if _, ok := store.GetConnectedHost(room.RoomID); ok {+ t.Fatal("a dormant room reported a connected host")+ }++ testClock.nowMs = 1_001+ expired, err := store.ExpireRooms(testClock.nowMs)+ if err != nil {+ t.Fatalf("ExpireRooms: %v", err)+ }+ if !slicesContainsRoom(expired, room.RoomID) {+ t.Fatalf("expired = %+v, want %q", expired, room.RoomID)+ }+}++func slicesContainsRoom(rooms []ClosedRoom, roomID string) bool {+ for _, room := range rooms {+ if room.RoomID == roomID {+ return true+ }+ }+ return false+}++func TestKeepsViewerGrantsIndependentFromCodeEntryPolicy(t *testing.T) {+ store, _ := newStore(t, Options{MaxRooms: 3})+ room := createRoom(t, store, protocol.CodeEntryPrivate, "", "")++ _, err := store.ConnectParticipant(viewerInput(room.RoomID, "code-only", ""))+ expectCode(t, err, CodeInvalidToken)+ _, err = tryConnectViewerWithPassword(store, ConnectViewerWithPasswordInput{+ RoomID: room.RoomID,+ Password: "any-password",+ ClientID: "private-code-viewer",+ SessionID: "private-code-session",+ }, nil)+ expectCode(t, err, CodeInvalidToken)+ granted := mustConnect(t, store, viewerInput(room.RoomID, "granted", room.ViewerGrant))+ if granted.Role != protocol.RoleViewer {+ t.Fatalf("role = %q", granted.Role)+ }+}++func TestKeepsTheExactViewerGrantValidForTheRoomIncarnation(t *testing.T) {+ store, testClock := newStore(t, Options{LeaseMs: 1_000})+ room := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ mustConnect(t, store, hostInput(room.RoomID, room.HostToken))++ if !viewerGrantPattern.MatchString(room.ViewerGrant) {+ t.Fatalf("viewer grant = %q", room.ViewerGrant)+ }+ testClock.nowMs = 8 * 24 * 60 * 60 * 1_000+ connected := mustConnect(t, store, viewerInput(room.RoomID, "room-lived-grant", room.ViewerGrant))+ if connected.Role != protocol.RoleViewer {+ t.Fatalf("role = %q", connected.Role)+ }+}++func TestSupportsOpenAndPasswordEnabledPrivateCodeEntry(t *testing.T) {+ store, _ := newStore(t, Options{MaxRooms: 3})+ open := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ if connected := mustConnect(t, store, viewerInput(open.RoomID, "open", "")); connected.Role !=+ protocol.RoleViewer {+ t.Fatalf("role = %q", connected.Role)+ }++ password := createRoom(t, store, protocol.CodeEntryPrivate, "room-password", "")+ _, err := store.ConnectParticipant(viewerInput(password.RoomID, "wrong", ""))+ expectCode(t, err, CodeInvalidToken)+ connected, err := tryConnectViewerWithPassword(store, ConnectViewerWithPasswordInput{+ RoomID: password.RoomID,+ Password: "room-password",+ ClientID: "password-viewer",+ SessionID: "password-session",+ }, nil)+ if err != nil || connected.Role != protocol.RoleViewer {+ t.Fatalf("password login = %+v, %v", connected, err)+ }+}++// gateState reads the KDF gate counters the way only a same-package test can.+func gateState(store *Store) (active, pending int) {+ store.gate.mu.Lock()+ defer store.gate.mu.Unlock()+ return store.gate.active, len(store.gate.waiters)+}++// withSaturatedGate holds the KDF gate at 2 running and 16 queued derivations+// for the duration of operation, which is what the vitest helper did by+// starting 18 password logins whose mayStart never returned.+func withSaturatedGate(t *testing.T, store *Store, operation func()) {+ t.Helper()+ release := make(chan struct{})+ var group sync.WaitGroup+ for index := 0; index < 18; index++ {+ group.Add(1)+ go func() {+ defer group.Done()+ _, _ = store.DeriveViewerPassword(+ "gate-password", make([]byte, viewerPasswordSaltBytes), func() bool {+ <-release+ return false+ })+ }()+ }+ defer func() {+ close(release)+ group.Wait()+ }()+ waitForSaturatedGate(t, store)+ operation()+}++func waitForSaturatedGate(t *testing.T, store *Store) {+ t.Helper()+ deadline := time.Now().Add(30 * time.Second)+ for {+ active, pending := gateState(store)+ if active == 2 && pending == 16 {+ return+ }+ if time.Now().After(deadline) {+ t.Fatalf("gate did not saturate: active=%d pending=%d", active, pending)+ }+ time.Sleep(time.Millisecond)+ }+}++func TestDoesNotCreateAPasswordlessRoomWhenTheGateIsBusy(t *testing.T) {+ store, _ := newStore(t, Options{MaxRooms: 1})++ withSaturatedGate(t, store, func() {+ _, err := tryCreateRoom(store, protocol.CodeEntryPrivate, "room-password", "4321")+ expectCode(t, err, CodeRoomBusy)+ })+ if store.Size() != 0 {+ t.Fatalf("size = %d, want 0", store.Size())+ }+ if created := createRoom(t, store, protocol.CodeEntryPrivate, "", "4321"); created.RoomID != "4321" {+ t.Fatalf("room = %q, want 4321", created.RoomID)+ }+}++func TestKeepsGateSaturationDistinctFromInvalidCredentials(t *testing.T) {+ store, _ := newStore(t, Options{})+ room := createRoom(t, store, protocol.CodeEntryPrivate, "room-password", "")++ withSaturatedGate(t, store, func() {+ _, err := tryConnectViewerWithPassword(store, ConnectViewerWithPasswordInput{+ RoomID: room.RoomID,+ Password: "room-password",+ ClientID: "busy-password-client",+ SessionID: "busy-password-session",+ }, nil)+ expectCode(t, err, CodeRoomBusy)+ })+}++func TestKeepsRoomReplacementAndPasswordUpdatesUnchangedWhenBusy(t *testing.T) {+ store, _ := newStore(t, Options{MaxRooms: 3})+ room := createRoom(t, store, protocol.CodeEntryPrivate, "old-password", "4321")++ withSaturatedGate(t, store, func() {+ _, err := tryReplaceRoom(+ store, room.RoomID, room.HostToken, protocol.CodeEntryPrivate, "replacement-password")+ expectCode(t, err, CodeRoomBusy)+ })+ if store.Size() != 1 {+ t.Fatalf("size = %d, want 1", store.Size())+ }+ if _, err := tryConnectViewerWithPassword(store, ConnectViewerWithPasswordInput{+ RoomID: room.RoomID,+ Password: "old-password",+ ClientID: "after-replacement-client",+ SessionID: "after-replacement-session",+ }, nil); err != nil {+ t.Fatalf("password login after a busy replacement: %v", err)+ }++ withSaturatedGate(t, store, func() {+ _, err := trySetViewerPassword(store, room.RoomID, "updated-password", room.HostToken)+ expectCode(t, err, CodeRoomBusy)+ })+ if _, err := tryConnectViewerWithPassword(store, ConnectViewerWithPasswordInput{+ RoomID: room.RoomID,+ Password: "old-password",+ ClientID: "after-update-client",+ SessionID: "after-update-session",+ }, nil); err != nil {+ t.Fatalf("password login after a busy update: %v", err)+ }+}++func TestBoundsPasswordDerivationsAndUsesTheSamePathForUnknownRooms(t *testing.T) {+ store, _ := newStore(t, Options{})++ var mayStartCalls atomic.Int64+ release := make(chan struct{})+ results := make(chan error, 40)+ var group sync.WaitGroup+ for index := 0; index < 40; index++ {+ group.Add(1)+ go func(index int) {+ defer group.Done()+ _, err := tryConnectViewerWithPassword(store, ConnectViewerWithPasswordInput{+ RoomID: "9999",+ Password: "bounded-password",+ ClientID: "bounded-client-" + strconv.Itoa(index),+ SessionID: "bounded-session-" + strconv.Itoa(index),+ }, func() bool {+ // The first two admitted hold their slot until every attempt+ // has been accepted or rejected, which the single-threaded+ // TypeScript got for free.+ if mayStartCalls.Add(1) <= 2 {+ <-release+ return true+ }+ return false+ })+ results <- err+ }(index)+ }+ waitForSaturatedGate(t, store)+ close(release)+ group.Wait()+ close(results)++ counts := map[ErrorCode]int{}+ for err := range results {+ var roomError *Error+ if !errors.As(err, &roomError) {+ t.Fatalf("unexpected error %v", err)+ }+ counts[roomError.Code]+++ }+ if calls := mayStartCalls.Load(); calls != 18 {+ t.Fatalf("mayStart calls = %d, want 18", calls)+ }+ if counts[CodeRoomNotFound] != 2 || counts[CodeInvalidToken] != 16 ||+ counts[CodeRoomBusy] != 22 {+ t.Fatalf("outcomes = %v", counts)+ }+}++func TestRotatesAndRevokesViewerGrantsWithoutChangingCodeEntry(t *testing.T) {+ store, _ := newStore(t, Options{})+ room := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ mustConnect(t, store, hostInput(room.RoomID, room.HostToken))++ rotated, err := store.SetViewerGrant(room.RoomID, "rotate", room.HostToken)+ if err != nil {+ t.Fatalf("rotate: %v", err)+ }+ _, err = store.ConnectParticipant(viewerInput(room.RoomID, "old-grant", room.ViewerGrant))+ expectCode(t, err, CodeInvalidToken)+ grantedViewer := mustConnect(t, store, viewerInput(room.RoomID, "new-grant", rotated.ViewerGrant))+ codeViewer := mustConnect(t, store, viewerInput(room.RoomID, "still-open", ""))++ revoked, err := store.SetViewerGrant(room.RoomID, "revoke", room.HostToken)+ if err != nil {+ t.Fatalf("revoke: %v", err)+ }+ if revoked.ViewerGrant != "" {+ t.Fatalf("revoked grant = %q, want empty", revoked.ViewerGrant)+ }+ if len(revoked.RevokedViewers) != 1 || revoked.RevokedViewers[0].PeerID != grantedViewer.PeerID {+ t.Fatalf("revoked viewers = %+v", revoked.RevokedViewers)+ }+ if connected, ok := store.GetConnectedViewer(+ room.RoomID, codeViewer.PeerID); !ok || connected.SessionID != "still-open" {+ t.Fatalf("code viewer = %+v %v", connected, ok)+ }+ _, err = store.ConnectParticipant(viewerInput(room.RoomID, "revoked", rotated.ViewerGrant))+ expectCode(t, err, CodeInvalidToken)+}++func TestKeepsTheOldGrantWhenRotationCannotCreateAGeneration(t *testing.T) {+ failedRandomCall := 0+ randomCalls := 0+ randomValue := byte(0)+ store, _ := newStore(t, Options{+ Random: func(size int) []byte {+ randomCalls+++ randomValue+++ if randomCalls == failedRandomCall {+ size--+ }+ return bytes.Repeat([]byte{randomValue}, size)+ },+ })+ room := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ mustConnect(t, store, hostInput(room.RoomID, room.HostToken))+ viewer := mustConnect(t, store, viewerInput(room.RoomID, "existing", room.ViewerGrant))++ failedRandomCall = randomCalls + 2+ _, err := store.SetViewerGrant(room.RoomID, "rotate", room.HostToken)+ if err == nil ||+ err.Error() != "Authorization generation random source must return 16 bytes" {+ t.Fatalf("rotate: %v", err)+ }+ failedRandomCall = 0++ if connected, ok := store.GetConnectedViewer(+ room.RoomID, viewer.PeerID); !ok || connected.SessionID != "existing" {+ t.Fatalf("viewer = %+v %v", connected, ok)+ }+ connected := mustConnect(t, store, viewerInput(+ room.RoomID, "old-grant-still-valid", room.ViewerGrant))+ if connected.Role != protocol.RoleViewer {+ t.Fatalf("role = %q", connected.Role)+ }+}++func TestClearsEveryCredentialOnProcessRestart(t *testing.T) {+ firstStore, _ := newStore(t, Options{})+ room := createRoom(t, firstStore, protocol.CodeEntryPrivate, "room-password", "")+ secondStore, _ := newStore(t, Options{})++ replacement := createRoom(t, secondStore, protocol.CodeEntryOpen, "", "")+ if !roomCodePattern.MatchString(replacement.RoomID) {+ t.Fatalf("room code = %q", replacement.RoomID)+ }+ _, err := secondStore.ConnectParticipant(hostInput(room.RoomID, room.HostToken))+ expectCode(t, err, CodeInvalidToken)+ _, err = secondStore.ConnectParticipant(viewerInput(room.RoomID, "old-grant", room.ViewerGrant))+ expectCode(t, err, CodeInvalidToken)+ _, err = tryConnectViewerWithPassword(secondStore, ConnectViewerWithPasswordInput{+ RoomID: room.RoomID,+ Password: "room-password",+ ClientID: "viewer",+ SessionID: "session",+ }, nil)+ expectCode(t, err, CodeRoomNotFound)+}++func TestRejectsAnOldGrantWhenANewRoomReusesTheSameCode(t *testing.T) {+ firstStore, _ := newStore(t, Options{+ Random: constantRandom(func(size int) byte {+ if size == 8 {+ return 0+ }+ return 1+ }),+ })+ firstRoom := createRoom(t, firstStore, protocol.CodeEntryOpen, "", "")+ if _, err := firstStore.AbandonRoom(firstRoom.RoomID); err != nil {+ t.Fatalf("AbandonRoom: %v", err)+ }++ secondStore, _ := newStore(t, Options{+ Random: constantRandom(func(size int) byte {+ if size == 8 {+ return 0+ }+ return 2+ }),+ })+ secondRoom := createRoom(t, secondStore, protocol.CodeEntryOpen, "", "")++ if secondRoom.RoomID != firstRoom.RoomID {+ t.Fatalf("codes differ: %q %q", secondRoom.RoomID, firstRoom.RoomID)+ }+ if secondRoom.ViewerGrant == firstRoom.ViewerGrant {+ t.Fatal("the new incarnation reused the old grant")+ }+ _, err := secondStore.ConnectParticipant(+ viewerInput(secondRoom.RoomID, "old-incarnation", firstRoom.ViewerGrant))+ expectCode(t, err, CodeInvalidToken)+}++func TestParticipantReplacementRules(t *testing.T) {+ store, _ := newStore(t, Options{})+ room := createRoom(t, store, protocol.CodeEntryOpen, "", "")+ host := mustConnect(t, store, hostInput(room.RoomID, room.HostToken))++ resumed := mustConnect(t, store, hostInput(room.RoomID, room.HostToken, "host-session-2"))+ if resumed.PeerID != host.PeerID || resumed.ReplacedSessionID != "host-session" {+ t.Fatalf("resumed host = %+v", resumed)+ }+ _, err := store.ConnectParticipant(ConnectParticipantInput{+ RoomID: room.RoomID,+ Role: protocol.RoleHost,+ Token: room.HostToken,+ ClientID: "second-host-client",+ SessionID: "second-host-session",+ })+ expectCode(t, err, CodeHostAlreadyConnected)++ first := mustConnect(t, store, viewerInput(room.RoomID, "first", room.ViewerGrant))+ second := mustConnect(t, store, viewerInput(room.RoomID, "second", room.ViewerGrant))+ _, err = store.ConnectParticipant(viewerInput(room.RoomID, "third", room.ViewerGrant))+ expectCode(t, err, CodeRoomFull)+ if peerIDs := store.GetViewerPeerIDs(room.RoomID); len(peerIDs) != 2 ||+ peerIDs[0] != first.PeerID || peerIDs[1] != second.PeerID {+ t.Fatalf("viewer order = %v", peerIDs)+ }++ // A viewer returning under the same client ID keeps its peer ID and its+ // place in the insertion order, which viewer presence is ordered by.+ returning := mustConnect(t, store, ConnectParticipantInput{+ RoomID: room.RoomID,+ Role: protocol.RoleViewer,+ ViewerGrant: room.ViewerGrant,+ ClientID: "viewer-first",+ SessionID: "first-again",+ })+ if returning.PeerID != first.PeerID || returning.ReplacedSessionID != "first" {+ t.Fatalf("returning viewer = %+v", returning)+ }+ if peerIDs := store.GetViewerPeerIDs(room.RoomID); len(peerIDs) != 2 ||+ peerIDs[0] != first.PeerID || peerIDs[1] != second.PeerID {+ t.Fatalf("viewer order after the return = %v", peerIDs)+ }++ if _, err := store.DisconnectParticipant(room.RoomID, second.PeerID, "second"); err != nil {+ t.Fatalf("DisconnectParticipant: %v", err)+ }+ connected := store.GetConnectedViewers(room.RoomID)+ if len(connected) != 1 || connected[0].PeerID != first.PeerID ||+ connected[0].SessionID != "first-again" {+ t.Fatalf("connected viewers = %+v", connected)+ }+ if store.RemoveDisconnectedViewer(room.RoomID, first.PeerID) {+ t.Fatal("removed a connected viewer")+ }+ if !store.RemoveDisconnectedViewer(room.RoomID, second.PeerID) {+ t.Fatal("did not remove the disconnected viewer")+ }+ if peerIDs := store.GetViewerPeerIDs(room.RoomID); len(peerIDs) != 1 ||+ peerIDs[0] != first.PeerID {+ t.Fatalf("viewer order after the removal = %v", peerIDs)+ }++ for _, testCase := range []struct {+ roomID, grant string+ want bool+ }{+ {room.RoomID, room.ViewerGrant, true},+ {room.RoomID, "", false},+ {room.RoomID, "AAAAAAAAAAAAAAAAAAAAAA", false},+ {"9999", room.ViewerGrant, false},+ } {+ mayEnter, err := store.ViewerGrantMayEnter(testCase.roomID, testCase.grant)+ if err != nil || mayEnter != testCase.want {+ t.Fatalf("ViewerGrantMayEnter(%q, %q) = %v, %v",+ testCase.roomID, testCase.grant, mayEnter, err)+ }+ }+}++// TestHostChangeChecksIdentityAfterTheDerivation pins the order of the checks+// the TypeScript ran after its KDF await: the second getHostManagedRoom first,+// then the room identity together with a cancelled derivation, then busy.+func TestHostChangeChecksIdentityAfterTheDerivation(t *testing.T) {+ // A constant random source gives a recreated room the same Host token, so+ // the identity comparison is reachable instead of being shadowed by the+ // token check.+ store, testClock := newStore(t, Options{+ MaxRooms: 3,+ Random: constantRandom(func(int) byte { return 7 }),+ })+ room := createRoom(t, store, protocol.CodeEntryOpen, "", "4321")+ current, err := store.HostManagedRoom(room.RoomID, room.HostToken)+ if err != nil {+ t.Fatalf("HostManagedRoom: %v", err)+ }+ if !store.HostStillOwnsRoom(room.RoomID, room.HostToken, current) {+ t.Fatal("HostStillOwnsRoom rejected the unchanged room")+ }++ if _, err := store.AbandonRoom(room.RoomID); err != nil {+ t.Fatalf("AbandonRoom: %v", err)+ }+ if store.HostStillOwnsRoom(room.RoomID, room.HostToken, current) {+ t.Fatal("HostStillOwnsRoom accepted an abandoned room")+ }+ _, err = store.SetViewerPassword(room.RoomID, room.HostToken, nil, nil, current)+ expectCode(t, err, CodeInvalidToken)++ again := createRoom(t, store, protocol.CodeEntryOpen, "", "4321")+ if again.HostToken != room.HostToken {+ t.Fatal("the constant random source did not repeat the Host token")+ }+ _, err = store.SetViewerPassword(again.RoomID, again.HostToken, nil, nil, current)+ expectCode(t, err, CodeRoomAccessDenied)++ incarnation, err := store.HostManagedRoom(again.RoomID, again.HostToken)+ if err != nil {+ t.Fatalf("HostManagedRoom: %v", err)+ }+ testClock.nowMs = 5_000+ _, err = store.SetViewerPassword(again.RoomID, again.HostToken, nil, nil, incarnation)+ expectCode(t, err, CodeRoomExpired)+ // An expired room outranks a saturated gate, as the TypeScript order did.+ _, err = store.SetViewerPassword(+ again.RoomID, again.HostToken, nil, codeError(CodeRoomBusy), incarnation)+ expectCode(t, err, CodeRoomExpired)++ testClock.nowMs = 0+ _, err = store.SetViewerPassword(+ again.RoomID, again.HostToken, nil, errDerivationCancelled, incarnation)+ expectCode(t, err, CodeRoomAccessDenied)+ _, err = store.SetViewerPassword(+ again.RoomID, again.HostToken, nil, codeError(CodeRoomBusy), incarnation)+ expectCode(t, err, CodeRoomBusy)+ _, err = store.ReplaceRoom(again.RoomID, again.HostToken, protocol.CodeEntryOpen,+ nil, errDerivationCancelled, incarnation)+ expectCode(t, err, CodeRoomAccessDenied)+}++// TestPasswordLoginRechecksTheRoomAfterTheDerivation covers the guard chain the+// TypeScript ran after its scrypt await: a vanished room answers ROOM_NOT_FOUND,+// a replaced room and a refusing mayConnect answer INVALID_TOKEN, and so does a+// full room, whose ROOM_FULL must not leak to the client.+func TestPasswordLoginRechecksTheRoomAfterTheDerivation(t *testing.T) {+ // A constant random source repeats the salt, so a recreated room holds the+ // same material and only the room identity separates the two incarnations.+ store, _ := newStore(t, Options{+ MaxRooms: 3,+ Random: constantRandom(func(int) byte { return 7 }),+ })+ room := createRoom(t, store, protocol.CodeEntryPrivate, "room-password", "4321")+ input := ConnectViewerWithPasswordInput{+ RoomID: room.RoomID,+ Password: "room-password",+ ClientID: "password-viewer",+ SessionID: "password-session",+ }+ alwaysConnect := func() bool { return true }++ salt, expectedMaterial, reference, err := store.ViewerPasswordChallenge(input.RoomID)+ if err != nil {+ t.Fatalf("ViewerPasswordChallenge: %v", err)+ }+ derived, err := store.DeriveViewerPassword(input.Password, salt, nil)+ if err != nil {+ t.Fatalf("DeriveViewerPassword: %v", err)+ }+ if _, err := store.AbandonRoom(room.RoomID); err != nil {+ t.Fatalf("AbandonRoom: %v", err)+ }+ _, err = store.ConnectViewerWithPassword(+ input, derived, expectedMaterial, reference, alwaysConnect)+ expectCode(t, err, CodeRoomNotFound)++ createRoom(t, store, protocol.CodeEntryPrivate, "room-password", "4321")+ _, err = store.ConnectViewerWithPassword(+ input, derived, expectedMaterial, reference, alwaysConnect)+ expectCode(t, err, CodeInvalidToken)++ salt, expectedMaterial, reference, err = store.ViewerPasswordChallenge(input.RoomID)+ if err != nil {+ t.Fatalf("ViewerPasswordChallenge: %v", err)+ }+ derived, err = store.DeriveViewerPassword(input.Password, salt, nil)+ if err != nil {+ t.Fatalf("DeriveViewerPassword: %v", err)+ }+ _, err = store.ConnectViewerWithPassword(+ input, derived, expectedMaterial, reference, func() bool { return false })+ expectCode(t, err, CodeInvalidToken)+}++// TestPasswordLoginRequiresAnInitializedStore pins the first check of+// connectViewerWithPassword: `ensureInitialized()` ran before the password was+// validated and before any derivation, so an uninitialized store answers the+// initialization error at the challenge, not INVALID_TOKEN after a KDF.+func TestPasswordLoginRequiresAnInitializedStore(t *testing.T) {+ database, err := NewDatabase(databasePath(t))+ if err != nil {+ t.Fatalf("NewDatabase: %v", err)+ }+ store, err := New(Options{LeaseMs: 1_000, MaxRooms: 2, MaxViewersPerRoom: 2, Database: database})+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ _, _, _, err = store.ViewerPasswordChallenge("1234")+ if err == nil || err.Error() != "RoomStore stable authority is not initialized" {+ t.Fatalf("ViewerPasswordChallenge before Initialize = %v", err)+ }+}++// TestPasswordLoginHidesAFullRoom keeps ROOM_FULL from leaking to a Viewer that+// authenticated with the room password.+func TestPasswordLoginHidesAFullRoom(t *testing.T) {+ store, _ := newStore(t, Options{MaxViewersPerRoom: 2})+ room := createRoom(t, store, protocol.CodeEntryPrivate, "room-password", "")+ mustConnect(t, store, viewerInput(room.RoomID, "first", room.ViewerGrant))+ mustConnect(t, store, viewerInput(room.RoomID, "second", room.ViewerGrant))++ _, err := tryConnectViewerWithPassword(store, ConnectViewerWithPasswordInput{+ RoomID: room.RoomID,+ Password: "room-password",+ ClientID: "password-viewer",+ SessionID: "password-session",+ }, nil)+ expectCode(t, err, CodeInvalidToken)+}++func TestCreateRoomReportsACancelledDerivation(t *testing.T) {+ store, _ := newStore(t, Options{})+ lease, err := store.BeginCreateRoom()+ if err != nil {+ t.Fatalf("BeginCreateRoom: %v", err)+ }+ material, derived := store.DeriveViewerPasswordMaterial(+ "room-password", func() bool { return false })+ if material != nil || !errors.Is(derived, errDerivationCancelled) {+ t.Fatalf("derive = %v, %v", material, derived)+ }+ _, err = store.CreateRoom(protocol.CodeEntryPrivate, material, derived, "", lease)+ if err == nil || err.Error() != "Room creation password derivation was cancelled" {+ t.Fatalf("CreateRoom = %v", err)+ }+ if store.Size() != 0 {+ t.Fatalf("size = %d, want 0", store.Size())+ }+}++func TestRejectsAMalformedViewerPassword(t *testing.T) {+ store, _ := newStore(t, Options{})+ for _, password := range []string{"", "with space", strings.Repeat("a", 65)} {+ material, derived := store.DeriveViewerPasswordMaterial(password, nil)+ if material != nil || !hasCode(derived, CodeInvalidToken) {+ t.Fatalf("derive(%q) = %v, %v", password, material, derived)+ }+ if _, err := store.DeriveViewerPassword(+ password, make([]byte, viewerPasswordSaltBytes), nil); !hasCode(err, CodeInvalidToken) {+ t.Fatalf("login derive(%q) = %v", password, err)+ }+ }+}++// TestUniformIndexRejectionLimit covers the D11 formula: (MaxUint64%n + 1) % n+// must not wrap where 2^64 % n is 0, which is every power-of-two free count.+func TestUniformIndexRejectionLimit(t *testing.T) {+ allOnes := bytes.Repeat([]byte{0xff}, 8)+ zeros := make([]byte, 8)+ for _, testCase := range []struct {+ name string+ count int+ wantIndex int+ wantDraws int+ }{+ {"power of two accepts the top value", 8_192, 8_191, 1},+ {"one free code accepts the top value", 1, 0, 1},+ {"three free codes reject the top value", 3, 0, 2},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ draws := 0+ random := func(size int) []byte {+ draws+++ if draws == 1 {+ return allOnes+ }+ return zeros+ }+ index, err := uniformIndex(testCase.count, random)+ if err != nil {+ t.Fatalf("uniformIndex: %v", err)+ }+ if index != testCase.wantIndex {+ t.Fatalf("index = %d, want %d", index, testCase.wantIndex)+ }+ if draws != testCase.wantDraws {+ t.Fatalf("draws = %d, want %d", draws, testCase.wantDraws)+ }+ })+ }+}++func TestUniformIndexRejectsAShortRandomSource(t *testing.T) {+ _, err := uniformIndex(9_000, func(int) []byte { return make([]byte, 7) })+ if err == nil || !strings.Contains(err.Error(), "must return 8 bytes") {+ t.Fatalf("uniformIndex: %v", err)+ }+}diff --git a/internal/server/room/testdata/node-rooms.db b/internal/server/room/testdata/node-rooms.dbnew file mode 100644index 00000000..3303a6f0Binary files /dev/null and b/internal/server/room/testdata/node-rooms.db differdiff --git a/internal/server/route/api.go b/internal/server/route/api.gonew file mode 100644index 00000000..ea887bd6--- /dev/null+++ b/internal/server/route/api.go@@ -0,0 +1,519 @@+package route++import (+ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// Resource is the caller-owned SFU/overlap allocation the controller stores,+// moves between collections and compares by pointer identity (TS: the bare+// Resource type parameter, always used through JS Set semantics). The+// controller never reads its fields; they exist for the router and tests.+type Resource struct {+ Kind ResourceKind+ // EndpointPeerID is set for ResourceOverlap.+ EndpointPeerID string+ // Fence fields (RoomID, ShareGeneration, PublicationGeneration) are set+ // for sfu-publication and sfu-subscription; ViewerPeerID only for the+ // subscription. All are opaque IDs.+ RoomID string+ ShareGeneration string+ PublicationGeneration string+ ViewerPeerID string+ // Released is flipped by the router once the allocation is freed.+ Released bool+}++// ResourceKind is the RouteResource discriminator of hybrid-media-router.ts.+type ResourceKind string++// Resource kinds.+const (+ ResourceOverlap ResourceKind = "overlap"+ ResourceSfuSubscription ResourceKind = "sfu-subscription"+ ResourceSfuPublication ResourceKind = "sfu-publication"+)++// UpstreamKind discriminates CandidateTuple, CommittedEdge, committedEdgeSeed+// and QualityUpstream (TS kind: "peer" | "sfu").+type UpstreamKind string++// Upstream kinds.+const (+ UpstreamPeer UpstreamKind = "peer"+ UpstreamSfu UpstreamKind = "sfu"+)++// Transport is the edge transport (TS transport: "direct" | "sfu").+type Transport string++// Transports.+const (+ TransportDirect Transport = "direct"+ TransportSfu Transport = "sfu"+)++// PublicationPlan is the SFU tuple action (TS publication: "reuse" | "create" | "replace").+type PublicationPlan string++// Publication plans.+const (+ PublicationReuse PublicationPlan = "reuse"+ PublicationCreate PublicationPlan = "create"+ PublicationReplace PublicationPlan = "replace"+)++// ReservationKind discriminates CandidateReservation.+type ReservationKind string++// Reservation kinds.+const (+ ReservationDirect ReservationKind = "direct"+ ReservationSfuReuse ReservationKind = "sfu-reuse"+ ReservationSfuCreate ReservationKind = "sfu-create"+)++// RetirementKind discriminates EndpointRetirement.+type RetirementKind string++// Retirement kinds.+const (+ RetireEdge RetirementKind = "edge"+ RetirePublication RetirementKind = "publication"+)++// TransitionKind discriminates EndpointTransition.+type TransitionKind string++// Transition kinds.+const (+ TransitionNone TransitionKind = "none"+ TransitionOverlap TransitionKind = "overlap"+ TransitionBoundedGap TransitionKind = "bounded-gap"+)++// SenderQualityState is the sender-side health sample state+// (TS "unknown" | "healthy" | "degraded").+type SenderQualityState string++// Sender quality states.+const (+ SenderQualityUnknown SenderQualityState = "unknown"+ SenderQualityHealthy SenderQualityState = "healthy"+ SenderQualityDegraded SenderQualityState = "degraded"+)++// DemandReason mirrors protocol RouteDemandReason.+type DemandReason string++// Demand reasons.+const (+ DemandJoin DemandReason = "join"+ DemandEdgeUnavailable DemandReason = "edge-unavailable"+ DemandParentDeparted DemandReason = "parent-departed"+ DemandCapacityReduction DemandReason = "capacity-reduction"+ DemandSfuBootstrap DemandReason = "sfu-bootstrap"+ DemandDirectConvergence DemandReason = "direct-convergence"+ DemandQualityConvergence DemandReason = "quality-convergence"+ DemandRootConvergence DemandReason = "root-convergence"+)++// FinalRoute mirrors protocol RouteDiagnosticFinalRoute.+type FinalRoute string++// Final routes.+const (+ FinalRouteDirect FinalRoute = "direct"+ FinalRouteSfu FinalRoute = "sfu"+ FinalRouteWaiting FinalRoute = "waiting"+ FinalRouteFailed FinalRoute = "failed"+)++// RejectionBucket mirrors protocol RouteDiagnosticRejectionBucket.+type RejectionBucket string++// Rejection buckets.+const (+ RejectionNone RejectionBucket = "none"+ RejectionStale RejectionBucket = "stale"+ RejectionEndpointCapacity RejectionBucket = "endpoint-capacity"+ RejectionSfuAdmission RejectionBucket = "sfu-admission"+ RejectionCandidateFailed RejectionBucket = "candidate-failed"+ RejectionFirstFrameTimeout RejectionBucket = "first-frame-timeout"+ RejectionOperationDeadline RejectionBucket = "operation-deadline"+ RejectionAborted RejectionBucket = "aborted"+)++// RouteQualityEvidenceResult is the ObserveQualityEvidence outcome.+type RouteQualityEvidenceResult string++// Quality evidence outcomes.+const (+ QualityEvidenceRejected RouteQualityEvidenceResult = "rejected"+ QualityEvidenceAccepted RouteQualityEvidenceResult = "accepted"+ QualityEvidenceObserved RouteQualityEvidenceResult = "observed"+)++// CandidateTuple is one route candidate: a direct edge from ParentPeerID+// (Kind UpstreamPeer, Transport always TransportDirect, Regenerate = rebuild+// the same edge with a fresh connection) or an SFU edge (Kind UpstreamSfu,+// Publication set). TS: CandidateTuple.+type CandidateTuple struct {+ Kind UpstreamKind+ ParentPeerID string+ Transport Transport+ Regenerate bool+ Publication PublicationPlan+}++// CandidateReservation is what the caller allocated before+// BeginCurrentCandidate. Edge/Publication are set per Kind+// (direct: neither; sfu-reuse: Edge, Borrowed when it is another holder's+// live subscription and must not be released; sfu-create: Edge and+// Publication). Overlap is optional for every kind. TS: CandidateReservation.+type CandidateReservation struct {+ Kind ReservationKind+ Edge *Resource+ Publication *Resource+ Borrowed bool+ Overlap *Resource+}++// EndpointRetirement is the producer retirement a bounded-gap transition+// requires: an existing direct edge (RetireEdge: Child*/Parent*/Transport/+// ConnectionID) or the Host publication (RetirePublication: HostSessionID/+// Generation/ConnectionID). TS: EndpointRetirement.+type EndpointRetirement struct {+ Kind RetirementKind+ ChildPeerID string+ ChildSessionID string+ ParentPeerID string+ ParentSessionID string+ Transport Transport+ ConnectionID string+ HostSessionID string+ Generation string+}++// EndpointTransition says how the producer's copy budget absorbs the+// candidate. ProducerPeerID is nil only for TransitionNone on an sfu/reuse+// plan (TS omitted it there and endpointTransitionEquals compares it).+// Retire is set only for TransitionBoundedGap. TS: EndpointTransition.+type EndpointTransition struct {+ Kind TransitionKind+ ProducerPeerID *string+ Retire *EndpointRetirement+}++// CandidatePlan is a tuple with its endpoint transition. TS: CandidatePlan.+type CandidatePlan struct {+ Tuple CandidateTuple+ EndpointTransition EndpointTransition+}++// CommittedEdge is a child's one upstream edge in the committed graph.+// Peer edges (Kind UpstreamPeer) set ParentPeerID/ParentSessionID and leave+// Resource nil; SFU edges (Kind UpstreamSfu) set PublicationGeneration and+// Resource. TS: CommittedEdge.+type CommittedEdge struct {+ Kind UpstreamKind+ ChildSessionID string+ ParentPeerID string+ ParentSessionID string+ PublicationGeneration string+ Transport Transport+ ConnectionID string+ Usable bool+ PhysicalActive bool+ Resource *Resource+}++// committedEdgeSeed is CommittedEdge without the session fields the+// controller derives at hydrateEdge. TS: CommittedEdgeSeed, which like+// hydrateEdge only ever had test callers.+type committedEdgeSeed struct {+ Kind UpstreamKind+ ParentPeerID string+ PublicationGeneration string+ Transport Transport+ ConnectionID string+ Usable bool+ PhysicalActive bool+ Resource *Resource+}++// HostPublication is the single live SFU ingress. TS: HostPublication.+type HostPublication struct {+ Generation string+ HostSessionID string+ ConnectionID string+ Usable bool+ PhysicalActive bool+ Resource *Resource+}++// ConnectionAttemptProgress is the NAT-prediction attempt counter+// (Total is always 3). TS: ConnectionAttemptProgress.+type ConnectionAttemptProgress struct {+ Current int+ Total int+}++// CurrentAttempt is OperationSnapshot.current: the live candidate attempt.+// ConnectionAttempt is nil when the attempt has no NAT opportunity.+type CurrentAttempt struct {+ Tuple CandidateTuple+ Revision int64+ ConnectionID string+ ConnectionAttempt *ConnectionAttemptProgress+}++// OperationSnapshot is a deep copy of the in-flight operation plus the+// derived WakeAtMs. Current is nil without a live attempt. TS: OperationSnapshot.+type OperationSnapshot struct {+ ChildPeerID string+ ChildSessionID string+ DemandPeerID string+ Reason DemandReason+ BaseRevision int64+ FactVersion int64+ Candidates []CandidatePlan+ Cursor int+ DeadlineAtMs int64+ WakeAtMs int64+ Current *CurrentAttempt+}++// RouteSnapshot is the committed graph as the router reads it.+// UpstreamByViewer is a fresh insertion-ordered copy (child peerId -> edge);+// HostPublication is a shallow copy or nil; Operation is nil when idle.+// TS: RouteSnapshot.+type RouteSnapshot struct {+ Revision int64+ Paused bool+ FactVersion int64+ UpstreamByViewer *ordered.Map[string, CommittedEdge]+ HostPublication *HostPublication+ Operation *OperationSnapshot+}++// ReconcileResult is the scheduler outcome. TS: ReconcileResult.+type ReconcileResult struct {+ Operation *OperationSnapshot+ RemovedPeerIDs []string+ FailedPeerIDs []string+ Released []*Resource+}++// SettleResult is the outcome of a candidate settlement call. Committed is+// true only when CandidateReady committed the attempt (TS: optional+// committed, read as truthy by the router). TS: SettleResult.+type SettleResult struct {+ Accepted bool+ Committed bool+ FailedPeerIDs []string+ ActiveRevision int64+ Released []*Resource+}++// SenderQualityEvidenceResult is the outcome of the two sender-side+// observers. TS declares it separately with a required committed flag; the+// Go shape is identical to SettleResult.+type SenderQualityEvidenceResult = SettleResult++// BeginResult is the outcome of the cursor-guarded candidate calls.+// TS: BeginResult.+type BeginResult struct {+ Accepted bool+ Operation *OperationSnapshot+ FailedPeerIDs []string+ Released []*Resource+}++// ParticipantInput describes a connected participant. TS: ParticipantInput.+type ParticipantInput struct {+ PeerID string+ Role protocol.Role+ SessionID string+ EffectiveDownstreamCapacity int+}++// EdgeGuard identifies one committed edge exactly. ParentSessionID is only+// compared for peer edges; callers pass the edge's own ParentSessionID for+// those and leave it empty for SFU edges. TS: EdgeGuard.+type EdgeGuard struct {+ ChildPeerID string+ ChildSessionID string+ RouteRevision int64+ ConnectionID string+ ParentSessionID string+}++// ParentEdgeGuard identifies a direct edge from the parent's side.+// TS: the inline input of invalidateDirectEdgeFromParent.+type ParentEdgeGuard struct {+ ParentPeerID string+ ParentSessionID string+ RouteRevision int64+ ConnectionID string+}++// PublicationGuard identifies the Host publication exactly. TS: the inline+// guard of invalidateHostPublication and retireHostPublication.+type PublicationGuard struct {+ HostSessionID string+ RouteRevision int64+ Generation string+ ConnectionID string+}++// AdoptDirectConnectionInput is an EdgeGuard plus the replacement+// connection. TS: EdgeGuard & { newConnectionId }.+type AdoptDirectConnectionInput struct {+ EdgeGuard+ NewConnectionID string+}++// CandidateGuard identifies the live attempt exactly. TS: CandidateGuard.+type CandidateGuard struct {+ ChildPeerID string+ ChildSessionID string+ Revision int64+ ConnectionID string+}++// CandidateCursorGuard identifies one candidate slot of the current+// operation: it must still be at Cursor with an equal Plan, built at+// FactVersion on BaseRevision. TS: CandidateCursorGuard.+type CandidateCursorGuard struct {+ ChildPeerID string+ ChildSessionID string+ BaseRevision int64+ FactVersion int64+ Cursor int+ Plan CandidatePlan+}++// BeginInput is the BeginCurrentCandidate input. PublicationGeneration and+// PublicationConnectionID are required for sfu create/replace tuples;+// HostSessionID is required for every SFU tuple (empty = TS undefined,+// rejected the same way). TS: the inline input of beginCurrentCandidate.+type BeginInput struct {+ Guard CandidateCursorGuard+ NowMs int64+ ConnectionID string+ Reservation CandidateReservation+ PublicationGeneration string+ PublicationConnectionID string+ HostSessionID string+}++// CandidateProof carries the Viewer's one-shot relative quality approval.+// TS: the proof parameter of candidateReady ({ relativeQualityApproved? }).+type CandidateProof struct {+ RelativeQualityApproved bool+}++// QualityUpstream names the upstream a receiver-side window was measured+// on: PeerID is set only for UpstreamPeer. TS: RouteQualityEvidenceInput.upstream.+type QualityUpstream struct {+ Kind UpstreamKind+ PeerID string+}++// RouteQualityEvidenceInput is one receiver-side quality window. Only+// FramesDecodedDelta, FreezeCountDelta, FreezeDurationMsDelta,+// PauseCountDelta and PauseDurationMsDelta of Metrics are read.+// TS: RouteQualityEvidenceInput.+type RouteQualityEvidenceInput struct {+ ChildPeerID string+ ChildSessionID string+ RouteRevision int64+ ConnectionID string+ Upstream QualityUpstream+ PresentationEpoch int64+ WindowMs int64+ Metrics protocol.ViewerQualityEvidenceMetrics+ AcceptedAtMs int64+}++// SenderQualityEvidenceInput is one sender-side health sample from a parent+// about one child. SenderIdentity and SampleTimestampMs are nullable.+// TS: SenderQualityEvidenceInput.+type SenderQualityEvidenceInput struct {+ ParentPeerID string+ ParentSessionID string+ ChildPeerID string+ RouteRevision int64+ ConnectionID string+ SenderIdentity *string+ SampleTimestampMs *int64+ State SenderQualityState+ AcceptedAtMs int64+}++// SfuPublisherQualityEvidenceInput is one Host->SFU ingress health sample.+// TS: SfuPublisherQualityEvidenceInput.+type SfuPublisherQualityEvidenceInput struct {+ HostPeerID string+ HostSessionID string+ PublicationGeneration string+ RouteRevision int64+ State SenderQualityState+ SampleTimestampMs *int64+ AcceptedAtMs int64+}++// Options configures a Controller. DebugRoomID empty disables the sanitised+// route debug events. TS: ControllerOptions.+type Options struct {+ HostPeerID string+ DebugRoomID string+ EndpointMediaCopyCapacity int+ OperationTimeoutMs int64+ SfuEnabled bool+ QualityConvergenceEnabled bool+ NatPredictionEnabled bool+}++// Controller ports RoomRouteController. It never locks: the caller holds+// signal.Server.mu around every call. The public methods live in the files+// named after the TS helper clusters (controller.go, operation.go,+// quality.go, ...); every signature below the types is unchanged.+type Controller struct {+ // hostPeerID is its own mutable field because RebindHostIdentity+ // reassigns it (TS: options.hostPeerId = peerId at line 660); the other+ // options are copied once and never change.+ hostPeerID string+ debugRoomID string+ endpointMediaCopyCapacity int+ operationTimeoutMs int64+ sfuEnabled bool+ qualityConvergenceEnabled bool+ natPredictionEnabled bool++ // Insertion order is load-bearing for participants, upstreamByViewer and+ // directContinuations (map §4.1-4.3); the opportunity ledgers and the+ // retiring set are ordered for the same delete-while-iterating semantics.+ participants ordered.Map[string, *participant]+ upstreamByViewer ordered.Map[string, *CommittedEdge]+ hostPublication *HostPublication+ operation *operation+ revision int64+ latestRevision int64+ factVersion int64+ nextJoinOrder int64+ paused bool+ routeTimings map[string]*routeTimingRecord+ qualityObservations map[string]*routeQualityObservation+ senderQualityObservations map[string]*senderQualityObservation+ senderQualityBaselines map[string]bool // tri-state: absent / false / true (read with comma-ok)+ senderQualityRegenerationBlocks map[string]senderQualityIdentity+ sfuPublisherQualityObservation *sfuPublisherQualityObservation+ qualityBaselinesPending map[string]struct{}+ directContinuations ordered.Map[string, *directContinuation]+ retiringPublicationGenerations ordered.Map[string, struct{}]+ sfuBootstrapIntent *sfuBootstrapIntent+ consumedSfuBootstrapOpportunities ordered.Map[string, int]+ rootConvergenceRootPeerID string // "" = TS undefined+}diff --git a/internal/server/route/candidates.go b/internal/server/route/candidates.gonew file mode 100644index 00000000..5aee90a9--- /dev/null+++ b/internal/server/route/candidates.go@@ -0,0 +1,562 @@+package route++import (+ "errors"+ "slices"+ "sort"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// buildCandidates ports 2767: the full plan list filtered by the+// availability opportunity ledger.+func (c *Controller) buildCandidates(childPeerID string, sfuOnly bool) []CandidatePlan {+ plans := c.buildCandidatePlans(childPeerID, sfuOnly, true)+ out := make([]CandidatePlan, 0, len(plans))+ for _, plan := range plans {+ if c.candidateOpportunityAvailable(childPeerID, plan) {+ out = append(out, plan)+ }+ }+ return out+}++// buildCandidatePlans ports 2777: eligible parents sorted by (untried+// attempts when preferUntried) then depth, remaining capacity descending,+// stablePairRank, compareParticipant; the SFU tuple is spliced into index 1+// (§4.4 #28) and the list is deduped by tupleKey (§4.4 #29).+func (c *Controller) buildCandidatePlans(childPeerID string, sfuOnly, preferUntried bool) []CandidatePlan {+ descendants := c.descendantsOf(childPeerID)+ parents := []*participant{}+ for _, parent := range c.participants.Values() {+ if parent.sessionID != "" && !parent.departureConfirmed && parent.peerID != childPeerID &&+ !slices.Contains(descendants, parent.peerID) && c.sourceUsable(parent.peerID) && c.targetFits(parent.peerID, childPeerID) {+ parents = append(parents, parent)+ }+ }+ sort.SliceStable(parents, func(i, j int) bool {+ left, right := parents[i], parents[j]+ if preferUntried {+ if d := c.peerAttemptsStarted(childPeerID, left.peerID) - c.peerAttemptsStarted(childPeerID, right.peerID); d != 0 {+ return d < 0+ }+ }+ if d := c.depth(left.peerID) - c.depth(right.peerID); d != 0 {+ return d < 0+ }+ if d := c.remaining(right.peerID, childPeerID) - c.remaining(left.peerID, childPeerID); d != 0 {+ return d < 0+ }+ if d := stablePairRank(childPeerID, left.peerID) - stablePairRank(childPeerID, right.peerID); d != 0 {+ return d < 0+ }+ return compareParticipant(left, right) < 0+ })+ directCandidates := make([]CandidateTuple, 0, len(parents))+ for _, parent := range parents {+ directCandidates = append(directCandidates, CandidateTuple{Kind: UpstreamPeer, ParentPeerID: parent.peerID, Transport: TransportDirect})+ }+ var sfuCandidate *CandidateTuple+ if c.sfuEnabled {+ if c.hostPublication != nil && c.hostPublication.Usable && c.hostPublication.PhysicalActive {+ sfuCandidate = &CandidateTuple{Kind: UpstreamSfu, Publication: PublicationReuse}+ } else if c.hostPublication != nil || c.publicationFits(childPeerID, false) {+ publication := PublicationCreate+ if c.hostPublication != nil {+ publication = PublicationReplace+ }+ sfuCandidate = &CandidateTuple{Kind: UpstreamSfu, Publication: publication}+ }+ }+ var candidates []CandidateTuple+ switch {+ case sfuOnly:+ if sfuCandidate != nil {+ candidates = []CandidateTuple{*sfuCandidate}+ }+ case sfuCandidate != nil && len(directCandidates) > 0:+ candidates = append(candidates, directCandidates[0], *sfuCandidate)+ candidates = append(candidates, directCandidates[1:]...)+ case sfuCandidate != nil:+ candidates = []CandidateTuple{*sfuCandidate}+ default:+ candidates = directCandidates+ }+ seen := make(map[string]struct{}, len(candidates))+ plans := make([]CandidatePlan, 0, len(candidates))+ for _, tuple := range candidates {+ key := tupleKey(tuple)+ if _, duplicate := seen[key]; duplicate {+ continue+ }+ seen[key] = struct{}{}+ plan := c.planCandidate(childPeerID, tuple)+ if plan != nil && c.candidateValid(childPeerID, *plan, nil) {+ plans = append(plans, *plan)+ }+ }+ return plans+}++// planCandidate ports 3947: decides none / overlap / bounded-gap from the+// producer's copy budget; nil when the producer is gone or over budget.+func (c *Controller) planCandidate(childPeerID string, tuple CandidateTuple) *CandidatePlan {+ if tuple.Kind == UpstreamSfu && tuple.Publication == PublicationReuse {+ // No producer on sfu/reuse (3949); endpointTransitionEquals compares it.+ return &CandidatePlan{Tuple: tuple, EndpointTransition: EndpointTransition{Kind: TransitionNone}}+ }+ producerPeerID := c.hostPeerID+ if tuple.Kind == UpstreamPeer {+ producerPeerID = tuple.ParentPeerID+ }+ producer, _ := c.participants.Get(producerPeerID)+ if producer == nil || producer.sessionID == "" || producer.departureConfirmed {+ return nil+ }+ copies := c.physicalCopies(producerPeerID)+ producer0 := producerPeerID+ if copies+1 <= producer.effectiveDownstreamCapacity {+ return &CandidatePlan{Tuple: tuple, EndpointTransition: EndpointTransition{Kind: TransitionNone, ProducerPeerID: &producer0}}+ }+ if copies+1 <= protocol.EndpointMediaCopyLimit(c.endpointMediaCopyCapacity, protocol.EndpointMediaCopyTransition) {+ return &CandidatePlan{Tuple: tuple, EndpointTransition: EndpointTransition{Kind: TransitionOverlap, ProducerPeerID: &producer0}}+ }+ retire := c.retirementFor(childPeerID, producerPeerID, tuple)+ if retire == nil || copies > producer.effectiveDownstreamCapacity {+ return nil+ }+ return &CandidatePlan{Tuple: tuple, EndpointTransition: EndpointTransition{Kind: TransitionBoundedGap, ProducerPeerID: &producer0, Retire: retire}}+}++// retirementFor ports 3969.+func (c *Controller) retirementFor(childPeerID, producerPeerID string, tuple CandidateTuple) *EndpointRetirement {+ old, _ := c.upstreamByViewer.Get(childPeerID)+ if old != nil && old.Kind == UpstreamPeer && old.ParentPeerID == producerPeerID && old.PhysicalActive {+ return &EndpointRetirement{+ Kind: RetireEdge,+ ChildPeerID: childPeerID,+ ChildSessionID: old.ChildSessionID,+ ParentPeerID: old.ParentPeerID,+ ParentSessionID: old.ParentSessionID,+ Transport: old.Transport,+ ConnectionID: old.ConnectionID,+ }+ }+ if producerPeerID != c.hostPeerID || c.hostPublication == nil || !c.hostPublication.PhysicalActive {+ return nil+ }+ replacesPublication := tuple.Kind == UpstreamSfu && tuple.Publication == PublicationReplace+ releasesLastPublication := tuple.Kind == UpstreamPeer && old != nil && old.Kind == UpstreamSfu && old.PhysicalActive &&+ c.sfuSubscriberCount() == 1+ if !replacesPublication && !releasesLastPublication {+ return nil+ }+ return &EndpointRetirement{+ Kind: RetirePublication,+ HostSessionID: c.hostPublication.HostSessionID,+ Generation: c.hostPublication.Generation,+ ConnectionID: c.hostPublication.ConnectionID,+ }+}++// candidateValid ports 3903; att is the live attempt when validating it.+func (c *Controller) candidateValid(childPeerID string, plan CandidatePlan, att *attempt) bool {+ tuple := plan.Tuple+ child, _ := c.participants.Get(childPeerID)+ if child == nil || child.sessionID == "" || child.departureConfirmed || (att != nil && att.childSessionID != child.sessionID) {+ return false+ }+ if tuple.Kind == UpstreamPeer {+ parent, _ := c.participants.Get(tuple.ParentPeerID)+ if parent == nil || parent.sessionID == "" || parent.departureConfirmed || (att != nil && parent.sessionID != att.parentSessionID) ||+ slices.Contains(c.descendantsOf(childPeerID), parent.peerID) || !c.sourceUsable(parent.peerID) ||+ !c.targetFits(parent.peerID, childPeerID) {+ return false+ }+ } else {+ if !c.sfuEnabled {+ return false+ }+ if att != nil && att.hostSessionID != "" {+ host, _ := c.participants.Get(c.hostPeerID)+ if host == nil || !host.sessionIs(att.hostSessionID) {+ return false+ }+ }+ switch tuple.Publication {+ case PublicationReuse:+ if c.hostPublication == nil || !c.hostPublication.Usable || !c.hostPublication.PhysicalActive ||+ (att != nil && att.publicationGeneration != c.hostPublication.Generation) {+ return false+ }+ case PublicationReplace:+ if c.hostPublication == nil || c.hostPublication.Usable || !c.publicationFits(childPeerID, true) {+ return false+ }+ default:+ if c.hostPublication != nil || !c.publicationFits(childPeerID, false) {+ return false+ }+ }+ }+ currentPlan := c.planCandidate(childPeerID, tuple)+ return currentPlan != nil && endpointTransitionEquals(currentPlan.EndpointTransition, plan.EndpointTransition)+}++// operationCandidateValid ports 3934.+func (c *Controller) operationCandidateValid(op *operation, plan CandidatePlan, att *attempt) bool {+ return c.candidateValid(op.childPeerID, plan, att) &&+ ((att != nil && att.connectionAttempt != nil) ||+ !isAvailabilityOperation(op.reason) ||+ c.candidateOpportunityAvailable(op.childPeerID, plan))+}++// physicalCopies ports 3999.+func (c *Controller) physicalCopies(peerID string) int {+ copies := 0+ for _, edge := range c.upstreamByViewer.Values() {+ if edge.Kind == UpstreamPeer && edge.ParentPeerID == peerID && edge.PhysicalActive {+ copies+++ }+ }+ if peerID == c.hostPeerID && c.hostPublication != nil && c.hostPublication.PhysicalActive {+ copies+++ }+ return copies+}++// assertReservation ports 4006: panics on a reservation kind that does not+// match the tuple or a missing overlap for an overlap transition.+func assertReservation(tuple CandidateTuple, reservation CandidateReservation, overlap bool) {+ expected := ReservationSfuCreate+ switch {+ case tuple.Kind == UpstreamPeer:+ expected = ReservationDirect+ case tuple.Publication == PublicationReuse:+ expected = ReservationSfuReuse+ }+ if reservation.Kind != expected {+ panic(errors.New("Candidate reservation kind does not match tuple"))+ }+ if overlap && reservation.Overlap == nil {+ panic(errors.New("Candidate requires an endpoint overlap reservation"))+ }+}++// targetFits ports 4380; the parent must exist.+func (c *Controller) targetFits(parentPeerID, childPeerID string) bool {+ parent, _ := c.participants.Get(parentPeerID)+ edge, _ := c.upstreamByViewer.Get(childPeerID)+ already := edge != nil && edge.Kind == UpstreamPeer && edge.ParentPeerID == parentPeerID && edge.PhysicalActive+ releasesLastPublication := parent.role == protocol.RoleHost && edge != nil && edge.Kind == UpstreamSfu && edge.PhysicalActive &&+ c.sfuSubscriberCount() == 1+ slots := c.usedSlots(parentPeerID)+ if releasesLastPublication {+ slots--+ }+ if !already {+ slots+++ }+ return slots <= parent.effectiveDownstreamCapacity+}++// publicationFits ports 4390.+func (c *Controller) publicationFits(childPeerID string, replacing bool) bool {+ host, _ := c.participants.Get(c.hostPeerID)+ edge, _ := c.upstreamByViewer.Get(childPeerID)+ releasesHost := edge != nil && edge.Kind == UpstreamPeer && edge.ParentPeerID == c.hostPeerID && edge.PhysicalActive+ replacesPhysicalPublication := replacing && c.hostPublication != nil && c.hostPublication.PhysicalActive+ nextSlots := c.usedSlots(c.hostPeerID)+ if releasesHost {+ nextSlots--+ }+ if !replacesPhysicalPublication {+ nextSlots+++ }+ return host != nil && host.sessionID != "" && !host.departureConfirmed && nextSlots <= host.effectiveDownstreamCapacity+}++// hostHasPublicationSlot ports 4400.+func (c *Controller) hostHasPublicationSlot() bool {+ host, _ := c.participants.Get(c.hostPeerID)+ return host != nil && c.usedSlots(c.hostPeerID)+1 <= host.effectiveDownstreamCapacity+}++func (c *Controller) usedSlots(peerID string) int {+ return c.physicalCopies(peerID)+}++// remaining ports 4409 and may be negative; the parent must exist.+func (c *Controller) remaining(parentPeerID, childPeerID string) int64 {+ parent, _ := c.participants.Get(parentPeerID)+ edge, _ := c.upstreamByViewer.Get(childPeerID)+ already := edge != nil && edge.Kind == UpstreamPeer && edge.ParentPeerID == parentPeerID && edge.PhysicalActive+ value := int64(parent.effectiveDownstreamCapacity - c.usedSlots(parentPeerID))+ if !already {+ value--+ }+ return value+}++// depth ports 4416; a cycle yields MAX_SAFE_INTEGER (not MaxInt64) so the+// comparator subtraction cannot overflow.+func (c *Controller) depth(peerID string) int64 {+ if peerID == c.hostPeerID {+ return 1+ }+ depth := int64(1)+ seen := make(map[string]struct{})+ for {+ if _, visited := seen[peerID]; visited {+ return maxSafeInteger+ }+ seen[peerID] = struct{}{}+ edge, _ := c.upstreamByViewer.Get(peerID)+ if edge == nil || edge.Kind == UpstreamSfu {+ return depth + 1+ }+ depth+++ if edge.ParentPeerID == c.hostPeerID {+ return depth+ }+ peerID = edge.ParentPeerID+ }+}++// childrenOf ports 4352: direct peer children in upstreamByViewer order+// (§4.2 #17), the base order for every children-derived list.+func (c *Controller) childrenOf(parentPeerID string) []string {+ children := []string{}+ for childPeerID, edge := range c.upstreamByViewer.All() {+ if edge.Kind == UpstreamPeer && edge.ParentPeerID == parentPeerID {+ children = append(children, childPeerID)+ }+ }+ return children+}++// descendantsOf ports 4356: a DFS (the TS queue is popped from the end,+// §4.5 #49) returning the visit order without duplicates.+func (c *Controller) descendantsOf(peerID string) []string {+ descendants := []string{}+ seen := make(map[string]struct{})+ stack := []string{peerID}+ for len(stack) > 0 {+ last := stack[len(stack)-1]+ stack = stack[:len(stack)-1]+ for _, child := range c.childrenOf(last) {+ if _, visited := seen[child]; visited {+ continue+ }+ seen[child] = struct{}{}+ descendants = append(descendants, child)+ stack = append(stack, child)+ }+ }+ return descendants+}++// withSelf ports `this.descendantsOf(peerId).add(peerId)`: the peer itself+// is appended last unless the walk already reached it (§4.5 #50).+func withSelf(descendants []string, peerID string) []string {+ if slices.Contains(descendants, peerID) {+ return descendants+ }+ return append(descendants, peerID)+}++// sourceUsable ports 4365: the whole upstream path is usable and active.+func (c *Controller) sourceUsable(peerID string) bool {+ if peerID == c.hostPeerID {+ return true+ }+ seen := make(map[string]struct{})+ for {+ if _, visited := seen[peerID]; visited {+ return false+ }+ seen[peerID] = struct{}{}+ edge, _ := c.upstreamByViewer.Get(peerID)+ if edge == nil || !edge.Usable || !edge.PhysicalActive {+ return false+ }+ if edge.Kind == UpstreamSfu {+ return c.hostPublication != nil && c.hostPublication.Usable &&+ c.hostPublication.PhysicalActive && c.hostPublication.Generation == edge.PublicationGeneration+ }+ if edge.ParentPeerID == c.hostPeerID {+ return true+ }+ peerID = edge.ParentPeerID+ }+}++// participantBlocked ports 3862.+func (c *Controller) participantBlocked(current *participant) bool {+ return current.availabilityExhausted && len(c.buildCandidates(current.peerID, false)) == 0+}++// availableViewers ports 3869: connected, non-departed viewers sorted by+// compareParticipant (a total order, so the map order does not leak).+func (c *Controller) availableViewers(includeBlocked bool) []*participant {+ viewers := []*participant{}+ for _, current := range c.participants.Values() {+ if current.role == protocol.RoleViewer && current.sessionID != "" && !current.departureConfirmed &&+ (includeBlocked || !c.participantBlocked(current)) {+ viewers = append(viewers, current)+ }+ }+ sort.SliceStable(viewers, func(i, j int) bool { return compareParticipant(viewers[i], viewers[j]) < 0 })+ return viewers+}++// overflowChildren ports 3876: per parent in participants order, the+// overflowing children newest-first (§4.1 #3).+func (c *Controller) overflowChildren() []string {+ result := []string{}+ for _, parent := range c.participants.Values() {+ overflow := []string{}+ for _, id := range c.overflowPeerChildren(parent.peerID) {+ child, _ := c.participants.Get(id)+ if child != nil && child.sessionID != "" && !child.departureConfirmed && !c.participantBlocked(child) {+ overflow = append(overflow, id)+ }+ }+ slices.Reverse(overflow)+ result = append(result, overflow...)+ }+ return result+}++// overflowPeerChildren ports 3889: the physically active direct children+// beyond the parent's capacity, oldest first kept.+func (c *Controller) overflowPeerChildren(parentPeerID string) []string {+ parent, _ := c.participants.Get(parentPeerID)+ if parent == nil {+ return []string{}+ }+ publicationCopies := 0+ if parent.role == protocol.RoleHost && c.hostPublication != nil && c.hostPublication.PhysicalActive {+ publicationCopies = 1+ }+ capacity := max(0, parent.effectiveDownstreamCapacity-publicationCopies)+ children := []string{}+ for _, id := range c.childrenOf(parentPeerID) {+ if edge, ok := c.upstreamByViewer.Get(id); ok && edge.Kind == UpstreamPeer && edge.PhysicalActive {+ children = append(children, id)+ }+ }+ sort.SliceStable(children, func(i, j int) bool {+ left, _ := c.participants.Get(children[i])+ right, _ := c.participants.Get(children[j])+ return compareParticipant(left, right) < 0+ })+ if capacity >= len(children) {+ return []string{}+ }+ return children[capacity:]+}++// tupleKey ports 4979.+func tupleKey(tuple CandidateTuple) string {+ if tuple.Kind == UpstreamPeer {+ key := "peer:" + tuple.ParentPeerID+ if tuple.Regenerate {+ key += ":regenerate"+ }+ return key+ }+ return "sfu:" + string(tuple.Publication)+}++// edgeTupleKey ports 4999.+func edgeTupleKey(edge *CommittedEdge) string {+ if edge.Kind == UpstreamPeer {+ return "peer:" + edge.ParentPeerID+ }+ return "sfu:reuse"+}++// endpointTransitionRank ports 5003.+func endpointTransitionRank(transition EndpointTransition) int {+ switch transition.Kind {+ case TransitionNone:+ return 0+ case TransitionOverlap:+ return 1+ default:+ return 2+ }+}++// cloneCandidatePlan ports 5020 (deep copy of the retirement).+func cloneCandidatePlan(plan CandidatePlan) CandidatePlan {+ clone := plan+ if plan.EndpointTransition.ProducerPeerID != nil {+ producer := *plan.EndpointTransition.ProducerPeerID+ clone.EndpointTransition.ProducerPeerID = &producer+ }+ if plan.EndpointTransition.Retire != nil {+ retire := *plan.EndpointTransition.Retire+ clone.EndpointTransition.Retire = &retire+ }+ return clone+}++// candidatePlanEquals ports 5029.+func candidatePlanEquals(left, right CandidatePlan) bool {+ return tupleKey(left.Tuple) == tupleKey(right.Tuple) &&+ endpointTransitionEquals(left.EndpointTransition, right.EndpointTransition)+}++func stringPtrEquals(left, right *string) bool {+ if left == nil || right == nil {+ return left == nil && right == nil+ }+ return *left == *right+}++// endpointTransitionEquals ports 5034; `undefined !== HOST` matters for the+// none producer, hence the pointer comparison.+func endpointTransitionEquals(left, right EndpointTransition) bool {+ if left.Kind != right.Kind {+ return false+ }+ if left.Kind == TransitionNone || left.Kind == TransitionOverlap {+ return stringPtrEquals(left.ProducerPeerID, right.ProducerPeerID)+ }+ if left.Kind != TransitionBoundedGap || !stringPtrEquals(left.ProducerPeerID, right.ProducerPeerID) ||+ left.Retire == nil || right.Retire == nil || left.Retire.Kind != right.Retire.Kind {+ return false+ }+ if left.Retire.Kind == RetirePublication {+ return left.Retire.HostSessionID == right.Retire.HostSessionID &&+ left.Retire.Generation == right.Retire.Generation &&+ left.Retire.ConnectionID == right.Retire.ConnectionID+ }+ if left.Retire.Kind == RetireEdge {+ return left.Retire.ChildPeerID == right.Retire.ChildPeerID &&+ left.Retire.ChildSessionID == right.Retire.ChildSessionID &&+ left.Retire.ParentPeerID == right.Retire.ParentPeerID &&+ left.Retire.ParentSessionID == right.Retire.ParentSessionID &&+ left.Retire.Transport == right.Retire.Transport &&+ left.Retire.ConnectionID == right.Retire.ConnectionID+ }+ return false+}++// reservationResources ports 5060 in order: edge (never for a borrowed+// sfu-reuse edge, which belongs to another holder), publication, overlap.+func reservationResources(reservation CandidateReservation) []*Resource {+ resources := []*Resource{}+ if reservation.Kind != ReservationDirect && !(reservation.Kind == ReservationSfuReuse && reservation.Borrowed) {+ resources = append(resources, reservation.Edge)+ }+ if reservation.Kind == ReservationSfuCreate {+ resources = append(resources, reservation.Publication)+ }+ if reservation.Overlap != nil {+ resources = append(resources, reservation.Overlap)+ }+ return resources+}diff --git a/internal/server/route/controller.go b/internal/server/route/controller.gonew file mode 100644index 00000000..a2975874--- /dev/null+++ b/internal/server/route/controller.go@@ -0,0 +1,995 @@+package route++import (+ "crypto/sha256"+ "errors"+ "math"+ "sort"+ "strings"++ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// File-local constants of room-route-controller.ts (lines 112-114).+const (+ maxDirectHeadStartMs int64 = 5_000+ maxNatConnectionAttempts = 3+ sfuOpportunityPrefix = "sfu\x00"+ maxSafeInteger int64 = protocol.MaxSafeInteger+ qualityEvidenceExpiryMs int64 = protocol.ViewerQualityEvidenceExpiryMs+ persistentDegradedWindows = int64(protocol.PersistentNativeEdgeDegradedWindows)+)++// candidateOpportunity is one consumed-ledger entry (TS CandidateOpportunity).+type candidateOpportunity struct {+ rank int+ startedAttempts int+ exhausted bool+}++// participant is a known peer (TS Participant). sessionID "" is the TS+// null: disconnected but in grace, or departed. Wire session IDs are+// validated opaque IDs, so an empty string never names a live session;+// bootstrapFailureReported and sfuFirstAtNextRoute are TS `true | undefined`+// and only ever compared to true, so a bool is exact.+type participant struct {+ peerID string+ role protocol.Role+ sessionID string+ departureConfirmed bool+ joinOrder int64+ effectiveDownstreamCapacity int+ availabilityExhausted bool+ consumedCandidateOpportunities ordered.Map[string, candidateOpportunity]+ bootstrapFailureReported bool+ sfuFirstAtNextRoute bool+}++// sessionIs ports `participant.sessionId === id`: a disconnected+// participant (TS null) never equals any session string.+func (p *participant) sessionIs(id string) bool {+ return p.sessionID != "" && p.sessionID == id+}++// senderQualityIdentity is TS SenderQualityIdentity.+type senderQualityIdentity struct {+ childSessionID string+ parentPeerID string+ parentSessionID string+ connectionID string+ senderIdentity string+}++// attempt is the live candidate (TS Attempt). The optional strings use ""+// for undefined (they are only ever set to non-empty values or compared+// after a truthiness check); the optional timestamps are pointers because+// 0 is a legal accepted/sample time and `!== undefined` is semantic.+type attempt struct {+ tuple CandidateTuple+ revision int64+ connectionID string+ childSessionID string+ parentSessionID string+ hostSessionID string+ publicationGeneration string+ publicationConnectionID string+ reservation CandidateReservation+ startedAtMs int64+ transportConnected bool+ mediaReady bool+ connectionAttempt *ConnectionAttemptProgress+ senderQualityState SenderQualityState // "" = undefined+ senderQualityAcceptedAtMs *int64+ senderQualityConsecutiveHealthyWindows int64 // read only through `?? 0`+ senderQualityConsecutiveDegradedWindows int64 // read only through `?? 0`+ senderQualitySampleTimestampMs *int64+ senderQualityIdentity string // "" = undefined+ relativeQualityApprovedAtMs *int64+}++// operation is the single in-flight route operation (TS ChildOperation).+type operation struct {+ childPeerID string+ childSessionID string+ demandPeerID string+ demandSessionID string+ reason DemandReason+ baseRevision int64+ candidates []CandidatePlan+ cursor int+ deadlineAtMs int64+ builtAtFactVersion int64+ deferredParentPeerIDs []string+ peerAttemptStarted bool+ qualitySource *senderQualityIdentity+ current *attempt+}++// planAt ports `operation.candidates[index]`: nil when out of range. It+// returns a copy because the candidate array is spliced in place and TS+// plan objects are never mutated after construction.+func (o *operation) planAt(index int) *CandidatePlan {+ if index < 0 || index >= len(o.candidates) {+ return nil+ }+ plan := o.candidates[index]+ return &plan+}++// planAtOrLast ports `operation.candidates[Math.min(cursor, length - 1)]`,+// which is undefined (nil) for an empty array (map R8).+func (o *operation) planAtOrLast() *CandidatePlan {+ return o.planAt(min(o.cursor, len(o.candidates)-1))+}++// currentTuple ports `operation.current?.tuple ?? operation.candidates[operation.cursor]?.tuple`.+func (o *operation) currentTuple() *CandidateTuple {+ if o.current != nil {+ tuple := o.current.tuple+ return &tuple+ }+ if plan := o.planAt(o.cursor); plan != nil {+ return &plan.Tuple+ }+ return nil+}++// directContinuation is TS DirectContinuation; parentPeerIDs is the retry+// order and is spliced in place.+type directContinuation struct {+ childSessionID string+ sfuConnectionID string+ publicationGeneration string+ parentPeerIDs []string+}++type sfuBootstrapIntent struct {+ demandPeerID string+ demandSessionID string+}++type sfuBootstrapCarrier struct {+ demandPeerID string+ demandSessionID string+ carrierPeerID string+}++// routeTimingRecord is TS RouteTimingRecord; the optional timestamps are+// pointers (undefined = never happened, distinct from 0).+type routeTimingRecord struct {+ demandAtMs int64+ reason DemandReason+ operationStartedAtMs *int64+ candidateStartedAtMs *int64+ firstDecodedFrameAtMs *int64+ finalAtMs *int64+ finalRoute FinalRoute+ rejectionBucket RejectionBucket+}++// routeQualityObservation is TS RouteQualityObservation. upstreamPeerID is+// "" for the sfu upstream (TS null); lastDecodedProgressAtMs nil is TS null.+type routeQualityObservation struct {+ childSessionID string+ upstreamKind UpstreamKind+ upstreamPeerID string+ connectionID string+ presentationEpoch int64+ eligibleWindows int64+ eligibleDurationMs int64+ freezeWindows int64+ freezeCount int64+ freezeDurationMs int64+ pauseCount int64+ pauseDurationMs int64+ lastAcceptedAtMs int64+ lastDecodedProgressAtMs *int64+}++// senderQualityObservation is TS SenderQualityObservation. The consumed+// ledger is a pointer because `{...previous}` copies carry the same Map.+type senderQualityObservation struct {+ childSessionID string+ parentPeerID string+ parentSessionID string+ connectionID string+ senderIdentity string+ state SenderQualityState+ consecutiveDegradedWindows int64+ lastSampleTimestampMs int64+ lastAcceptedAtMs int64+ consumedQualityCandidates *ordered.Map[string, int]+}++type sfuPublisherQualityObservation struct {+ hostSessionID string+ publicationGeneration string+ state SenderQualityState+ consecutiveHealthyWindows int64+ lastSampleTimestampMs int64+ lastAcceptedAtMs int64+}++// resourceSet is a JS Set<Resource>: pointer identity plus insertion order.+type resourceSet struct {+ seen map[*Resource]struct{}+ list []*Resource+}++func (s *resourceSet) add(resources ...*Resource) {+ if s.seen == nil {+ s.seen = make(map[*Resource]struct{})+ }+ for _, resource := range resources {+ if _, ok := s.seen[resource]; ok {+ continue+ }+ s.seen[resource] = struct{}{}+ s.list = append(s.list, resource)+ }+}++func (s *resourceSet) has(resource *Resource) bool {+ _, ok := s.seen[resource]+ return ok+}++// resources returns a fresh slice in insertion order (`[...set]`).+func (s *resourceSet) resources() []*Resource {+ return append([]*Resource{}, s.list...)+}++// concatResources ports `[...a, ...b]` into a fresh, never-nil slice.+func concatResources(parts ...[]*Resource) []*Resource {+ out := []*Resource{}+ for _, part := range parts {+ out = append(out, part...)+ }+ return out+}++// dedupeStrings ports `[...new Set(values)]`: first occurrence wins.+func dedupeStrings(values []string) []string {+ seen := make(map[string]struct{}, len(values))+ out := make([]string, 0, len(values))+ for _, value := range values {+ if _, ok := seen[value]; ok {+ continue+ }+ seen[value] = struct{}{}+ out = append(out, value)+ }+ return out+}++// New ports the constructor: panics with "Endpoint media copy capacity must+// be 1, 2, or 3" or "Route operation timeout must be a positive integer".+func New(options Options) *Controller {+ if err := protocol.AssertEndpointMediaCopyCapacity(options.EndpointMediaCopyCapacity); err != nil {+ panic(err)+ }+ if !isSafeInteger(options.OperationTimeoutMs) || options.OperationTimeoutMs <= 0 {+ panic(errors.New("Route operation timeout must be a positive integer"))+ }+ c := &Controller{+ hostPeerID: options.HostPeerID,+ debugRoomID: options.DebugRoomID,+ endpointMediaCopyCapacity: options.EndpointMediaCopyCapacity,+ operationTimeoutMs: options.OperationTimeoutMs,+ sfuEnabled: options.SfuEnabled,+ qualityConvergenceEnabled: options.QualityConvergenceEnabled,+ natPredictionEnabled: options.NatPredictionEnabled,+ routeTimings: make(map[string]*routeTimingRecord),+ qualityObservations: make(map[string]*routeQualityObservation),+ senderQualityObservations: make(map[string]*senderQualityObservation),+ senderQualityBaselines: make(map[string]bool),+ senderQualityRegenerationBlocks: make(map[string]senderQualityIdentity),+ qualityBaselinesPending: make(map[string]struct{}),+ }+ c.debug("controller-created",+ "endpointCapacity", options.EndpointMediaCopyCapacity,+ "operationTimeoutMs", options.OperationTimeoutMs,+ "sfuEnabled", options.SfuEnabled,+ "qualityConvergenceEnabled", options.QualityConvergenceEnabled)+ return c+}++// DiagnosticParticipantLabel returns "host", "viewer-<joinOrder>" or+// "viewer-unknown" for a peer ID without exposing the ID.+func (c *Controller) DiagnosticParticipantLabel(peerID string) string {+ return c.debugPeer(peerID)+}++// Revision is Snapshot().Revision without the graph copy, for the callers+// that only compare revisions before and after a mutation.+func (c *Controller) Revision() int64 { return c.revision }++// Operation is Snapshot().Operation without the graph copy: a deep copy of+// the in-flight operation, or nil when the controller is idle.+func (c *Controller) Operation() *OperationSnapshot { return c.operationSnapshot() }++// Publication is Snapshot().HostPublication without the graph copy: a copy+// of the single live SFU ingress, or nil when there is none.+func (c *Controller) Publication() *HostPublication {+ if c.hostPublication == nil {+ return nil+ }+ copied := *c.hostPublication+ return &copied+}++// Snapshot returns a copy of the committed graph, the publication and the+// operation snapshot; it mutates nothing.+func (c *Controller) Snapshot() RouteSnapshot {+ // Ordering site: the router iterates this map to build assignments (§4.2 #9).+ upstream := &ordered.Map[string, CommittedEdge]{}+ for id, edge := range c.upstreamByViewer.All() {+ upstream.Set(id, *edge)+ }+ var publication *HostPublication+ if c.hostPublication != nil {+ copied := *c.hostPublication+ publication = &copied+ }+ return RouteSnapshot{+ Revision: c.revision,+ Paused: c.paused,+ FactVersion: c.factVersion,+ UpstreamByViewer: upstream,+ HostPublication: publication,+ Operation: c.operationSnapshot(),+ }+}++// RouteDiagnosticSnapshot returns the privacy-safe snapshot: connected+// viewers sorted by join order with snapshot-local ordinals and relative+// durations; operation is nil unless its demand peer has an ordinal.+func (c *Controller) RouteDiagnosticSnapshot(nowMs int64) protocol.RouteDiagnosticSnapshot {+ viewers := []*participant{}+ for _, current := range c.participants.Values() {+ if current.role == protocol.RoleViewer && current.sessionID != "" && !current.departureConfirmed {+ viewers = append(viewers, current)+ }+ }+ sort.SliceStable(viewers, func(i, j int) bool { return compareParticipant(viewers[i], viewers[j]) < 0 })+ ordinals := make(map[string]int, len(viewers))+ for index, viewer := range viewers {+ ordinals[viewer.peerID] = index + 1+ }+ children := make([]protocol.RouteDiagnosticChild, 0, len(viewers))+ for _, viewer := range viewers {+ edge, _ := c.upstreamByViewer.Get(viewer.peerID)+ record := c.routeTimings[viewer.peerID]+ finalRoute := c.currentFinalRoute(viewer.peerID)+ childCount := 0+ for _, childPeerID := range c.childrenOf(viewer.peerID) {+ if childEdge, ok := c.upstreamByViewer.Get(childPeerID); ok && childEdge.Kind == UpstreamPeer && childEdge.PhysicalActive {+ childCount+++ }+ }+ child := protocol.RouteDiagnosticChild{+ Ordinal: protocol.Int(ordinals[viewer.peerID]),+ Parent: c.diagnosticParent(edge, ordinals),+ EffectiveCapacity: protocol.Int(viewer.effectiveDownstreamCapacity),+ ChildCount: protocol.Int(childCount),+ FinalRoute: string(finalRoute),+ RejectionBucket: string(RejectionNone),+ Quality: c.diagnosticQuality(viewer.peerID, edge, nowMs),+ }+ if record != nil {+ child.DemandAgeMs = elapsedMs(record.demandAtMs, nowMs)+ if record.operationStartedAtMs != nil {+ child.QueueWaitMs = elapsedMs(record.demandAtMs, *record.operationStartedAtMs)+ }+ if record.candidateStartedAtMs != nil {+ child.CandidateStartMs = elapsedMs(record.demandAtMs, *record.candidateStartedAtMs)+ }+ if record.firstDecodedFrameAtMs != nil {+ child.FirstDecodedFrameMs = elapsedMs(record.demandAtMs, *record.firstDecodedFrameAtMs)+ }+ if record.finalAtMs != nil {+ child.FinalMs = elapsedMs(record.demandAtMs, *record.finalAtMs)+ }+ child.RejectionBucket = string(record.rejectionBucket)+ }+ if finalRoute == FinalRouteWaiting {+ child.FinalRoute = string(FinalRouteWaiting)+ if record != nil && record.finalRoute == FinalRouteFailed {+ child.FinalRoute = string(FinalRouteFailed)+ }+ }+ children = append(children, child)+ }+ var diagnosticOperation *protocol.RouteDiagnosticOperation+ if op := c.operation; op != nil {+ if childOrdinal, ok := ordinals[op.demandPeerID]; ok {+ stage := "admission"+ if op.current != nil {+ stage = "first-frame"+ if op.current.mediaReady {+ stage = "quality-proof"+ }+ }+ diagnosticOperation = &protocol.RouteDiagnosticOperation{+ ChildOrdinal: protocol.Int(childOrdinal),+ Reason: string(op.reason),+ Stage: stage,+ Cursor: protocol.Int(op.cursor),+ CandidateCount: protocol.Int(len(op.candidates)),+ }+ }+ }+ return protocol.RouteDiagnosticSnapshot{Children: children, Operation: diagnosticOperation}+}++// UpsertParticipant adds or updates a participant, aborting an operation+// that used a replaced session; a viewer without a usable route records a+// "join" demand when nowMs is non-nil. Panics on a Host/role inconsistency.+func (c *Controller) UpsertParticipant(input ParticipantInput, nowMs *int64) []*Resource {+ if (input.PeerID == c.hostPeerID) != (input.Role == protocol.RoleHost) {+ panic(errors.New("Route Host identity is inconsistent"))+ }+ capacity := c.effectiveCapacity(input.EffectiveDownstreamCapacity)+ current, _ := c.participants.Get(input.PeerID)+ released := []*Resource{}+ if current != nil && current.role != input.Role {+ panic(errors.New("Route role cannot change"))+ }+ if current != nil {+ changed := false+ previousSessionID := current.sessionID+ if previousSessionID != input.SessionID {+ c.clearOpportunitiesForSessionChange(input.PeerID, input.Role)+ c.clearQualityForParticipant(input.PeerID)+ if c.operationUsesParticipantSession(input.PeerID) {+ released = append(released, c.abortOperation(nowMs, RejectionStale)...)+ }+ c.directContinuations.Delete(input.PeerID)+ c.clearSfuBootstrapForDemand(input.PeerID)+ current.sessionID = input.SessionID+ c.rebindCommittedSession(input.PeerID, input.SessionID)+ changed = true+ }+ if current.departureConfirmed {+ current.departureConfirmed = false+ changed = true+ }+ if current.effectiveDownstreamCapacity != capacity {+ current.effectiveDownstreamCapacity = capacity+ changed = true+ }+ if changed {+ c.touchFacts()+ c.debug("participant-updated",+ "participant", c.debugPeer(input.PeerID),+ "capacity", capacity,+ "sessionChanged", previousSessionID != input.SessionID)+ }+ if input.Role == protocol.RoleViewer && nowMs != nil && !c.usableRoute(input.PeerID) {+ c.recordDemand(input.PeerID, *nowMs, DemandJoin)+ }+ return released+ }+ // A new key appends to the insertion order (TS Map.set at 573).+ c.participants.Set(input.PeerID, &participant{+ peerID: input.PeerID,+ role: input.Role,+ sessionID: input.SessionID,+ effectiveDownstreamCapacity: capacity,+ joinOrder: c.nextJoinOrder,+ })+ c.nextJoinOrder+++ c.debug("participant-joined",+ "participant", c.debugPeer(input.PeerID),+ "role", input.Role,+ "capacity", capacity)+ if input.Role == protocol.RoleViewer && nowMs != nil {+ c.recordDemand(input.PeerID, *nowMs, DemandJoin)+ }+ c.touchFacts()+ return released+}++// RebindHostIdentity moves the Host to a new peer ID (same ID delegates to+// UpsertParticipant), tearing down the whole graph and returning every SFU+// subscription, the publication and the aborted reservation, deduplicated.+func (c *Controller) RebindHostIdentity(peerID, sessionID string, nowMs *int64) []*Resource {+ previousPeerID := c.hostPeerID+ if peerID == previousPeerID {+ return c.UpsertParticipant(ParticipantInput{+ PeerID: peerID,+ Role: protocol.RoleHost,+ SessionID: sessionID,+ EffectiveDownstreamCapacity: c.endpointMediaCopyCapacity,+ }, nowMs)+ }+ if c.participants.Has(peerID) {+ panic(errors.New("Route Host identity collides with another participant"))+ }+ host, _ := c.participants.Get(previousPeerID)+ if host == nil || host.role != protocol.RoleHost {+ panic(errors.New("Route Host identity is unavailable"))+ }++ // Ordering site §4.5 #38: aborted reservation, then SFU edges in map+ // order, then the publication, deduplicated.+ released := &resourceSet{}+ if c.operation != nil {+ released.add(c.abortOperation(nowMs, RejectionStale)...)+ }+ for _, edge := range c.upstreamByViewer.Values() {+ if edge.Kind == UpstreamSfu && edge.PhysicalActive {+ released.add(edge.Resource)+ }+ }+ if c.hostPublication != nil && c.hostPublication.PhysicalActive {+ released.add(c.hostPublication.Resource)+ }+ c.upstreamByViewer.Clear()+ c.hostPublication = nil+ clear(c.routeTimings)+ clear(c.qualityObservations)+ clear(c.senderQualityObservations)+ clear(c.senderQualityBaselines)+ clear(c.senderQualityRegenerationBlocks)+ clear(c.qualityBaselinesPending)+ c.sfuPublisherQualityObservation = nil+ c.directContinuations.Clear()+ c.retiringPublicationGenerations.Clear()+ c.sfuBootstrapIntent = nil+ c.consumedSfuBootstrapOpportunities.Clear()+ c.rootConvergenceRootPeerID = ""+ // Ordering site §4.1 #2: demand is re-recorded in participants order.+ for _, current := range c.participants.Values() {+ current.availabilityExhausted = false+ current.bootstrapFailureReported = false+ current.sfuFirstAtNextRoute = false+ current.consumedCandidateOpportunities.Clear()+ if current.role == protocol.RoleViewer && current.sessionID != "" && nowMs != nil {+ c.recordDemand(current.peerID, *nowMs, DemandEdgeUnavailable)+ }+ }++ // Ordering site §4.1 #1: delete + set moves the Host to the tail of the+ // insertion order while it keeps its joinOrder.+ c.participants.Delete(previousPeerID)+ host.peerID = peerID+ host.sessionID = sessionID+ host.departureConfirmed = false+ c.participants.Set(peerID, host)+ c.hostPeerID = peerID+ c.revision = c.allocateRevision()+ c.touchFacts()+ c.assertGraph()+ return released.resources()+}++// DisconnectSession marks the participant's exact session as gone (grace+// state, no revision change); false when the session does not match.+func (c *Controller) DisconnectSession(peerID, sessionID string) bool {+ current, _ := c.participants.Get(peerID)+ if current == nil || !current.sessionIs(sessionID) {+ return false+ }+ c.clearOpportunitiesForSessionChange(peerID, current.role)+ current.sessionID = ""+ c.clearQualityForParticipant(peerID)+ c.directContinuations.Delete(peerID)+ c.clearSfuBootstrapForDemand(peerID)+ c.touchFacts()+ c.debug("participant-disconnected", "participant", c.debugPeer(peerID))+ return true+}++// ConfirmDeparture finalises a viewer's departure (capacity 0, demand+// recorded for its children when nowMs is non-nil); false for the Host or+// an unknown peer; idempotent.+func (c *Controller) ConfirmDeparture(peerID string, nowMs *int64) bool {+ current, _ := c.participants.Get(peerID)+ if current == nil || current.role == protocol.RoleHost {+ return false+ }+ delete(c.routeTimings, peerID)+ if current.departureConfirmed && current.sessionID == "" && current.effectiveDownstreamCapacity == 0 {+ return true+ }+ c.clearOpportunitiesForSessionChange(peerID, current.role)+ current.sessionID = ""+ c.clearQualityForParticipant(peerID)+ current.departureConfirmed = true+ current.effectiveDownstreamCapacity = 0+ c.directContinuations.Delete(peerID)+ c.clearSfuBootstrapForDemand(peerID)+ if nowMs != nil {+ for _, childPeerID := range c.childrenOf(peerID) {+ c.recordDemand(childPeerID, *nowMs, DemandParentDeparted)+ }+ }+ c.touchFacts()+ c.debug("participant-departed", "participant", c.debugPeer(peerID))+ return true+}++// SetEffectiveCapacity clamps and stores the participant's downstream+// capacity for the matching session; true even when unchanged (facts are+// touched only on change).+func (c *Controller) SetEffectiveCapacity(peerID, sessionID string, value int, nowMs *int64) bool {+ current, _ := c.participants.Get(peerID)+ if current == nil || !current.sessionIs(sessionID) {+ return false+ }+ capacity := c.effectiveCapacity(value)+ if current.effectiveDownstreamCapacity == capacity {+ return true+ }+ current.effectiveDownstreamCapacity = capacity+ if nowMs != nil {+ for _, childPeerID := range c.overflowPeerChildren(peerID) {+ c.recordDemand(childPeerID, *nowMs, DemandCapacityReduction)+ }+ }+ c.touchFacts()+ c.debug("capacity-updated", "participant", c.debugPeer(peerID), "capacity", capacity)+ return true+}++// TouchExternalFacts reopens every SFU opportunity after an external fact+// change (for example a share generation) and bumps the fact version.+func (c *Controller) TouchExternalFacts() {+ c.clearSfuCandidateOpportunities()+ c.sfuBootstrapIntent = nil+ c.touchFacts()+}++// hydrateEdge installs a committed edge for a connected viewer while no+// operation is active, without changing revision or fact version. Panics+// on an active operation, a non-viewer child or a child without a session.+func (c *Controller) hydrateEdge(childPeerID string, edge committedEdgeSeed) {+ if c.operation != nil {+ panic(errors.New("Cannot hydrate while an operation is active"))+ }+ c.assertViewer(childPeerID)+ child, _ := c.participants.Get(childPeerID)+ childSessionID := child.sessionID+ if childSessionID == "" {+ panic(errors.New("Route child has no current session"))+ }+ committed := &CommittedEdge{+ Kind: edge.Kind,+ ChildSessionID: childSessionID,+ ParentPeerID: edge.ParentPeerID,+ PublicationGeneration: edge.PublicationGeneration,+ Transport: edge.Transport,+ ConnectionID: edge.ConnectionID,+ Usable: edge.Usable,+ PhysicalActive: edge.PhysicalActive,+ Resource: edge.Resource,+ }+ if edge.Kind == UpstreamPeer {+ // TS 750: `this.participants.get(edge.parentPeerId)?.sessionId ?? ""`.+ if parent, ok := c.participants.Get(edge.ParentPeerID); ok {+ committed.ParentSessionID = parent.sessionID+ }+ }+ // Map.set keeps the position of an existing child (§4.2 #15).+ c.upstreamByViewer.Set(childPeerID, committed)+ c.requireSenderQualityBaseline(childPeerID, false)+ c.assertGraph()+}++// hydrateHostPublication installs a usable, physically active publication+// while no operation is active; connectionID empty selects the TS default+// "publication:<generation>". Panics on an active operation or a Host+// without a session.+func (c *Controller) hydrateHostPublication(generation string, resource *Resource, connectionID string) {+ if c.operation != nil {+ panic(errors.New("Cannot hydrate while an operation is active"))+ }+ host, _ := c.participants.Get(c.hostPeerID)+ if host == nil || host.sessionID == "" {+ panic(errors.New("Route Host has no current session"))+ }+ if connectionID == "" {+ connectionID = "publication:" + generation+ }+ c.hostPublication = &HostPublication{+ Generation: generation,+ HostSessionID: host.sessionID,+ ConnectionID: connectionID,+ Usable: true,+ PhysicalActive: true,+ Resource: resource,+ }+ c.assertGraph()+}++// InvalidateEdge marks the exactly identified edge unusable and records an+// "edge-unavailable" demand; true when the guard matched (idempotent).+func (c *Controller) InvalidateEdge(guard EdgeGuard, nowMs *int64) bool {+ child, _ := c.participants.Get(guard.ChildPeerID)+ edge, _ := c.upstreamByViewer.Get(guard.ChildPeerID)+ if child == nil || !child.sessionIs(guard.ChildSessionID) || c.revision != guard.RouteRevision ||+ edge == nil || edge.ConnectionID != guard.ConnectionID ||+ edge.ChildSessionID != guard.ChildSessionID ||+ (edge.Kind == UpstreamPeer && edge.ParentSessionID != guard.ParentSessionID) {+ return false+ }+ if edge.Usable {+ c.consumeActiveEdgeOpportunity(child, edge)+ c.clearQualityForParticipant(guard.ChildPeerID)+ edge.Usable = false+ c.directContinuations.Delete(guard.ChildPeerID)+ child.availabilityExhausted = false+ child.bootstrapFailureReported = false+ c.touchFacts()+ if nowMs != nil {+ c.recordDemand(guard.ChildPeerID, *nowMs, DemandEdgeUnavailable)+ }+ }+ return true+}++// InvalidateDirectEdgeFromParent invalidates the first committed direct edge+// (insertion order) matching the parent-side guard.+func (c *Controller) InvalidateDirectEdgeFromParent(input ParentEdgeGuard, nowMs *int64) bool {+ // Ordering site §4.2 #10: first match in insertion order wins.+ for childPeerID, edge := range c.upstreamByViewer.All() {+ if edge.Kind == UpstreamPeer &&+ edge.ParentPeerID == input.ParentPeerID &&+ edge.ParentSessionID == input.ParentSessionID &&+ edge.ConnectionID == input.ConnectionID {+ return c.InvalidateEdge(EdgeGuard{+ ChildPeerID: childPeerID,+ ChildSessionID: edge.ChildSessionID,+ ParentSessionID: input.ParentSessionID,+ RouteRevision: input.RouteRevision,+ ConnectionID: input.ConnectionID,+ }, nowMs)+ }+ }+ return false+}++// InvalidateHostPublication marks the identified publication unusable and+// records demand for every SFU child; true when the guard matched (idempotent).+func (c *Controller) InvalidateHostPublication(guard PublicationGuard, nowMs *int64) bool {+ publication := c.hostPublication+ if publication == nil || c.revision != guard.RouteRevision ||+ publication.HostSessionID != guard.HostSessionID ||+ publication.Generation != guard.Generation ||+ publication.ConnectionID != guard.ConnectionID {+ return false+ }+ if publication.Usable {+ c.clearSfuQuality()+ publication.Usable = false+ c.directContinuations.Clear()+ c.sfuBootstrapIntent = nil+ if nowMs != nil {+ for childPeerID, edge := range c.upstreamByViewer.All() {+ if edge.Kind == UpstreamSfu {+ c.recordDemand(childPeerID, *nowMs, DemandEdgeUnavailable)+ }+ }+ }+ c.touchFacts()+ }+ return true+}++// AdoptDirectConnection rewrites the connection ID of a usable, active+// direct edge the operation does not own; true when adopted (no-op when+// unchanged).+func (c *Controller) AdoptDirectConnection(input AdoptDirectConnectionInput) bool {+ edge, _ := c.upstreamByViewer.Get(input.ChildPeerID)+ if (c.operation != nil && c.operation.childPeerID == input.ChildPeerID) ||+ c.revision != input.RouteRevision ||+ edge == nil ||+ edge.Kind != UpstreamPeer ||+ edge.Transport != TransportDirect ||+ !edge.Usable ||+ !edge.PhysicalActive ||+ edge.ChildSessionID != input.ChildSessionID ||+ edge.ParentSessionID != input.ParentSessionID ||+ edge.ConnectionID != input.ConnectionID ||+ input.NewConnectionID == "" {+ return false+ }+ if input.NewConnectionID == edge.ConnectionID {+ return true+ }+ c.clearQualityForParticipant(input.ChildPeerID)+ edge.ConnectionID = input.NewConnectionID+ if child, ok := c.participants.Get(input.ChildPeerID); ok {+ child.availabilityExhausted = false+ }+ c.touchFacts()+ return true+}++// RetireHostPublication retires the physically active publication and its+// subscriptions when no attempt is live and the guard matches, returning the+// subscriptions then the publication resource; empty otherwise.+func (c *Controller) RetireHostPublication(guard PublicationGuard) []*Resource {+ publication := c.hostPublication+ if (c.operation != nil && c.operation.current != nil) || publication == nil || !publication.PhysicalActive ||+ c.revision != guard.RouteRevision ||+ publication.HostSessionID != guard.HostSessionID ||+ publication.Generation != guard.Generation ||+ publication.ConnectionID != guard.ConnectionID {+ return []*Resource{}+ }+ // Ordering site §4.2 #11: subscriptions in map order, then the publication.+ released := []*Resource{}+ for viewerPeerID, edge := range c.upstreamByViewer.All() {+ if edge.Kind == UpstreamSfu && edge.PublicationGeneration == publication.Generation {+ c.retireSfuEdge(viewerPeerID, edge, &released, c.retainsAnchor(viewerPeerID))+ }+ }+ publication.PhysicalActive = false+ publication.Usable = false+ c.hostPublication = nil+ c.clearSfuQuality()+ c.revision = c.allocateRevision()+ if c.operation != nil {+ c.operation.baseRevision = c.revision+ }+ c.touchFacts()+ released = append(released, publication.Resource)+ c.pruneRetiringSfuAnchors()+ return released+}++// SetPaused pauses (aborting the operation and clearing quality state) or+// resumes; returns the aborted reservation's resources.+func (c *Controller) SetPaused(paused bool, nowMs *int64) []*Resource {+ if c.paused == paused {+ return []*Resource{}+ }+ c.paused = paused+ if paused {+ clear(c.qualityObservations)+ clear(c.qualityBaselinesPending)+ clear(c.senderQualityObservations)+ clear(c.senderQualityBaselines)+ clear(c.senderQualityRegenerationBlocks)+ c.sfuPublisherQualityObservation = nil+ }+ c.touchFacts()+ if paused {+ return c.abortOperation(nowMs, RejectionAborted)+ }+ return []*Resource{}+}++// Dispose clears all state, pauses the controller and returns the live+// reservation's resources then every committed resource, deduplicated.+func (c *Controller) Dispose() []*Resource {+ // Ordering site §4.5 #39: reservation first, then committed resources.+ resources := &resourceSet{}+ if c.operation != nil && c.operation.current != nil {+ resources.add(reservationResources(c.operation.current.reservation)...)+ }+ resources.add(c.committedResources()...)+ c.operation = nil+ c.upstreamByViewer.Clear()+ clear(c.qualityObservations)+ clear(c.qualityBaselinesPending)+ clear(c.senderQualityObservations)+ clear(c.senderQualityBaselines)+ clear(c.senderQualityRegenerationBlocks)+ c.sfuPublisherQualityObservation = nil+ c.hostPublication = nil+ c.participants.Clear()+ clear(c.routeTimings)+ c.directContinuations.Clear()+ c.retiringPublicationGenerations.Clear()+ c.sfuBootstrapIntent = nil+ c.consumedSfuBootstrapOpportunities.Clear()+ c.rootConvergenceRootPeerID = ""+ // nextJoinOrder, revision, latestRevision and factVersion survive (TS 2314-2339).+ c.paused = true+ return resources.resources()+}++// abortOperation ports the private abortOperation (4050): finishes the+// demand timing when nowMs is given, releases the live reservation and+// clears the operation.+func (c *Controller) abortOperation(nowMs *int64, bucket RejectionBucket) []*Resource {+ if c.operation == nil {+ return []*Resource{}+ }+ if nowMs != nil {+ c.finishTiming(c.operation.demandPeerID, *nowMs, c.currentFinalRoute(c.operation.demandPeerID), bucket, false)+ }+ op := c.operation+ released := []*Resource{}+ if op.current != nil {+ released = reservationResources(op.current.reservation)+ c.advanceActiveRevision(op)+ }+ c.operation = nil+ return released+}++// operationUsesParticipantSession ports 4072.+func (c *Controller) operationUsesParticipantSession(peerID string) bool {+ op := c.operation+ if op == nil {+ return false+ }+ if op.childPeerID == peerID || op.demandPeerID == peerID {+ return true+ }+ tuple := op.currentTuple()+ if tuple != nil && tuple.Kind == UpstreamPeer {+ return tuple.ParentPeerID == peerID+ }+ return peerID == c.hostPeerID+}++// effectiveCapacity ports 4925: panics "Effective capacity is invalid" for+// a negative or unsafe value and clamps to the endpoint capacity.+func (c *Controller) effectiveCapacity(value int) int {+ if !isSafeInteger(int64(value)) || value < 0 {+ panic(errors.New("Effective capacity is invalid"))+ }+ return min(value, c.endpointMediaCopyCapacity)+}++func (c *Controller) touchFacts() { c.factVersion++ }++// allocateRevision ports 4932; the revision space is MAX_SAFE_INTEGER.+func (c *Controller) allocateRevision() int64 {+ if c.latestRevision >= protocol.MaxMediaRouteRevision {+ panic(errors.New("Media route revision space exhausted"))+ }+ c.latestRevision+++ return c.latestRevision+}++// isSafeInteger is Number.isSafeInteger for a value that is already integral.+func isSafeInteger(value int64) bool {+ return value >= -maxSafeInteger && value <= maxSafeInteger+}++// compareParticipant ports 4939. joinOrder is allocated once per+// participant (573-577) and preserved across rebindHostIdentity, so two live+// participants never share one and the TS localeCompare (ICU) tiebreak is+// unreachable; strings.Compare stands in for it.+func compareParticipant(left, right *participant) int {+ if left.joinOrder != right.joinOrder {+ if left.joinOrder < right.joinOrder {+ return -1+ }+ return 1+ }+ return strings.Compare(left.peerID, right.peerID)+}++// stablePairRank ports 4955: the first 6 bytes, big-endian, of+// sha256(child + "\0" + parent). Byte-exact: it breaks parent ties.+func stablePairRank(childPeerID, parentPeerID string) int64 {+ sum := sha256.Sum256([]byte(childPeerID + "\x00" + parentPeerID))+ var rank int64+ for _, b := range sum[:6] {+ rank = rank<<8 | int64(b)+ }+ return rank+}++// safeAdd ports 4969. JS Math.round is half-up while math.Round is+// half-away-from-zero; they differ only for negative halves, which the+// `rounded < 0` branch drops either way. NaN and +/-Inf drop the window.+func safeAdd(total int64, delta float64) int64 {+ rounded := math.Round(delta)+ if math.IsNaN(rounded) || math.IsInf(rounded, 0) || rounded < 0 || rounded > float64(maxSafeInteger) {+ return total+ }+ value := int64(rounded)+ if value > maxSafeInteger-total {+ return maxSafeInteger+ }+ return total + value+}diff --git a/internal/server/route/controller_test.go b/internal/server/route/controller_test.gonew file mode 100644index 00000000..8b5465f2--- /dev/null+++ b/internal/server/route/controller_test.go@@ -0,0 +1,2866 @@+package route++// Oracle port of tests/room-route-controller.test.ts. Each test keeps the TS+// title and line as a comment; every nowMs is the explicit literal the TS+// used, so nothing here needs a clock.++import (+ "encoding/json"+ "fmt"+ "regexp"+ "slices"+ "strings"+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// TS 359: keeps one diagnostic label until a departed relay is finally pruned+func TestKeepsOneDiagnosticLabelUntilDepartedRelayIsPruned(t *testing.T) {+ routes := newController(2, Options{})+ addViewer(routes, A, 1, nil)+ addViewer(routes, B, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(A, "b_from_a"))+ label := routes.DiagnosticParticipantLabel(A)+ if !regexp.MustCompile(`^viewer-\d+$`).MatchString(label) {+ t.Fatalf("label %q is not viewer-<n>", label)+ }++ routes.UpsertParticipant(viewerInput(A, "a_replacement_session", 1), nil)+ eq(t, routes.DiagnosticParticipantLabel(A), label)+ eq(t, routes.DisconnectSession(A, "a_replacement_session"), true)+ eq(t, routes.DiagnosticParticipantLabel(A), label)+ eq(t, routes.ConfirmDeparture(A, ms(0)), true)+ eq(t, routes.DiagnosticParticipantLabel(A), label)++ repair := must(t, routes.Reconcile(1).Operation)+ eq(t, repair.ChildPeerID, B)+ eq(t, repair.Reason, DemandParentDeparted)+ commitCurrent(t, routes, 2, "b_from_host")+ pruned := routes.Reconcile(4)+ if !slices.Contains(pruned.RemovedPeerIDs, A) {+ t.Fatalf("removedPeerIds %v does not contain A", pruned.RemovedPeerIDs)+ }+ eq(t, routes.DiagnosticParticipantLabel(A), "viewer-unknown")++ addViewer(routes, C, 0, nil)+ if routes.DiagnosticParticipantLabel(C) == label {+ t.Fatalf("C reused label %q", label)+ }+}++// TS 394: clears an unknown sender run without rearming its healthy baseline+func TestClearsUnknownSenderRunWithoutRearmingHealthyBaseline(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ for _, seed := range [][2]string{{A, "a_from_host"}, {B, "b_from_host"}} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: seed[0], connectionID: seed[1], state: SenderQualityHealthy, acceptedAtMs: 0,+ }).Accepted, true)+ }+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: 1,+ }).Accepted, true)+ eq(t, routes.ObserveSenderQualityEvidence(unknownSample(HOST, A, routes.Snapshot().Revision, "a_from_host", 2), nil).Accepted, true)++ for _, acceptedAtMs := range []int64{3, 4, 5} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ }+ operation := must(t, routes.Reconcile(6).Operation)+ eq(t, operation.ChildPeerID, A)+ eq(t, operation.Reason, DemandQualityConvergence)+}++// TS 448: consumes a quality candidate rejected at preparation instead of rebuilding it+func TestConsumesQualityCandidateRejectedAtPreparation(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 0)+ first := must(t, routes.Reconcile(10).Operation)+ eq(t, first.ChildPeerID, A)+ eq(t, first.Reason, DemandQualityConvergence)+ rejected := first.Candidates[first.Cursor].Tuple++ operation := first+ for round := 0; operation != nil && round < 4; round++ {+ if round > 0 && slices.Contains(tuplesFrom(operation, operation.Cursor), rejected) {+ t.Fatalf("round %d rebuilt the rejected tuple %+v", round, rejected)+ }+ eq(t, routes.SkipCurrentCandidate(cursorGuard(operation), int64(11+round), RejectionStale).Accepted, true)+ operation = routes.Reconcile(int64(12 + round)).Operation+ }+ noOperation(t, operation)+}++// TS 480: lets a newly committed availability edge report persistent degradation before healthy+func TestNewlyCommittedEdgeReportsPersistentDegradationBeforeHealthy(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ addViewer(routes, A, 2, ms(0))+ joined := must(t, routes.Reconcile(0).Operation)+ eq(t, joined.ChildPeerID, A)+ commitCurrent(t, routes, 1, "a_from_host")++ for _, acceptedAtMs := range []int64{2, 3, 4} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ }++ operation := must(t, routes.Reconcile(5).Operation)+ eq(t, operation.ChildPeerID, A)+ eq(t, operation.Reason, DemandQualityConvergence)+}++// TS 506: starts a fresh degradation run when an availability sender identity changes+func TestStartsFreshDegradationRunWhenSenderIdentityChanges(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ addViewer(routes, A, 2, ms(0))+ routes.Reconcile(0)+ commitCurrent(t, routes, 1, "a_from_host")++ observe := func(identity string, at int64) {+ t.Helper()+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", senderIdentity: identity, state: SenderQualityDegraded, acceptedAtMs: at,+ }).Accepted, true)+ }+ observe("old-rtp\x00track", 2)+ observe("old-rtp\x00track", 3)+ observe("new-rtp\x00track", 4)+ noOperation(t, routes.Reconcile(4).Operation)+ observe("new-rtp\x00track", 5)+ observe("new-rtp\x00track", 6)+ operation := must(t, routes.Reconcile(7).Operation)+ eq(t, operation.ChildPeerID, A)+ eq(t, operation.Reason, DemandQualityConvergence)+}++// TS 566: lets a reset sender begin a new degradation run without a healthy sample+func TestResetSenderBeginsNewDegradationRunWithoutHealthySample(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ addViewer(routes, A, 2, ms(0))+ routes.Reconcile(0)+ commitCurrent(t, routes, 1, "a_from_host")+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityHealthy, acceptedAtMs: 2,+ }).Accepted, true)++ routes.ResetSenderQuality(HOST, "host_session", 3)+ for _, acceptedAtMs := range []int64{4, 5, 6} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ }+ operation := must(t, routes.Reconcile(7).Operation)+ eq(t, operation.ChildPeerID, A)+ eq(t, operation.Reason, DemandQualityConvergence)+}++// TS 599: regenerates a persistently degraded edge on the same parent+func TestRegeneratesPersistentlyDegradedEdgeOnSameParent(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 10)++ operation := must(t, routes.Reconcile(14).Operation)+ eq(t, len(operation.Candidates), 1)+ eq(t, operation.Candidates[0].Tuple, regenerateTuple(HOST))+ expectTransition(t, operation.Candidates[0].EndpointTransition, TransitionNone, HOST)++ begin := beginOperation(t, routes, BeginInput{NowMs: 15, ConnectionID: "a_regenerated", Reservation: direct()})+ edge := edgeOf(t, routes, A)+ eq(t, edge.ParentPeerID, HOST)+ eq(t, edge.ConnectionID, "a_from_host")+ eq(t, edge.Usable, true)+ eq(t, edge.PhysicalActive, true)+ guard := guardFor(A, begin.Current.Revision, "a_regenerated")+ ready := routes.CandidateReady(guard, 16, nil, CandidateProof{RelativeQualityApproved: true})+ eq(t, ready.Accepted, true)+ eq(t, ready.Committed, false)++ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ HOST, A, begin.Current.Revision, "a_regenerated", "a-regenerated-rtp\x00track", SenderQualityHealthy, 17), nil).Committed, true)+ edge = edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ParentPeerID, HOST)+ eq(t, edge.ConnectionID, "a_regenerated")+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_regenerated", senderIdentity: "a-regenerated-rtp\x00track",+ state: SenderQualityHealthy, acceptedAtMs: 18,+ }).Accepted, true)+ for _, acceptedAtMs := range []int64{19, 20, 21} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_regenerated", senderIdentity: "a-regenerated-rtp\x00track",+ state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ }+ eq(t, must(t, routes.Reconcile(22).Operation).Candidates[0].Tuple, regenerateTuple(HOST))+}++// TS 686: keeps same-edge regeneration damped while allowing a different parent+func TestKeepsSameEdgeRegenerationDampedWhileAllowingDifferentParent(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 10)++ routes.Reconcile(14)+ begin := beginOperation(t, routes, BeginInput{NowMs: 15, ConnectionID: "a_regenerated", Reservation: direct()})+ guard := guardFor(A, begin.Current.Revision, "a_regenerated")+ routes.CandidateReady(guard, 16, nil, CandidateProof{RelativeQualityApproved: true})+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ HOST, A, begin.Current.Revision, "a_regenerated", "a-regenerated-rtp\x00track", SenderQualityHealthy, 17), nil).Committed, true)++ for _, acceptedAtMs := range []int64{18, 19, 20} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_regenerated", senderIdentity: "a-regenerated-rtp\x00track",+ state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ }+ noOperation(t, routes.Reconcile(21).Operation)++ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ eq(t, observeSenderState(routes, senderState{+ childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 22,+ }).Accepted, true)+ withAlternate := must(t, routes.Reconcile(23).Operation)+ eq(t, withAlternate.ChildPeerID, A)+ eq(t, withAlternate.Reason, DemandQualityConvergence)+ eqSlice(t, tuples(withAlternate), []CandidateTuple{peerTuple(B)})+}++// TS 754: uses the existing one-slot overlap for same-parent regeneration+func TestUsesExistingOneSlotOverlapForSameParentRegeneration(t *testing.T) {+ routes := newController(1, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 1, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 10)++ operation := must(t, routes.Reconcile(14).Operation)+ expectTransition(t, operation.Candidates[0].EndpointTransition, TransitionOverlap, HOST)+ begin := beginOperation(t, routes, BeginInput{NowMs: 15, ConnectionID: "a_regenerated", Reservation: directOverlap("a_overlap")})+ guard := guardFor(A, begin.Current.Revision, "a_regenerated")+ routes.CandidateReady(guard, 16, nil, CandidateProof{RelativeQualityApproved: true})+ committed := routes.ObserveSenderQualityEvidence(senderSample(+ HOST, A, begin.Current.Revision, "a_regenerated", "a-regenerated-rtp\x00track", SenderQualityHealthy, 17), nil)+ eq(t, committed.Committed, true)+ containsLabels(t, committed.Released, "a_overlap")+}++// TS 794: keeps one quality experiment through inconclusive current windows+func TestKeepsOneQualityExperimentThroughInconclusiveWindows(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 9})+ observePersistentDegraded(t, routes, A, "a_from_host", 10)++ operation := must(t, routes.Reconcile(14).Operation)+ eqSlice(t, tuples(operation), []CandidateTuple{peerTuple(B), regenerateTuple(HOST)})+ beginCandidate(t, routes, BeginInput{NowMs: 15, ConnectionID: "a_from_b_failed", Reservation: direct()})++ currentRevision := routes.Snapshot().Revision+ eq(t, routes.ObserveSenderQualityEvidence(unknownSample(HOST, A, currentRevision, "a_from_host", 16), nil).Accepted, true)+ pending := must(t, routes.Snapshot().Operation)+ eq(t, pending.Reason, DemandQualityConvergence)+ eq(t, pending.Cursor, 0)++ afterFirst := routes.OperationExpired(must(t, routes.Snapshot().Operation).WakeAtMs)+ eq(t, afterFirst.Accepted, true)+ pending = must(t, routes.Snapshot().Operation)+ eq(t, pending.Reason, DemandQualityConvergence)+ eq(t, pending.Cursor, 1)+ regeneration := beginOperation(t, routes, BeginInput{+ NowMs: 20, ConnectionID: "a_regeneration_failed", Reservation: directOverlap("a_regeneration_overlap"),+ })+ eq(t, routes.CandidateFailed(guardFor(A, regeneration.Current.Revision, "a_regeneration_failed"), 21).Accepted, true)+ noOperation(t, routes.Snapshot().Operation)++ for _, acceptedAtMs := range []int64{22, 23, 24} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ }+ noOperation(t, routes.Reconcile(25).Operation)+ routes.TouchExternalFacts()+ noOperation(t, routes.Reconcile(26).Operation)++ addViewer(routes, C, 2, nil)+ routes.hydrateEdge(C, peerEdge(B, "c_from_b"))+ observeSenderState(routes, senderState{+ childPeerID: C, connectionID: "c_from_b", parentPeerID: B, state: SenderQualityHealthy, acceptedAtMs: 27,+ })+ newOpportunity := must(t, routes.Reconcile(28).Operation)+ eq(t, newOpportunity.ChildPeerID, A)+ eq(t, newOpportunity.Reason, DemandQualityConvergence)+ eqSlice(t, tuples(newOpportunity), []CandidateTuple{peerTuple(C)})+}++// TS 902: does not restart a quality candidate set after its total deadline+func TestDoesNotRestartQualityCandidateSetAfterTotalDeadline(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 9})+ observePersistentDegraded(t, routes, A, "a_from_host", 10)++ operation := must(t, routes.Reconcile(14).Operation)+ beginCandidate(t, routes, BeginInput{NowMs: 15, ConnectionID: "a_from_b_pending", Reservation: direct()})+ eq(t, routes.OperationExpired(operation.DeadlineAtMs).Accepted, true)+ noOperation(t, routes.Snapshot().Operation)+ noOperation(t, routes.Reconcile(operation.DeadlineAtMs+1).Operation)+ routes.TouchExternalFacts()+ noOperation(t, routes.Reconcile(operation.DeadlineAtMs+2).Operation)++ observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityHealthy, acceptedAtMs: operation.DeadlineAtMs + 3,+ })+ for _, acceptedAtMs := range []int64{operation.DeadlineAtMs + 4, operation.DeadlineAtMs + 5, operation.DeadlineAtMs + 6} {+ observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ })+ }+ eq(t, must(t, routes.Reconcile(operation.DeadlineAtMs+7).Operation).Reason, DemandQualityConvergence)+}++// TS 951: keeps isolated limitation windows diagnostic+func TestKeepsIsolatedLimitationWindowsDiagnostic(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 99})+ observeSenderState(routes, senderState{childPeerID: A, connectionID: "a_from_host", state: SenderQualityHealthy, acceptedAtMs: 99})+ observeSenderState(routes, senderState{childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: 100})+ repeated := senderSample(HOST, A, routes.Snapshot().Revision, "a_from_host", "a_from_host-rtp\x00track", SenderQualityDegraded, 101)+ repeated.SampleTimestampMs = ms(100) // TS: sampleTimestampMs 100 with acceptedAtMs 101+ eq(t, routes.ObserveSenderQualityEvidence(repeated, nil).Accepted, true)+ noOperation(t, routes.Reconcile(101).Operation)+ for _, acceptedAtMs := range []int64{102} {+ observeSenderState(routes, senderState{childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs})+ noOperation(t, routes.Reconcile(acceptedAtMs).Operation)+ }+ observeSenderState(routes, senderState{childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: 103})+ operation := must(t, routes.Reconcile(104).Operation)+ eq(t, operation.ChildPeerID, A)+ eq(t, operation.Reason, DemandQualityConvergence)+}++// TS 1010: never treats one degraded Host edge as SFU fanout pressure+func TestNeverTreatsOneDegradedHostEdgeAsSfuFanoutPressure(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true, QualityConvergenceEnabled: true})+ addViewer(routes, A, 1, nil)+ addViewer(routes, B, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateHostPublication("publication_generation_12345678", res("publication_resource"), "")+ routes.hydrateEdge(B, sfuEdge("publication_generation_12345678", "b_from_sfu", "b_subscription"))+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ observePersistentSfuHealthy(t, routes, "publication_generation_12345678", routes.Snapshot().Revision, 103)+ operation := must(t, routes.Reconcile(104).Operation)+ eq(t, operation.Reason, DemandQualityConvergence)+ eq(t, len(operation.Candidates), 1)+ eq(t, operation.Candidates[0].Tuple, regenerateTuple(HOST))+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ParentPeerID, HOST)+}++// TS 1052: commits only after the Viewer approves a P2P receive improvement+func TestCommitsOnlyAfterViewerApprovesP2PReceiveImprovement(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ eq(t, observeSenderState(routes, senderState{+ childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 100,+ }).Accepted, true)+ observePersistentDegraded(t, routes, A, "a_from_host", 99)++ operation := must(t, routes.Reconcile(103).Operation)+ eq(t, operation.Reason, DemandQualityConvergence)+ eq(t, operation.Candidates[0].Tuple, peerTuple(B))+ begin := beginCandidate(t, routes, BeginInput{NowMs: 104, ConnectionID: "a_from_b", Reservation: direct()})+ current := must(t, begin.Operation).Current+ guard := guardFor(A, current.Revision, "a_from_b")+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ParentPeerID, HOST)+ eq(t, edge.ConnectionID, "a_from_host")+ ready := routes.CandidateReady(guard, 105, nil, CandidateProof{RelativeQualityApproved: true})+ eq(t, ready.Accepted, true)+ eq(t, ready.Committed, false)+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ B, A, current.Revision, "a_from_b", "a-from-b-rtp\x00a-track", SenderQualityHealthy, 106), nil).Committed, true)+ edge = edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ParentPeerID, B)+ eq(t, edge.ConnectionID, "a_from_b")++ migratedRevision := routes.Snapshot().Revision+ observeMigrated := func(state SenderQualityState, at int64) SenderQualityEvidenceResult {+ return routes.ObserveSenderQualityEvidence(senderSample(+ B, A, migratedRevision, "a_from_b", "a-from-b-rtp\x00a-track", state, at), nil)+ }+ for _, acceptedAtMs := range []int64{107, 108, 109} {+ eq(t, observeMigrated(SenderQualityDegraded, acceptedAtMs).Accepted, true)+ }+ noOperation(t, routes.Reconcile(110).Operation)+ routes.TouchExternalFacts()+ noOperation(t, routes.Reconcile(110).Operation)+ eq(t, observeMigrated(SenderQualityHealthy, 111).Accepted, true)+ eq(t, observeMigrated(SenderQualityDegraded, 112).Accepted, true)+ eq(t, observeMigrated(SenderQualityDegraded, 113).Accepted, true)+ eq(t, observeMigrated(SenderQualityDegraded, 114).Accepted, true)+ eq(t, must(t, routes.Reconcile(115).Operation).Reason, DemandQualityConvergence)+}++// TS 1147: uses one healthy serial operation to distribute a newly committed Host root+func TestUsesOneHealthySerialOperationToDistributeNewHostRoot(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, B, 2, nil)+ addViewer(routes, C, 0, nil)+ addViewer(routes, D, 0, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ routes.hydrateEdge(C, peerEdge(B, "c_from_b"))+ routes.hydrateEdge(D, peerEdge(B, "d_from_b"))+ addViewer(routes, A, 2, ms(10))++ joined := must(t, routes.Reconcile(10).Operation)+ eq(t, joined.Candidates[0].Tuple, peerTuple(HOST))+ commitCurrent(t, routes, 11, "a_from_host")++ convergence := must(t, routes.Reconcile(13).Operation)+ eq(t, convergence.Reason, DemandRootConvergence)+ eq(t, len(convergence.Candidates), 1)+ eq(t, convergence.Candidates[0].Tuple, peerTuple(A))+ eq(t, edgeOf(t, routes, convergence.ChildPeerID).ParentPeerID, B)++ prepared := beginOperation(t, routes, BeginInput{NowMs: 14, ConnectionID: "root_convergence_candidate", Reservation: direct()})+ guard := CandidateGuard{+ ChildPeerID: convergence.ChildPeerID,+ ChildSessionID: convergence.ChildSessionID,+ Revision: prepared.Current.Revision,+ ConnectionID: "root_convergence_candidate",+ }+ ready := routes.CandidateReady(guard, 15, nil, CandidateProof{})+ eq(t, ready.Accepted, true)+ eq(t, ready.Committed, false)+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ A, convergence.ChildPeerID, prepared.Current.Revision, "root_convergence_candidate", "root-rtp\x00track",+ SenderQualityHealthy, 16), nil).Committed, true)+ eq(t, edgeOf(t, routes, convergence.ChildPeerID).ParentPeerID, A)+ migratedChildPeerID := convergence.ChildPeerID+ for _, acceptedAtMs := range []int64{17, 18, 19} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: migratedChildPeerID, connectionID: "root_convergence_candidate", parentPeerID: A,+ state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ }+ noOperation(t, routes.Reconcile(20).Operation)+ eq(t, observeSenderState(routes, senderState{+ childPeerID: migratedChildPeerID, connectionID: "root_convergence_candidate", parentPeerID: A,+ state: SenderQualityHealthy, acceptedAtMs: 21,+ }).Accepted, true)+ for _, acceptedAtMs := range []int64{22, 23, 24} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: migratedChildPeerID, connectionID: "root_convergence_candidate", parentPeerID: A,+ state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ }+ eq(t, must(t, routes.Reconcile(25).Operation).Reason, DemandQualityConvergence)+}++// TS 1247: advances a silent Peer only when another bounded candidate remains+func TestAdvancesSilentPeerOnlyWhenAnotherBoundedCandidateRemains(t *testing.T) {+ routes := newController(2, Options{OperationTimeoutMs: 20_000})+ addViewer(routes, B, 2, nil)+ addViewer(routes, C, 2, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"))+ addViewer(routes, A, 0, ms(0))++ operation := must(t, routes.Reconcile(0).Operation)+ beginCandidate(t, routes, BeginInput{NowMs: 100, ConnectionID: "first_silent_candidate", Reservation: direct()})+ eq(t, must(t, routes.Snapshot().Operation).WakeAtMs, 5_100)+ eq(t, routes.OperationExpired(5_100).Accepted, true)++ beginCandidate(t, routes, BeginInput{NowMs: 5_200, ConnectionID: "second_silent_candidate", Reservation: direct()})+ eq(t, must(t, routes.Snapshot().Operation).WakeAtMs, operation.DeadlineAtMs)+ eq(t, must(t, routes.Snapshot().Operation).DeadlineAtMs, operation.DeadlineAtMs)+ eq(t, routes.OperationExpired(10_200).Accepted, false)+ eq(t, must(t, routes.Snapshot().Operation).Current.ConnectionID, "second_silent_candidate")+}++// TS 1281: retains a peer-only direct attempt through the total operation deadline+func TestRetainsPeerOnlyDirectAttemptThroughTotalDeadline(t *testing.T) {+ routes := newController(1, Options{OperationTimeoutMs: 20_000})+ addViewer(routes, A, 0, ms(0))++ operation := must(t, routes.Reconcile(0).Operation)+ beginCandidate(t, routes, BeginInput{NowMs: 100, ConnectionID: "only_direct_candidate", Reservation: direct()})++ eq(t, must(t, routes.Snapshot().Operation).WakeAtMs, operation.DeadlineAtMs)+ eq(t, routes.OperationExpired(5_100).Accepted, false)+ eq(t, must(t, routes.Snapshot().Operation).Current.ConnectionID, "only_direct_candidate")+ expired := routes.OperationExpired(operation.DeadlineAtMs)+ eq(t, expired.Accepted, true)+ eqSlice(t, expired.FailedPeerIDs, []string{A})+}++// TS 1305: keeps only fresh exact-edge quality shadow aggregates+func TestKeepsOnlyFreshExactEdgeQualityShadowAggregates(t *testing.T) {+ routes := newController(2, Options{})+ addViewer(routes, A, 1, ms(0))+ routes.Reconcile(10)+ commitCurrent(t, routes, 20, "a_quality_connection")+ active := routes.Snapshot()++ eq(t, routes.ObserveQualityEvidence(qualityWindow(+ A, active.Revision, "a_quality_connection", peerUpstream(HOST), 1, 1_000, qualityMetrics())), QualityEvidenceObserved)+ eq(t, routes.Snapshot().Revision, active.Revision)+ eq(t, routes.Snapshot().FactVersion, active.FactVersion)+ addViewer(routes, B, 0, ms(1_100))+ routes.Reconcile(1_200)+ commitCurrent(t, routes, 1_210, "b_quality_connection")+ quality := routes.RouteDiagnosticSnapshot(1_300).Children[0].Quality+ if quality == nil {+ t.Fatal("expected quality aggregates")+ }+ eq(t, *quality, protocol.RouteDiagnosticQuality{+ EligibleWindows: 1,+ EligibleDurationMs: 2_000,+ FreezeWindows: 1,+ FreezeCount: 1,+ FreezeDurationMs: 250,+ PauseCount: 0,+ PauseDurationMs: 0,+ })+ if routes.RouteDiagnosticSnapshot(5_999).Children[0].Quality == nil {+ t.Fatal("quality expired before 6_000")+ }+ if routes.RouteDiagnosticSnapshot(6_000).Children[0].Quality != nil {+ t.Fatal("quality did not expire at 6_000")+ }++ nextRevision := routes.Snapshot().Revision+ nullDecoded := qualityMetrics()+ nullDecoded.FramesDecodedDelta = nil+ eq(t, routes.ObserveQualityEvidence(qualityWindow(+ A, nextRevision, "a_quality_connection", peerUpstream(HOST), 2, 7_000, nullDecoded)), QualityEvidenceAccepted)+ if routes.RouteDiagnosticSnapshot(7_100).Children[0].Quality != nil {+ t.Fatal("expected no quality after an accepted-only window")+ }+ eq(t, routes.ObserveQualityEvidence(qualityWindow(+ A, nextRevision, "a_quality_connection", peerUpstream(HOST), 2, 7_100, qualityMetrics())), QualityEvidenceObserved)+ eq(t, routes.ObserveQualityEvidence(qualityWindow(+ A, nextRevision, "a_quality_connection", peerUpstream(HOST), 1, 7_200, qualityMetrics())), QualityEvidenceRejected)++ routes.SetPaused(true, ms(7_300))+ if routes.RouteDiagnosticSnapshot(7_301).Children[0].Quality != nil {+ t.Fatal("expected no quality while paused")+ }+}++// TS 1390: waits for a fresh healthy candidate sender after relative proof+func TestWaitsForFreshHealthyCandidateSenderAfterRelativeProof(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ eq(t, observeSenderState(routes, senderState{+ childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 100,+ }).Accepted, true)+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ routes.Reconcile(103)+ begin := beginCandidate(t, routes, BeginInput{NowMs: 104, ConnectionID: "a_from_b", Reservation: direct()})+ current := must(t, begin.Operation).Current+ eq(t, routes.CandidateTransportConnected(guardFor(A, current.Revision, "a_from_b"), 105).Accepted, true)+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ B, A, current.Revision, "a_from_b", "a-from-b-rtp\x00track", SenderQualityDegraded, 105), nil).Accepted, true)+ eq(t, routes.CandidateReady(guardFor(A, current.Revision, "a_from_b"), 106, nil, CandidateProof{RelativeQualityApproved: true}).Committed, false)+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ B, A, current.Revision, "a_from_b", "a-from-b-rtp\x00track", SenderQualityHealthy, 107), nil).Committed, true)+}++// TS 1464: does not commit a relative proof after its freshness window expires+func TestDoesNotCommitRelativeProofAfterFreshnessWindowExpires(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ routes.Reconcile(103)+ begin := beginCandidate(t, routes, BeginInput{NowMs: 104, ConnectionID: "a_from_b_stale_proof", Reservation: direct()})+ current := must(t, begin.Operation).Current+ guard := guardFor(A, current.Revision, "a_from_b_stale_proof")+ eq(t, routes.CandidateTransportConnected(guard, 105).Accepted, true)++ eq(t, routes.CandidateReady(guard, 105, nil, CandidateProof{RelativeQualityApproved: true}).Committed, false)+ eq(t, routes.CandidateReady(guard, 109, nil, CandidateProof{RelativeQualityApproved: true}).Committed, false)+ for _, acceptedAtMs := range []int64{5_105, 5_106, 5_107} {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ }+ settled := routes.ObserveSenderQualityEvidence(senderSample(+ B, A, current.Revision, guard.ConnectionID, "stale-proof-rtp\x00track", SenderQualityHealthy, 5_111), nil)+ eq(t, settled.Accepted, true)+ eq(t, settled.Committed, false)+ operation := must(t, routes.Snapshot().Operation)+ eq(t, operation.Reason, DemandQualityConvergence)+ eq(t, operation.Cursor, 1)+ edge := edgeOf(t, routes, A)+ eq(t, edge.ParentPeerID, HOST)+ eq(t, edge.ConnectionID, "a_from_host")+}++// TS 1528: abandons a pending quality move when the incumbent recovers+func TestAbandonsPendingQualityMoveWhenIncumbentRecovers(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ routes.Reconcile(103)+ begin := beginCandidate(t, routes, BeginInput{NowMs: 104, ConnectionID: "a_from_b_incumbent_recovery", Reservation: direct()})+ current := must(t, begin.Operation).Current+ guard := guardFor(A, current.Revision, "a_from_b_incumbent_recovery")+ eq(t, routes.CandidateReady(guard, 105, nil, CandidateProof{RelativeQualityApproved: true}).Committed, false)++ eq(t, observeSenderState(routes, senderState{+ childPeerID: A, connectionID: "a_from_host", state: SenderQualityHealthy, acceptedAtMs: 106,+ }).Accepted, true)+ noOperation(t, routes.Snapshot().Operation)+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ B, A, current.Revision, guard.ConnectionID, "late-healthy-rtp\x00track", SenderQualityHealthy, 107), nil).Accepted, false)+ edge := edgeOf(t, routes, A)+ eq(t, edge.ParentPeerID, HOST)+ eq(t, edge.ConnectionID, "a_from_host")+}++// TS 2086-2095: when candidateReady abandons a quality move because the+// incumbent is no longer degraded, activeRevision is the revision that was+// active before the abort (the TS literal reads this.revision before+// abortOperation advances it), even though the abort itself advances it.+func TestReportsPreAbortRevisionWhenCandidateReadyAbandonsQualityMove(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ routes.Reconcile(103)+ begin := beginCandidate(t, routes, BeginInput{NowMs: 104, ConnectionID: "a_from_b", Reservation: direct()})+ current := must(t, begin.Operation).Current+ before := routes.Snapshot().Revision+ eq(t, routes.ObserveSenderQualityEvidence(unknownSample(HOST, A, before, "a_from_host", 105), nil).Accepted, true)+ settled := routes.CandidateReady(guardFor(A, current.Revision, "a_from_b"), 106, nil, CandidateProof{})+ eq(t, settled.Accepted, true)+ eq(t, settled.Committed, false)+ noOperation(t, routes.Snapshot().Operation)+ eq(t, settled.ActiveRevision, before)+ if routes.Snapshot().Revision <= before {+ t.Fatalf("expected the abort to advance the revision past %d, got %d", before, routes.Snapshot().Revision)+ }+}++// TS 1582: persists relative proof while candidate sender evidence is unknown+func TestPersistsRelativeProofWhileCandidateSenderEvidenceIsUnknown(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 99})+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ routes.Reconcile(103)+ begin := beginCandidate(t, routes, BeginInput{NowMs: 104, ConnectionID: "a_from_b", Reservation: direct()})+ current := must(t, begin.Operation).Current+ eq(t, routes.ObserveSenderQualityEvidence(unknownSample(B, A, current.Revision, "a_from_b", 105), nil).Accepted, true)+ eq(t, routes.CandidateReady(guardFor(A, current.Revision, "a_from_b"), 106, nil, CandidateProof{RelativeQualityApproved: true}).Committed, false)+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ B, A, current.Revision, "a_from_b", "a-from-b-rtp\x00track", SenderQualityHealthy, 107), nil).Committed, true)+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ParentPeerID, B)+ eq(t, edge.ConnectionID, "a_from_b")+}++// TS 1648: advances past a persistently limited quality candidate+func TestAdvancesPastPersistentlyLimitedQualityCandidate(t *testing.T) {+ routes := newController(3, Options{QualityConvergenceEnabled: true})+ for _, seed := range [][2]string{{A, "a_from_host"}, {B, "b_from_host"}, {C, "c_from_host"}} {+ addViewer(routes, seed[0], 3, nil)+ routes.hydrateEdge(seed[0], peerEdge(HOST, seed[1]))+ }+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 99})+ observeSenderState(routes, senderState{childPeerID: C, connectionID: "c_from_host", state: SenderQualityHealthy, acceptedAtMs: 99})+ observePersistentDegraded(t, routes, A, "a_from_host", 99)++ operation := must(t, routes.Reconcile(103).Operation)+ deadlineAtMs := operation.DeadlineAtMs+ eq(t, operation.Candidates[0].Tuple.Kind, UpstreamPeer)+ firstParent := operation.Candidates[0].Tuple.ParentPeerID+ first := beginOperation(t, routes, BeginInput{NowMs: 104, ConnectionID: "first_quality_candidate", Reservation: direct()})+ var lastResult SenderQualityEvidenceResult+ for _, acceptedAtMs := range []int64{105, 106, 107} {+ lastResult = routes.ObserveSenderQualityEvidence(senderSample(+ firstParent, A, first.Current.Revision, "first_quality_candidate", "first-quality-rtp\x00track",+ SenderQualityDegraded, acceptedAtMs), nil)+ eq(t, lastResult.Accepted, true)+ }+ eq(t, lastResult.Committed, false)+ edge := edgeOf(t, routes, A)+ eq(t, edge.ParentPeerID, HOST)+ eq(t, edge.ConnectionID, "a_from_host")+ pending := must(t, routes.Snapshot().Operation)+ eq(t, pending.Cursor, 1)+ eq(t, pending.DeadlineAtMs, deadlineAtMs)+ if pending.Current != nil {+ t.Fatal("expected no live attempt")+ }++ secondParent := pending.Candidates[1].Tuple.ParentPeerID+ if secondParent == firstParent {+ t.Fatalf("second parent %q repeats the first", secondParent)+ }+ second := beginOperation(t, routes, BeginInput{NowMs: 108, ConnectionID: "second_quality_candidate", Reservation: direct()})+ eq(t, routes.ObserveSenderQualityEvidence(unknownSample(+ secondParent, A, second.Current.Revision, "second_quality_candidate", 109), nil).Accepted, true)+ eq(t, routes.CandidateReady(guardFor(A, second.Current.Revision, "second_quality_candidate"), 110, nil,+ CandidateProof{RelativeQualityApproved: true}).Committed, false)+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ secondParent, A, second.Current.Revision, "second_quality_candidate", "second-quality-rtp\x00track",+ SenderQualityHealthy, 111), nil).Committed, true)+ edge = edgeOf(t, routes, A)+ eq(t, edge.ParentPeerID, secondParent)+ eq(t, edge.ConnectionID, "second_quality_candidate")+}++// TS 1768: preempts quality work for a Viewer without media+func TestPreemptsQualityWorkForViewerWithoutMedia(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 100})+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ eq(t, must(t, routes.Reconcile(103).Operation).Reason, DemandQualityConvergence)+ addViewer(routes, C, 0, ms(104))+ join := must(t, routes.Reconcile(105).Operation)+ eq(t, join.ChildPeerID, C)+ eq(t, join.Reason, DemandJoin)+ commitCurrent(t, routes, 106, "c_join_connection")+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 107})+ observePersistentDegraded(t, routes, A, "a_from_host", 107)+ eq(t, must(t, routes.Reconcile(111).Operation).Reason, DemandQualityConvergence)+ edge := edgeOf(t, routes, A)+ eq(t, edge.ParentPeerID, HOST)+ eq(t, edge.ConnectionID, "a_from_host")+}++// TS 1806: keeps a quality operation reason immutable until availability preempts it+func TestKeepsQualityOperationReasonImmutableUntilAvailabilityPreempts(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 99})+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ eq(t, must(t, routes.Reconcile(103).Operation).Reason, DemandQualityConvergence)++ eq(t, routes.InvalidateEdge(edgeGuard(A, "host_session", routes.Snapshot().Revision, "a_from_host"), ms(104)), true)+ eq(t, must(t, routes.Snapshot().Operation).Reason, DemandQualityConvergence)+ preempted := must(t, routes.Reconcile(105).Operation)+ eq(t, preempted.ChildPeerID, A)+ eq(t, preempted.Reason, DemandEdgeUnavailable)+}++// TS 1842: keeps a direct convergence reason immutable until availability preempts it+func TestKeepsDirectConvergenceReasonImmutableUntilAvailabilityPreempts(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ routes.hydrateHostPublication("publication", res("publication_resource"), "")+ addViewer(routes, A, 0, ms(0))+ acquisition := must(t, routes.Reconcile(0).Operation)+ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_head_start", Reservation: direct()})+ routes.OperationExpired(acquisition.WakeAtMs)+ sfu := beginOperation(t, routes, BeginInput{NowMs: acquisition.WakeAtMs + 1, ConnectionID: "a_sfu", Reservation: sfuReuse("a_subscription")})+ eq(t, routes.CandidateReady(guardFor(A, sfu.Current.Revision, "a_sfu"), acquisition.WakeAtMs+2, nil, CandidateProof{}).Committed, true)+ eq(t, must(t, routes.Reconcile(acquisition.WakeAtMs+3).Operation).Reason, DemandDirectConvergence)++ eq(t, routes.InvalidateEdge(edgeGuard(A, "", routes.Snapshot().Revision, "a_sfu"), ms(acquisition.WakeAtMs+4)), true)+ eq(t, must(t, routes.Snapshot().Operation).Reason, DemandDirectConvergence)+ preempted := must(t, routes.Reconcile(acquisition.WakeAtMs+5).Operation)+ eq(t, preempted.ChildPeerID, A)+ eq(t, preempted.Reason, DemandEdgeUnavailable)+}++// TS 1893: keeps a root convergence reason immutable until availability preempts it+func TestKeepsRootConvergenceReasonImmutableUntilAvailabilityPreempts(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, B, 2, nil)+ addViewer(routes, C, 0, nil)+ addViewer(routes, D, 0, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ routes.hydrateEdge(C, peerEdge(B, "c_from_b"))+ routes.hydrateEdge(D, peerEdge(B, "d_from_b"))+ addViewer(routes, A, 2, ms(10))+ routes.Reconcile(10)+ commitCurrent(t, routes, 11, "a_from_host")+ convergence := must(t, routes.Reconcile(13).Operation)+ eq(t, convergence.Reason, DemandRootConvergence)+ oldEdge := edgeOf(t, routes, convergence.ChildPeerID)+ eq(t, oldEdge.Kind, UpstreamPeer)++ eq(t, routes.InvalidateEdge(EdgeGuard{+ ChildPeerID: convergence.ChildPeerID,+ ChildSessionID: convergence.ChildSessionID,+ ParentSessionID: oldEdge.ParentSessionID,+ RouteRevision: routes.Snapshot().Revision,+ ConnectionID: oldEdge.ConnectionID,+ }, ms(14)), true)+ eq(t, must(t, routes.Snapshot().Operation).Reason, DemandRootConvergence)+ preempted := must(t, routes.Reconcile(15).Operation)+ eq(t, preempted.ChildPeerID, convergence.ChildPeerID)+ eq(t, preempted.Reason, DemandEdgeUnavailable)+}++// TS 1931: keeps a usable parent eligible before native state becomes clear+func TestKeepsUsableParentEligibleBeforeNativeStateBecomesClear(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ operation := must(t, routes.Reconcile(103).Operation)+ eq(t, operation.ChildPeerID, A)+ eq(t, operation.Reason, DemandQualityConvergence)+ eqSlice(t, tuples(operation), []CandidateTuple{peerTuple(B), regenerateTuple(HOST)})+}++// TS 1957: waits for a fresh candidate sender after prior evidence expires+func TestWaitsForFreshCandidateSenderAfterPriorEvidenceExpires(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observeCurrent := func(childPeerID, connectionID string, state SenderQualityState, acceptedAtMs int64) SenderQualityEvidenceResult {+ return routes.ObserveSenderQualityEvidence(senderSample(+ HOST, childPeerID, routes.Snapshot().Revision, connectionID, connectionID+"-rtp\x00track", state, acceptedAtMs), nil)+ }+ eq(t, observeCurrent(B, "b_from_host", SenderQualityHealthy, 100).Accepted, true)+ eq(t, observeCurrent(A, "a_from_host", SenderQualityHealthy, 99).Accepted, true)+ eq(t, observeCurrent(A, "a_from_host", SenderQualityDegraded, 100).Accepted, true)+ eq(t, observeCurrent(A, "a_from_host", SenderQualityDegraded, 101).Accepted, true)+ eq(t, observeCurrent(A, "a_from_host", SenderQualityDegraded, 102).Accepted, true)+ routes.Reconcile(103)+ begin := beginCandidate(t, routes, BeginInput{NowMs: 104, ConnectionID: "a_from_b_stale", Reservation: direct()})+ current := must(t, begin.Operation).Current+ eq(t, routes.CandidateTransportConnected(guardFor(A, current.Revision, "a_from_b_stale"), 105).Accepted, true)+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ B, A, current.Revision, "a_from_b_stale", "a-stale-rtp\x00a-track", SenderQualityHealthy, 104), nil).Accepted, true)+ for _, acceptedAtMs := range []int64{5_101, 5_102, 5_103} {+ eq(t, observeCurrent(A, "a_from_host", SenderQualityDegraded, acceptedAtMs).Accepted, true)+ }+ eq(t, routes.CandidateReady(guardFor(A, current.Revision, "a_from_b_stale"), 5_104, nil,+ CandidateProof{RelativeQualityApproved: true}).Committed, false)+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(+ B, A, current.Revision, "a_from_b_stale", "a-stale-rtp\x00a-track", SenderQualityHealthy, 5_105), nil).Committed, true)+ edge := edgeOf(t, routes, A)+ eq(t, edge.ParentPeerID, B)+ eq(t, edge.ConnectionID, "a_from_b_stale")+}++// TS 2063: keeps a usable candidate when its native source category expires+func TestKeepsUsableCandidateWhenNativeSourceCategoryExpires(t *testing.T) {+ routes := newController(2, Options{QualityConvergenceEnabled: true})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 0})+ observePersistentDegraded(t, routes, A, "a_from_host", 0)+ eq(t, must(t, routes.Reconcile(4).Operation).Reason, DemandQualityConvergence)+ begin := beginCandidate(t, routes, BeginInput{NowMs: 5_001, ConnectionID: "expired_candidate", Reservation: direct()})+ eq(t, begin.Accepted, true)+ eq(t, must(t, begin.Operation).Current.ConnectionID, "expired_candidate")+}++// TS 2086: keeps bounded SFU after direct candidates when every Host root is degraded+func TestKeepsBoundedSfuAfterDirectCandidatesWhenEveryHostRootIsDegraded(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true, QualityConvergenceEnabled: true})+ addViewer(routes, A, 1, nil)+ addViewer(routes, B, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ firstRegeneration := must(t, routes.Reconcile(103).Operation)+ eq(t, firstRegeneration.Candidates[0].Tuple, regenerateTuple(HOST))+ firstAttempt := beginOperation(t, routes, BeginInput{+ NowMs: 104, ConnectionID: "a_regeneration_failed", Reservation: directOverlap("a_regeneration_overlap"),+ })+ eq(t, routes.CandidateFailed(guardFor(A, firstAttempt.Current.Revision, "a_regeneration_failed"), 105).Accepted, true)+ eq(t, routes.SetEffectiveCapacity(B, sessionOf(B), 1, nil), true)+ observePersistentDegraded(t, routes, B, "b_from_host", 104)+ operation := must(t, routes.Reconcile(108).Operation)+ childPeerID := operation.ChildPeerID+ eq(t, childPeerID, A)+ eqSlice(t, tuples(operation), []CandidateTuple{peerTuple(B), sfuTuple(PublicationCreate)})+ directAttempt := beginOperation(t, routes, BeginInput{NowMs: 109, ConnectionID: "quality_peer_candidate", Reservation: direct()})+ failed := routes.CandidateFailed(guardFor(childPeerID, directAttempt.Current.Revision, "quality_peer_candidate"), 110)+ eq(t, failed.Accepted, true)+ eqSlice(t, failed.FailedPeerIDs, []string{})++ begin := beginCandidate(t, routes, BeginInput{+ NowMs: 111,+ ConnectionID: "quality_sfu_candidate",+ Reservation: sfuCreateOverlap("sfu-edge", "sfu-publication", "host-overlap"),+ PublicationGeneration: "publication_generation_12345678",+ PublicationConnectionID: "publication_connection_12345678",+ HostSessionID: "host_session",+ })+ current := must(t, begin.Operation).Current+ guard := guardFor(childPeerID, current.Revision, "quality_sfu_candidate")+ ready := routes.CandidateReady(guard, 112, nil, CandidateProof{})+ eq(t, ready.Accepted, true)+ eq(t, ready.Committed, false)+ for _, acceptedAtMs := range []int64{113, 114} {+ observed := routes.ObserveSfuPublisherQualityEvidence(publisherSample(+ "publication_generation_12345678", current.Revision, SenderQualityHealthy, acceptedAtMs), nil)+ eq(t, observed.Accepted, true)+ eq(t, observed.Committed, false)+ ready = routes.CandidateReady(guard, acceptedAtMs, nil, CandidateProof{})+ eq(t, ready.Accepted, true)+ eq(t, ready.Committed, false)+ }+ eq(t, routes.ObserveSfuPublisherQualityEvidence(publisherSample(+ "publication_generation_12345678", current.Revision, SenderQualityHealthy, 115), nil).Committed, true)+ edge := edgeOf(t, routes, childPeerID)+ eq(t, edge.Kind, UpstreamSfu)+ eq(t, edge.ConnectionID, "quality_sfu_candidate")+}++// TS 2201: rejects an SFU quality candidate on degraded publisher evidence+func TestRejectsSfuQualityCandidateOnDegradedPublisherEvidence(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true, QualityConvergenceEnabled: true})+ addViewer(routes, A, 1, nil)+ addViewer(routes, B, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ firstRegeneration := must(t, routes.Reconcile(103).Operation)+ eq(t, firstRegeneration.Candidates[0].Tuple, regenerateTuple(HOST))+ firstAttempt := beginOperation(t, routes, BeginInput{+ NowMs: 104, ConnectionID: "a_regeneration_failed", Reservation: directOverlap("a_regeneration_overlap"),+ })+ eq(t, routes.CandidateFailed(guardFor(A, firstAttempt.Current.Revision, "a_regeneration_failed"), 105).Accepted, true)+ eq(t, routes.SetEffectiveCapacity(B, sessionOf(B), 1, nil), true)+ observePersistentDegraded(t, routes, B, "b_from_host", 104)+ operation := must(t, routes.Reconcile(108).Operation)+ childPeerID := operation.ChildPeerID+ eq(t, childPeerID, A)+ peerAttempt := beginOperation(t, routes, BeginInput{NowMs: 109, ConnectionID: "quality_peer_candidate", Reservation: direct()})+ eq(t, routes.CandidateFailed(guardFor(childPeerID, peerAttempt.Current.Revision, "quality_peer_candidate"), 110).Accepted, true)+ sfuAttempt := beginOperation(t, routes, BeginInput{+ NowMs: 111,+ ConnectionID: "quality_sfu_degraded",+ Reservation: sfuCreateOverlap("sfu-edge", "sfu-publication", "host-overlap"),+ PublicationGeneration: "publication_generation_degraded",+ PublicationConnectionID: "publication_connection_degraded",+ HostSessionID: "host_session",+ })+ current := sfuAttempt.Current+ ready := routes.CandidateReady(guardFor(childPeerID, current.Revision, current.ConnectionID), 112, nil, CandidateProof{})+ eq(t, ready.Accepted, true)+ eq(t, ready.Committed, false)+ degraded := routes.ObserveSfuPublisherQualityEvidence(publisherSample(+ "publication_generation_degraded", current.Revision, SenderQualityDegraded, 113), nil)+ eq(t, degraded.Accepted, true)+ eq(t, degraded.Committed, false)+ noOperation(t, routes.Reconcile(114).Operation)+ edge := edgeOf(t, routes, childPeerID)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ParentPeerID, HOST)+}++// TS 2297: abandons Host relief when another Host root recovers during the canary+func TestAbandonsHostReliefWhenAnotherHostRootRecoversDuringCanary(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true, QualityConvergenceEnabled: true})+ addViewer(routes, A, 1, nil)+ addViewer(routes, B, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ observePersistentDegraded(t, routes, B, "b_from_host", 99)+ routes.Reconcile(103)+ begin := beginCandidate(t, routes, BeginInput{+ NowMs: 104,+ ConnectionID: "a_from_sfu",+ Reservation: sfuCreateOverlap("sfu-edge", "sfu-publication", "host-overlap"),+ PublicationGeneration: "publication_generation_12345678",+ PublicationConnectionID: "publication_connection_12345678",+ HostSessionID: "host_session",+ })+ current := must(t, begin.Operation).Current+ eq(t, observeSenderState(routes, senderState{+ childPeerID: B, connectionID: "b_from_host", state: SenderQualityHealthy, acceptedAtMs: 105,+ }).Accepted, true)+ eq(t, routes.CandidateReady(guardFor(A, current.Revision, "a_from_sfu"), 106, nil, CandidateProof{}).Committed, false)+ noOperation(t, routes.Snapshot().Operation)+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ParentPeerID, HOST)+ eq(t, edge.ConnectionID, "a_from_host")+}++// TS 2350: uses SFU reuse only for multi-edge Host relief with healthy ingress+func TestUsesSfuReuseOnlyForMultiEdgeHostReliefWithHealthyIngress(t *testing.T) {+ routes := newController(3, Options{SfuEnabled: true, QualityConvergenceEnabled: true})+ addViewer(routes, A, 0, nil)+ addViewer(routes, B, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ routes.hydrateHostPublication("publication_generation_12345678", res("publication_resource"), "")+ revision := routes.Snapshot().Revision+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ observePersistentDegraded(t, routes, B, "b_from_host", 99)+ noOperation(t, routes.Reconcile(103).Operation)+ observePersistentSfuHealthy(t, routes, "publication_generation_12345678", revision, 104)+ eq(t, must(t, routes.Reconcile(105).Operation).Candidates[0].Tuple, sfuTuple(PublicationReuse))+ begin := beginCandidate(t, routes, BeginInput{NowMs: 106, ConnectionID: "a_from_sfu_reuse", Reservation: sfuReuse("a_subscription")})+ current := must(t, begin.Operation).Current+ unknown := publisherSample("publication_generation_12345678", revision, SenderQualityUnknown, 107)+ unknown.SampleTimestampMs = nil+ eq(t, routes.ObserveSfuPublisherQualityEvidence(unknown, nil).Accepted, true)+ eq(t, routes.CandidateReady(guardFor(A, current.Revision, "a_from_sfu_reuse"), 108, nil, CandidateProof{}).Committed, false)+ for _, acceptedAtMs := range []int64{2_100, 4_100, 6_100} {+ observeSenderState(routes, senderState{childPeerID: A, connectionID: "a_from_host", state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs})+ observeSenderState(routes, senderState{childPeerID: B, connectionID: "b_from_host", state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs})+ settled := routes.ObserveSfuPublisherQualityEvidence(publisherSample(+ "publication_generation_12345678", revision, SenderQualityHealthy, acceptedAtMs), nil)+ eq(t, settled.Committed, acceptedAtMs == 6_100)+ }+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamSfu)+ eq(t, edge.ConnectionID, "a_from_sfu_reuse")+}++// TS 2435: accepts an SFU-fed Peer parent from decoded progress without freeze stats+func TestAcceptsSfuFedPeerParentFromDecodedProgressWithoutFreezeStats(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true, QualityConvergenceEnabled: true})+ addViewer(routes, A, 1, nil)+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateHostPublication("publication_generation_12345678", res("publication_resource"), "")+ routes.hydrateEdge(B, sfuEdge("publication_generation_12345678", "b_from_sfu", "b_subscription"))+ revision := routes.Snapshot().Revision+ observePersistentSfuHealthy(t, routes, "publication_generation_12345678", revision, 100)+ metrics := qualityMetrics()+ metrics.FreezeCountDelta = nil+ metrics.FreezeDurationMsDelta = nil+ metrics.PauseCountDelta = nil+ metrics.PauseDurationMsDelta = nil+ eq(t, routes.ObserveQualityEvidence(qualityWindow(B, revision, "b_from_sfu", sfuUpstream(), 1, 100, metrics)), QualityEvidenceAccepted)+ observePersistentDegraded(t, routes, A, "a_from_host", 99)+ eq(t, must(t, routes.Reconcile(103).Operation).Candidates[0].Tuple, peerTuple(B))+}++// TS 2489: clears quality shadow for a relay subtree when its source changes+func TestClearsQualityShadowForRelaySubtreeWhenSourceChanges(t *testing.T) {+ routes := newController(2, Options{})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ addViewer(routes, C, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(A, "b_from_a"))+ routes.hydrateEdge(C, peerEdge(B, "c_from_b"))+ revision := routes.Snapshot().Revision++ relays := [][3]string{{B, A, "b_from_a"}, {C, B, "c_from_b"}}+ for _, relay := range relays {+ eq(t, routes.ObserveQualityEvidence(qualityWindow(+ relay[0], revision, relay[2], peerUpstream(relay[1]), 1, 1_000, qualityMetrics())), QualityEvidenceObserved)+ }+ withQuality := func(nowMs int64) int {+ count := 0+ for _, child := range routes.RouteDiagnosticSnapshot(nowMs).Children {+ if child.Quality != nil {+ count+++ }+ }+ return count+ }+ eq(t, withQuality(1_001), 2)++ eq(t, routes.AdoptDirectConnection(AdoptDirectConnectionInput{+ EdgeGuard: edgeGuard(A, "host_session", revision, "a_from_host"),+ NewConnectionID: "a_from_host_recovered",+ }), true)+ eq(t, withQuality(1_002), 0)++ for _, step := range []struct {+ at int64+ expected RouteQualityEvidenceResult+ }{{1_100, QualityEvidenceAccepted}, {3_100, QualityEvidenceObserved}} {+ for _, relay := range relays {+ eq(t, routes.ObserveQualityEvidence(qualityWindow(+ relay[0], revision, relay[2], peerUpstream(relay[1]), 1, step.at, qualityMetrics())), step.expected)+ }+ }+ eq(t, withQuality(3_101), 2)+}++// TS 2569: retains one latest timing sample for a 20-Viewer burst+func TestRetainsOneLatestTimingSampleForTwentyViewerBurst(t *testing.T) {+ routes := newController(2, Options{})+ viewerPeerIDs := make([]string, 20)+ for index := range viewerPeerIDs {+ viewerPeerIDs[index] = fmt.Sprintf("burst_%02d_12345678", index)+ }+ for _, peerID := range viewerPeerIDs {+ addViewer(routes, peerID, 2, ms(0))+ }++ for index, peerID := range viewerPeerIDs {+ operationStartedAtMs := int64(index+1) * 10+ eq(t, must(t, routes.Reconcile(operationStartedAtMs).Operation).ChildPeerID, peerID)+ commitCurrent(t, routes, operationStartedAtMs+1, peerID+"_connection")+ }++ snapshot := routes.RouteDiagnosticSnapshot(250)+ eq(t, len(snapshot.Children), 20)+ for index, child := range snapshot.Children {+ eqDeep(t, child.QueueWaitMs, optInt(int64(index+1)*10))+ eq(t, child.FinalRoute, string(FinalRouteDirect))+ }+}++// TS 2598: projects latest route timing through snapshot-local ordinals+func TestProjectsLatestRouteTimingThroughSnapshotLocalOrdinals(t *testing.T) {+ routes := newController(2, Options{})+ addViewer(routes, A, 1, ms(100))++ eqDeep(t, routes.RouteDiagnosticSnapshot(150), protocol.RouteDiagnosticSnapshot{+ Children: []protocol.RouteDiagnosticChild{{+ Ordinal: 1,+ Parent: protocol.RouteDiagnosticParent{Kind: "none"},+ EffectiveCapacity: 1,+ ChildCount: 0,+ DemandAgeMs: optInt(50),+ QueueWaitMs: nil,+ CandidateStartMs: nil,+ FirstDecodedFrameMs: nil,+ FinalMs: nil,+ FinalRoute: "waiting",+ RejectionBucket: "none",+ Quality: nil,+ }},+ Operation: nil,+ })++ operation := must(t, routes.Reconcile(160).Operation)+ eqDeep(t, routes.RouteDiagnosticSnapshot(165).Operation, &protocol.RouteDiagnosticOperation{+ ChildOrdinal: 1,+ Reason: "join",+ Stage: "admission",+ Cursor: 0,+ CandidateCount: protocol.Int(len(operation.Candidates)),+ })+ prepared := beginOperation(t, routes, BeginInput{NowMs: 170, ConnectionID: "a_connection", Reservation: direct()})+ pending := routes.RouteDiagnosticSnapshot(180)+ eq(t, len(pending.Children), 1)+ eqDeep(t, pending.Children[0].QueueWaitMs, optInt(60))+ eqDeep(t, pending.Children[0].CandidateStartMs, optInt(70))+ eqDeep(t, pending.Children[0].FirstDecodedFrameMs, (*protocol.Int)(nil))+ eqDeep(t, pending.Children[0].FinalMs, (*protocol.Int)(nil))+ if pending.Operation == nil {+ t.Fatal("expected a diagnostic operation")+ }+ eq(t, pending.Operation.ChildOrdinal, 1)+ eq(t, pending.Operation.Stage, "first-frame")+ eq(t, routes.CandidateReady(guardFor(A, prepared.Current.Revision, "a_connection"), 230, nil, CandidateProof{}).Accepted, true)+ settled := routes.RouteDiagnosticSnapshot(240)+ eq(t, len(settled.Children), 1)+ eq(t, settled.Children[0].Parent, protocol.RouteDiagnosticParent{Kind: "host"})+ eqDeep(t, settled.Children[0].QueueWaitMs, optInt(60))+ eqDeep(t, settled.Children[0].CandidateStartMs, optInt(70))+ eqDeep(t, settled.Children[0].FirstDecodedFrameMs, optInt(130))+ eqDeep(t, settled.Children[0].FinalMs, optInt(130))+ eq(t, settled.Children[0].FinalRoute, "direct")+ eq(t, settled.Children[0].RejectionBucket, "none")+ if settled.Operation != nil {+ t.Fatal("expected no diagnostic operation")+ }+ serialized, err := json.Marshal(settled)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(serialized), A) {+ t.Fatalf("diagnostic snapshot leaks the peer ID: %s", serialized)+ }+ if strings.Contains(string(serialized), "a_connection") {+ t.Fatalf("diagnostic snapshot leaks the connection ID: %s", serialized)+ }++ eq(t, routes.InvalidateEdge(edgeGuard(A, "host_session", routes.Snapshot().Revision, "a_connection"), ms(300)), true)+ waiting := routes.RouteDiagnosticSnapshot(320).Children[0]+ eqDeep(t, waiting.DemandAgeMs, optInt(20))+ eqDeep(t, waiting.QueueWaitMs, (*protocol.Int)(nil))+ eqDeep(t, waiting.CandidateStartMs, (*protocol.Int)(nil))+ eqDeep(t, waiting.FirstDecodedFrameMs, (*protocol.Int)(nil))+ eqDeep(t, waiting.FinalMs, (*protocol.Int)(nil))+ eq(t, waiting.FinalRoute, "waiting")+ eq(t, waiting.RejectionBucket, "none")++ eq(t, routes.ConfirmDeparture(A, ms(330)), true)+ departed := routes.RouteDiagnosticSnapshot(330)+ eq(t, len(departed.Children), 0)+ if departed.Operation != nil {+ t.Fatal("expected no diagnostic operation")+ }+}++// TS 2704: records a bounded candidate failure without retaining route identity+func TestRecordsBoundedCandidateFailureWithoutRetainingRouteIdentity(t *testing.T) {+ routes := newController(1, Options{})+ addViewer(routes, A, 0, ms(0))+ routes.Reconcile(10)+ prepared := beginOperation(t, routes, BeginInput{NowMs: 20, ConnectionID: "failed_candidate", Reservation: direct()})+ failed := routes.CandidateFailed(guardFor(A, prepared.Current.Revision, "failed_candidate"), 30)+ eq(t, failed.Accepted, true)+ eqSlice(t, failed.FailedPeerIDs, []string{A})+ child := routes.RouteDiagnosticSnapshot(30).Children[0]+ eqDeep(t, child.FinalMs, optInt(30))+ eq(t, child.FinalRoute, "failed")+ eq(t, child.RejectionBucket, "candidate-failed")++ routes.Dispose()+ disposed := routes.RouteDiagnosticSnapshot(40)+ eq(t, len(disposed.Children), 0)+ if disposed.Operation != nil {+ t.Fatal("expected no diagnostic operation after dispose")+ }+}++// TS 2737: reports a current child that has no usable candidate+func TestReportsCurrentChildThatHasNoUsableCandidate(t *testing.T) {+ routes := newController(1, Options{})+ addViewer(routes, A, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_connection"))+ addViewer(routes, B, 0, ms(0))++ result := routes.Reconcile(10)+ noOperation(t, result.Operation)+ eqSlice(t, result.FailedPeerIDs, []string{B})+ child := routes.RouteDiagnosticSnapshot(10).Children[1]+ eqDeep(t, child.FinalMs, optInt(10))+ eq(t, child.FinalRoute, "failed")+ eq(t, child.RejectionBucket, "candidate-failed")+}++// TS 2753: records SFU admission waiting without advancing the route cursor+func TestRecordsSfuAdmissionWaitingWithoutAdvancingRouteCursor(t *testing.T) {+ routes := newController(1, Options{SfuEnabled: true})+ addViewer(routes, A, 0, ms(0))+ directOp := must(t, routes.Reconcile(10).Operation)+ eqSlice(t, tupleKinds(directOp), []UpstreamKind{UpstreamPeer, UpstreamSfu})+ eq(t, routes.SkipCurrentCandidate(cursorGuard(directOp), 20, RejectionCandidateFailed).Accepted, true)+ sfu := must(t, routes.Snapshot().Operation)+ eq(t, routes.NoteCurrentCandidateRejection(cursorGuard(sfu), RejectionSfuAdmission), true)+ snapshot := routes.RouteDiagnosticSnapshot(30)+ eq(t, len(snapshot.Children), 1)+ eq(t, snapshot.Children[0].FinalRoute, "waiting")+ eq(t, snapshot.Children[0].RejectionBucket, "sfu-admission")+ if snapshot.Operation == nil {+ t.Fatal("expected a diagnostic operation")+ }+ eq(t, *snapshot.Operation, protocol.RouteDiagnosticOperation{+ ChildOrdinal: 1, Reason: "join", Stage: "admission", Cursor: 1, CandidateCount: 2,+ })+}++// TS 2791: distinguishes first-frame timeout from the total operation deadline+func TestDistinguishesFirstFrameTimeoutFromTotalOperationDeadline(t *testing.T) {+ routes := newController(1, Options{SfuEnabled: true})+ addViewer(routes, A, 0, ms(0))+ directOp := must(t, routes.Reconcile(10).Operation)+ beginCandidate(t, routes, BeginInput{NowMs: 20, ConnectionID: "silent_direct", Reservation: direct()})++ eq(t, routes.OperationExpired(directOp.WakeAtMs).Accepted, true)+ snapshot := routes.RouteDiagnosticSnapshot(directOp.WakeAtMs)+ eq(t, len(snapshot.Children), 1)+ eqDeep(t, snapshot.Children[0].CandidateStartMs, (*protocol.Int)(nil))+ eqDeep(t, snapshot.Children[0].FinalMs, (*protocol.Int)(nil))+ eq(t, snapshot.Children[0].FinalRoute, "waiting")+ eq(t, snapshot.Children[0].RejectionBucket, "first-frame-timeout")+ if snapshot.Operation == nil {+ t.Fatal("expected a diagnostic operation")+ }+ eq(t, snapshot.Operation.Cursor, 1)+ eq(t, snapshot.Operation.Stage, "admission")++ deadline := must(t, routes.Snapshot().Operation).DeadlineAtMs+ expired := routes.OperationExpired(deadline)+ eq(t, expired.Accepted, true)+ eqSlice(t, expired.FailedPeerIDs, []string{A})+ child := routes.RouteDiagnosticSnapshot(deadline).Children[0]+ eqDeep(t, child.FinalMs, optInt(deadline))+ eq(t, child.FinalRoute, "failed")+ eq(t, child.RejectionBucket, "operation-deadline")+}++// TS 2828: admits 20 Viewers through one bounded event-driven graph at C=%i+func TestAdmitsTwentyViewersThroughOneBoundedGraph(t *testing.T) {+ for _, capacity := range []int{1, 2, 3} {+ t.Run(fmt.Sprintf("C=%d", capacity), func(t *testing.T) {+ routes := newController(capacity, Options{})+ viewerPeerIDs := make([]string, 20)+ for index := range viewerPeerIDs {+ viewerPeerIDs[index] = fmt.Sprintf("viewer_%02d_12345678", index)+ }+ for index, peerID := range viewerPeerIDs {+ addViewer(routes, peerID, capacity, nil)+ operation := must(t, routes.Reconcile(int64(index*2)).Operation)+ eq(t, operation.ChildPeerID, peerID)+ commitCurrent(t, routes, int64(index*2+1), peerID+"_connection")+ }+ snapshot := routes.Snapshot()+ eq(t, snapshot.UpstreamByViewer.Len(), 20)+ for _, parentPeerID := range append([]string{HOST}, viewerPeerIDs...) {+ childCount := 0+ for _, edge := range snapshot.UpstreamByViewer.Values() {+ if edge.Kind == UpstreamPeer && edge.PhysicalActive && edge.ParentPeerID == parentPeerID {+ childCount+++ }+ }+ if childCount > capacity {+ t.Fatalf("parent %q has %d children, capacity %d", parentPeerID, childCount, capacity)+ }+ }+ })+ }+}++// TS 2856: admits waiting Viewers through existing SFU before direct convergence+func TestAdmitsWaitingViewersThroughExistingSfuBeforeDirectConvergence(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateHostPublication("publication_generation", res("publication_resource"), "")+ routes.hydrateEdge(B, sfuEdge("publication_generation", "b_sfu", "b_subscription"))+ addViewer(routes, C, 0, nil)+ routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"))+ waiting := make([]string, 18)+ for index := range waiting {+ waiting[index] = fmt.Sprintf("silent_%02d_12345678", index)+ }+ for _, peerID := range waiting {+ addViewer(routes, peerID, 0, nil)+ }++ nowMs := int64(0)+ for index, peerID := range waiting {+ directOperation := must(t, routes.Reconcile(nowMs).Operation)+ eq(t, directOperation.ChildPeerID, peerID)+ eq(t, directOperation.Candidates[0].Tuple.Kind, UpstreamPeer)+ beginCandidate(t, routes, BeginInput{NowMs: nowMs + 1, ConnectionID: peerID + "_direct", Reservation: direct()})+ routes.OperationExpired(directOperation.WakeAtMs)+ sfuOperation := must(t, routes.Snapshot().Operation)+ eq(t, sfuOperation.Candidates[sfuOperation.Cursor].Tuple, sfuTuple(PublicationReuse))+ prepared := beginOperation(t, routes, BeginInput{+ NowMs: directOperation.WakeAtMs + 1, ConnectionID: peerID + "_sfu", Reservation: sfuReuse(peerID + "_subscription"),+ })+ eq(t, routes.CandidateReady(guardFor(peerID, prepared.Current.Revision, peerID+"_sfu"),+ directOperation.WakeAtMs+2, nil, CandidateProof{}).Accepted, true)+ nowMs = directOperation.WakeAtMs + 3++ bEdge := edgeOf(t, routes, B)+ eq(t, bEdge.Kind, UpstreamSfu)+ eq(t, bEdge.ConnectionID, "b_sfu")+ cEdge := edgeOf(t, routes, C)+ eq(t, cEdge.Kind, UpstreamPeer)+ eq(t, cEdge.ParentPeerID, HOST)+ eq(t, cEdge.ConnectionID, "c_from_host")+ admitted := edgeOf(t, routes, peerID)+ eq(t, admitted.Kind, UpstreamSfu)+ eq(t, admitted.Usable, true)+ eq(t, routes.Snapshot().UpstreamByViewer.Len(), index+3)+ }++ eq(t, routes.Snapshot().UpstreamByViewer.Len(), 20)+ publication := routes.Snapshot().HostPublication+ if publication == nil {+ t.Fatal("expected a host publication")+ }+ eq(t, publication.Generation, "publication_generation")+ eq(t, publication.Usable, true)+ eq(t, must(t, routes.Reconcile(nowMs).Operation).Reason, DemandDirectConvergence)+}++// TS 2943: builds a deterministic acyclic route without a depth cap at C=%i+func TestBuildsDeterministicAcyclicRouteWithoutDepthCap(t *testing.T) {+ for _, capacity := range []int{1, 2, 3} {+ t.Run(fmt.Sprintf("C=%d", capacity), func(t *testing.T) {+ routes := newController(capacity, Options{})+ for _, peerID := range []string{A, B, C, D} {+ addViewer(routes, peerID, capacity, nil)+ result := routes.Reconcile(0)+ eq(t, must(t, result.Operation).ChildPeerID, peerID)+ commitCurrent(t, routes, 1, peerID+"_connection")+ }++ snapshot := routes.Snapshot()+ eq(t, snapshot.UpstreamByViewer.Len(), 4)+ for childPeerID, edge := range snapshot.UpstreamByViewer.All() {+ eq(t, edge.Kind, UpstreamPeer)+ if edge.ParentPeerID == childPeerID {+ t.Fatalf("%q is its own parent", childPeerID)+ }+ }+ if capacity == 1 {+ // Pins the stablePairRank/depth ordering: at C=1 D hangs below C.+ dEdge := edgeOf(t, routes, D)+ eq(t, dEdge.Kind, UpstreamPeer)+ eq(t, dEdge.ParentPeerID, C)+ }+ })+ }+}++// TS 2969: keeps the old edge until exact candidate first-frame ready+func TestKeepsOldEdgeUntilExactCandidateFirstFrameReady(t *testing.T) {+ routes := newController(2, Options{})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ routes.Reconcile(0)+ commitCurrent(t, routes, 1, "old_connection")+ routes.Reconcile(2)+ commitCurrent(t, routes, 3, "b_connection")+ revision := routes.Snapshot().Revision+ eq(t, routes.InvalidateEdge(edgeGuard(A, "host_session", revision, "old_connection"), nil), true)++ routes.Reconcile(100)+ prepared := beginOperation(t, routes, BeginInput{NowMs: 101, ConnectionID: "new_connection", Reservation: direct()})+ eq(t, edgeOf(t, routes, A).ConnectionID, "old_connection")+ eq(t, routes.CandidateReady(guardFor(A, prepared.Current.Revision-1, "new_connection"), 102, nil, CandidateProof{}).Accepted, false)+ eq(t, routes.CandidateReady(guardFor(A, prepared.Current.Revision, "new_connection"), 102, nil, CandidateProof{}).Accepted, true)+ edge := edgeOf(t, routes, A)+ eq(t, edge.ConnectionID, "new_connection")+ eq(t, edge.ParentPeerID, B)+ eq(t, edge.Usable, true)+}++// TS 3020: invalidates one exact active Peer edge from its parent idempotently+func TestInvalidatesOneExactActivePeerEdgeFromParentIdempotently(t *testing.T) {+ routes := newController(2, Options{})+ addViewer(routes, A, 0, nil)+ addViewer(routes, B, 1, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ report := ParentEdgeGuard{+ ParentPeerID: HOST,+ ParentSessionID: "host_session",+ RouteRevision: routes.Snapshot().Revision,+ ConnectionID: "a_from_host",+ }++ eq(t, routes.InvalidateDirectEdgeFromParent(report, ms(10)), true)+ afterFirst := routes.Snapshot()+ aEdge, _ := afterFirst.UpstreamByViewer.Get(A)+ eq(t, aEdge.Usable, false)+ eq(t, aEdge.ConnectionID, "a_from_host")+ bEdge, _ := afterFirst.UpstreamByViewer.Get(B)+ eq(t, bEdge.Usable, true)+ eq(t, bEdge.ConnectionID, "b_from_host")+ eq(t, routes.InvalidateDirectEdgeFromParent(report, ms(11)), true)+ eq(t, routes.Snapshot().FactVersion, afterFirst.FactVersion)+ unknown := report+ unknown.ConnectionID = "unknown_connection"+ eq(t, routes.InvalidateDirectEdgeFromParent(unknown, nil), false)+ operation := must(t, routes.Reconcile(12).Operation)+ eq(t, operation.ChildPeerID, A)+ eq(t, operation.Reason, DemandEdgeUnavailable)+ eqSlice(t, tuples(operation), []CandidateTuple{peerTuple(B)})+}++// TS 3062: advances one candidate cursor without resetting the operation deadline+func TestAdvancesOneCandidateCursorWithoutResettingOperationDeadline(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, A, 2, nil)+ operation := must(t, routes.Reconcile(1_000).Operation)+ deadline := operation.DeadlineAtMs+ first := beginOperation(t, routes, BeginInput{NowMs: 1_001, ConnectionID: "candidate_1", Reservation: direct()})+ failed := routes.CandidateFailed(guardFor(A, first.Current.Revision, "candidate_1"), 1_001)+ eq(t, failed.Accepted, true)+ if failed.ActiveRevision <= first.Current.Revision {+ t.Fatalf("activeRevision %d did not advance past %d", failed.ActiveRevision, first.Current.Revision)+ }+ eqSlice(t, failed.FailedPeerIDs, []string{})+ eqLabels(t, failed.Released)+ pending := must(t, routes.Snapshot().Operation)+ eq(t, pending.Cursor, 1)+ eq(t, pending.DeadlineAtMs, deadline)++ second := beginOperation(t, routes, BeginInput{+ NowMs: 1_002,+ ConnectionID: "candidate_2",+ PublicationGeneration: "publication_2",+ PublicationConnectionID: "publication_connection_2",+ Reservation: sfuCreate("candidate_2_edge", "candidate_2_publication"),+ })+ lateReady := routes.CandidateReady(guardFor(A, second.Current.Revision, "candidate_2"), deadline, nil, CandidateProof{})+ eq(t, lateReady.Accepted, false)+ eqSlice(t, lateReady.FailedPeerIDs, []string{A})+ eqLabels(t, lateReady.Released, "candidate_2_edge", "candidate_2_publication")+ noOperation(t, routes.Snapshot().Operation)+ eq(t, routes.CandidateReady(guardFor(A, second.Current.Revision, "candidate_2"), deadline+1, nil, CandidateProof{}).Accepted, false)+ noOperation(t, routes.Reconcile(deadline+1).Operation)+ routes.TouchExternalFacts()+ eq(t, must(t, routes.Reconcile(deadline+2).Operation).ChildPeerID, A)+}++// TS 3123: reserves one derived deadline stage for direct and SFU+func TestReservesOneDerivedDeadlineStageForDirectAndSfu(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ addViewer(routes, A, 0, nil)++ operation := must(t, routes.Reconcile(0).Operation)+ eq(t, operation.DeadlineAtMs, 10_000)+ eq(t, operation.WakeAtMs, 5_000)+ for _, want := range []CandidateTuple{peerTuple(B), sfuTuple(PublicationCreate)} {+ if !slices.Contains(tuples(operation), want) {+ t.Fatalf("candidates %+v do not contain %+v", tuples(operation), want)+ }+ }++ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "silent_direct", Reservation: direct()})+ directExpired := routes.OperationExpired(operation.WakeAtMs)+ eq(t, directExpired.Accepted, true)+ eqSlice(t, directExpired.FailedPeerIDs, []string{})+ pending := must(t, routes.Snapshot().Operation)+ eq(t, pending.DeadlineAtMs, 10_000)+ eq(t, pending.WakeAtMs, 10_000)+ if pending.Current != nil {+ t.Fatal("expected no live attempt")+ }+ eq(t, pending.Candidates[pending.Cursor].Tuple.Kind, UpstreamSfu)++ prepared := beginOperation(t, routes, BeginInput{+ NowMs: 7_000,+ ConnectionID: "sfu_subscription",+ PublicationGeneration: "publication_generation",+ PublicationConnectionID: "publication_connection",+ Reservation: sfuCreate("sfu_edge", "sfu_publication"),+ })+ eq(t, routes.CandidateReady(guardFor(A, prepared.Current.Revision, "sfu_subscription"), 9_000, nil, CandidateProof{}).Accepted, true)+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamSfu)+ eq(t, edge.Usable, true)+}++// TS 3186: uses the same direct head-start after an early hard failure+func TestUsesSameDirectHeadStartAfterEarlyHardFailure(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, D, 0, nil)+ routes.hydrateEdge(D, peerEdge(HOST, "host_full"))+ routes.hydrateHostPublication("publication_1", res("publication_resource"), "")+ for _, peerID := range []string{B, C} {+ addViewer(routes, peerID, 1, nil)+ routes.hydrateEdge(peerID, sfuEdge("publication_1", peerID+"_sfu", peerID+"_subscription"))+ }+ addViewer(routes, A, 0, nil)++ operation := must(t, routes.Reconcile(0).Operation)+ eqSlice(t, tupleKinds(operation), []UpstreamKind{UpstreamPeer, UpstreamSfu, UpstreamPeer})+ first := beginOperation(t, routes, BeginInput{NowMs: 1, ConnectionID: "first_direct", Reservation: direct()})+ eq(t, routes.CandidateFailed(guardFor(A, first.Current.Revision, "first_direct"), 2).Accepted, true)+ pending := must(t, routes.Snapshot().Operation)+ eq(t, pending.Cursor, 1)+ eq(t, pending.WakeAtMs, operation.WakeAtMs)+ eq(t, pending.Candidates[1].Tuple.Kind, UpstreamPeer)+}++// TS 3231: keeps a transport-connected direct candidate until the total deadline+func TestKeepsTransportConnectedDirectCandidateUntilTotalDeadline(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, D, 0, nil)+ routes.hydrateEdge(D, peerEdge(HOST, "host_full"))+ routes.hydrateHostPublication("publication", res("publication_resource"), "")+ addViewer(routes, B, 1, nil)+ routes.hydrateEdge(B, sfuEdge("publication", "b_sfu", "b_subscription"))+ addViewer(routes, A, 0, nil)++ operation := must(t, routes.Reconcile(0).Operation)+ directOp := beginOperation(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_direct", Reservation: direct()})+ eq(t, routes.CandidateTransportConnected(guardFor(A, directOp.Current.Revision, "a_direct"), 1_000).Accepted, true)+ eq(t, routes.CandidateTransportConnected(guardFor(A, directOp.Current.Revision, "a_direct"), 1_001).Accepted, true)+ eq(t, routes.CandidateTransportConnected(guardFor(A, directOp.Current.Revision, "stale_direct"), 1_002).Accepted, false)+ eq(t, routes.Snapshot().Revision, directOp.Current.Revision-1)+ eq(t, must(t, routes.Snapshot().Operation).WakeAtMs, operation.DeadlineAtMs)+ eq(t, routes.OperationExpired(operation.WakeAtMs).Accepted, false)+ eq(t, must(t, routes.Snapshot().Operation).Current.ConnectionID, "a_direct")+ eq(t, routes.CandidateReady(guardFor(A, directOp.Current.Revision, "a_direct"), operation.WakeAtMs+1, nil, CandidateProof{}).Accepted, true)+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ConnectionID, "a_direct")+}++// TS 3288: keeps SFU active while converging through an SFU-fed parent+func TestKeepsSfuActiveWhileConvergingThroughSfuFedParent(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateHostPublication("publication_generation", res("publication_resource"), "")+ routes.hydrateEdge(B, sfuEdge("publication_generation", "b_sfu", "b_subscription"))+ addViewer(routes, C, 0, nil)+ routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"))+ addViewer(routes, A, 0, nil)++ acquisition := must(t, routes.Reconcile(0).Operation)+ eq(t, acquisition.Candidates[0].Tuple, peerTuple(B))+ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_direct_head_start", Reservation: direct()})+ routes.OperationExpired(acquisition.WakeAtMs)+ prepared := beginOperation(t, routes, BeginInput{+ NowMs: acquisition.WakeAtMs + 1, ConnectionID: "a_sfu_reuse", Reservation: sfuReuse("a_subscription"),+ })+ eq(t, routes.CandidateReady(guardFor(A, prepared.Current.Revision, "a_sfu_reuse"), acquisition.WakeAtMs+2, nil, CandidateProof{}).Accepted, true)+ publication := routes.Snapshot().HostPublication+ if publication == nil {+ t.Fatal("expected a host publication")+ }+ eq(t, publication.Generation, "publication_generation")+ eq(t, publication.Usable, true)+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamSfu)+ eq(t, edge.PublicationGeneration, "publication_generation")+ eq(t, edge.Usable, true)+ convergence := must(t, routes.Reconcile(acquisition.WakeAtMs+3).Operation)+ eq(t, convergence.ChildPeerID, A)+ eq(t, convergence.Reason, DemandDirectConvergence)+ eq(t, convergence.Candidates[0].Tuple, peerTuple(B))+ directOp := beginOperation(t, routes, BeginInput{NowMs: acquisition.WakeAtMs + 4, ConnectionID: "a_from_b", Reservation: direct()})+ eq(t, must(t, routes.Snapshot().Operation).WakeAtMs, convergence.DeadlineAtMs)+ edge = edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamSfu)+ eq(t, edge.ConnectionID, "a_sfu_reuse")+ eq(t, routes.CandidateReady(guardFor(A, directOp.Current.Revision, "a_from_b"), acquisition.WakeAtMs+5, nil, CandidateProof{}).Accepted, true)+ edge = edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ParentPeerID, B)+ eq(t, edge.ConnectionID, "a_from_b")+}++// TS 3380: advances exact direct convergence failures without failing SFU+func TestAdvancesExactDirectConvergenceFailuresWithoutFailingSfu(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, D, 0, nil)+ routes.hydrateEdge(D, peerEdge(HOST, "host_full"))+ routes.hydrateHostPublication("publication_1", res("publication_resource"), "")+ for _, peerID := range []string{B, C} {+ addViewer(routes, peerID, 1, nil)+ routes.hydrateEdge(peerID, sfuEdge("publication_1", peerID+"_sfu", peerID+"_subscription"))+ }+ addViewer(routes, A, 0, ms(0))+ acquisition := must(t, routes.Reconcile(0).Operation)+ headStartTuple := acquisition.Candidates[0].Tuple+ eq(t, headStartTuple.Kind, UpstreamPeer)+ headStartParent := headStartTuple.ParentPeerID+ otherParent := B+ if headStartParent == B {+ otherParent = C+ }+ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_direct_head_start", Reservation: direct()})+ routes.OperationExpired(acquisition.WakeAtMs)+ sfu := beginOperation(t, routes, BeginInput{NowMs: acquisition.WakeAtMs + 1, ConnectionID: "a_sfu", Reservation: sfuReuse("a_subscription")})+ eq(t, routes.CandidateReady(guardFor(A, sfu.Current.Revision, "a_sfu"), acquisition.WakeAtMs+2, nil, CandidateProof{}).Accepted, true)++ first := must(t, routes.Reconcile(acquisition.WakeAtMs+3).Operation)+ eq(t, first.Candidates[0].Tuple.Kind, UpstreamPeer)+ eq(t, first.Candidates[0].Tuple.ParentPeerID, otherParent)+ failed := beginOperation(t, routes, BeginInput{NowMs: acquisition.WakeAtMs + 4, ConnectionID: "a_direct_followup", Reservation: direct()})+ eqSlice(t, routes.CandidateFailed(guardFor(A, failed.Current.Revision, "a_direct_followup"), acquisition.WakeAtMs+5).FailedPeerIDs, []string{})+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamSfu)+ eq(t, edge.ConnectionID, "a_sfu")+ retry := must(t, routes.Reconcile(acquisition.WakeAtMs+6).Operation)+ eq(t, retry.Candidates[0].Tuple.Kind, UpstreamPeer)+ eq(t, retry.Candidates[0].Tuple.ParentPeerID, headStartParent)+}++// TS 3451: round-robins background direct convergence between SFU Viewers+func TestRoundRobinsBackgroundDirectConvergenceBetweenSfuViewers(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ routes.hydrateHostPublication("publication", res("publication_resource"), "")+ for _, peerID := range []string{B, C} {+ addViewer(routes, peerID, 2, nil)+ routes.hydrateEdge(peerID, sfuEdge("publication", peerID+"_sfu", peerID+"_subscription"))+ }++ nowMs := int64(0)+ for _, peerID := range []string{A, D} {+ addViewer(routes, peerID, 0, ms(nowMs))+ acquisition := must(t, routes.Reconcile(nowMs).Operation)+ beginCandidate(t, routes, BeginInput{NowMs: nowMs + 1, ConnectionID: peerID + "_head_start", Reservation: direct()})+ routes.OperationExpired(acquisition.WakeAtMs)+ sfu := beginOperation(t, routes, BeginInput{+ NowMs: acquisition.WakeAtMs + 1, ConnectionID: peerID + "_sfu", Reservation: sfuReuse(peerID + "_subscription"),+ })+ eq(t, routes.CandidateReady(guardFor(peerID, sfu.Current.Revision, peerID+"_sfu"), acquisition.WakeAtMs+2, nil, CandidateProof{}).Accepted, true)+ nowMs = acquisition.WakeAtMs + 3+ }++ first := must(t, routes.Reconcile(nowMs).Operation)+ eq(t, first.ChildPeerID, A)+ eq(t, first.Reason, DemandDirectConvergence)+ firstAttempt := beginOperation(t, routes, BeginInput{NowMs: nowMs + 1, ConnectionID: "a_background_direct", Reservation: direct()})+ eq(t, routes.CandidateFailed(guardFor(A, firstAttempt.Current.Revision, "a_background_direct"), nowMs+2).Accepted, true)+ next := must(t, routes.Reconcile(nowMs+3).Operation)+ eq(t, next.ChildPeerID, D)+ eq(t, next.Reason, DemandDirectConvergence)+}++// TS 3516: preempts direct convergence when another Viewer needs a route+func TestPreemptsDirectConvergenceWhenAnotherViewerNeedsRoute(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateHostPublication("publication_1", res("publication_resource"), "")+ routes.hydrateEdge(B, sfuEdge("publication_1", "b_sfu", "b_subscription"))+ addViewer(routes, C, 0, nil)+ routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"))+ addViewer(routes, A, 0, ms(0))+ acquisition := must(t, routes.Reconcile(0).Operation)+ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_direct_head_start", Reservation: direct()})+ routes.OperationExpired(acquisition.WakeAtMs)+ sfu := beginOperation(t, routes, BeginInput{NowMs: acquisition.WakeAtMs + 1, ConnectionID: "a_sfu", Reservation: sfuReuse("a_subscription")})+ routes.CandidateReady(guardFor(A, sfu.Current.Revision, "a_sfu"), acquisition.WakeAtMs+2, nil, CandidateProof{})+ eq(t, must(t, routes.Reconcile(acquisition.WakeAtMs+3).Operation).Reason, DemandDirectConvergence)+ beginCandidate(t, routes, BeginInput{NowMs: acquisition.WakeAtMs + 4, ConnectionID: "a_direct_pending", Reservation: directOverlap("a_overlap")})++ activeRevision := routes.Snapshot().Revision+ eq(t, routes.InvalidateEdge(edgeGuard(C, "host_session", activeRevision, "c_from_host"), ms(acquisition.WakeAtMs+5)), true)+ reconciled := routes.Reconcile(acquisition.WakeAtMs + 6)+ eqLabels(t, reconciled.Released, "a_overlap")+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamSfu)+ eq(t, edge.ConnectionID, "a_sfu")+ preempted := must(t, reconciled.Operation)+ eq(t, preempted.ChildPeerID, C)+ eq(t, preempted.Reason, DemandEdgeUnavailable)+}++// TS 3579: owns Host-full SFU bootstrap failure by the waiting demand+func TestOwnsHostFullSfuBootstrapFailureByWaitingDemand(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ addViewer(routes, C, 0, nil)+ routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"))+ addViewer(routes, A, 0, nil)+ addViewer(routes, D, 0, nil)++ operation := must(t, routes.Reconcile(0).Operation)+ eq(t, hasTuple(operation, isSfu), false)+ eq(t, operation.WakeAtMs, 5_000)+ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_silent_direct", Reservation: direct()})+ blocked := routes.OperationExpired(operation.WakeAtMs)+ eq(t, blocked.Accepted, true)+ eqSlice(t, blocked.FailedPeerIDs, []string{})+ eqLabels(t, blocked.Released)+ noOperation(t, routes.Snapshot().Operation)++ bootstrap := must(t, routes.Reconcile(operation.WakeAtMs+1).Operation)+ eq(t, bootstrap.ChildPeerID, C)+ eq(t, bootstrap.DemandPeerID, A)+ eq(t, bootstrap.Candidates[0].Tuple, sfuTuple(PublicationCreate))+ eq(t, bootstrap.Candidates[0].EndpointTransition.Kind, TransitionOverlap)+ firstCarrier := beginOperation(t, routes, BeginInput{+ NowMs: operation.WakeAtMs + 2,+ ConnectionID: "c_bootstrap_sfu",+ PublicationGeneration: "c_bootstrap_publication",+ PublicationConnectionID: "c_bootstrap_ingress",+ Reservation: sfuCreateOverlap("c_bootstrap_subscription", "c_bootstrap_publication_resource", "c_bootstrap_overlap"),+ })+ eqSlice(t, routes.CandidateFailed(guardFor(C, firstCarrier.Current.Revision, "c_bootstrap_sfu"), operation.WakeAtMs+3).FailedPeerIDs, []string{})+ cEdge := edgeOf(t, routes, C)+ eq(t, cEdge.ConnectionID, "c_from_host")+ eq(t, cEdge.Usable, true)+ eq(t, cEdge.PhysicalActive, true)++ secondBootstrap := must(t, routes.Reconcile(operation.WakeAtMs+4).Operation)+ eq(t, secondBootstrap.ChildPeerID, B)+ eq(t, secondBootstrap.DemandPeerID, A)+ eq(t, secondBootstrap.Reason, DemandSfuBootstrap)+ secondCarrier := beginOperation(t, routes, BeginInput{+ NowMs: operation.WakeAtMs + 5,+ ConnectionID: "b_bootstrap_sfu",+ PublicationGeneration: "b_bootstrap_publication",+ PublicationConnectionID: "b_bootstrap_ingress",+ Reservation: sfuCreateOverlap("b_bootstrap_subscription", "b_bootstrap_publication_resource", "b_bootstrap_overlap"),+ })+ eqSlice(t, routes.CandidateFailed(guardFor(B, secondCarrier.Current.Revision, "b_bootstrap_sfu"), operation.WakeAtMs+6).FailedPeerIDs, []string{A})+ for _, seed := range [][2]string{{B, "b_from_host"}, {C, "c_from_host"}} {+ edge := edgeOf(t, routes, seed[0])+ eq(t, edge.ConnectionID, seed[1])+ eq(t, edge.Usable, true)+ eq(t, edge.PhysicalActive, true)+ }+ nextDemand := must(t, routes.Reconcile(operation.WakeAtMs+7).Operation)+ eq(t, nextDemand.ChildPeerID, D)+ eq(t, nextDemand.Reason, DemandJoin)+ beginCandidate(t, routes, BeginInput{NowMs: operation.WakeAtMs + 8, ConnectionID: "d_direct", Reservation: direct()})+ eqSlice(t, routes.OperationExpired(nextDemand.DeadlineAtMs).FailedPeerIDs, []string{D})+ noOperation(t, routes.Reconcile(nextDemand.DeadlineAtMs+1).Operation)+}++// TS 3680: abandons bootstrap when a Host slot becomes available+func TestAbandonsBootstrapWhenHostSlotBecomesAvailable(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ eq(t, routes.SetEffectiveCapacity(HOST, "host_session", 1, nil), true)+ addViewer(routes, B, 0, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ addViewer(routes, A, 0, nil)++ bootstrap := must(t, routes.Reconcile(0).Operation)+ eq(t, bootstrap.ChildPeerID, B)+ eq(t, bootstrap.DemandPeerID, A)+ eq(t, bootstrap.Reason, DemandSfuBootstrap)+ prepared := beginOperation(t, routes, BeginInput{+ NowMs: 1,+ ConnectionID: "stale_bootstrap",+ PublicationGeneration: "stale_publication",+ PublicationConnectionID: "stale_ingress",+ Reservation: sfuCreateOverlap("stale_subscription", "stale_publication_resource", "stale_overlap"),+ })++ eq(t, routes.SetEffectiveCapacity(HOST, "host_session", 2, nil), true)+ stale := routes.CandidateReady(guardFor(B, prepared.Current.Revision, "stale_bootstrap"), 2, nil, CandidateProof{})+ eq(t, stale.Accepted, false)+ containsLabels(t, stale.Released, "stale_subscription", "stale_publication_resource", "stale_overlap")+ bEdge := edgeOf(t, routes, B)+ eq(t, bEdge.ConnectionID, "b_from_host")+ eq(t, bEdge.Usable, true)+ eq(t, bEdge.PhysicalActive, true)+ join := must(t, routes.Reconcile(3).Operation)+ eq(t, join.ChildPeerID, A)+ eq(t, join.DemandPeerID, A)+ eq(t, join.Reason, DemandJoin)+}++// TS 3731: tries SFU first after bootstrap and retains the direct suffix+func TestTriesSfuFirstAfterBootstrapAndRetainsDirectSuffix(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ for _, seed := range [][2]string{{B, "b_from_host"}, {C, "c_from_host"}} {+ addViewer(routes, seed[0], 1, nil)+ routes.hydrateEdge(seed[0], peerEdge(HOST, seed[1]))+ }+ addViewer(routes, A, 0, nil)++ acquisition := must(t, routes.Reconcile(0).Operation)+ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_direct_head_start", Reservation: direct()})+ routes.OperationExpired(acquisition.WakeAtMs)+ bootstrap := must(t, routes.Reconcile(acquisition.WakeAtMs+1).Operation)+ carrier := beginOperation(t, routes, BeginInput{+ NowMs: acquisition.WakeAtMs + 2,+ ConnectionID: "bootstrap_sfu",+ PublicationGeneration: "bootstrap_publication",+ PublicationConnectionID: "bootstrap_ingress",+ Reservation: sfuCreateOverlap("carrier_subscription", "bootstrap_publication_resource", "bootstrap_overlap"),+ })+ eq(t, routes.CandidateReady(CandidateGuard{+ ChildPeerID: bootstrap.ChildPeerID,+ ChildSessionID: bootstrap.ChildSessionID,+ Revision: carrier.Current.Revision,+ ConnectionID: "bootstrap_sfu",+ }, acquisition.WakeAtMs+3, nil, CandidateProof{}).Accepted, true)++ demand := must(t, routes.Reconcile(acquisition.WakeAtMs+4).Operation)+ eq(t, demand.ChildPeerID, A)+ eq(t, demand.DemandPeerID, A)+ eq(t, demand.Reason, DemandJoin)+ eq(t, demand.Candidates[0].Tuple, sfuTuple(PublicationReuse))+ for _, tuple := range tuplesFrom(demand, 1) {+ eq(t, tuple.Kind, UpstreamPeer)+ }+ subscription := beginOperation(t, routes, BeginInput{NowMs: acquisition.WakeAtMs + 5, ConnectionID: "a_sfu", Reservation: sfuReuse("a_subscription")})+ eq(t, routes.CandidateFailed(guardFor(A, subscription.Current.Revision, "a_sfu"), acquisition.WakeAtMs+6).Accepted, true)+ pending := must(t, routes.Snapshot().Operation)+ eq(t, pending.Candidates[pending.Cursor].Tuple.Kind, UpstreamPeer)+ directOp := beginOperation(t, routes, BeginInput{NowMs: acquisition.WakeAtMs + 7, ConnectionID: "a_deferred_direct", Reservation: direct()})+ eq(t, routes.CandidateReady(guardFor(A, directOp.Current.Revision, "a_deferred_direct"), acquisition.WakeAtMs+8, nil, CandidateProof{}).Accepted, true)+ edge := edgeOf(t, routes, A)+ eq(t, edge.Kind, UpstreamPeer)+ eq(t, edge.ConnectionID, "a_deferred_direct")+ convergence := must(t, routes.Reconcile(acquisition.WakeAtMs+9).Operation)+ eq(t, convergence.ChildPeerID, bootstrap.ChildPeerID)+ eq(t, convergence.Reason, DemandDirectConvergence)+}++// TS 3819: replans when the current candidate parent fails+func TestReplansWhenCurrentCandidateParentFails(t *testing.T) {+ routes := newController(3, Options{})+ addViewer(routes, A, 1, nil)+ addViewer(routes, B, 1, nil)+ addViewer(routes, C, 1, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_old"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_old"))+ routes.hydrateEdge(C, peerEdge(HOST, "c_old"))+ revision := routes.Snapshot().Revision+ eq(t, routes.InvalidateEdge(edgeGuard(A, "host_session", revision, "a_old"), nil), true)+ routes.Reconcile(0)+ current := beginOperation(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_new", Reservation: direct()})+ currentTuple := current.Current.Tuple+ eq(t, currentTuple.Kind, UpstreamPeer)+ failedParentPeerID := currentTuple.ParentPeerID+ failedParentConnectionID := "c_old"+ if failedParentPeerID == B {+ failedParentConnectionID = "b_old"+ }+ eq(t, routes.InvalidateEdge(edgeGuard(failedParentPeerID, "host_session", revision, failedParentConnectionID), nil), true)+ eq(t, routes.CandidateReady(guardFor(A, current.Current.Revision, "a_new"), 2, nil, CandidateProof{}).Accepted, false)+ replacement := beginOperation(t, routes, BeginInput{NowMs: 2, ConnectionID: "a_new_2", Reservation: direct()})+ eq(t, routes.CandidateReady(guardFor(A, replacement.Current.Revision, "a_new_2"), 3, nil, CandidateProof{}).Accepted, true)+ eq(t, must(t, routes.Reconcile(3).Operation).ChildPeerID, failedParentPeerID)+}++// TS 3886: keeps an active candidate when an unrelated session is replaced+func TestKeepsActiveCandidateWhenUnrelatedSessionIsReplaced(t *testing.T) {+ routes := newController(2, Options{})+ for _, seed := range [][2]string{{B, "b_from_host"}, {C, "c_from_host"}} {+ addViewer(routes, seed[0], 1, nil)+ routes.hydrateEdge(seed[0], peerEdge(HOST, seed[1]))+ }+ addViewer(routes, A, 0, nil)+ operation := must(t, routes.Reconcile(0).Operation)+ active := beginOperation(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_active_candidate", Reservation: direct()})+ tuple := active.Current.Tuple+ eq(t, tuple.Kind, UpstreamPeer)+ unrelatedPeerID := B+ if tuple.ParentPeerID == B {+ unrelatedPeerID = C+ }++ eqLabels(t, routes.UpsertParticipant(viewerInput(unrelatedPeerID, unrelatedPeerID+"_replacement", 1), ms(2)))+ current := must(t, routes.Snapshot().Operation).Current+ if current == nil {+ t.Fatal("expected the live attempt to survive")+ }+ eq(t, current.Revision, operation.BaseRevision+1)+ eq(t, current.ConnectionID, "a_active_candidate")+}++// TS 3920: uses a freed Host slot for new demand without moving healthy descendants+func TestUsesFreedHostSlotForNewDemandWithoutMovingHealthyDescendants(t *testing.T) {+ routes := newController(2, Options{})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 2, nil)+ addViewer(routes, C, 0, nil)+ addViewer(routes, D, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_root"))+ routes.hydrateEdge(B, peerEdge(HOST, "b_root"))+ routes.hydrateEdge(C, peerEdge(A, "c_from_a"))+ routes.hydrateEdge(D, peerEdge(B, "d_from_b"))++ eq(t, routes.ConfirmDeparture(B, nil), true)+ repair := must(t, routes.Reconcile(0).Operation)+ eq(t, repair.ChildPeerID, D)+ eq(t, repair.Candidates[0].Tuple, peerTuple(A))+ commitCurrent(t, routes, 1, "d_from_a")+ noOperation(t, routes.Reconcile(2).Operation)+ eq(t, hasEdge(routes, B), false)++ addViewer(routes, E, 0, nil)+ join := must(t, routes.Reconcile(3).Operation)+ eq(t, join.ChildPeerID, E)+ eq(t, join.Candidates[0].Tuple, peerTuple(HOST))+ commitCurrent(t, routes, 4, "e_from_host")++ cEdge := edgeOf(t, routes, C)+ eq(t, cEdge.ParentPeerID, A)+ eq(t, cEdge.ConnectionID, "c_from_a")+ dEdge := edgeOf(t, routes, D)+ eq(t, dEdge.ParentPeerID, A)+ eq(t, dEdge.ConnectionID, "d_from_a")+ eEdge := edgeOf(t, routes, E)+ eq(t, eEdge.ParentPeerID, HOST)+ eq(t, eEdge.ConnectionID, "e_from_host")+}++// TS 3967: keeps grace media, then reparents a confirmed relay departure+func TestKeepsGraceMediaThenReparentsConfirmedRelayDeparture(t *testing.T) {+ routes := newController(2, Options{})+ addViewer(routes, A, 2, nil)+ addViewer(routes, B, 1, nil)+ addViewer(routes, C, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_connection"))+ routes.hydrateEdge(B, peerEdge(A, "b_connection"))+ routes.hydrateEdge(C, peerEdge(B, "c_connection"))++ eq(t, routes.DisconnectSession(A, sessionOf(A)), true)+ noOperation(t, routes.Reconcile(0).Operation)+ eq(t, routes.ConfirmDeparture(A, nil), true)+ eq(t, must(t, routes.Reconcile(1).Operation).ChildPeerID, B)+ commitCurrent(t, routes, 2, "b_reparented")+ beforePrune := routes.Snapshot().Revision+ after := routes.Reconcile(3)+ if !slices.Contains(after.RemovedPeerIDs, A) {+ t.Fatalf("removedPeerIds %v does not contain A", after.RemovedPeerIDs)+ }+ if routes.Snapshot().Revision <= beforePrune {+ t.Fatalf("revision %d did not advance past %d", routes.Snapshot().Revision, beforePrune)+ }+ cEdge := edgeOf(t, routes, C)+ eq(t, cEdge.ParentPeerID, B)+ eq(t, cEdge.ConnectionID, "c_connection")+}++// TS 3991: moves newest overflow children and supports effective capacity zero+func TestMovesNewestOverflowChildrenAndSupportsEffectiveCapacityZero(t *testing.T) {+ routes := newController(3, Options{})+ addViewer(routes, A, 3, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "a_connection"))+ for _, peerID := range []string{B, C, D} {+ addViewer(routes, peerID, 0, nil)+ routes.hydrateEdge(peerID, peerEdge(A, peerID+"_connection"))+ }+ eq(t, routes.SetEffectiveCapacity(A, sessionOf(A), 1, nil), true)+ eq(t, must(t, routes.Reconcile(0).Operation).ChildPeerID, D)+ eqLabels(t, routes.SetPaused(true, nil))+ eq(t, routes.SetEffectiveCapacity(A, sessionOf(A), 0, nil), true)+ eqLabels(t, routes.SetPaused(false, nil))+ eq(t, must(t, routes.Reconcile(1).Operation).ChildPeerID, D)++ blocked := newController(1, Options{})+ addViewer(blocked, A, 0, nil)+ addViewer(blocked, B, 0, nil)+ blocked.hydrateEdge(A, peerEdge(HOST, "blocked_a"))+ blocked.hydrateEdge(B, peerEdge(A, "blocked_b"))+ noOperation(t, blocked.Reconcile(0).Operation)+ noOperation(t, blocked.Reconcile(1).Operation)+}++// TS 4015: aborts pending SFU resources on pause and repairs publication+func TestAbortsPendingSfuResourcesOnPauseAndRepairsPublication(t *testing.T) {+ routes := newController(1, Options{SfuEnabled: true})+ addViewer(routes, A, 1, nil)+ addViewer(routes, B, 0, nil)+ routes.hydrateHostPublication("publication_1", res("publication_resource"), "")+ routes.hydrateEdge(A, sfuEdge("publication_1", "a_sfu", "a_subscription"))+ operation := must(t, routes.Reconcile(0).Operation)+ eq(t, operation.Candidates[0].Tuple, peerTuple(A))+ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "b_direct_head_start", Reservation: direct()})+ routes.OperationExpired(operation.WakeAtMs)+ beginCandidate(t, routes, BeginInput{NowMs: operation.WakeAtMs + 1, ConnectionID: "b_candidate", Reservation: sfuReuse("b_subscription")})+ eqLabels(t, routes.SetPaused(true, nil), "b_subscription")+ noOperation(t, routes.Snapshot().Operation)+ eq(t, edgeOf(t, routes, A).ConnectionID, "a_sfu")+ routes.SetPaused(false, nil)+ eq(t, routes.InvalidateHostPublication(PublicationGuard{+ HostSessionID: "host_session",+ RouteRevision: routes.Snapshot().Revision,+ Generation: "publication_1",+ ConnectionID: "publication:publication_1",+ }, nil), true)+ routes.TouchExternalFacts()+ repair := must(t, routes.Reconcile(2).Operation)+ eq(t, repair.ChildPeerID, A)+ eq(t, repair.Candidates[0].Tuple, peerTuple(HOST))+ skipCandidate(t, routes, 3)+ eq(t, must(t, routes.Snapshot().Operation).Candidates[1].Tuple, sfuTuple(PublicationReplace))+ expectPanic(t, "endpoint overlap reservation", func() {+ beginCandidate(t, routes, BeginInput{+ NowMs: 3,+ ConnectionID: "a_sfu_2",+ PublicationGeneration: "publication_2",+ PublicationConnectionID: "publication_connection_2",+ Reservation: sfuCreate("a_subscription_2", "publication_resource_2"),+ })+ })+ publicationRepair := beginOperation(t, routes, BeginInput{+ NowMs: 3,+ ConnectionID: "a_sfu_2",+ PublicationGeneration: "publication_2",+ PublicationConnectionID: "publication_connection_2",+ Reservation: sfuCreateOverlap("a_subscription_2", "publication_resource_2", "publication_overlap"),+ })+ repaired := routes.CandidateReady(guardFor(A, publicationRepair.Current.Revision, "a_sfu_2"), 4, nil, CandidateProof{})+ eq(t, repaired.Accepted, true)+ eq(t, len(repaired.Released), 3)+ containsLabels(t, repaired.Released, "publication_overlap", "a_subscription", "publication_resource")+ publication := routes.Snapshot().HostPublication+ if publication == nil {+ t.Fatal("expected a repaired publication")+ }+ eq(t, publication.Generation, "publication_2")+ eq(t, publication.Usable, true)+ eq(t, publication.PhysicalActive, true)++ bootstrap := newController(1, Options{SfuEnabled: true})+ addViewer(bootstrap, A, 0, nil)+ addViewer(bootstrap, B, 0, nil)+ bootstrap.hydrateEdge(A, peerEdge(HOST, "bootstrap_a"))+ bootstrapOperation := must(t, bootstrap.Reconcile(0).Operation)+ eq(t, bootstrapOperation.ChildPeerID, A)+ eq(t, bootstrapOperation.Candidates[0].Tuple, sfuTuple(PublicationCreate))+ expectPanic(t, "endpoint overlap reservation", func() {+ beginCandidate(t, bootstrap, BeginInput{+ NowMs: 2,+ ConnectionID: "bootstrap_sfu",+ PublicationGeneration: "bootstrap_publication",+ PublicationConnectionID: "bootstrap_ingress_connection",+ Reservation: sfuCreate("bootstrap_subscription", "bootstrap_ingress"),+ })+ })+ preparedBootstrap := beginOperation(t, bootstrap, BeginInput{+ NowMs: 2,+ ConnectionID: "bootstrap_sfu",+ PublicationGeneration: "bootstrap_publication",+ PublicationConnectionID: "bootstrap_ingress_connection",+ Reservation: sfuCreateOverlap("bootstrap_subscription", "bootstrap_ingress", "bootstrap_overlap"),+ })+ eq(t, bootstrap.CandidateReady(guardFor(A, preparedBootstrap.Current.Revision, "bootstrap_sfu"), 3, nil, CandidateProof{}).Accepted, true)+ eq(t, must(t, bootstrap.Reconcile(4).Operation).ChildPeerID, B)+}++// TS 4153: reopens SFU bootstrap after the physical publication retires+func TestReopensSfuBootstrapAfterPhysicalPublicationRetires(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, A, 0, nil)+ routes.hydrateHostPublication("retired_publication", res("publication_resource"), "")+ routes.hydrateEdge(A, sfuEdge("retired_publication", "a_from_sfu", "a_subscription"))++ publication := routes.Snapshot().HostPublication+ if publication == nil {+ t.Fatal("expected a host publication")+ }+ containsLabels(t, routes.RetireHostPublication(PublicationGuard{+ HostSessionID: publication.HostSessionID,+ RouteRevision: routes.Snapshot().Revision,+ Generation: publication.Generation,+ ConnectionID: publication.ConnectionID,+ }), "a_subscription", "publication_resource")+ if routes.Snapshot().HostPublication != nil {+ t.Fatal("expected no host publication")+ }++ for _, seed := range [][2]string{{B, "b_from_host"}, {C, "c_from_host"}} {+ addViewer(routes, seed[0], 0, nil)+ routes.hydrateEdge(seed[0], peerEdge(HOST, seed[1]))+ }+ reconciled := routes.Reconcile(1)+ eqSlice(t, reconciled.FailedPeerIDs, []string{})+ operation := must(t, reconciled.Operation)+ eq(t, operation.DemandPeerID, A)+ eq(t, operation.Reason, DemandSfuBootstrap)+ eqSlice(t, tuples(operation), []CandidateTuple{sfuTuple(PublicationCreate)})+}++// TS 4199: binds reserve and skip results to the exact candidate cursor+func TestBindsReserveAndSkipResultsToExactCandidateCursor(t *testing.T) {+ reserve := newController(2, Options{})+ addViewer(reserve, A, 2, nil)+ reserve.hydrateEdge(A, peerEdge(HOST, "a_active"))+ addViewer(reserve, B, 0, nil)+ first := must(t, reserve.Reconcile(0).Operation)+ eq(t, first.Candidates[0].Tuple.Kind, UpstreamPeer)+ eq(t, first.Candidates[0].Tuple.ParentPeerID, HOST)+ reserve.SetEffectiveCapacity(HOST, "host_session", 0, nil)+ staleReserve := reserve.BeginCurrentCandidate(BeginInput{+ Guard: cursorGuard(first),+ NowMs: 1,+ ConnectionID: "reserved_for_old_cursor",+ Reservation: directOverlap("stale_reservation"),+ })+ eq(t, staleReserve.Accepted, false)+ eqLabels(t, staleReserve.Released, "stale_reservation")+ rebuilt := must(t, reserve.Snapshot().Operation)+ eq(t, rebuilt.Cursor, 0)+ eqSlice(t, tuples(rebuilt), []CandidateTuple{peerTuple(A)})+ if rebuilt.Current != nil {+ t.Fatal("expected no live attempt")+ }++ skip := newController(2, Options{})+ addViewer(skip, A, 2, nil)+ skip.hydrateEdge(A, peerEdge(HOST, "a_active"))+ addViewer(skip, B, 0, nil)+ staleCursor := must(t, skip.Reconcile(0).Operation)+ skip.SetEffectiveCapacity(HOST, "host_session", 0, nil)+ eq(t, skip.SkipCurrentCandidate(cursorGuard(staleCursor), 1, RejectionStale).Accepted, false)+ pending := must(t, skip.Snapshot().Operation)+ eq(t, pending.Cursor, 0)+ eq(t, pending.Candidates[0].Tuple.Kind, UpstreamPeer)+ eq(t, pending.Candidates[0].Tuple.ParentPeerID, A)+}++// TS 4243: keeps only old SFU roots that still anchor peer descendants+func TestKeepsOnlyOldSfuRootsThatStillAnchorPeerDescendants(t *testing.T) {+ routes := newController(1, Options{SfuEnabled: true})+ addViewer(routes, A, 0, nil)+ addViewer(routes, B, 1, nil)+ addViewer(routes, C, 0, nil)+ addViewer(routes, D, 0, nil)+ routes.hydrateHostPublication("publication_1", res("publication_resource_1"), "")+ for _, seed := range [][2]string{{A, "subscription_a"}, {B, "subscription_b"}, {D, "subscription_d"}} {+ routes.hydrateEdge(seed[0], sfuEdge("publication_1", seed[0]+"_sfu_1", seed[1]))+ }+ routes.hydrateEdge(C, peerEdge(B, "c_from_b"))+ eq(t, routes.InvalidateHostPublication(PublicationGuard{+ HostSessionID: "host_session",+ RouteRevision: 0,+ Generation: "publication_1",+ ConnectionID: "publication:publication_1",+ }, ms(10)), true)+ routes.TouchExternalFacts()+ operation := must(t, routes.Reconcile(20).Operation)+ eq(t, operation.Candidates[0].Tuple, sfuTuple(PublicationReplace))+ expectTransition(t, operation.Candidates[0].EndpointTransition, TransitionOverlap, HOST)+ prepared := beginOperation(t, routes, BeginInput{+ NowMs: 21,+ ConnectionID: "a_sfu_2",+ PublicationGeneration: "publication_2",+ PublicationConnectionID: "publication_connection_2",+ Reservation: sfuCreateOverlap("subscription_a_2", "publication_resource_2", "publication_overlap"),+ })+ settled := routes.CandidateReady(guardFor(A, prepared.Current.Revision, "a_sfu_2"), 22, nil, CandidateProof{})+ eq(t, settled.Accepted, true)+ containsLabels(t, settled.Released, "publication_overlap", "subscription_a", "subscription_b", "subscription_d", "publication_resource_1")+ eq(t, edgeOf(t, routes, A).PublicationGeneration, "publication_2")+ bEdge := edgeOf(t, routes, B)+ eq(t, bEdge.Kind, UpstreamSfu)+ eq(t, bEdge.PublicationGeneration, "publication_1")+ eq(t, bEdge.Usable, false)+ eq(t, bEdge.PhysicalActive, false)+ cEdge := edgeOf(t, routes, C)+ eq(t, cEdge.Kind, UpstreamPeer)+ eq(t, cEdge.ParentPeerID, B)+ eq(t, hasEdge(routes, D), false)+ child := routes.RouteDiagnosticSnapshot(22).Children[1]+ eqDeep(t, child.DemandAgeMs, optInt(12))+ eq(t, child.FinalRoute, "waiting")+ next := must(t, routes.Reconcile(23).Operation)+ eq(t, next.ChildPeerID, B)+ eq(t, next.Reason, DemandEdgeUnavailable)+}++// TS 4328: rebinds direct and SFU media to replacement sessions+func TestRebindsDirectAndSfuMediaToReplacementSessions(t *testing.T) {+ peerRoutes := newController(2, Options{})+ addViewer(peerRoutes, A, 1, nil)+ addViewer(peerRoutes, B, 0, nil)+ peerRoutes.hydrateEdge(A, peerEdge(HOST, "a_direct"))+ peerRoutes.hydrateEdge(B, peerEdge(A, "b_direct"))+ eqLabels(t, peerRoutes.UpsertParticipant(viewerInput(A, "a_replacement", 1), nil))+ aEdge := edgeOf(t, peerRoutes, A)+ eq(t, aEdge.ChildSessionID, "a_replacement")+ eq(t, aEdge.Usable, true)+ eq(t, aEdge.PhysicalActive, true)+ eq(t, edgeOf(t, peerRoutes, B).ParentSessionID, "a_replacement")+ eqLabels(t, peerRoutes.UpsertParticipant(viewerInput(B, "b_replacement", 0), nil))+ bEdge := edgeOf(t, peerRoutes, B)+ eq(t, bEdge.ChildSessionID, "b_replacement")+ eq(t, bEdge.Usable, true)+ eq(t, bEdge.PhysicalActive, true)++ sfuRoutes := newController(1, Options{SfuEnabled: true})+ addViewer(sfuRoutes, A, 0, nil)+ sfuRoutes.hydrateHostPublication("publication", res("publication_resource"), "publication_connection")+ sfuRoutes.hydrateEdge(A, sfuEdge("publication", "subscription_connection", "subscription_resource"))+ eqLabels(t, sfuRoutes.UpsertParticipant(hostInput("host_replacement", 1), nil))+ publication := sfuRoutes.Snapshot().HostPublication+ if publication == nil {+ t.Fatal("expected a host publication")+ }+ eq(t, publication.HostSessionID, "host_replacement")+ eq(t, publication.Usable, true)+ eq(t, publication.PhysicalActive, true)+ eqLabels(t, sfuRoutes.UpsertParticipant(viewerInput(A, "a_replacement", 0), nil))+ sfuEdgeA := edgeOf(t, sfuRoutes, A)+ eq(t, sfuEdgeA.ChildSessionID, "a_replacement")+ eq(t, sfuEdgeA.PhysicalActive, true)+}++// TS 4399: retries a bootstrap carrier only when its transition improves+func TestRetriesBootstrapCarrierOnlyWhenTransitionImproves(t *testing.T) {+ routes := newController(1, Options{SfuEnabled: true})+ addViewer(routes, A, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "failed_direct"))+ eq(t, routes.InvalidateEdge(edgeGuard(A, "host_session", 0, "failed_direct"), nil), true)+ operation := must(t, routes.Reconcile(0).Operation)+ prepared := beginOperation(t, routes, BeginInput{+ NowMs: 1,+ ConnectionID: "failed_sfu",+ PublicationGeneration: "failed_publication",+ PublicationConnectionID: "failed_publication_connection",+ Reservation: sfuCreateOverlap("failed_subscription_resource", "failed_publication_resource", "failed_overlap"),+ })+ failed := routes.CandidateFailed(CandidateGuard{+ ChildPeerID: operation.ChildPeerID,+ ChildSessionID: operation.ChildSessionID,+ Revision: prepared.Current.Revision,+ ConnectionID: "failed_sfu",+ }, 2)+ eq(t, failed.Accepted, true)+ eqSlice(t, failed.FailedPeerIDs, []string{A})+ improved := must(t, routes.Reconcile(3).Operation)+ eq(t, improved.Candidates[0].Tuple, sfuTuple(PublicationCreate))+ expectTransition(t, improved.Candidates[0].EndpointTransition, TransitionNone, HOST)+ improvedAttempt := beginOperation(t, routes, BeginInput{+ NowMs: 4,+ ConnectionID: "improved_sfu",+ PublicationGeneration: "improved_publication",+ PublicationConnectionID: "improved_publication_connection",+ Reservation: sfuCreate("improved_subscription_resource", "improved_publication_resource"),+ })+ failedAgain := routes.CandidateFailed(CandidateGuard{+ ChildPeerID: improved.ChildPeerID,+ ChildSessionID: improved.ChildSessionID,+ Revision: improvedAttempt.Current.Revision,+ ConnectionID: "improved_sfu",+ }, 5)+ eq(t, failedAgain.Accepted, true)+ eqSlice(t, failedAgain.FailedPeerIDs, []string{A})+ factVersion := routes.Snapshot().FactVersion+ noOperation(t, routes.Reconcile(6).Operation)+ eq(t, routes.SetEffectiveCapacity(A, sessionOf(A), 0, nil), true)+ eq(t, routes.Snapshot().FactVersion, factVersion)+ noOperation(t, routes.Reconcile(7).Operation)+ eq(t, routes.InvalidateEdge(edgeGuard(A, "host_session", routes.Snapshot().Revision, "failed_direct"), nil), true)+ eq(t, routes.Snapshot().FactVersion, factVersion)+ noOperation(t, routes.Reconcile(8).Operation)++ addViewer(routes, B, 0, ms(9))+ eq(t, must(t, routes.Reconcile(9).Operation).ChildPeerID, B)+ // TS: `while (routes.snapshot().operation) skipCandidate(routes, 10);` bounded here so a broken port cannot hang.+ for rounds := 0; routes.Snapshot().Operation != nil; rounds++ {+ if rounds > 100 {+ t.Fatal("skipping never exhausted the operation")+ }+ skipCandidate(t, routes, 10)+ }+ noOperation(t, routes.Reconcile(11).Operation)+}++// TS 4472: requires one overlap slot for an SFU-to-Host transition at C=%i+func TestRequiresOneOverlapSlotForSfuToHostTransition(t *testing.T) {+ for _, capacity := range []int{1, 2} {+ t.Run(fmt.Sprintf("C=%d", capacity), func(t *testing.T) {+ routes := newController(capacity, Options{SfuEnabled: true})+ addViewer(routes, A, 0, nil)+ if capacity == 2 {+ addViewer(routes, E, 0, nil)+ routes.hydrateEdge(E, peerEdge(HOST, "e_direct"))+ }+ routes.hydrateHostPublication("publication_1", res("publication_resource_1"), "")+ routes.hydrateEdge(A, sfuEdge("publication_1", "a_sfu", "a_subscription"))+ routes.InvalidateEdge(edgeGuard(A, "", 0, "a_sfu"), nil)+ operation := must(t, routes.Reconcile(0).Operation)+ eq(t, operation.Candidates[0].Tuple, peerTuple(HOST))+ expectTransition(t, operation.Candidates[0].EndpointTransition, TransitionOverlap, HOST)+ expectPanic(t, "endpoint overlap reservation", func() {+ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_host_direct", Reservation: direct()})+ })+ })+ }+}++// TS 4510: uses one bounded gap instead of a fourth Host copy at C=3+func TestUsesOneBoundedGapInsteadOfFourthHostCopyAtCapacityThree(t *testing.T) {+ routes := newController(3, Options{SfuEnabled: true})+ addViewer(routes, A, 0, nil)+ for _, peerID := range []string{E, F} {+ addViewer(routes, peerID, 0, nil)+ routes.hydrateEdge(peerID, peerEdge(HOST, peerID+"_direct"))+ }+ routes.hydrateHostPublication("publication_1", res("publication_resource_1"), "")+ routes.hydrateEdge(A, sfuEdge("publication_1", "a_sfu", "a_subscription"))+ routes.InvalidateEdge(edgeGuard(A, "", 0, "a_sfu"), nil)+ operation := must(t, routes.Reconcile(10).Operation)+ deadline := operation.DeadlineAtMs+ eq(t, operation.Candidates[0].Tuple, peerTuple(HOST))+ transition := operation.Candidates[0].EndpointTransition+ expectTransition(t, transition, TransitionBoundedGap, HOST)+ if transition.Retire == nil {+ t.Fatal("expected a retirement")+ }+ eq(t, transition.Retire.Kind, RetirePublication)+ eq(t, transition.Retire.Generation, "publication_1")+ gap := routes.RetireCurrentCandidateProducer(cursorGuard(operation), 11)+ eq(t, gap.Accepted, true)+ eqLabels(t, gap.Released, "a_subscription", "publication_resource_1")+ replanned := must(t, gap.Operation)+ eq(t, replanned.DeadlineAtMs, deadline)+ eq(t, len(replanned.Candidates), 1)+ expectTransition(t, replanned.Candidates[0].EndpointTransition, TransitionNone, HOST)+ prepared := beginOperation(t, routes, BeginInput{NowMs: 12, ConnectionID: "a_host_direct", Reservation: direct()})+ eq(t, routes.CandidateReady(guardFor(A, prepared.Current.Revision, "a_host_direct"), 13, nil, CandidateProof{}).Accepted, true)+ if routes.Snapshot().HostPublication != nil {+ t.Fatal("expected no host publication")+ }+}++// TS 4564: does not reopen consumed none transitions after capacity reduction+func TestDoesNotReopenConsumedNoneTransitionsAfterCapacityReduction(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ addViewer(routes, A, 0, nil)+ routes.hydrateHostPublication("publication", res("publication_resource"), "")+ routes.hydrateEdge(A, sfuEdge("publication", "a_from_sfu", "a_subscription"))+ eq(t, routes.InvalidateEdge(edgeGuard(A, "", 0, "a_from_sfu"), nil), true)+ operation := must(t, routes.Reconcile(0).Operation)+ eq(t, operation.Candidates[0].Tuple, peerTuple(HOST))+ expectTransition(t, operation.Candidates[0].EndpointTransition, TransitionNone, HOST)++ eq(t, routes.SetEffectiveCapacity(HOST, "host_session", 1, nil), true)+ eqSlice(t, routes.OperationExpired(operation.DeadlineAtMs).FailedPeerIDs, []string{A})+ noOperation(t, routes.Reconcile(operation.DeadlineAtMs+1).Operation)+}++// TS 4596: does not unblock an exhausted demand for an unrelated join+func TestDoesNotUnblockExhaustedDemandForUnrelatedJoin(t *testing.T) {+ routes := newController(1, Options{})+ addViewer(routes, B, 0, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"))+ addViewer(routes, A, 0, ms(0))+ eqSlice(t, routes.Reconcile(0).FailedPeerIDs, []string{A})++ eq(t, routes.SetEffectiveCapacity(A, sessionOf(A), 1, nil), true)+ noOperation(t, routes.Reconcile(1).Operation)++ addViewer(routes, C, 0, ms(2))+ eqSlice(t, routes.Reconcile(2).FailedPeerIDs, []string{C})+ noOperation(t, routes.Snapshot().Operation)++ eq(t, routes.SetEffectiveCapacity(B, sessionOf(B), 1, nil), true)+ operation := must(t, routes.Reconcile(3).Operation)+ eq(t, operation.ChildPeerID, A)+ eqSlice(t, tuples(operation), []CandidateTuple{peerTuple(B)})+}++// TS 4621: does not revive an exact failed Host tuple when a new parent joins+func TestDoesNotReviveExactFailedHostTupleWhenNewParentJoins(t *testing.T) {+ routes := newController(1, Options{})+ addViewer(routes, A, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "failed_direct"))+ eq(t, routes.InvalidateEdge(edgeGuard(A, "host_session", 0, "failed_direct"), nil), true)+ noOperation(t, routes.Reconcile(0).Operation)++ addViewer(routes, B, 1, ms(1))+ join := must(t, routes.Reconcile(2).Operation)+ eq(t, join.ChildPeerID, B)+ eq(t, join.Reason, DemandJoin)+ commitCurrent(t, routes, 2, "b_from_host")+ retry := must(t, routes.Reconcile(4).Operation)+ eq(t, retry.ChildPeerID, A)+ eqSlice(t, tuples(retry), []CandidateTuple{peerTuple(B)})+ eq(t, hasTuple(retry, func(tuple CandidateTuple) bool { return isPeer(tuple) && tuple.ParentPeerID == HOST }), false)+}++// TS 4660: does not unblock an exhausted Viewer when its candidate set shrinks+func TestDoesNotUnblockExhaustedViewerWhenCandidateSetShrinks(t *testing.T) {+ routes := newController(1, Options{})+ addViewer(routes, A, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "failed_host"))+ eq(t, routes.InvalidateEdge(edgeGuard(A, "host_session", 0, "failed_host"), nil), true)+ noOperation(t, routes.Reconcile(0).Operation)++ addViewer(routes, B, 1, ms(1))+ routes.Reconcile(1)+ commitCurrent(t, routes, 2, "b_from_host")+ candidate := must(t, routes.Reconcile(3).Operation)+ attempt := beginOperation(t, routes, BeginInput{NowMs: 4, ConnectionID: "a_from_b", Reservation: direct()})+ eqSlice(t, routes.CandidateFailed(guardFor(A, attempt.Current.Revision, "a_from_b"), 5).FailedPeerIDs, []string{A})+ eq(t, len(candidate.Candidates), 1)++ eq(t, routes.DisconnectSession(B, sessionOf(B)), true)+ noOperation(t, routes.Reconcile(6).Operation)+}++// TS 4694: treats a replacement child session as a new exact opportunity+func TestTreatsReplacementChildSessionAsNewExactOpportunity(t *testing.T) {+ routes := newController(1, Options{})+ addViewer(routes, A, 0, nil)+ routes.hydrateEdge(A, peerEdge(HOST, "failed_host"))+ eq(t, routes.InvalidateEdge(edgeGuard(A, "host_session", 0, "failed_host"), nil), true)+ noOperation(t, routes.Reconcile(0).Operation)++ routes.UpsertParticipant(viewerInput(A, "replacement_session", 0), nil)+ operation := must(t, routes.Reconcile(1).Operation)+ eq(t, operation.ChildPeerID, A)+ eq(t, operation.ChildSessionID, "replacement_session")+ eqSlice(t, tuples(operation), []CandidateTuple{peerTuple(HOST)})+}++// TS 4724: does not retry a failed bootstrap carrier when another carrier leaves+func TestDoesNotRetryFailedBootstrapCarrierWhenAnotherCarrierLeaves(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ for _, seed := range [][2]string{{B, "b_from_host"}, {C, "c_from_host"}} {+ addViewer(routes, seed[0], 1, nil)+ routes.hydrateEdge(seed[0], peerEdge(HOST, seed[1]))+ }+ addViewer(routes, A, 0, ms(0))+ acquisition := must(t, routes.Reconcile(0).Operation)+ beginCandidate(t, routes, BeginInput{NowMs: 1, ConnectionID: "a_head_start", Reservation: direct()})+ routes.OperationExpired(acquisition.WakeAtMs)++ bootstrap := must(t, routes.Reconcile(acquisition.WakeAtMs+1).Operation)+ eq(t, bootstrap.Reason, DemandSfuBootstrap)+ failedCarrier := bootstrap.ChildPeerID+ otherCarrier := B+ if failedCarrier == B {+ otherCarrier = C+ }+ attempt := beginOperation(t, routes, BeginInput{+ NowMs: acquisition.WakeAtMs + 2,+ ConnectionID: "failed_bootstrap",+ PublicationGeneration: "failed_publication",+ PublicationConnectionID: "failed_publication_connection",+ Reservation: sfuCreateOverlap("failed_subscription", "failed_publication_resource", "failed_overlap"),+ })+ eq(t, routes.CandidateFailed(guardFor(failedCarrier, attempt.Current.Revision, "failed_bootstrap"), acquisition.WakeAtMs+3).Accepted, true)++ eq(t, routes.DisconnectSession(otherCarrier, sessionOf(otherCarrier)), true)+ next := routes.Reconcile(acquisition.WakeAtMs + 4).Operation+ if next != nil && next.Reason == DemandSfuBootstrap && next.ChildPeerID == failedCarrier {+ t.Fatalf("retried the failed bootstrap carrier %q", failedCarrier)+ }+}++// TS 4775: does not bootstrap a new SFU generation after the last reuse opportunity expires+func TestDoesNotBootstrapNewSfuGenerationAfterLastReuseOpportunityExpires(t *testing.T) {+ routes, nowMs := retireLastSfuPublicationAfterReuseDeadline(t)++ reconciled := routes.Reconcile(nowMs)+ noOperation(t, reconciled.Operation)+ eqSlice(t, reconciled.FailedPeerIDs, []string{})+}++// TS 4783: reopens the exhausted SFU opportunity for a new %s authority+func TestReopensExhaustedSfuOpportunityForNewAuthority(t *testing.T) {+ for _, authority := range []string{"child-session", "host-session", "external-resource"} {+ t.Run(authority, func(t *testing.T) {+ routes, nowMs := retireLastSfuPublicationAfterReuseDeadline(t)+ switch authority {+ case "child-session":+ routes.UpsertParticipant(viewerInput(A, "replacement_child_session", 0), nil)+ case "host-session":+ routes.UpsertParticipant(hostInput("replacement_host_session", 2), nil)+ default:+ routes.TouchExternalFacts()+ }++ operation := must(t, routes.Reconcile(nowMs).Operation)+ eq(t, operation.DemandPeerID, A)+ eq(t, operation.Reason, DemandSfuBootstrap)+ eqSlice(t, tuples(operation), []CandidateTuple{sfuTuple(PublicationCreate)})+ })+ }+}++// TS 4817: consumes the canonical SFU opportunity when an active edge fails+func TestConsumesCanonicalSfuOpportunityWhenActiveEdgeFails(t *testing.T) {+ routes := invalidateActiveSfuEdge(t)++ // TS: `operation?.candidates.some(sfu)` toBe(false) needs an operation.+ operation := must(t, routes.Reconcile(0).Operation)+ eq(t, hasTuple(operation, isSfu), false)+}++// TS 4826: reopens an active-edge SFU opportunity for a new %s authority+func TestReopensActiveEdgeSfuOpportunityForNewAuthority(t *testing.T) {+ for _, authority := range []string{"child-session", "host-session", "external-resource"} {+ t.Run(authority, func(t *testing.T) {+ routes := invalidateActiveSfuEdge(t)+ switch authority {+ case "child-session":+ routes.UpsertParticipant(viewerInput(A, "active_edge_child_replacement", 0), nil)+ case "host-session":+ routes.UpsertParticipant(hostInput("active_edge_host_replacement", 1), nil)+ default:+ routes.TouchExternalFacts()+ }++ operation := must(t, routes.Reconcile(0).Operation)+ eq(t, hasTuple(operation, func(tuple CandidateTuple) bool {+ return isSfu(tuple) && tuple.Publication == PublicationReuse+ }), true)+ })+ }+}++// TS 4860: does not turn a failed same-rank SFU replace into a create retry+func TestDoesNotTurnFailedSameRankSfuReplaceIntoCreateRetry(t *testing.T) {+ routes := newController(2, Options{SfuEnabled: true})+ routes.hydrateHostPublication("failed_publication", res("failed_publication_resource"), "")+ eq(t, routes.InvalidateHostPublication(PublicationGuard{+ HostSessionID: "host_session",+ RouteRevision: routes.Snapshot().Revision,+ Generation: "failed_publication",+ ConnectionID: "publication:failed_publication",+ }, nil), true)+ addViewer(routes, A, 0, nil)+ operation := must(t, routes.Reconcile(0).Operation)+ eq(t, operation.Candidates[0].Tuple.Kind, UpstreamPeer)+ skipCandidate(t, routes, 1)+ replaceCandidate := must(t, routes.Snapshot().Operation).Candidates[1]+ eq(t, replaceCandidate.Tuple, sfuTuple(PublicationReplace))+ expectTransition(t, replaceCandidate.EndpointTransition, TransitionNone, HOST)+ replace := beginOperation(t, routes, BeginInput{+ NowMs: 2,+ ConnectionID: "failed_replace",+ PublicationGeneration: "replacement_publication",+ PublicationConnectionID: "replacement_ingress",+ Reservation: sfuCreate("replacement_subscription", "replacement_publication_resource"),+ })+ eqSlice(t, routes.CandidateFailed(guardFor(A, replace.Current.Revision, "failed_replace"), 3).FailedPeerIDs, []string{A})++ addViewer(routes, B, 0, nil)+ eq(t, routes.ConfirmDeparture(B, nil), true)+ reconciled := routes.Reconcile(4)+ if routes.Snapshot().HostPublication != nil {+ t.Fatal("expected no host publication")+ }+ noOperation(t, reconciled.Operation)+ eqSlice(t, reconciled.FailedPeerIDs, []string{})+}++// TS 4913: reopens only SFU opportunities for a new external fact+func TestReopensOnlySfuOpportunitiesForNewExternalFact(t *testing.T) {+ routes := newController(1, Options{SfuEnabled: true})+ addViewer(routes, A, 0, ms(0))+ routes.Reconcile(0)+ directAttempt := beginOperation(t, routes, BeginInput{NowMs: 1, ConnectionID: "failed_direct", Reservation: direct()})+ eq(t, routes.CandidateFailed(guardFor(A, directAttempt.Current.Revision, "failed_direct"), 2).Accepted, true)+ sfuAttempt := beginOperation(t, routes, BeginInput{+ NowMs: 3,+ ConnectionID: "failed_sfu",+ PublicationGeneration: "failed_publication",+ PublicationConnectionID: "failed_publication_connection",+ Reservation: sfuCreate("failed_subscription", "failed_publication_resource"),+ })+ eq(t, routes.CandidateFailed(guardFor(A, sfuAttempt.Current.Revision, "failed_sfu"), 4).Accepted, true)+ noOperation(t, routes.Snapshot().Operation)+ noOperation(t, routes.Reconcile(5).Operation)++ routes.TouchExternalFacts()+ retried := must(t, routes.Reconcile(6).Operation)+ eq(t, len(retried.Candidates), 1)+ eq(t, retried.Candidates[0].Tuple, sfuTuple(PublicationCreate))+ expectTransition(t, retried.Candidates[0].EndpointTransition, TransitionNone, HOST)+ eq(t, hasTuple(retried, isPeer), false)+}++// TS 4963: fails all waiting demands without cutting capacity-three Host children+func TestFailsAllWaitingDemandsWithoutCuttingCapacityThreeHostChildren(t *testing.T) {+ routes := newController(3, Options{SfuEnabled: true})+ seeds := [][2]string{{A, "a_direct"}, {B, "b_direct"}, {C, "c_direct"}}+ for _, seed := range seeds {+ addViewer(routes, seed[0], 0, nil)+ routes.hydrateEdge(seed[0], peerEdge(HOST, seed[1]))+ }+ addViewer(routes, D, 0, nil)+ addViewer(routes, E, 0, nil)+ reconciled := routes.Reconcile(0)+ noOperation(t, reconciled.Operation)+ eqSlice(t, reconciled.FailedPeerIDs, []string{D, E})+ for _, seed := range seeds {+ edge := edgeOf(t, routes, seed[0])+ eq(t, edge.ConnectionID, seed[1])+ eq(t, edge.Usable, true)+ eq(t, edge.PhysicalActive, true)+ }+}++// TS 4991: does not promote when synchronous admission commit fails+func TestDoesNotPromoteWhenSynchronousAdmissionCommitFails(t *testing.T) {+ routes := newController(1, Options{})+ addViewer(routes, A, 0, nil)+ operation := must(t, routes.Reconcile(0).Operation)+ prepared := beginOperation(t, routes, BeginInput{NowMs: 1, ConnectionID: "candidate_connection", Reservation: direct()})+ settled := routes.CandidateReady(CandidateGuard{+ ChildPeerID: operation.ChildPeerID,+ ChildSessionID: operation.ChildSessionID,+ Revision: prepared.Current.Revision,+ ConnectionID: "candidate_connection",+ }, 2, func(CandidateReservation) bool { return false }, CandidateProof{})+ eq(t, settled.Accepted, false)+ if settled.ActiveRevision <= prepared.Current.Revision {+ t.Fatalf("activeRevision %d did not advance past %d", settled.ActiveRevision, prepared.Current.Revision)+ }+ eq(t, hasEdge(routes, A), false)+}++// --- describe("bounded NAT candidate acquisition") -------------------------++// TS 5033: runs three real generations on %s, then exhausts until a new session+func TestRunsThreeRealGenerationsThenExhaustsUntilNewSession(t *testing.T) {+ for _, failure := range []string{"failed", "timeout"} {+ t.Run(failure, func(t *testing.T) {+ routes := newController(2, Options{NatPredictionEnabled: true, OperationTimeoutMs: 20_000})+ addViewer(routes, A, 0, nil)+ nowMs := int64(0)+ var previous *CandidateGuard+ for attempt := 1; attempt <= 3; attempt++ {+ operation, prepared, guard := preparePeer(t, routes, nowMs, fmt.Sprintf("nat_%d", attempt))+ eqDeep(t, prepared.Current.ConnectionAttempt, &ConnectionAttemptProgress{Current: attempt, Total: 3})+ eq(t, operation.DeadlineAtMs-nowMs, 20_000)+ eq(t, prepared.WakeAtMs, operation.DeadlineAtMs)+ if previous != nil {+ eq(t, routes.CandidateFailed(*previous, nowMs).Accepted, false)+ }+ eq(t, must(t, routes.Snapshot().Operation).Current.ConnectionID, fmt.Sprintf("nat_%d", attempt))+ var result SettleResult+ if failure == "timeout" {+ nowMs = operation.DeadlineAtMs+ result = routes.OperationExpired(nowMs)+ } else {+ nowMs+++ result = routes.CandidateFailed(guard, nowMs)+ }+ if attempt == 3 {+ eqSlice(t, result.FailedPeerIDs, []string{A})+ } else {+ eqSlice(t, result.FailedPeerIDs, []string{})+ }+ eq(t, routes.CandidateFailed(guard, nowMs).Accepted, false)+ previous = &guard+ nowMs+++ }+ noOperation(t, routes.Reconcile(nowMs).Operation)+ routes.UpsertParticipant(viewerInput(A, "replacement_session", 0), ms(nowMs))+ _, prepared, guard := preparePeer(t, routes, nowMs+1, "new_session")+ eq(t, attemptCurrent(t, prepared), 1)+ eq(t, routes.CandidateReady(guard, nowMs+2, nil, CandidateProof{}).Committed, true)+ })+ }+}++// TS 5067: gives waiting viewers their first opportunity before another viewer retries+func TestGivesWaitingViewersFirstOpportunityBeforeAnotherViewerRetries(t *testing.T) {+ routes := newController(2, Options{NatPredictionEnabled: true})+ addViewer(routes, A, 0, nil)+ addViewer(routes, B, 0, nil)+ for index, childPeerID := range []string{A, B, A, B, A, B} {+ _, prepared, guard := preparePeer(t, routes, int64(index*2), fmt.Sprintf("fair_%d", index))+ eq(t, prepared.ChildPeerID, childPeerID)+ eq(t, attemptCurrent(t, prepared), index/2+1)+ routes.CandidateFailed(guard, int64(index*2+1))+ }+ noOperation(t, routes.Reconcile(20).Operation)+}++// TS 5080: tries a newly usable parent before spending another attempt on an old parent+func TestTriesNewlyUsableParentBeforeSpendingAnotherAttemptOnOldParent(t *testing.T) {+ routes := newController(2, Options{NatPredictionEnabled: true})+ addViewer(routes, B, 2, nil)+ routes.hydrateEdge(B, peerEdge(HOST, "existing_b"))+ addViewer(routes, A, 0, nil)+ _, firstPrepared, firstGuard := preparePeer(t, routes, 0, "first_host")+ eq(t, firstPrepared.Current.Tuple.ParentPeerID, HOST)+ routes.CandidateFailed(firstGuard, 1)+ _, secondPrepared, secondGuard := preparePeer(t, routes, 2, "first_b")+ eq(t, secondPrepared.Current.Tuple.ParentPeerID, B)+ routes.CandidateFailed(secondGuard, 3)+ addViewer(routes, C, 2, ms(4))+ routes.hydrateEdge(C, peerEdge(HOST, "existing_c"))+ _, thirdPrepared, _ := preparePeer(t, routes, 5, "first_c")+ eq(t, thirdPrepared.Current.Tuple.ParentPeerID, C)+ eq(t, attemptCurrent(t, thirdPrepared), 1)+}++// TS 5098: keeps SFU's foreground timing and shares the attempt budget with round-robin direct continuations+func TestKeepsSfuForegroundTimingAndSharesAttemptBudgetWithDirectContinuations(t *testing.T) {+ routes := newController(2, Options{NatPredictionEnabled: true, SfuEnabled: true, OperationTimeoutMs: 20_000})+ nowMs := int64(0)+ for _, childPeerID := range []string{A, B} {+ addViewer(routes, childPeerID, 0, ms(nowMs))+ _, directPrepared, _ := preparePeer(t, routes, nowMs, childPeerID+"_first")+ eq(t, directPrepared.WakeAtMs, nowMs+5_000)+ nowMs += 5_000+ eqSlice(t, routes.OperationExpired(nowMs).FailedPeerIDs, []string{})+ reservation := sfuReuse("subscription_b")+ if childPeerID == A {+ reservation = sfuCreate("subscription_a", "publication")+ }+ sfu := beginOperation(t, routes, BeginInput{+ NowMs: nowMs,+ ConnectionID: childPeerID + "_sfu",+ PublicationGeneration: "sfu_generation",+ PublicationConnectionID: "sfu_publisher",+ Reservation: reservation,+ })+ if sfu.Current.ConnectionAttempt != nil {+ t.Fatal("SFU attempts carry no NAT connection attempt")+ }+ nowMs+++ routes.CandidateReady(CandidateGuard{+ ChildPeerID: childPeerID,+ ChildSessionID: sfu.ChildSessionID,+ Revision: sfu.Current.Revision,+ ConnectionID: childPeerID + "_sfu",+ }, nowMs, nil, CandidateProof{})+ nowMs+++ }+ for index, childPeerID := range []string{A, B, A, B} {+ _, retry, guard := preparePeer(t, routes, nowMs, fmt.Sprintf("background_%d", index))+ eq(t, retry.ChildPeerID, childPeerID)+ eq(t, retry.Reason, DemandDirectConvergence)+ eqDeep(t, retry.Current.ConnectionAttempt, &ConnectionAttemptProgress{Current: index/2 + 2, Total: 3})+ eq(t, retry.WakeAtMs-nowMs, 20_000)+ nowMs+++ eqSlice(t, routes.CandidateFailed(guard, nowMs).FailedPeerIDs, []string{})+ edge := edgeOf(t, routes, childPeerID)+ eq(t, edge.Kind, UpstreamSfu)+ eq(t, edge.Usable, true)+ nowMs+++ }+ noOperation(t, routes.Reconcile(nowMs).Operation)+}++// TS 5139: does not retry without NAT policy or when no candidate was created+func TestDoesNotRetryWithoutNatPolicyOrWhenNoCandidateWasCreated(t *testing.T) {+ ordinary := newController(2, Options{})+ addViewer(ordinary, A, 0, nil)+ _, firstPrepared, firstGuard := preparePeer(t, ordinary, 0, "ordinary")+ if firstPrepared.Current.ConnectionAttempt != nil {+ t.Fatal("expected no connection attempt without NAT prediction")+ }+ eqSlice(t, ordinary.CandidateFailed(firstGuard, 1).FailedPeerIDs, []string{A})+ noOperation(t, ordinary.Reconcile(2).Operation)++ routes := newController(2, Options{NatPredictionEnabled: true})+ addViewer(routes, A, 0, nil)+ operation := must(t, routes.Reconcile(0).Operation)+ routes.SkipCurrentCandidate(cursorGuard(operation), 1, RejectionCandidateFailed)+ noOperation(t, routes.Reconcile(2).Operation)+}diff --git a/internal/server/route/debug.go b/internal/server/route/debug.gonew file mode 100644index 00000000..2d74eee6--- /dev/null+++ b/internal/server/route/debug.go@@ -0,0 +1,72 @@+package route++import (+ "log/slog"+ "os"+ "strconv"+ "strings"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// debugEnabled is the port of `debuglog("screener-route")`: read once,+// enabled by SCREENER_DEBUG=route (comma-separated like NODE_DEBUG).+var debugEnabled = routeDebugEnabled(os.Getenv("SCREENER_DEBUG"))++func routeDebugEnabled(value string) bool {+ for _, section := range strings.Split(value, ",") {+ if strings.TrimSpace(section) == "route" {+ return true+ }+ }+ return false+}++// debugCandidate is the `{route, transition}` item of "operation-started".+type debugCandidate struct {+ Route string+ Transition TransitionKind+}++// debug ports 4911: one sanitised event with the room's debug ID, the+// current revision and fact version, then the caller's key/value details.+// Never pass raw peer IDs, session IDs or connection IDs; use debugPeer and+// debugTuple. It is a no-op without the env flag or a DebugRoomID; the+// level is Info because the env flag is the gate, as NODE_DEBUG was.+func (c *Controller) debug(event string, details ...any) {+ if !debugEnabled || c.debugRoomID == "" {+ return+ }+ args := make([]any, 0, 8+len(details))+ args = append(args,+ "event", event,+ "roomId", c.debugRoomID,+ "revision", c.revision,+ "factVersion", c.factVersion)+ args = append(args, details...)+ slog.Info("screener-route", args...)+}++// debugPeer ports 4895: "host", "viewer-<joinOrder>" or "viewer-unknown".+func (c *Controller) debugPeer(peerID string) string {+ current, _ := c.participants.Get(peerID)+ if peerID == c.hostPeerID || (current != nil && current.role == protocol.RoleHost) {+ return "host"+ }+ if current == nil {+ return "viewer-unknown"+ }+ return "viewer-" + strconv.FormatInt(current.joinOrder, 10)+}++// debugTuple ports 4903: "p2p:<label>[:regenerate]" or "sfu:<publication>".+func (c *Controller) debugTuple(tuple CandidateTuple) string {+ if tuple.Kind == UpstreamPeer {+ label := "p2p:" + c.debugPeer(tuple.ParentPeerID)+ if tuple.Regenerate {+ label += ":regenerate"+ }+ return label+ }+ return "sfu:" + string(tuple.Publication)+}diff --git a/internal/server/route/doc.go b/internal/server/route/doc.gonew file mode 100644index 00000000..2b450e93--- /dev/null+++ b/internal/server/route/doc.go@@ -0,0 +1,15 @@+// Package route ports src/server/room-route-controller.ts: the pure,+// synchronous decision logic that owns one room's media route graph, its+// single in-flight route operation, the quality/opportunity ledgers and the+// privacy-safe diagnostic snapshot.+//+// The controller performs no I/O, starts no timers and never locks. Every+// method is a state transition over the nowMs the caller passes in; the+// caller (signal.Server) holds the global mutex around every call and+// releases exactly the *Resource values a method returns, in order.+//+// Resources are compared by pointer identity, mirroring the JS Set semantics+// of the TypeScript source. Programming-error throws in the source+// (assertGraph, bad reservations, bad options) become panics with the same+// messages.+package routediff --git a/internal/server/route/graph.go b/internal/server/route/graph.gonew file mode 100644index 00000000..01fcaae6--- /dev/null+++ b/internal/server/route/graph.go@@ -0,0 +1,287 @@+package route++import (+ "errors"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// pruneDepartedLeaves ports 4015: removes departed viewers without+// children to a fixpoint, in participants order (§4.1 #4), and drops an+// orphaned publication.+func (c *Controller) pruneDepartedLeaves(released *[]*Resource) []string {+ removed := []string{}+ changed := true+ for changed {+ changed = false+ // Live iteration: deleting the visited entry is JS-safe (ordered.Map.All).+ for _, current := range c.participants.All() {+ if current.role != protocol.RoleViewer || !current.departureConfirmed || len(c.childrenOf(current.peerID)) > 0 {+ continue+ }+ edge, _ := c.upstreamByViewer.Get(current.peerID)+ if edge != nil && edge.Kind == UpstreamSfu {+ c.retireSfuEdge(current.peerID, edge, released, false)+ } else {+ c.upstreamByViewer.Delete(current.peerID)+ }+ c.clearQualityForParticipant(current.peerID)+ c.participants.Delete(current.peerID)+ delete(c.routeTimings, current.peerID)+ c.directContinuations.Delete(current.peerID)+ c.clearSfuBootstrapForDemand(current.peerID)+ removed = append(removed, current.peerID)+ changed = true+ }+ }+ if len(removed) > 0 {+ if !c.hasSfuSubscribers() && c.hostPublication != nil {+ c.clearSfuQuality()+ if c.hostPublication.PhysicalActive {+ *released = append(*released, c.hostPublication.Resource)+ }+ c.hostPublication = nil+ }+ c.revision = c.allocateRevision()+ c.touchFacts()+ c.pruneRetiringSfuAnchors()+ }+ return removed+}++// retireInvalidOperationEdge ports 4133.+func (c *Controller) retireInvalidOperationEdge(childPeerID string, released *[]*Resource) bool {+ edge, _ := c.upstreamByViewer.Get(childPeerID)+ if edge == nil || !c.edgeRequiresMove(childPeerID, edge) {+ return false+ }+ if edge.Kind == UpstreamSfu {+ c.retireSfuEdge(childPeerID, edge, released, c.retainsAnchor(childPeerID))+ c.pruneRetiringSfuAnchors()+ } else {+ edge.PhysicalActive = false+ edge.Usable = false+ }+ if edge.Kind == UpstreamSfu && !c.hasSfuSubscribers() && c.hostPublication != nil {+ publication := c.hostPublication+ if publication.PhysicalActive {+ *released = append(*released, publication.Resource)+ }+ publication.PhysicalActive = false+ publication.Usable = false+ c.hostPublication = nil+ }+ return true+}++// edgeRequiresMove ports 4153.+func (c *Controller) edgeRequiresMove(childPeerID string, edge *CommittedEdge) bool {+ if !edge.Usable || !edge.PhysicalActive {+ return true+ }+ if edge.Kind == UpstreamSfu {+ return c.hostPublication == nil || !c.hostPublication.Usable ||+ !c.hostPublication.PhysicalActive ||+ c.hostPublication.Generation != edge.PublicationGeneration+ }+ if parent, ok := c.participants.Get(edge.ParentPeerID); ok && parent.departureConfirmed {+ return true+ }+ for _, overflowing := range c.overflowPeerChildren(edge.ParentPeerID) {+ if overflowing == childPeerID {+ return true+ }+ }+ return false+}++// rebindCommittedSession ports 4747: the reconnecting peer keeps its edges+// and publication, which take its new session id. The TS `{released,+// retired}` result is dropped because it was dead: nothing ever joined the+// released set and retired was the constant false, so the caller's+// `rebound.retired &&` branch was unreachable (map R12).+func (c *Controller) rebindCommittedSession(peerID, sessionID string) {+ if ownEdge, ok := c.upstreamByViewer.Get(peerID); ok {+ ownEdge.ChildSessionID = sessionID+ }+ for _, edge := range c.upstreamByViewer.Values() {+ if edge.Kind != UpstreamPeer || edge.ParentPeerID != peerID {+ continue+ }+ edge.ParentSessionID = sessionID+ }+ if peerID == c.hostPeerID && c.hostPublication != nil {+ c.hostPublication.HostSessionID = sessionID+ }+}++// removePublicationGeneration ports 4766 (§4.2 #12).+func (c *Controller) removePublicationGeneration(generation string) []*Resource {+ released := []*Resource{}+ for viewerPeerID, edge := range c.upstreamByViewer.All() {+ if edge.Kind != UpstreamSfu || edge.PublicationGeneration != generation {+ continue+ }+ c.retireSfuEdge(viewerPeerID, edge, &released, c.retainsAnchor(viewerPeerID))+ }+ if c.hostPublication != nil && c.hostPublication.Generation == generation {+ if c.hostPublication.PhysicalActive {+ released = append(released, c.hostPublication.Resource)+ }+ c.hostPublication = nil+ }+ c.pruneRetiringSfuAnchors()+ return released+}++// retainsAnchor is the TS default argument of retireSfuEdge+// (`this.childrenOf(viewerPeerId).length > 0`), evaluated at call time.+func (c *Controller) retainsAnchor(viewerPeerID string) bool {+ return len(c.childrenOf(viewerPeerID)) > 0+}++// retireSfuEdge ports 4780: releases the subscription only while it is+// still physically active, then keeps the edge as an anchor for attached+// peer descendants or deletes it.+func (c *Controller) retireSfuEdge(viewerPeerID string, edge *CommittedEdge, released *[]*Resource, retainAnchor bool) {+ if edge.PhysicalActive {+ *released = append(*released, edge.Resource)+ }+ c.clearQualityForParticipant(viewerPeerID)+ if retainAnchor {+ edge.Usable = false+ edge.PhysicalActive = false+ c.retiringPublicationGenerations.Set(edge.PublicationGeneration, struct{}{})+ } else {+ c.upstreamByViewer.Delete(viewerPeerID)+ }+}++// hasRetiringAnchor reports whether an inactive SFU edge still references+// the generation (the `some` at 4816 and 4880).+func (c *Controller) hasRetiringAnchor(generation string) bool {+ for _, edge := range c.upstreamByViewer.Values() {+ if edge.Kind == UpstreamSfu && !edge.PhysicalActive && edge.PublicationGeneration == generation {+ return true+ }+ }+ return false+}++// pruneRetiringSfuAnchors ports 4797 (§4.2 #18, §4.5 #46).+func (c *Controller) pruneRetiringSfuAnchors() {+ removed := true+ for removed {+ removed = false+ for viewerPeerID, edge := range c.upstreamByViewer.All() {+ if edge.Kind == UpstreamSfu &&+ !edge.PhysicalActive &&+ c.retiringPublicationGenerations.Has(edge.PublicationGeneration) &&+ len(c.childrenOf(viewerPeerID)) == 0 {+ c.upstreamByViewer.Delete(viewerPeerID)+ removed = true+ }+ }+ }+ for generation := range c.retiringPublicationGenerations.All() {+ if !c.hasRetiringAnchor(generation) {+ c.retiringPublicationGenerations.Delete(generation)+ }+ }+}++// assertGraph ports 4827: programming-error panics with the TS messages+// (§4.2 #20, §4.1 #6 decide which violation is reported first).+func (c *Controller) assertGraph() {+ host, _ := c.participants.Get(c.hostPeerID)+ if host == nil || host.role != protocol.RoleHost {+ panic(errors.New("Route Host is missing"))+ }+ for child, edge := range c.upstreamByViewer.All() {+ c.assertViewer(child)+ if edge.Kind == UpstreamPeer && !c.participants.Has(edge.ParentPeerID) {+ panic(errors.New("Route parent is missing"))+ }+ if edge.Kind == UpstreamSfu && edge.PhysicalActive &&+ (c.hostPublication == nil || c.hostPublication.Generation != edge.PublicationGeneration) {+ panic(errors.New("SFU publication is stale"))+ }+ if edge.Kind == UpstreamSfu && !edge.PhysicalActive &&+ !c.retiringPublicationGenerations.Has(edge.PublicationGeneration) {+ panic(errors.New("Retiring SFU publication is unknown"))+ }+ seen := make(map[string]struct{})+ current := child+ for current != c.hostPeerID {+ if _, visited := seen[current]; visited {+ panic(errors.New("Peer route contains a cycle"))+ }+ seen[current] = struct{}{}+ currentEdge, ok := c.upstreamByViewer.Get(current)+ if !ok {+ panic(errors.New("Route is not source-reachable"))+ }+ if currentEdge.Kind == UpstreamSfu {+ var unknown bool+ if currentEdge.PhysicalActive {+ unknown = c.hostPublication == nil || c.hostPublication.Generation != currentEdge.PublicationGeneration+ } else {+ unknown = !c.retiringPublicationGenerations.Has(currentEdge.PublicationGeneration)+ }+ if unknown {+ panic(errors.New("Route terminates at an unknown SFU publication"))+ }+ break+ }+ current = currentEdge.ParentPeerID+ }+ }+ for _, current := range c.participants.Values() {+ if !protocol.EndpointMediaCopyCountFits(c.usedSlots(current.peerID), c.endpointMediaCopyCapacity, protocol.EndpointMediaCopySteady) {+ panic(errors.New("Committed route exceeds endpoint capacity"))+ }+ }+ for generation := range c.retiringPublicationGenerations.All() {+ if !c.hasRetiringAnchor(generation) {+ panic(errors.New("Retiring SFU publication has no anchor"))+ }+ }+}++// assertViewer ports 4891.+func (c *Controller) assertViewer(peerID string) {+ if current, ok := c.participants.Get(peerID); !ok || current.role != protocol.RoleViewer {+ panic(errors.New("Route child must be a Viewer"))+ }+}++// hasSfuSubscribers ports 4431.+func (c *Controller) hasSfuSubscribers() bool {+ return c.sfuSubscriberCount() > 0+}++// sfuSubscriberCount ports 4435.+func (c *Controller) sfuSubscriberCount() int {+ count := 0+ for _, edge := range c.upstreamByViewer.Values() {+ if edge.Kind == UpstreamSfu && edge.PhysicalActive {+ count+++ }+ }+ return count+}++// committedResources ports 4439: SFU subscriptions in map order, then the+// publication (§4.2 #13).+func (c *Controller) committedResources() []*Resource {+ resources := []*Resource{}+ for _, edge := range c.upstreamByViewer.Values() {+ if edge.Kind == UpstreamSfu && edge.PhysicalActive {+ resources = append(resources, edge.Resource)+ }+ }+ if c.hostPublication != nil && c.hostPublication.PhysicalActive {+ resources = append(resources, c.hostPublication.Resource)+ }+ return resources+}diff --git a/internal/server/route/harness_test.go b/internal/server/route/harness_test.gonew file mode 100644index 00000000..a6caac59--- /dev/null+++ b/internal/server/route/harness_test.go@@ -0,0 +1,570 @@+package route++// Test harness ported one-to-one from tests/room-route-controller.test.ts+// (lines 14-356 and preparePeer at 5017). TS resources were plain strings;+// here every resource is a distinct *Resource carrying the TS string as+// Label, and released slices are compared by label in order.++import (+ "fmt"+ "reflect"+ "slices"+ "strings"+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++const (+ HOST = "host_12345678"+ A = "viewer_a_12345678"+ B = "viewer_b_12345678"+ C = "viewer_c_12345678"+ D = "viewer_d_12345678"+ E = "viewer_e_12345678"+ F = "viewer_f_12345678"+)++// ms is the optional nowMs argument (TS: an omitted parameter is nil here).+func ms(v int64) *int64 { return &v }++func optInt(v int64) *protocol.Int {+ value := protocol.Int(v)+ return &value+}++func optNum(v float64) *protocol.Num {+ value := protocol.Num(v)+ return &value+}++// resourceLabels names the resources these tests create. The label lives here,+// not on Resource, because the controller compares resources by pointer+// identity only (TS: the tests instantiated the type parameter with a string).+// No test in this package calls t.Parallel(), so the map needs no lock.+var resourceLabels = map[*Resource]string{}++// res makes a fresh labelled resource (TS: a plain string).+func res(label string) *Resource {+ resource := &Resource{}+ resourceLabels[resource] = label+ return resource+}++func labels(resources []*Resource) []string {+ out := make([]string, 0, len(resources))+ for _, resource := range resources {+ out = append(out, resourceLabels[resource])+ }+ return out+}++func sessionOf(peerID string) string { return peerID + "_session" }++func parentSession(parentPeerID string) string {+ if parentPeerID == HOST {+ return "host_session"+ }+ return sessionOf(parentPeerID)+}++// newController ports controller(capacity, options): OperationTimeoutMs+// defaults to 10_000 and the Host is upserted at the same capacity.+func newController(capacity int, options Options) *Controller {+ options.HostPeerID = HOST+ options.EndpointMediaCopyCapacity = capacity+ if options.OperationTimeoutMs == 0 {+ options.OperationTimeoutMs = 10_000+ }+ routes := New(options)+ routes.UpsertParticipant(ParticipantInput{+ PeerID: HOST,+ Role: protocol.RoleHost,+ SessionID: "host_session",+ EffectiveDownstreamCapacity: capacity,+ }, nil)+ return routes+}++func addViewer(routes *Controller, peerID string, capacity int, nowMs *int64) {+ routes.UpsertParticipant(ParticipantInput{+ PeerID: peerID,+ Role: protocol.RoleViewer,+ SessionID: sessionOf(peerID),+ EffectiveDownstreamCapacity: capacity,+ }, nowMs)+}++func viewerInput(peerID, sessionID string, capacity int) ParticipantInput {+ return ParticipantInput{+ PeerID: peerID,+ Role: protocol.RoleViewer,+ SessionID: sessionID,+ EffectiveDownstreamCapacity: capacity,+ }+}++func hostInput(sessionID string, capacity int) ParticipantInput {+ return ParticipantInput{+ PeerID: HOST,+ Role: protocol.RoleHost,+ SessionID: sessionID,+ EffectiveDownstreamCapacity: capacity,+ }+}++func cursorGuard(operation *OperationSnapshot) CandidateCursorGuard {+ return CandidateCursorGuard{+ ChildPeerID: operation.ChildPeerID,+ ChildSessionID: operation.ChildSessionID,+ BaseRevision: operation.BaseRevision,+ FactVersion: operation.FactVersion,+ Cursor: operation.Cursor,+ Plan: operation.Candidates[operation.Cursor],+ }+}++// must ports the TS non-null assertion `operation!`.+func must(t *testing.T, operation *OperationSnapshot) *OperationSnapshot {+ t.Helper()+ if operation == nil {+ t.Fatal("expected an operation")+ }+ return operation+}++// noOperation ports `expect(operation).toBeUndefined()`.+func noOperation(t *testing.T, operation *OperationSnapshot) {+ t.Helper()+ if operation != nil {+ t.Fatalf("expected no operation, got child %q reason %q", operation.ChildPeerID, operation.Reason)+ }+}++// beginCandidate ports beginCandidate(routes, input): the guard is derived+// from the current operation and non-direct reservations default the Host+// session to "host_session".+func beginCandidate(t *testing.T, routes *Controller, input BeginInput) BeginResult {+ t.Helper()+ input.Guard = cursorGuard(must(t, routes.Snapshot().Operation))+ if input.Reservation.Kind != ReservationDirect && input.HostSessionID == "" {+ input.HostSessionID = "host_session"+ }+ return routes.BeginCurrentCandidate(input)+}++// beginOperation ports `beginCandidate(...).operation!`.+func beginOperation(t *testing.T, routes *Controller, input BeginInput) *OperationSnapshot {+ t.Helper()+ return must(t, beginCandidate(t, routes, input).Operation)+}++func skipCandidate(t *testing.T, routes *Controller, nowMs int64) BeginResult {+ t.Helper()+ return routes.SkipCurrentCandidate(cursorGuard(must(t, routes.Snapshot().Operation)), nowMs, RejectionStale)+}++func commitCurrent(t *testing.T, routes *Controller, nowMs int64, connectionID string) CandidateGuard {+ t.Helper()+ prepared := beginOperation(t, routes, BeginInput{NowMs: nowMs, ConnectionID: connectionID, Reservation: direct()})+ guard := CandidateGuard{+ ChildPeerID: prepared.ChildPeerID,+ ChildSessionID: prepared.ChildSessionID,+ Revision: prepared.Current.Revision,+ ConnectionID: connectionID,+ }+ eq(t, routes.CandidateReady(guard, nowMs+1, nil, CandidateProof{}).Accepted, true)+ return guard+}++// guardFor is the literal `{childPeerId, childSessionId: `${id}_session`, revision, connectionId}` the tests build.+func guardFor(peerID string, revision int64, connectionID string) CandidateGuard {+ return CandidateGuard{ChildPeerID: peerID, ChildSessionID: sessionOf(peerID), Revision: revision, ConnectionID: connectionID}+}++func edgeGuard(childPeerID, parentSessionID string, revision int64, connectionID string) EdgeGuard {+ return EdgeGuard{+ ChildPeerID: childPeerID,+ ChildSessionID: sessionOf(childPeerID),+ ParentSessionID: parentSessionID,+ RouteRevision: revision,+ ConnectionID: connectionID,+ }+}++func direct() CandidateReservation { return CandidateReservation{Kind: ReservationDirect} }++func directOverlap(overlap string) CandidateReservation {+ return CandidateReservation{Kind: ReservationDirect, Overlap: res(overlap)}+}++func sfuReuse(edge string) CandidateReservation {+ return CandidateReservation{Kind: ReservationSfuReuse, Edge: res(edge)}+}++func sfuCreate(edge, publication string) CandidateReservation {+ return CandidateReservation{Kind: ReservationSfuCreate, Edge: res(edge), Publication: res(publication)}+}++func sfuCreateOverlap(edge, publication, overlap string) CandidateReservation {+ reservation := sfuCreate(edge, publication)+ reservation.Overlap = res(overlap)+ return reservation+}++func peerEdge(parentPeerID, connectionID string) committedEdgeSeed {+ return committedEdgeSeed{+ Kind: UpstreamPeer,+ ParentPeerID: parentPeerID,+ Transport: TransportDirect,+ ConnectionID: connectionID,+ Usable: true,+ PhysicalActive: true,+ }+}++func sfuEdge(generation, connectionID, resource string) committedEdgeSeed {+ return committedEdgeSeed{+ Kind: UpstreamSfu,+ PublicationGeneration: generation,+ Transport: TransportSfu,+ ConnectionID: connectionID,+ Usable: true,+ PhysicalActive: true,+ Resource: res(resource),+ }+}++func peerTuple(parentPeerID string) CandidateTuple {+ return CandidateTuple{Kind: UpstreamPeer, ParentPeerID: parentPeerID, Transport: TransportDirect}+}++func regenerateTuple(parentPeerID string) CandidateTuple {+ tuple := peerTuple(parentPeerID)+ tuple.Regenerate = true+ return tuple+}++func sfuTuple(publication PublicationPlan) CandidateTuple {+ return CandidateTuple{Kind: UpstreamSfu, Publication: publication}+}++func tuples(operation *OperationSnapshot) []CandidateTuple {+ return tuplesFrom(operation, 0)+}++func tuplesFrom(operation *OperationSnapshot, from int) []CandidateTuple {+ out := make([]CandidateTuple, 0, len(operation.Candidates))+ for _, candidate := range operation.Candidates[from:] {+ out = append(out, candidate.Tuple)+ }+ return out+}++// tupleKinds ports `operation.candidates.map((candidate) => candidate.tuple.kind)`.+func tupleKinds(operation *OperationSnapshot) []UpstreamKind {+ out := make([]UpstreamKind, 0, len(operation.Candidates))+ for _, candidate := range operation.Candidates {+ out = append(out, candidate.Tuple.Kind)+ }+ return out+}++func hasTuple(operation *OperationSnapshot, match func(CandidateTuple) bool) bool {+ return slices.ContainsFunc(tuples(operation), match)+}++func isSfu(tuple CandidateTuple) bool { return tuple.Kind == UpstreamSfu }+func isPeer(tuple CandidateTuple) bool { return tuple.Kind == UpstreamPeer }++// edgeOf ports `routes.snapshot().upstreamByViewer.get(peerId)` where the+// test dereferences the edge.+func edgeOf(t *testing.T, routes *Controller, peerID string) CommittedEdge {+ t.Helper()+ edge, ok := routes.Snapshot().UpstreamByViewer.Get(peerID)+ if !ok {+ t.Fatalf("expected an upstream edge for %q", peerID)+ }+ return edge+}++func hasEdge(routes *Controller, peerID string) bool {+ return routes.Snapshot().UpstreamByViewer.Has(peerID)+}++func retireLastSfuPublicationAfterReuseDeadline(t *testing.T) (*Controller, int64) {+ t.Helper()+ routes := newController(2, Options{SfuEnabled: true})+ for _, seed := range [][2]string{{B, "b_from_host"}, {C, "c_from_host"}} {+ addViewer(routes, seed[0], 0, nil)+ routes.hydrateEdge(seed[0], peerEdge(HOST, seed[1]))+ }+ addViewer(routes, A, 0, ms(0))++ bootstrap := must(t, routes.Reconcile(0).Operation)+ eq(t, bootstrap.DemandPeerID, A)+ eq(t, bootstrap.Reason, DemandSfuBootstrap)+ eqSlice(t, tuples(bootstrap), []CandidateTuple{sfuTuple(PublicationCreate)})+ carrierPeerID := bootstrap.ChildPeerID+ carrier := beginOperation(t, routes, BeginInput{+ NowMs: 1,+ ConnectionID: "carrier_sfu",+ PublicationGeneration: "publication_generation",+ PublicationConnectionID: "publication_connection",+ Reservation: sfuCreateOverlap("carrier_subscription", "publication_resource", "publication_overlap"),+ })+ eq(t, routes.CandidateReady(CandidateGuard{+ ChildPeerID: carrier.ChildPeerID,+ ChildSessionID: carrier.ChildSessionID,+ Revision: carrier.Current.Revision,+ ConnectionID: "carrier_sfu",+ }, 2, nil, CandidateProof{}).Accepted, true)++ demand := must(t, routes.Reconcile(3).Operation)+ eq(t, demand.ChildPeerID, A)+ eq(t, demand.DemandPeerID, A)+ eqSlice(t, tuples(demand), []CandidateTuple{sfuTuple(PublicationReuse)})+ beginCandidate(t, routes, BeginInput{NowMs: 4, ConnectionID: "demand_sfu_reuse", Reservation: sfuReuse("demand_subscription")})+ eqSlice(t, routes.OperationExpired(demand.DeadlineAtMs).FailedPeerIDs, []string{A})++ convergence := must(t, routes.Reconcile(demand.DeadlineAtMs+1).Operation)+ eq(t, convergence.ChildPeerID, carrierPeerID)+ eq(t, convergence.Reason, DemandDirectConvergence)+ eqSlice(t, tuples(convergence), []CandidateTuple{peerTuple(HOST)})+ directOp := beginOperation(t, routes, BeginInput{+ NowMs: demand.DeadlineAtMs + 2,+ ConnectionID: "carrier_direct",+ Reservation: directOverlap("carrier_direct_overlap"),+ })+ committed := routes.CandidateReady(CandidateGuard{+ ChildPeerID: directOp.ChildPeerID,+ ChildSessionID: directOp.ChildSessionID,+ Revision: directOp.Current.Revision,+ ConnectionID: "carrier_direct",+ }, demand.DeadlineAtMs+3, nil, CandidateProof{})+ eq(t, committed.Accepted, true)+ containsLabels(t, committed.Released, "carrier_subscription", "publication_resource")+ if routes.Snapshot().HostPublication != nil {+ t.Fatal("expected no host publication")+ }+ return routes, demand.DeadlineAtMs + 4+}++func invalidateActiveSfuEdge(t *testing.T) *Controller {+ t.Helper()+ routes := newController(1, Options{SfuEnabled: true})+ addViewer(routes, A, 0, nil)+ routes.hydrateHostPublication("active_publication", res("publication_resource"), "")+ routes.hydrateEdge(A, sfuEdge("active_publication", "active_sfu_edge", "active_subscription"))+ eq(t, routes.InvalidateEdge(edgeGuard(A, "", routes.Snapshot().Revision, "active_sfu_edge"), nil), true)+ return routes+}++type senderState struct {+ childPeerID string+ connectionID string+ state SenderQualityState+ acceptedAtMs int64+ parentPeerID string // default HOST+ senderIdentity string // default "<connectionId>-rtp\x00track"+}++func observeSenderState(routes *Controller, input senderState) SenderQualityEvidenceResult {+ parentPeerID := input.parentPeerID+ if parentPeerID == "" {+ parentPeerID = HOST+ }+ identity := input.senderIdentity+ if identity == "" {+ identity = input.connectionID + "-rtp\x00track"+ }+ return routes.ObserveSenderQualityEvidence(senderSample(+ parentPeerID, input.childPeerID, routes.Snapshot().Revision,+ input.connectionID, identity, input.state, input.acceptedAtMs), nil)+}++// senderSample is the explicit observeSenderQualityEvidence literal the tests+// build (sampleTimestampMs == acceptedAtMs).+func senderSample(parentPeerID, childPeerID string, revision int64, connectionID, identity string, state SenderQualityState, at int64) SenderQualityEvidenceInput {+ return SenderQualityEvidenceInput{+ ParentPeerID: parentPeerID,+ ParentSessionID: parentSession(parentPeerID),+ ChildPeerID: childPeerID,+ RouteRevision: revision,+ ConnectionID: connectionID,+ SenderIdentity: &identity,+ SampleTimestampMs: ms(at),+ State: state,+ AcceptedAtMs: at,+ }+}++// unknownSample is the `state: "unknown", senderIdentity: null, sampleTimestampMs: null` literal.+func unknownSample(parentPeerID, childPeerID string, revision int64, connectionID string, at int64) SenderQualityEvidenceInput {+ return SenderQualityEvidenceInput{+ ParentPeerID: parentPeerID,+ ParentSessionID: parentSession(parentPeerID),+ ChildPeerID: childPeerID,+ RouteRevision: revision,+ ConnectionID: connectionID,+ State: SenderQualityUnknown,+ AcceptedAtMs: at,+ }+}++func observePersistentDegraded(t *testing.T, routes *Controller, childPeerID, connectionID string, acceptedAtMs int64) {+ t.Helper()+ eq(t, observeSenderState(routes, senderState{+ childPeerID: childPeerID, connectionID: connectionID, state: SenderQualityHealthy, acceptedAtMs: acceptedAtMs,+ }).Accepted, true)+ for offset := int64(1); offset <= 3; offset++ {+ eq(t, observeSenderState(routes, senderState{+ childPeerID: childPeerID, connectionID: connectionID, state: SenderQualityDegraded, acceptedAtMs: acceptedAtMs + offset,+ }).Accepted, true)+ }+}++func publisherSample(generation string, revision int64, state SenderQualityState, at int64) SfuPublisherQualityEvidenceInput {+ return SfuPublisherQualityEvidenceInput{+ HostPeerID: HOST,+ HostSessionID: "host_session",+ PublicationGeneration: generation,+ RouteRevision: revision,+ State: state,+ SampleTimestampMs: ms(at),+ AcceptedAtMs: at,+ }+}++func observePersistentSfuHealthy(t *testing.T, routes *Controller, generation string, revision, acceptedAtMs int64) SenderQualityEvidenceResult {+ t.Helper()+ var result SenderQualityEvidenceResult+ for offset := int64(0); offset < 3; offset++ {+ result = routes.ObserveSfuPublisherQualityEvidence(publisherSample(generation, revision, SenderQualityHealthy, acceptedAtMs+offset), nil)+ eq(t, result.Accepted, true)+ }+ return result+}++func qualityMetrics() protocol.ViewerQualityEvidenceMetrics {+ return protocol.ViewerQualityEvidenceMetrics{+ FramesDecodedDelta: optInt(120),+ FreezeCountDelta: optInt(1),+ FreezeDurationMsDelta: optNum(250),+ PauseCountDelta: optInt(0),+ PauseDurationMsDelta: optNum(0),+ }+}++func peerUpstream(peerID string) QualityUpstream {+ return QualityUpstream{Kind: UpstreamPeer, PeerID: peerID}+}++func sfuUpstream() QualityUpstream { return QualityUpstream{Kind: UpstreamSfu} }++func qualityWindow(childPeerID string, revision int64, connectionID string, upstream QualityUpstream, epoch, at int64, metrics protocol.ViewerQualityEvidenceMetrics) RouteQualityEvidenceInput {+ return RouteQualityEvidenceInput{+ ChildPeerID: childPeerID,+ ChildSessionID: sessionOf(childPeerID),+ RouteRevision: revision,+ ConnectionID: connectionID,+ Upstream: upstream,+ PresentationEpoch: epoch,+ WindowMs: 2_000,+ Metrics: metrics,+ AcceptedAtMs: at,+ }+}++// preparePeer ports the describe("bounded NAT candidate acquisition") helper.+func preparePeer(t *testing.T, routes *Controller, nowMs int64, id string) (operation, prepared *OperationSnapshot, guard CandidateGuard) {+ t.Helper()+ operation = must(t, routes.Reconcile(nowMs).Operation)+ prepared = beginOperation(t, routes, BeginInput{NowMs: nowMs, ConnectionID: id, Reservation: direct()})+ guard = CandidateGuard{+ ChildPeerID: prepared.ChildPeerID,+ ChildSessionID: prepared.ChildSessionID,+ Revision: prepared.Current.Revision,+ ConnectionID: id,+ }+ return operation, prepared, guard+}++func attemptCurrent(t *testing.T, operation *OperationSnapshot) int {+ t.Helper()+ if operation.Current == nil || operation.Current.ConnectionAttempt == nil {+ t.Fatal("expected a connection attempt")+ }+ return operation.Current.ConnectionAttempt.Current+}++// --- assertions -----------------------------------------------------------++func eq[T comparable](t *testing.T, got, want T) {+ t.Helper()+ if got != want {+ t.Fatalf("got %v, want %v", got, want)+ }+}++func eqSlice[T comparable](t *testing.T, got, want []T) {+ t.Helper()+ if !slices.Equal(got, want) {+ t.Fatalf("got %v, want %v", got, want)+ }+}++func eqDeep(t *testing.T, got, want any) {+ t.Helper()+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("got %+v, want %+v", got, want)+ }+}++// eqLabels ports `expect(released).toEqual([...])`: exact labels in order.+func eqLabels(t *testing.T, got []*Resource, want ...string) {+ t.Helper()+ eqSlice(t, labels(got), want)+}++// containsLabels ports `expect(released).toEqual(expect.arrayContaining([...]))`.+func containsLabels(t *testing.T, got []*Resource, want ...string) {+ t.Helper()+ have := labels(got)+ for _, label := range want {+ if !slices.Contains(have, label) {+ t.Fatalf("released %v does not contain %q", have, label)+ }+ }+}++// expectTransition ports toEqual on an endpoint transition without retire;+// producer "" means the TS object omitted producerPeerId.+func expectTransition(t *testing.T, got EndpointTransition, kind TransitionKind, producer string) {+ t.Helper()+ eq(t, got.Kind, kind)+ switch {+ case producer == "" && got.ProducerPeerID != nil:+ t.Fatalf("expected no producer, got %q", *got.ProducerPeerID)+ case producer != "" && (got.ProducerPeerID == nil || *got.ProducerPeerID != producer):+ t.Fatalf("expected producer %q, got %v", producer, got.ProducerPeerID)+ }+ if kind != TransitionBoundedGap && got.Retire != nil {+ t.Fatalf("expected no retirement for %q transition", kind)+ }+}++func expectPanic(t *testing.T, want string, fn func()) {+ t.Helper()+ defer func() {+ t.Helper()+ recovered := recover()+ if recovered == nil {+ t.Fatalf("expected a panic containing %q", want)+ }+ if !strings.Contains(fmt.Sprint(recovered), want) {+ t.Fatalf("panic %v does not contain %q", recovered, want)+ }+ }()+ fn()+}diff --git a/internal/server/route/operation.go b/internal/server/route/operation.gonew file mode 100644index 00000000..5cfac59e--- /dev/null+++ b/internal/server/route/operation.go@@ -0,0 +1,1468 @@+package route++import (+ "errors"+ "slices"+ "sort"+)++// validation is the private validateOrAdvance result. The TS `exhausted`+// flag was written (2454, 2588) but never read, so it is not ported.+type validation struct {+ released []*Resource+ exhaustedChildPeerID string // "" = undefined+ expired bool+ consumedGuard bool+}++// failedPeerIDsFrom ports 4943: dedupe preserving argument order.+func failedPeerIDsFrom(results ...validation) []string {+ ids := make([]string, 0, len(results))+ for _, result := range results {+ if result.exhaustedChildPeerID != "" {+ ids = append(ids, result.exhaustedChildPeerID)+ }+ }+ return dedupeStrings(ids)+}++func isBackgroundConvergence(reason DemandReason) bool {+ return reason == DemandDirectConvergence ||+ reason == DemandQualityConvergence ||+ reason == DemandRootConvergence+}++func isAvailabilityOperation(reason DemandReason) bool {+ return reason != DemandSfuBootstrap && !isBackgroundConvergence(reason)+}++// operationRequiresNativeCandidateProof ports 3554 (nil-safe).+func operationRequiresNativeCandidateProof(op *operation) bool {+ if op == nil {+ return false+ }+ return op.reason == DemandRootConvergence ||+ (op.reason == DemandQualityConvergence && op.current != nil && op.current.tuple.Kind == UpstreamSfu)+}++// directHeadStartMs ports 3535: min(5000, max(1, floor(timeout / 2))).+func (c *Controller) directHeadStartMs() int64 {+ return min(maxDirectHeadStartMs, max(1, c.operationTimeoutMs/2))+}++// Reconcile validates or advances the current operation, prunes departed+// leaves and starts at most one new operation in strict priority+// (sfu-bootstrap carrier, next child, direct continuation, quality child,+// root convergence).+func (c *Controller) Reconcile(nowMs int64) ReconcileResult {+ released := []*Resource{}+ validation := c.validateOrAdvance(nowMs, nil)+ released = append(released, validation.released...)+ failedPeerIDs := failedPeerIDsFrom(validation)+ if c.operation != nil &&+ isBackgroundConvergence(c.operation.reason) &&+ (c.hasSfuBootstrapWork() || c.selectNextChild() != "") {+ c.debug(string(c.operation.reason)+"-preempted", "child", c.debugPeer(c.operation.childPeerID))+ released = append(released, c.abortOperation(&nowMs, RejectionAborted)...)+ }+ if c.paused || c.operation != nil {+ return ReconcileResult{+ Operation: c.operationSnapshot(),+ RemovedPeerIDs: []string{},+ FailedPeerIDs: failedPeerIDs,+ Released: released,+ }+ }+ removedPeerIDs := c.pruneDepartedLeaves(&released)++ // The loop bound is a count, not an order (§4.1 #8).+ for remaining := c.participants.Len(); remaining > 0; remaining-- {+ bootstrap := c.takeSfuBootstrapCarrier(nowMs, &failedPeerIDs)+ routeChildPeerID := ""+ if bootstrap == nil {+ routeChildPeerID = c.selectNextChild()+ }+ var continuation *directContinuationPick+ if routeChildPeerID == "" && bootstrap == nil {+ continuation = c.selectDirectContinuation()+ }+ qualityChildPeerID := ""+ if routeChildPeerID == "" && bootstrap == nil && continuation == nil {+ qualityChildPeerID = c.selectQualityChild(nowMs)+ }+ var rootConvergence *rootConvergencePick+ if routeChildPeerID == "" && bootstrap == nil && continuation == nil && qualityChildPeerID == "" {+ rootConvergence = c.takeRootConvergenceIntent()+ }+ childPeerID := routeChildPeerID+ switch {+ case childPeerID != "":+ case bootstrap != nil:+ childPeerID = bootstrap.carrierPeerID+ case continuation != nil:+ childPeerID = continuation.childPeerID+ case qualityChildPeerID != "":+ childPeerID = qualityChildPeerID+ case rootConvergence != nil:+ childPeerID = rootConvergence.childPeerID+ }+ if childPeerID == "" {+ return ReconcileResult{RemovedPeerIDs: removedPeerIDs, FailedPeerIDs: failedPeerIDs, Released: released}+ }+ child, _ := c.participants.Get(childPeerID)+ var reason DemandReason+ switch {+ case continuation != nil:+ reason = DemandDirectConvergence+ case bootstrap != nil:+ reason = DemandSfuBootstrap+ case qualityChildPeerID != "":+ reason = DemandQualityConvergence+ case rootConvergence != nil:+ reason = DemandRootConvergence+ default:+ reason = c.routeDemandReason(childPeerID)+ }+ demandPeerID := childPeerID+ if bootstrap != nil {+ demandPeerID = bootstrap.demandPeerID+ }+ demand, _ := c.participants.Get(demandPeerID)+ c.ensureDemand(demandPeerID, nowMs, reason)+ var candidates []CandidatePlan+ switch {+ case continuation != nil:+ candidates = []CandidatePlan{continuation.plan}+ case qualityChildPeerID != "":+ candidates = c.buildQualityCandidates(childPeerID, nowMs)+ case rootConvergence != nil:+ candidates = []CandidatePlan{rootConvergence.plan}+ default:+ candidates = c.buildCandidates(childPeerID, bootstrap != nil)+ }+ if bootstrap == nil && continuation == nil && demand.sfuFirstAtNextRoute {+ // Ordering site §4.4 #30: the SFU candidate moves to the front.+ sfuIndex := slices.IndexFunc(candidates, func(candidate CandidatePlan) bool {+ return candidate.Tuple.Kind == UpstreamSfu+ })+ if sfuIndex > 0 {+ reordered := make([]CandidatePlan, 0, len(candidates))+ reordered = append(reordered, candidates[sfuIndex])+ reordered = append(reordered, candidates[:sfuIndex]...)+ reordered = append(reordered, candidates[sfuIndex+1:]...)+ candidates = reordered+ }+ }+ if reason == DemandSfuBootstrap {+ // Ordering site §4.4 #31: bootstrap sets drop bounded-gap candidates.+ filtered := make([]CandidatePlan, 0, len(candidates))+ for _, candidate := range candidates {+ if candidate.EndpointTransition.Kind != TransitionBoundedGap {+ filtered = append(filtered, candidate)+ }+ }+ candidates = filtered+ }+ if len(candidates) == 0 {+ c.debug("operation-unavailable", "child", c.debugPeer(childPeerID), "reason", reason)+ if isBackgroundConvergence(reason) {+ if reason == DemandDirectConvergence {+ c.directContinuations.Delete(childPeerID)+ }+ c.finishTiming(childPeerID, nowMs, c.currentFinalRoute(childPeerID), RejectionCandidateFailed, false)+ continue+ }+ if reason == DemandSfuBootstrap {+ if failedDemandPeerID := c.completeSfuBootstrapCarrier(childPeerID, nowMs, RejectionCandidateFailed, nil); failedDemandPeerID != "" {+ failedPeerIDs = append(failedPeerIDs, failedDemandPeerID)+ }+ continue+ }+ if c.retireInvalidOperationEdge(childPeerID, &released) {+ c.revision = c.allocateRevision()+ c.touchFacts()+ }+ child.availabilityExhausted = true+ bucket := RejectionCandidateFailed+ if reason == DemandCapacityReduction {+ bucket = RejectionEndpointCapacity+ }+ c.finishTiming(demandPeerID, nowMs, FinalRouteFailed, bucket, false)+ if c.bootstrapCandidateAvailable(demandPeerID) {+ continue+ }+ c.rememberUnavailableSfuBootstrap(demandPeerID)+ failedPeerIDs = append(failedPeerIDs, demandPeerID)+ continue+ }+ c.startOperationTiming(demandPeerID, nowMs)+ var qualitySource *senderQualityIdentity+ if reason == DemandQualityConvergence {+ qualitySource = c.currentQualityOperationSource(childPeerID)+ }+ c.operation = &operation{+ childPeerID: childPeerID,+ childSessionID: child.sessionID,+ demandPeerID: demandPeerID,+ demandSessionID: demand.sessionID,+ reason: reason,+ baseRevision: c.revision,+ candidates: candidates,+ cursor: 0,+ deadlineAtMs: nowMs + c.operationTimeoutMs,+ builtAtFactVersion: c.factVersion,+ deferredParentPeerIDs: []string{},+ qualitySource: qualitySource,+ }+ if debugEnabled {+ routes := make([]debugCandidate, 0, len(candidates))+ for _, candidate := range candidates {+ routes = append(routes, debugCandidate{Route: c.debugTuple(candidate.Tuple), Transition: candidate.EndpointTransition.Kind})+ }+ c.debug("operation-started", "child", c.debugPeer(childPeerID), "reason", reason, "candidates", routes)+ }+ return ReconcileResult{+ Operation: c.operationSnapshot(),+ RemovedPeerIDs: removedPeerIDs,+ FailedPeerIDs: failedPeerIDs,+ Released: released,+ }+ }+ return ReconcileResult{RemovedPeerIDs: removedPeerIDs, FailedPeerIDs: failedPeerIDs, Released: released}+}++// BeginCurrentCandidate starts the candidate at the guarded cursor with the+// caller's reservation; every rejection echoes the reservation back in+// Released. Panics on a reservation that does not match the tuple.+func (c *Controller) BeginCurrentCandidate(input BeginInput) BeginResult {+ validation := c.validateOrAdvance(input.NowMs, nil)+ op := c.operation+ if op == nil || op.current != nil || op.baseRevision != c.revision ||+ !c.cursorGuardMatches(input.Guard, op) {+ return BeginResult{+ Accepted: false,+ Released: concatResources(validation.released, reservationResources(input.Reservation)),+ FailedPeerIDs: failedPeerIDsFrom(validation),+ }+ }+ plan := op.planAt(op.cursor)+ if plan == nil || !c.operationCandidateValid(op, *plan, nil) {+ return BeginResult{+ Accepted: false,+ Released: concatResources(validation.released, reservationResources(input.Reservation)),+ FailedPeerIDs: failedPeerIDsFrom(validation),+ }+ }+ if plan.EndpointTransition.Kind == TransitionBoundedGap {+ return BeginResult{+ Accepted: false,+ Operation: c.operationSnapshot(),+ FailedPeerIDs: failedPeerIDsFrom(validation),+ Released: concatResources(validation.released, reservationResources(input.Reservation)),+ }+ }+ tuple := plan.Tuple+ hostSessionID := ""+ if tuple.Kind == UpstreamSfu {+ if host, ok := c.participants.Get(c.hostPeerID); ok {+ hostSessionID = host.sessionID+ }+ }+ if tuple.Kind == UpstreamSfu && (input.HostSessionID == "" || input.HostSessionID != hostSessionID) {+ return BeginResult{+ Accepted: false,+ Operation: c.operationSnapshot(),+ FailedPeerIDs: failedPeerIDsFrom(validation),+ Released: concatResources(validation.released, reservationResources(input.Reservation)),+ }+ }+ assertReservation(tuple, input.Reservation, plan.EndpointTransition.Kind == TransitionOverlap)+ publicationGeneration := ""+ if tuple.Kind == UpstreamSfu {+ if tuple.Publication == PublicationReuse {+ if c.hostPublication != nil {+ publicationGeneration = c.hostPublication.Generation+ }+ } else {+ publicationGeneration = input.PublicationGeneration+ }+ }+ if tuple.Kind == UpstreamSfu && publicationGeneration == "" {+ panic(errors.New("SFU candidate needs a publication generation"))+ }+ if tuple.Kind == UpstreamSfu && tuple.Publication != PublicationReuse && input.PublicationConnectionID == "" {+ panic(errors.New("SFU publication candidate needs an ingress connection identity"))+ }+ parentSessionID := ""+ if tuple.Kind == UpstreamPeer {+ if parent, ok := c.participants.Get(tuple.ParentPeerID); ok {+ parentSessionID = parent.sessionID+ }+ }+ attemptHostSessionID := ""+ if tuple.Kind == UpstreamSfu {+ attemptHostSessionID = input.HostSessionID+ }+ op.current = &attempt{+ tuple: tuple,+ revision: c.allocateRevision(), // this.revision is NOT advanced here (1841)+ connectionID: input.ConnectionID,+ childSessionID: op.childSessionID,+ parentSessionID: parentSessionID,+ hostSessionID: attemptHostSessionID,+ publicationGeneration: publicationGeneration,+ publicationConnectionID: input.PublicationConnectionID,+ reservation: input.Reservation,+ startedAtMs: input.NowMs,+ transportConnected: false,+ mediaReady: false,+ connectionAttempt: c.startCandidateOpportunity(op, *plan),+ }+ if debugEnabled {+ details := []any{+ "child", c.debugPeer(op.childPeerID),+ "candidate", c.debugTuple(tuple),+ "revision", op.current.revision,+ "cursor", op.cursor,+ }+ if op.current.connectionAttempt != nil {+ details = append(details, "connectionAttempt", *op.current.connectionAttempt)+ }+ c.debug("candidate-started", details...)+ }+ c.startCandidateTiming(op.demandPeerID, input.NowMs)+ return BeginResult{+ Accepted: true,+ Operation: c.operationSnapshot(),+ FailedPeerIDs: failedPeerIDsFrom(validation),+ Released: validation.released,+ }+}++// NoteCurrentCandidateRejection records a rejection bucket for the guarded+// cursor while no attempt is live; true when the guard matched.+func (c *Controller) NoteCurrentCandidateRejection(guard CandidateCursorGuard, bucket RejectionBucket) bool {+ op := c.operation+ if op == nil || op.current != nil || !c.cursorGuardMatches(guard, op) {+ return false+ }+ c.noteRejection(op.demandPeerID, bucket)+ return true+}++// SkipCurrentCandidate consumes the guarded candidate and advances the+// cursor (TS defaulted bucket to "stale"; Go callers pass RejectionStale).+func (c *Controller) SkipCurrentCandidate(guard CandidateCursorGuard, nowMs int64, bucket RejectionBucket) BeginResult {+ validation := c.validateOrAdvance(nowMs, nil)+ op := c.operation+ if op == nil || op.current != nil || !c.cursorGuardMatches(guard, op) {+ return BeginResult{+ Accepted: false,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ Released: validation.released,+ }+ }+ if bucket == RejectionCandidateFailed {+ if isAvailabilityOperation(op.reason) {+ c.consumeCandidateOpportunity(op.childPeerID, op.candidates[op.cursor])+ }+ c.promoteNextDirectWithinHeadStart(op, nowMs)+ }+ c.consumeQualityCandidateOpportunity(op, op.planAt(op.cursor))+ c.consumeDirectContinuationCandidate(op)+ c.noteRejection(op.demandPeerID, bucket)+ c.debug("candidate-rejected",+ "child", c.debugPeer(op.childPeerID),+ "candidate", c.debugTuple(op.candidates[op.cursor].Tuple),+ "bucket", bucket,+ "cursor", op.cursor)+ op.cursor+++ c.clearCandidateTiming(op.demandPeerID)+ advanced := c.validateOrAdvance(nowMs, nil)+ return BeginResult{+ Operation: c.operationSnapshot(),+ Accepted: true,+ FailedPeerIDs: failedPeerIDsFrom(validation, advanced),+ Released: concatResources(validation.released, advanced.released),+ }+}++// RetireCurrentCandidateProducer performs the bounded-gap retirement of the+// guarded candidate's producer, advances the revision and replans the tail.+func (c *Controller) RetireCurrentCandidateProducer(guard CandidateCursorGuard, nowMs int64) BeginResult {+ validation := c.validateOrAdvance(nowMs, nil)+ op := c.operation+ if op == nil || op.current != nil || !c.cursorGuardMatches(guard, op) {+ return BeginResult{+ Accepted: false,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ Released: validation.released,+ }+ }+ plan := op.planAt(op.cursor)+ if plan == nil || plan.EndpointTransition.Kind != TransitionBoundedGap {+ return BeginResult{+ Accepted: false,+ Operation: c.operationSnapshot(),+ FailedPeerIDs: failedPeerIDsFrom(validation),+ Released: validation.released,+ }+ }+ released := concatResources(validation.released)+ retirement := plan.EndpointTransition.Retire+ var restoreTuple *CandidateTuple+ if retirement.Kind == RetireEdge {+ edge, _ := c.upstreamByViewer.Get(retirement.ChildPeerID)+ if edge == nil || edge.Kind != UpstreamPeer || !edge.PhysicalActive ||+ edge.ChildSessionID != retirement.ChildSessionID ||+ edge.ParentPeerID != retirement.ParentPeerID ||+ edge.ParentSessionID != retirement.ParentSessionID ||+ edge.Transport != retirement.Transport ||+ edge.ConnectionID != retirement.ConnectionID {+ return BeginResult{+ Accepted: false,+ Operation: c.operationSnapshot(),+ FailedPeerIDs: failedPeerIDsFrom(validation),+ Released: released,+ }+ }+ if edge.Usable {+ restoreTuple = &CandidateTuple{Kind: UpstreamPeer, ParentPeerID: edge.ParentPeerID, Transport: edge.Transport}+ }+ edge.Usable = false+ edge.PhysicalActive = false+ } else {+ publication := c.hostPublication+ if publication == nil || !publication.PhysicalActive ||+ publication.HostSessionID != retirement.HostSessionID ||+ publication.Generation != retirement.Generation ||+ publication.ConnectionID != retirement.ConnectionID {+ return BeginResult{+ Accepted: false,+ Operation: c.operationSnapshot(),+ FailedPeerIDs: failedPeerIDsFrom(validation),+ Released: released,+ }+ }+ released = append(released, c.removePublicationGeneration(retirement.Generation)...)+ }+ c.advanceActiveRevision(op)+ c.touchFacts()+ nextTuple := plan.Tuple+ if retirement.Kind == RetirePublication && plan.Tuple.Kind == UpstreamSfu && plan.Tuple.Publication == PublicationReplace {+ nextTuple.Publication = PublicationCreate+ }+ c.replanRemaining(op, &nextTuple, restoreTuple)+ if op.cursor >= len(op.candidates) {+ advanced := c.validateOrAdvance(nowMs, nil)+ return BeginResult{+ Accepted: true,+ Operation: c.operationSnapshot(),+ FailedPeerIDs: failedPeerIDsFrom(validation, advanced),+ Released: concatResources(released, advanced.released),+ }+ }+ return BeginResult{+ Accepted: true,+ Operation: c.operationSnapshot(),+ FailedPeerIDs: failedPeerIDsFrom(validation),+ Released: released,+ }+}++// CandidateReady is the commit gate for the guarded live attempt: commits+// when the required proof is present and commitReservation (nil = always+// true) accepts, fails the candidate otherwise.+func (c *Controller) CandidateReady(guard CandidateGuard, nowMs int64, commitReservation func(CandidateReservation) bool, proof CandidateProof) SettleResult {+ if commitReservation == nil {+ commitReservation = func(CandidateReservation) bool { return true }+ }+ validation := c.validateOrAdvance(nowMs, nil)+ op := c.operation+ var att *attempt+ if op != nil {+ att = op.current+ }+ if op == nil || att == nil || !c.guardMatches(guard, op, att) {+ return SettleResult{+ Accepted: false,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: c.revision,+ Released: validation.released,+ }+ }+ qualityPeer := op.reason == DemandQualityConvergence && att.tuple.Kind == UpstreamPeer+ relativeP2pProof := qualityPeer && proof.RelativeQualityApproved+ if relativeP2pProof && att.relativeQualityApprovedAtMs == nil {+ approvedAt := nowMs+ att.relativeQualityApprovedAtMs = &approvedAt+ }+ relativeP2pApproved := qualityPeer &&+ att.relativeQualityApprovedAtMs != nil &&+ nowMs < *att.relativeQualityApprovedAtMs+qualityEvidenceExpiryMs+ relativeP2pExpired := qualityPeer &&+ att.relativeQualityApprovedAtMs != nil &&+ !relativeP2pApproved+ relativeP2pPending := qualityPeer && !relativeP2pApproved+ if relativeP2pApproved && c.candidateSenderPersistentlyDegraded(att, nowMs) {+ return c.CandidateFailed(guard, nowMs)+ }+ nativeCandidateProof := operationRequiresNativeCandidateProof(op)+ if relativeP2pApproved || relativeP2pPending || nativeCandidateProof {+ att.mediaReady = true+ currentEdge, _ := c.upstreamByViewer.Get(op.childPeerID)+ if (op.reason == DemandQualityConvergence &&+ (currentEdge == nil || c.senderQualityState(op.childPeerID, currentEdge, nowMs) != SenderQualityDegraded)) ||+ (op.reason == DemandRootConvergence && !c.rootConvergenceOperationStillEligible(op)) {+ // TS 2086-2095: the object literal reads `activeRevision: this.revision`+ // before `released: [...this.abortOperation(...)]` advances it.+ activeRevision := c.revision+ return SettleResult{+ Accepted: true,+ Committed: false,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: activeRevision,+ Released: concatResources(validation.released, c.abortOperation(&nowMs, RejectionAborted)),+ }+ }+ }+ if relativeP2pExpired {+ // A one-shot client proof cannot be renewed by a late sender sample.+ // Release this candidate so the existing bounded cursor can try the+ // next route instead of waiting for the whole operation deadline.+ return c.CandidateFailed(guard, nowMs)+ }+ if relativeP2pPending {+ return SettleResult{+ Accepted: true,+ Committed: false,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: c.revision,+ Released: validation.released,+ }+ }+ if relativeP2pApproved &&+ (att.senderQualityState != SenderQualityHealthy ||+ att.senderQualityAcceptedAtMs == nil ||+ nowMs >= *att.senderQualityAcceptedAtMs+qualityEvidenceExpiryMs) {+ return SettleResult{+ Accepted: true,+ Committed: false,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: c.revision,+ Released: validation.released,+ }+ }+ if nativeCandidateProof {+ sfuReuse := att.tuple.Kind == UpstreamSfu && att.tuple.Publication == PublicationReuse+ var candidateQualityState SenderQualityState+ if sfuReuse {+ candidateQualityState = c.sfuPublisherQualityState(att.publicationGeneration, nowMs)+ } else if att.senderQualityState != "" {+ candidateQualityState = att.senderQualityState+ } else {+ candidateQualityState = SenderQualityUnknown+ }+ candidateQualityReady := candidateQualityState == SenderQualityHealthy &&+ (att.tuple.Kind != UpstreamSfu ||+ att.tuple.Publication == PublicationReuse ||+ att.senderQualityConsecutiveHealthyWindows >= persistentDegradedWindows)+ if !candidateQualityReady && candidateQualityState != SenderQualityDegraded {+ return SettleResult{+ Accepted: true,+ Committed: false,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: c.revision,+ Released: validation.released,+ }+ }+ if !sfuReuse &&+ (att.senderQualityAcceptedAtMs == nil ||+ nowMs >= *att.senderQualityAcceptedAtMs+qualityEvidenceExpiryMs) {+ return c.CandidateFailed(guard, nowMs)+ }+ if candidateQualityState == SenderQualityDegraded {+ return c.CandidateFailed(guard, nowMs)+ }+ }+ if !commitReservation(att.reservation) {+ c.consumeCurrentAvailabilityOpportunity(op)+ c.debug("candidate-commit-rejected",+ "child", c.debugPeer(op.childPeerID),+ "candidate", c.debugTuple(att.tuple),+ "revision", att.revision)+ c.promoteNextDirectWithinHeadStart(op, nowMs)+ c.noteRejection(op.demandPeerID, RejectionCandidateFailed)+ failed := c.validateOrAdvance(nowMs, &guard)+ return SettleResult{+ Accepted: false,+ FailedPeerIDs: failedPeerIDsFrom(validation, failed),+ ActiveRevision: c.revision,+ Released: concatResources(validation.released, failed.released),+ }+ }+ if op.reason != DemandSfuBootstrap {+ finalRoute := FinalRouteSfu+ if att.tuple.Kind == UpstreamPeer {+ finalRoute = FinalRouteDirect+ }+ c.finishTiming(op.demandPeerID, nowMs, finalRoute, RejectionNone, true)+ }+ c.debug("candidate-ready",+ "child", c.debugPeer(op.childPeerID),+ "candidate", c.debugTuple(att.tuple),+ "revision", att.revision)+ // Ordering site §4.2 #16: displaced SFU children in map order.+ displacedSfuChildren := []string{}+ if att.tuple.Kind == UpstreamSfu && att.tuple.Publication == PublicationReplace {+ for childPeerID, edge := range c.upstreamByViewer.All() {+ if childPeerID != op.childPeerID && edge.Kind == UpstreamSfu && edge.PhysicalActive {+ displacedSfuChildren = append(displacedSfuChildren, childPeerID)+ }+ }+ }+ released := concatResources(validation.released, c.commitAttempt(op, att))+ for _, childPeerID := range displacedSfuChildren {+ c.ensureDemand(childPeerID, nowMs, DemandEdgeUnavailable)+ }+ return SettleResult{+ Accepted: true,+ Committed: true,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: c.revision,+ Released: released,+ }+}++// CandidateTransportConnected marks the guarded peer attempt as connected so+// it survives the direct head start until the operation deadline.+func (c *Controller) CandidateTransportConnected(guard CandidateGuard, nowMs int64) SettleResult {+ validation := c.validateOrAdvance(nowMs, nil)+ op := c.operation+ var att *attempt+ if op != nil {+ att = op.current+ }+ if op == nil || att == nil || att.tuple.Kind != UpstreamPeer || !c.guardMatches(guard, op, att) {+ return SettleResult{+ Accepted: false,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: c.revision,+ Released: validation.released,+ }+ }+ att.transportConnected = true+ c.debug("candidate-transport-connected",+ "child", c.debugPeer(op.childPeerID),+ "candidate", c.debugTuple(att.tuple),+ "revision", att.revision)+ return SettleResult{+ Accepted: true,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: c.revision,+ Released: validation.released,+ }+}++// CandidateFailed fails the guarded live attempt, releasing its reservation+// and advancing the cursor; Accepted reports whether the guard was consumed.+func (c *Controller) CandidateFailed(guard CandidateGuard, nowMs int64) SettleResult {+ op := c.operation+ if op != nil && op.current != nil && c.guardMatches(guard, op, op.current) {+ c.consumeCurrentAvailabilityOpportunity(op)+ c.debug("candidate-failed",+ "child", c.debugPeer(op.childPeerID),+ "candidate", c.debugTuple(op.current.tuple),+ "revision", op.current.revision)+ c.promoteNextDirectWithinHeadStart(op, nowMs)+ c.noteRejection(op.demandPeerID, RejectionCandidateFailed)+ }+ validation := c.validateOrAdvance(nowMs, &guard)+ return SettleResult{+ Accepted: validation.consumedGuard,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: c.revision,+ Released: validation.released,+ }+}++// OperationExpired applies head-start and deadline expiry at nowMs;+// Accepted reports whether something expired.+func (c *Controller) OperationExpired(nowMs int64) SettleResult {+ if op := c.operation; op != nil && debugEnabled {+ current := op.current+ noProgress := current != nil &&+ current.tuple.Kind == UpstreamPeer &&+ !current.transportConnected &&+ c.peerCandidateHasSuccessor(op) &&+ nowMs >= current.startedAtMs+c.directHeadStartMs() &&+ nowMs < op.deadlineAtMs+ event := "operation-deadline"+ if noProgress {+ event = "candidate-no-progress"+ }+ var candidate any+ if current != nil {+ candidate = c.debugTuple(current.tuple)+ }+ c.debug(event,+ "child", c.debugPeer(op.childPeerID),+ "candidate", candidate,+ "cursor", op.cursor,+ "candidateCount", len(op.candidates))+ }+ validation := c.validateOrAdvance(nowMs, nil)+ return SettleResult{+ Accepted: validation.expired,+ FailedPeerIDs: failedPeerIDsFrom(validation),+ ActiveRevision: c.revision,+ Released: validation.released,+ }+}++// validateOrAdvance ports 2342: the single place that expires, replans and+// clears the operation. failedGuard names an attempt the caller failed.+func (c *Controller) validateOrAdvance(nowMs int64, failedGuard *CandidateGuard) validation {+ activeRevisionAtStart := c.revision+ result := validation{released: []*Resource{}}+ op := c.operation+ if op == nil {+ return result+ }+ if !c.bootstrapOperationOwned(op) {+ if op.current != nil {+ result.released = append(result.released, reservationResources(op.current.reservation)...)+ c.advanceActiveRevision(op)+ }+ c.finishTiming(op.demandPeerID, nowMs, c.currentFinalRoute(op.demandPeerID), RejectionStale, false)+ c.operation = nil+ return result+ }+ if op.reason == DemandQualityConvergence && !c.qualityOperationStillEligible(op, nowMs) {+ result.released = append(result.released, c.abortOperation(&nowMs, RejectionAborted)...)+ return result+ }+ if op.reason == DemandRootConvergence && !c.rootConvergenceOperationStillEligible(op) {+ result.released = append(result.released, c.abortOperation(&nowMs, RejectionAborted)...)+ return result+ }+ if nowMs >= op.deadlineAtMs {+ directConvergence := op.reason == DemandDirectConvergence+ sfuBootstrap := op.reason == DemandSfuBootstrap+ qualityConvergence := op.reason == DemandQualityConvergence+ backgroundConvergence := isBackgroundConvergence(op.reason)+ if directConvergence {+ c.consumeDirectContinuationCandidate(op)+ }+ if qualityConvergence {+ c.consumeQualityOperationCandidates(op)+ }+ if op.current != nil {+ result.released = append(result.released, reservationResources(op.current.reservation)...)+ }+ revisionAdvanced := op.current != nil+ if op.current != nil {+ c.advanceActiveRevision(op)+ }+ factsChanged := op.builtAtFactVersion != c.factVersion+ deadlineBucket := RejectionOperationDeadline+ if factsChanged {+ deadlineBucket = RejectionStale+ }+ failedBootstrapDemand := ""+ if sfuBootstrap {+ failedBootstrapDemand = c.completeSfuBootstrapCarrier(op.childPeerID, nowMs, deadlineBucket, op.planAtOrLast())+ }+ bootstrapAvailable := !backgroundConvergence && !sfuBootstrap && c.bootstrapCandidateAvailable(op.demandPeerID)+ if bootstrapAvailable {+ c.consumeCurrentAvailabilityOpportunity(op)+ } else {+ c.consumeAvailabilityOperation(op)+ }+ var exhausted bool+ if sfuBootstrap {+ exhausted = failedBootstrapDemand != ""+ } else {+ exhausted = !backgroundConvergence && !bootstrapAvailable && !c.hasRemainingNatOpportunity(op)+ }+ if bootstrapAvailable {+ c.stageSfuBootstrap(op)+ }+ if !sfuBootstrap {+ c.finishTiming(op.demandPeerID, nowMs, c.expiredFinalRoute(op, backgroundConvergence, exhausted), deadlineBucket, false)+ }+ c.blockAndClear(op, !backgroundConvergence && !sfuBootstrap, &result.released, revisionAdvanced)+ if exhausted && !sfuBootstrap {+ c.rememberUnavailableSfuBootstrap(op.demandPeerID)+ }+ result.expired = true+ if failedBootstrapDemand != "" {+ result.exhaustedChildPeerID = failedBootstrapDemand+ } else if exhausted {+ result.exhaustedChildPeerID = op.demandPeerID+ }+ return result+ }+ if c.advanceExpiredDirectHeadStart(op, nowMs, &result.released) {+ result.expired = true+ }+ child, _ := c.participants.Get(op.childPeerID)+ demand, _ := c.participants.Get(op.demandPeerID)+ if child == nil || !child.sessionIs(op.childSessionID) || demand == nil || !demand.sessionIs(op.demandSessionID) {+ if op.current != nil {+ result.released = append(result.released, reservationResources(op.current.reservation)...)+ c.advanceActiveRevision(op)+ }+ c.finishTiming(op.demandPeerID, nowMs, c.currentFinalRoute(op.demandPeerID), RejectionAborted, false)+ c.operation = nil+ return result+ }++ for c.operation != nil {+ op = c.operation+ att := op.current+ if att == nil && op.builtAtFactVersion != c.factVersion {+ c.replanRemaining(op, nil, nil)+ }+ if att != nil {+ guardFailed := failedGuard != nil && c.guardMatches(*failedGuard, op, att)+ plan := op.planAt(op.cursor)+ peerNoProgressExpired := att.tuple.Kind == UpstreamPeer &&+ !att.transportConnected &&+ c.peerCandidateHasSuccessor(op) &&+ nowMs >= att.startedAtMs+c.directHeadStartMs()+ if !guardFailed && !peerNoProgressExpired && plan != nil && c.operationCandidateValid(op, *plan, att) {+ return result+ }+ if !guardFailed {+ bucket := RejectionStale+ if peerNoProgressExpired {+ bucket = RejectionFirstFrameTimeout+ }+ c.noteRejection(op.demandPeerID, bucket)+ }+ if peerNoProgressExpired {+ result.expired = true+ }+ if guardFailed || peerNoProgressExpired {+ c.consumeQualityCandidateOpportunity(op, plan)+ }+ if op.reason == DemandDirectConvergence {+ c.consumeDirectContinuationCandidate(op)+ }+ result.released = append(result.released, reservationResources(att.reservation)...)+ c.advanceActiveRevision(op)+ op.current = nil+ op.cursor+++ c.clearCandidateTiming(op.demandPeerID)+ result.consumedGuard = guardFailed+ c.replanRemaining(op, nil, nil)+ }+ for op.cursor < len(op.candidates) && !c.operationCandidateValid(op, op.candidates[op.cursor], nil) {+ c.noteRejection(op.demandPeerID, RejectionStale)+ if op.reason == DemandDirectConvergence {+ c.consumeDirectContinuationCandidate(op)+ }+ op.cursor+++ c.clearCandidateTiming(op.demandPeerID)+ }+ if op.cursor < len(op.candidates) {+ return result+ }+ sfuBootstrap := op.reason == DemandSfuBootstrap+ backgroundConvergence := isBackgroundConvergence(op.reason)+ factsChanged := op.builtAtFactVersion != c.factVersion+ rejectionBucket := RejectionCandidateFailed+ if factsChanged {+ rejectionBucket = RejectionStale+ } else if record := c.routeTimings[op.demandPeerID]; record != nil && record.rejectionBucket != RejectionNone {+ rejectionBucket = record.rejectionBucket+ }+ failedBootstrapDemand := ""+ if sfuBootstrap {+ failedBootstrapDemand = c.completeSfuBootstrapCarrier(op.childPeerID, nowMs, rejectionBucket, op.planAtOrLast())+ }+ bootstrapAvailable := !backgroundConvergence && !sfuBootstrap && c.bootstrapCandidateAvailable(op.demandPeerID)+ if !bootstrapAvailable {+ c.consumeAvailabilityOperation(op)+ }+ var exhausted bool+ if sfuBootstrap {+ exhausted = failedBootstrapDemand != ""+ } else {+ exhausted = !backgroundConvergence && !bootstrapAvailable && !c.hasRemainingNatOpportunity(op)+ }+ if bootstrapAvailable {+ c.stageSfuBootstrap(op)+ }+ if !sfuBootstrap {+ c.finishTiming(op.demandPeerID, nowMs, c.expiredFinalRoute(op, backgroundConvergence, exhausted), rejectionBucket, false)+ }+ c.blockAndClear(op, !backgroundConvergence && !sfuBootstrap, &result.released, c.revision != activeRevisionAtStart)+ if failedBootstrapDemand != "" {+ result.exhaustedChildPeerID = failedBootstrapDemand+ } else if exhausted {+ result.exhaustedChildPeerID = op.demandPeerID+ c.rememberUnavailableSfuBootstrap(op.demandPeerID)+ }+ }+ return result+}++// expiredFinalRoute is the finalRoute expression shared by both+// validateOrAdvance terminal branches (2434-2438, 2573-2577).+func (c *Controller) expiredFinalRoute(op *operation, backgroundConvergence, exhausted bool) FinalRoute {+ if backgroundConvergence {+ return c.currentFinalRoute(op.demandPeerID)+ }+ if exhausted {+ return FinalRouteFailed+ }+ return FinalRouteWaiting+}++// commitAttempt ports 2600: installs the attempt as the child's committed+// edge and returns the resources committed before but not after, plus the+// overlap (§4.2 #14).+func (c *Controller) commitAttempt(op *operation, att *attempt) []*Resource {+ before := &resourceSet{}+ before.add(c.committedResources()...)+ old, _ := c.upstreamByViewer.Get(op.childPeerID)+ oldPeer := old != nil && old.Kind == UpstreamPeer+ sameParentRegeneration := op.reason == DemandQualityConvergence &&+ att.tuple.Kind == UpstreamPeer &&+ att.tuple.Regenerate &&+ oldPeer &&+ old.ParentPeerID == att.tuple.ParentPeerID+ createsHostRoot := att.tuple.Kind == UpstreamPeer &&+ att.tuple.ParentPeerID == c.hostPeerID &&+ !(oldPeer && old.ParentPeerID == c.hostPeerID)+ c.clearQualityForParticipant(op.childPeerID)++ if att.tuple.Kind == UpstreamSfu && att.tuple.Publication == PublicationReplace {+ // The return value is discarded on purpose (2616): the before/after+ // diff below picks those resources up.+ c.removePublicationGeneration(c.hostPublication.Generation)+ }++ if att.tuple.Kind == UpstreamPeer {+ parent, _ := c.participants.Get(att.tuple.ParentPeerID)+ if parent == nil || parent.sessionID == "" {+ panic(errors.New("Candidate parent session is unavailable"))+ }+ // Map.set keeps an existing child's position (§4.2 #15).+ c.upstreamByViewer.Set(op.childPeerID, &CommittedEdge{+ Kind: UpstreamPeer,+ ChildSessionID: op.childSessionID,+ ParentPeerID: att.tuple.ParentPeerID,+ ParentSessionID: parent.sessionID,+ Transport: TransportDirect,+ ConnectionID: att.connectionID,+ Usable: true,+ PhysicalActive: true,+ })+ c.directContinuations.Delete(op.childPeerID)+ } else {+ generation := att.publicationGeneration+ if att.tuple.Publication != PublicationReuse {+ hostSessionID := ""+ if host, ok := c.participants.Get(c.hostPeerID); ok {+ hostSessionID = host.sessionID+ }+ if hostSessionID == "" || att.publicationConnectionID == "" {+ panic(errors.New("SFU publication identity is unavailable"))+ }+ if att.hostSessionID != hostSessionID {+ panic(errors.New("SFU publication Host session is stale"))+ }+ c.hostPublication = &HostPublication{+ Generation: generation,+ HostSessionID: hostSessionID,+ ConnectionID: att.publicationConnectionID,+ Usable: true,+ PhysicalActive: true,+ Resource: att.reservation.Publication,+ }+ }+ c.upstreamByViewer.Set(op.childPeerID, &CommittedEdge{+ Kind: UpstreamSfu,+ ChildSessionID: op.childSessionID,+ PublicationGeneration: generation,+ Transport: TransportSfu,+ ConnectionID: att.connectionID,+ Usable: true,+ PhysicalActive: true,+ Resource: att.reservation.Edge,+ })+ var remainingParentPeerIDs []string+ if op.reason == DemandSfuBootstrap && oldPeer && old.Usable && old.PhysicalActive {+ remainingParentPeerIDs = []string{old.ParentPeerID}+ } else if op.reason != DemandDirectConvergence {+ start := op.cursor + 1+ if c.natPredictionEnabled {+ start = 0+ }+ for _, candidate := range op.candidates[min(start, len(op.candidates)):] {+ if c.natPredictionEnabled && !c.candidateOpportunityAvailable(op.childPeerID, candidate) {+ continue+ }+ if candidate.Tuple.Kind == UpstreamPeer {+ remainingParentPeerIDs = append(remainingParentPeerIDs, candidate.Tuple.ParentPeerID)+ }+ }+ remainingParentPeerIDs = append(remainingParentPeerIDs, op.deferredParentPeerIDs...)+ }+ if len(remainingParentPeerIDs) > 0 {+ // Ordering site §4.3 #27: dedupe preserving first occurrence.+ c.directContinuations.Set(op.childPeerID, &directContinuation{+ childSessionID: op.childSessionID,+ sfuConnectionID: att.connectionID,+ publicationGeneration: generation,+ parentPeerIDs: dedupeStrings(remainingParentPeerIDs),+ })+ } else {+ c.directContinuations.Delete(op.childPeerID)+ }+ }+ producerPeerIDs := []string{}+ if oldPeer {+ producerPeerIDs = append(producerPeerIDs, old.ParentPeerID)+ }+ if att.tuple.Kind == UpstreamPeer {+ producerPeerIDs = append(producerPeerIDs, att.tuple.ParentPeerID)+ } else {+ producerPeerIDs = append(producerPeerIDs, c.hostPeerID)+ }+ for _, producerPeerID := range dedupeStrings(producerPeerIDs) {+ for _, childPeerID := range c.childrenOf(producerPeerID) {+ delete(c.senderQualityObservations, childPeerID)+ c.senderQualityBaselines[childPeerID] = true+ }+ }+ c.requireSenderQualityBaseline(op.childPeerID, true)+ if sameParentRegeneration {+ c.senderQualityBaselines[op.childPeerID] = false+ } else {+ c.senderQualityBaselines[op.childPeerID] = op.reason == DemandQualityConvergence || op.reason == DemandRootConvergence+ }+ if sameParentRegeneration &&+ att.tuple.Kind == UpstreamPeer &&+ att.parentSessionID != "" &&+ att.senderQualityIdentity != "" {+ c.senderQualityRegenerationBlocks[op.childPeerID] = senderQualityIdentity{+ childSessionID: op.childSessionID,+ parentPeerID: att.tuple.ParentPeerID,+ parentSessionID: att.parentSessionID,+ connectionID: att.connectionID,+ senderIdentity: att.senderQualityIdentity,+ }+ } else {+ delete(c.senderQualityRegenerationBlocks, op.childPeerID)+ }+ c.revision = att.revision+ c.operation = nil+ c.pruneRetiringSfuAnchors()+ c.touchFacts()+ if createsHostRoot {+ c.stageRootConvergence(op.childPeerID)+ }+ if current, ok := c.participants.Get(op.childPeerID); ok {+ current.availabilityExhausted = false+ current.bootstrapFailureReported = false+ }+ if old != nil && old.Kind == UpstreamSfu && !c.hasSfuSubscribers() && c.hostPublication != nil {+ c.hostPublication = nil+ }+ if op.reason == DemandSfuBootstrap && att.tuple.Kind == UpstreamSfu {+ if demand, ok := c.participants.Get(op.demandPeerID); ok && demand.sessionIs(op.demandSessionID) {+ demand.sfuFirstAtNextRoute = true+ }+ c.sfuBootstrapIntent = nil+ } else if c.usableRoute(op.demandPeerID) {+ c.clearSfuBootstrapForDemand(op.demandPeerID)+ }+ c.assertGraph()+ c.debug("route-committed",+ "child", c.debugPeer(op.childPeerID),+ "route", c.debugTuple(att.tuple),+ "revision", att.revision)+ after := &resourceSet{}+ after.add(c.committedResources()...)+ released := []*Resource{}+ for _, resource := range before.list {+ if !after.has(resource) {+ released = append(released, resource)+ }+ }+ if att.reservation.Overlap != nil {+ released = append(released, att.reservation.Overlap)+ }+ return released+}++// advanceActiveRevision ports 4088.+func (c *Controller) advanceActiveRevision(op *operation) {+ if op.reason == DemandQualityConvergence && op.current != nil {+ producerPeerID := c.hostPeerID+ if op.current.tuple.Kind == UpstreamPeer {+ producerPeerID = op.current.tuple.ParentPeerID+ }+ regeneratingChild := op.current.tuple.Kind == UpstreamPeer && op.current.tuple.Regenerate+ for _, childPeerID := range c.childrenOf(producerPeerID) {+ if regeneratingChild && childPeerID == op.childPeerID {+ // A failed same-edge trial must not turn the retained sender into a+ // global baseline block. Its exact candidate opportunity owns retry+ // damping while the retained sender identity remains current.+ continue+ }+ delete(c.senderQualityObservations, childPeerID)+ c.senderQualityBaselines[childPeerID] = true+ }+ }+ c.revision = c.allocateRevision()+ op.baseRevision = c.revision+}++// blockAndClear ports 4112.+func (c *Controller) blockAndClear(op *operation, block bool, released *[]*Resource, revisionAdvanced bool) {+ child, _ := c.participants.Get(op.childPeerID)+ c.operation = nil+ retiredInvalid := false+ if block && child != nil {+ retiredInvalid = c.retireInvalidOperationEdge(op.childPeerID, released)+ }+ if retiredInvalid && !revisionAdvanced {+ c.revision = c.allocateRevision()+ }+ if retiredInvalid {+ c.touchFacts()+ }+ if !block || child == nil {+ return+ }+ child.availabilityExhausted = true+}++// replanRemaining ports 4164: re-plans the suffix from the cursor, forcing+// firstTuple into the first slot and appending restoreTuple when absent.+func (c *Controller) replanRemaining(op *operation, firstTuple, restoreTuple *CandidateTuple) {+ // Ordering site §4.4 #34.+ cursor := min(op.cursor, len(op.candidates))+ prefix := append([]CandidatePlan{}, op.candidates[:cursor]...)+ tuples := make([]CandidateTuple, 0, len(op.candidates)-cursor+2)+ for _, candidate := range op.candidates[cursor:] {+ tuples = append(tuples, candidate.Tuple)+ }+ if firstTuple != nil {+ if len(tuples) == 0 {+ tuples = append(tuples, *firstTuple)+ } else {+ tuples[0] = *firstTuple+ }+ }+ if restoreTuple != nil {+ restoreKey := tupleKey(*restoreTuple)+ if !slices.ContainsFunc(tuples, func(tuple CandidateTuple) bool { return tupleKey(tuple) == restoreKey }) {+ tuples = append(tuples, *restoreTuple)+ }+ }+ replanned := prefix+ for _, tuple := range tuples {+ plan := c.planCandidate(op.childPeerID, tuple)+ if plan != nil && c.operationCandidateValid(op, *plan, nil) {+ replanned = append(replanned, *plan)+ }+ }+ op.candidates = replanned+ op.builtAtFactVersion = c.factVersion+}++// operationSnapshot ports 4190: a deep copy plus the derived wakeAtMs;+// Current omits ConnectionAttempt when undefined.+func (c *Controller) operationSnapshot() *OperationSnapshot {+ op := c.operation+ if op == nil {+ return nil+ }+ candidates := make([]CandidatePlan, 0, len(op.candidates))+ for _, candidate := range op.candidates {+ candidates = append(candidates, cloneCandidatePlan(candidate))+ }+ snapshot := &OperationSnapshot{+ ChildPeerID: op.childPeerID,+ ChildSessionID: op.childSessionID,+ DemandPeerID: op.demandPeerID,+ Reason: op.reason,+ BaseRevision: op.baseRevision,+ FactVersion: op.builtAtFactVersion,+ Candidates: candidates,+ Cursor: op.cursor,+ DeadlineAtMs: op.deadlineAtMs,+ WakeAtMs: c.operationWakeAt(op),+ }+ if op.current != nil {+ current := &CurrentAttempt{+ Tuple: op.current.tuple,+ Revision: op.current.revision,+ ConnectionID: op.current.connectionID,+ }+ if op.current.connectionAttempt != nil {+ progress := *op.current.connectionAttempt+ current.ConnectionAttempt = &progress+ }+ snapshot.Current = current+ }+ return snapshot+}++// advanceExpiredDirectHeadStart ports 4208.+func (c *Controller) advanceExpiredDirectHeadStart(op *operation, nowMs int64, released *[]*Resource) bool {+ currentTuple := op.currentTuple()+ sfuIndex := c.foregroundSfuIndex(op)+ if currentTuple == nil || currentTuple.Kind != UpstreamPeer ||+ (op.current != nil && op.current.transportConnected) ||+ sfuIndex <= op.cursor {+ return false+ }+ headStartDeadlineAtMs := c.directHeadStartDeadlineAt(op)+ if nowMs < headStartDeadlineAtMs {+ return false+ }+ var activeCandidate any+ if op.current != nil {+ activeCandidate = c.debugTuple(op.current.tuple)+ c.noteRejection(op.demandPeerID, RejectionFirstFrameTimeout)+ c.consumeCurrentAvailabilityOpportunity(op)+ *released = append(*released, reservationResources(op.current.reservation)...)+ c.advanceActiveRevision(op)+ op.current = nil+ c.clearCandidateTiming(op.demandPeerID)+ }+ // Ordering site §4.4 #33: deferred parents keep candidate order.+ for _, candidate := range op.candidates[op.cursor:min(sfuIndex, len(op.candidates))] {+ if candidate.Tuple.Kind == UpstreamPeer {+ op.deferredParentPeerIDs = append(op.deferredParentPeerIDs, candidate.Tuple.ParentPeerID)+ }+ }+ op.cursor = sfuIndex+ c.debug("direct-head-start-expired",+ "child", c.debugPeer(op.childPeerID),+ "activeCandidate", activeCandidate,+ "cursor", op.cursor,+ "deadlineAtMs", headStartDeadlineAtMs,+ "observedAtMs", nowMs)+ return true+}++// operationWakeAt ports 4258.+func (c *Controller) operationWakeAt(op *operation) int64 {+ currentTuple := op.currentTuple()+ if currentTuple != nil && currentTuple.Kind == UpstreamPeer &&+ !(op.current != nil && op.current.transportConnected) &&+ c.foregroundSfuIndex(op) > op.cursor {+ return c.directHeadStartDeadlineAt(op)+ }+ if op.current != nil && op.current.tuple.Kind == UpstreamPeer &&+ !op.current.transportConnected &&+ c.peerCandidateHasSuccessor(op) {+ return min(op.deadlineAtMs, op.current.startedAtMs+c.directHeadStartMs())+ }+ return op.deadlineAtMs+}++// peerCandidateHasSuccessor ports 4281.+func (c *Controller) peerCandidateHasSuccessor(op *operation) bool {+ return op.cursor+1 < len(op.candidates) || c.foregroundSfuIndex(op) > op.cursor+}++// directHeadStartDeadlineAt ports 4290.+func (c *Controller) directHeadStartDeadlineAt(op *operation) int64 {+ return op.deadlineAtMs - c.operationTimeoutMs + c.directHeadStartMs()+}++// foregroundSfuIndex ports 4299: the index of the first SFU candidate at or+// after the cursor, the candidate count when a bootstrap carrier exists, -1+// otherwise (and always -1 for background convergence).+func (c *Controller) foregroundSfuIndex(op *operation) int {+ if isBackgroundConvergence(op.reason) {+ return -1+ }+ for index := max(op.cursor, 0); index < len(op.candidates); index++ {+ if op.candidates[index].Tuple.Kind == UpstreamSfu {+ return index+ }+ }+ if c.bootstrapCandidateAvailable(op.demandPeerID) {+ return len(op.candidates)+ }+ return -1+}++// promoteNextDirectWithinHeadStart ports 4314 (§4.4 #32).+func (c *Controller) promoteNextDirectWithinHeadStart(op *operation, nowMs int64) {+ sfuIndex := c.foregroundSfuIndex(op)+ if sfuIndex != op.cursor+1 || nowMs >= c.directHeadStartDeadlineAt(op) {+ return+ }+ nextDirectIndex := -1+ for index := sfuIndex + 1; index < len(op.candidates); index++ {+ if op.candidates[index].Tuple.Kind == UpstreamPeer {+ nextDirectIndex = index+ break+ }+ }+ if nextDirectIndex < 0 {+ return+ }+ nextDirect := op.candidates[nextDirectIndex]+ op.candidates = slices.Delete(op.candidates, nextDirectIndex, nextDirectIndex+1)+ op.candidates = slices.Insert(op.candidates, sfuIndex, nextDirect)+}++// guardMatches ports 4338.+func (c *Controller) guardMatches(guard CandidateGuard, op *operation, att *attempt) bool {+ return guard.ChildPeerID == op.childPeerID && guard.ChildSessionID == op.childSessionID &&+ guard.Revision == att.revision && guard.ConnectionID == att.connectionID+}++// cursorGuardMatches ports 4343.+func (c *Controller) cursorGuardMatches(guard CandidateCursorGuard, op *operation) bool {+ plan := op.planAt(op.cursor)+ return plan != nil &&+ guard.ChildPeerID == op.childPeerID &&+ guard.ChildSessionID == op.childSessionID && guard.BaseRevision == op.baseRevision &&+ guard.FactVersion == op.builtAtFactVersion && guard.Cursor == op.cursor &&+ candidatePlanEquals(guard.Plan, *plan)+}++// selectNextChild ports 3451: five priority buckets, first-occurrence+// dedupe, then a STABLE sort by started attempts (§4.5 #42).+func (c *Controller) selectNextChild() string {+ viewers := c.availableViewers(false)+ departedParents := []string{}+ unusable := []string{}+ staleSfu := []string{}+ withoutEdge := []string{}+ for _, viewer := range viewers {+ edge, _ := c.upstreamByViewer.Get(viewer.peerID)+ if edge != nil && edge.Kind == UpstreamPeer {+ if parent, ok := c.participants.Get(edge.ParentPeerID); ok && parent.departureConfirmed {+ departedParents = append(departedParents, viewer.peerID)+ }+ }+ if edge != nil && !edge.Usable {+ unusable = append(unusable, viewer.peerID)+ }+ if edge != nil && edge.Kind == UpstreamSfu &&+ (c.hostPublication == nil || !c.hostPublication.Usable || c.hostPublication.Generation != edge.PublicationGeneration) {+ staleSfu = append(staleSfu, viewer.peerID)+ }+ if edge == nil {+ withoutEdge = append(withoutEdge, viewer.peerID)+ }+ }+ overflow := c.overflowChildren()+ candidates := dedupeStrings(slices.Concat(departedParents, overflow, unusable, staleSfu, withoutEdge))+ sort.SliceStable(candidates, func(i, j int) bool {+ return c.viewerAttemptsStarted(candidates[i]) < c.viewerAttemptsStarted(candidates[j])+ })+ if len(candidates) == 0 {+ return ""+ }+ return candidates[0]+}++// directContinuationPick is the selectDirectContinuation result.+type directContinuationPick struct {+ childPeerID string+ plan CandidatePlan+}++// selectDirectContinuation ports 3477 (§4.3 #23-25): a stable sort over+// the round-robin map order, then the first valid parent per child.+func (c *Controller) selectDirectContinuation() *directContinuationPick {+ type entry struct {+ childPeerID string+ continuation *directContinuation+ }+ entries := []entry{}+ for childPeerID, continuation := range c.directContinuations.All() {+ entries = append(entries, entry{childPeerID, continuation})+ }+ sort.SliceStable(entries, func(i, j int) bool {+ return c.viewerAttemptsStarted(entries[i].childPeerID) < c.viewerAttemptsStarted(entries[j].childPeerID)+ })+ for _, current := range entries {+ childPeerID, continuation := current.childPeerID, current.continuation+ child, _ := c.participants.Get(childPeerID)+ edge, _ := c.upstreamByViewer.Get(childPeerID)+ if child == nil || child.sessionID == "" ||+ child.departureConfirmed ||+ !child.sessionIs(continuation.childSessionID) ||+ edge == nil || edge.Kind != UpstreamSfu ||+ !edge.Usable ||+ !edge.PhysicalActive ||+ edge.ConnectionID != continuation.sfuConnectionID ||+ edge.PublicationGeneration != continuation.publicationGeneration ||+ c.hostPublication == nil || !c.hostPublication.Usable ||+ !c.hostPublication.PhysicalActive ||+ c.hostPublication.Generation != continuation.publicationGeneration {+ c.directContinuations.Delete(childPeerID)+ continue+ }+ parents := append([]string{}, continuation.parentPeerIDs...)+ sort.SliceStable(parents, func(i, j int) bool {+ return c.peerAttemptsStarted(childPeerID, parents[i]) < c.peerAttemptsStarted(childPeerID, parents[j])+ })+ for _, parentPeerID := range parents {+ tuple := CandidateTuple{Kind: UpstreamPeer, ParentPeerID: parentPeerID, Transport: TransportDirect}+ plan := c.planCandidate(childPeerID, tuple)+ if plan != nil &&+ plan.EndpointTransition.Kind != TransitionBoundedGap &&+ c.candidateValid(childPeerID, *plan, nil) &&+ (!c.natPredictionEnabled || c.candidateOpportunityAvailable(childPeerID, *plan)) {+ return &directContinuationPick{childPeerID: childPeerID, plan: *plan}+ }+ }+ if len(continuation.parentPeerIDs) == 0 {+ c.directContinuations.Delete(childPeerID)+ c.debug("direct-convergence-complete", "child", c.debugPeer(childPeerID), "route", "sfu")+ }+ }+ return nil+}++// consumeDirectContinuationCandidate ports 3564: removes the tried parent+// from the retry order (re-appending it while NAT attempts remain) and+// moves the continuation to the tail of the round-robin (§4.3 #24, #26).+func (c *Controller) consumeDirectContinuationCandidate(op *operation) {+ tuple := op.currentTuple()+ if op.reason != DemandDirectConvergence || tuple == nil || tuple.Kind != UpstreamPeer {+ return+ }+ continuation, ok := c.directContinuations.Get(op.childPeerID)+ if !ok {+ return+ }+ index := slices.Index(continuation.parentPeerIDs, tuple.ParentPeerID)+ if index < 0 {+ return+ }+ continuation.parentPeerIDs = slices.Delete(continuation.parentPeerIDs, index, index+1)+ plan := op.planAt(op.cursor)+ if op.current != nil && op.current.connectionAttempt != nil &&+ plan != nil &&+ c.candidateOpportunityAvailable(op.childPeerID, *plan) {+ continuation.parentPeerIDs = append(continuation.parentPeerIDs, tuple.ParentPeerID)+ }+ c.debug("direct-convergence-advanced",+ "child", c.debugPeer(op.childPeerID),+ "parent", c.debugPeer(tuple.ParentPeerID),+ "remaining", len(continuation.parentPeerIDs))+ if len(continuation.parentPeerIDs) == 0 {+ c.directContinuations.Delete(op.childPeerID)+ } else {+ // TS delete + set: the entry moves to the tail (round-robin state).+ c.directContinuations.MoveToBack(op.childPeerID, continuation)+ }+}diff --git a/internal/server/route/opportunities.go b/internal/server/route/opportunities.gonew file mode 100644index 00000000..3cc551bd--- /dev/null+++ b/internal/server/route/opportunities.go@@ -0,0 +1,270 @@+package route++import (+ "strings"++ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// candidateOpportunityBase ports 2900: the NUL-joined ledger key. A session+// change erases the key because the session is part of it.+func (c *Controller) candidateOpportunityBase(childPeerID string, plan CandidatePlan) string {+ childSessionID := ""+ if child, ok := c.participants.Get(childPeerID); ok {+ childSessionID = child.sessionID+ }+ if plan.Tuple.Kind == UpstreamPeer {+ parentSessionID := ""+ if parent, ok := c.participants.Get(plan.Tuple.ParentPeerID); ok {+ parentSessionID = parent.sessionID+ }+ return tupleKey(plan.Tuple) + "\x00" + childSessionID + "\x00" + parentSessionID+ }+ hostSessionID := ""+ if host, ok := c.participants.Get(c.hostPeerID); ok {+ hostSessionID = host.sessionID+ }+ return sfuOpportunityPrefix + childSessionID + "\x00" + hostSessionID+}++// candidateOpportunityAvailable ports 2823.+func (c *Controller) candidateOpportunityAvailable(childPeerID string, plan CandidatePlan) bool {+ child, _ := c.participants.Get(childPeerID)+ if child == nil {+ return true+ }+ consumed, ok := child.consumedCandidateOpportunities.Get(c.candidateOpportunityBase(childPeerID, plan))+ return !ok ||+ endpointTransitionRank(plan.EndpointTransition) < consumed.rank ||+ (c.natPredictionEnabled &&+ plan.Tuple.Kind == UpstreamPeer &&+ !consumed.exhausted &&+ consumed.startedAttempts < maxNatConnectionAttempts)+}++// startCandidateOpportunity ports 2842: counts one NAT attempt for a peer+// candidate of an availability or direct-convergence operation.+func (c *Controller) startCandidateOpportunity(op *operation, plan CandidatePlan) *ConnectionAttemptProgress {+ if !c.natPredictionEnabled ||+ plan.Tuple.Kind != UpstreamPeer ||+ (!isAvailabilityOperation(op.reason) && op.reason != DemandDirectConvergence) {+ return nil+ }+ child, _ := c.participants.Get(op.childPeerID)+ opportunities := &child.consumedCandidateOpportunities+ key := c.candidateOpportunityBase(op.childPeerID, plan)+ rank := endpointTransitionRank(plan.EndpointTransition)+ previous, ok := opportunities.Get(key)+ startedAttempts := 1+ if ok && previous.rank <= rank {+ startedAttempts = previous.startedAttempts + 1+ }+ newRank := rank+ if ok {+ newRank = min(previous.rank, rank)+ }+ // The new entry has no `exhausted` (2859-2862).+ opportunities.Set(key, candidateOpportunity{rank: newRank, startedAttempts: startedAttempts})+ op.peerAttemptStarted = true+ return &ConnectionAttemptProgress{Current: startedAttempts, Total: maxNatConnectionAttempts}+}++// peerAttemptsStarted ports 2867.+func (c *Controller) peerAttemptsStarted(childPeerID, parentPeerID string) int {+ if !c.natPredictionEnabled {+ return 0+ }+ plan := c.planCandidate(childPeerID, CandidateTuple{Kind: UpstreamPeer, ParentPeerID: parentPeerID, Transport: TransportDirect})+ if plan == nil {+ return 0+ }+ child, _ := c.participants.Get(childPeerID)+ if child == nil {+ return 0+ }+ opportunity, ok := child.consumedCandidateOpportunities.Get(c.candidateOpportunityBase(childPeerID, *plan))+ if ok && opportunity.rank <= endpointTransitionRank(plan.EndpointTransition) {+ return opportunity.startedAttempts+ }+ return 0+}++// viewerAttemptsStarted ports 2880: the sum over every peer key.+func (c *Controller) viewerAttemptsStarted(peerID string) int {+ if !c.natPredictionEnabled {+ return 0+ }+ current, _ := c.participants.Get(peerID)+ if current == nil {+ return 0+ }+ started := 0+ for key, opportunity := range current.consumedCandidateOpportunities.All() {+ if strings.HasPrefix(key, "peer:") {+ started += opportunity.startedAttempts+ }+ }+ return started+}++// hasRemainingNatOpportunity ports 2890.+func (c *Controller) hasRemainingNatOpportunity(op *operation) bool {+ if !isAvailabilityOperation(op.reason) || !op.peerAttemptStarted {+ return false+ }+ for _, plan := range c.buildCandidates(op.childPeerID, false) {+ if plan.Tuple.Kind == UpstreamPeer {+ return true+ }+ }+ return false+}++// consumeCandidateOpportunity ports 2916: exhausts the key at its best rank.+func (c *Controller) consumeCandidateOpportunity(childPeerID string, plan CandidatePlan) {+ child, _ := c.participants.Get(childPeerID)+ if child == nil {+ return+ }+ key := c.candidateOpportunityBase(childPeerID, plan)+ rank := endpointTransitionRank(plan.EndpointTransition)+ previous, ok := child.consumedCandidateOpportunities.Get(key)+ entry := candidateOpportunity{rank: rank, exhausted: true}+ if ok {+ entry.rank = min(previous.rank, rank)+ entry.startedAttempts = previous.startedAttempts+ }+ child.consumedCandidateOpportunities.Set(key, entry)+}++// qualityCandidateOpportunityAvailable ports 2934.+func (c *Controller) qualityCandidateOpportunityAvailable(childPeerID string, plan CandidatePlan) bool {+ observation := c.senderQualityObservations[childPeerID]+ if observation == nil {+ return true+ }+ consumed, ok := observation.consumedQualityCandidates.Get(c.candidateOpportunityBase(childPeerID, plan))+ return !ok || endpointTransitionRank(plan.EndpointTransition) < consumed+}++// consumeQualityCandidateOpportunity ports 2949.+func (c *Controller) consumeQualityCandidateOpportunity(op *operation, plan *CandidatePlan) {+ if op.reason != DemandQualityConvergence || plan == nil {+ return+ }+ observation := c.currentQualityOperationObservation(op)+ if observation == nil {+ return+ }+ consumeOpportunity(observation.consumedQualityCandidates,+ c.candidateOpportunityBase(op.childPeerID, *plan),+ endpointTransitionRank(plan.EndpointTransition))+}++// consumeQualityOperationCandidates ports 2967.+func (c *Controller) consumeQualityOperationCandidates(op *operation) {+ for index := range op.candidates {+ candidate := op.candidates[index]+ c.consumeQualityCandidateOpportunity(op, &candidate)+ }+}++// consumeActiveEdgeOpportunity ports 2975: an invalidated active edge+// exhausts its exact tuple at rank 0.+func (c *Controller) consumeActiveEdgeOpportunity(child *participant, edge *CommittedEdge) {+ if edge.Kind == UpstreamPeer {+ key := "peer:" + edge.ParentPeerID + "\x00" + child.sessionID + "\x00" + edge.ParentSessionID+ previous, _ := child.consumedCandidateOpportunities.Get(key)+ child.consumedCandidateOpportunities.Set(key, candidateOpportunity{+ rank: 0,+ startedAttempts: previous.startedAttempts,+ exhausted: true,+ })+ return+ }+ c.consumeCandidateOpportunity(child.peerID, CandidatePlan{+ Tuple: CandidateTuple{Kind: UpstreamSfu, Publication: PublicationReuse},+ EndpointTransition: EndpointTransition{Kind: TransitionNone},+ })+}++// consumeAvailabilityOperation ports 2993.+func (c *Controller) consumeAvailabilityOperation(op *operation) {+ if !isAvailabilityOperation(op.reason) {+ return+ }+ for _, plan := range op.candidates {+ if op.peerAttemptStarted && plan.Tuple.Kind == UpstreamPeer {+ continue+ }+ c.consumeCandidateOpportunity(op.childPeerID, plan)+ }+}++// consumeCurrentAvailabilityOpportunity ports 3003.+func (c *Controller) consumeCurrentAvailabilityOpportunity(op *operation) {+ if !isAvailabilityOperation(op.reason) {+ return+ }+ plan := op.planAt(op.cursor)+ if op.current != nil && op.current.connectionAttempt != nil && plan != nil && plan.Tuple.Kind == UpstreamPeer {+ return+ }+ if plan != nil {+ c.consumeCandidateOpportunity(op.childPeerID, *plan)+ }+}++// clearOpportunitiesForSessionChange ports 4561 (§4.1 #5, §4.5 #47): keys+// are snapshotted before deletion, which JS defines as safe in place.+func (c *Controller) clearOpportunitiesForSessionChange(peerID string, role protocol.Role) {+ if current, ok := c.participants.Get(peerID); ok {+ current.consumedCandidateOpportunities.Clear()+ current.availabilityExhausted = false+ current.bootstrapFailureReported = false+ }+ parentPrefix := "peer:" + peerID + "\x00"+ for _, child := range c.participants.Values() {+ for _, key := range child.consumedCandidateOpportunities.Keys() {+ if strings.HasPrefix(key, parentPrefix) ||+ (role == protocol.RoleHost && strings.HasPrefix(key, sfuOpportunityPrefix)) {+ child.consumedCandidateOpportunities.Delete(key)+ }+ }+ if role == protocol.RoleHost {+ child.bootstrapFailureReported = false+ }+ }+ if role == protocol.RoleHost {+ c.consumedSfuBootstrapOpportunities.Clear()+ return+ }+ carrierPrefix := peerID + "\x00"+ for _, key := range c.consumedSfuBootstrapOpportunities.Keys() {+ if strings.HasPrefix(key, carrierPrefix) {+ c.consumedSfuBootstrapOpportunities.Delete(key)+ }+ }+}++// clearSfuCandidateOpportunities ports 4597.+func (c *Controller) clearSfuCandidateOpportunities() {+ for _, current := range c.participants.Values() {+ for _, key := range current.consumedCandidateOpportunities.Keys() {+ if strings.HasPrefix(key, sfuOpportunityPrefix) {+ current.consumedCandidateOpportunities.Delete(key)+ }+ }+ current.bootstrapFailureReported = false+ }+ c.consumedSfuBootstrapOpportunities.Clear()+}++// consumeOpportunity ports 5011: keeps the best (lowest) rank.+func consumeOpportunity(consumed *ordered.Map[string, int], base string, rank int) {+ previous, ok := consumed.Get(base)+ if !ok || rank < previous {+ consumed.Set(base, rank)+ }+}diff --git a/internal/server/route/quality.go b/internal/server/route/quality.gonew file mode 100644index 00000000..52b27e03--- /dev/null+++ b/internal/server/route/quality.go@@ -0,0 +1,875 @@+package route++import (+ "sort"++ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+)++// ObserveQualityEvidence aggregates one receiver-side window onto the+// child's committed edge: rejected on any mismatch, accepted when consumed+// without aggregation, observed when aggregated.+func (c *Controller) ObserveQualityEvidence(input RouteQualityEvidenceInput) RouteQualityEvidenceResult {+ if c.paused ||+ input.RouteRevision != c.revision ||+ !isSafeInteger(input.PresentationEpoch) ||+ input.PresentationEpoch < 0 ||+ !isSafeInteger(input.WindowMs) ||+ input.WindowMs <= 0 ||+ !isSafeInteger(input.AcceptedAtMs) ||+ input.AcceptedAtMs < 0 {+ return QualityEvidenceRejected+ }+ child, _ := c.participants.Get(input.ChildPeerID)+ edge, _ := c.upstreamByViewer.Get(input.ChildPeerID)+ if child == nil ||+ !child.sessionIs(input.ChildSessionID) ||+ edge == nil ||+ !edge.Usable ||+ !edge.PhysicalActive ||+ edge.ChildSessionID != input.ChildSessionID ||+ edge.ConnectionID != input.ConnectionID ||+ !qualityUpstreamMatches(edge, input.Upstream) ||+ !c.sourceUsableForQuality(edge) {+ return QualityEvidenceRejected+ }++ upstreamPeerID := ""+ if input.Upstream.Kind == UpstreamPeer {+ upstreamPeerID = input.Upstream.PeerID+ }+ observation := c.qualityObservations[input.ChildPeerID]+ sameEdgeObservation := observation != nil &&+ observation.childSessionID == input.ChildSessionID &&+ observation.upstreamKind == input.Upstream.Kind &&+ observation.upstreamPeerID == upstreamPeerID &&+ observation.connectionID == input.ConnectionID+ if sameEdgeObservation && input.PresentationEpoch < observation.presentationEpoch {+ return QualityEvidenceRejected+ }+ if !sameEdgeObservation || observation.presentationEpoch != input.PresentationEpoch {+ observation = &routeQualityObservation{+ childSessionID: input.ChildSessionID,+ upstreamKind: input.Upstream.Kind,+ upstreamPeerID: upstreamPeerID,+ connectionID: input.ConnectionID,+ presentationEpoch: input.PresentationEpoch,+ lastAcceptedAtMs: input.AcceptedAtMs,+ }+ c.qualityObservations[input.ChildPeerID] = observation+ }++ metrics := input.Metrics+ if metrics.FramesDecodedDelta == nil || *metrics.FramesDecodedDelta <= 0 {+ return QualityEvidenceAccepted+ }+ hadFreshDecodedProgress := observation.lastDecodedProgressAtMs != nil &&+ input.AcceptedAtMs < *observation.lastDecodedProgressAtMs+qualityEvidenceExpiryMs+ decodedAt := input.AcceptedAtMs+ observation.lastDecodedProgressAtMs = &decodedAt+ if !hadFreshDecodedProgress && edge.Kind == UpstreamSfu {+ c.touchFacts()+ }+ if metrics.FreezeCountDelta == nil ||+ metrics.FreezeDurationMsDelta == nil ||+ metrics.PauseCountDelta == nil ||+ metrics.PauseDurationMsDelta == nil {+ return QualityEvidenceAccepted+ }+ observation.lastAcceptedAtMs = input.AcceptedAtMs+ if _, pending := c.qualityBaselinesPending[input.ChildPeerID]; pending {+ delete(c.qualityBaselinesPending, input.ChildPeerID)+ return QualityEvidenceAccepted+ }++ observation.eligibleWindows = safeAdd(observation.eligibleWindows, 1)+ observation.eligibleDurationMs = safeAdd(observation.eligibleDurationMs, float64(input.WindowMs))+ if *metrics.FreezeCountDelta > 0 {+ observation.freezeWindows = safeAdd(observation.freezeWindows, 1)+ }+ observation.freezeCount = safeAdd(observation.freezeCount, float64(*metrics.FreezeCountDelta))+ observation.freezeDurationMs = safeAdd(observation.freezeDurationMs, float64(*metrics.FreezeDurationMsDelta))+ observation.pauseCount = safeAdd(observation.pauseCount, float64(*metrics.PauseCountDelta))+ observation.pauseDurationMs = safeAdd(observation.pauseDurationMs, float64(*metrics.PauseDurationMsDelta))+ return QualityEvidenceObserved+}++// senderAccepted is the `accepted: true, committed: false` literal.+func (c *Controller) senderAccepted(released []*Resource) SenderQualityEvidenceResult {+ return SettleResult{+ Accepted: true,+ Committed: false,+ FailedPeerIDs: []string{},+ ActiveRevision: c.revision,+ Released: released,+ }+}++// senderRejected is the `rejected()` literal.+func (c *Controller) senderRejected() SenderQualityEvidenceResult {+ return SettleResult{+ Accepted: false,+ Committed: false,+ FailedPeerIDs: []string{},+ ActiveRevision: c.revision,+ Released: []*Resource{},+ }+}++// ObserveSenderQualityEvidence records a parent's health sample for a child,+// settling the live quality/root candidate when the sample names it; a nil+// commitReservation always commits. Requires QualityConvergenceEnabled.+func (c *Controller) ObserveSenderQualityEvidence(input SenderQualityEvidenceInput, commitReservation func(CandidateReservation) bool) SenderQualityEvidenceResult {+ if commitReservation == nil {+ commitReservation = func(CandidateReservation) bool { return true }+ }+ if !c.qualityConvergenceEnabled ||+ c.paused ||+ !isSafeInteger(input.AcceptedAtMs) ||+ input.AcceptedAtMs < 0 {+ return c.senderRejected()+ }+ parent, _ := c.participants.Get(input.ParentPeerID)+ child, _ := c.participants.Get(input.ChildPeerID)+ if parent == nil || parent.sessionID == "" ||+ !parent.sessionIs(input.ParentSessionID) ||+ child == nil || child.sessionID == "" ||+ child.departureConfirmed ||+ parent.departureConfirmed {+ return c.senderRejected()+ }++ op := c.operation+ var att *attempt+ if op != nil {+ att = op.current+ }+ if op != nil &&+ (op.reason == DemandRootConvergence || op.reason == DemandQualityConvergence) &&+ att != nil && att.tuple.Kind == UpstreamPeer &&+ op.childPeerID == input.ChildPeerID &&+ op.childSessionID == child.sessionID &&+ att.tuple.ParentPeerID == input.ParentPeerID &&+ att.parentSessionID == input.ParentSessionID &&+ att.connectionID == input.ConnectionID &&+ att.revision == input.RouteRevision {+ senderIdentity := ""+ if input.SenderIdentity != nil {+ senderIdentity = *input.SenderIdentity+ }+ return c.settleCandidateQuality(op, att, input.State, input.AcceptedAtMs, senderIdentity, input.SampleTimestampMs, commitReservation)+ }++ edge, _ := c.upstreamByViewer.Get(input.ChildPeerID)+ if input.RouteRevision != c.revision ||+ edge == nil || edge.Kind != UpstreamPeer ||+ !edge.Usable ||+ !edge.PhysicalActive ||+ edge.ParentPeerID != input.ParentPeerID ||+ edge.ParentSessionID != input.ParentSessionID ||+ edge.ChildSessionID != child.sessionID ||+ edge.ConnectionID != input.ConnectionID {+ return c.senderRejected()+ }+ previous := c.senderQualityObservations[input.ChildPeerID]+ sameConnectionIdentity := previous != nil &&+ previous.childSessionID == child.sessionID &&+ previous.parentPeerID == input.ParentPeerID &&+ previous.parentSessionID == input.ParentSessionID &&+ previous.connectionID == input.ConnectionID+ if input.State == SenderQualityUnknown {+ if previous != nil && previous.state != SenderQualityUnknown {+ c.debug("sender-quality-reset",+ "parent", c.debugPeer(input.ParentPeerID),+ "child", c.debugPeer(input.ChildPeerID))+ }+ if previous != nil && sameConnectionIdentity {+ // `{...previous}` keeps the same consumed ledger pointer.+ reset := *previous+ reset.state = SenderQualityUnknown+ reset.consecutiveDegradedWindows = 0+ reset.lastAcceptedAtMs = input.AcceptedAtMs+ c.senderQualityObservations[input.ChildPeerID] = &reset+ } else {+ delete(c.senderQualityObservations, input.ChildPeerID)+ }+ return c.senderAccepted([]*Resource{})+ }+ if input.SenderIdentity == nil || *input.SenderIdentity == "" || input.SampleTimestampMs == nil {+ return c.senderRejected()+ }+ senderIdentity := *input.SenderIdentity+ sampleTimestampMs := *input.SampleTimestampMs+ sameSenderIdentity := sameConnectionIdentity && previous.senderIdentity == senderIdentity+ if sameSenderIdentity && sampleTimestampMs <= previous.lastSampleTimestampMs {+ return c.senderAccepted([]*Resource{})+ }+ if block, ok := c.senderQualityRegenerationBlocks[input.ChildPeerID]; ok &&+ !senderQualityRegenerationBlockMatches(block, child.sessionID, input, senderIdentity) {+ // A new connection or sender identity is a new generation. Do not carry+ // a same-edge regeneration latch across that identity fence.+ delete(c.senderQualityRegenerationBlocks, input.ChildPeerID)+ }+ if input.State == SenderQualityHealthy {+ delete(c.senderQualityRegenerationBlocks, input.ChildPeerID)+ }+ sameFreshSenderIdentity := sameSenderIdentity &&+ input.AcceptedAtMs < previous.lastAcceptedAtMs+qualityEvidenceExpiryMs+ if input.State == SenderQualityHealthy {+ delete(c.senderQualityBaselines, input.ChildPeerID)+ }+ var consecutiveDegradedWindows int64+ if input.State == SenderQualityDegraded {+ consecutiveDegradedWindows = 1+ if sameFreshSenderIdentity && previous.state == SenderQualityDegraded {+ consecutiveDegradedWindows = safeAdd(previous.consecutiveDegradedWindows, 1)+ }+ }+ consumed := &ordered.Map[string, int]{}+ if sameSenderIdentity && input.State != SenderQualityHealthy {+ consumed = previous.consumedQualityCandidates+ }+ c.senderQualityObservations[input.ChildPeerID] = &senderQualityObservation{+ childSessionID: child.sessionID,+ parentPeerID: input.ParentPeerID,+ parentSessionID: input.ParentSessionID,+ connectionID: input.ConnectionID,+ senderIdentity: senderIdentity,+ state: input.State,+ consecutiveDegradedWindows: consecutiveDegradedWindows,+ lastSampleTimestampMs: sampleTimestampMs,+ lastAcceptedAtMs: input.AcceptedAtMs,+ consumedQualityCandidates: consumed,+ }+ if !sameFreshSenderIdentity ||+ previous.state != input.State ||+ consecutiveDegradedWindows == persistentDegradedWindows {+ c.debug("sender-quality-observed",+ "parent", c.debugPeer(input.ParentPeerID),+ "child", c.debugPeer(input.ChildPeerID),+ "state", input.State,+ "consecutiveDegradedWindows", consecutiveDegradedWindows)+ }+ if input.State == SenderQualityHealthy &&+ op != nil && op.reason == DemandQualityConvergence &&+ op.childPeerID == input.ChildPeerID {+ released := c.abortOperation(&input.AcceptedAtMs, RejectionAborted)+ return c.senderAccepted(released)+ }+ return c.senderAccepted([]*Resource{})+}++// senderQualityRegenerationBlockMatches ports 4985.+func senderQualityRegenerationBlockMatches(block senderQualityIdentity, childSessionID string, input SenderQualityEvidenceInput, senderIdentity string) bool {+ return block.childSessionID == childSessionID &&+ block.parentPeerID == input.ParentPeerID &&+ block.parentSessionID == input.ParentSessionID &&+ block.connectionID == input.ConnectionID &&+ block.senderIdentity == senderIdentity+}++// ObserveSfuPublisherQualityEvidence records a Host->SFU ingress sample,+// settling a live sfu/reuse quality candidate; a nil commitReservation+// always commits. Requires QualityConvergenceEnabled. Unlike the other two+// observers it validates no numbers (TS asymmetry, map R13).+func (c *Controller) ObserveSfuPublisherQualityEvidence(input SfuPublisherQualityEvidenceInput, commitReservation func(CandidateReservation) bool) SenderQualityEvidenceResult {+ if commitReservation == nil {+ commitReservation = func(CandidateReservation) bool { return true }+ }+ host, _ := c.participants.Get(c.hostPeerID)+ if !c.qualityConvergenceEnabled ||+ c.paused ||+ input.HostPeerID != c.hostPeerID ||+ host == nil || host.sessionID == "" ||+ !host.sessionIs(input.HostSessionID) {+ return c.senderRejected()+ }+ op := c.operation+ var att *attempt+ if op != nil {+ att = op.current+ }+ if op != nil && op.reason == DemandQualityConvergence &&+ att != nil && att.tuple.Kind == UpstreamSfu &&+ att.hostSessionID == input.HostSessionID &&+ att.publicationGeneration == input.PublicationGeneration &&+ att.revision == input.RouteRevision {+ return c.settleCandidateQuality(op, att, input.State, input.AcceptedAtMs, input.PublicationGeneration, input.SampleTimestampMs, commitReservation)+ }+ if input.RouteRevision != c.revision ||+ c.hostPublication == nil || !c.hostPublication.Usable ||+ !c.hostPublication.PhysicalActive ||+ c.hostPublication.HostSessionID != input.HostSessionID ||+ c.hostPublication.Generation != input.PublicationGeneration {+ return c.senderRejected()+ }+ if input.State == SenderQualityUnknown {+ if c.sfuPublisherQualityObservation != nil {+ c.debug("sfu-publisher-quality-reset")+ }+ c.sfuPublisherQualityObservation = nil+ return c.senderAccepted([]*Resource{})+ }+ if input.SampleTimestampMs == nil {+ return c.senderRejected()+ }+ sampleTimestampMs := *input.SampleTimestampMs+ previous := c.sfuPublisherQualityObservation+ samePublication := previous != nil &&+ previous.hostSessionID == input.HostSessionID &&+ previous.publicationGeneration == input.PublicationGeneration+ if samePublication && sampleTimestampMs <= previous.lastSampleTimestampMs {+ return c.senderAccepted([]*Resource{})+ }+ sameFreshPublication := samePublication &&+ input.AcceptedAtMs < previous.lastAcceptedAtMs+qualityEvidenceExpiryMs+ var consecutiveHealthyWindows int64+ if input.State == SenderQualityHealthy {+ consecutiveHealthyWindows = 1+ if sameFreshPublication && previous.state == SenderQualityHealthy {+ consecutiveHealthyWindows = safeAdd(previous.consecutiveHealthyWindows, 1)+ }+ }+ wasPersistentlyHealthy := sameFreshPublication &&+ previous.state == SenderQualityHealthy &&+ previous.consecutiveHealthyWindows >= persistentDegradedWindows+ c.sfuPublisherQualityObservation = &sfuPublisherQualityObservation{+ hostSessionID: input.HostSessionID,+ publicationGeneration: input.PublicationGeneration,+ state: input.State,+ consecutiveHealthyWindows: consecutiveHealthyWindows,+ lastSampleTimestampMs: sampleTimestampMs,+ lastAcceptedAtMs: input.AcceptedAtMs,+ }+ if !samePublication ||+ previous.state != input.State ||+ consecutiveHealthyWindows == persistentDegradedWindows {+ c.debug("sfu-publisher-quality-observed",+ "state", input.State,+ "consecutiveHealthyWindows", consecutiveHealthyWindows)+ }+ if input.State == SenderQualityHealthy &&+ consecutiveHealthyWindows >= persistentDegradedWindows &&+ !wasPersistentlyHealthy {+ c.touchFacts()+ }+ if op != nil && op.reason == DemandQualityConvergence &&+ att != nil && att.tuple.Kind == UpstreamSfu &&+ att.tuple.Publication == PublicationReuse &&+ att.hostSessionID == input.HostSessionID &&+ att.publicationGeneration == input.PublicationGeneration &&+ att.mediaReady {+ guard := CandidateGuard{+ ChildPeerID: op.childPeerID,+ ChildSessionID: op.childSessionID,+ Revision: att.revision,+ ConnectionID: att.connectionID,+ }+ var settled *SettleResult+ if input.State == SenderQualityDegraded {+ result := c.CandidateFailed(guard, input.AcceptedAtMs)+ settled = &result+ } else if consecutiveHealthyWindows >= persistentDegradedWindows {+ result := c.CandidateReady(guard, input.AcceptedAtMs, commitReservation, CandidateProof{})+ settled = &result+ }+ if settled != nil {+ return SettleResult{+ Accepted: settled.Accepted,+ Committed: settled.Committed,+ FailedPeerIDs: settled.FailedPeerIDs,+ ActiveRevision: settled.ActiveRevision,+ Released: settled.Released,+ }+ }+ }+ return c.senderAccepted([]*Resource{})+}++// settleCandidateQuality ports 1428: folds a sender sample into the live+// candidate and fails or commits it. senderIdentity "" is the TS null.+func (c *Controller) settleCandidateQuality(op *operation, att *attempt, state SenderQualityState, acceptedAtMs int64, senderIdentity string, sampleTimestampMs *int64, commitReservation func(CandidateReservation) bool) SenderQualityEvidenceResult {+ if att.senderQualityState != state {+ c.debug("candidate-quality-observed",+ "child", c.debugPeer(op.childPeerID),+ "candidate", c.debugTuple(att.tuple),+ "state", state)+ }+ if state == SenderQualityUnknown {+ att.senderQualityState = ""+ att.senderQualityAcceptedAtMs = nil+ att.senderQualityConsecutiveHealthyWindows = 0+ att.senderQualityConsecutiveDegradedWindows = 0+ att.senderQualitySampleTimestampMs = nil+ return c.senderAccepted([]*Resource{})+ }+ if senderIdentity == "" || sampleTimestampMs == nil {+ return c.senderRejected()+ }+ guard := CandidateGuard{+ ChildPeerID: op.childPeerID,+ ChildSessionID: op.childSessionID,+ Revision: att.revision,+ ConnectionID: att.connectionID,+ }+ if att.senderQualityIdentity != "" && att.senderQualityIdentity != senderIdentity {+ failed := c.CandidateFailed(guard, acceptedAtMs)+ return SettleResult{+ Accepted: failed.Accepted,+ Committed: failed.Committed,+ FailedPeerIDs: failed.FailedPeerIDs,+ ActiveRevision: failed.ActiveRevision,+ Released: failed.Released,+ }+ }+ if att.senderQualitySampleTimestampMs != nil && *sampleTimestampMs <= *att.senderQualitySampleTimestampMs {+ return c.senderAccepted([]*Resource{})+ }+ sameFreshState := att.senderQualityAcceptedAtMs != nil &&+ acceptedAtMs < *att.senderQualityAcceptedAtMs+qualityEvidenceExpiryMs+ var consecutiveHealthyWindows int64+ if att.tuple.Kind == UpstreamSfu && state == SenderQualityHealthy {+ consecutiveHealthyWindows = 1+ if att.senderQualityState == SenderQualityHealthy && sameFreshState {+ consecutiveHealthyWindows = safeAdd(att.senderQualityConsecutiveHealthyWindows, 1)+ }+ } else if state == SenderQualityHealthy {+ consecutiveHealthyWindows = 1+ }+ var consecutiveDegradedWindows int64+ if state == SenderQualityDegraded {+ consecutiveDegradedWindows = 1+ if att.senderQualityState == SenderQualityDegraded && sameFreshState {+ consecutiveDegradedWindows = safeAdd(att.senderQualityConsecutiveDegradedWindows, 1)+ }+ }+ acceptedAt := acceptedAtMs+ sampleAt := *sampleTimestampMs+ att.senderQualityState = state+ att.senderQualityAcceptedAtMs = &acceptedAt+ att.senderQualityConsecutiveHealthyWindows = consecutiveHealthyWindows+ att.senderQualityConsecutiveDegradedWindows = consecutiveDegradedWindows+ att.senderQualitySampleTimestampMs = &sampleAt+ att.senderQualityIdentity = senderIdentity+ persistentQualityPeerDegradation := op.reason == DemandQualityConvergence &&+ att.tuple.Kind == UpstreamPeer &&+ consecutiveDegradedWindows >= persistentDegradedWindows+ var settled *SettleResult+ if state == SenderQualityDegraded &&+ (att.tuple.Kind != UpstreamPeer ||+ op.reason != DemandQualityConvergence ||+ persistentQualityPeerDegradation) {+ result := c.CandidateFailed(guard, acceptedAtMs)+ settled = &result+ } else if att.mediaReady &&+ (att.tuple.Kind != UpstreamSfu || consecutiveHealthyWindows >= persistentDegradedWindows) {+ result := c.CandidateReady(guard, acceptedAtMs, commitReservation, CandidateProof{})+ settled = &result+ }+ if settled == nil {+ return c.senderAccepted([]*Resource{})+ }+ return SettleResult{+ Accepted: true,+ Committed: settled.Committed,+ FailedPeerIDs: settled.FailedPeerIDs,+ ActiveRevision: settled.ActiveRevision,+ Released: settled.Released,+ }+}++// ResetSenderQuality drops the parent's sender observations, baselines and+// regeneration latches and aborts an operation whose live candidate that+// parent owns; empty unless the parent's session matches.+func (c *Controller) ResetSenderQuality(parentPeerID, parentSessionID string, nowMs int64) []*Resource {+ parent, _ := c.participants.Get(parentPeerID)+ if parent == nil || !parent.sessionIs(parentSessionID) {+ return []*Resource{}+ }+ // Membership only (§4.5 #48): every affected child is deleted.+ children := make(map[string]struct{})+ for _, childPeerID := range c.childrenOf(parentPeerID) {+ children[childPeerID] = struct{}{}+ }+ for childPeerID, observation := range c.senderQualityObservations {+ if observation.parentPeerID == parentPeerID && observation.parentSessionID == parentSessionID {+ children[childPeerID] = struct{}{}+ }+ }+ for childPeerID := range children {+ delete(c.senderQualityObservations, childPeerID)+ // Reset means the next exact sender sequence is a new observation+ // window. A quality/root commit still installs the explicit rearm latch+ // below; a visibility or source reset must not deadlock a persistently+ // limited edge waiting for a healthy sample.+ delete(c.senderQualityBaselines, childPeerID)+ delete(c.senderQualityRegenerationBlocks, childPeerID)+ }+ if parentPeerID == c.hostPeerID {+ c.sfuPublisherQualityObservation = nil+ }+ op := c.operation+ var att *attempt+ if op != nil {+ att = op.current+ }+ ownsCandidate := false+ if att != nil {+ if att.tuple.Kind == UpstreamPeer {+ ownsCandidate = (op.reason == DemandRootConvergence || op.reason == DemandQualityConvergence) &&+ att.tuple.ParentPeerID == parentPeerID &&+ att.parentSessionID == parentSessionID+ } else {+ ownsCandidate = operationRequiresNativeCandidateProof(op) &&+ parentPeerID == c.hostPeerID &&+ att.hostSessionID == parentSessionID+ }+ }+ if ownsCandidate {+ return c.abortOperation(&nowMs, RejectionAborted)+ }+ return []*Resource{}+}++// senderQualityState ports 3012.+func (c *Controller) senderQualityState(childPeerID string, edge *CommittedEdge, nowMs int64) SenderQualityState {+ if edge.Kind != UpstreamPeer {+ if c.sourceUsableForQuality(edge) {+ return SenderQualityHealthy+ }+ return SenderQualityUnknown+ }+ observation := c.senderQualityObservations[childPeerID]+ child, _ := c.participants.Get(childPeerID)+ if observation != nil &&+ nowMs < observation.lastAcceptedAtMs+qualityEvidenceExpiryMs &&+ child != nil && child.sessionIs(observation.childSessionID) &&+ edge.ChildSessionID == observation.childSessionID &&+ edge.ParentPeerID == observation.parentPeerID &&+ edge.ParentSessionID == observation.parentSessionID &&+ edge.ConnectionID == observation.connectionID &&+ c.sourceUsableForQuality(edge) {+ return observation.state+ }+ return SenderQualityUnknown+}++// currentQualityOperationSource ports 3034.+func (c *Controller) currentQualityOperationSource(childPeerID string) *senderQualityIdentity {+ child, _ := c.participants.Get(childPeerID)+ edge, _ := c.upstreamByViewer.Get(childPeerID)+ observation := c.senderQualityObservations[childPeerID]+ if child == nil || child.sessionID == "" ||+ edge == nil || edge.Kind != UpstreamPeer ||+ observation == nil ||+ observation.childSessionID != child.sessionID ||+ observation.childSessionID != edge.ChildSessionID ||+ observation.parentPeerID != edge.ParentPeerID ||+ observation.parentSessionID != edge.ParentSessionID ||+ observation.connectionID != edge.ConnectionID {+ return nil+ }+ return &senderQualityIdentity{+ childSessionID: observation.childSessionID,+ parentPeerID: observation.parentPeerID,+ parentSessionID: observation.parentSessionID,+ connectionID: observation.connectionID,+ senderIdentity: observation.senderIdentity,+ }+}++// currentQualityOperationObservation ports 3061.+func (c *Controller) currentQualityOperationObservation(op *operation) *senderQualityObservation {+ source := op.qualitySource+ current := c.currentQualityOperationSource(op.childPeerID)+ if source == nil || current == nil || *source != *current {+ return nil+ }+ return c.senderQualityObservations[op.childPeerID]+}++// senderQualityRegenerationBlocked ports 3080.+func (c *Controller) senderQualityRegenerationBlocked(childPeerID string, edge *CommittedEdge) bool {+ block, ok := c.senderQualityRegenerationBlocks[childPeerID]+ if !ok {+ return false+ }+ observation := c.senderQualityObservations[childPeerID]+ if observation != nil && observation.senderIdentity != block.senderIdentity {+ delete(c.senderQualityRegenerationBlocks, childPeerID)+ return false+ }+ if block.childSessionID != edge.ChildSessionID ||+ block.parentPeerID != edge.ParentPeerID ||+ block.parentSessionID != edge.ParentSessionID ||+ block.connectionID != edge.ConnectionID {+ delete(c.senderQualityRegenerationBlocks, childPeerID)+ return false+ }+ return true+}++// candidateSenderPersistentlyDegraded ports 3105.+func (c *Controller) candidateSenderPersistentlyDegraded(att *attempt, nowMs int64) bool {+ return att.senderQualityState == SenderQualityDegraded &&+ att.senderQualityAcceptedAtMs != nil &&+ nowMs < *att.senderQualityAcceptedAtMs+qualityEvidenceExpiryMs &&+ att.senderQualityConsecutiveDegradedWindows >= persistentDegradedWindows+}++// sfuPublisherQualityState ports 3120.+func (c *Controller) sfuPublisherQualityState(publicationGeneration string, nowMs int64) SenderQualityState {+ observation := c.sfuPublisherQualityObservation+ if observation != nil &&+ observation.publicationGeneration == publicationGeneration &&+ c.hostPublication != nil && observation.hostSessionID == c.hostPublication.HostSessionID &&+ nowMs < observation.lastAcceptedAtMs+qualityEvidenceExpiryMs {+ if observation.state == SenderQualityHealthy && observation.consecutiveHealthyWindows < persistentDegradedWindows {+ return SenderQualityUnknown+ }+ return observation.state+ }+ return SenderQualityUnknown+}++// qualitySourcePathHealthy ports 3137.+func (c *Controller) qualitySourcePathHealthy(peerID string, nowMs int64) bool {+ if peerID == c.hostPeerID {+ return true+ }+ seen := make(map[string]struct{})+ for {+ if _, visited := seen[peerID]; visited {+ return false+ }+ seen[peerID] = struct{}{}+ edge, _ := c.upstreamByViewer.Get(peerID)+ if edge == nil || !edge.Usable || !edge.PhysicalActive {+ return false+ }+ if edge.Kind == UpstreamSfu {+ return c.sourceUsableForQuality(edge) &&+ c.decodedProgressFresh(peerID, edge, nowMs) &&+ c.sfuPublisherQualityState(edge.PublicationGeneration, nowMs) == SenderQualityHealthy+ }+ if c.senderQualityState(peerID, edge, nowMs) != SenderQualityHealthy {+ return false+ }+ if edge.ParentPeerID == c.hostPeerID {+ return true+ }+ peerID = edge.ParentPeerID+ }+}++// decodedProgressFresh ports 3169.+func (c *Controller) decodedProgressFresh(childPeerID string, edge *CommittedEdge, nowMs int64) bool {+ observation := c.qualityObservations[childPeerID]+ current, _ := c.participants.Get(childPeerID)+ return observation != nil &&+ observation.lastDecodedProgressAtMs != nil &&+ nowMs < *observation.lastDecodedProgressAtMs+qualityEvidenceExpiryMs &&+ current != nil && current.sessionIs(observation.childSessionID) &&+ edge.ChildSessionID == observation.childSessionID &&+ edge.ConnectionID == observation.connectionID &&+ qualityObservationMatchesEdge(observation, edge) &&+ c.sourceUsableForQuality(edge)+}++// buildQualityCandidates ports 3190: clear peers, remaining peers, SFU+// (only under Host fanout relief), same-parent regeneration (§4.4 #36),+// filtered by the per-observation consumed ledger.+func (c *Controller) buildQualityCandidates(childPeerID string, nowMs int64) []CandidatePlan {+ current, _ := c.upstreamByViewer.Get(childPeerID)+ if current == nil || current.Kind != UpstreamPeer {+ return []CandidatePlan{}+ }+ currentKey := edgeTupleKey(current)+ candidates := []CandidatePlan{}+ for _, candidate := range c.buildCandidatePlans(childPeerID, false, false) {+ if candidate.EndpointTransition.Kind == TransitionBoundedGap || tupleKey(candidate.Tuple) == currentKey {+ continue+ }+ if candidate.Tuple.Kind == UpstreamPeer ||+ candidate.Tuple.Publication != PublicationReuse ||+ (c.hostPublication != nil && c.sfuPublisherQualityState(c.hostPublication.Generation, nowMs) == SenderQualityHealthy) {+ candidates = append(candidates, candidate)+ }+ }+ clearPeers := []CandidatePlan{}+ remainingPeers := []CandidatePlan{}+ sfu := []CandidatePlan{}+ for _, candidate := range candidates {+ if candidate.Tuple.Kind != UpstreamPeer {+ sfu = append(sfu, candidate)+ continue+ }+ if c.qualitySourcePathHealthy(candidate.Tuple.ParentPeerID, nowMs) {+ clearPeers = append(clearPeers, candidate)+ } else {+ remainingPeers = append(remainingPeers, candidate)+ }+ }+ if !(current.ParentPeerID == c.hostPeerID && c.hostFanoutNeedsSfuRelief(nowMs)) {+ sfu = nil+ }+ regeneration := []CandidatePlan{}+ if !c.senderQualityRegenerationBlocked(childPeerID, current) {+ regenerationTuple := CandidateTuple{Kind: UpstreamPeer, ParentPeerID: current.ParentPeerID, Transport: TransportDirect, Regenerate: true}+ if plan := c.planCandidate(childPeerID, regenerationTuple); plan != nil &&+ plan.EndpointTransition.Kind != TransitionBoundedGap &&+ c.candidateValid(childPeerID, *plan, nil) {+ regeneration = append(regeneration, *plan)+ }+ }+ prioritized := make([]CandidatePlan, 0, len(candidates)+1)+ prioritized = append(prioritized, clearPeers...)+ prioritized = append(prioritized, remainingPeers...)+ prioritized = append(prioritized, sfu...)+ prioritized = append(prioritized, regeneration...)+ out := make([]CandidatePlan, 0, len(prioritized))+ for _, candidate := range prioritized {+ if c.qualityCandidateOpportunityAvailable(childPeerID, candidate) {+ out = append(out, candidate)+ }+ }+ return out+}++// selectQualityChild ports 3251.+func (c *Controller) selectQualityChild(nowMs int64) string {+ if !c.qualityConvergenceEnabled {+ return ""+ }+ targets := []*participant{}+ for _, viewer := range c.availableViewers(false) {+ edge, _ := c.upstreamByViewer.Get(viewer.peerID)+ if edge != nil && edge.Kind == UpstreamPeer &&+ !c.senderQualityBaselines[viewer.peerID] && // `get(...) !== true`+ c.senderQualityPersistentlyDegraded(viewer.peerID, edge, nowMs) &&+ len(c.buildQualityCandidates(viewer.peerID, nowMs)) > 0 {+ targets = append(targets, viewer)+ }+ }+ sort.SliceStable(targets, func(i, j int) bool {+ if d := c.depth(targets[i].peerID) - c.depth(targets[j].peerID); d != 0 {+ return d < 0+ }+ return compareParticipant(targets[i], targets[j]) < 0+ })+ if len(targets) == 0 {+ return ""+ }+ return targets[0].peerID+}++// senderQualityPersistentlyDegraded ports 3387.+func (c *Controller) senderQualityPersistentlyDegraded(childPeerID string, edge *CommittedEdge, nowMs int64) bool {+ observation := c.senderQualityObservations[childPeerID]+ return c.senderQualityState(childPeerID, edge, nowMs) == SenderQualityDegraded &&+ observation != nil &&+ observation.consecutiveDegradedWindows >= persistentDegradedWindows+}++// qualityOperationStillEligible ports 3401.+func (c *Controller) qualityOperationStillEligible(op *operation, nowMs int64) bool {+ currentEdge, _ := c.upstreamByViewer.Get(op.childPeerID)+ observation := c.currentQualityOperationObservation(op)+ tuple := op.currentTuple()+ if currentEdge == nil || currentEdge.Kind != UpstreamPeer || tuple == nil || observation == nil {+ return false+ }+ state := c.senderQualityState(op.childPeerID, currentEdge, nowMs)+ if state == SenderQualityHealthy {+ return false+ }+ return tuple.Kind == UpstreamPeer ||+ (state == SenderQualityDegraded && c.hostFanoutNeedsSfuRelief(nowMs))+}++// hostFanoutNeedsSfuRelief ports 3431.+func (c *Controller) hostFanoutNeedsSfuRelief(nowMs int64) bool {+ count := 0+ for childPeerID, edge := range c.upstreamByViewer.All() {+ if edge.Kind != UpstreamPeer || edge.ParentPeerID != c.hostPeerID || !edge.Usable || !edge.PhysicalActive {+ continue+ }+ count+++ if !c.senderQualityPersistentlyDegraded(childPeerID, edge, nowMs) {+ return false+ }+ }+ return count >= 2+}++// qualityUpstreamMatches ports 4506.+func qualityUpstreamMatches(edge *CommittedEdge, upstream QualityUpstream) bool {+ if edge.Kind == UpstreamPeer {+ return upstream.Kind == UpstreamPeer && upstream.PeerID == edge.ParentPeerID+ }+ return upstream.Kind == UpstreamSfu+}++// qualityObservationMatchesEdge ports 4515; upstreamPeerID "" is TS null.+func qualityObservationMatchesEdge(observation *routeQualityObservation, edge *CommittedEdge) bool {+ if edge.Kind == UpstreamPeer {+ return observation.upstreamKind == UpstreamPeer && observation.upstreamPeerID == edge.ParentPeerID+ }+ return observation.upstreamKind == UpstreamSfu && observation.upstreamPeerID == ""+}++// sourceUsableForQuality ports 4526.+func (c *Controller) sourceUsableForQuality(edge *CommittedEdge) bool {+ if edge.Kind == UpstreamPeer {+ parent, _ := c.participants.Get(edge.ParentPeerID)+ return parent != nil && parent.sessionIs(edge.ParentSessionID) && c.sourceUsable(edge.ParentPeerID)+ }+ return c.hostPublication != nil && c.hostPublication.Usable &&+ c.hostPublication.PhysicalActive &&+ c.hostPublication.Generation == edge.PublicationGeneration+}++// clearQualityForParticipant ports 4541: the Host clears every child, a+// viewer clears its subtree plus itself (§4.2 #21, §4.5 #50).+func (c *Controller) clearQualityForParticipant(peerID string) {+ var affected []string+ if peerID == c.hostPeerID {+ affected = c.upstreamByViewer.Keys()+ } else {+ affected = withSelf(c.descendantsOf(peerID), peerID)+ }+ for _, childPeerID := range affected {+ delete(c.qualityObservations, childPeerID)+ delete(c.senderQualityObservations, childPeerID)+ delete(c.senderQualityBaselines, childPeerID)+ delete(c.senderQualityRegenerationBlocks, childPeerID)+ if c.upstreamByViewer.Has(childPeerID) {+ c.qualityBaselinesPending[childPeerID] = struct{}{}+ c.senderQualityBaselines[childPeerID] = true+ } else {+ delete(c.qualityBaselinesPending, childPeerID)+ delete(c.senderQualityBaselines, childPeerID)+ }+ }+}++// requireSenderQualityBaseline ports 4609; a missing baseline reads as+// false (`get(...) === true`).+func (c *Controller) requireSenderQualityBaseline(peerID string, suppressFact bool) {+ for _, childPeerID := range withSelf(c.descendantsOf(peerID), peerID) {+ if c.upstreamByViewer.Has(childPeerID) {+ delete(c.senderQualityObservations, childPeerID)+ c.senderQualityBaselines[childPeerID] = suppressFact || c.senderQualityBaselines[childPeerID]+ }+ }+}++// clearSfuQuality ports 4624.+func (c *Controller) clearSfuQuality() {+ c.sfuPublisherQualityObservation = nil+ for childPeerID, edge := range c.upstreamByViewer.All() {+ if edge.Kind == UpstreamSfu {+ c.clearQualityForParticipant(childPeerID)+ }+ }+}diff --git a/internal/server/route/root_convergence.go b/internal/server/route/root_convergence.gonew file mode 100644index 00000000..8c21770f--- /dev/null+++ b/internal/server/route/root_convergence.go@@ -0,0 +1,131 @@+package route++import "sort"++// rootConvergencePick is the takeRootConvergenceIntent result.+type rootConvergencePick struct {+ childPeerID string+ plan CandidatePlan+}++// stageRootConvergence ports 3272: staged from commitAttempt whenever a+// child newly became a direct child of the Host.+func (c *Controller) stageRootConvergence(rootPeerID string) {+ if !c.qualityConvergenceEnabled {+ return+ }+ convergence := c.rootConvergencePlan(rootPeerID)+ if convergence == nil {+ return+ }+ c.rootConvergenceRootPeerID = rootPeerID+ c.debug("root-convergence-staged",+ "root", c.debugPeer(rootPeerID),+ "donor", c.debugPeer(convergence.donorPeerID),+ "child", c.debugPeer(convergence.childPeerID))+}++// takeRootConvergenceIntent ports 3284: one-shot (take = clear).+func (c *Controller) takeRootConvergenceIntent() *rootConvergencePick {+ rootPeerID := c.rootConvergenceRootPeerID+ c.rootConvergenceRootPeerID = ""+ if rootPeerID == "" || !c.qualityConvergenceEnabled {+ return nil+ }+ convergence := c.rootConvergencePlan(rootPeerID)+ if convergence == nil {+ return nil+ }+ return &rootConvergencePick{childPeerID: convergence.childPeerID, plan: convergence.plan}+}++type rootConvergence struct {+ donorPeerID string+ childPeerID string+ plan CandidatePlan+}++// rootConvergencePlan ports 3299: the busiest other Host root donates its+// newest active direct child to the fresh root (§4.5 #45).+func (c *Controller) rootConvergencePlan(rootPeerID string) *rootConvergence {+ root, _ := c.participants.Get(rootPeerID)+ if root == nil || root.sessionID == "" ||+ root.departureConfirmed ||+ !c.isActiveHostRoot(rootPeerID) ||+ len(c.activeDirectChildren(rootPeerID)) != 0 {+ return nil+ }+ donors := []string{}+ for _, peerID := range c.childrenOf(c.hostPeerID) {+ if peerID != rootPeerID && c.isActiveHostRoot(peerID) && len(c.activeDirectChildren(peerID)) >= 2 {+ donors = append(donors, peerID)+ }+ }+ sort.SliceStable(donors, func(i, j int) bool {+ if d := len(c.activeDirectChildren(donors[j])) - len(c.activeDirectChildren(donors[i])); d != 0 {+ return d < 0+ }+ left, _ := c.participants.Get(donors[i])+ right, _ := c.participants.Get(donors[j])+ return compareParticipant(left, right) < 0+ })+ if len(donors) == 0 {+ return nil+ }+ donorPeerID := donors[0]+ children := c.activeDirectChildren(donorPeerID)+ sort.SliceStable(children, func(i, j int) bool {+ left, _ := c.participants.Get(children[i])+ right, _ := c.participants.Get(children[j])+ return compareParticipant(right, left) < 0+ })+ if len(children) == 0 {+ return nil+ }+ childPeerID := children[0]+ plan := c.planCandidate(childPeerID, CandidateTuple{Kind: UpstreamPeer, ParentPeerID: rootPeerID, Transport: TransportDirect})+ if plan != nil &&+ plan.EndpointTransition.Kind != TransitionBoundedGap &&+ c.candidateValid(childPeerID, *plan, nil) {+ return &rootConvergence{donorPeerID: donorPeerID, childPeerID: childPeerID, plan: *plan}+ }+ return nil+}++// rootConvergenceOperationStillEligible ports 3350.+func (c *Controller) rootConvergenceOperationStillEligible(op *operation) bool {+ if op.reason != DemandRootConvergence {+ return true+ }+ tuple := op.currentTuple()+ current, _ := c.upstreamByViewer.Get(op.childPeerID)+ return tuple != nil && tuple.Kind == UpstreamPeer &&+ current != nil && current.Kind == UpstreamPeer &&+ current.Usable &&+ current.PhysicalActive &&+ current.ParentPeerID != tuple.ParentPeerID &&+ c.isActiveHostRoot(tuple.ParentPeerID) &&+ c.isActiveHostRoot(current.ParentPeerID) &&+ len(c.activeDirectChildren(tuple.ParentPeerID)) == 0 &&+ len(c.activeDirectChildren(current.ParentPeerID)) >= 2+}++// isActiveHostRoot ports 3370.+func (c *Controller) isActiveHostRoot(peerID string) bool {+ edge, _ := c.upstreamByViewer.Get(peerID)+ return edge != nil && edge.Kind == UpstreamPeer &&+ edge.ParentPeerID == c.hostPeerID &&+ edge.Usable &&+ edge.PhysicalActive+}++// activeDirectChildren ports 3380.+func (c *Controller) activeDirectChildren(parentPeerID string) []string {+ children := []string{}+ for _, childPeerID := range c.childrenOf(parentPeerID) {+ if edge, ok := c.upstreamByViewer.Get(childPeerID); ok && edge.Kind == UpstreamPeer && edge.Usable && edge.PhysicalActive {+ children = append(children, childPeerID)+ }+ }+ return children+}diff --git a/internal/server/route/sfu_bootstrap.go b/internal/server/route/sfu_bootstrap.gonew file mode 100644index 00000000..49f0872b--- /dev/null+++ b/internal/server/route/sfu_bootstrap.go@@ -0,0 +1,263 @@+package route++import (+ "slices"+ "sort"+)++// peekSfuBootstrapCarrier ports 3597.+func (c *Controller) peekSfuBootstrapCarrier() *sfuBootstrapCarrier {+ intent := c.currentSfuBootstrapIntent()+ if intent == nil {+ return nil+ }+ carriers := c.safeSfuBootstrapCarriers(intent.demandPeerID)+ if len(carriers) == 0 {+ return nil+ }+ return &sfuBootstrapCarrier{+ demandPeerID: intent.demandPeerID,+ demandSessionID: intent.demandSessionID,+ carrierPeerID: carriers[0],+ }+}++// hasSfuBootstrapWork ports 3612.+func (c *Controller) hasSfuBootstrapWork() bool {+ if c.currentSfuBootstrapIntent() != nil {+ return true+ }+ for _, viewer := range c.availableViewers(true) {+ if viewer.availabilityExhausted &&+ c.sfuBootstrapNeeded(viewer.peerID) &&+ (len(c.safeSfuBootstrapCarriers(viewer.peerID)) > 0 || !viewer.bootstrapFailureReported) {+ return true+ }+ }+ return false+}++// takeSfuBootstrapCarrier ports 3623.+func (c *Controller) takeSfuBootstrapCarrier(nowMs int64, failedPeerIDs *[]string) *sfuBootstrapCarrier {+ if !c.sfuBootstrapGloballyNeeded() {+ return nil+ }+ if carrier := c.peekSfuBootstrapCarrier(); carrier != nil {+ return carrier+ }+ c.sfuBootstrapIntent = nil+ c.reportSfuBootstrapFailures(nowMs, failedPeerIDs)+ return nil+}++// currentSfuBootstrapIntent ports 3635: the sticky intent is revalidated on+// every access and otherwise re-derived from the first exhausted viewer in+// availableViewers order (§4.5 #43).+func (c *Controller) currentSfuBootstrapIntent() *sfuBootstrapIntent {+ if current := c.sfuBootstrapIntent; current != nil {+ demand, _ := c.participants.Get(current.demandPeerID)+ if c.sfuBootstrapNeeded(current.demandPeerID) &&+ demand != nil && demand.sessionIs(current.demandSessionID) &&+ len(c.safeSfuBootstrapCarriers(current.demandPeerID)) > 0 {+ return current+ }+ c.sfuBootstrapIntent = nil+ }+ for _, viewer := range c.availableViewers(true) {+ if viewer.availabilityExhausted &&+ c.sfuBootstrapNeeded(viewer.peerID) &&+ len(c.safeSfuBootstrapCarriers(viewer.peerID)) > 0 {+ if viewer.sessionID == "" {+ return nil+ }+ created := &sfuBootstrapIntent{demandPeerID: viewer.peerID, demandSessionID: viewer.sessionID}+ c.sfuBootstrapIntent = created+ return created+ }+ }+ return nil+}++// bootstrapOperationOwned ports 3663; checked first in validateOrAdvance+// so a bootstrap operation evaporates with its intent.+func (c *Controller) bootstrapOperationOwned(op *operation) bool {+ if op.reason != DemandSfuBootstrap {+ return true+ }+ intent := c.sfuBootstrapIntent+ if intent == nil ||+ intent.demandPeerID != op.demandPeerID ||+ intent.demandSessionID != op.demandSessionID ||+ !c.sfuBootstrapNeeded(op.demandPeerID) {+ return false+ }+ return slices.Contains(c.safeSfuBootstrapCarriers(op.demandPeerID), op.childPeerID)+}++// sfuBootstrapNeeded ports 3681.+func (c *Controller) sfuBootstrapNeeded(demandPeerID string) bool {+ if !c.sfuBootstrapGloballyNeeded() {+ return false+ }+ demand, _ := c.participants.Get(demandPeerID)+ return demand != nil && demand.sessionID != "" &&+ !c.usableRoute(demandPeerID) &&+ c.sfuOpportunityAvailable(demandPeerID)+}++// sfuOpportunityAvailable ports 3690.+func (c *Controller) sfuOpportunityAvailable(demandPeerID string) bool {+ return c.candidateOpportunityAvailable(demandPeerID, CandidatePlan{+ Tuple: CandidateTuple{Kind: UpstreamSfu, Publication: PublicationReuse},+ EndpointTransition: EndpointTransition{Kind: TransitionNone},+ })+}++// sfuBootstrapGloballyNeeded ports 3697.+func (c *Controller) sfuBootstrapGloballyNeeded() bool {+ return c.sfuEnabled && c.hostPublication == nil && !c.hostHasPublicationSlot()+}++// safeSfuBootstrapCarriers ports 3705.+func (c *Controller) safeSfuBootstrapCarriers(demandPeerID string) []string {+ if !c.sfuBootstrapNeeded(demandPeerID) {+ return []string{}+ }+ return c.sfuBootstrapCarriers()+}++// sfuBootstrapCarriers ports 3712: the Host's usable direct children that+// can create a publication, newest first (§4.5 #44).+func (c *Controller) sfuBootstrapCarriers() []string {+ tuple := CandidateTuple{Kind: UpstreamSfu, Publication: PublicationCreate}+ carriers := []string{}+ for _, peerID := range c.childrenOf(c.hostPeerID) {+ current, _ := c.participants.Get(peerID)+ edge, _ := c.upstreamByViewer.Get(peerID)+ plan := c.planCandidate(peerID, tuple)+ if current != nil && current.sessionID != "" &&+ edge != nil && edge.Kind == UpstreamPeer &&+ edge.Transport == TransportDirect &&+ edge.Usable &&+ edge.PhysicalActive &&+ plan != nil &&+ plan.EndpointTransition.Kind != TransitionBoundedGap &&+ c.sfuBootstrapOpportunityAvailable(peerID, *plan) {+ carriers = append(carriers, peerID)+ }+ }+ sort.SliceStable(carriers, func(i, j int) bool {+ left, _ := c.participants.Get(carriers[i])+ right, _ := c.participants.Get(carriers[j])+ return compareParticipant(right, left) < 0+ })+ return carriers+}++// sfuBootstrapOpportunityAvailable ports 3744.+func (c *Controller) sfuBootstrapOpportunityAvailable(carrierPeerID string, plan CandidatePlan) bool {+ consumed, ok := c.consumedSfuBootstrapOpportunities.Get(c.sfuBootstrapOpportunityBase(carrierPeerID, plan))+ return !ok || endpointTransitionRank(plan.EndpointTransition) < consumed+}++// sfuBootstrapOpportunityBase ports 3757.+func (c *Controller) sfuBootstrapOpportunityBase(carrierPeerID string, plan CandidatePlan) string {+ return carrierPeerID + "\x00" + c.candidateOpportunityBase(carrierPeerID, plan)+}++// consumeSfuBootstrapOpportunity ports 3767.+func (c *Controller) consumeSfuBootstrapOpportunity(carrierPeerID string, plan CandidatePlan) {+ consumeOpportunity(&c.consumedSfuBootstrapOpportunities,+ c.sfuBootstrapOpportunityBase(carrierPeerID, plan),+ endpointTransitionRank(plan.EndpointTransition))+}++// completeSfuBootstrapCarrier ports 3778: consumes the carrier's attempt+// and returns the failed demand peer only once no carrier is left.+func (c *Controller) completeSfuBootstrapCarrier(carrierPeerID string, nowMs int64, bucket RejectionBucket, attemptedPlan *CandidatePlan) string {+ intent := c.sfuBootstrapIntent+ if intent == nil {+ return ""+ }+ plan := attemptedPlan+ if plan == nil {+ plan = c.planCandidate(carrierPeerID, CandidateTuple{Kind: UpstreamSfu, Publication: PublicationCreate})+ }+ if plan != nil {+ c.consumeSfuBootstrapOpportunity(carrierPeerID, *plan)+ c.consumeCandidateOpportunity(carrierPeerID, *plan)+ }+ if len(c.safeSfuBootstrapCarriers(intent.demandPeerID)) > 0 {+ return ""+ }+ demand, _ := c.participants.Get(intent.demandPeerID)+ if demand != nil {+ demand.availabilityExhausted = true+ }+ c.finishTiming(intent.demandPeerID, nowMs, FinalRouteFailed, bucket, false)+ if demand != nil {+ demand.bootstrapFailureReported = true+ }+ c.sfuBootstrapIntent = nil+ return intent.demandPeerID+}++// reportSfuBootstrapFailures ports 3808 (availableViewers order, §4.5 #43).+func (c *Controller) reportSfuBootstrapFailures(nowMs int64, failedPeerIDs *[]string) {+ for _, demand := range c.availableViewers(true) {+ if !demand.availabilityExhausted ||+ !c.sfuBootstrapNeeded(demand.peerID) ||+ c.usableRoute(demand.peerID) ||+ demand.bootstrapFailureReported {+ continue+ }+ demand.bootstrapFailureReported = true+ c.finishTiming(demand.peerID, nowMs, FinalRouteFailed, RejectionCandidateFailed, false)+ *failedPeerIDs = append(*failedPeerIDs, demand.peerID)+ }+}++// rememberUnavailableSfuBootstrap ports 3827.+func (c *Controller) rememberUnavailableSfuBootstrap(demandPeerID string) {+ if !c.sfuBootstrapNeeded(demandPeerID) {+ return+ }+ demand, _ := c.participants.Get(demandPeerID)+ if demand == nil || demand.sessionID == "" {+ return+ }+ demand.bootstrapFailureReported = true+ c.sfuBootstrapIntent = nil+}++// stageSfuBootstrap ports 3835.+func (c *Controller) stageSfuBootstrap(op *operation) {+ demand, _ := c.participants.Get(op.demandPeerID)+ if demand == nil || demand.sessionID == "" || !c.sfuBootstrapNeeded(demand.peerID) {+ return+ }+ if len(c.safeSfuBootstrapCarriers(demand.peerID)) == 0 {+ return+ }+ if current := c.sfuBootstrapIntent; current != nil &&+ current.demandPeerID == demand.peerID &&+ current.demandSessionID == demand.sessionID {+ return+ }+ c.sfuBootstrapIntent = &sfuBootstrapIntent{demandPeerID: demand.peerID, demandSessionID: demand.sessionID}+}++// clearSfuBootstrapForDemand ports 3854.+func (c *Controller) clearSfuBootstrapForDemand(demandPeerID string) {+ if demand, ok := c.participants.Get(demandPeerID); ok {+ demand.sfuFirstAtNextRoute = false+ }+ if c.sfuBootstrapIntent != nil && c.sfuBootstrapIntent.demandPeerID == demandPeerID {+ c.sfuBootstrapIntent = nil+ }+}++// bootstrapCandidateAvailable ports 4334.+func (c *Controller) bootstrapCandidateAvailable(demandPeerID string) bool {+ return len(c.safeSfuBootstrapCarriers(demandPeerID)) > 0+}diff --git a/internal/server/route/smoke_test.go b/internal/server/route/smoke_test.gonew file mode 100644index 00000000..c30908b5--- /dev/null+++ b/internal/server/route/smoke_test.go@@ -0,0 +1,83 @@+package route++import (+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// TestSmokeCommitsOneDirectCandidate wires the controller end to end: a+// Host and two Viewers join, reconcile starts one join operation for the+// first Viewer with the Host as its first direct candidate, and begin ++// candidateReady commit that edge at the attempt's revision.+func TestSmokeCommitsOneDirectCandidate(t *testing.T) {+ const host = "smoke_host_1234"+ const first = "smoke_viewer_a_1"+ const second = "smoke_viewer_b_1"+ routes := New(Options{HostPeerID: host, EndpointMediaCopyCapacity: 2, OperationTimeoutMs: 10_000})+ routes.UpsertParticipant(ParticipantInput{PeerID: host, Role: protocol.RoleHost, SessionID: "host_s", EffectiveDownstreamCapacity: 2}, nil)+ now := int64(1_000)+ for _, viewer := range []string{first, second} {+ routes.UpsertParticipant(ParticipantInput{PeerID: viewer, Role: protocol.RoleViewer, SessionID: viewer + "_s", EffectiveDownstreamCapacity: 2}, &now)+ }++ result := routes.Reconcile(now)+ if result.Operation == nil {+ t.Fatal("expected reconcile to start an operation")+ }+ operation := result.Operation+ if operation.ChildPeerID != first || operation.Reason != DemandJoin {+ t.Fatalf("operation = %+v, want a join for the first viewer", operation)+ }+ if len(operation.Candidates) == 0 || operation.Candidates[0].Tuple != (CandidateTuple{Kind: UpstreamPeer, ParentPeerID: host, Transport: TransportDirect}) {+ t.Fatalf("candidates = %+v, want the Host first", operation.Candidates)+ }+ if operation.WakeAtMs != operation.DeadlineAtMs || operation.DeadlineAtMs != now+10_000 {+ t.Fatalf("deadline %d wake %d, want both at %d", operation.DeadlineAtMs, operation.WakeAtMs, now+10_000)+ }++ begin := routes.BeginCurrentCandidate(BeginInput{+ Guard: CandidateCursorGuard{+ ChildPeerID: operation.ChildPeerID,+ ChildSessionID: operation.ChildSessionID,+ BaseRevision: operation.BaseRevision,+ FactVersion: operation.FactVersion,+ Cursor: operation.Cursor,+ Plan: operation.Candidates[operation.Cursor],+ },+ NowMs: now + 1,+ ConnectionID: "conn_a",+ Reservation: CandidateReservation{Kind: ReservationDirect},+ })+ if !begin.Accepted || begin.Operation == nil || begin.Operation.Current == nil {+ t.Fatalf("begin = %+v, want an accepted live attempt", begin)+ }+ if routes.Snapshot().Revision != operation.BaseRevision {+ t.Fatal("beginCurrentCandidate must not advance the advertised revision")+ }++ settled := routes.CandidateReady(CandidateGuard{+ ChildPeerID: operation.ChildPeerID,+ ChildSessionID: operation.ChildSessionID,+ Revision: begin.Operation.Current.Revision,+ ConnectionID: "conn_a",+ }, now+2, nil, CandidateProof{})+ if !settled.Accepted || !settled.Committed || len(settled.Released) != 0 {+ t.Fatalf("candidateReady = %+v, want a clean commit", settled)+ }+ snapshot := routes.Snapshot()+ if snapshot.Revision != begin.Operation.Current.Revision || snapshot.Operation != nil {+ t.Fatalf("snapshot revision %d operation %v, want %d and idle", snapshot.Revision, snapshot.Operation, begin.Operation.Current.Revision)+ }+ edge, ok := snapshot.UpstreamByViewer.Get(first)+ if !ok || edge.Kind != UpstreamPeer || edge.ParentPeerID != host || edge.ConnectionID != "conn_a" || !edge.Usable || !edge.PhysicalActive {+ t.Fatalf("edge = %+v, want a usable direct edge from the Host", edge)+ }+ if next := routes.Reconcile(now + 3).Operation; next == nil || next.ChildPeerID != second {+ t.Fatalf("next operation = %+v, want the second viewer", next)+ }+ diagnostic := routes.RouteDiagnosticSnapshot(now + 3)+ if len(diagnostic.Children) != 2 || diagnostic.Children[0].Parent.Kind != "host" || diagnostic.Children[0].FinalRoute != "direct" {+ t.Fatalf("diagnostic = %+v, want the first child routed through the Host", diagnostic)+ }+}diff --git a/internal/server/route/timing.go b/internal/server/route/timing.gonew file mode 100644index 00000000..54535388--- /dev/null+++ b/internal/server/route/timing.go@@ -0,0 +1,193 @@+package route++import "github.com/TNTcraftHIM/Screener/internal/server/protocol"++// recordDemand ports 4633: replaces the peer's timing record wholesale.+func (c *Controller) recordDemand(childPeerID string, nowMs int64, reason DemandReason) {+ c.routeTimings[childPeerID] = &routeTimingRecord{+ demandAtMs: nowMs,+ reason: reason,+ finalRoute: FinalRouteWaiting,+ rejectionBucket: RejectionNone,+ }+}++// ensureDemand ports 4647.+func (c *Controller) ensureDemand(childPeerID string, nowMs int64, reason DemandReason) {+ if _, ok := c.routeTimings[childPeerID]; !ok {+ c.recordDemand(childPeerID, nowMs, reason)+ }+}++// startOperationTiming ports 4657.+func (c *Controller) startOperationTiming(childPeerID string, nowMs int64) {+ record := c.routeTimings[childPeerID]+ if record == nil {+ return+ }+ startedAt := nowMs+ record.operationStartedAtMs = &startedAt+ record.candidateStartedAtMs = nil+ record.firstDecodedFrameAtMs = nil+ record.finalAtMs = nil+ record.finalRoute = FinalRouteWaiting+ record.rejectionBucket = RejectionNone+}++// startCandidateTiming ports 4668.+func (c *Controller) startCandidateTiming(childPeerID string, nowMs int64) {+ record := c.routeTimings[childPeerID]+ if record == nil {+ return+ }+ startedAt := nowMs+ record.candidateStartedAtMs = &startedAt+ record.firstDecodedFrameAtMs = nil+ record.finalAtMs = nil+ record.finalRoute = FinalRouteWaiting+ record.rejectionBucket = RejectionNone+}++// noteRejection ports 4678.+func (c *Controller) noteRejection(childPeerID string, bucket RejectionBucket) {+ if record := c.routeTimings[childPeerID]; record != nil {+ record.rejectionBucket = bucket+ }+}++// clearCandidateTiming ports 4686.+func (c *Controller) clearCandidateTiming(childPeerID string) {+ record := c.routeTimings[childPeerID]+ if record == nil {+ return+ }+ record.candidateStartedAtMs = nil+ record.firstDecodedFrameAtMs = nil+ record.finalAtMs = nil+ record.finalRoute = FinalRouteWaiting+}++// finishTiming ports 4695.+func (c *Controller) finishTiming(childPeerID string, nowMs int64, finalRoute FinalRoute, rejectionBucket RejectionBucket, firstDecodedFrame bool) {+ record := c.routeTimings[childPeerID]+ if record == nil {+ return+ }+ if firstDecodedFrame {+ decodedAt := nowMs+ record.firstDecodedFrameAtMs = &decodedAt+ }+ finalAt := nowMs+ record.finalAtMs = &finalAt+ record.finalRoute = finalRoute+ record.rejectionBucket = rejectionBucket+}++// usableRoute ports 4710.+func (c *Controller) usableRoute(childPeerID string) bool {+ return c.currentFinalRoute(childPeerID) != FinalRouteWaiting+}++// currentFinalRoute ports 4714.+func (c *Controller) currentFinalRoute(childPeerID string) FinalRoute {+ edge, _ := c.upstreamByViewer.Get(childPeerID)+ if edge == nil || !edge.Usable || !edge.PhysicalActive {+ return FinalRouteWaiting+ }+ if edge.Kind == UpstreamPeer {+ if c.sourceUsable(edge.ParentPeerID) {+ return FinalRouteDirect+ }+ return FinalRouteWaiting+ }+ if c.hostPublication != nil && c.hostPublication.Usable &&+ c.hostPublication.PhysicalActive &&+ c.hostPublication.Generation == edge.PublicationGeneration {+ return FinalRouteSfu+ }+ return FinalRouteWaiting+}++// routeDemandReason ports 4729.+func (c *Controller) routeDemandReason(childPeerID string) DemandReason {+ edge, _ := c.upstreamByViewer.Get(childPeerID)+ if edge == nil {+ return DemandJoin+ }+ if edge.Kind == UpstreamPeer {+ if parent, ok := c.participants.Get(edge.ParentPeerID); ok && parent.departureConfirmed {+ return DemandParentDeparted+ }+ for _, overflowing := range c.overflowPeerChildren(edge.ParentPeerID) {+ if overflowing == childPeerID {+ return DemandCapacityReduction+ }+ }+ }+ return DemandEdgeUnavailable+}++// diagnosticParent ports 4448.+func (c *Controller) diagnosticParent(edge *CommittedEdge, ordinals map[string]int) protocol.RouteDiagnosticParent {+ if edge == nil || !edge.Usable || !edge.PhysicalActive {+ return protocol.RouteDiagnosticParent{Kind: "none"}+ }+ if edge.Kind == UpstreamSfu {+ if c.hostPublication != nil && c.hostPublication.Usable &&+ c.hostPublication.PhysicalActive &&+ c.hostPublication.Generation == edge.PublicationGeneration {+ return protocol.RouteDiagnosticParent{Kind: "sfu"}+ }+ return protocol.RouteDiagnosticParent{Kind: "none"}+ }+ if edge.ParentPeerID == c.hostPeerID {+ return protocol.RouteDiagnosticParent{Kind: "host"}+ }+ ordinal, ok := ordinals[edge.ParentPeerID]+ if !ok {+ return protocol.RouteDiagnosticParent{Kind: "none"}+ }+ return protocol.RouteDiagnosticParent{Kind: "viewer", Ordinal: protocol.Int(ordinal)}+}++// diagnosticQuality ports 4471: nil (TS null) unless the observation is+// fresh, non-empty and still describes the current edge.+func (c *Controller) diagnosticQuality(childPeerID string, edge *CommittedEdge, nowMs int64) *protocol.RouteDiagnosticQuality {+ observation := c.qualityObservations[childPeerID]+ current, _ := c.participants.Get(childPeerID)+ if c.paused ||+ observation == nil ||+ observation.eligibleWindows == 0 ||+ nowMs >= observation.lastAcceptedAtMs+qualityEvidenceExpiryMs ||+ current == nil || current.sessionID == "" ||+ !current.sessionIs(observation.childSessionID) ||+ edge == nil ||+ !edge.Usable ||+ !edge.PhysicalActive ||+ edge.ConnectionID != observation.connectionID ||+ !qualityObservationMatchesEdge(observation, edge) ||+ !c.sourceUsableForQuality(edge) {+ return nil+ }+ return &protocol.RouteDiagnosticQuality{+ EligibleWindows: protocol.Int(observation.eligibleWindows),+ EligibleDurationMs: protocol.Int(observation.eligibleDurationMs),+ FreezeWindows: protocol.Int(observation.freezeWindows),+ FreezeCount: protocol.Int(observation.freezeCount),+ FreezeDurationMs: protocol.Int(observation.freezeDurationMs),+ PauseCount: protocol.Int(observation.pauseCount),+ PauseDurationMs: protocol.Int(observation.pauseDurationMs),+ }+}++// elapsedMs ports 4964: nil (TS null) when the end precedes the start or+// the difference is not a safe integer; the inputs are integral so+// Math.floor is the identity.+func elapsedMs(startedAtMs, endedAtMs int64) *protocol.Int {+ elapsed := endedAtMs - startedAtMs+ if !isSafeInteger(elapsed) || elapsed < 0 {+ return nil+ }+ value := protocol.Int(elapsed)+ return &value+}diff --git a/internal/server/sfu/admission.go b/internal/server/sfu/admission.gonew file mode 100644index 00000000..a59793e8--- /dev/null+++ b/internal/server/sfu/admission.go@@ -0,0 +1,424 @@+// Package sfu ports the server's LiveKit-facing modules: the resource+// admission ledger (src/server/sfu-resource-admission.ts), the RoomService+// control plane (src/server/sfu-room-control.ts) and the participant token+// issuer (src/server/livekit-token.ts).+//+// LiveKit access is stdlib only (DECISIONS D1): one HS256 JWT signed with+// crypto/hmac and Twirp JSON over net/http, no SDK.+package sfu++import (+ "errors"+ "regexp"+ "strings"++ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// ResourceFence is SfuResourceFence. It is a comparable value, so the+// TypeScript cloneFence/sameFence helpers are a plain copy and `==`.+type ResourceFence struct {+ RoomID string+ ShareGeneration string+ PublicationGeneration string+}++// SubscriptionFence is SfuSubscriptionFence, which extends SfuResourceFence.+// The embedded value is the `{ ...fence, viewerPeerId }` spread the router+// uses to derive one from a publication fence.+type SubscriptionFence struct {+ ResourceFence+ ViewerPeerID string+}++// Usage is SfuResourceUsage.+type Usage struct {+ Ingress int+ Egress int+}++// AdmissionOptions is SfuResourceAdmissionOptions.+type AdmissionOptions struct {+ IngressCapacity int+ EgressCapacity int+}++// resourceState is the TypeScript ResourceState union.+type resourceState string++const (+ stateReserved resourceState = "reserved"+ stateCommitted resourceState = "committed"+ stateDraining resourceState = "draining"+)++type subscriptionEntry struct {+ fence SubscriptionFence+ state resourceState+}++type publicationEntry struct {+ fence ResourceFence+ state resourceState+ // Ordering site: subscriptions are only counted, looked up by viewer and+ // state-scanned, so their iteration order is never observable. A plain map+ // is enough here; the two maps above it are ordered.+ subscriptions map[string]*subscriptionEntry+}++// roomPublications is RoomResources.publications. Ordering site: commitPublication+// returns the drained generations and beginDrainRoom returns every generation in+// insertion order, both of which the router turns into drain tasks.+type roomPublications = ordered.Map[string, *publicationEntry]++// Admission is SfuResourceAdmission: the ingress/egress ledger for the LiveKit+// fallback. It is not safe for concurrent use; the signaling server calls it+// under its global mutex, exactly as Node's single thread did.+type Admission struct {+ // Ordering site: beginDrainAll walks the rooms in insertion order.+ rooms ordered.Map[string, *roomPublications]+ ingressCapacity int+ egressCapacity int+ ingressInUse int+ egressInUse int+}++// NewAdmission mirrors the SfuResourceAdmission constructor. An invalid+// capacity panics where the TypeScript throws: the capacities come from a+// constant and from validated configuration, so this is an assertion.+func NewAdmission(options AdmissionOptions) *Admission {+ assertPositiveSafeInteger(options.IngressCapacity, "SFU ingress capacity")+ assertPositiveSafeInteger(options.EgressCapacity, "SFU egress capacity")+ return &Admission{+ ingressCapacity: options.IngressCapacity,+ egressCapacity: options.EgressCapacity,+ }+}++// ReservePublication ports reservePublication.+func (admission *Admission) ReservePublication(fence ResourceFence) bool {+ assertFence(fence)+ room, _ := admission.rooms.Get(fence.RoomID)+ var existing *publicationEntry+ if room != nil {+ existing, _ = room.Get(publicationKey(fence))+ }+ if existing != nil {+ return existing.state != stateDraining && existing.fence == fence+ }+ if admission.ingressInUse >= admission.ingressCapacity {+ return false+ }+ if room != nil {+ for _, publication := range room.All() {+ if publication.state == stateReserved {+ return false+ }+ }+ }++ resources := room+ if resources == nil {+ resources = &roomPublications{}+ }+ resources.Set(publicationKey(fence), &publicationEntry{+ fence: fence,+ state: stateReserved,+ subscriptions: map[string]*subscriptionEntry{},+ })+ admission.rooms.Set(fence.RoomID, resources)+ admission.ingressInUse+++ return true+}++// ReserveSubscription ports reserveSubscription.+func (admission *Admission) ReserveSubscription(fence SubscriptionFence) bool {+ assertSubscriptionFence(fence)+ publication := admission.publication(fence.ResourceFence)+ if publication == nil || publication.state == stateDraining {+ return false+ }+ if existing, ok := publication.subscriptions[fence.ViewerPeerID]; ok {+ if existing.fence != fence {+ return false+ }+ if existing.state == stateReserved || existing.state == stateCommitted {+ return true+ }+ if publication.state != stateCommitted {+ return false+ }+ existing.state = stateReserved+ return true+ }+ if admission.egressInUse >= admission.egressCapacity {+ return false+ }++ publication.subscriptions[fence.ViewerPeerID] = &subscriptionEntry{+ fence: fence,+ state: stateReserved,+ }+ admission.egressInUse+++ return true+}++// CommitPublication ports commitPublication. The second result is false where+// the TypeScript returns null; an empty slice with true is its empty array.+func (admission *Admission) CommitPublication(fence ResourceFence) ([]ResourceFence, bool) {+ assertFence(fence)+ room, _ := admission.rooms.Get(fence.RoomID)+ var publication *publicationEntry+ if room != nil {+ publication, _ = room.Get(publicationKey(fence))+ }+ if room == nil || publication == nil || publication.fence != fence {+ return nil, false+ }+ if publication.state == stateCommitted {+ return nil, true+ }+ if publication.state != stateReserved {+ return nil, false+ }+ reserved := false+ for _, subscription := range publication.subscriptions {+ if subscription.state == stateReserved {+ reserved = true+ break+ }+ }+ if !reserved {+ return nil, false+ }++ var draining []ResourceFence+ for _, other := range room.All() {+ if other == publication || other.state != stateCommitted {+ continue+ }+ markDraining(other)+ draining = append(draining, other.fence)+ }+ publication.state = stateCommitted+ for _, subscription := range publication.subscriptions {+ if subscription.state == stateReserved {+ subscription.state = stateCommitted+ }+ }+ return draining, true+}++// CommitSubscription ports commitSubscription.+func (admission *Admission) CommitSubscription(fence SubscriptionFence) bool {+ assertSubscriptionFence(fence)+ publication := admission.publication(fence.ResourceFence)+ if publication == nil || publication.state != stateCommitted {+ return false+ }+ subscription, ok := publication.subscriptions[fence.ViewerPeerID]+ if !ok || subscription.fence != fence {+ return false+ }+ if subscription.state == stateCommitted {+ return true+ }+ if subscription.state != stateReserved {+ return false+ }+ subscription.state = stateCommitted+ return true+}++// BeginSubscriptionDrain ports beginSubscriptionDrain.+func (admission *Admission) BeginSubscriptionDrain(fence SubscriptionFence) bool {+ assertSubscriptionFence(fence)+ publication := admission.publication(fence.ResourceFence)+ if publication == nil {+ return false+ }+ subscription, ok := publication.subscriptions[fence.ViewerPeerID]+ if !ok || subscription.fence != fence {+ return false+ }+ subscription.state = stateDraining+ return true+}++// BeginDrain ports beginDrain.+func (admission *Admission) BeginDrain(fence ResourceFence) bool {+ assertFence(fence)+ publication := admission.publication(fence)+ if publication == nil {+ return false+ }+ markDraining(publication)+ return true+}++// CompleteDrain ports completeDrain.+func (admission *Admission) CompleteDrain(fence ResourceFence) bool {+ assertFence(fence)+ room, _ := admission.rooms.Get(fence.RoomID)+ key := publicationKey(fence)+ var publication *publicationEntry+ if room != nil {+ publication, _ = room.Get(key)+ }+ if room == nil || publication == nil ||+ publication.state != stateDraining || publication.fence != fence {+ return false+ }++ room.Delete(key)+ admission.ingressInUse--+ admission.subtractEgress(len(publication.subscriptions))+ admission.assertNoUnderflow()+ if room.Len() == 0 {+ admission.rooms.Delete(fence.RoomID)+ }+ return true+}++// BeginDrainRoom ports beginDrainRoom.+func (admission *Admission) BeginDrainRoom(roomID string) []ResourceFence {+ if roomID == "" {+ panic("SFU resource room ID is invalid")+ }+ room, _ := admission.rooms.Get(roomID)+ if room == nil {+ return nil+ }+ for _, publication := range room.All() {+ markDraining(publication)+ }+ fences := make([]ResourceFence, 0, room.Len())+ for _, publication := range room.All() {+ fences = append(fences, publication.fence)+ }+ return fences+}++// BeginDrainAll ports beginDrainAll.+func (admission *Admission) BeginDrainAll() []ResourceFence {+ var fences []ResourceFence+ for _, roomID := range admission.rooms.Keys() {+ fences = append(fences, admission.BeginDrainRoom(roomID)...)+ }+ return fences+}++// Usage ports usage().+func (admission *Admission) Usage() Usage {+ return Usage{Ingress: admission.ingressInUse, Egress: admission.egressInUse}+}++func (admission *Admission) publication(fence ResourceFence) *publicationEntry {+ room, ok := admission.rooms.Get(fence.RoomID)+ if !ok {+ return nil+ }+ publication, ok := room.Get(publicationKey(fence))+ if !ok || publication.fence != fence {+ return nil+ }+ return publication+}++func (admission *Admission) subtractEgress(count int) {+ admission.egressInUse -= count+ admission.assertNoUnderflow()+}++func (admission *Admission) assertNoUnderflow() {+ if admission.ingressInUse < 0 || admission.egressInUse < 0 {+ panic("SFU resource accounting underflow")+ }+}++func markDraining(publication *publicationEntry) {+ publication.state = stateDraining+ for _, subscription := range publication.subscriptions {+ subscription.state = stateDraining+ }+}++func publicationKey(fence ResourceFence) string {+ return fence.ShareGeneration + "\x00" + fence.PublicationGeneration+}++func assertFence(fence ResourceFence) {+ if fence.RoomID == "" || fence.ShareGeneration == "" ||+ fence.PublicationGeneration == "" {+ panic("SFU resource fence is invalid")+ }+}++func assertSubscriptionFence(fence SubscriptionFence) {+ assertFence(fence.ResourceFence)+ if fence.ViewerPeerID == "" {+ panic("SFU subscription fence is invalid")+ }+}++// assertPositiveSafeInteger ports assertPositiveSafeInteger. Go's int makes the+// TypeScript Number.isSafeInteger fractional case unrepresentable; only the+// range checks survive.+func assertPositiveSafeInteger(value int, name string) {+ if value <= 0 || int64(value) > protocol.MaxSafeInteger {+ panic(name + " must be a positive safe integer")+ }+}++const managedRoomPrefix = "screener-v1."++// roomIDPattern is ROOM_ID_PATTERN, /^[1-9]\d{0,11}$/. Go's \d and $ are the+// ASCII digits and end of text, as they are in a non-unicode, non-multiline+// JavaScript regular expression. OPAQUE_ID_PATTERN is protocol.ValidOpaqueID.+var roomIDPattern = regexp.MustCompile(`^[1-9][0-9]{0,11}$`)++var errInvalidRoomFence = errors.New("Managed LiveKit room fence is invalid")++// ManagedRoomName ports managedSfuRoomName. An invalid fence panics where the+// TypeScript throws, because the router builds room-name keys from it in+// synchronous code that never caught the throw. The RoomService calls, whose+// TypeScript throw was caught by the router, use the error-returning form.+func ManagedRoomName(fence ResourceFence) string {+ name, err := managedRoomName(fence)+ if err != nil {+ panic(err.Error())+ }+ return name+}++func managedRoomName(fence ResourceFence) (string, error) {+ if !roomIDPattern.MatchString(fence.RoomID) ||+ !protocol.ValidOpaqueID(fence.ShareGeneration) ||+ !protocol.ValidOpaqueID(fence.PublicationGeneration) {+ return "", errInvalidRoomFence+ }+ return managedRoomPrefix + fence.RoomID + "." ++ fence.ShareGeneration + "." + fence.PublicationGeneration, nil+}++// IsManagedRoomName ports isManagedSfuRoomName.+func IsManagedRoomName(roomName string) bool {+ rest, ok := strings.CutPrefix(roomName, managedRoomPrefix)+ if !ok {+ return false+ }+ parts := strings.Split(rest, ".")+ return len(parts) == 3 &&+ roomIDPattern.MatchString(parts[0]) &&+ protocol.ValidOpaqueID(parts[1]) &&+ protocol.ValidOpaqueID(parts[2])+}++// viewerIdentity ports managedSfuViewerIdentity.+func viewerIdentity(peerID string) (string, error) {+ if !protocol.ValidOpaqueID(peerID) {+ return "", errors.New("Managed LiveKit Viewer identity is invalid")+ }+ return "viewer:" + peerID, nil+}diff --git a/internal/server/sfu/admission_test.go b/internal/server/sfu/admission_test.gonew file mode 100644index 00000000..7395b15c--- /dev/null+++ b/internal/server/sfu/admission_test.go@@ -0,0 +1,390 @@+package sfu++// Ported from tests/sfu-resource-admission.test.ts.++import (+ "slices"+ "strings"+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++func publicationFence(roomID string, publicationGeneration string) ResourceFence {+ return ResourceFence{+ RoomID: roomID,+ ShareGeneration: "share_" + roomID,+ PublicationGeneration: publicationGeneration,+ }+}++func subscriptionFence(fence ResourceFence, viewerPeerID string) SubscriptionFence {+ return SubscriptionFence{ResourceFence: fence, ViewerPeerID: viewerPeerID}+}++func expectPanic(t *testing.T, want string, run func()) {+ t.Helper()+ defer func() {+ recovered := recover()+ message, _ := recovered.(string)+ if recovered == nil || !strings.Contains(message, want) {+ t.Fatalf("panic = %v, want it to contain %q", recovered, want)+ }+ }()+ run()+}++func expectUsage(t *testing.T, admission *Admission, ingress int, egress int) {+ t.Helper()+ if usage := admission.Usage(); usage != (Usage{Ingress: ingress, Egress: egress}) {+ t.Fatalf("usage = %+v, want {Ingress:%d Egress:%d}", usage, ingress, egress)+ }+}++func expectDrained(t *testing.T, drained []ResourceFence, ok bool, want ...ResourceFence) {+ t.Helper()+ if !ok {+ t.Fatal("commit was refused, want it accepted")+ }+ if !slices.Equal(drained, want) {+ t.Fatalf("drained = %v, want %v", drained, want)+ }+}++func TestAdmissionRequiresExplicitCapacities(t *testing.T) {+ // Number.MAX_SAFE_INTEGER + 1 and 0; the TypeScript third case, 1.5, cannot+ // be expressed by Go's int.+ for _, ingressCapacity := range []int{0, protocol.MaxSafeInteger + 1} {+ expectPanic(t, "positive safe integer", func() {+ NewAdmission(AdmissionOptions{IngressCapacity: ingressCapacity, EgressCapacity: 1})+ })+ }+ expectPanic(t, "positive safe integer", func() {+ NewAdmission(AdmissionOptions{IngressCapacity: 1, EgressCapacity: 0})+ })+}++func TestAdmissionEnforcesIngressAndEgressIndependently(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 2, EgressCapacity: 2})+ first := publicationFence("1", "publication_first")+ second := publicationFence("2", "publication_second")++ if !admission.ReservePublication(first) || !admission.ReservePublication(second) {+ t.Fatal("both publications must fit the ingress capacity")+ }+ if admission.ReservePublication(publicationFence("3", "publication_third")) {+ t.Fatal("a third publication must exceed the ingress capacity")+ }+ if !admission.ReserveSubscription(subscriptionFence(first, "viewer_a")) ||+ !admission.ReserveSubscription(subscriptionFence(first, "viewer_b")) {+ t.Fatal("both subscriptions must fit the egress capacity")+ }+ if admission.ReserveSubscription(subscriptionFence(second, "viewer_c")) {+ t.Fatal("a third subscription must exceed the egress capacity")+ }+ expectUsage(t, admission, 2, 2)+}++func TestAdmissionKeepsExactOperationsIdempotent(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 1, EgressCapacity: 1})+ active := publicationFence("1", "publication_active")+ viewer := subscriptionFence(active, "viewer_a")++ if !admission.ReservePublication(active) || !admission.ReservePublication(active) {+ t.Fatal("an exact publication reservation must be idempotent")+ }+ if !admission.ReserveSubscription(viewer) || !admission.ReserveSubscription(viewer) {+ t.Fatal("an exact subscription reservation must be idempotent")+ }+ if admission.CommitSubscription(viewer) {+ t.Fatal("a subscription must not commit before its publication")+ }+ drained, ok := admission.CommitPublication(active)+ expectDrained(t, drained, ok)+ drained, ok = admission.CommitPublication(active)+ expectDrained(t, drained, ok)+ if !admission.CommitSubscription(viewer) {+ t.Fatal("the exact subscription must commit after its publication")+ }+ expectUsage(t, admission, 1, 1)++ stale := publicationFence("1", "publication_stale")+ if admission.ReserveSubscription(subscriptionFence(stale, "viewer_a")) {+ t.Fatal("a stale generation must not admit a subscription")+ }+ if _, ok := admission.CommitPublication(stale); ok {+ t.Fatal("a stale generation must not commit")+ }+ if admission.CommitSubscription(subscriptionFence(active, "viewer_b")) {+ t.Fatal("an unreserved viewer must not commit")+ }+ if admission.BeginSubscriptionDrain(subscriptionFence(active, "viewer_b")) {+ t.Fatal("an unreserved viewer must not drain")+ }+ if admission.BeginDrain(stale) {+ t.Fatal("a stale generation must not drain")+ }+}++func TestAdmissionDoesNotCommitWithoutFirstSubscription(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 1, EgressCapacity: 1})+ pending := publicationFence("1", "publication_pending")++ if !admission.ReservePublication(pending) {+ t.Fatal("the publication must reserve")+ }+ if _, ok := admission.CommitPublication(pending); ok {+ t.Fatal("a publication without a reserved subscription must not commit")+ }+ if !admission.BeginDrain(pending) || !admission.CompleteDrain(pending) {+ t.Fatal("the reserved publication must drain")+ }+ expectUsage(t, admission, 0, 0)+}++func TestAdmissionCommitsNewGenerationBeforeDrainingTheOld(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 2, EgressCapacity: 3})+ first := publicationFence("1", "publication_first")+ second := publicationFence("1", "publication_second")+ firstViewer := subscriptionFence(first, "viewer_a")++ if !admission.ReservePublication(first) || !admission.ReserveSubscription(firstViewer) {+ t.Fatal("the first generation must reserve")+ }+ drained, ok := admission.CommitPublication(first)+ expectDrained(t, drained, ok)++ if !admission.ReservePublication(second) ||+ !admission.ReserveSubscription(subscriptionFence(second, "viewer_b")) ||+ !admission.ReserveSubscription(subscriptionFence(second, "viewer_c")) {+ t.Fatal("the second generation must reserve alongside the first")+ }+ expectUsage(t, admission, 2, 3)++ drained, ok = admission.CommitPublication(second)+ expectDrained(t, drained, ok, first)+ if !admission.CommitSubscription(subscriptionFence(second, "viewer_b")) {+ t.Fatal("the new generation's subscription must commit")+ }+ if admission.ReservePublication(first) {+ t.Fatal("the draining generation must not be reserved again")+ }+ if admission.ReserveSubscription(firstViewer) {+ t.Fatal("the draining generation must not admit a subscription")+ }++ if !admission.CompleteDrain(first) {+ t.Fatal("the drained generation must complete")+ }+ if admission.CompleteDrain(first) {+ t.Fatal("a completed drain must not repeat")+ }+ expectUsage(t, admission, 1, 2)+}++func TestAdmissionKeepsReleasedReservedSubscriptionCharged(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 1, EgressCapacity: 2})+ active := publicationFence("1", "publication_active")+ first := subscriptionFence(active, "viewer_a")+ candidate := subscriptionFence(active, "viewer_b")++ if !admission.ReservePublication(active) || !admission.ReserveSubscription(first) {+ t.Fatal("the publication and its first viewer must reserve")+ }+ drained, ok := admission.CommitPublication(active)+ expectDrained(t, drained, ok)++ if !admission.ReserveSubscription(candidate) {+ t.Fatal("the candidate must reserve")+ }+ expectUsage(t, admission, 1, 2)+ if !admission.BeginSubscriptionDrain(candidate) ||+ !admission.BeginSubscriptionDrain(candidate) {+ t.Fatal("the subscription drain must be idempotent")+ }+ if admission.CommitSubscription(candidate) {+ t.Fatal("a draining subscription must not commit")+ }+ expectUsage(t, admission, 1, 2)+ if admission.ReserveSubscription(subscriptionFence(active, "viewer_c")) {+ t.Fatal("the draining subscription still holds its egress charge")+ }+ if !admission.BeginDrain(active) || !admission.CompleteDrain(active) {+ t.Fatal("the publication must drain")+ }+ expectUsage(t, admission, 0, 0)+}++func TestAdmissionReactivatesExactDrainingSubscription(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 1, EgressCapacity: 1})+ active := publicationFence("1", "publication_active")+ viewer := subscriptionFence(active, "viewer_a")++ if !admission.ReservePublication(active) || !admission.ReserveSubscription(viewer) {+ t.Fatal("the publication and its viewer must reserve")+ }+ drained, ok := admission.CommitPublication(active)+ expectDrained(t, drained, ok)+ if !admission.BeginSubscriptionDrain(viewer) {+ t.Fatal("the subscription must begin draining")+ }+ expectUsage(t, admission, 1, 1)++ if !admission.ReserveSubscription(viewer) || !admission.ReserveSubscription(viewer) {+ t.Fatal("the exact draining subscription must reactivate")+ }+ expectUsage(t, admission, 1, 1)+ if !admission.BeginSubscriptionDrain(viewer) {+ t.Fatal("the subscription must drain again")+ }+ if admission.ReserveSubscription(subscriptionFence(active, "viewer_b")) {+ t.Fatal("the charge must still block another viewer")+ }+ if !admission.ReserveSubscription(viewer) || !admission.CommitSubscription(viewer) {+ t.Fatal("the exact subscription must reactivate and commit")+ }+ expectUsage(t, admission, 1, 1)+}++func TestAdmissionKeepsDepartedSubscriptionChargedUntilDrainProof(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 1, EgressCapacity: 1})+ active := publicationFence("1", "publication_active")+ viewer := subscriptionFence(active, "viewer_a")++ if !admission.ReservePublication(active) || !admission.ReserveSubscription(viewer) {+ t.Fatal("the publication and its viewer must reserve")+ }+ drained, ok := admission.CommitPublication(active)+ expectDrained(t, drained, ok)+ if !admission.BeginSubscriptionDrain(viewer) {+ t.Fatal("the subscription must begin draining")+ }+ if admission.ReserveSubscription(subscriptionFence(active, "viewer_b")) {+ t.Fatal("the departed viewer still holds its egress charge")+ }+ if !admission.BeginDrain(active) || !admission.BeginDrain(active) {+ t.Fatal("the publication drain must be idempotent")+ }+ expectUsage(t, admission, 1, 1)+ if !admission.CompleteDrain(active) {+ t.Fatal("the publication must complete its drain")+ }+ expectUsage(t, admission, 0, 0)+}++func TestAdmissionDrainsEveryGenerationExactlyOnce(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 3, EgressCapacity: 4})+ active := publicationFence("1", "publication_active")+ replacement := publicationFence("1", "publication_replacement")+ other := publicationFence("2", "publication_other")++ if !admission.ReservePublication(active) ||+ !admission.ReserveSubscription(subscriptionFence(active, "viewer_a")) {+ t.Fatal("the active generation must reserve")+ }+ drained, ok := admission.CommitPublication(active)+ expectDrained(t, drained, ok)+ if !admission.ReservePublication(replacement) ||+ !admission.ReserveSubscription(subscriptionFence(replacement, "viewer_b")) ||+ !admission.ReservePublication(other) ||+ !admission.ReserveSubscription(subscriptionFence(other, "viewer_c")) {+ t.Fatal("the replacement and the other room must reserve")+ }++ // Insertion order, not map order: the drain tasks are created from it.+ firstRoom := admission.BeginDrainRoom("1")+ if !slices.Equal(firstRoom, []ResourceFence{active, replacement}) {+ t.Fatalf("beginDrainRoom = %v, want [active replacement]", firstRoom)+ }+ if repeated := admission.BeginDrainRoom("1"); !slices.Equal(repeated, firstRoom) {+ t.Fatalf("repeated beginDrainRoom = %v, want %v", repeated, firstRoom)+ }+ all := admission.BeginDrainAll()+ if !slices.Equal(all, []ResourceFence{active, replacement, other}) {+ t.Fatalf("beginDrainAll = %v, want [active replacement other]", all)+ }+ expectUsage(t, admission, 3, 3)++ for _, fence := range []ResourceFence{active, replacement, other} {+ if !admission.CompleteDrain(fence) {+ t.Fatalf("%s must complete its drain", fence.PublicationGeneration)+ }+ if admission.CompleteDrain(fence) {+ t.Fatalf("%s must not complete twice", fence.PublicationGeneration)+ }+ }+ expectUsage(t, admission, 0, 0)+}++func TestAdmissionRejectsInvalidFences(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 1, EgressCapacity: 1})+ valid := publicationFence("1", "publication_active")++ expectPanic(t, "SFU resource fence is invalid", func() {+ admission.ReservePublication(ResourceFence{ShareGeneration: "s", PublicationGeneration: "p"})+ })+ expectPanic(t, "SFU resource fence is invalid", func() {+ admission.BeginDrain(ResourceFence{RoomID: "1", PublicationGeneration: "p"})+ })+ expectPanic(t, "SFU subscription fence is invalid", func() {+ admission.ReserveSubscription(subscriptionFence(valid, ""))+ })+ expectPanic(t, "SFU resource room ID is invalid", func() {+ admission.BeginDrainRoom("")+ })+}++// TestAdmissionAssertsNoUnderflow reaches the accounting assertion the public+// state machine cannot reach, by corrupting the egress counter first.+func TestAdmissionAssertsNoUnderflow(t *testing.T) {+ admission := NewAdmission(AdmissionOptions{IngressCapacity: 1, EgressCapacity: 1})+ active := publicationFence("1", "publication_active")+ if !admission.ReservePublication(active) ||+ !admission.ReserveSubscription(subscriptionFence(active, "viewer_a")) ||+ !admission.BeginDrain(active) {+ t.Fatal("the publication must reserve and drain")+ }+ admission.egressInUse = 0+ expectPanic(t, "SFU resource accounting underflow", func() {+ admission.CompleteDrain(active)+ })+}++func TestManagedRoomName(t *testing.T) {+ fence := ResourceFence{+ RoomID: "42",+ ShareGeneration: "share_generation_12345678",+ PublicationGeneration: "publication_generation_12345678",+ }+ name := ManagedRoomName(fence)+ const want = "screener-v1.42.share_generation_12345678.publication_generation_12345678"+ if name != want {+ t.Fatalf("ManagedRoomName = %q, want %q", name, want)+ }+ if !IsManagedRoomName(name) {+ t.Fatal("the generated name must be managed")+ }++ for _, roomName := range []string{+ "screener-v1.42.bad.segment.extra",+ "another-application",+ "screener-v1.42.share_generation_12345678",+ "screener-v1.042.share_generation_12345678.publication_generation_12345678",+ "screener-v1.1234567890123.share_generation_12345678.publication_generation_12345678",+ "screener-v1.42.short.publication_generation_12345678",+ } {+ if IsManagedRoomName(roomName) {+ t.Fatalf("%q must not be a managed room name", roomName)+ }+ }++ for _, invalid := range []ResourceFence{+ {RoomID: "0", ShareGeneration: "share_generation_12345678", PublicationGeneration: "publication_generation_12345678"},+ {RoomID: "42", ShareGeneration: "has.dot.12345678", PublicationGeneration: "publication_generation_12345678"},+ {RoomID: "42", ShareGeneration: "share_generation_12345678", PublicationGeneration: "short"},+ } {+ expectPanic(t, "Managed LiveKit room fence is invalid", func() {+ ManagedRoomName(invalid)+ })+ }+}diff --git a/internal/server/sfu/roomcontrol.go b/internal/server/sfu/roomcontrol.gonew file mode 100644index 00000000..0c72ec95--- /dev/null+++ b/internal/server/sfu/roomcontrol.go@@ -0,0 +1,189 @@+package sfu++// Ported from src/server/sfu-room-control.ts.++import (+ "context"+ "errors"+)++// RoomControl is SfuRoomControl. Every method performs network I/O, so it must+// be called with the signaling server's mutex released.+type RoomControl interface {+ Initialize(ctx context.Context) error+ CreateRoom(ctx context.Context, fence ResourceFence) error+ DeleteRoom(ctx context.Context, fence ResourceFence) error+ DrainSubscription(ctx context.Context, fence SubscriptionFence) error+ HostParticipantExists(ctx context.Context, fence ResourceFence) (bool, error)+}++// LiveKitRoomControlOptions is LiveKitSfuRoomControlOptions minus the injected+// roomService: the tests drive a real Twirp client against httptest.+type LiveKitRoomControlOptions struct {+ APIURL string+ APIKey string+ APISecret string+ MaxViewersPerRoom int+}++// LiveKitRoomControl is LiveKitSfuRoomControl. It holds no state of its own:+// the TypeScript per-room-name operation queue moved to the router, which+// reserves each managed room's turn while the signaling mutex is still held+// and so orders the mutating calls by the decision that made them.+type LiveKitRoomControl struct {+ service roomService+ maxParticipants int+}++var _ RoomControl = (*LiveKitRoomControl)(nil)++// NewLiveKitRoomControl mirrors the LiveKitSfuRoomControl constructor.+func NewLiveKitRoomControl(options LiveKitRoomControlOptions) (*LiveKitRoomControl, error) {+ if options.APIURL == "" || options.APIKey == "" ||+ len(options.APISecret) < minAPISecretBytes {+ return nil, errors.New("LiveKit RoomService configuration is invalid")+ }+ if err := validateViewerLimit(options.MaxViewersPerRoom); err != nil {+ return nil, err+ }+ return &LiveKitRoomControl{+ service: newRoomService(options.APIURL, newSigner(options.APIKey, options.APISecret)),+ maxParticipants: options.MaxViewersPerRoom + 1,+ }, nil+}++// Initialize ports initialize(): it deletes in the order listRooms returned.+func (control *LiveKitRoomControl) Initialize(ctx context.Context) error {+ rooms, err := control.service.listRooms(ctx, nil)+ if err != nil {+ return err+ }+ for _, room := range rooms {+ if !IsManagedRoomName(room.Name) {+ return errors.New("Dedicated LiveKit instance contains a foreign room")+ }+ }+ for _, room := range rooms {+ if err := control.deleteRoomByName(ctx, room.Name); err != nil {+ return err+ }+ }+ remaining, err := control.service.listRooms(ctx, nil)+ if err != nil {+ return err+ }+ if len(remaining) != 0 {+ return errors.New("Dedicated LiveKit instance is not empty after startup drain")+ }+ return nil+}++// CreateRoom ports createRoom().+func (control *LiveKitRoomControl) CreateRoom(ctx context.Context, fence ResourceFence) error {+ roomName, err := managedRoomName(fence)+ if err != nil {+ return err+ }+ existing, err := control.service.listRooms(ctx, []string{roomName})+ if err != nil {+ return err+ }+ if len(existing) != 0 {+ return errors.New("Managed LiveKit room already exists")+ }+ if err := control.service.createRoom(ctx, roomName, control.maxParticipants); err != nil {+ return err+ }+ rooms, err := control.service.listRooms(ctx, []string{roomName})+ if err != nil {+ return err+ }+ if len(rooms) != 1 || rooms[0].Name != roomName {+ return errors.New("Managed LiveKit room creation was not confirmed")+ }+ return nil+}++// DeleteRoom ports deleteRoom().+func (control *LiveKitRoomControl) DeleteRoom(ctx context.Context, fence ResourceFence) error {+ roomName, err := managedRoomName(fence)+ if err != nil {+ return err+ }+ if err := control.deleteRoomByName(ctx, roomName); err != nil {+ return err+ }+ rooms, err := control.service.listRooms(ctx, []string{roomName})+ if err != nil {+ return err+ }+ if len(rooms) != 0 {+ return errors.New("Managed LiveKit room deletion was not confirmed")+ }+ return nil+}++// DrainSubscription ports drainSubscription().+func (control *LiveKitRoomControl) DrainSubscription(ctx context.Context, fence SubscriptionFence) error {+ roomName, err := managedRoomName(fence.ResourceFence)+ if err != nil {+ return err+ }+ identity, err := viewerIdentity(fence.ViewerPeerID)+ if err != nil {+ return err+ }+ if err := control.service.removeParticipant(ctx, roomName, identity); err != nil &&+ !isNotFound(err) {+ return err+ }+ exists, err := control.participantExists(ctx, roomName, identity)+ if err != nil {+ return err+ }+ if exists {+ return errors.New("Managed LiveKit participant removal was not confirmed")+ }+ return nil+}++// HostParticipantExists ports hostParticipantExists().+func (control *LiveKitRoomControl) HostParticipantExists(+ ctx context.Context,+ fence ResourceFence,+) (bool, error) {+ roomName, err := managedRoomName(fence)+ if err != nil {+ return false, err+ }+ return control.participantExists(ctx, roomName, "host")+}++// deleteRoomByName ports deleteRoomByName(): a missing room is not an error.+func (control *LiveKitRoomControl) deleteRoomByName(ctx context.Context, roomName string) error {+ if err := control.service.deleteRoom(ctx, roomName); err != nil && !isNotFound(err) {+ return err+ }+ return nil+}++// participantExists ports participantExists(): an absent room reads as absent.+func (control *LiveKitRoomControl) participantExists(+ ctx context.Context,+ roomName string,+ identity string,+) (bool, error) {+ participants, err := control.service.listParticipants(ctx, roomName)+ if err != nil {+ if isNotFound(err) {+ return false, nil+ }+ return false, err+ }+ for _, participant := range participants {+ if participant.Identity == identity {+ return true, nil+ }+ }+ return false, nil+}diff --git a/internal/server/sfu/roomcontrol_test.go b/internal/server/sfu/roomcontrol_test.gonew file mode 100644index 00000000..422e6182--- /dev/null+++ b/internal/server/sfu/roomcontrol_test.go@@ -0,0 +1,438 @@+package sfu++// Ported from tests/sfu-room-control.test.ts. The TypeScript injected a+// FakeRoomService; here the real Twirp client runs against an httptest server+// that reproduces that fake's behaviour, so the wire contract recorded in+// evidence/livekit.md section 3 is covered by the same scenarios.++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "regexp"+ "slices"+ "strings"+ "sync"+ "testing"++ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+)++// fakeLiveKit is tests/sfu-room-control.test.ts's FakeRoomService behind the+// real Twirp endpoints.+type fakeLiveKit struct {+ mu sync.Mutex+ // Ordering site: listRooms answers in insertion order, which initialize+ // turns into its delete order.+ rooms ordered.Map[string, map[string]struct{}]+ // operations records the mutating calls, as the TypeScript fake did;+ // listCalls counts the reads it did not record.+ operations []string+ listCalls int+ createOptions []int+ retainDeletedRoom bool+ retainRemovedParticipant bool+}++func newFakeLiveKit(t *testing.T) (*fakeLiveKit, string) {+ t.Helper()+ fake := &fakeLiveKit{}+ server := httptest.NewServer(http.HandlerFunc(fake.serve))+ t.Cleanup(server.Close)+ return fake, server.URL+}++func (fake *fakeLiveKit) serve(writer http.ResponseWriter, request *http.Request) {+ var body struct {+ Name string `json:"name"`+ Names []string `json:"names"`+ Room string `json:"room"`+ Identity string `json:"identity"`+ MaxParticipants int `json:"maxParticipants"`+ }+ _ = json.NewDecoder(request.Body).Decode(&body)+ method := request.URL.Path[strings.LastIndexByte(request.URL.Path, '/')+1:]++ status, payload := http.StatusOK, "{}"+ switch method {+ case "ListRooms":+ payload = fake.listRooms(body.Names)+ case "CreateRoom":+ status, payload = fake.createRoom(body.Name, body.MaxParticipants)+ case "DeleteRoom":+ status, payload = fake.deleteRoom(body.Room)+ case "ListParticipants":+ status, payload = fake.listParticipants(body.Room)+ case "RemoveParticipant":+ status, payload = fake.removeParticipant(body.Room, body.Identity)+ default:+ status, payload = http.StatusNotFound, `{"code":"bad_route","msg":"unknown method"}`+ }+ writer.Header().Set("Content-Type", "application/json")+ writer.WriteHeader(status)+ _, _ = writer.Write([]byte(payload))+}++const notFoundBody = `{"code":"not_found","msg":"missing"}`++func (fake *fakeLiveKit) listRooms(names []string) string {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.listCalls+++ selected := make([]string, 0, fake.rooms.Len())+ for _, name := range fake.rooms.Keys() {+ if len(names) == 0 || slices.Contains(names, name) {+ selected = append(selected, `{"name":`+quote(name)+`}`)+ }+ }+ return `{"rooms":[` + strings.Join(selected, ",") + `]}`+}++func (fake *fakeLiveKit) createRoom(name string, maxParticipants int) (int, string) {+ fake.mu.Lock()+ fake.operations = append(fake.operations, "create:"+name)+ fake.createOptions = append(fake.createOptions, maxParticipants)+ defer fake.mu.Unlock()+ if fake.rooms.Has(name) {+ return http.StatusConflict, `{"code":"already_exists","msg":"room already exists"}`+ }+ fake.rooms.Set(name, map[string]struct{}{})+ return http.StatusOK, `{"name":` + quote(name) + `}`+}++func (fake *fakeLiveKit) deleteRoom(room string) (int, string) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.operations = append(fake.operations, "delete:"+room)+ if !fake.rooms.Has(room) {+ return http.StatusNotFound, notFoundBody+ }+ if !fake.retainDeletedRoom {+ fake.rooms.Delete(room)+ }+ return http.StatusOK, "{}"+}++func (fake *fakeLiveKit) listParticipants(room string) (int, string) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ participants, ok := fake.rooms.Get(room)+ if !ok {+ return http.StatusNotFound, notFoundBody+ }+ records := make([]string, 0, len(participants))+ for identity := range participants {+ records = append(records, `{"identity":`+quote(identity)+`}`)+ }+ return http.StatusOK, `{"participants":[` + strings.Join(records, ",") + `]}`+}++func (fake *fakeLiveKit) removeParticipant(room string, identity string) (int, string) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.operations = append(fake.operations, "remove:"+room+":"+identity)+ participants, ok := fake.rooms.Get(room)+ if !ok {+ return http.StatusNotFound, notFoundBody+ }+ if _, joined := participants[identity]; !joined {+ return http.StatusNotFound, notFoundBody+ }+ if !fake.retainRemovedParticipant {+ delete(participants, identity)+ }+ return http.StatusOK, "{}"+}++// join is the TypeScript fake's join(): it fails when the room is absent.+func (fake *fakeLiveKit) join(room string, identity string) bool {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ participants, ok := fake.rooms.Get(room)+ if !ok {+ return false+ }+ participants[identity] = struct{}{}+ return true+}++func (fake *fakeLiveKit) seed(room string, identities ...string) {+ participants := make(map[string]struct{}, len(identities))+ for _, identity := range identities {+ participants[identity] = struct{}{}+ }+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.rooms.Set(room, participants)+}++func (fake *fakeLiveKit) snapshot() ([]string, []string) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ return fake.rooms.Keys(), append([]string(nil), fake.operations...)+}++func (fake *fakeLiveKit) operationLog() []string {+ _, operations := fake.snapshot()+ return operations+}++func (fake *fakeLiveKit) participants(room string) []string {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ found, ok := fake.rooms.Get(room)+ if !ok {+ return nil+ }+ identities := make([]string, 0, len(found))+ for identity := range found {+ identities = append(identities, identity)+ }+ slices.Sort(identities)+ return identities+}++func quote(value string) string {+ encoded, err := json.Marshal(value)+ if err != nil {+ panic(err)+ }+ return string(encoded)+}++func testControl(t *testing.T, apiURL string) *LiveKitRoomControl {+ t.Helper()+ control, err := NewLiveKitRoomControl(LiveKitRoomControlOptions{+ APIURL: apiURL,+ APIKey: testAPIKey,+ APISecret: testAPISecret,+ MaxViewersPerRoom: 8,+ })+ if err != nil {+ t.Fatalf("NewLiveKitRoomControl: %v", err)+ }+ return control+}++func testFence() ResourceFence {+ return ResourceFence{+ RoomID: "42",+ ShareGeneration: testShareGeneration,+ PublicationGeneration: "publication_generation_12345678",+ }+}++func TestRoomControlDrainsManagedRoomsBeforeStartup(t *testing.T) {+ fake, apiURL := newFakeLiveKit(t)+ current := ManagedRoomName(testFence())+ fake.seed(current, "host")++ if err := testControl(t, apiURL).Initialize(context.Background()); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ rooms, operations := fake.snapshot()+ if len(rooms) != 0 {+ t.Fatalf("rooms = %v, want none", rooms)+ }+ if !slices.Equal(operations, []string{"delete:" + current}) {+ t.Fatalf("operations = %v", operations)+ }+}++func TestRoomControlRejectsForeignInstanceAndUnconfirmedDrain(t *testing.T) {+ foreign, foreignURL := newFakeLiveKit(t)+ foreign.seed("another-application")+ err := testControl(t, foreignURL).Initialize(context.Background())+ if err == nil || !strings.Contains(err.Error(), "foreign room") {+ t.Fatalf("Initialize error = %v, want a foreign room refusal", err)+ }+ if operations := foreign.operationLog(); len(operations) != 0 {+ t.Fatalf("operations = %v, want none", operations)+ }++ retained, retainedURL := newFakeLiveKit(t)+ retained.retainDeletedRoom = true+ retained.seed(ManagedRoomName(testFence()))+ err = testControl(t, retainedURL).Initialize(context.Background())+ if err == nil || !strings.Contains(err.Error(), "not empty after startup drain") {+ t.Fatalf("Initialize error = %v, want an unconfirmed drain", err)+ }+}++// TestRoomControlInitializeAcceptsAnEmptyNamespace pins the confirmation call+// itself: an already empty instance still asks a second time.+func TestRoomControlInitializeAcceptsAnEmptyNamespace(t *testing.T) {+ fake, apiURL := newFakeLiveKit(t)+ if err := testControl(t, apiURL).Initialize(context.Background()); err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ if operations := fake.operationLog(); len(operations) != 0 {+ t.Fatalf("operations = %v, want none", operations)+ }+ fake.mu.Lock()+ defer fake.mu.Unlock()+ if fake.listCalls != 2 {+ t.Fatalf("listRooms calls = %d, want the drain and its confirmation", fake.listCalls)+ }+}++func TestRoomControlRejectsOffLedgerRoom(t *testing.T) {+ fake, apiURL := newFakeLiveKit(t)+ fence := testFence()+ fake.seed(ManagedRoomName(fence), "host")++ err := testControl(t, apiURL).CreateRoom(context.Background(), fence)+ if err == nil || !strings.Contains(err.Error(), "already exists") {+ t.Fatalf("CreateRoom error = %v, want an existing-room refusal", err)+ }+ if operations := fake.operationLog(); len(operations) != 0 {+ t.Fatalf("operations = %v, want none", operations)+ }+}++func TestRoomControlChecksExactHostParticipant(t *testing.T) {+ fake, apiURL := newFakeLiveKit(t)+ control := testControl(t, apiURL)+ fence := testFence()+ ctx := context.Background()+ if err := control.CreateRoom(ctx, fence); err != nil {+ t.Fatalf("CreateRoom: %v", err)+ }+ roomName := ManagedRoomName(fence)++ if !fake.join(roomName, "viewer:one") {+ t.Fatal("the viewer must join")+ }+ expectHost(t, control, fence, false)+ if !fake.join(roomName, "host") {+ t.Fatal("the host must join")+ }+ expectHost(t, control, fence, true)+ if err := control.DeleteRoom(ctx, fence); err != nil {+ t.Fatalf("DeleteRoom: %v", err)+ }+ // An absent room reads as an offline host, not as an error.+ expectHost(t, control, fence, false)+}++func TestRoomControlRemovesOnlyTheExactViewer(t *testing.T) {+ fake, apiURL := newFakeLiveKit(t)+ control := testControl(t, apiURL)+ fence := testFence()+ ctx := context.Background()+ if err := control.CreateRoom(ctx, fence); err != nil {+ t.Fatalf("CreateRoom: %v", err)+ }+ roomName := ManagedRoomName(fence)+ const viewerPeerID = "viewer_peer_12345678"+ for _, identity := range []string{"host", "viewer:" + viewerPeerID, "viewer:other_peer_12345678"} {+ if !fake.join(roomName, identity) {+ t.Fatalf("%s must join", identity)+ }+ }++ subscription := SubscriptionFence{ResourceFence: fence, ViewerPeerID: viewerPeerID}+ if err := control.DrainSubscription(ctx, subscription); err != nil {+ t.Fatalf("DrainSubscription: %v", err)+ }+ if participants := fake.participants(roomName); !slices.Equal(participants,+ []string{"host", "viewer:other_peer_12345678"}) {+ t.Fatalf("participants = %v", participants)+ }+ // The repeat drain is a not-found removal, which is tolerated.+ if err := control.DrainSubscription(ctx, subscription); err != nil {+ t.Fatalf("repeat DrainSubscription: %v", err)+ }+}++func TestRoomControlRejectsUnconfirmedViewerDrain(t *testing.T) {+ fake, apiURL := newFakeLiveKit(t)+ control := testControl(t, apiURL)+ fence := testFence()+ ctx := context.Background()+ if err := control.CreateRoom(ctx, fence); err != nil {+ t.Fatalf("CreateRoom: %v", err)+ }+ const viewerPeerID = "viewer_peer_12345678"+ fake.join(ManagedRoomName(fence), "viewer:"+viewerPeerID)+ fake.mu.Lock()+ fake.retainRemovedParticipant = true+ fake.mu.Unlock()++ err := control.DrainSubscription(ctx,+ SubscriptionFence{ResourceFence: fence, ViewerPeerID: viewerPeerID})+ if err == nil || !strings.Contains(err.Error(), "removal was not confirmed") {+ t.Fatalf("DrainSubscription error = %v, want an unconfirmed removal", err)+ }+}++func TestRoomControlRejectsInvalidConfiguration(t *testing.T) {+ for name, options := range map[string]LiveKitRoomControlOptions{+ "no url": {APIURL: "", APIKey: testAPIKey, APISecret: testAPISecret, MaxViewersPerRoom: 8},+ "no key": {APIURL: "http://127.0.0.1:7880", APIKey: "", APISecret: testAPISecret, MaxViewersPerRoom: 8},+ "short secret": {APIURL: "http://127.0.0.1:7880", APIKey: testAPIKey, APISecret: strings.Repeat("s", 31), MaxViewersPerRoom: 8},+ "no viewers": {APIURL: "http://127.0.0.1:7880", APIKey: testAPIKey, APISecret: testAPISecret, MaxViewersPerRoom: 0},+ "too many viewers": {+ APIURL: "http://127.0.0.1:7880", APIKey: testAPIKey,+ APISecret: testAPISecret, MaxViewersPerRoom: 21,+ },+ } {+ if _, err := NewLiveKitRoomControl(options); err == nil {+ t.Fatalf("%s: want a rejection", name)+ }+ }++ // An invalid fence is refused without touching the service.+ fake, apiURL := newFakeLiveKit(t)+ control := testControl(t, apiURL)+ broken := ResourceFence{RoomID: "0", ShareGeneration: testShareGeneration,+ PublicationGeneration: "publication_generation_12345678"}+ if err := control.CreateRoom(context.Background(), broken); err == nil {+ t.Fatal("an invalid fence must be refused")+ }+ if err := control.DrainSubscription(context.Background(), SubscriptionFence{+ ResourceFence: testFence(), ViewerPeerID: "short",+ }); err == nil {+ t.Fatal("an invalid viewer identity must be refused")+ }+ if operations := fake.operationLog(); len(operations) != 0 {+ t.Fatalf("operations = %v, want none", operations)+ }+}++// TestRoomControlPropagatesContextCancellation covers the ctx plumbing that+// carries the 5 second per-request timeout.+func TestRoomControlPropagatesContextCancellation(t *testing.T) {+ _, apiURL := newFakeLiveKit(t)+ control := testControl(t, apiURL)+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ if err := control.CreateRoom(ctx, testFence()); err == nil {+ t.Fatal("a cancelled context must abort the call")+ }+}++// TestRoomControlAutoCreateStaysDisabled keeps the deployment contract the+// TypeScript suite asserted next to these scenarios.+func TestRoomControlAutoCreateStaysDisabled(t *testing.T) {+ configuration, err := os.ReadFile("../../../deploy/livekit/livekit.yaml.example")+ if err != nil {+ t.Fatalf("read livekit.yaml.example: %v", err)+ }+ if !regexp.MustCompile(`(?s)room:\s+.*auto_create: false`).Match(configuration) {+ t.Fatal("the tracked LiveKit deployment must keep auto_create disabled")+ }+}++func expectHost(t *testing.T, control *LiveKitRoomControl, fence ResourceFence, want bool) {+ t.Helper()+ exists, err := control.HostParticipantExists(context.Background(), fence)+ if err != nil {+ t.Fatalf("HostParticipantExists: %v", err)+ }+ if exists != want {+ t.Fatalf("HostParticipantExists = %v, want %v", exists, want)+ }+}diff --git a/internal/server/sfu/roomservice.go b/internal/server/sfu/roomservice.gonew file mode 100644index 00000000..87657d93--- /dev/null+++ b/internal/server/sfu/roomservice.go@@ -0,0 +1,188 @@+package sfu++// Twirp/JSON client for livekit.RoomService, covering exactly the five RPCs+// src/server/sfu-room-control.ts used through RoomServiceClient. The wire+// contract is evidence/livekit.md section 3.++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"+)++const (+ // requestTimeout is RoomServiceClient's `requestTimeout: 5`, applied per+ // HTTP request. There is no retry and no failover.+ requestTimeout = 5 * time.Second+ twirpPathPrefix = "/twirp/livekit.RoomService/"+ // maxResponseBytes bounds a hostile or broken RoomService reply; the four+ // decoded shapes are tiny.+ maxResponseBytes = 1 << 20+)++// twirpError is the Twirp JSON error body {"code":..,"msg":..} plus the HTTP+// status. It is unexported on purpose: the only question the server ever asks+// is isNotFound, and the body must never be logged.+type twirpError struct {+ status int+ code string+ message string+}++func (failure *twirpError) Error() string {+ return fmt.Sprintf("livekit %s: %s (HTTP %d)",+ failure.code, failure.message, failure.status)+}++// isNotFound ports isNotFound(): HTTP 404 or the twirp code "not_found", and+// nothing else, so a 409 already_exists still propagates.+func isNotFound(err error) bool {+ var failure *twirpError+ return errors.As(err, &failure) &&+ (failure.status == http.StatusNotFound || failure.code == "not_found")+}++type roomRecord struct {+ Name string `json:"name"`+}++type participantRecord struct {+ Identity string `json:"identity"`+}++// roomService is the LiveKitRoomService interface of the TypeScript, bound to+// the real RoomService rather than to an injected double.+type roomService struct {+ baseURL string+ signer signer+}++// newRoomService applies TwirpRpc's ws->http host rewrite and drops a trailing+// slash so the path prefix below is exact.+func newRoomService(apiURL string, credentials signer) roomService {+ if strings.HasPrefix(apiURL, "ws") {+ apiURL = "http" + strings.TrimPrefix(apiURL, "ws")+ }+ return roomService{baseURL: strings.TrimSuffix(apiURL, "/"), signer: credentials}+}++func (service roomService) call(+ ctx context.Context,+ method string,+ grant videoGrant,+ request any,+ response any,+) error {+ body, err := json.Marshal(request)+ if err != nil {+ return err+ }+ token, err := service.signer.serviceToken(grant)+ if err != nil {+ return err+ }+ ctx, cancel := context.WithTimeout(ctx, requestTimeout)+ defer cancel()+ httpRequest, err := http.NewRequestWithContext(ctx, http.MethodPost,+ service.baseURL+twirpPathPrefix+method, bytes.NewReader(body))+ if err != nil {+ return err+ }+ httpRequest.Header.Set("Content-Type", "application/json;charset=UTF-8")+ httpRequest.Header.Set("Authorization", "Bearer "+token)+ httpResponse, err := http.DefaultClient.Do(httpRequest)+ if err != nil {+ return err+ }+ defer httpResponse.Body.Close()+ payload, err := io.ReadAll(io.LimitReader(httpResponse.Body, maxResponseBytes))+ if err != nil {+ return err+ }+ if httpResponse.StatusCode < 200 || httpResponse.StatusCode >= 300 {+ return newTwirpError(httpResponse, payload)+ }+ if response == nil {+ return nil+ }+ return json.Unmarshal(payload, response)+}++// newTwirpError decodes {"code","msg"} when the reply claims JSON. LiveKit's+// own 401 is plain text or {"Error":...}, which keeps code empty and so is not+// a not-found, exactly as the TypeScript SDK behaved.+func newTwirpError(response *http.Response, payload []byte) *twirpError {+ failure := &twirpError{status: response.StatusCode, message: "Unknown internal error"}+ if strings.HasPrefix(response.Header.Get("Content-Type"), "application/json") {+ var body struct {+ Code string `json:"code"`+ Msg string `json:"msg"`+ }+ if json.Unmarshal(payload, &body) == nil && body.Code != "" {+ failure.code = body.Code+ failure.message = body.Msg+ }+ }+ return failure+}++func (service roomService) listRooms(ctx context.Context, names []string) ([]roomRecord, error) {+ // protobuf-es omits an empty repeated field, so an unfiltered list sends {}.+ request := struct {+ Names []string `json:"names,omitempty"`+ }{Names: names}+ var response struct {+ Rooms []roomRecord `json:"rooms"`+ }+ if err := service.call(ctx, "ListRooms",+ videoGrant{RoomList: true}, request, &response); err != nil {+ return nil, err+ }+ return response.Rooms, nil+}++func (service roomService) createRoom(ctx context.Context, room string, maxParticipants int) error {+ request := struct {+ Name string `json:"name"`+ MaxParticipants int `json:"maxParticipants"`+ }{Name: room, MaxParticipants: maxParticipants}+ // The TypeScript discarded the returned Room record.+ return service.call(ctx, "CreateRoom", videoGrant{RoomCreate: true}, request, nil)+}++func (service roomService) deleteRoom(ctx context.Context, room string) error {+ request := struct {+ Room string `json:"room"`+ }{Room: room}+ return service.call(ctx, "DeleteRoom", videoGrant{RoomCreate: true}, request, nil)+}++func (service roomService) listParticipants(ctx context.Context, room string) ([]participantRecord, error) {+ request := struct {+ Room string `json:"room"`+ }{Room: room}+ var response struct {+ Participants []participantRecord `json:"participants"`+ }+ if err := service.call(ctx, "ListParticipants",+ videoGrant{RoomAdmin: true, Room: room}, request, &response); err != nil {+ return nil, err+ }+ return response.Participants, nil+}++func (service roomService) removeParticipant(ctx context.Context, room string, identity string) error {+ // revokeTokenTs stays absent, as the TypeScript passed undefined.+ request := struct {+ Room string `json:"room"`+ Identity string `json:"identity"`+ }{Room: room, Identity: identity}+ return service.call(ctx, "RemoveParticipant",+ videoGrant{RoomAdmin: true, Room: room}, request, nil)+}diff --git a/internal/server/sfu/roomservice_test.go b/internal/server/sfu/roomservice_test.gonew file mode 100644index 00000000..3f6c45c5--- /dev/null+++ b/internal/server/sfu/roomservice_test.go@@ -0,0 +1,178 @@+package sfu++// The Twirp wire contract recorded in evidence/livekit.md section 3: request+// path, method, headers, body and per-call service-token grant for each of the+// five RPCs, plus the exact not-found rule.++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "testing"+)++type capturedCall struct {+ path string+ method string+ contentType string+ authorized string+ body map[string]any+}++func captureLiveKit(+ t *testing.T,+ reply func(method string) (int, string, string),+) (*[]capturedCall, string) {+ t.Helper()+ var calls []capturedCall+ server := httptest.NewServer(http.HandlerFunc(+ func(writer http.ResponseWriter, request *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(request.Body).Decode(&body)+ if body == nil {+ body = map[string]any{}+ }+ calls = append(calls, capturedCall{+ path: request.URL.Path,+ method: request.Method,+ contentType: request.Header.Get("Content-Type"),+ authorized: request.Header.Get("Authorization"),+ body: body,+ })+ name := request.URL.Path[strings.LastIndexByte(request.URL.Path, '/')+1:]+ status, contentType, payload := reply(name)+ writer.Header().Set("Content-Type", contentType)+ writer.WriteHeader(status)+ _, _ = writer.Write([]byte(payload))+ }))+ t.Cleanup(server.Close)+ return &calls, server.URL+}++func TestRoomServiceRequestShape(t *testing.T) {+ const room = "screener-v1.42.a_1234567.b_1234567"+ calls, apiURL := captureLiveKit(t, func(method string) (int, string, string) {+ switch method {+ case "ListRooms":+ return 200, "application/json", `{"rooms":[{"sid":"RM_x","name":"` + room + `","empty_timeout":0}]}`+ case "ListParticipants":+ return 200, "application/json", `{"participants":[{"sid":"PA_x","identity":"host","state":"ACTIVE"}]}`+ default:+ return 200, "application/json", `{}`+ }+ })+ // The ws->http rewrite of TwirpRpc, exercised on the way in.+ service := newRoomService(strings.Replace(apiURL, "http", "ws", 1),+ newSigner(testAPIKey, testAPISecret))+ ctx := context.Background()++ if _, err := service.listRooms(ctx, nil); err != nil {+ t.Fatalf("listRooms: %v", err)+ }+ if _, err := service.listRooms(ctx, []string{room}); err != nil {+ t.Fatalf("filtered listRooms: %v", err)+ }+ if err := service.createRoom(ctx, room, 9); err != nil {+ t.Fatalf("createRoom: %v", err)+ }+ if err := service.deleteRoom(ctx, room); err != nil {+ t.Fatalf("deleteRoom: %v", err)+ }+ participants, err := service.listParticipants(ctx, room)+ if err != nil {+ t.Fatalf("listParticipants: %v", err)+ }+ if len(participants) != 1 || participants[0].Identity != "host" {+ t.Fatalf("participants = %v", participants)+ }+ if err := service.removeParticipant(ctx, room, "viewer:viewer_peer_12345678"); err != nil {+ t.Fatalf("removeParticipant: %v", err)+ }++ wanted := []struct {+ path string+ body map[string]any+ grant map[string]any+ }{+ {"ListRooms", map[string]any{}, map[string]any{"roomList": true}},+ {"ListRooms", map[string]any{"names": []any{room}}, map[string]any{"roomList": true}},+ {"CreateRoom", map[string]any{"name": room, "maxParticipants": float64(9)},+ map[string]any{"roomCreate": true}},+ {"DeleteRoom", map[string]any{"room": room}, map[string]any{"roomCreate": true}},+ {"ListParticipants", map[string]any{"room": room},+ map[string]any{"roomAdmin": true, "room": room}},+ {"RemoveParticipant", map[string]any{"room": room, "identity": "viewer:viewer_peer_12345678"},+ map[string]any{"roomAdmin": true, "room": room}},+ }+ if len(*calls) != len(wanted) {+ t.Fatalf("calls = %d, want %d", len(*calls), len(wanted))+ }+ for index, call := range *calls {+ want := wanted[index]+ if call.path != "/twirp/livekit.RoomService/"+want.path {+ t.Fatalf("call %d path = %s", index, call.path)+ }+ if call.method != http.MethodPost {+ t.Fatalf("call %d method = %s", index, call.method)+ }+ if call.contentType != "application/json;charset=UTF-8" {+ t.Fatalf("call %d content-type = %q", index, call.contentType)+ }+ if !strings.HasPrefix(call.authorized, "Bearer ") {+ t.Fatalf("call %d authorization = %q", index, call.authorized)+ }+ if !reflect.DeepEqual(call.body, want.body) {+ t.Fatalf("call %d body = %v, want %v", index, call.body, want.body)+ }++ claims := decodeSegment(t,+ strings.Split(strings.TrimPrefix(call.authorized, "Bearer "), ".")[1])+ if _, present := claims["sub"]; present {+ t.Fatalf("call %d service token must carry no sub", index)+ }+ if claims["iss"] != testAPIKey {+ t.Fatalf("call %d iss = %v", index, claims["iss"])+ }+ if lifetime := claims["exp"].(float64) - claims["nbf"].(float64); lifetime != 600 {+ t.Fatalf("call %d service token exp - nbf = %v, want 600", index, lifetime)+ }+ grant, _ := claims["video"].(map[string]any)+ if !reflect.DeepEqual(grant, want.grant) {+ t.Fatalf("call %d grant = %v, want %v", index, grant, want.grant)+ }+ }+}++// TestRoomServiceNotFoundRule pins isNotFound: HTTP 404 or code "not_found",+// nothing else. Both arms of the TypeScript `||` are reachable.+func TestRoomServiceNotFoundRule(t *testing.T) {+ for name, testCase := range map[string]struct {+ status int+ contentType string+ payload string+ notFound bool+ }{+ "twirp not found": {404, "application/json", `{"code":"not_found","msg":"missing"}`, true},+ "status only": {404, "text/plain", "Not Found", true},+ "code only": {500, "application/json", `{"code":"not_found","msg":"missing"}`, true},+ "already exists": {409, "application/json", `{"code":"already_exists","msg":"duplicate"}`, false},+ "internal": {500, "application/json", `{"code":"internal","msg":"boom"}`, false},+ "unauthenticated": {401, "application/json", `{"Error":"invalid API key"}`, false},+ "plain text error": {503, "text/plain", "unavailable", false},+ } {+ _, apiURL := captureLiveKit(t, func(string) (int, string, string) {+ return testCase.status, testCase.contentType, testCase.payload+ })+ service := newRoomService(apiURL, newSigner(testAPIKey, testAPISecret))+ err := service.deleteRoom(context.Background(), "screener-v1.42.a_1234567.b_1234567")+ if err == nil {+ t.Fatalf("%s: want an error", name)+ }+ if isNotFound(err) != testCase.notFound {+ t.Fatalf("%s: isNotFound = %v, want %v (%v)", name, !testCase.notFound, testCase.notFound, err)+ }+ }+}diff --git a/internal/server/sfu/sfutest/fake.go b/internal/server/sfu/sfutest/fake.gonew file mode 100644index 00000000..19bbfeed--- /dev/null+++ b/internal/server/sfu/sfutest/fake.go@@ -0,0 +1,271 @@+// Package sfutest holds the SFU test double the TypeScript suite kept in+// tests/fake-sfu-room-control.ts, so the signaling, router and app tests can+// drive the LiveKit fallback without a LiveKit.+package sfutest++import (+ "context"+ "errors"+ "sort"+ "sync"++ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+)++// FakeRoomControl is FakeSfuRoomControl. Every field is guarded: unlike the+// single-threaded TypeScript, the router calls it from goroutines while the+// test asserts. A barrier is a channel the test closes to release the call;+// a nil barrier does not block, which is the TypeScript `await undefined`.+type FakeRoomControl struct {+ mu sync.Mutex+ // Ordering site: initialize reports the room names in insertion order.+ rooms ordered.Map[string, map[string]struct{}]+ created []sfu.ResourceFence+ deleted []sfu.ResourceFence+ subscriptionDrainAttempts []sfu.SubscriptionFence+ drainedSubscriptions []sfu.SubscriptionFence+ startupDeletedRoomNames []string+ initializeCalls int+ initializeBarrier chan struct{}+ initializeError error+ createBarrier chan struct{}+ subscriptionDrainBarrier chan struct{}+ failDelete bool+ failHostCheck bool+}++var _ sfu.RoomControl = (*FakeRoomControl)(nil)++// New returns an empty fake.+func New() *FakeRoomControl { return &FakeRoomControl{} }++// Initialize records the call, then clears every room.+func (fake *FakeRoomControl) Initialize(ctx context.Context) error {+ fake.mu.Lock()+ fake.initializeCalls+++ barrier := fake.initializeBarrier+ fake.mu.Unlock()++ if err := wait(ctx, barrier); err != nil {+ return err+ }++ fake.mu.Lock()+ defer fake.mu.Unlock()+ if fake.initializeError != nil {+ return fake.initializeError+ }+ fake.startupDeletedRoomNames = append(fake.startupDeletedRoomNames, fake.rooms.Keys()...)+ fake.rooms.Clear()+ return nil+}++// CreateRoom refuses a room name that already exists.+func (fake *FakeRoomControl) CreateRoom(ctx context.Context, fence sfu.ResourceFence) error {+ fake.mu.Lock()+ barrier := fake.createBarrier+ fake.mu.Unlock()++ if err := wait(ctx, barrier); err != nil {+ return err+ }+ roomName := sfu.ManagedRoomName(fence)++ fake.mu.Lock()+ defer fake.mu.Unlock()+ if fake.rooms.Has(roomName) {+ return errors.New("room already exists")+ }+ fake.rooms.Set(roomName, map[string]struct{}{})+ fake.created = append(fake.created, fence)+ return nil+}++// DeleteRoom removes the room, whether or not it existed.+func (fake *FakeRoomControl) DeleteRoom(ctx context.Context, fence sfu.ResourceFence) error {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ if fake.failDelete {+ return errors.New("room deletion failed")+ }+ fake.rooms.Delete(sfu.ManagedRoomName(fence))+ fake.deleted = append(fake.deleted, fence)+ return nil+}++// DrainSubscription records the attempt before waiting, then removes the viewer.+func (fake *FakeRoomControl) DrainSubscription(ctx context.Context, fence sfu.SubscriptionFence) error {+ fake.mu.Lock()+ fake.subscriptionDrainAttempts = append(fake.subscriptionDrainAttempts, fence)+ barrier := fake.subscriptionDrainBarrier+ fake.mu.Unlock()++ if err := wait(ctx, barrier); err != nil {+ return err+ }++ fake.mu.Lock()+ defer fake.mu.Unlock()+ if participants, ok := fake.rooms.Get(sfu.ManagedRoomName(fence.ResourceFence)); ok {+ delete(participants, "viewer:"+fence.ViewerPeerID)+ }+ fake.drainedSubscriptions = append(fake.drainedSubscriptions, fence)+ return nil+}++// HostParticipantExists reports whether "host" joined the fenced room.+func (fake *FakeRoomControl) HostParticipantExists(+ _ context.Context,+ fence sfu.ResourceFence,+) (bool, error) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ if fake.failHostCheck {+ return false, errors.New("host check failed")+ }+ participants, ok := fake.rooms.Get(sfu.ManagedRoomName(fence))+ if !ok {+ return false, nil+ }+ _, joined := participants["host"]+ return joined, nil+}++// SeedRoom creates the fenced room with the given identities present.+func (fake *FakeRoomControl) SeedRoom(fence sfu.ResourceFence, identities ...string) {+ participants := make(map[string]struct{}, len(identities))+ for _, identity := range identities {+ participants[identity] = struct{}{}+ }+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.rooms.Set(sfu.ManagedRoomName(fence), participants)+}++// CanJoin reports whether the room name exists.+func (fake *FakeRoomControl) CanJoin(roomName string) bool {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ return fake.rooms.Has(roomName)+}++// RoomCount is rooms.size.+func (fake *FakeRoomControl) RoomCount() int {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ return fake.rooms.Len()+}++// Participants lists the identities in a room, sorted for a stable assertion.+func (fake *FakeRoomControl) Participants(roomName string) []string {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ participants, ok := fake.rooms.Get(roomName)+ if !ok {+ return nil+ }+ identities := make([]string, 0, len(participants))+ for identity := range participants {+ identities = append(identities, identity)+ }+ sort.Strings(identities)+ return identities+}++// InitializeCalls is initializeCalls.+func (fake *FakeRoomControl) InitializeCalls() int {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ return fake.initializeCalls+}++// StartupDeletedRoomNames is startupDeletedRoomNames.+func (fake *FakeRoomControl) StartupDeletedRoomNames() []string {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ return append([]string(nil), fake.startupDeletedRoomNames...)+}++// Created is created.+func (fake *FakeRoomControl) Created() []sfu.ResourceFence {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ return append([]sfu.ResourceFence(nil), fake.created...)+}++// Deleted is deleted.+func (fake *FakeRoomControl) Deleted() []sfu.ResourceFence {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ return append([]sfu.ResourceFence(nil), fake.deleted...)+}++// SubscriptionDrainAttempts is subscriptionDrainAttempts.+func (fake *FakeRoomControl) SubscriptionDrainAttempts() []sfu.SubscriptionFence {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ return append([]sfu.SubscriptionFence(nil), fake.subscriptionDrainAttempts...)+}++// DrainedSubscriptions is drainedSubscriptions.+func (fake *FakeRoomControl) DrainedSubscriptions() []sfu.SubscriptionFence {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ return append([]sfu.SubscriptionFence(nil), fake.drainedSubscriptions...)+}++// SetInitializeBarrier blocks Initialize until barrier is closed.+func (fake *FakeRoomControl) SetInitializeBarrier(barrier chan struct{}) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.initializeBarrier = barrier+}++// SetInitializeError makes Initialize fail after its barrier.+func (fake *FakeRoomControl) SetInitializeError(err error) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.initializeError = err+}++// SetCreateBarrier blocks CreateRoom until barrier is closed.+func (fake *FakeRoomControl) SetCreateBarrier(barrier chan struct{}) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.createBarrier = barrier+}++// SetSubscriptionDrainBarrier blocks DrainSubscription until barrier is closed.+func (fake *FakeRoomControl) SetSubscriptionDrainBarrier(barrier chan struct{}) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.subscriptionDrainBarrier = barrier+}++// SetFailDelete makes DeleteRoom fail.+func (fake *FakeRoomControl) SetFailDelete(fail bool) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.failDelete = fail+}++// SetFailHostCheck makes HostParticipantExists fail.+func (fake *FakeRoomControl) SetFailHostCheck(fail bool) {+ fake.mu.Lock()+ defer fake.mu.Unlock()+ fake.failHostCheck = fail+}++// wait is `await barrier` with the Go escape hatch a cancelled context needs.+func wait(ctx context.Context, barrier chan struct{}) error {+ if barrier == nil {+ return nil+ }+ select {+ case <-barrier:+ return nil+ case <-ctx.Done():+ return ctx.Err()+ }+}diff --git a/internal/server/sfu/sfutest/fake_test.go b/internal/server/sfu/sfutest/fake_test.gonew file mode 100644index 00000000..836223ab--- /dev/null+++ b/internal/server/sfu/sfutest/fake_test.go@@ -0,0 +1,193 @@+package sfutest++// The behaviour tests/fake-sfu-room-control.ts guarantees to the scenarios that+// use it, so a signaling or app test can rely on it the same way.++import (+ "context"+ "errors"+ "slices"+ "testing"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+)++func fence(publicationGeneration string) sfu.ResourceFence {+ return sfu.ResourceFence{+ RoomID: "42",+ ShareGeneration: "share_generation_12345678",+ PublicationGeneration: publicationGeneration,+ }+}++func TestFakeInitializeDrainsSeededRooms(t *testing.T) {+ fake := New()+ first := fence("publication_generation_12345678")+ second := fence("publication_generation_87654321")+ fake.SeedRoom(first, "host")+ fake.SeedRoom(second)+ barrier := make(chan struct{})+ fake.SetInitializeBarrier(barrier)++ done := make(chan error, 1)+ go func() { done <- fake.Initialize(context.Background()) }()+ // The call is counted before the barrier, which is what a startup test that+ // asserts "initialize was entered" observes.+ waitFor(t, "the initialize call", func() bool { return fake.InitializeCalls() == 1 })+ if fake.RoomCount() != 2 {+ t.Fatalf("rooms = %d, want the seeded pair", fake.RoomCount())+ }++ close(barrier)+ if err := <-done; err != nil {+ t.Fatalf("Initialize: %v", err)+ }+ if names := fake.StartupDeletedRoomNames(); !slices.Equal(names,+ []string{sfu.ManagedRoomName(first), sfu.ManagedRoomName(second)}) {+ t.Fatalf("startup deleted = %v, want both rooms in seeding order", names)+ }+ if fake.RoomCount() != 0 {+ t.Fatalf("rooms = %d, want none", fake.RoomCount())+ }+}++func TestFakeInitializeReportsInjectedFailure(t *testing.T) {+ fake := New()+ failure := errors.New("startup reconciliation failed")+ fake.SetInitializeError(failure)+ fake.SeedRoom(fence("publication_generation_12345678"))++ if err := fake.Initialize(context.Background()); !errors.Is(err, failure) {+ t.Fatalf("Initialize error = %v, want %v", err, failure)+ }+ if fake.RoomCount() != 1 {+ t.Fatal("a failed initialize must not clear the rooms")+ }+}++func TestFakeRecordsRoomLifecycle(t *testing.T) {+ fake := New()+ ctx := context.Background()+ current := fence("publication_generation_12345678")+ roomName := sfu.ManagedRoomName(current)++ if err := fake.CreateRoom(ctx, current); err != nil {+ t.Fatalf("CreateRoom: %v", err)+ }+ if err := fake.CreateRoom(ctx, current); err == nil {+ t.Fatal("a duplicate room must be refused")+ }+ if !fake.CanJoin(roomName) {+ t.Fatal("the created room must accept a join")+ }+ if created := fake.Created(); !slices.Equal(created, []sfu.ResourceFence{current}) {+ t.Fatalf("created = %v", created)+ }++ fake.SetFailDelete(true)+ if err := fake.DeleteRoom(ctx, current); err == nil {+ t.Fatal("the injected delete failure must surface")+ }+ if !fake.CanJoin(roomName) || len(fake.Deleted()) != 0 {+ t.Fatal("a failed delete must change nothing")+ }+ fake.SetFailDelete(false)+ if err := fake.DeleteRoom(ctx, current); err != nil {+ t.Fatalf("DeleteRoom: %v", err)+ }+ if fake.CanJoin(roomName) {+ t.Fatal("the deleted room must not accept a join")+ }+ if deleted := fake.Deleted(); !slices.Equal(deleted, []sfu.ResourceFence{current}) {+ t.Fatalf("deleted = %v", deleted)+ }+}++func TestFakeDrainsOnlyTheExactViewer(t *testing.T) {+ fake := New()+ ctx := context.Background()+ current := fence("publication_generation_12345678")+ roomName := sfu.ManagedRoomName(current)+ fake.SeedRoom(current, "host", "viewer:viewer_peer_12345678", "viewer:other_peer_12345678")+ barrier := make(chan struct{})+ fake.SetSubscriptionDrainBarrier(barrier)++ subscription := sfu.SubscriptionFence{+ ResourceFence: current,+ ViewerPeerID: "viewer_peer_12345678",+ }+ done := make(chan error, 1)+ go func() { done <- fake.DrainSubscription(ctx, subscription) }()+ // The attempt is recorded before the barrier; the removal is not.+ waitFor(t, "the drain attempt", func() bool {+ return len(fake.SubscriptionDrainAttempts()) == 1+ })+ if len(fake.DrainedSubscriptions()) != 0 {+ t.Fatal("the drain must not complete before its barrier")+ }++ close(barrier)+ if err := <-done; err != nil {+ t.Fatalf("DrainSubscription: %v", err)+ }+ if participants := fake.Participants(roomName); !slices.Equal(participants,+ []string{"host", "viewer:other_peer_12345678"}) {+ t.Fatalf("participants = %v", participants)+ }+ if drained := fake.DrainedSubscriptions(); !slices.Equal(drained,+ []sfu.SubscriptionFence{subscription}) {+ t.Fatalf("drained = %v", drained)+ }+}++func TestFakeHostParticipantExists(t *testing.T) {+ fake := New()+ ctx := context.Background()+ hosted := fence("publication_generation_12345678")+ empty := fence("publication_generation_87654321")+ fake.SeedRoom(hosted, "host")+ fake.SeedRoom(empty, "viewer:viewer_peer_12345678")++ for _, testCase := range []struct {+ fence sfu.ResourceFence+ want bool+ }{{hosted, true}, {empty, false}, {fence("publication_generation_11112222"), false}} {+ exists, err := fake.HostParticipantExists(ctx, testCase.fence)+ if err != nil {+ t.Fatalf("HostParticipantExists: %v", err)+ }+ if exists != testCase.want {+ t.Fatalf("HostParticipantExists(%s) = %v, want %v",+ testCase.fence.PublicationGeneration, exists, testCase.want)+ }+ }++ fake.SetFailHostCheck(true)+ if _, err := fake.HostParticipantExists(ctx, hosted); err == nil {+ t.Fatal("the injected host-check failure must surface")+ }+}++func TestFakeReleasesBlockedCallsOnCancellation(t *testing.T) {+ fake := New()+ fake.SetCreateBarrier(make(chan struct{}))+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ if err := fake.CreateRoom(ctx, fence("publication_generation_12345678")); err == nil {+ t.Fatal("a cancelled context must release the barrier")+ }+}++// waitFor is vitest's vi.waitFor: poll until the condition holds.+func waitFor(t *testing.T, description string, condition func() bool) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ if condition() {+ return+ }+ time.Sleep(time.Millisecond)+ }+ t.Fatalf("timed out waiting for %s", description)+}diff --git a/internal/server/sfu/token.go b/internal/server/sfu/token.gonew file mode 100644index 00000000..650d6fdf--- /dev/null+++ b/internal/server/sfu/token.go@@ -0,0 +1,203 @@+package sfu++// Ported from src/server/livekit-token.ts. The AccessToken of+// livekit-server-sdk is replaced by the HS256 JWT it produced; the claim set is+// the one recorded in evidence/livekit.md section 2.++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "errors"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++const (+ // tokenTTLSeconds and serviceTokenTTLSeconds are the AccessToken `ttl`+ // values of src/server/livekit-token.ts and the SDK's ServiceBase: a+ // participant token only has to survive the join it was issued for, and a+ // service token only the one RoomService call it authorises.+ tokenTTLSeconds = 5 * 60+ serviceTokenTTLSeconds = 10 * 60+ // minAPISecretBytes is the TypeScript Buffer.byteLength(secret) >= 32 guard,+ // which is len() in Go because both count UTF-8 bytes.+ minAPISecretBytes = 32+ // TrackSource enum strings, from livekit-server-sdk grants.ts+ // trackSourceToString().+ trackSourceScreenShare = "screen_share"+ trackSourceScreenShareAudio = "screen_share_audio"+)++// videoGrant is the subset of the SDK's VideoGrant this server sets. The four+// capability flags are *bool because absent and false differ to LiveKit:+// GetCanPublish() answers true for an absent flag, so a viewer's+// "canPublish": false must be emitted, not omitted.+type videoGrant struct {+ RoomCreate bool `json:"roomCreate,omitempty"`+ RoomJoin bool `json:"roomJoin,omitempty"`+ RoomList bool `json:"roomList,omitempty"`+ RoomAdmin bool `json:"roomAdmin,omitempty"`+ Room string `json:"room,omitempty"`+ CanPublish *bool `json:"canPublish,omitempty"`+ CanPublishSources []string `json:"canPublishSources,omitempty"`+ CanSubscribe *bool `json:"canSubscribe,omitempty"`+ CanPublishData *bool `json:"canPublishData,omitempty"`+ CanUpdateOwnMetadata *bool `json:"canUpdateOwnMetadata,omitempty"`+}++// tokenClaims is the registered claim set jose emitted for AccessToken: no+// `iat`, no duplicate `identity`, and no `sub` on a service token.+type tokenClaims struct {+ Iss string `json:"iss"`+ Sub string `json:"sub,omitempty"`+ Nbf int64 `json:"nbf"`+ Exp int64 `json:"exp"`+ Video videoGrant `json:"video"`+}++// signer holds the API credentials shared by the participant token issuer and+// the RoomService client.+type signer struct {+ apiKey string+ apiSecret []byte+}++func newSigner(apiKey string, apiSecret string) signer {+ return signer{apiKey: apiKey, apiSecret: []byte(apiSecret)}+}++// sign emits the compact JWS. jose's SignJWT with {alg:"HS256"} writes exactly+// {"alg":"HS256"} as the protected header: no typ, no kid.+func (s signer) sign(claims tokenClaims) (string, error) {+ payload, err := json.Marshal(claims)+ if err != nil {+ return "", err+ }+ header := []byte(`{"alg":"HS256"}`)+ encoding := base64.RawURLEncoding+ signing := make([]byte, 0,+ encoding.EncodedLen(len(header))+1+encoding.EncodedLen(len(payload)))+ signing = encoding.AppendEncode(signing, header)+ signing = append(signing, '.')+ signing = encoding.AppendEncode(signing, payload)+ mac := hmac.New(sha256.New, s.apiSecret)+ mac.Write(signing)+ token := append(signing, '.')+ token = encoding.AppendEncode(token, mac.Sum(nil))+ return string(token), nil+}++// serviceToken reproduces ServiceBase.authHeader: a 10 minute admin token+// carrying one video grant and no subject.+func (s signer) serviceToken(grant videoGrant) (string, error) {+ notBefore := time.Now().Unix()+ return s.sign(tokenClaims{+ Iss: s.apiKey,+ Nbf: notBefore,+ Exp: notBefore + serviceTokenTTLSeconds,+ Video: grant,+ })+}++// TokenRequest is SfuTokenRequest.+type TokenRequest struct {+ RoomID string+ Role protocol.Role+ PeerID string+ ShareGeneration string+ PublicationGeneration string+}++// TokenIssuer is SfuTokenIssuer. Issuing is local HMAC work, so unlike+// RoomControl it takes no context.+type TokenIssuer interface {+ IssueToken(request TokenRequest) (string, error)+}++// LiveKitTokenIssuerOptions is LiveKitTokenIssuerOptions.+type LiveKitTokenIssuerOptions struct {+ APIKey string+ APISecret string+ MaxViewersPerRoom int+}++// LiveKitTokenIssuer is LiveKitTokenIssuer.+type LiveKitTokenIssuer struct {+ signer signer+}++var _ TokenIssuer = (*LiveKitTokenIssuer)(nil)++// NewLiveKitTokenIssuer mirrors the LiveKitTokenIssuer constructor.+func NewLiveKitTokenIssuer(options LiveKitTokenIssuerOptions) (*LiveKitTokenIssuer, error) {+ if options.APIKey == "" || len(options.APISecret) < minAPISecretBytes {+ return nil, errors.New("LiveKit API credentials are invalid")+ }+ if err := validateViewerLimit(options.MaxViewersPerRoom); err != nil {+ return nil, err+ }+ return &LiveKitTokenIssuer{signer: newSigner(options.APIKey, options.APISecret)}, nil+}++// IssueToken ports issueToken.+func (issuer *LiveKitTokenIssuer) IssueToken(request TokenRequest) (string, error) {+ if !roomIDPattern.MatchString(request.RoomID) {+ return "", errors.New("LiveKit room ID is invalid")+ }+ if !protocol.ValidOpaqueID(request.PeerID) ||+ !protocol.ValidOpaqueID(request.ShareGeneration) ||+ !protocol.ValidOpaqueID(request.PublicationGeneration) {+ return "", errors.New("LiveKit participant identity is invalid")+ }++ isHost := request.Role == protocol.RoleHost+ // The validation above is a superset of managedRoomName's, so this cannot+ // fail; the TypeScript relied on the same ordering.+ room := ManagedRoomName(ResourceFence{+ RoomID: request.RoomID,+ ShareGeneration: request.ShareGeneration,+ PublicationGeneration: request.PublicationGeneration,+ })+ identity := "host"+ if !isHost {+ identity = "viewer:" + request.PeerID+ }+ grant := videoGrant{+ RoomJoin: true,+ Room: room,+ CanPublish: boolPointer(isHost),+ CanSubscribe: boolPointer(!isHost),+ CanPublishData: boolPointer(false),+ CanUpdateOwnMetadata: boolPointer(false),+ }+ if isHost {+ grant.CanPublishSources = []string{+ trackSourceScreenShare,+ trackSourceScreenShareAudio,+ }+ }+ // One clock read: jose called new Date() once per setter, so across a+ // second boundary its exp - nbf could be 299. Here it is always 300.+ notBefore := time.Now().Unix()+ return issuer.signer.sign(tokenClaims{+ Iss: issuer.signer.apiKey,+ Sub: identity,+ Nbf: notBefore,+ Exp: notBefore + tokenTTLSeconds,+ Video: grant,+ })+}++// validateViewerLimit is the shared viewer-limit guard of both LiveKit+// constructors. Number.isSafeInteger is implicit in Go's int.+func validateViewerLimit(maxViewersPerRoom int) error {+ if maxViewersPerRoom < 1 || maxViewersPerRoom > protocol.MaxViewersPerRoomLimit {+ return errors.New("LiveKit viewer limit is invalid")+ }+ return nil+}++func boolPointer(value bool) *bool { return &value }diff --git a/internal/server/sfu/token_test.go b/internal/server/sfu/token_test.gonew file mode 100644index 00000000..7d924944--- /dev/null+++ b/internal/server/sfu/token_test.go@@ -0,0 +1,225 @@+package sfu++// Ported from tests/livekit-token.test.ts. The TypeScript verified with the+// SDK's TokenVerifier; here the JWT is split, the HS256 signature recomputed+// and the payload compared to the claim set recorded in evidence/livekit.md+// section 2.++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "reflect"+ "strings"+ "testing"+ "time"+)++const (+ testAPIKey = "test-api-key"+ // Placeholder credential copied from tests/livekit-token.test.ts.+ testAPISecret = "ssssssssssssssssssssssssssssssss"+ testShareGeneration = "share_generation_12345678"+ testPublicationGeneration = "publication_12345678"+)++// decodeToken checks the signature and returns the header and payload claims.+func decodeToken(t *testing.T, token string) (map[string]any, map[string]any) {+ t.Helper()+ segments := strings.Split(token, ".")+ if len(segments) != 3 {+ t.Fatalf("token has %d segments, want 3", len(segments))+ }+ mac := hmac.New(sha256.New, []byte(testAPISecret))+ mac.Write([]byte(segments[0] + "." + segments[1]))+ want := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))+ if segments[2] != want {+ t.Fatal("HS256 signature does not verify with the API secret")+ }+ return decodeSegment(t, segments[0]), decodeSegment(t, segments[1])+}++func decodeSegment(t *testing.T, segment string) map[string]any {+ t.Helper()+ raw, err := base64.RawURLEncoding.DecodeString(segment)+ if err != nil {+ t.Fatalf("base64: %v", err)+ }+ var claims map[string]any+ if err := json.Unmarshal(raw, &claims); err != nil {+ t.Fatalf("json: %v", err)+ }+ return claims+}++func testIssuer(t *testing.T, maxViewersPerRoom int) *LiveKitTokenIssuer {+ t.Helper()+ issuer, err := NewLiveKitTokenIssuer(LiveKitTokenIssuerOptions{+ APIKey: testAPIKey,+ APISecret: testAPISecret,+ MaxViewersPerRoom: maxViewersPerRoom,+ })+ if err != nil {+ t.Fatalf("NewLiveKitTokenIssuer: %v", err)+ }+ return issuer+}++func issue(t *testing.T, issuer *LiveKitTokenIssuer, request TokenRequest) (map[string]any, map[string]any) {+ t.Helper()+ token, err := issuer.IssueToken(request)+ if err != nil {+ t.Fatalf("IssueToken: %v", err)+ }+ return decodeToken(t, token)+}++func TestTokenIssuesGenerationBoundHostToken(t *testing.T) {+ before := time.Now().Unix()+ header, claims := issue(t, testIssuer(t, 8), TokenRequest{+ RoomID: "42",+ Role: "host",+ PeerID: "host_peer_12345678",+ ShareGeneration: testShareGeneration,+ PublicationGeneration: testPublicationGeneration,+ })+ after := time.Now().Unix()++ // jose emitted exactly {"alg":"HS256"}: no typ, no kid.+ if !reflect.DeepEqual(header, map[string]any{"alg": "HS256"}) {+ t.Fatalf("header = %v", header)+ }+ if claims["iss"] != testAPIKey || claims["sub"] != "host" {+ t.Fatalf("iss/sub = %v/%v", claims["iss"], claims["sub"])+ }+ notBefore, expires := claims["nbf"].(float64), claims["exp"].(float64)+ if expires-notBefore != 5*60 {+ t.Fatalf("exp - nbf = %v, want 300", expires-notBefore)+ }+ if notBefore < float64(before) || notBefore > float64(after) {+ t.Fatalf("nbf = %v, want it inside [%d,%d]", notBefore, before, after)+ }+ if _, present := claims["iat"]; present {+ t.Fatal("iat must be absent")+ }+ if _, present := claims["identity"]; present {+ t.Fatal("identity must be absent")+ }+ if _, present := claims["roomConfig"]; present {+ t.Fatal("roomConfig must be absent")+ }+ want := map[string]any{+ "roomJoin": true,+ "room": "screener-v1.42." + testShareGeneration + "." + testPublicationGeneration,+ "canPublish": true,+ "canSubscribe": false,+ "canPublishData": false,+ "canUpdateOwnMetadata": false,+ "canPublishSources": []any{"screen_share", "screen_share_audio"},+ }+ assertVideoGrant(t, claims, want)+}++func TestTokenIssuesSubscribeOnlyViewerToken(t *testing.T) {+ const viewerPeerID = "viewer_root_12345678"+ _, claims := issue(t, testIssuer(t, 3), TokenRequest{+ RoomID: "7",+ Role: "viewer",+ PeerID: viewerPeerID,+ ShareGeneration: testShareGeneration,+ PublicationGeneration: testPublicationGeneration,+ })++ if claims["sub"] != "viewer:"+viewerPeerID {+ t.Fatalf("sub = %v", claims["sub"])+ }+ // canPublishSources is dropped entirely for a viewer, and canPublish must+ // be present as false: an absent flag reads as granted to LiveKit.+ assertVideoGrant(t, claims, map[string]any{+ "roomJoin": true,+ "room": "screener-v1.7." + testShareGeneration + "." + testPublicationGeneration,+ "canPublish": false,+ "canSubscribe": true,+ "canPublishData": false,+ "canUpdateOwnMetadata": false,+ })+}++func TestTokenIsolatesPublicationGenerations(t *testing.T) {+ issuer := testIssuer(t, 8)+ request := TokenRequest{+ RoomID: "7",+ Role: "host",+ PeerID: "host_peer_12345678",+ ShareGeneration: testShareGeneration,+ }+ request.PublicationGeneration = "generation_first_12345678"+ _, first := issue(t, issuer, request)+ request.PublicationGeneration = "generation_second_12345678"+ _, second := issue(t, issuer, request)++ firstRoom := first["video"].(map[string]any)["room"]+ secondRoom := second["video"].(map[string]any)["room"]+ if firstRoom == secondRoom {+ t.Fatalf("both generations share the room %v", firstRoom)+ }+}++func TestTokenRejectsInvalidRequestsAndCredentials(t *testing.T) {+ issuer := testIssuer(t, 8)+ base := TokenRequest{+ RoomID: "42",+ Role: "host",+ PeerID: "host_peer_12345678",+ ShareGeneration: testShareGeneration,+ PublicationGeneration: testPublicationGeneration,+ }+ for name, mutate := range map[string]func(*TokenRequest){+ "zero room": func(request *TokenRequest) { request.RoomID = "0" },+ "leading zero": func(request *TokenRequest) { request.RoomID = "042" },+ "thirteen digits": func(request *TokenRequest) {+ request.RoomID = "1234567890123"+ },+ "empty room": func(request *TokenRequest) { request.RoomID = "" },+ "short peer": func(request *TokenRequest) { request.PeerID = "short" },+ "dotted share": func(request *TokenRequest) { request.ShareGeneration = "has.dot.12345678" },+ "empty publication": func(request *TokenRequest) {+ request.PublicationGeneration = ""+ },+ "unicode peer": func(request *TokenRequest) { request.PeerID = "peer_é_12345678" },+ } {+ request := base+ mutate(&request)+ if _, err := issuer.IssueToken(request); err == nil {+ t.Fatalf("%s: want a rejection", name)+ }+ }++ for name, options := range map[string]LiveKitTokenIssuerOptions{+ "empty key": {APIKey: "", APISecret: testAPISecret, MaxViewersPerRoom: 8},+ "short secret": {APIKey: testAPIKey, APISecret: strings.Repeat("s", 31), MaxViewersPerRoom: 8},+ "no viewers": {APIKey: testAPIKey, APISecret: testAPISecret, MaxViewersPerRoom: 0},+ "too many viewers": {+ APIKey: testAPIKey, APISecret: testAPISecret, MaxViewersPerRoom: 21,+ },+ } {+ if _, err := NewLiveKitTokenIssuer(options); err == nil {+ t.Fatalf("%s: want a rejection", name)+ }+ }+}++// assertVideoGrant compares the whole claim: an extra or missing key is a+// different grant, which is the point of canPublishSources being absent for a+// viewer and canPublish being present as false.+func assertVideoGrant(t *testing.T, claims map[string]any, want map[string]any) {+ t.Helper()+ grant, ok := claims["video"].(map[string]any)+ if !ok {+ t.Fatalf("video = %v", claims["video"])+ }+ if !reflect.DeepEqual(grant, want) {+ t.Fatalf("video = %v, want %v", grant, want)+ }+}diff --git a/internal/server/signal/presence.go b/internal/server/signal/presence.gonew file mode 100644index 00000000..60a96cda--- /dev/null+++ b/internal/server/signal/presence.go@@ -0,0 +1,352 @@+package signal++// Viewer presence, host status, disconnect handling and room termination of+// src/server/signaling.ts (sendViewerPresence 1594, broadcastHostStatus+// 1683, handleDisconnect 1397, stopSharing 1466, terminateRoom 1500,+// revokeGrantViewers 1016, closeRevokedViewerSession 1697 and the+// viewer-keyed map helpers). Every function here runs with mu held.++import (+ "fmt"+ "strings"+ "time"++ "github.com/coder/websocket"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+ "github.com/TNTcraftHIM/Screener/internal/server/room"+)++// viewerKey is the TS `${roomId}:${peerId}` used by the grace timers and the+// viewer quality evidence maps (viewerGraceKey and viewerConnectionKey were+// the same expression).+func viewerKey(roomID, peerID string) string { return roomID + ":" + peerID }++// sendViewerPresence ports sendViewerPresence (O12): the host entry first+// when it has a display name, then viewers in store order; recipients are+// the opted-in host first, then opted-in viewers in store order, deduped by+// connection (hazard 11).+func (s *Server) sendViewerPresence(roomID string) {+ if _, deferred := s.deferredViewerPresenceRooms[roomID]; deferred {+ return+ }++ connectedViewers := s.store.GetConnectedViewers(roomID)+ viewers := []protocol.ParticipantPresenceEntry{}+ host, hasHost := s.store.GetConnectedHost(roomID)+ var hostSession *session+ var hostState *authenticatedSession+ if hasHost {+ hostSession = s.sessionsByID[host.SessionID]+ if hostSession != nil {+ hostState = hostSession.authenticated+ }+ }+ if hasHost && hostSession != nil && hostState != nil &&+ hostState.role == protocol.RoleHost &&+ hostState.roomID == roomID &&+ hostState.peerID == host.PeerID &&+ hostState.displayName != nil {+ viewers = append(viewers, protocol.HostPresenceEntry(host.PeerID, protocol.DisplayName(*hostState.displayName)))+ }++ for _, viewer := range connectedViewers {+ viewerState := s.authenticatedOf(viewer.SessionID)+ if viewerState == nil ||+ viewerState.role != protocol.RoleViewer ||+ viewerState.roomID != roomID ||+ viewerState.peerID != viewer.PeerID ||+ viewerState.displayName == nil {+ continue+ }+ upstream := s.router.getViewerRouteUpstream(roomID, viewer.PeerID)+ activeEdge, hasActiveEdge := s.router.resolveActiveViewerMediaEdge(roomID, viewer.PeerID)+ mediaReady := hasActiveEdge && upstream.Kind != "none"+ if mediaReady {+ if activeEdge.upstream.Kind == "sfu" {+ mediaReady = upstream.Kind == "sfu"+ } else {+ mediaReady = upstream.Kind == "peer" && activeEdge.upstream.PeerID == upstream.PeerID+ }+ }+ viewers = append(viewers, protocol.NewViewerPresenceEntry(+ viewer.PeerID, protocol.DisplayName(*viewerState.displayName), upstream, mediaReady))+ }+ encoded, err := protocol.EncodeServerMessage(protocol.ViewerPresenceMessage{+ Type: "viewer-presence",+ Viewers: viewers,+ })+ if err != nil {+ panic(err)+ }++ var recipients []*session+ seen := map[*session]struct{}{}+ add := func(sess *session) {+ if _, duplicate := seen[sess]; duplicate {+ return+ }+ seen[sess] = struct{}{}+ recipients = append(recipients, sess)+ }+ if hostSession != nil && hostState != nil && hostState.viewerPresence {+ add(hostSession)+ }+ for _, viewer := range connectedViewers {+ viewerSession := s.sessionsByID[viewer.SessionID]+ if viewerSession == nil {+ continue+ }+ viewerState := viewerSession.authenticated+ if viewerState != nil &&+ viewerState.role == protocol.RoleViewer &&+ viewerState.roomID == roomID &&+ viewerState.peerID == viewer.PeerID &&+ viewerState.viewerPresence {+ add(viewerSession)+ }+ }+ for _, sess := range recipients {+ s.sendEncoded(sess, encoded)+ }+}++// broadcastHostStatus ports broadcastHostStatus (O10).+func (s *Server) broadcastHostStatus(roomID string, online, paused bool) {+ for _, viewer := range s.store.GetConnectedViewers(roomID) {+ s.sendToSession(viewer.SessionID, protocol.HostStatusMessage{+ Type: "host-status",+ Online: online,+ Paused: paused,+ })+ }+}++// handleDisconnect ports handleDisconnect. It runs once, from the reader+// goroutine's exit (D6). The host lease write is one of the two paths the TS+// left uncaught, so its failure panics (D7).+func (s *Server) handleDisconnect(sess *session) {+ if !s.sessions.Has(sess) {+ return+ }+ sess.clearAuthenticationTimer()+ delete(s.senderQualityRateBySession, sess.sessionID)+ s.sessions.Delete(sess)+ if s.sessionsByID[sess.sessionID] == sess {+ delete(s.sessionsByID, sess.sessionID)+ }+ if sess.revoked {+ return+ }+ if sess.authenticated == nil {+ s.unauthenticatedConnections--+ return+ }+ if s.closing {+ return+ }++ disconnected, err := s.store.DisconnectParticipant(+ sess.authenticated.roomID, sess.authenticated.peerID, sess.sessionID)+ if err != nil {+ panic(fmt.Errorf("room store write failed during host disconnect: %w", err))+ }+ if disconnected == nil {+ return+ }+ s.router.disconnectParticipant(disconnected.RoomID, disconnected.PeerID, sess.sessionID)+ if disconnected.Role == protocol.RoleHost {+ s.broadcastHostStatus(disconnected.RoomID, false, false)+ s.sendViewerPresence(disconnected.RoomID)+ return+ }++ s.sendViewerPresence(disconnected.RoomID)++ // T5: the viewer grace timer. The registered-pointer check stands in+ // for clearTimeout; the store's removeDisconnectedViewer is the identity+ // guard against a viewer that reconnected meanwhile.+ roomID, peerID := disconnected.RoomID, disconnected.PeerID+ key := viewerKey(roomID, peerID)+ timer := &graceTimer{}+ timer.stop = s.afterFunc(time.Duration(s.viewerDisconnectGraceMs)*time.Millisecond, func() {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.viewerGraceTimers[key] != timer {+ return+ }+ delete(s.viewerGraceTimers, key)+ if s.store.RemoveDisconnectedViewer(roomID, peerID) {+ s.clearViewerEvidence(roomID, peerID)+ s.router.removeViewer(roomID, peerID)+ }+ })+ s.viewerGraceTimers[key] = timer+}++// stopSharing ports stopSharing (O9: per viewer, sharing-stopped then+// host-status). The share generation deliberately survives (hazard 2).+func (s *Server) stopSharing(roomID string) {+ if current, ok := s.shares[roomID]; ok {+ s.shares[roomID] = roomShare{generation: current.generation}+ }+ s.clearRoomViewerEvidence(roomID)+ s.router.stopRoom(roomID)+ for _, viewer := range s.store.GetConnectedViewers(roomID) {+ s.sendToSession(viewer.SessionID, protocol.SharingStoppedMessage{Type: "sharing-stopped"})+ s.sendToSession(viewer.SessionID, protocol.HostStatusMessage{+ Type: "host-status",+ Online: false,+ Paused: false,+ })+ }+}++// abandonRoom ports abandonRoom; the store error is the caller's to map.+func (s *Server) abandonRoom(roomID string) error {+ abandoned, err := s.store.AbandonRoom(roomID)+ if err != nil {+ return err+ }+ if abandoned == nil {+ return nil+ }+ s.closeRoom(*abandoned)+ return nil+}++// closeRoom ports closeRoom.+func (s *Server) closeRoom(closed room.ClosedRoom) {+ s.terminateRoom(closed, "host-ended", "Room abandoned")+}++// expireRooms ports expireRooms, the cleanup timer body. Its store write is+// the second path the TS left uncaught (D7).+func (s *Server) expireRooms() {+ expired, err := s.store.ExpireRooms(s.now())+ if err != nil {+ panic(fmt.Errorf("room store write failed while expiring rooms: %w", err))+ }+ for _, closed := range expired {+ s.terminateRoom(closed, "expired", "Room expired")+ }+}++// terminateRoom ports terminateRoom (O4: the host session first, then+// viewers in store order, each told room-closed then closed with 1000).+func (s *Server) terminateRoom(closed room.ClosedRoom, reason, closeText string) {+ s.clearRoomGraceTimers(closed.RoomID)+ s.clearRoomViewerEvidence(closed.RoomID)+ s.router.deleteRoom(closed.RoomID)+ delete(s.shares, closed.RoomID)+ for _, sessionID := range closed.SessionIDs {+ sess := s.sessionsByID[sessionID]+ if sess == nil {+ continue+ }+ s.send(sess, protocol.RoomClosedMessage{Type: "room-closed", Reason: reason})+ sess.close(websocket.StatusNormalClosure, closeText)+ }+}++// revokeGrantViewers ports revokeGrantViewers (O5): three separate passes+// over the revoked viewers, with presence deferred until the end.+func (s *Server) revokeGrantViewers(roomID string, update room.ViewerGrantUpdate) {+ if len(update.RevokedViewers) == 0 {+ return+ }+ s.deferredViewerPresenceRooms[roomID] = struct{}{}+ func() {+ defer delete(s.deferredViewerPresenceRooms, roomID)+ for _, viewer := range update.RevokedViewers {+ s.clearViewerState(roomID, viewer.PeerID)+ if viewer.SessionID == "" {+ continue+ }+ s.sendToSession(viewer.SessionID, protocol.ViewerGrantRevokedMessage{+ Type: "viewer-grant-revoked",+ ViewerAuthorizationGeneration: update.PreviousViewerAuthorizationGeneration,+ })+ }++ for _, viewer := range update.RevokedViewers {+ s.router.removeViewer(roomID, viewer.PeerID)+ }++ for _, viewer := range update.RevokedViewers {+ if viewer.SessionID == "" {+ continue+ }+ s.closeRevokedViewerSession(viewer.SessionID)+ }+ }()+ s.sendViewerPresence(roomID)+}++// closeRevokedViewerSession ports closeRevokedViewerSession: deauthorize+// before the close so queued callbacks of the old generation cannot route+// signaling after the persistent authorization commit.+func (s *Server) closeRevokedViewerSession(sessionID string) {+ sess := s.sessionsByID[sessionID]+ if sess == nil {+ return+ }+ if sess.sessionID == sessionID {+ sess.clearAuthenticationTimer()+ sess.revoked = true+ }+ if s.sessionsByID[sessionID] == sess {+ delete(s.sessionsByID, sessionID)+ }+ sess.close(websocket.StatusCode(protocol.SignalCloseViewerAccessRevoked), "Viewer access revoked")+}++// clearViewerGrace ports clearViewerGrace.+func (s *Server) clearViewerGrace(roomID, peerID string) {+ key := viewerKey(roomID, peerID)+ if timer, ok := s.viewerGraceTimers[key]; ok {+ timer.stop()+ delete(s.viewerGraceTimers, key)+ }+}++// clearViewerState ports clearViewerState.+func (s *Server) clearViewerState(roomID, peerID string) {+ s.clearViewerGrace(roomID, peerID)+ s.clearViewerEvidence(roomID, peerID)+}++// clearRoomGraceTimers ports clearRoomGraceTimers (O13: prefix scan; Go+// maps allow deletion during range).+func (s *Server) clearRoomGraceTimers(roomID string) {+ prefix := roomID + ":"+ for key, timer := range s.viewerGraceTimers {+ if strings.HasPrefix(key, prefix) {+ timer.stop()+ delete(s.viewerGraceTimers, key)+ }+ }+}++// clearRoomViewerEvidence ports clearRoomConnectionIds (O13) without the+// connection-ID mirror it also cleared.+func (s *Server) clearRoomViewerEvidence(roomID string) {+ prefix := roomID + ":"+ for key := range s.viewerQualityEvidenceGates {+ if strings.HasPrefix(key, prefix) {+ delete(s.viewerQualityEvidenceGates, key)+ }+ }+ for key := range s.viewerQualityEvidenceAttempts {+ if strings.HasPrefix(key, prefix) {+ delete(s.viewerQualityEvidenceAttempts, key)+ }+ }+}++// clearViewerEvidence drops one viewer's evidence gate and rate stamp.+func (s *Server) clearViewerEvidence(roomID, viewerPeerID string) {+ key := viewerKey(roomID, viewerPeerID)+ delete(s.viewerQualityEvidenceGates, key)+ delete(s.viewerQualityEvidenceAttempts, key)+}diff --git a/internal/server/signal/router.go b/internal/server/signal/router.gonew file mode 100644index 00000000..487c1cbc--- /dev/null+++ b/internal/server/signal/router.go@@ -0,0 +1,1616 @@+package signal++// Ported from src/server/hybrid-media-router.ts (baseline b20fd88).+//+// The router owns no lock. signal.Server.mu (routerOptions.mu) is held by the+// caller of every method except close, hooks are called with it held, and the+// goroutines the router starts (pump driver, fresh SFU config, host-offline+// probe, drains, timer callbacks) take it themselves. Every TS `await` is an+// unlock / I/O / lock window followed by exactly the guard the TS code ran+// after that await (map C:/tmp/screener-go/maps/effect-layer.md, section 2.2).++import (+ "context"+ "crypto/rand"+ "encoding/base64"+ "errors"+ "fmt"+ "log/slog"+ "net/url"+ "os"+ "strings"+ "sync"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+ "github.com/TNTcraftHIM/Screener/internal/server/room"+ "github.com/TNTcraftHIM/Screener/internal/server/route"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+)++const (+ defaultRouteOperationTimeoutMs int64 = 20_000+ defaultSfuDrainRetryMs int64 = 1_000+ defaultHostOfflineCheckMs int64 = 5_000+)++// routeDebugEnabled ports debuglog("screener-route"): SCREENER_DEBUG=route+// (D8), read once like NODE_DEBUG. The route package keeps the same flag+// unexported, so this is its second reader.+var routeDebugEnabled = routeDebugFlag(os.Getenv("SCREENER_DEBUG"))++func routeDebugFlag(value string) bool {+ for _, section := range strings.Split(value, ",") {+ if strings.TrimSpace(section) == "route" {+ return true+ }+ }+ return false+}++// sfuFallback is SfuFallbackOptions. A zero timeout means the TS default.+type sfuFallback struct {+ url string+ tokenIssuer sfu.TokenIssuer+ admission *sfu.Admission+ roomControl sfu.RoomControl+ prepareTimeoutMs int64+ drainRetryMs int64+ hostOfflineCheckMs int64+}++// routerHooks are the signaling server callbacks of HybridMediaRouterOptions.+// Every hook is called with mu held and must not block (D11). shareGeneration+// returns "" where the TS returned undefined; routesChanged may be nil.+type routerHooks struct {+ sendToSession func(sessionID string, message protocol.ServerMessage)+ shareGeneration func(roomID string) string+ routesChanged func(roomID string)+}++// routerOptions is HybridMediaRouterOptions plus the shared mutex and the+// timer factory of D5. now and afterFunc default to the wall clock.+type routerOptions struct {+ mu *sync.Mutex+ store *room.Store+ endpointMediaCopyCapacity int+ sfu *sfuFallback+ hooks routerHooks+ now func() int64+ afterFunc func(time.Duration, func()) func() bool+}++// authenticatedRouteParticipant is AuthenticatedRouteParticipant; routePolicy+// is nil where the TS key was absent.+type authenticatedRouteParticipant struct {+ roomID string+ role protocol.Role+ peerID string+ sessionID string+ routePolicy *protocol.RoutePolicy+}++// hybridAuthenticationState is HybridAuthenticationState.+type hybridAuthenticationState struct {+ routeRevision int64+ routeAssignment protocol.ParticipantRouteAssignment+}++// activeViewerMediaEdge is ActiveViewerMediaEdge; upstream is peer or sfu.+type activeViewerMediaEdge struct {+ revision int64+ connectionID string+ upstream protocol.MediaRouteUpstream+}++// signalAuthorization is the `boolean | "probe" | undefined` result of+// peerSignalAuthorization. signalAuthorizationUnassigned is the TS undefined:+// the signaling server falls back to the committed-edge assignment.+type signalAuthorization int++const (+ signalAuthorizationUnassigned signalAuthorization = iota+ signalAuthorizationDenied+ signalAuthorizationAllowed+ signalAuthorizationProbe+)++// peerSignalInput is the peerSignalAuthorization input; descriptionType is+// "" where the TS key was absent.+type peerSignalInput struct {+ roomID string+ sourcePeerID string+ sourceSessionID string+ targetPeerID string+ targetSessionID string+ connectionID string+ signalKind string+ descriptionType string+}++// peerSignalDebugInput is the debugPeerSignal input; candidateOrigin and+// descriptionType are "" where the TS keys were absent.+type peerSignalDebugInput struct {+ roomID string+ sourcePeerID string+ targetPeerID string+ signalKind string+ candidateOrigin protocol.CandidateSignalOrigin+ descriptionType string+ authorization signalAuthorization+}++// roomRuntime is RoomRuntime. pumping is the `pump` promise used as a+// single-flight token; deadlineGeneration is bumped by every clearDeadline so+// a callback that lost the Stop race sees it is stale (D5).+type roomRuntime struct {+ hostPeerID string+ controller *route.Controller+ // O32: capacities survive stopRoom in insertion order.+ advertisedCapacityByViewer ordered.Map[string, int]+ requested bool+ pumping bool+ deadlineStop func() bool+ deadlineGeneration uint64+ sfuRefreshesInFlight map[string]struct{}+}++// hostOfflineCheck is HostOfflineCheck; the timer callback compares the+// registered pointer with the one it was armed with.+type hostOfflineCheck struct {+ hostPeerID string+ fence sfu.ResourceFence+ hostSessionID string+ connectionID string+ stop func() bool+}++// router is HybridMediaRouter.+type router struct {+ mu *sync.Mutex+ store *room.Store+ capacity int+ sfu *sfuFallback+ hooks routerHooks+ now func() int64+ afterFunc func(time.Duration, func()) func() bool++ // O14, O16, O29: rooms, drain tasks and waiters are walked in insertion+ // order.+ rooms ordered.Map[string, *roomRuntime]+ resourceWaiters ordered.Map[string, struct{}]+ sfuDrainTasks ordered.Map[string, *sfuDrainTask]+ hostOfflineChecks ordered.Map[string, *hostOfflineCheck]+ // roomTurns is the per managed-room-name FIFO of takeTurn.+ roomTurns map[string]chan struct{}+ // inflight counts the goroutines that will re-acquire mu: the pump+ // drivers, fresh SFU config issues and drains. It is the TS microtask+ // backlog; tests wait for it to reach zero where the TS awaited.+ inflight int+ closing bool+ // closeCtx bounds every drain started once close began (D6).+ closeCtx context.Context+}++// newRouter is the HybridMediaRouter constructor.+func newRouter(options routerOptions) *router {+ if err := protocol.AssertEndpointMediaCopyCapacity(options.endpointMediaCopyCapacity); err != nil {+ panic(err)+ }+ if options.sfu != nil {+ // TS: new URL(options.sfuFallback.url) throws on a relative URL.+ if parsed, err := url.Parse(options.sfu.url); err != nil || parsed.Scheme == "" {+ panic(errors.New("SFU fallback URL is invalid"))+ }+ }+ r := &router{+ mu: options.mu,+ store: options.store,+ capacity: options.endpointMediaCopyCapacity,+ sfu: options.sfu,+ hooks: options.hooks,+ now: options.now,+ afterFunc: options.afterFunc,+ roomTurns: map[string]chan struct{}{},+ }+ if r.now == nil {+ r.now = func() int64 { return time.Now().UnixMilli() }+ }+ if r.afterFunc == nil {+ r.afterFunc = func(d time.Duration, fn func()) func() bool {+ return time.AfterFunc(d, fn).Stop+ }+ }+ return r+}++// io is one TS `await` on external work: mu is released around fn and always+// re-acquired, including while a panic unwinds. That last part is the reason+// this is a helper rather than an inline Unlock/Lock pair: recoverPump turns a+// panic raised inside such a window into the TS pump rejection, and its+// caller's `defer r.mu.Unlock()` would otherwise unlock a mutex nobody holds+// (an unrecoverable runtime error). Nothing may touch router state inside fn.+func (r *router) io(fn func()) {+ r.mu.Unlock()+ defer r.mu.Lock()+ fn()+}++// close ports close(). mu must be held, as for every other router method: the+// synchronous prefix (closing flag, timers, drains scheduled) runs in the+// caller's critical section exactly as the TS ran it before its first await,+// and mu is released only inside awaitDrain, around each LiveKit wait (R1,+// R2). Drains run sequentially in insertion order (O16) and their errors are+// joined; ctx bounds every wait and every close-initiated LiveKit call.+func (r *router) close(ctx context.Context) error {+ r.closing = true+ r.closeCtx = ctx+ for _, roomID := range r.rooms.Keys() {+ r.clearRoom(roomID)+ }+ r.resourceWaiters.Clear()+ for _, check := range r.hostOfflineChecks.Values() {+ check.stop()+ }+ r.hostOfflineChecks.Clear()+ fallback := r.sfu+ if fallback == nil {+ return nil+ }+ for _, fence := range fallback.admission.BeginDrainAll() {+ r.scheduleSfuPublicationDrain(fence)+ }+ type entry struct {+ key string+ task *sfuDrainTask+ }+ var snapshot []entry+ for key, task := range r.sfuDrainTasks.All() {+ snapshot = append(snapshot, entry{key, task})+ }+ var errs []error+ for _, current := range snapshot {+ key, task := current.key, current.task+ r.clearDrainRetry(task)+ if task.operation != nil {+ if err := r.awaitDrain(ctx, task.operation); err != nil {+ errs = append(errs, err)+ continue+ }+ }+ if registered, _ := r.sfuDrainTasks.Get(key); registered == task {+ if err := r.awaitDrain(ctx, r.runSfuDrain(ctx, key, task)); err != nil {+ errs = append(errs, err)+ }+ }+ }+ if len(errs) > 0 {+ return fmt.Errorf("LiveKit drain failed during shutdown: %w", errors.Join(errs...))+ }+ return nil+}++// connectParticipant ports connectParticipant.+func (r *router) connectParticipant(input authenticatedRouteParticipant) hybridAuthenticationState {+ rm := r.room(input.roomID)+ if input.role == protocol.RoleHost {+ if rm.controller != nil && rm.hostPeerID != input.peerID {+ r.clearDeadline(rm)+ // rm.hostPeerID always equals the controller's, so this branch+ // takes RebindHostIdentity's clearing path: every committed edge+ // goes, which is what the TS per-viewer deleteConnectionId loop+ // then restated into the mirror.+ r.releaseResources(rm.controller.RebindHostIdentity(input.peerID, input.sessionID, r.nowPtr()))+ }+ rm.hostPeerID = input.peerID+ r.cancelHostOfflineCheck(input.roomID)+ if rm.controller == nil {+ r.createController(input.roomID, rm, input)+ }+ } else {+ capacity, _ := rm.advertisedCapacityByViewer.Get(input.peerID)+ rm.advertisedCapacityByViewer.Set(input.peerID, capacity)+ }+ if rm.controller != nil {+ capacity := r.capacity+ if input.role != protocol.RoleHost {+ capacity, _ = rm.advertisedCapacityByViewer.Get(input.peerID)+ }+ r.releaseResources(rm.controller.UpsertParticipant(route.ParticipantInput{+ PeerID: input.peerID,+ Role: input.role,+ SessionID: input.sessionID,+ EffectiveDownstreamCapacity: capacity,+ }, r.nowPtr()))+ }+ state := hybridAuthenticationState{routeAssignment: emptyAssignment()}+ if rm.controller != nil {+ current := rm.controller.Snapshot()+ state.routeRevision = current.Revision+ state.routeAssignment = assignmentFor(r.assignments(input.roomID, current, nil, "", ""), input.peerID)+ }+ return state+}++// completeAuthentication ports completeAuthentication.+func (r *router) completeAuthentication(participant authenticatedRouteParticipant, _ hybridAuthenticationState) {+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ r.broadcastActive(participant.roomID, rm)+ // TS: void this.sendFreshSfuConfig(participant).catch(() => undefined)+ r.sendFreshSfuConfig(participant, nil, nil)+ r.requestPump(participant.roomID)+}++// setPaused ports setPaused.+func (r *router) setPaused(roomID string, paused bool) {+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ before := rm.controller.Revision()+ r.releaseResources(rm.controller.SetPaused(paused, r.nowPtr()))+ if rm.controller.Revision() != before {+ r.broadcastActive(roomID, rm)+ }+ if !paused {+ r.requestPump(roomID)+ }+}++// routeDiagnosticSnapshot ports routeDiagnosticSnapshot.+func (r *router) routeDiagnosticSnapshot(roomID string) protocol.RouteDiagnosticSnapshot {+ if rm, _ := r.rooms.Get(roomID); rm != nil && rm.controller != nil {+ return rm.controller.RouteDiagnosticSnapshot(r.now())+ }+ return protocol.RouteDiagnosticSnapshot{Children: []protocol.RouteDiagnosticChild{}, Operation: nil}+}++// observeQualityEvidence ports observeQualityEvidence; roomID is the TS+// input's roomId and evidence the rest.+func (r *router) observeQualityEvidence(roomID string, evidence route.RouteQualityEvidenceInput) route.RouteQualityEvidenceResult {+ result := route.QualityEvidenceRejected+ if rm, _ := r.rooms.Get(roomID); rm != nil && rm.controller != nil {+ result = rm.controller.ObserveQualityEvidence(evidence)+ }+ if result != route.QualityEvidenceRejected && routeDebugEnabled {+ upstream := "sfu"+ if evidence.Upstream.Kind == route.UpstreamPeer {+ upstream = "p2p:" + r.debugPeer(roomID, evidence.Upstream.PeerID)+ }+ metrics := evidence.Metrics+ var packetLossPercent any+ if percent, ok := protocol.PacketLossPercentFromDeltas(+ intFloat(metrics.PacketsReceivedDelta), intFloat(metrics.PacketsLostDelta)); ok {+ packetLossPercent = percent+ }+ r.debug(roomID, "viewer-quality-evidence",+ "viewer", r.debugPeer(roomID, evidence.ChildPeerID),+ "upstream", upstream,+ "natTraversalPath", metrics.NatTraversalPath,+ "framesPerSecond", optional(metrics.FramesPerSecond),+ "bitrateKbps", optional(metrics.BitrateKbps),+ "width", optional(metrics.Width),+ "height", optional(metrics.Height),+ "framesDecoded", optional(metrics.FramesDecodedDelta),+ "freezes", optional(metrics.FreezeCountDelta),+ "pauses", optional(metrics.PauseCountDelta),+ "packetsReceivedDelta", optional(metrics.PacketsReceivedDelta),+ "packetsLostDelta", optional(metrics.PacketsLostDelta),+ "packetLossPercent", packetLossPercent,+ "rttMs", optional(metrics.RttMs),+ "jitterMs", optional(metrics.JitterMs))+ }+ return result+}++// observeSenderQualityEvidence ports observeSenderQualityEvidence.+func (r *router) observeSenderQualityEvidence(participant authenticatedRouteParticipant, message protocol.SenderQualityEvidenceMessage) bool {+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil {+ return false+ }+ controller := rm.controller+ snapshot := controller.Snapshot()+ before := snapshot.Revision+ endpointCapacity := r.capacity+ if participant.role != protocol.RoleHost {+ advertised, _ := rm.advertisedCapacityByViewer.Get(participant.peerID)+ endpointCapacity = min(advertised, r.capacity)+ }+ copyContext := r.qualityCopyContext(snapshot, rm.hostPeerID, participant.peerID, endpointCapacity, qualitySample{+ kind: route.UpstreamPeer,+ childPeerID: message.ChildPeerID,+ routeRevision: int64(message.RouteRevision),+ connectionID: message.ConnectionID,+ })+ var senderIdentity *string+ if message.RtpStatsID != nil && *message.RtpStatsID != "" &&+ message.TrackIdentifier != nil && *message.TrackIdentifier != "" {+ identity := *message.RtpStatsID + "\x00" + *message.TrackIdentifier+ senderIdentity = &identity+ }+ input := route.SenderQualityEvidenceInput{+ ParentPeerID: participant.peerID,+ ParentSessionID: participant.sessionID,+ ChildPeerID: message.ChildPeerID,+ RouteRevision: int64(message.RouteRevision),+ ConnectionID: message.ConnectionID,+ SenderIdentity: senderIdentity,+ SampleTimestampMs: sampleTimestamp(message.SampleTimestampMs),+ State: route.SenderQualityState(message.State),+ AcceptedAtMs: r.now(),+ }+ result := controller.ObserveSenderQualityEvidence(input, r.commitReservation)+ if result.Accepted && routeDebugEnabled {+ diagnostics := message.Diagnostics+ details := []any{+ "parent", r.debugPeer(participant.roomID, participant.peerID),+ "child", r.debugPeer(participant.roomID, message.ChildPeerID),+ "routeRevision", int64(message.RouteRevision),+ }+ details = append(details, copyContext.kv()...)+ details = append(details,+ "state", message.State,+ "natTraversalPath", diagnostics.NatTraversalPath,+ "reason", optional(diagnostics.Reason),+ "framesPerSecond", optional(diagnostics.FramesPerSecond),+ "bitrateKbps", optional(diagnostics.BitrateKbps),+ "captureFramesPerSecond", nullable(diagnostics.CaptureFramesPerSecond),+ "mediaSourceFramesPerSecond", nullable(diagnostics.MediaSourceFramesPerSecond),+ "width", nullable(diagnostics.Width),+ "height", nullable(diagnostics.Height),+ "availableOutgoingKbps", nullable(diagnostics.AvailableOutgoingKbps),+ "rttMs", nullable(diagnostics.RttMs),+ "packetLossPercent", nullable(diagnostics.PacketLossPercent))+ r.debug(participant.roomID, "sender-quality-evidence", details...)+ }+ r.releaseResources(result.Released)+ if result.Committed {+ r.resourceWaiters.Delete(participant.roomID)+ }+ if controller.Revision() != before {+ r.broadcastActive(participant.roomID, rm)+ }+ r.sendRouteFailures(participant.roomID, result.FailedPeerIDs, controller.Revision())+ if result.Accepted {+ r.requestPump(participant.roomID)+ }+ return result.Accepted+}++// observeSfuPublisherQualityEvidence ports observeSfuPublisherQualityEvidence.+func (r *router) observeSfuPublisherQualityEvidence(participant authenticatedRouteParticipant, message protocol.SfuPublisherQualityEvidenceMessage) bool {+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil || participant.role != protocol.RoleHost {+ return false+ }+ controller := rm.controller+ snapshot := controller.Snapshot()+ operation := snapshot.Operation+ candidateChildPeerID, candidateConnectionID := "", ""+ if operation != nil {+ candidateChildPeerID = operation.ChildPeerID+ if operation.Current != nil {+ candidateConnectionID = operation.Current.ConnectionID+ }+ }+ before := snapshot.Revision+ copyContext := r.qualityCopyContext(snapshot, participant.peerID, participant.peerID, r.capacity, qualitySample{+ kind: route.UpstreamSfu,+ routeRevision: int64(message.RouteRevision),+ publicationGeneration: message.PublicationGeneration,+ hostSessionID: participant.sessionID,+ })+ input := route.SfuPublisherQualityEvidenceInput{+ HostPeerID: participant.peerID,+ HostSessionID: participant.sessionID,+ PublicationGeneration: message.PublicationGeneration,+ RouteRevision: int64(message.RouteRevision),+ State: route.SenderQualityState(message.State),+ SampleTimestampMs: sampleTimestamp(message.SampleTimestampMs),+ AcceptedAtMs: r.now(),+ }+ result := controller.ObserveSfuPublisherQualityEvidence(input, r.commitReservation)+ if result.Accepted && routeDebugEnabled {+ diagnostics := message.Diagnostics+ details := []any{"routeRevision", int64(message.RouteRevision)}+ details = append(details, copyContext.kv()...)+ details = append(details,+ "state", message.State,+ "reason", optional(diagnostics.Reason),+ "framesPerSecond", optional(diagnostics.FramesPerSecond),+ "bitrateKbps", optional(diagnostics.BitrateKbps),+ "captureFramesPerSecond", nullable(diagnostics.CaptureFramesPerSecond),+ "mediaSourceFramesPerSecond", nullable(diagnostics.MediaSourceFramesPerSecond),+ "width", nullable(diagnostics.Width),+ "height", nullable(diagnostics.Height),+ "videoEncodingCount", nullable(diagnostics.VideoEncodingCount),+ "activeVideoEncodingCount", nullable(diagnostics.ActiveVideoEncodingCount),+ "availableOutgoingKbps", nullable(diagnostics.AvailableOutgoingKbps),+ "rttMs", nullable(diagnostics.RttMs),+ "packetLossPercent", nullable(diagnostics.PacketLossPercent))+ r.debug(participant.roomID, "sfu-publisher-quality-evidence", details...)+ }+ r.releaseResources(result.Released)+ if result.Committed && candidateChildPeerID != "" && candidateConnectionID != "" {+ r.resourceWaiters.Delete(participant.roomID)+ }+ if controller.Revision() != before {+ r.broadcastActive(participant.roomID, rm)+ }+ r.sendRouteFailures(participant.roomID, result.FailedPeerIDs, controller.Revision())+ if result.Accepted {+ r.requestPump(participant.roomID)+ }+ return result.Accepted+}++// resetSenderQuality ports resetSenderQuality.+func (r *router) resetSenderQuality(participant authenticatedRouteParticipant) {+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ before := rm.controller.Revision()+ r.releaseResources(rm.controller.ResetSenderQuality(participant.peerID, participant.sessionID, r.now()))+ if rm.controller.Revision() != before {+ r.broadcastActive(participant.roomID, rm)+ }+ r.requestPump(participant.roomID)+}++// isActivePeerParentOf ports isActivePeerParentOf.+func (r *router) isActivePeerParentOf(roomID, parentPeerID, childPeerID string) bool {+ _, activeParent, ok := r.resolveActivePeerEdge(roomID, childPeerID)+ return ok && activeParent == parentPeerID+}++// resolveActivePeerEdge ports resolveActivePeerEdge; ok is false where the+// TS returned undefined.+func (r *router) resolveActivePeerEdge(roomID, childPeerID string) (revision int64, parentPeerID string, ok bool) {+ edge, found := r.resolveActiveViewerMediaEdge(roomID, childPeerID)+ if !found || edge.upstream.Kind != "peer" {+ return 0, "", false+ }+ return edge.revision, edge.upstream.PeerID, true+}++// resolveActiveViewerMediaEdge ports resolveActiveViewerMediaEdge.+func (r *router) resolveActiveViewerMediaEdge(roomID, childPeerID string) (activeViewerMediaEdge, bool) {+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.controller == nil {+ return activeViewerMediaEdge{}, false+ }+ snapshot := rm.controller.Snapshot()+ edge, hasEdge := snapshot.UpstreamByViewer.Get(childPeerID)+ if !hasEdge || !r.pathIsPhysical(roomID, snapshot, childPeerID) {+ return activeViewerMediaEdge{}, false+ }+ upstream := protocol.SfuUpstream()+ if edge.Kind == route.UpstreamPeer {+ upstream = protocol.PeerUpstream(edge.ParentPeerID)+ }+ return activeViewerMediaEdge{+ revision: snapshot.Revision,+ connectionID: edge.ConnectionID,+ upstream: upstream,+ }, true+}++// getViewerRouteUpstream ports getViewerRouteUpstream.+func (r *router) getViewerRouteUpstream(roomID, viewerPeerID string) protocol.MediaRouteUpstream {+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.controller == nil {+ return protocol.NoUpstream()+ }+ return assignmentFor(r.assignments(roomID, rm.controller.Snapshot(), nil, "", ""), viewerPeerID).Upstream+}++// peerSignalAuthorization ports peerSignalAuthorization.+func (r *router) peerSignalAuthorization(input peerSignalInput) signalAuthorization {+ rm, _ := r.rooms.Get(input.roomID)+ if rm == nil || rm.controller == nil {+ return signalAuthorizationUnassigned+ }+ controller := rm.controller+ snapshot := controller.Snapshot()+ operation := snapshot.Operation+ if operation != nil && operation.Current != nil && operation.Current.Tuple.Kind == route.UpstreamPeer {+ current := operation.Current+ parent, hasParent := r.connectedPeer(input.roomID, current.Tuple.ParentPeerID)+ child, hasChild := r.store.GetConnectedViewer(input.roomID, operation.ChildPeerID)+ parentToChild := input.sourcePeerID == current.Tuple.ParentPeerID &&+ input.targetPeerID == operation.ChildPeerID+ childToParent := input.sourcePeerID == operation.ChildPeerID &&+ input.targetPeerID == current.Tuple.ParentPeerID+ if parentToChild || childToParent {+ parentSession, childSession := input.targetSessionID, input.sourceSessionID+ if parentToChild {+ parentSession, childSession = input.sourceSessionID, input.targetSessionID+ }+ if hasParent && hasChild &&+ parent.SessionID == parentSession &&+ child.SessionID == childSession &&+ input.connectionID == current.ConnectionID &&+ (input.signalKind == "candidate" ||+ (parentToChild && input.descriptionType == "offer") ||+ (childToParent && input.descriptionType == "answer")) {+ return signalAuthorizationProbe+ }+ return signalAuthorizationDenied+ }+ }++ childPeerID := childForPair(snapshot, input.sourcePeerID, input.targetPeerID)+ if childPeerID == "" {+ return signalAuthorizationUnassigned+ }+ edge, hasEdge := snapshot.UpstreamByViewer.Get(childPeerID)+ if !hasEdge || edge.Kind != route.UpstreamPeer || !edge.PhysicalActive {+ return signalAuthorizationUnassigned+ }+ parentToChild := input.sourcePeerID == edge.ParentPeerID+ sessionsMatch := (parentToChild &&+ input.sourceSessionID == edge.ParentSessionID &&+ input.targetSessionID == edge.ChildSessionID) ||+ (!parentToChild &&+ input.sourceSessionID == edge.ChildSessionID &&+ input.targetSessionID == edge.ParentSessionID)+ if !sessionsMatch {+ return signalAuthorizationDenied+ }+ if edge.Transport == route.TransportDirect &&+ parentToChild &&+ input.signalKind == "description" &&+ input.descriptionType == "offer" &&+ input.connectionID != edge.ConnectionID {+ adopted := controller.AdoptDirectConnection(route.AdoptDirectConnectionInput{+ EdgeGuard: route.EdgeGuard{+ ChildPeerID: childPeerID,+ ChildSessionID: edge.ChildSessionID,+ ParentSessionID: edge.ParentSessionID,+ RouteRevision: snapshot.Revision,+ ConnectionID: edge.ConnectionID,+ },+ NewConnectionID: input.connectionID,+ })+ if adopted {+ return signalAuthorizationAllowed+ }+ return signalAuthorizationDenied+ }+ if input.connectionID == edge.ConnectionID {+ return signalAuthorizationAllowed+ }+ return signalAuthorizationDenied+}++// debugPeerSignal ports debugPeerSignal.+func (r *router) debugPeerSignal(input peerSignalDebugInput) {+ if !routeDebugEnabled {+ return+ }+ var authorization any+ switch input.authorization {+ case signalAuthorizationUnassigned:+ authorization = "assignment"+ case signalAuthorizationDenied:+ authorization = false+ case signalAuthorizationAllowed:+ authorization = true+ case signalAuthorizationProbe:+ authorization = "probe"+ }+ r.debug(input.roomID, "peer-signal",+ "source", r.debugPeer(input.roomID, input.sourcePeerID),+ "target", r.debugPeer(input.roomID, input.targetPeerID),+ "signalKind", input.signalKind,+ "candidateOrigin", nullString(string(input.candidateOrigin)),+ "descriptionType", nullString(input.descriptionType),+ "authorization", authorization)+}++// setViewerRelayCapacity ports setViewerRelayCapacity.+func (r *router) setViewerRelayCapacity(participant authenticatedRouteParticipant, downstreamEdges int) {+ rm := r.room(participant.roomID)+ r.debug(participant.roomID, "relay-capacity-received",+ "participant", r.debugPeer(participant.roomID, participant.peerID),+ "downstreamEdges", downstreamEdges)+ rm.advertisedCapacityByViewer.Set(participant.peerID, downstreamEdges)+ if rm.controller != nil &&+ rm.controller.SetEffectiveCapacity(participant.peerID, participant.sessionID, downstreamEdges, r.nowPtr()) {+ r.requestPump(participant.roomID)+ }+}++// handleRouteReady ports handleRouteReady.+func (r *router) handleRouteReady(participant authenticatedRouteParticipant, message protocol.RouteReadyMessage) {+ if participant.role != protocol.RoleViewer || message.Phase != "prepare" {+ return+ }+ revision := int64(message.Revision)+ r.debug(participant.roomID, "route-ready-received",+ "participant", r.debugPeer(participant.roomID, participant.peerID),+ "revision", revision)+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ controller := rm.controller+ operation := controller.Operation()+ if operation == nil || operation.Current == nil ||+ operation.ChildPeerID != participant.peerID ||+ operation.ChildSessionID != participant.sessionID ||+ operation.Current.Revision != revision {+ return+ }+ current := operation.Current+ before := controller.Revision()+ settled := controller.CandidateReady(route.CandidateGuard{+ ChildPeerID: participant.peerID,+ ChildSessionID: participant.sessionID,+ Revision: revision,+ ConnectionID: current.ConnectionID,+ }, r.now(), r.commitReservation, route.CandidateProof{RelativeQualityApproved: message.QualityApproved})+ r.debug(participant.roomID, "route-ready-settled",+ "participant", r.debugPeer(participant.roomID, participant.peerID),+ "revision", revision,+ "accepted", settled.Accepted,+ "exhausted", len(settled.FailedPeerIDs) > 0)+ r.releaseResources(settled.Released)+ if settled.Committed && settled.Accepted {+ r.resourceWaiters.Delete(participant.roomID)+ }+ if controller.Revision() != before {+ r.broadcastActive(participant.roomID, rm)+ }+ r.sendRouteFailures(participant.roomID, settled.FailedPeerIDs, controller.Revision())+ r.requestPump(participant.roomID)+}++// handleRouteTransportConnected ports handleRouteTransportConnected.+func (r *router) handleRouteTransportConnected(participant authenticatedRouteParticipant, message protocol.RouteTransportConnectedMessage) {+ if participant.role != protocol.RoleViewer {+ return+ }+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ controller := rm.controller+ operation := controller.Operation()+ revision := int64(message.Revision)+ if operation == nil || operation.Current == nil ||+ operation.ChildPeerID != participant.peerID ||+ operation.ChildSessionID != participant.sessionID ||+ operation.Current.Revision != revision ||+ operation.Current.ConnectionID != message.ConnectionID ||+ operation.Current.Tuple.Kind != route.UpstreamPeer {+ return+ }+ before := controller.Revision()+ progressed := controller.CandidateTransportConnected(route.CandidateGuard{+ ChildPeerID: participant.peerID,+ ChildSessionID: participant.sessionID,+ Revision: revision,+ ConnectionID: message.ConnectionID,+ }, r.now())+ r.releaseResources(progressed.Released)+ if controller.Revision() != before {+ r.broadcastActive(participant.roomID, rm)+ }+ r.sendRouteFailures(participant.roomID, progressed.FailedPeerIDs, controller.Revision())+ after := controller.Operation()+ if !progressed.Accepted || after == nil || after.WakeAtMs != operation.WakeAtMs {+ r.requestPump(participant.roomID)+ }+}++// handleRouteMediaUnavailable ports handleRouteMediaUnavailable.+func (r *router) handleRouteMediaUnavailable(participant authenticatedRouteParticipant, message protocol.RouteMediaUnavailableMessage) {+ if participant.role != protocol.RoleViewer {+ return+ }+ revision := int64(message.Revision)+ r.debug(participant.roomID, "sfu-media-unavailable",+ "participant", r.debugPeer(participant.roomID, participant.peerID),+ "revision", revision)+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ snapshot := rm.controller.Snapshot()+ edge, hasEdge := snapshot.UpstreamByViewer.Get(participant.peerID)+ if snapshot.Paused || snapshot.Revision != revision ||+ !hasEdge || edge.Kind != route.UpstreamSfu ||+ edge.ChildSessionID != participant.sessionID {+ return+ }+ rm.controller.InvalidateEdge(route.EdgeGuard{+ ChildPeerID: participant.peerID,+ ChildSessionID: participant.sessionID,+ RouteRevision: snapshot.Revision,+ ConnectionID: edge.ConnectionID,+ }, r.nowPtr())+ r.requestPump(participant.roomID)+}++// handleRouteFailed ports handleRouteFailed.+func (r *router) handleRouteFailed(participant authenticatedRouteParticipant, message protocol.RouteFailedMessage) {+ connectionID := ""+ if message.ConnectionID != nil {+ connectionID = *message.ConnectionID+ }+ revision := int64(message.Revision)+ r.debug(participant.roomID, "route-failed-received",+ "participant", r.debugPeer(participant.roomID, participant.peerID),+ "role", participant.role,+ "phase", message.Phase,+ "revision", revision,+ "hasConnectionId", connectionID != "")+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ controller := rm.controller+ snapshot := controller.Snapshot()+ if message.Phase == "prepare" {+ operation := snapshot.Operation+ if operation == nil || operation.Current == nil || operation.Current.Revision != revision {+ return+ }+ current := operation.Current+ ownsChild := participant.role == protocol.RoleViewer &&+ participant.peerID == operation.ChildPeerID &&+ participant.sessionID == operation.ChildSessionID+ ownsParent := false+ if current.Tuple.Kind == route.UpstreamPeer && participant.peerID == current.Tuple.ParentPeerID {+ peer, ok := r.connectedPeer(participant.roomID, participant.peerID)+ ownsParent = ok && peer.SessionID == participant.sessionID+ }+ ownsPublication := false+ if current.Tuple.Kind == route.UpstreamSfu && participant.role == protocol.RoleHost &&+ participant.peerID == rm.hostPeerID {+ host, ok := r.store.GetConnectedHost(participant.roomID)+ ownsPublication = ok && host.SessionID == participant.sessionID+ }+ if !ownsChild && !ownsParent && !ownsPublication {+ return+ }+ if connectionID != "" && connectionID != current.ConnectionID {+ return+ }+ before := snapshot.Revision+ settled := controller.CandidateFailed(route.CandidateGuard{+ ChildPeerID: operation.ChildPeerID,+ ChildSessionID: operation.ChildSessionID,+ Revision: current.Revision,+ ConnectionID: current.ConnectionID,+ }, r.now())+ r.releaseResources(settled.Released)+ if controller.Revision() != before {+ r.broadcastActive(participant.roomID, rm)+ }+ r.sendRouteFailures(participant.roomID, settled.FailedPeerIDs, controller.Revision())+ r.requestPump(participant.roomID)+ return+ }++ if snapshot.Revision != revision {+ return+ }+ if participant.role == protocol.RoleHost {+ if connectionID != "" && controller.InvalidateDirectEdgeFromParent(route.ParentEdgeGuard{+ ParentPeerID: participant.peerID,+ ParentSessionID: participant.sessionID,+ RouteRevision: snapshot.Revision,+ ConnectionID: connectionID,+ }, r.nowPtr()) {+ r.requestPump(participant.roomID)+ return+ }+ publication := snapshot.HostPublication+ if publication == nil || publication.HostSessionID != participant.sessionID ||+ (connectionID != "" && connectionID != publication.ConnectionID) {+ return+ }+ controller.InvalidateHostPublication(route.PublicationGuard{+ HostSessionID: participant.sessionID,+ RouteRevision: snapshot.Revision,+ Generation: publication.Generation,+ ConnectionID: publication.ConnectionID,+ }, r.nowPtr())+ r.releaseResources(controller.RetireHostPublication(route.PublicationGuard{+ HostSessionID: participant.sessionID,+ RouteRevision: controller.Revision(),+ Generation: publication.Generation,+ ConnectionID: publication.ConnectionID,+ }))+ r.broadcastActive(participant.roomID, rm)+ r.requestPump(participant.roomID)+ return+ }++ edge, hasEdge := snapshot.UpstreamByViewer.Get(participant.peerID)+ if !hasEdge || edge.ChildSessionID != participant.sessionID ||+ (connectionID != "" && connectionID != edge.ConnectionID) {+ return+ }+ guard := route.EdgeGuard{+ ChildPeerID: participant.peerID,+ ChildSessionID: participant.sessionID,+ RouteRevision: snapshot.Revision,+ ConnectionID: edge.ConnectionID,+ }+ if edge.Kind == route.UpstreamPeer {+ guard.ParentSessionID = edge.ParentSessionID+ }+ invalidated := controller.InvalidateEdge(guard, r.nowPtr())+ if invalidated && edge.Usable && snapshot.Paused && r.hooks.routesChanged != nil {+ r.hooks.routesChanged(participant.roomID)+ }+ r.requestPump(participant.roomID)+}++// refreshSfu ports refreshSfu.+func (r *router) refreshSfu(participant authenticatedRouteParticipant, revision int64) {+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ currentRevision := rm.controller.Revision()+ if revision > currentRevision {+ return+ }+ key := fmt.Sprintf("%d\x00%s\x00%s", currentRevision, participant.peerID, participant.sessionID)+ if _, inFlight := rm.sfuRefreshesInFlight[key]; inFlight {+ return+ }+ rm.sfuRefreshesInFlight[key] = struct{}{}+ r.sendFreshSfuConfig(participant,+ func() { r.failCurrentSfuRoute(participant, currentRevision) },+ func() { delete(rm.sfuRefreshesInFlight, key) })+}++// failCurrentSfuRoute ports failCurrentSfuRoute.+func (r *router) failCurrentSfuRoute(participant authenticatedRouteParticipant, revision int64) {+ rm, _ := r.rooms.Get(participant.roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ snapshot := rm.controller.Snapshot()+ if snapshot.Revision != revision {+ return+ }+ connectionID := ""+ if participant.peerID == rm.hostPeerID {+ if snapshot.HostPublication != nil {+ connectionID = snapshot.HostPublication.ConnectionID+ }+ } else if edge, ok := snapshot.UpstreamByViewer.Get(participant.peerID); ok && edge.Kind == route.UpstreamSfu {+ connectionID = edge.ConnectionID+ }+ if connectionID == "" {+ return+ }+ r.handleRouteFailed(participant, protocol.RouteFailedMessage{+ Type: "route-failed",+ Revision: protocol.Int(revision),+ Phase: "active",+ ConnectionID: &connectionID,+ })+}++// disconnectParticipant ports disconnectParticipant.+func (r *router) disconnectParticipant(roomID, peerID, sessionID string) {+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.controller == nil || !rm.controller.DisconnectSession(peerID, sessionID) {+ return+ }+ if peerID == rm.hostPeerID {+ r.scheduleHostOfflineCheck(roomID, peerID)+ }+ r.requestPump(roomID)+}++// removeViewer ports removeViewer.+func (r *router) removeViewer(roomID, peerID string) {+ rm, _ := r.rooms.Get(roomID)+ if rm != nil {+ rm.advertisedCapacityByViewer.Delete(peerID)+ }+ if rm != nil && rm.controller != nil && rm.controller.ConfirmDeparture(peerID, r.nowPtr()) {+ r.requestPump(roomID)+ } else if rm != nil && rm.controller == nil && rm.advertisedCapacityByViewer.Len() == 0 {+ r.rooms.Delete(roomID)+ }+}++// stopRoom ports stopRoom: advertised capacities survive the share (O32).+func (r *router) stopRoom(roomID string) {+ type capacity struct {+ peerID string+ value int+ }+ var capacities []capacity+ if rm, _ := r.rooms.Get(roomID); rm != nil {+ for peerID, value := range rm.advertisedCapacityByViewer.All() {+ capacities = append(capacities, capacity{peerID, value})+ }+ }+ r.clearRoom(roomID)+ if len(capacities) > 0 {+ rm := r.room(roomID)+ for _, current := range capacities {+ rm.advertisedCapacityByViewer.Set(current.peerID, current.value)+ }+ }+}++// deleteRoom ports deleteRoom.+func (r *router) deleteRoom(roomID string) {+ r.clearRoom(roomID)+}++func (r *router) room(roomID string) *roomRuntime {+ rm, ok := r.rooms.Get(roomID)+ if !ok {+ rm = &roomRuntime{sfuRefreshesInFlight: map[string]struct{}{}}+ r.rooms.Set(roomID, rm)+ }+ return rm+}++// createController ports createController (O18: connected viewers in store+// order).+func (r *router) createController(roomID string, rm *roomRuntime, host authenticatedRouteParticipant) {+ routePolicy := host.routePolicy+ operationTimeoutMs := defaultRouteOperationTimeoutMs+ if r.sfu != nil && r.sfu.prepareTimeoutMs != 0 {+ operationTimeoutMs = r.sfu.prepareTimeoutMs+ }+ rm.controller = route.New(route.Options{+ HostPeerID: host.peerID,+ DebugRoomID: roomID,+ EndpointMediaCopyCapacity: r.capacity,+ OperationTimeoutMs: operationTimeoutMs,+ SfuEnabled: r.sfu != nil && !(routePolicy != nil && routePolicy.PeerOnly),+ QualityConvergenceEnabled: routePolicy != nil && routePolicy.TopologyOptimization,+ NatPredictionEnabled: routePolicy != nil && routePolicy.NatPrediction,+ })+ rm.controller.UpsertParticipant(route.ParticipantInput{+ PeerID: host.peerID,+ Role: protocol.RoleHost,+ SessionID: host.sessionID,+ EffectiveDownstreamCapacity: r.capacity,+ }, r.nowPtr())+ for _, viewer := range r.store.GetConnectedViewers(roomID) {+ capacity, _ := rm.advertisedCapacityByViewer.Get(viewer.PeerID)+ rm.controller.UpsertParticipant(route.ParticipantInput{+ PeerID: viewer.PeerID,+ Role: protocol.RoleViewer,+ SessionID: viewer.SessionID,+ EffectiveDownstreamCapacity: capacity,+ }, r.nowPtr())+ }+}++// clearRoom ports clearRoom (O31: admission publication order).+func (r *router) clearRoom(roomID string) {+ rm, ok := r.rooms.Get(roomID)+ if !ok {+ return+ }+ r.clearDeadline(rm)+ r.cancelHostOfflineCheck(roomID)+ controller := rm.controller+ rm.controller = nil+ rm.requested = false+ if controller != nil {+ r.releaseResources(controller.Dispose())+ }+ r.rooms.Delete(roomID)+ r.resourceWaiters.Delete(roomID)+ if r.sfu != nil {+ for _, fence := range r.sfu.admission.BeginDrainRoom(roomID) {+ r.scheduleSfuPublicationDrain(fence)+ }+ }+}++// assignmentEdge is the value of the `edges` map of assignments().+type assignmentEdge struct {+ kind route.UpstreamKind+ parentPeerID string+ publicationGeneration string+}++// assignments ports assignments(). candidate overlays the current attempt+// (nil for the committed graph only). O19: peers are the host first, then+// the store's viewer order; O20/O21: edges keep the snapshot's insertion+// order, which is the childPeerIds order on the wire.+func (r *router) assignments(+ roomID string,+ snapshot route.RouteSnapshot,+ candidate *route.CandidateTuple,+ candidateChildPeerID string,+ candidatePublicationGeneration string,+) map[string]protocol.ParticipantRouteAssignment {+ assignments := map[string]protocol.ParticipantRouteAssignment{}+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.hostPeerID == "" {+ return assignments+ }+ hostPeerID := rm.hostPeerID+ peerIDs := []string{hostPeerID}+ seen := map[string]struct{}{hostPeerID: {}}+ for _, peerID := range r.store.GetViewerPeerIDs(roomID) {+ if _, duplicate := seen[peerID]; !duplicate {+ seen[peerID] = struct{}{}+ peerIDs = append(peerIDs, peerID)+ }+ }+ edges := &ordered.Map[string, assignmentEdge]{}+ for childPeerID, edge := range snapshot.UpstreamByViewer.All() {+ if !edge.PhysicalActive {+ continue+ }+ if edge.Kind == route.UpstreamPeer {+ edges.Set(childPeerID, assignmentEdge{kind: route.UpstreamPeer, parentPeerID: edge.ParentPeerID})+ } else {+ edges.Set(childPeerID, assignmentEdge{kind: route.UpstreamSfu, publicationGeneration: edge.PublicationGeneration})+ }+ }+ publicationGeneration := ""+ if snapshot.HostPublication != nil && snapshot.HostPublication.PhysicalActive {+ publicationGeneration = snapshot.HostPublication.Generation+ }+ if candidate != nil && candidateChildPeerID != "" {+ // TS delete-then-set: the candidate child moves to the back.+ edges.Delete(candidateChildPeerID)+ if candidate.Kind == route.UpstreamPeer {+ edges.Set(candidateChildPeerID, assignmentEdge{kind: route.UpstreamPeer, parentPeerID: candidate.ParentPeerID})+ if old, hasOld := snapshot.UpstreamByViewer.Get(candidateChildPeerID); hasOld && old.Kind == route.UpstreamSfu {+ anySfu := false+ for _, edge := range edges.Values() {+ if edge.kind == route.UpstreamSfu {+ anySfu = true+ break+ }+ }+ if !anySfu {+ publicationGeneration = ""+ }+ }+ } else {+ if candidate.Publication != route.PublicationReuse {+ for peerID, edge := range edges.All() {+ if edge.kind == route.UpstreamSfu {+ edges.Delete(peerID)+ }+ }+ publicationGeneration = candidatePublicationGeneration+ }+ if publicationGeneration != "" {+ edges.Set(candidateChildPeerID, assignmentEdge{kind: route.UpstreamSfu, publicationGeneration: publicationGeneration})+ }+ }+ }+ var sourceReachable func(peerID string, visited map[string]struct{}) bool+ sourceReachable = func(peerID string, visited map[string]struct{}) bool {+ if peerID == hostPeerID {+ return true+ }+ if _, again := visited[peerID]; again {+ return false+ }+ visited[peerID] = struct{}{}+ edge, ok := edges.Get(peerID)+ if !ok {+ return false+ }+ if edge.kind == route.UpstreamSfu {+ return publicationGeneration == edge.publicationGeneration+ }+ return sourceReachable(edge.parentPeerID, visited)+ }+ for _, peerID := range peerIDs {+ edge, hasEdge := edges.Get(peerID)+ reachable := sourceReachable(peerID, map[string]struct{}{})+ childPeerIDs := []string{}+ for childPeerID, child := range edges.All() {+ if child.kind == route.UpstreamPeer && child.parentPeerID == peerID {+ childPeerIDs = append(childPeerIDs, childPeerID)+ }+ }+ upstream := protocol.NoUpstream()+ switch {+ case peerID == hostPeerID || !hasEdge:+ case edge.kind == route.UpstreamPeer:+ upstream = protocol.PeerUpstream(edge.parentPeerID)+ case reachable:+ upstream = protocol.SfuUpstream()+ }+ var sfuPublicationGeneration *string+ if peerID == hostPeerID {+ if publicationGeneration != "" {+ generation := publicationGeneration+ sfuPublicationGeneration = &generation+ }+ } else if reachable && hasEdge && edge.kind == route.UpstreamSfu {+ generation := edge.publicationGeneration+ sfuPublicationGeneration = &generation+ }+ assignments[peerID] = protocol.ParticipantRouteAssignment{+ Upstream: upstream,+ ChildPeerIDs: childPeerIDs,+ SfuPublicationGeneration: sfuPublicationGeneration,+ }+ }+ return assignments+}++// broadcastActive ports broadcastActive (O23: host first, then viewers in+// store order; one routesChanged at the end).+func (r *router) broadcastActive(roomID string, rm *roomRuntime) {+ if rm.controller == nil {+ return+ }+ snapshot := rm.controller.Snapshot()+ if routeDebugEnabled {+ type routeEntry struct {+ Child string `json:"child"`+ Parent string `json:"parent"`+ Usable bool `json:"usable"`+ PhysicalActive bool `json:"physicalActive"`+ }+ routes := []routeEntry{}+ for childPeerID, edge := range snapshot.UpstreamByViewer.All() {+ parent := "sfu"+ if edge.Kind == route.UpstreamPeer {+ parent = r.debugPeer(roomID, edge.ParentPeerID)+ }+ routes = append(routes, routeEntry{r.debugPeer(roomID, childPeerID), parent, edge.Usable, edge.PhysicalActive})+ }+ r.debug(roomID, "active-topology",+ "revision", snapshot.Revision,+ "paused", snapshot.Paused,+ "hostPublication", snapshot.HostPublication != nil && snapshot.HostPublication.PhysicalActive,+ "routes", routes)+ }+ assignments := r.assignments(roomID, snapshot, nil, "", "")+ var participants []room.ConnectedPeer+ if host, ok := r.store.GetConnectedHost(roomID); ok {+ participants = append(participants, host)+ }+ participants = append(participants, r.store.GetConnectedViewers(roomID)...)+ for _, participant := range participants {+ r.hooks.sendToSession(participant.SessionID, protocol.RouteUpdateActiveMessage{+ Type: "route-update",+ Revision: protocol.Int(snapshot.Revision),+ Phase: "active",+ Assignment: assignmentFor(assignments, participant.PeerID),+ })+ }+ if r.hooks.routesChanged != nil {+ r.hooks.routesChanged(roomID)+ }+}++// pathIsPhysical ports pathIsPhysical.+func (r *router) pathIsPhysical(roomID string, snapshot route.RouteSnapshot, childPeerID string) bool {+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.hostPeerID == "" {+ return false+ }+ hostPeerID := rm.hostPeerID+ seen := map[string]struct{}{}+ current := childPeerID+ for current != hostPeerID {+ if _, again := seen[current]; again {+ return false+ }+ seen[current] = struct{}{}+ edge, ok := snapshot.UpstreamByViewer.Get(current)+ if !ok || !edge.PhysicalActive || !edge.Usable {+ return false+ }+ if edge.Kind == route.UpstreamSfu {+ return snapshot.HostPublication != nil &&+ snapshot.HostPublication.PhysicalActive &&+ snapshot.HostPublication.Generation == edge.PublicationGeneration+ }+ if edge.ParentPeerID == hostPeerID {+ return true+ }+ current = edge.ParentPeerID+ }+ return true+}++// childForPair ports childForPair; "" is the TS undefined.+func childForPair(snapshot route.RouteSnapshot, firstPeerID, secondPeerID string) string {+ if first, ok := snapshot.UpstreamByViewer.Get(firstPeerID); ok &&+ first.Kind == route.UpstreamPeer && first.ParentPeerID == secondPeerID {+ return firstPeerID+ }+ if second, ok := snapshot.UpstreamByViewer.Get(secondPeerID); ok &&+ second.Kind == route.UpstreamPeer && second.ParentPeerID == firstPeerID {+ return secondPeerID+ }+ return ""+}++// connectedPeer ports connectedPeer.+func (r *router) connectedPeer(roomID, peerID string) (room.ConnectedPeer, bool) {+ if host, ok := r.store.GetConnectedHost(roomID); ok && host.PeerID == peerID {+ return host, true+ }+ return r.store.GetConnectedViewer(roomID, peerID)+}++// debugPeer ports debugPeer.+func (r *router) debugPeer(roomID, peerID string) string {+ rm, _ := r.rooms.Get(roomID)+ if rm != nil && peerID == rm.hostPeerID {+ return "host"+ }+ if rm != nil && rm.controller != nil {+ return rm.controller.DiagnosticParticipantLabel(peerID)+ }+ return "viewer-unknown"+}++// qualitySample is QualitySampleReference; kind selects the peer or sfu+// fields.+type qualitySample struct {+ kind route.UpstreamKind+ childPeerID string+ routeRevision int64+ connectionID string+ publicationGeneration string+ hostSessionID string+}++// qualityCopyContext is QualityCopyContext; operationReason and+// candidateTransition are "" where the TS had null.+type qualityCopyContext struct {+ committedCopies int+ candidateReservedCopies int+ possibleCopies int+ endpointCapacity int+ operationReason route.DemandReason+ candidateTransition route.TransitionKind+ sampleRole string+}++// kv is the `...copyContext` spread of the debug events.+func (c qualityCopyContext) kv() []any {+ return []any{+ "committedCopies", c.committedCopies,+ "candidateReservedCopies", c.candidateReservedCopies,+ "possibleCopies", c.possibleCopies,+ "endpointCapacity", c.endpointCapacity,+ "operationReason", nullString(string(c.operationReason)),+ "candidateTransition", nullString(string(c.candidateTransition)),+ "sampleRole", c.sampleRole,+ }+}++// qualityCopyContext ports qualityCopyContext (O33: count only).+func (r *router) qualityCopyContext(+ snapshot route.RouteSnapshot,+ hostPeerID string,+ observedPeerID string,+ endpointCapacity int,+ sample qualitySample,+) qualityCopyContext {+ committedCopies := 0+ for _, edge := range snapshot.UpstreamByViewer.Values() {+ if edge.Kind == route.UpstreamPeer && edge.ParentPeerID == observedPeerID && edge.PhysicalActive {+ committedCopies+++ }+ }+ if observedPeerID == hostPeerID && snapshot.HostPublication != nil && snapshot.HostPublication.PhysicalActive {+ committedCopies+++ }++ operation := snapshot.Operation+ var current *route.CurrentAttempt+ var currentPlan *route.CandidatePlan+ if operation != nil {+ current = operation.Current+ if current != nil && operation.Cursor >= 0 && operation.Cursor < len(operation.Candidates) {+ plan := operation.Candidates[operation.Cursor]+ currentPlan = &plan+ }+ }+ candidateReservedCopies := 0+ if current != nil {+ if current.Tuple.Kind == route.UpstreamPeer && current.Tuple.ParentPeerID == observedPeerID {+ candidateReservedCopies = 1+ } else if current.Tuple.Kind == route.UpstreamSfu && observedPeerID == hostPeerID &&+ current.Tuple.Publication != route.PublicationReuse {+ candidateReservedCopies = 1+ }+ }++ candidateSample := false+ if current != nil {+ if sample.kind == route.UpstreamPeer {+ candidateSample = current.Tuple.Kind == route.UpstreamPeer &&+ operation.ChildPeerID == sample.childPeerID &&+ current.Tuple.ParentPeerID == observedPeerID &&+ current.Revision == sample.routeRevision &&+ current.ConnectionID == sample.connectionID+ } else {+ candidateSample = current.Tuple.Kind == route.UpstreamSfu &&+ observedPeerID == hostPeerID &&+ current.Revision == sample.routeRevision+ }+ }+ activeSample := false+ if sample.kind == route.UpstreamPeer {+ activeEdge, hasActive := snapshot.UpstreamByViewer.Get(sample.childPeerID)+ activeSample = sample.routeRevision == snapshot.Revision &&+ hasActive && activeEdge.Kind == route.UpstreamPeer &&+ activeEdge.PhysicalActive && activeEdge.Usable &&+ activeEdge.ParentPeerID == observedPeerID &&+ activeEdge.ConnectionID == sample.connectionID+ } else {+ publication := snapshot.HostPublication+ activeSample = sample.routeRevision == snapshot.Revision &&+ publication != nil && publication.PhysicalActive && publication.Usable &&+ publication.Generation == sample.publicationGeneration &&+ publication.HostSessionID == sample.hostSessionID+ }++ context := qualityCopyContext{+ committedCopies: committedCopies,+ candidateReservedCopies: candidateReservedCopies,+ possibleCopies: committedCopies + candidateReservedCopies,+ endpointCapacity: endpointCapacity,+ sampleRole: "unknown",+ }+ if operation != nil {+ context.operationReason = operation.Reason+ }+ if currentPlan != nil {+ context.candidateTransition = currentPlan.EndpointTransition.Kind+ }+ if candidateSample {+ context.sampleRole = "candidate"+ } else if activeSample {+ context.sampleRole = "active"+ }+ return context+}++// debugTuple ports debugTuple.+func (r *router) debugTuple(roomID string, tuple route.CandidateTuple) string {+ if tuple.Kind == route.UpstreamPeer {+ label := "p2p:" + r.debugPeer(roomID, tuple.ParentPeerID)+ if tuple.Regenerate {+ label += ":regenerate"+ }+ return label+ }+ return "sfu:" + string(tuple.Publication)+}++// debug ports debug(): one sanitised slog event. details are key/value+// pairs; never pass raw peer, session or connection IDs (use debugPeer).+func (r *router) debug(roomID, event string, details ...any) {+ if !routeDebugEnabled {+ return+ }+ args := make([]any, 0, 4+len(details))+ args = append(args, "event", event, "roomId", roomID)+ args = append(args, details...)+ slog.Info("screener-route", args...)+}++// sendRoomError ports sendRoomError: only the connected host is told.+func (r *router) sendRoomError(roomID, code, message string) {+ if host, ok := r.store.GetConnectedHost(roomID); ok {+ r.hooks.sendToSession(host.SessionID, protocol.ErrorMessage{Type: "error", Code: code, Message: message})+ }+}++// sendViewerRouteStatus ports sendViewerRouteStatus.+func (r *router) sendViewerRouteStatus(roomID, viewerPeerID string, message protocol.RouteStatusMessage) {+ if viewer, ok := r.store.GetConnectedViewer(roomID, viewerPeerID); ok {+ r.hooks.sendToSession(viewer.SessionID, message)+ }+}++// sendRouteFailures ports sendRouteFailures (O27: deduplicated, first+// occurrence wins).+func (r *router) sendRouteFailures(roomID string, failedPeerIDs []string, revision int64) {+ seen := map[string]struct{}{}+ for _, peerID := range failedPeerIDs {+ if _, duplicate := seen[peerID]; duplicate {+ continue+ }+ seen[peerID] = struct{}{}+ r.sendViewerRouteStatus(roomID, peerID, protocol.RouteStatusMessage{+ Type: "route-status",+ Revision: protocol.Int(revision),+ State: "failed",+ Reason: "route-exhausted",+ })+ }+}++func (r *router) nowPtr() *int64 {+ now := r.now()+ return &now+}++func emptyAssignment() protocol.ParticipantRouteAssignment {+ return protocol.ParticipantRouteAssignment{+ Upstream: protocol.NoUpstream(),+ ChildPeerIDs: []string{},+ SfuPublicationGeneration: nil,+ }+}++func assignmentFor(assignments map[string]protocol.ParticipantRouteAssignment, peerID string) protocol.ParticipantRouteAssignment {+ if assignment, ok := assignments[peerID]; ok {+ return assignment+ }+ return emptyAssignment()+}++// opaqueID ports opaqueId(): 16 random bytes, base64url without padding.+func opaqueID() string {+ value := make([]byte, 16)+ // crypto/rand.Read never fails; it panics if the operating system source does.+ _, _ = rand.Read(value)+ return base64.RawURLEncoding.EncodeToString(value)+}++func sampleTimestamp(value *protocol.Num) *int64 {+ if value == nil {+ return nil+ }+ timestamp := int64(*value)+ return ×tamp+}++func intFloat(value *protocol.Int) *float64 {+ if value == nil {+ return nil+ }+ converted := float64(*value)+ return &converted+}++// optional is the debug value of a nullable pointer field: nil for null.+func optional[T any](value *T) any {+ if value == nil {+ return nil+ }+ return *value+}++// nullable is the `value ?? null` of an optional-and-nullable field.+func nullable[T any](value protocol.Nullable[T]) any {+ if value.Value == nil {+ return nil+ }+ return *value.Value+}++// nullString is the debug value of a string that is "" where the TS had+// null or undefined.+func nullString(value string) any {+ if value == "" {+ return nil+ }+ return value+}diff --git a/internal/server/signal/router_pump.go b/internal/server/signal/router_pump.gonew file mode 100644index 00000000..618042e7--- /dev/null+++ b/internal/server/signal/router_pump.go@@ -0,0 +1,710 @@+package signal++// The route pump of hybrid-media-router.ts (requestPump 1114, pumpRoom 1135,+// prepareCandidate 1303, prepareNewPublication 1409, sendPrepareMessages 1492,+// scheduleDeadline 1822), following map section 7 step by step. The only+// unlock windows are inside prepareCandidate (R5, R6, R8, R9, R10); the+// cursor guard captured before them is the sole staleness detector.++import (+ "context"+ "log/slog"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+ "github.com/TNTcraftHIM/Screener/internal/server/room"+ "github.com/TNTcraftHIM/Screener/internal/server/route"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+)++// preparedCandidate is PreparedCandidate; the optional TS keys are "" / nil.+type preparedCandidate struct {+ reservation route.CandidateReservation+ connectionID string+ publicationGeneration string+ publicationConnectionID string+ hostSessionID string+ hostSfuConfig *protocol.SfuConfigMessage+ viewerSfuConfig *protocol.SfuConfigMessage+}++// prepareResult is PrepareResult.+type prepareResult struct {+ denied bool+ rejectionBucket route.RejectionBucket+ prepared preparedCandidate+}++func denied(bucket route.RejectionBucket) prepareResult {+ return prepareResult{denied: true, rejectionBucket: bucket}+}++// pumpCandidate is the pump loop state carried across the yield at+// `await prepareCandidate`: the selected slot with its cursor guard and the+// outcome of prepareCandidate's synchronous prefix. io is the awaited+// remainder (drain wait, token issue, LiveKit room creation), nil when+// result is already settled.+type pumpCandidate struct {+ operation *route.OperationSnapshot+ plan route.CandidatePlan+ guard route.CandidateCursorGuard+ revision int64+ result prepareResult+ io func() prepareResult+}++// requestPump ports requestPump: the single-flight driver. Every caller+// only sets requested; the pump that owns pumping drains it.+//+// The TS driver was an async IIFE, so it ran synchronously inside the+// caller up to its first await: the first pumpRoom iteration through the+// synchronous prefix of prepareCandidate (reconcile, candidate selection,+// the admission reservations and the LiveKit createRoom initiation). That+// prefix is observable: the calls that follow requestPump in the same+// handler see its reconcile, and two rooms woken by one drain reserve+// SFU capacity in wake order (map O29). It therefore runs here in the+// caller's critical section; everything after it ran in microtasks and+// runs in drivePump's goroutine.+//+// Deviation: `pumping` is set before that prefix, where `room.pump` was+// still undefined until the IIFE first suspended. A re-entrant requestPump+// during the prefix therefore only sets `requested` here and is drained by+// drivePump's loop, instead of starting a second overlapping pump as the+// TypeScript would have. No work is lost and the single-operation model of+// ADR-0005 is what a second pump would have put at risk.+func (r *router) requestPump(roomID string) {+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.controller == nil || r.closing {+ return+ }+ rm.requested = true+ if rm.pumping {+ return+ }+ rm.pumping = true+ rm.requested = false+ controller := rm.controller+ broadcastRevision := controller.Revision()+ var pending *pumpCandidate+ failed := r.recoverPump(func() {+ pending = r.pumpRoom(roomID, rm, controller, &broadcastRevision, nil, true)+ })+ r.inflight+++ go r.drivePump(roomID, rm, controller, broadcastRevision, pending, failed)+}++// recoverPump runs one pump segment; a panic is the TS rejection of the pump+// promise (controller assertion failures panic with the TS messages, D11).+func (r *router) recoverPump(segment func()) (failed bool) {+ defer func() {+ if recovered := recover(); recovered != nil {+ failed = true+ slog.Error("Media route reconciliation failed")+ }+ }()+ segment()+ return false+}++// drivePump is the asynchronous remainder of requestPump: the suspended+// first iteration, the `while (room.requested)` loop, the `finally` that+// frees the token and re-arms, and the `.catch` that tells the host.+func (r *router) drivePump(roomID string, rm *roomRuntime, controller *route.Controller, broadcastRevision int64, pending *pumpCandidate, failed bool) {+ r.mu.Lock()+ defer r.mu.Unlock()+ defer func() { r.inflight-- }()+ if !failed {+ failed = r.recoverPump(func() {+ if pending != nil {+ r.pumpRoom(roomID, rm, controller, &broadcastRevision, pending, false)+ }+ for rm.requested && !r.closing {+ rm.requested = false+ if rm.controller == nil {+ continue+ }+ revision := rm.controller.Revision()+ r.pumpRoom(roomID, rm, rm.controller, &revision, nil, false)+ }+ })+ }+ rm.pumping = false+ if rm.requested && !r.closing {+ r.requestPump(roomID)+ }+ if failed {+ r.sendRoomError(roomID, "SERVER_ERROR", "Media routing failed")+ }+}++// pumpRoom ports pumpRoom. mu is held on entry and exit; the candidate's io+// releases it around I/O. resume continues an iteration suspended at+// `await prepareCandidate`; with yieldAtPrepare the first candidate is+// returned after prepareCandidate's synchronous prefix instead of being+// awaited (the TS suspension point). Otherwise nil.+func (r *router) pumpRoom(+ roomID string,+ rm *roomRuntime,+ controller *route.Controller,+ broadcastRevision *int64,+ resume *pumpCandidate,+ yieldAtPrepare bool,+) *pumpCandidate {+ broadcastRevisionChange := func() {+ revision := controller.Revision()+ if revision == *broadcastRevision {+ return+ }+ r.broadcastActive(roomID, rm)+ *broadcastRevision = revision+ }+ for {+ var candidate pumpCandidate+ if resume != nil {+ candidate, resume = *resume, nil+ } else {+ selected, done := r.selectCandidate(roomID, rm, controller, broadcastRevisionChange)+ if done {+ return nil+ }+ candidate = selected+ candidate.result, candidate.io = r.prepareCandidate(+ roomID, rm, controller, candidate.operation, candidate.plan, candidate.revision)+ if yieldAtPrepare {+ return &candidate+ }+ }+ operation, plan, guard := candidate.operation, candidate.plan, candidate.guard+ preparation := candidate.result+ if candidate.io != nil {+ preparation = candidate.io()+ }+ if preparation.denied {+ r.debug(roomID, "candidate-preparation-denied",+ "child", r.debugPeer(roomID, operation.ChildPeerID),+ "route", r.debugTuple(roomID, plan.Tuple),+ "rejectionBucket", preparation.rejectionBucket,+ "cursor", operation.Cursor)+ if operation.Reason == route.DemandQualityConvergence ||+ operation.Reason == route.DemandRootConvergence {+ skipped := controller.SkipCurrentCandidate(guard, r.now(), preparation.rejectionBucket)+ r.releaseResources(skipped.Released)+ continue+ }+ if preparation.rejectionBucket != route.RejectionSfuAdmission {+ r.resourceWaiters.Delete(roomID)+ }+ if preparation.rejectionBucket == route.RejectionSfuAdmission {+ if !controller.NoteCurrentCandidateRejection(guard, route.RejectionSfuAdmission) {+ continue+ }+ r.resourceWaiters.Set(roomID, struct{}{})+ r.sendViewerRouteStatus(roomID, operation.DemandPeerID, protocol.RouteStatusMessage{+ Type: "route-status",+ Revision: protocol.Int(operation.BaseRevision),+ State: "waiting",+ Reason: "sfu-admission",+ })+ r.scheduleDeadline(roomID, rm, operation)+ return nil+ }+ skipped := controller.SkipCurrentCandidate(guard, r.now(), preparation.rejectionBucket)+ r.releaseResources(skipped.Released)+ r.sendRouteFailures(roomID, skipped.FailedPeerIDs, controller.Revision())+ continue+ }+ prepared := preparation.prepared+ r.resourceWaiters.Delete(roomID)+ r.debug(roomID, "candidate-prepared",+ "child", r.debugPeer(roomID, operation.ChildPeerID),+ "route", r.debugTuple(roomID, plan.Tuple),+ "cursor", operation.Cursor)+ beginGuard := guard+ if plan.EndpointTransition.Kind == route.TransitionBoundedGap {+ gap := controller.RetireCurrentCandidateProducer(guard, r.now())+ r.releaseResources(gap.Released)+ r.sendRouteFailures(roomID, gap.FailedPeerIDs, controller.Revision())+ if !gap.Accepted {+ r.releaseReservation(prepared.reservation)+ continue+ }+ broadcastRevisionChange()+ currentOperation := controller.Operation()+ if currentOperation == nil || currentOperation.Cursor < 0 ||+ currentOperation.Cursor >= len(currentOperation.Candidates) {+ r.releaseReservation(prepared.reservation)+ continue+ }+ // The guard is re-derived: the retirement moved the revision.+ beginGuard = cursorGuard(currentOperation, currentOperation.Candidates[currentOperation.Cursor])+ }+ begun := controller.BeginCurrentCandidate(route.BeginInput{+ Guard: beginGuard,+ NowMs: r.now(),+ ConnectionID: prepared.connectionID,+ Reservation: prepared.reservation,+ PublicationGeneration: prepared.publicationGeneration,+ PublicationConnectionID: prepared.publicationConnectionID,+ HostSessionID: prepared.hostSessionID,+ })+ r.debug(roomID, "candidate-begin-settled",+ "child", r.debugPeer(roomID, operation.ChildPeerID),+ "route", r.debugTuple(roomID, plan.Tuple),+ "accepted", begun.Accepted,+ "exhausted", len(begun.FailedPeerIDs) > 0)+ // A rejected begin returns the reservation inside begun.Released; it+ // must not be released a second time.+ r.releaseResources(begun.Released)+ if !begun.Accepted || begun.Operation == nil || begun.Operation.Current == nil {+ r.sendRouteFailures(roomID, begun.FailedPeerIDs, controller.Revision())+ continue+ }+ r.sendPrepareMessages(roomID, controller, begun.Operation, prepared)+ r.debug(roomID, "candidate-prepare-sent",+ "child", r.debugPeer(roomID, operation.ChildPeerID),+ "route", r.debugTuple(roomID, plan.Tuple),+ "revision", begun.Operation.Current.Revision)+ r.scheduleDeadline(roomID, rm, begun.Operation)+ return nil+ }+}++// selectCandidate is pumpRoom steps 1-7 (map 7.2): reconcile, then either+// finish the iteration (done) or pick the cursor's plan and its guard.+func (r *router) selectCandidate(+ roomID string,+ rm *roomRuntime,+ controller *route.Controller,+ broadcastRevisionChange func(),+) (candidate pumpCandidate, done bool) {+ reconciled := controller.Reconcile(r.now())+ r.releaseResources(reconciled.Released)+ broadcastRevisionChange()+ r.sendRouteFailures(roomID, reconciled.FailedPeerIDs, controller.Revision())+ operation := reconciled.Operation+ if operation == nil {+ operation = controller.Operation()+ }+ if operation == nil {+ r.clearDeadline(rm)+ r.resourceWaiters.Delete(roomID)+ return pumpCandidate{}, true+ }+ if operation.Current != nil {+ r.resourceWaiters.Delete(roomID)+ r.scheduleDeadline(roomID, rm, operation)+ return pumpCandidate{}, true+ }+ if operation.Cursor < 0 || operation.Cursor >= len(operation.Candidates) {+ // TS: `if (!plan)` -- note: no clearDeadline here.+ r.resourceWaiters.Delete(roomID)+ return pumpCandidate{}, true+ }+ plan := operation.Candidates[operation.Cursor]+ guard := cursorGuard(operation, plan)+ r.resourceWaiters.Delete(roomID)+ revision := operation.BaseRevision + 1+ if plan.EndpointTransition.Kind == route.TransitionBoundedGap {+ revision = operation.BaseRevision + 2+ }+ return pumpCandidate{operation: operation, plan: plan, guard: guard, revision: revision}, false+}++// prepareCandidate ports prepareCandidate. It runs the synchronous prefix+// (everything the TS executed before its first await: the stale checks,+// the borrowed edge lookup, the admission reservations, the LiveKit+// createRoom initiation) with mu held and returns either a settled result+// or the awaited remainder as io. io is called with mu held and releases+// it around reserveSfuSubscription's drain wait (R5/R10), the token issue+// (R6) and, for a new publication, the LiveKit room creation (R8/R9). No+// identity is re-read afterwards: the cursor guard in pumpRoom catches+// staleness. controller is the pump's captured controller (TS read+// room.controller!, the same object on every reachable path).+func (r *router) prepareCandidate(+ roomID string,+ rm *roomRuntime,+ controller *route.Controller,+ operation *route.OperationSnapshot,+ plan route.CandidatePlan,+ revision int64,+) (prepareResult, func() prepareResult) {+ snapshot := controller.Snapshot()+ child, hasChild := r.store.GetConnectedViewer(roomID, operation.ChildPeerID)+ shareGeneration := r.hooks.shareGeneration(roomID)+ if !hasChild || child.SessionID != operation.ChildSessionID || shareGeneration == "" {+ return denied(route.RejectionStale), nil+ }+ connectionID := opaqueID()+ var overlap *route.Resource+ if plan.EndpointTransition.Kind == route.TransitionOverlap {+ producerPeerID := ""+ if plan.EndpointTransition.ProducerPeerID != nil {+ producerPeerID = *plan.EndpointTransition.ProducerPeerID+ }+ overlap = overlapResource(producerPeerID)+ }+ if plan.Tuple.Kind == route.UpstreamPeer {+ return prepareResult{prepared: preparedCandidate{+ connectionID: connectionID,+ reservation: route.CandidateReservation{Kind: route.ReservationDirect, Overlap: overlap},+ }}, nil+ }++ fallback := r.sfu+ host, hasHost := r.store.GetConnectedHost(roomID)+ if fallback == nil || !hasHost || host.PeerID != rm.hostPeerID {+ return denied(route.RejectionStale), nil+ }+ if plan.Tuple.Publication == route.PublicationReuse {+ publication := snapshot.HostPublication+ if publication == nil || publication.Resource == nil ||+ publication.Resource.Kind != route.ResourceSfuPublication {+ return denied(route.RejectionStale), nil+ }+ fence := sfu.SubscriptionFence{+ ResourceFence: resourceFence(publication.Resource),+ ViewerPeerID: operation.ChildPeerID,+ }+ var borrowedEdge *route.Resource+ if currentEdge, ok := snapshot.UpstreamByViewer.Get(operation.ChildPeerID); ok &&+ currentEdge.Kind == route.UpstreamSfu &&+ currentEdge.PublicationGeneration == publication.Generation &&+ currentEdge.Resource != nil &&+ currentEdge.Resource.Kind == route.ResourceSfuSubscription &&+ !currentEdge.Resource.Released {+ borrowedEdge = currentEdge.Resource+ }+ // issue is the remainder after `await this.reserveSfuSubscription`.+ issue := func(edge *route.Resource) prepareResult {+ request := sfu.TokenRequest{+ RoomID: roomID,+ Role: protocol.RoleViewer,+ PeerID: operation.ChildPeerID,+ ShareGeneration: shareGeneration,+ PublicationGeneration: publication.Generation,+ }+ var token string+ var err error+ r.io(func() { token, err = fallback.tokenIssuer.IssueToken(request) }) // R6+ if err != nil {+ if borrowedEdge == nil {+ r.releaseResource(edge)+ }+ return denied(route.RejectionCandidateFailed)+ }+ return prepareResult{prepared: preparedCandidate{+ connectionID: connectionID,+ hostSessionID: host.SessionID,+ reservation: route.CandidateReservation{+ Kind: route.ReservationSfuReuse,+ Edge: edge,+ Borrowed: borrowedEdge != nil,+ Overlap: overlap,+ },+ publicationGeneration: publication.Generation,+ viewerSfuConfig: &protocol.SfuConfigMessage{+ Type: "sfu-config",+ Revision: protocol.Int(revision),+ URL: fallback.url,+ Token: token,+ },+ }}+ }+ if borrowedEdge != nil {+ return prepareResult{}, func() prepareResult { return issue(borrowedEdge) }+ }+ // reserveSfuSubscription (1788): a pending drain of the same+ // subscription is awaited first (R10); otherwise the reservation is+ // part of the synchronous prefix.+ key := sfuDrainKey(drainSubscription, fence)+ if pending, _ := r.sfuDrainTasks.Get(key); pending != nil && pending.operation != nil {+ drain := pending.operation+ return prepareResult{}, func() prepareResult {+ r.io(func() { <-drain.done })+ if drain.err != nil {+ return denied(route.RejectionSfuAdmission)+ }+ // Hazard 8: a drain that settled but left its task+ // registered means refuse.+ if registered, _ := r.sfuDrainTasks.Get(key); registered == pending {+ return denied(route.RejectionSfuAdmission)+ }+ if !r.reserveSfuSubscription(fence) {+ return denied(route.RejectionSfuAdmission)+ }+ return issue(subscriptionResource(fence))+ }+ }+ if !r.reserveSfuSubscription(fence) {+ return denied(route.RejectionSfuAdmission), nil+ }+ edge := subscriptionResource(fence)+ return prepareResult{}, func() prepareResult { return issue(edge) }+ }++ return r.prepareNewPublication(roomID, operation, revision, connectionID, shareGeneration, host, overlap)+}++// prepareNewPublication ports prepareNewPublication. The reservations and+// the room's FIFO turn (the TS createRoom call, registered synchronously+// by LiveKitSfuRoomControl.serialize) belong to the synchronous prefix;+// io creates the LiveKit room inside that turn and issues the two tokens+// sequentially where the TS used Promise.all (hazard 6: latency only).+// Failure releases the subscription before the publication (O26), the+// reverse of releaseResources.+func (r *router) prepareNewPublication(+ roomID string,+ operation *route.OperationSnapshot,+ revision int64,+ connectionID string,+ shareGeneration string,+ host room.ConnectedPeer,+ overlap *route.Resource,+) (prepareResult, func() prepareResult) {+ fallback := r.sfu+ publicationGeneration := opaqueID()+ publicationFence := sfu.ResourceFence{+ RoomID: roomID,+ ShareGeneration: shareGeneration,+ PublicationGeneration: publicationGeneration,+ }+ subscriptionFence := sfu.SubscriptionFence{+ ResourceFence: publicationFence,+ ViewerPeerID: operation.ChildPeerID,+ }+ if !fallback.admission.ReservePublication(publicationFence) {+ return denied(route.RejectionSfuAdmission), nil+ }+ if !fallback.admission.ReserveSubscription(subscriptionFence) {+ fallback.admission.BeginDrain(publicationFence)+ r.scheduleSfuPublicationDrain(publicationFence)+ return denied(route.RejectionSfuAdmission), nil+ }+ subscription := subscriptionResource(subscriptionFence)+ publicationConnectionID := publicationGeneration+ publication := publicationResource(publicationFence)+ turn := r.takeTurn(sfu.ManagedRoomName(publicationFence))+ return prepareResult{}, func() prepareResult {+ var err error+ var hostToken, viewerToken string+ r.io(func() {+ turn.run(func() {+ err = fallback.roomControl.CreateRoom(context.Background(), publicationFence) // R8+ })+ if err == nil { // R9+ hostToken, err = fallback.tokenIssuer.IssueToken(sfu.TokenRequest{+ RoomID: roomID,+ Role: protocol.RoleHost,+ PeerID: host.PeerID,+ ShareGeneration: shareGeneration,+ PublicationGeneration: publicationGeneration,+ })+ }+ if err == nil {+ viewerToken, err = fallback.tokenIssuer.IssueToken(sfu.TokenRequest{+ RoomID: roomID,+ Role: protocol.RoleViewer,+ PeerID: operation.ChildPeerID,+ ShareGeneration: shareGeneration,+ PublicationGeneration: publicationGeneration,+ })+ }+ })+ r.dropTurn(turn)+ if err != nil {+ r.releaseResource(subscription)+ r.releaseResource(publication)+ return denied(route.RejectionCandidateFailed)+ }+ return prepareResult{prepared: preparedCandidate{+ connectionID: connectionID,+ hostSessionID: host.SessionID,+ publicationGeneration: publicationGeneration,+ publicationConnectionID: publicationConnectionID,+ reservation: route.CandidateReservation{+ Kind: route.ReservationSfuCreate,+ Edge: subscription,+ Publication: publication,+ Overlap: overlap,+ },+ hostSfuConfig: &protocol.SfuConfigMessage{+ Type: "sfu-config",+ Revision: protocol.Int(revision),+ URL: fallback.url,+ Token: hostToken,+ },+ viewerSfuConfig: &protocol.SfuConfigMessage{+ Type: "sfu-config",+ Revision: protocol.Int(revision),+ URL: fallback.url,+ Token: viewerToken,+ },+ }}+ }+}++// sendPrepareMessages ports sendPrepareMessages (O24: fixed order). It sends+// nothing at all when the child is stale or the peer parent vanished; the+// deadline timer then resolves the operation (hazard 7).+func (r *router) sendPrepareMessages(+ roomID string,+ controller *route.Controller,+ operation *route.OperationSnapshot,+ prepared preparedCandidate,+) {+ current := operation.Current+ candidate := preparedRouteCandidate(operation, current.Tuple, current.ConnectionID)+ tuple := current.Tuple+ assignments := r.assignments(roomID, controller.Snapshot(), &tuple, operation.ChildPeerID, prepared.publicationGeneration)+ child, hasChild := r.store.GetConnectedViewer(roomID, operation.ChildPeerID)+ if !hasChild || child.SessionID != operation.ChildSessionID {+ return+ }+ prepare := func(peerID string) protocol.RouteUpdatePrepareMessage {+ return protocol.RouteUpdatePrepareMessage{+ Type: "route-update",+ Revision: protocol.Int(current.Revision),+ Phase: "prepare",+ Assignment: assignmentFor(assignments, peerID),+ Candidate: candidate,+ }+ }+ childUpdate := prepare(operation.ChildPeerID)+ if current.Tuple.Kind == route.UpstreamPeer {+ parent, hasParent := r.connectedPeer(roomID, current.Tuple.ParentPeerID)+ if !hasParent {+ return+ }+ r.hooks.sendToSession(child.SessionID, childUpdate)+ r.hooks.sendToSession(parent.SessionID, prepare(parent.PeerID))+ return+ }+ host, hasHost := r.store.GetConnectedHost(roomID)+ if prepared.hostSfuConfig != nil && hasHost && host.SessionID == prepared.hostSessionID {+ r.hooks.sendToSession(host.SessionID, prepare(host.PeerID))+ r.hooks.sendToSession(host.SessionID, *prepared.hostSfuConfig)+ }+ r.hooks.sendToSession(child.SessionID, childUpdate)+ if prepared.viewerSfuConfig != nil {+ r.hooks.sendToSession(child.SessionID, *prepared.viewerSfuConfig)+ }+}++// scheduleDeadline ports scheduleDeadline (T6). The callback verifies it is+// still the registered deadline through the room's generation counter, which+// clearDeadline bumps: a cleared TS timer never fired (D5).+func (r *router) scheduleDeadline(roomID string, rm *roomRuntime, operation *route.OperationSnapshot) {+ r.clearDeadline(rm)+ wakeInMs := max(int64(0), operation.WakeAtMs-r.now())+ if routeDebugEnabled {+ var current any+ if operation.Current != nil {+ current = r.debugTuple(roomID, operation.Current.Tuple)+ }+ r.debug(roomID, "deadline-scheduled",+ "child", r.debugPeer(roomID, operation.ChildPeerID),+ "wakeInMs", wakeInMs,+ "cursor", operation.Cursor,+ "candidateCount", len(operation.Candidates),+ "current", current)+ }+ generation := rm.deadlineGeneration+ rm.deadlineStop = r.afterFunc(time.Duration(wakeInMs)*time.Millisecond, func() {+ r.mu.Lock()+ defer r.mu.Unlock()+ if rm.deadlineGeneration != generation || rm.controller == nil || r.closing {+ return+ }+ rm.deadlineStop = nil+ before := rm.controller.Revision()+ expired := rm.controller.OperationExpired(r.now())+ r.debug(roomID, "deadline-fired",+ "child", r.debugPeer(roomID, operation.ChildPeerID),+ "accepted", expired.Accepted,+ "exhausted", len(expired.FailedPeerIDs) > 0)+ r.releaseResources(expired.Released)+ if rm.controller.Revision() != before {+ r.broadcastActive(roomID, rm)+ }+ r.sendRouteFailures(roomID, expired.FailedPeerIDs, rm.controller.Revision())+ r.requestPump(roomID)+ })+}++// clearDeadline ports clearDeadline; bumping the generation retires a+// callback that already lost the Stop race.+func (r *router) clearDeadline(rm *roomRuntime) {+ if rm.deadlineStop != nil {+ rm.deadlineStop()+ }+ rm.deadlineStop = nil+ rm.deadlineGeneration+++}++func cursorGuard(operation *route.OperationSnapshot, plan route.CandidatePlan) route.CandidateCursorGuard {+ return route.CandidateCursorGuard{+ ChildPeerID: operation.ChildPeerID,+ ChildSessionID: operation.ChildSessionID,+ BaseRevision: operation.BaseRevision,+ FactVersion: operation.FactVersion,+ Cursor: operation.Cursor,+ Plan: plan,+ }+}++// preparedRouteCandidate ports preparedRouteCandidate; connectionAttempt is+// present only when the current attempt carries one.+func preparedRouteCandidate(operation *route.OperationSnapshot, tuple route.CandidateTuple, connectionID string) protocol.PreparedRouteCandidate {+ transport := "sfu"+ if tuple.Kind == route.UpstreamPeer {+ transport = string(tuple.Transport)+ }+ candidate := protocol.PreparedRouteCandidate{+ ChildPeerID: operation.ChildPeerID,+ ConnectionID: connectionID,+ Transport: transport,+ QualityProbe: operation.Reason == route.DemandQualityConvergence,+ }+ if operation.Current != nil && operation.Current.ConnectionAttempt != nil {+ candidate.ConnectionAttempt = &protocol.ConnectionAttempt{+ Current: protocol.Int(operation.Current.ConnectionAttempt.Current),+ Total: protocol.Int(operation.Current.ConnectionAttempt.Total),+ }+ }+ return candidate+}++func overlapResource(endpointPeerID string) *route.Resource {+ return &route.Resource{Kind: route.ResourceOverlap, EndpointPeerID: endpointPeerID}+}++func subscriptionResource(fence sfu.SubscriptionFence) *route.Resource {+ return &route.Resource{+ Kind: route.ResourceSfuSubscription,+ RoomID: fence.RoomID,+ ShareGeneration: fence.ShareGeneration,+ PublicationGeneration: fence.PublicationGeneration,+ ViewerPeerID: fence.ViewerPeerID,+ }+}++func publicationResource(fence sfu.ResourceFence) *route.Resource {+ return &route.Resource{+ Kind: route.ResourceSfuPublication,+ RoomID: fence.RoomID,+ ShareGeneration: fence.ShareGeneration,+ PublicationGeneration: fence.PublicationGeneration,+ }+}++func resourceFence(resource *route.Resource) sfu.ResourceFence {+ return sfu.ResourceFence{+ RoomID: resource.RoomID,+ ShareGeneration: resource.ShareGeneration,+ PublicationGeneration: resource.PublicationGeneration,+ }+}++func subscriptionFence(resource *route.Resource) sfu.SubscriptionFence {+ return sfu.SubscriptionFence{ResourceFence: resourceFence(resource), ViewerPeerID: resource.ViewerPeerID}+}diff --git a/internal/server/signal/router_sfu.go b/internal/server/signal/router_sfu.gonew file mode 100644index 00000000..06fca5ca--- /dev/null+++ b/internal/server/signal/router_sfu.go@@ -0,0 +1,585 @@+package signal++// The SFU side of hybrid-media-router.ts: reservation commit and release+// (1734-1786), subscription reservation across a pending drain (1788),+// resource waiters (1811), fresh SFU configuration (1865), the host-offline+// probe (1903-2013) and the LiveKit drains (2015-2089).++import (+ "context"+ "errors"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+ "github.com/TNTcraftHIM/Screener/internal/server/route"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+)++type drainKind string++const (+ drainPublication drainKind = "publication"+ drainSubscription drainKind = "subscription"+)++// sfuDrainTask is SfuDrainTask; fence.ViewerPeerID is "" for a publication.+// operation is the in-flight drain (TS task.operation); retryGeneration is+// bumped by clearDrainRetry so a retry callback that lost the Stop race sees+// it is stale (D5).+type sfuDrainTask struct {+ kind drainKind+ fence sfu.SubscriptionFence+ operation *drainOperation+ retryStop func() bool+ retryGeneration uint64+}++// drainOperation is the promise runSfuDrain tracked: done is closed after err+// is set, with mu held, so a waiter that relocks sees the settled task.+type drainOperation struct {+ done chan struct{}+ err error+}++// turn is one slot in the per managed-room-name FIFO.+//+// The TS LiveKitSfuRoomControl.serialize registered every operation+// synchronously at call time, so operations on one managed room ran in the+// order the router decided them. In Go the RoomControl call happens after mu+// is released, and two goroutines could reach LiveKit in the opposite order+// (a drain deciding after a create but deleting the room before it exists).+// takeTurn therefore reserves the slot while mu is still held; run waits for+// the predecessor outside mu, performs the call and releases the successor;+// dropTurn forgets the tail entry once mu is held again. The sfu package's+// own serialisation then sees calls already in decision order. Only the+// mutating calls (CreateRoom, DeleteRoom, DrainSubscription) take a turn:+// their relative order is the correctness property; HostParticipantExists+// is a read whose result is re-validated against the controller anyway, and+// the TS suite's fake control never queued a drain behind it.+type turn struct {+ name string+ previous chan struct{}+ done chan struct{}+}++// takeTurn reserves the next slot for roomName. mu must be held.+func (r *router) takeTurn(roomName string) *turn {+ done := make(chan struct{})+ current := &turn{name: roomName, previous: r.roomTurns[roomName], done: done}+ r.roomTurns[roomName] = done+ return current+}++// run performs op in turn order. mu must NOT be held.+func (t *turn) run(op func()) {+ if t.previous != nil {+ <-t.previous+ }+ defer close(t.done)+ op()+}++// dropTurn removes the FIFO tail once it is this turn. mu must be held.+func (r *router) dropTurn(t *turn) {+ if r.roomTurns[t.name] == t.done {+ delete(r.roomTurns, t.name)+ }+}++// commitReservation ports commitReservation (O30: drained generations in+// admission order).+func (r *router) commitReservation(reservation route.CandidateReservation) bool {+ if reservation.Kind == route.ReservationDirect {+ return true+ }+ if reservation.Kind == route.ReservationSfuReuse {+ return reservation.Edge != nil &&+ reservation.Edge.Kind == route.ResourceSfuSubscription &&+ r.sfu != nil &&+ r.sfu.admission.CommitSubscription(subscriptionFence(reservation.Edge))+ }+ if reservation.Publication == nil || reservation.Publication.Kind != route.ResourceSfuPublication {+ return false+ }+ if r.sfu == nil {+ return false+ }+ draining, ok := r.sfu.admission.CommitPublication(resourceFence(reservation.Publication))+ if !ok {+ return false+ }+ for _, fence := range draining {+ r.scheduleSfuPublicationDrain(fence)+ }+ return true+}++func (r *router) releaseReservation(reservation route.CandidateReservation) {+ r.releaseResources(reservationResources(reservation))+}++// releaseResources ports releaseResources (O25). Publication drains own+// accounting; subscription drains only remove exact participants.+func (r *router) releaseResources(resources []*route.Resource) {+ for _, resource := range resources {+ if resource.Kind == route.ResourceSfuPublication {+ r.releaseResource(resource)+ }+ }+ for _, resource := range resources {+ if resource.Kind != route.ResourceSfuPublication {+ r.releaseResource(resource)+ }+ }+}++// releaseResource ports releaseResource: idempotent through Released.+func (r *router) releaseResource(resource *route.Resource) {+ if resource.Released {+ return+ }+ resource.Released = true+ switch resource.Kind {+ case route.ResourceOverlap:+ return+ case route.ResourceSfuSubscription:+ r.releaseSubscription(subscriptionFence(resource))+ return+ }+ if r.sfu != nil && r.sfu.admission.BeginDrain(resourceFence(resource)) {+ r.scheduleSfuPublicationDrain(resourceFence(resource))+ }+}++func (r *router) releaseSubscription(fence sfu.SubscriptionFence) bool {+ if r.sfu == nil {+ return false+ }+ accepted := r.sfu.admission.BeginSubscriptionDrain(fence)+ if accepted {+ r.scheduleSfuSubscriptionDrain(fence)+ }+ return accepted+}++// reserveSfuSubscription ports the synchronous tail of reserveSfuSubscription+// (1803-1808); the pending-drain wait before it (R10) lives in+// prepareCandidate, where the TS suspended.+func (r *router) reserveSfuSubscription(fence sfu.SubscriptionFence) bool {+ fallback := r.sfu+ if fallback == nil {+ return false+ }+ key := sfuDrainKey(drainSubscription, fence)+ if task, _ := r.sfuDrainTasks.Get(key); task != nil && task.kind == drainSubscription {+ r.clearDrainRetry(task)+ r.sfuDrainTasks.Delete(key)+ }+ return fallback.admission.ReserveSubscription(fence)+}++// wakeResourceWaiters ports wakeResourceWaiters (O29: snapshot order).+func (r *router) wakeResourceWaiters() {+ roomIDs := r.resourceWaiters.Keys()+ r.resourceWaiters.Clear()+ for _, roomID := range roomIDs {+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.controller == nil {+ continue+ }+ rm.controller.TouchExternalFacts()+ r.requestPump(roomID)+ }+}++// sendFreshSfuConfig ports sendFreshSfuConfig (R11). The pre-await guards run+// in the caller's critical section, as the TS ran them before its first+// await; the token is issued in a goroutine with mu released and the+// post-await guards re-run under mu with the pre-await snapshot. failed runs+// where the TS `.catch` ran and settled where `.finally` ran; both may be nil+// and both run under mu.+func (r *router) sendFreshSfuConfig(participant authenticatedRouteParticipant, failed, settled func()) {+ finish := func(err error) {+ if err != nil && failed != nil {+ failed()+ }+ if settled != nil {+ settled()+ }+ }+ fallback := r.sfu+ rm, _ := r.rooms.Get(participant.roomID)+ shareGeneration := r.hooks.shareGeneration(participant.roomID)+ if fallback == nil || rm == nil || rm.controller == nil {+ finish(nil)+ return+ }+ snapshot := rm.controller.Snapshot()+ publication := snapshot.HostPublication+ if publication == nil || !publication.PhysicalActive || shareGeneration == "" {+ finish(nil)+ return+ }+ isHost := participant.peerID == rm.hostPeerID+ if !isHost {+ edge, ok := snapshot.UpstreamByViewer.Get(participant.peerID)+ if !ok || edge.Kind != route.UpstreamSfu || !edge.PhysicalActive {+ finish(nil)+ return+ }+ }+ role := protocol.RoleViewer+ if isHost {+ role = protocol.RoleHost+ }+ request := sfu.TokenRequest{+ RoomID: participant.roomID,+ Role: role,+ PeerID: participant.peerID,+ ShareGeneration: shareGeneration,+ PublicationGeneration: publication.Generation,+ }+ r.inflight+++ go func() {+ token, err := fallback.tokenIssuer.IssueToken(request)+ r.mu.Lock()+ defer r.mu.Unlock()+ r.inflight--+ if err != nil {+ finish(err)+ return+ }+ if rm.controller == nil {+ finish(nil)+ return+ }+ currentPublication := rm.controller.Publication()+ peer, connected := r.connectedPeer(participant.roomID, participant.peerID)+ if rm.controller.Revision() != snapshot.Revision ||+ currentPublication == nil ||+ currentPublication.Generation != publication.Generation ||+ !connected || peer.SessionID != participant.sessionID {+ finish(nil)+ return+ }+ r.hooks.sendToSession(participant.sessionID, protocol.SfuConfigMessage{+ Type: "sfu-config",+ Revision: protocol.Int(snapshot.Revision),+ URL: fallback.url,+ Token: token,+ })+ finish(nil)+ }()+}++// activeHostPublication ports activeHostPublication.+func (r *router) activeHostPublication(roomID string) (hostOfflineCheck, bool) {+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.controller == nil {+ return hostOfflineCheck{}, false+ }+ publication := rm.controller.Publication()+ if publication == nil || !publication.PhysicalActive ||+ publication.Resource == nil || publication.Resource.Kind != route.ResourceSfuPublication {+ return hostOfflineCheck{}, false+ }+ return hostOfflineCheck{+ fence: resourceFence(publication.Resource),+ hostSessionID: publication.HostSessionID,+ connectionID: publication.ConnectionID,+ }, true+}++// scheduleHostOfflineCheck ports scheduleHostOfflineCheck (T7).+func (r *router) scheduleHostOfflineCheck(roomID, hostPeerID string) {+ r.cancelHostOfflineCheck(roomID)+ fallback := r.sfu+ publication, ok := r.activeHostPublication(roomID)+ if fallback == nil || !ok || r.closing {+ return+ }+ check := &publication+ check.hostPeerID = hostPeerID+ delay := fallback.hostOfflineCheckMs+ if delay == 0 {+ delay = defaultHostOfflineCheckMs+ }+ check.stop = r.afterFunc(time.Duration(delay)*time.Millisecond, func() {+ r.checkHostOffline(roomID, check)+ })+ r.hostOfflineChecks.Set(roomID, check)+}++// checkHostOffline ports checkHostOffline (R12) as the timer callback body.+// armed is the check the timer was armed with: a cleared TS timer never+// fired, so anything else registered for the room means return (D5).+func (r *router) checkHostOffline(roomID string, armed *hostOfflineCheck) {+ r.mu.Lock()+ defer r.mu.Unlock()+ check, _ := r.hostOfflineChecks.Get(roomID)+ fallback := r.sfu+ if check == nil || check != armed || fallback == nil || r.closing {+ return+ }+ if _, hostConnected := r.store.GetConnectedHost(roomID); hostConnected {+ r.cancelHostOfflineCheck(roomID)+ return+ }+ var exists bool+ var err error+ r.io(func() {+ exists, err = fallback.roomControl.HostParticipantExists(context.Background(), check.fence)+ })+ if err != nil {+ if registered, _ := r.hostOfflineChecks.Get(roomID); registered != check {+ return+ }+ r.hostOfflineChecks.Delete(roomID)+ r.scheduleHostOfflineCheck(roomID, check.hostPeerID)+ return+ }+ if registered, _ := r.hostOfflineChecks.Get(roomID); registered != check {+ return+ }+ r.hostOfflineChecks.Delete(roomID)+ if exists {+ r.scheduleHostOfflineCheck(roomID, check.hostPeerID)+ return+ }+ rm, _ := r.rooms.Get(roomID)+ if rm == nil || rm.controller == nil {+ return+ }+ controller := rm.controller+ snapshot := controller.Snapshot()+ publication := snapshot.HostPublication+ if publication == nil {+ return+ }+ // Hazard 9: six publication fields plus the fence triple; anything+ // short of that re-arms the check instead of retiring the publication.+ if publication.Resource == nil ||+ publication.Resource.Kind != route.ResourceSfuPublication ||+ resourceFence(publication.Resource) != check.fence ||+ publication.Generation != check.fence.PublicationGeneration ||+ publication.HostSessionID != check.hostSessionID ||+ publication.ConnectionID != check.connectionID ||+ !publication.PhysicalActive {+ r.scheduleHostOfflineCheck(roomID, check.hostPeerID)+ return+ }+ beforeRevision := snapshot.Revision+ controller.InvalidateHostPublication(route.PublicationGuard{+ HostSessionID: publication.HostSessionID,+ RouteRevision: snapshot.Revision,+ Generation: publication.Generation,+ ConnectionID: publication.ConnectionID,+ }, r.nowPtr())+ r.releaseResources(controller.RetireHostPublication(route.PublicationGuard{+ HostSessionID: publication.HostSessionID,+ RouteRevision: controller.Revision(),+ Generation: publication.Generation,+ ConnectionID: publication.ConnectionID,+ }))+ afterRetirement := controller.Publication()+ if afterRetirement != nil &&+ afterRetirement.Generation == publication.Generation &&+ afterRetirement.ConnectionID == publication.ConnectionID &&+ afterRetirement.PhysicalActive {+ if controller.Revision() != beforeRevision {+ r.broadcastActive(roomID, rm)+ }+ r.scheduleHostOfflineCheck(roomID, check.hostPeerID)+ r.requestPump(roomID)+ return+ }+ r.broadcastActive(roomID, rm)+ r.requestPump(roomID)+}++func (r *router) cancelHostOfflineCheck(roomID string) {+ if check, ok := r.hostOfflineChecks.Get(roomID); ok {+ check.stop()+ }+ r.hostOfflineChecks.Delete(roomID)+}++// scheduleSfuPublicationDrain ports scheduleSfuPublicationDrain (O28: the+// sibling subscription tasks are deleted during the live iteration).+func (r *router) scheduleSfuPublicationDrain(fence sfu.ResourceFence) {+ roomName := sfu.ManagedRoomName(fence)+ for key, task := range r.sfuDrainTasks.All() {+ if task.kind == drainSubscription && sfu.ManagedRoomName(task.fence.ResourceFence) == roomName {+ r.clearDrainRetry(task)+ r.sfuDrainTasks.Delete(key)+ }+ }+ r.scheduleSfuDrain(drainPublication, sfu.SubscriptionFence{ResourceFence: fence})+}++// scheduleSfuSubscriptionDrain ports scheduleSfuSubscriptionDrain: a pending+// publication drain of the same room already removes every participant.+func (r *router) scheduleSfuSubscriptionDrain(fence sfu.SubscriptionFence) {+ if r.sfuDrainTasks.Has(sfu.ManagedRoomName(fence.ResourceFence)) {+ return+ }+ r.scheduleSfuDrain(drainSubscription, fence)+}++// scheduleSfuDrain ports scheduleSfuDrain.+func (r *router) scheduleSfuDrain(kind drainKind, fence sfu.SubscriptionFence) {+ if r.sfu == nil {+ return+ }+ key := sfuDrainKey(kind, fence)+ task, _ := r.sfuDrainTasks.Get(key)+ if task == nil {+ task = &sfuDrainTask{kind: kind, fence: fence}+ r.sfuDrainTasks.Set(key, task)+ }+ if task.operation == nil && task.retryStop == nil {+ // TS: void this.runSfuDrain(key, task).catch(() => undefined)+ r.runSfuDrain(r.drainContext(), key, task)+ }+}++// runSfuDrain ports runSfuDrain (R13, R14). mu must be held; the returned+// operation is the tracked promise. The LiveKit call runs in a goroutine+// inside the room's FIFO turn taken here, and the post-await body runs under+// mu before done is closed.+func (r *router) runSfuDrain(ctx context.Context, key string, task *sfuDrainTask) *drainOperation {+ if task.operation != nil {+ return task.operation+ }+ operation := &drainOperation{done: make(chan struct{})}+ fallback := r.sfu+ if fallback == nil {+ close(operation.done)+ return operation+ }+ task.operation = operation+ turn := r.takeTurn(sfu.ManagedRoomName(task.fence.ResourceFence))+ r.inflight+++ go func() {+ var err error+ turn.run(func() {+ if task.kind == drainPublication {+ err = fallback.roomControl.DeleteRoom(ctx, task.fence.ResourceFence)+ } else {+ err = fallback.roomControl.DrainSubscription(ctx, task.fence)+ }+ })+ r.mu.Lock()+ defer r.mu.Unlock()+ r.inflight--+ r.dropTurn(turn)+ operation.err = r.settleSfuDrain(key, task, err)+ if task.operation == operation {+ task.operation = nil+ }+ close(operation.done)+ }()+ return operation+}++// settleSfuDrain is the post-await body of runSfuDrain: the try/catch after+// the LiveKit call. It returns the error the tracked promise rejected with.+func (r *router) settleSfuDrain(key string, task *sfuDrainTask, err error) error {+ fallback := r.sfu+ if err == nil {+ if registered, _ := r.sfuDrainTasks.Get(key); registered != task {+ return nil+ }+ if task.kind == drainPublication && !fallback.admission.CompleteDrain(task.fence.ResourceFence) {+ err = errors.New("LiveKit drain has no matching resource generation")+ } else {+ r.sfuDrainTasks.Delete(key)+ if task.kind == drainPublication {+ r.wakeResourceWaiters()+ } else {+ r.requestPump(task.fence.RoomID)+ }+ return nil+ }+ }+ // catch+ if registered, _ := r.sfuDrainTasks.Get(key); registered != task {+ return nil+ }+ if r.closing {+ return err+ }+ retryMs := fallback.drainRetryMs+ if retryMs == 0 {+ retryMs = defaultSfuDrainRetryMs+ }+ generation := task.retryGeneration+ task.retryStop = r.afterFunc(time.Duration(retryMs)*time.Millisecond, func() { // T8+ r.mu.Lock()+ defer r.mu.Unlock()+ if task.retryGeneration != generation || r.closing {+ return+ }+ task.retryStop = nil+ r.runSfuDrain(r.drainContext(), key, task)+ })+ return nil+}++// drainContext bounds the LiveKit drains: unbounded (the TS had none) until+// close installs its context (D6).+func (r *router) drainContext() context.Context {+ if r.closeCtx != nil {+ return r.closeCtx+ }+ return context.Background()+}++// clearDrainRetry is the clearTimeout(task.retryTimer) of the TS; bumping+// the generation retires a callback that already lost the Stop race.+func (r *router) clearDrainRetry(task *sfuDrainTask) {+ if task.retryStop != nil {+ task.retryStop()+ task.retryStop = nil+ }+ task.retryGeneration+++}++// awaitDrain is `await task.operation` inside close(): mu is released while+// waiting and re-acquired before returning; ctx bounds the wait (D6).+func (r *router) awaitDrain(ctx context.Context, operation *drainOperation) error {+ var err error+ r.io(func() {+ select {+ case <-operation.done:+ err = operation.err+ case <-ctx.Done():+ err = ctx.Err()+ }+ })+ return err+}++func sfuDrainKey(kind drainKind, fence sfu.SubscriptionFence) string {+ roomName := sfu.ManagedRoomName(fence.ResourceFence)+ if kind == drainPublication {+ return roomName+ }+ return roomName + "\x00viewer:" + fence.ViewerPeerID+}++// reservationResources ports reservationResources: a borrowed reuse edge+// belongs to another holder and is not released.+func reservationResources(reservation route.CandidateReservation) []*route.Resource {+ var resources []*route.Resource+ if reservation.Edge != nil && (reservation.Kind != route.ReservationSfuReuse || !reservation.Borrowed) {+ resources = append(resources, reservation.Edge)+ }+ if reservation.Publication != nil {+ resources = append(resources, reservation.Publication)+ }+ if reservation.Overlap != nil {+ resources = append(resources, reservation.Overlap)+ }+ return resources+}diff --git a/internal/server/signal/router_test.go b/internal/server/signal/router_test.gonew file mode 100644index 00000000..426d3306--- /dev/null+++ b/internal/server/signal/router_test.go@@ -0,0 +1,2512 @@+package signal++// Ported from tests/hybrid-media-router.test.ts (baseline b20fd88). The+// harness mirrors harness(...) there: a memory room.Store, a real+// sfu.Admission, sfutest.FakeRoomControl behind a thin spy (the vi.spyOn+// cases), a fake token issuer returning "token-<peerId>", recorded hooks and+// the shared mutex every router call and every assertion takes.+//+// Timing model. Node ran each TS test segment between two awaits as one+// synchronous tick with the router's continuations (the pump, token issues,+// drains) suspended; they ran at the next microtask checkpoint. Here every+// such segment is one h.locked block, so the router's goroutines (which take+// the same mutex) cannot interleave with it, and the TS await points map to+// waitFor/advance, which let those goroutines settle (router.inflight == 0).+// The seven fake-timer cases reproduce vitest 4.1 exactly: vi.waitFor ticks+// the clock 50 ms before every check and gives up after 20 checks,+// advanceTimersByTimeAsync fires due timers in order at their due time and+// flushes between them, and setSystemTime jumps the clock while shifting+// every pending timer by the same amount.++import (+ "context"+ "errors"+ "log/slog"+ "reflect"+ "runtime"+ "slices"+ "sort"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+ "github.com/TNTcraftHIM/Screener/internal/server/room"+ "github.com/TNTcraftHIM/Screener/internal/server/route"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu/sfutest"+)++const testShareGeneration = "share_generation_12345678"++// ---------------------------------------------------------------------------+// harness+// ---------------------------------------------------------------------------++type routerHarnessOptions struct {+ capacity int+ withSfu bool+ prepareTimeoutMs int64+ sfuIngressCapacity int+ drainRetryMs int64+ hostOfflineCheckMs int64+ fakeTimers bool+}++type routerHarness struct {+ t *testing.T+ mu sync.Mutex+ store *room.Store+ router *router+ admission *sfu.Admission+ roomControl *spyRoomControl+ tokens *fakeTokenIssuer+ clock *manualClock+ sent map[string][]protocol.ServerMessage+ routesChanged []string+}++func newRouterHarness(t *testing.T, options routerHarnessOptions) *routerHarness {+ t.Helper()+ h := &routerHarness{t: t, sent: map[string][]protocol.ServerMessage{}}+ storeOptions := room.Options{LeaseMs: 60_000, MaxRooms: 4, MaxViewersPerRoom: 20}+ var now func() int64+ var afterFunc func(time.Duration, func()) func() bool+ if options.fakeTimers {+ h.clock = &manualClock{settle: h.settle}+ now = h.clock.now+ afterFunc = h.clock.afterFunc+ storeOptions.Now = now+ }+ store, err := room.New(storeOptions)+ if err != nil {+ t.Fatalf("room.New: %v", err)+ }+ h.store = store+ var fallback *sfuFallback+ if options.withSfu {+ ingress := options.sfuIngressCapacity+ if ingress == 0 {+ ingress = 2+ }+ h.admission = sfu.NewAdmission(sfu.AdmissionOptions{IngressCapacity: ingress, EgressCapacity: 20})+ h.roomControl = &spyRoomControl{FakeRoomControl: sfutest.New()}+ h.tokens = &fakeTokenIssuer{}+ fallback = &sfuFallback{+ url: "wss://sfu.example.test",+ tokenIssuer: h.tokens,+ admission: h.admission,+ roomControl: h.roomControl,+ prepareTimeoutMs: options.prepareTimeoutMs,+ drainRetryMs: options.drainRetryMs,+ hostOfflineCheckMs: options.hostOfflineCheckMs,+ }+ }+ h.router = newRouter(routerOptions{+ mu: &h.mu,+ store: store,+ endpointMediaCopyCapacity: options.capacity,+ sfu: fallback,+ hooks: routerHooks{+ sendToSession: func(sessionID string, message protocol.ServerMessage) {+ h.sent[sessionID] = append(h.sent[sessionID], message)+ },+ shareGeneration: func(string) string { return testShareGeneration },+ routesChanged: func(roomID string) { h.routesChanged = append(h.routesChanged, roomID) },+ },+ now: now,+ afterFunc: afterFunc,+ })+ t.Cleanup(func() { _ = h.close() })+ return h+}++// locked runs fn as one synchronous TS segment.+func (h *routerHarness) locked(fn func()) {+ h.mu.Lock()+ defer h.mu.Unlock()+ fn()+}++// settle waits for the router's pending continuations (the TS microtask+// backlog) to finish.+func (h *routerHarness) settle() {+ h.t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for {+ var idle bool+ h.locked(func() { idle = h.router.inflight == 0 })+ if idle {+ return+ }+ if time.Now().After(deadline) {+ h.t.Fatal("timed out waiting for the router to settle")+ }+ time.Sleep(time.Millisecond)+ }+}++// close is the signaling server's `await this.hybridMediaRouter.close()`:+// entered with mu held, released only around the drain waits.+func (h *routerHarness) close() error {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ var err error+ h.locked(func() { err = h.router.close(ctx) })+ return err+}++func (h *routerHarness) createRoom() room.CreatedRoom {+ h.t.Helper()+ var created room.CreatedRoom+ var err error+ h.locked(func() {+ var lease int64+ lease, err = h.store.BeginCreateRoom()+ if err == nil {+ created, err = h.store.CreateRoom(protocol.CodeEntryOpen, nil, nil, "", lease)+ }+ })+ if err != nil {+ h.t.Fatalf("createRoom: %v", err)+ }+ return created+}++// connectHost ports connectHost: the store side only, like the TS helper.+func (h *routerHarness) connectHost(created room.CreatedRoom, policy *protocol.RoutePolicy, clientID, sessionID string) authenticatedRouteParticipant {+ h.t.Helper()+ if clientID == "" {+ clientID = "host_client_12345678"+ }+ if sessionID == "" {+ sessionID = "host_session_12345678"+ }+ var connected room.ConnectedParticipant+ var err error+ h.locked(func() {+ connected, err = h.store.ConnectParticipant(room.ConnectParticipantInput{+ RoomID: created.RoomID,+ Role: protocol.RoleHost,+ Token: created.HostToken,+ ClientID: clientID,+ SessionID: sessionID,+ })+ })+ if err != nil {+ h.t.Fatalf("connect host: %v", err)+ }+ return authenticatedRouteParticipant{+ roomID: created.RoomID,+ role: protocol.RoleHost,+ peerID: connected.PeerID,+ sessionID: sessionID,+ routePolicy: policy,+ }+}++// connectViewer ports connectViewer: the store side only.+func (h *routerHarness) connectViewer(created room.CreatedRoom, suffix string) authenticatedRouteParticipant {+ h.t.Helper()+ sessionID := "viewer_session_" + suffix + "_12345678"+ var connected room.ConnectedParticipant+ var err error+ h.locked(func() {+ connected, err = h.store.ConnectParticipant(room.ConnectParticipantInput{+ RoomID: created.RoomID,+ Role: protocol.RoleViewer,+ ViewerGrant: created.ViewerGrant,+ ClientID: "viewer_client_" + suffix + "_12345678",+ SessionID: sessionID,+ })+ })+ if err != nil {+ h.t.Fatalf("connect viewer %s: %v", suffix, err)+ }+ return authenticatedRouteParticipant{+ roomID: created.RoomID,+ role: protocol.RoleViewer,+ peerID: connected.PeerID,+ sessionID: sessionID,+ }+}++// The do* helpers are the TS router calls; they expect the harness lock to be+// held by an enclosing locked block. The lock-taking wrappers below serve the+// single-call segments.++func (h *routerHarness) doComplete(participant authenticatedRouteParticipant) hybridAuthenticationState {+ state := h.router.connectParticipant(participant)+ h.router.completeAuthentication(participant, state)+ return state+}++func readyMessage(revision int64) protocol.RouteReadyMessage {+ return protocol.RouteReadyMessage{Type: "route-ready", Revision: protocol.Int(revision), Phase: "prepare"}+}++func (h *routerHarness) doReady(participant authenticatedRouteParticipant, revision int64) {+ h.router.handleRouteReady(participant, readyMessage(revision))+}++func (h *routerHarness) doReadyApproved(participant authenticatedRouteParticipant, revision int64) {+ message := readyMessage(revision)+ message.QualityApproved = true+ h.router.handleRouteReady(participant, message)+}++func routeFailedMessage(revision int64, phase, connectionID string) protocol.RouteFailedMessage {+ message := protocol.RouteFailedMessage{Type: "route-failed", Revision: protocol.Int(revision), Phase: phase}+ if connectionID != "" {+ message.ConnectionID = &connectionID+ }+ return message+}++func (h *routerHarness) doFailed(participant authenticatedRouteParticipant, message protocol.RouteFailedMessage) {+ h.router.handleRouteFailed(participant, message)+}++func (h *routerHarness) doRelay(participant authenticatedRouteParticipant, downstreamEdges int) {+ h.router.setViewerRelayCapacity(participant, downstreamEdges)+}++// doDisconnect is the store.disconnectParticipant + router.disconnectParticipant pair.+func (h *routerHarness) doDisconnect(participant authenticatedRouteParticipant) {+ h.t.Helper()+ if _, err := h.store.DisconnectParticipant(participant.roomID, participant.peerID, participant.sessionID); err != nil {+ h.t.Fatalf("DisconnectParticipant: %v", err)+ }+ h.router.disconnectParticipant(participant.roomID, participant.peerID, participant.sessionID)+}++func (h *routerHarness) doEdge(roomID, peerID string) (activeViewerMediaEdge, bool) {+ return h.router.resolveActiveViewerMediaEdge(roomID, peerID)+}++func (h *routerHarness) doMustEdge(roomID, peerID string) activeViewerMediaEdge {+ h.t.Helper()+ edge, ok := h.doEdge(roomID, peerID)+ if !ok {+ h.t.Fatal("expected an active viewer media edge")+ }+ return edge+}++func (h *routerHarness) complete(participant authenticatedRouteParticipant) hybridAuthenticationState {+ var state hybridAuthenticationState+ h.locked(func() { state = h.doComplete(participant) })+ return state+}++func (h *routerHarness) routeReady(participant authenticatedRouteParticipant, revision int64) {+ h.locked(func() { h.doReady(participant, revision) })+}++func (h *routerHarness) routeFailed(participant authenticatedRouteParticipant, message protocol.RouteFailedMessage) {+ h.locked(func() { h.doFailed(participant, message) })+}++func (h *routerHarness) disconnect(participant authenticatedRouteParticipant) {+ h.t.Helper()+ h.locked(func() { h.doDisconnect(participant) })+}++func (h *routerHarness) activeEdge(roomID, peerID string) (activeViewerMediaEdge, bool) {+ var edge activeViewerMediaEdge+ var ok bool+ h.locked(func() { edge, ok = h.doEdge(roomID, peerID) })+ return edge, ok+}++func (h *routerHarness) mustActiveEdge(roomID, peerID string) activeViewerMediaEdge {+ h.t.Helper()+ edge, ok := h.activeEdge(roomID, peerID)+ if !ok {+ h.t.Fatal("expected an active viewer media edge")+ }+ return edge+}++func (h *routerHarness) messages(sessionID string) []protocol.ServerMessage {+ var copied []protocol.ServerMessage+ h.locked(func() { copied = slices.Clone(h.sent[sessionID]) })+ return copied+}++func (h *routerHarness) allMessages() []protocol.ServerMessage {+ var all []protocol.ServerMessage+ h.locked(func() {+ for _, messages := range h.sent {+ all = append(all, messages...)+ }+ })+ return all+}++// preparedFor ports preparedFor: the last phase "prepare" route-update.+func (h *routerHarness) preparedFor(sessionID string) (protocol.RouteUpdatePrepareMessage, bool) {+ return lastPrepare(h.messages(sessionID), "")+}++// ownPrepare is the test-local ownPrepare: the last prepare whose candidate+// child is the participant.+func (h *routerHarness) ownPrepare(participant authenticatedRouteParticipant) (protocol.RouteUpdatePrepareMessage, bool) {+ return lastPrepare(h.messages(participant.sessionID), participant.peerID)+}++func lastPrepare(messages []protocol.ServerMessage, childPeerID string) (protocol.RouteUpdatePrepareMessage, bool) {+ for index := len(messages) - 1; index >= 0; index-- {+ if prepared, ok := messages[index].(protocol.RouteUpdatePrepareMessage); ok &&+ (childPeerID == "" || prepared.Candidate.ChildPeerID == childPeerID) {+ return prepared, true+ }+ }+ return protocol.RouteUpdatePrepareMessage{}, false+}++// activeAfter ports activeAfter.+func (h *routerHarness) activeAfter(sessionID string, revision int64) (protocol.RouteUpdateActiveMessage, bool) {+ messages := h.messages(sessionID)+ for index := len(messages) - 1; index >= 0; index-- {+ if active, ok := messages[index].(protocol.RouteUpdateActiveMessage); ok && int64(active.Revision) > revision {+ return active, true+ }+ }+ return protocol.RouteUpdateActiveMessage{}, false+}++func (h *routerHarness) lastRouteStatus(sessionID string) (protocol.RouteStatusMessage, bool) {+ messages := h.messages(sessionID)+ for index := len(messages) - 1; index >= 0; index-- {+ if status, ok := messages[index].(protocol.RouteStatusMessage); ok {+ return status, true+ }+ }+ return protocol.RouteStatusMessage{}, false+}++func (h *routerHarness) hasRouteStatus(sessionID, state string) bool {+ return h.countRouteStatus(sessionID, state) > 0+}++func (h *routerHarness) countRouteStatus(sessionID, state string) int {+ count := 0+ for _, message := range h.messages(sessionID) {+ if status, ok := message.(protocol.RouteStatusMessage); ok && status.State == state {+ count+++ }+ }+ return count+}++func sfuConfigCount(messages []protocol.ServerMessage) int {+ count := 0+ for _, message := range messages {+ if _, ok := message.(protocol.SfuConfigMessage); ok {+ count+++ }+ }+ return count+}++// waitFor ports vi.waitFor. With fake timers every check first ticks the+// clock by the 50 ms poll interval and the 1 s timeout allows 20 checks, as+// vitest 4.1 does; with real timers it polls.+func (h *routerHarness) waitFor(description string, condition func() bool) {+ h.t.Helper()+ if h.clock != nil {+ for check := 0; check < 20; check++ {+ h.clock.advance(50)+ if condition() {+ return+ }+ }+ h.t.Fatalf("timed out waiting for %s", description)+ }+ deadline := time.Now().Add(5 * time.Second)+ for {+ if condition() {+ return+ }+ if time.Now().After(deadline) {+ h.t.Fatalf("timed out waiting for %s", description)+ }+ time.Sleep(time.Millisecond)+ }+}++func (h *routerHarness) waitPrepared(sessionID string) protocol.RouteUpdatePrepareMessage {+ h.t.Helper()+ return h.waitPreparedMatching(sessionID, "a prepare", func(protocol.RouteUpdatePrepareMessage) bool { return true })+}++func (h *routerHarness) waitPreparedTransport(sessionID, transport string) protocol.RouteUpdatePrepareMessage {+ h.t.Helper()+ return h.waitPreparedMatching(sessionID, transport+" prepare", func(prepared protocol.RouteUpdatePrepareMessage) bool {+ return prepared.Candidate.Transport == transport+ })+}++func (h *routerHarness) waitPreparedUpstream(sessionID string, upstream protocol.MediaRouteUpstream) protocol.RouteUpdatePrepareMessage {+ h.t.Helper()+ return h.waitPreparedMatching(sessionID, "a prepare with upstream "+upstream.Kind, func(prepared protocol.RouteUpdatePrepareMessage) bool {+ return prepared.Assignment.Upstream == upstream+ })+}++func (h *routerHarness) waitPreparedAbove(sessionID string, revision int64) protocol.RouteUpdatePrepareMessage {+ h.t.Helper()+ return h.waitPreparedMatching(sessionID, "a newer prepare", func(prepared protocol.RouteUpdatePrepareMessage) bool {+ return int64(prepared.Revision) > revision+ })+}++func (h *routerHarness) waitPreparedMatching(sessionID, description string, matches func(protocol.RouteUpdatePrepareMessage) bool) protocol.RouteUpdatePrepareMessage {+ h.t.Helper()+ var prepared protocol.RouteUpdatePrepareMessage+ h.waitFor(description+" for "+sessionID, func() bool {+ candidate, ok := h.preparedFor(sessionID)+ if ok && matches(candidate) {+ prepared = candidate+ return true+ }+ return false+ })+ return prepared+}++func (h *routerHarness) waitFailed(sessionID string) {+ h.t.Helper()+ h.waitFor("route-exhausted for "+sessionID, func() bool {+ status, ok := h.lastRouteStatus(sessionID)+ return ok && status.State == "failed" && status.Reason == "route-exhausted"+ })+}++func (h *routerHarness) waitUsage(want sfu.Usage) {+ h.t.Helper()+ h.waitFor("SFU usage to reach the expected value", func() bool { return h.usage() == want })+}++func (h *routerHarness) diagnostic(roomID string) protocol.RouteDiagnosticSnapshot {+ var snapshot protocol.RouteDiagnosticSnapshot+ h.locked(func() { snapshot = h.router.routeDiagnosticSnapshot(roomID) })+ return snapshot+}++func (h *routerHarness) usage() sfu.Usage {+ var usage sfu.Usage+ h.locked(func() { usage = h.admission.Usage() })+ return usage+}++func (h *routerHarness) failNextTokenIssue() {+ h.tokens.mu.Lock()+ defer h.tokens.mu.Unlock()+ h.tokens.nextError = errors.New("token issue failed")+}++func (h *routerHarness) panicNextTokenIssue() {+ h.tokens.mu.Lock()+ defer h.tokens.mu.Unlock()+ h.tokens.nextPanic = true+}++// establishSfuRoom ports establishSfuRoom: a Host, a first Viewer moved to+// the SFU and a second Viewer joining it.+func (h *routerHarness) establishSfuRoom(created room.CreatedRoom) (host, first, second authenticatedRouteParticipant) {+ h.t.Helper()+ host = h.connectHost(created, nil, "", "")+ first = h.connectViewer(created, "sfu-root-"+created.RoomID)+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(first)+ })+ firstDirect := h.waitPrepared(first.sessionID)+ second = h.connectViewer(created, "sfu-leaf-"+created.RoomID)+ h.locked(func() {+ h.doReady(first, int64(firstDirect.Revision))+ h.doComplete(second)+ })+ firstSfu := h.waitPreparedTransport(first.sessionID, "sfu")+ h.routeReady(first, int64(firstSfu.Revision))+ secondSfu := h.waitPreparedTransport(second.sessionID, "sfu")+ h.routeReady(second, int64(secondSfu.Revision))+ return host, first, second+}++// senderDiagnostics ports senderDiagnostics(state).+func senderDiagnostics(state string) protocol.SenderQualityDiagnostics {+ var reason *string+ switch state {+ case "healthy":+ value := "none"+ reason = &value+ case "degraded":+ value := "bandwidth"+ reason = &value+ }+ return protocol.SenderQualityDiagnostics{NatTraversalPath: "unknown", Reason: reason}+}++func senderEvidenceMessage(childPeerID, connectionID, rtpStatsID, trackIdentifier string, sampleTimestampMs float64, routeRevision int64, state string) protocol.SenderQualityEvidenceMessage {+ timestamp := protocol.Num(sampleTimestampMs)+ return protocol.SenderQualityEvidenceMessage{+ Type: "sender-quality-evidence",+ ChildPeerID: childPeerID,+ ConnectionID: connectionID,+ RtpStatsID: &rtpStatsID,+ TrackIdentifier: &trackIdentifier,+ SampleTimestampMs: ×tamp,+ RouteRevision: protocol.Int(routeRevision),+ State: state,+ Diagnostics: senderDiagnostics(state),+ }+}++// fakeTokenIssuer is the harness tokenIssuer: "token-<peerId>" with a+// one-shot failure switch and a one-shot panic switch. It is called with the+// router mutex released.+type fakeTokenIssuer struct {+ mu sync.Mutex+ nextError error+ nextPanic bool+}++func (f *fakeTokenIssuer) IssueToken(request sfu.TokenRequest) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ if f.nextPanic {+ f.nextPanic = false+ panic(errors.New("token issue panicked"))+ }+ if f.nextError != nil {+ err := f.nextError+ f.nextError = nil+ return "", err+ }+ return "token-" + request.PeerID, nil+}++// spyRoomControl is the vi.spyOn(roomControl, ...) of the TS suite over the+// shared fake: call counters, one-shot behaviours (mock*Once) and a+// persistent deleteRoom implementation.+type spyRoomControl struct {+ *sfutest.FakeRoomControl+ mu sync.Mutex+ deleteRoomCalls int+ hostCheckCalls int+ drainCalls []sfu.SubscriptionFence+ deleteRoom func(context.Context, sfu.ResourceFence) error+ hostCheckOnce []func(context.Context, sfu.ResourceFence) (bool, error)+ drainOnce []func(context.Context, sfu.SubscriptionFence) error+}++func (s *spyRoomControl) DeleteRoom(ctx context.Context, fence sfu.ResourceFence) error {+ s.mu.Lock()+ s.deleteRoomCalls+++ override := s.deleteRoom+ s.mu.Unlock()+ if override != nil {+ return override(ctx, fence)+ }+ return s.FakeRoomControl.DeleteRoom(ctx, fence)+}++func (s *spyRoomControl) HostParticipantExists(ctx context.Context, fence sfu.ResourceFence) (bool, error) {+ s.mu.Lock()+ s.hostCheckCalls+++ var once func(context.Context, sfu.ResourceFence) (bool, error)+ if len(s.hostCheckOnce) > 0 {+ once, s.hostCheckOnce = s.hostCheckOnce[0], s.hostCheckOnce[1:]+ }+ s.mu.Unlock()+ if once != nil {+ return once(ctx, fence)+ }+ return s.FakeRoomControl.HostParticipantExists(ctx, fence)+}++func (s *spyRoomControl) DrainSubscription(ctx context.Context, fence sfu.SubscriptionFence) error {+ s.mu.Lock()+ s.drainCalls = append(s.drainCalls, fence)+ var once func(context.Context, sfu.SubscriptionFence) error+ if len(s.drainOnce) > 0 {+ once, s.drainOnce = s.drainOnce[0], s.drainOnce[1:]+ }+ s.mu.Unlock()+ if once != nil {+ return once(ctx, fence)+ }+ return s.FakeRoomControl.DrainSubscription(ctx, fence)+}++func (s *spyRoomControl) counts() (deleteRoom, hostCheck, drain int) {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.deleteRoomCalls, s.hostCheckCalls, len(s.drainCalls)+}++// drainAttempts is the spy's own record (the TS toHaveBeenCalledWith on the+// spied drainSubscription), which also sees the mocked calls.+func (s *spyRoomControl) drainAttempts() []sfu.SubscriptionFence {+ s.mu.Lock()+ defer s.mu.Unlock()+ return slices.Clone(s.drainCalls)+}++func (s *spyRoomControl) queueHostCheck(behaviours ...func(context.Context, sfu.ResourceFence) (bool, error)) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.hostCheckOnce = append(s.hostCheckOnce, behaviours...)+}++func (s *spyRoomControl) queueDrain(behaviours ...func(context.Context, sfu.SubscriptionFence) error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.drainOnce = append(s.drainOnce, behaviours...)+}++func (s *spyRoomControl) setDeleteRoom(implementation func(context.Context, sfu.ResourceFence) error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.deleteRoom = implementation+}++func hasViewer(fences []sfu.SubscriptionFence, viewerPeerID string) bool {+ for _, fence := range fences {+ if fence.ViewerPeerID == viewerPeerID {+ return true+ }+ }+ return false+}++// manualClock is vi.useFakeTimers + vi.setSystemTime over sinon fake-timers:+// advance fires due timers in due order at their due time and lets the+// router settle after each (tickAsync); set jumps the clock and shifts every+// pending timer by the jump so none fires early (setSystemTime).+type manualClock struct {+ mu sync.Mutex+ nowMs int64+ seq uint64+ timers []*manualTimer+ settle func()+}++type manualTimer struct {+ dueMs int64+ seq uint64+ fn func()+ settled bool+}++func (c *manualClock) now() int64 {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.nowMs+}++func (c *manualClock) set(ms int64) {+ c.mu.Lock()+ defer c.mu.Unlock()+ difference := ms - c.nowMs+ c.nowMs = ms+ for _, timer := range c.timers {+ timer.dueMs += difference+ }+}++func (c *manualClock) afterFunc(d time.Duration, fn func()) func() bool {+ c.mu.Lock()+ defer c.mu.Unlock()+ timer := &manualTimer{dueMs: c.nowMs + d.Milliseconds(), seq: c.seq, fn: fn}+ c.seq+++ c.timers = append(c.timers, timer)+ return func() bool {+ c.mu.Lock()+ defer c.mu.Unlock()+ if timer.settled {+ return false+ }+ timer.settled = true+ c.timers = slices.DeleteFunc(c.timers, func(candidate *manualTimer) bool { return candidate == timer })+ return true+ }+}++func (c *manualClock) advance(ms int64) {+ c.settle()+ c.mu.Lock()+ target := c.nowMs + ms+ c.mu.Unlock()+ for {+ c.mu.Lock()+ var next *manualTimer+ for _, timer := range c.timers {+ if timer.dueMs <= target && (next == nil || timer.dueMs < next.dueMs ||+ (timer.dueMs == next.dueMs && timer.seq < next.seq)) {+ next = timer+ }+ }+ if next == nil {+ c.nowMs = target+ c.mu.Unlock()+ c.settle()+ return+ }+ next.settled = true+ c.timers = slices.DeleteFunc(c.timers, func(candidate *manualTimer) bool { return candidate == next })+ c.nowMs = max(c.nowMs, next.dueMs)+ c.mu.Unlock()+ next.fn()+ c.settle()+ }+}++// debugRecorder is vi.spyOn(router, "debug"): a slog handler that records+// the sanitised route events while the debug flag is forced on.+type debugRecord struct {+ roomID string+ event string+ details map[string]any+}++type debugRecorder struct {+ mu sync.Mutex+ records []debugRecord+}++func captureRouteDebug(t *testing.T) *debugRecorder {+ t.Helper()+ recorder := &debugRecorder{}+ previousEnabled := routeDebugEnabled+ previousLogger := slog.Default()+ routeDebugEnabled = true+ slog.SetDefault(slog.New(recorder))+ t.Cleanup(func() {+ slog.SetDefault(previousLogger)+ routeDebugEnabled = previousEnabled+ })+ return recorder+}++func (d *debugRecorder) Enabled(context.Context, slog.Level) bool { return true }++func (d *debugRecorder) Handle(_ context.Context, record slog.Record) error {+ if record.Message != "screener-route" {+ return nil+ }+ details := map[string]any{}+ record.Attrs(func(attr slog.Attr) bool {+ details[attr.Key] = normaliseAttr(attr.Value)+ return true+ })+ roomID, _ := details["roomId"].(string)+ event, _ := details["event"].(string)+ d.mu.Lock()+ defer d.mu.Unlock()+ d.records = append(d.records, debugRecord{roomID: roomID, event: event, details: details})+ return nil+}++func (d *debugRecorder) WithAttrs([]slog.Attr) slog.Handler { return d }+func (d *debugRecorder) WithGroup(string) slog.Handler { return d }++// calledWith is expect(debug).toHaveBeenCalledWith(roomId, event,+// expect.objectContaining(expected)).+func (d *debugRecorder) calledWith(roomID, event string, expected map[string]any) bool {+ d.mu.Lock()+ defer d.mu.Unlock()+ for _, record := range d.records {+ if record.roomID != roomID || record.event != event {+ continue+ }+ matches := true+ for key, want := range expected {+ if got, ok := record.details[key]; !ok || !reflect.DeepEqual(got, want) {+ matches = false+ break+ }+ }+ if matches {+ return true+ }+ }+ return false+}++// normaliseAttr flattens slog values to string/int64/float64/bool/nil so the+// expectations can use plain literals.+func normaliseAttr(value slog.Value) any {+ switch value.Kind() {+ case slog.KindString:+ return value.String()+ case slog.KindInt64:+ return value.Int64()+ case slog.KindUint64:+ return int64(value.Uint64())+ case slog.KindFloat64:+ return value.Float64()+ case slog.KindBool:+ return value.Bool()+ case slog.KindAny:+ raw := value.Any()+ if raw == nil {+ return nil+ }+ reflected := reflect.ValueOf(raw)+ switch reflected.Kind() {+ case reflect.String:+ return reflected.String()+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:+ return reflected.Int()+ case reflect.Float32, reflect.Float64:+ return reflected.Float()+ case reflect.Bool:+ return reflected.Bool()+ }+ return raw+ }+ return value.Any()+}++var qualityPolicy = &protocol.RoutePolicy{PeerOnly: false, TopologyOptimization: true, NatPrediction: false}++// prepareQualityConvergence ports the shared prefix of "commits P2P quality+// convergence after client relative approval": two Viewers on the Host, the+// second advertising relay capacity, and enough sender evidence for the+// controller to prepare a quality-convergence candidate for the first.+func prepareQualityConvergence(h *routerHarness, debug *debugRecorder) (created room.CreatedRoom, host, first, second authenticatedRouteParticipant, firstEdge activeViewerMediaEdge, qualityPrepare protocol.RouteUpdatePrepareMessage) {+ t := h.t+ t.Helper()+ created = h.createRoom()+ host = h.connectHost(created, qualityPolicy, "", "")+ first = h.connectViewer(created, "quality-first")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(first)+ })+ firstPrepare := h.waitPrepared(first.sessionID)+ if firstPrepare.Candidate.QualityProbe {+ t.Fatal("the join candidate must not be a quality probe")+ }+ second = h.connectViewer(created, "quality-second")+ h.locked(func() {+ h.doReady(first, int64(firstPrepare.Revision))+ h.doComplete(second)+ })+ secondPrepare := h.waitPrepared(second.sessionID)+ h.locked(func() {+ h.doReady(second, int64(secondPrepare.Revision))+ h.doRelay(second, 3)+ firstEdge = h.doMustEdge(created.RoomID, first.peerID)+ secondEdge := h.doMustEdge(created.RoomID, second.peerID)+ if firstEdge.upstream != protocol.PeerUpstream(host.peerID) || secondEdge.upstream != protocol.PeerUpstream(host.peerID) {+ t.Fatalf("both viewers must start on the host: %v %v", firstEdge.upstream, secondEdge.upstream)+ }+ if !h.router.observeSenderQualityEvidence(host, senderEvidenceMessage(second.peerID, secondEdge.connectionID, "second-rtp", "track", 100, secondEdge.revision, "healthy")) {+ t.Fatal("healthy evidence for the second viewer must be accepted")+ }+ if debug != nil && !debug.calledWith(created.RoomID, "sender-quality-evidence", map[string]any{+ "routeRevision": secondEdge.revision, "committedCopies": int64(2), "candidateReservedCopies": int64(0),+ "possibleCopies": int64(2), "endpointCapacity": int64(2), "operationReason": nil,+ "candidateTransition": nil, "sampleRole": "active",+ }) {+ t.Fatalf("active sender evidence debug context missing: %+v", debug.records)+ }+ if !h.router.observeSenderQualityEvidence(host, senderEvidenceMessage(first.peerID, firstEdge.connectionID, "first-rtp", "track", 100, firstEdge.revision, "healthy")) {+ t.Fatal("healthy evidence for the first viewer must be accepted")+ }+ for window := 0; window < 3; window++ {+ if !h.router.observeSenderQualityEvidence(host, senderEvidenceMessage(first.peerID, firstEdge.connectionID, "first-rtp", "track", float64(101+window), firstEdge.revision, "degraded")) {+ t.Fatal("degraded evidence must be accepted")+ }+ }+ })+ qualityPrepare = h.waitPreparedAbove(first.sessionID, firstEdge.revision)+ if !qualityPrepare.Candidate.QualityProbe {+ t.Fatal("the convergence candidate must be a quality probe")+ }+ h.locked(func() {+ if !h.router.observeSenderQualityEvidence(second, senderEvidenceMessage(first.peerID, qualityPrepare.Candidate.ConnectionID, "candidate-rtp", "track", 200, int64(qualityPrepare.Revision), "healthy")) {+ t.Fatal("candidate evidence must be accepted")+ }+ if debug != nil && !debug.calledWith(created.RoomID, "sender-quality-evidence", map[string]any{+ "routeRevision": int64(qualityPrepare.Revision), "committedCopies": int64(0), "candidateReservedCopies": int64(1),+ "possibleCopies": int64(1), "endpointCapacity": int64(2), "operationReason": "quality-convergence",+ "candidateTransition": "none", "sampleRole": "candidate",+ }) {+ t.Fatalf("candidate sender evidence debug context missing: %+v", debug.records)+ }+ })+ return created, host, first, second, firstEdge, qualityPrepare+}++// ---------------------------------------------------------------------------+// tests, in tests/hybrid-media-router.test.ts order+// ---------------------------------------------------------------------------++// TS: it.each([undefined, false, true]) with candidateReady mocked. Go cannot+// monkeypatch the controller and SettleResult.Committed collapses undefined+// and false, so the two representable outcomes come from a real+// quality-convergence candidate: ready without relative approval settles+// accepted-but-uncommitted, ready with approval commits.+func TestRouterPublishesConnectionIdentityOnlyForExplicitCommit(t *testing.T) {+ for _, committed := range []bool{false, true} {+ t.Run(map[bool]string{false: "uncommitted", true: "committed"}[committed], func(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ created, _, first, _, firstEdge, qualityPrepare := prepareQualityConvergence(h, nil)+ var got string+ h.locked(func() {+ if committed {+ h.doReadyApproved(first, int64(qualityPrepare.Revision))+ } else {+ h.doReady(first, int64(qualityPrepare.Revision))+ }+ edge, _ := h.doEdge(created.RoomID, first.peerID)+ got = edge.connectionID+ })+ want := firstEdge.connectionID+ if committed {+ want = qualityPrepare.Candidate.ConnectionID+ }+ if got != want {+ t.Fatalf("connection identity = %q, want %q", got, want)+ }+ })+ }+}++func TestRouterLogsOnlyAggregateCandidateOriginForRouteSignals(t *testing.T) {+ debug := captureRouteDebug(t)+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ h.locked(func() {+ h.router.debugPeerSignal(peerSignalDebugInput{+ roomID: "1234",+ sourcePeerID: "source_12345678",+ targetPeerID: "target_12345678",+ signalKind: "candidate",+ candidateOrigin: protocol.CandidateOriginPredicted,+ authorization: signalAuthorizationProbe,+ })+ })+ if !debug.calledWith("1234", "peer-signal", map[string]any{+ "candidateOrigin": "predicted", "signalKind": "candidate", "authorization": "probe",+ }) {+ t.Fatalf("peer-signal debug event missing: %+v", debug.records)+ }+ for _, record := range debug.records {+ for _, value := range record.details {+ if text, ok := value.(string); ok && (strings.Contains(text, "source_12345678") || strings.Contains(text, "target_12345678")) {+ t.Fatalf("raw peer id leaked into debug output: %+v", record.details)+ }+ }+ }+}++func TestRouterProjectsExactEndpointCopyContextFromCurrentSnapshot(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ edge := func(parentPeerID, connectionID string) route.CommittedEdge {+ return route.CommittedEdge{+ Kind: route.UpstreamPeer, ChildSessionID: "child-session", ParentPeerID: parentPeerID,+ ParentSessionID: "parent-session", Transport: route.TransportDirect, ConnectionID: connectionID,+ Usable: true, PhysicalActive: true,+ }+ }+ edges := func(entries ...[3]string) *ordered.Map[string, route.CommittedEdge] {+ upstream := &ordered.Map[string, route.CommittedEdge]{}+ for _, entry := range entries {+ upstream.Set(entry[0], edge(entry[1], entry[2]))+ }+ return upstream+ }+ operation := func(tuple route.CandidateTuple, transition route.EndpointTransition) *route.OperationSnapshot {+ return &route.OperationSnapshot{+ ChildPeerID: "candidate", ChildSessionID: "candidate-session", DemandPeerID: "candidate",+ Reason: route.DemandQualityConvergence, BaseRevision: 7, FactVersion: 1,+ Candidates: []route.CandidatePlan{{Tuple: tuple, EndpointTransition: transition}},+ Cursor: 0, DeadlineAtMs: 20_000, WakeAtMs: 20_000,+ Current: &route.CurrentAttempt{Tuple: tuple, Revision: 8, ConnectionID: "candidate-connection"},+ }+ }+ snapshot := func(upstream *ordered.Map[string, route.CommittedEdge], op *route.OperationSnapshot, publication *route.HostPublication) route.RouteSnapshot {+ return route.RouteSnapshot{Revision: 7, FactVersion: 1, UpstreamByViewer: upstream, HostPublication: publication, Operation: op}+ }+ project := func(state route.RouteSnapshot, observedPeerID string, endpointCapacity int, sample qualitySample) qualityCopyContext {+ var context qualityCopyContext+ h.locked(func() { context = h.router.qualityCopyContext(state, "host", observedPeerID, endpointCapacity, sample) })+ return context+ }+ hostProducer := "host"+ overlap := route.EndpointTransition{Kind: route.TransitionOverlap, ProducerPeerID: &hostProducer}+ none := route.EndpointTransition{Kind: route.TransitionNone}+ hostEdges := edges([3]string{"a", "host", "a-connection"}, [3]string{"b", "host", "b-connection"})+ peerCandidate := route.CandidateTuple{Kind: route.UpstreamPeer, ParentPeerID: "host", Transport: route.TransportDirect}+ sfuSample := qualitySample{kind: route.UpstreamSfu, routeRevision: 8, publicationGeneration: "publication", hostSessionID: "host-session"}+ publication := &route.HostPublication{+ Generation: "publication", HostSessionID: "host-session", ConnectionID: "publication-connection",+ Usable: true, PhysicalActive: true, Resource: &route.Resource{},+ }++ got := project(snapshot(hostEdges, operation(peerCandidate, overlap), nil), "host", 2,+ qualitySample{kind: route.UpstreamPeer, childPeerID: "candidate", routeRevision: 8, connectionID: "candidate-connection"})+ want := qualityCopyContext{+ committedCopies: 2, candidateReservedCopies: 1, possibleCopies: 3, endpointCapacity: 2,+ operationReason: route.DemandQualityConvergence, candidateTransition: route.TransitionOverlap, sampleRole: "candidate",+ }+ if got != want {+ t.Fatalf("peer candidate context = %+v, want %+v", got, want)+ }++ oneHostEdge := edges([3]string{"a", "host", "a-connection"})+ sfuCases := []struct {+ state route.RouteSnapshot+ expected qualityCopyContext+ }{+ {+ state: snapshot(hostEdges, operation(route.CandidateTuple{Kind: route.UpstreamSfu, Publication: route.PublicationCreate}, overlap), nil),+ expected: qualityCopyContext{committedCopies: 2, candidateReservedCopies: 1, possibleCopies: 3,+ candidateTransition: route.TransitionOverlap},+ },+ {+ state: snapshot(oneHostEdge, operation(route.CandidateTuple{Kind: route.UpstreamSfu, Publication: route.PublicationReuse}, none), publication),+ expected: qualityCopyContext{committedCopies: 2, candidateReservedCopies: 0, possibleCopies: 2,+ candidateTransition: route.TransitionNone},+ },+ }+ for index, testCase := range sfuCases {+ got := project(testCase.state, "host", 2, sfuSample)+ if got.committedCopies != testCase.expected.committedCopies ||+ got.candidateReservedCopies != testCase.expected.candidateReservedCopies ||+ got.possibleCopies != testCase.expected.possibleCopies ||+ got.candidateTransition != testCase.expected.candidateTransition ||+ got.sampleRole != "candidate" {+ t.Fatalf("sfu case %d = %+v, want %+v (candidate)", index, got, testCase.expected)+ }+ }++ relayEdges := edges([3]string{"a", "relay", "relay-a"}, [3]string{"b", "relay", "relay-b"})+ relaySample := qualitySample{kind: route.UpstreamPeer, childPeerID: "a", routeRevision: 7, connectionID: "relay-a"}+ got = project(snapshot(relayEdges, nil, nil), "relay", 3, relaySample)+ if got.committedCopies != 2 || got.candidateReservedCopies != 0 || got.possibleCopies != 2 ||+ got.endpointCapacity != 3 || got.sampleRole != "active" {+ t.Fatalf("relay context = %+v", got)+ }+ stale := relaySample+ stale.routeRevision = 6+ if got := project(snapshot(relayEdges, nil, nil), "relay", 3, stale); got.sampleRole != "unknown" {+ t.Fatalf("stale relay sample role = %q, want unknown", got.sampleRole)+ }+}++func TestRouterKeepsControllerDiagnosticLabelUntilDepartedRelayIsPruned(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ parent := h.connectViewer(created, "diagnostic-label-parent")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(parent)+ })+ parentPrepare := h.waitPrepared(parent.sessionID)+ temporaryRoot := h.connectViewer(created, "diagnostic-label-temporary-root")+ h.locked(func() {+ h.doReady(parent, int64(parentPrepare.Revision))+ h.doRelay(parent, 1)+ h.doComplete(temporaryRoot)+ })+ temporaryPrepare := h.waitPreparedUpstream(temporaryRoot.sessionID, protocol.PeerUpstream(host.peerID))+ child := h.connectViewer(created, "diagnostic-label-child")+ h.locked(func() {+ h.doReady(temporaryRoot, int64(temporaryPrepare.Revision))+ h.doComplete(child)+ })+ childPrepare := h.waitPreparedUpstream(child.sessionID, protocol.PeerUpstream(parent.peerID))+ h.locked(func() {+ h.doReady(child, int64(childPrepare.Revision))+ h.doDisconnect(temporaryRoot)+ h.router.removeViewer(created.RoomID, temporaryRoot.peerID)+ })+ h.waitFor("the temporary root to lose its edge", func() bool {+ _, ok := h.activeEdge(created.RoomID, temporaryRoot.peerID)+ return !ok+ })++ debugPeer := func(peerID string) string {+ var label string+ h.locked(func() { label = h.router.debugPeer(created.RoomID, peerID) })+ return label+ }+ h.locked(func() {+ label := h.router.debugPeer(created.RoomID, parent.peerID)+ h.doDisconnect(parent)+ h.router.removeViewer(created.RoomID, parent.peerID)+ if got := h.router.debugPeer(created.RoomID, parent.peerID); got != label {+ t.Fatalf("label after departure = %q, want %q", got, label)+ }+ })++ recovery := h.waitPreparedMatching(child.sessionID, "a recovery onto the host", func(prepared protocol.RouteUpdatePrepareMessage) bool {+ return int64(prepared.Revision) > int64(childPrepare.Revision) &&+ prepared.Assignment.Upstream == protocol.PeerUpstream(host.peerID)+ })+ h.routeReady(child, int64(recovery.Revision))+ h.waitFor("the departed relay to be pruned", func() bool { return debugPeer(parent.peerID) == "viewer-unknown" })+}++func TestRouterMapsExactHostActiveFailureToCommittedDirectEdge(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ viewer := h.connectViewer(created, "host-edge-failure")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(viewer)+ })+ prepared := h.waitPrepared(viewer.sessionID)+ h.locked(func() {+ h.doReady(viewer, int64(prepared.Revision))+ active := h.doMustEdge(created.RoomID, viewer.peerID)+ h.doFailed(host, routeFailedMessage(active.revision, "active", active.connectionID))+ })+ h.waitFailed(viewer.sessionID)+}++func TestRouterRebindsReplacementHostAndClearsOfflineViewerMediaOwnership(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ created := h.createRoom()+ previousHost := h.connectHost(created, nil, "", "")+ viewer := h.connectViewer(created, "host-rebind-offline-viewer")+ h.locked(func() {+ h.doComplete(previousHost)+ h.doComplete(viewer)+ })+ prepared := h.waitPrepared(viewer.sessionID)+ h.locked(func() {+ h.doReady(viewer, int64(prepared.Revision))+ h.doRelay(viewer, 1)+ })+ h.waitFor("the viewer connection identity", func() bool {+ _, ok := h.activeEdge(created.RoomID, viewer.peerID)+ return ok+ })++ h.locked(func() {+ h.doDisconnect(viewer)+ h.doDisconnect(previousHost)+ })+ resumedHost := h.connectHost(created, nil, "replacement-host-client", "replacement-host-session")+ if resumedHost.peerID == previousHost.peerID {+ t.Fatal("a replacement client must receive a new host peer id")+ }+ h.locked(func() {+ h.doComplete(resumedHost)+ if _, ok := h.doEdge(created.RoomID, viewer.peerID); ok {+ t.Fatal("the offline viewer must lose its media ownership")+ }+ })+ reconnectedViewer := h.connectViewer(created, "host-rebind-offline-viewer")+ if reconnectedViewer.peerID != viewer.peerID {+ t.Fatal("the same client must keep its viewer peer id")+ }+ h.locked(func() {+ h.router.connectParticipant(reconnectedViewer)+ found := false+ for _, child := range h.router.routeDiagnosticSnapshot(created.RoomID).Children {+ if child.EffectiveCapacity == 1 {+ found = true+ }+ }+ if !found {+ t.Fatal("the reconnected viewer must keep its advertised capacity")+ }+ })+}++func TestRouterAcceptsActiveFailureForDirectConnectionAdoptedDuringRebuild(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ viewer := h.connectViewer(created, "rebuilt-edge-failure")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(viewer)+ })+ prepared := h.waitPrepared(viewer.sessionID)+ h.locked(func() {+ h.doReady(viewer, int64(prepared.Revision))+ active := h.doMustEdge(created.RoomID, viewer.peerID)+ rebuiltConnectionID := "rebuilt_connection_12345678"+ authorization := h.router.peerSignalAuthorization(peerSignalInput{+ roomID: created.RoomID, sourcePeerID: host.peerID, sourceSessionID: host.sessionID,+ targetPeerID: viewer.peerID, targetSessionID: viewer.sessionID, connectionID: rebuiltConnectionID,+ signalKind: "description", descriptionType: "offer",+ })+ if authorization != signalAuthorizationAllowed {+ t.Fatalf("adoption authorization = %v, want allowed", authorization)+ }+ adopted := h.doMustEdge(created.RoomID, viewer.peerID)+ if adopted.revision != active.revision || adopted.connectionID != rebuiltConnectionID {+ t.Fatalf("adopted edge = %+v", adopted)+ }+ h.doFailed(viewer, routeFailedMessage(active.revision, "active", rebuiltConnectionID))+ })+ h.waitFailed(viewer.sessionID)+}++func TestRouterKeepsCommittedEdgeSignalingAuthorizedDuringAnotherPeerCandidate(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ h.complete(host)++ roots := []authenticatedRouteParticipant{+ h.connectViewer(created, "stable-root-a"),+ h.connectViewer(created, "stable-root-b"),+ }+ // TS: for each root, complete then await; the ready + capacity of one+ // root share the tick with the next root's complete.+ var pending func()+ for _, root := range roots {+ h.locked(func() {+ if pending != nil {+ pending()+ }+ h.doComplete(root)+ })+ prepared := h.waitPrepared(root.sessionID)+ pending = func() {+ h.doReady(root, int64(prepared.Revision))+ h.doRelay(root, 1)+ }+ }++ candidateChild := h.connectViewer(created, "candidate-child")+ h.locked(func() {+ pending()+ h.doComplete(candidateChild)+ })+ prepared := h.waitPreparedMatching(candidateChild.sessionID, "a peer candidate", func(prepared protocol.RouteUpdatePrepareMessage) bool {+ return prepared.Assignment.Upstream.Kind == "peer"+ })+ var candidateParent, unrelatedRoot authenticatedRouteParticipant+ for _, root := range roots {+ if root.peerID == prepared.Assignment.Upstream.PeerID {+ candidateParent = root+ } else {+ unrelatedRoot = root+ }+ }++ h.locked(func() {+ activeParentEdge := h.doMustEdge(created.RoomID, candidateParent.peerID)+ authorize := func(input peerSignalInput) signalAuthorization {+ input.roomID = created.RoomID+ input.signalKind = "description"+ input.descriptionType = "offer"+ return h.router.peerSignalAuthorization(input)+ }+ if got := authorize(peerSignalInput{+ sourcePeerID: host.peerID, sourceSessionID: host.sessionID,+ targetPeerID: candidateParent.peerID, targetSessionID: candidateParent.sessionID,+ connectionID: activeParentEdge.connectionID,+ }); got != signalAuthorizationAllowed {+ t.Fatalf("committed edge authorization = %v, want allowed", got)+ }+ if got := authorize(peerSignalInput{+ sourcePeerID: candidateParent.peerID, sourceSessionID: candidateParent.sessionID,+ targetPeerID: candidateChild.peerID, targetSessionID: candidateChild.sessionID,+ connectionID: prepared.Candidate.ConnectionID,+ }); got != signalAuthorizationProbe {+ t.Fatalf("candidate authorization = %v, want probe", got)+ }+ if got := authorize(peerSignalInput{+ sourcePeerID: unrelatedRoot.peerID, sourceSessionID: unrelatedRoot.sessionID,+ targetPeerID: candidateChild.peerID, targetSessionID: candidateChild.sessionID,+ connectionID: prepared.Candidate.ConnectionID,+ }); got != signalAuthorizationUnassigned {+ t.Fatalf("unrelated authorization = %v, want unassigned", got)+ }+ })+}++func TestRouterCommitsP2PQualityConvergenceAfterClientRelativeApproval(t *testing.T) {+ debug := captureRouteDebug(t)+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ created, host, first, second, _, qualityPrepare := prepareQualityConvergence(h, debug)+ h.locked(func() {+ h.doReady(first, int64(qualityPrepare.Revision))+ if edge := h.doMustEdge(created.RoomID, first.peerID); edge.upstream != protocol.PeerUpstream(host.peerID) {+ t.Fatalf("upstream before approval = %v, want the host", edge.upstream)+ }+ h.doReadyApproved(first, int64(qualityPrepare.Revision))+ if edge := h.doMustEdge(created.RoomID, first.peerID); edge.upstream != protocol.PeerUpstream(second.peerID) {+ t.Fatalf("upstream after approval = %v, want the second viewer", edge.upstream)+ }+ })+}++func TestRouterPreparesSameParentConnectionRegenerationAfterPersistentDegradation(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ created := h.createRoom()+ host := h.connectHost(created, qualityPolicy, "", "")+ viewer := h.connectViewer(created, "quality-regeneration")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(viewer)+ })+ initial := h.waitPrepared(viewer.sessionID)+ if initial.Assignment.Upstream != protocol.PeerUpstream(host.peerID) {+ t.Fatalf("initial upstream = %v", initial.Assignment.Upstream)+ }+ var edge activeViewerMediaEdge+ h.locked(func() {+ h.doReady(viewer, int64(initial.Revision))+ edge = h.doMustEdge(created.RoomID, viewer.peerID)+ h.router.observeSenderQualityEvidence(host, senderEvidenceMessage(viewer.peerID, edge.connectionID, "old-sender-rtp", "old-track", 100, edge.revision, "healthy"))+ for _, sampleTimestampMs := range []float64{101, 102, 103} {+ h.router.observeSenderQualityEvidence(host, senderEvidenceMessage(viewer.peerID, edge.connectionID, "old-sender-rtp", "old-track", sampleTimestampMs, edge.revision, "degraded"))+ }+ })++ regeneration := h.waitPreparedAbove(viewer.sessionID, edge.revision)+ if regeneration.Candidate.Transport != "direct" || !regeneration.Candidate.QualityProbe {+ t.Fatalf("regeneration candidate = %+v", regeneration.Candidate)+ }+ if regeneration.Assignment.Upstream != protocol.PeerUpstream(host.peerID) {+ t.Fatalf("regeneration upstream = %v", regeneration.Assignment.Upstream)+ }+ if hostPrepare, ok := h.preparedFor(host.sessionID); !ok || hostPrepare.Candidate.ConnectionID != regeneration.Candidate.ConnectionID {+ t.Fatal("the host must receive the same regeneration candidate")+ }+ if active := h.mustActiveEdge(created.RoomID, viewer.peerID); active.connectionID != edge.connectionID ||+ active.upstream != protocol.PeerUpstream(host.peerID) {+ t.Fatalf("active edge during regeneration = %+v", active)+ }+}++func TestRouterCreatesNatRetriesThroughRealPrepareMessages(t *testing.T) {+ for _, withSfu := range []bool{false, true} {+ t.Run(map[bool]string{false: "sfu=false", true: "sfu=true"}[withSfu], func(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: withSfu})+ created := h.createRoom()+ host := h.connectHost(created, &protocol.RoutePolicy{PeerOnly: true, TopologyOptimization: false, NatPrediction: true}, "", "")+ viewer := h.connectViewer(created, "nat-retry")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(viewer)+ })+ connectionIDs := map[string]struct{}{}+ var staleFailure *protocol.RouteFailedMessage+ for current := 1; current <= 3; current++ {+ prepared := h.waitPreparedMatching(viewer.sessionID, "connection attempt", func(prepared protocol.RouteUpdatePrepareMessage) bool {+ return prepared.Candidate.ConnectionAttempt != nil &&+ *prepared.Candidate.ConnectionAttempt == protocol.ConnectionAttempt{Current: protocol.Int(current), Total: 3}+ })+ connectionIDs[prepared.Candidate.ConnectionID] = struct{}{}+ h.locked(func() {+ if hostPrepare, ok := lastPrepare(h.sent[host.sessionID], ""); !ok || !reflect.DeepEqual(hostPrepare.Candidate, prepared.Candidate) {+ t.Fatal("the host must see the same candidate")+ }+ if staleFailure != nil {+ h.doFailed(viewer, *staleFailure)+ }+ if again, _ := lastPrepare(h.sent[viewer.sessionID], ""); again.Candidate.ConnectionID != prepared.Candidate.ConnectionID {+ t.Fatal("a stale failure must not disturb the current candidate")+ }+ if current == 3 {+ h.doReady(viewer, int64(prepared.Revision))+ if active := h.doMustEdge(created.RoomID, viewer.peerID); active.connectionID != prepared.Candidate.ConnectionID {+ t.Fatalf("active edge = %+v", active)+ }+ } else {+ failure := routeFailedMessage(int64(prepared.Revision), "prepare", prepared.Candidate.ConnectionID)+ staleFailure = &failure+ h.doFailed(viewer, failure)+ h.doFailed(host, failure)+ }+ })+ }+ if len(connectionIDs) != 3 {+ t.Fatalf("distinct connection ids = %d, want 3", len(connectionIDs))+ }+ for _, message := range h.allMessages() {+ switch typed := message.(type) {+ case protocol.SfuConfigMessage:+ t.Fatal("peer-only media must not receive an sfu-config")+ case protocol.RouteStatusMessage:+ if typed.State == "failed" {+ t.Fatal("NAT retries must not report failure")+ }+ }+ }+ })+ }+}++func TestRouterKeepsPeerOnlySharesOutOfConfiguredSfuFallback(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true})+ created := h.createRoom()+ host := h.connectHost(created, &protocol.RoutePolicy{PeerOnly: true}, "", "")+ first := h.connectViewer(created, "peer-only-first")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(first)+ })+ direct := h.waitPreparedTransport(first.sessionID, "direct")+ blocked := h.connectViewer(created, "peer-only-blocked")+ h.locked(func() {+ h.doReady(first, int64(direct.Revision))+ h.doComplete(blocked)+ })+ h.waitFailed(blocked.sessionID)+ if sfuConfigCount(h.allMessages()) != 0 {+ t.Fatal("peer-only shares must never receive an sfu-config")+ }+}++func TestRouterSilentlyKeepsWorkingMediaWhenQualityOnlySfuAdmissionIsDenied(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true, sfuIngressCapacity: 1})+ occupied := sfu.ResourceFence{RoomID: "9001", ShareGeneration: "occupied_share_12345678", PublicationGeneration: "occupied_publication_12345678"}+ created := h.createRoom()+ host := h.connectHost(created, qualityPolicy, "", "")+ viewer := h.connectViewer(created, "quality-sfu-denied")+ h.locked(func() {+ if !h.admission.ReservePublication(occupied) {+ t.Fatal("the occupying publication must be reserved")+ }+ h.doComplete(host)+ h.doComplete(viewer)+ })+ prepared := h.waitPrepared(viewer.sessionID)+ var active activeViewerMediaEdge+ h.locked(func() {+ h.doReady(viewer, int64(prepared.Revision))+ active = h.doMustEdge(created.RoomID, viewer.peerID)+ for index, state := range []string{"healthy", "degraded"} {+ if !h.router.observeSenderQualityEvidence(host, senderEvidenceMessage(viewer.peerID, active.connectionID, "viewer-rtp", "track", float64(100+index), active.revision, state)) {+ t.Fatalf("%s evidence must be accepted", state)+ }+ }+ })+ h.waitFor("the quality operation to settle", func() bool { return h.diagnostic(created.RoomID).Operation == nil })+ for _, message := range h.messages(viewer.sessionID) {+ if _, ok := message.(protocol.RouteStatusMessage); ok {+ t.Fatal("a denied quality-only candidate must stay silent")+ }+ }+ if edge := h.mustActiveEdge(created.RoomID, viewer.peerID); edge.connectionID != active.connectionID ||+ edge.upstream != protocol.PeerUpstream(host.peerID) {+ t.Fatalf("working media changed: %+v", edge)+ }+ h.locked(func() {+ h.admission.BeginDrain(occupied)+ h.admission.CompleteDrain(occupied)+ })+}++func TestRouterNotifiesPresenceOwnerAfterCommittedGraphChanges(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true})+ created := h.createRoom()+ h.establishSfuRoom(created)+ h.waitFor("the last routesChanged call", func() bool {+ var last string+ h.locked(func() {+ if len(h.routesChanged) > 0 {+ last = h.routesChanged[len(h.routesChanged)-1]+ }+ })+ return last == created.RoomID+ })+}++func TestRouterWakesAtDerivedDirectBoundaryAndPreparesSfuAutomatically(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, prepareTimeoutMs: 300, fakeTimers: true})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ viewer := h.connectViewer(created, "staged-deadline")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(viewer)+ })++ h.waitPreparedTransport(viewer.sessionID, "direct")+ h.clock.advance(150)+ h.waitPreparedTransport(viewer.sessionID, "sfu")+ if h.hasRouteStatus(viewer.sessionID, "failed") {+ t.Fatal("the direct boundary must not report failure")+ }+}++func TestRouterKeepsExactTransportConnectedDirectCandidatePastBoundary(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, prepareTimeoutMs: 300, fakeTimers: true})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ viewer := h.connectViewer(created, "transport-connected")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(viewer)+ })+ direct := h.waitPreparedTransport(viewer.sessionID, "direct")+ h.locked(func() {+ h.router.handleRouteTransportConnected(viewer, protocol.RouteTransportConnectedMessage{+ Type: "route-transport-connected", Revision: direct.Revision, ConnectionID: direct.Candidate.ConnectionID})+ })+ h.clock.advance(150)+ if prepared, _ := h.preparedFor(viewer.sessionID); !reflect.DeepEqual(prepared, direct) {+ t.Fatalf("prepare after the boundary = %+v, want the direct candidate", prepared)+ }+ h.routeReady(viewer, int64(direct.Revision))+ h.waitFor("the active direct edge", func() bool {+ active, ok := h.activeAfter(viewer.sessionID, int64(direct.Revision)-1)+ return ok && active.Assignment.Upstream.Kind == "peer"+ })+}++func TestRouterUsesDirectBoundaryToBootstrapSfuWhenEveryHostSlotIsFull(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, prepareTimeoutMs: 300, fakeTimers: true})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ firstRoot := h.connectViewer(created, "first-root")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(firstRoot)+ })+ firstPrepare := h.waitPreparedTransport(firstRoot.sessionID, "direct")+ secondRoot := h.connectViewer(created, "second-root")+ h.locked(func() {+ h.doReady(firstRoot, int64(firstPrepare.Revision))+ h.doRelay(firstRoot, 2)+ h.doComplete(secondRoot)+ })+ secondPrepare := h.waitPreparedTransport(secondRoot.sessionID, "direct")+ waiting := h.connectViewer(created, "waiting")+ h.locked(func() {+ h.doReady(secondRoot, int64(secondPrepare.Revision))+ h.doComplete(waiting)+ })+ h.waitPreparedTransport(waiting.sessionID, "direct")++ h.clock.advance(150)+ secondBootstrap := h.waitPreparedTransport(secondRoot.sessionID, "sfu")+ h.routeFailed(secondRoot, routeFailedMessage(int64(secondBootstrap.Revision), "prepare", secondBootstrap.Candidate.ConnectionID))+ firstBootstrap := h.waitPreparedTransport(firstRoot.sessionID, "sfu")+ if h.hasRouteStatus(secondRoot.sessionID, "failed") {+ t.Fatal("a failed carrier bootstrap must not fail the carrier")+ }+ h.routeFailed(firstRoot, routeFailedMessage(int64(firstBootstrap.Revision), "prepare", firstBootstrap.Candidate.ConnectionID))+ h.waitFailed(waiting.sessionID)+ for _, root := range []authenticatedRouteParticipant{firstRoot, secondRoot} {+ if h.hasRouteStatus(root.sessionID, "failed") {+ t.Fatal("roots must not be told about the waiting viewer's exhaustion")+ }+ }+ if !h.hasRouteStatus(waiting.sessionID, "failed") {+ t.Fatal("the waiting viewer must be told")+ }+}++func TestRouterDoesNotRecreateSfuAfterExhaustedReuseAndCarrierTeardown(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, prepareTimeoutMs: 300, fakeTimers: true})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ firstRoot := h.connectViewer(created, "reuse-loop-first-root")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(firstRoot)+ })+ firstDirect := h.waitPreparedTransport(firstRoot.sessionID, "direct")+ secondRoot := h.connectViewer(created, "reuse-loop-second-root")+ h.locked(func() {+ h.doReady(firstRoot, int64(firstDirect.Revision))+ h.doRelay(firstRoot, 1)+ h.doComplete(secondRoot)+ })+ secondDirect := h.waitPreparedTransport(secondRoot.sessionID, "direct")+ departedParent := h.connectViewer(created, "reuse-loop-departed-parent")+ h.locked(func() {+ h.doReady(secondRoot, int64(secondDirect.Revision))+ h.doComplete(departedParent)+ })+ parentDirect := h.waitPreparedUpstream(departedParent.sessionID, protocol.PeerUpstream(firstRoot.peerID))+ demand := h.connectViewer(created, "reuse-loop-demand")+ h.locked(func() {+ h.doReady(departedParent, int64(parentDirect.Revision))+ h.doRelay(departedParent, 1)+ h.doComplete(demand)+ })+ demandDirect := h.waitPreparedUpstream(demand.sessionID, protocol.PeerUpstream(departedParent.peerID))+ var departureAt int64+ h.locked(func() {+ h.doReady(demand, int64(demandDirect.Revision))+ departureAt = h.clock.now()+ h.doDisconnect(departedParent)+ h.router.removeViewer(created.RoomID, departedParent.peerID)+ h.doRelay(secondRoot, 1)+ })++ h.waitFor("a direct recovery for the demand", func() bool {+ recovery, ok := h.ownPrepare(demand)+ return ok && int64(recovery.Revision) > int64(demandDirect.Revision) &&+ recovery.Candidate.ChildPeerID == demand.peerID && recovery.Candidate.Transport == "direct"+ })+ h.clock.advance(max(int64(0), departureAt+150-h.clock.now()))++ var carrier authenticatedRouteParticipant+ h.waitFor("a carrier bootstrap", func() bool {+ for _, viewer := range []authenticatedRouteParticipant{firstRoot, secondRoot} {+ if prepared, ok := h.ownPrepare(viewer); ok && prepared.Candidate.Transport == "sfu" {+ carrier = viewer+ return true+ }+ }+ return false+ })+ bootstrap, _ := h.ownPrepare(carrier)+ h.routeReady(carrier, int64(bootstrap.Revision))++ h.waitPreparedTransport(demand.sessionID, "sfu")+ if len(h.roomControl.Created()) != 1 {+ t.Fatalf("created rooms = %d, want 1", len(h.roomControl.Created()))+ }+ configCountAfterBootstrap := sfuConfigCount(h.allMessages())+ if configCountAfterBootstrap < 3 {+ t.Fatalf("sfu-config count after bootstrap = %d, want >= 3", configCountAfterBootstrap)+ }++ h.clock.advance(max(int64(0), departureAt+300-h.clock.now()))+ h.waitFor("the carrier direct convergence", func() bool {+ prepared, ok := h.ownPrepare(carrier)+ return ok && prepared.Candidate.Transport == "direct"+ })+ if operation := h.diagnostic(created.RoomID).Operation; operation == nil || operation.Reason != "direct-convergence" {+ t.Fatalf("operation = %+v, want direct-convergence", operation)+ }+ carrierDirect, _ := h.ownPrepare(carrier)+ h.routeReady(carrier, int64(carrierDirect.Revision))++ h.waitFor("the carrier back on the host", func() bool {+ edge, ok := h.activeEdge(created.RoomID, carrier.peerID)+ return ok && edge.upstream == protocol.PeerUpstream(host.peerID)+ })+ h.waitFor("the publication drain", func() bool { return len(h.roomControl.Deleted()) == 1 })+ h.clock.advance(300)++ if len(h.roomControl.Created()) != 1 {+ t.Fatalf("created rooms = %d, want 1", len(h.roomControl.Created()))+ }+ if count := sfuConfigCount(h.allMessages()); count != configCountAfterBootstrap {+ t.Fatalf("sfu-config count = %d, want %d", count, configCountAfterBootstrap)+ }+ if usage := h.usage(); usage != (sfu.Usage{}) {+ t.Fatalf("usage = %+v, want empty", usage)+ }+}++func TestRouterReportsLateFinalSfuBootstrapReadyOnlyToWaitingDemand(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, prepareTimeoutMs: 300, fakeTimers: true})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ firstRoot := h.connectViewer(created, "late-ready-first-root")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(firstRoot)+ })+ firstPrepare := h.waitPreparedTransport(firstRoot.sessionID, "direct")+ secondRoot := h.connectViewer(created, "late-ready-second-root")+ h.locked(func() {+ h.doReady(firstRoot, int64(firstPrepare.Revision))+ h.doRelay(firstRoot, 2)+ h.doComplete(secondRoot)+ })+ secondPrepare := h.waitPreparedTransport(secondRoot.sessionID, "direct")+ waiting := h.connectViewer(created, "late-ready-waiting")+ h.locked(func() {+ h.doReady(secondRoot, int64(secondPrepare.Revision))+ h.doComplete(waiting)+ })+ h.waitPreparedTransport(waiting.sessionID, "direct")++ h.clock.advance(150)+ firstCarrier := h.waitPreparedTransport(secondRoot.sessionID, "sfu")+ h.routeFailed(secondRoot, routeFailedMessage(int64(firstCarrier.Revision), "prepare", firstCarrier.Candidate.ConnectionID))++ finalCarrier := h.waitPreparedTransport(firstRoot.sessionID, "sfu")+ h.clock.set(451)+ h.routeReady(firstRoot, int64(finalCarrier.Revision))++ h.waitFor("exactly one exhaustion for the waiting viewer", func() bool {+ count := 0+ for _, message := range h.messages(waiting.sessionID) {+ if status, ok := message.(protocol.RouteStatusMessage); ok && status.State == "failed" && status.Reason == "route-exhausted" {+ count+++ }+ }+ return count == 1+ })+ for _, carrier := range []authenticatedRouteParticipant{firstRoot, secondRoot} {+ if h.hasRouteStatus(carrier.sessionID, "failed") {+ t.Fatal("carriers must not be told about the waiting viewer's exhaustion")+ }+ }+}++func TestRouterReportsBoundedRouteExhaustionWithoutRawErrorText(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, prepareTimeoutMs: 300, fakeTimers: true})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ viewer := h.connectViewer(created, "route-exhausted")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(viewer)+ })++ h.waitPreparedTransport(viewer.sessionID, "direct")+ h.clock.advance(150)+ h.waitPreparedTransport(viewer.sessionID, "sfu")+ h.clock.advance(150)+ h.waitFailed(viewer.sessionID)+ for _, message := range h.messages(viewer.sessionID) {+ if failure, ok := message.(protocol.ErrorMessage); ok && strings.Contains(failure.Message, "media route") {+ t.Fatal("raw error text must not reach the viewer")+ }+ }+}++func TestRouterReportsTypedExhaustionWhenExactCandidateFails(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ viewer := h.connectViewer(created, "candidate-failed")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(viewer)+ })+ prepared := h.waitPrepared(viewer.sessionID)+ h.routeFailed(viewer, routeFailedMessage(int64(prepared.Revision), "prepare", prepared.Candidate.ConnectionID))+ h.waitFailed(viewer.sessionID)+}++func noCandidateExhaustion(t *testing.T) {+ t.Helper()+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ first := h.connectViewer(created, "only-slot")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(first)+ })+ firstPrepare := h.waitPrepared(first.sessionID)+ blocked := h.connectViewer(created, "no-candidate")+ h.locked(func() {+ h.doReady(first, int64(firstPrepare.Revision))+ h.doComplete(blocked)+ })+ h.waitFailed(blocked.sessionID)+}++func TestRouterReportsTypedExhaustionWhenReconciliationHasNoCandidate(t *testing.T) {+ noCandidateExhaustion(t)+}++func TestRouterReportsOnlySfuAdmissionWaitingWhileBoundedCapacityIsUnavailable(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, prepareTimeoutMs: 300, fakeTimers: true})+ capacityFences := []sfu.ResourceFence{+ {RoomID: "9001", ShareGeneration: "capacity_share_a", PublicationGeneration: "capacity_publication_a"},+ {RoomID: "9002", ShareGeneration: "capacity_share_b", PublicationGeneration: "capacity_publication_b"},+ }+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ viewer := h.connectViewer(created, "sfu-admission-wait")+ h.locked(func() {+ for _, fence := range capacityFences {+ if !h.admission.ReservePublication(fence) {+ t.Fatal("the capacity fence must be reserved")+ }+ }+ h.doComplete(host)+ h.doComplete(viewer)+ })++ h.waitPreparedTransport(viewer.sessionID, "direct")+ h.clock.advance(150)+ h.waitFor("the sfu-admission waiting status", func() bool {+ status, ok := h.lastRouteStatus(viewer.sessionID)+ return ok && status.State == "waiting" && status.Reason == "sfu-admission"+ })+ h.locked(func() {+ for _, fence := range capacityFences {+ h.admission.BeginDrain(fence)+ h.admission.CompleteDrain(fence)+ }+ })+}++// TS asserted admission.reservePublication was not called again through a+// spy; here the observable is the waiting status count, which a woken+// waiter would re-send (map 7.2 step 9c), plus the unchanged usage.+func TestRouterPhysicallyRemovesExactSubscriptionWithoutReleasingGenerationCharge(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true, sfuIngressCapacity: 2})+ activeRoom := h.createRoom()+ _, first, _ := h.establishSfuRoom(activeRoom)+ h.waitUsage(sfu.Usage{Ingress: 1, Egress: 2})+ waitingRoom := h.createRoom()+ waitingHost := h.connectHost(waitingRoom, nil, "", "")+ waitingViewer := h.connectViewer(waitingRoom, "waiter")+ h.locked(func() {+ if !h.admission.ReservePublication(sfu.ResourceFence{RoomID: "9001", ShareGeneration: "waiter_share_12345678", PublicationGeneration: "waiter_publication_12345678"}) {+ t.Fatal("the occupying publication must be reserved")+ }+ h.doComplete(waitingHost)+ h.doComplete(waitingViewer)+ })+ direct := h.waitPrepared(waitingViewer.sessionID)+ h.routeFailed(waitingViewer, routeFailedMessage(int64(direct.Revision), "prepare", direct.Candidate.ConnectionID))+ h.waitFor("the waiting status", func() bool {+ status, ok := h.lastRouteStatus(waitingViewer.sessionID)+ return ok && status.State == "waiting" && status.Reason == "sfu-admission"+ })+ waitingBeforeRelease := h.countRouteStatus(waitingViewer.sessionID, "waiting")+ drainGate := make(chan struct{})+ h.roomControl.SetSubscriptionDrainBarrier(drainGate)++ h.locked(func() {+ h.doDisconnect(first)+ h.router.removeViewer(activeRoom.RoomID, first.peerID)+ })+ h.waitFor("one diagnostic child", func() bool { return len(h.diagnostic(activeRoom.RoomID).Children) == 1 })+ h.waitFor("the subscription drain attempt", func() bool {+ return hasViewer(h.roomControl.SubscriptionDrainAttempts(), first.peerID)+ })+ if usage := h.usage(); usage != (sfu.Usage{Ingress: 2, Egress: 2}) {+ t.Fatalf("usage during drain = %+v", usage)+ }+ close(drainGate)+ h.waitFor("the drained subscription", func() bool {+ return hasViewer(h.roomControl.DrainedSubscriptions(), first.peerID)+ })++ if usage := h.usage(); usage != (sfu.Usage{Ingress: 2, Egress: 2}) {+ t.Fatalf("usage after drain = %+v", usage)+ }+ if count := h.countRouteStatus(waitingViewer.sessionID, "waiting"); count != waitingBeforeRelease {+ t.Fatalf("waiting statuses = %d, want %d (a subscription drain must not wake waiters)", count, waitingBeforeRelease)+ }++ if err := h.close(); err != nil {+ t.Fatalf("close: %v", err)+ }+ if usage := h.usage(); usage != (sfu.Usage{}) {+ t.Fatalf("usage after close = %+v", usage)+ }+}++func TestRouterOrdersExactPrepareCommitsOnlyChildProofAndRollsBackAboveP(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 2})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ first := h.connectViewer(created, "first")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(first)+ })++ firstPrepare := h.waitPrepared(first.sessionID)+ if firstPrepare.Candidate.ChildPeerID != first.peerID || firstPrepare.Candidate.Transport != "direct" {+ t.Fatalf("first candidate = %+v", firstPrepare.Candidate)+ }+ h.locked(func() {+ if hostPrepare, ok := lastPrepare(h.sent[host.sessionID], ""); !ok || !reflect.DeepEqual(hostPrepare.Candidate, firstPrepare.Candidate) {+ t.Fatal("the host must receive the same candidate")+ }+ h.doReady(host, int64(firstPrepare.Revision))+ for _, message := range h.sent[first.sessionID] {+ if active, ok := message.(protocol.RouteUpdateActiveMessage); ok && int64(active.Revision) > int64(firstPrepare.Revision) {+ t.Fatal("host proof must not commit the candidate")+ }+ }+ h.doReady(first, int64(firstPrepare.Revision))+ })+ h.waitFor("the active route at the prepare revision", func() bool {+ for _, message := range h.messages(first.sessionID) {+ if active, ok := message.(protocol.RouteUpdateActiveMessage); ok && active.Revision == firstPrepare.Revision {+ return true+ }+ }+ return false+ })++ second := h.connectViewer(created, "second")+ h.complete(second)+ secondPrepare := h.waitPrepared(second.sessionID)+ h.routeFailed(second, routeFailedMessage(int64(secondPrepare.Revision), "prepare", secondPrepare.Candidate.ConnectionID))+ h.waitFor("the rollback broadcast", func() bool {+ _, ok := h.activeAfter(second.sessionID, int64(secondPrepare.Revision))+ return ok+ })+ if active, _ := h.activeAfter(second.sessionID, int64(secondPrepare.Revision)); int64(active.Revision) <= int64(secondPrepare.Revision) {+ t.Fatalf("rollback revision = %d", active.Revision)+ }+}++func TestRouterCreatesOneHostPublicationAndReusesExactViewerSubscriptions(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ first := h.connectViewer(created, "sfu_first")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(first)+ })+ firstDirect := h.waitPrepared(first.sessionID)+ second := h.connectViewer(created, "sfu_second")+ h.locked(func() {+ h.doReady(first, int64(firstDirect.Revision))+ h.doComplete(second)+ })+ firstSfu := h.waitPreparedTransport(first.sessionID, "sfu")+ h.routeReady(first, int64(firstSfu.Revision))++ secondSfu := h.waitPreparedTransport(second.sessionID, "sfu")+ h.routeReady(second, int64(secondSfu.Revision))+ h.waitUsage(sfu.Usage{Ingress: 1, Egress: 2})+ if count := sfuConfigCount(h.messages(host.sessionID)); count != 1 {+ t.Fatalf("host sfu-config count = %d, want 1", count)+ }+}++func TestRouterDiscardsSfuPreparationWhoseCursorBecomesStaleWhileAwaitingLiveKit(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ root := h.connectViewer(created, "prepare-stale-root")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(root)+ })+ direct := h.waitPreparedTransport(root.sessionID, "direct")+ gate := make(chan struct{})+ waiting := h.connectViewer(created, "prepare-stale-waiting")+ h.locked(func() {+ h.doReady(root, int64(direct.Revision))+ h.roomControl.SetCreateBarrier(gate)+ h.doRelay(root, 0)+ h.doComplete(waiting)+ })+ h.waitFor("the publication reservation", func() bool { return h.usage().Ingress == 1 })+ h.locked(func() {+ h.doDisconnect(root)+ close(gate)+ })+ h.waitUsage(sfu.Usage{})+ if operation := h.diagnostic(created.RoomID).Operation; operation != nil {+ t.Fatalf("operation = %+v, want none", operation)+ }+}++func TestRouterReschedulesRegularHostOfflineCheckAfterReadError(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true, sfuIngressCapacity: 2, hostOfflineCheckMs: 10})+ created := h.createRoom()+ host, _, _ := h.establishSfuRoom(created)+ release := make(chan struct{})+ t.Cleanup(func() { close(release) })+ h.roomControl.queueHostCheck(+ func(context.Context, sfu.ResourceFence) (bool, error) {+ return false, errors.New("temporary LiveKit read failure")+ },+ func(context.Context, sfu.ResourceFence) (bool, error) {+ <-release+ return true, nil+ },+ )+ h.disconnect(host)++ h.waitFor("two host checks", func() bool {+ _, hostChecks, _ := h.roomControl.counts()+ return hostChecks == 2+ })+ if usage := h.usage(); usage != (sfu.Usage{Ingress: 1, Egress: 2}) {+ t.Fatalf("usage = %+v", usage)+ }+}++func TestRouterRechecksHostOfflineRetirementAfterLiveRouteOperation(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true, sfuIngressCapacity: 2, hostOfflineCheckMs: 10})+ created := h.createRoom()+ host, first, second := h.establishSfuRoom(created)+ var active activeViewerMediaEdge+ h.locked(func() {+ h.doRelay(second, 1)+ active = h.doMustEdge(created.RoomID, first.peerID)+ h.doFailed(first, routeFailedMessage(active.revision, "active", active.connectionID))+ })+ h.waitPreparedMatching(first.sessionID, "a direct rebuild", func(prepared protocol.RouteUpdatePrepareMessage) bool {+ return int64(prepared.Revision) > active.revision && prepared.Candidate.Transport == "direct"+ })+ retry := make(chan struct{})+ h.roomControl.queueHostCheck(+ func(context.Context, sfu.ResourceFence) (bool, error) { return false, nil },+ func(context.Context, sfu.ResourceFence) (bool, error) {+ <-retry+ return false, nil+ },+ )+ h.disconnect(host)++ h.waitFor("two host checks", func() bool {+ _, hostChecks, _ := h.roomControl.counts()+ return hostChecks == 2+ })+ if _, ok := h.activeEdge(created.RoomID, first.peerID); ok {+ t.Fatal("the first viewer must have no active edge during the rebuild")+ }+ close(retry)+ h.waitUsage(sfu.Usage{})+ if _, hostChecks, _ := h.roomControl.counts(); hostChecks != 2 {+ t.Fatalf("host checks = %d, want 2", hostChecks)+ }+}++func TestRouterIgnoresOldHostOfflineResultAfterNewSfuGenerationCommits(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true, sfuIngressCapacity: 2, hostOfflineCheckMs: 10})+ created := h.createRoom()+ host, first, second := h.establishSfuRoom(created)+ oldRevision := max(h.mustActiveEdge(created.RoomID, first.peerID).revision, h.mustActiveEdge(created.RoomID, second.peerID).revision)+ delayed := make(chan struct{})+ h.roomControl.queueHostCheck(func(context.Context, sfu.ResourceFence) (bool, error) {+ <-delayed+ return false, nil+ })+ h.disconnect(host)+ h.waitFor("the first host check", func() bool {+ _, hostChecks, _ := h.roomControl.counts()+ return hostChecks == 1+ })++ replacementHost := h.connectHost(created, nil, "new-physical-host-client", "new-physical-host-session")+ h.complete(replacementHost)+ handled := map[string]struct{}{}+ for index := 0; index < 3; index++ {+ var next authenticatedRouteParticipant+ var prepared protocol.RouteUpdatePrepareMessage+ h.waitFor("a new-generation prepare", func() bool {+ for _, viewer := range []authenticatedRouteParticipant{first, second} {+ candidate, ok := h.preparedFor(viewer.sessionID)+ if _, done := handled[candidate.Candidate.ConnectionID]; ok && int64(candidate.Revision) > oldRevision && !done {+ next, prepared = viewer, candidate+ return true+ }+ }+ return false+ })+ handled[prepared.Candidate.ConnectionID] = struct{}{}+ h.routeReady(next, int64(prepared.Revision))+ }+ h.waitUsage(sfu.Usage{Ingress: 1, Egress: 2})+ createdFences := h.roomControl.Created()+ currentFence := createdFences[len(createdFences)-1]+ if currentFence.PublicationGeneration == createdFences[0].PublicationGeneration {+ t.Fatal("the replacement host must publish a new generation")+ }++ close(delayed)+ // TS: two microtask turns for the stale continuation to run.+ time.Sleep(50 * time.Millisecond)+ if usage := h.usage(); usage != (sfu.Usage{Ingress: 1, Egress: 2}) {+ t.Fatalf("usage after the stale result = %+v", usage)+ }+ if slices.Contains(h.roomControl.Deleted(), currentFence) {+ t.Fatal("the stale host-offline result must not retire the new generation")+ }+}++func TestRouterResolvesExactDirectAndPeerRelayedViewerEvidenceSources(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ root := h.connectViewer(created, "evidence-root")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(root)+ })+ rootPrepare := h.waitPrepared(root.sessionID)+ h.locked(func() {+ if _, ok := h.doEdge(created.RoomID, root.peerID); ok {+ t.Fatal("a prepared candidate is not an active edge")+ }+ h.doReady(root, int64(rootPrepare.Revision))+ })+ h.waitFor("the root active edge", func() bool {+ edge, ok := h.activeEdge(created.RoomID, root.peerID)+ return ok && edge == activeViewerMediaEdge{+ revision: int64(rootPrepare.Revision), connectionID: rootPrepare.Candidate.ConnectionID,+ upstream: protocol.PeerUpstream(host.peerID),+ }+ })++ child := h.connectViewer(created, "evidence-child")+ h.locked(func() {+ h.doRelay(root, 1)+ h.doComplete(child)+ })+ childPrepare := h.waitPrepared(child.sessionID)+ if childPrepare.Candidate.Transport != "direct" {+ t.Fatalf("child transport = %q", childPrepare.Candidate.Transport)+ }+ h.routeReady(child, int64(childPrepare.Revision))+ h.waitFor("the child active edge", func() bool {+ edge, ok := h.activeEdge(created.RoomID, child.peerID)+ return ok && edge == activeViewerMediaEdge{+ revision: int64(childPrepare.Revision), connectionID: childPrepare.Candidate.ConnectionID,+ upstream: protocol.PeerUpstream(root.peerID),+ }+ })+}++func TestRouterDrainsEveryPendingSfuPublicationDuringCloseEvenWhenOneDrainRejects(t *testing.T) {+ before := runtime.NumGoroutine()+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true, prepareTimeoutMs: 1_000, sfuIngressCapacity: 2, drainRetryMs: 10_000})+ roomA := h.createRoom()+ h.establishSfuRoom(roomA)+ roomB := h.createRoom()+ h.establishSfuRoom(roomB)+ h.roomControl.SetFailDelete(true)+ h.locked(func() {+ h.router.stopRoom(roomA.RoomID)+ h.router.stopRoom(roomB.RoomID)+ })+ h.waitFor("two delete attempts", func() bool {+ deletes, _, _ := h.roomControl.counts()+ return deletes == 2+ })++ h.roomControl.SetFailDelete(false)+ fake := h.roomControl.FakeRoomControl+ h.roomControl.setDeleteRoom(func(ctx context.Context, fence sfu.ResourceFence) error {+ if fence.RoomID == roomA.RoomID {+ return errors.New("room deletion failed")+ }+ return fake.DeleteRoom(ctx, fence)+ })++ err := h.close()+ if err == nil || !strings.Contains(err.Error(), "LiveKit drain failed during shutdown") {+ t.Fatalf("close error = %v, want the shutdown drain failure", err)+ }+ var deleted []string+ for _, fence := range h.roomControl.Deleted() {+ deleted = append(deleted, fence.RoomID)+ }+ if !slices.Equal(deleted, []string{roomB.RoomID}) {+ t.Fatalf("deleted rooms = %v, want [%s]", deleted, roomB.RoomID)+ }+ expectGoroutinesSettled(t, before)+}++func TestRouterRetriesFailedPhysicalDrainBeforeReusingExactSfuIdentity(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true, prepareTimeoutMs: 1_000, sfuIngressCapacity: 2, drainRetryMs: 10})+ created := h.createRoom()+ _, first, _ := h.establishSfuRoom(created)+ h.waitFor("the first viewer on the SFU", func() bool {+ edge, ok := h.activeEdge(created.RoomID, first.peerID)+ return ok && edge.upstream == protocol.SfuUpstream()+ })++ child := h.connectViewer(created, "sfu-peer-child")+ h.locked(func() {+ h.doRelay(first, 1)+ h.doComplete(child)+ })+ h.waitPreparedTransport(child.sessionID, "direct")+ // The direct boundary of a 1000 ms operation is 500 ms of real time.+ time.Sleep(510 * time.Millisecond)+ sfuPrepare := h.waitPreparedTransport(child.sessionID, "sfu")+ h.routeReady(child, int64(sfuPrepare.Revision))+ h.waitFor("the child on the SFU", func() bool {+ edge, ok := h.activeEdge(created.RoomID, child.peerID)+ return ok && edge.upstream == protocol.SfuUpstream()+ })+ directPrepare := h.waitPreparedTransport(child.sessionID, "direct")+ drainGate := make(chan struct{})+ h.locked(func() {+ h.roomControl.queueDrain(func(context.Context, sfu.SubscriptionFence) error {+ <-drainGate+ return errors.New("transient participant drain failure")+ })+ h.doReady(child, int64(directPrepare.Revision))+ })+ h.waitFor("the child on the first viewer", func() bool {+ edge, ok := h.activeEdge(created.RoomID, child.peerID)+ return ok && edge.upstream == protocol.PeerUpstream(first.peerID)+ })+ h.waitFor("the child subscription drain attempt", func() bool {+ return hasViewer(h.roomControl.drainAttempts(), child.peerID)+ })+ if usage := h.usage(); usage != (sfu.Usage{Ingress: 1, Egress: 3}) {+ t.Fatalf("usage = %+v", usage)+ }++ h.routeFailed(child, routeFailedMessage(int64(directPrepare.Revision), "active", directPrepare.Candidate.ConnectionID))+ h.waitFor("a rebuild operation", func() bool { return h.diagnostic(created.RoomID).Operation != nil })+ if prepared, _ := h.preparedFor(child.sessionID); prepared.Revision != directPrepare.Revision {+ t.Fatalf("prepare revision during the pending drain = %d, want %d", prepared.Revision, directPrepare.Revision)+ }++ close(drainGate)+ h.waitFor("the drain retry", func() bool {+ _, _, drains := h.roomControl.counts()+ return drains == 2+ })+ reusedSfu := h.waitPreparedMatching(child.sessionID, "the reused SFU prepare", func(prepared protocol.RouteUpdatePrepareMessage) bool {+ return int64(prepared.Revision) > int64(directPrepare.Revision) && prepared.Candidate.Transport == "sfu"+ })+ h.routeReady(child, int64(reusedSfu.Revision))+ h.waitFor("the child back on the SFU", func() bool {+ edge, ok := h.activeEdge(created.RoomID, child.peerID)+ return ok && edge.upstream == protocol.SfuUpstream()+ })+ if !hasViewer(h.roomControl.DrainedSubscriptions(), child.peerID) {+ t.Fatal("the retried drain must have removed the child")+ }+ if usage := h.usage(); usage != (sfu.Usage{Ingress: 1, Egress: 3}) {+ t.Fatalf("usage after reuse = %+v", usage)+ }+ if edge := h.mustActiveEdge(created.RoomID, first.peerID); edge.upstream != protocol.SfuUpstream() {+ t.Fatalf("first viewer upstream = %v", edge.upstream)+ }+}++func TestRouterSerializesFreshSfuConfigurationWithoutMakingRefreshOneShot(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true})+ created := h.createRoom()+ _, first, _ := h.establishSfuRoom(created)+ configCount := func() int { return sfuConfigCount(h.messages(first.sessionID)) }+ var active activeViewerMediaEdge+ var initialCount int+ h.locked(func() {+ active = h.doMustEdge(created.RoomID, first.peerID)+ if active.upstream != protocol.SfuUpstream() {+ t.Fatalf("upstream = %v", active.upstream)+ }+ initialCount = sfuConfigCount(h.sent[first.sessionID])+ h.router.refreshSfu(first, 0)+ })+ h.waitFor("the first refresh", func() bool { return configCount() == initialCount+1 })+ h.locked(func() { h.router.refreshSfu(first, active.revision) })+ h.waitFor("the second refresh", func() bool { return configCount() == initialCount+2 })+}++func TestRouterFailsExactActiveSfuRouteWhenFreshConfigurationCannotBeIssued(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true})+ created := h.createRoom()+ _, first, _ := h.establishSfuRoom(created)+ var active activeViewerMediaEdge+ h.locked(func() {+ active = h.doMustEdge(created.RoomID, first.peerID)+ if active.upstream != protocol.SfuUpstream() {+ t.Fatalf("upstream = %v", active.upstream)+ }+ h.failNextTokenIssue()+ h.router.refreshSfu(first, active.revision)+ })+ h.waitFor("the active SFU route to fail", func() bool {+ edge, ok := h.activeEdge(created.RoomID, first.peerID)+ return !ok || edge != active+ })+}++// hybrid-media-router.ts:1129-1132: a throw from roomControl or tokenIssuer+// rejected the pump promise and its .catch told the Host. In Go the throw is a+// panic raised while mu is released for the token issue, so the pump must come+// back holding mu; otherwise drivePump's deferred Unlock aborts the process.+func TestRouterTellsHostWhenCandidatePreparationPanicsWithTheLockReleased(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true})+ created := h.createRoom()+ host, _, _ := h.establishSfuRoom(created)+ joining := h.connectViewer(created, "sfu-panic")++ h.locked(func() {+ h.panicNextTokenIssue()+ h.doComplete(joining)+ })++ h.waitFor("the host to be told that media routing failed", func() bool {+ for _, message := range h.messages(host.sessionID) {+ failure, ok := message.(protocol.ErrorMessage)+ if ok && failure.Code == "SERVER_ERROR" && failure.Message == "Media routing failed" {+ return true+ }+ }+ return false+ })+ // The router still owns its lock: it settles and serves the next call.+ h.settle()+ if _, ok := h.activeEdge(created.RoomID, joining.peerID); ok {+ t.Fatal("the failed candidate must not have been committed")+ }+}++func TestRouterEmitsTypedExhaustionAndClearsDiagnosticsOnDepartureAndRoomDeletion(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ viewer := h.connectViewer(created, "diagnostic")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(viewer)+ })+ prepared := h.waitPrepared(viewer.sessionID)+ h.locked(func() {+ if len(h.router.routeDiagnosticSnapshot(created.RoomID).Children) != 1 {+ t.Fatal("one diagnostic child expected")+ }+ h.doFailed(viewer, routeFailedMessage(int64(prepared.Revision), "prepare", prepared.Candidate.ConnectionID))+ })+ h.waitFailed(viewer.sessionID)++ replacement := h.connectViewer(created, "diagnostic-replacement")+ h.locked(func() {+ emptySnapshot := func() bool {+ snapshot := h.router.routeDiagnosticSnapshot(created.RoomID)+ return len(snapshot.Children) == 0 && snapshot.Operation == nil+ }+ h.router.removeViewer(created.RoomID, viewer.peerID)+ if !emptySnapshot() {+ t.Fatal("departure must clear the diagnostics")+ }+ h.doComplete(replacement)+ if len(h.router.routeDiagnosticSnapshot(created.RoomID).Children) != 1 {+ t.Fatal("the replacement must appear in the diagnostics")+ }+ h.router.stopRoom(created.RoomID)+ if !emptySnapshot() {+ t.Fatal("stopRoom must clear the diagnostics")+ }+ h.doComplete(host)+ if len(h.router.routeDiagnosticSnapshot(created.RoomID).Children) == 0 {+ t.Fatal("a restarted share must rebuild the diagnostics")+ }+ h.router.deleteRoom(created.RoomID)+ if !emptySnapshot() {+ t.Fatal("deleteRoom must clear the diagnostics")+ }+ })+}++func TestRouterPreservesConnectedViewerCapacityAcrossSharingGenerations(t *testing.T) {+ h := newRouterHarness(t, routerHarnessOptions{capacity: 1})+ created := h.createRoom()+ host := h.connectHost(created, nil, "", "")+ root := h.connectViewer(created, "retained-capacity-root")+ h.locked(func() {+ h.doComplete(host)+ h.doComplete(root)+ })+ initialRoot := h.waitPrepared(root.sessionID)+ h.locked(func() {+ h.doReady(root, int64(initialRoot.Revision))+ h.doRelay(root, 1)+ h.router.stopRoom(created.RoomID)+ h.sent[root.sessionID] = nil+ h.doComplete(host)+ })+ restartedRoot := h.waitPrepared(root.sessionID)+ child := h.connectViewer(created, "retained-capacity-child")+ h.locked(func() {+ h.doReady(root, int64(restartedRoot.Revision))+ h.doComplete(child)+ })+ childPrepare := h.waitPrepared(child.sessionID)+ if childPrepare.Assignment.Upstream != protocol.PeerUpstream(root.peerID) {+ t.Fatalf("child upstream = %v, want the retained root", childPrepare.Assignment.Upstream)+ }+}++// TS declared this scenario twice under two names; both are kept.+func TestRouterEmitsTypedExhaustionWhenReconciliationHasNoCandidate(t *testing.T) {+ noCandidateExhaustion(t)+}++// ---------------------------------------------------------------------------+// Go-only coverage of the concurrency seams the TS runtime did not have:+// the per-room-name FIFO keeps LiveKit calls in decision order.+// ---------------------------------------------------------------------------++func TestRouterTurnsRunInDecisionOrderPerRoomName(t *testing.T) {+ var mu sync.Mutex+ r := &router{mu: &mu, roomTurns: map[string]chan struct{}{}}+ mu.Lock()+ first := r.takeTurn("room")+ second := r.takeTurn("room")+ other := r.takeTurn("other")+ mu.Unlock()++ var order []string+ var orderMu sync.Mutex+ record := func(name string) {+ orderMu.Lock()+ defer orderMu.Unlock()+ order = append(order, name)+ }+ release := make(chan struct{})+ done := make(chan struct{})+ go func() {+ second.run(func() { record("second") })+ done <- struct{}{}+ }()+ go func() {+ other.run(func() { record("other") })+ done <- struct{}{}+ }()+ <-done // "other" is independent and finishes first+ go func() {+ first.run(func() {+ <-release+ record("first")+ })+ done <- struct{}{}+ }()+ time.Sleep(10 * time.Millisecond)+ orderMu.Lock()+ if !slices.Equal(order, []string{"other"}) {+ t.Fatalf("second must wait for first: %v", order)+ }+ orderMu.Unlock()+ close(release)+ <-done+ <-done+ orderMu.Lock()+ defer orderMu.Unlock()+ if !slices.Equal(order, []string{"other", "first", "second"}) {+ t.Fatalf("order = %v", order)+ }+ mu.Lock()+ r.dropTurn(first)+ if _, still := r.roomTurns["room"]; !still {+ t.Fatal("dropping a superseded turn must keep the tail")+ }+ r.dropTurn(second)+ if _, still := r.roomTurns["room"]; still {+ t.Fatal("dropping the tail must forget the room name")+ }+ mu.Unlock()+}++func TestRouterDebugFlagParsesLikeNodeDebug(t *testing.T) {+ cases := map[string]bool{"": false, "route": true, "http,route": true, " route ": true, "router": false}+ keys := make([]string, 0, len(cases))+ for key := range cases {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ for _, key := range keys {+ if got := routeDebugFlag(key); got != cases[key] {+ t.Fatalf("routeDebugFlag(%q) = %v, want %v", key, got, cases[key])+ }+ }+}diff --git a/internal/server/signal/server.go b/internal/server/signal/server.gonew file mode 100644index 00000000..643ebf32--- /dev/null+++ b/internal/server/signal/server.go@@ -0,0 +1,1699 @@+// Package signal ports src/server/signaling.ts (SignalingServer) and+// src/server/hybrid-media-router.ts (HybridMediaRouter) from baseline+// b20fd88. server.go is the signaling server's lifecycle, upgrade ladder,+// HTTP-facing room mutations and message dispatch; session.go the+// per-connection state; presence.go the viewer presence, host status and+// room termination paths; router*.go the media router.+//+// # Locking+//+// Server.mu is the one lock of the effect layer: it guards every field of+// the server and the router, the room.Store and the route controllers. Every+// handler, timer callback and goroutine takes it; it is released only around+// I/O (the password KDF, LiveKit, token issue), after which exactly the guard+// the TypeScript ran after its await is re-run. Router methods and hooks are+// called with mu held and never lock.+package signal++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "net/url"+ "sync"+ "time"++ "github.com/coder/websocket"++ "github.com/TNTcraftHIM/Screener/internal/server/config"+ "github.com/TNTcraftHIM/Screener/internal/server/ordered"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+ "github.com/TNTcraftHIM/Screener/internal/server/room"+ "github.com/TNTcraftHIM/Screener/internal/server/route"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+)++// Ceilings and option defaults ported from src/server/signaling.ts. The first+// five are its module constants; the last four are the `??` defaults of+// SignalingOptions.+const (+ // maxBufferedSignalBytes is MAX_BUFFERED_SIGNAL_BYTES: once a connection's+ // unsent queue passes it the peer is not draining and the connection is+ // terminated, so one stalled reader cannot grow the server's heap.+ maxBufferedSignalBytes = 256 * 1024+ // defaultMaxSignalConnections and defaultMaxUnauthenticatedConnections are+ // the DEFAULT_MAX_* admission ceilings: 20 viewers plus a host across 9_000+ // room codes is far above either, so they bound abuse, not capacity.+ defaultMaxSignalConnections = 2_048+ defaultMaxUnauthenticatedConnections = 256+ // minSignalingChallengeIntervalMs is MIN_SIGNALING_CHALLENGE_INTERVAL_MS:+ // the floor between two password challenges on one connection.+ minSignalingChallengeIntervalMs = int64(1_000)+ // serviceRestartCloseGrace is SERVICE_RESTART_CLOSE_GRACE_MS: how long a+ // peer has to acknowledge close{1012} before the socket is terminated.+ serviceRestartCloseGrace = 1_000 * time.Millisecond++ defaultAuthenticationTimeoutMs = 5_000+ defaultViewerDisconnectGraceMs = 5_000+ defaultHeartbeatIntervalMs = 30_000+ defaultCleanupIntervalMs = 30_000+)++// SfuFallback is SfuFallbackOptions: the LiveKit fallback the media router+// may use. A zero timeout means the TypeScript default.+type SfuFallback struct {+ URL string+ TokenIssuer sfu.TokenIssuer+ Admission *sfu.Admission+ RoomControl sfu.RoomControl+ PrepareTimeoutMs int64+ DrainRetryMs int64+ HostOfflineCheckMs int64+}++// Options is SignalingOptions. Every zero value is the TypeScript `undefined`+// and takes the same default.+type Options struct {+ Store *room.Store+ EndpointMediaCopyCapacity int+ // SfuFallback is nil when the LiveKit fallback is disabled.+ SfuFallback *SfuFallback+ // Ice is the derived wire ICE configuration (config.IceConfig).+ Ice protocol.IceConfig+ // NATPredictionEnabled is the server capability that clamps a Host's+ // requested natPrediction route policy (configuredRoutePolicy). It is+ // not derivable from Ice: an enabled capability with no STUN listener+ // still echoes the Host's policy.+ NATPredictionEnabled bool+ AllowedOrigins map[string]struct{}+ SiteAccessAtUpgrade func(*http.Request) bool+ PublicBaseURL *url.URL+ // Now returns Unix milliseconds; nil uses the wall clock.+ Now func() int64+ AuthenticationTimeoutMs int+ ViewerDisconnectGraceMs int+ HeartbeatIntervalMs int+ CleanupIntervalMs int+ MaxConnections int+ MaxUnauthenticatedConnections int+ // AfterFunc is the timer factory (D5); nil uses time.AfterFunc.+ AfterFunc func(time.Duration, func()) func() bool+ // Logger receives the three console.error records; nil uses slog.Default().+ Logger *slog.Logger+}++// viewerQualityEvidenceGate is ViewerQualityEvidenceGate; upstreamPeerID is+// "" where the TS had null.+type viewerQualityEvidenceGate struct {+ viewerSessionID string+ upstreamKind string+ upstreamPeerID string+ connectionID string+ presentationEpoch int64+ sequence int64+}++// viewerQualityEvidenceAttempt is viewerQualityEvidenceAttemptAtMs plus the+// committed-edge connection the stamp was taken under. Tagging replaces the+// TS setViewerConnectionId reset: a viewer whose media identity changed is+// never held back by the previous route's stamp.+//+// Deviation: it does not replace the deleteViewerConnectionId reset, which+// broadcastActive also ran when a viewer's path stopped being physical. A+// viewer whose path breaks and heals on the same committed connection without+// sending evidence in between keeps its stamp here, where the TypeScript had+// cleared it, so one frame inside the 2 s window can be dropped that the+// TypeScript accepted. Unobservable: the reporter's own+// VIEWER_QUALITY_EVIDENCE_INTERVAL_MS gate means its next send is already at+// least that far from the last accepted one. The epoch/sequence gate below+// cannot be affected the same way, because a committed edge that loses+// physicalActive is never reactivated - its replacement carries a new+// connectionID, so sameEdge is false.+type viewerQualityEvidenceAttempt struct {+ connectionID string+ atMs int64+}++// roomShare is one Host share of one room. Its zero value is the TS state+// where none of the four per-room share maps had an entry, so reads need no+// presence check: generation and pausedGeneration are never stored empty+// (authenticate falls back to the session id), which is what made the TS+// `undefined === undefined` comparisons meaningful.+type roomShare struct {+ // generation survives stopSharing; only terminateRoom drops the whole+ // record (hazard 2).+ generation string+ // qualitySettings and routePolicy are nil where the TS map had no entry;+ // their presence is observable (hazard 3, and the host `authenticated`+ // quality default).+ qualitySettings *protocol.QualitySettings+ routePolicy *protocol.RoutePolicy+ // pausedGeneration is the share generation the Host paused, "" if none.+ pausedGeneration string+}++// senderQualityRateWindow is SenderQualityRateWindow.+type senderQualityRateWindow struct {+ startedAtMs int64+ count int+}++// graceTimer is one viewerGraceTimers entry; the callback compares the+// registered pointer with its own (a cleared TS timer never fired).+type graceTimer struct {+ stop func() bool+}++// Server is SignalingServer.+type Server struct {+ // ponytail: global lock, per-room locks if throughput matters+ mu sync.Mutex++ store *room.Store+ endpointMediaCopyCapacity int+ sfuFallback *SfuFallback+ ice protocol.IceConfig+ natPredictionEnabled bool+ allowedOrigins map[string]struct{}+ siteAccessAtUpgrade func(*http.Request) bool+ publicBaseURL *url.URL+ now func() int64+ afterFunc func(time.Duration, func()) func() bool+ logger *slog.Logger++ authenticationTimeoutMs int+ viewerDisconnectGraceMs int+ heartbeatIntervalMs int+ cleanupIntervalMs int+ maxConnections int+ maxUnauthenticatedConnections int++ router *router++ // sessions is socketStates (O11: heartbeat walks it in insertion order);+ // sessionsByID is socketsBySessionId.+ sessions ordered.Map[*session, struct{}]+ sessionsByID map[string]*session+ // pendingConnections reserves the slots of upgrades between the capacity+ // check and accept() (D4).+ pendingConnections int+ unauthenticatedConnections int++ viewerGraceTimers map[string]*graceTimer+ viewerQualityEvidenceGates map[string]viewerQualityEvidenceGate+ viewerQualityEvidenceAttempts map[string]viewerQualityEvidenceAttempt+ senderQualityRateBySession map[string]*senderQualityRateWindow+ // shares owns the whole per-room share lifecycle (TS+ // shareGenerationsByRoom, qualitySettingsByRoom, routePolicyByRoom and+ // pausedShareGenerationsByRoom).+ shares map[string]roomShare+ deferredViewerPresenceRooms map[string]struct{}++ heartbeatStop func() bool+ cleanupStop func() bool+ closing bool+}++// New is the SignalingServer constructor. It performs no I/O; the heartbeat+// and cleanup tickers start immediately.+func New(options Options) (*Server, error) {+ if err := protocol.AssertEndpointMediaCopyCapacity(options.EndpointMediaCopyCapacity); err != nil {+ return nil, err+ }+ if options.Store == nil {+ return nil, errors.New("signaling requires a room store")+ }+ s := &Server{+ store: options.Store,+ endpointMediaCopyCapacity: options.EndpointMediaCopyCapacity,+ sfuFallback: options.SfuFallback,+ ice: options.Ice,+ natPredictionEnabled: options.NATPredictionEnabled,+ allowedOrigins: options.AllowedOrigins,+ siteAccessAtUpgrade: options.SiteAccessAtUpgrade,+ publicBaseURL: options.PublicBaseURL,+ now: options.Now,+ afterFunc: options.AfterFunc,+ logger: options.Logger,+ authenticationTimeoutMs: orDefault(options.AuthenticationTimeoutMs, defaultAuthenticationTimeoutMs),+ viewerDisconnectGraceMs: orDefault(options.ViewerDisconnectGraceMs, defaultViewerDisconnectGraceMs),+ heartbeatIntervalMs: orDefault(options.HeartbeatIntervalMs, defaultHeartbeatIntervalMs),+ cleanupIntervalMs: orDefault(options.CleanupIntervalMs, defaultCleanupIntervalMs),+ maxConnections: orDefault(options.MaxConnections, defaultMaxSignalConnections),+ maxUnauthenticatedConnections: orDefault(options.MaxUnauthenticatedConnections, defaultMaxUnauthenticatedConnections),+ sessionsByID: map[string]*session{},+ viewerGraceTimers: map[string]*graceTimer{},+ viewerQualityEvidenceGates: map[string]viewerQualityEvidenceGate{},+ viewerQualityEvidenceAttempts: map[string]viewerQualityEvidenceAttempt{},+ senderQualityRateBySession: map[string]*senderQualityRateWindow{},+ shares: map[string]roomShare{},+ deferredViewerPresenceRooms: map[string]struct{}{},+ }+ if s.maxConnections <= 0 || s.maxUnauthenticatedConnections <= 0 ||+ s.maxUnauthenticatedConnections > s.maxConnections {+ return nil, errors.New("WebSocket connection limits are invalid")+ }+ if s.now == nil {+ s.now = func() int64 { return time.Now().UnixMilli() }+ }+ if s.afterFunc == nil {+ s.afterFunc = func(d time.Duration, fn func()) func() bool {+ return time.AfterFunc(d, fn).Stop+ }+ }+ if s.logger == nil {+ s.logger = slog.Default()+ }+ if s.siteAccessAtUpgrade == nil {+ s.siteAccessAtUpgrade = func(*http.Request) bool { return true }+ }+ var fallback *sfuFallback+ if options.SfuFallback != nil {+ fallback = &sfuFallback{+ url: options.SfuFallback.URL,+ tokenIssuer: options.SfuFallback.TokenIssuer,+ admission: options.SfuFallback.Admission,+ roomControl: options.SfuFallback.RoomControl,+ prepareTimeoutMs: options.SfuFallback.PrepareTimeoutMs,+ drainRetryMs: options.SfuFallback.DrainRetryMs,+ hostOfflineCheckMs: options.SfuFallback.HostOfflineCheckMs,+ }+ }+ mediaRouter, err := buildRouter(routerOptions{+ mu: &s.mu,+ store: s.store,+ endpointMediaCopyCapacity: s.endpointMediaCopyCapacity,+ sfu: fallback,+ hooks: routerHooks{+ sendToSession: s.sendToSession,+ shareGeneration: func(roomID string) string { return s.shares[roomID].generation },+ routesChanged: s.sendViewerPresence,+ },+ now: s.now,+ afterFunc: s.afterFunc,+ })+ if err != nil {+ return nil, err+ }+ s.router = mediaRouter+ s.mu.Lock()+ s.armHeartbeat()+ s.armCleanup()+ s.mu.Unlock()+ return s, nil+}++// buildRouter turns the HybridMediaRouter constructor's throw (an invalid+// SFU URL) into the error New returns.+func buildRouter(options routerOptions) (r *router, err error) {+ defer func() {+ if recovered := recover(); recovered != nil {+ err = fmt.Errorf("%v", recovered)+ }+ }()+ return newRouter(options), nil+}++func orDefault(value, fallback int) int {+ if value == 0 {+ return fallback+ }+ return value+}++// InviteURL is viewerInviteUrl / the inviteUrl of createRoomResponse:+// new URL(`/r/${roomId}`, publicBaseUrl) with the Viewer grant in the+// fragment only. viewerGrant "" is the TypeScript null.+func InviteURL(publicBaseURL *url.URL, roomID, viewerGrant string) string {+ invite := *publicBaseURL+ invite.Opaque = ""+ invite.Path = "/r/" + roomID+ invite.RawPath = ""+ invite.ForceQuery = false+ invite.RawQuery = ""+ invite.Fragment = ""+ invite.RawFragment = ""+ if viewerGrant != "" {+ invite.Fragment = "v=" + viewerGrant+ }+ return invite.String()+}++// ---------------------------------------------------------------------------+// upgrade+// ---------------------------------------------------------------------------++// ServeHTTP is the "upgrade" listener: the TS rejection ladder, then the+// accept (D4).+func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {+ // TS: new URL(request.url ?? "/", "http://localhost") throws. net/http+ // accepts a scheme-relative target such as "//[" as a plain path, so+ // the WHATWG authority parse is re-run on the raw target.+ if _, err := url.Parse(request.RequestURI); err != nil {+ rejectUpgrade(writer, http.StatusBadRequest)+ return+ }+ // EscapedPath, not Path: the WHATWG pathname the TS compared is not+ // percent-decoded, so "/%73ignal" was a 404 there, while URL.Path decodes+ // it to "/signal" and would give the endpoint an alias the TS never had.+ // This is the path notion the sibling HTTP router already uses+ // (app/json.go requestPath), with the same dot-segment deviation.+ if request.URL.EscapedPath() != "/signal" || request.URL.RawQuery != "" {+ rejectUpgrade(writer, http.StatusNotFound)+ return+ }+ s.mu.Lock()+ if s.closing {+ s.mu.Unlock()+ rejectUpgrade(writer, http.StatusServiceUnavailable)+ return+ }+ if !s.isAllowedOrigin(request.Header.Get("Origin")) {+ s.mu.Unlock()+ rejectUpgrade(writer, http.StatusForbidden)+ return+ }+ if !s.hasConnectionCapacity() {+ s.mu.Unlock()+ rejectUpgrade(writer, http.StatusServiceUnavailable)+ return+ }+ // The TS counted the slot synchronously inside handleUpgrade; Accept+ // performs I/O, so the slot is reserved across it.+ s.pendingConnections+++ s.mu.Unlock()++ siteAccessAuthenticated := s.siteAccessAtUpgrade(request)+ var sess *session+ // Origin was verified above with the exact isAllowedOrigin rule, so the+ // library's own check is skipped; the TS ws server never compressed.+ conn, err := websocket.Accept(writer, request, &websocket.AcceptOptions{+ InsecureSkipVerify: true,+ CompressionMode: websocket.CompressionDisabled,+ OnPongReceived: func(context.Context, []byte) {+ // TS: socket.on("pong", () => { state.alive = true })+ s.mu.Lock()+ if sess != nil {+ sess.alive = true+ }+ s.mu.Unlock()+ },+ })+ s.mu.Lock()+ defer s.mu.Unlock()+ s.pendingConnections--+ if err != nil {+ return+ }+ conn.SetReadLimit(protocol.MaxSignalBytes)+ sess = s.accept(conn, siteAccessAuthenticated)+}++// rejectUpgrade is `HTTP/1.1 {status} {message}\r\nConnection: close\r\n+// Content-Length: 0\r\n\r\n`; net/http supplies the reason phrase.+func rejectUpgrade(writer http.ResponseWriter, status int) {+ writer.Header().Set("Connection", "close")+ writer.Header().Set("Content-Length", "0")+ writer.WriteHeader(status)+}++// isAllowedOrigin ports isAllowedOrigin: present, parses, equal to its own+// serialised origin (so "http://x/path" is refused) and configured.+func (s *Server) isAllowedOrigin(origin string) bool {+ if origin == "" {+ return false+ }+ parsed, err := url.Parse(origin)+ if err != nil || parsed.Scheme == "" || parsed.Host == "" {+ return false+ }+ _, allowed := s.allowedOrigins[origin]+ return config.Origin(parsed) == origin && allowed+}++// hasConnectionCapacity ports hasConnectionCapacity with the reserved slots+// counted in.+func (s *Server) hasConnectionCapacity() bool {+ return !s.closing &&+ s.sessions.Len()+s.pendingConnections < s.maxConnections &&+ s.unauthenticatedConnections+s.pendingConnections < s.maxUnauthenticatedConnections+}++// ---------------------------------------------------------------------------+// lifecycle and HTTP-facing mutations+// ---------------------------------------------------------------------------++// Close ports close() (D6). Every client is told 1012 "Service restart"+// before the router drains, as the TS did; readers get one second to finish+// the close handshake, survivors are terminated, and the router's drain+// error, if any, is returned after everything else settled.+func (s *Server) Close(ctx context.Context) error {+ s.mu.Lock()+ s.closing = true+ if s.heartbeatStop != nil {+ s.heartbeatStop()+ }+ if s.cleanupStop != nil {+ s.cleanupStop()+ }+ for key, timer := range s.viewerGraceTimers {+ timer.stop()+ delete(s.viewerGraceTimers, key)+ }+ sessions := s.sessions.Keys()+ for _, sess := range sessions {+ sess.clearAuthenticationTimer()+ sess.close(websocket.StatusServiceRestart, "Service restart")+ }++ // T4: the grace starts where forceCloseTimer was armed, before+ // `await this.hybridMediaRouter.close()` (signaling.ts:251-259).+ //+ // Deviation (D6): the TS timer fired on its own and terminated the+ // remaining clients at one second even while the drains were still+ // running; here the grace is only consumed by the waits below, so a+ // survivor is terminated after max(1 s, the router close). D6 specifies+ // this shape ("wait for reader goroutines with min(ctx, 1 s), then+ // CloseNow survivors"), and Close returns at the same moment either way,+ // because the TS also awaited the drains before returning.+ grace := time.NewTimer(serviceRestartCloseGrace)+ defer grace.Stop()+ // TS close() ran `this.closing = true` and the router's synchronous close+ // prefix (its own closing flag, every deadline / host-offline / retry+ // timer, the drains) in one tick; only the drain waits yielded. Keeping mu+ // held across that prefix reproduces it: a router timer callback that+ // fires now cannot slip in between and start a pump against LiveKit.+ routeCloseError := s.router.close(ctx)+ s.mu.Unlock()++ // A fired timer channel never delivers again, so once the grace has expired+ // every session still inside its close handshake is a survivor.+ var survivors []*session+ expired := false+ for _, sess := range sessions {+ if !expired {+ select {+ case <-sess.readerDone:+ continue+ case <-grace.C:+ case <-ctx.Done():+ }+ expired = true+ }+ select {+ case <-sess.readerDone:+ default:+ survivors = append(survivors, sess)+ }+ }+ if len(survivors) > 0 {+ s.mu.Lock()+ for _, sess := range survivors {+ sess.terminate()+ }+ s.mu.Unlock()+ for _, sess := range survivors {+ select {+ case <-sess.readerDone:+ case <-ctx.Done():+ }+ }+ }+ return routeCloseError+}++// EndAllRooms ports endAllRooms() (O3: store order).+func (s *Server) EndAllRooms() error {+ s.mu.Lock()+ defer s.mu.Unlock()+ closedRooms, err := s.store.AbandonAllRooms()+ if err != nil {+ return err+ }+ for _, closed := range closedRooms {+ s.closeRoom(closed)+ }+ return nil+}++// UpdateRoomAccess ports updateRoomAccess(). The set-viewer-password action+// releases mu around the password KDF (S3) in the sequence the room package+// documents. Like the other room mutations it takes no context: Node ran a+// room mutation to completion even when the browser went away, and half of a+// mutation is worse than a wasted one.+func (s *Server) UpdateRoomAccess(+ roomID, hostToken string,+ request protocol.RoomAccessUpdateRequest,+) (protocol.RoomAccessUpdateResponse, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ switch action := request.(type) {+ case protocol.SetCodeEntryPolicyRequest:+ update, err := s.store.SetCodeEntryPolicy(roomID, action.Policy, hostToken)+ if err != nil {+ return nil, err+ }+ return protocol.CodeEntryPolicyUpdatedResponse{+ Type: "code-entry-policy-updated",+ CodeEntryPolicy: update.CodeEntryPolicy,+ ViewerPasswordEnabled: update.ViewerPasswordEnabled,+ }, nil+ case protocol.SetViewerPasswordRequest:+ current, err := s.store.HostManagedRoom(roomID, hostToken)+ if err != nil {+ return nil, err+ }+ material, derived := s.deriveViewerPasswordMaterial(roomID, hostToken, action.Password, current)+ enabled, err := s.store.SetViewerPassword(roomID, hostToken, material, derived, current)+ if err != nil {+ return nil, err+ }+ return protocol.ViewerPasswordUpdatedResponse{Type: "viewer-password-updated", Enabled: enabled}, nil+ case protocol.RotateViewerGrantRequest, protocol.RevokeViewerGrantRequest:+ verb := "revoke"+ if _, rotate := action.(protocol.RotateViewerGrantRequest); rotate {+ verb = "rotate"+ }+ update, err := s.store.SetViewerGrant(roomID, verb, hostToken)+ if err != nil {+ return nil, err+ }+ s.revokeGrantViewers(roomID, update)+ var inviteURL *string+ if verb == "rotate" {+ invite := InviteURL(s.publicBaseURL, roomID, update.ViewerGrant)+ inviteURL = &invite+ }+ return protocol.ViewerGrantUpdatedResponse{+ Type: "viewer-grant-updated",+ ViewerAuthorizationGeneration: update.ViewerAuthorizationGeneration,+ InviteURL: inviteURL,+ }, nil+ }+ return nil, fmt.Errorf("unknown room access request %T", request)+}++// deriveViewerPasswordMaterial is the unlocked KDF window of replaceRoom and+// setViewerPassword; mayStart is the TS `rooms.get(roomId) === current &&+// verifyDigest(hostToken)` closure. mu must be held; it is released only+// while the derivation runs. A nil password derives nothing.+func (s *Server) deriveViewerPasswordMaterial(+ roomID, hostToken string, password *string, current *room.Room,+) (material []byte, derived error) {+ if password == nil || *password == "" {+ return nil, nil+ }+ s.mu.Unlock()+ defer s.mu.Lock()+ return s.store.DeriveViewerPasswordMaterial(*password, func() bool {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.store.HostStillOwnsRoom(roomID, hostToken, current)+ })+}++// ReplaceRoom ports replaceRoom() (S4): the KDF runs unlocked, the commit+// and closeRoom run locked.+func (s *Server) ReplaceRoom(+ roomID, hostToken string,+ codeEntryPolicy protocol.CodeEntryPolicy,+ roomPassword *string,+) (room.CreatedRoom, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ current, err := s.store.HostManagedRoom(roomID, hostToken)+ if err != nil {+ return room.CreatedRoom{}, err+ }+ material, derived := s.deriveViewerPasswordMaterial(roomID, hostToken, roomPassword, current)+ replacement, err := s.store.ReplaceRoom(roomID, hostToken, codeEntryPolicy, material, derived, current)+ if err != nil {+ return room.CreatedRoom{}, err+ }+ s.closeRoom(replacement.Closed)+ return replacement.Created, nil+}++// CreateRoom is the roomStore.createRoom call of app.ts, run under mu with+// the KDF unlocked (the room package's documented sequence).+func (s *Server) CreateRoom(+ codeEntryPolicy protocol.CodeEntryPolicy,+ roomPassword *string,+ preferredRoomID string,+) (room.CreatedRoom, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ lease, err := s.store.BeginCreateRoom()+ if err != nil {+ return room.CreatedRoom{}, err+ }+ var material []byte+ var derived error+ if roomPassword != nil && *roomPassword != "" {+ func() {+ s.mu.Unlock()+ defer s.mu.Lock()+ material, derived = s.store.DeriveViewerPasswordMaterial(*roomPassword, nil)+ }()+ }+ return s.store.CreateRoom(codeEntryPolicy, material, derived, preferredRoomID, lease)+}++// armHeartbeat is the heartbeat setInterval (T1): each tick re-arms the+// next; a tick that lost the Stop race sees closing.+func (s *Server) armHeartbeat() {+ interval := time.Duration(s.heartbeatIntervalMs) * time.Millisecond+ s.heartbeatStop = s.afterFunc(interval, func() {+ s.mu.Lock()+ if s.closing {+ s.mu.Unlock()+ return+ }+ pings := s.heartbeat()+ s.armHeartbeat()+ s.mu.Unlock()+ for _, sess := range pings {+ go sess.ping(interval)+ }+ })+}++// armCleanup is the expireRooms setInterval (T2).+func (s *Server) armCleanup() {+ s.cleanupStop = s.afterFunc(time.Duration(s.cleanupIntervalMs)*time.Millisecond, func() {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.closing {+ return+ }+ s.expireRooms()+ s.armCleanup()+ })+}++// ---------------------------------------------------------------------------+// messages+// ---------------------------------------------------------------------------++// handleMessage ports handleMessage(). mu must be held.+func (s *Server) handleMessage(sess *session, encoded []byte) {+ if !s.sessions.Has(sess) || s.closing {+ return+ }+ if sess.revoked {+ return+ }+ message, err := protocol.DecodeClientMessage(encoded)+ if err != nil {+ s.rejectInvalidMessage(sess)+ return+ }+ if _, evidence := message.(protocol.ViewerQualityEvidenceMessage); evidence &&+ len(encoded) > protocol.MaxViewerQualityEvidenceBytes {+ s.rejectInvalidMessage(sess)+ return+ }++ if sess.authenticated == nil {+ request, isAuthenticate := authRequestOf(message)+ if !isAuthenticate {+ s.sendError(sess, "AUTH_REQUIRED", "Authenticate before sending messages")+ sess.close(websocket.StatusCode(protocol.SignalCloseAuthenticationFailed), "Authentication required")+ return+ }+ if sess.authenticating {+ s.rejectInvalidMessage(sess)+ return+ }+ sess.authenticating = true+ s.authenticate(sess, request)+ return+ }+ if _, isAuthenticate := message.(protocol.AuthenticateHostMessage); isAuthenticate {+ s.sendError(sess, "FORBIDDEN", "Session is already authenticated")+ return+ }+ if _, isAuthenticate := message.(protocol.AuthenticateViewerMessage); isAuthenticate {+ s.sendError(sess, "FORBIDDEN", "Session is already authenticated")+ return+ }+ if !s.isCurrentSession(sess) {+ sess.close(websocket.StatusCode(protocol.SignalCloseSessionReplaced), "Session replaced")+ return+ }+ s.handleAuthenticatedMessage(sess, sess.authenticated, message)+}++// authRequest is the role-agnostic view of an authenticate message: the+// fields authenticate() and authenticationErrorCode() read. Empty strings+// and nil pointers are absent keys.+type authRequest struct {+ role protocol.Role+ roomID string+ clientID string+ token string+ viewerGrant string+ viewerPassword string+ shareGeneration string+ sharingPaused bool+ qualitySettings *protocol.QualitySettings+ routePolicy protocol.RoutePolicy+ viewerPresence bool+ displayName *string+}++func authRequestOf(message protocol.ClientMessage) (authRequest, bool) {+ switch m := message.(type) {+ case protocol.AuthenticateHostMessage:+ return authRequest{+ role: protocol.RoleHost,+ roomID: m.RoomID,+ clientID: m.ClientID,+ token: m.Token,+ shareGeneration: m.ShareGeneration,+ sharingPaused: m.SharingPaused != nil && *m.SharingPaused,+ qualitySettings: m.QualitySettings,+ routePolicy: m.RoutePolicy,+ viewerPresence: m.ViewerPresence,+ displayName: displayNameString(m.DisplayName),+ }, true+ case protocol.AuthenticateViewerMessage:+ return authRequest{+ role: protocol.RoleViewer,+ roomID: m.RoomID,+ clientID: m.ClientID,+ viewerGrant: m.ViewerGrant,+ viewerPassword: m.ViewerPassword,+ viewerPresence: m.ViewerPresence,+ displayName: displayNameString(m.DisplayName),+ }, true+ }+ return authRequest{}, false+}++func displayNameString(name *protocol.DisplayName) *string {+ if name == nil {+ return nil+ }+ value := string(*name)+ return &value+}++// authenticate ports authenticate() up to its one await. The non-password+// branches had no await and run to completion here, inside the caller's+// critical section, exactly as the TS ran them; the password branch is a+// goroutine (D5) so the reader keeps reading while the KDF runs.+func (s *Server) authenticate(sess *session, request authRequest) {+ if request.role == protocol.RoleHost && !sess.siteAccessAuthenticated {+ s.sendError(sess, "AUTH_REQUIRED", "Site access is required")+ sess.close(websocket.StatusCode(protocol.SignalCloseAuthenticationFailed), "Authentication failed")+ s.finishAuthenticating(sess)+ return+ }+ if request.role == protocol.RoleViewer && !sess.siteAccessAuthenticated {+ mayEnter := false+ if request.viewerGrant != "" {+ allowed, err := s.store.ViewerGrantMayEnter(request.roomID, request.viewerGrant)+ if err != nil {+ s.authenticationFailed(sess, request, err)+ s.finishAuthenticating(sess)+ return+ }+ mayEnter = allowed+ }+ if !mayEnter {+ s.sendError(sess, "INVALID_TOKEN", authenticationErrorMessage("INVALID_TOKEN"))+ sess.close(websocket.StatusCode(protocol.SignalCloseAuthenticationFailed), "Authentication failed")+ s.finishAuthenticating(sess)+ return+ }+ }++ if request.role == protocol.RoleViewer && request.viewerGrant == "" && request.viewerPassword != "" {+ go s.authenticateWithPassword(sess, request)+ return+ }+ participant, err := s.store.ConnectParticipant(room.ConnectParticipantInput{+ RoomID: request.roomID,+ Role: request.role,+ Token: request.token,+ ViewerGrant: request.viewerGrant,+ ClientID: request.clientID,+ SessionID: sess.sessionID,+ })+ if err != nil {+ s.authenticationFailed(sess, request, err)+ } else {+ s.completeAuthentication(sess, request, participant)+ }+ s.finishAuthenticating(sess)+}++// finishAuthenticating is the `.finally` of `void this.authenticate(...)`.+func (s *Server) finishAuthenticating(sess *session) {+ if s.sessions.Has(sess) {+ sess.authenticating = false+ }+}++// authenticateWithPassword is the connectViewerWithPassword branch (S5): the+// KDF runs with mu released; mayConnect is evaluated on the derive goroutine+// (gate admission) and again inside the commit, both against live state.+func (s *Server) authenticateWithPassword(sess *session, request authRequest) {+ mayConnect := func() bool {+ return !s.closing && s.sessions.Has(sess) && !sess.revoked &&+ sess.authenticated == nil && sess.open()+ }+ s.mu.Lock()+ salt, expected, ref, err := s.store.ViewerPasswordChallenge(request.roomID)+ s.mu.Unlock()+ var derivedKey []byte+ if err == nil {+ derivedKey, err = s.store.DeriveViewerPassword(request.viewerPassword, salt, func() bool {+ s.mu.Lock()+ defer s.mu.Unlock()+ return mayConnect()+ })+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ defer s.finishAuthenticating(sess)+ var participant room.ConnectedParticipant+ if err == nil {+ participant, err = s.store.ConnectViewerWithPassword(room.ConnectViewerWithPasswordInput{+ RoomID: request.roomID,+ Password: request.viewerPassword,+ ClientID: request.clientID,+ SessionID: sess.sessionID,+ }, derivedKey, expected, ref, mayConnect)+ }+ if err != nil {+ s.authenticationFailed(sess, request, err)+ return+ }+ s.completeAuthentication(sess, request, participant)+}++// authenticationFailed is the catch of authenticate(): silent for a socket+// that is gone or revoked, otherwise the mapped error and 4003.+func (s *Server) authenticationFailed(sess *session, request authRequest, err error) {+ if !s.sessions.Has(sess) || sess.revoked {+ return+ }+ var roomError *room.Error+ if !errors.As(err, &roomError) {+ s.logger.Error("Signaling authentication failed unexpectedly")+ }+ code := authenticationErrorCode(request, err)+ s.sendError(sess, code, authenticationErrorMessage(code))+ sess.close(websocket.StatusCode(protocol.SignalCloseAuthenticationFailed), "Authentication failed")+}++// completeAuthentication is authenticate() after the store admitted the+// participant (lines 519-751), starting with the post-await guard.+func (s *Server) completeAuthentication(sess *session, request authRequest, participant room.ConnectedParticipant) {+ if s.closing || !s.sessions.Has(sess) || sess.revoked || !sess.open() {+ if _, err := s.store.DisconnectParticipant(participant.RoomID, participant.PeerID, sess.sessionID); err != nil {+ // The TS threw out of the async function; there is no catcher (D7).+ panic(fmt.Errorf("room store write failed while releasing an aborted authentication: %w", err))+ }+ return+ }++ sess.clearAuthenticationTimer()+ s.unauthenticatedConnections--+ roomID := participant.RoomID+ shareGeneration := ""+ if participant.Role == protocol.RoleHost && request.role == protocol.RoleHost {+ shareGeneration = s.settleHostShare(roomID, sess.sessionID, request)+ }+ displayName := authenticatedDisplayName(request)+ authenticated := &authenticatedSession{+ roomID: roomID,+ role: participant.Role,+ peerID: participant.PeerID,+ shareGeneration: shareGeneration,+ displayName: displayName,+ viewerPresence: request.viewerPresence,+ }+ sess.authenticated = authenticated+ if participant.Role == protocol.RoleViewer {+ s.clearViewerEvidence(roomID, participant.PeerID)+ }+ s.clearViewerGrace(roomID, participant.PeerID)+ routeParticipant := authenticatedRouteParticipant{+ roomID: roomID,+ role: participant.Role,+ peerID: participant.PeerID,+ sessionID: sess.sessionID,+ }+ if participant.Role == protocol.RoleHost {+ policy := s.routePolicyOf(roomID)+ routeParticipant.routePolicy = &policy+ }+ hybridState, assigned := s.connectRouteParticipant(routeParticipant)+ if !assigned {+ s.logger.Error("Media router did not assign an authenticated participant")+ s.sendError(sess, "SERVER_ERROR", "Media assignment failed")+ sess.close(websocket.StatusInternalError, "Media assignment failed")+ return+ }+ // The viewer's media identity is derived from the committed edge, never+ // stored beside it; connectParticipant has just settled the graph.+ var connectionID *string+ if participant.Role == protocol.RoleViewer {+ if edge, ok := s.router.resolveActiveViewerMediaEdge(roomID, participant.PeerID); ok {+ current := edge.connectionID+ connectionID = ¤t+ }+ }+ // O7: the host-status fan-out below uses this pre-router snapshot.+ var connectedViewers []room.ConnectedPeer+ if participant.Role == protocol.RoleHost {+ connectedViewers = s.store.GetConnectedViewers(roomID)+ }+ share := s.shares[roomID]+ routePolicy := s.routePolicyOf(roomID)++ var sfuStandbyURL *string+ if s.sfuFallback != nil && share.routePolicy != nil && !routePolicy.PeerOnly {+ standby := s.sfuFallback.URL+ sfuStandbyURL = &standby+ }+ qualitySettings := protocol.DefaultQualitySettings+ if share.qualitySettings != nil {+ qualitySettings = *share.qualitySettings+ }+ var roomShareGeneration *string+ if share.generation != "" {+ generation := share.generation+ roomShareGeneration = &generation+ }+ if participant.Role == protocol.RoleHost {+ s.send(sess, protocol.AuthenticatedHostMessage{+ Type: "authenticated",+ Protocol: protocol.SignalingProtocol,+ PeerID: participant.PeerID,+ RoomExpiresAt: participant.ExpiresAt,+ MaxViewers: protocol.Int(s.store.MaxViewersPerRoom()),+ EndpointMediaCopyCapacity: protocol.Int(s.endpointMediaCopyCapacity),+ HostOnline: participant.HostOnline,+ ConnectionID: connectionID,+ IceConfig: s.ice,+ RoutePolicy: routePolicy,+ CodeEntryPolicy: participant.CodeEntryPolicy,+ ViewerAuthorizationGeneration: participant.ViewerAuthorizationGeneration,+ MediaMode: "peer-assisted",+ ShareGeneration: roomShareGeneration,+ RouteRevision: protocol.Int(hybridState.routeRevision),+ RouteAssignment: hybridState.routeAssignment,+ QualitySettings: qualitySettings,+ SfuStandbyURL: sfuStandbyURL,+ Role: protocol.RoleHost,+ ViewerPasswordEnabled: participant.ViewerPasswordEnabled,+ })+ } else {+ hostPaused := participant.HostOnline &&+ share.pausedGeneration == share.generation+ s.send(sess, protocol.AuthenticatedViewerMessage{+ Type: "authenticated",+ Protocol: protocol.SignalingProtocol,+ PeerID: participant.PeerID,+ RoomExpiresAt: participant.ExpiresAt,+ MaxViewers: protocol.Int(s.store.MaxViewersPerRoom()),+ EndpointMediaCopyCapacity: protocol.Int(s.endpointMediaCopyCapacity),+ HostOnline: participant.HostOnline,+ HostPaused: &hostPaused,+ ConnectionID: connectionID,+ IceConfig: s.ice,+ RoutePolicy: routePolicy,+ CodeEntryPolicy: participant.CodeEntryPolicy,+ ViewerAuthorizationGeneration: participant.ViewerAuthorizationGeneration,+ MediaMode: "peer-assisted",+ ShareGeneration: roomShareGeneration,+ RouteRevision: protocol.Int(hybridState.routeRevision),+ RouteAssignment: hybridState.routeAssignment,+ QualitySettings: qualitySettings,+ SfuStandbyURL: sfuStandbyURL,+ Role: protocol.RoleViewer,+ })+ }+ if participant.ReplacedSessionID != "" {+ if replaced := s.sessionsByID[participant.ReplacedSessionID]; replaced != nil && replaced != sess {+ replaced.close(websocket.StatusCode(protocol.SignalCloseSessionReplaced), "Session replaced")+ }+ }++ if participant.Role == protocol.RoleHost {+ s.router.setPaused(roomID, s.shares[roomID].pausedGeneration == shareGeneration)+ }+ s.router.completeAuthentication(routeParticipant, hybridState)++ if participant.Role == protocol.RoleHost && shareGeneration != "" &&+ s.shares[roomID].pausedGeneration == shareGeneration {+ s.sendToSession(sess.sessionID, protocol.PauseSharingSourceMessage{+ Type: "pause-sharing-source",+ ShareGeneration: shareGeneration,+ })+ }++ s.sendViewerPresence(roomID)++ if participant.Role == protocol.RoleHost {+ for _, viewer := range connectedViewers {+ s.sendToSession(viewer.SessionID, protocol.HostStatusMessage{+ Type: "host-status",+ Online: true,+ Paused: s.shares[roomID].pausedGeneration == shareGeneration,+ })+ }+ }+}++// settleHostShare is the share half of authenticate() for a Host: it settles+// which share generation this connection owns, retires a superseded one, and+// broadcasts the quality settings and route policy the new generation starts+// with. It returns the settled generation and must run with mu held, before the+// `authenticated` message is built from the record it writes.+func (s *Server) settleHostShare(roomID, sessionID string, request authRequest) string {+ current := s.shares[roomID]+ currentGeneration := current.generation+ shareGeneration := request.shareGeneration+ if shareGeneration == "" {+ shareGeneration = currentGeneration+ }+ if shareGeneration == "" {+ shareGeneration = sessionID+ }+ sameShareWasAuthoritativelyPaused := currentGeneration == shareGeneration &&+ current.pausedGeneration == shareGeneration+ if currentGeneration != "" && currentGeneration != shareGeneration {+ s.stopSharing(roomID)+ }+ // stopSharing may have cleared the record, so the survivors are read+ // after it, exactly as the TS map reads were.+ share := s.shares[roomID]+ if request.shareGeneration != "" &&+ (currentGeneration != shareGeneration || share.qualitySettings == nil) {+ initialQualitySettings := protocol.DefaultQualitySettings+ if request.qualitySettings != nil {+ initialQualitySettings = *request.qualitySettings+ }+ share.qualitySettings = &initialQualitySettings+ // O6: store order.+ for _, viewer := range s.store.GetConnectedViewers(roomID) {+ s.sendToSession(viewer.SessionID, protocol.QualitySettingsMessage{+ Type: "quality-settings",+ QualitySettings: initialQualitySettings,+ })+ }+ }+ if currentGeneration != shareGeneration || share.routePolicy == nil {+ routePolicy := configuredRoutePolicy(request.routePolicy, s.natPredictionEnabled)+ share.routePolicy = &routePolicy+ for _, viewer := range s.store.GetConnectedViewers(roomID) {+ message := protocol.RoutePolicyMessage{+ Type: "route-policy",+ ShareGeneration: shareGeneration,+ RoutePolicy: routePolicy,+ }+ // Hazard 3: no `has(roomId)` term here, unlike `authenticated`.+ if s.sfuFallback != nil && !routePolicy.PeerOnly {+ standby := s.sfuFallback.URL+ message.SfuStandbyURL = &standby+ }+ s.sendToSession(viewer.SessionID, message)+ }+ }+ share.generation = shareGeneration+ share.pausedGeneration = ""+ if request.sharingPaused || sameShareWasAuthoritativelyPaused {+ share.pausedGeneration = shareGeneration+ }+ s.shares[roomID] = share+ return shareGeneration+}++// authenticatedDisplayName is the display name authenticate() records: nil for+// a Host that did not opt into viewer presence, and otherwise the requested+// name or the role's default.+func authenticatedDisplayName(request authRequest) *string {+ if request.role == protocol.RoleHost && !request.viewerPresence {+ return nil+ }+ if request.displayName != nil {+ return request.displayName+ }+ name := protocol.DefaultViewerDisplayName+ if request.role == protocol.RoleHost {+ name = protocol.DefaultHostDisplayNamePrefix+ }+ return &name+}++// connectRouteParticipant is the try/catch around+// hybridMediaRouter.connectParticipant: a controller assertion panics with+// the TS message (D11), which the TS catch swallowed.+func (s *Server) connectRouteParticipant(participant authenticatedRouteParticipant) (state hybridAuthenticationState, assigned bool) {+ defer func() {+ if recover() != nil {+ assigned = false+ }+ }()+ return s.router.connectParticipant(participant), true+}++func (s *Server) routePolicyOf(roomID string) protocol.RoutePolicy {+ if policy := s.shares[roomID].routePolicy; policy != nil {+ return *policy+ }+ return protocol.DefaultRoutePolicy+}++// configuredRoutePolicy ports configuredRoutePolicy.+func configuredRoutePolicy(policy protocol.RoutePolicy, natPredictionEnabled bool) protocol.RoutePolicy {+ policy.NatPrediction = natPredictionEnabled && policy.NatPrediction+ return policy+}++// routeParticipant is the `{...authenticated, sessionId}` spread handed to+// the router by the authenticated message handlers.+func routeParticipant(sess *session, authenticated *authenticatedSession) authenticatedRouteParticipant {+ return authenticatedRouteParticipant{+ roomID: authenticated.roomID,+ role: authenticated.role,+ peerID: authenticated.peerID,+ sessionID: sess.sessionID,+ }+}++// handleAuthenticatedMessage ports handleAuthenticatedMessage().+func (s *Server) handleAuthenticatedMessage(sess *session, authenticated *authenticatedSession, message protocol.ClientMessage) {+ switch m := message.(type) {+ case protocol.SignalingChallengeMessage:+ if !s.sessions.Has(sess) || sess.authenticated != authenticated {+ return+ }+ now := s.now()+ if sess.challenged {+ elapsedMs := now - sess.lastSignalingChallengeAtMs+ if elapsedMs < 0 {+ sess.lastSignalingChallengeAtMs = now+ return+ }+ if elapsedMs < minSignalingChallengeIntervalMs {+ return+ }+ }+ sess.challenged = true+ sess.lastSignalingChallengeAtMs = now+ s.send(sess, protocol.SignalingChallengeResponseMessage{+ Type: "signaling-challenge-response",+ Sequence: m.Sequence,+ })+ case protocol.ClientSignalMessage:+ s.routePeerAssistedSignal(sess, authenticated, m)+ case protocol.ClientRestartRequestMessage:+ if authenticated.role != protocol.RoleViewer {+ s.sendError(sess, "FORBIDDEN", "Only viewers may request an ICE restart")+ return+ }+ s.routePeerAssistedRestart(sess, authenticated, m)+ case protocol.SetQualitySettingsMessage:+ if authenticated.role != protocol.RoleHost {+ s.sendError(sess, "FORBIDDEN", "Only the host may set quality settings")+ return+ }+ share := s.shares[authenticated.roomID]+ share.qualitySettings = &m.QualitySettings+ s.shares[authenticated.roomID] = share+ // O8: store order.+ for _, viewer := range s.store.GetConnectedViewers(authenticated.roomID) {+ s.sendToSession(viewer.SessionID, protocol.QualitySettingsMessage{+ Type: "quality-settings",+ QualitySettings: m.QualitySettings,+ })+ }+ case protocol.RelayCapacityMessage:+ if authenticated.role != protocol.RoleViewer {+ s.sendError(sess, "FORBIDDEN", "Only a viewer may advertise relay capacity")+ return+ }+ s.router.setViewerRelayCapacity(routeParticipant(sess, authenticated), int(m.DownstreamEdges))+ case protocol.RouteReadyMessage:+ s.router.handleRouteReady(routeParticipant(sess, authenticated), m)+ case protocol.RouteTransportConnectedMessage:+ s.router.handleRouteTransportConnected(routeParticipant(sess, authenticated), m)+ case protocol.RouteMediaUnavailableMessage:+ s.router.handleRouteMediaUnavailable(routeParticipant(sess, authenticated), m)+ case protocol.RouteFailedMessage:+ s.router.handleRouteFailed(routeParticipant(sess, authenticated), m)+ case protocol.RefreshSfuMessage:+ if s.sfuFallback == nil {+ s.sendError(sess, "FORBIDDEN", "SFU fallback is not enabled")+ return+ }+ s.router.refreshSfu(routeParticipant(sess, authenticated), int64(m.Revision))+ case protocol.RequestRouteDiagnosticMessage:+ if authenticated.role != protocol.RoleHost {+ s.sendError(sess, "FORBIDDEN", "Only the host may request route diagnostics")+ return+ }+ s.send(sess, protocol.RouteDiagnosticSnapshotMessage{+ Type: "route-diagnostic-snapshot",+ Snapshot: s.router.routeDiagnosticSnapshot(authenticated.roomID),+ })+ case protocol.ViewerQualityEvidenceMessage:+ s.handleViewerQualityEvidence(sess, authenticated, m)+ case protocol.SenderQualityEvidenceMessage:+ s.handleSenderQualityEvidence(sess, authenticated, m)+ case protocol.SfuPublisherQualityEvidenceMessage:+ s.handleSfuPublisherQualityEvidence(sess, authenticated, m)+ case protocol.ResetSenderQualityMessage:+ if s.sessions.Has(sess) && sess.authenticated == authenticated {+ s.router.resetSenderQuality(routeParticipant(sess, authenticated))+ }+ case protocol.SetDisplayNameMessage:+ if authenticated.role == protocol.RoleHost && !authenticated.viewerPresence {+ s.sendError(sess, "FORBIDDEN", "Display names require the Web presence capability")+ return+ }+ name := string(m.DisplayName)+ authenticated.displayName = &name+ s.sendViewerPresence(authenticated.roomID)+ case protocol.SetSharingPausedMessage:+ if authenticated.role != protocol.RoleHost {+ s.sendError(sess, "FORBIDDEN", "只有当前分享者可以暂停分享")+ return+ }+ connectedHost, hasHost := s.store.GetConnectedHost(authenticated.roomID)+ if !s.sessions.Has(sess) ||+ !hasHost || connectedHost.SessionID != sess.sessionID ||+ authenticated.shareGeneration == "" ||+ s.shares[authenticated.roomID].generation != authenticated.shareGeneration ||+ m.ShareGeneration != authenticated.shareGeneration {+ sess.close(websocket.StatusCode(protocol.SignalCloseSessionReplaced), "Sharing generation replaced")+ return+ }+ share := s.shares[authenticated.roomID]+ share.pausedGeneration = ""+ if m.Paused {+ share.pausedGeneration = authenticated.shareGeneration+ }+ s.shares[authenticated.roomID] = share+ s.router.setPaused(authenticated.roomID, m.Paused)+ s.broadcastHostStatus(authenticated.roomID, true, m.Paused)+ case protocol.StopSharingMessage:+ if authenticated.role != protocol.RoleHost {+ s.sendError(sess, "FORBIDDEN", "只有当前分享者可以停止分享")+ return+ }+ if authenticated.shareGeneration == "" ||+ s.shares[authenticated.roomID].generation != authenticated.shareGeneration ||+ (m.ShareGeneration != "" && m.ShareGeneration != authenticated.shareGeneration) {+ sess.close(websocket.StatusCode(protocol.SignalCloseSessionReplaced), "Sharing generation replaced")+ return+ }+ // Hazard 4: the participant leaves the store before stopSharing()+ // so the sharing-stopped / host-status pair is what viewers see.+ if s.sessions.Has(sess) && sess.authenticated == authenticated {+ if _, err := s.store.DisconnectParticipant(authenticated.roomID, authenticated.peerID, sess.sessionID); err != nil {+ // The TS threw out of the message handler; nothing caught it (D7).+ panic(fmt.Errorf("room store write failed while stopping sharing: %w", err))+ }+ }+ s.stopSharing(authenticated.roomID)+ s.sendViewerPresence(authenticated.roomID)+ sess.close(websocket.StatusNormalClosure, "Sharing stopped")+ case protocol.AbandonRoomMessage:+ if authenticated.role != protocol.RoleHost {+ s.sendError(sess, "FORBIDDEN", "Only the host may abandon the room")+ return+ }+ if err := s.abandonRoom(authenticated.roomID); err != nil {+ s.logger.Error("Room abandonment failed", "error", err)+ s.sendError(sess, "SERVER_ERROR", "Room could not be abandoned")+ }+ }+}++// ---------------------------------------------------------------------------+// quality evidence+// ---------------------------------------------------------------------------++// handleViewerQualityEvidence ports handleViewerQualityEvidence(). The+// forwarded envelope is encoded once; the same bytes reach the upstream+// recipient and, when different and opted in, the host (hazard 10).+func (s *Server) handleViewerQualityEvidence(sess *session, source *authenticatedSession, message protocol.ViewerQualityEvidenceMessage) {+ if source.role != protocol.RoleViewer {+ return+ }+ if !s.sessions.Has(sess) || sess.authenticated != source {+ return+ }+ connectedViewer, ok := s.store.GetConnectedViewer(source.roomID, source.peerID)+ if !ok || connectedViewer.SessionID != sess.sessionID {+ return+ }++ // The committed edge owns the viewer's media identity; connectionID is+ // "" while the viewer has no physical path (the TS mirror was absent).+ edge, hasEdge := s.router.resolveActiveViewerMediaEdge(source.roomID, source.peerID)+ connectionID := ""+ if hasEdge {+ connectionID = edge.connectionID+ }++ gateKey := viewerKey(source.roomID, source.peerID)+ now := s.now()+ if previous, attempted := s.viewerQualityEvidenceAttempts[gateKey]; attempted &&+ previous.connectionID == connectionID &&+ now-previous.atMs < protocol.ViewerQualityEvidenceIntervalMs {+ return+ }+ s.viewerQualityEvidenceAttempts[gateKey] = viewerQualityEvidenceAttempt{connectionID: connectionID, atMs: now}++ if !hasEdge || message.Guard.ConnectionID != connectionID {+ return+ }++ host, hasHost := s.store.GetConnectedHost(source.roomID)+ routeRevision := edge.revision+ upstream := edge.upstream+ var recipient room.ConnectedPeer+ hasRecipient := false+ if upstream.Kind == "peer" {+ recipient, hasRecipient = s.connectedPeer(source.roomID, upstream.PeerID)+ } else {+ recipient, hasRecipient = host, hasHost+ }+ if !hasRecipient || int64(message.Guard.RouteRevision) != routeRevision ||+ (upstream.Kind == "peer" && upstream.PeerID == source.peerID) {+ return+ }++ presentationEpoch := int64(message.Guard.PresentationEpoch)+ sequence := int64(message.Sequence)+ previous, hasPrevious := s.viewerQualityEvidenceGates[gateKey]+ sameEdge := hasPrevious &&+ previous.viewerSessionID == sess.sessionID &&+ previous.upstreamKind == upstream.Kind &&+ previous.upstreamPeerID == upstream.PeerID &&+ previous.connectionID == connectionID+ if sameEdge &&+ (presentationEpoch < previous.presentationEpoch ||+ (presentationEpoch == previous.presentationEpoch && sequence <= previous.sequence)) {+ return+ }++ forwarded := protocol.ServerViewerQualityEvidenceMessage{+ Type: "viewer-quality-evidence",+ ViewerPeerID: source.peerID,+ Upstream: upstream,+ Guard: protocol.ViewerQualityEvidenceGuard{+ ConnectionID: connectionID,+ RouteRevision: protocol.Int(routeRevision),+ PresentationEpoch: message.Guard.PresentationEpoch,+ },+ Sequence: message.Sequence,+ WindowMs: message.WindowMs,+ Metrics: message.Metrics,+ }+ encoded, err := protocol.EncodeServerMessage(forwarded)+ if err != nil {+ panic(err)+ }+ if len(encoded) > protocol.MaxViewerQualityEvidenceBytes {+ return+ }+ qualityUpstream := route.QualityUpstream{Kind: route.UpstreamSfu}+ if upstream.Kind == "peer" {+ qualityUpstream = route.QualityUpstream{Kind: route.UpstreamPeer, PeerID: upstream.PeerID}+ }+ qualityResult := s.router.observeQualityEvidence(source.roomID, route.RouteQualityEvidenceInput{+ ChildPeerID: source.peerID,+ ChildSessionID: sess.sessionID,+ RouteRevision: routeRevision,+ ConnectionID: connectionID,+ Upstream: qualityUpstream,+ PresentationEpoch: presentationEpoch,+ WindowMs: int64(message.WindowMs),+ Metrics: message.Metrics,+ AcceptedAtMs: now,+ })+ if qualityResult == route.QualityEvidenceRejected {+ return+ }+ s.viewerQualityEvidenceGates[gateKey] = viewerQualityEvidenceGate{+ viewerSessionID: sess.sessionID,+ upstreamKind: upstream.Kind,+ upstreamPeerID: upstream.PeerID,+ connectionID: connectionID,+ presentationEpoch: presentationEpoch,+ sequence: sequence,+ }+ s.sendEncodedToSession(recipient.SessionID, encoded)+ if !hasHost || host.SessionID == recipient.SessionID {+ return+ }+ if hostState := s.authenticatedOf(host.SessionID); hostState != nil &&+ hostState.role == protocol.RoleHost &&+ hostState.roomID == source.roomID &&+ hostState.peerID == host.PeerID &&+ hostState.viewerPresence {+ s.sendEncodedToSession(host.SessionID, encoded)+ }+}++// authenticatedOf is `socketStates.get(socketsBySessionId.get(id))?.authenticated`.+func (s *Server) authenticatedOf(sessionID string) *authenticatedSession {+ if sess := s.sessionsByID[sessionID]; sess != nil {+ return sess.authenticated+ }+ return nil+}++// handleSenderQualityEvidence ports handleSenderQualityEvidence().+func (s *Server) handleSenderQualityEvidence(sess *session, source *authenticatedSession, message protocol.SenderQualityEvidenceMessage) {+ if source.peerID == message.ChildPeerID {+ return+ }+ if !s.sessions.Has(sess) || sess.authenticated != source {+ return+ }+ if !s.consumeSenderQualityBudget(sess.sessionID, s.now()) {+ return+ }+ s.router.observeSenderQualityEvidence(routeParticipant(sess, source), message)+}++// handleSfuPublisherQualityEvidence ports handleSfuPublisherQualityEvidence().+func (s *Server) handleSfuPublisherQualityEvidence(sess *session, source *authenticatedSession, message protocol.SfuPublisherQualityEvidenceMessage) {+ if source.role != protocol.RoleHost {+ return+ }+ if !s.sessions.Has(sess) || sess.authenticated != source {+ return+ }+ if !s.consumeSenderQualityBudget(sess.sessionID, s.now()) {+ return+ }+ s.router.observeSfuPublisherQualityEvidence(routeParticipant(sess, source), message)+}++// consumeSenderQualityBudget ports consumeSenderQualityBudget().+func (s *Server) consumeSenderQualityBudget(sessionID string, nowMs int64) bool {+ maximumReports := min(s.endpointMediaCopyCapacity+1, 3) * 2+ current := s.senderQualityRateBySession[sessionID]+ if current == nil || nowMs-current.startedAtMs >= protocol.ViewerQualityEvidenceIntervalMs {+ s.senderQualityRateBySession[sessionID] = &senderQualityRateWindow{startedAtMs: nowMs, count: 1}+ return true+ }+ if current.count >= maximumReports {+ return false+ }+ current.count+++ return true+}++// ---------------------------------------------------------------------------+// peer-assisted signaling+// ---------------------------------------------------------------------------++// routePeerAssistedSignal ports routeSignal / routePeerAssistedSignal.+func (s *Server) routePeerAssistedSignal(sess *session, source *authenticatedSession, message protocol.ClientSignalMessage) {+ targetPeerID := message.TargetPeerID+ if targetPeerID == "" {+ s.sendError(sess, "FORBIDDEN", "Peer-assisted signals must target an assigned peer")+ return+ }+ parentToChild := s.router.isActivePeerParentOf(source.roomID, source.peerID, targetPeerID)+ childToParent := s.router.isActivePeerParentOf(source.roomID, targetPeerID, source.peerID)+ target, hasTarget := s.connectedPeer(source.roomID, targetPeerID)+ if !hasTarget {+ if parentToChild || childToParent {+ return+ }+ s.sendError(sess, "PEER_NOT_FOUND", "Target peer is not connected")+ return+ }++ payload := message.Payload+ descriptionType := ""+ if payload.Kind == "description" && payload.Description != nil {+ descriptionType = payload.Description.Type+ }+ candidateAuthorized := s.router.peerSignalAuthorization(peerSignalInput{+ roomID: source.roomID,+ sourcePeerID: source.peerID,+ sourceSessionID: sess.sessionID,+ targetPeerID: target.PeerID,+ targetSessionID: target.SessionID,+ connectionID: payload.ConnectionID,+ signalKind: payload.Kind,+ descriptionType: descriptionType,+ })+ debugInput := peerSignalDebugInput{+ roomID: source.roomID,+ sourcePeerID: source.peerID,+ targetPeerID: target.PeerID,+ signalKind: payload.Kind,+ descriptionType: descriptionType,+ authorization: candidateAuthorized,+ }+ if payload.Kind == "candidate" {+ candidate := ""+ if payload.Candidate != nil {+ candidate = payload.Candidate.Candidate+ }+ debugInput.candidateOrigin = protocol.CandidateSignalOriginOf(candidate)+ }+ s.router.debugPeerSignal(debugInput)+ var assignedEdgeAuthorized bool+ switch descriptionType {+ case "offer":+ assignedEdgeAuthorized = parentToChild+ case "":+ assignedEdgeAuthorized = parentToChild || childToParent+ default:+ assignedEdgeAuthorized = childToParent+ }+ var authorized bool+ switch candidateAuthorized {+ case signalAuthorizationUnassigned:+ authorized = assignedEdgeAuthorized+ case signalAuthorizationDenied:+ authorized = false+ default:+ authorized = true+ }+ if !authorized {+ return+ }++ // TS setViewerConnectionId here only ever restated the committed edge:+ // an authorized non-probe offer either matches edge.connectionId or was+ // adopted into it by peerSignalAuthorization.+ s.sendToSession(target.SessionID, protocol.ServerSignalMessage{+ Type: "signal",+ FromPeerID: source.peerID,+ Payload: payload,+ })+}++// routePeerAssistedRestart ports routePeerAssistedRestart.+func (s *Server) routePeerAssistedRestart(sess *session, source *authenticatedSession, message protocol.ClientRestartRequestMessage) {+ targetPeerID := message.TargetPeerID+ if targetPeerID == "" || !s.router.isActivePeerParentOf(source.roomID, targetPeerID, source.peerID) {+ s.sendError(sess, "FORBIDDEN", "Restart target is not the assigned media parent")+ return+ }+ parent, hasParent := s.connectedPeer(source.roomID, targetPeerID)+ if !hasParent {+ s.sendError(sess, "PEER_NOT_FOUND", "Media parent is not connected")+ return+ }+ s.sendToSession(parent.SessionID, protocol.ServerRestartRequestMessage{+ Type: "restart-request",+ FromPeerID: source.peerID,+ ConnectionID: message.ConnectionID,+ Rebuild: message.Rebuild,+ })+}++// isCurrentSession ports isCurrentSession: checked on every authenticated+// message before dispatch.+func (s *Server) isCurrentSession(sess *session) bool {+ authenticated := sess.authenticated+ if authenticated == nil {+ return false+ }+ var current room.ConnectedPeer+ var ok bool+ if authenticated.role == protocol.RoleHost {+ current, ok = s.store.GetConnectedHost(authenticated.roomID)+ } else {+ current, ok = s.store.GetConnectedViewer(authenticated.roomID, authenticated.peerID)+ }+ return ok && current.SessionID == sess.sessionID+}++// connectedPeer ports connectedPeer.+func (s *Server) connectedPeer(roomID, peerID string) (room.ConnectedPeer, bool) {+ if host, ok := s.store.GetConnectedHost(roomID); ok && host.PeerID == peerID {+ return host, true+ }+ return s.store.GetConnectedViewer(roomID, peerID)+}++// ---------------------------------------------------------------------------+// error tables+// ---------------------------------------------------------------------------++// authenticationErrorMessage ports authenticationErrorMessage.+func authenticationErrorMessage(code string) string {+ switch code {+ case "ROOM_ACCESS_DENIED":+ return "Room access denied"+ case "ROOM_NOT_FOUND":+ return "Room not found or expired"+ case "ROOM_EXPIRED":+ return "Room has expired"+ case "ROOM_FULL":+ return "Room is full"+ case "HOST_ALREADY_CONNECTED":+ return "A host is already connected"+ case "INVALID_TOKEN":+ return "Room is invalid or expired"+ }+ return "Authentication failed"+}++// authenticationErrorCode ports authenticationErrorCode verbatim.+func authenticationErrorCode(request authRequest, err error) string {+ var roomError *room.Error+ if !errors.As(err, &roomError) || roomError.Code == room.CodeRoomLimit {+ return "SERVER_ERROR"+ }+ if roomError.Code == room.CodeRoomBusy {+ if request.role == protocol.RoleViewer {+ return "ROOM_ACCESS_DENIED"+ }+ return "SERVER_ERROR"+ }+ if request.role != protocol.RoleViewer {+ return string(roomError.Code)+ }+ if request.viewerGrant == "" {+ if roomError.Code == room.CodeRoomNotFound || roomError.Code == room.CodeRoomExpired {+ return "ROOM_NOT_FOUND"+ }+ return "ROOM_ACCESS_DENIED"+ }+ if roomError.Code == room.CodeRoomExpired || roomError.Code == room.CodeRoomNotFound {+ return "INVALID_TOKEN"+ }+ return string(roomError.Code)+}diff --git a/internal/server/signal/server_test.go b/internal/server/signal/server_test.gonew file mode 100644index 00000000..f3d91a57--- /dev/null+++ b/internal/server/signal/server_test.go@@ -0,0 +1,2773 @@+package signal++// Ported from tests/server-signal.test.ts (baseline b20fd88): the 43 cases+// of describe("WebSocket signaling"). The harness mirrors startHarness: a+// memory room.Store, short timer options (authentication 500 ms, viewer+// grace 50 ms, heartbeat disabled at 60 s), an httptest.Server whose every+// request reaches Server.ServeHTTP, real coder/websocket clients and a+// MessageInbox port. Room access updates call the server directly where the+// TS went through HTTP; the site-access cookie is a stub predicate.++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net"+ "net/http"+ "net/http/httptest"+ "net/url"+ "path/filepath"+ "reflect"+ "runtime"+ "slices"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/coder/websocket"++ "github.com/TNTcraftHIM/Screener/internal/server/config"+ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+ "github.com/TNTcraftHIM/Screener/internal/server/room"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu"+ "github.com/TNTcraftHIM/Screener/internal/server/sfu/sfutest"+)++const (+ allowedOrigin = "http://allowed.test"+ siteAccessCookie = "screener-site-access=granted"+ defaultWait = 2 * time.Second+)++func TestCreateRoomReleasesLockWhenDerivationOrCommitPanics(t *testing.T) {+ for _, password := range []string{"", "room-password"} {+ t.Run(password, func(t *testing.T) {+ store, err := room.New(room.Options{+ LeaseMs: 86_400_000, MaxRooms: 1, MaxViewersPerRoom: 1,+ Random: func(int) []byte { panic("test random source") },+ })+ if err != nil {+ t.Fatal(err)+ }+ server := &Server{store: store}+ func() {+ defer func() {+ if value := recover(); value != "test random source" {+ t.Errorf("panic = %v, want original random-source panic", value)+ }+ }()+ _, _ = server.CreateRoom(protocol.CodeEntryOpen, &password, "")+ }()+ if !server.mu.TryLock() {+ t.Fatal("CreateRoom left the server locked after a recovered panic")+ }+ server.mu.Unlock()+ })+ }+}++// ---------------------------------------------------------------------------+// harness+// ---------------------------------------------------------------------------++type harnessOptions struct {+ authenticationTimeoutMs int+ viewerDisconnectGraceMs int+ maxViewersPerRoom int+ maxSignalConnections int+ maxUnauthenticatedSignalConnections int+ siteAccessPassword string+ endpointMediaCopyCapacity int+ stunURLs []string+ natPredictionEnabled bool+ now func() int64+ cleanupIntervalMs int+ store *room.Store+ room *room.CreatedRoom+ afterFunc func(time.Duration, func()) func() bool+ sfu *SfuFallback+}++type harness struct {+ t *testing.T+ server *Server+ http *httptest.Server+ store *room.Store+ room room.CreatedRoom+ wsURL string+ closed bool+}++func orValue(value, fallback int) int {+ if value == 0 {+ return fallback+ }+ return value+}++func newStore(t *testing.T, maxViewersPerRoom int, now func() int64, database *room.Database) *room.Store {+ t.Helper()+ store, err := room.New(room.Options{+ LeaseMs: 86_400_000,+ MaxRooms: room.Capacity,+ MaxViewersPerRoom: maxViewersPerRoom,+ Now: now,+ Database: database,+ })+ if err != nil {+ t.Fatalf("room.New: %v", err)+ }+ if database != nil {+ if err := store.Initialize(); err != nil {+ t.Fatalf("store.Initialize: %v", err)+ }+ }+ return store+}++// createStoreRoom is roomStore.createRoom() on a store no server guards yet.+func createStoreRoom(t *testing.T, store *room.Store, policy protocol.CodeEntryPolicy, password string) room.CreatedRoom {+ t.Helper()+ lease, err := store.BeginCreateRoom()+ if err != nil {+ t.Fatalf("BeginCreateRoom: %v", err)+ }+ var material []byte+ var derived error+ if password != "" {+ material, derived = store.DeriveViewerPasswordMaterial(password, nil)+ }+ created, err := store.CreateRoom(policy, material, derived, "", lease)+ if err != nil {+ t.Fatalf("CreateRoom: %v", err)+ }+ return created+}++func startHarness(t *testing.T, options harnessOptions) *harness {+ t.Helper()+ maxViewersPerRoom := orValue(options.maxViewersPerRoom, 8)+ store := options.store+ if store == nil {+ store = newStore(t, maxViewersPerRoom, options.now, nil)+ }+ var created room.CreatedRoom+ if options.room != nil {+ created = *options.room+ } else {+ created = createStoreRoom(t, store, protocol.CodeEntryOpen, "")+ }+ publicBaseURL, err := url.Parse("https://share.example.test")+ if err != nil {+ t.Fatal(err)+ }+ server, err := New(Options{+ Store: store,+ EndpointMediaCopyCapacity: orValue(options.endpointMediaCopyCapacity, 2),+ SfuFallback: options.sfu,+ Ice: config.IceConfig(config.Config{+ STUNURLs: options.stunURLs,+ NATPredictionEnabled: options.natPredictionEnabled,+ }),+ NATPredictionEnabled: options.natPredictionEnabled,+ AllowedOrigins: map[string]struct{}{allowedOrigin: {}},+ SiteAccessAtUpgrade: func(request *http.Request) bool {+ return options.siteAccessPassword == "" ||+ strings.Contains(request.Header.Get("Cookie"), siteAccessCookie)+ },+ PublicBaseURL: publicBaseURL,+ Now: options.now,+ AuthenticationTimeoutMs: orValue(options.authenticationTimeoutMs, 500),+ ViewerDisconnectGraceMs: orValue(options.viewerDisconnectGraceMs, 50),+ HeartbeatIntervalMs: 60_000,+ CleanupIntervalMs: orValue(options.cleanupIntervalMs, 60_000),+ MaxConnections: options.maxSignalConnections,+ MaxUnauthenticatedConnections: options.maxUnauthenticatedSignalConnections,+ AfterFunc: options.afterFunc,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ if err != nil {+ t.Fatalf("signal.New: %v", err)+ }+ httpServer := httptest.NewServer(server)+ h := &harness{+ t: t,+ server: server,+ http: httpServer,+ store: store,+ room: created,+ wsURL: "ws" + strings.TrimPrefix(httpServer.URL, "http") + "/signal",+ }+ t.Cleanup(h.close)+ return h+}++// close is runningServer.close(): the signaling server first, then the+// listener and the store. It is idempotent so tests may close early.+func (h *harness) close() {+ if h.closed {+ return+ }+ h.closed = true+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ if err := h.server.Close(ctx); err != nil {+ h.t.Errorf("server.Close: %v", err)+ }+ h.http.Close()+ if err := h.store.Close(); err != nil {+ h.t.Errorf("store.Close: %v", err)+ }+}++// locked runs fn under the server's mutex, which is how a test may touch the+// store while the server runs (the TS store was shared on one thread).+func (h *harness) locked(fn func()) {+ h.server.mu.Lock()+ defer h.server.mu.Unlock()+ fn()+}++func (h *harness) sessionCount() int {+ var count int+ h.locked(func() { count = h.server.sessions.Len() })+ return count+}++func (h *harness) storeSize() int {+ var size int+ h.locked(func() { size = h.store.Size() })+ return size+}++func (h *harness) updateRoomAccess(request protocol.RoomAccessUpdateRequest) protocol.RoomAccessUpdateResponse {+ h.t.Helper()+ response, err := h.server.UpdateRoomAccess(h.room.RoomID, h.room.HostToken, request)+ if err != nil {+ h.t.Fatalf("UpdateRoomAccess: %v", err)+ }+ return response+}++func (h *harness) createRoom(policy protocol.CodeEntryPolicy, password string) room.CreatedRoom {+ h.t.Helper()+ var roomPassword *string+ if password != "" {+ roomPassword = &password+ }+ created, err := h.server.CreateRoom(policy, roomPassword, "")+ if err != nil {+ h.t.Fatalf("CreateRoom: %v", err)+ }+ return created+}++func waitFor(t *testing.T, timeout time.Duration, condition func() bool) bool {+ t.Helper()+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ if condition() {+ return true+ }+ time.Sleep(5 * time.Millisecond)+ }+ return condition()+}++// expectGoroutinesSettled is the close tests' stand-in for the race detector+// (unavailable without cgo): every goroutine the server started (readers,+// writers, pings, pump drivers, drains, timer callbacks) must have exited,+// so the count returns to what it was before the harness started.+func expectGoroutinesSettled(t *testing.T, before int) {+ t.Helper()+ if waitFor(t, defaultWait, func() bool { return runtime.NumGoroutine() <= before }) {+ return+ }+ stacks := make([]byte, 1<<20)+ t.Fatalf("goroutines: %d before, %d after close\n%s",+ before, runtime.NumGoroutine(), stacks[:runtime.Stack(stacks, true)])+}++// ---------------------------------------------------------------------------+// client+// ---------------------------------------------------------------------------++type inbound struct {+ typ string+ raw []byte+}++type closeEvent struct {+ code int+ reason string+}++// testClient is MessageInbox plus the socket.+type testClient struct {+ t *testing.T+ conn *websocket.Conn++ mu sync.Mutex+ messages []inbound+ ignored map[string]bool+ decodeErrors []string+ notify chan struct{}+ closed chan closeEvent+}++func dialClient(t *testing.T, wsURL, origin, cookie string) (*websocket.Conn, *http.Response, error) {+ t.Helper()+ header := http.Header{}+ header.Set("Origin", origin)+ if cookie != "" {+ header.Set("Cookie", cookie)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ return websocket.Dial(ctx, wsURL, &websocket.DialOptions{HTTPHeader: header})+}++func openClient(t *testing.T, h *harness) *testClient {+ t.Helper()+ return openClientWithCookie(t, h, "")+}++func openClientWithCookie(t *testing.T, h *harness, cookie string) *testClient {+ t.Helper()+ conn, _, err := dialClient(t, h.wsURL, allowedOrigin, cookie)+ if err != nil {+ t.Fatalf("websocket.Dial: %v", err)+ }+ return newTestClient(t, conn)+}++func newTestClient(t *testing.T, conn *websocket.Conn) *testClient {+ t.Helper()+ conn.SetReadLimit(1 << 20)+ client := &testClient{+ t: t,+ conn: conn,+ ignored: map[string]bool{},+ notify: make(chan struct{}, 1),+ closed: make(chan closeEvent, 1),+ }+ go client.readLoop()+ t.Cleanup(func() {+ client.mu.Lock()+ defer client.mu.Unlock()+ for _, failure := range client.decodeErrors {+ t.Error(failure)+ }+ })+ return client+}++func (c *testClient) readLoop() {+ for {+ _, data, err := c.conn.Read(context.Background())+ if err != nil {+ event := closeEvent{code: -1, reason: err.Error()}+ var closeError websocket.CloseError+ if errors.As(err, &closeError) {+ event = closeEvent{code: int(closeError.Code), reason: closeError.Reason}+ }+ c.closed <- event+ return+ }+ var probe struct {+ Type string `json:"type"`+ }+ _ = json.Unmarshal(data, &probe)+ c.mu.Lock()+ // TS: decodeServerMessage(data) validates every server message.+ if _, err := protocol.DecodeServerMessage(data); err != nil {+ c.decodeErrors = append(c.decodeErrors,+ fmt.Sprintf("server message %q failed the wire schema: %v", probe.Type, err))+ }+ if !c.ignored[probe.Type] {+ c.messages = append(c.messages, inbound{typ: probe.Type, raw: data})+ }+ c.mu.Unlock()+ select {+ case c.notify <- struct{}{}:+ default:+ }+ }+}++func (c *testClient) sendText(text string) {+ c.t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ if err := c.conn.Write(ctx, websocket.MessageText, []byte(text)); err != nil {+ c.t.Fatalf("write: %v", err)+ }+}++func (c *testClient) sendJSON(message map[string]any) {+ c.t.Helper()+ encoded, err := json.Marshal(message)+ if err != nil {+ c.t.Fatal(err)+ }+ c.sendText(string(encoded))+}++func (c *testClient) tryNext(typ string, timeout time.Duration) (inbound, bool) {+ deadline := time.Now().Add(timeout)+ for {+ c.mu.Lock()+ for index, message := range c.messages {+ if message.typ == typ {+ c.messages = slices.Delete(c.messages, index, index+1)+ c.mu.Unlock()+ return message, true+ }+ }+ c.mu.Unlock()+ remaining := time.Until(deadline)+ if remaining <= 0 {+ return inbound{}, false+ }+ select {+ case <-c.notify:+ case <-time.After(remaining):+ }+ }+}++// next is inbox.next(type): the first buffered message of that type, or the+// next one to arrive.+func (c *testClient) next(typ string) inbound {+ c.t.Helper()+ return c.nextWithin(typ, defaultWait)+}++func (c *testClient) nextWithin(typ string, timeout time.Duration) inbound {+ c.t.Helper()+ message, ok := c.tryNext(typ, timeout)+ if !ok {+ c.t.Fatalf("Timed out waiting for %s", typ)+ }+ return message+}++// expectNone is inbox.expectNone(timeoutMs).+func (c *testClient) expectNone(timeout time.Duration) {+ c.t.Helper()+ check := func() {+ c.mu.Lock()+ defer c.mu.Unlock()+ if len(c.messages) > 0 {+ c.t.Fatalf("Unexpected message: %s", c.messages[0].typ)+ }+ }+ check()+ time.Sleep(timeout)+ check()+}++// ignore is inbox.ignore(type).+func (c *testClient) ignore(typ string) {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.ignored[typ] = true+ c.messages = slices.DeleteFunc(c.messages, func(message inbound) bool { return message.typ == typ })+}++// closeCode waits for the socket's close event.+func (c *testClient) closeCode() closeEvent {+ c.t.Helper()+ select {+ case event := <-c.closed:+ c.closed <- event+ return event+ case <-time.After(defaultWait):+ c.t.Fatalf("Timed out waiting for the socket to close")+ return closeEvent{}+ }+}++func (c *testClient) isClosed() bool {+ select {+ case event := <-c.closed:+ c.closed <- event+ return true+ default:+ return false+ }+}++// closeClient is closeClient(): a client-initiated close that also waits+// for the server to have run handleDisconnect, which the single-threaded TS+// tests sequenced through later messages.+func (h *harness) closeClient(c *testClient) {+ h.t.Helper()+ if c.isClosed() {+ return+ }+ before := h.sessionCount()+ _ = c.conn.Close(websocket.StatusNormalClosure, "")+ c.closeCode()+ if !waitFor(h.t, defaultWait, func() bool { return h.sessionCount() < before }) {+ h.t.Fatalf("server did not release the closed session")+ }+}++func rejectedUpgradeStatus(t *testing.T, h *harness, origin string) int {+ t.Helper()+ conn, response, err := dialClient(t, h.wsURL, origin, "")+ if err == nil {+ _ = conn.CloseNow()+ t.Fatalf("WebSocket upgrade unexpectedly succeeded")+ }+ if response == nil {+ t.Fatalf("upgrade failed without an HTTP response: %v", err)+ }+ return response.StatusCode+}++func rawUpgradeResponse(t *testing.T, h *harness, requestTarget string) string {+ t.Helper()+ parsed, err := url.Parse(h.wsURL)+ if err != nil {+ t.Fatal(err)+ }+ conn, err := net.DialTimeout("tcp", parsed.Host, 2*time.Second)+ if err != nil {+ t.Fatalf("dial: %v", err)+ }+ defer conn.Close()+ _ = conn.SetDeadline(time.Now().Add(2 * time.Second))+ request := strings.Join([]string{+ "GET " + requestTarget + " HTTP/1.1",+ "Host: " + parsed.Host,+ "Upgrade: websocket",+ "Connection: Upgrade",+ "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==",+ "Sec-WebSocket-Version: 13",+ "Origin: " + allowedOrigin,+ "",+ "",+ }, "\r\n")+ if _, err := conn.Write([]byte(request)); err != nil {+ t.Fatalf("write: %v", err)+ }+ response, _ := io.ReadAll(conn)+ return string(response)+}++// ---------------------------------------------------------------------------+// JSON assertions (expect(...).toEqual / toMatchObject on decoded JSON)+// ---------------------------------------------------------------------------++func jsonValue(t *testing.T, raw []byte) any {+ t.Helper()+ var value any+ if err := json.Unmarshal(raw, &value); err != nil {+ t.Fatalf("invalid JSON %s: %v", raw, err)+ }+ return value+}++func jsonObject(t *testing.T, raw []byte) map[string]any {+ t.Helper()+ object, ok := jsonValue(t, raw).(map[string]any)+ if !ok {+ t.Fatalf("expected a JSON object, got %s", raw)+ }+ return object+}++// matches is toMatchObject: objects are subset-matched recursively, arrays+// must have equal length with matching elements, scalars must be equal.+func matches(actual, expected any) bool {+ switch expected := expected.(type) {+ case map[string]any:+ actualObject, ok := actual.(map[string]any)+ if !ok {+ return false+ }+ for key, value := range expected {+ actualValue, present := actualObject[key]+ if !present || !matches(actualValue, value) {+ return false+ }+ }+ return true+ case []any:+ actualList, ok := actual.([]any)+ if !ok || len(actualList) != len(expected) {+ return false+ }+ for index := range expected {+ if !matches(actualList[index], expected[index]) {+ return false+ }+ }+ return true+ }+ return reflect.DeepEqual(actual, expected)+}++func expectEqual(t *testing.T, raw []byte, expected string) {+ t.Helper()+ if !reflect.DeepEqual(jsonValue(t, raw), jsonValue(t, []byte(expected))) {+ t.Fatalf("expected exactly %s\ngot %s", expected, raw)+ }+}++func expectMatch(t *testing.T, raw []byte, expected string) {+ t.Helper()+ if !matches(jsonValue(t, raw), jsonValue(t, []byte(expected))) {+ t.Fatalf("expected a match of %s\ngot %s", expected, raw)+ }+}++func hasKey(t *testing.T, raw []byte, key string) bool {+ t.Helper()+ _, present := jsonObject(t, raw)[key]+ return present+}++// ---------------------------------------------------------------------------+// typed views of the messages the tests inspect+// ---------------------------------------------------------------------------++type authenticatedMessage struct {+ PeerID string `json:"peerId"`+ HostOnline bool `json:"hostOnline"`+ HostPaused *bool `json:"hostPaused"`+ ConnectionID *string `json:"connectionId"`+ RoutePolicy protocol.RoutePolicy `json:"routePolicy"`+ RouteRevision int64 `json:"routeRevision"`+ RouteAssignment struct {+ Upstream protocol.MediaRouteUpstream `json:"upstream"`+ } `json:"routeAssignment"`+ QualitySettings json.RawMessage `json:"qualitySettings"`+ ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`+ MaxViewers int `json:"maxViewers"`+ ShareGeneration *string `json:"shareGeneration"`+ Role string `json:"role"`+ CodeEntryPolicy string `json:"codeEntryPolicy"`+ IceConfig json.RawMessage `json:"iceConfig"`+ raw []byte+}++func parseAuthenticated(t *testing.T, raw []byte) authenticatedMessage {+ t.Helper()+ var message authenticatedMessage+ if err := json.Unmarshal(raw, &message); err != nil {+ t.Fatalf("authenticated: %v (%s)", err, raw)+ }+ message.raw = raw+ return message+}++type routeUpdate struct {+ Revision int64 `json:"revision"`+ Phase string `json:"phase"`+ Assignment struct {+ Upstream protocol.MediaRouteUpstream `json:"upstream"`+ ChildPeerIDs []string `json:"childPeerIds"`+ } `json:"assignment"`+ Candidate struct {+ ChildPeerID string `json:"childPeerId"`+ ConnectionID string `json:"connectionId"`+ Transport string `json:"transport"`+ QualityProbe bool `json:"qualityProbe"`+ } `json:"candidate"`+ raw []byte+}++func parseRouteUpdate(t *testing.T, raw []byte) routeUpdate {+ t.Helper()+ var message routeUpdate+ if err := json.Unmarshal(raw, &message); err != nil {+ t.Fatalf("route-update: %v (%s)", err, raw)+ }+ message.raw = raw+ return message+}++type presenceEntry struct {+ Role string `json:"role"`+ PeerID string `json:"peerId"`+ DisplayName string `json:"displayName"`+ Upstream protocol.MediaRouteUpstream `json:"upstream"`+ MediaReady *bool `json:"mediaReady,omitempty"`+}++type presenceMessage struct {+ Viewers []presenceEntry `json:"viewers"`+ raw []byte+}++func parsePresence(t *testing.T, raw []byte) presenceMessage {+ t.Helper()+ var message presenceMessage+ if err := json.Unmarshal(raw, &message); err != nil {+ t.Fatalf("viewer-presence: %v (%s)", err, raw)+ }+ message.raw = raw+ return message+}++func viewerPresenceEntries(message presenceMessage) []presenceEntry {+ var viewers []presenceEntry+ for _, entry := range message.Viewers {+ if entry.Role == protocol.RoleViewer {+ viewers = append(viewers, entry)+ }+ }+ return viewers+}++// viewerEntriesJSON re-encodes viewerPresenceEntries(message) so the TS+// assertions on that filtered list can use the JSON matchers.+func viewerEntriesJSON(t *testing.T, message presenceMessage) []byte {+ t.Helper()+ entries := viewerPresenceEntries(message)+ if entries == nil {+ entries = []presenceEntry{}+ }+ encoded, err := json.Marshal(entries)+ if err != nil {+ t.Fatal(err)+ }+ return encoded+}++func hostPresenceEntry(message presenceMessage) *presenceEntry {+ for _, entry := range message.Viewers {+ if entry.Role == protocol.RoleHost {+ return &entry+ }+ }+ return nil+}++func displayNames(entries []presenceEntry) []string {+ names := []string{}+ for _, entry := range entries {+ names = append(names, entry.DisplayName)+ }+ return names+}++func peerIDs(entries []presenceEntry) []string {+ ids := []string{}+ for _, entry := range entries {+ ids = append(ids, entry.PeerID)+ }+ return ids+}++func isMediaReady(entry presenceEntry) bool {+ return entry.MediaReady != nil && *entry.MediaReady+}++// ---------------------------------------------------------------------------+// protocol helpers (authenticate, routes, presence, evidence)+// ---------------------------------------------------------------------------++type presenceOptions struct {+ displayName string+ viewerPresence bool+ viewerPassword string+ codeOnly bool+ sharingPaused *bool+ qualitySettings map[string]any+ routePolicy *protocol.RoutePolicy+}++// authenticate ports the authenticate() helper. relayCapacity -1 is the TS+// null (no relay-capacity message after the authenticated reply).+func authenticate(+ t *testing.T,+ client *testClient,+ rm room.CreatedRoom,+ role protocol.Role,+ clientID string,+ relayCapacity int,+ shareGeneration string,+ presence presenceOptions,+) authenticatedMessage {+ t.Helper()+ message := map[string]any{+ "type": "authenticate",+ "protocol": protocol.SignalingProtocol,+ "roomId": rm.RoomID,+ "role": role,+ "clientId": clientID,+ }+ if role == protocol.RoleHost {+ message["token"] = rm.HostToken+ if shareGeneration != "" {+ message["shareGeneration"] = shareGeneration+ }+ if presence.sharingPaused != nil {+ message["sharingPaused"] = *presence.sharingPaused+ }+ if presence.qualitySettings != nil {+ message["qualitySettings"] = presence.qualitySettings+ }+ if presence.routePolicy != nil {+ message["routePolicy"] = *presence.routePolicy+ }+ if presence.viewerPresence {+ message["viewerPresence"] = true+ }+ if presence.displayName != "" {+ message["displayName"] = presence.displayName+ }+ } else {+ if presence.viewerPassword != "" {+ message["viewerPassword"] = presence.viewerPassword+ } else if !presence.codeOnly && rm.ViewerGrant != "" {+ message["viewerGrant"] = rm.ViewerGrant+ }+ if presence.displayName != "" {+ message["displayName"] = presence.displayName+ }+ if presence.viewerPresence {+ message["viewerPresence"] = true+ }+ }+ client.sendJSON(message)+ authenticated := parseAuthenticated(t, client.next("authenticated").raw)+ if role == protocol.RoleViewer && relayCapacity >= 0 {+ client.sendJSON(map[string]any{"type": "relay-capacity", "downstreamEdges": relayCapacity})+ }+ return authenticated+}++func boolPointer(value bool) *bool { return &value }++func nextPreparedRoute(t *testing.T, client *testClient) routeUpdate {+ t.Helper()+ for {+ message := parseRouteUpdate(t, client.next("route-update").raw)+ if message.Phase == "prepare" {+ return message+ }+ }+}++func nextActiveRouteRevision(t *testing.T, client *testClient, revision int64) routeUpdate {+ t.Helper()+ for {+ message := parseRouteUpdate(t, client.next("route-update").raw)+ if message.Phase == "active" && message.Revision == revision {+ return message+ }+ }+}++func nextActiveRouteAfter(t *testing.T, client *testClient, revision int64) routeUpdate {+ t.Helper()+ for {+ message := parseRouteUpdate(t, client.next("route-update").raw)+ if message.Phase == "active" && message.Revision > revision {+ return message+ }+ }+}++func commitPreparedRoute(t *testing.T, client *testClient) routeUpdate {+ t.Helper()+ prepared := nextPreparedRoute(t, client)+ client.sendJSON(map[string]any{+ "type": "route-transport-connected",+ "revision": prepared.Revision,+ "connectionId": prepared.Candidate.ConnectionID,+ })+ client.sendJSON(map[string]any{+ "type": "route-ready",+ "revision": prepared.Revision,+ "phase": "prepare",+ })+ return nextActiveRouteRevision(t, client, prepared.Revision)+}++func nextViewerPresenceMatching(t *testing.T, client *testClient, predicate func(presenceMessage) bool) presenceMessage {+ t.Helper()+ for attempt := 0; attempt < 20; attempt++ {+ message := parsePresence(t, client.next("viewer-presence").raw)+ if predicate(message) {+ return message+ }+ }+ t.Fatalf("Viewer presence did not reach the expected state")+ return presenceMessage{}+}++func expectNoViewerPresenceMatching(t *testing.T, client *testClient, predicate func(presenceMessage) bool, timeout time.Duration) {+ t.Helper()+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ message, ok := client.tryNext("viewer-presence", time.Until(deadline))+ if !ok {+ return+ }+ if predicate(parsePresence(t, message.raw)) {+ t.Fatalf("Viewer presence reached a forbidden state: %s", message.raw)+ }+ }+}++func viewerQualityEvidenceMessage(connectionID string, routeRevision, sequence, presentationEpoch int64) map[string]any {+ return map[string]any{+ "type": "viewer-quality-evidence",+ "guard": map[string]any{+ "connectionId": connectionID,+ "routeRevision": routeRevision,+ "presentationEpoch": presentationEpoch,+ },+ "sequence": sequence,+ "windowMs": 2_000,+ "metrics": map[string]any{+ "natTraversalPath": "ordinary",+ "width": 1_920,+ "height": 1_080,+ "framesPerSecond": 60,+ "bitrateKbps": 7_500,+ "packetsReceivedDelta": 1_500,+ "packetsLostDelta": 2,+ "rttMs": 18,+ "jitterMs": 3.5,+ "framesDecodedDelta": 120,+ "framesDroppedDelta": 1,+ "decodeMsPerFrame": 2.4,+ "freezeCountDelta": 0,+ "freezeDurationMsDelta": 0,+ "pauseCountDelta": 0,+ "pauseDurationMsDelta": 0,+ "codec": "video/VP8",+ "codecProfile": nil,+ "codecParameters": nil,+ "audioBitrateKbps": 192,+ "audioPacketLossPercent": 0.2,+ "audioJitterMs": 2.5,+ "audioVideoPlayoutDeltaMs": -12.5,+ "videoJitterBufferDelayMs": 24,+ "audioJitterBufferDelayMs": 18,+ "audioConcealedSamplesPercent": 1,+ "audioConcealmentEventsDelta": 3,+ "audioCodec": "audio/opus",+ },+ }+}++func signalDescription(targetPeerID, connectionID, descriptionType string) map[string]any {+ return map[string]any{+ "type": "signal",+ "targetPeerId": targetPeerID,+ "payload": map[string]any{+ "kind": "description",+ "connectionId": connectionID,+ "description": map[string]any{"type": descriptionType, "sdp": "v=0\r\n"},+ },+ }+}++func signalCandidate(targetPeerID, connectionID string) map[string]any {+ return map[string]any{+ "type": "signal",+ "targetPeerId": targetPeerID,+ "payload": map[string]any{+ "kind": "candidate",+ "connectionId": connectionID,+ "candidate": nil,+ },+ }+}++func utcMillis(year int, month time.Month, day, hour int) int64 {+ return time.Date(year, month, day, hour, 0, 0, 0, time.UTC).UnixMilli()+}++type clock struct{ ms atomic.Int64 }++func newClock(start int64) *clock {+ c := &clock{}+ c.ms.Store(start)+ return c+}++func (c *clock) now() int64 { return c.ms.Load() }+func (c *clock) advance(deltaMs int64) { c.ms.Add(deltaMs) }++func expectClose(t *testing.T, client *testClient, code int, reason string) {+ t.Helper()+ event := client.closeCode()+ if event.code != code || event.reason != reason {+ t.Fatalf("expected close {%d %q}, got {%d %q}", code, reason, event.code, event.reason)+ }+}++func expectCloseCode(t *testing.T, client *testClient, code int) {+ t.Helper()+ if event := client.closeCode(); event.code != code {+ t.Fatalf("expected close code %d, got {%d %q}", code, event.code, event.reason)+ }+}++func expectString(t *testing.T, name, actual, expected string) {+ t.Helper()+ if actual != expected {+ t.Fatalf("%s: expected %q, got %q", name, expected, actual)+ }+}++func expectStrings(t *testing.T, name string, actual, expected []string) {+ t.Helper()+ if !slices.Equal(actual, expected) {+ t.Fatalf("%s: expected %q, got %q", name, expected, actual)+ }+}++func expectTrue(t *testing.T, name string, condition bool) {+ t.Helper()+ if !condition {+ t.Fatalf("%s", name)+ }+}++// ---------------------------------------------------------------------------+// route policy and ICE+// ---------------------------------------------------------------------------++func TestSignalEchoesExactPerShareRoutePolicyAuthority(t *testing.T) {+ h := startHarness(t, harnessOptions{+ stunURLs: []string{"stun:share.example.test:3478"},+ natPredictionEnabled: true,+ })+ viewer := openClient(t, h)+ waiting := authenticate(t, viewer, h.room, protocol.RoleViewer, "route-policy-viewer", 1, "", presenceOptions{})+ expectTrue(t, "waiting shareGeneration must be null", waiting.ShareGeneration == nil)+ host := openClient(t, h)+ routePolicy := protocol.RoutePolicy{PeerOnly: true, TopologyOptimization: true, NatPrediction: true}+ authenticated := authenticate(t, host, h.room, protocol.RoleHost, "route-policy-host", 1,+ "route_policy_share_generation_12345678", presenceOptions{routePolicy: &routePolicy})+ if authenticated.RoutePolicy != routePolicy {+ t.Fatalf("routePolicy: %+v", authenticated.RoutePolicy)+ }+ expectTrue(t, "sfuStandbyUrl must be absent", !hasKey(t, authenticated.raw, "sfuStandbyUrl"))+ expectEqual(t, viewer.next("route-policy").raw,+ `{"type":"route-policy","shareGeneration":"route_policy_share_generation_12345678","routePolicy":{"peerOnly":true,"topologyOptimization":true,"natPrediction":true}}`)+}++func TestSignalBroadcastsConfiguredNatPredictionInLightweightRooms(t *testing.T) {+ h := startHarness(t, harnessOptions{+ stunURLs: []string{"stun:share.example.test:3478"},+ natPredictionEnabled: true,+ })+ waitingViewer := openClient(t, h)+ waiting := authenticate(t, waitingViewer, h.room, protocol.RoleViewer, "ordinary-nat-waiting-viewer", -1, "", presenceOptions{})+ expectTrue(t, "waiting natPrediction must be false", !waiting.RoutePolicy.NatPrediction)++ host := openClient(t, h)+ routePolicy := protocol.DefaultRoutePolicy+ routePolicy.NatPrediction = true+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "ordinary-nat-host", -1,+ "ordinary_nat_share_generation_12345678", presenceOptions{routePolicy: &routePolicy})+ if hostAuth.RoutePolicy != routePolicy {+ t.Fatalf("routePolicy: %+v", hostAuth.RoutePolicy)+ }+ expectMatch(t, waitingViewer.next("route-policy").raw,+ `{"routePolicy":{"peerOnly":false,"topologyOptimization":true,"natPrediction":true}}`)++ joiningViewer := openClient(t, h)+ joined := authenticate(t, joiningViewer, h.room, protocol.RoleViewer, "ordinary-nat-joining-viewer", -1, "", presenceOptions{})+ if joined.RoutePolicy != routePolicy {+ t.Fatalf("joined routePolicy: %+v", joined.RoutePolicy)+ }+}++func TestSignalClampsNatPredictionOffWhenServerCapabilityIsDisabled(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ routePolicy := protocol.DefaultRoutePolicy+ routePolicy.NatPrediction = true+ authenticated := authenticate(t, host, h.room, protocol.RoleHost, "disabled-nat-host", -1,+ "disabled_nat_share_generation_12345678", presenceOptions{routePolicy: &routePolicy})+ expectTrue(t, "natPrediction must be clamped off", !authenticated.RoutePolicy.NatPrediction)+}++func TestSignalDeliversOnlySelfHostedAuxiliaryNatStunEndpoints(t *testing.T) {+ h := startHarness(t, harnessOptions{+ stunURLs: []string{"stun:ordinary.example.test:3478"},+ natPredictionEnabled: true,+ })+ viewer := openClient(t, h)+ authenticated := authenticate(t, viewer, h.room, protocol.RoleViewer, "nat-auxiliary-viewer", -1, "", presenceOptions{})+ expectEqual(t, authenticated.IceConfig,+ `{"iceServers":[{"urls":["stun:ordinary.example.test:3478"]}],"natPredictionStunUrls":["stun:ordinary.example.test:3479","stun:ordinary.example.test:3480"]}`)+}++// ---------------------------------------------------------------------------+// lifecycle and restart+// ---------------------------------------------------------------------------++func TestSignalRebuildsRouteWhenViewerReconnectsBeforeHostAfterRestart(t *testing.T) {+ path := filepath.Join(t.TempDir(), "rooms.sqlite")+ firstDatabase, err := room.NewDatabase(path)+ if err != nil {+ t.Fatal(err)+ }+ firstStore := newStore(t, 8, nil, firstDatabase)+ rm := createStoreRoom(t, firstStore, protocol.CodeEntryOpen, "")+ first := startHarness(t, harnessOptions{store: firstStore, room: &rm})+ firstHost := openClient(t, first)+ authenticate(t, firstHost, rm, protocol.RoleHost, "restart-route-host", 1, "restart_share_generation_12345678", presenceOptions{})+ firstViewer := openClient(t, first)+ authenticate(t, firstViewer, rm, protocol.RoleViewer, "restart-route-viewer", 1, "", presenceOptions{})+ nextPreparedRoute(t, firstViewer)++ first.close()++ secondDatabase, err := room.NewDatabase(path)+ if err != nil {+ t.Fatal(err)+ }+ secondStore := newStore(t, 8, nil, secondDatabase)+ second := startHarness(t, harnessOptions{store: secondStore, room: &rm})+ secondViewer := openClient(t, second)+ viewerAuth := authenticate(t, secondViewer, rm, protocol.RoleViewer, "restart-route-viewer", 1, "", presenceOptions{})+ expectString(t, "viewer upstream", viewerAuth.RouteAssignment.Upstream.Kind, "none")++ secondHost := openClient(t, second)+ authenticate(t, secondHost, rm, protocol.RoleHost, "restart-route-host", 1, "restart_share_generation_12345678", presenceOptions{})+ viewerPrepare := nextPreparedRoute(t, secondViewer)+ hostPrepare := nextPreparedRoute(t, secondHost)+ if viewerPrepare.Revision != hostPrepare.Revision || viewerPrepare.Candidate != hostPrepare.Candidate {+ t.Fatalf("viewer prepare %s\nhost prepare %s", viewerPrepare.raw, hostPrepare.raw)+ }+}++func TestSignalIdentifiesGracefulServiceRestartToConnectedClients(t *testing.T) {+ before := runtime.NumGoroutine()+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "restart-host", 1, "", presenceOptions{})++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ shutdown := make(chan error, 1)+ go func() { shutdown <- h.server.Close(ctx) }()++ expectClose(t, host, 1012, "Service restart")+ if err := <-shutdown; err != nil {+ t.Fatalf("Close: %v", err)+ }+ h.close()+ expectGoroutinesSettled(t, before)+}++// TS signaling.ts:251-256: forceCloseTimer terminates every client that has+// not finished the close handshake one second after close() began, however+// many there are; the library's own handshake timeout (5 s) never decides.+func TestSignalCloseTerminatesUnresponsiveClientsAfterOneSecondGrace(t *testing.T) {+ before := runtime.NumGoroutine()+ h := startHarness(t, harnessOptions{authenticationTimeoutMs: 60_000})+ var conns []*websocket.Conn+ for range 2 {+ // Never read: the close frame is never answered.+ conn, _, err := dialClient(t, h.wsURL, allowedOrigin, "")+ if err != nil {+ t.Fatalf("websocket.Dial: %v", err)+ }+ conns = append(conns, conn)+ }+ if !waitFor(t, defaultWait, func() bool { return h.sessionCount() == 2 }) {+ t.Fatalf("sessions = %d, want 2", h.sessionCount())+ }++ started := time.Now()+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := h.server.Close(ctx); err != nil {+ t.Fatalf("Close: %v", err)+ }+ if elapsed := time.Since(started); elapsed < serviceRestartCloseGrace || elapsed > 3*time.Second {+ t.Fatalf("Close took %v, want the one-second grace", elapsed)+ }+ for _, conn := range conns {+ _ = conn.CloseNow()+ }+ h.close()+ expectGoroutinesSettled(t, before)+}++func TestSignalEndsEveryRoomBeforeLocalAuthorityStops(t *testing.T) {+ before := runtime.NumGoroutine()+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "ending-host", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "ending-viewer", 1, "", presenceOptions{})++ // TS: server.end() = endAllRooms() then close().+ if err := h.server.EndAllRooms(); err != nil {+ t.Fatalf("EndAllRooms: %v", err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ shutdown := make(chan error, 1)+ go func() { shutdown <- h.server.Close(ctx) }()++ expectEqual(t, host.next("room-closed").raw, `{"type":"room-closed","reason":"host-ended"}`)+ expectEqual(t, viewer.next("room-closed").raw, `{"type":"room-closed","reason":"host-ended"}`)+ expectClose(t, host, 1000, "Room abandoned")+ expectClose(t, viewer, 1000, "Room abandoned")+ if err := <-shutdown; err != nil {+ t.Fatalf("Close: %v", err)+ }+ if size := h.storeSize(); size != 0 {+ t.Fatalf("store size %d", size)+ }+ h.close()+ expectGoroutinesSettled(t, before)+}++// ---------------------------------------------------------------------------+// challenge and diagnostics+// ---------------------------------------------------------------------------++func TestSignalAnswersOnlyOptedInCurrentSocketsAndRateLimitsEachSocket(t *testing.T) {+ now := newClock(time.Now().UnixMilli())+ h := startHarness(t, harnessOptions{now: now.now})+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "challenge-host", 1, "", presenceOptions{})+ nextActiveRouteRevision(t, host, hostAuth.RouteRevision)++ host.sendJSON(map[string]any{"type": "signaling-challenge", "sequence": 7})+ expectEqual(t, host.next("signaling-challenge-response").raw,+ `{"type":"signaling-challenge-response","sequence":7}`)++ host.sendJSON(map[string]any{"type": "signaling-challenge", "sequence": 8})+ host.expectNone(40 * time.Millisecond)++ now.advance(1_000)+ host.sendJSON(map[string]any{"type": "signaling-challenge", "sequence": 9})+ expectEqual(t, host.next("signaling-challenge-response").raw,+ `{"type":"signaling-challenge-response","sequence":9}`)+}++func TestSignalServesOneCurrentRouteSnapshotOnlyToAuthenticatedHost(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "route-diagnostic-host", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "route-diagnostic-viewer", 1, "", presenceOptions{})++ host.sendJSON(map[string]any{"type": "request-route-diagnostic"})+ expectMatch(t, host.next("route-diagnostic-snapshot").raw,+ `{"snapshot":{"children":[{"ordinal":1,"finalRoute":"waiting"}]}}`)++ viewer.sendJSON(map[string]any{"type": "request-route-diagnostic"})+ expectMatch(t, viewer.next("error").raw, `{"code":"FORBIDDEN"}`)+}++// ---------------------------------------------------------------------------+// native wire compatibility+// ---------------------------------------------------------------------------++func TestSignalKeepsExactNativeHostWireUnchangedWithoutPresenceOptIn(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "native-compatible-host", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "native-compatible-viewer", 1, "",+ presenceOptions{displayName: "移动观众"})+ hostPrepared := nextPreparedRoute(t, host)+ viewerActive := commitPreparedRoute(t, viewer)+ if hostPrepared.Revision != viewerActive.Revision {+ t.Fatalf("host prepare revision %d, viewer active revision %d", hostPrepared.Revision, viewerActive.Revision)+ }+ nextActiveRouteRevision(t, host, viewerActive.Revision)+ host.expectNone(40 * time.Millisecond)++ host.sendJSON(map[string]any{"type": "set-display-name", "displayName": "Native 不应改名"})+ expectMatch(t, host.next("error").raw, `{"code":"FORBIDDEN"}`)+ host.expectNone(40 * time.Millisecond)+}++// ---------------------------------------------------------------------------+// password and code entry+// ---------------------------------------------------------------------------++func sendPasswordAuthenticate(client *testClient, rm room.CreatedRoom, clientID, password string) {+ client.sendJSON(map[string]any{+ "type": "authenticate",+ "protocol": protocol.SignalingProtocol,+ "roomId": rm.RoomID,+ "role": protocol.RoleViewer,+ "clientId": clientID,+ "viewerPassword": password,+ })+}++func TestSignalKeepsPasswordOptionalForPrivateRoomEntry(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "password-settings-host", 1, "", presenceOptions{})++ updated := h.updateRoomAccess(protocol.SetCodeEntryPolicyRequest{Action: "set-code-entry-policy", Policy: protocol.CodeEntryPrivate})+ if !reflect.DeepEqual(updated, protocol.CodeEntryPolicyUpdatedResponse{+ Type: "code-entry-policy-updated", CodeEntryPolicy: protocol.CodeEntryPrivate, ViewerPasswordEnabled: false,+ }) {+ t.Fatalf("code entry update: %+v", updated)+ }++ wrongViewer := openClient(t, h)+ sendPasswordAuthenticate(wrongViewer, h.room, "wrong-password-viewer", "wrong-password")+ expectMatch(t, wrongViewer.next("error").raw, `{"code":"ROOM_ACCESS_DENIED"}`)++ password := "easy-password"+ enabled := h.updateRoomAccess(protocol.SetViewerPasswordRequest{Action: "set-viewer-password", Password: &password})+ if !reflect.DeepEqual(enabled, protocol.ViewerPasswordUpdatedResponse{Type: "viewer-password-updated", Enabled: true}) {+ t.Fatalf("password update: %+v", enabled)+ }++ passwordViewer := openClient(t, h)+ admitted := authenticate(t, passwordViewer, h.room, protocol.RoleViewer, "password-viewer", 1, "",+ presenceOptions{viewerPassword: "easy-password"})+ expectString(t, "role", admitted.Role, protocol.RoleViewer)+ commitPreparedRoute(t, passwordViewer)++ disabled := h.updateRoomAccess(protocol.SetViewerPasswordRequest{Action: "set-viewer-password", Password: nil})+ if !reflect.DeepEqual(disabled, protocol.ViewerPasswordUpdatedResponse{Type: "viewer-password-updated", Enabled: false}) {+ t.Fatalf("password removal: %+v", disabled)+ }++ grantViewer := openClient(t, h)+ granted := authenticate(t, grantViewer, h.room, protocol.RoleViewer, "grant-after-password-removal", 1, "", presenceOptions{})+ expectString(t, "role", granted.Role, protocol.RoleViewer)+ removedPasswordViewer := openClient(t, h)+ sendPasswordAuthenticate(removedPasswordViewer, h.room, "removed-password-viewer", "easy-password")+ expectMatch(t, removedPasswordViewer.next("error").raw, `{"code":"ROOM_ACCESS_DENIED"}`)+}++func TestSignalReportsPasswordConfigurationOnlyToAuthenticatedHost(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ h.updateRoomAccess(protocol.SetCodeEntryPolicyRequest{Action: "set-code-entry-policy", Policy: protocol.CodeEntryPrivate})++ host := openClient(t, h)+ withoutPassword := authenticate(t, host, h.room, protocol.RoleHost, "password-state-host", 1, "", presenceOptions{})+ expectMatch(t, withoutPassword.raw, `{"role":"host","codeEntryPolicy":"private","viewerPasswordEnabled":false}`)++ viewer := openClient(t, h)+ viewerAuthenticated := authenticate(t, viewer, h.room, protocol.RoleViewer, "password-state-viewer", 1, "", presenceOptions{})+ expectTrue(t, "viewerPasswordEnabled must be absent for viewers", !hasKey(t, viewerAuthenticated.raw, "viewerPasswordEnabled"))++ password := "room-password"+ h.updateRoomAccess(protocol.SetViewerPasswordRequest{Action: "set-viewer-password", Password: &password})+ replacementHost := openClient(t, h)+ withPassword := authenticate(t, replacementHost, h.room, protocol.RoleHost, "password-state-host", 1, "", presenceOptions{})+ expectMatch(t, withPassword.raw, `{"role":"host","codeEntryPolicy":"private","viewerPasswordEnabled":true}`)+}++// ---------------------------------------------------------------------------+// presence roster+// ---------------------------------------------------------------------------++func TestSignalReportsEveryOnlineViewerWithoutExpandingHostMediaFanout(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "presence-host", 1, "", presenceOptions{viewerPresence: true})+ nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return len(viewerPresenceEntries(message)) == 0+ })++ viewerNames := []string{"阿明", "阿青", ""}+ var viewers []*testClient+ for index, displayName := range viewerNames {+ viewer := openClient(t, h)+ viewers = append(viewers, viewer)+ authenticated := authenticate(t, viewer, h.room, protocol.RoleViewer,+ fmt.Sprintf("presence-viewer-%d", index), 1, "", presenceOptions{displayName: displayName})+ prepared := nextPreparedRoute(t, viewer)+ viewer.sendJSON(map[string]any{+ "type": "route-transport-connected",+ "revision": prepared.Revision,+ "connectionId": prepared.Candidate.ConnectionID,+ })+ viewer.sendJSON(map[string]any{"type": "route-ready", "revision": prepared.Revision, "phase": "prepare"})+ expectTrue(t, "prepare revision must exceed the authenticated revision", prepared.Revision > authenticated.RouteRevision)+ nextActiveRouteRevision(t, viewer, prepared.Revision)+ }++ isRelay := func(viewer presenceEntry) bool {+ return viewer.Upstream.Kind == "peer" && viewer.Upstream.PeerID != hostAuth.PeerID+ }+ full := nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ entries := viewerPresenceEntries(message)+ return len(entries) == 3 && slices.ContainsFunc(entries, isRelay)+ })+ fullEntries := viewerPresenceEntries(full)+ expectStrings(t, "display names", displayNames(fullEntries), []string{"阿明", "阿青", "观众"})+ directChildren := 0+ for _, viewer := range fullEntries {+ if viewer.Upstream.Kind == "peer" && viewer.Upstream.PeerID == hostAuth.PeerID {+ directChildren+++ }+ }+ if directChildren != 2 {+ t.Fatalf("expected 2 direct children of the host, got %d", directChildren)+ }+ for _, viewer := range fullEntries {+ expectTrue(t, "every viewer must be mediaReady", isMediaReady(viewer))+ }+ relayIndex := slices.IndexFunc(fullEntries, isRelay)+ relay := fullEntries[relayIndex]+ expectTrue(t, "relay parent must be in the roster", slices.ContainsFunc(fullEntries, func(viewer presenceEntry) bool {+ return viewer.PeerID == relay.Upstream.PeerID+ }))+ host.ignore("route-update")+ host.sendJSON(signalCandidate(relay.PeerID, "stale_connection_12345678"))+ host.expectNone(40 * time.Millisecond)++ viewers[2].sendJSON(map[string]any{"type": "set-display-name", "displayName": "后来改名"})+ renamed := nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return slices.ContainsFunc(viewerPresenceEntries(message), func(viewer presenceEntry) bool {+ return viewer.DisplayName == "后来改名"+ })+ })+ if len(viewerPresenceEntries(renamed)) != 3 {+ t.Fatalf("renamed roster: %s", renamed.raw)+ }++ h.closeClient(viewers[2])+ afterDisconnect := nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return len(viewerPresenceEntries(message)) == 2+ })+ expectStrings(t, "display names after disconnect", displayNames(viewerPresenceEntries(afterDisconnect)), []string{"阿明", "阿青"})+}++// ---------------------------------------------------------------------------+// quality evidence forwarding+// ---------------------------------------------------------------------------++func TestSignalForwardsExactDirectViewerReceiveEvidenceToHost(t *testing.T) {+ now := newClock(10_000)+ h := startHarness(t, harnessOptions{now: now.now})+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "evidence-direct-host", 1, "", presenceOptions{viewerPresence: true})+ viewer := openClient(t, h)+ viewerAuth := authenticate(t, viewer, h.room, protocol.RoleViewer, "evidence-direct-viewer", 1, "", presenceOptions{})+ host.ignore("viewer-presence")+ prepared := nextPreparedRoute(t, viewer)+ connectionID := prepared.Candidate.ConnectionID+ routeRevision := prepared.Revision+ viewer.sendJSON(map[string]any{"type": "route-transport-connected", "revision": routeRevision, "connectionId": connectionID})+ viewer.sendJSON(map[string]any{"type": "route-ready", "revision": routeRevision, "phase": "prepare"})+ nextActiveRouteRevision(t, viewer, routeRevision)+ nextActiveRouteRevision(t, host, routeRevision)+ host.sendJSON(signalDescription(viewerAuth.PeerID, connectionID, "offer"))+ viewer.next("signal")++ viewer.sendJSON(viewerQualityEvidenceMessage(connectionID, routeRevision, 0, 0))+ expectMatch(t, host.next("viewer-quality-evidence").raw, fmt.Sprintf(+ `{"viewerPeerId":%q,"upstream":{"kind":"peer","peerId":%q},"guard":{"connectionId":%q,"routeRevision":%d}}`,+ viewerAuth.PeerID, hostAuth.PeerID, connectionID, routeRevision))++ viewer.sendJSON(viewerQualityEvidenceMessage(connectionID, routeRevision, 0, 1))+ host.expectNone(40 * time.Millisecond)+ now.advance(2_000)+ viewer.sendJSON(viewerQualityEvidenceMessage(connectionID, routeRevision, 7, 1))+ expectMatch(t, host.next("viewer-quality-evidence").raw, fmt.Sprintf(+ `{"guard":{"connectionId":%q,"routeRevision":%d,"presentationEpoch":1},"sequence":7}`, connectionID, routeRevision))+ now.advance(2_000)+ viewer.sendJSON(viewerQualityEvidenceMessage(connectionID, routeRevision, 1, 0))+ host.expectNone(40 * time.Millisecond)+ viewer.sendJSON(viewerQualityEvidenceMessage(connectionID, routeRevision, 0, 2))+ host.expectNone(40 * time.Millisecond)+ now.advance(2_000)+ viewer.sendJSON(viewerQualityEvidenceMessage(connectionID, routeRevision, 9, 2))+ expectMatch(t, host.next("viewer-quality-evidence").raw, fmt.Sprintf(+ `{"guard":{"connectionId":%q,"routeRevision":%d,"presentationEpoch":2},"sequence":9}`, connectionID, routeRevision))+}++func diagnosticQuality(t *testing.T, raw []byte) map[string]any {+ t.Helper()+ snapshot, _ := jsonObject(t, raw)["snapshot"].(map[string]any)+ children, _ := snapshot["children"].([]any)+ for _, child := range children {+ entry, _ := child.(map[string]any)+ if quality, ok := entry["quality"].(map[string]any); ok {+ return quality+ }+ }+ return nil+}++func TestSignalForwardsRelayedChildReceiveReportToExactParentAndHost(t *testing.T) {+ now := newClock(10_000)+ h := startHarness(t, harnessOptions{endpointMediaCopyCapacity: 1, now: now.now})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "evidence-relay-host", 1, "", presenceOptions{viewerPresence: true})+ parent := openClient(t, h)+ parentAuth := authenticate(t, parent, h.room, protocol.RoleViewer, "evidence-relay-parent", 1, "", presenceOptions{})+ parentPrepare := nextPreparedRoute(t, parent)+ parent.sendJSON(map[string]any{"type": "route-ready", "revision": parentPrepare.Revision, "phase": "prepare"})+ nextActiveRouteRevision(t, parent, parentPrepare.Revision)++ child := openClient(t, h)+ childAuth := authenticate(t, child, h.room, protocol.RoleViewer, "evidence-relay-child", 1, "", presenceOptions{})+ childPrepare := nextPreparedRoute(t, child)+ if childPrepare.Assignment.Upstream != protocol.PeerUpstream(parentAuth.PeerID) {+ t.Fatalf("child upstream: %+v", childPrepare.Assignment.Upstream)+ }+ child.sendJSON(map[string]any{"type": "route-ready", "revision": childPrepare.Revision, "phase": "prepare"})+ nextActiveRouteRevision(t, child, childPrepare.Revision)++ child.sendJSON(viewerQualityEvidenceMessage(childPrepare.Candidate.ConnectionID, childPrepare.Revision, 0, 0))+ expected := fmt.Sprintf(+ `{"viewerPeerId":%q,"upstream":{"kind":"peer","peerId":%q},"guard":{"connectionId":%q,"routeRevision":%d}}`,+ childAuth.PeerID, parentAuth.PeerID, childPrepare.Candidate.ConnectionID, childPrepare.Revision)+ expectMatch(t, parent.next("viewer-quality-evidence").raw, expected)+ expectMatch(t, host.next("viewer-quality-evidence").raw, expected)+ host.sendJSON(map[string]any{"type": "request-route-diagnostic"})+ quality := diagnosticQuality(t, host.next("route-diagnostic-snapshot").raw)+ if !reflect.DeepEqual(quality, jsonValue(t, []byte(+ `{"eligibleWindows":1,"eligibleDurationMs":2000,"freezeWindows":0,"freezeCount":0,"freezeDurationMs":0,"pauseCount":0,"pauseDurationMs":0}`))) {+ t.Fatalf("diagnostic quality: %v", quality)+ }++ now.advance(2_000)+ incomplete := viewerQualityEvidenceMessage(childPrepare.Candidate.ConnectionID, childPrepare.Revision, 1, 0)+ incomplete["metrics"].(map[string]any)["pauseCountDelta"] = nil+ child.sendJSON(incomplete)+ expectMatch(t, parent.next("viewer-quality-evidence").raw, `{"metrics":{"pauseCountDelta":null}}`)+ expectMatch(t, host.next("viewer-quality-evidence").raw, `{"metrics":{"pauseCountDelta":null}}`)+ host.sendJSON(map[string]any{"type": "request-route-diagnostic"})+ unchanged := diagnosticQuality(t, host.next("route-diagnostic-snapshot").raw)+ if unchanged["eligibleWindows"] != float64(1) {+ t.Fatalf("eligibleWindows: %v", unchanged["eligibleWindows"])+ }+}++// ---------------------------------------------------------------------------+// presence roster (continued)+// ---------------------------------------------------------------------------++func TestSignalSharesOptedInHostNameWithHostAndViewerRosterSubscribers(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "named-host-client", 1, "",+ presenceOptions{viewerPresence: true, displayName: "原始分享者"})+ initial := parsePresence(t, host.next("viewer-presence").raw)+ entry := hostPresenceEntry(initial)+ if entry == nil || entry.PeerID != hostAuth.PeerID || entry.DisplayName != "原始分享者" || entry.Upstream.Kind != "none" {+ t.Fatalf("initial host presence: %s", initial.raw)+ }++ viewer := openClient(t, h)+ viewerAuth := authenticate(t, viewer, h.room, protocol.RoleViewer, "named-viewer-client", 1, "",+ presenceOptions{viewerPresence: true, displayName: "观看者"})+ hostNamed := func(name string) func(presenceMessage) bool {+ return func(message presenceMessage) bool {+ entry := hostPresenceEntry(message)+ return entry != nil && entry.DisplayName == name+ }+ }+ viewerSnapshot := nextViewerPresenceMatching(t, viewer, hostNamed("原始分享者"))+ expectString(t, "host peer", hostPresenceEntry(viewerSnapshot).PeerID, hostAuth.PeerID)+ expectTrue(t, "viewer must see itself", slices.ContainsFunc(viewerPresenceEntries(viewerSnapshot), func(entry presenceEntry) bool {+ return entry.PeerID == viewerAuth.PeerID+ }))++ hostSnapshot := nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return hostNamed("原始分享者")(message) && len(viewerPresenceEntries(message)) == 1+ })+ expectString(t, "host peer", hostPresenceEntry(hostSnapshot).PeerID, hostAuth.PeerID)++ host.sendJSON(map[string]any{"type": "set-display-name", "displayName": "改名后的分享者"})+ renamedViewer := nextViewerPresenceMatching(t, viewer, hostNamed("改名后的分享者"))+ expectString(t, "host peer", hostPresenceEntry(renamedViewer).PeerID, hostAuth.PeerID)+ renamedHost := nextViewerPresenceMatching(t, host, hostNamed("改名后的分享者"))+ expectString(t, "host peer", hostPresenceEntry(renamedHost).PeerID, hostAuth.PeerID)+}++func TestSignalReplacesOptedInViewerRosterAfterAnotherViewerLeaves(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "viewer-roster-host", 1, "", presenceOptions{})++ subscriber := openClient(t, h)+ subscriberAuth := authenticate(t, subscriber, h.room, protocol.RoleViewer, "viewer-roster-subscriber", 1, "",+ presenceOptions{viewerPresence: true, displayName: "订阅者"})+ nextViewerPresenceMatching(t, subscriber, func(message presenceMessage) bool {+ return len(viewerPresenceEntries(message)) == 1+ })++ other := openClient(t, h)+ otherAuth := authenticate(t, other, h.room, protocol.RoleViewer, "viewer-roster-other", 1, "",+ presenceOptions{displayName: "另一位"})+ joined := nextViewerPresenceMatching(t, subscriber, func(message presenceMessage) bool {+ return len(viewerPresenceEntries(message)) == 2+ })+ expectStrings(t, "joined roster", peerIDs(viewerPresenceEntries(joined)), []string{subscriberAuth.PeerID, otherAuth.PeerID})++ h.closeClient(other)+ left := nextViewerPresenceMatching(t, subscriber, func(message presenceMessage) bool {+ return len(viewerPresenceEntries(message)) == 1+ })+ expectStrings(t, "roster after leave", peerIDs(viewerPresenceEntries(left)), []string{subscriberAuth.PeerID})+}++func TestSignalClearsDisconnectedHostNameAndPublishesReplacementName(t *testing.T) {+ h := startHarness(t, harnessOptions{viewerDisconnectGraceMs: 40})+ firstHost := openClient(t, h)+ firstAuth := authenticate(t, firstHost, h.room, protocol.RoleHost, "replaceable-host-client", 1, "",+ presenceOptions{viewerPresence: true, displayName: "旧分享者"})+ firstHost.next("viewer-presence")++ viewer := openClient(t, h)+ viewerAuth := authenticate(t, viewer, h.room, protocol.RoleViewer, "replacement-roster-viewer", 1, "",+ presenceOptions{viewerPresence: true})+ nextViewerPresenceMatching(t, viewer, func(message presenceMessage) bool {+ entry := hostPresenceEntry(message)+ return entry != nil && entry.DisplayName == "旧分享者"+ })++ h.closeClient(firstHost)+ viewer.next("host-status")+ offline := nextViewerPresenceMatching(t, viewer, func(message presenceMessage) bool {+ return hostPresenceEntry(message) == nil+ })+ expectMatch(t, viewerEntriesJSON(t, offline), fmt.Sprintf(`[{"peerId":%q,"upstream":{"kind":"none"}}]`, viewerAuth.PeerID))++ replacement := openClient(t, h)+ replacementAuth := authenticate(t, replacement, h.room, protocol.RoleHost, "replaceable-host-client", 1, "",+ presenceOptions{viewerPresence: true, displayName: "新分享者"})+ expectString(t, "replacement peer", replacementAuth.PeerID, firstAuth.PeerID)+ online := nextViewerPresenceMatching(t, viewer, func(message presenceMessage) bool {+ entry := hostPresenceEntry(message)+ return entry != nil && entry.DisplayName == "新分享者"+ })+ expectString(t, "online host peer", hostPresenceEntry(online).PeerID, firstAuth.PeerID)+ h.closeClient(replacement)+ h.closeClient(viewer)+}++// ---------------------------------------------------------------------------+// grant rotation and revocation+// ---------------------------------------------------------------------------++func viewerGrantOf(t *testing.T, inviteURL string) string {+ t.Helper()+ parsed, err := url.Parse(inviteURL)+ if err != nil {+ t.Fatal(err)+ }+ values, err := url.ParseQuery(parsed.Fragment)+ if err != nil {+ t.Fatal(err)+ }+ return values.Get("v")+}++func TestSignalStronglyRotatesAndRevokesEveryViewerGenerationAndMediaEdge(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "ordinary-access-presence-host", 1, "",+ presenceOptions{viewerPresence: true})+ if entries := viewerPresenceEntries(parsePresence(t, host.next("viewer-presence").raw)); len(entries) != 0 {+ t.Fatalf("initial roster: %v", entries)+ }++ firstViewer := openClient(t, h)+ firstViewerAuth := authenticate(t, firstViewer, h.room, protocol.RoleViewer, "ordinary-access-presence-viewer-1", 1, "",+ presenceOptions{displayName: "第一位"})+ commitPreparedRoute(t, firstViewer)+ hasPeerEdge := func(message presenceMessage) bool {+ return slices.ContainsFunc(viewerPresenceEntries(message), func(entry presenceEntry) bool {+ return entry.Upstream.Kind == "peer"+ })+ }+ expectMatch(t, viewerEntriesJSON(t, nextViewerPresenceMatching(t, host, hasPeerEdge)), fmt.Sprintf(+ `[{"role":"viewer","peerId":%q,"displayName":"第一位","upstream":{"kind":"peer","peerId":%q}}]`,+ firstViewerAuth.PeerID, hostAuth.PeerID))++ rotated := h.updateRoomAccess(protocol.RotateViewerGrantRequest{Action: "rotate-viewer-grant"})+ expectMatch(t, firstViewer.next("viewer-grant-revoked").raw,+ fmt.Sprintf(`{"viewerAuthorizationGeneration":%q}`, firstViewerAuth.ViewerAuthorizationGeneration))+ expectCloseCode(t, firstViewer, 4004)+ nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return len(viewerPresenceEntries(message)) == 0+ })++ rotatedGrant, ok := rotated.(protocol.ViewerGrantUpdatedResponse)+ if !ok || rotatedGrant.InviteURL == nil {+ t.Fatalf("expected a rotated Viewer grant, got %+v", rotated)+ }+ grant := viewerGrantOf(t, *rotatedGrant.InviteURL)+ expectTrue(t, "rotated grant must be present", grant != "")+ rotatedRoom := h.room+ rotatedRoom.ViewerGrant = grant+ secondViewer := openClient(t, h)+ secondViewerAuth := authenticate(t, secondViewer, rotatedRoom, protocol.RoleViewer, "ordinary-access-presence-viewer-2", 1, "",+ presenceOptions{displayName: "第二位"})+ commitPreparedRoute(t, secondViewer)+ seen := nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return slices.ContainsFunc(viewerPresenceEntries(message), func(entry presenceEntry) bool {+ return entry.PeerID == secondViewerAuth.PeerID+ })+ })+ if len(viewerPresenceEntries(seen)) != 1 {+ t.Fatalf("second roster: %s", seen.raw)+ }++ revoked := h.updateRoomAccess(protocol.RevokeViewerGrantRequest{Action: "revoke-viewer-grant"})+ secondViewer.next("viewer-grant-revoked")+ expectCloseCode(t, secondViewer, 4004)+ nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return len(viewerPresenceEntries(message)) == 0+ })+ revokedGrant, ok := revoked.(protocol.ViewerGrantUpdatedResponse)+ if !ok || revokedGrant.InviteURL != nil {+ t.Fatalf("revoke response: %+v", revoked)+ }+ expectNoViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return len(viewerPresenceEntries(message)) > 0+ }, 30*time.Millisecond)+}++func TestSignalRotatesGrantAndPromotesWaitingCodeAdmittedViewer(t *testing.T) {+ h := startHarness(t, harnessOptions{endpointMediaCopyCapacity: 1, maxViewersPerRoom: 2})+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "mixed-access-host", 2, "", presenceOptions{viewerPresence: true})+ if entries := viewerPresenceEntries(parsePresence(t, host.next("viewer-presence").raw)); len(entries) != 0 {+ t.Fatalf("initial roster: %v", entries)+ }++ grantViewer := openClient(t, h)+ grantAuth := authenticate(t, grantViewer, h.room, protocol.RoleViewer, "mixed-grant-viewer", 0, "",+ presenceOptions{displayName: "邀请观众"})+ commitPreparedRoute(t, grantViewer)+ nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return slices.ContainsFunc(viewerPresenceEntries(message), func(entry presenceEntry) bool {+ return entry.PeerID == grantAuth.PeerID && entry.Upstream.Kind == "peer" && isMediaReady(entry)+ })+ })++ codeViewer := openClient(t, h)+ codeAuth := authenticate(t, codeViewer, h.room, protocol.RoleViewer, "mixed-code-viewer", 1, "",+ presenceOptions{codeOnly: true, displayName: "房间号观众"})+ nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return len(viewerPresenceEntries(message)) == 2+ })+ h.updateRoomAccess(protocol.RotateViewerGrantRequest{Action: "rotate-viewer-grant"})+ grantViewer.next("viewer-grant-revoked")+ expectCloseCode(t, grantViewer, 4004)+ commitPreparedRoute(t, codeViewer)+ remaining := nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ entries := viewerPresenceEntries(message)+ return len(entries) == 1 && entries[0].PeerID == codeAuth.PeerID && entries[0].Upstream.Kind == "peer"+ })+ expectEqual(t, viewerEntriesJSON(t, remaining), fmt.Sprintf(+ `[{"role":"viewer","peerId":%q,"displayName":"房间号观众","upstream":{"kind":"peer","peerId":%q},"mediaReady":true}]`,+ codeAuth.PeerID, hostAuth.PeerID))+ expectTrue(t, "code viewer must stay open", !codeViewer.isClosed())+ var connected bool+ h.locked(func() { _, connected = h.store.GetConnectedViewer(h.room.RoomID, codeAuth.PeerID) })+ expectTrue(t, "code viewer must stay connected", connected)++ h.closeClient(codeViewer)+ h.closeClient(host)+}++// ---------------------------------------------------------------------------+// site access at upgrade+// ---------------------------------------------------------------------------++func sendCodeOnlyAuthenticate(client *testClient, roomID, clientID string, extra map[string]any) {+ message := map[string]any{+ "type": "authenticate",+ "protocol": protocol.SignalingProtocol,+ "roomId": roomID,+ "role": protocol.RoleViewer,+ "clientId": clientID,+ }+ for key, value := range extra {+ message[key] = value+ }+ client.sendJSON(message)+}++func TestSignalRequiresSiteAccessForCodeOnlyViewersWhileAcceptingRoomGrants(t *testing.T) {+ h := startHarness(t, harnessOptions{siteAccessPassword: "protected-instance-password"})++ viewer := openClient(t, h)+ sendCodeOnlyAuthenticate(viewer, h.room.RoomID, "code-only-viewer-without-site-access", nil)+ expectMatch(t, viewer.next("error").raw, `{"code":"INVALID_TOKEN"}`)++ grantedViewer := openClient(t, h)+ granted := authenticate(t, grantedViewer, h.room, protocol.RoleViewer, "grant-viewer-without-site-access", 1, "", presenceOptions{})+ expectString(t, "role", granted.Role, protocol.RoleViewer)++ unauthorizedHost := openClient(t, h)+ unauthorizedHost.sendJSON(map[string]any{+ "type": "authenticate",+ "protocol": protocol.SignalingProtocol,+ "roomId": h.room.RoomID,+ "role": protocol.RoleHost,+ "token": h.room.HostToken,+ "clientId": "host-client-without-admission",+ })+ expectMatch(t, unauthorizedHost.next("error").raw, `{"code":"AUTH_REQUIRED"}`)++ viewerWithHostCookie := openClientWithCookie(t, h, siteAccessCookie)+ admitted := authenticate(t, viewerWithHostCookie, h.room, protocol.RoleViewer, "viewer-with-host-cookie", 1, "",+ presenceOptions{codeOnly: true})+ expectString(t, "role", admitted.Role, protocol.RoleViewer)++ publicRoom := h.createRoom(protocol.CodeEntryOpen, "")+ publicWithoutSiteAccess := openClient(t, h)+ sendCodeOnlyAuthenticate(publicWithoutSiteAccess, publicRoom.RoomID, "public-viewer-without-site-access", nil)+ expectMatch(t, publicWithoutSiteAccess.next("error").raw, `{"code":"INVALID_TOKEN"}`)++ publicWithForgedGrant := openClient(t, h)+ sendCodeOnlyAuthenticate(publicWithForgedGrant, publicRoom.RoomID, "public-viewer-with-forged-grant",+ map[string]any{"viewerGrant": strings.Repeat("x", 21) + "g"})+ expectMatch(t, publicWithForgedGrant.next("error").raw, `{"code":"INVALID_TOKEN"}`)++ publicWithSiteAccess := openClientWithCookie(t, h, siteAccessCookie)+ publicAdmitted := authenticate(t, publicWithSiteAccess, publicRoom, protocol.RoleViewer, "public-viewer-with-site-access", 1, "",+ presenceOptions{codeOnly: true})+ expectString(t, "role", publicAdmitted.Role, protocol.RoleViewer)++ passwordRoom := h.createRoom(protocol.CodeEntryPrivate, "room-password")++ passwordWithoutSiteAccess := openClient(t, h)+ sendCodeOnlyAuthenticate(passwordWithoutSiteAccess, passwordRoom.RoomID, "password-viewer-without-site-access",+ map[string]any{"viewerPassword": "room-password"})+ expectMatch(t, passwordWithoutSiteAccess.next("error").raw, `{"code":"INVALID_TOKEN"}`)++ passwordWithSiteAccess := openClientWithCookie(t, h, siteAccessCookie)+ passwordAdmitted := authenticate(t, passwordWithSiteAccess, passwordRoom, protocol.RoleViewer, "password-viewer-with-site-access", 1, "",+ presenceOptions{viewerPassword: "room-password"})+ expectString(t, "role", passwordAdmitted.Role, protocol.RoleViewer)++ host := openClientWithCookie(t, h, siteAccessCookie)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "host-client-protected", 1, "", presenceOptions{})+ expectString(t, "role", hostAuth.Role, protocol.RoleHost)+}++func TestSignalDistinguishesMissingRoomsFromExistingRoomCodeOnlyDenials(t *testing.T) {+ now := newClock(utcMillis(2026, time.August, 24, 12))+ h := startHarness(t, harnessOptions{+ siteAccessPassword: "protected-instance-password",+ maxViewersPerRoom: 1,+ now: now.now,+ })++ protectedRoom := h.createRoom(protocol.CodeEntryPrivate, "correct-password")+ expiring := h.createRoom(protocol.CodeEntryOpen, "")+ unusedRoomID := ""+ for code := 1_000; code < 10_000; code++ {+ candidate := fmt.Sprint(code)+ if candidate != h.room.RoomID && candidate != protectedRoom.RoomID && candidate != expiring.RoomID {+ unusedRoomID = candidate+ break+ }+ }++ admitted := openClientWithCookie(t, h, siteAccessCookie)+ authenticate(t, admitted, h.room, protocol.RoleViewer, "admitted-viewer", 1, "", presenceOptions{codeOnly: true})++ expectDenial := func(roomID, clientID, code, viewerPassword string) {+ t.Helper()+ client := openClientWithCookie(t, h, siteAccessCookie)+ extra := map[string]any{}+ if viewerPassword != "" {+ extra["viewerPassword"] = viewerPassword+ }+ sendCodeOnlyAuthenticate(client, roomID, clientID, extra)+ message := "Room access denied"+ if code == "ROOM_NOT_FOUND" {+ message = "Room not found or expired"+ }+ expectEqual(t, client.next("error").raw, fmt.Sprintf(`{"type":"error","code":%q,"message":%q}`, code, message))+ expectClose(t, client, 4003, "Authentication failed")+ }++ expectDenial(unusedRoomID, "unknown-room-viewer", "ROOM_NOT_FOUND", "")+ expectDenial(protectedRoom.RoomID, "missing-password-viewer", "ROOM_ACCESS_DENIED", "")+ expectDenial(protectedRoom.RoomID, "wrong-password-viewer", "ROOM_ACCESS_DENIED", "wrong-password")+ expectDenial(h.room.RoomID, "full-room-viewer", "ROOM_ACCESS_DENIED", "")++ now.advance(86_400_001)+ expectDenial(expiring.RoomID, "expired-room-viewer", "ROOM_NOT_FOUND", "")++ expiredGrant := openClientWithCookie(t, h, siteAccessCookie)+ sendCodeOnlyAuthenticate(expiredGrant, expiring.RoomID, "expired-grant-viewer",+ map[string]any{"viewerGrant": expiring.ViewerGrant})+ expectMatch(t, expiredGrant.next("error").raw, `{"code":"INVALID_TOKEN"}`)+}++// ---------------------------------------------------------------------------+// room lease and expiry+// ---------------------------------------------------------------------------++func TestSignalDoesNotExpireActiveRoomAndArmsItsLeaseAfterHostDisconnect(t *testing.T) {+ now := newClock(utcMillis(2026, time.August, 20, 12))+ h := startHarness(t, harnessOptions{now: now.now})+ host := openClient(t, h)+ authenticated := authenticate(t, host, h.room, protocol.RoleHost, "active-lease-host", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "provisional-viewer", 1, "", presenceOptions{})+ commitPreparedRoute(t, viewer)++ now.advance(86_401_000)+ expireAt := func(nowMs int64) []room.ClosedRoom {+ t.Helper()+ var expired []room.ClosedRoom+ var err error+ h.locked(func() { expired, err = h.store.ExpireRooms(nowMs) })+ if err != nil {+ t.Fatalf("ExpireRooms: %v", err)+ }+ return expired+ }+ if expired := expireAt(now.now()); len(expired) != 0 {+ t.Fatalf("active room expired: %v", expired)+ }+ h.closeClient(host)+ viewer.next("host-status")+ var hostConnected bool+ h.locked(func() { _, hostConnected = h.store.GetConnectedHost(h.room.RoomID) })+ expectTrue(t, "host must be disconnected", !hostConnected)+ if expired := expireAt(now.now() + 86_399_999); len(expired) != 0 {+ t.Fatalf("room expired before its lease: %v", expired)+ }+ expired := expireAt(now.now() + 86_401_000)+ if len(expired) != 1 || expired[0].RoomID != h.room.RoomID || len(expired[0].SessionIDs) != 1 {+ t.Fatalf("expired rooms: %+v", expired)+ }+ h.closeClient(viewer)+ expectString(t, "role", authenticated.Role, protocol.RoleHost)+}++func TestSignalTerminatesExpiredDormantRoomThroughCleanupTimer(t *testing.T) {+ now := newClock(utcMillis(2026, time.August, 20, 12))+ h := startHarness(t, harnessOptions{now: now.now, cleanupIntervalMs: 20})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "expiring-host", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "expiring-viewer", 1, "", presenceOptions{})+ commitPreparedRoute(t, viewer)+ h.closeClient(host)+ viewer.next("host-status")++ now.advance(86_401_000)++ expectEqual(t, viewer.next("room-closed").raw, `{"type":"room-closed","reason":"expired"}`)+ expectClose(t, viewer, 1000, "Room expired")+ if size := h.storeSize(); size != 0 {+ t.Fatalf("store size %d", size)+ }+}++func TestSignalKeepsPreHostViewerSessionCurrentAfterHostClearsRoomLease(t *testing.T) {+ now := newClock(utcMillis(2026, time.August, 20, 12))+ h := startHarness(t, harnessOptions{now: now.now})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "pre-host-lease-viewer", 1, "", presenceOptions{displayName: "Before"})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "pre-host-lease-host", 1, "", presenceOptions{viewerPresence: true})+ named := func(name string) func(presenceMessage) bool {+ return func(message presenceMessage) bool {+ return slices.ContainsFunc(viewerPresenceEntries(message), func(entry presenceEntry) bool {+ return entry.DisplayName == name+ })+ }+ }+ nextViewerPresenceMatching(t, host, named("Before"))++ now.advance(86_400_001)+ viewer.sendJSON(map[string]any{"type": "set-display-name", "displayName": "After"})+ updated := nextViewerPresenceMatching(t, host, named("After"))+ if len(viewerPresenceEntries(updated)) != 1 {+ t.Fatalf("updated roster: %s", updated.raw)+ }+}++// ---------------------------------------------------------------------------+// grant update failure+// ---------------------------------------------------------------------------++func TestSignalLeavesEstablishedAuthorizationAndMediaUntouchedWhenGrantUpdateFails(t *testing.T) {+ // The TS mocked setViewerGrant to throw; here the stable-authority+ // database is closed underneath the store, so the write fails before+ // memory changes, which is the same failure point.+ database, err := room.NewDatabase(filepath.Join(t.TempDir(), "rooms.sqlite"))+ if err != nil {+ t.Fatal(err)+ }+ store := newStore(t, 8, nil, database)+ h := startHarness(t, harnessOptions{store: store})+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "persistence-failure-host", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ viewerAuth := authenticate(t, viewer, h.room, protocol.RoleViewer, "persistence-failure-viewer", 1, "", presenceOptions{})+ commitPreparedRoute(t, viewer)+ host.sendJSON(signalDescription(viewerAuth.PeerID, "persistence-failure-edge", "offer"))+ viewer.next("signal")++ h.locked(func() {+ if err := database.Close(); err != nil {+ t.Fatalf("database.Close: %v", err)+ }+ })+ _, err = h.server.UpdateRoomAccess(h.room.RoomID, h.room.HostToken,+ protocol.RotateViewerGrantRequest{Action: "rotate-viewer-grant"})+ var roomError *room.Error+ if err == nil || errors.As(err, &roomError) {+ t.Fatalf("expected the rotation to fail with a non-room error, got %v", err)+ }+ if message, ok := viewer.tryNext("viewer-grant-revoked", 30*time.Millisecond); ok {+ t.Fatalf("viewer was revoked: %s", message.raw)+ }++ host.sendJSON(signalCandidate(viewerAuth.PeerID, "persistence-failure-edge"))+ expectMatch(t, viewer.next("signal").raw, fmt.Sprintf(+ `{"fromPeerId":%q,"payload":{"connectionId":"persistence-failure-edge"}}`, hostAuth.PeerID))++ secondViewer := openClient(t, h)+ secondAuth := authenticate(t, secondViewer, h.room, protocol.RoleViewer, "persistence-failure-new-viewer", 1, "", presenceOptions{})+ expectString(t, "viewerAuthorizationGeneration", secondAuth.ViewerAuthorizationGeneration, viewerAuth.ViewerAuthorizationGeneration)+}++// ---------------------------------------------------------------------------+// host arrival, pause and quality+// ---------------------------------------------------------------------------++func TestSignalLetsViewersArriveFirstAndReplaysTheirSnapshotWhenHostJoins(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ viewer := openClient(t, h)+ viewerAuth := authenticate(t, viewer, h.room, protocol.RoleViewer, "viewer-client-early", 1, "", presenceOptions{})+ expectTrue(t, "host must be offline", !viewerAuth.HostOnline)+ expectTrue(t, "mediaMode must be present", hasKey(t, viewerAuth.raw, "mediaMode"))+ expectTrue(t, "routeRevision must be present", hasKey(t, viewerAuth.raw, "routeRevision"))++ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "host-client-stable", 1, "", presenceOptions{})+ host.ignore("route-update")+ expectEqual(t, viewer.next("host-status").raw, `{"type":"host-status","online":true,"paused":false}`)+}++func setSharingPaused(client *testClient, shareGeneration string, paused bool) {+ client.sendJSON(map[string]any{"type": "set-sharing-paused", "shareGeneration": shareGeneration, "paused": paused})+}++func TestSignalSnapshotsIntentionalPauseAcrossViewerReplacementAndClearsItOnResumeAndStop(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ shareGeneration := "pause_share_generation_12345678"+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "pause-host-client", 1, shareGeneration, presenceOptions{})+ expectTrue(t, "hostPaused must be absent for the host", !hasKey(t, hostAuth.raw, "hostPaused"))+ viewer := openClient(t, h)+ viewerAuth := authenticate(t, viewer, h.room, protocol.RoleViewer, "pause-viewer-client", 1, "", presenceOptions{})+ expectTrue(t, "hostPaused must be false", viewerAuth.HostPaused != nil && !*viewerAuth.HostPaused)+ commitPreparedRoute(t, viewer)++ setSharingPaused(host, shareGeneration, true)+ expectEqual(t, viewer.next("host-status").raw, `{"type":"host-status","online":true,"paused":true}`)++ h.closeClient(host)+ expectMatch(t, viewer.next("host-status").raw, `{"online":false,"paused":false}`)+ activeHost := openClient(t, h)+ authenticate(t, activeHost, h.room, protocol.RoleHost, "pause-host-client", 1, shareGeneration,+ presenceOptions{sharingPaused: boolPointer(true)})+ expectMatch(t, viewer.next("host-status").raw, `{"online":true,"paused":true}`)++ replacement := openClient(t, h)+ replacementAuth := authenticate(t, replacement, h.room, protocol.RoleViewer, "pause-viewer-client", 1, "", presenceOptions{})+ expectTrue(t, "hostPaused must be true", replacementAuth.HostPaused != nil && *replacementAuth.HostPaused)++ setSharingPaused(activeHost, shareGeneration, false)+ expectMatch(t, replacement.next("host-status").raw, `{"online":true,"paused":false}`)++ setSharingPaused(activeHost, shareGeneration, true)+ expectMatch(t, replacement.next("host-status").raw, `{"paused":true}`)+ activeHost.sendJSON(map[string]any{"type": "stop-sharing", "shareGeneration": shareGeneration})+ replacement.next("sharing-stopped")+ expectMatch(t, replacement.next("host-status").raw, `{"online":false,"paused":false}`)++ nextHost := openClient(t, h)+ authenticate(t, nextHost, h.room, protocol.RoleHost, "pause-host-client", 1, "next_pause_share_generation_12345678", presenceOptions{})+ replacement.next("sharing-stopped")+ expectMatch(t, replacement.next("host-status").raw, `{"online":false,"paused":false}`)+ expectMatch(t, replacement.next("host-status").raw, `{"online":true,"paused":false}`)+}++func TestSignalAppliesSymmetricPauseUpdatesOnlyToExactCurrentHostShare(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ shareGeneration := "hybrid_pause_share_generation_12345678"+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "hybrid-pause-host-client", 1, shareGeneration, presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "hybrid-pause-viewer-client", 1, "", presenceOptions{})++ setSharingPaused(host, shareGeneration, true)+ expectMatch(t, viewer.next("host-status").raw, `{"online":true,"paused":true}`)+ setSharingPaused(host, shareGeneration, false)+ expectMatch(t, viewer.next("host-status").raw, `{"online":true,"paused":false}`)++ setSharingPaused(host, "stale_pause_share_generation_12345678", true)+ expectCloseCode(t, host, 4001)+}++func TestSignalRetainsAuthoritativePauseWhenReconnectingHostAdvertisesUnpaused(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ shareGeneration := "reconnect_resume_share_generation_12345678"+ hostClientID := "reconnect-resume-host-client"+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, hostClientID, 1, shareGeneration, presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "reconnect-resume-viewer-client", 1, "", presenceOptions{})+ commitPreparedRoute(t, viewer)++ setSharingPaused(host, shareGeneration, true)+ expectMatch(t, viewer.next("host-status").raw, `{"online":true,"paused":true}`)+ h.closeClient(host)+ expectMatch(t, viewer.next("host-status").raw, `{"online":false,"paused":false}`)++ reconnectedHost := openClient(t, h)+ authenticate(t, reconnectedHost, h.room, protocol.RoleHost, hostClientID, 1, shareGeneration,+ presenceOptions{sharingPaused: boolPointer(false)})+ expectEqual(t, reconnectedHost.next("pause-sharing-source").raw,+ fmt.Sprintf(`{"type":"pause-sharing-source","shareGeneration":%q}`, shareGeneration))+ expectMatch(t, viewer.next("host-status").raw, `{"online":true,"paused":true}`)++ setSharingPaused(reconnectedHost, shareGeneration, false)+ expectMatch(t, viewer.next("host-status").raw, `{"online":true,"paused":false}`)+}++func TestSignalBindsNewShareQualityAndPreservesActiveShareQualityAcrossReconnect(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ initialSettings := map[string]any{+ "resolution": "1440p",+ "maxFramerate": 60,+ "maxBitrate": 8_000_000,+ "degradationPreference": "maintain-resolution",+ "screenAudioQuality": "very-high",+ }+ initialJSON := `{"resolution":"1440p","maxFramerate":60,"maxBitrate":8000000,"degradationPreference":"maintain-resolution","screenAudioQuality":"very-high"}`+ firstGeneration := "first_share_generation_12345678"+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "quality-viewer-client", 1, "", presenceOptions{})++ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "quality-host-client", 1, firstGeneration,+ presenceOptions{qualitySettings: initialSettings})+ expectEqual(t, hostAuth.QualitySettings, initialJSON)+ expectEqual(t, viewer.next("quality-settings").raw, `{"type":"quality-settings","qualitySettings":`+initialJSON+`}`)++ reconnectSettings := map[string]any{+ "resolution": "480p",+ "maxFramerate": 15,+ "maxBitrate": 2_000_000,+ "degradationPreference": "maintain-framerate",+ "screenAudioQuality": "saver",+ }+ reconnectJSON := `{"resolution":"480p","maxFramerate":15,"maxBitrate":2000000,"degradationPreference":"maintain-framerate","screenAudioQuality":"saver"}`+ reconnectedHost := openClient(t, h)+ reconnectedAuth := authenticate(t, reconnectedHost, h.room, protocol.RoleHost, "quality-host-client", 1, firstGeneration,+ presenceOptions{qualitySettings: reconnectSettings})+ expectCloseCode(t, host, 4001)+ expectEqual(t, reconnectedAuth.QualitySettings, initialJSON)+ if message, ok := viewer.tryNext("quality-settings", 30*time.Millisecond); ok {+ t.Fatalf("unexpected quality-settings: %s", message.raw)+ }++ updatedSettings := map[string]any{+ "resolution": "720p",+ "maxFramerate": 30,+ "maxBitrate": 3_000_000,+ "degradationPreference": "balanced",+ "screenAudioQuality": "music",+ }+ updatedJSON := `{"resolution":"720p","maxFramerate":30,"maxBitrate":3000000,"degradationPreference":"balanced","screenAudioQuality":"music"}`+ reconnectedHost.sendJSON(map[string]any{"type": "set-quality-settings", "qualitySettings": updatedSettings})+ expectEqual(t, viewer.next("quality-settings").raw, `{"type":"quality-settings","qualitySettings":`+updatedJSON+`}`)++ reconnectedHost.sendJSON(map[string]any{"type": "stop-sharing", "shareGeneration": firstGeneration})+ expectCloseCode(t, reconnectedHost, 1000)+ viewer.next("sharing-stopped")++ nextHost := openClient(t, h)+ nextAuth := authenticate(t, nextHost, h.room, protocol.RoleHost, "quality-host-client", 1, "next_share_generation_12345678",+ presenceOptions{qualitySettings: reconnectSettings})+ expectEqual(t, nextAuth.QualitySettings, reconnectJSON)+ expectEqual(t, viewer.next("quality-settings").raw, `{"type":"quality-settings","qualitySettings":`+reconnectJSON+`}`)+}++// ---------------------------------------------------------------------------+// grace, reconnect and media identity+// ---------------------------------------------------------------------------++func TestSignalKeepsViewerPeerStableWhenItReconnectsInsideGracePeriod(t *testing.T) {+ h := startHarness(t, harnessOptions{viewerDisconnectGraceMs: 80})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "host-client-stable", 1, "", presenceOptions{})+ firstViewer := openClient(t, h)+ firstAuth := authenticate(t, firstViewer, h.room, protocol.RoleViewer, "viewer-client-stable", 1, "", presenceOptions{})+ activeRoute := commitPreparedRoute(t, firstViewer)+ nextActiveRouteRevision(t, host, activeRoute.Revision)+ host.sendJSON(signalDescription(firstAuth.PeerID, "stable-connection", "offer"))+ firstViewer.next("signal")++ h.closeClient(firstViewer)+ reconnectedViewer := openClient(t, h)+ reconnectedAuth := authenticate(t, reconnectedViewer, h.room, protocol.RoleViewer, "viewer-client-stable", 1, "", presenceOptions{})+ expectString(t, "peer", reconnectedAuth.PeerID, firstAuth.PeerID)+ if reconnectedAuth.ConnectionID == nil || *reconnectedAuth.ConnectionID != "stable-connection" {+ t.Fatalf("connectionId: %v", reconnectedAuth.ConnectionID)+ }+ nextActiveRouteRevision(t, host, reconnectedAuth.RouteRevision)+ host.expectNone(110 * time.Millisecond)++ h.closeClient(reconnectedViewer)+ nextActiveRouteAfter(t, host, activeRoute.Revision)+ host.sendJSON(map[string]any{"type": "request-route-diagnostic"})+ expectMatch(t, host.next("route-diagnostic-snapshot").raw, `{"snapshot":{"children":[]}}`)+}++func TestSignalClearsPreviousMediaGenerationWhenSharingStops(t *testing.T) {+ h := startHarness(t, harnessOptions{viewerDisconnectGraceMs: 300})+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "host-client-stop", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ viewerAuth := authenticate(t, viewer, h.room, protocol.RoleViewer, "viewer-client-stop", 1, "", presenceOptions{})+ commitPreparedRoute(t, viewer)+ host.sendJSON(signalDescription(viewerAuth.PeerID, "connection-before-stop", "offer"))+ viewer.next("signal")++ host.sendJSON(map[string]any{"type": "stop-sharing"})+ viewer.next("sharing-stopped")+ expectMatch(t, viewer.next("host-status").raw, `{"online":false}`)+ expectCloseCode(t, host, 1000)+ h.closeClient(viewer)++ reconnected := openClient(t, h)+ reconnectedAuth := authenticate(t, reconnected, h.room, protocol.RoleViewer, "viewer-client-stop", 1, "", presenceOptions{})+ expectTrue(t, "connectionId must be null", reconnectedAuth.ConnectionID == nil)+ expectString(t, "peer", reconnectedAuth.PeerID, viewerAuth.PeerID)+ expectTrue(t, "host must be offline", !reconnectedAuth.HostOnline)+}++func TestSignalReplacesSameClientPresenceWithoutTransientLeaveChurn(t *testing.T) {+ h := startHarness(t, harnessOptions{viewerDisconnectGraceMs: 40})+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "host-client-stable", 1, "", presenceOptions{viewerPresence: true})+ if entries := viewerPresenceEntries(parsePresence(t, host.next("viewer-presence").raw)); len(entries) != 0 {+ t.Fatalf("initial roster: %v", entries)+ }+ original := openClient(t, h)+ originalAuth := authenticate(t, original, h.room, protocol.RoleViewer, "viewer-client-stable", 1, "",+ presenceOptions{displayName: "旧会话"})+ commitPreparedRoute(t, original)+ expectMatch(t, viewerEntriesJSON(t, nextViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return slices.ContainsFunc(viewerPresenceEntries(message), func(entry presenceEntry) bool {+ return entry.Upstream.Kind == "peer"+ })+ })), fmt.Sprintf(+ `[{"role":"viewer","peerId":%q,"displayName":"旧会话","upstream":{"kind":"peer","peerId":%q}}]`,+ originalAuth.PeerID, hostAuth.PeerID))++ replacement := openClient(t, h)+ replacementAuth := authenticate(t, replacement, h.room, protocol.RoleViewer, "viewer-client-stable", 1, "",+ presenceOptions{displayName: "新会话"})++ expectString(t, "peer", replacementAuth.PeerID, originalAuth.PeerID)+ expectCloseCode(t, original, 4001)+ expectMatch(t, viewerEntriesJSON(t, parsePresence(t, host.next("viewer-presence").raw)), fmt.Sprintf(+ `[{"role":"viewer","peerId":%q,"displayName":"新会话","upstream":{"kind":"peer","peerId":%q}}]`,+ originalAuth.PeerID, hostAuth.PeerID))+ expectNoViewerPresenceMatching(t, host, func(message presenceMessage) bool {+ return !slices.ContainsFunc(viewerPresenceEntries(message), func(entry presenceEntry) bool {+ return entry.PeerID == originalAuth.PeerID+ })+ }, 70*time.Millisecond)+}++func TestSignalNotifiesHostWhenPreOfferViewerReconnectsInsideGrace(t *testing.T) {+ h := startHarness(t, harnessOptions{viewerDisconnectGraceMs: 300})+ originalViewer := openClient(t, h)+ originalAuth := authenticate(t, originalViewer, h.room, protocol.RoleViewer, "viewer-client-before-offer", 1, "", presenceOptions{})+ h.closeClient(originalViewer)++ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "host-client-stable", 1, "", presenceOptions{})+ nextActiveRouteRevision(t, host, hostAuth.RouteRevision)++ reconnectedViewer := openClient(t, h)+ reconnectedAuth := authenticate(t, reconnectedViewer, h.room, protocol.RoleViewer, "viewer-client-before-offer", 1, "", presenceOptions{})+ expectString(t, "peer", reconnectedAuth.PeerID, originalAuth.PeerID)+ prepared := nextPreparedRoute(t, host)+ expectMatch(t, prepared.raw, fmt.Sprintf(+ `{"candidate":{"childPeerId":%q,"transport":"direct","qualityProbe":false}}`, originalAuth.PeerID))+}++func TestSignalReplaysViewersWhenHostReconnects(t *testing.T) {+ h := startHarness(t, harnessOptions{viewerDisconnectGraceMs: 500})+ viewer := openClient(t, h)+ viewerAuth := authenticate(t, viewer, h.room, protocol.RoleViewer, "viewer-client-stable", 1, "", presenceOptions{})+ firstHost := openClient(t, h)+ firstHostAuth := authenticate(t, firstHost, h.room, protocol.RoleHost, "host-client-stable", 1, "", presenceOptions{})+ commitPreparedRoute(t, viewer)+ viewer.next("host-status")+ firstHost.sendJSON(signalDescription(viewerAuth.PeerID, "connection-before-control-outage", "offer"))+ viewer.next("signal")++ h.closeClient(firstHost)+ expectMatch(t, viewer.next("host-status").raw, `{"online":false}`)+ h.closeClient(viewer)+ refreshedViewer := openClient(t, h)+ refreshedViewerAuth := authenticate(t, refreshedViewer, h.room, protocol.RoleViewer, "viewer-client-stable", 1, "", presenceOptions{})+ expectString(t, "peer", refreshedViewerAuth.PeerID, viewerAuth.PeerID)+ expectTrue(t, "host must be offline", !refreshedViewerAuth.HostOnline)++ secondHost := openClient(t, h)+ secondHostAuth := authenticate(t, secondHost, h.room, protocol.RoleHost, "host-client-stable", 1, "", presenceOptions{})+ expectString(t, "host peer", secondHostAuth.PeerID, firstHostAuth.PeerID)+ var viewerPeerIDs []string+ h.locked(func() { viewerPeerIDs = h.store.GetViewerPeerIDs(h.room.RoomID) })+ expectStrings(t, "viewer peers", viewerPeerIDs, []string{viewerAuth.PeerID})+ nextActiveRouteRevision(t, secondHost, secondHostAuth.RouteRevision)+ expectMatch(t, refreshedViewer.next("host-status").raw, `{"online":true}`)+}++func TestSignalReconcilesEmptyRosterAfterViewerGracePeriodEndsOffline(t *testing.T) {+ h := startHarness(t, harnessOptions{viewerDisconnectGraceMs: 30})+ firstHost := openClient(t, h)+ firstHostAuth := authenticate(t, firstHost, h.room, protocol.RoleHost, "host-client-roster", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "viewer-client-roster", 1, "", presenceOptions{})+ commitPreparedRoute(t, viewer)++ h.closeClient(firstHost)+ h.closeClient(viewer)+ time.Sleep(70 * time.Millisecond)++ secondHost := openClient(t, h)+ secondHostAuth := authenticate(t, secondHost, h.room, protocol.RoleHost, "host-client-roster", 1, "", presenceOptions{})+ expectString(t, "host peer", secondHostAuth.PeerID, firstHostAuth.PeerID)+ var viewerPeerIDs []string+ h.locked(func() { viewerPeerIDs = h.store.GetViewerPeerIDs(h.room.RoomID) })+ if len(viewerPeerIDs) != 0 {+ t.Fatalf("viewer peers: %v", viewerPeerIDs)+ }+ nextActiveRouteRevision(t, secondHost, secondHostAuth.RouteRevision)+ secondHost.expectNone(30 * time.Millisecond)+}++func TestSignalKeepsMediaIdentityThroughGraceWhilePresenceReturnsOnce(t *testing.T) {+ h := startHarness(t, harnessOptions{viewerDisconnectGraceMs: 500})+ firstHost := openClient(t, h)+ firstHostAuth := authenticate(t, firstHost, h.room, protocol.RoleHost, "host-client-grace-roster", 1, "",+ presenceOptions{viewerPresence: true})+ if entries := viewerPresenceEntries(parsePresence(t, firstHost.next("viewer-presence").raw)); len(entries) != 0 {+ t.Fatalf("initial roster: %v", entries)+ }+ firstViewer := openClient(t, h)+ firstViewerAuth := authenticate(t, firstViewer, h.room, protocol.RoleViewer, "viewer-client-grace-roster", 1, "",+ presenceOptions{displayName: "短线重连"})+ commitPreparedRoute(t, firstViewer)+ expectMatch(t, viewerEntriesJSON(t, nextViewerPresenceMatching(t, firstHost, func(message presenceMessage) bool {+ return slices.ContainsFunc(viewerPresenceEntries(message), func(entry presenceEntry) bool {+ return entry.Upstream.Kind == "peer"+ })+ })), fmt.Sprintf(+ `[{"role":"viewer","peerId":%q,"displayName":"短线重连","upstream":{"kind":"peer","peerId":%q}}]`,+ firstViewerAuth.PeerID, firstHostAuth.PeerID))+ firstHost.sendJSON(signalDescription(firstViewerAuth.PeerID, "connection-during-grace", "offer"))+ firstViewer.next("signal")++ h.closeClient(firstViewer)+ if entries := viewerPresenceEntries(parsePresence(t, firstHost.next("viewer-presence").raw)); len(entries) != 0 {+ t.Fatalf("roster after viewer left: %v", entries)+ }+ h.closeClient(firstHost)++ secondHost := openClient(t, h)+ secondHostAuth := authenticate(t, secondHost, h.room, protocol.RoleHost, "host-client-grace-roster", 1, "",+ presenceOptions{viewerPresence: true})+ var viewerPeerIDs []string+ h.locked(func() { viewerPeerIDs = h.store.GetViewerPeerIDs(h.room.RoomID) })+ expectStrings(t, "viewer peers", viewerPeerIDs, []string{firstViewerAuth.PeerID})+ if entries := viewerPresenceEntries(parsePresence(t, secondHost.next("viewer-presence").raw)); len(entries) != 0 {+ t.Fatalf("second host roster: %v", entries)+ }++ secondViewer := openClient(t, h)+ secondViewerAuth := authenticate(t, secondViewer, h.room, protocol.RoleViewer, "viewer-client-grace-roster", 1, "",+ presenceOptions{displayName: "短线重连"})+ expectString(t, "peer", secondViewerAuth.PeerID, firstViewerAuth.PeerID)+ if secondViewerAuth.ConnectionID == nil || *secondViewerAuth.ConnectionID != "connection-during-grace" {+ t.Fatalf("connectionId: %v", secondViewerAuth.ConnectionID)+ }+ expectEqual(t, viewerEntriesJSON(t, nextViewerPresenceMatching(t, secondHost, func(message presenceMessage) bool {+ return slices.ContainsFunc(viewerPresenceEntries(message), func(entry presenceEntry) bool {+ return entry.PeerID == firstViewerAuth.PeerID+ })+ })), fmt.Sprintf(+ `[{"role":"viewer","peerId":%q,"displayName":"短线重连","upstream":{"kind":"peer","peerId":%q},"mediaReady":true}]`,+ firstViewerAuth.PeerID, secondHostAuth.PeerID))+ expectNoViewerPresenceMatching(t, secondHost, func(message presenceMessage) bool {+ return !slices.ContainsFunc(viewerPresenceEntries(message), func(entry presenceEntry) bool {+ return entry.PeerID == firstViewerAuth.PeerID+ })+ }, 30*time.Millisecond)++ secondViewer.sendJSON(map[string]any{+ "type": "restart-request",+ "targetPeerId": secondHostAuth.PeerID,+ "connectionId": *secondViewerAuth.ConnectionID,+ "rebuild": false,+ })+ expectMatch(t, secondHost.next("restart-request").raw, fmt.Sprintf(+ `{"fromPeerId":%q,"connectionId":"connection-during-grace","rebuild":false}`, firstViewerAuth.PeerID))+}++// ---------------------------------------------------------------------------+// capacity and abandonment+// ---------------------------------------------------------------------------++func TestSignalStopsSharingWithoutDeletingRoomAndRestrictsRoomAbandonment(t *testing.T) {+ maxViewersPerRoom := 5+ h := startHarness(t, harnessOptions{maxViewersPerRoom: maxViewersPerRoom})+ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "host-client-stable", 1, "", presenceOptions{})+ if hostAuth.MaxViewers != maxViewersPerRoom {+ t.Fatalf("maxViewers %d", hostAuth.MaxViewers)+ }+ var viewers []*testClient+ for index := 1; index <= maxViewersPerRoom; index++ {+ viewer := openClient(t, h)+ viewerAuth := authenticate(t, viewer, h.room, protocol.RoleViewer, fmt.Sprintf("viewer-client-%d", index), 1, "", presenceOptions{})+ if viewerAuth.MaxViewers != maxViewersPerRoom {+ t.Fatalf("viewer maxViewers %d", viewerAuth.MaxViewers)+ }+ commitPreparedRoute(t, viewer)+ viewers = append(viewers, viewer)+ }++ overflow := openClient(t, h)+ overflow.sendJSON(map[string]any{+ "type": "authenticate",+ "protocol": protocol.SignalingProtocol,+ "roomId": h.room.RoomID,+ "role": protocol.RoleViewer,+ "viewerGrant": h.room.ViewerGrant,+ "clientId": fmt.Sprintf("viewer-client-%d", maxViewersPerRoom+1),+ })+ expectMatch(t, overflow.next("error").raw, `{"code":"ROOM_FULL"}`)++ host.sendJSON(map[string]any{"type": "stop-sharing"})+ for _, viewer := range viewers {+ expectEqual(t, viewer.next("sharing-stopped").raw, `{"type":"sharing-stopped"}`)+ expectMatch(t, viewer.next("host-status").raw, `{"online":false}`)+ }+ expectCloseCode(t, host, 1000)+ if size := h.storeSize(); size != 1 {+ t.Fatalf("store size %d", size)+ }++ viewers[0].sendJSON(map[string]any{"type": "abandon-room"})+ expectMatch(t, viewers[0].next("error").raw, `{"code":"FORBIDDEN"}`)+ if size := h.storeSize(); size != 1 {+ t.Fatalf("store size %d", size)+ }++ abandonHost := openClient(t, h)+ authenticate(t, abandonHost, h.room, protocol.RoleHost, "host-client-stable", 1, "", presenceOptions{})+ abandonHost.sendJSON(map[string]any{"type": "abandon-room"})+ expectMatch(t, abandonHost.next("room-closed").raw, `{"reason":"host-ended"}`)+ for _, viewer := range viewers {+ expectMatch(t, viewer.next("room-closed").raw, `{"reason":"host-ended"}`)+ }+ if size := h.storeSize(); size != 0 {+ t.Fatalf("store size %d", size)+ }+}++// ---------------------------------------------------------------------------+// transport hardening+// ---------------------------------------------------------------------------++func TestSignalRequiresAllowedOriginTimelyAuthenticationAndBoundedPayloads(t *testing.T) {+ h := startHarness(t, harnessOptions{authenticationTimeoutMs: 30})+ if status := rejectedUpgradeStatus(t, h, allowedOrigin+"/path"); status != 403 {+ t.Fatalf("origin with path: %d", status)+ }+ if status := rejectedUpgradeStatus(t, h, "https://foreign.example.test"); status != 403 {+ t.Fatalf("foreign origin: %d", status)+ }++ unauthenticated := openClient(t, h)+ expectMatch(t, unauthenticated.nextWithin("error", 300*time.Millisecond).raw, `{"code":"AUTH_REQUIRED"}`)+ expectCloseCode(t, unauthenticated, 4003)++ oversized := openClient(t, h)+ oversized.sendText(strings.Repeat("x", protocol.MaxSignalBytes+1))+ expectCloseCode(t, oversized, 1009)+}++func TestSignalTerminatesStaleV12BeforeAuthentication(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ invalidClient := openClient(t, h)+ invalidClient.sendJSON(map[string]any{+ "type": "authenticate",+ "protocol": "screener-v12",+ "roomId": h.room.RoomID,+ "role": protocol.RoleViewer,+ "clientId": "invalid-client",+ })+ expectMatch(t, invalidClient.next("error").raw, `{"code":"INVALID_MESSAGE"}`)+ expectClose(t, invalidClient, 1008, "Invalid message")+}++func TestSignalRejectsInvalidUpgradeRequestTargetWithoutStoppingServer(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ for _, testCase := range []struct{ target, status string }{+ // new URL("//[", "http://localhost") throws (signaling.ts:186-190).+ {"//[", "HTTP/1.1 400 Bad Request"},+ // WHATWG pathname is not percent-decoded, so this is not "/signal".+ {"/%73ignal", "HTTP/1.1 404 Not Found"},+ } {+ response := rawUpgradeResponse(t, h, testCase.target)+ if !strings.HasPrefix(response, testCase.status) {+ t.Fatalf("target %q: raw response %q, want %s", testCase.target, response, testCase.status)+ }+ }++ host := openClient(t, h)+ hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "host-after-invalid-url", 1, "", presenceOptions{})+ expectString(t, "role", hostAuth.Role, protocol.RoleHost)+}++func TestSignalRejectsUnauthenticatedAndTotalConnectionOverflowBeforeUpgrade(t *testing.T) {+ h := startHarness(t, harnessOptions{maxSignalConnections: 2, maxUnauthenticatedSignalConnections: 1})+ host := openClient(t, h)+ if status := rejectedUpgradeStatus(t, h, allowedOrigin); status != 503 {+ t.Fatalf("unauthenticated overflow: %d", status)+ }++ authenticate(t, host, h.room, protocol.RoleHost, "capacity-host", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "capacity-viewer", 1, "", presenceOptions{})+ if status := rejectedUpgradeStatus(t, h, allowedOrigin); status != 503 {+ t.Fatalf("total overflow: %d", status)+ }+}++// ---------------------------------------------------------------------------+// Go-only coverage: the TS suite never exercised the heartbeat (it ran at+// 60 s) or the outbound buffer bound; both are new concurrency code here.+// ---------------------------------------------------------------------------++// timerQueue is an AfterFunc whose callbacks fire only on demand.+type timerQueue struct {+ mu sync.Mutex+ entries []*queuedTimer+}++type queuedTimer struct {+ duration time.Duration+ fn func()+ stopped bool+}++func (m *timerQueue) afterFunc(duration time.Duration, fn func()) func() bool {+ m.mu.Lock()+ defer m.mu.Unlock()+ entry := &queuedTimer{duration: duration, fn: fn}+ m.entries = append(m.entries, entry)+ return func() bool {+ m.mu.Lock()+ defer m.mu.Unlock()+ stopped := !entry.stopped+ entry.stopped = true+ return stopped+ }+}++// fire runs every pending callback armed with exactly duration.+func (m *timerQueue) fire(duration time.Duration) {+ m.fireWhere(func(armed time.Duration) bool { return armed == duration })+}++// fireDue runs every pending callback armed with less than limit.+func (m *timerQueue) fireDue(limit time.Duration) {+ m.fireWhere(func(armed time.Duration) bool { return armed < limit })+}++func (m *timerQueue) fireWhere(due func(time.Duration) bool) {+ m.mu.Lock()+ var fired []*queuedTimer+ m.entries = slices.DeleteFunc(m.entries, func(entry *queuedTimer) bool {+ if entry.stopped {+ return true+ }+ if due(entry.duration) {+ fired = append(fired, entry)+ return true+ }+ return false+ })+ m.mu.Unlock()+ for _, entry := range fired {+ entry.fn()+ }+}++func TestSignalHeartbeatTerminatesSilentConnectionAfterMissedPong(t *testing.T) {+ timers := &timerQueue{}+ h := startHarness(t, harnessOptions{afterFunc: timers.afterFunc, cleanupIntervalMs: 30_000})+ heartbeat := 60_000 * time.Millisecond+ responsive := openClient(t, h)+ header := http.Header{}+ header.Set("Origin", allowedOrigin)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ silentConn, _, err := websocket.Dial(ctx, h.wsURL, &websocket.DialOptions{+ HTTPHeader: header,+ // A false return suppresses the pong.+ OnPingReceived: func(context.Context, []byte) bool { return false },+ })+ if err != nil {+ t.Fatalf("websocket.Dial: %v", err)+ }+ silent := newTestClient(t, silentConn)+ // The client sees the 101 before the server goroutine registers the+ // session under mu (the slot itself is already reserved), so wait.+ if !waitFor(t, defaultWait, func() bool { return h.sessionCount() == 2 }) {+ t.Fatalf("sessions: %d", h.sessionCount())+ }++ aliveSessions := func() int {+ alive := 0+ h.locked(func() {+ for sess := range h.server.sessions.All() {+ if sess.alive {+ alive+++ }+ }+ })+ return alive+ }+ timers.fire(heartbeat)+ if !waitFor(t, defaultWait, func() bool { return aliveSessions() == 1 }) {+ t.Fatalf("expected exactly the responsive session to answer the ping, alive=%d", aliveSessions())+ }+ timers.fire(heartbeat)+ silent.closeCode()+ if !waitFor(t, defaultWait, func() bool { return h.sessionCount() == 1 }) {+ t.Fatalf("silent session was not terminated")+ }+ expectTrue(t, "responsive client must stay open", !responsive.isClosed())+ hostAuth := authenticate(t, responsive, h.room, protocol.RoleHost, "heartbeat-host", 1, "", presenceOptions{})+ expectString(t, "role", hostAuth.Role, protocol.RoleHost)+}++func TestSignalTerminatesConnectionAboveOutboundBufferBound(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ over := newSession(nil, true)+ closed := newSession(nil, true)+ h.locked(func() {+ over.queuedBytes = maxBufferedSignalBytes + 1+ h.server.sendEncoded(over, []byte("{}"))+ closed.close(websocket.StatusNormalClosure, "bye")+ h.server.sendEncoded(closed, []byte("{}"))+ })+ expectTrue(t, "a session above the bound is terminated, not queued", over.terminated && len(over.queue) == 0)+ expectTrue(t, "a closing session drops sends without terminating", !closed.terminated && len(closed.queue) == 1)+}++// TS signaling.ts:233-259: close() set `closing` and ran the router's close()+// up to its first await in the same tick, so no router timer could act in+// between. In Go a deadline callback parked on mu while Close runs must find+// the router already closing; otherwise it advances the operation and starts+// a pump that creates a LiveKit room during shutdown. The interleaving is+// forced through sync.Mutex starvation mode: a waiter that has waited over+// 1 ms and wakes to a locked mutex switches it to starvation mode, after+// which Unlock hands the lock to the front waiter in FIFO order, so Close+// (queued first) runs its locked prefix and its Unlock hands the lock+// straight to the callback (queued second) with no chance to re-acquire.+func TestSignalCloseMarksRouterClosingBeforeReleasingTheLock(t *testing.T) {+ timers := &timerQueue{}+ now := newClock(utcMillis(2026, time.August, 24, 12))+ control := sfutest.New()+ h := startHarness(t, harnessOptions{+ afterFunc: timers.afterFunc,+ now: now.now,+ sfu: &SfuFallback{+ URL: "wss://sfu.example.test",+ TokenIssuer: &fakeTokenIssuer{},+ Admission: sfu.NewAdmission(sfu.AdmissionOptions{IngressCapacity: 2, EgressCapacity: 20}),+ RoomControl: control,+ PrepareTimeoutMs: 300,+ },+ })+ host := openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "close-window-host", 1, "", presenceOptions{})+ viewer := openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "close-window-viewer", 1, "", presenceOptions{})+ // The direct candidate is prepared; once the pump driver settles its+ // boundary deadline (150 ms) is the only short timer armed.+ nextPreparedRoute(t, viewer)+ routerIdle := func() bool {+ idle := false+ h.locked(func() { idle = h.server.router.inflight == 0 })+ return idle+ }+ if !waitFor(t, defaultWait, routerIdle) {+ t.Fatal("pump driver did not settle")+ }+ now.advance(150)++ h.server.mu.Lock()+ closed := make(chan error, 1)+ go func() {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ closed <- h.server.Close(ctx)+ }()+ time.Sleep(50 * time.Millisecond) // Close is queued on mu first...+ fired := make(chan struct{})+ go func() {+ timers.fireDue(time.Minute) // ...the deadline callback second.+ close(fired)+ }()+ time.Sleep(50 * time.Millisecond)+ // Wake Close and take the lock back before it runs: it finds the mutex+ // locked after a long wait, flips starvation mode and requeues at the+ // front. From here every Unlock is a FIFO handoff.+ h.server.mu.Unlock()+ h.server.mu.Lock()+ time.Sleep(50 * time.Millisecond)+ h.server.mu.Unlock()++ if err := <-closed; err != nil {+ t.Fatalf("Close: %v", err)+ }+ <-fired+ if !waitFor(t, defaultWait, routerIdle) {+ t.Fatal("router goroutines did not settle after Close")+ }+ if created := control.Created(); len(created) != 0 {+ t.Fatalf("a deadline firing during Close created %d LiveKit room(s)", len(created))+ }+ h.close()+}diff --git a/internal/server/signal/session.go b/internal/server/signal/session.gonew file mode 100644index 00000000..db33c52f--- /dev/null+++ b/internal/server/signal/session.go@@ -0,0 +1,305 @@+package signal++// The per-connection state of src/server/signaling.ts (SocketState,+// accept(), the socket event handlers, send()/sendEncodedToSession(),+// heartbeat()). One reader goroutine and one writer goroutine per+// connection; the writer drains an outbound queue that handlers fill under+// mu, which is what the ws library's own send buffer did (D4).++import (+ "context"+ "time"++ "github.com/coder/websocket"++ "github.com/TNTcraftHIM/Screener/internal/server/protocol"+)++// authenticatedSession is AuthenticatedSession. Handlers compare it by+// pointer (hazard 1): `state.authenticated !== authenticated` detects a+// re-authentication between dispatch and use. shareGeneration is "" where+// the TS had null; displayName is nil where the TS had null.+type authenticatedSession struct {+ roomID string+ role protocol.Role+ peerID string+ shareGeneration string+ displayName *string+ viewerPresence bool+}++// outbound is one queue item: a text frame or the close frame that ends the+// connection.+type outbound struct {+ data []byte+ close bool+ code websocket.StatusCode+ reason string+}++// session is SocketState plus the connection it belongs to. Every field is+// guarded by Server.mu except conn, ctx, cancel, wake and readerDone, which+// are immutable after accept.+type session struct {+ conn *websocket.Conn+ // ctx is cancelled by terminate(); coder/websocket closes the socket+ // when the context of a pending Read or Write expires, which is the+ // `socket.terminate()` of the TS.+ ctx context.Context+ cancel context.CancelFunc++ sessionID string+ alive bool+ siteAccessAuthenticated bool+ revoked bool+ authenticating bool+ // challenged is `lastSignalingChallengeAtMs !== undefined`.+ challenged bool+ lastSignalingChallengeAtMs int64+ authenticated *authenticatedSession++ // authStop stops the authentication deadline (T3); authGeneration is+ // bumped whenever the TS cleared the timer so a callback that lost the+ // Stop race sees it is stale (D5).+ authStop func() bool+ authGeneration uint64++ // queue is the ws send buffer; queuedBytes is its bufferedAmount.+ queue []outbound+ queuedBytes int+ wake chan struct{}+ // closeQueued is readyState !== OPEN once close() was called: later+ // sends are dropped and later closes are no-ops, as with ws.+ closeQueued bool+ terminated bool+ readerDone chan struct{}+}++func newSession(conn *websocket.Conn, siteAccessAuthenticated bool) *session {+ ctx, cancel := context.WithCancel(context.Background())+ return &session{+ conn: conn,+ ctx: ctx,+ cancel: cancel,+ sessionID: opaqueID(),+ alive: true,+ siteAccessAuthenticated: siteAccessAuthenticated,+ wake: make(chan struct{}, 1),+ readerDone: make(chan struct{}),+ }+}++// open is `socket.readyState === WebSocket.OPEN`.+func (sess *session) open() bool {+ return !sess.closeQueued && !sess.terminated+}++func (sess *session) notify() {+ select {+ case sess.wake <- struct{}{}:+ default:+ }+}++// enqueue appends a text frame. mu must be held.+func (sess *session) enqueue(encoded []byte) {+ sess.queue = append(sess.queue, outbound{data: encoded})+ sess.queuedBytes += len(encoded)+ sess.notify()+}++// close is socket.close(code, reason): a no-op unless the socket is open.+// mu must be held.+func (sess *session) close(code websocket.StatusCode, reason string) {+ if !sess.open() {+ return+ }+ sess.closeQueued = true+ sess.queue = append(sess.queue, outbound{close: true, code: code, reason: reason})+ sess.notify()+}++// terminate is socket.terminate(): abrupt, no close frame. Cancelling the+// context closes the socket from inside the library, so nothing touches the+// connection under mu. mu must be held.+func (sess *session) terminate() {+ if sess.terminated {+ return+ }+ sess.terminated = true+ sess.cancel()+}++// clearAuthenticationTimer is clearTimeout(state.authenticationTimer).+func (sess *session) clearAuthenticationTimer() {+ if sess.authStop != nil {+ sess.authStop()+ sess.authStop = nil+ }+ sess.authGeneration+++}++// accept ports accept(): the slot is counted here, the two goroutines start+// here. mu must be held.+func (s *Server) accept(conn *websocket.Conn, siteAccessAuthenticated bool) *session {+ if !s.hasConnectionCapacity() {+ go func() { _ = conn.CloseNow() }()+ return nil+ }+ sess := newSession(conn, siteAccessAuthenticated)+ s.armAuthenticationTimer(sess)+ s.sessions.Set(sess, struct{}{})+ s.sessionsByID[sess.sessionID] = sess+ s.unauthenticatedConnections+++ go s.readLoop(sess)+ go s.writeLoop(sess)+ return sess+}++// armAuthenticationTimer is the setTimeout of accept() (T3). The TS timer+// fired blind; the generation check stands in for clearTimeout.+func (s *Server) armAuthenticationTimer(sess *session) {+ generation := sess.authGeneration+ sess.authStop = s.afterFunc(time.Duration(s.authenticationTimeoutMs)*time.Millisecond, func() {+ s.mu.Lock()+ defer s.mu.Unlock()+ if sess.authGeneration != generation {+ return+ }+ sess.authStop = nil+ s.sendError(sess, "AUTH_REQUIRED", "Authentication timed out")+ sess.close(websocket.StatusCode(protocol.SignalCloseAuthenticationFailed), "Authentication required")+ })+}++// readLoop is the "message" handler plus the "close" handler: it reads until+// the connection fails and then runs handleDisconnect exactly once (D6).+func (s *Server) readLoop(sess *session) {+ defer func() {+ sess.cancel()+ s.mu.Lock()+ s.handleDisconnect(sess)+ s.mu.Unlock()+ close(sess.readerDone)+ }()+ for {+ kind, data, err := sess.conn.Read(sess.ctx)+ if err != nil {+ return+ }+ s.mu.Lock()+ if kind == websocket.MessageBinary {+ // TS: if (isBinary) rejectInvalidMessage(socket)+ s.rejectInvalidMessage(sess)+ } else {+ s.handleMessage(sess, data)+ }+ s.mu.Unlock()+ }+}++// writeLoop drains the outbound queue. Conn.Write and Conn.Close are only+// ever called here, never under mu (D4).+func (s *Server) writeLoop(sess *session) {+ for {+ s.mu.Lock()+ if len(sess.queue) == 0 {+ s.mu.Unlock()+ select {+ case <-sess.wake:+ continue+ case <-sess.ctx.Done():+ _ = sess.conn.CloseNow()+ return+ }+ }+ item := sess.queue[0]+ sess.queue[0] = outbound{}+ sess.queue = sess.queue[1:]+ s.mu.Unlock()+ if item.close {+ _ = sess.conn.Close(item.code, item.reason)+ return+ }+ err := sess.conn.Write(sess.ctx, websocket.MessageText, item.data)+ s.mu.Lock()+ sess.queuedBytes -= len(item.data)+ s.mu.Unlock()+ if err != nil {+ _ = sess.conn.CloseNow()+ return+ }+ }+}++// ping is the socket.ping() of heartbeat(), fired outside mu. The pong is+// read by readLoop; the timeout bounds the wait, it does not close the+// socket (the next heartbeat tick does, through alive).+func (sess *session) ping(timeout time.Duration) {+ ctx, cancel := context.WithTimeout(sess.ctx, timeout)+ defer cancel()+ _ = sess.conn.Ping(ctx)+}++// heartbeat ports heartbeat() (O11: insertion order). It returns the+// sessions to ping so the caller can do that after releasing mu.+func (s *Server) heartbeat() []*session {+ var pings []*session+ for sess := range s.sessions.All() {+ if !sess.alive {+ sess.terminate()+ continue+ }+ sess.alive = false+ pings = append(pings, sess)+ }+ return pings+}++// send ports send(): drop unless open, terminate above the buffer bound,+// otherwise queue the encoded message.+func (s *Server) send(sess *session, message protocol.ServerMessage) {+ encoded, err := protocol.EncodeServerMessage(message)+ if err != nil {+ // JSON.stringify of a server literal cannot fail; neither can this.+ panic(err)+ }+ s.sendEncoded(sess, encoded)+}++// sendEncoded is the shared body of send() and sendEncodedToSession().+func (s *Server) sendEncoded(sess *session, encoded []byte) {+ if !sess.open() {+ return+ }+ if sess.queuedBytes > maxBufferedSignalBytes {+ sess.terminate()+ return+ }+ sess.enqueue(encoded)+}++// sendToSession ports sendToSession().+func (s *Server) sendToSession(sessionID string, message protocol.ServerMessage) {+ if sess := s.sessionsByID[sessionID]; sess != nil {+ s.send(sess, message)+ }+}++// sendEncodedToSession ports sendEncodedToSession(): the same bytes go to+// every recipient (hazard 10).+func (s *Server) sendEncodedToSession(sessionID string, encoded []byte) {+ if sess := s.sessionsByID[sessionID]; sess != nil {+ s.sendEncoded(sess, encoded)+ }+}++func (s *Server) sendError(sess *session, code, message string) {+ s.send(sess, protocol.ErrorMessage{Type: "error", Code: code, Message: message})+}++// rejectInvalidMessage ports rejectInvalidMessage().+func (s *Server) rejectInvalidMessage(sess *session) {+ s.sendError(sess, "INVALID_MESSAGE", "Message is invalid")+ sess.close(websocket.StatusPolicyViolation, "Invalid message")+}diff --git a/internal/server/webassets/assets.go b/internal/server/webassets/assets.gonew file mode 100644index 00000000..09c8c1f2--- /dev/null+++ b/internal/server/webassets/assets.go@@ -0,0 +1,27 @@+// Package webassets embeds the built Browser UI so a single binary can serve it.+package webassets++import (+ "embed"+ "io/fs"+)++// `all:` is the only pattern that still builds on a clean checkout, where dist+// holds nothing but the tracked .gitkeep marker. It also embeds dot-prefixed+// entries, which the static handler refuses to serve.+//+//go:embed all:dist+var embedded embed.FS++// FS returns the embedded Vite build, or nil when no build was embedded. The+// probe is dist/index.html, never an entry count: .gitkeep is always there.+func FS() fs.FS {+ assets, err := fs.Sub(embedded, "dist")+ if err != nil {+ return nil+ }+ if _, err := fs.Stat(assets, "index.html"); err != nil {+ return nil+ }+ return assets+}diff --git a/internal/server/webassets/assets_test.go b/internal/server/webassets/assets_test.gonew file mode 100644index 00000000..cc7c2c83--- /dev/null+++ b/internal/server/webassets/assets_test.go@@ -0,0 +1,35 @@+package webassets++import (+ "io/fs"+ "testing"+)++// TestFSTracksIndexHTML holds whether or not a Vite build is present: FS() must+// be non-nil exactly when dist/index.html is embedded.+func TestFSTracksIndexHTML(t *testing.T) {+ _, err := fs.Stat(embedded, "dist/index.html")+ assets := FS()++ switch {+ case err == nil && assets == nil:+ t.Fatal("dist/index.html is embedded but FS() returned nil")+ case err != nil && assets != nil:+ t.Fatalf("dist/index.html is absent (%v) but FS() returned a file system", err)+ case assets == nil:+ t.Log("no build embedded: the app serves the API only")+ return+ }++ if _, err := fs.Stat(assets, "index.html"); err != nil {+ t.Fatalf("index.html is not reachable through FS(): %v", err)+ }+}++// TestGitkeepIsEmbedded pins the `all:` prefix: without it the package does not+// build on a checkout whose dist holds only the dot-prefixed marker.+func TestGitkeepIsEmbedded(t *testing.T) {+ if _, err := fs.Stat(embedded, "dist/.gitkeep"); err != nil {+ t.Fatalf("dist/.gitkeep must stay tracked and embedded: %v", err)+ }+}diff --git a/internal/server/webassets/dist/.gitkeep b/internal/server/webassets/dist/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/licenses/GPL-3.0.txt b/licenses/GPL-3.0.txtnew file mode 100644index 00000000..f288702d--- /dev/null+++ b/licenses/GPL-3.0.txt@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights.++ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++ Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++ <program> Copyright (C) <year> <name of author>+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<https://www.gnu.org/licenses/>.++ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<https://www.gnu.org/licenses/why-not-lgpl.html>.diff --git a/licenses/LGPL-3.0.txt b/licenses/LGPL-3.0.txtnew file mode 100644index 00000000..0a041280--- /dev/null+++ b/licenses/LGPL-3.0.txt@@ -0,0 +1,165 @@+ GNU LESSER GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.+++ This version of the GNU Lesser General Public License incorporates+the terms and conditions of version 3 of the GNU General Public+License, supplemented by the additional permissions listed below.++ 0. Additional Definitions.++ As used herein, "this License" refers to version 3 of the GNU Lesser+General Public License, and the "GNU GPL" refers to version 3 of the GNU+General Public License.++ "The Library" refers to a covered work governed by this License,+other than an Application or a Combined Work as defined below.++ An "Application" is any work that makes use of an interface provided+by the Library, but which is not otherwise based on the Library.+Defining a subclass of a class defined by the Library is deemed a mode+of using an interface provided by the Library.++ A "Combined Work" is a work produced by combining or linking an+Application with the Library. The particular version of the Library+with which the Combined Work was made is also called the "Linked+Version".++ The "Minimal Corresponding Source" for a Combined Work means the+Corresponding Source for the Combined Work, excluding any source code+for portions of the Combined Work that, considered in isolation, are+based on the Application, and not on the Linked Version.++ The "Corresponding Application Code" for a Combined Work means the+object code and/or source code for the Application, including any data+and utility programs needed for reproducing the Combined Work from the+Application, but excluding the System Libraries of the Combined Work.++ 1. Exception to Section 3 of the GNU GPL.++ You may convey a covered work under sections 3 and 4 of this License+without being bound by section 3 of the GNU GPL.++ 2. Conveying Modified Versions.++ If you modify a copy of the Library, and, in your modifications, a+facility refers to a function or data to be supplied by an Application+that uses the facility (other than as an argument passed when the+facility is invoked), then you may convey a copy of the modified+version:++ a) under this License, provided that you make a good faith effort to+ ensure that, in the event an Application does not supply the+ function or data, the facility still operates, and performs+ whatever part of its purpose remains meaningful, or++ b) under the GNU GPL, with none of the additional permissions of+ this License applicable to that copy.++ 3. Object Code Incorporating Material from Library Header Files.++ The object code form of an Application may incorporate material from+a header file that is part of the Library. You may convey such object+code under terms of your choice, provided that, if the incorporated+material is not limited to numerical parameters, data structure+layouts and accessors, or small macros, inline functions and templates+(ten or fewer lines in length), you do both of the following:++ a) Give prominent notice with each copy of the object code that the+ Library is used in it and that the Library and its use are+ covered by this License.++ b) Accompany the object code with a copy of the GNU GPL and this license+ document.++ 4. Combined Works.++ You may convey a Combined Work under terms of your choice that,+taken together, effectively do not restrict modification of the+portions of the Library contained in the Combined Work and reverse+engineering for debugging such modifications, if you also do each of+the following:++ a) Give prominent notice with each copy of the Combined Work that+ the Library is used in it and that the Library and its use are+ covered by this License.++ b) Accompany the Combined Work with a copy of the GNU GPL and this license+ document.++ c) For a Combined Work that displays copyright notices during+ execution, include the copyright notice for the Library among+ these notices, as well as a reference directing the user to the+ copies of the GNU GPL and this license document.++ d) Do one of the following:++ 0) Convey the Minimal Corresponding Source under the terms of this+ License, and the Corresponding Application Code in a form+ suitable for, and under terms that permit, the user to+ recombine or relink the Application with a modified version of+ the Linked Version to produce a modified Combined Work, in the+ manner specified by section 6 of the GNU GPL for conveying+ Corresponding Source.++ 1) Use a suitable shared library mechanism for linking with the+ Library. A suitable mechanism is one that (a) uses at run time+ a copy of the Library already present on the user's computer+ system, and (b) will operate properly with a modified version+ of the Library that is interface-compatible with the Linked+ Version.++ e) Provide Installation Information, but only if you would otherwise+ be required to provide such information under section 6 of the+ GNU GPL, and only to the extent that such information is+ necessary to install and execute a modified version of the+ Combined Work produced by recombining or relinking the+ Application with a modified version of the Linked Version. (If+ you use option 4d0, the Installation Information must accompany+ the Minimal Corresponding Source and Corresponding Application+ Code. If you use option 4d1, you must provide the Installation+ Information in the manner specified by section 6 of the GNU GPL+ for conveying Corresponding Source.)++ 5. Combined Libraries.++ You may place library facilities that are a work based on the+Library side by side in a single library together with other library+facilities that are not Applications and are not covered by this+License, and convey such a combined library under terms of your+choice, if you do both of the following:++ a) Accompany the combined library with a copy of the same work based+ on the Library, uncombined with any other library facilities,+ conveyed under the terms of this License.++ b) Give prominent notice with the combined library that part of it+ is a work based on the Library, and explaining where to find the+ accompanying uncombined form of the same work.++ 6. Revised Versions of the GNU Lesser General Public License.++ The Free Software Foundation may publish revised and/or new versions+of the GNU Lesser General Public License from time to time. Such new+versions will be similar in spirit to the present version, but may+differ in detail to address new problems or concerns.++ Each version is given a distinguishing version number. If the+Library as you received it specifies that a certain numbered version+of the GNU Lesser General Public License "or any later version"+applies to it, you have the option of following the terms and+conditions either of that published version or of any later version+published by the Free Software Foundation. If the Library as you+received it does not specify a version number of the GNU Lesser+General Public License, you may choose any version of the GNU Lesser+General Public License ever published by the Free Software Foundation.++ If the Library as you received it specifies that a proxy can decide+whether future versions of the GNU Lesser General Public License shall+apply, that proxy's public statement of acceptance of any version is+permanent authorization for you to choose that version for the+Library.diff --git a/licenses/README.md b/licenses/README.mdindex f540b2e8..9d19dac8 100644--- a/licenses/README.md+++ b/licenses/README.md@@ -4,19 +4,31 @@ Screener-owned code uses the root [MIT license](../LICENSE). Dependencies retaintheir own licenses; MIT does not replace their copyright notices or terms.The [pinned source index](./upstream.json) records exact upstream commits and-SHA-256 values for Node, Cloudflared, and npm packages that omit license files.+SHA-256 values for Cloudflared, libvpx, and npm packages that omit license+files.The retained text normalizes line endings and incidental whitespace only.The Cloudflared text includes its source distribution's root and all vendoredLICENSE, COPYING, and NOTICE files, including platform variants. The protobuftext also preserves Google's BSD-licensed varint attribution.The Windows capture adapter statically links libvpx; its copyright, patent grantand author list are included in the Client's native notices.+Linux packages that include the native capture binary include+`linux-system-dependencies.txt`, the full LGPL-3.0-only text for libportal, and+the full GPL-3.0 text referenced by that license. The system shared libraries+and services are not bundled; the package still carries the license texts for+the linked capture path. Packages without native capture do not include these+capture-specific notices.`npm run dev` and `npm run build:client` generate `/third-party-licenses.txt`-offline from installed, lockfile-matched Web/Server runtime dependencies.-Client assembly adds licenses for the Go toolchain and actually compiled module-packages, Node's full same-version license, and the pinned Cloudflared notices.-Missing license texts or changed pinned contents stop packaging.+offline from installed, lockfile-matched Web runtime dependencies.+The application release and Client assembly each add the Go toolchain notice+and the license files of the modules actually compiled into that binary; the+Client package also carries the pinned Cloudflared notices. Missing license+texts or changed pinned contents stop packaging.++The Linux license texts come from the GNU license pages:+`https://www.gnu.org/licenses/lgpl-3.0.txt` and+`https://www.gnu.org/licenses/gpl-3.0.txt`.Update the corresponding source text and index when a pinned runtime changes.No dependency source tree, plugin, or license-scanning dependency is bundled.diff --git a/licenses/linux-system-dependencies.txt b/licenses/linux-system-dependencies.txtnew file mode 100644index 00000000..5581d5d9--- /dev/null+++ b/licenses/linux-system-dependencies.txt@@ -0,0 +1,19 @@+Linux capture dependencies (not bundled)++The Linux native capture process dynamically uses the distribution's XDG+Desktop Portal/libportal and GStreamer packages. Screener does not redistribute+those shared libraries. The Client package carries the applicable license texts+for this linked capture path.++libportal headers and library are LGPL-3.0-only. Source:+https://github.com/flatpak/libportal/blob/main/COPYING+The full LGPL-3.0-only and GPL-3.0 texts are included in the package notice.++GStreamer and its plugins carry the license and notices of each upstream+component. The core project is LGPL-2.1-or-later; consult the installed distro+packages for the exact plugin notices. Source and licensing information:+https://gstreamer.freedesktop.org/documentation/frequently-asked-questions/licensing.html+https://gstreamer.freedesktop.org/++The runtime stack also depends on the host's Portal, PipeWire, and hardware+encoder services. Those services are not part of the Screener Client package.diff --git a/licenses/node-24.19.0.txt b/licenses/node-24.19.0.txtdeleted file mode 100644index e286d438..00000000--- a/licenses/node-24.19.0.txt+++ /dev/null@@ -1,2946 +0,0 @@-Node.js is licensed for use as follows:--"""-Copyright Node.js contributors. All rights reserved.--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to-deal in the Software without restriction, including without limitation the-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or-sell copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in-all copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS-IN THE SOFTWARE.-"""--This license applies to parts of Node.js originating from the-https://github.com/joyent/node repository:--"""-Copyright Joyent, Inc. and other Node contributors. All rights reserved.-Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to-deal in the Software without restriction, including without limitation the-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or-sell copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in-all copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS-IN THE SOFTWARE.-"""--The Node.js license applies to all parts of Node.js that are not externally-maintained libraries.--The externally maintained libraries used by Node.js are:--- Acorn, located at deps/acorn, is licensed as follows:- """- MIT License-- Copyright (C) 2012-2022 by various contributors (see AUTHORS)-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to deal- in the Software without restriction, including without limitation the rights- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in- all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN- THE SOFTWARE.- """--- c-ares, located at deps/cares, is licensed as follows:- """- MIT License-- Copyright (c) 1998 Massachusetts Institute of Technology- Copyright (c) 2007 - 2023 Daniel Stenberg with many contributors, see AUTHORS- file.-- Permission is hereby granted, free of charge, to any person obtaining a copy of- this software and associated documentation files (the "Software"), to deal in- the Software without restriction, including without limitation the rights to- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of- the Software, and to permit persons to whom the Software is furnished to do so,- subject to the following conditions:-- The above copyright notice and this permission notice (including the next- paragraph) shall be included in all copies or substantial portions of the- Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE- SOFTWARE.- """--- merve, located at deps/merve, is licensed as follows:- """- Copyright 2026 Yagiz Nizipli-- Permission is hereby granted, free of charge, to any person obtaining a copy of- this software and associated documentation files (the "Software"), to deal in- the Software without restriction, including without limitation the rights to- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of- the Software, and to permit persons to whom the Software is furnished to do so,- subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- ittapi, located at deps/v8/third_party/ittapi, is licensed as follows:- """- Copyright (c) 2019 Intel Corporation. All rights reserved.-- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:-- 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.- 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.- 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- """--- amaro, located at deps/amaro, is licensed as follows:- """- MIT License-- Copyright (c) Marco Ippolito and Amaro contributors-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to deal- in the Software without restriction, including without limitation the rights- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE- SOFTWARE.- """--- swc, located at deps/amaro/dist, is licensed as follows:- """- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright 2024 SWC contributors.-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.- """--- ICU, located at deps/icu-small, is licensed as follows:- """- UNICODE LICENSE V3-- COPYRIGHT AND PERMISSION NOTICE-- Copyright © 2016-2025 Unicode, Inc.-- NOTICE TO USER: Carefully read the following legal agreement. BY- DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR- SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE- TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT- DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.-- Permission is hereby granted, free of charge, to any person obtaining a- copy of data files and any associated documentation (the "Data Files") or- software and any associated documentation (the "Software") to deal in the- Data Files or Software without restriction, including without limitation- the rights to use, copy, modify, merge, publish, distribute, and/or sell- copies of the Data Files or Software, and to permit persons to whom the- Data Files or Software are furnished to do so, provided that either (a)- this copyright and permission notice appear with all copies of the Data- Files or Software, or (b) this copyright and permission notice appear in- associated Documentation.-- THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY- KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF- THIRD PARTY RIGHTS.-- IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE- BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,- OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,- WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,- ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA- FILES OR SOFTWARE.-- Except as contained in this notice, the name of a copyright holder shall- not be used in advertising or otherwise to promote the sale, use or other- dealings in these Data Files or Software without prior written- authorization of the copyright holder.-- SPDX-License-Identifier: Unicode-3.0-- ------------------------------------------------------------------------ Third-Party Software Licenses-- This section contains third-party software notices and/or additional- terms for licensed third-party software components included within ICU- libraries.-- ------------------------------------------------------------------------ ICU License - ICU 1.8.1 to ICU 57.1-- COPYRIGHT AND PERMISSION NOTICE-- Copyright (c) 1995-2016 International Business Machines Corporation and others- All rights reserved.-- Permission is hereby granted, free of charge, to any person obtaining- a copy of this software and associated documentation files (the- "Software"), to deal in the Software without restriction, including- without limitation the rights to use, copy, modify, merge, publish,- distribute, and/or sell copies of the Software, and to permit persons- to whom the Software is furnished to do so, provided that the above- copyright notice(s) and this permission notice appear in all copies of- the Software and that both the above copyright notice(s) and this- permission notice appear in supporting documentation.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT- OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR- HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY- SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER- RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF- CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN- CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.-- Except as contained in this notice, the name of a copyright holder- shall not be used in advertising or otherwise to promote the sale, use- or other dealings in this Software without prior written authorization- of the copyright holder.-- All trademarks and registered trademarks mentioned herein are the- property of their respective owners.-- ------------------------------------------------------------------------ Chinese/Japanese Word Break Dictionary Data (cjdict.txt)-- # The Google Chrome software developed by Google is licensed under- # the BSD license. Other software included in this distribution is- # provided under other licenses, as set forth below.- #- # The BSD License- # http://opensource.org/licenses/bsd-license.php- # Copyright (C) 2006-2008, Google Inc.- #- # All rights reserved.- #- # Redistribution and use in source and binary forms, with or without- # modification, are permitted provided that the following conditions are met:- #- # Redistributions of source code must retain the above copyright notice,- # this list of conditions and the following disclaimer.- # Redistributions in binary form must reproduce the above- # copyright notice, this list of conditions and the following- # disclaimer in the documentation and/or other materials provided with- # the distribution.- # Neither the name of Google Inc. nor the names of its- # contributors may be used to endorse or promote products derived from- # this software without specific prior written permission.- #- #- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND- # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,- # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF- # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE- # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE- # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR- # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF- # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR- # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF- # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING- # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS- # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- #- #- # The word list in cjdict.txt are generated by combining three word lists- # listed below with further processing for compound word breaking. The- # frequency is generated with an iterative training against Google web- # corpora.- #- # * Libtabe (Chinese)- # - https://sourceforge.net/project/?group_id=1519- # - Its license terms and conditions are shown below.- #- # * IPADIC (Japanese)- # - http://chasen.aist-nara.ac.jp/chasen/distribution.html- # - Its license terms and conditions are shown below.- #- # ---------COPYING.libtabe ---- BEGIN--------------------- #- # /*- # * Copyright (c) 1999 TaBE Project.- # * Copyright (c) 1999 Pai-Hsiang Hsiao.- # * All rights reserved.- # *- # * Redistribution and use in source and binary forms, with or without- # * modification, are permitted provided that the following conditions- # * are met:- # *- # * . Redistributions of source code must retain the above copyright- # * notice, this list of conditions and the following disclaimer.- # * . Redistributions in binary form must reproduce the above copyright- # * notice, this list of conditions and the following disclaimer in- # * the documentation and/or other materials provided with the- # * distribution.- # * . Neither the name of the TaBE Project nor the names of its- # * contributors may be used to endorse or promote products derived- # * from this software without specific prior written permission.- # *- # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS- # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE- # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,- # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES- # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR- # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)- # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,- # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)- # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED- # * OF THE POSSIBILITY OF SUCH DAMAGE.- # */- #- # /*- # * Copyright (c) 1999 Computer Systems and Communication Lab,- # * Institute of Information Science, Academia- # * Sinica. All rights reserved.- # *- # * Redistribution and use in source and binary forms, with or without- # * modification, are permitted provided that the following conditions- # * are met:- # *- # * . Redistributions of source code must retain the above copyright- # * notice, this list of conditions and the following disclaimer.- # * . Redistributions in binary form must reproduce the above copyright- # * notice, this list of conditions and the following disclaimer in- # * the documentation and/or other materials provided with the- # * distribution.- # * . Neither the name of the Computer Systems and Communication Lab- # * nor the names of its contributors may be used to endorse or- # * promote products derived from this software without specific- # * prior written permission.- # *- # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS- # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE- # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,- # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES- # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR- # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)- # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,- # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)- # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED- # * OF THE POSSIBILITY OF SUCH DAMAGE.- # */- #- # Copyright 1996 Chih-Hao Tsai @ Beckman Institute,- # University of Illinois- # [email protected] http://casper.beckman.uiuc.edu/~c-tsai4- #- # ---------------COPYING.libtabe-----END--------------------------------- #- #- # ---------------COPYING.ipadic-----BEGIN-------------------------------- #- # Copyright 2000, 2001, 2002, 2003 Nara Institute of Science- # and Technology. All Rights Reserved.- #- # Use, reproduction, and distribution of this software is permitted.- # Any copy of this software, whether in its original form or modified,- # must include both the above copyright notice and the following- # paragraphs.- #- # Nara Institute of Science and Technology (NAIST),- # the copyright holders, disclaims all warranties with regard to this- # software, including all implied warranties of merchantability and- # fitness, in no event shall NAIST be liable for- # any special, indirect or consequential damages or any damages- # whatsoever resulting from loss of use, data or profits, whether in an- # action of contract, negligence or other tortuous action, arising out- # of or in connection with the use or performance of this software.- #- # A large portion of the dictionary entries- # originate from ICOT Free Software. The following conditions for ICOT- # Free Software applies to the current dictionary as well.- #- # Each User may also freely distribute the Program, whether in its- # original form or modified, to any third party or parties, PROVIDED- # that the provisions of Section 3 ("NO WARRANTY") will ALWAYS appear- # on, or be attached to, the Program, which is distributed substantially- # in the same form as set out herein and that such intended- # distribution, if actually made, will neither violate or otherwise- # contravene any of the laws and regulations of the countries having- # jurisdiction over the User or the intended distribution itself.- #- # NO WARRANTY- #- # The program was produced on an experimental basis in the course of the- # research and development conducted during the project and is provided- # to users as so produced on an experimental basis. Accordingly, the- # program is provided without any warranty whatsoever, whether express,- # implied, statutory or otherwise. The term "warranty" used herein- # includes, but is not limited to, any warranty of the quality,- # performance, merchantability and fitness for a particular purpose of- # the program and the nonexistence of any infringement or violation of- # any right of any third party.- #- # Each user of the program will agree and understand, and be deemed to- # have agreed and understood, that there is no warranty whatsoever for- # the program and, accordingly, the entire risk arising from or- # otherwise connected with the program is assumed by the user.- #- # Therefore, neither ICOT, the copyright holder, or any other- # organization that participated in or was otherwise related to the- # development of the program and their respective officials, directors,- # officers and other employees shall be held liable for any and all- # damages, including, without limitation, general, special, incidental- # and consequential damages, arising out of or otherwise in connection- # with the use or inability to use the program or any product, material- # or result produced or otherwise obtained by using the program,- # regardless of whether they have been advised of, or otherwise had- # knowledge of, the possibility of such damages at any time during the- # project or thereafter. Each user will be deemed to have agreed to the- # foregoing by his or her commencement of use of the program. The term- # "use" as used herein includes, but is not limited to, the use,- # modification, copying and distribution of the program and the- # production of secondary products from the program.- #- # In the case where the program, whether in its original form or- # modified, was distributed or delivered to or received by a user from- # any person, organization or entity other than ICOT, unless it makes or- # grants independently of ICOT any specific warranty to the user in- # writing, such person, organization or entity, will also be exempted- # from and not be held liable to the user for any such damages as noted- # above as far as the program is concerned.- #- # ---------------COPYING.ipadic-----END------------------------------------ ------------------------------------------------------------------------ Lao Word Break Dictionary Data (laodict.txt)-- # Copyright (C) 2016 and later: Unicode, Inc. and others.- # License & terms of use: http://www.unicode.org/copyright.html- # Copyright (c) 2015 International Business Machines Corporation- # and others. All Rights Reserved.- #- # Project: https://github.com/rober42539/lao-dictionary- # Dictionary: https://github.com/rober42539/lao-dictionary/laodict.txt- # License: https://github.com/rober42539/lao-dictionary/LICENSE.txt- # (copied below)- #- # This file is derived from the above dictionary version of Nov 22, 2020- # ----------------------------------------------------------------------- # Copyright (C) 2013 Brian Eugene Wilson, Robert Martin Campbell.- # All rights reserved.- #- # Redistribution and use in source and binary forms, with or without- # modification, are permitted provided that the following conditions are met:- #- # Redistributions of source code must retain the above copyright notice, this- # list of conditions and the following disclaimer. Redistributions in binary- # form must reproduce the above copyright notice, this list of conditions and- # the following disclaimer in the documentation and/or other materials- # provided with the distribution.- #- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS- # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE- # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,- # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES- # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR- # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)- # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,- # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)- # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED- # OF THE POSSIBILITY OF SUCH DAMAGE.- # ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Burmese Word Break Dictionary Data (burmesedict.txt)-- # Copyright (c) 2014 International Business Machines Corporation- # and others. All Rights Reserved.- #- # This list is part of a project hosted at:- # github.com/kanyawtech/myanmar-karen-word-lists- #- # --------------------------------------------------------------------------- # Copyright (c) 2013, LeRoy Benjamin Sharon- # All rights reserved.- #- # Redistribution and use in source and binary forms, with or without- # modification, are permitted provided that the following conditions- # are met: Redistributions of source code must retain the above- # copyright notice, this list of conditions and the following- # disclaimer. Redistributions in binary form must reproduce the- # above copyright notice, this list of conditions and the following- # disclaimer in the documentation and/or other materials provided- # with the distribution.- #- # Neither the name Myanmar Karen Word Lists, nor the names of its- # contributors may be used to endorse or promote products derived- # from this software without specific prior written permission.- #- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND- # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,- # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF- # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE- # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS- # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,- # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED- # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,- # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON- # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR- # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF- # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF- # SUCH DAMAGE.- # ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Time Zone Database-- ICU uses the public domain data and code derived from Time Zone- Database for its time zone support. The ownership of the TZ database- is explained in BCP 175: Procedure for Maintaining the Time Zone- Database section 7.-- # 7. Database Ownership- #- # The TZ database itself is not an IETF Contribution or an IETF- # document. Rather it is a pre-existing and regularly updated work- # that is in the public domain, and is intended to remain in the- # public domain. Therefore, BCPs 78 [RFC5378] and 79 [RFC3979] do- # not apply to the TZ Database or contributions that individuals make- # to it. Should any claims be made and substantiated against the TZ- # Database, the organization that is providing the IANA- # Considerations defined in this RFC, under the memorandum of- # understanding with the IETF, currently ICANN, may act in accordance- # with all competent court orders. No ownership claims will be made- # by ICANN or the IETF Trust on the database or the code. Any person- # making a contribution to the database or code waives all rights to- # future claims in that contribution or in the TZ Database.-- ------------------------------------------------------------------------ Google double-conversion-- Copyright 2006-2011, the V8 project authors. All rights reserved.- Redistribution and use in source and binary forms, with or without- modification, are permitted provided that the following conditions are- met:-- * Redistributions of source code must retain the above copyright- notice, this list of conditions and the following disclaimer.- * Redistributions in binary form must reproduce the above- copyright notice, this list of conditions and the following- disclaimer in the documentation and/or other materials provided- with the distribution.- * Neither the name of Google Inc. nor the names of its- contributors may be used to endorse or promote products derived- from this software without specific prior written permission.-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-- ------------------------------------------------------------------------ JSON parsing library (nlohmann/json)-- File: vendor/json/upstream/single_include/nlohmann/json.hpp (only for ICU4C)-- MIT License-- Copyright (c) 2013-2022 Niels Lohmann-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to deal- in the Software without restriction, including without limitation the rights- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE- SOFTWARE.-- ------------------------------------------------------------------------ File: aclocal.m4 (only for ICU4C)- Section: pkg.m4 - Macros to locate and utilise pkg-config.-- Copyright © 2004 Scott James Remnant .- Copyright © 2012-2015 Dan Nicholson-- This program is free software; you can redistribute it and/or modify- it under the terms of the GNU General Public License as published by- the Free Software Foundation; either version 2 of the License, or- (at your option) any later version.-- This program is distributed in the hope that it will be useful, but- WITHOUT ANY WARRANTY; without even the implied warranty of- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU- General Public License for more details.-- You should have received a copy of the GNU General Public License- along with this program; if not, write to the Free Software- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA- 02111-1307, USA.-- As a special exception to the GNU General Public License, if you- distribute this file as part of a program that contains a- configuration script generated by Autoconf, you may include it under- the same distribution terms that you use for the rest of that- program.-- (The condition for the exception is fulfilled because- ICU4C includes a configuration script generated by Autoconf,- namely the `configure` script.)-- ------------------------------------------------------------------------ File: config.guess (only for ICU4C)-- This file is free software; you can redistribute it and/or modify it- under the terms of the GNU General Public License as published by- the Free Software Foundation, either version 3 of the License, or- (at your option) any later version.-- This program is distributed in the hope that it will be useful, but- WITHOUT ANY WARRANTY; without even the implied warranty of- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU- General Public License for more details.-- You should have received a copy of the GNU General Public License- along with this program; if not, see .-- As a special exception to the GNU General Public License, if you- distribute this file as part of a program that contains a- configuration script generated by Autoconf, you may include it under- the same distribution terms that you use for the rest of that- program. This Exception is an additional permission under section 7- of the GNU General Public License, version 3 ("GPLv3").-- (The condition for the exception is fulfilled because- ICU4C includes a configuration script generated by Autoconf,- namely the `configure` script.)-- ------------------------------------------------------------------------ File: install-sh (only for ICU4C)-- Copyright 1991 by the Massachusetts Institute of Technology-- Permission to use, copy, modify, distribute, and sell this software and its- documentation for any purpose is hereby granted without fee, provided that- the above copyright notice appear in all copies and that both that- copyright notice and this permission notice appear in supporting- documentation, and that the name of M.I.T. not be used in advertising or- publicity pertaining to distribution of the software without specific,- written prior permission. M.I.T. makes no representations about the- suitability of this software for any purpose. It is provided "as is"- without express or implied warranty.-- ------------------------------------------------------------------------ File: sorttable.js (only for ICU4J)-- The MIT Licence, for code from kryogenix.org-- Code downloaded from the Browser Experiments section of kryogenix.org is- licenced under the so-called MIT licence. The licence is below.-- Copyright (c) 1997-date Stuart Langridge-- Permission is hereby granted, free of charge, to any person obtaining a- copy of this software and associated documentation files (the "Software"),- to deal in the Software without restriction, including without limitation- the rights to use, copy, modify, merge, publish, distribute, sublicense,- and/or sell copies of the Software, and to permit persons to whom the- Software is furnished to do so, subject to the following conditions:-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE- SOFTWARE.- """--- libuv, located at deps/uv, is licensed as follows:- """- Copyright (c) 2015-present libuv project contributors.-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to- deal in the Software without restriction, including without limitation the- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or- sell copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in- all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS- IN THE SOFTWARE.- This license applies to parts of libuv originating from the- https://github.com/joyent/libuv repository:-- ====-- Copyright Joyent, Inc. and other Node contributors. All rights reserved.- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to- deal in the Software without restriction, including without limitation the- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or- sell copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in- all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS- IN THE SOFTWARE.-- ====-- This license applies to all parts of libuv that are not externally- maintained libraries.-- The externally maintained libraries used by libuv are:-- - tree.h (from FreeBSD), copyright Niels Provos. Two clause BSD license.-- - inet_pton and inet_ntop implementations, contained in src/inet.c, are- copyright the Internet Systems Consortium, Inc., and licensed under the ISC- license.- """--- LIEF, located at deps/LIEF, is licensed as follows:- """- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "{}"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright 2017 - 2025 R. Thomas- Copyright 2017 - 2025 Quarkslab-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.- """--- llhttp, located at deps/llhttp, is licensed as follows:- """- This software is licensed under the MIT License.-- Copyright Fedor Indutny, 2018.-- Permission is hereby granted, free of charge, to any person obtaining a- copy of this software and associated documentation files (the- "Software"), to deal in the Software without restriction, including- without limitation the rights to use, copy, modify, merge, publish,- distribute, sublicense, and/or sell copies of the Software, and to permit- persons to whom the Software is furnished to do so, subject to the- following conditions:-- The above copyright notice and this permission notice shall be included- in all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN- NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE- USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- corepack, located at deps/corepack, is licensed as follows:- """- **Copyright © Corepack contributors**-- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- undici, located at deps/undici, is licensed as follows:- """- MIT License-- Copyright (c) Matteo Collina and Undici contributors-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to deal- in the Software without restriction, including without limitation the rights- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE- SOFTWARE.- """--- postject, located at test/fixtures/postject-copy, is licensed as follows:- """- Postject is licensed for use as follows:-- """- MIT License-- Copyright (c) 2022 Postman, Inc-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to deal- in the Software without restriction, including without limitation the rights- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE- SOFTWARE.- """-- The Postject license applies to all parts of Postject that are not externally- maintained libraries.-- The externally maintained libraries used by Postject are:-- - LIEF, located at vendor/LIEF, is licensed as follows:- """- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "{}"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright 2017 - 2022 R. Thomas- Copyright 2017 - 2022 Quarkslab-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.- """- """--- OpenSSL, located at deps/openssl, is licensed as follows:- """- Apache License- Version 2.0, January 2004- https://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS- """--- Punycode.js, located at lib/punycode.js, is licensed as follows:- """- Copyright Mathias Bynens <https://mathiasbynens.be/>-- Permission is hereby granted, free of charge, to any person obtaining- a copy of this software and associated documentation files (the- "Software"), to deal in the Software without restriction, including- without limitation the rights to use, copy, modify, merge, publish,- distribute, sublicense, and/or sell copies of the Software, and to- permit persons to whom the Software is furnished to do so, subject to- the following conditions:-- The above copyright notice and this permission notice shall be- included in all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- V8, located at deps/v8, is licensed as follows:- """- This license applies to all parts of V8 that are not externally- maintained libraries. The externally maintained libraries used by V8- are:-- - PCRE test suite, located in- test/mjsunit/third_party/regexp-pcre/regexp-pcre.js. This is based on the- test suite from PCRE-7.3, which is copyrighted by the University- of Cambridge and Google, Inc. The copyright notice and license- are embedded in regexp-pcre.js.-- - Layout tests, located in test/mjsunit/third_party/object-keys. These are- based on layout tests from webkit.org which are copyrighted by- Apple Computer, Inc. and released under a 3-clause BSD license.-- - Strongtalk assembler, the basis of the files assembler-arm-inl.h,- assembler-arm.cc, assembler-arm.h, assembler-ia32-inl.h,- assembler-ia32.cc, assembler-ia32.h, assembler-x64-inl.h,- assembler-x64.cc, assembler-x64.h, assembler.cc and assembler.h.- This code is copyrighted by Sun Microsystems Inc. and released- under a 3-clause BSD license.-- - Valgrind client API header, located at third_party/valgrind/valgrind.h- This is released under the BSD license.-- - The Wasm C/C++ API headers, located at third_party/wasm-api/wasm.{h,hh}- This is released under the Apache license. The API's upstream prototype- implementation also formed the basis of V8's implementation in- src/wasm/c-api.cc.-- These libraries have their own licenses; we recommend you read them,- as their terms may differ from the terms below.-- Further license information can be found in LICENSE files located in- sub-directories.-- Copyright 2014, the V8 project authors. All rights reserved.- Redistribution and use in source and binary forms, with or without- modification, are permitted provided that the following conditions are- met:-- * Redistributions of source code must retain the above copyright- notice, this list of conditions and the following disclaimer.- * Redistributions in binary form must reproduce the above- copyright notice, this list of conditions and the following- disclaimer in the documentation and/or other materials provided- with the distribution.- * Neither the name of Google Inc. nor the names of its- contributors may be used to endorse or promote products derived- from this software without specific prior written permission.-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- """--- SipHash, located at deps/v8/src/third_party/siphash, is licensed as follows:- """- SipHash reference C implementation-- Copyright (c) 2016 Jean-Philippe Aumasson <[email protected]>-- To the extent possible under law, the author(s) have dedicated all- copyright and related and neighboring rights to this software to the public- domain worldwide. This software is distributed without any warranty.- """--- zlib, located at deps/zlib, is licensed as follows:- """- zlib.h -- interface of the 'zlib' general purpose compression library- version 1.3.1, January 22nd, 2024-- Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler-- This software is provided 'as-is', without any express or implied- warranty. In no event will the authors be held liable for any damages- arising from the use of this software.-- Permission is granted to anyone to use this software for any purpose,- including commercial applications, and to alter it and redistribute it- freely, subject to the following restrictions:-- 1. The origin of this software must not be misrepresented; you must not- claim that you wrote the original software. If you use this software- in a product, an acknowledgment in the product documentation would be- appreciated but is not required.- 2. Altered source versions must be plainly marked as such, and must not be- misrepresented as being the original software.- 3. This notice may not be removed or altered from any source distribution.-- Jean-loup Gailly Mark Adler- """--- simdjson, located at deps/simdjson, is licensed as follows:- """- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "{}"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright 2018-2025 The simdjson authors-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.- """--- simdutf, located at deps/v8/third_party/simdutf, is licensed as follows:- """- Copyright 2021 The simdutf authors-- Permission is hereby granted, free of charge, to any person obtaining a copy of- this software and associated documentation files (the "Software"), to deal in- the Software without restriction, including without limitation the rights to- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of- the Software, and to permit persons to whom the Software is furnished to do so,- subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- ada, located at deps/ada, is licensed as follows:- """- Copyright 2023 Yagiz Nizipli and Daniel Lemire-- Permission is hereby granted, free of charge, to any person obtaining a copy of- this software and associated documentation files (the "Software"), to deal in- the Software without restriction, including without limitation the rights to- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of- the Software, and to permit persons to whom the Software is furnished to do so,- subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- minimatch, located at deps/minimatch, is licensed as follows:- """- # Blue Oak Model License-- Version 1.0.0-- ## Purpose-- This license gives everyone as much permission to work with- this software as possible, while protecting contributors- from liability.-- ## Acceptance-- In order to receive this license, you must agree to its- rules. The rules of this license are both obligations- under that agreement and conditions to your license.- You must not do anything with this software that triggers- a rule that you cannot or will not follow.-- ## Copyright-- Each contributor licenses you to do everything with this- software that would otherwise infringe that contributor's- copyright in it.-- ## Notices-- You must ensure that everyone who gets a copy of- any part of this software from you, with or without- changes, also gets the text of this license or a link to- <https://blueoakcouncil.org/license/1.0.0>.-- ## Excuse-- If anyone notifies you in writing that you have not- complied with [Notices](#notices), you can keep your- license by taking all practical steps to comply within 30- days after the notice. If you do not do so, your license- ends immediately.-- ## Patent-- Each contributor licenses you to do everything with this- software that would otherwise infringe any patent claims- they can license or become able to license.-- ## Reliability-- No contributor can revoke this license.-- ## No Liability-- **_As far as the law allows, this software comes as is,- without any warranty or condition, and no contributor- will be liable to anyone for any damages related to this- software or this license, under any kind of legal claim._**- """--- npm, located at deps/npm, is licensed as follows:- """- The npm application- Copyright (c) npm, Inc. and Contributors- Licensed on the terms of The Artistic License 2.0-- Node package dependencies of the npm application- Copyright (c) their respective copyright owners- Licensed on their respective license terms-- The npm public registry at https://registry.npmjs.org- and the npm website at https://www.npmjs.com- Operated by npm, Inc.- Use governed by terms published on https://www.npmjs.com-- "Node.js"- Trademark Joyent, Inc., https://joyent.com- Neither npm nor npm, Inc. are affiliated with Joyent, Inc.-- The Node.js application- Project of Node Foundation, https://nodejs.org-- The npm Logo- Copyright (c) Mathias Pettersson and Brian Hammond-- "Gubblebum Blocky" typeface- Copyright (c) Tjarda Koster, https://jelloween.deviantart.com- Used with permission-- ---------- The Artistic License 2.0-- Copyright (c) 2000-2006, The Perl Foundation.-- Everyone is permitted to copy and distribute verbatim copies- of this license document, but changing it is not allowed.-- Preamble-- This license establishes the terms under which a given free software- Package may be copied, modified, distributed, and/or redistributed.- The intent is that the Copyright Holder maintains some artistic- control over the development of that Package while still keeping the- Package available as open source and free software.-- You are always permitted to make arrangements wholly outside of this- license directly with the Copyright Holder of a given Package. If the- terms of this license do not permit the full use that you propose to- make of the Package, you should contact the Copyright Holder and seek- a different licensing arrangement.-- Definitions-- "Copyright Holder" means the individual(s) or organization(s)- named in the copyright notice for the entire Package.-- "Contributor" means any party that has contributed code or other- material to the Package, in accordance with the Copyright Holder's- procedures.-- "You" and "your" means any person who would like to copy,- distribute, or modify the Package.-- "Package" means the collection of files distributed by the- Copyright Holder, and derivatives of that collection and/or of- those files. A given Package may consist of either the Standard- Version, or a Modified Version.-- "Distribute" means providing a copy of the Package or making it- accessible to anyone else, or in the case of a company or- organization, to others outside of your company or organization.-- "Distributor Fee" means any fee that you charge for Distributing- this Package or providing support for this Package to another- party. It does not mean licensing fees.-- "Standard Version" refers to the Package if it has not been- modified, or has been modified only in ways explicitly requested- by the Copyright Holder.-- "Modified Version" means the Package, if it has been changed, and- such changes were not explicitly requested by the Copyright- Holder.-- "Original License" means this Artistic License as Distributed with- the Standard Version of the Package, in its current version or as- it may be modified by The Perl Foundation in the future.-- "Source" form means the source code, documentation source, and- configuration files for the Package.-- "Compiled" form means the compiled bytecode, object code, binary,- or any other form resulting from mechanical transformation or- translation of the Source form.-- Permission for Use and Modification Without Distribution-- (1) You are permitted to use the Standard Version and create and use- Modified Versions for any purpose without restriction, provided that- you do not Distribute the Modified Version.-- Permissions for Redistribution of the Standard Version-- (2) You may Distribute verbatim copies of the Source form of the- Standard Version of this Package in any medium without restriction,- either gratis or for a Distributor Fee, provided that you duplicate- all of the original copyright notices and associated disclaimers. At- your discretion, such verbatim copies may or may not include a- Compiled form of the Package.-- (3) You may apply any bug fixes, portability changes, and other- modifications made available from the Copyright Holder. The resulting- Package will still be considered the Standard Version, and as such- will be subject to the Original License.-- Distribution of Modified Versions of the Package as Source-- (4) You may Distribute your Modified Version as Source (either gratis- or for a Distributor Fee, and with or without a Compiled form of the- Modified Version) provided that you clearly document how it differs- from the Standard Version, including, but not limited to, documenting- any non-standard features, executables, or modules, and provided that- you do at least ONE of the following:-- (a) make the Modified Version available to the Copyright Holder- of the Standard Version, under the Original License, so that the- Copyright Holder may include your modifications in the Standard- Version.-- (b) ensure that installation of your Modified Version does not- prevent the user installing or running the Standard Version. In- addition, the Modified Version must bear a name that is different- from the name of the Standard Version.-- (c) allow anyone who receives a copy of the Modified Version to- make the Source form of the Modified Version available to others- under-- (i) the Original License or-- (ii) a license that permits the licensee to freely copy,- modify and redistribute the Modified Version using the same- licensing terms that apply to the copy that the licensee- received, and requires that the Source form of the Modified- Version, and of any works derived from it, be made freely- available in that license fees are prohibited but Distributor- Fees are allowed.-- Distribution of Compiled Forms of the Standard Version- or Modified Versions without the Source-- (5) You may Distribute Compiled forms of the Standard Version without- the Source, provided that you include complete instructions on how to- get the Source of the Standard Version. Such instructions must be- valid at the time of your distribution. If these instructions, at any- time while you are carrying out such distribution, become invalid, you- must provide new instructions on demand or cease further distribution.- If you provide valid instructions or cease distribution within thirty- days after you become aware that the instructions are invalid, then- you do not forfeit any of your rights under this license.-- (6) You may Distribute a Modified Version in Compiled form without- the Source, provided that you comply with Section 4 with respect to- the Source of the Modified Version.-- Aggregating or Linking the Package-- (7) You may aggregate the Package (either the Standard Version or- Modified Version) with other packages and Distribute the resulting- aggregation provided that you do not charge a licensing fee for the- Package. Distributor Fees are permitted, and licensing fees for other- components in the aggregation are permitted. The terms of this license- apply to the use and Distribution of the Standard or Modified Versions- as included in the aggregation.-- (8) You are permitted to link Modified and Standard Versions with- other works, to embed the Package in a larger work of your own, or to- build stand-alone binary or bytecode versions of applications that- include the Package, and Distribute the result without restriction,- provided the result does not expose a direct interface to the Package.-- Items That are Not Considered Part of a Modified Version-- (9) Works (including, but not limited to, modules and scripts) that- merely extend or make use of the Package, do not, by themselves, cause- the Package to be a Modified Version. In addition, such works are not- considered parts of the Package itself, and are not subject to the- terms of this license.-- General Provisions-- (10) Any use, modification, and distribution of the Standard or- Modified Versions is governed by this Artistic License. By using,- modifying or distributing the Package, you accept this license. Do not- use, modify, or distribute the Package, if you do not accept this- license.-- (11) If your Modified Version has been derived from a Modified- Version made by someone other than you, you are nevertheless required- to ensure that your Modified Version complies with the requirements of- this license.-- (12) This license does not grant you the right to use any trademark,- service mark, tradename, or logo of the Copyright Holder.-- (13) This license includes the non-exclusive, worldwide,- free-of-charge patent license to make, have made, use, offer to sell,- sell, import and otherwise transfer the Package with respect to any- patent claims licensable by the Copyright Holder that are necessarily- infringed by the Package. If you institute patent litigation- (including a cross-claim or counterclaim) against any party alleging- that the Package constitutes direct or contributory patent- infringement, then this Artistic License to you shall terminate on the- date that such litigation is filed.-- (14) Disclaimer of Warranty:- THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS- IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED- WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR- NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL- LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL- BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL- DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF- ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-- --------- """--- GYP, located at tools/gyp, is licensed as follows:- """- Copyright (c) 2020 Node.js contributors. All rights reserved.- Copyright (c) 2009 Google Inc. All rights reserved.-- Redistribution and use in source and binary forms, with or without- modification, are permitted provided that the following conditions are- met:-- * Redistributions of source code must retain the above copyright- notice, this list of conditions and the following disclaimer.- * Redistributions in binary form must reproduce the above- copyright notice, this list of conditions and the following disclaimer- in the documentation and/or other materials provided with the- distribution.- * Neither the name of Google Inc. nor the names of its- contributors may be used to endorse or promote products derived from- this software without specific prior written permission.-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- """--- inspector_protocol, located at deps/inspector_protocol, is licensed as follows:- """- // Copyright 2016 The Chromium Authors.- //- // Redistribution and use in source and binary forms, with or without- // modification, are permitted provided that the following conditions are- // met:- //- // * Redistributions of source code must retain the above copyright- // notice, this list of conditions and the following disclaimer.- // * Redistributions in binary form must reproduce the above- // copyright notice, this list of conditions and the following disclaimer- // in the documentation and/or other materials provided with the- // distribution.- // * Neither the name of Google Inc. nor the names of its- // contributors may be used to endorse or promote products derived from- // this software without specific prior written permission.- //- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR- // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT- // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,- // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,- // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY- // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT- // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE- // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- """--- jinja2, located at tools/inspector_protocol/jinja2, is licensed as follows:- """- Copyright (c) 2009 by the Jinja Team, see AUTHORS for more details.-- Some rights reserved.-- Redistribution and use in source and binary forms, with or without- modification, are permitted provided that the following conditions are- met:-- * Redistributions of source code must retain the above copyright- notice, this list of conditions and the following disclaimer.-- * Redistributions in binary form must reproduce the above- copyright notice, this list of conditions and the following- disclaimer in the documentation and/or other materials provided- with the distribution.-- * The names of the contributors may not be used to endorse or- promote products derived from this software without specific- prior written permission.-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- """--- markupsafe, located at tools/inspector_protocol/markupsafe, is licensed as follows:- """- Copyright (c) 2010 by Armin Ronacher and contributors. See AUTHORS- for more details.-- Some rights reserved.-- Redistribution and use in source and binary forms of the software as well- as documentation, with or without modification, are permitted provided- that the following conditions are met:-- * Redistributions of source code must retain the above copyright- notice, this list of conditions and the following disclaimer.-- * Redistributions in binary form must reproduce the above- copyright notice, this list of conditions and the following- disclaimer in the documentation and/or other materials provided- with the distribution.-- * The names of the contributors may not be used to endorse or- promote products derived from this software without specific- prior written permission.-- THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND- CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT- NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS- SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH- DAMAGE.- """--- cpplint.py, located at tools/cpplint.py, is licensed as follows:- """- Copyright (c) 2009 Google Inc. All rights reserved.-- Redistribution and use in source and binary forms, with or without- modification, are permitted provided that the following conditions are- met:-- * Redistributions of source code must retain the above copyright- notice, this list of conditions and the following disclaimer.- * Redistributions in binary form must reproduce the above- copyright notice, this list of conditions and the following disclaimer- in the documentation and/or other materials provided with the- distribution.- * Neither the name of Google Inc. nor the names of its- contributors may be used to endorse or promote products derived from- this software without specific prior written permission.-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- """--- gypi_to_gn.py, located at tools/gypi_to_gn.py, is licensed as follows:- """- Redistribution and use in source and binary forms, with or without- modification, are permitted provided that the following conditions are- met:-- * Redistributions of source code must retain the above copyright- notice, this list of conditions and the following disclaimer.- * Redistributions in binary form must reproduce the above- copyright notice, this list of conditions and the following disclaimer- in the documentation and/or other materials provided with the- distribution.- * Neither the name of Google LLC nor the names of its- contributors may be used to endorse or promote products derived from- this software without specific prior written permission.-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- """--- gtest, located at deps/googletest, is licensed as follows:- """- Copyright 2008, Google Inc.- All rights reserved.-- Redistribution and use in source and binary forms, with or without- modification, are permitted provided that the following conditions are- met:-- * Redistributions of source code must retain the above copyright- notice, this list of conditions and the following disclaimer.- * Redistributions in binary form must reproduce the above- copyright notice, this list of conditions and the following disclaimer- in the documentation and/or other materials provided with the- distribution.- * Neither the name of Google Inc. nor the names of its- contributors may be used to endorse or promote products derived from- this software without specific prior written permission.-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- """--- nghttp2, located at deps/nghttp2, is licensed as follows:- """- The MIT License-- Copyright (c) 2012, 2014, 2015, 2016 Tatsuhiro Tsujikawa- Copyright (c) 2012, 2014, 2015, 2016 nghttp2 contributors-- Permission is hereby granted, free of charge, to any person obtaining- a copy of this software and associated documentation files (the- "Software"), to deal in the Software without restriction, including- without limitation the rights to use, copy, modify, merge, publish,- distribute, sublicense, and/or sell copies of the Software, and to- permit persons to whom the Software is furnished to do so, subject to- the following conditions:-- The above copyright notice and this permission notice shall be- included in all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- large_pages, located at src/large_pages, is licensed as follows:- """- Copyright (C) 2018 Intel Corporation-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"),- to deal in the Software without restriction, including without limitation- the rights to use, copy, modify, merge, publish, distribute, sublicense,- and/or sell copies of the Software, and to permit persons to whom- the Software is furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included- in all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES- OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE- OR OTHER DEALINGS IN THE SOFTWARE.- """--- caja, located at lib/internal/freeze_intrinsics.js, is licensed as follows:- """- Adapted from SES/Caja - Copyright (C) 2011 Google Inc.- Copyright (C) 2018 Agoric-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.- """--- brotli, located at deps/brotli, is licensed as follows:- """- Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to deal- in the Software without restriction, including without limitation the rights- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in- all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN- THE SOFTWARE.- """--- zstd, located at deps/zstd, is licensed as follows:- """- BSD License-- For Zstandard software-- Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.-- Redistribution and use in source and binary forms, with or without modification,- are permitted provided that the following conditions are met:-- * Redistributions of source code must retain the above copyright notice, this- list of conditions and the following disclaimer.-- * Redistributions in binary form must reproduce the above copyright notice,- this list of conditions and the following disclaimer in the documentation- and/or other materials provided with the distribution.-- * Neither the name Facebook, nor Meta, nor the names of its contributors may- be used to endorse or promote products derived from this software without- specific prior written permission.-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- """--- HdrHistogram, located at deps/histogram, is licensed as follows:- """- The code in this repository code was Written by Gil Tene, Michael Barker,- and Matt Warren, and released to the public domain, as explained at- http://creativecommons.org/publicdomain/zero/1.0/-- For users of this code who wish to consume it under the "BSD" license- rather than under the public domain or CC0 contribution text mentioned- above, the code found under this directory is *also* provided under the- following license (commonly referred to as the BSD 2-Clause License). This- license does not detract from the above stated release of the code into- the public domain, and simply represents an additional license granted by- the Author.-- ------------------------------------------------------------------------------ ** Beginning of "BSD 2-Clause License" text. **-- Copyright (c) 2012, 2013, 2014 Gil Tene- Copyright (c) 2014 Michael Barker- Copyright (c) 2014 Matt Warren- All rights reserved.-- Redistribution and use in source and binary forms, with or without- modification, are permitted provided that the following conditions are met:-- 1. Redistributions of source code must retain the above copyright notice,- this list of conditions and the following disclaimer.-- 2. Redistributions in binary form must reproduce the above copyright notice,- this list of conditions and the following disclaimer in the documentation- and/or other materials provided with the distribution.-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF- THE POSSIBILITY OF SUCH DAMAGE.- """--- node-heapdump, located at src/heap_utils.cc, is licensed as follows:- """- ISC License-- Copyright (c) 2012, Ben Noordhuis <[email protected]>-- Permission to use, copy, modify, and/or distribute this software for any- purpose with or without fee is hereby granted, provided that the above- copyright notice and this permission notice appear in all copies.-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.-- === src/compat.h src/compat-inl.h ===-- ISC License-- Copyright (c) 2014, StrongLoop Inc.-- Permission to use, copy, modify, and/or distribute this software for any- purpose with or without fee is hereby granted, provided that the above- copyright notice and this permission notice appear in all copies.-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.- """--- rimraf, located at lib/internal/fs/rimraf.js, is licensed as follows:- """- The ISC License-- Copyright (c) Isaac Z. Schlueter and Contributors-- Permission to use, copy, modify, and/or distribute this software for any- purpose with or without fee is hereby granted, provided that the above- copyright notice and this permission notice appear in all copies.-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR- IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.- """--- uvwasi, located at deps/uvwasi, is licensed as follows:- """- MIT License-- Copyright (c) 2019 Colin Ihrig and Contributors-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to deal- in the Software without restriction, including without limitation the rights- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE- SOFTWARE.- """--- ngtcp2, located at deps/ngtcp2/ngtcp2/, is licensed as follows:- """- The MIT License-- Copyright (c) 2016 ngtcp2 contributors-- Permission is hereby granted, free of charge, to any person obtaining- a copy of this software and associated documentation files (the- "Software"), to deal in the Software without restriction, including- without limitation the rights to use, copy, modify, merge, publish,- distribute, sublicense, and/or sell copies of the Software, and to- permit persons to whom the Software is furnished to do so, subject to- the following conditions:-- The above copyright notice and this permission notice shall be- included in all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- nghttp3, located at deps/ngtcp2/nghttp3/, is licensed as follows:- """- The MIT License-- Copyright (c) 2019 nghttp3 contributors-- Permission is hereby granted, free of charge, to any person obtaining- a copy of this software and associated documentation files (the- "Software"), to deal in the Software without restriction, including- without limitation the rights to use, copy, modify, merge, publish,- distribute, sublicense, and/or sell copies of the Software, and to- permit persons to whom the Software is furnished to do so, subject to- the following conditions:-- The above copyright notice and this permission notice shall be- included in all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- node-fs-extra, located at lib/internal/fs/cp, is licensed as follows:- """- (The MIT License)-- Copyright (c) 2011-2017 JP Richardson-- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files- (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,- merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE- WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS- OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.- """--- on-exit-leak-free, located at lib/internal/process/finalization, is licensed as follows:- """- MIT License-- Copyright (c) 2021 Matteo Collina-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to deal- in the Software without restriction, including without limitation the rights- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE- SOFTWARE.- """--- sonic-boom, located at lib/internal/streams/fast-utf8-stream.js, is licensed as follows:- """- MIT License-- Copyright (c) 2017 Matteo Collina-- Permission is hereby granted, free of charge, to any person obtaining a copy- of this software and associated documentation files (the "Software"), to deal- in the Software without restriction, including without limitation the rights- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- copies of the Software, and to permit persons to whom the Software is- furnished to do so, subject to the following conditions:-- The above copyright notice and this permission notice shall be included in all- copies or substantial portions of the Software.-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE- SOFTWARE.- """diff --git a/licenses/polka-url-1.0.0-next.29.txt b/licenses/polka-url-1.0.0-next.29.txtdeleted file mode 100644index d46889ae..00000000--- a/licenses/polka-url-1.0.0-next.29.txt+++ /dev/null@@ -1,21 +0,0 @@-The MIT License (MIT)--Copyright (c) Luke Edwards <[email protected]> (https://lukeed.com)--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in-all copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN-THE SOFTWARE.diff --git a/licenses/sirv-3.0.2.txt b/licenses/sirv-3.0.2.txtdeleted file mode 100644index d46889ae..00000000--- a/licenses/sirv-3.0.2.txt+++ /dev/null@@ -1,21 +0,0 @@-The MIT License (MIT)--Copyright (c) Luke Edwards <[email protected]> (https://lukeed.com)--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in-all copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN-THE SOFTWARE.diff --git a/licenses/upstream.json b/licenses/upstream.jsonindex c82cb28d..ee1af1a4 100644--- a/licenses/upstream.json+++ b/licenses/upstream.json@@ -4,21 +4,6 @@"source": "https://github.com/webmproject/libvpx/tree/6df3ec34557879fff673706f4a1d9fbd0f3a6f0e","sha256": "3042109b4fb2a8d44e52c6241eaa8a1a9b4bfdbd632e67b7d91b4d1db36d653b"},- "[email protected]": {- "file": "node-24.19.0.txt",- "source": "https://raw.githubusercontent.com/nodejs/node/cdc1b38d40cb567b7ad0b39c86addf830a0af0ae/LICENSE",- "sha256": "d5dfe2ee1355c7c315e2b150c397c791d5fd17c154916ac2ac4b1c4eed04fd36"- },- "[email protected]": {- "file": "sirv-3.0.2.txt",- "source": "https://raw.githubusercontent.com/lukeed/sirv/1135207e92c40354543cbd15c763c7a61d79d432/license",- "sha256": "ba573393f24555ac0528612ad39665fab5bdcc80330a61096024bbf5f736526d"- },- "@polka/[email protected]": {- "file": "polka-url-1.0.0-next.29.txt",- "source": "https://raw.githubusercontent.com/lukeed/polka/02cbdb529ddca0a9f3d225e2abb2931924219cc3/license",- "sha256": "ba573393f24555ac0528612ad39665fab5bdcc80330a61096024bbf5f736526d"- },"@bufbuild/[email protected]": {"file": "bufbuild-protobuf-1.10.1.txt","source": "https://raw.githubusercontent.com/bufbuild/protobuf-es/e31c1b139cf1e7fea2fb914f650af3c28c42ec68/LICENSE",diff --git a/native/client/platform/darwin/capture/README.md b/native/capture/darwin/README.mdsimilarity index 95%rename from native/client/platform/darwin/capture/README.mdrename to native/capture/darwin/README.mdindex 4389939b..93d65049 100644--- a/native/client/platform/darwin/capture/README.md+++ b/native/capture/darwin/README.md@@ -12,7 +12,7 @@ the same Pion source.Build on Apple Silicon macOS 13 or newer:```sh-sh native/client/platform/darwin/capture/build.sh /outside/repository/build+sh native/capture/darwin/build.sh /outside/repository/build/outside/repository/build/screener-client-capture --self-test/outside/repository/build/screener-client-capture --probe```diff --git a/native/client/platform/darwin/capture/build.sh b/native/capture/darwin/build.shsimilarity index 100%rename from native/client/platform/darwin/capture/build.shrename to native/capture/darwin/build.shdiff --git a/native/client/platform/darwin/capture/main.swift b/native/capture/darwin/main.swiftsimilarity index 100%rename from native/client/platform/darwin/capture/main.swiftrename to native/capture/darwin/main.swiftdiff --git a/native/client/platform/linux/capture/README.md b/native/capture/linux/README.mdsimilarity index 82%rename from native/client/platform/linux/capture/README.mdrename to native/capture/linux/README.mdindex 37f96ff3..ad60cbfd 100644--- a/native/client/platform/linux/capture/README.md+++ b/native/capture/linux/README.md@@ -16,13 +16,16 @@ advertised.Build on a Linux desktop with development packages for libportal and GStreamer:```sh-sh native/client/platform/linux/capture/build.sh /outside/repository/build+sh native/capture/linux/build.sh /outside/repository/build```Runtime requirements are the desktop Portal/PipeWire services, a GStreamerPipeWire source, and an installed GStreamer hardware H.264 encoder. If any partis unavailable, the Client reports no Linux Native path and the same Browser-capture choice remains available.+capture choice remains available. These system libraries and services are not+bundled; their distribution-provided license notices remain applicable. Linux+Client packages repeat the dependency and source links in+`THIRD-PARTY-NOTICES.txt`.Primary references:diff --git a/native/client/platform/linux/capture/build.sh b/native/capture/linux/build.shold mode 100755new mode 100644similarity index 100%rename from native/client/platform/linux/capture/build.shrename to native/capture/linux/build.shdiff --git a/native/client/platform/linux/capture/main.c b/native/capture/linux/main.csimilarity index 100%rename from native/client/platform/linux/capture/main.crename to native/capture/linux/main.cdiff --git a/native/client/platform/linux/capture/portal.c b/native/capture/linux/portal.csimilarity index 100%rename from native/client/platform/linux/capture/portal.crename to native/capture/linux/portal.cdiff --git a/native/client/platform/linux/capture/portal.h b/native/capture/linux/portal.hsimilarity index 100%rename from native/client/platform/linux/capture/portal.hrename to native/capture/linux/portal.hdiff --git a/native/client/platform/windows/capture/README.md b/native/capture/windows/README.mdsimilarity index 100%rename from native/client/platform/windows/capture/README.mdrename to native/capture/windows/README.mddiff --git a/native/client/platform/windows/capture/build-libvpx.ps1 b/native/capture/windows/build-libvpx.ps1similarity index 100%rename from native/client/platform/windows/capture/build-libvpx.ps1rename to native/capture/windows/build-libvpx.ps1diff --git a/native/client/platform/windows/capture/build.ps1 b/native/capture/windows/build.ps1similarity index 100%rename from native/client/platform/windows/capture/build.ps1rename to native/capture/windows/build.ps1diff --git a/native/client/platform/windows/capture/capture_geometry.h b/native/capture/windows/capture_geometry.hsimilarity index 100%rename from native/client/platform/windows/capture/capture_geometry.hrename to native/capture/windows/capture_geometry.hdiff --git a/native/client/platform/windows/capture/capture_geometry.test.cpp b/native/capture/windows/capture_geometry.test.cppsimilarity index 100%rename from native/client/platform/windows/capture/capture_geometry.test.cpprename to native/capture/windows/capture_geometry.test.cppdiff --git a/native/client/platform/windows/capture/capture_target.cpp b/native/capture/windows/capture_target.cppsimilarity index 100%rename from native/client/platform/windows/capture/capture_target.cpprename to native/capture/windows/capture_target.cppdiff --git a/native/client/platform/windows/capture/capture_target.h b/native/capture/windows/capture_target.hsimilarity index 100%rename from native/client/platform/windows/capture/capture_target.hrename to native/capture/windows/capture_target.hdiff --git a/native/client/platform/windows/capture/libvpx-dependencies.json b/native/capture/windows/libvpx-dependencies.jsonsimilarity index 100%rename from native/client/platform/windows/capture/libvpx-dependencies.jsonrename to native/capture/windows/libvpx-dependencies.jsondiff --git a/native/client/platform/windows/capture/main.cpp b/native/capture/windows/main.cppsimilarity index 100%rename from native/client/platform/windows/capture/main.cpprename to native/capture/windows/main.cppdiff --git a/native/client/platform/windows/capture/process_audio.cpp b/native/capture/windows/process_audio.cppsimilarity index 100%rename from native/client/platform/windows/capture/process_audio.cpprename to native/capture/windows/process_audio.cppdiff --git a/native/client/platform/windows/capture/process_audio.h b/native/capture/windows/process_audio.hsimilarity index 100%rename from native/client/platform/windows/capture/process_audio.hrename to native/capture/windows/process_audio.hdiff --git a/native/client/platform/windows/capture/vp8_encoder.cpp b/native/capture/windows/vp8_encoder.cppsimilarity index 100%rename from native/client/platform/windows/capture/vp8_encoder.cpprename to native/capture/windows/vp8_encoder.cppdiff --git a/native/client/platform/windows/capture/vp8_encoder.h b/native/capture/windows/vp8_encoder.hsimilarity index 100%rename from native/client/platform/windows/capture/vp8_encoder.hrename to native/capture/windows/vp8_encoder.hdiff --git a/native/client/internal/clientapp/app_test.go b/native/client/internal/clientapp/app_test.godeleted file mode 100644index 6bb4030f..00000000--- a/native/client/internal/clientapp/app_test.go+++ /dev/null@@ -1,180 +0,0 @@-package clientapp--import (- "net/url"- "os"- "path/filepath"- "runtime"- "strings"- "testing"-- "github.com/TNTcraftHIM/Screener/native/client/internal/clientconfig"-)--func TestPackagePathsValidateAnExplicitPackage(t *testing.T) {- nodePath, appDirectory := packageFixture(t)- actualNode, actualApp, err := packagePaths(nodePath, appDirectory)- if err != nil || actualNode != nodePath || actualApp != appDirectory {- t.Fatalf("packagePaths = %q, %q, %v", actualNode, actualApp, err)- }-}--func TestPackagePathsRequireTheExactPackagedRevision(t *testing.T) {- nodePath, appDirectory := packageFixture(t)- if err := os.WriteFile(filepath.Join(appDirectory, "REVISION"), []byte("different"), 0o600); err != nil {- t.Fatal(err)- }- previous := BuildRevision- BuildRevision = "expected"- t.Cleanup(func() { BuildRevision = previous })- if _, _, err := packagePaths(nodePath, appDirectory); err == nil {- t.Fatal("mismatched package revision was accepted")- }- if err := os.WriteFile(filepath.Join(appDirectory, "REVISION"), []byte("expected\n"), 0o600); err != nil {- t.Fatal(err)- }- if _, _, err := packagePaths(nodePath, appDirectory); err != nil {- t.Fatal(err)- }-}--func TestClientLaunchURLMarksThePageWithoutChangingOrigin(t *testing.T) {- value := clientLaunchURL("https://share.example/")- parsed, err := url.Parse(value)- if err != nil || parsed.Scheme != "https" || parsed.Host != "share.example" ||- parsed.RawQuery != "" {- t.Fatalf("launch URL = %q, %v", value, err)- }- fragment, err := url.ParseQuery(parsed.Fragment)- if err != nil || fragment.Get("screener-client") != "1" {- t.Fatalf("Client launch fragment = %q, %v", parsed.Fragment, err)- }-}--func TestMissingCaptureKeepsViewerControlAvailable(t *testing.T) {- native := discoverNativeMedia(t.Context(), "missing-capture-process")- if native.capabilities.Video || native.capabilities.HardwareH264 {- t.Fatalf("missing native capture = %+v", native)- }- control := native.controlFactory()()- if control == nil {- t.Fatal("missing capture disabled the native Viewer control")- }- _ = control.Close()-}--func TestLaunchURLPreservesLocalAccessInsideThePrivateFragment(t *testing.T) {- value := clientLaunchURL("http://localhost:8787/#client-access=secret")- parsed, err := url.Parse(value)- if err != nil || parsed.RawQuery != "" {- t.Fatalf("local native launch URL = %q, %v", value, err)- }- fragment, err := url.ParseQuery(parsed.Fragment)- if err != nil || fragment.Get("client-access") != "secret" ||- fragment.Get("screener-client") != "1" {- t.Fatalf("local native launch fragment = %q, %v", parsed.Fragment, err)- }-}--func TestLaunchURLEncodesAndClearsOptionalLocalAccess(t *testing.T) {- value := clientLaunchURLWithLocalAccess(- "http://localhost:8787/#retained=yes&client-access=old",- "a+b&c?d=e",- )- parsed, err := url.Parse(value)- if err != nil {- t.Fatal(err)- }- fragment, err := url.ParseQuery(parsed.Fragment)- if err != nil || fragment.Get("client-access") != "a+b&c?d=e" ||- fragment.Get("screener-client") != "1" || fragment.Get("retained") != "yes" {- t.Fatalf("encoded local launch fragment = %q, %v", parsed.Fragment, err)- }-- open := clientLaunchURLWithLocalAccess("http://localhost:8787/#client-access=old", "")- parsed, err = url.Parse(open)- if err != nil {- t.Fatal(err)- }- fragment, err = url.ParseQuery(parsed.Fragment)- if err != nil || fragment.Get("client-access") != "" || fragment.Get("screener-client") != "1" {- t.Fatalf("open local launch fragment = %q, %v", parsed.Fragment, err)- }-}--func TestLinkModeKeepsOneLocalAuthority(t *testing.T) {- config := clientconfig.Config{- Version: 1,- LocalAccessPassword: "abcdefghijklmnopqrstuvwxyzABCDEF",- Site: "https://example.test",- }- selected, err := applyMode(config, Options{Link: true})- if err != nil || selected.Site != config.Site {- t.Fatalf("link mode = %+v, %v", selected, err)- }- if err = validateMode(Options{Link: true, SiteSet: true}); err == nil {- t.Fatal("link mode accepted a separate Site")- }- if err = validateMode(Options{Link: true, Local: true}); err == nil {- t.Fatal("link mode accepted a second Local selector")- }-}--func TestLocalEnvironmentOwnsItsSTUNConfiguration(t *testing.T) {- t.Setenv("STUN_URLS", "stun:inherited.example:3478")- environment := localEnvironment(- 8787,- "192.168.1.2",- []string{"192.168.1.2"},- "abcdefghijklmnopqrstuvwxyzABCDEF",- []string{"stun:public.example:3478"},- []string{"stun:survey-a.example:3478", "stun:survey-b.example:3478"},- "https://small-bright-room.trycloudflare.com",- )- stunEntries := []string{}- surveyEntries := []string{}- publicEntries := []string{}- for _, entry := range environment {- if strings.HasPrefix(entry, "STUN_URLS=") {- stunEntries = append(stunEntries, entry)- }- if strings.HasPrefix(entry, "SCREENER_CLIENT_NAT_PREDICTION_STUN_URLS=") {- surveyEntries = append(surveyEntries, entry)- }- if strings.HasPrefix(entry, "SCREENER_CLIENT_PUBLIC_ORIGIN=") {- publicEntries = append(publicEntries, entry)- }- }- if len(stunEntries) != 1 || stunEntries[0] != "STUN_URLS=stun:public.example:3478" {- t.Fatalf("Local STUN environment = %v", stunEntries)- }- if len(surveyEntries) != 1 ||- surveyEntries[0] != "SCREENER_CLIENT_NAT_PREDICTION_STUN_URLS=stun:survey-a.example:3478,stun:survey-b.example:3478" {- t.Fatalf("Local NAT survey environment = %v", surveyEntries)- }- if len(publicEntries) != 1 ||- publicEntries[0] != "SCREENER_CLIENT_PUBLIC_ORIGIN=https://small-bright-room.trycloudflare.com" {- t.Fatalf("Local public environment = %v", publicEntries)- }-}--func packageFixture(t *testing.T) (string, string) {- t.Helper()- root := t.TempDir()- nodeName := "node"- if runtime.GOOS == "windows" {- nodeName += ".exe"- }- nodePath := filepath.Join(root, nodeName)- appDirectory := filepath.Join(root, "app")- entry := filepath.Join(appDirectory, "dist", "server", "server", "local-index.js")- if err := os.MkdirAll(filepath.Dir(entry), 0o700); err != nil {- t.Fatal(err)- }- for path, body := range map[string]string{nodePath: "node", entry: "entry"} {- if err := os.WriteFile(path, []byte(body), 0o700); err != nil {- t.Fatal(err)- }- }- return nodePath, appDirectory-}diff --git a/native/client/internal/supervisor/process.go b/native/client/internal/supervisor/process.godeleted file mode 100644index ec3fe8b1..00000000--- a/native/client/internal/supervisor/process.go+++ /dev/null@@ -1,139 +0,0 @@-package supervisor--import (- "context"- "errors"- "fmt"- "io"- "net/http"- "os/exec"- "sync"- "time"-)--const (- readinessTimeout = 15 * time.Second- pollInterval = 100 * time.Millisecond- requestTimeout = 500 * time.Millisecond- shutdownTimeout = 5 * time.Second-)--type Command struct {- Path string- Args []string- Directory string- Environment []string- Stdout io.Writer- Stderr io.Writer- HealthURL string-}--type Process struct {- cancel context.CancelFunc- done chan struct{}- once sync.Once- mu sync.Mutex- err error-}--func Start(parent context.Context, command Command) (*Process, error) {- if parent == nil {- parent = context.Background()- }- if command.Path == "" || command.HealthURL == "" {- return nil, errors.New("supervised process command is incomplete")- }- ctx, cancel := context.WithCancel(parent)- child := exec.CommandContext(ctx, command.Path, command.Args...)- child.Dir = command.Directory- child.Env = command.Environment- child.Stdout = command.Stdout- child.Stderr = command.Stderr- stdin, err := child.StdinPipe()- if err != nil {- cancel()- return nil, fmt.Errorf("open supervised process stdin: %w", err)- }- child.Cancel = stdin.Close- child.WaitDelay = shutdownTimeout- if err = child.Start(); err != nil {- cancel()- return nil, fmt.Errorf("start supervised process: %w", err)- }- process := &Process{cancel: cancel, done: make(chan struct{})}- go func() {- waitErr := child.Wait()- if ctx.Err() != nil && (waitErr == nil || errors.Is(waitErr, context.Canceled)) {- waitErr = nil- }- process.mu.Lock()- process.err = waitErr- process.mu.Unlock()- close(process.done)- }()- if err = waitUntilReady(ctx, process, command.HealthURL); err != nil {- process.cancel()- <-process.done- return nil, err- }- return process, nil-}--func (process *Process) Done() <-chan struct{} {- return process.done-}--func (process *Process) Err() error {- select {- case <-process.done:- process.mu.Lock()- defer process.mu.Unlock()- return process.err- default:- return nil- }-}--func (process *Process) Close() error {- process.once.Do(process.cancel)- <-process.done- return process.Err()-}--func waitUntilReady(ctx context.Context, process *Process, healthURL string) error {- deadline := time.NewTimer(readinessTimeout)- defer deadline.Stop()- ticker := time.NewTicker(pollInterval)- defer ticker.Stop()- transport := &http.Transport{Proxy: nil}- defer transport.CloseIdleConnections()- client := &http.Client{- Timeout: requestTimeout,- Transport: transport,- }- for {- request, err := http.NewRequestWithContext(ctx, http.MethodGet, healthURL, nil)- if err != nil {- return errors.New("supervised process health URL is invalid")- }- response, requestErr := client.Do(request)- if requestErr == nil {- _ = response.Body.Close()- if response.StatusCode == http.StatusOK {- return nil- }- }- select {- case <-ctx.Done():- return ctx.Err()- case <-process.done:- if err = process.Err(); err != nil {- return fmt.Errorf("supervised process exited before readiness: %w", err)- }- return errors.New("supervised process exited before readiness")- case <-deadline.C:- return errors.New("supervised process readiness timed out")- case <-ticker.C:- }- }-}diff --git a/native/client/internal/supervisor/process_test.go b/native/client/internal/supervisor/process_test.godeleted file mode 100644index a6289dd4..00000000--- a/native/client/internal/supervisor/process_test.go+++ /dev/null@@ -1,85 +0,0 @@-package supervisor--import (- "context"- "fmt"- "io"- "net"- "net/http"- "os"- "strconv"- "testing"-)--func TestStartWaitsForReadinessAndClosesThroughStdin(t *testing.T) {- port := freePort(t)- process, err := Start(context.Background(), helperCommand(port, "serve"))- if err != nil {- t.Fatal(err)- }- if err = process.Close(); err != nil {- t.Fatal(err)- }- select {- case <-process.Done():- default:- t.Fatal("supervised process did not finish")- }-}--func TestStartReportsAChildThatExitsBeforeReadiness(t *testing.T) {- if _, err := Start(context.Background(), helperCommand(freePort(t), "exit")); err == nil {- t.Fatal("early child exit was accepted")- }-}--func TestSupervisorChild(t *testing.T) {- if os.Getenv("SCREENER_SUPERVISOR_TEST_CHILD") != "true" {- return- }- if os.Getenv("SCREENER_SUPERVISOR_TEST_MODE") == "exit" {- os.Exit(3)- }- port, err := strconv.Atoi(os.Getenv("SCREENER_SUPERVISOR_TEST_PORT"))- if err != nil {- os.Exit(4)- }- server := &http.Server{Handler: http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {- if request.URL.Path != "/healthz" {- http.NotFound(response, request)- return- }- response.WriteHeader(http.StatusOK)- })}- listener, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", port))- if err != nil {- os.Exit(5)- }- go func() { _ = server.Serve(listener) }()- _, _ = io.Copy(io.Discard, os.Stdin)- _ = server.Close()- os.Exit(0)-}--func helperCommand(port int, mode string) Command {- return Command{- Path: os.Args[0],- Args: []string{"-test.run=TestSupervisorChild"},- Environment: append(os.Environ(),- "SCREENER_SUPERVISOR_TEST_CHILD=true",- "SCREENER_SUPERVISOR_TEST_MODE="+mode,- fmt.Sprintf("SCREENER_SUPERVISOR_TEST_PORT=%d", port),- ),- HealthURL: fmt.Sprintf("http://127.0.0.1:%d/healthz", port),- }-}--func freePort(t *testing.T) int {- t.Helper()- listener, err := net.Listen("tcp4", "127.0.0.1:0")- if err != nil {- t.Fatal(err)- }- defer listener.Close()- return listener.Addr().(*net.TCPAddr).Port-}diff --git a/package-lock.json b/package-lock.jsonindex 1c9e510b..4b9d8350 100644--- a/package-lock.json+++ b/package-lock.json@@ -8,12 +8,6 @@"name": "screener","version": "0.1.0","license": "MIT",- "dependencies": {- "livekit-server-sdk": "2.18.0",- "sirv": "3.0.2",- "ws": "8.21.3",- "zod": "4.4.3"- },"devDependencies": {"@types/node": "24.13.3","@types/react": "19.2.18",@@ -22,13 +16,16 @@"@types/ws": "8.18.1","@vitejs/plugin-react": "6.0.5","livekit-client": "2.22.1",+ "livekit-server-sdk": "2.18.0","react": "19.2.8","react-dom": "19.2.8","sdp-transform": "3.0.0","tsx": "4.23.12","typescript": "~6.0.3","vite": "8.2.1",- "vitest": "4.1.10"+ "vitest": "4.1.10",+ "ws": "8.21.3",+ "zod": "4.4.3"},"engines": {"node": ">=24.0.0 <27"@@ -38,6 +35,7 @@"version": "1.10.1","resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz","integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==",+ "dev": true,"license": "(Apache-2.0 AND BSD-3-Clause)"},"node_modules/@esbuild/aix-ppc64": {@@ -516,12 +514,6 @@"url": "https://github.com/sponsors/Boshen"}},- "node_modules/@polka/url": {- "version": "1.0.0-next.29",- "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",- "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==",- "license": "MIT"- },"node_modules/@rolldown/binding-android-arm64": {"version": "1.2.4","resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.4.tgz",@@ -1486,6 +1478,7 @@"version": "2.18.0","resolved": "https://registry.npmjs.org/livekit-server-sdk/-/livekit-server-sdk-2.18.0.tgz","integrity": "sha512-iUGmkbyi0g4DHKQ0Z4VSVs/V+ddp3T75ccQIe6LX94AYlqgyh+SVSM1lQMjFQuI3Qh6Z9v06T4xxV+vWmp7VeQ==",+ "dev": true,"license": "Apache-2.0","dependencies": {"@bufbuild/protobuf": "^1.10.1",@@ -1500,6 +1493,7 @@"version": "1.48.0","resolved": "https://registry.npmjs.org/@livekit/protocol/-/protocol-1.48.0.tgz","integrity": "sha512-fYHYgltH6YavAsokl3qsHLkBdQeKCl4UORVTub5crS3t8JtKFZ0uinHDFQ+XXdNKS6Ub9gcOjV+UHcDiqnWXoQ==",+ "dev": true,"license": "Apache-2.0","dependencies": {"@bufbuild/protobuf": "^1.10.0"@@ -1509,6 +1503,7 @@"version": "5.10.0","resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz","integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==",+ "dev": true,"license": "MIT","funding": {"url": "https://github.com/sponsors/panva"@@ -1548,15 +1543,6 @@"@jridgewell/sourcemap-codec": "^1.5.5"}},- "node_modules/mrmime": {- "version": "2.0.1",- "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz",- "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==",- "license": "MIT",- "engines": {- "node": ">=10"- }- },"node_modules/nanoid": {"version": "3.3.18","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",@@ -1744,20 +1730,6 @@"dev": true,"license": "ISC"},- "node_modules/sirv": {- "version": "3.0.2",- "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.2.tgz",- "integrity": "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==",- "license": "MIT",- "dependencies": {- "@polka/url": "^1.0.0-next.24",- "mrmime": "^2.0.0",- "totalist": "^3.0.0"- },- "engines": {- "node": ">=18"- }- },"node_modules/source-map-js": {"version": "1.2.1","resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",@@ -1826,15 +1798,6 @@"node": ">=14.0.0"}},- "node_modules/totalist": {- "version": "3.0.1",- "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz",- "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==",- "license": "MIT",- "engines": {- "node": ">=6"- }- },"node_modules/tslib": {"version": "2.8.1","resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",@@ -2095,6 +2058,7 @@"version": "8.21.3","resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz","integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",+ "dev": true,"license": "MIT","engines": {"node": ">=10.0.0"@@ -2116,6 +2080,7 @@"version": "4.4.3","resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz","integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",+ "dev": true,"license": "MIT","funding": {"url": "https://github.com/sponsors/colinhacks"diff --git a/package.json b/package.jsonindex 1357ff3f..43a343c3 100644--- a/package.json+++ b/package.json@@ -9,10 +9,9 @@},"packageManager": "[email protected]","scripts": {- "dev": "node scripts/package-licenses.mjs public/third-party-licenses.txt && tsx watch src/server/index.ts",- "build": "npm run build:client && npm run build:server",- "build:client": "node scripts/package-licenses.mjs public/third-party-licenses.txt && vite build",- "build:server": "node --input-type=module -e \"import { rmSync } from 'node:fs'; rmSync('dist/server', { recursive: true, force: true })\" && tsc -p tsconfig.server.json",+ "dev": "node scripts/package-licenses.mjs public/third-party-licenses.txt && vite",+ "build": "npm run build:client",+ "build:client": "node scripts/package-licenses.mjs public/third-party-licenses.txt && node --input-type=module -e \"import { readdirSync, rmSync } from 'node:fs'; const dir = 'internal/server/webassets/dist'; for (const entry of readdirSync(dir)) { if (entry !== '.gitkeep') rmSync(dir + '/' + entry, { recursive: true, force: true }); }\" && vite build","package:client": "node scripts/assemble-client.mjs","package:client-candidate": "node scripts/package-client-candidate.mjs","check:client": "node scripts/check-client.mjs",@@ -21,14 +20,11 @@"gate:client-media": "tsx scripts/client-media-gate.ts","gate:client-native-host": "tsx scripts/client-native-host-gate.ts","gate:client-browser-fanout": "tsx scripts/client-browser-fanout-gate.ts",- "gate:client-cross-nat": "tsx scripts/client-native-host-gate.ts",- "gate:client-link-media": "tsx scripts/client-native-host-gate.ts","gate:client-native-sfu": "tsx scripts/client-native-sfu-gate.ts","gate:client-link": "tsx scripts/client-link-gate.ts",- "start": "node dist/server/server/index.js","gate:peer-topology-loopback": "tsx scripts/peer-assisted-benchmark.ts",- "gate:sfu-admission": "vitest run tests/room-route-controller.test.ts tests/hybrid-media-router.test.ts tests/sfu-resource-admission.test.ts tests/sfu-room-control.test.ts tests/livekit-token.test.ts tests/sfu-client.test.ts tests/route-transition.test.ts tests/server-config.test.ts tests/server-http.test.ts tests/server-signal.test.ts",- "gate:access-privacy": "npm run build:client && vitest run tests/server-signal.test.ts && tsx scripts/access-privacy-gate.ts",+ "gate:sfu-admission": "vitest run tests/sfu-client.test.ts tests/route-transition.test.ts && go test ./internal/server/...",+ "gate:access-privacy": "npm run build:client && tsx scripts/access-privacy-gate.ts","probe:client-loopback": "tsx scripts/client-loopback-gate.ts","gate:client-local": "tsx scripts/client-local-gate.ts","typecheck": "tsc -b --pretty false",@@ -36,12 +32,7 @@"test:watch": "vitest","check": "npm run typecheck && npm test && npm run build"},- "dependencies": {- "livekit-server-sdk": "2.18.0",- "sirv": "3.0.2",- "ws": "8.21.3",- "zod": "4.4.3"- },+ "dependencies": {},"devDependencies": {"@types/node": "24.13.3","@types/react": "19.2.18",@@ -50,12 +41,15 @@"@types/ws": "8.18.1","@vitejs/plugin-react": "6.0.5","livekit-client": "2.22.1",+ "livekit-server-sdk": "2.18.0","react": "19.2.8","react-dom": "19.2.8","sdp-transform": "3.0.0","tsx": "4.23.12","typescript": "~6.0.3","vite": "8.2.1",- "vitest": "4.1.10"+ "vitest": "4.1.10",+ "ws": "8.21.3",+ "zod": "4.4.3"}}diff --git a/scripts/access-privacy-gate.ts b/scripts/access-privacy-gate.tsindex c6a85f95..3669a49a 100644--- a/scripts/access-privacy-gate.ts+++ b/scripts/access-privacy-gate.ts@@ -1,22 +1,51 @@-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";import { randomBytes } from "node:crypto";-import { access, mkdtemp, readFile, readdir } from "node:fs/promises";+import { access, mkdir, mkdtemp, readFile, readdir } from "node:fs/promises";+import {+ createServer,+ request as httpRequest,+ type IncomingHttpHeaders,+ type IncomingMessage,+ type OutgoingHttpHeaders,+ type Server,+} from "node:http";+import { connect } from "node:net";import { tmpdir } from "node:os";-import { join, resolve } from "node:path";+import { dirname, join, resolve } from "node:path";import { pathToFileURL } from "node:url";-import { createRoomResponseSchema } from "../src/shared/protocol";-import { createScreenerServer, type ScreenerServer } from "../src/server/app";-import type { ServerConfig } from "../src/server/config";+import WebSocket from "ws";+import {+ SIGNALING_PROTOCOL,+ createRoomResponseSchema,+ decodeServerMessage,+ roomAccessUpdateResponseSchema,+} from "../src/shared/protocol";import {CdpConnection,cleanupRun,createPage,evaluate,+ fetchJsonBefore,+ launchChrome,reservePort,+ waitForSample,waitForVersion,+ withDeadline,} from "./browser-gate-harness";const root = resolve(import.meta.dirname, "..");const nginxConfigPath = resolve(root, "deploy/nginx/share.bonfire.icu.conf.example");+const serverExecutable = join(root, "build", "client-check",+ process.platform === "win32" ? "screener-server.exe" : "screener-server");+// SCREENER_ENV=production refuses to start without STUN. Nothing listens on+// this address, so the gate still never leaves the loopback interface.+const gateStunUrl = "stun:127.0.0.1:3478";+const hostClientId = "privacy-gate-host";+const serverReadyTimeoutMs = 20_000;+const signalDeadlineMs = 10_000;+const serverStopTimeoutMs = 10_000;+// Hop-by-hop headers the proxy must not forward (RFC 9110 7.6.1); Node frames+// the forwarded body itself.+const hopByHopHeaders = new Set(["connection", "keep-alive", "transfer-encoding", "upgrade"]);const fragmentProbe = `(() => {let domContentLoaded = false;const state = { fragmentAtStart: location.hash.length > 0, replaced: false, beforeDomContentLoaded: false };@@ -47,20 +76,145 @@ interface BrowserAudit {otherSessionGrantMatches: number; localGrantMatches: number;cookieGrantMatches: number; resourceGrantMatches: number;}+// An observer records the request line and returns the sink for its status.+type RequestObserver = (request: IncomingMessage) => (status: number) => void;function secret(): string { return randomBytes(24).toString("base64url"); }function leakCount(values: readonly (string | Buffer)[], secrets: readonly string[]): number {return values.filter((value) => secrets.some((item) => value.includes(item))).length;}-function diagnosticText(values: readonly unknown[]): string {- return values.map((value) => {- if (typeof value === "string") return value;- if (value instanceof Error) return `${value.name}:${value.message}`;- try { return JSON.stringify(value) ?? ""; } catch { return ""; }- }).join(" ");-}+// The profile is also the server's working directory, so a room database the+// gate never configured would land here.async function persistentRoomFiles(profile: string): Promise<string[]> {return (await readdir(profile)).filter((name) => name.startsWith("rooms.sqlite"));}+async function reserveDistinctPorts(count: number): Promise<number[]> {+ const ports: number[] = [];+ while (ports.length < count) {+ const port = await reservePort();+ if (!ports.includes(port)) ports.push(port);+ }+ return ports;+}+function buildServer(): void {+ const go = process.env.SCREENER_GO?.trim() || "go";+ const result = spawnSync(go, ["build", "-trimpath", "-o", serverExecutable, "./cmd/screener-server"], {+ cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"],+ env: { ...process.env, CGO_ENABLED: "0" },+ });+ if (result.error) throw result.error;+ if (result.status !== 0) throw new Error("screener-server build failed");+}+function forwardedHeaders(headers: IncomingHttpHeaders): OutgoingHttpHeaders {+ return Object.fromEntries(+ Object.entries(headers).filter(([name]) => !hopByHopHeaders.has(name)),+ );+}+function requestPreamble(request: IncomingMessage): string {+ const lines = [`${request.method} ${request.url} HTTP/1.1`];+ for (let index = 0; index < request.rawHeaders.length; index += 2) {+ lines.push(`${request.rawHeaders[index]}: ${request.rawHeaders[index + 1]}`);+ }+ return `${lines.join("\r\n")}\r\n\r\n`;+}+function upgradeStatus(chunk: Buffer): number {+ const statusLine = chunk.toString("latin1", 0, Math.min(chunk.length, 32));+ const match = /^HTTP\/1\.[01] (\d{3})/.exec(statusLine);+ return match ? Number(match[1]) : 0;+}+// startProxy stands in for the nginx reverse proxy the deployment runs in+// front of the server (deploy/nginx/share.bonfire.icu.conf.example). It+// observes every request line the browser and the gate emit, which is what the+// in-process httpServer.prependListener("request") hook used to do, and it is+// the only origin the browser ever sees.+// ponytail: the upgrade pipes ignore backpressure; gate traffic is a handful of+// signaling frames. Use stream.pipe with drain handling if that ever changes.+function startProxy(port: number, upstreamPort: number, observe: RequestObserver): Promise<Server> {+ const proxy = createServer((request, response) => {+ const finish = observe(request);+ response.once("finish", () => finish(response.statusCode));+ const upstream = httpRequest({+ host: "127.0.0.1", port: upstreamPort, method: request.method,+ path: request.url, headers: request.headers,+ }, (upstreamResponse) => {+ response.writeHead(upstreamResponse.statusCode ?? 502, forwardedHeaders(upstreamResponse.headers));+ upstreamResponse.pipe(response);+ });+ upstream.on("error", () => response.destroy());+ request.pipe(upstream);+ });+ proxy.on("upgrade", (request, clientSocket, head) => {+ const finish = observe(request);+ const upstream = connect({ host: "127.0.0.1", port: upstreamPort });+ const destroy = () => { clientSocket.destroy(); upstream.destroy(); };+ let statusRecorded = false;+ upstream.on("connect", () => {+ upstream.write(requestPreamble(request));+ if (head.length > 0) upstream.write(head);+ });+ upstream.on("data", (chunk: Buffer) => {+ if (!statusRecorded) { statusRecorded = true; finish(upgradeStatus(chunk)); }+ clientSocket.write(chunk);+ });+ clientSocket.on("data", (chunk: Buffer) => upstream.write(chunk));+ for (const socket of [clientSocket, upstream]) {+ socket.on("error", destroy);+ socket.on("close", destroy);+ }+ });+ return new Promise((resolveProxy, rejectProxy) => {+ proxy.once("error", rejectProxy);+ proxy.listen(port, "127.0.0.1", () => resolveProxy(proxy));+ });+}+async function stopChild(child: ChildProcessWithoutNullStreams): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) return;+ const closed = new Promise<void>((resolveClosed) => child.once("close", () => resolveClosed()));+ child.kill();+ await withDeadline(() => closed, Date.now() + serverStopTimeoutMs);+}+async function closeProxy(proxy: Server | null): Promise<void> {+ if (!proxy) return;+ proxy.closeAllConnections();+ await new Promise<void>((resolveClosed) => proxy.close(() => resolveClosed()));+}+// authenticateHost replaces the in-process roomStore.connectParticipant call:+// the room needs a connected Host, and out of process the only way to get one+// is the handshake tests/server-signal.test.ts drives over /signal.+async function authenticateHost(+ webSocketUrl: string, origin: string, cookie: string, roomId: string, hostToken: string,+): Promise<WebSocket> {+ const socket = new WebSocket(webSocketUrl, { origin, headers: { Cookie: cookie } });+ const deadline = Date.now() + signalDeadlineMs;+ await withDeadline(() => new Promise<void>((resolveOpen, rejectOpen) => {+ socket.once("open", resolveOpen);+ socket.once("error", rejectOpen);+ }), deadline);+ const authenticated = new Promise<void>((resolveAuth, rejectAuth) => {+ socket.on("error", rejectAuth);+ socket.once("close", () => rejectAuth(new Error("Host signaling closed before authenticating")));+ socket.on("message", (data) => {+ try {+ if (decodeServerMessage(data.toString()).type === "authenticated") resolveAuth();+ } catch (error) {+ rejectAuth(error instanceof Error ? error : new Error("Unreadable server message"));+ }+ });+ });+ socket.send(JSON.stringify({+ type: "authenticate", protocol: SIGNALING_PROTOCOL, roomId,+ role: "host", token: hostToken, clientId: hostClientId,+ }));+ try {+ await withDeadline(() => authenticated, deadline);+ } catch (error) {+ socket.terminate();+ throw error;+ }+ // The Host session lives until the server stops; a late transport error must+ // not surface as an unhandled event.+ socket.on("error", () => {});+ return socket;+}async function main(): Promise<void> {const report: GateReport = {passed: false, serverReady: false, roomPrepared: false,@@ -79,39 +233,71 @@ async function main(): Promise<void> {const requestRecords: string[] = [];const nginxLines: string[] = [];const appLogs: string[] = [];- const originalConsoleError = console.error;let profile: string | null = null;- let server: ScreenerServer | null = null;+ let server: { close(): Promise<void> } | null = null;let chrome: ChildProcessWithoutNullStreams | null = null;let cdp: CdpConnection | null = null;- let appPort = 0;+ let proxyPort = 0;+ let serverPort = 0;let debugPort = 0;- console.error = (...values: unknown[]) => { appLogs.push(diagnosticText(values)); };try {await access(chromePath);- appPort = await reservePort();- do { debugPort = await reservePort(); } while (debugPort === appPort);+ [proxyPort, serverPort, debugPort] = await reserveDistinctPorts(3);profile = await mkdtemp(join(tmpdir(), "screener-access-privacy-"));- const baseUrl = `http://127.0.0.1:${appPort}`;- const config: ServerConfig = {- nodeEnv: "production", port: appPort, listenHost: "127.0.0.1",- publicBaseUrl: new URL(baseUrl), allowedOrigins: new Set([baseUrl]),- siteAccessPassword: sitePassword, roomLeaseMs: 86_400_000,- maxViewersPerRoom: 2, endpointMediaCopyCapacity: 2,- peerAssistedMedia: false, stunUrls: [], natPredictionEnabled: false,- };- server = await createScreenerServer({- config,- frontend: { mode: "static", directory: resolve(root, "dist/client") },+ const baseUrl = `http://127.0.0.1:${proxyPort}`;+ await mkdir(dirname(serverExecutable), { recursive: true });+ buildServer();+ let proxy: Server | null = null;+ let hostSocket: WebSocket | null = null;+ const child = spawn(serverExecutable, [], {+ // The working directory decides where .env is read and where an+ // unconfigured room database would be written; the empty profile keeps+ // both the developer's environment and the repository out of the run.+ cwd: profile, stdio: "pipe", windowsHide: true,+ // An explicit environment: config.Load fails closed on a removed+ // variable, so nothing from the developer's shell may reach the server.+ env: {+ PATH: process.env.PATH,+ SystemRoot: process.env.SystemRoot,+ SCREENER_ENV: "production",+ PORT: String(serverPort),+ LISTEN_HOST: "127.0.0.1",+ // Production requires an https public origin. The browser reaches the+ // same host and port over plain HTTP through the observing proxy, so+ // only the scheme of the invite URL is rewritten before navigating.+ PUBLIC_BASE_URL: `https://127.0.0.1:${proxyPort}`,+ ALLOWED_ORIGINS: baseUrl,+ SITE_ACCESS_PASSWORD: sitePassword,+ MAX_VIEWERS_PER_ROOM: "2",+ ENDPOINT_MEDIA_COPY_CAPACITY: "2",+ STUN_URLS: gateStunUrl,+ },});- server.httpServer.prependListener("request", (request, response) => {- const target = request.url ?? "";- const record = `${request.method ?? ""} ${target} ${request.headers.referer ?? ""}`;+ child.stdout.on("data", (chunk: Buffer) => appLogs.push(chunk.toString()));+ child.stderr.on("data", (chunk: Buffer) => appLogs.push(chunk.toString()));+ server = {+ async close() {+ hostSocket?.terminate();+ await stopChild(child);+ await closeProxy(proxy);+ },+ };+ proxy = await startProxy(proxyPort, serverPort, (request) => {+ // The fields the in-process request listener recorded, plus whether a+ // Cookie travelled at all: the audit must see credential-bearing+ // requests without ever storing a credential.+ const record = `${request.method ?? ""} ${request.url ?? ""} ` ++ `${request.headers.referer ?? ""} ${request.headers.cookie ? "cookie" : "no-cookie"}`;requestRecords.push(record);- response.once("finish", () => nginxLines.push(`${record} ${response.statusCode}`));+ return (status) => nginxLines.push(`${record} ${status}`);});- await server.listen(appPort, "127.0.0.1");+ await waitForSample(+ (deadline) => fetchJsonBefore<{ status: string }>(+ `http://127.0.0.1:${serverPort}/healthz`, deadline),+ (health) => health.status === "ok",+ serverReadyTimeoutMs,+ );report.serverReady = true;const login = await fetch(`${baseUrl}/api/site-access`, {method: "POST", headers: { Authorization: `Bearer ${sitePassword}`, Origin: baseUrl },@@ -126,17 +312,26 @@ async function main(): Promise<void> {const invite = new URL(room.inviteUrl);const grant = new URLSearchParams(invite.hash.slice(1)).get("v") ?? "";if (!grant) throw new Error("Room creation did not return a Viewer grant");- server.roomStore.connectParticipant({- roomId: room.roomId, role: "host", token: room.hostToken,- clientId: "privacy-gate-host", sessionId: "privacy-gate-host-session",+ invite.protocol = "http:";+ hostSocket = await authenticateHost(+ `ws://127.0.0.1:${proxyPort}/signal`, baseUrl, cookie, room.roomId, room.hostToken);+ const accessResponse = await fetch(`${baseUrl}/api/rooms/${room.roomId}/access`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${room.hostToken}`, "Content-Type": "application/json",+ Cookie: cookie, Origin: baseUrl,+ },+ body: JSON.stringify({ action: "set-viewer-password", password: roomPassword }),});- await server.roomStore.setViewerPassword(room.roomId, roomPassword, room.hostToken);+ const accessUpdate = roomAccessUpdateResponseSchema.parse(await accessResponse.json());+ if (accessUpdate.type !== "viewer-password-updated" || !accessUpdate.enabled) {+ throw new Error("Room preparation did not enable the Viewer password");+ }report.roomPrepared = true;- chrome = spawn(chromePath, [- `--remote-debugging-port=${debugPort}`, `--user-data-dir=${profile}`,+ chrome = launchChrome(chromePath, debugPort, profile, ["--headless=new", "--no-first-run", "--disable-extensions",- "--disable-logging", "about:blank",- ], { cwd: root, stdio: "pipe", windowsHide: true });+ "--disable-logging",+ ], { cwd: root });chrome.stdout.resume();chrome.stderr.resume();const version = await waitForVersion(debugPort, chrome);@@ -145,7 +340,7 @@ async function main(): Promise<void> {const context = await cdp.call<{ browserContextId: string }>("Target.createBrowserContext", { disposeOnDetach: true }, undefined, Date.now() + 5_000,);- const page = await createPage(cdp, room.inviteUrl, fragmentProbe, true, context.browserContextId);+ const page = await createPage(cdp, invite.toString(), fragmentProbe, true, context.browserContextId);report.pageLoaded = true;const expected = JSON.stringify({ roomId: room.roomId, grant });const audit = await evaluate<BrowserAudit>(cdp, page, `(() => {@@ -185,10 +380,9 @@ async function main(): Promise<void> {} catch {// The report intentionally exposes no exception text or secret-bearing diagnostics.} finally {- console.error = originalConsoleError;const cleanup = await cleanupRun({cdp, native: null, chrome, server, profile,- ports: [appPort, debugPort].filter((port) => port > 0),+ ports: [proxyPort, serverPort, debugPort].filter((port) => port > 0),});report.cleanupPassed = Object.values(cleanup).every(Boolean);}diff --git a/scripts/archive-tool.mjs b/scripts/archive-tool.mjsnew file mode 100644index 00000000..11e0c14f--- /dev/null+++ b/scripts/archive-tool.mjs@@ -0,0 +1,10 @@+import { existsSync } from "node:fs";+import { join } from "node:path";++export function tarExecutable() {+ if (process.platform !== "win32") return "tar";+ const systemRoot = process.env.SystemRoot || process.env.WINDIR;+ if (!systemRoot) return "tar";+ const systemTar = join(systemRoot, "System32", "tar.exe");+ return existsSync(systemTar) ? systemTar : "tar";+}diff --git a/scripts/assemble-client.mjs b/scripts/assemble-client.mjsindex 28eb5ae5..55cea759 100644--- a/scripts/assemble-client.mjs+++ b/scripts/assemble-client.mjs@@ -25,6 +25,7 @@ import { fileURLToPath } from "node:url";import { clientPackageTarget, CLOUDFLARED_VERSION } from "./client-package-targets.mjs";import { writeClientPlatformAssets } from "./client-icons.mjs";import { writeClientLicenseNotices } from "./package-licenses.mjs";+import { tarExecutable } from "./archive-tool.mjs";function fail(message) {throw new Error(message);@@ -131,7 +132,7 @@ function readDescriptor(path) {function assertOutsideRepository(repositoryRoot, outputRoot) {const path = relative(repositoryRoot, outputRoot);- if (path === "" || (!path.startsWith("..") && !isAbsolute(path))) {+ if (path === "" || (path.split(/[\\/]/)[0] !== ".." && !isAbsolute(path))) {fail("Client output directory must be outside the repository");}if (existsSync(outputRoot)) {@@ -139,11 +140,11 @@ function assertOutsideRepository(repositoryRoot, outputRoot) {}}-const positional = process.argv.slice(2, 5);-const options = process.argv.slice(5);-if (positional.length !== 3 || options.length % 2 !== 0) {+const positional = process.argv.slice(2, 4);+const options = process.argv.slice(4);+if (positional.length !== 2 || options.length % 2 !== 0) {fail(- "Usage: node scripts/assemble-client.mjs <app-release.json> <node-executable> <new-output-directory> --target <windows-amd64|linux-amd64|darwin-arm64> [--capture <executable>] [--tunnel <executable>]",+ "Usage: node scripts/assemble-client.mjs <app-release.json> <new-output-directory> --target <windows-amd64|linux-amd64|darwin-arm64> [--capture <executable>] [--tunnel <executable>]",);}@@ -174,19 +175,10 @@ if (!target) fail("Client package target is invalid");const repositoryRoot = realpathSync(resolve(dirname(fileURLToPath(import.meta.url)), ".."));const descriptorPath = realpathSync(resolve(positional[0]));-const nodePath = realpathSync(resolve(positional[1]));-const outputRoot = resolve(process.cwd(), positional[2]);+const outputRoot = resolve(process.cwd(), positional[1]);const capturePath = captureArgument ? realpathSync(resolve(captureArgument)) : null;const tunnelPath = tunnelArgument ? realpathSync(resolve(tunnelArgument)) : null;assertOutsideRepository(repositoryRoot, outputRoot);-assertTargetExecutable(nodePath, target, "Node runtime");-const expectedNodeVersion = `v${readFileSync(- join(repositoryRoot, ".node-version"),- "ascii",-).trim()}`;-if (run(nodePath, ["--version"], repositoryRoot) !== expectedNodeVersion) {- fail(`Node runtime must be ${expectedNodeVersion}`);-}if (capturePath && !target.captureName) {fail("Capture runtime is invalid for the Client package target");}@@ -208,21 +200,20 @@ if (!existsSync(artifactPath) || sha256(artifactPath) !== descriptor.artifactShaconst temporaryRoot = mkdtempSync(join(tmpdir(), `screener-client-${revision.slice(0, 7)}-`));const packageRoot = join(temporaryRoot, "package");-const appRoot = join(packageRoot, "app");+const releaseRoot = join(temporaryRoot, "release");try {- mkdirSync(appRoot, { recursive: true });- run("tar", ["-xzf", artifactPath, "-C", appRoot], repositoryRoot);- if (readFileSync(join(appRoot, "REVISION"), "ascii") !== `${revision}\n`) {+ // The application release is consumed for its provenance only: the Client+ // embeds the Web assets, so the revision, clean-tree and digest assertions+ // above plus this REVISION check tie the binary to that immutable release.+ mkdirSync(releaseRoot, { recursive: true });+ run(tarExecutable(), ["-xzf", artifactPath, "-C", releaseRoot], repositoryRoot);+ if (readFileSync(join(releaseRoot, "REVISION"), "ascii") !== `${revision}\n`) {fail("Extracted application revision does not match the Client");}- runNpm(["ci", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"], appRoot);-- const runtimeRoot = join(packageRoot, "runtime", "node");- mkdirSync(runtimeRoot, { recursive: true });- const nodeName = target.nodeName;- const packagedNode = join(runtimeRoot, nodeName);- copyFileSync(nodePath, packagedNode);- chmodSync(packagedNode, 0o755);+ // Build the Web assets the Go binary embeds. The checkout is clean and at the+ // release revision, so this reproduces that release's client.+ runNpm(["run", "build:client"], repositoryRoot);+ mkdirSync(packageRoot, { recursive: true });let packagedCapture = null;if (capturePath) {@@ -250,31 +241,25 @@ try {"build","-trimpath","-ldflags",- `-s -w -X github.com/TNTcraftHIM/Screener/native/client/internal/clientapp.BuildRevision=${revision}`,+ `-s -w -X github.com/TNTcraftHIM/Screener/internal/client/clientapp.BuildRevision=${revision}`,"-o",clientPath,"./cmd/screener-client",- ], join(repositoryRoot, "native", "client"), {+ ], repositoryRoot, {...process.env,GOOS: target.goos,GOARCH: target.goarch,CGO_ENABLED: "0",});chmodSync(clientPath, 0o755);+ assertTargetExecutable(clientPath, target, "Client executable");writeClientLicenseNotices(repositoryRoot, packageRoot, goCommand, target,packagedTunnel ? CLOUDFLARED_VERSION : null);const platformAssets = writeClientPlatformAssets({packageRoot,target,revision,- iconPath: join(- repositoryRoot,- "native",- "client",- "cmd",- "screener-client",- "screener.ico",- ),+ iconPath: join(repositoryRoot, "cmd", "screener-client", "screener.ico"),});writeFileSync(join(packageRoot, "REVISION"), `${revision}\n`, "ascii");@@ -290,13 +275,11 @@ try {platform: target.goos,arch: target.goarch,client: clientName,- node: `runtime/node/${nodeName}`,nativeCapture: packagedCapture ? `runtime/native/${target.captureName}` : null,publicTunnel: packagedTunnel? `runtime/tunnel/${target.tunnelName}`: null,platformAssets,- app: "app",})}\n`);} finally {rmSync(temporaryRoot, { recursive: true, force: true });diff --git a/scripts/browser-gate-harness.ts b/scripts/browser-gate-harness.tsindex 4d0d7295..f160b76f 100644--- a/scripts/browser-gate-harness.ts+++ b/scripts/browser-gate-harness.ts@@ -27,11 +27,15 @@ interface AsyncCloseable {close(): Promise<void>;}+// A gate's server is either an in-process page server it closes directly or a+// spawned Screener server it stops like any other child.+export type CleanupServer = AsyncCloseable | ChildProcessWithoutNullStreams;+export interface CleanupResources {cdp: CdpConnection | null;native: ChildProcessWithoutNullStreams | null;chrome: ChildProcessWithoutNullStreams | null;- server: AsyncCloseable | null;+ server: CleanupServer | null;profile: string | null;ports: number[];}@@ -137,6 +141,27 @@ export class CdpConnection {}}+// launchChrome starts an isolated Chrome process with the shared CDP flags.+export function launchChrome(+ executable: string,+ debugPort: number,+ profile: string,+ flags: string[] = [],+ options: { cwd?: string; env?: NodeJS.ProcessEnv } = {},+): ChildProcessWithoutNullStreams {+ return spawn(executable, [+ `--remote-debugging-port=${debugPort}`,+ `--user-data-dir=${profile}`,+ ...flags,+ "about:blank",+ ], {+ cwd: options.cwd,+ env: options.env,+ stdio: "pipe",+ windowsHide: true,+ });+}+export function withDeadline<T>(operation: () => Promise<T>,deadline: number,@@ -297,12 +322,16 @@ export async function reservePort(): Promise<number> {});}+// Readiness is the debugging endpoint, never the spawned process: Chrome's+// Windows launcher exits as soon as the browser process takes over the profile+// (measured: exit at ~140 ms, endpoint ready at ~440 ms). The deadline bounds+// the wait, and the launcher's exit code is reported when it runs out.export async function waitForVersion(port: number,child: ChildProcessWithoutNullStreams,): Promise<{ Browser: string; webSocketDebuggerUrl: string }> {const deadline = Date.now() + 20_000;- while (Date.now() < deadline && child.exitCode === null) {+ while (Date.now() < deadline) {try {return await fetchJsonBefore<{ Browser: string; webSocketDebuggerUrl: string }>(`http://127.0.0.1:${port}/json/version`,@@ -311,7 +340,7 @@ export async function waitForVersion(} catch {}await delay(Math.min(100, Math.max(0, deadline - Date.now())));}- throw new Error("Chrome startup timed out");+ throw new Error(`Chrome startup timed out (exit ${child.exitCode ?? "running"})`);}export async function cleanupRun(@@ -339,13 +368,16 @@ export async function cleanupRun(const nativeExited = resources.native? await stopProcessTree(resources.native): true;+ const server = resources.server;let serverClosed = true;- if (resources.server) {+ if (server && "close" in server) {try {- await withDeadline(() => resources.server!.close(), Date.now() + 5_000);+ await withDeadline(() => server.close(), Date.now() + 5_000);} catch {serverClosed = false;}+ } else if (server) {+ serverClosed = await stopProcessTree(server);}const portsClosed = await waitForPortsClosed([...new Set(resources.ports)],diff --git a/scripts/check-client.mjs b/scripts/check-client.mjsindex 53a40b05..2e41d2a3 100644--- a/scripts/check-client.mjs+++ b/scripts/check-client.mjs@@ -9,10 +9,15 @@ import {import { basename, dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";-import { CLIENT_PACKAGE_TARGETS } from "./client-package-targets.mjs";+import { CLIENT_PACKAGE_TARGETS, clientPackageTarget } from "./client-package-targets.mjs";++// Every Go command embeds the Vite output, so the build, vet and test steps all+// fail without it. The Hosted binary is cross-built for its deployment target.+const CLIENT_INDEX = join("internal", "server", "webassets", "dist", "index.html");+const SERVER_TARGET = clientPackageTarget("linux-amd64");const root = realpathSync(resolve(dirname(fileURLToPath(import.meta.url)), ".."));-const clientRoot = join(root, "native", "client");+const captureRoot = join(root, "native", "capture");const mode = process.argv[2] ?? "--all";if (!["--all", "--core", "--capture-only"].includes(mode)) {@@ -36,54 +41,65 @@ function run(command, args, options = {}) {return options.capture ? result.stdout.trim() : "";}+function buildWebAssets() {+ if (existsSync(join(root, CLIENT_INDEX))) return;+ if (process.platform === "win32") {+ run(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "npm run build:client"]);+ return;+ }+ run("npm", ["run", "build:client"]);+}+function checkCore() {+ buildWebAssets();const go = process.env.SCREENER_GO?.trim() || "go";- const goRoot = run(go, ["env", "GOROOT"], { cwd: clientRoot, capture: true });+ const goRoot = run(go, ["env", "GOROOT"], { capture: true });const gofmt = process.env.SCREENER_GOFMT?.trim() ||join(goRoot, "bin", process.platform === "win32" ? "gofmt.exe" : "gofmt");- const unformatted = run(gofmt, ["-l", "."], { cwd: clientRoot, capture: true });+ const unformatted = run(gofmt, ["-l", "."], { capture: true });if (unformatted) {throw new Error(`Go source is not formatted:\n${unformatted}`);}runClientTests(go);- run(go, ["vet", "./..."], { cwd: clientRoot });+ run(go, ["vet", "./..."]);const buildRoot = join(root, "build", "client-check");mkdirSync(buildRoot, { recursive: true });- for (const target of CLIENT_PACKAGE_TARGETS) {- for (const command of ["screener-client", "screener-peer-gate"]) {- const outputName = target.goos === "windows"- ? `${command}.exe`- : `${command}-${target.id}`;- run(go, ["build", "-trimpath", "-o", join(buildRoot, outputName), `./cmd/${command}`], {- cwd: clientRoot,- env: {- ...process.env,- GOOS: target.goos,- GOARCH: target.goarch,- CGO_ENABLED: "0",- },- });- }+ const builds = CLIENT_PACKAGE_TARGETS.flatMap((target) =>+ ["screener-client", "screener-peer-gate"].map((command) => ({ target, command })),+ );+ builds.push({ target: SERVER_TARGET, command: "screener-server" });+ for (const { target, command } of builds) {+ const outputName = target.goos === "windows"+ ? `${command}.exe`+ : `${command}-${target.id}`;+ run(go, ["build", "-trimpath", "-o", join(buildRoot, outputName), `./cmd/${command}`], {+ env: {+ ...process.env,+ GOOS: target.goos,+ GOARCH: target.goarch,+ CGO_ENABLED: "0",+ },+ });}}function runClientTests(go) {if (process.platform !== "win32") {- run(go, ["test", "./..."], { cwd: clientRoot });+ run(go, ["test", "./..."]);return;}// Windows associates its listen prompt with the test executable path. Keep// the one UDP integration package at a stable path so repeated checks do not// create a new firewall rule for every Go build directory.- const packages = run(go, ["list", "./..."], { cwd: clientRoot, capture: true })+ const packages = run(go, ["list", "./..."], { capture: true }).split(/\r?\n/).map((value) => value.trim()).filter(Boolean);const stableNetworkPackages = [{- package: "github.com/TNTcraftHIM/Screener/native/client/internal/mediaedge",+ package: "github.com/TNTcraftHIM/Screener/internal/client/mediaedge",binary: "mediaedge.test.exe",},];@@ -92,16 +108,14 @@ function runClientTests(go) {);const otherPackages = packages.filter((value) => !stablePackageNames.has(value));if (otherPackages.length > 0) {- run(go, ["test", ...otherPackages], { cwd: clientRoot });+ run(go, ["test", ...otherPackages]);}const stableRoot = join(root, "build", "client-check");mkdirSync(stableRoot, { recursive: true });for (const entry of stableNetworkPackages) {const binary = join(stableRoot, entry.binary);- run(go, ["test", "-c", "-o", binary, entry.package], {- cwd: clientRoot,- });- run(binary, ["-test.v"], { cwd: clientRoot });+ run(go, ["test", "-c", "-o", binary, entry.package]);+ run(binary, ["-test.v"]);}}@@ -138,23 +152,17 @@ function checkPlatformCapture() {"-ExecutionPolicy","Bypass","-File",- join(clientRoot, "platform", "windows", "capture", "build.ps1"),+ join(captureRoot, "windows", "build.ps1"),"-OutputDirectory",buildRoot,"-Check",]);executable = join(buildRoot, "screener-client-capture.exe");} else if (process.platform === "darwin") {- run("sh", [- join(clientRoot, "platform", "darwin", "capture", "build.sh"),- buildRoot,- ]);+ run("sh", [join(captureRoot, "darwin", "build.sh"), buildRoot]);executable = join(buildRoot, "screener-client-capture");} else {- run("sh", [- join(clientRoot, "platform", "linux", "capture", "build.sh"),- buildRoot,- ]);+ run("sh", [join(captureRoot, "linux", "build.sh"), buildRoot]);executable = join(buildRoot, "screener-client-capture");}if (!existsSync(executable)) {diff --git a/scripts/check-project-state.ps1 b/scripts/check-project-state.ps1index fade1b5c..64456006 100644--- a/scripts/check-project-state.ps1+++ b/scripts/check-project-state.ps1@@ -19,7 +19,7 @@ if ($LASTEXITCODE -ne 0) { throw "Working-tree whitespace check failed." }git diff --cached --checkif ($LASTEXITCODE -ne 0) { throw "Staged whitespace check failed." }-if ($env:SCREENER_BASE_SHA) {+if ($env:SCREENER_BASE_SHA -and $env:SCREENER_BASE_SHA -notmatch '^0{40}$') {git diff --check "$env:SCREENER_BASE_SHA...HEAD"if ($LASTEXITCODE -ne 0) { throw "Commit-range whitespace check failed." }}diff --git a/scripts/check-project-state.sh b/scripts/check-project-state.shindex 87272b3b..e8302ea2 100755--- a/scripts/check-project-state.sh+++ b/scripts/check-project-state.sh@@ -15,7 +15,7 @@ done < scripts/required-project-paths.txtgit diff --checkgit diff --cached --check-if [ -n "${SCREENER_BASE_SHA:-}" ]; then+if [ -n "${SCREENER_BASE_SHA:-}" ] && [ "$SCREENER_BASE_SHA" != "0000000000000000000000000000000000000000" ]; thengit diff --check "$SCREENER_BASE_SHA"...HEADfidiff --git a/scripts/client-browser-fanout-gate.ts b/scripts/client-browser-fanout-gate.tsindex fa98327b..7a21d7c7 100644--- a/scripts/client-browser-fanout-gate.ts+++ b/scripts/client-browser-fanout-gate.ts@@ -1,16 +1,20 @@-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";import { mkdtemp, mkdir, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join, resolve } from "node:path";-import { createScreenerServer, type ScreenerServer } from "../src/server/app";-import { createLocalServerConfig } from "../src/server/local-config";import {- CdpConnection, cleanupRun, createPage, evaluate, reservePort,+ CdpConnection, cleanupRun, createPage, evaluate, fetchJsonBefore, launchChrome, reservePort,waitForSample, waitForVersion, type PageHandle,} from "./browser-gate-harness";import { decodeClientEndpoint } from "./client-gate-endpoint";const ROOT = resolve(import.meta.dirname, "..");+const BUILD_ROOT = join(ROOT, "build/client-check");+// A documentation-only LAN address: it makes the room server publish a LAN+// invitation the gate rewrites to its loopback origins, exactly as the packaged+// Client does on a real network.+const LAN_ADDRESS = "192.0.2.1";+const initialAudio = process.env.SCREENER_CLIENT_GATE_AUDIO !== "false";const probe = String.raw`(() => {localStorage.setItem('screener:ui-lang', 'en');@@ -91,6 +95,54 @@ const probe = String.raw`(() => {};})()`;+function build(command: string, args: string[]): void {+ const result = spawnSync(command, args, { cwd: ROOT, encoding: "utf8", windowsHide: true });+ if (result.error) throw result.error;+ if (result.status !== 0) {+ throw new Error((result.stderr || result.stdout).trim() || command + " failed");+ }+}++// startRoomServer builds and starts the Screener server the Browser pages and+// both Clients share. SCREENER_ENV stays development because production+// requires an https public origin, a site password and STUN; the Web assets are+// embedded either way.+async function startRoomServer(+ port: number,+ workingDirectory: string,+): Promise<ChildProcessWithoutNullStreams> {+ const go = process.env.SCREENER_GO?.trim() || "go";+ await mkdir(BUILD_ROOT, { recursive: true });+ // The server embeds the Vite output, so the Web build precedes the Go build.+ build(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "npm run build:client"]);+ const binary = join(BUILD_ROOT, "screener-server.exe");+ build(go, ["build", "-trimpath", "-o", binary, "./cmd/screener-server"]);+ const origins = [`http://localhost:${port}`, `http://127.0.0.1:${port}`, `http://${LAN_ADDRESS}:${port}`];+ const child = spawn(binary, [], {+ // The gate profile has no .env, and the environment is explicit: the+ // configuration this measurement runs against is these five values, never+ // the repository's development file or the operator's shell.+ cwd: workingDirectory, stdio: "pipe", windowsHide: true,+ env: {+ PATH: process.env.PATH,+ SystemRoot: process.env.SystemRoot,+ SCREENER_ENV: "development",+ PORT: String(port),+ LISTEN_HOST: "127.0.0.1",+ PUBLIC_BASE_URL: `http://${LAN_ADDRESS}:${port}`,+ ALLOWED_ORIGINS: origins.join(","),+ },+ });+ child.stdout.resume();+ child.stderr.resume();+ await waitForSample(+ (deadline) => fetchJsonBefore<{ status: string }>(`http://127.0.0.1:${port}/healthz`, deadline),+ (value) => value.status === "ok",+ 20000,+ );+ return child;+}+async function main(): Promise<void> {if (process.env.SCREENER_CLIENT_BROWSER_FANOUT_GATE !== "true") throw new Error("Browser fanout gate was not enabled");const chromePath = process.env.CHROME_PATH;@@ -102,21 +154,17 @@ async function main(): Promise<void> {let relayClient: ChildProcessWithoutNullStreams | null = null;let chrome: ChildProcessWithoutNullStreams | null = null;let cdp: CdpConnection | null = null;- let server: ScreenerServer | null = null;+ let server: ChildProcessWithoutNullStreams | null = null;let clientPort = 0;let relayPort = 0;const pages: PageHandle[] = [];const checks: Record<string, unknown> = {};let stage = "startup", error: string | null = null;try {- server = await createScreenerServer({- config: createLocalServerConfig({ port: appPort, publicAddress: "192.0.2.1" }),- frontend: { mode: "static", directory: join(ROOT, "dist/client") },- });- await server.listen(appPort, "127.0.0.1");- client = spawn(process.env.SCREENER_CLIENT_EXE || join(ROOT, "build/client-check/screener-client.exe"), [+ server = await startRoomServer(appPort, profile);+ client = spawn(process.env.SCREENER_CLIENT_EXE || join(BUILD_ROOT, "screener-client.exe"), ["--site", origin, "--config", join(profile, "client.json"),- "--capture-process", join(ROOT, "build/client-check/screener-client-capture.exe"),+ "--capture-process", join(BUILD_ROOT, "screener-client-capture.exe"),], { windowsHide: true, stdio: "pipe", env: { ...process.env, SCREENER_CLIENT_GATE_NO_BROWSER: "true" } });client.stderr.resume();let output = "";@@ -125,12 +173,12 @@ async function main(): Promise<void> {if (!clientPort && output.includes("\n")) clientPort = decodeClientEndpoint(output.split("\n")[0]!).port;});await waitForSample(async () => clientPort, (value) => value > 0, 15000);- chrome = spawn(chromePath, [- `--remote-debugging-port=${debugPort}`, `--user-data-dir=${profile}`, "--headless=new",+ chrome = launchChrome(chromePath, debugPort, profile, [+ "--headless=new","--no-first-run", "--no-default-browser-check", "--no-proxy-server","--autoplay-policy=no-user-gesture-required", "--disable-background-timer-throttling",- "--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows", "about:blank",- ], { windowsHide: true, stdio: "pipe" });+ "--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows",+ ]);chrome.stdout.resume(); chrome.stderr.resume();const version = await waitForVersion(debugPort, chrome);checks.browser = version.Browser;@@ -161,9 +209,9 @@ async function main(): Promise<void> {let invite = await evaluate<string>(cdp, host, "document.querySelector('.lr-invite-url').value", Date.now()+5000);const url = new URL(invite); url.host = `localhost:${appPort}`; invite = url.toString();const relayOrigin = `http://127.0.0.1:${appPort}`;- relayClient = spawn(process.env.SCREENER_CLIENT_EXE || join(ROOT,"build/client-check/screener-client.exe"), [+ relayClient = spawn(process.env.SCREENER_CLIENT_EXE || join(BUILD_ROOT,"screener-client.exe"), ["--site", relayOrigin, "--config", join(profile,"relay-client.json"),- "--capture-process", join(ROOT,"build/client-check/screener-client-capture.exe"),+ "--capture-process", join(BUILD_ROOT,"screener-client-capture.exe"),], { windowsHide:true, stdio:"pipe", env:{...process.env,SCREENER_CLIENT_GATE_NO_BROWSER:"true"} });relayClient.stderr.resume(); let relayOutput="";relayClient.stdout.on("data", (chunk:Buffer) => {@@ -224,9 +272,9 @@ async function main(): Promise<void> {checks.clientExitRecovery = true;checks.finalHost = await read(host);if ((checks.finalHost as any).errors.length > 0) throw new Error("Browser reported an unhandled media error");- await mkdir(join(ROOT,"build/client-check"), {recursive:true});+ await mkdir(BUILD_ROOT, {recursive:true});const screenshot = await cdp.call<{data:string}>("Page.captureScreenshot", {format:"png"}, host.sessionId, Date.now()+5000);- await writeFile(join(ROOT,"build/client-check/browser-fanout.png"), Buffer.from(screenshot.data,"base64"));+ await writeFile(join(BUILD_ROOT,"browser-fanout.png"), Buffer.from(screenshot.data,"base64"));await click(host, 'button[aria-label="Stop sharing"]');stage = "done";} catch (caught) {@@ -237,8 +285,8 @@ async function main(): Promise<void> {const relayCleanup = await cleanupRun({cdp:null,native:relayClient,chrome:null,server:null,profile:null,ports:relayPort?[relayPort]:[]});const cleanup = await cleanupRun({cdp, native:client, chrome, server, profile, ports:[appPort,debugPort,...(clientPort?[clientPort]:[])]});const result = {passed: error===null && Object.values(cleanup).every(Boolean) && relayCleanup.nativeExited && relayCleanup.portsClosed, stage, checks, error, cleanup};- await mkdir(join(ROOT,"build/client-check"),{recursive:true});- await writeFile(join(ROOT,"build/client-check/browser-fanout.json"), JSON.stringify(result,null,2));+ await mkdir(BUILD_ROOT,{recursive:true});+ await writeFile(join(BUILD_ROOT,"browser-fanout.json"), JSON.stringify(result,null,2));process.stdout.write(JSON.stringify(result)+"\n");if (!result.passed) process.exitCode=1;}diff --git a/scripts/client-gate-endpoint.ts b/scripts/client-gate-endpoint.tsindex a1fb2c7c..c95fd285 100644--- a/scripts/client-gate-endpoint.ts+++ b/scripts/client-gate-endpoint.ts@@ -1,6 +1,12 @@+import type { ChildProcessWithoutNullStreams } from "node:child_process";++import {+ NATIVE_CLIENT_PORT_END,+ NATIVE_CLIENT_PORT_START,+} from "../src/client/native/wire";+import { withDeadline } from "./browser-gate-harness";+const INSTANCE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;-const CLIENT_PORT_START = 39_721;-const CLIENT_PORT_END = 39_730;export interface ClientEndpoint {url: string;@@ -22,8 +28,8 @@ export function decodeClientEndpoint(line: string): ClientEndpoint {const endpoint = value as Partial<ClientEndpoint>;if (!Number.isInteger(endpoint.port) ||- endpoint.port! < CLIENT_PORT_START ||- endpoint.port! > CLIENT_PORT_END ||+ endpoint.port! < NATIVE_CLIENT_PORT_START ||+ endpoint.port! > NATIVE_CLIENT_PORT_END ||endpoint.host !== `127.0.0.1:${endpoint.port}` ||endpoint.url !== `http://${endpoint.host}` ||typeof endpoint.instanceToken !== "string" ||@@ -34,3 +40,58 @@ export function decodeClientEndpoint(line: string): ClientEndpoint {}return endpoint as ClientEndpoint;}++// readClientEndpoint waits for the first valid loopback endpoint from stdout.+export async function readClientEndpoint(+ client: ChildProcessWithoutNullStreams,+ options: { timeoutMs?: number; ignoreNonEndpointLines?: boolean } = {},+): Promise<ClientEndpoint> {+ const deadline = Date.now() + (options.timeoutMs ?? 10_000);+ let cleanup = () => undefined;+ try {+ return await withDeadline(+ () => new Promise<ClientEndpoint>((resolveEndpoint, rejectEndpoint) => {+ let buffered = "";+ const finish = (callback: () => void) => {+ cleanup();+ callback();+ };+ const onData = (chunk: Buffer) => {+ buffered += chunk.toString();+ for (;;) {+ const newline = buffered.indexOf("\n");+ if (newline < 0) return;+ const line = buffered.slice(0, newline).trim();+ buffered = buffered.slice(newline + 1);+ try {+ const endpoint = decodeClientEndpoint(line);+ finish(() => resolveEndpoint(endpoint));+ return;+ } catch (error) {+ if (!options.ignoreNonEndpointLines) {+ finish(() => rejectEndpoint(error));+ return;+ }+ }+ }+ };+ const onError = (error: Error) => finish(() => rejectEndpoint(error));+ const onExit = (code: number | null, signal: NodeJS.Signals | null) =>+ finish(() => rejectEndpoint(+ new Error(`Client exited before endpoint (${code ?? signal ?? "signal"})`),+ ));+ cleanup = () => {+ client.stdout.off("data", onData);+ client.off("error", onError);+ client.off("exit", onExit);+ };+ client.stdout.on("data", onData);+ client.once("error", onError);+ client.once("exit", onExit);+ }),+ deadline,+ );+ } finally {+ cleanup();+ }+}diff --git a/scripts/client-link-gate.ts b/scripts/client-link-gate.tsindex c9203c86..c14dd7da 100644--- a/scripts/client-link-gate.ts+++ b/scripts/client-link-gate.ts@@ -204,8 +204,6 @@ async function main(): Promise<void> {const destination = `${remote.user}@${remote.host}`;const go = process.env.SCREENER_GO?.trim() || "go";const configuredClient = process.env.SCREENER_CLIENT_EXE?.trim();- const node = process.env.SCREENER_CLIENT_NODE?.trim() || process.execPath;- const app = process.env.SCREENER_CLIENT_APP?.trim() || ROOT;const tunnel = process.env.SCREENER_CLOUDFLARED?.trim() ||join(BUILD_ROOT, process.platform === "win32" ? "cloudflared.exe" : "cloudflared");const profile = await mkdtemp(join(tmpdir(), "screener-client-link-"));@@ -231,14 +229,19 @@ async function main(): Promise<void> {try {result.stage = "build";if (!configuredClient) {+ // The Client embeds the Vite output, and this gate asserts on the page it+ // serves over the public link, so the Web build precedes the Go build.+ if (process.platform === "win32") {+ run(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "npm run build:client"]);+ } else {+ run("npm", ["run", "build:client"]);+ }run(go, ["build", "-trimpath", "-o", clientBinary, "./cmd/screener-client"],- join(ROOT, "native", "client"));+ ROOT);}result.stage = "client-start";client = spawn(clientBinary, ["--link",- "--node", node,- "--app", app,"--config", join(profile, "client.json"),"--port", String(port),"--lan-address", localLANAddress(),diff --git a/scripts/client-local-gate.ts b/scripts/client-local-gate.tsindex eafad5d1..3f993ac8 100644--- a/scripts/client-local-gate.ts+++ b/scripts/client-local-gate.ts@@ -1,8 +1,7 @@import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";import { mkdtemp, readFile } from "node:fs/promises";import { tmpdir } from "node:os";-import { join, resolve } from "node:path";-import { fileURLToPath } from "node:url";+import { join } from "node:path";import {CdpConnection,@@ -10,18 +9,15 @@ import {createPage,evaluate,fetchJsonBefore,+ launchChrome,reservePort,waitForSample,waitForVersion,- withDeadline,} from "./browser-gate-harness";import {- decodeClientEndpoint,- type ClientEndpoint as Endpoint,+ readClientEndpoint,} from "./client-gate-endpoint";-const ROOT = resolve(fileURLToPath(new URL("..", import.meta.url)));-interface GateReport {passed: boolean;platform: NodeJS.Platform;@@ -55,45 +51,16 @@ const LOCAL_PAGE_STATE = `fetch('/api/site-access')hostReady: Boolean(document.querySelector('.lr-host-personal-controls')),}))`;-async function readEndpoint(- client: ChildProcessWithoutNullStreams,-): Promise<Endpoint> {- let buffered = "";- return withDeadline(- () => new Promise<Endpoint>((resolveEndpoint, rejectEndpoint) => {- const onData = (chunk: Buffer) => {- buffered += chunk.toString();- const newline = buffered.indexOf("\n");- if (newline < 0) return;- client.stdout.off("data", onData);- try {- resolveEndpoint(decodeClientEndpoint(buffered.slice(0, newline)));- } catch (error) {- rejectEndpoint(error);- }- };- client.stdout.on("data", onData);- client.once("error", rejectEndpoint);- client.once("exit", (code) =>- rejectEndpoint(new Error(`Client exited before readiness (${code ?? "signal"})`)),- );- }),- Date.now() + 10_000,- );-}-async function main(): Promise<void> {if (process.env.SCREENER_CLIENT_LOCAL_GATE !== "true") {throw new Error("Local Client gate was not explicitly enabled");}const browserPath = process.env.CHROME_PATH?.trim();const clientPath = process.env.SCREENER_CLIENT_EXE?.trim();- const nodePath = process.env.SCREENER_CLIENT_NODE?.trim();- const appDirectory = process.env.SCREENER_CLIENT_APP?.trim() || ROOT;const lanAddress = process.env.SCREENER_CLIENT_GATE_LAN_ADDRESS?.trim();- if (!browserPath || !clientPath || !nodePath || !lanAddress) {+ if (!browserPath || !clientPath || !lanAddress) {throw new Error(- "CHROME_PATH, SCREENER_CLIENT_EXE, SCREENER_CLIENT_NODE, and SCREENER_CLIENT_GATE_LAN_ADDRESS are required",+ "CHROME_PATH, SCREENER_CLIENT_EXE, and SCREENER_CLIENT_GATE_LAN_ADDRESS are required",);}@@ -123,8 +90,7 @@ async function main(): Promise<void> {let loopbackPort = 0;try {client = spawn(clientPath, [- "--node", nodePath,- "--app", appDirectory,+ "--local","--config", configPath,"--lan-address", lanAddress,"--port", String(appPort),@@ -134,7 +100,7 @@ async function main(): Promise<void> {env: { ...process.env, SCREENER_CLIENT_GATE_NO_BROWSER: "true" },});client.stderr.resume();- const endpoint = await readEndpoint(client);+ const endpoint = await readClientEndpoint(client);loopbackPort = endpoint.port;report.clientStarted = true;await waitForSample(@@ -158,9 +124,7 @@ async function main(): Promise<void> {"screener-client": "1",}).toString();- browser = spawn(browserPath, [- `--remote-debugging-port=${debugPort}`,- `--user-data-dir=${profile}`,+ browser = launchChrome(browserPath, debugPort, profile, ["--headless=new",...(process.env.SCREENER_CLIENT_GATE_NO_SANDBOX === "true"? ["--no-sandbox"]@@ -168,8 +132,7 @@ async function main(): Promise<void> {"--no-first-run","--no-proxy-server","--disable-logging",- "about:blank",- ], { stdio: "pipe", windowsHide: true });+ ]);browser.stdout.resume();browser.stderr.resume();const version = await waitForVersion(debugPort, browser);diff --git a/scripts/client-loopback-gate.ts b/scripts/client-loopback-gate.tsindex fd3383a7..06f07e82 100644--- a/scripts/client-loopback-gate.ts+++ b/scripts/client-loopback-gate.ts@@ -9,14 +9,19 @@ import {cleanupRun,createPage,evaluate,+ launchChrome,waitForVersion,- withDeadline,} from "./browser-gate-harness";import {- decodeClientEndpoint,+ readClientEndpoint,type ClientEndpoint as Endpoint,} from "./client-gate-endpoint";-import { NATIVE_CLIENT_PROTOCOL, NATIVE_CLIENT_SUBPROTOCOL } from "../src/client/native/wire";+import {+ NATIVE_CLIENT_PORT_END,+ NATIVE_CLIENT_PORT_START,+ NATIVE_CLIENT_PROTOCOL,+ NATIVE_CLIENT_SUBPROTOCOL,+} from "../src/client/native/wire";const PAGE_URL = "https://share.bonfire.icu/";const NATIVE_PROTOCOL = NATIVE_CLIENT_PROTOCOL;@@ -40,33 +45,6 @@ interface GateReport {profileRemoved: boolean;}-async function readEndpoint(- client: ChildProcessWithoutNullStreams,-): Promise<Endpoint> {- let buffered = "";- return await withDeadline(- () => new Promise<Endpoint>((resolveEndpoint, rejectEndpoint) => {- const onData = (chunk: Buffer) => {- buffered += chunk.toString();- const newline = buffered.indexOf("\n");- if (newline < 0) return;- client.stdout.off("data", onData);- try {- resolveEndpoint(decodeClientEndpoint(buffered.slice(0, newline)));- } catch (error) {- rejectEndpoint(error instanceof Error ? error : new Error("Client endpoint is invalid"));- }- };- client.stdout.on("data", onData);- client.once("error", rejectEndpoint);- client.once("exit", (code) => {- rejectEndpoint(new Error(`Client exited before endpoint (${code ?? "signal"})`));- });- }),- Date.now() + 8_000,- );-}-async function browserHandshake(cdp: CdpConnection,page: { sessionId: string },@@ -75,8 +53,8 @@ async function browserHandshake(const endpointJSON = JSON.stringify({host: "127.0.0.1",expectedPort: endpoint.port,- portStart: 39721,- portEnd: 39730,+ portStart: NATIVE_CLIENT_PORT_START,+ portEnd: NATIVE_CLIENT_PORT_END,});return await evaluate(cdp,@@ -205,7 +183,7 @@ async function main(): Promise<void> {env: { ...process.env, SCREENER_CLIENT_GATE_NO_BROWSER: "true" },});client.stderr.resume();- const endpoint = await readEndpoint(client);+ const endpoint = await readClientEndpoint(client, { timeoutMs: 8_000 });report.clientStarted = true;const portServer = createServer();@@ -220,16 +198,13 @@ async function main(): Promise<void> {portServer.close((error) => error ? rejectPort(error) : resolvePort(address.port));});});- browser = spawn(browserPath, [- `--remote-debugging-port=${debugPort}`,- `--user-data-dir=${profile}`,+ browser = launchChrome(browserPath, debugPort, profile, ["--headless=new",...(disposableNoSandbox ? ["--no-sandbox"] : []),"--no-first-run","--no-proxy-server","--disable-logging",- "about:blank",- ], { stdio: "pipe", windowsHide: true });+ ]);browser.stdout.resume();browser.stderr.resume();const version = await waitForVersion(debugPort, browser);diff --git a/scripts/client-media-gate.ts b/scripts/client-media-gate.tsindex 35fa85f4..425252c8 100644--- a/scripts/client-media-gate.ts+++ b/scripts/client-media-gate.ts@@ -9,22 +9,25 @@ import {cleanupRun,createPage,evaluate,+ launchChrome,reservePort,waitForSample,waitForVersion,withDeadline,} from "./browser-gate-harness";import {- decodeClientEndpoint,+ readClientEndpoint,type ClientEndpoint as Endpoint,} from "./client-gate-endpoint";+import {+ NATIVE_CLIENT_PROTOCOL,+ NATIVE_CLIENT_SUBPROTOCOL,+} from "../src/client/native/wire";const ROOT = resolve(import.meta.dirname, "..");const BUILD_ROOT = join(ROOT, "build", "client-check");const SOURCE_TITLE = "Screener Native Gate Source";-const GATE_STUN_URL =- process.env.SCREENER_CLIENT_GATE_STUN_URL?.trim() ||- "stun:share.bonfire.icu:3478";+const GATE_STUN_URLS = process.env.SCREENER_CLIENT_GATE_STUN_URLS?.trim();interface Probe {protocol: number;@@ -242,36 +245,13 @@ async function stopCapture(child: ChildProcessWithoutNullStreams): Promise<void>if (code !== 0) throw new Error("Native capture did not stop cleanly");}-async function readEndpoint(child: ChildProcessWithoutNullStreams): Promise<Endpoint> {- let buffered = "";- return withDeadline(- () => new Promise<Endpoint>((resolveEndpoint, rejectEndpoint) => {- const onData = (chunk: Buffer) => {- buffered += chunk.toString();- const newline = buffered.indexOf("\n");- if (newline < 0) return;- child.stdout.off("data", onData);- try {- resolveEndpoint(decodeClientEndpoint(buffered.slice(0, newline)));- } catch (error) {- rejectEndpoint(error);- }- };- child.stdout.on("data", onData);- child.once("error", rejectEndpoint);- child.once("exit", (code) => {- rejectEndpoint(new Error("Client exited before readiness (" + String(code) + ")"));- });- }),- Date.now() + 10_000,- );-}-async function browserMediaGate(input: {endpoint: Endpoint;+ protocol: number;+ subprotocol: string;sourceTitle: string;sourceKind: "window" | "display";- stunUrl: string;+ stunUrls: string;}): Promise<MediaEvidence> {let socket: WebSocket | null = null;const peers: RTCPeerConnection[] = [];@@ -306,7 +286,7 @@ async function browserMediaGate(input: {} as RequestInit);const health = await healthResponse.json();if (- health.protocol !== 7 ||+ health.protocol !== input.protocol ||health.service !== "screener-client" ||health.instanceToken !== input.endpoint.instanceToken ||health.nativeMedia?.video !== true ||@@ -320,7 +300,7 @@ async function browserMediaGate(input: {socket = new WebSocket("ws://127.0.0.1:" + input.endpoint.port + "/control",- ["screener-client-v8." + input.endpoint.instanceToken],+ [input.subprotocol + "." + input.endpoint.instanceToken],);await new Promise<void>((resolveOpen, rejectOpen) => {const timer = window.setTimeout(@@ -493,7 +473,7 @@ async function browserMediaGate(input: {const offer = await request("prepare-edge", {shareId,connectionId: nextConnectionId,- iceServers: [{ urls: [input.stunUrl] }],+ iceServers: [{ urls: input.stunUrls.split(",") }],});await peer.setRemoteDescription({ type: "offer", sdp: offer.sdp });edge.remoteDescriptionSet = true;@@ -668,6 +648,9 @@ async function main(): Promise<void> {}const chromePath = process.env.CHROME_PATH?.trim();if (!chromePath) throw new Error("CHROME_PATH is required");+ if (!GATE_STUN_URLS) {+ throw new Error("SCREENER_CLIENT_GATE_STUN_URLS is required");+ }const profile = await mkdtemp(join(tmpdir(), "screener-client-media-"));// Keep network-capable binaries at a stable repository path. Windows@@ -733,7 +716,7 @@ async function main(): Promise<void> {"-ExecutionPolicy","Bypass","-File",- join(ROOT, "native", "client", "platform", "windows", "capture", "build.ps1"),+ join(ROOT, "native", "capture", "windows", "build.ps1"),"-OutputDirectory",buildRoot,]);@@ -746,9 +729,7 @@ async function main(): Promise<void> {}server = await startPageServer(pagePort);- chrome = spawn(chromePath, [- "--remote-debugging-port=" + debugPort,- "--user-data-dir=" + profile,+ chrome = launchChrome(chromePath, debugPort, profile, ["--no-first-run","--no-default-browser-check","--disable-extensions",@@ -757,8 +738,7 @@ async function main(): Promise<void> {"--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--window-size=1280,900",- "about:blank",- ], { stdio: "pipe", windowsHide: true });+ ]);chrome.stdout.resume();chrome.stderr.resume();const version = await waitForVersion(debugPort, chrome);@@ -868,10 +848,14 @@ async function main(): Promise<void> {);const clientExecutable = join(packageRoot, "screener-client.exe");const go = process.env.SCREENER_GO?.trim() || "go";+ // The Client embeds the Vite output, so the Web build precedes the Go build.+ run(process.env.ComSpec || "cmd.exe", [+ "/d", "/s", "/c", "npm run build:client",+ ], ROOT);run(go,["build", "-trimpath", "-o", clientExecutable, "./cmd/screener-client"],- join(ROOT, "native", "client"),+ ROOT,);client = spawn(clientExecutable, ["--site",@@ -884,7 +868,7 @@ async function main(): Promise<void> {env: { ...process.env, SCREENER_CLIENT_GATE_NO_BROWSER: "true" },});client.stderr.resume();- const endpoint = await readEndpoint(client);+ const endpoint = await readClientEndpoint(client);clientPort = endpoint.port;const controlPage = await createPage(cdp,@@ -897,9 +881,11 @@ async function main(): Promise<void> {controlPage,"((__name) => (" + browserMediaGate.toString() + ")(" + JSON.stringify({endpoint,+ protocol: NATIVE_CLIENT_PROTOCOL,+ subprotocol: NATIVE_CLIENT_SUBPROTOCOL,sourceTitle: SOURCE_TITLE,sourceKind,- stunUrl: GATE_STUN_URL,+ stunUrls: GATE_STUN_URLS,}) + "))((target) => target)",Date.now() + 70_000,);diff --git a/scripts/client-native-host-gate.ts b/scripts/client-native-host-gate.tsindex db906df4..01f25091 100644--- a/scripts/client-native-host-gate.ts+++ b/scripts/client-native-host-gate.ts@@ -16,6 +16,7 @@ import {cleanupRun,createPage,evaluate,+ launchChrome,reservePort,type PageHandle,waitForVersion,@@ -411,16 +412,14 @@ export async function startSourceBrowser(child: ChildProcessWithoutNullStreams;cdp: CdpConnection;}> {- const child = spawn(chromePath, [- "--remote-debugging-port=" + debugPort,- "--user-data-dir=" + profile,+ const child = launchChrome(chromePath, debugPort, profile, ["--no-first-run", "--no-default-browser-check","--disable-extensions", "--disable-logging","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--app=http://127.0.0.1:" + sourcePort + "/",- ], { stdio: "pipe", windowsHide: true });+ ]);child.stdout.resume();child.stderr.resume();const version = await waitForVersion(debugPort, child);@@ -547,6 +546,10 @@ async function main(): Promise<void> {throw new Error("Cross-NAT and one-link gate modes are mutually exclusive");}const mode: GateMode = linkMedia ? "one-link" : crossNat ? "cross-nat" : "local";+ const gateStunUrls = process.env.SCREENER_CLIENT_GATE_STUN_URLS?.trim();+ if (mode === "cross-nat" && !gateStunUrls) {+ throw new Error("SCREENER_CLIENT_GATE_STUN_URLS is required for the cross-NAT gate");+ }const crashGate =process.env.SCREENER_CLIENT_NATIVE_HOST_CRASH_GATE === "true";if (crashGate && mode !== "local") {@@ -564,7 +567,6 @@ async function main(): Promise<void> {const chromePath = process.env.CHROME_PATH?.trim();if (!chromePath) throw new Error("CHROME_PATH is required");const go = process.env.SCREENER_GO?.trim() || "go";- const node = process.env.SCREENER_NODE?.trim() || process.execPath;const tunnel = process.env.SCREENER_CLOUDFLARED?.trim() || join(BUILD_ROOT,"cloudflared.exe",@@ -634,26 +636,26 @@ async function main(): Promise<void> {try {stage = "application-build";run(process.env.ComSpec || "cmd.exe", [- "/d", "/s", "/c", "npm run build",+ "/d", "/s", "/c", "npm run build:client",]);stage = "source-server";source = await sourceServer(sourcePort);stage = "capture-build";run(powershell(), ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File",- join(ROOT, "native", "client", "platform", "windows", "capture", "build.ps1"),+ join(ROOT, "native", "capture", "windows", "build.ps1"),"-OutputDirectory", captureBuild,]);stage = "client-build";run(go, ["build", "-trimpath", "-o", clientBinary, "./cmd/screener-client",- ], join(ROOT, "native", "client"));+ ], ROOT);if (remote) {stage = "remote-peer-build";run(go,["build", "-trimpath", "-o", remoteBinary, "./cmd/screener-peer-gate"],- join(ROOT, "native", "client"),+ ROOT,{ ...process.env, GOOS: "linux", GOARCH: "amd64", CGO_ENABLED: "0" },);}@@ -672,8 +674,6 @@ async function main(): Promise<void> {? ["--tunnel-process", tunnel]: []),"--capture-process", captureBinary,- "--node", node,- "--app", ROOT,"--config", clientConfig,"--port", String(appPort),], {@@ -681,15 +681,12 @@ async function main(): Promise<void> {windowsHide: true,env: {...process.env,- NODE_DEBUG: "screener-route",- PEER_ASSISTED_MEDIA: "true",+ SCREENER_DEBUG: "route",SCREENER_CLIENT_GATE_NO_BROWSER: "true",- ...(mode === "cross-nat"- ? {- STUN_URLS:- process.env.SCREENER_CLIENT_GATE_STUN_URLS?.trim() ||- "stun:share.bonfire.icu:3478",- }+ // STUN_URLS reaches only the Client's own Pion edge: the in-process+ // room server never reads it, so the cross-NAT arm stays isolated.+ ...(mode === "cross-nat" && gateStunUrls+ ? { STUN_URLS: gateStunUrls }: {}),},});@@ -729,17 +726,14 @@ async function main(): Promise<void> {15_000,);stage = "host-browser";- chrome = spawn(chromePath, [- "--remote-debugging-port=" + debugPort,- "--user-data-dir=" + profile,+ chrome = launchChrome(chromePath, debugPort, profile, ["--no-first-run", "--no-default-browser-check","--disable-extensions", "--disable-logging","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--window-size=1280,900",- "about:blank",- ], { stdio: "pipe", windowsHide: true });+ ]);chrome.stdout.resume();chrome.stderr.resume();stage = "host-cdp";diff --git a/scripts/client-native-sfu-gate.ts b/scripts/client-native-sfu-gate.tsindex 716d32ce..6ad1d3ec 100644--- a/scripts/client-native-sfu-gate.ts+++ b/scripts/client-native-sfu-gate.ts@@ -17,6 +17,7 @@ import {cleanupRun,createPage,evaluate,+ launchChrome,reservePort,type PageHandle,waitForVersion,@@ -30,8 +31,7 @@ import {waitForCaptureWindow,} from "./client-native-host-gate";import {- decodeClientEndpoint,- type ClientEndpoint as Endpoint,+ readClientEndpoint,} from "./client-gate-endpoint";const ROOT = resolve(import.meta.dirname, "..");@@ -73,39 +73,6 @@ async function waitForHTTP(url: string, timeoutMs: number): Promise<void> {throw new Error(`service did not become ready: ${url}`);}-async function readEndpoint(- process: ChildProcessWithoutNullStreams,-): Promise<Endpoint> {- return await new Promise<Endpoint>((resolveEndpoint, rejectEndpoint) => {- const timer = setTimeout(- () => rejectEndpoint(new Error("native Client did not become ready")),- 10_000,- );- let buffered = "";- const onData = (chunk: Buffer) => {- buffered += chunk.toString();- for (;;) {- const newline = buffered.indexOf("\n");- if (newline < 0) return;- const line = buffered.slice(0, newline).trim();- buffered = buffered.slice(newline + 1);- try {- const value = decodeClientEndpoint(line);- clearTimeout(timer);- process.stdout.off("data", onData);- resolveEndpoint(value);- return;- } catch {- // Ignore non-JSON informational output.- }- }- };- process.stdout.on("data", onData);- process.once("error", rejectEndpoint);- process.once("exit", () => rejectEndpoint(new Error("native Client exited")));- });-}-async function issueToken(apiKey: string,apiSecret: string,@@ -190,14 +157,14 @@ async function main(): Promise<void> {let clientPort = 0;try {result.stage = "build";- run(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "npm run build"]);+ run(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "npm run build:client"]);run(powershell(), ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File",- join(ROOT, "native", "client", "platform", "windows", "capture", "build.ps1"),+ join(ROOT, "native", "capture", "windows", "build.ps1"),"-OutputDirectory", BUILD_ROOT,]);run(go, ["build", "-trimpath", "-o", clientBinary, "./cmd/screener-client"],- join(ROOT, "native", "client"));+ ROOT);result.stage = "livekit";livekit = spawn(livekitPath, [@@ -260,12 +227,12 @@ async function main(): Promise<void> {env: { ...process.env, SCREENER_CLIENT_GATE_NO_BROWSER: "true" },});client.stderr.resume();- clientPort = (await readEndpoint(client)).port;+ clientPort = (await readClientEndpoint(client, {+ ignoreNonEndpointLines: true,+ })).port;result.stage = "browser";- chrome = spawn(chromePath, [- `--remote-debugging-port=${debugPort}`,- `--user-data-dir=${profile}`,+ chrome = launchChrome(chromePath, debugPort, profile, ["--no-first-run","--no-default-browser-check","--disable-extensions",@@ -274,8 +241,7 @@ async function main(): Promise<void> {"--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-features=WebRtcHideLocalIpsWithMdns",- "about:blank",- ], { stdio: "pipe", windowsHide: true });+ ]);chrome.stdout.resume();chrome.stderr.resume();const version = await waitForVersion(debugPort, chrome);diff --git a/scripts/client-package-targets.mjs b/scripts/client-package-targets.mjsindex 47b1acc9..24044a8c 100644--- a/scripts/client-package-targets.mjs+++ b/scripts/client-package-targets.mjs@@ -8,7 +8,6 @@ export const CLIENT_PACKAGE_TARGETS = [goos: "windows",goarch: "amd64",clientName: "screener-client.exe",- nodeName: "node.exe",tunnelName: "cloudflared.exe",captureName: "screener-client-capture.exe",tunnelAsset: "cloudflared-windows-amd64.exe",@@ -22,7 +21,6 @@ export const CLIENT_PACKAGE_TARGETS = [goos: "linux",goarch: "amd64",clientName: "screener-client",- nodeName: "node",tunnelName: "cloudflared",captureName: "screener-client-capture",tunnelAsset: "cloudflared-linux-amd64",@@ -36,7 +34,6 @@ export const CLIENT_PACKAGE_TARGETS = [goos: "darwin",goarch: "arm64",clientName: "screener-client",- nodeName: "node",tunnelName: "cloudflared",captureName: "screener-client-capture",tunnelAsset: "cloudflared-darwin-arm64.tgz",diff --git a/scripts/package-app-release.mjs b/scripts/package-app-release.mjsindex 9322f338..2e38e108 100644--- a/scripts/package-app-release.mjs+++ b/scripts/package-app-release.mjs@@ -3,6 +3,7 @@import { spawnSync } from "node:child_process";import { createHash } from "node:crypto";import {+ chmodSync,copyFileSync,existsSync,lstatSync,@@ -19,13 +20,31 @@ import { tmpdir } from "node:os";import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";+import { writeServerLicenseNotices } from "./package-licenses.mjs";+import { tarExecutable } from "./archive-tool.mjs";++// The Hosted deployment target. deploy/release-app.sh runs the archived binary+// as the service user, so the release is always built for linux/amd64, and+// CGO_ENABLED=0 keeps it self-contained.+const SERVER_TARGET = { goos: "linux", goarch: "amd64" };+const SERVER_NAME = "screener-server";++// Everything the archive may contain. deploy/release-app.sh enforces the same+// four names in its entry allowlist and manifest pattern; both change together.+const RUNTIME_PATHS = ["REVISION", "LICENSE", "THIRD-PARTY-NOTICES.txt", SERVER_NAME];++// The Vite output the server embeds. Its index.html names the main asset the+// deployment postflight proves over HTTP.+const CLIENT_DIST = "internal/server/webassets/dist";+function fail(message) {throw new Error(message);}-function run(command, args, cwd) {+function run(command, args, cwd, environment = process.env) {const result = spawnSync(command, args, {cwd,+ env: environment,encoding: "utf8",stdio: ["ignore", "pipe", "pipe"],});@@ -36,16 +55,16 @@ function run(command, args, cwd) {return result.stdout.trim();}-function buildRuntime(cwd) {+function buildClient(cwd) {if (process.platform === "win32") {run(process.env.ComSpec || "cmd.exe",- ["/d", "/s", "/c", "npm run build"],+ ["/d", "/s", "/c", "npm run build:client"],cwd,);return;}- run("npm", ["run", "build"], cwd);+ run("npm", ["run", "build:client"], cwd);}function assertCleanRevision(repositoryRoot, expectedRevision) {@@ -77,17 +96,6 @@ function normalizedRelative(root, path) {return value;}-function runtimePathAllowed(path) {- return (- path === "REVISION" ||- path === "LICENSE" ||- path === "package.json" ||- path === "package-lock.json" ||- path.startsWith("dist/client/") ||- path.startsWith("dist/server/")- );-}-function regularFiles(root) {const files = [];const pending = [root];@@ -111,18 +119,10 @@ function regularFiles(root) {);}-function copyRuntimeFile(sourceRoot, targetRoot, source) {- const path = normalizedRelative(sourceRoot, source);- if (!runtimePathAllowed(path)) fail(`Unexpected runtime file: ${path}`);- const target = join(targetRoot, ...path.split("/"));- mkdirSync(dirname(target), { recursive: true });- copyFileSync(source, target);-}-function recordsFor(root) {return regularFiles(root).map((absolute) => {const path = normalizedRelative(root, absolute);- if (!runtimePathAllowed(path)) fail(`Unexpected packaged file: ${path}`);+ if (!RUNTIME_PATHS.includes(path)) fail(`Unexpected packaged file: ${path}`);return { path, size: statSync(absolute).size, sha256: sha256(absolute) };});}@@ -155,20 +155,23 @@ function validateArchiveEntries(entries) {) {fail(`Invalid archive entry: ${rawEntry}`);}- if (- entry !== "REVISION" &&- entry !== "LICENSE" &&- entry !== "package.json" &&- entry !== "package-lock.json" &&- entry !== "dist" &&- !entry.startsWith("dist/client") &&- !entry.startsWith("dist/server")- ) {- fail(`Unexpected archive entry: ${rawEntry}`);- }+ if (!RUNTIME_PATHS.includes(entry)) fail(`Unexpected archive entry: ${rawEntry}`);}}+// mainAsset is the hashed entry script Vite named in the embedded index.html.+// The deployment postflight proves it over HTTP, so it is read from the same+// build the binary embeds rather than from the archive.+function mainAssetOf(distributionRoot) {+ const html = readFileSync(join(distributionRoot, "index.html"), "utf8");+ const match = html.match(/<script[^>]+src="\/(assets\/index-[A-Za-z0-9_-]+\.js)"/);+ if (!match) fail("Built client HTML has no unique main asset");+ if (!existsSync(join(distributionRoot, ...match[1].split("/")))) {+ fail("Built client main asset is missing");+ }+ return match[1];+}+if (process.argv.length !== 3) {fail("Usage: node scripts/package-app-release.mjs <new-output-directory>");}@@ -176,21 +179,17 @@ if (process.argv.length !== 3) {const repositoryRoot = realpathSync(resolve(dirname(fileURLToPath(import.meta.url)), ".."));const outputRoot = resolve(process.cwd(), process.argv[2]);const relativeOutput = relative(repositoryRoot, outputRoot);-if (relativeOutput === "" || (!relativeOutput.startsWith("..") && !isAbsolute(relativeOutput))) {+if (relativeOutput === "" || (relativeOutput.split(/[\\/]/)[0] !== ".." && !isAbsolute(relativeOutput))) {fail("Output directory must be outside the repository");}if (existsSync(outputRoot)) fail("Output directory must not already exist");const revision = assertCleanRevision(repositoryRoot);-for (const required of ["LICENSE", "package.json", "package-lock.json"]) {- if (!existsSync(join(repositoryRoot, required))) fail(`Missing release input: ${required}`);-}-buildRuntime(repositoryRoot);+if (!existsSync(join(repositoryRoot, "LICENSE"))) fail("Missing release input: LICENSE");+buildClient(repositoryRoot);assertCleanRevision(repositoryRoot, revision);-for (const required of ["dist/client", "dist/server"]) {- if (!existsSync(join(repositoryRoot, required))) fail(`Missing built runtime path: ${required}`);-}+const mainAsset = mainAssetOf(join(repositoryRoot, CLIENT_DIST));const releaseId = revision.slice(0, 7);const temporaryRoot = mkdtempSync(join(tmpdir(), `screener-app-${releaseId}-`));@@ -199,14 +198,30 @@ const verifyRoot = join(temporaryRoot, "verify");try {mkdirSync(runtimeRoot, { recursive: true });- for (const source of [- join(repositoryRoot, "LICENSE"),- join(repositoryRoot, "package.json"),- join(repositoryRoot, "package-lock.json"),- ...regularFiles(join(repositoryRoot, "dist")),- ]) {- copyRuntimeFile(repositoryRoot, runtimeRoot, source);- }+ copyFileSync(join(repositoryRoot, "LICENSE"), join(runtimeRoot, "LICENSE"));+ const goCommand = process.env.SCREENER_GO?.trim() || "go";+ const serverPath = join(runtimeRoot, SERVER_NAME);+ run(goCommand, [+ "build",+ "-trimpath",+ "-ldflags",+ `-s -w -X main.BuildRevision=${revision}`,+ "-o",+ serverPath,+ "./cmd/screener-server",+ ], repositoryRoot, {+ ...process.env,+ GOOS: SERVER_TARGET.goos,+ GOARCH: SERVER_TARGET.goarch,+ CGO_ENABLED: "0",+ });+ chmodSync(serverPath, 0o755);+ writeServerLicenseNotices(+ repositoryRoot,+ join(runtimeRoot, "THIRD-PARTY-NOTICES.txt"),+ goCommand,+ SERVER_TARGET,+ );assertCleanRevision(repositoryRoot, revision);writeFileSync(join(runtimeRoot, "REVISION"), `${revision}\n`, "ascii");@@ -224,20 +239,13 @@ try {"ascii",);- run("tar", ["-czf", artifactPath, "-C", runtimeRoot, "."], repositoryRoot);- validateArchiveEntries(run("tar", ["-tzf", artifactPath], repositoryRoot));+ const tar = tarExecutable();+ run(tar, ["-czf", artifactPath, "-C", runtimeRoot, "."], repositoryRoot);+ validateArchiveEntries(run(tar, ["-tzf", artifactPath], repositoryRoot));mkdirSync(verifyRoot);- run("tar", ["-xzf", artifactPath, "-C", verifyRoot], repositoryRoot);+ run(tar, ["-xzf", artifactPath, "-C", verifyRoot], repositoryRoot);compareRecords(records, recordsFor(verifyRoot));- const html = readFileSync(join(runtimeRoot, "dist/client/index.html"), "utf8");- const mainAssetMatch = html.match(/<script[^>]+src="\/(assets\/index-[A-Za-z0-9_-]+\.js)"/);- if (!mainAssetMatch) fail("Built client HTML has no unique main asset");- const mainAsset = mainAssetMatch[1];- if (!existsSync(join(runtimeRoot, "dist/client", ...mainAsset.split("/")))) {- fail("Built client main asset is missing");- }-const descriptor = {schema: 1,revision,diff --git a/scripts/package-client-candidate.mjs b/scripts/package-client-candidate.mjsindex 423b620d..1b8e86f6 100644--- a/scripts/package-client-candidate.mjs+++ b/scripts/package-client-candidate.mjs@@ -21,6 +21,7 @@ import { pipeline } from "node:stream/promises";import { fileURLToPath } from "node:url";import { clientPackageTarget, CLOUDFLARED_VERSION } from "./client-package-targets.mjs";+import { tarExecutable } from "./archive-tool.mjs";function fail(message) {throw new Error(message);@@ -45,7 +46,7 @@ function sha256(path) {function assertOutsideRepository(repositoryRoot, outputRoot) {const path = relative(repositoryRoot, outputRoot);- if (path === "" || (!path.startsWith("..") && !isAbsolute(path))) {+ if (path === "" || (path.split(/[\\/]/)[0] !== ".." && !isAbsolute(path))) {fail("Client candidate output must be outside the repository");}if (existsSync(outputRoot)) {@@ -145,6 +146,7 @@ async function verifyLocalPackage(root, target, temporaryRoot) {const client = join(root, target.clientName);const port = await reservePort();const healthURL = `http://127.0.0.1:${port}/healthz`;+ const noticeURL = `http://127.0.0.1:${port}/third-party-licenses.txt`;const child = spawn(client, ["--local","--config", join(temporaryRoot, "smoke-client.json"),@@ -195,6 +197,14 @@ async function verifyLocalPackage(root, target, temporaryRoot) {if (!healthReady || !clientReady) {fail("Packaged Client Local health did not become ready");}+ // The Web notices ship inside the binary; the embedded assets serve them.+ const notices = await fetch(noticeURL, {+ headers: { Connection: "close" },+ signal: AbortSignal.timeout(2_000),+ });+ if (!notices.ok || (await notices.text()).length === 0) {+ fail("Packaged Client did not serve its Web third-party notices");+ }child.stdin.write("\n");const exitCode = await waitForExit(child, 10_000);if (exitCode !== 0) {@@ -225,29 +235,18 @@ async function verifyLocalPackage(root, target, temporaryRoot) {}}-async function verifyPackage(- root,- target,- revision,- expectedNodeVersion,- temporaryRoot,-) {+async function verifyPackage(root, target, revision, temporaryRoot) {const packagedRevision = readFileSync(join(root, "REVISION"), "ascii").trim();if (packagedRevision !== revision) fail("Client package revision mismatch");- for (const file of ["LICENSE", "THIRD-PARTY-NOTICES.txt", "app/LICENSE",- "app/dist/client/third-party-licenses.txt", "runtime/node/LICENSE",+ for (const file of ["LICENSE", "THIRD-PARTY-NOTICES.txt","runtime/tunnel/THIRD-PARTY-NOTICES.txt"]) {if (!existsSync(join(root, file)) || readFileSync(join(root, file)).length === 0) {fail(`Client package license text is missing: ${file}`);}}- const node = join(root, "runtime", "node", target.nodeName);const client = join(root, target.clientName);const tunnel = join(root, "runtime", "tunnel", target.tunnelName);- if (run(node, ["--version"], root) !== expectedNodeVersion) {- fail(`Packaged Node runtime must be ${expectedNodeVersion}`);- }run(client, ["--help"], root);run(tunnel, ["--version"], root);verifyPlatformAssets(root, target);@@ -323,10 +322,6 @@ if (process.platform !== target.nodePlatform || process.arch !== target.nodeArchassertOutsideRepository(repositoryRoot, outputRoot);const revision = run("git", ["rev-parse", "HEAD"], repositoryRoot).toLowerCase();-const expectedNodeVersion = `v${readFileSync(- join(repositoryRoot, ".node-version"),- "ascii",-).trim()}`;const temporaryRoot = join(tmpdir(), "screener-client-candidate", target.id);rmSync(temporaryRoot, { recursive: true, force: true });mkdirSync(temporaryRoot, { recursive: true, mode: 0o700 });@@ -342,7 +337,7 @@ try {let tunnel = tunnelDownload;if (target.tunnelArchive) {- run("tar", ["-xzf", tunnelDownload, "-C", temporaryRoot], repositoryRoot);+ run(tarExecutable(), ["-xzf", tunnelDownload, "-C", temporaryRoot], repositoryRoot);tunnel = join(temporaryRoot, target.tunnelName);}if (!existsSync(tunnel)) fail("Public-link runtime is missing");@@ -362,7 +357,6 @@ try {const assembleArguments = [join(repositoryRoot, "scripts", "assemble-client.mjs"),applicationDescriptor(applicationRoot),- process.execPath,packageRoot,"--target",target.id,@@ -371,19 +365,13 @@ try {];if (capture) assembleArguments.push("--capture", capture);run(process.execPath, assembleArguments, repositoryRoot);- await verifyPackage(- packageRoot,- target,- revision,- expectedNodeVersion,- temporaryRoot,- );+ await verifyPackage(packageRoot, target, revision, temporaryRoot);mkdirSync(outputRoot, { recursive: false, mode: 0o700 });const shortRevision = revision.slice(0, 7);const archiveName = `Screener-Client-${target.id}-${shortRevision}.tar.gz`;const archive = join(outputRoot, archiveName);- run("tar", ["-czf", archive, "-C", packageRoot, "."], repositoryRoot);+ run(tarExecutable(), ["-czf", archive, "-C", packageRoot, "."], repositoryRoot);const digest = sha256(archive);writeFileSync(join(outputRoot, `${archiveName}.sha256`), `${digest} ${archiveName}\n`, "ascii");process.stdout.write(`${JSON.stringify({diff --git a/scripts/package-licenses.mjs b/scripts/package-licenses.mjsindex 455e9fb8..b47ed8c8 100644--- a/scripts/package-licenses.mjs+++ b/scripts/package-licenses.mjs@@ -10,6 +10,14 @@ const pinned = JSON.parse(readFileSync(join(root, "licenses", "upstream.json"),const licenseName = /^(licen[cs]e|copying|notice|copyright|authors)([._-]|$)/i;const section = (label, body) => `\n===== ${label} =====\n\n${body.trim()}\n`;+// The packages the Vite bundle ships to the Browser. Nothing installs+// node_modules at runtime any more, so this list is the notice contract rather+// than package.json's dependencies field.+const WEB_BUNDLE_PACKAGES = ["react", "react-dom", "livekit-client", "sdp-transform", "zod"];++// Both binaries embed the Web bundle, which serves its own notice file.+const WEB_NOTICE_LINE = "Web dependencies: served at /third-party-licenses.txt\n";+function pinnedNotice(key) {const entry = pinned[key];if (!entry) throw new Error(`Missing pinned license text for ${key}`);@@ -28,10 +36,8 @@ function noticesIn(directory) {export function writeWebLicenseNotices(repositoryRoot, outputFile) {const packagePath = join(repositoryRoot, "package.json");- const pkg = JSON.parse(readFileSync(packagePath, "utf8"));const lock = JSON.parse(readFileSync(join(repositoryRoot, "package-lock.json"), "utf8"));- const queue = [...Object.keys(pkg.dependencies), "react", "react-dom", "livekit-client", "sdp-transform"]- .map((name) => [name, packagePath]);+ const queue = WEB_BUNDLE_PACKAGES.map((name) => [name, packagePath]);const visited = new Set();const entries = new Map();for (const [name, parent] of queue) {@@ -61,21 +67,16 @@ export function writeWebLicenseNotices(repositoryRoot, outputFile) {[...entries].sort(([a], [b]) => a.localeCompare(b)).map(([, body]) => body).join(""));}-export function writeClientLicenseNotices(repositoryRoot, packageRoot, goCommand, target, tunnelVersion) {- copyFileSync(join(repositoryRoot, "LICENSE"), join(packageRoot, "LICENSE"));- const nodeVersion = readFileSync(join(repositoryRoot, ".node-version"), "ascii").trim();- writeFileSync(join(packageRoot, "runtime", "node", "LICENSE"), pinnedNotice(`node@${nodeVersion}`));- if (tunnelVersion) {- writeFileSync(join(packageRoot, "runtime", "tunnel", "THIRD-PARTY-NOTICES.txt"),- pinnedNotice(`cloudflared@${tunnelVersion}`));- }- const cwd = join(repositoryRoot, "native", "client");- const options = { cwd, encoding: "utf8", windowsHide: true,+// goNotices enumerates the Go toolchain notice and every license file that+// belongs to a module actually compiled into `command` for `target`. A module+// without a recognised license filename fails closed.+function goNotices(repositoryRoot, goCommand, target, command) {+ const options = { cwd: repositoryRoot, encoding: "utf8", windowsHide: true,env: { ...process.env, GOOS: target.goos, GOARCH: target.goarch, CGO_ENABLED: "0" } };const runGo = (args) => execFileSync(goCommand, args, options).trim();const goroot = runGo(["env", "GOROOT"]);const template = '{{if .Module}}{{if not .Module.Main}}[{{printf "%q" .Module.Path}},{{printf "%q" .Module.Version}},{{printf "%q" .Module.Dir}},{{printf "%q" .Dir}}]{{end}}{{end}}';- const packages = runGo(["list", "-deps", "-f", template, "./cmd/screener-client"])+ const packages = runGo(["list", "-deps", "-f", template, command]).split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));const entries = new Map();for (const [name, version, directory, packageDirectory] of packages) {@@ -92,24 +93,57 @@ export function writeClientLicenseNotices(repositoryRoot, packageRoot, goCommand}entries.set(key, files);}+ const toolchain = section(runGo(["version"]), readFileSync(join(goroot, "LICENSE"), "utf8"));+ return { toolchain, modules: entries };+}++function moduleSections(modules) {+ let text = "";+ for (const [name, files] of [...modules].sort(([a], [b]) => a.localeCompare(b))) {+ for (const [file, body] of [...files].sort(([a], [b]) => a.localeCompare(b))) {+ text += section(`${name}/${file}`, body);+ }+ }+ return text;+}++// writeServerLicenseNotices produces the Hosted application release notice file,+// which ships beside the single screener-server binary.+export function writeServerLicenseNotices(repositoryRoot, outputFile, goCommand, target) {+ const notices = goNotices(repositoryRoot, goCommand, target, "./cmd/screener-server");+ writeFileSync(outputFile, "Screener server third-party software notices\n" ++ WEB_NOTICE_LINE + notices.toolchain + moduleSections(notices.modules));+}++export function writeClientLicenseNotices(repositoryRoot, packageRoot, goCommand, target, tunnelVersion) {+ copyFileSync(join(repositoryRoot, "LICENSE"), join(packageRoot, "LICENSE"));+ if (tunnelVersion) {+ writeFileSync(join(packageRoot, "runtime", "tunnel", "THIRD-PARTY-NOTICES.txt"),+ pinnedNotice(`cloudflared@${tunnelVersion}`));+ }+ const notices = goNotices(repositoryRoot, goCommand, target, "./cmd/screener-client");let text = "Native Client third-party software notices\n" +- "Web and Server dependencies: app/dist/client/third-party-licenses.txt\n" +- "Node runtime: runtime/node/LICENSE\n" ++ WEB_NOTICE_LINE +(tunnelVersion ? "Cloudflared: runtime/tunnel/THIRD-PARTY-NOTICES.txt\n" : "") +- section(runGo(["version"]), readFileSync(join(goroot, "LICENSE"), "utf8"));+ notices.toolchain;+ const linuxCapture = target.goos === "linux" && target.captureName &&+ existsSync(join(packageRoot, "runtime", "native", target.captureName));+ if (linuxCapture) {+ text += section("Linux system dependencies (not bundled)",+ readFileSync(join(repositoryRoot, "licenses", "linux-system-dependencies.txt"), "utf8"));+ text += section("LGPL-3.0-only (libportal)",+ readFileSync(join(repositoryRoot, "licenses", "LGPL-3.0.txt"), "utf8"));+ text += section("GPL-3.0 (libportal terms)",+ readFileSync(join(repositoryRoot, "licenses", "GPL-3.0.txt"), "utf8"));+ }if (target.goos === "windows" &&existsSync(join(packageRoot, "runtime", "native", target.captureName))) {- const dependencies = JSON.parse(readFileSync(join(repositoryRoot, "native", "client",- "platform", "windows", "capture", "libvpx-dependencies.json"), "utf8"));+ const dependencies = JSON.parse(readFileSync(join(repositoryRoot, "native", "capture",+ "windows", "libvpx-dependencies.json"), "utf8"));const name = `libvpx@${dependencies.libvpx.version}`;text += section(name, pinnedNotice(name));}- for (const [name, files] of [...entries].sort(([a], [b]) => a.localeCompare(b))) {- for (const [file, body] of [...files].sort(([a], [b]) => a.localeCompare(b))) {- text += section(`${name}/${file}`, body);- }- }- writeFileSync(join(packageRoot, "THIRD-PARTY-NOTICES.txt"), text);+ writeFileSync(join(packageRoot, "THIRD-PARTY-NOTICES.txt"), text + moduleSections(notices.modules));}if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {diff --git a/scripts/peer-assisted-benchmark.ts b/scripts/peer-assisted-benchmark.tsindex 9efe6002..f89c712a 100644--- a/scripts/peer-assisted-benchmark.ts+++ b/scripts/peer-assisted-benchmark.ts@@ -1,4 +1,5 @@-import { spawn, type ChildProcess } from "node:child_process";+import { spawn, spawnSync, type ChildProcess } from "node:child_process";+import { mkdirSync } from "node:fs";import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { createServer } from "node:net";import { tmpdir } from "node:os";@@ -15,15 +16,6 @@ import {DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY,MAX_ENDPOINT_MEDIA_COPY_CAPACITY,} from "../src/shared/media-copy-accounting";-import {- createScreenerServer,- type ScreenerServer,-} from "../src/server/app";-import { loadConfig } from "../src/server/config";-import {- ROOM_CAPACITY,- RoomStore,-} from "../src/server/room-store";import {QUALITY_PROFILES,QUALITY_RESOLUTIONS,@@ -34,8 +26,8 @@ import {const PROFILE_SETTINGS = QUALITY_PROFILES;type ProfileId = QualityProfileId;type PageRole = "host" | "viewer";-export type BenchmarkCodecMode = "vp8" | "auto" | "h264";-export type BenchmarkCanaryMode = "none" | "viewer-mbb";+type BenchmarkCodecMode = "vp8" | "auto" | "h264";+type BenchmarkCanaryMode = "none" | "viewer-mbb";const ROUTE_TIMING_KEYS = ["queueWaitMs",@@ -52,12 +44,12 @@ interface RouteTimingDistribution {p95Ms: number | null;maxMs: number | null;}-export type BenchmarkRouteTimingSamples = {+type BenchmarkRouteTimingSamples = {[Key in RouteTimingKey]: Array<RouteDiagnosticSnapshot["children"][number][Key]>;};-export type BenchmarkRouteTimingSummary = Record<+type BenchmarkRouteTimingSummary = Record<RouteTimingKey,RouteTimingDistribution>;@@ -70,7 +62,7 @@ interface ViewerMbbCanaryResult {failureCode?: "topology-unavailable" | "probe-unavailable";}-export interface BenchmarkConfig {+interface BenchmarkConfig {chromePath: string;viewerCounts: number[];expectedEndpointCap: number;@@ -116,7 +108,7 @@ interface ConnectionObservation {error?: string;}-export interface PagePerformanceSample {+interface PagePerformanceSample {timestampSeconds: number;taskDurationSeconds: number;scriptDurationSeconds: number;@@ -190,7 +182,7 @@ interface RunCheck {expected: string;}-export interface RecoveryResult {+interface RecoveryResult {triggered: boolean;relayPeerId?: string;affectedPeerIds?: string[];@@ -203,12 +195,12 @@ export interface RecoveryResult {error?: string;}-export interface RecoveryHostPeaks {+interface RecoveryHostPeaks {maxHostActiveMediaEdges?: number;maxHostAssignedChildren?: number;}-export interface RecoveryViewerBaseline {+interface RecoveryViewerBaseline {label: string;routeRevision: number;upstreamKind: "peer" | "sfu";@@ -305,7 +297,7 @@ class BoundedLog {}}-export class CdpConnection {+class CdpConnection {private nextId = 1;private readonly pending = new Map<number,@@ -432,7 +424,7 @@ export class CdpConnection {}}-export function summarizeBenchmarkRouteTiming(+function summarizeBenchmarkRouteTiming(samples: BenchmarkRouteTimingSamples,): BenchmarkRouteTimingSummary {return Object.fromEntries(@@ -467,7 +459,7 @@ function nearestRank(return sortedValues[Math.ceil(percentile * sortedValues.length) - 1] ?? null;}-export function buildRouteTimingCheck(+function buildRouteTimingCheck(status: BenchmarkRun["routeTimingStatus"],summary: BenchmarkRouteTimingSummary | null,expectedChildCount = MAX_VIEWERS,@@ -492,7 +484,7 @@ export function buildRouteTimingCheck(};}-export async function joinViewerBurst<T>(+async function joinViewerBurst<T>(viewerCount: number,createViewer: (viewerIndex: number) => Promise<T>,waitForMedia: (viewer: T, viewerIndex: number) => Promise<unknown>,@@ -523,7 +515,7 @@ export async function joinViewerBurst<T>(return viewers;}-export function parseViewerCounts(value: string | undefined): number[] {+function parseViewerCounts(value: string | undefined): number[] {if (!value?.trim()) {return [...DEFAULT_VIEWER_COUNTS];}@@ -575,13 +567,13 @@ function parseBoolean(value: string | undefined, fallback: boolean, name: stringthrow new Error(`${name} must be true, false, 1, or 0`);}-export function parseBenchmarkCanaryMode(value: string | undefined): BenchmarkCanaryMode {+function parseBenchmarkCanaryMode(value: string | undefined): BenchmarkCanaryMode {const mode = value?.trim() || "none";if (mode === "none" || mode === "viewer-mbb") return mode;throw new Error("BENCHMARK_CANARY must be none or viewer-mbb");}-export function parseBenchmarkCodecMode(+function parseBenchmarkCodecMode(value: string | undefined,): BenchmarkCodecMode {const mode = value?.trim().toLowerCase() || "auto";@@ -589,7 +581,7 @@ export function parseBenchmarkCodecMode(throw new Error("BENCHMARK_CODEC_MODE must be vp8, auto, or h264");}-export function parseExpectedEndpointCap(value: string | undefined): number {+function parseExpectedEndpointCap(value: string | undefined): number {const parsed = value?.trim()? Number(value): DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY;@@ -605,7 +597,7 @@ export function parseExpectedEndpointCap(value: string | undefined): number {return parsed;}-export function parseBenchmarkConfig(+function parseBenchmarkConfig(environment: NodeJS.ProcessEnv = process.env,): BenchmarkConfig {const chromePath = environment.CHROME_PATH?.trim();@@ -709,7 +701,7 @@ export function parseBenchmarkConfig(};}-export function parseExternalServerTarget(+function parseExternalServerTarget(environment: NodeJS.ProcessEnv = process.env,): ExternalServerTarget | null {const value = environment.BENCHMARK_SERVER_URL?.trim();@@ -736,7 +728,7 @@ export function parseExternalServerTarget(};}-export function activeVideoEdgeCount(+function activeVideoEdgeCount(page: PageObservation,direction: "send" | "receive",): number {@@ -753,7 +745,7 @@ export function activeVideoEdgeCount(}).length;}-export function sanitizeFailurePageEvidence(+function sanitizeFailurePageEvidence(page: PageObservation,): FailurePageEvidence {const connectionStates = new Set([@@ -891,7 +883,7 @@ const PAGE_PERFORMANCE_METRICS = {JSHeapUsedSize: "jsHeapUsedBytes",} as const satisfies Record<string, keyof PagePerformanceSample>;-export function parsePagePerformanceMetrics(+function parsePagePerformanceMetrics(rawMetrics: unknown,): PagePerformanceSample | null {if (!Array.isArray(rawMetrics)) return null;@@ -927,7 +919,7 @@ export function parsePagePerformanceMetrics(};}-export function summarizeSamples(samples: TimedSample[], viewerCount: number) {+function summarizeSamples(samples: TimedSample[], viewerCount: number) {let maxHostActiveMediaEdges = 0;let maxHostAssignedChildren = 0;let maxRelayActiveMediaEdges = 0;@@ -1214,7 +1206,7 @@ function finiteMetric(metrics: Record<string, unknown>, key: string): number | nreturn typeof value === "number" && Number.isFinite(value) ? value : null;}-export function summarizeViewerExperienceByDepth(samples: TimedSample[]) {+function summarizeViewerExperienceByDepth(samples: TimedSample[]) {const cohorts = new Map<string, ViewerExperienceAccumulator>();let unresolvedRouteSamples = 0;const cohort = (route: ViewerExperienceRoute, depth: number | null) => {@@ -1516,7 +1508,7 @@ function finishPageRuntime(accumulator: PageRuntimeAccumulator) {};}-export function summarizePageRuntimeResources(samples: TimedSample[]) {+function summarizePageRuntimeResources(samples: TimedSample[]) {const accumulators: Record<PageRuntimeRole, PageRuntimeAccumulator> = {host: emptyPageRuntimeAccumulator(),viewer: emptyPageRuntimeAccumulator(),@@ -1593,7 +1585,7 @@ export function summarizePageRuntimeResources(samples: TimedSample[]) {};}-export function buildRunChecks(+function buildRunChecks(summary: NonNullable<BenchmarkRun["summary"]>,viewerCount: number,profileId: ProfileId,@@ -1656,7 +1648,7 @@ export function buildRunChecks(];}-export function buildRecoveryCheck(+function buildRecoveryCheck(recovery: RecoveryResult,expectedEndpointCap = DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY,): RunCheck {@@ -1676,7 +1668,7 @@ export function buildRecoveryCheck(};}-export function buildBenchmarkInitScript(options: {+function buildBenchmarkInitScript(options: {label: string;role: PageRole;viewerIndex: number | null;@@ -2258,10 +2250,47 @@ async function reservePort(): Promise<number> {return address.port;}-function startProcess(command: string, args: string[], environment?: NodeJS.ProcessEnv): ManagedProcess {+function buildStep(command: string, args: string[], failure: string): void {+ const result = spawnSync(command, args, {+ cwd: REPO_ROOT,+ encoding: "utf8",+ windowsHide: true,+ });+ if (result.error) throw result.error;+ if (result.status !== 0) {+ throw new Error((result.stderr || result.stdout).trim() || failure);+ }+}++// buildServer compiles the Screener server this run starts. The Web assets are+// embedded, so the Vite build precedes the Go build and the Browser reaches the+// same bundle the binary serves.+function buildServer(): string {+ const go = process.env.SCREENER_GO?.trim() || "go";+ const buildRoot = join(REPO_ROOT, "build", "peer-benchmark");+ mkdirSync(buildRoot, { recursive: true });+ const output = join(buildRoot,+ process.platform === "win32" ? "screener-server.exe" : "screener-server");+ if (process.platform === "win32") {+ buildStep(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "npm run build:client"],+ "Browser client build failed");+ } else {+ buildStep("npm", ["run", "build:client"], "Browser client build failed");+ }+ buildStep(go, ["build", "-trimpath", "-o", output, "./cmd/screener-server"],+ "Screener server build failed");+ return output;+}++function startProcess(+ command: string,+ args: string[],+ environment?: NodeJS.ProcessEnv,+ cwd: string = REPO_ROOT,+): ManagedProcess {const log = new BoundedLog();const child = spawn(command, args, {- cwd: REPO_ROOT,+ cwd,env: environment,stdio: ["ignore", "pipe", "pipe"],windowsHide: true,@@ -2271,6 +2300,9 @@ function startProcess(command: string, args: string[], environment?: NodeJS.Procreturn { child, log };}+// Readiness is the endpoint, never the spawned process: Chrome's Windows+// launcher exits as soon as the browser process takes over the profile. The+// deadline bounds the wait; the exit code and captured log explain a failure.async function waitForHttp(url: string,process: ManagedProcess,@@ -2279,9 +2311,6 @@ async function waitForHttp(): Promise<void> {const deadline = Date.now() + timeoutMs;while (Date.now() < deadline) {- if (process.child.exitCode !== null) {- throw new Error(`Process exited before ${url} was ready\n${process.log.tail()}`);- }try {const response = await fetch(url, { signal: AbortSignal.timeout(1_000) });if (response.ok) {@@ -2292,7 +2321,9 @@ async function waitForHttp(}await delay(100, signal);}- throw new Error(`Timed out waiting for ${url}\n${process.log.tail()}`);+ throw new Error(+ `Timed out waiting for ${url} (exit ${process.child.exitCode ?? "running"})\n${process.log.tail()}`,+ );}async function stopProcess(process: ManagedProcess | null): Promise<void> {@@ -2359,7 +2390,7 @@ async function evaluate<T>(return evaluation.result.value as T;}-export async function createPage(+async function createPage(cdp: CdpConnection,url: string,options: Parameters<typeof buildBenchmarkInitScript>[0],@@ -2479,7 +2510,7 @@ async function progressSample();}-export function buildBenchmarkFailureEvidence(+function buildBenchmarkFailureEvidence(pages: readonly PageObservation[],expectedPageCount: number,): BenchmarkFailureEvidence {@@ -2935,7 +2966,7 @@ function totalDecodedFrames(page: PageObservation): number {);}-export function everyViewerAdvanced(+function everyViewerAdvanced(before: PageObservation[],after: PageObservation[],): boolean {@@ -2991,7 +3022,7 @@ function recoveryViewerBaseline(};}-export function captureRecoveryViewerBaselines(+function captureRecoveryViewerBaselines(pages: PageObservation[],): RecoveryViewerBaseline[] | null {const viewers = pages.filter((page) => page.role === "viewer");@@ -3001,7 +3032,7 @@ export function captureRecoveryViewerBaselines(: null;}-export function everyViewerRecoveredMedia(+function everyViewerRecoveredMedia(baselines: RecoveryViewerBaseline[] | null,after: PageObservation[],): boolean {@@ -3030,7 +3061,7 @@ export function everyViewerRecoveredMedia();}-export function mergeRecoveryHostPeaks(+function mergeRecoveryHostPeaks(peaks: RecoveryHostPeaks,host: PageObservation,): RecoveryHostPeaks {@@ -3590,7 +3621,7 @@ async function authenticateExternalServer(}}-export async function main(): Promise<number> {+async function main(): Promise<number> {let config: BenchmarkConfig;let externalServer: ExternalServerTarget | null;try {@@ -3656,7 +3687,7 @@ export async function main(): Promise<number> {runs: [],};- let server: ScreenerServer | null = null;+ let server: ManagedProcess | null = null;let chrome: ManagedProcess | null = null;let cdp: CdpConnection | null = null;let profileDirectory: string | null = null;@@ -3673,30 +3704,32 @@ export async function main(): Promise<number> {const baseUrl = externalServer?.origin ?? `http://127.0.0.1:${appPort}`;profileDirectory = await mkdtemp(join(tmpdir(), "screener-peer-benchmark-"));if (appPort !== null) {- const serverConfig = loadConfig({- NODE_ENV: "development",+ // An explicit environment and a profile working directory: the measured+ // configuration is exactly these values, never the repository's .env or+ // the operator's shell (a stray LIVEKIT_* or SITE_ACCESS_PASSWORD would+ // silently change the topology this run reports).+ server = startProcess(buildServer(), [], {+ PATH: process.env.PATH,+ SystemRoot: process.env.SystemRoot,+ SCREENER_ENV: "development",PORT: String(appPort),LISTEN_HOST: "127.0.0.1",PUBLIC_BASE_URL: baseUrl,ALLOWED_ORIGINS: baseUrl,- PEER_ASSISTED_MEDIA: "true",ENDPOINT_MEDIA_COPY_CAPACITY: String(config.expectedEndpointCap),MAX_VIEWERS_PER_ROOM: String(Math.max(...config.viewerCounts,config.canaryMode === "viewer-mbb" ? 3 : 1,)),+ // The loopback gate measures peer topology, never a relayed candidate.STUN_URLS: "",- });- server = await createScreenerServer({- config: serverConfig,- frontend: { mode: "development" },- roomStore: new RoomStore({- leaseMs: serverConfig.roomLeaseMs,- maxRooms: ROOM_CAPACITY,- maxViewersPerRoom: serverConfig.maxViewersPerRoom,- }),- });- await server.listen(appPort, "127.0.0.1");+ }, profileDirectory);+ await waitForHttp(+ `${baseUrl}/healthz`,+ server,+ 20_000,+ abortController.signal,+ );}const chromeArgs = [@@ -3773,7 +3806,7 @@ export async function main(): Promise<number> {}})(),),- cleanup(server?.close() ?? Promise.resolve()),+ cleanup(stopProcess(server)),]);await cleanup(stopProcess(chrome));if (profileDirectory) {diff --git a/scripts/release-update.mjs b/scripts/release-update.mjsdeleted file mode 100644index 8c8b0046..00000000--- a/scripts/release-update.mjs+++ /dev/null@@ -1,206 +0,0 @@-#!/usr/bin/env node--import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";-import { dirname, resolve } from "node:path";--export const DEFAULT_RELEASE_API_URL =- "https://api.github.com/repos/TNTcraftHIM/Screener/releases/latest";--export const UPDATE_EXIT_CODES = Object.freeze({- upToDate: 0,- available: 10,- unavailable: 20,-});--const FULL_REVISION = /^[0-9a-f]{40}$/i;-const RELEASE_PATH_PREFIX = "/TNTcraftHIM/Screener/releases/tag/";--export function normalizeRevision(value) {- const revision = typeof value === "string" ? value.trim().toLowerCase() : "";- return FULL_REVISION.test(revision) ? revision : null;-}--export function parseReleaseMetadata(value) {- if (!value || typeof value !== "object" || Array.isArray(value)) {- return null;- }- if (value.draft === true || value.prerelease === true) {- return null;- }- const revision = normalizeRevision(value.tag_name);- if (!revision || typeof value.html_url !== "string") {- return null;- }-- let releaseURL;- try {- releaseURL = new URL(value.html_url);- } catch {- return null;- }- if (- releaseURL.protocol !== "https:" ||- releaseURL.hostname !== "github.com" ||- releaseURL.username ||- releaseURL.password ||- releaseURL.port ||- releaseURL.search ||- releaseURL.hash ||- !releaseURL.pathname.startsWith(RELEASE_PATH_PREFIX)- ) {- return null;- }- let tag = "";- try {- tag = decodeURIComponent(releaseURL.pathname.slice(RELEASE_PATH_PREFIX.length));- } catch {- return null;- }- if (normalizeRevision(tag) !== revision) {- return null;- }- return { revision, url: releaseURL.toString() };-}--export function unavailableResult(currentRevision) {- return {- status: "unavailable",- currentRevision: normalizeRevision(currentRevision),- latestRevision: null,- releaseUrl: null,- };-}--export async function checkRelease({- currentRevision,- apiURL = DEFAULT_RELEASE_API_URL,- token = process.env.GITHUB_TOKEN || "",- timeoutMs = 5_000,- fetchImpl = globalThis.fetch,-} = {}) {- const current = normalizeRevision(currentRevision);- if (!current || typeof fetchImpl !== "function") {- return unavailableResult(currentRevision);- }-- let endpoint;- try {- endpoint = new URL(apiURL);- } catch {- return unavailableResult(currentRevision);- }- if (endpoint.protocol !== "https:" && endpoint.protocol !== "http:") {- return unavailableResult(currentRevision);- }-- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), timeoutMs);- try {- const headers = {- Accept: "application/vnd.github+json",- "X-GitHub-Api-Version": "2022-11-28",- "User-Agent": "Screener-release-check",- };- if (- endpoint.protocol === "https:" &&- endpoint.hostname === "api.github.com" &&- typeof token === "string" &&- token.trim() !== ""- ) {- headers.Authorization = `Bearer ${token.trim()}`;- }- const response = await fetchImpl(endpoint.toString(), {- headers,- redirect: "error",- signal: controller.signal,- });- if (!response?.ok) {- return unavailableResult(current);- }- const latest = parseReleaseMetadata(await response.json());- if (!latest) {- return unavailableResult(current);- }- return {- status: latest.revision === current ? "up-to-date" : "update-available",- currentRevision: current,- latestRevision: latest.revision,- releaseUrl: latest.url,- };- } catch {- return unavailableResult(current);- } finally {- clearTimeout(timer);- }-}--function usage() {- return "Usage: node scripts/release-update.mjs --current-file <REVISION> [--api-url <URL>]";-}--function parseArguments(argumentsList) {- let currentFile = null;- let apiURL = DEFAULT_RELEASE_API_URL;- let apiURLSet = false;- for (let index = 0; index < argumentsList.length; index += 1) {- const name = argumentsList[index];- const value = argumentsList[index + 1];- if (- (name === "--current-file" || name === "--api-url") &&- (!value || value.startsWith("--"))- ) {- throw new Error(usage());- }- if (name === "--current-file" && currentFile === null) {- currentFile = value;- index += 1;- } else if (name === "--api-url" && !apiURLSet) {- apiURL = value;- apiURLSet = true;- index += 1;- } else {- throw new Error(usage());- }- }- if (!currentFile) {- throw new Error(usage());- }- return { currentFile, apiURL };-}--async function main() {- let argumentsValue;- try {- argumentsValue = parseArguments(process.argv.slice(2));- } catch (error) {- process.stderr.write(`${error instanceof Error ? error.message : usage()}\n`);- process.exitCode = 2;- return;- }-- let currentRevision = null;- try {- currentRevision = readFileSync(resolve(argumentsValue.currentFile), "ascii");- } catch {- // An unavailable deployed identity is an unavailable check, not an update.- }- const result = await checkRelease({- currentRevision,- apiURL: argumentsValue.apiURL,- });- process.stdout.write(`${JSON.stringify(result)}\n`);- process.exitCode = UPDATE_EXIT_CODES[- result.status === "update-available"- ? "available"- : result.status === "up-to-date"- ? "upToDate"- : "unavailable"- ];-}--const entry = process.argv[1] ? resolve(process.argv[1]) : "";-const self = resolve(dirname(fileURLToPath(import.meta.url)), "release-update.mjs");-if (entry === self) {- await main();-}diff --git a/scripts/required-project-paths.txt b/scripts/required-project-paths.txtindex 93acf345..efe2462a 100644--- a/scripts/required-project-paths.txt+++ b/scripts/required-project-paths.txt@@ -10,6 +10,8 @@ README.mdpackage.jsonpackage-lock.jsontsconfig.json+go.mod+go.sum.codex/config.toml.codex/README.md.agents/skills/ponytail/SKILL.md@@ -32,15 +34,16 @@ docs/deployment.mddocs/operations/self-hosting.mddocs/reference/configuration.mdscripts/package-app-release.mjs-scripts/release-update.mjsscripts/assemble-client.mjsscripts/client-icons.mjsscripts/package-client-candidate.mjsscripts/check-client.mjsscripts/client-native-host-gate.ts-native/client/cmd/screener-peer-gate/main.go-native/client/cmd/screener-client/screener.ico-native/client/cmd/screener-client/screener_windows_amd64.syso+cmd/screener-server/main.go+cmd/screener-peer-gate/main.go+cmd/screener-client/screener.ico+cmd/screener-client/screener_windows_amd64.syso+internal/server/webassets/dist/.gitkeepdeploy/release-app.shdeploy/check-release.shdocs/adr/0001-p2p-first-media-topology.md@@ -48,16 +51,16 @@ docs/adr/0010-cross-platform-client-runtime.mddocs/research/agent-context-governance.mddocs/research/cross-platform-client-runtime.mddocs/research/webrtc-p2p-screen-sharing.md-native/client/platform/windows/capture/README.md-native/client/platform/windows/capture/build.ps1-native/client/platform/windows/capture/capture_target.cpp-native/client/platform/windows/capture/capture_target.h-native/client/platform/windows/capture/main.cpp-native/client/platform/windows/capture/process_audio.cpp-native/client/platform/windows/capture/process_audio.h-native/client/platform/darwin/capture/README.md-native/client/platform/darwin/capture/build.sh-native/client/platform/darwin/capture/main.swift+native/capture/windows/README.md+native/capture/windows/build.ps1+native/capture/windows/capture_target.cpp+native/capture/windows/capture_target.h+native/capture/windows/main.cpp+native/capture/windows/process_audio.cpp+native/capture/windows/process_audio.h+native/capture/darwin/README.md+native/capture/darwin/build.sh+native/capture/darwin/main.swiftscripts/required-project-paths.txtscripts/check-project-state.shscripts/check-project-state.ps1diff --git a/src/client/App.tsx b/src/client/App.tsxindex c87cec4e..c781686f 100644--- a/src/client/App.tsx+++ b/src/client/App.tsx@@ -1,9 +1,11 @@import {+ Component,Suspense,lazy,useEffect,useState,type FormEvent,+ type ReactNode,} from "react";import {ApiError,@@ -21,7 +23,7 @@ import {import { AppHeader } from "./components/living/Header";import { BrandLoader } from "./components/living/BrandMark";import { Btn, Pill } from "./components/living/primitives";-import { ComicTooltip } from "./components/living/ComicTooltip";+import { Comic, type ComicKind } from "./components/living/Comic";import { Glyph, type GlyphName } from "./ui/icons";import { useCopy } from "./ui/copy";import { OverlayPreviewPage } from "./pages/OverlayPreviewPage";@@ -90,12 +92,40 @@ export function App() {}, [lang, vis]);return (- <Suspense fallback={<RouteLoader />}>- <AppRoute />- </Suspense>+ <RouteBoundary>+ <Suspense fallback={<RouteLoader />}>+ <AppRoute />+ </Suspense>+ </RouteBoundary>);}+// A page chunk that fails to load (offline, stale deploy) throws during render;+// without this the root unmounts to a blank page with no way back.+class RouteBoundary extends Component<+ { children: ReactNode },+ { failed: boolean }+> {+ state = { failed: false };++ static getDerivedStateFromError(): { failed: boolean } {+ return { failed: true };+ }++ render(): ReactNode {+ return this.state.failed ? (+ <StaticRoute+ icon="alert"+ comic="warning"+ titleKey="gate.unavailableRoute"+ action="reload"+ />+ ) : (+ this.props.children+ );+ }+}+function AppRoute() {if (overlayPreview) {return <OverlayPreviewPage />;@@ -113,7 +143,7 @@ function AppRoute() {launchedByClient={clientLaunchBootstrap?.launchedByClient}/>) : (- <SiteAccessGate surface="viewer" />+ <SiteAccessGate surface="viewer" invalidInvite={viewerRoute.invalidGrant} />);}if (appRoute.kind === "host") {@@ -123,9 +153,15 @@ function AppRoute() {return <SiteAccessGate surface="join" />;}return appRoute.kind === "malformed-room" ? (- <StaticRoute icon="door" titleKey="gate.malformed" hintKey="gate.malformedHint" />+ <StaticRoute+ icon="door"+ comic="room-not-found"+ titleKey="gate.malformed"+ hintKey="gate.malformedHint"+ action="join"+ />) : (- <StaticRoute icon="alert" titleKey="gate.unavailableRoute" />+ <StaticRoute icon="alert" comic="warning" titleKey="gate.unavailableRoute" />);}@@ -157,28 +193,31 @@ function RouteLoader() {function StaticRoute({icon,+ comic,titleKey,hintKey,+ action,}: {icon: GlyphName;+ comic: ComicKind;titleKey: "gate.malformed" | "gate.unavailableRoute";hintKey?: "gate.malformedHint";+ action?: "join" | "reload";}) {const { t, vis } = useCopy();- const panelIcon = (- <span className="lr-tv-big" style={{ borderColor: "var(--ink)", color: "var(--ink)", background: "var(--paper)" }}>- <Glyph name={icon} size={30} />- </span>- );return (<div className="lr-app"><AppHeader /><main className="lr-join"><div className="lr-join-panel">{vis ? (- <ComicTooltip kind="warning">{panelIcon}</ComicTooltip>+ // The scene states this exact situation, so the meaning needs no+ // hover: a tooltip trigger would leave it pointer-only.+ <Comic kind={comic} theme="paper" />) : (- panelIcon+ <span className="lr-tv-big" style={{ borderColor: "var(--ink)", color: "var(--ink)", background: "var(--paper)" }}>+ <Glyph name={icon} size={30} />+ </span>)}{vis ? null : (<div className="lr-access-text">@@ -187,8 +226,24 @@ function StaticRoute({</div>)}<span className="visually-hidden" role="alert">- {t(titleKey)}+ {hintKey ? [t(titleKey), t(hintKey)].join(" · ") : t(titleKey)}</span>+ {action === "join" ? (+ <Btn+ icon="door"+ title="join.title"+ cap="join.title"+ hint="hint-join-go"+ onClick={() => window.location.assign("/join")}+ />+ ) : action === "reload" ? (+ <Btn+ icon="refresh"+ title="common.refresh"+ cap="common.refresh"+ onClick={() => window.location.reload()}+ />+ ) : null}</div></main></div>@@ -197,8 +252,11 @@ function StaticRoute({function SiteAccessGate({surface,+ invalidInvite,}: {surface: "host" | "join" | "viewer";+ /** The URL carried an invite fragment that could not be used. */+ invalidInvite?: boolean;}) {const { t, vis } = useCopy();const [access, setAccess] = useState<AccessState>({ kind: "checking" });@@ -220,11 +278,23 @@ function SiteAccessGate({([status, nextCapabilities]) => {if (!active) return;setCapabilities(nextCapabilities);- setAccess(stateFromStatus(status));+ const next = stateFromStatus(status);+ setAccess(+ next.kind === "required" && invalidInvite+ ? { kind: "required", error: t("viewer.msg.invalidInvite") }+ : next,+ );+ },+ (error: unknown) => {+ if (!active) return;+ // A rejected bootstrap credential is an access problem, not an outage:+ // the passphrase form is the recovery, not a retry of the same token.+ setAccess(+ error instanceof ApiError && error.status === 401+ ? { kind: "required", error: t("gate.expired") }+ : { kind: "unavailable", message: readableError(error, t) },+ );},- (error: unknown) =>- active &&- setAccess({ kind: "unavailable", message: readableError(error, t) }),);return () => {active = false;diff --git a/src/client/components/living/Comic.tsx b/src/client/components/living/Comic.tsxindex f138e8ab..5939da54 100644--- a/src/client/components/living/Comic.tsx+++ b/src/client/components/living/Comic.tsx@@ -26,26 +26,6 @@ export type ComicKind =| "encoder-limited"| "warning";-export const COMIC_KINDS: readonly ComicKind[] = [- "waiting-for-host",- "connecting-p2p",- "connecting-sfu",- "tap-to-play",- "host-paused",- "recovering",- "route-failed",- "playback-failed",- "host-offline",- "no-audio",- "room-not-found",- "access-denied",- "invalid-invite",- "room-full",- "bandwidth-limited",- "encoder-limited",- "warning",-];-/** stage = dark TV overlay (default for overlay states); paper = join rows. */export type ComicTheme = "stage" | "paper";diff --git a/src/client/components/living/ComicTooltip.tsx b/src/client/components/living/ComicTooltip.tsxindex f28df3c5..45b76a4f 100644--- a/src/client/components/living/ComicTooltip.tsx+++ b/src/client/components/living/ComicTooltip.tsx@@ -27,6 +27,8 @@ const TOUCH_HIDE_MS = 1500;const COMIC_EXIT_MS = 160;// Minimum clearance the re-picked alignment keeps to each viewport edge.const EDGE_MARGIN = 8;+// Paper panel before it is measured: 240-wide comic strip plus its padding.+const FALLBACK_PANEL_HEIGHT = 96;type Align = "center" | "start" | "end";@@ -55,6 +57,10 @@ export function ComicTooltip({const [touchOpen, setTouchOpen] = useState(false);const [comicMounted, setComicMounted] = useState(false);const [liveAlign, setLiveAlign] = useState<Align | null>(null);+ const [livePlace, setLivePlace] = useState<"above" | "below" | null>(null);+ // True while the current gesture is a touch, so contextmenu can tell a+ // long-press from a mouse right-click without reading vendor event fields.+ const touchGesture = useRef(false);const interactionOpen = hoverOpen || focusOpen || touchOpen;const disabledTrigger =isValidElement<{@@ -94,6 +100,22 @@ export function ComicTooltip({const rect = wrap.getBoundingClientRect();const measured = comicMounted ? (tipRef.current?.offsetWidth ?? 0) : 0;const width = Math.max(0, Math.min(measured || 320, vw - EDGE_MARGIN * 2));+ // Same idea vertically: a control scrolled near the top has no room above,+ // and the panel would be cut off by the viewport edge.+ const vh = window.innerHeight;+ const panelHeight =+ (comicMounted ? tipRef.current?.offsetHeight : 0) || FALLBACK_PANEL_HEIGHT;+ const fitsAbove = rect.top - panelHeight - EDGE_MARGIN >= 0;+ const fitsBelow = !vh || rect.bottom + panelHeight + EDGE_MARGIN <= vh;+ setLivePlace(+ place === "above"+ ? fitsAbove || !fitsBelow+ ? "above"+ : "below"+ : fitsBelow || !fitsAbove+ ? "below"+ : "above",+ );const center = rect.left + rect.width / 2;const boxes: Record<Align, { left: number; right: number }> = {center: { left: center - width / 2, right: center + width / 2 },@@ -180,7 +202,7 @@ export function ComicTooltip({}};- const placeClass = place === "below" ? " is-below" : "";+ const placeClass = (livePlace ?? place) === "below" ? " is-below" : "";const shownAlign = liveAlign ?? align;const alignClass =shownAlign === "start" ? " is-start" : shownAlign === "end" ? " is-end" : "";@@ -213,6 +235,7 @@ export function ComicTooltip({}}}onPointerDown={(event) => {+ touchGesture.current = event.pointerType === "touch";if (event.pointerType !== "touch") return;// A suppression token belongs only to the click synthesized for the// completed long-press. A later touch starts a new, actionable gesture.@@ -260,11 +283,18 @@ export function ComicTooltip({}}onContextMenu={(event) => {// Long-press on a wrapped control means "show the hint", never the- // native context menu. Chrome fires contextmenu as a PointerEvent;- // fall back to treating unknown types as touch.- if ((event.nativeEvent as PointerEvent).pointerType !== "mouse") {- event.preventDefault();+ // native context menu. Only that gesture is suppressed: a mouse+ // right-click (no touch pointerdown) and any menu raised over a text+ // field (its paste/select entries are the only way in) stay native.+ if (!touchGesture.current) return;+ if (+ (event.target as HTMLElement).closest(+ "input, textarea, [contenteditable=\"true\"]",+ )+ ) {+ return;}+ event.preventDefault();}}onClickCapture={(event) => {// The synthetic click after a long-press must not fire the control.diff --git a/src/client/components/living/Metrics.tsx b/src/client/components/living/Metrics.tsxindex deec2ed1..c2ff182f 100644--- a/src/client/components/living/Metrics.tsx+++ b/src/client/components/living/Metrics.tsx@@ -13,6 +13,8 @@ interface MetricValue {label: CopyKey;value: string;title?: string;+ /** Visual mode shows the glyph alone; the value stays in the a11y name. */+ glyphOnly?: boolean;}export function codecContractWarnings(@@ -62,6 +64,14 @@ function secondaryMetrics(};return t(keys[value] ?? "stats.quality.unclassified");};+ const qualityReasonIcon = (value: string): GlyphName =>+ value === "none"+ ? "check"+ : value === "bandwidth"+ ? "gauge"+ : value === "cpu"+ ? "cpu"+ : "alert";addNumber("stats.rtt", "clock", metrics.rttMs, "ms");if (metrics.codec) {@@ -76,9 +86,12 @@ function secondaryMetrics(addNumber("stats.outgoing", "gauge", metrics.availableOutgoingKbps, "kbps");if (metrics.qualityLimitationReason) {values.push({- icon: "gauge",+ icon: qualityReasonIcon(metrics.qualityLimitationReason),label: "stats.qualityState",value: qualityReason(metrics.qualityLimitationReason),+ // A limitation reason is a sentence, not a measured value: visual+ // mode states it with the glyph and keeps the words for AT.+ glyphOnly: true,});}const captureParts: string[] = [];@@ -163,16 +176,17 @@ export function MetricCells({onToggle: (expanded: boolean) => void;}) {const { t, vis } = useCopy();- const cell = ({ icon, label, value, title }: MetricValue): ReactNode => {- if (vis && label === "stats.qualityState") return null;+ const cell = ({ icon, label, value, title, glyphOnly }: MetricValue): ReactNode => {const display = vis && value === t("stats.unknown") ? "—" : value;return (<span className="lr-meter-cell" title={vis ? undefined : title ?? t(label)} key={label + display}><Glyph name={icon} size={16} />{vis ? (<>- <b>{display}</b>- <span className="visually-hidden">{t(label)}</span>+ {glyphOnly ? null : <b>{display}</b>}+ <span className="visually-hidden">+ {glyphOnly ? [t(label), display].join(" · ") : t(label)}+ </span></>) : (<span className="lr-meter-text">diff --git a/src/client/components/living/RouteTree.tsx b/src/client/components/living/RouteTree.tsxindex 9ffd6808..a0d7a5fa 100644--- a/src/client/components/living/RouteTree.tsx+++ b/src/client/components/living/RouteTree.tsx@@ -99,6 +99,7 @@ function edgeClass(kind: "p2p" | "sfu", ready = true): string {export const RouteTree = memo(function RouteTree({hostPeerId,+ hostIdentity,hostLabel,viewers,selfPeerId,@@ -107,6 +108,8 @@ export const RouteTree = memo(function RouteTree({onSelectPeer,}: {hostPeerId: string | null;+ /** Colour identity for the Host pawn while its peer id is still unknown. */+ hostIdentity?: string | null;hostLabel: string;viewers: readonly LabeledViewerPresence[];selfPeerId?: string | null;@@ -361,7 +364,10 @@ export const RouteTree = memo(function RouteTree({className="lr-route-node is-host"transform={`translate(${centeredPawnX(hostPos.x, PAWN_SCALE)}, ${centeredPawnY(hostPos.y, PAWN_SCALE)}) scale(${PAWN_SCALE})`}>- <PawnSvg color={participantColor(hostPeerId ?? "host-pending")} crown />+ <PawnSvg+ color={participantColor(hostPeerId ?? hostIdentity ?? "host-pending")}+ crown+ /></g><textclassName="lr-route-label is-host"@@ -491,9 +497,11 @@ export const RouteTree = memo(function RouteTree({key={`hit-${node.key}`}className="lr-route-hit"x={point.x - 48}- y={point.y - 28}+ // Bound the target to the row pitch: a taller rect would cover+ // the next row's label and steal its clicks (later rect wins).+ y={point.y - 26}width={96}- height={72}+ height={spacing}rx={12}role="button"tabIndex={0}diff --git a/src/client/components/living/Stage.tsx b/src/client/components/living/Stage.tsxindex e5d96687..a766e722 100644--- a/src/client/components/living/Stage.tsx+++ b/src/client/components/living/Stage.tsx@@ -135,7 +135,9 @@ export function StageOverlay({}return (<div- className={`lr-tv-overlay${dim ? " is-dim" : ""}${vis && comic ? " has-comic" : ""}`}+ // Passive state layer: it must not intercept clicks meant for the+ // native <video> controls it covers (it owns no controls itself).+ className={`lr-tv-overlay is-passive${dim ? " is-dim" : ""}${vis && comic ? " has-comic" : ""}`}role="status"aria-label={message}>diff --git a/src/client/components/living/hints/index.tsx b/src/client/components/living/hints/index.tsxindex b82c3d26..521db105 100644--- a/src/client/components/living/hints/index.tsx+++ b/src/client/components/living/hints/index.tsx@@ -47,8 +47,6 @@ export type Set3Kind =export type Set4Kind =| "hint-topology"| "hint-close"- | "hint-admit"- | "hint-deny"| "hint-rename"| "hint-theme"| "hint-join-go"@@ -87,8 +85,6 @@ export const HINT_KINDS: readonly HintKind[] = ["hint-more-metrics","hint-topology","hint-close",- "hint-admit",- "hint-deny","hint-rename","hint-theme","hint-join-go",diff --git a/src/client/components/living/hints/set4.tsx b/src/client/components/living/hints/set4.tsxindex 5062f732..41b77bb9 100644--- a/src/client/components/living/hints/set4.tsx+++ b/src/client/components/living/hints/set4.tsx@@ -1,4 +1,4 @@-// Hint set 4 — people & misc: topology, close, admit/deny, rename, theme, join-go, route p2p/sfu.+// Hint set 4 — people & misc: topology, close, rename, theme, join-go, route p2p/sfu.// Scenes follow ../Comic.tsx conventions: 320x96 canvas, 2-panel// before→after idiom (Frame x={4} w={152} + Frame x={164} w={152}), vls-// prefixed keyframes in an inline <style>, rmBlock for reduced motion.@@ -7,7 +7,6 @@import {BrowserWindow,Crown,- Door,FAINT,Frame,LIVE,@@ -105,83 +104,6 @@ ${rmBlock(</>);-/* hint-admit: [pawn knocking at a shut door] → [door open, pawn hops in,- star]. Loop 3.2s: two knocks 0-24%, hop-in 10-26%, star pop 30-42%;- rest ~58%. */-const HintAdmit: HintScene = ({ theme }) => (- <>- <style>{`-.vls-adm-knock{animation:vlsAdmKnock 3.2s ease-in-out infinite}-.vls-adm-kn{animation:vlsAdmKn 3.2s ease-in-out infinite}-.vls-adm-hop{transform-box:fill-box;transform-origin:50% 100%;animation:vlsAdmHop 3.2s cubic-bezier(.3,1.4,.5,1) infinite}-.vls-adm-star{transform-box:fill-box;transform-origin:center;animation:vlsAdmStar 3.2s cubic-bezier(.3,1.5,.5,1) infinite}-@keyframes vlsAdmKnock{0%{transform:translateX(0)}6%{transform:translateX(4px)}12%{transform:translateX(0)}18%{transform:translateX(4px)}24%,100%{transform:translateX(0)}}-@keyframes vlsAdmKn{0%,3%{opacity:0}7%{opacity:.9}11%{opacity:0}15%{opacity:.9}22%,100%{opacity:0}}-@keyframes vlsAdmHop{0%,10%{transform:translate(-40px,0)}18%{transform:translate(-18px,-9px)}26%,100%{transform:translate(0,0)}}-@keyframes vlsAdmStar{0%,30%{opacity:0;transform:scale(0)}36%{opacity:1;transform:scale(1.25)}42%,100%{opacity:1;transform:scale(1)}}-${rmBlock(- ["vls-adm-knock", "vls-adm-kn", "vls-adm-hop", "vls-adm-star"],- [- [".vls-adm-kn", "opacity:0"],- [".vls-adm-hop,.vls-adm-star", "transform:none"],- [".vls-adm-star", "opacity:1"],- ],-)}-`}</style>- <Frame x={4} w={152} theme={theme} />- <Frame x={164} w={152} theme={theme} accent={LIVE} />- <g className="vls-adm-knock">- <Pawn x={63} yb={76} s={9} eyes />- </g>- <g className="vls-adm-kn" stroke={INK} strokeWidth={2} strokeLinecap="round" opacity={0}>- <path d="M84 36l-7-3M82 46h-8M84 56l-7 3" />- </g>- <Door x={96} y={18} />- <rect x={242} y={18} width={38} height={56} rx={5} fill={TV_SCREEN} stroke={INK} strokeWidth={2.5} />- <path d="M242 18 L262 25 L262 67 L242 74 Z" fill={WALL2} stroke={INK} strokeWidth={2.5} strokeLinejoin="round" />- <circle cx={257} cy={46} r={1.8} fill={INK} />- <g className="vls-adm-hop">- <Pawn x={271} yb={74} s={8} eyes />- </g>- <Star x={288} y={24} className="vls-adm-star" baseOpacity={0} />- </>-);--/* hint-deny: [pawn at a shut door] → [door stays shut, pawn turned away- waving bye with a head-tilt; footprints trail back]. Gentle: no RedX.- Loop 3.2s: two knocks 0-24%, wave 32-52%; rest ~48%. */-const HintDeny: HintScene = ({ theme }) => (- <>- <style>{`-.vls-dny-kn{animation:vlsDnyKn 3.2s ease-in-out infinite}-.vls-dny-wave{transform-box:fill-box;transform-origin:50% 100%;animation:vlsDnyWave 3.2s ease-in-out infinite}-@keyframes vlsDnyKn{0%,3%{opacity:0}7%{opacity:.9}11%{opacity:0}15%{opacity:.9}22%,100%{opacity:0}}-@keyframes vlsDnyWave{0%,32%{transform:rotate(0)}36%{transform:rotate(-8deg)}40%{transform:rotate(8deg)}44%{transform:rotate(-8deg)}48%{transform:rotate(8deg)}52%,100%{transform:rotate(0)}}-${rmBlock(- ["vls-dny-kn", "vls-dny-wave"],- [[".vls-dny-kn", "opacity:0"], [".vls-dny-wave", "transform:none"]],-)}-`}</style>- <Frame x={4} w={152} theme={theme} />- <Frame x={164} w={152} theme={theme} />- <Pawn x={60} yb={76} s={9} eyes />- <g className="vls-dny-kn" stroke={INK} strokeWidth={2} strokeLinecap="round" opacity={0}>- <path d="M88 36l-7-3M86 46h-8M88 56l-7 3" />- </g>- <Door x={96} y={18} />- <Door x={252} y={18} />- <g fill={INK} opacity={0.35}>- <circle cx={222} cy={72} r={1.5} />- <circle cx={232} cy={68} r={1.5} />- </g>- <g className="vls-dny-wave">- <Pawn x={206} yb={76} s={9} />- <circle cx={202.5} cy={58} r={1} fill={EYE} />- <circle cx={206} cy={58} r={1} fill={EYE} />- </g>- </>-);-/* hint-rename: [blank name tag] → [pencil writes a squiggle on the tag +spark]. Loop 3.2s: pencil rides the pen tip left→right wiggling (6-34%)as the line draws, spark pops 38-46%, holds; rest 54%. */@@ -582,8 +504,6 @@ ${rmBlock(export const SET4_SCENES: Record<Set4Kind, HintScene> = {"hint-topology": HintTopology,"hint-close": HintClose,- "hint-admit": HintAdmit,- "hint-deny": HintDeny,"hint-rename": HintRename,"hint-theme": HintTheme,"hint-join-go": HintJoinGo,diff --git a/src/client/lib/session.ts b/src/client/lib/session.tsindex 6e09df5c..09edcbda 100644--- a/src/client/lib/session.ts+++ b/src/client/lib/session.ts@@ -39,6 +39,8 @@ export interface HostRoomState extends HostRoomIdentity {export interface ViewerRoute {roomId: string;viewerGrant?: string;+ /** An invite fragment was present but its grant was unusable. */+ invalidGrant?: true;}export type AppRoute =@@ -266,20 +268,22 @@ export function readViewerRoute(): ViewerRoute | null {}const roomId = route.roomId;- const fragment = window.location.hash;- if (fragment) {- const fragmentMatch = fragment.match(/^#v=(.+)$/);- const viewerGrant = fragmentMatch?.[1];- const validGrant = viewerGrant && isValidViewerGrant(viewerGrant)- ? viewerGrant- : null;+ // Only a `#v=` fragment is an invite credential. Any other fragment (a mail+ // client suffix, a `#:~:text=` scroll target) must not be read as a failed+ // grant, or it would revoke the grant this tab already holds.+ const fragmentMatch = window.location.hash.match(/^#v=(.*)$/);+ if (fragmentMatch) {+ const viewerGrant = fragmentMatch[1];+ const validGrant = isValidViewerGrant(viewerGrant) ? viewerGrant : null;if (validGrant) {writeSessionValue(viewerGrantStorageKey(roomId), validGrant);} else {clearViewerGrant(roomId);}window.history.replaceState(window.history.state, "", `/r/${roomId}`);- return validGrant ? { roomId, viewerGrant: validGrant } : { roomId };+ return validGrant+ ? { roomId, viewerGrant: validGrant }+ : { roomId, invalidGrant: true };}const storedGrant = readSessionValue(viewerGrantStorageKey(roomId));diff --git a/src/client/lib/signaling.ts b/src/client/lib/signaling.tsindex 34b4a77a..6f0e7aca 100644--- a/src/client/lib/signaling.ts+++ b/src/client/lib/signaling.ts@@ -144,10 +144,6 @@ export class SignalingClient {return this.send({ type: "set-display-name", displayName });}- setViewerDisplayName(displayName: DisplayName): boolean {- return this.setDisplayName(displayName);- }-setSharingPaused(paused: boolean): boolean {if (this.identity.role !== "host") {return false;@@ -325,9 +321,7 @@ export class SignalingClient {if (!this.stopped && shouldReconnectSignaling(event.code)) {this.scheduleReconnect();} else if (!this.stopped) {- this.stopped = true;- this.clearTimers();- this.events.onStatus("offline");+ this.stop();this.events.onTerminated(event.code === SIGNAL_CLOSE_CODES.sessionReplaced? "SESSION_REPLACED"diff --git a/src/client/locales/en.ts b/src/client/locales/en.tsindex 5e164eec..c3456c1e 100644--- a/src/client/locales/en.ts+++ b/src/client/locales/en.ts@@ -18,7 +18,6 @@ export const en: Record<CopyKey, string> = {"common.host": "Host","common.name.viewerDefault": "Viewer","common.name.hostDefault": "Host",- "page.room": "Room {room}","client.launch.title": "Open Screener","client.launch.hint": "Choose how to connect this time",@@ -35,6 +34,7 @@ export const en: Record<CopyKey, string> = {"client.launch.go": "Open Screener","client.launch.starting": "Preparing Screener","client.launch.error": "Screener could not start; check the setting and retry",+ "client.launch.loadFailed": "Could not read the launcher settings; retry","client.update.available": "A newer Screener release is available","gate.title": "Site access",@@ -53,11 +53,6 @@ export const en: Record<CopyKey, string> = {"join.field": "Room code","join.submit": "Join","join.invalid": "Enter a four-digit room code between 1000 and 9999",- "join.joining": "Joining the room",- "join.notFound": "Room not found or expired",- "join.notFoundHint": "Check the room code, or ask the host for a new invite link.",- "join.denied": "This room cannot be joined by code right now",- "join.deniedHint": "Use the host's invite link, or try the room password.","join.password": "Room password","join.passwordError": "Could not join; try again","join.passwordRule": "Enter 1-{max} visible characters",@@ -77,7 +72,6 @@ export const en: Record<CopyKey, string> = {"host.sourcePicker.windowAudio": "Application sound","host.sourcePicker.systemAudio": "System sound","host.sourcePicker.empty": "No sources available",- "host.sourcePicker.native": "Client native capture","host.sourcePicker.nativeAudio": "Client · with sound","host.sourcePicker.window": "Share window: {title}","host.sourcePicker.display": "Share screen: {title}",@@ -107,7 +101,6 @@ export const en: Record<CopyKey, string> = {"host.roomInvalid": "Room expired; press again to create a new one","host.roomReplace": "Replace room code","host.roomReplaceConfirm": "Confirm replacing the room code",- "host.captureError": "Screen capture unavailable; check browser permission and retry","host.terminated.stale": "Page updated; refresh to continue","host.terminated.session": "This page's session was taken over by another tab","host.terminated.signal": "Server connection terminated; refresh to continue",@@ -207,7 +200,6 @@ export const en: Record<CopyKey, string> = {"host.topology.show": "Show connection topology","host.topology.hide": "Hide connection topology","host.topology.pending": "Connecting",- "host.sfu": "Media server","state.signal.connected": "Server connected","state.signal.connecting": "Connecting",diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.tsindex 4a89e9bc..a1ed0197 100644--- a/src/client/locales/zh.ts+++ b/src/client/locales/zh.ts@@ -16,7 +16,6 @@ export const zh = {"common.host": "分享者","common.name.viewerDefault": "观众","common.name.hostDefault": "分享者",- "page.room": "房间 {room}","client.launch.title": "打开 Screener","client.launch.hint": "选择这次使用的连接方式",@@ -33,6 +32,7 @@ export const zh = {"client.launch.go": "进入 Screener","client.launch.starting": "正在准备 Screener","client.launch.error": "暂时无法启动,请检查设置后重试",+ "client.launch.loadFailed": "无法读取启动设置,请重试","client.update.available": "发现新的 Screener 版本","gate.title": "站点访问",@@ -51,11 +51,6 @@ export const zh = {"join.field": "房间号","join.submit": "加入","join.invalid": "请输入 1000 至 9999 的四位房间号",- "join.joining": "正在加入房间",- "join.notFound": "房间不存在或已过期",- "join.notFoundHint": "请确认房间号,或向分享者获取新的邀请链接。",- "join.denied": "当前无法通过房间号加入",- "join.deniedHint": "请使用分享者提供的邀请链接,或尝试房间密码。","join.password": "房间密码","join.passwordError": "无法加入房间,请重试","join.passwordRule": "请输入 1-{max} 个可见字符",@@ -75,7 +70,6 @@ export const zh = {"host.sourcePicker.windowAudio": "应用声音","host.sourcePicker.systemAudio": "系统声音","host.sourcePicker.empty": "暂无可用来源",- "host.sourcePicker.native": "Client 本机捕获","host.sourcePicker.nativeAudio": "Client · 含声音","host.sourcePicker.window": "分享窗口:{title}","host.sourcePicker.display": "分享屏幕:{title}",@@ -105,7 +99,6 @@ export const zh = {"host.roomInvalid": "房间已失效,再次点击将创建新房","host.roomReplace": "更换房间号","host.roomReplaceConfirm": "确认更换房间号",- "host.captureError": "无法开始屏幕采集,请检查浏览器权限后重试","host.terminated.stale": "页面版本已更新,请刷新后重试","host.terminated.session": "此页面的会话已被另一个标签页接管","host.terminated.signal": "服务器连接已终止,请刷新后重试",@@ -205,7 +198,6 @@ export const zh = {"host.topology.show": "显示连接拓扑","host.topology.hide": "隐藏连接拓扑","host.topology.pending": "连接中",- "host.sfu": "媒体服务器","state.signal.connected": "服务器已连接","state.signal.connecting": "正在连接",diff --git a/src/client/media/relay-capability.ts b/src/client/media/relay-capability.tsindex 39012590..aaa772b9 100644--- a/src/client/media/relay-capability.ts+++ b/src/client/media/relay-capability.ts@@ -7,11 +7,7 @@ type RelayCapacityMessage = Extract<>;export function relayCapacityMessageForBrowser(- peerAssisted: boolean,-): RelayCapacityMessage | null {- if (!peerAssisted) {- return null;- }+): RelayCapacityMessage {return {type: "relay-capacity",downstreamEdges: MAX_ENDPOINT_MEDIA_COPY_CAPACITY,diff --git a/src/client/media/viewer-presentation.ts b/src/client/media/viewer-presentation.tsindex fb948d8f..35b64a8d 100644--- a/src/client/media/viewer-presentation.ts+++ b/src/client/media/viewer-presentation.ts@@ -109,6 +109,7 @@ export type ViewerPresentationAction =revision: number;phase: "prepare" | "active";kind: ViewerRouteKind;+ authoritative?: boolean;}| {type: "route-status";@@ -193,7 +194,11 @@ export function reduceViewerPresentation(return { ...state, host: action.host };}case "route": {- if (state.revision !== null && action.revision < state.revision) {+ if (+ !action.authoritative &&+ state.revision !== null &&+ action.revision < state.revision+ ) {return state;}const revisionChanged = state.revision !== action.revision;@@ -208,19 +213,24 @@ export function reduceViewerPresentation(phase: action.phase,kind: action.kind,},- routeStatus:- !committedRoute && state.routeStatus?.revision === action.revision+ routeStatus: action.authoritative+ ? null+ : !committedRoute && state.routeStatus?.revision === action.revision? state.routeStatus: null,- connection: reactivatingTerminalRoute- ? state.media- ? "reconnecting"+ connection: action.authoritative && state.media === null+ ? action.kind === "none"+ ? "idle": "connecting"- : revisionChanged && state.media === null- ? action.kind === "none"- ? "idle"+ : reactivatingTerminalRoute+ ? state.media+ ? "reconnecting": "connecting"- : state.connection,+ : revisionChanged && state.media === null+ ? action.kind === "none"+ ? "idle"+ : "connecting"+ : state.connection,};}case "route-status": {diff --git a/src/client/native/media-bridge.ts b/src/client/native/media-bridge.tsindex 334b9597..a3bdc6d6 100644--- a/src/client/native/media-bridge.ts+++ b/src/client/native/media-bridge.ts@@ -37,6 +37,7 @@ export class NativeMediaBridge {private ready = false;private disposed = false;private startTimer: number | null = null;+ private rejectStart: ((error: Error) => void) | null = null;constructor(private readonly shareId: string,@@ -62,13 +63,9 @@ export class NativeMediaBridge {if (this.disposed || this.unsubscribe) {throw new Error("Native media bridge is unavailable");}- let rejectStart: (error: Error) => void = () => undefined;const started = new Promise<MediaStream>((resolve, reject) => {- rejectStart = reject;- this.startTimer = window.setTimeout(- () => this.fail(rejectStart),- BRIDGE_TIMEOUT_MS,- );+ this.rejectStart = reject;+ this.startTimer = window.setTimeout(() => this.fail(), BRIDGE_TIMEOUT_MS);const complete = () => {if (!this.ready &&@@ -77,6 +74,7 @@ export class NativeMediaBridge {(!this.expectedAudio || this.stream.getAudioTracks().length > 0)) {this.ready = true;+ this.rejectStart = null;this.clearStartTimer();resolve(this.stream);}@@ -92,7 +90,7 @@ export class NativeMediaBridge {this.peer.connectionState === "failed" ||this.peer.connectionState === "closed") {- this.fail(rejectStart);+ this.fail();return;}complete();@@ -114,12 +112,12 @@ export class NativeMediaBridge {}: null,},- ).catch(() => this.fail(rejectStart));+ ).catch(() => this.fail());});this.unsubscribe = this.control.onEvent((event) => {if (event.shareId !== this.shareId) return;if (event.type === "share-ended") {- this.fail(rejectStart);+ this.fail();return;}if (@@ -131,7 +129,7 @@ export class NativeMediaBridge {if (event.type === "edge-candidate") {if (!this.remoteDescriptionSet) {if (this.pendingCandidates.length >= MAX_PENDING_CANDIDATES) {- this.fail(rejectStart);+ this.fail();} else {this.pendingCandidates.push(event.candidate);}@@ -139,12 +137,12 @@ export class NativeMediaBridge {}void this.peer.addIceCandidate(event.candidate)- .catch(() => this.fail(rejectStart));+ .catch(() => this.fail());} else if (event.type === "edge-state" &&(event.state === "failed" || event.state === "closed")) {- this.fail(rejectStart);+ this.fail();}});@@ -189,6 +187,8 @@ export class NativeMediaBridge {dispose(): void {if (this.disposed) return;this.disposed = true;+ this.rejectStart?.(new Error("Native media bridge failed"));+ this.rejectStart = null;this.unsubscribe?.();this.unsubscribe = null;this.clearStartTimer();@@ -200,13 +200,9 @@ export class NativeMediaBridge {);}- private fail(rejectStart: (error: Error) => void): void {+ private fail(): void {if (this.disposed) return;- if (this.ready) {- this.onFailed();- } else {- rejectStart(new Error("Native media bridge failed"));- }+ if (this.ready) this.onFailed();this.dispose();}diff --git a/src/client/native/native-viewer-peer.ts b/src/client/native/native-viewer-peer.tsindex dce01cf2..3de7c29d 100644--- a/src/client/native/native-viewer-peer.ts+++ b/src/client/native/native-viewer-peer.ts@@ -456,7 +456,9 @@ class NativeViewerPeer implements ViewerMediaPeer {}this.events.onStream(stream);this.startObservation(bridge, connectionId);- }).catch(() => this.handleBridgeFailure(connectionId));+ }).catch(() => {+ if (this.bridge === bridge) this.handleBridgeFailure(connectionId);+ });}private onEvent(event: NativeClientEvent): void {@@ -643,6 +645,7 @@ class NativeViewerPeer implements ViewerMediaPeer {}private scheduleInitialConnectionDeadline(connectionId: string): void {+ if (this.recoveryOwner !== "viewer") return;this.clearInitialConnectionTimer();const timer = window.setTimeout(() => {if (this.initialConnectionTimer !== timer) return;diff --git a/src/client/pages/ClientLauncherPage.tsx b/src/client/pages/ClientLauncherPage.tsxindex 3e24e263..0639a0e6 100644--- a/src/client/pages/ClientLauncherPage.tsx+++ b/src/client/pages/ClientLauncherPage.tsx@@ -62,7 +62,7 @@ export function ClientLauncherPage() {const [mode, setMode] = useState<ClientMode>("local");const [site, setSite] = useState("");const [localAccessPassword, setLocalAccessPassword] = useState("");- const [error, setError] = useState(false);+ const [error, setError] = useState<null | "load" | "launch">(null);const [update, setUpdate] = useState<ReleaseUpdateNotice | null>(null);useEffect(() => {@@ -84,7 +84,7 @@ export function ClientLauncherPage() {}).catch(() => {if (!current) return;- setError(true);+ setError("load");setLoading(false);});return () => {@@ -96,7 +96,7 @@ export function ClientLauncherPage() {event.preventDefault();if (starting || (mode === "site" && !site.trim())) return;setStarting(true);- setError(false);+ setError(null);try {const response = await fetch("/api/client-launcher/launch", {method: "POST",@@ -111,7 +111,7 @@ export function ClientLauncherPage() {const result = launcherResultSchema.parse(await response.json());window.location.replace(result.target);} catch {- setError(true);+ setError("launch");setStarting(false);}}@@ -130,7 +130,7 @@ export function ClientLauncherPage() {title={vis ? undefined : t("client.launch.localAccessHint")}onChange={(event) => {setLocalAccessPassword(event.target.value);- setError(false);+ setError(null);}}/></label>@@ -155,6 +155,23 @@ export function ClientLauncherPage() {</span>)}</div>+ ) : error === "load" ? (+ <div className="lr-client-launch-panel">+ <BrandMark size={68} motion="once" />+ <Pill+ icon="alert"+ tone="bad"+ label={t("client.launch.loadFailed")}+ alert+ comic="warning"+ />+ <Btn+ icon="refresh"+ title="common.refresh"+ cap="common.refresh"+ onClick={() => window.location.reload()}+ />+ </div>) : (<form className="lr-client-launch-panel" onSubmit={launch}><BrandMark size={68} motion="once" />@@ -202,7 +219,7 @@ export function ClientLauncherPage() {title={vis ? undefined : t(choice.hint)}onClick={() => {setMode(choice.mode);- setError(false);+ setError(null);}}><Glyph name={choice.icon} size={27} />@@ -237,7 +254,7 @@ export function ClientLauncherPage() {aria-label={t("client.launch.siteAddress")}onChange={(event) => {setSite(event.target.value);- setError(false);+ setError(null);}}/></label>@@ -253,7 +270,7 @@ export function ClientLauncherPage() {)) : null}- {error ? (+ {error === "launch" ? (<Pillicon="alert"tone="bad"diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsxindex a94039ff..fd4f1544 100644--- a/src/client/pages/HostPage.tsx+++ b/src/client/pages/HostPage.tsx@@ -512,6 +512,7 @@ export function HostPage({setNoticeComic(comic);}const [copied, setCopied] = useState(false);+ const copiedResetTimerRef = useRef<number | null>(null);const [switchingSource, setSwitchingSource] = useState(false);const [changingQuality, setChangingQuality] = useState(false);const [sharingPaused, setSharingPaused] = useState(false);@@ -531,6 +532,13 @@ export function HostPage({const signalRef = useRef<SignalingClient | null>(null);const displayNameRef = useRef(displayName);const hostClientIdRef = useRef<string | null>(null);+ // Share start awaits capture, codec probe and room creation; the host can+ // switch expression mode meanwhile, so the name is derived from the current+ // mode rather than the render that began the start.+ const visRef = useRef(vis);+ useEffect(() => {+ visRef.current = vis;+ }, [vis]);useEffect(() => {if (hasCustomDisplayName) return;const fallback = defaultHostDisplayName(@@ -556,7 +564,6 @@ export function HostPage({new Map<string, number>(),);const viewerQualityEvidenceRenderFrameRef = useRef<number | null>(null);- const peerAssistedRef = useRef(false);const activeRouteRevisionRef = useRef(0);const generationRef = useRef(0);const activeGenerationRef = useRef<number | null>(null);@@ -692,6 +699,10 @@ export function HostPage({activeHostChildPeerIdsRef.current = [];endpointMediaCopyCapacityRef.current = MAX_ENDPOINT_MEDIA_CHILDREN;hostPeerIdRef.current = null;+ if (copiedResetTimerRef.current !== null) {+ window.clearTimeout(copiedResetTimerRef.current);+ copiedResetTimerRef.current = null;+ }viewerQualityEvidenceTimersRef.current.forEach((timer) =>window.clearTimeout(timer),);@@ -807,14 +818,6 @@ export function HostPage({return route;}- function clearHostSfuRoute(): void {- const route = hostSfuRouteRef.current;- hostSfuRouteRef.current = null;- setHostSfuQualityWarning(null);- sfuStandbyPrewarmerRef.current?.setUrl(null);- void route?.disconnect();- }-function setSfuStandbyUrl(url: string | null | undefined): void {if (!url) {sfuStandbyPrewarmerRef.current?.setUrl(null);@@ -878,7 +881,6 @@ export function HostPage({streamRef.current = null;retiringStreamRef.current = null;iceConfigRef.current = null;- peerAssistedRef.current = false;setStream(null);setDetails(null);setMaxViewers(null);@@ -943,6 +945,9 @@ export function HostPage({function endSharing(message: string | { key: CopyKey; vars?: Record<string, string> },notifyServer = true,+ // Involuntary endings keep the failure tone: the notice pill reads its+ // icon/tone from the comic, so a bare key would render as green success.+ comic: ComicKind | null = null,): void {const generation = activeGenerationRef.current;if (generation === null || generationRef.current !== generation) {@@ -955,11 +960,12 @@ export function HostPage({writePreferredRoom(currentRoom.roomId);}disposeResources(notifyServer);- if (typeof message === "string") {- setNotice(message);- } else {- setNoticeKey(message.key, message.vars);- }+ setNoticeValue(+ typeof message === "string"+ ? { kind: "text", text: message }+ : { kind: "key", key: message.key, vars: message.vars },+ );+ setNoticeComic(comic);setPhase("ended");}@@ -1038,7 +1044,10 @@ export function HostPage({}}if (forgetRoom(activeRoom)) {- endSharing({ key: "host.roomInvalid" }, false);+ // endSharing already stated the recovery path; the raw room error+ // would only overwrite it with the same 404 in server wording.+ endSharing({ key: "host.roomInvalid" }, false, "warning");+ return;}}setNoticeError(error, "room");@@ -1167,10 +1176,7 @@ export function HostPage({activeRouteRevisionRef.current,directSnapshot,);- if (- !evidenceSource ||- (evidenceSource === "peer-relayed" && !peerAssistedRef.current)- ) {+ if (!evidenceSource) {return;}commitViewerQualityEvidence(@@ -1231,7 +1237,7 @@ export function HostPage({nativeMediaBridgeRef.current === bridge &&isCurrentShare(generation, shareGeneration)) {- endSharing({ key: "host.shareEnded" });+ endSharing({ key: "host.shareEnded" }, true, "warning");}},started.audio,@@ -1250,9 +1256,11 @@ export function HostPage({isCurrentShare(generation, shareGeneration) &&nativeClientRef.current === client) {- endSharing({- key: event.failed ? "host.shareEnded" : "host.stopNotice",- });+ endSharing(+ { key: event.failed ? "host.shareEnded" : "host.stopNotice" },+ true,+ event.failed ? "warning" : null,+ );}});nativeEventCleanupRef.current = nativeEventCleanup;@@ -1293,7 +1301,7 @@ export function HostPage({if (nativeMediaIngressRef.current) {recoverBrowserFanout(nativeMediaIngressRef.current);} else if (nativeModeRef.current && activeGenerationRef.current !== null) {- endSharing({ key: "host.shareEnded" });+ endSharing({ key: "host.shareEnded" }, true, "warning");}});}@@ -1640,9 +1648,7 @@ export function HostPage({} else if (captureChanged) {setDetails(captureDetails(activeStream));}- if (peerAssistedRef.current) {- signalRef.current?.setHostQualitySettings(appliedProfile);- }+ signalRef.current?.setHostQualitySettings(appliedProfile);const activeSfuRoute = hostSfuRouteRef.current;const [results, sfuUpdated] = await Promise.all([Promise.all(@@ -1732,9 +1738,13 @@ export function HostPage({.setPaused(nativeShareGeneration, nextPaused).then(() => {if (!isCurrentGeneration(generation)) return;- if (signalRef.current?.setSharingPaused(nextPaused) !== true) {- void nativeClient.setPaused(nativeShareGeneration, !nextPaused);- setNoticeKey("host.pause.signalRecovering");+ const sent = signalRef.current?.setSharingPaused(nextPaused) === true;+ if (!sent && !nextPaused) {+ // Mirror the Browser branch: a resume the server did not hear+ // rolls back to paused and restores the wire intent.+ void nativeClient.setPaused(nativeShareGeneration, true);+ signalRef.current?.confirmSharingPaused();+ setNoticeErrorKey("host.pause.signalRecovering");return;}if (activeStream) {@@ -1747,7 +1757,11 @@ export function HostPage({hostSfuRouteRef.current?.setPaused(nextPaused);sharingPausedRef.current = nextPaused;setSharingPaused(nextPaused);- setNoticeKey(nextPaused ? "host.pauseNotice" : "host.resumeNotice");+ if (!sent) {+ setNoticeErrorKey("host.pause.signalRecovering");+ } else {+ setNoticeKey(nextPaused ? "host.pauseNotice" : "host.resumeNotice");+ }}).catch((error: unknown) => {if (isCurrentGeneration(generation)) {@@ -1761,7 +1775,7 @@ export function HostPage({}if (sharingPausedRef.current) {if (!setMediaPaused(activeStream, false)) {- setNoticeKey("host.pause.noTracksResume");+ setNoticeErrorKey("host.pause.noTracksResume");return;}nativeMediaIngressRef.current?.setPaused(false);@@ -1775,7 +1789,7 @@ export function HostPage({hostProvisionalChildRef.current?.setPaused(true);hostSfuRouteRef.current?.setPaused(true);signalRef.current?.confirmSharingPaused();- setNoticeKey("host.pause.signalRecovering");+ setNoticeErrorKey("host.pause.signalRecovering");return;}sharingPausedRef.current = false;@@ -1784,7 +1798,7 @@ export function HostPage({return;}if (!setMediaPaused(activeStream, true)) {- setNoticeKey("host.pause.noTracksPause");+ setNoticeErrorKey("host.pause.noTracksPause");return;}nativeMediaIngressRef.current?.setPaused(true);@@ -1797,7 +1811,7 @@ export function HostPage({if (signalRef.current?.setSharingPaused(true) === true) {setNoticeKey("host.pauseNotice");} else {- setNoticeKey("host.pause.signalRecovering");+ setNoticeErrorKey("host.pause.signalRecovering");}}@@ -1963,7 +1977,6 @@ export function HostPage({async function startPeer(peerId: string,generation: number,- attempt = 0,): Promise<void> {if (!isCurrentGeneration(generation) || !hostChildIsAssigned(peerId)) {return;@@ -2052,31 +2065,8 @@ export function HostPage({}const connectionId = peer.connectionId;- if (peerAssistedRef.current || attempt >= 1) {- reportHostChildFailure(peerId, connectionId, generation);- removePeer(peerId);- return;- }+ reportHostChildFailure(peerId, connectionId, generation);removePeer(peerId);- window.setTimeout(() => {- if (- isCurrentGeneration(generation) &&- !peerAssistedRef.current &&- hostChildIsAssigned(peerId) &&- !peersRef.current.has(peerId)- ) {- void startPeer(peerId, generation, attempt + 1).catch(- (error: unknown) => {- if (- isCurrentGeneration(generation) &&- hostChildIsAssigned(peerId)- ) {- setNoticeError(error, "connection");- }- },- );- }- }, 500);}async function recoverPeer(@@ -2148,7 +2138,6 @@ export function HostPage({): boolean {return Boolean(isCurrentGeneration(generation) &&- peerAssistedRef.current &&hostChildIsAssigned(peerId) &&signalRef.current?.send({type: "route-failed",@@ -2199,49 +2188,38 @@ export function HostPage({message.codeEntryPolicy,),);- if (- "mediaMode" in message &&- message.mediaMode === "peer-assisted"- ) {- const currentQualitySettings =- pendingQualitySettings ?? message.qualitySettings;- activeRouteRevisionRef.current = message.routeRevision;- peerAssistedRef.current = true;- if (reauthenticated) {- commitQuality(currentQualitySettings);- const endpointUpdates = [- ...[...peersRef.current.values()].map((peer) =>- peer.updateProfile(currentQualitySettings),- ),- ...(hostProvisionalChildRef.current- ? [- hostProvisionalChildRef.current.updateProfile(- currentQualitySettings,- ),- ]- : []),- ];- void Promise.allSettled(endpointUpdates);- }- const route = ensureHostSfuRoute(generation);- void route- .resyncAuthoritative({- revision: message.routeRevision,- phase: "active",- assignment: message.routeAssignment,- })- .then(async () => {- if (reauthenticated && hostSfuRouteRef.current === route) {- await route.updateProfile(currentQualitySettings);- }- syncHostSfuQualityWarning(route, generation);- });- return;+ const currentQualitySettings =+ pendingQualitySettings ?? message.qualitySettings;+ activeRouteRevisionRef.current = message.routeRevision;+ if (reauthenticated) {+ commitQuality(currentQualitySettings);+ const endpointUpdates = [+ ...[...peersRef.current.values()].map((peer) =>+ peer.updateProfile(currentQualitySettings),+ ),+ ...(hostProvisionalChildRef.current+ ? [+ hostProvisionalChildRef.current.updateProfile(+ currentQualitySettings,+ ),+ ]+ : []),+ ];+ void Promise.allSettled(endpointUpdates);}- activeRouteRevisionRef.current = 0;- peerAssistedRef.current = false;- clearHostSfuRoute();- reconcileHostChildren(message.viewerPeerIds, generation);+ const route = ensureHostSfuRoute(generation);+ void route+ .resyncAuthoritative({+ revision: message.routeRevision,+ phase: "active",+ assignment: message.routeAssignment,+ })+ .then(async () => {+ if (reauthenticated && hostSfuRouteRef.current === route) {+ await route.updateProfile(currentQualitySettings);+ }+ syncHostSfuQualityWarning(route, generation);+ });return;}if (message.type === "viewer-presence") {@@ -2271,36 +2249,34 @@ export function HostPage({sharingPausedRef.current = true;setSharingPaused(true);signalRef.current?.confirmSharingPaused();- setNoticeKey("host.pause.stillPaused");+ setNoticeErrorKey("host.pause.stillPaused");return;}if (message.type === "route-update") {- if (peerAssistedRef.current) {- const route = ensureHostSfuRoute(generation);- const accepted = route.accept(message);- if (accepted === "stale") return;- if (message.phase === "prepare") {- if (message.candidate.transport === "direct") {- prepareHostChild(- message.revision,- message.assignment,- message.candidate,- generation,- );- } else {- discardPreparedHostChild();- }+ const route = ensureHostSfuRoute(generation);+ const accepted = route.accept(message);+ if (accepted === "stale") return;+ if (message.phase === "prepare") {+ if (message.candidate.transport === "direct") {+ prepareHostChild(+ message.revision,+ message.assignment,+ message.candidate,+ generation,+ );} else {- activatePreparedHostChild(message.revision, message.assignment);- }- if (- message.phase === "active" &&- message.revision !== activeRouteRevisionRef.current- ) {- activeRouteRevisionRef.current = message.revision;+ discardPreparedHostChild();}- syncHostSfuQualityWarning(route, generation);+ } else {+ activatePreparedHostChild(message.revision, message.assignment);}+ if (+ message.phase === "active" &&+ message.revision !== activeRouteRevisionRef.current+ ) {+ activeRouteRevisionRef.current = message.revision;+ }+ syncHostSfuQualityWarning(route, generation);return;}if (message.type === "viewer-quality-evidence") {@@ -2308,45 +2284,10 @@ export function HostPage({return;}if (message.type === "sfu-config") {- if (peerAssistedRef.current) {- const route = ensureHostSfuRoute(generation);- void route- .acceptConfig(message)- .then(() => syncHostSfuQualityWarning(route, generation));- }- return;- }- if (message.type === "peer-joined") {- if (peerAssistedRef.current) {- return;- }- reconcileHostChildren(- [...activeHostChildPeerIdsRef.current, message.peerId],- generation,- );- return;- }- if (message.type === "peer-waiting") {- if (!peerAssistedRef.current) {- reconcileHostChildren(- activeHostChildPeerIdsRef.current.filter(- (peerId) => peerId !== message.peerId,- ),- generation,- );- }- return;- }- if (message.type === "peer-left") {- if (peerAssistedRef.current) {- return;- }- reconcileHostChildren(- activeHostChildPeerIdsRef.current.filter(- (peerId) => peerId !== message.peerId,- ),- generation,- );+ const route = ensureHostSfuRoute(generation);+ void route+ .acceptConfig(message)+ .then(() => syncHostSfuQualityWarning(route, generation));return;}if (message.type === "signal") {@@ -2381,6 +2322,7 @@ export function HostPage({endSharing(message.reason === "expired" ? say("host.roomExpired") : say("host.roomClosed"),false,+ "warning",);return;}@@ -2389,14 +2331,14 @@ export function HostPage({if (!forgetRoom(activeRoom)) {return;}- endSharing({ key: "host.roomInvalid" }, false);+ endSharing({ key: "host.roomInvalid" }, false, "warning");return;}if (message.code === "AUTH_REQUIRED") {return;}if (message.code === "HOST_ALREADY_CONNECTED") {- endSharing(hostServerErrorNotice(message.code), false);+ endSharing(hostServerErrorNotice(message.code), false, "warning");return;}setNotice(hostServerErrorNotice(message.code), "warning");@@ -2513,7 +2455,7 @@ export function HostPage({let authenticated = false;const hostClientId = getStableClientId("host", activeRoom.roomId);hostClientIdRef.current = hostClientId;- const hostFallback = defaultHostDisplayName(hostClientId, vis);+ const hostFallback = defaultHostDisplayName(hostClientId, visRef.current);const initialDisplayName = readDisplayName(hostFallback);displayNameRef.current = initialDisplayName;setDisplayName(initialDisplayName);@@ -2546,7 +2488,7 @@ export function HostPage({isCurrentShare(generation, shareGeneration) &&signalRef.current === signal) {- endSharing({ key: hostTerminationKey(reason) }, false);+ endSharing({ key: hostTerminationKey(reason) }, false, "warning");}},onAccessRequired: () => {@@ -2554,7 +2496,7 @@ export function HostPage({isCurrentShare(generation, shareGeneration) &&signalRef.current === signal) {- endSharing({ key: "gate.expired" }, false);+ endSharing({ key: "gate.expired" }, false, "warning");onAuthorizationRequired?.();}},@@ -2953,11 +2895,17 @@ export function HostPage({try {await navigator.clipboard.writeText(inviteUrl);setCopied(true);- window.setTimeout(() => {+ // One owner for the confirmation window: a second copy restarts it+ // instead of inheriting the first click's expiry.+ if (copiedResetTimerRef.current !== null) {+ window.clearTimeout(copiedResetTimerRef.current);+ }+ copiedResetTimerRef.current = window.setTimeout(() => {+ copiedResetTimerRef.current = null;setCopied(false);}, 1_500);} catch {- setNoticeKey("host.invite.copyFailed");+ setNoticeErrorKey("host.invite.copyFailed");}}@@ -3083,7 +3031,7 @@ export function HostPage({password !== null &&!viewerPasswordSchema.safeParse(password).success) {- setNoticeKey("host.password.rule", {+ setNoticeErrorKey("host.password.rule", "warning", {max: String(MAX_VIEWER_PASSWORD_LENGTH),});return;@@ -3151,7 +3099,7 @@ export function HostPage({setEditingDisplayName(false);setHasCustomDisplayName(readStoredDisplayName() !== null);if (!signalRef.current?.setDisplayName(saved)) {- setNoticeKey("host.nameOffline");+ setNoticeErrorKey("host.nameOffline");}}@@ -3167,6 +3115,9 @@ export function HostPage({const activeCodeEntryPolicy = room?.codeEntryPolicy ?? null;const hostPeerId = hostPresence?.peerId ?? hostPeerIdRef.current;+ // One identity for the Host body everywhere (couch, name tag, topology) so+ // the pawn is not recoloured per surface while the peer id is still pending.+ const hostIdentity = hostPeerId ?? hostClientIdRef.current ?? "host-pending";const couchEntries: CouchEntry[] = viewers.map((viewer) => {const snapshot =@@ -3292,7 +3243,7 @@ export function HostPage({}): phase === "starting"? `${t("host.starting")}…`- : phase === "ended" && room+ : phase === "ended"? t("host.ended"): room? t("host.roomReady")@@ -3409,7 +3360,7 @@ export function HostPage({<p>{t("host.idle.hint")}</p></div>)}- {phase === "ended" && room && !vis ? (+ {phase === "ended" && !vis ? (<span className="lr-tv-msg">{t("host.ended")}</span>) : null}<div className="lr-entry-actions">@@ -3525,7 +3476,9 @@ export function HostPage({) : null}</div>) : null}- {switchingSource ? (+ {/* The picker owns the stage while it is open: a state overlay+ painted after it would cover and swallow its controls. */}+ {nativeSources ? null : switchingSource ? (<StageOverlayicon="refresh"spin@@ -3556,8 +3509,8 @@ export function HostPage({<div className="lr-shelf" aria-hidden="true" /><Couchhost={{- key: hostPeerId ?? hostClientIdRef.current ?? "host-local",- name: hostPresence?.displayName ?? displayName,+ key: hostIdentity,+ name: labeledHostPresence?.label ?? displayName,you: true,selected:hostDiagnosticsAvailable &&@@ -3692,10 +3645,8 @@ export function HostPage({) : (<><NameTag- name={hostPresence?.displayName ?? displayName}- identity={- hostPeerId ?? hostClientIdRef.current ?? "host-pending"- }+ name={labeledHostPresence?.label ?? displayName}+ identity={hostIdentity}/>{hintWrap("hint-rename",@@ -3954,6 +3905,7 @@ export function HostPage({<Row sub><RouteTreehostPeerId={hostPeerId}+ hostIdentity={hostIdentity}hostLabel={labeledHostPresence?.label ?? displayName}viewers={viewers}selectedPeerId={selectedPawn}diff --git a/src/client/pages/JoinPage.tsx b/src/client/pages/JoinPage.tsxindex 67a45cad..2db6b6a4 100644--- a/src/client/pages/JoinPage.tsx+++ b/src/client/pages/JoinPage.tsx@@ -8,13 +8,16 @@ import { roomRouteForExplicitEntry } from "../lib/session";export function JoinPage() {const { t, vis } = useCopy();const [roomId, setRoomId] = useState("");- const [error, setError] = useState(false);+ // Counts rejected submits so a repeated one still restarts the shake and+ // re-announces the alert; a plain boolean would already be true.+ const [rejectedAttempt, setRejectedAttempt] = useState(0);+ const error = rejectedAttempt > 0;function join(event: FormEvent<HTMLFormElement>): void {event.preventDefault();const route = roomRouteForExplicitEntry(roomId);if (!route) {- setError(true);+ setRejectedAttempt((attempt) => attempt + 1);return;}window.location.assign(route);@@ -38,6 +41,7 @@ export function JoinPage() {<main className="lr-join"><form className="lr-join-panel" onSubmit={join} noValidate><span+ key={rejectedAttempt}className={`lr-join-door${error ? " is-shake" : ""}`}title={vis ? undefined : t("join.title")}role="img"@@ -72,13 +76,18 @@ export function JoinPage() {aria-invalid={error}onChange={(event) => {setRoomId(event.target.value.replace(/\D/g, "").slice(0, 4));- setError(false);+ setRejectedAttempt(0);}}/></div>{error ? (<>- <span className="lr-join-error" role="alert" aria-label={t("join.invalid")}>+ <span+ key={rejectedAttempt}+ className="lr-join-error"+ role="alert"+ aria-label={t("join.invalid")}+ ><Glyph name="x" size={24} /></span>{vis ? (diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsxindex 977b36be..0d34531a 100644--- a/src/client/pages/ViewerPage.tsx+++ b/src/client/pages/ViewerPage.tsx@@ -24,7 +24,8 @@ import {viewerRouteEvidence,} from "../components/status-badge-model";import { AppHeader, LedStrip, type LedState } from "../components/living/Header";-import { Couch, type CouchEntry } from "../components/living/Couch";+import { Couch, PawnSvg, type CouchEntry } from "../components/living/Couch";+import { participantColor } from "../components/living/participant-color";import { MetricCells, useMetricsExpanded } from "../components/living/Metrics";import { PawnDetail, RouteGlyph } from "../components/living/PawnDetail";import { Lcd } from "../components/living/RoomChip";@@ -72,6 +73,7 @@ import {senderQualityEvidenceFromSnapshot,} from "../media/sender-quality-evidence";import {+ freshViewerQualityEvidence,metricsFromQualityEvidence,nextViewerQualityEvidencePresentationExpiryAt,presentViewerQualityEvidence,@@ -303,8 +305,9 @@ export function ViewerPage({connectionAttempt?: PreparedRouteCandidate["connectionAttempt"];} | null>(null);const [relaySnapshot, setRelaySnapshot] = useState<PeerSnapshot | null>(null);- const [relayChildEvidence, setRelayChildEvidence] =- useState<ViewerQualityEvidencePresentation | null>(null);+ const [relayChildEvidence, setRelayChildEvidence] = useState<+ Map<string, ViewerQualityEvidencePresentation>+ >(() => new Map());const [showConnectionDetails, setShowConnectionDetails] = useState(false);const [showTopology, setShowTopology] = useState(false);const [theaterMode, setTheaterMode] = useState(false);@@ -425,7 +428,7 @@ export function ViewerPage({displayNameRef.current = fallback;setDisplayName(fallback);if (!editingDisplayName) setDisplayNameDraft(fallback);- signalRef.current?.setViewerDisplayName(fallback);+ signalRef.current?.setDisplayName(fallback);}, [hasCustomDisplayName, lang, vis, viewerClientId]);const remoteMediaRef = useRef<RemoteMediaBinding | null>(null);const mediaGenerationRef = useRef(0);@@ -573,9 +576,10 @@ export function ViewerPage({upstream: ParticipantRouteAssignment["upstream"],phase: "prepare" | "active" = "active",connectionAttempt?: PreparedRouteCandidate["connectionAttempt"],+ authoritative = false,): void {setAssignedRoute((current) =>- current && revision < current.revision+ !authoritative && current && revision < current.revision? current: { revision, phase, upstream, connectionAttempt },);@@ -584,6 +588,7 @@ export function ViewerPage({revision,phase,kind: routeKindFromAssignment(upstream),+ authoritative,});}@@ -592,7 +597,6 @@ export function ViewerPage({let currentIceConfig: IceConfig | null = null;let currentHostOnline = false;let currentHostPaused = false;- let peerAssisted = false;let currentPeerId: string | null = null;let currentRouteRevision = 0;let currentRouteAssignment: ParticipantRouteAssignment | null = null;@@ -622,9 +626,11 @@ export function ViewerPage({const decodedFrameStall = new DecodedFrameStallDetector();const messageAuthority = new ViewerMessageAuthority();let sfuStandbyPrewarmer: SfuStandbyPrewarmer | null = null;- let relayChildEvidenceCurrent: ViewerQualityEvidencePresentation | null =- null;- let relayChildEvidenceTimer: number | null = null;+ const relayChildEvidenceCurrent = new Map<+ string,+ ViewerQualityEvidencePresentation+ >();+ const relayChildEvidenceTimers = new Map<string, number>();let sfuTransportConnected = false;let nativeClientPromise: Promise<NativeClient | null> | null = null;const nativeViewerSessionId = createOpaqueId();@@ -649,7 +655,7 @@ export function ViewerPage({options,acquireNativeClient(),nativeViewerSessionId,- endpointMediaCopyCapacity,+ MAX_ENDPOINT_MEDIA_CHILDREN,);}@@ -835,16 +841,22 @@ export function ViewerPage({}function commitRelayChildEvidence(+ peerId: string,presentation: ViewerQualityEvidencePresentation | null,): void {- if (relayChildEvidenceTimer !== null) {- window.clearTimeout(relayChildEvidenceTimer);- relayChildEvidenceTimer = null;+ const timer = relayChildEvidenceTimers.get(peerId);+ if (timer !== undefined) {+ window.clearTimeout(timer);+ relayChildEvidenceTimers.delete(peerId);+ }+ const current = relayChildEvidenceCurrent.get(peerId) ?? null;+ if (presentation === null) {+ relayChildEvidenceCurrent.delete(peerId);+ } else {+ relayChildEvidenceCurrent.set(peerId, presentation);}- const current = relayChildEvidenceCurrent;- relayChildEvidenceCurrent = presentation;if (current !== presentation) {- setRelayChildEvidence(presentation);+ setRelayChildEvidence(new Map(relayChildEvidenceCurrent));}if (presentation === null) {return;@@ -859,25 +871,31 @@ export function ViewerPage({return;}const expected = presentation;- relayChildEvidenceTimer = window.setTimeout(() => {- if (relayChildEvidenceCurrent !== expected) {- return;- }- commitRelayChildEvidence(- refreshViewerQualityEvidencePresentation(expected),- );- }, Math.max(0, expiryAt - nowMs));+ relayChildEvidenceTimers.set(+ peerId,+ window.setTimeout(() => {+ relayChildEvidenceTimers.delete(peerId);+ if (relayChildEvidenceCurrent.get(peerId) !== expected) {+ return;+ }+ commitRelayChildEvidence(+ peerId,+ refreshViewerQualityEvidencePresentation(expected),+ );+ }, Math.max(0, expiryAt - nowMs)),+ );}function clearRelayChildEvidence(): void {- commitRelayChildEvidence(null);+ for (const peerId of [...relayChildEvidenceCurrent.keys()]) {+ commitRelayChildEvidence(peerId, null);+ }}function acceptRelayChildEvidence(evidence: ViewerQualityEvidence): void {const relaySnapshot =viewerRelay?.getSnapshot(evidence.viewerPeerId) ?? null;if (- !peerAssisted ||evidence.upstream.kind !== "peer" ||evidence.upstream.peerId !== currentPeerId ||evidence.guard.routeRevision !== currentRouteRevision ||@@ -886,8 +904,9 @@ export function ViewerPage({return;}commitRelayChildEvidence(+ evidence.viewerPeerId,presentViewerQualityEvidence(- relayChildEvidenceCurrent,+ relayChildEvidenceCurrent.get(evidence.viewerPeerId) ?? null,evidence,),);@@ -896,7 +915,7 @@ export function ViewerPage({function ensureViewerRelay(upstreamKind = currentRouteAssignment?.upstream.kind,): ViewerRelay | null {- if (!peerAssisted || !currentIceConfig) {+ if (!currentIceConfig) {return null;}const source =@@ -961,7 +980,7 @@ export function ViewerPage({currentQualitySettings,{sendSignal: (targetPeerId, payload) =>- active && peerAssisted+ active? signal.send({type: "signal",targetPeerId,@@ -971,16 +990,16 @@ export function ViewerPage({onUpdate: (snapshot) => {if (active) {setRelaySnapshot(snapshot);- if (relayChildEvidenceCurrent) {+ for (const [peerId, presentation] of [+ ...relayChildEvidenceCurrent,+ ]) {const reconciled =reconcileViewerQualityEvidencePresentation(- relayChildEvidenceCurrent,- viewerRelay?.getSnapshot(- relayChildEvidenceCurrent.evidence.viewerPeerId,- ) ?? null,+ presentation,+ viewerRelay?.getSnapshot(peerId) ?? null,);- if (reconciled !== relayChildEvidenceCurrent) {- commitRelayChildEvidence(reconciled);+ if (reconciled !== presentation) {+ commitRelayChildEvidence(peerId, reconciled);}}}@@ -1069,7 +1088,6 @@ export function ViewerPage({connectionId?: string,): void {if (- !peerAssisted ||currentHostPaused ||!decodedFrameStall.observe(`${route}:${identity}`, framesDecodedDelta)) {@@ -1409,7 +1427,6 @@ export function ViewerPage({): Promise<void> {while (active &&- peerAssisted &&preparedParentPeerId === parentPeerId) {const message = preparedParentSignals.shift();@@ -1472,9 +1489,8 @@ export function ViewerPage({currentIceConfig,{sendSignal: (targetPeerId, payload) =>- signal.send(viewerSignalMessage(peerAssisted, targetPeerId, payload)),+ signal.send(viewerSignalMessage(targetPeerId, payload)),sendRestartRequest: createOwnedViewerRestartSender(- peerAssisted,(targetPeerId, connectionId) => {const identity = peer.getConnectionIdentity();return (@@ -1603,11 +1619,8 @@ export function ViewerPage({currentIceConfig,{sendSignal: (targetPeerId, payload) =>- signal.send(- viewerSignalMessage(peerAssisted, targetPeerId, payload),- ),+ signal.send(viewerSignalMessage(targetPeerId, payload)),sendRestartRequest: createOwnedViewerRestartSender(- peerAssisted,(targetPeerId, connectionId) => {const identity = peer.getConnectionIdentity();return (@@ -1706,51 +1719,24 @@ export function ViewerPage({setSfuStandbyUrl("sfuStandbyUrl" in message ? message.sfuStandbyUrl : null,);- const nextPeerAssisted =- "mediaMode" in message && message.mediaMode === "peer-assisted";- if (!nextPeerAssisted && peerAssisted) {- clearViewerSfuRoute();- clearPeerState();- viewerRelay?.dispose();- viewerRelay = null;- viewerRelaySourceKey = null;- currentAssignment = { parentPeerId: null, childPeerIds: [] };- }- peerAssisted = nextPeerAssisted;- const nextRouteRevision =- nextPeerAssisted && "routeRevision" in message- ? message.routeRevision- : 0;+ const nextRouteRevision = message.routeRevision;if (nextRouteRevision !== currentRouteRevision) {clearRelayChildEvidence();}currentRouteRevision = nextRouteRevision;- if (nextPeerAssisted && "routeAssignment" in message) {- activateRouteIdentity(- message.routeRevision,- message.routeAssignment,- message.connectionId,- );- acceptAssignedRoute(- message.routeRevision,- message.routeAssignment.upstream,- );- } else {- currentRouteAssignment = null;- currentRouteConnectionId = null;- pendingRouteConnection = null;- setAssignedRoute(null);- dispatchPresentation({- type: "route",- revision: 0,- phase: "active",- kind: message.hostOnline ? "p2p" : "none",- });- }- const relayCapacity = relayCapacityMessageForBrowser(nextPeerAssisted);- if (relayCapacity) {- signal.send(relayCapacity);- }+ activateRouteIdentity(+ message.routeRevision,+ message.routeAssignment,+ message.connectionId,+ );+ acceptAssignedRoute(+ message.routeRevision,+ message.routeAssignment.upstream,+ "active",+ undefined,+ true,+ );+ signal.send(relayCapacityMessageForBrowser());currentIceConfig = message.iceConfig;currentHostOnline = message.hostOnline;const sharingPaused = message.hostPaused ?? false;@@ -1767,23 +1753,21 @@ export function ViewerPage({? "online": "stopped",});- if (nextPeerAssisted && "qualitySettings" in message) {- currentQualitySettings = message.qualitySettings;- currentShareGeneration = message.shareGeneration;- void viewerRelay?.updateProfile(currentQualitySettings);- const route = ensureViewerSfuRoute();- route.setPaused(sharingPaused);- await route.resyncAuthoritative(- {- revision: message.routeRevision,- phase: "active",- assignment: message.routeAssignment,- },- message.peerId,- );- if (!active || !messageAuthority.owns(authorityToken)) {- return;- }+ currentQualitySettings = message.qualitySettings;+ currentShareGeneration = message.shareGeneration;+ void viewerRelay?.updateProfile(currentQualitySettings);+ const route = ensureViewerSfuRoute();+ route.setPaused(sharingPaused);+ await route.resyncAuthoritative(+ {+ revision: message.routeRevision,+ phase: "active",+ assignment: message.routeAssignment,+ },+ message.peerId,+ );+ if (!active || !messageAuthority.owns(authorityToken)) {+ return;}if (!message.hostOnline &&@@ -1800,13 +1784,7 @@ export function ViewerPage({!peer?.hasConnectionId(message.connectionId)) {const parentPeerId = currentAssignment.parentPeerId;- if (!peerAssisted) {- signal.send({- type: "restart-request",- connectionId: message.connectionId,- rebuild: true,- });- } else if (parentPeerId) {+ if (parentPeerId) {signal.send({type: "restart-request",targetPeerId: parentPeerId,@@ -1820,61 +1798,59 @@ export function ViewerPage({return;}if (message.type === "route-update") {- if (peerAssisted) {- const result = ensureViewerSfuRoute().accept(message);- if (result !== "stale") {- if (- result === "accepted" &&- message.phase === "prepare" &&- message.candidate.childPeerId === currentPeerId- ) {- pendingRouteConnection = {- revision: message.revision,- connectionId: message.candidate.connectionId,- };- if (remoteMediaRef.current === null) {- acceptAssignedRoute(- message.revision,- message.assignment.upstream,- "prepare",- message.candidate.connectionAttempt,- );- }- }- if (message.phase === "active") {- const samePeerUpstream =- currentRouteAssignment?.upstream.kind === "peer" &&- message.assignment.upstream.kind === "peer" &&- currentRouteAssignment.upstream.peerId ===- message.assignment.upstream.peerId;- const sameSfuUpstream =- currentRouteAssignment?.upstream.kind === "sfu" &&- message.assignment.upstream.kind === "sfu" &&- currentRouteAssignment.sfuPublicationGeneration ===- message.assignment.sfuPublicationGeneration;- const connectionId =- pendingRouteConnection?.revision === message.revision- ? pendingRouteConnection.connectionId- : samePeerUpstream || sameSfuUpstream- ? currentRouteConnectionId- : null;- if (result === "accepted") {- if (message.revision !== currentRouteRevision) {- clearRelayChildEvidence();- }- activateRouteIdentity(- message.revision,- message.assignment,- connectionId,- );- }+ const result = ensureViewerSfuRoute().accept(message);+ if (result !== "stale") {+ if (+ result === "accepted" &&+ message.phase === "prepare" &&+ message.candidate.childPeerId === currentPeerId+ ) {+ pendingRouteConnection = {+ revision: message.revision,+ connectionId: message.candidate.connectionId,+ };+ if (remoteMediaRef.current === null) {acceptAssignedRoute(message.revision,message.assignment.upstream,- "active",+ "prepare",+ message.candidate.connectionAttempt,);}}+ if (message.phase === "active") {+ const samePeerUpstream =+ currentRouteAssignment?.upstream.kind === "peer" &&+ message.assignment.upstream.kind === "peer" &&+ currentRouteAssignment.upstream.peerId ===+ message.assignment.upstream.peerId;+ const sameSfuUpstream =+ currentRouteAssignment?.upstream.kind === "sfu" &&+ message.assignment.upstream.kind === "sfu" &&+ currentRouteAssignment.sfuPublicationGeneration ===+ message.assignment.sfuPublicationGeneration;+ const connectionId =+ pendingRouteConnection?.revision === message.revision+ ? pendingRouteConnection.connectionId+ : samePeerUpstream || sameSfuUpstream+ ? currentRouteConnectionId+ : null;+ if (result === "accepted") {+ if (message.revision !== currentRouteRevision) {+ clearRelayChildEvidence();+ }+ activateRouteIdentity(+ message.revision,+ message.assignment,+ connectionId,+ );+ }+ acceptAssignedRoute(+ message.revision,+ message.assignment.upstream,+ "active",+ );+ }}return;}@@ -1894,16 +1870,12 @@ export function ViewerPage({return;}if (message.type === "sfu-config") {- if (peerAssisted) {- await ensureViewerSfuRoute().acceptConfig(message);- }+ await ensureViewerSfuRoute().acceptConfig(message);return;}if (message.type === "quality-settings") {- if (peerAssisted) {- currentQualitySettings = message.qualitySettings;- void viewerRelay?.updateProfile(currentQualitySettings);- }+ currentQualitySettings = message.qualitySettings;+ void viewerRelay?.updateProfile(currentQualitySettings);return;}if (message.type === "route-policy") {@@ -1918,7 +1890,7 @@ export function ViewerPage({return;}if (message.type === "signal") {- if (peerAssisted && pendingPeer?.parentPeerId === message.fromPeerId) {+ if (pendingPeer?.parentPeerId === message.fromPeerId) {if (currentAssignment.parentPeerId !== message.fromPeerId) {await ensurePendingPeerRoute()?.acceptSignal(message.fromPeerId,@@ -1947,15 +1919,11 @@ export function ViewerPage({}return;}- if (- peerAssisted &&- preparedParentPeerId === message.fromPeerId- ) {+ if (preparedParentPeerId === message.fromPeerId) {preparedParentSignals.push(message);return;}if (- peerAssisted &&viewerRelay &&(await viewerRelay.acceptSignal(message.fromPeerId,@@ -1969,10 +1937,7 @@ export function ViewerPage({) {return;}- if (- peerAssisted &&- currentAssignment.parentPeerId !== message.fromPeerId- ) {+ if (currentAssignment.parentPeerId !== message.fromPeerId) {return;}const peer = ensurePeer();@@ -1983,13 +1948,11 @@ export function ViewerPage({return;}if (message.type === "restart-request") {- if (peerAssisted) {- await viewerRelay?.recover(- message.fromPeerId,- message.connectionId,- message.rebuild,- );- }+ await viewerRelay?.recover(+ message.fromPeerId,+ message.connectionId,+ message.rebuild,+ );return;}if (message.type === "host-status") {@@ -2145,6 +2108,7 @@ export function ViewerPage({viewerSfuRoute = null;preparedParentPeerId = null;preparedParentSignals = [];+ discardPendingPeer();peerRef.current?.dispose();peerRef.current = null;viewerRelay?.dispose();@@ -2266,7 +2230,7 @@ export function ViewerPage({setDisplayNameError(false);setEditingDisplayName(false);setHasCustomDisplayName(readStoredDisplayName() !== null);- signalRef.current?.setViewerDisplayName(saved);+ signalRef.current?.setDisplayName(saved);}function submitViewerPassword(event: React.FormEvent<HTMLFormElement>): void {@@ -2291,12 +2255,17 @@ export function ViewerPage({const failureCode = presentation.failureCode;const codeOnlyDenied =!viewerGrant && failureCode === "ROOM_ACCESS_DENIED";- const canRefresh = [- "STALE_CLIENT",- "SERVER_ERROR",- "SESSION_REPLACED",- "SIGNAL_TERMINATED",- ].includes(failureCode ?? "");+ const canRefresh =+ failureCode === null ||+ // ROOM_FULL is transient by nature: a seat frees when a Viewer leaves,+ // so the hint that says "try again" needs something to try.+ [+ "ROOM_FULL",+ "STALE_CLIENT",+ "SERVER_ERROR",+ "SESSION_REPLACED",+ "SIGNAL_TERMINATED",+ ].includes(failureCode);const deniedComic: ComicKind =failureCode === "ROOM_FULL"? "room-full"@@ -2325,7 +2294,10 @@ export function ViewerPage({failureCode === "ROOM_EXPIRED" ||failureCode === "ROOM_CLOSED"? "viewer.hint.notFound"- : failureCode === "INVALID_TOKEN"+ : failureCode === "INVALID_TOKEN" ||+ // A grant that the room no longer accepts is not a retry case:+ // the recovery is a new invite, not another attempt.+ failureCode === "ROOM_ACCESS_DENIED"? "viewer.hint.invite": "viewer.hint.generic";return (@@ -2483,11 +2455,22 @@ export function ViewerPage({? viewerNoticeVisual(presentation.noticeKey): null;const selectedChildEvidence =- selectedPawn !== null &&- selectedPawn !== selfPeerId &&- relayChildEvidence?.evidence.viewerPeerId === selectedPawn- ? relayChildEvidence+ selectedPawn !== null && selectedPawn !== selfPeerId+ ? freshViewerQualityEvidence(relayChildEvidence.get(selectedPawn)): null;+ // Downstream rows describe one named child each; expired evidence stops+ // rendering instead of freezing the last numbers on screen.+ const freshRelayChildEvidence = viewers+ .map((viewer) => ({+ viewer,+ evidence: freshViewerQualityEvidence(+ relayChildEvidence.get(viewer.peerId),+ ),+ }))+ .filter(+ (entry): entry is { viewer: typeof entry.viewer; evidence: ViewerQualityEvidence } =>+ entry.evidence !== null,+ );const couchEntries: CouchEntry[] = viewers.map((viewer) => {const isSelf = selfPeerId !== null && viewer.peerId === selfPeerId;const isChild =@@ -2837,7 +2820,7 @@ export function ViewerPage({disabled={!routePresentation.route &&!relaySnapshot &&- !relayChildEvidence+ freshRelayChildEvidence.length === 0}onClick={() =>setShowConnectionDetails((current) => !current)@@ -2896,17 +2879,23 @@ export function ViewerPage({/></Row>) : null}- {showConnectionDetails && relayChildEvidence ? (- <Row sub>- <MeterTag icon="arrowUp" label={t("stats.downstream")} />- <MetricCells- metrics={metricsFromQualityEvidence(relayChildEvidence.evidence)}- direction="receive"- expanded={downstreamMetricsExpanded}- onToggle={setDownstreamMetricsExpanded}- />- </Row>- ) : null}+ {showConnectionDetails+ ? freshRelayChildEvidence.map(({ viewer, evidence }) => (+ <Row sub key={viewer.peerId} label={viewer.label}>+ <MeterTag icon="arrowUp" label={t("stats.downstream")} />+ <span className="lr-pawn-mini">+ <PawnSvg color={participantColor(viewer.peerId)} />+ </span>+ <span className="lr-pawn-detail-name">{viewer.label}</span>+ <MetricCells+ metrics={metricsFromQualityEvidence(evidence)}+ direction="receive"+ expanded={downstreamMetricsExpanded}+ onToggle={setDownstreamMetricsExpanded}+ />+ </Row>+ ))+ : null}{selectedPawn !== null && selectedChildEvidence ? (<PawnDetailpawnKey={selectedPawn}@@ -2915,7 +2904,7 @@ export function ViewerPage({?.label ?? selectedPawn}route={null}- metrics={metricsFromQualityEvidence(selectedChildEvidence.evidence)}+ metrics={metricsFromQualityEvidence(selectedChildEvidence)}direction="receive"tag={{ icon: "arrowUp", label: t("stats.downstream") }}expanded={pawnMetricsExpanded}diff --git a/src/client/styles.css b/src/client/styles.cssindex 4cba9de8..58eaeaa1 100644--- a/src/client/styles.css+++ b/src/client/styles.css@@ -452,6 +452,7 @@ body.lr-theater-open { overflow: hidden; }text-align: center;}.lr-tv-overlay.is-dim { background: rgba(10, 16, 28, .62); }+.lr-tv-overlay.is-passive { pointer-events: none; }.lr-tv-status-content { display: flex; flex-direction: column; align-items: center; gap: 14px; }.lr-tv-progress { display: inline-flex; align-items: center; gap: 6px; }.lr-overlay-preview { max-width: 1440px; }@@ -1033,6 +1034,9 @@ html[data-theme="dark"] .lr-viewer-host-slot svg { color: #9bb0c5; }user-select: text;}html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #33465c; }+/* Touch only: the compact mono URL would auto-zoom iOS on focus under 16px,+ and the zoom never returns. Pointer devices keep the dense line. */+@media (pointer: coarse) { .lr-invite-url { font-size: 16px; } }.lr-status-text {min-width: 0;overflow: hidden;@@ -1174,7 +1178,9 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334border: 0;border-radius: 11px;background: transparent;- color: #8aa0b2;+ /* 68% ink clears AA on both themes (light 4.89:1, dark 5.89:1) while the+ selected option keeps its stronger contrast. */+ color: color-mix(in srgb, var(--ink) 68%, var(--paper));transition: color 180ms ease;}.lr-toggle button.is-selected { color: var(--paper); }@@ -1248,7 +1254,7 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334transition: border-color 140ms ease;}.lr-input:focus-within { border-color: var(--action); outline: 3px solid var(--action); outline-offset: 2px; }-.lr-input input { min-width: 0; flex: 1; height: 100%; border: 0; outline: 0; background: transparent; font: inherit; }+.lr-input input { min-width: 0; flex: 1; height: 100%; border: 0; outline: 0; background: transparent; font: inherit; font-size: 16px; }.lr-input input[type="password"]:not(:placeholder-shown) { letter-spacing: .25em; }.lr-input.lr-name-editor {width: clamp(140px, 18vw, 200px);@@ -1628,7 +1634,9 @@ html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }.lr-client-access input {min-width: 0;}-.lr-client-launch-panel > .lr-comic-tip-wrap {+/* Only the wrapped access field spans the panel width; a wrapped pill or+ button keeps its own size so the grid can center it. */+.lr-client-launch-panel > .lr-comic-tip-wrap:has(> .lr-client-access) {width: min(460px, 100%);}.lr-client-launch-panel > .lr-comic-tip-wrap > .lr-client-access {@@ -1858,7 +1866,8 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }position: absolute;z-index: 3;left: 50%;- bottom: max(18px, env(safe-area-inset-bottom));+ /* Clear the native <video> control bar underneath (~48px tall). */+ bottom: max(64px, calc(env(safe-area-inset-bottom) + 48px));width: min(92vw, 720px);margin: 0;transform: translateX(-50%);diff --git a/src/client/ui/icons.tsx b/src/client/ui/icons.tsxindex 656a210d..49dac682 100644--- a/src/client/ui/icons.tsx+++ b/src/client/ui/icons.tsx@@ -19,7 +19,6 @@ const PATHS: Record<string, { body: ReactNode; solid?: boolean }> = {stop: { solid: true, body: (<><rect pathLength={1} x="6" y="6" width="12" height="12" rx="2"/></>) },share: { body: (<><rect pathLength={1} x="2" y="4" width="20" height="13" rx="2"/><path pathLength={1} d="M12 17v-7m0 0-3 3m3-3 3 3"/><path pathLength={1} d="M8 21h8"/></>) },switchSource: { body: (<><rect pathLength={1} x="2" y="4" width="20" height="14" rx="2"/><path pathLength={1} d="M7 9h9m0 0-2.5-2.5M16 9l-2.5 2.5M17 13H8m0 0 2.5-2.5M8 13l2.5 2.5"/><path pathLength={1} d="M8 22h8M12 18v4"/></>) },- hash: { body: (<><path pathLength={1} d="M9 3 7 21M17 3l-2 18M4 8h17M3 16h17"/></>) },users: { body: (<><circle pathLength={1} cx="9" cy="8" r="3.5"/><path pathLength={1} d="M2.5 20c.8-3.2 3.4-5 6.5-5s5.7 1.8 6.5 5"/><circle pathLength={1} cx="17" cy="9" r="2.5"/><path pathLength={1} d="M16.2 15.2c2.5.4 4.6 1.8 5.3 4.8"/></>) },network: { body: (<><rect pathLength={1} x="9" y="2" width="6" height="6" rx="1.5"/><rect pathLength={1} x="2" y="16" width="6" height="6" rx="1.5"/><rect pathLength={1} x="16" y="16" width="6" height="6" rx="1.5"/><path pathLength={1} d="M12 8v3.5M12 11.5 5.5 16M12 11.5l6.5 4.5"/></>) },chevron: { body: (<><path pathLength={1} d="m6 9 6 6 6-6"/></>) },@@ -53,9 +52,7 @@ const PATHS: Record<string, { body: ReactNode; solid?: boolean }> = {branch: { body: (<><circle pathLength={1} cx="6" cy="6" r="2.5"/><circle pathLength={1} cx="6" cy="18" r="2.5"/><circle pathLength={1} cx="18" cy="8" r="2.5"/><path pathLength={1} d="M6 8.5v7M6 13c5 0 5.5-2 9.3-3.2"/></>) },clock: { body: (<><circle pathLength={1} cx="12" cy="12" r="9"/><path pathLength={1} d="M12 7v5.2l3.4 2"/></>) },cpu: { body: (<><rect pathLength={1} x="7" y="7" width="10" height="10" rx="2"/><path pathLength={1} d="M10 2v3m4-3v3M10 19v3m4-3v3M2 10h3M2 14h3m14-4h3m-3 4h3"/></>) },- star: { body: (<><path pathLength={1} d="m12 3 2.7 5.7 6.3.8-4.6 4.3 1.2 6.2-5.6-3-5.6 3 1.2-6.2L3 9.5l6.3-.8L12 3Z"/></>) },zap: { body: (<><path pathLength={1} d="M13 2 4 14h6l-1 8 9-12h-6l1-8Z"/></>) },- sparkles: { body: (<><path pathLength={1} d="m12 4 1.6 4.4L18 10l-4.4 1.6L12 16l-1.6-4.4L6 10l4.4-1.6L12 4Z"/><path pathLength={1} d="m18.5 15.5.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8.8-2.2Z"/></>) },cast: { body: (<><path pathLength={1} d="M4 16a4 4 0 0 1 4 4M4 12a8 8 0 0 1 8 8"/><circle pathLength={1} cx="4" cy="20" r="1.2" fill="currentColor" stroke="none"/><path pathLength={1} d="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-5"/></>) },sun: { body: (<><circle pathLength={1} cx="12" cy="12" r="4"/><path pathLength={1} d="M12 2v2m0 16v2M4.9 4.9l1.4 1.4m11.4 11.4 1.4 1.4M2 12h2m16 0h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></>) },};diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.tsindex 4c185099..e47d338e 100644--- a/src/client/webrtc/host-peer.ts+++ b/src/client/webrtc/host-peer.ts@@ -598,7 +598,7 @@ export class HostPeer {if (this.ordinaryAnswerEpoch === epoch) {this.ordinaryAnswerEpoch = null;}- this.setError(error, restart ? say("host.err.createConnection") : say("host.err.createConnection"));+ this.setError(error, say("host.err.createConnection"));return false;}}diff --git a/src/client/webrtc/media-assignment.ts b/src/client/webrtc/media-assignment.tsindex 8424244e..4a98daec 100644--- a/src/client/webrtc/media-assignment.ts+++ b/src/client/webrtc/media-assignment.ts@@ -21,16 +21,6 @@ export function limitMediaAssignment(};}-export function retainSelectedMediaParent(- assignment: MediaAssignment,- parentPeerId: string,-): MediaAssignment {- return {- parentPeerId,- childPeerIds: assignment.childPeerIds,- };-}-export function reconcileBoundedMediaChildren(currentPeerIds: Iterable<string>,nextChildPeerIds: readonly string[],@@ -55,33 +45,26 @@ export function reconcileBoundedMediaChildren(}export function viewerSignalMessage(- peerAssisted: boolean,targetPeerId: string,payload: SignalPayload,): Extract<ClientMessage, { type: "signal" }> {- return peerAssisted- ? { type: "signal", targetPeerId, payload }- : { type: "signal", payload };+ return { type: "signal", targetPeerId, payload };}export function viewerRestartMessage(- peerAssisted: boolean,targetPeerId: string,connectionId: string,rebuild: boolean,): Extract<ClientMessage, { type: "restart-request" }> {- return peerAssisted- ? {- type: "restart-request",- targetPeerId,- connectionId,- rebuild,- }- : { type: "restart-request", connectionId, rebuild };+ return {+ type: "restart-request",+ targetPeerId,+ connectionId,+ rebuild,+ };}export function createOwnedViewerRestartSender(- peerAssisted: boolean,ownsActivePeer: (targetPeerId: string, connectionId: string) => boolean,send: (message: Extract<ClientMessage, { type: "restart-request" }>,@@ -95,7 +78,6 @@ export function createOwnedViewerRestartSender(ownsActivePeer(targetPeerId, connectionId) &&send(viewerRestartMessage(- peerAssisted,targetPeerId,connectionId,rebuild,diff --git a/src/client/webrtc/viewer-peer.ts b/src/client/webrtc/viewer-peer.tsindex a19a6a52..ca4e925a 100644--- a/src/client/webrtc/viewer-peer.ts+++ b/src/client/webrtc/viewer-peer.ts@@ -230,7 +230,6 @@ export class ViewerPeer implements ViewerMediaPeer {return;}this.disposed = true;- this.clearRecoveryTimer();this.disposeConnection();this.pendingByConnection.clear();}@@ -440,14 +439,7 @@ export class ViewerPeer implements ViewerMediaPeer {if (this.recoveryOwner === "route") {this.clearDisconnectTimer();if (state === "failed") {- if (- this.natPredictionEnabled &&- this.automaticRecoveryRequests < VIEWER_MAX_AUTOMATIC_RECOVERY_REQUESTS- ) {- this.attemptAutomaticRecovery();- } else {- this.reportRecoveryExhausted();- }+ this.reportRecoveryExhausted();}return;}@@ -482,10 +474,7 @@ export class ViewerPeer implements ViewerMediaPeer {this.reportRecoveryExhausted();return;}- const rebuild =- this.recoveryOwner === "route"- ? false- : this.automaticRecoveryRequests > 0;+ const rebuild = this.automaticRecoveryRequests > 0;if (!this.events.sendRestartRequest(this.parentPeerId,@@ -699,6 +688,7 @@ export class ViewerPeer implements ViewerMediaPeer {private disposeConnection(): void {this.clearDisconnectTimer();this.clearInitialConnectionTimer();+ this.clearRecoveryTimer();this.stopDecodedFrameProof();if (this.statsTimer !== null) {window.clearInterval(this.statsTimer);diff --git a/src/client/webrtc/viewer-relay.ts b/src/client/webrtc/viewer-relay.tsindex 8d6ed7cc..ed39d5cf 100644--- a/src/client/webrtc/viewer-relay.ts+++ b/src/client/webrtc/viewer-relay.ts@@ -576,7 +576,7 @@ export class ViewerRelay {peerEvents,candidate,);- if (nativePeer) return nativePeer;+ if (nativePeer) return (peer = nativePeer);}peer = new HostPeer(childPeerId,diff --git a/src/server/access-session.ts b/src/server/access-session.tsdeleted file mode 100644index a34ab4ce..00000000--- a/src/server/access-session.ts+++ /dev/null@@ -1,102 +0,0 @@-import { createHash, createHmac, timingSafeEqual } from "node:crypto";--const DEFAULT_SESSION_TTL_SECONDS = 24 * 60 * 60;-const COOKIE_VERSION = "v1";--export interface SiteAccessOptions {- password?: string;- secure: boolean;- now?: () => number;- ttlSeconds?: number;-}--export class SiteAccess {- private readonly now: () => number;- private readonly ttlSeconds: number;-- constructor(private readonly options: SiteAccessOptions) {- this.now = options.now ?? Date.now;- this.ttlSeconds = options.ttlSeconds ?? DEFAULT_SESSION_TTL_SECONDS;- if (!Number.isSafeInteger(this.ttlSeconds) || this.ttlSeconds <= 0) {- throw new Error("Access session TTL must be a positive integer");- }- }-- get required(): boolean {- return Boolean(this.options.password);- }-- passwordMatches(value: string | undefined): boolean {- return !this.required || Boolean(value && secretMatches(value, this.options.password!));- }-- isAuthenticated(cookieHeader: string | undefined): boolean {- if (!this.required) {- return true;- }- const value = readCookie(cookieHeader, this.cookieName);- if (!value) {- return false;- }- const [version, expiresText, signature, ...extra] = value.split(".");- if (- version !== COOKIE_VERSION ||- extra.length > 0 ||- !/^\d+$/.test(expiresText ?? "") ||- !/^[A-Za-z0-9_-]{43}$/.test(signature ?? "")- ) {- return false;- }- const expiresAt = Number(expiresText);- if (!Number.isSafeInteger(expiresAt) || expiresAt <= Math.floor(this.now() / 1_000)) {- return false;- }- return secretMatches(signature!, this.sign(`${version}.${expiresText}`));- }-- createCookie(): string | undefined {- if (!this.required) {- return undefined;- }- const expiresAt = Math.floor(this.now() / 1_000) + this.ttlSeconds;- const payload = `${COOKIE_VERSION}.${expiresAt}`;- const value = `${payload}.${this.sign(payload)}`;- const attributes = [- `${this.cookieName}=${value}`,- "Path=/",- `Max-Age=${this.ttlSeconds}`,- "HttpOnly",- "SameSite=Strict",- ];- if (this.options.secure) {- attributes.push("Secure");- }- return attributes.join("; ");- }-- private get cookieName(): string {- return this.options.secure- ? "__Host-screener-site-access"- : "screener-site-access";- }-- private sign(payload: string): string {- return createHmac("sha256", this.options.password!).update(payload).digest("base64url");- }-}--function readCookie(header: string | undefined, name: string): string | undefined {- for (const part of header?.split(";") ?? []) {- const separator = part.indexOf("=");- if (separator !== -1 && part.slice(0, separator).trim() === name) {- return part.slice(separator + 1).trim() || undefined;- }- }- return undefined;-}--function secretMatches(actual: string, expected: string): boolean {- const actualDigest = createHash("sha256").update(actual).digest();- const expectedDigest = createHash("sha256").update(expected).digest();- return timingSafeEqual(actualDigest, expectedDigest);-}diff --git a/src/server/app.ts b/src/server/app.tsdeleted file mode 100644index 7447c76a..00000000--- a/src/server/app.ts+++ /dev/null@@ -1,805 +0,0 @@-import { createServer, type IncomingMessage, type ServerResponse } from "node:http";-import { fileURLToPath } from "node:url";--import sirv from "sirv";-import type { ViteDevServer } from "vite";--import {- createRoomRequestSchema,- replaceRoomRequestSchema,- roomAccessUpdateRequestSchema,- type CreateRoomResponse,-} from "../shared/protocol.js";-import { SiteAccess } from "./access-session.js";-import { loadConfig, type ServerConfig } from "./config.js";-import type { SfuFallbackOptions } from "./hybrid-media-router.js";-import type { SfuTokenIssuer } from "./livekit-token.js";-import type { SfuRoomControl } from "./sfu-room-control.js";-import { SfuResourceAdmission } from "./sfu-resource-admission.js";-import { RoomDatabase } from "./room-database.js";-import {- ROOM_CAPACITY,- RoomStore,- RoomStoreError,- type CreatedRoom,-} from "./room-store.js";-import { SignalingServer, type SignalingOptions } from "./signaling.js";--export interface CreateServerOptions {- frontend: FrontendComposition;- config?: ServerConfig;- roomStore?: RoomStore;- now?: () => number;- authenticationTimeoutMs?: number;- viewerDisconnectGraceMs?: number;- heartbeatIntervalMs?: number;- cleanupIntervalMs?: number;- maxSignalConnections?: number;- maxUnauthenticatedSignalConnections?: number;- siteAccessTtlSeconds?: number;- sfuTokenIssuer?: SfuTokenIssuer;- sfuRoomControl?: SfuRoomControl;-}--export type FrontendComposition =- | { mode: "development" }- | { mode: "static"; directory?: string }- | { mode: "none" };--export interface ScreenerServer {- readonly httpServer: ReturnType<typeof createServer>;- readonly roomStore: RoomStore;- listen(port?: number, host?: string): Promise<number>;- close(): Promise<void>;- end(): Promise<void>;-}--type FrontendHandler = (request: IncomingMessage, response: ServerResponse) => void;--export async function createScreenerServer(- options: CreateServerOptions,-): Promise<ScreenerServer> {- const config = options.config ?? loadConfig();- const now = options.now ?? Date.now;- const livekitFallback = config.livekitFallback;- let sfuFallback: SfuFallbackOptions | undefined;- let sfuRoomControl: SfuRoomControl | undefined;- if (livekitFallback) {- sfuRoomControl =- options.sfuRoomControl ??- new (await import("./sfu-room-control.js")).LiveKitSfuRoomControl({- apiUrl: livekitFallback.apiUrl,- apiKey: livekitFallback.apiKey,- apiSecret: livekitFallback.apiSecret,- maxViewersPerRoom: config.maxViewersPerRoom,- });- sfuFallback = {- url: livekitFallback.url,- tokenIssuer:- options.sfuTokenIssuer ??- new (await import("./livekit-token.js")).LiveKitTokenIssuer({- apiKey: livekitFallback.apiKey,- apiSecret: livekitFallback.apiSecret,- maxViewersPerRoom: config.maxViewersPerRoom,- }),- admission: new SfuResourceAdmission({- ingressCapacity: ROOM_CAPACITY,- egressCapacity: ROOM_CAPACITY * config.maxViewersPerRoom,- }),- roomControl: sfuRoomControl,- };- }- const roomStore =- options.roomStore ??- new RoomStore({- leaseMs: config.roomLeaseMs,- maxRooms: ROOM_CAPACITY,- maxViewersPerRoom: config.maxViewersPerRoom,- database: config.roomDatabasePath- ? new RoomDatabase(config.roomDatabasePath)- : undefined,- now,- });- const siteAccess = new SiteAccess({- password: config.siteAccessPassword,- secure:- config.nodeEnv === "production" &&- config.publicBaseUrl.protocol === "https:",- now,- ttlSeconds: options.siteAccessTtlSeconds,- });- const iceOptions = {- stunUrls: config.stunUrls,- natPredictionEnabled: config.natPredictionEnabled,- natPredictionStunUrls: config.natPredictionStunUrls,- };-- let frontendHandler: FrontendHandler | undefined;- let vite: ViteDevServer | undefined;- let acceptingTraffic = false;- const httpServer = createServer((request, response) => {- if (!acceptingTraffic) {- response.setHeader("Cache-Control", "no-store");- response.setHeader("Retry-After", "1");- sendJson(response, 503, { error: "Service starting" });- return;- }- void handleRequest(- request,- response,- config,- roomStore,- siteAccess,- () => frontendHandler,- () => signaling,- ).catch((error: unknown) => {- console.error("HTTP request failed", {- method: request.method,- path: safePathname(request.url),- error,- });- if (!response.headersSent) {- sendJson(response, 500, { error: "Internal server error" });- } else {- response.destroy();- }- });- });-- const signalingOptions: SignalingOptions = {- server: httpServer,- roomStore,- peerAssistedMedia: config.peerAssistedMedia,- endpointMediaCopyCapacity: config.endpointMediaCopyCapacity,- ...(sfuFallback ? { sfuFallback } : {}),- ice: iceOptions,- allowedOrigins: config.allowedOrigins,- siteAccessAtUpgrade: (request) =>- siteAccess.isAuthenticated(request.headers.cookie),- publicBaseUrl: config.publicBaseUrl,- now,- authenticationTimeoutMs: options.authenticationTimeoutMs,- viewerDisconnectGraceMs: options.viewerDisconnectGraceMs,- heartbeatIntervalMs: options.heartbeatIntervalMs,- cleanupIntervalMs: options.cleanupIntervalMs,- maxConnections: options.maxSignalConnections,- maxUnauthenticatedConnections:- options.maxUnauthenticatedSignalConnections,- passThroughUnknownUpgrades: options.frontend.mode === "development",- };- let signaling: SignalingServer | undefined;- let startupOperation: Promise<number> | undefined;- let shutdownOperation: Promise<void> | undefined;- let closing = false;-- if (options.frontend.mode === "development") {- const { createServer: createViteServer } = await import("vite");- vite = await createViteServer({- appType: "spa",- server: {- middlewareMode: true,- hmr: { server: httpServer },- },- });- frontendHandler = (request, response) => {- vite?.middlewares(request, response, () => {- sendJson(response, 404, { error: "Not found" });- });- };- } else if (options.frontend.mode === "static") {- const staticDirectory =- options.frontend.directory ??- fileURLToPath(new URL("../../client/", import.meta.url));- const serve = sirv(staticDirectory, {- single: true,- setHeaders(response) {- response.setHeader("X-Content-Type-Options", "nosniff");- response.setHeader("Referrer-Policy", "no-referrer");- },- });- frontendHandler = (request, response) => {- serve(request, response, () => {- sendJson(response, 404, { error: "Not found" });- });- };- }-- httpServer.requestTimeout = 10_000;- httpServer.headersTimeout = 15_000;- httpServer.keepAliveTimeout = 5_000;-- async function shutdown(endRooms: boolean): Promise<void> {- if (shutdownOperation) {- return await shutdownOperation;- }- shutdownOperation = (async () => {- acceptingTraffic = false;- closing = true;- const errors: unknown[] = [];- try {- await startupOperation;- } catch {- // The listen caller owns the startup error; shutdown still closes resources.- }- if (endRooms) {- try {- if (signaling) {- signaling.endAllRooms();- } else {- roomStore.abandonAllRooms();- }- } catch (error) {- errors.push(error);- }- }- try {- await signaling?.close();- } catch (error) {- errors.push(error);- }- try {- if (httpServer.listening) {- await new Promise<void>((resolve, reject) => {- httpServer.close((error) => (error ? reject(error) : resolve()));- });- }- } catch (error) {- errors.push(error);- }- try {- await vite?.close();- } catch (error) {- errors.push(error);- }- try {- roomStore.close();- } catch (error) {- errors.push(error);- }- if (errors.length > 0) {- throw new AggregateError(errors, "Screener server shutdown failed");- }- })();- return await shutdownOperation;- }-- return {- httpServer,- roomStore,- async listen(port = config.port, host = config.listenHost) {- if (startupOperation) {- throw new Error("Screener server startup was already requested");- }- if (closing) {- throw new Error("Screener server is closing");- }- startupOperation = (async () => {- const boundPort = await bindHttpServer(httpServer, port, host);- try {- roomStore.initialize();- await sfuRoomControl?.initialize();- if (!closing) {- signaling = new SignalingServer(signalingOptions);- acceptingTraffic = true;- }- return boundPort;- } catch (error) {- const cleanupErrors: unknown[] = [];- try {- roomStore.close();- } catch (closeError) {- cleanupErrors.push(closeError);- }- try {- await closeHttpServer(httpServer);- } catch (closeError) {- cleanupErrors.push(closeError);- }- if (cleanupErrors.length > 0) {- throw new AggregateError(- [error, ...cleanupErrors],- "Screener startup reconciliation failed",- );- }- throw error;- }- })();- return await startupOperation;- },- close: () => shutdown(false),- end: () => shutdown(true),- };-}--function bindHttpServer(- httpServer: ReturnType<typeof createServer>,- port: number,- host: string,-): Promise<number> {- return new Promise<number>((resolve, reject) => {- const onError = (error: Error) => {- httpServer.off("listening", onListening);- reject(error);- };- const onListening = () => {- httpServer.off("error", onError);- const address = httpServer.address();- if (!address || typeof address === "string") {- reject(new Error("Server did not bind to a TCP port"));- return;- }- resolve(address.port);- };- httpServer.once("error", onError);- httpServer.once("listening", onListening);- httpServer.listen(port, host);- });-}--function closeHttpServer(- httpServer: ReturnType<typeof createServer>,-): Promise<void> {- return new Promise<void>((resolve, reject) => {- httpServer.close((error) => (error ? reject(error) : resolve()));- });-}--async function handleRequest(- request: IncomingMessage,- response: ServerResponse,- config: ServerConfig,- roomStore: RoomStore,- siteAccess: SiteAccess,- getFrontendHandler: () => FrontendHandler | undefined,- getSignaling: () => SignalingServer | undefined,-): Promise<void> {- const url = new URL(request.url ?? "/", config.publicBaseUrl);- if (url.pathname === "/healthz") {- response.setHeader("Cache-Control", "no-store");- if (request.method !== "GET") {- response.setHeader("Allow", "GET");- sendJson(response, 405, { error: "Method not allowed" });- return;- }- sendJson(response, 200, { status: "ok" });- return;- }-- if (url.pathname === "/api/capabilities") {- response.setHeader("Cache-Control", "no-store");- response.setHeader("X-Content-Type-Options", "nosniff");- if (request.method !== "GET") {- response.setHeader("Allow", "GET");- sendJson(response, 405, { error: "Method not allowed" });- return;- }- sendJson(response, 200, {- natPrediction: config.natPredictionEnabled,- });- return;- }-- if (url.pathname === "/api/site-access") {- handleSiteAccessRequest(request, response, config, siteAccess);- return;- }-- const roomReplacementMatch =- /^\/api\/rooms\/([1-9]\d{3})\/replacement$/.exec(url.pathname);- if (roomReplacementMatch) {- response.setHeader("Cache-Control", "no-store");- response.setHeader("X-Content-Type-Options", "nosniff");- if (request.method !== "POST") {- response.setHeader("Allow", "POST");- sendJson(response, 405, { error: "Method not allowed" });- return;- }- const hostToken = authorizedRoomHostToken(- request,- response,- config,- siteAccess,- );- if (!hostToken) {- return;- }- let parsedRequest;- try {- parsedRequest = replaceRoomRequestSchema.safeParse(- await readJsonBody(request, 1_024),- );- } catch {- sendJson(response, 400, { error: "Invalid room replacement request" });- return;- }- if (!parsedRequest.success) {- sendJson(response, 400, { error: "Invalid room replacement request" });- return;- }- const signaling = getSignaling();- if (!signaling) {- sendJson(response, 503, { error: "Service unavailable" });- return;- }- try {- const room = await signaling.replaceRoom(- roomReplacementMatch[1]!,- hostToken,- parsedRequest.data.codeEntryPolicy,- parsedRequest.data.roomPassword ?? null,- );- sendJson(response, 201, createRoomResponse(room, config));- } catch (error) {- if (error instanceof RoomStoreError && error.code === "ROOM_LIMIT") {- sendJson(response, 503, { error: "Room capacity reached" });- return;- }- if (- error instanceof RoomStoreError &&- (error.code === "ROOM_ACCESS_DENIED" || error.code === "ROOM_BUSY")- ) {- sendJson(response, 503, { error: "Room replacement unavailable" });- return;- }- if (- error instanceof RoomStoreError &&- (error.code === "INVALID_TOKEN" ||- error.code === "ROOM_NOT_FOUND" ||- error.code === "ROOM_EXPIRED")- ) {- sendJson(response, 404, { error: "Room not found" });- return;- }- throw error;- }- return;- }-- const roomAccessMatch = /^\/api\/rooms\/([1-9]\d{3})\/access$/.exec(- url.pathname,- );- if (roomAccessMatch) {- response.setHeader("Cache-Control", "no-store");- response.setHeader("X-Content-Type-Options", "nosniff");- if (request.method !== "POST") {- response.setHeader("Allow", "POST");- sendJson(response, 405, { error: "Method not allowed" });- return;- }- const hostToken = authorizedRoomHostToken(- request,- response,- config,- siteAccess,- );- if (!hostToken) {- return;- }-- let parsedRequest;- try {- parsedRequest = roomAccessUpdateRequestSchema.safeParse(- await readJsonBody(request, 1_024),- );- } catch {- sendJson(response, 400, { error: "Invalid room access request" });- return;- }- if (!parsedRequest.success) {- sendJson(response, 400, { error: "Invalid room access request" });- return;- }-- const signaling = getSignaling();- if (!signaling) {- sendJson(response, 503, { error: "Service unavailable" });- return;- }- try {- sendJson(- response,- 200,- await signaling.updateRoomAccess(- roomAccessMatch[1]!,- hostToken,- parsedRequest.data,- ),- );- } catch (error) {- if (error instanceof RoomStoreError && error.code === "ROOM_BUSY") {- sendJson(response, 503, { error: "Room access update unavailable" });- return;- }- if (- error instanceof RoomStoreError &&- error.code === "ROOM_ACCESS_DENIED"- ) {- sendJson(response, 409, { error: "Room access update rejected" });- return;- }- if (error instanceof RoomStoreError) {- sendJson(response, 404, { error: "Room not found" });- return;- }- throw error;- }- return;- }-- if (url.pathname === "/api/rooms") {- response.setHeader("Cache-Control", "no-store");- response.setHeader("X-Content-Type-Options", "nosniff");- if (request.method !== "POST") {- response.setHeader("Allow", "POST");- sendJson(response, 405, { error: "Method not allowed" });- return;- }- if (- !isStrictlyAllowedRequestOrigin(- request.headers.origin,- config.allowedOrigins,- )- ) {- sendJson(response, 403, { error: "Forbidden" });- return;- }- if (- !isRoomCreationAuthorized(- request,- siteAccess,- )- ) {- sendJson(response, 401, { error: "Unauthorized" });- return;- }-- let parsedRequest;- try {- parsedRequest = createRoomRequestSchema.safeParse(- await readJsonBody(request, 1_024),- );- } catch {- sendJson(response, 400, { error: "Invalid room request" });- return;- }- if (!parsedRequest.success) {- sendJson(response, 400, { error: "Invalid room request" });- return;- }-- try {- const room = await roomStore.createRoom(- parsedRequest.data.codeEntryPolicy,- parsedRequest.data.roomPassword ?? null,- parsedRequest.data.preferredRoomId,- );- sendJson(response, 201, createRoomResponse(room, config));- } catch (error) {- if (error instanceof RoomStoreError && error.code === "ROOM_LIMIT") {- sendJson(response, 503, { error: "Room capacity reached" });- return;- }- if (error instanceof RoomStoreError && error.code === "ROOM_BUSY") {- sendJson(response, 503, { error: "Room creation unavailable" });- return;- }- if (error instanceof RoomStoreError && error.code === "INVALID_TOKEN") {- sendJson(response, 400, { error: "Invalid room request" });- return;- }- throw error;- }- return;- }-- if (url.pathname.startsWith("/api/")) {- response.setHeader("Cache-Control", "no-store");- sendJson(response, 404, { error: "Not found" });- return;- }-- const frontendHandler = getFrontendHandler();- if (frontendHandler) {- frontendHandler(request, response);- return;- }- sendJson(response, 404, { error: "Not found" });-}--function authorizedRoomHostToken(- request: IncomingMessage,- response: ServerResponse,- config: ServerConfig,- siteAccess: SiteAccess,-): string | null {- if (- !isStrictlyAllowedRequestOrigin(- request.headers.origin,- config.allowedOrigins,- )- ) {- sendJson(response, 403, { error: "Forbidden" });- return null;- }- if (!isRoomCreationAuthorized(request, siteAccess)) {- sendJson(response, 401, { error: "Unauthorized" });- return null;- }- const hostToken = readBearerToken(request);- if (!hostToken) {- sendJson(response, 404, { error: "Room not found" });- return null;- }- return hostToken;-}--function createRoomResponse(- room: CreatedRoom,- config: ServerConfig,-): CreateRoomResponse {- const inviteUrl = new URL(`/r/${room.roomId}`, config.publicBaseUrl);- if (room.viewerGrant) {- inviteUrl.hash = `v=${room.viewerGrant}`;- }- return {- roomId: room.roomId,- hostToken: room.hostToken,- inviteUrl: inviteUrl.toString(),- codeEntryPolicy: room.codeEntryPolicy,- expiresAt: room.expiresAt,- roomLeaseSeconds: config.roomLeaseMs / 1_000,- };-}--function handleSiteAccessRequest(- request: IncomingMessage,- response: ServerResponse,- config: ServerConfig,- siteAccess: SiteAccess,-): void {- response.setHeader("Cache-Control", "no-store");- response.setHeader("X-Content-Type-Options", "nosniff");-- if (request.method === "GET") {- const status = siteAccessStatus(request, siteAccess);- if (status.required && status.authenticated) {- response.setHeader("Set-Cookie", siteAccess.createCookie()!);- }- sendJson(response, 200, status);- return;- }-- if (request.method !== "POST") {- response.setHeader("Allow", "GET, POST");- sendJson(response, 405, { error: "Method not allowed" });- return;- }-- if (- !isStrictlyAllowedRequestOrigin(- request.headers.origin,- config.allowedOrigins,- )- ) {- sendJson(response, 403, { error: "Forbidden" });- return;- }- if (hasRequestBody(request)) {- sendJson(response, 400, { error: "Request body is not accepted" });- return;- }-- if (!siteAccess.required) {- sendJson(response, 200, { required: false, authenticated: true });- return;- }- if (!isBearerAuthorized(request, siteAccess)) {- response.setHeader("WWW-Authenticate", "Bearer");- sendJson(response, 401, { error: "Unauthorized" });- return;- }-- response.setHeader("Set-Cookie", siteAccess.createCookie()!);- sendJson(response, 200, { required: true, authenticated: true });-}--function siteAccessStatus(- request: IncomingMessage,- siteAccess: SiteAccess,-): { required: boolean; authenticated: boolean } {- return {- required: siteAccess.required,- authenticated: siteAccess.isAuthenticated(request.headers.cookie),- };-}--function hasRequestBody(request: IncomingMessage): boolean {- const contentLength = request.headers["content-length"];- const parsedLength = contentLength === undefined ? 0 : Number(contentLength);- return (- request.headers["transfer-encoding"] !== undefined ||- !Number.isFinite(parsedLength) ||- parsedLength !== 0- );-}--function isStrictlyAllowedRequestOrigin(- origin: string | undefined,- allowedOrigins: ReadonlySet<string>,-): boolean {- if (!origin) {- return false;- }- try {- const parsed = new URL(origin);- return parsed.origin === origin && allowedOrigins.has(origin);- } catch {- return false;- }-}--function isRoomCreationAuthorized(- request: IncomingMessage,- siteAccess: SiteAccess,-): boolean {- if (!siteAccess.required) {- return true;- }- return siteAccess.isAuthenticated(request.headers.cookie);-}--function isBearerAuthorized(- request: IncomingMessage,- siteAccess: SiteAccess,-): boolean {- const provided = readBearerToken(request);- return provided !== null && siteAccess.passwordMatches(provided);-}--function readBearerToken(request: IncomingMessage): string | null {- const authorization = request.headers.authorization;- if (!authorization?.startsWith("Bearer ")) {- return null;- }- return authorization.slice("Bearer ".length) || null;-}--async function readJsonBody(- request: IncomingMessage,- maximumBytes: number,-): Promise<unknown> {- const contentType = request.headers["content-type"]?.split(";", 1)[0]?.trim();- if (contentType !== "application/json") {- throw new Error("Request content type must be application/json");- }- const chunks: Buffer[] = [];- let bytes = 0;- for await (const chunk of request) {- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);- bytes += buffer.byteLength;- if (bytes > maximumBytes) {- throw new Error("Request body is too large");- }- chunks.push(buffer);- }- if (bytes === 0) {- throw new Error("Request body is required");- }- return JSON.parse(Buffer.concat(chunks).toString("utf8"));-}--function sendJson(response: ServerResponse, status: number, body: unknown): void {- const encoded = JSON.stringify(body);- response.statusCode = status;- response.setHeader("Content-Type", "application/json; charset=utf-8");- response.setHeader("Content-Length", Buffer.byteLength(encoded));- response.end(encoded);-}--function safePathname(requestUrl: string | undefined): string {- try {- return new URL(requestUrl ?? "/", "http://localhost").pathname;- } catch {- return "<invalid>";- }-}diff --git a/src/server/config.ts b/src/server/config.tsdeleted file mode 100644index 019556b1..00000000--- a/src/server/config.ts+++ /dev/null@@ -1,421 +0,0 @@-import { isAbsolute } from "node:path";--import {- MAX_ICE_SERVER_URLS,- MAX_VIEWERS_PER_ROOM_LIMIT,- stunUrlSchema,-} from "../shared/protocol.js";-import {- DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY,- MAX_ENDPOINT_MEDIA_COPY_CAPACITY,-} from "../shared/media-copy-accounting.js";-import { natPredictionStunUrls } from "./ice.js";--export type RuntimeEnvironment = "development" | "test" | "production";--const MIN_SITE_ACCESS_PASSWORD_BYTES = 8;-const MAX_SITE_ACCESS_PASSWORD_BYTES = 128;-const MIN_LIVEKIT_API_SECRET_BYTES = 32;-const DEFAULT_MAX_VIEWERS_PER_ROOM = 8;-const DEFAULT_ROOM_LEASE_SECONDS = 86_400;-const VISIBLE_ASCII_PATTERN = /^[\x21-\x7e]+$/;-const REMOVED_ENVIRONMENT_VARIABLES = [- "TURN_URLS",- "TURN_SHARED_SECRET",- "TURN_CREDENTIAL_TTL_SECONDS",- "PEER_ICE_TURN_URLS",- "PEER_ICE_TURN_SHARED_SECRET",- "PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS",- "SELECTED_EDGE_TURN_URLS",- "SELECTED_EDGE_TURN_SHARED_SECRET",- "SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS",- "SELECTED_EDGE_TURN_ALLOCATION_CAPACITY",- "PEER_ASSISTED_ROOM_IDS",- "HOST_ADMISSION_PASSWORD",- "MAX_PEER_RELAY_DOWNSTREAM_EDGES",- "ROOM_TTL_SECONDS",-] as const;--export interface LiveKitFallbackConfig {- url: string;- apiUrl: string;- apiKey: string;- apiSecret: string;-}--export interface ServerConfig {- nodeEnv: RuntimeEnvironment;- port: number;- listenHost: string;- publicBaseUrl: URL;- allowedOrigins: ReadonlySet<string>;- siteAccessPassword?: string;- roomDatabasePath?: string;- roomLeaseMs: number;- maxViewersPerRoom: number;- peerAssistedMedia: boolean;- endpointMediaCopyCapacity: number;- livekitFallback?: LiveKitFallbackConfig;- stunUrls: readonly string[];- natPredictionEnabled: boolean;- natPredictionStunUrls?: readonly string[];-}--function parseBoolean(- value: string | undefined,- fallback: boolean,- name: string,-): boolean {- if (value === undefined || value === "") {- return fallback;- }- if (value === "true") {- return true;- }- if (value === "false") {- return false;- }- throw new Error(`${name} must be true or false`);-}--function parsePositiveInteger(- value: string | undefined,- fallback: number,- name: string,-): number {- const parsed = value === undefined || value === "" ? fallback : Number(value);- if (!Number.isSafeInteger(parsed) || parsed <= 0) {- throw new Error(`${name} must be a positive integer`);- }- return parsed;-}--function parseBoundedInteger(- value: string | undefined,- fallback: number,- name: string,- minimum: number,- maximum: number,-): number {- const parsed = parsePositiveInteger(value, fallback, name);- if (parsed < minimum || parsed > maximum) {- throw new Error(`${name} must be between ${minimum} and ${maximum}`);- }- return parsed;-}--function parseEnvironment(value: string | undefined): RuntimeEnvironment {- const environment = value ?? "development";- if (- environment !== "development" &&- environment !== "test" &&- environment !== "production"- ) {- throw new Error("NODE_ENV must be development, test, or production");- }- return environment;-}--function parseRoomDatabasePath(value: string | undefined): string | undefined {- const path = value?.trim();- if (!path) {- return undefined;- }- if (path === ":memory:" || path.includes("\0") || !isAbsolute(path)) {- throw new Error("ROOM_DATABASE_PATH must be an absolute file path");- }- return path;-}--function parseLiveKitFallback(- environment: NodeJS.ProcessEnv,- nodeEnv: RuntimeEnvironment,-): LiveKitFallbackConfig | undefined {- const url = environment.LIVEKIT_URL?.trim() || undefined;- const apiUrl = environment.LIVEKIT_API_URL?.trim() || undefined;- const apiKey = environment.LIVEKIT_API_KEY?.trim() || undefined;- const apiSecret = environment.LIVEKIT_API_SECRET?.trim() || undefined;- const configuredValues = [url, apiUrl, apiKey, apiSecret].filter(Boolean).length;- if (configuredValues === 0) {- return undefined;- }- if (configuredValues !== 4) {- throw new Error(- "LIVEKIT_URL, LIVEKIT_API_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must be configured together",- );- }- if (Buffer.byteLength(apiSecret!) < MIN_LIVEKIT_API_SECRET_BYTES) {- throw new Error("LIVEKIT_API_SECRET must contain at least 32 bytes");- }-- let parsedUrl: URL;- try {- parsedUrl = new URL(url!);- } catch {- throw new Error("LIVEKIT_URL must be a valid ws or wss origin");- }- if (parsedUrl.protocol !== "ws:" && parsedUrl.protocol !== "wss:") {- throw new Error("LIVEKIT_URL must use ws or wss");- }- if (- parsedUrl.username ||- parsedUrl.password ||- parsedUrl.pathname !== "/" ||- parsedUrl.search ||- parsedUrl.hash- ) {- throw new Error(- "LIVEKIT_URL must be an origin without credentials, path, query, or fragment",- );- }- if (nodeEnv === "production" && parsedUrl.protocol !== "wss:") {- throw new Error("LIVEKIT_URL must use wss in production");- }-- let parsedApiUrl: URL;- try {- parsedApiUrl = new URL(apiUrl!);- } catch {- throw new Error("LIVEKIT_API_URL must be a valid http or https origin");- }- if (parsedApiUrl.protocol !== "http:" && parsedApiUrl.protocol !== "https:") {- throw new Error("LIVEKIT_API_URL must use http or https");- }- if (- parsedApiUrl.username ||- parsedApiUrl.password ||- parsedApiUrl.pathname !== "/" ||- parsedApiUrl.search ||- parsedApiUrl.hash- ) {- throw new Error(- "LIVEKIT_API_URL must be an origin without credentials, path, query, or fragment",- );- }- if (- nodeEnv === "production" &&- parsedApiUrl.protocol !== "https:" &&- !isLoopbackHostname(parsedApiUrl.hostname)- ) {- throw new Error("LIVEKIT_API_URL must use https or loopback in production");- }-- return {- url: parsedUrl.origin,- apiUrl: parsedApiUrl.origin,- apiKey: apiKey!,- apiSecret: apiSecret!,- };-}--function isLoopbackHostname(hostname: string): boolean {- return (- hostname === "localhost" ||- hostname === "127.0.0.1" ||- hostname === "[::1]" ||- hostname === "::1"- );-}--function parseUrlList(value: string | undefined, name: string): string[] {- if (!value?.trim()) {- return [];- }-- return value.split(",").map((entry) => {- const url = entry.trim();- if (!url) {- throw new Error(`${name} contains an empty URL`);- }- return url;- });-}--function parseStunUrlList(- value: string | undefined,- name: string,- maximum = MAX_ICE_SERVER_URLS,-): string[] {- const values = parseUrlList(value, name);- if (values.length > maximum) {- throw new Error(`${name} must contain at most ${maximum} URLs`);- }- return values.map((value) => {- if (!stunUrlSchema.safeParse(value).success) {- throw new Error(`${name} contains an invalid STUN URL`);- }- return value;- });-}--function parseOrigins(value: string | undefined, fallback: string): Set<string> {- const origins = parseUrlList(value, "ALLOWED_ORIGINS");- return new Set((origins.length > 0 ? origins : [fallback]).map(toOrigin));-}--function toOrigin(value: string): string {- const url = new URL(value);- if (url.protocol !== "http:" && url.protocol !== "https:") {- throw new Error("Allowed origins must use http or https");- }- return url.origin;-}--export function loadConfig(- environment: NodeJS.ProcessEnv = process.env,-): ServerConfig {- for (const name of REMOVED_ENVIRONMENT_VARIABLES) {- if (Object.prototype.hasOwnProperty.call(environment, name)) {- throw new Error(- name === "MAX_PEER_RELAY_DOWNSTREAM_EDGES"- ? `${name} is no longer supported; use ENDPOINT_MEDIA_COPY_CAPACITY`- : name === "HOST_ADMISSION_PASSWORD"- ? `${name} is no longer supported; use SITE_ACCESS_PASSWORD`- : name === "PEER_ASSISTED_ROOM_IDS"- ? `${name} is no longer supported; peer-assisted media applies to every room when enabled`- : name === "ROOM_TTL_SECONDS"- ? `${name} is no longer supported; use ROOM_LEASE_SECONDS`- : `${name} is no longer supported; ordinary ICE accepts STUN_URLS only`,- );- }- }- if (Object.prototype.hasOwnProperty.call(environment, "ACCESS_PASSWORD")) {- throw new Error(- "ACCESS_PASSWORD is no longer supported; use SITE_ACCESS_PASSWORD",- );- }-- const nodeEnv = parseEnvironment(environment.NODE_ENV);- const port = parsePositiveInteger(environment.PORT, 8787, "PORT");- if (port > 65_535) {- throw new Error("PORT must be at most 65535");- }- const listenHost = environment.LISTEN_HOST?.trim() || "0.0.0.0";-- const publicBaseUrl = new URL(- environment.PUBLIC_BASE_URL ?? `http://localhost:${port}`,- );- if (- publicBaseUrl.protocol !== "http:" &&- publicBaseUrl.protocol !== "https:"- ) {- throw new Error("PUBLIC_BASE_URL must use http or https");- }- if (- publicBaseUrl.username ||- publicBaseUrl.password ||- publicBaseUrl.pathname !== "/" ||- publicBaseUrl.search ||- publicBaseUrl.hash- ) {- throw new Error(- "PUBLIC_BASE_URL must be an origin without credentials, path, query, or fragment",- );- }- if (nodeEnv === "production" && publicBaseUrl.protocol !== "https:") {- throw new Error("PUBLIC_BASE_URL must use https in production");- }-- const siteAccessPassword =- environment.SITE_ACCESS_PASSWORD === ""- ? undefined- : environment.SITE_ACCESS_PASSWORD;- const roomDatabasePath = parseRoomDatabasePath(- environment.ROOM_DATABASE_PATH,- );- const stunUrls = parseStunUrlList(environment.STUN_URLS, "STUN_URLS");- const natPredictionEnabled = parseBoolean(- environment.NAT_PREDICTION_ENABLED,- false,- "NAT_PREDICTION_ENABLED",- );- if (- natPredictionEnabled &&- natPredictionStunUrls(stunUrls).length === 0- ) {- throw new Error(- "NAT_PREDICTION_ENABLED requires a STUN_URLS entry on UDP 3478",- );- }- if (natPredictionEnabled && stunUrls.length + 2 > MAX_ICE_SERVER_URLS) {- throw new Error(- `STUN_URLS must contain at most ${MAX_ICE_SERVER_URLS - 2} URLs when NAT_PREDICTION_ENABLED=true`,- );- }- const maxViewersPerRoom = parseBoundedInteger(- environment.MAX_VIEWERS_PER_ROOM,- DEFAULT_MAX_VIEWERS_PER_ROOM,- "MAX_VIEWERS_PER_ROOM",- 1,- MAX_VIEWERS_PER_ROOM_LIMIT,- );- const peerAssistedMedia = parseBoolean(- environment.PEER_ASSISTED_MEDIA,- false,- "PEER_ASSISTED_MEDIA",- );- const endpointMediaCopyCapacity = parseBoundedInteger(- environment.ENDPOINT_MEDIA_COPY_CAPACITY,- DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY,- "ENDPOINT_MEDIA_COPY_CAPACITY",- 1,- MAX_ENDPOINT_MEDIA_COPY_CAPACITY,- );- const livekitFallback = parseLiveKitFallback(environment, nodeEnv);-- if (livekitFallback && !peerAssistedMedia) {- throw new Error("LiveKit fallback requires PEER_ASSISTED_MEDIA=true");- }- const configuredSecrets = [- siteAccessPassword,- livekitFallback?.apiKey,- livekitFallback?.apiSecret,- ].filter((secret): secret is string => secret !== undefined);- if (new Set(configuredSecrets).size !== configuredSecrets.length) {- throw new Error(- "SITE_ACCESS_PASSWORD, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must use independent values",- );- }- if (- siteAccessPassword &&- (!VISIBLE_ASCII_PATTERN.test(siteAccessPassword) ||- Buffer.byteLength(siteAccessPassword) <- MIN_SITE_ACCESS_PASSWORD_BYTES ||- Buffer.byteLength(siteAccessPassword) >- MAX_SITE_ACCESS_PASSWORD_BYTES)- ) {- throw new Error(- "SITE_ACCESS_PASSWORD must contain 8 to 128 visible ASCII bytes",- );- }- if (nodeEnv === "production" && !siteAccessPassword) {- throw new Error("SITE_ACCESS_PASSWORD is required in production");- }- if (nodeEnv === "production" && stunUrls.length === 0) {- throw new Error("STUN is required in production");- }- return {- nodeEnv,- port,- listenHost,- publicBaseUrl,- allowedOrigins: parseOrigins(- environment.ALLOWED_ORIGINS,- publicBaseUrl.origin,- ),- siteAccessPassword,- roomDatabasePath,- roomLeaseMs:- parsePositiveInteger(- environment.ROOM_LEASE_SECONDS,- DEFAULT_ROOM_LEASE_SECONDS,- "ROOM_LEASE_SECONDS",- ) * 1_000,- maxViewersPerRoom,- peerAssistedMedia,- endpointMediaCopyCapacity,- livekitFallback,- stunUrls,- natPredictionEnabled,- };-}diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.tsdeleted file mode 100644index 5a285e45..00000000--- a/src/server/hybrid-media-router.ts+++ /dev/null@@ -1,2321 +0,0 @@-import { randomBytes } from "node:crypto";-import { debuglog } from "node:util";--import { packetLossPercentFromDeltas } from "../shared/packet-loss.js";-import type { CandidateSignalOrigin } from "../shared/nat-candidate.js";--import type {- ClientMessage,- MediaRouteUpstream,- ParticipantRouteAssignment,- PreparedRouteCandidate,- RoutePolicy,- Role,- ServerMessage,- ViewerQualityEvidenceMetrics,-} from "../shared/protocol.js";-import { assertEndpointMediaCopyCapacity } from "../shared/media-copy-accounting.js";-import type { SfuTokenIssuer } from "./livekit-token.js";-import {- RoomRouteController,- type CandidateCursorGuard,- type CandidatePlan,- type CandidateReservation,- type CandidateTuple,- type OperationSnapshot,- type RouteQualityEvidenceInput,- type RouteQualityEvidenceResult,- type SenderQualityEvidenceInput,- type SfuPublisherQualityEvidenceInput,- type RouteSnapshot,-} from "./room-route-controller.js";-import type { RoomStore } from "./room-store.js";-import type { SfuRoomControl } from "./sfu-room-control.js";-import { managedSfuRoomName } from "./sfu-resource-admission.js";-import type {- SfuResourceAdmission,- SfuResourceFence,- SfuSubscriptionFence,-} from "./sfu-resource-admission.js";--type ErrorCode = Extract<ServerMessage, { type: "error" }>["code"];--const DEFAULT_ROUTE_OPERATION_TIMEOUT_MS = 20_000;-const DEFAULT_SFU_DRAIN_RETRY_MS = 1_000;-const DEFAULT_HOST_OFFLINE_CHECK_MS = 5_000;-const routeDebug = debuglog("screener-route");--interface RouteResourceBase {- released: boolean;-}--interface SfuSubscriptionRouteResource extends RouteResourceBase {- kind: "sfu-subscription";- fence: SfuSubscriptionFence;-}--interface SfuPublicationRouteResource extends RouteResourceBase {- kind: "sfu-publication";- fence: SfuResourceFence;-}--interface OverlapRouteResource extends RouteResourceBase {- kind: "overlap";- endpointPeerId: string;-}--type RouteResource =- | SfuSubscriptionRouteResource- | SfuPublicationRouteResource- | OverlapRouteResource;--type SfuDrainTarget =- | { kind: "publication"; fence: SfuResourceFence }- | { kind: "subscription"; fence: SfuSubscriptionFence };--type SfuDrainTask = SfuDrainTarget & {- operation?: Promise<void>;- retryTimer?: NodeJS.Timeout;-};--interface HostOfflineCheck {- hostPeerId: string;- fence: SfuResourceFence;- hostSessionId: string;- connectionId: string;- timer: NodeJS.Timeout;-}--interface RoomRuntime {- hostPeerId?: string;- controller?: RoomRouteController<RouteResource>;- advertisedCapacityByViewer: Map<string, number>;- requested: boolean;- pump?: Promise<void>;- deadlineTimer?: NodeJS.Timeout;- sfuRefreshesInFlight: Set<string>;-}--interface PreparedCandidate {- reservation: CandidateReservation<RouteResource>;- connectionId: string;- publicationGeneration?: string;- publicationConnectionId?: string;- hostSessionId?: string;- hostSfuConfig?: Extract<ServerMessage, { type: "sfu-config" }>;- viewerSfuConfig?: Extract<ServerMessage, { type: "sfu-config" }>;-}--type PrepareResult =- | {- kind: "denied";- rejectionBucket: "stale" | "sfu-admission" | "candidate-failed";- }- | { kind: "ready"; prepared: PreparedCandidate };--type QualitySampleReference =- | {- kind: "peer";- childPeerId: string;- routeRevision: number;- connectionId: string;- }- | {- kind: "sfu";- routeRevision: number;- publicationGeneration: string;- hostSessionId: string;- };--interface QualityCopyContext {- committedCopies: number;- candidateReservedCopies: number;- possibleCopies: number;- endpointCapacity: number;- operationReason: OperationSnapshot["reason"] | null;- candidateTransition:- | CandidatePlan["endpointTransition"]["kind"]- | null;- sampleRole: "active" | "candidate" | "unknown";-}--export type ActiveViewerMediaEdge =- | {- revision: number;- connectionId: string;- upstream: { kind: "peer"; peerId: string };- }- | {- revision: number;- connectionId: string;- upstream: { kind: "sfu" };- };--export interface SfuFallbackOptions {- url: string;- tokenIssuer: SfuTokenIssuer;- admission: SfuResourceAdmission;- roomControl: SfuRoomControl;- prepareTimeoutMs?: number;- drainRetryMs?: number;- hostOfflineCheckMs?: number;-}--export interface HybridMediaRouterOptions {- roomStore: RoomStore;- endpointMediaCopyCapacity: number;- sfuFallback?: SfuFallbackOptions;- sendToSession: (sessionId: string, message: ServerMessage) => void;- getConnectionId: (roomId: string, viewerPeerId: string) => string | undefined;- setConnectionId: (roomId: string, viewerPeerId: string, connectionId: string) => void;- deleteConnectionId: (roomId: string, viewerPeerId: string) => void;- getShareGeneration: (roomId: string) => string | undefined;- onRoutesChanged?: (roomId: string) => void;- now?: () => number;-}--export interface HybridAuthenticationState {- routeRevision: number;- routeAssignment: ParticipantRouteAssignment;-}--export interface AuthenticatedRouteParticipant {- roomId: string;- role: Role;- peerId: string;- sessionId: string;- routePolicy?: RoutePolicy;-}--export class HybridMediaRouter {- private readonly rooms = new Map<string, RoomRuntime>();- private readonly resourceWaiters = new Set<string>();- private readonly sfuDrainTasks = new Map<string, SfuDrainTask>();- private readonly hostOfflineChecks = new Map<string, HostOfflineCheck>();- private readonly now: () => number;- private closing = false;-- constructor(private readonly options: HybridMediaRouterOptions) {- assertEndpointMediaCopyCapacity(options.endpointMediaCopyCapacity);- this.now = options.now ?? Date.now;- if (options.sfuFallback) new URL(options.sfuFallback.url);- }-- async close(): Promise<void> {- this.closing = true;- for (const roomId of [...this.rooms.keys()]) this.clearRoom(roomId);- this.resourceWaiters.clear();- for (const check of this.hostOfflineChecks.values()) clearTimeout(check.timer);- this.hostOfflineChecks.clear();- const fallback = this.options.sfuFallback;- if (!fallback) return;- for (const fence of fallback.admission.beginDrainAll()) {- this.scheduleSfuPublicationDrain(fence);- }- for (const [key, task] of [...this.sfuDrainTasks]) {- if (task.retryTimer) clearTimeout(task.retryTimer);- if (task.operation) await task.operation;- if (this.sfuDrainTasks.get(key) === task) await this.runSfuDrain(key, task);- }- }-- connectParticipant(input: AuthenticatedRouteParticipant): HybridAuthenticationState {- const room = this.room(input.roomId);- if (input.role === "host") {- if (room.controller && room.hostPeerId !== input.peerId) {- this.clearDeadline(room);- for (const viewerPeerId of this.options.roomStore.getViewerPeerIds(- input.roomId,- )) {- this.options.deleteConnectionId(input.roomId, viewerPeerId);- }- this.releaseResources(- room.controller.rebindHostIdentity(- input.peerId,- input.sessionId,- this.now(),- ),- );- }- room.hostPeerId = input.peerId;- this.cancelHostOfflineCheck(input.roomId);- if (!room.controller) this.createController(input.roomId, room, input);- } else {- room.advertisedCapacityByViewer.set(- input.peerId,- room.advertisedCapacityByViewer.get(input.peerId) ?? 0,- );- }- if (room.controller) {- this.releaseResources(- room.controller.upsertParticipant({- peerId: input.peerId,- role: input.role,- sessionId: input.sessionId,- effectiveDownstreamCapacity:- input.role === "host"- ? this.options.endpointMediaCopyCapacity- : (room.advertisedCapacityByViewer.get(input.peerId) ?? 0),- }, this.now()),- );- }- const snapshot = room.controller?.snapshot();- const assignment = snapshot- ? this.assignments(input.roomId, snapshot).get(input.peerId) ?? emptyAssignment()- : emptyAssignment();- if (input.role === "viewer") {- const edge = snapshot?.upstreamByViewer.get(input.peerId);- if (snapshot && edge && this.pathIsPhysical(input.roomId, snapshot, input.peerId)) {- this.options.setConnectionId(input.roomId, input.peerId, edge.connectionId);- } else {- this.options.deleteConnectionId(input.roomId, input.peerId);- }- }- return {- routeRevision: snapshot?.revision ?? 0,- routeAssignment: assignment,- };- }-- completeAuthentication(- participant: AuthenticatedRouteParticipant,- _state: HybridAuthenticationState,- ): void {- const room = this.rooms.get(participant.roomId);- if (!room?.controller) return;- this.broadcastActive(participant.roomId, room);- void this.sendFreshSfuConfig(participant).catch(() => undefined);- this.requestPump(participant.roomId);- }-- setPaused(roomId: string, paused: boolean): void {- const room = this.rooms.get(roomId);- if (!room?.controller) return;- const before = room.controller.snapshot().revision;- this.releaseResources(room.controller.setPaused(paused, this.now()));- if (room.controller.snapshot().revision !== before) this.broadcastActive(roomId, room);- if (!paused) this.requestPump(roomId);- }-- routeDiagnosticSnapshot(- roomId: string,- ): Extract<ServerMessage, { type: "route-diagnostic-snapshot" }>["snapshot"] {- return (- this.rooms.get(roomId)?.controller?.routeDiagnosticSnapshot(this.now()) ?? {- children: [],- operation: null,- }- );- }-- observeQualityEvidence(- input: Omit<RouteQualityEvidenceInput, "metrics"> & {- roomId: string;- metrics: ViewerQualityEvidenceMetrics;- },- ): RouteQualityEvidenceResult {- const { roomId, ...evidence } = input;- const result =- this.rooms.get(roomId)?.controller?.observeQualityEvidence(evidence) ??- "rejected";- if (result !== "rejected") {- this.debug(roomId, "viewer-quality-evidence", {- viewer: this.debugPeer(roomId, input.childPeerId),- upstream:- input.upstream.kind === "peer"- ? `p2p:${this.debugPeer(roomId, input.upstream.peerId)}`- : "sfu",- natTraversalPath: input.metrics.natTraversalPath,- framesPerSecond: input.metrics.framesPerSecond,- bitrateKbps: input.metrics.bitrateKbps,- width: input.metrics.width,- height: input.metrics.height,- framesDecoded: input.metrics.framesDecodedDelta,- freezes: input.metrics.freezeCountDelta,- pauses: input.metrics.pauseCountDelta,- packetsReceivedDelta: input.metrics.packetsReceivedDelta,- packetsLostDelta: input.metrics.packetsLostDelta,- packetLossPercent: packetLossPercentFromDeltas(- input.metrics.packetsReceivedDelta,- input.metrics.packetsLostDelta,- ),- rttMs: input.metrics.rttMs,- jitterMs: input.metrics.jitterMs,- });- }- return result;- }-- observeSenderQualityEvidence(- participant: AuthenticatedRouteParticipant,- message: Extract<ClientMessage, { type: "sender-quality-evidence" }>,- ): boolean {- const room = this.rooms.get(participant.roomId);- const controller = room?.controller;- if (!room || !controller) {- return false;- }- const snapshot = controller.snapshot();- const before = snapshot.revision;- const copyContext = this.qualityCopyContext(- snapshot,- room.hostPeerId ?? "",- participant.peerId,- participant.role === "host"- ? this.options.endpointMediaCopyCapacity- : Math.min(- room.advertisedCapacityByViewer.get(participant.peerId) ?? 0,- this.options.endpointMediaCopyCapacity,- ),- {- kind: "peer",- childPeerId: message.childPeerId,- routeRevision: message.routeRevision,- connectionId: message.connectionId,- },- );- const input: SenderQualityEvidenceInput = {- parentPeerId: participant.peerId,- parentSessionId: participant.sessionId,- childPeerId: message.childPeerId,- routeRevision: message.routeRevision,- connectionId: message.connectionId,- senderIdentity:- message.rtpStatsId && message.trackIdentifier- ? `${message.rtpStatsId}\u0000${message.trackIdentifier}`- : null,- sampleTimestampMs: message.sampleTimestampMs,- state: message.state,- acceptedAtMs: this.now(),- };- const result = controller.observeSenderQualityEvidence(- input,- (reservation) => this.commitReservation(reservation),- );- if (result.accepted) {- this.debug(participant.roomId, "sender-quality-evidence", {- parent: this.debugPeer(participant.roomId, participant.peerId),- child: this.debugPeer(participant.roomId, message.childPeerId),- routeRevision: message.routeRevision,- ...copyContext,- state: message.state,- natTraversalPath: message.diagnostics.natTraversalPath,- reason: message.diagnostics.reason,- framesPerSecond: message.diagnostics.framesPerSecond,- bitrateKbps: message.diagnostics.bitrateKbps,- captureFramesPerSecond:- message.diagnostics.captureFramesPerSecond ?? null,- mediaSourceFramesPerSecond:- message.diagnostics.mediaSourceFramesPerSecond ?? null,- width: message.diagnostics.width ?? null,- height: message.diagnostics.height ?? null,- availableOutgoingKbps:- message.diagnostics.availableOutgoingKbps ?? null,- rttMs: message.diagnostics.rttMs ?? null,- packetLossPercent: message.diagnostics.packetLossPercent ?? null,- });- }- this.releaseResources(result.released);- if (result.committed) {- this.resourceWaiters.delete(participant.roomId);- this.options.setConnectionId(- participant.roomId,- message.childPeerId,- message.connectionId,- );- }- if (controller.snapshot().revision !== before) {- this.broadcastActive(participant.roomId, room);- }- this.sendRouteFailures(- participant.roomId,- result.failedPeerIds,- controller.snapshot().revision,- );- if (result.accepted) {- this.requestPump(participant.roomId);- }- return result.accepted;- }-- observeSfuPublisherQualityEvidence(- participant: AuthenticatedRouteParticipant,- message: Extract<- ClientMessage,- { type: "sfu-publisher-quality-evidence" }- >,- ): boolean {- const room = this.rooms.get(participant.roomId);- const controller = room?.controller;- if (!room || !controller || participant.role !== "host") {- return false;- }- const snapshot = controller.snapshot();- const operation = snapshot.operation;- const candidateChildPeerId = operation?.childPeerId;- const candidateConnectionId = operation?.current?.connectionId;- const before = snapshot.revision;- const copyContext = this.qualityCopyContext(- snapshot,- participant.peerId,- participant.peerId,- this.options.endpointMediaCopyCapacity,- {- kind: "sfu",- routeRevision: message.routeRevision,- publicationGeneration: message.publicationGeneration,- hostSessionId: participant.sessionId,- },- );- const input: SfuPublisherQualityEvidenceInput = {- hostPeerId: participant.peerId,- hostSessionId: participant.sessionId,- publicationGeneration: message.publicationGeneration,- routeRevision: message.routeRevision,- state: message.state,- sampleTimestampMs: message.sampleTimestampMs,- acceptedAtMs: this.now(),- };- const result = controller.observeSfuPublisherQualityEvidence(- input,- (reservation) => this.commitReservation(reservation),- );- if (result.accepted) {- this.debug(participant.roomId, "sfu-publisher-quality-evidence", {- routeRevision: message.routeRevision,- ...copyContext,- state: message.state,- reason: message.diagnostics.reason,- framesPerSecond: message.diagnostics.framesPerSecond,- bitrateKbps: message.diagnostics.bitrateKbps,- captureFramesPerSecond:- message.diagnostics.captureFramesPerSecond ?? null,- mediaSourceFramesPerSecond:- message.diagnostics.mediaSourceFramesPerSecond ?? null,- width: message.diagnostics.width ?? null,- height: message.diagnostics.height ?? null,- videoEncodingCount:- message.diagnostics.videoEncodingCount ?? null,- activeVideoEncodingCount:- message.diagnostics.activeVideoEncodingCount ?? null,- availableOutgoingKbps:- message.diagnostics.availableOutgoingKbps ?? null,- rttMs: message.diagnostics.rttMs ?? null,- packetLossPercent: message.diagnostics.packetLossPercent ?? null,- });- }- this.releaseResources(result.released);- if (- result.committed &&- candidateChildPeerId &&- candidateConnectionId- ) {- this.resourceWaiters.delete(participant.roomId);- this.options.setConnectionId(- participant.roomId,- candidateChildPeerId,- candidateConnectionId,- );- }- if (controller.snapshot().revision !== before) {- this.broadcastActive(participant.roomId, room);- }- this.sendRouteFailures(- participant.roomId,- result.failedPeerIds,- controller.snapshot().revision,- );- if (result.accepted) {- this.requestPump(participant.roomId);- }- return result.accepted;- }-- resetSenderQuality(participant: AuthenticatedRouteParticipant): void {- const room = this.rooms.get(participant.roomId);- const controller = room?.controller;- if (!room || !controller) {- return;- }- const before = controller.snapshot().revision;- this.releaseResources(- controller.resetSenderQuality(- participant.peerId,- participant.sessionId,- this.now(),- ),- );- if (controller.snapshot().revision !== before) {- this.broadcastActive(participant.roomId, room);- }- this.requestPump(participant.roomId);- }-- isActivePeerParentOf(- roomId: string,- parentPeerId: string,- childPeerId: string,- ): boolean {- return this.resolveActivePeerEdge(roomId, childPeerId)?.parentPeerId === parentPeerId;- }-- resolveActivePeerEdge(- roomId: string,- childPeerId: string,- ): { revision: number; parentPeerId: string } | undefined {- const activeEdge = this.resolveActiveViewerMediaEdge(roomId, childPeerId);- return activeEdge?.upstream.kind === "peer"- ? {- revision: activeEdge.revision,- parentPeerId: activeEdge.upstream.peerId,- }- : undefined;- }-- resolveActiveViewerMediaEdge(- roomId: string,- childPeerId: string,- ): ActiveViewerMediaEdge | undefined {- const snapshot = this.rooms.get(roomId)?.controller?.snapshot();- const edge = snapshot?.upstreamByViewer.get(childPeerId);- if (- !snapshot ||- !edge ||- !this.pathIsPhysical(roomId, snapshot, childPeerId)- ) {- return undefined;- }- return edge.kind === "peer"- ? {- revision: snapshot.revision,- connectionId: edge.connectionId,- upstream: { kind: "peer", peerId: edge.parentPeerId },- }- : {- revision: snapshot.revision,- connectionId: edge.connectionId,- upstream: { kind: "sfu" },- };- }-- getViewerRouteUpstream(roomId: string, viewerPeerId: string): MediaRouteUpstream {- const snapshot = this.rooms.get(roomId)?.controller?.snapshot();- return snapshot- ? (this.assignments(roomId, snapshot).get(viewerPeerId)?.upstream ?? { kind: "none" })- : { kind: "none" };- }-- peerSignalAuthorization(input: {- roomId: string;- sourcePeerId: string;- sourceSessionId: string;- targetPeerId: string;- targetSessionId: string;- connectionId: string;- signalKind: "candidate" | "description";- descriptionType?: "offer" | "answer";- }): boolean | "probe" | undefined {- const controller = this.rooms.get(input.roomId)?.controller;- const snapshot = controller?.snapshot();- if (!controller || !snapshot) return undefined;- const operation = snapshot.operation;- const current = operation?.current;- if (operation && current?.tuple.kind === "peer") {- const parent = this.connectedPeer(input.roomId, current.tuple.parentPeerId);- const child = this.options.roomStore.getConnectedViewer(- input.roomId,- operation.childPeerId,- );- const parentToChild =- input.sourcePeerId === current.tuple.parentPeerId &&- input.targetPeerId === operation.childPeerId;- const childToParent =- input.sourcePeerId === operation.childPeerId &&- input.targetPeerId === current.tuple.parentPeerId;- if (parentToChild || childToParent) {- return Boolean(- parent &&- child &&- parent.sessionId === (parentToChild ? input.sourceSessionId : input.targetSessionId) &&- child.sessionId === (childToParent ? input.sourceSessionId : input.targetSessionId) &&- input.connectionId === current.connectionId &&- (input.signalKind === "candidate" ||- (parentToChild && input.descriptionType === "offer") ||- (childToParent && input.descriptionType === "answer")),- )- ? "probe"- : false;- }- }-- const childPeerId = this.childForPair(snapshot, input.sourcePeerId, input.targetPeerId);- const edge = childPeerId ? snapshot.upstreamByViewer.get(childPeerId) : undefined;- if (!childPeerId || edge?.kind !== "peer" || !edge.physicalActive) return undefined;- const parentToChild = input.sourcePeerId === edge.parentPeerId;- const sessionsMatch =- (parentToChild &&- input.sourceSessionId === edge.parentSessionId &&- input.targetSessionId === edge.childSessionId) ||- (!parentToChild &&- input.sourceSessionId === edge.childSessionId &&- input.targetSessionId === edge.parentSessionId);- if (!sessionsMatch) return false;- if (- edge.transport === "direct" &&- parentToChild &&- input.signalKind === "description" &&- input.descriptionType === "offer" &&- input.connectionId !== edge.connectionId- ) {- const adopted = controller.adoptDirectConnection({- childPeerId,- childSessionId: edge.childSessionId,- parentSessionId: edge.parentSessionId,- routeRevision: snapshot.revision,- connectionId: edge.connectionId,- newConnectionId: input.connectionId,- });- if (adopted) this.options.setConnectionId(input.roomId, childPeerId, input.connectionId);- return adopted;- }- return input.connectionId === edge.connectionId;- }-- debugPeerSignal(input: {- roomId: string;- sourcePeerId: string;- targetPeerId: string;- signalKind: "candidate" | "description";- candidateOrigin?: CandidateSignalOrigin;- descriptionType?: "offer" | "answer";- authorization: boolean | "probe" | undefined;- }): void {- this.debug(input.roomId, "peer-signal", {- source: this.debugPeer(input.roomId, input.sourcePeerId),- target: this.debugPeer(input.roomId, input.targetPeerId),- signalKind: input.signalKind,- candidateOrigin: input.candidateOrigin ?? null,- descriptionType: input.descriptionType ?? null,- authorization:- input.authorization === undefined ? "assignment" : input.authorization,- });- }-- setViewerRelayCapacity(- participant: AuthenticatedRouteParticipant,- downstreamEdges: number,- ): void {- const room = this.room(participant.roomId);- this.debug(participant.roomId, "relay-capacity-received", {- participant: this.debugPeer(participant.roomId, participant.peerId),- downstreamEdges,- });- room.advertisedCapacityByViewer.set(participant.peerId, downstreamEdges);- if (- room.controller?.setEffectiveCapacity(- participant.peerId,- participant.sessionId,- downstreamEdges,- this.now(),- )- ) {- this.requestPump(participant.roomId);- }- }-- handleRouteReady(- participant: AuthenticatedRouteParticipant,- message: Extract<ClientMessage, { type: "route-ready" }>,- ): void {- if (participant.role !== "viewer" || message.phase !== "prepare") return;- this.debug(participant.roomId, "route-ready-received", {- participant: this.debugPeer(participant.roomId, participant.peerId),- revision: message.revision,- });- const room = this.rooms.get(participant.roomId);- const controller = room?.controller;- const operation = controller?.snapshot().operation;- const current = operation?.current;- if (- !room ||- !controller ||- !operation ||- !current ||- operation.childPeerId !== participant.peerId ||- operation.childSessionId !== participant.sessionId ||- current.revision !== message.revision- ) {- return;- }- const before = controller.snapshot().revision;- const settled = controller.candidateReady(- {- childPeerId: participant.peerId,- childSessionId: participant.sessionId,- revision: message.revision,- connectionId: current.connectionId,- },- this.now(),- (reservation) => this.commitReservation(reservation),- { relativeQualityApproved: message.qualityApproved === true },- );- this.debug(participant.roomId, "route-ready-settled", {- participant: this.debugPeer(participant.roomId, participant.peerId),- revision: message.revision,- accepted: settled.accepted,- exhausted: settled.failedPeerIds.length > 0,- });- this.releaseResources(settled.released);- if (settled.committed !== false && settled.accepted) {- this.resourceWaiters.delete(participant.roomId);- this.options.setConnectionId(- participant.roomId,- participant.peerId,- current.connectionId,- );- }- if (controller.snapshot().revision !== before) this.broadcastActive(participant.roomId, room);- this.sendRouteFailures(- participant.roomId,- settled.failedPeerIds,- controller.snapshot().revision,- );- this.requestPump(participant.roomId);- }-- handleRouteTransportConnected(- participant: AuthenticatedRouteParticipant,- message: Extract<ClientMessage, { type: "route-transport-connected" }>,- ): void {- if (participant.role !== "viewer") return;- const room = this.rooms.get(participant.roomId);- const controller = room?.controller;- const operation = controller?.snapshot().operation;- const current = operation?.current;- if (- !room ||- !controller ||- !operation ||- !current ||- operation.childPeerId !== participant.peerId ||- operation.childSessionId !== participant.sessionId ||- current.revision !== message.revision ||- current.connectionId !== message.connectionId ||- current.tuple.kind !== "peer"- ) {- return;- }- const before = controller.snapshot().revision;- const progressed = controller.candidateTransportConnected(- {- childPeerId: participant.peerId,- childSessionId: participant.sessionId,- revision: message.revision,- connectionId: message.connectionId,- },- this.now(),- );- this.releaseResources(progressed.released);- if (controller.snapshot().revision !== before) {- this.broadcastActive(participant.roomId, room);- }- this.sendRouteFailures(- participant.roomId,- progressed.failedPeerIds,- controller.snapshot().revision,- );- const after = controller.snapshot().operation;- if (!progressed.accepted || after?.wakeAtMs !== operation.wakeAtMs) {- this.requestPump(participant.roomId);- }- }-- handleRouteMediaUnavailable(- participant: AuthenticatedRouteParticipant,- message: Extract<ClientMessage, { type: "route-media-unavailable" }>,- ): void {- if (participant.role !== "viewer") return;- this.debug(participant.roomId, "sfu-media-unavailable", {- participant: this.debugPeer(participant.roomId, participant.peerId),- revision: message.revision,- });- const room = this.rooms.get(participant.roomId);- const controller = room?.controller;- const snapshot = controller?.snapshot();- const edge = snapshot?.upstreamByViewer.get(participant.peerId);- if (- !room ||- !controller ||- !snapshot ||- snapshot.paused ||- snapshot.revision !== message.revision ||- edge?.kind !== "sfu" ||- edge.childSessionId !== participant.sessionId- ) {- return;- }- controller.invalidateEdge({- childPeerId: participant.peerId,- childSessionId: participant.sessionId,- routeRevision: snapshot.revision,- connectionId: edge.connectionId,- }, this.now());- this.requestPump(participant.roomId);- }-- handleRouteFailed(- participant: AuthenticatedRouteParticipant,- message: Extract<ClientMessage, { type: "route-failed" }>,- ): void {- this.debug(participant.roomId, "route-failed-received", {- participant: this.debugPeer(participant.roomId, participant.peerId),- role: participant.role,- phase: message.phase,- revision: message.revision,- hasConnectionId: Boolean(message.connectionId),- });- const room = this.rooms.get(participant.roomId);- const controller = room?.controller;- const snapshot = controller?.snapshot();- if (!room || !controller || !snapshot) return;- if (message.phase === "prepare") {- const operation = snapshot.operation;- const current = operation?.current;- if (!operation || !current || current.revision !== message.revision) return;- const ownsChild =- participant.role === "viewer" &&- participant.peerId === operation.childPeerId &&- participant.sessionId === operation.childSessionId;- const ownsParent =- current.tuple.kind === "peer" &&- participant.peerId === current.tuple.parentPeerId &&- this.connectedPeer(participant.roomId, participant.peerId)?.sessionId ===- participant.sessionId;- const ownsPublication =- current.tuple.kind === "sfu" &&- participant.role === "host" &&- participant.peerId === room.hostPeerId &&- this.options.roomStore.getConnectedHost(participant.roomId)- ?.sessionId === participant.sessionId;- if (!ownsChild && !ownsParent && !ownsPublication) return;- if (message.connectionId && message.connectionId !== current.connectionId) return;- const before = snapshot.revision;- const settled = controller.candidateFailed(- {- childPeerId: operation.childPeerId,- childSessionId: operation.childSessionId,- revision: current.revision,- connectionId: current.connectionId,- },- this.now(),- );- this.releaseResources(settled.released);- if (controller.snapshot().revision !== before) this.broadcastActive(participant.roomId, room);- this.sendRouteFailures(- participant.roomId,- settled.failedPeerIds,- controller.snapshot().revision,- );- this.requestPump(participant.roomId);- return;- }-- if (snapshot.revision !== message.revision) return;- if (participant.role === "host") {- if (- message.connectionId &&- controller.invalidateDirectEdgeFromParent(- {- parentPeerId: participant.peerId,- parentSessionId: participant.sessionId,- routeRevision: snapshot.revision,- connectionId: message.connectionId,- },- this.now(),- )- ) {- this.requestPump(participant.roomId);- return;- }- const publication = snapshot.hostPublication;- if (- !publication ||- publication.hostSessionId !== participant.sessionId ||- (message.connectionId && message.connectionId !== publication.connectionId)- ) {- return;- }- controller.invalidateHostPublication({- hostSessionId: participant.sessionId,- routeRevision: snapshot.revision,- generation: publication.generation,- connectionId: publication.connectionId,- }, this.now());- const invalid = controller.snapshot();- this.releaseResources(- controller.retireHostPublication({- hostSessionId: participant.sessionId,- routeRevision: invalid.revision,- generation: publication.generation,- connectionId: publication.connectionId,- }),- );- this.broadcastActive(participant.roomId, room);- this.requestPump(participant.roomId);- return;- }-- const edge = snapshot.upstreamByViewer.get(participant.peerId);- if (- !edge ||- edge.childSessionId !== participant.sessionId ||- (message.connectionId && message.connectionId !== edge.connectionId)- ) {- return;- }- const invalidated = controller.invalidateEdge({- childPeerId: participant.peerId,- childSessionId: participant.sessionId,- routeRevision: snapshot.revision,- connectionId: edge.connectionId,- ...(edge.kind === "peer" ? { parentSessionId: edge.parentSessionId } : {}),- }, this.now());- if (invalidated && edge.usable && snapshot.paused) {- this.options.onRoutesChanged?.(participant.roomId);- }- this.requestPump(participant.roomId);- }-- refreshSfu(participant: AuthenticatedRouteParticipant, revision: number): void {- const room = this.rooms.get(participant.roomId);- const snapshot = room?.controller?.snapshot();- if (!room || !snapshot || revision > snapshot.revision) return;- const currentRevision = snapshot.revision;- const key = `${currentRevision}\u0000${participant.peerId}\u0000${participant.sessionId}`;- if (room.sfuRefreshesInFlight.has(key)) return;- room.sfuRefreshesInFlight.add(key);- void this.sendFreshSfuConfig(participant)- .catch(() => this.failCurrentSfuRoute(participant, currentRevision))- .finally(() => room.sfuRefreshesInFlight.delete(key));- }-- private failCurrentSfuRoute(- participant: AuthenticatedRouteParticipant,- revision: number,- ): void {- const room = this.rooms.get(participant.roomId);- const snapshot = room?.controller?.snapshot();- if (!room || !snapshot || snapshot.revision !== revision) return;- const edge = snapshot.upstreamByViewer.get(participant.peerId);- const connectionId =- participant.peerId === room.hostPeerId- ? snapshot.hostPublication?.connectionId- : edge?.kind === "sfu"- ? edge.connectionId- : undefined;- if (!connectionId) return;- this.handleRouteFailed(participant, {- type: "route-failed",- revision,- phase: "active",- connectionId,- });- }-- disconnectParticipant(roomId: string, peerId: string, sessionId: string): void {- const room = this.rooms.get(roomId);- if (!room?.controller?.disconnectSession(peerId, sessionId)) return;- if (peerId === room.hostPeerId) this.scheduleHostOfflineCheck(roomId, peerId);- this.requestPump(roomId);- }-- removeViewer(roomId: string, peerId: string): void {- const room = this.rooms.get(roomId);- room?.advertisedCapacityByViewer.delete(peerId);- this.options.deleteConnectionId(roomId, peerId);- if (room?.controller?.confirmDeparture(peerId, this.now())) {- this.requestPump(roomId);- } else if (room && !room.controller && room.advertisedCapacityByViewer.size === 0) {- this.rooms.delete(roomId);- }- }-- stopRoom(roomId: string): void {- const capacities = new Map(- this.rooms.get(roomId)?.advertisedCapacityByViewer ?? [],- );- this.clearRoom(roomId);- if (capacities.size > 0) {- const room = this.room(roomId);- for (const [peerId, capacity] of capacities) {- room.advertisedCapacityByViewer.set(peerId, capacity);- }- }- }-- deleteRoom(roomId: string): void {- this.clearRoom(roomId);- }-- private room(roomId: string): RoomRuntime {- let room = this.rooms.get(roomId);- if (!room) {- room = {- advertisedCapacityByViewer: new Map(),- requested: false,- sfuRefreshesInFlight: new Set(),- };- this.rooms.set(roomId, room);- }- return room;- }-- private createController(- roomId: string,- room: RoomRuntime,- host: AuthenticatedRouteParticipant,- ): void {- const routePolicy = host.routePolicy;- room.controller = new RoomRouteController<RouteResource>({- hostPeerId: host.peerId,- debugRoomId: roomId,- endpointMediaCopyCapacity: this.options.endpointMediaCopyCapacity,- operationTimeoutMs:- this.options.sfuFallback?.prepareTimeoutMs ?? DEFAULT_ROUTE_OPERATION_TIMEOUT_MS,- sfuEnabled: Boolean(this.options.sfuFallback) && routePolicy?.peerOnly !== true,- qualityConvergenceEnabled:- routePolicy?.topologyOptimization === true,- natPredictionEnabled: routePolicy?.natPrediction === true,- });- room.controller.upsertParticipant({- peerId: host.peerId,- role: "host",- sessionId: host.sessionId,- effectiveDownstreamCapacity: this.options.endpointMediaCopyCapacity,- }, this.now());- for (const viewer of this.options.roomStore.getConnectedViewers(roomId)) {- room.controller.upsertParticipant({- peerId: viewer.peerId,- role: "viewer",- sessionId: viewer.sessionId,- effectiveDownstreamCapacity:- room.advertisedCapacityByViewer.get(viewer.peerId) ?? 0,- }, this.now());- }- }-- private requestPump(roomId: string): void {- const room = this.rooms.get(roomId);- if (!room?.controller || this.closing) return;- room.requested = true;- if (room.pump) return;- room.pump = (async () => {- try {- while (room.requested && !this.closing) {- room.requested = false;- await this.pumpRoom(roomId, room);- }- } finally {- room.pump = undefined;- if (room.requested && !this.closing) this.requestPump(roomId);- }- })().catch(() => {- console.error("Media route reconciliation failed");- this.sendRoomError(roomId, "SERVER_ERROR", "Media routing failed");- });- }-- private async pumpRoom(roomId: string, room: RoomRuntime): Promise<void> {- const controller = room.controller;- if (!controller) return;- let broadcastRevision = controller.snapshot().revision;- const broadcastRevisionChange = (): void => {- const revision = controller.snapshot().revision;- if (revision === broadcastRevision) return;- this.broadcastActive(roomId, room);- broadcastRevision = revision;- };- for (;;) {- const reconciled = controller.reconcile(this.now());- this.releaseResources(reconciled.released);- broadcastRevisionChange();- this.sendRouteFailures(- roomId,- reconciled.failedPeerIds,- controller.snapshot().revision,- );- const operation = reconciled.operation ?? controller.snapshot().operation;- if (!operation) {- this.clearDeadline(room);- this.resourceWaiters.delete(roomId);- return;- }- if (operation.current) {- this.resourceWaiters.delete(roomId);- this.scheduleDeadline(roomId, room, operation);- return;- }- const plan = operation.candidates[operation.cursor];- if (!plan) {- this.resourceWaiters.delete(roomId);- return;- }- const guard = cursorGuard(operation, plan);- this.resourceWaiters.delete(roomId);- const preparation = await this.prepareCandidate(- roomId,- room,- operation,- plan,- operation.baseRevision +- (plan.endpointTransition.kind === "bounded-gap" ? 2 : 1),- );- if (preparation.kind === "denied") {- this.debug(roomId, "candidate-preparation-denied", {- child: this.debugPeer(roomId, operation.childPeerId),- route: this.debugTuple(roomId, plan.tuple),- rejectionBucket: preparation.rejectionBucket,- cursor: operation.cursor,- });- if (- operation.reason === "quality-convergence" ||- operation.reason === "root-convergence"- ) {- const skipped = controller.skipCurrentCandidate(- guard,- this.now(),- preparation.rejectionBucket,- );- this.releaseResources(skipped.released);- continue;- }- if (preparation.rejectionBucket !== "sfu-admission") {- this.resourceWaiters.delete(roomId);- }- if (preparation.rejectionBucket === "sfu-admission") {- if (- !controller.noteCurrentCandidateRejection(- guard,- "sfu-admission",- )- ) {- continue;- }- this.resourceWaiters.add(roomId);- this.sendViewerRouteStatus(roomId, operation.demandPeerId, {- type: "route-status",- revision: operation.baseRevision,- state: "waiting",- reason: "sfu-admission",- });- this.scheduleDeadline(roomId, room, operation);- return;- }- const skipped = controller.skipCurrentCandidate(- guard,- this.now(),- preparation.rejectionBucket,- );- this.releaseResources(skipped.released);- this.sendRouteFailures(- roomId,- skipped.failedPeerIds,- controller.snapshot().revision,- );- continue;- }- this.resourceWaiters.delete(roomId);- this.debug(roomId, "candidate-prepared", {- child: this.debugPeer(roomId, operation.childPeerId),- route: this.debugTuple(roomId, plan.tuple),- cursor: operation.cursor,- });- let beginGuard = guard;- let currentOperation = controller.snapshot().operation;- if (plan.endpointTransition.kind === "bounded-gap") {- const gap = controller.retireCurrentCandidateProducer(guard, this.now());- this.releaseResources(gap.released);- this.sendRouteFailures(- roomId,- gap.failedPeerIds,- controller.snapshot().revision,- );- if (!gap.accepted) {- this.releaseReservation(preparation.prepared.reservation);- continue;- }- broadcastRevisionChange();- currentOperation = controller.snapshot().operation;- const currentPlan = currentOperation?.candidates[currentOperation.cursor];- if (!currentOperation || !currentPlan) {- this.releaseReservation(preparation.prepared.reservation);- continue;- }- beginGuard = cursorGuard(currentOperation, currentPlan);- }- const begun = controller.beginCurrentCandidate({- guard: beginGuard,- nowMs: this.now(),- connectionId: preparation.prepared.connectionId,- reservation: preparation.prepared.reservation,- publicationGeneration: preparation.prepared.publicationGeneration,- publicationConnectionId: preparation.prepared.publicationConnectionId,- hostSessionId: preparation.prepared.hostSessionId,- });- this.debug(roomId, "candidate-begin-settled", {- child: this.debugPeer(roomId, operation.childPeerId),- route: this.debugTuple(roomId, plan.tuple),- accepted: begun.accepted,- exhausted: begun.failedPeerIds.length > 0,- });- this.releaseResources(begun.released);- if (!begun.accepted || !begun.operation?.current) {- this.sendRouteFailures(- roomId,- begun.failedPeerIds,- controller.snapshot().revision,- );- continue;- }- this.sendPrepareMessages(- roomId,- room,- begun.operation,- preparation.prepared,- );- this.debug(roomId, "candidate-prepare-sent", {- child: this.debugPeer(roomId, operation.childPeerId),- route: this.debugTuple(roomId, plan.tuple),- revision: begun.operation.current.revision,- });- this.scheduleDeadline(roomId, room, begun.operation);- return;- }- }-- private async prepareCandidate(- roomId: string,- room: RoomRuntime,- operation: OperationSnapshot,- plan: CandidatePlan,- revision: number,- ): Promise<PrepareResult> {- const snapshot = room.controller!.snapshot();- const child = this.options.roomStore.getConnectedViewer(roomId, operation.childPeerId);- const shareGeneration = this.options.getShareGeneration(roomId);- if (!child || child.sessionId !== operation.childSessionId || !shareGeneration) {- return { kind: "denied", rejectionBucket: "stale" };- }- const connectionId = opaqueId();- const overlap =- plan.endpointTransition.kind === "overlap"- ? overlapResource(plan.endpointTransition.producerPeerId)- : undefined;- if (plan.tuple.kind === "peer") {- return {- kind: "ready",- prepared: {- connectionId,- reservation: { kind: "direct", ...(overlap ? { overlap } : {}) },- },- };- }-- const fallback = this.options.sfuFallback;- const host = this.options.roomStore.getConnectedHost(roomId);- if (- !fallback ||- !host ||- host.peerId !== room.hostPeerId- ) {- return { kind: "denied", rejectionBucket: "stale" };- }- if (plan.tuple.publication === "reuse") {- const publication = snapshot.hostPublication;- if (- !publication ||- publication.resource.kind !== "sfu-publication"- ) {- return { kind: "denied", rejectionBucket: "stale" };- }- const fence: SfuSubscriptionFence = {- ...publication.resource.fence,- viewerPeerId: operation.childPeerId,- };- const currentEdge = snapshot.upstreamByViewer.get(operation.childPeerId);- const borrowedEdge =- currentEdge?.kind === "sfu" &&- currentEdge.publicationGeneration === publication.generation &&- currentEdge.resource.kind === "sfu-subscription" &&- !currentEdge.resource.released- ? currentEdge.resource- : null;- if (!borrowedEdge && !(await this.reserveSfuSubscription(fence))) {- return { kind: "denied", rejectionBucket: "sfu-admission" };- }- const edge = borrowedEdge ?? subscriptionResource(fence);- try {- const token = await fallback.tokenIssuer.issueToken({- roomId,- role: "viewer",- peerId: operation.childPeerId,- shareGeneration,- publicationGeneration: publication.generation,- });- return {- kind: "ready",- prepared: {- connectionId,- hostSessionId: host.sessionId,- reservation: {- kind: "sfu-reuse",- edge,- ...(borrowedEdge ? { borrowed: true as const } : {}),- ...(overlap ? { overlap } : {}),- },- publicationGeneration: publication.generation,- viewerSfuConfig: {- type: "sfu-config",- revision,- url: fallback.url,- token,- },- },- };- } catch {- if (!borrowedEdge) this.releaseResource(edge);- return { kind: "denied", rejectionBucket: "candidate-failed" };- }- }-- return await this.prepareNewPublication(- roomId,- operation,- revision,- connectionId,- shareGeneration,- host,- overlap,- );- }-- private async prepareNewPublication(- roomId: string,- operation: OperationSnapshot,- revision: number,- connectionId: string,- shareGeneration: string,- host: { peerId: string; sessionId: string },- overlap?: OverlapRouteResource,- ): Promise<PrepareResult> {- const fallback = this.options.sfuFallback!;- const publicationGeneration = opaqueId();- const publicationFence: SfuResourceFence = {- roomId,- shareGeneration,- publicationGeneration,- };- const subscriptionFence: SfuSubscriptionFence = {- ...publicationFence,- viewerPeerId: operation.childPeerId,- };- if (!fallback.admission.reservePublication(publicationFence)) {- return { kind: "denied", rejectionBucket: "sfu-admission" };- }- if (!fallback.admission.reserveSubscription(subscriptionFence)) {- fallback.admission.beginDrain(publicationFence);- this.scheduleSfuPublicationDrain(publicationFence);- return { kind: "denied", rejectionBucket: "sfu-admission" };- }- const subscription = subscriptionResource(subscriptionFence);- const publicationConnectionId = publicationGeneration;- const publication = publicationResource(publicationFence);- try {- await fallback.roomControl.createRoom(publicationFence);- const [hostToken, viewerToken] = await Promise.all([- fallback.tokenIssuer.issueToken({- roomId,- role: "host",- peerId: host.peerId,- shareGeneration,- publicationGeneration,- }),- fallback.tokenIssuer.issueToken({- roomId,- role: "viewer",- peerId: operation.childPeerId,- shareGeneration,- publicationGeneration,- }),- ]);- return {- kind: "ready",- prepared: {- connectionId,- hostSessionId: host.sessionId,- publicationGeneration,- publicationConnectionId,- reservation: {- kind: "sfu-create",- edge: subscription,- publication,- ...(overlap ? { overlap } : {}),- },- hostSfuConfig: {- type: "sfu-config",- revision,- url: fallback.url,- token: hostToken,- },- viewerSfuConfig: {- type: "sfu-config",- revision,- url: fallback.url,- token: viewerToken,- },- },- };- } catch {- this.releaseResource(subscription);- this.releaseResource(publication);- return { kind: "denied", rejectionBucket: "candidate-failed" };- }- }-- private sendPrepareMessages(- roomId: string,- room: RoomRuntime,- operation: OperationSnapshot,- prepared: PreparedCandidate,- ): void {- const current = operation.current!;- const candidate = preparedRouteCandidate(operation, current.tuple, current.connectionId);- const assignments = this.assignments(- roomId,- room.controller!.snapshot(),- current.tuple,- operation.childPeerId,- prepared.publicationGeneration,- );- const child = this.options.roomStore.getConnectedViewer(roomId, operation.childPeerId);- if (!child || child.sessionId !== operation.childSessionId) return;- const childUpdate: ServerMessage = {- type: "route-update",- revision: current.revision,- phase: "prepare",- assignment: assignments.get(operation.childPeerId) ?? emptyAssignment(),- candidate,- };- if (current.tuple.kind === "peer") {- const parent = this.connectedPeer(roomId, current.tuple.parentPeerId);- if (!parent) return;- this.options.sendToSession(child.sessionId, childUpdate);- this.options.sendToSession(parent.sessionId, {- type: "route-update",- revision: current.revision,- phase: "prepare",- assignment: assignments.get(parent.peerId) ?? emptyAssignment(),- candidate,- });- return;- }- const host = this.options.roomStore.getConnectedHost(roomId);- if (- prepared.hostSfuConfig &&- host &&- host.sessionId === prepared.hostSessionId- ) {- this.options.sendToSession(host.sessionId, {- type: "route-update",- revision: current.revision,- phase: "prepare",- assignment: assignments.get(host.peerId) ?? emptyAssignment(),- candidate,- });- this.options.sendToSession(host.sessionId, prepared.hostSfuConfig);- }- this.options.sendToSession(child.sessionId, childUpdate);- if (prepared.viewerSfuConfig) {- this.options.sendToSession(child.sessionId, prepared.viewerSfuConfig);- }- }-- private assignments(- roomId: string,- snapshot: RouteSnapshot<RouteResource>,- candidateTuple?: CandidateTuple,- candidateChildPeerId?: string,- candidatePublicationGeneration?: string,- ): Map<string, ParticipantRouteAssignment> {- const hostPeerId = this.rooms.get(roomId)?.hostPeerId;- if (!hostPeerId) return new Map();- const peerIds = new Set([hostPeerId, ...this.options.roomStore.getViewerPeerIds(roomId)]);- const edges = new Map<- string,- { kind: "peer"; parentPeerId: string } | { kind: "sfu"; publicationGeneration: string }- >();- for (const [childPeerId, edge] of snapshot.upstreamByViewer) {- if (!edge.physicalActive) continue;- edges.set(- childPeerId,- edge.kind === "peer"- ? { kind: "peer", parentPeerId: edge.parentPeerId }- : { kind: "sfu", publicationGeneration: edge.publicationGeneration },- );- }- let publicationGeneration = snapshot.hostPublication?.physicalActive- ? snapshot.hostPublication.generation- : null;- if (candidateTuple && candidateChildPeerId) {- edges.delete(candidateChildPeerId);- if (candidateTuple.kind === "peer") {- edges.set(candidateChildPeerId, {- kind: "peer",- parentPeerId: candidateTuple.parentPeerId,- });- const old = snapshot.upstreamByViewer.get(candidateChildPeerId);- if (- old?.kind === "sfu" &&- [...edges.values()].every((edge) => edge.kind !== "sfu")- ) {- publicationGeneration = null;- }- } else {- if (candidateTuple.publication !== "reuse") {- for (const [peerId, edge] of [...edges]) {- if (edge.kind === "sfu") edges.delete(peerId);- }- publicationGeneration = candidatePublicationGeneration ?? null;- }- if (publicationGeneration) {- edges.set(candidateChildPeerId, {- kind: "sfu",- publicationGeneration,- });- }- }- }- const sourceReachable = (peerId: string, seen = new Set<string>()): boolean => {- if (peerId === hostPeerId) return true;- if (seen.has(peerId)) return false;- seen.add(peerId);- const edge = edges.get(peerId);- if (!edge) return false;- return edge.kind === "sfu"- ? publicationGeneration === edge.publicationGeneration- : sourceReachable(edge.parentPeerId, seen);- };- const assignments = new Map<string, ParticipantRouteAssignment>();- for (const peerId of peerIds) {- const edge = edges.get(peerId);- const reachable = sourceReachable(peerId);- const childPeerIds = [...edges]- .filter(([, candidate]) =>- candidate.kind === "peer" &&- candidate.parentPeerId === peerId,- )- .map(([childPeerId]) => childPeerId);- assignments.set(peerId, {- upstream:- peerId === hostPeerId || !edge- ? { kind: "none" }- : edge.kind === "peer"- ? { kind: "peer", peerId: edge.parentPeerId }- : reachable- ? { kind: "sfu" }- : { kind: "none" },- childPeerIds,- sfuPublicationGeneration:- peerId === hostPeerId- ? publicationGeneration- : reachable && edge?.kind === "sfu"- ? edge.publicationGeneration- : null,- });- }- return assignments;- }-- private broadcastActive(roomId: string, room: RoomRuntime): void {- const snapshot = room.controller?.snapshot();- if (!snapshot) return;- this.debug(roomId, "active-topology", {- revision: snapshot.revision,- paused: snapshot.paused,- hostPublication: snapshot.hostPublication?.physicalActive === true,- routes: [...snapshot.upstreamByViewer].map(([childPeerId, edge]) => ({- child: this.debugPeer(roomId, childPeerId),- parent:- edge.kind === "peer"- ? this.debugPeer(roomId, edge.parentPeerId)- : "sfu",- usable: edge.usable,- physicalActive: edge.physicalActive,- })),- });- const assignments = this.assignments(roomId, snapshot);- const participants = [- this.options.roomStore.getConnectedHost(roomId),- ...this.options.roomStore.getConnectedViewers(roomId),- ].filter((peer): peer is { peerId: string; sessionId: string } => Boolean(peer));- for (const participant of participants) {- const assignment = assignments.get(participant.peerId) ?? emptyAssignment();- this.options.sendToSession(participant.sessionId, {- type: "route-update",- revision: snapshot.revision,- phase: "active",- assignment,- });- if (participant.peerId !== room.hostPeerId) {- const edge = snapshot.upstreamByViewer.get(participant.peerId);- if (edge && this.pathIsPhysical(roomId, snapshot, participant.peerId)) {- this.options.setConnectionId(roomId, participant.peerId, edge.connectionId);- } else {- this.options.deleteConnectionId(roomId, participant.peerId);- }- }- }- this.options.onRoutesChanged?.(roomId);- }-- private pathIsPhysical(- roomId: string,- snapshot: RouteSnapshot<RouteResource>,- childPeerId: string,- ): boolean {- const hostPeerId = this.rooms.get(roomId)?.hostPeerId;- if (!hostPeerId) return false;- const seen = new Set<string>();- let current = childPeerId;- while (current !== hostPeerId) {- if (seen.has(current)) return false;- seen.add(current);- const edge = snapshot.upstreamByViewer.get(current);- if (!edge?.physicalActive || !edge.usable) return false;- if (edge.kind === "sfu") {- return Boolean(- snapshot.hostPublication?.physicalActive &&- snapshot.hostPublication.generation === edge.publicationGeneration,- );- }- if (edge.parentPeerId === hostPeerId) return true;- current = edge.parentPeerId;- }- return true;- }-- private childForPair(- snapshot: RouteSnapshot<RouteResource>,- firstPeerId: string,- secondPeerId: string,- ): string | undefined {- const first = snapshot.upstreamByViewer.get(firstPeerId);- if (first?.kind === "peer" && first.parentPeerId === secondPeerId) return firstPeerId;- const second = snapshot.upstreamByViewer.get(secondPeerId);- return second?.kind === "peer" && second.parentPeerId === firstPeerId- ? secondPeerId- : undefined;- }-- private connectedPeer(roomId: string, peerId: string) {- const host = this.options.roomStore.getConnectedHost(roomId);- return host?.peerId === peerId- ? host- : this.options.roomStore.getConnectedViewer(roomId, peerId);- }-- private commitReservation(- reservation: CandidateReservation<RouteResource>,- ): boolean {- if (reservation.kind === "direct") return true;- if (reservation.kind === "sfu-reuse") {- return reservation.edge.kind === "sfu-subscription" &&- this.options.sfuFallback?.admission.commitSubscription(- reservation.edge.fence,- ) === true;- }- if (reservation.publication.kind !== "sfu-publication") return false;- const draining = this.options.sfuFallback?.admission.commitPublication(- reservation.publication.fence,- );- if (!draining) return false;- for (const fence of draining) this.scheduleSfuPublicationDrain(fence);- return true;- }-- private releaseReservation(reservation: CandidateReservation<RouteResource>): void {- this.releaseResources(reservationResources(reservation));- }-- private releaseResources(resources: readonly RouteResource[]): void {- // Publication drains own accounting; subscription drains only remove exact participants.- for (const resource of resources) {- if (resource.kind === "sfu-publication") this.releaseResource(resource);- }- for (const resource of resources) {- if (resource.kind !== "sfu-publication") this.releaseResource(resource);- }- }-- private releaseResource(resource: RouteResource): void {- if (resource.released) return;- resource.released = true;- if (resource.kind === "overlap") return;- if (resource.kind === "sfu-subscription") {- this.releaseSubscription(resource.fence);- return;- }- if (this.options.sfuFallback?.admission.beginDrain(resource.fence)) {- this.scheduleSfuPublicationDrain(resource.fence);- }- }-- private releaseSubscription(fence: SfuSubscriptionFence): boolean {- const admission = this.options.sfuFallback?.admission;- if (!admission) return false;- const accepted = admission.beginSubscriptionDrain(fence);- if (accepted) this.scheduleSfuSubscriptionDrain(fence);- return accepted;- }-- private async reserveSfuSubscription(- fence: SfuSubscriptionFence,- ): Promise<boolean> {- const fallback = this.options.sfuFallback;- if (!fallback) return false;- const key = sfuDrainKey({ kind: "subscription", fence });- const pending = this.sfuDrainTasks.get(key);- if (pending?.operation) {- try {- await pending.operation;- } catch {- return false;- }- if (this.sfuDrainTasks.get(key) === pending) return false;- }- const task = this.sfuDrainTasks.get(key);- if (task?.kind === "subscription") {- if (task.retryTimer) clearTimeout(task.retryTimer);- this.sfuDrainTasks.delete(key);- }- return fallback.admission.reserveSubscription(fence);- }-- private wakeResourceWaiters(): void {- const roomIds = [...this.resourceWaiters];- this.resourceWaiters.clear();- for (const roomId of roomIds) {- const controller = this.rooms.get(roomId)?.controller;- if (!controller) continue;- controller.touchExternalFacts();- this.requestPump(roomId);- }- }-- private scheduleDeadline(- roomId: string,- room: RoomRuntime,- operation: OperationSnapshot,- ): void {- this.clearDeadline(room);- this.debug(roomId, "deadline-scheduled", {- child: this.debugPeer(roomId, operation.childPeerId),- wakeInMs: Math.max(0, operation.wakeAtMs - this.now()),- cursor: operation.cursor,- candidateCount: operation.candidates.length,- current: operation.current- ? this.debugTuple(roomId, operation.current.tuple)- : null,- });- const timer = setTimeout(() => {- if (room.deadlineTimer !== timer || !room.controller) return;- room.deadlineTimer = undefined;- const before = room.controller.snapshot().revision;- const expired = room.controller.operationExpired(this.now());- this.debug(roomId, "deadline-fired", {- child: this.debugPeer(roomId, operation.childPeerId),- accepted: expired.accepted,- exhausted: expired.failedPeerIds.length > 0,- });- this.releaseResources(expired.released);- if (room.controller.snapshot().revision !== before) this.broadcastActive(roomId, room);- this.sendRouteFailures(- roomId,- expired.failedPeerIds,- room.controller.snapshot().revision,- );- this.requestPump(roomId);- }, Math.max(0, operation.wakeAtMs - this.now()));- timer.unref();- room.deadlineTimer = timer;- }-- private clearDeadline(room: RoomRuntime): void {- if (room.deadlineTimer) clearTimeout(room.deadlineTimer);- room.deadlineTimer = undefined;- }-- private async sendFreshSfuConfig(- participant: AuthenticatedRouteParticipant,- ): Promise<void> {- const fallback = this.options.sfuFallback;- const room = this.rooms.get(participant.roomId);- const snapshot = room?.controller?.snapshot();- const publication = snapshot?.hostPublication;- const shareGeneration = this.options.getShareGeneration(participant.roomId);- if (!fallback || !room || !snapshot || !publication?.physicalActive || !shareGeneration) {- return;- }- const isHost = participant.peerId === room.hostPeerId;- const edge = snapshot.upstreamByViewer.get(participant.peerId);- if (!isHost && (edge?.kind !== "sfu" || !edge.physicalActive)) return;- const token = await fallback.tokenIssuer.issueToken({- roomId: participant.roomId,- role: isHost ? "host" : "viewer",- peerId: participant.peerId,- shareGeneration,- publicationGeneration: publication.generation,- });- const current = room.controller?.snapshot();- if (- current?.revision !== snapshot.revision ||- current.hostPublication?.generation !== publication.generation ||- this.connectedPeer(participant.roomId, participant.peerId)?.sessionId !==- participant.sessionId- ) {- return;- }- this.options.sendToSession(participant.sessionId, {- type: "sfu-config",- revision: snapshot.revision,- url: fallback.url,- token,- });- }-- private activeHostPublication(- roomId: string,- ): Omit<HostOfflineCheck, "hostPeerId" | "timer"> | null {- const publication = this.rooms.get(roomId)?.controller?.snapshot().hostPublication;- return publication?.physicalActive &&- publication.resource.kind === "sfu-publication"- ? {- fence: publication.resource.fence,- hostSessionId: publication.hostSessionId,- connectionId: publication.connectionId,- }- : null;- }-- private scheduleHostOfflineCheck(roomId: string, hostPeerId: string): void {- this.cancelHostOfflineCheck(roomId);- const fallback = this.options.sfuFallback;- const publication = this.activeHostPublication(roomId);- if (!fallback || !publication || this.closing) return;- const timer = setTimeout(() => {- void this.checkHostOffline(roomId).catch(() => undefined);- }, fallback.hostOfflineCheckMs ?? DEFAULT_HOST_OFFLINE_CHECK_MS);- timer.unref();- this.hostOfflineChecks.set(roomId, {- hostPeerId,- ...publication,- timer,- });- }-- private async checkHostOffline(roomId: string): Promise<void> {- const check = this.hostOfflineChecks.get(roomId);- const fallback = this.options.sfuFallback;- if (!check || !fallback || this.closing) return;- if (this.options.roomStore.getConnectedHost(roomId)) {- this.cancelHostOfflineCheck(roomId);- return;- }- let exists = true;- try {- exists = await fallback.roomControl.hostParticipantExists(check.fence);- } catch {- if (this.hostOfflineChecks.get(roomId) !== check) return;- this.hostOfflineChecks.delete(roomId);- this.scheduleHostOfflineCheck(roomId, check.hostPeerId);- return;- }- if (this.hostOfflineChecks.get(roomId) !== check) return;- this.hostOfflineChecks.delete(roomId);- if (exists) {- this.scheduleHostOfflineCheck(roomId, check.hostPeerId);- return;- }- const room = this.rooms.get(roomId);- const controller = room?.controller;- const snapshot = controller?.snapshot();- const publication = snapshot?.hostPublication;- if (!room || !controller || !snapshot || !publication) return;- if (- publication.resource.kind !== "sfu-publication" ||- publication.resource.fence.roomId !== check.fence.roomId ||- publication.resource.fence.shareGeneration !==- check.fence.shareGeneration ||- publication.resource.fence.publicationGeneration !==- check.fence.publicationGeneration ||- publication.generation !== check.fence.publicationGeneration ||- publication.hostSessionId !== check.hostSessionId ||- publication.connectionId !== check.connectionId ||- !publication.physicalActive- ) {- this.scheduleHostOfflineCheck(roomId, check.hostPeerId);- return;- }- const beforeRevision = snapshot.revision;- controller.invalidateHostPublication({- hostSessionId: publication.hostSessionId,- routeRevision: snapshot.revision,- generation: publication.generation,- connectionId: publication.connectionId,- }, this.now());- const invalid = controller.snapshot();- this.releaseResources(- controller.retireHostPublication({- hostSessionId: publication.hostSessionId,- routeRevision: invalid.revision,- generation: publication.generation,- connectionId: publication.connectionId,- }),- );- const afterRetirement = controller.snapshot().hostPublication;- if (- afterRetirement?.generation === publication.generation &&- afterRetirement.connectionId === publication.connectionId &&- afterRetirement.physicalActive- ) {- if (controller.snapshot().revision !== beforeRevision) {- this.broadcastActive(roomId, room);- }- this.scheduleHostOfflineCheck(roomId, check.hostPeerId);- this.requestPump(roomId);- return;- }- this.broadcastActive(roomId, room);- this.requestPump(roomId);- }-- private cancelHostOfflineCheck(roomId: string): void {- const check = this.hostOfflineChecks.get(roomId);- if (check) clearTimeout(check.timer);- this.hostOfflineChecks.delete(roomId);- }-- private scheduleSfuPublicationDrain(fence: SfuResourceFence): void {- const roomName = managedSfuRoomName(fence);- for (const [key, task] of this.sfuDrainTasks) {- if (- task.kind === "subscription" &&- managedSfuRoomName(task.fence) === roomName- ) {- if (task.retryTimer) clearTimeout(task.retryTimer);- this.sfuDrainTasks.delete(key);- }- }- this.scheduleSfuDrain({ kind: "publication", fence });- }-- private scheduleSfuSubscriptionDrain(fence: SfuSubscriptionFence): void {- if (this.sfuDrainTasks.has(managedSfuRoomName(fence))) return;- this.scheduleSfuDrain({ kind: "subscription", fence });- }-- private scheduleSfuDrain(target: SfuDrainTarget): void {- if (!this.options.sfuFallback) return;- const key = sfuDrainKey(target);- let task = this.sfuDrainTasks.get(key);- if (!task) {- task =- target.kind === "publication"- ? { kind: "publication", fence: { ...target.fence } }- : { kind: "subscription", fence: { ...target.fence } };- this.sfuDrainTasks.set(key, task);- }- if (!task.operation && !task.retryTimer) {- void this.runSfuDrain(key, task).catch(() => undefined);- }- }-- private runSfuDrain(key: string, task: SfuDrainTask): Promise<void> {- if (task.operation) return task.operation;- const fallback = this.options.sfuFallback;- if (!fallback) return Promise.resolve();- let tracked!: Promise<void>;- tracked = (async () => {- try {- if (task.kind === "publication") {- await fallback.roomControl.deleteRoom(task.fence);- } else {- await fallback.roomControl.drainSubscription(task.fence);- }- if (this.sfuDrainTasks.get(key) !== task) return;- if (- task.kind === "publication" &&- !fallback.admission.completeDrain(task.fence)- ) {- throw new Error("LiveKit drain has no matching resource generation");- }- this.sfuDrainTasks.delete(key);- if (task.kind === "publication") {- this.wakeResourceWaiters();- } else {- this.requestPump(task.fence.roomId);- }- } catch (error) {- if (this.sfuDrainTasks.get(key) !== task) return;- if (this.closing) throw error;- task.retryTimer = setTimeout(() => {- task.retryTimer = undefined;- void this.runSfuDrain(key, task).catch(() => undefined);- }, fallback.drainRetryMs ?? DEFAULT_SFU_DRAIN_RETRY_MS);- task.retryTimer.unref();- }- })().finally(() => {- if (task.operation === tracked) task.operation = undefined;- });- task.operation = tracked;- return tracked;- }-- private clearRoom(roomId: string): void {- const room = this.rooms.get(roomId);- if (!room) return;- this.clearDeadline(room);- this.cancelHostOfflineCheck(roomId);- const controller = room.controller;- room.controller = undefined;- room.requested = false;- if (controller) this.releaseResources(controller.dispose());- this.rooms.delete(roomId);- this.resourceWaiters.delete(roomId);- for (const fence of this.options.sfuFallback?.admission.beginDrainRoom(roomId) ?? []) {- this.scheduleSfuPublicationDrain(fence);- }- }-- private debugPeer(roomId: string, peerId: string): string {- const room = this.rooms.get(roomId);- if (peerId === room?.hostPeerId) return "host";- return (- room?.controller?.diagnosticParticipantLabel(peerId) ?? "viewer-unknown"- );- }-- private qualityCopyContext(- snapshot: RouteSnapshot<RouteResource>,- hostPeerId: string,- observedPeerId: string,- endpointCapacity: number,- sample: QualitySampleReference,- ): QualityCopyContext {- let committedCopies = 0;- for (const edge of snapshot.upstreamByViewer.values()) {- if (- edge.kind === "peer" &&- edge.parentPeerId === observedPeerId &&- edge.physicalActive- ) {- committedCopies += 1;- }- }- if (- observedPeerId === hostPeerId &&- snapshot.hostPublication?.physicalActive- ) {- committedCopies += 1;- }-- const operation = snapshot.operation;- const current = operation?.current;- const currentPlan = current- ? operation.candidates[operation.cursor]- : undefined;- const candidateReservedCopies =- current?.tuple.kind === "peer" &&- current.tuple.parentPeerId === observedPeerId- ? 1- : current?.tuple.kind === "sfu" &&- observedPeerId === hostPeerId &&- current.tuple.publication !== "reuse"- ? 1- : 0;-- const candidateSample =- sample.kind === "peer"- ? current?.tuple.kind === "peer" &&- operation?.childPeerId === sample.childPeerId &&- current.tuple.parentPeerId === observedPeerId &&- current.revision === sample.routeRevision &&- current.connectionId === sample.connectionId- : current?.tuple.kind === "sfu" &&- observedPeerId === hostPeerId &&- current.revision === sample.routeRevision;- const activeEdge =- sample.kind === "peer"- ? snapshot.upstreamByViewer.get(sample.childPeerId)- : undefined;- const activeSample =- sample.kind === "peer"- ? sample.routeRevision === snapshot.revision &&- activeEdge?.kind === "peer" &&- activeEdge.physicalActive &&- activeEdge.usable &&- activeEdge.parentPeerId === observedPeerId &&- activeEdge.connectionId === sample.connectionId- : sample.routeRevision === snapshot.revision &&- snapshot.hostPublication?.physicalActive === true &&- snapshot.hostPublication.usable &&- snapshot.hostPublication.generation ===- sample.publicationGeneration &&- snapshot.hostPublication.hostSessionId === sample.hostSessionId;-- return {- committedCopies,- candidateReservedCopies,- possibleCopies: committedCopies + candidateReservedCopies,- endpointCapacity,- operationReason: operation?.reason ?? null,- candidateTransition: currentPlan?.endpointTransition.kind ?? null,- sampleRole: candidateSample- ? "candidate"- : activeSample- ? "active"- : "unknown",- };- }-- private debugTuple(roomId: string, tuple: CandidateTuple): string {- return tuple.kind === "peer"- ? `p2p:${this.debugPeer(roomId, tuple.parentPeerId)}${- tuple.regenerate ? ":regenerate" : ""- }`- : `sfu:${tuple.publication}`;- }-- private debug(- roomId: string,- event: string,- details: Record<string, unknown>,- ): void {- routeDebug("%s", JSON.stringify({ event, roomId, ...details }));- }-- private sendRoomError(roomId: string, code: ErrorCode, message: string): void {- const host = this.options.roomStore.getConnectedHost(roomId);- if (host) this.options.sendToSession(host.sessionId, { type: "error", code, message });- }-- private sendViewerRouteStatus(- roomId: string,- viewerPeerId: string,- message: Extract<ServerMessage, { type: "route-status" }>,- ): void {- const viewer = this.options.roomStore.getConnectedViewer(roomId, viewerPeerId);- if (viewer) this.options.sendToSession(viewer.sessionId, message);- }-- private sendRouteFailures(- roomId: string,- failedPeerIds: readonly string[],- revision: number,- ): void {- for (const peerId of new Set(failedPeerIds)) {- this.sendViewerRouteStatus(roomId, peerId, {- type: "route-status",- revision,- state: "failed",- reason: "route-exhausted",- });- }- }-}--function cursorGuard(- operation: OperationSnapshot,- plan: CandidatePlan,-): CandidateCursorGuard {- return {- childPeerId: operation.childPeerId,- childSessionId: operation.childSessionId,- baseRevision: operation.baseRevision,- factVersion: operation.factVersion,- cursor: operation.cursor,- plan,- };-}--function emptyAssignment(): ParticipantRouteAssignment {- return {- upstream: { kind: "none" },- childPeerIds: [],- sfuPublicationGeneration: null,- };-}--function preparedRouteCandidate(- operation: OperationSnapshot,- tuple: CandidateTuple,- connectionId: string,-): PreparedRouteCandidate {- return {- childPeerId: operation.childPeerId,- connectionId,- transport: tuple.kind === "peer" ? tuple.transport : "sfu",- qualityProbe: operation.reason === "quality-convergence",- ...(operation.current?.connectionAttempt- ? { connectionAttempt: operation.current.connectionAttempt }- : {}),- };-}--function opaqueId(): string {- return randomBytes(16).toString("base64url");-}--function sfuDrainKey(target: SfuDrainTarget): string {- const roomName = managedSfuRoomName(target.fence);- return target.kind === "publication"- ? roomName- : `${roomName}\u0000viewer:${target.fence.viewerPeerId}`;-}--function overlapResource(endpointPeerId: string): OverlapRouteResource {- return { kind: "overlap", endpointPeerId, released: false };-}--function subscriptionResource(- fence: SfuSubscriptionFence,-): SfuSubscriptionRouteResource {- return { kind: "sfu-subscription", fence, released: false };-}--function publicationResource(- fence: SfuResourceFence,-): SfuPublicationRouteResource {- return {- kind: "sfu-publication",- fence,- released: false,- };-}--function reservationResources(- reservation: CandidateReservation<RouteResource>,-): RouteResource[] {- const resources: RouteResource[] = [];- if (- "edge" in reservation &&- (reservation.kind !== "sfu-reuse" || !reservation.borrowed)- ) {- resources.push(reservation.edge);- }- if ("publication" in reservation) resources.push(reservation.publication);- if ("overlap" in reservation && reservation.overlap) {- resources.push(reservation.overlap);- }- return resources;-}diff --git a/src/server/ice.ts b/src/server/ice.tsdeleted file mode 100644index 11ef3cc4..00000000--- a/src/server/ice.ts+++ /dev/null@@ -1,51 +0,0 @@-import type { WireIceConfig } from "../shared/protocol.js";--export interface IceConfigOptions {- stunUrls: readonly string[];- natPredictionEnabled: boolean;- natPredictionStunUrls?: readonly string[];-}--const NAT_PREDICTION_BASE_PORT = 3478;-const NAT_PREDICTION_AUXILIARY_PORTS = [3479, 3480] as const;--export function natPredictionStunUrls(- stunUrls: readonly string[],-): string[] {- for (const stunUrl of stunUrls) {- const authorityText = stunUrl.slice(stunUrl.indexOf(":") + 1);- let authority: URL;- try {- authority = new URL(`http://${authorityText}`);- } catch {- continue;- }- const port = authority.port- ? Number(authority.port)- : NAT_PREDICTION_BASE_PORT;- if (port !== NAT_PREDICTION_BASE_PORT) {- continue;- }- const hostname = authority.hostname.startsWith("[")- ? authority.hostname- : authority.hostname.includes(":")- ? `[${authority.hostname}]`- : authority.hostname;- return NAT_PREDICTION_AUXILIARY_PORTS.map(- (auxiliaryPort) => `stun:${hostname}:${auxiliaryPort}`,- );- }- return [];-}--export function createIceConfig(options: IceConfigOptions): WireIceConfig {- const predictionStunUrls =- options.natPredictionStunUrls ?? natPredictionStunUrls(options.stunUrls);- return {- iceServers:- options.stunUrls.length > 0 ? [{ urls: [...options.stunUrls] }] : [],- natPredictionStunUrls: options.natPredictionEnabled- ? [...predictionStunUrls]- : [],- };-}diff --git a/src/server/index.ts b/src/server/index.tsdeleted file mode 100644index d5806844..00000000--- a/src/server/index.ts+++ /dev/null@@ -1,52 +0,0 @@-import { loadEnvFile } from "node:process";--import { createScreenerServer } from "./app.js";-import { loadConfig } from "./config.js";--try {- loadEnvFile();-} catch (error) {- if (!isMissingFileError(error)) {- throw error;- }-}--const config = loadConfig();-const server = await createScreenerServer({- config,- frontend:- config.nodeEnv === "development"- ? { mode: "development" }- : config.nodeEnv === "production"- ? { mode: "static" }- : { mode: "none" },-});-const port = await server.listen();--console.log(- `Screener is listening on ${config.listenHost}:${port}; public URL ${config.publicBaseUrl.origin}`,-);--let shuttingDown = false;-async function shutdown(): Promise<void> {- if (shuttingDown) {- return;- }- shuttingDown = true;- await server.close();-}--process.once("SIGINT", () => {- void shutdown().then(() => process.exit(0));-});-process.once("SIGTERM", () => {- void shutdown().then(() => process.exit(0));-});--function isMissingFileError(error: unknown): boolean {- return (- error instanceof Error &&- "code" in error &&- (error as NodeJS.ErrnoException).code === "ENOENT"- );-}diff --git a/src/server/livekit-token.ts b/src/server/livekit-token.tsdeleted file mode 100644index 6dfee50e..00000000--- a/src/server/livekit-token.ts+++ /dev/null@@ -1,87 +0,0 @@-import {- AccessToken,- TrackSource,-} from "livekit-server-sdk";--import {- MAX_VIEWERS_PER_ROOM_LIMIT,- type Role,-} from "../shared/protocol.js";-import { managedSfuRoomName } from "./sfu-resource-admission.js";--const LIVEKIT_TOKEN_TTL_SECONDS = 5 * 60;-const ROOM_ID_PATTERN = /^[1-9]\d{0,11}$/;-const OPAQUE_ID_PATTERN = /^[A-Za-z0-9_-]{8,128}$/;--export interface SfuTokenRequest {- roomId: string;- role: Role;- peerId: string;- shareGeneration: string;- publicationGeneration: string;-}--export interface SfuTokenIssuer {- issueToken(request: SfuTokenRequest): Promise<string>;-}--export interface LiveKitTokenIssuerOptions {- apiKey: string;- apiSecret: string;- maxViewersPerRoom: number;-}--export class LiveKitTokenIssuer implements SfuTokenIssuer {- constructor(private readonly options: LiveKitTokenIssuerOptions) {- if (!options.apiKey || Buffer.byteLength(options.apiSecret) < 32) {- throw new Error("LiveKit API credentials are invalid");- }- if (- !Number.isSafeInteger(options.maxViewersPerRoom) ||- options.maxViewersPerRoom < 1 ||- options.maxViewersPerRoom > MAX_VIEWERS_PER_ROOM_LIMIT- ) {- throw new Error("LiveKit viewer limit is invalid");- }- }-- async issueToken(request: SfuTokenRequest): Promise<string> {- validateTokenRequest(request);-- const isHost = request.role === "host";- const room = managedSfuRoomName(request);- const token = new AccessToken(- this.options.apiKey,- this.options.apiSecret,- {- identity: isHost ? "host" : `viewer:${request.peerId}`,- ttl: LIVEKIT_TOKEN_TTL_SECONDS,- },- );- token.addGrant({- roomJoin: true,- room,- canPublish: isHost,- canPublishSources: isHost- ? [TrackSource.SCREEN_SHARE, TrackSource.SCREEN_SHARE_AUDIO]- : undefined,- canSubscribe: !isHost,- canPublishData: false,- canUpdateOwnMetadata: false,- });- return await token.toJwt();- }-}--function validateTokenRequest(request: SfuTokenRequest): void {- if (!ROOM_ID_PATTERN.test(request.roomId)) {- throw new Error("LiveKit room ID is invalid");- }- if (- !OPAQUE_ID_PATTERN.test(request.peerId) ||- !OPAQUE_ID_PATTERN.test(request.shareGeneration) ||- !OPAQUE_ID_PATTERN.test(request.publicationGeneration)- ) {- throw new Error("LiveKit participant identity is invalid");- }-}diff --git a/src/server/local-config.ts b/src/server/local-config.tsdeleted file mode 100644index c92894ad..00000000--- a/src/server/local-config.ts+++ /dev/null@@ -1,155 +0,0 @@-import { isIP } from "node:net";--import {- MAX_ICE_SERVER_URLS,- MAX_VIEWERS_PER_ROOM_LIMIT,- stunUrlSchema,-} from "../shared/protocol.js";-import { DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY } from "../shared/media-copy-accounting.js";-import type { ServerConfig } from "./config.js";--const DEFAULT_LOCAL_PORT = 8787;-const LOCAL_ROOM_LEASE_MS = 24 * 60 * 60 * 1_000;-const VISIBLE_ASCII_PATTERN = /^[\x21-\x7e]{8,128}$/;--export interface LocalServerConfigOptions {- port?: number;- publicAddress: string;- publicOrigin?: string;- allowedAddresses?: readonly string[];- siteAccessPassword?: string;- stunUrls?: readonly string[];- natPredictionStunUrls?: readonly string[];-}--export function createLocalServerConfig(- options: LocalServerConfigOptions,-): ServerConfig {- const port = options.port ?? DEFAULT_LOCAL_PORT;- if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) {- throw new Error("Local server port must be an integer between 1 and 65535");- }- const publicAddress = localIPv4(options.publicAddress, "public address");- if (publicAddress === "0.0.0.0" || publicAddress.startsWith("127.")) {- throw new Error("Local server public address must be reachable from the LAN");- }- const siteAccessPassword = options.siteAccessPassword?.trim() ?? "";- if (- siteAccessPassword &&- (!VISIBLE_ASCII_PATTERN.test(siteAccessPassword) ||- Buffer.byteLength(siteAccessPassword) < 8 ||- Buffer.byteLength(siteAccessPassword) > 128)- ) {- throw new Error("Local access password must contain 8 to 128 visible ASCII bytes");- }-- const allowedAddresses = new Set([- publicAddress,- ...(options.allowedAddresses ?? []).map((address) =>- localIPv4(address, "allowed address"),- ),- ]);- const stunUrls = [...(options.stunUrls ?? [])];- const natPredictionStunUrls = [- ...(options.natPredictionStunUrls ?? []),- ];- if (- stunUrls.length + natPredictionStunUrls.length > MAX_ICE_SERVER_URLS ||- stunUrls.some((url) => !stunUrlSchema.safeParse(url).success) ||- natPredictionStunUrls.some(- (url) => !stunUrlSchema.safeParse(url).success,- ) ||- ![0, 2].includes(natPredictionStunUrls.length) ||- (natPredictionStunUrls.length > 0 && stunUrls.length === 0)- ) {- throw new Error("Local STUN URLs are invalid");- }- const origin = (host: string) => `http://${host}:${port}`;- const publicBaseUrl = options.publicOrigin- ? publicHTTPSOrigin(options.publicOrigin)- : new URL(origin(publicAddress));-- return {- nodeEnv: "production",- port,- listenHost: "0.0.0.0",- publicBaseUrl,- allowedOrigins: new Set([- origin("localhost"),- origin("127.0.0.1"),- ...[...allowedAddresses].map(origin),- publicBaseUrl.origin,- ]),- siteAccessPassword: siteAccessPassword || undefined,- roomLeaseMs: LOCAL_ROOM_LEASE_MS,- maxViewersPerRoom: MAX_VIEWERS_PER_ROOM_LIMIT,- peerAssistedMedia: true,- endpointMediaCopyCapacity: DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY,- stunUrls,- natPredictionEnabled: natPredictionStunUrls.length === 2,- natPredictionStunUrls,- };-}--export function loadLocalServerConfig(- environment: NodeJS.ProcessEnv = process.env,-): ServerConfig {- const publicAddress = environment.SCREENER_CLIENT_LAN_ADDRESS?.trim();- if (!publicAddress) {- throw new Error("SCREENER_CLIENT_LAN_ADDRESS is required");- }- const siteAccessPassword = environment.SCREENER_CLIENT_LOCAL_PASSWORD?.trim() ?? "";- const portText = environment.SCREENER_CLIENT_PORT?.trim();- const port = portText ? Number(portText) : undefined;- const allowedAddresses = environment.SCREENER_CLIENT_ALLOWED_LAN_ADDRESSES- ?.split(",")- .map((address) => address.trim())- .filter(Boolean);- const stunUrls = environment.STUN_URLS- ?.split(",")- .map((url) => url.trim())- .filter(Boolean);- const natPredictionStunUrls =- environment.SCREENER_CLIENT_NAT_PREDICTION_STUN_URLS- ?.split(",")- .map((url) => url.trim())- .filter(Boolean);- const publicOrigin = environment.SCREENER_CLIENT_PUBLIC_ORIGIN?.trim();- return createLocalServerConfig({- ...(port === undefined ? {} : { port }),- publicAddress,- ...(publicOrigin ? { publicOrigin } : {}),- ...(allowedAddresses ? { allowedAddresses } : {}),- ...(siteAccessPassword ? { siteAccessPassword } : {}),- ...(stunUrls ? { stunUrls } : {}),- ...(natPredictionStunUrls ? { natPredictionStunUrls } : {}),- });-}--function publicHTTPSOrigin(value: string): URL {- let parsed: URL;- try {- parsed = new URL(value);- } catch {- throw new Error("Local public origin must be an HTTPS origin");- }- if (- parsed.protocol !== "https:" ||- parsed.username ||- parsed.password ||- parsed.pathname !== "/" ||- parsed.search ||- parsed.hash- ) {- throw new Error("Local public origin must be an HTTPS origin");- }- return parsed;-}--function localIPv4(value: string, name: string): string {- const address = value.trim();- if (isIP(address) !== 4) {- throw new Error(`Local server ${name} must be an IPv4 address`);- }- return address;-}diff --git a/src/server/local-index.ts b/src/server/local-index.tsdeleted file mode 100644index c6663f58..00000000--- a/src/server/local-index.ts+++ /dev/null@@ -1,34 +0,0 @@-import { createScreenerServer } from "./app.js";-import { loadLocalServerConfig } from "./local-config.js";--const config = loadLocalServerConfig();-const server = await createScreenerServer({- config,- frontend: { mode: "static" },-});--let shutdown: Promise<void> | undefined;-function stop(): Promise<void> {- shutdown ??= server.end();- return shutdown;-}--function requestStop(): void {- process.stdin.pause();- void stop().catch(() => {- process.exitCode = 1;- });-}--process.once("SIGINT", requestStop);-process.once("SIGTERM", requestStop);-process.stdin.resume();-process.stdin.once("end", requestStop);--try {- await server.listen();- console.log(`Screener Client is available at http://localhost:${config.port}`);-} catch {- await stop().catch(() => undefined);- throw new Error("Screener Client local server could not start");-}diff --git a/src/server/room-database.ts b/src/server/room-database.tsdeleted file mode 100644index 94e5a591..00000000--- a/src/server/room-database.ts+++ /dev/null@@ -1,578 +0,0 @@-import { DatabaseSync } from "node:sqlite";--import {- codeEntryPolicySchema,- roomCodeSchema,- type CodeEntryPolicy,-} from "../shared/protocol.js";--const ROOM_DATABASE_APPLICATION_ID = 0x5343524e;-const ROOM_DATABASE_SCHEMA_VERSION = 1;-const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;--export interface StoredRoomAuthority {- roomId: string;- hostTokenDigest: Buffer;- viewerGrantDigest: Buffer;- viewerAuthorizationGeneration: string;- codeEntryPolicy: CodeEntryPolicy;- viewerPasswordMaterial: Buffer | null;- leaseExpiresAtMs: number | null;-}--export class RoomDatabase {- private database: DatabaseSync | undefined;-- constructor(private readonly path: string) {- if (!path || path === ":memory:") {- throw new Error("Room database path must identify a file");- }- }-- initialize(- startupNowMs: number,- activeLeaseExpiresAtMs: number,- ): StoredRoomAuthority[] {- if (this.database) {- throw new Error("Room database is already initialized");- }- assertTimestamp(startupNowMs, "Room database startup time", true);- assertTimestamp(- activeLeaseExpiresAtMs,- "Room database active-room lease deadline",- );- if (activeLeaseExpiresAtMs <= startupNowMs) {- throw new Error("Room database active-room lease deadline must be in the future");- }-- const database = new DatabaseSync(this.path, { timeout: 0 });- try {- const lockingMode = database- .prepare("PRAGMA main.locking_mode = EXCLUSIVE")- .get() as Record<string, unknown> | undefined;- if (lockingMode?.locking_mode !== "exclusive") {- throw new Error("Room database could not acquire exclusive locking mode");- }-- database.exec("BEGIN EXCLUSIVE");- let restored: StoredRoomAuthority[];- try {- this.ensureExactSchema(database);- assertDatabaseIntegrity(database);- const stored = readStoredRooms(database);- const expiredCount = stored.filter(- (room) =>- room.leaseExpiresAtMs !== null &&- room.leaseExpiresAtMs <= startupNowMs,- ).length;- const activeCount = stored.filter(- (room) => room.leaseExpiresAtMs === null,- ).length;-- const deleted = database- .prepare(- `DELETE FROM rooms- WHERE lease_expires_at_ms IS NOT NULL- AND lease_expires_at_ms <= ?`,- )- .run(startupNowMs).changes;- if (Number(deleted) !== expiredCount) {- throw new Error("Room database expiry cleanup changed an unexpected row count");- }-- const converted = database- .prepare(- `UPDATE rooms- SET lease_expires_at_ms = ?- WHERE lease_expires_at_ms IS NULL`,- )- .run(activeLeaseExpiresAtMs).changes;- if (Number(converted) !== activeCount) {- throw new Error("Room database active-room recovery changed an unexpected row count");- }-- restored = stored.flatMap((room) => {- if (- room.leaseExpiresAtMs !== null &&- room.leaseExpiresAtMs <= startupNowMs- ) {- return [];- }- return [- room.leaseExpiresAtMs === null- ? { ...room, leaseExpiresAtMs: activeLeaseExpiresAtMs }- : room,- ];- });- database.exec("COMMIT");- } catch (error) {- if (database.isTransaction) {- database.exec("ROLLBACK");- }- throw error;- }-- this.database = database;- return restored;- } catch (error) {- database.close();- throw error;- }- }-- insertRoom(room: StoredRoomAuthority): void {- assertStoredRoom(room);- this.transaction((database) => {- assertSingleChange(insertStoredRoom(database, room), "insert");- });- }-- setLeaseDeadline(- roomId: string,- hostTokenDigest: Buffer,- leaseExpiresAtMs: number | null,- ): void {- assertRoomIdentity(roomId, hostTokenDigest);- if (leaseExpiresAtMs !== null) {- assertTimestamp(leaseExpiresAtMs, "Room lease deadline");- }- this.transaction((database) => {- const changes = database- .prepare(- `UPDATE rooms- SET lease_expires_at_ms = ?- WHERE room_id = ? AND host_token_digest = ?`,- )- .run(leaseExpiresAtMs, roomId, hostTokenDigest).changes;- assertSingleChange(changes, "lease update");- });- }-- setViewerPassword(- roomId: string,- hostTokenDigest: Buffer,- viewerPasswordMaterial: Buffer | null,- ): void {- assertRoomIdentity(roomId, hostTokenDigest);- assertPasswordMaterial(viewerPasswordMaterial);- this.transaction((database) => {- const changes = database- .prepare(- `UPDATE rooms- SET viewer_password_material = ?- WHERE room_id = ? AND host_token_digest = ?`,- )- .run(viewerPasswordMaterial, roomId, hostTokenDigest).changes;- assertSingleChange(changes, "password update");- });- }-- setCodeEntryPolicy(- roomId: string,- hostTokenDigest: Buffer,- codeEntryPolicy: CodeEntryPolicy,- ): void {- assertRoomIdentity(roomId, hostTokenDigest);- if (!codeEntryPolicySchema.safeParse(codeEntryPolicy).success) {- throw new Error("Room code-entry policy is invalid");- }- this.transaction((database) => {- const changes = database- .prepare(- `UPDATE rooms- SET code_entry_policy = ?- WHERE room_id = ? AND host_token_digest = ?`,- )- .run(codeEntryPolicy, roomId, hostTokenDigest).changes;- assertSingleChange(changes, "code-entry policy update");- });- }-- setViewerGrant(- roomId: string,- hostTokenDigest: Buffer,- viewerGrantDigest: Buffer,- viewerAuthorizationGeneration: string,- ): void {- assertRoomIdentity(roomId, hostTokenDigest);- assertDigest(viewerGrantDigest, "Viewer grant");- assertAuthorizationGeneration(viewerAuthorizationGeneration);- this.transaction((database) => {- const changes = database- .prepare(- `UPDATE rooms- SET viewer_grant_digest = ?,- viewer_authorization_generation = ?- WHERE room_id = ? AND host_token_digest = ?`,- )- .run(- viewerGrantDigest,- viewerAuthorizationGeneration,- roomId,- hostTokenDigest,- ).changes;- assertSingleChange(changes, "Viewer grant update");- });- }-- deleteRoom(roomId: string, hostTokenDigest: Buffer): void {- this.deleteRooms([{ roomId, hostTokenDigest }]);- }-- deleteRooms(- rooms: readonly { roomId: string; hostTokenDigest: Buffer }[],- ): void {- for (const room of rooms) {- assertRoomIdentity(room.roomId, room.hostTokenDigest);- }- if (rooms.length === 0) {- return;- }- this.transaction((database) => {- const statement = database.prepare(- "DELETE FROM rooms WHERE room_id = ? AND host_token_digest = ?",- );- for (const room of rooms) {- assertSingleChange(- statement.run(room.roomId, room.hostTokenDigest).changes,- "delete",- );- }- });- }-- replaceRoom(- oldRoomId: string,- oldHostTokenDigest: Buffer,- replacement: StoredRoomAuthority,- ): void {- assertRoomIdentity(oldRoomId, oldHostTokenDigest);- assertStoredRoom(replacement);- if (replacement.roomId === oldRoomId) {- throw new Error("Replacement room ID must be different");- }- this.transaction((database) => {- assertSingleChange(- insertStoredRoom(database, replacement),- "replacement insert",- );- const deleted = database- .prepare(- "DELETE FROM rooms WHERE room_id = ? AND host_token_digest = ?",- )- .run(oldRoomId, oldHostTokenDigest).changes;- assertSingleChange(deleted, "replacement delete");- });- }-- close(): void {- const database = this.database;- this.database = undefined;- if (database?.isOpen) {- database.close();- }- }-- private ensureExactSchema(database: DatabaseSync): void {- const applicationId = readPragmaInteger(database, "application_id");- const schemaVersion = readPragmaInteger(database, "user_version");- const schemaObjects = database- .prepare(- `SELECT type, name- FROM sqlite_schema- WHERE name NOT LIKE 'sqlite_%'- ORDER BY type, name`,- )- .all() as Array<Record<string, unknown>>;-- if (- applicationId === 0 &&- schemaVersion === 0 &&- schemaObjects.length === 0- ) {- database.exec(`- CREATE TABLE rooms (- room_id TEXT PRIMARY KEY NOT NULL- CHECK (room_id GLOB '[1-9][0-9][0-9][0-9]'),- host_token_digest BLOB NOT NULL- CHECK (typeof(host_token_digest) = 'blob' AND length(host_token_digest) = 32),- viewer_grant_digest BLOB NOT NULL- CHECK (typeof(viewer_grant_digest) = 'blob' AND length(viewer_grant_digest) = 32),- viewer_authorization_generation TEXT NOT NULL- CHECK (- length(viewer_authorization_generation) = 22 AND- viewer_authorization_generation NOT GLOB '*[^A-Za-z0-9_-]*'- ),- code_entry_policy TEXT NOT NULL- CHECK (code_entry_policy IN ('open', 'private')),- viewer_password_material BLOB NULL- CHECK (- viewer_password_material IS NULL OR- (typeof(viewer_password_material) = 'blob' AND length(viewer_password_material) = 48)- ),- lease_expires_at_ms INTEGER NULL- CHECK (- lease_expires_at_ms IS NULL OR- (lease_expires_at_ms > 0 AND lease_expires_at_ms <= ${MAX_SAFE_INTEGER})- )- ) STRICT;- PRAGMA application_id = ${ROOM_DATABASE_APPLICATION_ID};- PRAGMA user_version = ${ROOM_DATABASE_SCHEMA_VERSION};- `);- return;- }-- if (applicationId !== ROOM_DATABASE_APPLICATION_ID) {- throw new Error("Room database application identity does not match");- }- if (schemaVersion !== ROOM_DATABASE_SCHEMA_VERSION) {- throw new Error("Room database schema version does not match");- }- if (- schemaObjects.length !== 1 ||- schemaObjects[0]?.type !== "table" ||- schemaObjects[0]?.name !== "rooms"- ) {- throw new Error("Room database schema objects do not match");- }- assertExactColumns(database);- }-- private transaction(operation: (database: DatabaseSync) => void): void {- const database = this.database;- if (!database?.isOpen) {- throw new Error("Room database is not initialized");- }- database.exec("BEGIN IMMEDIATE");- try {- operation(database);- database.exec("COMMIT");- } catch (error) {- if (database.isTransaction) {- database.exec("ROLLBACK");- }- throw error;- }- }-}--function insertStoredRoom(- database: DatabaseSync,- room: StoredRoomAuthority,-): number | bigint {- return database- .prepare(- `INSERT INTO rooms (- room_id,- host_token_digest,- viewer_grant_digest,- viewer_authorization_generation,- code_entry_policy,- viewer_password_material,- lease_expires_at_ms- ) VALUES (?, ?, ?, ?, ?, ?, ?)`,- )- .run(- room.roomId,- room.hostTokenDigest,- room.viewerGrantDigest,- room.viewerAuthorizationGeneration,- room.codeEntryPolicy,- room.viewerPasswordMaterial,- room.leaseExpiresAtMs,- ).changes;-}--function readStoredRooms(database: DatabaseSync): StoredRoomAuthority[] {- const rows = database- .prepare(- `SELECT- room_id,- host_token_digest,- viewer_grant_digest,- viewer_authorization_generation,- code_entry_policy,- viewer_password_material,- lease_expires_at_ms- FROM rooms- ORDER BY room_id`,- )- .all() as Array<Record<string, unknown>>;- return rows.map((row) => {- const room: StoredRoomAuthority = {- roomId: readString(row.room_id, "room ID"),- hostTokenDigest: readDigest(row.host_token_digest, "Host token"),- viewerGrantDigest: readDigest(row.viewer_grant_digest, "Viewer grant"),- viewerAuthorizationGeneration: readString(- row.viewer_authorization_generation,- "Viewer authorization generation",- ),- codeEntryPolicy: readCodeEntryPolicy(row.code_entry_policy),- viewerPasswordMaterial: readPasswordMaterial(- row.viewer_password_material,- ),- leaseExpiresAtMs: readNullableTimestamp(row.lease_expires_at_ms),- };- assertStoredRoom(room);- return room;- });-}--function assertStoredRoom(room: StoredRoomAuthority): void {- if (!roomCodeSchema.safeParse(room.roomId).success) {- throw new Error("Room database contains an invalid room ID");- }- assertDigest(room.hostTokenDigest, "Host token");- assertDigest(room.viewerGrantDigest, "Viewer grant");- assertAuthorizationGeneration(room.viewerAuthorizationGeneration);- if (!codeEntryPolicySchema.safeParse(room.codeEntryPolicy).success) {- throw new Error("Room database contains an invalid code-entry policy");- }- assertPasswordMaterial(room.viewerPasswordMaterial);- if (room.leaseExpiresAtMs !== null) {- assertTimestamp(room.leaseExpiresAtMs, "Room database lease deadline");- }-}--function assertRoomIdentity(roomId: string, hostTokenDigest: Buffer): void {- if (!roomCodeSchema.safeParse(roomId).success) {- throw new Error("Room ID is invalid");- }- assertDigest(hostTokenDigest, "Host token");-}--function assertDigest(value: Uint8Array, name: string): void {- if (!(value instanceof Uint8Array) || value.byteLength !== 32) {- throw new Error(`${name} digest must contain 32 bytes`);- }-}--function assertPasswordMaterial(value: Uint8Array | null): void {- if (value !== null && (!(value instanceof Uint8Array) || value.byteLength !== 48)) {- throw new Error("Viewer password material must contain 48 bytes");- }-}--function assertAuthorizationGeneration(value: string): void {- let decoded: Buffer;- try {- decoded = Buffer.from(value, "base64url");- } catch {- throw new Error("Viewer authorization generation is invalid");- }- if (- decoded.byteLength !== 16 ||- decoded.toString("base64url") !== value- ) {- throw new Error("Viewer authorization generation is invalid");- }-}--function assertTimestamp(value: number, name: string, allowZero = false): void {- if (- !Number.isSafeInteger(value) ||- (allowZero ? value < 0 : value <= 0)- ) {- throw new Error(`${name} must be a safe positive integer`);- }-}--function assertSingleChange(- changes: number | bigint,- operation: string,-): void {- if (Number(changes) !== 1) {- throw new Error(`Room database ${operation} did not match current authority`);- }-}--function assertDatabaseIntegrity(database: DatabaseSync): void {- const rows = database.prepare("PRAGMA quick_check").all() as Array<- Record<string, unknown>- >;- if (rows.length !== 1 || rows[0]?.quick_check !== "ok") {- throw new Error("Room database integrity check failed");- }-}--function assertExactColumns(database: DatabaseSync): void {- const columns = database.prepare("PRAGMA table_info(rooms)").all() as Array<- Record<string, unknown>- >;- const expected = [- ["room_id", "TEXT", 1, 1],- ["host_token_digest", "BLOB", 1, 0],- ["viewer_grant_digest", "BLOB", 1, 0],- ["viewer_authorization_generation", "TEXT", 1, 0],- ["code_entry_policy", "TEXT", 1, 0],- ["viewer_password_material", "BLOB", 0, 0],- ["lease_expires_at_ms", "INTEGER", 0, 0],- ] as const;- if (- columns.length !== expected.length ||- columns.some((column, index) => {- const [name, type, notNull, primaryKey] = expected[index]!;- return (- column.name !== name ||- column.type !== type ||- column.notnull !== notNull ||- column.pk !== primaryKey- );- })- ) {- throw new Error("Room database columns do not match the current schema");- }-}--function readPragmaInteger(database: DatabaseSync, name: string): number {- const row = database.prepare(`PRAGMA ${name}`).get() as- | Record<string, unknown>- | undefined;- const value = row?.[name];- if (typeof value !== "number" || !Number.isSafeInteger(value)) {- throw new Error(`Room database ${name} is invalid`);- }- return value;-}--function readString(value: unknown, name: string): string {- if (typeof value !== "string") {- throw new Error(`Room database contains an invalid ${name}`);- }- return value;-}--function readDigest(value: unknown, name: string): Buffer {- if (!(value instanceof Uint8Array) || value.byteLength !== 32) {- throw new Error(`Room database contains an invalid ${name} digest`);- }- return Buffer.from(value);-}--function readCodeEntryPolicy(value: unknown): CodeEntryPolicy {- const parsed = codeEntryPolicySchema.safeParse(value);- if (!parsed.success) {- throw new Error("Room database contains an invalid code-entry policy");- }- return parsed.data;-}--function readPasswordMaterial(value: unknown): Buffer | null {- if (value === null) {- return null;- }- if (!(value instanceof Uint8Array) || value.byteLength !== 48) {- throw new Error("Room database contains invalid Viewer password material");- }- return Buffer.from(value);-}--function readNullableTimestamp(value: unknown): number | null {- if (value === null) {- return null;- }- if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {- throw new Error("Room database contains an invalid lease deadline");- }- return value;-}diff --git a/src/server/room-route-controller.ts b/src/server/room-route-controller.tsdeleted file mode 100644index be1d42db..00000000--- a/src/server/room-route-controller.ts+++ /dev/null@@ -1,5078 +0,0 @@-import { createHash } from "node:crypto";-import { debuglog } from "node:util";--import {- MAX_MEDIA_ROUTE_REVISION,- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS,- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS,- type RouteDemandReason,- type RouteDiagnosticFinalRoute,- type RouteDiagnosticRejectionBucket,- type RouteDiagnosticSnapshot,- type ViewerQualityEvidenceMetrics,-} from "../shared/protocol.js";-import { assertEndpointMediaCopyCapacity } from "../shared/media-copy-accounting.js";--export type CandidateTuple =- | {- kind: "peer";- parentPeerId: string;- transport: "direct";- /** Rebuild this exact edge with a fresh connection and media generation. */- regenerate?: true;- }- | { kind: "sfu"; publication: "reuse" | "create" | "replace" };--export type CandidateReservation<Resource> =- | { kind: "direct"; overlap?: Resource }- | { kind: "sfu-reuse"; edge: Resource; borrowed?: true; overlap?: Resource }- | { kind: "sfu-create"; edge: Resource; publication: Resource; overlap?: Resource };--export type EndpointRetirement =- | {- kind: "edge";- childPeerId: string;- childSessionId: string;- parentPeerId: string;- parentSessionId: string;- transport: "direct";- connectionId: string;- }- | {- kind: "publication";- hostSessionId: string;- generation: string;- connectionId: string;- };--export type EndpointTransition =- | { kind: "none"; producerPeerId?: string }- | { kind: "overlap"; producerPeerId: string }- | { kind: "bounded-gap"; producerPeerId: string; retire: EndpointRetirement };--export interface CandidatePlan {- tuple: CandidateTuple;- endpointTransition: EndpointTransition;-}--export type CommittedEdge<Resource> =- | { kind: "peer"; childSessionId: string; parentPeerId: string; parentSessionId: string; transport: "direct"; connectionId: string; usable: boolean; physicalActive: boolean }- | { kind: "sfu"; childSessionId: string; publicationGeneration: string; transport: "sfu"; connectionId: string; usable: boolean; physicalActive: boolean; resource: Resource };--export type CommittedEdgeSeed<Resource> =- | Omit<Extract<CommittedEdge<Resource>, { transport: "direct" }>, "childSessionId" | "parentSessionId">- | Omit<Extract<CommittedEdge<Resource>, { transport: "sfu" }>, "childSessionId">;--export interface ParticipantInput {- peerId: string;- role: "host" | "viewer";- sessionId: string;- effectiveDownstreamCapacity: number;-}--export interface EdgeGuard {- childPeerId: string;- childSessionId: string;- routeRevision: number;- connectionId: string;- parentSessionId?: string;-}--export interface CandidateGuard {- childPeerId: string;- childSessionId: string;- revision: number;- connectionId: string;-}--export interface CandidateCursorGuard {- childPeerId: string;- childSessionId: string;- baseRevision: number;- factVersion: number;- cursor: number;- plan: CandidatePlan;-}--export interface ControllerOptions {- hostPeerId: string;- debugRoomId?: string;- endpointMediaCopyCapacity: number;- operationTimeoutMs: number;- sfuEnabled?: boolean;- qualityConvergenceEnabled?: boolean;- natPredictionEnabled?: boolean;-}--const routeDebug = debuglog("screener-route");-const MAX_DIRECT_HEAD_START_MS = 5_000;-const MAX_NAT_CONNECTION_ATTEMPTS = 3;-const SFU_OPPORTUNITY_PREFIX = "sfu\0";--interface CandidateOpportunity {- rank: number;- startedAttempts: number;- exhausted?: true;-}--interface ConnectionAttemptProgress {- current: number;- total: typeof MAX_NAT_CONNECTION_ATTEMPTS;-}--interface Participant {- peerId: string;- role: "host" | "viewer";- sessionId: string | null;- departureConfirmed: boolean;- joinOrder: number;- effectiveDownstreamCapacity: number;- availabilityExhausted: boolean;- consumedCandidateOpportunities: Map<string, CandidateOpportunity>;- bootstrapFailureReported?: boolean;- sfuFirstAtNextRoute?: boolean;-}--interface Attempt<Resource> {- tuple: CandidateTuple;- revision: number;- connectionId: string;- childSessionId: string;- parentSessionId?: string;- hostSessionId?: string;- publicationGeneration?: string;- publicationConnectionId?: string;- reservation: CandidateReservation<Resource>;- startedAtMs: number;- transportConnected: boolean;- mediaReady: boolean;- connectionAttempt?: ConnectionAttemptProgress;- senderQualityState?: "healthy" | "degraded";- senderQualityAcceptedAtMs?: number;- senderQualityConsecutiveHealthyWindows?: number;- senderQualityConsecutiveDegradedWindows?: number;- senderQualitySampleTimestampMs?: number;- senderQualityIdentity?: string;- relativeQualityApprovedAtMs?: number;-}--interface ChildOperation<Resource> {- childPeerId: string;- childSessionId: string;- demandPeerId: string;- demandSessionId: string;- readonly reason: RouteDemandReason;- baseRevision: number;- candidates: CandidatePlan[];- cursor: number;- deadlineAtMs: number;- builtAtFactVersion: number;- deferredParentPeerIds: string[];- peerAttemptStarted: boolean;- qualitySource?: SenderQualityIdentity;- current?: Attempt<Resource>;-}--interface DirectContinuation {- childSessionId: string;- sfuConnectionId: string;- publicationGeneration: string;- parentPeerIds: string[];-}--interface SfuBootstrapIntent {- demandPeerId: string;- demandSessionId: string;-}--interface SfuBootstrapCarrier {- demandPeerId: string;- demandSessionId: string;- carrierPeerId: string;-}--export interface OperationSnapshot {- childPeerId: string;- childSessionId: string;- demandPeerId: string;- reason: RouteDemandReason;- baseRevision: number;- factVersion: number;- candidates: readonly CandidatePlan[];- cursor: number;- deadlineAtMs: number;- wakeAtMs: number;- current?: {- tuple: CandidateTuple;- revision: number;- connectionId: string;- connectionAttempt?: ConnectionAttemptProgress;- };-}--export interface RouteSnapshot<Resource> {- revision: number;- paused: boolean;- factVersion: number;- upstreamByViewer: ReadonlyMap<string, CommittedEdge<Resource>>;- hostPublication: HostPublication<Resource> | null;- operation?: OperationSnapshot;-}--export interface ReconcileResult<Resource> {- operation?: OperationSnapshot;- removedPeerIds: readonly string[];- failedPeerIds: readonly string[];- released: readonly Resource[];-}--export interface SettleResult<Resource> {- accepted: boolean;- committed?: boolean;- failedPeerIds: readonly string[];- activeRevision: number;- released: readonly Resource[];-}--export interface BeginResult<Resource> {- accepted: boolean;- operation?: OperationSnapshot;- failedPeerIds: readonly string[];- released: readonly Resource[];-}--interface HostPublication<Resource> {- generation: string;- hostSessionId: string;- connectionId: string;- usable: boolean;- physicalActive: boolean;- resource: Resource;-}--interface RouteTimingRecord {- demandAtMs: number;- reason: RouteDemandReason;- operationStartedAtMs?: number;- candidateStartedAtMs?: number;- firstDecodedFrameAtMs?: number;- finalAtMs?: number;- finalRoute: RouteDiagnosticFinalRoute;- rejectionBucket: RouteDiagnosticRejectionBucket;-}--interface RouteQualityObservation {- childSessionId: string;- upstreamKind: "peer" | "sfu";- upstreamPeerId: string | null;- connectionId: string;- presentationEpoch: number;- eligibleWindows: number;- eligibleDurationMs: number;- freezeWindows: number;- freezeCount: number;- freezeDurationMs: number;- pauseCount: number;- pauseDurationMs: number;- lastAcceptedAtMs: number;- lastDecodedProgressAtMs: number | null;-}--interface SenderQualityObservation {- childSessionId: string;- parentPeerId: string;- parentSessionId: string;- connectionId: string;- senderIdentity: string;- state: "unknown" | "healthy" | "degraded";- consecutiveDegradedWindows: number;- lastSampleTimestampMs: number;- lastAcceptedAtMs: number;- consumedQualityCandidates: Map<string, number>;-}--interface SenderQualityIdentity {- childSessionId: string;- parentPeerId: string;- parentSessionId: string;- connectionId: string;- senderIdentity: string;-}--export interface SenderQualityEvidenceInput {- parentPeerId: string;- parentSessionId: string;- childPeerId: string;- routeRevision: number;- connectionId: string;- senderIdentity: string | null;- sampleTimestampMs: number | null;- state: "unknown" | "healthy" | "degraded";- acceptedAtMs: number;-}--export interface SenderQualityEvidenceResult<Resource> {- accepted: boolean;- committed: boolean;- failedPeerIds: readonly string[];- activeRevision: number;- released: readonly Resource[];-}--interface SfuPublisherQualityObservation {- hostSessionId: string;- publicationGeneration: string;- state: "healthy" | "degraded";- consecutiveHealthyWindows: number;- lastSampleTimestampMs: number;- lastAcceptedAtMs: number;-}--export interface SfuPublisherQualityEvidenceInput {- hostPeerId: string;- hostSessionId: string;- publicationGeneration: string;- routeRevision: number;- state: "unknown" | "healthy" | "degraded";- sampleTimestampMs: number | null;- acceptedAtMs: number;-}--export interface RouteQualityEvidenceInput {- childPeerId: string;- childSessionId: string;- routeRevision: number;- connectionId: string;- upstream: { kind: "peer"; peerId: string } | { kind: "sfu" };- presentationEpoch: number;- windowMs: number;- metrics: Pick<- ViewerQualityEvidenceMetrics,- | "framesDecodedDelta"- | "freezeCountDelta"- | "freezeDurationMsDelta"- | "pauseCountDelta"- | "pauseDurationMsDelta"- > &- Partial<- Pick<- ViewerQualityEvidenceMetrics,- "width" | "height" | "framesPerSecond" | "bitrateKbps"- >- >;- acceptedAtMs: number;-}--export type RouteQualityEvidenceResult =- | "rejected"- | "accepted"- | "observed";--export class RoomRouteController<Resource = unknown> {- private readonly participants = new Map<string, Participant>();- private readonly upstreamByViewer = new Map<string, CommittedEdge<Resource>>();- private hostPublication: HostPublication<Resource> | null = null;- private operation?: ChildOperation<Resource>;- private revision = 0;- private latestRevision = 0;- private factVersion = 0;- private nextJoinOrder = 0;- private paused = false;- private readonly routeTimings = new Map<string, RouteTimingRecord>();- private readonly qualityObservations = new Map<- string,- RouteQualityObservation- >();- private readonly senderQualityObservations = new Map<- string,- SenderQualityObservation- >();- private readonly senderQualityBaselines = new Map<string, boolean>();- private readonly senderQualityRegenerationBlocks = new Map<- string,- SenderQualityIdentity- >();- private sfuPublisherQualityObservation?: SfuPublisherQualityObservation;- private readonly qualityBaselinesPending = new Set<string>();- private readonly directContinuations = new Map<string, DirectContinuation>();- private readonly retiringPublicationGenerations = new Set<string>();- private sfuBootstrapIntent?: SfuBootstrapIntent;- private readonly consumedSfuBootstrapOpportunities = new Map<- string,- number- >();- private rootConvergenceRootPeerId?: string;-- constructor(private readonly options: ControllerOptions) {- assertEndpointMediaCopyCapacity(options.endpointMediaCopyCapacity);- if (!Number.isSafeInteger(options.operationTimeoutMs) || options.operationTimeoutMs <= 0) {- throw new Error("Route operation timeout must be a positive integer");- }- this.debug("controller-created", {- endpointCapacity: options.endpointMediaCopyCapacity,- operationTimeoutMs: options.operationTimeoutMs,- sfuEnabled: options.sfuEnabled === true,- qualityConvergenceEnabled: options.qualityConvergenceEnabled === true,- });- }-- diagnosticParticipantLabel(peerId: string): string {- return this.debugPeer(peerId);- }-- snapshot(): RouteSnapshot<Resource> {- return {- revision: this.revision,- paused: this.paused,- factVersion: this.factVersion,- upstreamByViewer: new Map([...this.upstreamByViewer].map(([id, edge]) => [id, { ...edge }])),- hostPublication: this.hostPublication ? { ...this.hostPublication } : null,- operation: this.operationSnapshot(),- };- }-- routeDiagnosticSnapshot(nowMs: number): RouteDiagnosticSnapshot {- const viewers = [...this.participants.values()]- .filter(- (participant) =>- participant.role === "viewer" &&- participant.sessionId !== null &&- !participant.departureConfirmed,- )- .sort(compareParticipant);- const ordinals = new Map(- viewers.map((viewer, index) => [viewer.peerId, index + 1] as const),- );- const children: RouteDiagnosticSnapshot["children"] = viewers.map(- (viewer) => {- const ordinal = ordinals.get(viewer.peerId)!;- const edge = this.upstreamByViewer.get(viewer.peerId);- const record = this.routeTimings.get(viewer.peerId);- const finalRoute = this.currentFinalRoute(viewer.peerId);- return {- ordinal,- parent: this.diagnosticParent(edge, ordinals),- effectiveCapacity: viewer.effectiveDownstreamCapacity,- childCount: this.childrenOf(viewer.peerId).filter((childPeerId) => {- const childEdge = this.upstreamByViewer.get(childPeerId);- return childEdge?.kind === "peer" && childEdge.physicalActive;- }).length,- demandAgeMs: record- ? elapsedMs(record.demandAtMs, nowMs)- : null,- queueWaitMs:- record?.operationStartedAtMs === undefined- ? null- : elapsedMs(record.demandAtMs, record.operationStartedAtMs),- candidateStartMs:- record?.candidateStartedAtMs === undefined- ? null- : elapsedMs(record.demandAtMs, record.candidateStartedAtMs),- firstDecodedFrameMs:- record?.firstDecodedFrameAtMs === undefined- ? null- : elapsedMs(record.demandAtMs, record.firstDecodedFrameAtMs),- finalMs:- record?.finalAtMs === undefined- ? null- : elapsedMs(record.demandAtMs, record.finalAtMs),- finalRoute:- finalRoute === "waiting"- ? record?.finalRoute === "failed"- ? "failed"- : "waiting"- : finalRoute,- rejectionBucket: record?.rejectionBucket ?? "none",- quality: this.diagnosticQuality(viewer.peerId, edge, nowMs),- };- },- );- const operation = this.operation;- const childOrdinal = operation- ? ordinals.get(operation.demandPeerId)- : undefined;- return {- children,- operation:- operation && childOrdinal !== undefined- ? {- childOrdinal,- reason: operation.reason,- stage: operation.current?.mediaReady- ? "quality-proof"- : operation.current- ? "first-frame"- : "admission",- cursor: operation.cursor,- candidateCount: operation.candidates.length,- }- : null,- };- }-- upsertParticipant(- input: ParticipantInput,- nowMs?: number,- ): readonly Resource[] {- if ((input.peerId === this.options.hostPeerId) !== (input.role === "host")) {- throw new Error("Route Host identity is inconsistent");- }- const capacity = this.effectiveCapacity(input.effectiveDownstreamCapacity);- const current = this.participants.get(input.peerId);- const released: Resource[] = [];- if (current && current.role !== input.role) throw new Error("Route role cannot change");- if (current) {- let changed = false;- const previousSessionId = current.sessionId;- if (previousSessionId !== input.sessionId) {- this.clearOpportunitiesForSessionChange(input.peerId, input.role);- this.clearQualityForParticipant(input.peerId);- const revisionBefore = this.revision;- if (this.operationUsesParticipantSession(input.peerId)) {- released.push(...this.abortOperation(nowMs, "stale"));- }- this.directContinuations.delete(input.peerId);- this.clearSfuBootstrapForDemand(input.peerId);- current.sessionId = input.sessionId;- const rebound = this.rebindCommittedSession(input.peerId, input.sessionId);- released.push(...rebound.released);- if (rebound.retired && this.revision === revisionBefore) {- this.revision = this.allocateRevision();- }- changed = true;- }- if (current.departureConfirmed) {- current.departureConfirmed = false;- changed = true;- }- if (current.effectiveDownstreamCapacity !== capacity) {- current.effectiveDownstreamCapacity = capacity;- changed = true;- }- if (changed) {- this.touchFacts();- this.debug("participant-updated", {- participant: this.debugPeer(input.peerId),- capacity,- sessionChanged: previousSessionId !== input.sessionId,- });- }- if (- input.role === "viewer" &&- nowMs !== undefined &&- !this.usableRoute(input.peerId)- ) {- this.recordDemand(input.peerId, nowMs, "join");- }- return released;- } else {- this.participants.set(input.peerId, {- ...input,- effectiveDownstreamCapacity: capacity,- departureConfirmed: false,- joinOrder: this.nextJoinOrder++,- availabilityExhausted: false,- consumedCandidateOpportunities: new Map(),- });- this.debug("participant-joined", {- participant: this.debugPeer(input.peerId),- role: input.role,- capacity,- });- }- if (input.role === "viewer" && nowMs !== undefined) {- this.recordDemand(input.peerId, nowMs, "join");- }- this.touchFacts();- return released;- }-- rebindHostIdentity(- peerId: string,- sessionId: string,- nowMs?: number,- ): readonly Resource[] {- const previousPeerId = this.options.hostPeerId;- if (peerId === previousPeerId) {- return this.upsertParticipant({- peerId,- role: "host",- sessionId,- effectiveDownstreamCapacity: this.options.endpointMediaCopyCapacity,- }, nowMs);- }- if (this.participants.has(peerId)) {- throw new Error("Route Host identity collides with another participant");- }- const host = this.participants.get(previousPeerId);- if (!host || host.role !== "host") {- throw new Error("Route Host identity is unavailable");- }-- const released = new Set(- this.operation ? this.abortOperation(nowMs, "stale") : [],- );- for (const edge of this.upstreamByViewer.values()) {- if (edge.kind === "sfu" && edge.physicalActive) {- released.add(edge.resource);- }- }- if (this.hostPublication?.physicalActive) {- released.add(this.hostPublication.resource);- }- this.upstreamByViewer.clear();- this.hostPublication = null;- this.routeTimings.clear();- this.qualityObservations.clear();- this.senderQualityObservations.clear();- this.senderQualityBaselines.clear();- this.senderQualityRegenerationBlocks.clear();- this.qualityBaselinesPending.clear();- this.sfuPublisherQualityObservation = undefined;- this.directContinuations.clear();- this.retiringPublicationGenerations.clear();- this.sfuBootstrapIntent = undefined;- this.consumedSfuBootstrapOpportunities.clear();- this.rootConvergenceRootPeerId = undefined;- for (const participant of this.participants.values()) {- participant.availabilityExhausted = false;- participant.bootstrapFailureReported = undefined;- participant.sfuFirstAtNextRoute = undefined;- participant.consumedCandidateOpportunities.clear();- if (- participant.role === "viewer" &&- participant.sessionId !== null &&- nowMs !== undefined- ) {- this.recordDemand(participant.peerId, nowMs, "edge-unavailable");- }- }-- this.participants.delete(previousPeerId);- host.peerId = peerId;- host.sessionId = sessionId;- host.departureConfirmed = false;- this.participants.set(peerId, host);- this.options.hostPeerId = peerId;- this.revision = this.allocateRevision();- this.touchFacts();- this.assertGraph();- return [...released];- }-- disconnectSession(peerId: string, sessionId: string): boolean {- const participant = this.participants.get(peerId);- if (!participant || participant.sessionId !== sessionId) return false;- this.clearOpportunitiesForSessionChange(peerId, participant.role);- participant.sessionId = null;- this.clearQualityForParticipant(peerId);- this.directContinuations.delete(peerId);- this.clearSfuBootstrapForDemand(peerId);- this.touchFacts();- this.debug("participant-disconnected", {- participant: this.debugPeer(peerId),- });- return true;- }-- confirmDeparture(peerId: string, nowMs?: number): boolean {- const participant = this.participants.get(peerId);- if (!participant || participant.role === "host") return false;- this.routeTimings.delete(peerId);- if (participant.departureConfirmed && participant.sessionId === null &&- participant.effectiveDownstreamCapacity === 0) return true;- this.clearOpportunitiesForSessionChange(peerId, participant.role);- participant.sessionId = null;- this.clearQualityForParticipant(peerId);- participant.departureConfirmed = true;- participant.effectiveDownstreamCapacity = 0;- this.directContinuations.delete(peerId);- this.clearSfuBootstrapForDemand(peerId);- if (nowMs !== undefined) {- for (const childPeerId of this.childrenOf(peerId)) {- this.recordDemand(childPeerId, nowMs, "parent-departed");- }- }- this.touchFacts();- this.debug("participant-departed", {- participant: this.debugPeer(peerId),- });- return true;- }-- setEffectiveCapacity(- peerId: string,- sessionId: string,- value: number,- nowMs?: number,- ): boolean {- const participant = this.participants.get(peerId);- if (!participant || participant.sessionId !== sessionId) return false;- const capacity = this.effectiveCapacity(value);- const changed = participant.effectiveDownstreamCapacity !== capacity;- if (!changed) return true;- participant.effectiveDownstreamCapacity = capacity;- if (nowMs !== undefined) {- for (const childPeerId of this.overflowPeerChildren(peerId)) {- this.recordDemand(childPeerId, nowMs, "capacity-reduction");- }- }- this.touchFacts();- this.debug("capacity-updated", {- participant: this.debugPeer(peerId),- capacity,- });- return true;- }-- touchExternalFacts(): void {- this.clearSfuCandidateOpportunities();- this.sfuBootstrapIntent = undefined;- this.touchFacts();- }-- hydrateEdge(- childPeerId: string,- edge: CommittedEdgeSeed<Resource>,- ): void {- if (this.operation) throw new Error("Cannot hydrate while an operation is active");- this.assertViewer(childPeerId);- const childSessionId = this.participants.get(childPeerId)!.sessionId;- if (!childSessionId) throw new Error("Route child has no current session");- this.upstreamByViewer.set(childPeerId, edge.kind === "peer" ? {- ...edge,- childSessionId,- parentSessionId:- this.participants.get(edge.parentPeerId)?.sessionId ?? "",- } : { ...edge, childSessionId });- this.requireSenderQualityBaseline(childPeerId);- this.assertGraph();- }-- hydrateHostPublication(- generation: string,- resource: Resource,- connectionId = `publication:${generation}`,- ): void {- if (this.operation) throw new Error("Cannot hydrate while an operation is active");- const hostSessionId = this.participants.get(this.options.hostPeerId)?.sessionId;- if (!hostSessionId) throw new Error("Route Host has no current session");- this.hostPublication = {- generation,- hostSessionId,- connectionId,- usable: true,- physicalActive: true,- resource,- };- this.assertGraph();- }-- invalidateEdge(guard: EdgeGuard, nowMs?: number): boolean {- const child = this.participants.get(guard.childPeerId);- const edge = this.upstreamByViewer.get(guard.childPeerId);- if (!child || child.sessionId !== guard.childSessionId || this.revision !== guard.routeRevision ||- !edge || edge.connectionId !== guard.connectionId ||- edge.childSessionId !== guard.childSessionId ||- (edge.kind === "peer" && edge.parentSessionId !== guard.parentSessionId)) {- return false;- }- if (edge.usable) {- this.consumeActiveEdgeOpportunity(child, edge);- this.clearQualityForParticipant(guard.childPeerId);- edge.usable = false;- this.directContinuations.delete(guard.childPeerId);- child.availabilityExhausted = false;- child.bootstrapFailureReported = undefined;- this.touchFacts();- if (nowMs !== undefined) {- this.recordDemand(guard.childPeerId, nowMs, "edge-unavailable");- }- }- return true;- }-- invalidateDirectEdgeFromParent(- input: {- parentPeerId: string;- parentSessionId: string;- routeRevision: number;- connectionId: string;- },- nowMs?: number,- ): boolean {- const match = [...this.upstreamByViewer].find(- ([, edge]) =>- edge.kind === "peer" &&- edge.parentPeerId === input.parentPeerId &&- edge.parentSessionId === input.parentSessionId &&- edge.connectionId === input.connectionId,- );- if (!match) return false;- const [childPeerId, edge] = match;- return this.invalidateEdge(- {- childPeerId,- childSessionId: edge.childSessionId,- parentSessionId: input.parentSessionId,- routeRevision: input.routeRevision,- connectionId: input.connectionId,- },- nowMs,- );- }-- invalidateHostPublication(guard: {- hostSessionId: string;- routeRevision: number;- generation: string;- connectionId: string;- }, nowMs?: number): boolean {- const publication = this.hostPublication;- if (!publication || this.revision !== guard.routeRevision ||- publication.hostSessionId !== guard.hostSessionId ||- publication.generation !== guard.generation ||- publication.connectionId !== guard.connectionId) return false;- if (publication.usable) {- this.clearSfuQuality();- publication.usable = false;- this.directContinuations.clear();- this.sfuBootstrapIntent = undefined;- if (nowMs !== undefined) {- for (const [childPeerId, edge] of this.upstreamByViewer) {- if (edge.kind === "sfu") {- this.recordDemand(childPeerId, nowMs, "edge-unavailable");- }- }- }- this.touchFacts();- }- return true;- }-- adoptDirectConnection(input: EdgeGuard & { newConnectionId: string }): boolean {- const edge = this.upstreamByViewer.get(input.childPeerId);- if (- this.operation?.childPeerId === input.childPeerId ||- this.revision !== input.routeRevision ||- !edge ||- edge.kind !== "peer" ||- edge.transport !== "direct" ||- !edge.usable ||- !edge.physicalActive ||- edge.childSessionId !== input.childSessionId ||- edge.parentSessionId !== input.parentSessionId ||- edge.connectionId !== input.connectionId ||- !input.newConnectionId- ) {- return false;- }- if (input.newConnectionId === edge.connectionId) return true;- this.clearQualityForParticipant(input.childPeerId);- edge.connectionId = input.newConnectionId;- const child = this.participants.get(input.childPeerId);- if (child) child.availabilityExhausted = false;- this.touchFacts();- return true;- }-- retireCommittedTransport(guard: EdgeGuard): readonly Resource[] {- const child = this.participants.get(guard.childPeerId);- const edge = this.upstreamByViewer.get(guard.childPeerId);- if (this.operation?.current || !child || child.sessionId !== guard.childSessionId || this.revision !== guard.routeRevision ||- !edge || edge.connectionId !== guard.connectionId || !edge.physicalActive ||- edge.childSessionId !== guard.childSessionId ||- (edge.kind === "peer" && edge.parentSessionId !== guard.parentSessionId)) {- return [];- }- const released: Resource[] = [];- if (edge.kind === "sfu") {- this.retireSfuEdge(guard.childPeerId, edge, released);- this.pruneRetiringSfuAnchors();- } else {- edge.physicalActive = false;- edge.usable = false;- }- this.clearQualityForParticipant(guard.childPeerId);- child.availabilityExhausted = false;- this.revision = this.allocateRevision();- if (this.operation) this.operation.baseRevision = this.revision;- this.touchFacts();- return released;- }-- retireHostPublication(guard: {- hostSessionId: string;- routeRevision: number;- generation: string;- connectionId: string;- }): readonly Resource[] {- const publication = this.hostPublication;- if (this.operation?.current || !publication || !publication.physicalActive ||- this.revision !== guard.routeRevision ||- publication.hostSessionId !== guard.hostSessionId ||- publication.generation !== guard.generation ||- publication.connectionId !== guard.connectionId) return [];- const released: Resource[] = [];- for (const [viewerPeerId, edge] of this.upstreamByViewer) {- if (- edge.kind === "sfu" &&- edge.publicationGeneration === publication.generation- ) {- this.retireSfuEdge(viewerPeerId, edge, released);- }- }- publication.physicalActive = false;- publication.usable = false;- this.hostPublication = null;- this.clearSfuQuality();- this.revision = this.allocateRevision();- if (this.operation) this.operation.baseRevision = this.revision;- this.touchFacts();- released.push(publication.resource);- this.pruneRetiringSfuAnchors();- return released;- }-- setPaused(paused: boolean, nowMs?: number): readonly Resource[] {- if (this.paused === paused) return [];- this.paused = paused;- if (paused) {- this.qualityObservations.clear();- this.qualityBaselinesPending.clear();- this.senderQualityObservations.clear();- this.senderQualityBaselines.clear();- this.senderQualityRegenerationBlocks.clear();- this.sfuPublisherQualityObservation = undefined;- }- this.touchFacts();- return paused ? this.abortOperation(nowMs, "aborted") : [];- }-- observeQualityEvidence(- input: RouteQualityEvidenceInput,- ): RouteQualityEvidenceResult {- if (- this.paused ||- input.routeRevision !== this.revision ||- !Number.isSafeInteger(input.presentationEpoch) ||- input.presentationEpoch < 0 ||- !Number.isSafeInteger(input.windowMs) ||- input.windowMs <= 0 ||- !Number.isSafeInteger(input.acceptedAtMs) ||- input.acceptedAtMs < 0- ) {- return "rejected";- }- const child = this.participants.get(input.childPeerId);- const edge = this.upstreamByViewer.get(input.childPeerId);- if (- !child ||- child.sessionId !== input.childSessionId ||- !edge ||- !edge.usable ||- !edge.physicalActive ||- edge.childSessionId !== input.childSessionId ||- edge.connectionId !== input.connectionId ||- !this.qualityUpstreamMatches(edge, input.upstream) ||- !this.sourceUsableForQuality(edge)- ) {- return "rejected";- }-- const upstreamPeerId =- input.upstream.kind === "peer" ? input.upstream.peerId : null;- let observation = this.qualityObservations.get(input.childPeerId);- const sameEdgeObservation =- observation?.childSessionId === input.childSessionId &&- observation.upstreamKind === input.upstream.kind &&- observation.upstreamPeerId === upstreamPeerId &&- observation.connectionId === input.connectionId;- if (- sameEdgeObservation &&- observation &&- input.presentationEpoch < observation.presentationEpoch- ) {- return "rejected";- }- if (- !sameEdgeObservation ||- !observation ||- observation.presentationEpoch !== input.presentationEpoch- ) {- observation = {- childSessionId: input.childSessionId,- upstreamKind: input.upstream.kind,- upstreamPeerId,- connectionId: input.connectionId,- presentationEpoch: input.presentationEpoch,- eligibleWindows: 0,- eligibleDurationMs: 0,- freezeWindows: 0,- freezeCount: 0,- freezeDurationMs: 0,- pauseCount: 0,- pauseDurationMs: 0,- lastAcceptedAtMs: input.acceptedAtMs,- lastDecodedProgressAtMs: null,- };- this.qualityObservations.set(input.childPeerId, observation);- }-- const metrics = input.metrics;- if (- metrics.framesDecodedDelta === null ||- metrics.framesDecodedDelta <= 0- ) {- return "accepted";- }- const hadFreshDecodedProgress =- observation.lastDecodedProgressAtMs !== null &&- input.acceptedAtMs <- observation.lastDecodedProgressAtMs +- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;- observation.lastDecodedProgressAtMs = input.acceptedAtMs;- if (!hadFreshDecodedProgress && edge.kind === "sfu") {- this.touchFacts();- }- if (- metrics.freezeCountDelta === null ||- metrics.freezeDurationMsDelta === null ||- metrics.pauseCountDelta === null ||- metrics.pauseDurationMsDelta === null- ) {- return "accepted";- }- observation.lastAcceptedAtMs = input.acceptedAtMs;- if (this.qualityBaselinesPending.delete(input.childPeerId)) {- return "accepted";- }-- observation.eligibleWindows = safeAdd(observation.eligibleWindows, 1);- observation.eligibleDurationMs = safeAdd(- observation.eligibleDurationMs,- input.windowMs,- );- if (metrics.freezeCountDelta > 0) {- observation.freezeWindows = safeAdd(observation.freezeWindows, 1);- }- observation.freezeCount = safeAdd(- observation.freezeCount,- metrics.freezeCountDelta,- );- observation.freezeDurationMs = safeAdd(- observation.freezeDurationMs,- metrics.freezeDurationMsDelta,- );- observation.pauseCount = safeAdd(- observation.pauseCount,- metrics.pauseCountDelta,- );- observation.pauseDurationMs = safeAdd(- observation.pauseDurationMs,- metrics.pauseDurationMsDelta,- );- return "observed";- }-- observeSenderQualityEvidence(- input: SenderQualityEvidenceInput,- commitReservation: (- reservation: CandidateReservation<Resource>,- ) => boolean = () => true,- ): SenderQualityEvidenceResult<Resource> {- const rejected = (): SenderQualityEvidenceResult<Resource> => ({- accepted: false,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- });- if (- this.options.qualityConvergenceEnabled !== true ||- this.paused ||- !Number.isSafeInteger(input.acceptedAtMs) ||- input.acceptedAtMs < 0- ) {- return rejected();- }- const parent = this.participants.get(input.parentPeerId);- const child = this.participants.get(input.childPeerId);- if (- !parent?.sessionId ||- parent.sessionId !== input.parentSessionId ||- !child?.sessionId ||- child.departureConfirmed ||- parent.departureConfirmed- ) {- return rejected();- }-- const operation = this.operation;- const attempt = operation?.current;- if (- (operation?.reason === "root-convergence" ||- operation?.reason === "quality-convergence") &&- attempt?.tuple.kind === "peer" &&- operation.childPeerId === input.childPeerId &&- operation.childSessionId === child.sessionId &&- attempt.tuple.parentPeerId === input.parentPeerId &&- attempt.parentSessionId === input.parentSessionId &&- attempt.connectionId === input.connectionId &&- attempt.revision === input.routeRevision- ) {- return this.settleCandidateQuality(- operation,- attempt,- input.state,- input.acceptedAtMs,- input.senderIdentity,- input.sampleTimestampMs,- commitReservation,- );- }-- const edge = this.upstreamByViewer.get(input.childPeerId);- if (- input.routeRevision !== this.revision ||- edge?.kind !== "peer" ||- !edge.usable ||- !edge.physicalActive ||- edge.parentPeerId !== input.parentPeerId ||- edge.parentSessionId !== input.parentSessionId ||- edge.childSessionId !== child.sessionId ||- edge.connectionId !== input.connectionId- ) {- return rejected();- }- const previous = this.senderQualityObservations.get(input.childPeerId);- const sameConnectionIdentity =- previous?.childSessionId === child.sessionId &&- previous.parentPeerId === input.parentPeerId &&- previous.parentSessionId === input.parentSessionId &&- previous.connectionId === input.connectionId;- if (input.state === "unknown") {- if (previous && previous.state !== "unknown") {- this.debug("sender-quality-reset", {- parent: this.debugPeer(input.parentPeerId),- child: this.debugPeer(input.childPeerId),- });- }- if (previous && sameConnectionIdentity) {- this.senderQualityObservations.set(input.childPeerId, {- ...previous,- state: "unknown",- consecutiveDegradedWindows: 0,- lastAcceptedAtMs: input.acceptedAtMs,- });- } else {- this.senderQualityObservations.delete(input.childPeerId);- }- return {- accepted: true,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- };- }- if (!input.senderIdentity || input.sampleTimestampMs === null) {- return rejected();- }- const sameSenderIdentity =- sameConnectionIdentity && previous?.senderIdentity === input.senderIdentity;- if (- sameSenderIdentity &&- previous !== undefined &&- input.sampleTimestampMs <= previous.lastSampleTimestampMs- ) {- return {- accepted: true,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- };- }- const regenerationBlock = this.senderQualityRegenerationBlocks.get(- input.childPeerId,- );- if (- regenerationBlock &&- !senderQualityRegenerationBlockMatches(- regenerationBlock,- child.sessionId,- input,- )- ) {- // A new connection or sender identity is a new generation. Do not carry- // a same-edge regeneration latch across that identity fence.- this.senderQualityRegenerationBlocks.delete(input.childPeerId);- }- if (input.state === "healthy") {- this.senderQualityRegenerationBlocks.delete(input.childPeerId);- }- const sameFreshSenderIdentity =- sameSenderIdentity &&- previous !== undefined &&- input.acceptedAtMs <- previous.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;- if (input.state === "healthy") {- this.senderQualityBaselines.delete(input.childPeerId);- }- const consecutiveDegradedWindows =- input.state === "degraded"- ? sameFreshSenderIdentity && previous.state === "degraded"- ? safeAdd(previous.consecutiveDegradedWindows, 1)- : 1- : 0;- this.senderQualityObservations.set(input.childPeerId, {- childSessionId: child.sessionId,- parentPeerId: input.parentPeerId,- parentSessionId: input.parentSessionId,- connectionId: input.connectionId,- senderIdentity: input.senderIdentity,- state: input.state,- consecutiveDegradedWindows,- lastSampleTimestampMs: input.sampleTimestampMs,- lastAcceptedAtMs: input.acceptedAtMs,- consumedQualityCandidates:- sameSenderIdentity && previous && input.state !== "healthy"- ? previous.consumedQualityCandidates- : new Map(),- });- if (- !sameFreshSenderIdentity ||- previous.state !== input.state ||- consecutiveDegradedWindows ===- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS- ) {- this.debug("sender-quality-observed", {- parent: this.debugPeer(input.parentPeerId),- child: this.debugPeer(input.childPeerId),- state: input.state,- consecutiveDegradedWindows,- });- }- if (- input.state === "healthy" &&- operation?.reason === "quality-convergence" &&- operation.childPeerId === input.childPeerId- ) {- const released = this.abortOperation(input.acceptedAtMs, "aborted");- return {- accepted: true,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released,- };- }- return {- accepted: true,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- };- }-- observeSfuPublisherQualityEvidence(- input: SfuPublisherQualityEvidenceInput,- commitReservation: (- reservation: CandidateReservation<Resource>,- ) => boolean = () => true,- ): SenderQualityEvidenceResult<Resource> {- const rejected = (): SenderQualityEvidenceResult<Resource> => ({- accepted: false,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- });- const host = this.participants.get(this.options.hostPeerId);- if (- this.options.qualityConvergenceEnabled !== true ||- this.paused ||- input.hostPeerId !== this.options.hostPeerId ||- !host?.sessionId ||- host.sessionId !== input.hostSessionId- ) {- return rejected();- }- const operation = this.operation;- const attempt = operation?.current;- if (- operation?.reason === "quality-convergence" &&- attempt?.tuple.kind === "sfu" &&- attempt.hostSessionId === input.hostSessionId &&- attempt.publicationGeneration === input.publicationGeneration &&- attempt.revision === input.routeRevision- ) {- return this.settleCandidateQuality(- operation,- attempt,- input.state,- input.acceptedAtMs,- input.publicationGeneration,- input.sampleTimestampMs,- commitReservation,- );- }- if (- input.routeRevision !== this.revision ||- !this.hostPublication?.usable ||- !this.hostPublication.physicalActive ||- this.hostPublication.hostSessionId !== input.hostSessionId ||- this.hostPublication.generation !== input.publicationGeneration- ) {- return rejected();- }- if (input.state === "unknown") {- if (this.sfuPublisherQualityObservation) {- this.debug("sfu-publisher-quality-reset", {});- }- this.sfuPublisherQualityObservation = undefined;- return {- accepted: true,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- };- }- if (input.sampleTimestampMs === null) {- return rejected();- }- const previous = this.sfuPublisherQualityObservation;- if (- previous?.hostSessionId === input.hostSessionId &&- previous.publicationGeneration === input.publicationGeneration &&- input.sampleTimestampMs <= previous.lastSampleTimestampMs- ) {- return {- accepted: true,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- };- }- const sameFreshPublication =- previous?.hostSessionId === input.hostSessionId &&- previous.publicationGeneration === input.publicationGeneration &&- input.acceptedAtMs <- previous.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;- const consecutiveHealthyWindows =- input.state === "healthy"- ? sameFreshPublication && previous.state === "healthy"- ? safeAdd(previous.consecutiveHealthyWindows, 1)- : 1- : 0;- const wasPersistentlyHealthy =- sameFreshPublication &&- previous.state === "healthy" &&- previous.consecutiveHealthyWindows >=- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS;- this.sfuPublisherQualityObservation = {- hostSessionId: input.hostSessionId,- publicationGeneration: input.publicationGeneration,- state: input.state,- consecutiveHealthyWindows,- lastSampleTimestampMs: input.sampleTimestampMs,- lastAcceptedAtMs: input.acceptedAtMs,- };- if (- previous?.hostSessionId !== input.hostSessionId ||- previous.publicationGeneration !== input.publicationGeneration ||- previous.state !== input.state ||- consecutiveHealthyWindows ===- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS- ) {- this.debug("sfu-publisher-quality-observed", {- state: input.state,- consecutiveHealthyWindows,- });- }- if (- input.state === "healthy" &&- consecutiveHealthyWindows >=- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS &&- !wasPersistentlyHealthy- ) {- this.touchFacts();- }- if (- operation?.reason === "quality-convergence" &&- attempt?.tuple.kind === "sfu" &&- attempt.tuple.publication === "reuse" &&- attempt.hostSessionId === input.hostSessionId &&- attempt.publicationGeneration === input.publicationGeneration &&- attempt.mediaReady- ) {- const guard = {- childPeerId: operation.childPeerId,- childSessionId: operation.childSessionId,- revision: attempt.revision,- connectionId: attempt.connectionId,- };- const settled =- input.state === "degraded"- ? this.candidateFailed(guard, input.acceptedAtMs)- : consecutiveHealthyWindows >=- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS- ? this.candidateReady(- guard,- input.acceptedAtMs,- commitReservation,- )- : null;- if (settled) {- return {- accepted: settled.accepted,- committed: settled.committed === true,- failedPeerIds: settled.failedPeerIds,- activeRevision: settled.activeRevision,- released: settled.released,- };- }- }- return {- accepted: true,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- };- }-- private settleCandidateQuality(- operation: ChildOperation<Resource>,- attempt: Attempt<Resource>,- state: "unknown" | "healthy" | "degraded",- acceptedAtMs: number,- senderIdentity: string | null,- sampleTimestampMs: number | null,- commitReservation: (- reservation: CandidateReservation<Resource>,- ) => boolean,- ): SenderQualityEvidenceResult<Resource> {- if (attempt.senderQualityState !== state) {- this.debug("candidate-quality-observed", {- child: this.debugPeer(operation.childPeerId),- candidate: this.debugTuple(attempt.tuple),- state,- });- }- if (state === "unknown") {- attempt.senderQualityState = undefined;- attempt.senderQualityAcceptedAtMs = undefined;- attempt.senderQualityConsecutiveHealthyWindows = undefined;- attempt.senderQualityConsecutiveDegradedWindows = undefined;- attempt.senderQualitySampleTimestampMs = undefined;- return {- accepted: true,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- };- }- if (!senderIdentity || sampleTimestampMs === null) {- return {- accepted: false,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- };- }- if (- attempt.senderQualityIdentity !== undefined &&- attempt.senderQualityIdentity !== senderIdentity- ) {- const failed = this.candidateFailed(- {- childPeerId: operation.childPeerId,- childSessionId: operation.childSessionId,- revision: attempt.revision,- connectionId: attempt.connectionId,- },- acceptedAtMs,- );- return {- accepted: failed.accepted,- committed: failed.committed === true,- failedPeerIds: failed.failedPeerIds,- activeRevision: failed.activeRevision,- released: failed.released,- };- }- if (- attempt.senderQualitySampleTimestampMs !== undefined &&- sampleTimestampMs <= attempt.senderQualitySampleTimestampMs- ) {- return {- accepted: true,- committed: false,- failedPeerIds: [],- activeRevision: this.revision,- released: [],- };- }- const sameFreshState =- attempt.senderQualityAcceptedAtMs !== undefined &&- acceptedAtMs <- attempt.senderQualityAcceptedAtMs +- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;- const consecutiveHealthyWindows =- attempt.tuple.kind === "sfu" && state === "healthy"- ? attempt.senderQualityState === "healthy" &&- sameFreshState- ? safeAdd(- attempt.senderQualityConsecutiveHealthyWindows ?? 0,- 1,- )- : 1- : state === "healthy"- ? 1- : 0;- const consecutiveDegradedWindows =- state === "degraded"- ? attempt.senderQualityState === "degraded" && sameFreshState- ? safeAdd(- attempt.senderQualityConsecutiveDegradedWindows ?? 0,- 1,- )- : 1- : 0;- attempt.senderQualityState = state;- attempt.senderQualityAcceptedAtMs = acceptedAtMs;- attempt.senderQualityConsecutiveHealthyWindows =- consecutiveHealthyWindows;- attempt.senderQualityConsecutiveDegradedWindows =- consecutiveDegradedWindows;- attempt.senderQualitySampleTimestampMs = sampleTimestampMs;- attempt.senderQualityIdentity = senderIdentity;- const guard = {- childPeerId: operation.childPeerId,- childSessionId: operation.childSessionId,- revision: attempt.revision,- connectionId: attempt.connectionId,- };- const persistentQualityPeerDegradation =- operation.reason === "quality-convergence" &&- attempt.tuple.kind === "peer" &&- consecutiveDegradedWindows >= PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS;- const settled =- state === "degraded" &&- (attempt.tuple.kind !== "peer" ||- operation.reason !== "quality-convergence" ||- persistentQualityPeerDegradation)- ? this.candidateFailed(guard, acceptedAtMs)- : attempt.mediaReady &&- (attempt.tuple.kind !== "sfu" ||- consecutiveHealthyWindows >=- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS)- ? this.candidateReady(guard, acceptedAtMs, commitReservation)- : null;- return {- accepted: true,- committed: settled?.committed === true,- failedPeerIds: settled?.failedPeerIds ?? [],- activeRevision: settled?.activeRevision ?? this.revision,- released: settled?.released ?? [],- };- }-- resetSenderQuality(- parentPeerId: string,- parentSessionId: string,- nowMs: number,- ): readonly Resource[] {- const parent = this.participants.get(parentPeerId);- if (parent?.sessionId !== parentSessionId) {- return [];- }- const children = new Set(this.childrenOf(parentPeerId));- for (const [childPeerId, observation] of this.senderQualityObservations) {- if (- observation.parentPeerId === parentPeerId &&- observation.parentSessionId === parentSessionId- ) {- children.add(childPeerId);- }- }- for (const childPeerId of children) {- this.senderQualityObservations.delete(childPeerId);- // Reset means the next exact sender sequence is a new observation- // window. A quality/root commit still installs the explicit rearm latch- // below; a visibility or source reset must not deadlock a persistently- // limited edge waiting for a healthy sample.- this.senderQualityBaselines.delete(childPeerId);- this.senderQualityRegenerationBlocks.delete(childPeerId);- }- if (parentPeerId === this.options.hostPeerId) {- this.sfuPublisherQualityObservation = undefined;- }- const operation = this.operation;- const attempt = operation?.current;- const ownsCandidate =- attempt &&- (attempt.tuple.kind === "peer"- ? (operation?.reason === "root-convergence" ||- operation?.reason === "quality-convergence") &&- attempt.tuple.parentPeerId === parentPeerId &&- attempt.parentSessionId === parentSessionId- : this.operationRequiresNativeCandidateProof(operation) &&- parentPeerId === this.options.hostPeerId &&- attempt.hostSessionId === parentSessionId);- return ownsCandidate ? this.abortOperation(nowMs, "aborted") : [];- }-- reconcile(nowMs: number): ReconcileResult<Resource> {- const released: Resource[] = [];- const validation = this.validateOrAdvance(nowMs);- released.push(...validation.released);- const failedPeerIds = failedPeerIdsFrom(validation);- if (- this.operation &&- this.isBackgroundConvergence(this.operation.reason) &&- (this.hasSfuBootstrapWork() || this.selectNextChild())- ) {- this.debug(`${this.operation.reason}-preempted`, {- child: this.debugPeer(this.operation.childPeerId),- });- released.push(...this.abortOperation(nowMs, "aborted"));- }- if (this.paused || this.operation) {- return {- operation: this.operationSnapshot(),- removedPeerIds: [],- failedPeerIds,- released,- };- }- const removedPeerIds = this.pruneDepartedLeaves(released);-- for (let remaining = this.participants.size; remaining > 0; remaining -= 1) {- const bootstrap = this.takeSfuBootstrapCarrier(nowMs, failedPeerIds);- const routeChildPeerId = bootstrap ? undefined : this.selectNextChild();- const continuation = routeChildPeerId- ? undefined- : bootstrap- ? undefined- : this.selectDirectContinuation();- const qualityChildPeerId =- routeChildPeerId || bootstrap || continuation- ? undefined- : this.selectQualityChild(nowMs);- const rootConvergence =- routeChildPeerId || bootstrap || continuation || qualityChildPeerId- ? undefined- : this.takeRootConvergenceIntent();- const childPeerId =- routeChildPeerId ??- bootstrap?.carrierPeerId ??- continuation?.childPeerId ??- qualityChildPeerId ??- rootConvergence?.childPeerId;- if (!childPeerId) return { removedPeerIds, failedPeerIds, released };- const child = this.participants.get(childPeerId)!;- const reason: RouteDemandReason = continuation- ? "direct-convergence"- : bootstrap- ? "sfu-bootstrap"- : qualityChildPeerId- ? "quality-convergence"- : rootConvergence- ? "root-convergence"- : this.routeDemandReason(childPeerId);- const demandPeerId = bootstrap?.demandPeerId ?? childPeerId;- const demand = this.participants.get(demandPeerId)!;- this.ensureDemand(demandPeerId, nowMs, reason);- let candidates = continuation- ? [continuation.plan]- : qualityChildPeerId- ? this.buildQualityCandidates(childPeerId, nowMs)- : rootConvergence- ? [rootConvergence.plan]- : this.buildCandidates(childPeerId, bootstrap !== undefined);- if (!bootstrap && !continuation && demand.sfuFirstAtNextRoute) {- const sfuIndex = candidates.findIndex(- (candidate) => candidate.tuple.kind === "sfu",- );- if (sfuIndex > 0) {- const [sfu] = candidates.splice(sfuIndex, 1);- candidates = [sfu!, ...candidates];- }- }- if (reason === "sfu-bootstrap") {- candidates = candidates.filter(- (candidate) => candidate.endpointTransition.kind !== "bounded-gap",- );- }- if (candidates.length === 0) {- this.debug("operation-unavailable", {- child: this.debugPeer(childPeerId),- reason,- });- if (this.isBackgroundConvergence(reason)) {- if (reason === "direct-convergence") {- this.directContinuations.delete(childPeerId);- }- this.finishTiming(- childPeerId,- nowMs,- this.currentFinalRoute(childPeerId),- "candidate-failed",- );- continue;- }- if (reason === "sfu-bootstrap") {- const failedDemandPeerId = this.completeSfuBootstrapCarrier(- childPeerId,- nowMs,- "candidate-failed",- );- if (failedDemandPeerId) failedPeerIds.push(failedDemandPeerId);- continue;- }- if (this.retireInvalidOperationEdge(childPeerId, released)) {- this.revision = this.allocateRevision();- this.touchFacts();- }- child.availabilityExhausted = true;- this.finishTiming(- demandPeerId,- nowMs,- "failed",- reason === "capacity-reduction"- ? "endpoint-capacity"- : "candidate-failed",- );- if (this.bootstrapCandidateAvailable(demandPeerId)) {- continue;- }- this.rememberUnavailableSfuBootstrap(demandPeerId);- failedPeerIds.push(demandPeerId);- continue;- }- this.startOperationTiming(demandPeerId, nowMs);- this.operation = {- childPeerId,- childSessionId: child.sessionId!,- demandPeerId,- demandSessionId: demand.sessionId!,- reason,- baseRevision: this.revision,- candidates,- cursor: 0,- deadlineAtMs: nowMs + this.options.operationTimeoutMs,- builtAtFactVersion: this.factVersion,- deferredParentPeerIds: [],- peerAttemptStarted: false,- qualitySource:- reason === "quality-convergence"- ? this.currentQualityOperationSource(childPeerId)- : undefined,- };- this.debug("operation-started", {- child: this.debugPeer(childPeerId),- reason,- candidates: candidates.map((candidate) => ({- route: this.debugTuple(candidate.tuple),- transition: candidate.endpointTransition.kind,- })),- });- return {- operation: this.operationSnapshot(),- removedPeerIds,- failedPeerIds,- released,- };- }- return { removedPeerIds, failedPeerIds, released };- }-- beginCurrentCandidate(input: {- guard: CandidateCursorGuard;- nowMs: number;- connectionId: string;- reservation: CandidateReservation<Resource>;- publicationGeneration?: string;- publicationConnectionId?: string;- hostSessionId?: string;- }): BeginResult<Resource> {- const validation = this.validateOrAdvance(input.nowMs);- const operation = this.operation;- if (!operation || operation.current || operation.baseRevision !== this.revision ||- !this.cursorGuardMatches(input.guard, operation)) {- return {- accepted: false,- released: [...validation.released, ...reservationResources(input.reservation)],- failedPeerIds: failedPeerIdsFrom(validation),- };- }- const plan = operation.candidates[operation.cursor];- if (!plan || !this.operationCandidateValid(operation, plan)) {- return {- accepted: false,- released: [...validation.released, ...reservationResources(input.reservation)],- failedPeerIds: failedPeerIdsFrom(validation),- };- }- if (plan.endpointTransition.kind === "bounded-gap") {- return {- accepted: false,- operation: this.operationSnapshot(),- failedPeerIds: failedPeerIdsFrom(validation),- released: [...validation.released, ...reservationResources(input.reservation)],- };- }- const tuple = plan.tuple;- const hostSessionId =- tuple.kind === "sfu"- ? this.participants.get(this.options.hostPeerId)?.sessionId- : undefined;- if (- tuple.kind === "sfu" &&- (!input.hostSessionId || input.hostSessionId !== hostSessionId)- ) {- return {- accepted: false,- operation: this.operationSnapshot(),- failedPeerIds: failedPeerIdsFrom(validation),- released: [- ...validation.released,- ...reservationResources(input.reservation),- ],- };- }- this.assertReservation(tuple, input.reservation, plan.endpointTransition.kind === "overlap");- const publicationGeneration = tuple.kind === "sfu"- ? tuple.publication === "reuse" ? this.hostPublication?.generation : input.publicationGeneration- : undefined;- if (tuple.kind === "sfu" && !publicationGeneration) throw new Error("SFU candidate needs a publication generation");- if (tuple.kind === "sfu" && tuple.publication !== "reuse" && !input.publicationConnectionId) {- throw new Error("SFU publication candidate needs an ingress connection identity");- }- operation.current = {- tuple,- revision: this.allocateRevision(),- connectionId: input.connectionId,- childSessionId: operation.childSessionId,- parentSessionId: tuple.kind === "peer" ? this.participants.get(tuple.parentPeerId)?.sessionId ?? undefined : undefined,- hostSessionId:- tuple.kind === "sfu"- ? input.hostSessionId- : undefined,- publicationGeneration,- publicationConnectionId: input.publicationConnectionId,- reservation: input.reservation,- startedAtMs: input.nowMs,- transportConnected: false,- mediaReady: false,- connectionAttempt: this.startCandidateOpportunity(operation, plan),- };- this.debug("candidate-started", {- child: this.debugPeer(operation.childPeerId),- candidate: this.debugTuple(tuple),- revision: operation.current.revision,- cursor: operation.cursor,- ...(operation.current.connectionAttempt- ? { connectionAttempt: operation.current.connectionAttempt }- : {}),- });- this.startCandidateTiming(operation.demandPeerId, input.nowMs);- return {- accepted: true,- operation: this.operationSnapshot(),- failedPeerIds: failedPeerIdsFrom(validation),- released: validation.released,- };- }-- noteCurrentCandidateRejection(- guard: CandidateCursorGuard,- bucket: RouteDiagnosticRejectionBucket,- ): boolean {- const operation = this.operation;- if (- !operation ||- operation.current ||- !this.cursorGuardMatches(guard, operation)- ) {- return false;- }- this.noteRejection(operation.demandPeerId, bucket);- return true;- }-- skipCurrentCandidate(- guard: CandidateCursorGuard,- nowMs: number,- bucket: RouteDiagnosticRejectionBucket = "stale",- ): BeginResult<Resource> {- const validation = this.validateOrAdvance(nowMs);- const operation = this.operation;- if (!operation || operation.current || !this.cursorGuardMatches(guard, operation)) {- return {- accepted: false,- failedPeerIds: failedPeerIdsFrom(validation),- released: validation.released,- };- }- if (bucket === "candidate-failed") {- if (this.isAvailabilityOperation(operation.reason)) {- this.consumeCandidateOpportunity(- operation.childPeerId,- operation.candidates[operation.cursor]!,- );- }- this.promoteNextDirectWithinHeadStart(operation, nowMs);- }- this.consumeDirectContinuationCandidate(operation);- this.noteRejection(operation.demandPeerId, bucket);- this.debug("candidate-rejected", {- child: this.debugPeer(operation.childPeerId),- candidate: this.debugTuple(operation.candidates[operation.cursor]!.tuple),- bucket,- cursor: operation.cursor,- });- operation.cursor += 1;- this.clearCandidateTiming(operation.demandPeerId);- const advanced = this.validateOrAdvance(nowMs);- return {- operation: this.operationSnapshot(),- accepted: true,- failedPeerIds: failedPeerIdsFrom(validation, advanced),- released: [...validation.released, ...advanced.released],- };- }-- retireCurrentCandidateProducer(- guard: CandidateCursorGuard,- nowMs: number,- ): BeginResult<Resource> {- const validation = this.validateOrAdvance(nowMs);- const operation = this.operation;- if (!operation || operation.current || !this.cursorGuardMatches(guard, operation)) {- return {- accepted: false,- failedPeerIds: failedPeerIdsFrom(validation),- released: validation.released,- };- }- const plan = operation.candidates[operation.cursor];- if (!plan || plan.endpointTransition.kind !== "bounded-gap") {- return {- accepted: false,- operation: this.operationSnapshot(),- failedPeerIds: failedPeerIdsFrom(validation),- released: validation.released,- };- }- const released = [...validation.released];- const retirement = plan.endpointTransition.retire;- let restoreTuple: CandidateTuple | undefined;- if (retirement.kind === "edge") {- const edge = this.upstreamByViewer.get(retirement.childPeerId);- if (!edge || edge.kind !== "peer" || !edge.physicalActive ||- edge.childSessionId !== retirement.childSessionId ||- edge.parentPeerId !== retirement.parentPeerId ||- edge.parentSessionId !== retirement.parentSessionId ||- edge.transport !== retirement.transport ||- edge.connectionId !== retirement.connectionId) {- return {- accepted: false,- operation: this.operationSnapshot(),- failedPeerIds: failedPeerIdsFrom(validation),- released,- };- }- if (edge.usable) {- restoreTuple = {- kind: "peer",- parentPeerId: edge.parentPeerId,- transport: edge.transport,- };- }- edge.usable = false;- edge.physicalActive = false;- } else {- const publication = this.hostPublication;- if (!publication || !publication.physicalActive ||- publication.hostSessionId !== retirement.hostSessionId ||- publication.generation !== retirement.generation ||- publication.connectionId !== retirement.connectionId) {- return {- accepted: false,- operation: this.operationSnapshot(),- failedPeerIds: failedPeerIdsFrom(validation),- released,- };- }- released.push(...this.removePublicationGeneration(retirement.generation));- }- this.advanceActiveRevision(operation);- this.touchFacts();- const nextTuple = retirement.kind === "publication" && plan.tuple.kind === "sfu" &&- plan.tuple.publication === "replace"- ? { ...plan.tuple, publication: "create" as const }- : plan.tuple;- this.replanRemaining(operation, nextTuple, restoreTuple);- if (operation.cursor >= operation.candidates.length) {- const advanced = this.validateOrAdvance(nowMs);- return {- accepted: true,- operation: this.operationSnapshot(),- failedPeerIds: failedPeerIdsFrom(validation, advanced),- released: [...released, ...advanced.released],- };- }- return {- accepted: true,- operation: this.operationSnapshot(),- failedPeerIds: failedPeerIdsFrom(validation),- released,- };- }-- candidateReady(- guard: CandidateGuard,- nowMs: number,- commitReservation: (reservation: CandidateReservation<Resource>) => boolean = () => true,- proof: { relativeQualityApproved?: boolean } = {},- ): SettleResult<Resource> {- const validation = this.validateOrAdvance(nowMs);- const operation = this.operation;- const attempt = operation?.current;- if (!operation || !attempt || !this.guardMatches(guard, operation, attempt)) {- return {- accepted: false,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: validation.released,- };- }- const relativeP2pProof =- operation.reason === "quality-convergence" &&- attempt.tuple.kind === "peer" &&- proof.relativeQualityApproved === true;- if (relativeP2pProof && attempt.relativeQualityApprovedAtMs === undefined) {- attempt.relativeQualityApprovedAtMs = nowMs;- }- const relativeP2pApproved =- operation.reason === "quality-convergence" &&- attempt.tuple.kind === "peer" &&- attempt.relativeQualityApprovedAtMs !== undefined &&- nowMs <- attempt.relativeQualityApprovedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;- const relativeP2pExpired =- operation.reason === "quality-convergence" &&- attempt.tuple.kind === "peer" &&- attempt.relativeQualityApprovedAtMs !== undefined &&- !relativeP2pApproved;- const relativeP2pPending =- operation.reason === "quality-convergence" &&- attempt.tuple.kind === "peer" &&- !relativeP2pApproved;- if (- relativeP2pApproved &&- this.candidateSenderPersistentlyDegraded(attempt, nowMs)- ) {- return this.candidateFailed(guard, nowMs);- }- const nativeCandidateProof =- this.operationRequiresNativeCandidateProof(operation);- if (relativeP2pApproved || relativeP2pPending || nativeCandidateProof) {- attempt.mediaReady = true;- const currentEdge = this.upstreamByViewer.get(operation.childPeerId);- if (- (operation.reason === "quality-convergence" &&- (!currentEdge ||- this.senderQualityState(- operation.childPeerId,- currentEdge,- nowMs,- ) !== "degraded")) ||- (operation.reason === "root-convergence" &&- !this.rootConvergenceOperationStillEligible(operation))- ) {- return {- accepted: true,- committed: false,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: [- ...validation.released,- ...this.abortOperation(nowMs, "aborted"),- ],- };- }- }- if (relativeP2pExpired) {- // A one-shot client proof cannot be renewed by a late sender sample.- // Release this candidate so the existing bounded cursor can try the- // next route instead of waiting for the whole operation deadline.- return this.candidateFailed(guard, nowMs);- }- if (relativeP2pPending) {- return {- accepted: true,- committed: false,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: validation.released,- };- }- if (- relativeP2pApproved &&- (attempt.senderQualityState !== "healthy" ||- attempt.senderQualityAcceptedAtMs === undefined ||- nowMs >=- attempt.senderQualityAcceptedAtMs +- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS)- ) {- return {- accepted: true,- committed: false,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: validation.released,- };- }- if (nativeCandidateProof) {- const candidateQualityState =- attempt.tuple.kind === "sfu" && attempt.tuple.publication === "reuse"- ? this.sfuPublisherQualityState(- attempt.publicationGeneration!,- nowMs,- )- : attempt.senderQualityState ?? "unknown";- const candidateQualityReady =- candidateQualityState === "healthy" &&- (attempt.tuple.kind !== "sfu" ||- attempt.tuple.publication === "reuse" ||- (attempt.senderQualityConsecutiveHealthyWindows ?? 0) >=- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS);- if (!candidateQualityReady && candidateQualityState !== "degraded") {- return {- accepted: true,- committed: false,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: validation.released,- };- }- if (- (attempt.tuple.kind !== "sfu" ||- attempt.tuple.publication !== "reuse") &&- (attempt.senderQualityAcceptedAtMs === undefined ||- nowMs >=- attempt.senderQualityAcceptedAtMs +- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS)- ) {- return this.candidateFailed(guard, nowMs);- }- if (candidateQualityState === "degraded") {- return this.candidateFailed(guard, nowMs);- }- }- if (!commitReservation(attempt.reservation)) {- this.consumeCurrentAvailabilityOpportunity(operation);- this.debug("candidate-commit-rejected", {- child: this.debugPeer(operation.childPeerId),- candidate: this.debugTuple(attempt.tuple),- revision: attempt.revision,- });- this.promoteNextDirectWithinHeadStart(operation, nowMs);- this.noteRejection(operation.demandPeerId, "candidate-failed");- const failed = this.validateOrAdvance(nowMs, guard);- return {- accepted: false,- failedPeerIds: failedPeerIdsFrom(validation, failed),- activeRevision: this.revision,- released: [...validation.released, ...failed.released],- };- }- if (operation.reason !== "sfu-bootstrap") {- this.finishTiming(- operation.demandPeerId,- nowMs,- attempt.tuple.kind === "peer" ? "direct" : "sfu",- "none",- true,- );- }- this.debug("candidate-ready", {- child: this.debugPeer(operation.childPeerId),- candidate: this.debugTuple(attempt.tuple),- revision: attempt.revision,- });- const displacedSfuChildren =- attempt.tuple.kind === "sfu" && attempt.tuple.publication === "replace"- ? [...this.upstreamByViewer]- .filter(- ([childPeerId, edge]) =>- childPeerId !== operation.childPeerId &&- edge.kind === "sfu" &&- edge.physicalActive,- )- .map(([childPeerId]) => childPeerId)- : [];- const released = [...validation.released, ...this.commitAttempt(operation, attempt)];- for (const childPeerId of displacedSfuChildren) {- this.ensureDemand(childPeerId, nowMs, "edge-unavailable");- }- return {- accepted: true,- committed: true,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released,- };- }-- candidateTransportConnected(- guard: CandidateGuard,- nowMs: number,- ): SettleResult<Resource> {- const validation = this.validateOrAdvance(nowMs);- const operation = this.operation;- const attempt = operation?.current;- if (- !operation ||- !attempt ||- attempt.tuple.kind !== "peer" ||- !this.guardMatches(guard, operation, attempt)- ) {- return {- accepted: false,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: validation.released,- };- }- attempt.transportConnected = true;- this.debug("candidate-transport-connected", {- child: this.debugPeer(operation.childPeerId),- candidate: this.debugTuple(attempt.tuple),- revision: attempt.revision,- });- return {- accepted: true,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: validation.released,- };- }-- candidateFailed(guard: CandidateGuard, nowMs: number): SettleResult<Resource> {- const operation = this.operation;- if (- operation?.current &&- this.guardMatches(guard, operation, operation.current)- ) {- this.consumeCurrentAvailabilityOpportunity(operation);- this.debug("candidate-failed", {- child: this.debugPeer(operation.childPeerId),- candidate: this.debugTuple(operation.current.tuple),- revision: operation.current.revision,- });- this.promoteNextDirectWithinHeadStart(operation, nowMs);- this.noteRejection(operation.demandPeerId, "candidate-failed");- }- const validation = this.validateOrAdvance(nowMs, guard);- if (validation.consumedGuard) {- return {- accepted: true,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: validation.released,- };- }- return {- accepted: false,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: validation.released,- };- }-- operationExpired(nowMs: number): SettleResult<Resource> {- if (this.operation) {- const current = this.operation.current;- const noProgress =- current?.tuple.kind === "peer" &&- !current.transportConnected &&- this.peerCandidateHasSuccessor(this.operation) &&- nowMs >= current.startedAtMs + this.directHeadStartMs() &&- nowMs < this.operation.deadlineAtMs;- this.debug(noProgress ? "candidate-no-progress" : "operation-deadline", {- child: this.debugPeer(this.operation.childPeerId),- candidate: current- ? this.debugTuple(current.tuple)- : null,- cursor: this.operation.cursor,- candidateCount: this.operation.candidates.length,- });- }- const validation = this.validateOrAdvance(nowMs);- return {- accepted: validation.expired,- failedPeerIds: failedPeerIdsFrom(validation),- activeRevision: this.revision,- released: validation.released,- };- }-- dispose(): readonly Resource[] {- const resources = new Set<Resource>();- if (this.operation?.current) {- for (const resource of reservationResources(this.operation.current.reservation)) {- resources.add(resource);- }- }- for (const resource of this.committedResources()) resources.add(resource);- this.operation = undefined;- this.upstreamByViewer.clear();- this.qualityObservations.clear();- this.qualityBaselinesPending.clear();- this.senderQualityObservations.clear();- this.senderQualityBaselines.clear();- this.senderQualityRegenerationBlocks.clear();- this.sfuPublisherQualityObservation = undefined;- this.hostPublication = null;- this.participants.clear();- this.routeTimings.clear();- this.directContinuations.clear();- this.retiringPublicationGenerations.clear();- this.sfuBootstrapIntent = undefined;- this.consumedSfuBootstrapOpportunities.clear();- this.rootConvergenceRootPeerId = undefined;- this.paused = true;- return [...resources];- }-- private validateOrAdvance(nowMs: number, failedGuard?: CandidateGuard): {- released: Resource[];- exhausted?: boolean;- exhaustedChildPeerId?: string;- expired: boolean;- consumedGuard: boolean;- } {- const activeRevisionAtStart = this.revision;- const released: Resource[] = [];- const result: {- released: Resource[];- exhausted?: boolean;- exhaustedChildPeerId?: string;- expired: boolean;- consumedGuard: boolean;- } = { released, expired: false, consumedGuard: false };- let operation = this.operation;- if (!operation) return result;- if (!this.bootstrapOperationOwned(operation)) {- if (operation.current) {- released.push(...reservationResources(operation.current.reservation));- this.advanceActiveRevision(operation);- }- this.finishTiming(- operation.demandPeerId,- nowMs,- this.currentFinalRoute(operation.demandPeerId),- "stale",- );- this.operation = undefined;- return result;- }- if (- operation.reason === "quality-convergence" &&- !this.qualityOperationStillEligible(operation, nowMs)- ) {- released.push(...this.abortOperation(nowMs, "aborted"));- return result;- }- if (- operation.reason === "root-convergence" &&- !this.rootConvergenceOperationStillEligible(operation)- ) {- released.push(...this.abortOperation(nowMs, "aborted"));- return result;- }- if (nowMs >= operation.deadlineAtMs) {- const directConvergence = operation.reason === "direct-convergence";- const sfuBootstrap = operation.reason === "sfu-bootstrap";- const qualityConvergence = operation.reason === "quality-convergence";- const backgroundConvergence = this.isBackgroundConvergence(- operation.reason,- );- if (directConvergence) {- this.consumeDirectContinuationCandidate(operation);- }- if (qualityConvergence) {- this.consumeQualityOperationCandidates(operation);- }- if (operation.current) released.push(...reservationResources(operation.current.reservation));- const revisionAdvanced = Boolean(operation.current);- if (operation.current) this.advanceActiveRevision(operation);- const factsChanged = operation.builtAtFactVersion !== this.factVersion;- const failedBootstrapDemand = sfuBootstrap- ? this.completeSfuBootstrapCarrier(- operation.childPeerId,- nowMs,- factsChanged ? "stale" : "operation-deadline",- operation.candidates[- Math.min(operation.cursor, operation.candidates.length - 1)- ],- )- : undefined;- const bootstrapAvailable =- !backgroundConvergence &&- !sfuBootstrap &&- this.bootstrapCandidateAvailable(operation.demandPeerId);- if (bootstrapAvailable) {- this.consumeCurrentAvailabilityOpportunity(operation);- } else {- this.consumeAvailabilityOperation(operation);- }- const exhausted = sfuBootstrap- ? failedBootstrapDemand !== undefined- : !backgroundConvergence &&- !bootstrapAvailable &&- !this.hasRemainingNatOpportunity(operation);- if (bootstrapAvailable) this.stageSfuBootstrap(operation);- if (!sfuBootstrap) {- this.finishTiming(- operation.demandPeerId,- nowMs,- backgroundConvergence- ? this.currentFinalRoute(operation.demandPeerId)- : exhausted- ? "failed"- : "waiting",- factsChanged ? "stale" : "operation-deadline",- );- }- this.blockAndClear(- operation,- !backgroundConvergence &&- !sfuBootstrap,- released,- revisionAdvanced,- );- if (exhausted && !sfuBootstrap) {- this.rememberUnavailableSfuBootstrap(operation.demandPeerId);- }- return {- ...result,- exhausted:- backgroundConvergence ? undefined : exhausted,- exhaustedChildPeerId: failedBootstrapDemand ??- (exhausted ? operation.demandPeerId : undefined),- expired: true,- };- }- if (this.advanceExpiredDirectHeadStart(operation, nowMs, released)) {- result.expired = true;- }- if (- this.participants.get(operation.childPeerId)?.sessionId !==- operation.childSessionId ||- this.participants.get(operation.demandPeerId)?.sessionId !==- operation.demandSessionId- ) {- if (operation.current) released.push(...reservationResources(operation.current.reservation));- if (operation.current) this.advanceActiveRevision(operation);- this.finishTiming(- operation.demandPeerId,- nowMs,- this.currentFinalRoute(operation.demandPeerId),- "aborted",- );- this.operation = undefined;- return result;- }-- while ((operation = this.operation)) {- const attempt = operation.current;- if (!attempt && operation.builtAtFactVersion !== this.factVersion) {- this.replanRemaining(operation);- }- if (attempt) {- const guardFailed = failedGuard && this.guardMatches(failedGuard, operation, attempt);- const plan = operation.candidates[operation.cursor];- const peerNoProgressExpired =- attempt.tuple.kind === "peer" &&- !attempt.transportConnected &&- this.peerCandidateHasSuccessor(operation) &&- nowMs >= attempt.startedAtMs + this.directHeadStartMs();- if (- !guardFailed &&- !peerNoProgressExpired &&- plan &&- this.operationCandidateValid(operation, plan, attempt)- ) {- return result;- }- if (!guardFailed) {- this.noteRejection(- operation.demandPeerId,- peerNoProgressExpired ? "first-frame-timeout" : "stale",- );- }- if (peerNoProgressExpired) {- result.expired = true;- }- if (guardFailed || peerNoProgressExpired) {- this.consumeQualityCandidateOpportunity(operation, plan);- }- if (operation.reason === "direct-convergence") {- this.consumeDirectContinuationCandidate(operation);- }- released.push(...reservationResources(attempt.reservation));- this.advanceActiveRevision(operation);- operation.current = undefined;- operation.cursor += 1;- this.clearCandidateTiming(operation.demandPeerId);- result.consumedGuard = Boolean(guardFailed);- this.replanRemaining(operation);- }- while (operation.cursor < operation.candidates.length &&- !this.operationCandidateValid(operation, operation.candidates[operation.cursor]!)) {- this.noteRejection(operation.demandPeerId, "stale");- if (operation.reason === "direct-convergence") {- this.consumeDirectContinuationCandidate(operation);- }- operation.cursor += 1;- this.clearCandidateTiming(operation.demandPeerId);- }- if (operation.cursor < operation.candidates.length) return result;- const sfuBootstrap = operation.reason === "sfu-bootstrap";- const backgroundConvergence = this.isBackgroundConvergence(- operation.reason,- );- const factsChanged = operation.builtAtFactVersion !== this.factVersion;- const rejectionBucket = factsChanged- ? "stale"- : this.routeTimings.get(operation.demandPeerId)?.rejectionBucket ===- "none"- ? "candidate-failed"- : (this.routeTimings.get(operation.demandPeerId)?.rejectionBucket ??- "candidate-failed");- const failedBootstrapDemand = sfuBootstrap- ? this.completeSfuBootstrapCarrier(- operation.childPeerId,- nowMs,- rejectionBucket,- operation.candidates[- Math.min(operation.cursor, operation.candidates.length - 1)- ],- )- : undefined;- const bootstrapAvailable =- !backgroundConvergence &&- !sfuBootstrap &&- this.bootstrapCandidateAvailable(operation.demandPeerId);- if (!bootstrapAvailable) this.consumeAvailabilityOperation(operation);- const exhausted = sfuBootstrap- ? failedBootstrapDemand !== undefined- : !backgroundConvergence &&- !bootstrapAvailable &&- !this.hasRemainingNatOpportunity(operation);- if (bootstrapAvailable) this.stageSfuBootstrap(operation);- if (!sfuBootstrap) {- this.finishTiming(- operation.demandPeerId,- nowMs,- backgroundConvergence- ? this.currentFinalRoute(operation.demandPeerId)- : exhausted- ? "failed"- : "waiting",- rejectionBucket,- );- }- this.blockAndClear(- operation,- !backgroundConvergence &&- !sfuBootstrap,- released,- this.revision !== activeRevisionAtStart,- );- result.exhausted =- backgroundConvergence ? undefined : exhausted;- if (failedBootstrapDemand) {- result.exhaustedChildPeerId = failedBootstrapDemand;- } else if (exhausted) {- result.exhaustedChildPeerId = operation.demandPeerId;- this.rememberUnavailableSfuBootstrap(operation.demandPeerId);- }- }- return result;- }-- private commitAttempt(operation: ChildOperation<Resource>, attempt: Attempt<Resource>): Resource[] {- const beforeResources = new Set(this.committedResources());- const old = this.upstreamByViewer.get(operation.childPeerId);- const sameParentRegeneration =- operation.reason === "quality-convergence" &&- attempt.tuple.kind === "peer" &&- attempt.tuple.regenerate === true &&- old?.kind === "peer" &&- old.parentPeerId === attempt.tuple.parentPeerId;- const createsHostRoot =- attempt.tuple.kind === "peer" &&- attempt.tuple.parentPeerId === this.options.hostPeerId &&- !(old?.kind === "peer" && old.parentPeerId === this.options.hostPeerId);- this.clearQualityForParticipant(operation.childPeerId);-- if (attempt.tuple.kind === "sfu" && attempt.tuple.publication === "replace") {- this.removePublicationGeneration(this.hostPublication!.generation);- }-- if (attempt.tuple.kind === "peer") {- const parentSessionId = this.participants.get(attempt.tuple.parentPeerId)?.sessionId;- if (!parentSessionId) throw new Error("Candidate parent session is unavailable");- this.upstreamByViewer.set(operation.childPeerId, {- kind: "peer", childSessionId: operation.childSessionId,- parentPeerId: attempt.tuple.parentPeerId, parentSessionId, transport: "direct",- connectionId: attempt.connectionId, usable: true, physicalActive: true,- });- this.directContinuations.delete(operation.childPeerId);- } else {- const generation = attempt.publicationGeneration!;- if (attempt.tuple.publication !== "reuse") {- const reservation = attempt.reservation as Extract<CandidateReservation<Resource>, { kind: "sfu-create" }>;- const hostSessionId = this.participants.get(this.options.hostPeerId)?.sessionId;- if (!hostSessionId || !attempt.publicationConnectionId) {- throw new Error("SFU publication identity is unavailable");- }- if (attempt.hostSessionId !== hostSessionId) {- throw new Error("SFU publication Host session is stale");- }- this.hostPublication = {- generation,- hostSessionId,- connectionId: attempt.publicationConnectionId,- usable: true,- physicalActive: true,- resource: reservation.publication,- };- }- const edge = (attempt.reservation as Extract<CandidateReservation<Resource>, { kind: "sfu-reuse" | "sfu-create" }>).edge;- this.upstreamByViewer.set(operation.childPeerId, {- kind: "sfu", childSessionId: operation.childSessionId,- publicationGeneration: generation, transport: "sfu",- connectionId: attempt.connectionId, usable: true, physicalActive: true, resource: edge,- });- const remainingParentPeerIds =- operation.reason === "sfu-bootstrap" &&- old?.kind === "peer" &&- old.usable &&- old.physicalActive- ? [old.parentPeerId]- : operation.reason !== "direct-convergence"- ? [- ...operation.candidates- .slice(this.options.natPredictionEnabled ? 0 : operation.cursor + 1)- .filter((candidate) =>- !this.options.natPredictionEnabled ||- this.candidateOpportunityAvailable(operation.childPeerId, candidate),- )- .flatMap((candidate) =>- candidate.tuple.kind === "peer"- ? [candidate.tuple.parentPeerId]- : [],- ),- ...operation.deferredParentPeerIds,- ]- : [];- if (remainingParentPeerIds.length > 0) {- this.directContinuations.set(operation.childPeerId, {- childSessionId: operation.childSessionId,- sfuConnectionId: attempt.connectionId,- publicationGeneration: generation,- parentPeerIds: [...new Set(remainingParentPeerIds)],- });- } else {- this.directContinuations.delete(operation.childPeerId);- }- }- const producerPeerIds = new Set<string>();- if (old?.kind === "peer") {- producerPeerIds.add(old.parentPeerId);- }- producerPeerIds.add(- attempt.tuple.kind === "peer"- ? attempt.tuple.parentPeerId- : this.options.hostPeerId,- );- for (const producerPeerId of producerPeerIds) {- for (const childPeerId of this.childrenOf(producerPeerId)) {- this.senderQualityObservations.delete(childPeerId);- this.senderQualityBaselines.set(childPeerId, true);- }- }- this.requireSenderQualityBaseline(operation.childPeerId, true);- this.senderQualityBaselines.set(- operation.childPeerId,- sameParentRegeneration- ? false- : operation.reason === "quality-convergence" ||- operation.reason === "root-convergence",- );- if (- sameParentRegeneration &&- attempt.tuple.kind === "peer" &&- attempt.parentSessionId &&- attempt.senderQualityIdentity- ) {- this.senderQualityRegenerationBlocks.set(operation.childPeerId, {- childSessionId: operation.childSessionId,- parentPeerId: attempt.tuple.parentPeerId,- parentSessionId: attempt.parentSessionId,- connectionId: attempt.connectionId,- senderIdentity: attempt.senderQualityIdentity,- });- } else {- this.senderQualityRegenerationBlocks.delete(operation.childPeerId);- }- this.revision = attempt.revision;- this.operation = undefined;- this.pruneRetiringSfuAnchors();- this.touchFacts();- if (createsHostRoot) {- this.stageRootConvergence(operation.childPeerId);- }- const participant = this.participants.get(operation.childPeerId);- if (participant) {- participant.availabilityExhausted = false;- participant.bootstrapFailureReported = undefined;- }- if (old?.kind === "sfu" && !this.hasSfuSubscribers() && this.hostPublication) {- this.hostPublication = null;- }- if (- operation.reason === "sfu-bootstrap" &&- attempt.tuple.kind === "sfu"- ) {- const demand = this.participants.get(operation.demandPeerId);- if (demand?.sessionId === operation.demandSessionId) {- demand.sfuFirstAtNextRoute = true;- }- this.sfuBootstrapIntent = undefined;- } else if (this.usableRoute(operation.demandPeerId)) {- this.clearSfuBootstrapForDemand(operation.demandPeerId);- }- this.assertGraph();- this.debug("route-committed", {- child: this.debugPeer(operation.childPeerId),- route: this.debugTuple(attempt.tuple),- revision: attempt.revision,- });- const afterResources = new Set(this.committedResources());- const released = [...beforeResources].filter((resource) => !afterResources.has(resource));- if ("overlap" in attempt.reservation && attempt.reservation.overlap !== undefined) {- released.push(attempt.reservation.overlap);- }- return released;- }-- private buildCandidates(- childPeerId: string,- sfuOnly: boolean,- ): CandidatePlan[] {- return this.buildCandidatePlans(childPeerId, sfuOnly, true).filter(- (candidate) =>- this.candidateOpportunityAvailable(childPeerId, candidate),- );- }-- private buildCandidatePlans(- childPeerId: string,- sfuOnly: boolean,- preferUntried = false,- ): CandidatePlan[] {- const descendants = this.descendantsOf(childPeerId);- const parents = [...this.participants.values()]- .filter((parent) => parent.sessionId && !parent.departureConfirmed && parent.peerId !== childPeerId &&- !descendants.has(parent.peerId) && this.sourceUsable(parent.peerId) && this.targetFits(parent.peerId, childPeerId))- .sort((left, right) => (preferUntried- ? this.peerAttemptsStarted(childPeerId, left.peerId) - this.peerAttemptsStarted(childPeerId, right.peerId)- : 0) ||- this.depth(left.peerId) - this.depth(right.peerId) ||- this.remaining(right.peerId, childPeerId) - this.remaining(left.peerId, childPeerId) ||- stablePairRank(childPeerId, left.peerId) - stablePairRank(childPeerId, right.peerId) ||- compareParticipant(left, right));- const directCandidates: CandidateTuple[] = parents.map((parent) => ({- kind: "peer",- parentPeerId: parent.peerId,- transport: "direct",- }));- let sfuCandidate: Extract<CandidateTuple, { kind: "sfu" }> | undefined;- if (this.options.sfuEnabled) {- if (this.hostPublication?.usable && this.hostPublication.physicalActive) {- sfuCandidate = { kind: "sfu", publication: "reuse" };- } else if (this.hostPublication || this.publicationFits(childPeerId, false)) {- const publication = this.hostPublication ? "replace" : "create";- sfuCandidate = { kind: "sfu", publication };- }- }- const candidates: CandidateTuple[] = sfuOnly- ? sfuCandidate- ? [sfuCandidate]- : []- : sfuCandidate- ? directCandidates.length > 0- ? [directCandidates[0]!, sfuCandidate, ...directCandidates.slice(1)]- : [sfuCandidate]- : [...directCandidates, ...(sfuCandidate ? [sfuCandidate] : [])];- return candidates.filter((candidate, index, all) =>- all.findIndex((other) => tupleKey(other) === tupleKey(candidate)) === index)- .map((candidate) => this.planCandidate(childPeerId, candidate))- .filter((candidate): candidate is CandidatePlan => candidate !== null &&- this.candidateValid(childPeerId, candidate));- }-- private candidateOpportunityAvailable(- childPeerId: string,- plan: CandidatePlan,- ): boolean {- const consumed = this.participants- .get(childPeerId)- ?.consumedCandidateOpportunities.get(- this.candidateOpportunityBase(childPeerId, plan),- );- return (- consumed === undefined ||- endpointTransitionRank(plan.endpointTransition) < consumed.rank ||- (this.options.natPredictionEnabled === true &&- plan.tuple.kind === "peer" &&- !consumed.exhausted &&- consumed.startedAttempts < MAX_NAT_CONNECTION_ATTEMPTS)- );- }-- private startCandidateOpportunity(- operation: ChildOperation<Resource>,- plan: CandidatePlan,- ): ConnectionAttemptProgress | undefined {- if (- !this.options.natPredictionEnabled ||- plan.tuple.kind !== "peer" ||- (!this.isAvailabilityOperation(operation.reason) &&- operation.reason !== "direct-convergence")- ) return undefined;- const opportunities = this.participants.get(operation.childPeerId)!- .consumedCandidateOpportunities;- const key = this.candidateOpportunityBase(operation.childPeerId, plan);- const rank = endpointTransitionRank(plan.endpointTransition);- const previous = opportunities.get(key);- const startedAttempts =- (previous && previous.rank <= rank ? previous.startedAttempts : 0) + 1;- opportunities.set(key, {- rank: Math.min(previous?.rank ?? rank, rank),- startedAttempts,- });- operation.peerAttemptStarted = true;- return { current: startedAttempts, total: MAX_NAT_CONNECTION_ATTEMPTS };- }-- private peerAttemptsStarted(childPeerId: string, parentPeerId: string): number {- if (!this.options.natPredictionEnabled) return 0;- const plan = this.planCandidate(childPeerId, {- kind: "peer", parentPeerId, transport: "direct",- });- if (!plan) return 0;- const opportunity = this.participants.get(childPeerId)- ?.consumedCandidateOpportunities.get(this.candidateOpportunityBase(childPeerId, plan));- return opportunity && opportunity.rank <= endpointTransitionRank(plan.endpointTransition)- ? opportunity.startedAttempts- : 0;- }-- private viewerAttemptsStarted(peerId: string): number {- if (!this.options.natPredictionEnabled) return 0;- let started = 0;- for (const [key, opportunity] of this.participants.get(peerId)!- .consumedCandidateOpportunities) {- if (key.startsWith("peer:")) started += opportunity.startedAttempts;- }- return started;- }-- private hasRemainingNatOpportunity(operation: ChildOperation<Resource>): boolean {- return Boolean(- this.isAvailabilityOperation(operation.reason) &&- operation.peerAttemptStarted &&- this.buildCandidates(operation.childPeerId, false).some(- (plan) => plan.tuple.kind === "peer",- ),- );- }-- private candidateOpportunityBase(- childPeerId: string,- plan: CandidatePlan,- ): string {- const childSessionId =- this.participants.get(childPeerId)?.sessionId ?? "";- if (plan.tuple.kind === "peer") {- return `${tupleKey(plan.tuple)}\0${childSessionId}\0${- this.participants.get(plan.tuple.parentPeerId)?.sessionId ?? ""- }`;- }- return `${SFU_OPPORTUNITY_PREFIX}${childSessionId}\0${- this.participants.get(this.options.hostPeerId)?.sessionId ?? ""- }`;- }-- private consumeCandidateOpportunity(- childPeerId: string,- plan: CandidatePlan,- ): void {- const consumed = this.participants.get(- childPeerId,- )?.consumedCandidateOpportunities;- if (!consumed) return;- const key = this.candidateOpportunityBase(childPeerId, plan);- const rank = endpointTransitionRank(plan.endpointTransition);- const previous = consumed.get(key);- consumed.set(key, {- rank: Math.min(previous?.rank ?? rank, rank),- startedAttempts: previous?.startedAttempts ?? 0,- exhausted: true,- });- }-- private qualityCandidateOpportunityAvailable(- childPeerId: string,- plan: CandidatePlan,- ): boolean {- const consumed = this.senderQualityObservations- .get(childPeerId)- ?.consumedQualityCandidates.get(- this.candidateOpportunityBase(childPeerId, plan),- );- return (- consumed === undefined ||- endpointTransitionRank(plan.endpointTransition) < consumed- );- }-- private consumeQualityCandidateOpportunity(- operation: ChildOperation<Resource>,- plan: CandidatePlan | undefined,- ): void {- if (operation.reason !== "quality-convergence" || !plan) {- return;- }- const observation = this.currentQualityOperationObservation(operation);- if (!observation) {- return;- }- consumeOpportunity(- observation.consumedQualityCandidates,- this.candidateOpportunityBase(operation.childPeerId, plan),- endpointTransitionRank(plan.endpointTransition),- );- }-- private consumeQualityOperationCandidates(- operation: ChildOperation<Resource>,- ): void {- for (const candidate of operation.candidates) {- this.consumeQualityCandidateOpportunity(operation, candidate);- }- }-- private consumeActiveEdgeOpportunity(- child: Participant,- edge: CommittedEdge<Resource>,- ): void {- if (edge.kind === "peer") {- const key = `peer:${edge.parentPeerId}\0${child.sessionId ?? ""}\0${edge.parentSessionId}`;- child.consumedCandidateOpportunities.set(- key,- { rank: 0, startedAttempts: child.consumedCandidateOpportunities.get(key)?.startedAttempts ?? 0, exhausted: true },- );- return;- }- this.consumeCandidateOpportunity(child.peerId, {- tuple: { kind: "sfu", publication: "reuse" },- endpointTransition: { kind: "none" },- });- }-- private consumeAvailabilityOperation(- operation: ChildOperation<Resource>,- ): void {- if (!this.isAvailabilityOperation(operation.reason)) return;- for (const plan of operation.candidates) {- if (operation.peerAttemptStarted && plan.tuple.kind === "peer") continue;- this.consumeCandidateOpportunity(operation.childPeerId, plan);- }- }-- private consumeCurrentAvailabilityOpportunity(- operation: ChildOperation<Resource>,- ): void {- if (!this.isAvailabilityOperation(operation.reason)) return;- const plan = operation.candidates[operation.cursor];- if (operation.current?.connectionAttempt && plan?.tuple.kind === "peer") return;- if (plan) this.consumeCandidateOpportunity(operation.childPeerId, plan);- }-- private senderQualityState(- childPeerId: string,- edge: CommittedEdge<Resource>,- nowMs: number,- ): "unknown" | "healthy" | "degraded" {- if (edge.kind !== "peer") {- return this.sourceUsableForQuality(edge) ? "healthy" : "unknown";- }- const observation = this.senderQualityObservations.get(childPeerId);- const child = this.participants.get(childPeerId);- return observation &&- nowMs < observation.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS &&- child?.sessionId === observation.childSessionId &&- edge.childSessionId === observation.childSessionId &&- edge.parentPeerId === observation.parentPeerId &&- edge.parentSessionId === observation.parentSessionId &&- edge.connectionId === observation.connectionId &&- this.sourceUsableForQuality(edge)- ? observation.state- : "unknown";- }-- private currentQualityOperationSource(- childPeerId: string,- ): SenderQualityIdentity | undefined {- const child = this.participants.get(childPeerId);- const edge = this.upstreamByViewer.get(childPeerId);- const observation = this.senderQualityObservations.get(childPeerId);- if (- !child?.sessionId ||- edge?.kind !== "peer" ||- !observation ||- observation.childSessionId !== child.sessionId ||- observation.childSessionId !== edge.childSessionId ||- observation.parentPeerId !== edge.parentPeerId ||- observation.parentSessionId !== edge.parentSessionId ||- observation.connectionId !== edge.connectionId- ) {- return undefined;- }- return {- childSessionId: observation.childSessionId,- parentPeerId: observation.parentPeerId,- parentSessionId: observation.parentSessionId,- connectionId: observation.connectionId,- senderIdentity: observation.senderIdentity,- };- }-- private currentQualityOperationObservation(- operation: ChildOperation<Resource>,- ): SenderQualityObservation | undefined {- const source = operation.qualitySource;- const current = this.currentQualityOperationSource(operation.childPeerId);- if (- !source ||- !current ||- source.childSessionId !== current.childSessionId ||- source.parentPeerId !== current.parentPeerId ||- source.parentSessionId !== current.parentSessionId ||- source.connectionId !== current.connectionId ||- source.senderIdentity !== current.senderIdentity- ) {- return undefined;- }- return this.senderQualityObservations.get(operation.childPeerId);- }-- private senderQualityRegenerationBlocked(- childPeerId: string,- edge: Extract<CommittedEdge<Resource>, { kind: "peer" }>,- ): boolean {- const block = this.senderQualityRegenerationBlocks.get(childPeerId);- if (!block) {- return false;- }- const observation = this.senderQualityObservations.get(childPeerId);- if (observation && observation.senderIdentity !== block.senderIdentity) {- this.senderQualityRegenerationBlocks.delete(childPeerId);- return false;- }- if (- block.childSessionId !== edge.childSessionId ||- block.parentPeerId !== edge.parentPeerId ||- block.parentSessionId !== edge.parentSessionId ||- block.connectionId !== edge.connectionId- ) {- this.senderQualityRegenerationBlocks.delete(childPeerId);- return false;- }- return true;- }-- private candidateSenderPersistentlyDegraded(- attempt: Attempt<Resource>,- nowMs: number,- ): boolean {- return Boolean(- attempt.senderQualityState === "degraded" &&- attempt.senderQualityAcceptedAtMs !== undefined &&- nowMs <- attempt.senderQualityAcceptedAtMs +- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS &&- (attempt.senderQualityConsecutiveDegradedWindows ?? 0) >=- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS,- );- }-- private sfuPublisherQualityState(- publicationGeneration: string,- nowMs: number,- ): "unknown" | "healthy" | "degraded" {- const observation = this.sfuPublisherQualityObservation;- return observation &&- observation.publicationGeneration === publicationGeneration &&- observation.hostSessionId === this.hostPublication?.hostSessionId &&- nowMs < observation.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS- ? observation.state === "healthy" &&- observation.consecutiveHealthyWindows <- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS- ? "unknown"- : observation.state- : "unknown";- }-- private qualitySourcePathHealthy(peerId: string, nowMs: number): boolean {- if (peerId === this.options.hostPeerId) {- return true;- }- const seen = new Set<string>();- while (!seen.has(peerId)) {- seen.add(peerId);- const edge = this.upstreamByViewer.get(peerId);- if (!edge?.usable || !edge.physicalActive) {- return false;- }- if (edge.kind === "sfu") {- return (- this.sourceUsableForQuality(edge) &&- this.decodedProgressFresh(peerId, edge, nowMs) &&- this.sfuPublisherQualityState(- edge.publicationGeneration,- nowMs,- ) === "healthy"- );- }- if (this.senderQualityState(peerId, edge, nowMs) !== "healthy") {- return false;- }- if (edge.parentPeerId === this.options.hostPeerId) {- return true;- }- peerId = edge.parentPeerId;- }- return false;- }-- private decodedProgressFresh(- childPeerId: string,- edge: CommittedEdge<Resource>,- nowMs: number,- ): boolean {- const observation = this.qualityObservations.get(childPeerId);- const participant = this.participants.get(childPeerId);- return Boolean(- observation &&- observation.lastDecodedProgressAtMs !== null &&- nowMs <- observation.lastDecodedProgressAtMs +- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS &&- participant?.sessionId === observation.childSessionId &&- edge.childSessionId === observation.childSessionId &&- edge.connectionId === observation.connectionId &&- this.qualityObservationMatchesEdge(observation, edge) &&- this.sourceUsableForQuality(edge),- );- }-- private buildQualityCandidates(- childPeerId: string,- nowMs: number,- ): CandidatePlan[] {- const current = this.upstreamByViewer.get(childPeerId);- if (current?.kind !== "peer") {- return [];- }- const currentKey = edgeTupleKey(current);- const candidates = this.buildCandidatePlans(childPeerId, false).filter(- (candidate) =>- candidate.endpointTransition.kind !== "bounded-gap" &&- tupleKey(candidate.tuple) !== currentKey &&- (candidate.tuple.kind === "peer" ||- candidate.tuple.publication !== "reuse" ||- Boolean(- this.hostPublication &&- this.sfuPublisherQualityState(- this.hostPublication.generation,- nowMs,- ) === "healthy",- )),- );- const peers = candidates.filter(- (candidate) => candidate.tuple.kind === "peer",- );- const clearPeers = peers.filter(- (candidate) =>- candidate.tuple.kind === "peer" &&- this.qualitySourcePathHealthy(candidate.tuple.parentPeerId, nowMs),- );- const remainingPeers = peers.filter(- (candidate) => !clearPeers.includes(candidate),- );- const sfu =- current.parentPeerId === this.options.hostPeerId &&- this.hostFanoutNeedsSfuRelief(nowMs)- ? candidates.filter((candidate) => candidate.tuple.kind === "sfu")- : [];- const regenerationTuple: CandidateTuple = {- kind: "peer",- parentPeerId: current.parentPeerId,- transport: "direct",- regenerate: true,- };- const regenerationPlan =- this.senderQualityRegenerationBlocked(childPeerId, current)- ? null- : this.planCandidate(childPeerId, regenerationTuple);- const regeneration =- regenerationPlan &&- regenerationPlan.endpointTransition.kind !== "bounded-gap" &&- this.candidateValid(childPeerId, regenerationPlan)- ? [regenerationPlan]- : [];- return [...clearPeers, ...remainingPeers, ...sfu, ...regeneration].filter(- (candidate) =>- this.qualityCandidateOpportunityAvailable(childPeerId, candidate),- );- }-- private selectQualityChild(nowMs: number): string | undefined {- if (this.options.qualityConvergenceEnabled !== true) {- return undefined;- }- return this.availableViewers()- .filter(({ peerId }) => {- const edge = this.upstreamByViewer.get(peerId);- return Boolean(- edge?.kind === "peer" &&- this.senderQualityBaselines.get(peerId) !== true &&- this.senderQualityPersistentlyDegraded(peerId, edge, nowMs) &&- this.buildQualityCandidates(peerId, nowMs).length > 0,- );- })- .sort(- (left, right) =>- this.depth(left.peerId) - this.depth(right.peerId) ||- compareParticipant(left, right),- )[0]?.peerId;- }-- private stageRootConvergence(rootPeerId: string): void {- if (this.options.qualityConvergenceEnabled !== true) return;- const convergence = this.rootConvergencePlan(rootPeerId);- if (!convergence) return;- this.rootConvergenceRootPeerId = rootPeerId;- this.debug("root-convergence-staged", {- root: this.debugPeer(rootPeerId),- donor: this.debugPeer(convergence.donorPeerId),- child: this.debugPeer(convergence.childPeerId),- });- }-- private takeRootConvergenceIntent(): {- childPeerId: string;- plan: CandidatePlan;- } | undefined {- const rootPeerId = this.rootConvergenceRootPeerId;- this.rootConvergenceRootPeerId = undefined;- if (!rootPeerId || this.options.qualityConvergenceEnabled !== true) {- return undefined;- }- const convergence = this.rootConvergencePlan(rootPeerId);- return convergence- ? { childPeerId: convergence.childPeerId, plan: convergence.plan }- : undefined;- }-- private rootConvergencePlan(rootPeerId: string): {- donorPeerId: string;- childPeerId: string;- plan: CandidatePlan;- } | undefined {- const root = this.participants.get(rootPeerId);- if (- !root?.sessionId ||- root.departureConfirmed ||- !this.isActiveHostRoot(rootPeerId) ||- this.activeDirectChildren(rootPeerId).length !== 0- ) {- return undefined;- }- const donorPeerId = this.childrenOf(this.options.hostPeerId)- .filter(- (peerId) =>- peerId !== rootPeerId &&- this.isActiveHostRoot(peerId) &&- this.activeDirectChildren(peerId).length >= 2,- )- .sort(- (left, right) =>- this.activeDirectChildren(right).length -- this.activeDirectChildren(left).length ||- compareParticipant(- this.participants.get(left)!,- this.participants.get(right)!,- ),- )[0];- if (!donorPeerId) return undefined;- const childPeerId = this.activeDirectChildren(donorPeerId).sort(- (left, right) =>- compareParticipant(- this.participants.get(right)!,- this.participants.get(left)!,- ),- )[0];- if (!childPeerId) return undefined;- const plan = this.planCandidate(childPeerId, {- kind: "peer",- parentPeerId: rootPeerId,- transport: "direct",- });- return plan &&- plan.endpointTransition.kind !== "bounded-gap" &&- this.candidateValid(childPeerId, plan)- ? { donorPeerId, childPeerId, plan }- : undefined;- }-- private rootConvergenceOperationStillEligible(- operation: ChildOperation<Resource>,- ): boolean {- if (operation.reason !== "root-convergence") return true;- const tuple =- operation.current?.tuple ?? operation.candidates[operation.cursor]?.tuple;- const current = this.upstreamByViewer.get(operation.childPeerId);- return Boolean(- tuple?.kind === "peer" &&- current?.kind === "peer" &&- current.usable &&- current.physicalActive &&- current.parentPeerId !== tuple.parentPeerId &&- this.isActiveHostRoot(tuple.parentPeerId) &&- this.isActiveHostRoot(current.parentPeerId) &&- this.activeDirectChildren(tuple.parentPeerId).length === 0 &&- this.activeDirectChildren(current.parentPeerId).length >= 2,- );- }-- private isActiveHostRoot(peerId: string): boolean {- const edge = this.upstreamByViewer.get(peerId);- return Boolean(- edge?.kind === "peer" &&- edge.parentPeerId === this.options.hostPeerId &&- edge.usable &&- edge.physicalActive,- );- }-- private activeDirectChildren(parentPeerId: string): string[] {- return this.childrenOf(parentPeerId).filter((childPeerId) => {- const edge = this.upstreamByViewer.get(childPeerId);- return edge?.kind === "peer" && edge.usable && edge.physicalActive;- });- }-- private senderQualityPersistentlyDegraded(- childPeerId: string,- edge: CommittedEdge<Resource>,- nowMs: number,- ): boolean {- const observation = this.senderQualityObservations.get(childPeerId);- return (- this.senderQualityState(childPeerId, edge, nowMs) === "degraded" &&- observation !== undefined &&- observation.consecutiveDegradedWindows >=- PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS- );- }-- private qualityOperationStillEligible(- operation: ChildOperation<Resource>,- nowMs: number,- ): boolean {- const currentEdge = this.upstreamByViewer.get(operation.childPeerId);- const observation = this.currentQualityOperationObservation(operation);- const tuple =- operation.current?.tuple ??- operation.candidates[operation.cursor]?.tuple;- if (- currentEdge?.kind !== "peer" ||- !tuple ||- !observation- ) {- return false;- }- const state = this.senderQualityState(- operation.childPeerId,- currentEdge,- nowMs,- );- if (state === "healthy") {- return false;- }- return (- tuple.kind === "peer" ||- (state === "degraded" && this.hostFanoutNeedsSfuRelief(nowMs))- );- }-- private hostFanoutNeedsSfuRelief(nowMs: number): boolean {- const hostPeerEdges = [...this.upstreamByViewer].filter(- (entry): entry is [string, Extract<CommittedEdge<Resource>, { kind: "peer" }>] => {- const edge = entry[1];- return (- edge.kind === "peer" &&- edge.parentPeerId === this.options.hostPeerId &&- edge.usable &&- edge.physicalActive- );- },- );- return (- hostPeerEdges.length >= 2 &&- hostPeerEdges.every(([childPeerId, edge]) =>- this.senderQualityPersistentlyDegraded(childPeerId, edge, nowMs),- )- );- }-- private selectNextChild(): string | undefined {- const viewers = this.availableViewers();- const departedParents = viewers.filter(({ peerId }) => {- const edge = this.upstreamByViewer.get(peerId);- return edge?.kind === "peer" && this.participants.get(edge.parentPeerId)?.departureConfirmed;- });- const overflow = this.overflowChildren();- const unusable = viewers.filter(({ peerId }) => this.upstreamByViewer.get(peerId)?.usable === false);- const staleSfu = viewers.filter(({ peerId }) => {- const edge = this.upstreamByViewer.get(peerId);- return edge?.kind === "sfu" && (!this.hostPublication?.usable ||- this.hostPublication.generation !== edge.publicationGeneration);- });- const candidates = [...new Set([- ...departedParents.map(({ peerId }) => peerId),- ...overflow,- ...unusable.map(({ peerId }) => peerId),- ...staleSfu.map(({ peerId }) => peerId),- ...viewers.filter(({ peerId }) => !this.upstreamByViewer.has(peerId))- .map(({ peerId }) => peerId),- ])];- return candidates.sort((left, right) =>- this.viewerAttemptsStarted(left) - this.viewerAttemptsStarted(right),- )[0];- }-- private selectDirectContinuation(): {- childPeerId: string;- plan: CandidatePlan;- } | undefined {- for (const [childPeerId, continuation] of [- ...this.directContinuations,- ].sort(([left], [right]) =>- this.viewerAttemptsStarted(left) - this.viewerAttemptsStarted(right),- )) {- const child = this.participants.get(childPeerId);- const edge = this.upstreamByViewer.get(childPeerId);- if (- !child?.sessionId ||- child.departureConfirmed ||- child.sessionId !== continuation.childSessionId ||- edge?.kind !== "sfu" ||- !edge.usable ||- !edge.physicalActive ||- edge.connectionId !== continuation.sfuConnectionId ||- edge.publicationGeneration !== continuation.publicationGeneration ||- !this.hostPublication?.usable ||- !this.hostPublication.physicalActive ||- this.hostPublication.generation !== continuation.publicationGeneration- ) {- this.directContinuations.delete(childPeerId);- continue;- }- for (const parentPeerId of [...continuation.parentPeerIds].sort(- (left, right) => this.peerAttemptsStarted(childPeerId, left) -- this.peerAttemptsStarted(childPeerId, right),- )) {- const tuple: CandidateTuple = {- kind: "peer",- parentPeerId,- transport: "direct",- };- const plan = this.planCandidate(childPeerId, tuple);- if (- plan &&- plan.endpointTransition.kind !== "bounded-gap" &&- this.candidateValid(childPeerId, plan) &&- (!this.options.natPredictionEnabled ||- this.candidateOpportunityAvailable(childPeerId, plan))- ) {- return { childPeerId, plan };- }- }- if (continuation.parentPeerIds.length === 0) {- this.directContinuations.delete(childPeerId);- this.debug("direct-convergence-complete", {- child: this.debugPeer(childPeerId),- route: "sfu",- });- }- }- return undefined;- }-- private directHeadStartMs(): number {- return Math.min(- MAX_DIRECT_HEAD_START_MS,- Math.max(1, Math.floor(this.options.operationTimeoutMs / 2)),- );- }-- private isBackgroundConvergence(reason: RouteDemandReason): boolean {- return (- reason === "direct-convergence" ||- reason === "quality-convergence" ||- reason === "root-convergence"- );- }-- private isAvailabilityOperation(reason: RouteDemandReason): boolean {- return reason !== "sfu-bootstrap" && !this.isBackgroundConvergence(reason);- }-- private operationRequiresNativeCandidateProof(- operation: ChildOperation<Resource> | undefined,- ): operation is ChildOperation<Resource> {- return (- operation?.reason === "root-convergence" ||- (operation?.reason === "quality-convergence" &&- operation.current?.tuple.kind === "sfu")- );- }-- private consumeDirectContinuationCandidate(- operation: ChildOperation<Resource>,- ): void {- const tuple = operation.current?.tuple ?? operation.candidates[operation.cursor]?.tuple;- if (operation.reason !== "direct-convergence" || tuple?.kind !== "peer") {- return;- }- const continuation = this.directContinuations.get(operation.childPeerId);- if (!continuation) return;- const index = continuation.parentPeerIds.indexOf(tuple.parentPeerId);- if (index < 0) return;- continuation.parentPeerIds.splice(index, 1);- const plan = operation.candidates[operation.cursor];- if (- operation.current?.connectionAttempt &&- plan &&- this.candidateOpportunityAvailable(operation.childPeerId, plan)- ) {- continuation.parentPeerIds.push(tuple.parentPeerId);- }- this.debug("direct-convergence-advanced", {- child: this.debugPeer(operation.childPeerId),- parent: this.debugPeer(tuple.parentPeerId),- remaining: continuation.parentPeerIds.length,- });- if (continuation.parentPeerIds.length === 0) {- this.directContinuations.delete(operation.childPeerId);- } else {- this.directContinuations.delete(operation.childPeerId);- this.directContinuations.set(operation.childPeerId, continuation);- }- }-- private peekSfuBootstrapCarrier(): SfuBootstrapCarrier | undefined {- const intent = this.currentSfuBootstrapIntent();- if (!intent) return undefined;- const carrierPeerId = this.safeSfuBootstrapCarriers(- intent.demandPeerId,- )[0];- return carrierPeerId- ? {- demandPeerId: intent.demandPeerId,- demandSessionId: intent.demandSessionId,- carrierPeerId,- }- : undefined;- }-- private hasSfuBootstrapWork(): boolean {- if (this.currentSfuBootstrapIntent()) return true;- return this.availableViewers(true).some(- (viewer) =>- viewer.availabilityExhausted &&- this.sfuBootstrapNeeded(viewer.peerId) &&- (this.safeSfuBootstrapCarriers(viewer.peerId).length > 0 ||- viewer.bootstrapFailureReported !== true),- );- }-- private takeSfuBootstrapCarrier(- nowMs: number,- failedPeerIds: string[],- ): SfuBootstrapCarrier | undefined {- if (!this.sfuBootstrapGloballyNeeded()) return undefined;- const carrier = this.peekSfuBootstrapCarrier();- if (carrier) return carrier;- this.sfuBootstrapIntent = undefined;- this.reportSfuBootstrapFailures(nowMs, failedPeerIds);- return undefined;- }-- private currentSfuBootstrapIntent(): SfuBootstrapIntent | undefined {- const current = this.sfuBootstrapIntent;- if (current) {- const demand = this.participants.get(current.demandPeerId);- if (- this.sfuBootstrapNeeded(current.demandPeerId) &&- demand?.sessionId === current.demandSessionId &&- this.safeSfuBootstrapCarriers(current.demandPeerId).length > 0- ) {- return current;- }- this.sfuBootstrapIntent = undefined;- }- const demand = this.availableViewers(true).find(- (viewer) =>- viewer.availabilityExhausted &&- this.sfuBootstrapNeeded(viewer.peerId) &&- this.safeSfuBootstrapCarriers(viewer.peerId).length > 0,- );- if (!demand?.sessionId) return undefined;- const created: SfuBootstrapIntent = {- demandPeerId: demand.peerId,- demandSessionId: demand.sessionId,- };- this.sfuBootstrapIntent = created;- return created;- }-- private bootstrapOperationOwned(- operation: ChildOperation<Resource>,- ): boolean {- if (operation.reason !== "sfu-bootstrap") return true;- const intent = this.sfuBootstrapIntent;- if (- !intent ||- intent.demandPeerId !== operation.demandPeerId ||- intent.demandSessionId !== operation.demandSessionId ||- !this.sfuBootstrapNeeded(operation.demandPeerId)- ) {- return false;- }- return this.safeSfuBootstrapCarriers(operation.demandPeerId).includes(- operation.childPeerId,- );- }-- private sfuBootstrapNeeded(demandPeerId: string): boolean {- return Boolean(- this.sfuBootstrapGloballyNeeded() &&- this.participants.get(demandPeerId)?.sessionId &&- !this.usableRoute(demandPeerId) &&- this.sfuOpportunityAvailable(demandPeerId),- );- }-- private sfuOpportunityAvailable(demandPeerId: string): boolean {- return this.candidateOpportunityAvailable(demandPeerId, {- tuple: { kind: "sfu", publication: "reuse" },- endpointTransition: { kind: "none" },- });- }-- private sfuBootstrapGloballyNeeded(): boolean {- return Boolean(- this.options.sfuEnabled &&- !this.hostPublication &&- !this.hostHasPublicationSlot(),- );- }-- private safeSfuBootstrapCarriers(- demandPeerId: string,- ): string[] {- if (!this.sfuBootstrapNeeded(demandPeerId)) return [];- return this.sfuBootstrapCarriers();- }-- private sfuBootstrapCarriers(): string[] {- const tuple: Extract<CandidateTuple, { kind: "sfu" }> = {- kind: "sfu",- publication: "create",- };- return this.childrenOf(this.options.hostPeerId)- .filter((peerId) => {- const participant = this.participants.get(peerId);- const edge = this.upstreamByViewer.get(peerId);- const plan = this.planCandidate(peerId, tuple);- return Boolean(- participant?.sessionId &&- edge?.kind === "peer" &&- edge.transport === "direct" &&- edge.usable &&- edge.physicalActive &&- plan &&- plan.endpointTransition.kind !== "bounded-gap" &&- this.sfuBootstrapOpportunityAvailable(- peerId,- plan,- ),- );- })- .sort((left, right) =>- compareParticipant(- this.participants.get(right)!,- this.participants.get(left)!,- ),- );- }-- private sfuBootstrapOpportunityAvailable(- carrierPeerId: string,- plan: CandidatePlan,- ): boolean {- const consumed = this.consumedSfuBootstrapOpportunities.get(- this.sfuBootstrapOpportunityBase(carrierPeerId, plan),- );- return (- consumed === undefined ||- endpointTransitionRank(plan.endpointTransition) < consumed- );- }-- private sfuBootstrapOpportunityBase(- carrierPeerId: string,- plan: CandidatePlan,- ): string {- return `${carrierPeerId}\0${this.candidateOpportunityBase(- carrierPeerId,- plan,- )}`;- }-- private consumeSfuBootstrapOpportunity(- carrierPeerId: string,- plan: CandidatePlan,- ): void {- consumeOpportunity(- this.consumedSfuBootstrapOpportunities,- this.sfuBootstrapOpportunityBase(carrierPeerId, plan),- endpointTransitionRank(plan.endpointTransition),- );- }-- private completeSfuBootstrapCarrier(- carrierPeerId: string,- nowMs: number,- bucket: RouteDiagnosticRejectionBucket,- attemptedPlan?: CandidatePlan,- ): string | undefined {- const intent = this.sfuBootstrapIntent;- if (!intent) return undefined;- const plan = attemptedPlan ?? this.planCandidate(carrierPeerId, {- kind: "sfu",- publication: "create",- });- if (plan) {- this.consumeSfuBootstrapOpportunity(- carrierPeerId,- plan,- );- this.consumeCandidateOpportunity(carrierPeerId, plan);- }- if (this.safeSfuBootstrapCarriers(intent.demandPeerId).length > 0) {- return undefined;- }- const demand = this.participants.get(intent.demandPeerId);- if (demand) demand.availabilityExhausted = true;- this.finishTiming(intent.demandPeerId, nowMs, "failed", bucket);- if (demand) demand.bootstrapFailureReported = true;- this.sfuBootstrapIntent = undefined;- return intent.demandPeerId;- }-- private reportSfuBootstrapFailures(- nowMs: number,- failedPeerIds: string[],- ): void {- for (const demand of this.availableViewers(true)) {- if (- !demand.availabilityExhausted ||- !this.sfuBootstrapNeeded(demand.peerId) ||- this.usableRoute(demand.peerId) ||- demand.bootstrapFailureReported === true- ) {- continue;- }- demand.bootstrapFailureReported = true;- this.finishTiming(demand.peerId, nowMs, "failed", "candidate-failed");- failedPeerIds.push(demand.peerId);- }- }-- private rememberUnavailableSfuBootstrap(demandPeerId: string): void {- if (!this.sfuBootstrapNeeded(demandPeerId)) return;- const demand = this.participants.get(demandPeerId);- if (!demand?.sessionId) return;- demand.bootstrapFailureReported = true;- this.sfuBootstrapIntent = undefined;- }-- private stageSfuBootstrap(- operation: ChildOperation<Resource>,- ): void {- const demand = this.participants.get(operation.demandPeerId);- if (!demand?.sessionId || !this.sfuBootstrapNeeded(demand.peerId)) return;- if (this.safeSfuBootstrapCarriers(demand.peerId).length === 0) return;- const current = this.sfuBootstrapIntent;- if (- current?.demandPeerId === demand.peerId &&- current.demandSessionId === demand.sessionId- ) {- return;- }- this.sfuBootstrapIntent = {- demandPeerId: demand.peerId,- demandSessionId: demand.sessionId,- };- }-- private clearSfuBootstrapForDemand(demandPeerId: string): void {- const demand = this.participants.get(demandPeerId);- if (demand) demand.sfuFirstAtNextRoute = undefined;- if (this.sfuBootstrapIntent?.demandPeerId === demandPeerId) {- this.sfuBootstrapIntent = undefined;- }- }-- private participantBlocked(participant: Participant): boolean {- return Boolean(- participant.availabilityExhausted &&- this.buildCandidates(participant.peerId, false).length === 0,- );- }-- private availableViewers(includeBlocked = false): Participant[] {- return [...this.participants.values()].filter((participant) => participant.role === "viewer" &&- participant.sessionId && !participant.departureConfirmed &&- (includeBlocked || !this.participantBlocked(participant)))- .sort(compareParticipant);- }-- private overflowChildren(): string[] {- const result: string[] = [];- for (const parent of this.participants.values()) {- const overflow = this.overflowPeerChildren(parent.peerId).filter((id) => {- const child = this.participants.get(id);- return child?.sessionId && !child.departureConfirmed &&- !this.participantBlocked(child);- });- result.push(...overflow.reverse());- }- return result;- }-- private overflowPeerChildren(parentPeerId: string): string[] {- const parent = this.participants.get(parentPeerId);- if (!parent) return [];- const publicationCopies = parent.role === "host" && this.hostPublication?.physicalActive ? 1 : 0;- const capacity = Math.max(0, parent.effectiveDownstreamCapacity - publicationCopies);- return this.childrenOf(parentPeerId)- .filter((id) => {- const edge = this.upstreamByViewer.get(id);- return edge?.kind === "peer" && edge.physicalActive;- })- .sort((left, right) => compareParticipant(this.participants.get(left)!, this.participants.get(right)!))- .slice(capacity);- }-- private candidateValid(childPeerId: string, plan: CandidatePlan, attempt?: Attempt<Resource>): boolean {- const tuple = plan.tuple;- const child = this.participants.get(childPeerId);- if (!child?.sessionId || child.departureConfirmed || (attempt && attempt.childSessionId !== child.sessionId)) return false;- if (tuple.kind === "peer") {- const parent = this.participants.get(tuple.parentPeerId);- if (!parent?.sessionId || parent.departureConfirmed || (attempt && parent.sessionId !== attempt.parentSessionId) ||- this.descendantsOf(childPeerId).has(parent.peerId) || !this.sourceUsable(parent.peerId) ||- !this.targetFits(parent.peerId, childPeerId)) return false;- } else {- if (!this.options.sfuEnabled) return false;- if (- attempt?.hostSessionId &&- attempt.hostSessionId !==- this.participants.get(this.options.hostPeerId)?.sessionId- ) {- return false;- }- if (tuple.publication === "reuse") {- if (!this.hostPublication?.usable || !this.hostPublication.physicalActive ||- (attempt && attempt.publicationGeneration !== this.hostPublication.generation)) return false;- } else if (tuple.publication === "replace") {- if (!this.hostPublication || this.hostPublication.usable || !this.publicationFits(childPeerId, true)) return false;- } else if (this.hostPublication || !this.publicationFits(childPeerId, false)) {- return false;- }- }- const currentPlan = this.planCandidate(childPeerId, tuple);- return Boolean(currentPlan && endpointTransitionEquals(currentPlan.endpointTransition, plan.endpointTransition));- }-- private operationCandidateValid(- operation: ChildOperation<Resource>,- plan: CandidatePlan,- attempt?: Attempt<Resource>,- ): boolean {- return (- this.candidateValid(operation.childPeerId, plan, attempt) &&- (attempt?.connectionAttempt !== undefined ||- !this.isAvailabilityOperation(operation.reason) ||- this.candidateOpportunityAvailable(operation.childPeerId, plan))- );- }-- private planCandidate(childPeerId: string, tuple: CandidateTuple): CandidatePlan | null {- if (tuple.kind === "sfu" && tuple.publication === "reuse") {- return { tuple, endpointTransition: { kind: "none" } };- }- const producerPeerId = tuple.kind === "peer" ? tuple.parentPeerId : this.options.hostPeerId;- const producer = this.participants.get(producerPeerId);- if (!producer?.sessionId || producer.departureConfirmed) return null;- const copies = this.physicalCopies(producerPeerId);- if (copies + 1 <= producer.effectiveDownstreamCapacity) {- return { tuple, endpointTransition: { kind: "none", producerPeerId } };- }- if (copies + 1 <= Math.min(this.options.endpointMediaCopyCapacity + 1, 3)) {- return { tuple, endpointTransition: { kind: "overlap", producerPeerId } };- }- const retire = this.retirementFor(childPeerId, producerPeerId, tuple);- if (!retire || copies > producer.effectiveDownstreamCapacity) return null;- return { tuple, endpointTransition: { kind: "bounded-gap", producerPeerId, retire } };- }-- private retirementFor(- childPeerId: string,- producerPeerId: string,- tuple: CandidateTuple,- ): EndpointRetirement | null {- const old = this.upstreamByViewer.get(childPeerId);- if (old?.kind === "peer" && old.parentPeerId === producerPeerId && old.physicalActive) {- return {- kind: "edge",- childPeerId,- childSessionId: old.childSessionId,- parentPeerId: old.parentPeerId,- parentSessionId: old.parentSessionId,- transport: old.transport,- connectionId: old.connectionId,- };- }- if (producerPeerId !== this.options.hostPeerId || !this.hostPublication?.physicalActive) return null;- const replacesPublication = tuple.kind === "sfu" && tuple.publication === "replace";- const releasesLastPublication = tuple.kind === "peer" && old?.kind === "sfu" && old.physicalActive &&- this.sfuSubscriberCount() === 1;- if (!replacesPublication && !releasesLastPublication) return null;- return {- kind: "publication",- hostSessionId: this.hostPublication.hostSessionId,- generation: this.hostPublication.generation,- connectionId: this.hostPublication.connectionId,- };- }-- private physicalCopies(peerId: string): number {- let copies = [...this.upstreamByViewer.values()].filter((edge) =>- edge.kind === "peer" && edge.parentPeerId === peerId && edge.physicalActive).length;- if (peerId === this.options.hostPeerId && this.hostPublication?.physicalActive) copies += 1;- return copies;- }-- private assertReservation(tuple: CandidateTuple, reservation: CandidateReservation<Resource>, overlap: boolean): void {- const expected = tuple.kind === "peer" ? "direct" :- tuple.publication === "reuse" ? "sfu-reuse" : "sfu-create";- if (reservation.kind !== expected) throw new Error("Candidate reservation kind does not match tuple");- if (overlap && !("overlap" in reservation && reservation.overlap !== undefined)) {- throw new Error("Candidate requires an endpoint overlap reservation");- }- }-- private pruneDepartedLeaves(released: Resource[]): string[] {- const removed: string[] = [];- let changed = true;- while (changed) {- changed = false;- for (const participant of this.participants.values()) {- if (participant.role !== "viewer" || !participant.departureConfirmed || this.childrenOf(participant.peerId).length > 0) continue;- const edge = this.upstreamByViewer.get(participant.peerId);- if (edge?.kind === "sfu") {- this.retireSfuEdge(participant.peerId, edge, released, false);- } else {- this.upstreamByViewer.delete(participant.peerId);- }- this.clearQualityForParticipant(participant.peerId);- this.participants.delete(participant.peerId);- this.routeTimings.delete(participant.peerId);- this.directContinuations.delete(participant.peerId);- this.clearSfuBootstrapForDemand(participant.peerId);- removed.push(participant.peerId);- changed = true;- }- }- if (removed.length > 0) {- if (!this.hasSfuSubscribers() && this.hostPublication) {- this.clearSfuQuality();- if (this.hostPublication.physicalActive) released.push(this.hostPublication.resource);- this.hostPublication = null;- }- this.revision = this.allocateRevision();- this.touchFacts();- this.pruneRetiringSfuAnchors();- }- return removed;- }-- private abortOperation(- nowMs?: number,- bucket: RouteDiagnosticRejectionBucket = "aborted",- ): Resource[] {- if (!this.operation) return [];- if (nowMs !== undefined) {- this.finishTiming(- this.operation.demandPeerId,- nowMs,- this.currentFinalRoute(this.operation.demandPeerId),- bucket,- );- }- const operation = this.operation;- const released = operation.current- ? [...reservationResources(operation.current.reservation)]- : [];- if (operation.current) this.advanceActiveRevision(operation);- this.operation = undefined;- return released;- }-- private operationUsesParticipantSession(peerId: string): boolean {- const operation = this.operation;- if (!operation) return false;- if (- operation.childPeerId === peerId ||- operation.demandPeerId === peerId- ) {- return true;- }- const tuple =- operation.current?.tuple ?? operation.candidates[operation.cursor]?.tuple;- return tuple?.kind === "peer"- ? tuple.parentPeerId === peerId- : peerId === this.options.hostPeerId;- }-- private advanceActiveRevision(operation: ChildOperation<Resource>): void {- if (operation.reason === "quality-convergence" && operation.current) {- const producerPeerId =- operation.current.tuple.kind === "peer"- ? operation.current.tuple.parentPeerId- : this.options.hostPeerId;- const regeneratingChild =- operation.current.tuple.kind === "peer" &&- operation.current.tuple.regenerate === true;- for (const childPeerId of this.childrenOf(producerPeerId)) {- if (regeneratingChild && childPeerId === operation.childPeerId) {- // A failed same-edge trial must not turn the retained sender into a- // global baseline block. Its exact candidate opportunity owns retry- // damping while the retained sender identity remains current.- continue;- }- this.senderQualityObservations.delete(childPeerId);- this.senderQualityBaselines.set(childPeerId, true);- }- }- this.revision = this.allocateRevision();- operation.baseRevision = this.revision;- }-- private blockAndClear(- operation: ChildOperation<Resource>,- block = true,- released: Resource[] = [],- revisionAdvanced = false,- ): void {- const child = this.participants.get(operation.childPeerId);- this.operation = undefined;- const retiredInvalid = block && child- ? this.retireInvalidOperationEdge(operation.childPeerId, released)- : false;- if (retiredInvalid && !revisionAdvanced) {- this.revision = this.allocateRevision();- }- if (retiredInvalid) {- this.touchFacts();- }- if (!block || !child) return;- child.availabilityExhausted = true;- }-- private retireInvalidOperationEdge(childPeerId: string, released: Resource[]): boolean {- const edge = this.upstreamByViewer.get(childPeerId);- if (!edge || !this.edgeRequiresMove(childPeerId, edge)) return false;- if (edge.kind === "sfu") {- this.retireSfuEdge(childPeerId, edge, released);- this.pruneRetiringSfuAnchors();- } else {- edge.physicalActive = false;- edge.usable = false;- }- if (edge.kind === "sfu" && !this.hasSfuSubscribers() && this.hostPublication) {- const publication = this.hostPublication;- if (publication.physicalActive) released.push(publication.resource);- publication.physicalActive = false;- publication.usable = false;- this.hostPublication = null;- }- return true;- }-- private edgeRequiresMove(childPeerId: string, edge: CommittedEdge<Resource>): boolean {- if (!edge.usable || !edge.physicalActive) return true;- if (edge.kind === "sfu") {- return !this.hostPublication?.usable ||- !this.hostPublication.physicalActive ||- this.hostPublication.generation !== edge.publicationGeneration;- }- if (this.participants.get(edge.parentPeerId)?.departureConfirmed) return true;- return this.overflowPeerChildren(edge.parentPeerId).includes(childPeerId);- }-- private replanRemaining(- operation: ChildOperation<Resource>,- firstTuple?: CandidateTuple,- restoreTuple?: CandidateTuple,- ): void {- const prefix = operation.candidates.slice(0, operation.cursor);- const tuples = operation.candidates- .slice(operation.cursor)- .map((candidate) => candidate.tuple);- if (firstTuple) {- if (tuples.length === 0) tuples.push(firstTuple);- else tuples[0] = firstTuple;- }- if (restoreTuple && !tuples.some((tuple) => tupleKey(tuple) === tupleKey(restoreTuple))) {- tuples.push(restoreTuple);- }- const replanned = tuples- .map((tuple) => this.planCandidate(operation.childPeerId, tuple))- .filter(- (plan): plan is CandidatePlan =>- plan !== null && this.operationCandidateValid(operation, plan),- );- operation.candidates = [...prefix, ...replanned];- operation.builtAtFactVersion = this.factVersion;- }-- private operationSnapshot(): OperationSnapshot | undefined {- const operation = this.operation;- if (!operation) return undefined;- return { childPeerId: operation.childPeerId, childSessionId: operation.childSessionId,- demandPeerId: operation.demandPeerId,- reason: operation.reason,- baseRevision: operation.baseRevision, factVersion: operation.builtAtFactVersion,- candidates: operation.candidates.map(cloneCandidatePlan),- cursor: operation.cursor, deadlineAtMs: operation.deadlineAtMs,- wakeAtMs: this.operationWakeAt(operation),- current: operation.current ? { tuple: { ...operation.current.tuple }, revision: operation.current.revision,- connectionId: operation.current.connectionId,- ...(operation.current.connectionAttempt- ? { connectionAttempt: { ...operation.current.connectionAttempt } }- : {}),- } : undefined };- }-- private advanceExpiredDirectHeadStart(- operation: ChildOperation<Resource>,- nowMs: number,- released: Resource[],- ): boolean {- const currentTuple =- operation.current?.tuple ?? operation.candidates[operation.cursor]?.tuple;- const sfuIndex = this.foregroundSfuIndex(operation);- if (- currentTuple?.kind !== "peer" ||- operation.current?.transportConnected ||- sfuIndex <= operation.cursor- ) {- return false;- }- const headStartDeadlineAtMs = this.directHeadStartDeadlineAt(operation);- if (nowMs < headStartDeadlineAtMs) {- return false;- }- const activeCandidate = operation.current- ? this.debugTuple(operation.current.tuple)- : null;- if (operation.current) {- this.noteRejection(operation.demandPeerId, "first-frame-timeout");- this.consumeCurrentAvailabilityOpportunity(operation);- released.push(...reservationResources(operation.current.reservation));- this.advanceActiveRevision(operation);- operation.current = undefined;- this.clearCandidateTiming(operation.demandPeerId);- }- operation.deferredParentPeerIds.push(- ...operation.candidates- .slice(operation.cursor, sfuIndex)- .flatMap((candidate) =>- candidate.tuple.kind === "peer"- ? [candidate.tuple.parentPeerId]- : [],- ),- );- operation.cursor = sfuIndex;- this.debug("direct-head-start-expired", {- child: this.debugPeer(operation.childPeerId),- activeCandidate,- cursor: operation.cursor,- deadlineAtMs: headStartDeadlineAtMs,- observedAtMs: nowMs,- });- return true;- }-- private operationWakeAt(operation: ChildOperation<Resource>): number {- const currentTuple =- operation.current?.tuple ?? operation.candidates[operation.cursor]?.tuple;- if (- currentTuple?.kind === "peer" &&- !operation.current?.transportConnected &&- this.foregroundSfuIndex(operation) > operation.cursor- ) {- return this.directHeadStartDeadlineAt(operation);- }- if (- operation.current?.tuple.kind === "peer" &&- !operation.current.transportConnected &&- this.peerCandidateHasSuccessor(operation)- ) {- return Math.min(- operation.deadlineAtMs,- operation.current.startedAtMs + this.directHeadStartMs(),- );- }- return operation.deadlineAtMs;- }-- private peerCandidateHasSuccessor(- operation: ChildOperation<Resource>,- ): boolean {- return (- operation.cursor + 1 < operation.candidates.length ||- this.foregroundSfuIndex(operation) > operation.cursor- );- }-- private directHeadStartDeadlineAt(- operation: ChildOperation<Resource>,- ): number {- return (- operation.deadlineAtMs - this.options.operationTimeoutMs +- this.directHeadStartMs()- );- }-- private foregroundSfuIndex(operation: ChildOperation<Resource>): number {- if (this.isBackgroundConvergence(operation.reason)) {- return -1;- }- const index = operation.candidates.findIndex(- (candidate, candidateIndex) =>- candidateIndex >= operation.cursor && candidate.tuple.kind === "sfu",- );- return index >= 0- ? index- : this.bootstrapCandidateAvailable(operation.demandPeerId)- ? operation.candidates.length- : -1;- }-- private promoteNextDirectWithinHeadStart(- operation: ChildOperation<Resource>,- nowMs: number,- ): void {- const sfuIndex = this.foregroundSfuIndex(operation);- if (- sfuIndex !== operation.cursor + 1 ||- nowMs >= this.directHeadStartDeadlineAt(operation)- ) {- return;- }- const nextDirectIndex = operation.candidates.findIndex(- (candidate, candidateIndex) =>- candidateIndex > sfuIndex && candidate.tuple.kind === "peer",- );- if (nextDirectIndex < 0) return;- const [nextDirect] = operation.candidates.splice(nextDirectIndex, 1);- operation.candidates.splice(sfuIndex, 0, nextDirect!);- }-- private bootstrapCandidateAvailable(demandPeerId: string): boolean {- return this.safeSfuBootstrapCarriers(demandPeerId).length > 0;- }-- private guardMatches(guard: CandidateGuard, operation: ChildOperation<Resource>, attempt: Attempt<Resource>): boolean {- return guard.childPeerId === operation.childPeerId && guard.childSessionId === operation.childSessionId &&- guard.revision === attempt.revision && guard.connectionId === attempt.connectionId;- }-- private cursorGuardMatches(guard: CandidateCursorGuard, operation: ChildOperation<Resource>): boolean {- const plan = operation.candidates[operation.cursor];- return Boolean(plan &&- guard.childPeerId === operation.childPeerId &&- guard.childSessionId === operation.childSessionId && guard.baseRevision === operation.baseRevision &&- guard.factVersion === operation.builtAtFactVersion && guard.cursor === operation.cursor &&- candidatePlanEquals(guard.plan, plan));- }-- private childrenOf(parentPeerId: string): string[] {- return [...this.upstreamByViewer].filter(([, edge]) => edge.kind === "peer" && edge.parentPeerId === parentPeerId).map(([id]) => id);- }-- private descendantsOf(peerId: string): Set<string> {- const descendants = new Set<string>();- const queue = [peerId];- while (queue.length) for (const child of this.childrenOf(queue.pop()!)) if (!descendants.has(child)) {- descendants.add(child); queue.push(child);- }- return descendants;- }-- private sourceUsable(peerId: string): boolean {- if (peerId === this.options.hostPeerId) return true;- const seen = new Set<string>();- while (!seen.has(peerId)) {- seen.add(peerId);- const edge = this.upstreamByViewer.get(peerId);- if (!edge?.usable || !edge.physicalActive) return false;- if (edge.kind === "sfu") return Boolean(this.hostPublication?.usable &&- this.hostPublication.physicalActive && this.hostPublication.generation === edge.publicationGeneration);- if (edge.parentPeerId === this.options.hostPeerId) return true;- peerId = edge.parentPeerId;- }- return false;- }-- private targetFits(parentPeerId: string, childPeerId: string): boolean {- const parent = this.participants.get(parentPeerId)!;- const edge = this.upstreamByViewer.get(childPeerId);- const already = edge?.kind === "peer" && edge.parentPeerId === parentPeerId && edge.physicalActive;- const releasesLastPublication = parent.role === "host" && edge?.kind === "sfu" && edge.physicalActive &&- this.sfuSubscriberCount() === 1;- return this.usedSlots(parentPeerId) - (releasesLastPublication ? 1 : 0) +- (already ? 0 : 1) <= parent.effectiveDownstreamCapacity;- }-- private publicationFits(childPeerId: string, replacing: boolean): boolean {- const host = this.participants.get(this.options.hostPeerId);- const edge = this.upstreamByViewer.get(childPeerId);- const releasesHost = edge?.kind === "peer" && edge.parentPeerId === this.options.hostPeerId && edge.physicalActive;- const replacesPhysicalPublication = replacing && Boolean(this.hostPublication?.physicalActive);- const nextSlots = this.usedSlots(this.options.hostPeerId) - (releasesHost ? 1 : 0) +- (replacesPhysicalPublication ? 0 : 1);- return Boolean(host?.sessionId && !host.departureConfirmed && nextSlots <= host.effectiveDownstreamCapacity);- }-- private hostHasPublicationSlot(): boolean {- const host = this.participants.get(this.options.hostPeerId);- return Boolean(host && this.usedSlots(this.options.hostPeerId) + 1 <= host.effectiveDownstreamCapacity);- }-- private usedSlots(peerId: string): number {- return this.physicalCopies(peerId);- }-- private remaining(parentPeerId: string, childPeerId: string): number {- const parent = this.participants.get(parentPeerId)!;- const edge = this.upstreamByViewer.get(childPeerId);- const already = edge?.kind === "peer" && edge.parentPeerId === parentPeerId && edge.physicalActive;- return parent.effectiveDownstreamCapacity - this.usedSlots(parentPeerId) - (already ? 0 : 1);- }-- private depth(peerId: string): number {- if (peerId === this.options.hostPeerId) return 1;- let depth = 1;- const seen = new Set<string>();- while (!seen.has(peerId)) {- seen.add(peerId);- const edge = this.upstreamByViewer.get(peerId);- if (!edge || edge.kind === "sfu") return depth + 1;- depth += 1;- if (edge.parentPeerId === this.options.hostPeerId) return depth;- peerId = edge.parentPeerId;- }- return Number.MAX_SAFE_INTEGER;- }-- private hasSfuSubscribers(): boolean {- return [...this.upstreamByViewer.values()].some((edge) => edge.kind === "sfu" && edge.physicalActive);- }-- private sfuSubscriberCount(): number {- return [...this.upstreamByViewer.values()].filter((edge) => edge.kind === "sfu" && edge.physicalActive).length;- }-- private committedResources(): Resource[] {- const resources: Resource[] = [];- for (const edge of this.upstreamByViewer.values()) {- if (edge.kind === "sfu" && edge.physicalActive) resources.push(edge.resource);- }- if (this.hostPublication?.physicalActive) resources.push(this.hostPublication.resource);- return resources;- }-- private diagnosticParent(- edge: CommittedEdge<Resource> | undefined,- ordinals: ReadonlyMap<string, number>,- ): RouteDiagnosticSnapshot["children"][number]["parent"] {- if (!edge || !edge.usable || !edge.physicalActive) {- return { kind: "none" };- }- if (edge.kind === "sfu") {- return this.hostPublication?.usable &&- this.hostPublication.physicalActive &&- this.hostPublication.generation === edge.publicationGeneration- ? { kind: "sfu" }- : { kind: "none" };- }- if (edge.parentPeerId === this.options.hostPeerId) {- return { kind: "host" };- }- const ordinal = ordinals.get(edge.parentPeerId);- return ordinal === undefined- ? { kind: "none" }- : { kind: "viewer", ordinal };- }-- private diagnosticQuality(- childPeerId: string,- edge: CommittedEdge<Resource> | undefined,- nowMs: number,- ): RouteDiagnosticSnapshot["children"][number]["quality"] {- const observation = this.qualityObservations.get(childPeerId);- const participant = this.participants.get(childPeerId);- if (- this.paused ||- !observation ||- observation.eligibleWindows === 0 ||- nowMs >=- observation.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS ||- !participant?.sessionId ||- participant.sessionId !== observation.childSessionId ||- !edge ||- !edge.usable ||- !edge.physicalActive ||- edge.connectionId !== observation.connectionId ||- !this.qualityObservationMatchesEdge(observation, edge) ||- !this.sourceUsableForQuality(edge)- ) {- return null;- }- return {- eligibleWindows: observation.eligibleWindows,- eligibleDurationMs: observation.eligibleDurationMs,- freezeWindows: observation.freezeWindows,- freezeCount: observation.freezeCount,- freezeDurationMs: observation.freezeDurationMs,- pauseCount: observation.pauseCount,- pauseDurationMs: observation.pauseDurationMs,- };- }-- private qualityUpstreamMatches(- edge: CommittedEdge<Resource>,- upstream: RouteQualityEvidenceInput["upstream"],- ): boolean {- return edge.kind === "peer"- ? upstream.kind === "peer" && upstream.peerId === edge.parentPeerId- : upstream.kind === "sfu";- }-- private qualityObservationMatchesEdge(- observation: RouteQualityObservation,- edge: CommittedEdge<Resource>,- ): boolean {- return edge.kind === "peer"- ? observation.upstreamKind === "peer" &&- observation.upstreamPeerId === edge.parentPeerId- : observation.upstreamKind === "sfu" &&- observation.upstreamPeerId === null;- }-- private sourceUsableForQuality(edge: CommittedEdge<Resource>): boolean {- if (edge.kind === "peer") {- return (- edge.parentSessionId ===- this.participants.get(edge.parentPeerId)?.sessionId &&- this.sourceUsable(edge.parentPeerId)- );- }- return Boolean(- this.hostPublication?.usable &&- this.hostPublication.physicalActive &&- this.hostPublication.generation === edge.publicationGeneration,- );- }-- private clearQualityForParticipant(peerId: string): void {- const affected =- peerId === this.options.hostPeerId- ? new Set(this.upstreamByViewer.keys())- : this.descendantsOf(peerId).add(peerId);- affected.forEach((childPeerId) => {- this.qualityObservations.delete(childPeerId);- this.senderQualityObservations.delete(childPeerId);- this.senderQualityBaselines.delete(childPeerId);- this.senderQualityRegenerationBlocks.delete(childPeerId);- if (this.upstreamByViewer.has(childPeerId)) {- this.qualityBaselinesPending.add(childPeerId);- this.senderQualityBaselines.set(childPeerId, true);- } else {- this.qualityBaselinesPending.delete(childPeerId);- this.senderQualityBaselines.delete(childPeerId);- }- });- }-- private clearOpportunitiesForSessionChange(- peerId: string,- role: Participant["role"],- ): void {- const participant = this.participants.get(peerId);- if (participant) {- participant.consumedCandidateOpportunities.clear();- participant.availabilityExhausted = false;- participant.bootstrapFailureReported = undefined;- }- const parentPrefix = `peer:${peerId}\0`;- for (const child of this.participants.values()) {- for (const key of child.consumedCandidateOpportunities.keys()) {- if (- key.startsWith(parentPrefix) ||- (role === "host" && key.startsWith(SFU_OPPORTUNITY_PREFIX))- ) {- child.consumedCandidateOpportunities.delete(key);- }- }- if (role === "host") {- child.bootstrapFailureReported = undefined;- }- }- if (role === "host") {- this.consumedSfuBootstrapOpportunities.clear();- } else {- const carrierPrefix = `${peerId}\0`;- for (const key of this.consumedSfuBootstrapOpportunities.keys()) {- if (key.startsWith(carrierPrefix)) {- this.consumedSfuBootstrapOpportunities.delete(key);- }- }- }- }-- private clearSfuCandidateOpportunities(): void {- for (const participant of this.participants.values()) {- for (const key of participant.consumedCandidateOpportunities.keys()) {- if (key.startsWith(SFU_OPPORTUNITY_PREFIX)) {- participant.consumedCandidateOpportunities.delete(key);- }- }- participant.bootstrapFailureReported = undefined;- }- this.consumedSfuBootstrapOpportunities.clear();- }-- private requireSenderQualityBaseline(- peerId: string,- suppressFact = false,- ): void {- for (const childPeerId of this.descendantsOf(peerId).add(peerId)) {- if (this.upstreamByViewer.has(childPeerId)) {- this.senderQualityObservations.delete(childPeerId);- this.senderQualityBaselines.set(- childPeerId,- suppressFact || this.senderQualityBaselines.get(childPeerId) === true,- );- }- }- }-- private clearSfuQuality(): void {- this.sfuPublisherQualityObservation = undefined;- for (const [childPeerId, edge] of this.upstreamByViewer) {- if (edge.kind === "sfu") {- this.clearQualityForParticipant(childPeerId);- }- }- }-- private recordDemand(- childPeerId: string,- nowMs: number,- reason: RouteDemandReason,- ): void {- const record: RouteTimingRecord = {- demandAtMs: nowMs,- reason,- finalRoute: "waiting",- rejectionBucket: "none",- };- this.routeTimings.set(childPeerId, record);- }-- private ensureDemand(- childPeerId: string,- nowMs: number,- reason: RouteDemandReason,- ): void {- if (!this.routeTimings.has(childPeerId)) {- this.recordDemand(childPeerId, nowMs, reason);- }- }-- private startOperationTiming(childPeerId: string, nowMs: number): void {- const record = this.routeTimings.get(childPeerId);- if (!record) return;- record.operationStartedAtMs = nowMs;- record.candidateStartedAtMs = undefined;- record.firstDecodedFrameAtMs = undefined;- record.finalAtMs = undefined;- record.finalRoute = "waiting";- record.rejectionBucket = "none";- }-- private startCandidateTiming(childPeerId: string, nowMs: number): void {- const record = this.routeTimings.get(childPeerId);- if (!record) return;- record.candidateStartedAtMs = nowMs;- record.firstDecodedFrameAtMs = undefined;- record.finalAtMs = undefined;- record.finalRoute = "waiting";- record.rejectionBucket = "none";- }-- private noteRejection(- childPeerId: string,- bucket: RouteDiagnosticRejectionBucket,- ): void {- const record = this.routeTimings.get(childPeerId);- if (record) record.rejectionBucket = bucket;- }-- private clearCandidateTiming(childPeerId: string): void {- const record = this.routeTimings.get(childPeerId);- if (!record) return;- record.candidateStartedAtMs = undefined;- record.firstDecodedFrameAtMs = undefined;- record.finalAtMs = undefined;- record.finalRoute = "waiting";- }-- private finishTiming(- childPeerId: string,- nowMs: number,- finalRoute: RouteDiagnosticFinalRoute,- rejectionBucket: RouteDiagnosticRejectionBucket,- firstDecodedFrame = false,- ): void {- const record = this.routeTimings.get(childPeerId);- if (!record) return;- if (firstDecodedFrame) record.firstDecodedFrameAtMs = nowMs;- record.finalAtMs = nowMs;- record.finalRoute = finalRoute;- record.rejectionBucket = rejectionBucket;- }-- private usableRoute(childPeerId: string): boolean {- return this.currentFinalRoute(childPeerId) !== "waiting";- }-- private currentFinalRoute(- childPeerId: string,- ): RouteDiagnosticFinalRoute {- const edge = this.upstreamByViewer.get(childPeerId);- if (!edge?.usable || !edge.physicalActive) return "waiting";- if (edge.kind === "peer") {- return this.sourceUsable(edge.parentPeerId) ? "direct" : "waiting";- }- return this.hostPublication?.usable &&- this.hostPublication.physicalActive &&- this.hostPublication.generation === edge.publicationGeneration- ? "sfu"- : "waiting";- }-- private routeDemandReason(childPeerId: string): RouteDemandReason {- const edge = this.upstreamByViewer.get(childPeerId);- if (!edge) return "join";- if (- edge.kind === "peer" &&- this.participants.get(edge.parentPeerId)?.departureConfirmed- ) {- return "parent-departed";- }- if (- edge.kind === "peer" &&- this.overflowPeerChildren(edge.parentPeerId).includes(childPeerId)- ) {- return "capacity-reduction";- }- return "edge-unavailable";- }-- private rebindCommittedSession(- peerId: string,- sessionId: string,- ): { released: Resource[]; retired: boolean } {- const released = new Set<Resource>();- const ownEdge = this.upstreamByViewer.get(peerId);- if (ownEdge) {- ownEdge.childSessionId = sessionId;- }- for (const edge of this.upstreamByViewer.values()) {- if (edge.kind !== "peer" || edge.parentPeerId !== peerId) continue;- edge.parentSessionId = sessionId;- }- if (peerId === this.options.hostPeerId && this.hostPublication) {- this.hostPublication.hostSessionId = sessionId;- }- return { released: [...released], retired: false };- }-- private removePublicationGeneration(generation: string): Resource[] {- const released: Resource[] = [];- for (const [viewerPeerId, edge] of this.upstreamByViewer) {- if (edge.kind !== "sfu" || edge.publicationGeneration !== generation) continue;- this.retireSfuEdge(viewerPeerId, edge, released);- }- if (this.hostPublication?.generation === generation) {- if (this.hostPublication.physicalActive) released.push(this.hostPublication.resource);- this.hostPublication = null;- }- this.pruneRetiringSfuAnchors();- return released;- }-- private retireSfuEdge(- viewerPeerId: string,- edge: Extract<CommittedEdge<Resource>, { kind: "sfu" }>,- released: Resource[],- retainAnchor = this.childrenOf(viewerPeerId).length > 0,- ): void {- if (edge.physicalActive) released.push(edge.resource);- this.clearQualityForParticipant(viewerPeerId);- if (retainAnchor) {- edge.usable = false;- edge.physicalActive = false;- this.retiringPublicationGenerations.add(edge.publicationGeneration);- } else {- this.upstreamByViewer.delete(viewerPeerId);- }- }-- private pruneRetiringSfuAnchors(): void {- let removed = true;- while (removed) {- removed = false;- for (const [viewerPeerId, edge] of this.upstreamByViewer) {- if (- edge.kind === "sfu" &&- !edge.physicalActive &&- this.retiringPublicationGenerations.has(- edge.publicationGeneration,- ) &&- this.childrenOf(viewerPeerId).length === 0- ) {- this.upstreamByViewer.delete(viewerPeerId);- removed = true;- }- }- }- for (const generation of this.retiringPublicationGenerations) {- if (![...this.upstreamByViewer.values()].some(- (edge) =>- edge.kind === "sfu" &&- !edge.physicalActive &&- edge.publicationGeneration === generation,- )) {- this.retiringPublicationGenerations.delete(generation);- }- }- }-- private assertGraph(): void {- const host = this.participants.get(this.options.hostPeerId);- if (!host || host.role !== "host") throw new Error("Route Host is missing");- for (const [child, edge] of this.upstreamByViewer) {- this.assertViewer(child);- if (edge.kind === "peer" && !this.participants.has(edge.parentPeerId)) throw new Error("Route parent is missing");- if (- edge.kind === "sfu" &&- edge.physicalActive &&- this.hostPublication?.generation !== edge.publicationGeneration- ) {- throw new Error("SFU publication is stale");- }- if (- edge.kind === "sfu" &&- !edge.physicalActive &&- !this.retiringPublicationGenerations.has(edge.publicationGeneration)- ) {- throw new Error("Retiring SFU publication is unknown");- }- const seen = new Set<string>();- let current = child;- while (current !== this.options.hostPeerId) {- if (seen.has(current)) throw new Error("Peer route contains a cycle");- seen.add(current);- const currentEdge = this.upstreamByViewer.get(current);- if (!currentEdge) throw new Error("Route is not source-reachable");- if (currentEdge.kind === "sfu") {- if (- currentEdge.physicalActive- ? this.hostPublication?.generation !== currentEdge.publicationGeneration- : !this.retiringPublicationGenerations.has(- currentEdge.publicationGeneration,- )- ) {- throw new Error("Route terminates at an unknown SFU publication");- }- break;- }- current = currentEdge.parentPeerId;- }- }- for (const participant of this.participants.values()) if (this.usedSlots(participant.peerId) > this.options.endpointMediaCopyCapacity) {- throw new Error("Committed route exceeds endpoint capacity");- }- for (const generation of this.retiringPublicationGenerations) {- if (![...this.upstreamByViewer.values()].some(- (edge) =>- edge.kind === "sfu" &&- !edge.physicalActive &&- edge.publicationGeneration === generation,- )) {- throw new Error("Retiring SFU publication has no anchor");- }- }- }-- private assertViewer(peerId: string): void {- if (this.participants.get(peerId)?.role !== "viewer") throw new Error("Route child must be a Viewer");- }-- private debugPeer(peerId: string): string {- const participant = this.participants.get(peerId);- if (peerId === this.options.hostPeerId || participant?.role === "host") {- return "host";- }- return participant ? `viewer-${participant.joinOrder}` : "viewer-unknown";- }-- private debugTuple(tuple: CandidateTuple): string {- return tuple.kind === "peer"- ? `p2p:${this.debugPeer(tuple.parentPeerId)}${- tuple.regenerate ? ":regenerate" : ""- }`- : `sfu:${tuple.publication}`;- }-- private debug(event: string, details: Record<string, unknown>): void {- if (!this.options.debugRoomId) return;- routeDebug(- "%s",- JSON.stringify({- event,- roomId: this.options.debugRoomId,- revision: this.revision,- factVersion: this.factVersion,- ...details,- }),- );- }-- private effectiveCapacity(value: number): number {- if (!Number.isSafeInteger(value) || value < 0) throw new Error("Effective capacity is invalid");- return Math.min(value, this.options.endpointMediaCopyCapacity);- }-- private touchFacts(): void { this.factVersion += 1; }-- private allocateRevision(): number {- if (this.latestRevision >= MAX_MEDIA_ROUTE_REVISION) throw new Error("Media route revision space exhausted");- this.latestRevision += 1;- return this.latestRevision;- }-}--function compareParticipant(left: Participant, right: Participant): number {- return left.joinOrder - right.joinOrder || left.peerId.localeCompare(right.peerId);-}--function failedPeerIdsFrom(- ...results: ReadonlyArray<{ exhaustedChildPeerId?: string }>-): string[] {- return [- ...new Set(- results.flatMap((result) =>- result.exhaustedChildPeerId ? [result.exhaustedChildPeerId] : [],- ),- ),- ];-}--function stablePairRank(childPeerId: string, parentPeerId: string): number {- return createHash("sha256")- .update(childPeerId)- .update("\0")- .update(parentPeerId)- .digest()- .readUIntBE(0, 6);-}--function elapsedMs(startedAtMs: number, endedAtMs: number): number | null {- const elapsed = Math.floor(endedAtMs - startedAtMs);- return Number.isSafeInteger(elapsed) && elapsed >= 0 ? elapsed : null;-}--function safeAdd(total: number, delta: number): number {- const rounded = Math.round(delta);- if (!Number.isSafeInteger(rounded) || rounded < 0) {- return total;- }- return rounded > Number.MAX_SAFE_INTEGER - total- ? Number.MAX_SAFE_INTEGER- : total + rounded;-}--function tupleKey(tuple: CandidateTuple): string {- return tuple.kind === "peer"- ? `peer:${tuple.parentPeerId}${tuple.regenerate ? ":regenerate" : ""}`- : `sfu:${tuple.publication}`;-}--function senderQualityRegenerationBlockMatches(- block: SenderQualityIdentity,- childSessionId: string,- input: SenderQualityEvidenceInput,-): boolean {- return (- block.childSessionId === childSessionId &&- block.parentPeerId === input.parentPeerId &&- block.parentSessionId === input.parentSessionId &&- block.connectionId === input.connectionId &&- block.senderIdentity === input.senderIdentity- );-}--function edgeTupleKey<Resource>(edge: CommittedEdge<Resource>): string {- return edge.kind === "peer" ? `peer:${edge.parentPeerId}` : "sfu:reuse";-}--function endpointTransitionRank(transition: EndpointTransition): number {- return transition.kind === "none"- ? 0- : transition.kind === "overlap"- ? 1- : 2;-}--function consumeOpportunity(- consumed: Map<string, number>,- base: string,- rank: number,-): void {- const previous = consumed.get(base);- if (previous === undefined || rank < previous) consumed.set(base, rank);-}--function cloneCandidatePlan(plan: CandidatePlan): CandidatePlan {- return {- tuple: { ...plan.tuple },- endpointTransition: plan.endpointTransition.kind === "bounded-gap"- ? { ...plan.endpointTransition, retire: { ...plan.endpointTransition.retire } }- : { ...plan.endpointTransition },- };-}--function candidatePlanEquals(left: CandidatePlan, right: CandidatePlan): boolean {- return tupleKey(left.tuple) === tupleKey(right.tuple) &&- endpointTransitionEquals(left.endpointTransition, right.endpointTransition);-}--function endpointTransitionEquals(left: EndpointTransition, right: EndpointTransition): boolean {- if (left.kind !== right.kind) return false;- if (left.kind === "none" && right.kind === "none") {- return left.producerPeerId === right.producerPeerId;- }- if (left.kind === "overlap" && right.kind === "overlap") {- return left.producerPeerId === right.producerPeerId;- }- if (left.kind !== "bounded-gap" || right.kind !== "bounded-gap" ||- left.producerPeerId !== right.producerPeerId || left.retire.kind !== right.retire.kind) return false;- if (left.retire.kind === "publication" && right.retire.kind === "publication") {- return left.retire.hostSessionId === right.retire.hostSessionId &&- left.retire.generation === right.retire.generation &&- left.retire.connectionId === right.retire.connectionId;- }- if (left.retire.kind === "edge" && right.retire.kind === "edge") {- return left.retire.childPeerId === right.retire.childPeerId &&- left.retire.childSessionId === right.retire.childSessionId &&- left.retire.parentPeerId === right.retire.parentPeerId &&- left.retire.parentSessionId === right.retire.parentSessionId &&- left.retire.transport === right.retire.transport &&- left.retire.connectionId === right.retire.connectionId;- }- return false;-}--function reservationResources<Resource>(reservation: CandidateReservation<Resource>): Resource[] {- const resources: Resource[] = [];- if (- "edge" in reservation &&- (reservation.kind !== "sfu-reuse" || !reservation.borrowed)- ) {- resources.push(reservation.edge);- }- if ("publication" in reservation) resources.push(reservation.publication);- if ("overlap" in reservation && reservation.overlap !== undefined) resources.push(reservation.overlap);- return resources;-}diff --git a/src/server/room-store.ts b/src/server/room-store.tsdeleted file mode 100644index 91e36deb..00000000--- a/src/server/room-store.ts+++ /dev/null@@ -1,1093 +0,0 @@-import {- createHash,- randomBytes,- scrypt,- timingSafeEqual,-} from "node:crypto";--import {- MAX_VIEWERS_PER_ROOM_LIMIT,- viewerGrantSchema,- viewerPasswordSchema,- type CodeEntryPolicy,- type Role,-} from "../shared/protocol.js";-import {- type RoomDatabase,- type StoredRoomAuthority,-} from "./room-database.js";--export type RoomStoreErrorCode =- | "INVALID_TOKEN"- | "ROOM_ACCESS_DENIED"- | "ROOM_BUSY"- | "ROOM_NOT_FOUND"- | "ROOM_EXPIRED"- | "ROOM_FULL"- | "HOST_ALREADY_CONNECTED"- | "ROOM_LIMIT";--export const ROOM_CAPACITY = 9_000;-const ROOM_CODE_FIRST = 1_000;-const VIEWER_PASSWORD_SALT_BYTES = 16;-const VIEWER_PASSWORD_VERIFIER_BYTES = 32;-const VIEWER_PASSWORD_MATERIAL_BYTES =- VIEWER_PASSWORD_SALT_BYTES + VIEWER_PASSWORD_VERIFIER_BYTES;-const VIEWER_PASSWORD_KDF_CONCURRENCY = 2;-const VIEWER_PASSWORD_KDF_PENDING_LIMIT = 16;-const VIEWER_PASSWORD_SCRYPT_OPTIONS = {- N: 16_384,- r: 8,- p: 1,- maxmem: 32 * 1024 * 1024,-} as const;-const DUMMY_VIEWER_PASSWORD_MATERIAL = Buffer.alloc(- VIEWER_PASSWORD_MATERIAL_BYTES,-);--type AsyncGateOutcome<T> =- | { kind: "value"; value: T }- | { kind: "busy" }- | { kind: "cancelled" };--export class RoomStoreError extends Error {- constructor(public readonly code: RoomStoreErrorCode) {- super(code);- this.name = "RoomStoreError";- }-}--interface Participant {- clientId: string;- peerId: string;- sessionId?: string;- admittedBy: "grant" | "code";-}--interface Room {- roomId: string;- hostTokenDigest: Buffer;- viewerGrantDigest: Buffer;- viewerPasswordMaterial: Buffer | null;- viewerAuthorizationGeneration: string;- codeEntryPolicy: CodeEntryPolicy;- sharingActive: boolean;- leaseExpiresAtMs: number | null;- host?: Participant;- viewers: Map<string, Participant>;-}--export interface CreatedRoom {- roomId: string;- hostToken: string;- codeEntryPolicy: CodeEntryPolicy;- viewerGrant: string | null;- expiresAt: string | null;-}--export type ConnectParticipantInput =- | {- roomId: string;- role: "host";- token: string;- clientId: string;- sessionId: string;- }- | {- roomId: string;- role: "viewer";- viewerGrant?: string;- clientId: string;- sessionId: string;- };--export interface ConnectViewerWithPasswordInput {- roomId: string;- password: string;- clientId: string;- sessionId: string;-}--export interface ConnectedParticipant {- roomId: string;- role: Role;- peerId: string;- expiresAt: string | null;- hostOnline: boolean;- replacedSessionId?: string;- viewerPeerIds: readonly string[];- codeEntryPolicy: CodeEntryPolicy;- viewerPasswordEnabled: boolean;- viewerAuthorizationGeneration: string;-}--export interface DisconnectedParticipant {- roomId: string;- role: Role;- peerId: string;-}--export interface ConnectedPeer {- peerId: string;- sessionId: string;-}--export interface ClosedRoom {- roomId: string;- sessionIds: readonly string[];-}--export interface ReplacedRoom {- created: CreatedRoom;- closed: ClosedRoom;-}--export interface RevokedViewer {- peerId: string;- sessionId?: string;-}--export interface ViewerGrantUpdate {- viewerGrant: string | null;- viewerAuthorizationGeneration: string;- previousViewerAuthorizationGeneration: string;- revokedViewers: readonly RevokedViewer[];-}--export interface CodeEntryUpdate {- codeEntryPolicy: CodeEntryPolicy;- viewerPasswordEnabled: boolean;-}--export interface RoomStoreOptions {- leaseMs: number;- maxRooms: number;- maxViewersPerRoom: number;- database?: RoomDatabase;- now?: () => number;- random?: (size: number) => Buffer;-}--export class RoomStore {- private readonly rooms = new Map<string, Room>();- private readonly freeRoomCodes = Array.from(- { length: ROOM_CAPACITY },- (_, index) => (ROOM_CODE_FIRST + index).toString(),- );- private readonly now: () => number;- private readonly random: (size: number) => Buffer;- private initialized: boolean;- readonly maxViewersPerRoom: number;-- constructor(private readonly options: RoomStoreOptions) {- if (!Number.isSafeInteger(options.leaseMs) || options.leaseMs <= 0) {- throw new Error("Room lease must be a positive integer");- }- if (- !Number.isSafeInteger(options.maxRooms) ||- options.maxRooms <= 0 ||- options.maxRooms > ROOM_CAPACITY- ) {- throw new Error(- `Room limit must be an integer between 1 and ${ROOM_CAPACITY}`,- );- }- if (- !Number.isSafeInteger(options.maxViewersPerRoom) ||- options.maxViewersPerRoom <= 0 ||- options.maxViewersPerRoom > MAX_VIEWERS_PER_ROOM_LIMIT- ) {- throw new Error(- `Room viewer limit must be an integer between 1 and ${MAX_VIEWERS_PER_ROOM_LIMIT}`,- );- }- this.now = options.now ?? Date.now;- this.random = options.random ?? randomBytes;- this.initialized = options.database === undefined;- this.maxViewersPerRoom = options.maxViewersPerRoom;- }-- initialize(): void {- if (this.initialized) {- return;- }- const database = this.options.database;- if (!database) {- this.initialized = true;- return;- }-- const startupNowMs = this.now();- try {- const storedRooms = database.initialize(- startupNowMs,- this.leaseDeadline(startupNowMs),- );- if (storedRooms.length > this.options.maxRooms) {- throw new Error("Room database exceeds the configured room limit");- }- const roomIds = new Set(storedRooms.map((room) => room.roomId));- if (roomIds.size !== storedRooms.length) {- throw new Error("Room database contains duplicate room IDs");- }- for (const stored of storedRooms) {- this.rooms.set(stored.roomId, {- ...stored,- hostTokenDigest: Buffer.from(stored.hostTokenDigest),- viewerGrantDigest: Buffer.from(stored.viewerGrantDigest),- viewerPasswordMaterial:- stored.viewerPasswordMaterial === null- ? null- : Buffer.from(stored.viewerPasswordMaterial),- sharingActive: false,- viewers: new Map(),- });- }- const availableCodes = this.freeRoomCodes.filter(- (roomId) => !roomIds.has(roomId),- );- this.freeRoomCodes.splice(0, this.freeRoomCodes.length, ...availableCodes);- this.initialized = true;- } catch (error) {- this.rooms.clear();- database.close();- throw error;- }- }-- async createRoom(- codeEntryPolicy: CodeEntryPolicy = "open",- roomPassword?: string | null,- preferredRoomId?: string,- ): Promise<CreatedRoom> {- this.ensureInitialized();- if (this.rooms.size >= this.options.maxRooms) {- throw new RoomStoreError("ROOM_LIMIT");- }- const createdAtMs = this.now();- const leaseExpiresAtMs = this.leaseDeadline(createdAtMs);- const passwordOutcome = roomPassword- ? await this.createViewerPasswordMaterial(roomPassword)- : null;- if (this.rooms.size >= this.options.maxRooms) {- throw new RoomStoreError("ROOM_LIMIT");- }- if (passwordOutcome?.kind === "busy") {- throw new RoomStoreError("ROOM_BUSY");- }- if (passwordOutcome?.kind === "cancelled") {- throw new Error("Room creation password derivation was cancelled");- }- const viewerPasswordMaterial =- passwordOutcome?.kind === "value" ? passwordOutcome.value : null;- const roomId = this.takeRoomCode(preferredRoomId);- try {- const { room, created } = this.newRoom(- roomId,- codeEntryPolicy,- viewerPasswordMaterial,- leaseExpiresAtMs,- );- this.options.database?.insertRoom(storedRoomAuthority(room));- this.rooms.set(roomId, room);- return created;- } catch (error) {- this.releaseRoomCode(roomId);- throw error;- }- }-- async replaceRoom(- roomId: string,- hostToken: string,- codeEntryPolicy: CodeEntryPolicy,- roomPassword?: string | null,- ): Promise<ReplacedRoom> {- this.ensureInitialized();- const current = this.getHostManagedRoom(roomId, hostToken);- const passwordOutcome = roomPassword- ? await this.createViewerPasswordMaterial(roomPassword, () => {- const room = this.rooms.get(roomId);- return (- room === current &&- verifyDigest(hostToken, room.hostTokenDigest)- );- })- : null;- const owned = this.getHostManagedRoom(roomId, hostToken);- if (owned !== current || passwordOutcome?.kind === "cancelled") {- throw new RoomStoreError("ROOM_ACCESS_DENIED");- }- if (passwordOutcome?.kind === "busy") {- throw new RoomStoreError("ROOM_BUSY");- }- const viewerPasswordMaterial =- passwordOutcome?.kind === "value" ? passwordOutcome.value : null;-- const replacementRoomId = this.takeRoomCode();- try {- const leaseExpiresAtMs = this.leaseDeadline(this.now());- const replacement = this.newRoom(- replacementRoomId,- codeEntryPolicy,- viewerPasswordMaterial,- leaseExpiresAtMs,- );- this.options.database?.replaceRoom(- roomId,- current.hostTokenDigest,- storedRoomAuthority(replacement.room),- );- const closed = {- roomId,- sessionIds: connectedSessionIds(current),- } satisfies ClosedRoom;- this.rooms.delete(roomId);- this.rooms.set(replacementRoomId, replacement.room);- this.releaseRoomCode(roomId);- return { created: replacement.created, closed };- } catch (error) {- this.releaseRoomCode(replacementRoomId);- throw error;- }- }-- connectParticipant(input: ConnectParticipantInput): ConnectedParticipant {- this.ensureInitialized();- let room: Room;- try {- room = this.getAvailableRoom(input.roomId);- } catch (error) {- if (- input.role === "viewer" &&- !input.viewerGrant &&- error instanceof RoomStoreError &&- (error.code === "INVALID_TOKEN" || error.code === "ROOM_EXPIRED")- ) {- throw new RoomStoreError("ROOM_NOT_FOUND");- }- throw error;- }- if (input.role === "host") {- if (!verifyDigest(input.token, room.hostTokenDigest)) {- throw new RoomStoreError("INVALID_TOKEN");- }- return this.connectHost(room, input);- }-- if (input.viewerGrant) {- if (!this.viewerGrantIsValid(room, input.viewerGrant)) {- throw new RoomStoreError("INVALID_TOKEN");- }- return this.connectViewer(room, input, "grant");- }- if (room.codeEntryPolicy !== "open") {- throw new RoomStoreError("INVALID_TOKEN");- }- return this.connectViewer(room, input, "code");- }-- viewerGrantMayEnter(roomId: string, grant: string | undefined): boolean {- this.ensureInitialized();- try {- return this.viewerGrantIsValid(this.getAvailableRoom(roomId), grant);- } catch (error) {- if (error instanceof RoomStoreError) {- return false;- }- throw error;- }- }-- async connectViewerWithPassword(- input: ConnectViewerWithPasswordInput,- mayConnect: () => boolean = () => true,- ): Promise<ConnectedParticipant> {- this.ensureInitialized();- if (!viewerPasswordSchema.safeParse(input.password).success) {- throw new RoomStoreError("INVALID_TOKEN");- }-- let room: Room | undefined;- try {- room = this.getAvailableRoom(input.roomId);- } catch (error) {- if (!(error instanceof RoomStoreError)) {- throw error;- }- }- const expectedMaterial =- room?.codeEntryPolicy === "private" && room.viewerPasswordMaterial- ? Buffer.from(room.viewerPasswordMaterial)- : DUMMY_VIEWER_PASSWORD_MATERIAL;- const expectedSalt = expectedMaterial.subarray(0, VIEWER_PASSWORD_SALT_BYTES);- const expectedVerifier = expectedMaterial.subarray(VIEWER_PASSWORD_SALT_BYTES);- const derived = await deriveViewerPassword(- input.password,- expectedSalt,- mayConnect,- );- if (derived.kind === "busy") {- throw new RoomStoreError("ROOM_BUSY");- }- if (derived.kind === "cancelled") {- throw new RoomStoreError("INVALID_TOKEN");- }- const matches = timingSafeEqual(derived.value, expectedVerifier);-- let currentRoom: Room;- try {- currentRoom = this.getAvailableRoom(input.roomId);- } catch (error) {- if (error instanceof RoomStoreError) {- throw new RoomStoreError("ROOM_NOT_FOUND");- }- throw error;- }- if (- !room ||- currentRoom !== room ||- currentRoom.codeEntryPolicy !== "private" ||- currentRoom.viewerPasswordMaterial === null ||- !matches ||- !sameBytes(currentRoom.viewerPasswordMaterial, expectedMaterial) ||- !mayConnect()- ) {- throw new RoomStoreError("INVALID_TOKEN");- }- try {- return this.connectViewer(currentRoom, { ...input, role: "viewer" }, "code");- } catch (error) {- if (error instanceof RoomStoreError && error.code === "ROOM_FULL") {- throw new RoomStoreError("INVALID_TOKEN");- }- throw error;- }- }-- async setViewerPassword(- roomId: string,- password: string | null,- hostToken: string,- ): Promise<boolean> {- this.ensureInitialized();- const room = this.getHostManagedRoom(roomId, hostToken);-- const passwordOutcome = password- ? await this.createViewerPasswordMaterial(password, () => {- const currentRoom = this.rooms.get(roomId);- return (- currentRoom === room &&- verifyDigest(hostToken, currentRoom.hostTokenDigest)- );- })- : null;-- const currentRoom = this.getHostManagedRoom(roomId, hostToken);- if (currentRoom !== room || passwordOutcome?.kind === "cancelled") {- throw new RoomStoreError("ROOM_ACCESS_DENIED");- }- if (passwordOutcome?.kind === "busy") {- throw new RoomStoreError("ROOM_BUSY");- }- const nextPasswordMaterial =- passwordOutcome?.kind === "value" ? passwordOutcome.value : null;- this.options.database?.setViewerPassword(- roomId,- currentRoom.hostTokenDigest,- nextPasswordMaterial,- );- currentRoom.viewerPasswordMaterial = nextPasswordMaterial;- return nextPasswordMaterial !== null;- }-- setCodeEntryPolicy(- roomId: string,- policy: CodeEntryPolicy,- hostToken: string,- ): CodeEntryUpdate {- this.ensureInitialized();- const room = this.getHostManagedRoom(roomId, hostToken);- this.options.database?.setCodeEntryPolicy(- roomId,- room.hostTokenDigest,- policy,- );- room.codeEntryPolicy = policy;- return {- codeEntryPolicy: policy,- viewerPasswordEnabled: room.viewerPasswordMaterial !== null,- };- }-- setViewerGrant(- roomId: string,- action: "rotate" | "revoke",- hostToken: string,- ): ViewerGrantUpdate {- this.ensureInitialized();- const room = this.getHostManagedRoom(roomId, hostToken);- const previousViewerAuthorizationGeneration =- room.viewerAuthorizationGeneration;- const viewerGrant = action === "rotate" ? this.createViewerGrant() : null;-- const revokedViewers = [...room.viewers.values()]- .filter((viewer) => viewer.admittedBy === "grant")- .map((viewer) => ({- peerId: viewer.peerId,- ...(viewer.sessionId ? { sessionId: viewer.sessionId } : {}),- }));- const viewerGrantDigest = viewerGrant- ? digest(viewerGrant)- : this.randomDigest();- const viewerAuthorizationGeneration = this.newAuthorizationGeneration();- this.options.database?.setViewerGrant(- roomId,- room.hostTokenDigest,- viewerGrantDigest,- viewerAuthorizationGeneration,- );- room.viewerGrantDigest = viewerGrantDigest;- room.viewerAuthorizationGeneration = viewerAuthorizationGeneration;- for (const [clientId, viewer] of room.viewers) {- if (viewer.admittedBy === "grant") {- room.viewers.delete(clientId);- }- }- return {- viewerGrant,- viewerAuthorizationGeneration: room.viewerAuthorizationGeneration,- previousViewerAuthorizationGeneration,- revokedViewers,- };- }-- disconnectParticipant(- roomId: string,- peerId: string,- sessionId: string,- ): DisconnectedParticipant | undefined {- this.ensureInitialized();- const room = this.rooms.get(roomId);- if (!room) {- return undefined;- }-- if (room.host?.peerId === peerId) {- if (room.host.sessionId !== sessionId) {- return undefined;- }- const leaseExpiresAtMs = this.leaseDeadline(this.now());- this.options.database?.setLeaseDeadline(- roomId,- room.hostTokenDigest,- leaseExpiresAtMs,- );- room.host.sessionId = undefined;- room.sharingActive = false;- room.leaseExpiresAtMs = leaseExpiresAtMs;- return { roomId, role: "host", peerId };- }-- const viewer = findViewerByPeerId(room, peerId);- if (!viewer || viewer.sessionId !== sessionId) {- return undefined;- }- viewer.sessionId = undefined;- return { roomId, role: "viewer", peerId };- }-- removeDisconnectedViewer(roomId: string, peerId: string): boolean {- const room = this.rooms.get(roomId);- if (!room) {- return false;- }- const viewer = findViewerByPeerId(room, peerId);- if (!viewer || viewer.sessionId) {- return false;- }- return room.viewers.delete(viewer.clientId);- }-- getConnectedHost(roomId: string): ConnectedPeer | undefined {- const host = this.rooms.get(roomId)?.host;- return host?.sessionId- ? { peerId: host.peerId, sessionId: host.sessionId }- : undefined;- }-- getConnectedViewer(roomId: string, peerId: string): ConnectedPeer | undefined {- const room = this.rooms.get(roomId);- const viewer = room ? findViewerByPeerId(room, peerId) : undefined;- return viewer?.sessionId ? { peerId, sessionId: viewer.sessionId } : undefined;- }-- getViewerPeerIds(roomId: string): string[] {- const room = this.rooms.get(roomId);- return room ? [...room.viewers.values()].map((viewer) => viewer.peerId) : [];- }-- getConnectedViewers(roomId: string): ConnectedPeer[] {- const room = this.rooms.get(roomId);- if (!room) {- return [];- }- return [...room.viewers.values()].flatMap((viewer) =>- viewer.sessionId- ? [{ peerId: viewer.peerId, sessionId: viewer.sessionId }]- : [],- );- }-- abandonRoom(roomId: string): ClosedRoom | undefined {- this.ensureInitialized();- const room = this.rooms.get(roomId);- if (!room) {- return undefined;- }- const sessionIds = connectedSessionIds(room);- this.options.database?.deleteRoom(roomId, room.hostTokenDigest);- this.rooms.delete(roomId);- this.releaseRoomCode(roomId);- return { roomId, sessionIds };- }-- abandonAllRooms(): ClosedRoom[] {- this.ensureInitialized();- return [...this.rooms.keys()].flatMap((roomId) => {- const closed = this.abandonRoom(roomId);- return closed ? [closed] : [];- });- }-- expireRooms(nowMs = this.now()): ClosedRoom[] {- this.ensureInitialized();- const expiredRooms = [...this.rooms].filter(([, room]) =>- roomIsExpired(room, nowMs),- );- this.options.database?.deleteRooms(- expiredRooms.map(([roomId, room]) => ({- roomId,- hostTokenDigest: room.hostTokenDigest,- })),- );- const expired = expiredRooms.map(([roomId, room]) => ({- roomId,- sessionIds: connectedSessionIds(room),- }));- for (const [roomId] of expiredRooms) {- this.rooms.delete(roomId);- this.releaseRoomCode(roomId);- }- return expired;- }-- get size(): number {- return this.rooms.size;- }-- close(): void {- this.options.database?.close();- }-- private connectHost(- room: Room,- input: ConnectParticipantInput,- ): ConnectedParticipant {- const current = room.host;- if (current?.sessionId && current.clientId !== input.clientId) {- throw new RoomStoreError("HOST_ALREADY_CONNECTED");- }-- const isNewParticipant = !current || current.clientId !== input.clientId;- const participant: Participant = isNewParticipant- ? {- clientId: input.clientId,- peerId: this.newPeerId(room),- admittedBy: "code",- }- : current;- const replacedSessionId = participant.sessionId;- this.options.database?.setLeaseDeadline(- room.roomId,- room.hostTokenDigest,- null,- );- participant.sessionId = input.sessionId;- room.host = participant;- room.sharingActive = true;- room.leaseExpiresAtMs = null;-- return this.connectedParticipant(- room,- participant.peerId,- "host",- replacedSessionId,- input.sessionId,- );- }-- private connectViewer(- room: Room,- input: ConnectParticipantInput,- admittedBy: "grant" | "code",- ): ConnectedParticipant {- const current = room.viewers.get(input.clientId);- if (!current && room.viewers.size >= this.maxViewersPerRoom) {- throw new RoomStoreError("ROOM_FULL");- }-- const participant =- current ??- ({- clientId: input.clientId,- peerId: this.newPeerId(room),- admittedBy,- } satisfies Participant);- const replacedSessionId = participant.sessionId;- participant.sessionId = input.sessionId;- participant.admittedBy = admittedBy;- room.viewers.set(input.clientId, participant);- return this.connectedParticipant(- room,- participant.peerId,- "viewer",- replacedSessionId,- input.sessionId,- );- }-- private connectedParticipant(- room: Room,- peerId: string,- role: Role,- replacedSessionId: string | undefined,- sessionId: string,- ): ConnectedParticipant {- return {- roomId: room.roomId,- role,- peerId,- expiresAt: formatExpiresAt(room.leaseExpiresAtMs),- hostOnline: Boolean(room.host?.sessionId),- replacedSessionId:- replacedSessionId === sessionId ? undefined : replacedSessionId,- viewerPeerIds:- role === "host"- ? [...room.viewers.values()].map((viewer) => viewer.peerId)- : [],- codeEntryPolicy: room.codeEntryPolicy,- viewerPasswordEnabled: room.viewerPasswordMaterial !== null,- viewerAuthorizationGeneration: room.viewerAuthorizationGeneration,- };- }-- private getAvailableRoom(roomId: string): Room {- const room = this.rooms.get(roomId);- if (!room) {- throw new RoomStoreError("INVALID_TOKEN");- }- if (roomIsExpired(room, this.now())) {- throw new RoomStoreError("ROOM_EXPIRED");- }- return room;- }-- private getHostManagedRoom(roomId: string, hostToken: string): Room {- const room = this.getAvailableRoom(roomId);- if (!verifyDigest(hostToken, room.hostTokenDigest)) {- throw new RoomStoreError("INVALID_TOKEN");- }- return room;- }-- private newPeerId(room: Room): string {- return this.uniqueId(- 16,- (candidate) =>- room.host?.peerId === candidate ||- [...room.viewers.values()].some((viewer) => viewer.peerId === candidate),- );- }-- private takeRoomCode(preferredRoomId?: string): string {- if (this.freeRoomCodes.length === 0) {- throw new RoomStoreError("ROOM_LIMIT");- }- if (preferredRoomId) {- const preferredIndex = this.freeRoomCodes.indexOf(preferredRoomId);- if (preferredIndex >= 0) {- return this.takeRoomCodeAt(preferredIndex);- }- }- const range = BigInt(this.freeRoomCodes.length);- const randomLimit = (1n << 64n) - ((1n << 64n) % range);- for (let attempt = 0; attempt < 16; attempt += 1) {- const bytes = this.random(8);- if (bytes.byteLength !== 8) {- throw new Error("Room code random source must return 8 bytes");- }- const value = bytes.readBigUInt64BE();- if (value >= randomLimit) {- continue;- }- const index = Number(value % range);- return this.takeRoomCodeAt(index);- }- throw new Error("Unable to select a room code uniformly");- }-- private takeRoomCodeAt(index: number): string {- const roomId = this.freeRoomCodes[index]!;- const lastRoomId = this.freeRoomCodes.pop()!;- if (index < this.freeRoomCodes.length) {- this.freeRoomCodes[index] = lastRoomId;- }- return roomId;- }-- private releaseRoomCode(roomId: string): void {- this.freeRoomCodes.push(roomId);- }-- private uniqueId(size: number, exists: (candidate: string) => boolean): string {- for (let attempt = 0; attempt < 8; attempt += 1) {- const value = this.random(size);- if (value.byteLength !== size) {- throw new Error(`Identifier random source must return ${size} bytes`);- }- const candidate = value.toString("base64url");- if (!exists(candidate)) {- return candidate;- }- }- throw new Error("Unable to allocate a unique identifier");- }-- private viewerGrantIsValid(room: Room, grant: string | undefined): boolean {- if (!grant || !viewerGrantSchema.safeParse(grant).success) {- return false;- }- return verifyDigest(grant, room.viewerGrantDigest);- }-- private createViewerGrant(): string {- const secret = this.random(16);- if (secret.byteLength !== 16) {- throw new Error("Viewer grant random source must return 16 bytes");- }- return secret.toString("base64url");- }-- private newRoom(- roomId: string,- codeEntryPolicy: CodeEntryPolicy,- viewerPasswordMaterial: Buffer | null,- leaseExpiresAtMs: number,- ): { room: Room; created: CreatedRoom } {- const hostTokenBytes = this.random(32);- if (hostTokenBytes.byteLength !== 32) {- throw new Error("Host token random source must return 32 bytes");- }- const hostToken = hostTokenBytes.toString("base64url");- const viewerGrant = this.createViewerGrant();- const room: Room = {- roomId,- hostTokenDigest: digest(hostToken),- viewerGrantDigest: digest(viewerGrant),- viewerPasswordMaterial,- viewerAuthorizationGeneration: this.newAuthorizationGeneration(),- codeEntryPolicy,- sharingActive: false,- leaseExpiresAtMs,- viewers: new Map(),- };- return {- room,- created: {- roomId,- hostToken,- codeEntryPolicy,- viewerGrant,- expiresAt: formatExpiresAt(leaseExpiresAtMs),- },- };- }-- private async createViewerPasswordMaterial(- password: string,- mayStart: () => boolean = () => true,- ): Promise<AsyncGateOutcome<Buffer>> {- if (!viewerPasswordSchema.safeParse(password).success) {- throw new RoomStoreError("INVALID_TOKEN");- }- const salt = this.random(VIEWER_PASSWORD_SALT_BYTES);- if (salt.byteLength !== VIEWER_PASSWORD_SALT_BYTES) {- throw new Error("Viewer password salt source must return 16 bytes");- }- const verifier = await deriveViewerPassword(password, salt, mayStart);- return verifier.kind === "value"- ? { kind: "value", value: Buffer.concat([salt, verifier.value]) }- : verifier;- }-- private randomDigest(): Buffer {- const value = this.random(32);- if (value.byteLength !== 32) {- throw new Error("Viewer grant random source must return 32 bytes");- }- return Buffer.from(value);- }-- private newAuthorizationGeneration(): string {- const value = this.random(16);- if (value.byteLength !== 16) {- throw new Error(- "Authorization generation random source must return 16 bytes",- );- }- return value.toString("base64url");- }-- private leaseDeadline(nowMs: number): number {- const deadline = nowMs + this.options.leaseMs;- if (!Number.isSafeInteger(deadline) || deadline <= nowMs) {- throw new Error("Room lease deadline exceeds the supported time range");- }- return deadline;- }-- private ensureInitialized(): void {- if (!this.initialized) {- throw new Error("RoomStore stable authority is not initialized");- }- }-}--function storedRoomAuthority(room: Room): StoredRoomAuthority {- return {- roomId: room.roomId,- hostTokenDigest: room.hostTokenDigest,- viewerGrantDigest: room.viewerGrantDigest,- viewerAuthorizationGeneration: room.viewerAuthorizationGeneration,- codeEntryPolicy: room.codeEntryPolicy,- viewerPasswordMaterial: room.viewerPasswordMaterial,- leaseExpiresAtMs: room.leaseExpiresAtMs,- };-}--function roomIsExpired(room: Room, nowMs: number): boolean {- return (- !room.sharingActive &&- room.leaseExpiresAtMs !== null &&- room.leaseExpiresAtMs <= nowMs- );-}--function formatExpiresAt(expiresAtMs: number | null): string | null {- return expiresAtMs === null ? null : new Date(expiresAtMs).toISOString();-}--function findViewerByPeerId(- room: Room,- peerId: string,-): Participant | undefined {- return [...room.viewers.values()].find((viewer) => viewer.peerId === peerId);-}--function connectedSessionIds(room: Room): string[] {- const sessionIds = room.host?.sessionId ? [room.host.sessionId] : [];- for (const viewer of room.viewers.values()) {- if (viewer.sessionId) {- sessionIds.push(viewer.sessionId);- }- }- return sessionIds;-}--function digest(value: string): Buffer {- return createHash("sha256").update(value).digest();-}--function verifyDigest(value: string, expectedDigest: Buffer): boolean {- return timingSafeEqual(digest(value), expectedDigest);-}--function sameBytes(value: Buffer | null, expected: Buffer): boolean {- return value !== null && timingSafeEqual(value, expected);-}--function deriveViewerPassword(- password: string,- salt: Buffer,- mayStart: () => boolean = () => true,-): Promise<AsyncGateOutcome<Buffer>> {- return viewerPasswordKdfGate.run(- () =>- new Promise<Buffer>((resolve, reject) => {- scrypt(- password,- salt,- VIEWER_PASSWORD_VERIFIER_BYTES,- VIEWER_PASSWORD_SCRYPT_OPTIONS,- (error, derivedKey) =>- error ? reject(error) : resolve(derivedKey),- );- }),- mayStart,- );-}--class AsyncGate {- private active = 0;- private readonly waiters: Array<() => void> = [];-- constructor(- private readonly limit: number,- private readonly pendingLimit: number,- ) {}-- async run<T>(- task: () => Promise<T>,- mayStart: () => boolean,- ): Promise<AsyncGateOutcome<T>> {- if (!(await this.acquire())) {- return { kind: "busy" };- }- try {- if (!mayStart()) {- return { kind: "cancelled" };- }- return { kind: "value", value: await task() };- } finally {- this.release();- }- }-- private acquire(): Promise<boolean> {- if (this.active >= this.limit) {- if (this.waiters.length >= this.pendingLimit) {- return Promise.resolve(false);- }- return new Promise<boolean>((resolve) =>- this.waiters.push(() => resolve(true)),- );- }- this.active += 1;- return Promise.resolve(true);- }-- private release(): void {- const next = this.waiters.shift();- if (next) {- next();- return;- }- this.active -= 1;- }-}--const viewerPasswordKdfGate = new AsyncGate(- VIEWER_PASSWORD_KDF_CONCURRENCY,- VIEWER_PASSWORD_KDF_PENDING_LIMIT,-);diff --git a/src/server/sfu-resource-admission.ts b/src/server/sfu-resource-admission.tsdeleted file mode 100644index e2b2a3b1..00000000--- a/src/server/sfu-resource-admission.ts+++ /dev/null@@ -1,323 +0,0 @@-export interface SfuResourceFence {- roomId: string;- shareGeneration: string;- publicationGeneration: string;-}--export interface SfuSubscriptionFence extends SfuResourceFence {- viewerPeerId: string;-}--const MANAGED_ROOM_PREFIX = "screener-v1.";-const ROOM_ID_PATTERN = /^[1-9]\d{0,11}$/;-const OPAQUE_ID_PATTERN = /^[A-Za-z0-9_-]{8,128}$/;--export interface SfuResourceAdmissionOptions {- readonly ingressCapacity: number;- readonly egressCapacity: number;-}--export interface SfuResourceUsage {- ingress: number;- egress: number;-}--type ResourceState = "reserved" | "committed" | "draining";--interface SubscriptionEntry {- fence: SfuSubscriptionFence;- state: ResourceState;-}--interface PublicationEntry {- fence: SfuResourceFence;- state: ResourceState;- subscriptions: Map<string, SubscriptionEntry>;-}--interface RoomResources {- publications: Map<string, PublicationEntry>;-}--export class SfuResourceAdmission {- private readonly rooms = new Map<string, RoomResources>();- private readonly ingressCapacity: number;- private readonly egressCapacity: number;- private ingressInUse = 0;- private egressInUse = 0;-- constructor(options: SfuResourceAdmissionOptions) {- assertPositiveSafeInteger(options.ingressCapacity, "SFU ingress capacity");- assertPositiveSafeInteger(options.egressCapacity, "SFU egress capacity");- this.ingressCapacity = options.ingressCapacity;- this.egressCapacity = options.egressCapacity;- }-- reservePublication(fence: SfuResourceFence): boolean {- assertFence(fence);- const room = this.rooms.get(fence.roomId);- const existing = room?.publications.get(publicationKey(fence));- if (existing) {- return existing.state !== "draining" && sameFence(existing.fence, fence);- }- if (- this.ingressInUse >= this.ingressCapacity ||- [...(room?.publications.values() ?? [])].some(- (publication) => publication.state === "reserved",- )- ) {- return false;- }-- const resources = room ?? { publications: new Map() };- resources.publications.set(publicationKey(fence), {- fence: cloneFence(fence),- state: "reserved",- subscriptions: new Map(),- });- this.rooms.set(fence.roomId, resources);- this.ingressInUse += 1;- return true;- }-- reserveSubscription(fence: SfuSubscriptionFence): boolean {- assertSubscriptionFence(fence);- const publication = this.publication(fence);- if (!publication || publication.state === "draining") {- return false;- }- const existing = publication.subscriptions.get(fence.viewerPeerId);- if (existing) {- if (!sameSubscriptionFence(existing.fence, fence)) return false;- if (existing.state === "reserved" || existing.state === "committed") {- return true;- }- if (publication.state !== "committed") return false;- existing.state = "reserved";- return true;- }- if (this.egressInUse >= this.egressCapacity) return false;-- publication.subscriptions.set(fence.viewerPeerId, {- fence: cloneSubscriptionFence(fence),- state: "reserved",- });- this.egressInUse += 1;- return true;- }-- commitPublication(fence: SfuResourceFence): readonly SfuResourceFence[] | null {- assertFence(fence);- const room = this.rooms.get(fence.roomId);- const publication = room?.publications.get(publicationKey(fence));- if (!room || !publication || !sameFence(publication.fence, fence)) {- return null;- }- if (publication.state === "committed") return [];- if (publication.state !== "reserved") return null;- if (![...publication.subscriptions.values()].some((entry) => entry.state === "reserved")) {- return null;- }-- const draining: SfuResourceFence[] = [];- for (const other of room.publications.values()) {- if (other === publication || other.state !== "committed") continue;- this.markDraining(other);- draining.push(cloneFence(other.fence));- }- publication.state = "committed";- for (const subscription of publication.subscriptions.values()) {- if (subscription.state === "reserved") {- subscription.state = "committed";- }- }- return draining;- }-- commitSubscription(fence: SfuSubscriptionFence): boolean {- assertSubscriptionFence(fence);- const publication = this.publication(fence);- const subscription = publication?.subscriptions.get(fence.viewerPeerId);- if (- publication?.state !== "committed" ||- !subscription ||- !sameSubscriptionFence(subscription.fence, fence)- ) {- return false;- }- if (subscription.state === "committed") return true;- if (subscription.state !== "reserved") return false;- subscription.state = "committed";- return true;- }-- beginSubscriptionDrain(fence: SfuSubscriptionFence): boolean {- assertSubscriptionFence(fence);- const publication = this.publication(fence);- const subscription = publication?.subscriptions.get(fence.viewerPeerId);- if (- !publication ||- !subscription ||- !sameSubscriptionFence(subscription.fence, fence)- ) {- return false;- }- if (subscription.state !== "draining") {- subscription.state = "draining";- }- return true;- }-- beginDrain(fence: SfuResourceFence): boolean {- assertFence(fence);- const publication = this.publication(fence);- if (!publication) return false;- this.markDraining(publication);- return true;- }-- completeDrain(fence: SfuResourceFence): boolean {- assertFence(fence);- const room = this.rooms.get(fence.roomId);- const key = publicationKey(fence);- const publication = room?.publications.get(key);- if (- !room ||- !publication ||- publication.state !== "draining" ||- !sameFence(publication.fence, fence)- ) {- return false;- }-- room.publications.delete(key);- this.ingressInUse -= 1;- this.subtractEgress(publication.subscriptions.size);- this.assertNoUnderflow();- if (room.publications.size === 0) this.rooms.delete(fence.roomId);- return true;- }-- beginDrainRoom(roomId: string): readonly SfuResourceFence[] {- if (!roomId) throw new Error("SFU resource room ID is invalid");- const room = this.rooms.get(roomId);- if (!room) return [];- for (const publication of room.publications.values()) {- this.markDraining(publication);- }- return [...room.publications.values()].map((publication) =>- cloneFence(publication.fence),- );- }-- beginDrainAll(): readonly SfuResourceFence[] {- return [...this.rooms.keys()].flatMap((roomId) =>- this.beginDrainRoom(roomId),- );- }-- usage(): SfuResourceUsage {- return { ingress: this.ingressInUse, egress: this.egressInUse };- }-- private publication(- fence: SfuResourceFence,- ): PublicationEntry | undefined {- const publication = this.rooms- .get(fence.roomId)- ?.publications.get(publicationKey(fence));- return publication && sameFence(publication.fence, fence)- ? publication- : undefined;- }-- private markDraining(publication: PublicationEntry): void {- publication.state = "draining";- for (const subscription of publication.subscriptions.values()) {- subscription.state = "draining";- }- }-- private subtractEgress(count: number): void {- this.egressInUse -= count;- this.assertNoUnderflow();- }-- private assertNoUnderflow(): void {- if (this.ingressInUse < 0 || this.egressInUse < 0) {- throw new Error("SFU resource accounting underflow");- }- }-}--function publicationKey(fence: SfuResourceFence): string {- return `${fence.shareGeneration}\u0000${fence.publicationGeneration}`;-}--function cloneFence(fence: SfuResourceFence): SfuResourceFence {- return { ...fence };-}--function cloneSubscriptionFence(- fence: SfuSubscriptionFence,-): SfuSubscriptionFence {- return { ...fence };-}--function sameFence(left: SfuResourceFence, right: SfuResourceFence): boolean {- return (- left.roomId === right.roomId &&- left.shareGeneration === right.shareGeneration &&- left.publicationGeneration === right.publicationGeneration- );-}--function sameSubscriptionFence(- left: SfuSubscriptionFence,- right: SfuSubscriptionFence,-): boolean {- return sameFence(left, right) && left.viewerPeerId === right.viewerPeerId;-}--function assertFence(fence: SfuResourceFence): void {- if (!fence.roomId || !fence.shareGeneration || !fence.publicationGeneration) {- throw new Error("SFU resource fence is invalid");- }-}--function assertSubscriptionFence(fence: SfuSubscriptionFence): void {- assertFence(fence);- if (!fence.viewerPeerId) {- throw new Error("SFU subscription fence is invalid");- }-}--function assertPositiveSafeInteger(value: number, name: string): void {- if (!Number.isSafeInteger(value) || value <= 0) {- throw new Error(`${name} must be a positive safe integer`);- }-}--export function managedSfuRoomName(fence: SfuResourceFence): string {- if (- !ROOM_ID_PATTERN.test(fence.roomId) ||- !OPAQUE_ID_PATTERN.test(fence.shareGeneration) ||- !OPAQUE_ID_PATTERN.test(fence.publicationGeneration)- ) {- throw new Error("Managed LiveKit room fence is invalid");- }- return `${MANAGED_ROOM_PREFIX}${fence.roomId}.${fence.shareGeneration}.${fence.publicationGeneration}`;-}--export function isManagedSfuRoomName(roomName: string): boolean {- if (!roomName.startsWith(MANAGED_ROOM_PREFIX)) {- return false;- }- const parts = roomName.slice(MANAGED_ROOM_PREFIX.length).split(".");- return (- parts.length === 3 &&- ROOM_ID_PATTERN.test(parts[0] ?? "") &&- OPAQUE_ID_PATTERN.test(parts[1] ?? "") &&- OPAQUE_ID_PATTERN.test(parts[2] ?? "")- );-}diff --git a/src/server/sfu-room-control.ts b/src/server/sfu-room-control.tsdeleted file mode 100644index ecf2603a..00000000--- a/src/server/sfu-room-control.ts+++ /dev/null@@ -1,203 +0,0 @@-import { RoomServiceClient, ServerError } from "livekit-server-sdk";--import { MAX_VIEWERS_PER_ROOM_LIMIT } from "../shared/protocol.js";-import type {- SfuResourceFence,- SfuSubscriptionFence,-} from "./sfu-resource-admission.js";-import {- isManagedSfuRoomName,- managedSfuRoomName,-} from "./sfu-resource-admission.js";--const OPAQUE_ID_PATTERN = /^[A-Za-z0-9_-]{8,128}$/;-const ROOM_SERVICE_TIMEOUT_SECONDS = 5;--interface LiveKitRoomRecord {- name: string;-}--interface LiveKitParticipantRecord {- identity: string;-}--export interface LiveKitRoomService {- createRoom(options: {- name: string;- maxParticipants: number;- }): Promise<LiveKitRoomRecord>;- listRooms(names?: string[]): Promise<LiveKitRoomRecord[]>;- deleteRoom(room: string): Promise<void>;- listParticipants(room: string): Promise<LiveKitParticipantRecord[]>;- removeParticipant(room: string, identity: string): Promise<void>;-}--export interface SfuRoomControl {- initialize(): Promise<void>;- createRoom(fence: SfuResourceFence): Promise<void>;- deleteRoom(fence: SfuResourceFence): Promise<void>;- drainSubscription(fence: SfuSubscriptionFence): Promise<void>;- hostParticipantExists(fence: SfuResourceFence): Promise<boolean>;-}--export interface LiveKitSfuRoomControlOptions {- apiUrl: string;- apiKey: string;- apiSecret: string;- maxViewersPerRoom: number;- roomService?: LiveKitRoomService;-}--export class LiveKitSfuRoomControl implements SfuRoomControl {- private readonly roomService: LiveKitRoomService;- private readonly maxParticipants: number;- private readonly roomOperations = new Map<string, Promise<void>>();-- constructor(options: LiveKitSfuRoomControlOptions) {- if (!options.apiUrl || !options.apiKey || Buffer.byteLength(options.apiSecret) < 32) {- throw new Error("LiveKit RoomService configuration is invalid");- }- if (- !Number.isSafeInteger(options.maxViewersPerRoom) ||- options.maxViewersPerRoom < 1 ||- options.maxViewersPerRoom > MAX_VIEWERS_PER_ROOM_LIMIT- ) {- throw new Error("LiveKit viewer limit is invalid");- }- this.maxParticipants = options.maxViewersPerRoom + 1;- this.roomService =- options.roomService ??- new RoomServiceClient(- options.apiUrl,- options.apiKey,- options.apiSecret,- {- requestTimeout: ROOM_SERVICE_TIMEOUT_SECONDS,- failover: false,- },- );- }-- async initialize(): Promise<void> {- const rooms = await this.roomService.listRooms();- if (rooms.some((room) => !isManagedSfuRoomName(room.name))) {- throw new Error("Dedicated LiveKit instance contains a foreign room");- }- for (const room of rooms) {- await this.deleteRoomByName(room.name);- }- if ((await this.roomService.listRooms()).length !== 0) {- throw new Error("Dedicated LiveKit instance is not empty after startup drain");- }- }-- createRoom(fence: SfuResourceFence): Promise<void> {- const roomName = managedSfuRoomName(fence);- return this.serialize(roomName, async () => {- if ((await this.roomService.listRooms([roomName])).length !== 0) {- throw new Error("Managed LiveKit room already exists");- }- await this.roomService.createRoom({- name: roomName,- maxParticipants: this.maxParticipants,- });- const rooms = await this.roomService.listRooms([roomName]);- if (rooms.length !== 1 || rooms[0]?.name !== roomName) {- throw new Error("Managed LiveKit room creation was not confirmed");- }- });- }-- deleteRoom(fence: SfuResourceFence): Promise<void> {- const roomName = managedSfuRoomName(fence);- return this.serialize(roomName, async () => {- await this.deleteRoomByName(roomName);- if ((await this.roomService.listRooms([roomName])).length !== 0) {- throw new Error("Managed LiveKit room deletion was not confirmed");- }- });- }-- drainSubscription(fence: SfuSubscriptionFence): Promise<void> {- const roomName = managedSfuRoomName(fence);- const identity = managedSfuViewerIdentity(fence.viewerPeerId);- return this.serialize(roomName, async () => {- try {- await this.roomService.removeParticipant(roomName, identity);- } catch (error) {- if (!isNotFound(error)) {- throw error;- }- }- if (await this.participantExists(roomName, identity)) {- throw new Error("Managed LiveKit participant removal was not confirmed");- }- });- }-- hostParticipantExists(fence: SfuResourceFence): Promise<boolean> {- const roomName = managedSfuRoomName(fence);- return this.serialize(roomName, () =>- this.participantExists(roomName, "host"),- );- }-- private async deleteRoomByName(roomName: string): Promise<void> {- try {- await this.roomService.deleteRoom(roomName);- } catch (error) {- if (!isNotFound(error)) {- throw error;- }- }- }-- private async participantExists(- roomName: string,- identity: string,- ): Promise<boolean> {- try {- return (await this.roomService.listParticipants(roomName)).some(- (participant) => participant.identity === identity,- );- } catch (error) {- if (isNotFound(error)) {- return false;- }- throw error;- }- }-- private serialize<Result>(- roomName: string,- operation: () => Promise<Result>,- ): Promise<Result> {- const previous = this.roomOperations.get(roomName) ?? Promise.resolve();- const result = previous.catch(() => undefined).then(operation);- const tail = result.then(- () => undefined,- () => undefined,- );- this.roomOperations.set(roomName, tail);- void tail.then(() => {- if (this.roomOperations.get(roomName) === tail) {- this.roomOperations.delete(roomName);- }- });- return result;- }-}--function managedSfuViewerIdentity(peerId: string): string {- if (!OPAQUE_ID_PATTERN.test(peerId)) {- throw new Error("Managed LiveKit Viewer identity is invalid");- }- return `viewer:${peerId}`;-}--function isNotFound(error: unknown): boolean {- return (- error instanceof ServerError &&- (error.status === 404 || error.code === "not_found")- );-}diff --git a/src/server/signaling.ts b/src/server/signaling.tsdeleted file mode 100644index 798f2bcf..00000000--- a/src/server/signaling.ts+++ /dev/null@@ -1,2234 +0,0 @@-import { randomBytes } from "node:crypto";-import type { IncomingMessage, Server as HttpServer } from "node:http";-import type { Duplex } from "node:stream";--import WebSocket, { WebSocketServer } from "ws";--import {- DEFAULT_HOST_DISPLAY_NAME_PREFIX,- DEFAULT_VIEWER_DISPLAY_NAME,- DEFAULT_QUALITY_SETTINGS,- DEFAULT_ROUTE_POLICY,- MAX_SIGNAL_BYTES,- MAX_VIEWER_QUALITY_EVIDENCE_BYTES,- SIGNAL_CLOSE_CODES,- SIGNALING_PROTOCOL,- VIEWER_QUALITY_EVIDENCE_INTERVAL_MS,- decodeClientMessage,- type CodeEntryPolicy,- type ClientMessage,- type QualitySettings,- type RoutePolicy,- type RoomAccessUpdateRequest,- type RoomAccessUpdateResponse,- type Role,- type ServerMessage,- type ParticipantPresenceEntry,-} from "../shared/protocol.js";-import { candidateSignalOrigin } from "../shared/nat-candidate.js";-import { assertEndpointMediaCopyCapacity } from "../shared/media-copy-accounting.js";-import {- RoomStore,- RoomStoreError,- type ClosedRoom,- type ConnectedPeer,- type CreatedRoom,- type ViewerGrantUpdate,-} from "./room-store.js";-import {- HybridMediaRouter,- type SfuFallbackOptions,-} from "./hybrid-media-router.js";-import { createIceConfig, type IceConfigOptions } from "./ice.js";--type ErrorCode = Extract<ServerMessage, { type: "error" }>["code"];--const MAX_BUFFERED_SIGNAL_BYTES = 256 * 1024;-const DEFAULT_MAX_SIGNAL_CONNECTIONS = 2_048;-const DEFAULT_MAX_UNAUTHENTICATED_CONNECTIONS = 256;-const MIN_SIGNALING_CHALLENGE_INTERVAL_MS = 1_000;-const SERVICE_RESTART_CLOSE_GRACE_MS = 1_000;--interface AuthenticatedSession {- roomId: string;- role: Role;- peerId: string;- shareGeneration: string | null;- displayName: string | null;- viewerPresence: boolean;-}--interface SocketState {- sessionId: string;- alive: boolean;- authenticationTimer: NodeJS.Timeout;- siteAccessAuthenticated: boolean;- revoked?: boolean;- authenticating?: boolean;- lastSignalingChallengeAtMs?: number;- authenticated?: AuthenticatedSession;-}--interface ViewerQualityEvidenceGate {- viewerSessionId: string;- upstreamKind: "peer" | "sfu";- upstreamPeerId: string | null;- connectionId: string;- presentationEpoch: number;- sequence: number;-}--interface SenderQualityRateWindow {- startedAtMs: number;- count: number;-}--function configuredRoutePolicy(- policy: RoutePolicy,- natPredictionEnabled: boolean,-): RoutePolicy {- return {- ...policy,- natPrediction: natPredictionEnabled && policy.natPrediction,- };-}--export interface SignalingOptions {- server: HttpServer;- roomStore: RoomStore;- peerAssistedMedia: boolean;- endpointMediaCopyCapacity: number;- sfuFallback?: SfuFallbackOptions;- ice: IceConfigOptions;- allowedOrigins: ReadonlySet<string>;- siteAccessAtUpgrade: (request: IncomingMessage) => boolean;- publicBaseUrl: URL;- now?: () => number;- authenticationTimeoutMs?: number;- viewerDisconnectGraceMs?: number;- heartbeatIntervalMs?: number;- cleanupIntervalMs?: number;- passThroughUnknownUpgrades?: boolean;- maxConnections?: number;- maxUnauthenticatedConnections?: number;-}--export class SignalingServer {- private readonly webSocketServer = new WebSocketServer({- noServer: true,- maxPayload: MAX_SIGNAL_BYTES,- perMessageDeflate: false,- });- private readonly socketStates = new Map<WebSocket, SocketState>();- private readonly socketsBySessionId = new Map<string, WebSocket>();- private readonly viewerGraceTimers = new Map<string, NodeJS.Timeout>();- private readonly connectionIdsByViewer = new Map<string, string>();- private readonly ordinaryReadyConnectionIdsByViewer = new Map<- string,- string- >();- private readonly viewerQualityEvidenceGates = new Map<- string,- ViewerQualityEvidenceGate- >();- private readonly viewerQualityEvidenceAttemptAtMs = new Map<string, number>();- private readonly senderQualityRateBySession = new Map<- string,- SenderQualityRateWindow- >();- private readonly qualitySettingsByRoom = new Map<string, QualitySettings>();- private readonly routePolicyByRoom = new Map<string, RoutePolicy>();- private readonly shareGenerationsByRoom = new Map<string, string>();- private readonly pausedShareGenerationsByRoom = new Map<string, string>();- private readonly deferredViewerPresenceRooms = new Set<string>();- private readonly ordinaryActiveHostChildrenByRoom = new Map<- string,- Set<string>- >();- private readonly hybridMediaRouter?: HybridMediaRouter;- private readonly now: () => number;- private readonly authenticationTimeoutMs: number;- private readonly viewerDisconnectGraceMs: number;- private readonly heartbeatTimer: NodeJS.Timeout;- private readonly cleanupTimer: NodeJS.Timeout;- private readonly upgradeHandler: Parameters<HttpServer["on"]>[1];- private readonly maxConnections: number;- private readonly maxUnauthenticatedConnections: number;- private unauthenticatedConnections = 0;- private closing = false;-- constructor(private readonly options: SignalingOptions) {- assertEndpointMediaCopyCapacity(options.endpointMediaCopyCapacity);- this.now = options.now ?? Date.now;- this.authenticationTimeoutMs = options.authenticationTimeoutMs ?? 5_000;- this.viewerDisconnectGraceMs = options.viewerDisconnectGraceMs ?? 5_000;- this.maxConnections = options.maxConnections ?? DEFAULT_MAX_SIGNAL_CONNECTIONS;- this.maxUnauthenticatedConnections =- options.maxUnauthenticatedConnections ??- DEFAULT_MAX_UNAUTHENTICATED_CONNECTIONS;- if (- !Number.isSafeInteger(this.maxConnections) ||- this.maxConnections <= 0 ||- !Number.isSafeInteger(this.maxUnauthenticatedConnections) ||- this.maxUnauthenticatedConnections <= 0 ||- this.maxUnauthenticatedConnections > this.maxConnections- ) {- throw new Error("WebSocket connection limits are invalid");- }- if (options.sfuFallback && !options.peerAssistedMedia) {- throw new Error("SFU fallback requires peer-assisted media");- }- if (options.peerAssistedMedia) {- this.hybridMediaRouter = new HybridMediaRouter({- roomStore: options.roomStore,- endpointMediaCopyCapacity: options.endpointMediaCopyCapacity,- sfuFallback: options.sfuFallback,- sendToSession: (sessionId, message) =>- this.sendToSession(sessionId, message),- getConnectionId: (roomId, viewerPeerId) =>- this.connectionIdsByViewer.get(- viewerConnectionKey(roomId, viewerPeerId),- ),- setConnectionId: (roomId, viewerPeerId, connectionId) =>- this.setViewerConnectionId(roomId, viewerPeerId, connectionId),- deleteConnectionId: (roomId, viewerPeerId) =>- this.deleteViewerConnectionId(roomId, viewerPeerId),- getShareGeneration: (roomId) => this.shareGenerationsByRoom.get(roomId),- onRoutesChanged: (roomId) => this.sendViewerPresence(roomId),- now: this.now,- });- }-- this.upgradeHandler = (request, socket, head) => {- let requestUrl: URL;- try {- requestUrl = new URL(request.url ?? "/", "http://localhost");- } catch {- rejectUpgrade(socket, 400, "Bad Request");- return;- }- if (requestUrl.pathname !== "/signal" || requestUrl.search !== "") {- if (!options.passThroughUnknownUpgrades) {- rejectUpgrade(socket, 404, "Not Found");- }- return;- }- if (this.closing) {- rejectUpgrade(socket, 503, "Service Unavailable");- return;- }- if (!this.isAllowedOrigin(request.headers.origin)) {- rejectUpgrade(socket, 403, "Forbidden");- return;- }- if (!this.hasConnectionCapacity()) {- rejectUpgrade(socket, 503, "Service Unavailable");- return;- }- // No asynchronous verifyClient hook is installed: handleUpgrade emits- // connection synchronously, so accept() counts this slot before another- // upgrade event can observe the limit.- this.webSocketServer.handleUpgrade(request, socket, head, (webSocket) => {- this.webSocketServer.emit("connection", webSocket, request);- });- };- options.server.on("upgrade", this.upgradeHandler);- this.webSocketServer.on("connection", (socket, request) =>- this.accept(socket, options.siteAccessAtUpgrade(request)),- );-- this.heartbeatTimer = setInterval(- () => this.heartbeat(),- options.heartbeatIntervalMs ?? 30_000,- );- this.cleanupTimer = setInterval(- () => this.expireRooms(),- options.cleanupIntervalMs ?? 30_000,- );- this.heartbeatTimer.unref();- this.cleanupTimer.unref();- }-- async close(): Promise<void> {- this.closing = true;- this.options.server.off("upgrade", this.upgradeHandler);- clearInterval(this.heartbeatTimer);- clearInterval(this.cleanupTimer);- for (const timer of this.viewerGraceTimers.values()) {- clearTimeout(timer);- }- this.viewerGraceTimers.clear();- for (const state of this.socketStates.values()) {- clearTimeout(state.authenticationTimer);- }- const closed = new Promise<void>((resolve) => {- this.webSocketServer.close(() => resolve());- });- for (const socket of this.webSocketServer.clients) {- socket.close(SIGNAL_CLOSE_CODES.serviceRestart, "Service restart");- }- const forceCloseTimer = setTimeout(() => {- for (const socket of this.webSocketServer.clients) {- socket.terminate();- }- }, SERVICE_RESTART_CLOSE_GRACE_MS);- forceCloseTimer.unref();- let routeCloseError: unknown;- try {- await this.hybridMediaRouter?.close();- } catch (error) {- routeCloseError = error;- }- this.viewerQualityEvidenceGates.clear();- this.viewerQualityEvidenceAttemptAtMs.clear();- this.senderQualityRateBySession.clear();- this.routePolicyByRoom.clear();- this.shareGenerationsByRoom.clear();- this.pausedShareGenerationsByRoom.clear();- this.ordinaryActiveHostChildrenByRoom.clear();- this.ordinaryReadyConnectionIdsByViewer.clear();- await closed;- clearTimeout(forceCloseTimer);- if (routeCloseError) {- throw routeCloseError;- }- }-- endAllRooms(): void {- for (const closed of this.options.roomStore.abandonAllRooms()) {- this.closeRoom(closed);- }- }-- async updateRoomAccess(- roomId: string,- hostToken: string,- request: RoomAccessUpdateRequest,- ): Promise<RoomAccessUpdateResponse> {- switch (request.action) {- case "set-code-entry-policy": {- const update = this.options.roomStore.setCodeEntryPolicy(- roomId,- request.policy,- hostToken,- );- return {- type: "code-entry-policy-updated",- codeEntryPolicy: update.codeEntryPolicy,- viewerPasswordEnabled: update.viewerPasswordEnabled,- };- }- case "set-viewer-password":- return {- type: "viewer-password-updated",- enabled: await this.options.roomStore.setViewerPassword(- roomId,- request.password,- hostToken,- ),- };- case "rotate-viewer-grant":- case "revoke-viewer-grant": {- const action =- request.action === "rotate-viewer-grant" ? "rotate" : "revoke";- const update = this.options.roomStore.setViewerGrant(- roomId,- action,- hostToken,- );- this.revokeGrantViewers(roomId, update);- return {- type: "viewer-grant-updated",- viewerAuthorizationGeneration: update.viewerAuthorizationGeneration,- inviteUrl:- action === "revoke"- ? null- : this.viewerInviteUrl(roomId, update.viewerGrant),- };- }- }- }-- async replaceRoom(- roomId: string,- hostToken: string,- codeEntryPolicy: CodeEntryPolicy,- roomPassword: string | null,- ): Promise<CreatedRoom> {- const replacement = await this.options.roomStore.replaceRoom(- roomId,- hostToken,- codeEntryPolicy,- roomPassword,- );- this.closeRoom(replacement.closed);- return replacement.created;- }-- private accept(socket: WebSocket, siteAccessAuthenticated: boolean): void {- if (!this.hasConnectionCapacity()) {- socket.terminate();- return;- }-- const sessionId = randomBytes(16).toString("base64url");- const authenticationTimer = setTimeout(() => {- this.sendError(socket, "AUTH_REQUIRED", "Authentication timed out");- socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication required");- }, this.authenticationTimeoutMs);- authenticationTimer.unref();-- const state: SocketState = {- sessionId,- alive: true,- authenticationTimer,- siteAccessAuthenticated,- };- this.socketStates.set(socket, state);- this.socketsBySessionId.set(sessionId, socket);- this.unauthenticatedConnections += 1;-- socket.on("pong", () => {- state.alive = true;- });- socket.on("message", (data, isBinary) => {- if (isBinary) {- this.rejectInvalidMessage(socket);- return;- }- this.handleMessage(socket, data.toString());- });- socket.on("close", () => this.handleDisconnect(socket));- socket.on("error", () => {- // The close handler owns cleanup. Never log signaling payloads or tokens.- });- }-- private handleMessage(socket: WebSocket, encoded: string): void {- const state = this.socketStates.get(socket);- if (!state || this.closing) {- return;- }- if (state.revoked) {- return;- }-- let message: ClientMessage;- try {- message = decodeClientMessage(encoded);- } catch {- this.rejectInvalidMessage(socket);- return;- }- if (- message.type === "viewer-quality-evidence" &&- Buffer.byteLength(encoded, "utf8") >- MAX_VIEWER_QUALITY_EVIDENCE_BYTES- ) {- this.rejectInvalidMessage(socket);- return;- }-- if (!state.authenticated) {- if (message.type !== "authenticate") {- this.sendError(socket, "AUTH_REQUIRED", "Authenticate before sending messages");- socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication required");- return;- }- if (state.authenticating) {- this.rejectInvalidMessage(socket);- return;- }- state.authenticating = true;- void this.authenticate(socket, state, message).finally(() => {- if (this.socketStates.get(socket) === state) {- state.authenticating = false;- }- });- return;- }- if (message.type === "authenticate") {- this.sendError(socket, "FORBIDDEN", "Session is already authenticated");- return;- }-- if (!this.isCurrentSession(state)) {- socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Session replaced");- return;- }-- this.handleAuthenticatedMessage(socket, state.authenticated, message);- }-- private async authenticate(- socket: WebSocket,- state: SocketState,- message: Extract<ClientMessage, { type: "authenticate" }>,- ): Promise<void> {- if (message.role === "host" && !state.siteAccessAuthenticated) {- this.sendError(socket, "AUTH_REQUIRED", "Site access is required");- socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication failed");- return;- }- if (- message.role === "viewer" &&- !state.siteAccessAuthenticated &&- (!message.viewerGrant ||- !this.options.roomStore.viewerGrantMayEnter(- message.roomId,- message.viewerGrant,- ))- ) {- this.sendError(- socket,- "INVALID_TOKEN",- authenticationErrorMessage("INVALID_TOKEN"),- );- socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication failed");- return;- }-- let participant;- try {- if (- message.role === "viewer" &&- !message.viewerGrant &&- message.viewerPassword !== undefined- ) {- participant = await this.options.roomStore.connectViewerWithPassword(- {- roomId: message.roomId,- password: message.viewerPassword,- clientId: message.clientId,- sessionId: state.sessionId,- },- () =>- !this.closing &&- this.socketStates.get(socket) === state &&- !state.revoked &&- !state.authenticated &&- socket.readyState === WebSocket.OPEN,- );- } else {- participant = this.options.roomStore.connectParticipant(- message.role === "host"- ? {- roomId: message.roomId,- role: "host",- token: message.token,- clientId: message.clientId,- sessionId: state.sessionId,- }- : {- roomId: message.roomId,- role: "viewer",- ...(message.viewerGrant- ? { viewerGrant: message.viewerGrant }- : {}),- clientId: message.clientId,- sessionId: state.sessionId,- },- );- }- } catch (error) {- if (this.socketStates.get(socket) !== state || state.revoked) {- return;- }- if (!(error instanceof RoomStoreError)) {- console.error("Signaling authentication failed unexpectedly");- }- const code = authenticationErrorCode(message, error);- this.sendError(socket, code, authenticationErrorMessage(code));- socket.close(SIGNAL_CLOSE_CODES.authenticationFailed, "Authentication failed");- return;- }-- if (- this.closing ||- this.socketStates.get(socket) !== state ||- state.revoked ||- socket.readyState !== WebSocket.OPEN- ) {- this.options.roomStore.disconnectParticipant(- participant.roomId,- participant.peerId,- state.sessionId,- );- return;- }-- clearTimeout(state.authenticationTimer);- this.unauthenticatedConnections -= 1;- let shareGeneration: string | null = null;- if (participant.role === "host" && message.role === "host") {- const currentGeneration = this.shareGenerationsByRoom.get(- participant.roomId,- );- shareGeneration =- message.shareGeneration ?? currentGeneration ?? state.sessionId;- const sameShareWasAuthoritativelyPaused =- currentGeneration === shareGeneration &&- this.pausedShareGenerationsByRoom.get(participant.roomId) ===- shareGeneration;- if (- currentGeneration !== undefined &&- currentGeneration !== shareGeneration- ) {- this.stopSharing(participant.roomId);- }- if (- message.shareGeneration !== undefined &&- (currentGeneration !== shareGeneration ||- !this.qualitySettingsByRoom.has(participant.roomId))- ) {- const initialQualitySettings =- message.qualitySettings ?? DEFAULT_QUALITY_SETTINGS;- this.qualitySettingsByRoom.set(participant.roomId, {- ...initialQualitySettings,- });- for (const viewer of this.options.roomStore.getConnectedViewers(- participant.roomId,- )) {- this.sendToSession(viewer.sessionId, {- type: "quality-settings",- qualitySettings: initialQualitySettings,- });- }- }- if (- currentGeneration !== shareGeneration ||- !this.routePolicyByRoom.has(participant.roomId)- ) {- const routePolicy = configuredRoutePolicy(- message.routePolicy ?? DEFAULT_ROUTE_POLICY,- this.options.ice.natPredictionEnabled,- );- this.routePolicyByRoom.set(participant.roomId, routePolicy);- for (const viewer of this.options.roomStore.getConnectedViewers(- participant.roomId,- )) {- this.sendToSession(viewer.sessionId, {- type: "route-policy",- shareGeneration,- routePolicy,- ...(this.options.sfuFallback && !routePolicy.peerOnly- ? { sfuStandbyUrl: this.options.sfuFallback.url }- : {}),- });- }- }- this.shareGenerationsByRoom.set(participant.roomId, shareGeneration);- if (- message.sharingPaused === true ||- sameShareWasAuthoritativelyPaused- ) {- this.pausedShareGenerationsByRoom.set(- participant.roomId,- shareGeneration,- );- } else {- this.pausedShareGenerationsByRoom.delete(participant.roomId);- }- }- state.authenticated = {- roomId: participant.roomId,- role: participant.role,- peerId: participant.peerId,- shareGeneration,- displayName:- message.role === "host"- ? message.viewerPresence === true- ? (message.displayName ?? DEFAULT_HOST_DISPLAY_NAME_PREFIX)- : null- : (message.displayName ?? DEFAULT_VIEWER_DISPLAY_NAME),- viewerPresence: message.viewerPresence === true,- };- if (participant.role === "viewer") {- const viewerKey = viewerConnectionKey(- participant.roomId,- participant.peerId,- );- this.viewerQualityEvidenceGates.delete(viewerKey);- this.viewerQualityEvidenceAttemptAtMs.delete(viewerKey);- }- this.clearViewerGrace(participant.roomId, participant.peerId);- const routeParticipant = {- roomId: participant.roomId,- role: participant.role,- peerId: participant.peerId,- sessionId: state.sessionId,- ...(participant.role === "host"- ? {- routePolicy:- this.routePolicyByRoom.get(participant.roomId) ??- DEFAULT_ROUTE_POLICY,- }- : {}),- };- let hybridState;- try {- hybridState = this.isHybridMediaEnabled()- ? this.hybridMediaRouter!.connectParticipant(routeParticipant)- : undefined;- } catch {- console.error("Media router did not assign an authenticated participant");- this.sendError(socket, "SERVER_ERROR", "Media assignment failed");- socket.close(1011, "Media assignment failed");- return;- }- const connectionId =- participant.role === "viewer"- ? (this.connectionIdsByViewer.get(- viewerConnectionKey(participant.roomId, participant.peerId),- ) ?? null)- : null;- const connectedViewers =- participant.role === "host"- ? this.options.roomStore.getConnectedViewers(participant.roomId)- : [];- if (!this.isHybridMediaEnabled()) {- this.fillOrdinaryHostChildren(participant.roomId);- }- const routePolicy =- this.routePolicyByRoom.get(participant.roomId) ?? DEFAULT_ROUTE_POLICY;- const hasRoutePolicy = this.routePolicyByRoom.has(participant.roomId);-- const authenticatedMessageBase = {- type: "authenticated" as const,- protocol: SIGNALING_PROTOCOL as typeof SIGNALING_PROTOCOL,- peerId: participant.peerId,- roomExpiresAt: participant.expiresAt,- maxViewers: this.options.roomStore.maxViewersPerRoom,- endpointMediaCopyCapacity: this.options.endpointMediaCopyCapacity,- hostOnline: participant.hostOnline,- ...(participant.role === "viewer"- ? {- hostPaused:- participant.hostOnline &&- this.pausedShareGenerationsByRoom.get(participant.roomId) ===- this.shareGenerationsByRoom.get(participant.roomId),- }- : {}),- connectionId,- viewerPeerIds:- participant.role === "host" && !this.isHybridMediaEnabled()- ? [...this.ordinaryHostChildPeerIds(participant.roomId)]- : [...participant.viewerPeerIds],- iceConfig: this.iceConfig(),- routePolicy,- codeEntryPolicy: participant.codeEntryPolicy,- viewerAuthorizationGeneration:- participant.viewerAuthorizationGeneration,- };- const authenticatedMessage: Extract<- ServerMessage,- { type: "authenticated" }- > =- participant.role === "host"- ? {- ...authenticatedMessageBase,- role: "host" as const,- viewerPasswordEnabled: participant.viewerPasswordEnabled,- }- : {- ...authenticatedMessageBase,- role: "viewer" as const,- };- if (hybridState) {- this.send(socket, {- ...authenticatedMessage,- mediaMode: "peer-assisted",- shareGeneration:- this.shareGenerationsByRoom.get(participant.roomId) ?? null,- routeRevision: hybridState.routeRevision,- routeAssignment: hybridState.routeAssignment,- qualitySettings:- this.qualitySettingsByRoom.get(participant.roomId) ??- DEFAULT_QUALITY_SETTINGS,- ...(this.options.sfuFallback && hasRoutePolicy && !routePolicy.peerOnly- ? { sfuStandbyUrl: this.options.sfuFallback.url }- : {}),- });- } else {- this.send(socket, authenticatedMessage);- }- if (participant.replacedSessionId) {- const replaced = this.socketsBySessionId.get(participant.replacedSessionId);- if (replaced && replaced !== socket) {- replaced.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Session replaced");- }- }-- if (hybridState) {- if (participant.role === "host") {- this.hybridMediaRouter!.setPaused(- participant.roomId,- this.pausedShareGenerationsByRoom.get(participant.roomId) ===- shareGeneration,- );- }- this.hybridMediaRouter!.completeAuthentication(- routeParticipant,- hybridState,- );- }-- if (participant.role === "host") {- if (- shareGeneration !== null &&- this.pausedShareGenerationsByRoom.get(participant.roomId) ===- shareGeneration- ) {- this.sendToSession(state.sessionId, {- type: "pause-sharing-source",- shareGeneration,- });- }- }-- this.sendViewerPresence(participant.roomId);-- if (participant.role === "host") {- for (const viewer of connectedViewers) {- this.sendToSession(viewer.sessionId, {- type: "host-status",- online: true,- paused:- this.pausedShareGenerationsByRoom.get(participant.roomId) ===- shareGeneration,- });- if (- !this.isHybridMediaEnabled() &&- !this.isOrdinaryHostChild(participant.roomId, viewer.peerId)- ) {- this.send(socket, { type: "peer-waiting", peerId: viewer.peerId });- }- }- if (!this.isHybridMediaEnabled()) {- for (const viewer of connectedViewers) {- if (this.isOrdinaryHostChild(participant.roomId, viewer.peerId)) {- this.send(socket, { type: "peer-joined", peerId: viewer.peerId });- }- }- }- return;- }-- if (this.isHybridMediaEnabled()) {- return;- }-- const host = this.options.roomStore.getConnectedHost(participant.roomId);- if (!host) {- return;- }- // Re-authentication is also a presence assertion. The host treats this- // event idempotently, which closes races where its local peer was rebuilt- // while the viewer retained the same server-side connection ID.- this.sendToSession(host.sessionId, {- type: this.isOrdinaryHostChild(participant.roomId, participant.peerId)- ? "peer-joined"- : "peer-waiting",- peerId: participant.peerId,- });- }-- private handleAuthenticatedMessage(- socket: WebSocket,- authenticated: AuthenticatedSession,- message: Exclude<ClientMessage, { type: "authenticate" }>,- ): void {- switch (message.type) {- case "signaling-challenge": {- const state = this.socketStates.get(socket);- if (!state || state.authenticated !== authenticated) {- return;- }- const now = this.now();- if (state.lastSignalingChallengeAtMs !== undefined) {- const elapsedMs = now - state.lastSignalingChallengeAtMs;- if (elapsedMs < 0) {- state.lastSignalingChallengeAtMs = now;- return;- }- if (elapsedMs < MIN_SIGNALING_CHALLENGE_INTERVAL_MS) {- return;- }- }- state.lastSignalingChallengeAtMs = now;- this.send(socket, {- type: "signaling-challenge-response",- sequence: message.sequence,- });- return;- }- case "signal":- this.routeSignal(socket, authenticated, message);- return;- case "restart-request":- if (authenticated.role !== "viewer") {- this.sendError(socket, "FORBIDDEN", "Only viewers may request an ICE restart");- return;- }- if (this.isHybridMediaEnabled()) {- this.routePeerAssistedRestart(socket, authenticated, message);- return;- }- if (message.targetPeerId) {- this.sendError(socket, "FORBIDDEN", "P2P restart requests target the host implicitly");- return;- }- if (- !this.isOrdinaryHostChild(authenticated.roomId, authenticated.peerId)- ) {- this.sendError(socket, "FORBIDDEN", "Viewer has no active Host edge");- return;- }- this.routeToHost(socket, authenticated, {- type: "restart-request",- fromPeerId: authenticated.peerId,- connectionId: message.connectionId,- rebuild: message.rebuild,- });- return;- case "set-quality-settings":- if (- !this.isHybridMediaEnabled() ||- authenticated.role !== "host"- ) {- this.sendError(- socket,- "FORBIDDEN",- "Only a peer-assisted host may set quality settings",- );- return;- }- this.qualitySettingsByRoom.set(authenticated.roomId, {- ...message.qualitySettings,- });- for (const viewer of this.options.roomStore.getConnectedViewers(- authenticated.roomId,- )) {- this.sendToSession(viewer.sessionId, {- type: "quality-settings",- qualitySettings: message.qualitySettings,- });- }- return;- case "relay-capacity":- if (- !this.isHybridMediaEnabled() ||- authenticated.role !== "viewer"- ) {- this.sendError(- socket,- "FORBIDDEN",- "Only a peer-assisted viewer may advertise relay capacity",- );- return;- }- this.hybridMediaRouter!.setViewerRelayCapacity(- {- ...authenticated,- sessionId: this.socketStates.get(socket)!.sessionId,- },- message.downstreamEdges,- );- return;- case "route-ready":- if (!this.isHybridMediaEnabled()) {- this.sendError(socket, "FORBIDDEN", "Media routes are not enabled");- return;- }- this.hybridMediaRouter!.handleRouteReady(- {- ...authenticated,- sessionId: this.socketStates.get(socket)!.sessionId,- },- message,- );- return;- case "route-transport-connected":- if (!this.isHybridMediaEnabled()) {- this.sendError(socket, "FORBIDDEN", "Media routes are not enabled");- return;- }- this.hybridMediaRouter!.handleRouteTransportConnected(- {- ...authenticated,- sessionId: this.socketStates.get(socket)!.sessionId,- },- message,- );- return;- case "route-media-unavailable":- if (!this.isHybridMediaEnabled()) {- this.sendError(socket, "FORBIDDEN", "Media routes are not enabled");- return;- }- this.hybridMediaRouter!.handleRouteMediaUnavailable(- {- ...authenticated,- sessionId: this.socketStates.get(socket)!.sessionId,- },- message,- );- return;- case "route-failed":- if (!this.isHybridMediaEnabled()) {- this.sendError(socket, "FORBIDDEN", "Media routes are not enabled");- return;- }- this.hybridMediaRouter!.handleRouteFailed(- {- ...authenticated,- sessionId: this.socketStates.get(socket)!.sessionId,- },- message,- );- return;- case "refresh-sfu":- if (- !this.options.sfuFallback ||- !this.isHybridMediaEnabled()- ) {- this.sendError(socket, "FORBIDDEN", "SFU fallback is not enabled");- return;- }- this.hybridMediaRouter!.refreshSfu(- {- ...authenticated,- sessionId: this.socketStates.get(socket)!.sessionId,- },- message.revision,- );- return;- case "request-route-diagnostic":- if (authenticated.role !== "host") {- this.sendError(- socket,- "FORBIDDEN",- "Only the host may request route diagnostics",- );- return;- }- this.send(socket, {- type: "route-diagnostic-snapshot",- snapshot: this.hybridMediaRouter?.routeDiagnosticSnapshot(- authenticated.roomId,- ) ?? { children: [], operation: null },- });- return;- case "viewer-quality-evidence":- this.handleViewerQualityEvidence(socket, authenticated, message);- return;- case "sender-quality-evidence":- this.handleSenderQualityEvidence(socket, authenticated, message);- return;- case "sfu-publisher-quality-evidence":- this.handleSfuPublisherQualityEvidence(socket, authenticated, message);- return;- case "reset-sender-quality":- if (this.isHybridMediaEnabled()) {- const state = this.socketStates.get(socket);- if (state?.authenticated === authenticated) {- this.hybridMediaRouter!.resetSenderQuality({- roomId: authenticated.roomId,- role: authenticated.role,- peerId: authenticated.peerId,- sessionId: state.sessionId,- });- }- }- return;- case "set-display-name":- if (- authenticated.role === "host" &&- !authenticated.viewerPresence- ) {- this.sendError(- socket,- "FORBIDDEN",- "Display names require the Web presence capability",- );- return;- }- authenticated.displayName = message.displayName;- this.sendViewerPresence(authenticated.roomId);- return;- case "set-sharing-paused":- if (authenticated.role !== "host") {- this.sendError(socket, "FORBIDDEN", "只有当前分享者可以暂停分享");- return;- }- const pauseSocketState = this.socketStates.get(socket);- const connectedHost = this.options.roomStore.getConnectedHost(- authenticated.roomId,- );- if (- !pauseSocketState ||- connectedHost?.sessionId !== pauseSocketState.sessionId ||- authenticated.shareGeneration === null ||- this.shareGenerationsByRoom.get(authenticated.roomId) !==- authenticated.shareGeneration ||- message.shareGeneration !== authenticated.shareGeneration- ) {- socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Sharing generation replaced");- return;- }- if (message.paused) {- this.pausedShareGenerationsByRoom.set(- authenticated.roomId,- authenticated.shareGeneration,- );- } else {- this.pausedShareGenerationsByRoom.delete(authenticated.roomId);- }- if (this.isHybridMediaEnabled()) {- this.hybridMediaRouter!.setPaused(- authenticated.roomId,- message.paused,- );- }- this.broadcastHostStatus(- authenticated.roomId,- true,- message.paused,- );- return;- case "stop-sharing":- if (authenticated.role !== "host") {- this.sendError(socket, "FORBIDDEN", "只有当前分享者可以停止分享");- return;- }- if (- authenticated.shareGeneration === null ||- this.shareGenerationsByRoom.get(authenticated.roomId) !==- authenticated.shareGeneration ||- (message.shareGeneration !== undefined &&- message.shareGeneration !== authenticated.shareGeneration)- ) {- socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Sharing generation replaced");- return;- }- const state = this.socketStates.get(socket);- if (state?.authenticated === authenticated) {- this.options.roomStore.disconnectParticipant(- authenticated.roomId,- authenticated.peerId,- state.sessionId,- );- this.sendViewerPresence(authenticated.roomId);- }- this.stopSharing(authenticated.roomId);- socket.close(1000, "Sharing stopped");- return;- case "abandon-room":- if (authenticated.role !== "host") {- this.sendError(socket, "FORBIDDEN", "Only the host may abandon the room");- return;- }- try {- this.abandonRoom(authenticated.roomId);- } catch (error) {- console.error("Room abandonment failed", error);- this.sendError(socket, "SERVER_ERROR", "Room could not be abandoned");- }- return;- }- }-- private revokeGrantViewers(- roomId: string,- update: ViewerGrantUpdate,- ): void {- if (update.revokedViewers.length > 0) {- this.deferredViewerPresenceRooms.add(roomId);- try {- for (const viewer of update.revokedViewers) {- this.clearViewerState(roomId, viewer.peerId);- if (!viewer.sessionId) {- continue;- }- this.sendToSession(viewer.sessionId, {- type: "viewer-grant-revoked",- viewerAuthorizationGeneration:- update.previousViewerAuthorizationGeneration,- });- }-- if (this.isHybridMediaEnabled()) {- for (const viewer of update.revokedViewers) {- this.hybridMediaRouter!.removeViewer(- roomId,- viewer.peerId,- );- }- } else {- const host = this.options.roomStore.getConnectedHost(roomId);- const promotedPeerIds = this.fillOrdinaryHostChildren(roomId);- if (host) {- for (const viewer of update.revokedViewers) {- this.sendToSession(host.sessionId, {- type: "peer-left",- peerId: viewer.peerId,- });- }- for (const peerId of promotedPeerIds) {- this.sendToSession(host.sessionId, {- type: "peer-joined",- peerId,- });- }- }- }-- for (const viewer of update.revokedViewers) {- if (!viewer.sessionId) {- continue;- }- this.closeRevokedViewerSession(viewer.sessionId);- }- } finally {- this.deferredViewerPresenceRooms.delete(roomId);- }- this.sendViewerPresence(roomId);- }- }-- private handleViewerQualityEvidence(- socket: WebSocket,- source: AuthenticatedSession,- message: Extract<ClientMessage, { type: "viewer-quality-evidence" }>,- ): void {- if (source.role !== "viewer") {- return;- }- const viewerState = this.socketStates.get(socket);- if (!viewerState || viewerState.authenticated !== source) {- return;- }- const connectedViewer = this.options.roomStore.getConnectedViewer(- source.roomId,- source.peerId,- );- if (connectedViewer?.sessionId !== viewerState.sessionId) {- return;- }-- const gateKey = viewerConnectionKey(source.roomId, source.peerId);- const now = this.now();- const previousAttemptAtMs =- this.viewerQualityEvidenceAttemptAtMs.get(gateKey);- if (- previousAttemptAtMs !== undefined &&- now - previousAttemptAtMs < VIEWER_QUALITY_EVIDENCE_INTERVAL_MS- ) {- return;- }- this.viewerQualityEvidenceAttemptAtMs.set(gateKey, now);-- const connectionId = this.connectionIdsByViewer.get(gateKey);- if (!connectionId || message.guard.connectionId !== connectionId) {- return;- }-- const host = this.options.roomStore.getConnectedHost(source.roomId);- let routeRevision = 0;- let upstream: { kind: "peer"; peerId: string } | { kind: "sfu" };- let recipient: ConnectedPeer | undefined;- if (this.isHybridMediaEnabled()) {- const edge = this.hybridMediaRouter?.resolveActiveViewerMediaEdge(- source.roomId,- source.peerId,- );- if (!edge || edge.connectionId !== connectionId) {- return;- }- routeRevision = edge.revision;- upstream = edge.upstream;- recipient =- upstream.kind === "peer"- ? this.connectedPeer(source.roomId, upstream.peerId)- : host;- } else {- if (!host) {- return;- }- upstream = { kind: "peer", peerId: host.peerId };- recipient = host;- }- if (- !recipient ||- message.guard.routeRevision !== routeRevision ||- (upstream.kind === "peer" && upstream.peerId === source.peerId)- ) {- return;- }-- const previous = this.viewerQualityEvidenceGates.get(gateKey);- const sameEdge =- previous?.viewerSessionId === viewerState.sessionId &&- previous.upstreamKind === upstream.kind &&- previous.upstreamPeerId ===- (upstream.kind === "peer" ? upstream.peerId : null) &&- previous.connectionId === connectionId;- if (- sameEdge &&- previous &&- (message.guard.presentationEpoch < previous.presentationEpoch ||- (message.guard.presentationEpoch === previous.presentationEpoch &&- message.sequence <= previous.sequence))- ) {- return;- }-- const forwarded: Extract<- ServerMessage,- { type: "viewer-quality-evidence" }- > = {- type: "viewer-quality-evidence" as const,- viewerPeerId: source.peerId,- upstream,- guard: {- connectionId,- routeRevision,- presentationEpoch: message.guard.presentationEpoch,- },- sequence: message.sequence,- windowMs: message.windowMs,- metrics: message.metrics,- };- const encoded = JSON.stringify(forwarded);- if (Buffer.byteLength(encoded, "utf8") > MAX_VIEWER_QUALITY_EVIDENCE_BYTES) {- return;- }- const qualityResult = this.isHybridMediaEnabled()- ? (this.hybridMediaRouter?.observeQualityEvidence({- roomId: source.roomId,- childPeerId: source.peerId,- childSessionId: viewerState.sessionId,- routeRevision,- connectionId,- upstream,- presentationEpoch: message.guard.presentationEpoch,- windowMs: message.windowMs,- metrics: message.metrics,- acceptedAtMs: now,- }) ?? "rejected")- : "accepted";- if (qualityResult === "rejected") {- return;- }- this.viewerQualityEvidenceGates.set(gateKey, {- viewerSessionId: viewerState.sessionId,- upstreamKind: upstream.kind,- upstreamPeerId: upstream.kind === "peer" ? upstream.peerId : null,- connectionId,- presentationEpoch: message.guard.presentationEpoch,- sequence: message.sequence,- });- this.sendEncodedToSession(recipient.sessionId, encoded);- if (!host || host.sessionId === recipient.sessionId) {- return;- }- const hostSocket = this.socketsBySessionId.get(host.sessionId);- const hostState = hostSocket- ? this.socketStates.get(hostSocket)?.authenticated- : undefined;- if (- hostState?.role === "host" &&- hostState.roomId === source.roomId &&- hostState.peerId === host.peerId &&- hostState.viewerPresence- ) {- this.sendEncodedToSession(host.sessionId, encoded);- }- }-- private handleSenderQualityEvidence(- socket: WebSocket,- source: AuthenticatedSession,- message: Extract<ClientMessage, { type: "sender-quality-evidence" }>,- ): void {- if (!this.isHybridMediaEnabled() || source.peerId === message.childPeerId) {- return;- }- const state = this.socketStates.get(socket);- if (!state || state.authenticated !== source) {- return;- }- const now = this.now();- if (!this.consumeSenderQualityBudget(state.sessionId, now)) {- return;- }- this.hybridMediaRouter!.observeSenderQualityEvidence(- {- roomId: source.roomId,- role: source.role,- peerId: source.peerId,- sessionId: state.sessionId,- },- message,- );- }-- private handleSfuPublisherQualityEvidence(- socket: WebSocket,- source: AuthenticatedSession,- message: Extract<- ClientMessage,- { type: "sfu-publisher-quality-evidence" }- >,- ): void {- if (!this.isHybridMediaEnabled() || source.role !== "host") {- return;- }- const state = this.socketStates.get(socket);- if (!state || state.authenticated !== source) {- return;- }- const now = this.now();- if (!this.consumeSenderQualityBudget(state.sessionId, now)) {- return;- }- this.hybridMediaRouter!.observeSfuPublisherQualityEvidence(- {- roomId: source.roomId,- role: source.role,- peerId: source.peerId,- sessionId: state.sessionId,- },- message,- );- }-- private consumeSenderQualityBudget(- sessionId: string,- nowMs: number,- ): boolean {- const maximumReports =- Math.min(this.options.endpointMediaCopyCapacity + 1, 3) * 2;- const current = this.senderQualityRateBySession.get(sessionId);- if (- !current ||- nowMs - current.startedAtMs >= VIEWER_QUALITY_EVIDENCE_INTERVAL_MS- ) {- this.senderQualityRateBySession.set(sessionId, {- startedAtMs: nowMs,- count: 1,- });- return true;- }- if (current.count >= maximumReports) {- return false;- }- current.count += 1;- return true;- }-- private routeSignal(- sourceSocket: WebSocket,- source: AuthenticatedSession,- message: Extract<ClientMessage, { type: "signal" }>,- ): void {- if (this.isHybridMediaEnabled()) {- this.routePeerAssistedSignal(sourceSocket, source, message);- return;- }-- const description =- message.payload.kind === "description" ? message.payload.description : undefined;-- if (source.role === "host") {- if (!message.targetPeerId || description?.type === "answer") {- this.sendError(sourceSocket, "FORBIDDEN", "Host signals must target one viewer");- return;- }- const viewer = this.options.roomStore.getConnectedViewer(- source.roomId,- message.targetPeerId,- );- if (!viewer) {- this.sendError(sourceSocket, "PEER_NOT_FOUND", "Viewer is not connected");- return;- }- if (!this.isOrdinaryHostChild(source.roomId, viewer.peerId)) {- this.sendError(sourceSocket, "FORBIDDEN", "Viewer has no active Host edge");- return;- }- if (description?.type === "offer") {- this.setViewerConnectionId(- source.roomId,- viewer.peerId,- message.payload.connectionId,- );- }- this.sendToSession(viewer.sessionId, {- type: "signal",- fromPeerId: source.peerId,- payload: message.payload,- });- return;- }-- if (message.targetPeerId || description?.type === "offer") {- this.sendError(sourceSocket, "FORBIDDEN", "Viewer signals may only reply to the host");- return;- }- if (!this.isOrdinaryHostChild(source.roomId, source.peerId)) {- this.sendError(sourceSocket, "FORBIDDEN", "Viewer has no active Host edge");- return;- }- this.routeToHost(sourceSocket, source, {- type: "signal",- fromPeerId: source.peerId,- payload: message.payload,- });- const connectionKey = viewerConnectionKey(source.roomId, source.peerId);- if (- description?.type === "answer" &&- this.connectionIdsByViewer.get(connectionKey) ===- message.payload.connectionId- ) {- this.ordinaryReadyConnectionIdsByViewer.set(- connectionKey,- message.payload.connectionId,- );- this.sendViewerPresence(source.roomId);- }- }-- private routePeerAssistedSignal(- sourceSocket: WebSocket,- source: AuthenticatedSession,- message: Extract<ClientMessage, { type: "signal" }>,- ): void {- const targetPeerId = message.targetPeerId;- if (!targetPeerId) {- this.sendError(- sourceSocket,- "FORBIDDEN",- "Peer-assisted signals must target an assigned peer",- );- return;- }- const parentToChild = this.hybridMediaRouter!.isActivePeerParentOf(- source.roomId,- source.peerId,- targetPeerId,- );- const childToParent = this.hybridMediaRouter!.isActivePeerParentOf(- source.roomId,- targetPeerId,- source.peerId,- );- const target = this.connectedPeer(source.roomId, targetPeerId);- if (!target) {- if (parentToChild || childToParent) {- return;- }- this.sendError(sourceSocket, "PEER_NOT_FOUND", "Target peer is not connected");- return;- }-- const description =- message.payload.kind === "description"- ? message.payload.description- : undefined;- const candidateAuthorized =- this.hybridMediaRouter!.peerSignalAuthorization({- roomId: source.roomId,- sourcePeerId: source.peerId,- sourceSessionId: this.socketStates.get(sourceSocket)?.sessionId ?? "",- targetPeerId: target.peerId,- targetSessionId: target.sessionId,- connectionId: message.payload.connectionId,- signalKind: message.payload.kind,- ...(description ? { descriptionType: description.type } : {}),- });- this.hybridMediaRouter!.debugPeerSignal({- roomId: source.roomId,- sourcePeerId: source.peerId,- targetPeerId: target.peerId,- signalKind: message.payload.kind,- ...(message.payload.kind === "candidate"- ? {- candidateOrigin: candidateSignalOrigin(- message.payload.candidate?.candidate ?? null,- ),- }- : {}),- ...(description ? { descriptionType: description.type } : {}),- authorization: candidateAuthorized,- });- const assignedEdgeAuthorized = description- ? description.type === "offer"- ? parentToChild- : childToParent- : parentToChild || childToParent;- const authorized = candidateAuthorized ?? assignedEdgeAuthorized;- if (!authorized) {- return;- }-- if (- description?.type === "offer" &&- candidateAuthorized !== "probe"- ) {- this.setViewerConnectionId(- source.roomId,- targetPeerId,- message.payload.connectionId,- );- }- this.sendToSession(target.sessionId, {- type: "signal",- fromPeerId: source.peerId,- payload: message.payload,- });- }-- private routePeerAssistedRestart(- sourceSocket: WebSocket,- source: AuthenticatedSession,- message: Extract<ClientMessage, { type: "restart-request" }>,- ): void {- const targetPeerId = message.targetPeerId;- if (- !targetPeerId ||- !this.hybridMediaRouter!.isActivePeerParentOf(- source.roomId,- targetPeerId,- source.peerId,- )- ) {- this.sendError(- sourceSocket,- "FORBIDDEN",- "Restart target is not the assigned media parent",- );- return;- }- const parent = this.connectedPeer(source.roomId, targetPeerId);- if (!parent) {- this.sendError(sourceSocket, "PEER_NOT_FOUND", "Media parent is not connected");- return;- }- this.sendToSession(parent.sessionId, {- type: "restart-request",- fromPeerId: source.peerId,- connectionId: message.connectionId,- rebuild: message.rebuild,- });- }-- private routeToHost(- sourceSocket: WebSocket,- source: AuthenticatedSession,- message: ServerMessage,- ): void {- const host = this.options.roomStore.getConnectedHost(source.roomId);- if (!host) {- this.sendError(sourceSocket, "PEER_NOT_FOUND", "Host is not connected");- return;- }- this.sendToSession(host.sessionId, message);- }-- private handleDisconnect(socket: WebSocket): void {- const state = this.socketStates.get(socket);- if (!state) {- return;- }- clearTimeout(state.authenticationTimer);- this.senderQualityRateBySession.delete(state.sessionId);- this.socketStates.delete(socket);- if (this.socketsBySessionId.get(state.sessionId) === socket) {- this.socketsBySessionId.delete(state.sessionId);- }- if (state.revoked) {- return;- }- if (!state.authenticated) {- this.unauthenticatedConnections -= 1;- return;- }- if (this.closing) {- return;- }-- const disconnected = this.options.roomStore.disconnectParticipant(- state.authenticated.roomId,- state.authenticated.peerId,- state.sessionId,- );- if (!disconnected) {- return;- }- if (this.isHybridMediaEnabled()) {- this.hybridMediaRouter!.disconnectParticipant(- disconnected.roomId,- disconnected.peerId,- state.sessionId,- );- }- if (disconnected.role === "host") {- this.broadcastHostStatus(disconnected.roomId, false, false);- this.sendViewerPresence(disconnected.roomId);- return;- }-- this.sendViewerPresence(disconnected.roomId);-- const key = viewerGraceKey(disconnected.roomId, disconnected.peerId);- const timer = setTimeout(() => {- this.viewerGraceTimers.delete(key);- if (- this.options.roomStore.removeDisconnectedViewer(- disconnected.roomId,- disconnected.peerId,- )- ) {- this.deleteViewerConnectionId(- disconnected.roomId,- disconnected.peerId,- );- if (this.isHybridMediaEnabled()) {- this.hybridMediaRouter!.removeViewer(- disconnected.roomId,- disconnected.peerId,- );- return;- }- this.releaseOrdinaryHostChild(disconnected.roomId, disconnected.peerId);- const promotedPeerIds = this.fillOrdinaryHostChildren(- disconnected.roomId,- );- const host = this.options.roomStore.getConnectedHost(disconnected.roomId);- if (host) {- this.sendToSession(host.sessionId, {- type: "peer-left",- peerId: disconnected.peerId,- });- for (const peerId of promotedPeerIds) {- this.sendToSession(host.sessionId, {- type: "peer-joined",- peerId,- });- }- }- if (promotedPeerIds.length > 0) {- this.sendViewerPresence(disconnected.roomId);- }- }- }, this.viewerDisconnectGraceMs);- timer.unref();- this.viewerGraceTimers.set(key, timer);- }-- private stopSharing(roomId: string): void {- this.qualitySettingsByRoom.delete(roomId);- this.routePolicyByRoom.delete(roomId);- this.pausedShareGenerationsByRoom.delete(roomId);- this.ordinaryActiveHostChildrenByRoom.delete(roomId);- this.clearRoomConnectionIds(roomId);- if (this.isHybridMediaEnabled()) {- this.hybridMediaRouter!.stopRoom(roomId);- }- for (const viewer of this.options.roomStore.getConnectedViewers(roomId)) {- this.sendToSession(viewer.sessionId, { type: "sharing-stopped" });- this.sendToSession(viewer.sessionId, {- type: "host-status",- online: false,- paused: false,- });- }- }-- private abandonRoom(roomId: string): void {- const abandoned = this.options.roomStore.abandonRoom(roomId);- if (!abandoned) {- return;- }- this.closeRoom(abandoned);- }-- private closeRoom(closed: ClosedRoom): void {- this.clearRoomGraceTimers(closed.roomId);- this.clearRoomConnectionIds(closed.roomId);- this.ordinaryActiveHostChildrenByRoom.delete(closed.roomId);- if (this.isHybridMediaEnabled()) {- this.hybridMediaRouter!.deleteRoom(closed.roomId);- }- this.qualitySettingsByRoom.delete(closed.roomId);- this.routePolicyByRoom.delete(closed.roomId);- this.shareGenerationsByRoom.delete(closed.roomId);- this.pausedShareGenerationsByRoom.delete(closed.roomId);- for (const sessionId of closed.sessionIds) {- const socket = this.socketsBySessionId.get(sessionId);- if (!socket) {- continue;- }- this.send(socket, { type: "room-closed", reason: "host-ended" });- socket.close(1000, "Room abandoned");- }- }-- private expireRooms(): void {- for (const expired of this.options.roomStore.expireRooms(this.now())) {- this.clearRoomGraceTimers(expired.roomId);- this.clearRoomConnectionIds(expired.roomId);- this.ordinaryActiveHostChildrenByRoom.delete(expired.roomId);- if (this.isHybridMediaEnabled()) {- this.hybridMediaRouter!.deleteRoom(expired.roomId);- }- this.qualitySettingsByRoom.delete(expired.roomId);- this.routePolicyByRoom.delete(expired.roomId);- this.shareGenerationsByRoom.delete(expired.roomId);- this.pausedShareGenerationsByRoom.delete(expired.roomId);- for (const sessionId of expired.sessionIds) {- const socket = this.socketsBySessionId.get(sessionId);- if (!socket) {- continue;- }- this.send(socket, { type: "room-closed", reason: "expired" });- socket.close(1000, "Room expired");- }- }- }-- private heartbeat(): void {- for (const [socket, state] of this.socketStates) {- if (!state.alive) {- socket.terminate();- continue;- }- state.alive = false;- socket.ping();- }- }-- private isCurrentSession(state: SocketState): boolean {- const authenticated = state.authenticated;- if (!authenticated) {- return false;- }- const current =- authenticated.role === "host"- ? this.options.roomStore.getConnectedHost(authenticated.roomId)- : this.options.roomStore.getConnectedViewer(- authenticated.roomId,- authenticated.peerId,- );- return current?.sessionId === state.sessionId;- }-- private isAllowedOrigin(origin: string | undefined): boolean {- if (!origin) {- return false;- }- try {- const parsed = new URL(origin);- return parsed.origin === origin && this.options.allowedOrigins.has(origin);- } catch {- return false;- }- }-- private isHybridMediaEnabled(): boolean {- return this.hybridMediaRouter !== undefined;- }-- private ordinaryHostChildPeerIds(roomId: string): readonly string[] {- const active = this.ordinaryActiveHostChildren(roomId);- return this.options.roomStore- .getViewerPeerIds(roomId)- .filter((peerId) => active.has(peerId));- }-- private isOrdinaryHostChild(roomId: string, peerId: string): boolean {- return this.ordinaryActiveHostChildren(roomId).has(peerId);- }-- private ordinaryActiveHostChildren(roomId: string): Set<string> {- let active = this.ordinaryActiveHostChildrenByRoom.get(roomId);- if (!active) {- active = new Set<string>();- this.ordinaryActiveHostChildrenByRoom.set(roomId, active);- return active;- }- const members = new Set(this.options.roomStore.getViewerPeerIds(roomId));- for (const peerId of active) {- if (!members.has(peerId)) {- active.delete(peerId);- }- }- return active;- }-- private fillOrdinaryHostChildren(roomId: string): string[] {- const active = this.ordinaryActiveHostChildren(roomId);- const promotedPeerIds: string[] = [];- for (const viewer of this.options.roomStore.getConnectedViewers(roomId)) {- if (active.size >= this.options.endpointMediaCopyCapacity) {- break;- }- if (active.has(viewer.peerId)) {- continue;- }- active.add(viewer.peerId);- promotedPeerIds.push(viewer.peerId);- }- return promotedPeerIds;- }-- private releaseOrdinaryHostChild(roomId: string, peerId: string): void {- const active = this.ordinaryActiveHostChildrenByRoom.get(roomId);- if (!active) {- return;- }- active.delete(peerId);- if (active.size === 0) {- this.ordinaryActiveHostChildrenByRoom.delete(roomId);- }- }-- private hasConnectionCapacity(): boolean {- return (- !this.closing &&- this.socketStates.size < this.maxConnections &&- this.unauthenticatedConnections < this.maxUnauthenticatedConnections- );- }-- private iceConfig() {- return createIceConfig(this.options.ice);- }-- private viewerInviteUrl(roomId: string, viewerGrant: string | null): string {- const inviteUrl = new URL(`/r/${roomId}`, this.options.publicBaseUrl);- if (viewerGrant) {- inviteUrl.hash = `v=${viewerGrant}`;- }- return inviteUrl.toString();- }-- private connectedPeer(roomId: string, peerId: string) {- const host = this.options.roomStore.getConnectedHost(roomId);- if (host?.peerId === peerId) {- return host;- }- return this.options.roomStore.getConnectedViewer(roomId, peerId);- }-- private sendViewerPresence(roomId: string): void {- if (this.deferredViewerPresenceRooms.has(roomId)) {- return;- }-- const connectedViewers = this.options.roomStore.getConnectedViewers(roomId);- const viewers: ParticipantPresenceEntry[] = [];- const host = this.options.roomStore.getConnectedHost(roomId);- const hostSocket = host- ? this.socketsBySessionId.get(host.sessionId)- : undefined;- const hostState = hostSocket- ? this.socketStates.get(hostSocket)?.authenticated- : undefined;- if (- host &&- hostSocket &&- hostState?.role === "host" &&- hostState.roomId === roomId &&- hostState.peerId === host.peerId &&- hostState.displayName !== null- ) {- viewers.push({- role: "host",- peerId: host.peerId,- displayName: hostState.displayName,- upstream: { kind: "none" },- });- }-- for (const viewer of connectedViewers) {- const viewerSocket = this.socketsBySessionId.get(viewer.sessionId);- const viewerState = viewerSocket- ? this.socketStates.get(viewerSocket)?.authenticated- : undefined;- if (- viewerState?.role !== "viewer" ||- viewerState.roomId !== roomId ||- viewerState.peerId !== viewer.peerId ||- viewerState.displayName === null- ) {- continue;- }- const upstream = this.isHybridMediaEnabled()- ? this.hybridMediaRouter!.getViewerRouteUpstream(roomId, viewer.peerId)- : host && this.isOrdinaryHostChild(roomId, viewer.peerId)- ? { kind: "peer" as const, peerId: host.peerId }- : { kind: "none" as const };- const activeEdge = this.isHybridMediaEnabled()- ? this.hybridMediaRouter!.resolveActiveViewerMediaEdge(- roomId,- viewer.peerId,- )- : undefined;- const connectionKey = viewerConnectionKey(roomId, viewer.peerId);- const mediaReady = this.isHybridMediaEnabled()- ? activeEdge !== undefined &&- upstream.kind !== "none" &&- (activeEdge.upstream.kind === "sfu"- ? upstream.kind === "sfu"- : upstream.kind === "peer" &&- activeEdge.upstream.peerId === upstream.peerId)- : upstream.kind === "peer" &&- this.connectionIdsByViewer.has(connectionKey) &&- this.ordinaryReadyConnectionIdsByViewer.get(- connectionKey,- ) === this.connectionIdsByViewer.get(connectionKey);- viewers.push({- role: "viewer",- peerId: viewer.peerId,- displayName: viewerState.displayName,- upstream,- ...(mediaReady ? { mediaReady: true as const } : {}),- });- }- const message = { type: "viewer-presence" as const, viewers };- const recipients = new Set<WebSocket>();- if (hostSocket && hostState?.viewerPresence) {- recipients.add(hostSocket);- }- for (const viewer of connectedViewers) {- const viewerSocket = this.socketsBySessionId.get(viewer.sessionId);- const viewerState = viewerSocket- ? this.socketStates.get(viewerSocket)?.authenticated- : undefined;- if (- viewerSocket &&- viewerState?.role === "viewer" &&- viewerState.roomId === roomId &&- viewerState.peerId === viewer.peerId &&- viewerState.viewerPresence- ) {- recipients.add(viewerSocket);- }- }- recipients.forEach((socket) => this.send(socket, message));- }-- private sendToSession(sessionId: string, message: ServerMessage): void {- const socket = this.socketsBySessionId.get(sessionId);- if (socket) {- this.send(socket, message);- }- }-- private broadcastHostStatus(- roomId: string,- online: boolean,- paused: boolean,- ): void {- for (const viewer of this.options.roomStore.getConnectedViewers(roomId)) {- this.sendToSession(viewer.sessionId, {- type: "host-status",- online,- paused,- });- }- }-- private closeRevokedViewerSession(sessionId: string): void {- const socket = this.socketsBySessionId.get(sessionId);- if (!socket) {- return;- }- const state = this.socketStates.get(socket);- if (state?.sessionId === sessionId) {- clearTimeout(state.authenticationTimer);- state.revoked = true;- }- if (this.socketsBySessionId.get(sessionId) === socket) {- this.socketsBySessionId.delete(sessionId);- }- // Deauthorize before close so queued callbacks from the old generation- // cannot route signaling after the persistent authorization commit.- socket.close(SIGNAL_CLOSE_CODES.viewerAccessRevoked, "Viewer access revoked");- }-- private sendEncodedToSession(sessionId: string, encoded: string): boolean {- const socket = this.socketsBySessionId.get(sessionId);- if (!socket || socket.readyState !== WebSocket.OPEN) {- return false;- }- if (socket.bufferedAmount > MAX_BUFFERED_SIGNAL_BYTES) {- socket.terminate();- return false;- }- socket.send(encoded);- return true;- }-- private send(socket: WebSocket, message: ServerMessage): void {- if (socket.readyState !== WebSocket.OPEN) {- return;- }- if (socket.bufferedAmount > MAX_BUFFERED_SIGNAL_BYTES) {- socket.terminate();- return;- }- socket.send(JSON.stringify(message));- }-- private sendError(socket: WebSocket, code: ErrorCode, message: string): void {- this.send(socket, { type: "error", code, message });- }-- private rejectInvalidMessage(socket: WebSocket): void {- this.sendError(socket, "INVALID_MESSAGE", "Message is invalid");- socket.close(1008, "Invalid message");- }-- private clearViewerGrace(roomId: string, peerId: string): void {- const key = viewerGraceKey(roomId, peerId);- const timer = this.viewerGraceTimers.get(key);- if (timer) {- clearTimeout(timer);- this.viewerGraceTimers.delete(key);- }- }-- private clearViewerState(roomId: string, peerId: string): void {- this.clearViewerGrace(roomId, peerId);- this.deleteViewerConnectionId(roomId, peerId);-- const ordinaryChildren = this.ordinaryActiveHostChildrenByRoom.get(roomId);- ordinaryChildren?.delete(peerId);- if (ordinaryChildren?.size === 0) {- this.ordinaryActiveHostChildrenByRoom.delete(roomId);- }- }-- private clearRoomGraceTimers(roomId: string): void {- const prefix = `${roomId}:`;- for (const [key, timer] of this.viewerGraceTimers) {- if (key.startsWith(prefix)) {- clearTimeout(timer);- this.viewerGraceTimers.delete(key);- }- }- }-- private clearRoomConnectionIds(roomId: string): void {- const prefix = `${roomId}:`;- for (const key of this.connectionIdsByViewer.keys()) {- if (key.startsWith(prefix)) {- this.connectionIdsByViewer.delete(key);- }- }- for (const key of this.ordinaryReadyConnectionIdsByViewer.keys()) {- if (key.startsWith(prefix)) {- this.ordinaryReadyConnectionIdsByViewer.delete(key);- }- }- for (const key of this.viewerQualityEvidenceGates.keys()) {- if (key.startsWith(prefix)) {- this.viewerQualityEvidenceGates.delete(key);- }- }- for (const key of this.viewerQualityEvidenceAttemptAtMs.keys()) {- if (key.startsWith(prefix)) {- this.viewerQualityEvidenceAttemptAtMs.delete(key);- }- }- }-- private setViewerConnectionId(- roomId: string,- viewerPeerId: string,- connectionId: string,- ): void {- const key = viewerConnectionKey(roomId, viewerPeerId);- if (this.connectionIdsByViewer.get(key) !== connectionId) {- this.ordinaryReadyConnectionIdsByViewer.delete(key);- this.viewerQualityEvidenceGates.delete(key);- this.viewerQualityEvidenceAttemptAtMs.delete(key);- }- this.connectionIdsByViewer.set(key, connectionId);- }-- private deleteViewerConnectionId(- roomId: string,- viewerPeerId: string,- ): void {- const key = viewerConnectionKey(roomId, viewerPeerId);- this.connectionIdsByViewer.delete(key);- this.ordinaryReadyConnectionIdsByViewer.delete(key);- this.viewerQualityEvidenceGates.delete(key);- this.viewerQualityEvidenceAttemptAtMs.delete(key);- }-}--function viewerGraceKey(roomId: string, peerId: string): string {- return `${roomId}:${peerId}`;-}--function viewerConnectionKey(roomId: string, peerId: string): string {- return `${roomId}:${peerId}`;-}--function authenticationErrorMessage(code: ErrorCode): string {- switch (code) {- case "ROOM_ACCESS_DENIED":- return "Room access denied";- case "ROOM_NOT_FOUND":- return "Room not found or expired";- case "ROOM_EXPIRED":- return "Room has expired";- case "ROOM_FULL":- return "Room is full";- case "HOST_ALREADY_CONNECTED":- return "A host is already connected";- case "INVALID_TOKEN":- return "Room is invalid or expired";- default:- return "Authentication failed";- }-}--function authenticationErrorCode(- message: Extract<ClientMessage, { type: "authenticate" }>,- error: unknown,-): ErrorCode {- if (!(error instanceof RoomStoreError) || error.code === "ROOM_LIMIT") {- return "SERVER_ERROR";- }- if (error.code === "ROOM_BUSY") {- return message.role === "viewer" ? "ROOM_ACCESS_DENIED" : "SERVER_ERROR";- }- if (message.role !== "viewer") {- return error.code;- }- if (!message.viewerGrant) {- if (- error.code === "ROOM_NOT_FOUND" ||- error.code === "ROOM_EXPIRED"- ) {- return "ROOM_NOT_FOUND";- }- return "ROOM_ACCESS_DENIED";- }- return error.code === "ROOM_EXPIRED" || error.code === "ROOM_NOT_FOUND"- ? "INVALID_TOKEN"- : error.code;-}--function rejectUpgrade(socket: Duplex, status: number, message: string): void {- socket.write(- `HTTP/1.1 ${status} ${message}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`,- );- socket.destroy();-}diff --git a/src/shared/media-copy-accounting.ts b/src/shared/media-copy-accounting.tsindex 42b72c6c..948c9dbd 100644--- a/src/shared/media-copy-accounting.ts+++ b/src/shared/media-copy-accounting.ts@@ -62,13 +62,3 @@ export function assertEndpointMediaCopyCapacity(capacity: number): void {throw new Error("Endpoint media copy capacity must be 1, 2, or 3");}}--export function assertEndpointMediaCopyCount(- count: number,- capacity: number,- phase: EndpointMediaCopyPhase = "steady",-): void {- if (!endpointMediaCopyCountFits(count, capacity, phase)) {- throw new Error(`Endpoint ${phase} media copy capacity exceeded`);- }-}diff --git a/src/shared/protocol.ts b/src/shared/protocol.tsindex 4ea0e7de..294071ac 100644--- a/src/shared/protocol.ts+++ b/src/shared/protocol.ts@@ -7,7 +7,7 @@ import { NAT_TRAVERSAL_PATHS } from "./nat-candidate.js";export const MAX_VIEWERS_PER_ROOM_LIMIT = 20;export const MAX_PARTICIPANTS_PER_ROOM_LIMIT = MAX_VIEWERS_PER_ROOM_LIMIT + 1;export const MAX_SIGNAL_BYTES = 64 * 1024;-export const SIGNALING_PROTOCOL = "screener-v20";+export const SIGNALING_PROTOCOL = "screener-v21";export const SIGNAL_CLOSE_CODES = {serviceRestart: 1012,sessionReplaced: 4001,@@ -943,7 +943,6 @@ const authenticatedMessageShape = {hostOnline: z.boolean(),hostPaused: z.boolean().optional(),connectionId: opaqueIdSchema.nullable(),- viewerPeerIds: z.array(opaqueIdSchema).max(MAX_VIEWERS_PER_ROOM_LIMIT),iceConfig: iceConfigSchema,routePolicy: routePolicySchema.default(DEFAULT_ROUTE_POLICY),codeEntryPolicy: codeEntryPolicySchema,@@ -961,7 +960,7 @@ const authenticatedViewerMessageShape = {role: z.literal("viewer"),};-const peerAssistedAuthenticatedShape = {+const routeAuthenticatedShape = {mediaMode: z.literal("peer-assisted"),shareGeneration: opaqueIdSchema.nullable(),routeRevision: mediaRouteRevisionSchema,@@ -971,18 +970,16 @@ const peerAssistedAuthenticatedShape = {};const authenticatedMessageSchema = z.union([- z.object(authenticatedHostMessageShape).strict(),- z.object(authenticatedViewerMessageShape).strict(),z.object({...authenticatedHostMessageShape,- ...peerAssistedAuthenticatedShape,+ ...routeAuthenticatedShape,}).strict(),z.object({...authenticatedViewerMessageShape,- ...peerAssistedAuthenticatedShape,+ ...routeAuthenticatedShape,}).strict(),]);@@ -995,24 +992,6 @@ export const serverMessageSchema = z.union([sequence: signalingChallengeSequenceSchema,}).strict(),- z- .object({- type: z.literal("peer-joined"),- peerId: opaqueIdSchema,- })- .strict(),- z- .object({- type: z.literal("peer-waiting"),- peerId: opaqueIdSchema,- })- .strict(),- z- .object({- type: z.literal("peer-left"),- peerId: opaqueIdSchema,- })- .strict(),z.object({type: z.literal("signal"),diff --git a/tests/client-gate-endpoint.test.ts b/tests/client-gate-endpoint.test.tsindex cad28b65..1bc35136 100644--- a/tests/client-gate-endpoint.test.ts+++ b/tests/client-gate-endpoint.test.ts@@ -1,6 +1,13 @@+import { EventEmitter } from "node:events";+import type { ChildProcessWithoutNullStreams } from "node:child_process";+import { PassThrough } from "node:stream";+import { describe, expect, it } from "vitest";-import { decodeClientEndpoint } from "../scripts/client-gate-endpoint";+import {+ decodeClientEndpoint,+ readClientEndpoint,+} from "../scripts/client-gate-endpoint";describe("Client gate endpoint decoder", () => {const endpoint = {@@ -30,4 +37,16 @@ describe("Client gate endpoint decoder", () => {"Client endpoint is invalid",);});++ it("reads an endpoint after optional client status lines", async () => {+ const stdout = new PassThrough();+ const child = Object.assign(new EventEmitter(), { stdout }) as unknown as+ ChildProcessWithoutNullStreams;+ const result = readClientEndpoint(child, {+ ignoreNonEndpointLines: true,+ });+ stdout.write("Local access: open\n");+ stdout.write(`${JSON.stringify(endpoint)}\n`);+ await expect(result).resolves.toEqual(endpoint);+ });});diff --git a/tests/client-state.test.ts b/tests/client-state.test.tsindex 251b833b..285f6f37 100644--- a/tests/client-state.test.ts+++ b/tests/client-state.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import {+ DEFAULT_QUALITY_SETTINGS,DEFAULT_ROUTE_POLICY,SIGNALING_PROTOCOL,type QualitySettings,@@ -62,6 +63,24 @@ afterEach(() => {setCopy({ lang: "zh", vis: false });});+function routeAuthenticated(+ shareGeneration: string | null = null,+ qualitySettings: QualitySettings = DEFAULT_QUALITY_SETTINGS,+) {+ return {+ mediaMode: "peer-assisted" as const,+ shareGeneration,+ routeRevision: 0,+ routeAssignment: {+ upstream: { kind: "none" as const },+ childPeerIds: [],+ sfuPublicationGeneration: null,+ },+ qualitySettings,+ routePolicy: DEFAULT_ROUTE_POLICY,+ };+}+describe("browser-local display name", () => {it("localizes text defaults and uses visual emoji identities", () => {setCopy({ lang: "zh", vis: false });@@ -423,7 +442,7 @@ describe("client session identity", () => {},});- expect(readViewerRoute()).toEqual({ roomId: "1234" });+ expect(readViewerRoute()).toEqual({ roomId: "1234", invalidGrant: true });expect(readViewerGrant("1234")).toBeNull();replaceViewerInvite("1234", `https://share.test/r/1234#v=${"e".repeat(21)}Q`);expect(readViewerGrant("1234")).toBe(`${"e".repeat(21)}Q`);@@ -432,6 +451,26 @@ describe("client session identity", () => {expect(readViewerGrant("5678")).toBeNull();});+ it("keeps the stored Viewer grant when the URL carries an unrelated fragment", () => {+ const values = new Map<string, string>();+ const grant = `${"d".repeat(21)}w`;+ values.set("screener:viewer-grant:1234", grant);+ const replaceState = vi.fn();+ vi.stubGlobal("window", {+ location: new URL("https://share.test/r/1234#:~:text=hello"),+ history: { state: null, replaceState },+ sessionStorage: {+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => values.set(key, value),+ removeItem: (key: string) => values.delete(key),+ },+ });++ expect(readViewerRoute()).toEqual({ roomId: "1234", viewerGrant: grant });+ expect(readViewerGrant("1234")).toBe(grant);+ expect(replaceState).not.toHaveBeenCalled();+ });+it("persists a rotated Viewer invitation across reload and clears it on revoke", () => {const values = new Map<string, string>();vi.stubGlobal("window", {@@ -947,7 +986,7 @@ describe("client signaling recovery policy", () => {endpointMediaCopyCapacity: 2,hostOnline: true,connectionId: null,- viewerPeerIds: [],+ ...routeAuthenticated(),iceConfig: { iceServers: [], natPredictionStunUrls: [] },codeEntryPolicy: "open",viewerAuthorizationGeneration: "viewer_generation_12345678",@@ -1091,7 +1130,7 @@ describe("client signaling recovery policy", () => {hostOnline: true,hostPaused: true,connectionId: null,- viewerPeerIds: [],+ ...routeAuthenticated("share_generation_12345678"),iceConfig: { iceServers: [], natPredictionStunUrls: [] },codeEntryPolicy: "open",viewerPasswordEnabled: false,@@ -1127,7 +1166,7 @@ describe("client signaling recovery policy", () => {hostOnline: true,hostPaused: true,connectionId: null,- viewerPeerIds: [],+ ...routeAuthenticated("share_generation_12345678"),iceConfig: { iceServers: [], natPredictionStunUrls: [] },codeEntryPolicy: "open",viewerPasswordEnabled: false,@@ -1240,7 +1279,6 @@ describe("client signaling recovery policy", () => {hostOnline: true,hostPaused: false,connectionId: null,- viewerPeerIds: [],iceConfig: { iceServers: [], natPredictionStunUrls: [] },codeEntryPolicy: "open",viewerPasswordEnabled: false,@@ -1368,7 +1406,7 @@ describe("client signaling recovery policy", () => {endpointMediaCopyCapacity: 2,hostOnline: true,connectionId: null,- viewerPeerIds: [],+ ...routeAuthenticated(),iceConfig: { iceServers: [], natPredictionStunUrls: [] },codeEntryPolicy: "open",viewerPasswordEnabled: false,@@ -1485,7 +1523,6 @@ describe("client signaling recovery policy", () => {endpointMediaCopyCapacity: 2,hostOnline: true,connectionId: "connection_12345678",- viewerPeerIds: [],iceConfig: { iceServers: [], natPredictionStunUrls: [] },codeEntryPolicy: "open",viewerAuthorizationGeneration: "viewer_generation_12345678",@@ -1566,7 +1603,7 @@ describe("client signaling recovery policy", () => {maxViewers: 8,hostOnline: true,connectionId: null,- viewerPeerIds: [],+ ...routeAuthenticated(),iceConfig: { iceServers: [], natPredictionStunUrls: [] },}),])(diff --git a/tests/fake-sfu-room-control.ts b/tests/fake-sfu-room-control.tsdeleted file mode 100644index 2fa66b52..00000000--- a/tests/fake-sfu-room-control.ts+++ /dev/null@@ -1,78 +0,0 @@-import type {- SfuResourceFence,- SfuSubscriptionFence,-} from "../src/server/sfu-resource-admission.ts";-import { managedSfuRoomName } from "../src/server/sfu-resource-admission.ts";-import {- type SfuRoomControl,-} from "../src/server/sfu-room-control.ts";--export class FakeSfuRoomControl implements SfuRoomControl {- readonly rooms = new Map<string, Set<string>>();- readonly created: SfuResourceFence[] = [];- readonly deleted: SfuResourceFence[] = [];- readonly subscriptionDrainAttempts: SfuSubscriptionFence[] = [];- readonly drainedSubscriptions: SfuSubscriptionFence[] = [];- readonly startupDeletedRoomNames: string[] = [];- initializeCalls = 0;- initializeBarrier?: Promise<void>;- initializeError?: Error;- createBarrier?: Promise<void>;- deleteBarrier?: Promise<void>;- subscriptionDrainBarrier?: Promise<void>;- failDelete = false;- failHostCheck = false;-- async initialize(): Promise<void> {- this.initializeCalls += 1;- await this.initializeBarrier;- if (this.initializeError) {- throw this.initializeError;- }- this.startupDeletedRoomNames.push(...this.rooms.keys());- this.rooms.clear();- }-- async createRoom(fence: SfuResourceFence): Promise<void> {- await this.createBarrier;- const roomName = managedSfuRoomName(fence);- if (this.rooms.has(roomName)) {- throw new Error("room already exists");- }- this.rooms.set(roomName, new Set());- this.created.push({ ...fence });- }-- async deleteRoom(fence: SfuResourceFence): Promise<void> {- await this.deleteBarrier;- if (this.failDelete) {- throw new Error("room deletion failed");- }- this.rooms.delete(managedSfuRoomName(fence));- this.deleted.push({ ...fence });- }-- async drainSubscription(fence: SfuSubscriptionFence): Promise<void> {- this.subscriptionDrainAttempts.push({ ...fence });- await this.subscriptionDrainBarrier;- this.rooms- .get(managedSfuRoomName(fence))- ?.delete(`viewer:${fence.viewerPeerId}`);- this.drainedSubscriptions.push({ ...fence });- }-- async hostParticipantExists(fence: SfuResourceFence): Promise<boolean> {- if (this.failHostCheck) {- throw new Error("host check failed");- }- return this.rooms.get(managedSfuRoomName(fence))?.has("host") ?? false;- }-- seedRoom(fence: SfuResourceFence, identities: readonly string[] = []): void {- this.rooms.set(managedSfuRoomName(fence), new Set(identities));- }-- canJoin(roomName: string): boolean {- return this.rooms.has(roomName);- }-}diff --git a/tests/fixtures/wire-samples.json b/tests/fixtures/wire-samples.jsonnew file mode 100644index 00000000..553090eb--- /dev/null+++ b/tests/fixtures/wire-samples.json@@ -0,0 +1,911 @@+{+ "constants": {+ "signalingProtocol": "screener-v21",+ "maxViewersPerRoomLimit": 20,+ "maxParticipantsPerRoomLimit": 21,+ "maxSignalBytes": 65536,+ "roomCodeLength": 4,+ "maxMediaRouteRevision": 9007199254740991,+ "maxSfuTokenLength": 8192,+ "maxIceServerUrls": 8,+ "maxNatPredictionAuxiliaryStunUrls": 2,+ "maxViewerQualityEvidenceBytes": 2048,+ "viewerQualityEvidenceIntervalMs": 2000,+ "viewerQualityEvidenceExpiryMs": 5000,+ "persistentNativeEdgeDegradedWindows": 3,+ "maxDisplayNameCodePoints": 24,+ "defaultViewerDisplayName": "观众",+ "defaultHostDisplayNamePrefix": "分享者",+ "minViewerPasswordLength": 1,+ "maxViewerPasswordLength": 64,+ "defaultEndpointMediaCopyCapacity": 2,+ "maxEndpointMediaCopyCapacity": 3,+ "signalCloseCodeServiceRestart": 1012,+ "signalCloseCodeSessionReplaced": 4001,+ "signalCloseCodeClientReconnect": 4002,+ "signalCloseCodeAuthenticationFailed": 4003,+ "signalCloseCodeViewerAccessRevoked": 4004,+ "defaultQualitySettings": {+ "resolution": "1080p",+ "maxFramerate": 30,+ "maxBitrate": 5000000,+ "degradationPreference": "balanced",+ "screenAudioQuality": "music"+ },+ "defaultRoutePolicy": {+ "peerOnly": false,+ "topologyOptimization": true,+ "natPrediction": false+ }+ },+ "clientMessages": [+ {+ "name": "authenticate-host-minimal",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"host\",\"token\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"clientId\":\"client_12345678\"}",+ "valid": true+ },+ {+ "name": "authenticate-host-full",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"host\",\"token\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"clientId\":\"client_12345678\",\"shareGeneration\":\"share_generation_12345678\",\"sharingPaused\":false,\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\",\"screenAudioQuality\":\"music\"},\"routePolicy\":{\"peerOnly\":false,\"topologyOptimization\":true,\"natPrediction\":false},\"viewerPresence\":true,\"displayName\":\"小明\"}",+ "valid": true+ },+ {+ "name": "authenticate-host-carries-viewer-grant",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"host\",\"token\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"clientId\":\"client_12345678\",\"viewerGrant\":\"bbbbbbbbbbbbbbbbbbbbbg\"}",+ "valid": false+ },+ {+ "name": "authenticate-host-carries-viewer-password",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"host\",\"token\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"clientId\":\"client_12345678\",\"viewerPassword\":\"easy-password\"}",+ "valid": false+ },+ {+ "name": "authenticate-host-short-token",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"host\",\"token\":\"short\",\"clientId\":\"client_12345678\"}",+ "valid": false+ },+ {+ "name": "authenticate-host-unknown-key",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"host\",\"token\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"clientId\":\"client_12345678\",\"admin\":true}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-minimal",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\"}",+ "valid": true+ },+ {+ "name": "authenticate-viewer-full",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"viewerGrant\":\"bbbbbbbbbbbbbbbbbbbbbg\",\"viewerPassword\":\"easy-password\",\"displayName\":\"Café 朋友\",\"viewerPresence\":true}",+ "valid": true+ },+ {+ "name": "authenticate-viewer-carries-host-token",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"token\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-carries-route-policy",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"routePolicy\":{\"peerOnly\":false,\"topologyOptimization\":true,\"natPrediction\":false}}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-malformed-grant",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"viewerGrant\":\"bbbbbbbbbbbbbbbbbbbbb\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-grant-bad-final-character",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"viewerGrant\":\"bbbbbbbbbbbbbbbbbbbbbb\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-unknown-capabilities",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"capabilities\":{\"peerIceTurn\":true}}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-wrong-protocol",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"invalid-protocol\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-missing-protocol",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-leading-zero-room",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"0123\",\"role\":\"viewer\",\"clientId\":\"client_12345678\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-long-room",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"11111\",\"role\":\"viewer\",\"clientId\":\"client_12345678\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-noncanonical-display-name",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"displayName\":\" Café \"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-display-name-too-long",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"displayName\":\"名名名名名名名名名名名名名名名名名名名名名名名名名\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-display-name-at-limit",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"displayName\":\"名名名名名名名名名名名名名名名名名名名名名名名名\"}",+ "valid": true+ },+ {+ "name": "authenticate-viewer-display-name-bidi-override",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"displayName\":\"ab\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-display-name-newline",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"displayName\":\"a\\nb\"}",+ "valid": false+ },+ {+ "name": "authenticate-viewer-null-display-name",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"viewer\",\"clientId\":\"client_12345678\",\"displayName\":null}",+ "valid": false+ },+ {+ "name": "authenticate-unknown-role",+ "schema": "client",+ "json": "{\"type\":\"authenticate\",\"protocol\":\"screener-v21\",\"roomId\":\"1234\",\"role\":\"relay\",\"clientId\":\"client_12345678\"}",+ "valid": false+ },+ {+ "name": "signaling-challenge-max",+ "schema": "client",+ "json": "{\"type\":\"signaling-challenge\",\"sequence\":9007199254740991}",+ "valid": true+ },+ {+ "name": "signaling-challenge-negative",+ "schema": "client",+ "json": "{\"type\":\"signaling-challenge\",\"sequence\":-1}",+ "valid": false+ },+ {+ "name": "signaling-challenge-fractional",+ "schema": "client",+ "json": "{\"type\":\"signaling-challenge\",\"sequence\":1.5}",+ "valid": false+ },+ {+ "name": "signaling-challenge-above-safe-integer",+ "schema": "client",+ "json": "{\"type\":\"signaling-challenge\",\"sequence\":9007199254740992}",+ "valid": false+ },+ {+ "name": "signaling-challenge-extra-key",+ "schema": "client",+ "json": "{\"type\":\"signaling-challenge\",\"sequence\":1,\"roomId\":\"1234\"}",+ "valid": false+ },+ {+ "name": "signal-description",+ "schema": "client",+ "json": "{\"type\":\"signal\",\"targetPeerId\":\"viewer_12345678\",\"payload\":{\"kind\":\"description\",\"connectionId\":\"connection_12345678\",\"description\":{\"type\":\"offer\",\"sdp\":\"v=0\\r\\n\"}}}",+ "valid": true+ },+ {+ "name": "signal-candidate-end",+ "schema": "client",+ "json": "{\"type\":\"signal\",\"payload\":{\"kind\":\"candidate\",\"connectionId\":\"connection_12345678\",\"candidate\":null}}",+ "valid": true+ },+ {+ "name": "signal-candidate-full",+ "schema": "client",+ "json": "{\"type\":\"signal\",\"payload\":{\"kind\":\"candidate\",\"connectionId\":\"connection_12345678\",\"candidate\":{\"candidate\":\"candidate:1 1 udp 1 203.0.113.1 50000 typ host\",\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":null}}}",+ "valid": true+ },+ {+ "name": "signal-empty-sdp",+ "schema": "client",+ "json": "{\"type\":\"signal\",\"payload\":{\"kind\":\"description\",\"connectionId\":\"connection_12345678\",\"description\":{\"type\":\"offer\",\"sdp\":\"\"}}}",+ "valid": false+ },+ {+ "name": "signal-unknown-payload-kind",+ "schema": "client",+ "json": "{\"type\":\"signal\",\"payload\":{\"kind\":\"renegotiate\",\"connectionId\":\"connection_12345678\"}}",+ "valid": false+ },+ {+ "name": "signal-missing-candidate-key",+ "schema": "client",+ "json": "{\"type\":\"signal\",\"payload\":{\"kind\":\"candidate\",\"connectionId\":\"connection_12345678\"}}",+ "valid": false+ },+ {+ "name": "restart-request",+ "schema": "client",+ "json": "{\"type\":\"restart-request\",\"connectionId\":\"connection_12345678\",\"rebuild\":true}",+ "valid": true+ },+ {+ "name": "restart-request-targeted",+ "schema": "client",+ "json": "{\"type\":\"restart-request\",\"targetPeerId\":\"parent_12345678\",\"connectionId\":\"connection_12345678\",\"rebuild\":false}",+ "valid": true+ },+ {+ "name": "restart-request-missing-rebuild",+ "schema": "client",+ "json": "{\"type\":\"restart-request\",\"connectionId\":\"connection_12345678\"}",+ "valid": false+ },+ {+ "name": "set-quality-settings",+ "schema": "client",+ "json": "{\"type\":\"set-quality-settings\",\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\"}}",+ "valid": true+ },+ {+ "name": "set-quality-settings-with-audio",+ "schema": "client",+ "json": "{\"type\":\"set-quality-settings\",\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\",\"screenAudioQuality\":\"music\"}}",+ "valid": true+ },+ {+ "name": "set-quality-settings-legacy-codec",+ "schema": "client",+ "json": "{\"type\":\"set-quality-settings\",\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\",\"videoCodec\":\"vp8\"}}",+ "valid": false+ },+ {+ "name": "set-quality-settings-framerate-below-floor",+ "schema": "client",+ "json": "{\"type\":\"set-quality-settings\",\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":14,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\"}}",+ "valid": false+ },+ {+ "name": "set-quality-settings-fractional-bitrate",+ "schema": "client",+ "json": "{\"type\":\"set-quality-settings\",\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":5000000.5,\"degradationPreference\":\"maintain-resolution\"}}",+ "valid": false+ },+ {+ "name": "set-quality-settings-missing-framerate",+ "schema": "client",+ "json": "{\"type\":\"set-quality-settings\",\"qualitySettings\":{\"resolution\":\"1080p\",\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\"}}",+ "valid": false+ },+ {+ "name": "set-quality-settings-unknown-resolution",+ "schema": "client",+ "json": "{\"type\":\"set-quality-settings\",\"qualitySettings\":{\"resolution\":\"2160p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\"}}",+ "valid": false+ },+ {+ "name": "relay-capacity-max",+ "schema": "client",+ "json": "{\"type\":\"relay-capacity\",\"downstreamEdges\":3}",+ "valid": true+ },+ {+ "name": "relay-capacity-zero",+ "schema": "client",+ "json": "{\"type\":\"relay-capacity\",\"downstreamEdges\":0}",+ "valid": true+ },+ {+ "name": "relay-capacity-over-limit",+ "schema": "client",+ "json": "{\"type\":\"relay-capacity\",\"downstreamEdges\":4}",+ "valid": false+ },+ {+ "name": "relay-capacity-extra-key",+ "schema": "client",+ "json": "{\"type\":\"relay-capacity\",\"downstreamEdges\":1,\"score\":100}",+ "valid": false+ },+ {+ "name": "route-ready",+ "schema": "client",+ "json": "{\"type\":\"route-ready\",\"revision\":7,\"phase\":\"prepare\"}",+ "valid": true+ },+ {+ "name": "route-ready-quality-approved",+ "schema": "client",+ "json": "{\"type\":\"route-ready\",\"revision\":7,\"phase\":\"prepare\",\"qualityApproved\":true}",+ "valid": true+ },+ {+ "name": "route-ready-quality-approved-false",+ "schema": "client",+ "json": "{\"type\":\"route-ready\",\"revision\":7,\"phase\":\"prepare\",\"qualityApproved\":false}",+ "valid": false+ },+ {+ "name": "route-ready-negative-revision",+ "schema": "client",+ "json": "{\"type\":\"route-ready\",\"revision\":-1,\"phase\":\"prepare\"}",+ "valid": false+ },+ {+ "name": "route-transport-connected",+ "schema": "client",+ "json": "{\"type\":\"route-transport-connected\",\"revision\":7,\"connectionId\":\"connection_12345678\"}",+ "valid": true+ },+ {+ "name": "route-transport-connected-missing-connection",+ "schema": "client",+ "json": "{\"type\":\"route-transport-connected\",\"revision\":7}",+ "valid": false+ },+ {+ "name": "route-media-unavailable",+ "schema": "client",+ "json": "{\"type\":\"route-media-unavailable\",\"revision\":7}",+ "valid": true+ },+ {+ "name": "route-media-unavailable-negative",+ "schema": "client",+ "json": "{\"type\":\"route-media-unavailable\",\"revision\":-1}",+ "valid": false+ },+ {+ "name": "route-failed",+ "schema": "client",+ "json": "{\"type\":\"route-failed\",\"revision\":7,\"phase\":\"active\",\"connectionId\":null}",+ "valid": true+ },+ {+ "name": "route-failed-missing-connection",+ "schema": "client",+ "json": "{\"type\":\"route-failed\",\"revision\":7,\"phase\":\"active\"}",+ "valid": false+ },+ {+ "name": "refresh-sfu-max-revision",+ "schema": "client",+ "json": "{\"type\":\"refresh-sfu\",\"revision\":9007199254740991}",+ "valid": true+ },+ {+ "name": "refresh-sfu-fractional",+ "schema": "client",+ "json": "{\"type\":\"refresh-sfu\",\"revision\":1.5}",+ "valid": false+ },+ {+ "name": "request-route-diagnostic",+ "schema": "client",+ "json": "{\"type\":\"request-route-diagnostic\"}",+ "valid": true+ },+ {+ "name": "request-route-diagnostic-extra-key",+ "schema": "client",+ "json": "{\"type\":\"request-route-diagnostic\",\"roomId\":\"1234\"}",+ "valid": false+ },+ {+ "name": "viewer-quality-evidence",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": true+ },+ {+ "name": "viewer-quality-evidence-null-freeze",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":null,\"freezeDurationMsDelta\":null,\"pauseCountDelta\":null,\"pauseDurationMsDelta\":null,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": true+ },+ {+ "name": "viewer-quality-evidence-vp8",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/VP8\",\"codecProfile\":null,\"codecParameters\":\"max-fr=60; max-fs=8160\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": true+ },+ {+ "name": "viewer-quality-evidence-unknown-codec",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/unknown\",\"codecProfile\":null,\"codecParameters\":null,\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": true+ },+ {+ "name": "viewer-quality-evidence-missing-path",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": false+ },+ {+ "name": "viewer-quality-evidence-lonely-height",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":null,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": false+ },+ {+ "name": "viewer-quality-evidence-lonely-width",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":null,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": false+ },+ {+ "name": "viewer-quality-evidence-noncanonical-parameters",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"sprop-parameter-sets=deadbeef\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": false+ },+ {+ "name": "viewer-quality-evidence-window-too-short",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":999,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": false+ },+ {+ "name": "viewer-quality-evidence-extra-guard-key",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0,\"peerId\":\"viewer_12345678\"},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": false+ },+ {+ "name": "viewer-quality-evidence-device-fingerprint",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\",\"decoderImplementation\":\"device-specific-decoder\"}}",+ "valid": false+ },+ {+ "name": "viewer-quality-evidence-freeze-above-safe-integer",+ "schema": "client",+ "json": "{\"type\":\"viewer-quality-evidence\",\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":9007199254740992,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}",+ "valid": false+ },+ {+ "name": "sender-quality-evidence",+ "schema": "client",+ "json": "{\"type\":\"sender-quality-evidence\",\"childPeerId\":\"viewer_12345678\",\"connectionId\":\"connection_12345678\",\"rtpStatsId\":\"rtp-stats-1\",\"trackIdentifier\":\"track-1\",\"sampleTimestampMs\":2000,\"routeRevision\":3,\"state\":\"degraded\",\"diagnostics\":{\"natTraversalPath\":\"ordinary\",\"reason\":\"bandwidth\",\"framesPerSecond\":24,\"bitrateKbps\":1500}}",+ "valid": true+ },+ {+ "name": "sender-quality-evidence-unknown-state",+ "schema": "client",+ "json": "{\"type\":\"sender-quality-evidence\",\"childPeerId\":\"viewer_12345678\",\"connectionId\":\"connection_12345678\",\"rtpStatsId\":null,\"trackIdentifier\":null,\"sampleTimestampMs\":null,\"routeRevision\":3,\"state\":\"unknown\",\"diagnostics\":{\"natTraversalPath\":\"ordinary\",\"reason\":null,\"framesPerSecond\":24,\"bitrateKbps\":1500}}",+ "valid": true+ },+ {+ "name": "sender-quality-evidence-healthy-without-identity",+ "schema": "client",+ "json": "{\"type\":\"sender-quality-evidence\",\"childPeerId\":\"viewer_12345678\",\"connectionId\":\"connection_12345678\",\"rtpStatsId\":null,\"trackIdentifier\":\"track-1\",\"sampleTimestampMs\":2000,\"routeRevision\":3,\"state\":\"healthy\",\"diagnostics\":{\"natTraversalPath\":\"ordinary\",\"reason\":\"none\",\"framesPerSecond\":24,\"bitrateKbps\":1500}}",+ "valid": false+ },+ {+ "name": "sender-quality-evidence-reason-mismatch",+ "schema": "client",+ "json": "{\"type\":\"sender-quality-evidence\",\"childPeerId\":\"viewer_12345678\",\"connectionId\":\"connection_12345678\",\"rtpStatsId\":\"rtp-stats-1\",\"trackIdentifier\":\"track-1\",\"sampleTimestampMs\":2000,\"routeRevision\":3,\"state\":\"healthy\",\"diagnostics\":{\"natTraversalPath\":\"ordinary\",\"reason\":\"bandwidth\",\"framesPerSecond\":24,\"bitrateKbps\":1500}}",+ "valid": false+ },+ {+ "name": "sender-quality-evidence-missing-path",+ "schema": "client",+ "json": "{\"type\":\"sender-quality-evidence\",\"childPeerId\":\"viewer_12345678\",\"connectionId\":\"connection_12345678\",\"rtpStatsId\":\"rtp-stats-1\",\"trackIdentifier\":\"track-1\",\"sampleTimestampMs\":2000,\"routeRevision\":3,\"state\":\"degraded\",\"diagnostics\":{\"reason\":\"bandwidth\",\"framesPerSecond\":24,\"bitrateKbps\":1500}}",+ "valid": false+ },+ {+ "name": "sfu-publisher-quality-evidence",+ "schema": "client",+ "json": "{\"type\":\"sfu-publisher-quality-evidence\",\"publicationGeneration\":\"publication_generation_12345678\",\"routeRevision\":4,\"state\":\"healthy\",\"sampleTimestampMs\":2000,\"diagnostics\":{\"natTraversalPath\":\"ordinary\",\"reason\":\"none\",\"framesPerSecond\":30,\"bitrateKbps\":2000,\"captureFramesPerSecond\":30,\"mediaSourceFramesPerSecond\":null,\"width\":1920,\"height\":1080,\"videoEncodingCount\":1,\"activeVideoEncodingCount\":1,\"availableOutgoingKbps\":9000,\"rttMs\":12,\"packetLossPercent\":0.1}}",+ "valid": true+ },+ {+ "name": "sfu-publisher-quality-evidence-missing-sample",+ "schema": "client",+ "json": "{\"type\":\"sfu-publisher-quality-evidence\",\"publicationGeneration\":\"publication_generation_12345678\",\"routeRevision\":4,\"state\":\"healthy\",\"sampleTimestampMs\":null,\"diagnostics\":{\"natTraversalPath\":\"ordinary\",\"reason\":\"none\",\"framesPerSecond\":30,\"bitrateKbps\":2000,\"captureFramesPerSecond\":30,\"mediaSourceFramesPerSecond\":null,\"width\":1920,\"height\":1080,\"videoEncodingCount\":1,\"activeVideoEncodingCount\":1,\"availableOutgoingKbps\":9000,\"rttMs\":12,\"packetLossPercent\":0.1}}",+ "valid": false+ },+ {+ "name": "reset-sender-quality",+ "schema": "client",+ "json": "{\"type\":\"reset-sender-quality\"}",+ "valid": true+ },+ {+ "name": "reset-sender-quality-extra-key",+ "schema": "client",+ "json": "{\"type\":\"reset-sender-quality\",\"roomId\":\"1234\"}",+ "valid": false+ },+ {+ "name": "set-display-name",+ "schema": "client",+ "json": "{\"type\":\"set-display-name\",\"displayName\":\"小明\"}",+ "valid": true+ },+ {+ "name": "set-display-name-noncanonical",+ "schema": "client",+ "json": "{\"type\":\"set-display-name\",\"displayName\":\" Café \"}",+ "valid": false+ },+ {+ "name": "set-sharing-paused",+ "schema": "client",+ "json": "{\"type\":\"set-sharing-paused\",\"shareGeneration\":\"share_generation_12345678\",\"paused\":true}",+ "valid": true+ },+ {+ "name": "set-sharing-paused-resume",+ "schema": "client",+ "json": "{\"type\":\"set-sharing-paused\",\"shareGeneration\":\"share_generation_12345678\",\"paused\":false}",+ "valid": true+ },+ {+ "name": "set-sharing-paused-string-flag",+ "schema": "client",+ "json": "{\"type\":\"set-sharing-paused\",\"shareGeneration\":\"share_generation_12345678\",\"paused\":\"true\"}",+ "valid": false+ },+ {+ "name": "set-sharing-paused-extra-key",+ "schema": "client",+ "json": "{\"type\":\"set-sharing-paused\",\"shareGeneration\":\"share_generation_12345678\",\"paused\":true,\"unexpected\":1}",+ "valid": false+ },+ {+ "name": "set-sharing-paused-missing-generation",+ "schema": "client",+ "json": "{\"type\":\"set-sharing-paused\",\"paused\":true}",+ "valid": false+ },+ {+ "name": "stop-sharing",+ "schema": "client",+ "json": "{\"type\":\"stop-sharing\"}",+ "valid": true+ },+ {+ "name": "stop-sharing-generation",+ "schema": "client",+ "json": "{\"type\":\"stop-sharing\",\"shareGeneration\":\"share_generation_12345678\"}",+ "valid": true+ },+ {+ "name": "stop-sharing-short-generation",+ "schema": "client",+ "json": "{\"type\":\"stop-sharing\",\"shareGeneration\":\"short\"}",+ "valid": false+ },+ {+ "name": "abandon-room",+ "schema": "client",+ "json": "{\"type\":\"abandon-room\"}",+ "valid": true+ },+ {+ "name": "abandon-room-extra-key",+ "schema": "client",+ "json": "{\"type\":\"abandon-room\",\"reason\":\"expired\"}",+ "valid": false+ },+ {+ "name": "removed-refresh-ice",+ "schema": "client",+ "json": "{\"type\":\"refresh-ice\"}",+ "valid": false+ },+ {+ "name": "removed-set-code-entry-policy",+ "schema": "client",+ "json": "{\"type\":\"set-code-entry-policy\",\"policy\":\"open\"}",+ "valid": false+ },+ {+ "name": "removed-rotate-viewer-grant",+ "schema": "client",+ "json": "{\"type\":\"rotate-viewer-grant\"}",+ "valid": false+ },+ {+ "name": "create-room-open",+ "schema": "createRoomRequest",+ "json": "{\"codeEntryPolicy\":\"open\"}",+ "valid": true+ },+ {+ "name": "create-room-private-password",+ "schema": "createRoomRequest",+ "json": "{\"codeEntryPolicy\":\"private\",\"roomPassword\":\"room-password\"}",+ "valid": true+ },+ {+ "name": "create-room-null-password",+ "schema": "createRoomRequest",+ "json": "{\"codeEntryPolicy\":\"private\",\"roomPassword\":null}",+ "valid": true+ },+ {+ "name": "create-room-preferred-code",+ "schema": "createRoomRequest",+ "json": "{\"codeEntryPolicy\":\"open\",\"preferredRoomId\":\"4321\"}",+ "valid": true+ },+ {+ "name": "create-room-leading-zero-code",+ "schema": "createRoomRequest",+ "json": "{\"codeEntryPolicy\":\"open\",\"preferredRoomId\":\"0432\"}",+ "valid": false+ },+ {+ "name": "create-room-unknown-policy",+ "schema": "createRoomRequest",+ "json": "{\"codeEntryPolicy\":\"password\"}",+ "valid": false+ },+ {+ "name": "create-room-numeric-policy",+ "schema": "createRoomRequest",+ "json": "{\"codeEntryPolicy\":1}",+ "valid": false+ },+ {+ "name": "create-room-space-in-password",+ "schema": "createRoomRequest",+ "json": "{\"codeEntryPolicy\":\"private\",\"roomPassword\":\"contains space\"}",+ "valid": false+ },+ {+ "name": "create-room-unknown-key",+ "schema": "createRoomRequest",+ "json": "{\"codeEntryPolicy\":\"open\",\"hostToken\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}",+ "valid": false+ },+ {+ "name": "replace-room-private-password",+ "schema": "replaceRoomRequest",+ "json": "{\"codeEntryPolicy\":\"private\",\"roomPassword\":\"room-password\"}",+ "valid": true+ },+ {+ "name": "replace-room-open",+ "schema": "replaceRoomRequest",+ "json": "{\"codeEntryPolicy\":\"open\"}",+ "valid": true+ },+ {+ "name": "replace-room-preferred-code",+ "schema": "replaceRoomRequest",+ "json": "{\"codeEntryPolicy\":\"open\",\"preferredRoomId\":\"4321\"}",+ "valid": false+ },+ {+ "name": "replace-room-missing-policy",+ "schema": "replaceRoomRequest",+ "json": "{}",+ "valid": false+ },+ {+ "name": "room-access-set-code-entry-policy-open",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"set-code-entry-policy\",\"policy\":\"open\"}",+ "valid": true+ },+ {+ "name": "room-access-set-code-entry-policy-private",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"set-code-entry-policy\",\"policy\":\"private\"}",+ "valid": true+ },+ {+ "name": "room-access-set-code-entry-policy-disabled",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"set-code-entry-policy\",\"policy\":\"disabled\"}",+ "valid": false+ },+ {+ "name": "room-access-rotate-viewer-grant",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"rotate-viewer-grant\"}",+ "valid": true+ },+ {+ "name": "room-access-rotate-viewer-grant-extra-key",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"rotate-viewer-grant\",\"policy\":\"open\"}",+ "valid": false+ },+ {+ "name": "room-access-revoke-viewer-grant",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"revoke-viewer-grant\"}",+ "valid": true+ },+ {+ "name": "room-access-set-viewer-password",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"set-viewer-password\",\"password\":\"simple-password\"}",+ "valid": true+ },+ {+ "name": "room-access-clear-viewer-password",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"set-viewer-password\",\"password\":null}",+ "valid": true+ },+ {+ "name": "room-access-missing-password-key",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"set-viewer-password\"}",+ "valid": false+ },+ {+ "name": "room-access-long-password",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"set-viewer-password\",\"password\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}",+ "valid": false+ },+ {+ "name": "room-access-unknown-action",+ "schema": "roomAccessUpdateRequest",+ "json": "{\"action\":\"disable-room\"}",+ "valid": false+ }+ ],+ "serverMessages": [+ {+ "name": "authenticated-host-minimal",+ "json": "{\"type\":\"authenticated\",\"protocol\":\"screener-v21\",\"peerId\":\"host_12345678\",\"roomExpiresAt\":\"2026-08-18T18:00:00.000Z\",\"maxViewers\":8,\"endpointMediaCopyCapacity\":2,\"hostOnline\":true,\"connectionId\":null,\"iceConfig\":{\"iceServers\":[],\"natPredictionStunUrls\":[]},\"routePolicy\":{\"peerOnly\":false,\"topologyOptimization\":true,\"natPrediction\":false},\"codeEntryPolicy\":\"open\",\"viewerAuthorizationGeneration\":\"viewer_generation_12345678\",\"mediaMode\":\"peer-assisted\",\"shareGeneration\":\"share_generation_12345678\",\"routeRevision\":0,\"routeAssignment\":{\"upstream\":{\"kind\":\"none\"},\"childPeerIds\":[],\"sfuPublicationGeneration\":null},\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\",\"screenAudioQuality\":\"music\"},\"role\":\"host\",\"viewerPasswordEnabled\":false}"+ },+ {+ "name": "authenticated-host-full",+ "json": "{\"type\":\"authenticated\",\"protocol\":\"screener-v21\",\"peerId\":\"host_12345678\",\"roomExpiresAt\":null,\"maxViewers\":8,\"endpointMediaCopyCapacity\":2,\"hostOnline\":true,\"connectionId\":\"connection_12345678\",\"iceConfig\":{\"iceServers\":[{\"urls\":\"stun:stun.example.test:3478\"},{\"urls\":[\"stun:stun-1.example.test:3478\",\"stun:[2001:db8::1]:3478\"]}],\"natPredictionStunUrls\":[\"stun:nat.example.test:3478\"]},\"routePolicy\":{\"peerOnly\":false,\"topologyOptimization\":true,\"natPrediction\":false},\"codeEntryPolicy\":\"open\",\"viewerAuthorizationGeneration\":\"viewer_generation_12345678\",\"mediaMode\":\"peer-assisted\",\"shareGeneration\":\"share_generation_12345678\",\"routeRevision\":0,\"routeAssignment\":{\"upstream\":{\"kind\":\"sfu\"},\"childPeerIds\":[],\"sfuPublicationGeneration\":\"generation_12345678\"},\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\",\"screenAudioQuality\":\"music\"},\"sfuStandbyUrl\":\"wss://sfu.example.test\",\"role\":\"host\",\"viewerPasswordEnabled\":false}"+ },+ {+ "name": "authenticated-viewer-minimal",+ "json": "{\"type\":\"authenticated\",\"protocol\":\"screener-v21\",\"peerId\":\"viewer_12345678\",\"roomExpiresAt\":\"2026-08-18T18:00:00.000Z\",\"maxViewers\":8,\"endpointMediaCopyCapacity\":2,\"hostOnline\":true,\"hostPaused\":false,\"connectionId\":null,\"iceConfig\":{\"iceServers\":[],\"natPredictionStunUrls\":[]},\"routePolicy\":{\"peerOnly\":false,\"topologyOptimization\":true,\"natPrediction\":false},\"codeEntryPolicy\":\"open\",\"viewerAuthorizationGeneration\":\"viewer_generation_12345678\",\"mediaMode\":\"peer-assisted\",\"shareGeneration\":\"share_generation_12345678\",\"routeRevision\":0,\"routeAssignment\":{\"upstream\":{\"kind\":\"none\"},\"childPeerIds\":[],\"sfuPublicationGeneration\":null},\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\",\"screenAudioQuality\":\"music\"},\"role\":\"viewer\"}"+ },+ {+ "name": "authenticated-viewer-full",+ "json": "{\"type\":\"authenticated\",\"protocol\":\"screener-v21\",\"peerId\":\"viewer_12345678\",\"roomExpiresAt\":\"2026-08-18T18:00:00.000Z\",\"maxViewers\":8,\"endpointMediaCopyCapacity\":2,\"hostOnline\":true,\"hostPaused\":true,\"connectionId\":\"connection_12345678\",\"iceConfig\":{\"iceServers\":[],\"natPredictionStunUrls\":[]},\"routePolicy\":{\"peerOnly\":false,\"topologyOptimization\":true,\"natPrediction\":false},\"codeEntryPolicy\":\"open\",\"viewerAuthorizationGeneration\":\"viewer_generation_12345678\",\"mediaMode\":\"peer-assisted\",\"shareGeneration\":\"share_generation_12345678\",\"routeRevision\":0,\"routeAssignment\":{\"upstream\":{\"kind\":\"peer\",\"peerId\":\"parent_12345678\"},\"childPeerIds\":[\"child_12345678\",\"child_87654321\"],\"sfuPublicationGeneration\":null},\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\",\"screenAudioQuality\":\"music\"},\"sfuStandbyUrl\":\"wss://sfu.example.test\",\"role\":\"viewer\"}"+ },+ {+ "name": "signaling-challenge-response",+ "json": "{\"type\":\"signaling-challenge-response\",\"sequence\":0}"+ },+ {+ "name": "signal-description",+ "json": "{\"type\":\"signal\",\"fromPeerId\":\"host_12345678\",\"payload\":{\"kind\":\"description\",\"connectionId\":\"connection_12345678\",\"description\":{\"type\":\"offer\",\"sdp\":\"v=0\\r\\n\"}}}"+ },+ {+ "name": "signal-candidate-full",+ "json": "{\"type\":\"signal\",\"fromPeerId\":\"host_12345678\",\"payload\":{\"kind\":\"candidate\",\"connectionId\":\"connection_12345678\",\"candidate\":{\"candidate\":\"candidate:1 1 udp 1 203.0.113.1 50000 typ host\",\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":null}}}"+ },+ {+ "name": "signal-candidate-end",+ "json": "{\"type\":\"signal\",\"fromPeerId\":\"host_12345678\",\"payload\":{\"kind\":\"candidate\",\"connectionId\":\"connection_12345678\",\"candidate\":null}}"+ },+ {+ "name": "restart-request",+ "json": "{\"type\":\"restart-request\",\"fromPeerId\":\"viewer_12345678\",\"connectionId\":\"connection_12345678\",\"rebuild\":true}"+ },+ {+ "name": "route-update-prepare",+ "json": "{\"type\":\"route-update\",\"revision\":9,\"phase\":\"prepare\",\"assignment\":{\"upstream\":{\"kind\":\"peer\",\"peerId\":\"parent_12345678\"},\"childPeerIds\":[\"child_12345678\",\"child_87654321\"],\"sfuPublicationGeneration\":null},\"candidate\":{\"childPeerId\":\"child_12345678\",\"connectionId\":\"connection_12345678\",\"transport\":\"direct\",\"qualityProbe\":false}}"+ },+ {+ "name": "route-update-prepare-with-attempt",+ "json": "{\"type\":\"route-update\",\"revision\":10,\"phase\":\"prepare\",\"assignment\":{\"upstream\":{\"kind\":\"sfu\"},\"childPeerIds\":[],\"sfuPublicationGeneration\":\"generation_12345678\"},\"candidate\":{\"childPeerId\":\"child_12345678\",\"connectionId\":\"connection_12345678\",\"transport\":\"sfu\",\"qualityProbe\":true,\"connectionAttempt\":{\"current\":2,\"total\":3}}}"+ },+ {+ "name": "route-update-active",+ "json": "{\"type\":\"route-update\",\"revision\":11,\"phase\":\"active\",\"assignment\":{\"upstream\":{\"kind\":\"none\"},\"childPeerIds\":[],\"sfuPublicationGeneration\":null}}"+ },+ {+ "name": "route-status-waiting",+ "json": "{\"type\":\"route-status\",\"revision\":3,\"state\":\"waiting\",\"reason\":\"sfu-admission\"}"+ },+ {+ "name": "route-status-failed",+ "json": "{\"type\":\"route-status\",\"revision\":4,\"state\":\"failed\",\"reason\":\"route-exhausted\"}"+ },+ {+ "name": "route-diagnostic-snapshot-empty",+ "json": "{\"type\":\"route-diagnostic-snapshot\",\"snapshot\":{\"children\":[],\"operation\":null}}"+ },+ {+ "name": "route-diagnostic-snapshot",+ "json": "{\"type\":\"route-diagnostic-snapshot\",\"snapshot\":{\"children\":[{\"ordinal\":1,\"parent\":{\"kind\":\"host\"},\"effectiveCapacity\":2,\"childCount\":1,\"demandAgeMs\":100,\"queueWaitMs\":10,\"candidateStartMs\":20,\"firstDecodedFrameMs\":80,\"finalMs\":80,\"finalRoute\":\"direct\",\"rejectionBucket\":\"none\",\"quality\":{\"eligibleWindows\":3,\"eligibleDurationMs\":6000,\"freezeWindows\":1,\"freezeCount\":1,\"freezeDurationMs\":250,\"pauseCount\":0,\"pauseDurationMs\":0}},{\"ordinal\":2,\"parent\":{\"kind\":\"viewer\",\"ordinal\":1},\"effectiveCapacity\":0,\"childCount\":0,\"demandAgeMs\":90,\"queueWaitMs\":null,\"candidateStartMs\":null,\"firstDecodedFrameMs\":null,\"finalMs\":null,\"finalRoute\":\"waiting\",\"rejectionBucket\":\"sfu-admission\",\"quality\":null}],\"operation\":{\"childOrdinal\":2,\"reason\":\"join\",\"stage\":\"admission\",\"cursor\":1,\"candidateCount\":2}}}"+ },+ {+ "name": "sfu-config",+ "json": "{\"type\":\"sfu-config\",\"revision\":9,\"url\":\"wss://sfu.example.test\",\"token\":\"header.payload.signature\"}"+ },+ {+ "name": "quality-settings",+ "json": "{\"type\":\"quality-settings\",\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\",\"screenAudioQuality\":\"music\"}}"+ },+ {+ "name": "quality-settings-without-audio",+ "json": "{\"type\":\"quality-settings\",\"qualitySettings\":{\"resolution\":\"1080p\",\"maxFramerate\":60,\"maxBitrate\":8000000,\"degradationPreference\":\"maintain-resolution\"}}"+ },+ {+ "name": "route-policy",+ "json": "{\"type\":\"route-policy\",\"shareGeneration\":\"share_generation_12345678\",\"routePolicy\":{\"peerOnly\":false,\"topologyOptimization\":true,\"natPrediction\":false},\"sfuStandbyUrl\":\"wss://sfu.example.test\"}"+ },+ {+ "name": "route-policy-peer-only",+ "json": "{\"type\":\"route-policy\",\"shareGeneration\":\"share_generation_12345678\",\"routePolicy\":{\"peerOnly\":true,\"topologyOptimization\":true,\"natPrediction\":false}}"+ },+ {+ "name": "pause-sharing-source",+ "json": "{\"type\":\"pause-sharing-source\",\"shareGeneration\":\"share_generation_12345678\"}"+ },+ {+ "name": "viewer-quality-evidence-peer",+ "json": "{\"type\":\"viewer-quality-evidence\",\"viewerPeerId\":\"viewer_12345678\",\"upstream\":{\"kind\":\"peer\",\"peerId\":\"host_12345678\"},\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":0,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":1920,\"height\":1080,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":\"video/H264\",\"codecProfile\":\"profile-level-id=42e01f\",\"codecParameters\":\"packetization-mode=1; level-asymmetry-allowed=1\",\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}"+ },+ {+ "name": "viewer-quality-evidence-sfu",+ "json": "{\"type\":\"viewer-quality-evidence\",\"viewerPeerId\":\"viewer_12345678\",\"upstream\":{\"kind\":\"sfu\"},\"guard\":{\"connectionId\":\"connection_12345678\",\"routeRevision\":0,\"presentationEpoch\":0},\"sequence\":1,\"windowMs\":2000,\"metrics\":{\"natTraversalPath\":\"ordinary\",\"width\":null,\"height\":null,\"framesPerSecond\":59.8,\"bitrateKbps\":7500,\"packetsReceivedDelta\":1500,\"packetsLostDelta\":2,\"rttMs\":18,\"jitterMs\":3.5,\"framesDecodedDelta\":120,\"framesDroppedDelta\":1,\"decodeMsPerFrame\":2.4,\"freezeCountDelta\":0,\"freezeDurationMsDelta\":0,\"pauseCountDelta\":0,\"pauseDurationMsDelta\":0,\"codec\":null,\"codecProfile\":null,\"codecParameters\":null,\"audioBitrateKbps\":192,\"audioPacketLossPercent\":0.2,\"audioJitterMs\":2.5,\"audioVideoPlayoutDeltaMs\":-12.5,\"videoJitterBufferDelayMs\":24,\"audioJitterBufferDelayMs\":18,\"audioConcealedSamplesPercent\":1,\"audioConcealmentEventsDelta\":3,\"audioCodec\":\"audio/opus\"}}"+ },+ {+ "name": "host-status-online",+ "json": "{\"type\":\"host-status\",\"online\":true,\"paused\":false}"+ },+ {+ "name": "viewer-presence-empty",+ "json": "{\"type\":\"viewer-presence\",\"viewers\":[]}"+ },+ {+ "name": "viewer-presence",+ "json": "{\"type\":\"viewer-presence\",\"viewers\":[{\"role\":\"host\",\"peerId\":\"host_12345678\",\"displayName\":\"分享者\",\"upstream\":{\"kind\":\"none\"}},{\"role\":\"viewer\",\"peerId\":\"viewer_12345678\",\"displayName\":\"小明\",\"upstream\":{\"kind\":\"peer\",\"peerId\":\"host_12345678\"},\"mediaReady\":true},{\"role\":\"viewer\",\"peerId\":\"viewer_87654321\",\"displayName\":\"观众\",\"upstream\":{\"kind\":\"none\"}}]}"+ },+ {+ "name": "viewer-grant-revoked",+ "json": "{\"type\":\"viewer-grant-revoked\",\"viewerAuthorizationGeneration\":\"viewer_generation_12345678\"}"+ },+ {+ "name": "sharing-stopped",+ "json": "{\"type\":\"sharing-stopped\"}"+ },+ {+ "name": "room-closed-host-ended",+ "json": "{\"type\":\"room-closed\",\"reason\":\"host-ended\"}"+ },+ {+ "name": "room-closed-expired",+ "json": "{\"type\":\"room-closed\",\"reason\":\"expired\"}"+ },+ {+ "name": "error",+ "json": "{\"type\":\"error\",\"code\":\"ROOM_FULL\",\"message\":\"Room is full\"}"+ }+ ]+}diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.tsindex 3f65d512..65479223 100644--- a/tests/host-peer-tracks.test.ts+++ b/tests/host-peer-tracks.test.ts@@ -5,15 +5,19 @@ import {type QualityProfile,} from "../src/client/media/quality.ts";import { HostProvisionalChild } from "../src/client/media/host-provisional-child.ts";-import type { PeerSnapshot } from "../src/client/types.ts";-import { HostPeer } from "../src/client/webrtc/host-peer.ts";+import { EMPTY_METRICS, type PeerSnapshot } from "../src/client/types.ts";+import { HostPeer, type HostMediaPeer } from "../src/client/webrtc/host-peer.ts";import {automaticVideoCodecPreference,manualVideoCodecPreference,type BrowserVideoCodecPreference,VP8_ONLY_VIDEO_CODEC,} from "../src/client/webrtc/video-codec.ts";-import { ViewerRelay } from "../src/client/webrtc/viewer-relay.ts";+import {+ ViewerRelay,+ type ViewerRelayPeerEvents,+ type ViewerRelayPeerFactory,+} from "../src/client/webrtc/viewer-relay.ts";import { setCopy } from "../src/client/ui/copy.ts";import type {IceConfig,@@ -2010,6 +2014,88 @@ describe("ViewerRelay downstream ownership", () => {relay.dispose();});+ it("binds native relay children so their signalling and snapshots stay owned", async () => {+ const stubs = new Map<+ string,+ { peer: HostMediaPeer; events: ViewerRelayPeerEvents }+ >();+ const nativeSnapshot = (peer: HostMediaPeer): PeerSnapshot => ({+ peerId: peer.peerId,+ connectionId: peer.connectionId,+ connectionState: "connected",+ iceConnectionState: "connected",+ metrics: { ...EMPTY_METRICS },+ error: null,+ });+ const peerFactory: ViewerRelayPeerFactory = {+ requiresStream: false,+ create: (childPeerId, connectionId, events) => {+ const edgeConnectionId = connectionId ?? `native-${childPeerId}`;+ const peer: HostMediaPeer = {+ peerId: childPeerId,+ connectionId: edgeConnectionId,+ start: async () =>+ events.sendSignal(childPeerId, {+ kind: "description",+ connectionId: edgeConnectionId,+ description: { type: "offer", sdp: "native-offer" },+ }),+ acceptSignal: async () => undefined,+ restartIce: async () => true,+ isConnected: () => true,+ getSnapshot: () => nativeSnapshot(peer),+ updateIceConfig: () => undefined,+ updateProfile: async () => true,+ updateCaptureProfile: async () => true,+ setPaused: () => undefined,+ replaceStream: async () => true,+ dispose: () => undefined,+ };+ stubs.set(childPeerId, { peer, events });+ return peer;+ },+ };+ const onSenderUpdate = vi.fn();+ const relay = new ViewerRelay(+ { iceServers: [] },+ QUALITY_PROFILES["720p30"],+ { sendSignal: () => true, onSenderUpdate },+ 2,+ false,+ peerFactory,+ );++ relay.setChildren(["native-a"]);+ await vi.waitFor(() => expect(stubs.has("native-a")).toBe(true));+ expect(+ relay.prepareChild(7, routeCandidate(7, "native-b"), [+ "native-a",+ "native-b",+ ]),+ ).toBe(true);+ await vi.waitFor(() => expect(stubs.has("native-b")).toBe(true));+ const active = stubs.get("native-a")!;+ const prepared = stubs.get("native-b")!;++ expect(+ active.events.sendSignal("native-a", {+ kind: "candidate",+ connectionId: active.peer.connectionId,+ candidate: { candidate: "late-candidate" },+ }),+ ).toBe(true);+ prepared.events.onUpdate(nativeSnapshot(prepared.peer));+ expect(onSenderUpdate).toHaveBeenLastCalledWith(+ expect.objectContaining({ peerId: "native-b" }),+ 7,+ );++ relay.activateChildren(7, ["native-a", "native-b"]);+ prepared.events.onUpdate({ ...nativeSnapshot(prepared.peer), error: "late" });+ expect(relay.getSnapshot("native-b")?.error).toBe("late");+ relay.dispose();+ });+it("replaces one active child with a same-parent prepared connection", async () => {const signals: Array<{ peerId: string; connectionId: string }> = [];const relay = new ViewerRelay(diff --git a/tests/hybrid-media-router.test.ts b/tests/hybrid-media-router.test.tsdeleted file mode 100644index 31702002..00000000--- a/tests/hybrid-media-router.test.ts+++ /dev/null@@ -1,2598 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import type { RoutePolicy, ServerMessage } from "../src/shared/protocol.ts";-import {- HybridMediaRouter,- type AuthenticatedRouteParticipant,- type HybridAuthenticationState,-} from "../src/server/hybrid-media-router.ts";-import { RoomStore, type CreatedRoom } from "../src/server/room-store.ts";-import { SfuResourceAdmission } from "../src/server/sfu-resource-admission.ts";-import { FakeSfuRoomControl } from "./fake-sfu-room-control.ts";--const SHARE_GENERATION = "share_generation_12345678";--function senderDiagnostics(state: "unknown" | "healthy" | "degraded") {- return {- natTraversalPath: "unknown",- reason:- state === "unknown" ? null : state === "healthy" ? "none" : "bandwidth",- framesPerSecond: null,- bitrateKbps: null,- } as const;-}--function createStore(maxViewersPerRoom = 20) {- return new RoomStore({- leaseMs: 60_000,- maxRooms: 4,- maxViewersPerRoom,- });-}--function connectHost(- store: RoomStore,- room: CreatedRoom,- routePolicy?: RoutePolicy,- clientId = "host_client_12345678",- sessionId = "host_session_12345678",-) {- const connected = store.connectParticipant({- roomId: room.roomId,- role: "host",- token: room.hostToken,- clientId,- sessionId,- });- return {- roomId: room.roomId,- role: "host" as const,- peerId: connected.peerId,- sessionId,- ...(routePolicy ? { routePolicy } : {}),- };-}--function connectViewer(- store: RoomStore,- room: CreatedRoom,- suffix: string,-): AuthenticatedRouteParticipant {- const connected = store.connectParticipant({- roomId: room.roomId,- role: "viewer",- ...(room.viewerGrant ? { viewerGrant: room.viewerGrant } : {}),- clientId: `viewer_client_${suffix}_12345678`,- sessionId: `viewer_session_${suffix}_12345678`,- });- return {- roomId: room.roomId,- role: "viewer",- peerId: connected.peerId,- sessionId: `viewer_session_${suffix}_12345678`,- };-}--function complete(- router: HybridMediaRouter,- participant: AuthenticatedRouteParticipant,-): HybridAuthenticationState {- const state = router.connectParticipant(participant);- router.completeAuthentication(participant, state);- return state;-}--function preparedFor(- sent: Map<string, ServerMessage[]>,- sessionId: string,-) {- return sent- .get(sessionId)- ?.findLast(- (message): message is Extract<ServerMessage, { type: "route-update"; phase: "prepare" }> =>- message.type === "route-update" && message.phase === "prepare",- );-}--function activeAfter(- sent: Map<string, ServerMessage[]>,- sessionId: string,- revision: number,-) {- return sent- .get(sessionId)- ?.findLast(- (message): message is Extract<ServerMessage, { type: "route-update"; phase: "active" }> =>- message.type === "route-update" &&- message.phase === "active" &&- message.revision > revision,- );-}--function deferred(): {- promise: Promise<void>;- resolve: () => void;- reject: (reason?: unknown) => void;-} {- let resolve!: () => void;- let reject!: (reason?: unknown) => void;- const promise = new Promise<void>((settle, fail) => {- resolve = settle;- reject = fail;- });- return { promise, resolve, reject };-}--function deferredValue<T>(): {- promise: Promise<T>;- resolve: (value: T) => void;-} {- let resolve!: (value: T) => void;- const promise = new Promise<T>((settle) => {- resolve = settle;- });- return { promise, resolve };-}--function harness(- endpointMediaCopyCapacity: 1 | 2 | 3,- withSfu = false,- prepareTimeoutMs?: number,- sfuIngressCapacity = 2,- drainRetryMs?: number,- hostOfflineCheckMs?: number,-) {- const store = createStore();- const sent = new Map<string, ServerMessage[]>();- const connections = new Map<string, string>();- const admission = withSfu- ? new SfuResourceAdmission({- ingressCapacity: sfuIngressCapacity,- egressCapacity: 20,- })- : undefined;- const roomControl = withSfu ? new FakeSfuRoomControl() : undefined;- const onRoutesChanged = vi.fn();- let nextTokenIssueError: Error | null = null;- const router = new HybridMediaRouter({- roomStore: store,- endpointMediaCopyCapacity,- ...(admission && roomControl- ? {- sfuFallback: {- url: "wss://sfu.example.test",- admission,- roomControl,- ...(prepareTimeoutMs ? { prepareTimeoutMs } : {}),- ...(drainRetryMs ? { drainRetryMs } : {}),- ...(hostOfflineCheckMs ? { hostOfflineCheckMs } : {}),- tokenIssuer: {- async issueToken({ peerId }) {- if (nextTokenIssueError) {- const error = nextTokenIssueError;- nextTokenIssueError = null;- throw error;- }- return `token-${peerId}`;- },- },- },- }- : {}),- sendToSession(sessionId, message) {- const messages = sent.get(sessionId) ?? [];- messages.push(message);- sent.set(sessionId, messages);- },- getConnectionId(roomId, viewerPeerId) {- return connections.get(`${roomId}:${viewerPeerId}`);- },- setConnectionId(roomId, viewerPeerId, connectionId) {- connections.set(`${roomId}:${viewerPeerId}`, connectionId);- },- deleteConnectionId(roomId, viewerPeerId) {- connections.delete(`${roomId}:${viewerPeerId}`);- },- getShareGeneration: () => SHARE_GENERATION,- onRoutesChanged,- });- return {- store,- sent,- connections,- admission,- roomControl,- onRoutesChanged,- failNextTokenIssue() {- nextTokenIssueError = new Error("token issue failed");- },- router,- };-}--async function establishSfuRoom(- store: RoomStore,- sent: Map<string, ServerMessage[]>,- router: HybridMediaRouter,- room: CreatedRoom,-) {- const host = connectHost(store, room);- complete(router, host);- const first = connectViewer(store, room, `sfu-root-${room.roomId}`);- complete(router, first);- await vi.waitFor(() => expect(preparedFor(sent, first.sessionId)).toBeDefined());- const firstDirect = preparedFor(sent, first.sessionId)!;- router.handleRouteReady(first, {- type: "route-ready",- revision: firstDirect.revision,- phase: "prepare",- });- const second = connectViewer(store, room, `sfu-leaf-${room.roomId}`);- complete(router, second);- await vi.waitFor(() =>- expect(preparedFor(sent, first.sessionId)?.candidate.transport).toBe("sfu"),- );- const firstSfu = preparedFor(sent, first.sessionId)!;- router.handleRouteReady(first, {- type: "route-ready",- revision: firstSfu.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(preparedFor(sent, second.sessionId)?.candidate.transport).toBe("sfu"),- );- const secondSfu = preparedFor(sent, second.sessionId)!;- router.handleRouteReady(second, {- type: "route-ready",- revision: secondSfu.revision,- phase: "prepare",- });- return { host, first, second };-}--describe("HybridMediaRouter v9 runtime", () => {- it("logs only aggregate candidate origin for route signals", async () => {- const { router } = harness(2);- const debug = vi.spyOn(- router as unknown as {- debug(- roomId: string,- event: string,- details: Record<string, unknown>,- ): void;- },- "debug",- );- try {- router.debugPeerSignal({- roomId: "1234",- sourcePeerId: "source_12345678",- targetPeerId: "target_12345678",- signalKind: "candidate",- candidateOrigin: "predicted",- authorization: "probe",- });- expect(debug).toHaveBeenCalledWith(- "1234",- "peer-signal",- expect.objectContaining({- candidateOrigin: "predicted",- signalKind: "candidate",- authorization: "probe",- }),- );- } finally {- await router.close();- }- });-- it("projects exact endpoint copy context from the current snapshot", async () => {- const { router } = harness(2);- const internal = router as unknown as {- qualityCopyContext(- snapshot: unknown,- hostPeerId: string,- observedPeerId: string,- endpointCapacity: number,- sample: unknown,- ): Record<string, unknown>;- };- const edge = (parentPeerId: string, connectionId: string) => ({- kind: "peer", childSessionId: "child-session", parentPeerId,- parentSessionId: "parent-session", transport: "direct", connectionId,- usable: true, physicalActive: true,- });- const operation = (tuple: unknown, transition: unknown) => ({- childPeerId: "candidate", childSessionId: "candidate-session",- demandPeerId: "candidate", reason: "quality-convergence",- baseRevision: 7, factVersion: 1, candidates: [{ tuple, endpointTransition: transition }],- cursor: 0, deadlineAtMs: 20_000, wakeAtMs: 20_000,- current: { tuple, revision: 8, connectionId: "candidate-connection" },- });- const snapshot = (- upstreamByViewer: Map<string, unknown>,- op?: unknown,- hostPublication: unknown = null,- ) => ({- revision: 7, paused: false, factVersion: 1, upstreamByViewer,- hostPublication, ...(op ? { operation: op } : {}),- });- const project = (- state: unknown,- observedPeerId: string,- endpointCapacity: number,- sample: unknown,- ) => internal.qualityCopyContext(- state, "host", observedPeerId, endpointCapacity, sample,- );- const hostEdges = new Map<string, unknown>([- ["a", edge("host", "a-connection")],- ["b", edge("host", "b-connection")],- ]);- const peerCandidate = {- kind: "peer", parentPeerId: "host", transport: "direct",- };- const sfuSample = {- kind: "sfu", routeRevision: 8,- publicationGeneration: "publication", hostSessionId: "host-session",- };- const publication = {- generation: "publication", hostSessionId: "host-session",- connectionId: "publication-connection", usable: true,- physicalActive: true, resource: {},- };-- try {- expect(project(- snapshot(hostEdges, operation(peerCandidate, {- kind: "overlap", producerPeerId: "host",- })),- "host", 2,- { kind: "peer", childPeerId: "candidate", routeRevision: 8,- connectionId: "candidate-connection" },- )).toMatchObject({- committedCopies: 2, candidateReservedCopies: 1, possibleCopies: 3,- endpointCapacity: 2, operationReason: "quality-convergence",- candidateTransition: "overlap", sampleRole: "candidate",- });-- const oneHostEdge = new Map<string, unknown>([- ["a", edge("host", "a-connection")],- ]);- const sfuCases = [- {- state: snapshot(hostEdges, operation(- { kind: "sfu", publication: "create" },- { kind: "overlap", producerPeerId: "host" },- )),- expected: { committedCopies: 2, candidateReservedCopies: 1,- possibleCopies: 3, candidateTransition: "overlap" },- },- {- state: snapshot(oneHostEdge, operation(- { kind: "sfu", publication: "reuse" }, { kind: "none" },- ), publication),- expected: { committedCopies: 2, candidateReservedCopies: 0,- possibleCopies: 2, candidateTransition: "none" },- },- ];- for (const testCase of sfuCases) {- expect(project(testCase.state, "host", 2, sfuSample)).toMatchObject({- ...testCase.expected, sampleRole: "candidate",- });- }-- const relayEdges = new Map<string, unknown>([- ["a", edge("relay", "relay-a")],- ["b", edge("relay", "relay-b")],- ]);- const relaySample = {- kind: "peer", childPeerId: "a", routeRevision: 7,- connectionId: "relay-a",- };- expect(project(snapshot(relayEdges), "relay", 3, relaySample)).toMatchObject({- committedCopies: 2, candidateReservedCopies: 0, possibleCopies: 2,- endpointCapacity: 3, sampleRole: "active",- });- expect(project(- snapshot(relayEdges), "relay", 3,- { ...relaySample, routeRevision: 6 },- ).sampleRole).toBe("unknown");- } finally {- await router.close();- }- });-- it("keeps the controller diagnostic label until a departed relay is pruned", async () => {- const { store, sent, router } = harness(2);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const parent = connectViewer(store, room, "diagnostic-label-parent");- complete(router, parent);- const parentPrepare = await vi.waitFor(() => {- const prepared = preparedFor(sent, parent.sessionId);- expect(prepared).toBeDefined();- return prepared!;- });- router.handleRouteReady(parent, {- type: "route-ready",- revision: parentPrepare.revision,- phase: "prepare",- });- router.setViewerRelayCapacity(parent, 1);-- const temporaryRoot = connectViewer(- store,- room,- "diagnostic-label-temporary-root",- );- complete(router, temporaryRoot);- const temporaryPrepare = await vi.waitFor(() => {- const prepared = preparedFor(sent, temporaryRoot.sessionId);- expect(prepared?.assignment.upstream).toEqual({- kind: "peer",- peerId: host.peerId,- });- return prepared!;- });- router.handleRouteReady(temporaryRoot, {- type: "route-ready",- revision: temporaryPrepare.revision,- phase: "prepare",- });-- const child = connectViewer(store, room, "diagnostic-label-child");- complete(router, child);- const childPrepare = await vi.waitFor(() => {- const prepared = preparedFor(sent, child.sessionId);- expect(prepared?.assignment.upstream).toEqual({- kind: "peer",- peerId: parent.peerId,- });- return prepared!;- });- router.handleRouteReady(child, {- type: "route-ready",- revision: childPrepare.revision,- phase: "prepare",- });-- store.disconnectParticipant(- room.roomId,- temporaryRoot.peerId,- temporaryRoot.sessionId,- );- router.disconnectParticipant(- room.roomId,- temporaryRoot.peerId,- temporaryRoot.sessionId,- );- router.removeViewer(room.roomId, temporaryRoot.peerId);- await vi.waitFor(() =>- expect(- router.resolveActiveViewerMediaEdge(- room.roomId,- temporaryRoot.peerId,- ),- ).toBeUndefined(),- );-- const internal = router as unknown as {- debugPeer(roomId: string, peerId: string): string;- };- const label = internal.debugPeer(room.roomId, parent.peerId);-- store.disconnectParticipant(- room.roomId,- parent.peerId,- parent.sessionId,- );- router.disconnectParticipant(- room.roomId,- parent.peerId,- parent.sessionId,- );- router.removeViewer(room.roomId, parent.peerId);- expect(internal.debugPeer(room.roomId, parent.peerId)).toBe(label);-- const recovery = await vi.waitFor(() => {- const prepared = preparedFor(sent, child.sessionId);- expect(prepared?.revision).toBeGreaterThan(childPrepare.revision);- expect(prepared?.assignment.upstream).toEqual({- kind: "peer",- peerId: host.peerId,- });- return prepared!;- });- router.handleRouteReady(child, {- type: "route-ready",- revision: recovery.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(internal.debugPeer(room.roomId, parent.peerId)).toBe(- "viewer-unknown",- ),- );- } finally {- await router.close();- }- });-- it("maps an exact Host active failure to its committed direct edge", async () => {- const { store, sent, router } = harness(2);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const viewer = connectViewer(store, room, "host-edge-failure");- complete(router, viewer);- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)).toBeDefined(),- );- const prepared = preparedFor(sent, viewer.sessionId)!;- router.handleRouteReady(viewer, {- type: "route-ready",- revision: prepared.revision,- phase: "prepare",- });- const active = router.resolveActiveViewerMediaEdge(- room.roomId,- viewer.peerId,- )!;-- router.handleRouteFailed(host, {- type: "route-failed",- revision: active.revision,- phase: "active",- connectionId: active.connectionId,- });-- await vi.waitFor(() =>- expect(- sent- .get(viewer.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({- state: "failed",- reason: "route-exhausted",- }),- );- } finally {- await router.close();- }- });-- it("rebinds a replacement Host and clears offline Viewer media ownership", async () => {- const { store, sent, connections, router } = harness(2);- try {- const room = await store.createRoom();- const previousHost = connectHost(store, room);- complete(router, previousHost);- const viewer = connectViewer(store, room, "host-rebind-offline-viewer");- complete(router, viewer);- const prepared = await vi.waitFor(() => {- const message = preparedFor(sent, viewer.sessionId);- expect(message).toBeDefined();- return message!;- });- router.handleRouteReady(viewer, {- type: "route-ready",- revision: prepared.revision,- phase: "prepare",- });- router.setViewerRelayCapacity(viewer, 1);- await vi.waitFor(() =>- expect(connections.has(`${room.roomId}:${viewer.peerId}`)).toBe(true),- );-- store.disconnectParticipant(room.roomId, viewer.peerId, viewer.sessionId);- router.disconnectParticipant(room.roomId, viewer.peerId, viewer.sessionId);- store.disconnectParticipant(- room.roomId,- previousHost.peerId,- previousHost.sessionId,- );- router.disconnectParticipant(- room.roomId,- previousHost.peerId,- previousHost.sessionId,- );-- const resumedHost = connectHost(- store,- room,- undefined,- "replacement-host-client",- "replacement-host-session",- );- expect(resumedHost.peerId).not.toBe(previousHost.peerId);- complete(router, resumedHost);- expect(connections.has(`${room.roomId}:${viewer.peerId}`)).toBe(false);-- const reconnectedViewer = connectViewer(- store,- room,- "host-rebind-offline-viewer",- );- expect(reconnectedViewer.peerId).toBe(viewer.peerId);- router.connectParticipant(reconnectedViewer);- expect(- router- .routeDiagnosticSnapshot(room.roomId)- .children.find((child) => child.effectiveCapacity === 1),- ).toBeDefined();- } finally {- await router.close();- }- });-- it("accepts active failure for a direct connection adopted during rebuild", async () => {- const { store, sent, router } = harness(2);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const viewer = connectViewer(store, room, "rebuilt-edge-failure");- complete(router, viewer);- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)).toBeDefined(),- );- const prepared = preparedFor(sent, viewer.sessionId)!;- router.handleRouteReady(viewer, {- type: "route-ready",- revision: prepared.revision,- phase: "prepare",- });- const active = router.resolveActiveViewerMediaEdge(- room.roomId,- viewer.peerId,- )!;- const rebuiltConnectionId = "rebuilt_connection_12345678";- expect(- router.peerSignalAuthorization({- roomId: room.roomId,- sourcePeerId: host.peerId,- sourceSessionId: host.sessionId,- targetPeerId: viewer.peerId,- targetSessionId: viewer.sessionId,- connectionId: rebuiltConnectionId,- signalKind: "description",- descriptionType: "offer",- }),- ).toBe(true);- expect(- router.resolveActiveViewerMediaEdge(room.roomId, viewer.peerId),- ).toMatchObject({- revision: active.revision,- connectionId: rebuiltConnectionId,- });-- router.handleRouteFailed(viewer, {- type: "route-failed",- revision: active.revision,- phase: "active",- connectionId: rebuiltConnectionId,- });-- await vi.waitFor(() =>- expect(- sent- .get(viewer.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({- state: "failed",- reason: "route-exhausted",- }),- );- } finally {- await router.close();- }- });-- it("keeps committed-edge signaling authorized during another Peer candidate", async () => {- const { store, sent, router } = harness(2);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);-- const roots = [- connectViewer(store, room, "stable-root-a"),- connectViewer(store, room, "stable-root-b"),- ];- for (const root of roots) {- complete(router, root);- await vi.waitFor(() => expect(preparedFor(sent, root.sessionId)).toBeDefined());- const prepared = preparedFor(sent, root.sessionId)!;- router.handleRouteReady(root, {- type: "route-ready",- revision: prepared.revision,- phase: "prepare",- });- router.setViewerRelayCapacity(root, 1);- }-- const candidateChild = connectViewer(store, room, "candidate-child");- complete(router, candidateChild);- const prepared = await vi.waitFor(() => {- const update = preparedFor(sent, candidateChild.sessionId);- expect(update?.assignment.upstream.kind).toBe("peer");- return update!;- });- const candidateParentPeerId =- prepared.assignment.upstream.kind === "peer"- ? prepared.assignment.upstream.peerId- : "";- const candidateParent = roots.find(- (root) => root.peerId === candidateParentPeerId,- )!;- const activeParentEdge = router.resolveActiveViewerMediaEdge(- room.roomId,- candidateParent.peerId,- )!;-- expect(- router.peerSignalAuthorization({- roomId: room.roomId,- sourcePeerId: host.peerId,- sourceSessionId: host.sessionId,- targetPeerId: candidateParent.peerId,- targetSessionId: candidateParent.sessionId,- connectionId: activeParentEdge.connectionId,- signalKind: "description",- descriptionType: "offer",- }),- ).toBe(true);- expect(- router.peerSignalAuthorization({- roomId: room.roomId,- sourcePeerId: candidateParent.peerId,- sourceSessionId: candidateParent.sessionId,- targetPeerId: candidateChild.peerId,- targetSessionId: candidateChild.sessionId,- connectionId: prepared.candidate.connectionId,- signalKind: "description",- descriptionType: "offer",- }),- ).toBe("probe");-- const unrelatedRoot = roots.find(- (root) => root.peerId !== candidateParent.peerId,- )!;- expect(- router.peerSignalAuthorization({- roomId: room.roomId,- sourcePeerId: unrelatedRoot.peerId,- sourceSessionId: unrelatedRoot.sessionId,- targetPeerId: candidateChild.peerId,- targetSessionId: candidateChild.sessionId,- connectionId: prepared.candidate.connectionId,- signalKind: "description",- descriptionType: "offer",- }),- ).toBeUndefined();- } finally {- await router.close();- }- });-- it("commits P2P quality convergence after client relative approval", async () => {- const { store, sent, router } = harness(2);- try {- const room = await store.createRoom();- const host = connectHost(store, room, {- peerOnly: false,- topologyOptimization: true,- natPrediction: false,- });- complete(router, host);- const first = connectViewer(store, room, "quality-first");- complete(router, first);- await vi.waitFor(() => expect(preparedFor(sent, first.sessionId)).toBeDefined());- const firstPrepare = preparedFor(sent, first.sessionId)!;- expect(firstPrepare.candidate.qualityProbe).toBe(false);- router.handleRouteReady(first, {- type: "route-ready",- revision: firstPrepare.revision,- phase: "prepare",- });- const second = connectViewer(store, room, "quality-second");- complete(router, second);- await vi.waitFor(() => expect(preparedFor(sent, second.sessionId)).toBeDefined());- const secondPrepare = preparedFor(sent, second.sessionId)!;- router.handleRouteReady(second, {- type: "route-ready",- revision: secondPrepare.revision,- phase: "prepare",- });- router.setViewerRelayCapacity(second, 3);-- const firstEdge = router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)!;- const secondEdge = router.resolveActiveViewerMediaEdge(room.roomId, second.peerId)!;- expect(firstEdge.upstream).toEqual({ kind: "peer", peerId: host.peerId });- expect(secondEdge.upstream).toEqual({ kind: "peer", peerId: host.peerId });- const debug = vi.spyOn(- router as unknown as {- debug(- roomId: string,- event: string,- details: Record<string, unknown>,- ): void;- },- "debug",- );- expect(- router.observeSenderQualityEvidence(host, {- type: "sender-quality-evidence",- childPeerId: second.peerId,- connectionId: secondEdge.connectionId,- rtpStatsId: "second-rtp",- trackIdentifier: "track",- sampleTimestampMs: 100,- routeRevision: secondEdge.revision,- state: "healthy",- diagnostics: senderDiagnostics("healthy"),- }),- ).toBe(true);- expect(debug).toHaveBeenCalledWith(- room.roomId,- "sender-quality-evidence",- expect.objectContaining({- routeRevision: secondEdge.revision,- committedCopies: 2,- candidateReservedCopies: 0,- possibleCopies: 2,- endpointCapacity: 2,- operationReason: null,- candidateTransition: null,- sampleRole: "active",- }),- );- expect(- router.observeSenderQualityEvidence(host, {- type: "sender-quality-evidence",- childPeerId: first.peerId,- connectionId: firstEdge.connectionId,- rtpStatsId: "first-rtp",- trackIdentifier: "track",- sampleTimestampMs: 100,- routeRevision: firstEdge.revision,- state: "healthy",- diagnostics: senderDiagnostics("healthy"),- }),- ).toBe(true);- for (let window = 0; window < 3; window += 1) {- expect(- router.observeSenderQualityEvidence(host, {- type: "sender-quality-evidence",- childPeerId: first.peerId,- connectionId: firstEdge.connectionId,- rtpStatsId: "first-rtp",- trackIdentifier: "track",- sampleTimestampMs: 101 + window,- routeRevision: firstEdge.revision,- state: "degraded",- diagnostics: senderDiagnostics("degraded"),- }),- ).toBe(true);- }-- await vi.waitFor(() =>- expect(preparedFor(sent, first.sessionId)?.revision).toBeGreaterThan(- firstEdge.revision,- ),- );- const qualityPrepare = preparedFor(sent, first.sessionId)!;- expect(qualityPrepare.candidate.qualityProbe).toBe(true);- expect(- router.observeSenderQualityEvidence(second, {- type: "sender-quality-evidence",- childPeerId: first.peerId,- connectionId: qualityPrepare.candidate.connectionId,- rtpStatsId: "candidate-rtp",- trackIdentifier: "track",- sampleTimestampMs: 200,- routeRevision: qualityPrepare.revision,- state: "healthy",- diagnostics: senderDiagnostics("healthy"),- }),- ).toBe(true);- expect(debug).toHaveBeenCalledWith(- room.roomId,- "sender-quality-evidence",- expect.objectContaining({- routeRevision: qualityPrepare.revision,- committedCopies: 0,- candidateReservedCopies: 1,- possibleCopies: 1,- endpointCapacity: 2,- operationReason: "quality-convergence",- candidateTransition: "none",- sampleRole: "candidate",- }),- );- router.handleRouteReady(first, {- type: "route-ready",- revision: qualityPrepare.revision,- phase: "prepare",- });- expect(- router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)?.upstream,- ).toEqual({ kind: "peer", peerId: host.peerId });- router.handleRouteReady(first, {- type: "route-ready",- revision: qualityPrepare.revision,- phase: "prepare",- qualityApproved: true,- });- expect(- router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)?.upstream,- ).toEqual({ kind: "peer", peerId: second.peerId });- } finally {- await router.close();- }- });-- it("prepares a same-parent connection regeneration after persistent degradation", async () => {- const { store, sent, router } = harness(2);- try {- const room = await store.createRoom();- const host = connectHost(store, room, {- peerOnly: false,- topologyOptimization: true,- natPrediction: false,- });- complete(router, host);- const viewer = connectViewer(store, room, "quality-regeneration");- complete(router, viewer);- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)).toBeDefined(),- );- const initial = preparedFor(sent, viewer.sessionId)!;- expect(initial.assignment.upstream).toEqual({- kind: "peer",- peerId: host.peerId,- });- router.handleRouteReady(viewer, {- type: "route-ready",- revision: initial.revision,- phase: "prepare",- });- const edge = router.resolveActiveViewerMediaEdge(- room.roomId,- viewer.peerId,- )!;-- router.observeSenderQualityEvidence(host, {- type: "sender-quality-evidence",- childPeerId: viewer.peerId,- connectionId: edge.connectionId,- rtpStatsId: "old-sender-rtp",- trackIdentifier: "old-track",- sampleTimestampMs: 100,- routeRevision: edge.revision,- state: "healthy",- diagnostics: senderDiagnostics("healthy"),- });- for (const sampleTimestampMs of [101, 102, 103]) {- router.observeSenderQualityEvidence(host, {- type: "sender-quality-evidence",- childPeerId: viewer.peerId,- connectionId: edge.connectionId,- rtpStatsId: "old-sender-rtp",- trackIdentifier: "old-track",- sampleTimestampMs,- routeRevision: edge.revision,- state: "degraded",- diagnostics: senderDiagnostics("degraded"),- });- }-- await vi.waitFor(() => {- const prepared = preparedFor(sent, viewer.sessionId);- expect(prepared?.revision).toBeGreaterThan(edge.revision);- });- const regeneration = preparedFor(sent, viewer.sessionId)!;- expect(regeneration.candidate).toMatchObject({- transport: "direct",- qualityProbe: true,- });- expect(regeneration.assignment.upstream).toEqual({- kind: "peer",- peerId: host.peerId,- });- expect(preparedFor(sent, host.sessionId)?.candidate.connectionId).toBe(- regeneration.candidate.connectionId,- );- expect(- router.resolveActiveViewerMediaEdge(room.roomId, viewer.peerId),- ).toMatchObject({- connectionId: edge.connectionId,- upstream: { kind: "peer", peerId: host.peerId },- });- } finally {- await router.close();- }- });-- it.each([false, true])("creates NAT retries through real prepare messages with configured SFU=%s but peer-only media", async (withSfu) => {- const { store, sent, router } = harness(2, withSfu);- try {- const room = await store.createRoom();- const host = connectHost(store, room, {- peerOnly: true, topologyOptimization: false, natPrediction: true,- });- complete(router, host);- const viewer = connectViewer(store, room, "nat-retry");- complete(router, viewer);- const connectionIds = new Set<string>();- let staleFailure: Parameters<typeof router.handleRouteFailed>[1] | undefined;- for (let current = 1; current <= 3; current += 1) {- await vi.waitFor(() => expect(- preparedFor(sent, viewer.sessionId)?.candidate.connectionAttempt,- ).toEqual({ current, total: 3 }));- const prepared = preparedFor(sent, viewer.sessionId)!;- connectionIds.add(prepared.candidate.connectionId);- expect(preparedFor(sent, host.sessionId)?.candidate).toEqual(prepared.candidate);- if (staleFailure) router.handleRouteFailed(viewer, staleFailure);- expect(preparedFor(sent, viewer.sessionId)?.candidate.connectionId)- .toBe(prepared.candidate.connectionId);- if (current === 3) {- router.handleRouteReady(viewer, {- type: "route-ready", revision: prepared.revision, phase: "prepare",- });- expect(router.resolveActiveViewerMediaEdge(room.roomId, viewer.peerId))- .toMatchObject({ connectionId: prepared.candidate.connectionId });- } else {- staleFailure = {- type: "route-failed", revision: prepared.revision, phase: "prepare",- connectionId: prepared.candidate.connectionId,- };- router.handleRouteFailed(viewer, staleFailure);- router.handleRouteFailed(host, staleFailure);- }- }- expect(connectionIds.size).toBe(3);- expect([...sent.values()].flat().some((message) =>- message.type === "sfu-config" ||- (message.type === "route-status" && message.state === "failed"),- )).toBe(false);- } finally {- await router.close();- }- });-- it("keeps peer-only shares out of configured SFU fallback", async () => {- const { store, sent, router } = harness(1, true);- try {- const room = await store.createRoom();- const host = connectHost(store, room, {- peerOnly: true,- topologyOptimization: false,- natPrediction: false,- });- complete(router, host);- const first = connectViewer(store, room, "peer-only-first");- complete(router, first);- await vi.waitFor(() =>- expect(preparedFor(sent, first.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- const direct = preparedFor(sent, first.sessionId)!;- router.handleRouteReady(first, {- type: "route-ready",- revision: direct.revision,- phase: "prepare",- });-- const blocked = connectViewer(store, room, "peer-only-blocked");- complete(router, blocked);- await vi.waitFor(() =>- expect(- sent- .get(blocked.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({ state: "failed", reason: "route-exhausted" }),- );- expect(- [...sent.values()]- .flat()- .some((message) => message.type === "sfu-config"),- ).toBe(false);- } finally {- await router.close();- }- });-- it("silently keeps working media when quality-only SFU admission is denied", async () => {- const { store, sent, admission, router } = harness(1, true, undefined, 1);- const occupied = {- roomId: "9001",- shareGeneration: "occupied_share_12345678",- publicationGeneration: "occupied_publication_12345678",- };- try {- expect(admission?.reservePublication(occupied)).toBe(true);- const room = await store.createRoom();- const host = connectHost(store, room, {- peerOnly: false,- topologyOptimization: true,- natPrediction: false,- });- complete(router, host);- const viewer = connectViewer(store, room, "quality-sfu-denied");- complete(router, viewer);- await vi.waitFor(() => expect(preparedFor(sent, viewer.sessionId)).toBeDefined());- const prepared = preparedFor(sent, viewer.sessionId)!;- router.handleRouteReady(viewer, {- type: "route-ready",- revision: prepared.revision,- phase: "prepare",- });- const active = router.resolveActiveViewerMediaEdge(room.roomId, viewer.peerId)!;- for (const [index, state] of (- ["healthy", "degraded"] as const- ).entries()) {- expect(- router.observeSenderQualityEvidence(host, {- type: "sender-quality-evidence",- childPeerId: viewer.peerId,- connectionId: active.connectionId,- rtpStatsId: "viewer-rtp",- trackIdentifier: "track",- sampleTimestampMs: 100 + index,- routeRevision: active.revision,- state,- diagnostics: senderDiagnostics(state),- }),- ).toBe(true);- }- await vi.waitFor(() =>- expect(router.routeDiagnosticSnapshot(room.roomId).operation).toBeNull(),- );- expect(- sent- .get(viewer.sessionId)- ?.some((message) => message.type === "route-status"),- ).toBe(false);- expect(- router.resolveActiveViewerMediaEdge(room.roomId, viewer.peerId),- ).toMatchObject({- connectionId: active.connectionId,- upstream: { kind: "peer", peerId: host.peerId },- });- } finally {- if (admission) {- admission.beginDrain(occupied);- admission.completeDrain(occupied);- }- await router.close();- }- });--- it("notifies the presence owner after the committed graph changes", async () => {- const { store, sent, router, onRoutesChanged } = harness(1, true);- try {- const room = await store.createRoom();- await establishSfuRoom(- store,- sent,- router,- room,- );-- await vi.waitFor(() => {- expect(onRoutesChanged.mock.calls.at(-1)).toEqual([room.roomId]);- });- } finally {- await router.close();- }- });-- it("wakes at the derived direct boundary and prepares SFU automatically", async () => {- vi.useFakeTimers();- vi.setSystemTime(0);- const { store, sent, router } = harness(2, true, 300);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const viewer = connectViewer(store, room, "staged-deadline");- complete(router, viewer);-- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- await vi.advanceTimersByTimeAsync(150);- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)?.candidate.transport).toBe(- "sfu",- ),- );- expect(- sent- .get(viewer.sessionId)- ?.some(- (message) =>- message.type === "route-status" && message.state === "failed",- ),- ).toBe(false);- } finally {- await router.close();- vi.useRealTimers();- }- });-- it("keeps an exact transport-connected direct candidate past the boundary", async () => {- vi.useFakeTimers();- vi.setSystemTime(0);- const { store, sent, router } = harness(2, true, 300);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const viewer = connectViewer(store, room, "transport-connected");- complete(router, viewer);- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- const direct = preparedFor(sent, viewer.sessionId)!;- router.handleRouteTransportConnected(viewer, {- type: "route-transport-connected",- revision: direct.revision,- connectionId: direct.candidate.connectionId,- });- await vi.advanceTimersByTimeAsync(150);- expect(preparedFor(sent, viewer.sessionId)).toEqual(direct);- router.handleRouteReady(viewer, {- type: "route-ready",- revision: direct.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(activeAfter(sent, viewer.sessionId, direct.revision - 1)).toMatchObject({- assignment: { upstream: { kind: "peer" } },- }),- );- } finally {- await router.close();- vi.useRealTimers();- }- });-- it("uses the direct boundary to bootstrap SFU when every Host slot is full", async () => {- vi.useFakeTimers();- vi.setSystemTime(0);- const { store, sent, router } = harness(2, true, 300);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);-- const firstRoot = connectViewer(store, room, "first-root");- complete(router, firstRoot);- await vi.waitFor(() =>- expect(preparedFor(sent, firstRoot.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- const firstPrepare = preparedFor(sent, firstRoot.sessionId)!;- router.handleRouteReady(firstRoot, {- type: "route-ready",- revision: firstPrepare.revision,- phase: "prepare",- });- router.setViewerRelayCapacity(firstRoot, 2);-- const secondRoot = connectViewer(store, room, "second-root");- complete(router, secondRoot);- await vi.waitFor(() =>- expect(preparedFor(sent, secondRoot.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- const secondPrepare = preparedFor(sent, secondRoot.sessionId)!;- router.handleRouteReady(secondRoot, {- type: "route-ready",- revision: secondPrepare.revision,- phase: "prepare",- });-- const waiting = connectViewer(store, room, "waiting");- complete(router, waiting);- await vi.waitFor(() =>- expect(preparedFor(sent, waiting.sessionId)?.candidate.transport).toBe(- "direct",- ),- );-- await vi.advanceTimersByTimeAsync(150);- await vi.waitFor(() =>- expect(preparedFor(sent, secondRoot.sessionId)?.candidate.transport).toBe(- "sfu",- ),- );- const secondBootstrap = preparedFor(sent, secondRoot.sessionId)!;- router.handleRouteFailed(secondRoot, {- type: "route-failed",- revision: secondBootstrap.revision,- phase: "prepare",- connectionId: secondBootstrap.candidate.connectionId,- });- await vi.waitFor(() =>- expect(preparedFor(sent, firstRoot.sessionId)?.candidate.transport).toBe(- "sfu",- ),- );- expect(- sent- .get(secondRoot.sessionId)- ?.some(- (message) =>- message.type === "route-status" && message.state === "failed",- ),- ).toBe(false);- const firstBootstrap = preparedFor(sent, firstRoot.sessionId)!;- router.handleRouteFailed(firstRoot, {- type: "route-failed",- revision: firstBootstrap.revision,- phase: "prepare",- connectionId: firstBootstrap.candidate.connectionId,- });- await vi.waitFor(() =>- expect(- sent- .get(waiting.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({- state: "failed",- reason: "route-exhausted",- }),- );- for (const root of [firstRoot, secondRoot]) {- expect(- sent- .get(root.sessionId)- ?.some(- (message) =>- message.type === "route-status" && message.state === "failed",- ),- ).toBe(false);- }- expect(- sent- .get(waiting.sessionId)- ?.some(- (message) =>- message.type === "route-status" && message.state === "failed",- ),- ).toBe(true);- } finally {- await router.close();- vi.useRealTimers();- }- });-- it("does not recreate SFU after an exhausted reuse and carrier teardown", async () => {- vi.useFakeTimers();- vi.setSystemTime(0);- const { store, sent, admission, roomControl, router } = harness(- 2,- true,- 300,- );- const sfuConfigCount = () =>- [...sent.values()]- .flat()- .filter((message) => message.type === "sfu-config").length;- const ownPrepare = (participant: AuthenticatedRouteParticipant) =>- sent- .get(participant.sessionId)- ?.findLast(- (- message,- ): message is Extract<- ServerMessage,- { type: "route-update"; phase: "prepare" }- > =>- message.type === "route-update" &&- message.phase === "prepare" &&- message.candidate.childPeerId === participant.peerId,- );- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);-- const firstRoot = connectViewer(store, room, "reuse-loop-first-root");- complete(router, firstRoot);- await vi.waitFor(() =>- expect(preparedFor(sent, firstRoot.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- const firstDirect = preparedFor(sent, firstRoot.sessionId)!;- router.handleRouteReady(firstRoot, {- type: "route-ready",- revision: firstDirect.revision,- phase: "prepare",- });- router.setViewerRelayCapacity(firstRoot, 1);-- const secondRoot = connectViewer(store, room, "reuse-loop-second-root");- complete(router, secondRoot);- await vi.waitFor(() =>- expect(preparedFor(sent, secondRoot.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- const secondDirect = preparedFor(sent, secondRoot.sessionId)!;- router.handleRouteReady(secondRoot, {- type: "route-ready",- revision: secondDirect.revision,- phase: "prepare",- });-- const departedParent = connectViewer(- store,- room,- "reuse-loop-departed-parent",- );- complete(router, departedParent);- await vi.waitFor(() =>- expect(- preparedFor(sent, departedParent.sessionId)?.assignment.upstream,- ).toEqual({ kind: "peer", peerId: firstRoot.peerId }),- );- const parentDirect = preparedFor(sent, departedParent.sessionId)!;- router.handleRouteReady(departedParent, {- type: "route-ready",- revision: parentDirect.revision,- phase: "prepare",- });- router.setViewerRelayCapacity(departedParent, 1);-- const demand = connectViewer(store, room, "reuse-loop-demand");- complete(router, demand);- await vi.waitFor(() =>- expect(preparedFor(sent, demand.sessionId)?.assignment.upstream).toEqual(- { kind: "peer", peerId: departedParent.peerId },- ),- );- const demandDirect = preparedFor(sent, demand.sessionId)!;- router.handleRouteReady(demand, {- type: "route-ready",- revision: demandDirect.revision,- phase: "prepare",- });-- const departureAt = Date.now();- store.disconnectParticipant(- room.roomId,- departedParent.peerId,- departedParent.sessionId,- );- router.disconnectParticipant(- room.roomId,- departedParent.peerId,- departedParent.sessionId,- );- router.removeViewer(room.roomId, departedParent.peerId);- router.setViewerRelayCapacity(secondRoot, 1);-- await vi.waitFor(() => {- const recovery = ownPrepare(demand);- expect(recovery?.revision).toBeGreaterThan(demandDirect.revision);- expect(recovery?.candidate).toMatchObject({- childPeerId: demand.peerId,- transport: "direct",- });- });- await vi.advanceTimersByTimeAsync(- Math.max(0, departureAt + 150 - Date.now()),- );-- const carrier = await vi.waitFor(() => {- const value = [firstRoot, secondRoot].find(- (viewer) =>- ownPrepare(viewer)?.candidate.transport === "sfu",- );- expect(value).toBeDefined();- return value!;- });- const bootstrap = ownPrepare(carrier)!;- router.handleRouteReady(carrier, {- type: "route-ready",- revision: bootstrap.revision,- phase: "prepare",- });-- await vi.waitFor(() =>- expect(preparedFor(sent, demand.sessionId)?.candidate.transport).toBe(- "sfu",- ),- );- expect(roomControl?.created).toHaveLength(1);- const configCountAfterBootstrap = sfuConfigCount();- expect(configCountAfterBootstrap).toBeGreaterThanOrEqual(3);-- await vi.advanceTimersByTimeAsync(- Math.max(0, departureAt + 300 - Date.now()),- );- await vi.waitFor(() =>- expect(ownPrepare(carrier)?.candidate.transport).toBe(- "direct",- ),- );- expect(router.routeDiagnosticSnapshot(room.roomId).operation).toMatchObject({- reason: "direct-convergence",- });- const carrierDirect = ownPrepare(carrier)!;- router.handleRouteReady(carrier, {- type: "route-ready",- revision: carrierDirect.revision,- phase: "prepare",- });-- await vi.waitFor(() =>- expect(- router.resolveActiveViewerMediaEdge(room.roomId, carrier.peerId)- ?.upstream,- ).toEqual({ kind: "peer", peerId: host.peerId }),- );- await vi.waitFor(() => expect(roomControl?.deleted).toHaveLength(1));- await vi.advanceTimersByTimeAsync(300);-- expect(roomControl?.created).toHaveLength(1);- expect(sfuConfigCount()).toBe(configCountAfterBootstrap);- expect(admission?.usage()).toEqual({ ingress: 0, egress: 0 });- } finally {- await router.close();- vi.useRealTimers();- }- });-- it("reports a late final SFU bootstrap ready only to the waiting demand", async () => {- vi.useFakeTimers();- vi.setSystemTime(0);- const { store, sent, router } = harness(2, true, 300);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);-- const firstRoot = connectViewer(store, room, "late-ready-first-root");- complete(router, firstRoot);- await vi.waitFor(() =>- expect(preparedFor(sent, firstRoot.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- const firstPrepare = preparedFor(sent, firstRoot.sessionId)!;- router.handleRouteReady(firstRoot, {- type: "route-ready",- revision: firstPrepare.revision,- phase: "prepare",- });- router.setViewerRelayCapacity(firstRoot, 2);-- const secondRoot = connectViewer(store, room, "late-ready-second-root");- complete(router, secondRoot);- await vi.waitFor(() =>- expect(preparedFor(sent, secondRoot.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- const secondPrepare = preparedFor(sent, secondRoot.sessionId)!;- router.handleRouteReady(secondRoot, {- type: "route-ready",- revision: secondPrepare.revision,- phase: "prepare",- });-- const waiting = connectViewer(store, room, "late-ready-waiting");- complete(router, waiting);- await vi.waitFor(() =>- expect(preparedFor(sent, waiting.sessionId)?.candidate.transport).toBe(- "direct",- ),- );-- await vi.advanceTimersByTimeAsync(150);- await vi.waitFor(() =>- expect(preparedFor(sent, secondRoot.sessionId)?.candidate.transport).toBe(- "sfu",- ),- );- const firstCarrier = preparedFor(sent, secondRoot.sessionId)!;- router.handleRouteFailed(secondRoot, {- type: "route-failed",- revision: firstCarrier.revision,- phase: "prepare",- connectionId: firstCarrier.candidate.connectionId,- });-- await vi.waitFor(() =>- expect(preparedFor(sent, firstRoot.sessionId)?.candidate.transport).toBe(- "sfu",- ),- );- const finalCarrier = preparedFor(sent, firstRoot.sessionId)!;- vi.setSystemTime(451);- router.handleRouteReady(firstRoot, {- type: "route-ready",- revision: finalCarrier.revision,- phase: "prepare",- });-- await vi.waitFor(() =>- expect(- sent- .get(waiting.sessionId)- ?.filter(- (message) =>- message.type === "route-status" &&- message.state === "failed" &&- message.reason === "route-exhausted",- ),- ).toHaveLength(1),- );- for (const carrier of [firstRoot, secondRoot]) {- expect(- sent- .get(carrier.sessionId)- ?.some(- (message) =>- message.type === "route-status" && message.state === "failed",- ),- ).toBe(false);- }- } finally {- await router.close();- vi.useRealTimers();- }- });-- it("reports bounded route exhaustion without raw error text", async () => {- vi.useFakeTimers();- vi.setSystemTime(0);- const { store, sent, router } = harness(2, true, 300);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const viewer = connectViewer(store, room, "route-exhausted");- complete(router, viewer);-- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- await vi.advanceTimersByTimeAsync(150);- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)?.candidate.transport).toBe(- "sfu",- ),- );- await vi.advanceTimersByTimeAsync(150);- await vi.waitFor(() =>- expect(- sent- .get(viewer.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({- type: "route-status",- state: "failed",- reason: "route-exhausted",- }),- );- expect(- sent- .get(viewer.sessionId)- ?.some(- (message) =>- message.type === "error" &&- message.message.includes("media route"),- ),- ).toBe(false);- } finally {- await router.close();- vi.useRealTimers();- }- });-- it("reports typed exhaustion when the exact candidate fails", async () => {- const { store, sent, router } = harness(1);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const viewer = connectViewer(store, room, "candidate-failed");- complete(router, viewer);-- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)).toBeDefined(),- );- const prepared = preparedFor(sent, viewer.sessionId)!;- router.handleRouteFailed(viewer, {- type: "route-failed",- revision: prepared.revision,- phase: "prepare",- connectionId: prepared.candidate.connectionId,- });-- await vi.waitFor(() =>- expect(- sent- .get(viewer.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({- state: "failed",- reason: "route-exhausted",- }),- );- } finally {- await router.close();- }- });-- it("reports typed exhaustion when reconciliation has no candidate", async () => {- const { store, sent, router } = harness(1);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);-- const first = connectViewer(store, room, "only-slot");- complete(router, first);- await vi.waitFor(() =>- expect(preparedFor(sent, first.sessionId)).toBeDefined(),- );- const firstPrepare = preparedFor(sent, first.sessionId)!;- router.handleRouteReady(first, {- type: "route-ready",- revision: firstPrepare.revision,- phase: "prepare",- });-- const blocked = connectViewer(store, room, "no-candidate");- complete(router, blocked);- await vi.waitFor(() =>- expect(- sent- .get(blocked.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({- state: "failed",- reason: "route-exhausted",- }),- );- } finally {- await router.close();- }- });-- it("reports only SFU admission waiting while bounded capacity is unavailable", async () => {- vi.useFakeTimers();- vi.setSystemTime(0);- const { store, sent, admission, router } = harness(2, true, 300);- const capacityFences = [- {- roomId: "9001",- shareGeneration: "capacity_share_a",- publicationGeneration: "capacity_publication_a",- },- {- roomId: "9002",- shareGeneration: "capacity_share_b",- publicationGeneration: "capacity_publication_b",- },- ] as const;- try {- for (const fence of capacityFences) {- expect(admission?.reservePublication(fence)).toBe(true);- }- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const viewer = connectViewer(store, room, "sfu-admission-wait");- complete(router, viewer);-- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- await vi.advanceTimersByTimeAsync(150);- await vi.waitFor(() =>- expect(- sent- .get(viewer.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({- type: "route-status",- state: "waiting",- reason: "sfu-admission",- }),- );- } finally {- for (const fence of capacityFences) {- admission?.beginDrain(fence);- admission?.completeDrain(fence);- }- await router.close();- vi.useRealTimers();- }- });-- it("physically removes an exact subscription without releasing its generation charge", async () => {- const { store, sent, admission, roomControl, router } = harness(- 1,- true,- undefined,- 2,- );- let closed = false;- try {- const activeRoom = await store.createRoom();- const active = await establishSfuRoom(- store,- sent,- router,- activeRoom,- );- await vi.waitFor(() =>- expect(admission?.usage()).toEqual({ ingress: 1, egress: 2 }),- );- expect(- admission?.reservePublication({- roomId: "9001",- shareGeneration: "waiter_share_12345678",- publicationGeneration: "waiter_publication_12345678",- }),- ).toBe(true);- const reservePublication = vi.spyOn(admission!, "reservePublication");-- const waitingRoom = await store.createRoom();- const waitingHost = connectHost(store, waitingRoom);- complete(router, waitingHost);- const waitingViewer = connectViewer(store, waitingRoom, "waiter");- complete(router, waitingViewer);- await vi.waitFor(() =>- expect(preparedFor(sent, waitingViewer.sessionId)).toBeDefined(),- );- const direct = preparedFor(sent, waitingViewer.sessionId)!;- router.handleRouteFailed(waitingViewer, {- type: "route-failed",- revision: direct.revision,- phase: "prepare",- connectionId: direct.candidate.connectionId,- });- await vi.waitFor(() =>- expect(- sent- .get(waitingViewer.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({ state: "waiting", reason: "sfu-admission" }),- );- const attemptsBeforeRelease = reservePublication.mock.calls.length;- const drainGate = deferred();- roomControl!.subscriptionDrainBarrier = drainGate.promise;-- store.disconnectParticipant(- activeRoom.roomId,- active.first.peerId,- active.first.sessionId,- );- router.disconnectParticipant(- activeRoom.roomId,- active.first.peerId,- active.first.sessionId,- );- router.removeViewer(activeRoom.roomId, active.first.peerId);- await vi.waitFor(() =>- expect(router.routeDiagnosticSnapshot(activeRoom.roomId).children).toHaveLength(1),- );- await vi.waitFor(() =>- expect(roomControl?.subscriptionDrainAttempts).toContainEqual(- expect.objectContaining({ viewerPeerId: active.first.peerId }),- ),- );- expect(admission?.usage()).toEqual({ ingress: 2, egress: 2 });- drainGate.resolve();- await vi.waitFor(() =>- expect(roomControl?.drainedSubscriptions).toContainEqual(- expect.objectContaining({ viewerPeerId: active.first.peerId }),- ),- );-- expect(admission?.usage()).toEqual({ ingress: 2, egress: 2 });- expect(reservePublication).toHaveBeenCalledTimes(attemptsBeforeRelease);-- await router.close();- closed = true;- expect(admission?.usage()).toEqual({ ingress: 0, egress: 0 });- } finally {- if (!closed) await router.close();- }- });-- it("orders exact prepare, commits only child proof, and rolls back above P", async () => {- const { store, sent, router } = harness(2);- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const first = connectViewer(store, room, "first");- complete(router, first);-- await vi.waitFor(() => expect(preparedFor(sent, first.sessionId)).toBeDefined());- const firstPrepare = preparedFor(sent, first.sessionId)!;- expect(firstPrepare.candidate).toMatchObject({- childPeerId: first.peerId,- transport: "direct",- });- expect(preparedFor(sent, host.sessionId)?.candidate).toEqual(- firstPrepare.candidate,- );-- router.handleRouteReady(host, {- type: "route-ready",- revision: firstPrepare.revision,- phase: "prepare",- });- expect(activeAfter(sent, first.sessionId, firstPrepare.revision)).toBeUndefined();- router.handleRouteReady(first, {- type: "route-ready",- revision: firstPrepare.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(- sent- .get(first.sessionId)- ?.findLast(- (message) =>- message.type === "route-update" &&- message.phase === "active" &&- message.revision === firstPrepare.revision,- ),- ).toBeDefined(),- );-- const second = connectViewer(store, room, "second");- complete(router, second);- await vi.waitFor(() => expect(preparedFor(sent, second.sessionId)).toBeDefined());- const secondPrepare = preparedFor(sent, second.sessionId)!;- router.handleRouteFailed(second, {- type: "route-failed",- revision: secondPrepare.revision,- phase: "prepare",- connectionId: secondPrepare.candidate.connectionId,- });- await vi.waitFor(() =>- expect(activeAfter(sent, second.sessionId, secondPrepare.revision)).toBeDefined(),- );- expect(activeAfter(sent, second.sessionId, secondPrepare.revision)!.revision).toBeGreaterThan(- secondPrepare.revision,- );- await router.close();- });-- it("creates one Host publication and reuses exact Viewer subscriptions", async () => {- const { store, sent, admission, router } = harness(1, true);- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const first = connectViewer(store, room, "sfu_first");- complete(router, first);- const firstDirect = await vi.waitFor(() => {- const message = preparedFor(sent, first.sessionId);- expect(message).toBeDefined();- return message!;- });- router.handleRouteReady(first, {- type: "route-ready",- revision: firstDirect.revision,- phase: "prepare",- });-- const second = connectViewer(store, room, "sfu_second");- complete(router, second);- await vi.waitFor(() =>- expect(- preparedFor(sent, first.sessionId)?.candidate.transport,- ).toBe("sfu"),- );- const firstSfu = preparedFor(sent, first.sessionId)!;- router.handleRouteReady(first, {- type: "route-ready",- revision: firstSfu.revision,- phase: "prepare",- });-- await vi.waitFor(() =>- expect(preparedFor(sent, second.sessionId)?.candidate.transport).toBe("sfu"),- );- const secondSfu = preparedFor(sent, second.sessionId)!;- router.handleRouteReady(second, {- type: "route-ready",- revision: secondSfu.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(admission?.usage()).toEqual({ ingress: 1, egress: 2 }),- );- const hostConfigs = sent- .get(host.sessionId)- ?.filter((message) => message.type === "sfu-config");- expect(hostConfigs).toHaveLength(1);- await router.close();- });-- it("discards an SFU preparation whose cursor becomes stale while awaiting LiveKit", async () => {- const { store, sent, admission, roomControl, router } = harness(1, true);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const root = connectViewer(store, room, "prepare-stale-root");- complete(router, root);- const direct = await vi.waitFor(() => {- const prepared = preparedFor(sent, root.sessionId);- expect(prepared?.candidate.transport).toBe("direct");- return prepared!;- });- router.handleRouteReady(root, {- type: "route-ready",- revision: direct.revision,- phase: "prepare",- });- const gate = deferred();- roomControl!.createBarrier = gate.promise;- router.setViewerRelayCapacity(root, 0);- const waiting = connectViewer(store, room, "prepare-stale-waiting");- complete(router, waiting);- await vi.waitFor(() =>- expect(admission?.usage().ingress).toBe(1),- );- store.disconnectParticipant(room.roomId, root.peerId, root.sessionId);- router.disconnectParticipant(room.roomId, root.peerId, root.sessionId);- gate.resolve();- await vi.waitFor(() =>- expect(admission?.usage()).toEqual({ ingress: 0, egress: 0 }),- );- expect(router.routeDiagnosticSnapshot(room.roomId).operation).toBeNull();- } finally {- await router.close();- }- });-- it("reschedules the regular Host-offline check after a read error", async () => {- const { store, sent, admission, roomControl, router } = harness(- 1,- true,- undefined,- 2,- undefined,- 10,- );- try {- const room = await store.createRoom();- const { host } = await establishSfuRoom(store, sent, router, room);- const retry = deferredValue<boolean>();- const hostCheck = vi- .spyOn(roomControl!, "hostParticipantExists")- .mockRejectedValueOnce(new Error("temporary LiveKit read failure"))- .mockReturnValueOnce(retry.promise);- store.disconnectParticipant(room.roomId, host.peerId, host.sessionId);- router.disconnectParticipant(room.roomId, host.peerId, host.sessionId);-- await vi.waitFor(() => expect(hostCheck).toHaveBeenCalledTimes(2));- expect(admission?.usage()).toEqual({ ingress: 1, egress: 2 });- } finally {- await router.close();- }- });-- it("rechecks Host-offline retirement after a live route operation", async () => {- const { store, sent, admission, roomControl, router } = harness(- 1,- true,- undefined,- 2,- undefined,- 10,- );- try {- const room = await store.createRoom();- const { host, first, second } = await establishSfuRoom(- store,- sent,- router,- room,- );- router.setViewerRelayCapacity(second, 1);- const active = router.resolveActiveViewerMediaEdge(- room.roomId,- first.peerId,- )!;- router.handleRouteFailed(first, {- type: "route-failed",- revision: active.revision,- phase: "active",- connectionId: active.connectionId,- });- await vi.waitFor(() => {- const prepared = preparedFor(sent, first.sessionId);- expect(prepared?.revision).toBeGreaterThan(active.revision);- expect(prepared?.candidate.transport).toBe("direct");- return prepared!;- });- const retry = deferredValue<boolean>();- const hostCheck = vi- .spyOn(roomControl!, "hostParticipantExists")- .mockResolvedValueOnce(false)- .mockReturnValueOnce(retry.promise);- store.disconnectParticipant(room.roomId, host.peerId, host.sessionId);- router.disconnectParticipant(room.roomId, host.peerId, host.sessionId);-- await vi.waitFor(() => expect(hostCheck).toHaveBeenCalledTimes(2));- expect(- router.resolveActiveViewerMediaEdge(room.roomId, first.peerId),- ).toBeUndefined();- retry.resolve(false);- await vi.waitFor(() =>- expect(admission?.usage()).toEqual({ ingress: 0, egress: 0 }),- );- expect(hostCheck).toHaveBeenCalledTimes(2);- } finally {- await router.close();- }- });-- it("ignores an old Host-offline result after a new SFU generation commits", async () => {- const { store, sent, admission, roomControl, router } = harness(- 1,- true,- undefined,- 2,- undefined,- 10,- );- try {- const room = await store.createRoom();- const { host, first, second } = await establishSfuRoom(- store,- sent,- router,- room,- );- const oldRevision = Math.max(- router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)!.revision,- router.resolveActiveViewerMediaEdge(room.roomId, second.peerId)!.revision,- );- const delayed = deferredValue<boolean>();- const hostCheck = vi- .spyOn(roomControl!, "hostParticipantExists")- .mockReturnValueOnce(delayed.promise);- store.disconnectParticipant(room.roomId, host.peerId, host.sessionId);- router.disconnectParticipant(room.roomId, host.peerId, host.sessionId);- await vi.waitFor(() => expect(hostCheck).toHaveBeenCalledTimes(1));-- const replacementHost = connectHost(- store,- room,- undefined,- "new-physical-host-client",- "new-physical-host-session",- );- complete(router, replacementHost);- const handled = new Set<string>();- for (let index = 0; index < 3; index += 1) {- const next = await vi.waitFor(() => {- const prepared = [first, second]- .map((viewer) => ({- viewer,- prepared: preparedFor(sent, viewer.sessionId),- }))- .find(- ({ prepared }) =>- prepared &&- prepared.revision > oldRevision &&- !handled.has(prepared.candidate.connectionId),- );- expect(prepared).toBeDefined();- return prepared!;- });- handled.add(next.prepared!.candidate.connectionId);- router.handleRouteReady(next.viewer, {- type: "route-ready",- revision: next.prepared!.revision,- phase: "prepare",- });- }- await vi.waitFor(() =>- expect(admission?.usage()).toEqual({ ingress: 1, egress: 2 }),- );- const currentFence = roomControl!.created.at(-1)!;- expect(currentFence.publicationGeneration).not.toBe(- roomControl!.created[0]!.publicationGeneration,- );-- delayed.resolve(false);- await Promise.resolve();- await Promise.resolve();- expect(admission?.usage()).toEqual({ ingress: 1, egress: 2 });- expect(roomControl!.deleted).not.toContainEqual(currentFence);- } finally {- await router.close();- }- });-- it("resolves exact direct and peer-relayed Viewer evidence sources", async () => {- const { store, sent, router } = harness(1);- try {- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const root = connectViewer(store, room, "evidence-root");- complete(router, root);- await vi.waitFor(() =>- expect(preparedFor(sent, root.sessionId)).toBeDefined(),- );- const rootPrepare = preparedFor(sent, root.sessionId)!;- expect(- router.resolveActiveViewerMediaEdge(room.roomId, root.peerId),- ).toBeUndefined();- router.handleRouteReady(root, {- type: "route-ready",- revision: rootPrepare.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(- router.resolveActiveViewerMediaEdge(room.roomId, root.peerId),- ).toEqual({- revision: rootPrepare.revision,- connectionId: rootPrepare.candidate.connectionId,- upstream: { kind: "peer", peerId: host.peerId },- }),- );-- router.setViewerRelayCapacity(root, 1);- const child = connectViewer(store, room, "evidence-child");- complete(router, child);- await vi.waitFor(() =>- expect(preparedFor(sent, child.sessionId)).toBeDefined(),- );- const childPrepare = preparedFor(sent, child.sessionId)!;- expect(childPrepare.candidate.transport).toBe("direct");- router.handleRouteReady(child, {- type: "route-ready",- revision: childPrepare.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(- router.resolveActiveViewerMediaEdge(room.roomId, child.peerId),- ).toEqual({- revision: childPrepare.revision,- connectionId: childPrepare.candidate.connectionId,- upstream: { kind: "peer", peerId: root.peerId },- }),- );- } finally {- await router.close();- }- });-- it("retries a failed physical drain before reusing the exact SFU identity", async () => {- const { store, sent, admission, roomControl, router } = harness(- 1,- true,- 1_000,- 2,- 10,- );- try {- const room = await store.createRoom();- const { first } = await establishSfuRoom(store, sent, router, room);- await vi.waitFor(() =>- expect(- router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)- ?.upstream,- ).toEqual({ kind: "sfu" }),- );-- router.setViewerRelayCapacity(first, 1);- const child = connectViewer(store, room, "sfu-peer-child");- complete(router, child);- await vi.waitFor(() =>- expect(preparedFor(sent, child.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- await new Promise((resolve) => setTimeout(resolve, 510));- await vi.waitFor(() =>- expect(preparedFor(sent, child.sessionId)?.candidate.transport).toBe(- "sfu",- ),- );- const sfuPrepare = preparedFor(sent, child.sessionId)!;- router.handleRouteReady(child, {- type: "route-ready",- revision: sfuPrepare.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(- router.resolveActiveViewerMediaEdge(room.roomId, child.peerId)- ?.upstream,- ).toEqual({ kind: "sfu" }),- );- await vi.waitFor(() =>- expect(preparedFor(sent, child.sessionId)?.candidate.transport).toBe(- "direct",- ),- );- const directPrepare = preparedFor(sent, child.sessionId)!;- const drainGate = deferred();- const drainSubscription = vi- .spyOn(roomControl!, "drainSubscription")- .mockImplementationOnce(() => drainGate.promise);- router.handleRouteReady(child, {- type: "route-ready",- revision: directPrepare.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(- router.resolveActiveViewerMediaEdge(room.roomId, child.peerId)- ?.upstream,- ).toEqual({ kind: "peer", peerId: first.peerId }),- );- await vi.waitFor(() =>- expect(drainSubscription).toHaveBeenCalledWith(- expect.objectContaining({ viewerPeerId: child.peerId }),- ),- );- expect(admission?.usage()).toEqual({ ingress: 1, egress: 3 });-- router.handleRouteFailed(child, {- type: "route-failed",- revision: directPrepare.revision,- phase: "active",- connectionId: directPrepare.candidate.connectionId,- });- await vi.waitFor(() =>- expect(router.routeDiagnosticSnapshot(room.roomId).operation).not.toBeNull(),- );- expect(preparedFor(sent, child.sessionId)?.revision).toBe(- directPrepare.revision,- );-- drainGate.reject(new Error("transient participant drain failure"));- await vi.waitFor(() => expect(drainSubscription).toHaveBeenCalledTimes(2));- const reusedSfu = await vi.waitFor(() => {- const prepared = preparedFor(sent, child.sessionId);- expect(prepared?.revision).toBeGreaterThan(directPrepare.revision);- expect(prepared?.candidate.transport).toBe("sfu");- return prepared!;- });- router.handleRouteReady(child, {- type: "route-ready",- revision: reusedSfu.revision,- phase: "prepare",- });- await vi.waitFor(() =>- expect(- router.resolveActiveViewerMediaEdge(room.roomId, child.peerId)- ?.upstream,- ).toEqual({ kind: "sfu" }),- );- expect(roomControl!.drainedSubscriptions).toContainEqual(- expect.objectContaining({ viewerPeerId: child.peerId }),- );- expect(admission?.usage()).toEqual({ ingress: 1, egress: 3 });- expect(- router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)- ?.upstream,- ).toEqual({ kind: "sfu" });- } finally {- await router.close();- }- });-- it("serializes fresh SFU configuration without making refresh one-shot", async () => {- const { store, sent, router } = harness(1, true);- try {- const room = await store.createRoom();- const { first } = await establishSfuRoom(store, sent, router, room);- const active = router.resolveActiveViewerMediaEdge(- room.roomId,- first.peerId,- );- expect(active?.upstream).toEqual({ kind: "sfu" });- const configCount = () =>- sent- .get(first.sessionId)- ?.filter((message) => message.type === "sfu-config").length ?? 0;- const initialCount = configCount();-- router.refreshSfu(first, 0);- await vi.waitFor(() => expect(configCount()).toBe(initialCount + 1));- router.refreshSfu(first, active!.revision);- await vi.waitFor(() => expect(configCount()).toBe(initialCount + 2));- } finally {- await router.close();- }- });-- it("fails the exact active SFU route when fresh configuration cannot be issued", async () => {- const { store, sent, router, failNextTokenIssue } = harness(1, true);- try {- const room = await store.createRoom();- const { first } = await establishSfuRoom(store, sent, router, room);- const active = router.resolveActiveViewerMediaEdge(- room.roomId,- first.peerId,- )!;- expect(active.upstream).toEqual({ kind: "sfu" });-- failNextTokenIssue();- router.refreshSfu(first, active.revision);-- await vi.waitFor(() =>- expect(- router.resolveActiveViewerMediaEdge(room.roomId, first.peerId),- ).not.toEqual(active),- );- } finally {- await router.close();- }- });-------- it("emits typed exhaustion and clears diagnostics on departure and room deletion", async () => {- const { store, sent, router } = harness(1);- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const viewer = connectViewer(store, room, "diagnostic");- complete(router, viewer);- await vi.waitFor(() =>- expect(preparedFor(sent, viewer.sessionId)).toBeDefined(),- );- const prepared = preparedFor(sent, viewer.sessionId)!;- expect(router.routeDiagnosticSnapshot(room.roomId).children).toHaveLength(1);-- router.handleRouteFailed(viewer, {- type: "route-failed",- revision: prepared.revision,- phase: "prepare",- connectionId: prepared.candidate.connectionId,- });- await vi.waitFor(() =>- expect(- sent- .get(viewer.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({- state: "failed",- reason: "route-exhausted",- }),- );-- router.removeViewer(room.roomId, viewer.peerId);- expect(router.routeDiagnosticSnapshot(room.roomId)).toEqual({- children: [],- operation: null,- });-- const replacement = connectViewer(store, room, "diagnostic-replacement");- complete(router, replacement);- expect(router.routeDiagnosticSnapshot(room.roomId).children).toHaveLength(1);- router.stopRoom(room.roomId);- expect(router.routeDiagnosticSnapshot(room.roomId)).toEqual({- children: [],- operation: null,- });-- complete(router, host);- expect(- router.routeDiagnosticSnapshot(room.roomId).children.length,- ).toBeGreaterThan(0);- router.deleteRoom(room.roomId);- expect(router.routeDiagnosticSnapshot(room.roomId)).toEqual({- children: [],- operation: null,- });- await router.close();- });-- it("preserves connected Viewer capacity across sharing generations", async () => {- const { store, sent, router } = harness(1);- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);- const root = connectViewer(store, room, "retained-capacity-root");- complete(router, root);- await vi.waitFor(() => expect(preparedFor(sent, root.sessionId)).toBeDefined());- const initialRoot = preparedFor(sent, root.sessionId)!;- router.handleRouteReady(root, {- type: "route-ready",- revision: initialRoot.revision,- phase: "prepare",- });- router.setViewerRelayCapacity(root, 1);-- router.stopRoom(room.roomId);- sent.set(root.sessionId, []);- complete(router, host);- await vi.waitFor(() => expect(preparedFor(sent, root.sessionId)).toBeDefined());- const restartedRoot = preparedFor(sent, root.sessionId)!;- router.handleRouteReady(root, {- type: "route-ready",- revision: restartedRoot.revision,- phase: "prepare",- });-- const child = connectViewer(store, room, "retained-capacity-child");- complete(router, child);- await vi.waitFor(() => expect(preparedFor(sent, child.sessionId)).toBeDefined());- expect(preparedFor(sent, child.sessionId)?.assignment.upstream).toEqual({- kind: "peer",- peerId: root.peerId,- });- await router.close();- });-- it("emits typed exhaustion when reconciliation has no candidate", async () => {- const { store, sent, router } = harness(1);- const room = await store.createRoom();- const host = connectHost(store, room);- complete(router, host);-- const first = connectViewer(store, room, "only-slot");- complete(router, first);- await vi.waitFor(() =>- expect(preparedFor(sent, first.sessionId)).toBeDefined(),- );- const firstPrepare = preparedFor(sent, first.sessionId)!;- router.handleRouteReady(first, {- type: "route-ready",- revision: firstPrepare.revision,- phase: "prepare",- });-- const blocked = connectViewer(store, room, "no-candidate");- complete(router, blocked);- await vi.waitFor(() =>- expect(- sent- .get(blocked.sessionId)- ?.findLast((message) => message.type === "route-status"),- ).toMatchObject({- state: "failed",- reason: "route-exhausted",- }),- );- await router.close();- });--});diff --git a/tests/ice.test.ts b/tests/ice.test.tsdeleted file mode 100644index 4085ca7d..00000000--- a/tests/ice.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, expect, it } from "vitest";--import { createIceConfig } from "../src/server/ice.ts";--describe("ordinary ICE configuration", () => {- it("returns only the configured STUN servers", () => {- expect(- createIceConfig({- stunUrls: [- "stun:stun-a.example.test:3478",- "stun:stun-b.example.test:3478",- ],- natPredictionEnabled: true,- natPredictionStunUrls: [- "stun:survey-a.example.test:3478",- "stun:survey-b.example.test:3478",- ],- }),- ).toEqual({- iceServers: [- {- urls: [- "stun:stun-a.example.test:3478",- "stun:stun-b.example.test:3478",- ],- },- ],- natPredictionStunUrls: [- "stun:survey-a.example.test:3478",- "stun:survey-b.example.test:3478",- ],- });- });-- it("keeps local development explicit when STUN is absent", () => {- expect(- createIceConfig({ stunUrls: [], natPredictionEnabled: false }),- ).toEqual({ iceServers: [], natPredictionStunUrls: [] });- });-- it("does not expose auxiliary listeners when the capability is disabled", () => {- expect(- createIceConfig({- stunUrls: ["stun:share.example.test:3478"],- natPredictionEnabled: false,- }),- ).toEqual({- iceServers: [{ urls: ["stun:share.example.test:3478"] }],- natPredictionStunUrls: [],- });- });-- it("derives auxiliary listeners from an IPv6 STUN authority", () => {- expect(- createIceConfig({- stunUrls: ["STUN:[2001:db8::1]:3478"],- natPredictionEnabled: true,- }).natPredictionStunUrls,- ).toEqual([- "stun:[2001:db8::1]:3479",- "stun:[2001:db8::1]:3480",- ]);- });-});diff --git a/tests/livekit-token.test.ts b/tests/livekit-token.test.tsdeleted file mode 100644index 9b8b7e55..00000000--- a/tests/livekit-token.test.ts+++ /dev/null@@ -1,94 +0,0 @@-import { describe, expect, it } from "vitest";-import { TokenVerifier } from "livekit-server-sdk";--import { LiveKitTokenIssuer } from "../src/server/livekit-token.ts";--const apiKey = "test-api-key";-const apiSecret = "s".repeat(32);-const publicationGeneration = "publication_12345678";-const shareGeneration = "share_generation_12345678";-const rootPeerId = "viewer_root_12345678";--function issuer(maxViewersPerRoom = 8): LiveKitTokenIssuer {- return new LiveKitTokenIssuer({- apiKey,- apiSecret,- maxViewersPerRoom,- });-}--describe("LiveKitTokenIssuer", () => {- it("issues a generation-bound host token limited to screen sharing", async () => {- const claims = await new TokenVerifier(apiKey, apiSecret).verify(- await issuer().issueToken({- roomId: "42",- role: "host",- peerId: "host_peer_12345678",- shareGeneration,- publicationGeneration,- }),- );-- expect(claims.sub).toBe("host");- expect(claims.exp! - claims.nbf!).toBe(5 * 60);- expect(claims.video).toMatchObject({- roomJoin: true,- room: `screener-v1.42.${shareGeneration}.${publicationGeneration}`,- canPublish: true,- canSubscribe: false,- canPublishData: false,- canUpdateOwnMetadata: false,- canPublishSources: ["screen_share", "screen_share_audio"],- });- expect(claims.roomConfig).toBeUndefined();- });-- it("issues a generation-bound subscribe-only Viewer token", async () => {- const claims = await new TokenVerifier(apiKey, apiSecret).verify(- await issuer(3).issueToken({- roomId: "7",- role: "viewer",- peerId: rootPeerId,- shareGeneration,- publicationGeneration,- }),- );-- expect(claims.sub).toBe(`viewer:${rootPeerId}`);- expect(claims.video).toMatchObject({- roomJoin: true,- room: `screener-v1.7.${shareGeneration}.${publicationGeneration}`,- canPublish: false,- canSubscribe: true,- canPublishData: false,- canUpdateOwnMetadata: false,- });- expect(claims.video?.canPublishSources).toBeUndefined();- expect(claims.roomConfig).toBeUndefined();- });-- it("isolates publication generations in separate LiveKit rooms", async () => {- const tokenIssuer = issuer();- const verifier = new TokenVerifier(apiKey, apiSecret);- const baseRequest = {- roomId: "7",- role: "host" as const,- peerId: "host_peer_12345678",- shareGeneration,- };- const first = await verifier.verify(- await tokenIssuer.issueToken({- ...baseRequest,- publicationGeneration: "generation_first_12345678",- }),- );- const second = await verifier.verify(- await tokenIssuer.issueToken({- ...baseRequest,- publicationGeneration: "generation_second_12345678",- }),- );-- expect(first.video?.room).not.toBe(second.video?.room);- });-});diff --git a/tests/local-server-config.test.ts b/tests/local-server-config.test.tsdeleted file mode 100644index b075ff4e..00000000--- a/tests/local-server-config.test.ts+++ /dev/null@@ -1,113 +0,0 @@-import { describe, expect, it } from "vitest";--import {- createLocalServerConfig,- loadLocalServerConfig,-} from "../src/server/local-config.ts";--describe("local server configuration", () => {- it("maps Client inputs into the common P2P-only server contract", () => {- const config = createLocalServerConfig({- port: 9123,- publicAddress: "192.168.1.10",- allowedAddresses: ["10.0.0.8", "192.168.1.10"],- siteAccessPassword: "local-access-password",- });-- expect(config).toMatchObject({- nodeEnv: "production",- port: 9123,- listenHost: "0.0.0.0",- siteAccessPassword: "local-access-password",- roomLeaseMs: 86_400_000,- maxViewersPerRoom: 20,- peerAssistedMedia: true,- endpointMediaCopyCapacity: 2,- stunUrls: [],- natPredictionEnabled: false,- });- expect(config.publicBaseUrl.href).toBe("http://192.168.1.10:9123/");- expect(config.allowedOrigins).toEqual(new Set([- "http://localhost:9123",- "http://127.0.0.1:9123",- "http://192.168.1.10:9123",- "http://10.0.0.8:9123",- ]));- expect(config.livekitFallback).toBeUndefined();- expect(config.roomDatabasePath).toBeUndefined();- });-- it("loads the internal Client process environment", () => {- const config = loadLocalServerConfig({- SCREENER_CLIENT_PORT: "9234",- SCREENER_CLIENT_LAN_ADDRESS: "192.168.50.4",- SCREENER_CLIENT_ALLOWED_LAN_ADDRESSES: "192.168.50.4, 10.10.0.4",- SCREENER_CLIENT_LOCAL_PASSWORD: "persistent-local-password",- SCREENER_CLIENT_PUBLIC_ORIGIN: "https://small-bright-room.trycloudflare.com",- STUN_URLS: "stun:stun.example:3478, stun:stun.example:3479",- SCREENER_CLIENT_NAT_PREDICTION_STUN_URLS:- "stun:survey-a.example:3478, stun:survey-b.example:3478",- });-- expect(config.port).toBe(9234);- expect(config.publicBaseUrl.origin).toBe(- "https://small-bright-room.trycloudflare.com",- );- expect(config.allowedOrigins).toContain(- "https://small-bright-room.trycloudflare.com",- );- expect(config.allowedOrigins).toContain("http://10.10.0.4:9234");- expect(config.stunUrls).toEqual([- "stun:stun.example:3478",- "stun:stun.example:3479",- ]);- expect(config.natPredictionEnabled).toBe(true);- expect(config.natPredictionStunUrls).toEqual([- "stun:survey-a.example:3478",- "stun:survey-b.example:3478",- ]);- });-- it("leaves the Local site open when no password is supplied", () => {- const config = createLocalServerConfig({- port: 9235,- publicAddress: "192.168.1.10",- });-- expect(config.siteAccessPassword).toBeUndefined();- });-- it("accepts an empty Client password from the process environment", () => {- const config = loadLocalServerConfig({- SCREENER_CLIENT_PORT: "9236",- SCREENER_CLIENT_LAN_ADDRESS: "192.168.50.4",- SCREENER_CLIENT_LOCAL_PASSWORD: "",- });-- expect(config.siteAccessPassword).toBeUndefined();- });-- it.each([- { publicAddress: "localhost", password: "valid-password" },- { publicAddress: "127.0.0.1", password: "valid-password" },- { publicAddress: "0.0.0.0", password: "valid-password" },- { publicAddress: "192.168.1.2", password: "short" },- ])("rejects an invalid Local authority input", ({ publicAddress, password }) => {- expect(() => createLocalServerConfig({- publicAddress,- siteAccessPassword: password,- })).toThrow();- });-- it.each([- "http://public.example",- "https://public.example/path",- "https://[email protected]",- ])("rejects invalid public origin %s", (publicOrigin) => {- expect(() => createLocalServerConfig({- publicAddress: "192.168.1.2",- publicOrigin,- siteAccessPassword: "valid-password",- })).toThrow("Local public origin must be an HTTPS origin");- });-});diff --git a/tests/media-assignment.test.ts b/tests/media-assignment.test.tsindex 449d7b6f..473d6846 100644--- a/tests/media-assignment.test.ts+++ b/tests/media-assignment.test.ts@@ -6,7 +6,6 @@ import {limitMediaAssignment,MAX_ENDPOINT_MEDIA_CHILDREN,reconcileBoundedMediaChildren,- retainSelectedMediaParent,viewerRestartMessage,viewerSignalMessage,} from "../src/client/webrtc/media-assignment.ts";@@ -63,49 +62,14 @@ describe("peer-assisted client assignment", () => {]);});- it("updates selected Viewer children without replacing its retained parent", () => {- expect(- retainSelectedMediaParent(- {- parentPeerId: null,- childPeerIds: ["new-child_12345678"],- },- "selected-parent_12345678",- ),- ).toEqual({- parentPeerId: "selected-parent_12345678",- childPeerIds: ["new-child_12345678"],- });- });-- it("leaves ordinary viewer signaling untargeted", () => {- expect(viewerSignalMessage(false, "host_12345678", offer)).toEqual({- type: "signal",- payload: offer,- });- expect(- viewerRestartMessage(- false,- "host_12345678",- "connection_12345678",- true,- ),- ).toEqual({- type: "restart-request",- connectionId: "connection_12345678",- rebuild: true,- });- });-- it("targets peer-assisted signaling at the assigned parent", () => {- expect(viewerSignalMessage(true, "parent_12345678", offer)).toEqual({+ it("targets signaling at the assigned parent", () => {+ expect(viewerSignalMessage("parent_12345678", offer)).toEqual({type: "signal",targetPeerId: "parent_12345678",payload: offer,});expect(viewerRestartMessage(- true,"parent_12345678","connection_12345678",false,@@ -122,7 +86,6 @@ describe("peer-assisted client assignment", () => {let active = false;const messages: unknown[] = [];const sendRestart = createOwnedViewerRestartSender(- true,(targetPeerId, connectionId) =>active &&targetPeerId === "parent_12345678" &&diff --git a/tests/native-client.test.ts b/tests/native-client.test.tsindex ab90425c..6aeb819e 100644--- a/tests/native-client.test.ts+++ b/tests/native-client.test.ts@@ -321,5 +321,12 @@ describe("native Client private wire", () => {expect(nativeEventSchema.safeParse({ ...event, reason: "none" }).success,).toBe(false);+ expect(+ nativeEventSchema.safeParse({+ ...event,+ state: "unknown",+ reason: null,+ }).success,+ ).toBe(true);});});diff --git a/tests/native-media-bridge.test.ts b/tests/native-media-bridge.test.tsindex a878a224..45154b7d 100644--- a/tests/native-media-bridge.test.ts+++ b/tests/native-media-bridge.test.ts@@ -217,4 +217,19 @@ describe("native media bridge", () => {expect(current.peer().close).toHaveBeenCalledOnce();expect(current.control.closeEdge).toHaveBeenCalledOnce();});++ it("rejects a pending start when the bridge is disposed", async () => {+ const current = fixture();+ const starting = current.bridge.start();+ await vi.waitFor(() => {+ expect(current.peer().setLocalDescription).toHaveBeenCalledOnce();+ });++ current.bridge.dispose();++ await expect(starting).rejects.toThrow("Native media bridge failed");+ expect(current.onFailed).not.toHaveBeenCalled();+ expect(current.peer().close).toHaveBeenCalledOnce();+ expect(current.control.closeEdge).toHaveBeenCalledOnce();+ });});diff --git a/tests/protocol-fixture.test.ts b/tests/protocol-fixture.test.tsnew file mode 100644index 00000000..c4e9ea0e--- /dev/null+++ b/tests/protocol-fixture.test.ts@@ -0,0 +1,196 @@+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";++import { describe, expect, it } from "vitest";++import {+ DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY,+ MAX_ENDPOINT_MEDIA_COPY_CAPACITY,+} from "../src/shared/media-copy-accounting.js";+import {+ DEFAULT_HOST_DISPLAY_NAME_PREFIX,+ DEFAULT_QUALITY_SETTINGS,+ DEFAULT_ROUTE_POLICY,+ DEFAULT_VIEWER_DISPLAY_NAME,+ MAX_DISPLAY_NAME_CODE_POINTS,+ MAX_ICE_SERVER_URLS,+ MAX_MEDIA_ROUTE_REVISION,+ MAX_NAT_PREDICTION_AUXILIARY_STUN_URLS,+ MAX_PARTICIPANTS_PER_ROOM_LIMIT,+ MAX_SFU_TOKEN_LENGTH,+ MAX_SIGNAL_BYTES,+ MAX_VIEWER_PASSWORD_LENGTH,+ MAX_VIEWER_QUALITY_EVIDENCE_BYTES,+ MAX_VIEWERS_PER_ROOM_LIMIT,+ MIN_VIEWER_PASSWORD_LENGTH,+ PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS,+ ROOM_CODE_LENGTH,+ SIGNAL_CLOSE_CODES,+ SIGNALING_PROTOCOL,+ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS,+ VIEWER_QUALITY_EVIDENCE_INTERVAL_MS,+ clientMessageSchema,+ createRoomRequestSchema,+ replaceRoomRequestSchema,+ roomAccessUpdateRequestSchema,+ serverMessageSchema,+} from "../src/shared/protocol.js";++interface ClientSample {+ name: string;+ schema: "client" | "createRoomRequest" | "replaceRoomRequest" | "roomAccessUpdateRequest";+ json: string;+ valid: boolean;+}++interface ServerSample {+ name: string;+ json: string;+}++interface WireFixture {+ constants: Record<string, unknown>;+ clientMessages: ClientSample[];+ serverMessages: ServerSample[];+}++const fixture = JSON.parse(+ readFileSync(+ fileURLToPath(new URL("./fixtures/wire-samples.json", import.meta.url)),+ "utf8",+ ),+) as WireFixture;++const requestSchemas = {+ client: clientMessageSchema,+ createRoomRequest: createRoomRequestSchema,+ replaceRoomRequest: replaceRoomRequestSchema,+ roomAccessUpdateRequest: roomAccessUpdateRequestSchema,+} as const;++describe("shared wire fixture", () => {+ it("carries the protocol constants the Go port mirrors", () => {+ expect(fixture.constants).toEqual({+ signalingProtocol: SIGNALING_PROTOCOL,+ maxViewersPerRoomLimit: MAX_VIEWERS_PER_ROOM_LIMIT,+ maxParticipantsPerRoomLimit: MAX_PARTICIPANTS_PER_ROOM_LIMIT,+ maxSignalBytes: MAX_SIGNAL_BYTES,+ roomCodeLength: ROOM_CODE_LENGTH,+ maxMediaRouteRevision: MAX_MEDIA_ROUTE_REVISION,+ maxSfuTokenLength: MAX_SFU_TOKEN_LENGTH,+ maxIceServerUrls: MAX_ICE_SERVER_URLS,+ maxNatPredictionAuxiliaryStunUrls: MAX_NAT_PREDICTION_AUXILIARY_STUN_URLS,+ maxViewerQualityEvidenceBytes: MAX_VIEWER_QUALITY_EVIDENCE_BYTES,+ viewerQualityEvidenceIntervalMs: VIEWER_QUALITY_EVIDENCE_INTERVAL_MS,+ viewerQualityEvidenceExpiryMs: VIEWER_QUALITY_EVIDENCE_EXPIRY_MS,+ persistentNativeEdgeDegradedWindows: PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS,+ maxDisplayNameCodePoints: MAX_DISPLAY_NAME_CODE_POINTS,+ defaultViewerDisplayName: DEFAULT_VIEWER_DISPLAY_NAME,+ defaultHostDisplayNamePrefix: DEFAULT_HOST_DISPLAY_NAME_PREFIX,+ minViewerPasswordLength: MIN_VIEWER_PASSWORD_LENGTH,+ maxViewerPasswordLength: MAX_VIEWER_PASSWORD_LENGTH,+ defaultEndpointMediaCopyCapacity: DEFAULT_ENDPOINT_MEDIA_COPY_CAPACITY,+ maxEndpointMediaCopyCapacity: MAX_ENDPOINT_MEDIA_COPY_CAPACITY,+ signalCloseCodeServiceRestart: SIGNAL_CLOSE_CODES.serviceRestart,+ signalCloseCodeSessionReplaced: SIGNAL_CLOSE_CODES.sessionReplaced,+ signalCloseCodeClientReconnect: SIGNAL_CLOSE_CODES.clientReconnect,+ signalCloseCodeAuthenticationFailed: SIGNAL_CLOSE_CODES.authenticationFailed,+ signalCloseCodeViewerAccessRevoked: SIGNAL_CLOSE_CODES.viewerAccessRevoked,+ defaultQualitySettings: DEFAULT_QUALITY_SETTINGS,+ defaultRoutePolicy: DEFAULT_ROUTE_POLICY,+ });+ });++ it("covers every client message type and request body", () => {+ const covered = new Set<string>();+ for (const sample of fixture.clientMessages) {+ if (!sample.valid) {+ continue;+ }+ const value = JSON.parse(sample.json) as Record<string, unknown>;+ covered.add(+ sample.schema === "client"+ ? `client:${String(value.type)}`+ : sample.schema === "roomAccessUpdateRequest"+ ? `roomAccessUpdateRequest:${String(value.action)}`+ : sample.schema,+ );+ }+ expect([...covered].sort()).toEqual(+ [+ "client:abandon-room",+ "client:authenticate",+ "client:refresh-sfu",+ "client:relay-capacity",+ "client:request-route-diagnostic",+ "client:reset-sender-quality",+ "client:restart-request",+ "client:route-failed",+ "client:route-media-unavailable",+ "client:route-ready",+ "client:route-transport-connected",+ "client:sender-quality-evidence",+ "client:set-display-name",+ "client:set-quality-settings",+ "client:set-sharing-paused",+ "client:sfu-publisher-quality-evidence",+ "client:signal",+ "client:signaling-challenge",+ "client:stop-sharing",+ "client:viewer-quality-evidence",+ "createRoomRequest",+ "replaceRoomRequest",+ "roomAccessUpdateRequest:revoke-viewer-grant",+ "roomAccessUpdateRequest:rotate-viewer-grant",+ "roomAccessUpdateRequest:set-code-entry-policy",+ "roomAccessUpdateRequest:set-viewer-password",+ ].sort(),+ );+ });++ it.each(fixture.clientMessages.map((sample) => [sample.name, sample] as const))(+ "client sample %s matches its recorded validity",+ (_name, sample) => {+ expect(+ requestSchemas[sample.schema].safeParse(JSON.parse(sample.json)).success,+ ).toBe(sample.valid);+ },+ );++ it("covers every server message variant", () => {+ const covered = new Set(+ fixture.serverMessages.map(+ (sample) => (JSON.parse(sample.json) as { type: string }).type,+ ),+ );+ expect([...covered].sort()).toEqual([+ "authenticated",+ "error",+ "host-status",+ "pause-sharing-source",+ "quality-settings",+ "restart-request",+ "room-closed",+ "route-diagnostic-snapshot",+ "route-policy",+ "route-status",+ "route-update",+ "sfu-config",+ "sharing-stopped",+ "signal",+ "signaling-challenge-response",+ "viewer-grant-revoked",+ "viewer-presence",+ "viewer-quality-evidence",+ ]);+ });++ it.each(fixture.serverMessages.map((sample) => [sample.name, sample] as const))(+ "server sample %s parses",+ (_name, sample) => {+ expect(serverMessageSchema.safeParse(JSON.parse(sample.json)).success).toBe(+ true,+ );+ },+ );+});diff --git a/tests/protocol.test.ts b/tests/protocol.test.tsindex d6233244..0885fac4 100644--- a/tests/protocol.test.ts+++ b/tests/protocol.test.ts@@ -88,7 +88,7 @@ const qualityEvidence = {describe("client signaling protocol", () => {it("uses the current strict signaling generation", () => {- expect(SIGNALING_PROTOCOL).toBe("screener-v20");+ expect(SIGNALING_PROTOCOL).toBe("screener-v21");});it("keeps signaling challenges strict and sequence-only", () => {@@ -1244,7 +1244,7 @@ describe("server signaling protocol", () => {).toBe(false);});- function authenticatedMessage(maxViewers: number, viewerPeerIds: string[] = []) {+ function authenticatedMessage(maxViewers: number) {return {type: "authenticated",protocol: SIGNALING_PROTOCOL,@@ -1255,7 +1255,16 @@ describe("server signaling protocol", () => {endpointMediaCopyCapacity: 2,hostOnline: true,connectionId: null,- viewerPeerIds,+ mediaMode: "peer-assisted",+ shareGeneration: "share_generation_12345678",+ routeRevision: 0,+ routeAssignment: {+ upstream: { kind: "none" },+ childPeerIds: [],+ sfuPublicationGeneration: null,+ },+ qualitySettings,+ routePolicy: DEFAULT_ROUTE_POLICY,codeEntryPolicy: "open",viewerPasswordEnabled: false,viewerAuthorizationGeneration: "viewer_generation_12345678",@@ -1276,7 +1285,6 @@ describe("server signaling protocol", () => {...authenticatedMessage(8),role: "viewer",peerId: "viewer_12345678",- viewerPeerIds: [],} as Record<string, unknown>;delete viewer.viewerPasswordEnabled;expect(serverMessageSchema.safeParse(viewer).success).toBe(true);@@ -1331,26 +1339,6 @@ describe("server signaling protocol", () => {}});- it("accepts only a strict peer-waiting notification", () => {- expect(- serverMessageSchema.safeParse({- type: "peer-waiting",- peerId: "viewer_12345678",- }).success,- ).toBe(true);- expect(- serverMessageSchema.safeParse({- type: "peer-waiting",- peerId: "viewer_12345678",- active: false,- }).success,- ).toBe(false);- expect(- serverMessageSchema.safeParse({ type: "peer-waiting", peerId: "short" })- .success,- ).toBe(false);- });-it("accepts a strict, unique and bounded Viewer presence snapshot", () => {const viewer = {role: "viewer",@@ -1444,15 +1432,11 @@ describe("server signaling protocol", () => {sfuStandbyUrl: "wss://sfu.example.com",}).success,).toBe(true);- expect(- serverMessageSchema.safeParse({- ...authenticatedMessage(8),- mediaMode: "peer-assisted",- routeRevision: 0,- routeAssignment: peerAssisted.routeAssignment,- qualitySettings,- }).success,- ).toBe(false);+ const incomplete = {+ ...authenticatedMessage(8),+ } as Record<string, unknown>;+ delete incomplete.routeAssignment;+ expect(serverMessageSchema.safeParse(incomplete).success).toBe(false);expect(serverMessageSchema.safeParse({...peerAssisted,@@ -1473,18 +1457,11 @@ describe("server signaling protocol", () => {qualitySettings: { ...qualitySettings, maxBitrate: 20_000_000 },}).success,).toBe(false);- expect(- serverMessageSchema.safeParse({- ...authenticatedMessage(8),- qualitySettings,- }).success,- ).toBe(false);- expect(- serverMessageSchema.safeParse({- ...authenticatedMessage(8),- sfuStandbyUrl: "wss://sfu.example.com",- }).success,- ).toBe(false);+ const missingMode = {+ ...authenticatedMessage(8),+ } as Record<string, unknown>;+ delete missingMode.mediaMode;+ expect(serverMessageSchema.safeParse(missingMode).success).toBe(false);expect(serverMessageSchema.safeParse({...peerAssisted,@@ -1530,7 +1507,7 @@ describe("server signaling protocol", () => {}});- it("keeps hybrid route messages strict and separate from ordinary P2P auth", () => {+ it("keeps route messages strict alongside the single authenticated mode", () => {const assignment = {upstream: { kind: "peer", peerId: "parent_12345678" },childPeerIds: ["child_12345678", "child_87654321"],@@ -1629,7 +1606,7 @@ describe("server signaling protocol", () => {expect(serverMessageSchema.safeParse({...authenticatedMessage(8),- routeRevision: 9,+ routeRevision: MAX_MEDIA_ROUTE_REVISION + 1,}).success,).toBe(false);});@@ -1710,24 +1687,4 @@ describe("server signaling protocol", () => {},);- it("bounds authenticated viewer rosters independently of configured capacity", () => {- const viewerPeerIds = Array.from(- { length: MAX_VIEWERS_PER_ROOM_LIMIT },- (_, index) => `viewer_${index.toString().padStart(8, "0")}`,- );-- expect(- serverMessageSchema.safeParse(- authenticatedMessage(MAX_VIEWERS_PER_ROOM_LIMIT, viewerPeerIds),- ).success,- ).toBe(true);- expect(- serverMessageSchema.safeParse(- authenticatedMessage(MAX_VIEWERS_PER_ROOM_LIMIT, [- ...viewerPeerIds,- "viewer_overflow",- ]),- ).success,- ).toBe(false);- });});diff --git a/tests/relay-capability.test.ts b/tests/relay-capability.test.tsindex b12ce2d3..eca290b2 100644--- a/tests/relay-capability.test.ts+++ b/tests/relay-capability.test.ts@@ -6,13 +6,10 @@ import {describe("browser relay capability", () => {it("advertises the endpoint capability envelope without a Browser tier", () => {- expect(relayCapacityMessageForBrowser(true)).toEqual({+ expect(relayCapacityMessageForBrowser()).toEqual({type: "relay-capacity",downstreamEdges: 3,});});- it("does not create a relay message for ordinary P2P", () => {- expect(relayCapacityMessageForBrowser(false)).toBeNull();- });});diff --git a/tests/release-app-recovery.sh b/tests/release-app-recovery.shindex 22a7d809..65e8e454 100644--- a/tests/release-app-recovery.sh+++ b/tests/release-app-recovery.sh@@ -100,8 +100,10 @@ run_recover() {reset_releaserelease_owned=1+ln -s "$release" "${current}.${release_id}-$$"run_recover 37test ! -e "$release"+test ! -e "${current}.${release_id}-$$"reset_releaserelease_owned=0diff --git a/tests/release-update.test.ts b/tests/release-update.test.tsindex c7d1eb53..37bc0046 100644--- a/tests/release-update.test.ts+++ b/tests/release-update.test.ts@@ -6,10 +6,9 @@ import {parseReleaseMetadata,} from "../src/client/lib/release-update";-// The Node checker and the Browser checker deliberately share the same release-// contract while keeping their runtime boundaries independent.-// @ts-expect-error The executable helper has no generated TypeScript declaration.-import * as nodeRelease from "../scripts/release-update.mjs";+// The operator checker (cmd/screener-server --check-release, covered by+// cmd/screener-server/release_test.go) shares this release contract while+// keeping its runtime boundary independent.const currentRevision = "a".repeat(40);const latestRevision = "b".repeat(40);@@ -67,43 +66,3 @@ describe("Client release update notice", () => {).resolves.toBeNull();});});--describe("operator release checker", () => {- it("uses the same full-SHA release contract and status values", async () => {- const fetchImpl = async () => ({- ok: true,- json: async () => release,- });- await expect(- nodeRelease.checkRelease({ currentRevision, fetchImpl }),- ).resolves.toEqual({- status: "update-available",- currentRevision,- latestRevision,- releaseUrl: release.html_url,- });- await expect(- nodeRelease.checkRelease({ currentRevision: latestRevision, fetchImpl }),- ).resolves.toMatchObject({ status: "up-to-date" });- expect(nodeRelease.UPDATE_EXIT_CODES).toEqual({- upToDate: 0,- available: 10,- unavailable: 20,- });- });-- it("never forwards an operator token to a non-GitHub fixture endpoint", async () => {- let receivedHeaders: Record<string, string> | undefined;- const fetchImpl = async (_input: string, init?: RequestInit) => {- receivedHeaders = Object.fromEntries(new Headers(init?.headers));- return { ok: true, json: async () => release };- };- await nodeRelease.checkRelease({- currentRevision,- apiURL: "http://127.0.0.1:8787/releases/latest",- token: "fixture-secret",- fetchImpl,- });- expect(receivedHeaders?.authorization).toBeUndefined();- });-});diff --git a/tests/room-database.test.ts b/tests/room-database.test.tsdeleted file mode 100644index 3d5aa09f..00000000--- a/tests/room-database.test.ts+++ /dev/null@@ -1,437 +0,0 @@-import { createHash } from "node:crypto";-import { mkdtempSync, rmSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { DatabaseSync } from "node:sqlite";--import { afterEach, describe, expect, it } from "vitest";--import { RoomDatabase } from "../src/server/room-database.ts";-import { RoomStore, RoomStoreError } from "../src/server/room-store.ts";--interface MutableClock {- nowMs: number;-}--const temporaryDirectories: string[] = [];-const stores: RoomStore[] = [];--afterEach(() => {- for (const store of stores.splice(0).reverse()) {- store.close();- }- for (const directory of temporaryDirectories.splice(0).reverse()) {- rmSync(directory, { recursive: true, force: true });- }-});--function databasePath(): string {- const directory = mkdtempSync(join(tmpdir(), "screener-room-db-"));- temporaryDirectories.push(directory);- return join(directory, "rooms.sqlite");-}--function stableStore(- path: string,- clock: MutableClock,- options: { maxRooms?: number; leaseMs?: number } = {},-): RoomStore {- const store = new RoomStore({- leaseMs: options.leaseMs ?? 1_000,- maxRooms: options.maxRooms ?? 8,- maxViewersPerRoom: 8,- now: () => clock.nowMs,- database: new RoomDatabase(path),- });- store.initialize();- stores.push(store);- return store;-}--function hostInput(- roomId: string,- hostToken: string,- sessionId = "host-session",-) {- return {- roomId,- role: "host" as const,- token: hostToken,- clientId: "host-client",- sessionId,- };-}--function viewerInput(- roomId: string,- sessionId: string,- viewerGrant?: string,-) {- return {- roomId,- role: "viewer" as const,- ...(viewerGrant ? { viewerGrant } : {}),- clientId: `client-${sessionId}`,- sessionId,- };-}--function closeStore(store: RoomStore): void {- store.close();- const index = stores.indexOf(store);- if (index >= 0) {- stores.splice(index, 1);- }-}--describe("SQLite stable room authority", () => {- it("does not persist a room when password derivation is busy", async () => {- const path = databasePath();- const clock = { nowMs: 1_000 };- const first = stableStore(path, clock, { maxRooms: 1 });- const attempts = Array.from({ length: 18 }, (_, index) =>- first.connectViewerWithPassword(- {- roomId: "9999",- password: "gate-password",- clientId: `gate-client-${index}`,- sessionId: `gate-session-${index}`,- },- () => index < 2,- ),- );- try {- await expect(- first.createRoom("private", "room-password", "4321"),- ).rejects.toEqual(new RoomStoreError("ROOM_BUSY"));- } finally {- await Promise.allSettled(attempts);- }- expect(first.size).toBe(0);- closeStore(first);-- const second = stableStore(path, clock, { maxRooms: 1 });- expect(second.size).toBe(0);- expect((await second.createRoom("private", null, "4321")).roomId).toBe(- "4321",- );- });-- it("restores the exact authority aggregate without participants", async () => {- const path = databasePath();- const clock = { nowMs: 1_000 };- const first = stableStore(path, clock);- const room = await first.createRoom("open", null, "4321");- first.setCodeEntryPolicy(room.roomId, "private", room.hostToken);- await first.setViewerPassword(- room.roomId,- "room-password",- room.hostToken,- );- const rotated = first.setViewerGrant(- room.roomId,- "rotate",- room.hostToken,- );- const host = first.connectParticipant(- hostInput(room.roomId, room.hostToken),- );- const oldViewer = first.connectParticipant(- viewerInput(room.roomId, "old-viewer", rotated.viewerGrant!),- );- expect(first.getConnectedHost(room.roomId)).toMatchObject({- peerId: host.peerId,- });- expect(first.getConnectedViewer(room.roomId, oldViewer.peerId)).toBeDefined();- closeStore(first);-- clock.nowMs = 2_000;- const second = stableStore(path, clock);- expect(second.size).toBe(1);- expect(second.getConnectedHost(room.roomId)).toBeUndefined();- expect(second.getConnectedViewers(room.roomId)).toEqual([]);- expect(() =>- second.connectParticipant(- viewerInput(room.roomId, "revoked-grant", room.viewerGrant!),- ),- ).toThrow(new RoomStoreError("INVALID_TOKEN"));-- const granted = second.connectParticipant(- viewerInput(room.roomId, "current-grant", rotated.viewerGrant!),- );- expect(granted.expiresAt).toBe(new Date(3_000).toISOString());- expect(granted.viewerAuthorizationGeneration).toBe(- rotated.viewerAuthorizationGeneration,- );- await expect(- second.connectViewerWithPassword({- roomId: room.roomId,- password: "room-password",- clientId: "password-client",- sessionId: "password-session",- }),- ).resolves.toMatchObject({ codeEntryPolicy: "private" });- expect(() =>- second.connectParticipant(hostInput(room.roomId, "wrong-token")),- ).toThrow(new RoomStoreError("INVALID_TOKEN"));- expect(- second.connectParticipant(- hostInput(room.roomId, room.hostToken, "recovered-host"),- ).expiresAt,- ).toBeNull();- closeStore(second);-- const raw = new DatabaseSync(path);- try {- const row = raw.prepare("SELECT * FROM rooms").get() as Record<- string,- unknown- >;- expect(Object.keys(row).sort()).toEqual(- [- "room_id",- "host_token_digest",- "viewer_grant_digest",- "viewer_authorization_generation",- "code_entry_policy",- "viewer_password_material",- "lease_expires_at_ms",- ].sort(),- );- expect(Buffer.from(row.host_token_digest as Uint8Array)).toEqual(- createHash("sha256").update(room.hostToken).digest(),- );- expect(Buffer.from(row.viewer_grant_digest as Uint8Array)).toEqual(- createHash("sha256").update(rotated.viewerGrant!).digest(),- );- expect(row.viewer_password_material).toBeInstanceOf(Uint8Array);- expect(Buffer.from(row.viewer_password_material as Uint8Array)).toHaveLength(- 48,- );- expect(JSON.stringify(row)).not.toContain(room.hostToken);- expect(JSON.stringify(row)).not.toContain(rotated.viewerGrant!);- expect(JSON.stringify(row)).not.toContain("room-password");- } finally {- raw.close();- }- });-- it("converts an active marker once and preserves dormant deadlines", async () => {- const path = databasePath();- const clock = { nowMs: 100 };- const first = stableStore(path, clock);- const room = await first.createRoom("open", null, "5678");- first.connectParticipant(hostInput(room.roomId, room.hostToken));- closeStore(first);-- clock.nowMs = 500;- const second = stableStore(path, clock);- const firstRestart = second.connectParticipant(- viewerInput(room.roomId, "first-restart", room.viewerGrant!),- );- expect(firstRestart.expiresAt).toBe(new Date(1_500).toISOString());- closeStore(second);-- clock.nowMs = 700;- const third = stableStore(path, clock);- const secondRestart = third.connectParticipant(- viewerInput(room.roomId, "second-restart", room.viewerGrant!),- );- expect(secondRestart.expiresAt).toBe(new Date(1_500).toISOString());- closeStore(third);-- clock.nowMs = 1_501;- const fourth = stableStore(path, clock);- expect(fourth.size).toBe(0);- const replacement = await fourth.createRoom("open", null, room.roomId);- expect(replacement.roomId).toBe(room.roomId);- expect(() =>- fourth.connectParticipant(hostInput(room.roomId, room.hostToken)),- ).toThrow(new RoomStoreError("INVALID_TOKEN"));- expect(() =>- fourth.connectParticipant(- viewerInput(room.roomId, "stale-grant", room.viewerGrant!),- ),- ).toThrow(new RoomStoreError("INVALID_TOKEN"));- });-- it("preserves the exact Host disconnect deadline", async () => {- const path = databasePath();- const clock = { nowMs: 100 };- const first = stableStore(path, clock);- const room = await first.createRoom("open", null, "5890");- const host = first.connectParticipant(- hostInput(room.roomId, room.hostToken),- );- clock.nowMs = 250;- first.disconnectParticipant(room.roomId, host.peerId, "host-session");- closeStore(first);-- clock.nowMs = 500;- const second = stableStore(path, clock);- expect(- second.connectParticipant(- viewerInput(room.roomId, "dormant-viewer", room.viewerGrant!),- ).expiresAt,- ).toBe(new Date(1_250).toISOString());- });-- it("persists explicit room deletion before recycling its code", async () => {- const path = databasePath();- const clock = { nowMs: 10 };- const first = stableStore(path, clock);- const room = await first.createRoom("open", null, "6789");- expect(first.abandonRoom(room.roomId)?.roomId).toBe(room.roomId);- closeStore(first);-- const second = stableStore(path, clock);- expect(second.size).toBe(0);- const replacement = await second.createRoom("open", null, room.roomId);- expect(replacement.roomId).toBe(room.roomId);- expect(replacement.hostToken).not.toBe(room.hostToken);- expect(replacement.viewerGrant).not.toBe(room.viewerGrant);- });-- it("rolls back a batch expiry when any exact room authority is stale", async () => {- const path = databasePath();- const clock = { nowMs: 10 };- const first = stableStore(path, clock);- await first.createRoom("open", null, "4321");- await first.createRoom("open", null, "5678");- closeStore(first);-- const database = new RoomDatabase(path);- const restored = database.initialize(clock.nowMs, 1_010);- expect(restored).toHaveLength(2);- expect(() =>- database.deleteRooms([- {- roomId: restored[0]!.roomId,- hostTokenDigest: restored[0]!.hostTokenDigest,- },- {- roomId: restored[1]!.roomId,- hostTokenDigest: Buffer.alloc(32),- },- ]),- ).toThrow("Room database delete did not match current authority");- database.close();-- const second = stableStore(path, clock);- expect(second.size).toBe(2);- });-- it("persists room replacement as one authority transition", async () => {- const path = databasePath();- const clock = { nowMs: 10 };- const first = stableStore(path, clock);- const original = await first.createRoom("open", null, "4321");- const replacement = await first.replaceRoom(- original.roomId,- original.hostToken,- "private",- "new-password",- );- closeStore(first);-- const second = stableStore(path, clock);- expect(second.size).toBe(1);- expect(() =>- second.connectParticipant(- hostInput(original.roomId, original.hostToken),- ),- ).toThrow(new RoomStoreError("INVALID_TOKEN"));- expect(- second.connectParticipant(- viewerInput(- replacement.created.roomId,- "replacement-viewer",- replacement.created.viewerGrant!,- ),- ).roomId,- ).toBe(replacement.created.roomId);- await expect(- second.connectViewerWithPassword({- roomId: replacement.created.roomId,- password: "new-password",- clientId: "password-viewer",- sessionId: "password-session",- }),- ).resolves.toMatchObject({ roomId: replacement.created.roomId });- });-- it("rejects another owner of the same database", () => {- const path = databasePath();- const first = new RoomDatabase(path);- first.initialize(0, 1_000);- try {- const contender = new RoomDatabase(path);- expect(() => contender.initialize(0, 1_000)).toThrow(/locked/i);- contender.close();- } finally {- first.close();- }-- const successor = new RoomDatabase(path);- expect(successor.initialize(0, 1_000)).toEqual([]);- successor.close();- });-- it.each([- ["application identity", "PRAGMA application_id = 1"],- ["schema version", "PRAGMA user_version = 2"],- ])("rejects an unknown %s", (_name, mutation) => {- const path = databasePath();- const initial = new RoomDatabase(path);- initial.initialize(0, 1_000);- initial.close();-- const raw = new DatabaseSync(path);- raw.exec(mutation);- raw.close();-- const reopened = new RoomDatabase(path);- expect(() => reopened.initialize(0, 1_000)).toThrow(/does not match/);- reopened.close();- });-- it("rejects an altered current-version schema", () => {- const path = databasePath();- const initial = new RoomDatabase(path);- initial.initialize(0, 1_000);- initial.close();-- const raw = new DatabaseSync(path);- raw.exec("ALTER TABLE rooms ADD COLUMN unexpected TEXT");- raw.close();-- const reopened = new RoomDatabase(path);- expect(() => reopened.initialize(0, 1_000)).toThrow(- "Room database columns do not match the current schema",- );- reopened.close();- });-- it("rejects corrupt authority rows instead of partially restoring them", async () => {- const path = databasePath();- const clock = { nowMs: 100 };- const initial = stableStore(path, clock);- await initial.createRoom("open", null, "7890");- closeStore(initial);-- const raw = new DatabaseSync(path);- raw.exec("PRAGMA ignore_check_constraints = ON");- raw.prepare("UPDATE rooms SET host_token_digest = zeroblob(31)").run();- raw.close();-- const reopened = new RoomStore({- leaseMs: 1_000,- maxRooms: 8,- maxViewersPerRoom: 8,- now: () => clock.nowMs,- database: new RoomDatabase(path),- });- expect(() => reopened.initialize()).toThrow(/integrity|Host token/i);- reopened.close();- });-});diff --git a/tests/room-route-controller.test.ts b/tests/room-route-controller.test.tsdeleted file mode 100644index ced8759c..00000000--- a/tests/room-route-controller.test.ts+++ /dev/null@@ -1,5121 +0,0 @@-import { describe, expect, it } from "vitest";--import type { ViewerQualityEvidenceMetrics } from "../src/shared/protocol.ts";--import {- RoomRouteController,- type CandidateGuard,- type CandidateCursorGuard,- type CandidateReservation,- type CommittedEdgeSeed,- type OperationSnapshot,-} from "../src/server/room-route-controller.ts";--const HOST = "host_12345678";-const A = "viewer_a_12345678";-const B = "viewer_b_12345678";-const C = "viewer_c_12345678";-const D = "viewer_d_12345678";-const E = "viewer_e_12345678";-const F = "viewer_f_12345678";--function controller(- capacity: 1 | 2 | 3 = 2,- options: {- sfuEnabled?: boolean;- qualityConvergenceEnabled?: boolean;- operationTimeoutMs?: number;- natPredictionEnabled?: boolean;- } = {},-) {- const routes = new RoomRouteController<string>({- hostPeerId: HOST,- endpointMediaCopyCapacity: capacity,- operationTimeoutMs: 10_000,- ...options,- });- routes.upsertParticipant({- peerId: HOST,- role: "host",- sessionId: "host_session",- effectiveDownstreamCapacity: capacity,- });- return routes;-}--function addViewer(- routes: RoomRouteController<string>,- peerId: string,- capacity: 0 | 1 | 2 | 3,- nowMs?: number,-) {- routes.upsertParticipant({- peerId,- role: "viewer",- sessionId: `${peerId}_session`,- effectiveDownstreamCapacity: capacity,- }, nowMs);-}--function cursorGuard(operation: OperationSnapshot): CandidateCursorGuard {- return {- childPeerId: operation.childPeerId,- childSessionId: operation.childSessionId,- baseRevision: operation.baseRevision,- factVersion: operation.factVersion,- cursor: operation.cursor,- plan: operation.candidates[operation.cursor]!,- };-}--function beginCandidate(- routes: RoomRouteController<string>,- input: {- nowMs: number;- connectionId: string;- reservation: CandidateReservation<string>;- publicationGeneration?: string;- publicationConnectionId?: string;- hostSessionId?: string;- },-) {- const operation = routes.snapshot().operation!;- return routes.beginCurrentCandidate({- guard: cursorGuard(operation),- ...(input.reservation.kind === "direct"- ? {}- : { hostSessionId: input.hostSessionId ?? "host_session" }),- ...input,- });-}--function skipCandidate(routes: RoomRouteController<string>, nowMs: number) {- const operation = routes.snapshot().operation!;- return routes.skipCurrentCandidate(cursorGuard(operation), nowMs);-}--function commitCurrent(- routes: RoomRouteController<string>,- nowMs: number,- connectionId: string,-) {- const begin = beginCandidate(routes, {- nowMs,- connectionId,- reservation: { kind: "direct" },- });- const prepared = begin.operation!;- const current = prepared.current!;- const guard: CandidateGuard = {- childPeerId: prepared.childPeerId,- childSessionId: prepared.childSessionId,- revision: current.revision,- connectionId,- };- expect(routes.candidateReady(guard, nowMs + 1).accepted).toBe(true);- return guard;-}--function peerEdge(- parentPeerId: string,- connectionId: string,- usable = true,-): CommittedEdgeSeed<string> {- return {- kind: "peer",- parentPeerId,- transport: "direct",- connectionId,- usable,- physicalActive: true,- };-}--function retireLastSfuPublicationAfterReuseDeadline(): {- routes: RoomRouteController<string>;- nowMs: number;-} {- const routes = controller(2, { sfuEnabled: true });- for (const [peerId, connectionId] of [- [B, "b_from_host"],- [C, "c_from_host"],- ] as const) {- addViewer(routes, peerId, 0);- routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));- }- addViewer(routes, A, 0, 0);-- const bootstrap = routes.reconcile(0).operation!;- expect(bootstrap).toMatchObject({- demandPeerId: A,- reason: "sfu-bootstrap",- candidates: [- {- tuple: { kind: "sfu", publication: "create" },- },- ],- });- const carrierPeerId = bootstrap.childPeerId;- const carrier = beginCandidate(routes, {- nowMs: 1,- connectionId: "carrier_sfu",- publicationGeneration: "publication_generation",- publicationConnectionId: "publication_connection",- reservation: {- kind: "sfu-create",- edge: "carrier_subscription",- publication: "publication_resource",- overlap: "publication_overlap",- },- }).operation!;- expect(- routes.candidateReady(- {- childPeerId: carrier.childPeerId,- childSessionId: carrier.childSessionId,- revision: carrier.current!.revision,- connectionId: "carrier_sfu",- },- 2,- ).accepted,- ).toBe(true);-- const demand = routes.reconcile(3).operation!;- expect(demand).toMatchObject({- childPeerId: A,- demandPeerId: A,- candidates: [- {- tuple: { kind: "sfu", publication: "reuse" },- },- ],- });- beginCandidate(routes, {- nowMs: 4,- connectionId: "demand_sfu_reuse",- reservation: { kind: "sfu-reuse", edge: "demand_subscription" },- });- expect(routes.operationExpired(demand.deadlineAtMs).failedPeerIds).toEqual([- A,- ]);-- const convergence = routes.reconcile(demand.deadlineAtMs + 1).operation!;- expect(convergence).toMatchObject({- childPeerId: carrierPeerId,- reason: "direct-convergence",- candidates: [- {- tuple: { kind: "peer", parentPeerId: HOST, transport: "direct" },- },- ],- });- const direct = beginCandidate(routes, {- nowMs: demand.deadlineAtMs + 2,- connectionId: "carrier_direct",- reservation: { kind: "direct", overlap: "carrier_direct_overlap" },- }).operation!;- const committed = routes.candidateReady(- {- childPeerId: direct.childPeerId,- childSessionId: direct.childSessionId,- revision: direct.current!.revision,- connectionId: "carrier_direct",- },- demand.deadlineAtMs + 3,- );- expect(committed.accepted).toBe(true);- expect(committed.released).toEqual(- expect.arrayContaining(["carrier_subscription", "publication_resource"]),- );- expect(routes.snapshot().hostPublication).toBeNull();- return { routes, nowMs: demand.deadlineAtMs + 4 };-}--function invalidateActiveSfuEdge(): RoomRouteController<string> {- const routes = controller(1, { sfuEnabled: true });- addViewer(routes, A, 0);- routes.hydrateHostPublication("active_publication", "publication_resource");- routes.hydrateEdge(A, {- kind: "sfu",- publicationGeneration: "active_publication",- transport: "sfu",- connectionId: "active_sfu_edge",- usable: true,- physicalActive: true,- resource: "active_subscription",- });- expect(- routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- routeRevision: routes.snapshot().revision,- connectionId: "active_sfu_edge",- }),- ).toBe(true);- return routes;-}--function observeSenderState(- routes: RoomRouteController<string>,- input: {- childPeerId: string;- connectionId: string;- state: "healthy" | "degraded";- acceptedAtMs: number;- parentPeerId?: string;- senderIdentity?: string;- },-) {- const parentPeerId = input.parentPeerId ?? HOST;- return routes.observeSenderQualityEvidence({- parentPeerId,- parentSessionId:- parentPeerId === HOST ? "host_session" : `${parentPeerId}_session`,- childPeerId: input.childPeerId,- routeRevision: routes.snapshot().revision,- connectionId: input.connectionId,- senderIdentity:- input.senderIdentity ?? `${input.connectionId}-rtp\u0000track`,- sampleTimestampMs: input.acceptedAtMs,- state: input.state,- acceptedAtMs: input.acceptedAtMs,- });-}--function observePersistentDegraded(- routes: RoomRouteController<string>,- childPeerId: string,- connectionId: string,- acceptedAtMs: number,- parentPeerId = HOST,-): void {- expect(- observeSenderState(routes, {- childPeerId,- connectionId,- parentPeerId,- state: "healthy",- acceptedAtMs,- }).accepted,- ).toBe(true);- for (let offset = 1; offset <= 3; offset += 1) {- expect(- observeSenderState(routes, {- childPeerId,- connectionId,- parentPeerId,- state: "degraded",- acceptedAtMs: acceptedAtMs + offset,- }).accepted,- ).toBe(true);- }-}--function observePersistentSfuHealthy(- routes: RoomRouteController<string>,- publicationGeneration: string,- routeRevision: number,- acceptedAtMs: number,-) {- let result;- for (let offset = 0; offset < 3; offset += 1) {- result = routes.observeSfuPublisherQualityEvidence({- hostPeerId: HOST,- hostSessionId: "host_session",- publicationGeneration,- routeRevision,- state: "healthy",- sampleTimestampMs: acceptedAtMs + offset,- acceptedAtMs: acceptedAtMs + offset,- });- expect(result.accepted).toBe(true);- }- return result!;-}--type RouteQualityMetrics = Pick<- ViewerQualityEvidenceMetrics,- | "framesDecodedDelta"- | "freezeCountDelta"- | "freezeDurationMsDelta"- | "pauseCountDelta"- | "pauseDurationMsDelta"->;--function qualityMetrics(- overrides: Partial<RouteQualityMetrics> = {},-): RouteQualityMetrics {- return {- framesDecodedDelta: 120,- freezeCountDelta: 1,- freezeDurationMsDelta: 250,- pauseCountDelta: 0,- pauseDurationMsDelta: 0,- ...overrides,- };-}--describe("RoomRouteController", () => {- it("keeps one diagnostic label until a departed relay is finally pruned", () => {- const routes = controller(2);- addViewer(routes, A, 1);- addViewer(routes, B, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(A, "b_from_a"));- const label = routes.diagnosticParticipantLabel(A);- expect(label).toMatch(/^viewer-\d+$/);-- routes.upsertParticipant({- peerId: A,- role: "viewer",- sessionId: "a_replacement_session",- effectiveDownstreamCapacity: 1,- });- expect(routes.diagnosticParticipantLabel(A)).toBe(label);- expect(routes.disconnectSession(A, "a_replacement_session")).toBe(true);- expect(routes.diagnosticParticipantLabel(A)).toBe(label);- expect(routes.confirmDeparture(A, 0)).toBe(true);- expect(routes.diagnosticParticipantLabel(A)).toBe(label);-- const repair = routes.reconcile(1).operation!;- expect(repair).toMatchObject({- childPeerId: B,- reason: "parent-departed",- });- commitCurrent(routes, 2, "b_from_host");- const pruned = routes.reconcile(4);- expect(pruned.removedPeerIds).toContain(A);- expect(routes.diagnosticParticipantLabel(A)).toBe("viewer-unknown");-- addViewer(routes, C, 0);- expect(routes.diagnosticParticipantLabel(C)).not.toBe(label);- });-- it("clears an unknown sender run without rearming its healthy baseline", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- for (const childPeerId of [A, B]) {- expect(- observeSenderState(routes, {- childPeerId,- connectionId: `${childPeerId === A ? "a" : "b"}_from_host`,- state: "healthy",- acceptedAtMs: 0,- }).accepted,- ).toBe(true);- }- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs: 1,- }).accepted,- ).toBe(true);- expect(- routes.observeSenderQualityEvidence({- parentPeerId: HOST,- parentSessionId: "host_session",- childPeerId: A,- routeRevision: routes.snapshot().revision,- connectionId: "a_from_host",- senderIdentity: null,- sampleTimestampMs: null,- state: "unknown",- acceptedAtMs: 2,- }).accepted,- ).toBe(true);-- for (const acceptedAtMs of [3, 4, 5]) {- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs,- }).accepted,- ).toBe(true);- }- expect(routes.reconcile(6).operation).toMatchObject({- childPeerId: A,- reason: "quality-convergence",- });- });-- it("lets a newly committed availability edge report persistent degradation before healthy", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, B, 2);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- addViewer(routes, A, 2, 0);- const joined = routes.reconcile(0).operation!;- expect(joined.childPeerId).toBe(A);- commitCurrent(routes, 1, "a_from_host");-- for (const acceptedAtMs of [2, 3, 4]) {- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs,- }).accepted,- ).toBe(true);- }-- expect(routes.reconcile(5).operation).toMatchObject({- childPeerId: A,- reason: "quality-convergence",- });- });-- it("starts a fresh degradation run when an availability sender identity changes", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, B, 2);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- addViewer(routes, A, 2, 0);- routes.reconcile(0);- commitCurrent(routes, 1, "a_from_host");-- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- senderIdentity: "old-rtp\u0000track",- state: "degraded",- acceptedAtMs: 2,- }).accepted,- ).toBe(true);- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- senderIdentity: "old-rtp\u0000track",- state: "degraded",- acceptedAtMs: 3,- }).accepted,- ).toBe(true);- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- senderIdentity: "new-rtp\u0000track",- state: "degraded",- acceptedAtMs: 4,- }).accepted,- ).toBe(true);- expect(routes.reconcile(4).operation).toBeUndefined();- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- senderIdentity: "new-rtp\u0000track",- state: "degraded",- acceptedAtMs: 5,- }).accepted,- ).toBe(true);- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- senderIdentity: "new-rtp\u0000track",- state: "degraded",- acceptedAtMs: 6,- }).accepted,- ).toBe(true);- expect(routes.reconcile(7).operation).toMatchObject({- childPeerId: A,- reason: "quality-convergence",- });- });-- it("lets a reset sender begin a new degradation run without a healthy sample", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, B, 2);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- addViewer(routes, A, 2, 0);- routes.reconcile(0);- commitCurrent(routes, 1, "a_from_host");- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "healthy",- acceptedAtMs: 2,- }).accepted,- ).toBe(true);-- routes.resetSenderQuality(HOST, "host_session", 3);- for (const acceptedAtMs of [4, 5, 6]) {- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs,- }).accepted,- ).toBe(true);- }- expect(routes.reconcile(7).operation).toMatchObject({- childPeerId: A,- reason: "quality-convergence",- });- });-- it("regenerates a persistently degraded edge on the same parent", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- observePersistentDegraded(routes, A, "a_from_host", 10);-- const operation = routes.reconcile(14).operation!;- expect(operation.candidates).toEqual([- {- tuple: {- kind: "peer",- parentPeerId: HOST,- transport: "direct",- regenerate: true,- },- endpointTransition: { kind: "none", producerPeerId: HOST },- },- ]);-- const begin = beginCandidate(routes, {- nowMs: 15,- connectionId: "a_regenerated",- reservation: { kind: "direct" },- }).operation!;- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- parentPeerId: HOST,- connectionId: "a_from_host",- usable: true,- physicalActive: true,- });- const guard: CandidateGuard = {- childPeerId: A,- childSessionId: `${A}_session`,- revision: begin.current!.revision,- connectionId: "a_regenerated",- };- expect(- routes.candidateReady(guard, 16, undefined, {- relativeQualityApproved: true,- }),- ).toMatchObject({ accepted: true, committed: false });-- expect(- routes.observeSenderQualityEvidence({- parentPeerId: HOST,- parentSessionId: "host_session",- childPeerId: A,- routeRevision: begin.current!.revision,- connectionId: "a_regenerated",- senderIdentity: "a-regenerated-rtp\u0000track",- sampleTimestampMs: 17,- state: "healthy",- acceptedAtMs: 17,- }).committed,- ).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "peer",- parentPeerId: HOST,- connectionId: "a_regenerated",- });- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_regenerated",- senderIdentity: "a-regenerated-rtp\u0000track",- state: "healthy",- acceptedAtMs: 18,- }).accepted,- ).toBe(true);- for (const acceptedAtMs of [19, 20, 21]) {- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_regenerated",- senderIdentity: "a-regenerated-rtp\u0000track",- state: "degraded",- acceptedAtMs,- }).accepted,- ).toBe(true);- }- expect(routes.reconcile(22).operation?.candidates[0]?.tuple).toMatchObject({- kind: "peer",- parentPeerId: HOST,- regenerate: true,- });- });-- it("keeps same-edge regeneration damped while allowing a different parent", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- observePersistentDegraded(routes, A, "a_from_host", 10);-- routes.reconcile(14);- const begin = beginCandidate(routes, {- nowMs: 15,- connectionId: "a_regenerated",- reservation: { kind: "direct" },- }).operation!;- const guard: CandidateGuard = {- childPeerId: A,- childSessionId: `${A}_session`,- revision: begin.current!.revision,- connectionId: "a_regenerated",- };- routes.candidateReady(guard, 16, undefined, {- relativeQualityApproved: true,- });- expect(- routes.observeSenderQualityEvidence({- parentPeerId: HOST,- parentSessionId: "host_session",- childPeerId: A,- routeRevision: begin.current!.revision,- connectionId: "a_regenerated",- senderIdentity: "a-regenerated-rtp\u0000track",- sampleTimestampMs: 17,- state: "healthy",- acceptedAtMs: 17,- }).committed,- ).toBe(true);-- for (const acceptedAtMs of [18, 19, 20]) {- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_regenerated",- state: "degraded",- senderIdentity: "a-regenerated-rtp\u0000track",- acceptedAtMs,- }).accepted,- ).toBe(true);- }- expect(routes.reconcile(21).operation).toBeUndefined();-- addViewer(routes, B, 2);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- expect(- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 22,- }).accepted,- ).toBe(true);- const withAlternate = routes.reconcile(23).operation;- expect(withAlternate).toMatchObject({- childPeerId: A,- reason: "quality-convergence",- });- expect(withAlternate?.candidates.map((candidate) => candidate.tuple)).toEqual([- { kind: "peer", parentPeerId: B, transport: "direct" },- ]);- });-- it("uses the existing one-slot overlap for same-parent regeneration", () => {- const routes = controller(1, { qualityConvergenceEnabled: true });- addViewer(routes, A, 1);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- observePersistentDegraded(routes, A, "a_from_host", 10);-- const operation = routes.reconcile(14).operation!;- expect(operation.candidates[0]?.endpointTransition).toEqual({- kind: "overlap",- producerPeerId: HOST,- });- const begin = beginCandidate(routes, {- nowMs: 15,- connectionId: "a_regenerated",- reservation: { kind: "direct", overlap: "a_overlap" },- }).operation!;- const guard: CandidateGuard = {- childPeerId: A,- childSessionId: `${A}_session`,- revision: begin.current!.revision,- connectionId: "a_regenerated",- };- routes.candidateReady(guard, 16, undefined, {- relativeQualityApproved: true,- });- const committed = routes.observeSenderQualityEvidence({- parentPeerId: HOST,- parentSessionId: "host_session",- childPeerId: A,- routeRevision: begin.current!.revision,- connectionId: "a_regenerated",- senderIdentity: "a-regenerated-rtp\u0000track",- sampleTimestampMs: 17,- state: "healthy",- acceptedAtMs: 17,- });- expect(committed.committed).toBe(true);- expect(committed.released).toContain("a_overlap");- });-- it("keeps one quality experiment through inconclusive current windows", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 9,- });- observePersistentDegraded(routes, A, "a_from_host", 10);-- const operation = routes.reconcile(14).operation!;- expect(operation.candidates.map((candidate) => candidate.tuple)).toEqual([- { kind: "peer", parentPeerId: B, transport: "direct" },- {- kind: "peer",- parentPeerId: HOST,- transport: "direct",- regenerate: true,- },- ]);- beginCandidate(routes, {- nowMs: 15,- connectionId: "a_from_b_failed",- reservation: { kind: "direct" },- });-- const currentRevision = routes.snapshot().revision;- expect(- routes.observeSenderQualityEvidence({- parentPeerId: HOST,- parentSessionId: "host_session",- childPeerId: A,- routeRevision: currentRevision,- connectionId: "a_from_host",- senderIdentity: null,- sampleTimestampMs: null,- state: "unknown",- acceptedAtMs: 16,- }).accepted,- ).toBe(true);- expect(routes.snapshot().operation).toMatchObject({- reason: "quality-convergence",- cursor: 0,- });-- const afterFirst = routes.operationExpired(- routes.snapshot().operation!.wakeAtMs,- );- expect(afterFirst.accepted).toBe(true);- expect(routes.snapshot().operation).toMatchObject({- reason: "quality-convergence",- cursor: 1,- });- const regeneration = beginCandidate(routes, {- nowMs: 20,- connectionId: "a_regeneration_failed",- reservation: { kind: "direct", overlap: "a_regeneration_overlap" },- }).operation!;- expect(- routes.candidateFailed(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: regeneration.current!.revision,- connectionId: "a_regeneration_failed",- },- 21,- ).accepted,- ).toBe(true);- expect(routes.snapshot().operation).toBeUndefined();-- for (const acceptedAtMs of [22, 23, 24]) {- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs,- }).accepted,- ).toBe(true);- }- expect(routes.reconcile(25).operation).toBeUndefined();- routes.touchExternalFacts();- expect(routes.reconcile(26).operation).toBeUndefined();-- addViewer(routes, C, 2);- routes.hydrateEdge(C, peerEdge(B, "c_from_b"));- observeSenderState(routes, {- childPeerId: C,- connectionId: "c_from_b",- parentPeerId: B,- state: "healthy",- acceptedAtMs: 27,- });- const newOpportunity = routes.reconcile(28).operation;- expect(newOpportunity).toMatchObject({- childPeerId: A,- reason: "quality-convergence",- });- expect(newOpportunity?.candidates.map((candidate) => candidate.tuple)).toEqual([- { kind: "peer", parentPeerId: C, transport: "direct" },- ]);- });-- it("does not restart a quality candidate set after its total deadline", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 9,- });- observePersistentDegraded(routes, A, "a_from_host", 10);-- const operation = routes.reconcile(14).operation!;- beginCandidate(routes, {- nowMs: 15,- connectionId: "a_from_b_pending",- reservation: { kind: "direct" },- });- expect(routes.operationExpired(operation.deadlineAtMs).accepted).toBe(true);- expect(routes.snapshot().operation).toBeUndefined();- expect(routes.reconcile(operation.deadlineAtMs + 1).operation).toBeUndefined();- routes.touchExternalFacts();- expect(routes.reconcile(operation.deadlineAtMs + 2).operation).toBeUndefined();-- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "healthy",- acceptedAtMs: operation.deadlineAtMs + 3,- });- for (const acceptedAtMs of [- operation.deadlineAtMs + 4,- operation.deadlineAtMs + 5,- operation.deadlineAtMs + 6,- ]) {- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs,- });- }- expect(- routes.reconcile(operation.deadlineAtMs + 7).operation?.reason,- ).toBe("quality-convergence");- });-- it("keeps isolated limitation windows diagnostic", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 99,- });- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "healthy",- acceptedAtMs: 99,- });- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs: 100,- });- expect(- routes.observeSenderQualityEvidence({- parentPeerId: HOST,- parentSessionId: "host_session",- childPeerId: A,- routeRevision: routes.snapshot().revision,- connectionId: "a_from_host",- senderIdentity: "a_from_host-rtp\u0000track",- sampleTimestampMs: 100,- state: "degraded",- acceptedAtMs: 101,- }).accepted,- ).toBe(true);- expect(routes.reconcile(101).operation).toBeUndefined();- for (const acceptedAtMs of [102]) {- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs,- });- expect(routes.reconcile(acceptedAtMs).operation).toBeUndefined();- }- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs: 103,- });- expect(routes.reconcile(104).operation).toMatchObject({- childPeerId: A,- reason: "quality-convergence",- });- });-- it("never treats one degraded Host edge as SFU fanout pressure", () => {- const routes = controller(2, {- sfuEnabled: true,- qualityConvergenceEnabled: true,- });- addViewer(routes, A, 1);- addViewer(routes, B, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateHostPublication(- "publication_generation_12345678",- "publication_resource",- );- routes.hydrateEdge(B, {- kind: "sfu",- publicationGeneration: "publication_generation_12345678",- transport: "sfu",- connectionId: "b_from_sfu",- usable: true,- physicalActive: true,- resource: "b_subscription",- });- observePersistentDegraded(routes, A, "a_from_host", 99);- observePersistentSfuHealthy(- routes,- "publication_generation_12345678",- routes.snapshot().revision,- 103,- );- const operation = routes.reconcile(104).operation!;- expect(operation.reason).toBe("quality-convergence");- expect(operation.candidates).toHaveLength(1);- expect(operation.candidates[0]?.tuple).toMatchObject({- kind: "peer",- parentPeerId: HOST,- regenerate: true,- });- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "peer",- parentPeerId: HOST,- });- });-- it("commits only after the Viewer approves a P2P receive improvement", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- expect(- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 100,- }).accepted,- ).toBe(true);- observePersistentDegraded(routes, A, "a_from_host", 99);-- const operation = routes.reconcile(103).operation!;- expect(operation.reason).toBe("quality-convergence");- expect(operation.candidates[0]?.tuple).toEqual({- kind: "peer",- parentPeerId: B,- transport: "direct",- });- const begin = beginCandidate(routes, {- nowMs: 104,- connectionId: "a_from_b",- reservation: { kind: "direct" },- });- const current = begin.operation!.current!;- const guard: CandidateGuard = {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_b",- };- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "peer",- parentPeerId: HOST,- connectionId: "a_from_host",- });- expect(- routes.candidateReady(guard, 105, undefined, {- relativeQualityApproved: true,- }),- ).toMatchObject({- accepted: true,- committed: false,- });- expect(- routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: current.revision,- connectionId: "a_from_b",- senderIdentity: "a-from-b-rtp\u0000a-track",- sampleTimestampMs: 106,- state: "healthy",- acceptedAtMs: 106,- }).committed,- ).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "peer",- parentPeerId: B,- connectionId: "a_from_b",- });-- const migratedRevision = routes.snapshot().revision;- const observeMigrated = (state: "healthy" | "degraded", at: number) =>- routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: migratedRevision,- connectionId: "a_from_b",- senderIdentity: "a-from-b-rtp\u0000a-track",- sampleTimestampMs: at,- state,- acceptedAtMs: at,- });- for (const acceptedAtMs of [107, 108, 109]) {- expect(observeMigrated("degraded", acceptedAtMs).accepted).toBe(true);- }- expect(routes.reconcile(110).operation).toBeUndefined();- routes.touchExternalFacts();- expect(routes.reconcile(110).operation).toBeUndefined();- expect(observeMigrated("healthy", 111).accepted).toBe(true);- expect(observeMigrated("degraded", 112).accepted).toBe(true);- expect(observeMigrated("degraded", 113).accepted).toBe(true);- expect(observeMigrated("degraded", 114).accepted).toBe(true);- expect(routes.reconcile(115).operation?.reason).toBe(- "quality-convergence",- );- });-- it("uses one healthy serial operation to distribute a newly committed Host root", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, B, 2);- addViewer(routes, C, 0);- addViewer(routes, D, 0);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- routes.hydrateEdge(C, peerEdge(B, "c_from_b"));- routes.hydrateEdge(D, peerEdge(B, "d_from_b"));- addViewer(routes, A, 2, 10);-- const joined = routes.reconcile(10).operation!;- expect(joined.candidates[0]?.tuple).toEqual({- kind: "peer",- parentPeerId: HOST,- transport: "direct",- });- commitCurrent(routes, 11, "a_from_host");-- const convergence = routes.reconcile(13).operation!;- expect(convergence).toMatchObject({ reason: "root-convergence" });- expect(convergence.candidates).toHaveLength(1);- expect(convergence.candidates[0]?.tuple).toEqual({- kind: "peer",- parentPeerId: A,- transport: "direct",- });- const oldParent = (- routes.snapshot().upstreamByViewer.get(convergence.childPeerId) as {- parentPeerId: string;- }- ).parentPeerId;- expect(oldParent).toBe(B);-- const prepared = beginCandidate(routes, {- nowMs: 14,- connectionId: "root_convergence_candidate",- reservation: { kind: "direct" },- }).operation!;- const guard = {- childPeerId: convergence.childPeerId,- childSessionId: convergence.childSessionId,- revision: prepared.current!.revision,- connectionId: "root_convergence_candidate",- };- expect(routes.candidateReady(guard, 15)).toMatchObject({- accepted: true,- committed: false,- });- expect(- routes.observeSenderQualityEvidence({- parentPeerId: A,- parentSessionId: `${A}_session`,- childPeerId: convergence.childPeerId,- routeRevision: prepared.current!.revision,- connectionId: "root_convergence_candidate",- senderIdentity: "root-rtp\u0000track",- sampleTimestampMs: 16,- state: "healthy",- acceptedAtMs: 16,- }).committed,- ).toBe(true);- expect(- routes.snapshot().upstreamByViewer.get(convergence.childPeerId),- ).toMatchObject({ parentPeerId: A });- const migratedChildPeerId = convergence.childPeerId;- for (const acceptedAtMs of [17, 18, 19]) {- expect(- observeSenderState(routes, {- childPeerId: migratedChildPeerId,- connectionId: "root_convergence_candidate",- parentPeerId: A,- state: "degraded",- acceptedAtMs,- }).accepted,- ).toBe(true);- }- expect(routes.reconcile(20).operation).toBeUndefined();- expect(- observeSenderState(routes, {- childPeerId: migratedChildPeerId,- connectionId: "root_convergence_candidate",- parentPeerId: A,- state: "healthy",- acceptedAtMs: 21,- }).accepted,- ).toBe(true);- for (const acceptedAtMs of [22, 23, 24]) {- expect(- observeSenderState(routes, {- childPeerId: migratedChildPeerId,- connectionId: "root_convergence_candidate",- parentPeerId: A,- state: "degraded",- acceptedAtMs,- }).accepted,- ).toBe(true);- }- expect(routes.reconcile(25).operation?.reason).toBe("quality-convergence");- });-- it("advances a silent Peer only when another bounded candidate remains", () => {- const routes = controller(2, { operationTimeoutMs: 20_000 });- addViewer(routes, B, 2);- addViewer(routes, C, 2);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"));- addViewer(routes, A, 0, 0);-- const operation = routes.reconcile(0).operation!;- beginCandidate(routes, {- nowMs: 100,- connectionId: "first_silent_candidate",- reservation: { kind: "direct" },- });- expect(routes.snapshot().operation?.wakeAtMs).toBe(5_100);- expect(routes.operationExpired(5_100).accepted).toBe(true);-- beginCandidate(routes, {- nowMs: 5_200,- connectionId: "second_silent_candidate",- reservation: { kind: "direct" },- });- expect(routes.snapshot().operation?.wakeAtMs).toBe(- operation.deadlineAtMs,- );- expect(routes.snapshot().operation?.deadlineAtMs).toBe(- operation.deadlineAtMs,- );- expect(routes.operationExpired(10_200).accepted).toBe(false);- expect(routes.snapshot().operation?.current?.connectionId).toBe(- "second_silent_candidate",- );- });-- it("retains a peer-only direct attempt through the total operation deadline", () => {- const routes = controller(1, { operationTimeoutMs: 20_000 });- addViewer(routes, A, 0, 0);-- const operation = routes.reconcile(0).operation!;- beginCandidate(routes, {- nowMs: 100,- connectionId: "only_direct_candidate",- reservation: { kind: "direct" },- });-- expect(routes.snapshot().operation?.wakeAtMs).toBe(- operation.deadlineAtMs,- );- expect(routes.operationExpired(5_100).accepted).toBe(false);- expect(routes.snapshot().operation?.current?.connectionId).toBe(- "only_direct_candidate",- );- expect(routes.operationExpired(operation.deadlineAtMs)).toMatchObject({- accepted: true,- failedPeerIds: [A],- });- });-- it("keeps only fresh exact-edge quality shadow aggregates", () => {- const routes = controller(2);- addViewer(routes, A, 1, 0);- routes.reconcile(10);- commitCurrent(routes, 20, "a_quality_connection");- const active = routes.snapshot();-- expect(- routes.observeQualityEvidence({- childPeerId: A,- childSessionId: `${A}_session`,- routeRevision: active.revision,- connectionId: "a_quality_connection",- upstream: { kind: "peer", peerId: HOST },- presentationEpoch: 1,- windowMs: 2_000,- metrics: qualityMetrics(),- acceptedAtMs: 1_000,- }),- ).toBe("observed");- expect(routes.snapshot()).toMatchObject({- revision: active.revision,- factVersion: active.factVersion,- });- addViewer(routes, B, 0, 1_100);- routes.reconcile(1_200);- commitCurrent(routes, 1_210, "b_quality_connection");- expect(routes.routeDiagnosticSnapshot(1_300).children[0]?.quality).toEqual({- eligibleWindows: 1,- eligibleDurationMs: 2_000,- freezeWindows: 1,- freezeCount: 1,- freezeDurationMs: 250,- pauseCount: 0,- pauseDurationMs: 0,- });- expect(routes.routeDiagnosticSnapshot(5_999).children[0]?.quality).not.toBeNull();- expect(routes.routeDiagnosticSnapshot(6_000).children[0]?.quality).toBeNull();-- const nextRevision = routes.snapshot().revision;- expect(- routes.observeQualityEvidence({- childPeerId: A,- childSessionId: `${A}_session`,- routeRevision: nextRevision,- connectionId: "a_quality_connection",- upstream: { kind: "peer", peerId: HOST },- presentationEpoch: 2,- windowMs: 2_000,- metrics: qualityMetrics({ framesDecodedDelta: null }),- acceptedAtMs: 7_000,- }),- ).toBe("accepted");- expect(routes.routeDiagnosticSnapshot(7_100).children[0]?.quality).toBeNull();- expect(- routes.observeQualityEvidence({- childPeerId: A,- childSessionId: `${A}_session`,- routeRevision: nextRevision,- connectionId: "a_quality_connection",- upstream: { kind: "peer", peerId: HOST },- presentationEpoch: 2,- windowMs: 2_000,- metrics: qualityMetrics(),- acceptedAtMs: 7_100,- }),- ).toBe("observed");- expect(- routes.observeQualityEvidence({- childPeerId: A,- childSessionId: `${A}_session`,- routeRevision: nextRevision,- connectionId: "a_quality_connection",- upstream: { kind: "peer", peerId: HOST },- presentationEpoch: 1,- windowMs: 2_000,- metrics: qualityMetrics(),- acceptedAtMs: 7_200,- }),- ).toBe("rejected");-- routes.setPaused(true, 7_300);- expect(routes.routeDiagnosticSnapshot(7_301).children[0]?.quality).toBeNull();- });-- it("waits for a fresh healthy candidate sender after relative proof", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- expect(- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 100,- }).accepted,- ).toBe(true);- observePersistentDegraded(routes, A, "a_from_host", 99);- routes.reconcile(103);- const begin = beginCandidate(routes, {- nowMs: 104,- connectionId: "a_from_b",- reservation: { kind: "direct" },- });- const current = begin.operation!.current!;- expect(- routes.candidateTransportConnected(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_b",- },- 105,- ).accepted,- ).toBe(true);- expect(- routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: current.revision,- connectionId: "a_from_b",- senderIdentity: "a-from-b-rtp\u0000track",- sampleTimestampMs: 105,- state: "degraded",- acceptedAtMs: 105,- }).accepted,- ).toBe(true);- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_b",- },- 106,- undefined,- { relativeQualityApproved: true },- ).committed,- ).not.toBe(true);- expect(- routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: current.revision,- connectionId: "a_from_b",- senderIdentity: "a-from-b-rtp\u0000track",- sampleTimestampMs: 107,- state: "healthy",- acceptedAtMs: 107,- }).committed,- ).toBe(true);- });-- it("does not commit a relative proof after its freshness window expires", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observePersistentDegraded(routes, A, "a_from_host", 99);- routes.reconcile(103);- const begin = beginCandidate(routes, {- nowMs: 104,- connectionId: "a_from_b_stale_proof",- reservation: { kind: "direct" },- });- const current = begin.operation!.current!;- const guard: CandidateGuard = {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_b_stale_proof",- };- expect(routes.candidateTransportConnected(guard, 105).accepted).toBe(true);-- expect(- routes.candidateReady(guard, 105, undefined, {- relativeQualityApproved: true,- }).committed,- ).not.toBe(true);- expect(- routes.candidateReady(guard, 109, undefined, {- relativeQualityApproved: true,- }).committed,- ).not.toBe(true);- for (const acceptedAtMs of [5_105, 5_106, 5_107]) {- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs,- }).accepted,- ).toBe(true);- }- const settled = routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: current.revision,- connectionId: guard.connectionId,- senderIdentity: "stale-proof-rtp\u0000track",- sampleTimestampMs: 5_111,- state: "healthy",- acceptedAtMs: 5_111,- });- expect(settled).toMatchObject({ accepted: true, committed: false });- expect(routes.snapshot().operation).toMatchObject({- reason: "quality-convergence",- cursor: 1,- });- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- parentPeerId: HOST,- connectionId: "a_from_host",- });- });-- it("abandons a pending quality move when the incumbent recovers", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observePersistentDegraded(routes, A, "a_from_host", 99);- routes.reconcile(103);- const begin = beginCandidate(routes, {- nowMs: 104,- connectionId: "a_from_b_incumbent_recovery",- reservation: { kind: "direct" },- });- const current = begin.operation!.current!;- const guard: CandidateGuard = {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_b_incumbent_recovery",- };- expect(- routes.candidateReady(guard, 105, undefined, {- relativeQualityApproved: true,- }).committed,- ).not.toBe(true);-- expect(- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "healthy",- acceptedAtMs: 106,- }).accepted,- ).toBe(true);- expect(routes.snapshot().operation).toBeUndefined();- expect(- routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: current.revision,- connectionId: guard.connectionId,- senderIdentity: "late-healthy-rtp\u0000track",- sampleTimestampMs: 107,- state: "healthy",- acceptedAtMs: 107,- }).accepted,- ).toBe(false);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- parentPeerId: HOST,- connectionId: "a_from_host",- });- });-- it("persists relative proof while candidate sender evidence is unknown", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 99,- });- observePersistentDegraded(routes, A, "a_from_host", 99);- routes.reconcile(103);- const begin = beginCandidate(routes, {- nowMs: 104,- connectionId: "a_from_b",- reservation: { kind: "direct" },- });- const current = begin.operation!.current!;- expect(- routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: current.revision,- connectionId: "a_from_b",- senderIdentity: null,- sampleTimestampMs: null,- state: "unknown",- acceptedAtMs: 105,- }).accepted,- ).toBe(true);- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_b",- },- 106,- undefined,- { relativeQualityApproved: true },- ).committed,- ).not.toBe(true);- expect(- routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: current.revision,- connectionId: "a_from_b",- senderIdentity: "a-from-b-rtp\u0000track",- sampleTimestampMs: 107,- state: "healthy",- acceptedAtMs: 107,- }).committed,- ).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "peer",- parentPeerId: B,- connectionId: "a_from_b",- });- });-- it("advances past a persistently limited quality candidate", () => {- const routes = controller(3, { qualityConvergenceEnabled: true });- for (const [peerId, connectionId] of [- [A, "a_from_host"],- [B, "b_from_host"],- [C, "c_from_host"],- ] as const) {- addViewer(routes, peerId, 3);- routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));- }- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 99,- });- observeSenderState(routes, {- childPeerId: C,- connectionId: "c_from_host",- state: "healthy",- acceptedAtMs: 99,- });- observePersistentDegraded(routes, A, "a_from_host", 99);-- const operation = routes.reconcile(103).operation!;- const deadlineAtMs = operation.deadlineAtMs;- const firstParent = (- operation.candidates[0]!.tuple as Extract<- (typeof operation.candidates)[number]["tuple"],- { kind: "peer" }- >- ).parentPeerId;- const first = beginCandidate(routes, {- nowMs: 104,- connectionId: "first_quality_candidate",- reservation: { kind: "direct" },- }).operation!;- let lastResult;- for (const acceptedAtMs of [105, 106, 107]) {- lastResult = routes.observeSenderQualityEvidence({- parentPeerId: firstParent,- parentSessionId: `${firstParent}_session`,- childPeerId: A,- routeRevision: first.current!.revision,- connectionId: "first_quality_candidate",- senderIdentity: "first-quality-rtp\u0000track",- sampleTimestampMs: acceptedAtMs,- state: "degraded",- acceptedAtMs,- });- expect(lastResult.accepted).toBe(true);- }- expect(lastResult?.committed).toBe(false);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- parentPeerId: HOST,- connectionId: "a_from_host",- });- expect(routes.snapshot().operation).toMatchObject({- cursor: 1,- deadlineAtMs,- current: undefined,- });-- const secondParent = (- routes.snapshot().operation!.candidates[1]!.tuple as Extract<- (typeof operation.candidates)[number]["tuple"],- { kind: "peer" }- >- ).parentPeerId;- expect(secondParent).not.toBe(firstParent);- const second = beginCandidate(routes, {- nowMs: 108,- connectionId: "second_quality_candidate",- reservation: { kind: "direct" },- }).operation!;- expect(- routes.observeSenderQualityEvidence({- parentPeerId: secondParent,- parentSessionId: `${secondParent}_session`,- childPeerId: A,- routeRevision: second.current!.revision,- connectionId: "second_quality_candidate",- senderIdentity: null,- sampleTimestampMs: null,- state: "unknown",- acceptedAtMs: 109,- }).accepted,- ).toBe(true);- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: second.current!.revision,- connectionId: "second_quality_candidate",- },- 110,- undefined,- { relativeQualityApproved: true },- ).committed,- ).not.toBe(true);- expect(- routes.observeSenderQualityEvidence({- parentPeerId: secondParent,- parentSessionId: `${secondParent}_session`,- childPeerId: A,- routeRevision: second.current!.revision,- connectionId: "second_quality_candidate",- senderIdentity: "second-quality-rtp\u0000track",- sampleTimestampMs: 111,- state: "healthy",- acceptedAtMs: 111,- }).committed,- ).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- parentPeerId: secondParent,- connectionId: "second_quality_candidate",- });- });-- it("preempts quality work for a Viewer without media", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 100,- });- observePersistentDegraded(routes, A, "a_from_host", 99);- expect(routes.reconcile(103).operation?.reason).toBe(- "quality-convergence",- );- addViewer(routes, C, 0, 104);- expect(routes.reconcile(105).operation).toMatchObject({- childPeerId: C,- reason: "join",- });- commitCurrent(routes, 106, "c_join_connection");- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 107,- });- observePersistentDegraded(routes, A, "a_from_host", 107);- expect(routes.reconcile(111).operation?.reason).toBe(- "quality-convergence",- );- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- parentPeerId: HOST,- connectionId: "a_from_host",- });- });-- it("keeps a quality operation reason immutable until availability preempts it", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 99,- });- observePersistentDegraded(routes, A, "a_from_host", 99);- expect(routes.reconcile(103).operation?.reason).toBe(- "quality-convergence",- );-- expect(- routes.invalidateEdge(- {- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: routes.snapshot().revision,- connectionId: "a_from_host",- },- 104,- ),- ).toBe(true);- expect(routes.snapshot().operation?.reason).toBe("quality-convergence");- expect(routes.reconcile(105).operation).toMatchObject({- childPeerId: A,- reason: "edge-unavailable",- });- });-- it("keeps a direct convergence reason immutable until availability preempts it", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, B, 2);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- routes.hydrateHostPublication("publication", "publication_resource");- addViewer(routes, A, 0, 0);- const acquisition = routes.reconcile(0).operation!;- beginCandidate(routes, {- nowMs: 1,- connectionId: "a_head_start",- reservation: { kind: "direct" },- });- routes.operationExpired(acquisition.wakeAtMs);- const sfu = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 1,- connectionId: "a_sfu",- reservation: { kind: "sfu-reuse", edge: "a_subscription" },- }).operation!;- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: sfu.current!.revision,- connectionId: "a_sfu",- },- acquisition.wakeAtMs + 2,- ).committed,- ).toBe(true);- expect(routes.reconcile(acquisition.wakeAtMs + 3).operation?.reason).toBe(- "direct-convergence",- );-- expect(- routes.invalidateEdge(- {- childPeerId: A,- childSessionId: `${A}_session`,- routeRevision: routes.snapshot().revision,- connectionId: "a_sfu",- },- acquisition.wakeAtMs + 4,- ),- ).toBe(true);- expect(routes.snapshot().operation?.reason).toBe("direct-convergence");- expect(routes.reconcile(acquisition.wakeAtMs + 5).operation).toMatchObject({- childPeerId: A,- reason: "edge-unavailable",- });- });-- it("keeps a root convergence reason immutable until availability preempts it", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, B, 2);- addViewer(routes, C, 0);- addViewer(routes, D, 0);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- routes.hydrateEdge(C, peerEdge(B, "c_from_b"));- routes.hydrateEdge(D, peerEdge(B, "d_from_b"));- addViewer(routes, A, 2, 10);- routes.reconcile(10);- commitCurrent(routes, 11, "a_from_host");- const convergence = routes.reconcile(13).operation!;- expect(convergence.reason).toBe("root-convergence");- const oldEdge = routes.snapshot().upstreamByViewer.get(- convergence.childPeerId,- );- expect(oldEdge?.kind).toBe("peer");- if (oldEdge?.kind !== "peer") throw new Error("Expected Peer edge");-- expect(- routes.invalidateEdge(- {- childPeerId: convergence.childPeerId,- childSessionId: convergence.childSessionId,- parentSessionId: oldEdge.parentSessionId,- routeRevision: routes.snapshot().revision,- connectionId: oldEdge.connectionId,- },- 14,- ),- ).toBe(true);- expect(routes.snapshot().operation?.reason).toBe("root-convergence");- expect(routes.reconcile(15).operation).toMatchObject({- childPeerId: convergence.childPeerId,- reason: "edge-unavailable",- });- });-- it("keeps a usable parent eligible before native state becomes clear", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observePersistentDegraded(routes, A, "a_from_host", 99);- expect(routes.reconcile(103).operation).toMatchObject({- childPeerId: A,- reason: "quality-convergence",- candidates: [- {- tuple: { kind: "peer", parentPeerId: B, transport: "direct" },- },- {- tuple: {- kind: "peer",- parentPeerId: HOST,- transport: "direct",- regenerate: true,- },- },- ],- });- });-- it("waits for a fresh candidate sender after prior evidence expires", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- const observeCurrent = (- childPeerId: string,- connectionId: string,- state: "healthy" | "degraded",- acceptedAtMs: number,- ) =>- routes.observeSenderQualityEvidence({- parentPeerId: HOST,- parentSessionId: "host_session",- childPeerId,- routeRevision: routes.snapshot().revision,- connectionId,- senderIdentity: `${connectionId}-rtp\u0000track`,- sampleTimestampMs: acceptedAtMs,- state,- acceptedAtMs,- });- expect(observeCurrent(B, "b_from_host", "healthy", 100).accepted).toBe(- true,- );- expect(observeCurrent(A, "a_from_host", "healthy", 99).accepted).toBe(- true,- );- expect(observeCurrent(A, "a_from_host", "degraded", 100).accepted).toBe(- true,- );- expect(observeCurrent(A, "a_from_host", "degraded", 101).accepted).toBe(- true,- );- expect(observeCurrent(A, "a_from_host", "degraded", 102).accepted).toBe(- true,- );- routes.reconcile(103);- const begin = beginCandidate(routes, {- nowMs: 104,- connectionId: "a_from_b_stale",- reservation: { kind: "direct" },- });- const current = begin.operation!.current!;- expect(- routes.candidateTransportConnected(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_b_stale",- },- 105,- ).accepted,- ).toBe(true);- expect(- routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: current.revision,- connectionId: "a_from_b_stale",- senderIdentity: "a-stale-rtp\u0000a-track",- sampleTimestampMs: 104,- state: "healthy",- acceptedAtMs: 104,- }).accepted,- ).toBe(true);- for (const acceptedAtMs of [5_101, 5_102, 5_103]) {- expect(- observeCurrent(A, "a_from_host", "degraded", acceptedAtMs).accepted,- ).toBe(true);- }- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_b_stale",- },- 5_104,- undefined,- { relativeQualityApproved: true },- ).committed,- ).not.toBe(true);- expect(- routes.observeSenderQualityEvidence({- parentPeerId: B,- parentSessionId: `${B}_session`,- childPeerId: A,- routeRevision: current.revision,- connectionId: "a_from_b_stale",- senderIdentity: "a-stale-rtp\u0000a-track",- sampleTimestampMs: 5_105,- state: "healthy",- acceptedAtMs: 5_105,- }).committed,- ).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- parentPeerId: B,- connectionId: "a_from_b_stale",- });- });-- it("keeps a usable candidate when its native source category expires", () => {- const routes = controller(2, { qualityConvergenceEnabled: true });- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 0,- });- observePersistentDegraded(routes, A, "a_from_host", 0);- expect(routes.reconcile(4).operation?.reason).toBe("quality-convergence");- const begin = beginCandidate(routes, {- nowMs: 5_001,- connectionId: "expired_candidate",- reservation: { kind: "direct" },- });- expect(begin.accepted).toBe(true);- expect(begin.operation?.current?.connectionId).toBe("expired_candidate");- });-- it("keeps bounded SFU after direct candidates when every Host root is degraded", () => {- const routes = controller(2, {- sfuEnabled: true,- qualityConvergenceEnabled: true,- });- addViewer(routes, A, 1);- addViewer(routes, B, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observePersistentDegraded(routes, A, "a_from_host", 99);- const firstRegeneration = routes.reconcile(103).operation!;- expect(firstRegeneration.candidates[0]?.tuple).toMatchObject({- kind: "peer",- parentPeerId: HOST,- regenerate: true,- });- const firstAttempt = beginCandidate(routes, {- nowMs: 104,- connectionId: "a_regeneration_failed",- reservation: { kind: "direct", overlap: "a_regeneration_overlap" },- }).operation!;- expect(- routes.candidateFailed(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: firstAttempt.current!.revision,- connectionId: "a_regeneration_failed",- },- 105,- ).accepted,- ).toBe(true);- expect(routes.setEffectiveCapacity(B, `${B}_session`, 1)).toBe(true);- observePersistentDegraded(routes, B, "b_from_host", 104);- const operation = routes.reconcile(108).operation!;- const childPeerId = operation.childPeerId;- expect(childPeerId).toBe(A);- expect(operation.candidates.map((candidate) => candidate.tuple)).toEqual([- { kind: "peer", parentPeerId: B, transport: "direct" },- { kind: "sfu", publication: "create" },- ]);- const direct = beginCandidate(routes, {- nowMs: 109,- connectionId: "quality_peer_candidate",- reservation: { kind: "direct" },- }).operation!;- expect(- routes.candidateFailed(- {- childPeerId,- childSessionId: `${childPeerId}_session`,- revision: direct.current!.revision,- connectionId: "quality_peer_candidate",- },- 110,- ),- ).toMatchObject({ accepted: true, failedPeerIds: [] });-- const begin = beginCandidate(routes, {- nowMs: 111,- connectionId: "quality_sfu_candidate",- reservation: {- kind: "sfu-create",- edge: "sfu-edge",- publication: "sfu-publication",- overlap: "host-overlap",- },- publicationGeneration: "publication_generation_12345678",- publicationConnectionId: "publication_connection_12345678",- hostSessionId: "host_session",- });- const current = begin.operation!.current!;- const guard: CandidateGuard = {- childPeerId,- childSessionId: `${childPeerId}_session`,- revision: current.revision,- connectionId: "quality_sfu_candidate",- };- expect(- routes.candidateReady(guard, 112),- ).toMatchObject({ accepted: true, committed: false });- for (const acceptedAtMs of [113, 114]) {- expect(- routes.observeSfuPublisherQualityEvidence({- hostPeerId: HOST,- hostSessionId: "host_session",- publicationGeneration: "publication_generation_12345678",- routeRevision: current.revision,- state: "healthy",- sampleTimestampMs: acceptedAtMs,- acceptedAtMs,- }),- ).toMatchObject({ accepted: true, committed: false });- expect(routes.candidateReady(guard, acceptedAtMs)).toMatchObject({- accepted: true,- committed: false,- });- }- expect(- routes.observeSfuPublisherQualityEvidence({- hostPeerId: HOST,- hostSessionId: "host_session",- publicationGeneration: "publication_generation_12345678",- routeRevision: current.revision,- state: "healthy",- sampleTimestampMs: 115,- acceptedAtMs: 115,- }).committed,- ).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(childPeerId)).toMatchObject({- kind: "sfu",- connectionId: "quality_sfu_candidate",- });- });-- it("rejects an SFU quality candidate on degraded publisher evidence", () => {- const routes = controller(2, {- sfuEnabled: true,- qualityConvergenceEnabled: true,- });- addViewer(routes, A, 1);- addViewer(routes, B, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observePersistentDegraded(routes, A, "a_from_host", 99);- const firstRegeneration = routes.reconcile(103).operation!;- expect(firstRegeneration.candidates[0]?.tuple).toMatchObject({- kind: "peer",- parentPeerId: HOST,- regenerate: true,- });- const firstAttempt = beginCandidate(routes, {- nowMs: 104,- connectionId: "a_regeneration_failed",- reservation: { kind: "direct", overlap: "a_regeneration_overlap" },- }).operation!;- expect(- routes.candidateFailed(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: firstAttempt.current!.revision,- connectionId: "a_regeneration_failed",- },- 105,- ).accepted,- ).toBe(true);- expect(routes.setEffectiveCapacity(B, `${B}_session`, 1)).toBe(true);- observePersistentDegraded(routes, B, "b_from_host", 104);- const operation = routes.reconcile(108).operation!;- const childPeerId = operation.childPeerId;- expect(childPeerId).toBe(A);- const peerAttempt = beginCandidate(routes, {- nowMs: 109,- connectionId: "quality_peer_candidate",- reservation: { kind: "direct" },- }).operation!;- expect(- routes.candidateFailed(- {- childPeerId,- childSessionId: `${childPeerId}_session`,- revision: peerAttempt.current!.revision,- connectionId: "quality_peer_candidate",- },- 110,- ).accepted,- ).toBe(true);- const sfuAttempt = beginCandidate(routes, {- nowMs: 111,- connectionId: "quality_sfu_degraded",- reservation: {- kind: "sfu-create",- edge: "sfu-edge",- publication: "sfu-publication",- overlap: "host-overlap",- },- publicationGeneration: "publication_generation_degraded",- publicationConnectionId: "publication_connection_degraded",- hostSessionId: "host_session",- }).operation!;- const current = sfuAttempt.current!;- expect(- routes.candidateReady(- {- childPeerId,- childSessionId: `${childPeerId}_session`,- revision: current.revision,- connectionId: current.connectionId,- },- 112,- ),- ).toMatchObject({ accepted: true, committed: false });- expect(- routes.observeSfuPublisherQualityEvidence({- hostPeerId: HOST,- hostSessionId: "host_session",- publicationGeneration: "publication_generation_degraded",- routeRevision: current.revision,- state: "degraded",- sampleTimestampMs: 113,- acceptedAtMs: 113,- }),- ).toMatchObject({ accepted: true, committed: false });- expect(routes.reconcile(114).operation).toBeUndefined();- expect(routes.snapshot().upstreamByViewer.get(childPeerId)).toMatchObject({- kind: "peer",- parentPeerId: HOST,- });- });-- it("abandons Host relief when another Host root recovers during the canary", () => {- const routes = controller(2, {- sfuEnabled: true,- qualityConvergenceEnabled: true,- });- addViewer(routes, A, 1);- addViewer(routes, B, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- observePersistentDegraded(routes, A, "a_from_host", 99);- observePersistentDegraded(routes, B, "b_from_host", 99);- routes.reconcile(103);- const begin = beginCandidate(routes, {- nowMs: 104,- connectionId: "a_from_sfu",- reservation: {- kind: "sfu-create",- edge: "sfu-edge",- publication: "sfu-publication",- overlap: "host-overlap",- },- publicationGeneration: "publication_generation_12345678",- publicationConnectionId: "publication_connection_12345678",- hostSessionId: "host_session",- });- const current = begin.operation!.current!;- expect(- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "healthy",- acceptedAtMs: 105,- }).accepted,- ).toBe(true);- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_sfu",- },- 106,- ).committed,- ).not.toBe(true);- expect(routes.snapshot().operation).toBeUndefined();- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "peer",- parentPeerId: HOST,- connectionId: "a_from_host",- });- });-- it("uses SFU reuse only for multi-edge Host relief with healthy ingress", () => {- const routes = controller(3, {- sfuEnabled: true,- qualityConvergenceEnabled: true,- });- addViewer(routes, A, 0);- addViewer(routes, B, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- routes.hydrateHostPublication(- "publication_generation_12345678",- "publication_resource",- );- const revision = routes.snapshot().revision;- observePersistentDegraded(routes, A, "a_from_host", 99);- observePersistentDegraded(routes, B, "b_from_host", 99);- expect(routes.reconcile(103).operation).toBeUndefined();- observePersistentSfuHealthy(- routes,- "publication_generation_12345678",- revision,- 104,- );- expect(routes.reconcile(105).operation?.candidates[0]?.tuple).toEqual({- kind: "sfu",- publication: "reuse",- });- const begin = beginCandidate(routes, {- nowMs: 106,- connectionId: "a_from_sfu_reuse",- reservation: { kind: "sfu-reuse", edge: "a_subscription" },- });- const current = begin.operation!.current!;- expect(- routes.observeSfuPublisherQualityEvidence({- hostPeerId: HOST,- hostSessionId: "host_session",- publicationGeneration: "publication_generation_12345678",- routeRevision: revision,- state: "unknown",- sampleTimestampMs: null,- acceptedAtMs: 107,- }).accepted,- ).toBe(true);- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.revision,- connectionId: "a_from_sfu_reuse",- },- 108,- ).committed,- ).not.toBe(true);- for (const acceptedAtMs of [2_100, 4_100, 6_100]) {- observeSenderState(routes, {- childPeerId: A,- connectionId: "a_from_host",- state: "degraded",- acceptedAtMs,- });- observeSenderState(routes, {- childPeerId: B,- connectionId: "b_from_host",- state: "degraded",- acceptedAtMs,- });- const settled = routes.observeSfuPublisherQualityEvidence({- hostPeerId: HOST,- hostSessionId: "host_session",- publicationGeneration: "publication_generation_12345678",- routeRevision: revision,- state: "healthy",- sampleTimestampMs: acceptedAtMs,- acceptedAtMs,- });- expect(settled.committed).toBe(acceptedAtMs === 6_100);- }- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "sfu",- connectionId: "a_from_sfu_reuse",- });- });-- it("accepts an SFU-fed Peer parent from decoded progress without freeze stats", () => {- const routes = controller(2, {- sfuEnabled: true,- qualityConvergenceEnabled: true,- });- addViewer(routes, A, 1);- addViewer(routes, B, 2);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateHostPublication(- "publication_generation_12345678",- "publication_resource",- );- routes.hydrateEdge(B, {- kind: "sfu",- publicationGeneration: "publication_generation_12345678",- transport: "sfu",- connectionId: "b_from_sfu",- usable: true,- physicalActive: true,- resource: "b_subscription",- });- const revision = routes.snapshot().revision;- observePersistentSfuHealthy(- routes,- "publication_generation_12345678",- revision,- 100,- );- expect(- routes.observeQualityEvidence({- childPeerId: B,- childSessionId: `${B}_session`,- routeRevision: revision,- connectionId: "b_from_sfu",- upstream: { kind: "sfu" },- presentationEpoch: 1,- windowMs: 2_000,- metrics: qualityMetrics({- freezeCountDelta: null,- freezeDurationMsDelta: null,- pauseCountDelta: null,- pauseDurationMsDelta: null,- }),- acceptedAtMs: 100,- }),- ).toBe("accepted");- observePersistentDegraded(routes, A, "a_from_host", 99);- expect(routes.reconcile(103).operation?.candidates[0]?.tuple).toEqual({- kind: "peer",- parentPeerId: B,- transport: "direct",- });- });-- it("clears quality shadow for a relay subtree when its source changes", () => {- const routes = controller(2);- addViewer(routes, A, 2);- addViewer(routes, B, 2);- addViewer(routes, C, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(A, "b_from_a"));- routes.hydrateEdge(C, peerEdge(B, "c_from_b"));- const revision = routes.snapshot().revision;-- for (const [childPeerId, parentPeerId, connectionId] of [- [B, A, "b_from_a"],- [C, B, "c_from_b"],- ] as const) {- expect(- routes.observeQualityEvidence({- childPeerId,- childSessionId: `${childPeerId}_session`,- routeRevision: revision,- connectionId,- upstream: { kind: "peer", peerId: parentPeerId },- presentationEpoch: 1,- windowMs: 2_000,- metrics: qualityMetrics(),- acceptedAtMs: 1_000,- }),- ).toBe("observed");- }- expect(- routes- .routeDiagnosticSnapshot(1_001)- .children.filter((child) => child.quality !== null),- ).toHaveLength(2);-- expect(- routes.adoptDirectConnection({- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: revision,- connectionId: "a_from_host",- newConnectionId: "a_from_host_recovered",- }),- ).toBe(true);- expect(- routes- .routeDiagnosticSnapshot(1_002)- .children.every((child) => child.quality === null),- ).toBe(true);-- for (const [acceptedAtMs, expected] of [- [1_100, "accepted"],- [3_100, "observed"],- ] as const) {- for (const [childPeerId, parentPeerId, connectionId] of [- [B, A, "b_from_a"],- [C, B, "c_from_b"],- ] as const) {- expect(- routes.observeQualityEvidence({- childPeerId,- childSessionId: `${childPeerId}_session`,- routeRevision: revision,- connectionId,- upstream: { kind: "peer", peerId: parentPeerId },- presentationEpoch: 1,- windowMs: 2_000,- metrics: qualityMetrics(),- acceptedAtMs,- }),- ).toBe(expected);- }- }- expect(- routes- .routeDiagnosticSnapshot(3_101)- .children.filter((child) => child.quality !== null),- ).toHaveLength(2);- });-- it("retains one latest timing sample for a 20-Viewer burst", () => {- const routes = controller(2);- const viewerPeerIds = Array.from(- { length: 20 },- (_, index) => `burst_${String(index).padStart(2, "0")}_12345678`,- );- for (const peerId of viewerPeerIds) addViewer(routes, peerId, 2, 0);-- for (const [index, peerId] of viewerPeerIds.entries()) {- const operationStartedAtMs = (index + 1) * 10;- expect(routes.reconcile(operationStartedAtMs).operation?.childPeerId).toBe(- peerId,- );- commitCurrent(- routes,- operationStartedAtMs + 1,- `${peerId}_connection`,- );- }-- const snapshot = routes.routeDiagnosticSnapshot(250);- expect(snapshot.children).toHaveLength(20);- expect(snapshot.children.map((child) => child.queueWaitMs)).toEqual(- Array.from({ length: 20 }, (_, index) => (index + 1) * 10),- );- expect(snapshot.children.every((child) => child.finalRoute === "direct"))- .toBe(true);- });-- it("projects latest route timing through snapshot-local ordinals", () => {- const routes = controller(2);- addViewer(routes, A, 1, 100);-- expect(routes.routeDiagnosticSnapshot(150)).toEqual({- children: [- {- ordinal: 1,- parent: { kind: "none" },- effectiveCapacity: 1,- childCount: 0,- demandAgeMs: 50,- queueWaitMs: null,- candidateStartMs: null,- firstDecodedFrameMs: null,- finalMs: null,- finalRoute: "waiting",- rejectionBucket: "none",- quality: null,- },- ],- operation: null,- });-- const operation = routes.reconcile(160).operation!;- expect(routes.routeDiagnosticSnapshot(165).operation).toEqual({- childOrdinal: 1,- reason: "join",- stage: "admission",- cursor: 0,- candidateCount: operation.candidates.length,- });- const prepared = beginCandidate(routes, {- nowMs: 170,- connectionId: "a_connection",- reservation: { kind: "direct" },- }).operation!;- expect(routes.routeDiagnosticSnapshot(180)).toMatchObject({- children: [- {- queueWaitMs: 60,- candidateStartMs: 70,- firstDecodedFrameMs: null,- finalMs: null,- },- ],- operation: { childOrdinal: 1, stage: "first-frame" },- });- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: prepared.current!.revision,- connectionId: "a_connection",- },- 230,- ).accepted,- ).toBe(true);- const settled = routes.routeDiagnosticSnapshot(240);- expect(settled).toMatchObject({- children: [- {- parent: { kind: "host" },- queueWaitMs: 60,- candidateStartMs: 70,- firstDecodedFrameMs: 130,- finalMs: 130,- finalRoute: "direct",- rejectionBucket: "none",- },- ],- operation: null,- });- expect(JSON.stringify(settled)).not.toContain(A);- expect(JSON.stringify(settled)).not.toContain("a_connection");-- expect(- routes.invalidateEdge(- {- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: routes.snapshot().revision,- connectionId: "a_connection",- },- 300,- ),- ).toBe(true);- expect(routes.routeDiagnosticSnapshot(320).children[0]).toMatchObject({- demandAgeMs: 20,- queueWaitMs: null,- candidateStartMs: null,- firstDecodedFrameMs: null,- finalMs: null,- finalRoute: "waiting",- rejectionBucket: "none",- });-- expect(routes.confirmDeparture(A, 330)).toBe(true);- expect(routes.routeDiagnosticSnapshot(330)).toEqual({- children: [],- operation: null,- });- });-- it("records a bounded candidate failure without retaining route identity", () => {- const routes = controller(1);- addViewer(routes, A, 0, 0);- routes.reconcile(10);- const prepared = beginCandidate(routes, {- nowMs: 20,- connectionId: "failed_candidate",- reservation: { kind: "direct" },- }).operation!;- expect(- routes.candidateFailed(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: prepared.current!.revision,- connectionId: "failed_candidate",- },- 30,- ),- ).toMatchObject({ accepted: true, failedPeerIds: [A] });- expect(routes.routeDiagnosticSnapshot(30).children[0]).toMatchObject({- finalMs: 30,- finalRoute: "failed",- rejectionBucket: "candidate-failed",- });-- routes.dispose();- expect(routes.routeDiagnosticSnapshot(40)).toEqual({- children: [],- operation: null,- });- });-- it("reports a current child that has no usable candidate", () => {- const routes = controller(1);- addViewer(routes, A, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_connection"));- addViewer(routes, B, 0, 0);-- const result = routes.reconcile(10);- expect(result.operation).toBeUndefined();- expect(result.failedPeerIds).toEqual([B]);- expect(routes.routeDiagnosticSnapshot(10).children[1]).toMatchObject({- finalMs: 10,- finalRoute: "failed",- rejectionBucket: "candidate-failed",- });- });-- it("records SFU admission waiting without advancing the route cursor", () => {- const routes = controller(1, { sfuEnabled: true });- addViewer(routes, A, 0, 0);- const direct = routes.reconcile(10).operation!;- expect(direct.candidates.map((candidate) => candidate.tuple.kind)).toEqual([- "peer",- "sfu",- ]);- expect(- routes.skipCurrentCandidate(- cursorGuard(direct),- 20,- "candidate-failed",- ).accepted,- ).toBe(true);- const sfu = routes.snapshot().operation!;- expect(- routes.noteCurrentCandidateRejection(- cursorGuard(sfu),- "sfu-admission",- ),- ).toBe(true);- expect(routes.routeDiagnosticSnapshot(30)).toMatchObject({- children: [- {- finalRoute: "waiting",- rejectionBucket: "sfu-admission",- },- ],- operation: {- childOrdinal: 1,- stage: "admission",- cursor: 1,- candidateCount: 2,- },- });- });-- it("distinguishes first-frame timeout from the total operation deadline", () => {- const routes = controller(1, { sfuEnabled: true });- addViewer(routes, A, 0, 0);- const direct = routes.reconcile(10).operation!;- beginCandidate(routes, {- nowMs: 20,- connectionId: "silent_direct",- reservation: { kind: "direct" },- });-- expect(routes.operationExpired(direct.wakeAtMs)).toMatchObject({- accepted: true,- });- expect(routes.routeDiagnosticSnapshot(direct.wakeAtMs)).toMatchObject({- children: [- {- candidateStartMs: null,- finalMs: null,- finalRoute: "waiting",- rejectionBucket: "first-frame-timeout",- },- ],- operation: { cursor: 1, stage: "admission" },- });-- const deadline = routes.snapshot().operation!.deadlineAtMs;- expect(routes.operationExpired(deadline)).toMatchObject({- accepted: true,- failedPeerIds: [A],- });- expect(routes.routeDiagnosticSnapshot(deadline).children[0]).toMatchObject({- finalMs: deadline,- finalRoute: "failed",- rejectionBucket: "operation-deadline",- });- });-- it.each([1, 2, 3] as const)(- "admits 20 Viewers through one bounded event-driven graph at C=%i",- (capacity) => {- const routes = controller(capacity);- const viewerPeerIds = Array.from(- { length: 20 },- (_, index) => `viewer_${String(index).padStart(2, "0")}_12345678`,- );- viewerPeerIds.forEach((peerId, index) => {- addViewer(routes, peerId, capacity);- const operation = routes.reconcile(index * 2).operation!;- expect(operation.childPeerId).toBe(peerId);- commitCurrent(routes, index * 2 + 1, `${peerId}_connection`);- });- const snapshot = routes.snapshot();- expect(snapshot.upstreamByViewer).toHaveLength(20);- for (const parentPeerId of [HOST, ...viewerPeerIds]) {- const childCount = [...snapshot.upstreamByViewer.values()].filter(- (edge) =>- edge.kind === "peer" &&- edge.physicalActive &&- edge.parentPeerId === parentPeerId,- ).length;- expect(childCount).toBeLessThanOrEqual(capacity);- }- },- );-- it("admits waiting Viewers through existing SFU before direct convergence", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, B, 2);- routes.hydrateHostPublication(- "publication_generation",- "publication_resource",- );- routes.hydrateEdge(B, {- kind: "sfu",- publicationGeneration: "publication_generation",- transport: "sfu",- connectionId: "b_sfu",- usable: true,- physicalActive: true,- resource: "b_subscription",- });- addViewer(routes, C, 0);- routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"));- const waiting = Array.from(- { length: 18 },- (_, index) => `silent_${String(index).padStart(2, "0")}_12345678`,- );- waiting.forEach((peerId) => addViewer(routes, peerId, 0));-- let nowMs = 0;- waiting.forEach((peerId, index) => {- const directOperation = routes.reconcile(nowMs).operation!;- expect(directOperation.childPeerId).toBe(peerId);- expect(directOperation.candidates[0]?.tuple.kind).toBe("peer");- beginCandidate(routes, {- nowMs: nowMs + 1,- connectionId: `${peerId}_direct`,- reservation: { kind: "direct" },- });- routes.operationExpired(directOperation.wakeAtMs);- const sfuOperation = routes.snapshot().operation!;- expect(sfuOperation.candidates[sfuOperation.cursor]!.tuple).toEqual({- kind: "sfu",- publication: "reuse",- });- const prepared = beginCandidate(routes, {- nowMs: directOperation.wakeAtMs + 1,- connectionId: `${peerId}_sfu`,- reservation: {- kind: "sfu-reuse",- edge: `${peerId}_subscription`,- },- }).operation!;- expect(- routes.candidateReady(- {- childPeerId: peerId,- childSessionId: `${peerId}_session`,- revision: prepared.current!.revision,- connectionId: `${peerId}_sfu`,- },- directOperation.wakeAtMs + 2,- ).accepted,- ).toBe(true);- nowMs = directOperation.wakeAtMs + 3;-- expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({- kind: "sfu",- connectionId: "b_sfu",- });- expect(routes.snapshot().upstreamByViewer.get(C)).toMatchObject({- kind: "peer",- parentPeerId: HOST,- connectionId: "c_from_host",- });- expect(routes.snapshot().upstreamByViewer.get(peerId)).toMatchObject({- kind: "sfu",- usable: true,- });- expect(routes.snapshot().upstreamByViewer.size).toBe(index + 3);- });-- expect(routes.snapshot().upstreamByViewer.size).toBe(20);- expect(routes.snapshot().hostPublication).toMatchObject({- generation: "publication_generation",- usable: true,- });- expect(routes.reconcile(nowMs).operation).toMatchObject({- reason: "direct-convergence",- });- });-- it.each([1, 2, 3] as const)(- "builds a deterministic acyclic route without a depth cap at C=%i",- (capacity) => {- const routes = controller(capacity);- for (const peerId of [A, B, C, D]) {- addViewer(routes, peerId, capacity);- const result = routes.reconcile(0);- expect(result.operation?.childPeerId).toBe(peerId);- commitCurrent(routes, 1, `${peerId}_connection`);- }-- const snapshot = routes.snapshot();- expect(snapshot.upstreamByViewer).toHaveLength(4);- for (const [childPeerId, edge] of snapshot.upstreamByViewer) {- expect(edge.kind).toBe("peer");- expect(edge.kind === "peer" && edge.parentPeerId).not.toBe(childPeerId);- }- if (capacity === 1) {- expect(snapshot.upstreamByViewer.get(D)).toMatchObject({- kind: "peer",- parentPeerId: C,- });- }- },- );-- it("keeps the old edge until exact candidate first-frame ready", () => {- const routes = controller(2);- addViewer(routes, A, 2);- addViewer(routes, B, 2);- routes.reconcile(0);- commitCurrent(routes, 1, "old_connection");- routes.reconcile(2);- commitCurrent(routes, 3, "b_connection");- const revision = routes.snapshot().revision;- expect(- routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: revision,- connectionId: "old_connection",- }),- ).toBe(true);-- routes.reconcile(100);- const prepared = beginCandidate(routes, {- nowMs: 101,- connectionId: "new_connection",- reservation: { kind: "direct" },- }).operation!;- expect(routes.snapshot().upstreamByViewer.get(A)?.connectionId).toBe(- "old_connection",- );- expect(- routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: prepared.current!.revision - 1,- connectionId: "new_connection",- }, 102).accepted,- ).toBe(false);- expect(- routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: prepared.current!.revision,- connectionId: "new_connection",- }, 102),- ).toMatchObject({ accepted: true });- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- connectionId: "new_connection",- parentPeerId: B,- usable: true,- });- });-- it("invalidates one exact active Peer edge from its parent idempotently", () => {- const routes = controller(2);- addViewer(routes, A, 0);- addViewer(routes, B, 1);- routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- const report = {- parentPeerId: HOST,- parentSessionId: "host_session",- routeRevision: routes.snapshot().revision,- connectionId: "a_from_host",- };-- expect(routes.invalidateDirectEdgeFromParent(report, 10)).toBe(true);- const afterFirst = routes.snapshot();- expect(afterFirst.upstreamByViewer.get(A)).toMatchObject({- usable: false,- connectionId: "a_from_host",- });- expect(afterFirst.upstreamByViewer.get(B)).toMatchObject({- usable: true,- connectionId: "b_from_host",- });- expect(routes.invalidateDirectEdgeFromParent(report, 11)).toBe(true);- expect(routes.snapshot().factVersion).toBe(afterFirst.factVersion);- expect(- routes.invalidateDirectEdgeFromParent({- ...report,- connectionId: "unknown_connection",- }),- ).toBe(false);- expect(routes.reconcile(12).operation).toMatchObject({- childPeerId: A,- reason: "edge-unavailable",- candidates: [- {- tuple: { kind: "peer", parentPeerId: B, transport: "direct" },- },- ],- });- });-- it("advances one candidate cursor without resetting the operation deadline", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, A, 2);- const operation = routes.reconcile(1_000).operation!;- const deadline = operation.deadlineAtMs;- const first = beginCandidate(routes, {- nowMs: 1_001,- connectionId: "candidate_1",- reservation: { kind: "direct" },- }).operation!;- const failed = routes.candidateFailed({- childPeerId: A,- childSessionId: `${A}_session`,- revision: first.current!.revision,- connectionId: "candidate_1",- }, 1_001);- expect(failed.accepted).toBe(true);- expect(failed.activeRevision).toBeGreaterThan(first.current!.revision);- expect(failed.failedPeerIds).toEqual([]);- expect(failed.released).toEqual([]);- expect(routes.snapshot().operation).toMatchObject({- cursor: 1,- deadlineAtMs: deadline,- });-- const second = beginCandidate(routes, {- nowMs: 1_002,- connectionId: "candidate_2",- publicationGeneration: "publication_2",- publicationConnectionId: "publication_connection_2",- reservation: {- kind: "sfu-create",- edge: "candidate_2_edge",- publication: "candidate_2_publication",- },- }).operation!;- const lateReady = routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: second.current!.revision,- connectionId: "candidate_2",- }, deadline);- expect(lateReady).toMatchObject({ accepted: false, failedPeerIds: [A] });- expect(lateReady.released).toEqual([- "candidate_2_edge",- "candidate_2_publication",- ]);- expect(routes.snapshot().operation).toBeUndefined();- expect(- routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: second.current!.revision,- connectionId: "candidate_2",- }, deadline + 1).accepted,- ).toBe(false);- expect(routes.reconcile(deadline + 1).operation).toBeUndefined();- routes.touchExternalFacts();- expect(routes.reconcile(deadline + 2).operation?.childPeerId).toBe(A);- });-- it("reserves one derived deadline stage for direct and SFU", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, B, 2);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- addViewer(routes, A, 0);-- const operation = routes.reconcile(0).operation!;- expect(operation.deadlineAtMs).toBe(10_000);- expect(operation.wakeAtMs).toBe(5_000);- expect(operation.candidates.map((candidate) => candidate.tuple)).toEqual(- expect.arrayContaining([- { kind: "peer", parentPeerId: B, transport: "direct" },- { kind: "sfu", publication: "create" },- ]),- );-- beginCandidate(routes, {- nowMs: 1,- connectionId: "silent_direct",- reservation: { kind: "direct" },- });- const directExpired = routes.operationExpired(operation.wakeAtMs);- expect(directExpired).toMatchObject({ accepted: true });- expect(directExpired.failedPeerIds).toEqual([]);- expect(routes.snapshot().operation).toMatchObject({- deadlineAtMs: 10_000,- wakeAtMs: 10_000,- current: undefined,- });- expect(- routes.snapshot().operation!.candidates[- routes.snapshot().operation!.cursor- ]!.tuple,- ).toMatchObject({ kind: "sfu" });-- const prepared = beginCandidate(routes, {- nowMs: 7_000,- connectionId: "sfu_subscription",- publicationGeneration: "publication_generation",- publicationConnectionId: "publication_connection",- reservation: {- kind: "sfu-create",- edge: "sfu_edge",- publication: "sfu_publication",- },- }).operation!;- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: prepared.current!.revision,- connectionId: "sfu_subscription",- },- 9_000,- ).accepted,- ).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "sfu",- usable: true,- });- });-- it("uses the same direct head-start after an early hard failure", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, D, 0);- routes.hydrateEdge(D, peerEdge(HOST, "host_full"));- routes.hydrateHostPublication("publication_1", "publication_resource");- for (const peerId of [B, C]) {- addViewer(routes, peerId, 1);- routes.hydrateEdge(peerId, {- kind: "sfu",- publicationGeneration: "publication_1",- transport: "sfu",- connectionId: `${peerId}_sfu`,- usable: true,- physicalActive: true,- resource: `${peerId}_subscription`,- });- }- addViewer(routes, A, 0);-- const operation = routes.reconcile(0).operation!;- expect(operation.candidates.map((candidate) => candidate.tuple.kind)).toEqual([- "peer",- "sfu",- "peer",- ]);- const first = beginCandidate(routes, {- nowMs: 1,- connectionId: "first_direct",- reservation: { kind: "direct" },- }).operation!;- expect(routes.candidateFailed({- childPeerId: A,- childSessionId: `${A}_session`,- revision: first.current!.revision,- connectionId: "first_direct",- }, 2).accepted).toBe(true);- expect(routes.snapshot().operation).toMatchObject({- cursor: 1,- wakeAtMs: operation.wakeAtMs,- });- expect(- routes.snapshot().operation!.candidates[1]!.tuple.kind,- ).toBe("peer");- });-- it("keeps a transport-connected direct candidate until the total deadline", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, D, 0);- routes.hydrateEdge(D, peerEdge(HOST, "host_full"));- routes.hydrateHostPublication("publication", "publication_resource");- addViewer(routes, B, 1);- routes.hydrateEdge(B, {- kind: "sfu",- publicationGeneration: "publication",- transport: "sfu",- connectionId: "b_sfu",- usable: true,- physicalActive: true,- resource: "b_subscription",- });- addViewer(routes, A, 0);-- const operation = routes.reconcile(0).operation!;- const direct = beginCandidate(routes, {- nowMs: 1,- connectionId: "a_direct",- reservation: { kind: "direct" },- }).operation!;- expect(routes.candidateTransportConnected({- childPeerId: A,- childSessionId: `${A}_session`,- revision: direct.current!.revision,- connectionId: "a_direct",- }, 1_000).accepted).toBe(true);- expect(routes.candidateTransportConnected({- childPeerId: A,- childSessionId: `${A}_session`,- revision: direct.current!.revision,- connectionId: "a_direct",- }, 1_001).accepted).toBe(true);- expect(routes.candidateTransportConnected({- childPeerId: A,- childSessionId: `${A}_session`,- revision: direct.current!.revision,- connectionId: "stale_direct",- }, 1_002).accepted).toBe(false);- expect(routes.snapshot().revision).toBe(direct.current!.revision - 1);- expect(routes.snapshot().operation?.wakeAtMs).toBe(operation.deadlineAtMs);- expect(routes.operationExpired(operation.wakeAtMs).accepted).toBe(false);- expect(routes.snapshot().operation?.current?.connectionId).toBe("a_direct");- expect(routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: direct.current!.revision,- connectionId: "a_direct",- }, operation.wakeAtMs + 1).accepted).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "peer",- connectionId: "a_direct",- });- });-- it("keeps SFU active while converging through an SFU-fed parent", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, B, 2);- routes.hydrateHostPublication(- "publication_generation",- "publication_resource",- );- routes.hydrateEdge(B, {- kind: "sfu",- publicationGeneration: "publication_generation",- transport: "sfu",- connectionId: "b_sfu",- usable: true,- physicalActive: true,- resource: "b_subscription",- });- addViewer(routes, C, 0);- routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"));- addViewer(routes, A, 0);-- const acquisition = routes.reconcile(0).operation!;- expect(acquisition.candidates[0]?.tuple).toEqual({- kind: "peer",- parentPeerId: B,- transport: "direct",- });- beginCandidate(routes, {- nowMs: 1,- connectionId: "a_direct_head_start",- reservation: { kind: "direct" },- });- routes.operationExpired(acquisition.wakeAtMs);- const prepared = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 1,- connectionId: "a_sfu_reuse",- reservation: { kind: "sfu-reuse", edge: "a_subscription" },- }).operation!;- expect(- routes.candidateReady(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: prepared.current!.revision,- connectionId: "a_sfu_reuse",- },- acquisition.wakeAtMs + 2,- ).accepted,- ).toBe(true);- expect(routes.snapshot().hostPublication).toMatchObject({- generation: "publication_generation",- usable: true,- });- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "sfu",- publicationGeneration: "publication_generation",- usable: true,- });- const convergence = routes.reconcile(acquisition.wakeAtMs + 3).operation!;- expect(convergence).toMatchObject({- childPeerId: A,- reason: "direct-convergence",- });- expect(convergence.candidates[0]?.tuple).toEqual({- kind: "peer",- parentPeerId: B,- transport: "direct",- });- const direct = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 4,- connectionId: "a_from_b",- reservation: { kind: "direct" },- }).operation!;- expect(routes.snapshot().operation?.wakeAtMs).toBe(- convergence.deadlineAtMs,- );- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "sfu",- connectionId: "a_sfu_reuse",- });- expect(routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: direct.current!.revision,- connectionId: "a_from_b",- }, acquisition.wakeAtMs + 5).accepted).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "peer",- parentPeerId: B,- connectionId: "a_from_b",- });- });-- it("advances exact direct convergence failures without failing SFU", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, D, 0);- routes.hydrateEdge(D, peerEdge(HOST, "host_full"));- routes.hydrateHostPublication("publication_1", "publication_resource");- for (const peerId of [B, C]) {- addViewer(routes, peerId, 1);- routes.hydrateEdge(peerId, {- kind: "sfu",- publicationGeneration: "publication_1",- transport: "sfu",- connectionId: `${peerId}_sfu`,- usable: true,- physicalActive: true,- resource: `${peerId}_subscription`,- });- }- addViewer(routes, A, 0, 0);- const acquisition = routes.reconcile(0).operation!;- const headStartTuple = acquisition.candidates[0]!.tuple;- expect(headStartTuple.kind).toBe("peer");- const headStartParent = headStartTuple.kind === "peer"- ? headStartTuple.parentPeerId- : "";- const otherParent = headStartParent === B ? C : B;- beginCandidate(routes, {- nowMs: 1,- connectionId: "a_direct_head_start",- reservation: { kind: "direct" },- });- routes.operationExpired(acquisition.wakeAtMs);- const sfu = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 1,- connectionId: "a_sfu",- reservation: { kind: "sfu-reuse", edge: "a_subscription" },- }).operation!;- expect(routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: sfu.current!.revision,- connectionId: "a_sfu",- }, acquisition.wakeAtMs + 2).accepted).toBe(true);-- const first = routes.reconcile(acquisition.wakeAtMs + 3).operation!;- expect(first.candidates[0]?.tuple).toMatchObject({- kind: "peer",- parentPeerId: otherParent,- });- const failed = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 4,- connectionId: "a_direct_followup",- reservation: { kind: "direct" },- }).operation!;- expect(routes.candidateFailed({- childPeerId: A,- childSessionId: `${A}_session`,- revision: failed.current!.revision,- connectionId: "a_direct_followup",- }, acquisition.wakeAtMs + 5).failedPeerIds).toEqual([]);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "sfu",- connectionId: "a_sfu",- });- expect(- routes.reconcile(acquisition.wakeAtMs + 6).operation?.candidates[0]?.tuple,- ).toMatchObject({- kind: "peer",- parentPeerId: headStartParent,- });- });-- it("round-robins background direct convergence between SFU Viewers", () => {- const routes = controller(2, { sfuEnabled: true });- routes.hydrateHostPublication("publication", "publication_resource");- for (const peerId of [B, C]) {- addViewer(routes, peerId, 2);- routes.hydrateEdge(peerId, {- kind: "sfu",- publicationGeneration: "publication",- transport: "sfu",- connectionId: `${peerId}_sfu`,- usable: true,- physicalActive: true,- resource: `${peerId}_subscription`,- });- }-- let nowMs = 0;- for (const peerId of [A, D]) {- addViewer(routes, peerId, 0, nowMs);- const acquisition = routes.reconcile(nowMs).operation!;- beginCandidate(routes, {- nowMs: nowMs + 1,- connectionId: `${peerId}_head_start`,- reservation: { kind: "direct" },- });- routes.operationExpired(acquisition.wakeAtMs);- const sfu = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 1,- connectionId: `${peerId}_sfu`,- reservation: {- kind: "sfu-reuse",- edge: `${peerId}_subscription`,- },- }).operation!;- expect(routes.candidateReady({- childPeerId: peerId,- childSessionId: `${peerId}_session`,- revision: sfu.current!.revision,- connectionId: `${peerId}_sfu`,- }, acquisition.wakeAtMs + 2).accepted).toBe(true);- nowMs = acquisition.wakeAtMs + 3;- }-- const first = routes.reconcile(nowMs).operation!;- expect(first).toMatchObject({- childPeerId: A,- reason: "direct-convergence",- });- const firstAttempt = beginCandidate(routes, {- nowMs: nowMs + 1,- connectionId: "a_background_direct",- reservation: { kind: "direct" },- }).operation!;- expect(routes.candidateFailed({- childPeerId: A,- childSessionId: `${A}_session`,- revision: firstAttempt.current!.revision,- connectionId: "a_background_direct",- }, nowMs + 2).accepted).toBe(true);- expect(routes.reconcile(nowMs + 3).operation).toMatchObject({- childPeerId: D,- reason: "direct-convergence",- });- });-- it("preempts direct convergence when another Viewer needs a route", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, B, 2);- routes.hydrateHostPublication("publication_1", "publication_resource");- routes.hydrateEdge(B, {- kind: "sfu",- publicationGeneration: "publication_1",- transport: "sfu",- connectionId: "b_sfu",- usable: true,- physicalActive: true,- resource: "b_subscription",- });- addViewer(routes, C, 0);- routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"));- addViewer(routes, A, 0, 0);- const acquisition = routes.reconcile(0).operation!;- beginCandidate(routes, {- nowMs: 1,- connectionId: "a_direct_head_start",- reservation: { kind: "direct" },- });- routes.operationExpired(acquisition.wakeAtMs);- const sfu = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 1,- connectionId: "a_sfu",- reservation: { kind: "sfu-reuse", edge: "a_subscription" },- }).operation!;- routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: sfu.current!.revision,- connectionId: "a_sfu",- }, acquisition.wakeAtMs + 2);- expect(- routes.reconcile(acquisition.wakeAtMs + 3).operation?.reason,- ).toBe("direct-convergence");- beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 4,- connectionId: "a_direct_pending",- reservation: { kind: "direct", overlap: "a_overlap" },- });-- const activeRevision = routes.snapshot().revision;- expect(routes.invalidateEdge({- childPeerId: C,- childSessionId: `${C}_session`,- parentSessionId: "host_session",- routeRevision: activeRevision,- connectionId: "c_from_host",- }, acquisition.wakeAtMs + 5)).toBe(true);- const reconciled = routes.reconcile(acquisition.wakeAtMs + 6);- expect(reconciled.released).toEqual(["a_overlap"]);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "sfu",- connectionId: "a_sfu",- });- expect(reconciled.operation).toMatchObject({- childPeerId: C,- reason: "edge-unavailable",- });- });-- it("owns Host-full SFU bootstrap failure by the waiting demand", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, B, 2);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- addViewer(routes, C, 0);- routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"));- addViewer(routes, A, 0);- addViewer(routes, D, 0);-- const operation = routes.reconcile(0).operation!;- expect(operation.candidates.some((candidate) => candidate.tuple.kind === "sfu"))- .toBe(false);- expect(operation.wakeAtMs).toBe(5_000);- beginCandidate(routes, {- nowMs: 1,- connectionId: "a_silent_direct",- reservation: { kind: "direct" },- });- const blocked = routes.operationExpired(operation.wakeAtMs);- expect(blocked).toMatchObject({ accepted: true });- expect(blocked.failedPeerIds).toEqual([]);- expect(blocked.released).toEqual([]);- expect(routes.snapshot().operation).toBeUndefined();-- const bootstrap = routes.reconcile(operation.wakeAtMs + 1).operation!;- expect(bootstrap.childPeerId).toBe(C);- expect(bootstrap.demandPeerId).toBe(A);- expect(bootstrap.candidates[0]!.tuple).toMatchObject({- kind: "sfu",- publication: "create",- });- expect(bootstrap.candidates[0]!.endpointTransition.kind).toBe("overlap");- const firstCarrier = beginCandidate(routes, {- nowMs: operation.wakeAtMs + 2,- connectionId: "c_bootstrap_sfu",- publicationGeneration: "c_bootstrap_publication",- publicationConnectionId: "c_bootstrap_ingress",- reservation: {- kind: "sfu-create",- edge: "c_bootstrap_subscription",- publication: "c_bootstrap_publication_resource",- overlap: "c_bootstrap_overlap",- },- }).operation!;- expect(routes.candidateFailed({- childPeerId: C,- childSessionId: `${C}_session`,- revision: firstCarrier.current!.revision,- connectionId: "c_bootstrap_sfu",- }, operation.wakeAtMs + 3).failedPeerIds).toEqual([]);- expect(routes.snapshot().upstreamByViewer.get(C)).toMatchObject({- connectionId: "c_from_host",- usable: true,- physicalActive: true,- });-- const secondBootstrap = routes.reconcile(operation.wakeAtMs + 4).operation!;- expect(secondBootstrap).toMatchObject({- childPeerId: B,- demandPeerId: A,- reason: "sfu-bootstrap",- });- const secondCarrier = beginCandidate(routes, {- nowMs: operation.wakeAtMs + 5,- connectionId: "b_bootstrap_sfu",- publicationGeneration: "b_bootstrap_publication",- publicationConnectionId: "b_bootstrap_ingress",- reservation: {- kind: "sfu-create",- edge: "b_bootstrap_subscription",- publication: "b_bootstrap_publication_resource",- overlap: "b_bootstrap_overlap",- },- }).operation!;- expect(routes.candidateFailed({- childPeerId: B,- childSessionId: `${B}_session`,- revision: secondCarrier.current!.revision,- connectionId: "b_bootstrap_sfu",- }, operation.wakeAtMs + 6).failedPeerIds).toEqual([A]);- for (const [peerId, connectionId] of [- [B, "b_from_host"],- [C, "c_from_host"],- ] as const) {- expect(routes.snapshot().upstreamByViewer.get(peerId)).toMatchObject({- connectionId,- usable: true,- physicalActive: true,- });- }- const nextDemand = routes.reconcile(operation.wakeAtMs + 7).operation!;- expect(nextDemand).toMatchObject({ childPeerId: D, reason: "join" });- beginCandidate(routes, {- nowMs: operation.wakeAtMs + 8,- connectionId: "d_direct",- reservation: { kind: "direct" },- });- expect(routes.operationExpired(nextDemand.deadlineAtMs).failedPeerIds).toEqual([D]);- expect(routes.reconcile(nextDemand.deadlineAtMs + 1).operation).toBeUndefined();- });-- it("abandons bootstrap when a Host slot becomes available", () => {- const routes = controller(2, { sfuEnabled: true });- expect(routes.setEffectiveCapacity(HOST, "host_session", 1)).toBe(true);- addViewer(routes, B, 0);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- addViewer(routes, A, 0);-- const bootstrap = routes.reconcile(0).operation!;- expect(bootstrap).toMatchObject({- childPeerId: B,- demandPeerId: A,- reason: "sfu-bootstrap",- });- const prepared = beginCandidate(routes, {- nowMs: 1,- connectionId: "stale_bootstrap",- publicationGeneration: "stale_publication",- publicationConnectionId: "stale_ingress",- reservation: {- kind: "sfu-create",- edge: "stale_subscription",- publication: "stale_publication_resource",- overlap: "stale_overlap",- },- }).operation!;-- expect(routes.setEffectiveCapacity(HOST, "host_session", 2)).toBe(true);- const stale = routes.candidateReady({- childPeerId: B,- childSessionId: `${B}_session`,- revision: prepared.current!.revision,- connectionId: "stale_bootstrap",- }, 2);- expect(stale.accepted).toBe(false);- expect(stale.released).toEqual(expect.arrayContaining([- "stale_subscription",- "stale_publication_resource",- "stale_overlap",- ]));- expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({- connectionId: "b_from_host",- usable: true,- physicalActive: true,- });- expect(routes.reconcile(3).operation).toMatchObject({- childPeerId: A,- demandPeerId: A,- reason: "join",- });- });-- it("tries SFU first after bootstrap and retains the direct suffix", () => {- const routes = controller(2, { sfuEnabled: true });- for (const [peerId, connectionId] of [- [B, "b_from_host"],- [C, "c_from_host"],- ] as const) {- addViewer(routes, peerId, 1);- routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));- }- addViewer(routes, A, 0);-- const acquisition = routes.reconcile(0).operation!;- beginCandidate(routes, {- nowMs: 1,- connectionId: "a_direct_head_start",- reservation: { kind: "direct" },- });- routes.operationExpired(acquisition.wakeAtMs);- const bootstrap = routes.reconcile(acquisition.wakeAtMs + 1).operation!;- const carrier = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 2,- connectionId: "bootstrap_sfu",- publicationGeneration: "bootstrap_publication",- publicationConnectionId: "bootstrap_ingress",- reservation: {- kind: "sfu-create",- edge: "carrier_subscription",- publication: "bootstrap_publication_resource",- overlap: "bootstrap_overlap",- },- }).operation!;- expect(routes.candidateReady({- childPeerId: bootstrap.childPeerId,- childSessionId: bootstrap.childSessionId,- revision: carrier.current!.revision,- connectionId: "bootstrap_sfu",- }, acquisition.wakeAtMs + 3).accepted).toBe(true);-- const demand = routes.reconcile(acquisition.wakeAtMs + 4).operation!;- expect(demand).toMatchObject({- childPeerId: A,- demandPeerId: A,- reason: "join",- });- expect(demand.candidates[0]?.tuple).toEqual({- kind: "sfu",- publication: "reuse",- });- expect(- demand.candidates.slice(1).every((candidate) => candidate.tuple.kind === "peer"),- ).toBe(true);- const subscription = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 5,- connectionId: "a_sfu",- reservation: { kind: "sfu-reuse", edge: "a_subscription" },- }).operation!;- expect(routes.candidateFailed({- childPeerId: A,- childSessionId: `${A}_session`,- revision: subscription.current!.revision,- connectionId: "a_sfu",- }, acquisition.wakeAtMs + 6).accepted).toBe(true);- expect(- routes.snapshot().operation?.candidates[- routes.snapshot().operation!.cursor- ]?.tuple.kind,- ).toBe("peer");- const direct = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 7,- connectionId: "a_deferred_direct",- reservation: { kind: "direct" },- }).operation!;- expect(routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: direct.current!.revision,- connectionId: "a_deferred_direct",- }, acquisition.wakeAtMs + 8).accepted).toBe(true);- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- kind: "peer",- connectionId: "a_deferred_direct",- });- expect(routes.reconcile(acquisition.wakeAtMs + 9).operation).toMatchObject({- childPeerId: bootstrap.childPeerId,- reason: "direct-convergence",- });- });-- it("replans when the current candidate parent fails", () => {- const routes = controller(3);- addViewer(routes, A, 1);- addViewer(routes, B, 1);- addViewer(routes, C, 1);- routes.hydrateEdge(A, peerEdge(HOST, "a_old"));- routes.hydrateEdge(B, peerEdge(HOST, "b_old"));- routes.hydrateEdge(C, peerEdge(HOST, "c_old"));- const revision = routes.snapshot().revision;- expect(- routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: revision,- connectionId: "a_old",- }),- ).toBe(true);- routes.reconcile(0);- const current = beginCandidate(routes, {- nowMs: 1,- connectionId: "a_new",- reservation: { kind: "direct" },- }).operation!;- const currentTuple = current.current!.tuple;- expect(currentTuple.kind).toBe("peer");- const failedParentPeerId = currentTuple.kind === "peer"- ? currentTuple.parentPeerId- : B;- const failedParentConnectionId = failedParentPeerId === B- ? "b_old"- : "c_old";- expect(- routes.invalidateEdge({- childPeerId: failedParentPeerId,- childSessionId: `${failedParentPeerId}_session`,- parentSessionId: "host_session",- routeRevision: revision,- connectionId: failedParentConnectionId,- }),- ).toBe(true);- expect(- routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: current.current!.revision,- connectionId: "a_new",- }, 2).accepted,- ).toBe(false);- const replacement = beginCandidate(routes, {- nowMs: 2,- connectionId: "a_new_2",- reservation: { kind: "direct" },- }).operation!;- expect(- routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: replacement.current!.revision,- connectionId: "a_new_2",- }, 3).accepted,- ).toBe(true);- expect(routes.reconcile(3).operation?.childPeerId).toBe(- failedParentPeerId,- );- });-- it("keeps an active candidate when an unrelated session is replaced", () => {- const routes = controller(2);- for (const [peerId, connectionId] of [- [B, "b_from_host"],- [C, "c_from_host"],- ] as const) {- addViewer(routes, peerId, 1);- routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));- }- addViewer(routes, A, 0);- const operation = routes.reconcile(0).operation!;- const active = beginCandidate(routes, {- nowMs: 1,- connectionId: "a_active_candidate",- reservation: { kind: "direct" },- }).operation!;- const tuple = active.current!.tuple;- expect(tuple.kind).toBe("peer");- const unrelatedPeerId = tuple.kind === "peer" && tuple.parentPeerId === B- ? C- : B;-- expect(routes.upsertParticipant({- peerId: unrelatedPeerId,- role: "viewer",- sessionId: `${unrelatedPeerId}_replacement`,- effectiveDownstreamCapacity: 1,- }, 2)).toEqual([]);- expect(routes.snapshot().operation?.current).toMatchObject({- revision: operation.baseRevision + 1,- connectionId: "a_active_candidate",- });- });-- it("uses a freed Host slot for new demand without moving healthy descendants", () => {- const routes = controller(2);- addViewer(routes, A, 2);- addViewer(routes, B, 2);- addViewer(routes, C, 0);- addViewer(routes, D, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_root"));- routes.hydrateEdge(B, peerEdge(HOST, "b_root"));- routes.hydrateEdge(C, peerEdge(A, "c_from_a"));- routes.hydrateEdge(D, peerEdge(B, "d_from_b"));-- expect(routes.confirmDeparture(B)).toBe(true);- const repair = routes.reconcile(0).operation!;- expect(repair.childPeerId).toBe(D);- expect(repair.candidates[0]!.tuple).toEqual({- kind: "peer",- parentPeerId: A,- transport: "direct",- });- commitCurrent(routes, 1, "d_from_a");- expect(routes.reconcile(2).operation).toBeUndefined();- expect(routes.snapshot().upstreamByViewer.has(B)).toBe(false);-- addViewer(routes, E, 0);- const join = routes.reconcile(3).operation!;- expect(join.childPeerId).toBe(E);- expect(join.candidates[0]!.tuple).toEqual({- kind: "peer",- parentPeerId: HOST,- transport: "direct",- });- commitCurrent(routes, 4, "e_from_host");-- expect(routes.snapshot().upstreamByViewer.get(C)).toMatchObject({- parentPeerId: A,- connectionId: "c_from_a",- });- expect(routes.snapshot().upstreamByViewer.get(D)).toMatchObject({- parentPeerId: A,- connectionId: "d_from_a",- });- expect(routes.snapshot().upstreamByViewer.get(E)).toMatchObject({- parentPeerId: HOST,- connectionId: "e_from_host",- });- });-- it("keeps grace media, then reparents a confirmed relay departure", () => {- const routes = controller(2);- addViewer(routes, A, 2);- addViewer(routes, B, 1);- addViewer(routes, C, 0);- routes.hydrateEdge(A, peerEdge(HOST, "a_connection"));- routes.hydrateEdge(B, peerEdge(A, "b_connection"));- routes.hydrateEdge(C, peerEdge(B, "c_connection"));-- expect(routes.disconnectSession(A, `${A}_session`)).toBe(true);- expect(routes.reconcile(0).operation).toBeUndefined();- expect(routes.confirmDeparture(A)).toBe(true);- expect(routes.reconcile(1).operation?.childPeerId).toBe(B);- commitCurrent(routes, 2, "b_reparented");- const beforePrune = routes.snapshot().revision;- const after = routes.reconcile(3);- expect(after.removedPeerIds).toContain(A);- expect(routes.snapshot().revision).toBeGreaterThan(beforePrune);- expect(routes.snapshot().upstreamByViewer.get(C)).toMatchObject({- parentPeerId: B,- connectionId: "c_connection",- });- });-- it("moves newest overflow children and supports effective capacity zero", () => {- const routes = controller(3);- addViewer(routes, A, 3);- routes.hydrateEdge(A, peerEdge(HOST, "a_connection"));- for (const peerId of [B, C, D]) {- addViewer(routes, peerId, 0);- routes.hydrateEdge(peerId, peerEdge(A, `${peerId}_connection`));- }- expect(routes.setEffectiveCapacity(A, `${A}_session`, 1)).toBe(true);- expect(routes.reconcile(0).operation?.childPeerId).toBe(D);- expect(routes.setPaused(true)).toEqual([]);- expect(routes.setEffectiveCapacity(A, `${A}_session`, 0)).toBe(true);- expect(routes.setPaused(false)).toEqual([]);- expect(routes.reconcile(1).operation?.childPeerId).toBe(D);-- const blocked = controller(1);- addViewer(blocked, A, 0);- addViewer(blocked, B, 0);- blocked.hydrateEdge(A, peerEdge(HOST, "blocked_a"));- blocked.hydrateEdge(B, peerEdge(A, "blocked_b"));- expect(blocked.reconcile(0).operation).toBeUndefined();- expect(blocked.reconcile(1).operation).toBeUndefined();- });-- it("aborts pending SFU resources on pause and repairs publication", () => {- const routes = controller(1, { sfuEnabled: true });- addViewer(routes, A, 1);- addViewer(routes, B, 0);- routes.hydrateHostPublication("publication_1", "publication_resource");- routes.hydrateEdge(A, {- kind: "sfu",- publicationGeneration: "publication_1",- transport: "sfu",- connectionId: "a_sfu",- usable: true,- physicalActive: true,- resource: "a_subscription",- });- const operation = routes.reconcile(0).operation!;- expect(operation.candidates[0]?.tuple).toEqual({- kind: "peer",- parentPeerId: A,- transport: "direct",- });- beginCandidate(routes, {- nowMs: 1,- connectionId: "b_direct_head_start",- reservation: { kind: "direct" },- });- routes.operationExpired(operation.wakeAtMs);- beginCandidate(routes, {- nowMs: operation.wakeAtMs + 1,- connectionId: "b_candidate",- reservation: { kind: "sfu-reuse", edge: "b_subscription" },- });- expect(routes.setPaused(true)).toEqual(["b_subscription"]);- expect(routes.snapshot().operation).toBeUndefined();- expect(routes.snapshot().upstreamByViewer.get(A)?.connectionId).toBe("a_sfu");- routes.setPaused(false);- expect(routes.invalidateHostPublication({- hostSessionId: "host_session",- routeRevision: routes.snapshot().revision,- generation: "publication_1",- connectionId: "publication:publication_1",- })).toBe(true);- routes.touchExternalFacts();- const repair = routes.reconcile(2).operation!;- expect(repair.childPeerId).toBe(A);- expect(repair.candidates[0]?.tuple).toEqual({- kind: "peer",- parentPeerId: HOST,- transport: "direct",- });- skipCandidate(routes, 3);- expect(routes.snapshot().operation?.candidates[1]?.tuple).toEqual({- kind: "sfu",- publication: "replace",- });- expect(() => beginCandidate(routes, {- nowMs: 3,- connectionId: "a_sfu_2",- publicationGeneration: "publication_2",- publicationConnectionId: "publication_connection_2",- reservation: {- kind: "sfu-create",- edge: "a_subscription_2",- publication: "publication_resource_2",- },- })).toThrow("endpoint overlap reservation");- const publicationRepair = beginCandidate(routes, {- nowMs: 3,- connectionId: "a_sfu_2",- publicationGeneration: "publication_2",- publicationConnectionId: "publication_connection_2",- reservation: {- kind: "sfu-create",- edge: "a_subscription_2",- publication: "publication_resource_2",- overlap: "publication_overlap",- },- }).operation!;- const repaired = routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: publicationRepair.current!.revision,- connectionId: "a_sfu_2",- }, 4);- expect(repaired.accepted).toBe(true);- expect(repaired.released).toHaveLength(3);- expect(repaired.released).toEqual(expect.arrayContaining([- "publication_overlap",- "a_subscription",- "publication_resource",- ]));- expect(routes.snapshot().hostPublication).toMatchObject({- generation: "publication_2",- usable: true,- physicalActive: true,- });-- const bootstrap = controller(1, { sfuEnabled: true });- addViewer(bootstrap, A, 0);- addViewer(bootstrap, B, 0);- bootstrap.hydrateEdge(A, peerEdge(HOST, "bootstrap_a"));- const bootstrapOperation = bootstrap.reconcile(0).operation!;- expect(bootstrapOperation.childPeerId).toBe(A);- expect(bootstrapOperation.candidates[0]?.tuple).toEqual({- kind: "sfu",- publication: "create",- });- expect(() => beginCandidate(bootstrap, {- nowMs: 2,- connectionId: "bootstrap_sfu",- publicationGeneration: "bootstrap_publication",- publicationConnectionId: "bootstrap_ingress_connection",- reservation: {- kind: "sfu-create",- edge: "bootstrap_subscription",- publication: "bootstrap_ingress",- },- })).toThrow("endpoint overlap reservation");- const preparedBootstrap = beginCandidate(bootstrap, {- nowMs: 2,- connectionId: "bootstrap_sfu",- publicationGeneration: "bootstrap_publication",- publicationConnectionId: "bootstrap_ingress_connection",- reservation: {- kind: "sfu-create",- edge: "bootstrap_subscription",- publication: "bootstrap_ingress",- overlap: "bootstrap_overlap",- },- }).operation!;- expect(bootstrap.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: preparedBootstrap.current!.revision,- connectionId: "bootstrap_sfu",- }, 3).accepted).toBe(true);- expect(bootstrap.reconcile(4).operation?.childPeerId).toBe(B);- });-- it("reopens SFU bootstrap after the physical publication retires", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, A, 0);- routes.hydrateHostPublication("retired_publication", "publication_resource");- routes.hydrateEdge(A, {- kind: "sfu",- publicationGeneration: "retired_publication",- transport: "sfu",- connectionId: "a_from_sfu",- usable: true,- physicalActive: true,- resource: "a_subscription",- });-- const publication = routes.snapshot().hostPublication!;- expect(- routes.retireHostPublication({- hostSessionId: publication.hostSessionId,- routeRevision: routes.snapshot().revision,- generation: publication.generation,- connectionId: publication.connectionId,- }),- ).toEqual(expect.arrayContaining(["a_subscription", "publication_resource"]));- expect(routes.snapshot().hostPublication).toBeNull();-- for (const [peerId, connectionId] of [- [B, "b_from_host"],- [C, "c_from_host"],- ] as const) {- addViewer(routes, peerId, 0);- routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));- }- expect(routes.reconcile(1)).toMatchObject({- failedPeerIds: [],- operation: {- demandPeerId: A,- reason: "sfu-bootstrap",- candidates: [- {- tuple: { kind: "sfu", publication: "create" },- },- ],- },- });- });-- it("binds reserve and skip results to the exact candidate cursor", () => {- const reserve = controller(2);- addViewer(reserve, A, 2);- reserve.hydrateEdge(A, peerEdge(HOST, "a_active"));- addViewer(reserve, B, 0);- const first = reserve.reconcile(0).operation!;- expect(first.candidates[0]?.tuple).toMatchObject({- kind: "peer",- parentPeerId: HOST,- });- reserve.setEffectiveCapacity(HOST, "host_session", 0);- const staleReserve = reserve.beginCurrentCandidate({- guard: cursorGuard(first),- nowMs: 1,- connectionId: "reserved_for_old_cursor",- reservation: { kind: "direct", overlap: "stale_reservation" },- });- expect(staleReserve).toMatchObject({ accepted: false });- expect(staleReserve.released).toEqual(["stale_reservation"]);- expect(reserve.snapshot().operation).toMatchObject({- cursor: 0,- candidates: [- {- tuple: { kind: "peer", parentPeerId: A, transport: "direct" },- },- ],- });- expect(reserve.snapshot().operation?.current).toBeUndefined();-- const skip = controller(2);- addViewer(skip, A, 2);- skip.hydrateEdge(A, peerEdge(HOST, "a_active"));- addViewer(skip, B, 0);- const staleCursor = skip.reconcile(0).operation!;- skip.setEffectiveCapacity(HOST, "host_session", 0);- expect(skip.skipCurrentCandidate(cursorGuard(staleCursor), 1).accepted).toBe(false);- expect(skip.snapshot().operation).toMatchObject({ cursor: 0 });- expect(skip.snapshot().operation?.candidates[0]?.tuple).toMatchObject({- kind: "peer",- parentPeerId: A,- });- });--- it("keeps only old SFU roots that still anchor peer descendants", () => {- const routes = controller(1, { sfuEnabled: true });- addViewer(routes, A, 0);- addViewer(routes, B, 1);- addViewer(routes, C, 0);- addViewer(routes, D, 0);- routes.hydrateHostPublication("publication_1", "publication_resource_1");- for (const [peerId, resource] of [- [A, "subscription_a"],- [B, "subscription_b"],- [D, "subscription_d"],- ] as const) {- routes.hydrateEdge(peerId, {- kind: "sfu",- publicationGeneration: "publication_1",- transport: "sfu",- connectionId: `${peerId}_sfu_1`,- usable: true,- physicalActive: true,- resource,- });- }- routes.hydrateEdge(C, peerEdge(B, "c_from_b"));- expect(routes.invalidateHostPublication({- hostSessionId: "host_session",- routeRevision: 0,- generation: "publication_1",- connectionId: "publication:publication_1",- }, 10)).toBe(true);- routes.touchExternalFacts();- const operation = routes.reconcile(20).operation!;- expect(operation.candidates[0]).toMatchObject({- tuple: { kind: "sfu", publication: "replace" },- endpointTransition: { kind: "overlap", producerPeerId: HOST },- });- const prepared = beginCandidate(routes, {- nowMs: 21,- connectionId: "a_sfu_2",- publicationGeneration: "publication_2",- publicationConnectionId: "publication_connection_2",- reservation: {- kind: "sfu-create",- edge: "subscription_a_2",- publication: "publication_resource_2",- overlap: "publication_overlap",- },- }).operation!;- const settled = routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: prepared.current!.revision,- connectionId: "a_sfu_2",- }, 22);- expect(settled.accepted).toBe(true);- expect(settled.released).toEqual(expect.arrayContaining([- "publication_overlap",- "subscription_a",- "subscription_b",- "subscription_d",- "publication_resource_1",- ]));- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- publicationGeneration: "publication_2",- });- expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({- kind: "sfu",- publicationGeneration: "publication_1",- usable: false,- physicalActive: false,- });- expect(routes.snapshot().upstreamByViewer.get(C)).toMatchObject({- kind: "peer",- parentPeerId: B,- });- expect(routes.snapshot().upstreamByViewer.has(D)).toBe(false);- expect(routes.routeDiagnosticSnapshot(22).children[1]).toMatchObject({- demandAgeMs: 12,- finalRoute: "waiting",- });- expect(routes.reconcile(23).operation).toMatchObject({- childPeerId: B,- reason: "edge-unavailable",- });- });-- it("rebinds direct and SFU media to replacement sessions", () => {- const peerRoutes = controller(2);- addViewer(peerRoutes, A, 1);- addViewer(peerRoutes, B, 0);- peerRoutes.hydrateEdge(A, peerEdge(HOST, "a_direct"));- peerRoutes.hydrateEdge(B, peerEdge(A, "b_direct"));- expect(peerRoutes.upsertParticipant({- peerId: A,- role: "viewer",- sessionId: "a_replacement",- effectiveDownstreamCapacity: 1,- })).toEqual([]);- expect(peerRoutes.snapshot().upstreamByViewer.get(A)).toMatchObject({- childSessionId: "a_replacement",- usable: true,- physicalActive: true,- });- expect(peerRoutes.snapshot().upstreamByViewer.get(B)).toMatchObject({- parentSessionId: "a_replacement",- });- expect(peerRoutes.upsertParticipant({- peerId: B,- role: "viewer",- sessionId: "b_replacement",- effectiveDownstreamCapacity: 0,- })).toEqual([]);- expect(peerRoutes.snapshot().upstreamByViewer.get(B)).toMatchObject({- childSessionId: "b_replacement",- usable: true,- physicalActive: true,- });-- const sfuRoutes = controller(1, { sfuEnabled: true });- addViewer(sfuRoutes, A, 0);- sfuRoutes.hydrateHostPublication(- "publication",- "publication_resource",- "publication_connection",- );- sfuRoutes.hydrateEdge(A, {- kind: "sfu",- publicationGeneration: "publication",- transport: "sfu",- connectionId: "subscription_connection",- usable: true,- physicalActive: true,- resource: "subscription_resource",- });- expect(sfuRoutes.upsertParticipant({- peerId: HOST,- role: "host",- sessionId: "host_replacement",- effectiveDownstreamCapacity: 1,- })).toEqual([]);- expect(sfuRoutes.snapshot().hostPublication).toMatchObject({- hostSessionId: "host_replacement",- usable: true,- physicalActive: true,- });- expect(sfuRoutes.upsertParticipant({- peerId: A,- role: "viewer",- sessionId: "a_replacement",- effectiveDownstreamCapacity: 0,- })).toEqual([]);- expect(sfuRoutes.snapshot().upstreamByViewer.get(A)).toMatchObject({- childSessionId: "a_replacement",- physicalActive: true,- });- });-- it("retries a bootstrap carrier only when its transition improves", () => {- const routes = controller(1, { sfuEnabled: true });- addViewer(routes, A, 0);- routes.hydrateEdge(A, peerEdge(HOST, "failed_direct"));- expect(routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: 0,- connectionId: "failed_direct",- })).toBe(true);- const operation = routes.reconcile(0).operation!;- const prepared = beginCandidate(routes, {- nowMs: 1,- connectionId: "failed_sfu",- publicationGeneration: "failed_publication",- publicationConnectionId: "failed_publication_connection",- reservation: {- kind: "sfu-create",- edge: "failed_subscription_resource",- publication: "failed_publication_resource",- overlap: "failed_overlap",- },- }).operation!;- expect(routes.candidateFailed({- childPeerId: operation.childPeerId,- childSessionId: operation.childSessionId,- revision: prepared.current!.revision,- connectionId: "failed_sfu",- }, 2)).toMatchObject({ accepted: true, failedPeerIds: [A] });- const improved = routes.reconcile(3).operation!;- expect(improved.candidates[0]).toMatchObject({- tuple: { kind: "sfu", publication: "create" },- endpointTransition: { kind: "none", producerPeerId: HOST },- });- const improvedAttempt = beginCandidate(routes, {- nowMs: 4,- connectionId: "improved_sfu",- publicationGeneration: "improved_publication",- publicationConnectionId: "improved_publication_connection",- reservation: {- kind: "sfu-create",- edge: "improved_subscription_resource",- publication: "improved_publication_resource",- },- }).operation!;- expect(routes.candidateFailed({- childPeerId: improved.childPeerId,- childSessionId: improved.childSessionId,- revision: improvedAttempt.current!.revision,- connectionId: "improved_sfu",- }, 5)).toMatchObject({ accepted: true, failedPeerIds: [A] });- const factVersion = routes.snapshot().factVersion;- expect(routes.reconcile(6).operation).toBeUndefined();- expect(routes.setEffectiveCapacity(A, `${A}_session`, 0)).toBe(true);- expect(routes.snapshot().factVersion).toBe(factVersion);- expect(routes.reconcile(7).operation).toBeUndefined();- expect(routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: routes.snapshot().revision,- connectionId: "failed_direct",- })).toBe(true);- expect(routes.snapshot().factVersion).toBe(factVersion);- expect(routes.reconcile(8).operation).toBeUndefined();-- addViewer(routes, B, 0, 9);- expect(routes.reconcile(9).operation?.childPeerId).toBe(B);- while (routes.snapshot().operation) skipCandidate(routes, 10);- expect(routes.reconcile(11).operation).toBeUndefined();- });-- it.each([1, 2] as const)(- "requires one overlap slot for an SFU-to-Host transition at C=%i",- (capacity) => {- const routes = controller(capacity, { sfuEnabled: true });- addViewer(routes, A, 0);- if (capacity === 2) {- addViewer(routes, E, 0);- routes.hydrateEdge(E, peerEdge(HOST, "e_direct"));- }- routes.hydrateHostPublication("publication_1", "publication_resource_1");- routes.hydrateEdge(A, {- kind: "sfu",- publicationGeneration: "publication_1",- transport: "sfu",- connectionId: "a_sfu",- usable: true,- physicalActive: true,- resource: "a_subscription",- });- routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- routeRevision: 0,- connectionId: "a_sfu",- });- const operation = routes.reconcile(0).operation!;- expect(operation.candidates[0]).toMatchObject({- tuple: { kind: "peer", parentPeerId: HOST, transport: "direct" },- endpointTransition: { kind: "overlap", producerPeerId: HOST },- });- expect(() => beginCandidate(routes, {- nowMs: 1,- connectionId: "a_host_direct",- reservation: { kind: "direct" },- })).toThrow("endpoint overlap reservation");- },- );-- it("uses one bounded gap instead of a fourth Host copy at C=3", () => {- const routes = controller(3, { sfuEnabled: true });- addViewer(routes, A, 0);- for (const peerId of [E, F]) {- addViewer(routes, peerId, 0);- routes.hydrateEdge(peerId, peerEdge(HOST, `${peerId}_direct`));- }- routes.hydrateHostPublication("publication_1", "publication_resource_1");- routes.hydrateEdge(A, {- kind: "sfu",- publicationGeneration: "publication_1",- transport: "sfu",- connectionId: "a_sfu",- usable: true,- physicalActive: true,- resource: "a_subscription",- });- routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- routeRevision: 0,- connectionId: "a_sfu",- });- const operation = routes.reconcile(10).operation!;- const deadline = operation.deadlineAtMs;- expect(operation.candidates[0]).toMatchObject({- tuple: { kind: "peer", parentPeerId: HOST, transport: "direct" },- endpointTransition: {- kind: "bounded-gap",- producerPeerId: HOST,- retire: { kind: "publication", generation: "publication_1" },- },- });- const gap = routes.retireCurrentCandidateProducer(cursorGuard(operation), 11);- expect(gap).toMatchObject({ accepted: true });- expect(gap.released).toEqual(["a_subscription", "publication_resource_1"]);- expect(gap.operation).toMatchObject({- deadlineAtMs: deadline,- candidates: [{ endpointTransition: { kind: "none", producerPeerId: HOST } }],- });- const prepared = beginCandidate(routes, {- nowMs: 12,- connectionId: "a_host_direct",- reservation: { kind: "direct" },- }).operation!;- expect(routes.candidateReady({- childPeerId: A,- childSessionId: `${A}_session`,- revision: prepared.current!.revision,- connectionId: "a_host_direct",- }, 13).accepted).toBe(true);- expect(routes.snapshot().hostPublication).toBeNull();- });-- it("does not reopen consumed none transitions after capacity reduction", () => {- const routes = controller(2, { sfuEnabled: true });- addViewer(routes, A, 0);- routes.hydrateHostPublication("publication", "publication_resource");- routes.hydrateEdge(A, {- kind: "sfu",- publicationGeneration: "publication",- transport: "sfu",- connectionId: "a_from_sfu",- usable: true,- physicalActive: true,- resource: "a_subscription",- });- expect(routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- routeRevision: 0,- connectionId: "a_from_sfu",- })).toBe(true);- const operation = routes.reconcile(0).operation!;- expect(operation.candidates[0]).toMatchObject({- tuple: { kind: "peer", parentPeerId: HOST, transport: "direct" },- endpointTransition: { kind: "none", producerPeerId: HOST },- });-- expect(routes.setEffectiveCapacity(HOST, "host_session", 1)).toBe(true);- expect(routes.operationExpired(operation.deadlineAtMs).failedPeerIds).toEqual([- A,- ]);- expect(routes.reconcile(operation.deadlineAtMs + 1).operation).toBeUndefined();- });-- it("does not unblock an exhausted demand for an unrelated join", () => {- const routes = controller(1);- addViewer(routes, B, 0);- routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));- addViewer(routes, A, 0, 0);- expect(routes.reconcile(0).failedPeerIds).toEqual([A]);-- expect(routes.setEffectiveCapacity(A, `${A}_session`, 1)).toBe(true);- expect(routes.reconcile(1).operation).toBeUndefined();-- addViewer(routes, C, 0, 2);- expect(routes.reconcile(2).failedPeerIds).toEqual([C]);- expect(routes.snapshot().operation).toBeUndefined();-- expect(routes.setEffectiveCapacity(B, `${B}_session`, 1)).toBe(true);- expect(routes.reconcile(3).operation).toMatchObject({- childPeerId: A,- candidates: [- {- tuple: { kind: "peer", parentPeerId: B, transport: "direct" },- },- ],- });- });-- it("does not revive an exact failed Host tuple when a new parent joins", () => {- const routes = controller(1);- addViewer(routes, A, 0);- routes.hydrateEdge(A, peerEdge(HOST, "failed_direct"));- expect(- routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: 0,- connectionId: "failed_direct",- }),- ).toBe(true);- expect(routes.reconcile(0).operation).toBeUndefined();-- addViewer(routes, B, 1, 1);- expect(routes.reconcile(2).operation).toMatchObject({- childPeerId: B,- reason: "join",- });- commitCurrent(routes, 2, "b_from_host");- const retry = routes.reconcile(4).operation!;- expect(retry).toMatchObject({- childPeerId: A,- candidates: [- {- tuple: { kind: "peer", parentPeerId: B, transport: "direct" },- },- ],- });- expect(- retry.candidates.some(- (candidate) =>- candidate.tuple.kind === "peer" &&- candidate.tuple.parentPeerId === HOST,- ),- ).toBe(false);- });-- it("does not unblock an exhausted Viewer when its candidate set shrinks", () => {- const routes = controller(1);- addViewer(routes, A, 0);- routes.hydrateEdge(A, peerEdge(HOST, "failed_host"));- expect(routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: 0,- connectionId: "failed_host",- })).toBe(true);- expect(routes.reconcile(0).operation).toBeUndefined();-- addViewer(routes, B, 1, 1);- routes.reconcile(1);- commitCurrent(routes, 2, "b_from_host");- const candidate = routes.reconcile(3).operation!;- const attempt = beginCandidate(routes, {- nowMs: 4,- connectionId: "a_from_b",- reservation: { kind: "direct" },- }).operation!;- expect(routes.candidateFailed({- childPeerId: A,- childSessionId: `${A}_session`,- revision: attempt.current!.revision,- connectionId: "a_from_b",- }, 5).failedPeerIds).toEqual([A]);- expect(candidate.candidates).toHaveLength(1);-- expect(routes.disconnectSession(B, `${B}_session`)).toBe(true);- expect(routes.reconcile(6).operation).toBeUndefined();- });-- it("treats a replacement child session as a new exact opportunity", () => {- const routes = controller(1);- addViewer(routes, A, 0);- routes.hydrateEdge(A, peerEdge(HOST, "failed_host"));- expect(routes.invalidateEdge({- childPeerId: A,- childSessionId: `${A}_session`,- parentSessionId: "host_session",- routeRevision: 0,- connectionId: "failed_host",- })).toBe(true);- expect(routes.reconcile(0).operation).toBeUndefined();-- routes.upsertParticipant({- peerId: A,- role: "viewer",- sessionId: "replacement_session",- effectiveDownstreamCapacity: 0,- });- expect(routes.reconcile(1).operation).toMatchObject({- childPeerId: A,- childSessionId: "replacement_session",- candidates: [- {- tuple: { kind: "peer", parentPeerId: HOST, transport: "direct" },- },- ],- });- });-- it("does not retry a failed bootstrap carrier when another carrier leaves", () => {- const routes = controller(2, { sfuEnabled: true });- for (const [peerId, connectionId] of [- [B, "b_from_host"],- [C, "c_from_host"],- ] as const) {- addViewer(routes, peerId, 1);- routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));- }- addViewer(routes, A, 0, 0);- const acquisition = routes.reconcile(0).operation!;- beginCandidate(routes, {- nowMs: 1,- connectionId: "a_head_start",- reservation: { kind: "direct" },- });- routes.operationExpired(acquisition.wakeAtMs);-- const bootstrap = routes.reconcile(acquisition.wakeAtMs + 1).operation!;- expect(bootstrap.reason).toBe("sfu-bootstrap");- const failedCarrier = bootstrap.childPeerId;- const otherCarrier = failedCarrier === B ? C : B;- const attempt = beginCandidate(routes, {- nowMs: acquisition.wakeAtMs + 2,- connectionId: "failed_bootstrap",- publicationGeneration: "failed_publication",- publicationConnectionId: "failed_publication_connection",- reservation: {- kind: "sfu-create",- edge: "failed_subscription",- publication: "failed_publication_resource",- overlap: "failed_overlap",- },- }).operation!;- expect(routes.candidateFailed({- childPeerId: failedCarrier,- childSessionId: `${failedCarrier}_session`,- revision: attempt.current!.revision,- connectionId: "failed_bootstrap",- }, acquisition.wakeAtMs + 3).accepted).toBe(true);-- expect(- routes.disconnectSession(otherCarrier, `${otherCarrier}_session`),- ).toBe(true);- const next = routes.reconcile(acquisition.wakeAtMs + 4).operation;- expect(next).not.toMatchObject({- reason: "sfu-bootstrap",- childPeerId: failedCarrier,- });- });-- it("does not bootstrap a new SFU generation after the last reuse opportunity expires", () => {- const { routes, nowMs } = retireLastSfuPublicationAfterReuseDeadline();-- const reconciled = routes.reconcile(nowMs);- expect(reconciled.operation).toBeUndefined();- expect(reconciled.failedPeerIds).toEqual([]);- });-- it.each(["child-session", "host-session", "external-resource"] as const)(- "reopens the exhausted SFU opportunity for a new %s authority",- (authority) => {- const { routes, nowMs } = retireLastSfuPublicationAfterReuseDeadline();- if (authority === "child-session") {- routes.upsertParticipant({- peerId: A,- role: "viewer",- sessionId: "replacement_child_session",- effectiveDownstreamCapacity: 0,- });- } else if (authority === "host-session") {- routes.upsertParticipant({- peerId: HOST,- role: "host",- sessionId: "replacement_host_session",- effectiveDownstreamCapacity: 2,- });- } else {- routes.touchExternalFacts();- }-- expect(routes.reconcile(nowMs).operation).toMatchObject({- demandPeerId: A,- reason: "sfu-bootstrap",- candidates: [- {- tuple: { kind: "sfu", publication: "create" },- },- ],- });- },- );-- it("consumes the canonical SFU opportunity when an active edge fails", () => {- const routes = invalidateActiveSfuEdge();-- const operation = routes.reconcile(0).operation;- expect(- operation?.candidates.some((candidate) => candidate.tuple.kind === "sfu"),- ).toBe(false);- });-- it.each(["child-session", "host-session", "external-resource"] as const)(- "reopens an active-edge SFU opportunity for a new %s authority",- (authority) => {- const routes = invalidateActiveSfuEdge();- if (authority === "child-session") {- routes.upsertParticipant({- peerId: A,- role: "viewer",- sessionId: "active_edge_child_replacement",- effectiveDownstreamCapacity: 0,- });- } else if (authority === "host-session") {- routes.upsertParticipant({- peerId: HOST,- role: "host",- sessionId: "active_edge_host_replacement",- effectiveDownstreamCapacity: 1,- });- } else {- routes.touchExternalFacts();- }-- expect(- routes- .reconcile(0)- .operation?.candidates.some(- (candidate) =>- candidate.tuple.kind === "sfu" &&- candidate.tuple.publication === "reuse",- ),- ).toBe(true);- },- );-- it("does not turn a failed same-rank SFU replace into a create retry", () => {- const routes = controller(2, { sfuEnabled: true });- routes.hydrateHostPublication(- "failed_publication",- "failed_publication_resource",- );- expect(- routes.invalidateHostPublication({- hostSessionId: "host_session",- routeRevision: routes.snapshot().revision,- generation: "failed_publication",- connectionId: "publication:failed_publication",- }),- ).toBe(true);- addViewer(routes, A, 0);- const operation = routes.reconcile(0).operation!;- expect(operation.candidates[0]?.tuple).toMatchObject({ kind: "peer" });- skipCandidate(routes, 1);- expect(routes.snapshot().operation?.candidates[1]).toMatchObject({- tuple: { kind: "sfu", publication: "replace" },- endpointTransition: { kind: "none", producerPeerId: HOST },- });- const replace = beginCandidate(routes, {- nowMs: 2,- connectionId: "failed_replace",- publicationGeneration: "replacement_publication",- publicationConnectionId: "replacement_ingress",- reservation: {- kind: "sfu-create",- edge: "replacement_subscription",- publication: "replacement_publication_resource",- },- }).operation!;- expect(- routes.candidateFailed(- {- childPeerId: A,- childSessionId: `${A}_session`,- revision: replace.current!.revision,- connectionId: "failed_replace",- },- 3,- ).failedPeerIds,- ).toEqual([A]);-- addViewer(routes, B, 0);- expect(routes.confirmDeparture(B)).toBe(true);- const reconciled = routes.reconcile(4);- expect(routes.snapshot().hostPublication).toBeNull();- expect(reconciled.operation).toBeUndefined();- expect(reconciled.failedPeerIds).toEqual([]);- });-- it("reopens only SFU opportunities for a new external fact", () => {- const routes = controller(1, { sfuEnabled: true });- addViewer(routes, A, 0, 0);- routes.reconcile(0);- const directAttempt = beginCandidate(routes, {- nowMs: 1,- connectionId: "failed_direct",- reservation: { kind: "direct" },- }).operation!;- expect(routes.candidateFailed({- childPeerId: A,- childSessionId: `${A}_session`,- revision: directAttempt.current!.revision,- connectionId: "failed_direct",- }, 2).accepted).toBe(true);- const sfuAttempt = beginCandidate(routes, {- nowMs: 3,- connectionId: "failed_sfu",- publicationGeneration: "failed_publication",- publicationConnectionId: "failed_publication_connection",- reservation: {- kind: "sfu-create",- edge: "failed_subscription",- publication: "failed_publication_resource",- },- }).operation!;- expect(routes.candidateFailed({- childPeerId: A,- childSessionId: `${A}_session`,- revision: sfuAttempt.current!.revision,- connectionId: "failed_sfu",- }, 4).accepted).toBe(true);- expect(routes.snapshot().operation).toBeUndefined();- expect(routes.reconcile(5).operation).toBeUndefined();-- routes.touchExternalFacts();- const retried = routes.reconcile(6).operation!;- expect(retried.candidates).toEqual([- {- tuple: { kind: "sfu", publication: "create" },- endpointTransition: { kind: "none", producerPeerId: HOST },- },- ]);- expect(- retried.candidates.some(- (candidate) => candidate.tuple.kind === "peer",- ),- ).toBe(false);- });-- it("fails all waiting demands without cutting capacity-three Host children", () => {- const routes = controller(3, { sfuEnabled: true });- for (const [peerId, connectionId] of [- [A, "a_direct"],- [B, "b_direct"],- [C, "c_direct"],- ] as const) {- addViewer(routes, peerId, 0);- routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));- }- addViewer(routes, D, 0);- addViewer(routes, E, 0);- const reconciled = routes.reconcile(0);- expect(reconciled.operation).toBeUndefined();- expect(reconciled.failedPeerIds).toEqual([D, E]);- for (const [peerId, connectionId] of [- [A, "a_direct"],- [B, "b_direct"],- [C, "c_direct"],- ] as const) {- expect(routes.snapshot().upstreamByViewer.get(peerId)).toMatchObject({- connectionId,- usable: true,- physicalActive: true,- });- }- });-- it("does not promote when synchronous admission commit fails", () => {- const routes = controller(1);- addViewer(routes, A, 0);- const operation = routes.reconcile(0).operation!;- const prepared = beginCandidate(routes, {- nowMs: 1,- connectionId: "candidate_connection",- reservation: { kind: "direct" },- }).operation!;- const settled = routes.candidateReady(- {- childPeerId: operation.childPeerId,- childSessionId: operation.childSessionId,- revision: prepared.current!.revision,- connectionId: "candidate_connection",- },- 2,- () => false,- );- expect(settled.accepted).toBe(false);- expect(settled.activeRevision).toBeGreaterThan(prepared.current!.revision);- expect(routes.snapshot().upstreamByViewer.has(A)).toBe(false);- });-});--describe("bounded NAT candidate acquisition", () => {- function preparePeer(routes: RoomRouteController<string>, nowMs: number, id: string) {- const operation = routes.reconcile(nowMs).operation!;- const prepared = beginCandidate(routes, {- nowMs,- connectionId: id,- reservation: { kind: "direct" },- }).operation!;- const guard: CandidateGuard = {- childPeerId: prepared.childPeerId,- childSessionId: prepared.childSessionId,- revision: prepared.current!.revision,- connectionId: id,- };- return { operation, prepared, guard };- }-- it.each(["failed", "timeout"] as const)("runs three real generations on %s, then exhausts until a new session", (failure) => {- const routes = controller(2, {- natPredictionEnabled: true,- operationTimeoutMs: 20_000,- });- addViewer(routes, A, 0);- let nowMs = 0;- let previous: CandidateGuard | undefined;- for (let attempt = 1; attempt <= 3; attempt += 1) {- const { operation, prepared, guard } = preparePeer(routes, nowMs, `nat_${attempt}`);- expect(prepared.current?.connectionAttempt).toEqual({ current: attempt, total: 3 });- expect(operation.deadlineAtMs - nowMs).toBe(20_000);- expect(prepared.wakeAtMs).toBe(operation.deadlineAtMs);- if (previous) expect(routes.candidateFailed(previous, nowMs).accepted).toBe(false);- expect(routes.snapshot().operation?.current?.connectionId).toBe(`nat_${attempt}`);- nowMs = failure === "timeout" ? operation.deadlineAtMs : nowMs + 1;- const result = failure === "timeout"- ? routes.operationExpired(nowMs)- : routes.candidateFailed(guard, nowMs);- expect(result.failedPeerIds).toEqual(attempt === 3 ? [A] : []);- expect(routes.candidateFailed(guard, nowMs).accepted).toBe(false);- previous = guard;- nowMs += 1;- }- expect(routes.reconcile(nowMs).operation).toBeUndefined();- routes.upsertParticipant({- peerId: A, role: "viewer", sessionId: "replacement_session",- effectiveDownstreamCapacity: 0,- }, nowMs);- const { prepared, guard } = preparePeer(routes, nowMs + 1, "new_session");- expect(prepared.current?.connectionAttempt?.current).toBe(1);- expect(routes.candidateReady(guard, nowMs + 2).committed).toBe(true);- });-- it("gives waiting viewers their first opportunity before another viewer retries", () => {- const routes = controller(2, { natPredictionEnabled: true });- addViewer(routes, A, 0);- addViewer(routes, B, 0);- for (const [index, childPeerId] of [A, B, A, B, A, B].entries()) {- const { prepared, guard } = preparePeer(routes, index * 2, `fair_${index}`);- expect(prepared.childPeerId).toBe(childPeerId);- expect(prepared.current?.connectionAttempt?.current).toBe(Math.floor(index / 2) + 1);- routes.candidateFailed(guard, index * 2 + 1);- }- expect(routes.reconcile(20).operation).toBeUndefined();- });-- it("tries a newly usable parent before spending another attempt on an old parent", () => {- const routes = controller(2, { natPredictionEnabled: true });- addViewer(routes, B, 2);- routes.hydrateEdge(B, peerEdge(HOST, "existing_b"));- addViewer(routes, A, 0);- const first = preparePeer(routes, 0, "first_host");- expect(first.prepared.current?.tuple).toMatchObject({ parentPeerId: HOST });- routes.candidateFailed(first.guard, 1);- const second = preparePeer(routes, 2, "first_b");- expect(second.prepared.current?.tuple).toMatchObject({ parentPeerId: B });- routes.candidateFailed(second.guard, 3);- addViewer(routes, C, 2, 4);- routes.hydrateEdge(C, peerEdge(HOST, "existing_c"));- const third = preparePeer(routes, 5, "first_c");- expect(third.prepared.current?.tuple).toMatchObject({ parentPeerId: C });- expect(third.prepared.current?.connectionAttempt?.current).toBe(1);- });-- it("keeps SFU's foreground timing and shares the attempt budget with round-robin direct continuations", () => {- const routes = controller(2, {- natPredictionEnabled: true, sfuEnabled: true, operationTimeoutMs: 20_000,- });- let nowMs = 0;- for (const childPeerId of [A, B]) {- addViewer(routes, childPeerId, 0, nowMs);- const direct = preparePeer(routes, nowMs, `${childPeerId}_first`);- expect(direct.prepared.wakeAtMs).toBe(nowMs + 5_000);- nowMs += 5_000;- expect(routes.operationExpired(nowMs).failedPeerIds).toEqual([]);- const sfu = beginCandidate(routes, {- nowMs,- connectionId: `${childPeerId}_sfu`,- publicationGeneration: "sfu_generation",- publicationConnectionId: "sfu_publisher",- reservation: childPeerId === A- ? { kind: "sfu-create", edge: "subscription_a", publication: "publication" }- : { kind: "sfu-reuse", edge: "subscription_b" },- }).operation!;- expect(sfu.current?.connectionAttempt).toBeUndefined();- routes.candidateReady({- childPeerId, childSessionId: sfu.childSessionId,- revision: sfu.current!.revision, connectionId: `${childPeerId}_sfu`,- }, ++nowMs);- nowMs += 1;- }- for (const [index, childPeerId] of [A, B, A, B].entries()) {- const retry = preparePeer(routes, nowMs, `background_${index}`);- expect(retry.prepared).toMatchObject({- childPeerId, reason: "direct-convergence",- current: { connectionAttempt: { current: Math.floor(index / 2) + 2, total: 3 } },- });- expect(retry.prepared.wakeAtMs - nowMs).toBe(20_000);- expect(routes.candidateFailed(retry.guard, ++nowMs).failedPeerIds).toEqual([]);- expect(routes.snapshot().upstreamByViewer.get(childPeerId)).toMatchObject({ kind: "sfu", usable: true });- nowMs += 1;- }- expect(routes.reconcile(nowMs).operation).toBeUndefined();- });-- it("does not retry without NAT policy or when no candidate was created", () => {- const ordinary = controller();- addViewer(ordinary, A, 0);- const first = preparePeer(ordinary, 0, "ordinary");- expect(first.prepared.current?.connectionAttempt).toBeUndefined();- expect(ordinary.candidateFailed(first.guard, 1).failedPeerIds).toEqual([A]);- expect(ordinary.reconcile(2).operation).toBeUndefined();-- const routes = controller(2, { natPredictionEnabled: true });- addViewer(routes, A, 0);- const operation = routes.reconcile(0).operation!;- routes.skipCurrentCandidate(cursorGuard(operation), 1, "candidate-failed");- expect(routes.reconcile(2).operation).toBeUndefined();- });-});diff --git a/tests/room-store.test.ts b/tests/room-store.test.tsdeleted file mode 100644index 7d9a0f02..00000000--- a/tests/room-store.test.ts+++ /dev/null@@ -1,617 +0,0 @@-import { describe, expect, it } from "vitest";--import {- ROOM_CAPACITY,- RoomStore,- RoomStoreError,-} from "../src/server/room-store.ts";--interface MutableClock {- nowMs: number;-}--function store(options: Partial<ConstructorParameters<typeof RoomStore>[0]> = {}) {- const clock: MutableClock = { nowMs: 0 };- return {- clock,- store: new RoomStore({- leaseMs: 1_000,- maxRooms: 2,- maxViewersPerRoom: 2,- now: () => clock.nowMs,- ...options,- }),- };-}--function hostInput(roomId: string, hostToken: string, sessionId = "host-session") {- return {- roomId,- role: "host" as const,- token: hostToken,- clientId: "host-client",- sessionId,- };-}--function viewerInput(- roomId: string,- sessionId: string,- viewerGrant?: string,- clientId = `viewer-${sessionId}`,-) {- return {- roomId,- role: "viewer" as const,- ...(viewerGrant ? { viewerGrant } : {}),- clientId,- sessionId,- };-}--function expectRoomError(run: () => unknown, code: string) {- expect(run).toThrow(new RoomStoreError(code as never));-}--async function withSaturatedPasswordGate<Result>(- roomStore: RoomStore,- operation: () => Promise<Result>,-): Promise<Result> {- const attempts = Array.from({ length: 18 }, (_, index) =>- roomStore.connectViewerWithPassword(- {- roomId: "9999",- password: "gate-password",- clientId: `gate-client-${index}`,- sessionId: `gate-session-${index}`,- },- () => index < 2,- ),- );- try {- return await operation();- } finally {- await Promise.allSettled(attempts);- }-}--describe("RoomStore", () => {- it("allocates every free four-digit room code and recycles releases", async () => {- const { store: roomStore } = store({- maxRooms: ROOM_CAPACITY,- random: (size) => Buffer.alloc(size),- });-- const rooms = [];- for (let index = 0; index < ROOM_CAPACITY; index += 1) {- rooms.push(await roomStore.createRoom());- }- expect(new Set(rooms.map((room) => room.roomId)).size).toBe(ROOM_CAPACITY);- expect(rooms.every((room) => /^[1-9]\d{3}$/.test(room.roomId))).toBe(true);- await expect(roomStore.createRoom()).rejects.toEqual(- new RoomStoreError("ROOM_LIMIT"),- );-- const released = rooms[4_321]!.roomId;- expect(roomStore.abandonRoom(released)?.roomId).toBe(released);- expect((await roomStore.createRoom()).roomId).toBe(released);- });-- it("uses a free preferred code and falls back when it is occupied", async () => {- const { store: roomStore } = store({ maxRooms: 3 });-- const preferred = await roomStore.createRoom("open", null, "4321");- const fallback = await roomStore.createRoom("open", null, "4321");-- expect(preferred.roomId).toBe("4321");- expect(fallback.roomId).not.toBe("4321");- expect(roomStore.abandonRoom("4321")?.roomId).toBe("4321");- expect((await roomStore.createRoom("open", null, "4321")).roomId).toBe(- "4321",- );- });-- it("abandons every current room as one authority shutdown", async () => {- const { store: roomStore } = store({ maxRooms: 3 });- const first = await roomStore.createRoom();- const second = await roomStore.createRoom();- roomStore.connectParticipant(- hostInput(first.roomId, first.hostToken),- );-- expect(roomStore.abandonAllRooms()).toEqual(expect.arrayContaining([- { roomId: first.roomId, sessionIds: ["host-session"] },- { roomId: second.roomId, sessionIds: [] },- ]));- expect(roomStore.size).toBe(0);- });-- it("atomically replaces a room with different authority", async () => {- const { store: roomStore } = store();- const original = await roomStore.createRoom(- "private",- "old-password",- "4321",- );- const host = roomStore.connectParticipant(- hostInput(original.roomId, original.hostToken),- );- roomStore.connectParticipant(- viewerInput(- original.roomId,- "viewer-session",- original.viewerGrant!,- ),- );-- await expect(- roomStore.replaceRoom(- original.roomId,- original.hostToken,- "private",- "bad password",- ),- ).rejects.toEqual(new RoomStoreError("INVALID_TOKEN"));- expect(roomStore.getConnectedHost(original.roomId)?.peerId).toBe(- host.peerId,- );-- const replacement = await roomStore.replaceRoom(- original.roomId,- original.hostToken,- "private",- "new-password",- );-- expect(replacement.created.roomId).not.toBe(original.roomId);- expect(replacement.closed).toEqual({- roomId: original.roomId,- sessionIds: expect.arrayContaining(["host-session", "viewer-session"]),- });- expectRoomError(- () =>- roomStore.connectParticipant(- hostInput(original.roomId, original.hostToken),- ),- "INVALID_TOKEN",- );- expect(- roomStore.connectParticipant(- viewerInput(- replacement.created.roomId,- "new-viewer-session",- replacement.created.viewerGrant!,- ),- ).roomId,- ).toBe(replacement.created.roomId);- await expect(- roomStore.connectViewerWithPassword({- roomId: replacement.created.roomId,- password: "new-password",- clientId: "password-viewer",- sessionId: "password-session",- }),- ).resolves.toMatchObject({ roomId: replacement.created.roomId });- });-- it("rejects room limits beyond the four-digit code space", () => {- expect(() => store({ maxRooms: ROOM_CAPACITY + 1 }).store).toThrow(- `Room limit must be an integer between 1 and ${ROOM_CAPACITY}`,- );- });-- it("keeps active sharing alive and renews only with the exact Host token", async () => {- const { clock, store: roomStore } = store({ leaseMs: 1_000 });- const room = await roomStore.createRoom();- const host = roomStore.connectParticipant(- hostInput(room.roomId, room.hostToken),- );- clock.nowMs = 2_000;- expect(roomStore.expireRooms()).toEqual([]);-- roomStore.disconnectParticipant(- room.roomId,- host.peerId,- "host-session",- );- clock.nowMs = 2_500;- expect(roomStore.expireRooms()).toEqual([]);-- expectRoomError(- () => roomStore.connectParticipant(hostInput(room.roomId, "wrong-token")),- "INVALID_TOKEN",- );- const resumed = roomStore.connectParticipant(- hostInput(room.roomId, room.hostToken, "host-session-2"),- );- expect(resumed.expiresAt).toBeNull();-- roomStore.disconnectParticipant(- room.roomId,- resumed.peerId,- "host-session-2",- );- roomStore.connectParticipant(- viewerInput(room.roomId, "viewer-session", room.viewerGrant!),- );- clock.nowMs = 3_501;- expect(roomStore.expireRooms()).toHaveLength(1);- expectRoomError(- () =>- roomStore.connectParticipant(- hostInput(room.roomId, room.hostToken, "late-host"),- ),- "INVALID_TOKEN",- );- });-- it("manages dormant access with the exact Host token without renewing", async () => {- const { clock, store: roomStore } = store({ leaseMs: 1_000 });- const room = await roomStore.createRoom("open");- const otherRoom = await roomStore.createRoom("open");- clock.nowMs = 900;-- await expect(- roomStore.setViewerPassword(room.roomId, "room-password", "wrong-token"),- ).rejects.toEqual(new RoomStoreError("INVALID_TOKEN"));- expectRoomError(- () =>- roomStore.setCodeEntryPolicy(- room.roomId,- "private",- otherRoom.hostToken,- ),- "INVALID_TOKEN",- );-- expect(- roomStore.setCodeEntryPolicy(room.roomId, "private", room.hostToken),- ).toMatchObject({- codeEntryPolicy: "private",- viewerPasswordEnabled: false,- });- expect(- await roomStore.setViewerPassword(- room.roomId,- "room-password",- room.hostToken,- ),- ).toBe(true);- expect(- await roomStore.setViewerPassword(room.roomId, null, room.hostToken),- ).toBe(false);- expect(- roomStore.setViewerGrant(room.roomId, "rotate", room.hostToken)- .viewerGrant,- ).toMatch(/^[A-Za-z0-9_-]{21}[AQgw]$/);- expect(roomStore.getConnectedHost(room.roomId)).toBeUndefined();-- clock.nowMs = 1_001;- expect(roomStore.expireRooms().map((expired) => expired.roomId)).toContain(- room.roomId,- );- });-- it("keeps Viewer grants independent from code-entry policy", async () => {- const { store: roomStore } = store({ maxRooms: 3 });- const room = await roomStore.createRoom("private");-- expectRoomError(- () => roomStore.connectParticipant(viewerInput(room.roomId, "code-only")),- "INVALID_TOKEN",- );- await expect(- roomStore.connectViewerWithPassword({- roomId: room.roomId,- password: "any-password",- clientId: "private-code-viewer",- sessionId: "private-code-session",- }),- ).rejects.toEqual(new RoomStoreError("INVALID_TOKEN"));- expect(- roomStore.connectParticipant(- viewerInput(room.roomId, "granted", room.viewerGrant!),- ).role,- ).toBe("viewer");- });-- it("keeps the exact Viewer grant valid for the room incarnation", async () => {- const { clock, store: roomStore } = store({ leaseMs: 1_000 });- const room = await roomStore.createRoom("open");- roomStore.connectParticipant(hostInput(room.roomId, room.hostToken));-- expect(room.viewerGrant).toMatch(/^[A-Za-z0-9_-]{21}[AQgw]$/);- clock.nowMs = 8 * 24 * 60 * 60 * 1_000;- expect(- roomStore.connectParticipant(- viewerInput(room.roomId, "room-lived-grant", room.viewerGrant!),- ).role,- ).toBe("viewer");- });-- it("supports open and password-enabled private code entry", async () => {- const { store: roomStore } = store({ maxRooms: 3 });- const open = await roomStore.createRoom("open");- expect(- roomStore.connectParticipant(viewerInput(open.roomId, "open")).role,- ).toBe("viewer");-- const password = await roomStore.createRoom("private", "room-password");- expectRoomError(- () => roomStore.connectParticipant(viewerInput(password.roomId, "wrong")),- "INVALID_TOKEN",- );- expect(- await roomStore.connectViewerWithPassword({- roomId: password.roomId,- password: "room-password",- clientId: "password-viewer",- sessionId: "password-session",- }),- ).toMatchObject({ role: "viewer" });- });-- it("does not create a passwordless room when the password gate is busy", async () => {- const { store: roomStore } = store({ maxRooms: 1 });-- await expect(- withSaturatedPasswordGate(roomStore, () =>- roomStore.createRoom("private", "room-password", "4321"),- ),- ).rejects.toEqual(new RoomStoreError("ROOM_BUSY"));- expect(roomStore.size).toBe(0);- expect((await roomStore.createRoom("private", null, "4321")).roomId).toBe(- "4321",- );- });-- it("keeps password-gate saturation distinct from invalid credentials", async () => {- const { store: roomStore } = store();- const room = await roomStore.createRoom("private", "room-password");-- await expect(- withSaturatedPasswordGate(roomStore, () =>- roomStore.connectViewerWithPassword({- roomId: room.roomId,- password: "room-password",- clientId: "busy-password-client",- sessionId: "busy-password-session",- }),- ),- ).rejects.toEqual(new RoomStoreError("ROOM_BUSY"));- });-- it("keeps room replacement and password updates unchanged when busy", async () => {- const { store: roomStore } = store({- maxRooms: 3,- });- const room = await roomStore.createRoom(- "private",- "old-password",- "4321",- );-- await expect(- withSaturatedPasswordGate(roomStore, () =>- roomStore.replaceRoom(- room.roomId,- room.hostToken,- "private",- "replacement-password",- ),- ),- ).rejects.toEqual(new RoomStoreError("ROOM_BUSY"));- expect(roomStore.size).toBe(1);- await expect(- roomStore.connectViewerWithPassword({- roomId: room.roomId,- password: "old-password",- clientId: "after-replacement-client",- sessionId: "after-replacement-session",- }),- ).resolves.toMatchObject({ roomId: room.roomId });-- await expect(- withSaturatedPasswordGate(roomStore, () =>- roomStore.setViewerPassword(- room.roomId,- "updated-password",- room.hostToken,- ),- ),- ).rejects.toEqual(new RoomStoreError("ROOM_BUSY"));- await expect(- roomStore.connectViewerWithPassword({- roomId: room.roomId,- password: "old-password",- clientId: "after-update-client",- sessionId: "after-update-session",- }),- ).resolves.toMatchObject({ roomId: room.roomId });- });-- it("bounds password derivations and uses the same path for unknown rooms", async () => {- const { store: roomStore } = store();- let mayStartCalls = 0;- const attempts = Array.from({ length: 40 }, (_, index) =>- roomStore.connectViewerWithPassword(- {- roomId: "9999",- password: "bounded-password",- clientId: `bounded-client-${index}`,- sessionId: `bounded-session-${index}`,- },- () => {- mayStartCalls += 1;- return index < 2;- },- ),- );-- const results = await Promise.allSettled(attempts);- expect(mayStartCalls).toBe(18);- expect(- results.every(- (result) =>- result.status === "rejected" &&- result.reason instanceof RoomStoreError,- ),- ).toBe(true);- expect(- results.filter(- (result) =>- result.status === "rejected" &&- result.reason.code === "ROOM_NOT_FOUND",- ),- ).toHaveLength(2);- expect(- results.filter(- (result) =>- result.status === "rejected" &&- result.reason.code === "INVALID_TOKEN",- ),- ).toHaveLength(16);- expect(- results.filter(- (result) =>- result.status === "rejected" &&- result.reason.code === "ROOM_BUSY",- ),- ).toHaveLength(22);- });-- it("rotates and revokes Viewer grants without changing code entry", async () => {- const { store: roomStore } = store();- const room = await roomStore.createRoom("open");- roomStore.connectParticipant(hostInput(room.roomId, room.hostToken));-- const rotated = roomStore.setViewerGrant(- room.roomId,- "rotate",- room.hostToken,- );- expectRoomError(- () =>- roomStore.connectParticipant(- viewerInput(room.roomId, "old-grant", room.viewerGrant!),- ),- "INVALID_TOKEN",- );- const grantedViewer = roomStore.connectParticipant(- viewerInput(room.roomId, "new-grant", rotated.viewerGrant!),- );- const codeViewer = roomStore.connectParticipant(- viewerInput(room.roomId, "still-open"),- );-- const revoked = roomStore.setViewerGrant(- room.roomId,- "revoke",- room.hostToken,- );- expect(revoked.viewerGrant).toBeNull();- expect(revoked.revokedViewers.map((viewer) => viewer.peerId)).toEqual([- grantedViewer.peerId,- ]);- expect(codeViewer.role).toBe("viewer");- expect(- roomStore.getConnectedViewer(room.roomId, codeViewer.peerId),- ).toMatchObject({ sessionId: "still-open" });- expectRoomError(- () =>- roomStore.connectParticipant(- viewerInput(room.roomId, "revoked", rotated.viewerGrant!),- ),- "INVALID_TOKEN",- );- });-- it("keeps the old grant and viewers when rotation cannot create a generation", async () => {- let failedRandomCall: number | null = null;- let randomCalls = 0;- let randomValue = 0;- const { store: roomStore } = store({- random: (size) => {- randomCalls += 1;- return Buffer.alloc(- randomCalls === failedRandomCall ? size - 1 : size,- ++randomValue,- );- },- });- const room = await roomStore.createRoom("open");- roomStore.connectParticipant(hostInput(room.roomId, room.hostToken));- const viewer = roomStore.connectParticipant(- viewerInput(room.roomId, "existing", room.viewerGrant!),- );-- failedRandomCall = randomCalls + 2;- expect(() =>- roomStore.setViewerGrant(room.roomId, "rotate", room.hostToken),- ).toThrow("Authorization generation random source must return 16 bytes");- failedRandomCall = null;-- expect(- roomStore.getConnectedViewer(room.roomId, viewer.peerId),- ).toMatchObject({ sessionId: "existing" });- expect(- roomStore.connectParticipant(- viewerInput(room.roomId, "old-grant-still-valid", room.viewerGrant!),- ).role,- ).toBe("viewer");- });-- it("clears every credential on process restart", async () => {- const { store: firstStore } = store();- const room = await firstStore.createRoom("private", "room-password");- const { store: secondStore } = store();-- const replacement = await secondStore.createRoom("open");- expect(replacement.roomId).toMatch(/^[1-9]\d{3}$/);- expectRoomError(- () =>- secondStore.connectParticipant(- hostInput(room.roomId, room.hostToken),- ),- "INVALID_TOKEN",- );- expectRoomError(- () =>- secondStore.connectParticipant(- viewerInput(room.roomId, "old-grant", room.viewerGrant!),- ),- "INVALID_TOKEN",- );- await expect(- secondStore.connectViewerWithPassword({- roomId: room.roomId,- password: "room-password",- clientId: "viewer",- sessionId: "session",- }),- ).rejects.toThrow(new RoomStoreError("ROOM_NOT_FOUND"));- });-- it("rejects an old grant when a new room reuses the same code", async () => {- const firstStore = store({- random: (size) => Buffer.alloc(size, size === 8 ? 0 : 1),- }).store;- const firstRoom = await firstStore.createRoom("open");- firstStore.abandonRoom(firstRoom.roomId);-- const secondStore = store({- random: (size) => Buffer.alloc(size, size === 8 ? 0 : 2),- }).store;- const secondRoom = await secondStore.createRoom("open");-- expect(secondRoom.roomId).toBe(firstRoom.roomId);- expect(secondRoom.viewerGrant).not.toBe(firstRoom.viewerGrant);- expectRoomError(- () =>- secondStore.connectParticipant(- viewerInput(secondRoom.roomId, "old-incarnation", firstRoom.viewerGrant!),- ),- "INVALID_TOKEN",- );- });-});diff --git a/tests/server-config.test.ts b/tests/server-config.test.tsdeleted file mode 100644index 6d968425..00000000--- a/tests/server-config.test.ts+++ /dev/null@@ -1,511 +0,0 @@-import { resolve } from "node:path";--import { describe, expect, it } from "vitest";--import { MAX_VIEWERS_PER_ROOM_LIMIT } from "../src/shared/protocol.ts";-import { loadConfig } from "../src/server/config.ts";--const liveKitAdmission = {- LIVEKIT_API_URL: "https://livekit-api.test",-} as const;--describe("server configuration", () => {- it("allows local development without STUN and defaults the origin", () => {- const config = loadConfig({ NODE_ENV: "development", PORT: "9123" });-- expect(config.listenHost).toBe("0.0.0.0");- expect(config.publicBaseUrl.href).toBe("http://localhost:9123/");- expect(config.allowedOrigins).toEqual(new Set(["http://localhost:9123"]));- expect(config.roomDatabasePath).toBeUndefined();- expect(config.stunUrls).toEqual([]);- expect(config.natPredictionEnabled).toBe(false);- expect(config.maxViewersPerRoom).toBe(8);- expect(config.peerAssistedMedia).toBe(false);- expect(config.endpointMediaCopyCapacity).toBe(2);- expect(config.livekitFallback).toBeUndefined();- });-- it("enables LiveKit fallback only for a complete credential tuple", () => {- const config = loadConfig({- PEER_ASSISTED_MEDIA: "true",- LIVEKIT_URL: " ws://livekit.test:7880 ",- LIVEKIT_API_URL: " http://livekit.test:7880 ",- LIVEKIT_API_KEY: " test-key ",- LIVEKIT_API_SECRET: ` ${"s".repeat(32)} `,- });-- expect(config.livekitFallback).toEqual({- url: "ws://livekit.test:7880",- apiUrl: "http://livekit.test:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- });- });-- it("requires peer-assisted media for LiveKit fallback", () => {- expect(() =>- loadConfig({- PEER_ASSISTED_MEDIA: "false",- LIVEKIT_URL: "wss://livekit.test",- LIVEKIT_API_KEY: "test-key",- LIVEKIT_API_SECRET: "s".repeat(32),- ...liveKitAdmission,- }),- ).toThrow("LiveKit fallback requires PEER_ASSISTED_MEDIA=true");- });-- it.each([- { LIVEKIT_URL: "wss://livekit.test" },- { LIVEKIT_API_URL: "https://livekit-api.test" },- { LIVEKIT_API_KEY: "test-key" },- { LIVEKIT_API_SECRET: "s".repeat(32) },- {- LIVEKIT_URL: "wss://livekit.test",- LIVEKIT_API_URL: "https://livekit-api.test",- LIVEKIT_API_KEY: "test-key",- },- ])("rejects a partial LiveKit credential tuple", (partial) => {- expect(() => loadConfig(partial)).toThrow(- "LIVEKIT_URL, LIVEKIT_API_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must be configured together",- );- });-- it.each([- "https://livekit.test",- "wss://user:[email protected]",- "wss://livekit.test/rtc",- "wss://livekit.test?token=value",- "wss://livekit.test#fragment",- ])("rejects an invalid LiveKit origin: %s", (url) => {- expect(() =>- loadConfig({- LIVEKIT_URL: url,- LIVEKIT_API_KEY: "test-key",- LIVEKIT_API_SECRET: "s".repeat(32),- ...liveKitAdmission,- }),- ).toThrow("LIVEKIT_URL");- });-- it("requires wss for LiveKit fallback in production", () => {- expect(() =>- loadConfig({- NODE_ENV: "production",- PUBLIC_BASE_URL: "https://share.test",- STUN_URLS: "stun:stun.test:3478",- PEER_ASSISTED_MEDIA: "true",- LIVEKIT_URL: "ws://livekit.test:7880",- LIVEKIT_API_KEY: "test-key",- LIVEKIT_API_SECRET: "s".repeat(32),- ...liveKitAdmission,- }),- ).toThrow("LIVEKIT_URL must use wss in production");- });-- it.each([- "ws://livekit-api.test",- "http://user:[email protected]",- "http://livekit-api.test/rtc",- "http://livekit-api.test?token=value",- "http://livekit-api.test#fragment",- ])("rejects an invalid LiveKit control origin: %s", (apiUrl) => {- expect(() =>- loadConfig({- PEER_ASSISTED_MEDIA: "true",- LIVEKIT_URL: "wss://livekit.test",- LIVEKIT_API_URL: apiUrl,- LIVEKIT_API_KEY: "test-key",- LIVEKIT_API_SECRET: "s".repeat(32),- }),- ).toThrow("LIVEKIT_API_URL");- });-- it("allows only HTTPS or loopback LiveKit control in production", () => {- const production = {- NODE_ENV: "production",- PUBLIC_BASE_URL: "https://share.test",- SITE_ACCESS_PASSWORD: "host-password-12",- STUN_URLS: "stun:stun.test:3478",- PEER_ASSISTED_MEDIA: "true",- LIVEKIT_URL: "wss://livekit.test",- LIVEKIT_API_KEY: "test-key",- LIVEKIT_API_SECRET: "s".repeat(32),- };- expect(() =>- loadConfig({- ...production,- LIVEKIT_API_URL: "http://livekit-api.test:7880",- }),- ).toThrow("must use https or loopback");- expect(- loadConfig({- ...production,- LIVEKIT_API_URL: "http://127.0.0.1:7880",- }).livekitFallback?.apiUrl,- ).toBe("http://127.0.0.1:7880");- });-- it("rejects a short LiveKit API secret", () => {- const fallback = {- LIVEKIT_URL: "wss://livekit.test",- LIVEKIT_API_KEY: "test-key",- LIVEKIT_API_SECRET: "s".repeat(32),- ...liveKitAdmission,- };-- expect(() =>- loadConfig({ ...fallback, LIVEKIT_API_SECRET: "too-short" }),- ).toThrow("LIVEKIT_API_SECRET must contain at least 32 bytes");- });-- it.each([- {- SITE_ACCESS_PASSWORD: "x".repeat(32),- PEER_ASSISTED_MEDIA: "true",- LIVEKIT_URL: "wss://livekit.test",- LIVEKIT_API_KEY: "test-key",- LIVEKIT_API_SECRET: "x".repeat(32),- ...liveKitAdmission,- },- {- PEER_ASSISTED_MEDIA: "true",- LIVEKIT_URL: "wss://livekit.test",- LIVEKIT_API_KEY: "x".repeat(32),- LIVEKIT_API_SECRET: "x".repeat(32),- ...liveKitAdmission,- },- ])("rejects reused infrastructure secrets", (environment) => {- expect(() => loadConfig(environment)).toThrow(- "must use independent values",- );- });-- it("requires an explicit boolean to enable peer-assisted media", () => {- expect(- loadConfig({- PEER_ASSISTED_MEDIA: "true",- }).peerAssistedMedia,- ).toBe(true);- expect(loadConfig({ PEER_ASSISTED_MEDIA: "false" }).peerAssistedMedia).toBe(- false,- );- expect(() => loadConfig({ PEER_ASSISTED_MEDIA: "1" })).toThrow(- "PEER_ASSISTED_MEDIA must be true or false",- );- });-- it("keeps the peer-assisted room default at 8 and accepts the room ceiling", () => {- expect(- loadConfig({ PEER_ASSISTED_MEDIA: "true" }).maxViewersPerRoom,- ).toBe(8);- expect(- loadConfig({- PEER_ASSISTED_MEDIA: "true",- MAX_VIEWERS_PER_ROOM: String(MAX_VIEWERS_PER_ROOM_LIMIT),- }).maxViewersPerRoom,- ).toBe(MAX_VIEWERS_PER_ROOM_LIMIT);- expect(() =>- loadConfig({- PEER_ASSISTED_MEDIA: "true",- MAX_VIEWERS_PER_ROOM: String(MAX_VIEWERS_PER_ROOM_LIMIT + 1),- }),- ).toThrow("MAX_VIEWERS_PER_ROOM");- });-- it.each(["1", "2", "3"])(- "accepts an endpoint media copy capacity of %s",- (endpointMediaCopyCapacity) => {- expect(- loadConfig({- ENDPOINT_MEDIA_COPY_CAPACITY: endpointMediaCopyCapacity,- }).endpointMediaCopyCapacity,- ).toBe(Number(endpointMediaCopyCapacity));- },- );-- it.each(["0", "4", "1.5"])(- "rejects an invalid endpoint media copy capacity of %s",- (endpointMediaCopyCapacity) => {- expect(() =>- loadConfig({- ENDPOINT_MEDIA_COPY_CAPACITY: endpointMediaCopyCapacity,- }),- ).toThrow("ENDPOINT_MEDIA_COPY_CAPACITY");- },- );-- it("fails closed on the removed relay downstream setting", () => {- expect(() =>- loadConfig({ MAX_PEER_RELAY_DOWNSTREAM_EDGES: "2" }),- ).toThrow(- "MAX_PEER_RELAY_DOWNSTREAM_EDGES is no longer supported; use ENDPOINT_MEDIA_COPY_CAPACITY",- );- });-- it("enables the hybrid controller for every room when selected", () => {- expect(loadConfig({ PEER_ASSISTED_MEDIA: "true" }).peerAssistedMedia).toBe(- true,- );- expect(() =>- loadConfig({ PEER_ASSISTED_ROOM_IDS: "1" }),- ).toThrow("PEER_ASSISTED_ROOM_IDS is no longer supported");- });-- it("allows an explicit loopback listen host", () => {- expect(loadConfig({ LISTEN_HOST: " 127.0.0.1 " }).listenHost).toBe(- "127.0.0.1",- );- });-- it.each([- "https://user:[email protected]",- "https://share.test/path",- "https://share.test?query=1",- "https://share.test#fragment",- ])("rejects a PUBLIC_BASE_URL that is not a plain origin: %s", (url) => {- expect(() => loadConfig({ PUBLIC_BASE_URL: url })).toThrow(- "PUBLIC_BASE_URL must be an origin",- );- });-- it("requires STUN in production", () => {- expect(() =>- loadConfig({- NODE_ENV: "production",- PUBLIC_BASE_URL: "https://share.test",- SITE_ACCESS_PASSWORD: "host-password-12",- }),- ).toThrow("STUN is required in production");-- const config = loadConfig({- NODE_ENV: "production",- PUBLIC_BASE_URL: "https://share.test",- SITE_ACCESS_PASSWORD: "easy-key",- STUN_URLS: "stun:stun.test:3478",- });- expect(config.stunUrls).toEqual(["stun:stun.test:3478"]);- });-- it("allows STUN-only production with LiveKit configured", () => {- const config = loadConfig({- NODE_ENV: "production",- PUBLIC_BASE_URL: "https://share.test",- SITE_ACCESS_PASSWORD: "host-password-12",- STUN_URLS: "stun:stun.test:3478",- PEER_ASSISTED_MEDIA: "true",- LIVEKIT_URL: "wss://livekit.test",- LIVEKIT_API_KEY: "test-key",- LIVEKIT_API_SECRET: "s".repeat(32),- ...liveKitAdmission,- });-- expect(config.livekitFallback?.url).toBe("wss://livekit.test");- });-- it.each([1, MAX_VIEWERS_PER_ROOM_LIMIT])(- "accepts a per-room viewer limit at boundary %i",- (maxViewersPerRoom) => {- expect(- loadConfig({ MAX_VIEWERS_PER_ROOM: String(maxViewersPerRoom) })- .maxViewersPerRoom,- ).toBe(maxViewersPerRoom);- },- );-- it.each(["0", String(MAX_VIEWERS_PER_ROOM_LIMIT + 1), "1.5"])(- "rejects invalid per-room viewer limit %s",- (maxViewersPerRoom) => {- expect(() =>- loadConfig({ MAX_VIEWERS_PER_ROOM: maxViewersPerRoom }),- ).toThrow("MAX_VIEWERS_PER_ROOM");- },- );-- it("accepts uppercase STUN schemes and IPv6 hosts", () => {- expect(- loadConfig({ STUN_URLS: "STUN:[2001:db8::1]:3478" }).stunUrls,- ).toEqual(["STUN:[2001:db8::1]:3478"]);- });-- it("enables bounded NAT prediction only with a base STUN listener", () => {- expect(- loadConfig({- STUN_URLS: "stun:share.test:3478",- NAT_PREDICTION_ENABLED: "true",- }).natPredictionEnabled,- ).toBe(true);- expect(() =>- loadConfig({ NAT_PREDICTION_ENABLED: "true" }),- ).toThrow(- "NAT_PREDICTION_ENABLED requires a STUN_URLS entry on UDP 3478",- );- expect(() =>- loadConfig({- STUN_URLS: "stun:share.test:5349",- NAT_PREDICTION_ENABLED: "true",- }),- ).toThrow(- "NAT_PREDICTION_ENABLED requires a STUN_URLS entry on UDP 3478",- );- expect(() =>- loadConfig({ NAT_PREDICTION_ENABLED: "sometimes" }),- ).toThrow("NAT_PREDICTION_ENABLED must be true or false");- });-- it.each([- "stun:stun.test/path",- "stun:stun.test?transport=udp",- "stun:stun.test#fragment",- "stun:",- "stun:stun.test:",- "stun:stun.test:0",- "stun:[email protected]:3478",- ])("rejects a malformed STUN URL: %s", (invalidUrl) => {- expect(() => loadConfig({ STUN_URLS: invalidUrl })).toThrow(- "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 invalid STUN URL",- );- expect(() => loadConfig({ STUN_URLS: "stuns:stun.test:5349" })).toThrow(- "STUN_URLS contains an invalid STUN URL",- );- });-- it.each([- "TURN_URLS",- "TURN_SHARED_SECRET",- "TURN_CREDENTIAL_TTL_SECONDS",- "PEER_ICE_TURN_URLS",- "PEER_ICE_TURN_SHARED_SECRET",- "PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS",- "SELECTED_EDGE_TURN_URLS",- "SELECTED_EDGE_TURN_SHARED_SECRET",- "SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS",- "SELECTED_EDGE_TURN_ALLOCATION_CAPACITY",- ] as const)("rejects removed TURN configuration even when %s is blank", (name) => {- expect(() => loadConfig({ [name]: "" })).toThrow(- `${name} is no longer supported`,- );- });-- it("rejects more STUN URLs than the authenticated wire can carry", () => {- expect(() =>- loadConfig({- STUN_URLS: Array.from(- { length: 9 },- (_, index) => `stun:stun-${index}.test:3478`,- ).join(","),- }),- ).toThrow("STUN_URLS must contain at most 8 URLs");- });-- it("reserves two ICE URL slots for configured NAT prediction", () => {- expect(() =>- loadConfig({- STUN_URLS: Array.from(- { length: 7 },- (_, index) => `stun:ordinary-${index}.test:3478`,- ).join(","),- NAT_PREDICTION_ENABLED: "true",- }),- ).toThrow(- "STUN_URLS must contain at most 6 URLs when NAT_PREDICTION_ENABLED=true",- );- });-- it("requires and accepts a bounded production site access password", () => {- expect(() =>- loadConfig({- NODE_ENV: "production",- PUBLIC_BASE_URL: "https://share.test",- STUN_URLS: "stun:stun.test:3478",- }),- ).toThrow("SITE_ACCESS_PASSWORD is required in production");- const config = loadConfig({- NODE_ENV: "production",- PUBLIC_BASE_URL: "https://share.test",- SITE_ACCESS_PASSWORD: "easy-key",- STUN_URLS: "stun:stun.test:3478",- });- expect(config.siteAccessPassword).toBe("easy-key");- });-- it("defaults the room lease to 24 hours", () => {- expect(loadConfig({}).roomLeaseMs).toBe(86_400_000);- expect(loadConfig({ ROOM_LEASE_SECONDS: "3600" }).roomLeaseMs).toBe(- 3_600_000,- );- expect(() => loadConfig({ ROOM_LEASE_SECONDS: "0" })).toThrow(- "ROOM_LEASE_SECONDS must be a positive integer",- );- });-- it("accepts optional file-backed room authority in development and production", () => {- const developmentPath = resolve("state", "rooms.sqlite");- expect(- loadConfig({ ROOM_DATABASE_PATH: ` ${developmentPath} ` })- .roomDatabasePath,- ).toBe(developmentPath);- expect(loadConfig({ ROOM_DATABASE_PATH: "" }).roomDatabasePath).toBeUndefined();- const productionPath = resolve("production-state", "rooms.sqlite");- expect(- loadConfig({- NODE_ENV: "production",- PUBLIC_BASE_URL: "https://share.test",- SITE_ACCESS_PASSWORD: "host-password-12",- STUN_URLS: "stun:stun.test:3478",- ROOM_DATABASE_PATH: productionPath,- }).roomDatabasePath,- ).toBe(productionPath);- });-- it.each([":memory:", "rooms\0.sqlite", "rooms.sqlite", "./state/rooms.sqlite"])(- "rejects a non-absolute room database path",- (roomDatabasePath) => {- expect(() =>- loadConfig({ ROOM_DATABASE_PATH: roomDatabasePath }),- ).toThrow("ROOM_DATABASE_PATH must be an absolute file path");- },- );-- it("rejects the removed room TTL configuration", () => {- expect(() => loadConfig({ ROOM_TTL_SECONDS: "" })).toThrow(- "ROOM_TTL_SECONDS is no longer supported; use ROOM_LEASE_SECONDS",- );- });-- it.each(["x".repeat(7), "密码密码密码密码", "contains spaces", "x".repeat(129)])(- "rejects a site access password outside the visible ASCII boundary",- (siteAccessPassword) => {- expect(() =>- loadConfig({ SITE_ACCESS_PASSWORD: siteAccessPassword }),- ).toThrow(- "SITE_ACCESS_PASSWORD must contain 8 to 128 visible ASCII bytes",- );- },- );-- it.each([undefined, "", "legacy-password"])(- "rejects the removed ACCESS_PASSWORD configuration",- (accessPassword) => {- expect(() => loadConfig({ ACCESS_PASSWORD: accessPassword })).toThrow(- "ACCESS_PASSWORD is no longer supported; use SITE_ACCESS_PASSWORD",- );- },- );-- it.each([undefined, "", "legacy-password"])(- "rejects the removed HOST_ADMISSION_PASSWORD configuration",- (removedPassword) => {- expect(() =>- loadConfig({ HOST_ADMISSION_PASSWORD: removedPassword }),- ).toThrow(- "HOST_ADMISSION_PASSWORD is no longer supported; use SITE_ACCESS_PASSWORD",- );- },- );-});diff --git a/tests/server-http.test.ts b/tests/server-http.test.tsdeleted file mode 100644index 92ada7f3..00000000--- a/tests/server-http.test.ts+++ /dev/null@@ -1,1285 +0,0 @@-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { DatabaseSync } from "node:sqlite";--import { afterEach, describe, expect, it, vi } from "vitest";--import {- MAX_VIEWERS_PER_ROOM_LIMIT,- createRoomResponseSchema,- roomAccessUpdateResponseSchema,-} from "../src/shared/protocol.ts";-import {- createScreenerServer,- type CreateServerOptions,- type ScreenerServer,-} from "../src/server/app.ts";-import type { ServerConfig } from "../src/server/config.ts";-import {- ROOM_CAPACITY,- RoomStore,- RoomStoreError,-} from "../src/server/room-store.ts";-import { FakeSfuRoomControl } from "./fake-sfu-room-control.ts";--const allowedOrigin = "http://allowed.test";-const siteAccessPassword = "instance-access-password";-let runningServer: ScreenerServer | undefined;-const temporaryDirectories: string[] = [];-afterEach(async () => {- try {- await runningServer?.close();- runningServer = undefined;- } finally {- for (const directory of temporaryDirectories.splice(0).reverse()) {- rmSync(directory, { recursive: true, force: true });- }- }-});--function temporaryRoomDatabasePath(): string {- const directory = mkdtempSync(join(tmpdir(), "screener-server-room-db-"));- temporaryDirectories.push(directory);- return join(directory, "rooms.sqlite");-}--function testConfig(overrides: Partial<ServerConfig> = {}): ServerConfig {- return {- nodeEnv: "test",- port: 0,- listenHost: "127.0.0.1",- publicBaseUrl: new URL("https://share.example.test"),- allowedOrigins: new Set([allowedOrigin]),- siteAccessPassword,- roomLeaseMs: 86_400_000,- maxViewersPerRoom: 8,- peerAssistedMedia: false,- endpointMediaCopyCapacity: 2,- stunUrls: [],- natPredictionEnabled: false,- ...overrides,- };-}--async function start(- config = testConfig(),- options: Pick<- CreateServerOptions,- | "now"- | "roomStore"- | "siteAccessTtlSeconds"- | "sfuTokenIssuer"- | "sfuRoomControl"- > = {},-): Promise<string> {- const sfuRoomControl =- options.sfuRoomControl ??- (config.livekitFallback ? new FakeSfuRoomControl() : undefined);- runningServer = await createScreenerServer({- ...options,- ...(sfuRoomControl ? { sfuRoomControl } : {}),- config,- frontend: { mode: "none" },- });- const port = await runningServer.listen(0, "127.0.0.1");- return `http://127.0.0.1:${port}`;-}--function cookiePair(response: Response): string {- const setCookie = response.headers.get("set-cookie");- if (!setCookie) {- throw new Error("Expected a Set-Cookie header");- }- return setCookie.split(";", 1)[0]!;-}--async function login(baseUrl: string): Promise<Response> {- return fetch(`${baseUrl}/api/site-access`, {- method: "POST",- headers: {- Authorization: `Bearer ${siteAccessPassword}`,- Origin: allowedOrigin,- },- });-}--async function createRoom(- baseUrl: string,- cookie?: string,- codeEntryPolicy: "open" | "private" = "open",- roomPassword?: string,- preferredRoomId?: string,-): Promise<Response> {- return fetch(`${baseUrl}/api/rooms`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Origin: allowedOrigin,- ...(cookie ? { Cookie: cookie } : {}),- },- body: JSON.stringify({- codeEntryPolicy,- ...(roomPassword === undefined ? {} : { roomPassword }),- ...(preferredRoomId === undefined ? {} : { preferredRoomId }),- }),- });-}--async function updateRoomAccess(- baseUrl: string,- roomId: string,- hostToken: string | undefined,- body: unknown,- options: { cookie?: string; origin?: string; method?: string } = {},-): Promise<Response> {- return fetch(`${baseUrl}/api/rooms/${roomId}/access`, {- method: options.method ?? "POST",- headers: {- "Content-Type": "application/json",- Origin: options.origin ?? allowedOrigin,- ...(options.cookie ? { Cookie: options.cookie } : {}),- ...(hostToken ? { Authorization: `Bearer ${hostToken}` } : {}),- },- body:- (options.method ?? "POST") === "POST"- ? JSON.stringify(body)- : undefined,- });-}--async function replaceRoom(- baseUrl: string,- roomId: string,- hostToken: string,- body: unknown,- cookie?: string,-): Promise<Response> {- return fetch(`${baseUrl}/api/rooms/${roomId}/replacement`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Origin: allowedOrigin,- Authorization: `Bearer ${hostToken}`,- ...(cookie ? { Cookie: cookie } : {}),- },- body: JSON.stringify(body),- });-}--describe("runtime capabilities", () => {- it("keeps NAT prediction absent by default", async () => {- const baseUrl = await start();- const response = await fetch(`${baseUrl}/api/capabilities`);-- expect(response.status).toBe(200);- expect(await response.json()).toEqual({ natPrediction: false });- });-- it("reports optional NAT prediction without exposing configuration", async () => {- const baseUrl = await start(- testConfig({- stunUrls: ["stun:share.example.test:3478"],- natPredictionEnabled: true,- }),- );- const response = await fetch(`${baseUrl}/api/capabilities`);-- expect(response.status).toBe(200);- expect(response.headers.get("cache-control")).toBe("no-store");- expect(await response.json()).toEqual({ natPrediction: true });- expect(- (await fetch(`${baseUrl}/api/capabilities`, { method: "POST" })).status,- ).toBe(405);- });-});--describe("site access", () => {- it("reports status and issues a stateless 24-hour cookie", async () => {- const baseUrl = await start();- const initial = await fetch(`${baseUrl}/api/site-access`);-- expect(initial.status).toBe(200);- expect(initial.headers.get("cache-control")).toBe("no-store");- expect(initial.headers.get("set-cookie")).toBeNull();- expect(await initial.json()).toEqual({- required: true,- authenticated: false,- });-- const denied = await fetch(`${baseUrl}/api/site-access`, {- method: "POST",- headers: {- Authorization: "Bearer wrong-password",- Origin: allowedOrigin,- },- });- expect(denied.status).toBe(401);- expect(denied.headers.get("set-cookie")).toBeNull();-- const authenticated = await login(baseUrl);- const setCookie = authenticated.headers.get("set-cookie") ?? "";- expect(authenticated.status).toBe(200);- expect(setCookie).toContain("screener-site-access=v1.");- expect(setCookie).toContain("Path=/");- expect(setCookie).toContain("Max-Age=86400");- expect(setCookie).toContain("HttpOnly");- expect(setCookie).toContain("SameSite=Strict");- expect(setCookie).not.toContain("Secure");- expect(setCookie).not.toContain(siteAccessPassword);-- const deniedRenewal = await fetch(`${baseUrl}/api/site-access`, {- method: "POST",- headers: {- Authorization: "Bearer wrong-password",- Cookie: cookiePair(authenticated),- Origin: allowedOrigin,- },- });- expect(deniedRenewal.status).toBe(401);- expect(deniedRenewal.headers.get("set-cookie")).toBeNull();-- const status = await fetch(`${baseUrl}/api/site-access`, {- headers: { Cookie: cookiePair(authenticated) },- });- expect(status.headers.get("set-cookie")).toContain(- "screener-site-access=v1.",- );- expect(await status.json()).toEqual({- required: true,- authenticated: true,- });- });-- it("renews an authenticated cookie across successive idle deadlines", async () => {- let now = 1_000;- const baseUrl = await start(testConfig(), {- now: () => now,- siteAccessTtlSeconds: 12,- });- const authenticated = await login(baseUrl);- const originalCookie = cookiePair(authenticated);-- now = 7_000;- const firstRenewal = await fetch(`${baseUrl}/api/site-access`, {- headers: { Cookie: originalCookie },- });- const firstRenewedCookie = cookiePair(firstRenewal);- expect(firstRenewedCookie).not.toBe(originalCookie);-- now = 13_000;- const expiredOriginal = await fetch(`${baseUrl}/api/site-access`, {- headers: { Cookie: originalCookie },- });- expect(expiredOriginal.headers.get("set-cookie")).toBeNull();- expect((await expiredOriginal.json()).authenticated).toBe(false);-- const secondRenewal = await fetch(`${baseUrl}/api/site-access`, {- headers: { Cookie: firstRenewedCookie },- });- const secondRenewedCookie = cookiePair(secondRenewal);- expect(secondRenewedCookie).not.toBe(firstRenewedCookie);-- now = 20_000;- const expiredFirstRenewal = await fetch(`${baseUrl}/api/site-access`, {- headers: { Cookie: firstRenewedCookie },- });- expect(expiredFirstRenewal.headers.get("set-cookie")).toBeNull();- expect((await expiredFirstRenewal.json()).authenticated).toBe(false);-- const activeSecondRenewal = await fetch(`${baseUrl}/api/site-access`, {- headers: { Cookie: secondRenewedCookie },- });- expect(activeSecondRenewal.headers.get("set-cookie")).not.toBeNull();- expect((await activeSecondRenewal.json()).authenticated).toBe(true);- });-- it("uses a secure __Host- cookie for production HTTPS", async () => {- const baseUrl = await start(testConfig({ nodeEnv: "production" }));- const response = await login(baseUrl);- const setCookie = response.headers.get("set-cookie") ?? "";-- expect(setCookie).toContain("__Host-screener-site-access=");- expect(setCookie).toContain("Secure");- expect(setCookie).toContain("HttpOnly");- expect(setCookie).toContain("SameSite=Strict");- expect(setCookie).toContain("Path=/");- expect(setCookie).not.toContain("Domain=");- });-- it("requires an allowed Origin and an empty login body", async () => {- const baseUrl = await start();- const authorization = {- Authorization: `Bearer ${siteAccessPassword}`,- };-- expect(- (- await fetch(`${baseUrl}/api/site-access`, {- method: "POST",- headers: authorization,- })- ).status,- ).toBe(403);- expect(- (- await fetch(`${baseUrl}/api/site-access`, {- method: "POST",- headers: { ...authorization, Origin: "https://foreign.test" },- })- ).status,- ).toBe(403);- expect(- (- await fetch(`${baseUrl}/api/site-access`, {- method: "POST",- headers: { ...authorization, Origin: `${allowedOrigin}/path` },- })- ).status,- ).toBe(403);- expect(- (- await fetch(`${baseUrl}/api/site-access`, {- method: "POST",- headers: { ...authorization, Origin: allowedOrigin },- body: "{}",- })- ).status,- ).toBe(400);- });-- it("rejects an expired or modified cookie", async () => {- let now = 1_000;- const baseUrl = await start(testConfig(), {- now: () => now,- siteAccessTtlSeconds: 1,- });- const authenticated = await login(baseUrl);- const cookie = cookiePair(authenticated);-- const modified = await fetch(`${baseUrl}/api/site-access`, {- headers: { Cookie: `${cookie}x` },- });- expect((await modified.json()).authenticated).toBe(false);-- now = 2_000;- const expired = await fetch(`${baseUrl}/api/site-access`, {- headers: { Cookie: cookie },- });- expect(await expired.json()).toEqual({- required: true,- authenticated: false,- });- });-- it("is immediately authenticated when the access password is empty", async () => {- const baseUrl = await start(- testConfig({ siteAccessPassword: undefined }),- );- const status = await fetch(`${baseUrl}/api/site-access`);-- expect(await status.json()).toEqual({- required: false,- authenticated: true,- });- const post = await fetch(`${baseUrl}/api/site-access`, {- method: "POST",- headers: { Origin: allowedOrigin },- });- expect(post.status).toBe(200);- expect(post.headers.get("set-cookie")).toBeNull();- });-});--describe("room HTTP API", () => {- it("requires a logged-in browser when access protection is enabled", async () => {- const baseUrl = await start();- const anonymous = await createRoom(baseUrl);- expect(anonymous.status).toBe(401);- expect(anonymous.headers.get("www-authenticate")).toBeNull();-- const bearerBypass = await fetch(`${baseUrl}/api/rooms`, {- method: "POST",- headers: {- Authorization: `Bearer ${siteAccessPassword}`,- "Content-Type": "application/json",- Origin: allowedOrigin,- },- body: JSON.stringify({ codeEntryPolicy: "open" }),- });- expect(bearerBypass.status).toBe(401);- });-- it("creates a room with an independent fragment-only Viewer grant", async () => {- const baseUrl = await start();- const authenticated = await login(baseUrl);- const response = await createRoom(baseUrl, cookiePair(authenticated));-- expect(response.status).toBe(201);- expect(response.headers.get("cache-control")).toBe("no-store");- const body = createRoomResponseSchema.parse(await response.json());- const invite = new URL(body.inviteUrl);- expect(body.roomId).toMatch(/^[1-9]\d{3}$/);- expect(invite.origin).toBe("https://share.example.test");- expect(invite.pathname).toBe(`/r/${body.roomId}`);- expect(invite.hash).toMatch(/^#v=[A-Za-z0-9_-]{21}[AQgw]$/);- expect(invite.search).toBe("");- expect(body.codeEntryPolicy).toBe("open");- expect("viewerGrantExpiresAt" in body).toBe(false);- expect(body.expiresAt).toBeTruthy();- expect(body.roomLeaseSeconds).toBe(86_400);- expect("iceConfig" in body).toBe(false);- });-- it("passes the shared Viewer ceiling to room admission", async () => {- const baseUrl = await start(- testConfig({- siteAccessPassword: undefined,- maxViewersPerRoom: MAX_VIEWERS_PER_ROOM_LIMIT,- }),- );-- expect((await createRoom(baseUrl)).status).toBe(201);- expect(runningServer?.roomStore.maxViewersPerRoom).toBe(- MAX_VIEWERS_PER_ROOM_LIMIT,- );- });-- it("creates private rooms with optional passwords atomically", async () => {- const baseUrl = await start();- const authenticated = await login(baseUrl);- const cookie = cookiePair(authenticated);- const response = await createRoom(- baseUrl,- cookie,- "private",- "room-password",- );- expect(response.status).toBe(201);- expect(createRoomResponseSchema.parse(await response.json())).toMatchObject({- codeEntryPolicy: "private",- });-- const withoutPassword = await createRoom(baseUrl, cookie, "private");- expect(withoutPassword.status).toBe(201);- expect(- createRoomResponseSchema.parse(await withoutPassword.json()),- ).toMatchObject({ codeEntryPolicy: "private" });- });-- it("allows explicit open creation without site access in local mode", async () => {- const baseUrl = await start(- testConfig({ siteAccessPassword: undefined }),- );- const response = await createRoom(baseUrl, undefined, "open");- expect(response.status).toBe(201);- const body = createRoomResponseSchema.parse(await response.json());- expect(body).toMatchObject({- codeEntryPolicy: "open",- });- expect(new URL(body.inviteUrl).hash).toContain("#v=");- });-- it("allocates unique four-digit codes concurrently", async () => {- const baseUrl = await start();- const authenticated = await login(baseUrl);- const cookie = cookiePair(authenticated);- const create = () => createRoom(baseUrl, cookie);-- const responses = await Promise.all([create(), create()]);- const rooms = await Promise.all(- responses.map(async (response) =>- createRoomResponseSchema.parse(await response.json()),- ),- );- expect(new Set(rooms.map((room) => room.roomId)).size).toBe(2);- expect(rooms.every((room) => room.expiresAt !== null)).toBe(true);- });-- it("reuses a free preferred code and never replaces an occupied room", async () => {- const baseUrl = await start(testConfig({ roomLeaseMs: 90_000 }));- const authenticated = await login(baseUrl);- const cookie = cookiePair(authenticated);-- const preferred = createRoomResponseSchema.parse(- await (await createRoom(baseUrl, cookie, "open", undefined, "4321")).json(),- );- const fallback = createRoomResponseSchema.parse(- await (await createRoom(baseUrl, cookie, "open", undefined, "4321")).json(),- );-- expect(preferred.roomId).toBe("4321");- expect(preferred.roomLeaseSeconds).toBe(90);- expect(fallback.roomId).not.toBe("4321");- expect(fallback.hostToken).not.toBe(preferred.hostToken);- });-- it("replaces a room with a different authority and closes old membership", async () => {- const baseUrl = await start();- const authenticated = await login(baseUrl);- const cookie = cookiePair(authenticated);- const original = createRoomResponseSchema.parse(- await (- await createRoom(baseUrl, cookie, "private", "old-password", "4321")- ).json(),- );- const host = runningServer!.roomStore.connectParticipant({- roomId: original.roomId,- role: "host",- token: original.hostToken,- clientId: "host-client",- sessionId: "host-session",- });- runningServer!.roomStore.connectParticipant({- roomId: original.roomId,- role: "viewer",- viewerGrant: new URL(original.inviteUrl).hash.slice(3),- clientId: "viewer-client",- sessionId: "viewer-session",- });-- expect(- (- await replaceRoom(- baseUrl,- original.roomId,- original.hostToken,- { codeEntryPolicy: "open" },- )- ).status,- ).toBe(401);- const response = await replaceRoom(- baseUrl,- original.roomId,- original.hostToken,- { codeEntryPolicy: "private", roomPassword: "new-password" },- cookie,- );- expect(response.status).toBe(201);- const replacement = createRoomResponseSchema.parse(await response.json());-- expect(replacement.roomId).not.toBe(original.roomId);- expect(replacement.codeEntryPolicy).toBe("private");- expect(runningServer!.roomStore.getConnectedHost(original.roomId)).toBeUndefined();- expect(runningServer!.roomStore.getConnectedViewers(original.roomId)).toEqual([]);- expect(() =>- runningServer!.roomStore.connectParticipant({- roomId: original.roomId,- role: "host",- token: original.hostToken,- clientId: "old-host",- sessionId: "old-session",- }),- ).toThrow(new RoomStoreError("INVALID_TOKEN"));- expect(host.peerId).toBeTruthy();- });-- it("keeps valid Host authority on a transient replacement rejection", async () => {- const config = testConfig();- const roomStore = new RoomStore({- leaseMs: config.roomLeaseMs,- maxRooms: ROOM_CAPACITY,- maxViewersPerRoom: config.maxViewersPerRoom,- });- const original = await roomStore.createRoom("private", "room-password");- vi.spyOn(roomStore, "replaceRoom").mockRejectedValueOnce(- new RoomStoreError("ROOM_ACCESS_DENIED"),- );- const baseUrl = await start(config, { roomStore });- const cookie = cookiePair(await login(baseUrl));-- const response = await replaceRoom(- baseUrl,- original.roomId,- original.hostToken,- { codeEntryPolicy: "private", roomPassword: "room-password" },- cookie,- );-- expect(response.status).toBe(503);- expect(- roomStore.connectParticipant({- roomId: original.roomId,- role: "host",- token: original.hostToken,- clientId: "retained-host",- sessionId: "retained-host-session",- }).roomId,- ).toBe(original.roomId);- });-- it("maps a busy password gate to 503 for every HTTP mutation", async () => {- const config = testConfig();- const roomStore = new RoomStore({- leaseMs: config.roomLeaseMs,- maxRooms: ROOM_CAPACITY,- maxViewersPerRoom: config.maxViewersPerRoom,- });- const original = await roomStore.createRoom("private", "room-password");- const baseUrl = await start(config, { roomStore });- const cookie = cookiePair(await login(baseUrl));-- vi.spyOn(roomStore, "createRoom").mockRejectedValueOnce(- new RoomStoreError("ROOM_BUSY"),- );- const creation = await createRoom(- baseUrl,- cookie,- "private",- "room-password",- );- expect(creation.status).toBe(503);- expect(await creation.json()).toEqual({- error: "Room creation unavailable",- });-- vi.spyOn(roomStore, "replaceRoom").mockRejectedValueOnce(- new RoomStoreError("ROOM_BUSY"),- );- const replacement = await replaceRoom(- baseUrl,- original.roomId,- original.hostToken,- { codeEntryPolicy: "private", roomPassword: "room-password" },- cookie,- );- expect(replacement.status).toBe(503);- expect(await replacement.json()).toEqual({- error: "Room replacement unavailable",- });-- vi.spyOn(roomStore, "setViewerPassword").mockRejectedValueOnce(- new RoomStoreError("ROOM_BUSY"),- );- const update = await updateRoomAccess(- baseUrl,- original.roomId,- original.hostToken,- { action: "set-viewer-password", password: "room-password" },- { cookie },- );- expect(update.status).toBe(503);- expect(await update.json()).toEqual({- error: "Room access update unavailable",- });- expect(roomStore.size).toBe(1);- });-- it("manages dormant room access without starting sharing or renewing", async () => {- let nowMs = 0;- const baseUrl = await start(- testConfig({ roomLeaseMs: 1_000 }),- { now: () => nowMs },- );- const authenticated = await login(baseUrl);- const cookie = cookiePair(authenticated);- const createdResponse = await createRoom(baseUrl, cookie);- const room = createRoomResponseSchema.parse(await createdResponse.json());- nowMs = 900;-- const policy = await updateRoomAccess(- baseUrl,- room.roomId,- room.hostToken,- { action: "set-code-entry-policy", policy: "private" },- { cookie },- );- expect(policy.status).toBe(200);- expect(policy.headers.get("cache-control")).toBe("no-store");- expect(roomAccessUpdateResponseSchema.parse(await policy.json())).toEqual({- type: "code-entry-policy-updated",- codeEntryPolicy: "private",- viewerPasswordEnabled: false,- });-- const password = await updateRoomAccess(- baseUrl,- room.roomId,- room.hostToken,- { action: "set-viewer-password", password: "room-password" },- { cookie },- );- expect(roomAccessUpdateResponseSchema.parse(await password.json())).toEqual({- type: "viewer-password-updated",- enabled: true,- });- const removedPassword = await updateRoomAccess(- baseUrl,- room.roomId,- room.hostToken,- { action: "set-viewer-password", password: null },- { cookie },- );- expect(- roomAccessUpdateResponseSchema.parse(await removedPassword.json()),- ).toEqual({- type: "viewer-password-updated",- enabled: false,- });-- const rotated = await updateRoomAccess(- baseUrl,- room.roomId,- room.hostToken,- { action: "rotate-viewer-grant" },- { cookie },- );- const rotatedBody = roomAccessUpdateResponseSchema.parse(- await rotated.json(),- );- expect(rotatedBody.type).toBe("viewer-grant-updated");- expect(rotatedBody.type === "viewer-grant-updated" && rotatedBody.inviteUrl)- .toMatch(/#v=[A-Za-z0-9_-]{22}$/);-- const revoked = await updateRoomAccess(- baseUrl,- room.roomId,- room.hostToken,- { action: "revoke-viewer-grant" },- { cookie },- );- expect(roomAccessUpdateResponseSchema.parse(await revoked.json())).toMatchObject({- type: "viewer-grant-updated",- inviteUrl: null,- });- expect(runningServer?.roomStore.getConnectedHost(room.roomId)).toBeUndefined();-- nowMs = 1_001;- expect(- runningServer?.roomStore- .expireRooms()- .map((expired) => expired.roomId),- ).toContain(room.roomId);- });-- it("requires same-origin site access and the exact room Host token", async () => {- const baseUrl = await start();- const authenticated = await login(baseUrl);- const cookie = cookiePair(authenticated);- const first = createRoomResponseSchema.parse(- await (await createRoom(baseUrl, cookie)).json(),- );- const second = createRoomResponseSchema.parse(- await (await createRoom(baseUrl, cookie)).json(),- );- const action = { action: "rotate-viewer-grant" };-- expect(- (await updateRoomAccess(baseUrl, first.roomId, first.hostToken, action))- .status,- ).toBe(401);- expect(- (- await updateRoomAccess(baseUrl, first.roomId, first.hostToken, action, {- cookie,- origin: "https://foreign.test",- })- ).status,- ).toBe(403);- expect(- (await updateRoomAccess(baseUrl, first.roomId, undefined, action, { cookie }))- .status,- ).toBe(404);- expect(- (- await updateRoomAccess(baseUrl, first.roomId, "wrong-token", action, {- cookie,- })- ).status,- ).toBe(404);- expect(- (- await updateRoomAccess(baseUrl, first.roomId, second.hostToken, action, {- cookie,- })- ).status,- ).toBe(404);- expect(- (- await updateRoomAccess(- baseUrl,- first.roomId,- first.hostToken,- { action: "unknown" },- { cookie },- )- ).status,- ).toBe(400);- const method = await updateRoomAccess(- baseUrl,- first.roomId,- first.hostToken,- action,- { cookie, method: "GET" },- );- expect(method.status).toBe(405);- expect(method.headers.get("allow")).toBe("POST");- });-- it("rejects malformed room requests and foreign browser origins", async () => {- const baseUrl = await start(- testConfig({ siteAccessPassword: undefined }),- );- const withBody = await fetch(`${baseUrl}/api/rooms`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Origin: allowedOrigin,- },- body: "{}",- });- expect(withBody.status).toBe(400);-- const foreign = await fetch(`${baseUrl}/api/rooms`, {- method: "POST",- headers: { "Content-Type": "application/json", Origin: "https://foreign.test" },- body: JSON.stringify({ codeEntryPolicy: "open" }),- });- expect(foreign.status).toBe(403);- });-- it("returns service unavailable at the global room bound", async () => {- const baseUrl = await start(- testConfig({ siteAccessPassword: undefined }),- {- roomStore: new RoomStore({- leaseMs: 86_400_000,- maxRooms: 1,- maxViewersPerRoom: 8,- }),- },- );- const create = () => createRoom(baseUrl);-- expect((await create()).status).toBe(201);- expect((await create()).status).toBe(503);- });-});--describe("server HTTP listener and health", () => {- it("serves an explicit static frontend independently of NODE_ENV", async () => {- const directory = mkdtempSync(join(tmpdir(), "screener-static-frontend-"));- temporaryDirectories.push(directory);- writeFileSync(join(directory, "index.html"), "<main>local-static</main>");- runningServer = await createScreenerServer({- config: testConfig({ nodeEnv: "test" }),- frontend: { mode: "static", directory },- });- const port = await runningServer.listen(0, "127.0.0.1");-- const response = await fetch(`http://127.0.0.1:${port}/local-route`);-- expect(response.status).toBe(200);- expect(await response.text()).toBe("<main>local-static</main>");- });-- it("restores stable room authority across an application restart", async () => {- const roomDatabasePath = temporaryRoomDatabasePath();- let nowMs = 100;- const config = testConfig({- siteAccessPassword: undefined,- roomDatabasePath,- roomLeaseMs: 1_000,- });- const first = await createScreenerServer({- config,- frontend: { mode: "none" },- now: () => nowMs,- });- let second: ScreenerServer | undefined;- try {- const firstPort = await first.listen(0, "127.0.0.1");- const created = createRoomResponseSchema.parse(- await (- await createRoom(`http://127.0.0.1:${firstPort}`, undefined, "private")- ).json(),- );- await first.close();-- nowMs = 200;- second = await createScreenerServer({- config,- frontend: { mode: "none" },- now: () => nowMs,- });- const secondPort = await second.listen(0, "127.0.0.1");- expect(second.roomStore.size).toBe(1);- const update = await updateRoomAccess(- `http://127.0.0.1:${secondPort}`,- created.roomId,- created.hostToken,- { action: "set-code-entry-policy", policy: "open" },- );- expect(update.status).toBe(200);- expect(await update.json()).toMatchObject({- type: "code-entry-policy-updated",- codeEntryPolicy: "open",- });- } finally {- await second?.close();- await first.close();- }- });-- it("starts with an injected optional SFU token issuer", async () => {- const baseUrl = await start(- testConfig({- peerAssistedMedia: true,- livekitFallback: {- url: "ws://livekit.test:7880",- apiUrl: "http://livekit.test:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- },- }),- {- sfuTokenIssuer: {- issueToken: async () => "unused-test-token",- },- },- );-- const response = await fetch(`${baseUrl}/healthz`);- expect(response.status).toBe(200);- });-- it("clears a stale managed LiveKit room before a restarted server serves traffic", async () => {- const roomControl = new FakeSfuRoomControl();- const staleFence = {- roomId: "42",- shareGeneration: "stale_share_generation",- publicationGeneration: "stale_publication_generation",- };- roomControl.seedRoom(staleFence, ["host", "viewer:stale"]);- const baseUrl = await start(- testConfig({- peerAssistedMedia: true,- livekitFallback: {- url: "ws://livekit.test:7880",- apiUrl: "http://127.0.0.1:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- },- }),- {- sfuTokenIssuer: {- issueToken: async () => "unused-test-token",- },- sfuRoomControl: roomControl,- },- );-- expect(roomControl.initializeCalls).toBe(1);- expect(roomControl.startupDeletedRoomNames).toHaveLength(1);- expect(roomControl.rooms.size).toBe(0);- expect((await fetch(`${baseUrl}/healthz`)).status).toBe(200);- });-- it("binds the application listener before LiveKit reconciliation", async () => {- let releaseInitialization!: () => void;- const roomControl = new FakeSfuRoomControl();- roomControl.initializeBarrier = new Promise<void>((resolve) => {- releaseInitialization = resolve;- });- runningServer = await createScreenerServer({- config: testConfig({- peerAssistedMedia: true,- livekitFallback: {- url: "ws://livekit.test:7880",- apiUrl: "http://127.0.0.1:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- },- }),- frontend: { mode: "none" },- sfuRoomControl: roomControl,- sfuTokenIssuer: {- issueToken: async () => "unused-test-token",- },- });-- const listen = runningServer.listen(0, "127.0.0.1");- try {- await vi.waitFor(() => {- expect(roomControl.initializeCalls).toBe(1);- expect(runningServer?.httpServer.address()).not.toBeNull();- });- const address = runningServer.httpServer.address();- if (!address || typeof address === "string") {- throw new Error("Expected a TCP server address");- }- expect(runningServer.httpServer.listenerCount("upgrade")).toBe(0);- const response = await fetch(`http://127.0.0.1:${address.port}/healthz`);- expect(response.status).toBe(503);- expect(response.headers.get("retry-after")).toBe("1");- } finally {- releaseInitialization();- }-- await expect(listen).resolves.toBeGreaterThan(0);- expect(runningServer.httpServer.listenerCount("upgrade")).toBe(1);- });-- it("makes no LiveKit call when another process owns the listener", async () => {- const owner = await createScreenerServer({- config: testConfig(),- frontend: { mode: "none" },- });- const ownerPort = await owner.listen(0, "127.0.0.1");- const unavailableDatabasePath = join(- temporaryRoomDatabasePath(),- "missing-parent",- "rooms.sqlite",- );- const roomControl = new FakeSfuRoomControl();- const contender = await createScreenerServer({- config: testConfig({- roomDatabasePath: unavailableDatabasePath,- peerAssistedMedia: true,- livekitFallback: {- url: "ws://livekit.test:7880",- apiUrl: "http://127.0.0.1:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- },- }),- frontend: { mode: "none" },- sfuRoomControl: roomControl,- sfuTokenIssuer: {- issueToken: async () => "unused-test-token",- },- });-- try {- await expect(contender.listen(ownerPort, "127.0.0.1")).rejects.toMatchObject({- code: "EADDRINUSE",- });- expect(roomControl.initializeCalls).toBe(0);- expect(existsSync(unavailableDatabasePath)).toBe(false);- } finally {- await contender.close();- await owner.close();- }- });-- it("rejects a second database owner before LiveKit reconciliation", async () => {- const roomDatabasePath = temporaryRoomDatabasePath();- const owner = await createScreenerServer({- config: testConfig({ roomDatabasePath }),- frontend: { mode: "none" },- });- await owner.listen(0, "127.0.0.1");- const roomControl = new FakeSfuRoomControl();- const contender = await createScreenerServer({- config: testConfig({- roomDatabasePath,- peerAssistedMedia: true,- livekitFallback: {- url: "ws://livekit.test:7880",- apiUrl: "http://127.0.0.1:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- },- }),- frontend: { mode: "none" },- sfuRoomControl: roomControl,- sfuTokenIssuer: {- issueToken: async () => "unused-test-token",- },- });-- try {- await expect(contender.listen(0, "127.0.0.1")).rejects.toThrow(- /locked/i,- );- expect(roomControl.initializeCalls).toBe(0);- expect(contender.httpServer.listening).toBe(false);- expect(contender.httpServer.listenerCount("upgrade")).toBe(0);- } finally {- await contender.close();- await owner.close();- }- });-- it("rejects a mismatched database before LiveKit reconciliation", async () => {- const roomDatabasePath = temporaryRoomDatabasePath();- const raw = new DatabaseSync(roomDatabasePath);- raw.exec("CREATE TABLE unrelated(value TEXT) STRICT");- raw.close();- const roomControl = new FakeSfuRoomControl();- runningServer = await createScreenerServer({- config: testConfig({- roomDatabasePath,- peerAssistedMedia: true,- livekitFallback: {- url: "ws://livekit.test:7880",- apiUrl: "http://127.0.0.1:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- },- }),- frontend: { mode: "none" },- sfuRoomControl: roomControl,- sfuTokenIssuer: {- issueToken: async () => "unused-test-token",- },- });-- await expect(runningServer.listen(0, "127.0.0.1")).rejects.toThrow(- "Room database application identity does not match",- );- expect(roomControl.initializeCalls).toBe(0);- expect(runningServer.httpServer.listening).toBe(false);- expect(runningServer.httpServer.listenerCount("upgrade")).toBe(0);- });-- it("rejects an inaccessible database path before LiveKit reconciliation", async () => {- const roomDatabasePath = join(- temporaryRoomDatabasePath(),- "missing-parent",- "rooms.sqlite",- );- const roomControl = new FakeSfuRoomControl();- runningServer = await createScreenerServer({- config: testConfig({- roomDatabasePath,- peerAssistedMedia: true,- livekitFallback: {- url: "ws://livekit.test:7880",- apiUrl: "http://127.0.0.1:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- },- }),- frontend: { mode: "none" },- sfuRoomControl: roomControl,- sfuTokenIssuer: {- issueToken: async () => "unused-test-token",- },- });-- await expect(runningServer.listen(0, "127.0.0.1")).rejects.toThrow();- expect(roomControl.initializeCalls).toBe(0);- expect(existsSync(roomDatabasePath)).toBe(false);- expect(runningServer.httpServer.listening).toBe(false);- expect(runningServer.httpServer.listenerCount("upgrade")).toBe(0);- });-- it("holds listener ownership until an in-flight startup reconciliation settles", async () => {- let releaseInitialization!: () => void;- const roomControl = new FakeSfuRoomControl();- roomControl.initializeBarrier = new Promise<void>((resolve) => {- releaseInitialization = resolve;- });- runningServer = await createScreenerServer({- config: testConfig({- peerAssistedMedia: true,- livekitFallback: {- url: "ws://livekit.test:7880",- apiUrl: "http://127.0.0.1:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- },- }),- frontend: { mode: "none" },- sfuRoomControl: roomControl,- sfuTokenIssuer: {- issueToken: async () => "unused-test-token",- },- });- const listen = runningServer.listen(0, "127.0.0.1");- await vi.waitFor(() => {- expect(roomControl.initializeCalls).toBe(1);- expect(runningServer?.httpServer.address()).not.toBeNull();- });- const address = runningServer.httpServer.address();- if (!address || typeof address === "string") {- throw new Error("Expected a TCP server address");- }-- let closed = false;- const closing = runningServer.close().then(() => {- closed = true;- });- await new Promise((resolve) => setTimeout(resolve, 20));- expect(closed).toBe(false);- expect(runningServer.httpServer.listening).toBe(true);-- const contender = await createScreenerServer({- config: testConfig(),- frontend: { mode: "none" },- });- try {- await expect(- contender.listen(address.port, "127.0.0.1"),- ).rejects.toMatchObject({ code: "EADDRINUSE" });- } finally {- await contender.close();- }-- releaseInitialization();- await expect(listen).resolves.toBe(address.port);- await closing;- runningServer = undefined;- expect(closed).toBe(true);- });-- it("closes the listener when LiveKit startup reconciliation fails", async () => {- const roomControl = new FakeSfuRoomControl();- roomControl.initializeError = new Error("startup reconciliation failed");- runningServer = await createScreenerServer({- config: testConfig({- peerAssistedMedia: true,- livekitFallback: {- url: "ws://livekit.test:7880",- apiUrl: "http://127.0.0.1:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- },- }),- frontend: { mode: "none" },- sfuRoomControl: roomControl,- sfuTokenIssuer: {- issueToken: async () => "unused-test-token",- },- });-- await expect(runningServer.listen(0, "127.0.0.1")).rejects.toThrow(- "startup reconciliation failed",- );- expect(roomControl.initializeCalls).toBe(1);- expect(runningServer.httpServer.listening).toBe(false);- expect(runningServer.httpServer.listenerCount("upgrade")).toBe(0);- });-- it("uses the configured listen host by default", async () => {- runningServer = await createScreenerServer({- config: testConfig(),- frontend: { mode: "none" },- });- await runningServer.listen(0);- const address = runningServer.httpServer.address();- if (!address || typeof address === "string") {- throw new Error("Expected a TCP server address");- }- expect(address.address).toBe("127.0.0.1");- });-- it("reports process liveness without access checks", async () => {- const baseUrl = await start();- const response = await fetch(`${baseUrl}/healthz`, {- headers: { Origin: "https://foreign.test" },- });-- expect(response.status).toBe(200);- expect(response.headers.get("cache-control")).toBe("no-store");- expect(await response.json()).toEqual({ status: "ok" });- });-- it("only accepts GET health checks", async () => {- const baseUrl = await start();- const response = await fetch(`${baseUrl}/healthz`, { method: "POST" });- expect(response.status).toBe(405);- expect(response.headers.get("allow")).toBe("GET");- });-});diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.tsdeleted file mode 100644index 2aa3d329..00000000--- a/tests/server-signal.test.ts+++ /dev/null@@ -1,3382 +0,0 @@-import { connect } from "node:net";-import { mkdtempSync, rmSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";--import { afterEach, describe, expect, it, vi } from "vitest";-import WebSocket from "ws";--import {- DEFAULT_ROUTE_POLICY,- MAX_SIGNAL_BYTES,- SIGNALING_PROTOCOL,- decodeServerMessage,- type QualitySettings,- type RoutePolicy,- type RoomAccessUpdateRequest,- type Role,- type ServerMessage,- roomAccessUpdateResponseSchema,-} from "../src/shared/protocol.ts";-import {- createScreenerServer,- type ScreenerServer,-} from "../src/server/app.ts";-import type { ServerConfig } from "../src/server/config.ts";-import { RoomDatabase } from "../src/server/room-database.ts";-import {- ROOM_CAPACITY,- RoomStore,- type CreatedRoom,-} from "../src/server/room-store.ts";--const allowedOrigin = "http://allowed.test";-let runningServer: ScreenerServer | undefined;--afterEach(async () => {- await runningServer?.close();- runningServer = undefined;-});--class MessageInbox {- private readonly messages: ServerMessage[] = [];- private readonly ignoredTypes = new Set<ServerMessage["type"]>();- private readonly waiters: Array<{- type: ServerMessage["type"];- resolve: (message: ServerMessage) => void;- reject: (error: Error) => void;- timer: NodeJS.Timeout;- }> = [];-- constructor(socket: WebSocket) {- socket.on("message", (data) => {- const message = decodeServerMessage(data.toString());- if (this.ignoredTypes.has(message.type)) {- return;- }- const waiterIndex = this.waiters.findIndex((waiter) => waiter.type === message.type);- if (waiterIndex === -1) {- this.messages.push(message);- return;- }- const [waiter] = this.waiters.splice(waiterIndex, 1);- clearTimeout(waiter.timer);- waiter.resolve(message);- });- }-- next<Type extends ServerMessage["type"]>(- type: Type,- timeoutMs = 1_000,- ): Promise<Extract<ServerMessage, { type: Type }>> {- const existingIndex = this.messages.findIndex((message) => message.type === type);- if (existingIndex !== -1) {- const [message] = this.messages.splice(existingIndex, 1);- return Promise.resolve(message as Extract<ServerMessage, { type: Type }>);- }-- return new Promise((resolve, reject) => {- const timer = setTimeout(() => {- const waiterIndex = this.waiters.findIndex((waiter) => waiter.timer === timer);- if (waiterIndex !== -1) {- this.waiters.splice(waiterIndex, 1);- }- reject(new Error(`Timed out waiting for ${type}`));- }, timeoutMs);- this.waiters.push({- type,- resolve: (message) =>- resolve(message as Extract<ServerMessage, { type: Type }>),- reject,- timer,- });- });- }-- async expectNone(timeoutMs: number): Promise<void> {- if (this.messages.length > 0) {- throw new Error(`Unexpected message: ${this.messages[0].type}`);- }- await new Promise((resolve) => setTimeout(resolve, timeoutMs));- if (this.messages.length > 0) {- throw new Error(`Unexpected message: ${this.messages[0].type}`);- }- }-- ignore(type: ServerMessage["type"]): void {- this.ignoredTypes.add(type);- for (let index = this.messages.length - 1; index >= 0; index -= 1) {- if (this.messages[index]?.type === type) {- this.messages.splice(index, 1);- }- }- }-}--interface TestClient {- socket: WebSocket;- inbox: MessageInbox;-}--interface SignalHarness {- baseUrl: string;- webSocketUrl: string;- roomStore: RoomStore;- room: CreatedRoom;-}--function testConfig(): ServerConfig {- return {- nodeEnv: "test",- port: 0,- listenHost: "127.0.0.1",- publicBaseUrl: new URL("https://share.example.test"),- allowedOrigins: new Set([allowedOrigin]),- roomLeaseMs: 86_400_000,- maxViewersPerRoom: 8,- peerAssistedMedia: false,- endpointMediaCopyCapacity: 2,- stunUrls: [],- natPredictionEnabled: false,- };-}--async function startHarness(- overrides: {- authenticationTimeoutMs?: number;- viewerDisconnectGraceMs?: number;- maxViewersPerRoom?: number;- maxSignalConnections?: number;- maxUnauthenticatedSignalConnections?: number;- siteAccessPassword?: string;- peerAssistedMedia?: boolean;- endpointMediaCopyCapacity?: number;- stunUrls?: readonly string[];- natPredictionEnabled?: boolean;- now?: () => number;- roomStore?: RoomStore;- room?: CreatedRoom;- } = {},-): Promise<SignalHarness> {- const config = testConfig();- config.siteAccessPassword = overrides.siteAccessPassword;- config.peerAssistedMedia = overrides.peerAssistedMedia ?? false;- config.endpointMediaCopyCapacity =- overrides.endpointMediaCopyCapacity ?? 2;- config.stunUrls = overrides.stunUrls ?? [];- config.natPredictionEnabled = overrides.natPredictionEnabled ?? false;- const maxViewersPerRoom = overrides.maxViewersPerRoom ?? 8;- config.maxViewersPerRoom = maxViewersPerRoom;- const roomStore =- overrides.roomStore ??- new RoomStore({- leaseMs: config.roomLeaseMs,- maxRooms: ROOM_CAPACITY,- maxViewersPerRoom,- now: overrides.now,- });- const room = overrides.room ?? (await roomStore.createRoom());- runningServer = await createScreenerServer({- config,- roomStore,- frontend: { mode: "none" },- now: overrides.now,- authenticationTimeoutMs: overrides.authenticationTimeoutMs ?? 500,- viewerDisconnectGraceMs: overrides.viewerDisconnectGraceMs ?? 50,- heartbeatIntervalMs: 60_000,- cleanupIntervalMs: 60_000,- maxSignalConnections: overrides.maxSignalConnections,- maxUnauthenticatedSignalConnections:- overrides.maxUnauthenticatedSignalConnections,- });- const port = await runningServer.listen(0, "127.0.0.1");- return {- baseUrl: `http://127.0.0.1:${port}`,- webSocketUrl: `ws://127.0.0.1:${port}/signal`,- roomStore,- room,- };-}--async function updateRoomAccess(- harness: SignalHarness,- request: RoomAccessUpdateRequest,-) {- const response = await fetch(- `${harness.baseUrl}/api/rooms/${harness.room.roomId}/access`,- {- method: "POST",- headers: {- Authorization: `Bearer ${harness.room.hostToken}`,- "Content-Type": "application/json",- Origin: allowedOrigin,- },- body: JSON.stringify(request),- },- );- expect(response.status).toBe(200);- return roomAccessUpdateResponseSchema.parse(await response.json());-}--async function openClient(- webSocketUrl: string,- cookie?: string,-): Promise<TestClient> {- const socket = new WebSocket(webSocketUrl, {- origin: allowedOrigin,- headers: cookie ? { Cookie: cookie } : undefined,- });- await new Promise<void>((resolve, reject) => {- socket.once("open", resolve);- socket.once("error", reject);- });- return { socket, inbox: new MessageInbox(socket) };-}--async function rejectedUpgradeStatus(- webSocketUrl: string,- origin = allowedOrigin,-): Promise<number | undefined> {- const socket = new WebSocket(webSocketUrl, { origin });- socket.on("error", () => {- // The HTTP status is asserted through unexpected-response below.- });- return new Promise((resolve, reject) => {- socket.once("open", () => reject(new Error("WebSocket upgrade unexpectedly succeeded")));- socket.once("unexpected-response", (_request, response) => {- const status = response.statusCode;- response.resume();- resolve(status);- });- });-}--async function rawUpgradeResponse(- webSocketUrl: string,- requestTarget: string,-): Promise<string> {- const url = new URL(webSocketUrl);- return new Promise((resolve, reject) => {- const chunks: Buffer[] = [];- const socket = connect(Number(url.port), url.hostname);- socket.setTimeout(2_000, () => socket.destroy(new Error("Raw upgrade timed out")));- socket.on("error", reject);- socket.on("data", (chunk) => chunks.push(chunk));- socket.on("close", () => resolve(Buffer.concat(chunks).toString("utf8")));- socket.on("connect", () => {- socket.write(- [- `GET ${requestTarget} HTTP/1.1`,- `Host: ${url.host}`,- "Upgrade: websocket",- "Connection: Upgrade",- "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==",- "Sec-WebSocket-Version: 13",- `Origin: ${allowedOrigin}`,- "",- "",- ].join("\r\n"),- );- });- });-}--async function authenticate(- client: TestClient,- room: CreatedRoom,- role: Role,- clientId: string,- relayCapacity: 0 | 1 | 2 | 3 | null = 1,- shareGeneration?: string,- presence: {- displayName?: string;- viewerPresence?: true;- viewerPassword?: string;- codeOnly?: true;- sharingPaused?: boolean;- qualitySettings?: QualitySettings;- routePolicy?: RoutePolicy;- } = {},-) {- client.socket.send(- JSON.stringify(- role === "host"- ? {- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: room.roomId,- role,- token: room.hostToken,- clientId,- ...(shareGeneration ? { shareGeneration } : {}),- ...(presence.sharingPaused !== undefined- ? { sharingPaused: presence.sharingPaused }- : {}),- ...(presence.qualitySettings- ? { qualitySettings: presence.qualitySettings }- : {}),- ...(presence.routePolicy- ? { routePolicy: presence.routePolicy }- : {}),- ...(presence.viewerPresence ? { viewerPresence: true } : {}),- ...(presence.displayName- ? { displayName: presence.displayName }- : {}),- }- : {- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: room.roomId,- role,- clientId,- ...(presence.viewerPassword- ? { viewerPassword: presence.viewerPassword }- : !presence.codeOnly && room.viewerGrant- ? { viewerGrant: room.viewerGrant }- : {}),- ...(presence.displayName- ? { displayName: presence.displayName }- : {}),- ...(presence.viewerPresence ? { viewerPresence: true } : {}),- },- ),- );- const authenticated = await client.inbox.next("authenticated");- if (- role === "viewer" &&- relayCapacity !== null &&- "mediaMode" in authenticated- ) {- client.socket.send(- JSON.stringify({- type: "relay-capacity",- downstreamEdges: relayCapacity,- }),- );- }- return authenticated;-}--function peerAssisted(- message: Extract<ServerMessage, { type: "authenticated" }>,-) {- if (!("mediaMode" in message)) {- throw new Error("Expected a peer-assisted authenticated message");- }- return message;-}--async function nextViewerPresenceMatching(- client: TestClient,- predicate: (- message: Extract<ServerMessage, { type: "viewer-presence" }>,- ) => boolean,-) {- for (let attempt = 0; attempt < 20; attempt += 1) {- const message = await client.inbox.next("viewer-presence");- if (predicate(message)) {- return message;- }- }- throw new Error("Viewer presence did not reach the expected state");-}--function viewerPresenceEntries(- message: Extract<ServerMessage, { type: "viewer-presence" }>,-) {- return message.viewers.filter((participant) => participant.role === "viewer");-}--function hostPresenceEntry(- message: Extract<ServerMessage, { type: "viewer-presence" }>,-) {- return message.viewers.find((participant) => participant.role === "host");-}--async function nextPreparedRoute(client: TestClient) {- while (true) {- const message = await client.inbox.next("route-update");- if (message.phase === "prepare") {- return message;- }- }-}--async function nextActiveRouteRevision(client: TestClient, revision: number) {- while (true) {- const message = await client.inbox.next("route-update");- if (message.phase === "active" && message.revision === revision) {- return message;- }- }-}--function viewerQualityEvidenceMessage(- connectionId: string,- routeRevision: number,- sequence = 0,- presentationEpoch = 0,-) {- return {- type: "viewer-quality-evidence" as const,- guard: { connectionId, routeRevision, presentationEpoch },- sequence,- windowMs: 2_000,- metrics: {- natTraversalPath: "ordinary",- width: 1_920,- height: 1_080,- framesPerSecond: 60,- bitrateKbps: 7_500,- packetsReceivedDelta: 1_500,- packetsLostDelta: 2,- rttMs: 18,- jitterMs: 3.5,- framesDecodedDelta: 120,- framesDroppedDelta: 1,- decodeMsPerFrame: 2.4,- freezeCountDelta: 0,- freezeDurationMsDelta: 0,- pauseCountDelta: 0,- pauseDurationMsDelta: 0,- codec: "video/VP8",- codecProfile: null,- codecParameters: null,- audioBitrateKbps: 192,- audioPacketLossPercent: 0.2,- audioJitterMs: 2.5,- audioVideoPlayoutDeltaMs: -12.5,- videoJitterBufferDelayMs: 24,- audioJitterBufferDelayMs: 18,- audioConcealedSamplesPercent: 1,- audioConcealmentEventsDelta: 3,- audioCodec: "audio/opus",- },- };-}--async function closeClient(client: TestClient): Promise<void> {- if (client.socket.readyState === WebSocket.CLOSED) {- return;- }- const closed = new Promise<void>((resolve) => client.socket.once("close", () => resolve()));- client.socket.close();- await closed;-}--describe("WebSocket signaling", () => {- it("echoes the exact per-share route policy authority", async () => {- const harness = await startHarness({- peerAssistedMedia: true,- stunUrls: ["stun:share.example.test:3478"],- natPredictionEnabled: true,- });- const viewer = await openClient(harness.webSocketUrl);- const waiting = peerAssisted(- await authenticate(- viewer,- harness.room,- "viewer",- "route-policy-viewer",- 1,- ),- );- expect(waiting.shareGeneration).toBeNull();- const host = await openClient(harness.webSocketUrl);- const routePolicy = {- peerOnly: true,- topologyOptimization: true,- natPrediction: true,- } as const;- const authenticated = peerAssisted(- await authenticate(- host,- harness.room,- "host",- "route-policy-host",- 1,- "route_policy_share_generation_12345678",- { routePolicy },- ),- );- expect(authenticated.routePolicy).toEqual(routePolicy);- expect("sfuStandbyUrl" in authenticated).toBe(false);- expect(await viewer.inbox.next("route-policy")).toEqual({- type: "route-policy",- shareGeneration: "route_policy_share_generation_12345678",- routePolicy,- });- });-- it("broadcasts configured NAT prediction in lightweight rooms", async () => {- const harness = await startHarness({- peerAssistedMedia: false,- stunUrls: ["stun:share.example.test:3478"],- natPredictionEnabled: true,- });- const waitingViewer = await openClient(harness.webSocketUrl);- const waiting = await authenticate(- waitingViewer,- harness.room,- "viewer",- "ordinary-nat-waiting-viewer",- null,- );- expect(waiting.routePolicy.natPrediction).toBe(false);-- const host = await openClient(harness.webSocketUrl);- const routePolicy = {- ...DEFAULT_ROUTE_POLICY,- natPrediction: true,- };- const hostAuth = await authenticate(- host,- harness.room,- "host",- "ordinary-nat-host",- null,- "ordinary_nat_share_generation_12345678",- { routePolicy },- );- expect(hostAuth.routePolicy).toEqual(routePolicy);- expect(await waitingViewer.inbox.next("route-policy")).toMatchObject({- routePolicy,- });-- const joiningViewer = await openClient(harness.webSocketUrl);- const joined = await authenticate(- joiningViewer,- harness.room,- "viewer",- "ordinary-nat-joining-viewer",- null,- );- expect(joined.routePolicy).toEqual(routePolicy);- });-- it("clamps NAT prediction off when the server capability is disabled", async () => {- const harness = await startHarness({ peerAssistedMedia: false });- const host = await openClient(harness.webSocketUrl);- const authenticated = await authenticate(- host,- harness.room,- "host",- "disabled-nat-host",- null,- "disabled_nat_share_generation_12345678",- {- routePolicy: {- ...DEFAULT_ROUTE_POLICY,- natPrediction: true,- },- },- );-- expect(authenticated.routePolicy.natPrediction).toBe(false);- });-- it("delivers only self-hosted auxiliary NAT STUN endpoints", async () => {- const harness = await startHarness({- stunUrls: ["stun:ordinary.example.test:3478"],- natPredictionEnabled: true,- });- const viewer = await openClient(harness.webSocketUrl);- const authenticated = await authenticate(- viewer,- harness.room,- "viewer",- "nat-auxiliary-viewer",- null,- );-- expect(authenticated.iceConfig).toEqual({- iceServers: [{ urls: ["stun:ordinary.example.test:3478"] }],- natPredictionStunUrls: [- "stun:ordinary.example.test:3479",- "stun:ordinary.example.test:3480",- ],- });- });-- it("rebuilds a route when a Viewer reconnects before the Host after restart", async () => {- const directory = mkdtempSync(join(tmpdir(), "screener-route-restart-"));- const path = join(directory, "rooms.sqlite");- try {- const firstStore = new RoomStore({- leaseMs: 86_400_000,- maxRooms: ROOM_CAPACITY,- maxViewersPerRoom: 8,- database: new RoomDatabase(path),- });- firstStore.initialize();- const room = await firstStore.createRoom();- const first = await startHarness({- peerAssistedMedia: true,- roomStore: firstStore,- room,- });- const firstHost = await openClient(first.webSocketUrl);- await authenticate(- firstHost,- room,- "host",- "restart-route-host",- 1,- "restart_share_generation_12345678",- );- const firstViewer = await openClient(first.webSocketUrl);- await authenticate(- firstViewer,- room,- "viewer",- "restart-route-viewer",- 1,- );- await nextPreparedRoute(firstViewer);-- const firstServer = runningServer!;- runningServer = undefined;- await firstServer.close();-- const secondStore = new RoomStore({- leaseMs: 86_400_000,- maxRooms: ROOM_CAPACITY,- maxViewersPerRoom: 8,- database: new RoomDatabase(path),- });- secondStore.initialize();- const second = await startHarness({- peerAssistedMedia: true,- roomStore: secondStore,- room,- });- const secondViewer = await openClient(second.webSocketUrl);- const viewerAuth = peerAssisted(- await authenticate(- secondViewer,- room,- "viewer",- "restart-route-viewer",- 1,- ),- );- expect(viewerAuth.routeAssignment.upstream).toEqual({ kind: "none" });-- const secondHost = await openClient(second.webSocketUrl);- await authenticate(- secondHost,- room,- "host",- "restart-route-host",- 1,- "restart_share_generation_12345678",- );- const viewerPrepare = await nextPreparedRoute(secondViewer);- const hostPrepare = await nextPreparedRoute(secondHost);- expect(viewerPrepare).toMatchObject({- revision: hostPrepare.revision,- candidate: hostPrepare.candidate,- });- } finally {- await runningServer?.close();- runningServer = undefined;- rmSync(directory, { recursive: true, force: true });- }- });-- it("identifies a graceful service restart to connected clients", async () => {- const harness = await startHarness();- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "restart-host");- const closed = new Promise<{ code: number; reason: string }>((resolve) =>- host.socket.once("close", (code, reason) =>- resolve({ code, reason: reason.toString() }),- ),- );- const server = runningServer!;- runningServer = undefined;-- const shutdown = server.close();-- await expect(closed).resolves.toEqual({- code: 1012,- reason: "Service restart",- });- await shutdown;- });-- it("ends every room before a local authority stops", async () => {- const harness = await startHarness();- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "ending-host");- const viewer = await openClient(harness.webSocketUrl);- await authenticate(viewer, harness.room, "viewer", "ending-viewer");- const hostClosed = new Promise<{ code: number; reason: string }>((resolve) =>- host.socket.once("close", (code, reason) =>- resolve({ code, reason: reason.toString() }),- ),- );- const viewerClosed = new Promise<{ code: number; reason: string }>((resolve) =>- viewer.socket.once("close", (code, reason) =>- resolve({ code, reason: reason.toString() }),- ),- );- const server = runningServer!;- runningServer = undefined;-- const shutdown = server.end();-- await expect(host.inbox.next("room-closed")).resolves.toEqual({- type: "room-closed",- reason: "host-ended",- });- await expect(viewer.inbox.next("room-closed")).resolves.toEqual({- type: "room-closed",- reason: "host-ended",- });- await expect(hostClosed).resolves.toEqual({- code: 1000,- reason: "Room abandoned",- });- await expect(viewerClosed).resolves.toEqual({- code: 1000,- reason: "Room abandoned",- });- await shutdown;- expect(harness.roomStore.size).toBe(0);- });-- it("answers only opted-in current sockets and rate-limits each socket", async () => {- let now = Date.now();- const harness = await startHarness({ now: () => now });- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "challenge-host");-- host.socket.send(- JSON.stringify({ type: "signaling-challenge", sequence: 7 }),- );- expect(await host.inbox.next("signaling-challenge-response")).toEqual({- type: "signaling-challenge-response",- sequence: 7,- });-- host.socket.send(- JSON.stringify({ type: "signaling-challenge", sequence: 8 }),- );- await host.inbox.expectNone(40);-- now += 1_000;- host.socket.send(- JSON.stringify({ type: "signaling-challenge", sequence: 9 }),- );- expect(await host.inbox.next("signaling-challenge-response")).toEqual({- type: "signaling-challenge-response",- sequence: 9,- });- });-- it("serves one current route snapshot only to the authenticated Host", async () => {- const harness = await startHarness({ peerAssistedMedia: true });- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "route-diagnostic-host");- const viewer = await openClient(harness.webSocketUrl);- await authenticate(- viewer,- harness.room,- "viewer",- "route-diagnostic-viewer",- );-- host.socket.send(JSON.stringify({ type: "request-route-diagnostic" }));- expect(await host.inbox.next("route-diagnostic-snapshot")).toMatchObject({- snapshot: {- children: [{ ordinal: 1, finalRoute: "waiting" }],- },- });-- viewer.socket.send(JSON.stringify({ type: "request-route-diagnostic" }));- expect(await viewer.inbox.next("error")).toMatchObject({- code: "FORBIDDEN",- });- });-- it("keeps the exact Native Host wire unchanged without a presence opt-in", async () => {- const harness = await startHarness();- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "native-compatible-host");- const viewer = await openClient(harness.webSocketUrl);- await authenticate(- viewer,- harness.room,- "viewer",- "native-compatible-viewer",- 1,- undefined,- { displayName: "移动观众" },- );-- await host.inbox.next("peer-joined");- await host.inbox.expectNone(40);-- host.socket.send(- JSON.stringify({ type: "set-display-name", displayName: "Native 不应改名" }),- );- expect(await host.inbox.next("error")).toMatchObject({- code: "FORBIDDEN",- });- await host.inbox.expectNone(40);- });-- it("keeps a password optional for private room entry", async () => {- const harness = await startHarness();- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "password-settings-host");-- expect(- await updateRoomAccess(harness, {- action: "set-code-entry-policy",- policy: "private",- }),- ).toEqual({- type: "code-entry-policy-updated",- codeEntryPolicy: "private",- viewerPasswordEnabled: false,- });-- const wrongViewer = await openClient(harness.webSocketUrl);- wrongViewer.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: harness.room.roomId,- role: "viewer",- clientId: "wrong-password-viewer",- viewerPassword: "wrong-password",- }),- );- expect(await wrongViewer.inbox.next("error")).toMatchObject({- code: "ROOM_ACCESS_DENIED",- });-- expect(- await updateRoomAccess(harness, {- action: "set-viewer-password",- password: "easy-password",- }),- ).toEqual({- type: "viewer-password-updated",- enabled: true,- });-- const passwordViewer = await openClient(harness.webSocketUrl);- await expect(- authenticate(- passwordViewer,- harness.room,- "viewer",- "password-viewer",- 1,- undefined,- { viewerPassword: "easy-password" },- ),- ).resolves.toMatchObject({ role: "viewer" });- await host.inbox.next("peer-joined");-- expect(- await updateRoomAccess(harness, {- action: "set-viewer-password",- password: null,- }),- ).toEqual({- type: "viewer-password-updated",- enabled: false,- });-- const grantViewer = await openClient(harness.webSocketUrl);- await expect(- authenticate(- grantViewer,- harness.room,- "viewer",- "grant-after-password-removal",- ),- ).resolves.toMatchObject({ role: "viewer" });- await host.inbox.next("peer-joined");-- const removedPasswordViewer = await openClient(harness.webSocketUrl);- removedPasswordViewer.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: harness.room.roomId,- role: "viewer",- clientId: "removed-password-viewer",- viewerPassword: "easy-password",- }),- );- expect(await removedPasswordViewer.inbox.next("error")).toMatchObject({- code: "ROOM_ACCESS_DENIED",- });- });-- it("reports password configuration only to the authenticated Host", async () => {- const harness = await startHarness();- harness.roomStore.setCodeEntryPolicy(- harness.room.roomId,- "private",- harness.room.hostToken,- );-- const host = await openClient(harness.webSocketUrl);- const withoutPassword = await authenticate(- host,- harness.room,- "host",- "password-state-host",- );- expect(withoutPassword).toMatchObject({- role: "host",- codeEntryPolicy: "private",- viewerPasswordEnabled: false,- });-- const viewer = await openClient(harness.webSocketUrl);- const viewerAuthenticated = await authenticate(- viewer,- harness.room,- "viewer",- "password-state-viewer",- );- expect(viewerAuthenticated).not.toHaveProperty("viewerPasswordEnabled");-- await harness.roomStore.setViewerPassword(- harness.room.roomId,- "room-password",- harness.room.hostToken,- );- const replacementHost = await openClient(harness.webSocketUrl);- const withPassword = await authenticate(- replacementHost,- harness.room,- "host",- "password-state-host",- );- expect(withPassword).toMatchObject({- role: "host",- codeEntryPolicy: "private",- viewerPasswordEnabled: true,- });- });-- it("reports every online Viewer without expanding the Host media fanout", async () => {- const harness = await startHarness({ peerAssistedMedia: true });- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "presence-host",- 1,- undefined,- { viewerPresence: true },- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toEqual([]);-- const viewerNames = ["阿明", "阿青", undefined] as const;- const viewers: TestClient[] = [];- for (const [index, displayName] of viewerNames.entries()) {- const viewer = await openClient(harness.webSocketUrl);- viewers.push(viewer);- const authenticated = peerAssisted(- await authenticate(- viewer,- harness.room,- "viewer",- `presence-viewer-${index}`,- 1,- undefined,- displayName ? { displayName } : {},- ),- );- const prepared = await Promise.race([- nextPreparedRoute(viewer),- host.inbox.next("error").then((error) => {- throw new Error(`route error: ${error.message}`);- }),- ]);- viewer.socket.send(- JSON.stringify({- type: "route-transport-connected",- revision: prepared.revision,- connectionId: prepared.candidate.connectionId,- }),- );- viewer.socket.send(- JSON.stringify({- type: "route-ready",- revision: prepared.revision,- phase: "prepare",- }),- );- expect(prepared.revision).toBeGreaterThan(authenticated.routeRevision);- await nextActiveRouteRevision(viewer, prepared.revision);- }-- const full = await nextViewerPresenceMatching(- host,- (message) =>- viewerPresenceEntries(message).length === 3 &&- viewerPresenceEntries(message).some(- (viewer) =>- viewer.upstream.kind === "peer" &&- viewer.upstream.peerId !== hostAuth.peerId,- ),- );- expect(viewerPresenceEntries(full).map((viewer) => viewer.displayName)).toEqual([- "阿明",- "阿青",- "观众",- ]);- expect(- viewerPresenceEntries(full).filter(- (viewer) =>- viewer.upstream.kind === "peer" &&- viewer.upstream.peerId === hostAuth.peerId,- ),- ).toHaveLength(2);- expect(- viewerPresenceEntries(full).every((viewer) => viewer.mediaReady === true),- ).toBe(true);- const relay = viewerPresenceEntries(full).find(- (viewer) =>- viewer.upstream.kind === "peer" &&- viewer.upstream.peerId !== hostAuth.peerId,- )!;- const relayParentPeerId =- relay.upstream.kind === "peer" ? relay.upstream.peerId : null;- expect(- viewerPresenceEntries(full).some(- (viewer) => viewer.peerId === relayParentPeerId,- ),- ).toBe(true);- host.inbox.ignore("route-update");- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: relay.peerId,- payload: {- kind: "candidate",- connectionId: "stale_connection_12345678",- candidate: null,- },- }),- );- await host.inbox.expectNone(40);-- viewers[2].socket.send(- JSON.stringify({ type: "set-display-name", displayName: "后来改名" }),- );- const renamed = await nextViewerPresenceMatching(host, (message) =>- viewerPresenceEntries(message).some(- (viewer) => viewer.displayName === "后来改名",- ),- );- expect(viewerPresenceEntries(renamed)).toHaveLength(3);-- await closeClient(viewers[2]);- const afterDisconnect = await nextViewerPresenceMatching(- host,- (message) => viewerPresenceEntries(message).length === 2,- );- expect(- viewerPresenceEntries(afterDisconnect).map((viewer) => viewer.displayName),- ).toEqual([- "阿明",- "阿青",- ]);- });-- it("forwards exact direct Viewer receive evidence to the Host", async () => {- let now = 10_000;- const harness = await startHarness({ now: () => now });- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "evidence-direct-host",- 1,- undefined,- { viewerPresence: true },- );- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- "evidence-direct-viewer",- );- host.inbox.ignore("viewer-presence");- await host.inbox.next("peer-joined");- const connectionId = "evidence_direct_connection_12345678";- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerAuth.peerId,- payload: {- kind: "description",- connectionId,- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- await viewer.inbox.next("signal");-- viewer.socket.send(- JSON.stringify(viewerQualityEvidenceMessage(connectionId, 0)),- );- expect(await host.inbox.next("viewer-quality-evidence")).toMatchObject({- viewerPeerId: viewerAuth.peerId,- upstream: { kind: "peer", peerId: hostAuth.peerId },- guard: { connectionId, routeRevision: 0 },- });-- viewer.socket.send(- JSON.stringify(viewerQualityEvidenceMessage(connectionId, 0, 0, 1)),- );- await host.inbox.expectNone(40);- now += 2_000;- viewer.socket.send(- JSON.stringify(viewerQualityEvidenceMessage(connectionId, 0, 7, 1)),- );- expect(await host.inbox.next("viewer-quality-evidence")).toMatchObject({- guard: { connectionId, routeRevision: 0, presentationEpoch: 1 },- sequence: 7,- });- now += 2_000;- viewer.socket.send(- JSON.stringify(viewerQualityEvidenceMessage(connectionId, 0, 1, 0)),- );- await host.inbox.expectNone(40);- viewer.socket.send(- JSON.stringify(viewerQualityEvidenceMessage(connectionId, 0, 0, 2)),- );- await host.inbox.expectNone(40);- now += 2_000;- viewer.socket.send(- JSON.stringify(viewerQualityEvidenceMessage(connectionId, 0, 9, 2)),- );- expect(await host.inbox.next("viewer-quality-evidence")).toMatchObject({- guard: { connectionId, routeRevision: 0, presentationEpoch: 2 },- sequence: 9,- });- });-- it("forwards a relayed child receive report to its exact parent and Host", async () => {- let now = 10_000;- const harness = await startHarness({- peerAssistedMedia: true,- endpointMediaCopyCapacity: 1,- now: () => now,- });- const host = await openClient(harness.webSocketUrl);- await authenticate(- host,- harness.room,- "host",- "evidence-relay-host",- 1,- undefined,- { viewerPresence: true },- );- const parent = await openClient(harness.webSocketUrl);- const parentAuth = peerAssisted(- await authenticate(- parent,- harness.room,- "viewer",- "evidence-relay-parent",- 1,- ),- );- const parentPrepare = await nextPreparedRoute(parent);- parent.socket.send(- JSON.stringify({- type: "route-ready",- revision: parentPrepare.revision,- phase: "prepare",- }),- );- await nextActiveRouteRevision(parent, parentPrepare.revision);-- const child = await openClient(harness.webSocketUrl);- const childAuth = peerAssisted(- await authenticate(- child,- harness.room,- "viewer",- "evidence-relay-child",- 1,- ),- );- const childPrepare = await nextPreparedRoute(child);- expect(childPrepare.assignment.upstream).toEqual({- kind: "peer",- peerId: parentAuth.peerId,- });- child.socket.send(- JSON.stringify({- type: "route-ready",- revision: childPrepare.revision,- phase: "prepare",- }),- );- await nextActiveRouteRevision(child, childPrepare.revision);-- child.socket.send(- JSON.stringify(- viewerQualityEvidenceMessage(- childPrepare.candidate.connectionId,- childPrepare.revision,- ),- ),- );- const expected = {- viewerPeerId: childAuth.peerId,- upstream: { kind: "peer", peerId: parentAuth.peerId },- guard: {- connectionId: childPrepare.candidate.connectionId,- routeRevision: childPrepare.revision,- },- };- expect(await parent.inbox.next("viewer-quality-evidence")).toMatchObject(- expected,- );- expect(await host.inbox.next("viewer-quality-evidence")).toMatchObject(- expected,- );- host.socket.send(JSON.stringify({ type: "request-route-diagnostic" }));- const diagnostic = await host.inbox.next("route-diagnostic-snapshot");- expect(- diagnostic.snapshot.children.find((entry) => entry.quality !== null)- ?.quality,- ).toEqual({- eligibleWindows: 1,- eligibleDurationMs: 2_000,- freezeWindows: 0,- freezeCount: 0,- freezeDurationMs: 0,- pauseCount: 0,- pauseDurationMs: 0,- });-- now += 2_000;- const incomplete = viewerQualityEvidenceMessage(- childPrepare.candidate.connectionId,- childPrepare.revision,- 1,- );- child.socket.send(- JSON.stringify({- ...incomplete,- metrics: { ...incomplete.metrics, pauseCountDelta: null },- }),- );- expect(await parent.inbox.next("viewer-quality-evidence")).toMatchObject({- metrics: { pauseCountDelta: null },- });- expect(await host.inbox.next("viewer-quality-evidence")).toMatchObject({- metrics: { pauseCountDelta: null },- });- host.socket.send(JSON.stringify({ type: "request-route-diagnostic" }));- const unchanged = await host.inbox.next("route-diagnostic-snapshot");- expect(- unchanged.snapshot.children.find((entry) => entry.quality !== null)- ?.quality?.eligibleWindows,- ).toBe(1);- });-- it("shares an opted-in Host name with Host and Viewer roster subscribers", async () => {- const harness = await startHarness();- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "named-host-client",- 1,- undefined,- { viewerPresence: true, displayName: "原始分享者" },- );- const initial = await host.inbox.next("viewer-presence");- expect(hostPresenceEntry(initial)).toMatchObject({- role: "host",- peerId: hostAuth.peerId,- displayName: "原始分享者",- upstream: { kind: "none" },- });-- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- "named-viewer-client",- 1,- undefined,- { viewerPresence: true, displayName: "观看者" },- );- const viewerSnapshot = await nextViewerPresenceMatching(- viewer,- (message) => hostPresenceEntry(message)?.displayName === "原始分享者",- );- expect(hostPresenceEntry(viewerSnapshot)?.peerId).toBe(hostAuth.peerId);- expect(- viewerPresenceEntries(viewerSnapshot).some(- (entry) => entry.peerId === viewerAuth.peerId,- ),- ).toBe(true);-- const hostSnapshot = await nextViewerPresenceMatching(- host,- (message) =>- hostPresenceEntry(message)?.displayName === "原始分享者" &&- viewerPresenceEntries(message).length === 1,- );- expect(hostPresenceEntry(hostSnapshot)?.peerId).toBe(hostAuth.peerId);-- host.socket.send(- JSON.stringify({ type: "set-display-name", displayName: "改名后的分享者" }),- );- const renamedViewer = await nextViewerPresenceMatching(- viewer,- (message) => hostPresenceEntry(message)?.displayName === "改名后的分享者",- );- expect(hostPresenceEntry(renamedViewer)?.peerId).toBe(hostAuth.peerId);- const renamedHost = await nextViewerPresenceMatching(- host,- (message) => hostPresenceEntry(message)?.displayName === "改名后的分享者",- );- expect(hostPresenceEntry(renamedHost)?.peerId).toBe(hostAuth.peerId);- });-- it("replaces an opted-in Viewer roster after another Viewer leaves", async () => {- const harness = await startHarness();- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "viewer-roster-host");-- const subscriber = await openClient(harness.webSocketUrl);- const subscriberAuth = await authenticate(- subscriber,- harness.room,- "viewer",- "viewer-roster-subscriber",- 1,- undefined,- { viewerPresence: true, displayName: "订阅者" },- );- await nextViewerPresenceMatching(- subscriber,- (message) => viewerPresenceEntries(message).length === 1,- );-- const other = await openClient(harness.webSocketUrl);- const otherAuth = await authenticate(- other,- harness.room,- "viewer",- "viewer-roster-other",- 1,- undefined,- { displayName: "另一位" },- );- const joined = await nextViewerPresenceMatching(- subscriber,- (message) => viewerPresenceEntries(message).length === 2,- );- expect(viewerPresenceEntries(joined).map((viewer) => viewer.peerId)).toEqual([- subscriberAuth.peerId,- otherAuth.peerId,- ]);-- await closeClient(other);- const left = await nextViewerPresenceMatching(- subscriber,- (message) => viewerPresenceEntries(message).length === 1,- );- expect(viewerPresenceEntries(left).map((viewer) => viewer.peerId)).toEqual([- subscriberAuth.peerId,- ]);- });-- it("clears a disconnected Host name and publishes the replacement name", async () => {- const harness = await startHarness({ viewerDisconnectGraceMs: 40 });- const firstHost = await openClient(harness.webSocketUrl);- const firstAuth = await authenticate(- firstHost,- harness.room,- "host",- "replaceable-host-client",- 1,- undefined,- { viewerPresence: true, displayName: "旧分享者" },- );- await firstHost.inbox.next("viewer-presence");-- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- "replacement-roster-viewer",- 1,- undefined,- { viewerPresence: true },- );- await nextViewerPresenceMatching(- viewer,- (message) => hostPresenceEntry(message)?.displayName === "旧分享者",- );-- await closeClient(firstHost);- await viewer.inbox.next("host-status");- const offline = await nextViewerPresenceMatching(- viewer,- (message) => hostPresenceEntry(message) === undefined,- );- expect(offline.viewers.some((entry) => entry.role === "host")).toBe(false);- expect(viewerPresenceEntries(offline)).toMatchObject([- { peerId: viewerAuth.peerId, upstream: { kind: "none" } },- ]);-- const replacement = await openClient(harness.webSocketUrl);- const replacementAuth = await authenticate(- replacement,- harness.room,- "host",- "replaceable-host-client",- 1,- undefined,- { viewerPresence: true, displayName: "新分享者" },- );- expect(replacementAuth.peerId).toBe(firstAuth.peerId);- const online = await nextViewerPresenceMatching(- viewer,- (message) => hostPresenceEntry(message)?.displayName === "新分享者",- );- expect(hostPresenceEntry(online)?.peerId).toBe(firstAuth.peerId);- await closeClient(replacement);- await closeClient(viewer);- });-- it("strongly rotates and revokes every Viewer generation and media edge", async () => {- const harness = await startHarness();- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "ordinary-access-presence-host",- 1,- undefined,- { viewerPresence: true },- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toEqual([]);-- const firstViewer = await openClient(harness.webSocketUrl);- const firstViewerAuth = await authenticate(- firstViewer,- harness.room,- "viewer",- "ordinary-access-presence-viewer-1",- 1,- undefined,- { displayName: "第一位" },- );- expect((await host.inbox.next("peer-joined")).peerId).toBe(- firstViewerAuth.peerId,- );- expect(viewerPresenceEntries(await host.inbox.next("viewer-presence"))).toEqual([- {- role: "viewer",- peerId: firstViewerAuth.peerId,- displayName: "第一位",- upstream: { kind: "peer", peerId: hostAuth.peerId },- },- ]);-- const firstClosed = new Promise<number>((resolve) =>- firstViewer.socket.once("close", (code) => resolve(code)),- );- const rotated = await updateRoomAccess(harness, {- action: "rotate-viewer-grant",- });- expect(await firstViewer.inbox.next("viewer-grant-revoked")).toMatchObject({- viewerAuthorizationGeneration:- firstViewerAuth.viewerAuthorizationGeneration,- });- expect(await firstClosed).toBe(4004);- expect((await host.inbox.next("peer-left")).peerId).toBe(- firstViewerAuth.peerId,- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toEqual([]);- await host.inbox.expectNone(30);-- expect(rotated.type).toBe("viewer-grant-updated");- if (rotated.type !== "viewer-grant-updated") {- throw new Error("Expected a rotated Viewer grant");- }-- const rotatedGrant = new URLSearchParams(- new URL(rotated.inviteUrl!).hash.slice(1),- ).get("v");- expect(rotatedGrant).toBeTruthy();- const rotatedRoom = {- ...harness.room,- viewerGrant: rotatedGrant,- } satisfies CreatedRoom;- const secondViewer = await openClient(harness.webSocketUrl);- const secondViewerAuth = await authenticate(- secondViewer,- rotatedRoom,- "viewer",- "ordinary-access-presence-viewer-2",- 1,- undefined,- { displayName: "第二位" },- );- expect((await host.inbox.next("peer-joined")).peerId).toBe(- secondViewerAuth.peerId,- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toHaveLength(1);-- const secondClosed = new Promise<number>((resolve) =>- secondViewer.socket.once("close", (code) => resolve(code)),- );- const revoked = await updateRoomAccess(harness, {- action: "revoke-viewer-grant",- });- await secondViewer.inbox.next("viewer-grant-revoked");- expect(await secondClosed).toBe(4004);- expect((await host.inbox.next("peer-left")).peerId).toBe(- secondViewerAuth.peerId,- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toEqual([]);- expect(revoked).toMatchObject({- inviteUrl: null,- });- await host.inbox.expectNone(30);- });-- it("rotates a grant and promotes the waiting code-admitted Viewer", async () => {- const harness = await startHarness({- endpointMediaCopyCapacity: 1,- maxViewersPerRoom: 2,- });- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "mixed-access-host",- 2,- undefined,- { viewerPresence: true },- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toEqual([]);-- const grantViewer = await openClient(harness.webSocketUrl);- const grantAuth = await authenticate(- grantViewer,- harness.room,- "viewer",- "mixed-grant-viewer",- 1,- undefined,- { displayName: "邀请观众" },- );- await host.inbox.next("peer-joined");- await host.inbox.next("viewer-presence");-- const codeViewer = await openClient(harness.webSocketUrl);- const codeAuth = await authenticate(- codeViewer,- harness.room,- "viewer",- "mixed-code-viewer",- 1,- undefined,- { codeOnly: true, displayName: "房间号观众" },- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toHaveLength(2);- expect((await host.inbox.next("peer-waiting")).peerId).toBe(codeAuth.peerId);-- const grantClosed = new Promise<number>((resolve) =>- grantViewer.socket.once("close", (code) => resolve(code)),- );- await updateRoomAccess(harness, { action: "rotate-viewer-grant" });- await grantViewer.inbox.next("viewer-grant-revoked");- expect(await grantClosed).toBe(4004);- expect((await host.inbox.next("peer-left")).peerId).toBe(grantAuth.peerId);- expect((await host.inbox.next("peer-joined")).peerId).toBe(codeAuth.peerId);-- const remaining = viewerPresenceEntries(- await host.inbox.next("viewer-presence"),- );- expect(remaining).toEqual([- {- role: "viewer",- peerId: codeAuth.peerId,- displayName: "房间号观众",- upstream: { kind: "peer", peerId: hostAuth.peerId },- },- ]);- expect(codeViewer.socket.readyState).toBe(WebSocket.OPEN);- expect(- harness.roomStore.getConnectedViewer(harness.room.roomId, codeAuth.peerId),- ).toBeDefined();-- await closeClient(codeViewer);- await closeClient(host);- });-- it("requires site access for code-only Viewers while accepting room grants", async () => {- const siteAccessPassword = "protected-instance-password";- const harness = await startHarness({ siteAccessPassword });-- const viewer = await openClient(harness.webSocketUrl);- viewer.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: harness.room.roomId,- role: "viewer",- clientId: "code-only-viewer-without-site-access",- }),- );- await expect(viewer.inbox.next("error")).resolves.toMatchObject({- code: "INVALID_TOKEN",- });-- const grantedViewer = await openClient(harness.webSocketUrl);- await expect(- authenticate(- grantedViewer,- harness.room,- "viewer",- "grant-viewer-without-site-access",- 1,- ),- ).resolves.toMatchObject({ role: "viewer" });-- const unauthorizedHost = await openClient(harness.webSocketUrl);- unauthorizedHost.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: harness.room.roomId,- role: "host",- token: harness.room.hostToken,- clientId: "host-client-without-admission",- }),- );- await expect(unauthorizedHost.inbox.next("error")).resolves.toMatchObject({- code: "AUTH_REQUIRED",- });-- const login = await fetch(`${harness.baseUrl}/api/site-access`, {- method: "POST",- headers: {- Authorization: `Bearer ${siteAccessPassword}`,- Origin: allowedOrigin,- },- });- const cookie = login.headers.get("set-cookie")?.split(";", 1)[0];- expect(cookie).toBeTruthy();-- const viewerWithHostCookie = await openClient(harness.webSocketUrl, cookie);- await expect(- authenticate(- viewerWithHostCookie,- harness.room,- "viewer",- "viewer-with-host-cookie",- 1,- undefined,- { codeOnly: true },- ),- ).resolves.toMatchObject({ role: "viewer" });-- const publicRoom = await harness.roomStore.createRoom("open");- const publicWithoutSiteAccess = await openClient(harness.webSocketUrl);- publicWithoutSiteAccess.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: publicRoom.roomId,- role: "viewer",- clientId: "public-viewer-without-site-access",- }),- );- await expect(- publicWithoutSiteAccess.inbox.next("error"),- ).resolves.toMatchObject({ code: "INVALID_TOKEN" });-- const publicWithForgedGrant = await openClient(harness.webSocketUrl);- publicWithForgedGrant.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: publicRoom.roomId,- role: "viewer",- clientId: "public-viewer-with-forged-grant",- viewerGrant: `${"x".repeat(21)}g`,- }),- );- await expect(- publicWithForgedGrant.inbox.next("error"),- ).resolves.toMatchObject({ code: "INVALID_TOKEN" });-- const publicWithSiteAccess = await openClient(harness.webSocketUrl, cookie);- await expect(- authenticate(- publicWithSiteAccess,- publicRoom,- "viewer",- "public-viewer-with-site-access",- 1,- undefined,- { codeOnly: true },- ),- ).resolves.toMatchObject({ role: "viewer" });-- const passwordRoom = await harness.roomStore.createRoom(- "private",- "room-password",- );-- const passwordWithoutSiteAccess = await openClient(harness.webSocketUrl);- passwordWithoutSiteAccess.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: passwordRoom.roomId,- role: "viewer",- clientId: "password-viewer-without-site-access",- viewerPassword: "room-password",- }),- );- await expect(- passwordWithoutSiteAccess.inbox.next("error"),- ).resolves.toMatchObject({ code: "INVALID_TOKEN" });-- const passwordWithSiteAccess = await openClient(harness.webSocketUrl, cookie);- await expect(- authenticate(- passwordWithSiteAccess,- passwordRoom,- "viewer",- "password-viewer-with-site-access",- 1,- undefined,- { viewerPassword: "room-password" },- ),- ).resolves.toMatchObject({ role: "viewer" });-- const host = await openClient(harness.webSocketUrl, cookie);- await expect(- authenticate(host, harness.room, "host", "host-client-protected"),- ).resolves.toMatchObject({ role: "host" });- });-- it("distinguishes missing rooms from existing-room code-only denials", async () => {- let now = Date.UTC(2026, 7, 24, 12);- const siteAccessPassword = "protected-instance-password";- const harness = await startHarness({- siteAccessPassword,- maxViewersPerRoom: 1,- now: () => now,- });- const login = await fetch(`${harness.baseUrl}/api/site-access`, {- method: "POST",- headers: {- Authorization: `Bearer ${siteAccessPassword}`,- Origin: allowedOrigin,- },- });- let cookie = login.headers.get("set-cookie")?.split(";", 1)[0];- expect(cookie).toBeTruthy();-- const protectedRoom = await harness.roomStore.createRoom(- "private",- "correct-password",- );- const expiring = await harness.roomStore.createRoom("open");- const unusedRoomId = Array.from({ length: 9_000 }, (_, index) =>- String(1_000 + index),- ).find(- (roomId) =>- ![- harness.room.roomId,- protectedRoom.roomId,- expiring.roomId,- ].includes(roomId),- )!;-- const admitted = await openClient(harness.webSocketUrl, cookie);- await authenticate(- admitted,- harness.room,- "viewer",- "admitted-viewer",- 1,- undefined,- { codeOnly: true },- );-- async function expectDenial(- roomId: string,- clientId: string,- code: "ROOM_NOT_FOUND" | "ROOM_ACCESS_DENIED",- viewerPassword?: string,- ): Promise<void> {- const client = await openClient(harness.webSocketUrl, cookie);- const closed = new Promise<{ code: number; reason: string }>((resolve) =>- client.socket.once("close", (code, reason) =>- resolve({ code, reason: reason.toString() }),- ),- );- client.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId,- role: "viewer",- clientId,- ...(viewerPassword ? { viewerPassword } : {}),- }),- );- expect(await client.inbox.next("error")).toEqual({- type: "error",- code,- message:- code === "ROOM_NOT_FOUND"- ? "Room not found or expired"- : "Room access denied",- });- expect(await closed).toEqual({- code: 4003,- reason: "Authentication failed",- });- }-- await expectDenial(unusedRoomId, "unknown-room-viewer", "ROOM_NOT_FOUND");- await expectDenial(- protectedRoom.roomId,- "missing-password-viewer",- "ROOM_ACCESS_DENIED",- );- await expectDenial(- protectedRoom.roomId,- "wrong-password-viewer",- "ROOM_ACCESS_DENIED",- "wrong-password",- );- await expectDenial(- harness.room.roomId,- "full-room-viewer",- "ROOM_ACCESS_DENIED",- );-- now += 86_400_001;- const renewedLogin = await fetch(`${harness.baseUrl}/api/site-access`, {- method: "POST",- headers: {- Authorization: `Bearer ${siteAccessPassword}`,- Origin: allowedOrigin,- },- });- cookie = renewedLogin.headers.get("set-cookie")?.split(";", 1)[0];- expect(cookie).toBeTruthy();- await expectDenial(- expiring.roomId,- "expired-room-viewer",- "ROOM_NOT_FOUND",- );-- const expiredGrant = await openClient(harness.webSocketUrl, cookie);- expiredGrant.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: expiring.roomId,- role: "viewer",- clientId: "expired-grant-viewer",- viewerGrant: expiring.viewerGrant,- }),- );- expect(await expiredGrant.inbox.next("error")).toMatchObject({- code: "INVALID_TOKEN",- });- });-- it("does not expire an active room and arms its lease after Host disconnect", async () => {- let now = Date.UTC(2026, 7, 20, 12);- const harness = await startHarness({- now: () => now,- });- const host = await openClient(harness.webSocketUrl);- const authenticated = await authenticate(- host,- harness.room,- "host",- "active-lease-host",- );- const viewer = await openClient(harness.webSocketUrl);- await authenticate(viewer, harness.room, "viewer", "provisional-viewer");- await host.inbox.next("peer-joined");-- now += 86_401_000;- expect(harness.roomStore.expireRooms()).toEqual([]);- await closeClient(host);- await viewer.inbox.next("host-status");- expect(harness.roomStore.getConnectedHost(harness.room.roomId)).toBeUndefined();- expect(harness.roomStore.expireRooms(now + 86_399_999)).toEqual([]);- const expired = harness.roomStore.expireRooms(now + 86_401_000);- expect(expired).toHaveLength(1);- expect(expired[0]).toMatchObject({ roomId: harness.room.roomId });- expect(expired[0]?.sessionIds).toHaveLength(1);- await closeClient(viewer);- expect(authenticated.role).toBe("host");- });-- it("keeps a pre-Host Viewer session current after the Host clears the room lease", async () => {- let now = Date.UTC(2026, 7, 20, 12);- const harness = await startHarness({ now: () => now });- const viewer = await openClient(harness.webSocketUrl);- await authenticate(- viewer,- harness.room,- "viewer",- "pre-host-lease-viewer",- 1,- undefined,- { displayName: "Before" },- );- const host = await openClient(harness.webSocketUrl);- await authenticate(- host,- harness.room,- "host",- "pre-host-lease-host",- 1,- undefined,- { viewerPresence: true },- );- await nextViewerPresenceMatching(host, (message) =>- viewerPresenceEntries(message).some(- (participant) => participant.displayName === "Before",- ),- );-- now += 86_400_001;- viewer.socket.send(- JSON.stringify({ type: "set-display-name", displayName: "After" }),- );- const updated = await nextViewerPresenceMatching(host, (message) =>- viewerPresenceEntries(message).some(- (participant) => participant.displayName === "After",- ),- );- expect(viewerPresenceEntries(updated)).toHaveLength(1);- });-- it("leaves established authorization and media untouched when a grant update fails", async () => {- const harness = await startHarness();- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "persistence-failure-host",- );- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- "persistence-failure-viewer",- );- await host.inbox.next("peer-joined");- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerAuth.peerId,- payload: {- kind: "description",- connectionId: "persistence-failure-edge",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- await viewer.inbox.next("signal");-- const update = vi- .spyOn(harness.roomStore, "setViewerGrant")- .mockImplementationOnce(() => {- throw new Error("simulated database write failure");- });- const response = await fetch(- `${harness.baseUrl}/api/rooms/${harness.room.roomId}/access`,- {- method: "POST",- headers: {- Authorization: `Bearer ${harness.room.hostToken}`,- "Content-Type": "application/json",- Origin: allowedOrigin,- },- body: JSON.stringify({ action: "rotate-viewer-grant" }),- },- );- expect(response.status).toBe(500);- await expect(- viewer.inbox.next("viewer-grant-revoked", 30),- ).rejects.toThrow("Timed out");-- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerAuth.peerId,- payload: {- kind: "candidate",- connectionId: "persistence-failure-edge",- candidate: null,- },- }),- );- expect(await viewer.inbox.next("signal")).toMatchObject({- fromPeerId: hostAuth.peerId,- payload: { connectionId: "persistence-failure-edge" },- });- update.mockRestore();-- const secondViewer = await openClient(harness.webSocketUrl);- expect(- await authenticate(- secondViewer,- harness.room,- "viewer",- "persistence-failure-new-viewer",- ),- ).toMatchObject({- viewerAuthorizationGeneration:- viewerAuth.viewerAuthorizationGeneration,- });- });-- it("lets viewers arrive first and replays their snapshot when the host joins", async () => {- const harness = await startHarness();- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- "viewer-client-early",- );- expect(viewerAuth.hostOnline).toBe(false);- expect("mediaMode" in viewerAuth).toBe(false);- expect("routeRevision" in viewerAuth).toBe(false);-- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "host-client-stable");- expect((await host.inbox.next("peer-joined")).peerId).toBe(viewerAuth.peerId);- expect(await viewer.inbox.next("host-status")).toEqual({- type: "host-status",- online: true,- paused: false,- });- });-- it("snapshots intentional pause across Viewer replacement and clears it on resume and stop", async () => {- const harness = await startHarness();- const shareGeneration = "pause_share_generation_12345678";- const host = await openClient(harness.webSocketUrl);- let activeHost = host;- const hostAuth = await authenticate(- host,- harness.room,- "host",- "pause-host-client",- 1,- shareGeneration,- );- expect(hostAuth).not.toHaveProperty("hostPaused");- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- "pause-viewer-client",- );- expect(viewerAuth.hostPaused).toBe(false);- await host.inbox.next("peer-joined");-- host.socket.send(- JSON.stringify({- type: "set-sharing-paused",- shareGeneration,- paused: true,- }),- );- expect(await viewer.inbox.next("host-status")).toEqual({- type: "host-status",- online: true,- paused: true,- });-- await closeClient(host);- expect(await viewer.inbox.next("host-status")).toMatchObject({- online: false,- paused: false,- });- activeHost = await openClient(harness.webSocketUrl);- await authenticate(- activeHost,- harness.room,- "host",- "pause-host-client",- 1,- shareGeneration,- { sharingPaused: true },- );- expect(await viewer.inbox.next("host-status")).toMatchObject({- online: true,- paused: true,- });-- const replacement = await openClient(harness.webSocketUrl);- const replacementAuth = await authenticate(- replacement,- harness.room,- "viewer",- "pause-viewer-client",- );- expect(replacementAuth.hostPaused).toBe(true);-- activeHost.socket.send(- JSON.stringify({- type: "set-sharing-paused",- shareGeneration,- paused: false,- }),- );- expect(await replacement.inbox.next("host-status")).toMatchObject({- online: true,- paused: false,- });-- activeHost.socket.send(- JSON.stringify({- type: "set-sharing-paused",- shareGeneration,- paused: true,- }),- );- expect(await replacement.inbox.next("host-status")).toMatchObject({- paused: true,- });- activeHost.socket.send(- JSON.stringify({ type: "stop-sharing", shareGeneration }),- );- await replacement.inbox.next("sharing-stopped");- expect(await replacement.inbox.next("host-status")).toMatchObject({- online: false,- paused: false,- });-- const nextHost = await openClient(harness.webSocketUrl);- await authenticate(- nextHost,- harness.room,- "host",- "pause-host-client",- 1,- "next_pause_share_generation_12345678",- );- await replacement.inbox.next("sharing-stopped");- expect(await replacement.inbox.next("host-status")).toMatchObject({- online: false,- paused: false,- });- expect(await replacement.inbox.next("host-status")).toMatchObject({- online: true,- paused: false,- });- });-- it("applies symmetric pause updates only to the exact current Host share", async () => {- const harness = await startHarness({ peerAssistedMedia: true });- const shareGeneration = "hybrid_pause_share_generation_12345678";- const host = await openClient(harness.webSocketUrl);- await authenticate(- host,- harness.room,- "host",- "hybrid-pause-host-client",- 1,- shareGeneration,- );- const viewer = await openClient(harness.webSocketUrl);- await authenticate(- viewer,- harness.room,- "viewer",- "hybrid-pause-viewer-client",- );-- host.socket.send(- JSON.stringify({- type: "set-sharing-paused",- shareGeneration,- paused: true,- }),- );- expect(await viewer.inbox.next("host-status")).toMatchObject({- online: true,- paused: true,- });- host.socket.send(- JSON.stringify({- type: "set-sharing-paused",- shareGeneration,- paused: false,- }),- );- expect(await viewer.inbox.next("host-status")).toMatchObject({- online: true,- paused: false,- });-- const closed = new Promise<number>((resolve) =>- host.socket.once("close", (code) => resolve(code)),- );- host.socket.send(- JSON.stringify({- type: "set-sharing-paused",- shareGeneration: "stale_pause_share_generation_12345678",- paused: true,- }),- );- expect(await closed).toBe(4001);- });-- it("retains authoritative pause when a reconnecting Host advertises unpaused", async () => {- const harness = await startHarness({ peerAssistedMedia: false });- const shareGeneration = "reconnect_resume_share_generation_12345678";- const hostClientId = "reconnect-resume-host-client";- const host = await openClient(harness.webSocketUrl);- await authenticate(- host,- harness.room,- "host",- hostClientId,- 1,- shareGeneration,- );- const viewer = await openClient(harness.webSocketUrl);- await authenticate(- viewer,- harness.room,- "viewer",- "reconnect-resume-viewer-client",- );- await host.inbox.next("peer-joined");-- host.socket.send(- JSON.stringify({- type: "set-sharing-paused",- shareGeneration,- paused: true,- }),- );- expect(await viewer.inbox.next("host-status")).toMatchObject({- online: true,- paused: true,- });- await closeClient(host);- expect(await viewer.inbox.next("host-status")).toMatchObject({- online: false,- paused: false,- });-- const reconnectedHost = await openClient(harness.webSocketUrl);- await authenticate(- reconnectedHost,- harness.room,- "host",- hostClientId,- 1,- shareGeneration,- { sharingPaused: false },- );- expect(- await reconnectedHost.inbox.next("pause-sharing-source"),- ).toEqual({- type: "pause-sharing-source",- shareGeneration,- });- expect(await viewer.inbox.next("host-status")).toMatchObject({- online: true,- paused: true,- });-- reconnectedHost.socket.send(- JSON.stringify({- type: "set-sharing-paused",- shareGeneration,- paused: false,- }),- );- expect(await viewer.inbox.next("host-status")).toMatchObject({- online: true,- paused: false,- });- });-- it("marks an ordinary Host edge ready after its exact SDP handshake", async () => {- const harness = await startHarness({ peerAssistedMedia: false });- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "ordinary-ready-host",- 1,- undefined,- { viewerPresence: true },- );- await host.inbox.next("viewer-presence");- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- "ordinary-ready-viewer",- 1,- undefined,- { viewerPresence: true },- );- expect((await host.inbox.next("peer-joined")).peerId).toBe(- viewerAuth.peerId,- );- const assigned = await nextViewerPresenceMatching(- host,- (message) =>- viewerPresenceEntries(message).some(- (entry) => entry.peerId === viewerAuth.peerId,- ),- );- expect(viewerPresenceEntries(assigned)[0]).not.toHaveProperty("mediaReady");-- const connectionId = "ordinary_ready_connection_12345678";- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerAuth.peerId,- payload: {- kind: "description",- connectionId,- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- expect(await viewer.inbox.next("signal")).toMatchObject({- fromPeerId: hostAuth.peerId,- payload: { connectionId, description: { type: "offer" } },- });- host.socket.send(- JSON.stringify({- type: "set-display-name",- displayName: "等待应答",- }),- );- const offered = await nextViewerPresenceMatching(- host,- (message) =>- viewerPresenceEntries(message).some(- (entry) => entry.peerId === viewerAuth.peerId,- ),- );- expect(viewerPresenceEntries(offered)[0]).not.toHaveProperty("mediaReady");- viewer.socket.send(- JSON.stringify({- type: "signal",- payload: {- kind: "description",- connectionId,- description: { type: "answer", sdp: "v=0\r\n" },- },- }),- );- expect(await host.inbox.next("signal")).toMatchObject({- fromPeerId: viewerAuth.peerId,- payload: { connectionId, description: { type: "answer" } },- });- const ready = await nextViewerPresenceMatching(- host,- (message) =>- viewerPresenceEntries(message).some(- (entry) =>- entry.peerId === viewerAuth.peerId && entry.mediaReady === true,- ),- );- expect(viewerPresenceEntries(ready)[0]).toMatchObject({- peerId: viewerAuth.peerId,- upstream: { kind: "peer", peerId: hostAuth.peerId },- mediaReady: true,- });- });-- it("binds new-share quality and preserves active-share quality across reconnect", async () => {- const harness = await startHarness({ peerAssistedMedia: true });- const initialSettings: QualitySettings = {- resolution: "1440p",- maxFramerate: 60,- maxBitrate: 8_000_000,- degradationPreference: "maintain-resolution",- screenAudioQuality: "very-high",- };- const firstGeneration = "first_share_generation_12345678";- const viewer = await openClient(harness.webSocketUrl);- await authenticate(- viewer,- harness.room,- "viewer",- "quality-viewer-client",- );-- const host = await openClient(harness.webSocketUrl);- const hostAuth = peerAssisted(- await authenticate(- host,- harness.room,- "host",- "quality-host-client",- 1,- firstGeneration,- { qualitySettings: initialSettings },- ),- );- expect(hostAuth.qualitySettings).toEqual(initialSettings);- expect(await viewer.inbox.next("quality-settings")).toEqual({- type: "quality-settings",- qualitySettings: initialSettings,- });-- const reconnectSettings: QualitySettings = {- resolution: "480p",- maxFramerate: 15,- maxBitrate: 2_000_000,- degradationPreference: "maintain-framerate",- screenAudioQuality: "saver",- };- const replaced = new Promise<number>((resolve) =>- host.socket.once("close", (code) => resolve(code)),- );- const reconnectedHost = await openClient(harness.webSocketUrl);- const reconnectedAuth = peerAssisted(- await authenticate(- reconnectedHost,- harness.room,- "host",- "quality-host-client",- 1,- firstGeneration,- { qualitySettings: reconnectSettings },- ),- );- expect(await replaced).toBe(4001);- expect(reconnectedAuth.qualitySettings).toEqual(initialSettings);- await expect(- viewer.inbox.next("quality-settings", 30),- ).rejects.toThrow("Timed out");-- const updatedSettings: QualitySettings = {- ...initialSettings,- resolution: "720p",- maxFramerate: 30,- maxBitrate: 3_000_000,- degradationPreference: "balanced",- screenAudioQuality: "music",- };- reconnectedHost.socket.send(- JSON.stringify({- type: "set-quality-settings",- qualitySettings: updatedSettings,- }),- );- expect(await viewer.inbox.next("quality-settings")).toEqual({- type: "quality-settings",- qualitySettings: updatedSettings,- });-- const stopped = new Promise<number>((resolve) =>- reconnectedHost.socket.once("close", (code) => resolve(code)),- );- reconnectedHost.socket.send(- JSON.stringify({- type: "stop-sharing",- shareGeneration: firstGeneration,- }),- );- expect(await stopped).toBe(1000);- await viewer.inbox.next("sharing-stopped");-- const nextHost = await openClient(harness.webSocketUrl);- const nextAuth = peerAssisted(- await authenticate(- nextHost,- harness.room,- "host",- "quality-host-client",- 1,- "next_share_generation_12345678",- {- qualitySettings: reconnectSettings,- },- ),- );- expect(nextAuth.qualitySettings).toEqual(reconnectSettings);- expect(await viewer.inbox.next("quality-settings")).toEqual({- type: "quality-settings",- qualitySettings: reconnectSettings,- });- });-- it("keeps a viewer peer stable when it reconnects inside the grace period", async () => {- const harness = await startHarness({ viewerDisconnectGraceMs: 80 });- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "host-client-stable");- const firstViewer = await openClient(harness.webSocketUrl);- const firstAuth = await authenticate(- firstViewer,- harness.room,- "viewer",- "viewer-client-stable",- );- await host.inbox.next("peer-joined");- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: firstAuth.peerId,- payload: {- kind: "description",- connectionId: "stable-connection",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- await firstViewer.inbox.next("signal");-- await closeClient(firstViewer);- const reconnectedViewer = await openClient(harness.webSocketUrl);- const reconnectedAuth = await authenticate(- reconnectedViewer,- harness.room,- "viewer",- "viewer-client-stable",- );- expect(reconnectedAuth.peerId).toBe(firstAuth.peerId);- expect(reconnectedAuth.connectionId).toBe("stable-connection");- expect((await host.inbox.next("peer-joined")).peerId).toBe(firstAuth.peerId);-- reconnectedViewer.socket.send(- JSON.stringify({- type: "restart-request",- connectionId: reconnectedAuth.connectionId,- rebuild: false,- }),- );- expect(await host.inbox.next("restart-request")).toMatchObject({- fromPeerId: firstAuth.peerId,- connectionId: "stable-connection",- rebuild: false,- });- await host.inbox.expectNone(110);-- await closeClient(reconnectedViewer);- expect((await host.inbox.next("peer-left", 500)).peerId).toBe(firstAuth.peerId);- });-- it.each([1, 2, 3] as const)(- "authorizes exactly %i ordinary Host children independently of room admission",- async (endpointMediaCopyCapacity) => {- const maxViewersPerRoom = endpointMediaCopyCapacity + 1;- const harness = await startHarness({- endpointMediaCopyCapacity,- maxViewersPerRoom,- });- const viewers: TestClient[] = [];- const viewerPeerIds: string[] = [];- for (let index = 0; index < maxViewersPerRoom; index += 1) {- const viewer = await openClient(harness.webSocketUrl);- const authenticated = await authenticate(- viewer,- harness.room,- "viewer",- `ordinary-cap-viewer-${index}`,- 1,- undefined,- { viewerPresence: true },- );- expect(authenticated.endpointMediaCopyCapacity).toBe(- endpointMediaCopyCapacity,- );- viewers.push(viewer);- viewerPeerIds.push(authenticated.peerId);- }-- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "ordinary-cap-host",- 1,- undefined,- { viewerPresence: true },- );- expect(hostAuth).toMatchObject({- maxViewers: maxViewersPerRoom,- endpointMediaCopyCapacity,- viewerPeerIds: viewerPeerIds.slice(0, endpointMediaCopyCapacity),- });-- const presence = viewerPresenceEntries(- await host.inbox.next("viewer-presence"),- );- for (let index = 0; index < presence.length; index += 1) {- expect(presence[index]).toMatchObject({- peerId: viewerPeerIds[index],- upstream:- index < endpointMediaCopyCapacity- ? { kind: "peer", peerId: hostAuth.peerId }- : { kind: "none" },- });- }-- const waitingPeerId = viewerPeerIds.at(-1)!;- expect((await host.inbox.next("peer-waiting")).peerId).toBe(- waitingPeerId,- );- for (const activePeerId of viewerPeerIds.slice(- 0,- endpointMediaCopyCapacity,- )) {- expect((await host.inbox.next("peer-joined")).peerId).toBe(- activePeerId,- );- }-- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: waitingPeerId,- payload: {- kind: "description",- connectionId: "waiting-host-offer",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- expect((await host.inbox.next("error")).code).toBe("FORBIDDEN");-- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: waitingPeerId,- payload: {- kind: "candidate",- connectionId: "waiting-host-candidate",- candidate: null,- },- }),- );- expect((await host.inbox.next("error")).code).toBe("FORBIDDEN");-- const waitingViewer = viewers.at(-1)!;- waitingViewer.socket.send(- JSON.stringify({- type: "signal",- payload: {- kind: "description",- connectionId: "waiting-viewer-answer",- description: { type: "answer", sdp: "v=0\r\n" },- },- }),- );- expect((await waitingViewer.inbox.next("error")).code).toBe("FORBIDDEN");-- waitingViewer.socket.send(- JSON.stringify({- type: "signal",- payload: {- kind: "candidate",- connectionId: "waiting-viewer-candidate",- candidate: null,- },- }),- );- expect((await waitingViewer.inbox.next("error")).code).toBe("FORBIDDEN");-- waitingViewer.socket.send(- JSON.stringify({- type: "restart-request",- connectionId: "waiting-viewer-restart",- rebuild: true,- }),- );- expect((await waitingViewer.inbox.next("error")).code).toBe("FORBIDDEN");-- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerPeerIds[0],- payload: {- kind: "description",- connectionId: "active-host-offer",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- expect(await viewers[0]!.inbox.next("signal")).toMatchObject({- fromPeerId: hostAuth.peerId,- payload: { connectionId: "active-host-offer" },- });- },- );-- it("holds an active ordinary slot through grace and skips offline waiters", async () => {- const harness = await startHarness({- endpointMediaCopyCapacity: 1,- maxViewersPerRoom: 3,- viewerDisconnectGraceMs: 100,- });- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "ordinary-grace-host",- 1,- undefined,- { viewerPresence: true },- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toEqual([]);-- const activeViewer = await openClient(harness.webSocketUrl);- const activeAuth = await authenticate(- activeViewer,- harness.room,- "viewer",- "ordinary-grace-active",- );- expect((await host.inbox.next("peer-joined")).peerId).toBe(- activeAuth.peerId,- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toEqual([- expect.objectContaining({- peerId: activeAuth.peerId,- upstream: { kind: "peer", peerId: hostAuth.peerId },- }),- ]);-- const offlineWaitingViewer = await openClient(harness.webSocketUrl);- const offlineWaitingAuth = await authenticate(- offlineWaitingViewer,- harness.room,- "viewer",- "ordinary-grace-offline-waiting",- );- expect((await host.inbox.next("peer-waiting")).peerId).toBe(- offlineWaitingAuth.peerId,- );- await host.inbox.next("viewer-presence");-- const connectedWaitingViewer = await openClient(harness.webSocketUrl);- const connectedWaitingAuth = await authenticate(- connectedWaitingViewer,- harness.room,- "viewer",- "ordinary-grace-connected-waiting",- );- expect((await host.inbox.next("peer-waiting")).peerId).toBe(- connectedWaitingAuth.peerId,- );- await host.inbox.next("viewer-presence");-- await closeClient(activeViewer);- await host.inbox.next("viewer-presence");- await new Promise((resolve) => setTimeout(resolve, 20));- await closeClient(offlineWaitingViewer);- await host.inbox.next("viewer-presence");- await host.inbox.expectNone(40);-- expect((await host.inbox.next("peer-left", 300)).peerId).toBe(- activeAuth.peerId,- );- expect((await host.inbox.next("peer-joined", 300)).peerId).toBe(- connectedWaitingAuth.peerId,- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toEqual([- expect.objectContaining({- peerId: connectedWaitingAuth.peerId,- upstream: { kind: "peer", peerId: hostAuth.peerId },- }),- ]);-- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: connectedWaitingAuth.peerId,- payload: {- kind: "description",- connectionId: "promoted-host-offer",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- expect(await connectedWaitingViewer.inbox.next("signal")).toMatchObject({- payload: { connectionId: "promoted-host-offer" },- });- expect((await host.inbox.next("peer-left", 300)).peerId).toBe(- offlineWaitingAuth.peerId,- );- });-- it("clears the previous media generation when sharing stops", async () => {- const harness = await startHarness({ viewerDisconnectGraceMs: 300 });- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "host-client-stop");- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- "viewer-client-stop",- );- await host.inbox.next("peer-joined");- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerAuth.peerId,- payload: {- kind: "description",- connectionId: "connection-before-stop",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- await viewer.inbox.next("signal");-- const hostClosed = new Promise<number>((resolve) =>- host.socket.once("close", (code) => resolve(code)),- );- host.socket.send(JSON.stringify({ type: "stop-sharing" }));- await viewer.inbox.next("sharing-stopped");- expect(await viewer.inbox.next("host-status")).toMatchObject({ online: false });- expect(await hostClosed).toBe(1000);- await closeClient(viewer);-- const reconnected = await openClient(harness.webSocketUrl);- const reconnectedAuth = await authenticate(- reconnected,- harness.room,- "viewer",- "viewer-client-stop",- );- expect(reconnectedAuth.connectionId).toBeNull();- expect(reconnectedAuth.peerId).toBe(viewerAuth.peerId);- expect(reconnectedAuth.hostOnline).toBe(false);- });-- it("replaces the same client presence once without leave churn", async () => {- const harness = await startHarness({ viewerDisconnectGraceMs: 40 });- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "host-client-stable",- 1,- undefined,- { viewerPresence: true },- );- expect(- viewerPresenceEntries(await host.inbox.next("viewer-presence")),- ).toEqual([]);- const original = await openClient(harness.webSocketUrl);- const originalAuth = await authenticate(- original,- harness.room,- "viewer",- "viewer-client-stable",- 1,- undefined,- { displayName: "旧会话" },- );- await host.inbox.next("peer-joined");- expect(viewerPresenceEntries(await host.inbox.next("viewer-presence"))).toEqual([- {- role: "viewer",- peerId: originalAuth.peerId,- displayName: "旧会话",- upstream: { kind: "peer", peerId: hostAuth.peerId },- },- ]);-- const originalClosed = new Promise<number>((resolve) =>- original.socket.once("close", (code) => resolve(code)),- );- const replacement = await openClient(harness.webSocketUrl);- const replacementAuth = await authenticate(- replacement,- harness.room,- "viewer",- "viewer-client-stable",- 1,- undefined,- { displayName: "新会话" },- );-- expect(replacementAuth.peerId).toBe(originalAuth.peerId);- expect(await originalClosed).toBe(4001);- expect((await host.inbox.next("peer-joined")).peerId).toBe(originalAuth.peerId);- expect(viewerPresenceEntries(await host.inbox.next("viewer-presence"))).toEqual([- {- role: "viewer",- peerId: originalAuth.peerId,- displayName: "新会话",- upstream: { kind: "peer", peerId: hostAuth.peerId },- },- ]);- await host.inbox.expectNone(70);- });-- it("notifies the host when a pre-offer viewer reconnects inside grace", async () => {- const harness = await startHarness({ viewerDisconnectGraceMs: 300 });- const originalViewer = await openClient(harness.webSocketUrl);- const originalAuth = await authenticate(- originalViewer,- harness.room,- "viewer",- "viewer-client-before-offer",- );- await closeClient(originalViewer);-- const host = await openClient(harness.webSocketUrl);- await authenticate(host, harness.room, "host", "host-client-stable");- await host.inbox.expectNone(30);-- const reconnectedViewer = await openClient(harness.webSocketUrl);- const reconnectedAuth = await authenticate(- reconnectedViewer,- harness.room,- "viewer",- "viewer-client-before-offer",- );- expect(reconnectedAuth.peerId).toBe(originalAuth.peerId);- expect(await host.inbox.next("peer-joined")).toMatchObject({- peerId: originalAuth.peerId,- });- });-- it("replays viewers when a host reconnects", async () => {- const harness = await startHarness({ viewerDisconnectGraceMs: 500 });- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- "viewer-client-stable",- );- const firstHost = await openClient(harness.webSocketUrl);- const firstHostAuth = await authenticate(- firstHost,- harness.room,- "host",- "host-client-stable",- );- await firstHost.inbox.next("peer-joined");- await viewer.inbox.next("host-status");- firstHost.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerAuth.peerId,- payload: {- kind: "description",- connectionId: "connection-before-control-outage",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- await viewer.inbox.next("signal");-- await closeClient(firstHost);- expect(await viewer.inbox.next("host-status")).toMatchObject({ online: false });- await closeClient(viewer);- const refreshedViewer = await openClient(harness.webSocketUrl);- const refreshedViewerAuth = await authenticate(- refreshedViewer,- harness.room,- "viewer",- "viewer-client-stable",- );- expect(refreshedViewerAuth.peerId).toBe(viewerAuth.peerId);- expect(refreshedViewerAuth.hostOnline).toBe(false);-- const secondHost = await openClient(harness.webSocketUrl);- const secondHostAuth = await authenticate(- secondHost,- harness.room,- "host",- "host-client-stable",- );- expect(secondHostAuth.peerId).toBe(firstHostAuth.peerId);- expect(secondHostAuth.viewerPeerIds).toEqual([viewerAuth.peerId]);- expect((await secondHost.inbox.next("peer-joined")).peerId).toBe(- viewerAuth.peerId,- );- await secondHost.inbox.expectNone(30);- expect(await refreshedViewer.inbox.next("host-status")).toMatchObject({- online: true,- });- });-- it("reconciles an empty roster after a viewer grace period ends offline", async () => {- const harness = await startHarness({ viewerDisconnectGraceMs: 30 });- const firstHost = await openClient(harness.webSocketUrl);- const firstHostAuth = await authenticate(- firstHost,- harness.room,- "host",- "host-client-roster",- );- const viewer = await openClient(harness.webSocketUrl);- await authenticate(viewer, harness.room, "viewer", "viewer-client-roster");- await firstHost.inbox.next("peer-joined");-- await closeClient(firstHost);- await closeClient(viewer);- await new Promise((resolve) => setTimeout(resolve, 70));-- const secondHost = await openClient(harness.webSocketUrl);- const secondHostAuth = await authenticate(- secondHost,- harness.room,- "host",- "host-client-roster",- );- expect(secondHostAuth.peerId).toBe(firstHostAuth.peerId);- expect(secondHostAuth.viewerPeerIds).toEqual([]);- await secondHost.inbox.expectNone(30);- });-- it("keeps media identity through grace while presence returns once", async () => {- const harness = await startHarness({ viewerDisconnectGraceMs: 500 });- const firstHost = await openClient(harness.webSocketUrl);- const firstHostAuth = await authenticate(- firstHost,- harness.room,- "host",- "host-client-grace-roster",- 1,- undefined,- { viewerPresence: true },- );- expect(- viewerPresenceEntries(await firstHost.inbox.next("viewer-presence")),- ).toEqual([]);- const firstViewer = await openClient(harness.webSocketUrl);- const firstViewerAuth = await authenticate(- firstViewer,- harness.room,- "viewer",- "viewer-client-grace-roster",- 1,- undefined,- { displayName: "短线重连" },- );- await firstHost.inbox.next("peer-joined");- expect(- viewerPresenceEntries(await firstHost.inbox.next("viewer-presence")),- ).toEqual([- {- role: "viewer",- peerId: firstViewerAuth.peerId,- displayName: "短线重连",- upstream: { kind: "peer", peerId: firstHostAuth.peerId },- },- ]);- firstHost.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: firstViewerAuth.peerId,- payload: {- kind: "description",- connectionId: "connection-during-grace",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- await firstViewer.inbox.next("signal");-- await closeClient(firstViewer);- expect(- viewerPresenceEntries(await firstHost.inbox.next("viewer-presence")),- ).toEqual([]);- await closeClient(firstHost);-- const secondHost = await openClient(harness.webSocketUrl);- const secondHostAuth = await authenticate(- secondHost,- harness.room,- "host",- "host-client-grace-roster",- 1,- undefined,- { viewerPresence: true },- );- expect(secondHostAuth.viewerPeerIds).toEqual([firstViewerAuth.peerId]);- expect(- viewerPresenceEntries(await secondHost.inbox.next("viewer-presence")),- ).toEqual([]);- await secondHost.inbox.expectNone(30);-- const secondViewer = await openClient(harness.webSocketUrl);- const secondViewerAuth = await authenticate(- secondViewer,- harness.room,- "viewer",- "viewer-client-grace-roster",- 1,- undefined,- { displayName: "短线重连" },- );- expect(secondViewerAuth.peerId).toBe(firstViewerAuth.peerId);- expect(secondViewerAuth.connectionId).toBe("connection-during-grace");- expect((await secondHost.inbox.next("peer-joined")).peerId).toBe(- firstViewerAuth.peerId,- );- expect(- viewerPresenceEntries(await secondHost.inbox.next("viewer-presence")),- ).toEqual([- {- role: "viewer",- peerId: firstViewerAuth.peerId,- displayName: "短线重连",- upstream: { kind: "peer", peerId: secondHostAuth.peerId },- },- ]);- await secondHost.inbox.expectNone(30);-- secondViewer.socket.send(- JSON.stringify({- type: "restart-request",- connectionId: secondViewerAuth.connectionId,- rebuild: false,- }),- );- expect(await secondHost.inbox.next("restart-request")).toMatchObject({- fromPeerId: firstViewerAuth.peerId,- connectionId: "connection-during-grace",- rebuild: false,- });- });-- it("stops sharing without deleting the room and restricts room abandonment", async () => {- const maxViewersPerRoom = 5;- const harness = await startHarness({ maxViewersPerRoom });- const host = await openClient(harness.webSocketUrl);- const hostAuth = await authenticate(- host,- harness.room,- "host",- "host-client-stable",- );- expect(hostAuth.maxViewers).toBe(maxViewersPerRoom);- const viewers: TestClient[] = [];- for (let index = 1; index <= maxViewersPerRoom; index += 1) {- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = await authenticate(- viewer,- harness.room,- "viewer",- `viewer-client-${index}`,- );- expect(viewerAuth.maxViewers).toBe(maxViewersPerRoom);- await host.inbox.next(index <= 2 ? "peer-joined" : "peer-waiting");- viewers.push(viewer);- }-- const overflow = await openClient(harness.webSocketUrl);- overflow.socket.send(- JSON.stringify({- type: "authenticate",- protocol: SIGNALING_PROTOCOL,- roomId: harness.room.roomId,- role: "viewer",- viewerGrant: harness.room.viewerGrant,- clientId: `viewer-client-${maxViewersPerRoom + 1}`,- }),- );- expect((await overflow.inbox.next("error")).code).toBe("ROOM_FULL");-- const stoppedHostClosed = new Promise<number>((resolve) =>- host.socket.once("close", (code) => resolve(code)),- );- host.socket.send(JSON.stringify({ type: "stop-sharing" }));- 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 stoppedHostClosed).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);-- const abandonHost = await openClient(harness.webSocketUrl);- await authenticate(- abandonHost,- harness.room,- "host",- "host-client-stable",- );- abandonHost.socket.send(JSON.stringify({ type: "abandon-room" }));- expect(await abandonHost.inbox.next("room-closed")).toMatchObject({- reason: "host-ended",- });- for (const viewer of viewers) {- expect(await viewer.inbox.next("room-closed")).toMatchObject({- reason: "host-ended",- });- }- expect(harness.roomStore.size).toBe(0);- });-- it("requires an allowed Origin, timely authentication, and bounded payloads", async () => {- const harness = await startHarness({ authenticationTimeoutMs: 30 });- expect(- await rejectedUpgradeStatus(harness.webSocketUrl, `${allowedOrigin}/path`),- ).toBe(403);- const foreign = new WebSocket(harness.webSocketUrl, {- origin: "https://foreign.example.test",- });- foreign.on("error", () => {- // The status assertion below is the expected failure path.- });- const status = await new Promise<number | undefined>((resolve) => {- foreign.once("unexpected-response", (_request, response) =>- resolve(response.statusCode),- );- });- expect(status).toBe(403);-- const unauthenticated = await openClient(harness.webSocketUrl);- const unauthenticatedClosed = new Promise<number>((resolve) =>- unauthenticated.socket.once("close", (code) => resolve(code)),- );- expect((await unauthenticated.inbox.next("error", 300)).code).toBe(- "AUTH_REQUIRED",- );- expect(await unauthenticatedClosed).toBe(4003);-- const oversized = await openClient(harness.webSocketUrl);- const closeCode = new Promise<number>((resolve) =>- oversized.socket.once("close", (code) => resolve(code)),- );- oversized.socket.send("x".repeat(MAX_SIGNAL_BYTES + 1));- expect(await closeCode).toBe(1009);- });-- it("terminates stale v12 before authentication", async () => {- const harness = await startHarness();- const invalidClient = await openClient(harness.webSocketUrl);- const closed = new Promise<{ code: number; reason: string }>((resolve) =>- invalidClient.socket.once("close", (code, reason) =>- resolve({ code, reason: reason.toString() }),- ),- );-- invalidClient.socket.send(- JSON.stringify({- type: "authenticate",- protocol: "screener-v12",- roomId: harness.room.roomId,- role: "viewer",- clientId: "invalid-client",- }),- );-- expect(await invalidClient.inbox.next("error")).toMatchObject({- code: "INVALID_MESSAGE",- });- expect(await closed).toEqual({ code: 1008, reason: "Invalid message" });- });-- it("rejects an invalid upgrade request target without stopping the server", async () => {- const harness = await startHarness();- const response = await rawUpgradeResponse(harness.webSocketUrl, "//[");- expect(response).toMatch(/^HTTP\/1\.1 400 Bad Request/);-- const host = await openClient(harness.webSocketUrl);- expect(- (await authenticate(host, harness.room, "host", "host-after-invalid-url"))- .role,- ).toBe("host");- });-- it("rejects unauthenticated and total connection overflow before upgrade", async () => {- const harness = await startHarness({- maxSignalConnections: 2,- maxUnauthenticatedSignalConnections: 1,- });- const host = await openClient(harness.webSocketUrl);- expect(await rejectedUpgradeStatus(harness.webSocketUrl)).toBe(503);-- await authenticate(host, harness.room, "host", "capacity-host");- const viewer = await openClient(harness.webSocketUrl);- await authenticate(- viewer,- harness.room,- "viewer",- "capacity-viewer",- );- expect(await rejectedUpgradeStatus(harness.webSocketUrl)).toBe(503);- });--});diff --git a/tests/sfu-resource-admission.test.ts b/tests/sfu-resource-admission.test.tsdeleted file mode 100644index 3107ffa1..00000000--- a/tests/sfu-resource-admission.test.ts+++ /dev/null@@ -1,240 +0,0 @@-import { describe, expect, it } from "vitest";--import {- SfuResourceAdmission,- type SfuResourceFence,- type SfuSubscriptionFence,-} from "../src/server/sfu-resource-admission.ts";--function publication(- roomId: string,- publicationGeneration: string,- shareGeneration = `share_${roomId}`,-): SfuResourceFence {- return { roomId, shareGeneration, publicationGeneration };-}--function subscription(- fence: SfuResourceFence,- viewerPeerId: string,-): SfuSubscriptionFence {- return { ...fence, viewerPeerId };-}--describe("SfuResourceAdmission", () => {- it("requires explicit capacities and enforces ingress and egress independently", () => {- for (const ingressCapacity of [0, 1.5, Number.MAX_SAFE_INTEGER + 1]) {- expect(- () => new SfuResourceAdmission({ ingressCapacity, egressCapacity: 1 }),- ).toThrow("positive safe integer");- }- expect(- () => new SfuResourceAdmission({ ingressCapacity: 1, egressCapacity: 0 }),- ).toThrow("positive safe integer");-- const admission = new SfuResourceAdmission({- ingressCapacity: 2,- egressCapacity: 2,- });- const first = publication("1", "publication_first");- const second = publication("2", "publication_second");- expect(admission.reservePublication(first)).toBe(true);- expect(admission.reservePublication(second)).toBe(true);- expect(- admission.reservePublication(publication("3", "publication_third")),- ).toBe(false);- expect(admission.reserveSubscription(subscription(first, "viewer_a"))).toBe(- true,- );- expect(admission.reserveSubscription(subscription(first, "viewer_b"))).toBe(- true,- );- expect(- admission.reserveSubscription(subscription(second, "viewer_c")),- ).toBe(false);- expect(admission.usage()).toEqual({ ingress: 2, egress: 2 });- });-- it("keeps exact publication and subscription operations idempotent", () => {- const admission = new SfuResourceAdmission({- ingressCapacity: 1,- egressCapacity: 1,- });- const active = publication("1", "publication_active");- const viewer = subscription(active, "viewer_a");- expect(admission.reservePublication(active)).toBe(true);- expect(admission.reservePublication({ ...active })).toBe(true);- expect(admission.reserveSubscription(viewer)).toBe(true);- expect(admission.reserveSubscription({ ...viewer })).toBe(true);- expect(admission.commitSubscription(viewer)).toBe(false);- expect(admission.commitPublication(active)).toEqual([]);- expect(admission.commitPublication({ ...active })).toEqual([]);- expect(admission.commitSubscription(viewer)).toBe(true);- expect(admission.usage()).toEqual({ ingress: 1, egress: 1 });-- const stale = publication("1", "publication_stale");- expect(admission.reserveSubscription(subscription(stale, "viewer_a"))).toBe(- false,- );- expect(admission.commitPublication(stale)).toBeNull();- expect(admission.commitSubscription(subscription(active, "viewer_b"))).toBe(- false,- );- expect(- admission.beginSubscriptionDrain(subscription(active, "viewer_b")),- ).toBe(false);- expect(admission.beginDrain(stale)).toBe(false);- });-- it("does not commit a publication without its first exact subscription", () => {- const admission = new SfuResourceAdmission({- ingressCapacity: 1,- egressCapacity: 1,- });- const pending = publication("1", "publication_pending");- expect(admission.reservePublication(pending)).toBe(true);- expect(admission.commitPublication(pending)).toBeNull();- expect(admission.beginDrain(pending)).toBe(true);- expect(admission.completeDrain(pending)).toBe(true);- expect(admission.usage()).toEqual({ ingress: 0, egress: 0 });- });-- it("commits a new publication and its subscriptions before draining the old generation", () => {- const admission = new SfuResourceAdmission({- ingressCapacity: 2,- egressCapacity: 3,- });- const first = publication("1", "publication_first");- const second = publication("1", "publication_second");- const firstViewer = subscription(first, "viewer_a");- expect(admission.reservePublication(first)).toBe(true);- expect(admission.reserveSubscription(firstViewer)).toBe(true);- expect(admission.commitPublication(first)).toEqual([]);-- expect(admission.reservePublication(second)).toBe(true);- expect(admission.reserveSubscription(subscription(second, "viewer_b"))).toBe(- true,- );- expect(admission.reserveSubscription(subscription(second, "viewer_c"))).toBe(- true,- );- expect(admission.usage()).toEqual({ ingress: 2, egress: 3 });- expect(admission.commitPublication(second)).toEqual([first]);- expect(admission.commitSubscription(subscription(second, "viewer_b"))).toBe(- true,- );- expect(admission.reservePublication(first)).toBe(false);- expect(admission.reserveSubscription(firstViewer)).toBe(false);-- expect(admission.completeDrain(first)).toBe(true);- expect(admission.completeDrain(first)).toBe(false);- expect(admission.usage()).toEqual({ ingress: 1, egress: 2 });- });-- it("keeps a released reserved subscription charged until publication absence", () => {- const admission = new SfuResourceAdmission({- ingressCapacity: 1,- egressCapacity: 2,- });- const active = publication("1", "publication_active");- const first = subscription(active, "viewer_a");- const candidate = subscription(active, "viewer_b");- expect(admission.reservePublication(active)).toBe(true);- expect(admission.reserveSubscription(first)).toBe(true);- expect(admission.commitPublication(active)).toEqual([]);-- expect(admission.reserveSubscription(candidate)).toBe(true);- expect(admission.usage()).toEqual({ ingress: 1, egress: 2 });- expect(admission.beginSubscriptionDrain(candidate)).toBe(true);- expect(admission.beginSubscriptionDrain(candidate)).toBe(true);- expect(admission.commitSubscription(candidate)).toBe(false);- expect(admission.usage()).toEqual({ ingress: 1, egress: 2 });- expect(- admission.reserveSubscription(subscription(active, "viewer_c")),- ).toBe(false);- expect(admission.beginDrain(active)).toBe(true);- expect(admission.completeDrain(active)).toBe(true);- expect(admission.usage()).toEqual({ ingress: 0, egress: 0 });- });-- it("reactivates an exact draining subscription without double charging", () => {- const admission = new SfuResourceAdmission({- ingressCapacity: 1,- egressCapacity: 1,- });- const active = publication("1", "publication_active");- const viewer = subscription(active, "viewer_a");- expect(admission.reservePublication(active)).toBe(true);- expect(admission.reserveSubscription(viewer)).toBe(true);- expect(admission.commitPublication(active)).toEqual([]);- expect(admission.beginSubscriptionDrain(viewer)).toBe(true);- expect(admission.usage()).toEqual({ ingress: 1, egress: 1 });-- expect(admission.reserveSubscription(viewer)).toBe(true);- expect(admission.reserveSubscription(viewer)).toBe(true);- expect(admission.usage()).toEqual({ ingress: 1, egress: 1 });- expect(admission.beginSubscriptionDrain(viewer)).toBe(true);- expect(- admission.reserveSubscription(subscription(active, "viewer_b")),- ).toBe(false);- expect(admission.reserveSubscription(viewer)).toBe(true);- expect(admission.commitSubscription(viewer)).toBe(true);- expect(admission.usage()).toEqual({ ingress: 1, egress: 1 });- });-- it("keeps departed subscription egress charged until publication drain proof", () => {- const admission = new SfuResourceAdmission({- ingressCapacity: 1,- egressCapacity: 1,- });- const active = publication("1", "publication_active");- const viewer = subscription(active, "viewer_a");- expect(admission.reservePublication(active)).toBe(true);- expect(admission.reserveSubscription(viewer)).toBe(true);- expect(admission.commitPublication(active)).toEqual([]);- expect(admission.beginSubscriptionDrain(viewer)).toBe(true);- expect(- admission.reserveSubscription(subscription(active, "viewer_b")),- ).toBe(false);- expect(admission.beginDrain(active)).toBe(true);- expect(admission.beginDrain(active)).toBe(true);- expect(admission.usage()).toEqual({ ingress: 1, egress: 1 });- expect(admission.completeDrain(active)).toBe(true);- expect(admission.usage()).toEqual({ ingress: 0, egress: 0 });- });-- it("drains every reserved and committed generation exactly once", () => {- const admission = new SfuResourceAdmission({- ingressCapacity: 3,- egressCapacity: 4,- });- const active = publication("1", "publication_active");- const replacement = publication("1", "publication_replacement");- const other = publication("2", "publication_other");- expect(admission.reservePublication(active)).toBe(true);- expect(admission.reserveSubscription(subscription(active, "viewer_a"))).toBe(- true,- );- expect(admission.commitPublication(active)).toEqual([]);- expect(admission.reservePublication(replacement)).toBe(true);- expect(- admission.reserveSubscription(subscription(replacement, "viewer_b")),- ).toBe(true);- expect(admission.reservePublication(other)).toBe(true);- expect(admission.reserveSubscription(subscription(other, "viewer_c"))).toBe(- true,- );-- const firstRoom = admission.beginDrainRoom("1");- expect(firstRoom).toEqual([active, replacement]);- expect(admission.beginDrainRoom("1")).toEqual(firstRoom);- expect(admission.beginDrainAll()).toEqual([active, replacement, other]);- expect(admission.usage()).toEqual({ ingress: 3, egress: 3 });- for (const fence of [active, replacement, other]) {- expect(admission.completeDrain(fence)).toBe(true);- expect(admission.completeDrain(fence)).toBe(false);- }- expect(admission.usage()).toEqual({ ingress: 0, egress: 0 });- });--});diff --git a/tests/sfu-room-control.test.ts b/tests/sfu-room-control.test.tsdeleted file mode 100644index 19de8d59..00000000--- a/tests/sfu-room-control.test.ts+++ /dev/null@@ -1,236 +0,0 @@-import { readFileSync } from "node:fs";--import { ServerError } from "livekit-server-sdk";-import { describe, expect, it, vi } from "vitest";--import {- isManagedSfuRoomName,- managedSfuRoomName,- type SfuResourceFence,-} from "../src/server/sfu-resource-admission.ts";-import {- LiveKitSfuRoomControl,- type LiveKitRoomService,-} from "../src/server/sfu-room-control.ts";--class FakeRoomService implements LiveKitRoomService {- readonly rooms = new Map<string, Set<string>>();- readonly operations: string[] = [];- readonly createOptions: Array<{ name: string; maxParticipants: number }> = [];- createBarrier?: Promise<void>;- retainDeletedRoom = false;- retainRemovedParticipant = false;-- async createRoom(options: { name: string; maxParticipants: number }) {- this.operations.push(`create:${options.name}`);- this.createOptions.push(options);- await this.createBarrier;- if (this.rooms.has(options.name)) {- throw new Error("room already exists");- }- this.rooms.set(options.name, new Set());- return { name: options.name };- }-- async listRooms(names?: string[]) {- const selected = names?.length- ? [...this.rooms.keys()].filter((name) => names.includes(name))- : [...this.rooms.keys()];- return selected.map((name) => ({ name }));- }-- async deleteRoom(room: string): Promise<void> {- this.operations.push(`delete:${room}`);- if (!this.rooms.has(room)) {- throw new ServerError("Not Found", "missing", 404, "not_found");- }- if (!this.retainDeletedRoom) {- this.rooms.delete(room);- }- }-- async listParticipants(room: string) {- const participants = this.rooms.get(room);- if (!participants) {- throw new ServerError("Not Found", "missing", 404, "not_found");- }- return [...participants].map((identity) => ({ identity }));- }-- async removeParticipant(room: string, identity: string): Promise<void> {- this.operations.push(`remove:${room}:${identity}`);- const participants = this.rooms.get(room);- if (!participants?.has(identity)) {- throw new ServerError("Not Found", "missing", 404, "not_found");- }- if (!this.retainRemovedParticipant) {- participants.delete(identity);- }- }-- join(room: string, identity: string): boolean {- const participants = this.rooms.get(room);- if (!participants) {- return false;- }- participants.add(identity);- return true;- }-}--function fence(- roomId = "42",- shareGeneration = "share_generation_12345678",- publicationGeneration = "publication_generation_12345678",-): SfuResourceFence {- return { roomId, shareGeneration, publicationGeneration };-}--function control(roomService: FakeRoomService): LiveKitSfuRoomControl {- return new LiveKitSfuRoomControl({- apiUrl: "http://127.0.0.1:7880",- apiKey: "test-key",- apiSecret: "s".repeat(32),- maxViewersPerRoom: 8,- roomService,- });-}--function deferred(): { promise: Promise<void>; resolve: () => void } {- let resolve!: () => void;- const promise = new Promise<void>((settle) => {- resolve = settle;- });- return { promise, resolve };-}--describe("LiveKitSfuRoomControl", () => {- it("drains current managed rooms before startup", async () => {- const roomService = new FakeRoomService();- const current = managedSfuRoomName(fence());- roomService.rooms.set(current, new Set(["host"]));-- await expect(control(roomService).initialize()).resolves.toBeUndefined();- expect(roomService.rooms.size).toBe(0);- expect(roomService.operations).toEqual([`delete:${current}`]);- });-- it("rejects a shared instance and an unconfirmed startup drain", async () => {- const foreign = new FakeRoomService();- foreign.rooms.set("another-application", new Set());- await expect(control(foreign).initialize()).rejects.toThrow("foreign room");- expect(foreign.operations).toEqual([]);-- const retained = new FakeRoomService();- retained.retainDeletedRoom = true;- retained.rooms.set(managedSfuRoomName(fence()), new Set());- await expect(control(retained).initialize()).rejects.toThrow(- "not empty after startup drain",- );- });-- it("serializes create and delete and leaves a stale token with no room", async () => {- const roomService = new FakeRoomService();- const roomControl = control(roomService);- const resourceFence = fence();- const roomName = managedSfuRoomName(resourceFence);- const gate = deferred();- roomService.createBarrier = gate.promise;-- const creating = roomControl.createRoom(resourceFence);- await vi.waitFor(() =>- expect(roomService.operations).toEqual([`create:${roomName}`]),- );- const deleting = roomControl.deleteRoom(resourceFence);- await Promise.resolve();- expect(roomService.operations).toEqual([`create:${roomName}`]);-- gate.resolve();- await Promise.all([creating, deleting]);- expect(roomService.operations).toEqual([- `create:${roomName}`,- `delete:${roomName}`,- ]);- expect(roomService.createOptions[0]?.maxParticipants).toBe(9);- expect(roomService.join(roomName, "host")).toBe(false);- });-- it("rejects an off-ledger exact room before issuing another generation", async () => {- const roomService = new FakeRoomService();- const resourceFence = fence();- roomService.rooms.set(managedSfuRoomName(resourceFence), new Set(["host"]));-- await expect(control(roomService).createRoom(resourceFence)).rejects.toThrow(- "already exists",- );- expect(roomService.operations).toEqual([]);- });-- it("checks the exact Host participant and treats an absent room as offline", async () => {- const roomService = new FakeRoomService();- const roomControl = control(roomService);- const resourceFence = fence();- await roomControl.createRoom(resourceFence);- const roomName = managedSfuRoomName(resourceFence);-- expect(roomService.join(roomName, "viewer:one")).toBe(true);- await expect(- roomControl.hostParticipantExists(resourceFence),- ).resolves.toBe(false);- expect(roomService.join(roomName, "host")).toBe(true);- await expect(- roomControl.hostParticipantExists(resourceFence),- ).resolves.toBe(true);- await roomControl.deleteRoom(resourceFence);- await expect(- roomControl.hostParticipantExists(resourceFence),- ).resolves.toBe(false);- });-- it("removes and confirms only the exact Viewer subscription", async () => {- const roomService = new FakeRoomService();- const roomControl = control(roomService);- const resourceFence = fence();- await roomControl.createRoom(resourceFence);- const roomName = managedSfuRoomName(resourceFence);- const viewerPeerId = "viewer_peer_12345678";- expect(roomService.join(roomName, "host")).toBe(true);- expect(roomService.join(roomName, `viewer:${viewerPeerId}`)).toBe(true);- expect(roomService.join(roomName, "viewer:other_peer_12345678")).toBe(true);-- const subscriptionFence = { ...resourceFence, viewerPeerId };- await expect(- roomControl.drainSubscription(subscriptionFence),- ).resolves.toBeUndefined();- expect(roomService.rooms.get(roomName)).toEqual(- new Set(["host", "viewer:other_peer_12345678"]),- );- await expect(- roomControl.drainSubscription(subscriptionFence),- ).resolves.toBeUndefined();- });-- it("rejects an unconfirmed Viewer participant drain", async () => {- const roomService = new FakeRoomService();- const roomControl = control(roomService);- const resourceFence = fence();- await roomControl.createRoom(resourceFence);- const roomName = managedSfuRoomName(resourceFence);- const viewerPeerId = "viewer_peer_12345678";- roomService.join(roomName, `viewer:${viewerPeerId}`);- roomService.retainRemovedParticipant = true;-- await expect(- roomControl.drainSubscription({ ...resourceFence, viewerPeerId }),- ).rejects.toThrow("removal was not confirmed");- });-- it("keeps the tracked deployment unable to auto-create rooms", () => {- const configuration = readFileSync(- new URL("../deploy/livekit/livekit.yaml.example", import.meta.url),- "utf8",- );- expect(configuration).toMatch(/room:\s+[\s\S]*auto_create: false/);- expect(isManagedSfuRoomName("screener-v1.42.bad.segment.extra")).toBe(false);- });-});diff --git a/tests/viewer-peer-generation.test.ts b/tests/viewer-peer-generation.test.tsindex 50d3f6d3..994d8ae8 100644--- a/tests/viewer-peer-generation.test.ts+++ b/tests/viewer-peer-generation.test.ts@@ -471,7 +471,7 @@ describe("ViewerPeer connection generations", () => {expect(timeoutDelays.get(2)).toBe(3_000);});- it("gives a NAT-enabled pending route one bounded ICE retry", async () => {+ it("returns NAT-enabled candidate failure to its route owner without local retries", async () => {const restartRequests: string[] = [];const exhausted: string[] = [];const peer = new ViewerPeer(@@ -503,14 +503,8 @@ describe("ViewerPeer connection generations", () => {connection.connectionState = "failed";connection.dispatchEvent(new Event("connectionstatechange"));- expect(restartRequests).toEqual(["route-candidate"]);- expect(exhausted).toEqual([]);-- timeoutCallbacks.get(1)!();- expect(restartRequests).toEqual(["route-candidate", "route-candidate"]);- expect(exhausted).toEqual([]);-- timeoutCallbacks.get(2)!();+ expect(restartRequests).toEqual([]);+ expect(timeoutDelays).toEqual(new Map());expect(exhausted).toEqual(["route-candidate"]);});diff --git a/tests/viewer-presentation.test.ts b/tests/viewer-presentation.test.tsindex 47f7a4a5..98d6ea8c 100644--- a/tests/viewer-presentation.test.ts+++ b/tests/viewer-presentation.test.ts@@ -127,6 +127,50 @@ describe("Viewer presentation reducer", () => {expect(nextRoute.connection).toBe("connecting");});+ it("accepts an authoritative lower route revision without retaining failure state", () => {+ const failed = apply(+ { type: "access", access: "ready" },+ { type: "host", host: "online" },+ { type: "route", revision: 8, phase: "active", kind: "p2p" },+ { type: "route-status", revision: 8, state: "failed" },+ );++ const rebound = reduceViewerPresentation(failed, {+ type: "route",+ revision: 0,+ phase: "active",+ kind: "none",+ authoritative: true,+ });++ expect(rebound.revision).toBe(0);+ expect(rebound.routeStatus).toBeNull();+ expect(rebound.connection).toBe("idle");+ });++ it("keeps proven media across an authoritative same-route reauthentication", () => {+ const playing = apply(+ { type: "access", access: "ready" },+ { type: "host", host: "online" },+ { type: "route", revision: 8, phase: "active", kind: "p2p" },+ { type: "media-bound", generation: 1, revision: 8 },+ { type: "frame-presented", generation: 1, proofEpoch: 0, revision: 8 },+ { type: "route-status", revision: 8, state: "failed" },+ );++ const rebound = reduceViewerPresentation(playing, {+ type: "route",+ revision: 0,+ phase: "active",+ kind: "p2p",+ authoritative: true,+ });++ expect(rebound.routeStatus).toBeNull();+ expect(rebound.media).toMatchObject({ generation: 1 });+ expect(rebound.connection).toBe("reconnecting");+ });+it("keeps proven media independent of room graph revision changes", () => {const playing = apply({ type: "access", access: "ready" },diff --git a/tsconfig.json b/tsconfig.jsonindex c03f2b94..682304d8 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -2,7 +2,6 @@"files": [],"references": [{ "path": "./tsconfig.app.json" },- { "path": "./tsconfig.server.json" },{ "path": "./tsconfig.tools.json" }]}diff --git a/tsconfig.server.json b/tsconfig.server.jsondeleted file mode 100644index 36b918c7..00000000--- a/tsconfig.server.json+++ /dev/null@@ -1,21 +0,0 @@-{- "compilerOptions": {- "tsBuildInfoFile": "./node_modules/.cache/tsconfig.server.tsbuildinfo",- "target": "ES2023",- "lib": ["ES2023"],- "module": "NodeNext",- "moduleResolution": "NodeNext",- "types": ["node"],- "rootDir": "src",- "outDir": "dist/server",- "sourceMap": true,- "declaration": false,- "skipLibCheck": true,- "verbatimModuleSyntax": true,- "strict": true,- "noUnusedLocals": true,- "noUnusedParameters": true,- "noFallthroughCasesInSwitch": true- },- "include": ["src/server", "src/shared"]-}diff --git a/tsconfig.tools.json b/tsconfig.tools.jsonindex 4b8e4f06..d98680c8 100644--- a/tsconfig.tools.json+++ b/tsconfig.tools.json@@ -20,6 +20,7 @@"vite.config.ts","vitest.config.ts","scripts/access-privacy-gate.ts",+ "scripts/client-browser-fanout-gate.ts","scripts/client-media-gate.ts","scripts/client-native-host-gate.ts","scripts/client-native-sfu-gate.ts",@@ -27,6 +28,7 @@"scripts/client-loopback-gate.ts","scripts/client-local-gate.ts","scripts/client-link-gate.ts",+ "scripts/peer-assisted-benchmark.ts","tests"]}diff --git a/vite.config.ts b/vite.config.tsindex b41611df..b692618e 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,10 +1,27 @@import react from "@vitejs/plugin-react";import { defineConfig } from "vite";+// The Go server owns /api, /healthz and /signal; everything else (including+// /r/<roomId> invitation paths) is the SPA that Vite already serves. Keeping the+// Browser origin on 8787 leaves PUBLIC_BASE_URL, ALLOWED_ORIGINS, the README and+// the LAN-phone instructions unchanged; the Go dev server moves to 8788.+const server = "http://127.0.0.1:8788";+export default defineConfig({plugins: [react()],build: {- outDir: "dist/client",- emptyOutDir: true,+ outDir: "internal/server/webassets/dist",+ emptyOutDir: false,+ },+ server: {+ // host: true keeps the documented LAN-phone workflow reachable.+ host: true,+ port: 8787,+ strictPort: true,+ proxy: {+ "/api": { target: server },+ "/healthz": { target: server },+ "/signal": { target: server, ws: true },+ },},});diff --git a/vitest.config.ts b/vitest.config.tsindex dd392afb..faa6d98e 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -4,8 +4,5 @@ export default defineConfig({test: {environment: "node",include: ["tests/**/*.test.ts"],- coverage: {- reporter: ["text", "html"],- },},});