> For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt.

# Magic link

`magicLink` lets users log in with a link sent by email, without a password. It needs [messages and links](https://dotpress.dev/auth/messages.md), and the `users` (`findAccount`, `findByEmail`, `markEmailVerified`, `setPasswordHash`, and `create` with `signUp`) and `tokens` (with `invalidate`) [stores](https://dotpress.dev/auth/data-provider.md#the-stores). To claim the [unverified accounts](#unverified-accounts), it also needs `list` and `delete` of the `passkeys` store, `listByUser` and `delete` of the `identities` store, `listFactors`, `deleteFactor` and `deleteRecoveryCodes` of the `mfa` store, and `revokeAll` of the `trustedDevices` store, for each of these stores the data provider defines.

```ts
createAuth({
  // …
  messages: { send },
  links: { baseUrl: 'https://app.example.com' },
  magicLink: {
    ttl: '15m', // lifetime of the links
    signUp: false, // true: unknown addresses get a link too, and an account
  },
})
```

| Route                          | Body                                                | Answer                                                                       |
| ------------------------------ | --------------------------------------------------- | ---------------------------------------------------------------------------- |
| `POST /auth/magic-link`        | `{ email, redirectTo?, codeChallenge?, clientId? }` | `202 { status: 'accepted' }`, always                                         |
| `POST /auth/magic-link/verify` | `{ token, codeVerifier?, mode? }`                   | the answer of a login: `{ status: 'authenticated', userId, accessToken, … }` |

1. `POST /auth/magic-link` sends a `magic_link` message to the address of an account, and answers the same for any other address: a request for an unknown address waits for the running average time of the requests for known ones. A new link replaces the previous ones of the address. `3` requests per hour per address and `10` per IP address (`rateLimits.emailRequests`).
2. The link opens the app page `/magic-link?token=…` (see [Links](https://dotpress.dev/auth/messages.md#links)), which posts the token to `POST /auth/magic-link/verify`. An email scanner that opens the link logs nobody in.
3. The token is used once. The session uses the method `magic_link`, with `amr: ['email']`. The link proves the address: an unverified address becomes verified (`users.markEmailVerified()`), and `emailVerification.required` does not block it.

The login goes through the account gate (`403 ACCOUNT_SUSPENDED`, `403 ACCOUNT_DISABLED`), `beforeSession` and [MFA](https://dotpress.dev/auth/mfa.md), and records `login.succeeded` or `login.failed` with `method: 'magic_link'`. An unknown, expired or used link answers `400 INVALID_TOKEN`, `10` checks per 15 minutes per IP address (`rateLimits.tokenChecks`). An address of a domain that logs in with its IdP ([SSO enforcement](https://dotpress.dev/auth/sso.md#discovery-and-enforcement)) gets no link: `POST /auth/magic-link` answers `403 SSO_REQUIRED`, with `data.connectionId`. With `mode: 'cookie'`, a verification from an untrusted origin answers `403 CROSS_ORIGIN_REQUEST` (see [CSRF](https://dotpress.dev/auth/cookies.md#protection-against-cross-site-request-forgery)).

A password change or reset, and a confirmed email change, invalidate the pending links of the account.

## Unverified accounts

A link used on an unverified account gives the account to the owner of the address: whoever signed up with it before (a pre-registered account) loses what they set. The password of the account is removed, and its credentials too: passkeys, linked provider accounts, second factors, recovery codes and trusted devices (each removal records its event: `passkey.removed`, `identity.unlinked`, `mfa.factor_removed`, `trusted_device.revoked`). Its sessions are revoked (reason `account_claimed`), and its pending links are invalidated. When a password or a credential was removed, the address receives an `account_claimed` message (`passwordRemoved` tells whether the password went). The owner sets a password with a [password reset](https://dotpress.dev/auth/password-reset.md).

The same claim runs when an unverified account is proven by a [password reset](https://dotpress.dev/auth/password-reset.md#reset), by a [verification link](https://dotpress.dev/auth/email-verification.md#binding-the-link-to-the-browser) opened without the verifier of the sign-up (for an account with a password), or by a provider ([social login](https://dotpress.dev/auth/oauth.md), [SSO](https://dotpress.dev/auth/sso.md)).

## Sign-up by link

With `magicLink.signUp`, an address without account receives a link too. Nothing is created until the link is used: `users.create({ email, passwordHash: null, emailVerified: true, method: 'magic_link', extra: {} }, meta)` then creates the account, which `signUpRejected()` can still refuse (`400 SIGN_UP_REJECTED`). The message has `userId: null`.

While the [sign-up](https://dotpress.dev/auth/sign-up.md) is `closed` (`signUp.mode: 'closed'`), unknown addresses get no link, and a link sent before answers `403 SIGN_UP_DISABLED`: no account is created.

## Binding the link to a device

A link opened on another device, or intercepted, logs in whoever opens it. PKCE ([RFC 7636](https://www.rfc-editor.org/rfc/rfc7636), S256) binds it to the device that asked for it:

```ts
// When asking for the link: keep the verifier on the device.
const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)))
const challenge = base64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))
sessionStorage.setItem('magic-link-verifier', verifier)
await post('/auth/magic-link', { email, codeChallenge: challenge })

// On the page of the link:
await post('/auth/magic-link/verify', { token, codeVerifier: sessionStorage.getItem('magic-link-verifier') })
```

A link requested with a `codeChallenge` answers `400 INVALID_CODE_VERIFIER` without the right `codeVerifier`, and stays usable from the right device. The binding is chosen by the client: a link requested without `codeChallenge` is not bound, and logs in from any device. Mobile apps open the link in the app with `links.build()` (a universal link), which keeps the verifier.

## Clients

With the [`clients` setting](https://dotpress.dev/auth/clients.md), the `clientId` sent with the request becomes the client of the session. `clients.isUserRoleAllowed()` is called with `role: undefined`: a magic link has no `findUserIdentifiers()` result. Check the clients a user may reach in `beforeSession` when they depend on the role.

## Service

`auth.magicLink.request({ email, redirectTo?, codeChallenge?, clientId? })` and `auth.magicLink.verify({ token, codeVerifier?, locale? }, { logger? })` do the same outside the routes. A rejected login throws an `AuthError`: `ACCOUNT_SUSPENDED`, `ACCOUNT_DISABLED`, `CLIENT_NOT_ALLOWED`, `SIGN_UP_DISABLED`, or `SESSION_REJECTED` with the `reason` of `beforeSession` in `data`.

## Handoff codes

The redirect flows (OAuth, SSO) end on a page of the app, outside the API client that started them. In body mode, the API redirects with a one-time **handoff code**, and the client exchanges it for its tokens:

```ts
createAuth({
  // …
  handoff: { ttl: '60s', pkce: 'required' }, // or pkce: 'optional'
})
```

`handoff` needs the `tokens` store and `users.findAccount()`.

| Route              | Body                             | Answer                |
| ------------------ | -------------------------------- | --------------------- |
| `POST /auth/token` | `{ code, codeVerifier?, mode? }` | the answer of a login |

`auth.handoff.issue({ userId, method, amr, clientId?, identifier?, codeChallenge? })` stores a code of 256 random bits for an authentication completed by a redirect flow, and returns `{ code, expiresAt }`. The code holds no token: the session starts at the exchange, through the account gate and `beforeSession`. Each code works once, and the codes of a user do not replace each other. A password change or reset, an email verification or change, and the revocation of every session of the user invalidate the pending codes.

With `pkce: 'required'` (default), `issue()` throws `CODE_CHALLENGE_REQUIRED` without a `codeChallenge`, sent by the client when it started the flow, and `/auth/token` requires its `codeVerifier` (`400 INVALID_CODE_VERIFIER`): a code read from a redirect URL is useless to another app. The start routes of the [social login](https://dotpress.dev/auth/oauth.md#login) and [SSO](https://dotpress.dev/auth/sso.md#login) check it at once: `mode=body` without `codeChallenge` answers `400 CODE_CHALLENGE_REQUIRED`.

With `mode: 'cookie'`, an exchange from an untrusted origin answers `403 CROSS_ORIGIN_REQUEST`.
