@aooth/auth-moost 0.1.85 → 0.2.1

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,8 +1,9 @@
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, 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, 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 { TCookieAttributesInput } from "@wooksjs/event-http";
5
5
  import { FederatedIdentityStore, FederatedProfileSnapshot, MfaMethod, TransferablePolicy, TrustedDeviceRecord, UserCredentials, UserService } from "@aooth/user";
6
+ import { HttpError as HttpError$1 } from "@moostjs/event-http";
6
7
  import { FinishWfOpts, WfFinished, useAtscriptWf } from "@atscript/moost-wf";
7
8
  import { MoostWf, WfOutlet, WfOutletTokenConfig, WfStateStrategy } from "@moostjs/event-wf";
8
9
  import { FederatedLoginService, NormalizedProfile, OAuthProviderRegistry } from "@aooth/idp";
@@ -17,6 +18,15 @@ interface ResolvedAuthCookieConfig {
17
18
  httpOnly: boolean;
18
19
  path: string;
19
20
  domain?: string;
21
+ /**
22
+ * Keep the cookie across browser restarts: `Max-Age` follows the token it
23
+ * carries (access / refresh expiry) and is renewed on every rotation.
24
+ * Default `false` — a session cookie (gone when the browser closes). Not
25
+ * inherited by the refresh cookie: set it on `refreshCookie` for a
26
+ * "stay signed in" device (the access cookie can stay session-only — a
27
+ * missing one is silently refreshed).
28
+ */
29
+ persistent: boolean;
20
30
  }
21
31
  interface AuthOptions {
22
32
  cookie?: Partial<ResolvedAuthCookieConfig>;
@@ -30,6 +40,15 @@ interface AuthOptions {
30
40
  enableCookie?: boolean;
31
41
  /** Read the session token from `Authorization: Bearer ...`. Default: `true`. */
32
42
  enableBearer?: boolean;
43
+ /**
44
+ * Return `accessToken` / `refreshToken` in JSON bodies (login finish,
45
+ * `POST /auth/refresh`). Default: `!enableCookie` — a cookie app keeps token
46
+ * material out of reach of page scripts, so an XSS cannot read a fresh
47
+ * refresh token from `/auth/refresh`. Set `true` for token clients (CLI,
48
+ * mobile) that share the cookie deployment; accepting `Authorization: Bearer`
49
+ * on requests is controlled separately by {@link enableBearer}.
50
+ */
51
+ exposeTokensInBody?: boolean;
33
52
  }
34
53
  /**
35
54
  * Fully-resolved options carried by `authGuardInterceptor(opts)` through the
@@ -46,6 +65,7 @@ interface ResolvedAuthOptions {
46
65
  refreshCookie: ResolvedAuthCookieConfig;
47
66
  enableCookie: boolean;
48
67
  enableBearer: boolean;
68
+ exposeTokensInBody: boolean;
49
69
  }
50
70
  //#endregion
51
71
  //#region src/consent.store.d.ts
@@ -181,14 +201,14 @@ declare function authGuardInterceptor(opts?: AuthOptions): TInterceptorDef;
181
201
  */
182
202
  declare function AuthGuarded(opts?: AuthOptions): ClassDecorator & MethodDecorator;
183
203
  //#endregion
184
- //#region ../../node_modules/.pnpm/@wooksjs+event-wf@0.7.31_@prostojs+logger@0.4.3_@wooksjs+event-core@0.7.31_@wooksjs+eve_e8aba0a16501b60af733b247c57b6e07/node_modules/@wooksjs/event-wf/dist/index.d.ts
204
+ //#region ../../node_modules/.pnpm/@wooksjs+event-wf@0.8.0_@prostojs+logger@0.4.3_@prostojs+router@0.3.6_@wooksjs+event-co_86044e452e9fcfb26549e7ecde073940/node_modules/@wooksjs/event-wf/dist/index.d.ts
185
205
  interface WfFinishedResponse {
186
206
  type: 'redirect' | 'data';
187
207
  /** Redirect URL or response body */
188
208
  value: unknown;
189
209
  /** HTTP status code (default 200 for data, 302 for redirect) */
190
210
  status?: number;
191
- /** Cookies to set */
211
+ /** Cookies to set — `options` are `setCookie()` attributes (`maxAge` in **seconds**, `expires` a Date or ms timestamp) */
192
212
  cookies?: Record<string, {
193
213
  value: string;
194
214
  options?: Record<string, unknown>;
@@ -213,9 +233,10 @@ interface AuthLogoutBody {
213
233
  * POST /auth/refresh response body. Also returned by workflow finalize steps
214
234
  * (e.g. `AuthWorkflow`) when issuing tokens after a successful flow.
215
235
  *
216
- * Tokens are populated only when `enableBearer` is true. With `enableBearer=false`
217
- * the body still echoes `userId` + `accessExpiresAt` so the caller can schedule
218
- * a silent refresh; the actual tokens travel only in cookies.
236
+ * Tokens are populated only when `exposeTokensInBody` is true (default
237
+ * `!enableCookie`). Otherwise the body still echoes `userId` + `accessExpiresAt`
238
+ * so the caller can schedule a silent refresh; the actual tokens travel only in
239
+ * cookies.
219
240
  */
220
241
  interface AuthLoginResponse {
221
242
  userId: string;
@@ -263,7 +284,13 @@ interface AuthBindings {
263
284
  extractToken(): string | undefined;
264
285
  writeCookies(issue: IssueResult$1): void;
265
286
  clearCookies(): void;
266
- buildLoginResponse(userId: string, issue: IssueResult$1): AuthLoginResponse;
287
+ /**
288
+ * `opts.exposeTokens` overrides `exposeTokensInBody` for this response (the
289
+ * refresh route sets it when the refresh token arrived in the body).
290
+ */
291
+ buildLoginResponse(userId: string, issue: IssueResult$1, opts?: {
292
+ exposeTokens?: boolean;
293
+ }): AuthLoginResponse;
267
294
  buildFinishedCookies(issue: IssueResult$1): WfFinishedResponse["cookies"];
268
295
  /** Build cookie attrs from the resolved access-cookie config, with optional overrides. */
269
296
  cookieAttrs(extra?: TCookieAttributesInput): TCookieAttributesInput;
@@ -323,6 +350,81 @@ type AuthMate = Mate<TMoostMetadata & {
323
350
  }>;
324
351
  declare function getAuthMate(): AuthMate;
325
352
  //#endregion
353
+ //#region src/workflow/auth-messages.d.ts
354
+ /**
355
+ * Code-keyed catalogue of every user-facing text `AuthWorkflow` produces —
356
+ * form errors, banners, finish envelopes and button labels. Templates are
357
+ * English; `{name}` placeholders are filled from the message params.
358
+ *
359
+ * Override per app with `AuthWorkflowOpts.messages` (a partial map, or a
360
+ * function that receives the code and params and returns the text — e.g. a
361
+ * lookup in your own i18n library), or override `AuthWorkflow.msg()`.
362
+ */
363
+ declare const AOOTH_MESSAGES: {
364
+ readonly INVALID_CREDENTIALS: "Invalid credentials";
365
+ readonly ACCOUNT_LOCKED: "Account locked, please try again later";
366
+ readonly INVALID_PASSWORD: "Invalid password";
367
+ readonly INCORRECT_PASSWORD: "Incorrect password";
368
+ readonly SESSION_LIMIT_REACHED: "Session limit reached";
369
+ readonly PASSWORD_CHANGED_SIGN_IN_AGAIN: "Your password was changed. Please sign in again.";
370
+ readonly INVALID_CODE: "Invalid code";
371
+ /** Params: `seconds`. */
372
+ readonly RESEND_WAIT: "Please wait {seconds}s before requesting a new code.";
373
+ /** Params: `seconds`. */
374
+ readonly RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code";
375
+ /** Params: `seconds`, `channel` (`SMS` / `email`). */
376
+ readonly RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code";
377
+ readonly TOTP_RESEND_NOT_APPLICABLE: "Resend is not applicable for TOTP";
378
+ readonly UNKNOWN_MFA_METHOD: "Unknown MFA method";
379
+ readonly UNKNOWN_METHOD: "Unknown method";
380
+ readonly METHOD_UNAVAILABLE: "That method isn't available";
381
+ readonly METHOD_NOT_CHANGEABLE: "That method can't be changed here.";
382
+ readonly KEEP_ONE_MFA_METHOD: "You must keep at least one two-factor method.";
383
+ readonly CHOOSE_OPTION: "Choose an option";
384
+ readonly ALL_MFA_METHODS_SET_UP: "You've already set up every available authentication method.";
385
+ readonly NO_MFA_CHANGES: "No changes were made to your two-factor methods.";
386
+ readonly PASSWORDS_DO_NOT_MATCH: "Passwords do not match";
387
+ readonly PASSWORD_CHANGE_TOO_RECENT: "You changed your password too recently. Please try again later.";
388
+ readonly PASSWORD_CHANGED: "Your password has been changed.";
389
+ readonly PASSWORD_UPDATED_REDIRECTING: "Password updated. Redirecting to sign-in…";
390
+ readonly PASSWORD_UPDATED_STILL_LOCKED: "Password updated, but your account is still locked. Contact an administrator to regain access.";
391
+ readonly RECOVERY_INSTRUCTIONS_SENT: "If an account exists, you will receive instructions.";
392
+ readonly SIGNUP_DISABLED: "Self-signup is currently disabled.";
393
+ readonly ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.";
394
+ readonly ACCOUNT_LINKED: "Account linked.";
395
+ readonly INVALID_ROLE: "Invalid role";
396
+ readonly INVITE_ALREADY_PENDING: "Invite already pending";
397
+ readonly USER_ALREADY_EXISTS: "User already exists";
398
+ readonly DUPLICATE_INVITE_REJECTED: "Duplicate invite rejected";
399
+ readonly INVITE_CANCELLED: "This invite has been cancelled";
400
+ readonly INVITE_REPLACED: "This invite was replaced by a newer one";
401
+ readonly INVITE_ALREADY_ACCEPTED: "This invite was already accepted.";
402
+ readonly CHOOSE_USERNAME_TAKEN: "This username is taken";
403
+ readonly USERNAME_NOT_ALLOWED: "This username is not allowed";
404
+ readonly AUTHZ_EXPIRED: "Authorization request expired. Please try again.";
405
+ readonly AUTHZ_BROWSER_MISMATCH: "This authorization could not be verified for your browser. Please start again.";
406
+ readonly AUTHZ_FAILED: "Authorization could not be completed. Please start again.";
407
+ readonly GO_TO_SIGN_IN: "Go to sign-in";
408
+ readonly BACK_TO_SIGN_IN: "Back to sign-in";
409
+ readonly REQUEST_NEW_INVITE: "Request a new invite";
410
+ readonly BACK: "Back";
411
+ readonly GO_NOW: "Go now";
412
+ };
413
+ /** A message code of {@link AOOTH_MESSAGES}. */
414
+ type AoothMessageCode = keyof typeof AOOTH_MESSAGES;
415
+ /** Values filled into a message template's `{name}` placeholders. */
416
+ type AoothMessageParams = Readonly<Record<string, string | number>>;
417
+ /**
418
+ * App overrides for {@link AOOTH_MESSAGES}: a partial map (templates may use
419
+ * the same `{name}` placeholders), or a resolver returning the final text —
420
+ * `undefined` falls back to the built-in English template.
421
+ */
422
+ type AoothMessages = Partial<Record<AoothMessageCode, string>> | ((code: AoothMessageCode, params: AoothMessageParams) => string | undefined);
423
+ /** Fill `{name}` placeholders from `params`; unknown placeholders are kept. */
424
+ declare function renderAoothMessage(template: string, params?: AoothMessageParams): string;
425
+ /** Resolve `code` through `messages` (when given), falling back to the English template. */
426
+ declare function resolveAoothMessage(code: AoothMessageCode, params?: AoothMessageParams, messages?: AoothMessages): string;
427
+ //#endregion
326
428
  //#region src/auth.controller.d.ts
327
429
  /** Workflows allowed by the bundled `/auth/trigger` endpoint. Subclasses override `triggerWf()` to extend. */
328
430
  declare const DEFAULT_AUTH_WORKFLOWS: readonly ["auth/login/flow", "auth/invite/start", "auth/recovery/flow", "auth/signup/flow"];
@@ -410,13 +512,22 @@ declare class AuthController {
410
512
  * but the user-id baked into the magic-link URL by `buildMagicLinkUrl(…, {
411
513
  * userId })` lets the SPA resolve the "already accepted" condition itself.
412
514
  *
413
- * `@Public()` — invitees aren't signed in at this point.
515
+ * `@Public()` — invitees aren't signed in at this point. Rate limited
516
+ * (`30/5m` per IP, enforced when `rateLimitInterceptors` are installed); an
517
+ * unknown id and a still-pending invite get the same 404.
414
518
  *
415
519
  * Defaults for `loginUrl` / `alreadyAcceptedRedirectUrl` mirror the unified
416
520
  * `AuthWorkflow` defaults (`/login` / `/login`). Subclasses override
417
521
  * `resolveInvitePostRedemption()` to read live workflow opts.
418
522
  */
419
523
  invitePostRedemption(uid: string | undefined): Promise<WfFinished>;
524
+ /**
525
+ * Whether `GET auth/invite/post-redemption` is served. Default `true`.
526
+ * Override to return `false` when the app does not use magic-link invites —
527
+ * the route then answers 404 for every id (a subclass cannot unregister an
528
+ * inherited route).
529
+ */
530
+ protected invitePostRedemptionEnabled(): boolean;
420
531
  /**
421
532
  * URLs used by `invitePostRedemption`. Defaults mirror the unified
422
533
  * `AuthWorkflow` resolved opts so subclasses that customize either of
@@ -425,6 +536,8 @@ declare class AuthController {
425
536
  protected resolveInvitePostRedemption(): {
426
537
  loginUrl: string;
427
538
  alreadyAcceptedRedirectUrl: string;
539
+ /** Text overrides — pass the same value as `AuthWorkflowOpts.messages`. */
540
+ messages?: AoothMessages;
428
541
  };
429
542
  }
430
543
  //#endregion
@@ -501,7 +614,11 @@ declare class SessionsController {
501
614
  //#endregion
502
615
  //#region src/wf-trigger/decorator.d.ts
503
616
  interface WfTriggerOpts {
504
- /** Whitelist of workflow ids the trigger may start/resume. Defaults to the provider's setting. */
617
+ /**
618
+ * Workflow ids this trigger may START and RESUME (a leading `/` is ignored).
619
+ * Omitted = unrestricted; `[]` = deny every workflow. A state token minted
620
+ * for a workflow outside the list is refused with 403 and is not consumed.
621
+ */
505
622
  allow?: string[];
506
623
  /** Per-endpoint token wire override. Defaults to the provider's wire (`{read:['body','query','cookie'], write:'body', name:'wfs'}`). */
507
624
  token?: WfOutletTokenConfig;
@@ -584,6 +701,11 @@ declare function deriveWfStateSecret(secret: string): Buffer;
584
701
  declare class WfTriggerProvider {
585
702
  protected readonly wf: MoostWf;
586
703
  protected readonly auth: AuthCredential;
704
+ /**
705
+ * Outlets the trigger can pause on: HTTP (forms) and `invite` (the link of
706
+ * `AuthWorkflowOpts.inviteDelivery: 'deliver' | 'return-link'`). Append an
707
+ * `email` outlet (`createAuthEmailOutlet`) for the default invite delivery.
708
+ */
587
709
  protected outlets: WfOutlet[];
588
710
  protected token: WfOutletTokenConfig;
589
711
  constructor(wf: MoostWf, auth: AuthCredential);
@@ -605,12 +727,29 @@ declare class WfTriggerProvider {
605
727
  private cachedState?;
606
728
  /** 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. */
607
729
  protected stateRegistry(): StateRegistry;
730
+ /**
731
+ * Handle one trigger request. `allow` lists the workflow ids this route may
732
+ * START and RESUME (matched without a leading `/`); omitted = unrestricted,
733
+ * `[]` = deny all. A state token minted for a workflow outside the list is
734
+ * refused with 403 before it is consumed.
735
+ */
608
736
  handle(opts?: {
609
737
  allow?: string[];
610
738
  token?: WfOutletTokenConfig;
611
739
  }): Promise<unknown>;
612
740
  }
613
741
  //#endregion
742
+ //#region src/workflow/invite-outlet.d.ts
743
+ /** Name of the outlet `AuthWorkflow` pauses on for `inviteDelivery: 'deliver' | 'return-link'`. */
744
+ declare const INVITE_OUTLET = "invite";
745
+ /**
746
+ * The `invite` outlet (registered by default on `WfTriggerProvider`): hands
747
+ * the resume token to the callback the `send-email` step registered, which
748
+ * builds the link and delivers it (`'deliver'`) or returns it to the issuer
749
+ * (`'return-link'`). The token never rides the response on its own.
750
+ */
751
+ declare function createInviteOutlet(): WfOutlet;
752
+ //#endregion
614
753
  //#region src/rate-limit/mate.d.ts
615
754
  /**
616
755
  * Caller-identity strategy for a rate-limited route (RL.spec.md §5.3):
@@ -624,9 +763,12 @@ declare class WfTriggerProvider {
624
763
  * `'user'`. Apps supply their own kinds (`'tenant'`, `'apiKey'`, …) via
625
764
  * `setRateLimitSubject`.
626
765
  * - custom function — runs inside the event context PRE-guard; must be
627
- * self-sufficient (it cannot read what GUARD-priority code sets).
766
+ * self-sufficient (it cannot read what GUARD-priority code sets). Return
767
+ * a composite subject (e.g. client IP + submitted username) to key on
768
+ * several things at once, or `null` / `undefined` to SKIP the policy for
769
+ * this request (nothing is counted).
628
770
  */
629
- type RateLimitKeyStrategy = "ip" | "user" | "auto" | "session" | (string & {}) | (() => string | Promise<string>);
771
+ type RateLimitKeyStrategy = "ip" | "user" | "auto" | "session" | (string & {}) | (() => string | null | undefined | Promise<string | null | undefined>);
630
772
  /** Trailing options object accepted by `@RateLimit(...rules, opts)`. */
631
773
  interface RateLimitDecoratorOptions {
632
774
  /** Overrides the interceptor-level default key strategy for this route. */
@@ -639,15 +781,24 @@ interface RateLimitDecoratorOptions {
639
781
  */
640
782
  id?: string;
641
783
  }
784
+ /** One `@RateLimit(...)` declaration: its rules and options. */
785
+ interface TRateLimitPolicy {
786
+ /** Rules normalized at decoration time — bad grammar fails at boot. */
787
+ rules: RateLimitRule$1[];
788
+ options?: RateLimitDecoratorOptions;
789
+ }
642
790
  /**
643
791
  * Rate-limit metadata written by `@RateLimit()` and read by
644
792
  * `rateLimitInterceptors`. Merged into `TMoostMetadata` so other moost-aware
645
793
  * tooling sees it.
646
794
  */
647
795
  interface TRateLimitMeta {
648
- /** Rules normalized at decoration time — bad grammar fails at boot. */
649
- rateLimitRules?: RateLimitRule$1[];
650
- rateLimitOptions?: RateLimitDecoratorOptions;
796
+ /**
797
+ * One entry per stacked `@RateLimit(...)` decorator, in source order. Each
798
+ * is an independent policy (own key strategy and bucket); a request must
799
+ * pass all of them.
800
+ */
801
+ rateLimitPolicies?: TRateLimitPolicy[];
651
802
  /** `@RateLimit(false)` — opt this route out of interceptor-level default rules. */
652
803
  rateLimitDisabled?: boolean;
653
804
  }
@@ -677,7 +828,12 @@ interface RateLimitInterceptorOptions {
677
828
  rules?: RateLimitRuleInput$1[];
678
829
  /** Default key strategy for routes whose `@RateLimit` doesn't set one. Default: `'ip'`. */
679
830
  key?: RateLimitKeyStrategy;
680
- /** Trust `x-forwarded-for` for the client IP (behind a proxy). Default: `false`. */
831
+ /**
832
+ * Trust exactly ONE reverse proxy in front of the app: the client IP is the
833
+ * right-most `x-forwarded-for` entry (the one that proxy wrote). Default:
834
+ * `false` — the client IP as the HTTP app resolves it (`useRequest().getIp()`:
835
+ * the socket peer, unless the wooks HTTP app configures `trustProxy`).
836
+ */
681
837
  trustProxy?: boolean;
682
838
  /** Emit draft `RateLimit-*` headers on every response of a limited route. Default: `true`. */
683
839
  headers?: boolean;
@@ -707,10 +863,10 @@ interface RateLimitInterceptorOptions {
707
863
  * the auth context `useAuth()` reads, and by definition target
708
864
  * authenticated traffic where the guard must run anyway.
709
865
  *
710
- * Ownership is static per route (from metadata/options), so exactly one
711
- * phase evaluates each event; the decision event-slot additionally guards
712
- * against double counting when the pair is also attached per-controller
713
- * (see {@link RateLimited}).
866
+ * Ownership is static per policy (from metadata/options): a route whose
867
+ * stacked policies mix both kinds is evaluated by both phases, each checking
868
+ * its own policies. A per-event phase marker guards against double counting
869
+ * when the pair is also attached per-controller (see {@link RateLimited}).
714
870
  *
715
871
  * On rejection: draft `RateLimit-*` headers + `Retry-After` are written to
716
872
  * the accumulated response (they survive the throw — wooks renders the error
@@ -733,6 +889,10 @@ declare function rateLimitInterceptors(opts?: RateLimitInterceptorOptions): TInt
733
889
  * RateLimit(false) // opt out of interceptor-level default rules
734
890
  * ```
735
891
  *
892
+ * Stacking several `@RateLimit` decorators declares independent policies —
893
+ * each with its own key strategy and bucket — and a request must pass all
894
+ * of them (e.g. a per-IP limit plus a per-account limit).
895
+ *
736
896
  * Rules are parsed eagerly, so a bad rule string throws at decoration
737
897
  * (boot) time, not per request.
738
898
  */
@@ -1566,9 +1726,12 @@ interface AuthWfSessionPolicy {
1566
1726
  * `UserService.changePassword`), NOT rate limiting — so `rateLimit` is
1567
1727
  * optional and off by default.
1568
1728
  *
1569
- * - `revokeOtherSessions` — on success, revoke every session for the user then
1570
- * re-issue the acting session a fresh token (OWASP Session Management: kill
1571
- * ghost sessions after a credential change). Default `true`.
1729
+ * - `revokeOtherSessions` — on success, revoke the user's OTHER sessions (OWASP
1730
+ * Session Management: kill ghost sessions after a credential change). Default
1731
+ * `true`. Either way the acting device moves onto a fresh session and the
1732
+ * session the change was made from is revoked; when that session can't be
1733
+ * targeted (stateless JWT / encapsulated store, legacy pre-sessionId
1734
+ * credential) every session is revoked.
1572
1735
  * - `rateLimit.minIntervalMs` — minimum gap between successive password changes
1573
1736
  * (Okta "minimum password age"). Enforced against `password.lastChanged` with
1574
1737
  * ZERO extra storage. Omit to disable.
@@ -1614,6 +1777,10 @@ interface AuthWfAcceptState {
1614
1777
  showConfirmation?: boolean;
1615
1778
  confirmationMessage?: string;
1616
1779
  alreadyAccepted?: boolean;
1780
+ /** `inviteUsername: 'choose'` — the invitee picks their username at accept. */
1781
+ chooseUsername?: boolean;
1782
+ /** Set once `choose-username` stored the invitee's pick. */
1783
+ usernameChosen?: boolean;
1617
1784
  }
1618
1785
  /**
1619
1786
  * Recovery post-reset state. `freshLoginRequired` removed — the choice is
@@ -1666,6 +1833,22 @@ interface AuthWfAdminState {
1666
1833
  * second email and re-pausing. See `sendInviteEmail` for the why.
1667
1834
  */
1668
1835
  emailDispatched?: boolean;
1836
+ /**
1837
+ * App context for this invite, from `resolveInviteContext(ctx, startFormData)`
1838
+ * at `init-invite-admin` (e.g. a tenant / household id). Server-only.
1839
+ */
1840
+ app?: Record<string, unknown>;
1841
+ /** Admin-form fields beyond `email` / `roles` (a consumer's extended invite form). Server-only. */
1842
+ form?: Record<string, unknown>;
1843
+ /** User id of the issuer (from the session at `build-user-extras`). */
1844
+ invitedBy?: string;
1845
+ /**
1846
+ * Marker of THIS invite link, mirrored on `account.inviteNonce`. A re-invite
1847
+ * rotates the account's nonce, so this run's link then answers 410.
1848
+ */
1849
+ inviteNonce?: string;
1850
+ /** How the link was delivered (`AuthWorkflowOpts.inviteDelivery`), read at accept. */
1851
+ inviteDelivery?: "outlet-email" | "deliver" | "return-link";
1669
1852
  }
1670
1853
  /**
1671
1854
  * Pre-fill payload surfaced to forms via `@wf.context.pass 'defaults'`.
@@ -1952,6 +2135,13 @@ interface AuthWfPublicState {
1952
2135
  defaults?: {
1953
2136
  email?: string;
1954
2137
  };
2138
+ /**
2139
+ * Client-side form texts overridden through `AuthWorkflowOpts.messages`
2140
+ * (only codes a form validator reads; present only when overridden).
2141
+ */
2142
+ messages?: {
2143
+ PASSWORDS_DO_NOT_MATCH?: string;
2144
+ };
1955
2145
  /**
1956
2146
  * Mirrors `ctx.pendingLink` display fields — the proof `mode`, the masked
1957
2147
  * account `hint` ("an account for a***@x.com exists"), the masked delivery
@@ -2003,6 +2193,20 @@ interface AuthWfCtx {
2003
2193
  aborted?: boolean;
2004
2194
  isFirstLogin?: boolean;
2005
2195
  newPasswordRequired?: boolean;
2196
+ /**
2197
+ * Set by `create-password-form` once it stored a new password. In login.flow
2198
+ * it gates the `revoke-sessions` step after the MFA loop (sessions opened
2199
+ * with the old password end) and exempts the run from
2200
+ * `check-password-unchanged`. Server-only flow control.
2201
+ */
2202
+ passwordChanged?: boolean;
2203
+ /**
2204
+ * `password.lastChanged` of the account as the `credentials` step verified
2205
+ * it. `check-password-unchanged` compares it before the login is recorded,
2206
+ * so a run paused across a password change can't finish on the replaced
2207
+ * password. Server-only flow control.
2208
+ */
2209
+ passwordStamp?: number;
2006
2210
  /**
2007
2211
  * Idempotency latch for the single `record-login` funnel step. Set true once
2008
2212
  * a login has been stamped this run — by the `credentials` step (the password
@@ -2133,6 +2337,63 @@ interface AuthWorkflowOpts {
2133
2337
  * itself relax or tighten enforcement. Default `false`.
2134
2338
  */
2135
2339
  allowAnyInviteRole?: boolean;
2340
+ /**
2341
+ * How the invite link reaches the invitee:
2342
+ * - `'outlet-email'` (default) — the workflow pauses on the `email` outlet
2343
+ * (`invite.magicLink` template); register an email outlet on the trigger
2344
+ * provider (`createAuthEmailOutlet`).
2345
+ * - `'deliver'` — the link is handed to `deliver({ kind: 'invite-link', … })`,
2346
+ * the same seam as every other notice.
2347
+ * - `'return-link'` — nothing is sent; the issuer's trigger response carries
2348
+ * `data.inviteLink` to share by hand. A click then does not prove the
2349
+ * invitee's inbox, so accepting does not record `account.verifiedEmail`.
2350
+ * `'deliver'` and `'return-link'` need {@link inviteLinkUrl}.
2351
+ */
2352
+ inviteDelivery?: "outlet-email" | "deliver" | "return-link";
2353
+ /**
2354
+ * Builds the invite link from the resume token for `inviteDelivery:
2355
+ * 'deliver' | 'return-link'` (the `email` outlet builds its own). Put the
2356
+ * token in the `wfs` query parameter of the SPA page that renders the
2357
+ * invite workflow; `userId` lets that page resolve a re-click after
2358
+ * acceptance (`GET auth/invite/post-redemption?uid=`).
2359
+ */
2360
+ inviteLinkUrl?: (token: string, info: {
2361
+ userId?: string;
2362
+ }) => string;
2363
+ /**
2364
+ * Who picks the login handle of an invited account:
2365
+ * - `'email'` (default) — the invited email address is the username.
2366
+ * - `'choose'` — the invitee picks a username on the accept page (the
2367
+ * `InviteChooseUsernameForm` step, before the password); the email stays
2368
+ * the correspondence address.
2369
+ */
2370
+ inviteUsername?: "email" | "choose";
2371
+ /**
2372
+ * Overrides for the user-facing texts (`AOOTH_MESSAGES`, keyed by code): a
2373
+ * partial map of templates, or a resolver `(code, params) => text` (return
2374
+ * `undefined` to keep the English default). The resolver runs inside the
2375
+ * request, so it can read the caller's locale.
2376
+ */
2377
+ messages?: AoothMessages;
2378
+ /**
2379
+ * What a failed sign-in tells the caller about locked accounts:
2380
+ * - `'uniform'` (default) — a locked account answers "Account locked", and
2381
+ * so does an unknown (or inactive) handle after the same number of failed
2382
+ * attempts (a shadow counter, see `lockoutShadowStore`) — so the lock
2383
+ * message does not reveal which accounts exist.
2384
+ * - `'generic'` — every failure, locked or not, answers "Invalid credentials".
2385
+ * - `'reveal'` — only real locked accounts answer "Account locked" (the
2386
+ * pre-0.2 behaviour; reveals which handles exist).
2387
+ * The threshold and duration come from `UserService`'s `lockout` config; with
2388
+ * lockout disabled (`threshold: 0`) all three behave like `'generic'`.
2389
+ */
2390
+ lockoutDisclosure?: "uniform" | "generic" | "reveal";
2391
+ /**
2392
+ * Counter store for the `'uniform'` shadow lockout of unknown handles.
2393
+ * Default: one process-wide in-memory store — pass a shared store (e.g.
2394
+ * `RateLimitStoreRedis`) when several instances serve sign-ins.
2395
+ */
2396
+ lockoutShadowStore?: RateLimitStore$1;
2136
2397
  /** Pincode infrastructure shared by login MFA, invite MFA, and recovery OTP. */
2137
2398
  mfa?: {
2138
2399
  pincodeLength?: number;
@@ -2196,6 +2457,8 @@ interface AuthWorkflowOpts {
2196
2457
  setPassword?: TAtscriptAnnotatedType;
2197
2458
  /** Authenticated self-service "change my password" form (current + new + confirm). */
2198
2459
  changePassword?: TAtscriptAnnotatedType;
2460
+ /** Username picker shown at invite accept when `inviteUsername: 'choose'`. */
2461
+ inviteChooseUsername?: TAtscriptAnnotatedType;
2199
2462
  /** Password-proof form rendered by `prove-control` when the matched account has a real password. */
2200
2463
  proveControl?: TAtscriptAnnotatedType;
2201
2464
  /** OTP-proof form rendered by `prove-control` when the matched account is passwordless. */
@@ -2220,6 +2483,14 @@ interface ResolvedAuthWorkflowOpts {
2220
2483
  autoLoginOnRecover: boolean;
2221
2484
  invitableRoles: string[];
2222
2485
  allowAnyInviteRole: boolean;
2486
+ inviteDelivery: "outlet-email" | "deliver" | "return-link";
2487
+ inviteLinkUrl?: (token: string, info: {
2488
+ userId?: string;
2489
+ }) => string;
2490
+ inviteUsername: "email" | "choose";
2491
+ messages?: AoothMessages;
2492
+ lockoutDisclosure: "uniform" | "generic" | "reveal";
2493
+ lockoutShadowStore: RateLimitStore$1;
2223
2494
  mfa: {
2224
2495
  pincodeLength: number;
2225
2496
  pincodeTtlMs: number;
@@ -2258,6 +2529,7 @@ interface ResolvedAuthWorkflowOpts {
2258
2529
  pincode: TAtscriptAnnotatedType;
2259
2530
  setPassword: TAtscriptAnnotatedType;
2260
2531
  changePassword: TAtscriptAnnotatedType;
2532
+ inviteChooseUsername: TAtscriptAnnotatedType;
2261
2533
  proveControl: TAtscriptAnnotatedType;
2262
2534
  proveControlOtp: TAtscriptAnnotatedType;
2263
2535
  termsBump: TAtscriptAnnotatedType;
@@ -2373,19 +2645,28 @@ declare function parseInviteRoles(input?: string[]): string[];
2373
2645
  declare function buildInviteAlreadyAcceptedEnvelope(opts: {
2374
2646
  loginUrl: string;
2375
2647
  alreadyAcceptedRedirectUrl: string;
2648
+ /** Text overrides (see `AuthWorkflowOpts.messages`). */
2649
+ messages?: AoothMessages;
2376
2650
  }): FinishWfOpts;
2377
2651
  declare class AuthWorkflow {
2378
2652
  protected readonly opts: ResolvedAuthWorkflowOpts;
2379
2653
  protected readonly users: UserService;
2380
2654
  protected readonly auth: AuthCredential;
2381
2655
  protected readonly consentStore: ConsentStore;
2656
+ /** The invite context every invite hook receives: issuer, app context, extra form fields. */
2657
+ private inviteHookInput;
2658
+ /** Warn once per process when a `'reuse'` re-invite crosses issuers. */
2659
+ private warnCrossIssuerReuse;
2660
+ constructor(opts: Partial<AuthWorkflowOpts>, users: UserService, auth: AuthCredential, consentStore: ConsentStore);
2382
2661
  /**
2383
- * Process-lifetime warn-once latch for the "invite role whitelist is OFF"
2384
- * notice. App-level (singleton) state, NOT per-event — keeps the warning from
2385
- * spamming on every invite while still surfacing the misconfig once.
2662
+ * Resolve a user-facing text by code (`AOOTH_MESSAGES`) through
2663
+ * `opts.messages`. Every form error, banner, finish message and button label
2664
+ * the workflow produces goes through here — override for full control
2665
+ * (e.g. to call your i18n library with the request's locale).
2386
2666
  */
2387
- private warnedOpenInviteWhitelist;
2388
- constructor(opts: Partial<AuthWorkflowOpts>, users: UserService, auth: AuthCredential, consentStore: ConsentStore);
2667
+ protected msg(code: AoothMessageCode, params?: AoothMessageParams): string;
2668
+ /** An `HttpError` whose body carries the message `code` next to its (resolved) text. */
2669
+ protected httpError(status: 409 | 410, code: AoothMessageCode): HttpError$1;
2389
2670
  /**
2390
2671
  * Unified outbound dispatch hook for direct synchronous deliveries
2391
2672
  * (MFA / recovery / enrollment pincodes, new-device notices). NOT used for
@@ -2495,6 +2776,10 @@ declare class AuthWorkflow {
2495
2776
  email?: string;
2496
2777
  roles: string[];
2497
2778
  invitedBy?: string;
2779
+ /** Invite only: the app context from {@link resolveInviteContext}. */
2780
+ app?: Record<string, unknown>;
2781
+ /** Invite only: admin-form fields beyond `email` / `roles`. */
2782
+ form?: Record<string, unknown>;
2498
2783
  }): Promise<Record<string, unknown>> | Record<string, unknown>;
2499
2784
  /**
2500
2785
  * Derive roles server-side from the admin-form payload (e.g. AD lookup).
@@ -2503,7 +2788,20 @@ declare class AuthWorkflow {
2503
2788
  */
2504
2789
  protected inferAdminRoles(_input: {
2505
2790
  email: string;
2791
+ invitedBy?: string;
2792
+ app?: Record<string, unknown>;
2793
+ form?: Record<string, unknown>;
2506
2794
  }): Promise<string[]> | string[];
2795
+ /**
2796
+ * App context of an invite, resolved once when the issue phase starts
2797
+ * (`init-invite-admin`) from the trigger's START input (`{ wfid, input: {
2798
+ * formData } }` — the `startFormData` argument) and the session. Return
2799
+ * e.g. `{ tenantId }`; the value is kept server-side as `ctx.admin.app` and
2800
+ * handed to `prepareUser`, `inferAdminRoles` and `duplicateInviteCheck`.
2801
+ * Throw an `HttpError` to refuse the invite (e.g. the issuer may not invite
2802
+ * into that tenant). Default: `undefined` (no app context).
2803
+ */
2804
+ protected resolveInviteContext(_ctx: AuthWfCtx, _startFormData: Record<string, unknown> | undefined): Record<string, unknown> | undefined | Promise<Record<string, unknown> | undefined>;
2507
2805
  /**
2508
2806
  * Override the structural duplicate rule for `admin-form`. Default: a row
2509
2807
  * still parked on `account.pendingInvitation` → `'reuse'` (re-invite:
@@ -2514,11 +2812,25 @@ declare class AuthWorkflow {
2514
2812
  * Multi-tenant apps that allow re-inviting the same email into a different
2515
2813
  * tenant override to `'allow'`. Apps that want the strict legacy behavior
2516
2814
  * ("Invite already pending" error on a duplicate invite of a pending user)
2517
- * return `'reject'` for pending rows.
2815
+ * return `'reject'` for pending rows. Compare `invitedBy` / `app` with
2816
+ * `pending` and `existingUser` to refuse taking over another issuer's (or
2817
+ * tenant's) pending invite. On `'reuse'` the row's roles and extras are
2818
+ * REPLACED by this invite's, and every link issued before is superseded
2819
+ * (answers 410 "replaced").
2518
2820
  */
2519
2821
  protected duplicateInviteCheck(input: {
2520
2822
  email: string;
2521
2823
  existingUser: UserCredentials | null;
2824
+ /** The issuer of THIS invite (session user id). */
2825
+ invitedBy?: string;
2826
+ /** This invite's app context ({@link resolveInviteContext}). */
2827
+ app?: Record<string, unknown>;
2828
+ /** This invite's extra admin-form fields. */
2829
+ form?: Record<string, unknown>;
2830
+ /** The pending invite already on `existingUser`, when there is one. */
2831
+ pending?: {
2832
+ invitedBy?: string;
2833
+ };
2522
2834
  }): Promise<"allow" | "reject" | "reuse"> | "allow" | "reject" | "reuse";
2523
2835
  /**
2524
2836
  * Implements the "log out other sessions" branch of `sessionPolicy.concurrencyLimit`.
@@ -2684,7 +2996,8 @@ declare class AuthWorkflow {
2684
2996
  * successful change (OWASP Session Management) and applies NO rate limit —
2685
2997
  * current-password re-entry (enforced by `UserService.changePassword`) is the
2686
2998
  * primary protection, not throttling. Customers override to add a min-interval
2687
- * (`rateLimit.minIntervalMs`) or to keep other sessions alive.
2999
+ * (`rateLimit.minIntervalMs`) or to keep other sessions alive. The session the
3000
+ * change was made from is always ended (see `finish-change-password`).
2688
3001
  *
2689
3002
  * Whether the flow may be STARTED at all is governed by arbac on the trigger
2690
3003
  * route (deny the `change-password` action to forbid it for SSO-only orgs) —
@@ -3170,7 +3483,7 @@ declare class AuthWorkflow {
3170
3483
  */
3171
3484
  protected isAccountBlocked(user: UserCredentials): boolean;
3172
3485
  protected probeSilentAuthz(ctx: AuthWfCtx, policy: AuthzReauthPolicy): Promise<boolean>;
3173
- initInviteAdmin(ctx: AuthWfCtx): void;
3486
+ initInviteAdmin(ctx: AuthWfCtx): Promise<undefined>;
3174
3487
  initInviteAccept(ctx: AuthWfCtx): void;
3175
3488
  initRecovery(ctx: AuthWfCtx): void;
3176
3489
  /**
@@ -3208,6 +3521,18 @@ declare class AuthWorkflow {
3208
3521
  */
3209
3522
  initAddMfa(ctx: AuthWfCtx): Promise<undefined>;
3210
3523
  credentials(ctx: AuthWfCtx): Promise<unknown>;
3524
+ /**
3525
+ * Whether a failed password sign-in answers "Account locked" — see
3526
+ * `AuthWorkflowOpts.lockoutDisclosure`. Under `'uniform'` an unknown or
3527
+ * inactive handle keeps a shadow failure counter in `lockoutShadowStore`
3528
+ * that mirrors a real account exactly: every failure counts (the counter is
3529
+ * not reset when it trips — like `failedLoginAttempts`), a lock starts when
3530
+ * `failures >= threshold` and none is active, the tripping attempt still
3531
+ * reads "Invalid credentials", and a permanent lock stays on while probed.
3532
+ * Keys are a hash of the normalised handle (bounded size); the counter
3533
+ * slides for 30 days of inactivity.
3534
+ */
3535
+ private failedLoginReadsLocked;
3211
3536
  /**
3212
3537
  * Route a credentials alt-action click (forgotPassword / signup / magicLink
3213
3538
  * / sso-<id>) to a `finishWf` redirect envelope. Returns `ALT_HANDLED` when
@@ -3313,6 +3638,13 @@ declare class AuthWorkflow {
3313
3638
  * `ctx.admin.userExtras`.
3314
3639
  */
3315
3640
  buildUserExtras(ctx: AuthWfCtx): Promise<undefined>;
3641
+ /**
3642
+ * Invariant of the invite issue phase: once the admin form is accepted, the
3643
+ * pending user must exist before the link is sent. An issue phase that ends
3644
+ * without one (a broken override, a store that silently dropped the row) is
3645
+ * a server error — never a bare `{ finished: true }`.
3646
+ */
3647
+ assertInviteCreated(ctx: AuthWfCtx): undefined;
3316
3648
  /**
3317
3649
  * Create the user row from `ctx.admin.userExtras` (plus the admin-supplied
3318
3650
  * `ctx.admin.roles`), then stamp `pendingInvitation = true` via a follow-up
@@ -3358,6 +3690,32 @@ declare class AuthWorkflow {
3358
3690
  * cleared.
3359
3691
  */
3360
3692
  checkPendingInvitation(ctx: AuthWfCtx): Promise<undefined>;
3693
+ /**
3694
+ * Username policy for `inviteUsername: 'choose'`, applied to the normalised
3695
+ * (NFKC, trimmed) pick. Return a message code to refuse it. Default: at most
3696
+ * 256 characters, no whitespace or control characters, and no `@` unless it
3697
+ * is the invited address itself — a chosen name must not look like someone
3698
+ * else's email handle (sign-in resolves `username` before email columns).
3699
+ */
3700
+ protected validateChosenUsername(ctx: AuthWfCtx, username: string): AoothMessageCode | undefined;
3701
+ /**
3702
+ * The invited account, refusing a cancelled invite (410 `INVITE_CANCELLED`,
3703
+ * the row is gone) or a superseded link (410 `INVITE_REPLACED`, a re-invite
3704
+ * rotated the account's marker away from this run's).
3705
+ */
3706
+ private currentInviteRow;
3707
+ /**
3708
+ * Re-check, right before an invite-accept write, that this run's link is
3709
+ * still the current one and the invite is still pending — a re-invite or a
3710
+ * parallel acceptance may have happened while this run was paused.
3711
+ */
3712
+ private assertInviteStillOpen;
3713
+ /**
3714
+ * `inviteUsername: 'choose'` — the invitee picks the username they will
3715
+ * sign in with (the invited email stays the correspondence address). The
3716
+ * pick replaces the account's login handle; a taken one re-pauses.
3717
+ */
3718
+ chooseUsername(ctx: AuthWfCtx): Promise<undefined>;
3361
3719
  /**
3362
3720
  * Emit the "this invite was already accepted" finish envelope and short-
3363
3721
  * circuit the rest of the accept tail.
@@ -3404,11 +3762,28 @@ declare class AuthWorkflow {
3404
3762
  */
3405
3763
  changePasswordForm(ctx: AuthWfCtx): Promise<unknown>;
3406
3764
  /**
3407
- * Change-password terminal — rotate the acting session's token (so the
3408
- * current device stays signed in on a FRESH credential) and emit a success
3409
- * message. Runs AFTER the optional `revoke-sessions` step, so the net effect
3410
- * is "kill every other session, keep this one on a new token" (OWASP Session
3411
- * Management: no ghost sessions survive a credential change).
3765
+ * Change-password terminal — sign the current device in on a FRESH session
3766
+ * and end the one the change was made from, then emit a success message.
3767
+ * The new pair is minted under a new session id, so the pre-change session
3768
+ * (its access token, refresh token and every rotation) is revoked here —
3769
+ * whatever `revokeOtherSessions` says, since that policy covers only the
3770
+ * user's OTHER sessions. Runs AFTER the optional `revoke-sessions` step, so
3771
+ * the default net effect is "kill every old session, keep this device on a
3772
+ * new one" (OWASP Session Management: no ghost sessions survive a credential
3773
+ * change).
3774
+ *
3775
+ * The pre-change session is revoked BEFORE the issue, so a failed issue
3776
+ * (store error, `maxConcurrent` refusal) leaves the user signed out, never on
3777
+ * the old session. A refresh in flight during the change is covered by
3778
+ * `AuthCredential`'s revocation protocol (it can't leave live credentials in
3779
+ * a revoked session).
3780
+ *
3781
+ * When one session can't be targeted — a stateless store (JWT /
3782
+ * encapsulated), or a legacy credential minted before `sessionId` existed
3783
+ * (its fallback id, the access token's fingerprint, never reaches the refresh
3784
+ * row) — ALL of the user's sessions are revoked (`revokeAllForUser`, also
3785
+ * under `revokeOtherSessions: false`). A stateless store also denylists the
3786
+ * presented access token (best effort): its revocation epoch is process-local.
3412
3787
  */
3413
3788
  finishChangePassword(ctx: AuthWfCtx): Promise<undefined>;
3414
3789
  /**
@@ -3754,15 +4129,20 @@ declare class AuthWorkflow {
3754
4129
  persistConsents(ctx: AuthWfCtx): Promise<undefined>;
3755
4130
  /**
3756
4131
  * Revoke the user's existing sessions. Shared by recovery (gated upstream by
3757
- * `ctx.postReset.revokeAllSessions`) and authenticated change-password (gated
3758
- * by `ctx.changePassword.revokeOtherSessions`).
4132
+ * `ctx.postReset.revokeAllSessions`), authenticated change-password (gated
4133
+ * by `ctx.changePassword.revokeOtherSessions`) and the forced password change
4134
+ * at login / invite (gated by `ctx.passwordChanged`).
3759
4135
  *
3760
4136
  * - Change-password runs in an authenticated context, so we KEEP the caller's
3761
- * current device via `revokeOtherSessions(username, currentSessionId)` —
4137
+ * current session via `revokeOtherSessions(username, currentSessionId)` —
3762
4138
  * OWASP "invalidate other sessions" without logging the user out of the tab
3763
- * they just changed their password in. If the current session can't be
3764
- * resolved (no session id), fall back to revoking everything (fail-secure).
3765
- * - Recovery is anonymous (no current session to keep) → `revokeAllForUser`.
4139
+ * they just changed their password in. `finish-change-password` then moves
4140
+ * that tab onto a fresh session and revokes the kept one (and covers stores
4141
+ * that cannot enumerate, where `revokeOtherSessions` is a no-op). If the
4142
+ * current session can't be resolved (no session id), fall back to revoking
4143
+ * everything (fail-secure).
4144
+ * - Recovery and the forced change are anonymous (no current session to
4145
+ * keep) → `revokeAllForUser`.
3766
4146
  */
3767
4147
  revokeSessions(ctx: AuthWfCtx): Promise<undefined>;
3768
4148
  /**
@@ -3773,6 +4153,16 @@ declare class AuthWorkflow {
3773
4153
  * also zeroes `failedLoginAttempts`, so the next login starts clean.
3774
4154
  */
3775
4155
  unlockAccount(ctx: AuthWfCtx): Promise<undefined>;
4156
+ /**
4157
+ * Login-only guard before the `record-login` funnel (and again before
4158
+ * `mint-authz-code`, past the consent pause): the account's
4159
+ * `password.lastChanged` must still be the one the `credentials` step
4160
+ * verified (`ctx.passwordStamp`). A run paused after the password check (MFA,
4161
+ * enrolment, consents …) and resumed after the password was changed
4162
+ * elsewhere finishes with an error instead of issuing tokens or minting an
4163
+ * authorization code. Skipped when this run changed the password itself.
4164
+ */
4165
+ checkPasswordUnchanged(ctx: AuthWfCtx): Promise<undefined>;
3776
4166
  /**
3777
4167
  * The SINGLE login-completion funnel. Every flow that establishes an
3778
4168
  * authenticated session routes through here — placed in each login schema
@@ -4204,4 +4594,4 @@ interface AuditEmitter {
4204
4594
  emit(event: AuditEvent): Promise<void> | void;
4205
4595
  }
4206
4596
  //#endregion
4207
- export { ADD_MFA_WORKFLOW, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, type AuditEmitter, type AuditEvent, type AuthBindings, type AuthContext, AuthController, type AuthDeliveryPayload, type AuthEmailEvent, type AuthEmailKind, type AuthEmailOutletDeps, AuthGuarded, 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, AuthWorkflow, type AuthWorkflowOpts, type AuthorizationServerMetadata, AuthorizeController, AuthorizeRuntime, type AuthzReauthPolicy, type BuildAuthorizationServerMetadataOptions, type BuildMagicLinkUrl, type BuildProtectedResourceMetadataOptions, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, type ConcurrencyLimitOptions, type ConnectedAccount, type ConsentDescriptor, type ConsentDescriptorLike, type ConsentEvent, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, type DynamicClientRegistrationOptions, type EmailSender, type EnrichedSession, FEDERATED_IDENTITY_STORE_TOKEN, type IssueResult, type LoginRedirect, type MfaSummary, type MfaTransport, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, type ProtectedResourceMetadata, Public, RESERVED_USER_KEYS, RateLimit, type RateLimitBindings, type RateLimitDecision, type RateLimitDecoratorOptions, type RateLimitInterceptorOptions, type RateLimitKeyStrategy, type RateLimitRule, type RateLimitRuleInput, type RateLimitStore, RateLimitStoreMemory, RateLimited, RateLimiter, type RateLimiterOptions, type ResolvedAuthCookieConfig, type ResolvedAuthOptions, type ResolvedAuthWorkflowOpts, type SessionEnricher, SessionEnricherProvider, type SessionInfo, SessionsController, type SmsSender, type SsoProvider, type TAuthMeta, type TRateLimitMeta, UserId, WfTrigger, type WfTriggerOpts, WfTriggerProvider, type WwwAuthenticateBearerChallengeOptions, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, getRateLimitMate, getRateLimitSubject, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, resolveOAuthRedirect, setRateLimitSubject, stripReservedUserKeys, useAuth, useRateLimit };
4597
+ export { ADD_MFA_WORKFLOW, AOOTH_MESSAGES, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, type AoothMessageCode, type AoothMessageParams, type AoothMessages, type AuditEmitter, type AuditEvent, type AuthBindings, type AuthContext, AuthController, type AuthDeliveryPayload, type AuthEmailEvent, type AuthEmailKind, type AuthEmailOutletDeps, AuthGuarded, 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, AuthWorkflow, type AuthWorkflowOpts, type AuthorizationServerMetadata, AuthorizeController, AuthorizeRuntime, type AuthzReauthPolicy, type BuildAuthorizationServerMetadataOptions, type BuildMagicLinkUrl, type BuildProtectedResourceMetadataOptions, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, type ConcurrencyLimitOptions, type ConnectedAccount, type ConsentDescriptor, type ConsentDescriptorLike, type ConsentEvent, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, type DynamicClientRegistrationOptions, type EmailSender, type EnrichedSession, FEDERATED_IDENTITY_STORE_TOKEN, INVITE_OUTLET, type IssueResult, type LoginRedirect, type MfaSummary, type MfaTransport, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, type ProtectedResourceMetadata, Public, RESERVED_USER_KEYS, RateLimit, type RateLimitBindings, type RateLimitDecision, type RateLimitDecoratorOptions, type RateLimitInterceptorOptions, type RateLimitKeyStrategy, type RateLimitRule, type RateLimitRuleInput, type RateLimitStore, RateLimitStoreMemory, RateLimited, RateLimiter, type RateLimiterOptions, type ResolvedAuthCookieConfig, type ResolvedAuthOptions, type ResolvedAuthWorkflowOpts, type SessionEnricher, SessionEnricherProvider, type SessionInfo, SessionsController, type SmsSender, type SsoProvider, type TAuthMeta, type TRateLimitMeta, UserId, WfTrigger, type WfTriggerOpts, WfTriggerProvider, type WwwAuthenticateBearerChallengeOptions, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, createInviteOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, getRateLimitMate, getRateLimitSubject, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, renderAoothMessage, resolveAoothMessage, resolveOAuthRedirect, setRateLimitSubject, stripReservedUserKeys, useAuth, useRateLimit };