From e1444ca3344572d4b4a96317984d279de739aea4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 11:07:56 -0600 Subject: [PATCH] feat(desktop-commander): OAuth 2.1 front door for hosted MCP clients (#13404) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude and ChatGPT connect to the MCP endpoint from their own servers and cannot pass a Cloudflare Access login at /mcp — every path on commander.security.cab answered them with a 302 to the Access login, and there was no OAuth discovery to find. The Worker now runs an OAuth 2.1 authorization server (src/oauth.ts): - Public discovery: /.well-known/oauth-protected-resource (both shapes) and /.well-known/oauth-authorization-server. - POST /register: dynamic client registration, public clients, https / loopback-http redirect URIs, stored in the new OAUTH_KV namespace (desktop-commander-oauth). - GET/POST /authorize: the approval page — the one path that stays behind Access (the app is re-scoped to /authorize separately). The Worker verifies the Access JWT itself (RS256 vs the team JWKS, audience, owner email) before rendering; approval is a CSRF-nonce form POST issuing a single-use PKCE-bound code. - POST /token: authorization-code exchange (PKCE S256; the code is consumed on any exchange attempt) plus rotating refresh tokens. Codes and tokens are stored in KV under their SHA-256. - /mcp takes a live OAuth Bearer or the new MACHINE_BEARER secret; anything else gets a 401 with the resource_metadata pointer. The bridge door and the proxy core are unchanged. The publish workflow now also stages MACHINE_BEARER (GitHub environment secret; canonical value in fleet secrets as desktop-commander.machine-bearer) into the version secrets file. wrangler.toml and cloudflare.config.ts gain the OAUTH_KV binding and the ACCESS_AUD / ACCESS_TEAM_DOMAIN vars, kept in step. Tests: 21 green (proxy contract re-pointed at the new gate, plus an OAuth suite with a real in-test RSA keypair standing in for the Access team key: discovery, DCR validation, assertion rejection, plain-PKCE rejection, full approve-exchange-call flow, code single-use, wrong-verifier burn, refresh rotation, deny redirect). --- .../desktop-commander-worker-publish.yml | 6 +- pkgs/desktop-commander/worker/README.md | 70 ++- .../worker/cloudflare.config.ts | 12 +- pkgs/desktop-commander/worker/src/index.ts | 89 ++- pkgs/desktop-commander/worker/src/oauth.ts | 507 ++++++++++++++++++ .../worker/test/memory-kv.ts | 36 ++ .../worker/test/oauth.test.ts | 428 +++++++++++++++ .../worker/test/proxy.test.ts | 27 +- pkgs/desktop-commander/worker/wrangler.toml | 25 +- 9 files changed, 1151 insertions(+), 49 deletions(-) create mode 100644 pkgs/desktop-commander/worker/src/oauth.ts create mode 100644 pkgs/desktop-commander/worker/test/memory-kv.ts create mode 100644 pkgs/desktop-commander/worker/test/oauth.test.ts diff --git a/.github/workflows/desktop-commander-worker-publish.yml b/.github/workflows/desktop-commander-worker-publish.yml index 7051f12f6..b59e2b93c 100644 --- a/.github/workflows/desktop-commander-worker-publish.yml +++ b/.github/workflows/desktop-commander-worker-publish.yml @@ -44,10 +44,11 @@ jobs: CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} GITHUB_SHA: ${{ github.sha }} run: node upload-version.mjs --dry-run - - name: Stage bridge-door secrets file + - name: Stage Worker secrets file env: BRIDGE_ACCESS_CLIENT_ID: ${{ secrets.BRIDGE_ACCESS_CLIENT_ID }} BRIDGE_ACCESS_CLIENT_SECRET: ${{ secrets.BRIDGE_ACCESS_CLIENT_SECRET }} + MACHINE_BEARER: ${{ secrets.MACHINE_BEARER }} run: | umask 077 python3 - "$RUNNER_TEMP/desktop-commander-secrets.json" <<'PY' @@ -55,9 +56,10 @@ jobs: data = { "ACCESS_CLIENT_ID": os.environ["BRIDGE_ACCESS_CLIENT_ID"], "ACCESS_CLIENT_SECRET": os.environ["BRIDGE_ACCESS_CLIENT_SECRET"], + "MACHINE_BEARER": os.environ["MACHINE_BEARER"], } if not all(data.values()): - raise SystemExit("bridge Access secrets are empty") + raise SystemExit("Worker secrets are empty") with open(sys.argv[1], "w") as f: json.dump(data, f) PY diff --git a/pkgs/desktop-commander/worker/README.md b/pkgs/desktop-commander/worker/README.md index 9179a2f23..d2216c49d 100644 --- a/pkgs/desktop-commander/worker/README.md +++ b/pkgs/desktop-commander/worker/README.md @@ -10,33 +10,67 @@ whole path inside the fleet's own Cloudflare account and hardware. ``` AI client -> POST https://commander.security.cab/mcp - Access app "desktop-commander": owner Google identity (the IdP - wired under #12412 with the client saved under #12417), or the - "desktop-commander" service token for machine clients. - -> this Worker (src/index.ts): refuses requests without an Access - JWT assertion, then proxies the streamable-HTTP MCP request, - swapping the caller's Access material for its own egress token. + Guarded by this Worker's OAuth 2.1 authorization server + (src/oauth.ts). Hosted clients (Claude, ChatGPT) connect from + their own servers and cannot pass a Cloudflare Access login, so + /mcp takes a Bearer access token instead — or the machine bearer + for the owner's own tooling. + -> this Worker (src/index.ts): checks the Bearer, then proxies the + streamable-HTTP MCP request, swapping the caller's credentials + for its own bridge egress token. -> https://commander-link.security.cab/mcp Access app "desktop-commander link (bridge)": service-token-only - policy (the atlas-search pattern). + policy (the atlas-search pattern). This door did not change. -> sandbox-link Cloudflare Tunnel -> http://localhost:8931 on amd -> supergateway (systemd user unit desktop-commander-bridge, pkgs/supergateway) in streamable-HTTP mode -> the packaged Desktop Commander (pkgs/desktop-commander, stdio) ``` -`workers_dev` is off; `commander.security.cab` (a Worker custom -domain) is the only public door. +`workers_dev` is off; `commander.security.cab` (a Worker route) is +the only public door. + +## OAuth front door (src/oauth.ts) + +Standard MCP authorization shape, so Claude and ChatGPT can connect: + +- `GET /.well-known/oauth-protected-resource` (and `.../mcp`) and + `GET /.well-known/oauth-authorization-server` — public discovery. +- `POST /register` — dynamic client registration (RFC 7591); public + clients only (`token_endpoint_auth_method: "none"`), redirect URIs + must be https or loopback http. Clients live in the `OAUTH_KV` + namespace under `client:`. +- `GET /authorize` — the approval page, and the ONE path still behind + Cloudflare Access: the "desktop-commander" Access app is scoped to + `commander.security.cab/authorize` with the owner-email policy only. + The Worker also verifies the Access JWT itself (RS256 against the + team JWKS, audience, owner email) before rendering. Approving + issues a single-use code (10 min, PKCE S256 bound) via the form's + POST back to `/authorize`. +- `POST /token` — authorization-code exchange (PKCE verified, code + consumed on any attempt) issuing an opaque access token (1 h) and + a rotating refresh token (30 d). Codes and tokens are stored in KV + under their SHA-256 (`code:`, `at:`, `rt:`), + never in the clear. Revoke a client by deleting its `at:`/`rt:` + entries (and its `client:` record) from the namespace. +- `/mcp` without a valid Bearer answers 401 with + `WWW-Authenticate: Bearer resource_metadata="https://commander.security.cab/.well-known/oauth-protected-resource"`, + which is what sends hosted clients into the OAuth flow. + +The public Access service token that used to guard the whole hostname +is retired at this door (the token still exists; nothing accepts it +here anymore). The bridge door's service token is unchanged. ## Secrets — by name only, never values | Where | Name | | --- | --- | | fleet secrets (Bitwarden) | `cloudflare.access.desktop-commander-link-client-id` / `-client-secret` — bridge-door token the Worker presents | -| fleet secrets (Bitwarden) | `cloudflare.access.desktop-commander-client-id` / `-client-secret` — public-door token for machine MCP clients | +| fleet secrets (Bitwarden) | `cloudflare.access.desktop-commander-client-id` / `-client-secret` — the retired public-door token (kept, unused here) | | fleet secrets (Bitwarden) | `cloudflare.api-token-desktop-commander-worker` — scoped deploy token | -| GitHub environment `desktop-commander-production` | `DESKTOP_COMMANDER_WORKER_CF_TOKEN` (same deploy token), `BRIDGE_ACCESS_CLIENT_ID`, `BRIDGE_ACCESS_CLIENT_SECRET` | -| Worker version secrets | `ACCESS_CLIENT_ID`, `ACCESS_CLIENT_SECRET` — uploaded per version by the publish workflow from the environment secrets | +| fleet secrets (Bitwarden) | `desktop-commander.machine-bearer` — the /mcp machine bearer | +| GitHub environment `desktop-commander-production` | `DESKTOP_COMMANDER_WORKER_CF_TOKEN` (same deploy token), `BRIDGE_ACCESS_CLIENT_ID`, `BRIDGE_ACCESS_CLIENT_SECRET`, `MACHINE_BEARER` | +| Worker version secrets | `ACCESS_CLIENT_ID`, `ACCESS_CLIENT_SECRET`, `MACHINE_BEARER` — uploaded per version by the publish workflow from the environment secrets | ## Deploys — cf version deployments via GitHub Actions @@ -45,7 +79,7 @@ Modeled on the id-mail publisher/promoter pair: 1. **Publish** (`desktop-commander-worker-publish.yml`, manual dispatch on main, `confirm_upload`): tests, a credential-free dry run, then `upload-version.mjs` runs `cf workers versions create` with the - bridge secrets file. Uploading changes no traffic. The run emits a + Worker secrets file. Uploading changes no traffic. The run emits a provenance artifact naming the exact version, tag, and baseline. 2. **Promote** (`desktop-commander-worker-promote.yml`, manual dispatch with the publish run id + attempt, `confirm_promotion`): @@ -70,8 +104,10 @@ touching this directory. ## Client setup +- Hosted clients (Claude, ChatGPT): add the custom connector + `https://commander.security.cab/mcp`; the client registers itself + and sends the owner through the Access sign-in + approval page on + first connection. - Header-capable clients (Claude Code, Cursor, mcpx): send - `CF-Access-Client-Id` / `CF-Access-Client-Secret` with the - public-door token values. -- Browser clients: sign in with the owner's Google identity at the - Access prompt. + `Authorization: Bearer ` (fleet secrets: + `desktop-commander.machine-bearer`). diff --git a/pkgs/desktop-commander/worker/cloudflare.config.ts b/pkgs/desktop-commander/worker/cloudflare.config.ts index 5184dc4b1..529fe78d6 100644 --- a/pkgs/desktop-commander/worker/cloudflare.config.ts +++ b/pkgs/desktop-commander/worker/cloudflare.config.ts @@ -4,10 +4,10 @@ import * as entrypoint from "./src/index.ts" with { type: "cf-worker" }; // desktop-commander Worker — deployment source of truth for the cf // versions flow (see README.md). Mirrors wrangler.toml, kept in step // as the human-readable config record. The Worker's secrets -// (ACCESS_CLIENT_ID, ACCESS_CLIENT_SECRET) are never here: fleet -// secrets hold them by name, and a publish uploads them with the new -// version (cf workers versions create --secrets-file) so no version -// ever deploys without its bridge credentials. +// (ACCESS_CLIENT_ID, ACCESS_CLIENT_SECRET, MACHINE_BEARER) are never +// here: fleet secrets hold them by name, and a publish uploads them +// with the new version (cf workers versions create --secrets-file) so +// no version ever deploys without its credentials. export default defineConfig({ worker: { name: "desktop-commander", @@ -15,6 +15,10 @@ export default defineConfig({ entrypoint, env: { BRIDGE_BASE: bindings.text("https://commander-link.security.cab"), + ACCESS_TEAM_DOMAIN: bindings.text("snowy-sun-58a9.cloudflareaccess.com"), + // Audience of the Access app scoped to /authorize. + ACCESS_AUD: bindings.text("c6ddf0a5c0ba8742c0a3c74d12495bf5c4fe9bf6f01f604d62583cb2ed353879"), + OAUTH_KV: bindings.kv({ id: "ea675d3c7d5b4f3b9f1cecae82e57d1b" }), }, }, }); diff --git a/pkgs/desktop-commander/worker/src/index.ts b/pkgs/desktop-commander/worker/src/index.ts index 3b505160a..c137accd7 100644 --- a/pkgs/desktop-commander/worker/src/index.ts +++ b/pkgs/desktop-commander/worker/src/index.ts @@ -3,10 +3,13 @@ // // Shape: // AI client -> https://commander.security.cab/mcp -// Cloudflare Access app "desktop-commander" authenticates the caller -// first (owner Google identity, or the desktop-commander service -// token for machine clients). Unauthenticated requests never reach -// this Worker. +// Hosted clients (Claude, ChatGPT) connect from their own servers +// and cannot pass a Cloudflare Access login here, so /mcp is +// guarded by this Worker's OAuth 2.1 authorization server +// (src/oauth.ts): a Bearer access token issued through /authorize, +// or the machine bearer for the owner's own tooling. The one path +// still behind Access is /authorize — only the owner's Google +// identity reaches the approval page. // this Worker -> https://commander-link.security.cab/mcp // A second Access app guards the bridge door with a service-token- // only policy; the Worker presents that token (ACCESS_CLIENT_ID / @@ -14,14 +17,31 @@ // bridge door -> Cloudflare Tunnel -> supergateway on the laptop // -> the packaged Desktop Commander (stdio) on 127.0.0.1:8931. // -// The Worker is a transparent streamable-HTTP proxy: method, path, +// The /mcp proxy is a transparent streamable-HTTP proxy: method, path, // query, headers and body pass through, and the response (including // the Mcp-Session-Id header and any SSE stream) passes back untouched. -export interface Env { +import { + authorizationServerMetadata, + authorizeGet, + authorizePost, + isValidAccessToken, + protectedResourceMetadata, + registerClient, + timingSafeEqual, + tokenEndpoint, + type OAuthEnv, +} from "./oauth"; + +export interface Env extends OAuthEnv { BRIDGE_BASE: string; ACCESS_CLIENT_ID: string; ACCESS_CLIENT_SECRET: string; + // Bearer for the owner's machine clients (mcpx, curl): a Worker + // secret staged by the publish workflow from the GitHub environment + // secret of the same name; canonical value in fleet secrets as + // desktop-commander.machine-bearer. + MACHINE_BEARER: string; } function json(body: unknown, status = 200): Response { @@ -31,23 +51,59 @@ function json(body: unknown, status = 200): Response { }); } +async function isAuthorizedMcpCaller(request: Request, env: Env): Promise { + const authorization = request.headers.get("authorization"); + if (!authorization?.startsWith("Bearer ")) return false; + const token = authorization.slice("Bearer ".length).trim(); + if (!token) return false; + if (await isValidAccessToken(env, token)) return true; + const machineBearer = (env.MACHINE_BEARER ?? "").trim(); + return machineBearer.length > 0 && timingSafeEqual(token, machineBearer); +} + export default { async fetch(request: Request, env: Env): Promise { const url = new URL(request.url); + const path = url.pathname; - if (url.pathname === "/healthz") { + if (path === "/healthz") { return json({ ok: true, service: "desktop-commander" }); } - if (url.pathname !== "/mcp") { + + // OAuth authorization-server surface (src/oauth.ts). + if (path === "/.well-known/oauth-protected-resource" || path === "/.well-known/oauth-protected-resource/mcp") { + return protectedResourceMetadata(); + } + if (path === "/.well-known/oauth-authorization-server") { + return authorizationServerMetadata(); + } + if (path === "/register") { + if (request.method !== "POST") return json({ error: "method not allowed" }, 405); + return registerClient(request, env); + } + if (path === "/authorize") { + if (request.method === "GET") return authorizeGet(request, env); + if (request.method === "POST") return authorizePost(request, env); + return json({ error: "method not allowed" }, 405); + } + if (path === "/token") { + if (request.method !== "POST") return json({ error: "method not allowed" }, 405); + return tokenEndpoint(request, env); + } + + if (path !== "/mcp") { return json({ error: "not found" }, 404); } - // Defense in depth: Access injects this header only after a caller - // passes one of the app's policies. Its absence means the request - // did not come through the gate (a stray route or a future - // workers.dev re-enable), so refuse before touching the bridge. - if (!request.headers.get("Cf-Access-Jwt-Assertion")) { - return json({ error: "missing Cloudflare Access assertion" }, 401); + if (!(await isAuthorizedMcpCaller(request, env))) { + return new Response(JSON.stringify({ error: "unauthorized" }), { + status: 401, + headers: { + "content-type": "application/json", + "WWW-Authenticate": + 'Bearer resource_metadata="https://commander.security.cab/.well-known/oauth-protected-resource"', + }, + }); } if (!env.ACCESS_CLIENT_ID || !env.ACCESS_CLIENT_SECRET) { return json({ error: "bridge credentials are not configured" }, 500); @@ -56,8 +112,9 @@ export default { const target = new URL(url.pathname + url.search, env.BRIDGE_BASE); const headers = new Headers(request.headers); headers.delete("host"); - // The caller's own Access material is for the public door only; - // the bridge door gets the Worker's egress token instead. + // The caller's own credentials are for the public door only; the + // bridge door gets the Worker's egress token instead. + headers.delete("authorization"); headers.delete("cf-access-jwt-assertion"); headers.delete("cf-access-client-id"); headers.delete("cf-access-client-secret"); diff --git a/pkgs/desktop-commander/worker/src/oauth.ts b/pkgs/desktop-commander/worker/src/oauth.ts new file mode 100644 index 000000000..82f7978c5 --- /dev/null +++ b/pkgs/desktop-commander/worker/src/oauth.ts @@ -0,0 +1,507 @@ +// OAuth 2.1 authorization-server front for the desktop-commander +// Worker (#13404). Hosted MCP clients (Claude, ChatGPT) connect to +// https://commander.security.cab/mcp from their own servers, so they +// cannot pass a Cloudflare Access login at the /mcp door. This module +// gives the door the standard MCP authorization shape instead: +// +// - discovery documents (RFC 9728 / RFC 8414) — public +// - dynamic client registration (RFC 7591) — public +// - /authorize — the one path still behind Cloudflare Access; only +// the owner's Google identity gets in, and the Worker re-verifies +// the Access JWT itself (signature, audience, email) before +// rendering the approval page +// - /token — authorization-code exchange with PKCE S256, plus +// rotating refresh tokens +// +// State lives in the OAUTH_KV namespace. Authorization codes, access +// tokens and refresh tokens are stored under the SHA-256 of the +// presented value, never in the clear. + +export interface OAuthEnv { + OAUTH_KV: KVNamespace; + // Audience (AUD) of the Access application scoped to /authorize. + ACCESS_AUD: string; + // Access team domain hosting the JWKS, e.g. + // "snowy-sun-58a9.cloudflareaccess.com". + ACCESS_TEAM_DOMAIN: string; +} + +export const ISSUER = "https://commander.security.cab"; +export const RESOURCE = "https://commander.security.cab/mcp"; +export const SCOPE = "commander"; +export const OWNER_EMAIL = "drewrypope@gmail.com"; + +const CODE_TTL_S = 600; +const PENDING_TTL_S = 600; +const ACCESS_TOKEN_TTL_S = 3600; +const REFRESH_TOKEN_TTL_S = 30 * 24 * 3600; + +interface ClientRecord { + client_name?: string; + redirect_uris: string[]; + grant_types: string[]; + response_types: string[]; + token_endpoint_auth_method: string; + created_at: number; +} + +interface PendingRecord { + client_id: string; + redirect_uri: string; + state?: string; + scope: string; + code_challenge: string; +} + +interface CodeRecord { + client_id: string; + redirect_uri: string; + code_challenge: string; + scope: string; + exp: number; +} + +interface TokenRecord { + client_id: string; + scope: string; + exp: number; +} + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +} + +function oauthError(error: string, description: string, status = 400): Response { + return json({ error, error_description: description }, status); +} + +const encoder = new TextEncoder(); + +export function base64urlEncode(bytes: Uint8Array): string { + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +} + +function base64urlDecode(value: string): Uint8Array { + const padded = value.replaceAll("-", "+").replaceAll("_", "/").padEnd(Math.ceil(value.length / 4) * 4, "="); + const binary = atob(padded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +export async function sha256Hex(text: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", encoder.encode(text)); + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +async function sha256Base64url(text: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", encoder.encode(text)); + return base64urlEncode(new Uint8Array(digest)); +} + +function randomToken(bytes = 32): string { + return base64urlEncode(crypto.getRandomValues(new Uint8Array(bytes))); +} + +function randomHex(bytes = 16): string { + return [...crypto.getRandomValues(new Uint8Array(bytes))] + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} + +// Constant-time comparison for secret material. Length is not secret +// for a fixed-size bearer, so a length mismatch returns early. +export function timingSafeEqual(a: string, b: string): boolean { + const ab = encoder.encode(a); + const bb = encoder.encode(b); + if (ab.length !== bb.length) return false; + let diff = 0; + for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i]; + return diff === 0; +} + +function escapeHtml(text: string): string { + return text + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +// --------------------------------------------------------------------------- +// Discovery (RFC 9728 / RFC 8414) + +export function protectedResourceMetadata(): Response { + return json({ + resource: RESOURCE, + authorization_servers: [ISSUER], + bearer_methods_supported: ["header"], + scopes_supported: [SCOPE], + }); +} + +export function authorizationServerMetadata(): Response { + return json({ + issuer: ISSUER, + authorization_endpoint: `${ISSUER}/authorize`, + token_endpoint: `${ISSUER}/token`, + registration_endpoint: `${ISSUER}/register`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code", "refresh_token"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + scopes_supported: [SCOPE], + service_documentation: "https://github.com/developing-today/code/issues/13404", + }); +} + +// --------------------------------------------------------------------------- +// Dynamic client registration (RFC 7591) + +function isRegistrableRedirectUri(value: string): boolean { + let url: URL; + try { + url = new URL(value); + } catch { + return false; + } + if (url.protocol === "https:") return true; + // Loopback http is allowed for native / desktop clients (RFC 8252). + if (url.protocol === "http:") { + return url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]"; + } + return false; +} + +export async function registerClient(request: Request, env: OAuthEnv): Promise { + let body: Record; + try { + body = (await request.json()) as Record; + } catch { + return oauthError("invalid_client_metadata", "request body must be a JSON object"); + } + if (body === null || typeof body !== "object" || Array.isArray(body)) { + return oauthError("invalid_client_metadata", "request body must be a JSON object"); + } + + const redirectUris = body.redirect_uris; + if ( + !Array.isArray(redirectUris) || + redirectUris.length === 0 || + !redirectUris.every((u) => typeof u === "string" && isRegistrableRedirectUri(u)) + ) { + return oauthError( + "invalid_redirect_uri", + "redirect_uris must be a non-empty array of absolute https (or loopback http) URIs", + ); + } + if (body.token_endpoint_auth_method !== undefined && body.token_endpoint_auth_method !== "none") { + return oauthError("invalid_client_metadata", "only token_endpoint_auth_method \"none\" (public client) is supported"); + } + const grantTypes = Array.isArray(body.grant_types) ? body.grant_types.filter((g) => typeof g === "string") : ["authorization_code"]; + const responseTypes = Array.isArray(body.response_types) ? body.response_types.filter((g) => typeof g === "string") : ["code"]; + const clientName = typeof body.client_name === "string" ? body.client_name : undefined; + + const clientId = randomHex(16); + const record: ClientRecord = { + client_name: clientName, + redirect_uris: redirectUris as string[], + grant_types: grantTypes as string[], + response_types: responseTypes as string[], + token_endpoint_auth_method: "none", + created_at: Math.floor(Date.now() / 1000), + }; + await env.OAUTH_KV.put(`client:${clientId}`, JSON.stringify(record)); + + return json( + { + client_id: clientId, + client_id_issued_at: record.created_at, + client_name: clientName, + redirect_uris: record.redirect_uris, + grant_types: record.grant_types, + response_types: record.response_types, + token_endpoint_auth_method: "none", + }, + 201, + ); +} + +async function getClient(env: OAuthEnv, clientId: string | null): Promise { + if (!clientId) return null; + return env.OAUTH_KV.get(`client:${clientId}`, "json"); +} + +// --------------------------------------------------------------------------- +// Cloudflare Access JWT verification for /authorize. +// +// Access is the enforcement point (the /authorize app only lets the +// owner's identity through); this re-verification is defense in depth +// so the approval page never renders on a forged or stray request. + +interface AccessClaims { + email?: string; + aud?: string | string[]; + exp?: number; + iss?: string; + [key: string]: unknown; +} + +let jwksCache: { teamDomain: string; keys: JsonWebKey[]; fetchedAt: number } | null = null; + +async function fetchJwks(teamDomain: string): Promise { + const now = Date.now(); + if (jwksCache && jwksCache.teamDomain === teamDomain && now - jwksCache.fetchedAt < 300_000) { + return jwksCache.keys; + } + const res = await fetch(`https://${teamDomain}/cdn-cgi/access/certs`); + if (!res.ok) return null; + const body = (await res.json()) as { keys?: JsonWebKey[] }; + if (!Array.isArray(body.keys)) return null; + jwksCache = { teamDomain, keys: body.keys, fetchedAt: now }; + return body.keys; +} + +export async function verifyAccessAssertion(request: Request, env: OAuthEnv): Promise { + const jwt = request.headers.get("Cf-Access-Jwt-Assertion"); + if (!jwt) return null; + const parts = jwt.split("."); + if (parts.length !== 3) return null; + + let header: { alg?: string; kid?: string }; + let claims: AccessClaims; + try { + header = JSON.parse(new TextDecoder().decode(base64urlDecode(parts[0]))) as typeof header; + claims = JSON.parse(new TextDecoder().decode(base64urlDecode(parts[1]))) as AccessClaims; + } catch { + return null; + } + if (header.alg !== "RS256" || !header.kid) return null; + + const keys = await fetchJwks(env.ACCESS_TEAM_DOMAIN).catch(() => null); + if (!keys) return null; + const jwk = keys.find((k) => (k as { kid?: string }).kid === header.kid); + if (!jwk) return null; + + let verified = false; + try { + const key = await crypto.subtle.importKey( + "jwk", + jwk, + { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, + false, + ["verify"], + ); + verified = await crypto.subtle.verify( + "RSASSA-PKCS1-v1_5", + key, + base64urlDecode(parts[2]), + encoder.encode(`${parts[0]}.${parts[1]}`), + ); + } catch { + return null; + } + if (!verified) return null; + + const now = Math.floor(Date.now() / 1000); + if (typeof claims.exp !== "number" || claims.exp <= now) return null; + const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud]; + if (!audiences.includes(env.ACCESS_AUD)) return null; + if (claims.iss !== `https://${env.ACCESS_TEAM_DOMAIN}`) return null; + if (claims.email !== OWNER_EMAIL) return null; + return claims; +} + +// --------------------------------------------------------------------------- +// Authorization endpoint (approval page + decision). + +function authorizeErrorPage(status: number, message: string): Response { + const html = ` +Desktop Commander — authorization + +

Desktop Commander

+

${escapeHtml(message)}

+`; + return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8" } }); +} + +function redirectWithParams(redirectUri: string, params: Record): Response { + const url = new URL(redirectUri); + for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value); + return new Response(null, { status: 302, headers: { location: url.toString() } }); +} + +export async function authorizeGet(request: Request, env: OAuthEnv): Promise { + const claims = await verifyAccessAssertion(request, env); + if (!claims) return authorizeErrorPage(403, "This page is only reachable through the owner's Cloudflare Access sign-in."); + + const url = new URL(request.url); + const params = url.searchParams; + const clientId = params.get("client_id"); + const client = await getClient(env, clientId); + if (!client || !clientId) return authorizeErrorPage(400, "Unknown client_id."); + + const redirectUri = params.get("redirect_uri"); + if (!redirectUri || !client.redirect_uris.includes(redirectUri)) { + return authorizeErrorPage(400, "redirect_uri does not match a registered URI for this client."); + } + if (params.get("response_type") !== "code") { + return authorizeErrorPage(400, "Only response_type=code is supported."); + } + const codeChallenge = params.get("code_challenge"); + if (!codeChallenge || params.get("code_challenge_method") !== "S256") { + return authorizeErrorPage(400, "A PKCE code_challenge with method S256 is required."); + } + const requestedScope = params.get("scope"); + if (requestedScope !== null && !requestedScope.split(" ").includes(SCOPE)) { + return authorizeErrorPage(400, `Unsupported scope; this server issues only "${SCOPE}".`); + } + + const nonce = randomToken(24); + const pending: PendingRecord = { + client_id: clientId, + redirect_uri: redirectUri, + state: params.get("state") ?? undefined, + scope: SCOPE, + code_challenge: codeChallenge, + }; + await env.OAUTH_KV.put(`pending:${nonce}`, JSON.stringify(pending), { expirationTtl: PENDING_TTL_S }); + + const clientLabel = client.client_name ? `${client.client_name} (${clientId})` : clientId; + const redirectHost = new URL(redirectUri).host; + const html = ` +Desktop Commander — authorize + +

Desktop Commander

+

${escapeHtml(clientLabel)} is asking to connect to the Desktop Commander +on your laptop via ${escapeHtml(redirectHost)}, with scope ${SCOPE}.

+

Approving gives this client an access token (1 hour) and a refresh token (30 days) +that you can revoke by deleting them from the Worker's KV namespace.

+
+ + + +
+`; + return new Response(html, { status: 200, headers: { "content-type": "text/html; charset=utf-8" } }); +} + +export async function authorizePost(request: Request, env: OAuthEnv): Promise { + const claims = await verifyAccessAssertion(request, env); + if (!claims) return authorizeErrorPage(403, "This page is only reachable through the owner's Cloudflare Access sign-in."); + + const form = await request.formData(); + const nonce = form.get("nonce"); + const decision = form.get("decision"); + if (typeof nonce !== "string" || !nonce) return authorizeErrorPage(400, "Missing authorization request nonce."); + + const pending = await env.OAUTH_KV.get(`pending:${nonce}`, "json"); + // The pending request is single-use regardless of the outcome. + await env.OAUTH_KV.delete(`pending:${nonce}`); + if (!pending) return authorizeErrorPage(400, "This authorization request has expired or was already used."); + + const stateParam: Record = pending.state ? { state: pending.state } : {}; + if (decision !== "approve") { + return redirectWithParams(pending.redirect_uri, { error: "access_denied", ...stateParam }); + } + + const code = randomToken(32); + const record: CodeRecord = { + client_id: pending.client_id, + redirect_uri: pending.redirect_uri, + code_challenge: pending.code_challenge, + scope: pending.scope, + exp: Math.floor(Date.now() / 1000) + CODE_TTL_S, + }; + await env.OAUTH_KV.put(`code:${await sha256Hex(code)}`, JSON.stringify(record), { expirationTtl: CODE_TTL_S }); + return redirectWithParams(pending.redirect_uri, { code, ...stateParam }); +} + +// --------------------------------------------------------------------------- +// Token endpoint. + +async function issueTokens(env: OAuthEnv, clientId: string, scope: string): Promise { + const now = Math.floor(Date.now() / 1000); + const accessToken = randomToken(32); + const refreshToken = randomToken(32); + const accessRecord: TokenRecord = { client_id: clientId, scope, exp: now + ACCESS_TOKEN_TTL_S }; + const refreshRecord: TokenRecord = { client_id: clientId, scope, exp: now + REFRESH_TOKEN_TTL_S }; + await env.OAUTH_KV.put(`at:${await sha256Hex(accessToken)}`, JSON.stringify(accessRecord), { + expirationTtl: ACCESS_TOKEN_TTL_S, + }); + await env.OAUTH_KV.put(`rt:${await sha256Hex(refreshToken)}`, JSON.stringify(refreshRecord), { + expirationTtl: REFRESH_TOKEN_TTL_S, + }); + return json({ + access_token: accessToken, + token_type: "Bearer", + expires_in: ACCESS_TOKEN_TTL_S, + refresh_token: refreshToken, + scope, + }); +} + +export async function tokenEndpoint(request: Request, env: OAuthEnv): Promise { + let form: FormData; + try { + form = await request.formData(); + } catch { + return oauthError("invalid_request", "request body must be application/x-www-form-urlencoded"); + } + const grantType = form.get("grant_type"); + + if (grantType === "authorization_code") { + const code = form.get("code"); + const clientId = form.get("client_id"); + const redirectUri = form.get("redirect_uri"); + const verifier = form.get("code_verifier"); + if (typeof code !== "string" || typeof clientId !== "string" || typeof redirectUri !== "string" || typeof verifier !== "string") { + return oauthError("invalid_request", "code, client_id, redirect_uri and code_verifier are required"); + } + const codeKey = `code:${await sha256Hex(code)}`; + const record = await env.OAUTH_KV.get(codeKey, "json"); + if (!record) return oauthError("invalid_grant", "unknown or expired authorization code"); + // Consume the code on any exchange attempt, before issuing, so a + // failed PKCE or binding check cannot be retried against it. + await env.OAUTH_KV.delete(codeKey); + if (record.exp <= Math.floor(Date.now() / 1000)) return oauthError("invalid_grant", "authorization code expired"); + if (record.client_id !== clientId) return oauthError("invalid_grant", "client_id does not match the authorization request"); + if (record.redirect_uri !== redirectUri) return oauthError("invalid_grant", "redirect_uri does not match the authorization request"); + if ((await sha256Base64url(verifier)) !== record.code_challenge) { + return oauthError("invalid_grant", "PKCE code_verifier does not match the challenge"); + } + return issueTokens(env, clientId, record.scope); + } + + if (grantType === "refresh_token") { + const refreshToken = form.get("refresh_token"); + const clientId = form.get("client_id"); + if (typeof refreshToken !== "string" || typeof clientId !== "string") { + return oauthError("invalid_request", "refresh_token and client_id are required"); + } + const refreshKey = `rt:${await sha256Hex(refreshToken)}`; + const record = await env.OAUTH_KV.get(refreshKey, "json"); + if (!record) return oauthError("invalid_grant", "unknown or expired refresh token"); + // Rotation: the presented refresh token dies whatever happens next. + await env.OAUTH_KV.delete(refreshKey); + if (record.exp <= Math.floor(Date.now() / 1000)) return oauthError("invalid_grant", "refresh token expired"); + if (record.client_id !== clientId) return oauthError("invalid_grant", "client_id does not match the refresh token"); + return issueTokens(env, clientId, record.scope); + } + + return oauthError("unsupported_grant_type", "grant_type must be authorization_code or refresh_token"); +} + +// --------------------------------------------------------------------------- +// /mcp bearer validation. + +export async function isValidAccessToken(env: OAuthEnv, token: string): Promise { + const record = await env.OAUTH_KV.get(`at:${await sha256Hex(token)}`, "json"); + return record !== null && record.exp > Math.floor(Date.now() / 1000); +} diff --git a/pkgs/desktop-commander/worker/test/memory-kv.ts b/pkgs/desktop-commander/worker/test/memory-kv.ts new file mode 100644 index 000000000..f55cee164 --- /dev/null +++ b/pkgs/desktop-commander/worker/test/memory-kv.ts @@ -0,0 +1,36 @@ +// In-memory KVNamespace stub for tests: just enough of the Workers KV +// surface the OAuth module uses (get with "json", put with +// expirationTtl, delete), with lazy TTL expiry like the real thing. +export class MemoryKV { + private store = new Map(); + + async get(key: string, type?: string): Promise { + const entry = this.store.get(key); + if (!entry) return null; + if (entry.expiresAt !== undefined && entry.expiresAt <= Date.now()) { + this.store.delete(key); + return null; + } + return type === "json" ? JSON.parse(entry.value) : entry.value; + } + + async put(key: string, value: string, options?: { expirationTtl?: number }): Promise { + this.store.set(key, { + value, + expiresAt: options?.expirationTtl ? Date.now() + options.expirationTtl * 1000 : undefined, + }); + } + + async delete(key: string): Promise { + this.store.delete(key); + } + + // Test-only inspection helpers. + keys(): string[] { + return [...this.store.keys()]; + } +} + +export function memoryKvBinding(): KVNamespace { + return new MemoryKV() as unknown as KVNamespace; +} diff --git a/pkgs/desktop-commander/worker/test/oauth.test.ts b/pkgs/desktop-commander/worker/test/oauth.test.ts new file mode 100644 index 000000000..a3f28e41d --- /dev/null +++ b/pkgs/desktop-commander/worker/test/oauth.test.ts @@ -0,0 +1,428 @@ +import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import worker, { type Env } from "../src/index"; +import { base64urlEncode, sha256Hex } from "../src/oauth"; +import { MemoryKV } from "./memory-kv"; + +const TEAM_DOMAIN = "team.example.com"; +const AUD = "authorize-app-aud"; +const OWNER = "drewrypope@gmail.com"; +const REDIRECT_URI = "https://client.example.com/callback"; + +const kv = new MemoryKV(); +const env: Env = { + BRIDGE_BASE: "https://commander-link.security.cab", + ACCESS_CLIENT_ID: "bridge-id.access", + ACCESS_CLIENT_SECRET: "bridge-secret", + MACHINE_BEARER: "machine-bearer-for-tests", + ACCESS_AUD: AUD, + ACCESS_TEAM_DOMAIN: TEAM_DOMAIN, + OAUTH_KV: kv as unknown as KVNamespace, +}; + +// A real RSA keypair stands in for the Access team's signing key: the +// JWKS endpoint is stubbed to serve its public half, and assertions +// are signed with the private half, so the Worker's RS256 check runs +// for real. +let privateKey: CryptoKey; +let jwks: { keys: Record[] }; + +beforeAll(async () => { + const pair = (await crypto.subtle.generateKey( + { + name: "RSASSA-PKCS1-v1_5", + modulusLength: 2048, + publicExponent: new Uint8Array([1, 0, 1]), + hash: "SHA-256", + }, + true, + ["sign", "verify"], + )) as CryptoKeyPair; + privateKey = pair.privateKey; + const publicJwk = (await crypto.subtle.exportKey("jwk", pair.publicKey)) as unknown as Record; + jwks = { keys: [{ ...publicJwk, kid: "test-key-1", alg: "RS256", use: "sig" }] }; +}); + +async function accessJwt(claims: Record): Promise { + const header = { alg: "RS256", typ: "JWT", kid: "test-key-1" }; + const payload = { + email: OWNER, + aud: AUD, + iss: `https://${TEAM_DOMAIN}`, + exp: Math.floor(Date.now() / 1000) + 600, + ...claims, + }; + const encode = (obj: unknown) => + base64urlEncode(new TextEncoder().encode(JSON.stringify(obj))); + const signingInput = `${encode(header)}.${encode(payload)}`; + const signature = await crypto.subtle.sign( + "RSASSA-PKCS1-v1_5", + privateKey, + new TextEncoder().encode(signingInput), + ); + return `${signingInput}.${base64urlEncode(new Uint8Array(signature))}`; +} + +function stubFetch() { + const fetchStub = vi.fn(async (input: unknown) => { + const url = String(input instanceof URL ? input.href : input); + if (url.startsWith(`https://${TEAM_DOMAIN}/`)) { + return new Response(JSON.stringify(jwks), { + headers: { "content-type": "application/json" }, + }); + } + if (url.startsWith("https://commander-link.security.cab/")) { + return new Response("event: message\ndata: {}\n\n", { + status: 200, + headers: { "content-type": "text/event-stream", "mcp-session-id": "s-1" }, + }); + } + throw new Error(`unexpected fetch: ${url}`); + }); + vi.stubGlobal("fetch", fetchStub); + return fetchStub; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +async function registerTestClient(): Promise { + const res = await worker.fetch( + new Request("https://commander.security.cab/register", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + client_name: "Test Client", + redirect_uris: [REDIRECT_URI], + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + token_endpoint_auth_method: "none", + }), + }), + env, + ); + expect(res.status).toBe(201); + const body = (await res.json()) as { client_id: string }; + return body.client_id; +} + +async function pkcePair(): Promise<{ verifier: string; challenge: string }> { + const verifier = base64urlEncode(crypto.getRandomValues(new Uint8Array(32))); + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)); + return { verifier, challenge: base64urlEncode(new Uint8Array(digest)) }; +} + +function authorizeUrl(clientId: string, challenge: string, extra = ""): string { + return ( + `https://commander.security.cab/authorize?response_type=code&client_id=${clientId}` + + `&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&code_challenge=${challenge}` + + `&code_challenge_method=S256&state=state-123${extra}` + ); +} + +async function approveAndGetCode(clientId: string, verifier: string): Promise { + const { challenge } = await pkcePairFor(verifier); + const jwt = await accessJwt({}); + const page = await worker.fetch( + new Request(authorizeUrl(clientId, challenge), { + headers: { "cf-access-jwt-assertion": jwt }, + }), + env, + ); + expect(page.status).toBe(200); + const html = await page.text(); + const nonce = /name="nonce" value="([^"]+)"/.exec(html)?.[1]; + expect(nonce).toBeTruthy(); + + const decision = await worker.fetch( + new Request("https://commander.security.cab/authorize", { + method: "POST", + headers: { + "cf-access-jwt-assertion": jwt, + "content-type": "application/x-www-form-urlencoded", + }, + body: new URLSearchParams({ nonce: nonce!, decision: "approve" }).toString(), + }), + env, + ); + expect(decision.status).toBe(302); + const location = new URL(decision.headers.get("location")!); + expect(location.searchParams.get("state")).toBe("state-123"); + const code = location.searchParams.get("code"); + expect(code).toBeTruthy(); + return code!; +} + +async function pkcePairFor(verifier: string): Promise<{ verifier: string; challenge: string }> { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)); + return { verifier, challenge: base64urlEncode(new Uint8Array(digest)) }; +} + +function tokenRequest(fields: Record): Request { + return new Request("https://commander.security.cab/token", { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(fields).toString(), + }); +} + +describe("OAuth discovery", () => { + it("serves the protected-resource metadata, both path shapes", async () => { + stubFetch(); + for (const path of ["/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp"]) { + const res = await worker.fetch(new Request(`https://commander.security.cab${path}`), env); + expect(res.status).toBe(200); + const body = (await res.json()) as Record; + expect(body.resource).toBe("https://commander.security.cab/mcp"); + expect(body.authorization_servers).toEqual(["https://commander.security.cab"]); + expect(body.bearer_methods_supported).toEqual(["header"]); + expect(body.scopes_supported).toEqual(["commander"]); + } + }); + + it("serves the authorization-server metadata", async () => { + stubFetch(); + const res = await worker.fetch( + new Request("https://commander.security.cab/.well-known/oauth-authorization-server"), + env, + ); + expect(res.status).toBe(200); + const body = (await res.json()) as Record; + expect(body.issuer).toBe("https://commander.security.cab"); + expect(body.authorization_endpoint).toBe("https://commander.security.cab/authorize"); + expect(body.token_endpoint).toBe("https://commander.security.cab/token"); + expect(body.registration_endpoint).toBe("https://commander.security.cab/register"); + expect(body.code_challenge_methods_supported).toEqual(["S256"]); + expect(body.grant_types_supported).toEqual(["authorization_code", "refresh_token"]); + expect(body.token_endpoint_auth_methods_supported).toEqual(["none"]); + }); +}); + +describe("dynamic client registration", () => { + it("registers a public client and stores it", async () => { + stubFetch(); + const clientId = await registerTestClient(); + const stored = await kv.get(`client:${clientId}`, "json"); + expect(stored).toMatchObject({ client_name: "Test Client", redirect_uris: [REDIRECT_URI] }); + }); + + it("rejects empty and non-loopback-http redirect_uris", async () => { + stubFetch(); + for (const redirectUris of [[], ["http://evil.example.com/cb"], ["not a uri"]]) { + const res = await worker.fetch( + new Request("https://commander.security.cab/register", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ redirect_uris: redirectUris }), + }), + env, + ); + expect(res.status).toBe(400); + } + }); +}); + +describe("/authorize", () => { + it("rejects a request without an Access assertion", async () => { + stubFetch(); + const clientId = await registerTestClient(); + const { challenge } = await pkcePair(); + const res = await worker.fetch(new Request(authorizeUrl(clientId, challenge)), env); + expect(res.status).toBe(403); + }); + + it("rejects an assertion for a different email", async () => { + stubFetch(); + const clientId = await registerTestClient(); + const { challenge } = await pkcePair(); + const jwt = await accessJwt({ email: "someone-else@example.com" }); + const res = await worker.fetch( + new Request(authorizeUrl(clientId, challenge), { + headers: { "cf-access-jwt-assertion": jwt }, + }), + env, + ); + expect(res.status).toBe(403); + }); + + it("rejects a plain PKCE challenge", async () => { + stubFetch(); + const clientId = await registerTestClient(); + const jwt = await accessJwt({}); + const plain = await worker.fetch( + new Request( + `https://commander.security.cab/authorize?response_type=code&client_id=${clientId}` + + `&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&code_challenge=abc&code_challenge_method=plain`, + { headers: { "cf-access-jwt-assertion": jwt } }, + ), + env, + ); + expect(plain.status).toBe(400); + }); + + it("rejects an unregistered redirect_uri", async () => { + stubFetch(); + const clientId = await registerTestClient(); + const { challenge } = await pkcePair(); + const jwt = await accessJwt({}); + const res = await worker.fetch( + new Request( + `https://commander.security.cab/authorize?response_type=code&client_id=${clientId}` + + `&redirect_uri=${encodeURIComponent("https://other.example.com/cb")}&code_challenge=${challenge}&code_challenge_method=S256`, + { headers: { "cf-access-jwt-assertion": jwt } }, + ), + env, + ); + expect(res.status).toBe(400); + }); +}); + +describe("full OAuth flow", () => { + it("register → approve → exchange → /mcp, with single-use code and refresh rotation", async () => { + const fetchStub = stubFetch(); + const clientId = await registerTestClient(); + const { verifier } = await pkcePair(); + const code = await approveAndGetCode(clientId, verifier); + + // Exchange the code for tokens. + const tokenRes = await worker.fetch( + tokenRequest({ + grant_type: "authorization_code", + code, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + }), + env, + ); + expect(tokenRes.status).toBe(200); + const tokens = (await tokenRes.json()) as { + access_token: string; + refresh_token: string; + token_type: string; + expires_in: number; + }; + expect(tokens.token_type).toBe("Bearer"); + expect(tokens.expires_in).toBe(3600); + // Tokens are stored hashed, never in the clear. + expect(kv.keys()).toContain(`at:${await sha256Hex(tokens.access_token)}`); + expect(kv.keys()).not.toContain(`at:${tokens.access_token}`); + + // The access token opens /mcp. + const mcpRes = await worker.fetch( + new Request("https://commander.security.cab/mcp", { + method: "POST", + headers: { + authorization: `Bearer ${tokens.access_token}`, + "content-type": "application/json", + }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), + }), + env, + ); + expect(mcpRes.status).toBe(200); + expect( + fetchStub.mock.calls.some(([input]) => + String(input instanceof URL ? input.href : input).startsWith("https://commander-link.security.cab/"), + ), + ).toBe(true); + + // The code cannot be exchanged twice. + const reuse = await worker.fetch( + tokenRequest({ + grant_type: "authorization_code", + code, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + }), + env, + ); + expect(reuse.status).toBe(400); + expect(((await reuse.json()) as { error: string }).error).toBe("invalid_grant"); + + // Refresh rotates: new pair out, old refresh token dead. + const refreshed = await worker.fetch( + tokenRequest({ + grant_type: "refresh_token", + refresh_token: tokens.refresh_token, + client_id: clientId, + }), + env, + ); + expect(refreshed.status).toBe(200); + const rotated = (await refreshed.json()) as { refresh_token: string }; + expect(rotated.refresh_token).not.toBe(tokens.refresh_token); + const oldRefresh = await worker.fetch( + tokenRequest({ + grant_type: "refresh_token", + refresh_token: tokens.refresh_token, + client_id: clientId, + }), + env, + ); + expect(oldRefresh.status).toBe(400); + }); + + it("rejects a wrong PKCE verifier and burns the code", async () => { + stubFetch(); + const clientId = await registerTestClient(); + const { verifier } = await pkcePair(); + const code = await approveAndGetCode(clientId, verifier); + + const wrong = await worker.fetch( + tokenRequest({ + grant_type: "authorization_code", + code, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: "the-wrong-verifier", + }), + env, + ); + expect(wrong.status).toBe(400); + expect(((await wrong.json()) as { error: string }).error).toBe("invalid_grant"); + + const retry = await worker.fetch( + tokenRequest({ + grant_type: "authorization_code", + code, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + }), + env, + ); + expect(retry.status).toBe(400); + }); + + it("deny redirects with access_denied and no code", async () => { + stubFetch(); + const clientId = await registerTestClient(); + const { challenge } = await pkcePair(); + const jwt = await accessJwt({}); + const page = await worker.fetch( + new Request(authorizeUrl(clientId, challenge), { + headers: { "cf-access-jwt-assertion": jwt }, + }), + env, + ); + const nonce = /name="nonce" value="([^"]+)"/.exec(await page.text())?.[1]; + const decision = await worker.fetch( + new Request("https://commander.security.cab/authorize", { + method: "POST", + headers: { + "cf-access-jwt-assertion": jwt, + "content-type": "application/x-www-form-urlencoded", + }, + body: new URLSearchParams({ nonce: nonce!, decision: "deny" }).toString(), + }), + env, + ); + expect(decision.status).toBe(302); + const location = new URL(decision.headers.get("location")!); + expect(location.searchParams.get("error")).toBe("access_denied"); + expect(location.searchParams.get("code")).toBeNull(); + expect(location.searchParams.get("state")).toBe("state-123"); + }); +}); diff --git a/pkgs/desktop-commander/worker/test/proxy.test.ts b/pkgs/desktop-commander/worker/test/proxy.test.ts index 7f71de26d..4dabbf253 100644 --- a/pkgs/desktop-commander/worker/test/proxy.test.ts +++ b/pkgs/desktop-commander/worker/test/proxy.test.ts @@ -1,18 +1,23 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import worker, { type Env } from "../src/index"; +import { MemoryKV } from "./memory-kv"; const env: Env = { BRIDGE_BASE: "https://commander-link.security.cab", ACCESS_CLIENT_ID: "bridge-id.access", ACCESS_CLIENT_SECRET: "bridge-secret", + MACHINE_BEARER: "machine-bearer-for-tests", + ACCESS_AUD: "authorize-app-aud", + ACCESS_TEAM_DOMAIN: "team.example.com", + OAUTH_KV: new MemoryKV() as unknown as KVNamespace, }; -function mcpRequest(withAssertion: boolean): Request { +function mcpRequest(authorization?: string): Request { const headers: Record = { "content-type": "application/json", accept: "application/json, text/event-stream", }; - if (withAssertion) headers["cf-access-jwt-assertion"] = "test-jwt"; + if (authorization) headers["authorization"] = authorization; return new Request("https://commander.security.cab/mcp", { method: "POST", headers, @@ -37,10 +42,21 @@ describe("desktop-commander Worker proxy", () => { expect(bridge).not.toHaveBeenCalled(); }); - it("refuses /mcp without an Access assertion and never calls the bridge", async () => { + it("refuses /mcp without a Bearer token and never calls the bridge", async () => { const bridge = vi.fn(); vi.stubGlobal("fetch", bridge); - const res = await worker.fetch(mcpRequest(false), env); + const res = await worker.fetch(mcpRequest(), env); + expect(res.status).toBe(401); + expect(res.headers.get("www-authenticate")).toBe( + 'Bearer resource_metadata="https://commander.security.cab/.well-known/oauth-protected-resource"', + ); + expect(bridge).not.toHaveBeenCalled(); + }); + + it("refuses /mcp with an unknown Bearer token", async () => { + const bridge = vi.fn(); + vi.stubGlobal("fetch", bridge); + const res = await worker.fetch(mcpRequest("Bearer not-a-real-token"), env); expect(res.status).toBe(401); expect(bridge).not.toHaveBeenCalled(); }); @@ -56,7 +72,7 @@ describe("desktop-commander Worker proxy", () => { }); }); vi.stubGlobal("fetch", bridge); - const res = await worker.fetch(mcpRequest(true), env); + const res = await worker.fetch(mcpRequest("Bearer machine-bearer-for-tests"), env); expect(res.status).toBe(200); expect(res.headers.get("mcp-session-id")).toBe("session-123"); @@ -69,6 +85,7 @@ describe("desktop-commander Worker proxy", () => { const sent = new Headers(calledInit.headers); expect(sent.get("cf-access-client-id")).toBe("bridge-id.access"); expect(sent.get("cf-access-client-secret")).toBe("bridge-secret"); + expect(sent.get("authorization")).toBeNull(); expect(sent.get("cf-access-jwt-assertion")).toBeNull(); }); diff --git a/pkgs/desktop-commander/worker/wrangler.toml b/pkgs/desktop-commander/worker/wrangler.toml index e7dce8d78..ac7431c9b 100644 --- a/pkgs/desktop-commander/worker/wrangler.toml +++ b/pkgs/desktop-commander/worker/wrangler.toml @@ -1,11 +1,16 @@ # desktop-commander Worker (#13404). The self-hosted replacement for the -# vendor's metered Remote Desktop Commander relay: an Access-gated MCP -# front door that proxies to the Desktop Commander bridge on the laptop. +# vendor's metered Remote Desktop Commander relay: an OAuth-fronted MCP +# door that proxies to the Desktop Commander bridge on the laptop. # # workers_dev is OFF: the only door is the custom domain -# commander.security.cab, which sits behind a Cloudflare Access app -# (owner Google identity + a service-token policy). The Worker itself -# refuses any request that arrives without an Access JWT assertion. +# commander.security.cab. Hosted MCP clients (Claude, ChatGPT) cannot +# pass a Cloudflare Access login at /mcp, so the Worker runs an OAuth +# 2.1 authorization server (src/oauth.ts): public discovery + +# registration, /token with PKCE, and /authorize — the one path still +# behind a Cloudflare Access app scoped to commander.security.cab/ +# authorize (owner Google identity only). /mcp accepts the OAuth +# Bearer tokens it issues, or the machine bearer for the owner's +# tooling. # # Secrets (uploaded per version with --secrets-file at publish time; # values never in this file): @@ -14,6 +19,8 @@ # (fleet secrets: # cloudflare.access.desktop-commander-link-client-id # cloudflare.access.desktop-commander-link-client-secret) +# MACHINE_BEARER Bearer for the owner's machine MCP clients +# (fleet secrets: desktop-commander.machine-bearer) name = "desktop-commander" main = "src/index.ts" compatibility_date = "2025-09-15" @@ -21,3 +28,11 @@ workers_dev = false [vars] BRIDGE_BASE = "https://commander-link.security.cab" +ACCESS_TEAM_DOMAIN = "snowy-sun-58a9.cloudflareaccess.com" +# Audience of the Access app scoped to /authorize (the Worker verifies +# it on the Access JWT before rendering the approval page). +ACCESS_AUD = "c6ddf0a5c0ba8742c0a3c74d12495bf5c4fe9bf6f01f604d62583cb2ed353879" + +[[kv_namespaces]] +binding = "OAUTH_KV" +id = "ea675d3c7d5b4f3b9f1cecae82e57d1b"