Skip to content

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

TypeScript
45.7 KB
Raw Blame
import { getDomain } from 'tldts'
import {
  type PinnedFetchError,
  type PinnedResponse,
  type PinnedTransport,
  pinnedFetch,
} from '../http/pinnedFetch.js'
import {
  type DnsResolver,
  type ValidationError,
  validateOAuthEndpointUrl,
} from '../http/validateMcpServerSpec.js'
import { type Logger, rootLogger } from '../observability/logger.js'
import {
  type AsProfileId,
  ENTRA_TENANT_AUTHORITY_TEMPLATE,
  detectAsProfile,
  isEntraMultiTenantAuthority,
  isEntraTenantAuthority,
  profileHasResourceScope,
  profileScopeViolation,
  profileUnverifiedScopes,
  withProfileScopes,
} from './asProfiles.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
  /**
   * 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
}

/**
 * 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.
 *
 * 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.issBindingSupported &&
    input.cimdSupported &&
    input.tokenEndpointAuthMethods.includes('none')
  ) {
    return 'cimd'
  }
  if (input.hasRegistrationEndpoint) return 'dcr'
  return 'manual'
}

/**
 * The metadata-derived inputs of {@link selectRegistrationMode}, in one place so a
 * caller asking "what would this AS resolve to" reads the metadata exactly as
 * discovery does.
 */
export function registrationModeInputs(
  as: AuthorizationServerMetadata,
  opts: { hasPreRegisteredClient: boolean }
): SelectRegistrationModeInput {
  return {
    hasPreRegisteredClient: opts.hasPreRegisteredClient,
    cimdSupported: as.client_id_metadata_document_supported === true,
    tokenEndpointAuthMethods: as.token_endpoint_auth_methods_supported ?? [],
    hasRegistrationEndpoint: typeof as.registration_endpoint === 'string',
    issBindingSupported: advertisesIssBinding(as),
  }
}

/**
 * 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
}

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.
 *
 * Only the endpoints we send to are checked. `revocation_endpoint` is neither used nor
 * pinned on the CR, so an off-site or malformed one must not block an install; whatever
 * starts sending refresh tokens to it must first pin it on the CR and add it here (and
 * to the runtime coherence rule). 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',
  ]
  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 {
  /** 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 {
  /**
   * Injectable low-level transport for the IP-pinned fetch (H2). Production leaves it
   * undefined (the `node:https` default); tests inject one to assert the socket
   * connects to the validated IP with no real network. Replaces the old `fetchFn`
   * seam — discovery has no production caller before C1.5, so the swap is safe.
   */
  transport?: PinnedTransport
  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 }
  /** 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 }
  /**
   * The authorization server is Microsoft Entra ID's multi-tenant authority, whose
   * metadata declares a templated issuer that can never match. The operator must name
   * the tenant; `tenantAuthorityTemplate` is the URL to complete.
   */
  | {
      kind: 'tenant_required'
      authorizationServer: string
      tenantAuthorityTemplate: string
      detail: string
    }
  /** The operator-supplied authorization server is not accepted for this resource. */
  | { kind: 'authorization_server_override_rejected'; 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
  /** Closed authorization-server profile recognised from the pinned issuer (`asProfiles.ts`). */
  asProfile?: AsProfileId
  /**
   * With a profile, the first derived scope that would mint a token for another API.
   * Informative only: the install validates the operator's final list. May be `''`.
   */
  scopeAudienceViolation?: string
  /** With a profile, the derived GUID-form scopes the platform cannot tie to the MCP host. */
  unverifiedScopes?: string[]
  /** With a profile, the derived scopes name no resource (sign-in scopes only). */
  scopeAudienceMissing?: true
}

/** Default requested scopes: PRM `scopes_supported`, else AS `scopes_supported`, else none. Untrusted → strings only. */
export function defaultScopes(
  prm: ProtectedResourceMetadata,
  as: AuthorizationServerMetadata
): string[] {
  const pick = (v: unknown): string[] | undefined =>
    Array.isArray(v) ? v.filter((s): s is string => typeof s === 'string') : undefined
  return pick(prm.scopes_supported) ?? pick(as.scopes_supported) ?? []
}

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
}

function firstHeader(value: string | string[] | undefined): string | undefined {
  return Array.isArray(value) ? value[0] : value
}

/** Map a pinned-fetch error onto discovery's typed error union. */
function mapPinnedError(error: PinnedFetchError, url: string): DiscoveryError {
  switch (error.kind) {
    case 'kernel_rejected':
      return { kind: 'kernel_rejected', field: error.field, errors: error.errors }
    case 'transport_failed':
      return { kind: 'fetch_failed', url, detail: error.detail }
    case 'content_encoding_rejected':
      return { kind: 'content_encoding_rejected', url, encoding: error.encoding }
  }
}

/**
 * IP-pinned guarded fetch, following redirects MANUALLY and re-pinning EVERY hop.
 *
 * {@link pinnedFetch} resolves+validates+pins a single URL (spec §4, H2) and never
 * follows a 3xx itself. Here the loop re-runs it for each hop — so the initial URL
 * AND each `Location` (resolved against the current URL) is independently kernel-
 * validated and pinned to a freshly-resolved IP; hop 0's IP is never reused. 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: PinnedResponse; finalUrl: string } | { ok: false; error: DiscoveryError }
> {
  let currentUrl = url
  for (let hop = 0; ; hop++) {
    const fetched = await pinnedFetch(currentUrl, field, {
      resolveDns: deps.resolveDns,
      transport: deps.transport,
      timeoutMs: DISCOVERY_TIMEOUT_MS,
    })
    if (!fetched.ok) {
      return { ok: false, error: mapPinnedError(fetched.error, currentUrl) }
    }
    const response = fetched.response
    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 = firstHeader(response.headers.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 + pin a URL and only then parse it as JSON, following redirects
 * through the pin (see {@link guardedFetch}). Structurally guarantees the spec §4
 * invariant: validation runs BEFORE every fetch, and a URL the kernel rejects is
 * never fetched.
 */
export 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
  const isOk = response.status >= 200 && response.status < 300
  if (!isOk) {
    return {
      ok: false,
      error: {
        kind: 'fetch_failed',
        url: finalUrl,
        status: response.status,
        detail: `HTTP ${response.status}`,
      },
    }
  }
  try {
    return { ok: true, json: JSON.parse(response.bodyText) }
  } 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). */
export 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}/`)
}

/**
 * An RFC 8414 §2 issuer identifier: no query, no fragment and no userinfo. Checked
 * on the raw string because `URL` drops an empty `?` or `#`.
 */
function isBareIdentifier(raw: string, parsed: URL): boolean {
  return (
    !raw.includes('?') && !raw.includes('#') && parsed.username === '' && parsed.password === ''
  )
}

/**
 * RFC 8414 §3.3: the AS metadata `issuer` must be identical to the authorization
 * server it was retrieved from; neither carries a query, fragment or userinfo
 * (RFC 8414 §2). 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: string): boolean {
  let issuerUrl: URL
  let baseUrl: URL
  try {
    issuerUrl = new URL(issuer)
    baseUrl = new URL(base)
  } catch {
    return false
  }
  if (!isBareIdentifier(issuer, issuerUrl) || !isBareIdentifier(base, baseUrl)) return false
  return issuerUrl.origin === baseUrl.origin && trimmedPath(issuerUrl) === trimmedPath(baseUrl)
}

/**
 * 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 via the pinned fetch (kernel-guards +
  // pins the mcpUrl before connecting). A kernel rejection is fatal (never probe an
  // internal host); a transport/encoding failure is non-fatal — the well-known
  // candidates follow. The pin never auto-follows a 3xx, so a redirecting MCP server
  // simply yields no 401 hint here.
  const probe = await pinnedFetch(mcpUrl, 'mcpUrl', {
    resolveDns: deps.resolveDns,
    transport: deps.transport,
    timeoutMs: DISCOVERY_TIMEOUT_MS,
  })
  if (!probe.ok) {
    if (probe.error.kind === 'kernel_rejected') {
      return {
        ok: false,
        error: { kind: 'kernel_rejected', field: 'mcpUrl', errors: probe.error.errors },
      }
    }
    // transport / content-encoding failure of the probe is non-fatal — fall through.
  } else if (probe.response.status === 401) {
    const hint = parseResourceMetadataChallenge(
      firstHeader(probe.response.headers['www-authenticate'])
    )
    if (hint) candidates.push(hint)
  }

  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 }
}

/**
 * Why an operator-supplied authorization server cannot replace the one the PRM
 * advertises, or null when it can. Accepted only to name the tenant of Microsoft
 * Entra ID's multi-tenant authority: on authorization servers that separate tenants
 * by path on one origin (`auth.atlassian.com/<id>`, Keycloak realms, Okta
 * `/oauth2/<id>`), a "same origin" override would let the operator point a resource at
 * another tenant's issuer, so no wider override is offered.
 */
function authorizationServerOverrideRejection(
  override: string,
  advertisedAs: string
): string | null {
  if (!isEntraTenantAuthority(override)) {
    return 'authorizationServer must be a Microsoft Entra ID tenant authority (https://login.microsoftonline.com/<tenant-id>/v2.0)'
  }
  // Only the first entry counts: discovery replaces `authorization_servers[0]` and only
  // that entry raises `tenant_required`, so an Entra multi-tenant authority listed later
  // must not license swapping out an unrelated first authorization server.
  if (!URL.canParse(advertisedAs) || !isEntraMultiTenantAuthority(new URL(advertisedAs))) {
    return "the protected resource's first authorization server is not the Microsoft Entra ID multi-tenant authority"
  }
  return null
}

/**
 * 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, unless the pinned issuer matches a closed authorization-server
 * profile (`asProfiles.ts`) (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. `authorizationServer` is the operator's tenant authority for a
 * resource that advertises Microsoft Entra ID's multi-tenant authority
 * (`tenant_required`); any other override is `authorization_server_override_rejected`
 * and nothing is fetched from it.
 *
 * Contract with control-ui: the `/discover` and install responses built from this
 * result are pinned as wire goldens by test/routes.adminRemoteMcp.wireGoldens.test.ts,
 * which control-ui's fixtures consume (control-api is not importable there). A shape
 * change here must regenerate those goldens or control-ui certifies a stale shape.
 */
export async function discoverRemoteOAuth(
  mcpUrl: string,
  deps: DiscoveryDeps,
  opts: { hasPreRegisteredClient?: boolean; authorizationServer?: string } = {}
): 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 advertisedAs = prm.authorization_servers?.[0]
  if (typeof advertisedAs !== 'string' || advertisedAs.length === 0) {
    return {
      ok: false,
      error: { kind: 'no_authorization_server', detail: 'PRM has no authorization_servers[0]' },
    }
  }

  let asBase = advertisedAs
  if (opts.authorizationServer !== undefined) {
    const rejection = authorizationServerOverrideRejection(opts.authorizationServer, advertisedAs)
    if (rejection !== null) {
      log.warn(
        { discovery: 'authorization_server_override_rejected' },
        'remote discovery rejected the operator-supplied authorization server'
      )
      return {
        ok: false,
        error: { kind: 'authorization_server_override_rejected', detail: rejection },
      }
    }
    asBase = opts.authorizationServer
  }

  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',
      },
    }
  }

  // Entra's multi-tenant authority declares the literal issuer
  // `https://login.microsoftonline.com/{tenantid}/v2.0`, which can never equal the base,
  // so fetching it could only end in `issuer_mismatch`. Ask for the tenant instead.
  if (isEntraMultiTenantAuthority(asBaseUrl)) {
    log.warn({ discovery: 'tenant_required' }, 'remote discovery needs the Entra tenant')
    return {
      ok: false,
      error: {
        kind: 'tenant_required',
        authorizationServer: asBase,
        tenantAuthorityTemplate: ENTRA_TENANT_AUTHORITY_TEMPLATE,
        detail:
          'authorization server is the Microsoft Entra ID multi-tenant authority; name the tenant',
      },
    }
  }

  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, asBase)) {
      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 }
  }

  // Recognised only from an issuer that passed the strict comparison above, so a profile
  // never widens which issuers are trusted.
  const profile = detectAsProfile(as.issuer)

  // Invariant 3: fail closed unless S256 is advertised (ignore `plain`). A profile stands
  // in for the advertisement only for an authorization server that documents S256
  // support but omits it from its metadata (`asProfiles.ts`).
  const challengeMethods = as.code_challenge_methods_supported
  const advertisesS256 = Array.isArray(challengeMethods) && challengeMethods.includes('S256')
  if (!advertisesS256 && profile === null) {
    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 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 }
        : {}),
    })
    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(
    registrationModeInputs(as, {
      hasPreRegisteredClient: opts.hasPreRegisteredClient ?? false,
    })
  )

  const quirks = deriveQuirks(as, prm)
  // `mcpUrl` already parsed in `resolvePrm`, so the audience checks cannot throw here.
  const derivedScopes = withProfileScopes(defaultScopes(prm, as), profile?.id)
  const violation = profileScopeViolation(profile?.id, mcpUrl, derivedScopes)
  const unverified = profileUnverifiedScopes(profile?.id, mcpUrl, derivedScopes)

  return {
    ok: true,
    result: {
      prm,
      as,
      resource: prm.resource,
      issuer: as.issuer,
      issForCallback: issBindingSupported ? as.issuer : undefined,
      endpoints: {
        authorization: as.authorization_endpoint,
        token: as.token_endpoint,
        registration:
          typeof as.registration_endpoint === 'string' ? as.registration_endpoint : undefined,
      },
      registrationMode,
      quirks: profile ? { ...quirks, supportsRefresh: true } : quirks,
      ...(profile ? { asProfile: profile.id } : {}),
      ...(violation !== null ? { scopeAudienceViolation: violation } : {}),
      ...(unverified.length > 0 ? { unverifiedScopes: unverified } : {}),
      ...(profileHasResourceScope(profile?.id, mcpUrl, derivedScopes)
        ? {}
        : { scopeAudienceMissing: true as const }),
    },
  }
}

// ─── Generic self-hosted AS discovery (S3-B4 / E-19.5, D-A6) ─────────────────
//
// A separate entry point from `discoverRemoteOAuth` (which stays byte-identical,
// C1/C1.5 golden): the generic operator typically types an AS ISSUER, not a
// protected MCP resource. This resolves RFC 8414 / OIDC metadata ISSUER-FIRST
// (DA-2), falling back to RFC 9728 PRM only when the issuer path yields no AS. It
// reuses the same private primitives (`guardedFetchJson`, `asMetadataUrls`,
// `isIssuerConsistentWithBase`, `resolvePrm`, `deriveQuirks`) and has NO S256 gate:
// a generic client may legally run with `usePkce:false`, so PKCE support is REPORTED
// as a suggestion, never enforced.

/** Result of generic AS discovery. `prm`/`resource` present only via the PRM fallback. */
export interface AsDiscoveryResult {
  as: AuthorizationServerMetadata
  prm?: ProtectedResourceMetadata
  issuer: string
  endpoints: { authorization: string; token: string }
  /** RFC 8707 resource — only when reached through a protected-resource-metadata document. */
  resource?: string
}

export type AsDiscoveryOutcome =
  | { ok: true; result: AsDiscoveryResult }
  | { ok: false; error: DiscoveryError }

/**
 * Fetch + validate RFC 8414 / OIDC AS metadata from an authorization-server base URL,
 * trying both well-known forms. Mirrors the AS-metadata loop inside
 * {@link discoverRemoteOAuth} MINUS the S256 gate; kept separate so that golden path
 * stays byte-identical. Issuer is checked against the base (RFC 8414 §3.3).
 */
async function resolveAsMetadataFromBase(
  asBaseUrl: URL,
  deps: DiscoveryDeps
): Promise<{ ok: true; as: AuthorizationServerMetadata } | { ok: false; error: DiscoveryError }> {
  let lastError: DiscoveryError = {
    kind: 'fetch_failed',
    url: asBaseUrl.toString(),
    detail: 'no AS-metadata candidate resolved',
  }
  for (const url of asMetadataUrls(asBaseUrl)) {
    const fetched = await guardedFetchJson(url, 'asMetadataUrl', deps)
    if (!fetched.ok) {
      lastError = fetched.error
      continue
    }
    if (!isRecord(fetched.json)) {
      lastError = { 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'
    ) {
      lastError = {
        kind: 'invalid_metadata',
        url,
        detail: 'AS metadata missing issuer/authorization_endpoint/token_endpoint',
      }
      continue
    }
    if (!isIssuerConsistentWithBase(candidate.issuer, asBaseUrl.toString())) {
      lastError = {
        kind: 'issuer_mismatch',
        detail: `AS issuer "${candidate.issuer}" does not match authorization server "${asBaseUrl.toString()}"`,
      }
      continue
    }
    return { ok: true, as: candidate }
  }
  return { ok: false, error: lastError }
}

/**
 * Discover an authorization server's metadata for the generic carril. `url` is the
 * operator-typed AS issuer (or, in the fallback, a protected MCP resource). Every
 * fetched/pinned URL passes the kernel BEFORE the fetch (spec 19 §4), including the
 * typed URL and every discovered endpoint. Fail-closed: an AS that advertises an
 * internal/blocked endpoint is rejected (`kernel_rejected`), never pre-filled.
 */
export async function discoverAuthorizationServerMetadata(
  url: string,
  deps: DiscoveryDeps
): Promise<AsDiscoveryOutcome> {
  const log = (deps.logger ?? rootLogger).child({ module: 'oauth-discovery' })

  let base: URL
  try {
    base = new URL(url)
  } catch {
    return {
      ok: false,
      error: { kind: 'invalid_metadata', url, detail: 'url is not a valid absolute URL' },
    }
  }

  let as: AuthorizationServerMetadata
  let prm: ProtectedResourceMetadata | undefined
  let resource: string | undefined

  // Issuer-first (DA-2): the typed URL is most likely an AS issuer. Only its origin
  // and path locate the well-known documents, so the operator's query, fragment or
  // userinfo are dropped before the comparison; the issuer the AS declares must still
  // be bare. The PRM fallback below keeps `authorization_servers[0]` strict: that one
  // is a third party's claim of the identifier, not a locator typed by the operator.
  const operatorBase = new URL(base.href)
  operatorBase.search = ''
  operatorBase.hash = ''
  operatorBase.username = ''
  operatorBase.password = ''
  const issuerFirst = await resolveAsMetadataFromBase(operatorBase, deps)
  if (issuerFirst.ok) {
    as = issuerFirst.as
  } else {
    // PRM fallback (RFC 9728 → 8414): treat the URL as a protected resource, resolve
    // its PRM and follow authorization_servers[0]. Reuses the remote-lane PRM resolver
    // (kernel-guards + pins every candidate). On total failure we surface the
    // issuer-first error — that is the path the operator's input targeted.
    const prmResult = await resolvePrm(url, deps)
    if (!prmResult.ok) {
      log.warn(
        { issuerFirst: issuerFirst.error.kind, prm: prmResult.error.kind },
        'generic AS discovery failed (issuer-first and PRM fallback)'
      )
      return { ok: false, error: issuerFirst.error }
    }
    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',
        },
      }
    }
    const asViaPrm = await resolveAsMetadataFromBase(asBaseUrl, deps)
    if (!asViaPrm.ok) {
      log.warn({ discovery: asViaPrm.error.kind }, 'generic AS discovery failed (PRM → AS)')
      return { ok: false, error: asViaPrm.error }
    }
    as = asViaPrm.as
    resource = prm.resource
  }

  // Kernel-guard every discovered endpoint BEFORE it is pinned/suggested (spec §4):
  // an AS that announces an internal endpoint must not be pre-filled.
  const endpointChecks: Array<{ field: string; url: string }> = [
    { field: 'spec.oauth.authorizationEndpoint', url: as.authorization_endpoint },
    { field: 'spec.oauth.tokenEndpoint', url: as.token_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 } }
    }
  }

  return {
    ok: true,
    result: {
      as,
      prm,
      issuer: as.issuer,
      endpoints: { authorization: as.authorization_endpoint, token: as.token_endpoint },
      resource,
    },
  }
}

/** Suggestion wire the generic install wizard pre-fills from (E-19.5, §5.2). */
export interface GenericDiscoveryPrefill {
  issuer: string
  endpoints: { authorization: string; token: string }
  /** Only when discovery went through a protected-resource-metadata document. */
  resource?: string
  scopesSupported: string[]
  /** Raw AS advertisements, shown in the wizard "Detected" panel. */
  capabilities: {
    codeChallengeMethods: string[]
    tokenEndpointAuthMethods: string[]
    grantTypes: string[]
  }
  /** Deterministic, documented derivations (§5.2). */
  suggested: {
    usePkce: boolean
    tokenAuthMethod: 'body' | 'basic'
    supportsRefresh: boolean
  }
}

function stringArray(value: unknown): string[] {
  return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
}

function definedStringArray(value: unknown): string[] | undefined {
  return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : undefined
}

/**
 * Project an {@link AsDiscoveryResult} onto the wizard prefill wire (§5.2). Pure and
 * deterministic. Absent metadata never invents a value: `usePkce` is false without an
 * advertised S256 (invariant 7), `tokenAuthMethod` is `basic` only when the AS lists
 * `client_secret_basic` and NOT `client_secret_post`, `supportsRefresh` reuses the
 * fail-closed `deriveQuirks` rule (D4). Fields with no standard metadata
 * (tokenRequestFormat, scopeSeparator, sendScope, includeResponseType,
 * extraAuthorizeParams, refreshEndpoint) are never suggested here.
 *
 * Mirror: control-ui hand-copies this projection in
 * test/fixtures/__tests__/genericDiscoveryPrefill.contract.test.ts (projectPrefill),
 * because control-api is not importable there. A shape change here must be reflected
 * in that copy or its fixtures certify a stale shape.
 */
export function buildGenericDiscoveryPrefill(result: AsDiscoveryResult): GenericDiscoveryPrefill {
  const as = result.as
  const codeChallengeMethods = stringArray(as.code_challenge_methods_supported)
  const tokenEndpointAuthMethods = stringArray(as.token_endpoint_auth_methods_supported)
  const grantTypes = stringArray(as.grant_types_supported)
  const scopesSupported =
    definedStringArray(result.prm?.scopes_supported) ??
    definedStringArray(as.scopes_supported) ??
    []
  const tokenAuthMethod: 'body' | 'basic' =
    tokenEndpointAuthMethods.includes('client_secret_basic') &&
    !tokenEndpointAuthMethods.includes('client_secret_post')
      ? 'basic'
      : 'body'
  return {
    issuer: result.issuer,
    endpoints: result.endpoints,
    ...(result.resource ? { resource: result.resource } : {}),
    scopesSupported,
    capabilities: { codeChallengeMethods, tokenEndpointAuthMethods, grantTypes },
    suggested: {
      usePkce: codeChallengeMethods.includes('S256'),
      tokenAuthMethod,
      // Reuse the fail-closed refresh rule; prm is optional for it (bearerInBody unused).
      supportsRefresh: deriveQuirks(as, result.prm ?? ({} as ProtectedResourceMetadata))
        .supportsRefresh,
    },
  }
}