High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: harden recorder against resource exhaustion, races, and access control
Mariofef595668369
diff --git a/internal/cli/actions/actions_record.go b/internal/cli/actions/actions_record.goindex d59f5315..dc4fc705 100644--- a/internal/cli/actions/actions_record.go+++ b/internal/cli/actions/actions_record.go@@ -100,16 +100,29 @@ func recordingStateFile() string {if dir := os.Getenv("XDG_STATE_HOME"); dir != "" {return dir + "/pinchtab/current-recording"}- if home, err := os.UserHomeDir(); err == nil {- return home + "/.local/state/pinchtab/current-recording"+ home, err := os.UserHomeDir()+ if err != nil {+ home = os.TempDir()}- return "/tmp/pinchtab-current-recording"+ return home + "/.local/state/pinchtab/current-recording"}func writeRecordingState(outFile string) {path := recordingStateFile()- _ = os.MkdirAll(filepath.Dir(path), 0755)- _ = os.WriteFile(path, []byte(outFile+"\n"), 0644)+ dir := filepath.Dir(path)+ _ = os.MkdirAll(dir, 0700)+ tmp, err := os.CreateTemp(dir, ".current-recording-*")+ if err != nil {+ _ = os.WriteFile(path, []byte(outFile+"\n"), 0600)+ return+ }+ _, _ = tmp.WriteString(outFile + "\n")+ _ = tmp.Chmod(0600)+ tmpName := tmp.Name()+ _ = tmp.Close()+ if err := os.Rename(tmpName, path); err != nil {+ _ = os.Remove(tmpName)+ }}func readRecordingState() string {diff --git a/internal/handlers/middleware_session_grants.go b/internal/handlers/middleware_session_grants.goindex 19ebf240..73fc4060 100644--- a/internal/handlers/middleware_session_grants.go+++ b/internal/handlers/middleware_session_grants.go@@ -203,7 +203,8 @@ func sessionMediaGrantAllows(method, path string) bool {case path == "/pdf",path == "/download",path == "/screencast",- path == "/screencast/tabs":+ path == "/screencast/tabs",+ path == "/record/status":return truecase tabRouteHasSuffix(path, "/pdf"),tabRouteHasSuffix(path, "/download"):@@ -212,7 +213,9 @@ func sessionMediaGrantAllows(method, path string) bool {case http.MethodPost:switch {case path == "/pdf",- path == "/upload":+ path == "/upload",+ path == "/record/start",+ path == "/record/stop":return truecase tabRouteHasSuffix(path, "/pdf"),tabRouteHasSuffix(path, "/upload"):diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.goindex 73017df1..374db7b9 100644--- a/internal/handlers/openapi.go+++ b/internal/handlers/openapi.go@@ -103,6 +103,21 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {"description": security["screencast"].Message,"x-pinchtab-enabled": security["screencast"].Enabled,}},+ "/record/start": map[string]any{"post": map[string]any{+ "summary": "Start recording browser activity to video",+ "description": security["screencast"].Message,+ "x-pinchtab-enabled": security["screencast"].Enabled,+ }},+ "/record/stop": map[string]any{"post": map[string]any{+ "summary": "Stop recording and return encoded file",+ "description": security["screencast"].Message,+ "x-pinchtab-enabled": security["screencast"].Enabled,+ }},+ "/record/status": map[string]any{"get": map[string]any{+ "summary": "Check recording status",+ "description": security["screencast"].Message,+ "x-pinchtab-enabled": security["screencast"].Enabled,+ }},"/storage": map[string]any{"get": map[string]any{"summary": "Get localStorage/sessionStorage items (current origin only)",diff --git a/internal/handlers/record.go b/internal/handlers/record.goindex ce78e757..6014e806 100644--- a/internal/handlers/record.go+++ b/internal/handlers/record.go@@ -17,11 +17,23 @@ import ("sort""strconv""sync"+ "sync/atomic""time""github.com/pinchtab/pinchtab/internal/httpx")+const (+ maxRecordDuration = 5 * time.Minute+ maxRecordFrames = 9000 // 5min × 30fps+ maxTempBytes = 1 << 30 // 1 GB disk+ maxOutputBytes = 256 << 20 // 256 MB encoded+ encodeTimeout = 2 * time.Minute+ maxFPS = 30+ maxQuality = 100+ maxScale = 1.0+)+type RecordingStatus struct {Active bool `json:"active"`Format string `json:"format,omitempty"`@@ -29,25 +41,30 @@ type RecordingStatus struct {Frames int `json:"frames"`TabID string `json:"tabId,omitempty"`FPS int `json:"fps,omitempty"`+ Owner string `json:"owner,omitempty"`}type recorder struct {mu sync.Mutexactive bool+ stopping booltabCtx context.Context+ tabCancel context.CancelFunctabID string+ owner stringformat stringfps intquality intscale float64tmpDir stringframeNum int+ tempBytes int64startTime time.TimestopCh chan struct{}doneCh chan struct{}}-func (rec *recorder) start(tabCtx context.Context, tabID, format string, fps, quality int, scale float64) error {+func (rec *recorder) start(tabCtx context.Context, tabID, owner, format string, fps, quality int, scale float64) error {rec.mu.Lock()defer rec.mu.Unlock()@@ -60,15 +77,21 @@ func (rec *recorder) start(tabCtx context.Context, tabID, format string, fps, qureturn fmt.Errorf("create temp dir: %w", err)}+ ctx, cancel := context.WithCancel(tabCtx)+rec.active = true- rec.tabCtx = tabCtx+ rec.stopping = false+ rec.tabCtx = ctx+ rec.tabCancel = cancelrec.tabID = tabID+ rec.owner = ownerrec.format = formatrec.fps = fpsrec.quality = qualityrec.scale = scalerec.tmpDir = tmpDirrec.frameNum = 0+ rec.tempBytes = 0rec.startTime = time.Now()rec.stopCh = make(chan struct{})rec.doneCh = make(chan struct{})@@ -77,36 +100,66 @@ func (rec *recorder) start(tabCtx context.Context, tabID, format string, fps, qureturn nil}-func (rec *recorder) stop() ([]byte, string, error) {+func (rec *recorder) stop(callerOwner string) ([]byte, string, error) {rec.mu.Lock()if !rec.active {rec.mu.Unlock()return nil, "", fmt.Errorf("no active recording")}+ if rec.stopping {+ doneCh := rec.doneCh+ rec.mu.Unlock()+ <-doneCh+ return nil, "", fmt.Errorf("no active recording")+ }+ if callerOwner != "" && rec.owner != "" && callerOwner != rec.owner {+ rec.mu.Unlock()+ return nil, "", fmt.Errorf("recording owned by another session")+ }+ rec.stopping = trueclose(rec.stopCh)+ doneCh := rec.doneCh+ format := rec.format+ tmpDir := rec.tmpDir+ frameNum := rec.frameNum+ fps := rec.fps+ scale := rec.scalerec.mu.Unlock()- <-rec.doneCh+ <-doneChrec.mu.Lock()defer rec.mu.Unlock()+ defer rec.cleanup()- defer func() {- _ = os.RemoveAll(rec.tmpDir)- rec.active = false- rec.tmpDir = ""- }()-- if rec.frameNum == 0 {+ if frameNum == 0 {return nil, "", fmt.Errorf("no frames captured")}- data, err := rec.encode()+ data, err := encode(tmpDir, format, fps, scale)if err != nil {return nil, "", err}- return data, rec.format, nil+ if len(data) > maxOutputBytes {+ return nil, "", fmt.Errorf("encoded output too large (%d bytes, max %d)", len(data), maxOutputBytes)+ }++ return data, format, nil+}++func (rec *recorder) cleanup() {+ if rec.tabCancel != nil {+ rec.tabCancel()+ rec.tabCancel = nil+ }+ if rec.tmpDir != "" {+ _ = os.RemoveAll(rec.tmpDir)+ }+ rec.active = false+ rec.stopping = false+ rec.tmpDir = ""+ rec.owner = ""}func (rec *recorder) status() RecordingStatus {@@ -123,60 +176,93 @@ func (rec *recorder) status() RecordingStatus {Frames: rec.frameNum,TabID: rec.tabID,FPS: rec.fps,+ Owner: rec.owner,}}func (rec *recorder) captureLoop() {defer close(rec.doneCh)+ deadline := time.NewTimer(maxRecordDuration)+ defer deadline.Stop()+interval := time.Second / time.Duration(rec.fps)ticker := time.NewTicker(interval)defer ticker.Stop()+ var diskBytes atomic.Int64+for {select {case <-rec.stopCh:returncase <-rec.tabCtx.Done():+ rec.mu.Lock()+ rec.cleanup()+ rec.mu.Unlock()+ slog.Info("recording aborted: tab context canceled", "tab", rec.tabID)+ return+ case <-deadline.C:+ slog.Info("recording stopped: max duration reached", "tab", rec.tabID)returncase <-ticker.C:+ rec.mu.Lock()+ if rec.frameNum >= maxRecordFrames {+ rec.mu.Unlock()+ slog.Info("recording stopped: max frames reached", "tab", rec.tabID)+ return+ }+ rec.mu.Unlock()++ if diskBytes.Load() >= int64(maxTempBytes) {+ slog.Info("recording stopped: temp disk limit reached", "tab", rec.tabID)+ return+ }+frame, err := captureScreencastJPEG(rec.tabCtx, rec.quality)if err != nil {slog.Debug("recording frame capture failed", "err", err)continue}+rec.mu.Lock()rec.frameNum++path := filepath.Join(rec.tmpDir, fmt.Sprintf("frame_%06d.jpg", rec.frameNum))rec.mu.Unlock()+if err := os.WriteFile(path, frame, 0600); err != nil {slog.Debug("recording frame write failed", "err", err)+ } else {+ diskBytes.Add(int64(len(frame)))}}}}-func (rec *recorder) encode() ([]byte, error) {- switch rec.format {+func encode(tmpDir, format string, fps int, scale float64) ([]byte, error) {+ ctx, cancel := context.WithTimeout(context.Background(), encodeTimeout)+ defer cancel()++ switch format {case "gif":- return rec.encodeGIF()+ return encodeGIF(tmpDir, fps, scale)case "webm":- return rec.encodeFFmpeg("libvpx", "-crf", "10", "-b:v", "1M")+ return encodeFFmpeg(ctx, tmpDir, format, fps, scale, "libvpx", "-crf", "10", "-b:v", "1M")case "mp4":- return rec.encodeFFmpeg("libx264", "-pix_fmt", "yuv420p", "-crf", "23")+ return encodeFFmpeg(ctx, tmpDir, format, fps, scale, "libx264", "-pix_fmt", "yuv420p", "-crf", "23")default:- return nil, fmt.Errorf("unsupported format: %s", rec.format)+ return nil, fmt.Errorf("unsupported format: %s", format)}}-func (rec *recorder) encodeGIF() ([]byte, error) {- files, err := filepath.Glob(filepath.Join(rec.tmpDir, "frame_*.jpg"))+func encodeGIF(tmpDir string, fps int, scale float64) ([]byte, error) {+ files, err := filepath.Glob(filepath.Join(tmpDir, "frame_*.jpg"))if err != nil {return nil, err}sort.Strings(files)- delay := 100 / rec.fps+ delay := 100 / fpsif delay < 1 {delay = 1}@@ -193,8 +279,8 @@ func (rec *recorder) encodeGIF() ([]byte, error) {continue}- if rec.scale != 1.0 && rec.scale > 0 {- img = scaleImage(img, rec.scale)+ if scale != 1.0 && scale > 0 {+ img = scaleImage(img, scale)}bounds := img.Bounds()@@ -215,25 +301,25 @@ func (rec *recorder) encodeGIF() ([]byte, error) {return buf.Bytes(), nil}-func (rec *recorder) encodeFFmpeg(codec string, extraArgs ...string) ([]byte, error) {- outFile := filepath.Join(rec.tmpDir, "output."+rec.format)+func encodeFFmpeg(ctx context.Context, tmpDir, format string, fps int, scale float64, codec string, extraArgs ...string) ([]byte, error) {+ outFile := filepath.Join(tmpDir, "output."+format)args := []string{"-y",- "-framerate", strconv.Itoa(rec.fps),- "-i", filepath.Join(rec.tmpDir, "frame_%06d.jpg"),+ "-framerate", strconv.Itoa(fps),+ "-i", filepath.Join(tmpDir, "frame_%06d.jpg"),}- if rec.scale != 1.0 && rec.scale > 0 {+ if scale != 1.0 && scale > 0 {args = append(args, "-vf",- fmt.Sprintf("scale=trunc(iw*%g/2)*2:trunc(ih*%g/2)*2", rec.scale, rec.scale))+ fmt.Sprintf("scale=trunc(iw*%g/2)*2:trunc(ih*%g/2)*2", scale, scale))}args = append(args, "-c:v", codec)args = append(args, extraArgs...)args = append(args, outFile)- cmd := exec.Command("ffmpeg", args...)+ cmd := exec.CommandContext(ctx, "ffmpeg", args...)var stderr bytes.Buffercmd.Stderr = &stderrif err := cmd.Run(); err != nil {@@ -305,15 +391,21 @@ func (h *Handlers) HandleRecordStart(w http.ResponseWriter, r *http.Request) {if req.FPS <= 0 {req.FPS = 5}- if req.FPS > 30 {- req.FPS = 30+ if req.FPS > maxFPS {+ req.FPS = maxFPS}if req.Quality <= 0 {req.Quality = 80}+ if req.Quality > maxQuality {+ req.Quality = maxQuality+ }if req.Scale <= 0 {req.Scale = 1.0}+ if req.Scale > maxScale {+ req.Scale = maxScale+ }switch req.Format {case "gif":@@ -336,12 +428,14 @@ func (h *Handlers) HandleRecordStart(w http.ResponseWriter, r *http.Request) {return}- if err := h.recorder.start(ctx, resolvedTabID, req.Format, req.FPS, req.Quality, req.Scale); err != nil {+ owner := requestOwner(r)++ if err := h.recorder.start(ctx, resolvedTabID, owner, req.Format, req.FPS, req.Quality, req.Scale); err != nil {httpx.ErrorCode(w, 409, "recording_error", err.Error(), false, nil)return}- slog.Info("recording started", "tab", resolvedTabID, "format", req.Format, "fps", req.FPS)+ slog.Info("recording started", "tab", resolvedTabID, "format", req.Format, "fps", req.FPS, "owner", owner)httpx.JSON(w, 200, map[string]any{"status": "recording","format": req.Format,@@ -353,7 +447,8 @@ func (h *Handlers) HandleRecordStart(w http.ResponseWriter, r *http.Request) {// HandleRecordStop stops the active recording and returns the encoded file.func (h *Handlers) HandleRecordStop(w http.ResponseWriter, r *http.Request) {- data, format, err := h.recorder.stop()+ owner := requestOwner(r)+ data, format, err := h.recorder.stop(owner)if err != nil {httpx.ErrorCode(w, 400, "recording_error", err.Error(), false, nil)return@@ -381,3 +476,13 @@ func (h *Handlers) HandleRecordStop(w http.ResponseWriter, r *http.Request) {func (h *Handlers) HandleRecordStatus(w http.ResponseWriter, r *http.Request) {httpx.JSON(w, 200, h.recorder.status())}++func requestOwner(r *http.Request) string {+ if sid := r.Header.Get("X-Pinchtab-Session-Id"); sid != "" {+ return sid+ }+ if aid := r.Header.Get("X-Agent-Id"); aid != "" {+ return aid+ }+ return ""+}diff --git a/internal/handlers/record_test.go b/internal/handlers/record_test.goindex ed30fe0f..c6c6126a 100644--- a/internal/handlers/record_test.go+++ b/internal/handlers/record_test.go@@ -2,6 +2,7 @@ package handlersimport ("bytes"+ "context""encoding/json""net/http/httptest""testing"@@ -80,36 +81,26 @@ func TestHandleRecordStart_Success(t *testing.T) {if resp["tabId"] == nil || resp["tabId"] == "" {t.Errorf("expected tabId to be set, got %v", resp["tabId"])}-- // Clean up: stop the recording (ignore error since no frames captured)- _, _, _ = h.recorder.stop()}-func TestHandleRecordStart_AlreadyRecording(t *testing.T) {- cfg := &config.RuntimeConfig{AllowScreencast: true}- h := New(&mockBridge{}, cfg, nil, nil, nil)-- // First start: should succeed- body := `{"format":"gif","fps":5}`- req := httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))- w := httptest.NewRecorder()- h.HandleRecordStart(w, req)+func TestRecorderStart_AlreadyRecording(t *testing.T) {+ rec := &recorder{}+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()- if w.Code != 200 {- t.Fatalf("first start: expected 200, got %d: %s", w.Code, w.Body.String())+ if err := rec.start(ctx, "tab1", "", "gif", 5, 80, 1.0); err != nil {+ t.Fatalf("first start: %v", err)}- // Second start: should return 409- req = httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))- w = httptest.NewRecorder()- h.HandleRecordStart(w, req)-- if w.Code != 409 {- t.Errorf("expected 409 for already recording, got %d: %s", w.Code, w.Body.String())+ err := rec.start(ctx, "tab1", "", "gif", 5, 80, 1.0)+ if err == nil {+ t.Fatal("second start should fail")+ }+ if err.Error() != "recording already in progress" {+ t.Errorf("unexpected error: %v", err)}- // Clean up: stop the recording (ignore error since no frames captured)- _, _, _ = h.recorder.stop()+ _, _, _ = rec.stop("")}func TestHandleRecordStop_NoRecording(t *testing.T) {@@ -146,48 +137,105 @@ func TestHandleRecordStatus_Inactive(t *testing.T) {}}-func TestHandleRecordStatus_Active(t *testing.T) {+func TestRecorderStatus_Active(t *testing.T) {+ rec := &recorder{}+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ if err := rec.start(ctx, "tab1", "", "gif", 5, 80, 1.0); err != nil {+ t.Fatalf("start: %v", err)+ }++ status := rec.status()+ if !status.Active {+ t.Errorf("expected active=true, got false")+ }+ if status.Format != "gif" {+ t.Errorf("expected format=gif, got %q", status.Format)+ }+ if status.FPS != 5 {+ t.Errorf("expected fps=5, got %d", status.FPS)+ }+ if status.TabID != "tab1" {+ t.Errorf("expected tabId=tab1, got %q", status.TabID)+ }++ _, _, _ = rec.stop("")+}++func TestHandleRecordStart_ClampsInputs(t *testing.T) {cfg := &config.RuntimeConfig{AllowScreencast: true}h := New(&mockBridge{}, cfg, nil, nil, nil)- // Start a recording first- body := `{"format":"gif","fps":5}`+ body := `{"format":"gif","fps":60,"quality":200,"scale":3.0}`req := httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))w := httptest.NewRecorder()h.HandleRecordStart(w, req)if w.Code != 200 {- t.Fatalf("start: expected 200, got %d: %s", w.Code, w.Body.String())+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}- // Check status- req = httptest.NewRequest("GET", "/record/status", nil)- w = httptest.NewRecorder()- h.HandleRecordStatus(w, req)+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["fps"] != float64(maxFPS) {+ t.Errorf("expected fps clamped to %d, got %v", maxFPS, resp["fps"])+ }+ if resp["quality"] != float64(maxQuality) {+ t.Errorf("expected quality clamped to %d, got %v", maxQuality, resp["quality"])+ }+}- if w.Code != 200 {- t.Fatalf("status: expected 200, got %d", w.Code)+func TestRecorderStop_OwnerMismatch(t *testing.T) {+ rec := &recorder{}+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ if err := rec.start(ctx, "tab1", "agent-1", "gif", 5, 80, 1.0); err != nil {+ t.Fatal(err)}- var resp RecordingStatus- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode response: %v", err)+ _, _, err := rec.stop("agent-2")+ if err == nil || err.Error() != "recording owned by another session" {+ t.Errorf("expected owner mismatch error, got %v", err)}- if !resp.Active {- t.Errorf("expected active=true, got false")++ _, _, _ = rec.stop("agent-1")+}++func TestRecorderStop_OwnerMatch(t *testing.T) {+ rec := &recorder{}+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ if err := rec.start(ctx, "tab1", "agent-1", "gif", 5, 80, 1.0); err != nil {+ t.Fatal(err)}- if resp.Format != "gif" {- t.Errorf("expected format=gif, got %q", resp.Format)++ // Gets past owner check; fails with "no frames captured" which is expected+ _, _, err := rec.stop("agent-1")+ if err == nil || err.Error() != "no frames captured" {+ t.Errorf("expected 'no frames captured' error, got %v", err)}- if resp.FPS != 5 {- t.Errorf("expected fps=5, got %d", resp.FPS)+}++func TestRecorderStop_NoOwnerCanStopAnonymous(t *testing.T) {+ rec := &recorder{}+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ if err := rec.start(ctx, "tab1", "", "gif", 5, 80, 1.0); err != nil {+ t.Fatal(err)}- // Clean up: stop the recording (ignore error since no frames captured)- _, _, _ = h.recorder.stop()+ _, _, err := rec.stop("any-agent")+ if err == nil || err.Error() != "no frames captured" {+ t.Errorf("expected 'no frames captured', got %v", err)+ }}func TestFFmpegAvailable(t *testing.T) {- // Just verify it doesn't panic; result depends on environment._ = ffmpegAvailable()}diff --git a/internal/handlers/security.go b/internal/handlers/security.goindex 3fc73abf..d16904ec 100644--- a/internal/handlers/security.go+++ b/internal/handlers/security.go@@ -51,7 +51,7 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {Enabled: h.screencastEnabled(),Setting: "security.allowScreencast",Message: httpx.DisabledEndpointMessage("screencast", "security.allowScreencast"),- Paths: []string{"GET /screencast", "GET /screencast/tabs", "GET /instances/{id}/screencast", "GET /instances/{id}/proxy/screencast"},+ Paths: []string{"GET /screencast", "GET /screencast/tabs", "POST /record/start", "POST /record/stop", "GET /record/status", "GET /instances/{id}/screencast", "GET /instances/{id}/proxy/screencast"},},"download": {Enabled: h.downloadEnabled(),diff --git a/tests/e2e/scenarios/api/recording-smoke.sh b/tests/e2e/scenarios/api/recording-smoke.shindex 5e7b9a60..7f480872 100755--- a/tests/e2e/scenarios/api/recording-smoke.sh+++ b/tests/e2e/scenarios/api/recording-smoke.sh@@ -1,5 +1,5 @@#!/bin/bash-# recording-smoke.sh — Recording smoke tests (API + CLI).+# recording-smoke.sh — Recording smoke tests (API).GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"source "${GROUP_DIR}/../../helpers/api.sh"@@ -14,7 +14,7 @@ assert_json_eq "$RESULT" ".active" "false" "no active recording"end_test# ─────────────────────────────────────────────────────────────────-start_test "record: start → status → stop (API gif)"+start_test "record: start → status → stop (gif)"pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"assert_ok "navigate"@@ -57,29 +57,18 @@ assert_http_status 400 "stop without active recording"end_test# ─────────────────────────────────────────────────────────────────-start_test "record: CLI start → stop roundtrip"--rm -f "${XDG_STATE_HOME:-$HOME/.local/state}/pinchtab/current-recording" 2>/dev/null || true-rm -f /tmp/pinchtab-current-recording 2>/dev/null || true--CLI_OUTFILE="/tmp/e2e-cli-recording.gif"+start_test "record: double stop returns error"pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"-assert_ok "navigate for CLI recording"+assert_ok "navigate for double stop"-e2e_curl -s -X POST "${E2E_SERVER}/record/start" \- -H "Content-Type: application/json" \- -d '{"format":"gif","fps":2,"quality":60}' > /dev/null-sleep 2-e2e_curl -s -X POST "${E2E_SERVER}/record/stop" -o "$CLI_OUTFILE" \+pt_post /record/start -d '{"format":"gif","fps":2,"quality":60}'+assert_ok "start for double stop"++e2e_curl -s -X POST "${E2E_SERVER}/record/stop" -o /dev/null \-H "Content-Type: application/json" -d '{}'-FILESIZE=$(wc -c < "$CLI_OUTFILE" 2>/dev/null | tr -d ' ')-if [ -f "$CLI_OUTFILE" ] && [ "$FILESIZE" -gt 0 ]; then- pass_assert "CLI recording file created ($FILESIZE bytes)"-else- fail_assert "CLI recording file missing or empty"-fi-rm -f "$CLI_OUTFILE"+pt_post /record/stop -d '{}'+assert_http_status 400 "second stop returns error"end_test