MFA bypass: the paths around a second factor, and how to test each one
A second factor means a stolen password is not enough on its own, but only on the paths that ask for it.
This guide explains how second factors are relayed, fatigued and gone around through enrolment, recovery, remembered devices and older sign-in routes, what the standards ask for at each step, and how to test your own application. It comes with a test matrix organised by state change and a Node.js lab with a time-based one-time password checked against the RFC test values.
In this guide
MFA test matrix and local TOTP lab
An illustration on invented accounts. Part 1 is a test matrix organised by state change: enrolment, sign-in with the second factor, changing or removing a factor, recovery, remembered devices, push approval with number matching, and reauthentication for sensitive actions, with steps, the expected result, the evidence to keep and the source behind each expectation.
How to use itHide the instructions
Parts 2 to 6 are a Node.js lab with no installs: a time-based one-time password checked against the RFC test values, a sign-in service in a careless and a careful version, a runner that prints a result per matrix row, and a regression test that fails on the careless version. For an application you own or are authorised in writing to test.
mfa-security.txt
Introduction4 lines
Part 1: The MFA test matrix316 lines
Part 2: The lab files872 lines
Part 3: The code generator against the RFC test values25 lines
Part 4: The matrix rows the lab can show73 lines
Part 5: The regression test69 lines
Part 6: Point the checks at your own application5 lines
Whole template1,399 lines
MFA ENROLMENT, RECOVERY AND REMEMBERED-DEVICE TEST MATRIX, WITH A LOCAL LAB
An illustration, for testing an application you own or are authorised in writing to test.
Written and run on: Node.js 26.0.0 on an Apple M3 Max machine (macOS, arm64). The lab imports only node:http, node:crypto, node:test and node:assert, and installs no packages. Every output below was copied from that run by a script; the per-test timings will differ on your machine. The two accounts are invented, and their passwords end in not-real. Authenticator secrets, recovery codes and device tokens are random values the lab makes in memory on each run and never prints, and the only fixed key is the RFC test key. The lab talks only to its own server on 127.0.0.1.
================================================================
PART 1: THE MFA TEST MATRIX
Who it is for. Run these tests only on an application you own, or one you are authorised in writing to test, and only with test accounts created for the purpose. Use a staging copy where you have one. Lockout and recovery rows run only on test accounts. Push and text-message rows send only to a test device and a test number you hold, never to a real person's phone. The support-desk row is a walk-through with a support team that knows it is a test. Nothing here is for probing someone else's sign-in.
What you need:
Account A a test account with a password, an authenticator app you control and its recovery codes.
Account B a second test account set up the same way, for S2.
Devices a test phone for push prompts and a test number for text messages, if your application uses them.
Tools a way to read whole requests and responses, such as the Network panel in your browser's developer tools.
Staging a way to move the server clock or shorten lifetimes, for S6, D2 and P5.
Evidence to keep for every row: the request as sent, with passwords, codes and tokens redacted; the whole response (status, Set-Cookie and Location headers, and body); the time; the test account; and the build or commit tested.
How to read a row. Steps is what to do. Expected is what the named sources ask for, except where the row marks all or part of it as this matrix's own advice, interpretation or choice. Evidence is what to keep. Basis names the source, or says the expectation, or a part of it, is this matrix's own. Lab names the lab check that shows the row, or says the lab does not cover it.
Source names used in the rows:
MFA CS OWASP Multifactor Authentication Cheat Sheet
Auth CS OWASP Authentication Cheat Sheet
Forgot CS OWASP Forgot Password Cheat Sheet
ASVS OWASP ASVS 5.0.0, with each requirement's level: L1, L2 or L3
SP 800-63B-4 NIST SP 800-63B-4 (July 2025), with its section number and its own SHALL, SHOULD and MAY. Written for government information systems.
RFC 4226 HOTP: An HMAC-Based One-Time Password Algorithm (December 2005)
RFC 6238 TOTP: Time-Based One-Time Password Algorithm (May 2011)
WebAuthn L3 W3C Web Authentication Level 3, a W3C Recommendation dated 25 August 2026
CISA NM CISA fact sheet, Implementing Number Matching in MFA Applications (October 2022)
CISA PR CISA fact sheet, Implementing Phishing-Resistant MFA (October 2022)
T1621 and others MITRE ATT&CK techniques T1621, T1556.006, T1098.005 and T1539
WSTG-ATHN-03 OWASP WSTG v4.2, Testing for Weak Lock Out Mechanism
TRANSITION 1: NO FACTOR TO ENROLLED
E1 Who can start enrolment, and what is asked first
Steps: signed in to A with the password only, start setting up the authenticator app without entering the password again. If your application has accounts that have never signed in or are marked inactive, try to enrol a first factor on one of those with its password alone.
Expected: the password, or a factor already on the account, is asked for before any secret is shown; an inactive account cannot enrol a first factor on the password alone.
Evidence: each request and response.
Basis: SP 800-63B-4 4.1.2.1 (binding any new authenticator SHALL require authentication at the maximum AAL currently available in the account, or the maximum AAL the new authenticator will be used at, whichever is lower); T1098.005 (in some cases self-enrolment may require only a username and password to enrol an account's first device, or a device for an inactive account; its mitigation (M1032) includes configuring MFA systems to disallow enrolling new devices for inactive accounts). Asking for the password again on an account that has only a password is this matrix's advice.
Lab: E1.
E2 An unfinished enrolment changes nothing
Steps: start enrolment on A and stop before entering a code from the app. Sign out and sign in again.
Expected: the account signs in exactly as before; the new secret is not live until a code from the app has been accepted.
Evidence: the sign-in response before and after.
Basis: this matrix's advice.
Lab: E2.
E3 The secret is random and handed over once
Steps: enrol A twice, removing the factor in between, and compare the two secrets; read the code that generates and stores them.
Expected: each secret comes from a cryptographically secure generator and differs from the last; it is shown only on the enrolment screen of the signed-in session; on the server, only the components that verify codes can read it.
Evidence: the generation and storage code, and confirmation the two secrets differed (test accounts only, then discarded).
Basis: ASVS 6.5.3 (L2: TOTP seeds generated with a CSPRNG); RFC 6238 section 3 (keys SHOULD be randomly generated or derived) and 5.1 (RECOMMENDS storing keys securely in the validation system); SP 800-63B-4 3.1.4.2 (the symmetric keys SHALL be strongly protected against unauthorised disclosure by access controls that limit access to the software components that require it). MFA CS says this would typically involve the user scanning a QR code provided by the application, which provides the initial seed. Showing the secret only on the enrolment screen of the signed-in session is this matrix's own detail.
Lab: not checked; the careful version uses crypto.randomBytes for each secret.
E4 The owner hears that a factor was added
Steps: complete enrolment on A and read every inbox and device on the account.
Expected: a notice sent somewhere other than the session that enrolled the factor, saying what changed and who to contact if it was not them.
Evidence: the notice.
Basis: SP 800-63B-4 4.1.2.1 (when an authenticator is added, the CSP SHALL notify the subscriber via a mechanism independent of the transaction binding it) and 4.6 (the notification SHALL give clear instructions, including contact information, in case the recipient repudiates the event).
Lab: not checked; the careful version sends a notice to its outbox.
TRANSITION 2: PASSWORD ACCEPTED TO SECOND FACTOR CHECKED
S1 A code works once
Steps: sign in to A with a code; within the same 30 seconds, sign in again from a second browser with the same code.
Expected: the second use is refused.
Evidence: both responses, with their times.
Basis: RFC 6238 5.2 (the verifier MUST NOT accept the second attempt of the OTP after the successful validation of the first); SP 800-63B-4 3.1.4.2 (verifiers SHALL accept a given OTP only once while it is valid); ASVS 6.5.1 (L2: look-up secrets, out-of-band codes and TOTPs only successfully usable once); MFA CS (OTPs single use, and invalidated on successful verification).
Lab: S1.
S2 The code is checked against the account signing in
Steps: with A and B both enrolled, sign in with A's password, then send B's current code, adding B's email address to the request if the form or API will take it.
Expected: refused; A's sign-in stays unfinished.
Evidence: the request as sent and both responses.
Basis: this matrix's advice. ASVS 6.6.2 (L2) asks the same of out-of-band requests, codes and tokens: bound to the original authentication request and not usable for a previous or subsequent one.
Lab: S2.
S3 Wrong codes are limited per account, across sessions
Steps: on A only, send wrong codes, each from a new sign-in, until your limit, then send the right code.
Expected: after the limit, the right code is refused until the owner recovers the account; the count belongs to the account, not to a session or an address.
Evidence: each response, the count reached, and how the account was unlocked afterwards.
Basis: SP 800-63B-4 3.1.4.2 (rate limiting SHALL be implemented when the authenticator output is under 64 bits) and 3.2.2 (unless an authenticator type says otherwise, no more than 100 consecutive failed attempts on one authenticator, by disabling it; 100 is an upper bound and agencies MAY set lower limits); RFC 4226 7.3 (a throttling parameter set as low as possible while usability is not significantly impacted; delay or lockout schemes MUST be across login sessions); MFA CS (strict attempt limits); WSTG-ATHN-03 (testing a lockout needs an account the tester is willing or can afford to lock). Limits across the rest of sign-in are covered in the rate limiting guide.
Lab: S3, with an example limit of 5.
S4 The second step cannot be skipped
Steps: sign in to A with the password, stop at the code prompt, and request a signed-in page and a signed-in API route directly in the same browser.
Expected: both refused until the code is accepted.
Evidence: the requests and responses.
Basis: ASVS 6.3.3 (L2: either a multi-factor authentication mechanism or a combination of single-factor mechanisms must be used to access the application; relaxing any of the considerations in the requirement requires a fully documented rationale and a comprehensive set of mitigating controls). Reading a half-finished sign-in that opens the account as falling short of it is this matrix's interpretation.
Lab: S4.
S5 Every route that issues a session asks for the factor
Steps: list every way a session or token is issued for the same accounts: the web form, a mobile app's API, an older API version, single sign-on, a magic link and the end of a password reset. Sign in to A through each with the password alone.
Expected: each route asks for the second factor, or has another protection that is documented.
Evidence: the list of routes and one response from each.
Basis: MFA CS (if an application provides multiple ways to authenticate, these should all require MFA or have other protections; a separate login API or an associated mobile app is an area that is missed; MFA downgrade mitigations include disabling legacy authentication protocols and endpoints that cannot enforce MFA consistently); ASVS 6.3.4 (L2: no undocumented authentication pathways, and controls and strength enforced consistently); ASVS 6.4.3 (L2: a password reset does not bypass enabled MFA, covered in the authentication failures guide).
Lab: S5, an older API route.
S6 The time window and the clock
Steps: read the code check; on staging, submit a code from the previous 30-second step and one from two steps back.
Expected: codes outside the window you have documented are refused, and the server uses its own clock, never a time the client sends.
Evidence: the code check and both responses.
Basis: RFC 6238 5.2 (RECOMMENDS a default time step of 30 seconds and that at most one time step is allowed as network delay; a larger delay window exposes a larger window for attacks); ASVS 6.5.5 (L2: a maximum lifetime of 30 seconds for a TOTP); ASVS 6.5.8 (L3: TOTPs checked against a time source from a trusted service, not client-provided time); SP 800-63B-4 3.1.4.2 (a TOTP SHALL have a defined lifetime based on expected clock drift plus network delay and entry time). The RFC's one earlier step and ASVS's 30-second lifetime are different limits; record which one you follow.
Lab: not checked; the careful version accepts the current step and the one before.
S7 A failure in the factor check does not open the door
Steps: on staging, make the code-checking service or library unreachable, then sign in to A.
Expected: the sign-in stops with an error; it does not finish on the password alone.
Evidence: the response and the log entry.
Basis: T1556.006 (if a fail open policy is in place, an otherwise successful authentication may be granted access without enforcing MFA; its Multi-factor Authentication mitigation, M1032, says, if possible, to consider configuring MFA solutions to fail closed rather than grant access in case of serious errors).
Lab: not covered.
S8 Codes sent by text message or voice call
Steps: if your application sends codes by text or call, look at how a phone number is added and changed, what other options are offered and what users are told; on staging, check that a code expires and works once.
Expected: changing the number is treated as adding a new factor, so E1, E4, C1 and C2 apply; a stronger option is offered; users are told the risks; the code works once and expires.
Evidence: screenshots of the settings and messages, and the responses.
Basis: SP 800-63B-4 3.1.3.3 (out-of-band authentication over the telephone network is restricted; setting or changing the pre-registered number is the binding of a new authenticator and SHALL only occur as in 4.1.2; verifiers SHALL ensure alternative authenticator types are available; verifiers SHOULD consider risk indicators such as device swap, SIM change and number porting) and 3.2.9 (a CSP accepting a restricted authenticator SHALL, among other things, offer at least one unrestricted alternative and give meaningful notice of the risks); SP 800-63B-4 3.1.3.2 (an out-of-band authentication SHALL be considered invalid unless completed within 10 minutes, and a secret accepted only once); ASVS 6.6.1 (L2: phone or SMS codes only to a previously validated number, with stronger methods also offered and risk information given; not available at L3); CISA PR (SMS or voice vulnerable to phishing, SS7 and SIM swap attacks; a last resort).
Lab: not covered.
S9 Passkeys and security keys
Steps: if your application accepts passkeys or security keys as a factor, read the server code that verifies an assertion, and register a test authenticator on staging.
Expected: the server checks the origin and the RP ID hash; where the key is meant to count as two factors, it requires user verification and checks the UV flag, and treats a response without it as one factor.
Evidence: the verification code and the registered credential's flags.
Basis: WebAuthn L3 7.2 (verify that C.origin is an origin the Relying Party expects, that the rpIdHash matches its RP ID and that the UP bit is set; where user verification is required, verify the UV bit) and 13.4.9 (the Relying Party MUST validate the origin and MUST NOT accept unexpected values); MFA CS (when passkeys are used as MFA, require user verification and validate the returned user-verification flag on the server; a touch confirming user presence alone is not a second factor); SP 800-63B-4 3.1.7.2 (if a flag shows an activation factor was not used, the authentication SHALL be treated as single-factor).
Lab: not covered.
TRANSITION 3: ENROLLED TO FACTOR ADDED, CHANGED OR REMOVED
C1 Removing or replacing a factor asks for a factor first
Steps: signed in to A, try to remove the authenticator app, replace it, or change the text-message number, without entering a current code.
Expected: refused until an existing enrolled factor is used again. After a recovery sign-in, the recovery itself can count, as it does in the lab.
Evidence: each request and response.
Basis: MFA CS, Changing MFA Factors (require reauthentication with an existing enrolled factor before allowing changes; do not rely solely on the active session, as it may be hijacked; treat factor replacement as a high-risk action); MFA CS, When to Require MFA (disabling MFA among the sensitive actions where MFA may be appropriate); ASVS 7.5.1 (L2: full reauthentication before changes to MFA configuration or other information used in account recovery). Letting a recovery sign-in count in place of an enrolled factor is this matrix's own choice, as in the lab.
Lab: C1.
C2 The owner is told, through another channel
Steps: add, replace and remove a factor on A; read every inbox and device on the account.
Expected: a notice for each change, sent somewhere other than the session that made it, with contact details for someone who did not make the change.
Evidence: each notice.
Basis: SP 800-63B-4 4.1.2.1 (SHALL notify when an authenticator is added), 4.5 (SHOULD notify when an authenticator is invalidated) and 4.6 (SHALL send to the notification addresses stored in the account and support at least two; SHALL give clear instructions, including contact information); MFA CS (notify the user through out-of-band channels such as email or push notification whenever an MFA factor is changed); ASVS 6.3.7 (L3).
Lab: C2, for removal.
C3 A replaced factor stops working
Steps: replace A's authenticator app, then send a code from the old one.
Expected: refused.
Evidence: the response.
Basis: SP 800-63B-4 3.1.4.1 (a subscriber moving a software OTP authenticator to a new device SHOULD bind the app on the new device and invalidate the one no longer used, or MAY instead export the secret key and store it in a sync fabric that meets the requirements in Appendix B.2) and 4.5 (invalidation removes the binding); ASVS 6.5.6 (L3: any authentication factor can be revoked in case of theft or other loss).
Lab: not checked; the careful version replaces the secret when a new app is confirmed.
C4 Other sessions after a factor change
Steps: sign in to A in two browsers and change the factor in one of them.
Expected: the option to end the other sessions is offered, or they end.
Evidence: the prompt and the other browser's next response.
Basis: ASVS 7.4.3 (L2). How sessions end is covered in the session management guide.
Lab: not checked; the careful version ends other sessions when the factor is removed.
TRANSITION 4: FACTOR LOST TO ACCOUNT RECOVERED
R1 A recovery code works once
Steps: sign in to A with a recovery code, then sign in again from a second browser with the same recovery code.
Expected: the second use is refused. SP 800-63B-4 describes one saved code that is replaced after use; with a set of codes, the used one is removed and the user is told how many remain (the lab's approach, and this matrix's advice).
Evidence: both responses and the notice A receives.
Basis: SP 800-63B-4 4.2.1.1 (after a saved recovery code is used, the CSP SHALL invalidate it and SHALL issue a new one) and 3.1.2.2 (a look-up secret SHALL be used successfully only once); ASVS 6.5.1 (L2); MFA CS (single-use recovery codes issued when MFA is first set up, among its suggested methods).
Lab: R1.
R2 Recovery codes are random and stored only as hashes
Steps: issue codes to A, then read how they are generated and where and how they are stored.
Expected: codes come from a secure random generator; only hashes are stored.
Evidence: the generation and storage code.
Basis: SP 800-63B-4 4.2.1.1 (a saved recovery code SHALL include at least 64 bits from an approved random bit generator and SHALL be stored in hashed form using an approved one-way function, as described in 3.1.1.2); ASVS 6.5.2 (L2: look-up secrets with less than 112 bits of entropy hashed with an approved password hashing algorithm and a 32-bit random salt; a standard hash function at 112 bits or more); ASVS 6.5.3 (L2: CSPRNG).
Lab: R2. The lab's codes are 128 random bits, hashed with SHA-256.
R3 Recovery asks for no less than sign-in
Steps: on A, start recovery as if the authenticator were lost, and note every step it requires.
Expected: recovery needs at least what sign-in needs, for example the password and a recovery code; one emailed link alone, or a secret question, is not enough.
Evidence: each step of the flow.
Basis: MFA CS, Security Questions (account recovery is an alternate way to authenticate, so it should be no weaker than regular authentication); SP 800-63B-4 4.2.2.2 (to recover an account that can authenticate at a maximum of AAL2, the CSP SHALL require two recovery codes obtained by different methods, one recovery code plus authentication with a single-factor authenticator bound to the account, or repeated identity proofing where the account was proofed); SP 800-63B-4 6.3 (informative: one factor must not be usable to obtain an authenticator of a different factor); ASVS 6.4.2 (L1: no secret questions).
Lab: not checked; recovery in the lab follows the password step.
R4 Recovery attempts are limited
Steps: on A only, send wrong recovery codes until your limit.
Expected: further attempts are refused and the owner can still get back in through support.
Evidence: each response and the count.
Basis: SP 800-63B-4 4.2.1.1 and 4.2.1.2 (verification of saved and issued recovery codes SHALL be subject to the throttling requirements in 3.2.2). Keeping a support route open after the limit is this matrix's advice. Forgot CS says, of the methods for resetting a password, that no matter what, you must ensure that a user always has a way to recover their account, even if that involves contacting the support team and proving their identity to staff.
Lab: not checked; the careful version refuses after 5 wrong recovery codes.
R5 Support-desk resets
Steps: read the support team's written process for removing a second factor, then walk through it with the team on test account A, with everyone involved aware it is a test.
Expected: a written process that verifies identity at the level used at enrolment, records who approved the reset, and tells the account owner.
Evidence: the written process, the ticket and the notice.
Basis: MFA CS (a support team with a rigorous process to verify identity, among its suggested methods); ASVS 6.4.4 (L2: if an MFA factor is lost, identity proofing is performed at the same level as during enrolment); SP 800-63B-4 4.2.1 (an application-specific method, such as interaction with a CSP agent, MAY be supported; alternative methods SHALL be based on a risk analysis and documented), 4.2.3 (in all cases, account recovery SHALL cause a notification to be sent to the subscriber or their designee) and 6.3 (informative: where recovery is human-assisted, social engineering attacks also pose risks). Recording who approved the reset is this matrix's advice.
Lab: not covered.
R6 Recovery tells the owner and clears what the lost factor left behind
Steps: complete a recovery on A while another browser holds a session and a remembered device.
Expected: a notice to the account's notification addresses; other sessions and remembered devices ended; a prompt to set up a new factor.
Evidence: the notice and the other browser's next response.
Basis: SP 800-63B-4 4.2.3 (account recovery SHALL cause a notification); Forgot CS (a reset alone may not restore control, because an attacker may still have an active session or may have changed recovery information or MFA methods; after recovering a potentially compromised account, invalidate existing sessions and outstanding recovery links or codes). Ending remembered devices and prompting for a new factor are this matrix's advice.
Lab: D3 shows the remembered device; the careful version also ends other sessions when the factor is removed.
TRANSITION 5: REMEMBERED DEVICE SKIPS THE SECOND STEP
D1 What the device cookie holds
Steps: tick remember this device on A, then read the cookie and the server's record of it.
Expected: an opaque random value, stored on the server only as a hash and tied to one account and its current factor; nothing about the account in the cookie.
Evidence: the Set-Cookie header with the value redacted, and the stored record.
Basis: this matrix's advice. SP 800-63B-4 5.1 (remember my browser features SHALL NOT be used instead of authentication, except for reauthentication at AAL2 as in 2.2.3); Auth CS (remembered-device cookies are risk signals, not substitutes for authentication; its example asks for MFA on the first sign-in from a device but not later ones).
Lab: not checked; the careful version stores a SHA-256 hash of a 32-byte random token.
D2 It expires on the server
Steps: on staging, move the clock past the device lifetime, or set a short lifetime, and sign in from the remembered browser.
Expected: the second factor is asked for again.
Evidence: the response.
Basis: this matrix's advice, following the reasoning SP 800-63B-4 5.1.1 gives for session cookies (a cookie's expiry SHALL NOT be relied on to enforce session timeouts).
Lab: not checked; the careful version stores an expiry time and checks it.
D3 It is forgotten when the factor is reset or removed
Steps: remember a browser on A; then reset the factor through recovery, remove it, or reset the password; then sign in from the remembered browser.
Expected: the second factor is asked for again.
Evidence: the responses before and after.
Basis: this matrix's advice. Forgot CS (a reset alone may not restore control, because an attacker may still have an active session or may have changed recovery information or MFA methods).
Lab: D3, for a reset through a recovery code.
D4 The owner can see and remove remembered devices
Steps: open A's account page.
Expected: a list of remembered devices, each with a remove action that takes effect on the server.
Evidence: a screenshot and a sign-in from a removed device.
Basis: this matrix's advice. The account page for sessions and devices is covered in the session management guide.
Lab: not covered.
TRANSITION 6: PUSH SENT TO APPROVED
P1 Prompts are limited
Steps: on A, with a test device, sign in with the password several times in a row without approving.
Expected: prompts stop after a set number since the last successful sign-in, and the burst is recorded.
Evidence: the number of prompts the test device received, and the log.
Basis: SP 800-63B-4 3.1.3.2 (verifiers that send push notifications SHOULD implement a reasonable limit on the rate or total number sent since the last successful authentication); ASVS 6.6.4 (L3: rate limiting to prevent push bombing; number matching may also mitigate the risk); MFA CS (rate-limit or cap push notifications); T1621 mitigation M1032 (limits on the maximum number of MFA request prompts that can be sent to users in a period of time).
Lab: not covered.
P2 Approval needs the number from the sign-in screen
Steps: sign in to A and look at the prompt on the test device.
Expected: the user types the number shown on the sign-in screen into the app; a plain Approve button, or picking the number from a short list, does not finish the sign-in.
Evidence: screenshots of the sign-in screen and the prompt.
Basis: CISA NM (number matching forces the user to enter numbers from the identity platform into their app to approve; it mitigates MFA fatigue by requiring access to the login screen and by giving each prompt a unique set of numbers); SP 800-63B-4 3.1.3 (approval by comparing secrets is no longer considered acceptable because it makes approving without comparing more likely, as observed with authentication fatigue attacks; presenting a list of secrets to compare is not sufficient) and 3.1.3.1 (an authenticator that asks for approval SHALL accept a transfer of the secret from the primary channel); T1621 mitigation M1032 (having users enter a one-time code provided by the login screen into the MFA application may be more secure).
Lab: not covered.
P3 The prompt shows what is being approved
Steps: sign in to A from a different browser and network than usual, then read the prompt.
Expected: the prompt names the application and shows where the sign-in comes from and when.
Evidence: a screenshot of the prompt.
Basis: this matrix's advice. It supports the user training in T1621 mitigation M1017 (only accept MFA requests from login attempts you initiated, review the source location of the login attempt, and report suspicious or unsolicited prompts).
Lab: not covered.
P4 Denied prompts are followed up
Steps: deny a prompt on A's test device.
Expected: the denial is logged and reaches someone who looks into it, and the owner is told the password may be known to someone else.
Evidence: the log entry, the alert and the notice.
Basis: CISA NM (investigate denied push notification requests, because MFA checks happen after the first factor, so a denial could mean the password is compromised; train users to report unknown or bulk requests); MFA CS (after a correct password and a failed second factor, notify the user of the failed attempt with its time, browser and location, and encourage a password change if they do not recognise it).
Lab: not covered.
P5 A push request expires and works once
Steps: on staging, leave a prompt unanswered past its lifetime and then approve it; approve one prompt twice.
Expected: both refused.
Evidence: the responses.
Basis: SP 800-63B-4 3.1.3.2 (invalid unless completed within 10 minutes; a secret accepted as valid only once); ASVS 6.5.5 (L2: out-of-band requests have a maximum lifetime of 10 minutes) and 6.6.2 (L2: bound to the original authentication request).
Lab: not covered.
TRANSITION 7: SIGNED IN TO A SENSITIVE ACTION
A1 A sensitive change asks for a fresh factor
Steps: signed in to A, change payout details or turn the second factor off without entering a new code.
Expected: refused until a current code, or another enrolled factor, is used for this action.
Evidence: the request and response.
Basis: MFA CS, When to Require MFA (it may be appropriate to require MFA for sensitive actions such as changing passwords or security questions, changing the email address, disabling MFA and elevating to an administrative session); ASVS 7.5.3 (L3: further authentication with at least one factor, or secondary verification, before highly sensitive transactions). Password and email changes are covered in the authentication failures guide.
Lab: A1.
A2 A remembered device or an earlier sign-in does not count
Steps: sign in to A from a remembered browser, or sign in with a code and wait a few minutes, then repeat A1.
Expected: the factor is still asked for.
Evidence: the responses.
Basis: this matrix's advice.
Lab: A1 waits one time step after a full sign-in.
A3 With an identity provider, the claims are checked
Steps: if users sign in through OpenID Connect, read how the application decides a second factor was used and how recently.
Expected: the application checks the information the provider returns, for example the acr, amr and auth_time claims where present, and has a documented fallback that assumes the weakest method when it is missing.
Evidence: the claim-checking code and its documentation.
Basis: ASVS 6.8.4 (L2). The protocol is covered in the OAuth and OIDC security guide.
Lab: not covered.
AFTER THE RUN: THE LOG
L1 Failures are logged, codes never
Steps: after S1, S3 and P1, read the log.
Expected: each code check, prompt and recovery attempt with its outcome, the account and the time, and no code, secret or recovery code in any entry.
Evidence: the log lines for the run, with anything secret redacted before you store them.
Basis: ASVS 16.3.1 (L2: all authentication operations logged, successful and unsuccessful; the type of authentication or factors used should also be collected); MFA CS (OTP implementations SHOULD NOT log OTP values); ASVS 16.2.5 (L2: logging by protection level; some data, such as credentials, may not be allowed in logs).
Lab: L1.
L2 The factor's life is on record
Steps: read the records for E1 to R6.
Expected: a record of every factor bound to the account, with the date and time of binding, renewal, update and expiry, and the IP address or device it came from.
Evidence: the records.
Basis: SP 800-63B-4 4.1 (the CSP SHALL maintain a record of all authenticators bound to each account; the record SHALL contain the date and time of significant lifecycle events and SHOULD include the source of the binding, such as IP address or device identifier).
Lab: not checked.
L3 Bursts are noticed
Steps: after S3 and P1, check what raised an alert.
Expected: an alert, or at least a record someone reviews, for repeated prompts, repeated wrong codes, and a factor change soon after a sign-in from somewhere new.
Evidence: the alert or the query used.
Basis: T1621 detection (monitor for excessive or anomalous MFA push notifications or token requests; repeated failed logins followed by MFA challenges in rapid succession); MFA CS (monitor for multiple push prompts in a short period, new-device token reuse and sudden MFA method changes). Alerting on repeated wrong codes is this matrix's own detail. Where logs go and who is alerted is covered in the security logging and monitoring guide.
Lab: not covered.
================================================================
PART 2: THE LAB FILES
================================================================
The lab is an illustration with one kind of factor: a time-based one-time password built from RFC 6238. Push prompts, text messages and passkeys are covered by the matrix and its sources, not by the lab. Make an empty folder, save the seven files below into it with the names shown, and open a terminal in that folder. The server runs in a careless version and a careful version. Each flaw in the careless version is marked FLAW with the matrix row it belongs to. The lab clock starts at Unix time 1767225600 (1 January 2026, 00:00:00 UTC) for every check and moves only when a check moves it, so every run walks through the same time steps.
================================================================
FILE 1 OF 7: otp.mjs
================================================================
// otp.mjs: one-time passwords as RFC 4226 (HOTP) and RFC 6238 (TOTP)
// describe them, built on node:crypto. Illustration only.
import { createHmac } from 'node:crypto'
// RFC 6238 section 4.1: the time step X (default 30 seconds) and the start
// time T0 (default 0, the Unix epoch).
export const TIME_STEP_SECONDS = 30
export const START_OF_COUNTING = 0
// RFC 4226 section 5.3: HMAC of the counter (an 8-byte value, section 5.1),
// dynamic truncation to 31 bits, then that number modulo 10 to the power of
// digits. Padding with leading zeros follows the Appendix C reference code.
export function hotp(key, counter, digits, algorithm) {
const counterBytes = Buffer.alloc(8)
counterBytes.writeBigUInt64BE(BigInt(counter))
const mac = createHmac(algorithm || 'sha1', key).update(counterBytes).digest()
const offset = mac[mac.length - 1] & 0x0f
const binary =
((mac[offset] & 0x7f) << 24) |
(mac[offset + 1] << 16) |
(mac[offset + 2] << 8) |
mac[offset + 3]
const code = binary % 10 ** digits
return String(code).padStart(digits, '0')
}
// RFC 6238 section 4.2: T is the number of whole time steps since T0.
export function timeStepAt(unixSeconds) {
return Math.floor((unixSeconds - START_OF_COUNTING) / TIME_STEP_SECONDS)
}
// RFC 6238: TOTP = HOTP(K, T).
export function totp(key, unixSeconds, digits, algorithm) {
return hotp(key, timeStepAt(unixSeconds), digits, algorithm)
}
================================================================
FILE 2 OF 7: check-rfc-vectors.mjs
================================================================
// check-rfc-vectors.mjs: checks otp.mjs against the published test values.
// RFC 4226 Appendix D lists ten 6-digit HOTP values for counters 0 to 9.
// RFC 6238 Appendix B lists 8-digit TOTP values; the six SHA-1 rows are
// checked here. Both use the ASCII string "12345678901234567890" as the key.
// Run: node check-rfc-vectors.mjs
import { hotp, timeStepAt, totp } from './otp.mjs'
const RFC_TEST_KEY = Buffer.from('12345678901234567890', 'ascii')
const HOTP_VALUES = ['755224', '287082', '359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']
const TOTP_SHA1_ROWS = [
{ time: 59, expected: '94287082' },
{ time: 1111111109, expected: '07081804' },
{ time: 1111111111, expected: '14050471' },
{ time: 1234567890, expected: '89005924' },
{ time: 2000000000, expected: '69279037' },
{ time: 20000000000, expected: '65353130' },
]
let mismatches = 0
function report(label, actual, expected) {
const matches = actual === expected
if (!matches) mismatches += 1
console.log(' ' + label.padEnd(42) + 'expected ' + expected.padEnd(9) + 'got ' + actual.padEnd(9) + (matches ? 'match' : 'MISMATCH'))
}
console.log('RFC 4226 Appendix D: HOTP, 6 digits')
HOTP_VALUES.forEach(function (expected, counter) {
report('counter ' + counter, hotp(RFC_TEST_KEY, counter, 6, 'sha1'), expected)
})
console.log('')
console.log('RFC 6238 Appendix B: TOTP, SHA-1, 8 digits, X = 30, T0 = 0')
for (const row of TOTP_SHA1_ROWS) {
const step = timeStepAt(row.time).toString(16).toUpperCase().padStart(16, '0')
report('time ' + row.time + ' (T = ' + step + ')', totp(RFC_TEST_KEY, row.time, 8, 'sha1'), row.expected)
}
console.log('')
console.log(mismatches === 0 ? 'All 16 values match.' : mismatches + ' values do not match.')
process.exitCode = mismatches === 0 ? 0 : 1
================================================================
FILE 3 OF 7: mfa-lab-server.mjs
================================================================
// mfa-lab-server.mjs: a small sign-in service with a time-based one-time
// password as the second factor, in a careless version and a careful version.
// Illustration only. It listens on 127.0.0.1 on a port the system picks,
// keeps everything in memory, sends no real email (messages land in an
// in-memory outbox) and reads time from a clock the caller sets, so every
// run walks through the same time steps. Secrets, recovery codes and device
// tokens are random values made in memory on each run and never printed.
import { createServer } from 'node:http'
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
import { TIME_STEP_SECONDS, timeStepAt, totp } from './otp.mjs'
export const CODE_DIGITS = 6
// Example settings for the careful version. Choose your own.
export const MAX_CODE_FAILURES = 5
export const REMEMBER_DEVICE_SECONDS = 30 * 24 * 60 * 60
export const FRESH_PROOF_SECONDS = 5 * 60
const RECOVERY_CODE_COUNT = 10
const MAX_BODY_BYTES = 10000
// Invented accounts and passwords, used only by this lab.
export const LAB_ACCOUNTS = [
{ email: 'sam@example.com', password: 'sam-lab-password-not-real' },
{ email: 'alex@example.com', password: 'alex-lab-password-not-real' },
]
// version is 'careless' or 'careful'. startSeconds fixes the lab clock.
export async function startMfaLab(version, startSeconds) {
if (version !== 'careless' && version !== 'careful') throw new Error('version must be careless or careful')
const lab = {
version: version, clock: { seconds: startSeconds }, accounts: new Map(), sessions: new Map(),
deviceTokens: new Map(), outbox: [], events: [],
}
for (const account of LAB_ACCOUNTS) lab.accounts.set(account.email, await buildAccount(account))
const handlers = version === 'careful' ? carefulHandlers : carelessHandlers
const server = createServer(function (request, response) {
routeRequest(lab, handlers, request, response).catch(function () {
sendJson(response, 400, { message: 'The request could not be read.' })
})
})
await new Promise(function (resolve) { server.listen(0, '127.0.0.1', resolve) })
lab.server = server
lab.port = server.address().port
return lab
}
export function stopMfaLab(lab) {
lab.server.closeAllConnections()
return new Promise(function (resolve) { lab.server.close(resolve) })
}
async function routeRequest(lab, handlers, request, response) {
const route = request.method + ' ' + new URL(request.url, 'http://127.0.0.1').pathname
if (!Object.hasOwn(handlers, route)) return sendJson(response, 404, { message: 'Not found.' })
const fields = request.method === 'POST' ? await readJson(request) : {}
const context = { lab: lab, fields: fields, request: request, response: response, cookies: readCookies(request) }
context.session = lab.sessions.get(context.cookies.sid) || null
context.account = context.session ? lab.accounts.get(context.session.email) : null
return handlers[route](context)
}
// ---------------------------------------------------------------------------
// The careless version. Each marked line is a flaw from the test matrix.
// ---------------------------------------------------------------------------
const carelessHandlers = {
'POST /sign-in': async function (context) {
const account = await checkPassword(context)
if (!account) return sendJson(context.response, 401, { message: 'Email address or password is incorrect.' })
const device = context.lab.deviceTokens.get(String(context.cookies.device))
// FLAW D3: a remembered device is trusted however old it is and whatever happened to the factor since.
const remembered = device && device.email === account.email
return startSession(context, account, account.factor && !remembered ? 'awaiting-code' : 'signed-in')
},
// FLAW S5: an older route still signs in with the password alone.
'POST /api/v1/session': async function (context) {
const account = await checkPassword(context)
if (!account) return sendJson(context.response, 401, { message: 'Email address or password is incorrect.' })
return startSession(context, account, 'signed-in')
},
'POST /sign-in/code': function (context) {
const session = context.session
if (!session || session.state !== 'awaiting-code') return sendJson(context.response, 401, { message: 'Sign in with your password first.' })
// FLAW S2: the code is checked against whichever account the request names.
const checkedAccount = context.lab.accounts.get(context.fields.email) || context.account
// FLAW S1 and S3: no record of used codes and no count of wrong ones.
const step = findMatchingStep(context.lab, checkedAccount, context.fields.code)
if (step === null) {
// FLAW L1: the code itself goes into the log.
recordEvent(context.lab, 'second factor failed with code ' + context.fields.code, context.account.email)
return sendJson(context.response, 401, { message: 'That code is not right.' })
}
return finishSignIn(context)
},
'POST /sign-in/recovery': function (context) {
const session = context.session
if (!session || session.state !== 'awaiting-code') return sendJson(context.response, 401, { message: 'Sign in with your password first.' })
// FLAW R1: a recovery code is never used up. FLAW R2: codes are kept as written.
if (!context.account.recoveryCodes.includes(context.fields.recovery_code)) {
return sendJson(context.response, 401, { message: 'That recovery code is not right.' })
}
session.recoveredAt = context.lab.clock.seconds
return finishSignIn(context)
},
'GET /account': function (context) {
// FLAW S4: any session counts, even one still waiting for the code.
if (!context.session) return sendJson(context.response, 401, { message: 'Sign in first.' })
return sendJson(context.response, 200, { message: 'Account page for ' + context.account.email + '.' })
},
'POST /mfa/enrol/start': function (context) {
if (!isSignedIn(context)) return sendJson(context.response, 401, { message: 'Sign in first.' })
// FLAW E1: no password check first. FLAW E2: the factor is switched on before it is confirmed.
const secret = randomBytes(20)
context.account.factor = newFactor(secret)
return sendJson(context.response, 200, { message: 'Scan the secret into your authenticator app.', secret_hex: secret.toString('hex') })
},
'POST /mfa/enrol/confirm': function (context) {
if (!isSignedIn(context) || !context.account.factor) return sendJson(context.response, 401, { message: 'Start enrolment first.' })
if (findMatchingStep(context.lab, context.account, context.fields.code) === null) {
return sendJson(context.response, 401, { message: 'That code is not right.' })
}
const codes = makeRecoveryCodes()
context.account.recoveryCodes = codes
return sendJson(context.response, 200, { message: 'Two-step sign-in is on. Keep these recovery codes somewhere safe.', recovery_codes: codes })
},
'POST /mfa/remove': function (context) {
if (!isSignedIn(context)) return sendJson(context.response, 401, { message: 'Sign in first.' })
// FLAW C1: no proof of the factor. FLAW C2: nobody is told.
context.account.factor = null
return sendJson(context.response, 200, { message: 'Two-step sign-in is off.' })
},
'POST /account/payout-details': function (context) {
if (!isSignedIn(context)) return sendJson(context.response, 401, { message: 'Sign in first.' })
// FLAW A1: the session alone is enough for a sensitive change.
return sendJson(context.response, 200, { message: 'Payout details changed.' })
},
}
// ---------------------------------------------------------------------------
// The careful version.
// ---------------------------------------------------------------------------
const carefulHandlers = {
'POST /sign-in': async function (context) {
const account = await checkPassword(context)
if (!account) return sendJson(context.response, 401, { message: 'Email address or password is incorrect.' })
const remembered = account.factor && isRememberedDevice(context.lab, account, context.cookies.device)
if (remembered) recordEvent(context.lab, 'sign-in on a remembered device', account.email)
return startSession(context, account, account.factor && !remembered ? 'awaiting-code' : 'signed-in')
},
// The older route runs the same steps as the sign-in form.
'POST /api/v1/session': function (context) {
return carefulHandlers['POST /sign-in'](context)
},
'POST /sign-in/code': function (context) {
const session = context.session
if (!session || session.state !== 'awaiting-code') return sendJson(context.response, 401, { message: 'Sign in with your password first.' })
// The code is always checked against the account this session signed in as.
const account = context.account
if (!account.factor) return sendJson(context.response, 401, { message: 'Sign in with your password first.' })
if (account.factor.locked) return sendJson(context.response, 403, { message: 'Too many wrong codes. Use a recovery code.' })
const result = useCode(context.lab, account, context.fields.code)
if (result !== 'accepted') return refuseCode(context, account, result)
account.factor.failures = 0
session.lastProofAt = context.lab.clock.seconds
if (context.fields.remember_device === true) rememberDevice(context, account)
recordEvent(context.lab, 'second factor passed', account.email)
return finishSignIn(context)
},
'POST /sign-in/recovery': function (context) {
const session = context.session
if (!session || session.state !== 'awaiting-code') return sendJson(context.response, 401, { message: 'Sign in with your password first.' })
const account = context.account
if (account.recoveryFailures >= MAX_CODE_FAILURES) {
return sendJson(context.response, 403, { message: 'Too many wrong recovery codes. Contact support.' })
}
// Stored as hashes, checked against the hash, removed the first time one works.
const position = account.recoveryCodes.indexOf(hashText(context.fields.recovery_code))
if (position === -1) {
account.recoveryFailures += 1
recordEvent(context.lab, 'recovery code refused', account.email)
return sendJson(context.response, 401, { message: 'That recovery code is not right.' })
}
account.recoveryFailures = 0
account.recoveryCodes.splice(position, 1)
session.recoveredAt = context.lab.clock.seconds
session.lastProofAt = context.lab.clock.seconds
recordEvent(context.lab, 'recovery code used', account.email)
notify(context.lab, account.email, 'A recovery code was used to sign in. ' + account.recoveryCodes.length + ' left. If this was not you, contact us.')
return finishSignIn(context)
},
'GET /account': function (context) {
if (!isSignedIn(context)) return sendJson(context.response, 401, { message: 'Finish signing in first.' })
return sendJson(context.response, 200, { message: 'Account page for ' + context.account.email + '.' })
},
'POST /mfa/enrol/start': async function (context) {
if (!isSignedIn(context)) return sendJson(context.response, 401, { message: 'Sign in first.' })
if (!(await passwordMatches(context.account, context.fields.password))) {
return sendJson(context.response, 403, { message: 'Enter your password to set up two-step sign-in.' })
}
// Kept apart until a code proves the app holds it. The live factor is untouched.
const secret = randomBytes(20)
context.account.pendingSecret = secret
return sendJson(context.response, 200, { message: 'Scan the secret into your authenticator app.', secret_hex: secret.toString('hex') })
},
'POST /mfa/enrol/confirm': function (context) {
const account = context.account
if (!isSignedIn(context) || !account.pendingSecret) return sendJson(context.response, 401, { message: 'Start enrolment first.' })
const candidate = newFactor(account.pendingSecret)
if (useCode(context.lab, { factor: candidate }, context.fields.code) !== 'accepted') {
return sendJson(context.response, 401, { message: 'That code is not right.' })
}
account.factor = candidate
account.pendingSecret = null
const codes = makeRecoveryCodes()
account.recoveryCodes = codes.map(hashText)
recordEvent(context.lab, 'factor enrolled', account.email)
notify(context.lab, account.email, 'Two-step sign-in was turned on for your account. If this was not you, contact us.')
return sendJson(context.response, 200, { message: 'Two-step sign-in is on. Keep these recovery codes somewhere safe.', recovery_codes: codes })
},
'POST /mfa/remove': function (context) {
if (!isSignedIn(context)) return sendJson(context.response, 401, { message: 'Sign in first.' })
const account = context.account
if (!hasFreshProof(context, true)) {
recordEvent(context.lab, 'factor removal refused', account.email)
return sendJson(context.response, 403, { message: 'Enter a code from your authenticator app, or sign in with a recovery code, to remove it.' })
}
account.factor = null
account.deviceGeneration += 1
endOtherSessions(context.lab, account.email, context.cookies.sid)
recordEvent(context.lab, 'factor removed', account.email)
notify(context.lab, account.email, 'Your authenticator app was removed from your account. If this was not you, contact us.')
return sendJson(context.response, 200, { message: 'Two-step sign-in is off. Remembered devices were forgotten and other sessions ended.' })
},
'POST /account/payout-details': function (context) {
if (!isSignedIn(context)) return sendJson(context.response, 401, { message: 'Sign in first.' })
if (!hasFreshProof(context, false)) {
recordEvent(context.lab, 'sensitive action refused', context.account.email)
return sendJson(context.response, 403, { message: 'Enter a code from your authenticator app to change payout details.' })
}
recordEvent(context.lab, 'payout details changed', context.account.email)
notify(context.lab, context.account.email, 'Your payout details were changed. If this was not you, contact us.')
return sendJson(context.response, 200, { message: 'Payout details changed.' })
},
}
// ---------------------------------------------------------------------------
// One-time codes, recovery codes and remembered devices.
// ---------------------------------------------------------------------------
function newFactor(secret) {
return { secret: secret, lastUsedStep: -1, failures: 0, locked: false }
}
// Accepts the current time step and the one before it (RFC 6238 section 5.2).
function findMatchingStep(lab, account, code) {
if (!account || !account.factor || !isCodeShaped(code)) return null
const current = timeStepAt(lab.clock.seconds)
for (const step of [current, current - 1]) {
const expected = totp(account.factor.secret, step * TIME_STEP_SECONDS, CODE_DIGITS)
if (timingSafeEqual(Buffer.from(expected), Buffer.from(code))) return step
}
return null
}
// The careful check: a step is accepted once, and wrong codes are counted.
function useCode(lab, account, code) {
const step = findMatchingStep(lab, account, code)
if (step === null) return 'wrong'
if (step <= account.factor.lastUsedStep) return 'already used'
account.factor.lastUsedStep = step
return 'accepted'
}
function refuseCode(context, account, result) {
account.factor.failures += 1
if (account.factor.failures >= MAX_CODE_FAILURES) account.factor.locked = true
recordEvent(context.lab, 'second factor failed: ' + result, account.email)
const message = result === 'already used' ? 'That code was already used. Wait for the next one.' : 'That code is not right.'
return sendJson(context.response, 401, { message: message })
}
// Fresh proof: a code in this request, or for factor removal, a recovery sign-in a few minutes ago.
function hasFreshProof(context, recoveryCounts) {
const session = context.session
const recoveredRecently = session.recoveredAt !== undefined && context.lab.clock.seconds - session.recoveredAt <= FRESH_PROOF_SECONDS
if (recoveryCounts && recoveredRecently) return true
return Boolean(context.account.factor) && useCode(context.lab, context.account, context.fields.code) === 'accepted'
}
function makeRecoveryCodes() {
const codes = []
for (let count = 0; count < RECOVERY_CODE_COUNT; count++) codes.push(randomBytes(16).toString('hex'))
return codes
}
// The device token is random, stored only as a hash, and tied to the
// account's current factor generation and an expiry time.
function rememberDevice(context, account) {
const token = randomBytes(32).toString('base64url')
context.lab.deviceTokens.set(hashText(token), {
email: account.email, generation: account.deviceGeneration,
expiresAt: context.lab.clock.seconds + REMEMBER_DEVICE_SECONDS,
})
context.extraCookies = ['device=' + token + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + REMEMBER_DEVICE_SECONDS]
recordEvent(context.lab, 'device remembered', account.email)
}
function isRememberedDevice(lab, account, token) {
const record = lab.deviceTokens.get(hashText(token))
if (!record || record.email !== account.email) return false
return record.generation === account.deviceGeneration && lab.clock.seconds < record.expiresAt
}
// The careless version stores the device token as written; see finishSignIn.
function rememberDeviceCarelessly(context, account) {
const token = randomBytes(32).toString('base64url')
context.lab.deviceTokens.set(token, { email: account.email })
context.extraCookies = ['device=' + token + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + REMEMBER_DEVICE_SECONDS]
}
// ---------------------------------------------------------------------------
// Passwords, sessions, notices and the event log.
// ---------------------------------------------------------------------------
async function buildAccount(account) {
const salt = randomBytes(16)
return {
email: account.email, salt: salt, passwordHash: await hashPassword(account.password, salt),
factor: null, pendingSecret: null, recoveryCodes: [], recoveryFailures: 0, deviceGeneration: 0,
}
}
function hashPassword(password, salt) {
return new Promise(function (resolve, reject) {
scrypt(String(password || ''), salt, 32, function (error, key) {
if (error) reject(error)
else resolve(key)
})
})
}
async function passwordMatches(account, password) {
return timingSafeEqual(await hashPassword(password, account.salt), account.passwordHash)
}
async function checkPassword(context) {
const account = context.lab.accounts.get(String(context.fields.email || ''))
if (!account || !(await passwordMatches(account, context.fields.password))) return null
return account
}
function startSession(context, account, state) {
const sessionId = randomBytes(32).toString('base64url')
context.lab.sessions.set(sessionId, { email: account.email, state: state })
const cookie = 'sid=' + sessionId + '; Path=/; HttpOnly; SameSite=Lax'
if (state === 'awaiting-code') return sendJson(context.response, 202, { message: 'Enter the code from your authenticator app.' }, [cookie])
return sendJson(context.response, 200, { message: 'Signed in.' }, [cookie])
}
function finishSignIn(context) {
context.session.state = 'signed-in'
if (context.lab.version === 'careless' && context.fields.remember_device === true) rememberDeviceCarelessly(context, context.account)
return sendJson(context.response, 200, { message: 'Signed in.' }, context.extraCookies)
}
function isSignedIn(context) {
return Boolean(context.session) && context.session.state === 'signed-in'
}
function endOtherSessions(lab, email, keepSessionId) {
for (const entry of lab.sessions) {
if (entry[1].email === email && entry[0] !== keepSessionId) lab.sessions.delete(entry[0])
}
}
function notify(lab, email, text) {
lab.outbox.push({ to: email, text: text })
}
// What happened, to which account and when. Codes and secrets never go in.
function recordEvent(lab, event, email) {
lab.events.push({ at: new Date(lab.clock.seconds * 1000).toISOString(), event: event, email: email })
}
function hashText(text) {
return createHash('sha256').update(String(text || '')).digest('hex')
}
function isCodeShaped(code) {
return typeof code === 'string' && code.length === CODE_DIGITS && /^[0-9]+$/.test(code)
}
function readCookies(request) {
const cookies = {}
for (const pair of String(request.headers.cookie || '').split('; ')) {
const at = pair.indexOf('=')
if (at > 0) cookies[pair.slice(0, at)] = pair.slice(at + 1)
}
return cookies
}
function readJson(request) {
return new Promise(function (resolve, reject) {
const chunks = []
let size = 0
request.on('data', function (chunk) {
size += chunk.length
if (size > MAX_BODY_BYTES) reject(new Error('body too large'))
else chunks.push(chunk)
})
request.on('end', function () {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'))
} catch (error) {
reject(error)
}
})
})
}
function sendJson(response, status, body, cookies) {
const headers = { 'Content-Type': 'application/json' }
if (cookies && cookies.length) headers['Set-Cookie'] = cookies
response.writeHead(status, headers)
response.end(JSON.stringify(body))
}
================================================================
FILE 4 OF 7: lab-client.mjs
================================================================
// lab-client.mjs: sends requests to the lab server on 127.0.0.1 the way a
// browser would, keeping each browser's cookies, and acts as the user's
// authenticator app by computing codes from the secret it was shown.
import { request as httpRequest } from 'node:http'
import { totp } from './otp.mjs'
import { CODE_DIGITS } from './mfa-lab-server.mjs'
// A browser is a cookie jar: { sid, device }.
export function newBrowser() {
return {}
}
export function send(lab, browser, method, path, fields) {
const body = fields ? JSON.stringify(fields) : ''
const headers = { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }
const cookieHeader = Object.keys(browser).map(function (name) { return name + '=' + browser[name] }).join('; ')
if (cookieHeader) headers.Cookie = cookieHeader
const options = { host: '127.0.0.1', port: lab.port, method: method, path: path, headers: headers }
return new Promise(function (resolve, reject) {
const outgoing = httpRequest(options, function (response) {
const chunks = []
response.on('data', function (chunk) { chunks.push(chunk) })
response.on('end', function () {
keepCookies(browser, response.headers['set-cookie'] || [])
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'))
resolve({ status: response.statusCode, message: parsed.message, body: parsed })
})
})
outgoing.on('error', reject)
outgoing.end(body)
})
}
function keepCookies(browser, setCookieHeaders) {
for (const header of setCookieHeaders) {
const pair = header.split(';')[0]
const at = pair.indexOf('=')
browser[pair.slice(0, at)] = pair.slice(at + 1)
}
}
// The code the user's authenticator app shows at the lab clock's current time.
export function currentCode(lab, secret) {
return totp(secret, lab.clock.seconds, CODE_DIGITS)
}
// Moves the lab clock on to the next 30-second time step.
export function nextTimeStep(lab) {
lab.clock.seconds += 30
}
// One line of evidence: status and message.
export function describe(answer) {
return answer.status + ' ' + answer.message
}
================================================================
FILE 5 OF 7: mfa-checks.mjs
================================================================
// mfa-checks.mjs: the matrix rows the lab can show, written once and shared
// by the runner and the regression test. Each check starts a fresh lab with
// the clock fixed at LAB_START_SECONDS and returns whether the expected
// behaviour held, with one line of evidence.
import { LAB_ACCOUNTS, startMfaLab, stopMfaLab } from './mfa-lab-server.mjs'
import { currentCode, describe, newBrowser, nextTimeStep, send } from './lab-client.mjs'
// 1 January 2026 00:00:00 UTC, as Unix time.
export const LAB_START_SECONDS = 1767225600
const SAM = LAB_ACCOUNTS[0]
const ALEX = LAB_ACCOUNTS[1]
export async function runCheck(version, check) {
const lab = await startMfaLab(version, LAB_START_SECONDS)
try {
return await check.run(lab)
} finally {
await stopMfaLab(lab)
}
}
// Signs in with the password alone, turns on the authenticator app and
// confirms it with a code, as a user would. Returns what the user was shown.
async function enrol(lab, user) {
const browser = newBrowser()
await send(lab, browser, 'POST', '/sign-in', { email: user.email, password: user.password })
const started = await send(lab, browser, 'POST', '/mfa/enrol/start', { password: user.password })
const secret = Buffer.from(started.body.secret_hex, 'hex')
const confirmed = await send(lab, browser, 'POST', '/mfa/enrol/confirm', { code: currentCode(lab, secret) })
nextTimeStep(lab)
return { secret: secret, recoveryCodes: confirmed.body.recovery_codes }
}
async function signInWithCode(lab, user, secret, extraFields) {
const browser = newBrowser()
const password = await send(lab, browser, 'POST', '/sign-in', { email: user.email, password: user.password })
const fields = Object.assign({ code: currentCode(lab, secret) }, extraFields || {})
const code = await send(lab, browser, 'POST', '/sign-in/code', fields)
return { browser: browser, password: password, code: code }
}
function wrongCodeFor(lab, secret) {
const right = Number(currentCode(lab, secret))
return String((right + 500000) % 1000000).padStart(6, '0')
}
export const CHECKS = [
{
row: 'BASE', title: 'password and the right code sign in',
run: async function (lab) {
const sam = await enrol(lab, SAM)
const signIn = await signInWithCode(lab, SAM, sam.secret)
const page = await send(lab, signIn.browser, 'GET', '/account')
return { held: signIn.code.status === 200 && page.status === 200, evidence: 'code: ' + describe(signIn.code) + ' | account page: ' + page.status }
},
},
{
row: 'E1', title: 'starting enrolment asks for the password again',
run: async function (lab) {
const browser = newBrowser()
await send(lab, browser, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
const started = await send(lab, browser, 'POST', '/mfa/enrol/start', {})
return { held: started.status === 403, evidence: 'start with no password: ' + describe(started) }
},
},
{
row: 'E2', title: 'an enrolment never confirmed changes nothing',
run: async function (lab) {
const browser = newBrowser()
await send(lab, browser, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
await send(lab, browser, 'POST', '/mfa/enrol/start', { password: SAM.password })
const nextSignIn = await send(lab, newBrowser(), 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
return { held: nextSignIn.status === 200, evidence: 'enrolment started, not confirmed; next sign-in: ' + describe(nextSignIn) }
},
},
{
row: 'S1', title: 'a code is accepted once',
run: async function (lab) {
const sam = await enrol(lab, SAM)
const first = await signInWithCode(lab, SAM, sam.secret)
const second = await signInWithCode(lab, SAM, sam.secret)
return { held: second.code.status !== 200, evidence: 'first use: ' + first.code.status + ' | same code, new sign-in: ' + describe(second.code) }
},
},
{
row: 'S2', title: "only the signing-in account's code completes the sign-in",
run: async function (lab) {
await enrol(lab, SAM)
const alex = await enrol(lab, ALEX)
const browser = newBrowser()
await send(lab, browser, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
const answer = await send(lab, browser, 'POST', '/sign-in/code', { email: ALEX.email, code: currentCode(lab, alex.secret) })
const page = await send(lab, browser, 'GET', '/account')
return { held: page.status !== 200, evidence: "sam's password, alex's code: " + describe(answer) + ' | account page: ' + describe(page) }
},
},
{
row: 'S3', title: 'wrong codes are limited per account',
run: async function (lab) {
const sam = await enrol(lab, SAM)
const statuses = []
for (let attempt = 0; attempt < 5; attempt++) {
const browser = newBrowser()
await send(lab, browser, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
const wrong = await send(lab, browser, 'POST', '/sign-in/code', { code: wrongCodeFor(lab, sam.secret) })
statuses.push(wrong.status)
}
const right = await signInWithCode(lab, SAM, sam.secret)
return { held: right.code.status !== 200, evidence: '5 wrong codes, each from a new sign-in: ' + statuses.join(' ') + ' | then the right code: ' + describe(right.code) }
},
},
{
row: 'S4', title: 'a half-finished sign-in cannot open a signed-in page',
run: async function (lab) {
await enrol(lab, SAM)
const browser = newBrowser()
const password = await send(lab, browser, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
const page = await send(lab, browser, 'GET', '/account')
return { held: page.status === 401, evidence: 'password: ' + password.status + ' | account page with no code: ' + describe(page) }
},
},
{
row: 'S5', title: 'the older sign-in route asks for the code too',
run: async function (lab) {
await enrol(lab, SAM)
const browser = newBrowser()
const older = await send(lab, browser, 'POST', '/api/v1/session', { email: SAM.email, password: SAM.password })
const page = await send(lab, browser, 'GET', '/account')
return { held: page.status !== 200, evidence: '/api/v1/session: ' + describe(older) + ' | account page: ' + page.status }
},
},
{
row: 'C1', title: 'removing the factor asks for a current code',
run: async function (lab) {
const sam = await enrol(lab, SAM)
const signIn = await signInWithCode(lab, SAM, sam.secret)
nextTimeStep(lab)
const removed = await send(lab, signIn.browser, 'POST', '/mfa/remove', {})
return { held: removed.status === 403, evidence: 'remove with no code: ' + describe(removed) }
},
},
{
row: 'C2', title: 'the owner is told when the factor is removed',
run: async function (lab) {
const sam = await enrol(lab, SAM)
const signIn = await signInWithCode(lab, SAM, sam.secret)
nextTimeStep(lab)
const removed = await send(lab, signIn.browser, 'POST', '/mfa/remove', { code: currentCode(lab, sam.secret) })
const notices = lab.outbox.filter(function (message) { return message.to === SAM.email && message.text.includes('removed') })
return { held: removed.status === 200 && notices.length === 1, evidence: 'remove with a current code: ' + removed.status + ' | removal notices to sam: ' + notices.length }
},
},
{
row: 'R1', title: 'a recovery code works once',
run: async function (lab) {
const sam = await enrol(lab, SAM)
const recoveryCode = sam.recoveryCodes[0]
const answers = []
for (let attempt = 0; attempt < 2; attempt++) {
const browser = newBrowser()
await send(lab, browser, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
answers.push(await send(lab, browser, 'POST', '/sign-in/recovery', { recovery_code: recoveryCode }))
}
return { held: answers[1].status !== 200, evidence: 'first use: ' + answers[0].status + ' | same recovery code again: ' + describe(answers[1]) }
},
},
{
row: 'R2', title: 'recovery codes are stored only as hashes',
run: async function (lab) {
const sam = await enrol(lab, SAM)
const stored = lab.accounts.get(SAM.email).recoveryCodes
const asWritten = sam.recoveryCodes.filter(function (code) { return stored.includes(code) })
return { held: asWritten.length === 0, evidence: 'codes issued: ' + sam.recoveryCodes.length + ' | found as written in storage: ' + asWritten.length }
},
},
{
row: 'D3', title: 'a remembered device is forgotten when the factor is reset',
run: async function (lab) {
const sam = await enrol(lab, SAM)
// The device to be remembered signs in with a code and ticks "remember".
const device = (await signInWithCode(lab, SAM, sam.secret, { remember_device: true })).browser
const before = await send(lab, device, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
// Sam loses the phone: a recovery code, remove the old app, set up a new one.
nextTimeStep(lab)
const browser = newBrowser()
await send(lab, browser, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
await send(lab, browser, 'POST', '/sign-in/recovery', { recovery_code: sam.recoveryCodes[0] })
await send(lab, browser, 'POST', '/mfa/remove', {})
const started = await send(lab, browser, 'POST', '/mfa/enrol/start', { password: SAM.password })
await send(lab, browser, 'POST', '/mfa/enrol/confirm', { code: currentCode(lab, Buffer.from(started.body.secret_hex, 'hex')) })
nextTimeStep(lab)
const after = await send(lab, device, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
return { held: after.status === 202, evidence: 'remembered device before the reset: ' + describe(before) + ' | after the reset: ' + describe(after) }
},
},
{
row: 'A1', title: 'a sensitive change asks for a fresh code',
run: async function (lab) {
const sam = await enrol(lab, SAM)
const signIn = await signInWithCode(lab, SAM, sam.secret)
nextTimeStep(lab)
const change = await send(lab, signIn.browser, 'POST', '/account/payout-details', { account_name: 'lab payout account' })
return { held: change.status === 403, evidence: 'payout change with no code: ' + describe(change) }
},
},
{
row: 'L1', title: 'a wrong code is logged, without the code',
run: async function (lab) {
const sam = await enrol(lab, SAM)
const browser = newBrowser()
await send(lab, browser, 'POST', '/sign-in', { email: SAM.email, password: SAM.password })
const wrongCode = wrongCodeFor(lab, sam.secret)
await send(lab, browser, 'POST', '/sign-in/code', { code: wrongCode })
const failures = lab.events.filter(function (entry) { return entry.email === SAM.email && entry.event.startsWith('second factor failed') })
const codeInLog = JSON.stringify(lab.events).includes(wrongCode)
return { held: failures.length === 1 && !codeInLog, evidence: 'failure events for sam: ' + failures.length + ' | the code appears in the log: ' + (codeInLog ? 'yes' : 'no') }
},
},
]
================================================================
FILE 6 OF 7: run-matrix.mjs
================================================================
// run-matrix.mjs: runs every check against the careless version and then
// the careful version, and prints one result per matrix row.
// Run: node run-matrix.mjs
import { CHECKS, LAB_START_SECONDS, runCheck } from './mfa-checks.mjs'
async function runVersion(version) {
console.log(version.toUpperCase() + ' VERSION')
let heldCount = 0
for (const check of CHECKS) {
const result = await runCheck(version, check)
if (result.held) heldCount += 1
const label = check.row.padEnd(6) + check.title + ' '
console.log(' ' + label.padEnd(64, '.') + ' ' + (result.held ? 'held' : 'FLAW'))
console.log(' ' + result.evidence)
}
console.log(' Held: ' + heldCount + ' of ' + CHECKS.length)
console.log('')
}
console.log('Node.js ' + process.version + '. Lab clock fixed at ' + LAB_START_SECONDS + ' (' + new Date(LAB_START_SECONDS * 1000).toISOString() + ') at the start of every check.')
console.log('')
await runVersion('careless')
await runVersion('careful')
================================================================
FILE 7 OF 7: mfa-checks.test.mjs
================================================================
// mfa-checks.test.mjs: the same checks as a regression test using the
// node:test module. Each test fails with the check's evidence line.
// Run: node mfa-checks.test.mjs (careful version: every test passes)
// node mfa-checks.test.mjs careless (careless version: all but BASE fail)
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { CHECKS, runCheck } from './mfa-checks.mjs'
const version = process.argv[2] || 'careful'
for (const check of CHECKS) {
test(check.row + ' ' + check.title, async function () {
const result = await runCheck(version, check)
assert.ok(result.held, result.evidence)
})
}
================================================================
PART 3: THE CODE GENERATOR AGAINST THE RFC TEST VALUES
================================================================
Command: node check-rfc-vectors.mjs
RFC 4226 Appendix D: HOTP, 6 digits
counter 0 expected 755224 got 755224 match
counter 1 expected 287082 got 287082 match
counter 2 expected 359152 got 359152 match
counter 3 expected 969429 got 969429 match
counter 4 expected 338314 got 338314 match
counter 5 expected 254676 got 254676 match
counter 6 expected 287922 got 287922 match
counter 7 expected 162583 got 162583 match
counter 8 expected 399871 got 399871 match
counter 9 expected 520489 got 520489 match
RFC 6238 Appendix B: TOTP, SHA-1, 8 digits, X = 30, T0 = 0
time 59 (T = 0000000000000001) expected 94287082 got 94287082 match
time 1111111109 (T = 00000000023523EC) expected 07081804 got 07081804 match
time 1111111111 (T = 00000000023523ED) expected 14050471 got 14050471 match
time 1234567890 (T = 000000000273EF07) expected 89005924 got 89005924 match
time 2000000000 (T = 0000000003F940AA) expected 69279037 got 69279037 match
time 20000000000 (T = 0000000027BC86AA) expected 65353130 got 65353130 match
All 16 values match.
The process exits with code 0.
================================================================
PART 4: THE MATRIX ROWS THE LAB CAN SHOW
================================================================
Command: node run-matrix.mjs
Node.js v26.0.0. Lab clock fixed at 1767225600 (2026-01-01T00:00:00.000Z) at the start of every check.
CARELESS VERSION
BASE password and the right code sign in ...................... held
code: 200 Signed in. | account page: 200
E1 starting enrolment asks for the password again ........... FLAW
start with no password: 200 Scan the secret into your authenticator app.
E2 an enrolment never confirmed changes nothing ............. FLAW
enrolment started, not confirmed; next sign-in: 202 Enter the code from your authenticator app.
S1 a code is accepted once .................................. FLAW
first use: 200 | same code, new sign-in: 200 Signed in.
S2 only the signing-in account's code completes the sign-in . FLAW
sam's password, alex's code: 200 Signed in. | account page: 200 Account page for sam@example.com.
S3 wrong codes are limited per account ...................... FLAW
5 wrong codes, each from a new sign-in: 401 401 401 401 401 | then the right code: 200 Signed in.
S4 a half-finished sign-in cannot open a signed-in page ..... FLAW
password: 202 | account page with no code: 200 Account page for sam@example.com.
S5 the older sign-in route asks for the code too ............ FLAW
/api/v1/session: 200 Signed in. | account page: 200
C1 removing the factor asks for a current code .............. FLAW
remove with no code: 200 Two-step sign-in is off.
C2 the owner is told when the factor is removed ............. FLAW
remove with a current code: 200 | removal notices to sam: 0
R1 a recovery code works once ............................... FLAW
first use: 200 | same recovery code again: 200 Signed in.
R2 recovery codes are stored only as hashes ................. FLAW
codes issued: 10 | found as written in storage: 10
D3 a remembered device is forgotten when the factor is reset FLAW
remembered device before the reset: 200 Signed in. | after the reset: 200 Signed in.
A1 a sensitive change asks for a fresh code ................. FLAW
payout change with no code: 200 Payout details changed.
L1 a wrong code is logged, without the code ................. FLAW
failure events for sam: 1 | the code appears in the log: yes
Held: 1 of 15
CAREFUL VERSION
BASE password and the right code sign in ...................... held
code: 200 Signed in. | account page: 200
E1 starting enrolment asks for the password again ........... held
start with no password: 403 Enter your password to set up two-step sign-in.
E2 an enrolment never confirmed changes nothing ............. held
enrolment started, not confirmed; next sign-in: 200 Signed in.
S1 a code is accepted once .................................. held
first use: 200 | same code, new sign-in: 401 That code was already used. Wait for the next one.
S2 only the signing-in account's code completes the sign-in . held
sam's password, alex's code: 401 That code is not right. | account page: 401 Finish signing in first.
S3 wrong codes are limited per account ...................... held
5 wrong codes, each from a new sign-in: 401 401 401 401 401 | then the right code: 403 Too many wrong codes. Use a recovery code.
S4 a half-finished sign-in cannot open a signed-in page ..... held
password: 202 | account page with no code: 401 Finish signing in first.
S5 the older sign-in route asks for the code too ............ held
/api/v1/session: 202 Enter the code from your authenticator app. | account page: 401
C1 removing the factor asks for a current code .............. held
remove with no code: 403 Enter a code from your authenticator app, or sign in with a recovery code, to remove it.
C2 the owner is told when the factor is removed ............. held
remove with a current code: 200 | removal notices to sam: 1
R1 a recovery code works once ............................... held
first use: 200 | same recovery code again: 401 That recovery code is not right.
R2 recovery codes are stored only as hashes ................. held
codes issued: 10 | found as written in storage: 0
D3 a remembered device is forgotten when the factor is reset held
remembered device before the reset: 200 Signed in. | after the reset: 202 Enter the code from your authenticator app.
A1 a sensitive change asks for a fresh code ................. held
payout change with no code: 403 Enter a code from your authenticator app to change payout details.
L1 a wrong code is logged, without the code ................. held
failure events for sam: 1 | the code appears in the log: no
Held: 15 of 15
Reading the run:
Careless Only the baseline check held: the right password and code signed in. Every other row showed its flaw: enrolment started without the password and switched the factor on before it was confirmed; a code worked twice; another account's code finished Sam's sign-in; five wrong codes from five sign-ins changed nothing; the account page opened before the code; the older API route signed in on the password; the factor was removed with no code and nobody was told; a recovery code worked twice; recovery codes sat in storage as written; a device remembered before the reset still skipped the code after it; payout details changed on the session alone; and the wrong code went into the log.
Careful All fifteen checks held. A 403 means something must be given first: the password, a current code, or, after too many wrong codes, a recovery code. A 401 means a code or recovery code was wrong or already used, or the sign-in was not finished. The 202 after the reset means the remembered device no longer skipped the code.
================================================================
PART 5: THE REGRESSION TEST
================================================================
Command: node mfa-checks.test.mjs
✔ BASE password and the right code sign in (145.69475ms)
✔ E1 starting enrolment asks for the password again (107.12225ms)
✔ E2 an enrolment never confirmed changes nothing (134.38925ms)
✔ S1 a code is accepted once (153.050917ms)
✔ S2 only the signing-in account's code completes the sign-in (186.096709ms)
✔ S3 wrong codes are limited per account (264.015709ms)
✔ S4 a half-finished sign-in cannot open a signed-in page (130.994125ms)
✔ S5 the older sign-in route asks for the code too (124.749542ms)
✔ C1 removing the factor asks for a current code (132.67425ms)
✔ C2 the owner is told when the factor is removed (125.302166ms)
✔ R1 a recovery code works once (150.661666ms)
✔ R2 recovery codes are stored only as hashes (103.903375ms)
✔ D3 a remembered device is forgotten when the factor is reset (225.985375ms)
✔ A1 a sensitive change asks for a fresh code (125.14425ms)
✔ L1 a wrong code is logged, without the code (125.3845ms)
ℹ tests 15
ℹ suites 0
ℹ pass 15
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2238.640833
The process exits with code 0.
Command: node mfa-checks.test.mjs careless
✔ BASE password and the right code sign in (115.490125ms)
✖ E1 starting enrolment asks for the password again (76.241458ms)
✖ E2 an enrolment never confirmed changes nothing (101.609208ms)
✖ S1 a code is accepted once (126.199959ms)
✖ S2 only the signing-in account's code completes the sign-in (129.372917ms)
✖ S3 wrong codes are limited per account (231.666208ms)
✖ S4 a half-finished sign-in cannot open a signed-in page (103.847458ms)
✖ S5 the older sign-in route asks for the code too (101.3045ms)
✖ C1 removing the factor asks for a current code (101.933959ms)
✖ C2 the owner is told when the factor is removed (99.827083ms)
✖ R1 a recovery code works once (128.424667ms)
✖ R2 recovery codes are stored only as hashes (78.559542ms)
✖ D3 a remembered device is forgotten when the factor is reset (180.687667ms)
✖ A1 a sensitive change asks for a fresh code (99.150667ms)
✖ L1 a wrong code is logged, without the code (103.866333ms)
ℹ tests 15
ℹ suites 0
ℹ pass 1
ℹ fail 14
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1781.351708
✖ failing tests:
test at mfa-checks.test.mjs:12:3
✖ E1 starting enrolment asks for the password again (76.241458ms)
AssertionError [ERR_ASSERTION]: start with no password: 200 Scan the secret into your authenticator app.
(stack trace and error object removed here)
test at mfa-checks.test.mjs:12:3
✖ E2 an enrolment never confirmed changes nothing (101.609208ms)
AssertionError [ERR_ASSERTION]: enrolment started, not confirmed; next sign-in: 202 Enter the code from your authenticator app.
(stack trace and error object removed here)
(12 more failure blocks of the same form are left out here.)
The process exits with code 1. A pipeline step that treats a non-zero exit code as a failure then fails.
================================================================
PART 6: POINT THE CHECKS AT YOUR OWN APPLICATION
================================================================
1. Copy mfa-checks.mjs, lab-client.mjs and otp.mjs into your project's tests.
2. Replace startMfaLab with your application started on a test port with seeded test accounts, and change the paths and field names to your own.
3. Give the tests a clock. Have your code check read the time through one function a test can replace; without that, run each check that computes a code within a single 30-second step.
4. Replace lab.outbox with your test mail transport, lab.events with your test log output, and the storage read in R2 with a query against your test database.
5. Run the tests in the pipeline that deploys the application, and only against staging or a local copy with test accounts, never against real customers' accounts.What MFA bypass means
Multi-factor authentication asks for proof of two different kinds before it lets someone in.
OWASP's Multifactor Authentication Cheat Sheet defines it as evidence from at least two distinct authentication factors: something you know, something you have and something you are. It says requiring two instances of the same factor, such as a password and a PIN, does not constitute MFA, and that the factors should be independent of each other and not able to be compromised by the same attack.
Location and other risk signals can inform the decision, the cheat sheet adds, but do not substitute for a factor.
NIST SP 800-63B-4 says the same of fraud indicators such as an unexpected geolocation: using them does not change the assurance level of a sign-in or substitute for an authentication factor.
What the second factor adds is a limit on what a stolen password is worth. CISA's fact sheet on phishing-resistant MFA, dated October 2022, puts it this way: with MFA enabled, if one factor, such as a password, becomes compromised, unauthorised users will be unable to access the account if they cannot also provide the second factor.
The same fact sheet says not all forms of MFA are equally secure, and that attacks on some forms, through phishing, push bombing, SS7 protocol vulnerabilities or SIM swaps, may let a threat actor gain access to MFA credentials or bypass MFA.
In this guide, MFA bypass means getting into an account that has a second factor without that factor being checked at the moment it matters. It happens in two ways. The factor can be beaten at sign-in: a code relayed through a fake sign-in page, a push prompt approved to make the prompts stop, a text message intercepted, a short code guessed.
Or the factor can be gone around: enrolled by the wrong person, reset through a recovery path weaker than sign-in, skipped by a remembered device, never asked for on an older route, or shown on a page the server does not wait for.
The OWASP cheat sheet says attackers increasingly target weaknesses in MFA deployments and authentication workflows rather than attempting to defeat MFA itself. Every item in both lists has a row in the test matrix on this page.
Neighbouring subjects each have a guide of their own. The authentication failures guide covers sign-up, password sign-in and password reset, including a reset that skips the second factor. The credential stuffing guide covers what a second factor changes when passwords leaked from other sites are replayed.
The session management guide covers the session issued once sign-in finishes, including timeouts and signing out everywhere. The rate limiting guide covers how many attempts each sign-in step allows. The security logging and monitoring guide covers where authentication events are stored and who is alerted.
Phishing and MFA: codes that can be relayed, and factors that cannot
The difference that matters most between second factors is whether a fake sign-in page can pass them on.
NIST SP 800-63B-4, published in July 2025 and focused on authentication to government information systems, defines phishing resistance as the ability of the authentication protocol to prevent the disclosure of authentication secrets and valid authenticator outputs to an impostor verifier without relying on the vigilance of the claimant.
Section 3.2.5 says phishing resistance requires cryptographic authentication, and that authenticators whose output the user types in, such as out-of-band and one-time password authenticators, SHALL NOT be considered phishing-resistant, because typing it in does not bind the output to the specific session being authenticated.
Its example: an impostor verifier could relay an authenticator output to the verifier and successfully authenticate. NIST section 3.1.2 says look-up secrets are not phishing-resistant either, and that a typical application of them is for one-time saved recovery codes.
CISA's phishing-resistant MFA fact sheet gives the everyday version: a user visits a threat actor-controlled site that mimics a company's login portal and submits their username, password and the 6-digit code from their authenticator app. What is taken can be more than the code.
MITRE ATT&CK technique T1539, Steal Web Session Cookie, says session cookies can be used to bypass some multi-factor authentication protocols, and that open source frameworks can gather session cookies through a malicious proxy set up for phishing campaigns.
The OWASP cheat sheet calls this real-time phishing using reverse proxies, and gives two mitigations: monitor for anomalous authentication and session activity, such as impossible travel, a new ASN or sudden MFA method changes, and use phishing-resistant authenticators.
Phishing-resistant factors tie the response to the connection or to the site's name. NIST recognises two methods, channel binding and verifier name binding, and gives WebAuthn, used by authenticators that implement the FIDO2 specifications, as an example of a standard that provides phishing resistance through verifier name binding, by choosing an authenticator secret based on the authenticated domain name of the verifier.
The W3C's Web Authentication Level 3, a W3C Recommendation dated 25 August 2026, defines public key credentials each scoped to a given relying party.
Its section 13.4.9 says the relying party MUST validate the origin in the client data and MUST NOT accept unexpected values. It adds that this origin check is an additional layer of protection in case a faulty authenticator fails to enforce credential scope.
In the specification's terminology, passkey is another name for a discoverable credential, and its use cases describe phishing-resistant sign-in with multi-device credentials, commonly referred to as synced passkeys. CISA's October 2022 fact sheet called FIDO/WebAuthn the only widely available phishing-resistant authentication.
A passkey or security key counts as two factors only when the person was verified on the device. The OWASP cheat sheet says that when passkeys are used as MFA, the application should require user verification and validate the returned user-verification flag on the server, and that a touch confirming user presence alone is not a second factor.
NIST section 3.1.7.2 says that if a multi-factor cryptographic authenticator's flag shows an activation factor was not used, the authentication SHALL be treated as single-factor.
The standards differ in how hard they push. NIST section 2.2.2 says verifiers SHALL offer at least one phishing-resistant authentication option at AAL2 and SHOULD encourage its use whenever practical. ASVS 5.0 requirement 6.3.3, at Level 2, asks that a multi-factor mechanism or a combination of single-factor mechanisms is used to access the application, and at Level 3 that one of the factors is a hardware-based mechanism which provides compromise and impersonation resistance against phishing while verifying the intent to authenticate through a user-initiated action.
Its last sentence says relaxing any of the considerations in the requirement requires a fully documented rationale and a comprehensive set of mitigating controls.
The OWASP cheat sheet and CISA both say any MFA is better than no MFA. A one-time code still stops a password from being enough on its own. It does not stop a fake sign-in page that passes the code on.
MFA bypass techniques a defender should recognise
A strong factor can still be skipped.
The first four weaknesses below belong to the application rather than to the factor, and the last belongs to the factor itself. Each maps to rows in the test matrix, and the lab shows several of them in a careless and a careful version.
Where a sign-in with an authenticator app is two requests, the password and then the code, the flaw sits between them. If the password step already creates a session the rest of the application accepts, the code prompt is only a page, and a request straight to a signed-in address skips it.
The careless lab version treats any session as signed in, so its account page opened with no code at all. The careful version records how far each session has got and refuses every signed-in route until the code is accepted.
ASVS 5.0 requirement 6.3.3, at Level 2, asks that a multi-factor mechanism, or a combination of single-factor mechanisms, must be used to access the application, and says relaxing any of the considerations in the requirement requires a fully documented rationale and a comprehensive set of mitigating controls. This page reads a half-finished sign-in that opens the account as falling short of it.
The second request has a weakness of its own. The code has to be checked against the account that gave the right password, as the server recorded it, never against an account the request names. In the careless lab version, a request carrying Sam's half-finished sign-in and Alex's current code finished Sam's sign-in.
ASVS requirement 6.6.2, at Level 2, asks for that binding for out-of-band requests, codes and tokens: bound to the original authentication request, and not usable for a previous or subsequent one.
The OWASP cheat sheet describes MFA downgrade attacks, which try to force authentication through legacy protocols or flows that do not enforce the same MFA requirements. Its mitigations include disabling legacy authentication protocols and endpoints that cannot enforce MFA consistently, and preventing fallback from phishing-resistant authenticators to lower-assurance methods unless a documented security policy requires it.
ASVS 5.0 requirement 6.3.4, at Level 2, asks that there are no undocumented authentication pathways and that controls and authentication strength are enforced consistently across them.
The careless lab version keeps an older API route that issues a session on the password alone. A password reset that ends with the user signed in leaves the same gap; the authentication failures guide covers it.
A one-time password is only one-time if the server remembers it was used. RFC 6238, the TOTP specification, says the verifier MUST NOT accept the second attempt of an OTP after the successful validation of the first, and NIST section 3.1.4.2 says verifiers SHALL accept a given OTP only once while it is valid.
ASVS 5.0 requirement 6.5.1, at Level 2, asks the same of TOTPs, look-up secrets and out-of-band codes. The careful lab version stores the last time step each account used and refuses a code from that step or any earlier one.
Six digits can also be guessed without a limit. RFC 4226 says truncating the HMAC value to a short code makes a brute force attack possible, recommends a throttling parameter set as low as possible without significantly hurting usability, and says delay or lockout schemes MUST work across login sessions to prevent parallel guessing.
NIST section 3.2.2 says that, unless an authenticator type says otherwise, the verifier SHALL limit consecutive failed attempts on one authenticator to no more than 100 by disabling it, explains the number as a balance between the chance of a correct guess (for example, 100 attempts against a six-digit code) and the need for account recovery, and lets agencies set lower limits.
The careless lab version counted nothing and accepted the right code after five wrong ones, each sent from a new sign-in.
The careful version counts per account and locks the authenticator after five, a figure chosen for the lab. OWASP's WSTG-ATHN-03 notes that testing a lockout needs an account the tester is willing or can afford to lock.
The OWASP cheat sheet's guidance on handling one-time passwords fills in the rest. Implementations SHOULD enforce a short time-to-live, make codes single use, apply strict attempt limits and invalidate the code on successful verification, and SHOULD NOT log code values or store them in long-term plaintext form.
It also recommends generating codes with a cryptographically secure random number generator, considering 8-digit or longer codes where usability allows, and, on resend, generating a new code and overwriting the old record. The first and last of those concern codes the application generates and sends.
An authenticator app's codes come from the shared secret instead, which ASVS requirement 6.5.3, at Level 2, asks to be generated with a CSPRNG. For out-of-band codes, NIST adds that generating a new secret SHALL NOT reset the failed-attempt count.
The time window is a setting too. RFC 6238 recommends a default time step of 30 seconds and that at most one time step is allowed as network delay, and notes that a larger delay window exposes a larger window for attacks.
ASVS 5.0 requirement 6.5.5, at Level 2, gives a TOTP a maximum lifetime of 30 seconds, and requirement 6.5.8, at Level 3, asks that TOTPs are checked against a time source from a trusted service rather than a time the client provides.
The RFC's allowance and the ASVS lifetime are different limits, so decide which you follow and write it down. The lab accepts the current step and the one before. One time step is the most the RFC recommends allowing as network delay.
MITRE ATT&CK technique T1556.006 describes adversaries disabling or modifying MFA to keep access to compromised accounts, and notes that if a fail open policy is in place, an otherwise successful authentication may be granted access without enforcing MFA when the MFA process fails.
Its Multi-factor Authentication mitigation (M1032) says that, if possible, you should consider configuring MFA solutions to fail closed rather than grant access in case of serious errors.
On your own staging copy that is a short test: make the code-checking service or library unreachable, then confirm the sign-in stops with an error rather than finishing on the password.
NIST treats codes sent over the telephone network as a restricted authenticator. Section 3.1.3.3 says setting or changing the pre-registered phone number is the binding of a new authenticator, that verifiers SHALL ensure alternative authenticator types are available, and that verifiers SHOULD consider risk indicators such as a device swap, SIM change or number porting before sending a code.
Section 3.2.9 says a provider that accepts a restricted authenticator SHALL, among other things, offer at least one unrestricted alternative and give subscribers meaningful notice of the risks.
ASVS 5.0 requirement 6.6.1, at Level 2, allows phone and SMS codes only to a previously validated number, alongside stronger methods and information about the risks, and rules them out at Level 3. CISA's table lists SMS and voice as vulnerable to phishing, SS7 and SIM swap attacks, to be used only as a last resort or a temporary step while moving to something stronger. The OWASP cheat sheet says not to use SMS for high-value or PII-handling applications.
Email is weaker again. NIST section 3.1.3.1 says email SHALL NOT be used for out-of-band authentication, and ASVS requirement 6.3.6, at Level 3, asks that email is not used as either a single-factor or multi-factor mechanism.
MFA fatigue: push notification MFA and what number matching changes
Push notification MFA sends a prompt to an app on the user's phone and signs them in when they approve it.
CISA's fact sheet on number matching, dated October 2022, describes MFA fatigue, also known as push bombing, as a cyber threat actor bombarding a user with push notifications until the user approves the request by accident or out of annoyance.
Someone who already has the password can, in CISA's words, generate hundreds of prompts on the user's device over a short period of time, and the prompts may also confuse a user into assuming one of them is legitimate.
MITRE ATT&CK lists the technique as T1621, Multi-Factor Authentication Request Generation, and adds that adversaries who lack credentials may abuse automatic push generation where it is configured for self-service password reset.
NIST has moved away from plain approval. Section 3.1.3 says a method that compares the secrets received from the primary and secondary channels and requests approval on the secondary channel is no longer considered acceptable, because it increases the likelihood that the subscriber approves without actually comparing them, as observed with authentication fatigue attacks.
In a push flow, the secondary channel is the one that reaches the app on the user's phone. The guideline requires the secret to be transferred between the device and the sign-in session instead, and says presenting a list of secrets to compare is not sufficient, because the claimant may reasonably guess from a list that short.
Section 3.1.3.2 says verifiers that send push notifications SHOULD implement a reasonable limit on the rate or total number sent since the last successful authentication.
Number matching is the setting that makes that transfer. CISA describes it as forcing the user to enter numbers from the identity platform into their app to approve the request, and says it mitigates fatigue in two ways: approval requires access to the sign-in screen, and each prompt carries a unique set of numbers, so generating many prompts stops being effective.
CISA recommends number matching for organisations using push MFA that cannot yet implement phishing-resistant MFA, and says it is not as strong; its other fact sheet lists push with number matching as resistant to push bombing and vulnerable to phishing.
NIST does not count out-of-band authentication as phishing-resistant either. A fake page that relays the real sign-in can show the user the real number, so number matching answers fatigue rather than relay.
What a push flow on your own application should do, with the source behind each point:
- Cap the prompts. Beside NIST's SHOULD above, ASVS 5.0 requirement 6.6.4, at Level 3, asks for rate limiting to prevent push bombing and says number matching may also mitigate the risk; the OWASP cheat sheet says to rate-limit or cap push notifications; and one of MITRE's mitigations for T1621 (M1032) says, among other things, to implement limits on the maximum number of MFA request prompts that can be sent to users in a period of time.
- Require the number. The user types the number shown on the sign-in screen into the app; a bare Approve button, or a choice from a short list, does not finish the sign-in. NIST section 3.1.3.1 says an out-of-band authenticator that requests approval SHALL accept a transfer of the secret from the primary channel, and the note in section 3.1.3 says presenting a list of secrets to compare is not sufficient.
- Show what is being approved. MITRE's user training mitigation for T1621 (M1017) says, among other things, to train users to review the source location of the login attempt prompting the request. Users can do that from the prompt only if it shows where the attempt came from, so showing the application's name, the place and the time is this page's advice.
- Expire and use once. NIST section 3.1.3.2 says an out-of-band authentication SHALL be considered invalid unless completed within 10 minutes, and its secret accepted only once; ASVS requirement 6.5.5, at Level 2, gives out-of-band requests a maximum lifetime of 10 minutes.
- Follow up denials. CISA recommends investigating denied push requests, because MFA checks happen after the first factor, so a denial could mean the password is compromised, and training users to report unknown or bulk confirmation requests.
Enrolment and factor changes: when a factor is bound to the account
NIST calls the moment a factor is attached to an account binding.
Section 4, Authenticator Event Management, includes binding among the events that can occur over the lifetime of an authenticator and affect its use, and section 4.6 gives it as an example of an account event that requires the subscriber, or someone they designate, to be independently notified. Section 4.1.2.1 says that when any new authenticator is bound, the process SHALL require authentication at the maximum assurance level currently available in the account, or the maximum assurance level at which the new authenticator will be used, whichever is lower, and that the provider SHALL notify the subscriber through a mechanism independent of the transaction that bound it.
Section 4.1 says the provider SHALL keep a record of every authenticator bound to each account, with the date and time of significant lifecycle events, and SHOULD record the source of the binding, such as an IP address or device identifier.
Enrolment is a bypass in its own right when it asks for too little. MITRE ATT&CK technique T1098.005 says an adversary that compromises a user's credentials may enrol a new device to bypass initial MFA requirements and gain persistent access, and that in some cases self-enrolment may require only a username and password to enrol an account's first device or a device for an inactive account.
Its mitigation (M1032) includes configuring MFA systems to disallow enrolling new devices for inactive accounts. T1556.006 lists registering a new adversary-controlled MFA method among the ways an attacker who is already in keeps access.
The careless lab version let a signed-in session start enrolment without the password and switched the new factor on before any code from the app had confirmed it, so a user who stopped halfway met a code prompt at the next sign-in for an app they never finished setting up.
The careful version asks for the password first and keeps the new secret pending until a code proves the app holds it. Asking for the password again on an account that only has a password is this page's advice: NIST's rule asks for authentication at the lower of the account's current maximum level and the maximum level the new factor will be used at, which a session signed in with the password may already meet.
Changing a factor is where a stolen session can become a stolen account. The OWASP cheat sheet says factor changes, such as a new phone number, a new authenticator app or a replaced hardware token, must be strictly secured because attackers can exploit the process to take over accounts.
Its best practices include: require reauthentication with an existing enrolled factor before allowing changes; do not rely solely on the active session, as it may be hijacked; treat factor replacement as a high-risk action and apply risk-based checks, such as a new device or unusual location; notify the user through out-of-band channels, such as email or push notification, whenever a factor changes; and consider delays or step-up verification for high-value accounts.
ASVS 5.0 requirement 7.5.1, at Level 2, asks for full reauthentication before changes to the MFA configuration, and NIST counts a new phone number for text-message codes as binding a new authenticator. The careless lab version removed the factor on the session alone and told nobody.
Once a factor changes, the sessions it protected should not carry on unchallenged. ASVS 5.0 requirement 7.4.3, at Level 2, asks that users are given the option to end all other active sessions after a change or removal of any authentication factor, including an MFA settings update; the session management guide covers how sessions end. The careful lab version ends the other sessions and forgets remembered devices when the factor is removed.
MFA recovery security: why the lost-factor path is the weak point
Recovery exists to let someone in without the factor, which makes it the path to examine first.
NIST's informative threats section puts the risk plainly in section 6.3: the weak point in many authentication mechanisms is the process followed when a subscriber loses control of authenticators and needs to replace them; in many cases the options for authenticating the subscriber are limited, and economic concerns, such as the cost of maintaining call centres, motivate inexpensive and often less secure backup methods; and where recovery is human-assisted, social engineering attacks also pose risks.
The OWASP cheat sheet calls handling users who lose their factors one of the biggest challenges of implementing MFA: there needs to be a way back in, and it is crucial that the way back does not give an attacker a means to bypass MFA and hijack the account.
The cheat sheet says there is no definitive best way, and that what is appropriate varies with the security of the application and the control over its users. Its suggestions of possible methods include single-use recovery codes issued when MFA is first set up; requiring users to set up several types of MFA, so they are unlikely to lose all of them at once; mailing a one-use recovery code or a new hardware token to the registered address; requiring the user to contact a support team with a rigorous process to verify their identity; and requiring another trusted user to vouch for them.
Whichever method you choose, recovery should ask for no less than sign-in. The cheat sheet says so in its section on security questions: account recovery is an alternate way to authenticate, so it should be no weaker than regular authentication. NIST makes it concrete.
Section 4.2.2.2 says that to recover an account that can authenticate at a maximum of AAL2, the provider SHALL require one of three things: two recovery codes obtained by different methods, one recovery code plus authentication with a single-factor authenticator bound to the account, or repeated identity proofing where the account was proofed.
Section 6.3 adds that one factor must not be usable to obtain an authenticator of a different factor, giving the example that a password must not be usable to obtain a new list of look-up secrets.
ASVS 5.0 requirement 6.4.4, at Level 2, asks that when an MFA factor is lost, identity proofing is performed at the same level as during enrolment, and requirement 6.4.2, at Level 1, rules out secret questions.
Applied to an application where users sign in with a password and an authenticator app, the second of NIST's options means the password plus a recovery code. An emailed link on its own is one issued recovery code and no more. NIST allows issued recovery codes to be sent to an email address, valid for at most 24 hours, and section 3.1.3.1 says codes issued as recovery codes are not authentication processes and are not affected by its ban on email for out-of-band authentication; but one issued code alone is not among the three options at AAL2.
Saved recovery codes have rules of their own. NIST section 4.2.1.1 says a saved recovery code SHALL include at least 64 bits from an approved random bit generator and SHALL be stored in hashed form using an approved one-way function, as described in section 3.1.1.2; its verification SHALL be subject to the throttling requirements; and once used, the provider SHALL invalidate it and SHALL issue a new saved code.
It also says the subscriber MAY request a replacement recovery code at any point following enrolment, and that the issuance of a replacement recovery code SHALL result in an account recovery notification.
ASVS 5.0 requirement 6.5.2, at Level 2, asks that look-up secrets with less than 112 bits of entropy are hashed with an approved password hashing algorithm and a 32-bit random salt, and allows a standard hash function at 112 bits or more. The lab's codes are 128 random bits each, stored as SHA-256 hashes and removed when used.
NIST's text describes a saved code replaced after each use, while the lab issues a set of ten and tells the user how many remain. The careless version kept its codes as written and accepted the same one twice.
A support desk that can remove a factor is a recovery path too. NIST section 4.2.1 says a provider MAY support an application-specific method, such as interaction with one of its agents, but that alternative methods SHALL be based on a risk analysis and documented, and its threat table lists an insider, such as a customer support representative, colluding with an attacker to give access to accounts.
Write down what support may accept as proof, hold it to the level ASVS requirement 6.4.4 asks for, tell the account owner every time it is used, and test it with the support team, who know it is a test, on a test account.
Recovery should also clear away what the lost factor left behind. NIST section 4.2.3 says that in all cases account recovery SHALL cause a notification to be sent to the subscriber or their designee. The OWASP Forgot Password Cheat Sheet makes the point for password resets: a reset alone may not restore control, because an attacker may still have an active session or may have changed recovery information or MFA methods, and after recovering a potentially compromised account, existing sessions and outstanding recovery links or codes should be invalidated. Remembered devices need the same treatment, which the next section covers.
Remembered devices: what skipping the second step should cost
A remember this device option trades the second factor for a cookie, and the sources weigh that trade differently.
NIST SP 800-63B-4, written for government systems, says in section 5.1 that cookies and similar remember my browser features SHALL NOT be used instead of authentication, with one exception: reauthentication at AAL2 when the inactivity timeout has passed but the overall timeout has not.
The OWASP Multifactor Authentication Cheat Sheet takes a risk-based view: having to sign in with MFA frequently burdens users and may cause them to disable it, and risk-based authentication can reduce how often MFA is asked for, for example by requiring it when a user signs in from a new device or location. The OWASP Authentication Cheat Sheet says remembered-device cookies should be risk signals rather than substitutes for authentication.
If you offer it, the device token stands in for the second factor, so it needs the protections a factor has. In the careful lab version the token is a random value, stored on the server only as a hash, tied to one account and to that account's current factor, with an expiry the server checks.
When the factor is removed or reset, every remembered device is forgotten. In the careless version the token was stored as written and checked only against the account, so a browser remembered before Sam reset the authenticator through a recovery code still skipped the code afterwards.
None of these details comes from a standard; they are this page's advice for keeping the cookie no easier to misuse than the factor it replaces.
Two more rules follow. A remembered device should not count as fresh proof for a sensitive action, and the account owner should be able to see the list and remove a device, with the removal taking effect on the server. The session management guide covers the account page that lists sessions and devices.
Asking for the factor again before a sensitive action
Passing the second factor at sign-in does not mean every later action was approved by the person holding it.
The OWASP cheat sheet says the most important place to require MFA is sign-in, and that depending on the functionality it may also be appropriate to require it for sensitive actions such as changing passwords or security questions, changing the email address, disabling MFA, and elevating a session to an administrative one.
ASVS 5.0 requirement 7.5.3, at Level 3, asks for further authentication with at least one factor, or secondary verification, before highly sensitive transactions or operations. Reauthentication before password and email changes is covered in the authentication failures guide.
What counts as asking again is a design decision worth writing down. The careful lab version wants a code that has not been used before, sent with the request that changes payout details; the session alone, however recently it signed in, is not enough. The careless version changed the details on the session.
Where sign-in happens at an identity provider, ASVS requirement 6.8.4, at Level 2, asks the application to verify the authentication strength, methods or recentness it expects using the information the provider returns, gives validating the acr, amr and auth_time claims of an OpenID Connect ID token as one way this might be done, and asks for a documented fallback that assumes the minimum strength mechanism when the provider does not supply them. The OAuth and OIDC security guide covers the protocol.
Who should be told when a factor changes
The account owner first, and somewhere the person making the change cannot intercept.
NIST section 4.6 says certain account events, such as binding an authenticator and account recovery, require the subscriber or someone they designate to be independently notified, to help detect fraud. Notifications SHALL go to the notification addresses stored in the account, the provider SHALL support at least two such addresses, and each notification SHALL give clear instructions, including contact information, in case the recipient did not make the change.
Section 4.5 says the provider SHOULD notify the subscriber when an authenticator is invalidated.
The OWASP cheat sheet asks for a notice through out-of-band channels, such as email or push notification, whenever a factor changes, and ASVS 5.0 requirement 6.3.7, at Level 3, asks that users are notified after updates to authentication details.
A failed or denied second factor deserves a notice too. The OWASP cheat sheet and CISA both point out that it could mean the password is known to someone else; the credential stuffing guide covers that notice. ASVS 5.0 requirement 6.3.5, at Level 3, asks that users are notified of suspicious authentication attempts, and gives partially successful authentication, where only one of several factors succeeded, as an example.
Inside the business, someone should see the patterns no single user notices: a burst of prompts to one account, repeated wrong codes, a factor changed soon after a sign-in from somewhere new. That is a job for logging and alerting.
What to log for the second factor
ASVS 5.0 requirement 16.3.1, at Level 2, asks that all authentication operations are logged, successful and unsuccessful, and says the type of authentication or the factors used should be collected as well.
For a second factor that covers:
- Every code check, with its outcome and the reason for a refusal, such as wrong, already used or locked.
- Every push prompt sent, and whether it was approved, denied or left to expire.
- Each binding, change and removal of a factor, with the date and time and the IP address or device. Logging all three with those details is this page's advice. NIST section 4.1 says the provider's record SHALL contain the date and time of significant authenticator lifecycle events, giving binding, renewal, update and expiry as examples, and SHOULD include information about the source of the binding, such as an IP address or device identifier.
- Recovery codes used and refused, and every support-desk reset.
- Remembered devices issued, used and forgotten, and sensitive actions refused for want of a fresh code.
Keeping codes out of the log
The OWASP cheat sheet says one-time password implementations SHOULD NOT log code values, and ASVS requirement 16.2.5, at Level 2, asks that logging of sensitive data follows the data's protection level, giving as an example that it may not be allowed to log certain data, such as credentials or payment details.
The careless lab version wrote the wrong code into its log line; the careful version records the event, the account and the time. MITRE's detection guidance for T1621 suggests monitoring for excessive or anomalous push notifications or token requests, and the OWASP cheat sheet suggests watching for several push prompts in a short period and sudden MFA method changes.
Where these events are kept and who is alerted is the subject of the security logging and monitoring guide.
MFA testing on an application you own
The test matrix in the asset on this page is organised by state change: from no factor to enrolled, from password to second factor, from one factor to another, from a lost factor to a recovered account, from a remembered device to a skipped step, from a push prompt to approval, and from signed in to a sensitive action.
Each row gives the steps, the expected result, the evidence to keep and the source behind the expectation, or says the expectation is the matrix's own advice.
Run it only against an application you own or are authorised in writing to test, with test accounts created for the purpose, on a staging copy where you have one. Some rows can do harm even there. Lockout and recovery rows run only on test accounts.
Push rows send prompts only to a test device you hold, and text-message rows only to a test number, never to a real person's phone. The support-desk row is a walk-through with the support team, who know it is a test, on a test account.
Decide first which ASVS level you are working to, because several rows are Level 2 or Level 3 requirements. Some rows go faster with the code open: how the code check records the last used step, how recovery codes are stored, what the remembered-device cookie points to, and which routes issue a session.
Running the MFA lab on your own machine
The lab in the asset is an illustration with one kind of factor: a time-based one-time password built from RFC 6238 with node:crypto.
Push prompts, text messages and passkeys are covered by the matrix and the sources above, not by the lab. It is a small sign-in service with two invented accounts in a careless version and a careful version, plus a check of the code generator against the RFC test values, a runner that walks a baseline sign-in and the fourteen matrix rows the lab can show, and a regression test.
The server binds to 127.0.0.1 and asks for port 0, which the Node.js net documentation says makes the operating system assign an arbitrary unused port; it keeps everything in memory and puts notices in an in-memory outbox. The lab imports only node:http, node:crypto, node:test and node:assert, and installs no packages.
The lab's secrets are invented or made fresh. The two accounts are made up, and their passwords end in not-real. Authenticator secrets, recovery codes and device tokens are random values the lab creates in memory on each run and never prints, and the only fixed key is the RFC test key.
The lab reads time from a clock fixed at Unix time 1767225600 (1 January 2026, 00:00:00 UTC) at the start of every check and moved on only by the checks, so every run walks through the same time steps and prints the same results.
It was written and run on Node.js 26.0.0 on an Apple M3 Max machine running macOS, and every output in the asset was copied from that run by a script. Before anything else, check-rfc-vectors.mjs computes the ten 6-digit HOTP values in RFC 4226 Appendix D and the six SHA-1 TOTP values in RFC 6238 Appendix B, and all 16 matched.
- Save the seven files from the asset into an empty folder and open a terminal there.
- Run node check-rfc-vectors.mjs to check the code generator against the published values.
- Run node run-matrix.mjs. The careless version held 1 of the 15 checks, the baseline sign-in, and the careful version held all 15.
- Run node mfa-checks.test.mjs, where all 15 tests pass, then node mfa-checks.test.mjs careless, where 14 fail. Node's test runner sets the exit code to 1 when any test fails. A pipeline step that treats a non-zero exit code as a failure then fails.
Where an outside test fits
Your own matrix run covers the routes and flows you know about.
A Clever Ops web application and API penetration test covers authentication and sessions, including whether reset skips multi-factor sign-in where it is on, and lockout, password reset and multi-factor checks run on test accounts. Each finding comes with redacted requests and responses, the accounts that sent them, the steps to reproduce it, a fix and the criteria the retest will use.
If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
Getting into an account that has a second factor without that factor being checked when it matters. Either the factor is beaten at sign-in, for example a code typed into a fake page that relays it or a push prompt approved to make the prompts stop, or it is gone around through enrolment, recovery, a remembered device, an older sign-in route or a second step the server does not enforce. The OWASP Multifactor Authentication Cheat Sheet says attackers increasingly target weaknesses in MFA deployments and authentication workflows rather than attempting to defeat MFA itself.
It depends on the factor. NIST SP 800-63B-4 says out-of-band and one-time password authenticators, whose output the user types in, SHALL NOT be considered phishing-resistant, because typing the output in does not bind it to the session being authenticated; its example is an impostor verifier relaying the output to the real one and successfully authenticating. Phishing resistance needs cryptographic authentication bound to the session or to the site's name, and NIST gives WebAuthn as an example. CISA's October 2022 fact sheet called FIDO/WebAuthn the only widely available phishing-resistant authentication.
MFA fatigue, or push bombing, is sending push prompts to someone whose password is known until they approve one, by accident or out of annoyance, as CISA describes it. Number matching makes the user type a number from the sign-in screen into the app, so a prompt cannot be approved without seeing that screen. CISA says it mitigates fatigue but is not as strong as phishing-resistant MFA. Limiting how many prompts are sent, which NIST says verifiers SHOULD do, belongs beside it.
NIST SP 800-63B-4 treats codes sent by text or voice as a restricted authenticator: the provider SHALL, among other things, offer an unrestricted alternative and give meaningful notice of the risks, and a change of phone number counts as binding a new authenticator. ASVS 5.0 requirement 6.6.1, at Level 2, allows them only when the phone number has previously been validated, stronger methods are also offered and the service gives users information on their security risks, and says they must not be available at Level 3. CISA lists SMS and voice as vulnerable to phishing, SS7 and SIM swap attacks and calls them a last resort.
NIST SP 800-63B-4 section 4.2.1.1 says a saved recovery code SHALL include at least 64 bits from an approved random bit generator, SHALL be stored in hashed form and SHALL be subject to the throttling requirements of section 3.2.2, and that after a code is used the CSP SHALL invalidate it and SHALL issue a new saved recovery code. Recovery as a whole should ask for no less than sign-in. Section 4.2.2.2 says that to recover an account that can authenticate at a maximum of AAL2, the CSP SHALL require one of: two recovery codes obtained by different methods, one recovery code plus authentication with a single-factor authenticator bound to the account, or repeated identity proofing where the account has been identity-proofed. Section 4.2.3 says account recovery SHALL cause a notification to the subscriber or their designee.
NIST SP 800-63B-4, written for government systems, says remember-my-browser features SHALL NOT be used instead of authentication, outside one reauthentication case at AAL2. The OWASP cheat sheets take a risk-based view, with remembered-device cookies used as risk signals rather than substitutes for authentication. If you offer it, store the token only as a hash, expire it on the server, and forget every remembered device when the factor is reset or removed.
Use test accounts on a staging copy, send push prompts and text messages only to devices and numbers you hold, and walk through each state change: enrolment, sign-in with the code, changing or removing the factor, recovery, remembered devices, push approval and sensitive actions. The matrix on this page lists the steps, the expected result, the evidence to keep and the source for each row. The lab runs fourteen of those rows plus a baseline sign-in against a careless version, where the fourteen fail, and a careful version, where all fifteen checks hold.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.