Skip to content

An open-source, faster Devin alternative

TypeScript

fix api edge websocket query auth

Igor Zalutskib6e90702bc93
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 46be32d1..f60191cd 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -343,7 +343,8 @@ async function proxyWebSocket(
}
if (ArrayBuffer.isView(data)) {
const v = data as ArrayBufferView;
- const ab = v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength);
+ const ab = new ArrayBuffer(v.byteLength);
+ new Uint8Array(ab).set(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
addBytes(ab.byteLength);
try { target.send(ab); } catch (err) { console.error(`${label}: send (view) failed: ${(err as Error).message}`); }
return Promise.resolve();
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
new file mode 100644
index 00000000..8f5208a1
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -0,0 +1,118 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import worker, { type Env } from "./index";
+
+const orgID = "org-1";
+const userID = "user-1";
+const cellID = "azure-us-east-2-a";
+
+class FakeStatement {
+ constructor(private sql: string) {}
+
+ bind(..._args: unknown[]) {
+ return this;
+ }
+
+ async first<T>(): Promise<T | null> {
+ if (this.sql.includes("FROM api_keys")) {
+ return { org_id: orgID, created_by: userID, expires_at: null } as T;
+ }
+ if (this.sql.includes("FROM sandboxes_index") && this.sql.includes("SELECT cell_id, org_id")) {
+ return { cell_id: cellID, org_id: orgID } as T;
+ }
+ if (this.sql.includes("FROM cells WHERE cell_id")) {
+ return {
+ cell_id: cellID,
+ cloud: "azure",
+ region: "us-east-2",
+ base_url: "https://cp-us-east-2.opencomputer.dev",
+ status: "active",
+ available_workers: 1,
+ capacity_updated_at: Math.floor(Date.now() / 1000),
+ } as T;
+ }
+ if (this.sql.includes("SELECT plan FROM orgs")) {
+ return { plan: "pro" } as T;
+ }
+ return null;
+ }
+
+ async run() {
+ return {};
+ }
+}
+
+const env = {
+ OPENCOMPUTER_DB: {
+ prepare(sql: string) {
+ return new FakeStatement(sql);
+ },
+ },
+ SESSIONS_KV: {},
+ CREDIT_ACCOUNT: {},
+ SESSION_JWT_SECRET: "test-secret",
+ WORKOS_API_KEY: "",
+ WORKOS_CLIENT_ID: "",
+ STRIPE_API_KEY: "",
+ WORKER_ENV: "test",
+ CELLS: cellID,
+ CF_ADMIN_SECRET: "",
+ STRIPE_WEBHOOK_SECRET: "",
+ EVENT_SECRET: "",
+ SECRET_ENCRYPTION_KEY: "",
+} as unknown as Env;
+
+const ctx = {
+ waitUntil: vi.fn(),
+ passThroughOnException: vi.fn(),
+} as unknown as ExecutionContext;
+
+describe("api-edge WebSocket auth", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("accepts api_key query auth for sandbox WebSocket proxy requests", async () => {
+ const fetchSpy = vi.fn(async (_req: Request) => new Response("proxied", { status: 200 }));
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const resp = await worker.fetch(
+ new Request(
+ "https://app.opencomputer.dev/api/sandboxes/sb-123/exec/es-123?api_key=osb_test&stream=1",
+ {
+ headers: {
+ Upgrade: "websocket",
+ },
+ },
+ ),
+ env,
+ ctx,
+ );
+
+ expect(resp.status).toBe(200);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+
+ const forwarded = fetchSpy.mock.calls[0][0] as Request;
+ const forwardedURL = new URL(forwarded.url);
+ expect(forwardedURL.origin).toBe("https://cp-us-east-2.opencomputer.dev");
+ expect(forwardedURL.pathname).toBe("/api/sandboxes/sb-123/exec/es-123");
+ expect(forwardedURL.searchParams.get("stream")).toBe("1");
+ expect(forwardedURL.searchParams.has("api_key")).toBe(false);
+ expect(forwarded.headers.get("authorization")).toMatch(/^Bearer /);
+ expect(forwarded.headers.get("x-api-key")).toBeNull();
+ });
+
+ it("does not accept api_key query auth for non-WebSocket HTTP requests", async () => {
+ const fetchSpy = vi.fn(async (_req: Request) => new Response("proxied", { status: 200 }));
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const resp = await worker.fetch(
+ new Request("https://app.opencomputer.dev/api/sandboxes/sb-123/exec/es-123?api_key=osb_test"),
+ env,
+ ctx,
+ );
+
+ expect(resp.status).toBe(401);
+ expect(await resp.json()).toEqual({ error: "missing or invalid API key" });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index f566d175..b7bb418d 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -98,10 +98,35 @@ interface Caller {
userID: string | null;
}
-// Authenticate via X-API-Key (looked up by sha256 in D1 api_keys). Session-JWT
-// auth (browser flows) is a TODO; SDK/test traffic uses the API key.
+function isWebSocketUpgrade(req: Request): boolean {
+ return req.headers.get("upgrade")?.toLowerCase() === "websocket";
+}
+
+function apiKeyFromRequest(req: Request): string | null {
+ const headerKey = req.headers.get("X-API-Key");
+ if (headerKey) return headerKey;
+
+ // Browser WebSocket clients cannot set custom headers, so SDK attach uses
+ // `?api_key=`. Keep this limited to Upgrade requests to avoid normalizing
+ // query-string credentials across the whole HTTP API.
+ if (isWebSocketUpgrade(req)) {
+ return new URL(req.url).searchParams.get("api_key");
+ }
+ return null;
+}
+
+function stripEdgeAuthQueryParam(target: string): string {
+ const url = new URL(target);
+ url.searchParams.delete("api_key");
+ return url.toString();
+}
+
+// Authenticate via X-API-Key (looked up by sha256 in D1 api_keys). For
+// WebSocket Upgrade requests, also accept ?api_key= because browser WS APIs
+// cannot set custom headers. Session-JWT auth (browser flows) is a TODO;
+// SDK/test traffic uses the API key.
async function authenticate(req: Request, env: Env): Promise<Caller | null> {
- const apiKey = req.headers.get("X-API-Key");
+ const apiKey = apiKeyFromRequest(req);
if (!apiKey) return null;
const hash = await sha256Hex(apiKey);
const row = await env.OPENCOMPUTER_DB.prepare(
@@ -611,8 +636,8 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
// accept-key derivation). CF Workers + CF Tunnel forward WebSocket
// upgrades transparently when you pass a Request clone — same pattern
// handlePreviewURL uses and that's verified to work end-to-end with WS.
- if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
- const fwd = new Request(target, req);
+ if (isWebSocketUpgrade(req)) {
+ const fwd = new Request(stripEdgeAuthQueryParam(target), req);
fwd.headers.set("authorization", "Bearer " + token);
fwd.headers.delete("x-api-key");
return await fetch(fwd);