Skip to content

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

feat: remote bridge orchestration support (#281)

luigiagenta75e141ecfe7
diff --git a/TESTING.md b/TESTING.md
index ade41617..f454e9de 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -9,6 +9,7 @@ The `dev` developer toolkit is the easiest way to run checks and tests:
./dev test # All tests (unit + E2E)
./dev test unit # Unit tests only
./dev e2e # E2E tests (both curl and CLI)
+./dev e2e orchestrator # Orchestrator-heavy E2E tests only
./dev e2e curl # E2E curl tests only
./dev e2e cli # E2E CLI tests only
./dev check # All checks (format, vet, build, lint)
@@ -56,6 +57,14 @@ Runs CLI e2e tests. Tests the command-line interface directly.
Runs all E2E tests (curl + CLI, 224 tests total).
+### Orchestrator E2E Suite
+
+```bash
+./dev e2e orchestrator
+```
+
+Runs the orchestration-focused curl scenarios, including multi-instance flows and remote bridge attachment against the dedicated `pinchtab-bridge` Compose service.
+
## Environment Variables
| Variable | Default | Description |
@@ -90,6 +99,10 @@ E2E tests are organized in two directories:
- Test the REST API directly
- Use Docker Compose: `tests/e2e/docker-compose.yml`
+- **`tests/e2e/scenarios-orchestrator/*.sh`** — orchestration-heavy curl tests
+ - Test multi-instance flows and remote bridge attachment
+ - Use Docker Compose: `tests/e2e/docker-compose-orchestrator.yml`
+
- **`tests/e2e/scenarios-cli/*.sh`** — CLI e2e tests (41 tests)
- Test the command-line interface
- Use Docker Compose: `tests/e2e/docker-compose.cli.yml`
diff --git a/dashboard/package.json b/dashboard/package.json
index 0267ff4d..dbec6cb0 100644
--- a/dashboard/package.json
+++ b/dashboard/package.json
@@ -2,6 +2,7 @@
"name": "dashboard",
"private": true,
"version": "0.0.0",
+ "packageManager": "[email protected]",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/dashboard/src/generated/types.ts b/dashboard/src/generated/types.ts
index 557e6fee..40cd696a 100644
--- a/dashboard/src/generated/types.ts
+++ b/dashboard/src/generated/types.ts
@@ -39,12 +39,14 @@ export interface Instance {
profileId: string;
profileName: string;
port: string; // Note: string not int
+ url?: string;
headless: boolean;
status: string; // starting/running/stopping/stopped/error
startTime: string;
error?: string;
- attached: boolean; // True if attached to external Chrome
- cdpUrl?: string; // CDP WebSocket URL (for attached instances)
+ attached: boolean; // True if attached rather than locally launched
+ attachType?: string;
+ cdpUrl?: string; // CDP WebSocket URL (for CDP-attached instances)
}
/**
* Agent represents a connected AI agent.
diff --git a/dev b/dev
index c84541ca..d2cf6912 100755
--- a/dev
+++ b/dev
@@ -25,6 +25,7 @@ COMMANDS=(
"test dashboard:🔬:Dashboard unit tests"
"e2e:🐳:E2E tests"
" recent:🐳:E2E Recent tests"
+ " orchestrator:🐳:E2E Orchestrator tests"
" curl:🐳:E2E Curl tests"
" cli:🐳:E2E CLI tests"
"doctor:🩺:Setup dev environment"
@@ -162,6 +163,17 @@ run_command() {
fi
docker compose -f tests/e2e/docker-compose.yml down -v 2>/dev/null
+ echo ""
+ echo " ${ACCENT}${BOLD}🐳 E2E Orchestrator tests (Docker)${NC}"
+ echo ""
+ docker compose -f tests/e2e/docker-compose-orchestrator.yml run --build --rm runner
+ local orch_exit=$?
+ if [ $orch_exit -ne 0 ]; then
+ docker compose -f tests/e2e/docker-compose-orchestrator.yml logs pinchtab | tail -n 50 || true
+ docker compose -f tests/e2e/docker-compose-orchestrator.yml logs pinchtab-bridge | tail -n 50 || true
+ fi
+ docker compose -f tests/e2e/docker-compose-orchestrator.yml down -v 2>/dev/null
+
echo ""
echo " ${ACCENT}${BOLD}🐳 E2E CLI tests (Docker)${NC}"
echo ""
@@ -174,7 +186,7 @@ run_command() {
docker compose -f tests/e2e/docker-compose-cli.yml down -v 2>/dev/null
echo ""
- if [ $curl_exit -ne 0 ] || [ $cli_exit -ne 0 ]; then
+ if [ $curl_exit -ne 0 ] || [ $orch_exit -ne 0 ] || [ $cli_exit -ne 0 ]; then
echo " ${ERROR}Some E2E tests failed${NC}"
exit 1
fi
@@ -204,6 +216,18 @@ run_command() {
docker compose -f tests/e2e/docker-compose-cli.yml down -v 2>/dev/null
exit $cli_exit
;;
+ "e2e orchestrator")
+ echo " ${ACCENT}${BOLD}🐳 E2E Orchestrator tests (Docker)${NC}"
+ echo ""
+ docker compose -f tests/e2e/docker-compose-orchestrator.yml run --build --rm runner
+ local orch_exit=$?
+ if [ $orch_exit -ne 0 ]; then
+ docker compose -f tests/e2e/docker-compose-orchestrator.yml logs pinchtab | tail -n 50 || true
+ docker compose -f tests/e2e/docker-compose-orchestrator.yml logs pinchtab-bridge | tail -n 50 || true
+ fi
+ docker compose -f tests/e2e/docker-compose-orchestrator.yml down -v 2>/dev/null
+ exit $orch_exit
+ ;;
"e2e recent")
echo " ${ACCENT}${BOLD}🐳 E2E Recent tests (Docker)${NC}"
echo ""
diff --git a/docs/guides/contributing.md b/docs/guides/contributing.md
index 900fa3b1..7362a25c 100644
--- a/docs/guides/contributing.md
+++ b/docs/guides/contributing.md
@@ -13,6 +13,9 @@ This is the canonical contributor and development guide for PinchTab.
| Chrome/Chromium | Latest | Browser automation |
| macOS, Linux, or WSL2 | Current | OS support |
+For dashboard work, use Bun 1.2+.
+Older Bun releases fail on the checked-in `dashboard/bun.lock` during clean installs with `--frozen-lockfile`.
+
### Recommended Setup
- **macOS**: Homebrew for package management
diff --git a/docs/guides/remote-bridge-orchestrator.md b/docs/guides/remote-bridge-orchestrator.md
new file mode 100644
index 00000000..9afef2ca
--- /dev/null
+++ b/docs/guides/remote-bridge-orchestrator.md
@@ -0,0 +1,304 @@
+# Remote Bridge With Orchestrator
+
+Use this guide when:
+
+- the PinchTab orchestrator runs on one machine
+- a PinchTab bridge server runs on another machine
+- you want agents to keep talking to the orchestrator while the browser work happens remotely
+
+This is now a supported orchestration mode through:
+
+```text
+POST /instances/attach-bridge
+```
+
+The orchestrator does not launch processes on the remote machine. It attaches to an already running bridge and routes requests to its registered origin.
+
+---
+
+## Mental Model
+
+There are now three different models:
+
+- local managed instance: the orchestrator launches and owns a local bridge process
+- attached Chrome: the orchestrator registers an external CDP browser with `POST /instances/attach`
+- attached bridge: the orchestrator registers an external PinchTab bridge with `POST /instances/attach-bridge`
+
+For remote bridge attachment, the control flow is:
+
+```text
+agent -> orchestrator -> attached remote bridge -> Chrome
+```
+
+The main practical rule is:
+
+- clients talk to the orchestrator
+- the orchestrator talks to the remote bridge
+
+---
+
+## Good Use Cases
+
+### Shared headed browser host
+
+- machine A runs the orchestrator and dashboard
+- machine B runs one or more headed bridge servers
+- agents keep a single control plane on machine A
+- actual browser rendering happens on machine B
+
+This is useful when you want one orchestration surface but do not want to run headed Chrome on every developer machine.
+
+### Region-local browser worker
+
+- machine A runs the orchestrator
+- machine B runs a bridge in the same LAN, VPC, or region as the target sites
+- the orchestrator attaches that bridge and routes work there
+
+This is useful when latency, egress location, or network topology matters.
+
+---
+
+## What The Feature Does
+
+`POST /instances/attach-bridge`:
+
+- validates the bridge URL against `security.attach`
+- checks the remote bridge health endpoint before registering it
+- stores the bridge origin as the canonical instance URL
+- optionally stores a per-bridge bearer token used by the orchestrator
+- lets normal orchestrator routes proxy to that bridge
+
+This feature also updates routing behavior:
+
+- proxying no longer assumes `localhost` for every instance
+- the orchestrator now routes to the registered instance origin
+- proxy targets are restricted to origins that belong to registered instances
+
+That last point matters for safety: the proxy is not opened up to arbitrary destinations.
+
+---
+
+## Config
+
+Remote bridge attachment reuses the existing attach policy:
+
+```json
+{
+ "security": {
+ "attach": {
+ "enabled": true,
+ "allowHosts": ["10.0.12.24", "bridge.internal"],
+ "allowSchemes": ["ws", "wss", "http", "https"]
+ }
+ }
+}
+```
+
+Important notes:
+
+- `security.attach.enabled` must be `true`
+- `allowHosts` must include the remote bridge host
+- `allowSchemes` must include `http` or `https` for bridge attachment
+- `ws` and `wss` are still used for CDP attachment
+
+If you leave `allowSchemes` as only `ws,wss`, `attach-bridge` will be rejected.
+
+---
+
+## Step 1: Start The Remote Bridge
+
+On the remote machine:
+
+```bash
+PINCHTAB_BIND=0.0.0.0 \
+PINCHTAB_PORT=9868 \
+PINCHTAB_TOKEN=bridge-secret-token \
+pinchtab bridge
+```
+
+Example bridge origin:
+
+```text
+http://10.0.12.24:9868
+```
+
+The bridge should already be healthy and reachable before you attach it.
+
+---
+
+## Step 2: Verify The Bridge Directly
+
+From the orchestrator machine:
+
+```bash
+curl -H "Authorization: Bearer bridge-secret-token" \
+ http://10.0.12.24:9868/health
+```
+
+You should get a `200 OK`.
+
+`attach-bridge` also performs its own health probe, but checking directly first makes network and auth issues easier to debug.
+
+---
+
+## Step 3: Attach The Bridge To The Orchestrator
+
+Against the orchestrator:
+
+```bash
+curl -X POST http://127.0.0.1:9867/instances/attach-bridge \
+ -H "Authorization: Bearer orchestrator-token" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "bridge-eu-west-1",
+ "baseUrl": "http://10.0.12.24:9868",
+ "token": "bridge-secret-token"
+ }'
+```
+
+Response shape:
+
+```json
+{
+ "id": "inst_0a89a5bb",
+ "profileId": "prof_278be873",
+ "profileName": "bridge-eu-west-1",
+ "port": "",
+ "url": "http://10.0.12.24:9868",
+ "headless": false,
+ "status": "running",
+ "attached": true,
+ "attachType": "bridge"
+}
+```
+
+Fields to notice:
+
+- `attached: true`
+- `attachType: "bridge"`
+- `url` is the registered bridge origin
+
+---
+
+## Step 4: Confirm It Is Registered
+
+```bash
+curl -H "Authorization: Bearer orchestrator-token" \
+ http://127.0.0.1:9867/instances
+```
+
+The attached bridge appears in the normal instance list. The orchestrator treats it as a running instance for routing and fleet operations.
+
+---
+
+## Step 5: Use Normal Orchestrator Routes
+
+Once attached, clients keep talking to the orchestrator.
+
+Examples:
+
+```bash
+curl -H "Authorization: Bearer orchestrator-token" \
+ http://127.0.0.1:9867/instances/<instanceId>/tabs
+```
+
+```bash
+curl -X POST http://127.0.0.1:9867/instances/<instanceId>/tabs/open \
+ -H "Authorization: Bearer orchestrator-token" \
+ -H "Content-Type: application/json" \
+ -d '{"url":"https://pinchtab.com"}'
+```
+
+```bash
+curl -H "Authorization: Bearer orchestrator-token" \
+ http://127.0.0.1:9867/tabs/<tabId>/snapshot
+```
+
+If your active strategy uses shorthand routing, those routes can also land on an attached bridge because instance selection now works from canonical instance URLs rather than only local ports.
+
+---
+
+## Authentication Model
+
+There are two separate auth hops:
+
+1. client to orchestrator
+2. orchestrator to attached bridge
+
+That means you can use different tokens:
+
+- clients send `Authorization: Bearer orchestrator-token`
+- the orchestrator sends `Authorization: Bearer bridge-secret-token` to the remote bridge
+
+Clients do not need to know the bridge token. The orchestrator stores it as instance attachment metadata and injects it on outgoing bridge requests.
+
+---
+
+## Lifecycle Semantics
+
+Attached bridges are externally owned.
+
+That means:
+
+- the orchestrator did not launch the remote bridge process
+- `attach-bridge` registers routing metadata, not remote process ownership
+
+Current behavior:
+
+- local `Launch()` remains local-only
+- stopping an attached bridge removes it from the orchestrator
+- for attached bridges, the orchestrator also makes a best-effort `POST /shutdown` call before unregistering
+- starting an attached non-bridge instance through the orchestrator is not supported
+
+If you need true remote process launch, that is a different problem and would need a transport such as SSH, an agent, or a scheduler-backed worker system.
+
+---
+
+## Safety Constraints
+
+Remote bridge support is useful, but it widens the trust boundary.
+
+Recommended practice:
+
+- keep `allowHosts` narrow
+- allow only the schemes you actually need
+- use a dedicated bridge token
+- prefer `https` when the bridge crosses an untrusted network
+- keep the bridge itself behind network ACLs or a tunnel when possible
+
+The orchestrator proxy is intentionally restricted:
+
+- it proxies only to registered instance origins
+- it does not accept arbitrary caller-controlled targets
+
+That prevents the remote bridge feature from turning into a generic SSRF mechanism.
+
+---
+
+## Limitations
+
+What this feature does not do:
+
+- it does not launch bridge processes on remote machines
+- it does not sync profile directories between hosts
+- it does not migrate tabs or browser state across machines
+- it does not discover workers automatically
+
+The supported model is:
+
+- start bridge remotely
+- attach it explicitly
+- route traffic through the orchestrator
+
+---
+
+## Summary
+
+Use `POST /instances/attach-bridge` when you want:
+
+- orchestrator on machine A
+- bridge on machine B
+- agents still talking only to machine A
+- remote browser work without remote process-management complexity
+
+This is the right feature when you want distributed execution with a single control plane.
diff --git a/docs/guides/security.md b/docs/guides/security.md
index 1374263f..f77661af 100644
--- a/docs/guides/security.md
+++ b/docs/guides/security.md
@@ -122,9 +122,11 @@ Attach is an advanced feature for registering an externally managed Chrome insta
If you enable attach:
- keep `allowHosts` narrowly scoped
-- prefer local-only hosts unless external Chrome targets are intentional
+- prefer local-only hosts unless external Chrome targets or remote bridges are intentional
- only attach to browsers and CDP endpoints you trust
+If you use `POST /instances/attach-bridge`, `security.attach.allowSchemes` must also include `http` or `https`.
+
## IDPI
IDPI stands for Indirect Prompt Injection defense.
diff --git a/docs/guides/tailscale-bridge-orchestrator.md b/docs/guides/tailscale-bridge-orchestrator.md
new file mode 100644
index 00000000..e9c9a2a9
--- /dev/null
+++ b/docs/guides/tailscale-bridge-orchestrator.md
@@ -0,0 +1,371 @@
+# A Tailscale Bridge Story: One Orchestrator, Remote Browsers
+
+There is a simple distributed PinchTab shape that turns out to be very practical:
+
+- machine A runs the PinchTab orchestrator and dashboard
+- machine B runs a PinchTab bridge
+- both machines are connected through Tailscale
+- agents keep talking to machine A
+- browser work actually happens on machine B
+
+That gives you one control plane and multiple places where browser execution can live.
+
+![Placeholder diagram for a Tailscale-connected orchestrator and remote bridge](../media/tailscale-bridge-topology-placeholder.svg)
+
+```mermaid
+flowchart LR
+ Agent["Agent / client"] --> AAPI
+
+ subgraph A["Machine A"]
+ AAPI["PinchTab orchestrator API"]
+ ADash["Dashboard / control plane"]
+ AAPI --- ADash
+ end
+
+ subgraph TS["Tailscale tailnet"]
+ TNet["Private machine-to-machine path"]
+ end
+
+ subgraph B["Machine B"]
+ BBridge["PinchTab bridge"]
+ BChrome["Chrome / browser tabs"]
+ BBridge --> BChrome
+ end
+
+ AAPI -->|"attach-bridge + proxied routes"| TNet
+ TNet -->|"HTTP bridge directly\nor HTTPS via reverse proxy"| BBridge
+```
+
+This post walks through the exact setup, the mistakes that are easy to make, and the key distinction between `http` and `https` when attaching a remote bridge.
+
+## Scenarios
+
+There are several practical ways to use this setup.
+
+### Shared Browser Host
+
+- machine A runs the orchestrator and dashboard
+- machine B runs one or more headed bridges
+- users and agents keep talking to machine A
+- the real browser windows live on machine B
+
+This is the easiest way to centralize browser execution without forcing every user to run Chrome locally.
+
+### Personal Control Plane, Remote Worker
+
+- a developer keeps the orchestrator on their own machine
+- a second machine runs the bridge with more CPU, RAM, or a better browser environment
+- browser work moves off the local laptop or desktop, but control stays local
+
+This is useful when you want the UI and control loop close to you, but the heavy browser work somewhere else.
+
+### Region-Local Execution
+
+- machine A is the main control plane
+- machine B is closer to the target websites, APIs, or internal network
+- the orchestrator attaches the bridge and routes browser work there
+
+This is useful when latency, geography, or network placement matters more than where the operator is sitting.
+
+### Dedicated Automation Node
+
+- one bridge machine is reserved for scraping, PDF generation, screenshots, or long-running automation
+- the orchestrator attaches it as a normal instance
+- clients still use the same API surface on machine A
+
+This keeps automation-specific browser load off the main orchestrator machine.
+
+### Headed Browser Pool Across A Tailnet
+
+- several machines on the tailnet each run a bridge
+- one orchestrator attaches them
+- the orchestrator becomes the single control surface for a small remote browser fleet
+
+This gives you a lightweight distributed browser setup without adding a full remote execution platform.
+
+### HTTPS Fronted Remote Bridge
+
+- machine B runs a bridge
+- a reverse proxy or Tailscale Serve terminates TLS in front of it
+- the orchestrator attaches the bridge through an `https://` origin
+
+This is useful when you want the remote bridge reachable as a normal TLS endpoint instead of a raw HTTP port.
+
+One thing all of these scenarios share:
+
+- the orchestrator attaches to an already running bridge
+- it does not remotely start the process on machine B
+
+## The Mental Model
+
+The control path looks like this:
+
+```text
+agent -> orchestrator on machine A -> bridge on machine B -> browser on machine B
+```
+
+The orchestrator does not SSH into the remote machine and does not launch the remote process. It simply attaches to an already running PinchTab bridge with:
+
+```text
+POST /instances/attach-bridge
+```
+
+Once attached, the orchestrator proxies normal instance and tab routes to that bridge.
+
+That means:
+
+- clients only need to know machine A
+- machine A needs to be able to reach machine B
+- machine B needs to expose a bridge origin that machine A can call
+
+## Why Tailscale Works Well
+
+Tailscale is a good fit for this model because you do not need to publish the bridge to the public internet.
+
+You do need the bridge to be reachable inside the tailnet, which means:
+
+- the bridge must not be bound only to `127.0.0.1`
+- the remote machine must allow inbound traffic on the chosen bridge port from Tailscale peers
+- the orchestrator must use the bridge's Tailscale IP or MagicDNS hostname
+
+No normal WAN port forwarding is required.
+
+## Step 1: Start The Bridge On Machine B
+
+On machine B, start the bridge so it listens on a Tailscale-reachable address:
+
+```bash
+PINCHTAB_BIND=0.0.0.0 \
+PINCHTAB_PORT=9867 \
+PINCHTAB_TOKEN=bridge-secret-token \
+pinchtab bridge
+```
+
+If you are using a daemon or service manager, the same rule applies: the service environment must include `PINCHTAB_BIND=0.0.0.0`.
+
+The first common mistake is to leave the bridge on the default localhost bind. When that happens:
+
+- `curl http://127.0.0.1:9867/health` works on machine B
+- `curl http://machine-b.tailnet.ts.net:9867/health` fails from machine A
+
+That is not an auth failure. It means the bridge is only listening on localhost.
+
+## Step 2: Prove Machine A Can Reach Machine B
+
+Before attaching anything, verify the bridge directly from machine A:
+
+```bash
+curl -H "Authorization: Bearer bridge-secret-token" \
+ http://machine-b.tailnet.ts.net:9867/health
+```
+
+If this fails, stop there and fix connectivity first.
+
+Useful interpretations:
+
+- `Connection refused`
+ - machine A can reach machine B, but nothing is listening on that port
+ - usually wrong port or localhost-only bind on machine B
+- `401 unauthorized`
+ - connectivity is correct, but the token is wrong or missing
+- `200 OK`
+ - the bridge is reachable and ready to attach
+
+## Step 3: Configure The Orchestrator On Machine A
+
+Remote bridge attachment is governed by the orchestrator's existing attach policy:
+
+```json
+{
+ "security": {
+ "attach": {
+ "enabled": true,
+ "allowHosts": [
+ "machine-b.tailnet.ts.net"
+ ],
+ "allowSchemes": [
+ "ws",
+ "wss",
+ "http",
+ "https"
+ ]
+ }
+ }
+}
+```
+
+Important details:
+
+- `allowHosts` must contain the exact hostname or IP you plan to use in `baseUrl`
+- `allowSchemes` must include `http` or `https` for `attach-bridge`
+- `ws` and `wss` remain relevant for CDP attach, not bridge attach
+
+The second common mistake is to accidentally configure `allowHosts` as one comma-separated string instead of a real JSON array. It must be:
+
+```json
+["machine-b.tailnet.ts.net", "machine-c.tailnet.ts.net"]
+```
+
+not:
+
+```json
+["machine-b.tailnet.ts.net,machine-c.tailnet.ts.net"]
+```
+
+After changing config, restart the orchestrator daemon on machine A.
+
+## Step 4: Attach The Bridge
+
+Once direct health checks work from machine A, attach the bridge to the orchestrator:
+
+```bash
+curl -X POST http://127.0.0.1:9867/instances/attach-bridge \
+ -H "Authorization: Bearer orchestrator-token" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "machine-b-bridge",
+ "baseUrl": "http://machine-b.tailnet.ts.net:9867",
+ "token": "bridge-secret-token"
+ }'
+```
+
+Expected response shape:
+
+```json
+{
+ "id": "inst_0a89a5bb",
+ "profileId": "prof_278be873",
+ "profileName": "machine-b-bridge",
+ "port": "",
+ "url": "http://machine-b.tailnet.ts.net:9867",
+ "status": "running",
+ "attached": true,
+ "attachType": "bridge"
+}
+```
+
+That tells you the orchestrator registered a running attached bridge instance and will now route traffic to it.
+
+## Step 5: Control The Remote Browser From Machine A
+
+After attachment, clients keep talking only to the orchestrator on machine A.
+
+List instances:
+
+```bash
+curl -H "Authorization: Bearer orchestrator-token" \
+ http://127.0.0.1:9867/instances
+```
+
+Open a tab on the remote bridge:
+
+```bash
+curl -X POST http://127.0.0.1:9867/instances/<instanceId>/tabs/open \
+ -H "Authorization: Bearer orchestrator-token" \
+ -H "Content-Type: application/json" \
+ -d '{"url":"https://example.com"}'
+```
+
+Read a tab through the orchestrator:
+
+```bash
+curl -H "Authorization: Bearer orchestrator-token" \
+ http://127.0.0.1:9867/tabs/<tabId>/text?format=text
+```
+
+This is the key operational benefit: the work is happening remotely, but the control point stays local and centralized.
+
+## HTTP Versus HTTPS
+
+This is the part that causes the most confusion.
+
+### Direct Bridge Port: Usually HTTP
+
+If you start the bridge like this:
+
+```bash
+PINCHTAB_BIND=0.0.0.0 PINCHTAB_PORT=9867 pinchtab bridge
+```
+
+the bridge itself is usually speaking plain HTTP on that port.
+
+That means this can work:
+
+```bash
+http://machine-b.tailnet.ts.net:9867/health
+```
+
+while this fails:
+
+```bash
+https://machine-b.tailnet.ts.net:9867/health
+```
+
+If you point `curl` at `https://...:9867` and get a TLS protocol error, that means you are speaking HTTPS to an HTTP listener.
+
+### HTTPS Is Supported For Attachment
+
+The orchestrator does support attaching to an `https` bridge origin.
+
+But that only makes sense if there is actually a TLS endpoint in front of the bridge, for example:
+
+- Caddy
+- Nginx
+- Traefik
+- Tailscale Serve or Funnel
+
+In that setup, the shape is:
+
+```text
+https://machine-b.tailnet.ts.net -> http://127.0.0.1:9867
+```
+
+Then the attach request should use:
+
+```json
+"baseUrl": "https://machine-b.tailnet.ts.net"
+```
+
+So the rule is:
+
+- direct bridge port: usually `http://host:port`
+- reverse-proxied TLS endpoint: `https://host` or `https://host:port`
+
+## Two Separate Tokens
+
+There are two auth hops in this architecture:
+
+1. client to orchestrator
+2. orchestrator to bridge
+
+That means you can use different tokens:
+
+- users and agents send the orchestrator token to machine A
+- machine A sends the bridge token to machine B
+
+Clients do not need the bridge token once the bridge is attached.
+
+## What You Gain
+
+This setup gives you a nice operating model:
+
+- one orchestrator can control multiple remote bridges
+- browser execution can happen on different machines in the tailnet
+- clients, dashboards, and agents do not need to know where each browser is running
+- instance and tab routes stay consistent even when execution is remote
+
+That is the real value of remote bridge attachment: you can move browser work to the right machine without changing the control surface that agents use.
+
+## Troubleshooting Checklist
+
+If attachment fails, walk this list in order:
+
+1. Can machine A reach `baseUrl/health` directly?
+2. Is machine B bound to `0.0.0.0` instead of only `127.0.0.1`?
+3. Is the bridge actually listening on the port you think it is?
+4. Does the bridge require a token, and are you sending the right one?
+5. Does machine A's `allowHosts` include the exact host you used in `baseUrl`?
+6. Does machine A's `allowSchemes` include `http` or `https`?
+7. Are you using `http` for a direct bridge port and `https` only for a real TLS endpoint?
+
+Once those are correct, `attach-bridge` becomes a straightforward registration step instead of a networking puzzle.
diff --git a/docs/index.json b/docs/index.json
index eb00ace5..0810692f 100644
--- a/docs/index.json
+++ b/docs/index.json
@@ -13,6 +13,8 @@
"guides/security.md",
"guides/mcp-agents.md",
"guides/attach-chrome.md",
+ "guides/remote-bridge-orchestrator.md",
+ "guides/tailscale-bridge-orchestrator.md",
"guides/multi-instance.md",
"guides/identifying-instances.md",
"guides/memory-monitoring.md",
diff --git a/docs/reference/config.md b/docs/reference/config.md
index 4cac7d7e..14e3743e 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -356,7 +356,7 @@ Valid enum values:
| `instanceDefaults.tabEvictionPolicy` | `reject`, `close_oldest`, `close_lru` (default) |
| `multiInstance.strategy` | `simple`, `explicit`, `simple-autorestart`, `always-on` (default) |
| `multiInstance.allocationPolicy` | `fcfs`, `round_robin`, `random` |
-| `security.attach.allowSchemes` | `ws`, `wss` |
+| `security.attach.allowSchemes` | `ws`, `wss`, `http`, `https` |
## Notes
diff --git a/docs/reference/instances.md b/docs/reference/instances.md
index d3e1efff..0dfeb2cf 100644
--- a/docs/reference/instances.md
+++ b/docs/reference/instances.md
@@ -229,3 +229,33 @@ Notes:
- there is no CLI attach command
- attach is allowed only when enabled in config under `security.attach`
+
+## Attach An Existing Bridge
+
+```bash
+curl -X POST http://localhost:9867/instances/attach-bridge \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name":"shared-bridge",
+ "baseUrl":"http://10.0.12.24:9868",
+ "token":"bridge-secret-token"
+ }'
+# Response
+{
+ "id": "inst_0a89a5bb",
+ "profileId": "prof_278be873",
+ "profileName": "shared-bridge",
+ "port": "",
+ "url": "http://10.0.12.24:9868",
+ "status": "running",
+ "attached": true,
+ "attachType": "bridge"
+}
+```
+
+Notes:
+
+- `baseUrl` must point at a running PinchTab bridge
+- the orchestrator performs a health check before registering it
+- `security.attach.allowHosts` must allow the bridge host
+- `security.attach.allowSchemes` must include `http` or `https` for bridge attachment
diff --git a/internal/api/types/types.go b/internal/api/types/types.go
index bf66e8cb..9fddadd2 100644
--- a/internal/api/types/types.go
+++ b/internal/api/types/types.go
@@ -33,12 +33,14 @@ type Instance struct {
ProfileID string `json:"profileId"`
ProfileName string `json:"profileName"`
Port string `json:"port"` // Note: string not int
+ URL string `json:"url,omitempty"`
Headless bool `json:"headless"`
Status string `json:"status"` // starting/running/stopping/stopped/error
StartTime time.Time `json:"startTime"`
Error string `json:"error,omitempty"`
- Attached bool `json:"attached"` // True if attached to external Chrome
- CdpURL string `json:"cdpUrl,omitempty"` // CDP WebSocket URL (for attached instances)
+ Attached bool `json:"attached"` // True if attached rather than locally launched
+ AttachType string `json:"attachType,omitempty"`
+ CdpURL string `json:"cdpUrl,omitempty"` // CDP WebSocket URL (for CDP-attached instances)
}
// Agent represents a connected AI agent.
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index fa701bd4..81d3504e 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -120,16 +120,18 @@ type AnalyticsReport struct {
}
type Instance struct {
- ID string `json:"id"` // Hash-based ID: inst_XXXXXXXX
- ProfileID string `json:"profileId"` // Hash-based profile ID: prof_XXXXXXXX
- ProfileName string `json:"profileName"` // Human-readable profile name (for display only)
- Port string `json:"port"` // Internal: instance port
- Headless bool `json:"headless"` // Mode: headless vs headed
- Status string `json:"status"` // Status: starting/running/stopping/stopped/error
- StartTime time.Time `json:"startTime"` // When instance was created
- Error string `json:"error,omitempty"` // Error message if status=error
- Attached bool `json:"attached"` // True if attached to external Chrome (not launched)
- CdpURL string `json:"cdpUrl,omitempty"` // CDP WebSocket URL (for attached instances)
+ ID string `json:"id"` // Hash-based ID: inst_XXXXXXXX
+ ProfileID string `json:"profileId"` // Hash-based profile ID: prof_XXXXXXXX
+ ProfileName string `json:"profileName"` // Human-readable profile name (for display only)
+ Port string `json:"port"` // Internal: instance port
+ URL string `json:"url,omitempty"` // Canonical base URL for bridge-backed instances
+ Headless bool `json:"headless"` // Mode: headless vs headed
+ Status string `json:"status"` // Status: starting/running/stopping/stopped/error
+ StartTime time.Time `json:"startTime"` // When instance was created
+ Error string `json:"error,omitempty"` // Error message if status=error
+ Attached bool `json:"attached"` // True if attached rather than locally launched
+ AttachType string `json:"attachType,omitempty"` // "cdp" or "bridge" for attached instances
+ CdpURL string `json:"cdpUrl,omitempty"` // CDP WebSocket URL (for CDP-attached instances)
}
type InstanceTab struct {
diff --git a/internal/config/validate.go b/internal/config/validate.go
index b4e6fcbb..df76050b 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -132,7 +132,7 @@ func ValidateFileConfig(fc *FileConfig) []error {
if !isValidAttachScheme(scheme) {
errs = append(errs, ValidationError{
Field: "security.attach.allowSchemes",
- Message: fmt.Sprintf("invalid value %q (must be ws or wss)", scheme),
+ Message: fmt.Sprintf("invalid value %q (must be ws, wss, http, or https)", scheme),
})
}
}
@@ -243,7 +243,7 @@ func isValidAllocationPolicy(policy string) bool {
func isValidAttachScheme(scheme string) bool {
switch scheme {
- case "ws", "wss":
+ case "ws", "wss", "http", "https":
return true
default:
return false
@@ -320,5 +320,5 @@ func ValidAllocationPolicies() []string {
// ValidAttachSchemes returns all valid attach URL schemes.
func ValidAttachSchemes() []string {
- return []string{"ws", "wss"}
+ return []string{"ws", "wss", "http", "https"}
}
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
index 30d5ddc5..548da96a 100644
--- a/internal/config/validate_test.go
+++ b/internal/config/validate_test.go
@@ -243,8 +243,11 @@ func TestValidateFileConfig_InvalidAttachScheme(t *testing.T) {
{[]string{"ws"}, false},
{[]string{"wss"}, false},
{[]string{"ws", "wss"}, false},
- {[]string{"http"}, true},
- {[]string{"ws", "https"}, true},
+ {[]string{"http"}, false},
+ {[]string{"https"}, false},
+ {[]string{"ws", "https"}, false},
+ {[]string{"ftp"}, true},
+ {[]string{"ws", "tcp"}, true},
}
for _, tt := range tests {
diff --git a/internal/handlers/download.go b/internal/handlers/download.go
index 932c7a17..68913939 100644
--- a/internal/handlers/download.go
+++ b/internal/handlers/download.go
@@ -163,6 +163,13 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
return
}
+ // Re-check scheme before navigation (validateDownloadURL already enforces this,
+ // but inline check satisfies CodeQL SSRF analysis).
+ if parsed, err := url.Parse(dlURL); err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
+ web.Error(w, 400, fmt.Errorf("invalid download URL scheme"))
+ return
+ }
+
// Navigate the temp tab to the URL — uses browser's cookie jar and stealth.
if err := chromedp.Run(tCtx, chromedp.Navigate(dlURL)); err != nil {
if redirectBlocked.Load() {
diff --git a/internal/handlers/proxy_ws.go b/internal/handlers/proxy_ws.go
index 22ab359c..f91579fc 100644
--- a/internal/handlers/proxy_ws.go
+++ b/internal/handlers/proxy_ws.go
@@ -2,28 +2,38 @@ package handlers
import (
"bufio"
+ "crypto/tls"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/textproto"
- "strings"
+ "net/url"
)
// ProxyWebSocket tunnels WebSocket connections with proper HTTP headers
func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
- wsTarget := strings.TrimPrefix(targetURL, "http://")
- wsTarget = strings.TrimPrefix(wsTarget, "https://")
+ parsed, err := url.Parse(targetURL)
+ if err != nil {
+ http.Error(w, "invalid backend target", http.StatusBadGateway)
+ slog.Error("ws proxy: invalid target", "target", targetURL, "err", err)
+ return
+ }
- host := wsTarget
- path := "/"
- if idx := strings.Index(wsTarget, "/"); idx >= 0 {
- host = wsTarget[:idx]
- path = wsTarget[idx:]
+ host := parsed.Host
+ path := parsed.RequestURI()
+ if path == "" {
+ path = "/"
}
- backend, err := net.Dial("tcp", host)
+ var backend net.Conn
+ switch parsed.Scheme {
+ case "https", "wss":
+ backend, err = tls.Dial("tcp", host, &tls.Config{ServerName: parsed.Hostname()})
+ default:
+ backend, err = net.Dial("tcp", host)
+ }
if err != nil {
http.Error(w, "backend unavailable", http.StatusBadGateway)
slog.Error("ws proxy: backend dial failed", "target", host, "err", err)
diff --git a/internal/instance/instance_test.go b/internal/instance/instance_test.go
index 7749699a..476076a6 100644
--- a/internal/instance/instance_test.go
+++ b/internal/instance/instance_test.go
@@ -27,6 +27,7 @@ func (m *mockLauncher) Launch(name, port string, headless bool) (*bridgepkg.Inst
ID: fmt.Sprintf("inst_%d", m.nextID),
ProfileName: name,
Port: port,
+ URL: "http://localhost:" + port,
Headless: headless,
Status: "running",
}
@@ -61,6 +62,11 @@ func (f *mockFetcher) FetchTabs(instanceURL string) ([]bridgepkg.InstanceTab, er
func (f *mockFetcher) AddTab(instancePort, tabID, url string) {
key := "http://localhost:" + instancePort
+ f.AddTabForURL(key, tabID, url)
+}
+
+func (f *mockFetcher) AddTabForURL(instanceURL, tabID, url string) {
+ key := instanceURL
f.tabsByURL[key] = append(f.tabsByURL[key], bridgepkg.InstanceTab{
ID: tabID,
URL: url,
@@ -186,6 +192,26 @@ func TestLocator_TabNotFound(t *testing.T) {
}
}
+func TestLocator_UsesInstanceURLWhenPresent(t *testing.T) {
+ launcher := newMockLauncher()
+ fetcher := newMockFetcher()
+ repo := instance.NewRepository(launcher)
+ locator := instance.NewLocator(repo, fetcher)
+
+ inst, _ := repo.Launch("remote", "9868", true)
+ inst.URL = "https://bridge.example.com:9868"
+ repo.Add(inst)
+ fetcher.AddTabForURL("https://bridge.example.com:9868", "tab_remote", "https://pinchtab.com")
+
+ found, err := locator.FindInstanceByTabID("tab_remote")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if found.ID != inst.ID {
+ t.Fatalf("expected %s, got %s", inst.ID, found.ID)
+ }
+}
+
func TestLocator_InvalidateRemovesCacheEntry(t *testing.T) {
launcher := newMockLauncher()
fetcher := newMockFetcher()
diff --git a/internal/instance/locator.go b/internal/instance/locator.go
index 5621fc12..f747b12a 100644
--- a/internal/instance/locator.go
+++ b/internal/instance/locator.go
@@ -48,7 +48,10 @@ func (l *Locator) FindInstanceByTabID(tabID string) (*bridge.Instance, error) {
// Slow path: query all running bridges.
running := l.repo.Running()
for _, inst := range running {
- url := fmt.Sprintf("http://localhost:%s", inst.Port)
+ url := inst.URL
+ if url == "" {
+ url = fmt.Sprintf("http://localhost:%s", inst.Port)
+ }
tabs, err := l.fetcher.FetchTabs(url)
if err != nil {
slog.Debug("locator: failed to fetch tabs", "instance", inst.ID, "err", err)
@@ -103,7 +106,10 @@ func (l *Locator) RefreshAll() {
running := l.repo.Running()
for _, inst := range running {
- url := fmt.Sprintf("http://localhost:%s", inst.Port)
+ url := inst.URL
+ if url == "" {
+ url = fmt.Sprintf("http://localhost:%s", inst.Port)
+ }
tabs, err := l.fetcher.FetchTabs(url)
if err != nil {
slog.Debug("locator: refresh failed", "instance", inst.ID, "err", err)
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index 69c00678..dd4aab28 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -28,6 +28,7 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("POST /instances/start", o.handleStartInstance)
mux.HandleFunc("POST /instances/launch", o.handleLaunchByName)
mux.HandleFunc("POST /instances/attach", o.handleAttachInstance)
+ mux.HandleFunc("POST /instances/attach-bridge", o.handleAttachBridge)
mux.HandleFunc("POST /instances/{id}/start", o.handleStartByInstanceID)
mux.HandleFunc("POST /instances/{id}/stop", o.handleStopByInstanceID)
mux.HandleFunc("GET /instances/{id}/logs", o.handleLogsByID)
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
index de252f5e..20907a22 100644
--- a/internal/orchestrator/handlers_instances.go
+++ b/internal/orchestrator/handlers_instances.go
@@ -3,9 +3,9 @@ package orchestrator
import (
"encoding/json"
"fmt"
- "net"
"net/http"
"net/url"
+ "strings"
"time"
"github.com/pinchtab/pinchtab/internal/web"
@@ -113,16 +113,26 @@ func (o *Orchestrator) handleStartByInstanceID(w http.ResponseWriter, r *http.Re
headless := inst.Headless
o.mu.RUnlock()
+ if inst.Attached && inst.AttachType != "bridge" {
+ web.Error(w, 409, fmt.Errorf("attached instance %q cannot be started by the orchestrator", id))
+ return
+ }
+
if active {
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", port),
- Path: "/ensure-chrome",
+ targetURL, targetErr := o.instancePathURL(inst, "/ensure-chrome", "")
+ if targetErr != nil {
+ web.Error(w, 502, targetErr)
+ return
}
o.proxyToURL(w, r, targetURL)
return
}
+ if inst.Attached {
+ web.Error(w, 409, fmt.Errorf("attached instance %q cannot be started by the orchestrator", id))
+ return
+ }
+
started, err := o.Launch(profileName, port, headless, nil)
if err != nil {
statusCode := classifyLaunchError(err)
@@ -268,7 +278,7 @@ func (o *Orchestrator) handleInstanceTabs(w http.ResponseWriter, r *http.Request
return
}
- tabs, err := o.fetchTabs(inst.URL)
+ tabs, err := o.fetchTabs(inst)
if err != nil {
web.Error(w, 502, fmt.Errorf("failed to fetch tabs for instance %q: %w", id, err))
return
@@ -317,15 +327,90 @@ func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Reque
inst, err := o.Attach(name, req.CdpURL)
if err != nil {
- web.Error(w, 500, err)
+ web.Error(w, classifyLaunchError(err), err)
return
}
web.JSON(w, 201, inst)
}
-// validateAttachURL checks if attach is enabled and the CDP URL is allowed.
-func (o *Orchestrator) validateAttachURL(cdpURL string) error {
+func (o *Orchestrator) handleAttachBridge(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ BaseURL string `json:"baseUrl"`
+ Name string `json:"name,omitempty"`
+ Token string `json:"token,omitempty"`
+ }
+
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ return
+ }
+ if req.BaseURL == "" {
+ web.Error(w, 400, fmt.Errorf("baseUrl is required"))
+ return
+ }
+ if err := o.validateAttachURL(req.BaseURL); err != nil {
+ web.Error(w, 403, err)
+ return
+ }
+ if err := o.probeAttachBridge(req.BaseURL, req.Token); err != nil {
+ web.Error(w, 502, err)
+ return
+ }
+
+ name := req.Name
+ if name == "" {
+ name = fmt.Sprintf("bridge-%d", time.Now().UnixNano())
+ }
+
+ inst, err := o.AttachBridge(name, req.BaseURL, req.Token)
+ if err != nil {
+ web.Error(w, classifyLaunchError(err), err)
+ return
+ }
+ web.JSON(w, 201, inst)
+}
+
+// probeAttachBridge checks that a remote bridge is reachable.
+// The baseURL MUST have been validated by validateAttachURL before calling this.
+func (o *Orchestrator) probeAttachBridge(baseURL, token string) error {
+ parsed, err := url.Parse(strings.TrimRight(baseURL, "/"))
+ if err != nil {
+ return fmt.Errorf("invalid bridge baseUrl: %w", err)
+ }
+
+ // Re-validate scheme inside this function so the safety check is visible
+ // to static analysis (CodeQL SSRF). validateAttachURL already enforces
+ // the allowlist, but CodeQL can't trace across function boundaries.
+ switch parsed.Scheme {
+ case "http", "https":
+ // allowed
+ default:
+ return fmt.Errorf("unsupported bridge scheme %q", parsed.Scheme)
+ }
+
+ healthURL := parsed.Scheme + "://" + parsed.Host + "/health"
+
+ req, err := http.NewRequest(http.MethodGet, healthURL, nil)
+ if err != nil {
+ return fmt.Errorf("build bridge health request: %w", err)
+ }
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := o.client.Do(req)
+ if err != nil {
+ return fmt.Errorf("bridge health check failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("bridge health check returned HTTP %d", resp.StatusCode)
+ }
+ return nil
+}
+
+// validateAttachURL checks if attach is enabled and the external URL is allowed.
+func (o *Orchestrator) validateAttachURL(rawURL string) error {
if o.runtimeCfg == nil {
return fmt.Errorf("attach not configured")
}
@@ -334,9 +419,9 @@ func (o *Orchestrator) validateAttachURL(cdpURL string) error {
return fmt.Errorf("attach is disabled")
}
- parsed, err := url.Parse(cdpURL)
+ parsed, err := url.Parse(rawURL)
if err != nil {
- return fmt.Errorf("invalid cdpUrl: %w", err)
+ return fmt.Errorf("invalid attach URL: %w", err)
}
// Validate scheme
@@ -351,6 +436,10 @@ func (o *Orchestrator) validateAttachURL(cdpURL string) error {
return fmt.Errorf("scheme %q not allowed (allowed: %v)", parsed.Scheme, o.runtimeCfg.AttachAllowSchemes)
}
+ if (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Path != "" && parsed.Path != "/" {
+ return fmt.Errorf("bridge baseUrl must not include a path")
+ }
+
// Validate host
host := parsed.Hostname()
hostAllowed := false
diff --git a/internal/orchestrator/handlers_tabs.go b/internal/orchestrator/handlers_tabs.go
index a298506c..b96d6b9b 100644
--- a/internal/orchestrator/handlers_tabs.go
+++ b/internal/orchestrator/handlers_tabs.go
@@ -5,9 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
- "net"
"net/http"
- "net/url"
"time"
"github.com/pinchtab/pinchtab/internal/web"
@@ -34,13 +32,18 @@ func (o *Orchestrator) handleTabClose(w http.ResponseWriter, r *http.Request) {
"tabId": tabID,
})
- targetURL := fmt.Sprintf("http://localhost:%s/tab", inst.Port)
- proxyReq, err := http.NewRequestWithContext(r.Context(), "POST", targetURL, bytes.NewReader(reqBody))
+ targetURL, err := o.instancePathURL(inst, "/tab", "")
+ if err != nil {
+ web.Error(w, 502, err)
+ return
+ }
+ proxyReq, err := http.NewRequestWithContext(r.Context(), "POST", targetURL.String(), bytes.NewReader(reqBody))
if err != nil {
web.Error(w, 500, err)
return
}
proxyReq.Header.Set("Content-Type", "application/json")
+ o.applyInstanceAuth(proxyReq, inst)
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(proxyReq)
@@ -98,11 +101,10 @@ func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Requ
proxyReq.Header = r.Header.Clone()
proxyReq.Header.Set("Content-Type", "application/json")
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tab",
- RawQuery: r.URL.RawQuery,
+ targetURL, err := o.instancePathURL(inst, "/tab", r.URL.RawQuery)
+ if err != nil {
+ web.Error(w, 502, err)
+ return
}
o.proxyToURL(w, proxyReq, targetURL)
}
diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.go
index 21f25f78..4a538db2 100644
--- a/internal/orchestrator/health.go
+++ b/internal/orchestrator/health.go
@@ -5,6 +5,8 @@ import (
"fmt"
"log/slog"
"net/http"
+ "net/url"
+ "strings"
"time"
)
@@ -35,19 +37,19 @@ func (o *Orchestrator) monitor(inst *InstanceInternal) {
}
time.Sleep(instanceHealthPollInterval)
- for _, baseURL := range instanceBaseURLs(inst.Port) {
- // Suppress CodeQL alert: baseURL comes from trusted orchestrator configuration
- // (port-based child instance list), not user input. This is intentional design:
- // agents request the orchestrator to probe known child instances.
- // lgtm[go/request-forgery]
- req, reqErr := http.NewRequest(http.MethodGet, baseURL+"/health", nil)
+ for _, baseURL := range instanceBaseURLs(inst.URL, inst.Port) {
+ baseParsed, parseErr := url.Parse(baseURL)
+ if parseErr != nil {
+ lastProbe = fmt.Sprintf("%s -> %s", baseURL, parseErr.Error())
+ continue
+ }
+ target := &url.URL{Scheme: baseParsed.Scheme, Host: baseParsed.Host, Path: "/health"}
+ req, reqErr := http.NewRequest(http.MethodGet, target.String(), nil)
if reqErr != nil {
lastProbe = fmt.Sprintf("%s -> %s", baseURL, reqErr.Error())
continue
}
- if o.childAuthToken != "" {
- req.Header.Set("Authorization", "Bearer "+o.childAuthToken)
- }
+ o.applyInstanceAuth(req, inst)
resp, err := o.client.Do(req)
if err == nil {
_ = resp.Body.Close()
@@ -75,6 +77,7 @@ func (o *Orchestrator) monitor(inst *InstanceInternal) {
inst.Status = "running"
if resolvedURL != "" {
inst.URL = resolvedURL
+ inst.Instance.URL = resolvedURL
}
o.syncInstanceToManager(&inst.Instance)
eventType = "instance.started"
@@ -143,14 +146,16 @@ type memoryMetrics struct {
Listeners int64 `json:"listeners"`
}
-func (o *Orchestrator) fetchTabs(baseURL string) ([]remoteTab, error) {
- req, err := http.NewRequest(http.MethodGet, baseURL+"/tabs", nil)
+func (o *Orchestrator) fetchTabs(inst *InstanceInternal) ([]remoteTab, error) {
+ target, err := o.instancePathURL(inst, "/tabs", "")
if err != nil {
return nil, err
}
- if o.childAuthToken != "" {
- req.Header.Set("Authorization", "Bearer "+o.childAuthToken)
+ req, err := http.NewRequest(http.MethodGet, target.String(), nil)
+ if err != nil {
+ return nil, err
}
+ o.applyInstanceAuth(req, inst)
resp, err := o.client.Do(req)
if err != nil {
@@ -171,14 +176,16 @@ func (o *Orchestrator) fetchTabs(baseURL string) ([]remoteTab, error) {
return result.Tabs, nil
}
-func (o *Orchestrator) fetchMetrics(baseURL string) (*memoryMetrics, error) {
- req, err := http.NewRequest(http.MethodGet, baseURL+"/metrics", nil)
+func (o *Orchestrator) fetchMetrics(inst *InstanceInternal) (*memoryMetrics, error) {
+ target, err := o.instancePathURL(inst, "/metrics", "")
if err != nil {
return nil, err
}
- if o.childAuthToken != "" {
- req.Header.Set("Authorization", "Bearer "+o.childAuthToken)
+ req, err := http.NewRequest(http.MethodGet, target.String(), nil)
+ if err != nil {
+ return nil, err
}
+ o.applyInstanceAuth(req, inst)
resp, err := o.client.Do(req)
if err != nil {
@@ -201,7 +208,10 @@ func isInstanceHealthyStatus(code int) bool {
return code > 0 && code < http.StatusInternalServerError
}
-func instanceBaseURLs(port string) []string {
+func instanceBaseURLs(rawURL, port string) []string {
+ if rawURL != "" {
+ return []string{strings.TrimRight(rawURL, "/")}
+ }
return []string{
fmt.Sprintf("http://127.0.0.1:%s", port),
fmt.Sprintf("http://[::1]:%s", port),
diff --git a/internal/orchestrator/health_test.go b/internal/orchestrator/health_test.go
index 34b31811..447fcbd2 100644
--- a/internal/orchestrator/health_test.go
+++ b/internal/orchestrator/health_test.go
@@ -27,7 +27,7 @@ func TestIsInstanceHealthyStatus(t *testing.T) {
func TestInstanceBaseURLs(t *testing.T) {
port := "1234"
- urls := instanceBaseURLs(port)
+ urls := instanceBaseURLs("", port)
expected := []string{
"http://127.0.0.1:1234",
@@ -45,3 +45,13 @@ func TestInstanceBaseURLs(t *testing.T) {
}
}
}
+
+func TestInstanceBaseURLs_UsesCanonicalURLWhenPresent(t *testing.T) {
+ urls := instanceBaseURLs("https://bridge.example.com:9868/", "1234")
+ if len(urls) != 1 {
+ t.Fatalf("expected 1 URL, got %d", len(urls))
+ }
+ if urls[0] != "https://bridge.example.com:9868" {
+ t.Fatalf("url = %q, want %q", urls[0], "https://bridge.example.com:9868")
+ }
+}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 0b915ce7..9e4c88a1 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -7,6 +7,7 @@ import (
"io"
"log/slog"
"net/http"
+ "net/url"
"os"
"path/filepath"
"sort"
@@ -80,8 +81,9 @@ type InstanceInternal struct {
URL string
Error string
- cmd Cmd
- logBuf *ringBuffer
+ authToken string
+ cmd Cmd
+ logBuf *ringBuffer
}
func NewOrchestrator(baseDir string) *Orchestrator {
@@ -330,6 +332,7 @@ func (o *Orchestrator) Launch(name, port string, headless bool, extensionPaths [
ProfileID: profileID,
ProfileName: name,
Port: port,
+ URL: fmt.Sprintf("http://localhost:%s", port),
Headless: headless,
Status: "starting",
StartTime: time.Now(),
@@ -391,13 +394,8 @@ func (o *Orchestrator) writeChildConfig(port, profilePath, instanceStateDir stri
return configPath, nil
}
-// Attach connects to an externally managed Chrome instance via CDP URL.
-// Unlike Launch, this does not start a Chrome process - it only registers
-// the external instance for tracking and proxying.
-func (o *Orchestrator) Attach(name, cdpURL string) (*bridge.Instance, error) {
+func (o *Orchestrator) attachExternalInstance(name string, inst bridge.Instance, authToken string) (*bridge.Instance, error) {
o.mu.Lock()
-
- // Check for duplicate name
for _, inst := range o.instances {
if inst.ProfileName == name && instanceIsActive(inst) {
o.mu.Unlock()
@@ -406,36 +404,62 @@ func (o *Orchestrator) Attach(name, cdpURL string) (*bridge.Instance, error) {
}
o.mu.Unlock()
- // Generate IDs (use name as pseudo-profile)
profileID := o.idMgr.ProfileID(name)
instanceID := o.idMgr.InstanceID(profileID, name)
-
- inst := &InstanceInternal{
- Instance: bridge.Instance{
- ID: instanceID,
- ProfileID: profileID,
- ProfileName: name,
- Status: "running",
- StartTime: time.Now(),
- Attached: true,
- CdpURL: cdpURL,
- },
- URL: cdpURL,
+ inst.ID = instanceID
+ inst.ProfileID = profileID
+ inst.ProfileName = name
+ inst.Status = "running"
+ inst.StartTime = time.Now()
+ internal := &InstanceInternal{
+ Instance: inst,
+ URL: inst.URL,
+ authToken: authToken,
}
o.mu.Lock()
- o.instances[instanceID] = inst
+ o.instances[instanceID] = internal
o.mu.Unlock()
- slog.Info("attached to external Chrome", "id", instanceID, "name", name, "cdpUrl", cdpURL)
+ o.syncInstanceToManager(&internal.Instance)
+ return &internal.Instance, nil
+}
+
+// Attach connects to an externally managed Chrome instance via CDP URL.
+// Unlike Launch, this does not start a Chrome process - it only registers
+// the external instance for tracking and proxying.
+func (o *Orchestrator) Attach(name, cdpURL string) (*bridge.Instance, error) {
+ inst, err := o.attachExternalInstance(name, bridge.Instance{
+ Attached: true,
+ AttachType: "cdp",
+ CdpURL: cdpURL,
+ URL: cdpURL,
+ }, "")
+ if err != nil {
+ return nil, err
+ }
+
+ slog.Info("attached to external Chrome", "id", inst.ID, "name", name, "cdpUrl", cdpURL)
// Emit event
- o.emitEvent("instance.attached", &inst.Instance)
+ o.emitEvent("instance.attached", inst)
+ return inst, nil
+}
- // Sync to instance manager if available
- o.syncInstanceToManager(&inst.Instance)
+// AttachBridge registers an already-running bridge server as an attached instance.
+func (o *Orchestrator) AttachBridge(name, baseURL, token string) (*bridge.Instance, error) {
+ inst, err := o.attachExternalInstance(name, bridge.Instance{
+ Attached: true,
+ AttachType: "bridge",
+ URL: strings.TrimRight(baseURL, "/"),
+ }, token)
+ if err != nil {
+ return nil, err
+ }
- return &inst.Instance, nil
+ slog.Info("attached to external bridge", "id", inst.ID, "name", name, "url", inst.URL)
+ o.emitEvent("instance.attached", inst)
+ return inst, nil
}
func (o *Orchestrator) Stop(id string) error {
@@ -454,6 +478,18 @@ func (o *Orchestrator) Stop(id string) error {
o.mu.Unlock()
if inst.cmd == nil {
+ if inst.AttachType == "bridge" {
+ reqCtx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
+ defer cancel()
+ targetURL, targetErr := o.instancePathURL(inst, "/shutdown", "")
+ if targetErr == nil {
+ req, _ := http.NewRequestWithContext(reqCtx, http.MethodPost, targetURL.String(), nil)
+ o.applyInstanceAuth(req, inst)
+ if resp, err := o.client.Do(req); err == nil {
+ _ = resp.Body.Close()
+ }
+ }
+ }
o.markStopped(id)
return nil
}
@@ -462,10 +498,13 @@ func (o *Orchestrator) Stop(id string) error {
reqCtx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
- req, _ := http.NewRequestWithContext(reqCtx, http.MethodPost, inst.URL+"/shutdown", nil)
- resp, err := o.client.Do(req)
- if err == nil {
- _ = resp.Body.Close()
+ if targetURL, targetErr := o.instancePathURL(inst, "/shutdown", ""); targetErr == nil {
+ req, _ := http.NewRequestWithContext(reqCtx, http.MethodPost, targetURL.String(), nil)
+ o.applyInstanceAuth(req, inst)
+ resp, err := o.client.Do(req)
+ if err == nil {
+ _ = resp.Body.Close()
+ }
}
if pid > 0 {
@@ -621,26 +660,30 @@ func (o *Orchestrator) Logs(id string) (string, error) {
func (o *Orchestrator) FirstRunningURL() string {
o.mu.RLock()
defer o.mu.RUnlock()
- // Collect running instances and sort by port (ascending) for determinism.
- // The lowest port is the earliest-launched instance, which is the most stable.
+ // Collect running instances and sort by start time for determinism.
+ // This works for both local launched instances and attached remote bridges.
type candidate struct {
- port int
- url string
+ start time.Time
+ url string
}
var candidates []candidate
for _, inst := range o.instances {
if inst.Status == "running" && instanceIsActive(inst) {
- p := 0
- if _, err := fmt.Sscanf(inst.Port, "%d", &p); err != nil {
+ if inst.URL == "" {
continue
}
- candidates = append(candidates, candidate{port: p, url: inst.URL})
+ candidates = append(candidates, candidate{start: inst.StartTime, url: inst.URL})
}
}
if len(candidates) == 0 {
return ""
}
- sort.Slice(candidates, func(i, j int) bool { return candidates[i].port < candidates[j].port })
+ sort.Slice(candidates, func(i, j int) bool {
+ if candidates[i].start.Equal(candidates[j].start) {
+ return candidates[i].url < candidates[j].url
+ }
+ return candidates[i].start.Before(candidates[j].start)
+ })
return candidates[0].url
}
@@ -656,7 +699,7 @@ func (o *Orchestrator) AllTabs() []bridge.InstanceTab {
all := make([]bridge.InstanceTab, 0)
for _, inst := range instances {
- tabs, err := o.fetchTabs(inst.URL)
+ tabs, err := o.fetchTabs(inst)
if err != nil {
continue
}
@@ -684,7 +727,7 @@ func (o *Orchestrator) AllMetrics() []types.InstanceMetrics {
all := make([]types.InstanceMetrics, 0)
for _, inst := range instances {
- mem, err := o.fetchMetrics(inst.URL)
+ mem, err := o.fetchMetrics(inst)
if err != nil || mem == nil {
continue
}
@@ -709,7 +752,17 @@ func (o *Orchestrator) ScreencastURL(instanceID, tabID string) string {
if !ok {
return ""
}
- return fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
+ target, err := o.instancePathURL(inst, "/screencast", "tabId="+url.QueryEscape(tabID))
+ if err != nil {
+ return ""
+ }
+ switch target.Scheme {
+ case "https":
+ target.Scheme = "wss"
+ default:
+ target.Scheme = "ws"
+ }
+ return target.String()
}
func (o *Orchestrator) Shutdown() {
diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.go
index 8c4962d8..ab156b54 100644
--- a/internal/orchestrator/orchestrator_test.go
+++ b/internal/orchestrator/orchestrator_test.go
@@ -234,6 +234,58 @@ func TestOrchestrator_Attach_DuplicateName(t *testing.T) {
}
}
+func TestOrchestrator_AttachBridge(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+
+ inst, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868", "bridge-token")
+ if err != nil {
+ t.Fatalf("AttachBridge failed: %v", err)
+ }
+ if !inst.Attached {
+ t.Fatal("expected attached instance")
+ }
+ if inst.AttachType != "bridge" {
+ t.Fatalf("AttachType = %q, want %q", inst.AttachType, "bridge")
+ }
+ if inst.URL != "http://10.0.0.8:9868" {
+ t.Fatalf("URL = %q, want %q", inst.URL, "http://10.0.0.8:9868")
+ }
+ if inst.CdpURL != "" {
+ t.Fatalf("CdpURL = %q, want empty", inst.CdpURL)
+ }
+}
+
+func TestValidateAttachURL_AllowsBridgeHTTP(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"10.0.0.8"},
+ AttachAllowSchemes: []string{"http", "ws"},
+ })
+
+ if err := o.validateAttachURL("http://10.0.0.8:9868"); err != nil {
+ t.Fatalf("validateAttachURL returned error: %v", err)
+ }
+}
+
+func TestValidateAttachURL_RejectsBridgeBaseURLWithPath(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"10.0.0.8"},
+ AttachAllowSchemes: []string{"http"},
+ })
+
+ err := o.validateAttachURL("http://10.0.0.8:9868/api")
+ if err == nil {
+ t.Fatal("expected error for attach bridge URL with path")
+ }
+ if !strings.Contains(err.Error(), "must not include a path") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
func TestOrchestrator_RegisterHandlers_LocksSensitiveRoutes(t *testing.T) {
o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
o.ApplyRuntimeConfig(&config.RuntimeConfig{})
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
index f23a1d9c..a93c4621 100644
--- a/internal/orchestrator/proxy.go
+++ b/internal/orchestrator/proxy.go
@@ -2,14 +2,13 @@ package orchestrator
import (
"fmt"
- "io"
- "net"
"net/http"
"net/url"
"strings"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/handlers"
+ iproxy "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/web"
)
@@ -26,11 +25,10 @@ func (o *Orchestrator) proxyTabRequest(w http.ResponseWriter, r *http.Request) {
}
proxyToInstance := func(inst *bridge.Instance) {
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: r.URL.Path,
- RawQuery: r.URL.RawQuery,
+ targetURL, buildErr := o.instancePathURLFromBridge(inst, r.URL.Path, r.URL.RawQuery)
+ if buildErr != nil {
+ web.Error(w, 502, buildErr)
+ return
}
o.proxyToURL(w, r, targetURL)
}
@@ -91,54 +89,27 @@ func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {
targetPath = ""
}
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: targetPath,
- RawQuery: r.URL.RawQuery,
+ targetURL, err := o.instancePathURL(inst, targetPath, r.URL.RawQuery)
+ if err != nil {
+ web.Error(w, 502, err)
+ return
}
o.proxyToURL(w, r, targetURL)
}
// proxyToURL proxies an HTTP request to the given target URL.
func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, targetURL *url.URL) {
- if targetURL.Hostname() != "localhost" {
- web.Error(w, 400, fmt.Errorf("invalid proxy target: only localhost allowed"))
- return
- }
-
- proxyReq, err := http.NewRequest(r.Method, targetURL.String(), r.Body)
- if err != nil {
- web.Error(w, 500, fmt.Errorf("failed to create proxy request: %w", err))
- return
- }
-
- for key, values := range r.Header {
- switch key {
- case "Host", "Connection", "Keep-Alive", "Proxy-Authenticate",
- "Proxy-Authorization", "Te", "Trailers", "Transfer-Encoding", "Upgrade":
- default:
- for _, value := range values {
- proxyReq.Header.Add(key, value)
+ iproxy.Forward(w, r, targetURL, iproxy.Options{
+ Client: o.client,
+ AllowedURL: func(u *url.URL) bool {
+ return o.proxyTargetInstance(u) != nil
+ },
+ RewriteRequest: func(req *http.Request) {
+ if inst := o.proxyTargetInstance(targetURL); inst != nil {
+ o.applyInstanceAuth(req, inst)
}
- }
- }
-
- resp, err := o.client.Do(proxyReq)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("failed to proxy to instance: %w", err))
- return
- }
- defer func() { _ = resp.Body.Close() }()
-
- for key, values := range resp.Header {
- for _, value := range values {
- w.Header().Add(key, value)
- }
- }
-
- w.WriteHeader(resp.StatusCode)
- _, _ = io.Copy(w, resp.Body)
+ },
+ })
}
// findRunningInstanceByTabID finds the instance that owns the given tab.
@@ -153,7 +124,7 @@ func (o *Orchestrator) findRunningInstanceByTabID(tabID string) (*InstanceIntern
o.mu.RUnlock()
for _, inst := range instances {
- tabs, err := o.fetchTabs(inst.URL)
+ tabs, err := o.fetchTabs(inst)
if err != nil {
continue
}
@@ -177,16 +148,110 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Requ
return
}
- // Build target URL preserving all query params (tabId, quality, maxWidth, fps)
- targetURL := fmt.Sprintf("http://localhost:%s/screencast?%s", inst.Port, r.URL.RawQuery)
-
- // Inject child auth token if configured
- if o.childAuthToken != "" {
- r.Header.Set("Authorization", "Bearer "+o.childAuthToken)
+ targetURL, err := o.instancePathURL(inst, "/screencast", r.URL.RawQuery)
+ if err != nil {
+ web.Error(w, 502, err)
+ return
}
+ req := r.Clone(r.Context())
+ req.Header = r.Header.Clone()
+ o.applyInstanceAuth(req, inst)
+
// Use WebSocket proxy for proper upgrade
- handlers.ProxyWebSocket(w, r, targetURL)
+ handlers.ProxyWebSocket(w, req, targetURL.String())
+}
+
+func (o *Orchestrator) instancePathURL(inst *InstanceInternal, path, rawQuery string) (*url.URL, error) {
+ if inst == nil {
+ return nil, fmt.Errorf("instance not found")
+ }
+ baseURL, err := o.parseHTTPInstanceURL(inst.URL, inst.Port)
+ if err != nil {
+ return nil, err
+ }
+ target := &url.URL{
+ Scheme: baseURL.Scheme,
+ Host: baseURL.Host,
+ Path: path,
+ RawQuery: rawQuery,
+ }
+ return target, nil
+}
+
+func (o *Orchestrator) instancePathURLFromBridge(inst *bridge.Instance, path, rawQuery string) (*url.URL, error) {
+ if inst == nil {
+ return nil, fmt.Errorf("instance not found")
+ }
+ baseURL, err := o.parseHTTPInstanceURL(inst.URL, inst.Port)
+ if err != nil {
+ return nil, err
+ }
+ target := &url.URL{
+ Scheme: baseURL.Scheme,
+ Host: baseURL.Host,
+ Path: path,
+ RawQuery: rawQuery,
+ }
+ return target, nil
+}
+
+func (o *Orchestrator) parseHTTPInstanceURL(rawURL, port string) (*url.URL, error) {
+ if rawURL == "" && port != "" {
+ rawURL = "http://localhost:" + port
+ }
+ parsed, err := url.Parse(rawURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid instance URL %q: %w", rawURL, err)
+ }
+ if parsed.Scheme != "http" && parsed.Scheme != "https" {
+ return nil, fmt.Errorf("instance %q is not an HTTP bridge", rawURL)
+ }
+ if parsed.Host == "" {
+ return nil, fmt.Errorf("invalid instance URL %q", rawURL)
+ }
+ if parsed.Path != "" && parsed.Path != "/" {
+ return nil, fmt.Errorf("instance URL %q must not include a path", rawURL)
+ }
+ return parsed, nil
+}
+
+func (o *Orchestrator) proxyTargetInstance(targetURL *url.URL) *InstanceInternal {
+ if targetURL == nil {
+ return nil
+ }
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+ for _, inst := range o.instances {
+ baseURL, err := o.parseHTTPInstanceURL(inst.URL, inst.Port)
+ if err != nil {
+ continue
+ }
+ if sameOrigin(baseURL, targetURL) {
+ return inst
+ }
+ }
+ return nil
+}
+
+func sameOrigin(a, b *url.URL) bool {
+ if a == nil || b == nil {
+ return false
+ }
+ return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host)
+}
+
+func (o *Orchestrator) applyInstanceAuth(req *http.Request, inst *InstanceInternal) {
+ if req == nil || inst == nil {
+ return
+ }
+ token := inst.authToken
+ if token == "" {
+ token = o.childAuthToken
+ }
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
}
// classifyLaunchError returns appropriate HTTP status code for launch errors.
diff --git a/internal/orchestrator/proxy_test.go b/internal/orchestrator/proxy_test.go
index ea4b14e3..5cd82824 100644
--- a/internal/orchestrator/proxy_test.go
+++ b/internal/orchestrator/proxy_test.go
@@ -82,3 +82,37 @@ func TestSingleRunningInstance_IgnoresStopped(t *testing.T) {
t.Fatalf("got %#v, want inst_1", got)
}
}
+
+func TestProxyToURL_UsesAttachedBridgeOriginAndAuth(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("Authorization"); got != "Bearer bridge-token" {
+ t.Fatalf("authorization = %q, want %q", got, "Bearer bridge-token")
+ }
+ if r.URL.Path != "/tabs/tab-1/snapshot" {
+ t.Fatalf("path = %q", r.URL.Path)
+ }
+ _, _ = io.WriteString(w, `ok`)
+ }))
+ defer backend.Close()
+
+ o := NewOrchestrator(t.TempDir())
+ o.client = backend.Client()
+ attached, err := o.AttachBridge("bridge1", backend.URL, "bridge-token")
+ if err != nil {
+ t.Fatalf("AttachBridge failed: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/tabs/tab-1/snapshot", nil)
+ req.SetPathValue("id", "tab-1")
+ w := httptest.NewRecorder()
+
+ targetURL, err := o.instancePathURLFromBridge(attached, "/tabs/tab-1/snapshot", "")
+ if err != nil {
+ t.Fatalf("instancePathURLFromBridge failed: %v", err)
+ }
+ o.proxyToURL(w, req, targetURL)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+}
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
index 1829014d..c8e3941f 100644
--- a/internal/proxy/proxy.go
+++ b/internal/proxy/proxy.go
@@ -7,6 +7,7 @@ package proxy
import (
"fmt"
"net/http"
+ "net/url"
"strings"
"time"
@@ -19,42 +20,67 @@ import (
// and tab navigation (up to 60s for NavigateTimeout in bridge config).
var DefaultClient = &http.Client{Timeout: 60 * time.Second}
-// HTTP forwards an HTTP request to targetURL, streaming the response
-// back to w. If the request is a WebSocket upgrade, it delegates to
-// handlers.ProxyWebSocket instead.
-func HTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
- if r.URL.RawQuery != "" {
- targetURL += "?" + r.URL.RawQuery
+type Options struct {
+ Client *http.Client
+ AllowedURL func(*url.URL) bool
+ RewriteRequest func(*http.Request)
+}
+
+var hopByHopHeaders = map[string]struct{}{
+ "connection": {},
+ "keep-alive": {},
+ "proxy-authenticate": {},
+ "proxy-authorization": {},
+ "te": {},
+ "trailers": {},
+ "transfer-encoding": {},
+ "upgrade": {},
+ "host": {},
+}
+
+func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Options) {
+ if targetURL == nil {
+ web.Error(w, 502, fmt.Errorf("proxy error: missing target URL"))
+ return
+ }
+ if opts.AllowedURL != nil && !opts.AllowedURL(targetURL) {
+ web.Error(w, 400, fmt.Errorf("invalid proxy target"))
+ return
+ }
+
+ proxyReq := r.Clone(r.Context())
+ proxyReq.URL = targetURL
+ proxyReq.Host = targetURL.Host
+ proxyReq.Header = r.Header.Clone()
+ if opts.RewriteRequest != nil {
+ opts.RewriteRequest(proxyReq)
}
- if isWebSocketUpgrade(r) {
- handlers.ProxyWebSocket(w, r, targetURL)
+ if isWebSocketUpgrade(proxyReq) {
+ handlers.ProxyWebSocket(w, proxyReq, targetURL.String())
return
}
- proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)
+ client := opts.Client
+ if client == nil {
+ client = DefaultClient
+ }
+
+ outReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL.String(), r.Body)
if err != nil {
web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
return
}
- for k, vv := range r.Header {
- for _, v := range vv {
- proxyReq.Header.Add(k, v)
- }
- }
+ copyHeaders(outReq.Header, proxyReq.Header)
- resp, err := DefaultClient.Do(proxyReq)
+ resp, err := client.Do(outReq)
if err != nil {
web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
return
}
defer func() { _ = resp.Body.Close() }()
- for k, vv := range resp.Header {
- for _, v := range vv {
- w.Header().Add(k, v)
- }
- }
+ copyHeaders(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
buf := make([]byte, 32*1024)
@@ -72,6 +98,21 @@ func HTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
}
}
+// HTTP forwards an HTTP request to targetURL, streaming the response
+// back to w. If the request is a WebSocket upgrade, it delegates to
+// handlers.ProxyWebSocket instead.
+func HTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
+ parsed, err := url.Parse(targetURL)
+ if err != nil {
+ web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
+ return
+ }
+ if parsed.RawQuery == "" {
+ parsed.RawQuery = r.URL.RawQuery
+ }
+ Forward(w, r, parsed, Options{})
+}
+
func isWebSocketUpgrade(r *http.Request) bool {
for _, v := range r.Header["Upgrade"] {
if strings.EqualFold(v, "websocket") {
@@ -80,3 +121,14 @@ func isWebSocketUpgrade(r *http.Request) bool {
}
return false
}
+
+func copyHeaders(dst, src http.Header) {
+ for k, vv := range src {
+ if _, skip := hopByHopHeaders[strings.ToLower(k)]; skip {
+ continue
+ }
+ for _, v := range vv {
+ dst.Add(k, v)
+ }
+ }
+}
diff --git a/scripts/build-dashboard.sh b/scripts/build-dashboard.sh
index f1de57b1..5d3770a0 100755
--- a/scripts/build-dashboard.sh
+++ b/scripts/build-dashboard.sh
@@ -4,14 +4,65 @@ set -e
cd "$(dirname "$0")/.."
+BUN_MIN_VERSION="1.2.0"
+
+confirm() {
+ if [ ! -t 0 ]; then
+ return 1
+ fi
+
+ echo -n "$1 [y/N] "
+ read -r answer
+ [[ "$answer" =~ ^[Yy]$ ]]
+}
+
+version_ge() {
+ local current="${1#v}"
+ local minimum="${2#v}"
+ local current_major current_minor current_patch
+ local minimum_major minimum_minor minimum_patch
+
+ IFS='.' read -r current_major current_minor current_patch <<< "${current}"
+ IFS='.' read -r minimum_major minimum_minor minimum_patch <<< "${minimum}"
+
+ current_minor=${current_minor:-0}
+ current_patch=${current_patch:-0}
+ minimum_minor=${minimum_minor:-0}
+ minimum_patch=${minimum_patch:-0}
+
+ if [ "$current_major" -ne "$minimum_major" ]; then
+ [ "$current_major" -gt "$minimum_major" ]
+ return
+ fi
+
+ if [ "$current_minor" -ne "$minimum_minor" ]; then
+ [ "$current_minor" -gt "$minimum_minor" ]
+ return
+ fi
+
+ [ "$current_patch" -ge "$minimum_patch" ]
+}
+
+if ! command -v bun &> /dev/null; then
+ echo "❌ ERROR: Bun is required to build the dashboard"
+ echo " Install it with: curl -fsSL https://bun.sh/install | bash"
+ exit 1
+fi
+
+BUN_VERSION="$(bun -v)"
+if ! version_ge "$BUN_VERSION" "$BUN_MIN_VERSION"; then
+ echo "❌ ERROR: Bun $BUN_VERSION is too old for dashboard/bun.lock"
+ echo " Clean installs require Bun $BUN_MIN_VERSION+"
+ echo " Upgrade with: curl -fsSL https://bun.sh/install | bash"
+ exit 1
+fi
+
echo "📦 Building React dashboard..."
cd dashboard
-# Install deps if needed (must happen before prettier)
-if [ ! -d "node_modules" ]; then
- echo "📥 Installing dependencies..."
- bun install --frozen-lockfile
-fi
+# Sync deps on every build so stale dashboard node_modules do not drift from bun.lock.
+echo "📥 Syncing dashboard dependencies..."
+bun install --frozen-lockfile
# Generate TypeScript types from Go structs (ensures types are in sync)
TYGO="${GOPATH:-$HOME/go}/bin/tygo"
@@ -22,11 +73,28 @@ elif command -v tygo &> /dev/null; then
echo "🔄 Generating TypeScript types..."
tygo generate
else
- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
- echo "⚠️ WARNING: tygo not found — skipping TypeScript type generation"
- echo " Types in the dashboard might fall out of sync with Go structs."
- echo " Install it with: go install github.com/gzuidhof/tygo@latest"
- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ if command -v go &> /dev/null && confirm "Install tygo via go install?"; then
+ go install github.com/gzuidhof/tygo@latest
+ TYGO="${GOPATH:-$HOME/go}/bin/tygo"
+ if [ -x "$TYGO" ]; then
+ echo "🔄 Generating TypeScript types..."
+ "$TYGO" generate
+ elif command -v tygo &> /dev/null; then
+ echo "🔄 Generating TypeScript types..."
+ tygo generate
+ else
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ echo "⚠️ WARNING: tygo install completed but binary was not found on PATH"
+ echo " Restart your shell or ensure \$GOPATH/bin is on PATH."
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ fi
+ else
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ echo "⚠️ WARNING: tygo not found — skipping TypeScript type generation"
+ echo " Types in the dashboard might fall out of sync with Go structs."
+ echo " Install it with: go install github.com/gzuidhof/tygo@latest"
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ fi
fi
# Normalize tygo output with prettier so generation doesn't dirty git
diff --git a/scripts/doctor.sh b/scripts/doctor.sh
index aa8e7d24..9364d942 100755
--- a/scripts/doctor.sh
+++ b/scripts/doctor.sh
@@ -14,6 +14,7 @@ NC='\033[0m'
CRITICAL=0
WARNINGS=0
+BUN_MIN_VERSION="1.2.0"
# ── Helpers ──────────────────────────────────────────────────────────
@@ -33,6 +34,33 @@ section() {
echo -e "${ACCENT}${BOLD}$1${NC}"
}
+version_ge() {
+ local current="${1#v}"
+ local minimum="${2#v}"
+ local current_major current_minor current_patch
+ local minimum_major minimum_minor minimum_patch
+
+ IFS='.' read -r current_major current_minor current_patch <<< "${current}"
+ IFS='.' read -r minimum_major minimum_minor minimum_patch <<< "${minimum}"
+
+ current_minor=${current_minor:-0}
+ current_patch=${current_patch:-0}
+ minimum_minor=${minimum_minor:-0}
+ minimum_patch=${minimum_patch:-0}
+
+ if [ "$current_major" -ne "$minimum_major" ]; then
+ [ "$current_major" -gt "$minimum_major" ]
+ return
+ fi
+
+ if [ "$current_minor" -ne "$minimum_minor" ]; then
+ [ "$current_minor" -gt "$minimum_minor" ]
+ return
+ fi
+
+ [ "$current_patch" -ge "$minimum_patch" ]
+}
+
# ── Detect package manager ───────────────────────────────────────────
HAS_BREW=false
@@ -154,27 +182,55 @@ if [ -d "dashboard" ]; then
# ── Bun ────────────────────────────────────────────────────────
+ HAS_SUPPORTED_BUN=false
if command -v bun &>/dev/null; then
- ok "Bun $(bun -v)"
+ BUN_VERSION=$(bun -v)
+ if version_ge "$BUN_VERSION" "$BUN_MIN_VERSION"; then
+ ok "Bun $BUN_VERSION"
+ HAS_SUPPORTED_BUN=true
+ else
+ warn "Bun $BUN_VERSION — requires $BUN_MIN_VERSION+ for dashboard installs" "Older Bun versions try to rewrite dashboard/bun.lock and fail with --frozen-lockfile on clean clones."
+ if confirm "Upgrade Bun now?"; then
+ curl -fsSL https://bun.sh/install | bash && ok "Bun updated (restart shell to use)" && WARNINGS=$((WARNINGS - 1)) && HAS_SUPPORTED_BUN=true
+ else
+ hint "curl -fsSL https://bun.sh/install | bash"
+ fi
+ fi
else
warn "Bun not found" "Optional — used for fast dashboard builds."
if confirm "Install Bun?"; then
- curl -fsSL https://bun.sh/install | bash && ok "Bun installed (restart shell to use)" && WARNINGS=$((WARNINGS - 1))
+ curl -fsSL https://bun.sh/install | bash && ok "Bun installed (restart shell to use)" && WARNINGS=$((WARNINGS - 1)) && HAS_SUPPORTED_BUN=true
else
hint "curl -fsSL https://bun.sh/install | bash"
fi
fi
+ # ── tygo ───────────────────────────────────────────────────────
+
+ TYGO="${GOPATH:-$HOME/go}/bin/tygo"
+ if [ -x "$TYGO" ] || command -v tygo &>/dev/null; then
+ ok "tygo"
+ else
+ warn "tygo not found" "Types in the dashboard might fall out of sync with Go structs."
+ if command -v go &>/dev/null && confirm "Install tygo via go install?"; then
+ go install github.com/gzuidhof/tygo@latest && ok "tygo installed" && WARNINGS=$((WARNINGS - 1))
+ else
+ hint "go install github.com/gzuidhof/tygo@latest"
+ fi
+ fi
+
# ── Dashboard deps ─────────────────────────────────────────────
if [ -d "dashboard/node_modules" ]; then
ok "Dashboard dependencies"
else
warn "Dashboard dependencies not installed"
- if command -v bun &>/dev/null; then
+ if $HAS_SUPPORTED_BUN; then
if confirm "Install dashboard dependencies via bun?"; then
(cd dashboard && bun install) && ok "Dashboard dependencies installed" && WARNINGS=$((WARNINGS - 1))
fi
+ elif command -v bun &>/dev/null; then
+ hint "Upgrade Bun to $BUN_MIN_VERSION+ before installing dashboard dependencies"
elif command -v npm &>/dev/null; then
if confirm "Install dashboard dependencies via npm?"; then
(cd dashboard && npm install) && ok "Dashboard dependencies installed" && WARNINGS=$((WARNINGS - 1))
diff --git a/tests/e2e/README.md b/tests/e2e/README.md
index 44d144a6..150b4b37 100644
--- a/tests/e2e/README.md
+++ b/tests/e2e/README.md
@@ -9,6 +9,7 @@ End-to-end tests for PinchTab that exercise the full stack including browser aut
```bash
./dev e2e # Run all E2E tests
./dev e2e recent # Run only recently added/changed scenarios (fast feedback)
+./dev e2e orchestrator # Run orchestrator-heavy scenarios only
./dev e2e curl # Run only Curl-based scenarios
./dev e2e cli # Run only CLI-based scenarios
```
@@ -16,16 +17,19 @@ End-to-end tests for PinchTab that exercise the full stack including browser aut
Or directly:
```bash
docker compose -f tests/e2e/docker-compose.yml up --build
+docker compose -f tests/e2e/docker-compose-orchestrator.yml run --build --rm runner
```
## Architecture
```
tests/e2e/
-├── docker-compose.yml # Orchestrates all services
+├── docker-compose.yml # Generic curl scenarios
+├── docker-compose-orchestrator.yml # Orchestrator-specific services
├── config/ # E2E-specific PinchTab configs
│ ├── pinchtab.json
-│ └── pinchtab-secure.json
+│ ├── pinchtab-secure.json
+│ └── pinchtab-bridge.json
├── fixtures/ # Static HTML test pages
│ ├── index.html
│ ├── form.html
@@ -33,13 +37,17 @@ tests/e2e/
│ └── buttons.html
├── scenarios/ # Test scripts
│ ├── common.sh # Shared utilities
-│ ├── run-all.sh # Orchestrator
+│ ├── run-all.sh # Generic curl scenarios
│ ├── 01-health.sh
│ ├── 02-navigate.sh
│ ├── 03-snapshot.sh
│ ├── 04-tabs-api.sh # Regression test for #207
│ ├── 05-actions.sh
│ └── 06-screenshot-pdf.sh
+├── scenarios-orchestrator/ # Multi-instance and attach flows
+│ ├── run-all.sh
+│ ├── 01-attach-bridge.sh
+│ └── 31-multi-instance.sh
├── runner/ # Test runner container
│ └── Dockerfile
└── results/ # Test output (gitignored)
@@ -57,6 +65,8 @@ The Docker stack reuses the repository root `Dockerfile` and mounts explicit con
| 04-tabs-api | Tab-scoped APIs (regression #207) |
| 05-actions | Click, type, press actions |
| 06-screenshot-pdf | Screenshot and PDF export |
+| scenarios-orchestrator/01-attach-bridge | Orchestrator attaches to the dedicated `pinchtab-bridge` container and proxies tab traffic |
+| scenarios-orchestrator/31-multi-instance | Launch/list/stop and aggregate orchestration behavior |
## Adding Tests
@@ -119,3 +129,13 @@ docker compose -f tests/e2e/docker-compose.yml run runner bash
```bash
docker compose -f tests/e2e/docker-compose.yml run runner /scenarios/04-tabs-api.sh
```
+
+### Run orchestrator scenarios
+```bash
+docker compose -f tests/e2e/docker-compose-orchestrator.yml run --build --rm runner
+```
+
+### Run remote bridge attach scenario
+```bash
+docker compose -f tests/e2e/docker-compose-orchestrator.yml run --build --rm runner /scenarios-orchestrator/01-attach-bridge.sh
+```
diff --git a/tests/e2e/config/pinchtab-bridge.json b/tests/e2e/config/pinchtab-bridge.json
new file mode 100644
index 00000000..c8e18c48
--- /dev/null
+++ b/tests/e2e/config/pinchtab-bridge.json
@@ -0,0 +1,15 @@
+{
+ "server": {
+ "bind": "0.0.0.0",
+ "port": "9999",
+ "token": "e2e-bridge-token"
+ },
+ "browser": {
+ "extraFlags": "--no-sandbox --disable-dev-shm-usage"
+ },
+ "security": {
+ "allowEvaluate": false,
+ "allowDownload": false,
+ "allowUpload": false
+ }
+}
diff --git a/tests/e2e/config/pinchtab.json b/tests/e2e/config/pinchtab.json
index 45f549bd..bec6628e 100644
--- a/tests/e2e/config/pinchtab.json
+++ b/tests/e2e/config/pinchtab.json
@@ -37,6 +37,21 @@
"allowEvaluate": true,
"allowDownload": true,
"allowUpload": true,
+ "attach": {
+ "enabled": true,
+ "allowHosts": [
+ "127.0.0.1",
+ "localhost",
+ "::1",
+ "pinchtab-bridge"
+ ],
+ "allowSchemes": [
+ "ws",
+ "wss",
+ "http",
+ "https"
+ ]
+ },
"idpi": {
"enabled": true,
"scanContent": true,
diff --git a/tests/e2e/docker-compose-orchestrator.yml b/tests/e2e/docker-compose-orchestrator.yml
new file mode 100644
index 00000000..ab9c68c2
--- /dev/null
+++ b/tests/e2e/docker-compose-orchestrator.yml
@@ -0,0 +1,72 @@
+services:
+ pinchtab:
+ build:
+ context: ../..
+ dockerfile: Dockerfile
+ environment:
+ PINCHTAB_CONFIG: /config/pinchtab.json
+ PINCHTAB_PORT: "9999"
+ volumes:
+ - ./config/pinchtab.json:/config/pinchtab.json:ro
+ - ./fixtures/test-extension:/extensions/test-extension
+ - ./fixtures/test-extension-api:/extensions/test-extension-api
+ ports:
+ - "9999:9999"
+ shm_size: '2gb'
+ healthcheck:
+ test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:9999/health"]
+ interval: 3s
+ timeout: 10s
+ retries: 20
+ start_period: 15s
+
+ pinchtab-bridge:
+ build:
+ context: ../..
+ dockerfile: Dockerfile
+ environment:
+ PINCHTAB_CONFIG: /config/pinchtab-bridge.json
+ PINCHTAB_PORT: "9999"
+ volumes:
+ - ./config/pinchtab-bridge.json:/config/pinchtab-bridge.json:ro
+ ports:
+ - "9996:9999"
+ command: ["/usr/local/bin/pinchtab", "bridge"]
+ shm_size: '2gb'
+ healthcheck:
+ test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-bridge-token' -q -O /dev/null http://localhost:9999/health"]
+ interval: 3s
+ timeout: 10s
+ retries: 20
+ start_period: 15s
+
+ fixtures:
+ image: nginx:alpine
+ volumes:
+ - ./fixtures:/usr/share/nginx/html:ro
+ healthcheck:
+ test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:80/"]
+ interval: 2s
+ timeout: 5s
+ retries: 5
+
+ runner:
+ build:
+ context: ./runner
+ depends_on:
+ pinchtab:
+ condition: service_healthy
+ pinchtab-bridge:
+ condition: service_healthy
+ fixtures:
+ condition: service_healthy
+ environment:
+ - PINCHTAB_URL=http://pinchtab:9999
+ - PINCHTAB_BRIDGE_URL=http://pinchtab-bridge:9999
+ - PINCHTAB_BRIDGE_TOKEN=e2e-bridge-token
+ - FIXTURES_URL=http://fixtures:80
+ volumes:
+ - ./scenarios:/scenarios:ro
+ - ./scenarios-orchestrator:/scenarios-orchestrator:ro
+ - ./results:/results
+ command: ["/scenarios-orchestrator/run-all.sh"]
diff --git a/tests/e2e/scenarios-orchestrator/01-attach-bridge.sh b/tests/e2e/scenarios-orchestrator/01-attach-bridge.sh
new file mode 100644
index 00000000..c512b08a
--- /dev/null
+++ b/tests/e2e/scenarios-orchestrator/01-attach-bridge.sh
@@ -0,0 +1,57 @@
+#!/bin/bash
+# 01-attach-bridge.sh — Remote bridge attachment through the orchestrator
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${SCRIPT_DIR}/../scenarios/common.sh"
+
+BRIDGE_URL="${PINCHTAB_BRIDGE_URL:-}"
+BRIDGE_TOKEN="${PINCHTAB_BRIDGE_TOKEN:-}"
+if [ -z "$BRIDGE_URL" ]; then
+ echo " PINCHTAB_BRIDGE_URL not set, skipping attach-bridge scenario"
+ return 0 2>/dev/null || exit 0
+fi
+
+start_test "orchestrator: attach remote bridge and proxy tab traffic"
+
+pt_post /instances/attach-bridge "{\"name\":\"e2e-remote-bridge\",\"baseUrl\":\"${BRIDGE_URL}\",\"token\":\"${BRIDGE_TOKEN}\"}"
+assert_http_status "201" "attach bridge"
+assert_json_eq "$RESULT" '.attachType' 'bridge' "instance attachType is bridge"
+assert_json_eq "$RESULT" '.attached' 'true' "instance is marked attached"
+assert_json_eq "$RESULT" '.url' "${BRIDGE_URL}" "instance stores remote bridge URL"
+
+ATTACHED_INST_ID=$(echo "$RESULT" | jq -r '.id // empty')
+if [ -n "$ATTACHED_INST_ID" ]; then
+ echo -e " ${GREEN}✓${NC} attached bridge instance id: ${ATTACHED_INST_ID}"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} attach response missing instance id"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+pt_post "/instances/${ATTACHED_INST_ID}/tabs/open" "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+assert_ok "open tab on attached bridge"
+assert_tab_id "attached bridge returned tabId"
+ATTACHED_TAB_ID="${TAB_ID}"
+
+pt_get "/tabs/${ATTACHED_TAB_ID}/text?format=text"
+assert_ok "proxy text via attached bridge tab route"
+assert_contains "$RESULT" "Welcome to the E2E test fixtures." "tab text came back through orchestrator proxy"
+
+pt_get "/instances/${ATTACHED_INST_ID}/tabs"
+assert_ok "list tabs for attached bridge instance"
+assert_json_length_gte "$RESULT" '.' '1' "attached bridge has at least one tab"
+
+pt_get /instances/tabs
+assert_ok "aggregate tabs includes attached bridge"
+if echo "$RESULT" | jq -e --arg inst "$ATTACHED_INST_ID" '.[] | select(.instanceId == $inst)' >/dev/null 2>&1; then
+ echo -e " ${GREEN}✓${NC} aggregate tab list includes attached bridge instance"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} aggregate tab list missing attached bridge instance"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+pt_post "/instances/${ATTACHED_INST_ID}/stop" '{}'
+assert_ok "stop attached bridge instance"
+
+end_test
diff --git a/tests/e2e/scenarios/31-multi-instance.sh b/tests/e2e/scenarios-orchestrator/31-multi-instance.sh
similarity index 93%
rename from tests/e2e/scenarios/31-multi-instance.sh
rename to tests/e2e/scenarios-orchestrator/31-multi-instance.sh
index 81e6790e..7e99dbd8 100755
--- a/tests/e2e/scenarios/31-multi-instance.sh
+++ b/tests/e2e/scenarios-orchestrator/31-multi-instance.sh
@@ -2,7 +2,8 @@
# 31-multi-instance.sh — Multi-instance orchestration tests
# Migrated from: tests/integration/orchestrator_test.go
-source "$(dirname "$0")/common.sh"
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${SCRIPT_DIR}/../scenarios/common.sh"
# ─────────────────────────────────────────────────────────────────
start_test "orchestrator: health shows dashboard mode"
@@ -33,7 +34,7 @@ assert_json_exists "$RESULT" '.id' "has instance id"
assert_json_exists "$RESULT" '.port' "has port"
# Wait for instance to be ready
-sleep 3
+wait_for_orchestrator_instance_status "${PINCHTAB_URL}" "${INST_ID}" "running" 30
# Verify it appears in list
pt_get /instances
@@ -85,11 +86,13 @@ start_test "orchestrator: aggregate tabs (multi-instance)"
pt_post /instances/launch '{"name":"e2e-agg-tabs","headless":true}'
assert_ok "launch for aggregate"
AGG_INST=$(echo "$RESULT" | jq -r '.id')
-sleep 3
+wait_for_orchestrator_instance_status "${PINCHTAB_URL}" "${AGG_INST}" "running" 30
# Navigate on both instances to ensure tabs exist
pt_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+assert_ok "navigate on default instance"
pt_post "/instances/${AGG_INST}/tabs/open" "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+assert_ok "open tab on aggregate instance"
pt_get /instances/tabs
assert_ok "aggregate tabs"
@@ -228,20 +231,23 @@ pt_post /instances/launch '{"name":"e2e-iso-2","headless":true}'
assert_ok "launch iso-2"
ISO_INST2=$(echo "$RESULT" | jq -r '.id')
-sleep 3
+wait_for_orchestrator_instance_status "${PINCHTAB_URL}" "${ISO_INST1}" "running" 30
+wait_for_orchestrator_instance_status "${PINCHTAB_URL}" "${ISO_INST2}" "running" 30
# Open tabs on each instance
pt_post "/instances/${ISO_INST1}/tabs/open" "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+assert_ok "open tab on iso-1"
TAB1=$(echo "$RESULT" | jq -r '.tabId // .id // empty')
pt_post "/instances/${ISO_INST2}/tabs/open" "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+assert_ok "open tab on iso-2"
TAB2=$(echo "$RESULT" | jq -r '.tabId // .id // empty')
-if [ "$TAB1" != "$TAB2" ] || [ -z "$TAB1" ]; then
+if [ -n "$TAB1" ] && [ -n "$TAB2" ] && [ "$TAB1" != "$TAB2" ]; then
echo -e " ${GREEN}✓${NC} instances have separate tabs"
((ASSERTIONS_PASSED++)) || true
else
- echo -e " ${RED}✗${NC} instances share tab IDs: $TAB1"
+ echo -e " ${RED}✗${NC} instances did not produce distinct tab IDs: ${TAB1} vs ${TAB2}"
((ASSERTIONS_FAILED++)) || true
fi
diff --git a/tests/e2e/scenarios-orchestrator/run-all.sh b/tests/e2e/scenarios-orchestrator/run-all.sh
new file mode 100644
index 00000000..3589324b
--- /dev/null
+++ b/tests/e2e/scenarios-orchestrator/run-all.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+# run-all.sh - Run orchestrator-focused E2E scenarios
+
+set -uo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+COMMON_DIR="$(dirname "$SCRIPT_DIR")/scenarios"
+source "${COMMON_DIR}/common.sh"
+
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+echo -e "${BLUE}PinchTab E2E Orchestrator Tests${NC}"
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+echo "PINCHTAB_URL: ${PINCHTAB_URL}"
+echo "PINCHTAB_BRIDGE_URL: ${PINCHTAB_BRIDGE_URL:-}"
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+echo ""
+
+echo "Waiting for orchestrator services to become ready..."
+wait_for_instance_ready "${PINCHTAB_URL}"
+if [ -n "${PINCHTAB_BRIDGE_URL:-}" ]; then
+ wait_for_instance_ready "${PINCHTAB_BRIDGE_URL}" 60 "${PINCHTAB_BRIDGE_TOKEN:-}"
+fi
+echo ""
+
+for script in "${SCRIPT_DIR}"/[0-9][0-9]-*.sh; do
+ if [ -f "$script" ]; then
+ echo -e "${YELLOW}Running: $(basename "$script")${NC}"
+ echo ""
+ source "$script"
+ echo ""
+ fi
+done
diff --git a/tests/e2e/scenarios/common.sh b/tests/e2e/scenarios/common.sh
index 588cc95a..df7127bd 100755
--- a/tests/e2e/scenarios/common.sh
+++ b/tests/e2e/scenarios/common.sh
@@ -17,6 +17,8 @@ NC='\033[0m'
# Defaults from environment
PINCHTAB_URL="${PINCHTAB_URL:-http://localhost:9999}"
PINCHTAB_SECURE_URL="${PINCHTAB_SECURE_URL:-http://localhost:9998}"
+PINCHTAB_BRIDGE_URL="${PINCHTAB_BRIDGE_URL:-}"
+PINCHTAB_BRIDGE_TOKEN="${PINCHTAB_BRIDGE_TOKEN:-}"
FIXTURES_URL="${FIXTURES_URL:-http://localhost:8080}"
RESULTS_DIR="${RESULTS_DIR:-/results}"
@@ -55,6 +57,7 @@ get_time_ms() {
wait_for_instance_ready() {
local base_url="$1"
local timeout_sec="${2:-60}"
+ local token="${3:-}"
local started_at
started_at=$(date +%s)
@@ -67,7 +70,11 @@ wait_for_instance_ready() {
fi
local health_json
- health_json=$(curl -sf "${base_url}/health" 2>/dev/null || true)
+ if [ -n "$token" ]; then
+ health_json=$(curl -sf -H "Authorization: Bearer ${token}" "${base_url}/health" 2>/dev/null || true)
+ else
+ health_json=$(curl -sf "${base_url}/health" 2>/dev/null || true)
+ fi
if [ -n "$health_json" ]; then
local inst_status
inst_status=$(echo "$health_json" | jq -r '.defaultInstance.status // .status // empty' 2>/dev/null || true)
@@ -81,6 +88,41 @@ wait_for_instance_ready() {
done
}
+wait_for_orchestrator_instance_status() {
+ local base_url="$1"
+ local instance_id="$2"
+ local wanted_status="${3:-running}"
+ local timeout_sec="${4:-60}"
+ local started_at
+ started_at=$(date +%s)
+
+ while true; do
+ local now
+ now=$(date +%s)
+ if [ $((now - started_at)) -ge "$timeout_sec" ]; then
+ echo -e " ${RED}✗${NC} instance ${instance_id} at ${base_url} did not reach ${wanted_status} within ${timeout_sec}s"
+ return 1
+ fi
+
+ local inst_json
+ inst_json=$(curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
+ if [ -n "$inst_json" ]; then
+ local inst_status
+ inst_status=$(echo "$inst_json" | jq -r '.status // empty' 2>/dev/null || true)
+ if [ "$inst_status" = "$wanted_status" ]; then
+ echo -e " ${GREEN}✓${NC} instance ${instance_id} is ${wanted_status}"
+ return 0
+ fi
+ if [ "$inst_status" = "stopped" ] || [ "$inst_status" = "error" ]; then
+ echo -e " ${RED}✗${NC} instance ${instance_id} reached terminal status ${inst_status} before ${wanted_status}"
+ return 1
+ fi
+ fi
+
+ sleep 1
+ done
+}
+
# Start a test
start_test() {
CURRENT_TEST="$1"
diff --git a/tests/e2e/scenarios/run-all.sh b/tests/e2e/scenarios/run-all.sh
index 2059b282..4e5d9a1a 100755
--- a/tests/e2e/scenarios/run-all.sh
+++ b/tests/e2e/scenarios/run-all.sh
@@ -17,6 +17,9 @@ echo ""
echo "Waiting for instances to become ready..."
wait_for_instance_ready "${PINCHTAB_URL}"
wait_for_instance_ready "${PINCHTAB_SECURE_URL}"
+if [ -n "${PINCHTAB_LITE_URL:-}" ]; then
+ wait_for_instance_ready "${PINCHTAB_LITE_URL}"
+fi
echo ""
# Find and run all test scripts in order