Skip to content

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

fix: upload discards the original filename, so every file reaches the page as upload-0.bin and extension-validating forms reject it (PIN-132)

Luigi Agosti038a9fdb1af1
diff --git a/docs/endpoints.md b/docs/endpoints.md
index ed75d434..95262e1b 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -430,7 +430,8 @@ Notes:
- download automatically decompresses `.gz` files and returns the decompressed content
- `security.downloadAllowedDomains` can whitelist specific domains (bypasses SSRF checks for those domains). Setting `["*"]` matches every host and disables all private-IP protection on the download endpoint.
- clipboard endpoints are gated by `security.allowClipboard`
-- upload uses a JSON body with `selector` and `files`
+- upload uses a JSON body with `selector`, `files`, and optional `fileNames`
+- `fileNames` is index-aligned with `files` and sets the name the page sees in `file.name` — send it, or every upload arrives as `upload-<i>.bin` and forms gating on `accept=".csv"` or `file.name.endsWith(...)` reject it. Without a name the extension is sniffed from content, which cannot identify text formats (`.csv`, `.json`, `.txt`, `.md`, `.html`) because they have no magic bytes. A supplied name wins over the sniffed type even when the two disagree, matching what a browser sends. Only the basename is used: any directory part is dropped.
## Storage
diff --git a/internal/bridge/upload_filename_test.go b/internal/bridge/upload_filename_test.go
new file mode 100644
index 00000000..d14c3167
--- /dev/null
+++ b/internal/bridge/upload_filename_test.go
@@ -0,0 +1,136 @@
+package bridge
+
+import (
+ "context"
+ "encoding/base64"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/testbrowser"
+)
+
+const uploadFixtureHTML = `<body>
+<input type="file" id="target" multiple>
+</body>`
+
+func newUploadFixture(t *testing.T) context.Context {
+ t.Helper()
+
+ // Not t.TempDir: its cleanup FAILS THE TEST when the removal errors, and a
+ // Chrome that is still flushing its cache directory as the test returns makes
+ // that removal error — a green assertion then reports red for a reason that
+ // has nothing to do with what was asserted. Best-effort removal instead.
+ userDataDir, err := os.MkdirTemp("", "pinchtab-upload-fixture-*")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(userDataDir) })
+
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(testbrowser.Path(t)),
+ chromedp.UserDataDir(userDataDir),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ })
+
+ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(uploadFixtureHTML))
+ if err := chromedp.Run(ctx,
+ chromedp.Navigate(dataURL),
+ chromedp.WaitVisible("#target", chromedp.ByID),
+ ); err != nil {
+ t.Fatal(err)
+ }
+ return ctx
+}
+
+// stageFile writes content under dir/name and returns the path, so a test can
+// choose the on-disk basename the browser will see.
+func stageFile(t *testing.T, dir, name, content string) string {
+ t.Helper()
+
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, name)
+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
+
+func pageFileNames(t *testing.T, ctx context.Context) []string {
+ t.Helper()
+
+ var names []string
+ if err := chromedp.Run(ctx, chromedp.Evaluate(
+ `Array.from(document.getElementById('target').files).map(f => f.name)`, &names)); err != nil {
+ t.Fatal(err)
+ }
+ return names
+}
+
+// The premise the whole filename fix rests on: the page-visible file.name is the
+// BASENAME of the staged path, so preserving the caller's filename on disk is
+// what makes forms gating on `accept=".csv"` or `file.name.endsWith(...)` pass.
+// Nothing else can set it — CDP hands the input a path, not a name — so this is
+// asserted against a real browser rather than assumed.
+func TestSetFileInputFilesShowsTheStagedBasenameToThePage(t *testing.T) {
+ ctx := newUploadFixture(t)
+
+ staged := stageFile(t, t.TempDir(), "quarterly-report.csv", "a,b\n1,2\n")
+ nodeID := uploadTargetNodeID(t, ctx)
+
+ b := &Bridge{}
+ if err := b.SetFileInputFiles(ctx, nodeID, []string{staged}); err != nil {
+ t.Fatal(err)
+ }
+
+ names := pageFileNames(t, ctx)
+ if len(names) != 1 || names[0] != "quarterly-report.csv" {
+ t.Fatalf("page sees %v, want [quarterly-report.csv]", names)
+ }
+}
+
+// Two files with the same basename is the case the per-index staging directory
+// exists for: they must reach the page as two files under their real shared
+// name, not one file or a de-duplicated rename.
+func TestSetFileInputFilesKeepsDuplicateBasenamesFromSeparateDirs(t *testing.T) {
+ ctx := newUploadFixture(t)
+
+ base := t.TempDir()
+ first := stageFile(t, filepath.Join(base, "0"), "data.csv", "first")
+ second := stageFile(t, filepath.Join(base, "1"), "data.csv", "second")
+ nodeID := uploadTargetNodeID(t, ctx)
+
+ b := &Bridge{}
+ if err := b.SetFileInputFiles(ctx, nodeID, []string{first, second}); err != nil {
+ t.Fatal(err)
+ }
+
+ names := pageFileNames(t, ctx)
+ if len(names) != 2 || names[0] != "data.csv" || names[1] != "data.csv" {
+ t.Fatalf("page sees %v, want two files both named data.csv", names)
+ }
+}
+
+func uploadTargetNodeID(t *testing.T, ctx context.Context) int64 {
+ t.Helper()
+
+ b := &Bridge{}
+ nodeID, err := b.ResolveSelectorToNodeID(ctx, "#target")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return nodeID
+}
diff --git a/internal/cli/actions/actions_upload.go b/internal/cli/actions/actions_upload.go
index 19c6627a..bb89823e 100644
--- a/internal/cli/actions/actions_upload.go
+++ b/internal/cli/actions/actions_upload.go
@@ -5,6 +5,7 @@ import (
"net/http"
"net/url"
"os"
+ "path/filepath"
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/cli/apiclient"
@@ -15,17 +16,23 @@ func Upload(client *http.Client, base, token string, args []string, selector, ta
cli.Fatal("Usage: pinchtab upload <file-path> [--selector <css>] [--tab <id>]")
}
- var files []string
+ var files, fileNames []string
for _, path := range args {
data, err := os.ReadFile(path)
if err != nil {
cli.Fatal("Failed to read %s: %v", path, err)
}
files = append(files, base64.StdEncoding.EncodeToString(data))
+ // The page reads file.name from the name the server stages under, so the
+ // name the user typed has to travel with the bytes. Without it every
+ // upload arrives as upload-<i>.bin and any form gating on the extension
+ // rejects it — and the CLI is holding the real name right here.
+ fileNames = append(fileNames, filepath.Base(path))
}
body := map[string]any{
- "files": files,
+ "files": files,
+ "fileNames": fileNames,
}
if selector != "" {
body["selector"] = selector
diff --git a/internal/cli/actions/actions_upload_test.go b/internal/cli/actions/actions_upload_test.go
index b02e0fa5..513e6aae 100644
--- a/internal/cli/actions/actions_upload_test.go
+++ b/internal/cli/actions/actions_upload_test.go
@@ -1,8 +1,11 @@
package actions
import (
+ "encoding/json"
"os"
"path/filepath"
+ "reflect"
+ "strings"
"testing"
)
@@ -41,3 +44,75 @@ func TestUploadTabScopedPath(t *testing.T) {
t.Fatalf("expected /tabs/tab1/upload, got %s", m.lastPath)
}
}
+
+// The CLI is the only place that still holds the name the user typed — the
+// server receives bytes. Sending filepath.Base is what lets the page see
+// data.csv instead of upload-0.bin, so it is asserted on the wire.
+func TestUploadSendsTheBasenameOfEachFile(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+
+ dir := t.TempDir()
+ first := filepath.Join(dir, "quarterly report.csv")
+ second := filepath.Join(dir, "notes.md")
+ for _, f := range []string{first, second} {
+ if err := os.WriteFile(f, []byte("x"), 0600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ }
+
+ captureStdout(t, func() {
+ Upload(m.server.Client(), m.base(), "", []string{first, second}, "#file", "")
+ })
+
+ var body struct {
+ Files []string `json:"files"`
+ FileNames []string `json:"fileNames"`
+ }
+ if err := json.Unmarshal([]byte(m.lastBody), &body); err != nil {
+ t.Fatalf("decode body: %v (%s)", err, m.lastBody)
+ }
+ want := []string{"quarterly report.csv", "notes.md"}
+ if !reflect.DeepEqual(body.FileNames, want) {
+ t.Errorf("fileNames = %v, want %v", body.FileNames, want)
+ }
+ // Index alignment is the contract the server reads them by, so the two
+ // arrays have to stay the same length.
+ if len(body.Files) != len(body.FileNames) {
+ t.Errorf("files=%d fileNames=%d; the server pairs them by index", len(body.Files), len(body.FileNames))
+ }
+}
+
+// Only the basename travels: the directory the file came from is the caller's
+// filesystem layout, which the page has no business seeing and which would make
+// the name a path the server then has to defend against.
+func TestUploadSendsNoDirectoryComponent(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+
+ nested := filepath.Join(t.TempDir(), "sub", "dir")
+ if err := os.MkdirAll(nested, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ f := filepath.Join(nested, "doc.txt")
+ if err := os.WriteFile(f, []byte("hello"), 0600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+
+ captureStdout(t, func() {
+ Upload(m.server.Client(), m.base(), "", []string{f}, "#file", "")
+ })
+
+ var body struct {
+ FileNames []string `json:"fileNames"`
+ }
+ if err := json.Unmarshal([]byte(m.lastBody), &body); err != nil {
+ t.Fatalf("decode body: %v (%s)", err, m.lastBody)
+ }
+ if len(body.FileNames) != 1 || body.FileNames[0] != "doc.txt" {
+ t.Fatalf("fileNames = %v, want [doc.txt]", body.FileNames)
+ }
+ if strings.ContainsRune(body.FileNames[0], filepath.Separator) {
+ t.Errorf("fileNames[0] = %q carries a directory component", body.FileNames[0])
+ }
+}
diff --git a/internal/handlers/upload.go b/internal/handlers/upload.go
index 03463743..020f4e66 100644
--- a/internal/handlers/upload.go
+++ b/internal/handlers/upload.go
@@ -8,6 +8,7 @@ import (
"net/http"
"os"
"path/filepath"
+ "strconv"
"strings"
"time"
@@ -19,7 +20,12 @@ import (
type uploadRequest struct {
Selector string `json:"selector"`
Files []string `json:"files"`
- Paths []string `json:"paths"`
+ // FileNames names the entries of Files by index, so a page sees the file
+ // the caller actually sent rather than a synthetic one. Optional and
+ // index-aligned: a short or absent list leaves the remaining files on the
+ // content-sniffed name, which is all a caller posting bare blobs can offer.
+ FileNames []string `json:"fileNames"`
+ Paths []string `json:"paths"`
}
const (
@@ -54,6 +60,7 @@ var (
// {
// "selector": "input[type=file]", // unified selector: CSS, XPath, text, ref, or semantic
// "files": ["data:image/png;base64,...", "base64:..."],
+// "fileNames": ["chart.png", "data.csv"],
// "paths": ["uploads/photo.jpg"]
// }
//
@@ -61,6 +68,13 @@ var (
// provided. Both can be combined. Files are written to a temp dir and passed to
// CDP. Path-based uploads are limited to StateDir/uploads/. Successful base64
// staging dirs are retained briefly for lazy browser reads, then cleaned.
+//
+// "fileNames" is index-aligned with "files" and decides the name the page sees.
+// A supplied name wins over the content sniff even when the two disagree,
+// because that is what a browser does: it sends the user's filename and leaves
+// the receiving page to decide whether to trust it. Without a name the extension
+// is sniffed from content, which is all a bare blob can support — and sniffing is
+// blind to exactly the text formats forms validate by extension.
func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowUpload {
h.writeCapabilityDisabled(w, routes.CapUpload)
@@ -159,7 +173,11 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
httpx.Error(w, 400, fmt.Errorf("upload payload too large: max %d bytes total", maxTotalBytes))
return
}
- path := fmt.Sprintf("%s/upload-%d%s", stagedDir, i, ext)
+ path, err := stageUploadPath(stagedDir, i, uploadFileName(req.FileNames, i), ext)
+ if err != nil {
+ httpx.Error(w, 400, fmt.Errorf("file[%d]: %w", i, err))
+ return
+ }
if err := os.WriteFile(path, data, 0600); err != nil {
httpx.Error(w, 500, fmt.Errorf("write staged file: %w", err))
return
@@ -225,6 +243,63 @@ func (h *Handlers) HandleTabUpload(w http.ResponseWriter, r *http.Request) {
h.withPathTabID(w, r, h.HandleUpload)
}
+// uploadFileName returns the caller-supplied name for file i, or "" when none
+// was sent. Names are index-aligned with files and the list may be shorter.
+func uploadFileName(names []string, i int) string {
+ if i < 0 || i >= len(names) {
+ return ""
+ }
+ return strings.TrimSpace(names[i])
+}
+
+// stagedUploadName reduces a caller-supplied name to the single filesystem
+// element it will be staged as, falling back to the generated upload-<i><ext>
+// when the caller sent nothing usable.
+//
+// Containment is a property of the RETURN VALUE rather than a second check after
+// the fact: the result is always one path element — never empty, never "." or
+// "..", never carrying a separator — so joining it under a directory cannot
+// leave that directory. A re-resolution after this would be unreachable by
+// construction, and an unreachable guard is one no test can hold to account.
+//
+// Reducing rather than refusing is what a browser does: it sends the basename of
+// whatever the user picked and never the directory above it.
+func stagedUploadName(name string, i int, ext string) string {
+ generated := fmt.Sprintf("upload-%d%s", i, ext)
+
+ // filepath.Base already guarantees the result carries no separator, so the
+ // only rejections left are the values Base returns that are not usable
+ // filenames: the empty input, the two relative markers, the root itself, and
+ // a NUL, which Base passes through and the filesystem then refuses.
+ base := filepath.Base(filepath.FromSlash(strings.TrimSpace(name)))
+ switch {
+ case strings.TrimSpace(name) == "",
+ base == ".", base == "..",
+ base == string(filepath.Separator),
+ strings.ContainsRune(base, 0):
+ return generated
+ }
+ return base
+}
+
+// stageUploadPath returns the path to write file i to, under its own numbered
+// subdirectory of stagedDir.
+//
+// The subdirectory is what keeps the caller's real basename usable: a page reads
+// file.name from the basename of the path CDP was handed, so the presented name
+// and the on-disk name are the same string by construction, and two files sent in
+// one request under the same name (a/data.csv and b/data.csv) would otherwise
+// resolve to one path that os.WriteFile truncates — losing a file silently. The
+// index used to live in the filename and provided that uniqueness; moving it to
+// the directory keeps it while freeing the name.
+func stageUploadPath(stagedDir string, i int, name, ext string) (string, error) {
+ fileDir := filepath.Join(stagedDir, strconv.Itoa(i))
+ if err := os.MkdirAll(fileDir, 0o700); err != nil {
+ return "", fmt.Errorf("create staged dir: %w", err)
+ }
+ return filepath.Join(fileDir, stagedUploadName(name, i, ext)), nil
+}
+
func validateUploadSandboxPath(baseDir, rawPath string, maxFileBytes int) (string, int64, error) {
normalized := normalizeUploadSandboxPath(rawPath)
safe, err := httpx.SafeExistingPath(baseDir, normalized)
diff --git a/internal/handlers/upload_test.go b/internal/handlers/upload_test.go
index 0331e3c0..25626e62 100644
--- a/internal/handlers/upload_test.go
+++ b/internal/handlers/upload_test.go
@@ -500,3 +500,220 @@ func TestNewCleansStaleUploadStagingDirs(t *testing.T) {
t.Fatalf("non-staged upload sandbox dir should be kept: %v", err)
}
}
+
+// stagedNames runs one upload and returns the basenames CDP was handed, which is
+// exactly what the page reads file.name from.
+func stagedNames(t *testing.T, body string) []string {
+ t.Helper()
+
+ rec := &recordingUploadBridge{}
+ h := New(rec, &config.RuntimeConfig{AllowUpload: true, StateDir: t.TempDir(), ActionTimeout: time.Second}, nil, nil, nil)
+
+ req := httptest.NewRequest("POST", "/upload", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+
+ names := make([]string, 0, len(rec.attachedPaths))
+ for _, p := range rec.attachedPaths {
+ names = append(names, filepath.Base(p))
+ }
+ return names
+}
+
+// The defect: every file reached the page as upload-<i>.bin, so a form gating on
+// `accept=".csv"` rejected it. The staged basename IS the page-visible
+// file.name (asserted against a real browser in
+// internal/bridge/upload_filename_test.go), so this is that name.
+func TestHandleUpload_KeepsTheSuppliedFileName(t *testing.T) {
+ names := stagedNames(t, `{"files":["aGVsbG8="],"fileNames":["data.csv"]}`)
+
+ if len(names) != 1 || names[0] != "data.csv" {
+ t.Fatalf("page would see %v, want [data.csv]", names)
+ }
+}
+
+// Text formats are the ones upload forms validate by extension and the ones
+// content sniffing can never identify — no magic bytes exist for .csv, .json or
+// .txt. A supplied name is the only way they can arrive correctly named.
+func TestHandleUpload_NamesSniffingCannotProduce(t *testing.T) {
+ for _, name := range []string{"notes.txt", "export.json", "sheet.csv", "page.html", "readme.md"} {
+ got := stagedNames(t, fmt.Sprintf(`{"files":["aGVsbG8="],"fileNames":[%q]}`, name))
+ if len(got) != 1 || got[0] != name {
+ t.Errorf("page would see %v, want [%s]", got, name)
+ }
+ }
+}
+
+// Unchanged behaviour for a caller posting a bare blob: no name, so the
+// extension is sniffed from content and the generated basename stands.
+func TestHandleUpload_FallsBackToSniffedNameWithoutASuppliedName(t *testing.T) {
+ png := base64.StdEncoding.EncodeToString([]byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a})
+
+ for _, tc := range []struct{ name, body, want string }{
+ {"no fileNames at all", `{"files":["` + png + `"]}`, "upload-0.png"},
+ {"empty name", `{"files":["` + png + `"],"fileNames":[""]}`, "upload-0.png"},
+ {"unrecognised content", `{"files":["aGVsbG8="]}`, "upload-0.bin"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got := stagedNames(t, tc.body)
+ if len(got) != 1 || got[0] != tc.want {
+ t.Fatalf("staged %v, want [%s]", got, tc.want)
+ }
+ })
+ }
+}
+
+// A shorter fileNames list must not shift names onto the wrong files or drop the
+// remaining uploads: the unnamed tail falls back to sniffing, index by index.
+func TestHandleUpload_ShortFileNamesListNamesOnlyItsOwnFiles(t *testing.T) {
+ names := stagedNames(t, `{"files":["aGVsbG8=","aGVsbG8=","aGVsbG8="],"fileNames":["first.csv"]}`)
+
+ want := []string{"first.csv", "upload-1.bin", "upload-2.bin"}
+ if len(names) != len(want) {
+ t.Fatalf("staged %v, want %v", names, want)
+ }
+ for i := range want {
+ if names[i] != want[i] {
+ t.Errorf("file %d staged as %q, want %q", i, names[i], want[i])
+ }
+ }
+}
+
+// The case that could not break before the index moved out of the filename: two
+// files sent under ONE name in one request. Both must reach the page under that
+// name — a de-duplicating rename would corrupt the very thing this fixes, and a
+// shared path would let os.WriteFile truncate the first file away.
+func TestHandleUpload_DuplicateNamesInOneRequestStayDistinctFiles(t *testing.T) {
+ rec := &recordingUploadBridge{}
+ h := New(rec, &config.RuntimeConfig{AllowUpload: true, StateDir: t.TempDir(), ActionTimeout: time.Second}, nil, nil, nil)
+
+ first := base64.StdEncoding.EncodeToString([]byte("first file"))
+ second := base64.StdEncoding.EncodeToString([]byte("second file, longer"))
+ body := fmt.Sprintf(`{"files":[%q,%q],"fileNames":["data.csv","data.csv"]}`, first, second)
+
+ req := httptest.NewRequest("POST", "/upload", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+
+ if len(rec.attachedPaths) != 2 {
+ t.Fatalf("attached %d paths, want 2 — a shared path silently loses a file", len(rec.attachedPaths))
+ }
+ if rec.attachedPaths[0] == rec.attachedPaths[1] {
+ t.Fatalf("both files staged at %q; the second truncated the first", rec.attachedPaths[0])
+ }
+ for i, p := range rec.attachedPaths {
+ if got := filepath.Base(p); got != "data.csv" {
+ t.Errorf("file %d staged as %q, want data.csv — a de-duplicating rename defeats the fix", i, got)
+ }
+ }
+ // Distinct paths are only worth anything if the CONTENT survived separately.
+ firstBytes, err := os.ReadFile(rec.attachedPaths[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ secondBytes, err := os.ReadFile(rec.attachedPaths[1])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(firstBytes) != "first file" || string(secondBytes) != "second file, longer" {
+ t.Errorf("staged contents = %q / %q, want the two distinct payloads", firstBytes, secondBytes)
+ }
+}
+
+// Containment as a property of the staged NAME, asserted precisely rather than
+// tolerantly: each traversal attempt must land on a named result inside the
+// per-file directory. An earlier version of this test accepted "or the request
+// is refused", which made it blind to whether the reduction happened at all.
+// This surface did not exist before a caller-supplied string became part of a
+// filesystem path.
+func TestHandleUpload_SuppliedNameCannotEscapeTheStagingDirectory(t *testing.T) {
+ for _, tc := range []struct{ name, want string }{
+ {"../escape.txt", "escape.txt"},
+ {"../../../../etc/passwd", "passwd"},
+ {"sub/dir/nested.txt", "nested.txt"},
+ {"/etc/passwd", "passwd"},
+ {"..", "upload-0.bin"},
+ {".", "upload-0.bin"},
+ {"/", "upload-0.bin"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := &recordingUploadBridge{}
+ stateDir := t.TempDir()
+ h := New(rec, &config.RuntimeConfig{AllowUpload: true, StateDir: stateDir, ActionTimeout: time.Second}, nil, nil, nil)
+
+ body := fmt.Sprintf(`{"files":["aGVsbG8="],"fileNames":[%q]}`, tc.name)
+ req := httptest.NewRequest("POST", "/upload", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 — a browser reduces such a name rather than refusing: %s", w.Code, w.Body.String())
+ }
+ if len(rec.attachedPaths) != 1 {
+ t.Fatalf("attached %v, want exactly one staged file", rec.attachedPaths)
+ }
+ if got := filepath.Base(rec.attachedPaths[0]); got != tc.want {
+ t.Errorf("staged as %q, want %q", got, tc.want)
+ }
+
+ staged, err := filepath.EvalSymlinks(rec.attachedPaths[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ root, err := filepath.EvalSymlinks(filepath.Join(stateDir, uploadSandboxDirName))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.HasPrefix(staged, root+string(filepath.Separator)) {
+ t.Fatalf("staged %q escaped the upload root %q", staged, root)
+ }
+ })
+ }
+}
+
+// The reduction rule, driven directly, so every branch has a named case — the
+// handler test above can only reach the ones an upload can carry.
+func TestStagedUploadNameIsAlwaysOneSafeElement(t *testing.T) {
+ for _, tc := range []struct{ name, want string }{
+ {"data.csv", "data.csv"},
+ {" spaced.csv ", "spaced.csv"},
+ {"../escape.txt", "escape.txt"},
+ {"a/b/c.json", "c.json"},
+ {"", "upload-3.bin"},
+ {" ", "upload-3.bin"},
+ {".", "upload-3.bin"},
+ {"..", "upload-3.bin"},
+ {"/", "upload-3.bin"},
+ {"with\x00null", "upload-3.bin"},
+ } {
+ got := stagedUploadName(tc.name, 3, ".bin")
+ if got != tc.want {
+ t.Errorf("stagedUploadName(%q) = %q, want %q", tc.name, got, tc.want)
+ }
+ if got == "" || got == "." || got == ".." || strings.ContainsRune(got, filepath.Separator) || strings.ContainsRune(got, '/') {
+ t.Errorf("stagedUploadName(%q) = %q, which is not a single safe path element", tc.name, got)
+ }
+ }
+}
+
+// Precedence: a name wins over the sniffed content type even when the two
+// disagree. A browser sends the user's filename regardless of content and lets
+// the receiving page decide whether to trust it; a consistency check here would
+// diverge from that and break legitimate mislabelled-but-intended uploads.
+func TestHandleUpload_SuppliedNameWinsOverSniffedContent(t *testing.T) {
+ png := base64.StdEncoding.EncodeToString([]byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a})
+
+ names := stagedNames(t, fmt.Sprintf(`{"files":[%q],"fileNames":["actually-a-png.csv"]}`, png))
+ if len(names) != 1 || names[0] != "actually-a-png.csv" {
+ t.Fatalf("staged %v, want [actually-a-png.csv]", names)
+ }
+}
diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.md
index 895e2466..168f1622 100644
--- a/skills/pinchtab/references/api.md
+++ b/skills/pinchtab/references/api.md
@@ -330,11 +330,13 @@ curl -X POST "/upload?tabId=TAB_ID" -H "Content-Type: application/json" \
# Upload base64-encoded data
curl -X POST /upload -H "Content-Type: application/json" \
- -d '{"selector": "#avatar-input", "files": ["data:image/png;base64,iVBOR..."]}'
+ -d '{"selector": "#avatar-input", "files": ["data:image/png;base64,iVBOR..."], "fileNames": ["avatar.png"]}'
```
Sets files on `<input type=file>` elements via CDP. Fires `change` events. Selector defaults to `input[type=file]` if omitted.
+`fileNames` is index-aligned with `files` and is the name the page reads from `file.name`. Send it whenever you know the filename: without it a file arrives as `upload-<i>.bin`, and forms that gate on the extension (`accept=".csv"`, `file.name.endsWith(".pdf")`) reject it. Content sniffing fills the gap only for formats with magic bytes — png, jpeg, gif, webp, pdf — never for csv, json, txt, md or html. The CLI sends it automatically.
+
## Screenshot
```bash