Skip to content

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

refactor: route upload through the provider runtime abstraction

Luigi Agostid23906322435
diff --git a/internal/handlers/upload.go b/internal/handlers/upload.go
index 751128aa..eaaef432 100644
--- a/internal/handlers/upload.go
+++ b/internal/handlers/upload.go
@@ -11,10 +11,6 @@ import (
"strings"
"time"
- "github.com/chromedp/cdproto/cdp"
- "github.com/chromedp/cdproto/dom"
- "github.com/chromedp/cdproto/runtime"
- "github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/httpx"
)
@@ -36,18 +32,6 @@ const (
)
var (
- setUploadFileInputFiles = func(ctx context.Context, selector string, paths []string) error {
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- nodeID, err := resolveSelector(ctx, selector)
- if err != nil {
- return fmt.Errorf("selector %q: %w", selector, err)
- }
- return dom.SetFileInputFiles(paths).WithNodeID(nodeID).Do(ctx)
- }),
- )
- }
-
cleanupStagedUploadDirAfter = func(dir string, after time.Duration) {
if dir == "" {
return
@@ -205,7 +189,13 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
defer tCancel()
go httpx.CancelOnClientDone(r.Context(), tCancel)
- if err := setUploadFileInputFiles(tCtx, req.Selector, allPaths); err != nil {
+ nodeID, err := h.Bridge.ResolveSelectorToNodeID(tCtx, req.Selector)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("upload: selector %q: %w", req.Selector, err))
+ return
+ }
+
+ if err := h.Bridge.SetFileInputFiles(tCtx, nodeID, allPaths); err != nil {
httpx.Error(w, 500, fmt.Errorf("upload: %w", err))
return
}
@@ -246,42 +236,6 @@ func (h *Handlers) HandleTabUpload(w http.ResponseWriter, r *http.Request) {
h.HandleUpload(w, req)
}
-// resolveSelector finds a DOM node by a unified selector string and returns its NodeID.
-// Supports CSS (default), XPath (xpath: prefix or // auto-detect), and text (text: prefix).
-func resolveSelector(ctx context.Context, sel string) (cdp.NodeID, error) {
- // Determine the JavaScript expression based on selector type.
- var expr string
- switch {
- case strings.HasPrefix(sel, "xpath:"):
- xpath := sel[len("xpath:"):]
- expr = fmt.Sprintf(`(function(){var r=document.evaluate(%q,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);return r.singleNodeValue})()`, xpath)
- case strings.HasPrefix(sel, "//") || strings.HasPrefix(sel, "(//"):
- expr = fmt.Sprintf(`(function(){var r=document.evaluate(%q,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);return r.singleNodeValue})()`, sel)
- case strings.HasPrefix(sel, "text:"):
- text := sel[len("text:"):]
- expr = fmt.Sprintf(`(function(){var w=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);while(w.nextNode()){if(w.currentNode.textContent.includes(%q))return w.currentNode.parentElement}return null})()`, text)
- case strings.HasPrefix(sel, "css:"):
- css := sel[len("css:"):]
- expr = fmt.Sprintf(`document.querySelector(%q)`, css)
- default:
- // Bare selector: treat as CSS (backward compatible).
- expr = fmt.Sprintf(`document.querySelector(%q)`, sel)
- }
-
- val, _, err := runtime.Evaluate(expr).Do(ctx)
- if err != nil {
- return 0, fmt.Errorf("evaluate: %w", err)
- }
- if val.ObjectID == "" {
- return 0, fmt.Errorf("no element matches selector")
- }
- node, err := dom.RequestNode(val.ObjectID).Do(ctx)
- if err != nil {
- return 0, fmt.Errorf("request node: %w", err)
- }
- return node, 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 589f486d..7bc5216a 100644
--- a/internal/handlers/upload_test.go
+++ b/internal/handlers/upload_test.go
@@ -26,6 +26,29 @@ func (m *uploadLockBridge) TabLockInfo(tabID string) *bridge.LockInfo {
return m.lock
}
+type recordingUploadBridge struct {
+ mockBridge
+ selector string
+ nodeID int64
+ attachedPaths []string
+}
+
+func (m *recordingUploadBridge) ResolveSelectorToNodeID(_ context.Context, selector string) (int64, error) {
+ m.selector = selector
+ return 42, nil
+}
+
+func (m *recordingUploadBridge) SetFileInputFiles(_ context.Context, nodeID int64, paths []string) error {
+ m.nodeID = nodeID
+ m.attachedPaths = append([]string(nil), paths...)
+ for _, path := range m.attachedPaths {
+ if _, err := os.Stat(path); err != nil {
+ return fmt.Errorf("staged file was not readable before attach: %w", err)
+ }
+ }
+ return nil
+}
+
func TestHandleUpload_BadJSON(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{AllowUpload: true}, nil, nil, nil)
req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte("not json")))
@@ -366,27 +389,11 @@ func TestHandleUpload_StagedFilesCleanedOnFailureNotCWD(t *testing.T) {
}
func TestHandleUpload_SuccessSchedulesStagedCleanup(t *testing.T) {
- origSetUploadFileInputFiles := setUploadFileInputFiles
origCleanupStagedUploadDirAfter := cleanupStagedUploadDirAfter
t.Cleanup(func() {
- setUploadFileInputFiles = origSetUploadFileInputFiles
cleanupStagedUploadDirAfter = origCleanupStagedUploadDirAfter
})
- var attachedPaths []string
- setUploadFileInputFiles = func(_ context.Context, selector string, paths []string) error {
- if selector != "input[type=file]" {
- t.Fatalf("selector = %q, want default file input", selector)
- }
- attachedPaths = append([]string(nil), paths...)
- for _, path := range attachedPaths {
- if _, err := os.Stat(path); err != nil {
- t.Fatalf("staged file was not readable before attach: %v", err)
- }
- }
- return nil
- }
-
var cleanupDir string
var cleanupAfter time.Duration
cleanupStagedUploadDirAfter = func(dir string, after time.Duration) {
@@ -396,7 +403,8 @@ func TestHandleUpload_SuccessSchedulesStagedCleanup(t *testing.T) {
}
tmpDir := t.TempDir()
- h := New(&mockBridge{}, &config.RuntimeConfig{AllowUpload: true, StateDir: tmpDir}, nil, nil, nil)
+ uploadBridge := &recordingUploadBridge{}
+ h := New(uploadBridge, &config.RuntimeConfig{AllowUpload: true, StateDir: tmpDir}, nil, nil, nil)
req := httptest.NewRequest("POST", "/upload?tabId=t1", bytes.NewReader([]byte(`{"files":["aGVsbG8="]}`)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
@@ -405,8 +413,14 @@ func TestHandleUpload_SuccessSchedulesStagedCleanup(t *testing.T) {
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
- if len(attachedPaths) != 1 {
- t.Fatalf("attached paths = %d, want 1", len(attachedPaths))
+ if uploadBridge.selector != "input[type=file]" {
+ t.Fatalf("selector = %q, want default file input", uploadBridge.selector)
+ }
+ if uploadBridge.nodeID != 42 {
+ t.Fatalf("nodeID = %d, want 42", uploadBridge.nodeID)
+ }
+ if len(uploadBridge.attachedPaths) != 1 {
+ t.Fatalf("attached paths = %d, want 1", len(uploadBridge.attachedPaths))
}
if cleanupDir == "" {
t.Fatal("successful upload did not schedule staged cleanup")