Claude skill session fixation and concurrent session security — SA-SKL-SESSION2
Session management vulnerabilities in MCP skills are exploitable without any cryptographic attack — the common patterns depend on the application trusting a session ID that the attacker already knows. SA-SKL-SESSION2 covers four patterns: session fixation via failure to regenerate the session ID on login, concurrent sessions remaining valid after one-device logout, session tokens leaked via URL Referer header to third-party scripts, and JWT access tokens issued without an expiry claim.
SESSION2-001 — Session fixation: session ID not regenerated on login
Session fixation is a pre-authentication attack. The attacker first visits the skill's login page and obtains a valid (unauthenticated) session ID — stored in the connect.sid cookie. The attacker then tricks the target user into using that same session ID, for example by embedding a login link containing the session cookie value in a phishing email, or by injecting a Set-Cookie header on a shared network. When the target user logs in, if the application does not regenerate the session ID on successful authentication, the attacker's known session ID is now associated with the authenticated user. The attacker sends requests using the same session cookie they obtained in step one and is now authenticated as the victim.
The fix is mechanically simple: call req.session.regenerate() after successful authentication, before writing the user identity into the new session. The express-session library provides this method — it creates a new session ID, copies the existing session data, and invalidates the old ID.
// VULNERABLE — SESSION2-001: session fixation — session ID not regenerated on login
app.post('/auth/login', async (req, res) => {
const { email, password } = req.body;
const user = await db.users.findByEmail(email);
if (!user || !await bcrypt.compare(password, user.passwordHash)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// VULNERABLE: assigns user to the existing (pre-login) session
// The session ID is the SAME as before login — attacker who knew the pre-login
// session ID now has an authenticated session
req.session.userId = user.id;
req.session.role = user.role;
res.json({ ok: true });
});
// FIXED — SESSION2-001: regenerate session ID on login
app.post('/auth/login', async (req, res) => {
const { email, password } = req.body;
const user = await db.users.findByEmail(email);
if (!user || !await bcrypt.compare(password, user.passwordHash)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// FIXED: regenerate the session — creates a new session ID, invalidates the old one
// Any pre-authentication session ID the attacker knew is now worthless
req.session.regenerate((err) => {
if (err) return res.status(500).json({ error: 'Session error' });
// Set user data in the NEW session (after regeneration)
req.session.userId = user.id;
req.session.role = user.role;
req.session.loginAt = new Date().toISOString();
req.session.save((err) => {
if (err) return res.status(500).json({ error: 'Session save error' });
res.json({ ok: true });
});
});
});
req.session.regenerate() are vulnerable to session fixation — an attacker who obtains a pre-authentication session ID inherits the authenticated session after the victim logs in; fix by calling req.session.regenerate() before assigning user identity and saving the session. Detection: SkillAudit flags route handlers matching /login or /auth/ patterns that assign to req.session without a preceding req.session.regenerate() call.SESSION2-002 — Concurrent sessions not invalidated on logout from one device
When a user logs in from two devices, most session stores create two independent session records. When the user logs out from device B, the skill destroys device B's session. Device A's session — including one that may have been compromised in a prior security incident — remains active indefinitely. An attacker who stole a valid session token (via XSS, network sniffing on HTTP, or session fixation) retains access even after the user performs a "security logout" from another device. The two fix approaches are: (1) single-session mode — revoke all previous sessions when a new login occurs; (2) session listing with per-device revocation — store a list of active sessions per user and display it in the account settings with a "revoke" button.
// VULNERABLE — SESSION2-002: logout only destroys the current device's session
// Other active sessions for the same user remain valid
app.post('/auth/logout', requireAuth, (req, res) => {
req.session.destroy((err) => {
if (err) return res.status(500).json({ error: 'Logout failed' });
res.clearCookie('connect.sid');
res.json({ ok: true });
// User is logged out on THIS device — but session on other devices (or stolen sessions)
// are still valid in the session store. Attacker retains access.
});
});
// FIXED (Option A) — SESSION2-002: single-session mode
// Store the current session ID in the user record; on new login, revoke the previous session
// Also revoke all sessions on explicit "logout all devices" action
// In login handler (after req.session.regenerate()):
await db.users.update(user.id, { currentSessionId: req.session.id });
// In auth middleware:
app.use(async (req, res, next) => {
if (req.session?.userId) {
const user = await db.users.findById(req.session.userId);
if (user?.currentSessionId !== req.session.id) {
// This session was superseded by a newer login — invalidate it
req.session.destroy(() => {});
return res.status(401).json({ error: 'Session invalidated — please log in again' });
}
}
next();
});
// FIXED (Option B) — SESSION2-002: session listing with per-device revocation
// Store session IDs in a user-keyed set in the session store
// On "logout all devices": delete all session records for this user ID
app.post('/auth/logout-all', requireAuth, async (req, res) => {
const sessionIds = await db.userSessions.findByUserId(req.user.id);
for (const sessionId of sessionIds) {
await sessionStore.destroy(sessionId); // Revoke each session in the store
}
await db.userSessions.deleteByUserId(req.user.id);
res.json({ ok: true, sessionsRevoked: sessionIds.length });
});
req.session.destroy() in the logout handler but no mechanism to revoke other concurrent sessions for the same user.SESSION2-003 — Session ID in URL leaks via Referer header to analytics scripts
Some MCP skills pass session tokens or one-time login tokens in URL query parameters for email-based authentication flows. For example, a magic link in an email contains https://app.skillaudit.dev/auth/verify?token=abc123 and the user is redirected after verification to https://app.skillaudit.dev/dashboard?session=xyz789. If the dashboard page loads any third-party scripts (Google Analytics, Intercom, Mixpanel, Hotjar), the browser sends the full URL including the session token in the Referer header on each subresource request. Third-party analytics servers receive and potentially log the session token. The fix is to never include session tokens or one-time codes in URLs after the exchange step — exchange the URL token for a httpOnly cookie immediately on first use, then redirect to a clean URL.
// VULNERABLE — SESSION2-003: session token persists in URL after authentication
app.get('/auth/verify', async (req, res) => {
const { token } = req.query;
const user = await db.verifyMagicToken(token);
if (!user) return res.status(401).send('Invalid or expired token');
// VULNERABLE: the session token is set in a cookie, BUT the page redirects to a URL
// that still contains a session identifier as a query parameter
req.session.regenerate((err) => {
req.session.userId = user.id;
req.session.save(() => {
// Session cookie is set, but we also pass a "welcome" parameter that includes
// something identifying — or in worse patterns, the token itself is re-used in the redirect
res.redirect('/dashboard?verified=1&session=' + req.session.id); // NEVER do this
// Any third-party script on /dashboard now sees: Referer: .../dashboard?session=XYZ
});
});
});
// FIXED — SESSION2-003: exchange token immediately, redirect to clean URL with no token in query
app.get('/auth/verify', async (req, res) => {
const { token } = req.query;
// Validate and immediately consume the one-time magic token
const user = await db.verifyMagicToken(token);
if (!user) return res.status(401).send('Invalid or expired token');
// Invalidate the token after first use — one-time use enforced
await db.consumeMagicToken(token);
// Regenerate session and store user identity
req.session.regenerate((err) => {
if (err) return res.status(500).send('Session error');
req.session.userId = user.id;
req.session.loginAt = new Date().toISOString();
req.session.save((err) => {
if (err) return res.status(500).send('Session save error');
// Redirect to a CLEAN URL with NO session identifier in the query string
// The session is in the httpOnly cookie — not visible to third-party scripts via Referer
res.redirect('/dashboard');
});
});
});
// In Caddy/nginx: also set Referrer-Policy header to limit Referer leakage to same-origin
// Referrer-Policy: strict-origin-when-cross-origin
// This ensures full URLs are only sent as Referer to same-origin resources
Referer header to any third-party script loaded on subsequent pages; fix by exchanging URL tokens for httpOnly cookies immediately on first use and redirecting to a clean URL with no token in the query string, plus setting Referrer-Policy: strict-origin-when-cross-origin. Detection: SkillAudit flags redirect responses in auth handlers that include session-related values in the redirect URL query string.SESSION2-004 — JWT access token without exp claim is valid forever
JSON Web Tokens issued without an exp (expiry) claim remain valid indefinitely from the server's perspective. If a JWT is stolen — via XSS from a compromised dependency, from localStorage on an infected device, or from a server log that captures Authorization headers — the attacker retains access as long as the signing key is not rotated. JWT libraries do not enforce expiry by default unless you explicitly set the exp claim and configure the verification step to reject expired tokens. The standard pattern is to issue short-lived access tokens (15 minutes) and refresh tokens with rotation (7-day sliding window), where each refresh invalidates the previous refresh token.
// VULNERABLE — SESSION2-004: JWT issued without exp claim
import jwt from 'jsonwebtoken';
app.post('/auth/login', async (req, res) => {
const user = await authenticate(req.body);
if (!user) return res.status(401).json({ error: 'Invalid credentials' });
// VULNERABLE: no expiresIn option — JWT has no exp claim — valid forever
const token = jwt.sign(
{ sub: user.id, role: user.role },
process.env.JWT_SECRET
// Missing: expiresIn option
);
// Also stored in localStorage — reachable from XSS
res.json({ accessToken: token });
});
// FIXED — SESSION2-004: short-lived access tokens + refresh token rotation
import jwt from 'jsonwebtoken';
import { randomBytes } from 'crypto';
const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET;
const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET;
function issueAccessToken(userId, role) {
return jwt.sign(
{ sub: userId, role },
ACCESS_TOKEN_SECRET,
{ expiresIn: '15m' } // Short-lived — 15-minute access window
);
}
async function issueRefreshToken(userId) {
const token = randomBytes(40).toString('hex'); // Opaque random token
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days
await db.refreshTokens.create({ token, userId, expiresAt, used: false });
return token;
}
app.post('/auth/login', async (req, res) => {
const user = await authenticate(req.body);
if (!user) return res.status(401).json({ error: 'Invalid credentials' });
const accessToken = issueAccessToken(user.id, user.role);
const refreshToken = await issueRefreshToken(user.id);
// Access token in memory (not localStorage) — refresh token in httpOnly cookie
res.cookie('refresh_token', refreshToken, {
httpOnly: true, secure: true, sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
path: '/auth/refresh', // Restrict refresh token cookie to only the refresh endpoint
});
res.json({ accessToken }); // Client stores in memory, not localStorage
});
app.post('/auth/refresh', async (req, res) => {
const { refresh_token: token } = req.cookies;
if (!token) return res.status(401).json({ error: 'No refresh token' });
const record = await db.refreshTokens.findValidToken(token);
if (!record || record.used || new Date() > record.expiresAt) {
// Revoke all tokens for this user if reuse is detected (token theft indicator)
if (record?.used) await db.refreshTokens.revokeAllForUser(record.userId);
return res.status(401).json({ error: 'Invalid or expired refresh token' });
}
// Rotation: mark old token as used, issue a new one
await db.refreshTokens.markUsed(token);
const user = await db.users.findById(record.userId);
const newAccessToken = issueAccessToken(user.id, user.role);
const newRefreshToken = await issueRefreshToken(user.id);
res.cookie('refresh_token', newRefreshToken, {
httpOnly: true, secure: true, sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000,
path: '/auth/refresh',
});
res.json({ accessToken: newAccessToken });
});
exp claim are valid indefinitely — a stolen token grants permanent access unless the signing key is rotated; fix by issuing short-lived access tokens (expiresIn: '15m') paired with opaque refresh tokens stored in httpOnly cookies using rotation (each use issues a new token and invalidates the previous one). Detection: SkillAudit flags jwt.sign() calls that do not include an expiresIn option in the sign options object.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| SESSION2-001 | HIGH | Login assigns user to existing session without req.session.regenerate() — session fixation |
Call req.session.regenerate() before assigning user identity |
| SESSION2-002 | MEDIUM | Logout only destroys current session; concurrent sessions from other devices remain valid | Single-session mode (store current session ID per user) or session listing with revocation |
| SESSION2-003 | MEDIUM | Session token in URL query param — leaked via Referer header to third-party analytics |
Exchange token for httpOnly cookie immediately; redirect to clean URL; set Referrer-Policy |
| SESSION2-004 | HIGH | JWT issued without exp claim — stolen token valid forever |
expiresIn: '15m' for access tokens + opaque refresh token rotation in httpOnly cookie |
Related patterns: SA-SKL-CSRF2 covers double-submit cookie CSRF bypass patterns. SA-SKL-CORS6 covers credentialed cross-origin requests that interact with session cookies. SA-SKL-CORS7 covers SameSite=Lax cookie forwarding on WebSocket upgrades, which also applies to session cookies in WebSocket-based skill channels.