All files / lib/server authentication.ts

100% Statements 900/900
97.54% Branches 159/163
100% Functions 35/35
100% Lines 900/900

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 9011x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1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23x 5x 5x 5x 23x 1x 1x 1x 1x 1x 1x 23x 4x 23x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 23x 23x 23x 23x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 4x 18x 18x 18x 18x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 1x 1x 1x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 35x 1x 1x 1x 1x 1x 1x 24x 24x 17x 17x 24x 1x 1x 24x 24x 1x 1x 24x 24x 1x 1x 24x 24x  
"use strict";
/**
 * Authentication of callers of the MCP server over Streamable HTTP.
 *
 * Modes:
 * - `none`: local development only; the server refuses to bind a
 *   non-loopback address in this mode.
 * - `static-bearer`: pre-shared bearer tokens mapped to named principals.
 *   This does NOT implement MCP OAuth discovery/authorization; it suits
 *   clients that let you configure an Authorization header.
 * - `oauth`: OAuth 2.0 resource server per the MCP authorization
 *   specification: RFC 9728 protected resource metadata, Bearer challenges,
 *   and token validation (issuer, audience/resource, expiry, scopes) via a
 *   configured JWKS or RFC 7662 introspection at an external authorization
 *   server.
 *
 * Every protected request is authenticated; session identifiers are never
 * treated as credentials, and tokens are only accepted in the Authorization
 * header.
 *
 * @module server/authentication
 */
import crypto from "node:crypto";
 
import {
  type AuthInfo,
  OAuthError,
  OAuthErrorCode,
  type OAuthTokenVerifier,
  bearerAuthChallengeResponse,
  getOAuthProtectedResourceMetadataUrl,
  verifyBearerToken,
} from "@modelcontextprotocol/server";
import * as jose from "jose";
 
import type { Config } from "../config.js";
import type { SecretResolver } from "../util/secrets.js";
import { OagMcpError } from "../errors.js";
import type { Logs } from "../logging/logger.js";
import type { SecretRegistry } from "../util/redact.js";
import type { Principal } from "../types.js";
import { trimTrailingSlashes } from "../util/path.js";
import { opaquePrincipalId } from "./authorization.js";
 
/** Result of authenticating a request. */
export type AuthResult =
  | { ok: true; principal: Principal; authInfo: AuthInfo }
  | { ok: false; response: Response };
 
/** Authenticator for HTTP requests. */
export interface HttpAuthenticator {
  readonly mode: "none" | "static-bearer" | "oauth";
  /** Authenticate one request. */
  authenticate(req: Request, logs: Logs): Promise<AuthResult>;
  /** Serve discovery metadata, or undefined when the path is not metadata. */
  metadata(req: Request): Response | undefined;
}
 
/** Error carrying a machine-readable token validation reason. */
class TokenRejected extends OAuthError {
  constructor(
    readonly reason: string,
    message: string,
  ) {
    super(OAuthErrorCode.InvalidToken, message);
  }
}
 
/**
 * Parse scopes from token claims (`scope` string or `scp` array/string).
 *
 * @param {Object} claims - token claims
 * @return {Array} scopes
 */
export function scopesFromClaims(claims: Record<string, unknown>): string[] {
  const raw = claims.scope ?? claims.scp;
  if (Array.isArray(raw)) {
    return raw.map(String);
  }
  if (typeof raw === "string") {
    return raw.split(/\s+/).filter(Boolean);
  }
  return [];
}
 
/** Reasons for jose errors, by error class; the first match wins. */
const JOSE_REASONS: ReadonlyArray<
  [abstract new (...args: never[]) => Error, string]
> = [
  [jose.errors.JWTExpired, "expired"],
  [jose.errors.JWSSignatureVerificationFailed, "invalid_signature"],
  [jose.errors.JWKSNoMatchingKey, "unknown_signing_key"],
  [jose.errors.JOSEAlgNotAllowed, "algorithm_not_allowed"],
  [jose.errors.JWSInvalid, "malformed_token"],
  [jose.errors.JWTInvalid, "malformed_token"],
];
 
/** Reasons for failed JWT claim checks, by claim. */
const CLAIM_REASONS: Readonly<Record<string, string>> = {
  aud: "audience_mismatch",
  iss: "issuer_mismatch",
  nbf: "not_yet_valid",
};
 
/**
 * Map jose errors to stable reasons.
 *
 * @private
 */
function _joseReason(err: unknown): string {
  if (
    err instanceof jose.errors.JWTClaimValidationFailed &&
    !(err instanceof jose.errors.JWTExpired)
  ) {
    return Object.hasOwn(CLAIM_REASONS, err.claim)
      ? CLAIM_REASONS[err.claim]
      : `claim_${err.claim}_invalid`;
  }
  return (
    JOSE_REASONS.find(([cls]) => err instanceof cls)?.[1] ?? "invalid_token"
  );
}
 
/**
 * Whether a host binds only to loopback.
 *
 * @param {String} host - bind host
 * @return {Boolean} true for loopback
 */
export function isLoopbackHost(host: string): boolean {
  return (
    ["127.0.0.1", "localhost", "::1", "[::1]"].includes(host) ||
    host.startsWith("127.")
  );
}
 
/**
 * Discover the JWKS URI from authorization server metadata.
 *
 * @private
 */
async function _discoverJwks(issuer: string): Promise<string> {
  const u = new URL(issuer);
  const pathPart = trimTrailingSlashes(u.pathname);
  const candidates = [
    `${u.origin}/.well-known/oauth-authorization-server${pathPart}`,
    `${trimTrailingSlashes(issuer)}/.well-known/openid-configuration`,
  ];
  for (const url of candidates) {
    try {
      const res = await fetch(url, { redirect: "error" });
      if (!res.ok) {
        continue;
      }
      const meta = (await res.json()) as Record<string, unknown>;
      if (meta.issuer !== issuer) {
        throw new OagMcpError(
          "MCP_AUTH_ISSUER_MISMATCH",
          `Authorization server metadata at ${url} reports issuer ${String(meta.issuer)}, expected ${issuer}`,
        );
      }
      if (typeof meta.jwks_uri === "string") {
        return meta.jwks_uri;
      }
    } catch (err) {
      if (err instanceof OagMcpError) {
        throw err;
      }
    }
  }
  throw new OagMcpError(
    "MCP_AUTH_JWKS_UNKNOWN",
    `Could not discover jwks_uri for issuer ${issuer}`,
    {
      hint: "Set mcpAuth.oauth.jwksUri explicitly, or configure introspection.",
    },
  );
}
 
/**
 * JWT access token verifier using a remote JWKS.
 */
class JwtVerifier implements OAuthTokenVerifier {
  private readonly jwks: ReturnType<typeof jose.createRemoteJWKSet>;
 
  constructor(
    jwksUri: string,
    private readonly o: {
      issuer: string;
      audiences: string[];
      algorithms: string[];
      clockToleranceSec: number;
      resource: URL;
    },
  ) {
    this.jwks = jose.createRemoteJWKSet(new URL(jwksUri), {
      timeoutDuration: 5000,
      cooldownDuration: 30000,
    });
  }
 
  async verifyAccessToken(token: string): Promise<AuthInfo> {
    let payload: jose.JWTPayload;
    try {
      ({ payload } = await jose.jwtVerify(token, this.jwks, {
        issuer: this.o.issuer,
        audience: this.o.audiences,
        algorithms: this.o.algorithms,
        clockTolerance: this.o.clockToleranceSec,
        requiredClaims: ["exp"],
      }));
    } catch (err) {
      throw new TokenRejected(_joseReason(err), "The access token is invalid");
    }
    const claims = payload as Record<string, unknown>;
    return {
      token,
      clientId: String(
        claims.client_id ?? claims.azp ?? claims.sub ?? "unknown",
      ),
      scopes: scopesFromClaims(claims),
      expiresAt: payload.exp,
      resource: this.o.resource,
      extra: { sub: payload.sub, iss: payload.iss },
    };
  }
}
 
/** An introspection response that passed the checks. */
type ActiveToken = Record<string, unknown> & { exp: number };
 
/**
 * The audiences of an introspection response's `aud`.
 *
 * @private
 */
function _audiences(aud: unknown): string[] {
  if (Array.isArray(aud)) {
    return aud.map(String);
  }
  return aud ? [String(aud)] : [];
}
 
/**
 * RFC 7662 token introspection verifier for opaque tokens.
 */
class IntrospectionVerifier implements OAuthTokenVerifier {
  constructor(
    private readonly o: {
      endpoint: string;
      clientId: string;
      clientSecret: string;
      issuer: string;
      audiences: string[];
      resource: URL;
    },
  ) {}
 
  async verifyAccessToken(token: string): Promise<AuthInfo> {
    const data = await this._introspect(token);
    this._check(data);
    return {
      token,
      clientId: String(data.client_id ?? data.sub ?? "unknown"),
      scopes: scopesFromClaims(data),
      expiresAt: data.exp,
      resource: this.o.resource,
      extra: { sub: data.sub, iss: data.iss ?? this.o.issuer },
    };
  }
 
  /**
   * Ask the introspection endpoint about a token.
   *
   * @private
   */
  private async _introspect(token: string): Promise<Record<string, unknown>> {
    let res: Response;
    try {
      res = await fetch(this.o.endpoint, {
        method: "POST",
        redirect: "error",
        headers: {
          "content-type": "application/x-www-form-urlencoded",
          accept: "application/json",
          authorization: `Basic ${Buffer.from(`${encodeURIComponent(this.o.clientId)}:${encodeURIComponent(this.o.clientSecret)}`).toString("base64")}`,
        },
        body: new URLSearchParams({ token, token_type_hint: "access_token" }),
        signal: AbortSignal.timeout(5000),
      });
    } catch {
      throw new OAuthError(
        OAuthErrorCode.ServerError,
        "Token introspection is unavailable",
      );
    }
    if (!res.ok) {
      throw new OAuthError(
        OAuthErrorCode.ServerError,
        "Token introspection failed",
      );
    }
    return (await res.json()) as Record<string, unknown>;
  }
 
  /**
   * Check that a token is active, ours and unexpired.
   *
   * @private
   */
  private _check(data: Record<string, unknown>): asserts data is ActiveToken {
    if (data.active !== true) {
      throw new TokenRejected("inactive", "The access token is not active");
    }
    if (data.iss !== undefined && data.iss !== this.o.issuer) {
      throw new TokenRejected(
        "issuer_mismatch",
        "The access token was issued by another issuer",
      );
    }
    if (!_audiences(data.aud).some((a) => this.o.audiences.includes(a))) {
      throw new TokenRejected(
        "audience_mismatch",
        "The access token is not intended for this server",
      );
    }
    if (typeof data.exp !== "number" || data.exp * 1000 < Date.now()) {
      throw new TokenRejected("expired", "The access token has expired");
    }
  }
}
 
/**
 * Timing-safe comparison of two strings via their digests.
 *
 * @private
 */
function _safeEqual(a: string, b: string): boolean {
  const da = crypto.createHash("sha256").update(a).digest();
  const db = crypto.createHash("sha256").update(b).digest();
  return crypto.timingSafeEqual(da, db);
}
 
/**
 * Bearer token from an Authorization header.
 *
 * @private
 */
function _bearer(req: Request): string | undefined {
  const h = req.headers.get("authorization");
  const m = h ? /^Bearer\s+([^\s]+)\s*$/i.exec(h) : null;
  return m ? m[1] : undefined;
}
 
/**
 * JSON error response with a WWW-Authenticate challenge.
 *
 * @private
 */
function _challenge(
  status: number,
  error: string | undefined,
  description: string,
): Response {
  const params = [`realm="oag-mcp"`];
  if (error) {
    params.push(`error="${error}"`, `error_description="${description}"`);
  }
  return new Response(
    JSON.stringify({
      error: error ?? "unauthorized",
      error_description: description,
    }),
    {
      status,
      headers: {
        "content-type": "application/json",
        "www-authenticate": `Bearer ${params.join(", ")}`,
      },
    },
  );
}
 
/** Options for {@link createHttpAuthenticator}. */
export interface AuthenticatorOptions {
  config: Config;
  resolver: SecretResolver;
  registry: SecretRegistry;
  logs: Logs;
  /** Public URL of the MCP endpoint (the protected resource). */
  resourceUrl: URL;
  resourceName: string;
}
 
/** A configured static bearer token with its resolved value. */
type StaticEntry = NonNullable<
  Config["mcpAuth"]["staticBearer"]
>["tokens"][number] & { value: string };
 
/** OAuth resource server settings. */
type OAuthConfig = NonNullable<Config["mcpAuth"]["oauth"]>;
 
/** What an OAuth authenticator checks tokens against. */
interface OAuthContext {
  o: OAuthConfig;
  verifier: OAuthTokenVerifier;
  validation: "jwt" | "introspection";
  resource: URL;
  resourceMetadataUrl: string;
  registry: SecretRegistry;
  /** The HMAC key for opaque principal ids. */
  principalIdKey: crypto.BinaryLike;
}
 
/**
 * Create the HTTP authenticator for the configured mode.
 *
 * @param {Object} opts - options
 * @return {Promise} authenticator
 */
export async function createHttpAuthenticator(
  opts: AuthenticatorOptions,
): Promise<HttpAuthenticator> {
  const mode = opts.config.mcpAuth.mode;
  if (mode === "none") {
    return _noneAuthenticator(opts.logs);
  }
  if (mode === "static-bearer") {
    return _staticBearerAuthenticator(opts);
  }
  return _oauthAuthenticator(opts);
}
 
/**
 * Local development: every caller is anonymous.
 *
 * @private
 */
function _noneAuthenticator(logs: Logs): HttpAuthenticator {
  const mode = "none";
  logs.audit(
    "authentication.mode_configured",
    "success",
    {
      mode,
      warning: "unauthenticated; loopback only",
    },
    "warn",
  );
  return {
    mode,
    metadata: () => undefined,
    authenticate: async (_req, l) => {
      const principal: Principal = {
        id: "anonymous",
        kind: "anonymous",
        scopes: [],
      };
      l.audit("authentication.succeeded", "success", {
        mode,
        principalId: principal.id,
      });
      return {
        ok: true,
        principal,
        authInfo: {
          token: "",
          clientId: "anonymous",
          scopes: [],
          extra: { principal },
        },
      };
    },
  };
}
 
/**
 * Pre-shared bearer tokens mapped to named principals.
 *
 * @private
 */
function _staticBearerAuthenticator(
  opts: AuthenticatorOptions,
): HttpAuthenticator {
  const mode = "static-bearer";
  const entries = _staticEntries(opts);
  opts.logs.audit("authentication.mode_configured", "success", {
    mode,
    principals: entries.map((e) => e.principal),
    note: "static bearer does not implement MCP OAuth discovery",
  });
  return {
    mode,
    metadata: () => undefined,
    authenticate: async (req, l) => _authenticateStatic(req, l, entries),
  };
}
 
/**
 * Resolve the configured static bearer tokens, refusing weak ones.
 *
 * @private
 */
function _staticEntries(opts: AuthenticatorOptions): StaticEntry[] {
  const tokens = opts.config.mcpAuth.staticBearer?.tokens;
  if (!tokens || tokens.length === 0) {
    throw new OagMcpError(
      "MCP_AUTH_CONFIG_INVALID",
      "mcpAuth.mode is static-bearer but mcpAuth.staticBearer.tokens is empty",
    );
  }
  return tokens.map((t) => {
    const value = opts.resolver.resolve(
      t.token,
      `mcpAuth token for ${t.principal}`,
    );
    if (value.length < 16) {
      throw new OagMcpError(
        "MCP_AUTH_TOKEN_WEAK",
        `Static bearer token for ${t.principal} is shorter than 16 characters`,
        { hint: "Generate one with: openssl rand -hex 32" },
      );
    }
    opts.registry.add(value);
    return { ...t, value };
  });
}
 
/**
 * The entry a token belongs to, comparing against every entry to keep
 * timing independent of position.
 *
 * @private
 */
function _matchStatic(
  token: string,
  entries: StaticEntry[],
): StaticEntry | undefined {
  let match: StaticEntry | undefined;
  for (const e of entries) {
    if (_safeEqual(token, e.value) && !match) {
      match = e;
    }
  }
  return match;
}
 
/**
 * Audit a refused static bearer request and challenge the caller.
 *
 * @private
 */
function _refuseStatic(
  l: Logs,
  reason: string,
  response: Response,
): AuthResult {
  l.audit(
    "authentication.failed",
    "failure",
    { mode: "static-bearer", reason },
    "warn",
  );
  return { ok: false, response };
}
 
/**
 * Authenticate a request with a static bearer token.
 *
 * @private
 */
function _authenticateStatic(
  req: Request,
  l: Logs,
  entries: StaticEntry[],
): AuthResult {
  const token = _bearer(req);
  if (!token) {
    return _refuseStatic(
      l,
      "missing_token",
      _challenge(401, undefined, "Bearer token required"),
    );
  }
  const match = _matchStatic(token, entries);
  if (!match) {
    return _refuseStatic(
      l,
      "invalid_token",
      _challenge(401, "invalid_token", "The bearer token is invalid"),
    );
  }
  const principal: Principal = {
    id: `static:${match.principal}`,
    kind: "static",
    name: match.principal,
    scopes: match.scopes,
  };
  l.audit("authentication.succeeded", "success", {
    mode: "static-bearer",
    principalId: principal.id,
  });
  return {
    ok: true,
    principal,
    authInfo: {
      token: "[static-bearer]",
      clientId: match.principal,
      scopes: match.scopes,
      extra: { principal },
    },
  };
}
 
/**
 * The OAuth settings, refusing a missing section or an insecure issuer.
 *
 * @private
 */
function _oauthConfig(config: Config): OAuthConfig {
  const o = config.mcpAuth.oauth;
  if (!o) {
    throw new OagMcpError(
      "MCP_AUTH_CONFIG_INVALID",
      "mcpAuth.mode is oauth but mcpAuth.oauth is not configured",
    );
  }
  const issuerUrl = new URL(o.issuer);
  if (
    issuerUrl.protocol !== "https:" &&
    !o.allowInsecureIssuer &&
    !isLoopbackHost(issuerUrl.hostname)
  ) {
    throw new OagMcpError(
      "MCP_AUTH_ISSUER_INSECURE",
      `OAuth issuer ${o.issuer} must use HTTPS`,
      {
        hint: "Use an HTTPS issuer; allowInsecureIssuer is for local testing only.",
      },
    );
  }
  return o;
}
 
/**
 * The token verifier: introspection when configured, otherwise JWTs signed
 * by the issuer's JWKS.
 *
 * @private
 */
async function _oauthVerifier(
  o: OAuthConfig,
  opts: AuthenticatorOptions,
  audiences: string[],
  resource: URL,
): Promise<Pick<OAuthContext, "verifier" | "validation">> {
  if (o.introspection) {
    const clientId = opts.resolver.resolve(
      o.introspection.clientId,
      "introspection client id",
    );
    const clientSecret = opts.resolver.resolve(
      o.introspection.clientSecret,
      "introspection client secret",
    );
    opts.registry.add(clientSecret);
    return {
      verifier: new IntrospectionVerifier({
        endpoint: o.introspection.endpoint,
        clientId,
        clientSecret,
        issuer: o.issuer,
        audiences,
        resource,
      }),
      validation: "introspection",
    };
  }
  const jwksUri = o.jwksUri ?? (await _discoverJwks(o.issuer));
  return {
    verifier: new JwtVerifier(jwksUri, {
      issuer: o.issuer,
      audiences,
      algorithms: o.algorithms,
      clockToleranceSec: o.clockToleranceSec,
      resource,
    }),
    validation: "jwt",
  };
}
 
/**
 * Serve RFC 9728 protected resource metadata at its well-known paths.
 *
 * @private
 */
function _metadataHandler(
  prm: Record<string, unknown>,
  paths: Set<string>,
): HttpAuthenticator["metadata"] {
  return (req) => {
    if (!paths.has(new URL(req.url).pathname)) {
      return undefined;
    }
    if (req.method !== "GET" && req.method !== "HEAD") {
      return new Response(null, {
        status: 405,
        headers: { allow: "GET, HEAD" },
      });
    }
    return new Response(JSON.stringify(prm), {
      status: 200,
      headers: {
        "content-type": "application/json",
        "cache-control": "max-age=300",
      },
    });
  };
}
 
/** The shortest accepted `mcpAuth.oauth.principalIdKey`. */
const MIN_PRINCIPAL_ID_KEY_LENGTH = 32;
 
/**
 * The HMAC key for opaque OAuth principal ids: the configured
 * `principalIdKey`, or without one a random key for this process only, so
 * ids stay private but change on every restart.
 *
 * @private
 */
function _principalIdKey(
  o: OAuthConfig,
  opts: AuthenticatorOptions,
): crypto.BinaryLike {
  if (!o.principalIdKey) {
    return crypto.randomBytes(32);
  }
  const key = opts.resolver.resolve(
    o.principalIdKey,
    "mcpAuth.oauth.principalIdKey",
  );
  if (key.length < MIN_PRINCIPAL_ID_KEY_LENGTH) {
    throw new OagMcpError(
      "MCP_AUTH_PRINCIPAL_KEY_WEAK",
      `mcpAuth.oauth.principalIdKey is shorter than ${MIN_PRINCIPAL_ID_KEY_LENGTH} characters`,
      { hint: "Generate one with: openssl rand -hex 32" },
    );
  }
  opts.registry.add(key);
  return key;
}
 
/**
 * OAuth 2.0 resource server.
 *
 * @private
 */
async function _oauthAuthenticator(
  opts: AuthenticatorOptions,
): Promise<HttpAuthenticator> {
  const mode = "oauth";
  const o = _oauthConfig(opts.config);
  const resource = new URL(o.resource ?? opts.resourceUrl.toString());
  const audiences =
    o.audience && o.audience.length > 0 ? o.audience : [resource.toString()];
  const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resource);
  const { verifier, validation } = await _oauthVerifier(
    o,
    opts,
    audiences,
    resource,
  );
  const metadata = _metadataHandler(
    {
      resource: resource.toString(),
      authorization_servers: [o.issuer],
      scopes_supported: o.scopesSupported ?? o.requiredScopes,
      bearer_methods_supported: ["header"],
      resource_name: opts.resourceName,
    },
    new Set([
      "/.well-known/oauth-protected-resource",
      new URL(resourceMetadataUrl).pathname,
    ]),
  );
  const principalIdKey = _principalIdKey(o, opts);
  opts.logs.audit(
    "authentication.mode_configured",
    "success",
    {
      mode,
      validation,
      issuer: o.issuer,
      requiredScopes: o.requiredScopes,
      ...(o.principalIdKey
        ? {}
        : {
            warning:
              "mcpAuth.oauth.principalIdKey is not set; principal ids change on every restart",
          }),
    },
    o.principalIdKey ? "info" : "warn",
  );
  const ctx: OAuthContext = {
    o,
    verifier,
    validation,
    resource,
    resourceMetadataUrl,
    registry: opts.registry,
    principalIdKey,
  };
  return {
    mode,
    metadata,
    authenticate: (req, l) => _authenticateOAuth(req, l, ctx),
  };
}
 
/**
 * Authenticate a request with an OAuth access token.
 *
 * @private
 */
async function _authenticateOAuth(
  req: Request,
  l: Logs,
  ctx: OAuthContext,
): Promise<AuthResult> {
  const { o, validation, resourceMetadataUrl } = ctx;
  try {
    const authInfo = await verifyBearerToken(req.headers.get("authorization"), {
      verifier: ctx.verifier,
      requiredScopes: o.requiredScopes,
      resourceMetadataUrl,
      expectedResource: ctx.resource,
    });
    const extra = (authInfo.extra ?? {}) as { sub?: string; iss?: string };
    const principal: Principal = {
      id: opaquePrincipalId(
        "oauth",
        [String(extra.iss ?? o.issuer), String(extra.sub ?? authInfo.clientId)],
        ctx.principalIdKey,
      ),
      kind: "oauth",
      clientId: authInfo.clientId,
      scopes: authInfo.scopes,
      expiresAt: authInfo.expiresAt,
    };
    ctx.registry.add(authInfo.token);
    l.audit("authentication.succeeded", "success", {
      mode: "oauth",
      validation,
      principalId: principal.id,
      scopeCount: principal.scopes.length,
    });
    return {
      ok: true,
      principal,
      authInfo: { ...authInfo, extra: { ...authInfo.extra, principal } },
    };
  } catch (err) {
    l.audit(
      "authentication.failed",
      "failure",
      { mode: "oauth", validation, reason: _oauthFailureReason(err, req) },
      "warn",
    );
    return {
      ok: false,
      response: bearerAuthChallengeResponse(err, {
        requiredScopes: o.requiredScopes,
        resourceMetadataUrl,
      }),
    };
  }
}
 
/**
 * A stable reason for a refused OAuth request.
 *
 * @private
 */
function _oauthFailureReason(err: unknown, req: Request): string {
  if (err instanceof TokenRejected) {
    return err.reason;
  }
  if (!req.headers.get("authorization")) {
    return "missing_token";
  }
  const code = err instanceof OAuthError ? err.code : "server_error";
  if (code === OAuthErrorCode.InsufficientScope) {
    return "insufficient_scope";
  }
  const message = String((err as Error).message);
  if (/expired/i.test(message)) {
    return "expired";
  }
  return /resource/i.test(message) ? "resource_mismatch" : String(code);
}