Skip to content

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

fix: support non-loopback child health probes and improve dashboard

Luigi Agosti36ce30159318
diff --git a/README.md b/README.md
index 18843868..85fa7f8f 100644
--- a/README.md
+++ b/README.md
@@ -61,10 +61,17 @@ PinchTab also provides a CLI with an interactive entry point for local setup and
PinchTab defaults to a **local-first security posture**:
- `server.bind = 127.0.0.1`
+- dashboard session cookies are `Secure` only when the dashboard is actually served over HTTPS
- sensitive endpoint families are disabled by default
- `attach` is disabled by default
- IDPI is enabled with a **local-only website allowlist**
+If you intentionally access the dashboard over plain HTTP on a non-loopback
+address, PinchTab now warns in the UI that the session is running without
+transport encryption. Prefer HTTPS or localhost when possible. If you force
+`server.cookieSecure = true`, dashboard login requires HTTPS and will fail
+explicitly on plain HTTP instead of looping silently.
+
> [!CAUTION]
> By default, IDPI restricts browsing to **locally hosted websites only**.
> This prevents agents from navigating the public internet until you explicitly allow it.
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index 2f5086c3..df497bca 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -14,7 +14,9 @@ import * as api from "./services/api";
import {
AUTH_REQUIRED_EVENT,
AUTH_STATE_CHANGED_EVENT,
+ INSECURE_DASHBOARD_TRANSPORT_WARNING,
SERVER_UNREACHABLE_EVENT,
+ isInsecureDashboardTransport,
} from "./services/auth";
import { acquireDashboardRealtime } from "./services/dashboardRealtime";
import { useAppStore } from "./stores/useAppStore";
@@ -37,6 +39,7 @@ function AppContent() {
const [authRetryCount, setAuthRetryCount] = useState(0);
const dashboardAccessible = authMode === "open";
const loginRequired = authMode === "required";
+ const insecureDashboardTransport = isInsecureDashboardTransport();
useEffect(() => {
document.documentElement.setAttribute("data-site-mode", "agent");
@@ -244,6 +247,11 @@ function AppContent() {
return (
<div className="dashboard-shell flex h-screen flex-col bg-bg-app">
<NavBar showLogout={authProtected} />
+ {insecureDashboardTransport && (
+ <div className="border-b border-warning/25 bg-warning/10 px-4 py-2 text-sm text-warning">
+ {INSECURE_DASHBOARD_TRANSPORT_WARNING}
+ </div>
+ )}
<main className="dashboard-grid flex-1 overflow-hidden">
<Routes>
<Route
diff --git a/dashboard/src/pages/LoginPage.tsx b/dashboard/src/pages/LoginPage.tsx
index 2fcb472c..49115ff9 100644
--- a/dashboard/src/pages/LoginPage.tsx
+++ b/dashboard/src/pages/LoginPage.tsx
@@ -3,7 +3,11 @@ import type { ComponentProps } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Button, Card } from "../components/atoms";
import * as api from "../services/api";
-import { dispatchAuthStateChanged } from "../services/auth";
+import {
+ dispatchAuthStateChanged,
+ INSECURE_DASHBOARD_TRANSPORT_WARNING,
+ isInsecureDashboardTransport,
+} from "../services/auth";
export default function LoginPage() {
const navigate = useNavigate();
@@ -11,6 +15,7 @@ export default function LoginPage() {
const [token, setToken] = useState("");
const [error, setError] = useState("");
const [submitting, setSubmitting] = useState(false);
+ const insecureDashboardTransport = isInsecureDashboardTransport();
const from =
(location.state as { from?: string } | null)?.from ||
@@ -52,6 +57,11 @@ export default function LoginPage() {
</code>{" "}
to copy the token to your clipboard.
</p>
+ {insecureDashboardTransport && (
+ <div className="mt-3 rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-xs leading-5 text-warning">
+ {INSECURE_DASHBOARD_TRANSPORT_WARNING}
+ </div>
+ )}
</div>
<form
diff --git a/dashboard/src/pages/settings/NetworkSettingsSection.tsx b/dashboard/src/pages/settings/NetworkSettingsSection.tsx
index 244d05c8..a5117300 100644
--- a/dashboard/src/pages/settings/NetworkSettingsSection.tsx
+++ b/dashboard/src/pages/settings/NetworkSettingsSection.tsx
@@ -129,6 +129,42 @@ export function NetworkSettingsSection({
{backendConfig.server.trustProxyHeaders ? "Enabled" : "Disabled"}
</label>
</SettingRow>
+ <SettingRow
+ label="Cookie Secure mode"
+ description="Controls whether dashboard session cookies require HTTPS. Auto enables Secure only on HTTPS. Force Secure is appropriate when TLS is in front of PinchTab."
+ >
+ <div className="space-y-2">
+ <select
+ value={
+ backendConfig.server.cookieSecure === true
+ ? "true"
+ : backendConfig.server.cookieSecure === false
+ ? "false"
+ : "auto"
+ }
+ onChange={(e) =>
+ updateBackendSection("server", {
+ cookieSecure:
+ e.target.value === "auto"
+ ? undefined
+ : e.target.value === "true",
+ })
+ }
+ className={fieldClass}
+ >
+ <option value="auto">Auto</option>
+ <option value="true">Force Secure</option>
+ <option value="false">Force Insecure</option>
+ </select>
+ <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-xs leading-5 text-warning">
+ Force Secure blocks dashboard login on plain HTTP. Use it when
+ PinchTab is served through HTTPS directly or behind a trusted proxy.
+ If TLS terminates in front of PinchTab, enable{" "}
+ <code>trustProxyHeaders</code> so forwarded HTTPS requests are
+ recognized.
+ </div>
+ </div>
+ </SettingRow>
<SettingRow
label="Persist dashboard sessions"
description="Keep dashboard login sessions across server restarts. Disable this if you want every restart to force a fresh login."
diff --git a/dashboard/src/services/auth.test.ts b/dashboard/src/services/auth.test.ts
index cdc9660f..bd2fb027 100644
--- a/dashboard/src/services/auth.test.ts
+++ b/dashboard/src/services/auth.test.ts
@@ -2,10 +2,12 @@ import { describe, expect, it, vi } from "vitest";
import {
AUTH_REQUIRED_EVENT,
AUTH_STATE_CHANGED_EVENT,
+ INSECURE_DASHBOARD_TRANSPORT_WARNING,
SERVER_UNREACHABLE_EVENT,
dispatchAuthRequired,
dispatchAuthStateChanged,
dispatchServerUnreachable,
+ isInsecureDashboardTransport,
sameOriginUrl,
} from "./auth";
@@ -49,4 +51,21 @@ describe("auth helpers", () => {
vi.unstubAllGlobals();
});
+
+ it("detects insecure LAN dashboard transport", () => {
+ vi.stubGlobal("location", new URL("http://192.168.1.50:9867/dashboard"));
+
+ expect(isInsecureDashboardTransport()).toBe(true);
+ expect(INSECURE_DASHBOARD_TRANSPORT_WARNING).toContain("insecure HTTP");
+
+ vi.unstubAllGlobals();
+ });
+
+ it("does not flag localhost over plain http as insecure LAN transport", () => {
+ vi.stubGlobal("location", new URL("http://localhost:9867/dashboard"));
+
+ expect(isInsecureDashboardTransport()).toBe(false);
+
+ vi.unstubAllGlobals();
+ });
});
diff --git a/dashboard/src/services/auth.ts b/dashboard/src/services/auth.ts
index a82c7838..a8ebd540 100644
--- a/dashboard/src/services/auth.ts
+++ b/dashboard/src/services/auth.ts
@@ -1,6 +1,8 @@
const AUTH_REQUIRED_EVENT = "pinchtab-auth-required";
const AUTH_STATE_CHANGED_EVENT = "pinchtab-auth-state-changed";
const SERVER_UNREACHABLE_EVENT = "pinchtab-server-unreachable";
+export const INSECURE_DASHBOARD_TRANSPORT_WARNING =
+ "Dashboard session is running over insecure HTTP; use HTTPS or localhost for stronger session protection.";
export function dispatchAuthRequired(reason: string): void {
window.dispatchEvent(
@@ -23,6 +25,27 @@ export function sameOriginUrl(url: string): string {
return absolute.pathname + absolute.search;
}
+function isLoopbackHostname(hostname: string): boolean {
+ const host = hostname.trim().toLowerCase();
+ if (
+ host === "localhost" ||
+ host === "::1" ||
+ host === "[::1]" ||
+ host.endsWith(".localhost")
+ ) {
+ return true;
+ }
+ return /^127(?:\.\d{1,3}){3}$/.test(host);
+}
+
+export function isInsecureDashboardTransport(): boolean {
+ if (typeof window === "undefined") {
+ return false;
+ }
+ const { protocol, hostname } = window.location;
+ return protocol === "http:" && !isLoopbackHostname(hostname);
+}
+
export {
AUTH_REQUIRED_EVENT,
AUTH_STATE_CHANGED_EVENT,
diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.ts
index d3016503..82c71635 100644
--- a/dashboard/src/types/index.ts
+++ b/dashboard/src/types/index.ts
@@ -59,6 +59,7 @@ export interface BackendServerConfig {
token: string;
stateDir: string;
trustProxyHeaders: boolean;
+ cookieSecure?: boolean;
}
export interface BackendDashboardSessionConfig {
@@ -213,6 +214,7 @@ export const defaultBackendConfig: BackendConfig = {
token: "",
stateDir: "",
trustProxyHeaders: false,
+ cookieSecure: undefined,
},
browser: {
version: "144.0.7559.133",
diff --git a/docs/architecture/orchestration.md b/docs/architecture/orchestration.md
index 9edd4c56..ced73407 100644
--- a/docs/architecture/orchestration.md
+++ b/docs/architecture/orchestration.md
@@ -40,7 +40,7 @@ flowchart LR
R["Start Request"] --> V["Validate profile + port"]
V --> W["Write child config"]
W --> P["Spawn pinchtab bridge"]
- P --> H["Poll /health on loopback addresses"]
+ P --> H["Poll /health on configured bind or loopback"]
H --> S{"Healthy before timeout?"}
S -->|Yes| OK["Mark running"]
S -->|No| ER["Mark error"]
@@ -54,7 +54,8 @@ What the code does today:
- prevents reusing a port already in use
- writes a child config file under the profile state directory
- launches `pinchtab bridge`
-- polls `/health` on `127.0.0.1`, `::1`, and `localhost`
+- polls `/health` on the configured child bind first when present, then falls
+ back to `127.0.0.1`, `::1`, and `localhost`
- moves the instance from `starting` to `running` or `error`
## Attach Flow
diff --git a/docs/guides/security.md b/docs/guides/security.md
index c8b84ee1..72bd69ac 100644
--- a/docs/guides/security.md
+++ b/docs/guides/security.md
@@ -99,9 +99,32 @@ The browser dashboard uses a different flow:
elevation
By default, PinchTab auto-detects whether the dashboard session cookie should
-use the `Secure` flag. For reverse-proxied HTTPS this stays enabled. If you
-intentionally access the dashboard over plain HTTP on a trusted LAN, you can
-explicitly disable it:
+use the `Secure` flag. In `auto` mode, HTTPS requests get `Secure` cookies and
+plain HTTP requests do not.
+
+That means:
+
+- reverse-proxied HTTPS keeps `Secure` enabled
+- plain `http://localhost:9867` keeps working for local-only use
+- plain `http://192.168.x.x:9867` or `http://10.x.x.x:9867` works, but the
+ dashboard warns that the session is running over insecure HTTP
+
+If you want to require HTTPS for dashboard login, force `server.cookieSecure`
+to `true`:
+
+```json
+{
+ "server": {
+ "cookieSecure": true
+ }
+}
+```
+
+On plain HTTP, that now fails explicitly with an HTTPS-required login error
+instead of appearing to succeed and then looping.
+
+If you intentionally need plain HTTP on a trusted LAN, you can also force
+`cookieSecure` off explicitly:
```json
{
@@ -111,6 +134,14 @@ explicitly disable it:
}
```
+Recommended usage:
+
+- leave `cookieSecure` unset (`auto`) unless you have a reason to override it
+- use `cookieSecure: true` when TLS is in front of PinchTab
+- only use `cookieSecure: false` on operator-controlled plain-HTTP deployments
+- if TLS terminates at a trusted reverse proxy, enable
+ `server.trustProxyHeaders` so forwarded HTTPS requests are recognized
+
Why this matters:
- without a token, any process that can reach the server can call the API
diff --git a/docs/reference/config.md b/docs/reference/config.md
index a887badd..74383472 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -153,7 +153,8 @@ Current nested file-config shape:
"stateDir": "/path/to/state",
"engine": "chrome",
"networkBufferSize": 100,
- "trustProxyHeaders": false
+ "trustProxyHeaders": false,
+ "cookieSecure": null
},
"browser": {
"version": "144.0.7559.133",
@@ -361,6 +362,36 @@ pinchtab server
Changing `server.bind` away from loopback is a documented, non-default, security-reducing deployment change. Use it only when remote reachability is intentional, keep a token set, and review the outer network boundary explicitly.
+If the dashboard is served over plain HTTP on a non-loopback bind, PinchTab
+shows an in-product warning because session cookies are no longer transport
+encrypted. Prefer HTTPS or localhost when possible.
+
+### Dashboard Cookie Transport
+
+`server.cookieSecure` controls whether the dashboard session cookie must use the
+`Secure` flag:
+
+- `null` / unset / `auto`: default behavior. Session cookies are `Secure` on
+ HTTPS and non-`Secure` on plain HTTP.
+- `true`: always require `Secure`. Dashboard login works only over HTTPS.
+- `false`: always omit `Secure`, even on HTTPS. Use only for operator-managed
+ edge cases.
+
+Examples:
+
+```bash
+pinchtab config set server.cookieSecure true
+pinchtab config set server.cookieSecure false
+pinchtab config set server.cookieSecure auto
+```
+
+When `server.cookieSecure = true`, plain-HTTP dashboard login fails explicitly
+with an HTTPS-required error instead of appearing to succeed and looping.
+
+If TLS terminates in front of PinchTab, also set `server.trustProxyHeaders=true`
+only when the proxy is trusted and rewrites `Forwarded` / `X-Forwarded-*`
+headers correctly.
+
### Custom Instance Port Range
```json
diff --git a/internal/authn/cookie.go b/internal/authn/cookie.go
index 57d2faa7..9b9f063b 100644
--- a/internal/authn/cookie.go
+++ b/internal/authn/cookie.go
@@ -1,7 +1,6 @@
package authn
import (
- "net"
"net/http"
"net/url"
"strings"
@@ -45,10 +44,11 @@ func sessionCookieSecure(r *http.Request, trustProxy bool, cookieSecure *bool) b
if cookieSecure != nil {
return *cookieSecure
}
- if requestScheme(r, trustProxy) == "https" {
- return true
- }
- return !isLoopbackHost(requestHost(r, trustProxy))
+ return RequestIsHTTPS(r, trustProxy)
+}
+
+func RequestIsHTTPS(r *http.Request, trustProxy bool) bool {
+ return requestScheme(r, trustProxy) == "https"
}
func requestScheme(r *http.Request, trustProxy bool) string {
@@ -74,55 +74,3 @@ func requestScheme(r *http.Request, trustProxy bool) string {
}
return "http"
}
-
-func requestHost(r *http.Request, trustProxy bool) string {
- if r == nil {
- return ""
- }
- if trustProxy {
- if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Host")); forwarded != "" {
- return strings.TrimSpace(strings.Split(forwarded, ",")[0])
- }
- if forwarded := strings.TrimSpace(r.Header.Get("Forwarded")); forwarded != "" {
- for _, part := range strings.Split(forwarded, ";") {
- key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
- if !ok || !strings.EqualFold(key, "host") {
- continue
- }
- return strings.Trim(value, `"`)
- }
- }
- }
- return strings.TrimSpace(r.Host)
-}
-
-func isLoopbackHost(host string) bool {
- host = hostOnly(host)
- if host == "" {
- return false
- }
- if strings.EqualFold(host, "localhost") {
- return true
- }
- ip := net.ParseIP(host)
- return ip != nil && ip.IsLoopback()
-}
-
-func hostOnly(hostport string) string {
- hostport = strings.TrimSpace(hostport)
- if hostport == "" {
- return ""
- }
- if host, port, err := net.SplitHostPort(hostport); err == nil {
- if port != "" {
- return strings.Trim(host, "[]")
- }
- }
- if strings.HasPrefix(hostport, "[") && strings.HasSuffix(hostport, "]") {
- return strings.Trim(hostport, "[]")
- }
- if strings.Count(hostport, ":") > 1 {
- return strings.Trim(hostport, "[]")
- }
- return hostport
-}
diff --git a/internal/authn/cookie_test.go b/internal/authn/cookie_test.go
index 748c4d42..c72ada4e 100644
--- a/internal/authn/cookie_test.go
+++ b/internal/authn/cookie_test.go
@@ -20,10 +20,10 @@ func TestSessionCookieSecure_AutoDetect(t *testing.T) {
}
})
- t.Run("lan host over http remains secure for backward compatibility", func(t *testing.T) {
+ t.Run("lan host over http is not secure", func(t *testing.T) {
req := httptest.NewRequest("GET", "http://192.168.1.50:9867/dashboard", nil)
- if !sessionCookieSecure(req, false, nil) {
- t.Fatal("expected lan http request to keep Secure cookie in auto-detect mode")
+ if sessionCookieSecure(req, false, nil) {
+ t.Fatal("expected lan http request to omit Secure so browser sessions work over plain HTTP")
}
})
}
diff --git a/internal/bridge/cdp_element_ops_test.go b/internal/bridge/cdp_element_ops_test.go
index a2bb0695..ed1b4848 100644
--- a/internal/bridge/cdp_element_ops_test.go
+++ b/internal/bridge/cdp_element_ops_test.go
@@ -3,12 +3,11 @@ package bridge
import (
"context"
"testing"
-
- "github.com/chromedp/chromedp"
)
func TestSelectByNodeID_UsesValue(t *testing.T) {
- ctx, _ := chromedp.NewContext(context.Background())
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately - no browser spawned
// Without a real browser this will error, but it must NOT silently succeed
// (the old implementation was a no-op that always returned nil).
err := SelectByNodeID(ctx, 1, "option-value")
diff --git a/internal/bridge/cdp_navigation_test.go b/internal/bridge/cdp_navigation_test.go
index 468c675b..9865845e 100644
--- a/internal/bridge/cdp_navigation_test.go
+++ b/internal/bridge/cdp_navigation_test.go
@@ -4,8 +4,6 @@ import (
"context"
"testing"
"time"
-
- "github.com/chromedp/chromedp"
)
func TestWaitForTitle_ContextCancelled(t *testing.T) {
@@ -19,7 +17,8 @@ func TestWaitForTitle_ContextCancelled(t *testing.T) {
}
func TestWaitForTitle_NoTimeout(t *testing.T) {
- ctx, _ := chromedp.NewContext(context.Background())
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately - no browser spawned
// With timeout <= 0, should return immediately
title, _ := WaitForTitle(ctx, 0)
diff --git a/internal/bridge/input_human_test.go b/internal/bridge/input_human_test.go
index c9b628e2..1a44190e 100644
--- a/internal/bridge/input_human_test.go
+++ b/internal/bridge/input_human_test.go
@@ -4,8 +4,6 @@ import (
"context"
"math/rand"
"testing"
-
- "github.com/chromedp/chromedp"
)
func TestSetHumanRandSeed(t *testing.T) {
@@ -42,8 +40,8 @@ func TestTypeWithCorrections(t *testing.T) {
}
func TestMouseMove(t *testing.T) {
- // Create a context that chromedp.Run won't immediately reject
- ctx, _ := chromedp.NewContext(context.Background())
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately - no browser spawned
// MouseMove will try to call chromedp.Run.
// Without a real browser it will return an error, but we cover the code path.
@@ -51,7 +49,8 @@ func TestMouseMove(t *testing.T) {
}
func TestClick(t *testing.T) {
- ctx, _ := chromedp.NewContext(context.Background())
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately - no browser spawned
_ = Click(ctx, 50, 50)
}
@@ -83,7 +82,8 @@ func TestClickElement_RequiresMinContentLength(t *testing.T) {
// CDP BoxModel Content has 8 float64 values (4 x/y pairs)
// The guard must check len(box.Content) < 8
// Without a browser, GetBoxModel will fail
- ctx, _ := chromedp.NewContext(context.Background())
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately - no browser spawned
err := ClickElement(ctx, 0)
if err == nil {
t.Error("expected error without browser connection")
diff --git a/internal/dashboard/auth_api.go b/internal/dashboard/auth_api.go
index 19faaeba..9468a532 100644
--- a/internal/dashboard/auth_api.go
+++ b/internal/dashboard/auth_api.go
@@ -80,6 +80,14 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {
return
}
+ if a.requiresHTTPSForDashboardSession(r) {
+ httpx.ErrorCode(w, http.StatusBadRequest, "secure_cookie_requires_https", "server.cookieSecure=true requires HTTPS for dashboard login", false, map[string]any{
+ "hint": "Use HTTPS directly or through a trusted reverse proxy, or set server.cookieSecure back to auto/false for plain HTTP local use.",
+ "remedy": "If TLS terminates in front of PinchTab, also enable server.trustProxyHeaders so forwarded https requests are recognized.",
+ })
+ return
+ }
+
if subtle.ConstantTimeCompare([]byte(provided), []byte(token)) != 1 {
if a.loginLimiter != nil {
a.loginLimiter.RecordFailure(clientIP)
@@ -185,6 +193,13 @@ func cookieSecureSetting(cfg *config.RuntimeConfig) *bool {
return cfg.CookieSecure
}
+func (a *AuthAPI) requiresHTTPSForDashboardSession(r *http.Request) bool {
+ if a == nil || a.runtime == nil || a.runtime.CookieSecure == nil || !*a.runtime.CookieSecure {
+ return false
+ }
+ return !authn.RequestIsHTTPS(r, a.runtime.TrustProxyHeaders)
+}
+
func secondsCeil(d time.Duration) int {
if d <= 0 {
return 1
diff --git a/internal/dashboard/auth_api_test.go b/internal/dashboard/auth_api_test.go
index 738a0f93..05312537 100644
--- a/internal/dashboard/auth_api_test.go
+++ b/internal/dashboard/auth_api_test.go
@@ -15,7 +15,7 @@ func TestAuthAPIHandleLogin(t *testing.T) {
sessions := authn.NewSessionManager(authn.SessionConfig{})
api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
- req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
+ req := httptest.NewRequest("POST", "https://pinchtab.example/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
@@ -72,6 +72,29 @@ func TestAuthAPIHandleLogin_LocalhostHTTPUsesNonSecureCookie(t *testing.T) {
}
}
+func TestAuthAPIHandleLogin_LANHTTPUsesNonSecureCookie(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+
+ req := httptest.NewRequest("POST", "http://192.168.1.50:9867/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
+ req.Host = "192.168.1.50:9867"
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ cookies := w.Result().Cookies()
+ if len(cookies) != 1 {
+ t.Fatalf("cookies = %d, want 1", len(cookies))
+ }
+ if cookies[0].Secure {
+ t.Fatal("expected LAN http auth cookie to omit Secure so browser sessions work reliably")
+ }
+}
+
func TestAuthAPIHandleLogin_TrustedProxyHTTPSUsesSecureCookie(t *testing.T) {
sessions := authn.NewSessionManager(authn.SessionConfig{})
api := NewAuthAPI(&config.RuntimeConfig{
@@ -126,6 +149,32 @@ func TestAuthAPIHandleLogin_CookieSecureFalseOverridesHTTPS(t *testing.T) {
}
}
+func TestAuthAPIHandleLogin_CookieSecureTrueRejectsPlainHTTP(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ forceSecure := true
+ api := NewAuthAPI(&config.RuntimeConfig{
+ Token: "secret-token",
+ CookieSecure: &forceSecure,
+ }, sessions)
+
+ req := httptest.NewRequest("POST", "http://192.168.1.50:9867/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
+ req.Host = "192.168.1.50:9867"
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusBadRequest)
+ }
+ if !strings.Contains(w.Body.String(), "secure_cookie_requires_https") {
+ t.Fatalf("response = %q, want secure_cookie_requires_https error", w.Body.String())
+ }
+ if cookies := w.Result().Cookies(); len(cookies) != 0 {
+ t.Fatalf("cookies = %+v, want none", cookies)
+ }
+}
+
func TestAuthAPIHandleLoginRejectsBadToken(t *testing.T) {
api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, authn.NewSessionManager(authn.SessionConfig{}))
@@ -152,7 +201,7 @@ func TestAuthAPIHandleLogoutClearsCookie(t *testing.T) {
}
api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
- req := httptest.NewRequest("POST", "/api/auth/logout", nil)
+ req := httptest.NewRequest("POST", "https://pinchtab.example/api/auth/logout", nil)
req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
w := httptest.NewRecorder()
@@ -200,6 +249,33 @@ func TestAuthAPIHandleLogout_LocalhostHTTPClearsNonSecureCookie(t *testing.T) {
}
}
+func TestAuthAPIHandleLogout_LANHTTPClearsNonSecureCookie(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create("secret-token")
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+
+ req := httptest.NewRequest("POST", "http://192.168.1.50:9867/api/auth/logout", nil)
+ req.Host = "192.168.1.50:9867"
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+
+ api.HandleLogout(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ cookies := w.Result().Cookies()
+ if len(cookies) != 1 || cookies[0].Name != authn.CookieName || cookies[0].MaxAge != -1 {
+ t.Fatalf("expected expired auth cookie, got %+v", cookies)
+ }
+ if cookies[0].Secure {
+ t.Fatal("expected LAN http logout cookie clearing to omit Secure")
+ }
+}
+
func TestAuthAPIHandleElevateMarksSessionElevated(t *testing.T) {
sessions := authn.NewSessionManager(authn.SessionConfig{})
sessionID, err := sessions.Create("secret-token")
diff --git a/internal/handlers/download_test.go b/internal/handlers/download_test.go
index 3193a9c5..4c9c8e69 100644
--- a/internal/handlers/download_test.go
+++ b/internal/handlers/download_test.go
@@ -12,7 +12,6 @@ import (
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/target"
- "github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/netguard"
@@ -26,11 +25,14 @@ type downloadPolicyBridge struct {
}
func (m *downloadPolicyBridge) BrowserContext() context.Context {
- return context.Background()
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately - no browser spawned
+ return ctx
}
func (m *downloadPolicyBridge) TabContext(tabID string) (context.Context, string, error) {
- ctx, _ := chromedp.NewContext(context.Background())
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately - no browser spawned
return ctx, tabID, nil
}
diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.go
index e5079d2a..4641e74f 100644
--- a/internal/handlers/handlers_test.go
+++ b/internal/handlers/handlers_test.go
@@ -13,7 +13,6 @@ import (
"time"
"github.com/chromedp/cdproto/target"
- "github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -31,9 +30,8 @@ func (m *mockBridge) TabContext(tabID string) (context.Context, string, error) {
if m.failTab {
return nil, "", fmt.Errorf("tab not found")
}
- // We need a context that chromedp.Run won't complain about,
- // even if it's not fully functional for real CDP commands.
- ctx, _ := chromedp.NewContext(context.Background())
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
return ctx, "tab1", nil
}
@@ -51,7 +49,8 @@ func (m *mockBridge) ExecuteAction(ctx context.Context, kind string, req bridge.
func (m *mockBridge) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
m.createTabURLs = append(m.createTabURLs, url)
- ctx, cancel := chromedp.NewContext(context.Background())
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately - no browser spawned
return "tab_abc12345", ctx, cancel, nil
}
diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.go
index 94be7ef5..7699b538 100644
--- a/internal/orchestrator/health.go
+++ b/internal/orchestrator/health.go
@@ -7,10 +7,12 @@ import (
"net"
"net/http"
"net/url"
+ "strconv"
"strings"
"time"
"github.com/pinchtab/pinchtab/internal/activity"
+ "github.com/pinchtab/pinchtab/internal/config"
)
const (
@@ -58,7 +60,7 @@ func (o *Orchestrator) monitor(inst *InstanceInternal) {
// monitor only probes child bridge processes started by Launch.
// Attached remote bridges are validated and probed during attach.
- for _, baseURL := range instanceBaseURLs(probePort) {
+ for _, baseURL := range instanceBaseURLs(configuredChildBind(o.runtimeCfg), probePort) {
targetBaseURL, err := o.validatedHealthProbeBaseURL(baseURL, "", healthProbePolicyLoopback)
if err != nil {
lastProbe = fmt.Sprintf("%s -> %s", baseURL, err.Error())
@@ -197,7 +199,7 @@ func (o *Orchestrator) probeInstanceHealth(inst *InstanceInternal) (bool, string
if err != nil {
return false, "", err.Error()
}
- baseURLs = instanceBaseURLs(probePort)
+ baseURLs = instanceBaseURLs("", probePort)
}
policy := healthProbePolicyLoopback
@@ -339,7 +341,7 @@ func (o *Orchestrator) validatedHealthProbeBaseURL(rawURL, port string, policy h
return nil, fmt.Errorf("blocked: host not allowed")
}
default:
- if !isAllowedProbeHost(host) {
+ if !isAllowedChildProbeHost(host, configuredChildBind(o.runtimeCfg)) {
slog.Warn("health probe blocked: non-loopback host", "url", rawURL, "host", host)
return nil, fmt.Errorf("blocked: non-loopback host")
}
@@ -366,7 +368,7 @@ func healthProbeURL(baseURL *url.URL) string {
}).String()
}
-// isAllowedProbeHost restricts health probes to loopback addresses to
+// isAllowedProbeHost restricts generic health probes to loopback addresses to
// prevent SSRF when inst.URL is attacker-controlled.
func isAllowedProbeHost(host string) bool {
if strings.EqualFold(host, "localhost") {
@@ -376,10 +378,56 @@ func isAllowedProbeHost(host string) bool {
return ip != nil && ip.IsLoopback()
}
-func instanceBaseURLs(port int) []string {
- return []string{
- fmt.Sprintf("http://127.0.0.1:%d", port),
- fmt.Sprintf("http://[::1]:%d", port),
- fmt.Sprintf("http://localhost:%d", port),
+func isAllowedChildProbeHost(host, bind string) bool {
+ if isAllowedProbeHost(host) {
+ return true
+ }
+ return strings.EqualFold(host, configuredChildInstanceHost(bind))
+}
+
+func configuredChildBind(cfg *config.RuntimeConfig) string {
+ if cfg == nil {
+ return ""
+ }
+ return strings.TrimSpace(cfg.Bind)
+}
+
+func configuredChildInstanceHost(bind string) string {
+ bind = strings.TrimSpace(bind)
+ switch bind {
+ case "", "0.0.0.0", "::":
+ return "localhost"
+ default:
+ return bind
+ }
+}
+
+func httpBaseURL(host, port string) string {
+ return (&url.URL{
+ Scheme: "http",
+ Host: net.JoinHostPort(host, port),
+ }).String()
+}
+
+func instanceBaseURLs(bind string, port int) []string {
+ portStr := strconv.Itoa(port)
+ candidates := make([]string, 0, 4)
+ seen := make(map[string]struct{}, 4)
+ appendURL := func(host string) {
+ baseURL := httpBaseURL(host, portStr)
+ if _, ok := seen[baseURL]; ok {
+ return
+ }
+ seen[baseURL] = struct{}{}
+ candidates = append(candidates, baseURL)
+ }
+
+ bind = strings.TrimSpace(bind)
+ if bind != "" && bind != "0.0.0.0" && bind != "::" {
+ appendURL(bind)
}
+ appendURL("127.0.0.1")
+ appendURL("::1")
+ appendURL("localhost")
+ return candidates
}
diff --git a/internal/orchestrator/health_test.go b/internal/orchestrator/health_test.go
index cb4e28af..34baed98 100644
--- a/internal/orchestrator/health_test.go
+++ b/internal/orchestrator/health_test.go
@@ -37,7 +37,7 @@ func TestIsInstanceHealthyStatus(t *testing.T) {
}
func TestInstanceBaseURLs(t *testing.T) {
- urls := instanceBaseURLs(1234)
+ urls := instanceBaseURLs("", 1234)
expected := []string{
"http://127.0.0.1:1234",
@@ -56,6 +56,40 @@ func TestInstanceBaseURLs(t *testing.T) {
}
}
+func TestInstanceBaseURLs_IncludesConfiguredBindFirst(t *testing.T) {
+ urls := instanceBaseURLs("192.168.1.50", 1234)
+
+ expected := []string{
+ "http://192.168.1.50:1234",
+ "http://127.0.0.1:1234",
+ "http://[::1]:1234",
+ "http://localhost:1234",
+ }
+
+ if len(urls) != len(expected) {
+ t.Fatalf("expected %d URLs, got %d", len(expected), len(urls))
+ }
+
+ for i, url := range urls {
+ if url != expected[i] {
+ t.Errorf("url[%d] = %q, want %q", i, url, expected[i])
+ }
+ }
+}
+
+func TestValidatedHealthProbeBaseURL_AllowsConfiguredChildBindHost(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{Bind: "192.168.1.50"})
+
+ baseURL, err := o.validatedHealthProbeBaseURL("http://192.168.1.50:9872", "", healthProbePolicyLoopback)
+ if err != nil {
+ t.Fatalf("validatedHealthProbeBaseURL() error = %v", err)
+ }
+ if got := baseURL.String(); got != "http://192.168.1.50:9872" {
+ t.Fatalf("validatedHealthProbeBaseURL() = %q, want %q", got, "http://192.168.1.50:9872")
+ }
+}
+
func TestProbeInstanceHealth_AllowsConfiguredAttachedBridgeHost(t *testing.T) {
o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
o.ApplyRuntimeConfig(&config.RuntimeConfig{
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 95f6fdbf..c82d1a98 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -353,12 +353,12 @@ func (o *Orchestrator) Launch(name, port string, headless bool, extensionPaths [
ProfileID: profileID,
ProfileName: name,
Port: port,
- URL: fmt.Sprintf("http://localhost:%s", port),
+ URL: o.childInstanceBaseURL(port),
Headless: headless,
Status: "starting",
StartTime: time.Now(),
},
- URL: fmt.Sprintf("http://localhost:%s", port),
+ URL: o.childInstanceBaseURL(port),
cdpPort: cdpPort,
cmd: cmd,
logBuf: logBuf,
@@ -374,6 +374,14 @@ func (o *Orchestrator) Launch(name, port string, headless bool, extensionPaths [
return &inst.Instance, nil
}
+func (o *Orchestrator) childInstanceBaseURL(port string) string {
+ host := configuredChildInstanceHost("")
+ if o != nil && o.runtimeCfg != nil {
+ host = configuredChildInstanceHost(o.runtimeCfg.Bind)
+ }
+ return httpBaseURL(host, port)
+}
+
func (o *Orchestrator) writeChildConfig(port string, cdpPort int, profilePath, instanceStateDir string, headless bool, extensionPaths []string) (string, error) {
fc := config.FileConfigFromRuntime(o.runtimeCfg)
fc.Server.Port = port
diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.go
index 0afd6f85..88a89445 100644
--- a/internal/orchestrator/orchestrator_test.go
+++ b/internal/orchestrator/orchestrator_test.go
@@ -93,6 +93,25 @@ func TestOrchestrator_ListAndStop(t *testing.T) {
}
}
+func TestOrchestrator_Launch_UsesConfiguredBindInInstanceURL(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ defer func() { processAliveFunc = old }()
+ stubPortAvailability(t, func(int) bool { return true })
+
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{Bind: "192.168.1.50"})
+
+ inst, err := o.Launch("profile1", "9001", true, nil)
+ if err != nil {
+ t.Fatalf("Launch failed: %v", err)
+ }
+ if inst.URL != "http://192.168.1.50:9001" {
+ t.Fatalf("URL = %q, want %q", inst.URL, "http://192.168.1.50:9001")
+ }
+}
+
func TestOrchestrator_StopProfile(t *testing.T) {
old := processAliveFunc
processAliveFunc = func(pid int) bool { return true }
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index 5f5d2848..f2b739df 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -95,7 +95,10 @@ func (s *Strategy) ensureRunning() (string, error) {
deadline := time.Now().Add(30 * time.Second)
for time.Now().Before(deadline) {
time.Sleep(500 * time.Millisecond)
- url := fmt.Sprintf("http://localhost:%s", launched.Port)
+ url := launched.URL
+ if url == "" {
+ url = fmt.Sprintf("http://localhost:%s", launched.Port)
+ }
resp, healthErr := http.Get(url + "/health")
if healthErr == nil {
_ = resp.Body.Close()