Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

feat(rooms): prefer the last available room code

AAAd52f1b950b6e
diff --git a/docs/adr/0002-memory-resident-protected-rooms.md b/docs/adr/0002-memory-resident-protected-rooms.md
index 949fe223..2d206a4b 100644
--- a/docs/adr/0002-memory-resident-protected-rooms.md
+++ b/docs/adr/0002-memory-resident-protected-rooms.md
@@ -38,10 +38,12 @@ All room state lives in the authoritative application process:
verifier;
- authorization generations and the existing signaling/route state.
-The free-code pool contains every currently unallocated four-digit code. Room
-creation selects uniformly from that pool, and room release returns the code to
-it. `MAX_ROOMS` must not exceed the 9,000-code space; its product default remains
-1,000. A room code is a locator, not a secret or permanent identity.
+The free-code pool contains every currently unallocated four-digit code. A room
+creation request may name one locally preferred code: the store takes it only if
+it is still in the free pool, otherwise it selects uniformly from the current
+pool. Room release returns the code to that pool. `MAX_ROOMS` must not exceed the
+9,000-code space; its product default remains 1,000. A room code is a locator and
+best-effort preference, not a secret, reservation, or permanent identity.
`ROOM_LEASE_SECONDS` is the single room-lifetime setting and defaults to 86,400
seconds. An authenticated, actively sharing Host prevents expiry. When sharing
@@ -52,7 +54,7 @@ invalidates its credentials, and releases its code.
Process restart deliberately clears every room, lease, credential digest,
password verifier, and participant. Old Host records and invitations then fail
-closed, and the next Host share creates a new room. There is no room database,
+closed, and the next Host share creates a new room incarnation. There is no room database,
`ROOM_DATABASE_PATH`, persistent-room mode, schema migration, or compatibility
reader. The site-access secret remains deployment configuration rather than room
state.
@@ -65,13 +67,18 @@ raw token in same-origin `localStorage`; the server keeps only its digest in the
current room. Clearing local data or changing browser/device loses ownership.
The Host browser also keeps one local creation profile containing its display
-name, code-entry policy, and optional room password. When an old room no longer
-exists, the next explicit share creates a new room and atomically reapplies that
-profile, so the same browser retains its preferences but receives a new code,
-Host token, and Viewer grant. The site-access password is never part of this
-profile. A Host room password may be stored locally as a convenience for this
-private product; the server receives it only over the authenticated creation or
-update path, derives the verifier, and never stores or logs the plaintext.
+name, code-entry policy, and optional room password, plus an independent
+non-secret preferred room code. It has no deadline while the Host is sharing;
+normal stop starts a local deadline equal to that room's configured lease
+duration (24 hours by default). When old ownership no longer works, the next explicit
+share requests the still-current preferred code and atomically reapplies the
+creation profile. A free code may therefore be reused, but the result always has
+a new Host token, Viewer grant, password material, lease, and room incarnation;
+an occupied or expired preference falls back to random allocation. The site-access
+password is never part of this profile. A Host room password may be stored locally
+as a convenience for this private product; the server receives it only over the
+authenticated creation or update path, derives the verifier, and never stores or
+logs the plaintext.
### Orthogonal Viewer Access
@@ -135,8 +142,9 @@ the generic `SERVER_ERROR`. None of those paths is folded into
invitations. Active media already disconnects at that boundary; the additional
cost is a new room code and invitation. Same-browser Host preferences are
reapplied automatically on the next explicit share.
-- A room unused beyond the lease is released. With a 24-hour value, any dormant
- interval longer than 24 hours produces a new code.
+- A room unused beyond the lease is released. The local code preference likewise
+ starts its configured lease countdown on normal stop; active sharing does not
+ count down.
- Recycled code-only bookmarks may eventually identify a different room. A stale
grant remains unusable because the new room has a different digest.
- Multi-process room coordination, seamless restart, and horizontal scaling are
@@ -157,8 +165,10 @@ the generic `SERVER_ERROR`. None of those paths is folded into
valid for exactly the current room incarnation and has no independent expiry.
`open` and `private` code entry, including private rooms with and without a
password, are covered independently from grant rotate/revoke.
-- Same-browser recreation reapplies the Host profile; another browser or cleared
- storage does not. No fingerprint or server user record participates.
+- Same-browser recreation reapplies the Host profile and requests a current
+ preferred code only while it is free; another browser, cleared storage, an
+ expired preference, or an occupied code uses random allocation. No fingerprint
+ or server user record participates.
- Raw site passwords, Host tokens, Viewer grants, and room passwords remain out
of application/proxy logs and server durable storage.
- On the accepted `screener-v12` Browser wire, a well-formed, site-authorized
diff --git a/docs/todo.md b/docs/todo.md
index dece978a..8a4c03d8 100644
--- a/docs/todo.md
+++ b/docs/todo.md
@@ -7,16 +7,20 @@ later topic is not implementation authority by itself.
## Now
-1. **Browser VP8 hardware evidence.** Measure supported Chrome/Edge platforms
+1. **Preferred room reacquisition.** While sharing, keep the last assigned code
+ as an unexpired local preference; normal stop starts the configured room
+ lease countdown. A new room may request that code, but the server uses it
+ only while free and always creates a new room incarnation and credentials.
+2. **Browser VP8 hardware evidence.** Measure supported Chrome/Edge platforms
under real game load using actual codec, encoder implementation, encode time,
frame rate, and CPU/GPU attribution. Do not add another codec, custom encoder,
GPU selector, or Native helper without a new decision.
-2. **Mobile Viewer lifecycle.** Run Android Chrome and iOS Safari matrices for
+3. **Mobile Viewer lifecycle.** Run Android Chrome and iOS Safari matrices for
autoplay gesture, foreground/background audio, foreground video recovery,
lock/page reclamation, rotation, Wi-Fi/cellular migration, and assigned-relay
survival or controller recovery. Web does not promise background video or
relay execution after OS suspension.
-3. **Finish real-network route and media acceptance.** Exercise direct peer,
+4. **Finish real-network route and media acceptance.** Exercise direct peer,
Browser relay, SFU, relay-ingress recovery with subtree retention,
disconnect/capacity drain, Pause/Resume, source replacement, screen-audio
continuity, and real-game A/V sync across representative IPv4/IPv6,
@@ -27,36 +31,33 @@ later topic is not implementation authority by itself.
## Accepted Later Roadmap
-1. **Preferred room reacquisition.** Keep the last assigned four-digit code and
- its 24-hour preference window in the Host browser. When prior ownership is
- no longer valid, the next explicit share requests that code only if the
- preference is still current; the server grants it only while free and
- otherwise uses normal random allocation. This does not reserve a dormant
- code or restore the old room incarnation, Host token, Viewer grant, password
- verifier, lease, participants, or routes.
-2. **Quality-based topology research.** After the real-network baseline, decide
+1. **Quality-based topology research.** After the real-network baseline, decide
whether measured user-visible quality justifies any active parent-selection
mechanism. Current evidence cannot compare an active route with an
unconnected alternative, so no quality score, all-pairs probing, periodic
rebalancing, relay abdication threshold, or active parent switch is accepted.
Prefer mature algorithms and one general model if this boundary is reopened.
-3. **Platform output only when real.** Revisit AirPlay/Cast only when a target
+2. **Platform output only when real.** Revisit AirPlay/Cast only when a target
browser and physical receiver prove the live `MediaStream` contract. System
mirroring remains external.
-4. **Public-server one-click package.** After functional and real-network work,
+3. **Public-server one-click package.** After functional and real-network work,
package the exact application, STUN/SFU, reverse proxy, secrets, and health
checks for a user-owned public server. Do not call a partial installer ready.
-5. **Fully local one-click package.** Package Windows/macOS/Linux Host capture,
+4. **Fully local one-click package.** Package Windows/macOS/Linux Host capture,
application server, and local state without requiring source or Node. Report
public-origin, TLS, gateway, NAT, and firewall limits honestly.
-6. **Native Host and shared encode, Windows first.** Productize only after real
+5. **Native Host and shared encode, Windows first.** Productize only after real
capture, hardware-only encode, audio, identity, RTP/RTCP feedback, resource,
packaging, and licensing gates pass. Browser Host/relay keeps standard
per-`RTCPeerConnection` encoding.
-7. **Whole-product UI and bilingual decision.** Once media and route behavior
+6. **Whole-product UI and bilingual decision.** Once media and route behavior
stabilizes, review copy, responsive hierarchy, visual consistency, restrained
motion, bundle/rendering cost, and Chinese/English scope once as a whole.
Ordinary screen-specific edits do not create parallel documentation.
+7. **Client-input security review.** Inventory HTTP and WebSocket inputs once as
+ a whole: strict schemas, authentication, authorization, rate and body bounds,
+ resource effects, error disclosure, logging, and secret handling. Begin
+ read-only and add no parallel security framework without a proven gap.
8. **Repository simplification audit.** After the Browser, route, room, and
physical-media checkpoints settle, inventory components, configuration,
migrations, timers, compatibility paths, tests, and truth duplication using
diff --git "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md" "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
index ebeb8063..5cee8f57 100644
--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
@@ -80,11 +80,11 @@ code-only policy 使用单一 `open | private` 状态:`open` 是无房间密
房间准入管理统一使用同源 `POST /api/rooms/{roomId}/access`:site-access cookie 与 `Authorization: Bearer {hostToken}` 共同授权一个受 schema 约束的 policy、password、rotate 或 revoke 动作。该控制面在分享活动和休眠期间语义相同,不建立 Host participant/WebSocket/media route,不改变 `sharingActive` 或 dormant lease;rotate/revoke 的现有强撤销副作用保持不变。
-Host 的同源 `localStorage` creation profile 保存显示名、code-only policy 和可选房间密码,使进程重启或租约过期后的下一次显式分享可原子应用同一偏好。该密码只保存在 Host 浏览器;不保存在 Viewer 浏览器、URL/query/fragment、cookie、日志、错误或服务器持久存储。建房/更新请求通过 HTTPS 把明文短暂交给服务端,服务端使用 Node 标准异步 `scrypt` 固定 `N=16384,r=8,p=1`、16-byte 随机 salt 和 32-byte verifier,只在当前房间内存保存 48-byte material。进程级 gate 最多执行 2 个、等待 16 个派生,队满即有界失败;任务开始和提交前都复核当前 Host authority 与 room material。不存在、已回收或已过期房间使用 `ROOM_NOT_FOUND`;现存房间的未配置/错误密码和正确密码后的满房使用 `ROOM_ACCESS_DENIED`。
+Host 的同源 `localStorage` creation profile 保存显示名、code-only policy 和可选房间密码,使进程重启或租约过期后的下一次显式分享可原子应用同一偏好。建房响应同时返回实际 `roomLeaseSeconds`;Host ownership 保存该值,独立的 preferred-room 记录保存上次四位号码和 nullable 截止时间。Host 鉴权分享时截止时间为 `null`,正常停播时写为 `now + roomLeaseSeconds`;清除失效 ownership 不清除仍有效的号码偏好,也不建立刷新 timer。该密码只保存在 Host 浏览器;不保存在 Viewer 浏览器、URL/query/fragment、cookie、日志、错误或服务器持久存储。建房/更新请求通过 HTTPS 把明文短暂交给服务端,服务端使用 Node 标准异步 `scrypt` 固定 `N=16384,r=8,p=1`、16-byte 随机 salt 和 32-byte verifier,只在当前房间内存保存 48-byte material。进程级 gate 最多执行 2 个、等待 16 个派生,队满即有界失败;任务开始和提交前都复核当前 Host authority 与 room material。不存在、已回收或已过期房间使用 `ROOM_NOT_FOUND`;现存房间的未配置/错误密码和正确密码后的满房使用 `ROOM_ACCESS_DENIED`。
邀请使用 `/r/{roomId}#v={grant}`。RFC 3986 要求 fragment 在 dereference 前由 user agent 分离,因此 HTTP request-target 与反向代理 access log 看不到它;WHATWG WebSocket 还明确拒绝含 fragment 的 URL。客户端只从页面 URL 严格解析一次,把 grant 写入 `screener:viewer-grant:{roomId}` 的 `sessionStorage`,随即以 `history.replaceState` 把地址栏替换为 canonical `/r/{roomId}`;刷新和页面内 WSS 重连继续使用该页面会话的值。Host 建房/rotate 收到的 raw grant 同样只在内存和 room-scoped `sessionStorage` 中保留,用它临时构造复制链接;`localStorage` 的 room ownership 只包含 canonical URL、room ID、Host token 和期限。grant 不进入 cookie、query、WebSocket URL、Referrer、日志或错误。生产继续发送 `Referrer-Policy: no-referrer`;fragment 与该 header 降低传输泄漏,但不能防止原邀请消息、浏览器扩展、截图或用户转发,UI 必须把链接称为访问凭据。
-房间只有一种易失模型。进程启动时建立 `1000..9999` 的空闲码池;创建房间时用加密随机索引从当前空闲集合取出一个号码并以 swap-remove 删除,释放时放回。这样在 9000 个号码内没有碰撞重试、递增身份或数据库序列。`MAX_ROOMS` 默认 1000 且不得超过 9000。
+房间只有一种易失模型。进程启动时建立 `1000..9999` 的空闲码池;创建房间可携带一个严格四位 `preferredRoomId`,若它仍在空闲池则以同一个 swap-remove 取走,否则用加密随机索引从当前空闲集合分配,释放时放回。偏好请求不预占、不替换现存房间,也不改变新房凭据生成。这样在 9000 个号码内没有碰撞重试、递增身份或数据库序列。`MAX_ROOMS` 默认 1000 且不得超过 9000。
`ROOM_LEASE_SECONDS` 默认 86400。RoomStore 对连接中的 Host 不执行到期;Host 明确停止或连接消失时将 `expiresAt` 设为 `now + lease`,同一 Host token 在期限内重新鉴权并分享时续租,Viewer 活动不修改期限。清理循环删除 dormant expired room、关闭其 session/route/resource 并把号码归还空闲池。应用进程重启直接清空全部房间;配置不再包含 `ROOM_DATABASE_PATH`、`ROOM_TTL_SECONDS` 或任何 schema/migration。所有房间继续生成 256-bit Host token,Host 浏览器保存 raw token,服务器当前进程只保存摘要;不使用 IP、UA、设备信息或浏览器指纹认领。
@@ -137,7 +137,7 @@ accepted 的唯一 wire 是 `screener-v12`,不做版本协商、旧 parser、
分享者是唯一 offerer。每名观看者对应一个 `RTCPeerConnection`,以独立 `connectionId` 区分重建代次:
1. 分享者在开始按钮的同一用户手势内先成功调用 `getDisplayMedia()`。
-2. 只有捕获 track 已存在时才请求创建或续租房间、连接 Host WebSocket 并显示邀请。新建请求携带本地 creation profile,使 code-only policy 与可选密码 verifier 在房间可见前原子生效;若用户在响应返回前取消,迟到结果不得覆盖后续分享会话,尚未认领的房间通过内部 `abandon-room` 立即释放号码。已经认领的房间在停止捕获后进入 dormant lease,过期才释放。
+2. 只有捕获 track 已存在时才请求创建或续租房间、连接 Host WebSocket 并显示邀请。新建请求携带本地 creation profile 和仍有效的 preferred room,使 code-only policy、可选密码 verifier 与号码分配在房间可见前原子生效;偏好号码已占用时服务端直接随机分配。若用户在响应返回前取消,迟到结果不得覆盖后续分享会话,尚未认领的房间通过内部 `abandon-room` 立即释放号码。已经认领的房间在停止捕获后进入 dormant lease,过期才释放。
3. 观看者认证后,服务端向在线分享者发送 `peer-joined`;host 晚上线或重连时收到完整观看者快照。
4. 分享者创建连接、加入当前视频 track,并以现有音轨或空 sender 预留 audio transceiver,设置 sender 参数,然后创建 offer。
5. 观看者收到 offer 后创建连接、设置 remote description、创建 answer。
diff --git "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md" "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
index 7e5c5adf..2f9b6689 100644
--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
+++ "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"
@@ -37,7 +37,7 @@ SFU 的 publication、subscription、server-resource accounting、临时 overlap
- 站点访问:生产部署必须配置独立的 `SITE_ACCESS_PASSWORD` 控制建房、Host 信令角色和所有 code-only Viewer 入口;只有本地开发/测试可显式关闭。非空值接受 8 至 128 个可见 ASCII bytes,不能复用 LiveKit、TLS 或其他部署 secret。`POST /api/site-access` 验证成功签发 12 小时、无服务端会话状态的 HttpOnly、`SameSite=Strict` site-access cookie。有效 room-scoped fragment grant 可绕过站点 gate 直接进入对应房间;其余 `/r/{code}` 和 `/join` 必须先持有效 site-access cookie,之后才检查房间是否存在与 `open | private` code-only policy。未分配、已回收或已过期的 code 返回 `ROOM_NOT_FOUND`;现存私密房间的无密码、缺失或错误密码及容量拒绝继续使用 `ROOM_ACCESS_DENIED`。建房 HTTP 只认该 cookie。已移除的旧环境变量、endpoint 和 cookie 不保留兼容。不引入账号、JWT、服务端 session Map 或通用 logout。
- 房间级观看授权:新房间总是生成一个 128-bit 随机、22 字符 base64url、可 rotate/revoke 的 room-scoped Viewer grant;服务端内存只在该 exact room incarnation 保存完整 grant 的 SHA-256 摘要。grant 没有独立到期时间或内嵌 room/expiry 字段,与房间同寿,并在房间回收、进程重启、rotate 或 revoke 时失效;同号新房间使用新摘要,旧链接不能进入。浏览器从 URL fragment 严格读取 grant 后,只写该房间的 `sessionStorage` 并立即用 `history.replaceState` 清除 fragment;刷新和页面内重连可继续。code-only 入口独立采用 `open | private`,默认 `open` 且无房间密码;`private` 可不设密码并拒绝全部 code-only 尝试,设置密码后只接受匹配值。所有 code-only 尝试先通过站点访问。grant 不得进入 `localStorage`、cookie、query、WebSocket URL、Referrer、日志或错误。Host 可独立 rotate/revoke grant、改变 code-only policy 或设置/移除密码;授权变化必须先提交新的内存代次,再清除 Viewer grace/路由、终止旧代次信令和媒体并断开受影响 Viewer。
- 易失房间状态:服务器只在一个有界内存 RoomStore 中保存房间码、租期、Host token/Viewer grant 摘要、code-only policy、可选 48-byte 房间密码校验材料、参与者和控制状态。`ROOM_LEASE_SECONDS` 默认 `86400`;Host 正在分享时不回收,停止分享或 Host 断开后开始 dormant lease,同一 Host token 在期限内重新分享即续租,Viewer 活动不续租,过期后释放号码。应用进程重启时全部房间、租约、邀请和密码状态直接失效;不使用 SQLite、`ROOM_DATABASE_PATH`、schema migration、账号、用户表或服务器 session 表。
-- 本地 Host 偏好:房间所有权继续使用随机 Host token,不使用 IP、UA、硬件信息或浏览器指纹。Host 浏览器在同源 `localStorage` 保存 raw Host token,以及昵称、code-only policy 和可选房间密码组成的创建偏好;服务器只在当前进程内保存 token 摘要和密码 verifier。旧房间不存在时,下一次显式分享创建新房间并原子应用本地偏好,同时生成新的四位房间号、Host token 和 Viewer grant。换设备、换浏览器或清理站点数据即不恢复。
+- 本地 Host 偏好:房间所有权继续使用随机 Host token,不使用 IP、UA、硬件信息或浏览器指纹。Host 浏览器在同源 `localStorage` 保存 raw Host token,以及昵称、code-only policy 和可选房间密码组成的创建偏好;另以无秘密记录保存上次分配的四位号码。Host 分享中该偏好不倒计时,正常停播后按该房间实际 `ROOM_LEASE_SECONDS` 开始截止时间(默认 24 小时)。服务器只在当前进程内保存 token 摘要和密码 verifier。旧 ownership 失效后的下一次显式分享仅在偏好仍有效时请求原号码;服务端只在号码空闲时分配,否则随机分配。两种结果都创建全新 room incarnation、Host token 和 Viewer grant,不恢复旧租约、密码材料、成员或路由。换设备、换浏览器或清理站点数据即不恢复。
### P1 - 重要功能
- 公网服务器一键部署包:在用户自有的公网服务器上一键部署当前 Web/信令应用、易失房间状态和所需 STUN/SFU/反向代理组件,复用唯一配置、secret、路由、健康检查和恢复合同。普通 app-only 更新先验证新的不可变 artifact 再原子切换,切换前 application release 只保证保留到有限 health/postflight 完成;之后没有保留合同,也不作为维护中的备份。只有实际改动基础设施、配置、secret、持久或不可逆状态时,才为被触及表面定义恢复并预检。它不是托管服务,不能内置真实凭据或跳过域名、TLS、防火墙、端口、容量和适用的恢复预检。
@@ -105,8 +105,8 @@ SFU 的 publication、subscription、server-resource accounting、临时 overlap
- Given 已通过 site access 的 well-formed code-only 尝试对应未分配、已回收或已过期房间,When `screener-v12` 首条信令鉴权到达,Then 服务端返回 `ROOM_NOT_FOUND`,UI 显示“房间不存在或已过期”且不提供密码重试。Given code 属于现存房间但缺失/错误密码、满房或其他已知有界 admission refusal,Then 服务端继续返回 `ROOM_ACCESS_DENIED` 并使用共享 authentication-failed close code,UI 可提供现有可选密码重试和 Host 邀请提示。Given grant 无效,Then 继续使用通用 `INVALID_TOKEN`;Host 鉴权保持独立错误,unexpected internal failure 使用不含 raw message 的 `SERVER_ERROR`。Given Viewer 持另一个房间的 grant、缺失 grant 或自行把 role 改为 Host,Then 不能建房、发布、跨房或绕过 Host token。
- Given Host rotate/revoke Viewer grant,When 新内存摘要和 authorization generation 提交,Then 服务端清除 Viewer grace/路由,命令 Viewer 关闭接收 PC/媒体并让每个 Host/relay/SFU upstream owner 关闭对应旧代次媒体边,最后关闭旧 Viewer socket;rotate 返回一次新 grant,revoke 锁定 grant 路径,code-only policy 保持独立。
- Given Host 浏览器仍持有现存房间的 ownership,When 分享活动或休眠期间更新邀请、code-only policy 或房间密码,Then 同源 HTTP 管理只接受有效 site access 与该房间精确 Host token;操作不建立 Host 媒体会话、不把房间标为分享中、不申请 route/resource,也不续租 dormant lease。rotate/revoke 继续执行同一强撤销,服务端只在 rotate 成功时返回新的 raw grant。
-- Given Host 同源本地偏好保存了 `open | private` 和可选房间密码,When 服务器重启后该 Host 下一次显式开始分享,Then 客户端清除失效 ownership、创建新四位房间并原子重放偏好;新的 Host token 和 grant 替换旧值。Given 换浏览器、换设备或清理站点数据,Then 不恢复这些偏好或所有权。
-- Given 应用进程重启,When 旧 Host、Viewer 或 code-only 链接再次访问,Then 所有旧房间、租约、摘要、密码 verifier 和参与者均已丢弃并 fail closed;运行时不读取数据库、迁移旧 schema 或恢复旧号码。
+- Given Host 同源本地偏好保存了 `open | private`、可选房间密码和仍在该房间配置租期窗口内的上次房间号,When 服务器重启后该 Host 下一次显式开始分享,Then 客户端清除失效 ownership、请求该 preferred room 并原子重放创建偏好;号码空闲时分配给新的 room incarnation,已占用时随机分配。两者都生成新的 Host token 和 Viewer grant。Given 偏好过期、换浏览器、换设备或清理站点数据,Then 不请求旧号码或恢复旧所有权。
+- Given 应用进程重启,When 旧 Host、Viewer 或 code-only 链接再次访问,Then 所有旧房间、租约、摘要、密码 verifier 和参与者均已丢弃并 fail closed;运行时不读取数据库、迁移旧 schema 或恢复旧房间。后续同号分配只能创建凭据完全独立的新 incarnation。
- Given 部署切换了不兼容的当前协议,When 仍打开的旧页面连接新服务端,Then 单一 release/protocol mismatch 边界终止该 session、停止自动重连并明确提示刷新;不得通过旧 parser、双写或双协议继续假连接。
### P2P 与 SFU 兜底
diff --git a/src/client/lib/api.ts b/src/client/lib/api.ts
index eed2cc10..6c4ee4f8 100644
--- a/src/client/lib/api.ts
+++ b/src/client/lib/api.ts
@@ -88,6 +88,7 @@ export async function authenticateSiteAccess(
export async function createRoom(
codeEntryPolicy: CodeEntryPolicy,
roomPassword: string | null,
+ preferredRoomId: string | null = null,
): Promise<CreateRoomResponse> {
const response = await fetch("/api/rooms", {
method: "POST",
@@ -98,6 +99,7 @@ export async function createRoom(
body: JSON.stringify({
codeEntryPolicy,
...(roomPassword === null ? {} : { roomPassword }),
+ ...(preferredRoomId === null ? {} : { preferredRoomId }),
}),
});
diff --git a/src/client/lib/session.ts b/src/client/lib/session.ts
index 7cdd8e74..f56c9d76 100644
--- a/src/client/lib/session.ts
+++ b/src/client/lib/session.ts
@@ -5,20 +5,29 @@ import {
type CreateRoomResponse,
type CodeEntryPolicy,
} from "../../shared/protocol";
+import { z } from "zod";
import { createOpaqueId } from "./opaque-id";
const CLIENT_ID_PATTERN = /^[A-Za-z0-9_-]{8,128}$/;
const HOST_ROOM_STORAGE_KEY = "screener:host-room:v1";
+const HOST_ROOM_PREFERENCE_STORAGE_KEY = "screener:host-room-preference:v1";
const hostRoomStorageSchema = createRoomResponseSchema.pick({
roomId: true,
hostToken: true,
inviteUrl: true,
expiresAt: true,
+ roomLeaseSeconds: true,
});
+const hostRoomPreferenceSchema = z
+ .object({
+ roomId: roomCodeSchema,
+ preferenceExpiresAt: z.string().datetime().nullable(),
+ })
+ .strict();
export type HostRoomIdentity = Pick<
CreateRoomResponse,
- "roomId" | "hostToken" | "expiresAt"
+ "roomId" | "hostToken" | "expiresAt" | "roomLeaseSeconds"
> & { canonicalUrl: string };
export interface HostRoomState extends HostRoomIdentity {
@@ -100,6 +109,7 @@ export function readHostRoom(): HostRoomIdentity | null {
roomId: parsed.data.roomId,
hostToken: parsed.data.hostToken,
expiresAt: parsed.data.expiresAt,
+ roomLeaseSeconds: parsed.data.roomLeaseSeconds,
canonicalUrl: canonicalViewerUrl(parsed.data.inviteUrl),
};
return room;
@@ -109,6 +119,72 @@ export function readHostRoom(): HostRoomIdentity | null {
}
}
+export function readPreferredRoomId(nowMs = Date.now()): string | null {
+ let stored: string | null;
+ try {
+ stored = window.localStorage.getItem(HOST_ROOM_PREFERENCE_STORAGE_KEY);
+ } catch {
+ return null;
+ }
+ if (!stored) {
+ return null;
+ }
+ try {
+ const parsed = hostRoomPreferenceSchema.safeParse(JSON.parse(stored));
+ if (
+ !parsed.success ||
+ (parsed.data.preferenceExpiresAt !== null &&
+ Date.parse(parsed.data.preferenceExpiresAt) <= nowMs)
+ ) {
+ clearPreferredRoom();
+ return null;
+ }
+ return parsed.data.roomId;
+ } catch {
+ clearPreferredRoom();
+ return null;
+ }
+}
+
+export function writePreferredRoom(
+ roomId: string,
+ roomLeaseSeconds: number | null,
+ nowMs = Date.now(),
+): void {
+ if (
+ !roomCodeSchema.safeParse(roomId).success ||
+ (roomLeaseSeconds !== null &&
+ (!Number.isSafeInteger(roomLeaseSeconds) || roomLeaseSeconds <= 0))
+ ) {
+ return;
+ }
+ const expiresAtMs =
+ roomLeaseSeconds === null ? null : nowMs + roomLeaseSeconds * 1_000;
+ if (expiresAtMs !== null && !Number.isFinite(expiresAtMs)) {
+ return;
+ }
+ try {
+ window.localStorage.setItem(
+ HOST_ROOM_PREFERENCE_STORAGE_KEY,
+ JSON.stringify({
+ roomId,
+ preferenceExpiresAt:
+ expiresAtMs === null ? null : new Date(expiresAtMs).toISOString(),
+ }),
+ );
+ } catch {
+ // A storage failure only disables best-effort code reuse.
+ }
+}
+
+export function clearPreferredRoom(): void {
+ try {
+ window.localStorage.removeItem(HOST_ROOM_PREFERENCE_STORAGE_KEY);
+ } catch {
+ // Restricted storage is equivalent to having no local preference.
+ }
+}
+
export function writeHostRoom(
room: HostRoomIdentity | CreateRoomResponse,
): void {
@@ -123,6 +199,7 @@ export function writeHostRoom(
roomId: room.roomId,
hostToken: room.hostToken,
expiresAt: room.expiresAt,
+ roomLeaseSeconds: room.roomLeaseSeconds,
inviteUrl: canonicalUrl,
}),
);
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 2e02b34d..5e9ddc1f 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -64,9 +64,11 @@ import {
type HostRoomState,
mergeAuthenticatedHostRoom,
readHostRoom,
+ readPreferredRoomId,
readViewerGrant,
replaceViewerInvite,
writeHostRoom,
+ writePreferredRoom,
} from "../lib/session";
import {
SignalingClient,
@@ -210,6 +212,7 @@ function hostRoomFromCreated(room: CreateRoomResponse): HostRoomState {
roomId: room.roomId,
hostToken: room.hostToken,
expiresAt: room.expiresAt,
+ roomLeaseSeconds: room.roomLeaseSeconds,
canonicalUrl: canonicalUrl.toString(),
codeEntryPolicy: room.codeEntryPolicy,
inviteUrl: room.inviteUrl,
@@ -247,6 +250,10 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const [room, setRoom] = useState<HostRoomState | null>(() =>
hostRoomFromStored(readHostRoom()),
);
+ const roomRef = useRef(room);
+ useEffect(() => {
+ roomRef.current = room;
+ }, [room]);
const [creationProfile, setCreationProfile] =
useState<HostCreationProfile>(readCreationProfile);
const creationProfileRef = useRef(creationProfile);
@@ -547,6 +554,13 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
}
activeGenerationRef.current = null;
generationRef.current += 1;
+ const currentRoom = roomRef.current;
+ if (notifyServer && currentRoom) {
+ writePreferredRoom(
+ currentRoom.roomId,
+ currentRoom.roomLeaseSeconds,
+ );
+ }
disposeResources(notifyServer);
setNotice(message);
setPhase("ended");
@@ -1410,6 +1424,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const response = await createRoom(
creationProfileRef.current.codeEntryPolicy,
creationProfileRef.current.roomPassword,
+ readPreferredRoomId(),
);
createdRoom = hostRoomFromCreated(response);
if (!isCurrentGeneration(generation)) {
@@ -1510,6 +1525,10 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
...activeRoom,
expiresAt: message.roomExpiresAt,
});
+ writePreferredRoom(
+ activeRoom.roomId,
+ null,
+ );
setPhase("live");
}
handleSignalMessage(
@@ -1528,6 +1547,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const response = await createRoom(
creationProfileRef.current.codeEntryPolicy,
creationProfileRef.current.roomPassword,
+ readPreferredRoomId(),
);
const replacement = hostRoomFromCreated(response);
if (!isCurrentGeneration(generation)) {
diff --git a/src/server/app.ts b/src/server/app.ts
index cb902e96..eb8b8c24 100644
--- a/src/server/app.ts
+++ b/src/server/app.ts
@@ -446,6 +446,7 @@ async function handleRequest(
const room = await roomStore.createRoom(
parsedRequest.data.codeEntryPolicy,
parsedRequest.data.roomPassword ?? null,
+ parsedRequest.data.preferredRoomId,
);
const inviteUrl = new URL(`/r/${room.roomId}`, config.publicBaseUrl);
if (room.viewerGrant) {
@@ -457,6 +458,7 @@ async function handleRequest(
inviteUrl: inviteUrl.toString(),
codeEntryPolicy: room.codeEntryPolicy,
expiresAt: room.expiresAt,
+ roomLeaseSeconds: config.roomLeaseMs / 1_000,
};
sendJson(response, 201, responseBody);
} catch (error) {
diff --git a/src/server/room-store.ts b/src/server/room-store.ts
index a6e1adee..cd372dbc 100644
--- a/src/server/room-store.ts
+++ b/src/server/room-store.ts
@@ -192,6 +192,7 @@ export class RoomStore {
async createRoom(
codeEntryPolicy: CodeEntryPolicy = "open",
roomPassword?: string | null,
+ preferredRoomId?: string,
): Promise<CreatedRoom> {
if (this.rooms.size >= this.options.maxRooms) {
throw new RoomStoreError("ROOM_LIMIT");
@@ -203,7 +204,7 @@ export class RoomStore {
if (this.rooms.size >= this.options.maxRooms) {
throw new RoomStoreError("ROOM_LIMIT");
}
- const roomId = this.takeRoomCode();
+ const roomId = this.takeRoomCode(preferredRoomId);
try {
const hostTokenBytes = this.random(32);
if (hostTokenBytes.byteLength !== 32) {
@@ -638,10 +639,16 @@ export class RoomStore {
);
}
- private takeRoomCode(): string {
+ 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) {
@@ -654,16 +661,20 @@ export class RoomStore {
continue;
}
const index = Number(value % range);
- const roomId = this.freeRoomCodes[index]!;
- const lastRoomId = this.freeRoomCodes.pop()!;
- if (index < this.freeRoomCodes.length) {
- this.freeRoomCodes[index] = lastRoomId;
- }
- return roomId;
+ 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);
}
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index 23da06d1..abcfafd5 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -991,6 +991,7 @@ export const createRoomResponseSchema = z
inviteUrl: z.string().url().max(2048),
codeEntryPolicy: codeEntryPolicySchema,
expiresAt: z.string().datetime().nullable(),
+ roomLeaseSeconds: z.number().int().positive(),
})
.strict();
export type CreateRoomResponse = z.infer<typeof createRoomResponseSchema>;
@@ -999,6 +1000,7 @@ export const createRoomRequestSchema = z
.object({
codeEntryPolicy: codeEntryPolicySchema,
roomPassword: viewerPasswordSchema.nullable().optional(),
+ preferredRoomId: roomCodeSchema.optional(),
})
.strict();
diff --git a/tests/client-state.test.ts b/tests/client-state.test.ts
index 4787bd27..9b785b93 100644
--- a/tests/client-state.test.ts
+++ b/tests/client-state.test.ts
@@ -17,12 +17,14 @@ import {
parseAppRoute,
mergeAuthenticatedHostRoom,
readHostRoom,
+ readPreferredRoomId,
readViewerGrant,
readViewerRoute,
replaceViewerInvite,
roomRouteForExplicitEntry,
roomRouteFromInput,
writeHostRoom,
+ writePreferredRoom,
} from "../src/client/lib/session.ts";
import {
shouldReconnectSignaling,
@@ -272,6 +274,7 @@ describe("client session identity", () => {
inviteUrl: `https://share.test/r/1234#v=${"b".repeat(21)}A`,
codeEntryPolicy: "open" as const,
expiresAt: null,
+ roomLeaseSeconds: 3_600,
};
writeHostRoom(room);
@@ -281,12 +284,14 @@ describe("client session identity", () => {
hostToken: "a".repeat(32),
canonicalUrl: "https://share.test/r/1234",
expiresAt: null,
+ roomLeaseSeconds: 3_600,
});
expect(values.get("screener:host-room:v1")).toBe(
JSON.stringify({
roomId: "1234",
hostToken: "a".repeat(32),
expiresAt: null,
+ roomLeaseSeconds: 3_600,
inviteUrl: "https://share.test/r/1234",
}),
);
@@ -304,6 +309,7 @@ describe("client session identity", () => {
hostToken: "h".repeat(32),
inviteUrl: "https://share.test/r/1234",
expiresAt: null,
+ roomLeaseSeconds: 3_600,
}),
],
]);
@@ -320,6 +326,7 @@ describe("client session identity", () => {
hostToken: "h".repeat(32),
canonicalUrl: "https://share.test/r/1234",
expiresAt: null,
+ roomLeaseSeconds: 3_600,
});
});
@@ -338,6 +345,7 @@ describe("client session identity", () => {
hostToken: "b".repeat(32),
canonicalUrl: "https://share.test/r/1234",
expiresAt: "2026-08-18T00:00:00.000Z",
+ roomLeaseSeconds: 3_600,
};
writeHostRoom(expired);
@@ -435,6 +443,7 @@ describe("client session identity", () => {
hostToken: "h".repeat(32),
canonicalUrl: "https://share.test/r/1234",
expiresAt: null,
+ roomLeaseSeconds: 3_600,
codeEntryPolicy: "open" as const,
inviteUrl: oldInvite,
};
@@ -466,6 +475,27 @@ describe("client session identity", () => {
).toBeNull();
});
+ it("keeps a preferred room for the server-configured lease window", () => {
+ const values = new Map<string, string>();
+ vi.stubGlobal("window", {
+ localStorage: {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => values.set(key, value),
+ removeItem: (key: string) => values.delete(key),
+ },
+ });
+
+ writePreferredRoom("4321", null, 1_000);
+ expect(readPreferredRoomId(Number.MAX_SAFE_INTEGER)).toBe("4321");
+
+ writePreferredRoom("4321", 90, 1_000);
+
+ clearHostRoom();
+ expect(readPreferredRoomId(90_999)).toBe("4321");
+ expect(readPreferredRoomId(91_000)).toBeNull();
+ expect(values.has("screener:host-room-preference:v1")).toBe(false);
+ });
+
it("removes a legacy Viewer grant from room-scoped session storage", () => {
const values = new Map<string, string>([
["screener:viewer-grant:1234", `g1.1234.1.${"f".repeat(43)}`],
@@ -575,6 +605,24 @@ describe("site access API", () => {
);
});
+ it("sends only the preferred room code when one is current", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(
+ new Response(JSON.stringify({ error: "test response" }), {
+ status: 500,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(createRoom("open", null, "4321")).rejects.toBeInstanceOf(
+ ApiError,
+ );
+
+ expect(fetchMock.mock.calls[0][1]?.body).toBe(
+ JSON.stringify({ codeEntryPolicy: "open", preferredRoomId: "4321" }),
+ );
+ });
+
it("accepts an active room with a lease deadline", async () => {
const room = {
roomId: "1234",
@@ -582,6 +630,7 @@ describe("site access API", () => {
inviteUrl: `https://share.test/r/1234#v=${"f".repeat(21)}A`,
codeEntryPolicy: "open",
expiresAt: "2026-08-24T00:00:00.000Z",
+ roomLeaseSeconds: 86_400,
};
vi.stubGlobal(
"fetch",
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index c8b3f14e..34817161 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -217,6 +217,18 @@ describe("client signaling protocol", () => {
expect(
createRoomRequestSchema.parse({ codeEntryPolicy: "private" }),
).toEqual({ codeEntryPolicy: "private" });
+ expect(
+ createRoomRequestSchema.parse({
+ codeEntryPolicy: "open",
+ preferredRoomId: "4321",
+ }),
+ ).toEqual({ codeEntryPolicy: "open", preferredRoomId: "4321" });
+ expect(
+ createRoomRequestSchema.safeParse({
+ codeEntryPolicy: "open",
+ preferredRoomId: "0432",
+ }).success,
+ ).toBe(false);
for (const codeEntryPolicy of [
"password",
"private-link",
diff --git a/tests/room-store.test.ts b/tests/room-store.test.ts
index d404ce6e..f21bb55d 100644
--- a/tests/room-store.test.ts
+++ b/tests/room-store.test.ts
@@ -71,6 +71,20 @@ describe("RoomStore", () => {
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("rejects room limits beyond the four-digit code space", () => {
expect(() => store({ maxRooms: 9_001 }).store).toThrow(
"Room limit must be an integer between 1 and 9000",
diff --git a/tests/server-http.test.ts b/tests/server-http.test.ts
index 00cd6b4f..dacc01a4 100644
--- a/tests/server-http.test.ts
+++ b/tests/server-http.test.ts
@@ -82,6 +82,7 @@ async function createRoom(
cookie?: string,
codeEntryPolicy: "open" | "private" = "open",
roomPassword?: string,
+ preferredRoomId?: string,
): Promise<Response> {
return fetch(`${baseUrl}/api/rooms`, {
method: "POST",
@@ -93,6 +94,7 @@ async function createRoom(
body: JSON.stringify({
codeEntryPolicy,
...(roomPassword === undefined ? {} : { roomPassword }),
+ ...(preferredRoomId === undefined ? {} : { preferredRoomId }),
}),
});
}
@@ -294,6 +296,7 @@ describe("room HTTP API", () => {
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);
});
@@ -362,6 +365,24 @@ describe("room HTTP API", () => {
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("manages dormant room access without starting sharing or renewing", async () => {
let nowMs = 0;
const baseUrl = await start(