Skip to content

Context7 Platform -- Up-to-date docs for AI agents

CTX7-3107: fix(mcp): validate audience and type of Clerk OAuth JWTs (#3367)

Ramazan Onur Acarc30f27940856
diff --git a/.changeset/clerk-oauth-jwt-audience.md b/.changeset/clerk-oauth-jwt-audience.md
new file mode 100644
index 00000000..20b7c81b
--- /dev/null
+++ b/.changeset/clerk-oauth-jwt-audience.md
@@ -0,0 +1,5 @@
+---
+"@upstash/context7-mcp": patch
+---
+
+Verify OAuth JWT access tokens from the authorization server (Clerk) strictly on the hosted HTTP transport: signature, issuer, a `typ` of `at+jwt`, expiry with a minute of clock tolerance, and the token's `aud`. Clerk ID tokens and session JWTs, which share the issuer, now get HTTP 401. The audience is compared against the `RESOURCE_URL` origin, `/mcp` and `/mcp/oauth` (override with `MCP_OAUTH_ALLOWED_AUDIENCES`); `MCP_OAUTH_AUDIENCE_ENFORCEMENT` defaults to `observe`, which admits a mismatch and logs the OAuth client ID and audience (once per token every ten minutes), and `required` answers 401. These JWTs count as `oauth` in authentication telemetry, a token the Context7 API rejects on a tool call is challenged on the next request, and a rejected OAuth token now stays rejected in the per-replica cache for ten minutes instead of thirty seconds.
diff --git a/.env.example b/.env.example
index 001dad6d..79ea2277 100644
--- a/.env.example
+++ b/.env.example
@@ -19,6 +19,19 @@ MCP_CLIENT_IP_ASSERTION_KEY=
# Defaults to required. Set observe to accept requests without credentials on
# /mcp and record them, for example during a migration.
MCP_AUTH_ENFORCEMENT=
+# Set off to forward opaque OAuth tokens (oat_…) without checking them against
+# the Context7 API first.
+MCP_OAUTH_TOKEN_VALIDATION=
+# Audience check for OAuth JWT access tokens from OAUTH_AUTH_SERVER_URL.
+# observe (default): a token whose aud is missing or not allowed is accepted
+# and logged as audienceMismatch (clientId, aud). required: it gets HTTP 401.
+# Flip back to observe to roll back.
+MCP_OAUTH_AUDIENCE_ENFORCEMENT=
+# Comma-separated allowed audiences, normalized (lowercase scheme and host, no
+# trailing slash) before comparison. Defaults to the RESOURCE_URL origin plus
+# its /mcp and /mcp/oauth paths, e.g.
+# https://mcp.context7.com,https://mcp.context7.com/mcp,https://mcp.context7.com/mcp/oauth
+MCP_OAUTH_ALLOWED_AUDIENCES=
# Network / certificates
HTTPS_PROXY=
diff --git a/docs/resources/developer.mdx b/docs/resources/developer.mdx
index 475b2747..6617afa5 100644
--- a/docs/resources/developer.mdx
+++ b/docs/resources/developer.mdx
@@ -51,7 +51,9 @@ node packages/mcp/dist/index.js --transport http --port 8080
HTTP transport requires a credential on every request by default. Clients send `Authorization: Bearer YOUR_API_KEY`. Set `MCP_AUTH_ENFORCEMENT=observe` to also accept requests without credentials on `/mcp`.
-Opaque OAuth access tokens (`oat_…`) are checked against the Context7 API before each request is served (one check per token per minute on each replica; the cache is in memory). An expired or revoked token gets an HTTP 401 with a `WWW-Authenticate` challenge so MCP clients refresh it. Set `MCP_OAUTH_TOKEN_VALIDATION=off` to skip that check and forward the token unchecked.
+Opaque OAuth access tokens (`oat_…`) are checked against the Context7 API before each request is served (one check per token per minute on each replica; the cache is in memory, and a rejected token stays rejected for ten minutes). An expired or revoked token gets an HTTP 401 with a `WWW-Authenticate` challenge so MCP clients refresh it. Set `MCP_OAUTH_TOKEN_VALIDATION=off` to skip that check and forward the token unchecked.
+
+OAuth JWT access tokens from the authorization server (`OAUTH_AUTH_SERVER_URL`) are verified locally: signature against its JWKS, issuer, a `typ` of `at+jwt`, and expiry with a minute of clock tolerance. Clerk ID tokens and session JWTs share that issuer but are not access tokens, so they are always rejected. The token's `aud` must name this server (`RESOURCE_URL` origin, `/mcp`, or `/mcp/oauth`; override with a comma-separated `MCP_OAUTH_ALLOWED_AUDIENCES`). `MCP_OAUTH_AUDIENCE_ENFORCEMENT=observe` (default) admits a token with a missing or foreign audience and logs the OAuth client ID and audience, once per token every ten minutes; `required` answers HTTP 401.
Stdio transport with API key:
diff --git a/packages/mcp/README.md b/packages/mcp/README.md
index 210d5815..63f69241 100644
--- a/packages/mcp/README.md
+++ b/packages/mcp/README.md
@@ -1444,7 +1444,9 @@ bun run dist/index.js --transport http --port 8080
HTTP transport requires a credential on every request by default. Clients send `Authorization: Bearer YOUR_API_KEY`. Set `MCP_AUTH_ENFORCEMENT=observe` to also accept requests without credentials on `/mcp`.
-Opaque OAuth access tokens (`oat_…`) are checked against the Context7 API before each request is served (one check per token per minute on each replica; the cache is in memory). An expired or revoked token gets an HTTP 401 with a `WWW-Authenticate` challenge so MCP clients refresh it. Set `MCP_OAUTH_TOKEN_VALIDATION=off` to skip that check and forward the token unchecked.
+Opaque OAuth access tokens (`oat_…`) are checked against the Context7 API before each request is served (one check per token per minute on each replica; the cache is in memory, and a rejected token stays rejected for ten minutes). An expired or revoked token gets an HTTP 401 with a `WWW-Authenticate` challenge so MCP clients refresh it. Set `MCP_OAUTH_TOKEN_VALIDATION=off` to skip that check and forward the token unchecked.
+
+OAuth JWT access tokens from the authorization server (`OAUTH_AUTH_SERVER_URL`) are verified locally: signature against its JWKS, issuer, a `typ` of `at+jwt`, and expiry with a minute of clock tolerance. Clerk ID tokens and session JWTs share that issuer but are not access tokens, so they are always rejected. The token's `aud` must name this server (`RESOURCE_URL` origin, `/mcp`, or `/mcp/oauth`; override with a comma-separated `MCP_OAUTH_ALLOWED_AUDIENCES`). `MCP_OAUTH_AUDIENCE_ENFORCEMENT=observe` (default) admits a token with a missing or foreign audience and logs the OAuth client ID and audience, once per token every ten minutes; `required` answers HTTP 401.
Another example with stdio transport:
diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts
index 171ba2bd..eaeb513e 100644
--- a/packages/mcp/src/index.ts
+++ b/packages/mcp/src/index.ts
@@ -52,6 +52,7 @@ import {
setBearerChallenge,
} from "./lib/mcp-http-auth.js";
import { mcpRouteFromUrl } from "./lib/mcp-route.js";
+import { parseOAuthAudienceEnforcement } from "./lib/oauth-audience.js";
/** Default HTTP server port */
const DEFAULT_PORT = 3000;
@@ -452,6 +453,8 @@ async function main() {
onerror: (error) => console.error("MCP node adapter error:", error),
});
const authMode = parseMcpAuthMode();
+ // Read again per token; parsed here so a typo fails startup, not requests.
+ parseOAuthAudienceEnforcement();
const handleMcpRequest = async (req: express.Request, res: express.Response) => {
try {
diff --git a/packages/mcp/src/lib/api.ts b/packages/mcp/src/lib/api.ts
index 90a68079..478685a3 100644
--- a/packages/mcp/src/lib/api.ts
+++ b/packages/mcp/src/lib/api.ts
@@ -8,8 +8,9 @@ import { observeUpstreamRequest } from "./telemetry-runtime.js";
import {
INVALID_OAUTH_TOKEN_ERROR_CODE,
isOpaqueOAuthToken,
- rememberInvalidOpaqueOAuthToken,
+ rememberInvalidOAuthToken,
} from "./oauth-token-validation.js";
+import { isClerkOAuthJwt } from "./jwt.js";
/**
* Ceiling on a single Context7 API call. Without a signal a stalled backend
@@ -46,10 +47,10 @@ async function parseErrorResponse(response: Response, context: ClientContext): P
if (
status === 401 &&
context.transport === "http" &&
- isOpaqueOAuthToken(apiKey) &&
+ (isOpaqueOAuthToken(apiKey) || isClerkOAuthJwt(apiKey)) &&
(json?.error === INVALID_OAUTH_TOKEN_ERROR_CODE || json?.error === undefined)
) {
- rememberInvalidOpaqueOAuthToken(apiKey);
+ rememberInvalidOAuthToken(apiKey);
return EXPIRED_SIGN_IN_MESSAGE;
}
if (json?.message) {
diff --git a/packages/mcp/src/lib/jwt.ts b/packages/mcp/src/lib/jwt.ts
index 305395ea..3fd6290b 100644
--- a/packages/mcp/src/lib/jwt.ts
+++ b/packages/mcp/src/lib/jwt.ts
@@ -7,6 +7,7 @@ import {
OAUTH_JWKS_URL,
RESOURCE_URL,
} from "./constants.js";
+import { checkOAuthAudience } from "./oauth-audience.js";
import { isVercelMarketplaceIssuer, validateVercelMarketplaceJwt } from "./vercelMarketplaceJwt.js";
const oauthJwks = jose.createRemoteJWKSet(new URL(OAUTH_JWKS_URL));
@@ -15,6 +16,11 @@ const emaJwks = jose.createRemoteJWKSet(new URL(EMA_JWKS_URL));
const ENTRA_V2_ISSUER_RE = /^https:\/\/login\.microsoftonline\.com\/[0-9a-f-]{36}\/v2\.0$/;
+/** RFC 9068 media type of a JWT OAuth access token. */
+const OAUTH_ACCESS_TOKEN_TYP = "at+jwt";
+/** Allowed skew between Clerk's clock and ours when checking `exp`/`nbf`. */
+const OAUTH_CLOCK_TOLERANCE_SECONDS = 60;
+
const jwksByTenant = new Map<string, ReturnType<typeof jose.createRemoteJWKSet>>();
function entraJwks(tenantId: string) {
let jwks = jwksByTenant.get(tenantId);
@@ -66,12 +72,74 @@ async function fetchEntraConfig(audience: string): Promise<EntraConfig | null> {
export interface JWTValidationResult {
valid: boolean;
error?: string;
+ /**
+ * A finding about an otherwise verified token that the caller should log,
+ * for example an audience mismatch that `observe` mode let through. It
+ * names the OAuth client and the audience, never the token.
+ */
+ warning?: string;
}
export function isJWT(token: string): boolean {
return token.split(".").length === 3;
}
+/** jose compares `typ` the same way: case-insensitive, `application/` prefix optional. */
+function normalizeTyp(typ: string): string {
+ return typ.toLowerCase().replace(/^application\//, "");
+}
+
+/**
+ * Whether the token looks like an OAuth access token minted by Clerk: three
+ * segments, a `typ` header of `at+jwt` (or `application/at+jwt`), and the
+ * configured authorization server as its unsigned `iss`. This only routes the
+ * token to the Clerk branch and classifies it for telemetry; trust comes from
+ * `jwtVerify`, which checks the signed header and claims.
+ */
+export function isClerkOAuthJwt(token: string | undefined): token is string {
+ if (typeof token !== "string" || !isJWT(token)) return false;
+ try {
+ const { typ } = jose.decodeProtectedHeader(token);
+ if (typeof typ !== "string" || normalizeTyp(typ) !== OAUTH_ACCESS_TOKEN_TYP) return false;
+ return jose.decodeJwt(token).iss === OAUTH_AUTH_SERVER_URL;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Clerk signs ID tokens and session JWTs with the same issuer and JWKS as its
+ * OAuth access tokens, so issuer and signature alone cannot tell them apart.
+ * Only an access token (`typ: at+jwt`, RFC 9068) is a credential for this
+ * resource server: an ID token is addressed to the OAuth client, and a session
+ * JWT carries the user's whole browser session, which the user never granted
+ * to an MCP client and which names no audience at all. Both are rejected with
+ * 401 in every audience-enforcement mode; `observe` only relaxes the `aud`
+ * comparison of a genuine access token.
+ */
+async function validateClerkOAuthJwt(token: string): Promise<JWTValidationResult> {
+ if (!isClerkOAuthJwt(token)) {
+ return { valid: false, error: "Not an OAuth access token" };
+ }
+
+ const { payload } = await jose.jwtVerify(token, oauthJwks, {
+ issuer: OAUTH_AUTH_SERVER_URL,
+ typ: OAUTH_ACCESS_TOKEN_TYP,
+ clockTolerance: OAUTH_CLOCK_TOLERANCE_SECONDS,
+ });
+
+ const audience = checkOAuthAudience(payload.aud);
+ if (audience.allowed) return { valid: true };
+
+ const clientId =
+ typeof payload.client_id === "string" && payload.client_id ? payload.client_id : "unknown";
+ const warning = `audienceMismatch clientId=${clientId} aud=${audience.aud} enforcement=${audience.enforcement}`;
+ if (audience.enforcement === "required") {
+ return { valid: false, error: "Token audience not accepted", warning };
+ }
+ return { valid: true, warning };
+}
+
export async function validateJWT(token: string): Promise<JWTValidationResult> {
try {
const decoded = jose.decodeJwt(token);
@@ -108,8 +176,14 @@ export async function validateJWT(token: string): Promise<JWTValidationResult> {
return validateVercelMarketplaceJwt(token, iss);
}
- await jose.jwtVerify(token, oauthJwks, { issuer: OAUTH_AUTH_SERVER_URL });
- return { valid: true };
+ if (iss === OAUTH_AUTH_SERVER_URL) {
+ return await validateClerkOAuthJwt(token);
+ }
+
+ // No trusted issuer claims the token, so no JWKS could verify it; the
+ // Clerk branch used to be the fallback and failed on the issuer claim
+ // after a key lookup.
+ return { valid: false, error: "Untrusted issuer" };
} catch (error) {
if (error instanceof jose.errors.JWTExpired) {
return { valid: false, error: "Token expired" };
diff --git a/packages/mcp/src/lib/log-throttle.ts b/packages/mcp/src/lib/log-throttle.ts
new file mode 100644
index 00000000..32fffbf0
--- /dev/null
+++ b/packages/mcp/src/lib/log-throttle.ts
@@ -0,0 +1,55 @@
+import { createHash } from "node:crypto";
+
+/**
+ * A log line about a token that repeats on every request while the condition
+ * lasts (an OAuth JWT without an `aud`, sent by a client at hundreds of
+ * requests a minute) is written at most once per token per window. The line
+ * that does get written carries how many were suppressed since the previous
+ * one, so the rate stays readable from the log. The verdict the line reports
+ * is still taken on every request; only the line is deduplicated.
+ *
+ * Keyed by the SHA-256 of the token so a heap dump or a debug print of the
+ * map never exposes a usable credential. Map insertion order doubles as the
+ * eviction order once the map is full. State is per replica.
+ */
+export interface PerTokenLogWindow {
+ /**
+ * Returns the number of lines suppressed since the token was last admitted
+ * when this call should log, or `undefined` when it falls inside the window.
+ */
+ admit(token: string, now?: number): number | undefined;
+ /** Test hook: forget every token. */
+ reset(): void;
+}
+
+interface Entry {
+ loggedAt: number;
+ suppressed: number;
+}
+
+export function createPerTokenLogWindow(windowMs: number, maxEntries = 10_000): PerTokenLogWindow {
+ const entries = new Map<string, Entry>();
+
+ return {
+ admit(token, now = Date.now()) {
+ const key = createHash("sha256").update(token).digest("hex");
+ const entry = entries.get(key);
+ if (entry && now - entry.loggedAt < windowMs) {
+ entry.suppressed += 1;
+ return undefined;
+ }
+ const suppressed = entry?.suppressed ?? 0;
+ entries.delete(key);
+ while (entries.size >= maxEntries) {
+ const oldest = entries.keys().next().value;
+ if (oldest === undefined) break;
+ entries.delete(oldest);
+ }
+ entries.set(key, { loggedAt: now, suppressed: 0 });
+ return suppressed;
+ },
+ reset() {
+ entries.clear();
+ },
+ };
+}
diff --git a/packages/mcp/src/lib/mcp-http-auth.ts b/packages/mcp/src/lib/mcp-http-auth.ts
index d9e57327..6809ac5b 100644
--- a/packages/mcp/src/lib/mcp-http-auth.ts
+++ b/packages/mcp/src/lib/mcp-http-auth.ts
@@ -1,8 +1,10 @@
import type { Request, Response } from "express";
import { EMA_ISSUER, OAUTH_AUTH_SERVER_URL, RESOURCE_URL } from "./constants.js";
-import { isJWT, validateJWT } from "./jwt.js";
+import { isClerkOAuthJwt, isJWT, validateJWT } from "./jwt.js";
+import { createPerTokenLogWindow } from "./log-throttle.js";
import {
EXPIRED_OAUTH_TOKEN_ERROR,
+ isOAuthTokenRememberedInvalid,
isOpaqueOAuthToken,
isOpaqueOAuthTokenValidationEnabled,
validateOpaqueOAuthToken,
@@ -15,9 +17,26 @@ export type McpEndpoint = "/mcp" | "/mcp/oauth";
export type McpAuthDecision = AuthenticationObservation &
({ allowed: true } | { allowed: false; error: string });
+// A JWT from a grant authorized before Clerk's "Include Audience" setting was
+// on has no `aud` on every refresh, so its warning would repeat on every MCP
+// request (millions of lines a day). One line per token per window is enough
+// to collect the (clientId, aud) pairs before enforcement.
+const JWT_WARNING_WINDOW_MS = 10 * 60_000;
+const jwtWarningLog = createPerTokenLogWindow(JWT_WARNING_WINDOW_MS);
+
+/** Test hook: forget which tokens have had their warning logged. */
+export function resetJwtWarningLog(): void {
+ jwtWarningLog.reset();
+}
+
+/**
+ * A Clerk OAuth JWT counts as `oauth` like the opaque `oat_` token it replaces,
+ * so OAuth telemetry stays continuous across the switch to JWT access tokens.
+ * `jwt` is left for Entra, EMA, Vercel Marketplace and unrecognised JWTs.
+ */
export function classifyAuthMethod(token: string | undefined): AuthenticationMethod {
if (!token) return "none";
- if (isOpaqueOAuthToken(token)) return "oauth";
+ if (isOpaqueOAuthToken(token) || isClerkOAuthJwt(token)) return "oauth";
if (isJWT(token)) return "jwt";
return "api_key";
}
@@ -50,9 +69,11 @@ export function effectiveMcpAuthMode(
* Decide whether the HTTP request may reach the MCP transport. JWTs are
* verified at this boundary. Opaque OAuth tokens are checked against the
* Context7 API (cached per token) so an expired sign-in gets the HTTP 401 that
- * makes MCP clients refresh it; the check fails open. API keys are recorded as
- * present, then authoritatively validated by the Context7 API before data is
- * returned.
+ * makes MCP clients refresh it; the check fails open. A Clerk OAuth JWT is
+ * verified locally (signature, issuer, type, audience) with no API call, and
+ * only a rejection the Context7 API returned on an earlier data request can
+ * still turn it away. API keys are recorded as present, then authoritatively
+ * validated by the Context7 API before data is returned.
*/
export async function evaluateMcpAuthentication(
token: string | undefined,
@@ -96,14 +117,34 @@ export async function evaluateMcpAuthentication(
};
}
+ if (isClerkOAuthJwt(token) && isOAuthTokenRememberedInvalid(token)) {
+ return {
+ allowed: false,
+ method,
+ error: EXPIRED_OAUTH_TOKEN_ERROR,
+ event: "credential_rejected",
+ outcome: "expired",
+ };
+ }
+
const validation = await validateJWT(token);
+ if (validation.warning) {
+ // Names the OAuth client and the audience, never the token. The verdict
+ // below is still applied on every request; only the line is deduplicated.
+ const suppressed = jwtWarningLog.admit(token);
+ if (suppressed !== undefined) {
+ console.error(`[Context7] ${validation.warning} suppressedSincePrevious=${suppressed}`);
+ }
+ }
if (!validation.valid) {
return {
allowed: false,
method,
error: validation.error || "Invalid token. Please re-authenticate.",
event: "credential_rejected",
- outcome: "invalid",
+ // An expired Clerk access token is the JWT form of an expired `oat_`:
+ // the client refreshes it after this 401.
+ outcome: method === "oauth" && validation.error === "Token expired" ? "expired" : "invalid",
};
}
diff --git a/packages/mcp/src/lib/oauth-audience.ts b/packages/mcp/src/lib/oauth-audience.ts
new file mode 100644
index 00000000..55775f8a
--- /dev/null
+++ b/packages/mcp/src/lib/oauth-audience.ts
@@ -0,0 +1,107 @@
+import { RESOURCE_URL } from "./constants.js";
+
+/**
+ * Audience check for the OAuth JWT access tokens Clerk issues to the hosted
+ * MCP server's clients.
+ *
+ * An MCP client asks the authorization server for a token bound to the server
+ * it is talking to (RFC 8707 `resource`), and Clerk records that value as the
+ * token's `aud`. The MCP authorization spec requires the resource server to
+ * accept only tokens issued for it; otherwise a token obtained by any other
+ * MCP server that points its metadata at our Clerk instance would work here.
+ *
+ * The comparison is done in our code, not by jose's `audience` option, so a
+ * mismatch can be observed before it is enforced. Names and normalization
+ * match `lib/auth/oauthAudience.ts` in context7app so both servers agree on
+ * which tokens are ours.
+ */
+
+export type OAuthAudienceEnforcement = "observe" | "required";
+
+/** The forms of the MCP resource identifier clients have been seen to request. */
+export function defaultOAuthAllowedAudiences(resourceUrl = RESOURCE_URL): string[] {
+ const origin = new URL(resourceUrl).origin;
+ return [origin, `${origin}/mcp`, `${origin}/mcp/oauth`];
+}
+
+/**
+ * Canonical form of an audience for comparison: lowercase scheme and host,
+ * default port dropped, fragment dropped, no trailing slash. The path keeps
+ * its case. A value that is not an http(s) URL is only trimmed, since it can
+ * never match an allowed audience and matters only in the log.
+ */
+export function normalizeAudience(value: string): string {
+ const trimmed = value.trim();
+ let normalized = trimmed;
+ try {
+ const url = new URL(trimmed);
+ if (url.protocol === "http:" || url.protocol === "https:") {
+ normalized = `${url.protocol}//${url.host}${url.pathname}${url.search}`;
+ }
+ } catch {
+ // Not a URL; compared and logged as written.
+ }
+ return normalized.replace(/\/+$/, "");
+}
+
+/**
+ * `observe` (default) accepts a token whose `aud` is missing or not allowed
+ * and only logs the mismatch; `required` answers 401. Unknown values throw so
+ * a typo is caught at startup rather than silently staying in observe.
+ */
+export function parseOAuthAudienceEnforcement(
+ raw = process.env.MCP_OAUTH_AUDIENCE_ENFORCEMENT
+): OAuthAudienceEnforcement {
+ const value = raw?.trim().toLowerCase();
+ if (!value) return "observe";
+ if (value === "observe" || value === "required") return value;
+ throw new Error(
+ `MCP_OAUTH_AUDIENCE_ENFORCEMENT must be "observe" or "required"; received "${raw}"`
+ );
+}
+
+export function getAllowedOAuthAudiences(
+ raw = process.env.MCP_OAUTH_ALLOWED_AUDIENCES
+): Set<string> {
+ const configured = raw?.trim();
+ const values = configured ? configured.split(",") : defaultOAuthAllowedAudiences();
+ return new Set(
+ values
+ .map((value) => value.trim())
+ .filter(Boolean)
+ .map(normalizeAudience)
+ );
+}
+
+export interface OAuthAudienceCheck {
+ /** At least one of the token's audiences is allowed. */
+ allowed: boolean;
+ /** The normalized audiences, comma-joined, or `missing`. Safe to log. */
+ aud: string;
+ enforcement: OAuthAudienceEnforcement;
+}
+
+/**
+ * Checks a verified token's `aud` against the allowed audiences. A token with
+ * no `aud` fails the check like a foreign one: the client asked for no
+ * resource, so nothing says the token was meant for this server.
+ */
+export function checkOAuthAudience(audiences: unknown): OAuthAudienceCheck {
+ const enforcement = parseOAuthAudienceEnforcement();
+ const list =
+ typeof audiences === "string"
+ ? [audiences]
+ : Array.isArray(audiences)
+ ? audiences.filter((value): value is string => typeof value === "string")
+ : [];
+ const normalized = list.map(normalizeAudience).filter(Boolean);
+ if (normalized.length === 0) {
+ return { allowed: false, aud: "missing", enforcement };
+ }
+ const allowed = getAllowedOAuthAudiences();
+ return {
+ allowed: normalized.some((audience) => allowed.has(audience)),
+ aud: normalized.join(","),
+ enforcement,
+ };
+}
diff --git a/packages/mcp/src/lib/oauth-token-validation.ts b/packages/mcp/src/lib/oauth-token-validation.ts
index 36533542..77f315dc 100644
--- a/packages/mcp/src/lib/oauth-token-validation.ts
+++ b/packages/mcp/src/lib/oauth-token-validation.ts
@@ -9,6 +9,10 @@ import { observeUpstreamRequest } from "./telemetry-runtime.js";
* leaves a signed-in client stuck with text errors. The hosted server therefore
* asks the Context7 API whether the token is still accepted before the request
* reaches the MCP transport, and answers 401 when it is not.
+ *
+ * The verdict cache also records Clerk OAuth JWTs the Context7 API rejected on
+ * a data request (for example after the member was removed). Those tokens
+ * verify locally, so the cache is the only way the next request gets a 401.
*/
export type OpaqueOAuthTokenVerdict = "valid" | "invalid" | "unavailable";
@@ -21,7 +25,10 @@ export const INVALID_OAUTH_TOKEN_ERROR_CODE = "invalid_oauth_token";
const AUTH_CHECK_PATH = "/v2/auth/check";
const AUTH_CHECK_TIMEOUT_MS = 5_000;
const VALID_TTL_MS = 60_000;
-const INVALID_TTL_MS = 30_000;
+// A rejected token never becomes valid again (Clerk mints a new one on
+// refresh), so a long negative TTL only cuts repeated checks from clients
+// that keep retrying with the same token.
+export const INVALID_TTL_MS = 10 * 60_000;
// A short negative cache keeps an outage from adding the check's latency to
// every request while still retrying soon after the API recovers.
const UNAVAILABLE_TTL_MS = 10_000;
@@ -158,14 +165,20 @@ export async function validateOpaqueOAuthToken(
}
/**
- * The Context7 API rejected the token on a data request. Remember that so the
- * next MCP request gets the 401 immediately instead of waiting for the cached
- * positive verdict to expire.
+ * The Context7 API rejected the token (opaque `oat_` or Clerk OAuth JWT) on a
+ * data request. Remember that so the next MCP request gets the 401 immediately
+ * instead of waiting for the cached positive verdict to expire, or, for a JWT
+ * that still verifies locally, at all.
*/
-export function rememberInvalidOpaqueOAuthToken(token: string, now = Date.now()): void {
+export function rememberInvalidOAuthToken(token: string, now = Date.now()): void {
remember(cacheKey(token), "invalid", now);
}
+/** Whether a data request rejected this token within the last `INVALID_TTL_MS`. */
+export function isOAuthTokenRememberedInvalid(token: string, now = Date.now()): boolean {
+ return recall(cacheKey(token), now) === "invalid";
+}
+
/** Test hook: drop every cached verdict and in-flight check. */
export function resetOpaqueOAuthTokenValidation(): void {
verdicts.clear();
diff --git a/packages/mcp/src/lib/telemetry-contracts.ts b/packages/mcp/src/lib/telemetry-contracts.ts
index 91a33e09..4105c7a9 100644
--- a/packages/mcp/src/lib/telemetry-contracts.ts
+++ b/packages/mcp/src/lib/telemetry-contracts.ts
@@ -2,9 +2,10 @@ import type { McpHttpRoute } from "./mcp-route.js";
export type UpstreamOperation =
"auth_check" | "fetch_context" | "oauth_metadata" | "search_libraries";
-// `expired`: the Context7 API rejected an opaque OAuth token, so the client was
-// challenged to refresh. `unverified`: the token check was unavailable and the
-// request was forwarded unchecked (fail open).
+// `expired`: an OAuth token was rejected (the Context7 API refused an opaque
+// token, or a Clerk OAuth JWT had expired), so the client was challenged to
+// refresh. `unverified`: the token check was unavailable and the request was
+// forwarded unchecked (fail open).
export type AuthenticationOutcome =
"accepted" | "error" | "expired" | "invalid" | "missing" | "unverified";
export type AuthenticationMethod = "api_key" | "jwt" | "none" | "oauth";
diff --git a/packages/mcp/test/clerk-oauth-jwt.test.ts b/packages/mcp/test/clerk-oauth-jwt.test.ts
new file mode 100644
index 00000000..44f74025
--- /dev/null
+++ b/packages/mcp/test/clerk-oauth-jwt.test.ts
@@ -0,0 +1,383 @@
+/**
+ * End-to-end checks of the Clerk OAuth JWT branch: real `jose` verification
+ * against a key generated for the test run, with the remote JWKS replaced by
+ * a local key set so nothing touches the network.
+ */
+import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
+import * as jose from "jose";
+import type { Response as ExpressResponse } from "express";
+
+const keys = vi.hoisted(() => ({
+ jwks: undefined as ReturnType<typeof jose.createLocalJWKSet> | undefined,
+ remoteJwksUrls: [] as string[],
+}));
+
+vi.mock("jose", async () => {
+ const actual = await vi.importActual<typeof jose>("jose");
+ return {
+ ...actual,
+ createRemoteJWKSet: (url: URL) => {
+ keys.remoteJwksUrls.push(url.toString());
+ const resolver = (
+ header: jose.JWSHeaderParameters,
+ token: jose.FlattenedJWSInput
+ ): Promise<jose.CryptoKey> => {
+ if (!keys.jwks) throw new Error("JWKS not initialised");
+ return keys.jwks(header, token);
+ };
+ return resolver as unknown as ReturnType<typeof actual.createRemoteJWKSet>;
+ },
+ };
+});
+
+import { isClerkOAuthJwt, validateJWT } from "../src/lib/jwt.js";
+import {
+ classifyAuthMethod,
+ evaluateMcpAuthentication,
+ resetJwtWarningLog,
+ setBearerChallenge,
+} from "../src/lib/mcp-http-auth.js";
+import {
+ rememberInvalidOAuthToken,
+ resetOpaqueOAuthTokenValidation,
+} from "../src/lib/oauth-token-validation.js";
+import { searchLibraries } from "../src/lib/api.js";
+
+const ISSUER = "https://clerk.context7.com";
+const AUDIENCE = "https://mcp.context7.com/mcp";
+const CLIENT_ID = "client_2abcDEF";
+const KID = "ins_test_key";
+
+let privateKey: jose.CryptoKey;
+let strangerKey: jose.CryptoKey;
+const fetchMock = vi.fn<typeof fetch>();
+
+interface TokenOptions {
+ typ?: string | null;
+ iss?: string;
+ aud?: string | string[] | null;
+ expiresIn?: number;
+ key?: jose.CryptoKey;
+ claims?: jose.JWTPayload;
+}
+
+async function sign({
+ typ = "at+jwt",
+ iss = ISSUER,
+ aud = AUDIENCE,
+ expiresIn = 3600,
+ key = privateKey,
+ claims = { client_id: CLIENT_ID },
+}: TokenOptions = {}): Promise<string> {
+ const now = Math.floor(Date.now() / 1000);
+ const payload: jose.JWTPayload = {
+ iss,
+ sub: "user_123",
+ iat: now - 5,
+ exp: now + expiresIn,
+ jti: "jti_123",
+ ...claims,
+ };
+ if (aud !== null) payload.aud = aud;
+ const header: jose.JWTHeaderParameters = { alg: "RS256", kid: KID };
+ if (typ !== null) header.typ = typ;
+ return new jose.SignJWT(payload).setProtectedHeader(header).sign(key);
+}
+
+/** The shape Clerk gives a session JWT: `typ: JWT`, no `aud`, session claims. */
+function sessionJwt(): Promise<string> {
+ return sign({ typ: "JWT", aud: null, claims: { sid: "sess_123", azp: "https://context7.com" } });
+}
+
+/** The shape of an OIDC ID token: `typ: JWT`, addressed to the OAuth client. */
+function idToken(): Promise<string> {
+ return sign({ typ: "JWT", aud: CLIENT_ID, claims: { nonce: "n", email: "[email protected]" } });
+}
+
+function challenge(error?: string): string {
+ let header = "";
+ const res = { set: (_name: string, value: string) => (header = value) } as ExpressResponse;
+ setBearerChallenge(res, "/mcp", error);
+ return header;
+}
+
+beforeAll(async () => {
+ const pair = await jose.generateKeyPair("RS256");
+ privateKey = pair.privateKey;
+ strangerKey = (await jose.generateKeyPair("RS256")).privateKey;
+ const jwk = await jose.exportJWK(pair.publicKey);
+ keys.jwks = jose.createLocalJWKSet({ keys: [{ ...jwk, kid: KID, alg: "RS256", use: "sig" }] });
+});
+
+beforeEach(() => {
+ resetOpaqueOAuthTokenValidation();
+ resetJwtWarningLog();
+ fetchMock.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+function loggedLines(): string {
+ return vi.mocked(console.error).mock.calls.flat().map(String).join("\n");
+}
+
+describe("isClerkOAuthJwt", () => {
+ test("recognises only at+jwt tokens from the configured issuer", async () => {
+ expect(isClerkOAuthJwt(await sign())).toBe(true);
+ expect(isClerkOAuthJwt(await sign({ typ: "application/at+jwt" }))).toBe(true);
+ expect(isClerkOAuthJwt(await sign({ typ: "AT+JWT" }))).toBe(true);
+ expect(isClerkOAuthJwt(await sign({ typ: "JWT" }))).toBe(false);
+ expect(isClerkOAuthJwt(await sign({ typ: null }))).toBe(false);
+ expect(isClerkOAuthJwt(await sign({ iss: "https://clerk.context7.com/" }))).toBe(false);
+ expect(isClerkOAuthJwt(await sign({ iss: "https://evil.example" }))).toBe(false);
+ expect(isClerkOAuthJwt("oat_abc")).toBe(false);
+ expect(isClerkOAuthJwt("not.base64url!.x")).toBe(false);
+ expect(isClerkOAuthJwt(undefined)).toBe(false);
+ });
+
+ test("is only a router: classification does not imply trust", async () => {
+ const forged = await sign({ key: strangerKey });
+ expect(isClerkOAuthJwt(forged)).toBe(true);
+ expect(classifyAuthMethod(forged)).toBe("oauth");
+ await expect(validateJWT(forged)).resolves.toEqual({
+ valid: false,
+ error: "Invalid signature",
+ });
+ });
+});
+
+describe("a valid Clerk OAuth JWT", () => {
+ test("is accepted locally with no auth/check fetch and reported as oauth", async () => {
+ const token = await sign();
+
+ await expect(evaluateMcpAuthentication(token, "required")).resolves.toEqual({
+ allowed: true,
+ method: "oauth",
+ event: "credential_validated",
+ outcome: "accepted",
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(keys.remoteJwksUrls).toContain("https://clerk.context7.com/.well-known/jwks.json");
+ expect(loggedLines()).toBe("");
+ });
+
+ test("accepts application/at+jwt and an audience array that includes this server", async () => {
+ const token = await sign({
+ typ: "application/at+jwt",
+ aud: ["https://other.example/mcp", "https://MCP.context7.com/mcp/oauth/"],
+ });
+
+ await expect(validateJWT(token)).resolves.toEqual({ valid: true });
+ });
+
+ test("tolerates a minute of clock skew but no more", async () => {
+ await expect(validateJWT(await sign({ expiresIn: -30 }))).resolves.toEqual({ valid: true });
+ await expect(validateJWT(await sign({ expiresIn: -90 }))).resolves.toEqual({
+ valid: false,
+ error: "Token expired",
+ });
+ });
+});
+
+describe("an expired Clerk OAuth JWT", () => {
+ test("gets a 401 with an invalid_token challenge in both modes", async () => {
+ const token = await sign({ expiresIn: -600 });
+
+ for (const mode of ["observe", "required"] as const) {
+ const decision = await evaluateMcpAuthentication(token, mode);
+ expect(decision).toEqual({
+ allowed: false,
+ method: "oauth",
+ error: "Token expired",
+ event: "credential_rejected",
+ outcome: "expired",
+ });
+ expect(challenge(decision.allowed ? undefined : decision.error)).toBe(
+ 'Bearer error="invalid_token", error_description="Token expired", resource_metadata="https://mcp.context7.com/.well-known/oauth-protected-resource/mcp"'
+ );
+ }
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("Clerk ID tokens and session JWTs", () => {
+ test("are rejected with 401 whatever the audience enforcement", async () => {
+ for (const enforcement of ["observe", "required"]) {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", enforcement);
+ for (const token of [await idToken(), await sessionJwt()]) {
+ expect(classifyAuthMethod(token)).toBe("jwt");
+ await expect(evaluateMcpAuthentication(token, "observe")).resolves.toEqual({
+ allowed: false,
+ method: "jwt",
+ error: "Not an OAuth access token",
+ event: "credential_rejected",
+ outcome: "invalid",
+ });
+ }
+ }
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ test("the ID token's audience (the OAuth client) is not an allowed audience either", async () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "required");
+ // Same claims as the ID token but relabelled as an access token: the
+ // audience check is the second line of defence.
+ const relabelled = await sign({ aud: CLIENT_ID });
+ await expect(validateJWT(relabelled)).resolves.toMatchObject({
+ valid: false,
+ error: "Token audience not accepted",
+ });
+ });
+});
+
+describe("audience enforcement", () => {
+ const foreign = () => sign({ aud: "https://other-mcp.example/mcp" });
+
+ test("observe (default) admits a foreign audience and logs the client and audience", async () => {
+ const token = await foreign();
+
+ await expect(evaluateMcpAuthentication(token, "required")).resolves.toMatchObject({
+ allowed: true,
+ method: "oauth",
+ event: "credential_validated",
+ outcome: "accepted",
+ });
+
+ const logged = loggedLines();
+ expect(logged).toContain(
+ `audienceMismatch clientId=${CLIENT_ID} aud=https://other-mcp.example/mcp enforcement=observe`
+ );
+ expect(logged).not.toContain(token);
+ expect(logged).not.toContain(token.split(".")[2]);
+ });
+
+ test("logs the same mismatched token once, and each other token once", async () => {
+ const missing = await sign({ aud: null });
+ const other = await sign({ aud: null, claims: { client_id: CLIENT_ID, jti: "jti_other" } });
+
+ for (let i = 0; i < 3; i += 1) {
+ await expect(evaluateMcpAuthentication(missing, "required")).resolves.toMatchObject({
+ allowed: true,
+ outcome: "accepted",
+ });
+ }
+ await expect(evaluateMcpAuthentication(other, "required")).resolves.toMatchObject({
+ allowed: true,
+ });
+
+ const lines = vi.mocked(console.error).mock.calls.map((call) => String(call[0]));
+ expect(lines).toEqual([
+ `[Context7] audienceMismatch clientId=${CLIENT_ID} aud=missing enforcement=observe suppressedSincePrevious=0`,
+ `[Context7] audienceMismatch clientId=${CLIENT_ID} aud=missing enforcement=observe suppressedSincePrevious=0`,
+ ]);
+ });
+
+ test("observe logs a missing audience as such", async () => {
+ const token = await sign({ aud: null, claims: {} });
+
+ await expect(validateJWT(token)).resolves.toEqual({
+ valid: true,
+ warning: "audienceMismatch clientId=unknown aud=missing enforcement=observe",
+ });
+ });
+
+ test("required rejects a foreign or missing audience with 401 and still logs it", async () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "required");
+
+ for (const token of [await foreign(), await sign({ aud: null })]) {
+ await expect(evaluateMcpAuthentication(token, "observe")).resolves.toEqual({
+ allowed: false,
+ method: "oauth",
+ error: "Token audience not accepted",
+ event: "credential_rejected",
+ outcome: "invalid",
+ });
+ }
+ expect(loggedLines()).toContain(
+ `audienceMismatch clientId=${CLIENT_ID} aud=https://other-mcp.example/mcp enforcement=required`
+ );
+ expect(loggedLines()).toContain("aud=missing enforcement=required");
+
+ await expect(evaluateMcpAuthentication(await sign(), "required")).resolves.toMatchObject({
+ allowed: true,
+ });
+ });
+
+ test("MCP_OAUTH_ALLOWED_AUDIENCES replaces the default list", async () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "required");
+ vi.stubEnv("MCP_OAUTH_ALLOWED_AUDIENCES", "http://localhost:8787/mcp/");
+
+ await expect(validateJWT(await sign({ aud: "http://localhost:8787/mcp" }))).resolves.toEqual({
+ valid: true,
+ });
+ await expect(validateJWT(await sign())).resolves.toMatchObject({ valid: false });
+ });
+});
+
+describe("a Clerk OAuth JWT the Context7 API rejected", () => {
+ test("is challenged on the next request without re-verification", async () => {
+ const token = await sign();
+ const now = Date.now();
+ rememberInvalidOAuthToken(token, now);
+
+ await expect(evaluateMcpAuthentication(token, "observe")).resolves.toEqual({
+ allowed: false,
+ method: "oauth",
+ error: "The access token expired or is invalid",
+ event: "credential_rejected",
+ outcome: "expired",
+ });
+
+ // The memory is per token: a fresh token for the same user is unaffected.
+ const refreshed = await sign({ claims: { client_id: CLIENT_ID, jti: "jti_456" } });
+ await expect(evaluateMcpAuthentication(refreshed, "observe")).resolves.toMatchObject({
+ allowed: true,
+ });
+ });
+
+ test("is remembered by api.ts when a tool call answers 401 invalid_oauth_token", async () => {
+ const token = await sign();
+ fetchMock.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ error: "invalid_oauth_token",
+ message: "Invalid or expired OAuth token.",
+ }),
+ { status: 401, headers: { "content-type": "application/json" } }
+ )
+ );
+
+ const result = await searchLibraries("q", "react", { apiKey: token, transport: "http" });
+ expect(result.error).toBe(
+ "Your Context7 sign-in expired. Retry the request so your MCP client can refresh the sign-in."
+ );
+ expect(loggedLines()).not.toContain(token);
+
+ await expect(evaluateMcpAuthentication(token, "required")).resolves.toMatchObject({
+ allowed: false,
+ outcome: "expired",
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("the opaque oat_ path", () => {
+ test("still asks the Context7 API and never touches the JWKS", async () => {
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await expect(evaluateMcpAuthentication("oat_still_opaque", "required")).resolves.toEqual({
+ allowed: true,
+ method: "oauth",
+ event: "credential_validated",
+ outcome: "accepted",
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(String(fetchMock.mock.calls[0][0])).toMatch(/\/v2\/auth\/check$/);
+ });
+});
diff --git a/packages/mcp/test/jwt.test.ts b/packages/mcp/test/jwt.test.ts
index d7a8b3ed..d481dacc 100644
--- a/packages/mcp/test/jwt.test.ts
+++ b/packages/mcp/test/jwt.test.ts
@@ -35,12 +35,22 @@ function makeFetchResponse(init: Partial<Response> & { jsonData?: unknown }): Re
} as Response;
}
-function makeEntraToken(payload: jose.JWTPayload): string {
- const header = Buffer.from(JSON.stringify({ alg: "RS256", typ: "JWT" })).toString("base64url");
+function makeEntraToken(payload: jose.JWTPayload, typ = "JWT"): string {
+ const header = Buffer.from(JSON.stringify({ alg: "RS256", typ })).toString("base64url");
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
return `${header}.${body}.signature`;
}
+function makeClerkToken(payload: jose.JWTPayload, typ = "at+jwt"): string {
+ return makeEntraToken({ aud: "https://mcp.context7.com/mcp", ...payload }, typ);
+}
+
+const CLERK_VERIFY_OPTIONS = {
+ issuer: "https://clerk.context7.com",
+ typ: "at+jwt",
+ clockTolerance: 60,
+};
+
beforeEach(() => {
vi.stubGlobal("fetch", vi.fn());
vi.stubEnv("VERCEL_MARKETPLACE_OIDC_ISSUER", VERCEL_ISSUER);
@@ -183,17 +193,19 @@ describe("validateJWT - Entra path", () => {
});
describe("validateJWT - Clerk path", () => {
- test("verifies against Clerk JWKS for non-Entra issuers", async () => {
+ test("verifies a Clerk access token against the Clerk JWKS without any fetch", async () => {
vi.mocked(jose.jwtVerify).mockResolvedValue({
- payload: {},
- protectedHeader: { alg: "RS256" },
+ payload: { aud: "https://mcp.context7.com/mcp" },
+ protectedHeader: { alg: "RS256", typ: "at+jwt" },
} as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);
const { validateJWT } = await loadModule();
- const result = await validateJWT(makeEntraToken({ iss: "https://clerk.context7.com" }));
+ const token = makeClerkToken({ iss: "https://clerk.context7.com" });
+ const result = await validateJWT(token);
- expect(result.valid).toBe(true);
+ expect(result).toEqual({ valid: true });
expect(fetch).not.toHaveBeenCalled();
+ expect(jose.jwtVerify).toHaveBeenCalledWith(token, "fake-jwks", CLERK_VERIFY_OPTIONS);
});
test("returns 'Token expired' when jwtVerify throws JWTExpired", async () => {
@@ -202,29 +214,54 @@ describe("validateJWT - Clerk path", () => {
);
const { validateJWT } = await loadModule();
- const result = await validateJWT(makeEntraToken({ iss: "https://clerk.context7.com" }));
+ const result = await validateJWT(makeClerkToken({ iss: "https://clerk.context7.com" }));
expect(result.valid).toBe(false);
expect(result.error).toBe("Token expired");
});
+ test("rejects Clerk ID tokens and session JWTs before any key lookup", async () => {
+ const { validateJWT } = await loadModule();
+
+ for (const typ of ["JWT", "jwt", undefined]) {
+ const result = await validateJWT(makeEntraToken({ iss: "https://clerk.context7.com" }, typ));
+ expect(result).toEqual({ valid: false, error: "Not an OAuth access token" });
+ }
+ expect(jose.jwtVerify).not.toHaveBeenCalled();
+ });
+
+ test("rejects JWTs from an untrusted issuer without a key lookup", async () => {
+ const { validateJWT } = await loadModule();
+
+ await expect(validateJWT(makeClerkToken({ iss: "https://evil.example" }))).resolves.toEqual({
+ valid: false,
+ error: "Untrusted issuer",
+ });
+ await expect(validateJWT(makeClerkToken({}))).resolves.toEqual({
+ valid: false,
+ error: "Untrusted issuer",
+ });
+ expect(jose.jwtVerify).not.toHaveBeenCalled();
+ });
+
test("uses the configured OAuth issuer and its JWKS for verification", async () => {
process.env.OAUTH_AUTH_SERVER_URL = "https://supreme-foal-19.clerk.accounts.dev/";
vi.mocked(jose.jwtVerify).mockResolvedValue({
- payload: {},
- protectedHeader: { alg: "RS256" },
+ payload: { aud: "https://mcp.context7.com/mcp" },
+ protectedHeader: { alg: "RS256", typ: "at+jwt" },
} as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);
const { validateJWT } = await loadModule();
const result = await validateJWT(
- makeEntraToken({ iss: "https://supreme-foal-19.clerk.accounts.dev" })
+ makeClerkToken({ iss: "https://supreme-foal-19.clerk.accounts.dev" })
);
- expect(result.valid).toBe(true);
+ expect(result).toEqual({ valid: true });
expect(jose.createRemoteJWKSet).toHaveBeenCalledWith(
new URL("https://supreme-foal-19.clerk.accounts.dev/.well-known/jwks.json")
);
expect(jose.jwtVerify).toHaveBeenCalledWith(expect.any(String), "fake-jwks", {
+ ...CLERK_VERIFY_OPTIONS,
issuer: "https://supreme-foal-19.clerk.accounts.dev",
});
});
@@ -268,20 +305,16 @@ describe("validateJWT - Vercel Marketplace OIDC path", () => {
});
test("does not trust lookalike Vercel hosts", async () => {
- vi.mocked(jose.jwtVerify).mockResolvedValue({
- payload: {},
- protectedHeader: { alg: "RS256" },
- } as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);
-
const { validateJWT } = await loadModule();
const token = makeEntraToken({
iss: "https://integrations.vercel.com.attacker.test/oac_123456789",
});
- await validateJWT(token);
- expect(jose.jwtVerify).toHaveBeenCalledWith(token, "fake-jwks", {
- issuer: "https://clerk.context7.com",
+ await expect(validateJWT(token)).resolves.toEqual({
+ valid: false,
+ error: "Untrusted issuer",
});
+ expect(jose.jwtVerify).not.toHaveBeenCalled();
});
test("rejects tokens from another Vercel integration", async () => {
diff --git a/packages/mcp/test/log-throttle.test.ts b/packages/mcp/test/log-throttle.test.ts
new file mode 100644
index 00000000..8e51e24f
--- /dev/null
+++ b/packages/mcp/test/log-throttle.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, test } from "vitest";
+import { createPerTokenLogWindow } from "../src/lib/log-throttle.js";
+
+describe("createPerTokenLogWindow", () => {
+ test("admits a token once per window and reports what it suppressed", () => {
+ const window = createPerTokenLogWindow(10_000);
+ const start = 1_000_000;
+
+ expect(window.admit("token-a", start)).toBe(0);
+ expect(window.admit("token-a", start + 1)).toBeUndefined();
+ expect(window.admit("token-a", start + 9_999)).toBeUndefined();
+
+ // The next admission carries the two suppressed lines, then counts afresh.
+ expect(window.admit("token-a", start + 10_000)).toBe(2);
+ expect(window.admit("token-a", start + 10_001)).toBeUndefined();
+ expect(window.admit("token-a", start + 20_000)).toBe(1);
+ });
+
+ test("keeps tokens independent", () => {
+ const window = createPerTokenLogWindow(10_000);
+ const start = 2_000_000;
+
+ expect(window.admit("token-a", start)).toBe(0);
+ expect(window.admit("token-b", start)).toBe(0);
+ expect(window.admit("token-a", start + 1)).toBeUndefined();
+ expect(window.admit("token-b", start + 1)).toBeUndefined();
+ });
+
+ test("bounds its size by evicting the oldest token", () => {
+ const window = createPerTokenLogWindow(10_000, 2);
+ const start = 3_000_000;
+
+ window.admit("token-a", start);
+ window.admit("token-b", start + 1);
+ window.admit("token-c", start + 2);
+
+ // token-a was evicted, so it logs again inside its window; token-c stays.
+ expect(window.admit("token-a", start + 3)).toBe(0);
+ expect(window.admit("token-c", start + 4)).toBeUndefined();
+ });
+
+ test("forgets everything on reset", () => {
+ const window = createPerTokenLogWindow(10_000);
+ window.admit("token-a", 0);
+ window.reset();
+ expect(window.admit("token-a", 1)).toBe(0);
+ });
+});
diff --git a/packages/mcp/test/mcp-http-auth.test.ts b/packages/mcp/test/mcp-http-auth.test.ts
index 83ebadbc..8412ff55 100644
--- a/packages/mcp/test/mcp-http-auth.test.ts
+++ b/packages/mcp/test/mcp-http-auth.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, test, vi } from "vitest";
vi.mock("../src/lib/jwt.js", () => ({
isJWT: (token: string) => token.split(".").length === 3,
+ isClerkOAuthJwt: (token: string | undefined) => token?.startsWith("clerk.") ?? false,
validateJWT: vi.fn(),
}));
@@ -11,7 +12,12 @@ vi.mock("../src/lib/oauth-token-validation.js", async (importOriginal) => ({
}));
import { validateJWT } from "../src/lib/jwt.js";
-import { validateOpaqueOAuthToken } from "../src/lib/oauth-token-validation.js";
+import {
+ rememberInvalidOAuthToken,
+ resetOpaqueOAuthTokenValidation,
+ validateOpaqueOAuthToken,
+} from "../src/lib/oauth-token-validation.js";
+import { resetJwtWarningLog } from "../src/lib/mcp-http-auth.js";
import {
classifyAuthMethod,
effectiveMcpAuthMode,
@@ -20,8 +26,11 @@ import {
} from "../src/lib/mcp-http-auth.js";
afterEach(() => {
+ resetOpaqueOAuthTokenValidation();
+ resetJwtWarningLog();
vi.unstubAllEnvs();
vi.clearAllMocks();
+ vi.restoreAllMocks();
});
describe("MCP HTTP authentication policy", () => {
@@ -29,6 +38,7 @@ describe("MCP HTTP authentication policy", () => {
expect(classifyAuthMethod(undefined)).toBe("none");
expect(classifyAuthMethod("oat_example")).toBe("oauth");
expect(classifyAuthMethod("header.payload.signature")).toBe("jwt");
+ expect(classifyAuthMethod("clerk.payload.signature")).toBe("oauth");
expect(classifyAuthMethod("ctx7sk_example")).toBe("api_key");
});
@@ -143,6 +153,91 @@ describe("MCP HTTP authentication policy", () => {
allowed: false,
error: "Token expired",
event: "credential_rejected",
+ outcome: "invalid",
+ });
+ });
+
+ test("reports an expired Clerk OAuth JWT like an expired opaque token", async () => {
+ vi.mocked(validateJWT).mockResolvedValueOnce({ valid: false, error: "Token expired" });
+
+ await expect(evaluateMcpAuthentication("clerk.payload.signature", "observe")).resolves.toEqual({
+ allowed: false,
+ method: "oauth",
+ error: "Token expired",
+ event: "credential_rejected",
+ outcome: "expired",
+ });
+ expect(validateOpaqueOAuthToken).not.toHaveBeenCalled();
+ });
+
+ test("logs a validation warning without the token and still admits the request", async () => {
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+ vi.mocked(validateJWT).mockResolvedValueOnce({
+ valid: true,
+ warning: "audienceMismatch clientId=client_1 aud=https://other.example enforcement=observe",
+ });
+
+ await expect(evaluateMcpAuthentication("clerk.payload.signature", "required")).resolves.toEqual(
+ {
+ allowed: true,
+ method: "oauth",
+ event: "credential_validated",
+ outcome: "accepted",
+ }
+ );
+ const logged = consoleError.mock.calls.flat().map(String).join("\n");
+ expect(logged).toContain("audienceMismatch clientId=client_1 aud=https://other.example");
+ expect(logged).not.toContain("clerk.payload.signature");
+ });
+
+ test("logs a repeated warning once per token and keeps rejecting in required mode", async () => {
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+ const warning = (aud: string) => ({
+ valid: false,
+ error: "Token audience not accepted",
+ warning: `audienceMismatch clientId=client_1 aud=${aud} enforcement=required`,
+ });
+ vi.mocked(validateJWT)
+ .mockResolvedValueOnce(warning("missing"))
+ .mockResolvedValueOnce(warning("missing"))
+ .mockResolvedValueOnce(warning("missing"))
+ .mockResolvedValueOnce(warning("https://other.example"));
+
+ for (let i = 0; i < 3; i += 1) {
+ await expect(
+ evaluateMcpAuthentication("clerk.first.signature", "observe")
+ ).resolves.toMatchObject({ allowed: false, error: "Token audience not accepted" });
+ }
+ await expect(
+ evaluateMcpAuthentication("clerk.second.signature", "observe")
+ ).resolves.toMatchObject({ allowed: false });
+
+ expect(consoleError).toHaveBeenCalledTimes(2);
+ expect(consoleError.mock.calls[0][0]).toBe(
+ "[Context7] audienceMismatch clientId=client_1 aud=missing enforcement=required suppressedSincePrevious=0"
+ );
+ expect(consoleError.mock.calls[1][0]).toBe(
+ "[Context7] audienceMismatch clientId=client_1 aud=https://other.example enforcement=required suppressedSincePrevious=0"
+ );
+ });
+
+ test("challenges a Clerk OAuth JWT the Context7 API rejected earlier", async () => {
+ rememberInvalidOAuthToken("clerk.payload.signature");
+
+ await expect(evaluateMcpAuthentication("clerk.payload.signature", "observe")).resolves.toEqual({
+ allowed: false,
+ method: "oauth",
+ error: "The access token expired or is invalid",
+ event: "credential_rejected",
+ outcome: "expired",
});
+ expect(validateJWT).not.toHaveBeenCalled();
+
+ // Other JWTs are never looked up in the OAuth verdict cache.
+ rememberInvalidOAuthToken("header.payload.signature");
+ vi.mocked(validateJWT).mockResolvedValueOnce({ valid: true });
+ await expect(
+ evaluateMcpAuthentication("header.payload.signature", "observe")
+ ).resolves.toMatchObject({ allowed: true, method: "jwt" });
});
});
diff --git a/packages/mcp/test/oauth-audience.test.ts b/packages/mcp/test/oauth-audience.test.ts
new file mode 100644
index 00000000..3856f214
--- /dev/null
+++ b/packages/mcp/test/oauth-audience.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, describe, expect, test, vi } from "vitest";
+import {
+ checkOAuthAudience,
+ defaultOAuthAllowedAudiences,
+ getAllowedOAuthAudiences,
+ normalizeAudience,
+ parseOAuthAudienceEnforcement,
+} from "../src/lib/oauth-audience.js";
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("normalizeAudience", () => {
+ test("lowercases scheme and host, drops default port, fragment and trailing slashes", () => {
+ expect(normalizeAudience(" HTTPS://MCP.Context7.com:443/mcp/ ")).toBe(
+ "https://mcp.context7.com/mcp"
+ );
+ expect(normalizeAudience("https://mcp.context7.com/#frag")).toBe("https://mcp.context7.com");
+ expect(normalizeAudience("https://mcp.context7.com/MCP")).toBe("https://mcp.context7.com/MCP");
+ expect(normalizeAudience("http://localhost:8787/mcp?x=1")).toBe(
+ "http://localhost:8787/mcp?x=1"
+ );
+ });
+
+ test("only trims values that are not http(s) URLs", () => {
+ expect(normalizeAudience(" client_abc ")).toBe("client_abc");
+ expect(normalizeAudience("urn:example:mcp/")).toBe("urn:example:mcp");
+ });
+});
+
+describe("allowed audiences", () => {
+ test("defaults to the resource origin and both MCP endpoints", () => {
+ expect(defaultOAuthAllowedAudiences("https://mcp.context7.com/mcp")).toEqual([
+ "https://mcp.context7.com",
+ "https://mcp.context7.com/mcp",
+ "https://mcp.context7.com/mcp/oauth",
+ ]);
+ expect(getAllowedOAuthAudiences(undefined)).toEqual(new Set(defaultOAuthAllowedAudiences()));
+ });
+
+ test("reads a comma-separated override and normalizes each entry", () => {
+ expect(getAllowedOAuthAudiences(" https://a.example/ , HTTP://b.example:80/mcp,, ")).toEqual(
+ new Set(["https://a.example", "http://b.example/mcp"])
+ );
+ });
+});
+
+describe("parseOAuthAudienceEnforcement", () => {
+ test("defaults to observe and accepts both modes", () => {
+ expect(parseOAuthAudienceEnforcement(undefined)).toBe("observe");
+ expect(parseOAuthAudienceEnforcement("")).toBe("observe");
+ expect(parseOAuthAudienceEnforcement(" Observe ")).toBe("observe");
+ expect(parseOAuthAudienceEnforcement("REQUIRED")).toBe("required");
+ });
+
+ test("rejects unknown values", () => {
+ expect(() => parseOAuthAudienceEnforcement("require")).toThrow(/observe.*required/);
+ });
+});
+
+describe("checkOAuthAudience", () => {
+ test("treats a missing or non-string audience as a mismatch", () => {
+ expect(checkOAuthAudience(undefined)).toEqual({
+ allowed: false,
+ aud: "missing",
+ enforcement: "observe",
+ });
+ expect(checkOAuthAudience([])).toMatchObject({ allowed: false, aud: "missing" });
+ expect(checkOAuthAudience(42)).toMatchObject({ allowed: false, aud: "missing" });
+ });
+
+ test("accepts a string or array containing an allowed audience", () => {
+ expect(checkOAuthAudience("https://mcp.context7.com/mcp/")).toMatchObject({ allowed: true });
+ expect(checkOAuthAudience(["http://localhost:8787", "https://MCP.context7.com"])).toEqual({
+ allowed: true,
+ aud: "http://localhost:8787,https://mcp.context7.com",
+ enforcement: "observe",
+ });
+ });
+
+ test("reports the enforcement mode and honours the override list", () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "required");
+ vi.stubEnv("MCP_OAUTH_ALLOWED_AUDIENCES", "http://localhost:8787");
+
+ expect(checkOAuthAudience(["http://localhost:8787/"])).toEqual({
+ allowed: true,
+ aud: "http://localhost:8787",
+ enforcement: "required",
+ });
+ expect(checkOAuthAudience("https://mcp.context7.com/mcp")).toEqual({
+ allowed: false,
+ aud: "https://mcp.context7.com/mcp",
+ enforcement: "required",
+ });
+ });
+});
diff --git a/packages/mcp/test/oauth-token-validation.test.ts b/packages/mcp/test/oauth-token-validation.test.ts
index 5347cb52..6ee8b803 100644
--- a/packages/mcp/test/oauth-token-validation.test.ts
+++ b/packages/mcp/test/oauth-token-validation.test.ts
@@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
+ INVALID_TTL_MS,
+ isOAuthTokenRememberedInvalid,
isOpaqueOAuthToken,
isOpaqueOAuthTokenValidationEnabled,
- rememberInvalidOpaqueOAuthToken,
+ rememberInvalidOAuthToken,
resetOpaqueOAuthTokenValidation,
validateOpaqueOAuthToken,
} from "../src/lib/oauth-token-validation.js";
@@ -95,7 +97,8 @@ describe("opaque OAuth token validation", () => {
expect(logged).not.toContain("oat_");
});
- test("caches a valid verdict for a minute and an invalid one for 30 seconds", async () => {
+ test("caches a valid verdict for a minute and an invalid one for ten minutes", async () => {
+ expect(INVALID_TTL_MS).toBe(10 * 60_000);
const start = 1_000_000;
fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
await expect(validateOpaqueOAuthToken("oat_valid", start)).resolves.toBe("valid");
@@ -104,12 +107,16 @@ describe("opaque OAuth token validation", () => {
fetchMock.mockResolvedValueOnce(rejected());
await expect(validateOpaqueOAuthToken("oat_expired", start)).resolves.toBe("invalid");
- await expect(validateOpaqueOAuthToken("oat_expired", start + 29_000)).resolves.toBe("invalid");
+ await expect(validateOpaqueOAuthToken("oat_expired", start + 9 * 60_000)).resolves.toBe(
+ "invalid"
+ );
expect(fetchMock).toHaveBeenCalledTimes(2);
// Each verdict is re-checked once its own TTL lapses.
fetchMock.mockResolvedValueOnce(rejected());
- await expect(validateOpaqueOAuthToken("oat_expired", start + 31_000)).resolves.toBe("invalid");
+ await expect(validateOpaqueOAuthToken("oat_expired", start + 11 * 60_000)).resolves.toBe(
+ "invalid"
+ );
fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
await expect(validateOpaqueOAuthToken("oat_valid", start + 61_000)).resolves.toBe("valid");
expect(fetchMock).toHaveBeenCalledTimes(4);
@@ -146,12 +153,24 @@ describe("opaque OAuth token validation", () => {
fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
await expect(validateOpaqueOAuthToken("oat_revoked", start)).resolves.toBe("valid");
- rememberInvalidOpaqueOAuthToken("oat_revoked", start + 1_000);
+ rememberInvalidOAuthToken("oat_revoked", start + 1_000);
await expect(validateOpaqueOAuthToken("oat_revoked", start + 2_000)).resolves.toBe("invalid");
expect(fetchMock).toHaveBeenCalledTimes(1);
});
+ test("remembers a rejected JWT by hash for the invalid TTL", () => {
+ const start = 5_000_000;
+ const jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6ImF0K2p3dCJ9.eyJpc3MiOiJ4In0.signature";
+ expect(isOAuthTokenRememberedInvalid(jwt, start)).toBe(false);
+
+ rememberInvalidOAuthToken(jwt, start);
+
+ expect(isOAuthTokenRememberedInvalid(jwt, start + INVALID_TTL_MS - 1)).toBe(true);
+ expect(isOAuthTokenRememberedInvalid(jwt, start + INVALID_TTL_MS)).toBe(false);
+ expect(isOAuthTokenRememberedInvalid("other.jwt.signature", start)).toBe(false);
+ });
+
test("bounds the cache size", async () => {
const start = 4_000_000;
for (let index = 0; index < 10_001; index += 1) {