Files
piik/docs/standards/rooms-access.md
T
AAA 499789671c feat(app): bring Android sharing and touch control into the shared runtime (#504)
## Problem and outcome / 问题与结果

Bring Android into Piik's shared App workflow and make phone control usable without a separate Web UI. One signed APK covers ARM64 and x64; screen capture, room authority, routing, voice and site approval reuse the existing Go and Browser owners. Android opens the user's system browser rather than shipping an embedded browser.

This phase also fixes capture replacement and encoding-clock failures, improves source-audio startup, contains recoverable input and transport failures, adds a bounded relay-volunteer setting and supports hostnames in `SFU_PUBLIC_IP`. The website separates desktop and mobile downloads, gives iOS users an online entry and aligns the bilingual installation guides.

Related reports: #495, #499, #500, #501, #502 and #503. For #502, input execution failures now preserve authorization, and temporary target observations suspend rather than revoke it; the original Windows report remains open for candidate feedback.

## Release notes

**Piik, now in your pocket.**

Piik App now supports Android screen sharing, with touch controls for a friend's computer.

**手机,也能开播。**

Piik App 现已支持 Android 屏幕分享,也能用手机控制朋友的电脑。

### English

Piik v2.5.0 brings the App to Android and improves capture reliability, touch control and everyday startup. The existing 2.x compatibility baseline is unchanged.

- **Android App:** share your screen, join room voice or control a supported computer. One APK supports ARM64 and x64, using your own browser and the same Piik interface.
- **Phone controls:** use direct touch or a compact floating mouse with dragging, left/right buttons and a scroll wheel. Pinch to zoom and pan the picture while controlling.
- **More reliable sharing:** keep video progressing through source and encoder-output changes, and improve low-bitrate recovery and stationary-screen keyframes. Correct Windows window-size handling and Linux NVENC settings; start optional source sound after video is ready.
- **Smoother App entry:** retry failed startup in place, reopen the running room and retain the correct App connection when returning from the browser. Compress shared page assets to reduce loading traffic and keep microphone choices stable during ordinary page updates.
- **Recovery stays local:** a rejected input or canceled source replacement no longer revokes remote-control permission. Full ICE candidate queues and failed audio-parameter updates retain healthy connections. A failed local room leaves the App and unrelated approved sites running.
- **Connection settings:** relay volunteers can cap their downstream viewers. Self-hosted SFU setups can use a DNS hostname in `SFU_PUBLIC_IP`.
- **Clearer help:** refine sharing-error guidance, preserve input-failure diagnostics without recording input content, and update the bilingual platform and network guides.

Update both the App and your self-hosted site to use the new features. Android can control a supported computer; the Android device itself is not a controlled endpoint.

If you previously installed a test APK, uninstall it once before installing this release: the official signing key is different. Uninstalling clears App-local site approvals and starred-site choices; browser settings remain in the browser. Later official releases can be installed over this one.

### 中文

Piik v2.5.0 带来 Android App,并改善采集稳定性、手机远控与日常启动体验。沿用现有 2.x 兼容基线。

- **Android App:** 分享手机画面、加入房间语音,或控制支持远控的电脑。一个安装包同时支持 ARM64 与 x64,使用自己的浏览器和熟悉的 Piik 界面。
- **手机远控:** 直接触摸操作,或展开小巧的悬浮鼠标,使用拖拽、左右键与滚轮;控制时也能双指缩放、移动画面。
- **分享更稳定:** 修复切换采集来源、编码输出时画面停止推进的问题,改善低码率恢复与静止画面的关键帧响应。修正 Windows 窗口尺寸处理和 Linux NVENC 设置,来源声音会在画面就绪后启动。
- **App 进出更顺畅:** 启动失败可原地重试,再次打开会回到正在运行的房间;从浏览器返回时保持连接到正确的 App。共用页面资源启用压缩,减少加载流量,麦克风选项不再随普通页面更新反复加载。
- **局部问题就地恢复:** 单次操作失败或取消换源不再撤销远控授权;ICE 候选队列满或音频参数调整失败时保留健康连接。本地房间故障不会连带停止 App 和其他已授权站点的分享。
- **连接设置:** 帮助转发的观众可设置承接人数上限;自部署 SFU 的 `SFU_PUBLIC_IP` 现在支持 DNS 主机名。
- **排查更直接:** 打磨分享失败提示,补充不记录输入内容的远控故障诊断,并更新中英文平台说明与网络指南。

使用新功能时,请一起更新 App 与自部署站点。Android 可作为控制端操作电脑,手机本身不作为被控端。

曾安装测试 APK 的用户需先卸载一次,再安装正式版,两者签名不同。卸载会清除 App 内的站点授权和收藏,浏览器设置仍保留在浏览器中;后续正式版可直接覆盖安装。

## Verification / 验证

- Local full Web/type/build checks passed: 104 test files, 1,848 tests; the website and documentation builds passed.
- Android full-App emulator acceptance covered real decoded screen sharing, concurrent 1080p/540p encoder allocation, live bitrate changes, stationary keyframes, Viewer departure, consent reuse/reentry and final capture-resource retirement.
- A local universal release APK passed signing, package identity, version-code, ABI and non-debuggable checks using the permanent release key. GitHub Actions receives the same key through encrypted Secrets; manual candidate runs use a disposable candidate signer.
- Windows real capture checks covered H264/VP8 window resizing and restoration. Source-audio startup and failure/close ordering passed focused runtime checks; Linux race checks passed.
- Desktop/mobile website layouts were reviewed in English and Chinese, both themes, including grouped downloads, the iOS online entry and self-hosting links.
- All three Server and six App candidate targets, including the signed Android universal APK, passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40350004792. This uses the same release packaging path with publication disabled.
- The complete network laboratory passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40354253735: 43 expected scenario outcomes (37 media connections, six expected-unavailable controls), six negative controls, and complete process/network cleanup.
- Recoverable-error checks cover real encrypted input replies and legacy opt-in, retained grants and held-key cleanup, real Windows target geometry recovery, candidate queue overflow, and audio-parameter retry on the existing edge. Android room failure and full shutdown use real launcher, control WebSocket and supervised-process checks; unrelated site resources remain intact.
- The lifecycle fixes at `7eb04de373567cfe7aff2db6c93adf2a38e0b1aa` passed all nine package targets and Go/vulnerability/race/Web checks in https://github.com/TNTcraftHIM/Piik/actions/runs/40362794088, including macOS x64/ARM64 cgo and Android. Publication was skipped.
- Final cross-review found and fixed the same candidate-overflow false failure in the SFU voice owner. Its real-Pion regression verifies the first 64 candidates remain queued, a valid answer drains them, and renegotiation succeeds. Independent reviews confirmed real SDP and authorization failures still propagate.
- A real-browser before/after check reduced microphone enumeration from nine calls to one across eight ordinary Host rerenders. Changing the native client or switching to Browser capture still enumerates the new devices. The separate focused contribution #507 preserves input focus during queued floating-panel opening and is not attributed to this phase.
- The verified Windows candidate and reproduction steps have been updated in #502. macOS/Linux physical-device coverage and iOS device acceptance keep their documented boundaries.

## Impact / 影响

- Planned release: **v2.5.0**; no public wire or storage version bump.
- Android is a sharing and controlling endpoint, not a remotely controlled Android device. iOS is held outside this release.
- New Android release target joins the existing complete-target, checksum, GitHub and Gitee artifact pipeline. Signing material stays outside Git; optional input SDKs/drivers are not bundled.
- The owner authorized closure and publication after the final design review and acceptance checks. Restore the publication gate after the held focused contribution and merge this complete phase once; CI publishes only after its full checks and registered packages pass.
- Current TODO, platform guidance, media/routing evidence and release operations retain their existing document owners; no additional audit ledger or changelog archive is introduced.
2026-10-26 13:37:33 -04:00

17 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.

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.