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.
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-mfa0
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
00 since Nov 8
| Date | Stars |
|---|---|
| Dec 6, 2026 | 0 |
| Dec 5, 2026 | 0 |
| Dec 4, 2026 | 0 |
| Dec 3, 2026 | 0 |
| Dec 2, 2026 | 0 |
| Dec 1, 2026 | 0 |
| Nov 30, 2026 | 0 |
| Nov 29, 2026 | 0 |
| Nov 28, 2026 | 0 |
| Nov 27, 2026 | 0 |
| Nov 26, 2026 | 0 |
| Nov 25, 2026 | 0 |
| Nov 24, 2026 | 0 |
| Nov 23, 2026 | 0 |
| Nov 22, 2026 | 0 |
| Nov 21, 2026 | 0 |
| Nov 20, 2026 | 0 |
| Nov 19, 2026 | 0 |
| Nov 18, 2026 | 0 |
| Nov 17, 2026 | 0 |
| Nov 16, 2026 | 0 |
| Nov 15, 2026 | 0 |
| Nov 14, 2026 | 0 |
| Nov 13, 2026 | 0 |
| Nov 12, 2026 | 0 |
| Nov 11, 2026 | 0 |
| Nov 10, 2026 | 0 |
| Nov 9, 2026 | 0 |
| Nov 8, 2026 | 0 |
616+616 since Nov 13
| Date | Weekly downloads |
|---|---|
| Dec 6, 2026 | 616 |
| Dec 5, 2026 | 646 |
| Dec 4, 2026 | 786 |
| Dec 3, 2026 | 814 |
| Dec 2, 2026 | 810 |
| Dec 1, 2026 | 661 |
| Nov 30, 2026 | 683 |
| Nov 29, 2026 | 559 |
| Nov 28, 2026 | 537 |
| Nov 27, 2026 | 380 |
| Nov 26, 2026 | 352 |
| Nov 25, 2026 | 331 |
| Nov 24, 2026 | 292 |
| Nov 23, 2026 | 261 |
| Nov 22, 2026 | 346 |
| Nov 21, 2026 | 316 |
| Nov 20, 2026 | 295 |
| Nov 19, 2026 | 262 |
| Nov 18, 2026 | 240 |
| Nov 17, 2026 | 219 |
| Nov 16, 2026 | 200 |
| Nov 15, 2026 | 0 |
| Nov 14, 2026 | 201 |
| Nov 13, 2026 | 0 |
Each point is npm's rolling 7-day download count.
Health Score
Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.
Badge for your README
[](https://payloaddirectory.dev/plugins/1453222867-root)<a href="https://payloaddirectory.dev/plugins/1453222867-root"><img src="https://payloaddirectory.dev/badge/1453222867-root.svg" alt="Payload Directory"></a>README
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.
limit; the plugin builds the key itself.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.resetPassword.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.mfa-state collection (one document per account), hidden from every API read and never written by Payload's sign-in.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:
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.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.
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
}),
],
})
HTTP can't carry the code: it travels in req.context, which only your server code can set. So:
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.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.turnOff and newRecoveryCodesFor. Check the password first; both need an app or recovery code (an emailed code only proves the mailbox).sendEmailCode(payload, { email }). It answers the same whatever the address, so say "if that account uses two-step, we've sent a code".verify(payload, { user, code, req }). For Hats: stepUp: { available: (u) => isOnFor(payload, u.id), verify: ({ user, code, req }) => verify(payload, { user, code, req }) }.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).afterPasswordSet(payload, { userId }).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.resetFor(payload, userId, { enrollHours, actor }).
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.reset event with by: pass the maintainer's id as actor, never an email address. If your onEvent throws, the reset has still happened.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' } })
@simplewebauthn/browser (startAuthentication, startRegistration) on your pages. The plugin gives you the options and checks the answer.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.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.proof) is { code } (an app or recovery code) or { passkey: { token, response } } from passkeyProofOptions(payload, { userId }). removePasskey(payload, { userId, id, proof }) always needs one.listPasskeys gives names and dates, never keys. renamePasskey changes a name. Up to 10 passkeys per account (maxPerAccount).MfaRefused with reason wrongPasskey, and the endpoint answers one 401. Challenges work once and last 5 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.resetFor also removes the account's passkeys (keepPasskeys: true keeps them).passkey-added, passkey-removed, passkey-renamed, passkey-signed-in and passkey-refused. None carry a key, a credential id, a name or an address.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],
},
})
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.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.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.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.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.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).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.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.
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.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.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.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.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.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.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.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.)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 }).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.recovery-requested event) and any screen.If your site kept two-step state in a group on the account (the first site did, as twoStep):
legacyUserField: 'twoStep', plus the keyDerivation values you used. The plugin refuses to start while the field is still declared.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.
useAPIKey on. Keep API keys on another collection. A custom auth strategy is your code's job: check isOnFor and your rule there.MFA_TRUSTED once you've checked one).requiredFor.keyDerivation values) makes stored authenticator secrets unreadable. People then sign in with a recovery code and set up again.onEvent is the record.sendEmailCode for your own. The same goes for recovery messages and recovery.send, and for the cancel page served with endpoint: true.npm test # Vitest, in-memory MongoDB
npm run typecheck
npm run build
MIT
Topics
payload better auth
Better Auth database adapter and plugins that run authentication through Payload collections
9011.9k/wk77v3 v4
payload auth
Replace Payload's built-in auth with Better Auth for a shared admin and frontend session
7021.0k/wk349v3
payload passkey
Passkey login and management for the Payload admin panel, built on Better Auth
66490/wk1v3 v4
payload auth pwless
Passwordless login for Payload with passkeys, magic links, OAuth and refresh-token sessions
4214/wk2v3
payload totp
Add TOTP-based two-factor authentication to a Payload auth collection using authenticator apps
8425.1k/wk168v3
oidc
OpenID Connect single sign-on for Payload using Authorization Code Flow with PKCE and native Payload sessions
65745/wk0v3