Claude skill OAuth PKCE security vulnerabilities — SA-SKL-OAUTH3
OAuth authorization code flows in Claude MCP skills carry four recurring weaknesses: omitting PKCE entirely exposes the authorization code to interception via Referer leakage or a compromised redirect URI; skipping state validation before the token exchange opens a CSRF path where an attacker's code is exchanged under the victim's session; generating the PKCE code_verifier with Math.random() reduces entropy to 32 bits, making it brute-forceable against a stolen code; and persisting the access token in localStorage makes it readable by any JavaScript executing on the same origin. SA-SKL-OAUTH3 covers all four patterns with SkillAudit detection rules and correct Node.js fixes.
Why PKCE matters even for server-side skills
PKCE (Proof Key for Code Exchange, RFC 7636) was originally designed for public clients — mobile apps and SPAs that cannot keep a client secret confidential. Its threat model is authorization code interception: a malicious app on the same device intercepts the redirect URI and captures the code query parameter. For server-side MCP skills, the same risk appears in a different form: the code can leak via the Referer header when the callback page loads a third-party resource, via browser history, or via a redirect URI that partially matches a path an attacker controls.
Even without code interception, PKCE provides a second benefit for server-side skills: it binds the authorization request to the token exchange at the cryptographic level. If the token endpoint is ever confused about which authorization code belongs to which session (e.g., via a request-smuggling attack on a shared proxy), PKCE prevents an attacker's code from being exchanged in a victim's session. The code_challenge in the authorization request and the code_verifier in the token request form a cryptographic binding that the authorization server verifies.
SA-SKL-OAUTH3 in scope: OAUTH3-001 (missing PKCE entirely — no code_challenge or code_challenge_method), OAUTH3-002 (state parameter generated but not validated on callback before code exchange — CSRF), OAUTH3-003 (PKCE code_verifier generated with Math.random() — 32-bit entropy), OAUTH3-004 (access token stored in localStorage — readable by XSS). Each finding includes SkillAudit detection rules and corrected code.
OAUTH3-001 — Missing PKCE entirely in authorization code flow
An MCP skill that initiates an OAuth 2.0 authorization code flow to obtain a GitHub or Google token constructs the authorization URL without a code_challenge or code_challenge_method parameter. The authorization server issues a code that is not bound to any PKCE verifier. If that code leaks — through the Referer header when the callback page loads an analytics script, through browser history synchronization, or through a partial redirect URI match — an attacker who captures the code can exchange it at the token endpoint without needing the client secret (for public clients) or alongside stolen credentials (for confidential clients). RFC 9700 (OAuth 2.1) requires PKCE for all authorization code flows unconditionally.
The fix requires two additions: at authorization URL construction time, generate a cryptographically random 32-byte code_verifier, compute its SHA-256 hash as the code_challenge, and append code_challenge and code_challenge_method=S256 to the authorization URL. Store the code_verifier in the server-side session (not in a cookie that is sent to the browser). At the token exchange callback, retrieve the code_verifier from the session and include it in the token request body.
// VULNERABLE — authorization code flow with no PKCE
import { randomBytes } from 'crypto';
function buildAuthorizationUrl(clientId: string, redirectUri: string): string {
const state = randomBytes(16).toString('hex');
// Store state in session for CSRF check... (but no PKCE)
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
response_type: 'code',
scope: 'read:user repo',
state,
// Missing: code_challenge, code_challenge_method
// The authorization code that comes back is NOT bound to this session
});
return `https://github.com/login/oauth/authorize?${params}`;
}
async function exchangeCode(
code: string,
clientId: string,
clientSecret: string,
redirectUri: string
): Promise<{ access_token: string }> {
const response = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
code,
redirect_uri: redirectUri,
// Missing: code_verifier — no PKCE binding
}),
});
return response.json();
}
// FIXED — full PKCE S256 implementation
import { randomBytes, createHash } from 'crypto';
interface PkceChallenge {
codeVerifier: string;
codeChallenge: string;
}
function generatePkce(): PkceChallenge {
// RFC 7636: code_verifier is 43-128 URL-safe chars; use 32 random bytes = 43 base64url chars
const codeVerifier = randomBytes(32).toString('base64url');
// S256 method: BASE64URL(SHA256(ASCII(code_verifier)))
const codeChallenge = createHash('sha256')
.update(codeVerifier)
.digest('base64url');
return { codeVerifier, codeChallenge };
}
function buildAuthorizationUrl(
clientId: string,
redirectUri: string,
session: Map<string, string>
): string {
const state = randomBytes(16).toString('hex');
const { codeVerifier, codeChallenge } = generatePkce();
// Store BOTH state and codeVerifier server-side — never send codeVerifier to browser
session.set('oauth_state', state);
session.set('oauth_code_verifier', codeVerifier);
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
response_type: 'code',
scope: 'read:user repo',
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
return `https://github.com/login/oauth/authorize?${params}`;
}
async function exchangeCode(
code: string,
clientId: string,
clientSecret: string,
redirectUri: string,
session: Map<string, string>
): Promise<{ access_token: string }> {
const codeVerifier = session.get('oauth_code_verifier');
if (!codeVerifier) throw new Error('No PKCE verifier in session — possible replay attack');
// Delete verifier from session immediately — single use
session.delete('oauth_code_verifier');
const response = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier, // Authorization server verifies SHA256(verifier) == challenge
}),
});
const tokens = await response.json();
if (!tokens.access_token) throw new Error('Token exchange failed');
return tokens;
}
code unbound to the initiating session; the code can be intercepted via Referer header on the callback page, browser history sync, or a partial redirect URI match, and exchanged by an attacker without the client secret (public clients) or alongside it (confidential clients); fix by generating a 32-byte code_verifier with crypto.randomBytes, computing code_challenge = SHA256(verifier) in base64url, adding both code_challenge and code_challenge_method: 'S256' to the authorization URL, and including code_verifier in the token exchange. Detection: SkillAudit flags OAuth authorization URL construction where URLSearchParams does not include code_challenge and code_challenge_method.OAUTH3-002 — State parameter not validated before code exchange — OAuth CSRF
An MCP skill's OAuth callback handler receives the code and state query parameters, but exchanges the code for a token before verifying that the state matches the value stored in the user's session. This omission enables a CSRF attack: the attacker initiates their own OAuth authorization flow on the target service, captures the code in the redirect, and then tricks the victim's browser into loading the callback URL with the attacker's code and state. The victim's callback handler exchanges the attacker's code for a token, binding the attacker's third-party account to the victim's MCP skill session. The attacker can then log into the third-party service as themselves and observe the victim's actions in the skill, or the attacker has silently linked their own account to a victim's workspace.
The state parameter must be generated with a cryptographically random value, stored in the server-side session before the redirect, and compared with the callback's state in constant time before any code exchange is attempted. If the values do not match, the request must be rejected — the code must never be exchanged. The comparison must happen as the first operation in the callback handler.
// VULNERABLE — state parameter generated but not validated on callback
import express from 'express';
import { randomBytes } from 'crypto';
const router = express.Router();
router.get('/oauth/start', (req, res) => {
const state = randomBytes(16).toString('hex');
req.session.oauthState = state; // State stored — but never checked on callback
const params = new URLSearchParams({
client_id: process.env.GITHUB_CLIENT_ID!,
redirect_uri: 'https://app.skillaudit.dev/oauth/callback',
scope: 'repo',
state,
});
res.redirect(`https://github.com/login/oauth/authorize?${params}`);
});
router.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query;
// BUG: state is never validated against req.session.oauthState
// Attacker crafts URL: /oauth/callback?code=ATTACKERS_CODE&state=anything
// Victim's browser loads this URL — their session exchanges the attacker's code
if (!code) {
return res.status(400).send('Missing code');
}
// Code is exchanged immediately without checking state
const tokenResponse = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code,
}),
});
const { access_token } = await tokenResponse.json();
req.session.githubToken = access_token;
res.redirect('/dashboard');
});
// FIXED — validate state in constant time before any code exchange
import express from 'express';
import { randomBytes, timingSafeEqual } from 'crypto';
const router = express.Router();
router.get('/oauth/start', (req, res) => {
const state = randomBytes(16).toString('hex');
req.session.oauthState = state;
req.session.oauthStartedAt = Date.now(); // Expire the flow after 10 minutes
const params = new URLSearchParams({
client_id: process.env.GITHUB_CLIENT_ID!,
redirect_uri: 'https://app.skillaudit.dev/oauth/callback',
scope: 'repo',
state,
// Add PKCE as well (see OAUTH3-001)
});
res.redirect(`https://github.com/login/oauth/authorize?${params}`);
});
router.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query;
// 1. Reject if state or code are missing
if (typeof state !== 'string' || typeof code !== 'string') {
return res.status(400).send('Missing state or code');
}
// 2. Retrieve and immediately clear the stored state — single use
const storedState = req.session.oauthState as string | undefined;
const startedAt = req.session.oauthStartedAt as number | undefined;
delete req.session.oauthState;
delete req.session.oauthStartedAt;
// 3. Reject if no stored state (session expired or never started)
if (!storedState || !startedAt) {
return res.status(400).send('No OAuth flow in progress');
}
// 4. Reject if the OAuth flow started more than 10 minutes ago
if (Date.now() - startedAt > 10 * 60 * 1000) {
return res.status(400).send('OAuth flow expired');
}
// 5. Validate state using constant-time comparison to prevent timing attacks
const stateBuffer = Buffer.from(state, 'utf8');
const storedBuffer = Buffer.from(storedState, 'utf8');
if (
stateBuffer.length !== storedBuffer.length ||
!timingSafeEqual(stateBuffer, storedBuffer)
) {
return res.status(400).send('State mismatch — possible CSRF attack');
}
// 6. Only after state validation: exchange the code
const tokenResponse = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code,
}),
});
const { access_token } = await tokenResponse.json();
if (!access_token) return res.status(400).send('Token exchange failed');
// Store in session memory only — not localStorage (see OAUTH3-004)
req.session.githubToken = access_token;
res.redirect('/dashboard');
});
state parameter against the session-stored value is vulnerable to CSRF: an attacker initiates their own authorization, redirects the victim's browser to /oauth/callback?code=ATTACKERS_CODE&state=anything, and the victim's session acquires a token linked to the attacker's account; fix by validating state with timingSafeEqual against the session-stored value as the first operation in the callback handler, clearing the stored state immediately after reading it, and aborting the flow on any mismatch. Detection: SkillAudit flags OAuth callback route handlers that call a token exchange function before a timingSafeEqual or strict-equality check on req.query.state vs req.session.oauthState.OAUTH3-003 — PKCE code_verifier generated with Math.random() — 32-bit entropy
Even when a skill implements PKCE, the security of the proof key depends entirely on the entropy of the code_verifier. Math.random() in V8 uses an xorshift128+ PRNG seeded with 64 bits of state, but only about 32 bits are observable per call because the output is a 64-bit float with 52 mantissa bits and the seed is not refreshed. For PKCE purposes this is disqualifying: an attacker who intercepts the code (via Referer or other leakage) can try every possible code_verifier value derived from the 2^32 possible Math.random() seeds. At 100,000 token requests per second against the authorization server's token endpoint (rate-limiting permitting), the full space is exhausted in under 12 hours. crypto.randomBytes(32) provides 256 bits of entropy, reducing offline attack time to infeasible.
The fix is a one-line substitution: replace Math.random().toString(36).slice(2) (or any variant) with crypto.randomBytes(32).toString('base64url'). The base64url encoding produces exactly the 43-character URL-safe string that RFC 7636 requires as the minimum code_verifier length. No padding characters are introduced. The resulting verifier has 256 bits of entropy.
// VULNERABLE — code_verifier generated from Math.random() (32-bit effective entropy)
function buildAuthUrlWithWeakPkce(clientId: string, redirectUri: string): {
url: string;
codeVerifier: string;
} {
// Math.random() returns a float — 32 bits of effective entropy in V8
// An attacker who captures the auth code can try all 2^32 seeds offline
const weakVerifier =
Math.random().toString(36).slice(2) +
Math.random().toString(36).slice(2) +
Math.random().toString(36).slice(2); // Still only ~96 bits of Math.random() output
// but only 64 bits of PRNG state total
const challenge = createHash('sha256')
.update(weakVerifier)
.digest('base64url');
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
response_type: 'code',
scope: 'openid profile email',
code_challenge: challenge,
code_challenge_method: 'S256',
});
return {
url: `https://accounts.google.com/o/oauth2/v2/auth?${params}`,
codeVerifier: weakVerifier,
};
}
// Alternative weak pattern seen in real skills:
const weakVerifier2 = btoa(String(Math.random())); // base64 of a float — <7 bits entropy
const weakVerifier3 = Date.now().toString(36); // Timestamp — predictable from public info
// FIXED — code_verifier from crypto.randomBytes(32) = 256 bits of entropy
import { randomBytes, createHash } from 'crypto';
function buildAuthUrlWithStrongPkce(clientId: string, redirectUri: string): {
url: string;
codeVerifier: string;
} {
// RFC 7636 §4.1: code_verifier = 43-128 chars from [A-Z a-z 0-9 - . _ ~]
// randomBytes(32) = 256 bits of entropy → base64url = 43 chars, all URL-safe
const codeVerifier = randomBytes(32).toString('base64url');
// RFC 7636 §4.2: code_challenge = BASE64URL(SHA256(ASCII(code_verifier)))
const codeChallenge = createHash('sha256')
.update(codeVerifier, 'ascii')
.digest('base64url');
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
response_type: 'code',
scope: 'openid profile email',
code_challenge: codeChallenge,
code_challenge_method: 'S256',
// Also add state from crypto.randomBytes — see OAUTH3-002
state: randomBytes(16).toString('hex'),
});
// codeVerifier must be stored in server-side session, never in a cookie or URL
return {
url: `https://accounts.google.com/o/oauth2/v2/auth?${params}`,
codeVerifier, // Store this in req.session.oauthCodeVerifier — see OAUTH3-001
};
}
code_verifier generated with Math.random() provides at most 32 bits of effective entropy because V8's xorshift128+ PRNG has 64 bits of state observable from output; an attacker who captures the authorization code via Referer leakage can brute-force all 2^32 seeds offline and derive the verifier, allowing them to exchange the code at the token endpoint; fix by using crypto.randomBytes(32).toString('base64url') for 256 bits of entropy. Detection: SkillAudit flags PKCE code_verifier assignments that use Math.random(), Date.now(), or Math.floor() rather than crypto.randomBytes.OAUTH3-004 — Access token stored in localStorage — readable by any XSS
After the OAuth token exchange, an MCP skill's frontend companion stores the access token in localStorage for persistence across page reloads. localStorage is synchronously accessible to any JavaScript executing in the same origin — including JavaScript injected via XSS. A single reflected or stored XSS vulnerability anywhere on the same origin (a user-uploaded SVG, a Markdown preview page, an unsanitized error message) allows an attacker to exfiltrate the access token with localStorage.getItem('access_token'). Because localStorage persists indefinitely, a session-fixation XSS executed once can read tokens inserted in the future.
The correct storage strategy for OAuth tokens in a browser-side MCP skill companion differs by token type: the short-lived access token should be held in a module-scoped JavaScript variable (memory) so it is cleared on page navigation. The long-lived refresh token should be stored in an httpOnly SameSite=Strict Secure cookie, which is never accessible from JavaScript regardless of XSS. The refresh token cookie is sent automatically by the browser on requests to the token-refresh endpoint, while the access token is kept only in memory and re-obtained from the refresh endpoint on page load.
// VULNERABLE — access token (and refresh token) stored in localStorage
async function handleOAuthCallback(code: string): Promise<void> {
const response = await fetch('/api/oauth/exchange', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
const { access_token, refresh_token, expires_in } = await response.json();
// Both tokens stored in localStorage — readable by any XSS on this origin
localStorage.setItem('access_token', access_token);
localStorage.setItem('refresh_token', refresh_token); // Especially dangerous
localStorage.setItem('token_expires_at', String(Date.now() + expires_in * 1000));
}
// Usage — reads from localStorage everywhere
async function callGitHubApi(endpoint: string): Promise<unknown> {
const token = localStorage.getItem('access_token');
const response = await fetch(`https://api.github.com${endpoint}`, {
headers: { Authorization: `Bearer ${token}` },
});
return response.json();
}
// FIXED — access token in memory only; refresh token in httpOnly cookie (server-side)
// Server-side: set refresh token as httpOnly cookie
import express from 'express';
const authRouter = express.Router();
authRouter.post('/api/oauth/exchange', async (req, res) => {
const { code } = req.body;
// ... exchange code for tokens (with PKCE verifier from session) ...
const { access_token, refresh_token, expires_in } = await exchangeCode(code, req.session);
// Refresh token: httpOnly SameSite=Strict Secure cookie — never readable by JS
res.cookie('rt', refresh_token, {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
path: '/api/oauth/refresh', // Only sent to the refresh endpoint
});
// Return access token in response body — client stores in memory, not localStorage
res.json({ access_token, expires_in });
});
authRouter.post('/api/oauth/refresh', async (req, res) => {
const refreshToken = req.cookies.rt; // httpOnly cookie — not accessible from frontend JS
if (!refreshToken) return res.status(401).json({ error: 'No refresh token' });
const { access_token, expires_in } = await refreshAccessToken(refreshToken);
res.json({ access_token, expires_in });
});
// Client-side: store access token in module memory, never localStorage
let _accessToken: string | null = null;
let _tokenExpiresAt = 0;
async function getAccessToken(): Promise<string> {
// If we have a valid in-memory token, use it
if (_accessToken && Date.now() < _tokenExpiresAt - 30_000) {
return _accessToken;
}
// Otherwise, use the httpOnly refresh token cookie to get a new access token
// The cookie is sent automatically — the client never sees the refresh token value
const response = await fetch('/api/oauth/refresh', {
method: 'POST',
credentials: 'include', // Send the httpOnly cookie
});
if (!response.ok) throw new Error('Re-authentication required');
const { access_token, expires_in } = await response.json();
// Store access token in module-scoped memory — cleared on page navigation
_accessToken = access_token;
_tokenExpiresAt = Date.now() + expires_in * 1000;
return _accessToken;
}
localStorage are synchronously readable by any JavaScript executing on the same origin, including XSS payloads; a single XSS anywhere on the origin can exfiltrate both tokens with localStorage.getItem(); fix by holding the access token in a module-scoped memory variable (cleared on navigation) and storing the refresh token exclusively in an httpOnly SameSite=Strict Secure cookie scoped to the refresh endpoint. Detection: SkillAudit flags client-side code that calls localStorage.setItem with values from an OAuth token exchange response, specifically matching patterns like access_token, refresh_token, or id_token as the key.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| OAUTH3-001 | HIGH | Authorization code flow without code_challenge — code unbound to session, interceptable via Referer or redirect URI leak |
crypto.randomBytes(32).toString('base64url') as verifier; SHA256(verifier) as challenge; code_challenge_method: 'S256' |
| OAUTH3-002 | HIGH | State parameter not validated before code exchange — CSRF allows attacker's code to be exchanged in victim's session | timingSafeEqual comparison of callback state vs session-stored value as first operation; delete stored state after reading |
| OAUTH3-003 | HIGH | code_verifier from Math.random() — 32-bit effective entropy, brute-forceable against stolen auth code in <12 hours |
crypto.randomBytes(32).toString('base64url') — 256 bits of entropy |
| OAUTH3-004 | HIGH | Access token in localStorage — readable by any XSS on same origin, persists across sessions |
Access token in module memory; refresh token in httpOnly SameSite=Strict Secure cookie scoped to refresh endpoint |
Related patterns: SA-SKL-OAUTH1 covers foundational OAuth PKCE implementation patterns. SA-SKL-OAUTH2 covers OAuth token rotation and refresh token reuse. SA-SKL-REDIRECT1 covers open redirect vulnerabilities that can be chained with OAuth flows to intercept authorization codes.