@aooth/auth-moost 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { Mate, TConsoleBase, TInterceptorDef, TMateParamMeta, TMoostMetadata } from "moost";
2
- import { AuthContext, AuthContext as AuthContext$1, AuthCredential, AuthEmailEvent, AuthEmailKind, AuthEmailKind as AuthEmailKind$1, AuthSmsEvent, AuthSmsKind, BuildMagicLinkUrl, BuildMagicLinkUrl as BuildMagicLinkUrl$1, CredentialMetadata, EmailSender, EmailSender as EmailSender$1, EnrichedSession, EnrichedSession as EnrichedSession$1, IssueResult, IssueResult as IssueResult$1, RateLimitDecision, RateLimitDecision as RateLimitDecision$1, RateLimitRule, RateLimitRule as RateLimitRule$1, RateLimitRuleInput, RateLimitRuleInput as RateLimitRuleInput$1, RateLimitStore, RateLimitStore as RateLimitStore$1, RateLimitStoreMemory, RateLimiter, RateLimiter as RateLimiter$1, RateLimiterOptions, SessionEnricher, SessionEnricher as SessionEnricher$1, SessionInfo, SessionInfo as SessionInfo$1, SmsSender, generateMagicLinkToken } from "@aooth/auth";
2
+ import { AuthContext, AuthContext as AuthContext$1, AuthCredential, AuthEmailEvent, AuthEmailKind, AuthEmailKind as AuthEmailKind$1, AuthSmsEvent, AuthSmsKind, BuildMagicLinkUrl, BuildMagicLinkUrl as BuildMagicLinkUrl$1, CredentialMetadata, EmailSender, EmailSender as EmailSender$1, EnrichedSession, EnrichedSession as EnrichedSession$1, IssueResult, IssueResult as IssueResult$1, RateLimitDecision, RateLimitDecision as RateLimitDecision$1, RateLimitRule, RateLimitRule as RateLimitRule$1, RateLimitRuleInput, RateLimitRuleInput as RateLimitRuleInput$1, RateLimitStore, RateLimitStore as RateLimitStore$1, RateLimitStoreMemory, RateLimitStoreMemory as RateLimitStoreMemory$1, RateLimiter, RateLimiter as RateLimiter$1, RateLimiterOptions, SessionEnricher, SessionEnricher as SessionEnricher$1, SessionInfo, SessionInfo as SessionInfo$1, SmsSender, generateMagicLinkToken } from "@aooth/auth";
3
3
  import { EventContext } from "@wooksjs/event-core";
4
4
  import { HttpError, TCookieAttributesInput } from "@wooksjs/event-http";
5
- import { FederatedIdentityStore, FederatedProfileSnapshot, MfaMethod, TransferablePolicy, TrustedDeviceRecord, UserAuthError, UserAuthErrorType, UserCredentials, UserService } from "@aooth/user";
5
+ import { FederatedIdentityStore, FederatedProfileSnapshot, MfaMethod, TransferablePolicy, TrustedDeviceRecord, UserAuthError, UserAuthErrorCode, UserCredentials, UserService } from "@aooth/user";
6
6
  import { HttpError as HttpError$1 } from "@moostjs/event-http";
7
7
  import { FinishWfOpts, WfFinished, useAtscriptWf } from "@atscript/moost-wf";
8
- import { MoostWf, WfOutlet, WfOutletTokenConfig, WfOutletTriggerConfig, WfStateStrategy } from "@moostjs/event-wf";
8
+ import { MoostWf, WfOutlet, WfOutletTokenConfig, WfOutletTriggerConfig, WfStateStore, WfStateStoreMemory, WfStateStrategy } from "@moostjs/event-wf";
9
9
  import { FederatedLoginService, NormalizedProfile, OAuthProviderRegistry } from "@aooth/idp";
10
10
  import { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
11
11
  import { AuthCodeStore, AuthorizationServerMetadata, AuthorizationServerMetadata as AuthorizationServerMetadata$1, BuildAuthorizationServerMetadataOptions, BuildProtectedResourceMetadataOptions, ClientRedirectPolicy, DynamicClientRegistration, DynamicClientRegistration as DynamicClientRegistration$1, DynamicClientRegistrationOptions, IdTokenSigner, OidcClaimsResolver, PendingAuthorizationStore, ProtectedResourceMetadata, WwwAuthenticateBearerChallengeOptions, buildAuthorizationServerMetadata, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer } from "@aooth/auth/authz";
@@ -339,45 +339,80 @@ export declare function getAuthMate(): AuthMate;
339
339
  * form errors, banners, finish envelopes and button labels. Templates are
340
340
  * English; `{name}` placeholders are filled from the message params.
341
341
  *
342
+ * Registered with moost's `registerMessages` on import, so a moost translator
343
+ * (`setTranslator`) translates every code and `$i18n` serves the templates.
342
344
  * Override per app with `AuthWorkflowOpts.messages` (a partial map, or a
343
- * function that receives the code and params and returns the text — e.g. a
344
- * lookup in your own i18n library), or override `AuthWorkflow.msg()`.
345
+ * function that receives the code and params and returns the text), or
346
+ * override `AuthWorkflow.msg()`.
345
347
  */
346
348
  export declare const AOOTH_MESSAGES: {
347
349
  readonly INVALID_CREDENTIALS: "Invalid credentials";
348
- readonly ACCOUNT_LOCKED: "Account locked, please try again later";
350
+ readonly AOOTH_ACCOUNT_LOCKED: "Account locked, please try again later";
349
351
  readonly INVALID_PASSWORD: "Invalid password";
350
352
  readonly INCORRECT_PASSWORD: "Incorrect password";
351
353
  readonly SESSION_LIMIT_REACHED: "Session limit reached";
352
354
  readonly PASSWORD_CHANGED_SIGN_IN_AGAIN: "Your password was changed. Please sign in again.";
353
- readonly INVALID_CODE: "Invalid code";
355
+ readonly AOOTH_INVALID_CODE: "Invalid code";
356
+ readonly AOOTH_CODE_EXPIRED: "Code expired";
357
+ readonly AOOTH_TOO_MANY_CODE_ATTEMPTS: "Too many invalid attempts. Please request a new code.";
354
358
  /** Params: `seconds`. */
355
- readonly RESEND_WAIT: "Please wait {seconds}s before requesting a new code.";
359
+ readonly AOOTH_RESEND_WAIT: "Please wait {seconds}s before requesting a new code.";
356
360
  /** Params: `seconds`. */
357
- readonly RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code";
361
+ readonly AOOTH_RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code";
358
362
  /** Params: `seconds`, `channel` (`SMS` / `email`). */
359
- readonly RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code";
363
+ readonly AOOTH_RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code";
360
364
  readonly TOTP_RESEND_NOT_APPLICABLE: "Resend is not applicable for TOTP";
365
+ /** HTTP 400 — a TOTP code submitted for an account without TOTP. */
366
+ readonly TOTP_NOT_CONFIGURED: "No TOTP MFA configured";
367
+ readonly AOOTH_ADDRESS_REQUIRED: "This field is required";
368
+ readonly AOOTH_INVALID_EMAIL_ADDRESS: "Enter a valid email address";
369
+ readonly AOOTH_INVALID_PHONE_NUMBER: "Enter a valid phone number";
370
+ readonly OTP_DISCLOSURE_EMAIL: "By providing your email address, you consent to receive one-time security codes from us via email. Standard email delivery may apply.";
371
+ readonly OTP_DISCLOSURE_PHONE: "By providing your phone number, you consent to receive one-time security codes from us via SMS. Message and data rates may apply.";
361
372
  readonly UNKNOWN_MFA_METHOD: "Unknown MFA method";
362
- readonly UNKNOWN_METHOD: "Unknown method";
363
- readonly METHOD_UNAVAILABLE: "That method isn't available";
364
- readonly METHOD_NOT_CHANGEABLE: "That method can't be changed here.";
373
+ readonly AOOTH_UNKNOWN_METHOD: "Unknown method";
374
+ readonly AOOTH_METHOD_UNAVAILABLE: "That method isn't available";
375
+ readonly AOOTH_METHOD_NOT_CHANGEABLE: "That method can't be changed here.";
365
376
  readonly KEEP_ONE_MFA_METHOD: "You must keep at least one two-factor method.";
366
- readonly CHOOSE_OPTION: "Choose an option";
377
+ readonly AOOTH_CHOOSE_OPTION: "Choose an option";
367
378
  readonly ALL_MFA_METHODS_SET_UP: "You've already set up every available authentication method.";
368
379
  readonly NO_MFA_CHANGES: "No changes were made to your two-factor methods.";
380
+ readonly LAST_MFA_METHOD_NOT_REMOVABLE: "You must keep at least one two-factor method, so this one can't be removed.";
381
+ readonly MFA_METHOD_TOTP: "Authenticator app";
382
+ readonly MFA_METHOD_EMAIL: "Email code";
383
+ readonly MFA_METHOD_SMS: "Text-message code";
384
+ /** Params: `method` (the method's label). */
385
+ readonly MFA_METHOD_ADDED: "{method} added.";
386
+ /** Params: `method`. */
387
+ readonly MFA_METHOD_UPDATED: "{method} updated.";
388
+ /** Params: `method`. */
389
+ readonly MFA_METHOD_REMOVED: "{method} removed.";
369
390
  readonly PASSWORDS_DO_NOT_MATCH: "Passwords do not match";
370
391
  readonly PASSWORD_CHANGE_TOO_RECENT: "You changed your password too recently. Please try again later.";
371
392
  readonly PASSWORD_CHANGED: "Your password has been changed.";
372
393
  readonly PASSWORD_UPDATED_REDIRECTING: "Password updated. Redirecting to sign-in…";
373
394
  readonly PASSWORD_UPDATED_STILL_LOCKED: "Password updated, but your account is still locked. Contact an administrator to regain access.";
374
- readonly RECOVERY_INSTRUCTIONS_SENT: "If an account exists, you will receive instructions.";
395
+ readonly CHANGE_PASSWORD_HEADING: "Change your password";
396
+ readonly CHANGE_PASSWORD_INTRO: "Enter your current password, then choose a new one.";
397
+ readonly SET_PASSWORD_EXPIRED_HEADING: "Your password has expired";
398
+ readonly SET_PASSWORD_EXPIRED_INTRO: "Choose a new password to continue. The previous one is no longer valid.";
399
+ readonly SET_PASSWORD_RESET_HEADING: "Reset your password";
400
+ readonly SET_PASSWORD_RESET_INTRO: "Choose a new password for your account.";
401
+ readonly SET_PASSWORD_INVITE_HEADING: "Welcome — set your password";
402
+ readonly SET_PASSWORD_INVITE_INTRO: "Choose a password to activate your account.";
403
+ readonly SET_PASSWORD_INITIAL_HEADING: "Set your initial password";
404
+ readonly SET_PASSWORD_INITIAL_INTRO: "Your account was created without a password. Choose one to continue.";
405
+ /** A magic link that cannot be used: expired, of another purpose, or already used up. */
406
+ readonly AOOTH_MAGIC_LINK_INVALID: "This link is invalid or has expired. Please request a new one.";
375
407
  readonly SIGNUP_DISABLED: "Self-signup is currently disabled.";
376
- readonly ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.";
377
- readonly ACCOUNT_LINKED: "Account linked.";
378
- readonly INVALID_ROLE: "Invalid role";
408
+ readonly AOOTH_ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.";
409
+ readonly AOOTH_ACCOUNT_LINKED: "Account linked.";
410
+ /** HTTP 400 — the SSO alt action named a provider that is not offered. */
411
+ readonly UNKNOWN_SSO_PROVIDER: "Unknown SSO provider";
412
+ readonly AOOTH_ACCOUNT_CREATED: "Your account has been created.";
413
+ readonly AOOTH_INVALID_ROLE: "Invalid role";
379
414
  readonly INVITE_ALREADY_PENDING: "Invite already pending";
380
- readonly USER_ALREADY_EXISTS: "User already exists";
415
+ readonly AOOTH_USER_ALREADY_EXISTS: "User already exists";
381
416
  readonly DUPLICATE_INVITE_REJECTED: "Duplicate invite rejected";
382
417
  readonly INVITE_CANCELLED: "This invite has been cancelled";
383
418
  readonly INVITE_REPLACED: "This invite was replaced by a newer one";
@@ -390,8 +425,8 @@ export declare const AOOTH_MESSAGES: {
390
425
  readonly GO_TO_SIGN_IN: "Go to sign-in";
391
426
  readonly BACK_TO_SIGN_IN: "Back to sign-in";
392
427
  readonly REQUEST_NEW_INVITE: "Request a new invite";
393
- readonly BACK: "Back";
394
- readonly GO_NOW: "Go now";
428
+ readonly AOOTH_BACK: "Back";
429
+ readonly AOOTH_GO_NOW: "Go now";
395
430
  };
396
431
  /** A message code of {@link AOOTH_MESSAGES}. */
397
432
  type AoothMessageCode = keyof typeof AOOTH_MESSAGES;
@@ -405,7 +440,11 @@ type AoothMessageParams = Readonly<Record<string, string | number>>;
405
440
  type AoothMessages = Partial<Record<AoothMessageCode, string>> | ((code: AoothMessageCode, params: AoothMessageParams) => string | undefined);
406
441
  /** Fill `{name}` placeholders from `params`; unknown placeholders are kept. */
407
442
  export declare function renderAoothMessage(template: string, params?: AoothMessageParams): string;
408
- /** Resolve `code` through `messages` (when given), falling back to the English template. */
443
+ /**
444
+ * Resolve `code`: `messages` (the app's override, when given), then moost's
445
+ * translator in the current event's locale (`useTranslate`), then the English
446
+ * template. Outside an event the translator is skipped.
447
+ */
409
448
  export declare function resolveAoothMessage(code: AoothMessageCode, params?: AoothMessageParams, messages?: AoothMessages): string;
410
449
  /** Workflows allowed by the bundled `/auth/trigger` endpoint. Subclasses override `triggerWf()` to extend. */
411
450
  export declare const DEFAULT_AUTH_WORKFLOWS: readonly ["auth/login/flow", "auth/invite/start", "auth/recovery/flow", "auth/signup/flow"];
@@ -455,6 +494,14 @@ export declare class AuthController {
455
494
  */
456
495
  initRefreshCookiePath(paths: string[], logger: TConsoleBase): Promise<void>;
457
496
  logout(body: AuthLogoutBody | undefined): Promise<AuthOkResponse>;
497
+ /**
498
+ * Rotate the access/refresh pair. Rate limited by two policies, enforced
499
+ * when `rateLimitInterceptors` are installed ({@link REFRESH_RATE_LIMITS}):
500
+ * `aooth.refresh` per client IP (checked before the auth guard, so a flood
501
+ * of junk tokens costs no lookups), and `aooth.refresh-token` per presented
502
+ * refresh token from any IP (a request without one skips it — the handler
503
+ * answers 401).
504
+ */
458
505
  refresh(body: AuthRefreshBody | undefined): Promise<AuthLoginResponse>;
459
506
  status(): AuthContext$1;
460
507
  triggerWf(): void;
@@ -593,28 +640,32 @@ export declare class SessionsController {
593
640
  /** The body of an `HttpError` made by {@link userAuthErrorToHttp}. */
594
641
  interface UserAuthErrorBody {
595
642
  message: string;
596
- /** The `UserAuthError` type (`"PASSWORD_IN_HISTORY"`, `"NOT_FOUND"`, …). */
597
- code: UserAuthErrorType;
598
- /** `POLICY_VIOLATION`: `{ policies: [{ description, passed }] }` — every policy and its result. */
643
+ /** The `UserAuthError`'s message code (`"PASSWORD_IN_HISTORY"`, `"AOOTH_USER_LOCKED"`, …) — see `USER_AUTH_ERROR_CODES`. */
644
+ code: UserAuthErrorCode;
645
+ /**
646
+ * `POLICY_VIOLATION`: `{ policies: [{ description, passed, errorMessage, code?, params? }] }`
647
+ * — every policy and its result (`code` / `params`: the built-in policies' `PP_*` codes).
648
+ */
599
649
  params?: Record<string, unknown>;
600
650
  /** The form field the error belongs to (password errors only). */
601
651
  field?: "currentPassword" | "newPassword" | "confirmPassword";
602
652
  }
603
653
  /**
604
654
  * Map a `UserAuthError` (thrown by `UserService`) to an `HttpError` whose body
605
- * carries `code` (the error type), the message and — for password errors —
606
- * the form `field` it belongs to (named as in the bundled password forms):
655
+ * carries `code` (the error's message code, `err.code`), the message and — for
656
+ * password errors — the form `field` it belongs to (named as in the bundled
657
+ * password forms):
607
658
  *
608
- * | type | status | field |
609
- * |---|---|---|
610
- * | `NOT_FOUND` | 404 | |
611
- * | `ALREADY_EXISTS`, `CAS_EXHAUSTED` | 409 | |
612
- * | `INVALID_CREDENTIALS` | 400 | `currentPassword` |
613
- * | `PASSWORD_IN_HISTORY` | 400 | `newPassword` |
614
- * | `POLICY_VIOLATION` (+ `params.policies`) | 422 | `newPassword` |
615
- * | `PASSWORDS_MISMATCH` | 400 | `confirmPassword` |
616
- * | `MFA_INVALID`, `MFA_NOT_CONFIGURED` | 400 | |
617
- * | `INACTIVE`, `LOCKED`, `MFA_REQUIRED` | 403 | |
659
+ * | type | code | status | field |
660
+ * |---|---|---|---|
661
+ * | `NOT_FOUND` | `NOT_FOUND` | 404 | |
662
+ * | `ALREADY_EXISTS`, `CAS_EXHAUSTED` | `AOOTH_USER_ALREADY_EXISTS`, `AOOTH_USER_CAS_EXHAUSTED` | 409 | |
663
+ * | `INVALID_CREDENTIALS` | `INVALID_CREDENTIALS` | 400 | `currentPassword` |
664
+ * | `PASSWORD_IN_HISTORY` | `PASSWORD_IN_HISTORY` | 400 | `newPassword` |
665
+ * | `POLICY_VIOLATION` (+ `params.policies`) | `AOOTH_USER_POLICY_VIOLATION` | 422 | `newPassword` |
666
+ * | `PASSWORDS_MISMATCH` | `PASSWORDS_MISMATCH` | 400 | `confirmPassword` |
667
+ * | `MFA_INVALID`, `MFA_NOT_CONFIGURED` | same as type | 400 | |
668
+ * | `INACTIVE`, `LOCKED`, `MFA_REQUIRED` | `AOOTH_USER_INACTIVE`, `AOOTH_USER_LOCKED`, `MFA_REQUIRED` | 403 | |
618
669
  *
619
670
  * For routes such as an admin "set password" endpoint. Do not use it on a
620
671
  * sign-in endpoint: distinct answers for unknown, inactive and locked accounts
@@ -653,6 +704,8 @@ declare const HOOK_NAMES: readonly ["around", "beforePersist", "renderEnvelope",
653
704
  * call `run()` again after a failure; each run starts over from the request.
654
705
  * - `beforePersist(state, pause)` — runs right before a paused state is
655
706
  * persisted, inside `around`; throw to abort (nothing persisted, no delivery).
707
+ * `AuthWorkflow`'s rendered `ctx.public` projection is already stripped
708
+ * from `state.context` then (it is never persisted).
656
709
  * - `renderEnvelope(envelope, info)` — maps every body the trigger answers
657
710
  * with (paused envelopes and finished values), e.g. to translate texts.
658
711
  * - `restoreOnError` — opt-in (default off): when a resume fails after its
@@ -742,9 +795,11 @@ export declare class WfTriggerProvider {
742
795
  protected readonly wf: MoostWf;
743
796
  protected readonly auth: AuthCredential;
744
797
  /**
745
- * Outlets the trigger can pause on: HTTP (forms) and `invite` (the link of
746
- * `AuthWorkflowOpts.inviteDelivery: 'deliver' | 'return-link'`). Append an
747
- * `email` outlet (`createAuthEmailOutlet`) for the default invite delivery.
798
+ * Outlets the trigger can pause on: HTTP (forms), `invite` (the link of
799
+ * `AuthWorkflowOpts.inviteDelivery: 'deliver' | 'return-link'`) and
800
+ * `magic-link` (recovery and sign-in links — it sends through the `email`
801
+ * outlet). Append an `email` outlet (`createAuthEmailOutlet`) for the default
802
+ * invite delivery and for magic links.
748
803
  */
749
804
  protected outlets: WfOutlet[];
750
805
  protected token: WfOutletTokenConfig;
@@ -759,10 +814,36 @@ export declare class WfTriggerProvider {
759
814
  * `return deriveWfStateSecret(env.MY_SECRET)`.
760
815
  */
761
816
  protected wfStateSecret(): string | Buffer;
817
+ /**
818
+ * Secret that keys the digests of one-time codes (recovery, sign-in, signup
819
+ * and enrolment codes) held in workflow state — the state keeps a keyed
820
+ * digest of each code, never the code. Default: the wf-state secret, so a
821
+ * store-backed setup that overrides `wfStateSecret()` needs nothing more.
822
+ * All instances must agree on it.
823
+ */
824
+ protected pincodeSecret(): string | Buffer;
825
+ private cachedPincodeKey?;
826
+ /**
827
+ * The key of the one-time-code digests this provider publishes on every
828
+ * request: {@link derivePincodeKey} of {@link pincodeSecret}. With the
829
+ * default secrets it equals what `AuthWorkflow.pincodeKey()` derives outside
830
+ * a provider (`defaultPincodeKey`).
831
+ */
832
+ protected pincodeKey(): Buffer;
762
833
  /** TTL (ms) for encapsulated pre-validation tokens. Default: undefined = no TTL (token valid until used), so an idle login form never expires server-side. */
763
834
  protected wfStateEncapsulatedTtlMs(): number | undefined;
764
835
  /** Durable strategy a workflow swaps to after the first validated input. Default = encapsulated (no real store); customers override to return e.g. new HandleStateStrategy({ store: <redis/db> }). */
765
836
  protected storeStrategy(): WfStateStrategy;
837
+ /**
838
+ * Store of the magic-link pauses (recovery and sign-in links). Default: one
839
+ * in-memory store per provider — single process only. With several
840
+ * instances, return a shared `WfStateStore` (e.g. the `AsWfStore` of your
841
+ * wf-state table). The strategy around it is fixed: handles are stored
842
+ * hashed (a read of the store yields no usable link), each link is consumed
843
+ * by its first use, and it expires with the link (`magicLinkTtlMs`).
844
+ */
845
+ protected magicLinkStore(): WfStateStore;
846
+ private defaultMagicLinkStore?;
766
847
  private makeEncapsulated;
767
848
  /**
768
849
  * App-wide workflow-trigger hooks ({@link WfTriggerHooks}): `around`,
@@ -778,7 +859,7 @@ export declare class WfTriggerProvider {
778
859
  */
779
860
  protected triggerHooks(): WfTriggerHooks;
780
861
  private cachedState?;
781
- /** Named strategy registry: every wf starts on `encapsulated` (default); a step calls swapStrategy('store') to move durable. Built lazily so subclass overrides (storeStrategy/wfStateSecret) are in effect. */
862
+ /** Named strategy registry: every wf starts on `encapsulated` (default); a step calls swapStrategy('store') to move durable, and a magic-link pause swaps to `magic-link`. Built lazily so subclass overrides (storeStrategy/wfStateSecret/magicLinkStore) are in effect. */
782
863
  protected stateRegistry(): StateRegistry;
783
864
  /**
784
865
  * Handle one trigger request. `allow` lists the workflow ids this route may
@@ -826,14 +907,16 @@ export declare function createInviteOutlet(): WfOutlet;
826
907
  * `'session'` (per login/device) derive from the auth context; anything
827
908
  * unresolved falls back to the IP budget. `'auto'` is an alias of
828
909
  * `'user'`. Apps supply their own kinds (`'tenant'`, `'apiKey'`, …) via
829
- * `setRateLimitSubject`.
910
+ * `setRateLimitSubject`. `'refresh-token'` keys on the refresh token the
911
+ * request presents (body `refreshToken`, else the refresh cookie), hashed;
912
+ * a request without one skips the policy.
830
913
  * - custom function — runs inside the event context PRE-guard; must be
831
914
  * self-sufficient (it cannot read what GUARD-priority code sets). Return
832
915
  * a composite subject (e.g. client IP + submitted username) to key on
833
916
  * several things at once, or `null` / `undefined` to SKIP the policy for
834
917
  * this request (nothing is counted).
835
918
  */
836
- type RateLimitKeyStrategy = "ip" | "user" | "auto" | "session" | (string & {}) | (() => string | null | undefined | Promise<string | null | undefined>);
919
+ type RateLimitKeyStrategy = "ip" | "user" | "auto" | "session" | "refresh-token" | (string & {}) | (() => string | null | undefined | Promise<string | null | undefined>);
837
920
  /** Trailing options object accepted by `@RateLimit(...rules, opts)`. */
838
921
  interface RateLimitDecoratorOptions {
839
922
  /** Overrides the interceptor-level default key strategy for this route. */
@@ -900,7 +983,21 @@ interface RateLimitInterceptorOptions {
900
983
  trustProxy?: boolean;
901
984
  /** Emit draft `RateLimit-*` headers on every response of a limited route. Default: `true`. */
902
985
  headers?: boolean;
903
- /** App-wide default 429 message template (placeholders `{{limit}}`, `{{window}}`, `{{delta}}`). */
986
+ /**
987
+ * Re-tune declared policies without redeclaring their routes, by policy id
988
+ * (the `id` a `@RateLimit` names, or a bundled id such as `aooth.refresh` /
989
+ * `aooth.send`): new rules replace the declared ones — the key strategy, id
990
+ * and message stay — and `false` switches the policy off. E.g.
991
+ * `{ "aooth.refresh": "300/5m", "aooth.refresh-token": false }`. Parsed at
992
+ * registration, like `rules`; an id no policy declared throws.
993
+ */
994
+ policies?: Record<string, RateLimitRuleInput$1 | RateLimitRuleInput$1[] | false>;
995
+ /**
996
+ * App-wide default 429 message template (placeholders `{{limit}}`,
997
+ * `{{window}}`, `{{delta}}` humanized; `{limit}`, `{window}`, `{retryAfter}`
998
+ * in seconds). Under a moost translator the body is translated by its
999
+ * `RATE_LIMITED` code, which replaces this English text.
1000
+ */
904
1001
  message?: string;
905
1002
  }
906
1003
  /**
@@ -1330,6 +1427,13 @@ export declare class AuthorizeController {
1330
1427
  */
1331
1428
  protected scopesSupported(): string[] | undefined;
1332
1429
  authorize(responseType: string | undefined, redirectUri: string | undefined, clientId: string | undefined, state: string | undefined, codeChallenge: string | undefined, codeChallengeMethod: string | undefined, scope: string | undefined, nonce: string | undefined, resource: string | undefined): Promise<string>;
1430
+ /**
1431
+ * Rate limited when `rateLimitInterceptors` are installed
1432
+ * ({@link AUTHZ_RATE_LIMITS}): `aooth.token` per client IP, and
1433
+ * `aooth.token-refresh` per presented `refresh_token` of a refresh grant.
1434
+ * Both are checked before the auth guard; over the limit the endpoint
1435
+ * answers the coded `429` (`RATE_LIMITED`, `Retry-After`).
1436
+ */
1333
1437
  token(body: TokenRequestBody | undefined): Promise<TokenSuccess | TokenError>;
1334
1438
  /**
1335
1439
  * `grant_type=refresh_token` (OAuth 2.1 §4.3): rotate the presented refresh
@@ -1589,8 +1693,14 @@ interface AuthWfMfaEnrollState {
1589
1693
  interface AuthWfPasswordUiState {
1590
1694
  policies?: TransferablePolicy[];
1591
1695
  changeReason?: "initial" | "expired" | "reset";
1696
+ /** The app's own heading (`resolveSetPasswordCopy`), shown as is; wins over `headingCode`. */
1592
1697
  heading?: string;
1698
+ /** The app's own intro, shown as is; wins over `introCode`. */
1593
1699
  intro?: string;
1700
+ /** The default heading's message code — rendered through `msg()` in each request's language. */
1701
+ headingCode?: AoothMessageCode;
1702
+ /** The default intro's message code. */
1703
+ introCode?: AoothMessageCode;
1594
1704
  }
1595
1705
  /**
1596
1706
  * Completion outcome — carries data set by terminal steps. Step-completion
@@ -1674,12 +1784,32 @@ interface AuthWfSessionState {
1674
1784
  activeSessions?: number;
1675
1785
  riskStepUpEvaluated?: boolean;
1676
1786
  }
1787
+ /** How recovery delivers its proof of inbox: a one-time code, a magic link, or the user's pick. */
1788
+ type AuthWfRecoveryDeliveryMode = "otp" | "magicLink" | "choice";
1789
+ /** Server-only state of a magic link (recovery or sign-in). */
1790
+ interface AuthWfMagicLinkState {
1791
+ /** What the link may do: reset the password, or sign in (first factor only). */
1792
+ purpose: "recovery" | "login";
1793
+ /** The account the identifier resolved to — unset for an unknown identifier. */
1794
+ subject?: string;
1795
+ /** The typed identifier, normalised — kept only until the send (the cooldown key of an unknown one). */
1796
+ identifier?: string;
1797
+ /** Where the link went (an inbox the account proved) — unset when nothing was sent. */
1798
+ address?: string;
1799
+ /** Set when the link pause was persisted; the resume (the click) skips the send. */
1800
+ sentAt?: number;
1801
+ /** When the link stops working. */
1802
+ expiresAt?: number;
1803
+ /** Set once the landing step ("Continue as …") was submitted — the link is then used up. */
1804
+ confirmed?: boolean;
1805
+ /** Sign-in links bound to the requesting browser: a hash of the binding cookie's nonce. */
1806
+ browser?: string;
1807
+ }
1677
1808
  /** Alt-credential mirror flags (login). */
1678
1809
  interface AuthWfAltActionsState {
1679
1810
  forgotPassword?: boolean;
1680
1811
  signup?: boolean;
1681
1812
  magicLink?: boolean;
1682
- usedMagicLink?: boolean;
1683
1813
  /** SSO providers offered on the login form — each renders a `sso-<id>` button. */
1684
1814
  ssoProviders?: SsoProvider[];
1685
1815
  }
@@ -1688,11 +1818,15 @@ interface AuthWfAltCredsPolicy {
1688
1818
  forgotPassword: boolean;
1689
1819
  signup: boolean;
1690
1820
  magicLink: boolean;
1691
- magicLinkSkipsMfa: boolean;
1821
+ /**
1822
+ * Bind sign-in links to the browser that asked for them (a cookie nonce):
1823
+ * the link then works only there. Default `false` — opening the email on
1824
+ * another device is legitimate.
1825
+ */
1826
+ magicLinkSameBrowser?: boolean;
1692
1827
  ssoProviders: SsoProvider[];
1693
1828
  recoveryUrl: string;
1694
1829
  signupUrl: string;
1695
- embedRecovery: boolean;
1696
1830
  }
1697
1831
  /** Device-trust policy (login). */
1698
1832
  interface AuthWfDeviceTrustPolicy {
@@ -1816,6 +1950,7 @@ interface AuthWfAcceptState {
1816
1950
  alreadyAcceptedRedirectUrl?: string;
1817
1951
  loginUrl?: string;
1818
1952
  showConfirmation?: boolean;
1953
+ /** The app's own confirmation text, shown as is; default: `AOOTH_ACCOUNT_CREATED`, rendered per request. */
1819
1954
  confirmationMessage?: string;
1820
1955
  alreadyAccepted?: boolean;
1821
1956
  /** `inviteUsername: 'choose'` — the invitee picks their username at accept. */
@@ -1948,7 +2083,7 @@ interface AuthWfOAuthState {
1948
2083
  * (the schema gate right after `sso-callback`) is what keeps an unproven user
1949
2084
  * out of the token-issuing tail. The `snapshot` has `profile.raw` stripped (raw
1950
2085
  * claims are never persisted — RFC §7). The OTP-proof code lives HERE, not on the
1951
- * shared top-level `ctx.pin`, so it cannot collide with the post-link MFA loop's
2086
+ * shared top-level code fields (`ctx.pinNonce` …), so it cannot collide with the post-link MFA loop's
1952
2087
  * own pincode in the same run.
1953
2088
  */
1954
2089
  interface AuthWfPendingLinkState {
@@ -1974,9 +2109,9 @@ interface AuthWfPendingLinkState {
1974
2109
  hint?: string;
1975
2110
  /** OTP mode only — masked delivery target for the "code sent to …" copy. Safe to expose. */
1976
2111
  sentTo?: string;
1977
- pin?: string;
2112
+ pinNonce?: string;
2113
+ pinDigest?: string;
1978
2114
  pinExpire?: number;
1979
- pinAttempts?: number;
1980
2115
  }
1981
2116
  /**
1982
2117
  * Standalone add-MFA flow state (`auth/add-mfa/flow`). Populated by
@@ -2105,6 +2240,10 @@ interface AuthWfPublicState {
2105
2240
  pending?: ConsentDescriptorLike[];
2106
2241
  decidedAt?: number;
2107
2242
  };
2243
+ /** The account a clicked magic link signs into / resets, masked (`MagicLinkConfirmForm`). */
2244
+ magicLink?: {
2245
+ account?: string;
2246
+ };
2108
2247
  /** Mirrors `ctx.altActions` — which alt-action buttons render on login (incl. SSO providers). */
2109
2248
  altActions?: {
2110
2249
  forgotPassword?: boolean;
@@ -2227,10 +2366,11 @@ interface AuthWfCtx {
2227
2366
  */
2228
2367
  email?: string;
2229
2368
  defaults?: AuthWfDefaults;
2230
- pin?: string;
2369
+ /** Random id of the code currently in flight — keys its server-side attempt counter and single-use marker. Set by `mintPin`. */
2370
+ pinNonce?: string;
2371
+ /** Keyed digest of the code in flight, bound to who it was sent for — never the code itself. */
2372
+ pinDigest?: string;
2231
2373
  pinExpire?: number;
2232
- /** Wrong-code attempt counter for the currently minted pincode. Reset by `mintPin`; incremented by `verifyPin`; cleared when the cap is hit (which also clears `pin`/`pinExpire` so the user must request a fresh code). */
2233
- pinAttempts?: number;
2234
2374
  aborted?: boolean;
2235
2375
  isFirstLogin?: boolean;
2236
2376
  newPasswordRequired?: boolean;
@@ -2292,6 +2432,10 @@ interface AuthWfCtx {
2292
2432
  accept?: AuthWfAcceptState;
2293
2433
  postReset?: AuthWfPostResetState;
2294
2434
  recoveryAltActions?: AuthWfRecoveryAltActions;
2435
+ /** How the recovery code goes out: `'choice'` until the user picks on `RecoveryModeSelectForm`. [recovery] */
2436
+ recoveryDelivery?: AuthWfRecoveryDeliveryMode;
2437
+ /** Server-only state of a recovery or sign-in magic link — never projected to the wire. [recovery, login] */
2438
+ magicLink?: AuthWfMagicLinkState;
2295
2439
  mfa?: AuthWfMfaState;
2296
2440
  channel?: AuthWfChannelState;
2297
2441
  notice?: AuthWfNoticeState;
@@ -2434,9 +2578,11 @@ interface AuthWorkflowOpts {
2434
2578
  */
2435
2579
  lockoutDisclosure?: "uniform" | "generic" | "reveal";
2436
2580
  /**
2437
- * Counter store for the `'uniform'` shadow lockout of unknown handles.
2438
- * Default: one process-wide in-memory store — pass a shared store (e.g.
2439
- * `RateLimitStoreRedis`) when several instances serve sign-ins.
2581
+ * Counter store for the `'uniform'` shadow lockout of unknown handles and
2582
+ * for the magic-link send cooldown (one link per account and purpose per
2583
+ * `mfa.pincodeResendTimeoutMs`). Default: one process-wide in-memory store —
2584
+ * pass a shared store (e.g. `RateLimitStoreRedis`) when several instances
2585
+ * serve sign-ins.
2440
2586
  */
2441
2587
  lockoutShadowStore?: RateLimitStore$1;
2442
2588
  /** Pincode infrastructure shared by login MFA, invite MFA, and recovery OTP. */
@@ -2446,9 +2592,37 @@ interface AuthWorkflowOpts {
2446
2592
  pincodeResendTimeoutMs?: number;
2447
2593
  /** Max wrong-code submissions per minted pincode before the code is invalidated and the user must request a fresh one. Defaults to 5. */
2448
2594
  pincodeMaxAttempts?: number;
2595
+ /**
2596
+ * Wrong codes allowed per destination (an account's address, or a typed
2597
+ * recovery / signup identifier) and client IP, across all its codes within
2598
+ * `pincodeFailureWindowMs`; past it every send and check for that
2599
+ * destination from that IP answers `429 AOOTH_CODE_LIMIT_REACHED`.
2600
+ * Defaults to 10.
2601
+ */
2602
+ pincodeMaxFailures?: number;
2603
+ /** Window of `pincodeMaxFailures`, from the first wrong code. Defaults to 1 hour. */
2604
+ pincodeFailureWindowMs?: number;
2605
+ /**
2606
+ * Backstop over `pincodeMaxFailures`: wrong codes per destination from all
2607
+ * client IPs together within `pincodeFailureWindowMs`. Defaults to 100.
2608
+ */
2609
+ pincodeMaxFailuresGlobal?: number;
2610
+ /**
2611
+ * Codes sent per destination from all client IPs together within
2612
+ * `pincodeFailureWindowMs`; past it a request mints a code and sends
2613
+ * nothing (the resend wait itself is per client IP). Defaults to 10 — a
2614
+ * person needs a few codes an hour; this caps mail-bombing and SMS
2615
+ * pumping spread over many IPs at 10 messages per destination per hour.
2616
+ */
2617
+ pincodeMaxSendsGlobal?: number;
2449
2618
  };
2450
2619
  /** Persisted-state TTL for the recovery flow — caps the window between OTP request and password reset. Applied at every recovery-side `requireInput` pause via the wf engine's `output.expires`. */
2451
2620
  recoveryStateTtlMs?: number;
2621
+ /**
2622
+ * Lifetime of a magic link (recovery and sign-in links), from the moment it
2623
+ * is sent. Default 15 minutes. The link is single-use either way.
2624
+ */
2625
+ magicLinkTtlMs?: number;
2452
2626
  /** Canonical login URL — used by invite (post-accept redirect) and recovery (abort-to-login + post-reset redirect) as the resolver-default loginUrl. */
2453
2627
  loginUrl?: string;
2454
2628
  /** TOTP provisioning issuer — used by login MFA and invite MFA enrollment. */
@@ -2511,6 +2685,12 @@ interface AuthWorkflowOpts {
2511
2685
  termsBump?: TAtscriptAnnotatedType;
2512
2686
  concurrencyLimit?: TAtscriptAnnotatedType;
2513
2687
  recoveryPincode?: TAtscriptAnnotatedType;
2688
+ /** Recovery delivery picker (magic link vs one-time code) — `resolveRecoveryDeliveryMode` → `'choice'`. */
2689
+ recoveryModeSelect?: TAtscriptAnnotatedType;
2690
+ /** Identifier form of the login flow's `magicLink` alt-action. */
2691
+ magicLinkRequest?: TAtscriptAnnotatedType;
2692
+ /** Landing step of a clicked magic link ("Continue as …") — the link is used up on submit. */
2693
+ magicLinkConfirm?: TAtscriptAnnotatedType;
2514
2694
  /** Self-signup identifier form (`auth/signup/flow` entry pause). */
2515
2695
  signup?: TAtscriptAnnotatedType;
2516
2696
  /** Consent prompt shown before `mint-authz-code` mints an auth code (AUTH-SERVER.md §6). */
@@ -2541,8 +2721,13 @@ interface ResolvedAuthWorkflowOpts {
2541
2721
  pincodeTtlMs: number;
2542
2722
  pincodeResendTimeoutMs: number;
2543
2723
  pincodeMaxAttempts: number;
2724
+ pincodeMaxFailures: number;
2725
+ pincodeFailureWindowMs: number;
2726
+ pincodeMaxFailuresGlobal: number;
2727
+ pincodeMaxSendsGlobal: number;
2544
2728
  };
2545
2729
  recoveryStateTtlMs: number;
2730
+ magicLinkTtlMs: number;
2546
2731
  loginUrl: string;
2547
2732
  totpIssuer: string;
2548
2733
  deviceTrust: {
@@ -2580,17 +2765,35 @@ interface ResolvedAuthWorkflowOpts {
2580
2765
  termsBump: TAtscriptAnnotatedType;
2581
2766
  concurrencyLimit: TAtscriptAnnotatedType;
2582
2767
  recoveryPincode: TAtscriptAnnotatedType;
2768
+ recoveryModeSelect: TAtscriptAnnotatedType;
2769
+ magicLinkRequest: TAtscriptAnnotatedType;
2770
+ magicLinkConfirm: TAtscriptAnnotatedType;
2583
2771
  signup: TAtscriptAnnotatedType;
2584
2772
  authzConsent: TAtscriptAnnotatedType;
2585
2773
  };
2586
2774
  }
2775
+ /**
2776
+ * The set-password screen's copy ({@link AuthWorkflow.resolveSetPasswordCopy}):
2777
+ * your own `heading` / `intro` text (shown as is), or message codes rendered
2778
+ * through `msg()` in each request's language. Text wins over a code.
2779
+ */
2780
+ type SetPasswordCopy = Pick<AuthWfPasswordUiState, SetPasswordCopyKey>;
2781
+ type SetPasswordCopyKey = "heading" | "intro" | "headingCode" | "introCode";
2587
2782
  /**
2588
2783
  * Unified outbound-dispatch payload. Customers override `deliver(payload)` on
2589
2784
  * the `AuthWorkflow` subclass to route by `kind` (per-purpose templates) and
2590
2785
  * `channel` (email vs SMS). Replaces the prior workflow-specific deliver
2591
2786
  * payloads which carried slightly different field sets per call site.
2592
2787
  */
2593
- type AuthDeliveryPayload = {
2788
+ type AuthDeliveryPayload = AuthDeliveryPayloadOf & {
2789
+ /**
2790
+ * The locale of the request the delivery is sent from (moost
2791
+ * `useLocale()`), for a localized message. Absent when the request has none.
2792
+ */
2793
+ locale?: string;
2794
+ };
2795
+ /** The {@link AuthDeliveryPayload} variants, by `kind`. */
2796
+ type AuthDeliveryPayloadOf = {
2594
2797
  kind: "mfa-pincode";
2595
2798
  channel: "sms" | "email";
2596
2799
  recipient: string;
@@ -2643,6 +2846,12 @@ type AuthDeliveryPayload = {
2643
2846
  loginAt: number;
2644
2847
  context?: Record<string, unknown>;
2645
2848
  };
2849
+ /** Where a one-time code in flight lives (top-level ctx, or a pending federated link). */
2850
+ type PinState = {
2851
+ pinNonce?: string;
2852
+ pinDigest?: string;
2853
+ pinExpire?: number;
2854
+ };
2646
2855
  /**
2647
2856
  * Top-level `UserCredentials` keys that workflow-collected profile payloads
2648
2857
  * MUST NEVER carry through to persistence. The server sets these out-of-band
@@ -2702,14 +2911,17 @@ export declare class AuthWorkflow {
2702
2911
  private warnCrossIssuerReuse;
2703
2912
  constructor(opts: Partial<AuthWorkflowOpts>, users: UserService, auth: AuthCredential, consentStore: ConsentStore);
2704
2913
  /**
2705
- * Resolve a user-facing text by code (`AOOTH_MESSAGES`) through
2706
- * `opts.messages`. Every form error, banner, finish message and button label
2707
- * the workflow produces goes through here — override for full control
2708
- * (e.g. to call your i18n library with the request's locale).
2914
+ * Resolve a user-facing text by code (`AOOTH_MESSAGES`): `opts.messages`
2915
+ * first, then moost's translator in the request's locale, then the English
2916
+ * template. Every form error, banner, finish message and button label the
2917
+ * workflow produces goes through here — override for full control.
2709
2918
  */
2710
2919
  protected msg(code: AoothMessageCode, params?: AoothMessageParams): string;
2711
- /** An `HttpError` whose body carries the message `code` next to its (resolved) text. */
2712
- protected httpError(status: 409 | 410, code: AoothMessageCode): HttpError$1;
2920
+ /**
2921
+ * An `HttpError` whose body carries the message `code` and `params` next to
2922
+ * its (resolved) text, so an error-body translator can translate it by code.
2923
+ */
2924
+ protected httpError(status: 400 | 409 | 410, code: AoothMessageCode, params?: AoothMessageParams): HttpError$1;
2713
2925
  /**
2714
2926
  * Unified outbound dispatch hook for direct synchronous deliveries
2715
2927
  * (MFA / recovery / enrollment pincodes, new-device notices). NOT used for
@@ -2720,6 +2932,8 @@ export declare class AuthWorkflow {
2720
2932
  * sync-friendly: the default `void` preserves the engine's sync fast path.
2721
2933
  */
2722
2934
  protected deliver(_payload: AuthDeliveryPayload): void | Promise<void>;
2935
+ /** {@link deliver} with the request's locale stamped on the payload. */
2936
+ private dispatch;
2723
2937
  /**
2724
2938
  * The blessed one-call alert path for risk overrides — emit a
2725
2939
  * `security-alert` delivery (e.g. from an impossible-travel
@@ -2934,6 +3148,13 @@ export declare class AuthWorkflow {
2934
3148
  * `Set-Cookie` is stored before `AsWfForm` follows the redirect.
2935
3149
  */
2936
3150
  protected beginSso(providerId: string, authzHandle?: string): Promise<void>;
3151
+ /**
3152
+ * How recovery proves the inbox: `'otp'` (default — a one-time code),
3153
+ * `'magicLink'` (a single-use link, sent through the email outlet as
3154
+ * `recovery.magicLink`) or `'choice'` (the user picks on
3155
+ * `RecoveryModeSelectForm` after the identifier). Reached from recovery.flow.
3156
+ */
3157
+ protected resolveRecoveryDeliveryMode(_ctx: AuthWfCtx): AuthWfRecoveryDeliveryMode | Promise<AuthWfRecoveryDeliveryMode>;
2937
3158
  /**
2938
3159
  * Resolve the alternate-credentials policy (forgot-password / signup /
2939
3160
  * magic-link / SSO providers). Reached from login.flow.
@@ -3129,9 +3350,12 @@ export declare class AuthWorkflow {
3129
3350
  /**
3130
3351
  * Resolve the channel-OTP disclosure copy rendered beneath the email/phone
3131
3352
  * input on `AskEmailForm` / `AskPhoneForm`. Reached from login.flow Phase 3.
3132
- * Default returns a TCPA / PECR / CASL / GDPR-safe English paragraph that is
3353
+ * Default returns a TCPA / PECR / CASL / GDPR-safe paragraph that is
3133
3354
  * GENERIC per channel (no target templated in — the user hasn't submitted
3134
- * yet at ask-time).
3355
+ * yet at ask-time): `OTP_DISCLOSURE_EMAIL` / `OTP_DISCLOSURE_PHONE` in the
3356
+ * request's language. The text is kept in the workflow state as shown and
3357
+ * recorded with the consent (`recordOtpChannelConsent`) — the one text the
3358
+ * state keeps translated, because the record must be what the user saw.
3135
3359
  */
3136
3360
  protected resolveOtpDisclosure(_ctx: AuthWfCtx, channel: "email" | "phone"): string | Promise<string>;
3137
3361
  /**
@@ -3160,24 +3384,27 @@ export declare class AuthWorkflow {
3160
3384
  * Resolve the invite accept-tail policy. Reached from invite.start accept
3161
3385
  * phase. `loginUrl` defaults to `this.opts.loginUrl`. Note: today's
3162
3386
  * `freshLoginRequired` field is GONE — the auto-login choice is the static
3163
- * `AuthWorkflowOpts.autoLoginOnInvite` boolean (per §2 decision).
3387
+ * `AuthWorkflowOpts.autoLoginOnInvite` boolean (per §2 decision). Return
3388
+ * `confirmationMessage` to replace the default confirmation text
3389
+ * (`AOOTH_ACCOUNT_CREATED`, rendered in the finishing request's language) with your
3390
+ * own, shown as is.
3164
3391
  */
3165
3392
  protected resolveAccept(_ctx: AuthWfCtx): NonNullable<AuthWfCtx["accept"]> | Promise<NonNullable<AuthWfCtx["accept"]>>;
3166
3393
  /**
3167
3394
  * Copy (heading + intro) for the unified set-password screen, staged by
3168
- * `create-password-form` BEFORE the pause. Branches on the resolved
3169
- * `ctx.password.changeReason` (`expired` / `reset`), then invite-accept
3170
- * (`ctx.accept`), then the initial-password fallback. Override to re-brand any
3171
- * phase; return a partial (`{ heading }` only) to change one field and leave
3172
- * the other at whatever an earlier step staged, or `{}` to keep both as-is.
3395
+ * `create-password-form` BEFORE the pause. The default picks message codes
3396
+ * — `SET_PASSWORD_{EXPIRED,RESET,INVITE,INITIAL}_{HEADING,INTRO}` by the
3397
+ * resolved `ctx.password.changeReason` (`expired` / `reset`), then
3398
+ * invite-accept (`ctx.accept`), then the initial-password fallback — which
3399
+ * are rendered through `msg()` in each request's language.
3400
+ *
3401
+ * Override to re-brand any phase: `heading` / `intro` are your own text,
3402
+ * shown as is (they win over the codes); `headingCode` / `introCode` pick
3403
+ * other codes. Return a partial to change one field and leave the other at
3404
+ * whatever an earlier step staged (spread `super`'s result to keep the
3405
+ * default for it), or `{}` to keep both as-is.
3173
3406
  */
3174
- protected resolveSetPasswordCopy(ctx: AuthWfCtx): {
3175
- heading?: string;
3176
- intro?: string;
3177
- } | Promise<{
3178
- heading?: string;
3179
- intro?: string;
3180
- }>;
3407
+ protected resolveSetPasswordCopy(ctx: AuthWfCtx): SetPasswordCopy | Promise<SetPasswordCopy>;
3181
3408
  /**
3182
3409
  * Resolve the recovery post-reset policy. Reached from recovery.flow.
3183
3410
  * `freshLoginRequired` REMOVED — the auto-login choice is the static
@@ -3203,6 +3430,11 @@ export declare class AuthWorkflow {
3203
3430
  * set) or from `ctx.email` (recovery path). Loads the user to read the raw
3204
3431
  * method `value` — the `ctx.mfa.enrolledMethods` summary carries only the
3205
3432
  * MASKED form, which is for display, never for delivery.
3433
+ *
3434
+ * In recovery it also runs for an identifier with no account a code can go
3435
+ * to (unknown, inactive), on a copy of `ctx` whose `subject` is the
3436
+ * placeholder `00000000-0000-4000-8000-000000000000` — so every identifier
3437
+ * makes the same calls. Its result (or any error) is discarded there.
3206
3438
  */
3207
3439
  protected resolvePincodeTarget(ctx: AuthWfCtx): {
3208
3440
  address: string;
@@ -3222,13 +3454,13 @@ export declare class AuthWorkflow {
3222
3454
  * row (`selectRecoveryRegisteredMethod`) and the channel is that method's own
3223
3455
  * kind. The user only typed an account identifier; the destination is a
3224
3456
  * pre-verified channel they already control, so this also can't redirect
3225
- * cross-account. `request`'s M2 guard normally generic-finishes any row with
3226
- * no deliverable method up front; if the method is deleted in the narrow
3227
- * window between that guard and this send (e.g. on a resend), this throws
3228
- * `RecoveryMethodUnavailableError`, which `pincode-send` degrades to the
3229
- * same generic finish — never a distinguishable 500.
3457
+ * cross-account. With no deliverable method this throws
3458
+ * `RecoveryMethodUnavailableError`, which recovery treats as "no account"
3459
+ * (nothing sent, every code refused) — never a distinguishable 500.
3230
3460
  */
3231
3461
  private recoveryPincodeTarget;
3462
+ /** `resolveRecoveryDeliverySource`, awaited. */
3463
+ private recoveryDeliverySource;
3232
3464
  /**
3233
3465
  * Recovery OTP delivery channel. The address is ALWAYS the typed recovery
3234
3466
  * identifier (`ctx.email`) — symmetric with how email recovery already works:
@@ -3251,7 +3483,7 @@ export declare class AuthWorkflow {
3251
3483
  * row** — `selectRecoveryRegisteredMethod` picks the confirmed MFA method;
3252
3484
  * the destination is never taken from user input, so it cannot be redirected
3253
3485
  * to an attacker-controlled address. A row with no deliverable confirmed
3254
- * method finishes with the generic anti-enumeration envelope (see `request`).
3486
+ * method runs the ghost OTP pause, like an unknown identifier (see `request`).
3255
3487
  *
3256
3488
  * Consulted inline by `request` (no-method guard) and `recoveryPincodeTarget`
3257
3489
  * — no `prepare-*` step, mirroring `resolveRecoveryChannel`. Override to arm
@@ -3263,7 +3495,7 @@ export declare class AuthWorkflow {
3263
3495
  * its OTP to. Prefers a confirmed SMS method, then a confirmed email method —
3264
3496
  * phone-recovery-first. TOTP carries no deliverable address and is skipped.
3265
3497
  * Returns `null` when the row has no deliverable confirmed method; the caller
3266
- * turns that into the anti-enumeration generic finish. Stays sync (operates on
3498
+ * turns that into the ghost OTP run (anti-enumeration). Stays sync (operates on
3267
3499
  * an already-loaded row); override to change the selection policy (e.g. honour
3268
3500
  * the user's `mfa.defaultMethod`).
3269
3501
  */
@@ -3322,6 +3554,7 @@ export declare class AuthWorkflow {
3322
3554
  *
3323
3555
  * Called via `throwPublic` immediately before every `requireInput`-style
3324
3556
  * pause so the FE always reads a fresh projection of the post-step ctx.
3557
+ * `WfTriggerProvider` strips the projection before persisting the state.
3325
3558
  */
3326
3559
  protected populatePublic(ctx: AuthWfCtx): void;
3327
3560
  /**
@@ -3345,29 +3578,100 @@ export declare class AuthWorkflow {
3345
3578
  protected useAtscriptWfPublic(ctx: AuthWfCtx, type: Parameters<typeof useAtscriptWf>[0]): ReturnType<typeof useAtscriptWf>;
3346
3579
  /** Translate `CAS_EXHAUSTED` UserAuthError to 409 Conflict (OCC contract). */
3347
3580
  protected withStoreErrorTranslation<T>(op: () => Promise<T>): Promise<T>;
3348
- /** Mint a numeric pincode + stash it onto ctx. Returns the plain code. */
3349
- protected mintPin(ctx: {
3350
- pin?: string;
3351
- pinExpire?: number;
3352
- pinAttempts?: number;
3353
- }, length: number, ttlMs: number): string;
3354
- /**
3355
- * Verify a submitted pincode against `ctx.pin`. Returns an error map (with
3356
- * the message keyed under `code` so it renders inline on the code input) or
3357
- * `null` on success. Brute-force protection: wrong-code attempts increment
3358
- * `ctx.pinAttempts`; on the `pincodeMaxAttempts`-th miss the code is
3359
- * invalidated (clears `pin` + `pinExpire` + `pinAttempts`) and the returned
3360
- * error tells the user to request a fresh code. Without this gate the user
3361
- * could probe the full 10^pincodeLength space inside one `pincodeTtlMs`
3362
- * window.
3363
- */
3364
- protected verifyPin(ctx: {
3365
- pin?: string;
3366
- pinExpire?: number;
3367
- pinAttempts?: number;
3368
- }, submitted: string | undefined): {
3581
+ /**
3582
+ * Mint a numeric one-time code for `binding` (who it is sent for) and return
3583
+ * the plain code for delivery. The state keeps only a random nonce and a
3584
+ * keyed digest of `nonce|binding|code` — fixed lengths, never the code — so
3585
+ * a read of the state does not reveal it, and {@link verifyPin} accepts it
3586
+ * only for the same binding. `length` and `ttlMs` default to
3587
+ * `mfa.pincodeLength` / `mfa.pincodeTtlMs`.
3588
+ */
3589
+ protected mintPin(ctx: PinState, binding: string, length?: number, ttlMs?: number): string;
3590
+ /** Drop the code in flight (its nonce stays spent or counted server-side). */
3591
+ protected clearPin(ctx: PinState): void;
3592
+ /** Binding of a code sent to `address` in this run (and for its subject, once known). */
3593
+ private pinFor;
3594
+ /**
3595
+ * Binding of a recovery code: the account and the address it went to (a
3596
+ * changed registered channel refuses the old channel's code). Without an
3597
+ * account, the placeholder — the digest has the same length either way.
3598
+ */
3599
+ private recoveryBinding;
3600
+ /**
3601
+ * Server-side key of where a code goes — its resend cooldown and failed-code
3602
+ * budget. Never an account id the caller could not know: recovery and signup
3603
+ * key on the typed identifier, so known and unknown ones behave alike.
3604
+ */
3605
+ private codeTarget;
3606
+ /** {@link codeTarget} of a code sent to `address` to enrol or verify a channel. */
3607
+ private enrollTarget;
3608
+ /** {@link codeTarget} of a federated link's proof-of-control code. */
3609
+ private linkTarget;
3610
+ /** {@link codeTarget} of the `pincode-send` / `pincode-check` pair. */
3611
+ private pincodeTarget;
3612
+ /**
3613
+ * Server-side gate of a code send to `target`, before minting: answers
3614
+ * `429 AOOTH_CODE_LIMIT_REACHED` once the target's failed-code budget is
3615
+ * spent (this client IP's, or all IPs' together), applies the per-account
3616
+ * `aooth.send-user` limit when `account` is given (sends after a first
3617
+ * factor), and claims this client IP's resend wait for the target
3618
+ * (`mfa.pincodeResendTimeoutMs`) and a slot of the target's send cap from
3619
+ * all IPs (`mfa.pincodeMaxSendsGlobal` per `pincodeFailureWindowMs`).
3620
+ * Returns whether the code may go out: `false` inside the wait or past the
3621
+ * cap — the caller mints a code all the same and sends nothing, for known
3622
+ * and unknown destinations alike.
3623
+ */
3624
+ protected claimCodeSend(target: string, account?: string): Promise<boolean>;
3625
+ /** Whether a send to `target` is cooling down (`false` when the store cannot peek). */
3626
+ private codeSendCoolingDown;
3627
+ /**
3628
+ * Counters of a destination, per client IP and across all IPs:
3629
+ * - sends (`CODE_SEND_PREFIX`): this client's resend wait, and the sends
3630
+ * from all IPs together in the window (the cap on mail-bombing and SMS
3631
+ * pumping spread over many IPs);
3632
+ * - failed codes (`CODE_FAIL_PREFIX`): the budget one caller can spend (so
3633
+ * an attacker cannot lock the owner out from elsewhere), and the backstop
3634
+ * against distributed guessing.
3635
+ *
3636
+ * The client IP is hashed: fixed-size keys, no raw IPs in the store.
3637
+ */
3638
+ private counterKeys;
3639
+ /** Answer `429 AOOTH_CODE_LIMIT_REACHED` once a destination's failed-code budget is spent. */
3640
+ private assertCodeBudget;
3641
+ /**
3642
+ * Verify a submitted code against the one minted for `binding`. Returns an
3643
+ * error map (keyed under `code` so it renders on the code input) or `null`
3644
+ * on success.
3645
+ *
3646
+ * Attempts are counted server-side in `lockoutShadowStore`, per minted code
3647
+ * (its nonce), before the comparison: a replayed older state token shares
3648
+ * the counter, so `pincodeMaxAttempts` holds across replays and parallel
3649
+ * submits. A code is single-use: once it verifies, its nonce is spent and
3650
+ * the same code through any copy of the state is refused. A binding that
3651
+ * differs from the one at mint (the account resolved differently since the
3652
+ * send) reads as a wrong code. Wrong codes also count against `target`'s
3653
+ * failed-code budgets across resends (`mfa.pincodeMaxFailures` per client
3654
+ * IP, `pincodeMaxFailuresGlobal` for all IPs, per
3655
+ * `pincodeFailureWindowMs`); once one is spent every check answers
3656
+ * `429 AOOTH_CODE_LIMIT_REACHED`.
3657
+ */
3658
+ protected verifyPin(ctx: PinState, submitted: string | undefined, binding: string, target: string): Promise<{
3369
3659
  code: string;
3370
- } | null;
3660
+ } | null>;
3661
+ /** Keyed digest of a code, bound to its nonce and to who it was sent for. */
3662
+ private pinDigest;
3663
+ /**
3664
+ * Key of the code digests: the one `WfTriggerProvider` publishes for the
3665
+ * request (derived from its `pincodeSecret()`), else the key a default
3666
+ * provider publishes (`defaultPincodeKey`: derived from the default wf-state
3667
+ * secret), so a code minted on one path verifies on the other. Throws
3668
+ * `INVALID_CONFIG` outside a provider when the credential store has no
3669
+ * derivable secret. Override when the workflow runs outside a
3670
+ * `WfTriggerProvider` whose `wfStateSecret()` / `pincodeSecret()` is
3671
+ * overridden — return that provider's key; every instance must agree.
3672
+ */
3673
+ protected pincodeKey(): Buffer;
3674
+ private fallbackPincodeKey?;
3371
3675
  /**
3372
3676
  * Validate + stash inline-consent fields submitted on a carrier form.
3373
3677
  * SECURITY: silently drops unknown ids (audit-grade defense — see base
@@ -3409,6 +3713,8 @@ export declare class AuthWorkflow {
3409
3713
  * and resend.
3410
3714
  */
3411
3715
  private mintAndSendEnrollPincode;
3716
+ /** Seconds a resend still has to wait — the state's hint, else a full cooldown. */
3717
+ private resendWaitSeconds;
3412
3718
  /**
3413
3719
  * Idempotent TOTP secret provisioning into wf-state ONLY (the QR renders
3414
3720
  * from `public.mfaEnroll.secret/uri`; the user record is written on confirm
@@ -3564,6 +3870,17 @@ export declare class AuthWorkflow {
3564
3870
  */
3565
3871
  initAddMfa(ctx: AuthWfCtx): Promise<undefined>;
3566
3872
  credentials(ctx: AuthWfCtx): Promise<unknown>;
3873
+ /**
3874
+ * Bind the login run to the account that passed its first factor — shared
3875
+ * by the password and magic-link sign-ins, so both leave the run alike:
3876
+ * - `ctx.subject` and the password stamp;
3877
+ * - the inline password guards (`ctx.guards`): top-level
3878
+ * `isPasswordInitial` / `isPasswordExpired` (read by
3879
+ * `prepare-semantic-flags` later as a fallback) and the change reason;
3880
+ * - the account's confirmed channels, so `ensureEmail` / `ensurePhone` skip
3881
+ * what is already confirmed and security notices have a recipient.
3882
+ */
3883
+ private bindSignedInUser;
3567
3884
  /**
3568
3885
  * Whether a failed password sign-in answers "Account locked" — see
3569
3886
  * `AuthWorkflowOpts.lockoutDisclosure`. Under `'uniform'` an unknown or
@@ -3583,6 +3900,31 @@ export declare class AuthWorkflow {
3583
3900
  */
3584
3901
  private handleCredentialsAlt;
3585
3902
  request(ctx: AuthWfCtx): Promise<unknown>;
3903
+ /**
3904
+ * Start recovery's delivery `mode` — the same way for known and unknown
3905
+ * identifiers:
3906
+ * - `'magicLink'`: the link for the typed identifier, resolved now but held
3907
+ * only in the link's server-side pause (the requester never gets a token
3908
+ * for it, and an earlier picker's state holds nothing about the account);
3909
+ * - `'otp'`: the durable store strategy. Nothing about the account goes into
3910
+ * the state before the code is verified: `pincode-send` /
3911
+ * `pincode-check` resolve it from the typed identifier each time.
3912
+ */
3913
+ private applyRecoveryMode;
3914
+ /** A recovery magic link for the typed identifier (`subject` unset when it matches no account). */
3915
+ private recoveryMagicLink;
3916
+ /** `emailToUserId`, with an unknown identifier as `undefined`. */
3917
+ private lookupRecoverySubject;
3918
+ /**
3919
+ * The account a recovery code for the typed identifier goes to, and where —
3920
+ * or `null` when no code can go anywhere: an unknown identifier, an inactive
3921
+ * (pending / deactivated) account, or under M2 an account without a
3922
+ * deliverable confirmed channel. A locked account may recover (self-service
3923
+ * unlock). Resolved from `ctx.email` on every send and at verification —
3924
+ * never kept in the state — and with the same reads for every identifier
3925
+ * (an unknown one reads a placeholder row).
3926
+ */
3927
+ private recoveryAccount;
3586
3928
  /**
3587
3929
  * Resolves the recovery-step `email` input to the user's stable `id` (the
3588
3930
  * token subject). Default: resolves via `findByHandle` (username exact, then
@@ -3590,8 +3932,6 @@ export declare class AuthWorkflow {
3590
3932
  * user matches.
3591
3933
  */
3592
3934
  protected emailToUserId(email: string): Promise<string | null>;
3593
- /** Anti-enumeration generic finish envelope used when recovery's `request` step receives an unknown email. */
3594
- private finishGenericRecovery;
3595
3935
  /**
3596
3936
  * Stamp `recoveryStateTtlMs` on a paused-state error so the wf engine's
3597
3937
  * persisted-state strategy expires the state at that timestamp. Use at
@@ -3930,6 +4270,13 @@ export declare class AuthWorkflow {
3930
4270
  */
3931
4271
  confirmRemoveMfa(ctx: AuthWfCtx): Promise<undefined>;
3932
4272
  askChannel(ctx: AuthWfCtx, channel: "email" | "phone"): Promise<unknown>;
4273
+ /**
4274
+ * Mint the code proving a channel (`ask/*`, `verify/*`), deliver it when
4275
+ * `deliver`, and arm the PincodeForm: the resend wait `verifyChannel`
4276
+ * gates "Resend code" on (the same cooldown contract as `pincode-send`),
4277
+ * the masked `sentTo` its "Code sent to …" hint renders, and the code length.
4278
+ */
4279
+ private sendChannelPincode;
3933
4280
  verifyChannel(ctx: AuthWfCtx, channel: "email" | "phone"): Promise<unknown>;
3934
4281
  /**
3935
4282
  * Read the device-trust cookie; if it matches a valid record, set
@@ -4219,6 +4566,19 @@ export declare class AuthWorkflow {
4219
4566
  * authorization code. Skipped when this run changed the password itself.
4220
4567
  */
4221
4568
  checkPasswordUnchanged(ctx: AuthWfCtx): Promise<undefined>;
4569
+ /**
4570
+ * Login-only guard before the `record-login` funnel: an account deactivated
4571
+ * or locked while the run was paused (MFA, enrolment, consents …) is not
4572
+ * stamped, announced or signed in — the run finishes with an error.
4573
+ */
4574
+ checkCanSignIn(ctx: AuthWfCtx): Promise<undefined>;
4575
+ /**
4576
+ * Whether the run's account can no longer sign in (deactivated, locked or
4577
+ * deleted since it authenticated). If so the run is finished with an error
4578
+ * (`AOOTH_ACCOUNT_LOCKED` for a lock unless `lockoutDisclosure` is
4579
+ * `'generic'`, else `INVALID_CREDENTIALS`) and `ctx.aborted` is set.
4580
+ */
4581
+ private loginAccountBlocked;
4222
4582
  /**
4223
4583
  * The SINGLE login-completion funnel. Every flow that establishes an
4224
4584
  * authenticated session routes through here — placed in each login schema
@@ -4253,6 +4613,14 @@ export declare class AuthWorkflow {
4253
4613
  * still locked: self-service ran `unlock-account`; temporary auto-expires).
4254
4614
  */
4255
4615
  recoveryLockCheck(ctx: AuthWfCtx): Promise<undefined>;
4616
+ /**
4617
+ * Auto-login guard, ahead of `record-login` on every auto-login path (invite,
4618
+ * recovery, signup): never stamp a login, fire `afterLogin` or issue a
4619
+ * session for an account that is no longer active (deactivated meanwhile —
4620
+ * every flow reaching here activated or verified it first). Recovery and
4621
+ * invite fall back to the fresh-login finish (no session); signup fails.
4622
+ */
4623
+ autoLoginCheck(ctx: AuthWfCtx): Promise<undefined>;
4256
4624
  /**
4257
4625
  * Thin dispatcher steps for the flow-specific lifecycle hooks. Each is its own
4258
4626
  * schema step (rather than an in-terminal call) because its flow's finalize
@@ -4366,10 +4734,10 @@ export declare class AuthWorkflow {
4366
4734
  * tokens (WF-INVITE-020).
4367
4735
  *
4368
4736
  * It records NOTHING and guards NOTHING: `account.lastLogin` + the
4369
- * `afterLogin` hook are owned by the upstream `record-login` funnel step, and
4370
- * the admin-only-survived-lock guard by the upstream `recovery-lock-check`
4371
- * step — both of which `{ break }`/gate this step out when they apply, so a
4372
- * still-frozen account never reaches here.
4737
+ * `afterLogin` hook are owned by the upstream `record-login` funnel step,
4738
+ * the inactive-account guard by `auto-login-check`, and the
4739
+ * admin-only-survived-lock guard by `recovery-lock-check` — all upstream, so
4740
+ * an inactive or still-frozen account never reaches here.
4373
4741
  */
4374
4742
  finalizeAutoLogin(ctx: AuthWfCtx): Promise<undefined>;
4375
4743
  /**
@@ -4413,9 +4781,80 @@ export declare class AuthWorkflow {
4413
4781
  * the freshly-created `ctx.subject`. Mirrors login's `extra-step` seam.
4414
4782
  */
4415
4783
  signupExtraStep(_ctx: AuthWfCtx): unknown | Promise<unknown>;
4416
- magicLinkRequest(_ctx: AuthWfCtx): unknown | Promise<unknown>;
4417
- magicLinkSend(_ctx: AuthWfCtx): unknown | Promise<unknown>;
4418
- magicLinkVerified(_ctx: AuthWfCtx): unknown | Promise<unknown>;
4784
+ /**
4785
+ * Login's `magicLink` alt-action: the identifier form. Resolves the account
4786
+ * (unknown, inactive or locked identifiers resolve to none — the answer is
4787
+ * the same) and hands over to `magic-link-send`.
4788
+ */
4789
+ magicLinkRequest(ctx: AuthWfCtx): Promise<unknown>;
4790
+ /**
4791
+ * Send a magic link (recovery or sign-in) and pause until it is used. The
4792
+ * pause is persisted under the `magic-link` strategy — a fresh, hashed,
4793
+ * single-use handle that expires with the link (`magicLinkTtlMs`) — and the
4794
+ * `magic-link` outlet hands the token to the email outlet only. Known and
4795
+ * unknown identifiers take the same path and get the same answer; nothing is
4796
+ * sent for an unknown identifier, an account without a proven inbox, a
4797
+ * sign-in the account may not start (inactive, locked), or a repeat within
4798
+ * `mfa.pincodeResendTimeoutMs`. The click resumes here and moves on to the
4799
+ * purpose's verify step.
4800
+ */
4801
+ magicLinkSend(ctx: AuthWfCtx): Promise<unknown>;
4802
+ /**
4803
+ * Where a magic link may go — an inbox the account proved, or `undefined`
4804
+ * (nothing is sent). Recovery with the typed identifier as destination (M1,
4805
+ * email channel) sends to the typed address, like the recovery code; every
4806
+ * other case sends to the account's proven inbox: `account.verifiedEmail`,
4807
+ * else a confirmed email MFA method — never an unproven address. The account
4808
+ * must be active; a sign-in link also needs it unlocked (a recovery link may
4809
+ * go to a locked account — self-service unlock). Override to change the
4810
+ * destination.
4811
+ */
4812
+ protected magicLinkAddress(ctx: AuthWfCtx, ml: NonNullable<AuthWfCtx["magicLink"]>): Promise<string | undefined>;
4813
+ /**
4814
+ * The landing step of a clicked link: "Continue as a•••@example.com". Opening
4815
+ * the link (or a mail scanner fetching it) only renders this step — the
4816
+ * pause stays on the link's own handle, so the link still works; it is used
4817
+ * up only when this form is submitted. The masked account lets the user see
4818
+ * which account the link signs into (a forwarded link would be someone
4819
+ * else's).
4820
+ */
4821
+ magicLinkConfirm(ctx: AuthWfCtx): unknown;
4822
+ /** Name of the cookie binding a sign-in link to the browser that asked for it. */
4823
+ protected magicLinkBrowserCookie(): string;
4824
+ /** Set the browser-binding cookie; returns the hash the link keeps. */
4825
+ private bindMagicLinkBrowser;
4826
+ /** Whether this request carries the browser-binding cookie the link was sent with. */
4827
+ private sameMagicLinkBrowser;
4828
+ /**
4829
+ * A used sign-in link: the FIRST factor only. Re-checks the account
4830
+ * (active, not locked), binds `ctx.subject` and leaves the second factor to
4831
+ * the MFA loop, exactly as after a password. Refuses a link of another
4832
+ * purpose, an expired one, and one sent for no account.
4833
+ */
4834
+ magicLinkVerified(ctx: AuthWfCtx): Promise<unknown>;
4835
+ /**
4836
+ * A used recovery link: proof of the inbox it went to, exactly like a
4837
+ * verified recovery code — `ctx.otp.verified` set, the inbox recorded as
4838
+ * the account's verified email, and the flow goes on to the new password.
4839
+ * Refuses a link of another purpose, an expired one, one sent for no
4840
+ * account, and one whose account is no longer active.
4841
+ */
4842
+ recoveryLinkVerified(ctx: AuthWfCtx): Promise<unknown>;
4843
+ /**
4844
+ * The magic link this run was resumed through, checked for `purpose` and
4845
+ * expiry — or `undefined` after emitting the "invalid link" finish. Swaps
4846
+ * off the `magic-link` strategy first, so the link's token is never the
4847
+ * continuation (the next pause gets a fresh handle).
4848
+ */
4849
+ private usedMagicLink;
4850
+ /** The finish of a link that cannot be used (wrong purpose, expired, no account). */
4851
+ private finishMagicLinkInvalid;
4852
+ /**
4853
+ * Recovery's `'choice'` delivery: the user picks a magic link or a one-time
4854
+ * code. Shown for known and unknown identifiers alike. A one-time code for
4855
+ * an unknown identifier runs the ghost OTP pause, like the default path.
4856
+ */
4857
+ selectRecoveryMode(ctx: AuthWfCtx): Promise<unknown>;
4419
4858
  passkey(_ctx: AuthWfCtx): unknown | Promise<unknown>;
4420
4859
  /**
4421
4860
  * Verify the OAuth callback and resolve a user. Reaches here (instead of
@@ -4533,8 +4972,9 @@ export declare class AuthWorkflow {
4533
4972
  */
4534
4973
  inviteFlow(): void;
4535
4974
  /**
4536
- * recovery.flow — OTP-via-email reset. `@Public()` on the body because
4537
- * anonymous users start recovery.
4975
+ * recovery.flow — reset by a one-time code or a magic link
4976
+ * (`resolveRecoveryDeliveryMode`). `@Public()` on the body because anonymous
4977
+ * users start recovery.
4538
4978
  */
4539
4979
  recoveryFlow(): void;
4540
4980
  /**
@@ -4608,6 +5048,48 @@ export declare class AuthWorkflow {
4608
5048
  */
4609
5049
  signupFlow(): void;
4610
5050
  }
5051
+ /**
5052
+ * Code-keyed English templates of the `HttpError`s auth-moost raises outside
5053
+ * the auth workflow (guard, controllers, `useAuth()`, the workflow trigger).
5054
+ * Each error body carries the `code` and its `params`;
5055
+ * `MoostHttp` translates it by code with the moost translator
5056
+ * (`translateErrorBody`). Registered with `registerMessages` on import.
5057
+ *
5058
+ * The workflow's own texts are in `AOOTH_MESSAGES`; the rate limiter's 429
5059
+ * (`RATE_LIMITED`) template is `RATE_LIMIT_MESSAGES` from `@aooth/auth`.
5060
+ */
5061
+ export declare const AOOTH_HTTP_MESSAGES: {
5062
+ /** 401 — the guard found no credential on a protected route. */
5063
+ readonly AOOTH_AUTH_REQUIRED: "Unauthorized";
5064
+ /** 401 — the guard's credential is invalid, expired or revoked. */
5065
+ readonly AOOTH_CREDENTIAL_INVALID: "Invalid credential";
5066
+ /** 401 — `useAuth().getUserId()` and `AuthController` routes without a signed-in user. */
5067
+ readonly AOOTH_NOT_AUTHENTICATED: "Not authenticated";
5068
+ /** 401 — "log out other sessions" without a current session. */
5069
+ readonly NO_CURRENT_SESSION: "No current session to keep";
5070
+ /** 401 — `POST /auth/refresh` without a refresh token. */
5071
+ readonly MISSING_REFRESH_TOKEN: "Missing refresh token";
5072
+ /** 401 — `POST /auth/refresh` with an unknown, expired or reused refresh token. */
5073
+ readonly INVALID_REFRESH_TOKEN: "Invalid refresh token";
5074
+ /** 400 — `DELETE /auth/sessions` without `?others=true`. */
5075
+ readonly LOGOUT_OTHERS_REQUIRED: "Pass ?others=true to log out other sessions";
5076
+ /** 404 — `GET /auth/invite/post-redemption` for an unknown or still pending invite. */
5077
+ readonly INVITE_NOT_FOUND: "Invite not found";
5078
+ /** 400 — `GET /auth/invite/post-redemption` without `uid`. */
5079
+ readonly AOOTH_MISSING_UID: "Missing uid query parameter";
5080
+ /** 404 — unlinking an identity the user does not have. */
5081
+ readonly LINKED_IDENTITY_NOT_FOUND: "Linked identity not found";
5082
+ /** 409 — unlinking the user's only sign-in method. */
5083
+ readonly LAST_SIGN_IN_METHOD: "Cannot remove your only sign-in method. Set a password first, or link another provider.";
5084
+ /** 404 — unlinking an identity of an unconfigured provider. Params: `provider`. */
5085
+ readonly AOOTH_UNKNOWN_PROVIDER: "Unknown provider '{provider}'";
5086
+ /** 429 — the one-time codes of this account or address failed too often; answered to every code send and check until the window passes. */
5087
+ readonly AOOTH_CODE_LIMIT_REACHED: "Too many code attempts. Try again later.";
5088
+ /** 403 — the workflow trigger refused a workflow outside its allow list. Params: `workflow`. */
5089
+ readonly AOOTH_WORKFLOW_NOT_ALLOWED: "Workflow '{workflow}' is not allowed";
5090
+ };
5091
+ /** A code of {@link AOOTH_HTTP_MESSAGES}. */
5092
+ type AoothHttpMessageCode = keyof typeof AOOTH_HTTP_MESSAGES;
4611
5093
  interface AuthEmailOutletDeps {
4612
5094
  emailSender: EmailSender$1;
4613
5095
  buildMagicLinkUrl: BuildMagicLinkUrl$1;
@@ -4620,6 +5102,27 @@ interface AuthEmailOutletDeps {
4620
5102
  * `handleWfOutletRequest({ outlets })`.
4621
5103
  */
4622
5104
  export declare function createAuthEmailOutlet(deps: AuthEmailOutletDeps): WfOutlet;
5105
+ /** Name of the outlet `AuthWorkflow` pauses on to send a recovery or sign-in magic link. */
5106
+ export declare const MAGIC_LINK_OUTLET = "magic-link";
5107
+ /**
5108
+ * Name of the state strategy a magic link's pause is persisted under
5109
+ * (registered by `WfTriggerProvider`). Its own keyspace makes the trigger mint
5110
+ * a fresh handle for the link, and the next pause swaps off it again — so the
5111
+ * emailed token is consumed by its first use and never becomes the
5112
+ * continuation of the flow.
5113
+ */
5114
+ export declare const MAGIC_LINK_STRATEGY = "magic-link";
5115
+ /**
5116
+ * The `magic-link` outlet (registered by default on `WfTriggerProvider`). The
5117
+ * step decides whether a link goes out (`context.deliver`); when it does, the
5118
+ * link is handed to the app's `email` outlet (`createAuthEmailOutlet`) with
5119
+ * the step's template (`recovery.magicLink` / `login.magicLink`). Known and
5120
+ * unknown identifiers get the same answer, and a failed delivery is logged,
5121
+ * not reported — the response never says whether an account exists.
5122
+ *
5123
+ * @param emailOutlet - resolves the app's `email` outlet at delivery time.
5124
+ */
5125
+ export declare function createMagicLinkOutlet(emailOutlet: () => WfOutlet | undefined): WfOutlet;
4623
5126
  /**
4624
5127
  * Audit event emitter — used by `AuthWorkflow`'s audit-login step (and
4625
5128
  * future recovery / invite audit steps) to fan out login.success and similar
@@ -4645,4 +5148,4 @@ interface AuditEvent {
4645
5148
  interface AuditEmitter {
4646
5149
  emit(event: AuditEvent): Promise<void> | void;
4647
5150
  }
4648
- export { type AoothMessageCode, type AoothMessageParams, type AoothMessages, type AuditEmitter, type AuditEvent, type AuthBindings, type AuthContext, type AuthDeliveryPayload, type AuthEmailEvent, type AuthEmailKind, type AuthEmailOutletDeps, type AuthLoginResponse, type AuthLogoutBody, type AuthOkResponse, type AuthOptions, type AuthRefreshBody, type AuthSmsEvent, type AuthSmsKind, type AuthWfCompletionState, type AuthWfConsentsState, type AuthWfCtx, type AuthWfMfaEnrollState, type AuthWfOAuthState, type AuthWfPasswordUiState, type AuthWfPincodeUiState, type AuthWorkflowOpts, type AuthorizationServerMetadata, type AuthzReauthPolicy, type BuildAuthorizationServerMetadataOptions, type BuildMagicLinkUrl, type BuildProtectedResourceMetadataOptions, type ConcurrencyLimitOptions, type ConnectedAccount, type ConsentDescriptor, type ConsentDescriptorLike, type ConsentEvent, DynamicClientRegistration, type DynamicClientRegistrationOptions, type EmailSender, type EnrichedSession, type IssueResult, type LoginRedirect, type MfaSummary, type MfaTransport, type ProtectedResourceMetadata, type RateLimitBindings, type RateLimitDecision, type RateLimitDecoratorOptions, type RateLimitInterceptorOptions, type RateLimitKeyStrategy, type RateLimitRule, type RateLimitRuleInput, type RateLimitStore, RateLimitStoreMemory, RateLimiter, type RateLimiterOptions, type ResolvedAuthCookieConfig, type ResolvedAuthOptions, type ResolvedAuthWorkflowOpts, type SessionEnricher, type SessionInfo, type SmsSender, type SsoProvider, type TAuthMeta, type TRateLimitMeta, type UserAuthErrorBody, type WfTriggerHooks, type WfTriggerOpts, type WwwAuthenticateBearerChallengeOptions, buildAuthorizationServerMetadata, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, generateMagicLinkToken };
5151
+ export { type AoothHttpMessageCode, type AoothMessageCode, type AoothMessageParams, type AoothMessages, type AuditEmitter, type AuditEvent, type AuthBindings, type AuthContext, type AuthDeliveryPayload, type AuthEmailEvent, type AuthEmailKind, type AuthEmailOutletDeps, type AuthLoginResponse, type AuthLogoutBody, type AuthOkResponse, type AuthOptions, type AuthRefreshBody, type AuthSmsEvent, type AuthSmsKind, type AuthWfCompletionState, type AuthWfConsentsState, type AuthWfCtx, type AuthWfMagicLinkState, type AuthWfMfaEnrollState, type AuthWfOAuthState, type AuthWfPasswordUiState, type AuthWfPincodeUiState, type AuthWfRecoveryDeliveryMode, type AuthWorkflowOpts, type AuthorizationServerMetadata, type AuthzReauthPolicy, type BuildAuthorizationServerMetadataOptions, type BuildMagicLinkUrl, type BuildProtectedResourceMetadataOptions, type ConcurrencyLimitOptions, type ConnectedAccount, type ConsentDescriptor, type ConsentDescriptorLike, type ConsentEvent, DynamicClientRegistration, type DynamicClientRegistrationOptions, type EmailSender, type EnrichedSession, type IssueResult, type LoginRedirect, type MfaSummary, type MfaTransport, type ProtectedResourceMetadata, type RateLimitBindings, type RateLimitDecision, type RateLimitDecoratorOptions, type RateLimitInterceptorOptions, type RateLimitKeyStrategy, type RateLimitRule, type RateLimitRuleInput, type RateLimitStore, RateLimitStoreMemory, RateLimiter, type RateLimiterOptions, type ResolvedAuthCookieConfig, type ResolvedAuthOptions, type ResolvedAuthWorkflowOpts, type SessionEnricher, type SessionInfo, type SetPasswordCopy, type SmsSender, type SsoProvider, type TAuthMeta, type TRateLimitMeta, type UserAuthErrorBody, type WfTriggerHooks, type WfTriggerOpts, type WwwAuthenticateBearerChallengeOptions, buildAuthorizationServerMetadata, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, generateMagicLinkToken };