Files
Piik/internal/server/app/routes.go
T
AAA 89a03e6470 fix(app): improve capture selection and media recovery (#433)
## Problem and outcome / 问题与结果

This maintenance phase fixes failures around native capture startup, room reconnection and media handoffs. Capture mutations stay cancellable, relayed-content failures remain request-scoped, and failed media connections return to the existing route controller. Windows Auto codec selection measures delivered cadence instead of timer-sensitive per-frame work estimates.

The phase preserves P2P-first routing, one committed graph and one route operation. It adds no signaling replay mechanism, changes no wire/schema version, and includes no interaction prototype or 4K feature work.

## Release notes

### 中文

Piik v1.6.8 是一次稳定性修复,重点改善 Windows 原生采集、断线恢复和分享过程中的控制响应。

#### 修复与改善

- **更准确地选择编码器。** Windows 的自动模式按实际出帧表现评估 H.264,并正确区分启动预热和持续性能不足,减少计时误差导致的不必要 VP8 回退。硬件编码事件改为异步等待。
- **改善断线与线路切换。** 房间信令短暂断开后保留观众成员身份 20 秒;修复线路切换、SFU 订阅恢复及声音重协商卡住的问题。失效连接及时交回现有路由控制器处理,原生 SFU 发送端不再把短暂断连直接判为终止。
- **保持 App 控制响应。** 开始分享和更换来源时仍可取消操作;合法消息突发不再直接关闭控制连接。中继信令的单条内容错误不会连带结束整场原生分享。
- **修正设备列表与配置保存。** 来源或麦克风数量达到上限时保留可用列表;配置替换失败时保留原有设置。
- **改善紧凑布局和辅助功能。** 调整手机横屏下的画面与播控布局、画质预设标签和长邀请链接显示,修正部分提示与辅助功能语义。
- **加强站点访问保护。** 站点登录 Cookie 使用独立随机签名密钥,应用自身阻止被其他页面嵌套。发布说明也会在合并前检查。

#### 升级说明

通信协议和持久化格式保持不变。设置了站点密码时,App 或 Server 重启后需要重新输入站点密码;持久化房间和邀请授权不受这项 Cookie 调整影响。Piik 操作页面不再支持嵌入 iframe。

### English

Piik v1.6.8 is a stability update focused on Windows native capture, connection recovery and responsive sharing controls.

#### Fixes and improvements

- **More accurate codec selection.** Windows Auto mode evaluates H.264 using delivered frames and distinguishes startup warmup from sustained performance limits, reducing unnecessary VP8 fallback caused by timing noise. Hardware encoder events now use asynchronous waiting.
- **Improved reconnection and route handoffs.** Viewer membership survives brief signaling outages for 20 seconds. Fixes cover route activation, SFU subscription recovery and stalled audio renegotiation. Failed connections return to the existing route controller, and the native SFU publisher no longer treats a transient disconnect as immediate termination.
- **Responsive App controls.** Starting a share and replacing its source remain cancellable. Valid message bursts no longer close the control connection, and an invalid relayed payload cannot terminate the entire native sharing session.
- **Device lists and saved settings.** Source and microphone enumeration retain a usable list at their limits. Failed configuration replacement preserves the previous settings.
- **Compact layouts and accessibility.** Improved picture and playback-control layout on landscape phones, quality preset labels and long invitation links, with corrected tooltip and accessibility semantics.
- **Stronger site-access protection.** Login cookies use an independent random signing key, and the application prevents embedding by other pages. Release notes are also checked before merge.

#### Upgrade notes

Wire protocols and persistent formats are unchanged. If a site password is configured, restarting the App or Server requires entering it again; this cookie change does not revoke persisted rooms or invitation grants. Piik operation pages can no longer be embedded in an iframe.

## Verification / 验证

- `npm run check`: passed, 76 test files / 1,171 tests, TypeScript and production Web build.
- `npm run check:go-core`: passed; full Go/native checks also passed during integration of the capture changes. macOS cgo builds remain native-runner checks.
- Windows native Host gates: Auto, H.264 and VP8 passed during the phase; final control changes rechecked with Auto, including live/paused quality, source replacement, failure retirement and subsequent sharing.
- Embedded SFU browser VP8 recovery: passed with production Host/Viewer route owners.
- Embedded SFU native H.264, two rooms: passed, including recovered decoded video/audio, independent room retirement and resource cleanup.
- Documentation, repository hygiene and diff checks: passed. Final follow-up changes only align operations documentation with the PR note check.
- Go race checks could not run locally because no cgo/GCC toolchain is available; the existing Linux CI race job remains required. AMD/Intel hardware, broader device combinations, public-NAT field reports and long endurance are not established by these local checks.

## Impact / 影响

Compatible patch release after v1.6.7. The cookie and frame-protection effects are disclosed in the public upgrade notes. No automatic retry budget, room-code admission policy, room lifetime or media topology is replaced. Reports without matched diagnostics and unmeasured native performance costs remain in the TODO ledger.
2026-09-29 08:44:17 +08:00

465 lines
14 KiB
Go

package app
import (
"encoding/json"
"errors"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/TNTcraftHIM/Piik/internal/server/config"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/TNTcraftHIM/Piik/internal/server/room"
"github.com/TNTcraftHIM/Piik/internal/server/signal"
)
// The first matching route wins. The /api/ catch-all follows every concrete
// route so unknown API requests cannot fall through to the frontend.
var (
roomReplacementPath = regexp.MustCompile(`^/api/rooms/([1-9][0-9]{3})/replacement$`)
roomAccessPath = regexp.MustCompile(`^/api/rooms/([1-9][0-9]{3})/access$`)
)
// ServeHTTP dispatches requests and contains handler panics at the HTTP boundary.
func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Security-Policy", "frame-ancestors 'none'")
writer.Header().Set("X-Frame-Options", "DENY")
recorder := &responseRecorder{ResponseWriter: writer}
defer func() {
recovered := recover()
if recovered == nil {
return
}
if recovered == http.ErrAbortHandler {
panic(recovered)
}
// Persist only fixed request categories, never the panic or raw URL.
s.requestFailed(recorder, request)
}()
if !s.acceptingTraffic.Load() {
// No traffic is accepted until startup completes; /healthz also returns 503.
recorder.Header().Set("Cache-Control", "no-store")
recorder.Header().Set("Retry-After", "1")
sendJSON(recorder, http.StatusServiceUnavailable, errorBody{"Service starting"})
return
}
signaling := s.signaling.Load()
if isUpgradeRequest(request) {
// Node routed every upgrade to the SignalingServer's "upgrade"
// listener, which was attached only while traffic was accepted.
signaling.ServeHTTP(recorder, request)
return
}
s.route(recorder, request, signaling)
}
func (s *Server) route(
writer http.ResponseWriter,
request *http.Request,
signaling *signal.Server,
) {
path := requestPath(request)
if path == "/healthz" {
writer.Header().Set("Cache-Control", "no-store")
if !allowMethod(writer, request, http.MethodGet) {
return
}
sendJSON(writer, http.StatusOK, healthBody{"ok"})
return
}
if path == "/api/capabilities" {
noStoreJSON(writer)
if !allowMethod(writer, request, http.MethodGet) {
return
}
sendJSON(writer, http.StatusOK, protocol.RuntimeCapabilities{
ConnectionAttemptProgress4: true,
Sfu: s.config.SFU != nil,
NatPrediction: s.config.NATPredictionEnabled,
})
return
}
if path == "/api/site-access" {
s.handleSiteAccess(writer, request)
return
}
if match := roomReplacementPath.FindStringSubmatch(path); match != nil {
s.handleRoomReplacement(writer, request, signaling, match[1])
return
}
if match := roomAccessPath.FindStringSubmatch(path); match != nil {
s.handleRoomAccess(writer, request, signaling, match[1])
return
}
if path == "/api/rooms" {
s.handleRoomCreation(writer, request, signaling)
return
}
if strings.HasPrefix(path, "/api/") {
// The catch-all sets no nosniff header; only the concrete routes do.
writer.Header().Set("Cache-Control", "no-store")
sendJSON(writer, http.StatusNotFound, errorBody{"Not found"})
return
}
if s.frontend != nil {
s.frontend.ServeHTTP(writer, request)
return
}
notFoundJSON(writer, request)
}
// notFoundJSON is the fallthrough app.ts handed to sirv as its next()
// callback and used when no frontend is composed at all.
func notFoundJSON(writer http.ResponseWriter, _ *http.Request) {
sendJSON(writer, http.StatusNotFound, errorBody{"Not found"})
}
// noStoreJSON sets the two headers every /api route sets before its method
// check, so a 405 carries them too.
func noStoreJSON(writer http.ResponseWriter) {
writer.Header().Set("Cache-Control", "no-store")
writer.Header().Set("X-Content-Type-Options", "nosniff")
}
// allowMethod answers the 405 row of the HTTP table, Allow header included.
func allowMethod(writer http.ResponseWriter, request *http.Request, allowed string) bool {
if request.Method == allowed {
return true
}
writer.Header().Set("Allow", allowed)
sendJSON(writer, http.StatusMethodNotAllowed, errorBody{"Method not allowed"})
return false
}
// handleSiteAccess is handleSiteAccessRequest of app.ts.
func (s *Server) handleSiteAccess(writer http.ResponseWriter, request *http.Request) {
noStoreJSON(writer)
access := s.siteAccessForRequest(request)
if request.Method == http.MethodGet {
status := siteAccessBody{
Required: access.required(),
Authenticated: access.isAuthenticated(cookieHeader(request)),
}
if status.Required && status.Authenticated {
// The Set-Cookie value is written verbatim, in the TS attribute
// order.
writer.Header().Set("Set-Cookie", access.createCookie())
}
sendJSON(writer, http.StatusOK, status)
return
}
if request.Method != http.MethodPost {
writer.Header().Set("Allow", "GET, POST")
sendJSON(writer, http.StatusMethodNotAllowed, errorBody{"Method not allowed"})
return
}
if !s.allowedRequestOrigin(request) {
sendJSON(writer, http.StatusForbidden, errorBody{"Origin not allowed"})
return
}
// Released clients send a bodyless Bearer request. JSON preserves passwords
// that cannot be represented in an HTTP header and takes precedence when sent.
provided := bearerToken(request)
if hasRequestBody(request) {
body, err := readJSONBody(request)
var fields map[string]json.RawMessage
var password *string
if err != nil || json.Unmarshal(body, &fields) != nil || len(fields) != 1 ||
json.Unmarshal(fields["password"], &password) != nil || password == nil {
sendJSON(writer, http.StatusBadRequest, errorBody{"Invalid site access request"})
return
}
provided = *password
}
if !access.required() {
sendJSON(writer, http.StatusOK, siteAccessBody{Required: false, Authenticated: true})
return
}
if !access.passwordMatches(provided) {
writer.Header().Set("WWW-Authenticate", "Bearer")
sendJSON(writer, http.StatusUnauthorized, errorBody{"Unauthorized"})
return
}
writer.Header().Set("Set-Cookie", access.createCookie())
sendJSON(writer, http.StatusOK, siteAccessBody{Required: true, Authenticated: true})
}
func (s *Server) handleRoomReplacement(
writer http.ResponseWriter,
request *http.Request,
signaling *signal.Server,
roomID string,
) {
noStoreJSON(writer)
if !allowMethod(writer, request, http.MethodPost) {
return
}
hostToken, authorized := s.authorizedRoomHostToken(writer, request)
if !authorized {
return
}
body, err := readJSONBody(request)
var parsed protocol.ReplaceRoomRequest
if err == nil {
parsed, err = protocol.DecodeReplaceRoomRequest(body)
}
if err != nil {
sendJSON(writer, http.StatusBadRequest, errorBody{"Invalid room replacement request"})
return
}
if signaling == nil {
sendJSON(writer, http.StatusServiceUnavailable, errorBody{"Service unavailable"})
return
}
created, err := signaling.ReplaceRoom(
roomID,
hostToken,
parsed.CodeEntryPolicy,
parsed.RoomPassword.Value,
)
if err != nil {
if status, message, mapped := replacementFailure(err); mapped {
sendJSON(writer, status, errorBody{message})
return
}
s.requestFailed(writer, request)
return
}
sendJSON(writer, http.StatusCreated, s.createRoomResponse(created))
}
func (s *Server) handleRoomAccess(
writer http.ResponseWriter,
request *http.Request,
signaling *signal.Server,
roomID string,
) {
noStoreJSON(writer)
if !allowMethod(writer, request, http.MethodPost) {
return
}
hostToken, authorized := s.authorizedRoomHostToken(writer, request)
if !authorized {
return
}
body, err := readJSONBody(request)
var parsed protocol.RoomAccessUpdateRequest
if err == nil {
parsed, err = protocol.DecodeRoomAccessUpdateRequest(body)
}
if err != nil {
sendJSON(writer, http.StatusBadRequest, errorBody{"Invalid room access request"})
return
}
if signaling == nil {
sendJSON(writer, http.StatusServiceUnavailable, errorBody{"Service unavailable"})
return
}
updated, err := signaling.UpdateRoomAccess(roomID, hostToken, parsed)
if err != nil {
if status, message, mapped := accessFailure(err); mapped {
sendJSON(writer, status, errorBody{message})
return
}
s.requestFailed(writer, request)
return
}
sendJSON(writer, http.StatusOK, updated)
}
func (s *Server) handleRoomCreation(
writer http.ResponseWriter,
request *http.Request,
signaling *signal.Server,
) {
noStoreJSON(writer)
if !allowMethod(writer, request, http.MethodPost) {
return
}
if !s.allowedRequestOrigin(request) {
sendJSON(writer, http.StatusForbidden, errorBody{"Origin not allowed"})
return
}
// When site access requires a password, room creation uses its cookie;
// a `Bearer <site password>` header does not authorize it.
if !s.roomCreationAuthorized(request) {
sendJSON(writer, http.StatusUnauthorized, errorBody{"Unauthorized"})
return
}
body, err := readJSONBody(request)
var parsed protocol.CreateRoomRequest
if err == nil {
parsed, err = protocol.DecodeCreateRoomRequest(body)
}
if err != nil {
sendJSON(writer, http.StatusBadRequest, errorBody{"Invalid room request"})
return
}
// TS called roomStore.createRoom directly; the store is now guarded by the
// signaling server's global mutex, so creation goes through it. There is
// no `signaling == nil` answer here, because app.ts had no getSignaling()
// check on this route: reconcile stores the signaling server before it
// sets acceptingTraffic and never clears it again, so reaching a handler
// at all means the pointer is set (the two sibling room routes keep their
// 503 only because the TypeScript had one).
created, err := signaling.CreateRoom(
parsed.CodeEntryPolicy,
parsed.RoomPassword.Value,
parsed.PreferredRoomID,
)
if err != nil {
if status, message, mapped := creationFailure(err); mapped {
sendJSON(writer, status, errorBody{message})
return
}
s.requestFailed(writer, request)
return
}
sendJSON(writer, http.StatusCreated, s.createRoomResponse(created))
}
// authorizedRoomHostToken of app.ts: origin, then site access, then the bearer
// Host token, each with its own terminal response.
func (s *Server) authorizedRoomHostToken(
writer http.ResponseWriter,
request *http.Request,
) (string, bool) {
if !s.allowedRequestOrigin(request) {
sendJSON(writer, http.StatusForbidden, errorBody{"Origin not allowed"})
return "", false
}
if !s.roomCreationAuthorized(request) {
sendJSON(writer, http.StatusUnauthorized, errorBody{"Unauthorized"})
return "", false
}
hostToken := bearerToken(request)
if hostToken == "" {
// An absent Host token is indistinguishable from a wrong one.
sendJSON(writer, http.StatusNotFound, errorBody{"Room not found"})
return "", false
}
return hostToken, true
}
// allowedRequestOrigin requires a present, parseable header equal to its own
// serialised origin (so "http://allowed.test/path" is refused) and configured.
func (s *Server) allowedRequestOrigin(request *http.Request) bool {
origin := request.Header.Get("Origin")
if origin == "" {
return false
}
parsed, err := url.Parse(origin)
if err != nil || config.Origin(parsed) != origin {
return false
}
_, allowed := s.config.AllowedOrigins[origin]
return allowed
}
func (s *Server) roomCreationAuthorized(request *http.Request) bool {
return s.siteAccessForRequest(request).isAuthenticated(cookieHeader(request))
}
// signal.InviteURL is the one owner of the invite
// URL shape; the rotated-grant notification on the signaling side uses it too.
func (s *Server) createRoomResponse(created room.CreatedRoom) protocol.CreateRoomResponse {
return protocol.CreateRoomResponse{
RoomID: created.RoomID,
HostToken: created.HostToken,
InviteURL: signal.InviteURL(s.config.PublicBaseURL, created.RoomID, created.ViewerGrant),
CodeEntryPolicy: created.CodeEntryPolicy,
}
}
// requestFailed logs fixed request categories, then answers 500 or aborts a
// response that already started. Request paths and arbitrary methods are private.
func (s *Server) requestFailed(writer http.ResponseWriter, request *http.Request) {
method := request.Method
switch method {
case http.MethodGet, http.MethodPost, http.MethodHead, http.MethodOptions,
http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodConnect, http.MethodTrace:
default:
method = "other"
}
path := requestPath(request)
category := "frontend"
switch {
case isUpgradeRequest(request):
category = "signaling"
case path == "/healthz":
category = "health"
case strings.HasPrefix(path, "/api/"):
category = "api"
}
s.logger.Error("HTTP request failed", "method", method, "route", category)
if recorder, ok := writer.(*responseRecorder); ok && recorder.wrote {
panic(http.ErrAbortHandler)
}
sendJSON(writer, http.StatusInternalServerError, errorBody{"Internal server error"})
}
// roomErrorCode returns the RoomStoreError code, or "" when err is not one.
func roomErrorCode(err error) room.ErrorCode {
var roomError *room.Error
if errors.As(err, &roomError) {
return roomError.Code
}
return ""
}
// replacementFailure maps replaceRoom errors; an unmapped error rethrows into
// the 500 handler, as the TS `throw error` did.
func replacementFailure(err error) (int, string, bool) {
switch roomErrorCode(err) {
case room.CodeRoomLimit:
return http.StatusServiceUnavailable, "Room capacity reached", true
case room.CodeRoomAccessDenied, room.CodeRoomBusy:
return http.StatusServiceUnavailable, "Room replacement unavailable", true
case room.CodeInvalidToken, room.CodeRoomNotFound:
return http.StatusNotFound, "Room not found", true
}
return 0, "", false
}
// accessFailure maps updateRoomAccess errors. Unlike the other two tables,
// every remaining RoomStoreError is a 404; only a non-store error rethrows.
func accessFailure(err error) (int, string, bool) {
switch code := roomErrorCode(err); code {
case "":
return 0, "", false
case room.CodeRoomBusy:
return http.StatusServiceUnavailable, "Room access update unavailable", true
case room.CodeRoomAccessDenied:
return http.StatusConflict, "Room access update rejected", true
default:
return http.StatusNotFound, "Room not found", true
}
}
// creationFailure maps createRoom errors.
func creationFailure(err error) (int, string, bool) {
switch roomErrorCode(err) {
case room.CodeRoomLimit:
return http.StatusServiceUnavailable, "Room capacity reached", true
case room.CodeRoomBusy:
return http.StatusServiceUnavailable, "Room creation unavailable", true
case room.CodeInvalidToken:
return http.StatusBadRequest, "Invalid room request", true
}
return 0, "", false
}