← Blog

Claude skill DOM-based open redirect via location.hash and history.pushState in MCP skill SPAs — SA-SKL-REDIRECT4

DOM-based open redirects are harder to detect than server-side ones because the redirect logic lives in JavaScript rather than a 302 response — static code analysis misses them, server logs don't show the destination URL, and the attack surface expands with every new SPA routing pattern. SA-SKL-REDIRECT4 covers four DOM redirect patterns found in MCP skill frontend SPAs: hash fragment redirect after OAuth, history.pushState history poisoning, React Router next param bypass, and postMessage redirect without origin validation.

By SkillAudit  |  7 Nov 2026

REDIRECT4-001 — location.href = location.hash.slice(1) after OAuth callback

OAuth 2.0 authorization code flows often redirect the browser back to a callback URL like https://app.example.com/auth/callback?code=abc&state=xyz. Some SPAs preserve the user's pre-auth destination in the URL hash fragment so the hash survives the redirect: before redirecting to the OAuth provider, the app writes the return path into the hash (location.href = providerUrl + '#' + encodeURIComponent(currentPath)), and after the callback, it reads location.hash.slice(1) and sets window.location.href to that value to return the user to where they were. The vulnerability is that the hash value is never validated to be a same-origin path: an attacker who crafts the link https://app.example.com/auth/callback#https://evil.com/phishing and delivers it to a logged-out user causes the app to redirect the user to https://evil.com/phishing after completing the OAuth flow. Because the redirect happens after a successful OAuth login, the user has just seen a trusted branding screen and is primed to trust wherever they land next. The fix is to parse the hash value as a URL and confirm that the hostname matches window.location.hostname before navigating — relative paths that do not contain a protocol or authority are always safe.

# VULNERABLE — REDIRECT4-001: location.href set from location.hash without origin check
// auth/callback.jsx (React component, runs after OAuth redirect returns to app):
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

function AuthCallback() {
  const navigate = useNavigate();

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');
    const state = params.get('state');

    // Exchange code for token...
    exchangeCodeForToken(code, state).then(() => {
      // VULNERABLE: redirect destination taken from hash fragment without validation
      const returnPath = window.location.hash.slice(1) || '/dashboard';
      // If hash is '#https://evil.com/phishing', this navigates to evil.com
      window.location.href = decodeURIComponent(returnPath);
    });
  }, []);

  return <div>Signing in...</div>;
}

# Attack URL crafted by attacker:
# https://app.skillaudit.dev/auth/callback#https://evil.com/steal-credentials
# Delivered to victim as a phishing link or embedded in a forum post
# After OAuth completes, victim is sent to evil.com — appears to be post-login
# FIXED — REDIRECT4-001: validate that hash destination is same-origin before navigating
// auth/callback.jsx (fixed):
import { useEffect } from 'react';

function isSameOriginPath(raw) {
  if (!raw) return false;
  try {
    const decoded = decodeURIComponent(raw);
    // Relative paths starting with '/' and containing no '//' are always safe
    if (decoded.startsWith('/') && !decoded.startsWith('//')) return true;
    // Absolute URL: parse and compare hostname
    const url = new URL(decoded, window.location.origin);
    return url.hostname === window.location.hostname;
  } catch {
    return false; // malformed URL — reject
  }
}

function AuthCallback() {
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');
    const state = params.get('state');

    exchangeCodeForToken(code, state).then(() => {
      const rawHash = window.location.hash.slice(1);

      // Validate before navigating — reject anything that leaves this origin
      const safePath = isSameOriginPath(rawHash) ? decodeURIComponent(rawHash) : '/dashboard';
      window.location.replace(safePath); // replace() prevents back-navigation to callback
    });
  }, []);

  return <div>Signing in...</div>;
}

// Alternatively, store the return path in sessionStorage before OAuth redirect
// (never in the hash/query — these are attacker-controllable) and read it back:
// Before redirect: sessionStorage.setItem('post_auth_return', location.pathname);
// After callback:  const ret = sessionStorage.getItem('post_auth_return') || '/dashboard';
//                  sessionStorage.removeItem('post_auth_return');
//                  navigate(ret); // React Router navigate — always same-app
HIGH
SA-SKL-REDIRECT4-001 — OAuth callback handlers that read the post-login return destination from window.location.hash and assign it to window.location.href without validating the hostname allow an attacker to craft a callback URL with a malicious hash fragment that redirects authenticated users to an arbitrary external site immediately after a successful login; fix by parsing the hash value as a URL and confirming url.hostname === window.location.hostname before navigating, or storing the return path in sessionStorage before the OAuth redirect so it is never attacker-controllable. Detection: SkillAudit flags JavaScript patterns of location.href = .*location.hash or window.location = .*hash without a preceding same-origin check in OAuth callback components.

REDIRECT4-002 — history.pushState from query param poisons browser history

history.pushState(state, title, url) adds a new entry to the browser's session history without triggering a navigation — the page content does not change, but the address bar updates and the back button adds an entry. This is commonly used in SPAs to update the URL to reflect the current view without a full page load. When an MCP skill SPA calls history.pushState(null, '', returnUrl) where returnUrl comes from a query parameter (?next=/settings), and no hostname validation is applied, an attacker who links to https://app.example.com/login?next=https://evil.com/page causes the app's address bar to display https://evil.com/page immediately after the user interacts with the login page — before any navigation occurs. This is a URL spoofing attack: the browser's trust indicators (padlock, domain in address bar) now show the attacker's URL in a tab that is still running the legitimate app's JavaScript. If a phishing form is then injected via DOM manipulation, the user sees the legitimate domain in the address bar while interacting with attacker-controlled content. The fix is to validate that returnUrl is a path-only string (starts with /, contains no ://) before passing it to pushState.

# VULNERABLE — REDIRECT4-002: history.pushState with unvalidated returnUrl query param
// login/page.jsx:
import { useEffect } from 'react';

function LoginPage() {
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const next = params.get('next');

    if (next) {
      // VULNERABLE: pushState updates address bar to attacker-controlled value
      // Does NOT navigate the page — but address bar now shows evil.com URL
      history.pushState(null, '', next);
    }
  }, []);

  return <LoginForm />;
}

# Attack URL:
# https://app.skillaudit.dev/login?next=https://evil.com/fake-login
# When user visits this URL:
# 1. LoginPage renders normally (skillaudit.dev code, skillaudit.dev padlock)
# 2. useEffect calls pushState — address bar NOW shows https://evil.com/fake-login
# 3. Address bar shows evil.com domain with skillaudit.dev's SSL padlock (URL bar confusion)
# 4. Attacker can follow up with DOM injection via other XSS to show a "phishing" form
# FIXED — REDIRECT4-002: validate returnUrl is a same-origin path-only string before pushState
// login/page.jsx (fixed):
import { useEffect } from 'react';

function isSafeReturnPath(url) {
  if (!url || typeof url !== 'string') return false;
  // Must start with '/' and not start with '//' (which is protocol-relative)
  if (!url.startsWith('/') || url.startsWith('//')) return false;
  // Must not contain '://' — rejects absolute URLs with protocol
  if (url.includes('://')) return false;
  // Must not contain control characters or CR/LF
  if (/[\x00-\x1f]/.test(url)) return false;
  return true;
}

function LoginPage() {
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const next = params.get('next');

    if (next && isSafeReturnPath(next)) {
      // Safe: next is a path-only string like '/settings' or '/dashboard'
      history.pushState(null, '', next);
    }
    // If next fails validation, leave the URL as-is — no pushState at all
  }, []);

  return <LoginForm />;
}

// Best practice: use React Router's navigate() instead of raw history.pushState
// navigate() is SPA-internal and cannot navigate outside the app's route tree:
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
if (next && isSafeReturnPath(next)) navigate(next, { replace: true });
MEDIUM
SA-SKL-REDIRECT4-002 — history.pushState(null, '', returnUrl) called with an unvalidated query parameter value updates the browser address bar to display an attacker-controlled URL while the legitimate application continues running, enabling URL-spoofing attacks where the browser's padlock icon and domain display remain trustworthy while the visible URL is changed to a phishing domain; fix by validating that the returnUrl starts with /, does not start with //, and contains no :// before passing to pushState. Detection: SkillAudit flags history.pushState calls where the third argument is derived from a URL query parameter or hash fragment without a preceding same-origin path validation step.

REDIRECT4-003 — React Router <Navigate to={searchParams.get('next')} /> without hostname check

React Router's <Navigate> component and navigate() hook are designed for in-app routing: they push to the React Router history stack and render the matching route component. However, when the to prop is an absolute URL string with a protocol and hostname, React Router falls through to a full browser navigation — it effectively calls window.location.href = to. This means <Navigate to="https://evil.com" /> does navigate the browser to evil.com. MCP skill SPAs that read the redirect destination from search parameters and pass it directly to <Navigate> are therefore vulnerable to open redirect: a relative path like /dashboard stays in-app as intended, but an absolute URL like https://evil.com causes a full browser redirect. The pattern is subtle because developers who know React Router assume <Navigate> is SPA-internal; the absolute-URL edge case is easy to miss in code review. The fix is to validate that the next parameter either starts with / (relative path) or is a known safe route name before passing it to <Navigate>.

# VULNERABLE — REDIRECT4-003: React Router Navigate with unsanitized searchParams.get('next')
// components/ProtectedRoute.jsx:
import { Navigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';

function ProtectedRoute({ children }) {
  const { isAuthenticated } = useAuth();
  const [searchParams] = useSearchParams();

  if (!isAuthenticated) {
    const next = searchParams.get('next') || '/dashboard';
    // VULNERABLE: if next is 'https://evil.com', React Router navigates the browser there
    // Relative paths ('/settings') work as expected
    // Absolute paths ('https://evil.com') trigger full browser navigation to external URL
    return <Navigate to={next} replace />;
  }

  return children;
}

# Attack URL:
# https://app.skillaudit.dev/settings?next=https://evil.com/phishing
# User visits this URL while not logged in
# ProtectedRoute renders <Navigate to="https://evil.com/phishing" />
# Browser navigates to evil.com — user sees phishing page
# Because the original URL was skillaudit.dev, user trusts the destination
# FIXED — REDIRECT4-003: validate next param is a path-only string before Navigate
// components/ProtectedRoute.jsx (fixed):
import { Navigate, useSearchParams, useLocation } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';

function sanitizeRedirectPath(raw) {
  if (!raw) return '/dashboard';
  // Must be a relative path (starts with /, no protocol)
  if (!raw.startsWith('/') || raw.startsWith('//') || raw.includes('://')) {
    return '/dashboard'; // reject — fall back to safe default
  }
  // Extra: reject paths with null bytes or control characters
  if (/[\x00-\x1f]/.test(raw)) return '/dashboard';
  return raw;
}

function ProtectedRoute({ children }) {
  const { isAuthenticated } = useAuth();
  const [searchParams] = useSearchParams();
  const location = useLocation();

  if (!isAuthenticated) {
    const rawNext = searchParams.get('next');
    const safePath = sanitizeRedirectPath(rawNext);
    return <Navigate to={safePath} replace />;
  }

  return children;
}

// Also safe: encode the current path into state rather than a query param
// In the Router's loader or redirect logic:
// navigate('/login', { state: { from: location.pathname } })
// After login, read location.state?.from which is never attacker-controllable
// (state is React Router internal, not from the URL)
HIGH
SA-SKL-REDIRECT4-003 — React Router <Navigate to={searchParams.get('next')} /> without a hostname check allows open redirect because React Router performs a full browser navigation when the to prop is an absolute URL, sending the user to an attacker-controlled domain while the original URL appeared trusted; fix by validating that next starts with / and contains no :// before passing to <Navigate>, or by encoding the return path in location.state which is not attacker-controllable from the URL. Detection: SkillAudit flags <Navigate to={.*searchParams.*} or navigate(searchParams patterns in React components without a preceding path-only validation check.

REDIRECT4-004 — postMessage redirect without origin check navigates to any URL

window.addEventListener('message', handler) registers a handler for cross-origin postMessage events. The handler fires for any message sent to the window, from any origin, unless the handler explicitly checks event.origin. When an MCP skill SPA listens for messages to perform actions like closing a modal, refreshing a token, or navigating after an embedded OAuth flow, and one of those actions is to call window.location.href = event.data.redirectUrl, any page that can open the app in an iframe or a popup can send a message with a malicious redirectUrl and hijack navigation. The attack does not require the two pages to be on the same origin — postMessage is specifically designed for cross-origin communication. Any attacker who can get a victim to visit their page and load the target app in an invisible iframe can then send a redirect message. The fix is to check event.origin against an exact allowlist of trusted origins before acting on any message, and specifically to validate that any URL in message data is same-origin before assigning to window.location.

# VULNERABLE — REDIRECT4-004: window.location.href set from postMessage without origin check
// App's main window listens for messages from an embedded OAuth popup:
window.addEventListener('message', (event) => {
  // VULNERABLE: event.origin not checked — ANY page can send this message
  if (event.data?.type === 'oauth_complete') {
    const { token, redirectUrl } = event.data;
    localStorage.setItem('auth_token', token);

    // VULNERABLE: redirectUrl from postMessage — attacker page sends evil URL
    if (redirectUrl) {
      window.location.href = redirectUrl; // navigates to attacker's URL
    } else {
      window.location.href = '/dashboard';
    }
  }
});

# Attack (attacker page at https://evil.com/attack.html):
# <!-- Open victim app in an invisible iframe -->
# <iframe id="target" src="https://app.skillaudit.dev/settings" style="display:none"></iframe>
# <script>
#   const frame = document.getElementById('target');
#   frame.onload = () => {
#     // Send message to frame — no same-origin restriction on postMessage delivery
#     frame.contentWindow.postMessage({
#       type: 'oauth_complete',
#       token: 'fake',
#       redirectUrl: 'https://evil.com/phishing'
#     }, '*');  // '*' means "deliver to any origin"
#   };
# </script>
# When victim visits evil.com/attack.html, the frame sends the message
# App navigates to evil.com/phishing without user interaction
# FIXED — REDIRECT4-004: check event.origin before acting on any postMessage redirect
// Define the exact set of trusted message senders
const TRUSTED_ORIGINS = new Set([
  'https://app.skillaudit.dev',
  'https://auth.skillaudit.dev',  // OAuth popup origin
]);

window.addEventListener('message', (event) => {
  // 1. Check origin first — reject any message from an untrusted source
  if (!TRUSTED_ORIGINS.has(event.origin)) {
    return; // silently ignore messages from unknown origins
  }

  // 2. Validate message structure
  if (typeof event.data !== 'object' || event.data === null) return;
  if (event.data.type !== 'oauth_complete') return;

  const { token, redirectUrl } = event.data;

  if (token) {
    localStorage.setItem('auth_token', token);
  }

  // 3. Validate redirectUrl is same-origin relative path only
  if (redirectUrl) {
    try {
      const url = new URL(redirectUrl, window.location.origin);
      if (url.hostname === window.location.hostname) {
        window.location.replace(url.pathname + url.search + url.hash);
      } else {
        window.location.replace('/dashboard'); // reject cross-origin redirect
      }
    } catch {
      window.location.replace('/dashboard');
    }
  } else {
    window.location.replace('/dashboard');
  }
});

// Also restrict what origins your OAuth popup can postMessage TO:
// In the OAuth popup, use the specific parent origin rather than '*':
// window.opener.postMessage({ type: 'oauth_complete', token }, 'https://app.skillaudit.dev');
// Never use '*' as the targetOrigin when posting sensitive data
HIGH
SA-SKL-REDIRECT4-004 — window.addEventListener('message', handler) that sets window.location.href from event.data.redirectUrl without first checking event.origin allows any page that can embed or open the app to send a message redirecting the user to an arbitrary external URL; fix by validating event.origin against an explicit allowlist of trusted origins before acting on any message, and additionally validating that any URL in message data is a same-origin path before navigation. Detection: SkillAudit flags window.location assignments inside message event listeners where event.origin is not checked before the assignment is reached.

Detection summary

ID Severity Pattern Fix
REDIRECT4-001 HIGH location.href = location.hash.slice(1) after OAuth callback — attacker crafts #https://evil.com fragment Parse hash as URL; confirm url.hostname === window.location.hostname; or store return path in sessionStorage
REDIRECT4-002 MEDIUM history.pushState(null, '', returnUrl) from query param — address bar shows attacker URL while app still runs Require / prefix, no ://, no // before pushState; use React Router navigate()
REDIRECT4-003 HIGH React Router <Navigate to={searchParams.get('next')} /> — absolute URLs trigger real browser navigation Validate path-only (/ prefix, no ://); encode return path in location.state instead
REDIRECT4-004 HIGH postMessage redirect without event.origin check — any embedding page triggers navigation Check event.origin against explicit trusted-origin allowlist before acting; validate URL is same-origin path

Related patterns: SA-SKL-REDIRECT3 covers server-side open redirect via res.redirect(req.query.next), Location header injection, and unvalidated redirect after form POST — the server-side counterparts to these DOM-based patterns. MCP server OAuth callback security covers CSRF on the OAuth callback, state parameter validation, PKCE enforcement, and token leakage via Referer header in the full OAuth integration pattern for MCP skills.