Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(control-api): per-server callback decision core for ASes without RFC 9207

Diego Zacarias85b19e7126e9
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 817e575a9..9d353c859 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.680",
+ "version": "0.1.681",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.680",
+ "version": "0.1.681",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
@@ -25,6 +25,7 @@
"pg": "^8.13.1",
"pino": "^10.3.1",
"prom-client": "^15.1.3",
+ "tldts": "^7.4.16",
"yaml": "^2.8.3",
"zod": "^4.3.6"
},
@@ -3715,6 +3716,24 @@
"node": ">=14.0.0"
}
},
+ "node_modules/tldts": {
+ "version": "7.4.16",
+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.16.tgz",
+ "integrity": "sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg==",
+ "license": "MIT",
+ "dependencies": {
+ "tldts-core": "^7.4.16"
+ },
+ "bin": {
+ "tldts": "bin/cli.js"
+ }
+ },
+ "node_modules/tldts-core": {
+ "version": "7.4.16",
+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.16.tgz",
+ "integrity": "sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA==",
+ "license": "MIT"
+ },
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
diff --git a/control-api/package.json b/control-api/package.json
index ab5a7cfd6..d8e807591 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.680",
+ "version": "0.1.681",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
@@ -33,6 +33,7 @@
"pg": "^8.13.1",
"pino": "^10.3.1",
"prom-client": "^15.1.3",
+ "tldts": "^7.4.16",
"yaml": "^2.8.3",
"zod": "^4.3.6"
},
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index 33b7b30a2..1b867df37 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -18,20 +18,15 @@ import {
isKnownOAuthProvider,
parseRemoteTokenResponse,
} from './providers.js'
+import { REMOTE_CALLBACK_CLIENT_SEGMENT } from './remoteCallback.js'
import type { OAuthMcpStateClaims } from './state.js'
import { signOAuthState, verifyOAuthStateSignature } from './state.js'
import { bootstrapSharedOAuthGrant, setUserGrantBackground, upsertOAuthGrant } from './store.js'
-/**
- * Reserved last URL segment of the STABLE remote OAuth callback
- * (`/api/v1/oauth-callback/remote`). The remote lane (CIMD/DCR) registers ONE
- * fixed redirect_uri, so the URL segment is a constant and the real client
- * binding rides the signed state (`subjectKind:'mcp'` + `mcpServerName`, both
- * re-resolved authoritatively). `cimd.ts` derives `REMOTE_CALLBACK_PATH` from
- * this. Kept here (not in `cimd.ts`) to avoid an import cycle
- * (callback → cimd → external/oauthCallback → callback).
- */
-export const REMOTE_CALLBACK_CLIENT_SEGMENT = 'remote'
+// Reserved last URL segment of the shared remote OAuth callback. Defined in
+// `remoteCallback.ts` (the single redirect-URI builder); re-exported for the existing
+// importers of this module.
+export { REMOTE_CALLBACK_CLIENT_SEGMENT }
/**
* Discriminator for WHERE an mcp-server's OAuth client credentials live
diff --git a/control-api/src/oauth/cimd.ts b/control-api/src/oauth/cimd.ts
index 3116c22d2..1a03248e4 100644
--- a/control-api/src/oauth/cimd.ts
+++ b/control-api/src/oauth/cimd.ts
@@ -2,7 +2,7 @@ import { Router } from 'express'
import { config } from '../config.js'
import { type Logger, rootLogger } from '../observability/logger.js'
import { normalizeConfiguredOrigin } from '../routes/external/oauthCallback.js'
-import { REMOTE_CALLBACK_CLIENT_SEGMENT } from './callback.js'
+import { REMOTE_CALLBACK_PATH, buildRemoteRedirectUri } from './remoteCallback.js'
/**
* Client ID Metadata Document (CIMD, SEP-991), served by control-api as the
@@ -21,7 +21,12 @@ 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). */
+ /**
+ * Only the SHARED remote callback: this one platform identity is accepted by every AS
+ * that trusts the document, so listing per-server URIs here would let any such AS
+ * redirect to any server and void the per-server separation. CIMD is therefore only
+ * offered against an AS that returns `iss` (RFC 9207).
+ */
redirect_uris: readonly string[]
/** Public client — no client_secret. */
token_endpoint_auth_method: 'none'
@@ -36,12 +41,9 @@ 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, and
- * C2 DCR (`dcr.ts`) derives its `redirect_uris` from the same constant so the CIMD
- * document and a dynamically-registered client advertise a byte-identical callback.
- */
-export const REMOTE_CALLBACK_PATH = `/api/v1/oauth-callback/${REMOTE_CALLBACK_CLIENT_SEGMENT}`
+// The shared remote callback path, defined by the single redirect-URI builder
+// (`remoteCallback.ts`). Re-exported for the existing importers of this module.
+export { REMOTE_CALLBACK_PATH }
/**
* Build the frozen CIMD document for a given public `origin` (scheme://host, no
@@ -54,7 +56,7 @@ 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}`]),
+ redirect_uris: Object.freeze([buildRemoteRedirectUri({ origin, variant: 'shared' })]),
token_endpoint_auth_method: 'none',
grant_types: Object.freeze(['authorization_code', 'refresh_token']),
response_types: Object.freeze(['code']),
diff --git a/control-api/src/oauth/dcr.ts b/control-api/src/oauth/dcr.ts
index d3e06e9be..30128b7dc 100644
--- a/control-api/src/oauth/dcr.ts
+++ b/control-api/src/oauth/dcr.ts
@@ -2,6 +2,7 @@ import { type PinnedFetchError, type PinnedTransport, pinnedFetch } from '../htt
import type { DnsResolver, ValidationError } from '../http/validateMcpServerSpec.js'
import { type Logger, rootLogger } from '../observability/logger.js'
import type { DiscoveryResult } from './discovery.js'
+import type { RemoteCallbackVariant } from './remoteCallback.js'
/**
* Dynamic Client Registration client (RFC 7591), spec 02 C2 / D-5 / DEC-18.
@@ -59,6 +60,11 @@ export interface DcrRegistrationResponse {
/** RFC 7592 management endpoint. */
registration_client_uri?: string
token_endpoint_auth_method?: string
+ /**
+ * RFC 7591 §3.2.1: the AS echoes the registered metadata, including the redirect
+ * URIs it actually accepted. Untrusted — check it with {@link verifyDcrRedirectUris}.
+ */
+ redirect_uris?: unknown
[k: string]: unknown
}
@@ -321,3 +327,44 @@ export async function registerDynamicClient(
effectiveClientMode,
}
}
+
+export type DcrRedirectUrisCheck =
+ | { ok: true }
+ | { ok: false; reason: 'redirect_uris_missing' | 'redirect_uris_mismatch' }
+
+/**
+ * Check the `redirect_uris` a registration response reports against the ones we sent.
+ *
+ * per-server: REQUIRED and exactly equal (same strings, no normalization). The
+ * per-server redirect URI is the only mix-up defence there, so a client
+ * the AS registered with a different or unreported URI cannot be trusted
+ * to redirect only to this installation.
+ * shared: the response `iss` is the defence, so an ABSENT (or `null`) field is
+ * tolerated (ASes that omit the echo keep working); a PRESENT one that
+ * differs still fails.
+ *
+ * Comparison is set equality over exact strings (RFC 7591 gives the array no order).
+ * Pure; the caller turns a failure into an install failure with RFC 7592 cleanup.
+ */
+export function verifyDcrRedirectUris(input: {
+ variant: RemoteCallbackVariant
+ requested: readonly string[]
+ response: Pick<DcrRegistrationResponse, 'redirect_uris'>
+}): DcrRedirectUrisCheck {
+ const reported = input.response.redirect_uris
+ // JSON `null` is how some serializers spell an omitted field, so it counts as absent.
+ if (reported === undefined || reported === null) {
+ return input.variant === 'shared'
+ ? { ok: true }
+ : { ok: false, reason: 'redirect_uris_missing' }
+ }
+ if (
+ !Array.isArray(reported) ||
+ reported.length !== input.requested.length ||
+ !reported.every(uri => typeof uri === 'string' && input.requested.includes(uri)) ||
+ !input.requested.every(uri => reported.includes(uri))
+ ) {
+ return { ok: false, reason: 'redirect_uris_mismatch' }
+ }
+ return { ok: true }
+}
diff --git a/control-api/src/oauth/discovery.ts b/control-api/src/oauth/discovery.ts
index 8f26b4e07..2b15a380c 100644
--- a/control-api/src/oauth/discovery.ts
+++ b/control-api/src/oauth/discovery.ts
@@ -1,3 +1,4 @@
+import { getDomain } from 'tldts'
import {
type PinnedFetchError,
type PinnedResponse,
@@ -74,6 +75,12 @@ export interface SelectRegistrationModeInput {
cimdSupported: boolean
tokenEndpointAuthMethods: string[]
hasRegistrationEndpoint: boolean
+ /**
+ * Whether the AS returns `iss` on the authorization response (RFC 9207) — compute it
+ * with {@link advertisesIssBinding}. Required, with no default, so a caller cannot
+ * silently fall back to offering CIMD against an AS without it.
+ */
+ issBindingSupported: boolean
}
/**
@@ -84,14 +91,118 @@ export interface SelectRegistrationModeInput {
* 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.
+ *
+ * Without RFC 9207 CIMD is never offered, even when the AS supports it: such a server
+ * needs a redirect URI of its own, and the CIMD document is one platform-wide identity
+ * that can only list the shared callback. A CIMD-only AS without `iss` therefore
+ * resolves to `manual` (the operator pre-registers a client).
*/
export function selectRegistrationMode(input: SelectRegistrationModeInput): RegistrationMode {
if (input.hasPreRegisteredClient) return 'pre-registered'
- if (input.cimdSupported && input.tokenEndpointAuthMethods.includes('none')) return 'cimd'
+ if (
+ input.issBindingSupported &&
+ input.cimdSupported &&
+ input.tokenEndpointAuthMethods.includes('none')
+ ) {
+ return 'cimd'
+ }
if (input.hasRegistrationEndpoint) return 'dcr'
return 'manual'
}
+/**
+ * RFC 9207: the AS advertises that it returns `iss` on the authorization response.
+ * The ONE expression behind both `issForCallback` and the registration-mode choice, so
+ * the callback variant and the offered modes cannot disagree about the same AS.
+ * Strictly `=== true`: the metadata is untrusted and a truthy non-boolean is not an
+ * advertisement.
+ */
+export function advertisesIssBinding(as: AuthorizationServerMetadata): boolean {
+ return as.authorization_response_iss_parameter_supported === true
+}
+
+// ─── Same-site rule for AS endpoints (per-server callback only) ─────────────
+
+/**
+ * Registrable domain (eTLD+1, Public Suffix List including its private section) of a
+ * URL, or `null` when it has none.
+ *
+ * The host is taken from WHATWG `new URL()` — the same parse `pinnedFetch` connects
+ * with — and only the hostname is handed to `tldts`. Passing the raw URL would let the
+ * two parsers disagree: `https://evil.com\@honest.com/t` is `evil.com` to WHATWG (and
+ * to the socket) but `honest.com` to `tldts`. A URL carrying userinfo is refused
+ * outright (`null`) since no AS endpoint legitimately has one. `allowPrivateDomains`
+ * keeps shared-hosting suffixes (`github.io`, `herokuapp.com`) as public suffixes, so
+ * two tenants of one platform are two sites; a bare public suffix or an IP literal has
+ * no registrable domain and yields `null`.
+ */
+export function registrableSite(url: string): string | null {
+ let parsed: URL
+ try {
+ parsed = new URL(url)
+ } catch {
+ return null
+ }
+ if (parsed.username !== '' || parsed.password !== '') return null
+ return getDomain(parsed.hostname, { allowPrivateDomains: true })
+}
+
+export interface AsEndpointSites {
+ issuer: string
+ authorization: string
+ token: string
+ registration?: string
+ revocation?: string
+}
+
+export type AsEndpointSiteCheck =
+ | { ok: true }
+ | { ok: false; field: keyof AsEndpointSites; detail: string }
+
+/**
+ * Every AS endpoint must share the issuer's registrable domain. Applies when the AS
+ * does not return `iss` (RFC 9207): the callback then cannot tell which AS produced a
+ * code, so a hostile metadata document that borrows an honest AS's authorize and
+ * registration endpoints but names its own token endpoint would have us register a
+ * client at the honest AS and redeem its codes at the attacker. With `iss` the response
+ * is bound to the issuer and this rule is not needed.
+ *
+ * `revocation` is checked although nothing sends to it yet, so the day it is used it
+ * cannot receive refresh tokens on an unvalidated host. A `null` site is never equal to
+ * anything, including another `null`. Pure: callers pass the endpoints they are about
+ * to trust (discovery output, or the values pinned on a CR).
+ */
+export function checkAsEndpointsSameSite(endpoints: AsEndpointSites): AsEndpointSiteCheck {
+ const issuerSite = registrableSite(endpoints.issuer)
+ if (issuerSite === null) {
+ return {
+ ok: false,
+ field: 'issuer',
+ detail:
+ 'issuer has no registrable domain (public suffix, IP literal, userinfo or invalid URL)',
+ }
+ }
+ const fields: Array<Exclude<keyof AsEndpointSites, 'issuer'>> = [
+ 'authorization',
+ 'token',
+ 'registration',
+ 'revocation',
+ ]
+ for (const field of fields) {
+ const url = endpoints[field]
+ if (url === undefined) continue
+ const site = registrableSite(url)
+ if (site !== issuerSite) {
+ return {
+ ok: false,
+ field,
+ detail: `${field} endpoint ${site === null ? 'has no registrable domain' : `is on site "${site}"`}, issuer is on site "${issuerSite}"`,
+ }
+ }
+ }
+ return { ok: true }
+}
+
// ─── Transport quirks derived from metadata (D-8, pure) ─────────────────────
export interface RemoteQuirks {
@@ -153,6 +264,8 @@ export type DiscoveryError =
| { kind: 'issuer_mismatch'; detail: string }
/** Response arrived with a non-identity `content-encoding` (fail-closed, never mis-parse). */
| { kind: 'content_encoding_rejected'; url: string; encoding: string }
+ /** Without RFC 9207, an AS endpoint is not on the issuer's registrable domain. */
+ | { kind: 'as_endpoints_cross_site'; field: string; detail: string }
export interface DiscoveryResult {
prm: ProtectedResourceMetadata
@@ -496,11 +609,12 @@ async function resolvePrm(
* 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).
+ * not advertise S256 (invariant 3), and — when it does not return `iss` (RFC 9207) —
+ * if any of its endpoints leaves the issuer's registrable domain
+ * (`as_endpoints_cross_site`), before anything is registered against it.
*
* `hasPreRegisteredClient` reflects operator config (a pre-registered Secret),
- * defaulting to false — the C1 pilots (Notion/Canva/Linear/Sentry) have none and
- * resolve to CIMD.
+ * defaulting to false.
*
* Mirror: control-ui hand-copies this projection (the `detected` shape the remoteMcp
* route builds from this result) in test/fixtures/__tests__/remoteMcpDiscovery.contract.test.ts
@@ -621,11 +735,35 @@ export async function discoverRemoteOAuth(
}
}
+ const issBindingSupported = advertisesIssBinding(as)
+ if (!issBindingSupported) {
+ const sameSite = checkAsEndpointsSameSite({
+ issuer: as.issuer,
+ authorization: as.authorization_endpoint,
+ token: as.token_endpoint,
+ ...(typeof as.registration_endpoint === 'string'
+ ? { registration: as.registration_endpoint }
+ : {}),
+ ...(typeof as.revocation_endpoint === 'string' ? { revocation: as.revocation_endpoint } : {}),
+ })
+ if (!sameSite.ok) {
+ log.warn(
+ { discovery: 'as_endpoints_cross_site', field: sameSite.field },
+ 'authorization server endpoints are not on the issuer site'
+ )
+ return {
+ ok: false,
+ error: { kind: 'as_endpoints_cross_site', field: sameSite.field, detail: sameSite.detail },
+ }
+ }
+ }
+
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',
+ issBindingSupported,
})
return {
@@ -635,8 +773,7 @@ export async function discoverRemoteOAuth(
as,
resource: prm.resource,
issuer: as.issuer,
- issForCallback:
- as.authorization_response_iss_parameter_supported === true ? as.issuer : undefined,
+ issForCallback: issBindingSupported ? as.issuer : undefined,
endpoints: {
authorization: as.authorization_endpoint,
token: as.token_endpoint,
diff --git a/control-api/src/oauth/discoveryHttpStatus.ts b/control-api/src/oauth/discoveryHttpStatus.ts
index ae99210ec..96d5efcd8 100644
--- a/control-api/src/oauth/discoveryHttpStatus.ts
+++ b/control-api/src/oauth/discoveryHttpStatus.ts
@@ -26,6 +26,7 @@ export function discoveryHttpStatus(error: DiscoveryError): number {
case 'redirect_blocked':
case 'prm_resource_mismatch':
case 'issuer_mismatch':
+ case 'as_endpoints_cross_site':
return 400
default: {
const _exhaustive: never = error
diff --git a/control-api/src/oauth/remoteCallback.ts b/control-api/src/oauth/remoteCallback.ts
new file mode 100644
index 000000000..696ea3803
--- /dev/null
+++ b/control-api/src/oauth/remoteCallback.ts
@@ -0,0 +1,149 @@
+import { RFC1123_RE } from '../http/rfc1123.js'
+
+/**
+ * Redirect-URI policy for the remote MCP-OAuth lane (CIMD / DCR / pre-registered).
+ *
+ * Two callback variants exist, and which one a server uses is decided solely by
+ * whether its authorization server advertises RFC 9207 (`iss` on the authorization
+ * response):
+ *
+ * - `shared` — every server lands on ONE stable callback. Safe only because the
+ * callback checks the response `iss` against the pinned issuer; the
+ * URL itself carries no per-server binding.
+ * - `per-server` — without `iss`, the redirect URI itself is the mix-up defence: each
+ * server (and, for DCR, each installation) registers a distinct URI,
+ * so an AS can only ever deliver a code to the server it was issued
+ * for.
+ *
+ * This module is the single place that derives the variant and builds the URI, so the
+ * value registered at the AS, sent on authorize and replayed on the token exchange
+ * cannot drift apart. It deliberately imports nothing from the OAuth modules: both
+ * `callback.ts` and `cimd.ts` depend on it, and `cimd.ts` already reaches
+ * `callback.ts` through `routes/external/oauthCallback.ts`, so any OAuth import here
+ * would risk closing a cycle.
+ */
+
+/** Reserved last URL segment of the shared remote callback. */
+export const REMOTE_CALLBACK_CLIENT_SEGMENT = 'remote'
+
+/** Public path of the shared remote callback; per-server URIs extend it. */
+export const REMOTE_CALLBACK_PATH = `/api/v1/oauth-callback/${REMOTE_CALLBACK_CLIENT_SEGMENT}`
+
+export type RemoteCallbackVariant = 'shared' | 'per-server'
+
+/**
+ * Derive the callback variant from a remote `spec.oauth` block. Takes the block (not
+ * the CR) so the install can call it on the block it is about to write, before the CR
+ * exists, and the runtime paths on the block read back from the CR — one derivation
+ * for both. `issForCallback` is third-party-derived CR data, hence `unknown`.
+ */
+export function remoteCallbackVariant(oauth: { issForCallback?: unknown }): RemoteCallbackVariant {
+ return typeof oauth.issForCallback === 'string' && oauth.issForCallback.length > 0
+ ? 'shared'
+ : 'per-server'
+}
+
+/** A server name usable as a callback path segment: an RFC 1123 label (the K8s name rule). */
+export function isValidRemoteServerNameSegment(value: unknown): value is string {
+ return typeof value === 'string' && RFC1123_RE.test(value)
+}
+
+// Lowercase only: the install nonce is minted by `randomUUID()` (always lowercase) and
+// is compared byte-for-byte against the stored `install_id`, so an uppercase spelling
+// can never be legitimate and accepting it would give one nonce two valid URIs.
+const INSTALL_NONCE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
+
+/** An installation nonce usable as a callback path segment: a canonical lowercase UUID. */
+export function isValidInstallNonce(value: unknown): value is string {
+ return typeof value === 'string' && INSTALL_NONCE_RE.test(value)
+}
+
+// A per-server URI is compared byte-for-byte by the AS and replayed on the token
+// exchange, so its origin must already be in canonical form: no path, trailing slash,
+// query, fragment or userinfo, and no spelling `new URL` would normalize differently.
+function isBareOrigin(origin: unknown): origin is string {
+ if (typeof origin !== 'string' || origin.length === 0) return false
+ try {
+ return new URL(origin).origin === origin
+ } catch {
+ return false
+ }
+}
+
+export type RemoteRedirectUriInput =
+ | { origin: string; variant: 'shared' }
+ | {
+ origin: string
+ variant: 'per-server'
+ mode: 'dcr'
+ serverName: string
+ installNonce: string
+ }
+ | { origin: string; variant: 'per-server'; mode: 'pre-registered'; serverName: string }
+
+export class InvalidRemoteRedirectUriInputError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'InvalidRemoteRedirectUriInputError'
+ }
+}
+
+/**
+ * Build the remote redirect URI.
+ *
+ * shared → `${origin}/api/v1/oauth-callback/remote`
+ * per-server, DCR → `${origin}/api/v1/oauth-callback/remote/<serverName>/<installNonce>`
+ * per-server, pre-registered → `${origin}/api/v1/oauth-callback/remote/<serverName>`
+ *
+ * DCR carries the installation nonce because a DCR client outlives its uninstall at
+ * the AS (RFC 7592 deletion is best-effort): without it, a later server reusing the
+ * name would receive codes minted for the old, still-consented client. A pre-registered
+ * client is confidential and its secret is deleted with the CR, so an old code is
+ * useless and the URI stays stable for the operator to register once.
+ *
+ * Segments are validated and then interpolated verbatim — no `encodeURIComponent` —
+ * because the validators admit only characters that are already URL-safe, and the
+ * callback route must see the exact same bytes. Throws on any input that does not fit
+ * the table (invalid segment, missing/extra nonce, or a mode without a per-server URI
+ * such as CIMD), since a malformed redirect URI must never reach an AS.
+ */
+export function buildRemoteRedirectUri(input: RemoteRedirectUriInput): string {
+ // The shared URI keeps its historical origin handling (callers may fall back to the
+ // request Host); the per-server variant is only ever built from a configured origin.
+ if (input.variant === 'shared') {
+ return `${input.origin}${REMOTE_CALLBACK_PATH}`
+ }
+ if (input.variant !== 'per-server') {
+ throw new InvalidRemoteRedirectUriInputError(
+ `unknown callback variant "${String((input as { variant: unknown }).variant)}"`
+ )
+ }
+ if (!isBareOrigin(input.origin)) {
+ throw new InvalidRemoteRedirectUriInputError(
+ 'a per-server redirect URI requires a bare origin (scheme://host[:port])'
+ )
+ }
+ if (!isValidRemoteServerNameSegment(input.serverName)) {
+ throw new InvalidRemoteRedirectUriInputError('serverName is not a valid RFC 1123 label')
+ }
+ const base = `${input.origin}${REMOTE_CALLBACK_PATH}/${input.serverName}`
+ if (input.mode === 'dcr') {
+ if (!isValidInstallNonce(input.installNonce)) {
+ throw new InvalidRemoteRedirectUriInputError(
+ 'a per-server DCR redirect URI requires a lowercase UUID installNonce'
+ )
+ }
+ return `${base}/${input.installNonce}`
+ }
+ if (input.mode === 'pre-registered') {
+ if ((input as { installNonce?: unknown }).installNonce !== undefined) {
+ throw new InvalidRemoteRedirectUriInputError(
+ 'a per-server pre-registered redirect URI carries no installNonce'
+ )
+ }
+ return base
+ }
+ throw new InvalidRemoteRedirectUriInputError(
+ `registration mode "${String((input as { mode: unknown }).mode)}" has no per-server redirect URI`
+ )
+}
diff --git a/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts b/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts
index 1d52d37fb..03653bf6e 100644
--- a/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts
+++ b/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts
@@ -105,6 +105,10 @@ describe('discoveryHttpStatus — DiscoveryError → HTTP status decision table'
status: 400,
},
{ error: { kind: 'issuer_mismatch', detail: 'issuer != base' }, status: 400 },
+ {
+ error: { kind: 'as_endpoints_cross_site', field: 'token', detail: 'token on another site' },
+ status: 400,
+ },
]
for (const { error, status } of cases) {
diff --git a/control-api/test/fixtures/remoteOAuthDiscovery.ts b/control-api/test/fixtures/remoteOAuthDiscovery.ts
index b397c800e..05545fdc5 100644
--- a/control-api/test/fixtures/remoteOAuthDiscovery.ts
+++ b/control-api/test/fixtures/remoteOAuthDiscovery.ts
@@ -43,8 +43,11 @@ export const NOTION_AS_JSON =
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
+// Re-probed 2026-09-29: Linear now advertises RFC 9207
+// (`authorization_response_iss_parameter_supported: true`), which the 2026-09-20 bytes
+// did not carry. Byte-identical otherwise.
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"}'
+ '{"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"],"authorization_response_iss_parameter_supported":true,"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
@@ -202,6 +205,67 @@ export const VERCEL_PILOT: PilotFixture = {
},
}
+// ─── Atlassian v2 + Dropbox — ASes WITHOUT RFC 9207 (sondeo en vivo 2026-09-29) ──
+//
+// The exact bytes both servers returned on 2026-09-29 (curl, `Accept: application/json`).
+// Neither AS advertises `authorization_response_iss_parameter_supported`, so both take
+// the per-server callback path and the same-site rule applies to their endpoints.
+//
+// PROVENANCE (curl, 2026-09-29):
+// GET https://mcp.atlassian.com/v2/mcp → 401 www-authenticate: Bearer resource_metadata="https://mcp.atlassian.com/.well-known/oauth-protected-resource/v2/mcp"
+// GET https://mcp.atlassian.com/.well-known/oauth-protected-resource/v2/mcp → 200
+// GET https://auth.atlassian.com/.well-known/oauth-authorization-server/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3 → 200
+// GET https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3/.well-known/openid-configuration → 404
+// GET https://mcp.dropbox.com/mcp → 401 www-authenticate: Bearer resource_metadata="https://mcp.dropbox.com/.well-known/oauth-protected-resource/mcp", error="invalid_token", error_description="missing bearer token"
+// GET https://mcp.dropbox.com/.well-known/oauth-protected-resource/mcp → 200
+// GET https://www.dropbox.com/.well-known/oauth-authorization-server → 200
+//
+// Atlassian: CIMD + DCR + `none`, every endpoint on atlassian.com (same site as the
+// issuer) → DCR, never CIMD. Dropbox: token and revocation endpoints on
+// api.dropboxapi.com while the issuer is www.dropbox.com → cross-site.
+
+export const ATLASSIAN_V2_WWW_AUTHENTICATE =
+ 'Bearer resource_metadata="https://mcp.atlassian.com/.well-known/oauth-protected-resource/v2/mcp"'
+export const ATLASSIAN_V2_PRM_JSON =
+ '{"resource":"https://mcp.atlassian.com/v2/mcp","authorization_servers":["https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3"],"bearer_methods_supported":["header"],"scopes_supported":["read:me","read:account","offline_access","email","read:jira:agent-interface","write:jira:agent-interface","search:jira:agent-interface","delete:jira:agent-interface","manage:jira:agent-interface","read:confluence:agent-interface","write:confluence:agent-interface","search:confluence:agent-interface","search:rovo:agent-interface","search:code:agent-interface","read:all:twg","write:all:twg","read:goals:agent-interface","write:goals:agent-interface","read:projects:agent-interface","write:projects:agent-interface","read:bitbucket:agent-interface","write:bitbucket:agent-interface","read:loom:agent-interface","write:loom:agent-interface","read:talent:agent-interface","write:talent:agent-interface","read:jira-align:agent-interface","write:jira-align:agent-interface","read:teams:agent-interface","write:teams:agent-interface","read:artifacts:agent-interface","write:artifacts:agent-interface","read:capacity-planning:agent-interface","write:capacity-planning:agent-interface","read:focus:agent-interface","write:focus:agent-interface","read:assets:agent-interface","write:assets:agent-interface"],"resource_documentation":"https://www.atlassian.com/platform/remote-mcp-server"}'
+export const ATLASSIAN_V2_AS_JSON =
+ '{"authorization_endpoint":"https://auth.atlassian.com/authorize","client_id_metadata_document_supported":true,"code_challenge_methods_supported":["S256"],"grant_types_supported":["authorization_code","client_credentials","refresh_token","urn:ietf:params:oauth:grant-type:token-revoke","urn:ietf:params:oauth:grant-type:jwt-bearer","urn:ietf:params:oauth:grant-type:token-exchange"],"issuer":"https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3","jwks_uri":"https://auth.atlassian.com/.well-known/jwks.json","pushed_authorization_request_endpoint":"https://auth.atlassian.com/oauth/par","registration_endpoint":"https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3/dcr/register","response_types_supported":["code","token"],"revocation_endpoint":"https://auth.atlassian.com/oauth/revoke","token_endpoint":"https://auth.atlassian.com/oauth/token","token_endpoint_auth_methods_supported":["none","client_secret_post","client_secret_basic","private_key_jwt"]}'
+
+export const ATLASSIAN_V2_PILOT: PilotFixture = {
+ name: 'atlassian-v2',
+ mcpUrl: 'https://mcp.atlassian.com/v2/mcp',
+ wwwAuthenticate: ATLASSIAN_V2_WWW_AUTHENTICATE,
+ prm: {
+ url: 'https://mcp.atlassian.com/.well-known/oauth-protected-resource/v2/mcp',
+ json: ATLASSIAN_V2_PRM_JSON,
+ },
+ as: {
+ url: 'https://auth.atlassian.com/.well-known/oauth-authorization-server/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3',
+ json: ATLASSIAN_V2_AS_JSON,
+ },
+}
+
+export const DROPBOX_WWW_AUTHENTICATE =
+ 'Bearer resource_metadata="https://mcp.dropbox.com/.well-known/oauth-protected-resource/mcp", error="invalid_token", error_description="missing bearer token"'
+export const DROPBOX_PRM_JSON =
+ '{"resource":"https://mcp.dropbox.com/mcp","authorization_servers":["https://www.dropbox.com"],"scopes_supported":["account_info.read","file_requests.read","file_requests.write","files.content.read","files.content.write","files.metadata.read","files.metadata.write","sharing.read","sharing.write"]}'
+export const DROPBOX_AS_JSON =
+ '{"issuer": "https://www.dropbox.com", "authorization_endpoint": "https://www.dropbox.com/oauth2/authorize", "token_endpoint": "https://api.dropboxapi.com/oauth2/token", "revocation_endpoint": "https://api.dropboxapi.com/2/auth/token/revoke", "scopes_supported": ["account_info.read", "contacts.read", "contacts.write", "files.metadata.read", "files.content.read", "files.content.write", "files.permanent_delete", "files.metadata.write", "sharing.read", "sharing.write", "file_requests.read", "file_requests.write", "openid", "profile", "email", "account_info.write", "backup.read", "backup.write", "dash/content.read", "dash/content.write", "team_info.read", "team_info.write", "sessions.list", "sessions.modify", "members.read", "members.write", "members.delete", "groups.read", "groups.write", "events.read", "team_data.governance.read", "team_data.governance.write", "team_data.member", "team_data.content.read", "team_data.content.write", "team_data.team_space", "files.team_metadata.write", "events.write", "files.team_metadata.read"], "response_types_supported": ["code"], "grant_types_supported": ["authorization_code", "client_credentials", "refresh_token", "device_code"], "code_challenge_methods_supported": ["plain", "S256"], "token_endpoint_auth_methods_supported": ["client_secret_post", "client_secret_basic", "none"], "registration_endpoint": "https://www.dropbox.com/oauth2/register"}'
+
+export const DROPBOX_PILOT: PilotFixture = {
+ name: 'dropbox',
+ mcpUrl: 'https://mcp.dropbox.com/mcp',
+ wwwAuthenticate: DROPBOX_WWW_AUTHENTICATE,
+ prm: {
+ url: 'https://mcp.dropbox.com/.well-known/oauth-protected-resource/mcp',
+ json: DROPBOX_PRM_JSON,
+ },
+ as: {
+ url: 'https://www.dropbox.com/.well-known/oauth-authorization-server',
+ json: DROPBOX_AS_JSON,
+ },
+}
+
/**
* Build a {@link PinnedTransport}-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
diff --git a/control-api/test/oauth.dcr.redirectUris.test.ts b/control-api/test/oauth.dcr.redirectUris.test.ts
new file mode 100644
index 000000000..d66ee6bd8
--- /dev/null
+++ b/control-api/test/oauth.dcr.redirectUris.test.ts
@@ -0,0 +1,152 @@
+import { describe, expect, it } from 'vitest'
+import {
+ type DcrRegistrationResponse,
+ buildDcrRequest,
+ registerDynamicClient,
+ verifyDcrRedirectUris,
+} from '../src/oauth/dcr.js'
+import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'
+import { buildRemoteRedirectUri } from '../src/oauth/remoteCallback.js'
+import {
+ ATLASSIAN_V2_PILOT,
+ DCR_PUBLIC_REGISTRATION_RESPONSE,
+ makeDcrTransport,
+ makeDiscoveryTransport,
+} from './fixtures/remoteOAuthDiscovery.js'
+
+/**
+ * `redirect_uris` echoed by the AS on a registration response, checked per callback
+ * variant: per-server requires it and requires it exact; shared only fails when it is
+ * present and different.
+ *
+ * The request comes from the real builders (discovery → `buildRemoteRedirectUri` →
+ * `buildDcrRequest`) and the response goes through the real parser
+ * (`registerDynamicClient`), so the verifier sees exactly the shapes it will see in the
+ * install. The response body itself is the RFC 7591 §3.2.1 fixture the DCR suite uses
+ * (a live registration would create a real client at a third-party AS), with only
+ * `redirect_uris` varied.
+ */
+
+const PUBLIC_IP = async () => ['93.184.216.34']
+const ORIGIN = 'https://control.example.com'
+const NONCE = '0b8f6a52-5c7d-4e21-9f3a-1d2c3b4a5e6f'
+
+async function atlassianDiscovery(): Promise<DiscoveryResult> {
+ const outcome = await discoverRemoteOAuth(ATLASSIAN_V2_PILOT.mcpUrl, {
+ transport: makeDiscoveryTransport(ATLASSIAN_V2_PILOT),
+ resolveDns: PUBLIC_IP,
+ })
+ if (!outcome.ok) throw new Error(`discovery failed: ${outcome.error.kind}`)
+ return outcome.result
+}
+
+const PER_SERVER_URI = buildRemoteRedirectUri({
+ origin: ORIGIN,
+ variant: 'per-server',
+ mode: 'dcr',
+ serverName: 'atlassian',
+ installNonce: NONCE,
+})
+const SHARED_URI = buildRemoteRedirectUri({ origin: ORIGIN, variant: 'shared' })
+
+/** Register through the real client and return the parsed response it hands back. */
+async function registeredResponse(
+ requestedUri: string,
+ echoed: unknown | 'omit'
+): Promise<{ requested: string[]; response: DcrRegistrationResponse }> {
+ const discovery = await atlassianDiscovery()
+ const request = buildDcrRequest(discovery, {
+ clientMode: 'public',
+ redirectUris: [requestedUri],
+ })
+ const body: Record<string, unknown> = { ...DCR_PUBLIC_REGISTRATION_RESPONSE }
+ if (echoed === 'omit') delete body.redirect_uris
+ else body.redirect_uris = echoed
+ const endpoint = discovery.endpoints.registration
+ if (!endpoint) throw new Error('fixture AS has no registration endpoint')
+ const { transport } = makeDcrTransport({
+ registrationEndpoint: endpoint,
+ responseJson: JSON.stringify(body),
+ })
+ const outcome = await registerDynamicClient(
+ { transport, resolveDns: PUBLIC_IP },
+ endpoint,
+ request
+ )
+ if (!outcome.ok) throw new Error(`registration failed: ${outcome.error.kind}`)
+ return { requested: request.redirect_uris, response: outcome.response }
+}
+
+describe('verifyDcrRedirectUris — per-server (required, exact)', () => {
+ it('exact echo → ok', async () => {
+ const r = await registeredResponse(PER_SERVER_URI, [PER_SERVER_URI])
+ expect(verifyDcrRedirectUris({ variant: 'per-server', ...r })).toEqual({ ok: true })
+ })
+
+ it('absent → redirect_uris_missing', async () => {
+ const r = await registeredResponse(PER_SERVER_URI, 'omit')
+ expect(verifyDcrRedirectUris({ variant: 'per-server', ...r })).toEqual({
+ ok: false,
+ reason: 'redirect_uris_missing',
+ })
+ })
+
+ const mismatches: Array<{ label: string; echoed: unknown }> = [
+ { label: 'the shared URI instead', echoed: [SHARED_URI] },
+ {
+ label: 'another installation nonce',
+ echoed: [PER_SERVER_URI.replace(NONCE, '1'.repeat(8) + NONCE.slice(8))],
+ },
+ { label: 'a normalized-looking variant (trailing slash)', echoed: [`${PER_SERVER_URI}/`] },
+ { label: 'a case-changed variant', echoed: [PER_SERVER_URI.toUpperCase()] },
+ { label: 'an extra URI', echoed: [PER_SERVER_URI, SHARED_URI] },
+ { label: 'the right URI duplicated', echoed: [PER_SERVER_URI, PER_SERVER_URI] },
+ { label: 'an empty list', echoed: [] },
+ { label: 'a bare string', echoed: PER_SERVER_URI },
+ { label: 'a non-string element', echoed: [42] },
+ ]
+ for (const { label, echoed } of mismatches) {
+ it(`${label} → redirect_uris_mismatch`, async () => {
+ const r = await registeredResponse(PER_SERVER_URI, echoed)
+ expect(verifyDcrRedirectUris({ variant: 'per-server', ...r })).toEqual({
+ ok: false,
+ reason: 'redirect_uris_mismatch',
+ })
+ })
+ }
+})
+
+describe('verifyDcrRedirectUris — per-server treats null as missing', () => {
+ it('null → redirect_uris_missing', async () => {
+ const r = await registeredResponse(PER_SERVER_URI, null)
+ expect(verifyDcrRedirectUris({ variant: 'per-server', ...r })).toEqual({
+ ok: false,
+ reason: 'redirect_uris_missing',
+ })
+ })
+})
+
+describe('verifyDcrRedirectUris — shared (tolerates absence, rejects a different echo)', () => {
+ it('null → ok (same as absent)', async () => {
+ const r = await registeredResponse(SHARED_URI, null)
+ expect(verifyDcrRedirectUris({ variant: 'shared', ...r })).toEqual({ ok: true })
+ })
+
+ it('absent → ok (ASes that do not echo keep working)', async () => {
+ const r = await registeredResponse(SHARED_URI, 'omit')
+ expect(verifyDcrRedirectUris({ variant: 'shared', ...r })).toEqual({ ok: true })
+ })
+
+ it('exact echo → ok', async () => {
+ const r = await registeredResponse(SHARED_URI, [SHARED_URI])
+ expect(verifyDcrRedirectUris({ variant: 'shared', ...r })).toEqual({ ok: true })
+ })
+
+ it('present and different → redirect_uris_mismatch', async () => {
+ const r = await registeredResponse(SHARED_URI, ['https://attacker.example/cb'])
+ expect(verifyDcrRedirectUris({ variant: 'shared', ...r })).toEqual({
+ ok: false,
+ reason: 'redirect_uris_mismatch',
+ })
+ })
+})
diff --git a/control-api/test/oauth.discovery.properties.test.ts b/control-api/test/oauth.discovery.properties.test.ts
index 1c92718ae..dede253ce 100644
--- a/control-api/test/oauth.discovery.properties.test.ts
+++ b/control-api/test/oauth.discovery.properties.test.ts
@@ -4,6 +4,7 @@ import {
type AuthorizationServerMetadata,
type ProtectedResourceMetadata,
type RegistrationMode,
+ advertisesIssBinding,
deriveQuirks,
selectRegistrationMode,
} from '../src/oauth/discovery.js'
@@ -17,13 +18,17 @@ import { PILOTS } from './fixtures/remoteOAuthDiscovery.js'
// Reference implementation of the normative order, kept deliberately independent
// of the production one so the property catches a reordering in either direction.
+// Without RFC 9207 CIMD is never a candidate (its single platform identity can only
+// list the shared callback, which relies on `iss`).
function expectedMode(input: {
hasPreRegisteredClient: boolean
cimdSupported: boolean
tokenEndpointAuthMethods: string[]
hasRegistrationEndpoint: boolean
+ issBindingSupported: boolean
}): RegistrationMode {
if (input.hasPreRegisteredClient) return 'pre-registered'
+ if (!input.issBindingSupported) return input.hasRegistrationEndpoint ? 'dcr' : 'manual'
if (input.cimdSupported && input.tokenEndpointAuthMethods.includes('none')) return 'cimd'
if (input.hasRegistrationEndpoint) return 'dcr'
return 'manual'
@@ -39,17 +44,20 @@ describe('selectRegistrationMode — order pre-reg > CIMD > DCR > manual (T2)',
fc.boolean(),
authMethodArb,
fc.boolean(),
+ fc.boolean(),
(
hasPreRegisteredClient,
cimdSupported,
tokenEndpointAuthMethods,
- hasRegistrationEndpoint
+ hasRegistrationEndpoint,
+ issBindingSupported
) => {
const input = {
hasPreRegisteredClient,
cimdSupported,
tokenEndpointAuthMethods,
hasRegistrationEndpoint,
+ issBindingSupported,
}
expect(selectRegistrationMode(input)).toBe(expectedMode(input))
}
@@ -58,20 +66,55 @@ describe('selectRegistrationMode — order pre-reg > CIMD > DCR > manual (T2)',
})
it('pre-registered wins over everything else', () => {
+ fc.assert(
+ fc.property(
+ fc.boolean(),
+ authMethodArb,
+ fc.boolean(),
+ fc.boolean(),
+ (cimd, methods, reg, iss) => {
+ expect(
+ selectRegistrationMode({
+ hasPreRegisteredClient: true,
+ cimdSupported: cimd,
+ tokenEndpointAuthMethods: methods,
+ hasRegistrationEndpoint: reg,
+ issBindingSupported: iss,
+ })
+ ).toBe('pre-registered')
+ }
+ )
+ )
+ })
+
+ it('never selects CIMD without RFC 9207', () => {
fc.assert(
fc.property(fc.boolean(), authMethodArb, fc.boolean(), (cimd, methods, reg) => {
expect(
selectRegistrationMode({
- hasPreRegisteredClient: true,
+ hasPreRegisteredClient: false,
cimdSupported: cimd,
tokenEndpointAuthMethods: methods,
hasRegistrationEndpoint: reg,
+ issBindingSupported: false,
})
- ).toBe('pre-registered')
+ ).not.toBe('cimd')
})
)
})
+ it('CIMD-only AS (no registration endpoint) without RFC 9207 → manual', () => {
+ expect(
+ selectRegistrationMode({
+ hasPreRegisteredClient: false,
+ cimdSupported: true,
+ tokenEndpointAuthMethods: ['none'],
+ hasRegistrationEndpoint: false,
+ issBindingSupported: false,
+ })
+ ).toBe('manual')
+ })
+
it('CIMD requires BOTH cimdSupported AND `none` (never one alone)', () => {
// cimdSupported without `none` → not cimd.
expect(
@@ -80,6 +123,7 @@ describe('selectRegistrationMode — order pre-reg > CIMD > DCR > manual (T2)',
cimdSupported: true,
tokenEndpointAuthMethods: ['client_secret_post'],
hasRegistrationEndpoint: true,
+ issBindingSupported: true,
})
).toBe('dcr')
// `none` without cimdSupported → not cimd.
@@ -89,11 +133,13 @@ describe('selectRegistrationMode — order pre-reg > CIMD > DCR > manual (T2)',
cimdSupported: false,
tokenEndpointAuthMethods: ['none'],
hasRegistrationEndpoint: true,
+ issBindingSupported: true,
})
).toBe('dcr')
})
- it('the 4 real pilots all select CIMD', () => {
+ it('the 4 real pilots: CIMD only where the AS returns `iss` (Linear, Sentry)', () => {
+ const expected = { notion: 'dcr', linear: 'cimd', sentry: 'cimd', canva: 'dcr' } as const
for (const key of ['notion', 'linear', 'sentry', 'canva'] as const) {
const as = JSON.parse(PILOTS[key].as.json) as AuthorizationServerMetadata
expect(
@@ -102,8 +148,9 @@ describe('selectRegistrationMode — order pre-reg > CIMD > DCR > manual (T2)',
cimdSupported: as.client_id_metadata_document_supported === true,
tokenEndpointAuthMethods: as.token_endpoint_auth_methods_supported ?? [],
hasRegistrationEndpoint: typeof as.registration_endpoint === 'string',
+ issBindingSupported: advertisesIssBinding(as),
})
- ).toBe('cimd')
+ ).toBe(expected[key])
}
})
})
diff --git a/control-api/test/oauth.discovery.sameSite.test.ts b/control-api/test/oauth.discovery.sameSite.test.ts
new file mode 100644
index 000000000..5c1af8901
--- /dev/null
+++ b/control-api/test/oauth.discovery.sameSite.test.ts
@@ -0,0 +1,293 @@
+import { describe, expect, it, vi } from 'vitest'
+import fc from 'fast-check'
+import type { PinnedTransport } from '../src/http/pinnedFetch.js'
+import {
+ type DiscoveryDeps,
+ checkAsEndpointsSameSite,
+ discoverRemoteOAuth,
+ registrableSite,
+} from '../src/oauth/discovery.js'
+import {
+ ATLASSIAN_V2_AS_JSON,
+ ATLASSIAN_V2_PILOT,
+ DROPBOX_PILOT,
+ PILOTS,
+ type PilotFixture,
+ VERCEL_PILOT,
+ makeDiscoveryTransport,
+} from './fixtures/remoteOAuthDiscovery.js'
+
+/**
+ * Without RFC 9207 the callback cannot tell which AS produced a code, so discovery
+ * requires every AS endpoint to share the issuer's registrable domain (PSL, private
+ * section included). With RFC 9207 the rule does not apply.
+ *
+ * The honest cases run on real probe bytes (Atlassian v2, Dropbox, Vercel — no 9207).
+ * The hostile cases cannot be probed (no real AS serves them), so they are the real
+ * Atlassian bytes with ONE documented field swapped, the way a malicious metadata
+ * document would borrow an honest AS's endpoints.
+ */
+
+const PUBLIC_IP = ['93.184.216.34']
+
+interface RecordedRequest {
+ url: string
+ method?: string
+}
+
+/** Wrap a fixture transport, recording every request that reaches the socket layer. */
+function recording(base: PinnedTransport): {
+ transport: PinnedTransport
+ calls: RecordedRequest[]
+} {
+ const calls: RecordedRequest[] = []
+ const transport: PinnedTransport = async input => {
+ calls.push({ url: input.url, method: input.method })
+ return base(input)
+ }
+ return { transport, calls }
+}
+
+function deps(transport: PinnedTransport): DiscoveryDeps {
+ return { transport, resolveDns: vi.fn(async () => PUBLIC_IP) }
+}
+
+/** The real Atlassian v2 pilot with its AS metadata rewritten by `mutate`. */
+function atlassianWith(mutate: (as: Record<string, unknown>) => void): PilotFixture {
+ const as = JSON.parse(ATLASSIAN_V2_AS_JSON) as Record<string, unknown>
+ mutate(as)
+ return { ...ATLASSIAN_V2_PILOT, as: { ...ATLASSIAN_V2_PILOT.as, json: JSON.stringify(as) } }
+}
+
+async function discover(pilot: PilotFixture) {
+ const { transport, calls } = recording(makeDiscoveryTransport(pilot))
+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, deps(transport))
+ return { outcome, calls }
+}
+
+describe('discovery same-site rule — real ASes without RFC 9207', () => {
+ it('Atlassian v2 (CIMD + DCR, all on atlassian.com) → DCR, never CIMD', async () => {
+ const { outcome } = await discover(ATLASSIAN_V2_PILOT)
+ expect(outcome.ok).toBe(true)
+ if (!outcome.ok) return
+ expect(outcome.result.issForCallback).toBeUndefined()
+ expect(outcome.result.registrationMode).toBe('dcr')
+ })
+
+ it('Vercel (token on api.vercel.com, issuer vercel.com) is one site → accepted', async () => {
+ const { outcome } = await discover(VERCEL_PILOT)
+ expect(outcome.ok).toBe(true)
+ if (outcome.ok) expect(outcome.result.registrationMode).toBe('dcr')
+ })
+
+ it('Dropbox (token on api.dropboxapi.com, issuer www.dropbox.com) → as_endpoints_cross_site', async () => {
+ const { outcome, calls } = await discover(DROPBOX_PILOT)
+ expect(outcome.ok).toBe(false)
+ if (!outcome.ok) {
+ expect(outcome.error).toMatchObject({ kind: 'as_endpoints_cross_site', field: 'token' })
+ }
+ // Discovery never reaches the registration endpoint (nor POSTs anything).
+ expect(calls.some(c => c.url === 'https://www.dropbox.com/oauth2/register')).toBe(false)
+ expect(calls.some(c => c.method === 'POST')).toBe(false)
+ })
+})
+
+describe('discovery same-site rule — mixed metadata (mix-up via a borrowed AS)', () => {
+ it('authorize + registration on the honest AS, token on another site → rejected before any registration', async () => {
+ const pilot = atlassianWith(as => {
+ as.token_endpoint = 'https://attacker.example/oauth/token'
+ })
+ const { outcome, calls } = await discover(pilot)
+ expect(outcome.ok).toBe(false)
+ if (!outcome.ok) {
+ expect(outcome.error).toMatchObject({ kind: 'as_endpoints_cross_site', field: 'token' })
+ }
+ expect(calls.some(c => c.url.includes('/dcr/register'))).toBe(false)
+ expect(calls.some(c => c.method === 'POST')).toBe(false)
+ })
+
+ it('the same mixed metadata WITH RFC 9207 is not subject to the rule (unchanged behaviour)', async () => {
+ const pilot = atlassianWith(as => {
+ as.token_endpoint = 'https://attacker.example/oauth/token'
+ as.authorization_response_iss_parameter_supported = true
+ })
+ const { outcome } = await discover(pilot)
+ expect(outcome.ok).toBe(true)
+ if (outcome.ok) {
+ expect(outcome.result.issForCallback).toBe(JSON.parse(ATLASSIAN_V2_AS_JSON).issuer)
+ expect(outcome.result.endpoints.token).toBe('https://attacker.example/oauth/token')
+ }
+ })
+
+ it('registration endpoint on another site → rejected', async () => {
+ const { outcome } = await discover(
+ atlassianWith(as => {
+ as.registration_endpoint = 'https://attacker.example/register'
+ })
+ )
+ expect(!outcome.ok && outcome.error).toMatchObject({
+ kind: 'as_endpoints_cross_site',
+ field: 'registration',
+ })
+ })
+
+ it('revocation endpoint on another site → rejected', async () => {
+ const { outcome } = await discover(
+ atlassianWith(as => {
+ as.revocation_endpoint = 'https://attacker.example/revoke'
+ })
+ )
+ expect(!outcome.ok && outcome.error).toMatchObject({
+ kind: 'as_endpoints_cross_site',
+ field: 'revocation',
+ })
+ })
+
+ it('authorization endpoint on another site → rejected', async () => {
+ const { outcome } = await discover(
+ atlassianWith(as => {
+ as.authorization_endpoint = 'https://attacker.example/authorize'
+ })
+ )
+ expect(!outcome.ok && outcome.error).toMatchObject({
+ kind: 'as_endpoints_cross_site',
+ field: 'authorization',
+ })
+ })
+
+ it('token `https://evil.com\\@auth.atlassian.com/…` (parser differential) → rejected', async () => {
+ // WHATWG — and therefore the pinned socket — reads the host as `evil.com`. The
+ // site must come from that same parse, never from a second parser over the raw URL.
+ const { outcome } = await discover(
+ atlassianWith(as => {
+ as.token_endpoint = 'https://evil.com\\@auth.atlassian.com/oauth/token'
+ })
+ )
+ expect(outcome.ok).toBe(false)
+ if (!outcome.ok) expect(outcome.error.kind).toBe('as_endpoints_cross_site')
+ })
+
+ it('token endpoint with userinfo on the honest host → rejected', async () => {
+ const { outcome } = await discover(
+ atlassianWith(as => {
+ as.token_endpoint = 'https://user:[email protected]/oauth/token'
+ })
+ )
+ expect(outcome.ok).toBe(false)
+ if (!outcome.ok) {
+ expect(outcome.error).toMatchObject({ kind: 'as_endpoints_cross_site', field: 'token' })
+ }
+ })
+})
+
+describe('registrableSite / checkAsEndpointsSameSite (PSL semantics)', () => {
+ it('private PSL section: two github.io tenants are two sites', () => {
+ expect(registrableSite('https://a.github.io/x')).toBe('a.github.io')
+ expect(
+ checkAsEndpointsSameSite({
+ issuer: 'https://a.github.io',
+ authorization: 'https://a.github.io/authorize',
+ token: 'https://b.github.io/token',
+ })
+ ).toMatchObject({ ok: false, field: 'token' })
+ })
+
+ it('subdomains of one registrable domain are one site (api.vercel.com ~ vercel.com)', () => {
+ expect(
+ checkAsEndpointsSameSite({
+ issuer: 'https://vercel.com',
+ authorization: 'https://vercel.com/oauth/authorize',
+ token: 'https://api.vercel.com/login/oauth/token',
+ registration: 'https://api.vercel.com/login/oauth/register',
+ revocation: 'https://api.vercel.com/login/oauth/token/revoke',
+ })
+ ).toEqual({ ok: true })
+ })
+
+ it('a host that is itself a public suffix has no site; null never equals null', () => {
+ expect(registrableSite('https://github.io/token')).toBeNull()
+ expect(
+ checkAsEndpointsSameSite({
+ issuer: 'https://github.io',
+ authorization: 'https://github.io/authorize',
+ token: 'https://github.io/token',
+ })
+ ).toMatchObject({ ok: false, field: 'issuer' })
+ expect(
+ checkAsEndpointsSameSite({
+ issuer: 'https://honest.example.com',
+ authorization: 'https://honest.example.com/authorize',
+ token: 'https://herokuapp.com/token',
+ })
+ ).toMatchObject({ ok: false, field: 'token' })
+ })
+
+ it('the site is taken from the WHATWG host, the one the pinned socket connects to', () => {
+ expect(registrableSite('https://evil.com\\@honest.com/token')).toBe('evil.com')
+ // WHATWG decodes these hosts to `api.vercel.com`; `tldts` over the raw string does
+ // not, so only the hostname-first parse yields the site the request really goes to.
+ expect(registrableSite('https://api%2Evercel.com/token')).toBe('vercel.com')
+ expect(registrableSite('https://api\u3002vercel.com/token')).toBe('vercel.com')
+ })
+
+ it('any userinfo, an IP literal or an unparsable URL has no site', () => {
+ expect(registrableSite('https://[email protected]/token')).toBeNull()
+ expect(registrableSite('https://user:[email protected]/token')).toBeNull()
+ expect(registrableSite('https://93.184.216.34/token')).toBeNull()
+ expect(registrableSite('not a url')).toBeNull()
+ })
+})
+
+describe('I3 — without RFC 9207 discovery never selects CIMD (T2, through discoverRemoteOAuth)', () => {
+ // Arbitrary AS capabilities layered on the real Notion bytes. The `iss` flag is
+ // fuzzed over non-boolean truthy values too: only a literal `true` is an advertisement.
+ const issFlagArb = fc.constantFrom<unknown>(undefined, true, false, 'true', 1)
+ const cimdFlagArb = fc.constantFrom<unknown>(undefined, true, false)
+ const methodsArb = fc.subarray(['none', 'client_secret_basic', 'client_secret_post'])
+
+ it('registrationMode is cimd only when the AS literally advertises iss === true', async () => {
+ await fc.assert(
+ fc.asyncProperty(
+ issFlagArb,
+ cimdFlagArb,
+ methodsArb,
+ fc.boolean(),
+ async (issFlag, cimdFlag, methods, hasRegistration) => {
+ const as = JSON.parse(PILOTS.notion.as.json) as Record<string, unknown>
+ delete as.authorization_response_iss_parameter_supported
+ delete as.client_id_metadata_document_supported
+ if (issFlag !== undefined) as.authorization_response_iss_parameter_supported = issFlag
+ if (cimdFlag !== undefined) as.client_id_metadata_document_supported = cimdFlag
+ as.token_endpoint_auth_methods_supported = methods
+ if (!hasRegistration) delete as.registration_endpoint
+ const pilot: PilotFixture = {
+ ...PILOTS.notion,
+ as: { ...PILOTS.notion.as, json: JSON.stringify(as) },
+ }
+ const outcome = await discoverRemoteOAuth(
+ pilot.mcpUrl,
+ deps(makeDiscoveryTransport(pilot))
+ )
+ expect(outcome.ok).toBe(true)
+ if (!outcome.ok) return
+ const iss = issFlag === true
+ expect(outcome.result.issForCallback !== undefined).toBe(iss)
+ if (!iss) expect(outcome.result.registrationMode).not.toBe('cimd')
+ const expectedCimd = iss && cimdFlag === true && methods.includes('none')
+ expect(outcome.result.registrationMode === 'cimd').toBe(expectedCimd)
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+})
+
+// Guards the recording helper itself: a transport that never records would make the
+// "no POST / no registration fetch" assertions above vacuous.
+describe('recording transport sanity', () => {
+ it('records the discovery GETs', async () => {
+ const { calls } = await discover(ATLASSIAN_V2_PILOT)
+ expect(calls.length).toBeGreaterThan(0)
+ expect(calls.every(c => c.method !== 'POST')).toBe(true)
+ })
+})
diff --git a/control-api/test/oauth.discovery.test.ts b/control-api/test/oauth.discovery.test.ts
index cb1252df6..214cd7176 100644
--- a/control-api/test/oauth.discovery.test.ts
+++ b/control-api/test/oauth.discovery.test.ts
@@ -29,16 +29,20 @@ function deps(transport: PinnedTransport, resolveDns = publicDns()): DiscoveryDe
return { transport, resolveDns }
}
-describe('discoverRemoteOAuth — 4 CIMD pilots (T1 real fixtures)', () => {
+describe('discoverRemoteOAuth — 4 CIMD-capable pilots (T1 real fixtures)', () => {
+ // All 4 advertise CIMD + `none`, but CIMD is only offered when the AS also returns
+ // `iss` (RFC 9207): Linear and Sentry do; Notion and Canva do not and fall back to
+ // their registration endpoint (DCR).
+ const expectedMode = { notion: 'dcr', linear: 'cimd', sentry: 'cimd', canva: 'dcr' } as const
for (const key of ['notion', 'linear', 'sentry', 'canva'] as const) {
const pilot = PILOTS[key]
- it(`${key}: resolves PRM→AS, selects CIMD, pins endpoints`, async () => {
+ it(`${key}: resolves PRM→AS, selects ${expectedMode[key]}, pins endpoints`, async () => {
const outcome = await discoverRemoteOAuth(pilot.mcpUrl, deps(makeDiscoveryTransport(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')
+ expect(r.registrationMode).toBe(expectedMode[key])
+ expect(r.issForCallback !== undefined).toBe(expectedMode[key] === '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.
@@ -52,13 +56,19 @@ describe('discoverRemoteOAuth — 4 CIMD pilots (T1 real fixtures)', () => {
})
}
- it('sentry: exposes issForCallback (RFC 9207); others do not', async () => {
+ it('sentry and linear expose issForCallback (RFC 9207); notion does not', async () => {
const sentry = await discoverRemoteOAuth(
PILOTS.sentry.mcpUrl,
deps(makeDiscoveryTransport(PILOTS.sentry))
)
expect(sentry.ok && sentry.result.issForCallback).toBe('https://mcp.sentry.dev')
+ const linear = await discoverRemoteOAuth(
+ PILOTS.linear.mcpUrl,
+ deps(makeDiscoveryTransport(PILOTS.linear))
+ )
+ expect(linear.ok && linear.result.issForCallback).toBe('https://mcp.linear.app')
+
const notion = await discoverRemoteOAuth(
PILOTS.notion.mcpUrl,
deps(makeDiscoveryTransport(PILOTS.notion))
diff --git a/control-api/test/oauth.remoteCallback.test.ts b/control-api/test/oauth.remoteCallback.test.ts
new file mode 100644
index 000000000..5659bd0a2
--- /dev/null
+++ b/control-api/test/oauth.remoteCallback.test.ts
@@ -0,0 +1,250 @@
+import { describe, expect, it, vi } from 'vitest'
+import { buildCimdDocument } from '../src/oauth/cimd.js'
+import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'
+import {
+ InvalidRemoteRedirectUriInputError,
+ REMOTE_CALLBACK_PATH,
+ type RemoteRedirectUriInput,
+ buildRemoteRedirectUri,
+ isValidInstallNonce,
+ isValidRemoteServerNameSegment,
+ remoteCallbackVariant,
+} from '../src/oauth/remoteCallback.js'
+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
+import {
+ ATLASSIAN_V2_PILOT,
+ PILOTS,
+ type PilotFixture,
+ makeDiscoveryTransport,
+} from './fixtures/remoteOAuthDiscovery.js'
+
+const ORIGIN = 'https://evenfire.example.com'
+const NONCE = '3f1c2b7e-9a4d-4c1e-8b2a-6d5e4f3a2b1c'
+
+async function discovered(pilot: PilotFixture): Promise<DiscoveryResult> {
+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, {
+ transport: makeDiscoveryTransport(pilot),
+ resolveDns: vi.fn(async () => ['93.184.216.34']),
+ })
+ if (!outcome.ok) throw new Error(`discovery failed: ${outcome.error.kind}`)
+ return outcome.result
+}
+
+describe('remoteCallbackVariant', () => {
+ it('non-empty issForCallback → shared; absent, empty or non-string → per-server', () => {
+ expect(remoteCallbackVariant({ issForCallback: 'https://mcp.sentry.dev' })).toBe('shared')
+ expect(remoteCallbackVariant({})).toBe('per-server')
+ expect(remoteCallbackVariant({ issForCallback: undefined })).toBe('per-server')
+ expect(remoteCallbackVariant({ issForCallback: '' })).toBe('per-server')
+ expect(remoteCallbackVariant({ issForCallback: true })).toBe('per-server')
+ expect(remoteCallbackVariant({ issForCallback: 1 })).toBe('per-server')
+ })
+})
+
+// Partial (unit-level) coverage of I15: the variant derived from the block the real
+// producer builds, and stable across a JSON round-trip. The round-trip is NOT the CR the
+// install writes and reads back from the apiserver — that composability
+// (variant(install block) === variant(written CR)) is asserted with the install saga in
+// phase 2.
+describe('I15 (partial, unit) — remoteCallbackVariant on the block the install builds', () => {
+ const cases: Array<{ pilot: PilotFixture; variant: 'shared' | 'per-server' }> = [
+ { pilot: PILOTS.sentry, variant: 'shared' },
+ { pilot: PILOTS.linear, variant: 'shared' },
+ { pilot: PILOTS.notion, variant: 'per-server' },
+ { pilot: ATLASSIAN_V2_PILOT, variant: 'per-server' },
+ ]
+ for (const { pilot, variant } of cases) {
+ it(`${pilot.name}: ${variant} on the install block (JSON round-trip stable)`, async () => {
+ const block = buildRemoteOAuthSpec(await discovered(pilot), {
+ clientMode: 'public',
+ grantScope: 'user',
+ dynamicClientId: 'client-from-as',
+ })
+ expect(remoteCallbackVariant(block)).toBe(variant)
+ // Round-trip only; not a substitute for reading the written CR.
+ const fromCr = JSON.parse(JSON.stringify(block)) as Record<string, unknown>
+ expect(remoteCallbackVariant(fromCr)).toBe(remoteCallbackVariant(block))
+ })
+ }
+})
+
+describe('buildRemoteRedirectUri — decision table', () => {
+ it('shared → the stable shared path (any mode)', () => {
+ expect(buildRemoteRedirectUri({ origin: ORIGIN, variant: 'shared' })).toBe(
+ `${ORIGIN}/api/v1/oauth-callback/remote`
+ )
+ expect(REMOTE_CALLBACK_PATH).toBe('/api/v1/oauth-callback/remote')
+ })
+
+ it('per-server DCR → /remote/<serverName>/<installNonce>', () => {
+ expect(
+ buildRemoteRedirectUri({
+ origin: ORIGIN,
+ variant: 'per-server',
+ mode: 'dcr',
+ serverName: 'atlassian',
+ installNonce: NONCE,
+ })
+ ).toBe(`${ORIGIN}/api/v1/oauth-callback/remote/atlassian/${NONCE}`)
+ })
+
+ it('per-server pre-registered → /remote/<serverName>', () => {
+ expect(
+ buildRemoteRedirectUri({
+ origin: ORIGIN,
+ variant: 'per-server',
+ mode: 'pre-registered',
+ serverName: 'slack',
+ })
+ ).toBe(`${ORIGIN}/api/v1/oauth-callback/remote/slack`)
+ })
+
+ it('per-server accepts a bare origin with an explicit non-default port', () => {
+ expect(
+ buildRemoteRedirectUri({
+ origin: 'http://localhost:8080',
+ variant: 'per-server',
+ mode: 'pre-registered',
+ serverName: 'slack',
+ })
+ ).toBe('http://localhost:8080/api/v1/oauth-callback/remote/slack')
+ })
+
+ it('shared keeps its historical origin handling (no origin validation)', () => {
+ expect(buildRemoteRedirectUri({ origin: `${ORIGIN}/base`, variant: 'shared' })).toBe(
+ `${ORIGIN}/base/api/v1/oauth-callback/remote`
+ )
+ })
+
+ it('the CIMD document lists exactly the shared URI from the same builder', () => {
+ expect(buildCimdDocument(ORIGIN).redirect_uris).toEqual([
+ buildRemoteRedirectUri({ origin: ORIGIN, variant: 'shared' }),
+ ])
+ })
+
+ const invalid: Array<{ label: string; input: unknown }> = [
+ {
+ label: 'per-server CIMD (no per-server URI exists)',
+ input: { origin: ORIGIN, variant: 'per-server', mode: 'cimd', serverName: 'notion' },
+ },
+ {
+ label: 'per-server DCR without a nonce',
+ input: { origin: ORIGIN, variant: 'per-server', mode: 'dcr', serverName: 'notion' },
+ },
+ {
+ label: 'per-server pre-registered WITH a nonce',
+ input: {
+ origin: ORIGIN,
+ variant: 'per-server',
+ mode: 'pre-registered',
+ serverName: 'slack',
+ installNonce: NONCE,
+ },
+ },
+ {
+ label: 'uppercase UUID nonce',
+ input: {
+ origin: ORIGIN,
+ variant: 'per-server',
+ mode: 'dcr',
+ serverName: 'notion',
+ installNonce: NONCE.toUpperCase(),
+ },
+ },
+ {
+ label: 'per-server without an origin',
+ input: { origin: '', variant: 'per-server', mode: 'pre-registered', serverName: 'slack' },
+ },
+ ...[
+ `${ORIGIN}/`,
+ `${ORIGIN}/base`,
+ `${ORIGIN}?q=1`,
+ `${ORIGIN}#f`,
+ 'https://user:[email protected]',
+ 'https://Evenfire.Example.com',
+ 'https://evenfire.example.com:443',
+ 'evenfire.example.com',
+ 'not a url',
+ ].map(origin => ({
+ label: `per-server with a non-bare origin ${JSON.stringify(origin)}`,
+ input: { origin, variant: 'per-server', mode: 'pre-registered', serverName: 'slack' },
+ })),
+ { label: 'unknown variant', input: { origin: ORIGIN, variant: 'other' } },
+ ]
+ for (const { label, input } of invalid) {
+ it(`throws: ${label}`, () => {
+ expect(() => buildRemoteRedirectUri(input as RemoteRedirectUriInput)).toThrow(
+ InvalidRemoteRedirectUriInputError
+ )
+ })
+ }
+
+ for (const serverName of [
+ '..',
+ '%2F',
+ 'a/b',
+ 'a%2Fb',
+ 'Notion',
+ 'my_server',
+ '-lead',
+ 'trail-',
+ '',
+ 'a'.repeat(64),
+ ]) {
+ it(`throws on a non-RFC-1123 serverName ${JSON.stringify(serverName)}`, () => {
+ expect(() =>
+ buildRemoteRedirectUri({
+ origin: ORIGIN,
+ variant: 'per-server',
+ mode: 'pre-registered',
+ serverName,
+ })
+ ).toThrow(InvalidRemoteRedirectUriInputError)
+ })
+ }
+})
+
+describe('segment validators', () => {
+ it('isValidRemoteServerNameSegment accepts RFC 1123 labels only', () => {
+ for (const ok of ['notion', 'a', 'atlassian-v2', 'a'.repeat(63), '0abc']) {
+ expect(isValidRemoteServerNameSegment(ok)).toBe(true)
+ }
+ for (const bad of [
+ '..',
+ '.',
+ '%2F',
+ '%2e%2e',
+ '%252F',
+ 'a/b',
+ 'A',
+ 'a_b',
+ '-a',
+ 'a-',
+ '',
+ 'a'.repeat(64),
+ 'a\n',
+ 42,
+ undefined,
+ ]) {
+ expect(isValidRemoteServerNameSegment(bad)).toBe(false)
+ }
+ })
+
+ it('isValidInstallNonce accepts only canonical lowercase UUIDs', () => {
+ expect(isValidInstallNonce(NONCE)).toBe(true)
+ expect(isValidInstallNonce(crypto.randomUUID())).toBe(true)
+ for (const bad of [
+ NONCE.toUpperCase(),
+ `${NONCE}\n`,
+ `{${NONCE}}`,
+ NONCE.replace(/-/g, ''),
+ '..',
+ '%2F',
+ '',
+ undefined,
+ 42,
+ ]) {
+ expect(isValidInstallNonce(bad)).toBe(false)
+ }
+ })
+})
diff --git a/control-api/test/routes.adminRemoteMcp.test.ts b/control-api/test/routes.adminRemoteMcp.test.ts
index c6439a4da..452a9a540 100644
--- a/control-api/test/routes.adminRemoteMcp.test.ts
+++ b/control-api/test/routes.adminRemoteMcp.test.ts
@@ -131,6 +131,20 @@ let rfc9207Result: DiscoveryResult
// real producer (T1) by documented substitution of the Notion PRM's
// `bearer_methods_supported` to `["body"]` — the only field changed.
let bodyBearerResult: DiscoveryResult
+// Real Linear DiscoveryResult (T1): the 2026-09-29 Linear probe advertises CIMD + `none`
+// AND RFC 9207, so it still resolves to CIMD on the shared callback.
+let linearResult: DiscoveryResult
+// An AS that genuinely offers NO registration endpoint, derived from the real producer
+// (T1) by documented subtraction: the real Linear pilot minus `registration_endpoint`.
+// Linear keeps CIMD + RFC 9207, so discovery resolves to `cimd`, never `dcr`.
+let noDcrResult: DiscoveryResult
+
+/** Documented T1 subtraction: drop `registration_endpoint` from a pilot's AS metadata. */
+function withoutRegistrationEndpoint<T extends { as: { json: string } }>(pilot: T): T {
+ const as = JSON.parse(pilot.as.json)
+ delete as.registration_endpoint
+ return { ...pilot, as: { ...pilot.as, json: JSON.stringify(as) } }
+}
/**
* Documented T1 substitution: add `authorization_response_iss_parameter_supported`
@@ -190,6 +204,22 @@ beforeAll(async () => {
if (!bodyBearerOutcome.ok)
throw new Error(`body-bearer fixture discovery failed: ${bodyBearerOutcome.error.kind}`)
bodyBearerResult = bodyBearerOutcome.result
+
+ const linearOutcome = await actual.discoverRemoteOAuth(PILOTS.linear.mcpUrl, {
+ transport: makeDiscoveryTransport(PILOTS.linear),
+ resolveDns: async () => ['93.184.216.34'],
+ })
+ if (!linearOutcome.ok)
+ throw new Error(`linear fixture discovery failed: ${linearOutcome.error.kind}`)
+ linearResult = linearOutcome.result
+
+ const noDcrOutcome = await actual.discoverRemoteOAuth(PILOTS.linear.mcpUrl, {
+ transport: makeDiscoveryTransport(withoutRegistrationEndpoint(PILOTS.linear)),
+ resolveDns: async () => ['93.184.216.34'],
+ })
+ if (!noDcrOutcome.ok)
+ throw new Error(`no-DCR fixture discovery failed: ${noDcrOutcome.error.kind}`)
+ noDcrResult = noDcrOutcome.result
})
beforeEach(() => {
@@ -210,20 +240,41 @@ describe('POST /admin/mcp-servers/remote/discover (dry-run)', () => {
expect(discoverRemoteOAuth).not.toHaveBeenCalled()
})
- it('returns the "Detected" prefill for a CIMD server → 200', async () => {
- mockDiscovery(notionResult)
+ it('returns the "Detected" prefill for a CIMD server (Linear: CIMD + RFC 9207) → 200', async () => {
+ expect(linearResult.registrationMode).toBe('cimd')
+ mockDiscovery(linearResult)
const res = await request(makeApp(gatewayWithContext()))
.post('/admin/mcp-servers/remote/discover')
- .send({ baseUrl: 'https://mcp.notion.com/mcp' })
+ .send({ baseUrl: 'https://mcp.linear.app/mcp' })
expect(res.status).toBe(200)
expect(res.body.detected.registrationMode).toBe('cimd')
- expect(res.body.detected.endpoints.token).toBe('https://mcp.notion.com/token')
- expect(res.body.detected.resource).toBe('https://mcp.notion.com')
+ expect(res.body.detected.endpoints.token).toBe('https://mcp.linear.app/token')
+ expect(res.body.detected.resource).toBe('https://mcp.linear.app/mcp')
+ expect(res.body.detected.issForCallback).toBe('https://mcp.linear.app')
expect(res.body.detected.quirks).toEqual({ bearerInBody: false, supportsRefresh: true })
// No DCR marker for a CIMD server.
expect(res.body.detected.dcr).toBeUndefined()
})
+ it('CIMD-capable AS WITHOUT RFC 9207 (Notion) is detected as DCR, not CIMD → 200', async () => {
+ // Notion advertises CIMD + `none` but no `iss`: CIMD's single platform identity can
+ // only list the shared callback, so discovery falls back to its registration endpoint.
+ expect(notionResult.registrationMode).toBe('dcr')
+ mockDiscovery(notionResult)
+ const res = await request(makeApp(gatewayWithContext()))
+ .post('/admin/mcp-servers/remote/discover')
+ .send({ baseUrl: 'https://mcp.notion.com/mcp' })
+ expect(res.status).toBe(200)
+ expect(res.body.detected.registrationMode).toBe('dcr')
+ expect(res.body.detected.issForCallback).toBeUndefined()
+ expect(res.body.detected.endpoints.token).toBe('https://mcp.notion.com/token')
+ expect(res.body.detected.dcr).toEqual({
+ available: true,
+ clientMode: 'public',
+ supportsRefresh: true,
+ })
+ })
+
it('marks DCR mode available (C2) with resolved clientMode + supportsRefresh → 200', async () => {
mockDiscovery({ ...notionResult, registrationMode: 'dcr' })
const res = await request(makeApp(gatewayWithContext()))
@@ -447,13 +498,15 @@ describe('POST /admin/mcp-servers/remote (install saga)', () => {
})
it('rejects mode "dcr" when server-side discovery resolves a non-DCR AS → 400 mode_unsupported', async () => {
- // The AS actually offers CIMD (not DCR); the operator's "dcr" request loses.
- mockDiscovery(notionResult)
+ // The AS offers CIMD but no registration endpoint; the operator's "dcr" request loses.
+ expect(noDcrResult.endpoints.registration).toBeUndefined()
+ expect(noDcrResult.registrationMode).toBe('cimd')
+ mockDiscovery(noDcrResult)
const gw = gatewayWithContext('ctx-a')
const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
serverName: 'stripe-remote',
contextRef: 'ctx-a',
- baseUrl: 'https://mcp.notion.com/mcp',
+ baseUrl: 'https://mcp.linear.app/mcp',
mode: 'dcr',
})
expect(res.status).toBe(400)