Files
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

295 lines
9.9 KiB
Go

package app
import (
"strings"
"testing"
)
const testAccessPassword = "instance-access-password"
// newTestAccess builds a siteAccessGate over a mutable clock, mirroring the
// `now: () => now` injection used by tests/server-http.test.ts.
func newTestAccess(t *testing.T, options siteAccessOptions) *siteAccessGate {
t.Helper()
access, err := newSiteAccess(options)
if err != nil {
t.Fatalf("newSiteAccess: %v", err)
}
return access
}
// cookiePair is the test helper of the same name: the `name=value` pair of a
// Set-Cookie header, which is what a browser sends back.
func cookiePair(t *testing.T, setCookie string) string {
t.Helper()
if setCookie == "" {
t.Fatal("expected a Set-Cookie value")
}
return strings.SplitN(setCookie, ";", 2)[0]
}
// Ports "reports status and issues a stateless 24-hour cookie".
func TestSiteAccessIssuesStatelessDayLongCookie(t *testing.T) {
now := int64(1_000)
access := newTestAccess(t, siteAccessOptions{
Password: testAccessPassword,
Now: func() int64 { return now },
})
if !access.required() {
t.Fatal("a configured password must make site access required")
}
if access.isAuthenticated("") {
t.Fatal("a request without a cookie must not be authenticated")
}
if access.passwordMatches("wrong-password") {
t.Fatal("a wrong password must be rejected")
}
if !access.passwordMatches(testAccessPassword) {
t.Fatal("the configured password must be accepted")
}
setCookie := access.createCookie()
if want := "piik-site-access=v1."; !strings.Contains(setCookie, want) {
t.Fatalf("Set-Cookie %q does not contain %q", setCookie, want)
}
for _, attribute := range []string{"Path=/", "Max-Age=86400", "HttpOnly", "SameSite=Strict"} {
if !strings.Contains(setCookie, attribute) {
t.Fatalf("Set-Cookie %q is missing %q", setCookie, attribute)
}
}
if strings.Contains(setCookie, "Secure") {
t.Fatalf("Set-Cookie %q must not be Secure without HTTPS", setCookie)
}
if strings.Contains(setCookie, testAccessPassword) {
t.Fatal("Set-Cookie must never carry the access password")
}
if !access.isAuthenticated(cookiePair(t, setCookie)) {
t.Fatal("the freshly issued cookie must authenticate")
}
}
// Ports the exact attribute order of createCookie, which app.ts writes verbatim
// into the Set-Cookie header.
func TestSiteAccessCookieAttributeOrder(t *testing.T) {
insecure := newTestAccess(t, siteAccessOptions{
Password: testAccessPassword,
Now: func() int64 { return 1_000 },
TTLSeconds: 12,
})
secure := *insecure
secure.secure = true
signature := strings.Split(cookiePair(t, insecure.createCookie()), ".")[2]
if len(signature) != 43 {
t.Fatalf("signature %q is %d characters, want 43 (base64url, no padding)", signature, len(signature))
}
// now = 1000 ms -> floor(1) + 12 = 13 seconds.
wantValue := "v1.13." + signature
want := "piik-site-access=" + wantValue +
"; Path=/; Max-Age=12; HttpOnly; SameSite=Strict"
if got := insecure.createCookie(); got != want {
t.Fatalf("CreateCookie() = %q, want %q", got, want)
}
wantSecure := "__Host-piik-site-access=" + wantValue +
"; Path=/; Max-Age=12; HttpOnly; SameSite=Strict; Secure"
if got := secure.createCookie(); got != wantSecure {
t.Fatalf("secure CreateCookie() = %q, want %q", got, wantSecure)
}
}
func TestSiteCookieUsesAnIndependentProcessKey(t *testing.T) {
first := newTestAccess(t, siteAccessOptions{Password: "1"})
second := newTestAccess(t, siteAccessOptions{Password: "1"})
cookie := cookiePair(t, first.createCookie())
if !first.isAuthenticated(cookie) || second.isAuthenticated(cookie) {
t.Fatal("site cookies must authenticate only their issuing process")
}
// LAN/HTTPS adapters copy the same gate; they do not allocate another key.
copy := *first
if !copy.isAuthenticated(cookie) {
t.Fatal("a request adapter lost the process key")
}
}
// Ports "uses a secure __Host- cookie for production HTTPS".
func TestSiteAccessUsesHostPrefixedCookieWhenSecure(t *testing.T) {
access := newTestAccess(t, siteAccessOptions{
Password: testAccessPassword,
Secure: true,
Now: func() int64 { return 1_000 },
})
setCookie := access.createCookie()
for _, attribute := range []string{
"__Host-piik-site-access=", "Secure", "HttpOnly", "SameSite=Strict", "Path=/",
} {
if !strings.Contains(setCookie, attribute) {
t.Fatalf("Set-Cookie %q is missing %q", setCookie, attribute)
}
}
if strings.Contains(setCookie, "Domain=") {
t.Fatalf("Set-Cookie %q must not carry a Domain for a __Host- cookie", setCookie)
}
if !access.isAuthenticated(cookiePair(t, setCookie)) {
t.Fatal("the secure cookie must authenticate under its own name")
}
// The cookie name is part of the signed identity only through the lookup;
// an insecure instance never finds a __Host- cookie.
insecure := newTestAccess(t, siteAccessOptions{
Password: testAccessPassword,
Now: func() int64 { return 1_000 },
})
if insecure.isAuthenticated(cookiePair(t, setCookie)) {
t.Fatal("the insecure instance must not read the __Host- cookie")
}
}
// Ports "renews an authenticated cookie across successive idle deadlines".
func TestSiteAccessRenewsAcrossSuccessiveIdleDeadlines(t *testing.T) {
now := int64(1_000)
access := newTestAccess(t, siteAccessOptions{
Password: testAccessPassword,
Now: func() int64 { return now },
TTLSeconds: 12,
})
originalCookie := cookiePair(t, access.createCookie())
now = 7_000
if !access.isAuthenticated(originalCookie) {
t.Fatal("the original cookie must still be valid at 7s")
}
firstRenewedCookie := cookiePair(t, access.createCookie())
if firstRenewedCookie == originalCookie {
t.Fatal("a renewal at a later second must produce a different cookie")
}
now = 13_000
if access.isAuthenticated(originalCookie) {
t.Fatal("the original cookie must expire 12s after it was issued")
}
if !access.isAuthenticated(firstRenewedCookie) {
t.Fatal("the first renewal must still be valid at 13s")
}
secondRenewedCookie := cookiePair(t, access.createCookie())
if secondRenewedCookie == firstRenewedCookie {
t.Fatal("the second renewal must differ from the first")
}
now = 20_000
if access.isAuthenticated(firstRenewedCookie) {
t.Fatal("the first renewal must expire 12s after it was issued")
}
if !access.isAuthenticated(secondRenewedCookie) {
t.Fatal("the second renewal must still be valid at 20s")
}
}
// Ports "rejects an expired or modified cookie" plus the parsing rules the HTTP
// scenarios only reach indirectly.
func TestSiteAccessRejectsExpiredOrTamperedCookies(t *testing.T) {
now := int64(1_000)
access := newTestAccess(t, siteAccessOptions{
Password: testAccessPassword,
Now: func() int64 { return now },
TTLSeconds: 1,
})
cookie := cookiePair(t, access.createCookie())
value := strings.SplitN(cookie, "=", 2)[1]
segments := strings.Split(value, ".")
if access.isAuthenticated(cookie + "x") {
t.Fatal("an appended character must invalidate the signature")
}
other := newTestAccess(t, siteAccessOptions{
Password: "another-access-password",
Now: func() int64 { return now },
TTLSeconds: 1,
})
if other.isAuthenticated(cookie) {
t.Fatal("a cookie signed with a different password must be rejected")
}
// Expiry is compared against floor(now / 1000): 2000 ms is second 2 and the
// cookie expires at second 2, so `expiresAt <= now` rejects it.
now = 2_000
if access.isAuthenticated(cookie) {
t.Fatal("an expired cookie must be rejected")
}
now = 1_000
name := strings.SplitN(cookie, "=", 2)[0]
for _, testCase := range []struct {
name string
cookie string
}{
{"no cookie header", ""},
{"different cookie name", "other=" + value},
{"empty value", name + "="},
{"no equals sign", name},
{"wrong version", name + "=v2." + segments[1] + "." + segments[2]},
{"missing version", name + "=" + segments[1] + "." + segments[2]},
{"extra segment", name + "=" + value + ".extra"},
{"non-digit expiry", name + "=v1.1e3." + segments[2]},
{"signed expiry", name + "=v1.+42." + segments[2]},
{"empty expiry", name + "=v1.." + segments[2]},
{"short signature", name + "=v1." + segments[1] + "." + segments[2][:42]},
{"long signature", name + "=v1." + segments[1] + "." + segments[2] + "A"},
{"padded signature", name + "=v1." + segments[1] + "." + segments[2][:42] + "="},
{"unsafe expiry", name + "=v1.9007199254740992." + segments[2]},
} {
if access.isAuthenticated(testCase.cookie) {
t.Errorf("%s: %q must not authenticate", testCase.name, testCase.cookie)
}
}
// Surrounding cookies and whitespace are tolerated, as the TS reader is.
for _, header := range []string{
"a=1; " + cookie + "; b=2",
"a=1;" + cookie,
" " + name + " = " + value + " ",
} {
if !access.isAuthenticated(header) {
t.Errorf("Cookie header %q must authenticate", header)
}
}
}
// Ports "is immediately authenticated when the access password is empty".
func TestSiteAccessWithoutPassword(t *testing.T) {
access := newTestAccess(t, siteAccessOptions{Now: func() int64 { return 1_000 }})
if access.required() {
t.Fatal("an empty password must not require site access")
}
if !access.isAuthenticated("") {
t.Fatal("every request must be authenticated without a password")
}
if !access.isAuthenticated("piik-site-access=nonsense") {
t.Fatal("a bogus cookie must not matter without a password")
}
if !access.passwordMatches("") || !access.passwordMatches("anything") {
t.Fatal("passwordMatches must be true without a password")
}
if got := access.createCookie(); got != "" {
t.Fatalf("CreateCookie() = %q, want \"\" (TS returned undefined)", got)
}
}
func TestNewSiteAccessTTLValidation(t *testing.T) {
if _, err := newSiteAccess(siteAccessOptions{Password: testAccessPassword, TTLSeconds: -1}); err == nil {
t.Fatal("a negative TTL must be rejected")
}
access := newTestAccess(t, siteAccessOptions{
Password: testAccessPassword,
Now: func() int64 { return 0 },
})
if !strings.Contains(access.createCookie(), "Max-Age=86400") {
t.Fatal("an unset TTL must default to 24 hours")
}
}