SecurityOAuth 2.1

OAuth Security

Protocol-level hardening for OAuth 2.1 authorization, mandatory PKCE S256, RFC 8707 resource binding, DCR and CIMD validation, and atomic refresh token rotation.

Protocol baseline and threat model

Taicket MCP implements OAuth 2.1 as a standalone authorization server bridged to Discord Official OAuth2. Every remote MCP client authenticates against https://mcp.taicket.xyz/oauth/* before invoking /mcp. Legacy OAuth 2.0 grants with weak security properties, including the Implicit grant and Resource Owner Password Credentials grant, are disabled.

ControlStandardEnforcement Rule
PKCE S256OAuth 2.1 / RFC 7636Mandatory on every authorization request. Missing code_challenge or code_challenge_method=plain is rejected with invalid_request.
Resource bindingRFC 8707resource must equal the canonical MCP resource URL (https://mcp.taicket.xyz/mcp) at authorize, token exchange, and bearer verification.
Discovery metadataRFC 9728 / RFC 8414Unauthenticated /mcp requests return HTTP 401 with WWW-Authenticate pointing to /.well-known/oauth-protected-resource.
Transaction bindingServer state + cookie10-minute McpOAuthTransaction record bound to an HttpOnly cookie hash (cookieTokenHash) and form CSRF token hash (csrfTokenHash).
Authorization codesOAuth 2.1Single-use, 60-second TTL, stored as SHA-256 codeHash, atomically marked consumedAt on exchange.
Refresh rotationOAuth 2.1Atomic single-use rotation via MongoDB findOneAndUpdate. Replaying a rotated refresh token revokes the entire token family immediately.

PKCE S256 and RFC 8707 verification

During authorization, the client submits a base64url-encoded SHA-256 digest of a high-entropy code_verifier (43 to 128 characters). At POST /oauth/token, the server recomputes SHA-256 over the submitted code_verifier and compares it to the persisted codeChallenge using crypto.timingSafeEqual to prevent timing side channels.

RFC 8707 Resource Indicators prevent cross-service token confusion. Every token minted by Taicket MCP is audience-bound to https://mcp.taicket.xyz/mcp. If a client passes a mismatched resource parameter during authorization or token exchange, or presents a token whose resource claim does not match MCP_RESOURCE_URL, the request fails closed.

Constant-time PKCE S256 verificationtypescript
import crypto from 'node:crypto';

export function verifyPkceS256(codeVerifier: string, storedChallenge: string): boolean {
  if (codeVerifier.length < 43 || codeVerifier.length > 128) {
    return false;
  }
  const computed = crypto
    .createHash('sha256')
    .update(codeVerifier, 'ascii')
    .digest('base64url');

  const computedBuf = Buffer.from(computed, 'utf8');
  const storedBuf = Buffer.from(storedChallenge, 'utf8');
  if (computedBuf.length !== storedBuf.length) {
    return false;
  }
  return crypto.timingSafeEqual(computedBuf, storedBuf);
}

DCR and CIMD client registration controls

Clients register through either Dynamic Client Registration (RFC 7591 at POST /oauth/register) or Client ID Metadata Documents (CIMD). Both paths enforce strict redirect URI and network safety validation before persisting or caching client metadata in McpOAuthClient.

  • Exact redirect URI allowlisting:: Redirect URIs must use https:// with a public host, or loopback http://127.0.0.1 / http://localhost for local desktop clients. Wildcards, URI fragments (#), credential-bearing URLs, and non-loopback HTTP URIs are rejected.
  • Per-IP DCR rate limiting:: POST /oauth/register is protected by the taicket_mcp_oauth_limit Nginx zone (10 requests per second, burst 20) plus application IP tracking via createdByIpHash.
  • DNS-rebinding-pinned CIMD fetching:: When client_id is an HTTPS metadata URL, the server resolves DNS once, confirms every resolved IP is publicly routable (blocking RFC 1918, loopback, link-local 169.254.0.0/16, CGNAT 100.64.0.0/10, and multicast ranges), and pins the TLS connection to that validated IP with redirect handling disabled, a 5-second timeout, and a 32 KB response cap.
Dynamic Client Registration requesthttp
POST /oauth/register HTTP/1.1
Host: mcp.taicket.xyz
Content-Type: application/json

{
  "client_name": "Claude Desktop",
  "redirect_uris": [
    "https://claude.ai/api/mcp/auth_callback"
  ],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none"
}

Atomic refresh token rotation and replay family revocation

Refresh tokens carry a 30-day TTL and rotate on every POST /oauth/token call with grant_type=refresh_token. Rotation uses an atomic MongoDB findOneAndUpdate query conditioned on revokedAt: null and rotatedAt: null so concurrent refresh requests cannot race to mint duplicate descendant tokens.

Atomic rotation and family replay revocation patterntypescript
const claimed = await McpRefreshToken.findOneAndUpdate(
  {
    tokenHash: presentedHash,
    revokedAt: null,
    rotatedAt: null,
    expiresAt: { $gt: now },
  },
  {
    $set: {
      rotatedAt: now,
      replacedByHash: nextRefreshHash,
    },
  },
  { new: false }
);

if (!claimed) {
  const existing = await McpRefreshToken.findOne({ tokenHash: presentedHash }).lean();
  if (existing && existing.rotatedAt) {
    // Replay detected: revoke the entire grant family atomically.
    await Promise.all([
      McpOAuthGrant.updateMany(
        { familyId: existing.familyId, revokedAt: null },
        { $set: { revokedAt: now, revokedReason: 'refresh_token_reuse_detected' } }
      ),
      McpAccessToken.updateMany(
        { grantId: existing.grantId, revokedAt: null },
        { $set: { revokedAt: now } }
      ),
      McpRefreshToken.updateMany(
        { familyId: existing.familyId, revokedAt: null },
        { $set: { revokedAt: now } }
      ),
    ]);
  }
  throw new OAuthError('invalid_grant', 'Refresh token is invalid or has already been used.');
}

Replay response behavior

When a previously rotated refresh token is replayed, Taicket MCP revokes every access token, refresh token, and grant linked to that familyId. The legitimate client receives HTTP 401 on its next call and prompts the user to re-authorize.

Consent and callback hardening

Browser-facing OAuth endpoints (/oauth/authorize, /oauth/discord/callback, /oauth/consent) defend against login CSRF, clickjacking, and referrer leaks using layered HTTP and cookie controls.

  • HttpOnly session binding:: Pending authorization state is stored server-side in McpOAuthTransaction and linked to an HttpOnly, Secure, SameSite=Lax browser cookie hashed with SHA-256.
  • Per-transaction CSRF tokens:: Submitting /oauth/consent verifies the posted CSRF token against csrfTokenHash in constant time before minting an authorization code.
  • Strict response headers:: Nginx enforces X-Frame-Options: DENY, Referrer-Policy: no-referrer, Cache-Control: no-store, no-cache, must-revalidate, private, and Strict-Transport-Security on all /oauth/ routes.

Related documentation