Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ Desktop packaging targets macOS only (from `packages/desktop`): `CM_BRAND=1 bun

Everything custom lives in `packages/desktop/src/main/wpp-bridge/`. It turns authenticated **WPP Open** browser sessions (`ogilvy.os.wpp.com` — Ogilvy/WPP's AI platform, NOT WhatsApp) into an OpenAI-compatible model backend.

1. `proxy/server.mjs` — HTTP server (default :8787, override with `O1_CODE_PROXY_HOST`/`O1_CODE_PROXY_PORT`): `POST /v1/chat/completions`, `GET /v1/models`, `POST /bridge/login`, `GET /bridge/health`, `GET /health`, and `GET /` + `/status` (diagnostic HTML from `proxy/statusPage.mjs`). Model ids are the `CM_*` roster in `proxy/modelProfiles.mjs` — **not** the retired `o1-code`. An origin guard rejects cross-site browser callers; the sidecar's server-to-server fetch sends no `Origin`, which is allowed. `proxy/openaiCompat.mjs` adapts OpenAI request/response shapes.
1. `proxy/server.mjs` — HTTP server (default :8787, override with `O1_CODE_PROXY_HOST`/`O1_CODE_PROXY_PORT`): `POST /v1/chat/completions`, `GET /v1/models`, `POST /bridge/login`, `GET /bridge/health`, `GET /health`, and `GET /` + `/status` (diagnostic HTML from `proxy/statusPage.mjs`). Model ids are the `CM_*` roster in `proxy/modelProfiles.mjs` — **not** the retired `o1-code`. A Host check admits only `localhost`, IP literals and the configured bind host, which blocks DNS rebinding. An origin guard then rejects cross-site and browser-extension callers; the sidecar's server-to-server fetch sends no `Origin`, which is allowed. `proxy/openaiCompat.mjs` adapts OpenAI request/response shapes.
2. `proxy/extensionBridge.mjs` queues jobs onto a `WorkerPool` (`worker-pool.ts`).
3. Each worker is a hidden Electron BrowserWindow (`session.ts`) on the persistent `persist:wpp` partition (SSO cookies survive restarts — log in once). `controller-injection.ts` injects a job handler (`injected/content.js`) via CDP into the page's main world; `recorder-injection.ts` injects the main-world `injected/pageRecorder.js` (the SSE/JSON parser) at document-start.
4. `WorkerPool.run(job, onProgress)` is the single entry point: `acquire(agent)` (soft per-agent affinity) → `spawn()` if needed → `controller.runJob()` → stream progress → `release()`.
Expand Down
39 changes: 39 additions & 0 deletions packages/desktop/src/main/wpp-bridge/proxy/server-auth.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,45 @@
import { expect, test } from "bun:test";
import net from "node:net";
import { startServerWithActions } from "./server.mjs";

// fetch() always sends the real Host header, so a raw request stands in for a DNS-rebinding page.
function statusWithHost(port, path, host) {
const crlf = String.fromCharCode(13, 10);
return new Promise((resolve, reject) => {
let reply = "";
const socket = net.connect(port, "127.0.0.1", () => {
socket.write([`GET ${path} HTTP/1.1`, `Host: ${host}`, "Connection: close", "", ""].join(crlf));
});
socket.setEncoding("utf8");
socket.on("data", (chunk) => { reply += chunk; });
socket.on("end", () => resolve(Number(reply.split(" ")[1])));
socket.on("error", reject);
});
}

test("every route rejects a rebinding Host and extension origins", async () => {
let login = 0;
const server = await startServerWithActions({
host: "127.0.0.1", port: 0,
checkAuth: async () => ({ status: "signed-in" }),
openLogin: async () => { login++; },
});
const port = server.address().port;
try {
for (const path of ["/status", "/health", "/bridge/health", "/bridge/auth", "/v1/models"]) {
expect(await statusWithHost(port, path, "rebind.example:" + port)).toBe(403);
expect(await statusWithHost(port, path, "127.0.0.1:" + port)).toBe(200);
expect(await statusWithHost(port, path, "localhost:" + port)).toBe(200);
}
const extension = { method: "POST", headers: { Origin: "chrome-extension://abcdefghijklmnop" } };
expect((await fetch("http://127.0.0.1:" + port + "/bridge/login", extension)).status).toBe(403);
expect(login).toBe(0);
} finally {
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
}
});

test("live auth probe discloses only status, enforces origin checks and opens sign-in", async () => {
let status = "signed-out";
let login = 0;
Expand Down
56 changes: 39 additions & 17 deletions packages/desktop/src/main/wpp-bridge/proxy/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export async function startServerWithActions({ host = DEFAULT_HOST, port = DEFAU
if (typeof openLogin === "function") extensionBridge.onAuthRequired = openLogin;
const server = http.createServer(async (request, response) => {
try {
await route(request, response, { openLogin, checkAuth });
await route(request, response, { openLogin, checkAuth }, host);
} catch (error) {
writeJson(response, error.statusCode || 500, {
error: {
Expand Down Expand Up @@ -49,10 +49,10 @@ export async function startServerWithActions({ host = DEFAULT_HOST, port = DEFAU
return server;
}

async function route(request, response, actions = {}) {
async function route(request, response, actions = {}, bindHost = DEFAULT_HOST) {
const url = new URL(request.url, "http://127.0.0.1");

if (!enforceBrowserOrigin(request, response)) {
if (!enforceBrowserOrigin(request, response, bindHost)) {
return;
}

Expand Down Expand Up @@ -128,7 +128,19 @@ async function route(request, response, actions = {}) {
});
}

function enforceBrowserOrigin(request, response) {
function enforceBrowserOrigin(request, response, bindHost) {
// DNS rebinding points an attacker's hostname at this port. Its requests are same-origin to the
// attacker's page, so a GET carries no Origin and would pass the origin checks below.
if (!isAllowedHost(request.headers.host, bindHost)) {
writeJson(response, 403, {
error: {
message: "Request host is not allowed to access the local O1-Code proxy.",
type: "forbidden_host"
}
});
return false;
}

if (isAllowedBrowserRequest(request.headers)) {
return true;
}
Expand All @@ -145,6 +157,27 @@ function enforceBrowserOrigin(request, response) {
return false;
}

// Rebinding needs a hostname the attacker controls, so IP literals and localhost are safe. The
// configured bind host stays allowed for an O1_CODE_PROXY_HOST that names this machine.
export function isAllowedHost(host, bindHost = DEFAULT_HOST) {
// Browsers send a bare host and optional port. Reject anything URL parsing could reinterpret.
if (!host || /[/@?#\\\s]/.test(host)) {
return false;
}

try {
const name = new URL(`http://${host}`).hostname.toLowerCase();

// URL parsing leaves an IPv4 literal in dotted-decimal form and an IPv6 literal in brackets.
return name === "localhost" ||
name === bindHost.toLowerCase() ||
name.startsWith("[") ||
/^\d+\.\d+\.\d+\.\d+$/.test(name);
} catch {
return false;
}
}

function writeCors(response, request) {
const origin = request.headers.origin;

Expand All @@ -163,10 +196,6 @@ export function isAllowedBrowserOrigin(origin) {
return true;
}

if (String(origin).startsWith("chrome-extension://")) {
return true;
}

try {
const url = new URL(origin);

Expand All @@ -182,18 +211,11 @@ export function isAllowedBrowserOrigin(origin) {
}

export function isAllowedBrowserRequest(headers = {}) {
const origin = headers.origin;
const fetchSite = headers["sec-fetch-site"];

if (isAllowedBrowserOrigin(origin) && String(origin || "").startsWith("chrome-extension://")) {
return true;
}

if (fetchSite === "cross-site") {
if (headers["sec-fetch-site"] === "cross-site") {
return false;
}

return isAllowedBrowserOrigin(origin);
return isAllowedBrowserOrigin(headers.origin);
}

export async function readJson(request, maxBytes = MAX_REQUEST_BODY_BYTES) {
Expand Down
38 changes: 37 additions & 1 deletion packages/desktop/src/main/wpp-bridge/proxy/server.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,42 @@
import { describe, expect, test } from "bun:test"
import { Readable } from "node:stream"
import { readJson } from "./server.mjs"
import { isAllowedBrowserRequest, isAllowedHost, readJson } from "./server.mjs"

describe("isAllowedHost", () => {
test("allows localhost and IP literals, with or without a port", () => {
const hosts = ["127.0.0.1:8787", "127.0.0.1", "localhost:8787", "LOCALHOST", "[::1]:8787", "192.168.1.20:8787"]
expect(hosts.filter((host) => !isAllowedHost(host, "127.0.0.1"))).toEqual([])
})

test("rejects other hostnames, so a DNS-rebinding page cannot reach the proxy", () => {
const hosts = [
undefined,
"",
"rebind.example",
"rebind.example:8787",
"127.0.0.1.nip.io:8787",
"localhost.rebind.example",
"rebind.example@127.0.0.1",
"127.0.0.1/rebind.example",
"127.0.0.1 rebind.example",
]
expect(hosts.filter((host) => isAllowedHost(host, "127.0.0.1"))).toEqual([])
})

test("allows the configured bind host name", () => {
expect(isAllowedHost("devbox.lan:8787", "devbox.lan")).toBe(true)
expect(isAllowedHost("DevBox.lan:8787", "devbox.lan")).toBe(true)
expect(isAllowedHost("devbox.lan:8787", "127.0.0.1")).toBe(false)
})
})

describe("isAllowedBrowserRequest", () => {
test("rejects browser extension origins now that the extension job queue is gone", () => {
expect(isAllowedBrowserRequest({ origin: "chrome-extension://abcdefghijklmnop" })).toBe(false)
expect(isAllowedBrowserRequest({ origin: "http://127.0.0.1:8787", "sec-fetch-site": "same-origin" })).toBe(true)
expect(isAllowedBrowserRequest({})).toBe(true)
})
})

describe("readJson", () => {
test("rejects a declared request body above the limit before reading it", async () => {
Expand Down
Loading