diff --git a/packages/adapter-utils/src/execution-target-sandbox.test.ts b/packages/adapter-utils/src/execution-target-sandbox.test.ts index e6e4dc69a55..103a77c7b4f 100644 --- a/packages/adapter-utils/src/execution-target-sandbox.test.ts +++ b/packages/adapter-utils/src/execution-target-sandbox.test.ts @@ -2401,4 +2401,147 @@ describe("sandbox adapter execution targets", () => { await new Promise((resolve) => apiServer.close(() => resolve())); } }); + + it("forwards bridge traffic to the local listen origin even when public API URLs are configured", async () => { + const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-execution-target-bridge-local-")); + cleanupDirs.push(rootDir); + const remoteCwd = path.join(rootDir, "workspace"); + const runtimeRootDir = path.join(remoteCwd, ".paperclip-runtime", "claude"); + await mkdir(runtimeRootDir, { recursive: true }); + + const requests: Array<{ method: string; url: string; auth: string | null; runId: string | null }> = []; + const apiServer = createServer((req, res) => { + requests.push({ + method: req.method ?? "GET", + url: req.url ?? "/", + auth: req.headers.authorization ?? null, + runId: typeof req.headers["x-paperclip-run-id"] === "string" ? req.headers["x-paperclip-run-id"] : null, + }); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true })); + }); + await new Promise((resolve, reject) => { + apiServer.once("error", reject); + apiServer.listen(0, "127.0.0.1", () => resolve()); + }); + const address = apiServer.address(); + if (!address || typeof address === "string") { + throw new Error("Expected the bridge local-origin test API server to listen on a TCP port."); + } + + // Simulate a deployment where a public base URL is configured: server boot + // exports the public origin via PAPERCLIP_RUNTIME_API_URL / PAPERCLIP_API_URL + // and the local listen host/port via PAPERCLIP_LISTEN_HOST / PAPERCLIP_LISTEN_PORT. + // The wildcard listen host must map to the loopback address of the same + // family (0.0.0.0 -> 127.0.0.1), where the test API server is bound. + vi.stubEnv("PAPERCLIP_RUNTIME_API_URL", "https://public.example.invalid"); + vi.stubEnv("PAPERCLIP_API_URL", "https://public.example.invalid"); + vi.stubEnv("PAPERCLIP_LISTEN_HOST", "0.0.0.0"); + vi.stubEnv("PAPERCLIP_LISTEN_PORT", String(address.port)); + + const target: AdapterSandboxExecutionTarget = { + kind: "remote", + transport: "sandbox", + providerKey: "e2b", + environmentId: "env-1", + leaseId: "lease-1", + remoteCwd, + runner: createLocalSandboxRunner(), + timeoutMs: 30_000, + }; + + const bridge = await startAdapterExecutionTargetPaperclipBridge({ + runId: "run-bridge-local", + target, + runtimeRootDir, + adapterKey: "claude", + hostApiToken: "real-run-jwt", + }); + try { + expect(bridge).not.toBeNull(); + const response = await fetch(`${bridge!.env.PAPERCLIP_API_URL}/api/agents/me`, { + headers: { + authorization: `Bearer ${bridge!.env.PAPERCLIP_API_KEY}`, + accept: "application/json", + }, + }); + + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ ok: true }); + expect(requests).toEqual([{ + method: "GET", + url: "/api/agents/me", + auth: "Bearer real-run-jwt", + runId: "run-bridge-local", + }]); + } finally { + await bridge?.stop(); + await new Promise((resolve) => apiServer.close(() => resolve())); + } + }); + + it("lets an explicit hostApiUrl input override the bridge forward target", async () => { + const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-execution-target-bridge-override-")); + cleanupDirs.push(rootDir); + const remoteCwd = path.join(rootDir, "workspace"); + const runtimeRootDir = path.join(remoteCwd, ".paperclip-runtime", "claude"); + await mkdir(runtimeRootDir, { recursive: true }); + + const requests: string[] = []; + const apiServer = createServer((req, res) => { + requests.push(req.url ?? "/"); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true })); + }); + await new Promise((resolve, reject) => { + apiServer.once("error", reject); + apiServer.listen(0, "127.0.0.1", () => resolve()); + }); + const address = apiServer.address(); + if (!address || typeof address === "string") { + throw new Error("Expected the bridge override test API server to listen on a TCP port."); + } + + // Neither the public URL envs nor the listen host/port should matter when + // the caller passes an explicit hostApiUrl. + vi.stubEnv("PAPERCLIP_RUNTIME_API_URL", "https://public.example.invalid"); + vi.stubEnv("PAPERCLIP_API_URL", "https://public.example.invalid"); + vi.stubEnv("PAPERCLIP_LISTEN_HOST", "203.0.113.1"); + vi.stubEnv("PAPERCLIP_LISTEN_PORT", "9"); + + const target: AdapterSandboxExecutionTarget = { + kind: "remote", + transport: "sandbox", + providerKey: "e2b", + environmentId: "env-1", + leaseId: "lease-1", + remoteCwd, + runner: createLocalSandboxRunner(), + timeoutMs: 30_000, + }; + + const bridge = await startAdapterExecutionTargetPaperclipBridge({ + runId: "run-bridge-override", + target, + runtimeRootDir, + adapterKey: "claude", + hostApiToken: "real-run-jwt", + hostApiUrl: `http://127.0.0.1:${address.port}`, + }); + try { + expect(bridge).not.toBeNull(); + const response = await fetch(`${bridge!.env.PAPERCLIP_API_URL}/api/agents/me`, { + headers: { + authorization: `Bearer ${bridge!.env.PAPERCLIP_API_KEY}`, + accept: "application/json", + }, + }); + + expect(response.status).toBe(200); + expect(requests).toEqual(["/api/agents/me"]); + } finally { + await bridge?.stop(); + await new Promise((resolve) => apiServer.close(() => resolve())); + } + }); }); diff --git a/packages/adapter-utils/src/execution-target.ts b/packages/adapter-utils/src/execution-target.ts index fd4a1586510..4c21a33acce 100644 --- a/packages/adapter-utils/src/execution-target.ts +++ b/packages/adapter-utils/src/execution-target.ts @@ -219,7 +219,12 @@ function readStringMeta(parsed: Record, key: string): string | function resolveHostForUrl(rawHost: string): string { const host = rawHost.trim(); - if (!host || host === "0.0.0.0" || host === "::") return "localhost"; + // Preserve the wildcard bind's address family: a server bound to 0.0.0.0 + // accepts IPv4, so target the IPv4 loopback (and [::1] for ::) instead of + // "localhost", which the resolver may map to the other family. + if (host === "0.0.0.0") return "127.0.0.1"; + if (host === "::") return "[::1]"; + if (!host) return "localhost"; if (host.includes(":") && !host.startsWith("[") && !host.endsWith("]")) return `[${host}]`; return host; } @@ -2104,11 +2109,19 @@ export async function startAdapterExecutionTargetPaperclipBridge(input: { typeof input.maxBodyBytes === "number" && Number.isFinite(input.maxBodyBytes) && input.maxBodyBytes > 0 ? Math.trunc(input.maxBodyBytes) : DEFAULT_SANDBOX_CALLBACK_BRIDGE_MAX_BODY_BYTES; - const hostApiUrl = - input.hostApiUrl?.trim() || - process.env.PAPERCLIP_RUNTIME_API_URL?.trim() || - process.env.PAPERCLIP_API_URL?.trim() || - resolveDefaultPaperclipApiUrl(); + // The bridge worker runs inside the same process that serves the Paperclip + // API, so forwarded sandbox calls must target the LOCAL listen origin. The + // PAPERCLIP_RUNTIME_API_URL / PAPERCLIP_API_URL exports now prefer a + // configured public base URL, which is the origin browsers and external + // agents use; routing this in-process loopback hop through the network edge + // breaks deployments whose public origin sits behind a session-gated proxy + // (every forwarded agent API call is rejected at the edge). Server boot + // exports PAPERCLIP_LISTEN_HOST / PAPERCLIP_LISTEN_PORT before any run + // executes, and resolveDefaultPaperclipApiUrl() maps wildcard listen hosts + // to the loopback address of the same family (0.0.0.0 -> 127.0.0.1, + // :: -> [::1]), so the fallback is always loopback-reachable. + // input.hostApiUrl stays available as an explicit override seam. + const hostApiUrl = input.hostApiUrl?.trim() || resolveDefaultPaperclipApiUrl(); const shellCommand = adapterExecutionTargetShellCommand(target); const runner = adapterExecutionTargetCommandRunner(target); const bridgeTimeoutMs =