From b1ecde5c67178a0744a8b30644eeac2d713bfb41 Mon Sep 17 00:00:00 2001 From: euphyra-dev <279452614+euphyra-dev@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:29:49 +0100 Subject: [PATCH 1/2] workers/mcp: connect an agent with a FacturX account, no key to paste MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The consent page offers « Se connecter avec mon compte FacturX » when WEB_ORIGIN and both agent-connect secrets are set. The Worker approves the consent, binds the flow to the browser with the OAuth library's beginUpstream (__Host- cookie), signs a consent token and sends the browser to facturxapi.com/connecter-agent. On the fixed return /authorize/retour, finishUpstream refuses any other browser before the code is exchanged server to server. The paste field stays as a fallback. The wrangler comment states the real deploy rule. Co-Authored-By: Claude Opus 5.5 --- workers/mcp/src/agent-connect.ts | 153 ++++++++++++++++ workers/mcp/src/consent.ts | 125 ++++++++++++- workers/mcp/src/index.ts | 11 +- workers/mcp/test/agent-connect.test.ts | 235 +++++++++++++++++++++++++ workers/mcp/wrangler.jsonc | 13 +- 5 files changed, 529 insertions(+), 8 deletions(-) create mode 100644 workers/mcp/src/agent-connect.ts create mode 100644 workers/mcp/test/agent-connect.test.ts diff --git a/workers/mcp/src/agent-connect.ts b/workers/mcp/src/agent-connect.ts new file mode 100644 index 0000000..07dd057 --- /dev/null +++ b/workers/mcp/src/agent-connect.ts @@ -0,0 +1,153 @@ +/** + * « Se connecter avec mon compte FacturX »: connect an agent without pasting a key. + * + * Flow (design and review on the FacturX side, conditions S1–S5): + * 1. On the consent page the user picks this button. The Worker approves the consent, then calls the + * OAuth library's `beginUpstream`: a 256-bit `state`, the request stored encrypted in KV for 600 s, + * and a `__Host-` cookie holding the state's hash. Only this browser can finish the flow (S1). + * 2. The Worker signs a consent token (S2) and sends the browser to the fixed address + * `${webOrigin}/connecter-agent#consent=`. The token travels in the fragment. + * 3. facturxapi.com shows what the token covers, records the user's consent and sends the browser + * back to the fixed path `/authorize/retour?state=…&code=…` (S4). + * 4. `finishUpstream` refuses a browser that did not start the flow, before anything else. Only then + * does the Worker exchange the code, server to server, with its dedicated secret (S5). The API + * creates the agent key at this exchange only (S3), so a refused return leaves no key behind. + * + * The key is never in a URL, a page or the browser. + */ + +export const RETURN_PATH = "/authorize/retour"; +export const CONSENT_TTL_SECONDS = 600; // the API refuses more than 15 minutes +const EXCHANGE_PATH = "/api/v1/internal/agent-connections/exchange"; +const MAX_FIELD = 200; +const MAX_CODE = 200; + +export interface AgentConnectConfig { + webOrigin: string; + signingSecret: string; + exchangeSecret: string; +} + +export interface AgentConnectEnv { + WEB_ORIGIN?: string; + AGENT_CONNECT_SIGNING_SECRET?: string; + AGENT_CONNECT_EXCHANGE_SECRET?: string; +} + +/** A bare https origin (scheme, host, optional port), nothing else; anything else disables the flow. */ +export function bareHttpsOrigin(value: string | undefined): string | null { + if (!value) return null; + try { + const url = new URL(value); + if (url.protocol !== "https:" || url.username || url.password) return null; + if (url.origin !== value.replace(/\/$/, "")) return null; + return url.origin; + } catch { + return null; + } +} + +/** The flow is offered only when every piece is configured; otherwise the paste field stays alone. */ +export function agentConnectConfig(env: AgentConnectEnv): AgentConnectConfig | null { + const webOrigin = bareHttpsOrigin(env.WEB_ORIGIN); + const signingSecret = env.AGENT_CONNECT_SIGNING_SECRET ?? ""; + const exchangeSecret = env.AGENT_CONNECT_EXCHANGE_SECRET ?? ""; + if (!webOrigin || signingSecret.length < 32 || exchangeSecret.length < 32) return null; + return { webOrigin, signingSecret, exchangeSecret }; +} + +function base64url(bytes: Uint8Array): string { + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} + +function field(value: string): string { + const trimmed = value.trim(); + if (!trimmed) throw new Error("empty consent field"); + return trimmed.slice(0, MAX_FIELD); +} + +export interface ConsentClaims { + state: string; + clientId: string; + clientName: string; + redirectHost: string; + scopes: string[]; +} + +/** + * The token the API verifies (agent_connect_token.py): base64url(JSON payload) "." base64url(HMAC-SHA256(secret, + * payload part)), no padding. The API recomputes the MAC over the payload part exactly as received. + */ +export async function signConsentToken( + claims: ConsentClaims, + secret: string, + nowSeconds: number = Math.floor(Date.now() / 1000), +): Promise { + const payload = { + v: 1, + state: field(claims.state), + client_id: field(claims.clientId), + client_name: field(claims.clientName), + redirect_host: field(claims.redirectHost), + scopes: claims.scopes, + exp: nowSeconds + CONSENT_TTL_SECONDS, + }; + const payloadPart = base64url(new TextEncoder().encode(JSON.stringify(payload))); + const key = await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payloadPart))); + return `${payloadPart}.${base64url(mac)}`; +} + +/** The only place the browser is sent: the fixed page on the configured web origin. */ +export function consentRedirect(config: AgentConnectConfig, token: string): string { + return `${config.webOrigin}/connecter-agent#consent=${token}`; +} + +/** The return parameters, or null when they are missing or not plausible. Never echoed anywhere. */ +export function returnParams(url: URL): { state: string; code: string } | null { + const state = url.searchParams.get("state") ?? ""; + const code = url.searchParams.get("code") ?? ""; + if (!state || !code || state.length > MAX_FIELD || code.length > MAX_CODE) return null; + return { state, code }; +} + +export type ExchangeResult = { ok: true; apiKey: string } | { ok: false; status: number }; + +/** Server-to-server exchange of the single-use code for the agent key. */ +export async function exchangeCode( + baseUrl: string, + config: AgentConnectConfig, + params: { state: string; code: string }, + fetchImpl: typeof fetch = fetch, +): Promise { + let response: Response; + try { + response = await fetchImpl(`${baseUrl.replace(/\/$/, "")}${EXCHANGE_PATH}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Agent-Connect-Secret": config.exchangeSecret, + }, + body: JSON.stringify({ code: params.code, state: params.state }), + redirect: "manual", + }); + } catch { + return { ok: false, status: 502 }; + } + if (response.status !== 200) return { ok: false, status: response.status }; + try { + const body = (await response.json()) as { api_key?: unknown }; + if (typeof body.api_key !== "string" || !body.api_key) return { ok: false, status: 502 }; + return { ok: true, apiKey: body.api_key }; + } catch { + return { ok: false, status: 502 }; + } +} diff --git a/workers/mcp/src/consent.ts b/workers/mcp/src/consent.ts index 81db072..680ba62 100644 --- a/workers/mcp/src/consent.ts +++ b/workers/mcp/src/consent.ts @@ -1,3 +1,11 @@ +import { + type AgentConnectConfig, + consentRedirect, + exchangeCode, + RETURN_PATH, + returnParams, + signConsentToken, +} from "./agent-connect.ts"; import { asApiError, facturxFetch, multipart } from "./api.ts"; import { SCOPES } from "./constants.ts"; import { isLoopbackRedirect, redirectAllowed } from "./redirects.ts"; @@ -35,6 +43,11 @@ export interface OauthLike { options?: { scope?: string[] }, ): Promise<{ request: AuthRequestLike; headers: Headers }>; denyConsent(request: Request, handle: string): Promise<{ redirectTo: string; headers: Headers }>; + beginUpstream( + request: AuthRequestLike, + options?: { data?: unknown; headers?: Headers }, + ): Promise<{ state: string; headers: Headers }>; + finishUpstream(request: Request): Promise<{ request: AuthRequestLike; data?: unknown; headers: Headers }>; completeAuthorization(options: { request: AuthRequestLike; userId: string; @@ -58,7 +71,7 @@ function scopeCaption(scope: string): string { return scope; } -export function consentPage(details: ConsentFacts, handle: string): string { +export function consentPage(details: ConsentFacts, handle: string, accountButton = false): string { const name = escapeHtml(details.clientName); const origin = details.clientDomain ? `Publié par ${escapeHtml(details.clientDomain)}.` @@ -71,6 +84,10 @@ export function consentPage(details: ConsentFacts, handle: string): string { return `${hidden}`; }) .join(""); + const account = accountButton + ? `

+

Vous avez déjà un compte FacturX ? Autorisez ${name} en un clic : une clé dédiée est créée pour lui, sans rien copier. Ou collez une clé ci-dessous.

` + : ""; const loopback = details.redirectIsLoopback ? "

Cet accès part vers une application sur cet ordinateur. Continuez seulement si vous venez de lancer la connexion.

" : ""; @@ -93,6 +110,7 @@ export function consentPage(details: ConsentFacts, handle: string): string { ${loopback}
+ ${account}

Pas encore de clé ? Créez-en une sur facturxapi.com/api-key.

${scopes}
@@ -150,8 +168,12 @@ export async function handleAuthorize( oauth: OauthLike, baseUrl: string, fetchImpl?: typeof fetch, + agentConnect?: AgentConnectConfig | null, ): Promise { const url = new URL(request.url); + if (url.pathname === RETURN_PATH) { + return handleReturn(request, url, oauth, baseUrl, agentConnect ?? null, fetchImpl); + } if (url.pathname !== "/authorize") { return new Response("FacturX MCP. The connector is /mcp. The API key is never put in a URL.", { headers: { "Content-Type": "text/plain; charset=utf-8" }, @@ -165,11 +187,14 @@ export async function handleAuthorize( if (loopbackWithoutS256(auth)) return page(PKCE_REQUIRED, 400); const details = await oauth.describeConsent(auth); const consent = await oauth.beginConsent(auth); - return page(consentPage(details, consent.handle), 200, consent.headers); + return page(consentPage(details, consent.handle, Boolean(agentConnect)), 200, consent.headers); } if (request.method !== "POST") return page("

Méthode refusée.

", 405); const form = await request.formData(); const handle = String(form.get("handle") ?? ""); + if (form.get("decision") === "facturx") { + return startAccountConnect(request, form, handle, oauth, agentConnect ?? null); + } if (form.get("decision") !== "approve") { const denied = await oauth.denyConsent(request, handle); const headers = denied.headers; @@ -220,3 +245,99 @@ export async function handleAuthorize( approved.headers.set("Location", completed.redirectTo); return new Response(null, { status: 302, headers: approved.headers }); } + +const RESTART = "

La connexion n'a pas abouti. Relancez-la depuis votre agent. Aucune clé n'a été créée.

"; + +function grantedScopes(form: FormData): string[] { + return form + .getAll("scope") + .map(String) + .filter((scope) => (SCOPES as readonly string[]).includes(scope)); +} + +/** « Se connecter avec mon compte FacturX »: approve, bind the flow to this browser, send it to facturxapi.com. */ +async function startAccountConnect( + request: Request, + form: FormData, + handle: string, + oauth: OauthLike, + config: AgentConnectConfig | null, +): Promise { + if (!config) return page("

Cette option n'est pas disponible. Collez une clé API.

", 400); + const granted = grantedScopes(form); + if (!granted.includes("mcp:read")) { + return page("

La portée mcp:read est requise. Rien n'a été enregistré.

", 400); + } + const approved = await oauth.approveConsent(request, handle, { scope: granted }); + if (!redirectAllowed(approved.request.redirectUri)) { + return page("

Cette adresse de retour n'est pas celle de Claude, de ChatGPT ni d'une application locale.

", 400); + } + if (loopbackWithoutS256(approved.request)) return page(PKCE_REQUIRED, 400); + if (!approved.request.scope.includes("mcp:read")) { + return page("

Le client doit demander mcp:read. Rien n'a été enregistré.

", 400); + } + const scope = granted.filter((name) => approved.request.scope.includes(name)); + const details = await oauth.describeConsent(approved.request); + // S1: the library stores the request under a fresh state and binds it to this browser (__Host- cookie). + const upstream = await oauth.beginUpstream(approved.request, { data: { scope }, headers: approved.headers }); + // S2: everything the page shows comes from this signed token, never from URL parameters. + const token = await signConsentToken( + { + state: upstream.state, + clientId: approved.request.clientId, + clientName: details.clientName, + redirectHost: new URL(approved.request.redirectUri).host, + scopes: scope, + }, + config.signingSecret, + ); + upstream.headers.set("Location", consentRedirect(config, token)); + upstream.headers.set("Cache-Control", "no-store"); + return new Response(null, { status: 303, headers: upstream.headers }); +} + +/** The fixed return from facturxapi.com: this browser only (S1), then the server-to-server exchange (S5). */ +async function handleReturn( + request: Request, + url: URL, + oauth: OauthLike, + baseUrl: string, + config: AgentConnectConfig | null, + fetchImpl?: typeof fetch, +): Promise { + if (!config || request.method !== "GET") return page(RESTART, 400); + const params = returnParams(url); + if (!params) return page(RESTART, 400); + let finished: Awaited>; + try { + // Refuses a browser without this flow's cookie BEFORE anything else: the code is then never exchanged, + // and the API, which creates the key at the exchange only, creates none. + finished = await oauth.finishUpstream(request); + } catch { + return page(RESTART, 400); + } + if (!redirectAllowed(finished.request.redirectUri) || loopbackWithoutS256(finished.request)) { + return page(RESTART, 400, finished.headers); + } + const exchanged = await exchangeCode(baseUrl, config, params, fetchImpl); + if (!exchanged.ok) return page(RESTART, 400, finished.headers); + const apiKey = exchanged.apiKey; + const stored = (finished.data ?? {}) as { scope?: unknown }; + const scope = (Array.isArray(stored.scope) ? stored.scope.map(String) : []).filter( + (name) => (SCOPES as readonly string[]).includes(name) && finished.request.scope.includes(name), + ); + if (!scope.includes("mcp:read")) return page(RESTART, 400, finished.headers); + // userId is stored in the clear by the OAuth library. It must not be the key or its hash. + const completed = await oauth.completeAuthorization({ + request: finished.request, + userId: crypto.randomUUID(), + metadata: {}, + scope, + props: { apiKey }, + }); + if (completed.redirectTo.includes(apiKey) || completed.redirectTo.includes(encodeURIComponent(apiKey))) { + throw new Error("refusing a redirect that echoes the key"); + } + finished.headers.set("Location", completed.redirectTo); + return new Response(null, { status: 302, headers: finished.headers }); +} diff --git a/workers/mcp/src/index.ts b/workers/mcp/src/index.ts index 50d70ed..d88e6de 100644 --- a/workers/mcp/src/index.ts +++ b/workers/mcp/src/index.ts @@ -5,11 +5,12 @@ import { type OAuthHelpers, } from "@cloudflare/workers-oauth-provider"; import { SCOPES } from "./constants.ts"; +import { agentConnectConfig, type AgentConnectEnv } from "./agent-connect.ts"; import { handleAuthorize } from "./consent.ts"; import { handleMcp } from "./mcp.ts"; import { registrationRedirectsAllowed } from "./redirects.ts"; -export interface Env { +export interface Env extends AgentConnectEnv { OAUTH_KV: KVNamespace; FACTURX_BASE_URL: string; PUBLIC_BASE_URL?: string; @@ -42,7 +43,13 @@ function providerFor(request: Request, env: Env): OAuthProvider { defaultHandler: { async fetch(incoming, handlerEnv) { try { - return await handleAuthorize(incoming, handlerEnv.OAUTH_PROVIDER, handlerEnv.FACTURX_BASE_URL); + return await handleAuthorize( + incoming, + handlerEnv.OAUTH_PROVIDER, + handlerEnv.FACTURX_BASE_URL, + undefined, + agentConnectConfig(handlerEnv), + ); } catch (error) { if (error instanceof AuthorizationError && error.redirectTo) { return Response.redirect(error.redirectTo, 302); diff --git a/workers/mcp/test/agent-connect.test.ts b/workers/mcp/test/agent-connect.test.ts new file mode 100644 index 0000000..ae86b26 --- /dev/null +++ b/workers/mcp/test/agent-connect.test.ts @@ -0,0 +1,235 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + agentConnectConfig, + bareHttpsOrigin, + CONSENT_TTL_SECONDS, + signConsentToken, + type AgentConnectConfig, +} from "../src/agent-connect.ts"; +import { consentPage, handleAuthorize, type AuthRequestLike, type OauthLike } from "../src/consent.ts"; + +const BASE = "https://api.facturxapi.com"; +const SIGNING = "s".repeat(40); +const EXCHANGE = "e".repeat(40); +const CONFIG: AgentConnectConfig = { webOrigin: "https://facturxapi.com", signingSecret: SIGNING, exchangeSecret: EXCHANGE }; +const AGENT_KEY = "fxk_test_agent_zzzzzzzz"; +const AUTH: AuthRequestLike = { + redirectUri: "http://127.0.0.1:33418/callback", + scope: ["mcp:read", "mcp:write"], + clientId: "client-abc", + codeChallenge: "x".repeat(43), + codeChallengeMethod: "S256", +}; + +function b64urlDecode(part: string): Uint8Array { + const b64 = part.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (part.length % 4)) % 4); + return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)); +} + +interface Calls { + begin: number; + finish: number; + complete: Array<{ scope: string[]; props: { apiKey: string } }>; +} + +function fakeOauth(calls: Calls, finish: () => Promise<{ request: AuthRequestLike; data?: unknown; headers: Headers }>): OauthLike { + return { + async parseAuthRequest() { + return AUTH; + }, + async describeConsent() { + return { clientName: "Claude Code", redirectHost: "127.0.0.1:33418", redirectIsLoopback: true, scope: AUTH.scope }; + }, + async beginConsent() { + return { handle: "handle-1", headers: new Headers() }; + }, + async approveConsent(_request, _handle, options) { + return { request: { ...AUTH, scope: AUTH.scope }, headers: new Headers({ "X-Approved": String(options?.scope) }) }; + }, + async denyConsent() { + return { redirectTo: "http://127.0.0.1:33418/callback?error=access_denied", headers: new Headers() }; + }, + async beginUpstream(_request, options) { + calls.begin += 1; + const headers = options?.headers ?? new Headers(); + headers.append("Set-Cookie", "__Host-oauth-upstream-abc=hash; Path=/; Secure; HttpOnly; SameSite=Lax"); + return { state: "state-from-library", headers }; + }, + async finishUpstream() { + calls.finish += 1; + return finish(); + }, + async completeAuthorization(options) { + calls.complete.push({ scope: options.scope, props: options.props }); + return { redirectTo: "http://127.0.0.1:33418/callback?code=oauth-code&state=client-state" }; + }, + }; +} + +function postForm(fields: Record, query = ""): Request { + const form = new FormData(); + for (const [name, value] of Object.entries(fields)) { + for (const item of Array.isArray(value) ? value : [value]) form.append(name, item); + } + return new Request(`https://mcp.facturxapi.com/authorize${query}`, { method: "POST", body: form }); +} + +test("the signed token is the exact format the API verifies, valid 600 s", async () => { + const now = 1_800_000_000; + const token = await signConsentToken( + { state: "st", clientId: "cid", clientName: "Claude Code", redirectHost: "127.0.0.1:33418", scopes: ["mcp:read"] }, + SIGNING, + now, + ); + assert.equal(token.split(".").length, 2); + assert.doesNotMatch(token, /[=+/]/); + const [payloadPart, macPart] = token.split("."); + const payload = JSON.parse(new TextDecoder().decode(b64urlDecode(payloadPart))); + assert.deepEqual(payload, { + v: 1, + state: "st", + client_id: "cid", + client_name: "Claude Code", + redirect_host: "127.0.0.1:33418", + scopes: ["mcp:read"], + exp: now + 600, + }); + assert.ok(CONSENT_TTL_SECONDS <= 15 * 60); + const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(SIGNING), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]); + assert.equal(await crypto.subtle.verify("HMAC", key, b64urlDecode(macPart), new TextEncoder().encode(payloadPart)), true); +}); + +test("the web origin must be a bare https origin; otherwise the flow is off", () => { + assert.equal(bareHttpsOrigin("https://facturxapi.com"), "https://facturxapi.com"); + assert.equal(bareHttpsOrigin("https://facturxapi.com/"), "https://facturxapi.com"); + for (const bad of ["http://facturxapi.com", "https://facturxapi.com/path", "https://facturxapi.com?x=1", "https://u:p@facturxapi.com", "", undefined]) { + assert.equal(bareHttpsOrigin(bad), null, String(bad)); + } + assert.equal(agentConnectConfig({ WEB_ORIGIN: "https://facturxapi.com", AGENT_CONNECT_SIGNING_SECRET: SIGNING }), null); + assert.equal(agentConnectConfig({ WEB_ORIGIN: "https://facturxapi.com", AGENT_CONNECT_SIGNING_SECRET: "short", AGENT_CONNECT_EXCHANGE_SECRET: EXCHANGE }), null); + assert.deepEqual( + agentConnectConfig({ WEB_ORIGIN: "https://facturxapi.com", AGENT_CONNECT_SIGNING_SECRET: SIGNING, AGENT_CONNECT_EXCHANGE_SECRET: EXCHANGE }), + CONFIG, + ); +}); + +test("the account button appears only when the flow is configured, and skips the key field's validation", () => { + const facts = { clientName: "Claude Code", redirectHost: "127.0.0.1:33418", redirectIsLoopback: true, scope: ["mcp:read"] }; + assert.doesNotMatch(consentPage(facts, "h"), /Se connecter avec mon compte FacturX/); + const html = consentPage(facts, "h", true); + assert.match(html, /