Workflows
@aooth/auth-moost ships one workflow class — AuthWorkflow — that declares six @moostjs/event-wf schemas. It replaces the former LoginWorkflow / RecoveryWorkflow / InviteWorkflow quartet. This page is the narrative map: the policy model, the observable pauses of each flow, the extension seams, and the wf-trigger machinery that drives them via /auth/trigger. Full signatures live in the API reference. Client-side rendering of the forms lives in SPA Components.
@Workflow method | Workflow id | Covers |
|---|---|---|
loginFlow | auth/login/flow | credentials (password, SSO or magic link) → enrollment → MFA → finalize |
inviteFlow | auth/invite/start | admin invite → anonymous magic-link accept |
recoveryFlow | auth/recovery/flow | magic-link or OTP password reset |
changePasswordFlow | auth/change-password/flow | authenticated self-service password change |
addMfaFlow | auth/add-mfa/flow | authenticated self-service "Manage MFA" (add/change/remove, step-up first) |
signupFlow | auth/signup/flow | verify-first self-signup → set password → auto-login |
The login, invite, recovery, and signup @Workflow bodies carry @Public() so the wf adapter can dispatch anonymous logins, magic-link clicks, and self-signups. Invite's admin-phase @Step methods deliberately omit @Public() — they are ARBAC-evaluated (the admin needs the invite permission). Change-password and add-mfa are the two fully-gated flows: neither flow's @Workflow body nor its init / finish steps is @Public() — they carry @ArbacResource("auth.change-password") / @ArbacResource("auth.add-mfa") + @ArbacAction("self"), so each runs only for an authenticated principal whose role grants that resource. See Change password and Add MFA method.
The policy model
Two layers, kept strictly separate:
AuthWorkflowOpts— infrastructure only. Pincode timers, magic-link TTL,loginUrl,totpIssuer, device-trust cookie config, and the per-form schema slots. Passed asPartial<AuthWorkflowOpts>to the constructor; defaults applied bymergeAuthWorkflowOpts. Read asthis.opts.<group>.<field>. See the AuthWorkflowOpts reference.protected resolveXxx(ctx)getters — policy. Anything that varies by request / tenant / user (force MFA enrollment, device-trust posture, session-concurrency limit, redirect target, lockout posture, OTP disclosure copy, …). Each resolver has a paired@Step("prepare-<group>")that writes its result toctx.<group>. Defaults are hardcoded in the resolver body — policy never lives on opts.
// ❌ wrong — policy on opts
new AuthWorkflow({ mfa: { enabled: true } }, ...) // no such field
// ✅ right — policy on a resolver
class MyAuth extends AuthWorkflow {
protected override resolveMfaPolicy(ctx: AuthWfCtx) {
return { required: this.tenantRequiresMfa(ctx.subject), transports: ["email", "totp"] };
}
}Per-flow discrimination — ctx-slot presence, never a flow name
AuthWfCtx has no flow field. A resolver or step body that must branch reads which slot is populated:
| Slot present | Flow |
|---|---|
ctx.admin | invite (admin phase) |
ctx.accept | invite (accept phase) |
ctx.postReset | recovery |
ctx.signup | self-signup |
ctx.changePassword | change-password |
ctx.addMfa | add-mfa |
| (none of these) | login |
protected resolveRedirect(ctx: AuthWfCtx): string | undefined {
if (ctx.accept) return this.opts.loginUrl; // invite-accept
if (ctx.postReset) return "/account/security"; // recovery
return ctx.input?.next ?? "/dashboard"; // login
}The subclass recipe
import { AuthWorkflow, type AuthWfCtx, type AuthDeliveryPayload } from "@aooth/auth-moost";
import { AuthCredential } from "@aooth/auth";
import { UserService } from "@aooth/user";
import { ConsentStore } from "@aooth/auth-moost";
import { Controller, Inherit } from "moost";
@Inherit() // flows @Workflow / @WorkflowSchema / @Step / @Public metadata
@Controller() // SINGLETON, like the base
class MyAuth extends AuthWorkflow {
// Declare a constructor that supplies the options — DI cannot resolve the
// base's plain `opts` parameter; it resolves only this constructor's params.
constructor(users: UserService, auth: AuthCredential, consentStore: ConsentStore) {
super({ loginUrl: "/sign-in", totpIssuer: "MyApp" }, users, auth, consentStore);
}
protected override async deliver(payload: AuthDeliveryPayload): Promise<void> {
if (payload.channel === "email") await myEmailSender.send(/* … */);
else await mySmsSender.send(/* … */);
}
protected override resolveRedirect(ctx: AuthWfCtx) {
return ctx.input?.next ?? "/dashboard";
}
}
app.setReplaceRegistry(createReplaceRegistry([AuthWorkflow, MyAuth]));Re-apply @Inherit() @Controller() and re-declare the constructor
@Inherit() carries @Workflow / @WorkflowSchema / @Step / @Public metadata — without it the subclass serves none of the base's steps. The base constructor's first parameter is the plain options object, which DI cannot resolve, and a re-declared constructor uses only its own parameter metadata: declare one that takes the three injectables and passes the options to super(...). Add @Injectable("FOR_EVENT") ONLY if the constructor reads request-scoped composables — AuthWorkflow holds no per-event state on this, so SINGLETON is correct.
Step IDs are registered globally
@moostjs/event-wf registers every @Step("id") into one global registry — identical IDs on two classes silently collide. When adding steps in a subclass, pick IDs that won't clash with the base inventory. Never use a resolveXxx name as a @Step id or handler method name (that name is reserved for the policy getters).
Extension point catalog
Every protected member below is an override seam — change behavior by subclassing AuthWorkflow and overriding it (the subclass recipe above). Resolvers return T | Promise<T> (never async on the default); each has a prepare-<group> @Step that writes its result to ctx.<group>. Full signatures live in the API reference; the narrative below (and the linked topic pages) shows how to use the high-traffic ones.
Policy resolvers — context-varying policy (per request / tenant / user)
| Resolver | Decides | Default | Flow(s) |
|---|---|---|---|
resolveMfaPolicy | MFA mode / available transports / TOTP issuer | optional, all transports | login, invite, add-mfa |
resolveEnrollment | force a confirmed email/phone before issuing | ensureEmail/Phone: false | login |
resolveDeviceTrust | trusted-device posture (enabled / optIn / skipsMfa) | disabled | login |
resolveLockout | failed-login lockout mode (temporary / self-service / admin-only) | temporary | login, recovery |
resolveGuards | login-time guards (passwordInitial / passwordExpiry / emailVerifiedRequired) | initial-password guard on | login |
resolveSessionPolicy | session concurrency limit | none | login |
resolveFinalize | new-device notice (recognition-gated) + post-login redirect mode | both off | login |
resolveRiskStepUp | require an extra MFA round (risk-based) | require: false | login |
resolveAlternateCredentials | which login alt-actions show (forgotPassword / signup / magicLink / SSO list) | forgot-password on | login |
resolveSignupPolicy | self-signup on/off + collectUsername | allowSignup: false | signup |
resolveChangePasswordPolicy | revokeOtherSessions + optional rate-limit | revoke on | change-password |
resolveAccept | invite accept-tail (redirect / confirmation) | redirect to loginUrl | invite |
resolveAdminForm | invite admin form (collectRoles) | collectRoles: true | invite |
resolvePostReset | recovery post-reset (revokeAllSessions / loginUrl) | revoke all on | recovery |
resolveRecoveryAltActions | recovery alt-actions (backToLogin) | on | recovery |
resolveRecoveryChannel | M1 OTP transport for the typed identifier | email | recovery → guide |
resolveRecoveryDeliverySource | M1 (typed) vs M2 (registered) OTP delivery | typed | recovery → guide |
resolveRecoveryDeliveryMode | one-time code (otp), magic link (magicLink) or the user's pick (choice) | otp | recovery → magic links |
resolvePromoteHandleField | which login-handle column a confirmed channel promotes into | undefined (off) | login, invite, add-mfa → guide |
resolveEnrollPreConfirmed | skip the enrol pincode for a verified-by-construction address | false (always prove) | login, invite, add-mfa → recipe |
resolveEnrollAddress | pin the sms/email enrolment address to an account record (free-text form never renders) | 'collect' (free-text) | login, invite, add-mfa → recipe |
resolveTotpAccountLabel | the account half of the authenticator's "issuer: account" TOTP label | ctx.email → username | login, invite, add-mfa |
resolveStepUpConfirmBeforeSend | ask explicit consent before the manage step-up dispatches its sms/email code | true (ask first) | add-mfa |
resolveOtpDisclosure | per-channel consent copy under the address input | empty | login, add-mfa |
resolveLockedMfaTransports | factors the user may NOT change/remove (e.g. a handle-bound email/phone) | [] (none locked) | add-mfa |
resolveRedirect | post-login redirect URL | per resolveFinalize | login |
resolveOAuthErrorRedirect | federated-login failure redirect target | error page | login (SSO) |
resolveFederatedEmailTrust | whether a provider's email claim counts as correspondence inbox proof | email_verified === true | login (SSO) → guide |
resolvePincodeForm / resolvePincodeTarget / resolvePincodeAltAction | which OTP form, recipient+channel, alt-action mapping for the shared pincode pair | MFA-vs-recovery by ctx slot | login, recovery |
resolveRecoveryUrl (sync helper) | URL the forgotPassword alt-action targets | loginUrl-derived | login |
resolveClientIp / resolveUserAgent / resolveIssueMetadata (sync helpers) | device-trust + audit metadata at issue time | request headers | login |
selectRecoveryRegisteredMethod(user) is a sync helper (not a resolver) paired with M2 — see its guide.
Step extension-point stubs — no-op @Steps you override for new behavior
@Step | Override to | Reached from |
|---|---|---|
extra-step | add input pauses / persistence to the login + invite-accept tail (invite: runs BEFORE the acceptance write — prefer afterInvitationAccepted for writes) | login, invite |
signup-extra-step | seed app rows / welcome email after self-signup creates the user | signup |
promote-to-handle | (usually leave as-is; gate via resolvePromoteHandleField) | login, invite, add-mfa |
passkey | implement a passkey credential (bundled stub is a no-op) | login |
Lifecycle hooks
| Hook | Override to | Default |
|---|---|---|
deliver(payload) | route MFA / recovery / enrollment pincodes + new-device notices by kind + channel — see below | no-op |
prepareUser(input) | supply required app columns on a freshly-created row (shared by invite + signup); invites also pass app / form / invitedBy — see Invites | {} |
resolveInviteContext(ctx, startFormData) | resolve an invite's server-side app context (e.g. a tenant id) from the start request; throw to refuse | undefined |
inferAdminRoles(input) | derive roles server-side from the admin invite payload | [] |
getAvailableRoles() | whitelist selectable roles on the admin invite form | none |
duplicateInviteCheck(input) | override the duplicate-invitee rule ('allow' | 'reject' | 'reuse'); receives the issuer, app context and the pending invite's issuer | re-invite pending; reject accepted |
msg(code, params) | resolve every user-facing text — see Messages | opts.messages → English |
logoutOtherSessions(username) | customize the concurrency-limit eviction | revoke all |
loadActiveSessionsCount(username) | count active sessions for the concurrency prompt | store-backed |
validateMfaAddress(ctx, method, value) | stricter rules on the user-typed enrolment address — ctx-first and async-capable, so record-based rules (domain allowlists, match-the-account-email) load the row directly | email-shape / permissive E.164 |
beginSso / oauthRuntime / authorizeRuntime | federated-login wiring — see Federated Login | runtime-resolved |
ConsentStore (getPendingConsents / save / read / recordOtpChannelConsent) and the WfTriggerProvider overrides (storeStrategy / wfStateSecret / wfStateEncapsulatedTtlMs / stateRegistry / triggerHooks) are separate provider classes, documented in their own sections below.
Event hooks
Six after* seams fire once at the single completion point of each flow — the place to provision a tenant, send a welcome email, push analytics, or sync an external directory. Each is protected, defaults to a no-op, receives the live AuthWfCtx (ctx.subject set; read ctx.isFirstLogin, ctx.oauth, ctx.accept, … for context), and is async-capable. They are awaited and a throw propagates — a failing hook aborts the run (the login hooks fire before the session/code is delivered, so a throw fails the login atomically, with no half-issued session); wrap your own body in try/catch for best-effort behaviour.
| Hook | Fires when | Also fires afterLogin? |
|---|---|---|
afterLogin(ctx) | an authenticated session is established — interactive, federated (SSO), or invite/signup/recovery auto-login | — |
afterInvitationAccepted(ctx) | an invitee finished accepting (account activated), auto-login or fresh-login | only on the auto-login path |
afterSignup(ctx) | a self-signup account was created + activated | yes (signup auto-logins) |
afterPasswordReset(ctx) | a recovery reset completed — even if an admin-only lock survived | only on the auto-login path |
afterPasswordChanged(ctx) | an authenticated user changed their own password (change-password) | no — it's a rotation, not a login |
afterMfaChanged(ctx) | a factor was added / changed / removed (add-mfa) — not on cancel/no-change | no — the session is kept, not re-issued |
afterLogin is the login funnel. It fires at the one record-login step every login flow routes through, right after account.lastLogin is stamped and before the terminal that issues the session (issue) or auth code (mint-authz-code). Because the funnel — not the delivery terminals — owns the stamp + hook, a login can't reach delivery without firing afterLogin exactly once, regardless of credential type (password / SSO / passwordless). It does not fire for finalize paths that establish no session: the invite/recovery fresh-login redirect (the user signs in separately afterwards), nor for change-password's token rotation, nor for an invite, recovery or signup auto-login whose account is no longer active by then (that run finishes without a session). Stamp-at-authenticated: an authorization-server login the user later denies at the consent screen still counts (they proved identity at the AS).
class AppAuthWorkflow extends AuthWorkflow {
protected override async afterLogin(ctx: AuthWfCtx): Promise<void> {
await analytics.track("login", { userId: ctx.subject, firstLogin: !!ctx.isFirstLogin });
}
protected override async afterInvitationAccepted(ctx: AuthWfCtx): Promise<void> {
await provisionWorkspace(ctx.subject!); // an auto-login invite ALSO fires afterLogin
}
}What the user sees
Login (auth/login/flow)
A login run pauses on one or more of these forms before issuing tokens. Which pauses appear is driven by account state + your resolver overrides:
- Credentials — username + password. Alt-actions
forgotPassword,signupand per-SSOsso-${id}finish the run early via a redirect envelope;magicLinkreplaces this step with the magic-link sign-in (identifier → link → the click is the first factor). - Channel enrollment — email/phone, when
resolveEnrollmentrequires a confirmed address the account lacks. - MFA challenge — when the user has a confirmed method (picker shown for multiple).
- MFA enrollment — pick-method → address (sms/email) or TOTP QR step → confirm, when
resolveMfaPolicyrequires it and the user has none. TOTP shows its QR on a dedicated step before code entry (see SPA Components — AsQrCode). The authenticator entry reads "issuer: account" — the issuer half isopts.totpIssuer/resolveMfaPolicy().issuer, the account half comes fromresolveTotpAccountLabel(ctx)(default:ctx.email, else the user'susername) and is baked into theotpauth://URI forever (re-labeling requires re-enrolment), so override it early if you want anything fancier than the username. - Forced password change — when the password is flagged initial or expired. Once the new password is stored and the MFA challenge (if any) is passed, every existing session of the user is revoked (the shared
revoke-sessionsstep, since 0.2.1), so a session opened with the old password — on another device, or by someone who had it — ends with the change. The revocation waits for the second factor on purpose: the old password alone must not be enough to sign the user out everywhere. The flip side: if the user sets the new password and then abandons the MFA step, the old sessions are not revoked (and the next sign-in is no longer forced). CallrevokeAllForUserfrom your own code if that matters to you, for example after a password-expiry rotation. The run then signs this device in on a fresh session as usual. - Terms / consent — when
ConsentStore.getPendingConsentsreturns descriptors (rendered inline on the open form). - Concurrency-limit prompt — when
resolveSessionPolicysets a max-sessions limit and it's exceeded. - Authorize consent — only when the login was started from
GET /auth/authorize(the authorization-server flow). After authentication the run verifies theaooth_authzbrowser binding and pauses onAuthorizeConsentForm; Authorize mints the code, Deny returnserror=access_denied. WithresolveAuthzReauthPolicy() → { mode: 'consent-only' }, a live browser session skips steps 1–7 entirely and pauses straight here ("Signed in as …" names the acting identity). See Consent gate & browser binding and Consent-only for live sessions.
Before finishing, a run that verified the password re-checks that the password hasn't changed since (since 0.2.1). A run paused on a later form (MFA, enrolment, terms, the authorize consent prompt, …) and resumed after the password was changed elsewhere ends with PASSWORD_CHANGED_SIGN_IN_AGAIN instead of issuing tokens or an authorization code.
The run finishes by issuing tokens (or a fresh-login redirect) — or, for an authorize-initiated login, by minting a single-use code to the requesting client instead of a browser session. Any user-initiated abort (Cancel, decline-terms) emits a structured aborted envelope via abortWf.
Failed sign-ins and lockout disclosure
A wrong password reads "Invalid credentials". What a locked account reads is set by AuthWorkflowOpts.lockoutDisclosure:
| Mode | Locked account | Unknown / inactive handle |
|---|---|---|
'uniform' (default) | "Account locked" | the same message sequence a real account produces — "Account locked" after the same number of failures, for the same duration, re-locking after expiry the same way |
'generic' | "Invalid credentials" | "Invalid credentials" |
'reveal' | "Account locked" | "Invalid credentials" — so the lock message tells an attacker which handles exist (the pre-0.2 behaviour) |
Threshold and duration come from UserService's lockout config (and resolveLockout); with lockout disabled (threshold: 0) every mode behaves like 'generic'. 'uniform' keeps a shadow failure counter per unknown handle in lockoutShadowStore. It mirrors a real account exactly: every failure counts and the counter is not reset by a lock (like failedLoginAttempts), so after a lock expires the next failure locks again; a permanent lock stays on while the handle keeps being tried. Counters are keyed by a SHA-256 of the normalised handle (fixed size), slide for 30 days of inactivity, and the login form caps username at 256 characters. The default store is one in-memory store per process, capped at 50,000 counters (oldest dropped first, active locks last — a flood of fresh counters cannot push out the lock of a handle being probed; give your own RateLimitStoreMemory({ maxEntries }) the same evictLast: (k) => k.startsWith("shadow-lock:")) — pass a shared store (e.g. RateLimitStoreRedis from @aooth/auth/redis) when several instances serve sign-ins, otherwise each instance counts on its own and the sequence differs from a real account's:
new AuthWorkflow(
{ lockoutDisclosure: "uniform", lockoutShadowStore: new RateLimitStoreRedis({ redis }) },
users,
auth,
consentStore,
);UserService.login also spends one password hash on every early exit, so response time does not tell an unknown, inactive or locked account from a wrong password. A small difference remains: a wrong password on a real account writes its failure counter (one store round trip), which an unknown handle does not — 'uniform' spends a shadow-counter write instead. Neither replaces a rate limit on the login route — see Rate Limiting.
Since 0.2: unknown handles can read "Account locked"
The default changed from revealing locks ('reveal') to 'uniform'. Support tooling or tests that treat "Account locked" as proof an account exists must switch to checking the account itself, or set lockoutDisclosure: 'reveal'.
Device recognition — when the "new sign-in" notice fires
aooth keeps two device concepts deliberately separate:
- Trust — "skip MFA on this device". Opt-in ("Remember this device" on the MFA form), short TTL, optionally IP-bound, gated by
resolveDeviceTrust. Security-sensitive, so it stays strict. - Recognition — "we've seen this device — don't email about a new sign-in". Pure noise control with no security bypass, so it is always on, long-lived, and never IP-bound. Without it, a user who declines remember-me (or whose trust cookie lapses or changes IP) would get a "new sign-in" email on every login.
Recognition rides its own cookie plus a per-user seenDevices ledger. On every successful login the device-recognition step (login finalize tail, before issue) verifies an arriving recognition cookie against the ledger — sliding its expiry on a hit, so active devices never age out — or mints and persists a fresh record labelled with a humanized user-agent summary ("Chrome on macOS"); issue then (re-)sets the cookie on the finish envelope. The notice fires only when the device was not recognized on arrival: the gate is !ctx.isFirstLogin && !!ctx.finalize.notifyNewDevice && !ctx.trust.recognized (a freshly minted record does not count as recognized for the current login). Trust semantics — what skips MFA — are completely unchanged.
| Login from… | MFA | "New sign-in" email |
|---|---|---|
| brand-new device | full | yes — once |
| seen device, "Remember this device" declined | full | no |
| seen device, valid trust cookie | skipped | no |
| seen device, expired trust cookie | full | no (previously: yes) |
| 6th device (cap eviction) | full | evicted device emails again on next use |
Infrastructure knobs live on the deviceRecognition opts group: cookieName (default <deviceTrust.cookieName>_seen, i.e. aooth_trusted_device_seen), ttlMs (default 180 days), maxDevices (ledger cap, default 5 — expired records drop first, then the least-recently-verified are evicted). See the AuthWorkflowOpts reference and the @aooth/user seen-device methods the step calls.
Configure deviceTrust.secret or recognition is silently off. Recognition tokens are signed with the same UserService deviceTrust.secret as trust tokens (domain-separated payloads — the two token kinds are not interchangeable), and without the secret the step no-ops, leaving the legacy notify-on-every-unrecognized-login behavior. Recognition does not require resolveDeviceTrust to be enabled — it works with device trust fully disabled.
Hygiene: the revoke-sessions step (change-password + recovery reset) clears the whole ledger. Each device re-mints on its next login, so the single fresh "new sign-in" notice after a password change is deliberate signal, not a regression.
Where security notices go
The notice needs an email recipient, and not every account has email MFA. The recipient is resolved by UserService.getCorrespondenceEmail — a PROVEN-first chain: account.verifiedEmail, then the first confirmed email-MFA method (also a proven inbox), then your @aooth.user.email-annotated column (when UserServiceConfig.emailField names it — app-canonical but unproven). Proven-first is deliberate for security notices: when an address changes, the notice should reach the inbox someone actually demonstrated control of, mirroring the standard "your email was changed" notice going to the OLD address. The login flow falls back to this chain whenever no confirmed email-MFA method set the recipient — so invited or self-signed-up users with zero MFA still receive new-device notices.
account.verifiedEmail is captured automatically wherever a flow proves inbox ownership: invite acceptance (the magic-link click), signup (the pre-create OTP), recovery (only when the reset code was actually delivered over email — recorded against the address it went to), email channel/MFA confirmation, and federated logins. The capture is correspondence-only — it never becomes a login handle and never resolves accounts.
Two override seams:
UserService.getCorrespondenceEmail(user)— replace the chain to source the address from anywhere (a profile table, a tenant directory, a CRM). The default is sync, but the return type admits aPromise, so anasyncoverride just works.resolveFederatedEmailTrust(ctx, profile)— should a federated provider's email claim count as inbox proof? The default trusts exactly the provider'semail_verified === trueclaim: a provider trusted to authenticate the user is strictly more trusted than its email claim. Override to exclude a provider whose claim shouldn't be taken at face value (e.g. an internal OIDC issuer that stampsemail_verifiedon unverified directory entries). The capture is idempotent — an already-current address skips the write.
One note for subclass authors: the three email slots are separately owned — ctx.notice.email is the security-notice recipient (server-only; may be seeded without any code sent), ctx.channel.email is the enrollment target, and ctx.email is the flow-subject address recovery/invite/signup use (the login flow never writes it). The email channel-enrollment gates key on ctx.channel.email — the ask→verify progress marker, mirroring channel.phone — never on ctx.email. Full signatures: setVerifiedEmail / getCorrespondenceEmail and the resolver set.
Geo anomalies & impossible travel (recipe)
aooth ships no geo resolution and no default thresholds — detection is consumer policy. What the framework provides is the three outlets the policy composes from: per-session metadata persistence, the MFA re-arm hook, and the alert path.
Capture geo per session.
CredentialMetadatais declaration-merge extensible; add your geo fields and stamp them in aresolveIssueMetadataoverride (the default already records IP + User-Agent). With CloudFront in front, the viewer-location headers are already on the request:tsdeclare module "@aooth/auth" { interface CredentialMetadata { geoLat?: number; geoLon?: number; geoCity?: string; } } protected override resolveIssueMetadata(ctx: AuthWfCtx): CredentialMetadata | undefined { const headers = useHeaders(); // cloudfront-viewer-latitude / -longitude / -city const lat = Number(headers["cloudfront-viewer-latitude"]); const lon = Number(headers["cloudfront-viewer-longitude"]); return { ...super.resolveIssueMetadata(ctx), ...(Number.isFinite(lat) && { geoLat: lat }), ...(Number.isFinite(lon) && { geoLon: lon }), }; }Detect in
resolveRiskStepUp. Therisk-step-upstep runs inside login's MFA loop — beforeissuemints the current session — soauth.listSessions(ctx.subject)returns prior logins only, newest first. Compare the request's geo against the most recent prior session's metadata withhaversineKmand return{ require: true, reason: "impossible-travel" }past your threshold to clearotp.verifiedand re-arm the loop. One ordering caveat: re-arming cannot out-rank a valid trust cookie —check-trusted-devicesits in the same loop and re-verifies on the next iteration, so a trusted device still skips the repeat challenge. If geo must out-rank device trust, also suppress the skip (e.g. returnskipsMfa: falsefromresolveDeviceTrustwhen the anomaly fires).Alert with
sendSecurityAlert(ctx, reason, context?). The blessed one-call alert path: it emits asecurity-alertpayload through the samedeliver()as every other notice. The recipient isctx.notice.email— the proven-first correspondence chain above — and when no provable inbox exists the call is a silent no-op (same posture as the new-device notice).reasonis the machine-readable trigger;contextis free-form template data (distances, cities). The base class never sends one on its own.
protected override async resolveRiskStepUp(ctx: AuthWfCtx) {
if (!ctx.subject) return { require: false };
const here = this.readRequestGeo(); // your header/db lookup
if (!here) return { require: false };
const [prior] = (await this.auth.listSessions(ctx.subject)) // prior sessions only here
.filter((s) => s.metadata?.geoLat !== undefined && s.metadata.geoLon !== undefined);
if (!prior?.metadata) return { require: false };
const km = haversineKm(
{ lat: prior.metadata.geoLat!, lon: prior.metadata.geoLon! },
{ lat: here.lat, lon: here.lon },
);
if (km <= 500) return { require: false }; // your threshold — aooth has no default
await this.sendSecurityAlert(ctx, "impossible-travel", { distanceKm: Math.round(km) });
return { require: true, reason: "impossible-travel" };
}If you persist credentials through the atscript-db store, note the credential-metadata column is consumer-declared: the shipped AoothAuthCredential carries no metadata column. Declare a @db.json field on your extending model shaped as AoothCredentialMetadataBase & { geoLat?: number, geoLon?: number, geoCity?: string } (the exported .as type single-sources the framework-written envelope keys), mark it @aooth.auth.metadata, and pass that model's table to CredentialStoreAtscriptDb({ table }) — the store finds the column on table.type itself, and the closed schema then validates your exact shape (the .as field is the runtime twin of the CredentialMetadata declaration merge above).
Invite (auth/invite/start)
Admin phase (ARBAC-gated by the auth.invite resource): the admin fills the invite form (email, optional roles — server-validated against getAvailableRoles(); extend it via forms.invite), a pending user is created, and the link is delivered — by the email outlet, through deliver(), or returned to the issuer as a shareable link (inviteDelivery). Re-entry never double-sends.
Re-inviting a pending user is the "resend": submit the same email again. The default duplicateInviteCheck verdict 'reuse' refreshes the pending row (roles and prepareUser extras are replaced) and sends a new full-TTL link; since 0.2 every earlier link of that account answers 410 INVITE_REPLACED. An accepted account rejects (AOOTH_USER_ALREADY_EXISTS).
Invitee phase (anonymous resume of the link): cancelled / replaced / already-accepted checks → optional username pick (inviteUsername: 'choose') → set initial password → MFA enrolment when required → optional confirmation banner → finish (auto-login when autoLoginOnInvite, else redirect to loginUrl). A re-clicked link whose state row was already evicted falls through to GET /auth/invite/post-redemption, which rebuilds the same idempotent "already accepted" envelope from the uid in the URL.
App context (resolveInviteContext), required columns, delivery modes, re-invite rules for multi-tenant apps and the error codes: Invites.
Pre-seeded enrolment & verified-by-construction addresses
The shared MFA enrol trio splits collection from dispatch: enroll-address only stages the typed address, and the dedicated enroll-send step (gated on no code being in flight, the same "send once" pattern as the challenge pair) mints + delivers the one verification code — in the same engine pass, so the user experience is unchanged. The split is what makes pre-seeding safe: a consumer that already knows the address — typically resolveAccept staging the invited email — sets ctx.mfaEnroll.address up front, enroll-address self-skips (no redundant ask), and enroll-send still fires exactly once:
protected override resolveAccept(ctx: AuthWfCtx) {
if (ctx.email) (ctx.mfaEnroll ??= {}).address ??= ctx.email; // the invited address
return super.resolveAccept(ctx);
}Skipping the code entirely — at invite accept the user is inside the flow only because they redeemed a magic link delivered to that exact address, the same proof activate-user already trusts to write account.verifiedEmail. Re-proving the same inbox with a pincode in the same sitting is redundant friction, so resolveEnrollPreConfirmed(ctx, method, address) (default false) can vouch for it: enroll-send then dispatches nothing and enroll-confirm writes the confirmed factor (+ verifiedEmail, + default method) with no code-entry pause:
protected override resolveEnrollPreConfirmed(ctx: AuthWfCtx, method: MfaTransport, address: string) {
return !!ctx.accept && method === "email" && address === ctx.email;
}Keep the equality check — the magic-link proof transfers ONLY to the address it was delivered to; vouching for whatever the user typed would write an unproven inbox as a confirmed factor. TOTP is never asked (possession of an authenticator cannot be proven by construction), and a vouch never outlives its address (useDifferentMethod/cancel clear it with the rest of the enrol scratch). Deployments that prefer the double-check simply keep the default.
Pin the enrolment address to an account record
Some deployments need the email/SMS factor bound to an account record rather than free-text — e.g. staff MFA locked to the work mailbox so portal access dies with it at offboarding; letting the user pincode-prove a personal inbox would defeat the control entirely. resolveEnrollAddress(ctx, method) (default 'collect') is that policy knob: return a string and enroll-address stages it (normalized) without ever rendering the free-text form — the user is never shown a form whose only valid input is one known string.
protected override async resolveEnrollAddress(ctx: AuthWfCtx, method: MfaTransport) {
if (method !== "email") return "collect";
const user = await this.users.getUser(ctx.subject!);
return (user as { email?: string }).email ?? "collect"; // your @aooth.user.email handle column
}A pinned address composes with everything above untouched: enroll-address self-skips its form, enroll-send dispatches the one code to it, and resolveEnrollPreConfirmed may vouch it — pin to a verified-by-construction address and the user gets the no-code path for free. The returned value is consumer-authoritative (no validateMfaAddress pass); a blank return falls back to 'collect'. For nuanced rules on what the user types — domain allowlists, must-match-the-record comparisons — override the ctx-first, async-capable validateMfaAddress(ctx, method, value) instead and keep the form.
Recovery (auth/recovery/flow)
Identifier (anti-enumeration: an identifier no code can go to runs a ghost of the code step with the same responses — see No enumeration) → delivery mode (with resolveRecoveryDeliveryMode → 'choice', RecoveryModeSelectForm asks: magic link or one-time code) → OTP entry or magic-link click → new password (revokes existing sessions) → finish (auto-login when autoLoginOnRecover, else fresh-login redirect). The default is the one-time code; Magic links covers the link.
Where the OTP is delivered is itself an extension seam: M1 sends it to the identifier the user typed (transport picked by resolveRecoveryChannel), M2 sends it to a channel already verified on the resolved row (resolveRecoveryDeliverySource + selectRecoveryRegisteredMethod). Logging in by phone and auto-promoting a confirmed channel into a login handle (resolvePromoteHandleField) live alongside these — see Phone, recovery channels & handle promotion.
Magic links
Two flows can send a single-use link instead of asking for a code or a password:
- Recovery —
resolveRecoveryDeliveryMode(ctx)returns'magicLink'(always a link) or'choice'(the user picks onRecoveryModeSelectForm, shown after the identifier). Using the link stands for a verified recovery code: the flow goes on toSetPasswordForm, and the inbox the link went to becomes the account's verified email. - Sign-in —
resolveAlternateCredentials(ctx)returnsmagicLink: true, which shows the login form'smagicLinkaction. It opensMagicLinkRequestForm(email or username); using the link is the first factor only: the run continues exactly as after a password — a forced password change (initial or expired password), enrolment, the MFA challenge for a user with MFA, then the session.
class AppAuth extends AuthWorkflow {
protected override resolveRecoveryDeliveryMode() {
return "magicLink" as const; // or "choice"
}
protected override async resolveAlternateCredentials(ctx: AuthWfCtx) {
return { ...(await super.resolveAlternateCredentials(ctx)), magicLink: true };
}
}The link is sent through the email outlet — append createAuthEmailOutlet to WfTriggerProvider.outlets — with the kind recovery.magicLink or login.magicLink; your buildMagicLinkUrl turns the token into the URL (the token is a wfs, resumed like any other).
Opening a link does not use it up. It shows MagicLinkConfirmForm — "Continue as a•••@example.com", the masked inbox the link went to — and only submitting that step uses the link. A mail scanner that opens links renders the step and leaves the link working; the masked account shows the user which account the link is for.
What the tests pin:
| Property | How |
|---|---|
| Single use | The link is a workflow pause of its own (magic-link state strategy). Opening it re-renders the confirm step on the same link; continuing uses it up and the run goes on with a fresh token. The link then answers 410. |
| Short-lived | It expires after magicLinkTtlMs (default 15 minutes), confirm step included. |
| Hashed at rest | The store keeps a hash of the link's handle, never the handle. (This covers the link pauses; for the store strategy pass hashHandles: true yourself — see state strategy.) |
| Resumed only as a link | Every stored state records the strategy that stored it, and a resume through another strategy is refused (410) without consuming it — so a link's key read from the database cannot be opened as a store. token, even when the links share the store table. |
| No account oracle | The requester gets { sent: true, outlet: "email" } for every identifier and never the link's token. Known and unknown identifiers make the same reads (an identifier lookup and an account read — of a placeholder for an unknown one) and store one link pause each. Nothing is sent for an unknown identifier, an inactive or pending account, an account without a proven inbox, or — for sign-in — a locked one. A failed delivery is logged, not reported. In 'choice' mode the account is resolved only after the pick, so the picker's token holds nothing about it. |
| Rate limited | At most one link per account and purpose per mfa.pincodeResendTimeoutMs (default 60 s; a repeat gets the same answer and sends nothing; the counter lives in lockoutShadowStore), and the bundled per-IP aooth.send limit on anonymous sends. |
| Bound to its purpose | A recovery link only resumes recovery; a sign-in link only resumes the sign-in. Each verify step also checks the link's purpose. |
| Re-checked when used | A recovery link refuses an account that became inactive or was deleted; a sign-in link refuses one that became inactive or locked. Both finish with AOOTH_MAGIC_LINK_INVALID. |
| Proven inboxes only | A link goes to account.verifiedEmail, else a confirmed email MFA method. Recovery with the typed identifier as destination (M1, email channel) sends to the typed address, like the recovery code. |
Override magicLinkAddress(ctx, link) to change the destination.
Login CSRF and forwarded links. Whoever opens a sign-in link is signed into the account it was sent to — a link forwarded to someone else signs them into the sender's account. The confirm step names the account; for a stricter posture return magicLinkSameBrowser: true from resolveAlternateCredentials: the request sets an httpOnly cookie (aooth_magic_link, name: magicLinkBrowserCookie()) and the link then works only in that browser. A link confirmed on another device is spent all the same: that run finishes with AOOTH_MAGIC_LINK_INVALID, and the user requests a new link from the browser they will use. It is off by default, because opening the email on another device is legitimate.
The landing page. Serve the page the link opens with Referrer-Policy: no-referrer, so the token in its URL does not leak to third-party resources it loads.
The state of the link pauses lives in WfTriggerProvider.magicLinkStore() — in memory by default (one process, at most 10,000 links, the oldest dropped first). Every link request stores a pause, known identifier or not, so a flood spread over many addresses — about 500 IPs within the per-IP aooth.send limit of 20 per 15 minutes — pushes out links before they are used. In production, and with several instances, return a durable shared WfStateStore, e.g. the AsWfStore of your wf-state table:
class AppWfTriggerProvider extends WfTriggerProvider {
protected override magicLinkStore(): WfStateStore {
return new AsWfStore({ table: db.tables.wfStates });
}
}Whatever store you return, the link handles are stored hashed, consumed on use and resumable only as links. Sharing the table with the store strategy is safe; give that strategy hashHandles: true too (as in the state strategy example), or a read of the table yields usable store. tokens of the other runs. The send cooldown needs a shared lockoutShadowStore as well (e.g. RateLimitStoreRedis).
Delivery time is the one difference
A known identifier also waits for the email to be sent. Use an EmailSender that queues (returns before the mail goes out) if response time must not depend on delivery.
Change password (auth/change-password/flow)
The authenticated "change MY password" flow — for a signed-in user rotating their own credential (distinct from recovery, which is for users who are locked out). The single pause is ChangePasswordForm (current password + new + confirm, with the live password-rules readout); on submit it verifies the current password, applies the new one through UserService.changePassword, optionally revokes the user's other sessions, then signs the current device in on a fresh session and revokes the session the change was made from (its access token, refresh token and every rotation). The current device stays signed in; no ghost sessions survive.
Identity is session-bound, never input. init-change-password sets ctx.subject (the stable user id) from useAuth().getUserId() — there is no target-user parameter anywhere in the flow, so it is structurally "change my password", not "change someone's password".
Fully ARBAC-gated, no @Public(). Unlike the other (public) flows, the @Workflow body and every step carry @ArbacResource("auth.change-password") + @ArbacAction("self"). A customer enables the feature with a single grant — allow("auth.change-password", "*") — and forbids it (e.g. SSO-only orgs that disallow local password changes) by simply omitting that grant. There is no on/off opts flag; the privilege is the switch. See ARBAC Authorize — gating a whole workflow.
Policy lives on resolveChangePasswordPolicy(ctx) (override seam): revokeOtherSessions (default true) and an optional min-interval rateLimit ({ minIntervalMs }) that emits a terminal "try again later" before the form pause. Current-password re-entry is the primary protection; rate-limiting is optional defense-in-depth.
revokeOtherSessions governs only the user's other sessions. The pre-change session is always revoked (since 0.2.1; earlier versions left its refresh token valid), so a copy of the old access or refresh token stops working the moment the change completes, also under revokeOtherSessions: false. It is revoked before the new pair is minted, so if minting fails (a store error, a maxConcurrent refusal) the user ends up signed out, never left on the old session. A refresh racing the change can't keep the old session alive either (see Sessions — revoking sessions).
When one session can't be targeted, a password change revokes all of the user's sessions (revokeAllForUser) whatever the policy says: on a store that cannot enumerate sessions (stateless CredentialStoreJwt / CredentialStoreEncapsulated), and for a legacy credential minted before session ids existed. Use a stateful store (memory, Redis, atscript-db) if revokeOtherSessions: false must keep other devices signed in. On the stateless stores that revocation is the per-user epoch, which lives in process memory — it does not reach other instances or survive a restart (see Refresh — the per-user revocation epoch); the presented access token is also denylisted, which reaches every instance only through a shared denylist. Multi-instance deployments that must end sessions reliably need a stateful store.
This flow is not in DEFAULT_AUTH_WORKFLOWS, so it is unreachable from the public /auth/trigger — it is dispatched from its own guarded POST /auth/change-password route (CHANGE_PASSWORD_WORKFLOW). See REST Controllers.
Manage MFA (auth/add-mfa/flow)
The authenticated "Manage two-factor authentication" flow — the profile-maintenance twin of change-password — lets a signed-in user add, change, or remove their MFA factors on demand (distinct from login's forced first-time enrollment). It is the same @Workflow as before (id auth/add-mfa/flow, route POST /auth/add-mfa, ARBAC resource auth.add-mfa); the behavior expanded from add-only to full management.
Step-up first. A user who already has a confirmed factor must re-verify an existing one before any change — init-add-mfa sets ctx.addMfa.stepUpRequired, and the flow runs the login MFA challenge steps (load-enrolled-mfa-methods → select-mfa-method → pincode / totp-check) before showing the menu. This step-up deliberately omits the trusted-device skip: a trusted device cannot bypass it.
…but consent before the code goes out. Opening the manage dialog must never email/text the user as a side effect, so the sms/email step-up pauses on StepUpConfirmForm (manage-stepup-confirm) before pincode-send: "To continue, we will send a verification code to ma•••@x" with a Continue submit. A user who opened the dialog by mistake closes it with zero codes consumed and no resend cooldown burnt. The pause is skipped wherever consent already exists — an explicit pick on the factor picker counts (Select2faForm's options show the masked destination, so choosing "Email (ma•••@x)" is informed consent), a code already in flight never re-asks, and TOTP step-up dispatches nothing so it never pauses here. Restore the zero-click dispatch with resolveStepUpConfirmBeforeSend(ctx) → false (login's challenge keeps zero-click — it is mid-authentication, not a dialog side effect). If the user's only confirmed factor is of a kind the policy no longer allows — so nothing is MFA-challengeable (a tightened policy orphaned it) — manage-password-reauth falls back to re-verifying the account password (UserService.verifyPassword) instead, so identity is always re-proven before a change. A zero-MFA user has nothing to verify, so step-up + menu are skipped and the flow drops straight to the enrol picker — the first-time opt-in path. The enrol forms run in 'manage' mode: their "Skip for now" action is hidden, and so is their built-in Cancel — the cancel action stays in the whitelist but the consumer renders its own cancel affordance (see Host-rendered cancel below). A cancel or exit at any point — including on the step-up challenge — fails closed: the step-up loop breaks on abort and the flow routes to the cancelled terminal, so no factor is ever changed without a completed challenge. (Login's challenge loop deliberately does not adopt this abort-break, because exiting it without a paired failure terminal could issue a session.)
The menu (manage-menu, ManageMfaForm) offers one radio whose value encodes action + target: Add the un-enrolled transports (ctx.addMfa.candidates), Change or Remove the enrolled ones — omitting any factor in ctx.addMfa.locked (see below). It never offers an operation that cannot succeed: when the user is down to their last confirmed factor under a required policy, the Remove option is omitted too (removeBlocked, with a one-line note explaining that the method can be changed but not removed) — otherwise the user would land on a confirm form whose only submit re-throws the keep-at-least-one guard, with no way out (the manage forms hide their built-in cancel). Add / Change route into the reused trio (enroll-pick-method → enroll-address / enroll-totp-qr → enroll-send → enroll-confirm); Remove routes to confirm-remove-mfa. The single enroll-address field is transport-aware — its label resolves to "Phone number" for sms and "Email address" for email (via @ui.form.fn.label reading ctx.public.mfaEnroll.method; @meta.label 'Address' is the static fallback when @atscript/ui-fns is absent).
Enrolment is write-on-confirm (no strand, no clobber). The enrol trio stages every candidate value — sms/email address or totp secret — in wf-state and writes the user record only once the new value's code verifies (enroll-confirm upserts it confirmed via addMfaMethod). So an ADD leaves no partial row, and a REPLACE keeps the old confirmed value live until it is atomically swapped — TOTP included: no single-slot clobber, no stash/restore, no crash window. A cancel, or a crafted useDifferentMethod (the manage forms hide both actions but they stay in the declared whitelist), therefore has nothing to undo — it can never strand or clobber the live factor, by construction. Removing the last confirmed factor is blocked only when the MFA policy mode is required — the menu omits that Remove option up front, and if a stale/crafted route reaches confirm-remove-mfa in an un-removable state anyway (last-required-factor, or a locked transport), the step aborts to the finish terminal with a reason-specific message ({ added: false, reason: 'last-required-factor' | 'method-locked' }) instead of pausing on a retryable form that can never succeed.
Host-rendered cancel. Every manage-MFA form hides its built-in cancel action (@ui.form.fn.hidden '() => true') — but keeps it in the action whitelist, so it is still dispatchable. The intended pattern: render your own Cancel affordance (next to your submit) and dispatch the cancel action when the user abandons the flow. Doing so aborts the run server-side (→ the cancelled terminal) and lets the durable wf-state row be cleaned up immediately rather than left to expire — important once the flow has swapped to the store strategy. Since @atscript/vue-wf@0.1.101, <AsWfForm> exposes this on its instance: hold a template ref and call form.value.action('cancel'), gating the button on form.value.supportsAction('cancel') (which checks the form's declared-action ids — @ui.form.action ∪ @wf.action.withData — so it never renders on the reused login step-up challenge forms, which don't whitelist cancel). The demo's WfHostCancelForm.vue is the reference implementation — a thin <AsWfForm ref> wrapper that adds the Cancel button. (Pre-0.1.101 the only route was re-implementing the form with the headless useWfForm() engine and calling its action('cancel'); still valid, no longer necessary.)
Locked (handle-bound) factors. resolveLockedMfaTransports(ctx) (default []) names factors the user may not change or remove here — typically an MFA email/phone whose value is a login handle (changing it would desync identity). Override it to compare each enrolled channel value against your @aooth.user.email / @aooth.user.phone handle columns (resolved at boot via getAoothUserHandleSpec). The menu omits locked factors from Change/Remove and re-checks server-side.
Durable step-up state. Once the step-up factor verifies, manage-stepup-done swaps off the cheap encapsulated start onto the durable store strategy (mirrors login's swap-after-credentials) — the pincode becomes single-use server state and the staged new factor lives server-side, not in the SPA-held token. Degrades to encapsulated when no durable store is wired.
Identity is session-bound + fully ARBAC-gated, exactly like change-password: init-add-mfa sets ctx.subject from useAuth().getUserId() (no target-user parameter), and the @Workflow body + the init / finish / manage steps carry @ArbacResource("auth.add-mfa") + @ArbacAction("self"). Enable with allow("auth.add-mfa", "*"); omit to disable. Not in DEFAULT_AUTH_WORKFLOWS — dispatched from its own guarded POST /auth/add-mfa route (ADD_MFA_WORKFLOW). The user keeps their current session — the finish is a plain data envelope ({ added | changed | removed, method }, or { added: false, reason } for nothing-to-do / cancelled), no token re-issue. UserService.removeMfaMethod is still available for a direct domain call. See REST Controllers.
Self-signup (auth/signup/flow)
Open self-registration for anonymous users — the reciprocal of login (signup is typically the initial flow). Shape = recovery's email→OTP front + invite's create→set-password→activate tail, so it reuses those steps wholesale. The pauses: SignupForm (email — and the "I already have an account" action that cross-links to login) → PincodeForm (the emailed OTP) → SetPasswordForm (password chosen after verification) → finish (auto-login, tokens issued).
Verify-first, so the password is never held in workflow state across the OTP wait — the account row is created only after the email is proven, and the password is set on the shared SetPasswordForm afterward.
Anti-enumeration by construction. Every submitted email gets the same OTP pause — account existence is resolved only at signup-create-user, after proof-of-ownership. A new email creates the user (inactive → password set → activated) and auto-logs-in; an already-registered email finishes with a redirect to loginUrl (reason already-registered) and never issues tokens. An attacker on the wire sees identical behavior either way.
Off by default. resolveSignupPolicy(ctx) returns allowSignup: false (invite-only is the safe default); a deployment opts into open self-serve by overriding it to true (and flips the login form's signup alt-action on via resolveAlternateCredentials). Required app columns (e.g. a NOT-NULL tenantId) come from the same prepareUser hook invite uses — an override distinguishes signup by the absence of invitedBy + empty roles. signup-extra-step is the post-creation extension seam (seed app rows, welcome email, etc.). It IS in DEFAULT_AUTH_WORKFLOWS, so it runs via the public /auth/trigger.
One-time codes
Every emailed or texted code — recovery, the email/SMS second factor at sign-in, signup verification, MFA enrolment and channel verification, the proof code of a federated account link — follows the same rules. Length, lifetime, resend wait, attempt limit and failure budget come from mfa.pincodeLength / pincodeTtlMs / pincodeResendTimeoutMs / pincodeMaxAttempts / pincodeMaxFailures + pincodeFailureWindowMs (config).
Each code goes to a destination: the typed identifier for recovery and signup (known or not — so the limits below answer alike for every identifier), the account and address for the second factor and enrolment, the account for a federated link proof.
| Property | How |
|---|---|
| Not in the state | The state holds a random id and a keyed digest of the code, never the code — a read of a stored or decrypted state does not reveal it. |
| Bound to its target | A code verifies only for what it was sent for: a recovery code for the account the identifier resolved to at the send and the address it went to, the others for the account and address they went to. A changed target answers AOOTH_INVALID_CODE. |
| Attempt limit | Counted on the server per sent code, before the comparison — in lockoutShadowStore. A replayed older token or parallel submits share the count. From the pincodeMaxAttempts-th wrong code on, every submit for that code answers AOOTH_TOO_MANY_CODE_ATTEMPTS; only a resend gives a usable code. |
| Single use | A code that verified is spent: the same code through a replayed earlier state answers AOOTH_CODE_EXPIRED. |
| Resend wait | At most one code per destination and client IP per pincodeResendTimeoutMs, counted on the server, and at most pincodeMaxSendsGlobal (10) per destination from all IPs together per pincodeFailureWindowMs (1 h). A resend inside the wait answers AOOTH_RESEND_WAIT, whatever state it comes from; a new run inside the wait or past the cap pauses on the code form and sends nothing. Another IP's requests never delay yours. |
| Failure budget | At most pincodeMaxFailures (10) wrong codes per destination and client IP, and pincodeMaxFailuresGlobal (100) per destination from all IPs together, per pincodeFailureWindowMs (1 h), across all its codes and runs. Past one of them every send and check for the destination (from that IP, or from anywhere) answers 429 AOOTH_CODE_LIMIT_REACHED until the window passes. The IP is the one the HTTP app resolves — behind a proxy, configure trustProxy on the HTTP app. |
| Per-account sends | Codes sent after a first factor (second factor, enrolment, link proof) also count against aooth.send-user (10/1h per account); anonymous ones (recovery, signup) against the per-IP aooth.send. |
The digests are keyed with a subkey of WfTriggerProvider.pincodeSecret() — by default the wf-state secret, so a setup that overrides wfStateSecret() needs nothing more. A workflow driven outside WfTriggerProvider derives the same key as a default provider, so a code minted on one path verifies on the other. If the provider's wfStateSecret() or pincodeSecret() is overridden, or the credential store has no derivable secret (INVALID_CONFIG), that workflow overrides AuthWorkflow.pincodeKey() to return the provider's key.
Several instances
Pass a shared lockoutShadowStore (e.g. RateLimitStoreRedis) and the same secret to every instance. With the default in-memory store each instance counts on its own, so a client spreading submits across instances gets every limit once per instance.
What the budget does not stop
- A distributed attacker can spend a global cap from many IPs —
pincodeMaxSendsGlobalsends orpincodeMaxFailuresGlobalwrong codes — and so keep codes from a destination for everyone until the window passes: the price of bounding mail-bombing, SMS pumping and total guesses. Raise the caps if that weighs more for you. - A password holder can spend a user's email/SMS second-factor budgets and
aooth.send-userfor the window; other factors (TOTP) are unaffected.
Budgets follow the identifier, not the account. Recovery and signup key on the typed identifier, trimmed and lower-cased: an account reachable by several identifiers (its username and its email, or spellings your store's collation treats as equal) has one budget per identifier, and two accounts whose identifiers differ only in case — on a case-sensitive store — share one.
Outbound delivery — deliver(payload)
Override protected deliver(payload: AuthDeliveryPayload) to route direct sends (MFA / recovery / enroll pincodes, new-device notice) by payload.kind and payload.channel. The invite link goes through deliver (kind: 'invite-link') only under inviteDelivery: 'deliver'; by default it goes through the email outlet on the trigger route (see Invites — delivery modes). There is no audit() method — see Audit Log for wiring your own. See AuthDeliveryPayload.
Consent collection — ConsentStore
AuthWorkflow takes consentStore: ConsentStore as its 4th constructor param. On every run the prepare-consents step calls getPendingConsents(ctx.subject) — the argument is the stable user id, not the username — and writes the result to ctx.consents.pending; the bundled forms surface them inline as a consents: string[] field rendered by the AsConsentArray component. Signatures: ConsentStore reference.
getPendingConsents is user-scoped only
The argument is the stable user id (the workflow passes ctx.subject). The returned descriptor set MUST NOT vary by workflow or transport channel — every flow consults the same user-level consent universe. OTP channel-ownership consent (which IS channel-specific) is captured separately via recordOtpChannelConsent.
import { ConsentStore, type ConsentDescriptor, type ConsentEvent } from "@aooth/auth-moost";
import { Injectable } from "moost";
@Injectable() // SINGLETON
class MyConsentStore extends ConsentStore {
override async getPendingConsents(userId: string | undefined): Promise<ConsentDescriptor[]> {
if (!userId) return [];
const accepted = await db.consents.find({ userId, id: "terms" });
if (accepted.some((e) => e.version === "v2")) return [];
return [
{
id: "terms",
text: "I accept the updated [Terms](/terms) and [Privacy](/privacy)",
required: "You must accept the updated terms to continue",
version: "v2",
},
];
}
override async save(username: string, events: ConsentEvent[]): Promise<void> {
await db.consents.insertMany(events.map((e) => ({ ...e, username })));
}
}
app.setReplaceRegistry(createReplaceRegistry([ConsentStore, MyConsentStore]));OTP-channel disclosure
For each OTP-via-email / OTP-via-sms channel the user enrolls, resolveOtpDisclosure(ctx, channel) stages a generic disclosure paragraph onto ctx.channel.otpDisclosure, rendered next to the address input so the user reads it before submitting (typing + submitting their address is implied consent). After the pincode validates and the method is confirmed, the step calls recordOtpChannelConsent(username, channel, target, disclosure) — so the audit record pins both the literal copy shown and the verified address. The default is disclosure-only (sufficient for transactional OTPs under TCPA / PECR / CASL / GDPR); override recordOtpChannelConsent for affirmative-consent capture.
wf-trigger — workflow trigger machinery
WfTriggerProvider
The @Injectable() singleton owning workflow-state persistence, outlets, and the token wire. Constructor is (wf: MoostWf, auth: AuthCredential). Signatures: WfTriggerProvider reference.
Default outlets: the HTTP (form) outlet and the invite outlet (createInviteOutlet(), used by inviteDelivery: 'deliver' | 'return-link'). Append the email outlet as in the example below; if you replace this.outlets instead, keep createInviteOutlet() in the list.
Workflow state strategy
State is a named-strategy registry, not a single strategy. Every workflow starts on the encapsulated strategy (the registry default): state rides inside the SPA-held token, so opening a login form persists zero server-side rows before the first validated input — a restart or eviction cannot 410 Gone an idle form. A later step calls swapStrategy('store') to move durable once there is real state worth persisting. A third entry, magic-link, holds the pauses of magic links (its store is magicLinkStore()); it is not meant for your own steps.
Both registry entries default to EncapsulatedStateStrategy. To make store durable, override storeStrategy() — there is no this.state field to assign:
import { WfTriggerProvider, createAuthEmailOutlet } from "@aooth/auth-moost";
import { HandleStateStrategy, MoostWf, type WfStateStrategy } from "@moostjs/event-wf";
import { AsWfStore } from "@atscript/moost-wf";
import { AuthCredential } from "@aooth/auth";
import { Injectable } from "moost";
@Injectable()
class MyWfTriggerProvider extends WfTriggerProvider {
constructor(wf: MoostWf, auth: AuthCredential) {
super(wf, auth);
this.outlets = [
...this.outlets,
createAuthEmailOutlet({
emailSender,
buildMagicLinkUrl: (kind, token, ctx) =>
`${env.FRONTEND_URL}/redeem?wfs=${token}${ctx?.userId ? `&uid=${ctx.userId}` : ""}`,
magicLinkTtlMs: (kind) =>
kind === "invite.magicLink" ? 7 * 24 * 60 * 60_000 : 60 * 60_000,
}),
];
}
protected override storeStrategy(): WfStateStrategy {
return new HandleStateStrategy({
store: new AsWfStore({ table: db.tables.wfStates }),
hashHandles: true,
});
}
}
app.setReplaceRegistry(createReplaceRegistry([WfTriggerProvider, MyWfTriggerProvider]));Pass hashHandles: true. The store then keeps a hash of each handle, so a read of the table yields no resumable token — an unaccepted invite link, a recovery run paused on its password form. aooth hashes the magic-link pauses itself; the store strategy is yours to configure.
The encapsulated token's secret defaults to auth.deriveStateKey("wf-state") (HKDF-derived from the auth secret, stable across restarts) — override wfStateSecret() for a dedicated secret, or wfStateEncapsulatedTtlMs() to expire idle forms. The same secret keys the one-time code digests unless pincodeSecret() is overridden. HandleStateStrategy / EncapsulatedStateStrategy come from @moostjs/event-wf; AsWfStore (a @atscript/db-table-backed store) from @atscript/moost-wf.
WfTrigger({ allow?, resumeOnly?, block?, token?, ...hooks })
Method decorator wrapping defineAfterInterceptor at INTERCEPTOR priority. When the wrapped handler returns undefined, the interceptor instantiates WfTriggerProvider and replies with provider.handle(opts). opts.allow lists the workflow ids the route may start and resume, opts.resumeOnly those it may only resume, opts.block those it refuses (below). opts.token overrides the wire (default { read: ['body','query','cookie'], write: 'body', name: 'wfs' }). The trigger hooks can be set per route too. Return a non-undefined value to short-circuit (see Controllers — Pattern B).
Trigger allow lists — start and resume
allow | Effect |
|---|---|
| omitted | any workflow may be started or resumed on this route |
["auth/login/flow"] | only the listed ids; a leading / is ignored when matching |
[] | every workflow is refused |
The wooks trigger makes the decision; aooth answers every refusal as 403: AOOTH_WORKFLOW_NOT_ALLOWED for a start (param workflow) and AOOTH_WORKFLOW_RESUME_NOT_ALLOWED for a resume (no params — a resume never names the stored flow). The flow judged is the registered flow a request resolves to, not the spelling the client sent (since 0.2.7): a start that an onNotFound handler or a parametric route (auth/:kind/flow) would catch is judged as that flow, so listing an id that registers nothing admits nothing. An allow entry admits only a flow registered under exactly that id (for a parametric flow, its pattern). A start of an id that resolves to no flow is refused with the same 403 whenever allow is set — whether or not allow lists the id, so a caller cannot tell which ids are listed; with only resumeOnly / block set it stays a 404.
| Option | Start | Resume |
|---|---|---|
allow | admitted when listed | admitted when listed |
resumeOnly | refused, even when allow lists it | admitted (no allow entry needed) |
block | refused — wins over allow / resumeOnly | refused — wins over allow / resumeOnly |
A block entry also blocks the flow it resolves to ("user/42" blocks user/:id). resumeOnly: [] and block: [] have no effect.
resumeOnly is for a public trigger that continues a flow only someone else can start — for example the invitee's link of the admin-issued invite flow: a public route resumes auth/invite/start from the emailed link but can never start one (the issuing route, behind its ARBAC grant, lists it in allow).
@Inherit()
@Controller("auth")
class MyAuthController extends AuthController {
/** Public: sign-in flows start here; invite links resume here, but no invite starts here. */
@Post("trigger")
@Public()
@WfTrigger({
allow: ["auth/login/flow", "auth/recovery/flow", "auth/signup/flow"],
resumeOnly: ["auth/invite/start"],
})
override triggerWf(): void {}
/** Issuing: the admin (ARBAC-gated) starts the invite flow and fills its form here. */
@Post("invite")
@ArbacResource("auth.invite")
@ArbacAction("create")
@WfTrigger({ allow: ["auth/invite/start"] })
invite(): void {}
}Since 0.2: allow also governs resume, and [] denies all
A wfs token minted for a workflow outside the route's list is refused with 403 before it is consumed — it stays usable on its own route. This closes route-hopping: a login wfs can no longer be resumed on the authenticated POST /auth/change-password route (which would sidestep the login route's rate limit), and a change-password wfs is refused on the public /auth/trigger. Before 0.2, allow was checked on start only, and allow: [] allowed everything. When you add a trigger route of your own, list exactly the workflows it serves.
Trigger hooks — transactions, pre-persist checks, rendering, retryable links
The trigger passes the @moostjs/event-wf trigger hooks through. Set them app-wide by overriding triggerHooks() on your WfTriggerProvider subclass, or per route on @WfTrigger({...}) — a route's hook replaces the provider's hook of the same name, the others still apply.
import { WfTriggerProvider, type WfTriggerHooks } from "@aooth/auth-moost";
@Injectable()
class MyWfTriggerProvider extends WfTriggerProvider {
protected override triggerHooks(): WfTriggerHooks {
return {
// State row + the steps' writes + outlet side effects in ONE transaction.
around: (run) => db.transaction(() => run()),
// Throw to refuse a pause: nothing is persisted, the outlet is not called.
beforePersist: (state, pause) => {
if (JSON.stringify(state.context).length > 64_000) throw new Error("context too large");
},
};
}
}| Hook | Runs | Use for |
|---|---|---|
around(run) | Wraps everything the request does to state and the outside world: access checks, consume/start/resume, persist, delivery | A database transaction ((run) => db.transaction(run)); may call run() again — each run starts over |
beforePersist(state, pause) | Right before a paused state is persisted, inside around; not on finish. state.context no longer has the rendered ctx.public projection (stripped first, since 0.2.5) | Validating or counting before the pause is saved; throw to abort |
renderEnvelope(body, info) | On every body the trigger answers with — paused envelopes (info.phase: 'paused', info.outlet) and finished values | Translating form texts and messages per request |
restoreOnError / maxRestores | When a resume fails after its single-use token was consumed | Keeping a durable link usable after a transient step failure (opt-in) |
restoreOnError is off by default. With true (or a predicate (error) => boolean choosing which errors qualify) a resume that throws puts the pre-step state back under the same token, so the same link can be retried — at most maxRestores times (default 3), never extending its lifetime. It works only with a durable strategy that reports expiries (HandleStateStrategy over a store that does); encapsulated tokens are never consumed, so they need no restore.
- DO keep the workflow-state store inside the
aroundtransaction — if the commit fails afterrun()succeeded and the store is outside it, the token is spent while the steps' writes roll back. - DON'T enable
restoreOnErroron a route whose steps have side effects that must not run twice (sent emails, charged payments): a restore rolls back the workflow context, not the outside world. - DO enable it per route (
@WfTrigger({ restoreOnError })), or pass a predicate that accepts only transient store errors, e.g.restoreOnError: (error) => isTransientStoreError(error)with your own check. A provider-widetruealso covers aooth's own credential-changing steps (set password, recovery reset, MFA enrolment): a failure after such a step puts its single-use link back. The bundled password forms refuse a restored state once the password has changed (410,code: "PASSWORD_CHANGED_SIGN_IN_AGAIN"), but other effects of the failed request stay done. - DON'T use
renderEnvelopefor errors — refused requests and step errors go through the HTTP app's error-body hook.
Exact semantics: the wooks outlets guide — Transactions and envelopes and Retrying a failed resume.
createAuthEmailOutlet(deps)
Builds the email outlet that delivers magic links: the invite link, and the recovery and sign-in links (recovery.magicLink / login.magicLink, handed over by the bundled magic-link outlet). deps.buildMagicLinkUrl is the 3-arg BuildMagicLinkUrl — (kind, token, ctx?: { userId? }) => string — where the { userId } arg is supplied for the invite.magicLink kind so the URL can carry the invitee id for the post-redemption side route. Add the outlet to WfTriggerProvider.outlets. See createAuthEmailOutlet.
Finish + error envelopes
Steps end a run with finishWf(opts) (success) or abortWf(reason, opts) (user-initiated abort), and re-pause on a retriable error with wf.requireInput(...). finishWf / abortWf / FinishWfOpts / WfFinished are from @atscript/moost-wf — the unified envelope (next: { trigger, action?, primary?, options? }, auto-redirect countdown, manual choice, aborted soft-failure) is owned by that package; see the atscript-ui-wf docs for its full shape. The login path attaches session cookies to the finish envelope via useAuth().buildFinishedCookies(issue).
Error patterns — retriable vs terminal
@Step bodies throw exactly two shapes. Pick by asking: can the user fix this from the form they are looking at?
| Shape | Behaviour | Use for |
|---|---|---|
throw wf.requireInput({ errors, formMessage? }) — retriable | Engine re-persists state under the SAME wfs handle and re-renders the form with per-field errors. The token survives. | Wrong password, invalid OTP, mismatched confirm-password, duplicate email, missing required consent, account lockout, "session limit reached". |
throw new HttpError(<status>, <msg>) — terminal | The token is consumed (unless restoreOnError restores it); the SPA renders a final error. | 500 state corruption, 501 not-implemented stubs, 410 cancelled / replaced invite, 403 feature disabled, 409 CAS exhausted. |
wf is the handle from useAtscriptWf(FormSchema). The form payload + @wf.context.pass keys are auto-included in the re-render, so the SPA's next render sees fresh ctx without an extra round-trip.
// ✅ Retriable — user corrects input on the same form (token survives).
throw wf.requireInput({ formMessage: this.msg("INVALID_CREDENTIALS") });
throw wf.requireInput({ errors: { confirmPassword: this.msg("PASSWORDS_DO_NOT_MATCH") } });
// ❌ Terminal — not a client error; no form to retry from.
if (!ctx.subject) throw new HttpError(500, "Workflow state corrupted: missing subject");
if (!this.isCancellationEnabled()) throw new HttpError(403, "Invite cancellation is disabled");Never throw HttpError(4xx) for a user-fixable input error
A terminal HttpError consumes the wfs token — the user's next submission lands on a dead handle and gets 410 Gone. Use wf.requireInput for anything the user can correct from the open form.
Workflow state tokens (wfs)
The wfs URL / body / cookie token is the single resume handle for a paused run. It is stable across:
wf.requireInputretries — the URLwfs=…stays live; the user fixes input and resubmits.- Browser refresh / bookmark / revisit — the URL's
wfs=…resumes at the current pause. - Multi-tab — concurrent submissions on one token serialize; the loser gets the form re-render under the same handle.
The token mints fresh only at three boundaries: (1) workflow start (no incoming token); (2) workflow finish (no token persisted — a later POST /auth/trigger with the dead token returns 410 Gone); (3) workflow-id change (replaying a auth/login/flow token against auth/recovery/flow).
Use delete ctx.field, not ctx.field = undefined
The state persistence layer JSON-schema-validates the serialized ctx and rejects undefined (allowed: string / number / boolean / null / array / object). To clear an optional ctx field at the end of a step body, delete ctx.field (or assign false / null if a forward step reads presence).
Rendering the forms (SPA)
The bundled forms are server-driven atscript types; the SPA renders them with <AsWfForm> (@atscript/vue-wf) and registers the aooth companion components (AsConsentArray, AsPasswordRules, AsQrCode) by name. See SPA Components.
See also
- API reference — full signatures for
AuthWorkflow,AuthWorkflowOpts,ConsentStore,WfTriggerProvider,AuthDeliveryPayload. - REST Controllers — the
/auth/triggerendpoint that dispatches into these workflows. - SPA Components — client-side rendering of the workflow forms.
- Config Reference —
AuthOptions+AuthWorkflowOptsdefaults. - packages/auth-moost/CLAUDE.md — the canonical workflow-authoring conventions.