Skip to content

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

feat(runtime): hardening, tab leases, macros, and metrics (#83)

luigiagentcd7cf3afab88
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
index 0d038f16..e50630ab 100644
--- a/internal/bridge/bridge.go
+++ b/internal/bridge/bridge.go
@@ -196,4 +196,5 @@ type ActionRequest struct {
ScrollY int `json:"scrollY"`
WaitNav bool `json:"waitNav"`
Fast bool `json:"fast"`
+ Owner string `json:"owner"`
}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 60a0ad1e..98fbc089 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -7,66 +7,43 @@ import (
"fmt"
"io"
"net/http"
+ "strconv"
+ "strings"
"time"
+ "github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/web"
)
+func resolveOwner(r *http.Request, fallback string) string {
+ if o := strings.TrimSpace(r.Header.Get("X-Owner")); o != "" {
+ return o
+ }
+ if o := strings.TrimSpace(r.URL.Query().Get("owner")); o != "" {
+ return o
+ }
+ return strings.TrimSpace(fallback)
+}
+
+func (h *Handlers) enforceTabLease(tabID, owner string) error {
+ if tabID == "" {
+ return nil
+ }
+ lock := h.Bridge.TabLockInfo(tabID)
+ if lock == nil {
+ return nil
+ }
+ if owner == "" {
+ return fmt.Errorf("tab %s is locked by %s; owner required", tabID, lock.Owner)
+ }
+ if owner != lock.Owner {
+ return fmt.Errorf("tab %s is locked by %s", tabID, lock.Owner)
+ }
+ return nil
+}
+
// HandleAction performs a single action on a tab (click, type, fill, etc).
-//
-// @Endpoint POST /action
-// @Description Interact with page elements: click, type text, fill inputs, press keys, hover, focus, scroll, select
-//
-// @Param tabId string body Tab ID (required)
-// @Param kind string body Action type: "click", "type", "fill", "press", "hover", "focus", "scroll", "select" (required)
-// @Param ref string body Element reference from snapshot (e.g., "e5") (required)
-// @Param text string body Text to type or fill (for "type"/"fill" actions)
-// @Param value string body Value for "select" action (e.g., option index)
-// @Param key string body Key to press (for "press" action, e.g., "Enter", "Tab")
-// @Param x int body X coordinate for "scroll" action (optional)
-// @Param y int body Y coordinate for "scroll" action (optional)
-//
-// @Response 200 application/json Returns {success: true}
-// @Response 400 application/json Invalid action or parameters
-// @Response 404 application/json Tab or element not found
-// @Response 500 application/json Chrome error
-//
-// @Example curl click:
-//
-// curl -X POST http://localhost:9867/action \
-// -H "Content-Type: application/json" \
-// -d '{"tabId":"abc123","kind":"click","ref":"e5"}'
-//
-// @Example curl type:
-//
-// curl -X POST http://localhost:9867/action \
-// -H "Content-Type: application/json" \
-// -d '{"tabId":"abc123","kind":"type","ref":"e3","text":"[email protected]"}'
-//
-// @Example curl fill form:
-//
-// curl -X POST http://localhost:9867/action \
-// -H "Content-Type: application/json" \
-// -d '{"tabId":"abc123","kind":"fill","ref":"e3","text":"John Doe"}'
-//
-// @Example curl press key:
-//
-// curl -X POST http://localhost:9867/action \
-// -H "Content-Type: application/json" \
-// -d '{"tabId":"abc123","kind":"press","ref":"e7","key":"Enter"}'
-//
-// @Example cli click:
-//
-// pinchtab click e5
-//
-// @Example cli type:
-//
-// pinchtab type e3 "[email protected]"
-//
-// @Example cli fill:
-//
-// pinchtab fill e3 "John Doe"
func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
// Ensure Chrome is initialized
if err := h.ensureChrome(); err != nil {
@@ -75,9 +52,26 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
}
var req bridge.ActionRequest
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
- return
+ if r.Method == http.MethodGet {
+ q := r.URL.Query()
+ req.Kind = q.Get("kind")
+ req.TabID = q.Get("tabId")
+ req.Owner = q.Get("owner")
+ req.Ref = q.Get("ref")
+ req.Selector = q.Get("selector")
+ req.Text = q.Get("text")
+ req.Value = q.Get("value")
+ req.Key = q.Get("key")
+ if v := q.Get("nodeId"); v != "" {
+ if n, err := strconv.ParseInt(v, 10, 64); err == nil {
+ req.NodeID = n
+ }
+ }
+ } else {
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
}
// Validate kind — single endpoint returns 400 for bad input (unlike batch which returns 200 with errors)
@@ -108,6 +102,27 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
if req.TabID == "" {
req.TabID = resolvedTabID
}
+ owner := resolveOwner(r, req.Owner)
+ if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
+ web.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
+ return
+ }
+
+ // Allow custom timeout via query param (1-60 seconds)
+ actionTimeout := h.Config.ActionTimeout
+ if r.Method == http.MethodGet {
+ if v := r.URL.Query().Get("timeout"); v != "" {
+ if n, err := strconv.ParseFloat(v, 64); err == nil {
+ if n > 0 && n <= 60 {
+ actionTimeout = time.Duration(n * float64(time.Second))
+ }
+ }
+ }
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
// Resolve ref → nodeID
if req.Ref != "" && req.NodeID == 0 && req.Selector == "" {
@@ -123,12 +138,26 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
}
}
- tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
- defer tCancel()
-
result, err := h.Bridge.ExecuteAction(tCtx, req.Kind, req)
+ if err != nil && req.Ref != "" && shouldRetryStaleRef(err) {
+ recordStaleRefRetry()
+ h.refreshRefCache(tCtx, resolvedTabID)
+ if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {
+ if nid, ok := cache.Refs[req.Ref]; ok {
+ req.NodeID = nid
+ result, err = h.Bridge.ExecuteAction(tCtx, req.Kind, req)
+ }
+ }
+ }
if err != nil {
- web.Error(w, 500, err)
+ if strings.HasPrefix(err.Error(), "unknown action") {
+ kinds := h.Bridge.AvailableActions()
+ web.JSON(w, 400, map[string]string{
+ "error": fmt.Sprintf("%s - valid values: %s", err.Error(), strings.Join(kinds, ", ")),
+ })
+ return
+ }
+ web.ErrorCode(w, 500, "action_failed", fmt.Sprintf("action %s: %v", req.Kind, err), true, nil)
return
}
@@ -172,6 +201,7 @@ func (h *Handlers) HandleTabAction(w http.ResponseWriter, r *http.Request) {
type actionsRequest struct {
TabID string `json:"tabId"`
+ Owner string `json:"owner"`
Actions []bridge.ActionRequest `json:"actions"`
StopOnError bool `json:"stopOnError"`
}
@@ -247,6 +277,11 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
web.Error(w, 404, err)
return
}
+ owner := resolveOwner(r, req.Owner)
+ if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
+ web.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
+ return
+ }
results := make([]actionResult, 0, len(req.Actions))
@@ -265,6 +300,13 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
}
continue
}
+ if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
+ results = append(results, actionResult{Index: i, Success: false, Error: err.Error()})
+ if req.StopOnError {
+ break
+ }
+ continue
+ }
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
@@ -301,6 +343,16 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
}
actionRes, err := h.Bridge.ExecuteAction(tCtx, action.Kind, action)
+ if err != nil && action.Ref != "" && shouldRetryStaleRef(err) {
+ recordStaleRefRetry()
+ h.refreshRefCache(tCtx, resolvedTabID)
+ if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {
+ if nid, ok := cache.Refs[action.Ref]; ok {
+ action.NodeID = nid
+ actionRes, err = h.Bridge.ExecuteAction(tCtx, action.Kind, action)
+ }
+ }
+ }
tCancel()
if err != nil {
@@ -330,6 +382,75 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
})
}
+func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ TabID string `json:"tabId"`
+ Owner string `json:"owner"`
+ Steps []bridge.ActionRequest `json:"steps"`
+ StopOnError bool `json:"stopOnError"`
+ StepTimeout float64 `json:"stepTimeout"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.ErrorCode(w, 400, "bad_request", fmt.Sprintf("decode: %v", err), false, nil)
+ return
+ }
+ if len(req.Steps) == 0 {
+ web.ErrorCode(w, 400, "bad_request", "steps array is empty", false, nil)
+ return
+ }
+ owner := resolveOwner(r, req.Owner)
+ stepTimeout := h.Config.ActionTimeout
+ if req.StepTimeout > 0 && req.StepTimeout <= 60 {
+ stepTimeout = time.Duration(req.StepTimeout * float64(time.Second))
+ }
+
+ ctx, resolvedTabID, err := h.Bridge.TabContext(req.TabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+ if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
+ web.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
+ return
+ }
+
+ results := make([]actionResult, 0, len(req.Steps))
+ for i, step := range req.Steps {
+ if step.TabID == "" {
+ step.TabID = resolvedTabID
+ }
+ tCtx, cancel := context.WithTimeout(ctx, stepTimeout)
+ res, err := h.Bridge.ExecuteAction(tCtx, step.Kind, step)
+ if err != nil && step.Ref != "" && shouldRetryStaleRef(err) {
+ recordStaleRefRetry()
+ h.refreshRefCache(tCtx, resolvedTabID)
+ if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {
+ if nid, ok := cache.Refs[step.Ref]; ok {
+ step.NodeID = nid
+ res, err = h.Bridge.ExecuteAction(tCtx, step.Kind, step)
+ }
+ }
+ }
+ cancel()
+ if err != nil {
+ results = append(results, actionResult{Index: i, Success: false, Error: err.Error()})
+ if req.StopOnError {
+ break
+ }
+ continue
+ }
+ results = append(results, actionResult{Index: i, Success: true, Result: res})
+ }
+
+ web.JSON(w, 200, map[string]any{
+ "kind": "macro",
+ "results": results,
+ "total": len(req.Steps),
+ "successful": countSuccessful(results),
+ "failed": len(req.Steps) - countSuccessful(results),
+ })
+}
+
func countSuccessful(results []actionResult) int {
count := 0
for _, r := range results {
@@ -339,3 +460,30 @@ func countSuccessful(results []actionResult) int {
}
return count
}
+
+func shouldRetryStaleRef(err error) bool {
+ if err == nil {
+ return false
+ }
+ e := strings.ToLower(err.Error())
+ return strings.Contains(e, "could not find node") || strings.Contains(e, "node with given id") || strings.Contains(e, "no node")
+}
+
+func (h *Handlers) refreshRefCache(ctx context.Context, tabID string) {
+ var rawResult json.RawMessage
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(c context.Context) error {
+ return chromedp.FromContext(c).Target.Execute(c, "Accessibility.getFullAXTree", nil, &rawResult)
+ }),
+ ); err != nil {
+ return
+ }
+ var treeResp struct {
+ Nodes []bridge.RawAXNode `json:"nodes"`
+ }
+ if err := json.Unmarshal(rawResult, &treeResp); err != nil {
+ return
+ }
+ flat, refs := bridge.BuildSnapshot(treeResp.Nodes, bridge.FilterInteractive, -1)
+ h.Bridge.SetRefCache(tabID, &bridge.RefCache{Refs: refs, Nodes: flat})
+}
diff --git a/internal/handlers/handler_actions_test.go b/internal/handlers/handler_actions_test.go
index 7fa478ee..afb114f6 100644
--- a/internal/handlers/handler_actions_test.go
+++ b/internal/handlers/handler_actions_test.go
@@ -237,6 +237,28 @@ func TestHandleFingerprintRotate_NoTab(t *testing.T) {
}
}
+func TestHandleAction_GetMissingKind(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/action?tabId=tab1", nil)
+ w := httptest.NewRecorder()
+
+ h.HandleAction(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400 for missing kind, got %d", w.Code)
+ }
+}
+
+func TestHandleMacro_EmptySteps(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/macro", bytes.NewReader([]byte(`{"tabId":"tab1","steps":[]}`)))
+ w := httptest.NewRecorder()
+ h.HandleMacro(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400 for empty macro steps, got %d", w.Code)
+ }
+}
+
func TestCountSuccessful(t *testing.T) {
results := []actionResult{
{Success: true},
diff --git a/internal/handlers/handler_test.go b/internal/handlers/handler_test.go
index 6510fb64..dc991c22 100644
--- a/internal/handlers/handler_test.go
+++ b/internal/handlers/handler_test.go
@@ -6,6 +6,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
"github.com/chromedp/cdproto/target"
@@ -63,9 +64,39 @@ func (m *mockBridge) DeleteRefCache(tabID string) {}
func (m *mockBridge) TabLockInfo(tabID string) *bridge.LockInfo { return nil }
func TestHandlers(t *testing.T) {
- h := New(&mockBridge{}, nil, nil, nil, nil)
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
mux := http.NewServeMux()
h.RegisterRoutes(mux, nil)
+
+ req := httptest.NewRequest("GET", "/help", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200 from /help, got %d", w.Code)
+ }
+ if !strings.Contains(w.Body.String(), "endpoints") {
+ t.Fatalf("expected /help response to include endpoints")
+ }
+
+ req = httptest.NewRequest("GET", "/openapi.json", nil)
+ w = httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200 from /openapi.json, got %d", w.Code)
+ }
+ if !strings.Contains(w.Body.String(), "openapi") {
+ t.Fatalf("expected /openapi.json response to include openapi")
+ }
+
+ req = httptest.NewRequest("GET", "/metrics", nil)
+ w = httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200 from /metrics, got %d", w.Code)
+ }
+ if !strings.Contains(w.Body.String(), "metrics") {
+ t.Fatalf("expected /metrics response to include metrics")
+ }
}
func TestHandleNavigate(t *testing.T) {
@@ -73,7 +104,7 @@ func TestHandleNavigate(t *testing.T) {
m := &mockBridge{}
h := New(m, cfg, nil, nil, nil)
- // 1. Valid request
+ // 1. Valid POST request
body := `{"url": "https://example.com"}`
req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
@@ -84,7 +115,15 @@ func TestHandleNavigate(t *testing.T) {
t.Errorf("unexpected status %d: %s", w.Code, w.Body.String())
}
- // 2. Missing URL
+ // 2. Valid GET request (ergonomic alias path style)
+ req = httptest.NewRequest("GET", "/nav?url=https%3A%2F%2Fexample.com", nil)
+ w = httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+ if w.Code != 200 && w.Code != 500 {
+ t.Errorf("unexpected status for GET navigate %d: %s", w.Code, w.Body.String())
+ }
+
+ // 3. Missing URL
req = httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`{}`)))
w = httptest.NewRecorder()
h.HandleNavigate(w, req)
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 0ba9c355..108b6200 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -47,14 +47,21 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("POST /tabs/{id}/actions", h.HandleTabActions)
mux.HandleFunc("GET /tabs/{id}/text", h.HandleTabText)
mux.HandleFunc("POST /tabs/{id}/evaluate", h.HandleTabEvaluate)
+ mux.HandleFunc("GET /metrics", h.HandleMetrics)
mux.HandleFunc("GET /snapshot", h.HandleSnapshot)
mux.HandleFunc("GET /screenshot", h.HandleScreenshot)
mux.HandleFunc("GET /tabs/{id}/pdf", h.HandleTabPDF)
mux.HandleFunc("POST /tabs/{id}/pdf", h.HandleTabPDF)
mux.HandleFunc("GET /text", h.HandleText)
+ mux.HandleFunc("GET /help", h.HandleHelp)
+ mux.HandleFunc("GET /openapi.json", h.HandleOpenAPI)
mux.HandleFunc("POST /navigate", h.HandleNavigate)
+ mux.HandleFunc("GET /navigate", h.HandleNavigate)
+ mux.HandleFunc("GET /nav", h.HandleNavigate)
mux.HandleFunc("POST /action", h.HandleAction)
+ mux.HandleFunc("GET /action", h.HandleAction)
mux.HandleFunc("POST /actions", h.HandleActions)
+ mux.HandleFunc("POST /macro", h.HandleMacro)
mux.HandleFunc("POST /evaluate", h.HandleEvaluate)
mux.HandleFunc("POST /tab", h.HandleTab)
mux.HandleFunc("POST /tab/lock", h.HandleTabLock)
diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.go
index 047aa7e3..92302685 100644
--- a/internal/handlers/health_tabs.go
+++ b/internal/handlers/health_tabs.go
@@ -38,6 +38,10 @@ func (h *Handlers) HandleEnsureChrome(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, map[string]string{"status": "chrome_ready"})
}
+func (h *Handlers) HandleMetrics(w http.ResponseWriter, r *http.Request) {
+ web.JSON(w, 200, map[string]any{"metrics": snapshotMetrics()})
+}
+
func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {
// Guard against nil Bridge
if h.Bridge == nil {
diff --git a/internal/handlers/help.go b/internal/handlers/help.go
new file mode 100644
index 00000000..80ba7392
--- /dev/null
+++ b/internal/handlers/help.go
@@ -0,0 +1,31 @@
+package handlers
+
+import (
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func (h *Handlers) HandleHelp(wr http.ResponseWriter, _ *http.Request) {
+ web.JSON(wr, 200, map[string]any{
+ "name": "pinchtab",
+ "endpoints": map[string]any{
+ "GET /health": "health status",
+ "GET /tabs": "list tabs",
+ "GET /metrics": "runtime metrics",
+ "GET /help": "this help payload",
+ "GET /openapi.json": "lightweight machine-readable API schema",
+ "GET /text": "extract page text (supports mode=raw,maxChars=<int>,format=text)",
+ "POST|GET /navigate": "navigate tab (JSON body or query params)",
+ "GET /nav": "alias for GET /navigate",
+ "POST|GET /action": "run a single action (JSON body or query params)",
+ "POST /actions": "run multiple actions",
+ "POST /macro": "run macro steps with single request",
+ "GET /snapshot": "accessibility snapshot",
+ },
+ "notes": []string{
+ "Use Authorization: Bearer <token> when auth is enabled.",
+ "Prefer /text with maxChars for token-efficient reads.",
+ },
+ })
+}
diff --git a/internal/handlers/media.go b/internal/handlers/media.go
index f712ab4f..98c00510 100644
--- a/internal/handlers/media.go
+++ b/internal/handlers/media.go
@@ -10,6 +10,7 @@ import (
"os"
"path/filepath"
"strconv"
+ "strings"
"time"
"github.com/chromedp/cdproto/page"
@@ -365,6 +366,13 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
mode := r.URL.Query().Get("mode")
+ format := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("format")))
+ maxChars := -1
+ if v := r.URL.Query().Get("maxChars"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ maxChars = n
+ }
+ }
ctx, _, err := h.Bridge.TabContext(tabID)
if err != nil {
@@ -393,16 +401,30 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
}
}
+ truncated := false
+ if maxChars > -1 && len(text) > maxChars {
+ text = text[:maxChars]
+ truncated = true
+ }
+
var url, title string
_ = chromedp.Run(tCtx,
chromedp.Location(&url),
chromedp.Title(&title),
)
+ if format == "text" || format == "plain" {
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.WriteHeader(200)
+ _, _ = w.Write([]byte(text))
+ return
+ }
+
web.JSON(w, 200, map[string]any{
- "url": url,
- "title": title,
- "text": text,
+ "url": url,
+ "title": title,
+ "text": text,
+ "truncated": truncated,
})
}
diff --git a/internal/handlers/metrics.go b/internal/handlers/metrics.go
new file mode 100644
index 00000000..046b312f
--- /dev/null
+++ b/internal/handlers/metrics.go
@@ -0,0 +1,24 @@
+package handlers
+
+import "sync/atomic"
+
+func recordStaleRefRetry() {
+ atomic.AddUint64(&metricStaleRefRetries, 1)
+}
+
+func snapshotMetrics() map[string]any {
+ total := atomic.LoadUint64(&metricRequestsTotal)
+ failed := atomic.LoadUint64(&metricRequestsFailed)
+ latencySum := atomic.LoadUint64(&metricRequestLatencyN)
+ avgMs := 0.0
+ if total > 0 {
+ avgMs = float64(latencySum) / float64(total)
+ }
+ return map[string]any{
+ "requestsTotal": total,
+ "requestsFailed": failed,
+ "avgLatencyMs": avgMs,
+ "rateLimited": atomic.LoadUint64(&metricRateLimited),
+ "staleRefRetries": atomic.LoadUint64(&metricStaleRefRetries),
+ }
+}
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index 4cb092aa..76f1bf73 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -1,26 +1,46 @@
package handlers
import (
+ "crypto/rand"
"crypto/subtle"
- "fmt"
+ "encoding/hex"
"log/slog"
+ "net"
"net/http"
+ "strings"
+ "sync"
+ "sync/atomic"
"time"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/web"
)
+var (
+ metricRequestsTotal uint64
+ metricRequestsFailed uint64
+ metricRequestLatencyN uint64
+ metricRateLimited uint64
+ metricStaleRefRetries uint64
+)
+
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &web.StatusWriter{ResponseWriter: w, Code: 200}
next.ServeHTTP(sw, r)
+ ms := uint64(time.Since(start).Milliseconds())
+ atomic.AddUint64(&metricRequestsTotal, 1)
+ atomic.AddUint64(&metricRequestLatencyN, ms)
+ if sw.Code >= 400 {
+ atomic.AddUint64(&metricRequestsFailed, 1)
+ }
slog.Info("request",
+ "requestId", w.Header().Get("X-Request-Id"),
"method", r.Method,
"path", r.URL.Path,
"status", sw.Code,
- "ms", time.Since(start).Milliseconds(),
+ "ms", ms,
)
})
}
@@ -29,9 +49,15 @@ func AuthMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if cfg.Token != "" {
auth := r.Header.Get("Authorization")
+ if auth == "" {
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)
+ web.ErrorCode(w, 401, "missing_token", "unauthorized", false, nil)
+ return
+ }
expected := "Bearer " + cfg.Token
if subtle.ConstantTimeCompare([]byte(auth), []byte(expected)) != 1 {
- web.Error(w, 401, fmt.Errorf("unauthorized"))
+ w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
+ web.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
return
}
}
@@ -51,3 +77,61 @@ func CorsMiddleware(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}
+
+func RequestIDMiddleware(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ rid := r.Header.Get("X-Request-Id")
+ if rid == "" {
+ b := make([]byte, 8)
+ _, _ = rand.Read(b)
+ rid = hex.EncodeToString(b)
+ }
+ w.Header().Set("X-Request-Id", rid)
+ next.ServeHTTP(w, r)
+ })
+}
+
+var (
+ rateMu sync.Mutex
+ rateBuckets = map[string][]time.Time{}
+)
+
+func RateLimitMiddleware(next http.Handler) http.Handler {
+ const window = 10 * time.Second
+ const maxReq = 120
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ p := strings.TrimSpace(r.URL.Path)
+ if p == "/health" || p == "/metrics" || strings.HasPrefix(p, "/health/") || strings.HasPrefix(p, "/metrics/") {
+ next.ServeHTTP(w, r)
+ return
+ }
+ host, _, _ := net.SplitHostPort(r.RemoteAddr)
+ if host == "" {
+ host = r.RemoteAddr
+ }
+ if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
+ host = strings.TrimSpace(strings.Split(xff, ",")[0])
+ }
+
+ now := time.Now()
+ rateMu.Lock()
+ hits := rateBuckets[host]
+ filtered := hits[:0]
+ for _, t := range hits {
+ if now.Sub(t) < window {
+ filtered = append(filtered, t)
+ }
+ }
+ if len(filtered) >= maxReq {
+ rateBuckets[host] = filtered
+ rateMu.Unlock()
+ atomic.AddUint64(&metricRateLimited, 1)
+ web.ErrorCode(w, 429, "rate_limited", "too many requests", true, map[string]any{"windowSec": int(window.Seconds()), "max": maxReq})
+ return
+ }
+ rateBuckets[host] = append(filtered, now)
+ rateMu.Unlock()
+
+ next.ServeHTTP(w, r)
+ })
+}
diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.go
index 9c729860..9cb54b1c 100644
--- a/internal/handlers/middleware_test.go
+++ b/internal/handlers/middleware_test.go
@@ -65,6 +65,28 @@ func TestAuthMiddleware_InvalidToken(t *testing.T) {
if w.Code != 401 {
t.Errorf("expected 401, got %d", w.Code)
}
+ if w.Header().Get("WWW-Authenticate") == "" {
+ t.Error("expected WWW-Authenticate header")
+ }
+}
+
+func TestAuthMiddleware_MissingTokenHeader(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("GET", "/test", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != 401 {
+ t.Errorf("expected 401, got %d", w.Code)
+ }
+ if w.Header().Get("WWW-Authenticate") == "" {
+ t.Error("expected WWW-Authenticate header")
+ }
}
func TestAuthMiddleware_TableDriven(t *testing.T) {
@@ -150,6 +172,46 @@ func TestLoggingMiddleware(t *testing.T) {
}
}
+func TestRequestIDMiddleware_SetsHeader(t *testing.T) {
+ handler := RequestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ }))
+ req := httptest.NewRequest("GET", "/test", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ if w.Header().Get("X-Request-Id") == "" {
+ t.Fatal("expected X-Request-Id")
+ }
+}
+
+func TestRateLimitMiddleware_AllowsRequest(t *testing.T) {
+ handler := RateLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ }))
+ req := httptest.NewRequest("GET", "/test", nil)
+ req.RemoteAddr = "127.0.0.1:12345"
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
+func TestRateLimitMiddleware_BypassHealthAndMetrics(t *testing.T) {
+ handler := RateLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ }))
+ for _, p := range []string{"/health", "/metrics"} {
+ req := httptest.NewRequest("GET", p, nil)
+ req.RemoteAddr = "127.0.0.1:12345"
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200 for %s, got %d", p, w.Code)
+ }
+ }
+}
+
func TestStatusWriter(t *testing.T) {
w := httptest.NewRecorder()
sw := &web.StatusWriter{ResponseWriter: w, Code: 200}
diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.go
index 237c3653..4a02e92d 100644
--- a/internal/handlers/navigation.go
+++ b/internal/handlers/navigation.go
@@ -9,6 +9,7 @@ import (
"io"
"net/http"
"net/url"
+ "strconv"
"strings"
"time"
@@ -57,19 +58,42 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
}
var req struct {
- TabID string `json:"tabId"`
- URL string `json:"url"`
- NewTab bool `json:"newTab"`
- WaitTitle float64 `json:"waitTitle"`
- Timeout float64 `json:"timeout"`
- BlockImages *bool `json:"blockImages"`
- BlockMedia *bool `json:"blockMedia"`
- BlockAds *bool `json:"blockAds"`
- }
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
- return
+ TabID string `json:"tabId"`
+ URL string `json:"url"`
+ NewTab bool `json:"newTab"`
+ WaitTitle float64 `json:"waitTitle"`
+ Timeout float64 `json:"timeout"`
+ BlockImages *bool `json:"blockImages"`
+ BlockMedia *bool `json:"blockMedia"`
+ BlockAds *bool `json:"blockAds"`
+ WaitFor string `json:"waitFor"`
+ WaitSelector string `json:"waitSelector"`
+ }
+
+ if r.Method == http.MethodGet {
+ q := r.URL.Query()
+ req.URL = q.Get("url")
+ req.TabID = q.Get("tabId")
+ req.NewTab = strings.EqualFold(q.Get("newTab"), "true") || q.Get("newTab") == "1"
+ req.WaitFor = q.Get("waitFor")
+ req.WaitSelector = q.Get("waitSelector")
+ if v := q.Get("waitTitle"); v != "" {
+ if n, err := strconv.ParseFloat(v, 64); err == nil {
+ req.WaitTitle = n
+ }
+ }
+ if v := q.Get("timeout"); v != "" {
+ if n, err := strconv.ParseFloat(v, 64); err == nil {
+ req.Timeout = n
+ }
+ }
+ } else {
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
}
+
if req.URL == "" {
web.Error(w, 400, fmt.Errorf("url required"))
return
@@ -159,6 +183,11 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
return
}
+ if err := h.waitForNavigationState(tCtx, req.WaitFor, req.WaitSelector); err != nil {
+ web.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)
+ return
+ }
+
var url string
_ = chromedp.Run(tCtx, chromedp.Location(&url))
title, _ := bridge.WaitForTitle(tCtx, titleWait)
@@ -196,6 +225,11 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
h.Bridge.DeleteRefCache(resolvedTabID)
+ if err := h.waitForNavigationState(tCtx, req.WaitFor, req.WaitSelector); err != nil {
+ web.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)
+ return
+ }
+
var url string
_ = chromedp.Run(tCtx, chromedp.Location(&url))
title, _ := bridge.WaitForTitle(tCtx, titleWait)
@@ -250,6 +284,48 @@ func (h *Handlers) HandleTabNavigate(w http.ResponseWriter, r *http.Request) {
h.HandleNavigate(w, req)
}
+func (h *Handlers) waitForNavigationState(ctx context.Context, waitFor, waitSelector string) error {
+ waitMode := strings.ToLower(strings.TrimSpace(waitFor))
+ switch waitMode {
+ case "", "none":
+ return nil
+ case "dom":
+ var ready string
+ return chromedp.Run(ctx, chromedp.Evaluate(`document.readyState`, &ready))
+ case "selector":
+ if waitSelector == "" {
+ return fmt.Errorf("waitSelector required when waitFor=selector")
+ }
+ return chromedp.Run(ctx, chromedp.WaitVisible(waitSelector, chromedp.ByQuery))
+ case "networkidle":
+ // Approximation for "network idle": require fully loaded readyState and no URL changes
+ var lastURL string
+ idleChecks := 0
+ for i := 0; i < 12; i++ { // up to ~3s
+ var ready, curURL string
+ if err := chromedp.Run(ctx,
+ chromedp.Evaluate(`document.readyState`, &ready),
+ chromedp.Location(&curURL),
+ ); err != nil {
+ return err
+ }
+ if ready == "complete" && curURL == lastURL {
+ idleChecks++
+ if idleChecks >= 2 {
+ return nil
+ }
+ } else {
+ idleChecks = 0
+ }
+ lastURL = curURL
+ time.Sleep(250 * time.Millisecond)
+ }
+ return fmt.Errorf("networkidle wait timed out")
+ default:
+ return fmt.Errorf("unsupported waitFor %q (use: none|dom|selector|networkidle)", waitMode)
+ }
+}
+
func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.go
new file mode 100644
index 00000000..e1e34986
--- /dev/null
+++ b/internal/handlers/openapi.go
@@ -0,0 +1,30 @@
+package handlers
+
+import (
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
+ web.JSON(w, 200, map[string]any{
+ "openapi": "3.0.0",
+ "info": map[string]any{
+ "title": "Pinchtab API",
+ "version": "0.7.x-local",
+ },
+ "paths": map[string]any{
+ "/health": map[string]any{"get": map[string]any{"summary": "Health"}},
+ "/tabs": map[string]any{"get": map[string]any{"summary": "List tabs"}},
+ "/metrics": map[string]any{"get": map[string]any{"summary": "Runtime metrics"}},
+ "/help": map[string]any{"get": map[string]any{"summary": "Human help"}},
+ "/text": map[string]any{"get": map[string]any{"summary": "Extract text", "parameters": []map[string]any{{"name": "maxChars", "in": "query", "schema": map[string]string{"type": "integer"}}, {"name": "format", "in": "query", "schema": map[string]string{"type": "string"}}}}},
+ "/navigate": map[string]any{"post": map[string]any{"summary": "Navigate"}, "get": map[string]any{"summary": "Navigate (query params)"}},
+ "/nav": map[string]any{"get": map[string]any{"summary": "Navigate alias"}},
+ "/action": map[string]any{"post": map[string]any{"summary": "Single action"}, "get": map[string]any{"summary": "Single action (query params)"}},
+ "/actions": map[string]any{"post": map[string]any{"summary": "Batch actions"}},
+ "/macro": map[string]any{"post": map[string]any{"summary": "Macro action pipeline"}},
+ "/snapshot": map[string]any{"get": map[string]any{"summary": "Accessibility snapshot"}},
+ },
+ })
+}
diff --git a/internal/web/web.go b/internal/web/web.go
index 50f834b1..5cdf54d8 100644
--- a/internal/web/web.go
+++ b/internal/web/web.go
@@ -19,7 +19,21 @@ func JSON(w http.ResponseWriter, code int, data any) {
}
func Error(w http.ResponseWriter, code int, err error) {
- JSON(w, code, map[string]string{"error": err.Error()})
+ ErrorCode(w, code, "error", err.Error(), false, nil)
+}
+
+func ErrorCode(w http.ResponseWriter, status int, code, message string, retryable bool, details map[string]any) {
+ payload := map[string]any{
+ "error": message,
+ "code": code,
+ }
+ if retryable {
+ payload["retryable"] = true
+ }
+ if len(details) > 0 {
+ payload["details"] = details
+ }
+ JSON(w, status, payload)
}
// CancelOnClientDone cancels the given cancel func when the HTTP client disconnects.
diff --git a/internal/web/web_test.go b/internal/web/web_test.go
index eb401320..936605ec 100644
--- a/internal/web/web_test.go
+++ b/internal/web/web_test.go
@@ -53,7 +53,7 @@ func TestError(t *testing.T) {
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400, got %d", w.Code)
}
- expectedBody := `{"error":"bad request"}` + "\n"
+ expectedBody := `{"code":"error","error":"bad request"}` + "\n"
if w.Body.String() != expectedBody {
t.Errorf("expected body %q, got %q", expectedBody, w.Body.String())
}