@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.mjs CHANGED
@@ -1,14 +1,15 @@
1
- import { C as RemoveMfaConfirmForm, D as StepUpConfirmForm, E as SignupForm, O as TermsBumpForm, T as SetPasswordForm, _ as PasswordReauthForm, a as ConcurrencyLimitForm, b as ProveControlOtpForm, c as EnrollConfirmForm, d as InviteChooseUsernameForm, f as InviteForm, g as MfaCodeForm, h as ManageMfaForm, i as ChangePasswordForm, l as EnrollPickMethodForm, n as AskPhoneForm, o as EmailIdentifierForm, p as LoginCredentialsForm, r as AuthorizeConsentForm, s as EnrollAddressForm, t as AskEmailForm, u as EnrollTotpQrForm, v as PincodeForm, w as Select2faForm, y as ProveControlForm } from "./forms-C_VNxSDn.mjs";
2
- import { Controller, HandlerPaths, Inherit, Inject, InjectMoostLogger, Injectable, Intercept, MoostInit, Optional, Param, Resolve, TInterceptorPriority, defineAfterInterceptor, defineBeforeInterceptor, defineErrorInterceptor, getMoostMate, useControllerContext, useLogger } from "moost";
3
- import { AuthCredential, AuthError, RateLimitStoreMemory, RateLimitStoreMemory as RateLimitStoreMemory$1, RateLimiter, RateLimiter as RateLimiter$1, generateMagicLinkToken, generateOpaqueToken, parseRateLimitRule, pickGoverning } from "@aooth/auth";
4
- import { current, defineWook, eventTypeKey, key } from "@wooksjs/event-core";
1
+ import { C as RemoveMfaConfirmForm, D as StepUpConfirmForm, E as SignupForm, O as TermsBumpForm, S as RecoveryModeSelectForm, T as SetPasswordForm, _ as MfaCodeForm, a as ConcurrencyLimitForm, b as ProveControlForm, c as EnrollConfirmForm, d as InviteChooseUsernameForm, f as InviteForm, g as ManageMfaForm, h as MagicLinkRequestForm, i as ChangePasswordForm, l as EnrollPickMethodForm, m as MagicLinkConfirmForm, n as AskPhoneForm, o as EmailIdentifierForm, p as LoginCredentialsForm, r as AuthorizeConsentForm, s as EnrollAddressForm, t as AskEmailForm, u as EnrollTotpQrForm, v as PasswordReauthForm, w as Select2faForm, x as ProveControlOtpForm, y as PincodeForm } from "./forms-BUF9oMsE.mjs";
2
+ import { Controller, HandlerPaths, Inherit, Inject, InjectMoostLogger, Injectable, Intercept, MoostInit, Optional, Param, Resolve, TInterceptorPriority, defineAfterInterceptor, defineBeforeInterceptor, defineErrorInterceptor, formatMessage, getMoostMate, registerMessages, useControllerContext, useLogger, useTranslate } from "moost";
3
+ import { AuthCredential, AuthError, RATE_LIMIT_MESSAGES, RateLimitStoreMemory, RateLimitStoreMemory as RateLimitStoreMemory$1, RateLimiter, RateLimiter as RateLimiter$1, generateMagicLinkToken, generateOpaqueToken, parseRateLimitRule, pickGoverning } from "@aooth/auth";
4
+ import { current, defineWook, eventTypeKey, key, tryGetCurrent, useLocale } from "@wooksjs/event-core";
5
5
  import { HttpError, resolveForwarded, useAuthorization, useCookies, useHeaders, useRequest, useResponse, useUrlParams } from "@wooksjs/event-http";
6
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
7
+ import { useBody } from "@wooksjs/http-body";
6
8
  import { ArbacAction, ArbacResource, getArbacMate, useArbac } from "@aooth/arbac-moost";
7
- import { FederatedIdentityStore, SEEN_DEVICES_DEFAULT_CAP, UserAuthError, UserService, generateMfaCode, generateTotpSecret, generateTotpUri, maskEmail, maskPhone, pickDefinedProfile, verifyTotpCode } from "@aooth/user";
9
+ import { FederatedIdentityStore, PASSWORD_POLICY_MESSAGES, SEEN_DEVICES_DEFAULT_CAP, USER_AUTH_ERROR_MESSAGES, UserAuthError, UserService, generateMfaCode, generateTotpSecret, generateTotpUri, maskEmail, maskPhone, pickDefinedProfile, verifyTotpCode } from "@aooth/user";
8
10
  import { Body, Delete, Get, HttpError as HttpError$1, Post, Query } from "@moostjs/event-http";
9
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
10
11
  import { createAsHttpOutlet, finishWf, handleAsOutletRequest, useAtscriptWf } from "@atscript/moost-wf";
11
- import { EncapsulatedStateStrategy, MoostWf, Step, StepRetriableError, StepTTL, Workflow, WorkflowParam, WorkflowSchema, createEmailOutlet, outlet, outletEmail, swapStrategy, useWfFinished, useWfState } from "@moostjs/event-wf";
12
+ import { EncapsulatedStateStrategy, HandleStateStrategy, MoostWf, Step, StepRetriableError, StepTTL, WfStateStoreMemory, Workflow, WorkflowParam, WorkflowSchema, createEmailOutlet, outlet, outletEmail, swapStrategy, useWfFinished, useWfState } from "@moostjs/event-wf";
12
13
  import { FederatedLoginService, OAuthError, OAuthProviderRegistry, generateRandomState, pkceChallengeFor } from "@aooth/idp";
13
14
  import { ClientRegistrationError, DynamicClientRegistration, NoopOidcClaimsResolver, buildAuthorizationServerMetadata, buildAuthorizationServerMetadata as buildAuthorizationServerMetadata$1, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, canonicalizeIssuer as canonicalizeIssuer$1, tokenPolicyToIssueOptions } from "@aooth/auth/authz";
14
15
  // \0@oxc-project+runtime@0.155.0/helpers/esm/decorate.js
@@ -95,6 +96,102 @@ function resolveAuthOptions(opts = {}) {
95
96
  exposeTokensInBody: opts.exposeTokensInBody ?? !enableCookie
96
97
  };
97
98
  }
99
+ // src/http-messages.ts
100
+ /**
101
+ * Code-keyed English templates of the `HttpError`s auth-moost raises outside
102
+ * the auth workflow (guard, controllers, `useAuth()`, the workflow trigger).
103
+ * Each error body carries the `code` and its `params`;
104
+ * `MoostHttp` translates it by code with the moost translator
105
+ * (`translateErrorBody`). Registered with `registerMessages` on import.
106
+ *
107
+ * The workflow's own texts are in `AOOTH_MESSAGES`; the rate limiter's 429
108
+ * (`RATE_LIMITED`) template is `RATE_LIMIT_MESSAGES` from `@aooth/auth`.
109
+ */
110
+ const AOOTH_HTTP_MESSAGES = {
111
+ /** 401 — the guard found no credential on a protected route. */
112
+ AOOTH_AUTH_REQUIRED: "Unauthorized",
113
+ /** 401 — the guard's credential is invalid, expired or revoked. */
114
+ AOOTH_CREDENTIAL_INVALID: "Invalid credential",
115
+ /** 401 — `useAuth().getUserId()` and `AuthController` routes without a signed-in user. */
116
+ AOOTH_NOT_AUTHENTICATED: "Not authenticated",
117
+ /** 401 — "log out other sessions" without a current session. */
118
+ NO_CURRENT_SESSION: "No current session to keep",
119
+ /** 401 — `POST /auth/refresh` without a refresh token. */
120
+ MISSING_REFRESH_TOKEN: "Missing refresh token",
121
+ /** 401 — `POST /auth/refresh` with an unknown, expired or reused refresh token. */
122
+ INVALID_REFRESH_TOKEN: "Invalid refresh token",
123
+ /** 400 — `DELETE /auth/sessions` without `?others=true`. */
124
+ LOGOUT_OTHERS_REQUIRED: "Pass ?others=true to log out other sessions",
125
+ /** 404 — `GET /auth/invite/post-redemption` for an unknown or still pending invite. */
126
+ INVITE_NOT_FOUND: "Invite not found",
127
+ /** 400 — `GET /auth/invite/post-redemption` without `uid`. */
128
+ AOOTH_MISSING_UID: "Missing uid query parameter",
129
+ /** 404 — unlinking an identity the user does not have. */
130
+ LINKED_IDENTITY_NOT_FOUND: "Linked identity not found",
131
+ /** 409 — unlinking the user's only sign-in method. */
132
+ LAST_SIGN_IN_METHOD: "Cannot remove your only sign-in method. Set a password first, or link another provider.",
133
+ /** 404 — unlinking an identity of an unconfigured provider. Params: `provider`. */
134
+ AOOTH_UNKNOWN_PROVIDER: "Unknown provider '{provider}'",
135
+ /** 429 — the one-time codes of this account or address failed too often; answered to every code send and check until the window passes. */
136
+ AOOTH_CODE_LIMIT_REACHED: "Too many code attempts. Try again later.",
137
+ /** 403 — the workflow trigger refused a workflow outside its allow list. Params: `workflow`. */
138
+ AOOTH_WORKFLOW_NOT_ALLOWED: "Workflow '{workflow}' is not allowed"
139
+ };
140
+ registerMessages(AOOTH_HTTP_MESSAGES);
141
+ /** An `HttpError` with `code`, `params` and the code's English text. */
142
+ function aoothHttpError(status, code, params) {
143
+ return codedHttpError(status, code, formatMessage(AOOTH_HTTP_MESSAGES[code], params), params);
144
+ }
145
+ /**
146
+ * An `HttpError` whose body carries the message `code` and `params` next to
147
+ * its text, so `MoostHttp` can translate it by code.
148
+ */
149
+ function codedHttpError(status, code, message, params) {
150
+ return new HttpError(status, {
151
+ message,
152
+ code,
153
+ ...params && { params }
154
+ });
155
+ }
156
+ // src/rate-limit/subjects.ts
157
+ /**
158
+ * Internal: a fixed-size, one-way rate-limit subject for a bearer token
159
+ * (`rt:` + 128 bits of its SHA-256) — the raw secret never becomes a counter
160
+ * key in the store.
161
+ */
162
+ function tokenSubject(token) {
163
+ return `rt:${createHash("sha256").update(canonicalToken(token)).digest("base64url").slice(0, 22)}`;
164
+ }
165
+ /**
166
+ * The base64url-canonical form of a token, segment by segment (`.`-separated,
167
+ * as in a JWT): Node's decoder skips stray characters and reads `+/=`, so
168
+ * `tok=`, `tok `, `tok\n` or a `+/` spelling are one bucket, not several.
169
+ */
170
+ function canonicalToken(token) {
171
+ return token.split(".").map((segment) => Buffer.from(segment, "base64url").toString("base64url")).join(".");
172
+ }
173
+ /**
174
+ * Internal: the request body for code that runs before the handler (moost's
175
+ * `@Body()` reuses the parse) — `undefined` when it cannot be parsed.
176
+ */
177
+ async function tryParseBody(ctx = current()) {
178
+ try {
179
+ return await useBody(ctx).parseBody();
180
+ } catch {
181
+ return;
182
+ }
183
+ }
184
+ /**
185
+ * Internal key function of the `aooth.token-refresh` policy on
186
+ * `POST /auth/token`: the `refresh_token` of a `grant_type=refresh_token`
187
+ * request, as a {@link tokenSubject}. Any other request skips the policy.
188
+ * Runs before the auth guard (it needs nothing the guard sets); an unparsable
189
+ * body is no token.
190
+ */
191
+ async function oauthRefreshTokenSubject() {
192
+ const { grant_type: grant, refresh_token: token } = await tryParseBody() ?? {};
193
+ return grant === "refresh_token" && typeof token === "string" && token ? tokenSubject(token) : null;
194
+ }
98
195
  // src/auth.composables.ts
99
196
  const authContextKey = key("auth.context");
100
197
  const authCredentialKey = key("auth.credential");
@@ -152,7 +249,7 @@ const useAuth = defineWook((ctx) => {
152
249
  };
153
250
  const getUserId = () => {
154
251
  const auth = getAuthContext();
155
- if (!auth) throw new HttpError(401, "Not authenticated");
252
+ if (!auth) throw aoothHttpError(401, "AOOTH_NOT_AUTHENTICATED");
156
253
  return auth.userId;
157
254
  };
158
255
  const isAuthenticated = () => getAuthContext() !== null;
@@ -165,7 +262,7 @@ const useAuth = defineWook((ctx) => {
165
262
  const revokeSession = (sessionId) => requireCredential().revokeSession(getUserId(), sessionId);
166
263
  const revokeOtherSessions = () => {
167
264
  const sessionId = getSessionId();
168
- if (!sessionId) throw new HttpError(401, "No current session to keep");
265
+ if (!sessionId) throw aoothHttpError(401, "NO_CURRENT_SESSION");
169
266
  return requireCredential().revokeOtherSessions(getUserId(), sessionId);
170
267
  };
171
268
  let cachedOptions;
@@ -268,6 +365,27 @@ function setAuthContext(ctx, value) {
268
365
  function setAuthCredential(ctx, value) {
269
366
  ctx.set(authCredentialKey, value);
270
367
  }
368
+ /**
369
+ * Internal: the refresh token a request presents — an explicit body
370
+ * `refreshToken` first, else the refresh cookie when the guard enables
371
+ * cookies. Shared by `AuthController.refresh/logout` and the `'refresh-token'`
372
+ * rate-limit subject, so both read the same token.
373
+ */
374
+ function resolveRefreshToken(options, body, ctx = current()) {
375
+ const fromBody = body?.refreshToken;
376
+ if (typeof fromBody === "string") return fromBody;
377
+ if (!options?.enableCookie) return void 0;
378
+ return useCookies(ctx).getCookie(options.refreshCookie.name) ?? void 0;
379
+ }
380
+ /**
381
+ * Internal: {@link resolveRefreshToken} for code that runs before the handler
382
+ * (the rate limiter): parses the body itself (moost's `@Body()` reuses the
383
+ * parse), treats an unparsable body as none, and reads the cookie only once
384
+ * `authGuardInterceptor` has published its options.
385
+ */
386
+ async function readPresentedRefreshToken(ctx = current()) {
387
+ return resolveRefreshToken(ctx.has(authOptionsKey) ? ctx.get(authOptionsKey) : void 0, await tryParseBody(ctx), ctx);
388
+ }
271
389
  // src/auth.route.ts
272
390
  /**
273
391
  * Normalize a router path into a value usable as a cookie `Path` attribute:
@@ -328,7 +446,7 @@ function authGuardInterceptor(opts) {
328
446
  setAuthContext(ctx, null);
329
447
  return;
330
448
  }
331
- throw new HttpError(401, "Unauthorized");
449
+ throw aoothHttpError(401, "AOOTH_AUTH_REQUIRED");
332
450
  }
333
451
  const credential = await cc.instantiate(AuthCredential);
334
452
  setAuthCredential(ctx, credential);
@@ -338,7 +456,7 @@ function authGuardInterceptor(opts) {
338
456
  setAuthContext(ctx, null);
339
457
  return;
340
458
  }
341
- throw new HttpError(401, "Invalid credential");
459
+ throw aoothHttpError(401, "AOOTH_CREDENTIAL_INVALID");
342
460
  }
343
461
  setAuthContext(ctx, authContext);
344
462
  }, TInterceptorPriority.GUARD);
@@ -391,6 +509,8 @@ const UserId = () => Resolve(() => useAuth().getUserId());
391
509
  * evaluated so far), written by `rateLimitInterceptors`.
392
510
  */
393
511
  const rateLimitDecisionKey = key("aooth.rateLimit.decision");
512
+ /** Internal: the installed interceptors' runtime, published on every HTTP event. */
513
+ const rateLimitRuntimeKey = key("aooth.rateLimit.runtime");
394
514
  /** Internal: phases (`pre` / `post`) that already evaluated this event — the double-count guard. */
395
515
  const rateLimitPhasesKey = key("aooth.rateLimit.phases");
396
516
  /**
@@ -423,7 +543,48 @@ function getRateLimitSubject(kind, ctx = current()) {
423
543
  function useRateLimit(ctx = current()) {
424
544
  return { decision: ctx.has(rateLimitDecisionKey) ? ctx.get(rateLimitDecisionKey) : null };
425
545
  }
546
+ // src/rate-limit/registry.ts
547
+ /**
548
+ * Policy ids that `rateLimitInterceptors({ policies })` accepts: every
549
+ * `@RateLimit({ id })` registers its id when it decorates, and aooth's own
550
+ * handler-enforced policies register below. Process-wide.
551
+ */
552
+ const declared = /* @__PURE__ */ new Set();
553
+ /** Internal: record a policy id as re-tunable through `policies`. */
554
+ function declareRateLimitId(id) {
555
+ declared.add(id);
556
+ }
557
+ /** Internal: whether `id` was declared (see {@link declareRateLimitId}). */
558
+ function isDeclaredRateLimitId(id) {
559
+ return declared.has(id);
560
+ }
561
+ /** Internal: every declared id, sorted. */
562
+ function declaredRateLimitIds() {
563
+ return [...declared].toSorted();
564
+ }
565
+ /** Declare a bundled handler-enforced policy: its id and parsed rule. */
566
+ function bundledRateLimit(id, rule) {
567
+ declareRateLimitId(id);
568
+ return {
569
+ id,
570
+ rules: [parseRateLimitRule(rule)]
571
+ };
572
+ }
573
+ /**
574
+ * The bundled per-IP limit on anonymous sends — recovery codes, magic links
575
+ * and signup codes (each request that could send, whether or not it does).
576
+ * Re-tune or switch off with `rateLimitInterceptors({ policies: { "aooth.send": … } })`.
577
+ */
578
+ const SEND_RATE_LIMIT = bundledRateLimit("aooth.send", "20/15m");
579
+ /**
580
+ * The bundled per-account limit on code sends after a first factor — the
581
+ * email/SMS second factor, MFA enrolment and channel checks, the proof code of
582
+ * a federated account link. Keyed by the account, not the IP. Re-tune or
583
+ * switch off with `rateLimitInterceptors({ policies: { "aooth.send-user": … } })`.
584
+ */
585
+ const SEND_USER_RATE_LIMIT = bundledRateLimit("aooth.send-user", "10/1h");
426
586
  // src/rate-limit/interceptor.ts
587
+ registerMessages(RATE_LIMIT_MESSAGES);
427
588
  /**
428
589
  * Global interceptor PAIR enforcing `@RateLimit` metadata (RL.spec.md §5.2)
429
590
  * — register with spread:
@@ -460,6 +621,13 @@ function useRateLimit(ctx = current()) {
460
621
  */
461
622
  function rateLimitInterceptors(opts) {
462
623
  const defaultRules = opts?.rules?.map((r) => parseRateLimitRule(r));
624
+ const overrides = /* @__PURE__ */ new Map();
625
+ for (const [id, value] of Object.entries(opts?.policies ?? {})) {
626
+ if (!isDeclaredRateLimitId(id)) throw new Error(`rateLimitInterceptors: unknown policy id "${id}" in policies — known ids: ${declaredRateLimitIds().join(", ")}. Give a @RateLimit an { id } to re-tune it here (declare it before configuring).`);
627
+ const rules = value === false ? false : Array.isArray(value) ? value : [value];
628
+ if (rules !== false && rules.length === 0) throw new Error(`rateLimitInterceptors: policies["${id}"] has no rules — pass false to switch it off`);
629
+ overrides.set(id, rules && rules.map((r) => parseRateLimitRule(r)));
630
+ }
463
631
  const limiter = opts?.limiter ?? new RateLimiter$1();
464
632
  const emitHeaders = opts?.headers ?? true;
465
633
  const trustProxy = opts?.trustProxy ?? false;
@@ -486,15 +654,18 @@ function rateLimitInterceptors(opts) {
486
654
  post: []
487
655
  };
488
656
  for (const [i, policy] of declared.entries()) {
657
+ const scope = policy.options?.id ?? (i === 0 ? baseScope : `${baseScope}#${i}`);
658
+ const rules = effectiveRules(overrides, scope, policy.rules);
659
+ if (!rules) continue;
489
660
  const rawKey = policy.options?.key ?? opts?.key ?? "ip";
490
661
  const keyStrategy = rawKey === "auto" ? "user" : rawKey;
491
662
  const message = policy.options?.message ?? opts?.message;
492
663
  route[typeof keyStrategy === "string" && keyStrategy !== "ip" ? "post" : "pre"].push({
493
- rules: policy.rules,
664
+ rules,
494
665
  keyStrategy,
495
- scope: policy.options?.id ?? (i === 0 ? baseScope : `${baseScope}#${i}`),
666
+ scope,
496
667
  ...message !== void 0 && { defaultMessage: message },
497
- policyHeader: policy.rules.map((p) => `${p.limit};w=${Math.max(1, Math.round(p.window / 1e3))}`).join(", ")
668
+ policyHeader: policyHeader(rules)
498
669
  });
499
670
  }
500
671
  config = route;
@@ -502,9 +673,16 @@ function rateLimitInterceptors(opts) {
502
673
  byMethod.set(method, config);
503
674
  return config;
504
675
  };
676
+ const runtime = {
677
+ limiter,
678
+ overrides,
679
+ trustProxy,
680
+ emitHeaders
681
+ };
505
682
  const evaluate = async (phase) => {
506
683
  const ctx = current();
507
684
  if (ctx.get(eventTypeKey) !== "http") return;
685
+ if (!ctx.has(rateLimitRuntimeKey)) ctx.set(rateLimitRuntimeKey, runtime);
508
686
  const done = ctx.has(rateLimitPhasesKey) ? ctx.get(rateLimitPhasesKey) : [];
509
687
  if (done.includes(phase)) return;
510
688
  const config = resolveRouteConfig(useControllerContext(ctx));
@@ -524,23 +702,7 @@ function rateLimitInterceptors(opts) {
524
702
  if (decisions.length === 0) return;
525
703
  const decision = pickGoverning(decisions, (d) => !d.allowed);
526
704
  ctx.set(rateLimitDecisionKey, decision);
527
- const response = useResponse(ctx);
528
- if (emitHeaders) {
529
- const prior = response.getHeader("ratelimit-policy");
530
- if (typeof prior === "string" && prior) headers.unshift(prior);
531
- response.setHeader("ratelimit-limit", String(decision.limit));
532
- response.setHeader("ratelimit-remaining", String(decision.remaining));
533
- response.setHeader("ratelimit-reset", String(Math.ceil(decision.resetAfterMs / 1e3)));
534
- response.setHeader("ratelimit-policy", headers.join(", "));
535
- }
536
- if (!decision.allowed) {
537
- response.setHeader("retry-after", String(Math.ceil(decision.resetAfterMs / 1e3)));
538
- throw new HttpError(429, {
539
- message: decision.message ?? "Too many requests",
540
- code: decision.code ?? "RATE_LIMITED",
541
- ...decision.params && { params: decision.params }
542
- });
543
- }
705
+ answerDecision(decision, headers, emitHeaders, ctx);
544
706
  };
545
707
  return [defineBeforeInterceptor(() => evaluate("pre"), TInterceptorPriority.BEFORE_GUARD), defineBeforeInterceptor(() => evaluate("post"), TInterceptorPriority.AFTER_GUARD)];
546
708
  }
@@ -549,6 +711,10 @@ async function resolveSubject(strategy, trustProxy, ctx) {
549
711
  if (strategy !== "ip") {
550
712
  const subject = getRateLimitSubject(strategy, ctx);
551
713
  if (subject !== void 0) return subject;
714
+ if (strategy === "refresh-token") {
715
+ const token = await readPresentedRefreshToken(ctx);
716
+ return token === void 0 ? null : tokenSubject(token);
717
+ }
552
718
  const auth = strategy === "user" || strategy === "session" ? useAuth(ctx).getAuthContext() : null;
553
719
  if (strategy === "user" && auth?.userId !== void 0) return `u:${auth.userId}`;
554
720
  if (strategy === "session" && auth?.sessionId !== void 0) return `s:${auth.sessionId}`;
@@ -566,6 +732,62 @@ function clientIp(trustProxy, ctx) {
566
732
  const req = useRequest(ctx);
567
733
  return trustProxy ? resolveForwarded(req.raw, trustOneHop).ip : req.getIp();
568
734
  }
735
+ /**
736
+ * Internal: the client IP of the current HTTP event, derived like the rate
737
+ * limiter does (its `trustProxy` when `rateLimitInterceptors` are installed,
738
+ * else the socket peer / the wooks app's own `trustProxy`). `""` outside an
739
+ * HTTP event.
740
+ */
741
+ function requestClientIp(ctx = tryGetCurrent()) {
742
+ if (!ctx) return "";
743
+ try {
744
+ return clientIp(ctx.has(rateLimitRuntimeKey) && ctx.get(rateLimitRuntimeKey).trustProxy, ctx);
745
+ } catch {
746
+ return "";
747
+ }
748
+ }
749
+ /**
750
+ * Write the decision's `RateLimit-*` headers (with `emitHeaders`) and, when it
751
+ * rejects, `Retry-After` and the coded 429.
752
+ */
753
+ function answerDecision(decision, policyHeaders, emitHeaders, ctx) {
754
+ const response = useResponse(ctx);
755
+ if (emitHeaders) {
756
+ const prior = response.getHeader("ratelimit-policy");
757
+ if (typeof prior === "string" && prior) policyHeaders.unshift(prior);
758
+ response.setHeader("ratelimit-limit", String(decision.limit));
759
+ response.setHeader("ratelimit-remaining", String(decision.remaining));
760
+ response.setHeader("ratelimit-reset", String(Math.ceil(decision.resetAfterMs / 1e3)));
761
+ response.setHeader("ratelimit-policy", policyHeaders.join(", "));
762
+ }
763
+ if (!decision.allowed) {
764
+ response.setHeader("retry-after", String(Math.ceil(decision.resetAfterMs / 1e3)));
765
+ throw codedHttpError(429, decision.code ?? "RATE_LIMITED", decision.message ?? formatMessage(RATE_LIMIT_MESSAGES.RATE_LIMITED, decision.params), decision.params);
766
+ }
767
+ }
768
+ /**
769
+ * Internal: check a bundled policy from inside a handler — per client IP
770
+ * unless `key` names another subject (e.g. `user:<id>`), with the limiter and
771
+ * `policies` overrides of the installed `rateLimitInterceptors` (none
772
+ * installed → nothing is enforced, like any `@RateLimit`). Over the limit it
773
+ * throws the same coded 429 as the interceptors. Used by the auth workflow
774
+ * for code and link sends (`aooth.send`, `aooth.send-user`).
775
+ */
776
+ async function enforceRateLimit(policy, key, ctx = tryGetCurrent()) {
777
+ if (!ctx?.has(rateLimitRuntimeKey)) return;
778
+ const runtime = ctx.get(rateLimitRuntimeKey);
779
+ const rules = effectiveRules(runtime.overrides, policy.id, policy.rules);
780
+ if (!rules) return;
781
+ answerDecision(await runtime.limiter.check(policy.id, key ?? `ip:${clientIp(runtime.trustProxy, ctx)}`, rules), [policyHeader(rules)], runtime.emitHeaders, ctx);
782
+ }
783
+ /** The rules of policy `id` after `policies` overrides — `false` when switched off. */
784
+ function effectiveRules(overrides, id, declared) {
785
+ return overrides.get(id) ?? declared;
786
+ }
787
+ /** The draft `RateLimit-Policy` value of `rules` (`<limit>;w=<seconds>`, comma-joined). */
788
+ function policyHeader(rules) {
789
+ return rules.map((p) => `${p.limit};w=${Math.max(1, Math.round(p.window / 1e3))}`).join(", ");
790
+ }
569
791
  // src/rate-limit/mate.ts
570
792
  function getRateLimitMate() {
571
793
  return getMoostMate();
@@ -580,6 +802,7 @@ function RateLimit(...args) {
580
802
  if (typeof last === "object" && last !== null && !("limit" in last)) options = inputs.pop();
581
803
  if (inputs.length === 0) throw new Error("@RateLimit requires at least one rule (or the literal `false` to opt out)");
582
804
  const rules = inputs.map((r) => parseRateLimitRule(r));
805
+ if (options?.id) declareRateLimitId(options.id);
583
806
  const policy = options ? {
584
807
  rules,
585
808
  options
@@ -641,11 +864,220 @@ function createInviteOutlet() {
641
864
  }
642
865
  };
643
866
  }
867
+ // src/workflow/magic-link-outlet.ts
868
+ /** Name of the outlet `AuthWorkflow` pauses on to send a recovery or sign-in magic link. */
869
+ const MAGIC_LINK_OUTLET = "magic-link";
870
+ /**
871
+ * Name of the state strategy a magic link's pause is persisted under
872
+ * (registered by `WfTriggerProvider`). Its own keyspace makes the trigger mint
873
+ * a fresh handle for the link, and the next pause swaps off it again — so the
874
+ * emailed token is consumed by its first use and never becomes the
875
+ * continuation of the flow.
876
+ */
877
+ const MAGIC_LINK_STRATEGY = "magic-link";
878
+ /** The answer of every magic-link request, sent or not: nothing tells the outcomes apart. */
879
+ const SENT = Object.freeze({
880
+ sent: true,
881
+ outlet: "email"
882
+ });
883
+ /**
884
+ * The `magic-link` outlet (registered by default on `WfTriggerProvider`). The
885
+ * step decides whether a link goes out (`context.deliver`); when it does, the
886
+ * link is handed to the app's `email` outlet (`createAuthEmailOutlet`) with
887
+ * the step's template (`recovery.magicLink` / `login.magicLink`). Known and
888
+ * unknown identifiers get the same answer, and a failed delivery is logged,
889
+ * not reported — the response never says whether an account exists.
890
+ *
891
+ * @param emailOutlet - resolves the app's `email` outlet at delivery time.
892
+ */
893
+ function createMagicLinkOutlet(emailOutlet) {
894
+ return {
895
+ name: MAGIC_LINK_OUTLET,
896
+ tokenDelivery: "out-of-band",
897
+ async deliver(request, token) {
898
+ const email = emailOutlet();
899
+ if (!email) throw new Error("Magic links are sent through the `email` outlet — append createAuthEmailOutlet(...) to WfTriggerProvider.outlets");
900
+ const { deliver, ...context } = request.context ?? {};
901
+ if (deliver === true && request.target) try {
902
+ await email.deliver({
903
+ ...request,
904
+ outlet: "email",
905
+ context
906
+ }, token);
907
+ } catch (err) {
908
+ useLogger("aooth:magic-link").error("magic link delivery failed", err);
909
+ }
910
+ return { response: { ...SENT } };
911
+ }
912
+ };
913
+ }
914
+ // src/workflow/pincode-key.ts
915
+ /** Label of the default wf-state secret, `auth.deriveStateKey(WF_STATE_KEY_LABEL)`. */
916
+ const WF_STATE_KEY_LABEL = "wf-state";
917
+ /**
918
+ * Internal: the key that seals one-time codes held in workflow state (their
919
+ * keyed digests), published on every trigger request by `WfTriggerProvider`.
920
+ */
921
+ const pincodeKeySlot = key("aooth.pincodeKey");
922
+ /**
923
+ * Derive the one-time-code key from a secret — the wf-state secret by default.
924
+ * A separate subkey (HMAC under its own label), never the secret itself, so the
925
+ * code digests and the encapsulated state's AES key never share a key.
926
+ */
927
+ function derivePincodeKey(secret) {
928
+ return createHmac("sha256", secret).update("aooth-pincode").digest();
929
+ }
930
+ /**
931
+ * The one-time-code key of the default wf-state secret — what a default
932
+ * `WfTriggerProvider` publishes, and what `AuthWorkflow.pincodeKey()` uses
933
+ * outside one, so a code minted on either path verifies on the other. Throws
934
+ * `AuthError("INVALID_CONFIG")` when the credential store has no derivable
935
+ * secret (a stateful store): the secret must then be supplied explicitly.
936
+ */
937
+ function defaultPincodeKey(auth) {
938
+ return derivePincodeKey(auth.deriveStateKey(WF_STATE_KEY_LABEL));
939
+ }
940
+ // src/workflow/public-projection.ts
941
+ /**
942
+ * `ctx.public` — the form-facing projection `AuthWorkflow` rebuilds before
943
+ * every pause, in the request's language — is a per-response render value,
944
+ * not workflow state. `WfTriggerProvider` strips it before a paused state is
945
+ * persisted (store-backed and token-backed alike), so the state never carries
946
+ * rendered (translated) text. Only projections built by `AuthWorkflow` are
947
+ * stripped: an app's own `public` context key is left alone.
948
+ */
949
+ const projections = /* @__PURE__ */ new WeakSet();
950
+ /** Marks `projection` as `AuthWorkflow`'s rendered `ctx.public`. */
951
+ function markPublicProjection(projection) {
952
+ projections.add(projection);
953
+ }
954
+ /** `context` without its rendered `public` projection (the same object when there is none). */
955
+ function withoutPublicProjection(context) {
956
+ if (!context || typeof context !== "object") return context;
957
+ const pub = context.public;
958
+ if (!pub || typeof pub !== "object" || !projections.has(pub)) return context;
959
+ const { public: _projection, ...rest } = context;
960
+ return rest;
961
+ }
644
962
  // \0@oxc-project+runtime@0.155.0/helpers/esm/decorateMetadata.js
645
963
  function __decorateMetadata(k, v) {
646
964
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
647
965
  }
648
966
  // src/wf-trigger/provider.ts
967
+ /** Cap of the default (in-memory) magic-link store. */
968
+ const MAGIC_LINK_STORE_MAX_ENTRIES = 1e4;
969
+ /**
970
+ * The default magic-link store: memory, with expired links swept at most once
971
+ * a minute on write, and at most {@link MAGIC_LINK_STORE_MAX_ENTRIES} links —
972
+ * the oldest is dropped first. Links nobody clicks (and requests for unknown
973
+ * identifiers) must not pile up for the life of the process.
974
+ */
975
+ var BoundedWfStateStoreMemory = class extends WfStateStoreMemory {
976
+ maxEntries;
977
+ lastSweep = 0;
978
+ /** The stored handles, oldest first, with their expiry (the base map is private). */
979
+ expiries = /* @__PURE__ */ new Map();
980
+ constructor(maxEntries = MAGIC_LINK_STORE_MAX_ENTRIES) {
981
+ super();
982
+ this.maxEntries = maxEntries;
983
+ }
984
+ async set(handle, state, expiresAt) {
985
+ const now = Date.now();
986
+ if (now - this.lastSweep > 6e4) {
987
+ this.lastSweep = now;
988
+ await this.cleanup();
989
+ for (const [key, expiry] of this.expiries) if (expiry && now > expiry) this.expiries.delete(key);
990
+ }
991
+ this.expiries.delete(handle);
992
+ while (this.expiries.size >= this.maxEntries) {
993
+ const oldest = this.expiries.keys().next().value;
994
+ this.expiries.delete(oldest);
995
+ await super.delete(oldest);
996
+ }
997
+ this.expiries.set(handle, expiresAt);
998
+ return super.set(handle, state, expiresAt);
999
+ }
1000
+ async delete(handle) {
1001
+ this.expiries.delete(handle);
1002
+ return super.delete(handle);
1003
+ }
1004
+ async getAndDelete(handle) {
1005
+ this.expiries.delete(handle);
1006
+ return super.getAndDelete(handle);
1007
+ }
1008
+ };
1009
+ /** Where aooth records, inside a persisted state, which strategy persisted it. */
1010
+ const STRATEGY_TAG = "aoothStrategy";
1011
+ /** Padding aooth adds to encapsulated states (stripped on read). */
1012
+ const PAD_KEY = "aoothPad";
1013
+ /** Encapsulated payloads are padded to a multiple of this many bytes. */
1014
+ const PAD_BUCKET = 256;
1015
+ /** Strategies new enough that every state they hold carries the tag. */
1016
+ const TAG_REQUIRED = /* @__PURE__ */ new Set([MAGIC_LINK_STRATEGY]);
1017
+ /**
1018
+ * Wrap a registered strategy so a state can only be resumed through the
1019
+ * strategy that persisted it: `persist` tags the state with `name`, and
1020
+ * `retrieve` / `consume` refuse (as "not found") a state tagged by another
1021
+ * strategy — e.g. a magic-link entry presented as a `store.` token when both
1022
+ * share one store. A refused state is checked before it is consumed, so the
1023
+ * attempt does not destroy it. States persisted before tagging existed are
1024
+ * accepted, except by strategies that always tag. Encapsulated states are also
1025
+ * padded to a {@link PAD_BUCKET}-byte multiple, so the token's length does not
1026
+ * follow the length of what is inside.
1027
+ */
1028
+ function tagStrategy(name, strategy) {
1029
+ const pad = strategy instanceof EncapsulatedStateStrategy;
1030
+ const accepts = (state) => {
1031
+ if (!state) return false;
1032
+ const tag = state.meta?.[STRATEGY_TAG];
1033
+ return tag === void 0 ? !TAG_REQUIRED.has(name) : tag === name;
1034
+ };
1035
+ const tagged = (state) => {
1036
+ const { [PAD_KEY]: _pad, ...meta } = state.meta ?? {};
1037
+ const out = {
1038
+ ...state,
1039
+ meta: {
1040
+ ...meta,
1041
+ [STRATEGY_TAG]: name
1042
+ }
1043
+ };
1044
+ if (!pad) return out;
1045
+ const size = Buffer.byteLength(JSON.stringify(out)) + 32;
1046
+ const fill = (PAD_BUCKET - size % PAD_BUCKET) % PAD_BUCKET;
1047
+ out.meta[PAD_KEY] = "x".repeat(fill);
1048
+ return out;
1049
+ };
1050
+ const clean = (state) => {
1051
+ const { [PAD_KEY]: _pad, ...meta } = state.meta ?? {};
1052
+ return {
1053
+ ...state,
1054
+ meta
1055
+ };
1056
+ };
1057
+ const wrapped = {
1058
+ persist: (state, options, overrides) => strategy.persist(tagged(state), options, overrides),
1059
+ retrieve: async (token) => {
1060
+ const state = await strategy.retrieve(token);
1061
+ return accepts(state) ? clean(state) : null;
1062
+ },
1063
+ consume: async (token) => {
1064
+ if (!accepts(await strategy.retrieve(token))) return null;
1065
+ const state = await strategy.consume(token);
1066
+ return accepts(state) ? clean(state) : null;
1067
+ }
1068
+ };
1069
+ Object.defineProperty(wrapped, "inner", { value: strategy });
1070
+ if (strategy.persistEntry) wrapped.persistEntry = (state, options, overrides) => strategy.persistEntry(tagged(state), options, overrides);
1071
+ if (strategy.consumeEntry) wrapped.consumeEntry = async (token) => {
1072
+ if (!accepts(await strategy.retrieve(token))) return null;
1073
+ const entry = await strategy.consumeEntry(token);
1074
+ return entry && accepts(entry.state) ? {
1075
+ ...entry,
1076
+ state: clean(entry.state)
1077
+ } : null;
1078
+ };
1079
+ return wrapped;
1080
+ }
649
1081
  const HOOK_NAMES = [
650
1082
  "around",
651
1083
  "beforePersist",
@@ -684,7 +1116,7 @@ function normalizeWfId(id) {
684
1116
  return id.replace(/^\/+/, "");
685
1117
  }
686
1118
  function notAllowed(id) {
687
- return new HttpError(403, `Workflow '${normalizeWfId(id)}' is not allowed`);
1119
+ return aoothHttpError(403, "AOOTH_WORKFLOW_NOT_ALLOWED", { workflow: normalizeWfId(id) });
688
1120
  }
689
1121
  /**
690
1122
  * Wrap a strategy so a resume is checked against the allow list BEFORE the
@@ -727,11 +1159,17 @@ let WfTriggerProvider = class WfTriggerProvider {
727
1159
  wf;
728
1160
  auth;
729
1161
  /**
730
- * Outlets the trigger can pause on: HTTP (forms) and `invite` (the link of
731
- * `AuthWorkflowOpts.inviteDelivery: 'deliver' | 'return-link'`). Append an
732
- * `email` outlet (`createAuthEmailOutlet`) for the default invite delivery.
733
- */
734
- outlets = [createAsHttpOutlet(), createInviteOutlet()];
1162
+ * Outlets the trigger can pause on: HTTP (forms), `invite` (the link of
1163
+ * `AuthWorkflowOpts.inviteDelivery: 'deliver' | 'return-link'`) and
1164
+ * `magic-link` (recovery and sign-in links — it sends through the `email`
1165
+ * outlet). Append an `email` outlet (`createAuthEmailOutlet`) for the default
1166
+ * invite delivery and for magic links.
1167
+ */
1168
+ outlets = [
1169
+ createAsHttpOutlet(),
1170
+ createInviteOutlet(),
1171
+ createMagicLinkOutlet(() => this.outlets.find((o) => o.name === "email"))
1172
+ ];
735
1173
  token = {
736
1174
  read: [
737
1175
  "body",
@@ -755,7 +1193,27 @@ let WfTriggerProvider = class WfTriggerProvider {
755
1193
  * `return deriveWfStateSecret(env.MY_SECRET)`.
756
1194
  */
757
1195
  wfStateSecret() {
758
- return this.auth.deriveStateKey("wf-state");
1196
+ return this.auth.deriveStateKey(WF_STATE_KEY_LABEL);
1197
+ }
1198
+ /**
1199
+ * Secret that keys the digests of one-time codes (recovery, sign-in, signup
1200
+ * and enrolment codes) held in workflow state — the state keeps a keyed
1201
+ * digest of each code, never the code. Default: the wf-state secret, so a
1202
+ * store-backed setup that overrides `wfStateSecret()` needs nothing more.
1203
+ * All instances must agree on it.
1204
+ */
1205
+ pincodeSecret() {
1206
+ return this.wfStateSecret();
1207
+ }
1208
+ cachedPincodeKey;
1209
+ /**
1210
+ * The key of the one-time-code digests this provider publishes on every
1211
+ * request: {@link derivePincodeKey} of {@link pincodeSecret}. With the
1212
+ * default secrets it equals what `AuthWorkflow.pincodeKey()` derives outside
1213
+ * a provider (`defaultPincodeKey`).
1214
+ */
1215
+ pincodeKey() {
1216
+ return this.cachedPincodeKey ??= derivePincodeKey(this.pincodeSecret());
759
1217
  }
760
1218
  /** TTL (ms) for encapsulated pre-validation tokens. Default: undefined = no TTL (token valid until used), so an idle login form never expires server-side. */
761
1219
  wfStateEncapsulatedTtlMs() {}
@@ -763,6 +1221,18 @@ let WfTriggerProvider = class WfTriggerProvider {
763
1221
  storeStrategy() {
764
1222
  return this.makeEncapsulated();
765
1223
  }
1224
+ /**
1225
+ * Store of the magic-link pauses (recovery and sign-in links). Default: one
1226
+ * in-memory store per provider — single process only. With several
1227
+ * instances, return a shared `WfStateStore` (e.g. the `AsWfStore` of your
1228
+ * wf-state table). The strategy around it is fixed: handles are stored
1229
+ * hashed (a read of the store yields no usable link), each link is consumed
1230
+ * by its first use, and it expires with the link (`magicLinkTtlMs`).
1231
+ */
1232
+ magicLinkStore() {
1233
+ return this.defaultMagicLinkStore ??= new BoundedWfStateStoreMemory();
1234
+ }
1235
+ defaultMagicLinkStore;
766
1236
  makeEncapsulated() {
767
1237
  return new EncapsulatedStateStrategy({
768
1238
  secret: this.wfStateSecret(),
@@ -785,12 +1255,16 @@ let WfTriggerProvider = class WfTriggerProvider {
785
1255
  return {};
786
1256
  }
787
1257
  cachedState;
788
- /** 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. */
1258
+ /** 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. */
789
1259
  stateRegistry() {
790
1260
  if (!this.cachedState) this.cachedState = {
791
1261
  strategies: {
792
- encapsulated: this.makeEncapsulated(),
793
- store: this.storeStrategy()
1262
+ encapsulated: tagStrategy("encapsulated", this.makeEncapsulated()),
1263
+ store: tagStrategy("store", this.storeStrategy()),
1264
+ [MAGIC_LINK_STRATEGY]: tagStrategy(MAGIC_LINK_STRATEGY, new HandleStateStrategy({
1265
+ store: this.magicLinkStore(),
1266
+ hashHandles: true
1267
+ }))
794
1268
  },
795
1269
  default: "encapsulated"
796
1270
  };
@@ -805,6 +1279,7 @@ let WfTriggerProvider = class WfTriggerProvider {
805
1279
  */
806
1280
  async handle(opts = {}) {
807
1281
  const wfApp = this.wf.getWfApp();
1282
+ current().set(pincodeKeySlot, this.pincodeKey());
808
1283
  const allowed = opts.allow && new Set(opts.allow.map(normalizeWfId));
809
1284
  const permits = (schemaId) => !allowed || allowed.has(normalizeWfId(schemaId));
810
1285
  const registry = this.stateRegistry();
@@ -836,6 +1311,11 @@ let WfTriggerProvider = class WfTriggerProvider {
836
1311
  const value = opts[name] ?? base[name];
837
1312
  if (value !== void 0) hooks[name] = value;
838
1313
  }
1314
+ const beforePersist = opts.beforePersist ?? base.beforePersist;
1315
+ hooks.beforePersist = (state, pause) => {
1316
+ state.context = withoutPublicProjection(state.context);
1317
+ return beforePersist?.(state, pause);
1318
+ };
839
1319
  const around = opts.around ?? base.around;
840
1320
  return handleAsOutletRequest({
841
1321
  ...hooks,
@@ -1107,7 +1587,134 @@ let OAuthRuntime = class OAuthRuntime {
1107
1587
  }
1108
1588
  };
1109
1589
  OAuthRuntime = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [typeof OAuthProviderRegistry === "undefined" ? Object : OAuthProviderRegistry, typeof FederatedLoginService === "undefined" ? Object : FederatedLoginService])], OAuthRuntime);
1590
+ // src/workflow/auth-messages.ts
1591
+ /**
1592
+ * Code-keyed catalogue of every user-facing text `AuthWorkflow` produces —
1593
+ * form errors, banners, finish envelopes and button labels. Templates are
1594
+ * English; `{name}` placeholders are filled from the message params.
1595
+ *
1596
+ * Registered with moost's `registerMessages` on import, so a moost translator
1597
+ * (`setTranslator`) translates every code and `$i18n` serves the templates.
1598
+ * Override per app with `AuthWorkflowOpts.messages` (a partial map, or a
1599
+ * function that receives the code and params and returns the text), or
1600
+ * override `AuthWorkflow.msg()`.
1601
+ */
1602
+ const AOOTH_MESSAGES = {
1603
+ INVALID_CREDENTIALS: "Invalid credentials",
1604
+ AOOTH_ACCOUNT_LOCKED: "Account locked, please try again later",
1605
+ INVALID_PASSWORD: "Invalid password",
1606
+ INCORRECT_PASSWORD: "Incorrect password",
1607
+ SESSION_LIMIT_REACHED: "Session limit reached",
1608
+ PASSWORD_CHANGED_SIGN_IN_AGAIN: "Your password was changed. Please sign in again.",
1609
+ AOOTH_INVALID_CODE: "Invalid code",
1610
+ AOOTH_CODE_EXPIRED: "Code expired",
1611
+ AOOTH_TOO_MANY_CODE_ATTEMPTS: "Too many invalid attempts. Please request a new code.",
1612
+ /** Params: `seconds`. */
1613
+ AOOTH_RESEND_WAIT: "Please wait {seconds}s before requesting a new code.",
1614
+ /** Params: `seconds`. */
1615
+ AOOTH_RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code",
1616
+ /** Params: `seconds`, `channel` (`SMS` / `email`). */
1617
+ AOOTH_RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code",
1618
+ TOTP_RESEND_NOT_APPLICABLE: "Resend is not applicable for TOTP",
1619
+ /** HTTP 400 — a TOTP code submitted for an account without TOTP. */
1620
+ TOTP_NOT_CONFIGURED: "No TOTP MFA configured",
1621
+ AOOTH_ADDRESS_REQUIRED: "This field is required",
1622
+ AOOTH_INVALID_EMAIL_ADDRESS: "Enter a valid email address",
1623
+ AOOTH_INVALID_PHONE_NUMBER: "Enter a valid phone number",
1624
+ 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.",
1625
+ 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.",
1626
+ UNKNOWN_MFA_METHOD: "Unknown MFA method",
1627
+ AOOTH_UNKNOWN_METHOD: "Unknown method",
1628
+ AOOTH_METHOD_UNAVAILABLE: "That method isn't available",
1629
+ AOOTH_METHOD_NOT_CHANGEABLE: "That method can't be changed here.",
1630
+ KEEP_ONE_MFA_METHOD: "You must keep at least one two-factor method.",
1631
+ AOOTH_CHOOSE_OPTION: "Choose an option",
1632
+ ALL_MFA_METHODS_SET_UP: "You've already set up every available authentication method.",
1633
+ NO_MFA_CHANGES: "No changes were made to your two-factor methods.",
1634
+ LAST_MFA_METHOD_NOT_REMOVABLE: "You must keep at least one two-factor method, so this one can't be removed.",
1635
+ MFA_METHOD_TOTP: "Authenticator app",
1636
+ MFA_METHOD_EMAIL: "Email code",
1637
+ MFA_METHOD_SMS: "Text-message code",
1638
+ /** Params: `method` (the method's label). */
1639
+ MFA_METHOD_ADDED: "{method} added.",
1640
+ /** Params: `method`. */
1641
+ MFA_METHOD_UPDATED: "{method} updated.",
1642
+ /** Params: `method`. */
1643
+ MFA_METHOD_REMOVED: "{method} removed.",
1644
+ PASSWORDS_DO_NOT_MATCH: "Passwords do not match",
1645
+ PASSWORD_CHANGE_TOO_RECENT: "You changed your password too recently. Please try again later.",
1646
+ PASSWORD_CHANGED: "Your password has been changed.",
1647
+ PASSWORD_UPDATED_REDIRECTING: "Password updated. Redirecting to sign-in…",
1648
+ PASSWORD_UPDATED_STILL_LOCKED: "Password updated, but your account is still locked. Contact an administrator to regain access.",
1649
+ CHANGE_PASSWORD_HEADING: "Change your password",
1650
+ CHANGE_PASSWORD_INTRO: "Enter your current password, then choose a new one.",
1651
+ SET_PASSWORD_EXPIRED_HEADING: "Your password has expired",
1652
+ SET_PASSWORD_EXPIRED_INTRO: "Choose a new password to continue. The previous one is no longer valid.",
1653
+ SET_PASSWORD_RESET_HEADING: "Reset your password",
1654
+ SET_PASSWORD_RESET_INTRO: "Choose a new password for your account.",
1655
+ SET_PASSWORD_INVITE_HEADING: "Welcome — set your password",
1656
+ SET_PASSWORD_INVITE_INTRO: "Choose a password to activate your account.",
1657
+ SET_PASSWORD_INITIAL_HEADING: "Set your initial password",
1658
+ SET_PASSWORD_INITIAL_INTRO: "Your account was created without a password. Choose one to continue.",
1659
+ /** A magic link that cannot be used: expired, of another purpose, or already used up. */
1660
+ AOOTH_MAGIC_LINK_INVALID: "This link is invalid or has expired. Please request a new one.",
1661
+ SIGNUP_DISABLED: "Self-signup is currently disabled.",
1662
+ AOOTH_ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.",
1663
+ AOOTH_ACCOUNT_LINKED: "Account linked.",
1664
+ /** HTTP 400 — the SSO alt action named a provider that is not offered. */
1665
+ UNKNOWN_SSO_PROVIDER: "Unknown SSO provider",
1666
+ AOOTH_ACCOUNT_CREATED: "Your account has been created.",
1667
+ AOOTH_INVALID_ROLE: "Invalid role",
1668
+ INVITE_ALREADY_PENDING: "Invite already pending",
1669
+ AOOTH_USER_ALREADY_EXISTS: "User already exists",
1670
+ DUPLICATE_INVITE_REJECTED: "Duplicate invite rejected",
1671
+ INVITE_CANCELLED: "This invite has been cancelled",
1672
+ INVITE_REPLACED: "This invite was replaced by a newer one",
1673
+ INVITE_ALREADY_ACCEPTED: "This invite was already accepted.",
1674
+ CHOOSE_USERNAME_TAKEN: "This username is taken",
1675
+ USERNAME_NOT_ALLOWED: "This username is not allowed",
1676
+ AUTHZ_EXPIRED: "Authorization request expired. Please try again.",
1677
+ AUTHZ_BROWSER_MISMATCH: "This authorization could not be verified for your browser. Please start again.",
1678
+ AUTHZ_FAILED: "Authorization could not be completed. Please start again.",
1679
+ GO_TO_SIGN_IN: "Go to sign-in",
1680
+ BACK_TO_SIGN_IN: "Back to sign-in",
1681
+ REQUEST_NEW_INVITE: "Request a new invite",
1682
+ AOOTH_BACK: "Back",
1683
+ AOOTH_GO_NOW: "Go now"
1684
+ };
1685
+ registerMessages(AOOTH_MESSAGES);
1686
+ /** Fill `{name}` placeholders from `params`; unknown placeholders are kept. */
1687
+ function renderAoothMessage(template, params) {
1688
+ return formatMessage(template, params);
1689
+ }
1690
+ /**
1691
+ * Resolve `code`: `messages` (the app's override, when given), then moost's
1692
+ * translator in the current event's locale (`useTranslate`), then the English
1693
+ * template. Outside an event the translator is skipped.
1694
+ */
1695
+ function resolveAoothMessage(code, params = {}, messages) {
1696
+ if (typeof messages === "function") {
1697
+ const text = messages(code, params);
1698
+ if (text !== void 0) return text;
1699
+ } else if (messages?.[code] !== void 0) return renderAoothMessage(messages[code], params);
1700
+ return translateCode(code, params, renderAoothMessage(AOOTH_MESSAGES[code], params));
1701
+ }
1702
+ /** The current event's locale (`useLocale()`); `undefined` outside an event. */
1703
+ function currentLocale() {
1704
+ const event = tryGetCurrent();
1705
+ return event ? useLocale(event).get() : void 0;
1706
+ }
1707
+ /**
1708
+ * `code` through moost's translator in the current event's locale, else
1709
+ * `english` (the filled English text). Outside an event: `english`.
1710
+ */
1711
+ function translateCode(code, params, english) {
1712
+ const event = tryGetCurrent();
1713
+ return event ? useTranslate(event)(code, params, english) : english;
1714
+ }
1110
1715
  // src/user-errors.ts
1716
+ registerMessages(PASSWORD_POLICY_MESSAGES);
1717
+ registerMessages(USER_AUTH_ERROR_MESSAGES);
1111
1718
  const STATUS = {
1112
1719
  NOT_FOUND: 404,
1113
1720
  ALREADY_EXISTS: 409,
@@ -1134,19 +1741,20 @@ function userAuthErrorField(type) {
1134
1741
  }
1135
1742
  /**
1136
1743
  * Map a `UserAuthError` (thrown by `UserService`) to an `HttpError` whose body
1137
- * carries `code` (the error type), the message and — for password errors —
1138
- * the form `field` it belongs to (named as in the bundled password forms):
1744
+ * carries `code` (the error's message code, `err.code`), the message and — for
1745
+ * password errors — the form `field` it belongs to (named as in the bundled
1746
+ * password forms):
1139
1747
  *
1140
- * | type | status | field |
1141
- * |---|---|---|
1142
- * | `NOT_FOUND` | 404 | |
1143
- * | `ALREADY_EXISTS`, `CAS_EXHAUSTED` | 409 | |
1144
- * | `INVALID_CREDENTIALS` | 400 | `currentPassword` |
1145
- * | `PASSWORD_IN_HISTORY` | 400 | `newPassword` |
1146
- * | `POLICY_VIOLATION` (+ `params.policies`) | 422 | `newPassword` |
1147
- * | `PASSWORDS_MISMATCH` | 400 | `confirmPassword` |
1148
- * | `MFA_INVALID`, `MFA_NOT_CONFIGURED` | 400 | |
1149
- * | `INACTIVE`, `LOCKED`, `MFA_REQUIRED` | 403 | |
1748
+ * | type | code | status | field |
1749
+ * |---|---|---|---|
1750
+ * | `NOT_FOUND` | `NOT_FOUND` | 404 | |
1751
+ * | `ALREADY_EXISTS`, `CAS_EXHAUSTED` | `AOOTH_USER_ALREADY_EXISTS`, `AOOTH_USER_CAS_EXHAUSTED` | 409 | |
1752
+ * | `INVALID_CREDENTIALS` | `INVALID_CREDENTIALS` | 400 | `currentPassword` |
1753
+ * | `PASSWORD_IN_HISTORY` | `PASSWORD_IN_HISTORY` | 400 | `newPassword` |
1754
+ * | `POLICY_VIOLATION` (+ `params.policies`) | `AOOTH_USER_POLICY_VIOLATION` | 422 | `newPassword` |
1755
+ * | `PASSWORDS_MISMATCH` | `PASSWORDS_MISMATCH` | 400 | `confirmPassword` |
1756
+ * | `MFA_INVALID`, `MFA_NOT_CONFIGURED` | same as type | 400 | |
1757
+ * | `INACTIVE`, `LOCKED`, `MFA_REQUIRED` | `AOOTH_USER_INACTIVE`, `AOOTH_USER_LOCKED`, `MFA_REQUIRED` | 403 | |
1150
1758
  *
1151
1759
  * For routes such as an admin "set password" endpoint. Do not use it on a
1152
1760
  * sign-in endpoint: distinct answers for unknown, inactive and locked accounts
@@ -1157,13 +1765,45 @@ function userAuthErrorToHttp(err) {
1157
1765
  const field = userAuthErrorField(err.type);
1158
1766
  const policies = err.type === "POLICY_VIOLATION" ? err.details?.policies : void 0;
1159
1767
  return new HttpError(STATUS[err.type], {
1160
- message: err.message,
1161
- code: err.type,
1768
+ message: userAuthErrorText(err),
1769
+ code: err.code,
1162
1770
  ...policies !== void 0 && { params: { policies } },
1163
1771
  ...field && { field }
1164
1772
  });
1165
1773
  }
1166
1774
  /**
1775
+ * A policy's texts in the request's locale (moost translator): `errorMessage`
1776
+ * by its `code`, `description` by `${code}_DESCRIPTION` — by the text itself
1777
+ * when the policy has no code. Unchanged without a translation.
1778
+ */
1779
+ function translatePolicyTexts(policy) {
1780
+ const { code, params, description, errorMessage } = policy;
1781
+ const out = { ...policy };
1782
+ if (description) out.description = translateCode(code ? `${code}_DESCRIPTION` : description, params, description);
1783
+ if (errorMessage) out.errorMessage = translatePolicyError(policy);
1784
+ return out;
1785
+ }
1786
+ /** A policy's `errorMessage` in the request's locale, by its `code` (or the text itself). */
1787
+ function translatePolicyError({ code, params, errorMessage }) {
1788
+ return errorMessage && translateCode(code ?? errorMessage, params, errorMessage);
1789
+ }
1790
+ /**
1791
+ * A `UserAuthError`'s text in the request's locale: a `POLICY_VIOLATION` lists
1792
+ * its failed policies' translated `errorMessage`s (`; `-joined, like the
1793
+ * English message) when at least one of them has a translation; otherwise —
1794
+ * and for any other type — the error is translated by its code (`err.code`),
1795
+ * its own message the fallback.
1796
+ */
1797
+ function userAuthErrorText(err) {
1798
+ const policies = err.type === "POLICY_VIOLATION" ? err.details?.policies : void 0;
1799
+ const failed = Array.isArray(policies) ? policies.filter((p) => p?.passed === false) : [];
1800
+ if (failed.length > 0 && failed.every((p) => typeof p.errorMessage === "string")) {
1801
+ const texts = failed.map((p) => translatePolicyError(p));
1802
+ if (texts.some((text, i) => text !== failed[i].errorMessage)) return texts.join("; ");
1803
+ }
1804
+ return translateCode(err.code, void 0, err.message);
1805
+ }
1806
+ /**
1167
1807
  * Error interceptor answering every `UserAuthError` a handler throws with
1168
1808
  * {@link userAuthErrorToHttp}; other errors pass through. Attach it per
1169
1809
  * controller (or per handler) where `UserService` errors should become 4xx
@@ -1183,78 +1823,6 @@ function userAuthErrorToHttp(err) {
1183
1823
  const userAuthErrorInterceptor = defineErrorInterceptor((error, reply) => {
1184
1824
  if (error instanceof UserAuthError) reply(userAuthErrorToHttp(error));
1185
1825
  }, TInterceptorPriority.CATCH_ERROR);
1186
- // src/workflow/auth-messages.ts
1187
- /**
1188
- * Code-keyed catalogue of every user-facing text `AuthWorkflow` produces —
1189
- * form errors, banners, finish envelopes and button labels. Templates are
1190
- * English; `{name}` placeholders are filled from the message params.
1191
- *
1192
- * Override per app with `AuthWorkflowOpts.messages` (a partial map, or a
1193
- * function that receives the code and params and returns the text — e.g. a
1194
- * lookup in your own i18n library), or override `AuthWorkflow.msg()`.
1195
- */
1196
- const AOOTH_MESSAGES = {
1197
- INVALID_CREDENTIALS: "Invalid credentials",
1198
- ACCOUNT_LOCKED: "Account locked, please try again later",
1199
- INVALID_PASSWORD: "Invalid password",
1200
- INCORRECT_PASSWORD: "Incorrect password",
1201
- SESSION_LIMIT_REACHED: "Session limit reached",
1202
- PASSWORD_CHANGED_SIGN_IN_AGAIN: "Your password was changed. Please sign in again.",
1203
- INVALID_CODE: "Invalid code",
1204
- /** Params: `seconds`. */
1205
- RESEND_WAIT: "Please wait {seconds}s before requesting a new code.",
1206
- /** Params: `seconds`. */
1207
- RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code",
1208
- /** Params: `seconds`, `channel` (`SMS` / `email`). */
1209
- RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code",
1210
- TOTP_RESEND_NOT_APPLICABLE: "Resend is not applicable for TOTP",
1211
- UNKNOWN_MFA_METHOD: "Unknown MFA method",
1212
- UNKNOWN_METHOD: "Unknown method",
1213
- METHOD_UNAVAILABLE: "That method isn't available",
1214
- METHOD_NOT_CHANGEABLE: "That method can't be changed here.",
1215
- KEEP_ONE_MFA_METHOD: "You must keep at least one two-factor method.",
1216
- CHOOSE_OPTION: "Choose an option",
1217
- ALL_MFA_METHODS_SET_UP: "You've already set up every available authentication method.",
1218
- NO_MFA_CHANGES: "No changes were made to your two-factor methods.",
1219
- PASSWORDS_DO_NOT_MATCH: "Passwords do not match",
1220
- PASSWORD_CHANGE_TOO_RECENT: "You changed your password too recently. Please try again later.",
1221
- PASSWORD_CHANGED: "Your password has been changed.",
1222
- PASSWORD_UPDATED_REDIRECTING: "Password updated. Redirecting to sign-in…",
1223
- PASSWORD_UPDATED_STILL_LOCKED: "Password updated, but your account is still locked. Contact an administrator to regain access.",
1224
- RECOVERY_INSTRUCTIONS_SENT: "If an account exists, you will receive instructions.",
1225
- SIGNUP_DISABLED: "Self-signup is currently disabled.",
1226
- ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.",
1227
- ACCOUNT_LINKED: "Account linked.",
1228
- INVALID_ROLE: "Invalid role",
1229
- INVITE_ALREADY_PENDING: "Invite already pending",
1230
- USER_ALREADY_EXISTS: "User already exists",
1231
- DUPLICATE_INVITE_REJECTED: "Duplicate invite rejected",
1232
- INVITE_CANCELLED: "This invite has been cancelled",
1233
- INVITE_REPLACED: "This invite was replaced by a newer one",
1234
- INVITE_ALREADY_ACCEPTED: "This invite was already accepted.",
1235
- CHOOSE_USERNAME_TAKEN: "This username is taken",
1236
- USERNAME_NOT_ALLOWED: "This username is not allowed",
1237
- AUTHZ_EXPIRED: "Authorization request expired. Please try again.",
1238
- AUTHZ_BROWSER_MISMATCH: "This authorization could not be verified for your browser. Please start again.",
1239
- AUTHZ_FAILED: "Authorization could not be completed. Please start again.",
1240
- GO_TO_SIGN_IN: "Go to sign-in",
1241
- BACK_TO_SIGN_IN: "Back to sign-in",
1242
- REQUEST_NEW_INVITE: "Request a new invite",
1243
- BACK: "Back",
1244
- GO_NOW: "Go now"
1245
- };
1246
- /** Fill `{name}` placeholders from `params`; unknown placeholders are kept. */
1247
- function renderAoothMessage(template, params = {}) {
1248
- return template.replace(/\{(\w+)\}/g, (whole, name) => Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : whole);
1249
- }
1250
- /** Resolve `code` through `messages` (when given), falling back to the English template. */
1251
- function resolveAoothMessage(code, params = {}, messages) {
1252
- if (typeof messages === "function") {
1253
- const text = messages(code, params);
1254
- if (text !== void 0) return text;
1255
- } else if (messages?.[code] !== void 0) return renderAoothMessage(messages[code], params);
1256
- return renderAoothMessage(AOOTH_MESSAGES[code], params);
1257
- }
1258
1826
  // src/workflow/auth-workflow.schemas.ts
1259
1827
  /**
1260
1828
  * Canonical OTP send-then-check pair. Used by:
@@ -1267,7 +1835,7 @@ function resolveAoothMessage(code, params = {}, messages) {
1267
1835
  */
1268
1836
  const pincodeSendCheckPair = [{
1269
1837
  id: "pincode-send",
1270
- condition: (ctx) => !ctx.pin
1838
+ condition: (ctx) => !ctx.pinNonce
1271
1839
  }, {
1272
1840
  id: "pincode-check",
1273
1841
  condition: (ctx) => !ctx.aborted
@@ -1303,7 +1871,7 @@ const enrollTrioSteps = [
1303
1871
  },
1304
1872
  {
1305
1873
  id: "enroll-send",
1306
- condition: (ctx) => (ctx.mfaEnroll?.method === "sms" || ctx.mfaEnroll?.method === "email") && !!ctx.mfaEnroll.address && !ctx.mfaEnroll.done && !ctx.mfaEnroll.preConfirmed && !ctx.pin
1874
+ condition: (ctx) => (ctx.mfaEnroll?.method === "sms" || ctx.mfaEnroll?.method === "email") && !!ctx.mfaEnroll.address && !ctx.mfaEnroll.done && !ctx.mfaEnroll.preConfirmed && !ctx.pinNonce
1307
1875
  },
1308
1876
  {
1309
1877
  id: "enroll-confirm",
@@ -1357,7 +1925,7 @@ const mfaStepUpLoop = [{
1357
1925
  },
1358
1926
  {
1359
1927
  id: "manage-stepup-confirm",
1360
- condition: (ctx) => !ctx.otp?.verified && (ctx.mfa?.method === "sms" || ctx.mfa?.method === "email") && !ctx.addMfa?.stepUpConfirmed && !ctx.pin
1928
+ condition: (ctx) => !ctx.otp?.verified && (ctx.mfa?.method === "sms" || ctx.mfa?.method === "email") && !ctx.addMfa?.stepUpConfirmed && !ctx.pinNonce
1361
1929
  },
1362
1930
  { break: (ctx) => !!ctx.aborted },
1363
1931
  {
@@ -1449,6 +2017,12 @@ const consentsPersistTailSchema = [{
1449
2017
  * schemas would no-op every step.
1450
2018
  */
1451
2019
  var _AuthWorkflow;
2020
+ const SET_PASSWORD_COPY_KEYS = [
2021
+ "heading",
2022
+ "intro",
2023
+ "headingCode",
2024
+ "introCode"
2025
+ ];
1452
2026
  /**
1453
2027
  * Default form schemas — the bundled `forms.as` models the workflow's
1454
2028
  * `useAtscriptWf()` callers resolve to. Consumers can override any field
@@ -1483,6 +2057,9 @@ const DEFAULT_FORMS = {
1483
2057
  termsBump: TermsBumpForm,
1484
2058
  concurrencyLimit: ConcurrencyLimitForm,
1485
2059
  recoveryPincode: PincodeForm,
2060
+ recoveryModeSelect: RecoveryModeSelectForm,
2061
+ magicLinkRequest: MagicLinkRequestForm,
2062
+ magicLinkConfirm: MagicLinkConfirmForm,
1486
2063
  signup: SignupForm,
1487
2064
  authzConsent: AuthorizeConsentForm
1488
2065
  };
@@ -1494,19 +2071,56 @@ const warnedOnce = {
1494
2071
  openInviteWhitelist: false,
1495
2072
  crossIssuerReuse: false
1496
2073
  };
2074
+ /** What `pincode-check` compares a recovery code against when there is no account: matches no code. */
2075
+ const NO_CODE = "\0";
2076
+ /** Default name of the cookie that binds a sign-in link to its browser (opt-in). */
2077
+ const MAGIC_LINK_BROWSER_COOKIE = "aooth_magic_link";
2078
+ /** The id an unknown identifier's recovery reads, so its lookups match a known one's. */
2079
+ const UNKNOWN_ACCOUNT_ID = "00000000-0000-4000-8000-000000000000";
2080
+ /** Key prefixes of a code's attempt counter and single-use marker (in `lockoutShadowStore`). */
2081
+ const PIN_ATTEMPT_PREFIX = "code-attempts:";
2082
+ const PIN_SPENT_PREFIX = "code-spent:";
2083
+ /** Key prefixes of a code destination's resend cooldown and failed-code budget. */
2084
+ const CODE_SEND_PREFIX = "code-send:";
2085
+ const CODE_FAIL_PREFIX = "code-fail:";
2086
+ /** Key prefix of a magic link's resend cooldown. */
2087
+ const MAGIC_LINK_SEND_PREFIX = "magic-link:";
2088
+ /** SHA-256 of `value`, base64url — fixed-size store keys and binding hashes. */
2089
+ function sha256url(value) {
2090
+ return createHash("sha256").update(value).digest("base64url");
2091
+ }
2092
+ /** How long a code's counters outlive the code. */
2093
+ const PIN_COUNTER_GRACE_MS = 6e4;
1497
2094
  /** Sliding lifetime of a shadow failure counter (and of a shadow "permanent" lock). */
1498
2095
  const SHADOW_TTL_MS = 2592e6;
1499
2096
  /** Key prefix of an active shadow lock (kept longest by the default store). */
1500
2097
  const SHADOW_LOCK_PREFIX = "shadow-lock:";
1501
2098
  /** Cap of the default (process-wide, in-memory) shadow-lockout store. */
1502
2099
  const SHADOW_STORE_MAX_ENTRIES = 5e4;
2100
+ /**
2101
+ * Keys a flood of fresh failure counters must not push out of the default
2102
+ * store: ACTIVE shadow locks (evicting one would unmask exactly the handles an
2103
+ * attacker is probing), and the code and magic-link counters (evicting one
2104
+ * would restore a code's attempt budget, or lift a resend wait).
2105
+ */
2106
+ const EVICT_LAST_PREFIXES = [
2107
+ SHADOW_LOCK_PREFIX,
2108
+ PIN_ATTEMPT_PREFIX,
2109
+ PIN_SPENT_PREFIX,
2110
+ CODE_SEND_PREFIX,
2111
+ CODE_FAIL_PREFIX,
2112
+ MAGIC_LINK_SEND_PREFIX
2113
+ ];
2114
+ /** Internal: a memory `lockoutShadowStore` as the default one is built (bounded, protected keys evicted last). */
2115
+ function createShadowStore(maxEntries = SHADOW_STORE_MAX_ENTRIES) {
2116
+ return new RateLimitStoreMemory$1({
2117
+ maxEntries,
2118
+ evictLast: (key) => EVICT_LAST_PREFIXES.some((prefix) => key.startsWith(prefix))
2119
+ });
2120
+ }
1503
2121
  let sharedShadowStore;
1504
2122
  function defaultShadowStore() {
1505
- sharedShadowStore ??= new RateLimitStoreMemory$1({
1506
- maxEntries: SHADOW_STORE_MAX_ENTRIES,
1507
- evictLast: (key) => key.startsWith(SHADOW_LOCK_PREFIX)
1508
- });
1509
- return sharedShadowStore;
2123
+ return sharedShadowStore ??= createShadowStore();
1510
2124
  }
1511
2125
  function mergeAuthWorkflowOpts(opts) {
1512
2126
  const deviceTrust = {
@@ -1530,9 +2144,14 @@ function mergeAuthWorkflowOpts(opts) {
1530
2144
  pincodeLength: opts.mfa?.pincodeLength ?? 6,
1531
2145
  pincodeTtlMs: opts.mfa?.pincodeTtlMs ?? 3e5,
1532
2146
  pincodeResendTimeoutMs: opts.mfa?.pincodeResendTimeoutMs ?? 6e4,
1533
- pincodeMaxAttempts: opts.mfa?.pincodeMaxAttempts ?? 5
2147
+ pincodeMaxAttempts: opts.mfa?.pincodeMaxAttempts ?? 5,
2148
+ pincodeMaxFailures: opts.mfa?.pincodeMaxFailures ?? 10,
2149
+ pincodeFailureWindowMs: opts.mfa?.pincodeFailureWindowMs ?? 36e5,
2150
+ pincodeMaxFailuresGlobal: opts.mfa?.pincodeMaxFailuresGlobal ?? 100,
2151
+ pincodeMaxSendsGlobal: opts.mfa?.pincodeMaxSendsGlobal ?? 10
1534
2152
  },
1535
2153
  recoveryStateTtlMs: opts.recoveryStateTtlMs ?? 36e5,
2154
+ magicLinkTtlMs: opts.magicLinkTtlMs ?? 9e5,
1536
2155
  loginUrl: opts.loginUrl ?? "/login",
1537
2156
  totpIssuer: opts.totpIssuer ?? "aooth",
1538
2157
  deviceTrust,
@@ -1713,6 +2332,12 @@ function readUsernameQueryParam() {
1713
2332
  return;
1714
2333
  }
1715
2334
  }
2335
+ /** The message code of each MFA method's label. */
2336
+ const MFA_METHOD_LABEL_CODES = {
2337
+ totp: "MFA_METHOD_TOTP",
2338
+ email: "MFA_METHOD_EMAIL",
2339
+ sms: "MFA_METHOD_SMS"
2340
+ };
1716
2341
  /**
1717
2342
  * Subset-copy of `src` keyed by `keys`, omitting any key whose value is
1718
2343
  * `undefined`. Returns `undefined` when no key carries a value — keeps
@@ -1735,8 +2360,8 @@ function pickDefined(src, keys) {
1735
2360
  * Thrown by `recoveryPincodeTarget`'s registered (M2) branch when the confirmed
1736
2361
  * recovery method that `request`'s guard saw has VANISHED before send time
1737
2362
  * (deleted between the two row loads — the request→send TOCTOU). `pincode-send`
1738
- * catches it and degrades to the generic anti-enumeration finish instead of
1739
- * surfacing a distinguishable 500, so a known account can never become
2363
+ * catches it and degrades to the ghost OTP run instead of surfacing a
2364
+ * distinguishable 500, so a known account can never become
1740
2365
  * distinguishable from an unknown one on a resend. Recovery-only; the MFA
1741
2366
  * challenge branch keeps its own `HttpError(500)` (that path is post-password,
1742
2367
  * so enumeration is moot there).
@@ -1769,21 +2394,20 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
1769
2394
  this.consentStore = consentStore;
1770
2395
  }
1771
2396
  /**
1772
- * Resolve a user-facing text by code (`AOOTH_MESSAGES`) through
1773
- * `opts.messages`. Every form error, banner, finish message and button label
1774
- * the workflow produces goes through here — override for full control
1775
- * (e.g. to call your i18n library with the request's locale).
2397
+ * Resolve a user-facing text by code (`AOOTH_MESSAGES`): `opts.messages`
2398
+ * first, then moost's translator in the request's locale, then the English
2399
+ * template. Every form error, banner, finish message and button label the
2400
+ * workflow produces goes through here — override for full control.
1776
2401
  */
1777
2402
  msg(code, params) {
1778
2403
  return resolveAoothMessage(code, params, this.opts.messages);
1779
2404
  }
1780
- /** An `HttpError` whose body carries the message `code` next to its (resolved) text. */
1781
- httpError(status, code) {
1782
- return new HttpError$1(status, {
1783
- message: this.msg(code),
1784
- statusCode: status,
1785
- code
1786
- });
2405
+ /**
2406
+ * An `HttpError` whose body carries the message `code` and `params` next to
2407
+ * its (resolved) text, so an error-body translator can translate it by code.
2408
+ */
2409
+ httpError(status, code, params) {
2410
+ return codedHttpError(status, code, this.msg(code, params), params);
1787
2411
  }
1788
2412
  /**
1789
2413
  * Unified outbound dispatch hook for direct synchronous deliveries
@@ -1795,6 +2419,14 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
1795
2419
  * sync-friendly: the default `void` preserves the engine's sync fast path.
1796
2420
  */
1797
2421
  deliver(_payload) {}
2422
+ /** {@link deliver} with the request's locale stamped on the payload. */
2423
+ dispatch(payload) {
2424
+ const locale = currentLocale();
2425
+ return this.deliver(locale === void 0 ? payload : {
2426
+ ...payload,
2427
+ locale
2428
+ });
2429
+ }
1798
2430
  /**
1799
2431
  * The blessed one-call alert path for risk overrides — emit a
1800
2432
  * `security-alert` delivery (e.g. from an impossible-travel
@@ -1807,7 +2439,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
1807
2439
  async sendSecurityAlert(ctx, reason, context) {
1808
2440
  const recipient = ctx.notice?.email;
1809
2441
  if (!recipient) return;
1810
- await this.deliver({
2442
+ await this.dispatch({
1811
2443
  kind: "security-alert",
1812
2444
  channel: "email",
1813
2445
  recipient,
@@ -2068,6 +2700,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2068
2700
  });
2069
2701
  }
2070
2702
  /**
2703
+ * How recovery proves the inbox: `'otp'` (default — a one-time code),
2704
+ * `'magicLink'` (a single-use link, sent through the email outlet as
2705
+ * `recovery.magicLink`) or `'choice'` (the user picks on
2706
+ * `RecoveryModeSelectForm` after the identifier). Reached from recovery.flow.
2707
+ */
2708
+ resolveRecoveryDeliveryMode(_ctx) {
2709
+ return "otp";
2710
+ }
2711
+ /**
2071
2712
  * Resolve the alternate-credentials policy (forgot-password / signup /
2072
2713
  * magic-link / SSO providers). Reached from login.flow.
2073
2714
  */
@@ -2076,11 +2717,9 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2076
2717
  forgotPassword: true,
2077
2718
  signup: false,
2078
2719
  magicLink: false,
2079
- magicLinkSkipsMfa: false,
2080
2720
  ssoProviders: [],
2081
2721
  recoveryUrl: "/recover",
2082
- signupUrl: "/signup",
2083
- embedRecovery: false
2722
+ signupUrl: "/signup"
2084
2723
  };
2085
2724
  }
2086
2725
  /**
@@ -2331,12 +2970,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2331
2970
  /**
2332
2971
  * Resolve the channel-OTP disclosure copy rendered beneath the email/phone
2333
2972
  * input on `AskEmailForm` / `AskPhoneForm`. Reached from login.flow Phase 3.
2334
- * Default returns a TCPA / PECR / CASL / GDPR-safe English paragraph that is
2973
+ * Default returns a TCPA / PECR / CASL / GDPR-safe paragraph that is
2335
2974
  * GENERIC per channel (no target templated in — the user hasn't submitted
2336
- * yet at ask-time).
2975
+ * yet at ask-time): `OTP_DISCLOSURE_EMAIL` / `OTP_DISCLOSURE_PHONE` in the
2976
+ * request's language. The text is kept in the workflow state as shown and
2977
+ * recorded with the consent (`recordOtpChannelConsent`) — the one text the
2978
+ * state keeps translated, because the record must be what the user saw.
2337
2979
  */
2338
2980
  resolveOtpDisclosure(_ctx, channel) {
2339
- return channel === "phone" ? "By providing your phone number, you consent to receive one-time security codes from us via SMS. Message and data rates may apply." : "By providing your email address, you consent to receive one-time security codes from us via email. Standard email delivery may apply.";
2981
+ return this.msg(channel === "phone" ? "OTP_DISCLOSURE_PHONE" : "OTP_DISCLOSURE_EMAIL");
2340
2982
  }
2341
2983
  /**
2342
2984
  * Resolve whether to require an additional MFA round (risk step-up).
@@ -2367,41 +3009,38 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2367
3009
  * Resolve the invite accept-tail policy. Reached from invite.start accept
2368
3010
  * phase. `loginUrl` defaults to `this.opts.loginUrl`. Note: today's
2369
3011
  * `freshLoginRequired` field is GONE — the auto-login choice is the static
2370
- * `AuthWorkflowOpts.autoLoginOnInvite` boolean (per §2 decision).
3012
+ * `AuthWorkflowOpts.autoLoginOnInvite` boolean (per §2 decision). Return
3013
+ * `confirmationMessage` to replace the default confirmation text
3014
+ * (`AOOTH_ACCOUNT_CREATED`, rendered in the finishing request's language) with your
3015
+ * own, shown as is.
2371
3016
  */
2372
3017
  resolveAccept(_ctx) {
2373
3018
  return {
2374
3019
  alreadyAcceptedRedirectUrl: this.opts.loginUrl,
2375
3020
  loginUrl: this.opts.loginUrl,
2376
- showConfirmation: true,
2377
- confirmationMessage: "Your account has been created."
3021
+ showConfirmation: true
2378
3022
  };
2379
3023
  }
2380
3024
  /**
2381
3025
  * Copy (heading + intro) for the unified set-password screen, staged by
2382
- * `create-password-form` BEFORE the pause. Branches on the resolved
2383
- * `ctx.password.changeReason` (`expired` / `reset`), then invite-accept
2384
- * (`ctx.accept`), then the initial-password fallback. Override to re-brand any
2385
- * phase; return a partial (`{ heading }` only) to change one field and leave
2386
- * the other at whatever an earlier step staged, or `{}` to keep both as-is.
3026
+ * `create-password-form` BEFORE the pause. The default picks message codes
3027
+ * — `SET_PASSWORD_{EXPIRED,RESET,INVITE,INITIAL}_{HEADING,INTRO}` by the
3028
+ * resolved `ctx.password.changeReason` (`expired` / `reset`), then
3029
+ * invite-accept (`ctx.accept`), then the initial-password fallback — which
3030
+ * are rendered through `msg()` in each request's language.
3031
+ *
3032
+ * Override to re-brand any phase: `heading` / `intro` are your own text,
3033
+ * shown as is (they win over the codes); `headingCode` / `introCode` pick
3034
+ * other codes. Return a partial to change one field and leave the other at
3035
+ * whatever an earlier step staged (spread `super`'s result to keep the
3036
+ * default for it), or `{}` to keep both as-is.
2387
3037
  */
2388
3038
  resolveSetPasswordCopy(ctx) {
2389
3039
  const reason = ctx.password?.changeReason;
2390
- if (reason === "expired") return {
2391
- heading: "Your password has expired",
2392
- intro: "Choose a new password to continue. The previous one is no longer valid."
2393
- };
2394
- if (reason === "reset") return {
2395
- heading: "Reset your password",
2396
- intro: "Choose a new password for your account."
2397
- };
2398
- if (ctx.accept) return {
2399
- heading: "Welcome — set your password",
2400
- intro: "Choose a password to activate your account."
2401
- };
3040
+ const phase = reason === "expired" ? "EXPIRED" : reason === "reset" ? "RESET" : ctx.accept ? "INVITE" : "INITIAL";
2402
3041
  return {
2403
- heading: "Set your initial password",
2404
- intro: "Your account was created without a password. Choose one to continue."
3042
+ headingCode: `SET_PASSWORD_${phase}_HEADING`,
3043
+ introCode: `SET_PASSWORD_${phase}_INTRO`
2405
3044
  };
2406
3045
  }
2407
3046
  /**
@@ -2438,6 +3077,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2438
3077
  * set) or from `ctx.email` (recovery path). Loads the user to read the raw
2439
3078
  * method `value` — the `ctx.mfa.enrolledMethods` summary carries only the
2440
3079
  * MASKED form, which is for display, never for delivery.
3080
+ *
3081
+ * In recovery it also runs for an identifier with no account a code can go
3082
+ * to (unknown, inactive), on a copy of `ctx` whose `subject` is the
3083
+ * placeholder `00000000-0000-4000-8000-000000000000` — so every identifier
3084
+ * makes the same calls. Its result (or any error) is discarded there.
2441
3085
  */
2442
3086
  resolvePincodeTarget(ctx) {
2443
3087
  if (ctx.mfa?.method && ctx.mfa.method !== "totp") {
@@ -2469,11 +3113,9 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2469
3113
  * row (`selectRecoveryRegisteredMethod`) and the channel is that method's own
2470
3114
  * kind. The user only typed an account identifier; the destination is a
2471
3115
  * pre-verified channel they already control, so this also can't redirect
2472
- * cross-account. `request`'s M2 guard normally generic-finishes any row with
2473
- * no deliverable method up front; if the method is deleted in the narrow
2474
- * window between that guard and this send (e.g. on a resend), this throws
2475
- * `RecoveryMethodUnavailableError`, which `pincode-send` degrades to the
2476
- * same generic finish — never a distinguishable 500.
3116
+ * cross-account. With no deliverable method this throws
3117
+ * `RecoveryMethodUnavailableError`, which recovery treats as "no account"
3118
+ * (nothing sent, every code refused) — never a distinguishable 500.
2477
3119
  */
2478
3120
  recoveryPincodeTarget(ctx, source) {
2479
3121
  if (source === "registered") {
@@ -2498,6 +3140,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2498
3140
  channel
2499
3141
  };
2500
3142
  }
3143
+ /** `resolveRecoveryDeliverySource`, awaited. */
3144
+ async recoveryDeliverySource(ctx) {
3145
+ const source = this.resolveRecoveryDeliverySource(ctx);
3146
+ return source instanceof Promise ? await source : source;
3147
+ }
2501
3148
  /**
2502
3149
  * Recovery OTP delivery channel. The address is ALWAYS the typed recovery
2503
3150
  * identifier (`ctx.email`) — symmetric with how email recovery already works:
@@ -2522,7 +3169,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2522
3169
  * row** — `selectRecoveryRegisteredMethod` picks the confirmed MFA method;
2523
3170
  * the destination is never taken from user input, so it cannot be redirected
2524
3171
  * to an attacker-controlled address. A row with no deliverable confirmed
2525
- * method finishes with the generic anti-enumeration envelope (see `request`).
3172
+ * method runs the ghost OTP pause, like an unknown identifier (see `request`).
2526
3173
  *
2527
3174
  * Consulted inline by `request` (no-method guard) and `recoveryPincodeTarget`
2528
3175
  * — no `prepare-*` step, mirroring `resolveRecoveryChannel`. Override to arm
@@ -2536,7 +3183,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2536
3183
  * its OTP to. Prefers a confirmed SMS method, then a confirmed email method —
2537
3184
  * phone-recovery-first. TOTP carries no deliverable address and is skipped.
2538
3185
  * Returns `null` when the row has no deliverable confirmed method; the caller
2539
- * turns that into the anti-enumeration generic finish. Stays sync (operates on
3186
+ * turns that into the ghost OTP run (anti-enumeration). Stays sync (operates on
2540
3187
  * an already-loaded row); override to change the selection policy (e.g. honour
2541
3188
  * the user's `mfa.defaultMethod`).
2542
3189
  */
@@ -2603,6 +3250,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2603
3250
  *
2604
3251
  * Called via `throwPublic` immediately before every `requireInput`-style
2605
3252
  * pause so the FE always reads a fresh projection of the post-step ctx.
3253
+ * `WfTriggerProvider` strips the projection before persisting the state.
2606
3254
  */
2607
3255
  populatePublic(ctx) {
2608
3256
  const pub = {};
@@ -2640,7 +3288,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2640
3288
  if (sub) pub.trust = sub;
2641
3289
  }
2642
3290
  if (ctx.password) {
2643
- const sub = pickDefined(ctx.password, [
3291
+ const { heading, headingCode, intro, introCode, policies } = ctx.password;
3292
+ const sub = pickDefined({
3293
+ heading: heading ?? (headingCode ? this.msg(headingCode) : void 0),
3294
+ intro: intro ?? (introCode ? this.msg(introCode) : void 0),
3295
+ policies: policies?.map(translatePolicyTexts)
3296
+ }, [
2644
3297
  "heading",
2645
3298
  "intro",
2646
3299
  "policies"
@@ -2689,6 +3342,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2689
3342
  if (sub) pub.proveControl = sub;
2690
3343
  }
2691
3344
  if (ctx.newPasswordRequired !== void 0) pub.newPasswordRequired = ctx.newPasswordRequired;
3345
+ if (ctx.magicLink?.sentAt && ctx.magicLink.address && !ctx.magicLink.confirmed) pub.magicLink = { account: this.maskAddress(ctx.magicLink.address, "email") };
2692
3346
  if (ctx.authz) {
2693
3347
  const sub = pickDefined(ctx.authz, [
2694
3348
  "clientName",
@@ -2699,6 +3353,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2699
3353
  if (sub) pub.authz = sub;
2700
3354
  }
2701
3355
  ctx.public = pub;
3356
+ markPublicProjection(pub);
2702
3357
  }
2703
3358
  /**
2704
3359
  * Wrap `wf.requireInput(opts)` so `ctx.public` is freshly projected
@@ -2732,40 +3387,170 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2732
3387
  throw err;
2733
3388
  }
2734
3389
  }
2735
- /** Mint a numeric pincode + stash it onto ctx. Returns the plain code. */
2736
- mintPin(ctx, length, ttlMs) {
3390
+ /**
3391
+ * Mint a numeric one-time code for `binding` (who it is sent for) and return
3392
+ * the plain code for delivery. The state keeps only a random nonce and a
3393
+ * keyed digest of `nonce|binding|code` — fixed lengths, never the code — so
3394
+ * a read of the state does not reveal it, and {@link verifyPin} accepts it
3395
+ * only for the same binding. `length` and `ttlMs` default to
3396
+ * `mfa.pincodeLength` / `mfa.pincodeTtlMs`.
3397
+ */
3398
+ mintPin(ctx, binding, length = this.opts.mfa.pincodeLength, ttlMs = this.opts.mfa.pincodeTtlMs) {
2737
3399
  const code = generateMfaCode(length);
2738
- ctx.pin = code;
3400
+ ctx.pinNonce = randomBytes(16).toString("base64url");
3401
+ ctx.pinDigest = this.pinDigest(ctx.pinNonce, binding, code);
2739
3402
  ctx.pinExpire = Date.now() + ttlMs;
2740
- delete ctx.pinAttempts;
2741
3403
  return code;
2742
3404
  }
3405
+ /** Drop the code in flight (its nonce stays spent or counted server-side). */
3406
+ clearPin(ctx) {
3407
+ delete ctx.pinNonce;
3408
+ delete ctx.pinDigest;
3409
+ delete ctx.pinExpire;
3410
+ }
3411
+ /** Binding of a code sent to `address` in this run (and for its subject, once known). */
3412
+ pinFor(ctx, address) {
3413
+ return `${ctx.subject ?? ""}|${address}`;
3414
+ }
2743
3415
  /**
2744
- * Verify a submitted pincode against `ctx.pin`. Returns an error map (with
2745
- * the message keyed under `code` so it renders inline on the code input) or
2746
- * `null` on success. Brute-force protection: wrong-code attempts increment
2747
- * `ctx.pinAttempts`; on the `pincodeMaxAttempts`-th miss the code is
2748
- * invalidated (clears `pin` + `pinExpire` + `pinAttempts`) and the returned
2749
- * error tells the user to request a fresh code. Without this gate the user
2750
- * could probe the full 10^pincodeLength space inside one `pincodeTtlMs`
2751
- * window.
2752
- */
2753
- verifyPin(ctx, submitted) {
2754
- if (!ctx.pin || !ctx.pinExpire || Date.now() > ctx.pinExpire) return { code: "Code expired" };
2755
- if (submitted !== ctx.pin) {
2756
- const attempts = (ctx.pinAttempts ?? 0) + 1;
2757
- if (attempts >= this.opts.mfa.pincodeMaxAttempts) {
2758
- delete ctx.pin;
2759
- delete ctx.pinExpire;
2760
- delete ctx.pinAttempts;
2761
- return { code: "Too many invalid attempts. Please request a new code." };
2762
- }
2763
- ctx.pinAttempts = attempts;
2764
- return { code: "Invalid code" };
2765
- }
2766
- delete ctx.pinAttempts;
3416
+ * Binding of a recovery code: the account and the address it went to (a
3417
+ * changed registered channel refuses the old channel's code). Without an
3418
+ * account, the placeholder — the digest has the same length either way.
3419
+ */
3420
+ recoveryBinding(account) {
3421
+ return account ? `${account.subject}|${account.address}` : `${UNKNOWN_ACCOUNT_ID}|`;
3422
+ }
3423
+ /**
3424
+ * Server-side key of where a code goes — its resend cooldown and failed-code
3425
+ * budget. Never an account id the caller could not know: recovery and signup
3426
+ * key on the typed identifier, so known and unknown ones behave alike.
3427
+ */
3428
+ codeTarget(...parts) {
3429
+ return sha256url(parts.map((p) => (p ?? "").trim().toLowerCase()).join("|"));
3430
+ }
3431
+ /** {@link codeTarget} of a code sent to `address` to enrol or verify a channel. */
3432
+ enrollTarget(ctx, address) {
3433
+ return this.codeTarget("enroll", ctx.subject, address);
3434
+ }
3435
+ /** {@link codeTarget} of a federated link's proof-of-control code. */
3436
+ linkTarget(pending) {
3437
+ return this.codeTarget("link", pending.candidateUserId);
3438
+ }
3439
+ /** {@link codeTarget} of the `pincode-send` / `pincode-check` pair. */
3440
+ pincodeTarget(ctx, address) {
3441
+ if (ctx.mfa?.method) return this.codeTarget("mfa", ctx.subject, address);
3442
+ return this.codeTarget(ctx.signup ? "signup" : "recovery", ctx.email);
3443
+ }
3444
+ /**
3445
+ * Server-side gate of a code send to `target`, before minting: answers
3446
+ * `429 AOOTH_CODE_LIMIT_REACHED` once the target's failed-code budget is
3447
+ * spent (this client IP's, or all IPs' together), applies the per-account
3448
+ * `aooth.send-user` limit when `account` is given (sends after a first
3449
+ * factor), and claims this client IP's resend wait for the target
3450
+ * (`mfa.pincodeResendTimeoutMs`) and a slot of the target's send cap from
3451
+ * all IPs (`mfa.pincodeMaxSendsGlobal` per `pincodeFailureWindowMs`).
3452
+ * Returns whether the code may go out: `false` inside the wait or past the
3453
+ * cap — the caller mints a code all the same and sends nothing, for known
3454
+ * and unknown destinations alike.
3455
+ */
3456
+ async claimCodeSend(target, account) {
3457
+ if (account !== void 0) await enforceRateLimit(SEND_USER_RATE_LIMIT, `user:${account}`);
3458
+ await this.assertCodeBudget(this.counterKeys(CODE_FAIL_PREFIX, target));
3459
+ const store = this.opts.lockoutShadowStore;
3460
+ const keys = this.counterKeys(CODE_SEND_PREFIX, target);
3461
+ if (await store.hit(keys.client, this.opts.mfa.pincodeResendTimeoutMs) > 1) return false;
3462
+ return await store.hit(keys.global, this.opts.mfa.pincodeFailureWindowMs) <= this.opts.mfa.pincodeMaxSendsGlobal;
3463
+ }
3464
+ /** Whether a send to `target` is cooling down (`false` when the store cannot peek). */
3465
+ async codeSendCoolingDown(target) {
3466
+ const store = this.opts.lockoutShadowStore;
3467
+ if (!store.get) return false;
3468
+ const keys = this.counterKeys(CODE_SEND_PREFIX, target);
3469
+ return await store.get(keys.client) > 0 || await store.get(keys.global) >= this.opts.mfa.pincodeMaxSendsGlobal;
3470
+ }
3471
+ /**
3472
+ * Counters of a destination, per client IP and across all IPs:
3473
+ * - sends (`CODE_SEND_PREFIX`): this client's resend wait, and the sends
3474
+ * from all IPs together in the window (the cap on mail-bombing and SMS
3475
+ * pumping spread over many IPs);
3476
+ * - failed codes (`CODE_FAIL_PREFIX`): the budget one caller can spend (so
3477
+ * an attacker cannot lock the owner out from elsewhere), and the backstop
3478
+ * against distributed guessing.
3479
+ *
3480
+ * The client IP is hashed: fixed-size keys, no raw IPs in the store.
3481
+ */
3482
+ counterKeys(prefix, target) {
3483
+ return {
3484
+ client: `${prefix}${target}:${sha256url(requestClientIp())}`,
3485
+ global: `${prefix}${target}`
3486
+ };
3487
+ }
3488
+ /** Answer `429 AOOTH_CODE_LIMIT_REACHED` once a destination's failed-code budget is spent. */
3489
+ async assertCodeBudget(keys) {
3490
+ const store = this.opts.lockoutShadowStore;
3491
+ if (!store.get) return;
3492
+ const [client, global] = await Promise.all([store.get(keys.client), store.get(keys.global)]);
3493
+ if (client >= this.opts.mfa.pincodeMaxFailures || global >= this.opts.mfa.pincodeMaxFailuresGlobal) throw aoothHttpError(429, "AOOTH_CODE_LIMIT_REACHED");
3494
+ }
3495
+ /**
3496
+ * Verify a submitted code against the one minted for `binding`. Returns an
3497
+ * error map (keyed under `code` so it renders on the code input) or `null`
3498
+ * on success.
3499
+ *
3500
+ * Attempts are counted server-side in `lockoutShadowStore`, per minted code
3501
+ * (its nonce), before the comparison: a replayed older state token shares
3502
+ * the counter, so `pincodeMaxAttempts` holds across replays and parallel
3503
+ * submits. A code is single-use: once it verifies, its nonce is spent and
3504
+ * the same code through any copy of the state is refused. A binding that
3505
+ * differs from the one at mint (the account resolved differently since the
3506
+ * send) reads as a wrong code. Wrong codes also count against `target`'s
3507
+ * failed-code budgets across resends (`mfa.pincodeMaxFailures` per client
3508
+ * IP, `pincodeMaxFailuresGlobal` for all IPs, per
3509
+ * `pincodeFailureWindowMs`); once one is spent every check answers
3510
+ * `429 AOOTH_CODE_LIMIT_REACHED`.
3511
+ */
3512
+ async verifyPin(ctx, submitted, binding, target) {
3513
+ const failureKeys = this.counterKeys(CODE_FAIL_PREFIX, target);
3514
+ await this.assertCodeBudget(failureKeys);
3515
+ const { pinNonce: nonce, pinDigest: digest, pinExpire: expire } = ctx;
3516
+ const now = Date.now();
3517
+ if (!nonce || !digest || !expire || now > expire) return { code: this.msg("AOOTH_CODE_EXPIRED") };
3518
+ const store = this.opts.lockoutShadowStore;
3519
+ const ttl = expire - now + PIN_COUNTER_GRACE_MS;
3520
+ const attempts = await store.hit(`${PIN_ATTEMPT_PREFIX}${nonce}`, ttl);
3521
+ const max = this.opts.mfa.pincodeMaxAttempts;
3522
+ if (attempts > max) return { code: this.msg("AOOTH_TOO_MANY_CODE_ATTEMPTS") };
3523
+ if (!safeEqual(this.pinDigest(nonce, binding, submitted ?? ""), digest)) {
3524
+ const window = this.opts.mfa.pincodeFailureWindowMs;
3525
+ const [client, global] = await Promise.all([store.hit(failureKeys.client, window), store.hit(failureKeys.global, window)]);
3526
+ if (client > this.opts.mfa.pincodeMaxFailures || global > this.opts.mfa.pincodeMaxFailuresGlobal) throw aoothHttpError(429, "AOOTH_CODE_LIMIT_REACHED");
3527
+ return { code: this.msg(attempts >= max ? "AOOTH_TOO_MANY_CODE_ATTEMPTS" : "AOOTH_INVALID_CODE") };
3528
+ }
3529
+ const spent = await store.hit(`${PIN_SPENT_PREFIX}${nonce}`, ttl);
3530
+ this.clearPin(ctx);
3531
+ if (spent > 1) return { code: this.msg("AOOTH_CODE_EXPIRED") };
2767
3532
  return null;
2768
3533
  }
3534
+ /** Keyed digest of a code, bound to its nonce and to who it was sent for. */
3535
+ pinDigest(nonce, binding, code) {
3536
+ return createHmac("sha256", this.pincodeKey()).update(`${nonce}|${binding}|${code}`).digest("base64url");
3537
+ }
3538
+ /**
3539
+ * Key of the code digests: the one `WfTriggerProvider` publishes for the
3540
+ * request (derived from its `pincodeSecret()`), else the key a default
3541
+ * provider publishes (`defaultPincodeKey`: derived from the default wf-state
3542
+ * secret), so a code minted on one path verifies on the other. Throws
3543
+ * `INVALID_CONFIG` outside a provider when the credential store has no
3544
+ * derivable secret. Override when the workflow runs outside a
3545
+ * `WfTriggerProvider` whose `wfStateSecret()` / `pincodeSecret()` is
3546
+ * overridden — return that provider's key; every instance must agree.
3547
+ */
3548
+ pincodeKey() {
3549
+ const ctx = tryGetCurrent();
3550
+ if (ctx?.has(pincodeKeySlot)) return ctx.get(pincodeKeySlot);
3551
+ return this.fallbackPincodeKey ??= defaultPincodeKey(this.auth);
3552
+ }
3553
+ fallbackPincodeKey;
2769
3554
  /**
2770
3555
  * Validate + stash inline-consent fields submitted on a carrier form.
2771
3556
  * SECURITY: silently drops unknown ids (audit-grade defense — see base
@@ -2811,7 +3596,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2811
3596
  const pincode = ctx.pincode ??= {};
2812
3597
  const channel = ctx.mfaEnroll?.method === "email" ? "email" : "sms";
2813
3598
  pincode.sentTo = this.maskAddress(address, channel);
2814
- await this.deliver({
3599
+ await this.dispatch({
2815
3600
  kind: "enroll-pincode",
2816
3601
  channel,
2817
3602
  recipient: address,
@@ -2826,12 +3611,19 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2826
3611
  * `enrollConfirm`, so the arming policy cannot drift between first send
2827
3612
  * and resend.
2828
3613
  */
2829
- async mintAndSendEnrollPincode(ctx, address) {
2830
- const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
3614
+ async mintAndSendEnrollPincode(ctx, address, claimed) {
3615
+ const deliver = claimed ?? await this.claimCodeSend(this.enrollTarget(ctx, address), ctx.subject);
3616
+ const code = this.mintPin(ctx, this.pinFor(ctx, address));
2831
3617
  const pincode = ctx.pincode ??= {};
2832
3618
  pincode.resendAllowedAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
2833
3619
  pincode.codeLength = this.opts.mfa.pincodeLength;
2834
- await this.sendEnrollPincode(ctx, address, code);
3620
+ if (deliver) await this.sendEnrollPincode(ctx, address, code);
3621
+ }
3622
+ /** Seconds a resend still has to wait — the state's hint, else a full cooldown. */
3623
+ resendWaitSeconds(until) {
3624
+ const now = Date.now();
3625
+ const ms = until && until > now ? until - now : this.opts.mfa.pincodeResendTimeoutMs;
3626
+ return Math.ceil(ms / 1e3);
2835
3627
  }
2836
3628
  /**
2837
3629
  * Idempotent TOTP secret provisioning into wf-state ONLY (the QR renders
@@ -2876,8 +3668,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2876
3668
  delete m.qrSeen;
2877
3669
  delete m.preConfirmed;
2878
3670
  }
2879
- delete ctx.pin;
2880
- delete ctx.pinExpire;
3671
+ this.clearPin(ctx);
2881
3672
  if (ctx.pincode) delete ctx.pincode.sentTo;
2882
3673
  }
2883
3674
  /**
@@ -2906,11 +3697,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2906
3697
  */
2907
3698
  validateMfaAddress(_ctx, method, value) {
2908
3699
  const v = (value ?? "").trim();
2909
- if (!v) return "This field is required";
2910
- if (method === "email") return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? void 0 : "Enter a valid email address";
3700
+ if (!v) return this.msg("AOOTH_ADDRESS_REQUIRED");
3701
+ if (method === "email") return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? void 0 : this.msg("AOOTH_INVALID_EMAIL_ADDRESS");
2911
3702
  if (method === "sms") {
2912
3703
  const digits = v.replace(/[\s()+.-]/g, "");
2913
- return /^[1-9]\d{6,14}$/.test(digits) ? void 0 : "Enter a valid phone number";
3704
+ return /^[1-9]\d{6,14}$/.test(digits) ? void 0 : this.msg("AOOTH_INVALID_PHONE_NUMBER");
2914
3705
  }
2915
3706
  }
2916
3707
  /**
@@ -3084,8 +3875,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3084
3875
  initChangePassword(ctx) {
3085
3876
  ctx.subject = useAuth().getUserId();
3086
3877
  const password = ctx.password ??= {};
3087
- password.heading = "Change your password";
3088
- password.intro = "Enter your current password, then choose a new one.";
3878
+ password.headingCode = "CHANGE_PASSWORD_HEADING";
3879
+ password.introCode = "CHANGE_PASSWORD_INTRO";
3089
3880
  }
3090
3881
  /**
3091
3882
  * Bind the standalone "Manage two-factor authentication" flow (add / change /
@@ -3148,6 +3939,10 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3148
3939
  if (alt.ssoProviders.length > 0) altActions.ssoProviders = alt.ssoProviders;
3149
3940
  const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.loginCredentials);
3150
3941
  const action = wf.resolveAction();
3942
+ if (action === "magicLink" && alt.magicLink) {
3943
+ ctx.magicLink = { purpose: "login" };
3944
+ return;
3945
+ }
3151
3946
  if (action) {
3152
3947
  const typedUsername = getInputField("username");
3153
3948
  if (await this.handleCredentialsAlt(action, typedUsername, alt, ctx.authz?.handle) === ALT_HANDLED) return void 0;
@@ -3155,35 +3950,48 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3155
3950
  const input = wf.resolveInput();
3156
3951
  try {
3157
3952
  const result = await this.users.login(input.username, input.password, this.lockoutOverride(ctx));
3158
- ctx.subject = result.user.id;
3159
- ctx.passwordStamp = result.user.password.lastChanged ?? 0;
3160
3953
  ctx.loginRecorded = true;
3161
3954
  swapStrategy("store");
3162
- if (ctx.guards?.passwordInitial && result.user.password.isInitial) ctx.isPasswordInitial = true;
3163
- if (ctx.guards?.passwordExpiry && this.users.isPasswordExpired(result.user)) ctx.isPasswordExpired = true;
3164
- if (ctx.isPasswordInitial) (ctx.password ??= {}).changeReason = "initial";
3165
- else if (ctx.isPasswordExpired) (ctx.password ??= {}).changeReason = "expired";
3166
- const email = result.user.mfa.methods.find((m) => m.name === "email" && m.confirmed);
3167
- if (email) {
3168
- (ctx.notice ??= {}).email = email.value;
3169
- (ctx.channel ??= {}).emailConfirmed = true;
3170
- }
3171
- const phone = result.user.mfa.methods.find((m) => m.name === "sms" && m.confirmed);
3172
- if (phone) {
3173
- const channel = ctx.channel ??= {};
3174
- channel.phone = phone.value;
3175
- channel.phoneConfirmed = true;
3176
- }
3177
- if (!ctx.notice?.email) await this.seedCorrespondenceEmail(ctx, result.user);
3955
+ await this.bindSignedInUser(ctx, result.user);
3178
3956
  } catch (err) {
3179
3957
  if (err instanceof UserAuthError) {
3180
3958
  const locked = await this.failedLoginReadsLocked(ctx, err, input.username);
3181
- throw this.throwPublic(ctx, wf, { formMessage: this.msg(locked ? "ACCOUNT_LOCKED" : "INVALID_CREDENTIALS") });
3959
+ throw this.throwPublic(ctx, wf, { formMessage: this.msg(locked ? "AOOTH_ACCOUNT_LOCKED" : "INVALID_CREDENTIALS") });
3182
3960
  }
3183
3961
  throw err;
3184
3962
  }
3185
3963
  }
3186
3964
  /**
3965
+ * Bind the login run to the account that passed its first factor — shared
3966
+ * by the password and magic-link sign-ins, so both leave the run alike:
3967
+ * - `ctx.subject` and the password stamp;
3968
+ * - the inline password guards (`ctx.guards`): top-level
3969
+ * `isPasswordInitial` / `isPasswordExpired` (read by
3970
+ * `prepare-semantic-flags` later as a fallback) and the change reason;
3971
+ * - the account's confirmed channels, so `ensureEmail` / `ensurePhone` skip
3972
+ * what is already confirmed and security notices have a recipient.
3973
+ */
3974
+ async bindSignedInUser(ctx, user) {
3975
+ ctx.subject = user.id;
3976
+ ctx.passwordStamp = user.password.lastChanged ?? 0;
3977
+ if (ctx.guards?.passwordInitial && user.password.isInitial) ctx.isPasswordInitial = true;
3978
+ if (ctx.guards?.passwordExpiry && this.users.isPasswordExpired(user)) ctx.isPasswordExpired = true;
3979
+ if (ctx.isPasswordInitial) (ctx.password ??= {}).changeReason = "initial";
3980
+ else if (ctx.isPasswordExpired) (ctx.password ??= {}).changeReason = "expired";
3981
+ const email = user.mfa.methods.find((m) => m.name === "email" && m.confirmed);
3982
+ if (email) {
3983
+ (ctx.notice ??= {}).email = email.value;
3984
+ (ctx.channel ??= {}).emailConfirmed = true;
3985
+ }
3986
+ const phone = user.mfa.methods.find((m) => m.name === "sms" && m.confirmed);
3987
+ if (phone) {
3988
+ const channel = ctx.channel ??= {};
3989
+ channel.phone = phone.value;
3990
+ channel.phoneConfirmed = true;
3991
+ }
3992
+ if (!ctx.notice?.email) await this.seedCorrespondenceEmail(ctx, user);
3993
+ }
3994
+ /**
3187
3995
  * Whether a failed password sign-in answers "Account locked" — see
3188
3996
  * `AuthWorkflowOpts.lockoutDisclosure`. Under `'uniform'` an unknown or
3189
3997
  * inactive handle keeps a shadow failure counter in `lockoutShadowStore`
@@ -3205,7 +4013,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3205
4013
  };
3206
4014
  if (threshold <= 0) return false;
3207
4015
  const store = this.opts.lockoutShadowStore;
3208
- const id = createHash("sha256").update(handle.trim().toLowerCase()).digest("base64url");
4016
+ const id = sha256url(handle.trim().toLowerCase());
3209
4017
  const lockKey = `${SHADOW_LOCK_PREFIX}${id}`;
3210
4018
  if (store.get && await store.get(lockKey) > 0) {
3211
4019
  if (duration <= 0) await store.expire?.(lockKey, SHADOW_TTL_MS);
@@ -3247,11 +4055,10 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3247
4055
  } });
3248
4056
  return ALT_HANDLED;
3249
4057
  }
3250
- if (action === "magicLink" && alt.magicLink) throw new HttpError$1(501, "Magic-link login path not implemented in this version");
3251
4058
  if (action === "sso") {
3252
4059
  const providerId = getInputField("ssoProvider");
3253
4060
  const sso = providerId ? alt.ssoProviders.find((p) => p.id === providerId) : void 0;
3254
- if (!sso) throw new HttpError$1(400, "Unknown SSO provider");
4061
+ if (!sso) throw this.httpError(400, "UNKNOWN_SSO_PROVIDER");
3255
4062
  await this.beginSso(sso.id, authzHandle);
3256
4063
  return ALT_HANDLED;
3257
4064
  }
@@ -3272,28 +4079,75 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3272
4079
  if (prefilled) ctx.defaults = { email: prefilled };
3273
4080
  throw this.throwPublic(ctx, emailWf);
3274
4081
  }
3275
- const email = emailWf.resolveInput().email;
3276
- ctx.email = email;
3277
- let subject;
4082
+ ctx.email = emailWf.resolveInput().email;
4083
+ const modeResult = this.resolveRecoveryDeliveryMode(ctx);
4084
+ await this.applyRecoveryMode(ctx, modeResult instanceof Promise ? await modeResult : modeResult);
4085
+ }
4086
+ /**
4087
+ * Start recovery's delivery `mode` — the same way for known and unknown
4088
+ * identifiers:
4089
+ * - `'magicLink'`: the link for the typed identifier, resolved now but held
4090
+ * only in the link's server-side pause (the requester never gets a token
4091
+ * for it, and an earlier picker's state holds nothing about the account);
4092
+ * - `'otp'`: the durable store strategy. Nothing about the account goes into
4093
+ * the state before the code is verified: `pincode-send` /
4094
+ * `pincode-check` resolve it from the typed identifier each time.
4095
+ */
4096
+ async applyRecoveryMode(ctx, mode) {
4097
+ ctx.recoveryDelivery = mode;
4098
+ if (mode === "magicLink") ctx.magicLink = await this.recoveryMagicLink(ctx);
4099
+ else if (mode === "otp") swapStrategy("store");
4100
+ }
4101
+ /** A recovery magic link for the typed identifier (`subject` unset when it matches no account). */
4102
+ async recoveryMagicLink(ctx) {
4103
+ const email = ctx.email ?? "";
4104
+ const subject = await this.lookupRecoverySubject(email);
4105
+ return {
4106
+ purpose: "recovery",
4107
+ identifier: email.trim().toLowerCase(),
4108
+ ...subject && { subject }
4109
+ };
4110
+ }
4111
+ /** `emailToUserId`, with an unknown identifier as `undefined`. */
4112
+ async lookupRecoverySubject(identifier) {
3278
4113
  try {
3279
- subject = await this.emailToUserId(email) ?? void 0;
4114
+ return await this.emailToUserId(identifier) ?? void 0;
3280
4115
  } catch (err) {
3281
4116
  if (!(err instanceof UserAuthError) || err.type !== "NOT_FOUND") throw err;
3282
- }
3283
- if (!subject) {
3284
- this.finishGenericRecovery();
3285
4117
  return;
3286
4118
  }
3287
- const sourceResult = this.resolveRecoveryDeliverySource(ctx);
3288
- if ((sourceResult instanceof Promise ? await sourceResult : sourceResult) === "registered") {
3289
- const user = await this.users.getUser(subject);
3290
- if (!this.selectRecoveryRegisteredMethod(user)) {
3291
- this.finishGenericRecovery();
3292
- return;
3293
- }
4119
+ }
4120
+ /**
4121
+ * The account a recovery code for the typed identifier goes to, and where —
4122
+ * or `null` when no code can go anywhere: an unknown identifier, an inactive
4123
+ * (pending / deactivated) account, or under M2 an account without a
4124
+ * deliverable confirmed channel. A locked account may recover (self-service
4125
+ * unlock). Resolved from `ctx.email` on every send and at verification —
4126
+ * never kept in the state — and with the same reads for every identifier
4127
+ * (an unknown one reads a placeholder row).
4128
+ */
4129
+ async recoveryAccount(ctx) {
4130
+ const subject = await this.lookupRecoverySubject(ctx.email ?? "");
4131
+ let user;
4132
+ try {
4133
+ user = await this.users.getUser(subject ?? UNKNOWN_ACCOUNT_ID);
4134
+ } catch (err) {
4135
+ if (!(err instanceof UserAuthError) || err.type !== "NOT_FOUND") throw err;
4136
+ }
4137
+ const known = Boolean(subject && user?.account.active);
4138
+ try {
4139
+ const target = await this.resolvePincodeTarget({
4140
+ ...ctx,
4141
+ subject: known ? subject : UNKNOWN_ACCOUNT_ID
4142
+ });
4143
+ return known ? {
4144
+ subject,
4145
+ ...target
4146
+ } : null;
4147
+ } catch (err) {
4148
+ if (!known || err instanceof RecoveryMethodUnavailableError) return null;
4149
+ throw err;
3294
4150
  }
3295
- ctx.subject = subject;
3296
- swapStrategy("store");
3297
4151
  }
3298
4152
  /**
3299
4153
  * Resolves the recovery-step `email` input to the user's stable `id` (the
@@ -3304,16 +4158,6 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3304
4158
  async emailToUserId(email) {
3305
4159
  return (await this.users.findByHandle(email))?.id ?? null;
3306
4160
  }
3307
- /** Anti-enumeration generic finish envelope used when recovery's `request` step receives an unknown email. */
3308
- finishGenericRecovery() {
3309
- finishWf({
3310
- data: { sent: true },
3311
- message: {
3312
- level: "info",
3313
- text: this.msg("RECOVERY_INSTRUCTIONS_SENT")
3314
- }
3315
- });
3316
- }
3317
4161
  /**
3318
4162
  * Stamp `recoveryStateTtlMs` on a paused-state error so the wf engine's
3319
4163
  * persisted-state strategy expires the state at that timestamp. Use at
@@ -3556,7 +4400,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3556
4400
  const parsed = this.effectiveInviteRoles(ctx, roles);
3557
4401
  if (Array.isArray(ctx.admin?.availableRoles)) {
3558
4402
  const allowed = new Set(ctx.admin.availableRoles);
3559
- if (parsed.find((r) => !allowed.has(r)) !== void 0) throw this.throwPublic(ctx, wf, { errors: { roles: this.msg("INVALID_ROLE") } });
4403
+ if (parsed.find((r) => !allowed.has(r)) !== void 0) throw this.throwPublic(ctx, wf, { errors: { roles: this.msg("AOOTH_INVALID_ROLE") } });
3560
4404
  }
3561
4405
  if (Object.keys(extra).length > 0) (ctx.admin ??= {}).form = extra;
3562
4406
  const existing = await this.users.findByHandle(email);
@@ -3571,7 +4415,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3571
4415
  });
3572
4416
  if (action === "reject") {
3573
4417
  if (existing?.account?.pendingInvitation) throw this.throwPublic(ctx, wf, { errors: { email: this.msg("INVITE_ALREADY_PENDING") } });
3574
- if (existing) throw this.throwPublic(ctx, wf, { errors: { email: this.msg("USER_ALREADY_EXISTS") } });
4418
+ if (existing) throw this.throwPublic(ctx, wf, { errors: { email: this.msg("AOOTH_USER_ALREADY_EXISTS") } });
3575
4419
  throw this.throwPublic(ctx, wf, { errors: { email: this.msg("DUPLICATE_INVITE_REJECTED") } });
3576
4420
  }
3577
4421
  if (action === "reuse") {
@@ -3657,7 +4501,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3657
4501
  if (admin.reuseExisting) {
3658
4502
  const existing = await this.users.findByHandle(ctx.email);
3659
4503
  if (existing) {
3660
- if (!existing.account?.pendingInvitation) throw this.httpError(409, "USER_ALREADY_EXISTS");
4504
+ if (!existing.account?.pendingInvitation) throw this.httpError(409, "AOOTH_USER_ALREADY_EXISTS");
3661
4505
  await this.users.update(existing.id, {
3662
4506
  ...fields,
3663
4507
  account: pendingAccount
@@ -3670,7 +4514,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3670
4514
  try {
3671
4515
  created = await this.users.createUser(ctx.email, void 0, fields);
3672
4516
  } catch (err) {
3673
- if (err instanceof UserAuthError && err.type === "ALREADY_EXISTS") throw this.httpError(409, "USER_ALREADY_EXISTS");
4517
+ if (err instanceof UserAuthError && err.type === "ALREADY_EXISTS") throw this.httpError(409, "AOOTH_USER_ALREADY_EXISTS");
3674
4518
  throw err;
3675
4519
  }
3676
4520
  await this.users.update(created.id, { account: pendingAccount });
@@ -3720,7 +4564,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3720
4564
  ...userId && { userId }
3721
4565
  }
3722
4566
  };
3723
- await this.deliver({
4567
+ await this.dispatch({
3724
4568
  kind: "invite-link",
3725
4569
  channel: "email",
3726
4570
  recipient: email,
@@ -3830,7 +4674,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3830
4674
  data: { confirmed: true },
3831
4675
  message: {
3832
4676
  level: "success",
3833
- text: ctx.accept.confirmationMessage
4677
+ text: ctx.accept?.confirmationMessage ?? this.msg("AOOTH_ACCOUNT_CREATED")
3834
4678
  }
3835
4679
  });
3836
4680
  }
@@ -3845,8 +4689,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3845
4689
  this.requireSubject(ctx);
3846
4690
  const password = ctx.password ??= {};
3847
4691
  const copy = await this.resolveSetPasswordCopy(ctx);
3848
- if (copy.heading !== void 0) password.heading = copy.heading;
3849
- if (copy.intro !== void 0) password.intro = copy.intro;
4692
+ Object.assign(password, pickDefined(copy, SET_PASSWORD_COPY_KEYS));
3850
4693
  const user = await this.refusePasswordFormReplay(ctx);
3851
4694
  const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.setPassword);
3852
4695
  let input;
@@ -3861,7 +4704,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3861
4704
  try {
3862
4705
  await this.users.setPassword(ctx.subject, input.newPassword);
3863
4706
  } catch (err) {
3864
- if (err instanceof UserAuthError) throw this.throwPublic(ctx, wf, { errors: { newPassword: err.message } });
4707
+ if (err instanceof UserAuthError) throw this.throwPublic(ctx, wf, { errors: { newPassword: userAuthErrorText(err) } });
3865
4708
  throw err;
3866
4709
  }
3867
4710
  this.processInlineConsent(ctx, input, wf);
@@ -3871,8 +4714,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3871
4714
  delete ctx.passwordFormStamp;
3872
4715
  ctx.newPasswordRequired = false;
3873
4716
  delete password.changeReason;
3874
- delete password.heading;
3875
- delete password.intro;
4717
+ for (const key of SET_PASSWORD_COPY_KEYS) delete password[key];
3876
4718
  }
3877
4719
  /**
3878
4720
  * Optional min-interval rate limit (Okta "minimum password age"). Gated
@@ -3898,7 +4740,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3898
4740
  next: {
3899
4741
  trigger: "manual",
3900
4742
  primary: {
3901
- label: this.msg("BACK"),
4743
+ label: this.msg("AOOTH_BACK"),
3902
4744
  action: {
3903
4745
  type: "redirect",
3904
4746
  target: this.opts.loginUrl,
@@ -3929,7 +4771,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3929
4771
  } catch (err) {
3930
4772
  if (err instanceof UserAuthError) {
3931
4773
  const field = userAuthErrorField(err.type) ?? "newPassword";
3932
- throw this.throwPublic(ctx, wf, { errors: { [field]: err.message } });
4774
+ throw this.throwPublic(ctx, wf, { errors: { [field]: userAuthErrorText(err) } });
3933
4775
  }
3934
4776
  throw err;
3935
4777
  }
@@ -4032,11 +4874,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4032
4874
  * cancelled) is unit-testable without a wf event context.
4033
4875
  */
4034
4876
  buildAddMfaFinishEnvelope(ctx) {
4035
- const labels = {
4036
- totp: "Authenticator app",
4037
- email: "Email code",
4038
- sms: "Text-message code"
4039
- };
4877
+ const label = (method) => this.msg(MFA_METHOD_LABEL_CODES[method]);
4040
4878
  const m = ctx.mfaEnroll;
4041
4879
  const addMfa = ctx.addMfa;
4042
4880
  const method = m?.method;
@@ -4050,7 +4888,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4050
4888
  },
4051
4889
  message: {
4052
4890
  level: "success",
4053
- text: `${labels[addMfa.removed]} removed.`
4891
+ text: this.msg("MFA_METHOD_REMOVED", { method: label(addMfa.removed) })
4054
4892
  }
4055
4893
  };
4056
4894
  else if (m?.done && method && addMfa?.action === "replace") envelope = {
@@ -4061,7 +4899,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4061
4899
  },
4062
4900
  message: {
4063
4901
  level: "success",
4064
- text: `${labels[method]} updated.`
4902
+ text: this.msg("MFA_METHOD_UPDATED", { method: label(method) })
4065
4903
  }
4066
4904
  };
4067
4905
  else if (m?.done && method) envelope = {
@@ -4072,7 +4910,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4072
4910
  },
4073
4911
  message: {
4074
4912
  level: "success",
4075
- text: `${labels[method]} added.`
4913
+ text: this.msg("MFA_METHOD_ADDED", { method: label(method) })
4076
4914
  }
4077
4915
  };
4078
4916
  else if (addMfa?.blocked) envelope = {
@@ -4083,7 +4921,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4083
4921
  },
4084
4922
  message: {
4085
4923
  level: "info",
4086
- text: addMfa.blocked === "last-required-factor" ? "You must keep at least one two-factor method, so this one can't be removed." : "That method can't be changed here."
4924
+ text: addMfa.blocked === "last-required-factor" ? this.msg("LAST_MFA_METHOD_NOT_REMOVABLE") : this.msg("AOOTH_METHOD_NOT_CHANGEABLE")
4087
4925
  }
4088
4926
  };
4089
4927
  else if (candidates.length === 0 && !addMfa?.stepUpRequired) envelope = {
@@ -4240,12 +5078,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4240
5078
  const action = sep >= 0 ? input.operation.slice(0, sep) : "";
4241
5079
  const target = sep >= 0 ? input.operation.slice(sep + 1) : "";
4242
5080
  if (action === "add") {
4243
- if (!candidates.includes(target)) throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("METHOD_UNAVAILABLE") } });
5081
+ if (!candidates.includes(target)) throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("AOOTH_METHOD_UNAVAILABLE") } });
4244
5082
  } else if (action === "replace" || action === "remove") {
4245
- if (locked.has(target)) throw this.throwPublic(ctx, wf, { formMessage: this.msg("METHOD_NOT_CHANGEABLE") });
4246
- if (!enrolled.some((e) => e.kind === target)) throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("UNKNOWN_METHOD") } });
5083
+ if (locked.has(target)) throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_METHOD_NOT_CHANGEABLE") });
5084
+ if (!enrolled.some((e) => e.kind === target)) throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("AOOTH_UNKNOWN_METHOD") } });
4247
5085
  if (action === "remove" && addMfa.removeBlocked) throw this.throwPublic(ctx, wf, { formMessage: this.msg("KEEP_ONE_MFA_METHOD") });
4248
- } else throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("CHOOSE_OPTION") } });
5086
+ } else throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("AOOTH_CHOOSE_OPTION") } });
4249
5087
  addMfa.action = action;
4250
5088
  addMfa.target = target;
4251
5089
  const m = ctx.mfaEnroll ??= {};
@@ -4313,20 +5151,30 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4313
5151
  }));
4314
5152
  if (isEmail) (ctx.channel ??= {}).email = value;
4315
5153
  else (ctx.channel ??= {}).phone = value;
4316
- const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
4317
- await this.deliver({
5154
+ const deliver = await this.claimCodeSend(this.enrollTarget(ctx, value), ctx.subject);
5155
+ await this.sendChannelPincode(ctx, value, isEmail ? "email" : "sms", deliver);
5156
+ const pincodeWf = this.useAtscriptWfPublic(ctx, this.opts.forms.pincode);
5157
+ throw this.throwPublic(ctx, pincodeWf);
5158
+ }
5159
+ /**
5160
+ * Mint the code proving a channel (`ask/*`, `verify/*`), deliver it when
5161
+ * `deliver`, and arm the PincodeForm: the resend wait `verifyChannel`
5162
+ * gates "Resend code" on (the same cooldown contract as `pincode-send`),
5163
+ * the masked `sentTo` its "Code sent to …" hint renders, and the code length.
5164
+ */
5165
+ async sendChannelPincode(ctx, address, channel, deliver) {
5166
+ const code = this.mintPin(ctx, this.pinFor(ctx, address));
5167
+ if (deliver) await this.dispatch({
4318
5168
  kind: "enroll-pincode",
4319
- channel: isEmail ? "email" : "sms",
4320
- recipient: value,
5169
+ channel,
5170
+ recipient: address,
4321
5171
  code,
4322
5172
  expiresInMs: this.opts.mfa.pincodeTtlMs
4323
5173
  });
4324
5174
  const pincode = ctx.pincode ??= {};
4325
5175
  pincode.resendAllowedAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
4326
- pincode.sentTo = this.maskAddress(value, isEmail ? "email" : "sms");
5176
+ pincode.sentTo = this.maskAddress(address, channel);
4327
5177
  pincode.codeLength = this.opts.mfa.pincodeLength;
4328
- const pincodeWf = this.useAtscriptWfPublic(ctx, this.opts.forms.pincode);
4329
- throw this.throwPublic(ctx, pincodeWf);
4330
5178
  }
4331
5179
  async verifyChannel(ctx, channel) {
4332
5180
  this.requireSubject(ctx);
@@ -4334,27 +5182,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4334
5182
  const pincodeWf = this.useAtscriptWfPublic(ctx, this.opts.forms.pincode);
4335
5183
  const action = pincodeWf.resolveAction();
4336
5184
  if (action && this.resolvePincodeAltAction(ctx, action) === "resend") {
4337
- if (ctx.pincode?.resendAllowedAt && ctx.pincode.resendAllowedAt > Date.now()) {
4338
- const remainingSec = Math.ceil((ctx.pincode.resendAllowedAt - Date.now()) / 1e3);
4339
- throw this.throwPublic(ctx, pincodeWf, { formMessage: this.msg("RESEND_WAIT", { seconds: remainingSec }) });
4340
- }
5185
+ const cooldown = ctx.pincode?.resendAllowedAt;
4341
5186
  const recipient = isEmail ? ctx.channel?.email : ctx.channel?.phone;
4342
- const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
4343
- await this.deliver({
4344
- kind: "enroll-pincode",
4345
- channel: isEmail ? "email" : "sms",
4346
- recipient,
4347
- code,
4348
- expiresInMs: this.opts.mfa.pincodeTtlMs
4349
- });
4350
- const pincode = ctx.pincode ??= {};
4351
- pincode.resendAllowedAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
4352
- pincode.sentTo = this.maskAddress(recipient, isEmail ? "email" : "sms");
4353
- pincode.codeLength = this.opts.mfa.pincodeLength;
5187
+ if (cooldown && cooldown > Date.now() || !await this.claimCodeSend(this.enrollTarget(ctx, recipient), ctx.subject)) throw this.throwPublic(ctx, pincodeWf, { formMessage: this.msg("AOOTH_RESEND_WAIT", { seconds: this.resendWaitSeconds(cooldown) }) });
5188
+ await this.sendChannelPincode(ctx, recipient, isEmail ? "email" : "sms", true);
4354
5189
  throw this.throwPublic(ctx, pincodeWf);
4355
5190
  }
4356
5191
  const input = pincodeWf.resolveInput();
4357
- const pinErr = this.verifyPin(ctx, input.code);
5192
+ const recipient = (isEmail ? ctx.channel?.email : ctx.channel?.phone) ?? "";
5193
+ const pinErr = await this.verifyPin(ctx, input.code, this.pinFor(ctx, recipient), this.enrollTarget(ctx, recipient));
4358
5194
  if (pinErr) throw this.throwPublic(ctx, pincodeWf, { errors: pinErr });
4359
5195
  await this.withStoreErrorTranslation(() => this.users.confirmMfaMethod(ctx.subject, isEmail ? "email" : "sms"));
4360
5196
  const channelState = ctx.channel ??= {};
@@ -4370,8 +5206,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4370
5206
  const target = isEmail ? channelState.email : channelState.phone;
4371
5207
  await this.consentStore.recordOtpChannelConsent(ctx.subject, channelArg, target, channelState.otpDisclosure);
4372
5208
  }
4373
- delete ctx.pin;
4374
- delete ctx.pinExpire;
5209
+ this.clearPin(ctx);
4375
5210
  if (ctx.pincode) {
4376
5211
  delete ctx.pincode.resendAllowedAt;
4377
5212
  delete ctx.pincode.sentTo;
@@ -4509,7 +5344,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4509
5344
  if (cooldownUntil && Date.now() < cooldownUntil) {
4510
5345
  const waitSec = Math.ceil((cooldownUntil - Date.now()) / 1e3);
4511
5346
  const channel = picked.kind === "sms" ? "SMS" : "email";
4512
- throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_CHANNEL", {
5347
+ throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_RESEND_WAIT_CHANNEL", {
4513
5348
  seconds: waitSec,
4514
5349
  channel
4515
5350
  }) });
@@ -4526,45 +5361,52 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4526
5361
  * `resolvePincodeTarget` (which discriminate on `ctx.mfa?.method` presence).
4527
5362
  */
4528
5363
  async pincodeSend(ctx) {
5364
+ const recovery = !ctx.mfa?.method && !ctx.signup;
5365
+ if (!ctx.mfa?.method) await enforceRateLimit(SEND_RATE_LIMIT);
4529
5366
  let target;
4530
- try {
5367
+ let account = null;
5368
+ if (recovery) {
5369
+ account = await this.recoveryAccount(ctx);
5370
+ target = await this.recoveryPincodeTarget(ctx, "typed");
5371
+ } else {
4531
5372
  const targetResult = this.resolvePincodeTarget(ctx);
4532
5373
  target = targetResult instanceof Promise ? await targetResult : targetResult;
4533
- } catch (err) {
4534
- if (err instanceof RecoveryMethodUnavailableError) {
4535
- ctx.aborted = true;
4536
- this.finishGenericRecovery();
4537
- return;
4538
- }
4539
- throw err;
4540
5374
  }
4541
- const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
4542
- if (ctx.mfa?.method) await this.deliver({
4543
- kind: "mfa-pincode",
4544
- channel: target.channel,
4545
- recipient: target.address,
4546
- code,
4547
- expiresInMs: this.opts.mfa.pincodeTtlMs
4548
- });
4549
- else if (ctx.signup) await this.deliver({
4550
- kind: "signup-pincode",
4551
- channel: "email",
4552
- recipient: target.address,
4553
- code,
4554
- expiresInMs: this.opts.mfa.pincodeTtlMs
4555
- });
4556
- else await this.deliver({
4557
- kind: "recovery-pincode",
4558
- channel: target.channel,
4559
- recipient: target.address,
4560
- code,
4561
- expiresInMs: this.opts.mfa.pincodeTtlMs
4562
- });
4563
- const otp = ctx.otp ??= {};
4564
- otp.deliveredTo = target.address;
4565
- otp.deliveredChannel = target.channel;
5375
+ const registeredRecovery = recovery && await this.recoveryDeliverySource(ctx) === "registered";
5376
+ const binding = recovery ? this.recoveryBinding(account) : this.pinFor(ctx, target.address);
5377
+ const deliver = await this.claimCodeSend(this.pincodeTarget(ctx, target.address), ctx.mfa?.method ? ctx.subject : void 0);
5378
+ const code = this.mintPin(ctx, binding);
5379
+ if (deliver) {
5380
+ if (ctx.mfa?.method) await this.dispatch({
5381
+ kind: "mfa-pincode",
5382
+ channel: target.channel,
5383
+ recipient: target.address,
5384
+ code,
5385
+ expiresInMs: this.opts.mfa.pincodeTtlMs
5386
+ });
5387
+ else if (ctx.signup) await this.dispatch({
5388
+ kind: "signup-pincode",
5389
+ channel: "email",
5390
+ recipient: target.address,
5391
+ code,
5392
+ expiresInMs: this.opts.mfa.pincodeTtlMs
5393
+ });
5394
+ else if (account) await this.dispatch({
5395
+ kind: "recovery-pincode",
5396
+ channel: account.channel,
5397
+ recipient: account.address,
5398
+ code,
5399
+ expiresInMs: this.opts.mfa.pincodeTtlMs
5400
+ });
5401
+ }
5402
+ if (!recovery) {
5403
+ const otp = ctx.otp ??= {};
5404
+ otp.deliveredTo = target.address;
5405
+ otp.deliveredChannel = target.channel;
5406
+ }
4566
5407
  const pincode = ctx.pincode ??= {};
4567
- pincode.sentTo = this.maskAddress(target.address, target.channel);
5408
+ if (registeredRecovery) delete pincode.sentTo;
5409
+ else pincode.sentTo = this.maskAddress(target.address, target.channel);
4568
5410
  pincode.codeLength = this.opts.mfa.pincodeLength;
4569
5411
  const cooldownAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
4570
5412
  pincode.resendAllowedAt = cooldownAt;
@@ -4581,12 +5423,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4581
5423
  if (action) {
4582
5424
  const outcome = this.resolvePincodeAltAction(ctx, action);
4583
5425
  if (outcome === "resend") {
4584
- if (ctx.pincode?.resendAllowedAt && ctx.pincode.resendAllowedAt > Date.now()) {
4585
- const remainingSec = Math.ceil((ctx.pincode.resendAllowedAt - Date.now()) / 1e3);
4586
- throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT", { seconds: remainingSec }) });
4587
- }
4588
- delete ctx.pin;
4589
- delete ctx.pinExpire;
5426
+ if (ctx.pincode?.resendAllowedAt && ctx.pincode.resendAllowedAt > Date.now() || await this.codeSendCoolingDown(this.pincodeTarget(ctx, ctx.otp?.deliveredTo))) throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_RESEND_WAIT", { seconds: this.resendWaitSeconds(ctx.pincode?.resendAllowedAt) }) });
5427
+ this.clearPin(ctx);
4590
5428
  return;
4591
5429
  }
4592
5430
  if (outcome === "exit") {
@@ -4598,8 +5436,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4598
5436
  ctx.mfa.ignoreDefault = true;
4599
5437
  delete ctx.mfa.method;
4600
5438
  }
4601
- delete ctx.pin;
4602
- delete ctx.pinExpire;
5439
+ this.clearPin(ctx);
4603
5440
  if (ctx.pincode) delete ctx.pincode.resendAllowedAt;
4604
5441
  return;
4605
5442
  }
@@ -4611,15 +5448,22 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4611
5448
  if (ctx.postReset && err instanceof StepRetriableError) throw this.stampRecoveryExpiry(err);
4612
5449
  throw err;
4613
5450
  }
4614
- const pinErr = this.verifyPin(ctx, input.code);
5451
+ const recovery = !ctx.mfa?.method && !ctx.signup;
5452
+ const account = recovery ? await this.recoveryAccount(ctx) : null;
5453
+ const binding = recovery ? this.recoveryBinding(account) : this.pinFor(ctx, ctx.otp?.deliveredTo ?? "");
5454
+ const pinErr = await this.verifyPin(ctx, recovery && !account ? NO_CODE : input.code, binding, this.pincodeTarget(ctx, ctx.otp?.deliveredTo));
4615
5455
  if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
4616
5456
  const otp = ctx.otp ??= {};
5457
+ if (account) {
5458
+ ctx.subject = account.subject;
5459
+ otp.deliveredTo = account.address;
5460
+ otp.deliveredChannel = account.channel;
5461
+ }
4617
5462
  otp.verified = true;
4618
5463
  if (ctx.subject && otp.deliveredChannel === "email" && otp.deliveredTo) await this.users.setVerifiedEmail(ctx.subject, otp.deliveredTo);
4619
5464
  (ctx.session ??= {}).riskStepUpEvaluated = false;
4620
5465
  if (ctx.deviceTrust?.enabled && ctx.deviceTrust?.optIn) (ctx.trust ??= {}).rememberDevice = Boolean(input.rememberDevice);
4621
- delete ctx.pin;
4622
- delete ctx.pinExpire;
5466
+ this.clearPin(ctx);
4623
5467
  }
4624
5468
  /**
4625
5469
  * TOTP MFA challenge step body. Verifies a TOTP code via `users.verifyMfa`
@@ -4643,12 +5487,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4643
5487
  if (ctx.deviceTrust?.enabled && ctx.deviceTrust?.optIn) (ctx.trust ??= {}).rememberDevice = Boolean(input.rememberDevice);
4644
5488
  } catch (err) {
4645
5489
  if (err instanceof UserAuthError) {
4646
- if (err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
4647
- if (err.type === "INACTIVE") throw this.throwPublic(ctx, wf, { errors: { code: this.msg("INVALID_CODE") } });
4648
- if (err.type === "MFA_NOT_CONFIGURED") throw new HttpError$1(400, "No TOTP MFA configured");
5490
+ if (err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_ACCOUNT_LOCKED") });
5491
+ if (err.type === "INACTIVE") throw this.throwPublic(ctx, wf, { errors: { code: this.msg("AOOTH_INVALID_CODE") } });
5492
+ if (err.type === "MFA_NOT_CONFIGURED") throw this.httpError(400, "TOTP_NOT_CONFIGURED");
4649
5493
  if (err.type === "MFA_INVALID") {
4650
- if (err.details?.lockEnds !== void 0) throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
4651
- throw this.throwPublic(ctx, wf, { errors: { code: this.msg("INVALID_CODE") } });
5494
+ if (err.details?.lockEnds !== void 0) throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_ACCOUNT_LOCKED") });
5495
+ throw this.throwPublic(ctx, wf, { errors: { code: this.msg("AOOTH_INVALID_CODE") } });
4652
5496
  }
4653
5497
  }
4654
5498
  throw err;
@@ -4691,7 +5535,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4691
5535
  return;
4692
5536
  }
4693
5537
  const picked = wf.resolveInput().method;
4694
- if (!m.availableTransports.includes(picked)) throw this.throwPublic(ctx, wf, { errors: { method: this.msg("UNKNOWN_METHOD") } });
5538
+ if (!m.availableTransports.includes(picked)) throw this.throwPublic(ctx, wf, { errors: { method: this.msg("AOOTH_UNKNOWN_METHOD") } });
4695
5539
  m.method = picked;
4696
5540
  }
4697
5541
  return this.provisionTotpSecret(ctx);
@@ -4824,18 +5668,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4824
5668
  if (action === "resend") {
4825
5669
  if (m.method === "totp") throw this.throwPublic(ctx, wf, { formMessage: this.msg("TOTP_RESEND_NOT_APPLICABLE") });
4826
5670
  const cooldown = ctx.pincode?.resendAllowedAt;
4827
- if (cooldown && Date.now() < cooldown) {
4828
- const waitSec = Math.ceil((cooldown - Date.now()) / 1e3);
4829
- throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_ANOTHER", { seconds: waitSec }) });
4830
- }
4831
- await this.mintAndSendEnrollPincode(ctx, m.address);
5671
+ if (cooldown && Date.now() < cooldown || !await this.claimCodeSend(this.enrollTarget(ctx, m.address), ctx.subject)) throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_RESEND_WAIT_ANOTHER", { seconds: this.resendWaitSeconds(cooldown) }) });
5672
+ await this.mintAndSendEnrollPincode(ctx, m.address, true);
4832
5673
  return;
4833
5674
  }
4834
5675
  const input = wf.resolveInput();
4835
5676
  if (m.method === "totp") {
4836
- if (verifyTotpCode(m.secret, input.code) === null) throw this.throwPublic(ctx, wf, { errors: { code: this.msg("INVALID_CODE") } });
5677
+ if (verifyTotpCode(m.secret, input.code) === null) throw this.throwPublic(ctx, wf, { errors: { code: this.msg("AOOTH_INVALID_CODE") } });
4837
5678
  } else {
4838
- const pinErr = this.verifyPin(ctx, input.code);
5679
+ const pinErr = await this.verifyPin(ctx, input.code, this.pinFor(ctx, m.address ?? ""), this.enrollTarget(ctx, m.address));
4839
5680
  if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
4840
5681
  }
4841
5682
  await this.confirmEnrolledFactor(ctx);
@@ -4865,8 +5706,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4865
5706
  if (!m.keepExistingDefault) await this.users.setDefaultMfaMethod(username, methodName);
4866
5707
  m.done = true;
4867
5708
  (ctx.otp ??= {}).verified = true;
4868
- delete ctx.pin;
4869
- delete ctx.pinExpire;
5709
+ this.clearPin(ctx);
4870
5710
  }
4871
5711
  /**
4872
5712
  * Promote a freshly-confirmed channel into its login-handle column so future
@@ -4920,8 +5760,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4920
5760
  if (res.require) {
4921
5761
  session.riskStepUpReason = res.reason ?? "additional verification required";
4922
5762
  if (ctx.otp) delete ctx.otp.verified;
4923
- delete ctx.pin;
4924
- delete ctx.pinExpire;
5763
+ this.clearPin(ctx);
4925
5764
  } else delete session.riskStepUpReason;
4926
5765
  }
4927
5766
  /**
@@ -5114,6 +5953,36 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5114
5953
  }
5115
5954
  }
5116
5955
  /**
5956
+ * Login-only guard before the `record-login` funnel: an account deactivated
5957
+ * or locked while the run was paused (MFA, enrolment, consents …) is not
5958
+ * stamped, announced or signed in — the run finishes with an error.
5959
+ */
5960
+ async checkCanSignIn(ctx) {
5961
+ await this.loginAccountBlocked(ctx);
5962
+ }
5963
+ /**
5964
+ * Whether the run's account can no longer sign in (deactivated, locked or
5965
+ * deleted since it authenticated). If so the run is finished with an error
5966
+ * (`AOOTH_ACCOUNT_LOCKED` for a lock unless `lockoutDisclosure` is
5967
+ * `'generic'`, else `INVALID_CREDENTIALS`) and `ctx.aborted` is set.
5968
+ */
5969
+ async loginAccountBlocked(ctx) {
5970
+ this.requireSubject(ctx);
5971
+ try {
5972
+ await this.users.assertCanSignIn(ctx.subject);
5973
+ return false;
5974
+ } catch (err) {
5975
+ if (!(err instanceof UserAuthError)) throw err;
5976
+ const locked = err.type === "LOCKED" && this.opts.lockoutDisclosure !== "generic";
5977
+ ctx.aborted = true;
5978
+ finishWf({ message: {
5979
+ level: "error",
5980
+ text: this.msg(locked ? "AOOTH_ACCOUNT_LOCKED" : "INVALID_CREDENTIALS")
5981
+ } });
5982
+ return true;
5983
+ }
5984
+ }
5985
+ /**
5117
5986
  * The SINGLE login-completion funnel. Every flow that establishes an
5118
5987
  * authenticated session routes through here — placed in each login schema
5119
5988
  * right after the guards and BEFORE the delivery terminal (`issue` /
@@ -5161,6 +6030,21 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5161
6030
  }
5162
6031
  }
5163
6032
  /**
6033
+ * Auto-login guard, ahead of `record-login` on every auto-login path (invite,
6034
+ * recovery, signup): never stamp a login, fire `afterLogin` or issue a
6035
+ * session for an account that is no longer active (deactivated meanwhile —
6036
+ * every flow reaching here activated or verified it first). Recovery and
6037
+ * invite fall back to the fresh-login finish (no session); signup fails.
6038
+ */
6039
+ async autoLoginCheck(ctx) {
6040
+ this.requireSubject(ctx);
6041
+ const { account } = await this.users.getUser(ctx.subject);
6042
+ if (account.active) return void 0;
6043
+ if (!ctx.postReset && !ctx.accept) throw new HttpError$1(403, "Account is not active");
6044
+ this.finalizeFreshLogin(ctx);
6045
+ ctx.autoLogin = false;
6046
+ }
6047
+ /**
5164
6048
  * Thin dispatcher steps for the flow-specific lifecycle hooks. Each is its own
5165
6049
  * schema step (rather than an in-terminal call) because its flow's finalize
5166
6050
  * terminals are SHARED across flows (`finalize-auto-login` serves invite +
@@ -5185,6 +6069,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5185
6069
  */
5186
6070
  async issue(ctx) {
5187
6071
  this.requireSubject(ctx);
6072
+ try {
6073
+ await this.users.assertCanSignIn(ctx.subject);
6074
+ } catch (err) {
6075
+ if (err instanceof UserAuthError) throw new HttpError$1(403, "Account cannot sign in");
6076
+ throw err;
6077
+ }
5188
6078
  const issue = await this.issueForContext(ctx);
5189
6079
  const auth = useAuth();
5190
6080
  const envelope = {
@@ -5227,7 +6117,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5227
6117
  async notifyNewDevice(ctx) {
5228
6118
  const recipient = ctx.notice?.email;
5229
6119
  if (!recipient) return void 0;
5230
- await this.deliver({
6120
+ await this.dispatch({
5231
6121
  kind: "new-device-notice",
5232
6122
  channel: "email",
5233
6123
  recipient,
@@ -5363,6 +6253,10 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5363
6253
  } });
5364
6254
  return;
5365
6255
  }
6256
+ if (await this.loginAccountBlocked(ctx)) {
6257
+ await pending.delete(handle);
6258
+ return;
6259
+ }
5366
6260
  const { code } = await codes.mint({
5367
6261
  userId: ctx.subject,
5368
6262
  codeChallenge: req.codeChallenge,
@@ -5465,7 +6359,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5465
6359
  target,
5466
6360
  reason: "reset-success"
5467
6361
  },
5468
- skipButton: { label: this.msg("GO_NOW") }
6362
+ skipButton: { label: this.msg("AOOTH_GO_NOW") }
5469
6363
  }
5470
6364
  });
5471
6365
  (ctx.completion ??= {}).redirectUrl = target;
@@ -5478,13 +6372,14 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5478
6372
  * tokens (WF-INVITE-020).
5479
6373
  *
5480
6374
  * It records NOTHING and guards NOTHING: `account.lastLogin` + the
5481
- * `afterLogin` hook are owned by the upstream `record-login` funnel step, and
5482
- * the admin-only-survived-lock guard by the upstream `recovery-lock-check`
5483
- * step — both of which `{ break }`/gate this step out when they apply, so a
5484
- * still-frozen account never reaches here.
6375
+ * `afterLogin` hook are owned by the upstream `record-login` funnel step,
6376
+ * the inactive-account guard by `auto-login-check`, and the
6377
+ * admin-only-survived-lock guard by `recovery-lock-check` — all upstream, so
6378
+ * an inactive or still-frozen account never reaches here.
5485
6379
  */
5486
6380
  async finalizeAutoLogin(ctx) {
5487
6381
  this.requireSubject(ctx);
6382
+ if (!(await this.users.getUser(ctx.subject)).account.active) throw new HttpError$1(403, "Account is not active");
5488
6383
  const issue = await this.issueForContext(ctx);
5489
6384
  const auth = useAuth();
5490
6385
  const previousMessage = (useWfFinished().get()?.value)?.message;
@@ -5587,7 +6482,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5587
6482
  finishWf({
5588
6483
  message: {
5589
6484
  level: "info",
5590
- text: this.msg("ALREADY_HAVE_ACCOUNT")
6485
+ text: this.msg("AOOTH_ALREADY_HAVE_ACCOUNT")
5591
6486
  },
5592
6487
  next: {
5593
6488
  trigger: "immediate",
@@ -5607,9 +6502,215 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5607
6502
  * the freshly-created `ctx.subject`. Mirrors login's `extra-step` seam.
5608
6503
  */
5609
6504
  signupExtraStep(_ctx) {}
5610
- magicLinkRequest(_ctx) {}
5611
- magicLinkSend(_ctx) {}
5612
- magicLinkVerified(_ctx) {}
6505
+ /**
6506
+ * Login's `magicLink` alt-action: the identifier form. Resolves the account
6507
+ * (unknown, inactive or locked identifiers resolve to none — the answer is
6508
+ * the same) and hands over to `magic-link-send`.
6509
+ */
6510
+ async magicLinkRequest(ctx) {
6511
+ const ml = ctx.magicLink;
6512
+ if (!ml || ml.purpose !== "login" || ml.sentAt !== void 0) return void 0;
6513
+ const { identifier } = this.useAtscriptWfPublic(ctx, this.opts.forms.magicLinkRequest).resolveInput();
6514
+ const user = await this.users.findByHandle(identifier.trim());
6515
+ if (user) ml.subject = user.id;
6516
+ ml.identifier = identifier.trim().toLowerCase();
6517
+ }
6518
+ /**
6519
+ * Send a magic link (recovery or sign-in) and pause until it is used. The
6520
+ * pause is persisted under the `magic-link` strategy — a fresh, hashed,
6521
+ * single-use handle that expires with the link (`magicLinkTtlMs`) — and the
6522
+ * `magic-link` outlet hands the token to the email outlet only. Known and
6523
+ * unknown identifiers take the same path and get the same answer; nothing is
6524
+ * sent for an unknown identifier, an account without a proven inbox, a
6525
+ * sign-in the account may not start (inactive, locked), or a repeat within
6526
+ * `mfa.pincodeResendTimeoutMs`. The click resumes here and moves on to the
6527
+ * purpose's verify step.
6528
+ */
6529
+ async magicLinkSend(ctx) {
6530
+ const ml = ctx.magicLink;
6531
+ if (!ml || ml.sentAt !== void 0) return void 0;
6532
+ await enforceRateLimit(SEND_RATE_LIMIT);
6533
+ const now = Date.now();
6534
+ ml.sentAt = now;
6535
+ ml.expiresAt = now + this.opts.magicLinkTtlMs;
6536
+ const address = await this.magicLinkAddress(ctx, ml);
6537
+ if (address) ml.address = address;
6538
+ const cooldownKey = sha256url(`${ml.purpose}|${ml.subject ?? ml.identifier ?? ""}`);
6539
+ const sends = await this.opts.lockoutShadowStore.hit(`${MAGIC_LINK_SEND_PREFIX}${cooldownKey}`, this.opts.mfa.pincodeResendTimeoutMs);
6540
+ const deliver = !!address && sends === 1;
6541
+ delete ml.identifier;
6542
+ if (ml.purpose === "login" && ctx.alternateCredentials?.magicLinkSameBrowser) ml.browser = this.bindMagicLinkBrowser();
6543
+ swapStrategy(MAGIC_LINK_STRATEGY);
6544
+ return {
6545
+ ...outlet(MAGIC_LINK_OUTLET, {
6546
+ target: deliver ? address : "",
6547
+ template: ml.purpose === "recovery" ? "recovery.magicLink" : "login.magicLink",
6548
+ context: {
6549
+ deliver,
6550
+ expiresAtMs: this.opts.magicLinkTtlMs
6551
+ }
6552
+ }),
6553
+ expires: ml.expiresAt
6554
+ };
6555
+ }
6556
+ /**
6557
+ * Where a magic link may go — an inbox the account proved, or `undefined`
6558
+ * (nothing is sent). Recovery with the typed identifier as destination (M1,
6559
+ * email channel) sends to the typed address, like the recovery code; every
6560
+ * other case sends to the account's proven inbox: `account.verifiedEmail`,
6561
+ * else a confirmed email MFA method — never an unproven address. The account
6562
+ * must be active; a sign-in link also needs it unlocked (a recovery link may
6563
+ * go to a locked account — self-service unlock). Override to change the
6564
+ * destination.
6565
+ */
6566
+ async magicLinkAddress(ctx, ml) {
6567
+ let user;
6568
+ try {
6569
+ user = ml.purpose === "login" ? await this.users.assertCanSignIn(ml.subject ?? UNKNOWN_ACCOUNT_ID) : await this.users.getUser(ml.subject ?? UNKNOWN_ACCOUNT_ID);
6570
+ } catch (err) {
6571
+ if (err instanceof UserAuthError) return void 0;
6572
+ throw err;
6573
+ }
6574
+ if (!ml.subject || !user.account.active) return void 0;
6575
+ if (ml.purpose === "recovery" && await this.recoveryDeliverySource(ctx) === "typed") {
6576
+ const typed = await this.recoveryPincodeTarget(ctx, "typed");
6577
+ return typed.channel === "email" && typed.address ? typed.address : void 0;
6578
+ }
6579
+ return user.account.verifiedEmail ?? user.mfa.methods.find((m) => m.name === "email" && m.confirmed)?.value;
6580
+ }
6581
+ /**
6582
+ * The landing step of a clicked link: "Continue as a•••@example.com". Opening
6583
+ * the link (or a mail scanner fetching it) only renders this step — the
6584
+ * pause stays on the link's own handle, so the link still works; it is used
6585
+ * up only when this form is submitted. The masked account lets the user see
6586
+ * which account the link signs into (a forwarded link would be someone
6587
+ * else's).
6588
+ */
6589
+ magicLinkConfirm(ctx) {
6590
+ const ml = ctx.magicLink;
6591
+ if (!ml?.sentAt || ml.confirmed) return void 0;
6592
+ const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.magicLinkConfirm);
6593
+ try {
6594
+ wf.resolveInput();
6595
+ } catch (err) {
6596
+ if (err instanceof StepRetriableError) err.expires = ml.expiresAt;
6597
+ throw err;
6598
+ }
6599
+ ml.confirmed = true;
6600
+ }
6601
+ /** Name of the cookie binding a sign-in link to the browser that asked for it. */
6602
+ magicLinkBrowserCookie() {
6603
+ return MAGIC_LINK_BROWSER_COOKIE;
6604
+ }
6605
+ /** Set the browser-binding cookie; returns the hash the link keeps. */
6606
+ bindMagicLinkBrowser() {
6607
+ const nonce = randomBytes(24).toString("base64url");
6608
+ useResponse(current()).setCookie(this.magicLinkBrowserCookie(), nonce, authzBindingCookieAttrs({
6609
+ secure: useAuth().options.cookie.secure,
6610
+ maxAgeSec: Math.ceil(this.opts.magicLinkTtlMs / 1e3)
6611
+ }));
6612
+ return sha256url(nonce);
6613
+ }
6614
+ /** Whether this request carries the browser-binding cookie the link was sent with. */
6615
+ sameMagicLinkBrowser(expected) {
6616
+ const cookie = useCookies(current()).getCookie(this.magicLinkBrowserCookie());
6617
+ if (!cookie) return false;
6618
+ return safeEqual(sha256url(cookie), expected);
6619
+ }
6620
+ /**
6621
+ * A used sign-in link: the FIRST factor only. Re-checks the account
6622
+ * (active, not locked), binds `ctx.subject` and leaves the second factor to
6623
+ * the MFA loop, exactly as after a password. Refuses a link of another
6624
+ * purpose, an expired one, and one sent for no account.
6625
+ */
6626
+ async magicLinkVerified(ctx) {
6627
+ const ml = this.usedMagicLink(ctx, "login");
6628
+ if (!ml) return void 0;
6629
+ if (!ml.subject || ml.browser && !this.sameMagicLinkBrowser(ml.browser)) {
6630
+ this.finishMagicLinkInvalid(ctx);
6631
+ return;
6632
+ }
6633
+ let user;
6634
+ try {
6635
+ user = await this.users.assertCanSignIn(ml.subject);
6636
+ } catch (err) {
6637
+ if (!(err instanceof UserAuthError)) throw err;
6638
+ this.finishMagicLinkInvalid(ctx);
6639
+ return;
6640
+ }
6641
+ ctx.subject = user.id;
6642
+ const guardsResult = this.resolveGuards(ctx);
6643
+ ctx.guards = guardsResult instanceof Promise ? await guardsResult : guardsResult;
6644
+ await this.bindSignedInUser(ctx, user);
6645
+ }
6646
+ /**
6647
+ * A used recovery link: proof of the inbox it went to, exactly like a
6648
+ * verified recovery code — `ctx.otp.verified` set, the inbox recorded as
6649
+ * the account's verified email, and the flow goes on to the new password.
6650
+ * Refuses a link of another purpose, an expired one, one sent for no
6651
+ * account, and one whose account is no longer active.
6652
+ */
6653
+ async recoveryLinkVerified(ctx) {
6654
+ const ml = this.usedMagicLink(ctx, "recovery");
6655
+ if (!ml) return void 0;
6656
+ let active = false;
6657
+ if (ml.subject && ml.address) try {
6658
+ active = (await this.users.getUser(ml.subject)).account.active;
6659
+ } catch (err) {
6660
+ if (!(err instanceof UserAuthError)) throw err;
6661
+ }
6662
+ if (!active || !ml.subject || !ml.address) {
6663
+ this.finishMagicLinkInvalid(ctx);
6664
+ return;
6665
+ }
6666
+ ctx.subject = ml.subject;
6667
+ const otp = ctx.otp ??= {};
6668
+ otp.verified = true;
6669
+ otp.deliveredTo = ml.address;
6670
+ otp.deliveredChannel = "email";
6671
+ await this.users.setVerifiedEmail(ml.subject, ml.address);
6672
+ }
6673
+ /**
6674
+ * The magic link this run was resumed through, checked for `purpose` and
6675
+ * expiry — or `undefined` after emitting the "invalid link" finish. Swaps
6676
+ * off the `magic-link` strategy first, so the link's token is never the
6677
+ * continuation (the next pause gets a fresh handle).
6678
+ */
6679
+ usedMagicLink(ctx, purpose) {
6680
+ const ml = ctx.magicLink;
6681
+ if (!ml?.sentAt) return void 0;
6682
+ swapStrategy("store");
6683
+ if (ml.purpose !== purpose || !ml.expiresAt || Date.now() > ml.expiresAt) {
6684
+ this.finishMagicLinkInvalid(ctx);
6685
+ return;
6686
+ }
6687
+ return ml;
6688
+ }
6689
+ /** The finish of a link that cannot be used (wrong purpose, expired, no account). */
6690
+ finishMagicLinkInvalid(ctx) {
6691
+ ctx.aborted = true;
6692
+ finishWf({ message: {
6693
+ level: "error",
6694
+ text: this.msg("AOOTH_MAGIC_LINK_INVALID")
6695
+ } });
6696
+ }
6697
+ /**
6698
+ * Recovery's `'choice'` delivery: the user picks a magic link or a one-time
6699
+ * code. Shown for known and unknown identifiers alike. A one-time code for
6700
+ * an unknown identifier runs the ghost OTP pause, like the default path.
6701
+ */
6702
+ async selectRecoveryMode(ctx) {
6703
+ const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.recoveryModeSelect);
6704
+ let mode;
6705
+ try {
6706
+ ({mode} = wf.resolveInput());
6707
+ } catch (err) {
6708
+ if (err instanceof StepRetriableError) throw this.stampRecoveryExpiry(err);
6709
+ throw err;
6710
+ }
6711
+ if (mode !== "magicLink" && mode !== "otp") throw this.throwPublic(ctx, wf, { errors: { mode: this.msg("AOOTH_CHOOSE_OPTION") } });
6712
+ await this.applyRecoveryMode(ctx, mode);
6713
+ }
5613
6714
  passkey(_ctx) {}
5614
6715
  /**
5615
6716
  * Verify the OAuth callback and resolve a user. Reaches here (instead of
@@ -5669,7 +6770,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5669
6770
  finishWf({
5670
6771
  message: {
5671
6772
  level: "success",
5672
- text: this.msg("ACCOUNT_LINKED")
6773
+ text: this.msg("AOOTH_ACCOUNT_LINKED")
5673
6774
  },
5674
6775
  next: {
5675
6776
  trigger: "immediate",
@@ -5820,11 +6921,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5820
6921
  * the confirmed channel vanished between resolve and dispatch (the caller
5821
6922
  * routes that to the safe generic terminal).
5822
6923
  */
5823
- async deliverPendingLinkPin(candidate, pending) {
6924
+ async deliverPendingLinkPin(candidate, pending, claimed) {
5824
6925
  const method = candidate.mfa.methods.find((m) => m.name === pending.otpChannel && m.confirmed);
5825
6926
  if (!method) return null;
5826
- const code = this.mintPin(pending, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
5827
- await this.deliver({
6927
+ const deliver = claimed ?? await this.claimCodeSend(this.linkTarget(pending), pending.candidateUserId);
6928
+ const code = this.mintPin(pending, pending.candidateUserId);
6929
+ if (deliver) await this.dispatch({
5828
6930
  kind: "mfa-pincode",
5829
6931
  channel: pending.otpChannel,
5830
6932
  recipient: method.value,
@@ -5882,11 +6984,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5882
6984
  }
5883
6985
  if (isOtp && action === "resend") {
5884
6986
  const cooldown = pending.resendAllowedAt;
5885
- if (cooldown && Date.now() < cooldown) {
5886
- const waitSec = Math.ceil((cooldown - Date.now()) / 1e3);
5887
- throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_ANOTHER", { seconds: waitSec }) });
5888
- }
5889
- const sentTo = await this.deliverPendingLinkPin(candidate, pending);
6987
+ if (cooldown && Date.now() < cooldown || !await this.claimCodeSend(this.linkTarget(pending), pending.candidateUserId)) throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_RESEND_WAIT_ANOTHER", { seconds: this.resendWaitSeconds(cooldown) }) });
6988
+ const sentTo = await this.deliverPendingLinkPin(candidate, pending, true);
5890
6989
  if (sentTo === null) {
5891
6990
  delete ctx.pendingLink;
5892
6991
  return this.finishOAuth(ctx, "needs-link");
@@ -5896,12 +6995,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5896
6995
  }
5897
6996
  const input = wf.resolveInput();
5898
6997
  if (isOtp) {
5899
- const pinErr = this.verifyPin(pending, input.code);
6998
+ const pinErr = await this.verifyPin(pending, input.code, pending.candidateUserId, this.linkTarget(pending));
5900
6999
  if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
5901
7000
  } else try {
5902
7001
  await this.users.login(candidate.username, input.password ?? "", this.lockoutOverride(ctx));
5903
7002
  } catch (err) {
5904
- if (err instanceof UserAuthError && err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
7003
+ if (err instanceof UserAuthError && err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_ACCOUNT_LOCKED") });
5905
7004
  throw this.throwPublic(ctx, wf, { errors: { password: this.msg("INVALID_PASSWORD") } });
5906
7005
  }
5907
7006
  if (this.isAccountBlocked(candidate)) {
@@ -5947,8 +7046,9 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5947
7046
  */
5948
7047
  inviteFlow() {}
5949
7048
  /**
5950
- * recovery.flow — OTP-via-email reset. `@Public()` on the body because
5951
- * anonymous users start recovery.
7049
+ * recovery.flow — reset by a one-time code or a magic link
7050
+ * (`resolveRecoveryDeliveryMode`). `@Public()` on the body because anonymous
7051
+ * users start recovery.
5952
7052
  */
5953
7053
  recoveryFlow() {}
5954
7054
  /**
@@ -6638,6 +7738,14 @@ __decorate([
6638
7738
  __decorateMetadata("design:paramtypes", [Object]),
6639
7739
  __decorateMetadata("design:returntype", Promise)
6640
7740
  ], AuthWorkflow.prototype, "checkPasswordUnchanged", null);
7741
+ __decorate([
7742
+ Step("check-can-sign-in"),
7743
+ Public(),
7744
+ __decorateParam(0, WorkflowParam("context")),
7745
+ __decorateMetadata("design:type", Function),
7746
+ __decorateMetadata("design:paramtypes", [Object]),
7747
+ __decorateMetadata("design:returntype", Promise)
7748
+ ], AuthWorkflow.prototype, "checkCanSignIn", null);
6641
7749
  __decorate([
6642
7750
  Step("record-login"),
6643
7751
  Public(),
@@ -6654,6 +7762,14 @@ __decorate([
6654
7762
  __decorateMetadata("design:paramtypes", [Object]),
6655
7763
  __decorateMetadata("design:returntype", Promise)
6656
7764
  ], AuthWorkflow.prototype, "recoveryLockCheck", null);
7765
+ __decorate([
7766
+ Step("auto-login-check"),
7767
+ Public(),
7768
+ __decorateParam(0, WorkflowParam("context")),
7769
+ __decorateMetadata("design:type", Function),
7770
+ __decorateMetadata("design:paramtypes", [Object]),
7771
+ __decorateMetadata("design:returntype", Promise)
7772
+ ], AuthWorkflow.prototype, "autoLoginCheck", null);
6657
7773
  __decorate([
6658
7774
  Step("after-invitation-accepted"),
6659
7775
  Public(),
@@ -6772,7 +7888,7 @@ __decorate([
6772
7888
  __decorateParam(0, WorkflowParam("context")),
6773
7889
  __decorateMetadata("design:type", Function),
6774
7890
  __decorateMetadata("design:paramtypes", [Object]),
6775
- __decorateMetadata("design:returntype", Object)
7891
+ __decorateMetadata("design:returntype", Promise)
6776
7892
  ], AuthWorkflow.prototype, "magicLinkRequest", null);
6777
7893
  __decorate([
6778
7894
  Step("magic-link-send"),
@@ -6780,16 +7896,40 @@ __decorate([
6780
7896
  __decorateParam(0, WorkflowParam("context")),
6781
7897
  __decorateMetadata("design:type", Function),
6782
7898
  __decorateMetadata("design:paramtypes", [Object]),
6783
- __decorateMetadata("design:returntype", Object)
7899
+ __decorateMetadata("design:returntype", Promise)
6784
7900
  ], AuthWorkflow.prototype, "magicLinkSend", null);
6785
7901
  __decorate([
6786
- Step("magic-link-verified"),
7902
+ Step("magic-link-confirm"),
6787
7903
  Public(),
6788
7904
  __decorateParam(0, WorkflowParam("context")),
6789
7905
  __decorateMetadata("design:type", Function),
6790
7906
  __decorateMetadata("design:paramtypes", [Object]),
6791
7907
  __decorateMetadata("design:returntype", Object)
7908
+ ], AuthWorkflow.prototype, "magicLinkConfirm", null);
7909
+ __decorate([
7910
+ Step("magic-link-verified"),
7911
+ Public(),
7912
+ __decorateParam(0, WorkflowParam("context")),
7913
+ __decorateMetadata("design:type", Function),
7914
+ __decorateMetadata("design:paramtypes", [Object]),
7915
+ __decorateMetadata("design:returntype", Promise)
6792
7916
  ], AuthWorkflow.prototype, "magicLinkVerified", null);
7917
+ __decorate([
7918
+ Step("recovery-link-verified"),
7919
+ Public(),
7920
+ __decorateParam(0, WorkflowParam("context")),
7921
+ __decorateMetadata("design:type", Function),
7922
+ __decorateMetadata("design:paramtypes", [Object]),
7923
+ __decorateMetadata("design:returntype", Promise)
7924
+ ], AuthWorkflow.prototype, "recoveryLinkVerified", null);
7925
+ __decorate([
7926
+ Step("select-recovery-mode"),
7927
+ Public(),
7928
+ __decorateParam(0, WorkflowParam("context")),
7929
+ __decorateMetadata("design:type", Function),
7930
+ __decorateMetadata("design:paramtypes", [Object]),
7931
+ __decorateMetadata("design:returntype", Promise)
7932
+ ], AuthWorkflow.prototype, "selectRecoveryMode", null);
6793
7933
  __decorate([
6794
7934
  Step("passkey"),
6795
7935
  Public(),
@@ -6825,7 +7965,19 @@ __decorate([
6825
7965
  },
6826
7966
  {
6827
7967
  id: "credentials",
6828
- condition: (ctx) => !ctx.idpInbound && !ctx.subject
7968
+ condition: (ctx) => !ctx.idpInbound && !ctx.subject && !ctx.magicLink
7969
+ },
7970
+ {
7971
+ condition: (ctx) => ctx.magicLink?.purpose === "login" && !ctx.subject,
7972
+ steps: [
7973
+ { id: "magic-link-request" },
7974
+ { id: "magic-link-send" },
7975
+ { id: "magic-link-confirm" },
7976
+ {
7977
+ id: "magic-link-verified",
7978
+ condition: (ctx) => !ctx.aborted
7979
+ }
7980
+ ]
6829
7981
  },
6830
7982
  {
6831
7983
  id: "prove-control",
@@ -6845,12 +7997,7 @@ __decorate([
6845
7997
  { break: (ctx) => !!ctx.aborted },
6846
7998
  {
6847
7999
  condition: () => false,
6848
- steps: [
6849
- { id: "magic-link-request" },
6850
- { id: "magic-link-send" },
6851
- { id: "magic-link-verified" },
6852
- { id: "passkey" }
6853
- ]
8000
+ steps: [{ id: "passkey" }]
6854
8001
  },
6855
8002
  {
6856
8003
  id: "ask/email",
@@ -6898,6 +8045,10 @@ __decorate([
6898
8045
  id: "check-password-unchanged",
6899
8046
  condition: (ctx) => ctx.passwordStamp !== void 0 && !ctx.passwordChanged
6900
8047
  },
8048
+ {
8049
+ id: "check-can-sign-in",
8050
+ condition: (ctx) => !!ctx.subject && !ctx.aborted
8051
+ },
6901
8052
  { break: (ctx) => !!ctx.aborted },
6902
8053
  {
6903
8054
  id: "record-login",
@@ -6999,6 +8150,10 @@ __decorate([
6999
8150
  id: "finalize-fresh-login",
7000
8151
  condition: (ctx) => !ctx.autoLogin
7001
8152
  },
8153
+ {
8154
+ id: "auto-login-check",
8155
+ condition: (ctx) => !!ctx.autoLogin
8156
+ },
7002
8157
  {
7003
8158
  id: "record-login",
7004
8159
  condition: (ctx) => !!ctx.autoLogin
@@ -7020,11 +8175,22 @@ __decorate([
7020
8175
  WorkflowSchema([
7021
8176
  { id: "init-recovery" },
7022
8177
  { id: "request" },
7023
- { break: (ctx) => !ctx.subject },
8178
+ {
8179
+ id: "select-recovery-mode",
8180
+ condition: (ctx) => ctx.recoveryDelivery === "choice"
8181
+ },
8182
+ {
8183
+ condition: (ctx) => ctx.recoveryDelivery === "magicLink",
8184
+ steps: [
8185
+ { id: "magic-link-send" },
8186
+ { id: "magic-link-confirm" },
8187
+ { id: "recovery-link-verified" }
8188
+ ]
8189
+ },
8190
+ { break: (ctx) => !!ctx.aborted || !ctx.subject && ctx.recoveryDelivery !== "otp" },
7024
8191
  { id: "prepare-post-reset" },
7025
8192
  { id: "prepare-recovery-alt-actions" },
7026
8193
  { id: "prepare-lockout" },
7027
- { id: "prepare-consents" },
7028
8194
  { id: "prepare-semantic-flags" },
7029
8195
  {
7030
8196
  while: (ctx) => !ctx.otp?.verified && !ctx.aborted,
@@ -7033,7 +8199,11 @@ __decorate([
7033
8199
  { break: (ctx) => !!ctx.aborted },
7034
8200
  {
7035
8201
  condition: (ctx) => !!ctx.otp?.verified,
7036
- steps: [{ id: "prepare-password-rules" }, { id: "create-password-form" }]
8202
+ steps: [
8203
+ { id: "prepare-consents" },
8204
+ { id: "prepare-password-rules" },
8205
+ { id: "create-password-form" }
8206
+ ]
7037
8207
  },
7038
8208
  { break: (ctx) => !!ctx.aborted },
7039
8209
  {
@@ -7055,6 +8225,10 @@ __decorate([
7055
8225
  id: "finalize-fresh-login",
7056
8226
  condition: (ctx) => !ctx.autoLogin
7057
8227
  },
8228
+ {
8229
+ id: "auto-login-check",
8230
+ condition: (ctx) => !!ctx.autoLogin
8231
+ },
7058
8232
  {
7059
8233
  id: "record-login",
7060
8234
  condition: (ctx) => !!ctx.autoLogin
@@ -7156,6 +8330,7 @@ __decorate([
7156
8330
  ...consentsPersistTailSchema,
7157
8331
  { id: "signup-extra-step" },
7158
8332
  { id: "after-signup" },
8333
+ { id: "auto-login-check" },
7159
8334
  { id: "record-login" },
7160
8335
  { id: "finalize-auto-login" }
7161
8336
  ]),
@@ -7196,14 +8371,18 @@ const CHANGE_PASSWORD_WORKFLOW = "auth/change-password/flow";
7196
8371
  const ADD_MFA_WORKFLOW = "auth/add-mfa/flow";
7197
8372
  /** The post-redemption route's single "not found" answer. */
7198
8373
  function inviteNotFound() {
7199
- return new HttpError$1(404, "Invite not found");
7200
- }
7201
- /** Prefer an explicit body field, fall back to the refresh cookie when enabled. */
7202
- function resolveRefreshToken(auth, body) {
7203
- if (typeof body?.refreshToken === "string") return body.refreshToken;
7204
- if (!auth.options.enableCookie) return void 0;
7205
- return useCookies(current()).getCookie(auth.options.refreshCookie.name) ?? void 0;
8374
+ return aoothHttpError(404, "INVITE_NOT_FOUND");
7206
8375
  }
8376
+ /**
8377
+ * Default rate limits of `POST /auth/refresh` (see `refresh()`), by policy id —
8378
+ * re-tune or switch one off with `rateLimitInterceptors({ policies })`.
8379
+ */
8380
+ const REFRESH_RATE_LIMITS = {
8381
+ /** Per client IP — bounds the token lookups any one caller can force. */
8382
+ "aooth.refresh": "150/5m",
8383
+ /** Per presented refresh token, from any IP — bounds re-presenting one token. */
8384
+ "aooth.refresh-token": "10/1m"
8385
+ };
7207
8386
  let AuthController = class AuthController {
7208
8387
  auth;
7209
8388
  users;
@@ -7229,13 +8408,13 @@ let AuthController = class AuthController {
7229
8408
  }
7230
8409
  async logout(body) {
7231
8410
  const auth = useAuth();
7232
- if (!auth.getAuthContext()) throw new HttpError$1(401, "Not authenticated");
8411
+ if (!auth.getAuthContext()) throw aoothHttpError(401, "AOOTH_NOT_AUTHENTICATED");
7233
8412
  const sessionId = auth.getSessionId();
7234
8413
  if (sessionId) try {
7235
8414
  await this.auth.revokeSession(auth.getUserId(), sessionId);
7236
8415
  } catch {}
7237
8416
  const accessToken = auth.extractToken();
7238
- const refreshToken = resolveRefreshToken(auth, body);
8417
+ const refreshToken = resolveRefreshToken(auth.options, body);
7239
8418
  if (accessToken) try {
7240
8419
  await this.auth.revoke(accessToken);
7241
8420
  } catch {}
@@ -7245,10 +8424,18 @@ let AuthController = class AuthController {
7245
8424
  auth.clearCookies();
7246
8425
  return { ok: true };
7247
8426
  }
8427
+ /**
8428
+ * Rotate the access/refresh pair. Rate limited by two policies, enforced
8429
+ * when `rateLimitInterceptors` are installed ({@link REFRESH_RATE_LIMITS}):
8430
+ * `aooth.refresh` per client IP (checked before the auth guard, so a flood
8431
+ * of junk tokens costs no lookups), and `aooth.refresh-token` per presented
8432
+ * refresh token from any IP (a request without one skips it — the handler
8433
+ * answers 401).
8434
+ */
7248
8435
  async refresh(body) {
7249
8436
  const auth = useAuth();
7250
- const refreshToken = resolveRefreshToken(auth, body);
7251
- if (!refreshToken) throw new HttpError$1(401, "Missing refresh token");
8437
+ const refreshToken = resolveRefreshToken(auth.options, body);
8438
+ if (!refreshToken) throw aoothHttpError(401, "MISSING_REFRESH_TOKEN");
7252
8439
  const fromBody = typeof body?.refreshToken === "string";
7253
8440
  let issue;
7254
8441
  try {
@@ -7256,7 +8443,7 @@ let AuthController = class AuthController {
7256
8443
  } catch (err) {
7257
8444
  if (!(err instanceof AuthError)) throw err;
7258
8445
  if (!fromBody) auth.clearCookies();
7259
- throw new HttpError$1(401, "Invalid refresh token");
8446
+ throw aoothHttpError(401, "INVALID_REFRESH_TOKEN");
7260
8447
  }
7261
8448
  auth.writeCookies(issue);
7262
8449
  const validated = await this.auth.validate(issue.accessToken);
@@ -7264,7 +8451,7 @@ let AuthController = class AuthController {
7264
8451
  }
7265
8452
  status() {
7266
8453
  const auth = useAuth().getAuthContext();
7267
- if (!auth) throw new HttpError$1(401, "Not authenticated");
8454
+ if (!auth) throw aoothHttpError(401, "AOOTH_NOT_AUTHENTICATED");
7268
8455
  return auth;
7269
8456
  }
7270
8457
  triggerWf() {}
@@ -7313,7 +8500,7 @@ let AuthController = class AuthController {
7313
8500
  */
7314
8501
  async invitePostRedemption(uid) {
7315
8502
  if (!this.invitePostRedemptionEnabled()) throw inviteNotFound();
7316
- if (!uid) throw new HttpError$1(400, "Missing uid query parameter");
8503
+ if (!uid) throw aoothHttpError(400, "AOOTH_MISSING_UID");
7317
8504
  if (!this.users) throw new HttpError$1(500, "UserService not wired — cannot resolve post-redemption state");
7318
8505
  let user;
7319
8506
  try {
@@ -7368,6 +8555,11 @@ __decorate([
7368
8555
  __decorate([
7369
8556
  Post("refresh"),
7370
8557
  Public(),
8558
+ RateLimit(REFRESH_RATE_LIMITS["aooth.refresh"], { id: "aooth.refresh" }),
8559
+ RateLimit(REFRESH_RATE_LIMITS["aooth.refresh-token"], {
8560
+ key: "refresh-token",
8561
+ id: "aooth.refresh-token"
8562
+ }),
7371
8563
  __decorateParam(0, Body()),
7372
8564
  __decorateMetadata("design:type", Function),
7373
8565
  __decorateMetadata("design:paramtypes", [Object]),
@@ -7409,7 +8601,7 @@ __decorate([
7409
8601
  __decorate([
7410
8602
  Get("invite/post-redemption"),
7411
8603
  Public(),
7412
- RateLimit("30/5m"),
8604
+ RateLimit("30/5m", { id: "aooth.invite-post-redemption" }),
7413
8605
  __decorateParam(0, Query("uid")),
7414
8606
  __decorateMetadata("design:type", Function),
7415
8607
  __decorateMetadata("design:paramtypes", [Object]),
@@ -7467,10 +8659,10 @@ let SessionsController = class SessionsController {
7467
8659
  * sessions (including the current one) is what `POST /auth/logout` is for.
7468
8660
  */
7469
8661
  async revokeOthers(others) {
7470
- if (others !== "true") throw new HttpError$1(400, "Pass ?others=true to log out other sessions");
8662
+ if (others !== "true") throw aoothHttpError(400, "LOGOUT_OTHERS_REQUIRED");
7471
8663
  const auth = useAuth();
7472
8664
  const current = auth.getSessionId();
7473
- if (!current) throw new HttpError$1(401, "No current session to keep");
8665
+ if (!current) throw aoothHttpError(401, "NO_CURRENT_SESSION");
7474
8666
  return { revoked: await this.auth.revokeOtherSessions(auth.getUserId(), current) };
7475
8667
  }
7476
8668
  };
@@ -7643,9 +8835,9 @@ let OAuthController = class OAuthController {
7643
8835
  const userId = useAuth().getUserId();
7644
8836
  const store = this.federated;
7645
8837
  const owned = await store.listForUser(userId);
7646
- if (!owned.find((i) => i.provider === providerId && i.subject === subject)) throw new HttpError$1(404, "Linked identity not found");
8838
+ if (!owned.find((i) => i.provider === providerId && i.subject === subject)) throw aoothHttpError(404, "LINKED_IDENTITY_NOT_FOUND");
7647
8839
  if (owned.length - 1 === 0) {
7648
- if ((await this.users.getUser(userId)).password.isInitial) throw new HttpError$1(409, "Cannot remove your only sign-in method. Set a password first, or link another provider.");
8840
+ if ((await this.users.getUser(userId)).password.isInitial) throw aoothHttpError(409, "LAST_SIGN_IN_METHOD");
7649
8841
  }
7650
8842
  await store.unlink(providerId, subject);
7651
8843
  await this.auth.revokeAllForUser(userId);
@@ -7656,7 +8848,7 @@ let OAuthController = class OAuthController {
7656
8848
  try {
7657
8849
  return this.registry.require(providerId);
7658
8850
  } catch (err) {
7659
- if (err instanceof OAuthError && err.type === "UNKNOWN_PROVIDER") throw new HttpError$1(404, `Unknown provider '${providerId}'`);
8851
+ if (err instanceof OAuthError && err.type === "UNKNOWN_PROVIDER") throw aoothHttpError(404, "AOOTH_UNKNOWN_PROVIDER", { provider: providerId });
7660
8852
  throw err;
7661
8853
  }
7662
8854
  }
@@ -7719,6 +8911,18 @@ function toConnectedAccount(i) {
7719
8911
  };
7720
8912
  }
7721
8913
  // src/authz/authorize.controller.ts
8914
+ /**
8915
+ * Default rate limits of the authorization server's public token endpoints, by
8916
+ * policy id — re-tune or switch one off with `rateLimitInterceptors({ policies })`.
8917
+ */
8918
+ const AUTHZ_RATE_LIMITS = {
8919
+ /** `POST /auth/token`, per client IP — every grant. */
8920
+ "aooth.token": "150/5m",
8921
+ /** `POST /auth/token` with `grant_type=refresh_token`, per presented refresh token, from any IP. */
8922
+ "aooth.token-refresh": "10/1m",
8923
+ /** `POST /auth/register` (dynamic client registration), per client IP. */
8924
+ "aooth.register": "20/1h"
8925
+ };
7722
8926
  /** Shared default claims resolver — stateless, so one instance is reused across requests. */
7723
8927
  const NOOP_OIDC_CLAIMS_RESOLVER = new NoopOidcClaimsResolver();
7724
8928
  let AuthorizeController = class AuthorizeController {
@@ -7834,6 +9038,13 @@ let AuthorizeController = class AuthorizeController {
7834
9038
  res.setHeader("Location", target);
7835
9039
  return "";
7836
9040
  }
9041
+ /**
9042
+ * Rate limited when `rateLimitInterceptors` are installed
9043
+ * ({@link AUTHZ_RATE_LIMITS}): `aooth.token` per client IP, and
9044
+ * `aooth.token-refresh` per presented `refresh_token` of a refresh grant.
9045
+ * Both are checked before the auth guard; over the limit the endpoint
9046
+ * answers the coded `429` (`RATE_LIMITED`, `Retry-After`).
9047
+ */
7837
9048
  async token(body) {
7838
9049
  if (body?.grant_type === "refresh_token") return await this.refreshTokenGrant(body);
7839
9050
  const res = useResponse(current());
@@ -8153,6 +9364,11 @@ __decorate([
8153
9364
  __decorate([
8154
9365
  Post("token"),
8155
9366
  Public(),
9367
+ RateLimit(AUTHZ_RATE_LIMITS["aooth.token"], { id: "aooth.token" }),
9368
+ RateLimit(AUTHZ_RATE_LIMITS["aooth.token-refresh"], {
9369
+ key: oauthRefreshTokenSubject,
9370
+ id: "aooth.token-refresh"
9371
+ }),
8156
9372
  __decorateParam(0, Body()),
8157
9373
  __decorateMetadata("design:type", Function),
8158
9374
  __decorateMetadata("design:paramtypes", [Object]),
@@ -8175,6 +9391,7 @@ __decorate([
8175
9391
  __decorate([
8176
9392
  Post("register"),
8177
9393
  Public(),
9394
+ RateLimit(AUTHZ_RATE_LIMITS["aooth.register"], { id: "aooth.register" }),
8178
9395
  __decorateParam(0, Body()),
8179
9396
  __decorateMetadata("design:type", Function),
8180
9397
  __decorateMetadata("design:paramtypes", [Object]),
@@ -8222,6 +9439,8 @@ function createAuthEmailOutlet(deps) {
8222
9439
  expiresAt
8223
9440
  };
8224
9441
  if (typeof opts.context?.username === "string") event.username = opts.context.username;
9442
+ const locale = currentLocale();
9443
+ if (locale !== void 0) event.locale = locale;
8225
9444
  const rolesRaw = opts.context?.roles;
8226
9445
  if (Array.isArray(rolesRaw)) {
8227
9446
  const roles = rolesRaw.filter((r) => typeof r === "string");
@@ -8230,4 +9449,4 @@ function createAuthEmailOutlet(deps) {
8230
9449
  await deps.emailSender.send(event);
8231
9450
  });
8232
9451
  }
8233
- export { ADD_MFA_WORKFLOW, AOOTH_MESSAGES, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, AuthController, AuthGuarded, AuthWorkflow, AuthorizeController, AuthorizeRuntime, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, FEDERATED_IDENTITY_STORE_TOKEN, INVITE_OUTLET, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, Public, RESERVED_USER_KEYS, RateLimit, RateLimitStoreMemory, RateLimited, RateLimiter, SessionEnricherProvider, SessionsController, UserId, WfTrigger, WfTriggerProvider, 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, userAuthErrorInterceptor, userAuthErrorToHttp };
9452
+ export { ADD_MFA_WORKFLOW, AOOTH_HTTP_MESSAGES, AOOTH_MESSAGES, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, AuthController, AuthGuarded, AuthWorkflow, AuthorizeController, AuthorizeRuntime, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, FEDERATED_IDENTITY_STORE_TOKEN, INVITE_OUTLET, MAGIC_LINK_OUTLET, MAGIC_LINK_STRATEGY, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, Public, RESERVED_USER_KEYS, RateLimit, RateLimitStoreMemory, RateLimited, RateLimiter, SessionEnricherProvider, SessionsController, UserId, WfTrigger, WfTriggerProvider, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, createInviteOutlet, createMagicLinkOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, getRateLimitMate, getRateLimitSubject, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, renderAoothMessage, resolveAoothMessage, resolveOAuthRedirect, setRateLimitSubject, stripReservedUserKeys, useAuth, useRateLimit, userAuthErrorInterceptor, userAuthErrorToHttp };