Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): remote MCP-OAuth discovery client + CIMD document (C1)
Diego Zacarias8ebd128588cc
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex c76225829..461945ecf 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.588",+ "version": "0.1.589","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.588",+ "version": "0.1.589","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex d3cc0edd9..a518fab2a 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.588",+ "version": "0.1.589","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/app.ts b/control-api/src/app.tsindex 400efa88e..7d27a8a8b 100644--- a/control-api/src/app.ts+++ b/control-api/src/app.ts@@ -10,6 +10,7 @@ import {createTracingInFlightLimiter,getTracingMaxInFlight,} from './middleware/tracingSubmitterAuth.js'+import { createCimdRouter } from './oauth/cimd.js'import { createAdminAuthRouter } from './routes/admin/auth.js'import { createAdminRouter } from './routes/admin/index.js'import { createWorkflowsAdminRouter } from './routes/admin/workflows/index.js'@@ -194,6 +195,10 @@ export function createApp(gateway: K8sGateway) {// parameter, not a Clerum cookie or service token. Mounted BEFORE// requireInternalToken so the public can hit it.api.use(createOAuthCallbackRouter(gateway))+ // CIMD (SEP-991): public GET of the platform's OAuth Client ID Metadata+ // Document for the remote MCP-OAuth lane. Read-only, no auth — a remote AS+ // fetches it. Mounted BEFORE requireInternalToken so it stays public.+ api.use(createCimdRouter())api.use(createAuthRoutes(gateway))// Recipe OAuth broker — background workloads present a per-recipe broker// token (Bearer, aud=oauth-broker). Auth is the broker token itself, not adiff --git a/control-api/src/oauth/cimd.ts b/control-api/src/oauth/cimd.tsnew file mode 100644index 000000000..9d6a3f24b--- /dev/null+++ b/control-api/src/oauth/cimd.ts@@ -0,0 +1,94 @@+import { Router } from 'express'+import { config } from '../config.js'+import { type Logger, rootLogger } from '../observability/logger.js'+import { normalizeConfiguredOrigin } from '../routes/external/oauthCallback.js'++/**+ * Client ID Metadata Document (CIMD, SEP-991), served by control-api as the+ * platform's OAuth client identity for the remote MCP-OAuth lane (spec 19 §5 C1,+ * D-9 / S-6).+ *+ * The document is Evenfire's *identity as an OAuth client*: its `client_id` IS the+ * public URL the document is served at (SEP-991), so a remote Authorization Server+ * can fetch it to learn our redirect URIs and auth method without any per-AS+ * registration. Because the identity lives in versioned deploy code (this module),+ * not in hot-editable config, it is reviewable and immutable at runtime (S-6):+ * there is NO write path here — the router serves a frozen object on GET only.+ */++export interface CimdDocument {+ /** SEP-991: the client_id IS this document's own public URL (byte-identical to the fetch URL). */+ client_id: string+ client_name: string+ /** Stable remote callback segment; server disambiguation rides the signed `state` (C1.5). */+ redirect_uris: readonly string[]+ /** Public client — no client_secret. */+ token_endpoint_auth_method: 'none'+ grant_types: readonly string[]+ response_types: readonly string[]+ application_type: 'web'+}++/** Path the CIMD document is served at, relative to the `/api/v1` mount in app.ts. */+export const CIMD_ROUTE_PATH = '/.well-known/evenfire-mcp-client'++/** Full public path of the served document (what `client_id` must equal, minus origin). */+const CIMD_PUBLIC_PATH = `/api/v1${CIMD_ROUTE_PATH}`++/** Stable remote-lane callback segment. C1.5 honours this exact oauthClientId. */+const REMOTE_CALLBACK_PATH = '/api/v1/oauth-callback/remote'++/**+ * Build the frozen CIMD document for a given public `origin` (scheme://host, no+ * trailing slash — as produced by `normalizeConfiguredOrigin`). `client_id` is the+ * document's own URL (SEP-991); `redirect_uris` carries the stable remote callback+ * segment. The result is `Object.freeze`d so no caller can mutate the served+ * identity in place (S-6).+ */+export function buildCimdDocument(origin: string): Readonly<CimdDocument> {+ return Object.freeze<CimdDocument>({+ client_id: `${origin}${CIMD_PUBLIC_PATH}`,+ client_name: 'Evenfire',+ redirect_uris: Object.freeze([`${origin}${REMOTE_CALLBACK_PATH}`]),+ token_endpoint_auth_method: 'none',+ grant_types: Object.freeze(['authorization_code', 'refresh_token']),+ response_types: Object.freeze(['code']),+ application_type: 'web',+ })+}++/**+ * Router serving the CIMD document. Read-only (GET), no write path (S-6).+ *+ * Fails closed with 503 when no public callback base URL is configured: unlike the+ * OAuth callback, CIMD must NOT fall back to the request Host — a remote AS fetching+ * this document would otherwise be handed the internal proxy Host as our origin,+ * which would break the SEP-991 `client_id == document URL` identity.+ *+ * `getBaseUrl` is injectable for testing both the served document and the+ * fail-closed path without mutating the process-wide config singleton; it defaults+ * to the same `config.oauthCallbackBaseUrl` the callback redirect uses.+ */+export function createCimdRouter(+ deps: { getBaseUrl?: () => string; logger?: Logger } = {}+): Router {+ const getBaseUrl = deps.getBaseUrl ?? (() => config.oauthCallbackBaseUrl)+ const log = (deps.logger ?? rootLogger).child({ module: 'oauth-cimd' })+ const router = Router()++ router.get(CIMD_ROUTE_PATH, (_req, res) => {+ const origin = normalizeConfiguredOrigin(getBaseUrl())+ if (origin === null) {+ log.error('cimd document requested but no public callback base URL configured')+ return res.status(503).json({ error: 'cimd_base_url_unconfigured' })+ }+ const document = buildCimdDocument(origin)+ return res+ .status(200)+ .type('application/json')+ .set('Cache-Control', 'public, max-age=300')+ .json(document)+ })++ return router+}diff --git a/control-api/src/oauth/discovery.ts b/control-api/src/oauth/discovery.tsnew file mode 100644index 000000000..7118e0782--- /dev/null+++ b/control-api/src/oauth/discovery.ts@@ -0,0 +1,622 @@+import {+ type DnsResolver,+ type ValidationError,+ validateOAuthEndpointUrl,+} from '../http/validateMcpServerSpec.js'+import { type Logger, rootLogger } from '../observability/logger.js'++/**+ * Remote MCP-OAuth discovery client (spec 19 §4/§5 C1, D-3/D-8).+ *+ * Implements the client side of RFC 9728 (Protected Resource Metadata) → RFC 8414+ * (Authorization Server Metadata), carrying RFC 8707 (`resource`) and RFC 9207+ * (`iss`) forward for the exchange/callback. Every URL fetched or pinned passes the+ * policy kernel (`validateOAuthEndpointUrl`, spec §4) BEFORE the fetch — the AS/PRM+ * are third-party data (§0), so discovery is fail-closed on internal/blocked hosts.+ *+ * Nothing here re-discovers at runtime: C1.5 pins the resolved endpoints on the CR.+ */++const DISCOVERY_TIMEOUT_MS = 15_000++/**+ * Max redirect hops discovery follows manually. undici's default+ * `redirect:'follow'` would let an untrusted AS/PRM 3xx us into an internal host+ * (IMDS/cluster) with only the FIRST hop kernel-checked, so we follow by hand and+ * re-validate every hop; this bounds the chain to a fail-closed limit.+ */+const MAX_DISCOVERY_REDIRECTS = 5++// ─── Metadata shapes (third-party data — every field is untrusted) ──────────++export interface ProtectedResourceMetadata {+ resource: string+ authorization_servers?: string[]+ scopes_supported?: string[]+ /** RFC 9728: how the resource accepts the bearer token (D-8 bearer-in-body). */+ bearer_methods_supported?: string[]+ resource_name?: string+ [key: string]: unknown+}++export interface AuthorizationServerMetadata {+ issuer: string+ authorization_endpoint: string+ token_endpoint: string+ registration_endpoint?: string+ scopes_supported?: string[]+ response_types_supported?: string[]+ grant_types_supported?: string[]+ token_endpoint_auth_methods_supported?: string[]+ code_challenge_methods_supported?: string[]+ /** SEP-991: AS accepts a Client ID Metadata Document as the client_id. */+ client_id_metadata_document_supported?: boolean+ /** RFC 9207: AS returns `iss` on the authorization response. */+ authorization_response_iss_parameter_supported?: boolean+ revocation_endpoint?: string+ resource?: string+ resource_metadata?: string+ [key: string]: unknown+}++// ─── Registration mode selection (D-3, pure) ────────────────────────────────++export type RegistrationMode = 'pre-registered' | 'cimd' | 'dcr' | 'manual'++export interface SelectRegistrationModeInput {+ hasPreRegisteredClient: boolean+ cimdSupported: boolean+ tokenEndpointAuthMethods: string[]+ hasRegistrationEndpoint: boolean+}++/**+ * Choose the client-registration mode in the normative order+ * `pre-registered > CIMD > DCR > manual` (D-3), returning the FIRST applicable one.+ *+ * The classic industry bug is inverting this order (Claude Code × Slack), so the+ * ordering is an invariant with a property test (T2): CIMD requires the DOUBLE+ * condition (`cimdSupported` AND `none` ∈ auth methods — a public client); DCR+ * requires a registration endpoint; otherwise the operator registers manually.+ */+export function selectRegistrationMode(input: SelectRegistrationModeInput): RegistrationMode {+ if (input.hasPreRegisteredClient) return 'pre-registered'+ if (input.cimdSupported && input.tokenEndpointAuthMethods.includes('none')) return 'cimd'+ if (input.hasRegistrationEndpoint) return 'dcr'+ return 'manual'+}++// ─── Transport quirks derived from metadata (D-8, pure) ─────────────────────++export interface RemoteQuirks {+ /** Token goes in the request body, not the Authorization header (SEMrush). */+ bearerInBody: boolean+ /** AS advertises `refresh_token` in grant_types — fail-closed on absence. */+ supportsRefresh: boolean+}++/**+ * Derive transport quirks from metadata (D-8).+ *+ * `bearerInBody` is a Protected Resource Metadata property (RFC 9728+ * `bearer_methods_supported`), NOT an AS field. The safe rule: only use the body+ * when the resource does NOT accept the header — i.e. `["body"]` without+ * `"header"`. When the resource advertises `"header"` (the RFC 6750 default) or+ * says nothing, we keep the token in the Authorization header, which is where a+ * bearer belongs unless the resource explicitly refuses it.+ *+ * `supportsRefresh` is fail-closed (invariant 8): a missing `grant_types_supported`+ * or one without `refresh_token` means we never attempt a refresh.+ */+export function deriveQuirks(+ as: AuthorizationServerMetadata,+ prm: ProtectedResourceMetadata+): RemoteQuirks {+ const methods = prm.bearer_methods_supported+ const bearerInBody =+ Array.isArray(methods) && methods.includes('body') && !methods.includes('header')+ const supportsRefresh = as.grant_types_supported?.includes('refresh_token') ?? false+ return { bearerInBody, supportsRefresh }+}++// ─── Discovery flow ─────────────────────────────────────────────────────────++export interface DiscoveryDeps {+ fetchFn: typeof fetch+ resolveDns?: DnsResolver+ logger?: Logger+}++export type DiscoveryError =+ | { kind: 'kernel_rejected'; field: string; errors: ValidationError[] }+ | { kind: 'fetch_failed'; url: string; status?: number; detail: string }+ | { kind: 'invalid_metadata'; url: string; detail: string }+ | { kind: 'no_s256'; detail: string }+ | { kind: 'no_authorization_server'; detail: string }+ /** A redirect the kernel could not clear was blocked (missing/invalid Location, or the hop bound was hit). */+ | { kind: 'redirect_blocked'; url: string; detail: string }+ /** PRM `resource` (RFC 9728 §3.3) is not consistent with the MCP URL it describes. */+ | { kind: 'prm_resource_mismatch'; url: string; detail: string }+ /** AS metadata `issuer` (RFC 8414 §3.3) does not match the AS base it was fetched from. */+ | { kind: 'issuer_mismatch'; detail: string }++export interface DiscoveryResult {+ prm: ProtectedResourceMetadata+ as: AuthorizationServerMetadata+ /** RFC 8707 value to send in authorize + token requests. */+ resource: string+ /** AS issuer (RFC 8414). */+ issuer: string+ /**+ * Issuer to validate the callback `iss` against (RFC 9207), present ONLY when the+ * AS advertises `authorization_response_iss_parameter_supported`. When present,+ * the callback MUST reject a response whose `iss` != this value; when absent, the+ * AS does not return `iss` and there is nothing to compare.+ */+ issForCallback?: string+ /** Endpoints pinned after passing the kernel — safe to persist on the CR (C1.5). */+ endpoints: {+ authorization: string+ token: string+ registration?: string+ }+ registrationMode: RegistrationMode+ quirks: RemoteQuirks+}++export type DiscoveryOutcome =+ | { ok: true; result: DiscoveryResult }+ | { ok: false; error: DiscoveryError }++function errMessage(e: unknown): string {+ return e instanceof Error ? e.message : String(e)+}++function isRedirectStatus(status: number): boolean {+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308+}++/**+ * Kernel-guard a URL and fetch it, following redirects MANUALLY (`redirect:'manual'`).+ *+ * The default `redirect:'follow'` only lets the kernel veto the FIRST hop — undici+ * then follows a `302 Location: http://169.254.169.254/…` from an untrusted AS/PRM+ * (§0) straight to IMDS/an internal host (SSRF). Here every hop — the initial URL+ * AND each `Location` (resolved against the current URL) — passes+ * `validateOAuthEndpointUrl` (§4, DNS-resolved) BEFORE it is fetched. A `Location`+ * the kernel rejects, a missing/invalid `Location`, or exceeding+ * {@link MAX_DISCOVERY_REDIRECTS} is a typed fail-closed error, never followed.+ */+async function guardedFetch(+ url: string,+ field: string,+ deps: DiscoveryDeps+): Promise<+ { ok: true; response: Response; finalUrl: string } | { ok: false; error: DiscoveryError }+> {+ let currentUrl = url+ for (let hop = 0; ; hop++) {+ const errors = await validateOAuthEndpointUrl(currentUrl, field, {+ resolveDns: deps.resolveDns,+ })+ if (errors.length > 0) {+ return { ok: false, error: { kind: 'kernel_rejected', field, errors } }+ }+ let response: Response+ try {+ response = await deps.fetchFn(currentUrl, {+ redirect: 'manual',+ signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),+ })+ } catch (e) {+ return { ok: false, error: { kind: 'fetch_failed', url: currentUrl, detail: errMessage(e) } }+ }+ if (!isRedirectStatus(response.status)) {+ return { ok: true, response, finalUrl: currentUrl }+ }+ if (hop >= MAX_DISCOVERY_REDIRECTS) {+ return {+ ok: false,+ error: {+ kind: 'redirect_blocked',+ url: currentUrl,+ detail: `exceeded ${MAX_DISCOVERY_REDIRECTS} redirects`,+ },+ }+ }+ const location = response.headers.get('location')+ if (!location) {+ return {+ ok: false,+ error: {+ kind: 'redirect_blocked',+ url: currentUrl,+ detail: `HTTP ${response.status} redirect without a Location header`,+ },+ }+ }+ try {+ currentUrl = new URL(location, currentUrl).toString()+ } catch {+ return {+ ok: false,+ error: {+ kind: 'redirect_blocked',+ url: currentUrl,+ detail: 'redirect Location is not a valid URL',+ },+ }+ }+ }+}++/**+ * Kernel-guard a URL and only then fetch it as JSON, following redirects through+ * the kernel (see {@link guardedFetch}). Structurally guarantees the spec §4+ * invariant: `validateOAuthEndpointUrl` runs BEFORE every `fetchFn`, and a URL the+ * kernel rejects is never fetched.+ */+async function guardedFetchJson(+ url: string,+ field: string,+ deps: DiscoveryDeps+): Promise<{ ok: true; json: unknown } | { ok: false; error: DiscoveryError }> {+ const fetched = await guardedFetch(url, field, deps)+ if (!fetched.ok) return fetched+ const { response, finalUrl } = fetched+ if (!response.ok) {+ return {+ ok: false,+ error: {+ kind: 'fetch_failed',+ url: finalUrl,+ status: response.status,+ detail: `HTTP ${response.status}`,+ },+ }+ }+ try {+ return { ok: true, json: await response.json() }+ } catch (e) {+ return { ok: false, error: { kind: 'invalid_metadata', url: finalUrl, detail: errMessage(e) } }+ }+}++/**+ * Extract the `resource_metadata` hint from a `WWW-Authenticate` challenge+ * (RFC 9728 §5.1). The value is third-party data — the caller kernel-guards it+ * before fetching.+ */+export function parseResourceMetadataChallenge(+ header: string | null | undefined+): string | undefined {+ if (!header) return undefined+ const match = /resource_metadata\s*=\s*"([^"]+)"/i.exec(header)+ return match?.[1]+}++/**+ * Build the RFC 9728 §3.1 well-known PRM URL candidates for an MCP URL. Root form+ * for a resource without a path (Notion/Canva); path-suffixed for a resource with a+ * path (Sentry serves only this form; Linear serves both). Both are tried, in the+ * order most likely to hit for the given path.+ */+export function wellKnownPrmUrls(mcpUrl: URL): string[] {+ const path = mcpUrl.pathname.replace(/\/+$/, '')+ const root = `${mcpUrl.origin}/.well-known/oauth-protected-resource`+ if (path === '') return [root]+ // Path-suffixed inserts the well-known between host and path.+ return [`${root}${path}`, root]+}++/**+ * Build the RFC 8414 AS-metadata URL candidates for an authorization server URL.+ * `oauth-authorization-server` first, then the OIDC `openid-configuration` fallback.+ *+ * The two forms differ when the AS URL carries a path (RFC 8414 §3.1 vs §5):+ * `oauth-authorization-server` is path-INSERTED between host and path+ * (`{host}/.well-known/oauth-authorization-server{path}`), while OIDC+ * `openid-configuration` is path-APPENDED after the issuer including its path+ * (`{host}{path}/.well-known/openid-configuration`). For a path-less AS both+ * collapse to the root form.+ */+export function asMetadataUrls(asUrl: URL): string[] {+ const path = trimmedPath(asUrl)+ const oauthInserted =+ path === ''+ ? `${asUrl.origin}/.well-known/oauth-authorization-server`+ : `${asUrl.origin}/.well-known/oauth-authorization-server${path}`+ const oidcAppended =+ path === ''+ ? `${asUrl.origin}/.well-known/openid-configuration`+ : `${asUrl.origin}${path}/.well-known/openid-configuration`+ return [oauthInserted, oidcAppended]+}++function isRecord(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v)+}++/** Path with any trailing slashes stripped (so `/mcp/` and `/mcp` compare equal). */+function trimmedPath(url: URL): string {+ return url.pathname.replace(/\/+$/, '')+}++/**+ * RFC 9728 §3.3: the PRM `resource` must be the resource the metadata describes.+ * A hostile PRM could otherwise name a *different* resource and make us carry that+ * value as the RFC 8707 `resource`, minting tokens scoped to another destination.+ *+ * Consistency = same origin AND the MCP URL path is within the resource path: the+ * `resource` is either the bare origin (path empty — Notion `https://mcp.notion.com`+ * for MCP `…/mcp`) or a path prefix of the MCP URL at a segment boundary (Linear+ * `…/mcp` for MCP `…/mcp`). A cross-origin or unrelated-path `resource` is rejected.+ */+function isResourceConsistentWithMcpUrl(resource: string, mcpUrl: URL): boolean {+ let resourceUrl: URL+ try {+ resourceUrl = new URL(resource)+ } catch {+ return false+ }+ if (resourceUrl.origin !== mcpUrl.origin) return false+ const resPath = trimmedPath(resourceUrl)+ if (resPath === '') return true+ const mcpPath = trimmedPath(mcpUrl)+ return mcpPath === resPath || mcpPath.startsWith(`${resPath}/`)+}++/**+ * RFC 8414 §3.3: the AS metadata `issuer` must be identical to the authorization+ * server it was retrieved from. Otherwise a hostile AS response could hand us an+ * `issuer` we then trust for the RFC 9207 callback `iss` check. Compared as+ * origin+path with trailing slashes normalized.+ */+function isIssuerConsistentWithBase(issuer: string, base: URL): boolean {+ let issuerUrl: URL+ try {+ issuerUrl = new URL(issuer)+ } catch {+ return false+ }+ return issuerUrl.origin === base.origin && trimmedPath(issuerUrl) === trimmedPath(base)+}++/**+ * Resolve the Protected Resource Metadata for an MCP server URL: prefer the+ * `WWW-Authenticate: resource_metadata` hint from a 401 probe, then fall back to+ * the RFC 9728 well-known candidates. Every candidate URL (including the untrusted+ * hint) passes the kernel before it is fetched.+ */+async function resolvePrm(+ mcpUrl: string,+ deps: DiscoveryDeps+): Promise<{ ok: true; prm: ProtectedResourceMetadata } | { ok: false; error: DiscoveryError }> {+ let parsed: URL+ try {+ parsed = new URL(mcpUrl)+ } catch {+ return {+ ok: false,+ error: {+ kind: 'invalid_metadata',+ url: mcpUrl,+ detail: 'mcpUrl is not a valid absolute URL',+ },+ }+ }++ const candidates: string[] = []++ // Best-effort probe for the challenge hint. The probe URL is kernel-guarded+ // first; a probe failure is non-fatal — the well-known candidates follow.+ const probeGuard = await validateOAuthEndpointUrl(mcpUrl, 'mcpUrl', {+ resolveDns: deps.resolveDns,+ })+ if (probeGuard.length > 0) {+ return { ok: false, error: { kind: 'kernel_rejected', field: 'mcpUrl', errors: probeGuard } }+ }+ try {+ // `redirect:'manual'`: the probe URL is kernel-guarded above, but a 3xx from an+ // untrusted MCP server must NOT be auto-followed to an internal host. A redirect+ // simply yields no 401 hint here — the kernel-guarded well-known candidates below+ // are the fallback.+ const probe = await deps.fetchFn(mcpUrl, {+ method: 'GET',+ redirect: 'manual',+ signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),+ })+ if (probe.status === 401) {+ const hint = parseResourceMetadataChallenge(probe.headers.get('www-authenticate'))+ if (hint) candidates.push(hint)+ }+ } catch {+ // Probe failure is expected for some servers; fall back to well-known.+ }++ for (const wk of wellKnownPrmUrls(parsed)) {+ if (!candidates.includes(wk)) candidates.push(wk)+ }++ let lastError: DiscoveryError = {+ kind: 'fetch_failed',+ url: mcpUrl,+ detail: 'no protected-resource-metadata candidate resolved',+ }+ for (const url of candidates) {+ const fetched = await guardedFetchJson(url, 'prmUrl', deps)+ if (!fetched.ok) {+ lastError = fetched.error+ continue+ }+ if (!isRecord(fetched.json) || typeof fetched.json.resource !== 'string') {+ lastError = { kind: 'invalid_metadata', url, detail: 'PRM missing string "resource"' }+ continue+ }+ // RFC 9728 §3.3: the advertised `resource` must describe the MCP URL we asked+ // about. A mismatch (hostile hint PRM naming another destination) is dropped and+ // the next candidate — a legitimate well-known — is tried.+ if (!isResourceConsistentWithMcpUrl(fetched.json.resource, parsed)) {+ lastError = {+ kind: 'prm_resource_mismatch',+ url,+ detail: `PRM resource "${fetched.json.resource}" is not consistent with MCP URL "${mcpUrl}"`,+ }+ continue+ }+ return { ok: true, prm: fetched.json as ProtectedResourceMetadata }+ }+ return { ok: false, error: lastError }+}++/**+ * Full RFC 9728 → 8414 discovery for a remote MCP server URL. Returns the pinned+ * endpoints, `resource` (RFC 8707), issuer/`iss` handling (RFC 9207), the+ * registration mode (D-3) and transport quirks (D-8). Fail-closed if the AS does+ * not advertise S256 (invariant 3).+ *+ * `hasPreRegisteredClient` reflects operator config (a pre-registered Secret),+ * defaulting to false — the C1 pilots (Notion/Canva/Linear/Sentry) have none and+ * resolve to CIMD.+ */+export async function discoverRemoteOAuth(+ mcpUrl: string,+ deps: DiscoveryDeps,+ opts: { hasPreRegisteredClient?: boolean } = {}+): Promise<DiscoveryOutcome> {+ const log = (deps.logger ?? rootLogger).child({ module: 'oauth-discovery' })++ const prmResult = await resolvePrm(mcpUrl, deps)+ if (!prmResult.ok) {+ log.warn({ discovery: prmResult.error.kind }, 'protected resource metadata discovery failed')+ return { ok: false, error: prmResult.error }+ }+ const prm = prmResult.prm++ const asBase = prm.authorization_servers?.[0]+ if (typeof asBase !== 'string' || asBase.length === 0) {+ return {+ ok: false,+ error: { kind: 'no_authorization_server', detail: 'PRM has no authorization_servers[0]' },+ }+ }++ let asBaseUrl: URL+ try {+ asBaseUrl = new URL(asBase)+ } catch {+ return {+ ok: false,+ error: {+ kind: 'invalid_metadata',+ url: asBase,+ detail: 'authorization_servers[0] is not a valid URL',+ },+ }+ }++ let as: AuthorizationServerMetadata | undefined+ let lastAsError: DiscoveryError = {+ kind: 'fetch_failed',+ url: asBase,+ detail: 'no AS-metadata candidate resolved',+ }+ for (const url of asMetadataUrls(asBaseUrl)) {+ const fetched = await guardedFetchJson(url, 'asMetadataUrl', deps)+ if (!fetched.ok) {+ lastAsError = fetched.error+ continue+ }+ if (!isRecord(fetched.json)) {+ lastAsError = { kind: 'invalid_metadata', url, detail: 'AS metadata is not an object' }+ continue+ }+ const candidate = fetched.json as AuthorizationServerMetadata+ if (+ typeof candidate.issuer !== 'string' ||+ typeof candidate.authorization_endpoint !== 'string' ||+ typeof candidate.token_endpoint !== 'string'+ ) {+ lastAsError = {+ kind: 'invalid_metadata',+ url,+ detail: 'AS metadata missing issuer/authorization_endpoint/token_endpoint',+ }+ continue+ }+ // RFC 8414 §3.3: `issuer` must match the AS we fetched the metadata from. The+ // `issuer` feeds the RFC 9207 callback `iss` check, so a hostile mismatch is+ // rejected here rather than trusted downstream.+ if (!isIssuerConsistentWithBase(candidate.issuer, asBaseUrl)) {+ lastAsError = {+ kind: 'issuer_mismatch',+ detail: `AS issuer "${candidate.issuer}" does not match authorization server "${asBase}"`,+ }+ continue+ }+ as = candidate+ break+ }+ if (!as) {+ log.warn({ discovery: lastAsError.kind }, 'authorization server metadata discovery failed')+ return { ok: false, error: lastAsError }+ }++ // Invariant 3: fail closed unless S256 is advertised (ignore `plain`).+ const challengeMethods = as.code_challenge_methods_supported+ if (!Array.isArray(challengeMethods) || !challengeMethods.includes('S256')) {+ return {+ ok: false,+ error: {+ kind: 'no_s256',+ detail: 'AS does not advertise code_challenge_methods_supported=S256',+ },+ }+ }++ // Kernel-guard every endpoint BEFORE pinning it (spec §4). These are validated+ // (DNS-resolved) but not fetched here — authorize is a browser redirect and+ // token is used at exchange time.+ const endpointChecks: Array<{ field: string; url: string }> = [+ { field: 'spec.oauth.authorizationEndpoint', url: as.authorization_endpoint },+ { field: 'spec.oauth.tokenEndpoint', url: as.token_endpoint },+ ]+ if (typeof as.registration_endpoint === 'string') {+ endpointChecks.push({ field: 'spec.oauth.registrationEndpoint', url: as.registration_endpoint })+ }+ for (const check of endpointChecks) {+ const errors = await validateOAuthEndpointUrl(check.url, check.field, {+ resolveDns: deps.resolveDns,+ })+ if (errors.length > 0) {+ return { ok: false, error: { kind: 'kernel_rejected', field: check.field, errors } }+ }+ }++ const registrationMode = selectRegistrationMode({+ hasPreRegisteredClient: opts.hasPreRegisteredClient ?? false,+ cimdSupported: as.client_id_metadata_document_supported === true,+ tokenEndpointAuthMethods: as.token_endpoint_auth_methods_supported ?? [],+ hasRegistrationEndpoint: typeof as.registration_endpoint === 'string',+ })++ return {+ ok: true,+ result: {+ prm,+ as,+ resource: prm.resource,+ issuer: as.issuer,+ issForCallback:+ as.authorization_response_iss_parameter_supported === true ? as.issuer : undefined,+ endpoints: {+ authorization: as.authorization_endpoint,+ token: as.token_endpoint,+ registration:+ typeof as.registration_endpoint === 'string' ? as.registration_endpoint : undefined,+ },+ registrationMode,+ quirks: deriveQuirks(as, prm),+ },+ }+}diff --git a/control-api/src/oauth/providers.ts b/control-api/src/oauth/providers.tsindex 53a5cbc21..07469939e 100644--- a/control-api/src/oauth/providers.ts+++ b/control-api/src/oauth/providers.ts@@ -600,3 +600,47 @@ export const KNOWN_OAUTH_PROVIDERS: ReadonlySet<OAuthProvider> = new Set(export function isKnownOAuthProvider(value: string): value is OAuthProvider {return KNOWN_OAUTH_PROVIDERS.has(value as OAuthProvider)}++// ─── Generic public token client for the remote MCP-OAuth lane (D-10 §3) ────+//+// The remote lane speaks OAuth to an endpoint discovered at install (not one of+// the 8 baked adapters), as a PUBLIC client (CIMD/DCR-public + PKCE, no secret).+// These wrappers reuse the standard form-encoded builders and append the RFC 8707+// `resource` parameter WITHOUT touching `standardTokenRequest`/`standardRefreshRequest`,+// so the 8 baked adapters stay byte-identical (verified by the T1 golden). They are+// wrappers, not new adapters: nothing is added to `OAuthProvider`/`ADAPTERS`/+// `KNOWN_OAUTH_PROVIDERS`.++/** Append the RFC 8707 `resource` param to an already form-encoded body. */+function appendResource(request: TokenRequest, resource?: string): TokenRequest {+ if (!resource) return request+ return { ...request, body: `${request.body}&resource=${encodeURIComponent(resource)}` }+}++/**+ * Build a remote token-exchange POST against a discovered `tokenEndpoint`, as a+ * public client (omits `client_secret` when `input.clientSecret` is absent — the+ * standard builder already drops it) and appending RFC 8707 `resource` when given.+ */+export function buildRemoteTokenRequest(+ tokenEndpoint: string,+ input: TokenExchangeInput,+ resource?: string+): TokenRequest {+ return appendResource(standardTokenRequest(tokenEndpoint, input), resource)+}++/**+ * Build a remote refresh POST against a discovered `tokenEndpoint`, public client+ * (omits `client_secret` when absent), appending RFC 8707 `resource` when given.+ */+export function buildRemoteRefreshRequest(+ tokenEndpoint: string,+ input: RefreshTokenInput,+ resource?: string+): TokenRequest {+ return appendResource(standardRefreshRequest(tokenEndpoint, input), resource)+}++/** Remote token responses are standard OAuth2 — reuse the baked parser. */+export const parseRemoteTokenResponse = parseStandardOAuth2diff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.tsindex cffec340d..2e0618d13 100644--- a/control-api/src/routes/external/oauthCallback.ts+++ b/control-api/src/routes/external/oauthCallback.ts@@ -172,6 +172,20 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {return router}+/**+ * Normalize the configured public callback base URL into a bare origin (trailing+ * slashes stripped), or `null` when none is configured. This is the SAME origin+ * derivation `buildPublicCallbackUrl` uses for its configured branch; the CIMD+ * document (`oauth/cimd.ts`) reuses it so the served `client_id` / `redirect_uris`+ * share a byte-identical origin with the callback redirect. Unlike the callback,+ * CIMD callers must NOT fall back to the request Host (an AS would see the+ * internal proxy Host), so this returns `null` for them to fail closed on.+ */+export function normalizeConfiguredOrigin(configuredBaseUrl?: string): string | null {+ if (!configuredBaseUrl || configuredBaseUrl.length === 0) return null+ return configuredBaseUrl.replace(/\/+$/, '')+}+export function buildPublicCallbackUrl(req: { protocol: string; get: (h: string) => string | undefined },oauthClientId: string,@@ -188,9 +202,8 @@ export function buildPublicCallbackUrl(// public base URL (CONTROL_API_OAUTH_CALLBACK_BASE_URL). Fall back to the// request Host for local/dev where none is set.const origin =- configuredBaseUrl && configuredBaseUrl.length > 0- ? configuredBaseUrl.replace(/\/+$/, '')- : `${req.protocol}://${req.get('host') ?? 'localhost'}`+ normalizeConfiguredOrigin(configuredBaseUrl) ??+ `${req.protocol}://${req.get('host') ?? 'localhost'}`return `${origin}/api/v1/oauth-callback/${encodeURIComponent(oauthClientId)}`}diff --git a/control-api/test/fixtures/remoteOAuthDiscovery.ts b/control-api/test/fixtures/remoteOAuthDiscovery.tsnew file mode 100644index 000000000..513685305--- /dev/null+++ b/control-api/test/fixtures/remoteOAuthDiscovery.ts@@ -0,0 +1,164 @@+/**+ * T1 fixtures — remote MCP-OAuth discovery (spec 19 §7 T1).+ *+ * These are the EXACT bytes returned by the real production servers on 2026-09-20+ * (curl, `Accept: application/json`), copied verbatim from the live probe. They are+ * NOT hand-authored — a PRM/AS shape the real server cannot emit would leave the+ * discovery code unreachable. Each entry cites its probe URL. Parsing the raw string+ * (mirroring `Response.json()`) is what the discovery client consumes.+ *+ * Probe method — the discovery client probes the MCP URL with GET; re-sondeo+ * 2026-09-20 confirmed the four pilots emit the same `WWW-Authenticate:+ * resource_metadata` challenge on GET as on POST (all pointing at the+ * path-suffixed well-known), so the GET probe is derived from the real producer,+ * not invented. Real GET responses (2026-09-20):+ * GET https://mcp.notion.com/mcp → 401 www-authenticate: Bearer realm="OAuth", resource_metadata="https://mcp.notion.com/.well-known/oauth-protected-resource/mcp", error="invalid_token", …+ * GET https://mcp.linear.app/mcp → 401 www-authenticate: Bearer realm="OAuth", resource_metadata="https://mcp.linear.app/.well-known/oauth-protected-resource/mcp", error="invalid_token", …+ * GET https://mcp.sentry.dev/mcp → 401 www-authenticate: Bearer realm="OAuth", resource_metadata="https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp"+ * GET https://mcp.canva.com/mcp → 401 www-authenticate: Bearer realm="OAuth", resource_metadata="https://mcp.canva.com/.well-known/oauth-protected-resource/mcp", error="invalid_token", …+ * (POST initialize returns the identical header on all four.)+ *+ * Provenance: scratchpad/c1-fixtures-provenance.md (sondeo en vivo 2026-09-20,+ * sección "EVIDENCIA GET").+ */++// ─── Notion (resource base sin path) ────────────────────────────────────────+// PRM: GET https://mcp.notion.com/.well-known/oauth-protected-resource → 200+export const NOTION_PRM_JSON =+ '{"resource":"https://mcp.notion.com","authorization_servers":["https://mcp.notion.com"],"scopes_supported":["default"],"bearer_methods_supported":["header"],"resource_name":"Notion MCP (Beta)"}'+// AS: GET https://mcp.notion.com/.well-known/oauth-authorization-server → 200+export const NOTION_AS_JSON =+ '{"issuer":"https://mcp.notion.com","authorization_endpoint":"https://mcp.notion.com/authorize","token_endpoint":"https://mcp.notion.com/token","registration_endpoint":"https://mcp.notion.com/register","scopes_supported":["default"],"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:jwt-bearer"],"authorization_grant_profiles_supported":["urn:ietf:params:oauth:grant-profile:id-jag"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.notion.com/token","code_challenge_methods_supported":["plain","S256"],"client_id_metadata_document_supported":true,"introspection_endpoint":"https://mcp.notion.com/introspect","introspection_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"]}'++// ─── Linear (resource con path /mcp; PRM en root Y path-suffixed) ───────────+// PRM (root): GET https://mcp.linear.app/.well-known/oauth-protected-resource → 200+export const LINEAR_PRM_JSON =+ '{"resource":"https://mcp.linear.app/mcp","authorization_servers":["https://mcp.linear.app"],"scopes_supported":["read","write"],"bearer_methods_supported":["header"]}'+// AS: GET https://mcp.linear.app/.well-known/oauth-authorization-server → 200+export const LINEAR_AS_JSON =+ '{"issuer":"https://mcp.linear.app","authorization_endpoint":"https://mcp.linear.app/authorize","token_endpoint":"https://mcp.linear.app/token","registration_endpoint":"https://mcp.linear.app/register","scopes_supported":["read","write","openid","email"],"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:jwt-bearer"],"authorization_grant_profiles_supported":["urn:ietf:params:oauth:grant-profile:id-jag"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.linear.app/token","code_challenge_methods_supported":["S256"],"client_id_metadata_document_supported":true,"resource":"https://mcp.linear.app/mcp","resource_metadata":"https://mcp.linear.app/.well-known/oauth-protected-resource/mcp"}'++// ─── Sentry (PRM SOLO path-suffixed; root → 404; 401 trae WWW-Authenticate) ─+// 401 header emitted identically on GET and POST of https://mcp.sentry.dev/mcp+// (the client probes with GET; POST initialize returns the same header).+export const SENTRY_WWW_AUTHENTICATE =+ 'Bearer realm="OAuth", resource_metadata="https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp"'+// PRM: GET https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp → 200+export const SENTRY_PRM_JSON =+ '{"resource":"https://mcp.sentry.dev/mcp","authorization_servers":["https://mcp.sentry.dev"],"scopes_supported":["org:read","project:write","team:write","event:write"],"bearer_methods_supported":["header"]}'+// AS: GET https://mcp.sentry.dev/.well-known/oauth-authorization-server → 200+export const SENTRY_AS_JSON =+ '{"issuer":"https://mcp.sentry.dev","authorization_endpoint":"https://mcp.sentry.dev/oauth/authorize","token_endpoint":"https://mcp.sentry.dev/oauth/token","registration_endpoint":"https://mcp.sentry.dev/oauth/register","scopes_supported":["org:read","project:write","team:write","event:write"],"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.sentry.dev/oauth/token","code_challenge_methods_supported":["S256"],"authorization_response_iss_parameter_supported":true,"client_id_metadata_document_supported":true}'++// ─── Canva (resource base sin path) ─────────────────────────────────────────+// PRM: GET https://mcp.canva.com/.well-known/oauth-protected-resource → 200+export const CANVA_PRM_JSON =+ '{"resource":"https://mcp.canva.com","authorization_servers":["https://mcp.canva.com"],"scopes_supported":["profile:read","design:meta:read","design:content:write","design:content:read","folder:read","folder:write","brandtemplate:content:read","brandtemplate:meta:read","brandtemplate:content:write","comment:write","comment:read","asset:read","asset:write","brandkit:read","help:answers:read","help:answers:write"],"bearer_methods_supported":["header"]}'+// AS: GET https://mcp.canva.com/.well-known/oauth-authorization-server → 200+export const CANVA_AS_JSON =+ '{"issuer":"https://mcp.canva.com","authorization_endpoint":"https://mcp.canva.com/authorize","token_endpoint":"https://mcp.canva.com/token","registration_endpoint":"https://mcp.canva.com/register","response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:jwt-bearer"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.canva.com/token","code_challenge_methods_supported":["plain","S256"],"client_id_metadata_document_supported":true,"authorization_grant_profiles_supported":["urn:ietf:params:oauth:grant-profile:id-jag"]}'++export interface PilotFixture {+ name: string+ /** MCP server URL discovery is entered with. */+ mcpUrl: string+ prm: { url: string; json: string }+ /** Additional well-known/PRM URLs the server 404s on (for candidate fallback). */+ prmNotFound?: string[]+ /** WWW-Authenticate header the 401 probe of `mcpUrl` returns, if any. */+ wwwAuthenticate?: string+ as: { url: string; json: string }+}++/** The 4 CIMD-ready pilots, keyed by the real well-known URLs they serve. */+export const PILOTS: Record<'notion' | 'linear' | 'sentry' | 'canva', PilotFixture> = {+ notion: {+ name: 'notion',+ mcpUrl: 'https://mcp.notion.com/mcp',+ // Notion serves PRM only at root; the path-suffixed candidate 404s.+ prm: {+ url: 'https://mcp.notion.com/.well-known/oauth-protected-resource',+ json: NOTION_PRM_JSON,+ },+ prmNotFound: ['https://mcp.notion.com/.well-known/oauth-protected-resource/mcp'],+ as: {+ url: 'https://mcp.notion.com/.well-known/oauth-authorization-server',+ json: NOTION_AS_JSON,+ },+ },+ linear: {+ name: 'linear',+ mcpUrl: 'https://mcp.linear.app/mcp',+ prm: {+ url: 'https://mcp.linear.app/.well-known/oauth-protected-resource/mcp',+ json: LINEAR_PRM_JSON,+ },+ as: {+ url: 'https://mcp.linear.app/.well-known/oauth-authorization-server',+ json: LINEAR_AS_JSON,+ },+ },+ sentry: {+ name: 'sentry',+ mcpUrl: 'https://mcp.sentry.dev/mcp',+ wwwAuthenticate: SENTRY_WWW_AUTHENTICATE,+ prm: {+ url: 'https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp',+ json: SENTRY_PRM_JSON,+ },+ // Sentry root well-known 404s — only the path-suffixed form (or the hint) works.+ prmNotFound: ['https://mcp.sentry.dev/.well-known/oauth-protected-resource'],+ as: {+ url: 'https://mcp.sentry.dev/.well-known/oauth-authorization-server',+ json: SENTRY_AS_JSON,+ },+ },+ canva: {+ name: 'canva',+ mcpUrl: 'https://mcp.canva.com/mcp',+ prm: {+ url: 'https://mcp.canva.com/.well-known/oauth-protected-resource',+ json: CANVA_PRM_JSON,+ },+ prmNotFound: ['https://mcp.canva.com/.well-known/oauth-protected-resource/mcp'],+ as: {+ url: 'https://mcp.canva.com/.well-known/oauth-authorization-server',+ json: CANVA_AS_JSON,+ },+ },+}++/**+ * Build a `fetch`-shaped mock from a pilot fixture: a 401 (with WWW-Authenticate)+ * on the MCP probe when the fixture has a hint, 200+JSON on the served well-known+ * URLs, and 404 on the URLs the real server does not serve. Mirrors the real HTTP+ * responses so the discovery code path is exercised, not a hand-invented one.+ */+export function makeDiscoveryFetch(pilot: PilotFixture): typeof fetch {+ const jsonByUrl = new Map<string, string>([+ [pilot.prm.url, pilot.prm.json],+ [pilot.as.url, pilot.as.json],+ ])+ const notFound = new Set(pilot.prmNotFound ?? [])+ const fn = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {+ const url = typeof input === 'string' ? input : input.toString()+ // MCP probe (GET) → 401 with the challenge header when the fixture has one.+ if (url === pilot.mcpUrl && (init?.method ?? 'GET') === 'GET') {+ if (pilot.wwwAuthenticate) {+ return new Response(null, {+ status: 401,+ headers: { 'www-authenticate': pilot.wwwAuthenticate },+ })+ }+ // No challenge advertised — probe returns a plain 401 with no hint.+ return new Response(null, { status: 401 })+ }+ const body = jsonByUrl.get(url)+ if (body !== undefined) {+ return new Response(body, { status: 200, headers: { 'content-type': 'application/json' } })+ }+ if (notFound.has(url)) return new Response('not found', { status: 404 })+ return new Response('unexpected url', { status: 404 })+ }+ return fn as unknown as typeof fetch+}diff --git a/control-api/test/oauth.cimd.test.ts b/control-api/test/oauth.cimd.test.tsnew file mode 100644index 000000000..c452fcf64--- /dev/null+++ b/control-api/test/oauth.cimd.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from 'vitest'+import express from 'express'+import request from 'supertest'+import { CIMD_ROUTE_PATH, buildCimdDocument, createCimdRouter } from '../src/oauth/cimd.js'++/**+ * CIMD document (spec 19 §5 C1, D-9 / S-6). Served read-only under /api/v1; the+ * `client_id` is byte-identical to the document's own URL (SEP-991). `getBaseUrl`+ * is injected so both the served document and the fail-closed 503 are exercised+ * without mutating the process config singleton.+ */+const ORIGIN = 'https://control.example.com'++function appWith(baseUrl: string) {+ const app = express()+ app.use('/api/v1', createCimdRouter({ getBaseUrl: () => baseUrl }))+ return app+}++describe('buildCimdDocument (frozen identity, S-6)', () => {+ it('client_id equals the document URL; redirect_uris carries the stable remote segment', () => {+ const doc = buildCimdDocument(ORIGIN)+ expect(doc.client_id).toBe('https://control.example.com/api/v1/.well-known/evenfire-mcp-client')+ expect(doc.redirect_uris).toEqual(['https://control.example.com/api/v1/oauth-callback/remote'])+ expect(doc.token_endpoint_auth_method).toBe('none')+ expect(doc.grant_types).toEqual(['authorization_code', 'refresh_token'])+ expect(doc.response_types).toEqual(['code'])+ expect(doc.application_type).toBe('web')+ })++ it('is frozen — no runtime mutation of the served identity', () => {+ const doc = buildCimdDocument(ORIGIN)+ expect(Object.isFrozen(doc)).toBe(true)+ expect(() => {+ // @ts-expect-error deliberate mutation attempt+ doc.client_id = 'https://evil.example.com'+ }).toThrow()+ expect(doc.client_id).toBe('https://control.example.com/api/v1/.well-known/evenfire-mcp-client')+ })+})++describe('createCimdRouter', () => {+ it('serves 200 + application/json with the frozen document', async () => {+ const res = await request(appWith(ORIGIN)).get('/api/v1/.well-known/evenfire-mcp-client')+ expect(res.status).toBe(200)+ expect(res.headers['content-type']).toMatch(/application\/json/)+ expect(res.headers['cache-control']).toMatch(/max-age=300/)+ expect(res.body).toEqual(buildCimdDocument(ORIGIN))+ })++ it('client_id is byte-identical to the fetch URL', async () => {+ const res = await request(appWith(ORIGIN)).get('/api/v1/.well-known/evenfire-mcp-client')+ expect(res.body.client_id).toBe(`${ORIGIN}/api/v1/.well-known/evenfire-mcp-client`)+ })++ it('two GETs return byte-identical bodies (S-6, no runtime drift)', async () => {+ const app = appWith(ORIGIN)+ const a = await request(app).get('/api/v1/.well-known/evenfire-mcp-client')+ const b = await request(app).get('/api/v1/.well-known/evenfire-mcp-client')+ expect(a.text).toBe(b.text)+ })++ it('fails closed with 503 when no base URL is configured', async () => {+ const res = await request(appWith('')).get('/api/v1/.well-known/evenfire-mcp-client')+ expect(res.status).toBe(503)+ expect(res.body).toEqual({ error: 'cimd_base_url_unconfigured' })+ })++ it('has NO write path — POST/PUT/DELETE are not routed (404/405, never mutate)', async () => {+ const app = appWith(ORIGIN)+ for (const method of ['post', 'put', 'delete', 'patch'] as const) {+ const res = await request(app)[method]('/api/v1/.well-known/evenfire-mcp-client')+ expect(res.status).not.toBe(200)+ }+ })++ it('normalizes a trailing slash in the configured base URL', async () => {+ const res = await request(appWith('https://control.example.com/')).get(+ '/api/v1/.well-known/evenfire-mcp-client'+ )+ expect(res.body.client_id).toBe(+ 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'+ )+ })++ // N1: `CIMD_PUBLIC_PATH` embeds the `/api/v1` prefix that app.ts fixes with+ // `app.use('/api/v1', api)` + `api.use(createCimdRouter())`. If either side+ // drifts, the served `client_id` points at a path that is no longer routable.+ // This ties the served `client_id` path to the real mount: whatever path the+ // document advertises MUST resolve back to the document under the same mount.+ it("the served client_id path is routable under the real '/api/v1' mount", async () => {+ const app = express()+ // Mirror app.ts exactly: nested router mounted under the '/api/v1' prefix.+ const api = express.Router()+ api.use(createCimdRouter({ getBaseUrl: () => ORIGIN }))+ app.use('/api/v1', api)++ const doc = await request(app).get('/api/v1/.well-known/evenfire-mcp-client')+ expect(doc.status).toBe(200)++ // Drive the second GET from the advertised client_id, not a hardcoded path.+ const clientIdPath = new URL(doc.body.client_id).pathname+ expect(clientIdPath).toBe(`/api/v1${CIMD_ROUTE_PATH}`)+ const viaClientId = await request(app).get(clientIdPath)+ expect(viaClientId.status).toBe(200)+ expect(viaClientId.body).toEqual(doc.body)+ })+})diff --git a/control-api/test/oauth.discovery.properties.test.ts b/control-api/test/oauth.discovery.properties.test.tsnew file mode 100644index 000000000..1c92718ae--- /dev/null+++ b/control-api/test/oauth.discovery.properties.test.ts@@ -0,0 +1,153 @@+import { describe, expect, it } from 'vitest'+import fc from 'fast-check'+import {+ type AuthorizationServerMetadata,+ type ProtectedResourceMetadata,+ type RegistrationMode,+ deriveQuirks,+ selectRegistrationMode,+} from '../src/oauth/discovery.js'+import { PILOTS } from './fixtures/remoteOAuthDiscovery.js'++/**+ * T2 property-based coverage for the two pure decision functions of discovery.+ * The classic industry bug is inverting the registration order (D-3); the fuzz+ * blinds that across every combination a human enumeration misses.+ */++// Reference implementation of the normative order, kept deliberately independent+// of the production one so the property catches a reordering in either direction.+function expectedMode(input: {+ hasPreRegisteredClient: boolean+ cimdSupported: boolean+ tokenEndpointAuthMethods: string[]+ hasRegistrationEndpoint: boolean+}): RegistrationMode {+ if (input.hasPreRegisteredClient) return 'pre-registered'+ if (input.cimdSupported && input.tokenEndpointAuthMethods.includes('none')) return 'cimd'+ if (input.hasRegistrationEndpoint) return 'dcr'+ return 'manual'+}++const authMethodArb = fc.subarray(['none', 'client_secret_basic', 'client_secret_post'])++describe('selectRegistrationMode — order pre-reg > CIMD > DCR > manual (T2)', () => {+ it('always returns the first applicable mode in the fixed order', () => {+ fc.assert(+ fc.property(+ fc.boolean(),+ fc.boolean(),+ authMethodArb,+ fc.boolean(),+ (+ hasPreRegisteredClient,+ cimdSupported,+ tokenEndpointAuthMethods,+ hasRegistrationEndpoint+ ) => {+ const input = {+ hasPreRegisteredClient,+ cimdSupported,+ tokenEndpointAuthMethods,+ hasRegistrationEndpoint,+ }+ expect(selectRegistrationMode(input)).toBe(expectedMode(input))+ }+ )+ )+ })++ it('pre-registered wins over everything else', () => {+ fc.assert(+ fc.property(fc.boolean(), authMethodArb, fc.boolean(), (cimd, methods, reg) => {+ expect(+ selectRegistrationMode({+ hasPreRegisteredClient: true,+ cimdSupported: cimd,+ tokenEndpointAuthMethods: methods,+ hasRegistrationEndpoint: reg,+ })+ ).toBe('pre-registered')+ })+ )+ })++ it('CIMD requires BOTH cimdSupported AND `none` (never one alone)', () => {+ // cimdSupported without `none` → not cimd.+ expect(+ selectRegistrationMode({+ hasPreRegisteredClient: false,+ cimdSupported: true,+ tokenEndpointAuthMethods: ['client_secret_post'],+ hasRegistrationEndpoint: true,+ })+ ).toBe('dcr')+ // `none` without cimdSupported → not cimd.+ expect(+ selectRegistrationMode({+ hasPreRegisteredClient: false,+ cimdSupported: false,+ tokenEndpointAuthMethods: ['none'],+ hasRegistrationEndpoint: true,+ })+ ).toBe('dcr')+ })++ it('the 4 real pilots all select CIMD', () => {+ for (const key of ['notion', 'linear', 'sentry', 'canva'] as const) {+ const as = JSON.parse(PILOTS[key].as.json) as AuthorizationServerMetadata+ expect(+ selectRegistrationMode({+ hasPreRegisteredClient: false,+ cimdSupported: as.client_id_metadata_document_supported === true,+ tokenEndpointAuthMethods: as.token_endpoint_auth_methods_supported ?? [],+ hasRegistrationEndpoint: typeof as.registration_endpoint === 'string',+ })+ ).toBe('cimd')+ }+ })+})++describe('deriveQuirks (D-8, T2)', () => {+ const asWith = (grants?: string[]): AuthorizationServerMetadata =>+ ({+ issuer: 'https://as.example.com',+ authorization_endpoint: 'https://as.example.com/authorize',+ token_endpoint: 'https://as.example.com/token',+ ...(grants ? { grant_types_supported: grants } : {}),+ }) as AuthorizationServerMetadata+ const prmWith = (methods?: string[]): ProtectedResourceMetadata => ({+ resource: 'https://r.example.com',+ ...(methods ? { bearer_methods_supported: methods } : {}),+ })++ it('supportsRefresh is fail-closed: true only when refresh_token is advertised', () => {+ fc.assert(+ fc.property(+ fc.option(fc.subarray(['authorization_code', 'refresh_token']), { nil: undefined }),+ grants => {+ const { supportsRefresh } = deriveQuirks(asWith(grants), prmWith())+ expect(supportsRefresh).toBe((grants ?? []).includes('refresh_token'))+ }+ )+ )+ })++ it('bearerInBody: true only for ["body"] without "header"', () => {+ fc.assert(+ fc.property(fc.option(fc.subarray(['header', 'body']), { nil: undefined }), methods => {+ const { bearerInBody } = deriveQuirks(asWith(), prmWith(methods))+ const m = methods ?? []+ expect(bearerInBody).toBe(m.includes('body') && !m.includes('header'))+ })+ )+ })++ it('the 4 real pilots are header-bearer with refresh', () => {+ for (const key of ['notion', 'linear', 'sentry', 'canva'] as const) {+ const as = JSON.parse(PILOTS[key].as.json) as AuthorizationServerMetadata+ const prm = JSON.parse(PILOTS[key].prm.json) as ProtectedResourceMetadata+ expect(deriveQuirks(as, prm)).toEqual({ bearerInBody: false, supportsRefresh: true })+ }+ })+})diff --git a/control-api/test/oauth.discovery.test.ts b/control-api/test/oauth.discovery.test.tsnew file mode 100644index 000000000..f7f93bb8a--- /dev/null+++ b/control-api/test/oauth.discovery.test.ts@@ -0,0 +1,371 @@+import { describe, expect, it, vi } from 'vitest'+import {+ type DiscoveryDeps,+ asMetadataUrls,+ discoverRemoteOAuth,+ parseResourceMetadataChallenge,+ wellKnownPrmUrls,+} from '../src/oauth/discovery.js'+import { PILOTS, makeDiscoveryFetch } from './fixtures/remoteOAuthDiscovery.js'++/**+ * Discovery client (spec 19 §4/§5 C1). Fixtures are the real 2026-09-20 probe+ * bytes (T1). `resolveDns` is injected so the kernel runs without a cluster.+ */+const PUBLIC_IP = ['93.184.216.34']+const publicDns = () => vi.fn(async () => PUBLIC_IP)++function deps(pilotFetch: typeof fetch, resolveDns = publicDns()): DiscoveryDeps {+ return { fetchFn: pilotFetch, resolveDns }+}++describe('discoverRemoteOAuth — 4 CIMD pilots (T1 real fixtures)', () => {+ for (const key of ['notion', 'linear', 'sentry', 'canva'] as const) {+ const pilot = PILOTS[key]+ it(`${key}: resolves PRM→AS, selects CIMD, pins endpoints`, async () => {+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, deps(makeDiscoveryFetch(pilot)))+ expect(outcome.ok).toBe(true)+ if (!outcome.ok) return+ const r = outcome.result+ // D-3: all 4 pilots resolve to CIMD (cimd_supported + `none`).+ expect(r.registrationMode).toBe('cimd')+ // RFC 8707: resource is the PRM resource verbatim.+ expect(r.resource).toBe(JSON.parse(pilot.prm.json).resource)+ // Endpoints pinned from the AS metadata.+ const as = JSON.parse(pilot.as.json)+ expect(r.endpoints.token).toBe(as.token_endpoint)+ expect(r.endpoints.authorization).toBe(as.authorization_endpoint)+ expect(r.issuer).toBe(as.issuer)+ // All 4 advertise refresh_token → supportsRefresh true; none is bearer-in-body.+ expect(r.quirks.supportsRefresh).toBe(true)+ expect(r.quirks.bearerInBody).toBe(false)+ })+ }++ it('sentry: exposes issForCallback (RFC 9207); others do not', async () => {+ const sentry = await discoverRemoteOAuth(+ PILOTS.sentry.mcpUrl,+ deps(makeDiscoveryFetch(PILOTS.sentry))+ )+ expect(sentry.ok && sentry.result.issForCallback).toBe('https://mcp.sentry.dev')++ const notion = await discoverRemoteOAuth(+ PILOTS.notion.mcpUrl,+ deps(makeDiscoveryFetch(PILOTS.notion))+ )+ expect(notion.ok && notion.result.issForCallback).toBeUndefined()+ })++ it('sentry: uses the WWW-Authenticate resource_metadata hint (path-suffixed PRM)', async () => {+ // Sentry root well-known 404s; discovery must follow the 401 hint.+ const outcome = await discoverRemoteOAuth(+ PILOTS.sentry.mcpUrl,+ deps(makeDiscoveryFetch(PILOTS.sentry))+ )+ expect(outcome.ok).toBe(true)+ if (outcome.ok) expect(outcome.result.prm.resource).toBe('https://mcp.sentry.dev/mcp')+ })+})++describe('discoverRemoteOAuth — kernel §4 before every fetch (invariant 2, T5)', () => {+ it('calls the kernel (resolveDns) before fetching each URL', async () => {+ const order: string[] = []+ const resolveDns = vi.fn(async (host: string) => {+ order.push(`dns:${host}`)+ return PUBLIC_IP+ })+ const base = makeDiscoveryFetch(PILOTS.notion)+ const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ order.push(`fetch:${typeof input === 'string' ? input : input.toString()}`)+ return base(input, init)+ }) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth(PILOTS.notion.mcpUrl, { fetchFn, resolveDns })+ expect(outcome.ok).toBe(true)+ // Every fetch is immediately preceded by a DNS resolve of its host — no fetch+ // ever appears before its guarding resolve.+ order+ .filter(e => e.startsWith('fetch:'))+ .forEach(fetchEntry => {+ const host = new URL(fetchEntry.slice('fetch:'.length)).hostname+ const fetchIdx = order.indexOf(fetchEntry)+ const dnsIdx = order.lastIndexOf(`dns:${host}`, fetchIdx)+ expect(dnsIdx).toBeGreaterThanOrEqual(0)+ expect(dnsIdx).toBeLessThan(fetchIdx)+ })+ })++ it('rejects a PRM host resolving to a private IP WITHOUT fetching it', async () => {+ const resolveDns = vi.fn(async () => ['10.0.0.5'])+ const fetchFn = vi.fn(+ async () => new Response('{}', { status: 200 })+ ) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) expect(outcome.error.kind).toBe('kernel_rejected')+ expect(fetchFn).not.toHaveBeenCalled()+ })++ it('skips a kernel-rejected WWW-Authenticate hint and never fetches it', async () => {+ // AS points resource_metadata at an internal host; kernel must drop it and+ // fall back to the well-known (public) candidate.+ const evilHint = 'Bearer resource_metadata="https://metadata.internal/.well-known/x"'+ const resolveDns = vi.fn(async (host: string) => {+ if (host === 'metadata.internal') return ['169.254.169.254']+ return PUBLIC_IP+ })+ const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString()+ if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {+ return new Response(null, { status: 401, headers: { 'www-authenticate': evilHint } })+ }+ if (url === 'https://mcp.notion.com/.well-known/oauth-protected-resource') {+ return new Response(PILOTS.notion.prm.json, { status: 200 })+ }+ if (url === 'https://mcp.notion.com/.well-known/oauth-authorization-server') {+ return new Response(PILOTS.notion.as.json, { status: 200 })+ }+ return new Response('nf', { status: 404 })+ }) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })+ expect(outcome.ok).toBe(true)+ // The internal host was never fetched.+ const fetchedUrls = (fetchFn as unknown as ReturnType<typeof vi.fn>).mock.calls.map(c =>+ String(c[0])+ )+ expect(fetchedUrls.some(u => u.includes('metadata.internal'))).toBe(false)+ })+})++describe('discoverRemoteOAuth — SSRF via redirects (H1: redirect:manual + re-validate)', () => {+ it('does NOT follow a 302 → IMDS from a well-known fetch (rejected by the kernel)', async () => {+ const resolveDns = vi.fn(async () => PUBLIC_IP)+ const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString()+ if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {+ return new Response(null, { status: 401 })+ }+ // Every PRM well-known candidate 302s at the link-local IMDS address.+ if (url.startsWith('https://mcp.notion.com/.well-known/oauth-protected-resource')) {+ return new Response(null, {+ status: 302,+ headers: { location: 'http://169.254.169.254/latest/meta-data/' },+ })+ }+ return new Response('nf', { status: 404 })+ }) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) expect(outcome.error.kind).toBe('kernel_rejected')+ const fetched = (fetchFn as unknown as ReturnType<typeof vi.fn>).mock.calls.map(c =>+ String(c[0])+ )+ expect(fetched.some(u => u.includes('169.254.169.254'))).toBe(false)+ })++ it('does NOT follow a 302 → internal .svc host (rejected by the kernel)', async () => {+ const resolveDns = vi.fn(async () => PUBLIC_IP)+ const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString()+ if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {+ return new Response(null, { status: 401 })+ }+ if (url.startsWith('https://mcp.notion.com/.well-known/oauth-protected-resource')) {+ return new Response(null, {+ status: 302,+ headers: { location: 'http://control-api.mcp-host.svc/.well-known/x' },+ })+ }+ return new Response('nf', { status: 404 })+ }) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) expect(outcome.error.kind).toBe('kernel_rejected')+ const fetched = (fetchFn as unknown as ReturnType<typeof vi.fn>).mock.calls.map(c =>+ String(c[0])+ )+ expect(fetched.some(u => u.includes('.svc'))).toBe(false)+ })++ it('fails closed (redirect_blocked) when the hop count is exceeded', async () => {+ const resolveDns = vi.fn(async () => PUBLIC_IP)+ const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString()+ if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {+ return new Response(null, { status: 401 })+ }+ // A public host that keeps redirecting to itself — never terminates.+ return new Response(null, {+ status: 302,+ headers: { location: 'https://loop.example.com/next' },+ })+ }) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) expect(outcome.error.kind).toBe('redirect_blocked')+ })++ it('DOES follow a kernel-approved redirect to a public host', async () => {+ const resolveDns = vi.fn(async () => PUBLIC_IP)+ const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString()+ if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {+ return new Response(null, { status: 401 })+ }+ if (url === 'https://mcp.notion.com/.well-known/oauth-protected-resource') {+ return new Response(null, {+ status: 302,+ headers: { location: 'https://mcp.notion.com/prm-moved' },+ })+ }+ if (url === 'https://mcp.notion.com/prm-moved') {+ return new Response(PILOTS.notion.prm.json, { status: 200 })+ }+ if (url === 'https://mcp.notion.com/.well-known/oauth-authorization-server') {+ return new Response(PILOTS.notion.as.json, { status: 200 })+ }+ return new Response('nf', { status: 404 })+ }) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })+ expect(outcome.ok).toBe(true)+ if (outcome.ok) expect(outcome.result.resource).toBe('https://mcp.notion.com')+ const fetched = (fetchFn as unknown as ReturnType<typeof vi.fn>).mock.calls.map(c =>+ String(c[0])+ )+ expect(fetched).toContain('https://mcp.notion.com/prm-moved')+ })+})++describe('discoverRemoteOAuth — third-party metadata self-consistency (C2/C3)', () => {+ it('C2: rejects a PRM whose resource is cross-origin (RFC 9728 §3.3)', async () => {+ const evilPrm = { ...JSON.parse(PILOTS.notion.prm.json), resource: 'https://evil.example.com' }+ const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString()+ if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {+ return new Response(null, { status: 401 })+ }+ if (url.startsWith('https://mcp.notion.com/.well-known/oauth-protected-resource')) {+ return new Response(JSON.stringify(evilPrm), { status: 200 })+ }+ return new Response('nf', { status: 404 })+ }) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {+ fetchFn,+ resolveDns: publicDns(),+ })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) expect(outcome.error.kind).toBe('prm_resource_mismatch')+ })++ it('C2: accepts the real pilots (Notion origin-match, Linear exact)', async () => {+ for (const key of ['notion', 'linear'] as const) {+ const outcome = await discoverRemoteOAuth(+ PILOTS[key].mcpUrl,+ deps(makeDiscoveryFetch(PILOTS[key]))+ )+ expect(outcome.ok).toBe(true)+ if (outcome.ok)+ expect(outcome.result.resource).toBe(JSON.parse(PILOTS[key].prm.json).resource)+ }+ })++ it('C3: rejects AS metadata whose issuer != authorization server base (RFC 8414 §3.3)', async () => {+ const evilAs = { ...JSON.parse(PILOTS.notion.as.json), issuer: 'https://evil.example.com' }+ const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString()+ if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {+ return new Response(null, { status: 401 })+ }+ if (url === 'https://mcp.notion.com/.well-known/oauth-protected-resource') {+ return new Response(PILOTS.notion.prm.json, { status: 200 })+ }+ // The evil issuer is served on BOTH AS-metadata candidates (oauth + OIDC),+ // so neither clears the RFC 8414 §3.3 check.+ if (+ url === 'https://mcp.notion.com/.well-known/oauth-authorization-server' ||+ url === 'https://mcp.notion.com/.well-known/openid-configuration'+ ) {+ return new Response(JSON.stringify(evilAs), { status: 200 })+ }+ return new Response('nf', { status: 404 })+ }) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {+ fetchFn,+ resolveDns: publicDns(),+ })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) expect(outcome.error.kind).toBe('issuer_mismatch')+ })++ it('C3: accepts the real pilots (issuer == authorization server base)', async () => {+ for (const key of ['notion', 'sentry'] as const) {+ const outcome = await discoverRemoteOAuth(+ PILOTS[key].mcpUrl,+ deps(makeDiscoveryFetch(PILOTS[key]))+ )+ expect(outcome.ok).toBe(true)+ if (outcome.ok) expect(outcome.result.issuer).toBe(JSON.parse(PILOTS[key].as.json).issuer)+ }+ })+})++describe('discoverRemoteOAuth — fail-closed without S256 (invariant 3, T5)', () => {+ it('refuses when code_challenge_methods_supported lacks S256', async () => {+ const noS256As = JSON.parse(PILOTS.notion.as.json)+ noS256As.code_challenge_methods_supported = ['plain']+ const fetchFn = vi.fn(async (input: string | URL | Request) => {+ const url = String(input)+ if (url === 'https://mcp.notion.com/.well-known/oauth-protected-resource') {+ return new Response(PILOTS.notion.prm.json, { status: 200 })+ }+ if (url === 'https://mcp.notion.com/.well-known/oauth-authorization-server') {+ return new Response(JSON.stringify(noS256As), { status: 200 })+ }+ if (url === 'https://mcp.notion.com/mcp') return new Response(null, { status: 401 })+ return new Response('nf', { status: 404 })+ }) as unknown as typeof fetch+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {+ fetchFn,+ resolveDns: vi.fn(async () => PUBLIC_IP),+ })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) expect(outcome.error.kind).toBe('no_s256')+ })+})++describe('well-known URL construction (RFC 9728 §3.1 / RFC 8414)', () => {+ it('PRM: root-only for a resource without path', () => {+ expect(wellKnownPrmUrls(new URL('https://mcp.notion.com/'))).toEqual([+ 'https://mcp.notion.com/.well-known/oauth-protected-resource',+ ])+ })+ it('PRM: path-suffixed then root for a resource with path', () => {+ expect(wellKnownPrmUrls(new URL('https://mcp.linear.app/mcp'))).toEqual([+ 'https://mcp.linear.app/.well-known/oauth-protected-resource/mcp',+ 'https://mcp.linear.app/.well-known/oauth-protected-resource',+ ])+ })+ it('AS: oauth-authorization-server then openid-configuration at root', () => {+ expect(asMetadataUrls(new URL('https://mcp.sentry.dev'))).toEqual([+ 'https://mcp.sentry.dev/.well-known/oauth-authorization-server',+ 'https://mcp.sentry.dev/.well-known/openid-configuration',+ ])+ })+ it('AS with a path: oauth is path-inserted, OIDC is path-appended (RFC 8414 §3.1/§5)', () => {+ expect(asMetadataUrls(new URL('https://as.example.com/tenant1'))).toEqual([+ 'https://as.example.com/.well-known/oauth-authorization-server/tenant1',+ 'https://as.example.com/tenant1/.well-known/openid-configuration',+ ])+ })+})++describe('parseResourceMetadataChallenge', () => {+ it('extracts resource_metadata from a real Sentry challenge', () => {+ expect(parseResourceMetadataChallenge(PILOTS.sentry.wwwAuthenticate)).toBe(+ 'https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp'+ )+ })+ it('returns undefined when no header / no field', () => {+ expect(parseResourceMetadataChallenge(null)).toBeUndefined()+ expect(parseResourceMetadataChallenge('Bearer realm="x"')).toBeUndefined()+ })+})diff --git a/control-api/test/oauth.providers.remote.test.ts b/control-api/test/oauth.providers.remote.test.tsnew file mode 100644index 000000000..de534553d--- /dev/null+++ b/control-api/test/oauth.providers.remote.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from 'vitest'+import {+ buildRemoteRefreshRequest,+ buildRemoteTokenRequest,+ getOAuthProviderAdapter,+ parseRemoteTokenResponse,+} from '../src/oauth/providers.js'++/**+ * Generic public token client for the remote lane (D-10 §3). T4: assert the+ * OBSERVABLE emitted `TokenRequest.body` — a public client omits `client_secret`,+ * carries `code_verifier` under PKCE, and appends RFC 8707 `resource`. The wrapper+ * must NOT perturb the 8 baked adapters (byte-identity is pinned by the T1 golden+ * suite; here we prove the wrapper adds only `resource`).+ */+const TOKEN_ENDPOINT = 'https://mcp.notion.com/token'+const RESOURCE = 'https://mcp.notion.com'++describe('buildRemoteTokenRequest (public client, RFC 8707)', () => {+ it('omits client_secret and appends resource (public + PKCE)', () => {+ const req = buildRemoteTokenRequest(+ TOKEN_ENDPOINT,+ {+ code: 'CODE',+ clientId: 'CID',+ redirectUri: 'https://cb.example.com/remote',+ codeVerifier: 'VER',+ },+ RESOURCE+ )+ expect(req.url).toBe(TOKEN_ENDPOINT)+ expect(req.method).toBe('POST')+ expect(req.body).not.toContain('client_secret')+ expect(req.body).toBe(+ 'grant_type=authorization_code&code=CODE&client_id=CID&redirect_uri=https%3A%2F%2Fcb.example.com%2Fremote&code_verifier=VER&resource=https%3A%2F%2Fmcp.notion.com'+ )+ })++ it('omits resource when not provided (body identical to the standard builder)', () => {+ const req = buildRemoteTokenRequest(TOKEN_ENDPOINT, {+ code: 'CODE',+ clientId: 'CID',+ redirectUri: 'https://cb.example.com/remote',+ })+ expect(req.body).toBe(+ 'grant_type=authorization_code&code=CODE&client_id=CID&redirect_uri=https%3A%2F%2Fcb.example.com%2Fremote'+ )+ })++ it('includes client_secret when a confidential secret is supplied (append still last)', () => {+ const req = buildRemoteTokenRequest(+ TOKEN_ENDPOINT,+ {+ code: 'CODE',+ clientId: 'CID',+ clientSecret: 'SEC',+ redirectUri: 'https://cb.example.com/remote',+ },+ RESOURCE+ )+ expect(req.body).toBe(+ 'grant_type=authorization_code&code=CODE&client_id=CID&client_secret=SEC&redirect_uri=https%3A%2F%2Fcb.example.com%2Fremote&resource=https%3A%2F%2Fmcp.notion.com'+ )+ })+})++describe('buildRemoteRefreshRequest (public client, RFC 8707)', () => {+ it('omits client_secret and appends resource', () => {+ const req = buildRemoteRefreshRequest(+ TOKEN_ENDPOINT,+ { refreshToken: 'RT', clientId: 'CID' },+ RESOURCE+ )+ expect(req.body).toBe(+ 'grant_type=refresh_token&refresh_token=RT&client_id=CID&resource=https%3A%2F%2Fmcp.notion.com'+ )+ })++ it('omits resource when not provided', () => {+ const req = buildRemoteRefreshRequest(TOKEN_ENDPOINT, { refreshToken: 'RT', clientId: 'CID' })+ expect(req.body).toBe('grant_type=refresh_token&refresh_token=RT&client_id=CID')+ })+})++describe('parseRemoteTokenResponse', () => {+ it('is the standard OAuth2 parser', () => {+ const parsed = parseRemoteTokenResponse({+ access_token: 'AT',+ refresh_token: 'RT',+ expires_in: 3600,+ token_type: 'Bearer',+ scope: 'read',+ })+ expect(parsed).toEqual({+ accessToken: 'AT',+ refreshToken: 'RT',+ expiresIn: 3600,+ tokenType: 'Bearer',+ scope: 'read',+ })+ })+})++describe('the 8 baked adapters are untouched by the remote wrappers', () => {+ it('salesforce token body is unchanged (no resource leaks in)', () => {+ const body = getOAuthProviderAdapter('salesforce').buildTokenRequest({+ code: 'thecode',+ clientId: 'cid',+ clientSecret: 'csec',+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/provider',+ }).body+ expect(body).not.toContain('resource=')+ expect(body).toBe(+ 'grant_type=authorization_code&code=thecode&client_id=cid&client_secret=csec&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider'+ )+ })+})