← Blog

Claude skill magic link and passwordless email token security — SA-SKL-MAGICLINK

Magic links shift the authentication secret from a password in the user's memory to a token in the user's email inbox. This trade-off is only secure if the token is single-use (deleted immediately after the first successful authentication), short-lived (expires within 15 minutes to bound the window of inbox compromise), high-entropy (at least 128 bits from a cryptographically secure random source), and followed immediately by session regeneration (to prevent session fixation). MCP skills that miss any of these properties expose their users to account takeover via email forwarding interception, historical inbox breach, brute force against the token verification endpoint, or session fixation. SA-SKL-MAGICLINK-001 through MAGICLINK-004 cover each gap with the vulnerable pattern and the correct fix.

By SkillAudit  |  5 Nov 2026

The magic link threat model

Email is not a secure channel. Email is transmitted via SMTP with optional TLS (not guaranteed end-to-end), stored on servers operated by third parties, forwarded via rules the user may have set years ago, and accessible to anyone with the inbox credentials. A magic link token stored in an email is effectively a password written in an email — except it is typically valid for longer than a session password and grants immediate full account access on a single click. The minimum viable security properties are: (1) single-use, so forwarding rules or shared inbox access cannot replay the link; (2) short-lived (15 minutes), so a delayed inbox breach does not lead to account takeover; (3) high-entropy (128+ bits), so the verification endpoint cannot be brute-forced even without lockout; and (4) session regeneration, so a session fixation attack via pre-set cookies cannot hijack the authenticated session.

SA-SKL-MAGICLINK in scope: MAGICLINK-001 (token reusable after first use — not deleted from DB), MAGICLINK-002 (token without expiry timestamp), MAGICLINK-003 (token generated with insufficient entropy — 8 hex chars = 32 bits), MAGICLINK-004 (session not regenerated after magic link auth — session fixation). All four are detected by SkillAudit's static analysis of authentication route handlers and token generation/verification logic.

MAGICLINK-001 — Token not invalidated after first use

The most common magic link vulnerability is failing to delete the token from the database immediately after the first successful authentication. If the token persists after use, it becomes a standing authentication credential valid for anyone who can observe the email: email forwarding rules, shared inboxes, email provider staff with inbox access, or any attacker who breaches the email provider. Because the token is a full account access credential, every additional day it remains valid is an additional day of exposure. The fix is a single DB delete call in the same transaction as the session creation — if the delete fails, the session creation must also fail (not committed).

// VULNERABLE: token not deleted after successful authentication
app.get('/auth/magic', async (req, res) => {
  const { token } = req.query;
  const record = await db.magicLinks.findOne({ token });

  if (!record) {
    return res.status(401).send('Invalid or expired link.');
  }

  // VULNERABLE: token remains in DB — same link works again after this request
  req.session.userId = record.userId;
  res.redirect('/dashboard');
});
// FIXED: token deleted in same transaction as session creation
app.get('/auth/magic', async (req, res) => {
  const { token } = req.query;
  if (!token || typeof token !== 'string') {
    return res.status(400).send('Missing token.');
  }

  const record = await db.magicLinks.findOne({ token });
  if (!record) {
    return res.status(401).send('Invalid or expired link.');
  }

  // Check expiry (see MAGICLINK-002)
  if (record.expiresAt < Date.now()) {
    await db.magicLinks.delete({ token }); // Clean up expired token
    return res.status(401).send('This link has expired. Request a new one.');
  }

  // FIXED: delete token BEFORE creating session — single-use guarantee
  // If delete fails (throws), session is never created
  await db.magicLinks.delete({ token });

  // Regenerate session to prevent fixation (see MAGICLINK-004)
  req.session.regenerate((err) => {
    if (err) return res.status(500).send('Session error.');
    req.session.userId = record.userId;
    res.redirect('/dashboard');
  });
});
CRITICAL
SA-SKL-MAGICLINK-001 — MCP skill magic link verification handler does not delete the token from the database after the first successful authentication; the same link can authenticate the user on any subsequent request, making it a standing account access credential valid until manually expired; anyone with historical access to the user's email inbox (forwarding rules, shared inbox, prior email breach) can replay the link at any future time. Fix: call db.magicLinks.delete({ token }) as the first DB operation in the success path — before req.session.userId is set; use a DB transaction so that delete and session creation are atomic. Detection: SkillAudit flags magic link verification handlers that set req.session.userId without a preceding DELETE or equivalent invalidation of the token record.

MAGICLINK-002 — Token without expiry window

A magic link without an expiry timestamp is an authentication credential with an indefinite validity window. If the user's email inbox is compromised 6 months after the magic link was sent — perhaps via a data breach at their email provider, or via a leaked credential for the inbox — an attacker who finds the unclicked link in archived email can still use it to authenticate. Magic links should have a 15-minute expiry: long enough for the user to receive and open the email, short enough to bound the breach window. The expiry timestamp must be stored in the database (not encoded in the token itself, where it could be forged) and checked on every use.

// VULNERABLE: magic link token with no expiry stored or checked
async function sendMagicLink(email) {
  const token = crypto.randomBytes(32).toString('hex');

  // VULNERABLE: no expiresAt stored
  await db.magicLinks.create({ token, userId: user.id });

  await email.send({
    to: email,
    subject: 'Your SkillAudit sign-in link',
    html: `Sign in`,
  });
}

app.get('/auth/magic', async (req, res) => {
  const record = await db.magicLinks.findOne({ token: req.query.token });
  if (!record) return res.status(401).send('Invalid link.');

  // VULNERABLE: no expiry check — link valid indefinitely
  req.session.userId = record.userId;
  res.redirect('/dashboard');
});
// FIXED: 15-minute expiry stored in DB and checked on use
const MAGIC_LINK_TTL_MS = 15 * 60 * 1000; // 15 minutes

async function sendMagicLink(user) {
  const token = crypto.randomBytes(32).toString('hex');
  const expiresAt = Date.now() + MAGIC_LINK_TTL_MS;

  // Invalidate any existing unused tokens for this user (one active link at a time)
  await db.magicLinks.deleteMany({ userId: user.id });

  // FIXED: store expiry timestamp
  await db.magicLinks.create({ token, userId: user.id, expiresAt });

  await email.send({
    to: user.email,
    subject: 'Your SkillAudit sign-in link (expires in 15 minutes)',
    html: `Sign in`,
  });
}

app.get('/auth/magic', async (req, res) => {
  const record = await db.magicLinks.findOne({ token: req.query.token });
  if (!record) return res.status(401).send('Invalid or expired link.');

  // FIXED: check expiry
  if (record.expiresAt < Date.now()) {
    await db.magicLinks.delete({ token: req.query.token });
    return res.status(401).send('This link has expired. Request a new one.');
  }

  await db.magicLinks.delete({ token: req.query.token }); // Single-use
  req.session.regenerate((err) => {
    if (err) return res.status(500).send('Session error.');
    req.session.userId = record.userId;
    res.redirect('/dashboard');
  });
});
HIGH
SA-SKL-MAGICLINK-002 — MCP skill magic link token is stored without an expiresAt timestamp and the verification handler does not check expiry; a link emailed to the user remains valid indefinitely, extending the account takeover window to the entire lifetime of the archived email; an attacker who obtains access to old email (email provider breach, leaked inbox credentials, forwarded-email archive) can replay any previously sent magic link. Fix: store expiresAt = Date.now() + 900000 (15 minutes) in the token record at creation time; check record.expiresAt < Date.now() in the verification handler before any authentication action; delete expired tokens on check. Detection: SkillAudit flags db.magicLinks.create() calls that do not include an expiresAt field, and verification handlers that do not read record.expiresAt.

MAGICLINK-003 — Token too short to resist brute force

Magic link tokens must be generated from a cryptographically secure random source with sufficient entropy to make brute force infeasible against the token verification endpoint. An 8-character hex token (32 bits of entropy, ~4.3 billion combinations) is brute-forceable: at 100 requests per second (a modest rate against an unprotected endpoint), the full space is exhausted in ~12 hours. Even with a per-token attempt limit, low-entropy tokens can be cracked in under 100 guesses if the attacker has the email address and can guess the target user's token from a small window of recent sends. The correct choice is crypto.randomBytes(32).toString('hex'), which produces 64 hexadecimal characters representing 256 bits of entropy — infeasible to brute force regardless of endpoint protection.

// VULNERABLE: 8-hex-char token — 32 bits, ~4.3 billion combinations
async function sendMagicLink(user) {
  // VULNERABLE: 4 bytes = 8 hex chars = 2^32 possibilities
  const token = crypto.randomBytes(4).toString('hex');
  // At 100 req/s: exhausted in ~12 hours; at 1000 req/s: ~1.2 hours

  await db.magicLinks.create({ token, userId: user.id, expiresAt: Date.now() + 900000 });
  // ...
}

// Also vulnerable: Math.random() — not cryptographically secure
const token = Math.random().toString(36).substring(2); // ← NEVER use Math.random for tokens
// FIXED: 32 bytes = 64 hex chars = 256 bits of entropy
async function sendMagicLink(user) {
  // FIXED: 32 bytes = 2^256 combinations — infeasible to brute force
  const token = crypto.randomBytes(32).toString('hex');
  // 64-character hex string; even at 1 trillion requests/second, exhaustion
  // would require longer than the age of the universe

  await db.magicLinks.create({ token, userId: user.id, expiresAt: Date.now() + 900000 });

  await email.send({
    to: user.email,
    subject: 'Your SkillAudit sign-in link (expires in 15 minutes)',
    html: `Sign in`,
  });
}

// Alternative: URL-safe base64 for shorter token strings at same entropy
// crypto.randomBytes(32).toString('base64url') → 43-char token, 256 bits
HIGH
SA-SKL-MAGICLINK-003 — MCP skill magic link token is generated with insufficient entropy: crypto.randomBytes(4).toString('hex') (32 bits), Math.random().toString(36) (not cryptographically secure), or similar short or non-CSPRNG token construction; against an unprotected or inadequately rate-limited token verification endpoint, an attacker can exhaust the token space in hours for short tokens or in unpredictable but feasible time for PRNG-based tokens. Fix: use crypto.randomBytes(32).toString('hex') (256 bits of entropy) or crypto.randomBytes(32).toString('base64url') for all magic link tokens; never use Math.random(), Date.now(), or sequential IDs as authentication tokens. Detection: SkillAudit flags crypto.randomBytes(N) calls with N < 16 (less than 128 bits) in token generation, and any use of Math.random() in authentication contexts.

MAGICLINK-004 — Session fixation via missing session regeneration

Session fixation is an attack where an adversary pre-sets the victim's session ID before authentication, then observes the authenticated session by monitoring the same session ID after the victim completes authentication. In the magic link context: an attacker who can inject a cookie into the victim's browser (via XSS on a subdomain, or if the magic link is opened on a shared device with a pre-existing session) can fix the session ID before the user clicks the magic link. If the magic link verification handler assigns req.session.userId = record.userId without calling req.session.regenerate() first, the session ID is unchanged — the attacker's pre-fixed session ID is now associated with the authenticated user. The fix is to call req.session.regenerate() before setting any authentication properties on the session, ensuring the session ID changes at the moment of authentication.

// VULNERABLE: session not regenerated — session fixation possible
app.get('/auth/magic', async (req, res) => {
  const record = await db.magicLinks.findOne({ token: req.query.token });
  if (!record || record.expiresAt < Date.now()) {
    return res.status(401).send('Invalid or expired link.');
  }

  await db.magicLinks.delete({ token: req.query.token });

  // VULNERABLE: session ID unchanged after authentication
  // Attacker who pre-set the session cookie now has an authenticated session
  req.session.userId = record.userId;
  res.redirect('/dashboard');
});
// FIXED: regenerate session before setting userId
app.get('/auth/magic', async (req, res) => {
  const { token } = req.query;
  if (!token || typeof token !== 'string') {
    return res.status(400).send('Missing token.');
  }

  const record = await db.magicLinks.findOne({ token });
  if (!record) return res.status(401).send('Invalid or expired link.');

  if (record.expiresAt < Date.now()) {
    await db.magicLinks.delete({ token });
    return res.status(401).send('This link has expired. Request a new one.');
  }

  await db.magicLinks.delete({ token }); // Single-use

  // FIXED: regenerate session ID before assigning auth properties
  // The old session ID (potentially fixed by attacker) is invalidated
  req.session.regenerate((err) => {
    if (err) {
      console.error('Session regeneration error:', err.message);
      return res.status(500).send('Authentication error. Please try again.');
    }
    req.session.userId = record.userId;
    req.session.authenticatedAt = Date.now();
    res.redirect('/dashboard');
  });
});
MEDIUM
SA-SKL-MAGICLINK-004 — MCP skill magic link verification handler sets req.session.userId without first calling req.session.regenerate(); an attacker who can pre-fix the victim's session ID (via XSS on a subdomain, shared device access, or network interception on HTTP) can hijack the authenticated session by monitoring the fixed session ID after the victim clicks the magic link. Fix: call req.session.regenerate(callback) before setting any session properties in all authentication success paths — magic link, OAuth callback, and password-based login; set req.session.userId inside the regenerate callback, not before it. Detection: SkillAudit flags authentication handlers that set req.session.userId (or equivalent auth property) without a preceding req.session.regenerate() call in the same code path.

SkillAudit detection summary — SA-SKL-MAGICLINK

Pattern IDSeverityWhat SkillAudit flagsFix
MAGICLINK-001CRITICALreq.session.userId set without a preceding DELETE or equivalent invalidation of the magic link token recordDelete token before session creation; use DB transaction for atomicity
MAGICLINK-002HIGHdb.magicLinks.create() without expiresAt field, or verification handler without record.expiresAt check15-minute TTL stored at creation; check expiresAt < Date.now() before auth
MAGICLINK-003HIGHcrypto.randomBytes(N) with N < 16 or Math.random() in token generationcrypto.randomBytes(32).toString('hex') — 256-bit entropy; never Math.random()
MAGICLINK-004MEDIUMreq.session.userId set without preceding req.session.regenerate() in authentication success pathreq.session.regenerate(cb) before setting auth properties in all auth flows

Related patterns: For brute force protection on login endpoints, see SA-SKL-BRUTEFORCE. For Host header injection in password reset email links, see SA-SKL-HOSTINJ. For JWT algorithm confusion in stateless auth tokens, see SA-SKL-JWTALG.