Files
piik/docs/standards/rooms-access.md
T
AAA 24e9b639a8 feat: add attended remote control and refine shared viewing (#482)
Piik can now let one invited Viewer control the Host's shared desktop or window, using the existing media route and explicit source-scoped consent. This phase also finishes Viewer playback settings, the combined interaction window, the shared control/theme/icon polish, and concrete forwarding-feedback recovery fixes.

Remote input stays off by default, uses one controller and releases held input on revocation, retirement or loss. Existing 2.x sharing remains compatible; new capabilities are negotiated with supporting App/Site/relay peers. No virtual input driver, new media listener or route planner is added.

Validation: full Web check (97 files / 1,677 tests), Windows Go/native checks; seven real Browser/App lifecycle scenarios covering P2P, SFU and fallback-to-direct continuity; existing cross-version and physical Windows routed-input evidence; native macOS/Linux packaging, Go race/security and container checks through the publishing pipeline. Physical macOS/Linux permissions, mobile devices, mixed DPI and commercial games retain their documented limits. README/wiki keep deployment under the optional self-hosted Server chapters.

Refs #472, #477, #479, #480. Issue follow-up happens after publication; unmatched field reports remain open.

## Release notes

### 中文

这是一次功能更新:一起看屏幕时,可以把键鼠交给一位朋友操作,聊天和表情也整合进了同一个互动窗口。本次还整理了分享与播放设置,并修复部分连接恢复和中转画质停滞的问题。

#### 新功能与体验

- **可选键鼠远控**:房主可以让一位朋友操作当前分享的桌面或窗口,随时撤回授权;换源或停播后关闭远控。提供手机触控、缩放和小键盘。当前实机验证覆盖 Windows App。
- **观众播放设置**:新增完整显示、等比铺满、拉伸铺满,以及自动/仅 P2P/仅 SFU 线路选择;站点和房主的线路限制仍然生效。
- **互动窗口**:聊天、参与者和表情放在同一窗口;可以从聊天头像选择接收者,新增点赞、倒彩等表情。支持的浏览器可以独立置顶,继续查看聊天和互动。全屏保留弹幕开关。
- **分享与播放设置更清楚**:暂停与停止相邻,画面、声音、连接和远控各有对应入口。观众播控在移动鼠标时显现,远控时收进画面边缘的小抽屉;点击画面不再意外暂停。没有声音输入时播控给出明确反馈,恢复输入后保留观众的音量设置。

#### 修复

- **连接与播放修复**:修正部分中转路径的媒体时钟、往返时间与重复反馈统计,改善这些错误导致的画质恢复停滞;重新进入房间后,SFU 连接仍可继续尝试直连。同步底层握手恢复修复。
- **界面修复**:修复浮窗返回后遮挡全屏、无法操作,窄屏控件错位、菜单超出边界等问题。虚拟键盘长按不会选中文字,拖出、取消或失焦后释放按键。页面和选源面板统一中性底色;App 图标与 favicon 保留小电视轮廓,精修对比度与底板层次。
- **兼容性修复**:新表情按站点支持情况显示,避免旧站点拒收后断开连接。补齐旧浏览器的浮层支持;修正 macOS `.app` 对包外启动文件的依赖。macOS 的 Finder、权限和远控仍需实机验证。

#### 更新说明

沿用 2.x 兼容边界。使用远控需要更新房主 App 和所连接的站点;要获得完整的中转修复,请同时更新 App 与自部署 Server。

### English

This feature update lets a Host hand keyboard and mouse control to one friend while sharing a screen. Chat and reactions now share one interaction window. It also clarifies sharing and playback settings and fixes specific connection-recovery and server-forwarding quality stalls.

#### Features and experience

- **Optional keyboard and mouse control:** the Host can let one friend control the shared desktop or window and revoke access at any time. Changing sources or stopping sharing disables control. Touch controls, zoom and an on-screen keyboard are included. Physical validation currently covers the Windows App.
- **Viewer playback settings:** choose fit, crop or stretch, and Auto, P2P-only or SFU-only routing. Site and Host restrictions still apply.
- **One interaction window:** chat, participants and reactions stay together. Choose a recipient from their chat avatar and use new reactions, including thumbs up and down. Supported browsers can detach the window and keep chat and reactions visible on top. Fullscreen retains the chat-overlay toggle.
- **Clearer sharing and playback controls:** pause and stop stay together, with separate picture, sound, connection and remote-control settings. Pointer movement reveals the playback bar during viewing; remote control uses a small drawer at the picture edge. Clicking the picture no longer pauses it accidentally. Sound controls reflect missing input and retain the Viewer's volume when it returns.

#### Fixes

- **Connection and playback fixes:** correct media clocks, round-trip-time updates and duplicate feedback accounting on affected forwarding paths, improving recovery from the quality stalls caused by those errors. Rejoining a room restores direct-connection attempts while SFU playback continues. Incorporate upstream handshake-recovery fixes.
- **Interface fixes:** returning a detached tool during fullscreen no longer leaves an inaccessible panel over the picture. Fix compact-layout shifts and overflowing menus. Holding a virtual key no longer selects its label; release, cancellation and focus loss clear held keys. Pages and the source picker use shared neutral surfaces. Refine App icons and favicons while retaining the familiar television outline.
- **Compatibility fixes:** show new reactions only when the site supports them, preventing disconnects on older sites. Support popovers on older browsers and remove the macOS `.app` launcher's dependency on files outside the bundle. Finder, permissions and remote input still need physical macOS validation.

#### Updating

The existing 2.x compatibility boundary is retained. Remote control needs an updated Host App and site; update both App and self-hosted Server for the complete forwarding fix.
2026-10-19 01:58:33 +08:00

11 KiB

Rooms And Access

This file owns the current room, admission, invitation, interaction, and persistence contract. ADR-0002 explains the storage decision; implementation detail belongs in code and tests.

Room Authority

  • A room has one Host and at most 20 authenticated Viewers.
  • Room codes are random free four-digit values from 1000..9999. A code locates a room within its site authority; it is not globally unique, a secret or a permanent identity. App public-link rooms belong to that App's local authority.
  • Every room has a 256-bit Host token. The server stores only its digest; the owning Browser keeps the raw token locally.
  • Each Host tab retains its current room in session storage. The origin keeps one persistent resume hint and a separate preferred code; a new tab may resume that room only when no other tab claims it. Secure Browser origins use Web Locks, including protection against copied tab storage. Without Web Locks, fresh tabs create independent rooms and same-tab reload can retain authority, but duplicated-tab exclusion is not guaranteed. Closing the tab releases its claim; losing Host authority clears that tab without erasing another tab's resume hint.
  • Room identity and credentials have no inactivity expiry by default. The exact Host token resumes the room until explicit replacement or deletion, including the optional empty-room policy below. Grant rotation or revocation ends an invitation without changing the room code.
  • The Host may replace its room code. Replacement atomically creates a different room and invalidates the old ownership, invitations, password, sessions, routes, and media resources. It ends an active share and stops its capture tracks; it does not migrate or automatically restart capture.
  • A locally remembered preferred code is only a request. The server remains the authority and allocates another code when that code is unavailable. The store remains bounded by 9,000 codes; full allocation rejects new rooms when no empty room may be reclaimed under the deployment's retention policy.

Optional empty-room retention

Hosted operators may enable ROOM_EMPTY_TIMEOUT_SECONDS; 0 (default) preserves indefinite authority. A positive value retires a room after that many seconds continuously without any authenticated Host or Viewer. Never-joined rooms start empty at creation. Sharing, pausing and idle chat do not change this rule; failed authentication and HTTP access do not renew it. The existing heartbeat performs expiry checks, normally every 30 seconds.

With retention enabled, allocation first reclaims expired empty rooms; if none are available, it may retire the earliest-created empty room before the timeout, including when replacing a room code. Early reclamation observes the existing 20-second reconnect grace after creation, restore or the last departure. Occupied rooms are never candidates; a replacement cannot reclaim its own old room before the replacement commits. If all rooms are occupied, creation still returns capacity exhaustion. Expiry and pressure retirement use the same storage-first deletion and signaling cleanup as explicit abandonment; recycled codes never retain old credentials, share generations or reconnect timers.

The empty interval is process-local. Restored rooms receive a fresh interval so surviving pages can reconnect; allocation pressure can still reclaim them while empty. SQLite restores the insertion order of retained rows. This policy adds no room lease, client renewal, wire field or persisted presence. Deletion ends both ownership and invitations; ordinary missing-room/invalid-credential handling applies. Configuration owns deployment values. Disabling retention stops future reclamation; it cannot restore retired authority.

Admission Paths

Three independent authorities exist:

  1. Site access. SITE_ACCESS_PASSWORD is optional in every environment, including production. Unset or empty makes site access immediate without a cookie; room ownership and Viewer admission still apply. When configured, successful password entry creates a stateless, HttpOnly, SameSite=Strict cookie with a 24-hour rolling idle lifetime. An already authorized page renews it through the site-access check while it remains active. It authorizes room creation, Host role, and code-only Viewer attempts; it is not a room credential, and Viewer-grant admission cannot create or renew it. Cookie transport attributes follow the configured destination: public HTTPS retains the Secure host-prefixed cookie, while a separately configured HTTP LAN origin can use its HTTP cookie. Login, renewal, room creation and WebSocket admission use that same selection. Cookie signatures use a random process key independent of the password; restarting the Server/App requires site-password entry again. This does not revoke persisted room ownership or Viewer invitations. The application rejects framing through its own HTTP headers, including without a proxy. A signaling authentication failure alone does not establish site-access loss: its existing error also covers an incomplete or timed-out room handshake. The Host checks the site-access authority before entering the password gate; an allowed or unavailable check retains ordinary connection recovery. Explicit room credential rejection remains terminal.
  2. Host ownership. The exact Host token authorizes that room's Host and access-management operations. It cannot authorize another room.
  3. Viewer invitation. Every room creates a 128-bit, 22-character base64url Viewer grant. It authorizes only the Viewer role for that exact room incarnation and bypasses site access and code-entry policy.

The invitation grant is carried in the URL fragment, removed from the address bar on first read, and retained only in room-scoped sessionStorage. Refreshing the same tab preserves it. It is not intentionally persisted across independent tabs or Browser sessions; tab duplication and opener initialization remain Browser behavior. The grant has no independent TTL and ends with the room or when the Host rotates or revokes it.

The Host can omit the grant from the displayed/copied link. This page-local choice defaults to including it and does not change admission policy, revoke existing invitations or clear a recipient's valid authorization. The ordinary room address retains the server-provided site and room path; it follows site access and code-entry rules. An invite-only room has no ordinary-address entry.

Code-only admission is independent of invitations:

  • open admits a site-authorized Viewer by room code;
  • private without a password is invitation-only;
  • private with a password additionally admits a site-authorized matching code-and-password attempt.

An unknown or deleted code returns ROOM_NOT_FOUND. A current room that refuses a code-only attempt returns the generic ROOM_ACCESS_DENIED result without exposing its exact policy. Invalid grants and Host ownership failures remain separate.

Rotating or revoking the Viewer grant is a strong authorization change. The new generation is committed before old Viewers, signaling grace, routes, and sender edges are closed. An affected SFU Viewer's exact embedded subscription is closed before its egress reservation is released. Room-authenticated signaling cannot recreate a revoked subscription; no separate media token survives revocation. Changing code-entry policy or password affects later code-only attempts and does not silently revoke invitations.

Room Interactions

Text and reactions reuse the authenticated room signaling connection. The server derives sender identity from that session and accepts targeted reactions only for participants still connected to the same room. Interaction subscriptions inherit existing membership, replacement and revocation checks; they grant no additional authority and do not modify media routes.

The reaction palette is curated, with no free-form input. Additions preserve existing choices.

Sending a reaction requires a registered identifier. The Server advertises its command registry through the optional roomReactionIds runtime capability. The palette and send owner use its intersection with effects the page knows; an absent registry retains the published 2.1 reaction set. Interaction-ready events keep their existing shape. Received reaction events validate their envelope, identity, target and bounded identifier, then the page skips effects it cannot display. An unknown effect does not terminate signaling, enter history, clear a draft or confirm a pending send. Unknown message kinds, extra fields and malformed identities remain invalid; this presentation rule does not make commands or access checks extensible.

Delivery is transient and bounded. The server keeps no message history; each page keeps only a bounded set of received messages and effects, without writing them to storage or diagnostics. Re-admission to the same room may retain that page's conversation, but refresh, leaving or authority loss clears it. There is no history replay or offline outbox. HTTPS/WSS protects transport; chat is not end-to-end encrypted, and the site operator can access live message contents.

Presentation and lifecycle owns the distinction between a room session and its current media publication. Interaction research records delivery bounds, compatibility and design rationale.

Persistence Modes

  • Stable mode (Hosted default): one exact-schema SQLite owner persists room authority across application restart. ROOM_DATABASE_PATH selects an absolute file path; absent or empty uses rooms.sqlite in the working directory.
  • Lightweight mode: explicit ROOM_DATABASE_PATH=:memory: keeps room authority in process memory and all rooms disappear on restart.
  • App Local mode: the packaged App composes the same memory RoomStore and ends every room when its local authority exits. Saved Site/password and last-confirmed mode preferences follow App configuration; rooms and media state remain process-only. A blank password leaves that site open.

Persistence evidence, limits and the earlier cross-restart evaluation live in cross-restart recovery research.

The App opens its own localhost Host page with the configured password, when present, in a fragment. The page removes the fragment and uses the existing SiteAccess endpoint; this does not create a fourth admission authority. LAN and one-link Internet Viewers use the same room-scoped invitation grant; its fragment never enters the public tunnel request, and the Host's Local RoomStore remains the only authority. Selecting a Site moves room authority wholly to that Site rather than synchronizing two stores.

Stable mode does not persist participants, signaling sessions, sharing state, routes, codec decisions, quality evidence, or SFU state. After restart, clients reauthenticate and rebuild media. No restored room is considered online until fresh sessions connect. Status owns the selected deployment mode and ADR-0002 owns storage validation.

The Host Browser may persist its creation preferences, including policy and an optional room password. Raw Viewer grants never enter localStorage, cookies, queries, server logs, or SQLite. Credentials, passwords, and invitation URLs are never committed to the repository.