Threat model
The threat model of @noctcore/auth: what it protects, who it protects it from, where it trusts its surroundings, and which test proves each defense. The defenses are explained in the Learn guide; each attack listed here has a numbered regression test in the attack suite.
What the library is
A server-side library. A consuming app calls it from its own HTTP handlers to register, log in, validate a session, reset or change a password, and verify or change an email address. The library never handles HTTP itself: the app passes in the request metadata (client IP, user agent, origin) and turns results into responses. Everything it stores goes through four store ports (users, sessions, one-time tokens, counters), with adapters for Redis and Prisma, and every mail goes through a mailer port. The optional two-factor plugin (@noctcore/auth/two-factor) adds a fifth store (factors, recovery codes, trusted devices, step-up proofs) and a cipher port for TOTP secrets. The optional membership plugin (@noctcore/auth/membership) adds a membership store (who holds which role in which scope) and guards the changes to it. The optional invitations plugin (@noctcore/auth/invitations) adds an invitation store (pending invitations, by a SHA-256 of their token) and mails invitation links.
Assets
| Asset | Where it lives | What losing it means |
|---|---|---|
| Passwords | Never stored; only an Argon2id hash in the user store | Account takeover here and anywhere the password is reused |
| Password hashes | User store | Offline guessing; slowed by Argon2id, not stopped |
| Session tokens | The browser cookie; the store holds only their SHA-256 | Signing in as the user until the session ends |
| Reset and verification links and codes | The user’s mailbox; the store holds a SHA-256 (links) or an HMAC under the server secret (codes) | Taking over the account, or verifying an address the attacker does not own |
| Email change codes and revert links | The new address’s mailbox (codes) and the old address’s (revert links); the store holds an HMAC (codes) or a SHA-256 (links) | Moving the account to an address the attacker does not own; or, with a revert link, moving it back and removing its password |
| Trusted-device cookies | The browser; an HMAC under the server secret | Getting past a lock with a known password |
| The server secret | App configuration | Forging device cookies and CSRF tokens, and making stored code HMACs guessable offline |
| TOTP secrets (two-factor plugin) | The user’s authenticator app; the store holds only what the app’s cipher returns | Generating the user’s codes, so the second factor is gone |
| Recovery codes (two-factor plugin) | With the user; the store holds an HMAC under the server secret, bound to the user (codes imported from an app’s earlier scheme keep that scheme’s hash until the first one passes a login challenge, which replaces the set) | Getting past the second factor once per code |
| Two-factor trusted-device tokens | The browser cookie; the store holds their SHA-256 | Skipping the second factor, never the password, until the next password change, reset or revoke-all |
| Who may manage a scope (membership plugin) | The membership store: each member’s role per scope | A scope nobody can manage, or a member who keeps powers taken away from them |
| Pending invitations (invitations plugin) | The invitation store: a SHA-256 per invitation; the token only in the mail | A seat or an account handed to someone other than the invited address’s owner |
| Whether an address has an account | Nowhere on purpose | A list of users to phish or attack, and a privacy leak |
| The owner’s ability to sign in | Lockout counters | Locking the owner out is a denial of service on one account |
Trust boundaries
The app is trusted. It holds the configuration and the server secret, decides who may do what once a user is signed in, and renders every page. The library trusts the app to pass in correct request metadata, and checks the configuration at startup instead of trusting it blindly: for example, it refuses a server secret shorter than 32 bytes, a password policy below 8 characters and Argon2id parameters below the OWASP floor, and its parseTrustProxy helper refuses true.
The stores (Redis, Postgres through Prisma, or an adapter the app writes) are trusted to keep what is written and to honour the port contracts: single-use consumption, atomic counters, keys that expire, and a session touch that never brings a deleted session back. The conformance suite in @noctcore/auth/testing checks an adapter against those contracts. The library limits what a store leak gives away: tokens are stored only as hashes and codes as HMACs, so a read-only dump does not hand out working credentials.
The mailer is trusted to deliver to the address it is given. A mailbox is treated as proof of control: proving one lifts a lock, verifies the address and ends every other session. No flow awaits delivery. Every mail (sign-up, email verification, email change, password change, password reset, the reset request’s job and the lockout notice) is handed to mailer.send and the flow answers without awaiting the promise send returns, so a delivery that is slow, or never settles, neither delays nor hangs a response. In most flows the call to send is still on the response path, though: whatever send does before it returns its promise counts toward the response time, and a door that mails on one branch only answers slower on that branch. send must only enqueue, with templates built and mail sent by a worker. Sign-up goes further: both of its mails (account-exists for a taken address, verify-email for a new one) are handed over from a background task, after a store call, so with a store that does network I/O the call to send comes after the answer (in an earlier review, a 40 ms template rendered inside send made taken-address sign-up more than 30 ms slower, when both mails were still handed over on the response path). A mailer that throws or rejects never changes the answer: the error is logged as Mailer failed. Delivery is at most once from the library: each mail is handed over once and never retried, so a dropped mail stays dropped unless the app’s mailer or queue retries it (the dedupeKey on each event is safe to use as a job id). Enqueueing narrows the window in which mail can be lost but does not close it: the enqueue write itself is not awaited, so a process that exits, or a serverless runtime that freezes the instance after the response, between the answer and the moment that write settles loses the mail. The app closes that window with the background option: waitUntil on runtimes that freeze after the response, and auth.flush() on graceful shutdown of a long-lived process. Without them, nothing waits for a send. By default the library also sets no timeout and no cap on background tasks, so during an outage in which send hangs, unsettled promises pile up in memory. background.maxPending turns that into logged, counted drops of mail once that many tasks are still running (work that writes an audit row off the response path, including the lookups of a taken-address sign-up and of a detached reset job, is never dropped and takes no slot, so the audit trail survives a cap that drops mail, apart from the email.verification_sent row of a dropped verification mail; a hung audit sink or user store on those paths still grows memory); background.timeout only stops flush and waitUntil waiting on a task (a promise cannot be cancelled, so the send keeps its memory until it settles). Give the mailer’s enqueue its own timeout as well. auth.flush({ timeout }) bounds a shutdown that waits on a hung send, and the NestJS module does so by default (10 seconds).
Sign-up timing. With the uniform registration answer, a taken and a new address both hash the password and the answer then waits on one insert: it stores a row for a new address and fails, or is skipped, for a taken one. Everything after the insert that differs between the paths runs off the response path: the owner lookup, the account-exists mail and the register.existing audit event for a taken address, the register.created event, the verification token and the verify-email mail for a new one (attack A004 pins both sequences and checks that the answer waits on none of them). With a user store that has changeEmail, every sign-up first looks for a hold on the address (an email change away from it can still be reverted), one indexed token read on every path before the insert; a held address reads its holder in the insert’s place (A061). So sign-up answers before its mail is handed over and before its audit event is written, and a failure in that work is logged as Background task failed, not answered. On PostgreSQL and CockroachDB the Prisma user store inserts with createManyAndReturn and skipDuplicates, because on PostgreSQL through @prisma/adapter-pg a failed insert made the next query about 3 ms slower, which used to land on the owner lookup. Where Prisma refuses that (SQLite has no skipDuplicates; a createData with nested writes or relations cannot go through a bulk insert) the store falls back to create and a unique violation, which was not measured. Two pieces of work still run only for a new address and are awaited, so their time shows: the app’s afterRegister hooks (keep them fast and queue slow work such as a welcome mail or a CRM call), and with registration.autoLogin the session it issues. autoLogin is only allowed with revealExisting, whose answer already names a taken address, so its cost reveals nothing new. The insert itself also differs (a stored row against a skipped one). bun run bench:timing:stores times the sign-up pair on Postgres (through Prisma) and Redis: before this change the taken path measured about 4.5 ms slower on one laptop (Welch’s t about 20 over 200 samples per arm); after it, three seeds of 400 samples per arm gave |t| of 2.8, 1.7 and 0.1, under the 4.5 threshold the benchmark uses, on a machine that was heavily loaded during the run, which widens the spread and so hides small gaps. That is a measurement on one machine, not a guarantee: with a different database, a slower disk or an app’s own hooks, a gap of the size of one insert can remain, so the register door’s rate limit (10 a minute per IP by default) and a captcha still bound how many samples an attacker gets.
The cipher (two-factor plugin) is trusted to encrypt and decrypt TOTP secrets, and to bind each ciphertext to the user id it is given. The plugin never holds a key: key management and rotation are the app’s. A store dump without the key yields no TOTP secret; an attacker who runs code with the key yields every one.
Plugins and callers of auth.context are trusted code, like the app. They can call issueSession, and the two-factor plugin’s enforcement lets through a session issued with via: 'second-factor', which is a claim that the factor was checked; the library cannot tell a true claim from a false one. The core’s re-issue labels are the exception: it accepts them only with a session it read live from the store for the same user.
The membership store (membership plugin) is trusted to decide its two guarded writes atomically: a role change or a removal checks the member’s current role and the other admins of the scope in the same step that writes, so concurrent writes cannot together leave a scope with no admin (membershipStoreConformance checks it under concurrency). The plugin reads the acting user’s role from this store on every call, never from the session. Writes that bypass the store (an app’s own SQL on the same table) are outside that guarantee.
The invitation store (invitations plugin) is trusted to spend an invitation in one atomic step (consume) and to keep at most one live invitation per scope and address, also under concurrent creates (invitationStoreConformance checks both). It holds only a SHA-256 of each token (256 random bits, so the hash cannot be searched), under no key, so rotating the server secret leaves pending invitations working. With acceptWithoutSession on, the token alone (proof of the invited mailbox) joins the account that holds the verified address, and still signs nobody in. The app’s authorize and onAccept hooks are trusted code: the plugin refuses to start without authorize, but what it allows, and what an accepted invitation grants, is the app’s decision.
The proxy. Only the proxies the app configures are trusted: a number of hops, or a list of proxy addresses and CIDR ranges (the Express presets loopback, linklocal and uniquelocal included). With a count, the client IP is read that many hops from the right of X-Forwarded-For; with a list, the header is read only when the socket address is inside the list, and the first entry outside it, from the right, is the client. The entry picked has a port, brackets and an IPv6 zone id stripped and must then be exactly one IP; otherwise the socket address is used, so a per-connection port or a proxy’s junk never becomes a rate-limit key. Either way entries the client wrote never decide it, and with no proxy configured the header is ignored. With a hop count the app must be reachable only through its proxies, because a direct client is taken for one; a list checks the socket address instead. A list entry that holds every address (a prefix length of zero) is refused at boot like true. An app may also name a single-address header its edge sets (such as cf-connecting-ip). It needs a proxy list (it is refused at boot with a hop count) and is read only when the socket address is inside the list and the header holds exactly one valid IP. The list must name the edge itself, or hops that accept traffic only from the edge: anyone who can reach a listed hop directly (an internal load balancer with an open port, another tenant on the network) can set the header. The app must name only a header its edge always overwrites.
Lookups by address are exact on the core’s side: after every findCredentialByEmail (login, the reset request and its job, the reset code, sign-up, an email change, joining by invitation, the lockout admin) a row whose stored address is not exactly the normalised one asked for counts as not found, on the same equal-work path as an unknown address. A store whose lookup goes through a case- or accent-insensitive collation (MySQL’s default utf8mb4_0900_ai_ci) would otherwise reach one account under several spellings, each with its own lockout and rate-limit keys. The core logs a warning with the user id (never the address) each time it discards such a row, so an operator can find rows written in another spelling. Behind an insensitive collation the warning repeats on every lookup of such a row (each sign-in attempt, reset request or sign-up under that spelling, within the rate limits), so it can be noisy until the rows are rewritten or the column made binary. The conformance suite also asks stores for exact lookups. A lint rule keeps flows and plugins off the store’s own lookup, whether they call it as a member, by a computed key or destructured.
A custom email normaliser (email.normalize set to a function) is trusted code, like the app. Every address the library compares, stores or turns into a counter key goes through the one normaliser createAuth resolved, so a normaliser that folds two mailboxes into one spelling gives them one account. The library checks what it can: at startup it runs the function over a sample (mixed case, IDN, decomposed accents, confusables, junk) and refuses one that throws, returns something unusable, answers differently twice or is not idempotent; on each call it refuses an address whose result is not a fixed point or is not a single plain address (exactly one @, no whitespace, control characters or RFC 5322 specials: , ; : < > ( ) " \ [ ]), and logs only the error class name of a throw. The startup sample also checks that different mailboxes it accepts stay apart. Whether the function merges the right addresses is the app’s decision. The same rule on what an address may contain applies to the built-in policies, so under every policy an accepted address is one plain mailbox to an address parser; every built-in policy takes only a host name as the domain (letters, digits and inner hyphens per label, at most 63, no empty label, a last label that is not all digits, so no IPv4 address); under the unicode policy the domain also has no port, path, query, fragment, credentials or percent escape, every label of its ASCII (punycode) form is letters, digits and inner hyphens (at most 63) and decodes back to exactly the label typed, so nothing UTS 46 would remap is accepted (an ideographic full stop for a dot, a Greek iota subscript, an old Cyrillic letter form, 127.1).
The browser is not trusted: everything it sends is attacker-controlled input. The library sets cookies so the browser protects them (__Host- prefix, HttpOnly, Secure, SameSite=Lax by default), and checks the Origin, Sec-Fetch-Site and a signed double-submit token against cross-site requests. The adapters’ CSRF, pre-session and blank session cookies take the session cookie’s SameSite for the request’s Origin, so they never travel more widely than the session cookie does. A cross-site origin the app lists in csrf.crossSiteOrigins is trusted like the app’s own origin (see Out of scope). Request bodies, cookies, tokens and codes are validated for shape before they reach a store key or a hash.
Attacker capabilities
The attacker is assumed to be able to:
- send any number of requests from many IP addresses, in parallel, with any headers and bodies, including a spoofed
X-Forwarded-For; - measure response times precisely over many requests;
- know or guess the victim’s email address;
- register accounts of their own, including one on the victim’s address before the victim does;
- get the victim’s browser to load a page they control (so they can send cross-site requests with the victim’s cookies, though not read the responses);
- obtain an old session cookie, reset link or code (from a shared computer, a forwarded mail or a log) after it was used or revoked;
- read a copy of the database or a Redis snapshot (a backup or dump), without being able to write to the live store.
In scope
The library defends against: guessing passwords and codes (through login, and through a stolen session at reauthenticate and changePassword, which spend login’s lockout budgets by default (with sessionProofs: 'door' only each door’s own limit, see Out of scope), the live session counting as a trusted device under a lock so an outsider’s lock does not block the owner’s step-up); locking the owner out of the password login; finding out which addresses have accounts, by the answer or by its timing; holding answers up through a slow mailer; replaying or reusing sessions, links and codes; keeping a session alive after a revocation, a password change or a reset; cross-site request forgery on the flows it serves; spoofing the client IP to escape rate limits (through X-Forwarded-For, a configured edge header, or posing as a trusted proxy); getting past a configured captcha with a token solved on another hostname or for another form (with the Turnstile verifier’s hostname and action checks set), or while the provider is down; taking over an account registered on someone else’s address (weakened when the app turns on emailVerification.linkWithoutSession, see Out of scope); getting a second account, a reset mailed elsewhere or a fresh guessing budget from another spelling of an address (case, composed or decomposed accents) under any email policy; registering a lookalike of an address under the unicode policy by mixing in a letter from another script, an invisible or bidi character, a compatibility form, a punycode label, the dotless i, an IPA Extensions letter or a dot above on i or j (other lookalikes within one script are not stopped, see Out of scope); keeping an account by changing its email from a stolen session (the change needs fresh authentication and a live session, a proof from the new mailbox, and leaves the old address a revert link that a password change cannot void, held for its owner until the link is used or expires); forging trusted-device cookies; and turning a leaked store into working credentials. With the two-factor plugin on, also: replaying or guessing a TOTP or recovery code (including one imported from an app’s earlier scheme), reusing a login challenge, getting a session past the second factor through the core’s flows (sign-up with auto-login, a plain login, and re-issues, which need a session the core read live for the same user), resetting a password, turning the factor off or requesting an email change without it, and a stolen trusted-device token outliving a password change. With the membership plugin on, also: leaving a scope without an admin through concurrent demotions or removals, acting on yourself (self-promotion, demoting or removing yourself), a demoted admin acting on the old role (the role is read from the store on every call), with revokeSessionsOnChange off, signing a stranger out by adding them and changing or removing them again (with it on, that holds only where adding a member needs the user’s consent, see below), and, with revokeSessionsOnChange on, a demoted or removed member keeping a session, including through a login racing the change. With the invitations plugin on, also: reusing an invitation or racing two accepts of one, accepting with an account at another address, collecting an invitation with an unverified account (pre-hijacking), accepting an expired invitation, getting a session past a second factor through an invitation, learning whether an address has an account from the create answer or from refusals of a token, mail bombing through repeated invitations, and inviting without the app’s permission or accepting after the inviter lost it.
Out of scope
- The app’s own authorization. The library says who the user is. Whether that user may read an invoice or delete a project is the app’s decision and the app’s code. The membership plugin guards changes to roles; it does not scope data: filtering queries by tenant and checking membership on each request stay in the app.
- Forced sign-out by a scope admin (membership plugin,
revokeSessionsOnChangeon). The epoch is per user, so an admin of any scope a user belongs to can sign that user out everywhere, and void their trusted devices, by a role change or a removal, even one the store then refuses (last_admin, a target that changed or left): the first revocation runs before the write. With the invitations plugin, only the user’s invitations to that scope are deleted. That is the price of revoking at all; the option is off by default because the guards never need it. Who may be added to a scope, and whether they must agree first, is app policy:addtakes a user id and asks no consent. The consent path is an invitation the user accepts (the invitations plugin, #26). If revocation after the write fails, the change stands and the flow throws: every session from before the change was already revoked by the bump before the write, so only a login that ran between the two bumps can stay live; callauth.context.revokeAllSessions(userId, 'membership-changed')to finish. - XSS in the host app. Script running in the app’s origin can act as the user: send requests with their cookies, read pages, and change the password through the app’s own forms.
HttpOnlykeeps the session cookie itself out of reach, but no authentication library can defend a page that runs the attacker’s code. - A compromised Redis or database with write access. An attacker who can write to the stores can create sessions, reset counters and edit password hashes. The store is inside the trust boundary; protect it with network isolation, credentials and TLS.
- A leaked server secret or app configuration. Rotate the secret (CSRF tokens accept the previous one during rollover, and each safe request moves a client to a token under the new one, so the previous CSRF secret can be removed once clients have made a safe request since the rotation); device cookies and outstanding codes signed with it become void, and so do the two-factor plugin’s recovery codes, whose HMAC key is derived from it: users with a factor must generate a new set after a rotation.
- The mail provider and the user’s mailbox. Whoever controls the mailbox controls the account.
- Weak configuration chosen by the app. Defaults are the library’s responsibility; overrides are the app’s.
- What runs on an origin the app lists in
csrf.crossSiteOrigins. The list is empty by default. An origin on it, matched exactly, passes theOrigincheck, and itsSec-Fetch-Site: cross-siterequests pass the fetch-metadata check, so a page that can run script on that origin is stopped only by the double-submit token, which stays required. WithSameSite=Nonefor that origin (fromsession.cookie.sameSite) the browser also sends the session and CSRF cookies on requests it starts. The list is meant for a custom scheme only the app’s own desktop shell serves. A web origin the app does not control, or one with an XSS, put on it is the app’s choice and outside what the library can defend. A client that is not a browser can send anyOrigin, but it has no victim’s cookies to send with it. - Verifying an address with
emailVerification.linkWithoutSessionon. The option is off by default. With it on, whoever opens the link verifies the account without proving they hold its password. A mailbox owner who clicks a link for an account someone else registered on their address verifies that account; every session ends and the link signs nobody in, but the registrant still knows the password and can sign back in to a now-verified account. Mail link scanners make that zero-click: a corporate or provider scanner that fetches the link verifies the account if the app verifies on a GET or on page load. The app must keep the token where a fetch does not send it (the URL fragment), verify only on a POST from a human click (a confirm button), and word the mail so a reader who did not sign up ignores it. Trust that matters (an invitation, linking a social login) should stay behind a proof the registrant cannot pass, such as a password reset. - The opt-in lockout options and what they give up. Each is off by default.
throttle.lockout.permanentlocks an account for good afterafterLockstemporary locks in a row, password locks and the two-factor plugin’s factor locks alike (a completed sign-in, every factor proved, or a completed password reset resets the count; a correct password with a second factor still owed, or at a step-up door, does not), until an admin callsauth.lockout.clear: anyone who knows an address can spread failures over many IPs and lock its owner out on purpose (denial of service). The lock follows the account’s user id through an email change, ends its sessions and refuses email changes from any session. The owner’s trusted device still gets through unlesstrustedDevicesis false, which bumps the revocation epoch and refuses every session door (validation included, so a session the background revocation failed to end is refused on its next request), so the lock holds against the owner too. With trusted devices, a few ways in still mint a session, each needing a correct password or the app’s SSO: a device sign-in, an app’s SSO throughissueSession, a two-factor challenge started before the lock, and a login racing the revocation; none of those sessions can change the email. A lock on an address with no account is cleared when someone signs up on that address.auth.lockout.clearis not atomic: a burst of failures running during the clear can lock the account again as soon as it is lifted.throttle.lockout.revealLockedanswersaccount_locked(with the time left for a temporary lock) instead ofinvalid_credentials: it tells anyone who tries the address that it is locked and when the lock lifts. Unknown addresses lock and answer the same, so the answer alone does not prove an account exists, but it confirms the address is under attack and hands an attacker an enumeration signal the generic answer does not, for example when combined with a sign-up or reset flow that reveals more.throttle.lockout.countSuccesses: falsehands a completed sign-in’s account-wide slot back, so only failures count: an attacker who also holds the password could win budget back between guesses, which only matters with a second factor, and there the slot comes back only once the factor is proved; refunds are matched by count, not to the attempt that earned them, and capped per account-wide window: a completion never hands back more slots than correct passwords reserved in the current window, and slots owed in a window that ended (a lock included) never come back (A110). The check is not atomic: a completion racing the first attempt of a new window, or racing a password reset, can hand back one slot of the new budget.throttle.lockout.sessionProofs: 'door'takesreauthenticateandchangePasswordout of login’s lockout, so a stolen session cannot lock the owner out of sign-in or climb the permanent tier by guessing passwords at those two doors (A002): the door’s own per-user limit is then the only bound on guesses from a session, and those guesses never lock anything, so a stolen session can keep guessing at the doors’ rate (1440 a day per door, 2880 across both, by default) until the session ends. Under a permanent lock withtrustedDeviceson, it also gives such a session the door’s rate instead of the sharedperDevicebudget. Wrong second-factor codes at a step-up are not covered: they still lock the factor, and each factor lock counts toward the permanent tier. Apps that turn any of these on should put a captcha on login and keep per-IP rate limits, and the admin lockout tools belong on admin-only routes: they answer for any address. - Session management without fresh authentication (
session.requireFreshAuth). Both checks are on by default. WithrevokeSession: false, a stolen session can end the owner’s other sessions one by one; withrevokeOtherSessions: false, it can sign out every other device at once, and call it again each time the owner signs back in, without knowing the password. Neither gives the attacker access they did not have, the door still needs a live session of the same user, and the re-issued session keeps the oldauthenticatedAt, so it cannot be used to freshen a stale proof. The owner’s way out is a password change or reset, which revokes every session and needs the password or the mailbox. An app that turns a check off accepts that trade. - Changing the email policy on a live database. Rows are stored in the spelling of the policy that wrote them. Switching
email.normalize(tounicodeafterstandard, or to a custom function) without first rewriting every stored address, every pending invitation and every outstanding token that names an address into the new spelling leaves rows the new policy no longer matches: their owners cannot sign in or reset by address, and a fresh sign-up can create a second account for the same mailbox. The library does not migrate data; plan the rewrite (and the duplicates it may reveal) before the switch. - Whole-script and same-script lookalikes under the
unicodepolicy. The policy refuses an address part that mixes scripts, but a part written entirely in one script that resembles another (every letter Cyrillic, spelling a Latin word) is a different, valid address. There is also no UTS 39 skeleton (confusables) check: beyond the short list it refuses (the dotless i, the IPA Extensions block, a dot above on i or j), other lookalikes within one script remain possible (Latin small capitals, a dotless j, letters with marks that are hard to see). Each is a different mailbox, so mailbox verification is the backstop: the verification mail proves it; apps that show addresses to other users (an admin list, an inviter) should display them with care, or stay onstandard. - Unicode version drift under the
unicodepolicy. Normalisation, case mapping and the script and category tables come from the JavaScript runtime. NFC is stable for assigned characters, and unassigned code points are refused, but a runtime upgrade that assigns new characters can accept, or map, an address an older runtime refused, and an upgrade that remaps one of a stored address’s characters can refuse an address an older runtime accepted, so its owner can no longer sign in by address until the row is rewritten. Uniqueness holds on one runtime. - Volumetric denial of service. Rate limits protect accounts and the hasher, not the network.
- Phishing and malware on the user’s device. This includes a phishing page that relays a password and a TOTP code to the real site in real time: TOTP does not stop it, only origin-bound factors (WebAuthn) would.
- Enrolling a factor for a required user who has none yet. For that user the password is the only credential, so whoever has it can answer the enrollment challenge. The owner is mailed when the factor goes on.
- A stolen session locking the second factor. Step-up counts wrong codes in the same per-account budget as the login challenge, so a session holder can lock the factor (and the owner’s challenge) for up to an hour at a time, as long as the session lives.
- A recovery code spent by a race on one challenge. Two proofs sent at once on one challenge can both be checked; one gets the session, and a recovery code sent as the other is spent anyway.
- What an email change revert does not restore. A revert moves the address back, removes the password, and ends every session and trusted device. It never removes a second factor: it cannot tell the owner’s from one the intruder enrolled, and removing factors by enrolment time would let whoever reads the old mailbox strip a factor the owner added just before a legitimate change (A063). A factor the intruder enrolled therefore stays, and the owner, who cannot pass it, needs support to verify them outside the account and remove it. The old address is held for its owner while the revert link lives, but only the library’s sign-up, invitation sign-up and change flows check the hold: an app’s own user-creating paths must call
isAddressHeld, and sign-up checks before its insert (invitation sign-up reads the account, then the hold, and a confirm writes the hold before it moves the address, so a confirm between the two reads is seen by one of them), so a race with sign-up (or a direct store write) can still give the address an account. The revert then cannot restore it; it locks the account out instead (no session from any flow, no reset mail, reset links refused) and keeps the link alive as long. The lockout never lapses (marker and link are stored to expire at the start of 9999-12-31 UTC); it ends only when the owner’s revert finishes or when support callsclearEmailRevertLockout, which also voids the revert link and the hold; clearing it while the account names the intruder’s address hands that address a reset. A revert link refuses once the account no longer names the address the change moved it to, so after support settles the account on another address the link cannot move it back, even years later when the old address frees up, and its clicks cannot lock the account out again (A062). A held address costs sign-up the same answer, mail and number of round trips before the answer as a taken one, not the same time (a read of the holder in the insert’s place). While a revert link lives the account cannot start another change, even a legitimate one. Anyone signed in can spend a new address’s request limit and stall changes to it for an hour. The flows are series of store calls, not transactions: confirm writes the revert link before it moves the address, and revert removes the password in the restore’s write and revokes sessions right after, with the link unspent until the end so a click after a failure runs again. Whoever controls the old mailbox can use its revert link. - A two-factor challenge carried to another browser. A challenge is bound only to the user agent it was issued to, which an attacker holding the challenge can copy. Its limits are its 5-minute life and 5 codes.
Mapping to the attack suite
| Attack | Defense | Test |
|---|---|---|
| Brute force by parallel guesses | Attempts reserved before the verify, per (account, IP) and per account | A001 |
| Locking the victim out | Capped lock (the permanent tier is opt-in and off by default), one backoff step per lock (not per request that crosses the limit), trusted-device bypass, a reset lifts a temporary lock (a permanent one only an admin lifts) | A002 |
| Account enumeration by the answer | Public codes that never name account state | A003 |
| Account enumeration by timing | Same store calls and one verify for every address at login and reset request; at sign-up one hash and one insert on the response path, the rest off it | A004 |
| Holding responses up through a slow or hung mailer | Every mail handed to the mailer without waiting; at-most-once delivery, failures logged | A023 |
| The locked-account oracle | Unknown addresses lock too; a lock answers like a wrong password unless the app opts into revealLocked |
A005 |
| Replaying a revoked session | The epoch fence | A006 |
| Reusing a password reset token, or one that outlives a failed password write | Atomic single-use consume, expiry checked after it; every reset token voided before a reset or a change writes the hash (so a refused write leaves none), and once more right after; the sessions end whatever that second sweep does, and when it fails twice the flow throws after telling the owner, and a link minted during the write may stay live until it expires | A007 |
| Cross-site request forgery | Origin allowlist, Sec-Fetch-Site, signed double-submit token, SameSite=Lax |
A008 |
| Forging or hoarding trusted-device cookies | HMAC over user, epoch and issue time; shared device budget | A009 |
| A stolen session cookie outliving a password change | Every session revoked after the new hash is written | A010 |
| Spoofing the client IP | Trusted hops counted from the right; parseTrustProxy refuses true |
A011 |
| Account pre-hijacking | Proving the mailbox ends every other session | A012 |
| Guessing a short code | Attempt cap counted atomically; a per-address budget across IPs | A013 |
| Verifying an address with someone else’s proof | Codes bound to user and purpose; links checked against the session | A014 |
| A login rehash bringing back an old password | Compare-and-set rehash | A015 |
| A plugin minting a session outside the seam | No mint exposed to plugins | A016 |
| Replaying secrets from a leaked store | Only hashes and HMACs stored | A017 |
| Cookie tossing and reading the cookie from script | __Host- prefix, HttpOnly |
A018 |
| Two spellings of one address | ASCII-only normalisation, non-ASCII refused | A019 |
| Exhausting the server with oversized passwords | Maximum length; oversized input verified as empty against the dummy hash | A020 |
| Passing an unsafe method as a safe one through case folding | ASCII-only method comparison | A021 |
| Turning a malformed breach-check response into a verdict through case folding | ASCII-only upper-casing before the format check | A022 |
| Replaying a TOTP code (two-factor plugin) | The last accepted step moves forward by compare-and-set | A036 |
| Submitting one TOTP code twice at once | Atomic step advance; the challenge is consumed atomically | A037 |
| Brute forcing the second factor from many IPs | Attempts reserved per account before the compare; capped lock; 5 codes per challenge | A038 |
| Reusing a login challenge | Consumed on success, 5-minute life, replaced by a new login, bound to the user agent | A039 |
| Using a login challenge as a session or reset ticket | A one-time token under its own purpose, never in the session store | A040 |
| Reusing a recovery code | Atomic single-use delete; regenerating replaces the set in one write | A041 |
| Brute forcing a recovery code | 50 random bits per code; guesses spend the factor budget | A042 |
| A trusted-device token outliving a password change | Bound to the revocation epoch, deleted with the revocation | A043 |
| Resetting a password without the second factor | The reset demands a code; the factor is never touched | A044 |
| Turning two-factor off without a proof | Step-up per session id; a password alone never records one | A045 |
| Confirming an enrollment with a wrong or stale code | Fresh auth, read from the live session, to start and to confirm; compare-and-set on the pending secret within 10 minutes | A046 |
| Telling two-factor refusals apart by timing | Stand-in secret decrypted, same store calls for unknown and wrong | A047 |
| Getting a session past the second factor through another flow | The session hook refuses every issue but the plugin’s own and re-issues | A048 |
| Acting on a stale or borrowed second-factor proof | Expiry on the server clock, bound to one session, fresh auth (read from the live session) required too | A049 |
| Learning two-factor state from the answers | The factor is checked only after the password; one public code for every refusal | A050 |
| Changing the email without a fresh credential proof | The request needs a password proof inside freshAuthAge |
A051 |
| Changing the email of a two-factor account without the factor | A step-up in the session or a code with the request | A052 |
| Brute forcing the email change code | Attempt cap counted atomically before the compare; per-IP limit | A053 |
| Reusing an email change code or link | Atomic single-use consume; only hashes stored | A054 |
| Confirming an email change with a proof for another address or account | Codes bound to user and purpose; the token carries both addresses; compare-and-set on the old one | A055 |
| Keeping the account after an email change by changing the password | The revert link survives password changes and resets, removes the password and voids reset tokens | A056 |
| Replaying an email revert link | Purpose-bound, atomic single-use consume once the address is back | A057 |
| Account enumeration through the email change answer | Same answer and store calls for a taken, held and free address; the code only to a free one | A058 |
| Racing two email changes | One pending change per user; unique compare-and-set in the store | A059 |
| Taking the account back after a revert | No new change while a revert link lives; the lost address is blocked; tokens and trusted devices end; second factors stay (the intruder’s needs support) | A060 |
| Registering the old address so the revert fails | The old address is held for its owner while the revert link lives and gets the taken-address answer; if it has an account anyway, the revert still removes the password and sessions and the link stays usable | A061 |
| Resetting the password at the intruder’s address after a refused revert | A refused revert locks the account out: no session, no reset mail, reset links refused, each with the usual answer and no password hashed; it never lapses, ending only when the revert finishes or support clears it, which also voids the revert link and the hold; a link refuses once the account left the intruder’s address | A062 |
| Stripping the owner’s second factor with an email revert | A revert never removes a second factor, so a reset from the old mailbox still asks for the owner’s | A063 |
| Leaving a scope without an admin by concurrent demotions or removals (membership plugin) | The store checks the other admins and writes in one atomic step | A065 |
| Acting on yourself through the membership flows | User ids compared before any lookup; the actor’s role read from the store | A066 |
| Keeping a role or a scope after it was taken away | The actor’s role read from the store on every call; with revokeSessionsOnChange, every session revoked before and after the write, and the epoch fence refuses a racing login |
A067 |
| Signing a stranger out of everything through the membership flows | No revocation by default; never on an add or a same-role change. With revokeSessionsOnChange on, only consent to joining stops it |
A068 |
| Reusing an invitation, or racing two accepts of one (invitations plugin) | The store spends it in one atomic step | A069 |
| Accepting an invitation with an account at another address | Normalised addresses compared; nothing spent on a mismatch | A070 |
| Collecting an invitation with an unverified account | accept needs a verified address; register refuses a taken one |
A071 |
| Accepting an expired invitation | 7-day default, 30-day cap; expired answers like unknown | A072 |
| Getting a session past a second factor through an invitation | accept issues none; register issues through the seam the two-factor hook guards |
A073 |
| Learning whether an address has an account through invitations | create never reads the address; every bad token is invalid_token |
A074 |
| Mail bombing through repeated invitations | One live invitation per scope and address; per-address, per-inviter and per-IP limits | A075 |
| Inviting without the right, or accepting after the inviter lost it | authorize required and asked on every create and again on accept; revoke-all deletes an inviter’s invitations |
A076 |
| Passing a captcha with a token solved elsewhere, or while the provider is down | Hostname and action checked when configured; an outage, timeout or malformed answer refuses the request, before the rate limit and any account work | A077 |
| Learning a secret from how long its comparison takes | Hashes, MACs and tokens compared only through the constant-time helpers: Node’s crypto.timingSafeEqual where the runtime has it, a loop that never stops early elsewhere; a length mismatch is refused before either runs, and every caller compares fixed-length digests |
A078 |
| Riding the cross-site origin allowlist (NestJS and tRPC adapters) | Empty by default; only an exact listed origin passes the Origin and cross-site fetch-metadata checks; the double-submit token still required; wildcards refused at boot; the CSRF cookies take the session cookie’s SameSite |
A079, A080 |
Using a CSRF token read from the adapters’ token route or ctx.auth.csrfToken() for another session or pre-session |
Only the token the response sets or keeps as the cookie is returned, bound to the request’s own session or pre-session; the cookie is still required next to the header; an unsafe request from an origin outside the allowlist is refused on Origin and Sec-Fetch-Site whatever the token, and whatever the app’s CORS lets a page read; the response is no-store (on tRPC only when the app’s responseMeta is wrapped in authResponseMeta, which drops these headers it returns: Cache-Control, Surrogate-Control, CDN-Cache-Control, every *-CDN-Cache-Control (such as Cloudflare-CDN-Cache-Control), X-Accel-Expires and Edge-Control; a proxy-specific cache header outside this list is not touched, so such rules stay off the token route; on nestjs-trpc 2.14.0 and later through trpc.responseMeta, while before 2.14.0 it has no responseMeta and cache-setting middleware stays off the base path; and on Nest only when the route stays out of CacheInterceptor, any other response cache and any interceptor or middleware that sets Cache-Control); a subscription, a streamed batch and an exempt path get nothing |
A100, A101 |
| Choosing your own IP with a spoofed edge header | The client IP header needs a proxy list (refused at boot with a hop count), is read only when the socket address is inside it and only when it holds exactly one valid IP; otherwise the hop rule decides | A081 |
| Posing as a trusted proxy | With a proxy list, X-Forwarded-For is read only when the socket address is inside it; presets expand to the Express ranges; an unknown entry or a range that holds every address is refused at boot, and fails closed on the request path | A082 |
Using a verification link opened outside a session (opt-in linkWithoutSession) |
The link alone issues no session; every verify bumps the epoch, so a squatter’s session ends; another account’s session is refused and the link left unspent; single-use, expiring and bound to the address it was sent to. Not stopped: a squatter who keeps the password can sign back in to the now-verified account, and a link scanner can click for the owner unless the app verifies only on a POST (see Out of scope) | A083 |
| Locking the owner out for good through the permanent lockout tier | The tier is opt-in and off by default; with it on, the owner’s trusted device still gets through unless the app turns that off, a reset never lifts it, only an admin does, and the owner is mailed and a hook runs | A084 |
| Learning account state from the explicit locked answer | The answer is opt-in and off by default; with it on, unknown addresses lock and answer the same after the same work, and a wrong password or one source’s spent budget never reads as locked | A085 |
| Escaping a permanent lock through a live session | The lock ends every session (deleting them with trusted devices, bumping the epoch without); no session may change the email; without trusted devices every session door and session issue is refused; the marker is keyed on the user id, so it follows the account to any address | A086 |
| Reading a session’s store key through the session list, or revoking another user’s session by handle | The list shows a handle (an HMAC of the store key under a key derived from the server secret), never the key; revoke resolves a handle only among the caller’s own live sessions, asks a stale session for fresh authentication before any lookup (by default; see Out of scope for session.requireFreshAuth), and answers garbage, a raw store key, a gone session and another user’s handle the same |
A087 |
| Another spelling of the victim’s address under a configured email policy | One normaliser resolved at startup and used for every comparison, store write and counter key; every policy idempotent, custom ones checked at startup and per call; a lint rule bans the fixed function in the flows | A089 |
A lookalike address under the unicode policy (mixed scripts, invisible characters, compatibility forms, punycode, a short list of Latin lookalikes) |
Invisible, bidi, control, unassigned and compatibility characters refused; one script per part (UTS 39 CJK mixes allowed); punycode labels refused; the dotless i, the IPA Extensions block and a dot above on i or j refused. Not stopped: whole-script lookalikes and other same-script lookalikes (no UTS 39 confusables check), see Out of scope | A090 |
| Escaping a per-user tRPC rate limit, or spending another user’s budget | The user part of the key comes only from the session the core accepted, as an HMAC under a key derived from the server secret; a refused or made-up cookie counts by client IP | A094 |
Reusing an imported recovery code (opt-in importedRecoveryCodes) |
Accepted only if the store deletes it, under a prefix the plugin’s own hash never takes; counted in the factor budget; the first one to pass a login challenge replaces the whole set once the session is issued (a refused login leaves the rest in place), so the rest of the old hashes leave the store; of two logins racing with two imported codes only one replaces the set and shows it. Not stopped: an imported hash keeps the old scheme’s strength (an unsalted one is not bound to the user) until the user moves over | A095, A098 |
Accepting an invitation without a session (opt-in acceptWithoutSession) |
The option is off by default, and a null session is refused before the token is looked up; with it on, only the verified holder of the invited address joins, nothing is spent for an unverified one, the inviter is checked again, and no session is issued. Not stopped: whoever reads a leaked or forwarded link can attach the account to the inviting scope without its password, and a link scanner can do it for the owner unless the app accepts only on a POST | A096 |
Bringing back a revoked session through the legacy store an app adopts sessions from (adoptLegacySessions) |
The old record is removed before the session is written, so it is adopted at most once; the adopted session carries epoch 0, so a revocation of the user since the switch refuses it; its expiry never passes the old expiry or maxTtl after its creation; expired, future-dated and malformed records are dropped |
A097 |
| An address a mail header reads as several recipients, or whose domain is more than a host | Every policy, built in or custom, refuses whitespace, control characters and every RFC 5322 special besides the one @ (, ; : < > ( ) " \ [ ]), so lists, group syntax, comments, quoting and domain literals never reach the store or a mail header; every built-in policy takes only a host name as the domain (letter-digit-hyphen labels of at most 63, none empty, a last label that is not all digits), so an IPv4 address (127.0.0.1, 127.1) or a label such as exa_mple is refused; under the unicode policy the domain also has no port, path, query, fragment, credentials or percent escape, every label of its ASCII (punycode) form is letters, digits and inner hyphens (at most 63) and decodes back to exactly the label typed, so nothing UTS 46 would remap is accepted (an ideographic full stop for a dot, a Greek iota subscript, an old Cyrillic letter form, 127.1) |
A099 |
| Keeping a revoked session alive on a tRPC WebSocket connection | The WebSocket adapter is not supported yet: the tRPC context refuses a response that cannot set headers (the adapter’s socket) before it reads a cookie or validates a session, so no connection gets a context | A103 |
| Writing the session from a tRPC query that a link on another site can run | writesCookies (and WritesCookiesMiddleware on nestjs-trpc) refuses every call that is not a mutation, and runs the CSRF check itself on the mutation, before the procedure runs, so only a mutation that passed the CSRF check gets the cookie writers, even on a bare t.procedure; assertProceduresGuarded names a marked query or subscription |
A104 |
| A forwarded entry that is not one address (a port, or junk from a proxy) | The picked X-Forwarded-For entry has its port, brackets and IPv6 zone id stripped and must then be exactly one IP, with a hop count or a proxy list; otherwise the socket address stands in for it | A105 |
| Keeping a revoked session alive on an open tRPC SSE subscription | Every session check keeps a subscription’s events behind it: before an event leaves, when the last check that saw the session live started longer ago than revalidateSubscriptions (default 30s), the session is validated again without a touch and its user loaded, and a refusal ends the stream in place of the event. The bound is read on the core’s clock, which is not monotonic: a backwards step delays the next check |
A107 |
A report that breaks one of these defenses, or shows an attack the table misses, is a vulnerability: see SECURITY.md.