Files
piik/internal/app/app_test.go
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

953 lines
32 KiB
Go

package app
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"github.com/TNTcraftHIM/Piik/internal/app/buildinfo"
appconfig "github.com/TNTcraftHIM/Piik/internal/app/config"
"github.com/TNTcraftHIM/Piik/internal/app/lan"
"github.com/TNTcraftHIM/Piik/internal/app/launcher"
"github.com/TNTcraftHIM/Piik/internal/app/loopback"
serverconfig "github.com/TNTcraftHIM/Piik/internal/server/config"
)
func TestMain(tests *testing.M) {
if mode := os.Getenv("PIIK_APP_TUNNEL_FIXTURE"); mode != "" {
if err := os.WriteFile(os.Getenv("PIIK_APP_TUNNEL_STARTED"), nil, 0600); err != nil {
os.Exit(1)
}
if mode == "failed" {
os.Exit(7)
}
if mode == "ready" || mode == "ready-failed" {
fmt.Println(`{"message":"https://test-room.trycloudflare.com"}`)
fmt.Println(`{"message":"Registered tunnel connection"}`)
}
if mode == "ready-failed" {
for {
if _, err := os.Stat(os.Getenv("PIIK_APP_TUNNEL_EXIT")); err == nil {
os.Exit(7)
}
time.Sleep(time.Millisecond)
}
}
time.Sleep(10 * time.Second)
os.Exit(0)
}
os.Exit(tests.Run())
}
func TestPublicLinkStartupDistinguishesCancellationFromFailure(t *testing.T) {
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
t.Setenv("PIIK_DEBUG", "")
for _, mode := range []string{"starting", "ready", "failed", "ready-failed"} {
t.Run(mode, func(t *testing.T) {
directory := t.TempDir()
marker := filepath.Join(directory, "tunnel-started")
exit := filepath.Join(directory, "tunnel-exit")
t.Setenv("PIIK_APP_TUNNEL_FIXTURE", mode)
t.Setenv("PIIK_APP_TUNNEL_STARTED", marker)
t.Setenv("PIIK_APP_TUNNEL_EXIT", exit)
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := listener.Addr().(*net.TCPAddr).Port
if err = listener.Close(); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
ready := false
done := make(chan error, 1)
joined := false
defer func() {
cancel()
if !joined {
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("App tunnel fixture did not retire")
}
}
}()
go func() {
done <- Run(ctx, Options{
Link: true, DisableBrowser: true, Debug: true, LogDir: filepath.Join(directory, "logs"),
ConfigPath: filepath.Join(directory, "client.json"), Port: port,
CaptureProcess: filepath.Join(directory, "missing-capture"), TunnelProcess: executable,
Ready: func(string) {
ready = true
if mode == "ready-failed" {
if err := os.WriteFile(exit, nil, 0600); err != nil {
t.Error(err)
cancel()
}
} else {
cancel()
}
},
})
}()
if mode == "starting" {
deadline := time.Now().Add(3 * time.Second)
for {
if _, err = os.Stat(marker); err == nil {
break
}
if time.Now().After(deadline) {
t.Fatal("public link startup did not reach its tunnel")
}
time.Sleep(10 * time.Millisecond)
}
cancel()
}
waitForResult := 5 * time.Second
if mode == "failed" {
// Startup includes three retry pauses and four real child launches;
// this is not the cancellation/ready-tunnel retirement deadline.
waitForResult = 15 * time.Second
}
select {
case err = <-done:
joined = true
if mode == "failed" {
if err == nil || !strings.Contains(err.Error(), "service exited before connecting") {
t.Fatalf("startup failure was lost: %v", err)
}
} else if mode == "ready-failed" {
if err == nil || !strings.Contains(err.Error(), "public invitation link stopped") ||
strings.Count(err.Error(), "exit status 7") != 1 {
t.Fatalf("ready tunnel failure must be retained once: %v", err)
}
} else if err != nil {
t.Fatalf("intentional %s stop became an App failure: %v", mode, err)
}
if ready != (mode == "ready" || mode == "ready-failed") {
t.Fatalf("startup readiness = %v for %s", ready, mode)
}
case <-time.After(waitForResult):
t.Fatal("App did not retire its local authority and tunnel")
}
content, err := os.ReadFile(filepath.Join(directory, "logs", "client.log"))
if err != nil || !strings.Contains(string(content), fmt.Sprintf(`"event":"stopped","failed":%v`, mode == "failed" || mode == "ready-failed")) {
t.Fatalf("diagnostics misclassified the App outcome: %s, %v", content, err)
}
})
}
}
type launcherRuntimeLog struct {
started chan struct{}
release <-chan struct{}
}
func (writer launcherRuntimeLog) Write(data []byte) (int, error) {
if bytes.Contains(data, []byte(`"event":"mode"`)) {
close(writer.started)
<-writer.release
}
return len(data), nil
}
func TestLauncherRetainsItsRuntimeFailureDuringCancellation(t *testing.T) {
for _, cancelBeforeFailure := range []bool{true, false} {
t.Run(fmt.Sprintf("cancel=%v", cancelBeforeFailure), func(t *testing.T) {
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4zero})
if err != nil {
t.Fatal(err)
}
defer listener.Close()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
control, err := loopback.Start(ctx, loopback.Options{})
if err != nil {
t.Fatal(err)
}
defer control.Close()
configPath := filepath.Join(t.TempDir(), "client.json")
config, err := appconfig.LoadOrCreate(configPath)
if err != nil {
t.Fatal(err)
}
started, release := make(chan struct{}), make(chan struct{})
resume := sync.OnceFunc(func() { close(release) })
previous := slog.Default()
slog.SetDefault(slog.New(slog.NewJSONHandler(launcherRuntimeLog{started, release},
&slog.HandlerOptions{Level: slog.LevelDebug})))
defer slog.SetDefault(previous)
defer resume()
opened := make(chan string, 1)
console := newConsole(cancel, true)
console.openURL = func(target string) error { opened <- target; return nil }
done := make(chan error, 1)
joined := false
go func() {
done <- runLauncher(ctx, Options{Port: listener.Addr().(*net.TCPAddr).Port, console: console},
configPath, config, control, func(*Options, appconfig.Config) error { return nil })
}()
defer func() {
cancel()
resume()
if !joined {
select {
case <-done:
case <-time.After(3 * time.Second):
t.Error("launcher runtime did not retire")
}
}
}()
var target string
select {
case target = <-opened:
case <-time.After(2 * time.Second):
t.Fatal("launcher did not open")
}
requestDone := make(chan struct{})
go func() {
defer close(requestDone)
client := &http.Client{Timeout: 3 * time.Second}
response, err := postLocalLauncher(client, strings.TrimSuffix(target, "/client")+"/api/client-launcher/launch",
"application/json", strings.NewReader(`{"mode":"link","language":"en"}`))
if err != nil {
if !cancelBeforeFailure {
t.Error(err)
}
return
}
defer response.Body.Close()
if !cancelBeforeFailure && response.StatusCode != http.StatusServiceUnavailable {
t.Errorf("launcher did not report the runtime failure: %d", response.StatusCode)
}
}()
select {
case <-started:
case <-time.After(2 * time.Second):
t.Fatal("launcher selection did not start its runtime")
}
if cancelBeforeFailure {
cancel()
select {
case <-requestDone:
case <-time.After(2 * time.Second):
t.Fatal("launcher did not retire its pending selection")
}
// Hold the real port failure while the launcher handles cancellation.
select {
case err := <-done:
joined = true
t.Fatalf("launcher returned before its runtime: %v", err)
case <-time.After(25 * time.Millisecond):
}
}
resume()
if !cancelBeforeFailure {
select {
case <-requestDone:
case <-time.After(2 * time.Second):
t.Fatal("launcher did not report its failed room")
}
response, err := http.Get(strings.TrimSuffix(target, "/client") + "/api/client-launcher")
if err != nil {
t.Fatalf("room failure retired the App approval UI: %v", err)
}
var state struct {
Target, Detail string
Starting bool
}
err = json.NewDecoder(response.Body).Decode(&state)
response.Body.Close()
if err != nil || state.Target != "" || state.Starting || !strings.Contains(state.Detail, "local server port is unavailable") {
t.Fatalf("failed room was not reflected in the live launcher: %+v, %v", state, err)
}
select {
case err := <-done:
joined = true
t.Fatalf("room failure retired the resident App: %v", err)
default:
}
cancel()
}
select {
case err := <-done:
joined = true
var bindError *net.OpError
if !errors.As(err, &bindError) || bindError.Op != "listen" ||
strings.Count(err.Error(), "local server port is unavailable") != 1 {
t.Fatalf("launcher must retain its runtime failure once: %v", err)
}
case <-time.After(3 * time.Second):
t.Fatal("launcher did not join its failed runtime")
}
select {
case <-requestDone:
case <-time.After(2 * time.Second):
t.Fatal("launcher selection did not finish")
}
})
}
}
func TestLauncherRetriesARetiredFailureWithoutReplacingAReadyRoom(t *testing.T) {
t.Setenv("PIIK_APP_TUNNEL_FIXTURE", "ready")
t.Setenv("PIIK_APP_TUNNEL_STARTED", filepath.Join(t.TempDir(), "started"))
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
occupied, err := net.Listen("tcp4", "0.0.0.0:0")
if err != nil {
t.Fatal(err)
}
defer occupied.Close()
port := occupied.Addr().(*net.TCPAddr).Port
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
control, err := loopback.Start(ctx, loopback.Options{})
if err != nil {
t.Fatal(err)
}
defer control.Close()
configPath := filepath.Join(t.TempDir(), "client.json")
config, err := appconfig.LoadOrCreate(configPath)
if err != nil {
t.Fatal(err)
}
config.SetApprovedSites([]string{"https://site.example"})
opened := make(chan string, 1)
console := newConsole(cancel, true)
console.openURL = func(target string) error { opened <- target; return nil }
done := make(chan error, 1)
go func() {
done <- runLauncher(ctx, Options{Port: port, console: console, TunnelProcess: executable},
configPath, config, control, func(*Options, appconfig.Config) error { return nil })
}()
t.Cleanup(func() {
cancel()
select {
case err := <-done:
if err != nil {
t.Errorf("retried room exit retained an obsolete failure: %v", err)
}
case <-time.After(5 * time.Second):
t.Error("retried launcher did not retire")
}
})
var target string
select {
case target = <-opened:
case <-time.After(2 * time.Second):
t.Fatal("launcher did not open")
}
client := &http.Client{Timeout: 5 * time.Second}
endpoint := strings.TrimSuffix(target, "/client") + "/api/client-launcher/launch"
post := func() *http.Response {
t.Helper()
response, err := postLocalLauncher(client, endpoint, "application/json", strings.NewReader(`{"mode":"link","language":"en"}`))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { response.Body.Close() })
return response
}
if response := post(); response.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("occupied port startup = %d", response.StatusCode)
}
if err := occupied.Close(); err != nil {
t.Fatal(err)
}
response := post()
var ready struct{ Target string }
if err := json.NewDecoder(response.Body).Decode(&ready); err != nil || response.StatusCode != http.StatusOK || ready.Target == "" {
t.Fatalf("retry did not become ready: %d %+v %v", response.StatusCode, ready, err)
}
response = post()
var reopened struct{ Target string }
if err := json.NewDecoder(response.Body).Decode(&reopened); err != nil || response.StatusCode != http.StatusOK || reopened.Target != ready.Target {
t.Fatalf("reentry replaced the ready room: %d %+v %v", response.StatusCode, reopened, err)
}
response, err = client.Get(fmt.Sprintf("http://127.0.0.1:%d/healthz", port))
if err != nil {
t.Fatal(err)
}
response.Body.Close()
if response.StatusCode != http.StatusOK {
t.Fatalf("launcher reopening retired the ready room = %d", response.StatusCode)
}
}
func TestHungBrowserHandoffDoesNotBlockLauncherOrSiteExit(t *testing.T) {
t.Setenv("TERM", "dumb")
for _, mode := range []string{"launcher", "site", "starred-site", "starred-second-site", "revoked-site"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
control, err := loopback.Start(ctx, loopback.Options{})
if err != nil {
t.Fatal(err)
}
defer control.Close()
console := newConsole(cancel, false)
started, release := make(chan struct{}, 10), make(chan struct{})
defer close(release)
console.openURL = func(string) error { started <- struct{}{}; <-release; return errors.New("late browser result") }
options := Options{Port: 8787, console: console}
configPath := filepath.Join(t.TempDir(), "client.json")
config, err := appconfig.LoadOrCreate(configPath)
if err != nil {
t.Fatal(err)
}
if mode == "starred-site" || mode == "revoked-site" {
if err := launcher.SaveStartupSite(configPath, "https://share.example"); err != nil {
t.Fatal(err)
}
if mode == "starred-site" {
config.Site = "https://share.example"
}
}
if mode == "starred-second-site" {
config.SetApprovedSites([]string{"https://first.example", "https://share.example"})
if err := launcher.SaveStartupSite(configPath, "https://share.example"); err != nil {
t.Fatal(err)
}
}
done := make(chan error, 1)
go func() {
if mode == "site" {
options.SiteSet = true
config.Site = "https://share.example"
done <- runLauncher(ctx, options, configPath, config, control, func(*Options, appconfig.Config) error { return nil })
} else {
done <- runLauncher(ctx, options, configPath, config, control, func(*Options, appconfig.Config) error { return nil })
}
}()
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("browser handoff was not started")
}
console.mu.Lock()
model := console.plain
console.mu.Unlock()
if model.view.entry == "" {
t.Fatal("manual entry was not available while browser opening hung")
}
if mode == "site" || mode == "starred-site" || mode == "starred-second-site" {
if model.view.entry != launcher.EntryURL("https://share.example", control.Endpoint().Port) {
t.Fatalf("App did not open the selected Site: %s", model.view.entry)
}
response, err := http.Get(strings.TrimSuffix(model.launcher, "/client") + "/api/client-launcher")
if err != nil {
t.Fatalf("launcher management is unavailable: %v", err)
}
var state struct {
ControlPort int `json:"controlPort"`
}
if err := json.NewDecoder(response.Body).Decode(&state); err != nil || state.ControlPort != control.Endpoint().Port {
t.Fatalf("launcher selected another App runtime: %+v, %v", state, err)
}
response.Body.Close()
if response.StatusCode != http.StatusOK {
t.Fatal("Site entry lost access to the launcher")
}
} else if !strings.HasSuffix(model.view.entry, "/client") {
t.Fatalf("App did not preserve launcher entry: %s", model.view.entry)
}
for range 5 {
_, command := model.Update(tea.KeyPressMsg{Code: 'o'})
if command != nil {
command()
}
}
select {
case <-started:
t.Fatal("repeated open queued another hung handler")
case <-time.After(50 * time.Millisecond):
}
model.Update(tea.KeyPressMsg{Code: 'q'})
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(time.Second):
t.Fatal("App exit waited for the browser handler")
}
console.finish(nil, "")
})
}
}
func TestBrowserOpenFailureKeepsTheAppAvailable(t *testing.T) {
// An empty launcher search path makes the real browser.Open fail on every
// supported platform without changing the user's default browser or opening it.
t.Setenv("PATH", t.TempDir())
t.Setenv("TERM", "dumb")
for _, mode := range []string{"launcher", "site"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
control, err := loopback.Start(ctx, loopback.Options{})
if err != nil {
t.Fatal(err)
}
defer control.Close()
console := newConsole(cancel, false)
options := Options{Port: 8787, console: console}
configPath := filepath.Join(t.TempDir(), "client.json")
config, err := appconfig.LoadOrCreate(configPath)
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
if mode == "site" {
options.SiteSet = true
config.Site = "https://share.example"
done <- runLauncher(ctx, options, configPath, config, control, func(*Options, appconfig.Config) error { return nil })
} else {
done <- runLauncher(ctx, options, configPath, config, control,
func(*Options, appconfig.Config) error { return nil })
}
}()
t.Cleanup(func() {
cancel()
select {
case err := <-done:
if err != nil {
t.Errorf("App exit: %v", err)
}
case <-time.After(5 * time.Second):
t.Error("App did not stop after cancellation")
}
})
var view consoleView
deadline := time.After(3 * time.Second)
for view.browserError == nil {
console.mu.Lock()
view = console.plain.view
console.mu.Unlock()
select {
case <-deadline:
t.Fatal("browser failure was not reported")
case <-time.After(10 * time.Millisecond):
}
}
if view.entry == "" || view.state != "setup" && view.state != "ready" {
t.Fatalf("unusable App after browser failure: %+v", view)
}
if mode == "launcher" {
client := &http.Client{Timeout: 3 * time.Second}
origin := strings.TrimSuffix(view.entry, "/client")
response, err := postLocalLauncher(client, origin+"/api/client-launcher/site", "application/json",
strings.NewReader(`{"site":"https://share.example","allowed":true}`))
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
var result struct{ Sites []string }
if json.NewDecoder(response.Body).Decode(&result) != nil || response.StatusCode != http.StatusOK || strings.Join(result.Sites, ",") != "https://share.example" {
t.Fatalf("manual approval failed: status=%d, site=%q", response.StatusCode, result.Sites)
}
saved, err := appconfig.LoadOrCreate(configPath)
if err != nil || saved.Site != strings.Join(result.Sites, ",") {
t.Fatalf("approval was not saved: %v", err)
}
}
})
}
}
func TestSavedSiteAllowsBrowserOriginAtNativeControl(t *testing.T) {
for _, site := range []struct{ input, origin string }{
{"https://Share.Example:443", "https://share.example"},
{"http://share.example:80", "http://share.example"},
{"http://share.example:8787", "http://share.example:8787"},
} {
t.Run(site.input, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "client.json")
payload := fmt.Sprintf(`{"version":1,"localAccessPassword":"","site":%q,"sites":["https://second.example"]}`, site.input)
if err := os.WriteFile(path, []byte(payload), 0o600); err != nil {
t.Fatal(err)
}
configuration, err := appconfig.LoadOrCreate(path)
if err != nil {
t.Fatal(err)
}
control, err := loopback.Start(t.Context(), loopback.Options{
AllowedOrigins: allowedOrigins(configuration.ApprovedSites(), 8787),
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = control.Close() })
client := &http.Client{Timeout: 3 * time.Second}
for _, probe := range []struct {
method, origin string
status int
}{
{http.MethodOptions, site.origin, http.StatusNoContent},
{http.MethodGet, site.origin, http.StatusOK},
{http.MethodGet, "https://second.example", http.StatusOK},
{http.MethodOptions, "https://other.example", http.StatusForbidden},
} {
request, err := http.NewRequest(probe.method, control.Endpoint().URL+"/health", nil)
if err != nil {
t.Fatal(err)
}
request.Header.Set("Origin", probe.origin)
response, err := client.Do(request)
if err != nil {
t.Fatal(err)
}
response.Body.Close()
if response.StatusCode != probe.status {
t.Fatalf("%s health from %q = %d, want %d", probe.method, probe.origin, response.StatusCode, probe.status)
}
}
})
}
}
func TestOccupiedPortRejectsLinkBeforeStartingATunnel(t *testing.T) {
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4zero})
if err != nil {
t.Fatal(err)
}
defer listener.Close()
err = runLocal(t.Context(), Options{
Link: true, Port: listener.Addr().(*net.TCPAddr).Port,
TunnelProcess: "missing-tunnel-process", console: &console{machine: true},
}, appconfig.Config{}, nil)
var bindError *net.OpError
if !errors.As(err, &bindError) || bindError.Op != "listen" {
t.Fatalf("occupied port must fail before tunnel work: %v", err)
}
}
func TestLocalLaunchRevalidatesTheChosenLANAddress(t *testing.T) {
addresses, err := lan.Addresses()
if err != nil {
t.Skipf("test requires an active LAN address: %v", err)
}
const inactive = "192.0.2.254"
if slices.Contains(addresses, inactive) {
t.Skip("documentation address is configured on this test machine")
}
err = runLocal(t.Context(), Options{
Local: true, LANAddress: inactive, console: &console{machine: true},
}, appconfig.Config{}, nil)
if err == nil || !strings.Contains(err.Error(), "selected LAN address is not active") {
t.Fatalf("Local launch accepted an unavailable invitation address: %v", err)
}
}
func TestAppLaunchURLMarksThePageWithoutChangingOrigin(t *testing.T) {
value := launcher.EntryURL("https://share.example/", loopback.DefaultPortStart)
parsed, err := url.Parse(value)
if err != nil || parsed.Scheme != "https" || parsed.Host != "share.example" ||
parsed.Query().Get("piik-client-port") != strconv.Itoa(loopback.DefaultPortStart) {
t.Fatalf("launch URL = %q, %v", value, err)
}
fragment, err := url.ParseQuery(parsed.EscapedFragment())
if err != nil || fragment.Get("piik-client") != "1" {
t.Fatalf("App launch fragment = %q, %v", parsed.Fragment, err)
}
}
func TestAppDiagnosticsUseFilesOnlyWhenEnabled(t *testing.T) {
for value, want := range map[string]bool{
"client": true, "route, client": true, "client,": true,
"": false, "route": false, "all": false, "client-secret": false,
} {
if got := debugEnabled(value); got != want {
t.Fatalf("debugEnabled(%q) = %v, want %v", value, got, want)
}
}
var output bytes.Buffer
previousOutput := log.Writer()
previousLevel := slog.SetLogLoggerLevel(slog.LevelInfo)
log.SetOutput(&output)
t.Cleanup(func() {
log.SetOutput(previousOutput)
slog.SetLogLoggerLevel(previousLevel)
})
t.Setenv("PIIK_DEBUG", "")
for _, enabled := range []bool{false, true} {
output.Reset()
directory := t.TempDir()
err := Run(t.Context(), Options{Debug: enabled, LogDir: directory, DisableBrowser: true, Local: true, Link: true})
if err == nil {
t.Fatal("invalid mode must stop before starting capture or services")
}
if strings.Contains(output.String(), "piik-client") {
t.Fatalf("App diagnostics reached stderr: %s", output.String())
}
content, readErr := os.ReadFile(filepath.Join(directory, "client.log"))
if !enabled {
if !errors.Is(readErr, os.ErrNotExist) {
t.Fatalf("disabled diagnostics created a log: %v", readErr)
}
continue
}
if readErr != nil || !strings.Contains(string(content), `"event":"start"`) ||
!strings.Contains(string(content), `"version":"`+buildinfo.Version()+`"`) ||
!strings.Contains(string(content), `"revision":`) ||
!strings.Contains(string(content), `"event":"stopped","failed":true`) {
t.Fatalf("missing file lifecycle events: %s, %v", content, readErr)
}
reports, err := filepath.Glob(filepath.Join(directory, "*.zip"))
if err != nil || len(reports) != 1 {
t.Fatalf("failed App did not export its diagnostic report: %v, %v", reports, err)
}
}
}
func TestAppConfigurationFailurePreservesSystemCause(t *testing.T) {
t.Setenv("PIIK_DEBUG", "")
blocked := filepath.Join(t.TempDir(), "not-a-directory")
if err := os.WriteFile(blocked, nil, 0o600); err != nil {
t.Fatal(err)
}
err := Run(t.Context(), Options{DisableBrowser: true, ConfigPath: filepath.Join(blocked, "client.json")})
var cause *os.PathError
if !errors.As(err, &cause) || !strings.Contains(err.Error(), "Piik App configuration is unavailable") {
t.Fatalf("configuration failure lost its path/system cause: %v", err)
}
}
func TestAppDiagnosticDirectoryHonorsExplicitSelection(t *testing.T) {
environmentDirectory := t.TempDir()
t.Setenv("PIIK_LOG_DIR", environmentDirectory)
for _, directory := range []string{"", t.TempDir()} {
recorder, err := openDiagnostics(directory)
if err != nil {
t.Fatal(err)
}
want := directory
if want == "" {
want = environmentDirectory
}
if recorder.LogPath() != filepath.Join(want, "client.log") {
t.Fatalf("diagnostic path = %q", recorder.LogPath())
}
if err = recorder.Close(); err != nil {
t.Fatal(err)
}
}
blocked := filepath.Join(t.TempDir(), "not-a-directory")
if err := os.WriteFile(blocked, nil, 0o600); err != nil {
t.Fatal(err)
}
if recorder, err := openDiagnostics(blocked); err == nil {
_ = recorder.Close()
t.Fatal("an explicit directory failure silently fell back")
}
}
func TestMissingCaptureKeepsViewerControlAvailable(t *testing.T) {
native := discoverNativeMedia(t.Context(), "missing-capture-process")
if native.capabilities.Video || native.capabilities.HardwareH264 {
t.Fatalf("missing native capture = %+v", native)
}
if !native.capabilities.ReceiverReuse || native.capabilities.MaxRelayChildren != 20 {
t.Fatalf("missing capture lost native receiver capability: %+v", native.capabilities)
}
control := native.controlFactory(nil)()
if control == nil {
t.Fatal("missing capture disabled the native Viewer control")
}
_ = control.Close()
}
func TestFailedCaptureProbeRetainsItsCause(t *testing.T) {
path := t.TempDir() // A directory exists but cannot run as a capture sidecar.
native := discoverNativeMedia(t.Context(), path)
if native.discoveryErr == nil || native.captureProcess != path || native.capabilities.Video {
t.Fatalf("failed probe lost its diagnostic context: %+v", native)
}
}
func TestLaunchURLPreservesLocalAccessInsideThePrivateFragment(t *testing.T) {
value := launcher.EntryURL("http://localhost:8787/#client-access=secret", loopback.DefaultPortStart)
parsed, err := url.Parse(value)
if err != nil || parsed.Query().Get("piik-client-port") != strconv.Itoa(loopback.DefaultPortStart) {
t.Fatalf("local native launch URL = %q, %v", value, err)
}
fragment, err := url.ParseQuery(parsed.EscapedFragment())
if err != nil || fragment.Get("client-access") != "secret" ||
fragment.Get("piik-client") != "1" {
t.Fatalf("local native launch fragment = %q, %v", parsed.Fragment, err)
}
}
func TestLaunchURLEncodesAndClearsOptionalLocalAccess(t *testing.T) {
for _, password := range []string{"x", "好", " ", "+", "%", "#&?=", " 中文 a+b&c?d=e% "} {
t.Run(password, func(t *testing.T) {
value := launcher.LocalEntryURL(
"http://localhost:8787/?retained=query#retained=a%2Bb%25&client-access=old&piik-lang=zh&piik-mode=text&piik-theme=dark",
password,
loopback.DefaultPortStart,
)
for _, target := range []string{value, launcher.EntryURL(value, loopback.DefaultPortStart)} {
parsed, err := url.Parse(target)
if err != nil || parsed.Query().Get("retained") != "query" ||
parsed.Query().Get("piik-client-port") != strconv.Itoa(loopback.DefaultPortStart) {
t.Fatalf("local launch URL = %q, %v", target, err)
}
// location.hash stays escaped. Parsing Fragment instead would decode
// twice and hide the browser's percent-encoded-password regression.
fragment, err := url.ParseQuery(parsed.EscapedFragment())
if err != nil || fragment.Get("client-access") != password ||
fragment.Get("piik-client") != "1" || fragment.Get("retained") != "a+b%" ||
fragment.Get("piik-lang") != "zh" || fragment.Get("piik-mode") != "text" ||
fragment.Get("piik-theme") != "dark" {
t.Fatalf("browser-visible launch fragment = %q, %v", parsed.EscapedFragment(), err)
}
}
})
}
open := launcher.LocalEntryURL("http://localhost:8787/#client-access=old", "", loopback.DefaultPortStart)
parsed, err := url.Parse(open)
if err != nil {
t.Fatal(err)
}
fragment, err := url.ParseQuery(parsed.EscapedFragment())
if err != nil || fragment.Get("client-access") != "" || fragment.Get("piik-client") != "1" {
t.Fatalf("open local launch fragment = %q, %v", parsed.Fragment, err)
}
}
func TestLinkModeKeepsOneLocalAuthority(t *testing.T) {
config := appconfig.Config{
Version: 1,
LocalAccessPassword: "abcdefghijklmnopqrstuvwxyzABCDEF",
Site: "https://example.test",
}
for _, options := range []Options{{Link: true}, {Local: true}} {
selected, err := applyMode(config, options)
if err != nil || !reflect.DeepEqual(selected, config) {
t.Fatalf("mode selection changed saved settings: %+v, %v", selected, err)
}
}
if err := validateMode(Options{Link: true, SiteSet: true}); err == nil {
t.Fatal("link mode accepted a separate Site")
}
if err := validateMode(Options{Link: true, Local: true}); err == nil {
t.Fatal("link mode accepted a second Local selector")
}
}
// The Local room authority owns its ICE configuration independently of Hosted
// environment settings, and only --link is public.
func TestLocalServerOwnsItsSTUNConfiguration(t *testing.T) {
t.Setenv("STUN_URLS", "stun:inherited.example:3478")
for _, testCase := range []struct {
name string
link bool
override string
stunURLs []string
natPredictionSTUNURLs []string
}{
{name: "local"},
{name: "local ignores public override", override: "invalid"},
{
name: "link", link: true,
stunURLs: []string{"stun:stun.cloudflare.com:3478", "stun:stun.miwifi.com:3478", "stun:stun.chat.bilibili.com:3478"},
natPredictionSTUNURLs: []string{
"stun:stun.miwifi.com:3478", "stun:stun.chat.bilibili.com:3478",
},
},
{
name: "custom discovery", link: true, override: "stun:chosen.test:3478",
stunURLs: []string{"stun:chosen.test:3478"},
},
{
name: "custom survey", link: true,
override: "stun:a.test:19302, stun:b.test:3478, stun:c.test:3478, stun:fallback.test:3478",
stunURLs: []string{"stun:a.test:19302", "stun:b.test:3478", "stun:c.test:3478", "stun:fallback.test:3478"},
natPredictionSTUNURLs: []string{"stun:b.test:3478", "stun:c.test:3478"},
},
} {
t.Run(testCase.name, func(t *testing.T) {
t.Setenv("PIIK_STUN_URLS", testCase.override)
stunURLs, natPredictionSTUNURLs, err := localSTUNURLs(testCase.link)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(stunURLs, testCase.stunURLs) ||
!slices.Equal(natPredictionSTUNURLs, testCase.natPredictionSTUNURLs) {
t.Fatalf("Local STUN selection = %v, %v", stunURLs, natPredictionSTUNURLs)
}
publicOrigin := ""
wantSTUNURLs := []string{"stun:192.168.1.2:8787"}
if testCase.link {
publicOrigin = "https://public.example.test"
wantSTUNURLs = testCase.stunURLs
}
config, err := serverconfig.Local(serverconfig.LocalOptions{
Port: 8787,
PublicAddress: "192.168.1.2",
PublicOrigin: publicOrigin,
AllowedAddresses: []string{"192.168.1.2"},
SiteAccessPassword: "abcdefghijklmnopqrstuvwxyzABCDEF",
STUNURLs: stunURLs,
NATPredictionSTUNURLs: natPredictionSTUNURLs,
})
if err != nil {
t.Fatal(err)
}
if !slices.Equal(config.STUNURLs, wantSTUNURLs) ||
config.NATPredictionEnabled != (len(testCase.natPredictionSTUNURLs) != 0) {
t.Fatalf("Local server config = %v, NAT prediction %t",
config.STUNURLs, config.NATPredictionEnabled)
}
})
}
for _, value := range []string{"turn:chosen.test:3478", "stun:a.test:3478,,stun:b.test:3478",
"stun:a:1,stun:b:2,stun:c:3,stun:d:4,stun:e:5,stun:f:6,stun:g:7"} {
t.Setenv("PIIK_STUN_URLS", value)
if _, _, err := localSTUNURLs(true); err == nil {
t.Fatalf("invalid public STUN list accepted: %q", value)
}
}
}
func postLocalLauncher(client *http.Client, target, contentType string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPost, target, body)
if err != nil {
return nil, err
}
address, _ := url.Parse(target)
req.Header.Set("Origin", address.Scheme+"://"+address.Host)
req.Header.Set("Content-Type", contentType)
return client.Do(req)
}