Files
Tom Moor b4601a61ff feat: Support OAuth Client ID Metadata Documents for MCP clients (#14015)
* feat: Support OAuth Client ID Metadata Documents for MCP clients

MCP clients can send an https URL as their client_id. The server fetches
the metadata document at that URL and caches one team-less client row per
URL, so MCP works on the root domain without dynamic registration.

Closes #14010

* fix: Address review findings for client ID metadata documents

- Only count unexpired tokens when cleaning up metadata document clients
- Reject backslashes, whitespace and trailing host dots in client_id URLs
- Strip trailing dots before installation host comparisons
- Type clientSecret as nullable

* fix: Keep OAuth clients with pending authorization codes during cleanup

* refactor: Simplify client ID metadata document handling

- Gate metadata document fetches on the MCP preference inside the helper
- Add isMCPClient getter and a shared client ID prefix constant
- Enforce the team/metadata document CHECK in both directions
- Index oauthClientId on OAuth token and code tables
- Reuse parseDomain, clamp and time helpers

* revert: Remove pending authorization code check from OAuth client cleanup

* fix: Block all special-use addresses when fetching client metadata documents

ALLOWED_PRIVATE_IP_ADDRESSES no longer applies to client ID metadata
document requests (draft -02 section 8.6). The fetch wrapper takes an
allowIPAddressList option to override the environment list.

* fix: Reject empty userinfo in client metadata document URLs

https://@host and https://:@host have a userinfo component that the URL
parser drops, so check the raw authority (draft -02 section 3).

* fix: Accept a root path in client metadata document URLs

Draft -02 section 3 marks a root path as NOT RECOMMENDED, not invalid, so
https://example.com/ is a valid client_id. A URL with no path is still
rejected.

* fix: Reject client metadata documents with private key material

A jwks key with private or symmetric members (d, p, q, dp, dq, qi, oth,
k) makes the document invalid, so it is not cached (draft -02 section 4.1).
Public keys are still ignored.

* fix: Respect no-cache, no-store and Age for client metadata documents

no-store and no-cache now expire the cached document at once, so it is
fetched again before the next authorization. Freshness from max-age or
Expires (measured from Date) is reduced by Age before clamping (draft -02
section 5.2).

* feat: Copy DCR and CIMD client logos to file storage in the background

logo_uri was rendered directly on the consent screen, which lets the logo
host track users and change the image at any time (draft -02 sections 8.8
and 9.2). A background task now fetches the logo with the strict fetch
rules, accepts only PNG, JPEG, GIF and WebP by their leading bytes, and
stores it content addressed in the public bucket. Requests never wait for
the upload.

* fix: Match loopback redirect URIs on any port

Native apps such as Claude Code register http://localhost/callback and
then listen on a free port, so an exact match rejected them. Loopback
redirect URIs now match on any port (RFC 8252 section 7.3); the scheme,
host and path must still match, and other URIs still match exactly.

* fix: Only break the redirect URL mid-word on the consent screen

break-all on the whole notice split words such as "continue" in the
loopback warning. It now applies only to the redirect URL.

* chore: Shorten the loopback warning on the consent screen

* fix: Show the punycode host of client metadata documents on the consent screen

A lookalike Unicode host was shown as written. Hostnames now come from a
shared getHostname helper that returns the punycode form.

* refactor: Move image type detection to ImageHelper and use it for avatars

Avatars and integration logos copied from a URL are now stored only if
they are PNG, JPEG, GIF or WebP, with the content type detected from the
file data rather than the remote host.

* fix: Address review findings for OAuth client logos and metadata caching

- Count the time since the Date header as age when caching metadata
  documents, so a document is not cached past its Expires time
- Log logo scheduling failures instead of failing registration requests
- Run dynamic client registration in a transaction
- Delete copied logos from storage when no client uses them

* fix: Store one logo per OAuth client and return a distinct metadata document error

- Logos are stored per client, so a file is only deleted when its own
  client stops using it. This removes the reference count and its race.
- A metadata document that cannot be fetched or is invalid now returns
  invalid_client_metadata with the reason, not a 404. Network errors
  are only logged.
- Move scheduleOptional to BaseTask so that any task can use it.
2026-10-12 11:01:55 -04:00

391 lines
11 KiB
TypeScript

import crypto from "node:crypto";
import { subSeconds } from "date-fns";
import type {
RefreshTokenModel,
AuthorizationCodeModel,
User as OAuthUser,
} from "@node-oauth/oauth2-server";
import type { Required } from "utility-types";
import AuthenticationHelper from "@shared/helpers/AuthenticationHelper";
import {
OAuthClient,
OAuthAuthentication,
OAuthAuthorizationCode,
} from "@server/models";
import { hash, safeEqual } from "@server/utils/crypto";
import { OAuthHelper } from "./OAuthHelper";
/**
* The number of seconds during which a rotated refresh token may be replayed
* without triggering reuse detection. This provides a grace window for clients
* that issue concurrent refresh requests, preventing the entire grant from being
* revoked due to a benign race.
*/
const refreshTokenReuseInterval = 10;
/**
* Additional configuration for the OAuthInterface, not part of the
* OAuth2Server library.
*/
interface Config {
grants: string[];
}
/**
* An extension of the OAuth2Server User type that includes a grantId for
* session tracking.
*/
interface GrantUser extends OAuthUser {
grantId?: string;
}
/**
* This interface is used by the OAuth2Server library to handle OAuth2
* authentication and authorization flows. See the library's documentation:
*
* https://node-oauthoauth2-server.readthedocs.io/en/master/model/overview.html
*/
export const OAuthInterface: RefreshTokenModel &
Required<
AuthorizationCodeModel,
| "validateScope"
| "validateRedirectUri"
| "generateAccessToken"
| "generateRefreshToken"
| "generateAuthorizationCode"
> &
Config = {
/** Supported grant types */
grants: [...OAuthHelper.grantTypes],
/**
* Generates a new access token.
*
* @returns The generated access token.
*/
async generateAccessToken() {
return `${OAuthAuthentication.accessTokenPrefix}${crypto
.randomBytes(32)
.toString("hex")}`;
},
/**
* Generates a new refresh token.
*
* @returns The generated refresh token.
*/
async generateRefreshToken() {
return `${OAuthAuthentication.refreshTokenPrefix}${crypto
.randomBytes(32)
.toString("hex")}`;
},
/**
* Generates a new authorization code.
*
* @returns The generated authorization code.
*/
async generateAuthorizationCode() {
return `${OAuthAuthorizationCode.authorizationCodePrefix}${crypto
.randomBytes(32)
.toString("hex")}`;
},
/**
* Retrieves an access token by its value.
*
* @param accessToken The access token to retrieve.
* @returns The access token if found, false otherwise.
*/
async getAccessToken(accessToken: string) {
const authentication =
await OAuthAuthentication.findByAccessToken(accessToken);
if (!authentication) {
return false;
}
return {
accessToken,
accessTokenExpiresAt: authentication.accessTokenExpiresAt,
scope: authentication.scope,
client: {
id: authentication.oauthClient.clientId,
grants: this.grants,
},
user: authentication.user,
};
},
/**
* Retrieves a refresh token by its value, with reuse detection.
*
* @param refreshToken The refresh token to retrieve.
* @returns The refresh token if found, false otherwise.
*/
async getRefreshToken(refreshToken: string) {
let authentication =
await OAuthAuthentication.findByRefreshToken(refreshToken);
if (!authentication) {
// If the refresh token is not found, it may have already been used or
// revoked. In this case we perform reuse detection as recommended by RFC 9700.
authentication = await OAuthAuthentication.findOne({
where: {
refreshTokenHash: hash(refreshToken),
},
paranoid: false,
});
// A recently rotated token may be replayed by a client that issued
// concurrent refresh requests. Treat replays within the reuse interval as
// benign and skip revocation, so the grant won by the parallel request
// survives. Replays outside the window are treated as genuine reuse.
const reuseWindowStart = subSeconds(
new Date(),
refreshTokenReuseInterval
);
const withinReuseInterval =
authentication?.deletedAt &&
authentication.deletedAt > reuseWindowStart;
if (authentication?.grantId && !withinReuseInterval) {
await Promise.all([
OAuthAuthentication.destroy({
where: {
grantId: authentication.grantId,
},
}),
OAuthAuthorizationCode.destroy({
where: {
grantId: authentication.grantId,
},
}),
]);
}
return false;
}
const user = authentication.user;
Object.assign(user, { grantId: authentication.grantId });
return {
refreshToken,
refreshTokenExpiresAt: authentication.refreshTokenExpiresAt,
scope: authentication.scope,
client: {
id: authentication.oauthClient.clientId,
grants: this.grants,
},
user,
};
},
/**
* Retrieves an authorization code by its value.
*
* @param authorizationCode The authorization code to retrieve.
* @returns The authorization code if found, false otherwise.
*/
async getAuthorizationCode(authorizationCode) {
const code = await OAuthAuthorizationCode.findByCode(authorizationCode);
if (!code) {
return false;
}
const oauthClient = await OAuthClient.findByPk(code.oauthClientId);
if (!oauthClient) {
return false;
}
const user = code.user;
Object.assign(user, { grantId: code.grantId });
return {
authorizationCode,
expiresAt: code.expiresAt,
scope: code.scope,
redirectUri: code.redirectUri,
codeChallenge: code.codeChallenge,
codeChallengeMethod: code.codeChallengeMethod,
client: {
id: oauthClient.clientId,
grants: this.grants,
},
user,
};
},
/**
* Retrieves a client by its ID and secret.
*
* @param clientId The client ID.
* @param clientSecret The client secret.
* @returns The client if found and valid, false otherwise.
*/
async getClient(clientId: string, clientSecret?: string) {
const client = await OAuthClient.findByClientId(clientId);
if (!client) {
return false;
}
if (clientSecret && !safeEqual(client.clientSecret, clientSecret)) {
return false;
}
return {
id: client.clientId,
redirectUris: client.redirectUris,
clientType: client.clientType,
databaseId: client.id,
grants: this.grants,
};
},
/**
* Saves an access and refresh token.
*
* @param token The token object to save.
* @param client The client that requested the token.
* @param user The user that authorized the token.
* @returns The saved token.
*/
async saveToken(token, client, user) {
const {
accessToken,
refreshToken,
accessTokenExpiresAt,
refreshTokenExpiresAt,
} = token;
const accessTokenHash = hash(accessToken);
const refreshTokenHash = refreshToken ? hash(refreshToken) : undefined;
await OAuthAuthentication.create({
accessTokenHash,
refreshTokenHash,
accessTokenExpiresAt,
refreshTokenExpiresAt,
scope: token.scope,
oauthClientId: client.databaseId,
userId: user.id,
grantId: (user as GrantUser).grantId || crypto.randomUUID(),
});
return {
accessToken,
accessTokenExpiresAt,
refreshToken,
refreshTokenExpiresAt,
scope: token.scope,
client: {
id: client.id,
grants: this.grants,
},
user,
};
},
/**
* Saves an authorization code.
*
* @param code The authorization code object to save.
* @param client The client that requested the code.
* @param user The user that authorized the code.
* @returns The saved authorization code.
*/
async saveAuthorizationCode(code, client, user) {
const {
authorizationCode,
expiresAt,
redirectUri,
scope,
codeChallenge,
codeChallengeMethod,
} = code;
const authCode = await OAuthAuthorizationCode.create({
authorizationCodeHash: hash(authorizationCode),
expiresAt,
scope,
redirectUri,
codeChallenge,
codeChallengeMethod: codeChallengeMethod?.trim() || undefined,
oauthClientId: client.databaseId,
userId: user.id,
grantId: (user as GrantUser).grantId || crypto.randomUUID(),
});
return {
authorizationCode,
expiresAt,
scope,
redirectUri,
client: {
id: client.id,
grants: this.grants,
},
user: authCode.user,
};
},
/**
* Revokes a refresh token. The token is revoked atomically, so that only one
* of a set of concurrent requests can exchange it for new tokens.
*
* @param token The token object containing the refresh token to revoke.
* @returns True if the token was revoked, false otherwise.
*/
async revokeToken(token) {
return OAuthAuthentication.revokeByRefreshToken(token.refreshToken);
},
/**
* Revokes an authorization code. The code is consumed atomically, so that only
* one of a set of concurrent requests can exchange it for a token.
*
* @param code The authorization code object to revoke.
* @returns True if the code was revoked, false otherwise.
*/
async revokeAuthorizationCode(code) {
return OAuthAuthorizationCode.consume(code.authorizationCode);
},
/**
* Ensure the redirect URI is not plain HTTP. Custom protocols are allowed.
* Loopback addresses (RFC 8252 §7.3) are allowed with http:// for native apps.
*
* @param uri The redirect URI to validate.
* @returns True if the URI is valid, false otherwise.
*/
async validateRedirectUri(uri, client) {
const redirectUris = [client.redirectUris ?? []].flat();
if (!OAuthHelper.isRegisteredRedirectUri(redirectUris, uri)) {
return false;
}
return OAuthHelper.isValidRedirectUri(uri);
},
/**
* Invoked to check if the requested scope is valid for a particular
* client/user combination.
*
* @param scope The requested scopes.
* @returns The scopes if valid, false otherwise.
*/
async validateScope(user, client, scope) {
if (!scope?.length) {
return [];
}
const scopes = Array.isArray(scope) ? scope : [scope];
// OAuth clients cannot request scopes that grant unrestricted access.
return scopes.every((s: string) =>
AuthenticationHelper.isValidScope(s, { allowRootWildcard: false })
)
? scopes
: false;
},
};