ExtantApe

payload plugin mfa

by ExtantApe
Authentication & SSO
v3
^3.90.0
MIT

Overview

Summary generated from the README

Adds multi-factor authentication to a Payload users collection. People sign in with a passkey, or with an authenticator app code after the password, with emailed and recovery codes as single-use backups. A rule you set decides who must enrol. Your server code calls the exported functions and your site builds the pages. Requires Payload 3.90 or later and MongoDB for recovery.

Features

  • Authenticator app codes with replay protection and per-account rate limits
  • Emailed codes and ten single-use recovery codes as backups
  • Passkey sign-in and management through WebAuthn with a required user check
  • Required-for rule checked at sign-in, on refresh and on every request
  • Remembered browser cookie and per-session code expiry
  • Recovery by emailed link with optional second-person approval and holder cancel link

Use cases

  • Require authenticator codes for admin users while letting members opt in
  • Let staff reset two-step for someone who lost their phone and recovery codes
  • Add passkey sign-in to a Payload site with your own custom login pages

From the author

MFA for Payload: sign in with a passkey, or with an authenticator code after the password. Emailed and recovery codes are backups, each used once, rate limited per account, and required by a rule you set.

Installation

npm i @extantape/payload-plugin-mfa

0

Stars

0

Forks

3

Open Issues

3 days ago

Last Updated

406

Weekly Downloads

v0.3.0

npm Version

213.3 KB

Unpacked Size

2

Dependencies

GitHub stars

00 since Nov 8

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20260
Dec 5, 20260
Dec 4, 20260
Dec 3, 20260
Dec 2, 20260
Dec 1, 20260
Nov 30, 20260
Nov 29, 20260
Nov 28, 20260
Nov 27, 20260
Nov 26, 20260
Nov 25, 20260
Nov 24, 20260
Nov 23, 20260
Nov 22, 20260
Nov 21, 20260
Nov 20, 20260
Nov 19, 20260
Nov 18, 20260
Nov 17, 20260
Nov 16, 20260
Nov 15, 20260
Nov 14, 20260
Nov 13, 20260
Nov 12, 20260
Nov 11, 20260
Nov 10, 20260
Nov 9, 20260
Nov 8, 20260
npm weekly downloads

616+616 since Nov 13

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 2026616
Dec 5, 2026646
Dec 4, 2026786
Dec 3, 2026814
Dec 2, 2026810
Dec 1, 2026661
Nov 30, 2026683
Nov 29, 2026559
Nov 28, 2026537
Nov 27, 2026380
Nov 26, 2026352
Nov 25, 2026331
Nov 24, 2026292
Nov 23, 2026261
Nov 22, 2026346
Nov 21, 2026316
Nov 20, 2026295
Nov 19, 2026262
Nov 18, 2026240
Nov 17, 2026219
Nov 16, 2026200
Nov 15, 20260
Nov 14, 2026201
Nov 13, 20260

Each point is npm's rolling 7-day download count.

Health Score

64/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1453222867-root.svg)](https://payloaddirectory.dev/plugins/1453222867-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1453222867-root"><img src="https://payloaddirectory.dev/badge/1453222867-root.svg" alt="Payload Directory"></a>
Updated Dec 3, 2026Created Nov 10, 2026Published Nov 29, 2026

README

payload-plugin-mfa

MFA for Payload: sign in with a passkey, or with an authenticator code after the password. Emailed and recovery codes are backups, each used once, limited per account, and required by a rule you set.

Status: early. 0.3.0 is the latest release. Recovery is new in 0.3.0 and no site uses it yet. Passkeys have been tested only against a software authenticator in the test suite, never on a real device or in a browser. 166 tests pass against a real Payload 3.92 with an in-memory MongoDB, covering every factor, replays, the limits (including 40 tries at once), remembered browsers, per-session expiry, the required rule, the login endpoint, races with Payload's own sign-in, passkeys, and recovery with every refusal (nobody signed in, the person themselves, the wrong role, another location, an approver without two-step, used and expired links, the holder's cancel link, a rule that throws, email that can't be sent, a password reset after a recovery by link alone). It's extracted from the version a live site runs, and it has no screens of its own apart from an optional plain page for canceling a recovery: your site builds the sign-in, settings and recovery pages.

What it does

  • After the password, a code. From an authenticator app (6 digits, one 30-second step of clock drift allowed), or as backups an emailed code (8 digits, 10 minutes) or one of 10 recovery codes. No text messages.
  • Each code works once. An app code can't be replayed, even within its drift window. An emailed or recovery code is used up. Two requests racing with the same code can't both win.
  • Limited per account, never by address. 5 code tries and 3 emailed codes per 15 minutes per account, so changing address gives no fresh tries. An optional per-address limit sits on top. Bring your own limiter with limit; the plugin builds the key itself.
  • Required by your rule. requiredFor decides who must have it. It's checked at sign-in, on every refresh, and on every request for open sessions, and if it throws the account counts as required. A required account that hasn't enrolled can't sign in, so a stolen password can't enrol its own phone. Staff can open a short window with allowEnrollment.
  • Remembered browsers. After a code, the site can set a cookie so the password alone works for 24 hours. A new password or a new app ends it. A session can't outlive the code it came from, counted per session, so one device's code never extends another.
  • After a password reset, emailed codes are off for 24 hours, since the mailbox has just proved itself. The plugin does this by itself after Payload's resetPassword.
  • A way back. With recovery set, someone who lost their app and recovery codes asks by email, a second person approves it where your rule says so, and a single-use link resets two-step. The holder can cancel it from the first email, is told, every session ends, and each recovery is kept on record.
  • Nothing readable. The secret is sealed with AES-256-GCM, using a key derived from your app secret. Codes are stored hashed. The state lives in its own mfa-state collection (one document per account), hidden from every API read and never written by Payload's sign-in.

On its own, and with others

On its own: it adds its own mfa-state and tries collections beside your users collection (plus mfa-recoveries when recovery is on). Your server code calls signIn, start, confirm and verify, and your site builds the pages. API keys can't be on the same collection.

Needs: Payload ^3.90.0 as a peer dependency. No other EXTANT APE plugin is required.

Works with:

  • Hats: use isOnFor and verify as Hats' stepUp (the two lines are under "Using it"), so switching into a sensitive hat asks for the same authenticator code.
  • Audit Trail: pass onEvent through Audit Trail's fromPluginEvent. MFA's own state writes skip collection hooks, so these events are the only record the trail gets.

Color Theory: none needed. It has no screens of its own apart from the optional cancel page, and its collections use Payload's standard admin, which takes Color Theory's admin colors when its applyToAdmin option is on.

Family: It's part of the Identity family (a working draft): plugins designed to sit together for accounts and access.

Install

npm install @extantape/payload-plugin-mfa
import { mfa } from '@extantape/payload-plugin-mfa'

export default buildConfig({
  plugins: [
    mfa({
      requiredFor: ({ user }) => user.roles?.includes('admin') ?? false,
      issuer: 'My site',
      onEvent: (event) => auditLog(event), // event.user is the account; event.req has no code, headers or body, and its payload isn't enumerable
    }),
  ],
})

Using it

HTTP can't carry the code: it travels in req.context, which only your server code can set. So:

  • Sign in from a server action with signIn(payload, { email, password, code }), or with remember (the cookie's value) instead of code. Errors are Payload's usual ones; an MfaError has mfa: 'needed' | 'wrong' | 'enroll'. After a good code, set the REMEMBER_COOKIE cookie (HttpOnly) to await rememberValue(payload, { userId }). Sites without server actions can turn on endpoint: true for POST /api/users/mfa/login { email, password, code }, which sets both cookies.
  • Set up with start(payload, { userId }), which returns { uri, key } for a QR code, and then confirm(payload, { userId, code }), which returns the recovery codes once. Check the person's password before start. If two-step is already on, start needs a current app or recovery code.
  • Turn off or renew codes with turnOff and newRecoveryCodesFor. Check the password first; both need an app or recovery code (an emailed code only proves the mailbox).
  • Emailed codes: sendEmailCode(payload, { email }). It answers the same whatever the address, so say "if that account uses two-step, we've sent a code".
  • Step-up before a sensitive action: verify(payload, { user, code, req }). For Hats: stepUp: { available: (u) => isOnFor(payload, u.id), verify: ({ user, code, req }) => verify(payload, { user, code, req }) }.
  • Your own vouching: pass context: { [MFA_TRUSTED]: true } to payload.login only from server code that has checked the person another way, or that throws the token away (for example, checking a password).
  • Invitations: after a password set through an emailed link, call afterPasswordSet(payload, { userId }).
  • Status for the person's own security page: statusFor(payload, userId) gives { on, since, recoveryLeft }, and nothing about the secret or the codes. Pass the signed-in person's own id; it trusts the id it's given.
  • A maintainer's reset, for someone who lost their app and their recovery codes: resetFor(payload, userId, { enrollHours, actor }).
    • It needs no code, so check the maintainer, and confirm who you're resetting another way, in your own code first.
    • It clears the app, the recovery codes, any emailed code and the per-session records. Remembered browsers stop working.
    • It signs the account out everywhere, because a stolen phone may have a session open. Pass endSessions: false to keep them. It also records when the reset happened, and any session made before then is refused at every request and refresh. That holds even if a sign-in racing the reset wrote the old sessions back, so each signed-in request reads the account's two-step state once (one small query). This needs Payload's sessions (auth.useSessions, on by default). With sessions off there's nothing to end, and old tokens keep working until they expire.
    • It opens an enrollment window: default 24 hours, at most 14 days. During it, anyone who knows the password can set up a phone. Keep it short, and reset the password too if it may be known.
    • It clears the account's built-in limiter tries. A limiter of your own isn't cleared.
    • It sends a reset event with by: pass the maintainer's id as actor, never an email address. If your onEvent throws, the reset has still happened.
    • A block on emailed codes after a password reset stays.
    • Neither function has an endpoint.

Passkeys

Off until you set passkeys. A passkey signs a person in by itself, with no password and no code. The authenticator app and recovery codes stay as the fallback. The design is in docs/adr/0002-passkeys.md.

mfa({ passkeys: { rpID: 'example.com', origins: ['https://example.com'], rpName: 'Example' } })
  • Browser side is yours. Use @simplewebauthn/browser (startAuthentication, startRegistration) on your pages. The plugin gives you the options and checks the answer.
  • Sign in: passkeySignInOptions(payload, { req }) returns { token, options }. Send options to the browser, then pass { token, response } to passkeySignIn(payload, { token, response, req }). It returns { token, exp, sid, user } after starting a normal Payload session, with your collection's login hooks run. Set the cookie from token. With endpoint: true the same two steps are POST /api/users/mfa/passkey/options and POST /api/users/mfa/passkey/sign-in, which sets the cookie.
  • Add one: beginPasskey(payload, { userId, proof }) then finishPasskey(payload, { userId, token, response, name }). Every passkey needs a name. Check the password first. If the account already has an app or a passkey, proof is needed too.
  • A fresh check (proof) is { code } (an app or recovery code) or { passkey: { token, response } } from passkeyProofOptions(payload, { userId }). removePasskey(payload, { userId, id, proof }) always needs one.
  • Manage: listPasskeys gives names and dates, never keys. renamePasskey changes a name. Up to 10 passkeys per account (maxPerAccount).
  • Always the person's own check. Passkeys must be discoverable and need the fingerprint, face or PIN. A bare tap is refused.
  • One refusal. Every sign-in problem gives MfaRefused with reason wrongPasskey, and the endpoint answers one 401. Challenges work once and last 5 minutes.
  • Limits: 10 tries per account per 15 minutes (limits.passkey), and per address when you give clientAddress. Challenge requests are limited too. Give clientAddress on a public site. Without a known address, every request shares one bucket of limits.passkey tries per window, so guessing stays limited but one busy period can lock everyone out. Every limits.* value and windowMinutes must be a whole number of at least 1.
  • A maintainer's resetFor also removes the account's passkeys (keepPasskeys: true keeps them).
  • Events: passkey-added, passkey-removed, passkey-renamed, passkey-signed-in and passkey-refused. None carry a key, a credential id, a name or an address.
  • Not covered: attestation checks, Hats step-up with a passkey, and any screen. An account that must have two-step and has only a passkey can't sign in with its password; it uses the passkey.

Recovery

Off until you set recovery. It's for someone who lost their authenticator app and their recovery codes, or their only passkey. A single-use emailed link resets two-step, and for the accounts you choose a second person has to approve it first.

const rank = { member: 1, staff: 2, admin: 3 }

mfa({
  recovery: {
    link: (token) => `https://example.com/recover/${token}`,
    cancelLink: (token) => `https://example.com/recover/cancel/${token}`,
    // Mailbox only for members who chose it on their settings page. Everyone else needs an approver.
    needsApproval: ({ account }) => !(account.role === 'member' && account.mailboxRecovery === true),
    // An admin at the same location who ranks at least as high as the account.
    canApprove: ({ approver, account }) =>
      approver.role === 'admin' && approver.site === account.site && rank[approver.role] >= rank[account.role],
  },
})
  • Ask: call requestRecovery(payload, { email, req }) from your lost-my-code form. It answers at once, before it looks anything up, so the answer is the same and takes the same time whatever the address. Say "if that account uses two-step, we've sent instructions". The work then runs through after, which by default starts it without waiting. If your host stops work once the response is sent (serverless functions often do), pass its own hook, such as Next's after from next/server. Each account gets 3 requests per 15 minutes (limits.recovery) from each client address, counted per account and address together when clientAddress gives one, and per account alone when it doesn't. With an address, each address also gets 3 across all accounts. One recovery at a time per account.
  • Who needs a second person: needsApproval. Only an exact false sends the link straight to the account's own address. Any other answer, a thrown error or no rule at all means an approver is needed. The holder then gets a notice that someone asked, and nothing else changes. Keep the mailbox-only route for accounts whose holders chose it, since it trusts the mailbox alone.
  • The mailbox alone, and password resets. A link sent straight to the account isn't sent while emailed codes are blocked after a password reset (emailBlockHours, 24 by default), nor at all once a password has been set through the mailbox, until the account signs in with its second step again. After a recovery by link alone, password resets are refused for emailBlockHours, or until the window to set up again closes if that's later. Payload's resetPassword answers with its usual expired-link error and the plugin sends a password-reset-refused event. Before a reset through your own form, check passwordResetAllowed(payload, { userId }). A recovery a second person approved doesn't block resets.
  • Who may approve: canApprove. Only an exact true passes. Any other answer or a thrown error refuses, and with no rule nobody can approve. The plugin always refuses an approver who is the account itself, and by default one with no second step of their own (no authenticator app and no passkey); approverNeedsTwoStep: false turns that off. Have the rule pass only approvers who rank at least as high as the account. If one person can hold several accounts on your site, check for that in this rule. The rule runs again when the link is used, with the holder's request as req, so an approver who has since lost the right can't have their link used, and a rule that reads req.user fails at that point and refuses the link.
  • An account someone else looks after (a child's, say): keep needsApproval on for it, and have canApprove pass only the person your site has on record for that account. The plugin knows nothing about how your site links them. If the account's own address can't take mail, your own send decides where the link goes.
  • Approve or decline: listRecoveries(payload, { approver }) gives the open recoveries that person may act on. approveRecovery(payload, { id, approver, note }) emails the link. declineRecovery(payload, { id, approver }) ends the recovery, a link already sent stops working, and the holder is told. It throws MfaRefused with gone when the recovery had already ended, and with unsure when the database failed and the decline isn't known to have landed: the link may still work, so decline it again. approver is the signed-in person's id, and note is their own line on how they checked who the person is. A refusal is always MfaRefused with reason notAllowed, whether or not the recovery exists. An approver has 72 hours (approveWithinHours).
  • Use: your page at link(token) shows a button, and the button calls useRecovery(payload, { token }). Don't call it when the page loads, because mail scanners open links. It returns done, expired (unknown, used, declined, out of time, or an approver who may no longer approve, without saying which) or failed. The link works once, for 24 hours (linkHours). done means every part of the reset was written: the app, recovery codes and passkeys are gone, every session has ended, and the account has 24 hours (enrollHours) to set up again. failed means some part wasn't, and the link still works, so pressing it again finishes the reset. It also answers failed when the database fails while the link is being marked used; pressing again then either finishes the reset or answers expired, and the account can ask again.
  • Cancel: the first email of every recovery (the notice that someone asked, or the link itself when no approver is needed) also carries cancelLink(token), for the holder. cancelLink must return a non-empty address; if it returns anything else or throws, no recovery is opened and nothing is sent. Your page at that address shows a button, and the button calls cancelRecovery(payload, { token, req }). Opening the page must change nothing: don't call it when the page loads. With endpoint: true, the plugin serves a plain page for this at GET /api/<users>/mfa/recovery/cancel?token=<token>, so cancelLink can point there. Its button posts the token in the form body to the same path, with no query. The page is sent with Cache-Control: no-store, Referrer-Policy: no-referrer, X-Content-Type-Options: nosniff and a strict content security policy.
    • Tokens in addresses get logged. Hosts, proxies and analytics often log the full address of every request, query string included, so a cancel token in an emailed address can end up in those logs. On your own page, have the button post the token in the body to an address without it. cancelRecovery leaves the request's address and query out of the request it passes to your limit, send and onEvent. The cancel link works once, for as long as the recovery could still run (the time to approve plus the link's time, or the link's time alone). It returns:
    • canceled: that one recovery is stopped, its reset link no longer works, and the account can ask again later. Nothing else changes: no sign-in, no session, no change to two-step or the password.
    • finished: the reset link was used first, so this recovery can't be canceled. From then on its reset link is never put back: if that reset then fails part way, useRecovery answers failed, the recovery stays ended and the account asks again. Tell the holder to contact your staff if the reset wasn't them.
    • expired: anything else (unknown, already used, past its time, or a recovery that was declined or ran out), without saying which.
    • It throws MfaRefused with unsure when the database failed and it can't be told whether the cancel landed. Have the holder press again: expired then means the reset link no longer works. Any other error means nothing was canceled, and pressing again is safe. The plugin's page says this.
    • It throws MfaRefused with tooMany past 10 tries per client address per 15 minutes (limits.cancel), or when your limit throws or answers anything but true. A request with no known address (no clientAddress, or it returns nothing) is counted against the link it names instead (LimitKind recoveryCancel-link), so it can only use up that link's tries. A token of the wrong shape names no link and is answered expired without being counted. Give clientAddress anyway, so one address can't try many links. Without it, put your own rate limit in front of the cancel button, and with it, raise limits.cancel if many holders reach you from one shared address.
    • The record keeps when it was canceled. The approver who approved it, if any, gets a canceled message, and a recovery-canceled event names what it was when canceled (was: open while waiting for an approver, approved once an approver approved it, or link for a link sent by the mailbox alone), who approved it (by) and whether they were told. An approval that is still sending its link when the cancel lands is refused with gone, and its link never works. If the approval was recorded before the cancel landed, the recovery-canceled event comes after it, with was: approved; otherwise the approval is never recorded. An approver who hadn't acted yet only sees it drop off listRecoveries; use the event to tell them.
  • If someone else controls the holder's mailbox, the holder can't use the cancel link, and whoever reads that mail can ask for a recovery and reset the password. The holder should contact your site's staff another way. What the plugin gives staff: an approver can decline the recovery with declineRecovery (open or already approved), which stops its link at once, and a maintainer can run resetFor to end every session. Changing the account's email address and password is your site's own job. The plugin can't tell who reads a mailbox, and it has no switch to stop new recovery requests for one account, so keep needsApproval on for accounts that matter.
  • It fails closed. If the notice or the link can't be sent, or your onEvent throws while a request or an approval is being recorded, nothing is opened or approved. A reset link works only once it was sent, its event was recorded and that was stored, by either route; until then nothing can use it. After the link goes out, approveRecovery answers notSent or gone only when its link is known not to work. Its message says whether the recovery was put back, so it can be approved again, or may be left being approved, in which case the account can ask again after 15 minutes. When the database fails so badly that it can't tell, it answers unsure: the link may work, so decline the recovery with declineRecovery if it shouldn't go ahead. A recovery left part way by a database failure stops new requests for that account for 15 minutes. With no send of your own and no email adapter, nothing is sent, because Payload would write a working link to the server log.
  • The holder is told when someone asks (where an approver is needed), by the link itself, when an approver declines, and once two-step has been reset. The first of these is sent from the work that requestRecovery hands to after, so on a serverless host pass after (Next's after, or your host's waitUntil), or the notice may never be sent. Pass send for your own wording and sender. It gets { kind, to, account, approver, link, hours, resetsBlockedUntil }, where kind is link, requested, declined, completed, password-reset or canceled, plus cancel (the holder's cancel link) on the first notice. A canceled message goes to the approver who approved the recovery. The default is plain English through payload.sendEmail.
  • The record. Each recovery stays in the hidden mfa-recoveries collection: whose account, who approved or declined it, when, how (approved or link) and the approver's note. Only the hashes of the link and the cancel link are kept. The collection is closed to every REST and Local API read and write, and left out of GraphQL. The events are recovery-requested, recovery-approved, recovery-declined, recovery-refused, recovery-completed, recovery-canceled and password-reset-refused, plus the reset that resetFor sends. None carry a token or an address. (recovery-used and recovery-renewed are about recovery codes.)
  • After a password reset. Payload's own forgot-password link works once and expires. A reset changes the password only: an account with two-step still needs its second step to sign in, and emailed codes stay off for emailBlockHours. With recovery set, after Payload's resetPassword the plugin also ends every session except the one the reset made, emails the holder and sends a password-reset event. After a reset through your own form, call afterPasswordReset(payload, { userId, keepSession }).
  • MongoDB only. Each step of a recovery is one conditional write, and one recovery per account rests on a unique index on the liveKey field of mfa-recoveries. Both have been tested only with Payload's MongoDB adapter. Make sure that index exists before you turn recovery on: the MongoDB adapter builds it at start unless index building is off, and if you build indexes yourself, include it.
  • Not covered: a waiting period after a recovery, messages to approvers (use the recovery-requested event) and any screen.

Moving from state kept on the account

If your site kept two-step state in a group on the account (the first site did, as twoStep):

  1. Back up the database. Get the site owner's yes before it runs on production.
  2. Remove that field from the auth collection and pass legacyUserField: 'twoStep', plus the keyDerivation values you used. The plugin refuses to start while the field is still declared.
  3. Run await moveLegacyState(payload) once, as a script. It copies each account's old state where the account has no record yet and removes the old field. If the account already has a record with no secret and no sign that two-step was cleared on purpose (a started setup, or an email-code block after a password reset), the old secret, enabled date and last step are merged into that record, which keeps what it already had. Recovery codes are never copied into an existing record. The old field is removed only after the merge is written. If the record was left by turnOff or by a maintainer's resetFor (it has turnedOffAt, resetAt or enrollUntil, or an enabled date, recovery codes or a last step), nothing is merged: the old field stays, the account stays at the two-step step, and its id is listed in needsReview for the site to decide. If the record already has a secret, that secret stays. When the old secret is different, the id is listed in differentSecret and the old secret is gone from the account, so keep the backup. A setup that was never confirmed is dropped and counted. It returns { moved, merged, alreadyMoved, unfinished, cleared, differentSecret, needsReview } and is safe to run again. MongoDB only.

Until an account's old state is moved, that account can't sign in, so nothing runs half-moved with weaker sign-in.

Limits

  • API keys aren't supported on the same collection: they sign in without a password or code, so the plugin refuses to start with useAPIKey on. Keep API keys on another collection. A custom auth strategy is your code's job: check isOnFor and your rule there.
  • Payload's own reset page can't collect a code. For an enrolled account, reset the password through your own form, with a code (or MFA_TRUSTED once you've checked one).
  • The per-request check for open sessions looks the account up once per authenticated request, and only when you set requiredFor.
  • Changing the app secret (or the keyDerivation values) makes stored authenticator secrets unreadable. People then sign in with a recovery code and set up again.
  • The plugin's own state writes go straight to the database, so collection hooks (an audit trail's included) don't see them; onEvent is the record.
  • The try limit orders tries by each server's clock. If your servers' clocks disagree, a burst could get a few extra tries through. Keep clocks in sync (they are on any managed host).
  • Old tries are deleted as new ones arrive, so the try table stays small.
  • The emailed code's default wording is English. Pass sendEmailCode for your own. The same goes for recovery messages and recovery.send, and for the cancel page served with endpoint: true.

Commands

npm test          # Vitest, in-memory MongoDB
npm run typecheck
npm run build

License

MIT

Similar plugins