@aooth/auth-moost 0.2.5 → 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-D-MZTAyd.mjs";
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
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
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
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
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
@@ -108,11 +109,11 @@ function resolveAuthOptions(opts = {}) {
108
109
  */
109
110
  const AOOTH_HTTP_MESSAGES = {
110
111
  /** 401 — the guard found no credential on a protected route. */
111
- AUTH_REQUIRED: "Unauthorized",
112
+ AOOTH_AUTH_REQUIRED: "Unauthorized",
112
113
  /** 401 — the guard's credential is invalid, expired or revoked. */
113
- CREDENTIAL_INVALID: "Invalid credential",
114
+ AOOTH_CREDENTIAL_INVALID: "Invalid credential",
114
115
  /** 401 — `useAuth().getUserId()` and `AuthController` routes without a signed-in user. */
115
- NOT_AUTHENTICATED: "Not authenticated",
116
+ AOOTH_NOT_AUTHENTICATED: "Not authenticated",
116
117
  /** 401 — "log out other sessions" without a current session. */
117
118
  NO_CURRENT_SESSION: "No current session to keep",
118
119
  /** 401 — `POST /auth/refresh` without a refresh token. */
@@ -124,15 +125,17 @@ const AOOTH_HTTP_MESSAGES = {
124
125
  /** 404 — `GET /auth/invite/post-redemption` for an unknown or still pending invite. */
125
126
  INVITE_NOT_FOUND: "Invite not found",
126
127
  /** 400 — `GET /auth/invite/post-redemption` without `uid`. */
127
- MISSING_UID: "Missing uid query parameter",
128
+ AOOTH_MISSING_UID: "Missing uid query parameter",
128
129
  /** 404 — unlinking an identity the user does not have. */
129
130
  LINKED_IDENTITY_NOT_FOUND: "Linked identity not found",
130
131
  /** 409 — unlinking the user's only sign-in method. */
131
132
  LAST_SIGN_IN_METHOD: "Cannot remove your only sign-in method. Set a password first, or link another provider.",
132
133
  /** 404 — unlinking an identity of an unconfigured provider. Params: `provider`. */
133
- UNKNOWN_PROVIDER: "Unknown provider '{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.",
134
137
  /** 403 — the workflow trigger refused a workflow outside its allow list. Params: `workflow`. */
135
- WORKFLOW_NOT_ALLOWED: "Workflow '{workflow}' is not allowed"
138
+ AOOTH_WORKFLOW_NOT_ALLOWED: "Workflow '{workflow}' is not allowed"
136
139
  };
137
140
  registerMessages(AOOTH_HTTP_MESSAGES);
138
141
  /** An `HttpError` with `code`, `params` and the code's English text. */
@@ -150,6 +153,45 @@ function codedHttpError(status, code, message, params) {
150
153
  ...params && { params }
151
154
  });
152
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
+ }
153
195
  // src/auth.composables.ts
154
196
  const authContextKey = key("auth.context");
155
197
  const authCredentialKey = key("auth.credential");
@@ -207,7 +249,7 @@ const useAuth = defineWook((ctx) => {
207
249
  };
208
250
  const getUserId = () => {
209
251
  const auth = getAuthContext();
210
- if (!auth) throw aoothHttpError(401, "NOT_AUTHENTICATED");
252
+ if (!auth) throw aoothHttpError(401, "AOOTH_NOT_AUTHENTICATED");
211
253
  return auth.userId;
212
254
  };
213
255
  const isAuthenticated = () => getAuthContext() !== null;
@@ -323,6 +365,27 @@ function setAuthContext(ctx, value) {
323
365
  function setAuthCredential(ctx, value) {
324
366
  ctx.set(authCredentialKey, value);
325
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
+ }
326
389
  // src/auth.route.ts
327
390
  /**
328
391
  * Normalize a router path into a value usable as a cookie `Path` attribute:
@@ -383,7 +446,7 @@ function authGuardInterceptor(opts) {
383
446
  setAuthContext(ctx, null);
384
447
  return;
385
448
  }
386
- throw aoothHttpError(401, "AUTH_REQUIRED");
449
+ throw aoothHttpError(401, "AOOTH_AUTH_REQUIRED");
387
450
  }
388
451
  const credential = await cc.instantiate(AuthCredential);
389
452
  setAuthCredential(ctx, credential);
@@ -393,7 +456,7 @@ function authGuardInterceptor(opts) {
393
456
  setAuthContext(ctx, null);
394
457
  return;
395
458
  }
396
- throw aoothHttpError(401, "CREDENTIAL_INVALID");
459
+ throw aoothHttpError(401, "AOOTH_CREDENTIAL_INVALID");
397
460
  }
398
461
  setAuthContext(ctx, authContext);
399
462
  }, TInterceptorPriority.GUARD);
@@ -446,6 +509,8 @@ const UserId = () => Resolve(() => useAuth().getUserId());
446
509
  * evaluated so far), written by `rateLimitInterceptors`.
447
510
  */
448
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");
449
514
  /** Internal: phases (`pre` / `post`) that already evaluated this event — the double-count guard. */
450
515
  const rateLimitPhasesKey = key("aooth.rateLimit.phases");
451
516
  /**
@@ -478,6 +543,46 @@ function getRateLimitSubject(kind, ctx = current()) {
478
543
  function useRateLimit(ctx = current()) {
479
544
  return { decision: ctx.has(rateLimitDecisionKey) ? ctx.get(rateLimitDecisionKey) : null };
480
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");
481
586
  // src/rate-limit/interceptor.ts
482
587
  registerMessages(RATE_LIMIT_MESSAGES);
483
588
  /**
@@ -516,6 +621,13 @@ registerMessages(RATE_LIMIT_MESSAGES);
516
621
  */
517
622
  function rateLimitInterceptors(opts) {
518
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
+ }
519
631
  const limiter = opts?.limiter ?? new RateLimiter$1();
520
632
  const emitHeaders = opts?.headers ?? true;
521
633
  const trustProxy = opts?.trustProxy ?? false;
@@ -542,15 +654,18 @@ function rateLimitInterceptors(opts) {
542
654
  post: []
543
655
  };
544
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;
545
660
  const rawKey = policy.options?.key ?? opts?.key ?? "ip";
546
661
  const keyStrategy = rawKey === "auto" ? "user" : rawKey;
547
662
  const message = policy.options?.message ?? opts?.message;
548
663
  route[typeof keyStrategy === "string" && keyStrategy !== "ip" ? "post" : "pre"].push({
549
- rules: policy.rules,
664
+ rules,
550
665
  keyStrategy,
551
- scope: policy.options?.id ?? (i === 0 ? baseScope : `${baseScope}#${i}`),
666
+ scope,
552
667
  ...message !== void 0 && { defaultMessage: message },
553
- policyHeader: policy.rules.map((p) => `${p.limit};w=${Math.max(1, Math.round(p.window / 1e3))}`).join(", ")
668
+ policyHeader: policyHeader(rules)
554
669
  });
555
670
  }
556
671
  config = route;
@@ -558,9 +673,16 @@ function rateLimitInterceptors(opts) {
558
673
  byMethod.set(method, config);
559
674
  return config;
560
675
  };
676
+ const runtime = {
677
+ limiter,
678
+ overrides,
679
+ trustProxy,
680
+ emitHeaders
681
+ };
561
682
  const evaluate = async (phase) => {
562
683
  const ctx = current();
563
684
  if (ctx.get(eventTypeKey) !== "http") return;
685
+ if (!ctx.has(rateLimitRuntimeKey)) ctx.set(rateLimitRuntimeKey, runtime);
564
686
  const done = ctx.has(rateLimitPhasesKey) ? ctx.get(rateLimitPhasesKey) : [];
565
687
  if (done.includes(phase)) return;
566
688
  const config = resolveRouteConfig(useControllerContext(ctx));
@@ -580,19 +702,7 @@ function rateLimitInterceptors(opts) {
580
702
  if (decisions.length === 0) return;
581
703
  const decision = pickGoverning(decisions, (d) => !d.allowed);
582
704
  ctx.set(rateLimitDecisionKey, decision);
583
- const response = useResponse(ctx);
584
- if (emitHeaders) {
585
- const prior = response.getHeader("ratelimit-policy");
586
- if (typeof prior === "string" && prior) headers.unshift(prior);
587
- response.setHeader("ratelimit-limit", String(decision.limit));
588
- response.setHeader("ratelimit-remaining", String(decision.remaining));
589
- response.setHeader("ratelimit-reset", String(Math.ceil(decision.resetAfterMs / 1e3)));
590
- response.setHeader("ratelimit-policy", headers.join(", "));
591
- }
592
- if (!decision.allowed) {
593
- response.setHeader("retry-after", String(Math.ceil(decision.resetAfterMs / 1e3)));
594
- throw codedHttpError(429, decision.code ?? "RATE_LIMITED", decision.message ?? formatMessage(RATE_LIMIT_MESSAGES.RATE_LIMITED, decision.params), decision.params);
595
- }
705
+ answerDecision(decision, headers, emitHeaders, ctx);
596
706
  };
597
707
  return [defineBeforeInterceptor(() => evaluate("pre"), TInterceptorPriority.BEFORE_GUARD), defineBeforeInterceptor(() => evaluate("post"), TInterceptorPriority.AFTER_GUARD)];
598
708
  }
@@ -601,6 +711,10 @@ async function resolveSubject(strategy, trustProxy, ctx) {
601
711
  if (strategy !== "ip") {
602
712
  const subject = getRateLimitSubject(strategy, ctx);
603
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
+ }
604
718
  const auth = strategy === "user" || strategy === "session" ? useAuth(ctx).getAuthContext() : null;
605
719
  if (strategy === "user" && auth?.userId !== void 0) return `u:${auth.userId}`;
606
720
  if (strategy === "session" && auth?.sessionId !== void 0) return `s:${auth.sessionId}`;
@@ -618,6 +732,62 @@ function clientIp(trustProxy, ctx) {
618
732
  const req = useRequest(ctx);
619
733
  return trustProxy ? resolveForwarded(req.raw, trustOneHop).ip : req.getIp();
620
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
+ }
621
791
  // src/rate-limit/mate.ts
622
792
  function getRateLimitMate() {
623
793
  return getMoostMate();
@@ -632,6 +802,7 @@ function RateLimit(...args) {
632
802
  if (typeof last === "object" && last !== null && !("limit" in last)) options = inputs.pop();
633
803
  if (inputs.length === 0) throw new Error("@RateLimit requires at least one rule (or the literal `false` to opt out)");
634
804
  const rules = inputs.map((r) => parseRateLimitRule(r));
805
+ if (options?.id) declareRateLimitId(options.id);
635
806
  const policy = options ? {
636
807
  rules,
637
808
  options
@@ -693,6 +864,79 @@ function createInviteOutlet() {
693
864
  }
694
865
  };
695
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
+ }
696
940
  // src/workflow/public-projection.ts
697
941
  /**
698
942
  * `ctx.public` — the form-facing projection `AuthWorkflow` rebuilds before
@@ -720,6 +964,120 @@ function __decorateMetadata(k, v) {
720
964
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
721
965
  }
722
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
+ }
723
1081
  const HOOK_NAMES = [
724
1082
  "around",
725
1083
  "beforePersist",
@@ -758,7 +1116,7 @@ function normalizeWfId(id) {
758
1116
  return id.replace(/^\/+/, "");
759
1117
  }
760
1118
  function notAllowed(id) {
761
- return aoothHttpError(403, "WORKFLOW_NOT_ALLOWED", { workflow: normalizeWfId(id) });
1119
+ return aoothHttpError(403, "AOOTH_WORKFLOW_NOT_ALLOWED", { workflow: normalizeWfId(id) });
762
1120
  }
763
1121
  /**
764
1122
  * Wrap a strategy so a resume is checked against the allow list BEFORE the
@@ -801,11 +1159,17 @@ let WfTriggerProvider = class WfTriggerProvider {
801
1159
  wf;
802
1160
  auth;
803
1161
  /**
804
- * Outlets the trigger can pause on: HTTP (forms) and `invite` (the link of
805
- * `AuthWorkflowOpts.inviteDelivery: 'deliver' | 'return-link'`). Append an
806
- * `email` outlet (`createAuthEmailOutlet`) for the default invite delivery.
807
- */
808
- 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
+ ];
809
1173
  token = {
810
1174
  read: [
811
1175
  "body",
@@ -829,7 +1193,27 @@ let WfTriggerProvider = class WfTriggerProvider {
829
1193
  * `return deriveWfStateSecret(env.MY_SECRET)`.
830
1194
  */
831
1195
  wfStateSecret() {
832
- 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());
833
1217
  }
834
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. */
835
1219
  wfStateEncapsulatedTtlMs() {}
@@ -837,6 +1221,18 @@ let WfTriggerProvider = class WfTriggerProvider {
837
1221
  storeStrategy() {
838
1222
  return this.makeEncapsulated();
839
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;
840
1236
  makeEncapsulated() {
841
1237
  return new EncapsulatedStateStrategy({
842
1238
  secret: this.wfStateSecret(),
@@ -859,12 +1255,16 @@ let WfTriggerProvider = class WfTriggerProvider {
859
1255
  return {};
860
1256
  }
861
1257
  cachedState;
862
- /** 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. */
863
1259
  stateRegistry() {
864
1260
  if (!this.cachedState) this.cachedState = {
865
1261
  strategies: {
866
- encapsulated: this.makeEncapsulated(),
867
- 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
+ }))
868
1268
  },
869
1269
  default: "encapsulated"
870
1270
  };
@@ -879,6 +1279,7 @@ let WfTriggerProvider = class WfTriggerProvider {
879
1279
  */
880
1280
  async handle(opts = {}) {
881
1281
  const wfApp = this.wf.getWfApp();
1282
+ current().set(pincodeKeySlot, this.pincodeKey());
882
1283
  const allowed = opts.allow && new Set(opts.allow.map(normalizeWfId));
883
1284
  const permits = (schemaId) => !allowed || allowed.has(normalizeWfId(schemaId));
884
1285
  const registry = this.stateRegistry();
@@ -1200,34 +1601,34 @@ OAuthRuntime = __decorate([Injectable(), __decorateMetadata("design:paramtypes",
1200
1601
  */
1201
1602
  const AOOTH_MESSAGES = {
1202
1603
  INVALID_CREDENTIALS: "Invalid credentials",
1203
- ACCOUNT_LOCKED: "Account locked, please try again later",
1604
+ AOOTH_ACCOUNT_LOCKED: "Account locked, please try again later",
1204
1605
  INVALID_PASSWORD: "Invalid password",
1205
1606
  INCORRECT_PASSWORD: "Incorrect password",
1206
1607
  SESSION_LIMIT_REACHED: "Session limit reached",
1207
1608
  PASSWORD_CHANGED_SIGN_IN_AGAIN: "Your password was changed. Please sign in again.",
1208
- INVALID_CODE: "Invalid code",
1209
- CODE_EXPIRED: "Code expired",
1210
- TOO_MANY_CODE_ATTEMPTS: "Too many invalid attempts. Please request a new code.",
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.",
1211
1612
  /** Params: `seconds`. */
1212
- RESEND_WAIT: "Please wait {seconds}s before requesting a new code.",
1613
+ AOOTH_RESEND_WAIT: "Please wait {seconds}s before requesting a new code.",
1213
1614
  /** Params: `seconds`. */
1214
- RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code",
1615
+ AOOTH_RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code",
1215
1616
  /** Params: `seconds`, `channel` (`SMS` / `email`). */
1216
- RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code",
1617
+ AOOTH_RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code",
1217
1618
  TOTP_RESEND_NOT_APPLICABLE: "Resend is not applicable for TOTP",
1218
1619
  /** HTTP 400 — a TOTP code submitted for an account without TOTP. */
1219
1620
  TOTP_NOT_CONFIGURED: "No TOTP MFA configured",
1220
- ADDRESS_REQUIRED: "This field is required",
1221
- INVALID_EMAIL_ADDRESS: "Enter a valid email address",
1222
- INVALID_PHONE_NUMBER: "Enter a valid phone number",
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",
1223
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.",
1224
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.",
1225
1626
  UNKNOWN_MFA_METHOD: "Unknown MFA method",
1226
- UNKNOWN_METHOD: "Unknown method",
1227
- METHOD_UNAVAILABLE: "That method isn't available",
1228
- METHOD_NOT_CHANGEABLE: "That method can't be changed here.",
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.",
1229
1630
  KEEP_ONE_MFA_METHOD: "You must keep at least one two-factor method.",
1230
- CHOOSE_OPTION: "Choose an option",
1631
+ AOOTH_CHOOSE_OPTION: "Choose an option",
1231
1632
  ALL_MFA_METHODS_SET_UP: "You've already set up every available authentication method.",
1232
1633
  NO_MFA_CHANGES: "No changes were made to your two-factor methods.",
1233
1634
  LAST_MFA_METHOD_NOT_REMOVABLE: "You must keep at least one two-factor method, so this one can't be removed.",
@@ -1255,16 +1656,17 @@ const AOOTH_MESSAGES = {
1255
1656
  SET_PASSWORD_INVITE_INTRO: "Choose a password to activate your account.",
1256
1657
  SET_PASSWORD_INITIAL_HEADING: "Set your initial password",
1257
1658
  SET_PASSWORD_INITIAL_INTRO: "Your account was created without a password. Choose one to continue.",
1258
- RECOVERY_INSTRUCTIONS_SENT: "If an account exists, you will receive instructions.",
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.",
1259
1661
  SIGNUP_DISABLED: "Self-signup is currently disabled.",
1260
- ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.",
1261
- ACCOUNT_LINKED: "Account linked.",
1662
+ AOOTH_ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.",
1663
+ AOOTH_ACCOUNT_LINKED: "Account linked.",
1262
1664
  /** HTTP 400 — the SSO alt action named a provider that is not offered. */
1263
1665
  UNKNOWN_SSO_PROVIDER: "Unknown SSO provider",
1264
- ACCOUNT_CREATED: "Your account has been created.",
1265
- INVALID_ROLE: "Invalid role",
1666
+ AOOTH_ACCOUNT_CREATED: "Your account has been created.",
1667
+ AOOTH_INVALID_ROLE: "Invalid role",
1266
1668
  INVITE_ALREADY_PENDING: "Invite already pending",
1267
- USER_ALREADY_EXISTS: "User already exists",
1669
+ AOOTH_USER_ALREADY_EXISTS: "User already exists",
1268
1670
  DUPLICATE_INVITE_REJECTED: "Duplicate invite rejected",
1269
1671
  INVITE_CANCELLED: "This invite has been cancelled",
1270
1672
  INVITE_REPLACED: "This invite was replaced by a newer one",
@@ -1277,8 +1679,8 @@ const AOOTH_MESSAGES = {
1277
1679
  GO_TO_SIGN_IN: "Go to sign-in",
1278
1680
  BACK_TO_SIGN_IN: "Back to sign-in",
1279
1681
  REQUEST_NEW_INVITE: "Request a new invite",
1280
- BACK: "Back",
1281
- GO_NOW: "Go now"
1682
+ AOOTH_BACK: "Back",
1683
+ AOOTH_GO_NOW: "Go now"
1282
1684
  };
1283
1685
  registerMessages(AOOTH_MESSAGES);
1284
1686
  /** Fill `{name}` placeholders from `params`; unknown placeholders are kept. */
@@ -1339,19 +1741,20 @@ function userAuthErrorField(type) {
1339
1741
  }
1340
1742
  /**
1341
1743
  * Map a `UserAuthError` (thrown by `UserService`) to an `HttpError` whose body
1342
- * carries `code` (the error type), the message and — for password errors —
1343
- * 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):
1344
1747
  *
1345
- * | type | status | field |
1346
- * |---|---|---|
1347
- * | `NOT_FOUND` | 404 | |
1348
- * | `ALREADY_EXISTS`, `CAS_EXHAUSTED` | 409 | |
1349
- * | `INVALID_CREDENTIALS` | 400 | `currentPassword` |
1350
- * | `PASSWORD_IN_HISTORY` | 400 | `newPassword` |
1351
- * | `POLICY_VIOLATION` (+ `params.policies`) | 422 | `newPassword` |
1352
- * | `PASSWORDS_MISMATCH` | 400 | `confirmPassword` |
1353
- * | `MFA_INVALID`, `MFA_NOT_CONFIGURED` | 400 | |
1354
- * | `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 | |
1355
1758
  *
1356
1759
  * For routes such as an admin "set password" endpoint. Do not use it on a
1357
1760
  * sign-in endpoint: distinct answers for unknown, inactive and locked accounts
@@ -1363,7 +1766,7 @@ function userAuthErrorToHttp(err) {
1363
1766
  const policies = err.type === "POLICY_VIOLATION" ? err.details?.policies : void 0;
1364
1767
  return new HttpError(STATUS[err.type], {
1365
1768
  message: userAuthErrorText(err),
1366
- code: err.type,
1769
+ code: err.code,
1367
1770
  ...policies !== void 0 && { params: { policies } },
1368
1771
  ...field && { field }
1369
1772
  });
@@ -1388,8 +1791,8 @@ function translatePolicyError({ code, params, errorMessage }) {
1388
1791
  * A `UserAuthError`'s text in the request's locale: a `POLICY_VIOLATION` lists
1389
1792
  * its failed policies' translated `errorMessage`s (`; `-joined, like the
1390
1793
  * English message) when at least one of them has a translation; otherwise —
1391
- * and for any other type — the error is translated by its type, its own
1392
- * message the fallback.
1794
+ * and for any other type — the error is translated by its code (`err.code`),
1795
+ * its own message the fallback.
1393
1796
  */
1394
1797
  function userAuthErrorText(err) {
1395
1798
  const policies = err.type === "POLICY_VIOLATION" ? err.details?.policies : void 0;
@@ -1398,7 +1801,7 @@ function userAuthErrorText(err) {
1398
1801
  const texts = failed.map((p) => translatePolicyError(p));
1399
1802
  if (texts.some((text, i) => text !== failed[i].errorMessage)) return texts.join("; ");
1400
1803
  }
1401
- return translateCode(err.type, void 0, err.message);
1804
+ return translateCode(err.code, void 0, err.message);
1402
1805
  }
1403
1806
  /**
1404
1807
  * Error interceptor answering every `UserAuthError` a handler throws with
@@ -1432,7 +1835,7 @@ const userAuthErrorInterceptor = defineErrorInterceptor((error, reply) => {
1432
1835
  */
1433
1836
  const pincodeSendCheckPair = [{
1434
1837
  id: "pincode-send",
1435
- condition: (ctx) => !ctx.pin
1838
+ condition: (ctx) => !ctx.pinNonce
1436
1839
  }, {
1437
1840
  id: "pincode-check",
1438
1841
  condition: (ctx) => !ctx.aborted
@@ -1468,7 +1871,7 @@ const enrollTrioSteps = [
1468
1871
  },
1469
1872
  {
1470
1873
  id: "enroll-send",
1471
- 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
1472
1875
  },
1473
1876
  {
1474
1877
  id: "enroll-confirm",
@@ -1522,7 +1925,7 @@ const mfaStepUpLoop = [{
1522
1925
  },
1523
1926
  {
1524
1927
  id: "manage-stepup-confirm",
1525
- 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
1526
1929
  },
1527
1930
  { break: (ctx) => !!ctx.aborted },
1528
1931
  {
@@ -1654,6 +2057,9 @@ const DEFAULT_FORMS = {
1654
2057
  termsBump: TermsBumpForm,
1655
2058
  concurrencyLimit: ConcurrencyLimitForm,
1656
2059
  recoveryPincode: PincodeForm,
2060
+ recoveryModeSelect: RecoveryModeSelectForm,
2061
+ magicLinkRequest: MagicLinkRequestForm,
2062
+ magicLinkConfirm: MagicLinkConfirmForm,
1657
2063
  signup: SignupForm,
1658
2064
  authzConsent: AuthorizeConsentForm
1659
2065
  };
@@ -1665,19 +2071,56 @@ const warnedOnce = {
1665
2071
  openInviteWhitelist: false,
1666
2072
  crossIssuerReuse: false
1667
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;
1668
2094
  /** Sliding lifetime of a shadow failure counter (and of a shadow "permanent" lock). */
1669
2095
  const SHADOW_TTL_MS = 2592e6;
1670
2096
  /** Key prefix of an active shadow lock (kept longest by the default store). */
1671
2097
  const SHADOW_LOCK_PREFIX = "shadow-lock:";
1672
2098
  /** Cap of the default (process-wide, in-memory) shadow-lockout store. */
1673
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
+ }
1674
2121
  let sharedShadowStore;
1675
2122
  function defaultShadowStore() {
1676
- sharedShadowStore ??= new RateLimitStoreMemory$1({
1677
- maxEntries: SHADOW_STORE_MAX_ENTRIES,
1678
- evictLast: (key) => key.startsWith(SHADOW_LOCK_PREFIX)
1679
- });
1680
- return sharedShadowStore;
2123
+ return sharedShadowStore ??= createShadowStore();
1681
2124
  }
1682
2125
  function mergeAuthWorkflowOpts(opts) {
1683
2126
  const deviceTrust = {
@@ -1701,9 +2144,14 @@ function mergeAuthWorkflowOpts(opts) {
1701
2144
  pincodeLength: opts.mfa?.pincodeLength ?? 6,
1702
2145
  pincodeTtlMs: opts.mfa?.pincodeTtlMs ?? 3e5,
1703
2146
  pincodeResendTimeoutMs: opts.mfa?.pincodeResendTimeoutMs ?? 6e4,
1704
- 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
1705
2152
  },
1706
2153
  recoveryStateTtlMs: opts.recoveryStateTtlMs ?? 36e5,
2154
+ magicLinkTtlMs: opts.magicLinkTtlMs ?? 9e5,
1707
2155
  loginUrl: opts.loginUrl ?? "/login",
1708
2156
  totpIssuer: opts.totpIssuer ?? "aooth",
1709
2157
  deviceTrust,
@@ -1912,8 +2360,8 @@ function pickDefined(src, keys) {
1912
2360
  * Thrown by `recoveryPincodeTarget`'s registered (M2) branch when the confirmed
1913
2361
  * recovery method that `request`'s guard saw has VANISHED before send time
1914
2362
  * (deleted between the two row loads — the request→send TOCTOU). `pincode-send`
1915
- * catches it and degrades to the generic anti-enumeration finish instead of
1916
- * 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
1917
2365
  * distinguishable from an unknown one on a resend. Recovery-only; the MFA
1918
2366
  * challenge branch keeps its own `HttpError(500)` (that path is post-password,
1919
2367
  * so enumeration is moot there).
@@ -2252,6 +2700,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2252
2700
  });
2253
2701
  }
2254
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
+ /**
2255
2712
  * Resolve the alternate-credentials policy (forgot-password / signup /
2256
2713
  * magic-link / SSO providers). Reached from login.flow.
2257
2714
  */
@@ -2260,11 +2717,9 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2260
2717
  forgotPassword: true,
2261
2718
  signup: false,
2262
2719
  magicLink: false,
2263
- magicLinkSkipsMfa: false,
2264
2720
  ssoProviders: [],
2265
2721
  recoveryUrl: "/recover",
2266
- signupUrl: "/signup",
2267
- embedRecovery: false
2722
+ signupUrl: "/signup"
2268
2723
  };
2269
2724
  }
2270
2725
  /**
@@ -2556,7 +3011,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2556
3011
  * `freshLoginRequired` field is GONE — the auto-login choice is the static
2557
3012
  * `AuthWorkflowOpts.autoLoginOnInvite` boolean (per §2 decision). Return
2558
3013
  * `confirmationMessage` to replace the default confirmation text
2559
- * (`ACCOUNT_CREATED`, rendered in the finishing request's language) with your
3014
+ * (`AOOTH_ACCOUNT_CREATED`, rendered in the finishing request's language) with your
2560
3015
  * own, shown as is.
2561
3016
  */
2562
3017
  resolveAccept(_ctx) {
@@ -2622,6 +3077,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2622
3077
  * set) or from `ctx.email` (recovery path). Loads the user to read the raw
2623
3078
  * method `value` — the `ctx.mfa.enrolledMethods` summary carries only the
2624
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.
2625
3085
  */
2626
3086
  resolvePincodeTarget(ctx) {
2627
3087
  if (ctx.mfa?.method && ctx.mfa.method !== "totp") {
@@ -2653,11 +3113,9 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2653
3113
  * row (`selectRecoveryRegisteredMethod`) and the channel is that method's own
2654
3114
  * kind. The user only typed an account identifier; the destination is a
2655
3115
  * pre-verified channel they already control, so this also can't redirect
2656
- * cross-account. `request`'s M2 guard normally generic-finishes any row with
2657
- * no deliverable method up front; if the method is deleted in the narrow
2658
- * window between that guard and this send (e.g. on a resend), this throws
2659
- * `RecoveryMethodUnavailableError`, which `pincode-send` degrades to the
2660
- * 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.
2661
3119
  */
2662
3120
  recoveryPincodeTarget(ctx, source) {
2663
3121
  if (source === "registered") {
@@ -2682,6 +3140,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2682
3140
  channel
2683
3141
  };
2684
3142
  }
3143
+ /** `resolveRecoveryDeliverySource`, awaited. */
3144
+ async recoveryDeliverySource(ctx) {
3145
+ const source = this.resolveRecoveryDeliverySource(ctx);
3146
+ return source instanceof Promise ? await source : source;
3147
+ }
2685
3148
  /**
2686
3149
  * Recovery OTP delivery channel. The address is ALWAYS the typed recovery
2687
3150
  * identifier (`ctx.email`) — symmetric with how email recovery already works:
@@ -2706,7 +3169,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2706
3169
  * row** — `selectRecoveryRegisteredMethod` picks the confirmed MFA method;
2707
3170
  * the destination is never taken from user input, so it cannot be redirected
2708
3171
  * to an attacker-controlled address. A row with no deliverable confirmed
2709
- * method finishes with the generic anti-enumeration envelope (see `request`).
3172
+ * method runs the ghost OTP pause, like an unknown identifier (see `request`).
2710
3173
  *
2711
3174
  * Consulted inline by `request` (no-method guard) and `recoveryPincodeTarget`
2712
3175
  * — no `prepare-*` step, mirroring `resolveRecoveryChannel`. Override to arm
@@ -2720,7 +3183,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2720
3183
  * its OTP to. Prefers a confirmed SMS method, then a confirmed email method —
2721
3184
  * phone-recovery-first. TOTP carries no deliverable address and is skipped.
2722
3185
  * Returns `null` when the row has no deliverable confirmed method; the caller
2723
- * 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
2724
3187
  * an already-loaded row); override to change the selection policy (e.g. honour
2725
3188
  * the user's `mfa.defaultMethod`).
2726
3189
  */
@@ -2879,6 +3342,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2879
3342
  if (sub) pub.proveControl = sub;
2880
3343
  }
2881
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") };
2882
3346
  if (ctx.authz) {
2883
3347
  const sub = pickDefined(ctx.authz, [
2884
3348
  "clientName",
@@ -2923,40 +3387,170 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2923
3387
  throw err;
2924
3388
  }
2925
3389
  }
2926
- /** Mint a numeric pincode + stash it onto ctx. Returns the plain code. */
2927
- 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) {
2928
3399
  const code = generateMfaCode(length);
2929
- ctx.pin = code;
3400
+ ctx.pinNonce = randomBytes(16).toString("base64url");
3401
+ ctx.pinDigest = this.pinDigest(ctx.pinNonce, binding, code);
2930
3402
  ctx.pinExpire = Date.now() + ttlMs;
2931
- delete ctx.pinAttempts;
2932
3403
  return code;
2933
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
+ }
2934
3415
  /**
2935
- * Verify a submitted pincode against `ctx.pin`. Returns an error map (with
2936
- * the message keyed under `code` so it renders inline on the code input) or
2937
- * `null` on success. Brute-force protection: wrong-code attempts increment
2938
- * `ctx.pinAttempts`; on the `pincodeMaxAttempts`-th miss the code is
2939
- * invalidated (clears `pin` + `pinExpire` + `pinAttempts`) and the returned
2940
- * error tells the user to request a fresh code. Without this gate the user
2941
- * could probe the full 10^pincodeLength space inside one `pincodeTtlMs`
2942
- * window.
2943
- */
2944
- verifyPin(ctx, submitted) {
2945
- if (!ctx.pin || !ctx.pinExpire || Date.now() > ctx.pinExpire) return { code: this.msg("CODE_EXPIRED") };
2946
- if (submitted !== ctx.pin) {
2947
- const attempts = (ctx.pinAttempts ?? 0) + 1;
2948
- if (attempts >= this.opts.mfa.pincodeMaxAttempts) {
2949
- delete ctx.pin;
2950
- delete ctx.pinExpire;
2951
- delete ctx.pinAttempts;
2952
- return { code: this.msg("TOO_MANY_CODE_ATTEMPTS") };
2953
- }
2954
- ctx.pinAttempts = attempts;
2955
- return { code: this.msg("INVALID_CODE") };
2956
- }
2957
- 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") };
2958
3532
  return null;
2959
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;
2960
3554
  /**
2961
3555
  * Validate + stash inline-consent fields submitted on a carrier form.
2962
3556
  * SECURITY: silently drops unknown ids (audit-grade defense — see base
@@ -3017,12 +3611,19 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3017
3611
  * `enrollConfirm`, so the arming policy cannot drift between first send
3018
3612
  * and resend.
3019
3613
  */
3020
- async mintAndSendEnrollPincode(ctx, address) {
3021
- 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));
3022
3617
  const pincode = ctx.pincode ??= {};
3023
3618
  pincode.resendAllowedAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
3024
3619
  pincode.codeLength = this.opts.mfa.pincodeLength;
3025
- 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);
3026
3627
  }
3027
3628
  /**
3028
3629
  * Idempotent TOTP secret provisioning into wf-state ONLY (the QR renders
@@ -3067,8 +3668,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3067
3668
  delete m.qrSeen;
3068
3669
  delete m.preConfirmed;
3069
3670
  }
3070
- delete ctx.pin;
3071
- delete ctx.pinExpire;
3671
+ this.clearPin(ctx);
3072
3672
  if (ctx.pincode) delete ctx.pincode.sentTo;
3073
3673
  }
3074
3674
  /**
@@ -3097,11 +3697,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3097
3697
  */
3098
3698
  validateMfaAddress(_ctx, method, value) {
3099
3699
  const v = (value ?? "").trim();
3100
- if (!v) return this.msg("ADDRESS_REQUIRED");
3101
- if (method === "email") return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? void 0 : this.msg("INVALID_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");
3102
3702
  if (method === "sms") {
3103
3703
  const digits = v.replace(/[\s()+.-]/g, "");
3104
- return /^[1-9]\d{6,14}$/.test(digits) ? void 0 : this.msg("INVALID_PHONE_NUMBER");
3704
+ return /^[1-9]\d{6,14}$/.test(digits) ? void 0 : this.msg("AOOTH_INVALID_PHONE_NUMBER");
3105
3705
  }
3106
3706
  }
3107
3707
  /**
@@ -3339,6 +3939,10 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3339
3939
  if (alt.ssoProviders.length > 0) altActions.ssoProviders = alt.ssoProviders;
3340
3940
  const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.loginCredentials);
3341
3941
  const action = wf.resolveAction();
3942
+ if (action === "magicLink" && alt.magicLink) {
3943
+ ctx.magicLink = { purpose: "login" };
3944
+ return;
3945
+ }
3342
3946
  if (action) {
3343
3947
  const typedUsername = getInputField("username");
3344
3948
  if (await this.handleCredentialsAlt(action, typedUsername, alt, ctx.authz?.handle) === ALT_HANDLED) return void 0;
@@ -3346,35 +3950,48 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3346
3950
  const input = wf.resolveInput();
3347
3951
  try {
3348
3952
  const result = await this.users.login(input.username, input.password, this.lockoutOverride(ctx));
3349
- ctx.subject = result.user.id;
3350
- ctx.passwordStamp = result.user.password.lastChanged ?? 0;
3351
3953
  ctx.loginRecorded = true;
3352
3954
  swapStrategy("store");
3353
- if (ctx.guards?.passwordInitial && result.user.password.isInitial) ctx.isPasswordInitial = true;
3354
- if (ctx.guards?.passwordExpiry && this.users.isPasswordExpired(result.user)) ctx.isPasswordExpired = true;
3355
- if (ctx.isPasswordInitial) (ctx.password ??= {}).changeReason = "initial";
3356
- else if (ctx.isPasswordExpired) (ctx.password ??= {}).changeReason = "expired";
3357
- const email = result.user.mfa.methods.find((m) => m.name === "email" && m.confirmed);
3358
- if (email) {
3359
- (ctx.notice ??= {}).email = email.value;
3360
- (ctx.channel ??= {}).emailConfirmed = true;
3361
- }
3362
- const phone = result.user.mfa.methods.find((m) => m.name === "sms" && m.confirmed);
3363
- if (phone) {
3364
- const channel = ctx.channel ??= {};
3365
- channel.phone = phone.value;
3366
- channel.phoneConfirmed = true;
3367
- }
3368
- if (!ctx.notice?.email) await this.seedCorrespondenceEmail(ctx, result.user);
3955
+ await this.bindSignedInUser(ctx, result.user);
3369
3956
  } catch (err) {
3370
3957
  if (err instanceof UserAuthError) {
3371
3958
  const locked = await this.failedLoginReadsLocked(ctx, err, input.username);
3372
- 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") });
3373
3960
  }
3374
3961
  throw err;
3375
3962
  }
3376
3963
  }
3377
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
+ /**
3378
3995
  * Whether a failed password sign-in answers "Account locked" — see
3379
3996
  * `AuthWorkflowOpts.lockoutDisclosure`. Under `'uniform'` an unknown or
3380
3997
  * inactive handle keeps a shadow failure counter in `lockoutShadowStore`
@@ -3396,7 +4013,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3396
4013
  };
3397
4014
  if (threshold <= 0) return false;
3398
4015
  const store = this.opts.lockoutShadowStore;
3399
- const id = createHash("sha256").update(handle.trim().toLowerCase()).digest("base64url");
4016
+ const id = sha256url(handle.trim().toLowerCase());
3400
4017
  const lockKey = `${SHADOW_LOCK_PREFIX}${id}`;
3401
4018
  if (store.get && await store.get(lockKey) > 0) {
3402
4019
  if (duration <= 0) await store.expire?.(lockKey, SHADOW_TTL_MS);
@@ -3438,7 +4055,6 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3438
4055
  } });
3439
4056
  return ALT_HANDLED;
3440
4057
  }
3441
- if (action === "magicLink" && alt.magicLink) throw new HttpError$1(501, "Magic-link login path not implemented in this version");
3442
4058
  if (action === "sso") {
3443
4059
  const providerId = getInputField("ssoProvider");
3444
4060
  const sso = providerId ? alt.ssoProviders.find((p) => p.id === providerId) : void 0;
@@ -3463,28 +4079,75 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3463
4079
  if (prefilled) ctx.defaults = { email: prefilled };
3464
4080
  throw this.throwPublic(ctx, emailWf);
3465
4081
  }
3466
- const email = emailWf.resolveInput().email;
3467
- ctx.email = email;
3468
- 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) {
3469
4113
  try {
3470
- subject = await this.emailToUserId(email) ?? void 0;
4114
+ return await this.emailToUserId(identifier) ?? void 0;
3471
4115
  } catch (err) {
3472
4116
  if (!(err instanceof UserAuthError) || err.type !== "NOT_FOUND") throw err;
3473
- }
3474
- if (!subject) {
3475
- this.finishGenericRecovery();
3476
4117
  return;
3477
4118
  }
3478
- const sourceResult = this.resolveRecoveryDeliverySource(ctx);
3479
- if ((sourceResult instanceof Promise ? await sourceResult : sourceResult) === "registered") {
3480
- const user = await this.users.getUser(subject);
3481
- if (!this.selectRecoveryRegisteredMethod(user)) {
3482
- this.finishGenericRecovery();
3483
- return;
3484
- }
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;
3485
4150
  }
3486
- ctx.subject = subject;
3487
- swapStrategy("store");
3488
4151
  }
3489
4152
  /**
3490
4153
  * Resolves the recovery-step `email` input to the user's stable `id` (the
@@ -3495,16 +4158,6 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3495
4158
  async emailToUserId(email) {
3496
4159
  return (await this.users.findByHandle(email))?.id ?? null;
3497
4160
  }
3498
- /** Anti-enumeration generic finish envelope used when recovery's `request` step receives an unknown email. */
3499
- finishGenericRecovery() {
3500
- finishWf({
3501
- data: { sent: true },
3502
- message: {
3503
- level: "info",
3504
- text: this.msg("RECOVERY_INSTRUCTIONS_SENT")
3505
- }
3506
- });
3507
- }
3508
4161
  /**
3509
4162
  * Stamp `recoveryStateTtlMs` on a paused-state error so the wf engine's
3510
4163
  * persisted-state strategy expires the state at that timestamp. Use at
@@ -3747,7 +4400,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3747
4400
  const parsed = this.effectiveInviteRoles(ctx, roles);
3748
4401
  if (Array.isArray(ctx.admin?.availableRoles)) {
3749
4402
  const allowed = new Set(ctx.admin.availableRoles);
3750
- 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") } });
3751
4404
  }
3752
4405
  if (Object.keys(extra).length > 0) (ctx.admin ??= {}).form = extra;
3753
4406
  const existing = await this.users.findByHandle(email);
@@ -3762,7 +4415,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3762
4415
  });
3763
4416
  if (action === "reject") {
3764
4417
  if (existing?.account?.pendingInvitation) throw this.throwPublic(ctx, wf, { errors: { email: this.msg("INVITE_ALREADY_PENDING") } });
3765
- 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") } });
3766
4419
  throw this.throwPublic(ctx, wf, { errors: { email: this.msg("DUPLICATE_INVITE_REJECTED") } });
3767
4420
  }
3768
4421
  if (action === "reuse") {
@@ -3848,7 +4501,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3848
4501
  if (admin.reuseExisting) {
3849
4502
  const existing = await this.users.findByHandle(ctx.email);
3850
4503
  if (existing) {
3851
- if (!existing.account?.pendingInvitation) throw this.httpError(409, "USER_ALREADY_EXISTS");
4504
+ if (!existing.account?.pendingInvitation) throw this.httpError(409, "AOOTH_USER_ALREADY_EXISTS");
3852
4505
  await this.users.update(existing.id, {
3853
4506
  ...fields,
3854
4507
  account: pendingAccount
@@ -3861,7 +4514,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3861
4514
  try {
3862
4515
  created = await this.users.createUser(ctx.email, void 0, fields);
3863
4516
  } catch (err) {
3864
- 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");
3865
4518
  throw err;
3866
4519
  }
3867
4520
  await this.users.update(created.id, { account: pendingAccount });
@@ -4021,7 +4674,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4021
4674
  data: { confirmed: true },
4022
4675
  message: {
4023
4676
  level: "success",
4024
- text: ctx.accept?.confirmationMessage ?? this.msg("ACCOUNT_CREATED")
4677
+ text: ctx.accept?.confirmationMessage ?? this.msg("AOOTH_ACCOUNT_CREATED")
4025
4678
  }
4026
4679
  });
4027
4680
  }
@@ -4087,7 +4740,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4087
4740
  next: {
4088
4741
  trigger: "manual",
4089
4742
  primary: {
4090
- label: this.msg("BACK"),
4743
+ label: this.msg("AOOTH_BACK"),
4091
4744
  action: {
4092
4745
  type: "redirect",
4093
4746
  target: this.opts.loginUrl,
@@ -4268,7 +4921,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4268
4921
  },
4269
4922
  message: {
4270
4923
  level: "info",
4271
- text: addMfa.blocked === "last-required-factor" ? this.msg("LAST_MFA_METHOD_NOT_REMOVABLE") : this.msg("METHOD_NOT_CHANGEABLE")
4924
+ text: addMfa.blocked === "last-required-factor" ? this.msg("LAST_MFA_METHOD_NOT_REMOVABLE") : this.msg("AOOTH_METHOD_NOT_CHANGEABLE")
4272
4925
  }
4273
4926
  };
4274
4927
  else if (candidates.length === 0 && !addMfa?.stepUpRequired) envelope = {
@@ -4425,12 +5078,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4425
5078
  const action = sep >= 0 ? input.operation.slice(0, sep) : "";
4426
5079
  const target = sep >= 0 ? input.operation.slice(sep + 1) : "";
4427
5080
  if (action === "add") {
4428
- 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") } });
4429
5082
  } else if (action === "replace" || action === "remove") {
4430
- if (locked.has(target)) throw this.throwPublic(ctx, wf, { formMessage: this.msg("METHOD_NOT_CHANGEABLE") });
4431
- 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") } });
4432
5085
  if (action === "remove" && addMfa.removeBlocked) throw this.throwPublic(ctx, wf, { formMessage: this.msg("KEEP_ONE_MFA_METHOD") });
4433
- } 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") } });
4434
5087
  addMfa.action = action;
4435
5088
  addMfa.target = target;
4436
5089
  const m = ctx.mfaEnroll ??= {};
@@ -4498,20 +5151,30 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4498
5151
  }));
4499
5152
  if (isEmail) (ctx.channel ??= {}).email = value;
4500
5153
  else (ctx.channel ??= {}).phone = value;
4501
- const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
4502
- await this.dispatch({
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({
4503
5168
  kind: "enroll-pincode",
4504
- channel: isEmail ? "email" : "sms",
4505
- recipient: value,
5169
+ channel,
5170
+ recipient: address,
4506
5171
  code,
4507
5172
  expiresInMs: this.opts.mfa.pincodeTtlMs
4508
5173
  });
4509
5174
  const pincode = ctx.pincode ??= {};
4510
5175
  pincode.resendAllowedAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
4511
- pincode.sentTo = this.maskAddress(value, isEmail ? "email" : "sms");
5176
+ pincode.sentTo = this.maskAddress(address, channel);
4512
5177
  pincode.codeLength = this.opts.mfa.pincodeLength;
4513
- const pincodeWf = this.useAtscriptWfPublic(ctx, this.opts.forms.pincode);
4514
- throw this.throwPublic(ctx, pincodeWf);
4515
5178
  }
4516
5179
  async verifyChannel(ctx, channel) {
4517
5180
  this.requireSubject(ctx);
@@ -4519,27 +5182,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4519
5182
  const pincodeWf = this.useAtscriptWfPublic(ctx, this.opts.forms.pincode);
4520
5183
  const action = pincodeWf.resolveAction();
4521
5184
  if (action && this.resolvePincodeAltAction(ctx, action) === "resend") {
4522
- if (ctx.pincode?.resendAllowedAt && ctx.pincode.resendAllowedAt > Date.now()) {
4523
- const remainingSec = Math.ceil((ctx.pincode.resendAllowedAt - Date.now()) / 1e3);
4524
- throw this.throwPublic(ctx, pincodeWf, { formMessage: this.msg("RESEND_WAIT", { seconds: remainingSec }) });
4525
- }
5185
+ const cooldown = ctx.pincode?.resendAllowedAt;
4526
5186
  const recipient = isEmail ? ctx.channel?.email : ctx.channel?.phone;
4527
- const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
4528
- await this.dispatch({
4529
- kind: "enroll-pincode",
4530
- channel: isEmail ? "email" : "sms",
4531
- recipient,
4532
- code,
4533
- expiresInMs: this.opts.mfa.pincodeTtlMs
4534
- });
4535
- const pincode = ctx.pincode ??= {};
4536
- pincode.resendAllowedAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
4537
- pincode.sentTo = this.maskAddress(recipient, isEmail ? "email" : "sms");
4538
- 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);
4539
5189
  throw this.throwPublic(ctx, pincodeWf);
4540
5190
  }
4541
5191
  const input = pincodeWf.resolveInput();
4542
- 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));
4543
5194
  if (pinErr) throw this.throwPublic(ctx, pincodeWf, { errors: pinErr });
4544
5195
  await this.withStoreErrorTranslation(() => this.users.confirmMfaMethod(ctx.subject, isEmail ? "email" : "sms"));
4545
5196
  const channelState = ctx.channel ??= {};
@@ -4555,8 +5206,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4555
5206
  const target = isEmail ? channelState.email : channelState.phone;
4556
5207
  await this.consentStore.recordOtpChannelConsent(ctx.subject, channelArg, target, channelState.otpDisclosure);
4557
5208
  }
4558
- delete ctx.pin;
4559
- delete ctx.pinExpire;
5209
+ this.clearPin(ctx);
4560
5210
  if (ctx.pincode) {
4561
5211
  delete ctx.pincode.resendAllowedAt;
4562
5212
  delete ctx.pincode.sentTo;
@@ -4694,7 +5344,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4694
5344
  if (cooldownUntil && Date.now() < cooldownUntil) {
4695
5345
  const waitSec = Math.ceil((cooldownUntil - Date.now()) / 1e3);
4696
5346
  const channel = picked.kind === "sms" ? "SMS" : "email";
4697
- throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_CHANNEL", {
5347
+ throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_RESEND_WAIT_CHANNEL", {
4698
5348
  seconds: waitSec,
4699
5349
  channel
4700
5350
  }) });
@@ -4711,45 +5361,52 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4711
5361
  * `resolvePincodeTarget` (which discriminate on `ctx.mfa?.method` presence).
4712
5362
  */
4713
5363
  async pincodeSend(ctx) {
5364
+ const recovery = !ctx.mfa?.method && !ctx.signup;
5365
+ if (!ctx.mfa?.method) await enforceRateLimit(SEND_RATE_LIMIT);
4714
5366
  let target;
4715
- try {
5367
+ let account = null;
5368
+ if (recovery) {
5369
+ account = await this.recoveryAccount(ctx);
5370
+ target = await this.recoveryPincodeTarget(ctx, "typed");
5371
+ } else {
4716
5372
  const targetResult = this.resolvePincodeTarget(ctx);
4717
5373
  target = targetResult instanceof Promise ? await targetResult : targetResult;
4718
- } catch (err) {
4719
- if (err instanceof RecoveryMethodUnavailableError) {
4720
- ctx.aborted = true;
4721
- this.finishGenericRecovery();
4722
- return;
4723
- }
4724
- throw err;
4725
5374
  }
4726
- const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
4727
- if (ctx.mfa?.method) await this.dispatch({
4728
- kind: "mfa-pincode",
4729
- channel: target.channel,
4730
- recipient: target.address,
4731
- code,
4732
- expiresInMs: this.opts.mfa.pincodeTtlMs
4733
- });
4734
- else if (ctx.signup) await this.dispatch({
4735
- kind: "signup-pincode",
4736
- channel: "email",
4737
- recipient: target.address,
4738
- code,
4739
- expiresInMs: this.opts.mfa.pincodeTtlMs
4740
- });
4741
- else await this.dispatch({
4742
- kind: "recovery-pincode",
4743
- channel: target.channel,
4744
- recipient: target.address,
4745
- code,
4746
- expiresInMs: this.opts.mfa.pincodeTtlMs
4747
- });
4748
- const otp = ctx.otp ??= {};
4749
- otp.deliveredTo = target.address;
4750
- 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
+ }
4751
5407
  const pincode = ctx.pincode ??= {};
4752
- pincode.sentTo = this.maskAddress(target.address, target.channel);
5408
+ if (registeredRecovery) delete pincode.sentTo;
5409
+ else pincode.sentTo = this.maskAddress(target.address, target.channel);
4753
5410
  pincode.codeLength = this.opts.mfa.pincodeLength;
4754
5411
  const cooldownAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
4755
5412
  pincode.resendAllowedAt = cooldownAt;
@@ -4766,12 +5423,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4766
5423
  if (action) {
4767
5424
  const outcome = this.resolvePincodeAltAction(ctx, action);
4768
5425
  if (outcome === "resend") {
4769
- if (ctx.pincode?.resendAllowedAt && ctx.pincode.resendAllowedAt > Date.now()) {
4770
- const remainingSec = Math.ceil((ctx.pincode.resendAllowedAt - Date.now()) / 1e3);
4771
- throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT", { seconds: remainingSec }) });
4772
- }
4773
- delete ctx.pin;
4774
- 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);
4775
5428
  return;
4776
5429
  }
4777
5430
  if (outcome === "exit") {
@@ -4783,8 +5436,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4783
5436
  ctx.mfa.ignoreDefault = true;
4784
5437
  delete ctx.mfa.method;
4785
5438
  }
4786
- delete ctx.pin;
4787
- delete ctx.pinExpire;
5439
+ this.clearPin(ctx);
4788
5440
  if (ctx.pincode) delete ctx.pincode.resendAllowedAt;
4789
5441
  return;
4790
5442
  }
@@ -4796,15 +5448,22 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4796
5448
  if (ctx.postReset && err instanceof StepRetriableError) throw this.stampRecoveryExpiry(err);
4797
5449
  throw err;
4798
5450
  }
4799
- 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));
4800
5455
  if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
4801
5456
  const otp = ctx.otp ??= {};
5457
+ if (account) {
5458
+ ctx.subject = account.subject;
5459
+ otp.deliveredTo = account.address;
5460
+ otp.deliveredChannel = account.channel;
5461
+ }
4802
5462
  otp.verified = true;
4803
5463
  if (ctx.subject && otp.deliveredChannel === "email" && otp.deliveredTo) await this.users.setVerifiedEmail(ctx.subject, otp.deliveredTo);
4804
5464
  (ctx.session ??= {}).riskStepUpEvaluated = false;
4805
5465
  if (ctx.deviceTrust?.enabled && ctx.deviceTrust?.optIn) (ctx.trust ??= {}).rememberDevice = Boolean(input.rememberDevice);
4806
- delete ctx.pin;
4807
- delete ctx.pinExpire;
5466
+ this.clearPin(ctx);
4808
5467
  }
4809
5468
  /**
4810
5469
  * TOTP MFA challenge step body. Verifies a TOTP code via `users.verifyMfa`
@@ -4828,12 +5487,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4828
5487
  if (ctx.deviceTrust?.enabled && ctx.deviceTrust?.optIn) (ctx.trust ??= {}).rememberDevice = Boolean(input.rememberDevice);
4829
5488
  } catch (err) {
4830
5489
  if (err instanceof UserAuthError) {
4831
- if (err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
4832
- if (err.type === "INACTIVE") throw this.throwPublic(ctx, wf, { errors: { code: this.msg("INVALID_CODE") } });
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") } });
4833
5492
  if (err.type === "MFA_NOT_CONFIGURED") throw this.httpError(400, "TOTP_NOT_CONFIGURED");
4834
5493
  if (err.type === "MFA_INVALID") {
4835
- if (err.details?.lockEnds !== void 0) throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
4836
- 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") } });
4837
5496
  }
4838
5497
  }
4839
5498
  throw err;
@@ -4876,7 +5535,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4876
5535
  return;
4877
5536
  }
4878
5537
  const picked = wf.resolveInput().method;
4879
- 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") } });
4880
5539
  m.method = picked;
4881
5540
  }
4882
5541
  return this.provisionTotpSecret(ctx);
@@ -5009,18 +5668,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5009
5668
  if (action === "resend") {
5010
5669
  if (m.method === "totp") throw this.throwPublic(ctx, wf, { formMessage: this.msg("TOTP_RESEND_NOT_APPLICABLE") });
5011
5670
  const cooldown = ctx.pincode?.resendAllowedAt;
5012
- if (cooldown && Date.now() < cooldown) {
5013
- const waitSec = Math.ceil((cooldown - Date.now()) / 1e3);
5014
- throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_ANOTHER", { seconds: waitSec }) });
5015
- }
5016
- 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);
5017
5673
  return;
5018
5674
  }
5019
5675
  const input = wf.resolveInput();
5020
5676
  if (m.method === "totp") {
5021
- 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") } });
5022
5678
  } else {
5023
- 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));
5024
5680
  if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
5025
5681
  }
5026
5682
  await this.confirmEnrolledFactor(ctx);
@@ -5050,8 +5706,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5050
5706
  if (!m.keepExistingDefault) await this.users.setDefaultMfaMethod(username, methodName);
5051
5707
  m.done = true;
5052
5708
  (ctx.otp ??= {}).verified = true;
5053
- delete ctx.pin;
5054
- delete ctx.pinExpire;
5709
+ this.clearPin(ctx);
5055
5710
  }
5056
5711
  /**
5057
5712
  * Promote a freshly-confirmed channel into its login-handle column so future
@@ -5105,8 +5760,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5105
5760
  if (res.require) {
5106
5761
  session.riskStepUpReason = res.reason ?? "additional verification required";
5107
5762
  if (ctx.otp) delete ctx.otp.verified;
5108
- delete ctx.pin;
5109
- delete ctx.pinExpire;
5763
+ this.clearPin(ctx);
5110
5764
  } else delete session.riskStepUpReason;
5111
5765
  }
5112
5766
  /**
@@ -5299,6 +5953,36 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5299
5953
  }
5300
5954
  }
5301
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
+ /**
5302
5986
  * The SINGLE login-completion funnel. Every flow that establishes an
5303
5987
  * authenticated session routes through here — placed in each login schema
5304
5988
  * right after the guards and BEFORE the delivery terminal (`issue` /
@@ -5346,6 +6030,21 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5346
6030
  }
5347
6031
  }
5348
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
+ /**
5349
6048
  * Thin dispatcher steps for the flow-specific lifecycle hooks. Each is its own
5350
6049
  * schema step (rather than an in-terminal call) because its flow's finalize
5351
6050
  * terminals are SHARED across flows (`finalize-auto-login` serves invite +
@@ -5370,6 +6069,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5370
6069
  */
5371
6070
  async issue(ctx) {
5372
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
+ }
5373
6078
  const issue = await this.issueForContext(ctx);
5374
6079
  const auth = useAuth();
5375
6080
  const envelope = {
@@ -5548,6 +6253,10 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5548
6253
  } });
5549
6254
  return;
5550
6255
  }
6256
+ if (await this.loginAccountBlocked(ctx)) {
6257
+ await pending.delete(handle);
6258
+ return;
6259
+ }
5551
6260
  const { code } = await codes.mint({
5552
6261
  userId: ctx.subject,
5553
6262
  codeChallenge: req.codeChallenge,
@@ -5650,7 +6359,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5650
6359
  target,
5651
6360
  reason: "reset-success"
5652
6361
  },
5653
- skipButton: { label: this.msg("GO_NOW") }
6362
+ skipButton: { label: this.msg("AOOTH_GO_NOW") }
5654
6363
  }
5655
6364
  });
5656
6365
  (ctx.completion ??= {}).redirectUrl = target;
@@ -5663,13 +6372,14 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5663
6372
  * tokens (WF-INVITE-020).
5664
6373
  *
5665
6374
  * It records NOTHING and guards NOTHING: `account.lastLogin` + the
5666
- * `afterLogin` hook are owned by the upstream `record-login` funnel step, and
5667
- * the admin-only-survived-lock guard by the upstream `recovery-lock-check`
5668
- * step — both of which `{ break }`/gate this step out when they apply, so a
5669
- * 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.
5670
6379
  */
5671
6380
  async finalizeAutoLogin(ctx) {
5672
6381
  this.requireSubject(ctx);
6382
+ if (!(await this.users.getUser(ctx.subject)).account.active) throw new HttpError$1(403, "Account is not active");
5673
6383
  const issue = await this.issueForContext(ctx);
5674
6384
  const auth = useAuth();
5675
6385
  const previousMessage = (useWfFinished().get()?.value)?.message;
@@ -5772,7 +6482,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5772
6482
  finishWf({
5773
6483
  message: {
5774
6484
  level: "info",
5775
- text: this.msg("ALREADY_HAVE_ACCOUNT")
6485
+ text: this.msg("AOOTH_ALREADY_HAVE_ACCOUNT")
5776
6486
  },
5777
6487
  next: {
5778
6488
  trigger: "immediate",
@@ -5792,9 +6502,215 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5792
6502
  * the freshly-created `ctx.subject`. Mirrors login's `extra-step` seam.
5793
6503
  */
5794
6504
  signupExtraStep(_ctx) {}
5795
- magicLinkRequest(_ctx) {}
5796
- magicLinkSend(_ctx) {}
5797
- 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
+ }
5798
6714
  passkey(_ctx) {}
5799
6715
  /**
5800
6716
  * Verify the OAuth callback and resolve a user. Reaches here (instead of
@@ -5854,7 +6770,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5854
6770
  finishWf({
5855
6771
  message: {
5856
6772
  level: "success",
5857
- text: this.msg("ACCOUNT_LINKED")
6773
+ text: this.msg("AOOTH_ACCOUNT_LINKED")
5858
6774
  },
5859
6775
  next: {
5860
6776
  trigger: "immediate",
@@ -6005,11 +6921,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
6005
6921
  * the confirmed channel vanished between resolve and dispatch (the caller
6006
6922
  * routes that to the safe generic terminal).
6007
6923
  */
6008
- async deliverPendingLinkPin(candidate, pending) {
6924
+ async deliverPendingLinkPin(candidate, pending, claimed) {
6009
6925
  const method = candidate.mfa.methods.find((m) => m.name === pending.otpChannel && m.confirmed);
6010
6926
  if (!method) return null;
6011
- const code = this.mintPin(pending, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
6012
- await this.dispatch({
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({
6013
6930
  kind: "mfa-pincode",
6014
6931
  channel: pending.otpChannel,
6015
6932
  recipient: method.value,
@@ -6067,11 +6984,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
6067
6984
  }
6068
6985
  if (isOtp && action === "resend") {
6069
6986
  const cooldown = pending.resendAllowedAt;
6070
- if (cooldown && Date.now() < cooldown) {
6071
- const waitSec = Math.ceil((cooldown - Date.now()) / 1e3);
6072
- throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_ANOTHER", { seconds: waitSec }) });
6073
- }
6074
- 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);
6075
6989
  if (sentTo === null) {
6076
6990
  delete ctx.pendingLink;
6077
6991
  return this.finishOAuth(ctx, "needs-link");
@@ -6081,12 +6995,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
6081
6995
  }
6082
6996
  const input = wf.resolveInput();
6083
6997
  if (isOtp) {
6084
- const pinErr = this.verifyPin(pending, input.code);
6998
+ const pinErr = await this.verifyPin(pending, input.code, pending.candidateUserId, this.linkTarget(pending));
6085
6999
  if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
6086
7000
  } else try {
6087
7001
  await this.users.login(candidate.username, input.password ?? "", this.lockoutOverride(ctx));
6088
7002
  } catch (err) {
6089
- 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") });
6090
7004
  throw this.throwPublic(ctx, wf, { errors: { password: this.msg("INVALID_PASSWORD") } });
6091
7005
  }
6092
7006
  if (this.isAccountBlocked(candidate)) {
@@ -6132,8 +7046,9 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
6132
7046
  */
6133
7047
  inviteFlow() {}
6134
7048
  /**
6135
- * recovery.flow — OTP-via-email reset. `@Public()` on the body because
6136
- * 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.
6137
7052
  */
6138
7053
  recoveryFlow() {}
6139
7054
  /**
@@ -6823,6 +7738,14 @@ __decorate([
6823
7738
  __decorateMetadata("design:paramtypes", [Object]),
6824
7739
  __decorateMetadata("design:returntype", Promise)
6825
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);
6826
7749
  __decorate([
6827
7750
  Step("record-login"),
6828
7751
  Public(),
@@ -6839,6 +7762,14 @@ __decorate([
6839
7762
  __decorateMetadata("design:paramtypes", [Object]),
6840
7763
  __decorateMetadata("design:returntype", Promise)
6841
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);
6842
7773
  __decorate([
6843
7774
  Step("after-invitation-accepted"),
6844
7775
  Public(),
@@ -6957,7 +7888,7 @@ __decorate([
6957
7888
  __decorateParam(0, WorkflowParam("context")),
6958
7889
  __decorateMetadata("design:type", Function),
6959
7890
  __decorateMetadata("design:paramtypes", [Object]),
6960
- __decorateMetadata("design:returntype", Object)
7891
+ __decorateMetadata("design:returntype", Promise)
6961
7892
  ], AuthWorkflow.prototype, "magicLinkRequest", null);
6962
7893
  __decorate([
6963
7894
  Step("magic-link-send"),
@@ -6965,16 +7896,40 @@ __decorate([
6965
7896
  __decorateParam(0, WorkflowParam("context")),
6966
7897
  __decorateMetadata("design:type", Function),
6967
7898
  __decorateMetadata("design:paramtypes", [Object]),
6968
- __decorateMetadata("design:returntype", Object)
7899
+ __decorateMetadata("design:returntype", Promise)
6969
7900
  ], AuthWorkflow.prototype, "magicLinkSend", null);
6970
7901
  __decorate([
6971
- Step("magic-link-verified"),
7902
+ Step("magic-link-confirm"),
6972
7903
  Public(),
6973
7904
  __decorateParam(0, WorkflowParam("context")),
6974
7905
  __decorateMetadata("design:type", Function),
6975
7906
  __decorateMetadata("design:paramtypes", [Object]),
6976
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)
6977
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);
6978
7933
  __decorate([
6979
7934
  Step("passkey"),
6980
7935
  Public(),
@@ -7010,7 +7965,19 @@ __decorate([
7010
7965
  },
7011
7966
  {
7012
7967
  id: "credentials",
7013
- 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
+ ]
7014
7981
  },
7015
7982
  {
7016
7983
  id: "prove-control",
@@ -7030,12 +7997,7 @@ __decorate([
7030
7997
  { break: (ctx) => !!ctx.aborted },
7031
7998
  {
7032
7999
  condition: () => false,
7033
- steps: [
7034
- { id: "magic-link-request" },
7035
- { id: "magic-link-send" },
7036
- { id: "magic-link-verified" },
7037
- { id: "passkey" }
7038
- ]
8000
+ steps: [{ id: "passkey" }]
7039
8001
  },
7040
8002
  {
7041
8003
  id: "ask/email",
@@ -7083,6 +8045,10 @@ __decorate([
7083
8045
  id: "check-password-unchanged",
7084
8046
  condition: (ctx) => ctx.passwordStamp !== void 0 && !ctx.passwordChanged
7085
8047
  },
8048
+ {
8049
+ id: "check-can-sign-in",
8050
+ condition: (ctx) => !!ctx.subject && !ctx.aborted
8051
+ },
7086
8052
  { break: (ctx) => !!ctx.aborted },
7087
8053
  {
7088
8054
  id: "record-login",
@@ -7184,6 +8150,10 @@ __decorate([
7184
8150
  id: "finalize-fresh-login",
7185
8151
  condition: (ctx) => !ctx.autoLogin
7186
8152
  },
8153
+ {
8154
+ id: "auto-login-check",
8155
+ condition: (ctx) => !!ctx.autoLogin
8156
+ },
7187
8157
  {
7188
8158
  id: "record-login",
7189
8159
  condition: (ctx) => !!ctx.autoLogin
@@ -7205,11 +8175,22 @@ __decorate([
7205
8175
  WorkflowSchema([
7206
8176
  { id: "init-recovery" },
7207
8177
  { id: "request" },
7208
- { 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" },
7209
8191
  { id: "prepare-post-reset" },
7210
8192
  { id: "prepare-recovery-alt-actions" },
7211
8193
  { id: "prepare-lockout" },
7212
- { id: "prepare-consents" },
7213
8194
  { id: "prepare-semantic-flags" },
7214
8195
  {
7215
8196
  while: (ctx) => !ctx.otp?.verified && !ctx.aborted,
@@ -7218,7 +8199,11 @@ __decorate([
7218
8199
  { break: (ctx) => !!ctx.aborted },
7219
8200
  {
7220
8201
  condition: (ctx) => !!ctx.otp?.verified,
7221
- 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
+ ]
7222
8207
  },
7223
8208
  { break: (ctx) => !!ctx.aborted },
7224
8209
  {
@@ -7240,6 +8225,10 @@ __decorate([
7240
8225
  id: "finalize-fresh-login",
7241
8226
  condition: (ctx) => !ctx.autoLogin
7242
8227
  },
8228
+ {
8229
+ id: "auto-login-check",
8230
+ condition: (ctx) => !!ctx.autoLogin
8231
+ },
7243
8232
  {
7244
8233
  id: "record-login",
7245
8234
  condition: (ctx) => !!ctx.autoLogin
@@ -7341,6 +8330,7 @@ __decorate([
7341
8330
  ...consentsPersistTailSchema,
7342
8331
  { id: "signup-extra-step" },
7343
8332
  { id: "after-signup" },
8333
+ { id: "auto-login-check" },
7344
8334
  { id: "record-login" },
7345
8335
  { id: "finalize-auto-login" }
7346
8336
  ]),
@@ -7383,12 +8373,16 @@ const ADD_MFA_WORKFLOW = "auth/add-mfa/flow";
7383
8373
  function inviteNotFound() {
7384
8374
  return aoothHttpError(404, "INVITE_NOT_FOUND");
7385
8375
  }
7386
- /** Prefer an explicit body field, fall back to the refresh cookie when enabled. */
7387
- function resolveRefreshToken(auth, body) {
7388
- if (typeof body?.refreshToken === "string") return body.refreshToken;
7389
- if (!auth.options.enableCookie) return void 0;
7390
- return useCookies(current()).getCookie(auth.options.refreshCookie.name) ?? void 0;
7391
- }
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
+ };
7392
8386
  let AuthController = class AuthController {
7393
8387
  auth;
7394
8388
  users;
@@ -7414,13 +8408,13 @@ let AuthController = class AuthController {
7414
8408
  }
7415
8409
  async logout(body) {
7416
8410
  const auth = useAuth();
7417
- if (!auth.getAuthContext()) throw aoothHttpError(401, "NOT_AUTHENTICATED");
8411
+ if (!auth.getAuthContext()) throw aoothHttpError(401, "AOOTH_NOT_AUTHENTICATED");
7418
8412
  const sessionId = auth.getSessionId();
7419
8413
  if (sessionId) try {
7420
8414
  await this.auth.revokeSession(auth.getUserId(), sessionId);
7421
8415
  } catch {}
7422
8416
  const accessToken = auth.extractToken();
7423
- const refreshToken = resolveRefreshToken(auth, body);
8417
+ const refreshToken = resolveRefreshToken(auth.options, body);
7424
8418
  if (accessToken) try {
7425
8419
  await this.auth.revoke(accessToken);
7426
8420
  } catch {}
@@ -7430,9 +8424,17 @@ let AuthController = class AuthController {
7430
8424
  auth.clearCookies();
7431
8425
  return { ok: true };
7432
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
+ */
7433
8435
  async refresh(body) {
7434
8436
  const auth = useAuth();
7435
- const refreshToken = resolveRefreshToken(auth, body);
8437
+ const refreshToken = resolveRefreshToken(auth.options, body);
7436
8438
  if (!refreshToken) throw aoothHttpError(401, "MISSING_REFRESH_TOKEN");
7437
8439
  const fromBody = typeof body?.refreshToken === "string";
7438
8440
  let issue;
@@ -7449,7 +8451,7 @@ let AuthController = class AuthController {
7449
8451
  }
7450
8452
  status() {
7451
8453
  const auth = useAuth().getAuthContext();
7452
- if (!auth) throw aoothHttpError(401, "NOT_AUTHENTICATED");
8454
+ if (!auth) throw aoothHttpError(401, "AOOTH_NOT_AUTHENTICATED");
7453
8455
  return auth;
7454
8456
  }
7455
8457
  triggerWf() {}
@@ -7498,7 +8500,7 @@ let AuthController = class AuthController {
7498
8500
  */
7499
8501
  async invitePostRedemption(uid) {
7500
8502
  if (!this.invitePostRedemptionEnabled()) throw inviteNotFound();
7501
- if (!uid) throw aoothHttpError(400, "MISSING_UID");
8503
+ if (!uid) throw aoothHttpError(400, "AOOTH_MISSING_UID");
7502
8504
  if (!this.users) throw new HttpError$1(500, "UserService not wired — cannot resolve post-redemption state");
7503
8505
  let user;
7504
8506
  try {
@@ -7553,6 +8555,11 @@ __decorate([
7553
8555
  __decorate([
7554
8556
  Post("refresh"),
7555
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
+ }),
7556
8563
  __decorateParam(0, Body()),
7557
8564
  __decorateMetadata("design:type", Function),
7558
8565
  __decorateMetadata("design:paramtypes", [Object]),
@@ -7594,7 +8601,7 @@ __decorate([
7594
8601
  __decorate([
7595
8602
  Get("invite/post-redemption"),
7596
8603
  Public(),
7597
- RateLimit("30/5m"),
8604
+ RateLimit("30/5m", { id: "aooth.invite-post-redemption" }),
7598
8605
  __decorateParam(0, Query("uid")),
7599
8606
  __decorateMetadata("design:type", Function),
7600
8607
  __decorateMetadata("design:paramtypes", [Object]),
@@ -7841,7 +8848,7 @@ let OAuthController = class OAuthController {
7841
8848
  try {
7842
8849
  return this.registry.require(providerId);
7843
8850
  } catch (err) {
7844
- if (err instanceof OAuthError && err.type === "UNKNOWN_PROVIDER") throw aoothHttpError(404, "UNKNOWN_PROVIDER", { provider: providerId });
8851
+ if (err instanceof OAuthError && err.type === "UNKNOWN_PROVIDER") throw aoothHttpError(404, "AOOTH_UNKNOWN_PROVIDER", { provider: providerId });
7845
8852
  throw err;
7846
8853
  }
7847
8854
  }
@@ -7904,6 +8911,18 @@ function toConnectedAccount(i) {
7904
8911
  };
7905
8912
  }
7906
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
+ };
7907
8926
  /** Shared default claims resolver — stateless, so one instance is reused across requests. */
7908
8927
  const NOOP_OIDC_CLAIMS_RESOLVER = new NoopOidcClaimsResolver();
7909
8928
  let AuthorizeController = class AuthorizeController {
@@ -8019,6 +9038,13 @@ let AuthorizeController = class AuthorizeController {
8019
9038
  res.setHeader("Location", target);
8020
9039
  return "";
8021
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
+ */
8022
9048
  async token(body) {
8023
9049
  if (body?.grant_type === "refresh_token") return await this.refreshTokenGrant(body);
8024
9050
  const res = useResponse(current());
@@ -8338,6 +9364,11 @@ __decorate([
8338
9364
  __decorate([
8339
9365
  Post("token"),
8340
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
+ }),
8341
9372
  __decorateParam(0, Body()),
8342
9373
  __decorateMetadata("design:type", Function),
8343
9374
  __decorateMetadata("design:paramtypes", [Object]),
@@ -8360,6 +9391,7 @@ __decorate([
8360
9391
  __decorate([
8361
9392
  Post("register"),
8362
9393
  Public(),
9394
+ RateLimit(AUTHZ_RATE_LIMITS["aooth.register"], { id: "aooth.register" }),
8363
9395
  __decorateParam(0, Body()),
8364
9396
  __decorateMetadata("design:type", Function),
8365
9397
  __decorateMetadata("design:paramtypes", [Object]),
@@ -8417,4 +9449,4 @@ function createAuthEmailOutlet(deps) {
8417
9449
  await deps.emailSender.send(event);
8418
9450
  });
8419
9451
  }
8420
- 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, 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 };