Skip to content
Merged
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
12 changes: 8 additions & 4 deletions apps/server/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -528,14 +528,18 @@ export const layer = Contract.Api.toLayer(
expiresAt: started.expiresAt,
};

// Arm the loopback waiter before emitting Authorize so a fast redirect cannot arrive early.
const expectedPath = new URL(started.redirectUrl).pathname;
const waitCallback = loopback
.wait(started.state, expectedPath)
.pipe(Effect.mapError((message) => new DesktopConnectorError({ message })));

const completion = Stream.fromEffect(
Effect.gen(function* () {
const code = yield* loopback
.wait(started.state)
.pipe(Effect.mapError((message) => new DesktopConnectorError({ message })));
const callbackUrl = yield* waitCallback;
const connection = yield* onMachine(machineId)(
connectorCall((client) =>
client("connections.oauth.finish", { state: started.state, code }),
client("connections.oauth.finish", { state: started.state, code: callbackUrl }),
),
);
return { _tag: "Connected", connection } satisfies OAuthRunEvent;
Expand Down
97 changes: 74 additions & 23 deletions apps/server/src/oauth-loopback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,34 @@
import { createServer, type ServerResponse } from "node:http";
import { Deferred, Effect } from "effect";

const successHtml = (title: string, detail: string) =>
`<!doctype html><html><head><meta charset="utf-8"><title>${title}</title><style>body{font-family:system-ui,-apple-system,sans-serif;display:grid;place-items:center;min-height:100vh;margin:0;background:#0f1115;color:#eef1f6}main{max-width:420px;padding:32px;border-radius:14px;background:#171a21;border:1px solid #262b36;text-align:center}h1{font-size:18px;margin:0 0 8px}p{font-size:14px;color:#9aa3b2;margin:0}</style></head><body><main><h1>${title}</h1><p>${detail}</p></main></body></html>`;
const PER_SERVER_CALLBACK = /^\/oauth\/callback\/[A-Za-z0-9_-]{12}$/;

const escapeHtml = (value: string) =>
value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;");

const statusHtml = (ok: boolean, title: string, detail: string, errorDetail?: string) => {
const icon = ok
? `<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path d="M4.5 10.5L8.25 14.25L15.5 6.25" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/></svg>`
: `<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path d="M5.75 5.75L14.25 14.25M14.25 5.75L5.75 14.25" stroke="currentColor" stroke-width="1.75" stroke-linecap="round"/></svg>`;
const extra = errorDetail ? `<p class="code">${escapeHtml(errorDetail)}</p>` : "";
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)}</title><style>:root{color-scheme:light dark;--bg:light-dark(#f9f9fa,#09090a);--ink:light-dark(#1b1b1b,#f7f8f8);--muted:light-dark(#5e5e60,#959597);--edge:light-dark(#e2e2e2,#212224);--tone:${ok ? "light-dark(#16a34a,#4cb782)" : "light-dark(#dc2626,#eb5757)"}}*{box-sizing:border-box}body{margin:0;min-height:100dvh;display:grid;place-items:center;padding:24px 24px 8vh;background:var(--bg);color:var(--ink);font-family:-apple-system,BlinkMacSystemFont,"Inter","Segoe UI",system-ui,sans-serif;-webkit-font-smoothing:antialiased;text-align:center}main{width:100%;max-width:360px;display:flex;flex-direction:column;align-items:center}.mark{color:var(--tone);margin-bottom:14px;display:grid;place-items:center}h1{margin:0 0 6px;font-size:17px;font-weight:560;letter-spacing:-0.02em;line-height:1.3;text-wrap:balance}p{margin:0;font-size:13.5px;line-height:1.55;color:var(--muted);text-wrap:balance}.code{margin-top:16px;padding-top:12px;width:100%;border-top:1px solid var(--edge);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;color:var(--muted);white-space:pre-wrap;word-break:break-word}</style></head><body><main><div class="mark">${icon}</div><h1>${escapeHtml(title)}</h1><p>${escapeHtml(detail)}</p>${extra}</main></body></html>`;
};

const replyHtml = (res: ServerResponse, status: number, html: string) =>
res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(html);

export interface LoopbackHandle {
readonly redirectUrl: string;
readonly wait: (state: string) => Effect.Effect<string, string>;
/**
* Arms and returns an Effect waiting for the full observed callback URL carrying `state`.
* When `expectedPath` is given, a response on another path fails immediately (RFC 9700 §4.4.2.2).
*/
readonly wait: (state: string, expectedPath?: string) => Effect.Effect<string, string>;
}

/**
Expand All @@ -37,61 +56,93 @@ export const acquireLoopback = (opts: {
}
});
}),
({ server }) => Effect.callback<void>((resume) => void server.close(() => resume(Effect.void))),
({ server }) =>
Effect.callback<void>((resume) => {
server.close(() => resume(Effect.void));
server.closeIdleConnections();
}),
).pipe(
Effect.map(({ server, port }): LoopbackHandle => {
const redirectUrl = `http://${opts.redirectHost}:${port}${opts.path}`;
const pending = new Map<string, Deferred.Deferred<string, string>>();
const defaultHost = `${opts.redirectHost}:${port}`;
const redirectUrl = `http://${defaultHost}${opts.path}`;
const allowedHosts = new Set([
defaultHost.toLowerCase(),
...(opts.redirectHost === "127.0.0.1" ? [`localhost:${port}`] : []),
]);
const pending = new Map<
string,
{ readonly deferred: Deferred.Deferred<string, string>; readonly expectedPath?: string | undefined }
>();

server.on("request", (req, res) => {
const url = new URL(req.url ?? "/", redirectUrl);
if (url.pathname !== opts.path) {
return replyHtml(res, 404, successHtml("Not found", "Unexpected callback path."));
const rawHost = req.headers.host?.trim().toLowerCase();
const effectiveHost = rawHost !== undefined && allowedHosts.has(rawHost) ? rawHost : defaultHost;
const url = new URL(req.url ?? "/", `http://${effectiveHost}`);
const pathAccepted =
url.pathname === opts.path ||
(opts.path === "/oauth/callback" && PER_SERVER_CALLBACK.test(url.pathname));
if (!pathAccepted) {
return replyHtml(res, 404, statusHtml(false, "Not found", "Unexpected callback path."));
}
const state = url.searchParams.get("state");
const waiting = state === null ? undefined : pending.get(state);
if (state === null || waiting === undefined) {
return replyHtml(
res,
400,
successHtml(
statusHtml(
false,
"Link expired",
"This authorization session is no longer active. You may close this tab.",
"This authorization session is no longer active. You can close this tab.",
),
);
}
pending.delete(state);
if (waiting.expectedPath !== undefined && url.pathname !== waiting.expectedPath) {
Deferred.doneUnsafe(
waiting.deferred,
Effect.fail("The authorization response arrived on another redirect URI"),
);
return replyHtml(
res,
400,
statusHtml(false, "Unexpected redirect URI", "This callback path does not match the active sign-in."),
);
}
const error = url.searchParams.get("error");
const code = url.searchParams.get("code");
if (error !== null) {
const desc = url.searchParams.get("error_description") ?? error;
Deferred.doneUnsafe(waiting, Effect.fail(desc));
return replyHtml(res, 200, successHtml("Authorization failed", desc));
Deferred.doneUnsafe(waiting.deferred, Effect.fail(desc));
return replyHtml(
res,
200,
statusHtml(false, "Authorization failed", "You can close this tab and try again in CodeWork.", desc),
);
}
if (code === null || code.length === 0) {
Deferred.doneUnsafe(waiting, Effect.fail("Missing authorization code"));
Deferred.doneUnsafe(waiting.deferred, Effect.fail("Missing authorization code"));
return replyHtml(
res,
400,
successHtml("Missing code", "The provider did not return an authorization code."),
statusHtml(false, "Missing code", "The provider did not return an authorization code."),
);
}
Deferred.doneUnsafe(waiting, Effect.succeed(code));
Deferred.doneUnsafe(waiting.deferred, Effect.succeed(url.href));
return replyHtml(
res,
200,
successHtml("Connected to CodeWork", "You can close this window and return to CodeWork."),
statusHtml(true, "Connected to CodeWork", "You can close this tab and return to CodeWork."),
);
});

return {
redirectUrl,
wait: (state) =>
Effect.suspend(() => {
const deferred = Deferred.makeUnsafe<string, string>();
pending.set(state, deferred);
return Deferred.await(deferred).pipe(Effect.ensuring(Effect.sync(() => pending.delete(state))));
}),
wait: (state, expectedPath) => {
const deferred = Deferred.makeUnsafe<string, string>();
pending.set(state, { deferred, expectedPath });
return Deferred.await(deferred).pipe(Effect.ensuring(Effect.sync(() => pending.delete(state))));
},
};
}),
);
12 changes: 12 additions & 0 deletions apps/server/test/__artifacts__/oauth-loopback.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"perStatus": 200,
"perPath": "/oauth/callback/-zkQPH0u2sKR",
"perCode": "code-per",
"wrongStatus": 400,
"wrongErr": "The authorization response arrived on another redirect URI",
"localStatus": 200,
"localHost": "localhost",
"localIss": "https://clerk.example",
"xssEscaped": true,
"xssErr": "<script>alert(1)</script>"
}
75 changes: 75 additions & 0 deletions apps/server/test/oauth-loopback.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/* @effect-diagnostics asyncFunction:off -- vitest test bodies are async. */
/* @effect-diagnostics preferSchemaOverJson:off -- test artifacts serialize plain JSON. */
import { Effect } from "effect";
import { expect, it } from "vite-plus/test";
import { acquireLoopback } from "../src/oauth-loopback.ts";

it("desktop oauth loopback enforces per-server paths, preserves localhost rewrites, and escapes error HTML", async () => {
const artifact = await Effect.gen(function* () {
const loopback = yield* acquireLoopback({
host: "127.0.0.1",
redirectHost: "127.0.0.1",
port: 0,
path: "/oauth/callback",
});
const base = new URL(loopback.redirectUrl);

// 1. Per-server path accepted and preserves full callback URL (code + state + iss)
const perPath = "/oauth/callback/-zkQPH0u2sKR";
const waitPer = loopback.wait("state-per", perPath);
const perUrl = new URL(perPath, base);
perUrl.searchParams.set("code", "code-per");
perUrl.searchParams.set("state", "state-per");
const perRes = yield* Effect.promise(() => fetch(perUrl.href));
const perCallback = yield* waitPer;

// 2. Wrong path with valid state is rejected
const waitWrong = loopback.wait("state-wrong", perPath);
const wrongUrl = new URL("/oauth/callback", base);
wrongUrl.searchParams.set("code", "code-wrong");
wrongUrl.searchParams.set("state", "state-wrong");
const wrongRes = yield* Effect.promise(() => fetch(wrongUrl.href));
const wrongErr = yield* waitWrong.pipe(Effect.flip);

// 3. Clerk `127.0.0.1` -> `localhost` rewrite is preserved in observed callback URL
const waitLocalhost = loopback.wait("state-local", "/oauth/callback");
const localUrl = new URL("/oauth/callback", base);
localUrl.hostname = "localhost";
localUrl.searchParams.set("code", "code-local");
localUrl.searchParams.set("state", "state-local");
localUrl.searchParams.set("iss", "https://clerk.example");
const localRes = yield* Effect.promise(() => fetch(localUrl.href));
const localCallback = new URL(yield* waitLocalhost);

// 4. Error description is HTML-escaped on the browser page
const waitErr = loopback.wait("state-xss", "/oauth/callback");
const xssUrl = new URL("/oauth/callback", base);
xssUrl.searchParams.set("state", "state-xss");
xssUrl.searchParams.set("error", "access_denied");
xssUrl.searchParams.set("error_description", "<script>alert(1)</script>");
const xssRes = yield* Effect.promise(() => fetch(xssUrl.href));
const xssHtml = yield* Effect.promise(() => xssRes.text());
const xssErr = yield* waitErr.pipe(Effect.flip);

return {
perStatus: perRes.status,
perPath: new URL(perCallback).pathname,
perCode: new URL(perCallback).searchParams.get("code"),
wrongStatus: wrongRes.status,
wrongErr,
localStatus: localRes.status,
localHost: localCallback.hostname,
localIss: localCallback.searchParams.get("iss"),
xssEscaped: !xssHtml.includes("<script>") && xssHtml.includes("&lt;script&gt;alert(1)&lt;/script&gt;"),
xssErr,
};
}).pipe(Effect.scoped, Effect.runPromise);

expect(artifact.perStatus).toBe(200);
expect(artifact.perPath).toBe("/oauth/callback/-zkQPH0u2sKR");
expect(artifact.wrongStatus).toBe(400);
expect(artifact.localHost).toBe("localhost");
expect(artifact.localIss).toBe("https://clerk.example");
expect(artifact.xssEscaped).toBe(true);
await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/oauth-loopback.json");
});
2 changes: 1 addition & 1 deletion apps/web/src/settings/connectors/inline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,7 @@ function OAuthBrowserStep({

<div className="flex flex-col gap-1.5">
<label htmlFor={`oauth-manual-${connection.id}`} className="text-2xs text-ink-muted">
Browser didn’t redirect back? Paste the redirected URL or code:
Browser didn’t redirect back? Paste the full redirected URL:
</label>
<div className="flex gap-2">
<Input
Expand Down
2 changes: 2 additions & 0 deletions docs/internals/08_plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ Servers come from two sources: `mcp.json` beside each settings file, in the `mcp

Connections never open a browser. They use stored tokens, refresh them, or move to `authenticate`, and the user signs in with `codework connect` (for connector-backed servers) or `codework mcp login` (for legacy `mcp.json` OAuth servers). Server states are single words. Connector-backed MCP credentials live in `<home>/connections.db`, validated against the connection's `allowedHosts` before any token is injected, with single-flight refresh locking; legacy `mcp.json` OAuth tokens live in `<home>/mcpauth.json` under a cross-process refresh lock because servers rotate refresh tokens and a token used twice loses the grant ([oauth.ts](../../packages/harness/src/mcp/oauth.ts)). A tool call is never retried once the server may have run it.

Both MCP sign-in and Connectors identify CodeWork with a Client ID Metadata Document (CIMD) hosted on `https://codework.sh/oauth/` and share one loopback callback path: `/oauth/callback` ([cimd.ts](../../packages/harness/src/mcp/cimd.ts)). After discovery, if no custom `clientId`, `clientName`, or unlisted redirect URI is configured and the server advertises `client_id_metadata_document_supported` with `none` token auth (which allows servers with DCR off, such as Clerk, to sign in without manual registration), CodeWork uses `https://codework.sh/oauth/client.json` when the server advertises RFC 9207 `iss` support, or a per-resource document `https://codework.sh/oauth/<id>/client.json` with callback `/oauth/callback/<id>` otherwise so codes from different servers cannot be mixed up (RFC 9700 §4.4.2.2). Without CIMD support it falls back to DCR. CIMD client IDs are never stored as DCR registrations in `mcpauth.json`, so future sign-ins always re-decide from discovery while refreshes reuse the grant's issuing client ID.

## Examples

[`extras/`](../../extras) holds example third-party plugins: a tool plugin, a prompt plugin, single-file local plugins and a sandbox driver. The tool and prompt examples export TypeScript and are loaded by path in this repo, so they are not installable from a registry as written.
2 changes: 1 addition & 1 deletion docs/internals/09_server.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ The CLI runs the harness in-process when there is no `--server`, and that mode s

Threads are shared, so the event stream a CLI client reads carries other clients' work too. [client.ts](../../packages/codework/src/server/client.ts) attributes every terminal event to its own prompt before believing it.

Browser callbacks stay on the client machine because a localhost redirect cannot cross RPC. For `codework connect` and the desktop app, the host starts PKCE/DCR and exchanges the code (`connections.oauth.*` in [oauth.ts](../../packages/codework/src/connector/oauth.ts)) while the client runs the temporary loopback listener (or device-code prompt). Legacy `codework auth` still runs the full login in the CLI and sends the resulting credentials to the server ([oauth.ts](../../packages/codework/src/server/oauth.ts)).
Browser callbacks stay on the client machine because a localhost redirect cannot cross RPC. For `codework connect` and the desktop app, the client binds a local loopback listener on `/oauth/callback` and passes its base redirect URI to `connections.oauth.start`; the host runs discovery, selects CIMD (shared or per-server `/oauth/callback/<id>`) or DCR, returns the final `redirectUrl`, and validates the full observed callback URL (`state`, path, `iss`, and any `127.0.0.1` → `localhost` rewrite) in `connections.oauth.finish` ([oauth.ts](../../packages/codework/src/connector/oauth.ts)). Legacy `codework auth` still runs the full login in the CLI and sends the resulting credentials to the server ([oauth.ts](../../packages/codework/src/server/oauth.ts)).

## Two Ways to Keep Up

Expand Down
Loading