## Added
- **WebSocket Protocol Specification** (docs/PROTOCOL.md) - Complete reference
for all 20+ events with payload schemas, rate limits, and edge cases
- **LEAVE_ROOM Rate Limiting** - 10 requests/socket/minute to prevent abuse
- **Vitest Testing Framework** - Modern test setup with coverage reporting
- **Host Control Mode Documentation** - Consolidated EN documentation
(docs/host-control-mode.md) with references to internal implementation
## Changed
- **Graceful Shutdown** - Socket.IO clients properly disconnected during
server shutdown (server/index.js)
- **CI Workflow** - Added test step with continue-on-error for gradual rollout
- **README** - Added protocol documentation link
- **CHANGELOG** - Updated with all new features and improvements
## Moved
- Internal documentation moved to docs/internal/ for better organization
- Host Control Mode docs consolidated from 4 files to 1 comprehensive guide
## Technical Details
- Protocol spec: 495 lines, covers all events from shared/constants.js
- Rate limiter: Follows existing pattern (checkAuthRate, checkEventRate)
- Vitest: 6 tests for rate limiter, all passing
- Documentation: Host Control Mode doc includes edge cases, testing checklist,
architecture decisions
- Remove duplicate local TITLE_PRIVACY_MODES array definition
- Use Object.values(TITLE_PRIVACY_MODES).includes() for validation instead
- Keeps single source of truth in title-privacy.js
Co-Authored-By: Claude <noreply@anthropic.com>
- Manual Connect: split the server picker into its own inset panel,
visually separated from the Room ID / Password fields (they were
welded together in one flat list).
- Custom server URL: stop auto-prepending ws:// — default to wss://
for real hosts, ws:// only for localhost/127.0.0.1 (matches what
the background already enforces; the displayed URL no longer lies).
- Host Control card: replace the raw native checkbox with the proper
.toggle-switch slider used in Options; move the toggle row from a
<label> to a <div> to avoid an illegally nested label.
- Co-host discoverability: owner-only hint in the Host Control card
pointing to the participant list (new NOTICE_COHOST_HINT across all
15 locales). Shown only when actionable: owner + co-host-capable
relay + host-only active.
- Peer row: group right-side badges/actions into one container so they
no longer scatter via space-between or collide with long names;
restyle the give/revoke button (padding, weight, hover fill, tooltip).
- Gate promote/demote (and role badges) on host-only mode being ON,
in addition to the existing owner-privilege check — roles are moot
in 'everyone' mode, so no badge/button noise there.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- server: SET_PEER_ROLE now uses the same per-room 500ms debounce as
SET_CONTROL_MODE (M-4), preventing a buggy/malicious host from
thrashing the room's UI with rapid promote/demote bursts.
- server: PEER_STATUS relay treats explicit null as 'clear' for
tabTitle/mediaTitle/currentTime, so the tab-close heartbeat actually
zeroes out stale state on other peers instead of being silently
preserved by the clamp fallback.
- background: _persistLastSeq is now trailing-debounced (500ms),
cutting storage.session IPC writes from one-per-relayed-event to
one-per-quiet-window in active rooms.
- locales: add missing TOAST_ID_REGENERATED to all 14 non-English
locales (was blocking locale coverage test on main).
- test: H-1 force-sync demote test now waits out the debounce window
to reflect real-world UI timing (a host cannot promote, run a
force-sync, and demote inside 500ms).
Two pre-existing issues surfaced during audit follow-up:
1. popup.js bound elements.regenId but never attached a click handler —
the 'Regenerate Peer ID' button has been dead UI since it was added
(verified across full git history). Wired it up to send REGENERATE_ID;
the background handler already did the right thing (rotate peerId,
persist, force reconnect). The button is functional (regen ID on
duplicate-identity errors), not privacy-theater — username is already
user-changeable in settings, so it stays out of scope.
2. MAX_CONTROLLERS=10 was arbitrary. Payload math (25 controllers ×
16-char IDs ≈ 500 bytes) is well under the 4KB maxHttpBufferSize,
controllers.has() is O(1) on a Set, and 'just use everyone mode' is
not a real answer when a host wants 12 controllers + 3 guests in a
15-person room. Removed the cap entirely; the only real upper bound
is MAX_PEERS_PER_ROOM (25).
Added TOAST_ID_REGENERATED to en.json — the i18n fallback merge
(Object.assign({}, enDict, targetDict)) covers the other 14 locales
automatically with English until they're translated.
Defense-in-depth: the field was always undefined in practice (no code
path ever sets currentRoom.password — verified across the full git
history), and no GET_STATUS caller in the codebase reads it. But if a
future change ever populated currentRoom.password, any caller of
GET_STATUS would receive it in cleartext.
Threat surface today is narrow (externally_connectable is not set, no
content script sends GET_STATUS, only the popup uses it), but the field
has no reason to exist — removing it eliminates the future-leak vector
for free.
Backward compatible: no caller reads this field, so removing it is a no-op
for every existing code path.
8 hex chars (32-bit) gives ~7% collision probability at the relay's
25k-peer capacity and ~1% at 10k peers. A same-room collision silently
triggers the dedup path and kicks the older session with a confusing
'Another session with this ID joined' error.
16 hex chars (64-bit) drops collision probability to ~1e-10 even at one
million peers. The server's JOIN_ROOM sanitizer already clamps peerId to
16 chars, so no server change is needed. Fully backward compatible:
- Existing clients keep their persisted 8-char peerId (only newly
generated IDs change).
- Mixed 8-char + 16-char ID rooms work — both fit the server's 16-char
clamp.
- No protocol change on the wire.
Birthday-paradox reference (computed, not estimated):
32-bit @ 10k peers: 1.16%
32-bit @ 25k peers: 7.02%
64-bit @ 25k peers: ~0.017e-9%
Three drop-in lengths for product listings, launch pages, and directory
submissions where the same pitch gets re-typed repeatedly. Bonus taglines
for hero headlines and social bios. All claims verified against the
codebase and docs/TESTED_SERVICES.md.
Audit fixes (each verified against the actual code path):
H-1 (server): track force-sync initiator on PREPARE; let the demoted
initiator's EXECUTE through the host-only gate so mid-sync demotion no
longer strands the whole room paused. Clear on EXECUTE/peer-leave.
M-1 (background): episode-lobby gate now uses !amController() for parity
with CONTENT_EVENT and server gates — co-hosts can drive the room and
initiate lobbies, not just the owner.
M-2/M-3 (popup/content/background): forceSyncReset respects hcmGuestLocked;
desynced guest skips EPISODE_LOBBY so they don't get frozen in pause after
lobby completion, and checkEpisodeLobbyCompletion excludes desynced peers
from the required count so they don't block the lobby.
M-4 (background): getHostSyncTarget clamps extrapolation to 2x heartbeat
interval so a stale host heartbeat can't snap the guest tens of seconds
past the host's real position.
L-1..L-4 (server/content/background/popup): clarify dedup comment re:
network-blip window, enforce desync invariant on SW-restore, add
forceSyncBtn guest-locked backstop, refresh badge text in place.
Backward compatibility (verified by BC-1..BC-4 regression tests):
- Old client ↔ new server: server adds fields only, never requires; old
heartbeats stripped of desynced; host-only enforced server-side even
when the client has no awareness.
- New client ↔ old server: empty capabilities → host-control UI hidden,
all gates default to everyone, behavior byte-identical to pre-HCM.
- Mixed rooms: every pre-HCM event type relays cleanly in both directions.
- updateHostControlUI takes a state object now; role badge shows Host / Controller
/ Guest; remote-control lock uses amController (a co-host can drive, so their
buttons aren't locked).
- Peer list: Host/Controller badges and, for the owner, a per-peer Give control /
Revoke button (SET_PEER_ROLE). Shown only when the feature is active and the room
is host-only or the viewer is the owner — no role noise for guests in normal rooms.
Hidden entirely against a relay without the co-host capability.
- i18n: BADGE_CONTROLLER, BTN_GIVE_CONTROL, BTN_REVOKE_CONTROL across all 15 locales.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- background: track controllers[] from ROOM_DATA/CONTROL_MODE (restore + reset on
teardown); add amController() (owner or co-host). Both gates now key on controller
membership (sender: !amController(); receiver: senderId not in controllers); desync
invariant uses amController. Thread controllers/amController/coHostSupported through
GET_STATUS/GET_CONTROL_MODE/CONTROL_MODE. New SET_PEER_ROLE message (owner→server).
- content: gate on amController instead of amHost (a controller is not a gated guest);
reconcile/HOST_BLOCKED updated accordingly. Drop now-unused hcmAmHost.
Single-host behavior unchanged (owner is always the sole controller until they promote).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Generalizes host-only from a single host to a controller SET. The owner (creator)
can promote/demote peers; in host-only mode the relay gate allows any controller,
not just the owner. Single-host is now the special case controllers={owner}, so
existing behavior/tests are unchanged.
- shared: CAPABILITIES.CO_HOST enabled; new SET_PEER_ROLE event; CONTROL_MODE
payload carries controllers.
- server: room.controllers Set (always incl. owner), advertised in ROOM_DATA;
gate checks controllers.has(peerId); SET_PEER_ROLE handler (owner-only, target
must be present, MAX_CONTROLLERS=10 cap, re-sync on reject); controlModePayload
helper for consistent emits; owner-leave resets controllers + falls back to
everyone, co-host-leave broadcasts the updated list (dedup/reconnect guarded).
- WS test: promote→drive, plain guest still gated, non-owner can't promote,
demote→re-gated.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Move KNOWN_LIMITATIONS.md → docs/KNOWN_LIMITATIONS.md (+ fix SECURITY.md link).
- WS test: in default 'everyone' mode a non-host guest can still drive
play/pause/seek/force-sync/episode-lobby — proves host-control OFF == unchanged
behavior.
- docs/host-control-mode-COHOST-PLAN.md: plan for multi-controller (owner grants
drive rights to several co-hosts), built on the capabilities hook; covers the
gate generalization, roles, backwards-compat, edge cases, and a separate
large-room (510-peer) scaling track.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Records the accepted, out-of-threat-model decisions that reviewers/agents keep
re-reporting as bugs: unauthenticated peerId (host impersonation), non-constant-
time room-password compare, public server token, enumerable room IDs, and
pause-revert-not-prevent. Spells out the threat model (ephemeral, account-less
rooms of invited participants watching a video) so the "NOFIX" rationale is clear,
and distinguishes these from genuinely-deferred items (EC-10 host grace, classifier
tuning). Cross-referenced from SECURITY.md.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Room-password hashing falls back to a built-in salt that is public in the repo
when SERVER_SALT is not configured. Low risk (the hash never leaves the server),
but operators should set a unique salt — warn at startup, mirroring the existing
ADMIN_METRICS_TOKEN warning.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Findings recovered from the multi-agent audit (verification phase was cut off by a
usage limit; verified inline against the code):
HIGH:
- Host was demoted on peerId dedup (fast reconnect / second tab): the dedup path
removes the old socket and the kicked socket's 'disconnect' both ran the
host-leave fallback before the same peerId re-joined → room silently unlocked on
every host network blip. Now skip the fallback while a join for that peerId is in
flight (peerJoinLocks). Regression test added. (A long real disconnect still
falls back — that's the deferred host-grace EC-10.)
- Episode auto-advance froze a gated guest: in host-only the guest's EPISODE_LOBBY
is dropped server-side, but the guest still self-paused (PAUSE_FOR_LOBBY) waiting
for readies that never came → 60s freeze. A host-only guest now skips creating a
lobby (the host drives episode sync).
LOW / cleanup:
- GET_HCM_STRINGS could return a raw key name ("HCM_DIALOG_TITLE") if the locale
dictionary failed to load (getMessage returns the key on miss) → omit it so
content keeps its English fallback.
- hcmReset now also clears the snap-back cooldown + buffering grace, so a stale
cooldown can't swallow the first snap-back after a room/host change.
- Popup play/pause labels reset on lock too (not just unlock), so a button can't
freeze on "Playing…" when host-only activates mid-click.
- Fix a stale comment (heartbeat now carries 'desynced').
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Audit follow-up on the snap-back paths. The immediate involuntary snap used the
captured target directly; if it was null/invalid (host position not known yet,
e.g. before the first host heartbeat) hcmSnapBackToHost no-ops and the guest is
left silently paused with no dialog and no retry. The deferred and "Stay in sync"
paths already re-query with retry — make the immediate path fall back to the same
when the captured target isn't usable.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Implements the snap-back robustly instead of deferring it to device testing —
since the set of video sites is unbounded, "measure which players misbehave, then
fix" doesn't scale; the snap-back must be safe on any player.
On an involuntary pause/seek, if the player isn't ready to play (readyState<3 or
seeking) we no longer snap immediately (which fights the buffer: seek → re-buffer
→ pause → … = stutter). Instead hcmDeferredSnapBack polls until the player can
play (8s cap) and then snaps ONCE to the host's re-queried current position. A
player can't play while buffering anyway, so waiting is also more correct, not
just safer. Ready players still snap immediately (no regression).
Guards: aborts if the user goes solo or is no longer a gated guest; single
pending poll (no stacking); cleared in hcmReset.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Replace the implicit "hostPeerId present ⇒ feature supported" heuristic with an
explicit capabilities list the relay advertises in ROOM_DATA. Cleaner, self-
documenting, and the extensible hook for the planned co-host feature (owner
promotes guests to extra controllers) — a future 'co-host' capability + events
slot in without a protocol bump.
- shared: CAPABILITIES { HOST_CONTROL }.
- server: SERVER_CAPABILITIES advertised in ROOM_DATA.
- background: track serverCapabilities (empty against older relay), serverSupports(),
thread hostControlSupported through GET_STATUS / GET_CONTROL_MODE / CONTROL_MODE.
- popup: gate the host-control card on the explicit capability instead of hostPeerId.
Backwards-compatible both ways: old relay omits the field → feature stays hidden
(no errors); old client ignores the field. WS test asserts ROOM_DATA advertises
the capability. Adds docs/host-control-mode-TESTING.md (beta-server setup, wss
caveat, two-new-clients note, verification checklist).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds a separate workflow that builds the server image and pushes it to GHCR under
non-production tags (beta, branch slug, sha-<commit>, and an optional custom tag
via manual dispatch) so the host-control branch can be deployed to a staging /
backup server and used as a custom server — without ever touching ':latest' that
the official relay tracks (flavor: latest=false).
Runs on push to feature/host-control-mode and on workflow_dispatch. Remove once
the feature is merged and released normally.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The card was rendered in every room with a "Guest" badge by default — confusing
in normal rooms, and outright misleading against a relay that doesn't yet support
host control (older server omits hostPeerId, so amHost is always false and nobody
is ever recognized as host).
Now the card shows only when it's meaningful: the host always sees it (to toggle
host-only), a guest sees it only while host-only is active, and it's hidden in a
normal "everyone" room and whenever the server doesn't advertise hostPeerId
(feature unavailable). Thread hostPeerId through updateHostControlUI to detect
server support.
Note: the feature still requires the relay to run the host-control server code;
this just makes the client degrade cleanly instead of showing a stray "Guest".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The host-control desync dialog and the "watching on your own" badge were
hardcoded English — content.js has no i18n loader. Background does, so it now
resolves the strings (GET_HCM_STRINGS: loadLocale + getMessage) and content
fetches them on init with English fallbacks, re-rendering the badge if it was
already shown. The dialog body is now generic (dropped the paused/jumped verb)
to keep translation clean across languages.
Adds 6 keys (HCM_DIALOG_TITLE/BODY/STAY/SOLO, HCM_BADGE_SOLO/RESYNC) translated
across all 15 popup locales.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Two issues surfaced by a holistic audit of the combined desync-persist +
reconcile-on-init changes:
1. Stale desync outside gated-guest state. hcmDesynced is persisted, but neither
ROOM_DATA nor CONTROL_MODE cleared it when the local peer became host or the
room switched to 'everyone'. Combined with reconcile-on-init, a desynced guest
promoted to host (host-leave fallback) while content was reloading could
re-adopt desynced=true — self-labelling "Solo" to all peers and ignoring host
commands in 'everyone' mode. Enforce the invariant centrally
(hcmEnforceDesyncInvariant: desynced ⟹ host-only && !host) on every role/mode
change, and guard the content reconcile to only adopt when actually a gated guest.
2. Solo-badge flicker. The host-side PEER_STATUS handler set peer.desynced
unconditionally, but the background-driven keepAlive heartbeat omits the field —
so every ~30s it clobbered desynced to false, flickering the badge. Only update
when present (matching the sibling fields), and include desynced in the
background heartbeat so both heartbeat sources are consistent.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The Resync badge already retried REQUEST_HOST_SYNC when the host's state wasn't
known yet, but the dialog's "Stay in sync" path did a single no-retry request —
so a stay tap right after the host paused (before a heartbeat propagated) could
silently leave the guest paused/out of sync. Extracted the retry loop into a
shared hcmRequestHostSyncWithRetry() and used it in both paths.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Fixes a split-brain where a guest who chose "watch on my own" and then reloaded
the video page would appear stuck as "Solo" to the host while actually being
back in sync.
Root cause: background persists hcmDesynced (survives SW restart) and attaches
it to content-driven heartbeats, but a freshly injected content script started
with hcmDesynced=false and GET_CONTROL_MODE never returned the desync state — so
content re-applied host commands (synced) while background kept relaying
desynced=true to the host.
Fix: GET_CONTROL_MODE now also returns desynced; content adopts it on init
(re-shows the badge) and also adopts hostPeerId so later host-change resets work.
Desync now survives a page reload consistently on both sides, as intended.
Verified the full path: background.js heartbeat (1555 omits / 2018 attaches),
reset paths, CONTENT_BOOT and keepAlive-disconnect (neither reset it), content
sendHeartbeat on inject.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Original code at L1957 already validates sender.tab tabId against
currentTabId before calling processEvent() — added guard was
duplicate. HCM_DESYNC_STATE had no such guard; added with same
sender.tab && currentTabId pattern (popup-safe via undefined
short-circuit).
hcmDesynced now persisted in session storage:
- Restored in ensureState()
- Set on HCM_DESYNC_STATE change
- Reset to false in all 3 teardown storage.sets
Survives SW restarts; cleared on leave/switch/idle-room
- CONTENT_EVENT now rejected from non-selected tabs (popup exempted via sender.tab check)
- HCM_DESYNC_STATE same guard
- hcmDesynced persisted in session storage: restored on SW restart, cleared on teardown
Bis auf peerId-Auth (akzeptiert) alle Audit-Findings behoben:
- Snap-back spielt nicht mehr blind ab, wenn Host-Status unbekannt
- Teardown-Pfade broadcasten jetzt CONTROL_MODE → kein verwaistes Badge/Dialog
- Dialog-Timer bei Ersetzung sauber gecleart
- Server re-synchronisiert Sender bei nicht-Host-Reject
- Popup-Toggle revertiert bei Server-Ablehnung
- Desync-Zweig sendet keine Phantom-ACKs mehr an Host
- Toggle-Debouncing serverseitig (500ms pro Raum)
- Button-Text auf Unlock zurückgesetzt
- Live-Erkennung defensiver, Resync-Retry bei fehlendem Target, Badge-Retry
Neu: Host sieht 'Solo'-Badge für desyncte Gäste via PEER_STATUS-Heartbeat
(16 Sprachen, neuer i18n-Key BADGE_DESYNCED/TOOLTIP_PEER_DESYNCED)
Tests: H-5-Reject-Unicast, M-4-Debounce, Desync-Heartbeat-Relay
hcmHandleBlocked no longer re-checks local control mode before acting. Background
only sends HOST_BLOCKED to a gated guest, so the message itself is authoritative —
adopt host-only/guest role from it. Fixes the join race where a HOST_BLOCKED
arriving before the CONTROL_MODE broadcast was silently ignored.
Also corrects the EC-4 note: "let catch-up re-sync" is invalid (sync is
event-driven, no continuous catch-up); the right fix is a buffer-aware deferred
snap-back.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>