Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: write recordings to server-controlled directory, not caller-supplied paths

Mariocda11213ae1a
diff --git a/internal/cli/actions/actions_record.go b/internal/cli/actions/actions_record.go
index 21985923..0a037d05 100644
--- a/internal/cli/actions/actions_record.go
+++ b/internal/cli/actions/actions_record.go
@@ -62,9 +62,9 @@ func RecordStop(client *http.Client, base, token string) {
outFile = abs
}
- raw := apiclient.DoPostRaw(client, base, token, "/record/stop", map[string]any{
- "outputPath": outFile,
- })
+ // Server encodes to its own recordings directory; we move the file
+ // to the user's desired location after encoding completes.
+ raw := apiclient.DoPostRaw(client, base, token, "/record/stop", map[string]any{})
clearRecordingState()
if raw == nil {
@@ -75,15 +75,48 @@ func RecordStop(client *http.Client, base, token string) {
Status string `json:"status"`
Path string `json:"path"`
Frames int `json:"frames"`
- Hint string `json:"hint"`
}
if err := json.Unmarshal(raw, &result); err != nil {
- fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Encoding → %s", outFile)))
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, "Recording stopped"))
return
}
- fmt.Println(cli.StyleStdout(cli.SuccessStyle,
- fmt.Sprintf("Encoding %d frames → %s (use `record status` to check progress)", result.Frames, result.Path)))
+ if result.Path == "" {
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle,
+ fmt.Sprintf("Recording stopped (%d frames)", result.Frames)))
+ return
+ }
+
+ fmt.Println(cli.StyleStdout(cli.MutedStyle,
+ fmt.Sprintf("Encoding %d frames...", result.Frames)))
+
+ serverPath := result.Path
+ for i := 0; i < 300; i++ {
+ time.Sleep(time.Second)
+ statusRaw := apiclient.DoGetRaw(client, base, token, "/record/status", nil)
+ if statusRaw == nil {
+ continue
+ }
+ var s struct {
+ State string `json:"state"`
+ Error string `json:"error"`
+ }
+ if json.Unmarshal(statusRaw, &s) != nil {
+ continue
+ }
+ if s.State == "finished" || s.State == "idle" {
+ if s.Error != "" {
+ cli.Fatal("Encoding failed: %s", s.Error)
+ }
+ if err := os.Rename(serverPath, outFile); err != nil {
+ cli.Fatal("Failed to move %s → %s: %v", serverPath, outFile, err)
+ }
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle,
+ fmt.Sprintf("Saved → %s", outFile)))
+ return
+ }
+ }
+ cli.Fatal("Encoding timed out — file may be at %s", serverPath)
}
func RecordStatus(client *http.Client, base, token string) {
diff --git a/internal/handlers/record.go b/internal/handlers/record.go
index aecf932a..495bbe66 100644
--- a/internal/handlers/record.go
+++ b/internal/handlers/record.go
@@ -277,6 +277,15 @@ func (rec *recorder) cleanup() {
rec.encodeErr = nil
}
+func (rec *recorder) activeFormat() string {
+ rec.mu.Lock()
+ defer rec.mu.Unlock()
+ if rec.format == "" {
+ return "gif"
+ }
+ return rec.format
+}
+
func (rec *recorder) status() RecordingStatus {
rec.mu.Lock()
defer rec.mu.Unlock()
@@ -653,31 +662,34 @@ func (h *Handlers) HandleRecordStart(w http.ResponseWriter, r *http.Request) {
})
}
-// HandleRecordStop stops the active recording. If outputPath is provided,
-// encoding runs in the background and the endpoint returns immediately.
-// If outputPath is empty, the recording is discarded (capture stops, no
-// encoding). Use /record/status to check encoding progress.
+// HandleRecordStop stops the active recording. If discard is false (default),
+// encoding runs in the background into a server-controlled recordings directory
+// and the endpoint returns the path immediately. If discard is true, frames are
+// dropped without encoding. Use /record/status to check encoding progress.
func (h *Handlers) HandleRecordStop(w http.ResponseWriter, r *http.Request) {
var req struct {
- OutputPath string `json:"outputPath"`
+ Discard bool `json:"discard"`
}
_ = httpx.DecodeJSONBody(w, r, 0, &req)
- if req.OutputPath != "" {
- if err := validateOutputPath(req.OutputPath); err != nil {
- httpx.ErrorCode(w, 400, "invalid_output_path", err.Error(), false, nil)
+ var outputPath string
+ if !req.Discard {
+ var err error
+ outputPath, err = h.recordingsOutputPath()
+ if err != nil {
+ httpx.ErrorCode(w, 500, "recording_error", err.Error(), false, nil)
return
}
}
owner := authenticatedOwner(r)
- result, err := h.recorder.stop(owner, req.OutputPath)
+ result, err := h.recorder.stop(owner, outputPath)
if err != nil {
httpx.ErrorCode(w, 400, "recording_error", err.Error(), false, nil)
return
}
- if req.OutputPath == "" {
+ if req.Discard {
httpx.JSON(w, 200, map[string]any{
"status": "discarded",
"format": result.Format,
@@ -697,46 +709,17 @@ func (h *Handlers) HandleRecordStop(w http.ResponseWriter, r *http.Request) {
})
}
-// validateOutputPath checks that an output path is safe to write to:
-// absolute, supported extension, parent dir exists and is not a symlink,
-// target and temp file do not already exist.
-func validateOutputPath(path string) error {
- cleaned := filepath.Clean(path)
- if !filepath.IsAbs(cleaned) {
- return fmt.Errorf("outputPath must be an absolute path, got %q", path)
- }
- ext := filepath.Ext(cleaned)
- switch ext {
- case ".gif", ".webm", ".mp4":
- default:
- return fmt.Errorf("unsupported extension %q — use .gif, .webm, or .mp4", ext)
- }
-
- dir := filepath.Dir(cleaned)
- dirInfo, err := os.Lstat(dir)
- if err != nil {
- return fmt.Errorf("output directory: %w", err)
- }
- if dirInfo.Mode()&os.ModeSymlink != 0 {
- return fmt.Errorf("output directory %q is a symlink", dir)
- }
- if !dirInfo.IsDir() {
- return fmt.Errorf("output directory %q is not a directory", dir)
- }
-
- if info, err := os.Lstat(cleaned); err == nil {
- if info.Mode()&os.ModeSymlink != 0 {
- return fmt.Errorf("refusing to follow symlink at %q", cleaned)
- }
- return fmt.Errorf("file already exists at %q — remove it first or choose another path", cleaned)
- }
-
- tmpPath := cleaned + ".encoding.tmp"
- if _, err := os.Lstat(tmpPath); err == nil {
- return fmt.Errorf("temp file already exists at %q — a previous encoding may still be running", tmpPath)
- }
-
- return nil
+// recordingsOutputPath returns a unique output path inside the server-controlled
+// recordings directory. The caller never chooses the path — only the server does.
+func (h *Handlers) recordingsOutputPath() (string, error) {
+ dir := filepath.Join(h.Config.StateDir, "recordings")
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return "", fmt.Errorf("create recordings dir: %w", err)
+ }
+ format := h.recorder.activeFormat()
+ ext := "." + format
+ name := fmt.Sprintf("rec_%s%s", time.Now().Format("20060102_150405"), ext)
+ return filepath.Join(dir, name), nil
}
// HandleRecordStatus returns the current recording status.
diff --git a/internal/mcp/handlers_record.go b/internal/mcp/handlers_record.go
index 4a354d66..2a6ab2b2 100644
--- a/internal/mcp/handlers_record.go
+++ b/internal/mcp/handlers_record.go
@@ -2,10 +2,12 @@ package mcp
import (
"context"
+ "encoding/json"
"fmt"
"io"
"os"
"path/filepath"
+ "time"
"github.com/mark3labs/mcp-go/mcp"
)
@@ -69,9 +71,7 @@ func handleRecordStop(c *Client) func(context.Context, mcp.CallToolRequest) (*mc
dest, pathErr := safeRecordPath(file)
if pathErr != nil {
- // Discard the recording: empty outputPath tells the server to
- // stop capture without encoding.
- _, _, stopErr := c.Post(ctx, "/record/stop", map[string]any{})
+ _, _, stopErr := c.Post(ctx, "/record/stop", map[string]any{"discard": true})
msg := fmt.Sprintf("invalid output path: %v — recording discarded", pathErr)
if stopErr != nil {
msg += fmt.Sprintf(" (also failed to discard recording: %v)", stopErr)
@@ -79,9 +79,9 @@ func handleRecordStop(c *Client) func(context.Context, mcp.CallToolRequest) (*mc
return mcp.NewToolResultError(msg), nil
}
- body, code, err := c.Post(ctx, "/record/stop", map[string]any{
- "outputPath": dest,
- })
+ // Server encodes to a controlled recordings directory; we move the
+ // file to the caller's desired destination after encoding completes.
+ body, code, err := c.Post(ctx, "/record/stop", map[string]any{})
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
@@ -89,8 +89,92 @@ func handleRecordStop(c *Client) func(context.Context, mcp.CallToolRequest) (*mc
return resultFromBytes(body, code)
}
- return resultFromBytes(body, code)
+ var stopResp struct {
+ Path string `json:"path"`
+ }
+ if json.Unmarshal(body, &stopResp) != nil || stopResp.Path == "" {
+ return resultFromBytes(body, code)
+ }
+
+ // Poll until encoding finishes, then move the file.
+ serverPath := stopResp.Path
+ if err := pollRecordingFinished(ctx, c); err != nil {
+ return mcp.NewToolResultError(fmt.Sprintf(
+ "encoding did not complete: %v — partial file may be at %s", err, serverPath)), nil
+ }
+
+ if err := moveFile(serverPath, dest); err != nil {
+ return mcp.NewToolResultError(fmt.Sprintf(
+ "encoded to %s but failed to move to %s: %v", serverPath, dest, err)), nil
+ }
+
+ return mcp.NewToolResultText(fmt.Sprintf(
+ "Recording saved to %s", dest)), nil
+ }
+}
+
+// pollRecordingFinished polls /record/status until state is "finished" or "idle".
+func pollRecordingFinished(ctx context.Context, c *Client) error {
+ ticker := time.NewTicker(time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
+ body, _, err := c.Get(ctx, "/record/status", nil)
+ if err != nil {
+ continue
+ }
+ var status struct {
+ State string `json:"state"`
+ Error string `json:"error"`
+ }
+ if json.Unmarshal(body, &status) != nil {
+ continue
+ }
+ switch status.State {
+ case "finished":
+ if status.Error != "" {
+ return fmt.Errorf("encode failed: %s", status.Error)
+ }
+ return nil
+ case "idle":
+ return nil
+ }
+ }
+ }
+}
+
+// moveFile moves src to dst using rename (fast, same filesystem) or
+// falls back to copy+remove for cross-filesystem moves. The destination
+// is created with O_EXCL to prevent overwrites or symlink following.
+func moveFile(src, dst string) error {
+ if err := os.Rename(src, dst); err == nil {
+ return nil
+ }
+ // Cross-filesystem: copy with exclusive creation.
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = in.Close() }()
+
+ out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(out, in); err != nil {
+ _ = out.Close()
+ _ = os.Remove(dst)
+ return err
+ }
+ if err := out.Close(); err != nil {
+ _ = os.Remove(dst)
+ return err
}
+ _ = os.Remove(src)
+ return nil
}
// safeRecordPath validates a recording output path to prevent arbitrary file
diff --git a/tests/e2e/scenarios/api/recording-smoke.sh b/tests/e2e/scenarios/api/recording-smoke.sh
index 834cca44..627c3d65 100755
--- a/tests/e2e/scenarios/api/recording-smoke.sh
+++ b/tests/e2e/scenarios/api/recording-smoke.sh
@@ -30,7 +30,7 @@ pt_get /record/status
assert_ok "record status"
assert_json_eq "$RESULT" ".active" "true" "recording active"
-pt_post /record/stop -d '{"outputPath":"/tmp/e2e-recording-test.gif"}'
+pt_post /record/stop -d '{}'
assert_ok "record stop"
assert_json_eq "$RESULT" ".status" "encoding" "stop returns encoding status"
@@ -77,10 +77,39 @@ assert_ok "start for double stop"
sleep 2
-pt_post /record/stop -d '{"outputPath":"/tmp/e2e-recording-double-stop.gif"}'
+pt_post /record/stop -d '{}'
assert_ok "first stop"
-pt_post /record/stop -d '{"outputPath":"/tmp/e2e-recording-double-stop2.gif"}'
+pt_post /record/stop -d '{}'
assert_http_status 400 "second stop returns error"
+# Wait for background encoding from the first stop to finish before next test
+for i in $(seq 1 60); do
+ pt_get /record/status >/dev/null 2>&1
+ STATE=$(echo "$RESULT" | jq -r '.state // empty')
+ if [ "$STATE" = "finished" ] || [ "$STATE" = "idle" ]; then break; fi
+ sleep 1
+done
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "record: discard drops frames without encoding"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+assert_ok "navigate for discard"
+
+pt_post /record/start -d '{"format":"gif","fps":2,"quality":60}'
+assert_ok "start for discard"
+
+sleep 2
+
+pt_post /record/stop -d '{"discard":true}'
+assert_ok "discard stop"
+assert_json_eq "$RESULT" ".status" "discarded" "discard returns discarded status"
+
+pt_get /record/status
+assert_ok "status after discard"
+assert_json_eq "$RESULT" ".state" "idle" "idle after discard"
+
end_test