Configuration
createAuth(config) takes one object, typed AuthConfig (packages/auth/src/core/config.ts). Only four keys are required. Everything else has a default chosen for safety first: where published guidance disagrees, the stricter value wins. The configuration is checked once, at startup, and anything unsafe throws an AuthConfigError before the app serves a request; Startup checks lists every refusal.
Click a key for its link. Paths are relative to packages/auth/src/ unless they name another package. Full types are in the API reference.
Most apps set only these
Section titled “Most apps set only these”| Key | Default | What it does |
|---|---|---|
storesobject | required | Users and tokens from @noctcore/auth-prisma, sessions and counters from @noctcore/auth-redis. |
password.PasswordHasher | required | argon2id() from @noctcore/auth/argon2. |
secretstring | Uint8Array | required | The server secret, at least 32 bytes, kept apart from your CSRF secret. |
mailerMailer | required | Enqueues each mail; flows never await it. |
urls.(token) => string | none | Required for link resets, which are the default. |
password.BreachChecker | false | none | Pass pwnedPasswords() to refuse passwords from known breaches. |
session.boolean | true | Set false only for plain-HTTP local development. |
The rest keep their defaults. The full shape writes every group out with its default values.
Durations
Section titled “Durations”Every time option takes a Duration: a number is seconds, a string carries its unit, one of ms, s, m, h or d ('15m', '1h', '30d'). One parser reads them all, so a TTL can never be read as milliseconds in one place and seconds in another. Source: shared/duration.ts.
Required
Section titled “Required”Source: create-auth.ts (assertRequiredConfig), crypto/keys.ts.
| Key | Default | What it does |
|---|---|---|
stores.UserStore | required | Users and their password hashes. @noctcore/auth-prisma ships one. |
stores.TokenStore | required | One-time codes and links, stored only as hashes. @noctcore/auth-prisma ships one. |
stores.SessionStore | required | Sessions. @noctcore/auth-redis ships one. |
stores.CounterStore | required | Rate limits and lockout. @noctcore/auth-redis ships one. |
password.PasswordHasher | required | Use argon2id() from @noctcore/auth/argon2. |
secretstring | Uint8Array | required | The server secret, at least 32 bytes. See what rotating it does. |
mailerMailer | required | send(event) enqueues the mail. See Mail into your templates and queue. |
Any store that passes the conformance suite in @noctcore/auth/testing is valid; see Writing a store adapter. Flows never await the mailer, and each mail is handed over at most once. Keep secret apart from your CSRF secret.
What rotating the secret does
Section titled “What rotating the secret does”Separate keys are derived from secret for code HMACs, trusted-device tokens, session handles and plugins’ keyed hashes (such as the two-factor recovery codes), so one key never serves two purposes. Source: crypto/keys.ts, core/plugin-context.ts.
Rotating with previousSecret. Deploy the new value in secret and the one it replaced in previousSecret (a list, newest first, if a second rotation starts before the first ends):
| Key | Default | What it does |
|---|---|---|
previousSecretstring | Uint8Array | a list of them | none | The secret, or secrets newest first, that a rotation replaced, kept for a grace window. Each at least 32 bytes, and different from secret and from each other. An empty string is refused, not read as unset. |
Every key is derived from each secret too, so these keep verifying during the grace window, while everything new is made under secret only:
- outstanding codes and trusted-device cookies;
- session handles: a handle listed before the rotation still revokes its session, and
sessions.listshows the new handles at once; - two-factor recovery codes, through the plugins’ keyed hashes;
- invitations created before 0.6, which are found through a fallback lookup under their old keyed hash (it tries each previous secret as well) until they expire.
Sessions and invitations created since 0.6 never depend on the secret: an invitation token is stored as a SHA-256, under no key.
Remove previousSecret once the longest-lived value has expired: the trusted-device cookie (throttle.lockout.deviceMaxAge), and the recovery codes that users made before the rotation, which never expire. Ask every user with a factor to make a new set first, counting from the point where every instance runs the new secret (after the second deploy of a rolling deploy; a set made earlier is made under the old secret and stops working when previousSecret goes), or accept that their old codes stop working. Leave the key out, or pass undefined, when no rotation is under way: an empty string is not “unset”, and startup refuses it as shorter than the minimum.
Rotating without it invalidates all of the following at once:
- outstanding codes and device cookies;
- every session handle: a client holding an old one gets
{ revoked: false }and must list again (see Session handles); - every recovery code of the two-factor plugin, because their HMAC key is derived from the secret: have every user with a factor regenerate their recovery codes;
- invitations created before 0.6, found through a fallback lookup under their old keyed hash until they expire.
Sessions themselves never depend on the secret, so no rotation signs anyone out.
After a suspected leak, rotate without previousSecret, or keep the window to minutes. While the old secret is configured it is still accepted: whoever holds it can forge device cookies and code HMACs that verify.
Rolling deploys. An instance still configured with the old secret alone cannot verify a code, device cookie or handle that an instance on the new one issued, so those fail on it until the roll-out ends. To avoid the gap, deploy twice: first with the current secret in secret and the new one in previousSecret, so every instance can verify under both, then swap them.
Password
Section titled “Password”Source: password/policy.ts, password/breach.ts, create-auth.ts. Why these defaults: Passwords.
| Key | Default | What it does |
|---|---|---|
password.number | 12 | The shortest password accepted. A configured minimum below 8 is refused. |
password.number | 256 | Bounds the hashing work one request can make the server do. |
password.BreachChecker | false | none | Pass pwnedPasswords() to refuse passwords from known breaches (recommended). Fails open. |
The minimum is stricter than the auth guide’s 8 or 10.
Length is counted in Unicode code points of the NFC form, so the same password typed on a phone and a desktop has the same length.
No composition rules (“one digit, one symbol”): they push people toward predictable patterns, as NIST SP 800-63B notes, and the breach check does the job they were meant to do.
The breach check. false or leaving it out runs no check. The check fails open: an outage accepts the password and is logged, counted and written to the audit trail as password.breach_check_unavailable. Only the first five hex characters of the password’s SHA-1 leave the server.
pwnedPasswords(options)
Section titled “pwnedPasswords(options)”| Option | Default | What it does |
|---|---|---|
timeoutMsnumber | 3000 | How long to wait for the range API, in milliseconds. |
fetchtypeof fetch | global fetch | The fetch to call it with. |
userAgentstring | 'noctcore-auth' | The User-Agent header sent. |
baseUrlstring | 'https://api.pwnedpasswords.com/range/' | The public range API. |
onResult(outcome) => void | none | Called with every outcome, to log or count it. Not awaited. |
loggerLogger | silent | Where a throw from onResult is reported. |
onResult is called with every outcome ({ verdict, reason?, status? }) to log or count it; it is not awaited, cannot change the verdict, and a throw is reported to logger. The checker’s check(password) returns the same outcome. Outcomes never carry the password, its hash or the prefix. The reasons are listed in Passwords.
Session
Section titled “Session”The session key takes the session options and three more keys, cookie, freshAuthAge and requireFreshAuth. Source: session/session-types.ts, session/session-manager.ts, flows/resolve-settings.ts. Why these defaults: Sessions and expiry.
| Key | Default | What it does |
|---|---|---|
session.Duration | '24h' | A session without "remember me" ends this long after sign-in, however active it is. |
session.Duration | '30d' | The absolute lifetime with "remember me". At most the session store's maxSessionTtlMs. |
session.Duration | (context) => Duration | '30m', or '7d' with "remember me" | Ends sessions left open on a shared machine. |
session.Duration | '60s' | Last-active is written at most this often, and only for a request that counts as activity (see the adapters' touch option). Must be shorter than the idle timeout: a fixed one is checked at startup, the value of an idleTimeout function at each sign-in. |
session.number | null | 10 | The oldest sessions beyond the cap are evicted when a new one is issued. null for no cap. |
session.AttributeSchema | none | A schema with a zod-style parse, run on every read. Required when you declare session attributes. |
session.Duration | '10m' | How recent a credential proof must be for the doors that ask for one: revoking another session or every other session, the email change, two-factor enrollment and management, step-up. |
session.boolean | true | Whether sessions.revoke asks for a proof inside freshAuthAge to end another device's session. false still needs a live session of the same user. |
session.boolean | true | Whether sessions.revokeOthers asks for a proof inside freshAuthAge. false still needs a live session of the same user. |
absoluteTtl bounds what a stolen cookie is worth.
rememberMeTtl must not exceed the session store’s maxSessionTtlMs (the Redis store’s maxSessionTtl, also 30 days by default).
idleTimeout also accepts a function of { rememberMe, attributes }, decided per session at sign-in. Its value must be longer than touchInterval, like a fixed one: otherwise a session in steady use is never touched and expires as idle while its user is active. The startup check cannot see a function’s values, so the sign-in that gets a value no longer than touchInterval throws an AuthConfigError before any session is written.
touchInterval: last-active is written at most once a minute instead of on every request.
attributes: the schema makes a corrupt or old record refused, not trusted. Attributes that fail it when a session is issued are logged (‘Session attributes failed the schema at issue time’) and refused: as invalid_credentials with a login.failure row after a correct password, so a caller cannot tell it from a wrong password, and as forbidden on every other path (reason invalid_session_attributes on both).
Evictions at the cap
Section titled “Evictions at the cap”The oldest sessions beyond session.maxPerUser are evicted after the new one is written, so concurrent sign-ins converge on the cap. They are picked by creation time, then by id, and never include the session being issued, even when its creation time ties an older one or its instance’s clock is behind. A session written while the sign-in ran is evicted only if it sorts before the new one, so two sign-ins racing at a cap of one leave exactly one. A sign-in that stalls before its write can leave one session over the cap until the next sign-in, and sign-ins on instances whose clocks disagree can, rarely, evict each other. Each sign-in reads the user’s sessions once more, before its write, when a cap is set.
- The issued session lists the evicted sessions’ handles in
evictedHandles(safe for a client) and their store keys inevicted(server-side only). onSessionsRevokedhears of them with reasonevicted, so you can close their sockets and drop their caches.- Each eviction is reported once, even when sign-ins race at the cap or race a sign-out of the same session, provided the session store’s
deletereturns the ids it removed (the memory and Redis stores do).
Fresh authentication
Section titled “Fresh authentication”session.freshAuthAge is how recent a credential proof must be at the doors that ask for one: revoking another session or every other session (so a stolen session cannot sign the owner out), asking for an email change, and the two-factor plugin’s enrollment, management and step-up.
- The library’s own doors (revoking devices, second-factor enrollment, step-up) read it from the live session in the store.
- Your own routes can ask for it with
auth.requireFreshAuth(session), which checks the object you pass, so pass the sessionvalidateRequestjust returned. - Plugins have
context.requireFreshLiveSession(session), which re-reads it.
session.requireFreshAuth turns the check off at one or both session management doors, for an app where “sign out that device” and “sign out everywhere else” are plain self-service actions behind a live session:
session: { requireFreshAuth: { revokeSession: false, revokeOtherSessions: false } }revokeSession: false:sessions.revokeends another device’s session without a recent proof.revokeOtherSessions: false:sessions.revokeOtherssigns out every other device without one. The re-issued session keeps the old proof time, so it is no fresher than the one it replaces.- Both default to
true. Withfalsethe door still needs a live session of the same user and answerssession_expiredotherwise; only the age check is skipped. freshAuthAgeand every other door (the email change, two-factor enrollment and management, step-up, your ownrequireFreshAuthcalls) are unchanged. RaisingfreshAuthAgeinstead would turn the check off at all of them.- The trade: whoever holds a stolen session can then sign the owner’s other devices out without knowing the password. It gains no access by that, and the owner who spots a strange device can end it at once.
- With
revokeOtherSessions: false, a stolen session that is old but still live can callrevokeOthersagain and again, so each time the owner signs back in they are signed out. Signing out the strange device in return does not settle it while the attacker keeps a session. The owner’s way out ischangePassword(or a reset), which revokes every session, the attacker’s included, and asks for the current password, which the attacker does not have. Point users to it from your devices page.
Session cookie
Section titled “Session cookie”Source: http/cookie.ts. Why these defaults: Cookies and desktop shells.
| Key | Default | What it does |
|---|---|---|
session.string | 'session' | Base name; __Host-session when Secure. Letters, digits, _ and - only. |
session.boolean | true | Turn it off only for plain-HTTP local development. Off also drops the __Host- prefix. |
session.'lax' | 'strict' | 'none' | (origin) => SameSite | 'lax' | Keeps the cookie off cross-site subrequests and form posts while links into the site still work. |
name. When the cookie is Secure the name becomes __Host-session: the browser then requires Secure, Path=/ and no Domain, so a sibling subdomain cannot set or overwrite it.
secure: false also drops the __Host- prefix from the device cookie (device instead of __Host-device).
sameSite accepts a function of the request’s Origin, for an app that also serves a desktop shell. The trusted-device cookies and the NestJS and tRPC adapters’ CSRF, pre-session and blank session cookies get the same answer.
The cookie is always HttpOnly. A session without “remember me” gets a browser-session cookie (no Max-Age).
Email addresses
Section titled “Email addresses”Source: shared/email.ts. Why the default: Email and requests in the design choices.
| Key | Default | What it does |
|---|---|---|
email.'standard' | 'ascii' | 'unicode' | (email) => string | null | 'standard' | How every address is normalised before it is compared, stored or used as a counter key. An unknown name is refused at startup. |
The policy applies everywhere: every flow and plugin, and auth.normalizeEmail.
The built-in policies
Section titled “The built-in policies”| Policy | What it does |
|---|---|
'standard' |
Trims, lowercases A to Z and refuses any non-ASCII character (invalid_email), so Unicode case folding can never merge two addresses. |
'ascii' |
Stores the same spelling as 'standard', but answers a non-ASCII address with email_not_ascii, so you can say why. |
'unicode' |
Keeps Unicode addresses: NFC, then lowercase of the domain and the local part. The details follow. |
'unicode' folds the local part too. The Greek final sigma is folded to the plain one in the local part only (a domain keeps a typed final sigma, which IDNA2008 treats as its own letter, while a capital sigma lowercases to the plain one). No mainstream provider treats the local part as case-sensitive, and folding it stops case-collision takeovers.
'unicode' refuses invisible, bidi, control and compatibility characters (fullwidth letters, ligatures), punycode labels (send the Unicode form), any part that mixes scripts, apart from the Chinese, Japanese and Korean mixes with Latin, and the Latin letters that read as other Latin ones it knows about: the dotless i, the IPA Extensions block (U+0250 to U+02AF) and a combining dot above on i or j.
'unicode' domains also have no port, path, query, fragment, credentials or percent escape. Every label of the domain’s 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).
What every policy refuses
Section titled “What every policy refuses”- An address with whitespace, a control character or an RFC 5322 special besides the one
@(, ; : < > ( ) " \ [ ]): an address parser must read it as one plain mailbox. - A domain that is not a host name. Every built-in policy takes only letters, digits and inner hyphens per label, at most 63, no empty label, and a last label that is not all digits, so
exa_mple.com,-example.com,example..comand an IPv4 address such as127.0.0.1or127.1are refused.
Surrounding whitespace. Every policy trims with String.prototype.trim, which also strips Unicode whitespace (a no-break space, an ideographic space) around the address, not only ASCII spaces and tabs. ascii trims exactly like standard, so the two always store the same spelling.
A custom normaliser
Section titled “A custom normaliser”Or pass (email) => string | null, your own normaliser. Return null for an address you refuse; it is answered invalid_email. Refusing whole domains is fine.
It must be pure, deterministic and idempotent: normalize(normalize(x)) === normalize(x), because a stored address is normalised again every time it is compared.
Its result must be null or an address of at most 254 bytes with exactly one @, a non-empty local part and domain, and no whitespace, control characters or RFC 5322 specials (, ; : < > ( ) " \ [ ]; the address goes into mail headers). A normaliser that passes a quoted local part such as "quoted"@example.com through fails the startup check.
createAuth tests it at startup over a sample of addresses (mixed case, IDN, decomposed accents, confusables, junk) and refuses to start if it throws, returns anything else, answers differently twice, is not idempotent, or gives the same result for different mailboxes it accepts (alice@example.com and bob@example.com, or one local part at two domains), so a constant or domain-only normaliser fails at startup.
On each call an address whose result is unusable or not a fixed point is refused and logged. When it throws, the address is refused and the log line carries only the error’s class name (errorName), never its message, which could quote the address.
Living with the policy
Section titled “Living with the policy”Lookups are exact. The core treats a user row whose stored address is not exactly the one it asked for as not found, so a store whose lookup goes through a case- or accent-insensitive collation cannot hand one account to several spellings. Prefer a binary or accent-sensitive collation on the email column anyway; see the Prisma adapter’s README.
Use the same normaliser in your own code. auth.normalizeEmail(email) gives the configured spelling, or null. Call it wherever your app stores or looks up an address outside the flows (an admin create, an import, an SSO first login), never a fixed function. The exported normalizeEmail is the standard policy only.
Upgrading: check rows written outside the flows. Lookups by address are exact, whatever the policy: a user row whose stored email is not exactly what the normaliser produces counts as not found. A row written by an import, an admin tool or a seed in another spelling (uppercase letters, surrounding whitespace, a non-ASCII character under the default policy) is unreachable even if you never change email.normalize.
Before upgrading, find the rows where the stored email differs from auth.normalizeEmail(email), then rewrite them or merge the duplicates. Each time the store returns such a row for a lookup, the core logs a warning with the user id (never the address), so rows you missed show up in your logs. Behind a case- or accent-insensitive collation that warning repeats on every lookup of such a row and can be noisy; rewrite the rows or make the column binary to silence it.
Upgrading: domains that are not host names. The standard and ascii policies take only a host name as the domain, as unicode does: letters, digits and inner hyphens per label (at most 63), no empty label, and a last label that is not all digits. They used to check only for one inner dot, so a stored address whose domain is an IPv4 address (127.0.0.1, 127.1), has an underscore or another character outside a host name, or a label that is empty, starts or ends with a hyphen or is longer than 63 is now refused: its owner can no longer sign in, reset or be found by address, and a pending invitation to it cannot be accepted.
An outstanding email change or verification token that names such an address can no longer be redeemed either: the flows normalise the address again when the token is used and refuse it (they fail closed), so the user has to start the change or request a new mail with a valid address. Find such rows before upgrading and rewrite or remove them. In PostgreSQL:
SELECT id, email FROM users -- your user tableWHERE split_part(email, '@', 2) !~ '^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' OR split_part(email, '@', 2) ~ '\.[0-9]+$';
SELECT id, email FROM "AuthInvitation"WHERE split_part(email, '@', 2) !~ '^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' OR split_part(email, '@', 2) ~ '\.[0-9]+$';On another store, run the check above in your own code: every row where auth.normalizeEmail(email) is not exactly the stored email, which also finds these.
Registration
Section titled “Registration”Source: flows/resolve-settings.ts. Why these defaults: Enumeration.
| Key | Default | What it does |
|---|---|---|
registration.boolean | false | A taken address gets the same answer as a new one, and its owner an account-exists mail. true answers email_in_use. |
registration.boolean | false | Issue a session on registration. Allowed only with revealExisting. |
revealExisting: false means registration cannot tell anyone who has an account.
autoLogin needs revealExisting, or the session would reveal that the account is new. Issuing it is work only a new address does, so it shows in sign-up timing, which the email_in_use answer already gives away.
Email verification
Section titled “Email verification”Source: flows/resolve-settings.ts. Why these defaults: Email verification.
| Key | Default | What it does |
|---|---|---|
emailVerification.'code' | 'link' | 'code' | A code typed by the signed-in user ties the proof to that account's session. 'link' needs urls.verifyEmail. |
emailVerification.Duration | '15m' for codes, '24h' for links | A short code is guessable over time, so it lives briefly; a 32-byte link is not, so it can wait in an inbox. |
emailVerification.number | 8 | The auth guide's length. Must be 6 to 9. |
emailVerification.number | 5 | Wrong guesses per code, counted atomically before each comparison. |
emailVerification.boolean | false | Link verification only. Also accepts a valid link opened with no session, and signs nobody in. |
linkWithoutSession verifies the address and revokes every session, but signs nobody in. A session of another account is still refused. It is refused at startup with codes, and anything but true or false is refused. See Email verification for the trade-off.
Password reset
Section titled “Password reset”Source: flows/resolve-settings.ts, flows/password-reset-request.ts. Why these defaults: Password reset.
| Key | Default | What it does |
|---|---|---|
passwordReset.'link' | 'code' | 'link' | A single-use link of 32 random bytes. 'code' mails digits exchanged for a short ticket. Links need urls.resetPassword. |
passwordReset.Duration | '1h' for links, '15m' for codes | Long enough to reach the inbox, short enough that an old mail is useless. |
passwordReset.number | 8 | Must be 6 to 9. |
passwordReset.number | 5 | Wrong guesses per code. |
passwordReset.Duration | '10m' | How long the ticket a verified code becomes can set the password. |
passwordReset.(job) => Promise<void> | none | Puts the request on your queue; your worker calls auth.jobs.processPasswordReset(job). |
passwordReset.boolean | true | A completed reset proves the mailbox, so it marks the address verified. |
Without enqueue the job runs detached in-process, which keeps the response time independent of the address but is lost if the process dies.
Email change
Section titled “Email change”Source: flows/resolve-settings.ts, flows/email-change.ts. Why these defaults: Email change.
| Key | Default | What it does |
|---|---|---|
emailChange.'code' | 'link' | 'code' | A code typed in the signed-in session of the same account. 'link' needs urls.confirmEmailChange and works only in such a session. |
emailChange.Duration | '15m' for codes, '1h' for links | How long the code or link works. |
emailChange.number | 8 | Must be 6 to 9. |
emailChange.number | 5 | Wrong guesses per code, counted atomically before each comparison. |
emailChange.Duration | '7d' | How long the revert link mailed to the old address works. Shorter is refused: the owner may be away for a week. |
emailChange.Duration | '30d' | After a revert, how long the account may not change to the address it lost. |
The flows also need urls.revertEmailChange and a user store with changeEmail, and throw an AuthConfigError on the first call without them. See Email change.
Source: core/config.ts, flows/resolve-settings.ts.
| Key | Default | What it does |
|---|---|---|
urls.(token) => string | none | Required for link verification. |
urls.(token) => string | none | Required for link resets, which are the default, so most apps set it. |
urls.(token) => string | none | Required for link email changes. |
urls.(token) => string | none | The revert link of an email change; the email change flows throw without it. |
Put the token in the path or the fragment, not the query string, and send Referrer-Policy: no-referrer on those pages so the token does not leak to other sites.
Throttle
Section titled “Throttle”Two keys: throttle.lockout for the login lockout, throttle.doors for the per-door rate limits. Each rule is { limit, window }; a part you leave out keeps its default.
Lockout
Section titled “Lockout”The login lockout. Source: throttle/rules.ts, throttle/throttle.ts; the reasoning is in Brute force and lockout.
| Key | Default | What it does |
|---|---|---|
throttle.RateLimitRule | 5 per '15m' | Stops one source guessing at one account without touching the owner on another network. |
throttle.RateLimitRule | 10 per '15m' | Against guessing spread over many sources: close to one attempt a minute. Spending it locks the account. |
throttle.Duration | '5m' | The first lock. Each further lock multiplies it by 3. |
throttle.Duration | '1h' | Cap on a single temporary lock. |
throttle.Duration[] | none | Your own ladder of lock durations in place of baseLock and maxLock: lock N lasts entry N, the last repeats. See Lock durations. |
throttle.Duration | '24h' | The backoff resets only after this long without a new lock. |
throttle.RateLimitRule | 5 per '15m' | Under a lock, the attempts a trusted device gets, and the budget all of an account's devices share. |
throttle.Duration | '30d' | The oldest trusted-device cookie accepted, checked on use. At least a minute (the clock skew a device cookie is allowed) shorter than the session store's epochTtlMs. |
throttle.{ afterLocks, trustedDevices? } | off | Opt in to a lock that holds until an admin clears it. See The permanent tier. |
throttle.boolean | true | Whether the owner's trusted-device cookies still sign in through a permanent lock. |
throttle.boolean | false | Answer account_locked from login, with retryAfterSeconds for a temporary lock, instead of invalid_credentials. |
throttle.boolean | true | Whether a correct password spends perAccount. false: a completed sign-in hands its slot back, so only failures count. See Counting successes. |
throttle.'lockout' | 'door' | 'lockout' | What bounds the password proved again at reauthenticate and changePassword: login's budgets, or ('door') only each door's own limit, so a stolen session cannot lock the owner out by guessing passwords at these two doors. Wrong second-factor codes at a step-up still lock the factor and count toward the permanent tier. See Session proofs out of the lockout. |
No permanent lock by default. maxLock caps every temporary lock, and there is no permanent lock unless you opt into permanent, because a permanent lock lets an attacker lock the owner out.
Device cookies. Holding many device cookies adds no guesses: perDevice is also the budget all of an account’s devices share.
Session doors. reauthenticate and changePassword spend these same budgets: perAccountIp and perAccount while the account is unlocked, and under a lock the live session counts as one more device in perDevice. Guesses through login and both doors add up. A correct proof while the account is unlocked still counts toward perAccount (success returns only the perAccountIp slot, as at login), so an app that asks for re-authentication very often can lock its own user and send a lock notice; with countSuccesses: false the correct proof hands its perAccount slot back at once, since the caller already holds a session. Under a lock, a stolen session can spend the perDevice budget shared by every device of the account, which refuses the owner’s device cookie until the lock ends; a password reset clears the lock and ends every session. Second-factor codes have their own budget and do not draw on these. With sessionProofs: 'door' none of this applies: see Session proofs out of the lockout.
deviceMaxAge must be at least a minute shorter than the session store’s epochTtlMs (the Redis store’s epochTtl, 90 days by default). A device cookie is revoked only by the user’s revocation epoch, and a store that forgets an epoch reads it as 0 again, so a cookie revoked by a sign-out everywhere would verify once more after the lapse. The minute is the clock skew a cookie is allowed: its issue time comes from the server that set it, which may run ahead, so equal values are refused too.
revealLocked. Unknown addresses lock and answer the same, but the answer tells anyone that the address is locked and when it lifts: an enumeration signal the generic answer does not give. Pair it with a captcha and per-IP rate limits.
Lock durations
Section titled “Lock durations”By default a lock lasts baseLock, multiplied for each lock in a row and capped at maxLock. durations replaces both with a ladder you write out: the first lock in a row lasts the first entry, the next the second, and once the list runs out every further lock lasts the last entry. ['15m', '1h'] locks for 15 minutes, then an hour each time after, until quietPeriod passes with no new lock and the ladder starts over. The two-factor plugin’s factor locks share the password lockout’s backoff, so they climb the same ladder (in their own count). Startup refuses an empty list, an entry that is not a duration or is zero, and durations together with baseLock or maxLock, since one of them would be ignored.
Session proofs out of the lockout
Section titled “Session proofs out of the lockout”By default (sessionProofs: 'lockout') a password proved again from a live session, at reauthenticate and changePassword, spends login’s budgets, as above. So whoever holds a session, a stolen one included, can lock the owner out of sign-in by guessing wrong current passwords, send the lock mail, and with the permanent tier on, climb toward a lock for good.
With sessionProofs: 'door' the lockout is left out of those two doors. Each door’s own per-user limit (throttle.doors: password-change and reauthenticate, 5 per '5m' by default) is the only budget. A wrong password writes password.change_failed and touches no lockout counter: no lock, no lock mail, nothing toward the permanent tier. A temporary lock does not refuse a correct password from a live session. The permanent tier still refuses these doors exactly as it does by default, which is only with permanent.trustedDevices: false (with trusted devices on, a session from a device sign-in may prove its password under a permanent lock in either mode).
The trade-off: guesses from a stolen session are bounded by the doors’ rate instead of login’s, and they never lock anything, so they can go on all day. Each door counts on its own key, so the defaults allow 1440 a day per door, 2880 across both. A correct guess still needs the live session, and the session ends when the password changes or is reset. The owner hears nothing of it: no lock, so no lock mail, and the library sends no other notice. The guesses show only as password.change_failed events (reason wrong_password:password-change or wrong_password:reauthenticate) in your audit sink, so if you want the owner told, count those per user and alert from there. Keep the door limits as tight as your users allow.
'door' covers passwords only. Wrong second-factor codes at a step-up (twoFactor.stepUp) are not covered: they still count in the factor’s budget, the one login’s challenge uses, so a stolen session can still lock the factor, and each factor lock counts toward the permanent tier.
Counting successes
Section titled “Counting successes”By default a correct password spends a slot of perAccount like a wrong one: only its own source’s slot (perAccountIp, or a device’s) comes back. A user who signs in many times within the window, from several devices or a script, can lock their own account.
With countSuccesses: false the perAccount slot comes back too, so only failures count. It comes back when the sign-in completes (its session is issued with via: 'password' or via: 'second-factor', every factor proved), not when the password proves right: a correct password that opens a second-factor challenge keeps spending until the factor is proved. At reauthenticate and changePassword it comes back right after the correct password. A completion hands back at most one slot, and never more slots than correct passwords reserved in the current window, however many sign-ins complete at once. Refunds are capped per window and matched by count, not to the attempt that earned them: a completion that reserved nothing of its own (a challenge opened in an earlier window, a device sign-in) can take a slot another correct password in the window is owed. Slots owed in a window that ended, a lock included, never come back in the next. 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.
The trade-off: an attacker who also holds the password could sign in between guesses to win budget back. That only matters together with a second factor, and there the slot comes back only once the factor is proved.
The permanent tier
Section titled “The permanent tier”throttle.lockout.permanent takes { afterLocks, trustedDevices? }.
- When it locks. After
afterLockstemporary locks in a row (each withinquietPeriodof the last; a completed sign-in or a completed password reset resets the count), the next lock holds until an admin callsauth.lockout.clear. The count takes password locks and the two-factor plugin’s factor locks alike. A sign-in completes when its session is issued withvia: 'password'orvia: 'second-factor'(every factor proved); a correct password with a second factor still owed, or atreauthenticateorchangePassword, does not reset it. A password reset does not lift it.afterLocksmust be a whole number of at least 1. - What it locks. For an address with an account the lock is kept under the user id, so it follows the account through an email change, and it ends the account’s sessions. For an address with no account it is kept under the address, and a sign-up on that address clears it.
- Turning it off later stops login reading its marker, but
auth.lockout.inspectstill reports a leftover permanent lock untilauth.lockout.clearlifts it.
trustedDevices: true (the default): the lock deletes the account’s sessions but keeps its device cookies, so the owner can still sign in from a known device with the usual device budgets. A session from such a sign-in may reauthenticate and change the password, but no session may change the email. With sessionProofs: 'door' those two doors give a session the door’s rate of password guesses instead of the perDevice budget it shares with every device of the account. Other ways in still mint a session in this mode, each needing a correct password or your SSO: an app’s SSO through issueSession, a two-factor challenge started before the lock, and a login racing the revocation. The default mode adds no read per request.
trustedDevices: false: the lock bumps the revocation epoch (every session and device cookie ends) and refuses every session door (issuing a session by any path, validating one, reauthentication, password change, email change, email verification) until an admin clears it. Because validation checks the lock, a session the background revocation failed to end is refused, and revoked, on its next request.
Inspecting and clearing locks
Section titled “Inspecting and clearing locks”auth.lockout.inspect({ email })or({ userId })returns{ locked, permanent, until }for an address.auth.lockout.clear({ email | userId, meta })lifts every lock on it, the permanent one included, resets its backoff, returns the state it found and writes anaccount.lock_clearedaudit row. The clear is not atomic: a burst of failures running during it can lock the account again as soon as it is lifted.- Both answer for any address, known or not, so expose them only on admin routes.
- The
onPermanentLockhook ({ userId, email, meta }) runs off the response path when the permanent tier locks an account, after its sessions end (onSessionsRevokedhearslocked-permanently), beside theaccount.locked_permanentlyaudit row and alockoutmail withpermanent: true.
Source: flows/lockout-admin.ts, flows/lock-notice.ts.
Counting your own proofs
Section titled “Counting your own proofs”For a proof your app checks itself (its own second factor, a PIN), outside login’s gate:
auth.context.recordFailedProof({ userId | email, meta })counts a failure in the address’s account-wide budget, the one login spends. A lock it sets is carried out like a password lock (thelockoutmail, theaccount.lockedaudit row and, in the permanent tier, the end of the sessions andonPermanentLock), off the response path, and counts toward the permanent tier. It returns{ newLock? }. An address with no account counts the same and nobody is told. Pass only the account the request is already acting on (the user of its session or challenge): it locks whatever account it is pointed at, so a target taken from the request body lets anyone lock any account.auth.context.escalateLock({ userId, meta }), for a proof with its own budget and lock: call it once for each new lock it sets. Withpermanenton, the lock counts toward the tier in the same count as the password locks, and a permanent lock is carried out the same way. It does nothing whilepermanentis off.auth.context.throttle.recordFailureonly counts: a lock reached through it sends nothing. PreferrecordFailedProof.
Source: core/auth-core.ts, core/plugin-context.ts.
Door limits
Section titled “Door limits”throttle.doors overrides the per-door rate limits, each a { limit, window } rule. Doors are keyed by client IP unless noted. Every limit fails closed: a counter store that cannot answer refuses the request. Source: DEFAULT_DOOR_LIMITS in core/config.ts.
| Door | Default | Keyed by |
|---|---|---|
login | 10 per '1m' | IP |
register | 10 per '1m' | IP |
password-reset-request | 10 per '1m' | IP |
password-reset-mail | 3 per '1h' | User: reset mails one account can receive. Spent before the mail is handed over. |
password-reset | 10 per '1m' | IP |
password-reset-code | 10 per '1m' | IP |
password-reset-code-address | 5 per '15m' | Address: code guesses for one email from every IP. |
email-verification | 10 per '1m' | IP |
email-verification-request | 3 per '1h' | User: verification mails one account can request. Spent before the mail is handed over. |
password-change | 5 per '5m' | User. Each attempt also spends login's lockout budgets (throttle.lockout). |
reauthenticate | 5 per '5m' | User. Each attempt also spends login's lockout budgets (throttle.lockout). |
email-change-request | 3 per '1h' | User: email change requests one account can make. Spent before the mail is handed over. |
email-change-address | 3 per '1h' | Address: email change requests naming one new address, from every account. |
email-change | 10 per '1m' | IP: confirming an email change. |
email-change-revert | 10 per '1m' | IP: using a revert link. |
Mail budgets are spent before the mail is handed over. password-reset-mail, email-verification-request and email-change-request count a request even when its mail is then dropped or fails (see Mail).
The per-address door has a trade-off: anyone who knows an address can spend its budget and block that address’s code-mode reset for 15 minutes. Link-mode reset, the default, does not use it.
Collaborators
Section titled “Collaborators”None of these is required. Source: core/config.ts, create-auth.ts, ports/.
| Key | Default | What it does |
|---|---|---|
captchaCaptchaVerifier | none | Checked on login, register and the reset request. Fails closed with captcha_unavailable. |
auditAuditSink | none | Every flow emits an event for each success and each refusal, with the internal reason. |
hooksAuthHooks | none | Functions the flows call at fixed points. A hook can refuse with refuse(code, reason). |
pluginsAuthPlugin[] | [] | Plugins add hooks and flows, never endpoints. A plugin's flows appear on the auth object under its id. |
loggerLogger | silent | Where the package reports what it cannot return. Messages never carry secrets. |
metricsMetrics | no-op | Counters such as breach check outages and door refusals. Labels never carry user input. |
background.(promise) => void | none | Handed every background task's promise as it starts, so a runtime that freezes after the response keeps it alive. |
background.Duration | none | Stop waiting on a task after this long; logged and counted as timed_out. The task is not cancelled. |
background.number | none | While this many tasks are still running, new ones are dropped, logged and counted as dropped. |
clockClock | system clock | Injectable so tests move time instead of sleeping. |
randomRandomSource | crypto.getRandomValues | Injectable for tests. |
audit. Events that record a grant are awaited before the grant is returned; a failing sink never fails the flow.
plugins. The two-factor plugin (twoFactor from @noctcore/auth/two-factor) is configured on its own; its options are in Two-factor. The membership plugin (membership from @noctcore/auth/membership) is configured the same way; its options are in Membership guards. So is the invitations plugin (invitations from @noctcore/auth/invitations), in Invitations. A plugin gets its keyed hashes from the core (keyedHash, and since 0.7.0 keyedHashes and matchesSessionHandle, which try the previous secrets of a rotation). A hand-written PluginContext stand-in, such as a test double, has to add those two members to compile against 0.7.0 and later. The core also hands a plugin parseSessionAttributes(value), which runs a value through your session.attributes schema for a startup check of the attributes the plugin adds (the two-factor plugin probes its twoFactorStanding stamp with it); a stand-in has to add it too.
logger: where the package reports what it cannot return, such as a failed breach check, or a mailer or audit sink that threw.
background. See Mail. waitUntil gets the promise of every background task (mail, lock notices, a reset job without enqueue), and auth.flush() waits for the same tasks on shutdown. maxPending counts tasks still running, timed out or not, and bounds memory when a mailer hangs. A dropped mail still spends the per-account mail budget of its door; see Mail.
What the hooks do
Section titled “What the hooks do”Functions the flows call at fixed points, such as sessionAttributes, beforeSessionCreate, beforePasswordReset, beforeEmailChange, afterRegister and onPermanentLock. A hook can refuse with refuse(reason, code); code defaults to invalid_credentials.
beforeSessionCreateruns before every session is minted, as{ user, via, attributes, meta, reissueOf?, beforeChallenge? }. With a second-factor plugin it also runs after a correct password, before any challenge is made (via: 'password',beforeChallenge: true; thesessionAttributeshooks run for it too). A refusal there ends the login as your code (invalid_credentialsby default), writeslogin.failurewith your reason, makes no challenge, and counts as a wrong password in the lockout, so a refused account never learns its password was right. The session itself comes later (via: 'second-factor', or'password'when no challenge is due), and the hook runs again then. On the'password'path a refusal there counts as a wrong password too; a refusal of the'second-factor'session comes after the password was credited. What still differs from a wrong password is the work the hooks do: your own, and the core’s (the email revert lockout’s token read, and the permanent lockout’s read when trusted devices are off).reissueOfis the live session an issue replaces, as the core read it from the store: set for the core’s re-issues, and for your own via when you pass that user’s live session asinherit(an issue whoseinheritis revoked, expired or another user’s is refused before the hooks, assession_expired). The new session’s attributes, remember-me and cookie shape come from that stored copy, not from your object, and when the core read it itself, the new session is fenced at its epoch: a revoke-all or reset that lands before the mint refuses it. A flow of yours that ends sessions before it re-issues callsconfirmLiveSession(session)on the plugin context first, and passes what it returns.passwordResetRequirementssays ahead of time what applying a reset will ask for, as{ secondFactor?: boolean }for{ user }, soinspectPasswordResetcan tell a reset page to show the code field. AnswersecondFactor: truewhen your ownbeforePasswordResethook will demand a code for that user; the two-factor plugin answers it for a confirmed factor. Any hook’struewins. For an account yourbeforePasswordResetalways refuses (one your app closed), return the samerefuse(...)here, so the check answers what the reset would; the core does this for an account in an email revert lockout. It must only read: it runs on every inspection, which spends nothing.afterRegisteris awaited and runs only for a new address, so its time shows in sign-up timing: queue slow work instead of awaiting it.onSessionsRevokedhears of every session that ends by a flow, with its reason (logout,revoke-all,evictedfor the per-user cap, and so on), as{ userId, sessionIds, sessionHandles, reason, scope? }.sessionIdsare store keys for server-side use only,sessionHandlesthe same sessions’ public handles, assessions.listshowed them. An error it throws is logged and never fails the flow. It is awaited on the response path, on sign-in too when the cap evicts, so keep it fast and queue slow work instead of awaiting it.sessionStandingruns on every validated request, afteronSessionValidateaccepted it, and returns a standing thatvalidateRequestattaches to the session for that request only (the two-factor plugin’stwoFactor:graceorenrollment-only). A standing never widens access, so anenrollment-onlyfrom any hook wins over agrace. Keep it cheap.
turnstile(options)
Section titled “turnstile(options)”Builds a captcha for Cloudflare Turnstile.
| Option | Default | What it does |
|---|---|---|
secretstring | required | Your Turnstile site's secret key. |
expectedHostnamesstring[] | none | Hostnames the widget may be served from. Strongly recommended. |
checkActionboolean | off | Require the widget's action to equal the door name (login, register, ...). |
timeoutMsnumber | 5000 | How long to wait for the provider, in milliseconds. |
fetchtypeof fetch | global fetch | The fetch to call it with. |
onResult(outcome) => void | none | Called with every outcome, to log or count it. Not awaited. |
loggerLogger | silent | Where a throw from onResult is reported. |
onResult is called with every outcome ({ verdict, door, errorCodes, reason?, status? }) to log or count it; it is not awaited (keep its synchronous part cheap, since that still runs on the request path), cannot change the verdict, and a throw is reported to logger. Outcomes never carry the token or the secret. The verifier’s check(token, context) returns the same outcome. The reasons are listed in Captcha.
Adapter options
Section titled “Adapter options”The adapters take their own options beside the createAuth result; the guides cover them (NestJS, tRPC). The ones below tie in with keys on this page. Source: auth-nestjs/src/options.ts, auth-trpc/src/options.ts, session/session-manager.ts.
Counting activity: touch
Section titled “Counting activity: touch”session.touchInterval says how often last-active may be written; touch decides which requests may write it at all. A request that counts as activity refreshes last-active at most once per touchInterval. A passive one (a poll on a timer) is validated and answered with its session as usual, but never refreshes last-active, so an idle session still expires while only polls arrive. The core’s validateRequest takes the same switch as touch: false. Anything but a boolean or a function stops the boot with an AuthConfigError. Background: Background polls.
AuthModule.forRoot(options)
Section titled “AuthModule.forRoot(options)”| Option | Default | What it does |
|---|---|---|
touchboolean | (request: TouchRequest) => boolean | true | Whether a request counts as activity for the idle timeout. A predicate sees { method, path, headers } and returns false for a poll. false touches on no request. |
The predicate runs before the middleware validates the session and cannot read route decorators. Under nestjs-trpc the tRPC context validates it a second time, with its own switch (see Use with tRPC). Its path is the raw request path with the global prefix and without the query string: it is not normalised, so a trailing slash or a different case is a different path, and a predicate that compares it should normalise first. See Use with NestJS.
createAuthContext(options)
Section titled “createAuthContext(options)”| Option | Default | What it does |
|---|---|---|
touchboolean | (path: string) => boolean | true | Whether a call counts as activity for the idle timeout. A predicate gets each procedure path of the request. false touches on no request. |
meta.false | none | On a procedure, .meta({ touch: false }) marks it passive. A batch touches when any of its procedures is active. |
The predicate and the meta are read from the calls tRPC parsed before it built the context. When tRPC names no call, the request touches. With nestjs-trpc and AuthModule mounted, the session is validated by both, and a poll is passive only when marked in both; see Use with tRPC for that and the other cases where this has no effect.
Handing out the CSRF token
Section titled “Handing out the CSRF token”For a client that cannot read the csrf cookie. The token is the one the adapter already set as the cookie on that response, bound to the same session or pre-session. Source: auth-nestjs/src/session-cookies.ts, auth-trpc/src/context.ts, auth-trpc/src/response-meta.ts.
| Call | Default | What it does |
|---|---|---|
SessionCookies.{ csrfToken: string } | none | On NestJS, returns the CSRF token of the request for a client that cannot read the cookie, from a @Public() GET route, and marks the response no-store. |
ctx.{ csrfToken: string } | none | On tRPC, the same from a public query sent with GET. It throws on an unsafe method, a streamed batch and a subscription. |
authResponseMeta(responseMeta?)(opts) => ResponseMeta | none | Wraps your tRPC responseMeta so its cache headers cannot replace the no-store on a response that handed out a token. Pass it to the tRPC handler. |
authResponseMeta drops Cache-Control, Surrogate-Control, CDN-Cache-Control, every *-CDN-Cache-Control, X-Accel-Expires and Edge-Control from the headers your responseMeta returns, only on a response that handed out a token; any other response gets your answer unchanged. Other proxy-specific cache headers are left alone, so keep such rules off the token route.
For adapter authors: the CSRF layer
Section titled “For adapter authors: the CSRF layer”Both adapters run one CSRF implementation from @noctcore/auth, so an adapter of your own (another framework, another tRPC transport) can give the same answers for the same cookies. These exports are public API, checked by the API snapshot and versioned like the rest of the core:
resolveCsrfSettings(input, secure): the boot checks (the options present and of their type, lists without empty slots, at least one secret of 32 bytes, exactcrossSiteOrigins, a non-empty allowlist, a valid header name) and the cookie names,__Host-prefixed whensecure.readCsrfCookies(csrf, cookieHeader): the pre-session id and the CSRF cookie from theCookieheader.csrfRequestAllowed(csrf, request): the verdict on a request judged as unsafe (Origin allowlist,Sec-Fetch-Site, the signed double-submit token). Your adapter decides which requests it judges.handOutCsrfToken(options, request): what a safe request sets, and the token to hand to a client that cannot read the cookie.bindCsrfToSession(options, session, sameSite)andstartCsrfPreSession(options, sameSite): the CSRF cookie to write with a new session, and the fresh pre-session after one ends.appendSetCookie(res, spec): adds aSet-Cookieheader to a Node-style response without dropping the ones already set.isSafeMethod(method): the methods that skip the check (GET, HEAD, OPTIONS, ASCII case folding only).
Source: auth/src/http/csrf-adapter.ts. Background: CSRF.
Startup checks
Section titled “Startup checks”createAuth throws an AuthConfigError when:
- a store,
password.hasherormaileris missing, orsecretis missing or neither a string nor bytes; password.breachCheckis neither a breach checker (a function, such aspwnedPasswords()) norfalse, orcaptchais not a verifier with averifyfunction (a string such as"false"from the environment used to count as configured and throw on the first sign-up or login);password.policy.minLengthis below 8 or not a whole number, orpassword.policy.maxLengthis not a whole number of at leastminLength;session.cookie.nameis not a string, or has characters other than letters, digits,_and-;session.cookie.secureis nottrueorfalse;session.cookie.sameSiteis a fixed'none'whilesession.cookie.secureisfalse;session.cookie.sameSiteis a fixed value other than'lax','strict'or'none'('None'used to skip the check above; a function’s value is checked the same way when a cookie is built);session.attributeshas noparsefunction;session.maxPerUseris not a positive integer ornull;session.touchIntervalis not shorter than a fixedidleTimeout(anidleTimeoutfunction is checked at each sign-in instead, see Session);session.absoluteTtlorrememberMeTtlis longer than the session store’smaxSessionTtlMs;throttle.lockout.deviceMaxAge, or the two-factor plugin’strustedDevices.ttl, plus a minute of clock skew is longer than the session store’sepochTtlMs, or the store declaresepochTtlMsormaxSessionTtlMsas anything but a positive number;email.normalizeis an unknown name, or a custom normaliser fails its startup test;registration.revealExisting,registration.autoLoginorpasswordReset.markEmailVerifiedis nottrueorfalse;session.requireFreshAuthis not an object (falsewould otherwise read as “nothing set” and keep both checks on), orrevokeSessionorrevokeOtherSessionsunder it is nottrueorfalse;registration.autoLoginis set withoutrevealExisting;emailVerification.kind,passwordReset.kindoremailChange.kindis not'code'or'link'(a typo such as'Link'used to read as the other kind);- a
urlsentry orpasswordReset.enqueueis not a function, or link verification, link reset or link email change is chosen without itsurlsfunction; - a duration option does not parse (
'15 min',NaN, a negative number): everyttl,passwordReset.ticketTtl,emailChange.revertTtlandblockAfterRevert,session.freshAuthAge,absoluteTtl,rememberMeTtl,touchIntervaland a fixedidleTimeout, thethrottle.lockoutdurations and rule windows, andbackground.timeout. The error names the key; emailVerification.linkWithoutSessionis set withoutkind: 'link', or is nottrueorfalse;emailVerification.digits,passwordReset.digitsoremailChange.digitsis outside 6 to 9;emailVerification.maxAttempts,passwordReset.maxAttemptsoremailChange.maxAttemptsis not a whole number of at least 1;emailChange.revertTtlis shorter than 7 days;- a rule under
throttle.lockout(perAccountIp,perAccount,perDevice) is not an object, or alimitunder it orthrottle.doorsis not a whole number of at least 1, or itswindowis zero (a door rule also needs alimitand a validwindow; anulldoor rule, and anullthrottle.lockout, keep the defaults); throttle.lockout.baseLockorthrottle.lockout.maxLockis zero;throttle.lockout.durationsis not a list, is empty, has an entry that is not a duration or is zero, or is set together withbaseLockormaxLock;throttle.lockout.revealLockedorthrottle.lockout.permanent.trustedDevicesis nottrueorfalse;throttle.lockout.countSuccessesis nottrueorfalse;throttle.lockout.permanent.afterLocksis not a whole number of at least 1;previousSecretholds a value that is not a string or bytes, is shorter than the minimum forsecret, or repeatssecretor another previous secret (an empty string counts as shorter), or is a list with an empty slot;pluginsis not a list, holds an empty slot or an entry that is not a plugin with anid, a plugin’sflowsis not a function or itsrequiresis not a list;- a plugin requires
captchaand none is configured; background.timeoutis zero,background.maxPendingis not a whole number of at least 1, orbackground.waitUntilis not a function.
Sources: create-auth.ts, plugins/two-factor/index.ts, core/background.ts, flows/resolve-settings.ts, session/session-manager.ts, http/cookie.ts, shared/email.ts, shared/config-checks.ts, throttle/throttle.ts, throttle/rules.ts, core/plugins.ts, crypto/keys.ts; for the plugins, their options.ts; for the factories, password/argon2.ts, password/breach.ts and http/turnstile.ts.
A list option has to be a real list with no empty slot: a single string would be read character by character, and an empty slot ([, '/x']) is skipped by the checks that walk a list but read as undefined later. A boolean option has to be a real true or false, and a count a real number: a value read from the environment as the string "false", or as Number(undefined) (NaN), is refused rather than read as on or as no limit. Convert it first, for example process.env.REVEAL_EXISTING === 'true'. Leaving a key out, or passing undefined or null, still gives its default, also for password.policy.minLength and maxLength.
The plugins check their own options the same way when they are created: invitations refuses an acceptWithoutSession or recheckInviter that is not true or false and a ttl or rule window that does not parse; membership a revokeSessionsOnChange that is not true or false, a canManage that is not a function and an adminRoles with an empty slot; and twoFactor a trustedDevices that is neither false nor an object, a required or enforcement that is not a function, a stepUpWindow, trustedDevices.ttl or rule window that does not parse, an enrollmentWindow that does not parse, is not positive or is longer than 24 hours, and an enforcementStanding that is not 'live', 'at-issue' or { mode: 'at-issue', version?, maxAge? } (a non-empty version, a maxAge that parses, is positive and is at most 30 days), or that is set without enforcement; under 'at-issue' it also refuses a session.attributes schema that accepts {} but refuses the twoFactorStanding stamp (a null required, enforcement or importedRecoveryCodes counts as left out).
The collaborators you build with a factory check theirs when called: argon2id() refuses an unsafeAllowWeakParameters that is not true or false, a memoryCost, timeCost or parallelism that is not a whole number of at least 1, and a secret that is not bytes; turnstile() a missing or empty secret, an expectedHostnames that is not a list of strings (one string was matched as a substring, so any part of the host name passed), a checkAction that is not true or false, a timeoutMs that is not a number above zero, and a fetch or onResult that is not a function; pwnedPasswords() the same for timeoutMs, fetch and onResult, and a userAgent or baseUrl that is not a string.
The full shape
Section titled “The full shape”Every group written out with its default, around the four required keys and the reset link. Leave a group out and you get the same values.
import { createAuth, pwnedPasswords, type AuthConfig, type AuthUser, type Mailer,} from '@noctcore/auth';import { argon2id } from '@noctcore/auth/argon2';
interface Deps { stores: AuthConfig<AuthUser, unknown, []>['stores']; mailer: Mailer; /** At least 32 bytes, from your secret manager. */ secret: string; origin: string;}
// The four required keys, the reset link most apps need, and every other// group written out with its default. Leave a group out and you get the// same values.export function authConfig({ stores, mailer, secret, origin }: Deps) { return { stores, secret, mailer, password: { hasher: argon2id(), breachCheck: pwnedPasswords(), policy: { minLength: 12, maxLength: 256 }, }, urls: { resetPassword: (token) => `${origin}/reset-password#${token}`, }, session: { absoluteTtl: '24h', rememberMeTtl: '30d', idleTimeout: ({ rememberMe }) => (rememberMe ? '7d' : '30m'), touchInterval: '60s', maxPerUser: 10, freshAuthAge: '10m', cookie: { name: 'session', secure: true, sameSite: 'lax' }, }, email: { normalize: 'standard' }, registration: { revealExisting: false, autoLogin: false }, emailVerification: { kind: 'code', ttl: '15m', digits: 8, maxAttempts: 5 }, passwordReset: { kind: 'link', ttl: '1h', ticketTtl: '10m', markEmailVerified: true }, emailChange: { kind: 'code', ttl: '15m', revertTtl: '7d', blockAfterRevert: '30d' }, throttle: { lockout: { perAccountIp: { limit: 5, window: '15m' }, perAccount: { limit: 10, window: '15m' }, baseLock: '5m', maxLock: '1h', quietPeriod: '24h', revealLocked: false, }, // One entry per door; every door is in the Door limits table. doors: { login: { limit: 10, window: '1m' } }, }, } satisfies AuthConfig<AuthUser, unknown, []>;}
export const buildAuth = (deps: Deps) => createAuth(authConfig(deps));Store and hasher options
Section titled “Store and hasher options”These belong to the objects you pass in, not to createAuth.
argon2id(options)
Section titled “argon2id(options)”Source: password/argon2.ts.
| Option | Default | What it does |
|---|---|---|
memoryCostnumber (KiB) | 19456 (19 MiB) | OWASP's memory floor. Raise it per machine; login rehashes old hashes, so raising it later costs nothing. |
timeCostnumber | 3 | The auth guide's pass count, stricter than OWASP's 2 at this memory. |
parallelismnumber | 1 | OWASP's recommendation. |
secretstring | Uint8Array | none | An optional pepper kept outside the database. Changing or losing it makes every hash unverifiable. |
unsafeAllowWeakParametersboolean | false | Parameters below every row of OWASP's equivalence table are refused unless this is set. Tests only. |
redisStores(redis, options)
Section titled “redisStores(redis, options)”Source: packages/auth-redis/src/options.ts, session-store.ts.
| Option | Default | What it does |
|---|---|---|
prefixstring | 'auth:' | Key prefix, so several apps can share one Redis. |
maxSessionTtlDuration | '30d' | The longest session the store holds. At least your session.rememberMeTtl; createAuth refuses a longer session. |
epochTtlDuration | '90d' | How long a user's revocation epoch outlives its last write. Must be longer than maxSessionTtl, and at least a minute (the clock skew a device cookie is allowed) longer than throttle.lockout.deviceMaxAge and a two-factor trustedDevices.ttl. |
clockClock | system clock | For tests. |
If epochTtl is not longer than maxSessionTtl, the store refuses to start. If an epoch ever lapses, the user’s sessions fail closed. The store reports epochTtl as epochTtlMs, and createAuth refuses a throttle.lockout.deviceMaxAge or a two-factor trustedDevices.ttl that is not at least a minute (the allowed clock skew) shorter: those are fenced by the epoch alone, so a lapse would let a revoked one through again.
adoptLegacySessions(store, options)
Section titled “adoptLegacySessions(store, options)”Source: session/legacy-sessions.ts. Wraps a session store so sessions from the app’s own store, from before the switch, are adopted on first use. See Switching from your own sessions.
| Option | Default | What it does |
|---|---|---|
take(id) => Promise<LegacySession | null> | required | Removes and returns, in one atomic step, the old session stored under id (the SHA-256 hex of the cookie token). |
maxTtlDuration | required | The longest an adopted session lives, from its createdAt. Set it to session.rememberMeTtl. |
clockClock | system clock | For tests. |
loggerLogger | none | Told about a malformed old session it dropped, with the user id only. |
maxTtl: the store’s maxSessionTtlMs wins when shorter. Zero is refused with an AuthConfigError.
While the wrapper is installed, a token neither store knows is refused with the reason session_adopting, since another request may still be adopting it; clearsSessionCookie(result) is false for that refusal, so the adapters keep its cookie.
prismaStores(options)
Section titled “prismaStores(options)”Source: packages/auth-prisma/src/user-store.ts, index.ts.
| Option | Default | What it does |
|---|---|---|
delegatePrismaUserDelegate | required | prisma.user, or whichever model holds your accounts. |
tokenDelegatePrismaAuthTokenDelegate | required | prisma.authToken. |
fieldsUserFields | id, email, emailVerified, passwordHash, deletedAt | Column names on your user model. deletedAt: null turns soft deletion off. |
selectRecord<string, true> | none | Extra columns to read for your own user type. |
toUser(row) => U | the four auth fields | Maps a row to your user type. |
createData(input) => object | none | Values for your other required columns on sign-up, such as a tenant or a display name. |
writeWhereRecord<string, unknown> | none | A Prisma where a row must also match to take a new password hash, a verified mark or an email change, such as { closedAt: null } for an account your app closed. It is in the same UPDATE, so an account closed after your beforePasswordReset hook still refuses the write. Reads, login and an email revert are left alone. Startup refuses anything but a plain, non-empty object without undefined inside. See Accounts your app closed. |
Accounts your app closed
Section titled “Accounts your app closed”The store guards its reads and writes with deletedAt only. An app that closes an account to new credentials on a column of its own (a member removed from an organisation who keeps the row and the address, say) can refuse such an account in a beforePasswordReset hook, but the hook runs before the token is spent and the hash is written, so an account closed in between would still get the new password. writeWhere puts the app’s condition in the same UPDATE as the write:
const { users, tokens } = prismaStores({ delegate: prisma.user, tokenDelegate: prisma.authToken, writeWhere: { closedAt: null },});A closed row then refuses setPasswordHash, markEmailVerified and changeEmail, and the flows answer that like any refused write:
resetPasswordanswersinvalid_token, and every other reset link, code and ticket of the account, and a pending email change, is voided with it;changePasswordanswerssession_expired;- an email change answers as stale;
- email verification answers
invalid_token; - a reset that would also mark the address verified leaves it unverified;
- an invitation sign-up (the invitations plugin) still creates the account, records the membership (
onAccept) and signs it in, but unverified; the same happens when the mark throws (a misspelled column, an outage), which is logged asMarking an invited address verified failed; - a rehash after login keeps the old hash, and the login is not affected.
The condition is combined with the store’s own through AND, so it can narrow a write but never widen it.
The store checks and copies writeWhere when it is built, and refuses (AuthConfigError) anything but a plain object, and any guard whose shape shows it would match every row. It refuses these pieces anywhere in the guard:
- an empty object (
{},{ closedAt: {} }), except the two empty relation filters that narrow:some: {}(at least one related row, such as{ memberships: { some: {} } }) andnone: {}(no related row).every: {}matches every row, andis: {}holds for every row of a required relation, so both are refused: ask for a related row withisNot: null; - an
undefined(Prisma reads it as no filter, so{ orgId: process.env.ORG_ID }with the variable unset would guard nothing), and a list with an empty slot ({ AND: [, { closedAt: null }] }, which reaches Prisma asundefined); - an empty
ANDorNOTlist (Prisma reads those as true).
It then works out, from the shape alone and as a best-effort extra refusal rather than a proof that the guard narrows, which conditions match no row and which match every row, and refuses any condition, at any depth, that matches every row. “Matches no row” starts at OR: [] and in: [], and is carried through AND, OR, NOT, a field’s not, and the relation filters some, none, is and isNot; notIn: [] matches every row. So it refuses { NOT: { OR: [] } }, { NOT: { OR: [{ OR: [] }] } }, { NOT: { closedAt: { in: [] } } }, { memberships: { none: { OR: [] } } }, { profile: { isNot: { OR: [] } } }, { closedAt: { notIn: [] } }, and an OR with any such branch. It also refuses the two halves of one relation and condition: on one key ({ memberships: { some: {}, none: {} } } matches no row, and every row under a NOT), and split over the direct entries of one OR ({ OR: [{ memberships: { some: {} } }, { memberships: { none: {} } }] }), and the same for is and isNot. An OR: [] or an in: [] on its own matches no row, so it only narrows and is allowed. An empty notIn is refused wherever it is a field’s whole filter, under AND, OR and NOT too, so a block list you build from configuration ({ id: { notIn: blockedIds } }) fails boot while it is empty; only a field’s not ({ closedAt: { not: { notIn: [] } } }) keeps it.
What it cannot see, because it does not know your model:
- a condition every row meets because of your data;
- a condition that matches every row in a form it does not read. Among them:
notIn: []beside another operator of the same field ({ email: { notIn: [], mode: 'insensitive' } }),hasEvery: []on a list column, and a relation split it does not see. The split check reads only the direct entries of oneORthat each hold just that relation, so it misses an entry with other keys ({ OR: [{ m: { some: {} }, tags: { hasEvery: [] } }, { m: { none: {} } }] }), a nestedOR({ OR: [{ OR: [{ m: { some: {} } }] }, { m: { none: {} } }] }), aNOTentry ({ OR: [{ m: { some: {} } }, { NOT: { m: { some: {} } } }] }) and aNOTaround anAND({ NOT: { AND: [{ m: { some: {} } }, { m: { none: {} } }] } },{ NOT: { m: { some: {} }, AND: { m: { none: {} } } } }); - a relation filter in the wrong place (
{ closedAt: { some: {} } }), or a column name Prisma does not know. These pass at boot and the first guarded write throws, after the reset link it was for is spent. The store rethrows Prisma’s error without its message, which prints the whole call and the new password hash with it (a failed sign-up insert is rethrown the same way). Try one reset in a test environment after you set the guard; - a to-one relation filtered by its fields without
isreads as a column’s filter, so an emptysomeornoneunder it is refused even when it is right: write{ profile: { is: { badges: { some: {} } } } }instead of{ profile: { badges: { some: {} } } }.
The guard is copied and frozen, and each write gets a fresh copy, so neither the object you passed nor a Prisma extension that changes one call’s where can change later writes.
What it leaves alone:
- Reads. Lookups still find the row, so login works for a closed account unless your hooks refuse it (
beforeSessionCreate, say). Refuse it there too. - An email revert (the
changeEmailthat also clears the password). It only takes access away, so the owner of the old address can still undo a change on a closed account.