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
170 changes: 170 additions & 0 deletions workers/mcp/src/agent-connect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
/**
* « 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=<token>`. 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(/=+$/, "");
}

export class ConsentFieldError extends Error {}

/** The API refuses any field over 200 characters: an identifier that long is refused here, never cut (IMPL-2). */
function exactField(value: string): string {
const trimmed = value.trim();
if (!trimmed || trimmed.length > MAX_FIELD) throw new ConsentFieldError("consent field empty or too long");
return trimmed;
}

/** Only the displayed name may be shortened: the page shows it as plain text, at most 60 characters. */
function displayField(value: string): string {
const trimmed = value.trim();
if (!trimmed) throw new ConsentFieldError("empty client name");
return trimmed.slice(0, MAX_FIELD);
}

/** Whether a client can use the account flow at all (identifiers the API will accept). */
export function consentFieldsAcceptable(clientId: string, redirectHost: string): boolean {
const ok = (value: string) => value.trim().length > 0 && value.trim().length <= MAX_FIELD;
return ok(clientId) && ok(redirectHost);
}

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<string> {
const payload = {
v: 1,
state: exactField(claims.state),
client_id: exactField(claims.clientId),
client_name: displayField(claims.clientName),
redirect_host: exactField(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; scopes: 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<ExchangeResult> {
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; scopes?: unknown };
if (typeof body.api_key !== "string" || !body.api_key) return { ok: false, status: 502 };
const scopes = Array.isArray(body.scopes) ? body.scopes.filter((s): s is string => typeof s === "string") : [];
return { ok: true, apiKey: body.api_key, scopes };
} catch {
return { ok: false, status: 502 };
}
}
135 changes: 133 additions & 2 deletions workers/mcp/src/consent.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
import {
type AgentConnectConfig,
consentFieldsAcceptable,
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";
Expand Down Expand Up @@ -35,6 +44,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;
Expand All @@ -58,7 +72,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 <strong>${escapeHtml(details.clientDomain)}</strong>.`
Expand All @@ -71,6 +85,10 @@ export function consentPage(details: ConsentFacts, handle: string): string {
return `${hidden}<label><input type="checkbox" name="scope" value="${safe}"${required}> ${escapeHtml(scopeCaption(scope))}</label>`;
})
.join("");
const account = accountButton
? `<p><button name="decision" value="facturx" formnovalidate>Se connecter avec mon compte FacturX</button></p>
<p>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.</p>`
: "";
const loopback = details.redirectIsLoopback
? "<p><strong>Cet accès part vers une application sur cet ordinateur.</strong> Continuez seulement si vous venez de lancer la connexion.</p>"
: "";
Expand All @@ -93,6 +111,7 @@ export function consentPage(details: ConsentFacts, handle: string): string {
${loopback}
<form method="post">
<input type="hidden" name="handle" value="${escapeHtml(handle)}">
${account}
<label>Votre clé API FacturX <input type="password" name="api_key" autocomplete="off" required></label>
<p>Pas encore de clé ? <a href="https://facturxapi.com/api-key">Créez-en une sur facturxapi.com/api-key</a>.</p>
<div>${scopes}</div>
Expand Down Expand Up @@ -150,8 +169,12 @@ export async function handleAuthorize(
oauth: OauthLike,
baseUrl: string,
fetchImpl?: typeof fetch,
agentConnect?: AgentConnectConfig | null,
): Promise<Response> {
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" },
Expand All @@ -165,11 +188,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("<p>Méthode refusée.</p>", 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;
Expand Down Expand Up @@ -220,3 +246,108 @@ export async function handleAuthorize(
approved.headers.set("Location", completed.redirectTo);
return new Response(null, { status: 302, headers: approved.headers });
}

const RESTART = "<p>La connexion n'a pas abouti. Relancez-la depuis votre agent. Aucune clé n'a été créée.</p>";

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<Response> {
if (!config) return page("<p>Cette option n'est pas disponible. Collez une clé API.</p>", 400);
const granted = grantedScopes(form);
if (!granted.includes("mcp:read")) {
return page("<p>La portée mcp:read est requise. Rien n'a été enregistré.</p>", 400);
}
const approved = await oauth.approveConsent(request, handle, { scope: granted });
if (!redirectAllowed(approved.request.redirectUri)) {
return page("<p>Cette adresse de retour n'est pas celle de Claude, de ChatGPT ni d'une application locale.</p>", 400);
}
if (loopbackWithoutS256(approved.request)) return page(PKCE_REQUIRED, 400);
if (!approved.request.scope.includes("mcp:read")) {
return page("<p>Le client doit demander mcp:read. Rien n'a été enregistré.</p>", 400);
}
const scope = granted.filter((name) => approved.request.scope.includes(name));
const redirectHost = new URL(approved.request.redirectUri).host;
if (!consentFieldsAcceptable(approved.request.clientId, redirectHost)) {
// Checked before anything is bound to the browser: the API would refuse these identifiers.
return page("<p>Cette application ne peut pas utiliser la connexion par compte. Collez une clé API.</p>", 400);
}
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,
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<Response> {
if (!config || request.method !== "GET") return page(RESTART, 400);
const params = returnParams(url);
if (!params) return page(RESTART, 400);
let finished: Awaited<ReturnType<OauthLike["finishUpstream"]>>;
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 };
// Scopes: what the user granted here, the client asked for, AND the API recorded for this key (IMPL-3).
const scope = (Array.isArray(stored.scope) ? stored.scope.map(String) : []).filter(
(name) =>
(SCOPES as readonly string[]).includes(name) &&
finished.request.scope.includes(name) &&
exchanged.scopes.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 });
}
11 changes: 9 additions & 2 deletions workers/mcp/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -42,7 +43,13 @@ function providerFor(request: Request, env: Env): OAuthProvider<Env> {
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);
Expand Down
Loading