Files
piik/docs/standards/rooms-access.md
T
TNTcraft e25bd00950 feat(maintenance): improve invitations and playback controls
## Problem and outcome / 问题与结果

Inviting another device, changing sources and adjusting playback should preserve the selected access and accepted settings. This update adds local QR invitations, optional translations and a video buffer setting, and repairs App discovery, source retirement, shared controls, remote-input geometry and audio reporting within the existing 2.x contracts.

## Release notes

### English

This update makes invitations easier to share and playback easier to adjust, while improving App connection, source switching and everyday controls. It also adds optional interface translations and more useful audio diagnostics.

- Show the current invitation as a locally generated QR code for another device to scan, preserving the selected access information.
- Add optional Traditional Chinese, Japanese and Korean translations. Chinese and English remain direct choices; the third menu includes extra languages and visual mode. Missing translations use English.
- Add an **Increase playback buffering** switch with an adjustable target. More buffering may reduce stalls from uneven packet arrival, at the cost of added viewing delay. Automatic remains the default.
- Ignore remote-control clicks on blank space outside a zoomed or rotated video.
- Check for a local Piik App once when a site opens. Automatic discovery respects local-network permission; explicit connection keeps approval under your control, and passive failures stay quiet.
- Keep a pending Browser screen or camera selection when the previous Native source ends or the App disconnects. Release the old source while allowing the new selection to finish; cancellation and Stop still end the operation correctly.
- Improve App-to-App connections when port mappings shift during setup.
- Keep playback hints clear of sharing controls, selection indicators inside their tracks, disabled action icons visible, and numeric settings aligned with accepted values.
- Use receiver audio reports for outgoing shared-sound loss statistics, and add opt-in Windows capture-progress diagnostics to help locate missing audio.

Existing 2.x App/site compatibility, saved room data and invitation privacy are preserved. Update the App for Native changes. After updating a hosted Server, refresh open site pages; App-local pages use the Web UI included in the updated App package.

### 中文

本次更新让邀请分享和播放调整更方便,并改善 App 连接、切换来源及日常控件。同时增加可选界面译文和更有帮助的音频诊断。

- 将当前邀请在本地生成二维码,保留所选访问凭证,方便另一台设备扫码加入。
- 增加繁体中文、日语和韩语可选译文。中英文保留快捷入口,第三个菜单提供附加语言与纯视觉模式;缺少的译文回退英文。
- 增加 **增加播放缓冲** 开关,并可调整目标值。更多缓冲可减少数据到达不均造成的停顿,但会增加观看延迟;默认仍由系统自动决定。
- 缩放或旋转画面后,不再把画面外空白区域的点击误传给远端。
- 打开站点时检查一次本地 Piik App。自动发现遵循本地网络权限,主动连接时才由你批准访问;被动发现失败保持安静。
- 旧 Native 来源结束或 App 断开时,保留正在进行的浏览器屏幕或摄像头选择。释放旧来源后仍可完成新选择;取消或主动停止时正确收尾。
- 改善建立连接时端口映射变化情况下的 App 间连接。
- 避免播放提示遮挡分享控件,让选中指示保持在轨道内,保留禁用按钮图标,并让数值设置显示实际接受的值。
- 共享声音的发送端丢包统计改用接收方音频报告,并增加可选的 Windows 采集进度诊断,帮助定位无声发生在哪一段。

保留现有 2.x App/站点兼容性、已保存的房间数据和邀请隐私。Native 改动需要更新 App。托管 Server 更新后请刷新已打开的页面;App 本地页面使用新版 App 包内的网页。

## Verification / 验证

- Complete frontend check: TypeScript, 110 test files / 2001 tests, Web build. Go core check: format, tests, vet and supported cross-target builds; macOS App builds require their native SDK.
- QR invitations passed independent local decoding, credential/rotation checks and short-window layout. Language/visual menus and guidance passed native and forced-polyfill Browser checks.
- Native preparation passed actual Pion socket adoption, VP8 SRTP and reverse SRTCP controls. Remote-input geometry and accepted numeric settings have focused regressions.
- Optional buffer transitions passed real P2P and actual SFU subscriber receiver-API controls for automatic to 300 ms to automatic. The SFU control used a Browser mock upstream rather than the embedded backend; Native preview delegation has unit coverage only.
- Windows diagnostics passed strict translation compilation, counter tests and stderr-to-diagnostic-ZIP verification. Physical capture, optical QR scanning and a public-network success-rate improvement are not claimed.

## Impact / 影响

Compatible 2.x update: Browser/server v24, Native control v10, capture v7 and SQLite schema 2 remain unchanged. Optional translations preserve English fallback and the independent visual preference. Playback buffer is a local viewing preference and leaves the default automatic. Existing room authority and invitation handling are preserved.

The HTTP compression dependency receives a compatible patch update. Mirror preparation detects a rejected missing tag before original-artifact downloads; the platform restriction remains open, with original-package validation and continuation rules intact. This does not establish fixes for #499, #502, #529 or #534.
2026-11-15 18:23:50 -04:00

18 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 production destination: HTTPS retains the Secure host-prefixed cookie, while a separately configured HTTP origin, such as App loopback, uses 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.

The invitation QR code is generated locally from the same selected link, including its fragment. Credential choice, rotation and revocation update it with the copied link; no external QR service receives the invitation.

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.

A send-confirmation timeout releases the send control without retransmitting. A late reply on the same connection can still settle the latest submitted send; another submitted send or reconnection retires that confirmation identity. Only confirmation of the matching chat text clears its draft.

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

Room Voice

Optional room voice uses the same authenticated room. The Host joining opens room voice; leaving closes it for everyone. Channel availability is derived from that membership, not a separate switch. Authenticated room members can join an open channel without another approval. Joining never opens a microphone. Closing clears everyone's voice membership and publications; reopening does not rejoin Viewers or restart microphones. Each speaker explicitly starts capture and owns one server-assigned publication; mute, leaving and session replacement retire that publication. Local mute changes only the listener's playback, including when that listener relays for others. Pausing listening mutes all local room-voice playback without changing the microphone, membership or forwarding. Microphone and listening are independent. The Host owns one room-wide voice bitrate ceiling. Changing it does not open voice, activate microphones or replace routes. It is live room state, not App configuration; media quality owns its bounds.

Joining also authorizes a participant to forward decodable voice. A video relay outside voice cannot carry it; the existing route controller selects a joined path or reports that voice is unavailable. Local deafening never removes that forwarding responsibility. This is transport encryption between neighbors, not end-to-end encryption against an admitted relay or the SFU operator.

Voice membership and routes outlive picture pause, stop and source replacement. Leaving voice releases its microphone and forwarding demand; room retirement or authorization loss ends the corresponding voice authority. Runtime voice state is not persisted. The routing contract owns placement and recovery; status indexes delivery.

Remote Control

Remote input belongs to one active App-owned window or screen share. The Host explicitly enables it for that source using Ask each time, Room Viewers or a separate control password. Viewer identity and requests reuse authenticated room membership; grants and encrypted input stay bound to the current route and source. Changing the source, stopping sharing, authorization loss or route retirement releases the corresponding grants and held input. Reconnection requires a new grant. Preparing a source replacement preserves the current source's authorization; failed preparation or cancellation does not retire a still-active source. An individual input execution failure drops that operation and preserves the grant. Failed key/button releases remain owned cleanup; only releases are retried, never presses, movement or text. Missing current target geometry suspends input until observation recovers; confirmed target identity loss retires its grants.

Remote control defaults to one controller. The Host can enable Allow simultaneous control for the current source so approved, capability-negotiated Viewers share input through the same authorization choice. Changing this setting retires current requests and grants without changing the authorization mode or password; replacing the source resets it off. Older published clients retain the exclusive keyboard/mouse baseline. Gamepad support and participant presentation remain available with simultaneous control off. One grant authorizes one Viewer to use keyboard/mouse and an optional supported gamepad. Switching or combining input devices requires no additional approval. The simultaneous-control limit counts approved Viewers, not device types. Held keys and mouse buttons belong to each grant; releasing one participant cannot release another's still-held inputs. All approved keyboard/mouse grants contribute to the same pointer, with no per-player mouse assignment or join-order priority. Committed text insertion is available with one approved Viewer and pauses while two or more grants coexist; physical key input remains available. Input still belongs to one process-wide source owner, not multiple simultaneous shares.

Collaboration markers describe granted participation, not live key or pointer activity. The Host publishes the native grant owner's current input endpoints; room signaling resolves their authenticated room identities and distributes a read-only, share-scoped snapshot to opted-in Viewers. Pending requests are not participants, and stopped sources or replaced endpoints cannot retain a marker. This presentation neither grants control nor creates another routing path.

Optional Windows x64 gamepad use creates independent Xbox 360 devices through the public device interface of an already-installed ViGEmBus. Optional input drivers and third-party input SDK binaries stay external on every platform: Piik does not download, install or bundle them. Each approved Viewer owns their virtual device under the same remote-control grant. Windows is subject to the four XInput slots shared with the Host's existing devices; slot limits belong to the platform backend. Driver connection and target creation determine availability; keyboard/mouse input continues when the optional backend is unavailable. Linux uinput has kernel-level validation; macOS virtual HID remains a prototype, with platform permissions and evidence limits recorded in the co-play assessment.

Losing shared-window focus releases held input and neutralizes gamepads while keeping grants suspended. Disconnecting a gamepad neutralizes and removes only its device; ending remote control releases every input owned by that Viewer. The Host's stop shortcut ends all remote input. The reader guide owns usage and driver setup; interaction research owns backend rationale and measurements.

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.