@aooth/auth-moost 0.2.5 → 0.2.7

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
- import { HttpError, resolveForwarded, useAuthorization, useCookies, useHeaders, useRequest, useResponse, useUrlParams } from "@wooksjs/event-http";
5
+ import { HttpError, 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, normalizeWfId, 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,19 @@ 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
- /** 403 — the workflow trigger refused a workflow outside its allow list. Params: `workflow`. */
135
- WORKFLOW_NOT_ALLOWED: "Workflow '{workflow}' is not allowed"
134
+ AOOTH_UNKNOWN_PROVIDER: "Unknown provider '{provider}'",
135
+ /** 429 — the one-time codes of this account or address failed too often; answered to every code send and check until the window passes. */
136
+ AOOTH_CODE_LIMIT_REACHED: "Too many code attempts. Try again later.",
137
+ /** 403 — the workflow trigger refused a START (outside `allow`, in `resumeOnly`, or `block`ed, or an unregistered id under `allow`). Params: `workflow`. */
138
+ AOOTH_WORKFLOW_NOT_ALLOWED: "Workflow '{workflow}' is not allowed",
139
+ /** 403 — a refused RESUME (not in the route's `allow` / `resumeOnly`, or `block`ed). No params: it never names the stored flow. */
140
+ AOOTH_WORKFLOW_RESUME_NOT_ALLOWED: "Workflow is not allowed"
136
141
  };
137
142
  registerMessages(AOOTH_HTTP_MESSAGES);
138
143
  /** An `HttpError` with `code`, `params` and the code's English text. */
@@ -150,6 +155,45 @@ function codedHttpError(status, code, message, params) {
150
155
  ...params && { params }
151
156
  });
152
157
  }
158
+ // src/rate-limit/subjects.ts
159
+ /**
160
+ * Internal: a fixed-size, one-way rate-limit subject for a bearer token
161
+ * (`rt:` + 128 bits of its SHA-256) — the raw secret never becomes a counter
162
+ * key in the store.
163
+ */
164
+ function tokenSubject(token) {
165
+ return `rt:${createHash("sha256").update(canonicalToken(token)).digest("base64url").slice(0, 22)}`;
166
+ }
167
+ /**
168
+ * The base64url-canonical form of a token, segment by segment (`.`-separated,
169
+ * as in a JWT): Node's decoder skips stray characters and reads `+/=`, so
170
+ * `tok=`, `tok `, `tok\n` or a `+/` spelling are one bucket, not several.
171
+ */
172
+ function canonicalToken(token) {
173
+ return token.split(".").map((segment) => Buffer.from(segment, "base64url").toString("base64url")).join(".");
174
+ }
175
+ /**
176
+ * Internal: the request body for code that runs before the handler (moost's
177
+ * `@Body()` reuses the parse) — `undefined` when it cannot be parsed.
178
+ */
179
+ async function tryParseBody(ctx = current()) {
180
+ try {
181
+ return await useBody(ctx).parseBody();
182
+ } catch {
183
+ return;
184
+ }
185
+ }
186
+ /**
187
+ * Internal key function of the `aooth.token-refresh` policy on
188
+ * `POST /auth/token`: the `refresh_token` of a `grant_type=refresh_token`
189
+ * request, as a {@link tokenSubject}. Any other request skips the policy.
190
+ * Runs before the auth guard (it needs nothing the guard sets); an unparsable
191
+ * body is no token.
192
+ */
193
+ async function oauthRefreshTokenSubject() {
194
+ const { grant_type: grant, refresh_token: token } = await tryParseBody() ?? {};
195
+ return grant === "refresh_token" && typeof token === "string" && token ? tokenSubject(token) : null;
196
+ }
153
197
  // src/auth.composables.ts
154
198
  const authContextKey = key("auth.context");
155
199
  const authCredentialKey = key("auth.credential");
@@ -207,7 +251,7 @@ const useAuth = defineWook((ctx) => {
207
251
  };
208
252
  const getUserId = () => {
209
253
  const auth = getAuthContext();
210
- if (!auth) throw aoothHttpError(401, "NOT_AUTHENTICATED");
254
+ if (!auth) throw aoothHttpError(401, "AOOTH_NOT_AUTHENTICATED");
211
255
  return auth.userId;
212
256
  };
213
257
  const isAuthenticated = () => getAuthContext() !== null;
@@ -323,6 +367,27 @@ function setAuthContext(ctx, value) {
323
367
  function setAuthCredential(ctx, value) {
324
368
  ctx.set(authCredentialKey, value);
325
369
  }
370
+ /**
371
+ * Internal: the refresh token a request presents — an explicit body
372
+ * `refreshToken` first, else the refresh cookie when the guard enables
373
+ * cookies. Shared by `AuthController.refresh/logout` and the `'refresh-token'`
374
+ * rate-limit subject, so both read the same token.
375
+ */
376
+ function resolveRefreshToken(options, body, ctx = current()) {
377
+ const fromBody = body?.refreshToken;
378
+ if (typeof fromBody === "string") return fromBody;
379
+ if (!options?.enableCookie) return void 0;
380
+ return useCookies(ctx).getCookie(options.refreshCookie.name) ?? void 0;
381
+ }
382
+ /**
383
+ * Internal: {@link resolveRefreshToken} for code that runs before the handler
384
+ * (the rate limiter): parses the body itself (moost's `@Body()` reuses the
385
+ * parse), treats an unparsable body as none, and reads the cookie only once
386
+ * `authGuardInterceptor` has published its options.
387
+ */
388
+ async function readPresentedRefreshToken(ctx = current()) {
389
+ return resolveRefreshToken(ctx.has(authOptionsKey) ? ctx.get(authOptionsKey) : void 0, await tryParseBody(ctx), ctx);
390
+ }
326
391
  // src/auth.route.ts
327
392
  /**
328
393
  * Normalize a router path into a value usable as a cookie `Path` attribute:
@@ -383,7 +448,7 @@ function authGuardInterceptor(opts) {
383
448
  setAuthContext(ctx, null);
384
449
  return;
385
450
  }
386
- throw aoothHttpError(401, "AUTH_REQUIRED");
451
+ throw aoothHttpError(401, "AOOTH_AUTH_REQUIRED");
387
452
  }
388
453
  const credential = await cc.instantiate(AuthCredential);
389
454
  setAuthCredential(ctx, credential);
@@ -393,7 +458,7 @@ function authGuardInterceptor(opts) {
393
458
  setAuthContext(ctx, null);
394
459
  return;
395
460
  }
396
- throw aoothHttpError(401, "CREDENTIAL_INVALID");
461
+ throw aoothHttpError(401, "AOOTH_CREDENTIAL_INVALID");
397
462
  }
398
463
  setAuthContext(ctx, authContext);
399
464
  }, TInterceptorPriority.GUARD);
@@ -446,8 +511,22 @@ const UserId = () => Resolve(() => useAuth().getUserId());
446
511
  * evaluated so far), written by `rateLimitInterceptors`.
447
512
  */
448
513
  const rateLimitDecisionKey = key("aooth.rateLimit.decision");
449
- /** Internal: phases (`pre` / `post`) that already evaluated this event — the double-count guard. */
450
- const rateLimitPhasesKey = key("aooth.rateLimit.phases");
514
+ /** Internal: the installed interceptors' runtime, published on every HTTP event. */
515
+ const rateLimitRuntimeKey = key("aooth.rateLimit.runtime");
516
+ const rateLimitCheckedKey = key("aooth.rateLimit.checked");
517
+ /**
518
+ * Internal: the decision of every policy already checked on `limiter` during
519
+ * this event, by `<phase>:<scope>` — the double-count guard (a policy registered
520
+ * twice on the same limiter counts once) and what a later chain on the same
521
+ * event re-answers.
522
+ */
523
+ function checkedPolicies(ctx, limiter) {
524
+ let byLimiter = ctx.has(rateLimitCheckedKey) ? ctx.get(rateLimitCheckedKey) : void 0;
525
+ if (!byLimiter) ctx.set(rateLimitCheckedKey, byLimiter = /* @__PURE__ */ new Map());
526
+ let checked = byLimiter.get(limiter);
527
+ if (!checked) byLimiter.set(limiter, checked = /* @__PURE__ */ new Map());
528
+ return checked;
529
+ }
451
530
  /**
452
531
  * Internal: named rate-limit subjects for this event — subject kind
453
532
  * (`'user'`, `'tenant'`, …) → resolved caller identity, written via
@@ -478,6 +557,46 @@ function getRateLimitSubject(kind, ctx = current()) {
478
557
  function useRateLimit(ctx = current()) {
479
558
  return { decision: ctx.has(rateLimitDecisionKey) ? ctx.get(rateLimitDecisionKey) : null };
480
559
  }
560
+ // src/rate-limit/registry.ts
561
+ /**
562
+ * Policy ids that `rateLimitInterceptors({ policies })` accepts: every
563
+ * `@RateLimit({ id })` registers its id when it decorates, and aooth's own
564
+ * handler-enforced policies register below. Process-wide.
565
+ */
566
+ const declared = /* @__PURE__ */ new Set();
567
+ /** Internal: record a policy id as re-tunable through `policies`. */
568
+ function declareRateLimitId(id) {
569
+ declared.add(id);
570
+ }
571
+ /** Internal: whether `id` was declared (see {@link declareRateLimitId}). */
572
+ function isDeclaredRateLimitId(id) {
573
+ return declared.has(id);
574
+ }
575
+ /** Internal: every declared id, sorted. */
576
+ function declaredRateLimitIds() {
577
+ return [...declared].toSorted();
578
+ }
579
+ /** Declare a bundled handler-enforced policy: its id and parsed rule. */
580
+ function bundledRateLimit(id, rule) {
581
+ declareRateLimitId(id);
582
+ return {
583
+ id,
584
+ rules: [parseRateLimitRule(rule)]
585
+ };
586
+ }
587
+ /**
588
+ * The bundled per-IP limit on anonymous sends — recovery codes, magic links
589
+ * and signup codes (each request that could send, whether or not it does).
590
+ * Re-tune or switch off with `rateLimitInterceptors({ policies: { "aooth.send": … } })`.
591
+ */
592
+ const SEND_RATE_LIMIT = bundledRateLimit("aooth.send", "20/15m");
593
+ /**
594
+ * The bundled per-account limit on code sends after a first factor — the
595
+ * email/SMS second factor, MFA enrolment and channel checks, the proof code of
596
+ * a federated account link. Keyed by the account, not the IP. Re-tune or
597
+ * switch off with `rateLimitInterceptors({ policies: { "aooth.send-user": … } })`.
598
+ */
599
+ const SEND_USER_RATE_LIMIT = bundledRateLimit("aooth.send-user", "10/1h");
481
600
  // src/rate-limit/interceptor.ts
482
601
  registerMessages(RATE_LIMIT_MESSAGES);
483
602
  /**
@@ -487,7 +606,7 @@ registerMessages(RATE_LIMIT_MESSAGES);
487
606
  * ```ts
488
607
  * app.applyGlobalInterceptors(
489
608
  * authGuardInterceptor({ ... }),
490
- * ...rateLimitInterceptors({ limiter, trustProxy: true }),
609
+ * ...rateLimitInterceptors({ limiter }),
491
610
  * )
492
611
  * ```
493
612
  *
@@ -505,8 +624,12 @@ registerMessages(RATE_LIMIT_MESSAGES);
505
624
  *
506
625
  * Ownership is static per policy (from metadata/options): a route whose
507
626
  * stacked policies mix both kinds is evaluated by both phases, each checking
508
- * its own policies. A per-event phase marker guards against double counting
509
- * when the pair is also attached per-controller (see {@link RateLimited}).
627
+ * its own policies. Each policy is checked once per event: a per-event record
628
+ * of the checked policies guards against double counting when the pair is also
629
+ * attached per-controller (see {@link RateLimited}), and when a request runs
630
+ * the handler chains of two apps sharing one router (wooks moves on to the next
631
+ * chain when a handler throws) — the second chain re-answers a policy's
632
+ * rejection without counting it again and checks only the policies it adds.
510
633
  *
511
634
  * On rejection: draft `RateLimit-*` headers + `Retry-After` are written to
512
635
  * the accumulated response (they survive the throw — wooks renders the error
@@ -516,9 +639,17 @@ registerMessages(RATE_LIMIT_MESSAGES);
516
639
  */
517
640
  function rateLimitInterceptors(opts) {
518
641
  const defaultRules = opts?.rules?.map((r) => parseRateLimitRule(r));
642
+ const overrides = /* @__PURE__ */ new Map();
643
+ for (const [id, value] of Object.entries(opts?.policies ?? {})) {
644
+ 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).`);
645
+ const rules = value === false ? false : Array.isArray(value) ? value : [value];
646
+ if (rules !== false && rules.length === 0) throw new Error(`rateLimitInterceptors: policies["${id}"] has no rules — pass false to switch it off`);
647
+ overrides.set(id, rules && rules.map((r) => parseRateLimitRule(r)));
648
+ }
519
649
  const limiter = opts?.limiter ?? new RateLimiter$1();
520
650
  const emitHeaders = opts?.headers ?? true;
521
651
  const trustProxy = opts?.trustProxy ?? false;
652
+ if (opts?.trustProxy !== void 0) warnTrustProxyDeprecated();
522
653
  const routeConfigs = /* @__PURE__ */ new WeakMap();
523
654
  const resolveRouteConfig = (cc) => {
524
655
  const ctor = cc.getController().constructor;
@@ -542,15 +673,18 @@ function rateLimitInterceptors(opts) {
542
673
  post: []
543
674
  };
544
675
  for (const [i, policy] of declared.entries()) {
676
+ const scope = policy.options?.id ?? (i === 0 ? baseScope : `${baseScope}#${i}`);
677
+ const rules = effectiveRules(overrides, scope, policy.rules);
678
+ if (!rules) continue;
545
679
  const rawKey = policy.options?.key ?? opts?.key ?? "ip";
546
680
  const keyStrategy = rawKey === "auto" ? "user" : rawKey;
547
681
  const message = policy.options?.message ?? opts?.message;
548
682
  route[typeof keyStrategy === "string" && keyStrategy !== "ip" ? "post" : "pre"].push({
549
- rules: policy.rules,
683
+ rules,
550
684
  keyStrategy,
551
- scope: policy.options?.id ?? (i === 0 ? baseScope : `${baseScope}#${i}`),
685
+ scope,
552
686
  ...message !== void 0 && { defaultMessage: message },
553
- policyHeader: policy.rules.map((p) => `${p.limit};w=${Math.max(1, Math.round(p.window / 1e3))}`).join(", ")
687
+ policyHeader: policyHeader(rules)
554
688
  });
555
689
  }
556
690
  config = route;
@@ -558,65 +692,126 @@ function rateLimitInterceptors(opts) {
558
692
  byMethod.set(method, config);
559
693
  return config;
560
694
  };
695
+ const runtime = {
696
+ limiter,
697
+ overrides,
698
+ trustProxy,
699
+ emitHeaders
700
+ };
561
701
  const evaluate = async (phase) => {
562
702
  const ctx = current();
563
703
  if (ctx.get(eventTypeKey) !== "http") return;
564
- const done = ctx.has(rateLimitPhasesKey) ? ctx.get(rateLimitPhasesKey) : [];
565
- if (done.includes(phase)) return;
704
+ if (!ctx.has(rateLimitRuntimeKey)) ctx.set(rateLimitRuntimeKey, runtime);
566
705
  const config = resolveRouteConfig(useControllerContext(ctx));
567
706
  if (!config) return;
568
707
  const owned = config[phase];
569
708
  if (owned.length === 0) return;
570
- ctx.set(rateLimitPhasesKey, [...done, phase]);
709
+ const checked = checkedPolicies(ctx, limiter);
571
710
  const decisions = [];
572
711
  const headers = [];
573
712
  for (const policy of owned) {
574
- const subject = await resolveSubject(policy.keyStrategy, trustProxy, ctx);
713
+ const id = `${phase}:${policy.scope}`;
714
+ const seen = checked.get(id);
715
+ if (seen) {
716
+ if (!seen.allowed) answerDecision(seen, [], false, ctx);
717
+ continue;
718
+ }
719
+ const subject = await resolveSubject(policy.keyStrategy, ctx);
575
720
  if (subject == null) continue;
576
- decisions.push(await limiter.check(policy.scope, subject, policy.rules, { ...policy.defaultMessage !== void 0 && { defaultMessage: policy.defaultMessage } }));
721
+ const result = await limiter.check(policy.scope, subject, policy.rules, { ...policy.defaultMessage !== void 0 && { defaultMessage: policy.defaultMessage } });
722
+ checked.set(id, result);
723
+ decisions.push(result);
577
724
  headers.push(policy.policyHeader);
578
725
  }
579
- if (ctx.has(rateLimitDecisionKey)) decisions.unshift(ctx.get(rateLimitDecisionKey));
580
726
  if (decisions.length === 0) return;
727
+ if (ctx.has(rateLimitDecisionKey)) decisions.unshift(ctx.get(rateLimitDecisionKey));
581
728
  const decision = pickGoverning(decisions, (d) => !d.allowed);
582
729
  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
- }
730
+ answerDecision(decision, headers, emitHeaders, ctx);
596
731
  };
597
732
  return [defineBeforeInterceptor(() => evaluate("pre"), TInterceptorPriority.BEFORE_GUARD), defineBeforeInterceptor(() => evaluate("post"), TInterceptorPriority.AFTER_GUARD)];
598
733
  }
599
- async function resolveSubject(strategy, trustProxy, ctx) {
734
+ async function resolveSubject(strategy, ctx) {
600
735
  if (typeof strategy === "function") return await strategy();
601
736
  if (strategy !== "ip") {
602
737
  const subject = getRateLimitSubject(strategy, ctx);
603
738
  if (subject !== void 0) return subject;
739
+ if (strategy === "refresh-token") {
740
+ const token = await readPresentedRefreshToken(ctx);
741
+ return token === void 0 ? null : tokenSubject(token);
742
+ }
604
743
  const auth = strategy === "user" || strategy === "session" ? useAuth(ctx).getAuthContext() : null;
605
744
  if (strategy === "user" && auth?.userId !== void 0) return `u:${auth.userId}`;
606
745
  if (strategy === "session" && auth?.sessionId !== void 0) return `s:${auth.sessionId}`;
607
746
  }
608
- return `ip:${clientIp(trustProxy, ctx)}`;
747
+ return `ip:${requestClientIp(ctx)}`;
748
+ }
749
+ let warnedTrustProxy = false;
750
+ /** Warn once per process (at registration — no event yet) that the limiter's own `trustProxy` is deprecated. */
751
+ function warnTrustProxyDeprecated() {
752
+ if (warnedTrustProxy) return;
753
+ warnedTrustProxy = true;
754
+ console.warn("[aooth] rateLimitInterceptors({ trustProxy }) is deprecated — still honoured (one hop, using the app's proxyHeaders); removed in 0.3. Set `trustProxy` on the HTTP app instead.");
609
755
  }
610
- /** Hop 0 (the socket peer) is the one trusted proxy. */
611
- const trustOneHop = (_addr, hop) => hop < 1;
612
756
  /**
613
- * `trustProxy: true` resolves like wooks' deprecated `getIp({ trustProxy: true })`
614
- * (one trusted hop, the right-most forwarded entry; `''` with no known peer)
615
- * without its deprecation notice; otherwise the app's own `getIp()`.
757
+ * Internal: the client IP of the current HTTP event — the single source of
758
+ * every client IP aooth keys on (rate limits, one-time-code failure buckets,
759
+ * session metadata, device binding). The IP the HTTP app resolves
760
+ * (`useRequest().getIp()`, governed by the app's `trustProxy` /
761
+ * `proxyHeaders`); with the deprecated `rateLimitInterceptors({ trustProxy:
762
+ * true })` installed, wooks' one-hop resolution (`getIp({ trustProxy: true })`,
763
+ * which reads the app's `proxyHeaders` family). `""` outside an HTTP event.
616
764
  */
617
- function clientIp(trustProxy, ctx) {
618
- const req = useRequest(ctx);
619
- return trustProxy ? resolveForwarded(req.raw, trustOneHop).ip : req.getIp();
765
+ function requestClientIp(ctx = tryGetCurrent()) {
766
+ if (!ctx) return "";
767
+ try {
768
+ const req = useRequest(ctx);
769
+ return ctx.has(rateLimitRuntimeKey) && ctx.get(rateLimitRuntimeKey).trustProxy ? req.getIp({ trustProxy: true }) : req.getIp();
770
+ } catch {
771
+ return "";
772
+ }
773
+ }
774
+ /**
775
+ * Write the decision's `RateLimit-*` headers (with `emitHeaders`) and, when it
776
+ * rejects, `Retry-After` and the coded 429.
777
+ */
778
+ function answerDecision(decision, policyHeaders, emitHeaders, ctx) {
779
+ const response = useResponse(ctx);
780
+ if (emitHeaders) {
781
+ const prior = response.getHeader("ratelimit-policy");
782
+ if (typeof prior === "string" && prior) policyHeaders.unshift(prior);
783
+ response.setHeader("ratelimit-limit", String(decision.limit));
784
+ response.setHeader("ratelimit-remaining", String(decision.remaining));
785
+ response.setHeader("ratelimit-reset", String(Math.ceil(decision.resetAfterMs / 1e3)));
786
+ response.setHeader("ratelimit-policy", policyHeaders.join(", "));
787
+ }
788
+ if (!decision.allowed) {
789
+ response.setHeader("retry-after", String(Math.ceil(decision.resetAfterMs / 1e3)));
790
+ throw codedHttpError(429, decision.code ?? "RATE_LIMITED", decision.message ?? formatMessage(RATE_LIMIT_MESSAGES.RATE_LIMITED, decision.params), decision.params);
791
+ }
792
+ }
793
+ /**
794
+ * Internal: check a bundled policy from inside a handler — per client IP
795
+ * unless `key` names another subject (e.g. `user:<id>`), with the limiter and
796
+ * `policies` overrides of the installed `rateLimitInterceptors` (none
797
+ * installed → nothing is enforced, like any `@RateLimit`). Over the limit it
798
+ * throws the same coded 429 as the interceptors. Used by the auth workflow
799
+ * for code and link sends (`aooth.send`, `aooth.send-user`).
800
+ */
801
+ async function enforceRateLimit(policy, key, ctx = tryGetCurrent()) {
802
+ if (!ctx?.has(rateLimitRuntimeKey)) return;
803
+ const runtime = ctx.get(rateLimitRuntimeKey);
804
+ const rules = effectiveRules(runtime.overrides, policy.id, policy.rules);
805
+ if (!rules) return;
806
+ answerDecision(await runtime.limiter.check(policy.id, key ?? `ip:${requestClientIp(ctx)}`, rules), [policyHeader(rules)], runtime.emitHeaders, ctx);
807
+ }
808
+ /** The rules of policy `id` after `policies` overrides — `false` when switched off. */
809
+ function effectiveRules(overrides, id, declared) {
810
+ return overrides.get(id) ?? declared;
811
+ }
812
+ /** The draft `RateLimit-Policy` value of `rules` (`<limit>;w=<seconds>`, comma-joined). */
813
+ function policyHeader(rules) {
814
+ return rules.map((p) => `${p.limit};w=${Math.max(1, Math.round(p.window / 1e3))}`).join(", ");
620
815
  }
621
816
  // src/rate-limit/mate.ts
622
817
  function getRateLimitMate() {
@@ -632,6 +827,7 @@ function RateLimit(...args) {
632
827
  if (typeof last === "object" && last !== null && !("limit" in last)) options = inputs.pop();
633
828
  if (inputs.length === 0) throw new Error("@RateLimit requires at least one rule (or the literal `false` to opt out)");
634
829
  const rules = inputs.map((r) => parseRateLimitRule(r));
830
+ if (options?.id) declareRateLimitId(options.id);
635
831
  const policy = options ? {
636
832
  rules,
637
833
  options
@@ -693,6 +889,79 @@ function createInviteOutlet() {
693
889
  }
694
890
  };
695
891
  }
892
+ // src/workflow/magic-link-outlet.ts
893
+ /** Name of the outlet `AuthWorkflow` pauses on to send a recovery or sign-in magic link. */
894
+ const MAGIC_LINK_OUTLET = "magic-link";
895
+ /**
896
+ * Name of the state strategy a magic link's pause is persisted under
897
+ * (registered by `WfTriggerProvider`). Its own keyspace makes the trigger mint
898
+ * a fresh handle for the link, and the next pause swaps off it again — so the
899
+ * emailed token is consumed by its first use and never becomes the
900
+ * continuation of the flow.
901
+ */
902
+ const MAGIC_LINK_STRATEGY = "magic-link";
903
+ /** The answer of every magic-link request, sent or not: nothing tells the outcomes apart. */
904
+ const SENT = Object.freeze({
905
+ sent: true,
906
+ outlet: "email"
907
+ });
908
+ /**
909
+ * The `magic-link` outlet (registered by default on `WfTriggerProvider`). The
910
+ * step decides whether a link goes out (`context.deliver`); when it does, the
911
+ * link is handed to the app's `email` outlet (`createAuthEmailOutlet`) with
912
+ * the step's template (`recovery.magicLink` / `login.magicLink`). Known and
913
+ * unknown identifiers get the same answer, and a failed delivery is logged,
914
+ * not reported — the response never says whether an account exists.
915
+ *
916
+ * @param emailOutlet - resolves the app's `email` outlet at delivery time.
917
+ */
918
+ function createMagicLinkOutlet(emailOutlet) {
919
+ return {
920
+ name: MAGIC_LINK_OUTLET,
921
+ tokenDelivery: "out-of-band",
922
+ async deliver(request, token) {
923
+ const email = emailOutlet();
924
+ if (!email) throw new Error("Magic links are sent through the `email` outlet — append createAuthEmailOutlet(...) to WfTriggerProvider.outlets");
925
+ const { deliver, ...context } = request.context ?? {};
926
+ if (deliver === true && request.target) try {
927
+ await email.deliver({
928
+ ...request,
929
+ outlet: "email",
930
+ context
931
+ }, token);
932
+ } catch (err) {
933
+ useLogger("aooth:magic-link").error("magic link delivery failed", err);
934
+ }
935
+ return { response: { ...SENT } };
936
+ }
937
+ };
938
+ }
939
+ // src/workflow/pincode-key.ts
940
+ /** Label of the default wf-state secret, `auth.deriveStateKey(WF_STATE_KEY_LABEL)`. */
941
+ const WF_STATE_KEY_LABEL = "wf-state";
942
+ /**
943
+ * Internal: the key that seals one-time codes held in workflow state (their
944
+ * keyed digests), published on every trigger request by `WfTriggerProvider`.
945
+ */
946
+ const pincodeKeySlot = key("aooth.pincodeKey");
947
+ /**
948
+ * Derive the one-time-code key from a secret — the wf-state secret by default.
949
+ * A separate subkey (HMAC under its own label), never the secret itself, so the
950
+ * code digests and the encapsulated state's AES key never share a key.
951
+ */
952
+ function derivePincodeKey(secret) {
953
+ return createHmac("sha256", secret).update("aooth-pincode").digest();
954
+ }
955
+ /**
956
+ * The one-time-code key of the default wf-state secret — what a default
957
+ * `WfTriggerProvider` publishes, and what `AuthWorkflow.pincodeKey()` uses
958
+ * outside one, so a code minted on either path verifies on the other. Throws
959
+ * `AuthError("INVALID_CONFIG")` when the credential store has no derivable
960
+ * secret (a stateful store): the secret must then be supplied explicitly.
961
+ */
962
+ function defaultPincodeKey(auth) {
963
+ return derivePincodeKey(auth.deriveStateKey(WF_STATE_KEY_LABEL));
964
+ }
696
965
  // src/workflow/public-projection.ts
697
966
  /**
698
967
  * `ctx.public` — the form-facing projection `AuthWorkflow` rebuilds before
@@ -720,6 +989,133 @@ function __decorateMetadata(k, v) {
720
989
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
721
990
  }
722
991
  // src/wf-trigger/provider.ts
992
+ /** Cap of the default (in-memory) magic-link store. */
993
+ const MAGIC_LINK_STORE_MAX_ENTRIES = 1e4;
994
+ /**
995
+ * The default magic-link store: memory, with expired links swept at most once
996
+ * a minute on write, and at most {@link MAGIC_LINK_STORE_MAX_ENTRIES} links —
997
+ * the oldest is dropped first. Links nobody clicks (and requests for unknown
998
+ * identifiers) must not pile up for the life of the process.
999
+ */
1000
+ var BoundedWfStateStoreMemory = class extends WfStateStoreMemory {
1001
+ maxEntries;
1002
+ lastSweep = 0;
1003
+ /** The stored handles, oldest first, with their expiry (the base map is private). */
1004
+ expiries = /* @__PURE__ */ new Map();
1005
+ constructor(maxEntries = MAGIC_LINK_STORE_MAX_ENTRIES) {
1006
+ super();
1007
+ this.maxEntries = maxEntries;
1008
+ }
1009
+ async set(handle, state, expiresAt) {
1010
+ const now = Date.now();
1011
+ if (now - this.lastSweep > 6e4) {
1012
+ this.lastSweep = now;
1013
+ await this.cleanup();
1014
+ for (const [key, expiry] of this.expiries) if (expiry && now > expiry) this.expiries.delete(key);
1015
+ }
1016
+ this.expiries.delete(handle);
1017
+ while (this.expiries.size >= this.maxEntries) {
1018
+ const oldest = this.expiries.keys().next().value;
1019
+ this.expiries.delete(oldest);
1020
+ await super.delete(oldest);
1021
+ }
1022
+ this.expiries.set(handle, expiresAt);
1023
+ return super.set(handle, state, expiresAt);
1024
+ }
1025
+ async delete(handle) {
1026
+ this.expiries.delete(handle);
1027
+ return super.delete(handle);
1028
+ }
1029
+ async getAndDelete(handle) {
1030
+ this.expiries.delete(handle);
1031
+ return super.getAndDelete(handle);
1032
+ }
1033
+ };
1034
+ /** Where aooth records, inside a persisted state, which strategy persisted it. */
1035
+ const STRATEGY_TAG = "aoothStrategy";
1036
+ /**
1037
+ * Where aooth records, inside a persisted state, when it expires (ms; absent =
1038
+ * never, or unknown for a custom strategy).
1039
+ */
1040
+ const STATE_EXPIRES_KEY = "aoothExpiresAt";
1041
+ /** Padding aooth adds to encapsulated states (stripped on read). */
1042
+ const PAD_KEY = "aoothPad";
1043
+ /** Encapsulated payloads are padded to a multiple of this many bytes. */
1044
+ const PAD_BUCKET = 256;
1045
+ /** Strategies new enough that every state they hold carries the tag. */
1046
+ const TAG_REQUIRED = /* @__PURE__ */ new Set([MAGIC_LINK_STRATEGY]);
1047
+ /**
1048
+ * Wrap a registered strategy so a state can only be resumed through the
1049
+ * strategy that persisted it: `persist` tags the state with `name`, and
1050
+ * `retrieve` / `consume` refuse (as "not found") a state tagged by another
1051
+ * strategy — e.g. a magic-link entry presented as a `store.` token when both
1052
+ * share one store. A refused state is checked before it is consumed, so the
1053
+ * attempt does not destroy it. States persisted before tagging existed are
1054
+ * accepted, except by strategies that always tag. Encapsulated states are also
1055
+ * padded to a {@link PAD_BUCKET}-byte multiple, so the token's length does not
1056
+ * follow the length of what is inside. The expiry the strategy applies is
1057
+ * recorded too ({@link STATE_EXPIRES_KEY}), as the strategy reports it through
1058
+ * `expiresAtFor` (the earlier of the persist-time `ttl` / `expiresAt`, else its
1059
+ * own default TTL), so a peek can tell when the token stops working. A strategy
1060
+ * without `expiresAtFor` (a custom one, or a built-in with `persist` overridden)
1061
+ * leaves it unrecorded.
1062
+ */
1063
+ function tagStrategy(name, strategy) {
1064
+ const pad = strategy instanceof EncapsulatedStateStrategy;
1065
+ const accepts = (state) => {
1066
+ if (!state) return false;
1067
+ const tag = state.meta?.[STRATEGY_TAG];
1068
+ return tag === void 0 ? !TAG_REQUIRED.has(name) : tag === name;
1069
+ };
1070
+ const tagged = (state, options) => {
1071
+ const { [PAD_KEY]: _pad, [STATE_EXPIRES_KEY]: _expires, ...meta } = state.meta ?? {};
1072
+ const reported = strategy.expiresAtFor?.(options);
1073
+ const expiresAt = reported !== void 0 && reported > 0 ? reported : void 0;
1074
+ const out = {
1075
+ ...state,
1076
+ meta: {
1077
+ ...meta,
1078
+ [STRATEGY_TAG]: name,
1079
+ ...expiresAt !== void 0 && { ["aoothExpiresAt"]: expiresAt }
1080
+ }
1081
+ };
1082
+ if (!pad) return out;
1083
+ const size = Buffer.byteLength(JSON.stringify(out)) + 32;
1084
+ const fill = (PAD_BUCKET - size % PAD_BUCKET) % PAD_BUCKET;
1085
+ out.meta[PAD_KEY] = "x".repeat(fill);
1086
+ return out;
1087
+ };
1088
+ const clean = (state) => {
1089
+ const { [PAD_KEY]: _pad, ...meta } = state.meta ?? {};
1090
+ return {
1091
+ ...state,
1092
+ meta
1093
+ };
1094
+ };
1095
+ const wrapped = {
1096
+ persist: (state, options, overrides) => strategy.persist(tagged(state, options), options, overrides),
1097
+ retrieve: async (token) => {
1098
+ const state = await strategy.retrieve(token);
1099
+ return accepts(state) ? clean(state) : null;
1100
+ },
1101
+ consume: async (token) => {
1102
+ if (!accepts(await strategy.retrieve(token))) return null;
1103
+ const state = await strategy.consume(token);
1104
+ return accepts(state) ? clean(state) : null;
1105
+ }
1106
+ };
1107
+ Object.defineProperty(wrapped, "inner", { value: strategy });
1108
+ if (strategy.persistEntry) wrapped.persistEntry = (state, options, overrides) => strategy.persistEntry(tagged(state, options), options, overrides);
1109
+ if (strategy.consumeEntry) wrapped.consumeEntry = async (token) => {
1110
+ if (!accepts(await strategy.retrieve(token))) return null;
1111
+ const entry = await strategy.consumeEntry(token);
1112
+ return entry && accepts(entry.state) ? {
1113
+ ...entry,
1114
+ state: clean(entry.state)
1115
+ } : null;
1116
+ };
1117
+ return wrapped;
1118
+ }
723
1119
  const HOOK_NAMES = [
724
1120
  "around",
725
1121
  "beforePersist",
@@ -753,59 +1149,61 @@ const HOOK_NAMES = [
753
1149
  function deriveWfStateSecret(secret) {
754
1150
  return createHash("sha256").update(secret).digest();
755
1151
  }
756
- /** One canonical workflow-id form for allow-list matching: no leading `/`. */
757
- function normalizeWfId(id) {
758
- return id.replace(/^\/+/, "");
759
- }
760
- function notAllowed(id) {
761
- return aoothHttpError(403, "WORKFLOW_NOT_ALLOWED", { workflow: normalizeWfId(id) });
762
- }
763
1152
  /**
764
- * Wrap a strategy so a resume is checked against the allow list BEFORE the
765
- * state is consumed: the state is peeked (`retrieve`), refused with 403 when
766
- * its workflow is not allowed on this route (the token stays usable on its
767
- * own route), and only then consumed. The optional expiry-reporting methods
768
- * (`persistEntry` / `consumeEntry`, which `restoreOnError` needs) are kept
769
- * when the wrapped strategy has them.
1153
+ * The access refusals the wooks trigger raises, in aooth's public form. The
1154
+ * engine decides (`allow` / `resumeOnly` / `block`, judged on the resolved
1155
+ * flow); aooth keeps its own wire contract:
1156
+ *
1157
+ * - `WF_FORBIDDEN` (403) on a start becomes `AOOTH_WORKFLOW_NOT_ALLOWED` (403,
1158
+ * `workflow` param). On a resume the engine never names the stored flow, so
1159
+ * it becomes `AOOTH_WORKFLOW_RESUME_NOT_ALLOWED` (403, no params, a template
1160
+ * without a placeholder).
1161
+ * - `WF_NOT_FOUND` (404) — a start whose id resolves to no flow while access
1162
+ * lists are set — becomes `AOOTH_WORKFLOW_NOT_ALLOWED` (403) whenever `allow`
1163
+ * is set: unregistered ids answer like unlisted ones, so a probe cannot tell
1164
+ * which ids `allow` lists. With only `resumeOnly` / `block` set it stays 404.
1165
+ *
1166
+ * Anything else passes through untouched. The error is recognised by its body
1167
+ * code, not by class, so a second installed copy of `@wooksjs/event-http` does
1168
+ * not let a raw `WF_FORBIDDEN` through.
770
1169
  */
771
- function guardStrategy(strategy, permits) {
772
- const check = async (token) => {
773
- const peeked = await strategy.retrieve(token);
774
- if (peeked && !permits(peeked.schemaId)) throw notAllowed(peeked.schemaId);
775
- };
776
- const guarded = {
777
- persist: (state, options, overrides) => strategy.persist(state, options, overrides),
778
- retrieve: (token) => strategy.retrieve(token),
779
- consume: async (token) => {
780
- await check(token);
781
- return strategy.consume(token);
782
- }
783
- };
784
- if (strategy.persistEntry) guarded.persistEntry = (state, options, overrides) => strategy.persistEntry(state, options, overrides);
785
- if (strategy.consumeEntry) guarded.consumeEntry = async (token) => {
786
- await check(token);
787
- return strategy.consumeEntry(token);
788
- };
789
- return guarded;
1170
+ function mapRefusal(error, allowed) {
1171
+ const body = error?.body;
1172
+ if (!body || typeof body !== "object") return error;
1173
+ const wfid = typeof body.params?.wfid === "string" ? normalizeWfId(body.params.wfid) : void 0;
1174
+ if (body.code === "WF_FORBIDDEN") return wfid === void 0 ? aoothHttpError(403, "AOOTH_WORKFLOW_RESUME_NOT_ALLOWED") : aoothHttpError(403, "AOOTH_WORKFLOW_NOT_ALLOWED", { workflow: wfid });
1175
+ if (body.code === "WF_NOT_FOUND" && allowed && wfid !== void 0) return aoothHttpError(403, "AOOTH_WORKFLOW_NOT_ALLOWED", { workflow: wfid });
1176
+ return error;
790
1177
  }
791
1178
  /**
792
1179
  * Run one trigger attempt. The invite outlet reads the link callback from a
793
1180
  * slot reserved on the HTTP event; it is reserved per run, so a run that
794
- * `around` retries starts clean.
1181
+ * `around` retries starts clean. Access refusals leave in aooth's form
1182
+ * ({@link mapRefusal}).
795
1183
  */
796
- function runTrigger(run) {
1184
+ async function runTrigger(run, allowed) {
797
1185
  reservePendingInviteLink();
798
- return run();
1186
+ try {
1187
+ return await run();
1188
+ } catch (error) {
1189
+ throw mapRefusal(error, allowed);
1190
+ }
799
1191
  }
800
1192
  let WfTriggerProvider = class WfTriggerProvider {
801
1193
  wf;
802
1194
  auth;
803
1195
  /**
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()];
1196
+ * Outlets the trigger can pause on: HTTP (forms), `invite` (the link of
1197
+ * `AuthWorkflowOpts.inviteDelivery: 'deliver' | 'return-link'`) and
1198
+ * `magic-link` (recovery and sign-in links — it sends through the `email`
1199
+ * outlet). Append an `email` outlet (`createAuthEmailOutlet`) for the default
1200
+ * invite delivery and for magic links.
1201
+ */
1202
+ outlets = [
1203
+ createAsHttpOutlet(),
1204
+ createInviteOutlet(),
1205
+ createMagicLinkOutlet(() => this.outlets.find((o) => o.name === "email"))
1206
+ ];
809
1207
  token = {
810
1208
  read: [
811
1209
  "body",
@@ -829,7 +1227,27 @@ let WfTriggerProvider = class WfTriggerProvider {
829
1227
  * `return deriveWfStateSecret(env.MY_SECRET)`.
830
1228
  */
831
1229
  wfStateSecret() {
832
- return this.auth.deriveStateKey("wf-state");
1230
+ return this.auth.deriveStateKey(WF_STATE_KEY_LABEL);
1231
+ }
1232
+ /**
1233
+ * Secret that keys the digests of one-time codes (recovery, sign-in, signup
1234
+ * and enrolment codes) held in workflow state — the state keeps a keyed
1235
+ * digest of each code, never the code. Default: the wf-state secret, so a
1236
+ * store-backed setup that overrides `wfStateSecret()` needs nothing more.
1237
+ * All instances must agree on it.
1238
+ */
1239
+ pincodeSecret() {
1240
+ return this.wfStateSecret();
1241
+ }
1242
+ cachedPincodeKey;
1243
+ /**
1244
+ * The key of the one-time-code digests this provider publishes on every
1245
+ * request: {@link derivePincodeKey} of {@link pincodeSecret}. With the
1246
+ * default secrets it equals what `AuthWorkflow.pincodeKey()` derives outside
1247
+ * a provider (`defaultPincodeKey`).
1248
+ */
1249
+ pincodeKey() {
1250
+ return this.cachedPincodeKey ??= derivePincodeKey(this.pincodeSecret());
833
1251
  }
834
1252
  /** 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
1253
  wfStateEncapsulatedTtlMs() {}
@@ -837,6 +1255,18 @@ let WfTriggerProvider = class WfTriggerProvider {
837
1255
  storeStrategy() {
838
1256
  return this.makeEncapsulated();
839
1257
  }
1258
+ /**
1259
+ * Store of the magic-link pauses (recovery and sign-in links). Default: one
1260
+ * in-memory store per provider — single process only. With several
1261
+ * instances, return a shared `WfStateStore` (e.g. the `AsWfStore` of your
1262
+ * wf-state table). The strategy around it is fixed: handles are stored
1263
+ * hashed (a read of the store yields no usable link), each link is consumed
1264
+ * by its first use, and it expires with the link (`magicLinkTtlMs`).
1265
+ */
1266
+ magicLinkStore() {
1267
+ return this.defaultMagicLinkStore ??= new BoundedWfStateStoreMemory();
1268
+ }
1269
+ defaultMagicLinkStore;
840
1270
  makeEncapsulated() {
841
1271
  return new EncapsulatedStateStrategy({
842
1272
  secret: this.wfStateSecret(),
@@ -859,50 +1289,59 @@ let WfTriggerProvider = class WfTriggerProvider {
859
1289
  return {};
860
1290
  }
861
1291
  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. */
1292
+ /** 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
1293
  stateRegistry() {
864
1294
  if (!this.cachedState) this.cachedState = {
865
1295
  strategies: {
866
- encapsulated: this.makeEncapsulated(),
867
- store: this.storeStrategy()
1296
+ encapsulated: tagStrategy("encapsulated", this.makeEncapsulated()),
1297
+ store: tagStrategy("store", this.storeStrategy()),
1298
+ [MAGIC_LINK_STRATEGY]: tagStrategy(MAGIC_LINK_STRATEGY, new HandleStateStrategy({
1299
+ store: this.magicLinkStore(),
1300
+ hashHandles: true
1301
+ }))
868
1302
  },
869
1303
  default: "encapsulated"
870
1304
  };
871
1305
  return this.cachedState;
872
1306
  }
873
1307
  /**
874
- * Handle one trigger request. `allow` lists the workflow ids this route may
875
- * START and RESUME (matched without a leading `/`); omitted = unrestricted,
876
- * `[]` = deny all. A state token minted for a workflow outside the list is
877
- * refused with 403 before it is consumed. Trigger hooks set in `opts`
878
- * replace the {@link triggerHooks} of the same name.
1308
+ * Read the paused workflow state a resume token (`wfs`) points at, WITHOUT
1309
+ * consuming it — e.g. to show what a link is for before its holder acts.
1310
+ * The token is resolved exactly as a resume resolves it (its strategy
1311
+ * prefix, the strategy's handle hashing and legacy-key rules, the strategy
1312
+ * tag), so a peek finds what a resume would. An unknown, expired, malformed
1313
+ * or foreign token is `null` — one answer for all. The state carries
1314
+ * server-only context: project what you need, never send it as-is.
1315
+ */
1316
+ async peek(token) {
1317
+ const i = token.indexOf(".");
1318
+ if (i <= 0 || i === token.length - 1) return null;
1319
+ const strategies = this.stateRegistry().strategies;
1320
+ const name = token.slice(0, i);
1321
+ if (!Object.hasOwn(strategies, name)) return null;
1322
+ return strategies[name].retrieve(token.slice(i + 1));
1323
+ }
1324
+ /**
1325
+ * Handle one trigger request. `opts` is {@link WfTriggerOpts}: the access
1326
+ * lists are judged by the wooks trigger before a state token is consumed, and
1327
+ * hooks set in `opts` replace the {@link triggerHooks} of the same name.
879
1328
  */
880
1329
  async handle(opts = {}) {
881
1330
  const wfApp = this.wf.getWfApp();
882
- const allowed = opts.allow && new Set(opts.allow.map(normalizeWfId));
883
- const permits = (schemaId) => !allowed || allowed.has(normalizeWfId(schemaId));
884
- const registry = this.stateRegistry();
885
- const stateConfig = allowed ? {
886
- default: registry.default,
887
- strategies: Object.fromEntries(Object.entries(registry.strategies).map(([name, strategy]) => [name, guardStrategy(strategy, permits)]))
888
- } : registry;
1331
+ current().set(pincodeKeySlot, this.pincodeKey());
889
1332
  const deps = {
890
- start: (schemaId, context, o) => {
891
- if (!permits(schemaId)) throw notAllowed(schemaId);
892
- return wfApp.start(schemaId, context, {
893
- input: o?.input,
894
- eventContext: o?.eventContext ?? current(),
895
- strategy: o?.strategy
896
- });
897
- },
898
- resume: (state, o) => {
899
- if (!permits(state.schemaId)) throw notAllowed(state.schemaId);
900
- return wfApp.resume(state, {
901
- input: o?.input,
902
- eventContext: o?.eventContext ?? current(),
903
- strategy: o?.strategy
904
- });
905
- }
1333
+ start: (schemaId, context, o) => wfApp.start(schemaId, context, {
1334
+ input: o?.input,
1335
+ eventContext: o?.eventContext ?? current(),
1336
+ strategy: o?.strategy,
1337
+ expectSchemaId: o?.expectSchemaId
1338
+ }),
1339
+ resume: (state, o) => wfApp.resume(state, {
1340
+ input: o?.input,
1341
+ eventContext: o?.eventContext ?? current(),
1342
+ strategy: o?.strategy
1343
+ }),
1344
+ resolveSchemaId: (id, o) => this.wf.resolveSchemaId(id, o)
906
1345
  };
907
1346
  const base = this.triggerHooks();
908
1347
  const hooks = {};
@@ -916,10 +1355,15 @@ let WfTriggerProvider = class WfTriggerProvider {
916
1355
  return beforePersist?.(state, pause);
917
1356
  };
918
1357
  const around = opts.around ?? base.around;
1358
+ const { allow, resumeOnly, block } = opts;
1359
+ const attempt = (run) => runTrigger(run, allow !== void 0);
919
1360
  return handleAsOutletRequest({
920
1361
  ...hooks,
921
- around: around ? (run) => around(() => runTrigger(run)) : runTrigger,
922
- state: stateConfig,
1362
+ allow,
1363
+ resumeOnly,
1364
+ block,
1365
+ around: around ? (run) => around(() => attempt(run)) : attempt,
1366
+ state: this.stateRegistry(),
923
1367
  outlets: this.outlets,
924
1368
  token: opts.token ?? this.token
925
1369
  }, deps);
@@ -928,6 +1372,18 @@ let WfTriggerProvider = class WfTriggerProvider {
928
1372
  WfTriggerProvider = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [typeof MoostWf === "undefined" ? Object : MoostWf, typeof AuthCredential === "undefined" ? Object : AuthCredential])], WfTriggerProvider);
929
1373
  // src/wf-trigger/decorator.ts
930
1374
  /**
1375
+ * The ONE trigger interceptor every `@WfTrigger` attaches. moost dedupes
1376
+ * interceptors by handler reference, so a subclass override decorated again
1377
+ * keeps a single trigger; the options ride on the method's metadata, where
1378
+ * the override's own value replaces the inherited one.
1379
+ */
1380
+ const wfTriggerInterceptor = defineAfterInterceptor(async (response, reply) => {
1381
+ if (await response !== void 0) return;
1382
+ const cc = useControllerContext();
1383
+ const opts = cc.getMethodMeta()?.wfTrigger ?? {};
1384
+ reply(await (await cc.instantiate(WfTriggerProvider)).handle(opts));
1385
+ }, TInterceptorPriority.INTERCEPTOR);
1386
+ /**
931
1387
  * Method decorator that turns a handler into a workflow trigger.
932
1388
  *
933
1389
  * The handler may have an empty body — the interceptor's after-phase invokes
@@ -935,19 +1391,33 @@ WfTriggerProvider = __decorate([Injectable(), __decorateMetadata("design:paramty
935
1391
  * that need to short-circuit (e.g. emit a custom error response) just return a
936
1392
  * non-undefined value from the overridden handler and the trigger is skipped.
937
1393
  *
938
- * `opts` also takes the workflow-trigger hooks (`around`, `beforePersist`,
1394
+ * `opts` is `WfTriggerOpts`: the access lists `allow` / `resumeOnly` /
1395
+ * `block` and the workflow-trigger hooks (`around`, `beforePersist`,
939
1396
  * `renderEnvelope`, `restoreOnError`, `maxRestores` — see `WfTriggerHooks`);
940
- * each one set here replaces the provider's `triggerHooks()` hook of the
1397
+ * each hook set here replaces the provider's `triggerHooks()` hook of the
941
1398
  * same name for this route.
942
1399
  *
1400
+ * Under `@Inherit()`, re-decorating an overridden handler REPLACES the base
1401
+ * route's options as a whole (e.g. a narrower `allow` is the only list
1402
+ * checked) — the trigger still runs once per request. An override without
1403
+ * its own `@WfTrigger` keeps the base options.
1404
+ *
943
1405
  * The single `useControllerContext().instantiate(...)` call is the one
944
1406
  * documented escape hatch: interceptors are functions, not classes, so there's
945
1407
  * no ctor to inject into. Every class still uses constructor injection.
946
1408
  */
947
- const WfTrigger = (opts = {}) => Intercept(defineAfterInterceptor(async (response, reply) => {
948
- if (await response !== void 0) return;
949
- reply(await (await useControllerContext().instantiate(WfTriggerProvider)).handle(opts));
950
- }, TInterceptorPriority.INTERCEPTOR));
1409
+ const WfTrigger = (opts = {}) => {
1410
+ const intercept = Intercept(wfTriggerInterceptor);
1411
+ return (target, key, descriptor) => {
1412
+ let first = false;
1413
+ getMoostMate().decorate((meta) => {
1414
+ first = meta.wfTrigger === void 0;
1415
+ meta.wfTrigger = opts;
1416
+ return meta;
1417
+ })(target, key, descriptor);
1418
+ if (first) intercept(target, key, descriptor);
1419
+ };
1420
+ };
951
1421
  /**
952
1422
  * Build the leg-1 federated-login authorization request — STATELESS, no flow
953
1423
  * store. Mints a fresh non-secret `seed`, DERIVES the PKCE verifier + OIDC nonce
@@ -1200,34 +1670,34 @@ OAuthRuntime = __decorate([Injectable(), __decorateMetadata("design:paramtypes",
1200
1670
  */
1201
1671
  const AOOTH_MESSAGES = {
1202
1672
  INVALID_CREDENTIALS: "Invalid credentials",
1203
- ACCOUNT_LOCKED: "Account locked, please try again later",
1673
+ AOOTH_ACCOUNT_LOCKED: "Account locked, please try again later",
1204
1674
  INVALID_PASSWORD: "Invalid password",
1205
1675
  INCORRECT_PASSWORD: "Incorrect password",
1206
1676
  SESSION_LIMIT_REACHED: "Session limit reached",
1207
1677
  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.",
1678
+ AOOTH_INVALID_CODE: "Invalid code",
1679
+ AOOTH_CODE_EXPIRED: "Code expired",
1680
+ AOOTH_TOO_MANY_CODE_ATTEMPTS: "Too many invalid attempts. Please request a new code.",
1211
1681
  /** Params: `seconds`. */
1212
- RESEND_WAIT: "Please wait {seconds}s before requesting a new code.",
1682
+ AOOTH_RESEND_WAIT: "Please wait {seconds}s before requesting a new code.",
1213
1683
  /** Params: `seconds`. */
1214
- RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code",
1684
+ AOOTH_RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code",
1215
1685
  /** Params: `seconds`, `channel` (`SMS` / `email`). */
1216
- RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code",
1686
+ AOOTH_RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code",
1217
1687
  TOTP_RESEND_NOT_APPLICABLE: "Resend is not applicable for TOTP",
1218
1688
  /** HTTP 400 — a TOTP code submitted for an account without TOTP. */
1219
1689
  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",
1690
+ AOOTH_ADDRESS_REQUIRED: "This field is required",
1691
+ AOOTH_INVALID_EMAIL_ADDRESS: "Enter a valid email address",
1692
+ AOOTH_INVALID_PHONE_NUMBER: "Enter a valid phone number",
1223
1693
  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
1694
  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
1695
  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.",
1696
+ AOOTH_UNKNOWN_METHOD: "Unknown method",
1697
+ AOOTH_METHOD_UNAVAILABLE: "That method isn't available",
1698
+ AOOTH_METHOD_NOT_CHANGEABLE: "That method can't be changed here.",
1229
1699
  KEEP_ONE_MFA_METHOD: "You must keep at least one two-factor method.",
1230
- CHOOSE_OPTION: "Choose an option",
1700
+ AOOTH_CHOOSE_OPTION: "Choose an option",
1231
1701
  ALL_MFA_METHODS_SET_UP: "You've already set up every available authentication method.",
1232
1702
  NO_MFA_CHANGES: "No changes were made to your two-factor methods.",
1233
1703
  LAST_MFA_METHOD_NOT_REMOVABLE: "You must keep at least one two-factor method, so this one can't be removed.",
@@ -1255,16 +1725,17 @@ const AOOTH_MESSAGES = {
1255
1725
  SET_PASSWORD_INVITE_INTRO: "Choose a password to activate your account.",
1256
1726
  SET_PASSWORD_INITIAL_HEADING: "Set your initial password",
1257
1727
  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.",
1728
+ /** A magic link that cannot be used: expired, of another purpose, or already used up. */
1729
+ AOOTH_MAGIC_LINK_INVALID: "This link is invalid or has expired. Please request a new one.",
1259
1730
  SIGNUP_DISABLED: "Self-signup is currently disabled.",
1260
- ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.",
1261
- ACCOUNT_LINKED: "Account linked.",
1731
+ AOOTH_ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.",
1732
+ AOOTH_ACCOUNT_LINKED: "Account linked.",
1262
1733
  /** HTTP 400 — the SSO alt action named a provider that is not offered. */
1263
1734
  UNKNOWN_SSO_PROVIDER: "Unknown SSO provider",
1264
- ACCOUNT_CREATED: "Your account has been created.",
1265
- INVALID_ROLE: "Invalid role",
1735
+ AOOTH_ACCOUNT_CREATED: "Your account has been created.",
1736
+ AOOTH_INVALID_ROLE: "Invalid role",
1266
1737
  INVITE_ALREADY_PENDING: "Invite already pending",
1267
- USER_ALREADY_EXISTS: "User already exists",
1738
+ AOOTH_USER_ALREADY_EXISTS: "User already exists",
1268
1739
  DUPLICATE_INVITE_REJECTED: "Duplicate invite rejected",
1269
1740
  INVITE_CANCELLED: "This invite has been cancelled",
1270
1741
  INVITE_REPLACED: "This invite was replaced by a newer one",
@@ -1277,8 +1748,8 @@ const AOOTH_MESSAGES = {
1277
1748
  GO_TO_SIGN_IN: "Go to sign-in",
1278
1749
  BACK_TO_SIGN_IN: "Back to sign-in",
1279
1750
  REQUEST_NEW_INVITE: "Request a new invite",
1280
- BACK: "Back",
1281
- GO_NOW: "Go now"
1751
+ AOOTH_BACK: "Back",
1752
+ AOOTH_GO_NOW: "Go now"
1282
1753
  };
1283
1754
  registerMessages(AOOTH_MESSAGES);
1284
1755
  /** Fill `{name}` placeholders from `params`; unknown placeholders are kept. */
@@ -1339,19 +1810,20 @@ function userAuthErrorField(type) {
1339
1810
  }
1340
1811
  /**
1341
1812
  * 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):
1813
+ * carries `code` (the error's message code, `err.code`), the message and — for
1814
+ * password errors — the form `field` it belongs to (named as in the bundled
1815
+ * password forms):
1344
1816
  *
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 | |
1817
+ * | type | code | status | field |
1818
+ * |---|---|---|---|
1819
+ * | `NOT_FOUND` | `NOT_FOUND` | 404 | |
1820
+ * | `ALREADY_EXISTS`, `CAS_EXHAUSTED` | `AOOTH_USER_ALREADY_EXISTS`, `AOOTH_USER_CAS_EXHAUSTED` | 409 | |
1821
+ * | `INVALID_CREDENTIALS` | `INVALID_CREDENTIALS` | 400 | `currentPassword` |
1822
+ * | `PASSWORD_IN_HISTORY` | `PASSWORD_IN_HISTORY` | 400 | `newPassword` |
1823
+ * | `POLICY_VIOLATION` (+ `params.policies`) | `AOOTH_USER_POLICY_VIOLATION` | 422 | `newPassword` |
1824
+ * | `PASSWORDS_MISMATCH` | `PASSWORDS_MISMATCH` | 400 | `confirmPassword` |
1825
+ * | `MFA_INVALID`, `MFA_NOT_CONFIGURED` | same as type | 400 | |
1826
+ * | `INACTIVE`, `LOCKED`, `MFA_REQUIRED` | `AOOTH_USER_INACTIVE`, `AOOTH_USER_LOCKED`, `MFA_REQUIRED` | 403 | |
1355
1827
  *
1356
1828
  * For routes such as an admin "set password" endpoint. Do not use it on a
1357
1829
  * sign-in endpoint: distinct answers for unknown, inactive and locked accounts
@@ -1363,7 +1835,7 @@ function userAuthErrorToHttp(err) {
1363
1835
  const policies = err.type === "POLICY_VIOLATION" ? err.details?.policies : void 0;
1364
1836
  return new HttpError(STATUS[err.type], {
1365
1837
  message: userAuthErrorText(err),
1366
- code: err.type,
1838
+ code: err.code,
1367
1839
  ...policies !== void 0 && { params: { policies } },
1368
1840
  ...field && { field }
1369
1841
  });
@@ -1388,8 +1860,8 @@ function translatePolicyError({ code, params, errorMessage }) {
1388
1860
  * A `UserAuthError`'s text in the request's locale: a `POLICY_VIOLATION` lists
1389
1861
  * its failed policies' translated `errorMessage`s (`; `-joined, like the
1390
1862
  * 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.
1863
+ * and for any other type — the error is translated by its code (`err.code`),
1864
+ * its own message the fallback.
1393
1865
  */
1394
1866
  function userAuthErrorText(err) {
1395
1867
  const policies = err.type === "POLICY_VIOLATION" ? err.details?.policies : void 0;
@@ -1398,7 +1870,7 @@ function userAuthErrorText(err) {
1398
1870
  const texts = failed.map((p) => translatePolicyError(p));
1399
1871
  if (texts.some((text, i) => text !== failed[i].errorMessage)) return texts.join("; ");
1400
1872
  }
1401
- return translateCode(err.type, void 0, err.message);
1873
+ return translateCode(err.code, void 0, err.message);
1402
1874
  }
1403
1875
  /**
1404
1876
  * Error interceptor answering every `UserAuthError` a handler throws with
@@ -1432,7 +1904,7 @@ const userAuthErrorInterceptor = defineErrorInterceptor((error, reply) => {
1432
1904
  */
1433
1905
  const pincodeSendCheckPair = [{
1434
1906
  id: "pincode-send",
1435
- condition: (ctx) => !ctx.pin
1907
+ condition: (ctx) => !ctx.pinNonce
1436
1908
  }, {
1437
1909
  id: "pincode-check",
1438
1910
  condition: (ctx) => !ctx.aborted
@@ -1468,7 +1940,7 @@ const enrollTrioSteps = [
1468
1940
  },
1469
1941
  {
1470
1942
  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
1943
+ condition: (ctx) => (ctx.mfaEnroll?.method === "sms" || ctx.mfaEnroll?.method === "email") && !!ctx.mfaEnroll.address && !ctx.mfaEnroll.done && !ctx.mfaEnroll.preConfirmed && !ctx.pinNonce
1472
1944
  },
1473
1945
  {
1474
1946
  id: "enroll-confirm",
@@ -1522,7 +1994,7 @@ const mfaStepUpLoop = [{
1522
1994
  },
1523
1995
  {
1524
1996
  id: "manage-stepup-confirm",
1525
- condition: (ctx) => !ctx.otp?.verified && (ctx.mfa?.method === "sms" || ctx.mfa?.method === "email") && !ctx.addMfa?.stepUpConfirmed && !ctx.pin
1997
+ condition: (ctx) => !ctx.otp?.verified && (ctx.mfa?.method === "sms" || ctx.mfa?.method === "email") && !ctx.addMfa?.stepUpConfirmed && !ctx.pinNonce
1526
1998
  },
1527
1999
  { break: (ctx) => !!ctx.aborted },
1528
2000
  {
@@ -1654,6 +2126,9 @@ const DEFAULT_FORMS = {
1654
2126
  termsBump: TermsBumpForm,
1655
2127
  concurrencyLimit: ConcurrencyLimitForm,
1656
2128
  recoveryPincode: PincodeForm,
2129
+ recoveryModeSelect: RecoveryModeSelectForm,
2130
+ magicLinkRequest: MagicLinkRequestForm,
2131
+ magicLinkConfirm: MagicLinkConfirmForm,
1657
2132
  signup: SignupForm,
1658
2133
  authzConsent: AuthorizeConsentForm
1659
2134
  };
@@ -1665,19 +2140,56 @@ const warnedOnce = {
1665
2140
  openInviteWhitelist: false,
1666
2141
  crossIssuerReuse: false
1667
2142
  };
2143
+ /** What `pincode-check` compares a recovery code against when there is no account: matches no code. */
2144
+ const NO_CODE = "\0";
2145
+ /** Default name of the cookie that binds a sign-in link to its browser (opt-in). */
2146
+ const MAGIC_LINK_BROWSER_COOKIE = "aooth_magic_link";
2147
+ /** The id an unknown identifier's recovery reads, so its lookups match a known one's. */
2148
+ const UNKNOWN_ACCOUNT_ID = "00000000-0000-4000-8000-000000000000";
2149
+ /** Key prefixes of a code's attempt counter and single-use marker (in `lockoutShadowStore`). */
2150
+ const PIN_ATTEMPT_PREFIX = "code-attempts:";
2151
+ const PIN_SPENT_PREFIX = "code-spent:";
2152
+ /** Key prefixes of a code destination's resend cooldown and failed-code budget. */
2153
+ const CODE_SEND_PREFIX = "code-send:";
2154
+ const CODE_FAIL_PREFIX = "code-fail:";
2155
+ /** Key prefix of a magic link's resend cooldown. */
2156
+ const MAGIC_LINK_SEND_PREFIX = "magic-link:";
2157
+ /** SHA-256 of `value`, base64url — fixed-size store keys and binding hashes. */
2158
+ function sha256url(value) {
2159
+ return createHash("sha256").update(value).digest("base64url");
2160
+ }
2161
+ /** How long a code's counters outlive the code. */
2162
+ const PIN_COUNTER_GRACE_MS = 6e4;
1668
2163
  /** Sliding lifetime of a shadow failure counter (and of a shadow "permanent" lock). */
1669
2164
  const SHADOW_TTL_MS = 2592e6;
1670
2165
  /** Key prefix of an active shadow lock (kept longest by the default store). */
1671
2166
  const SHADOW_LOCK_PREFIX = "shadow-lock:";
1672
2167
  /** Cap of the default (process-wide, in-memory) shadow-lockout store. */
1673
2168
  const SHADOW_STORE_MAX_ENTRIES = 5e4;
2169
+ /**
2170
+ * Keys a flood of fresh failure counters must not push out of the default
2171
+ * store: ACTIVE shadow locks (evicting one would unmask exactly the handles an
2172
+ * attacker is probing), and the code and magic-link counters (evicting one
2173
+ * would restore a code's attempt budget, or lift a resend wait).
2174
+ */
2175
+ const EVICT_LAST_PREFIXES = [
2176
+ SHADOW_LOCK_PREFIX,
2177
+ PIN_ATTEMPT_PREFIX,
2178
+ PIN_SPENT_PREFIX,
2179
+ CODE_SEND_PREFIX,
2180
+ CODE_FAIL_PREFIX,
2181
+ MAGIC_LINK_SEND_PREFIX
2182
+ ];
2183
+ /** Internal: a memory `lockoutShadowStore` as the default one is built (bounded, protected keys evicted last). */
2184
+ function createShadowStore(maxEntries = SHADOW_STORE_MAX_ENTRIES) {
2185
+ return new RateLimitStoreMemory$1({
2186
+ maxEntries,
2187
+ evictLast: (key) => EVICT_LAST_PREFIXES.some((prefix) => key.startsWith(prefix))
2188
+ });
2189
+ }
1674
2190
  let sharedShadowStore;
1675
2191
  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;
2192
+ return sharedShadowStore ??= createShadowStore();
1681
2193
  }
1682
2194
  function mergeAuthWorkflowOpts(opts) {
1683
2195
  const deviceTrust = {
@@ -1701,9 +2213,14 @@ function mergeAuthWorkflowOpts(opts) {
1701
2213
  pincodeLength: opts.mfa?.pincodeLength ?? 6,
1702
2214
  pincodeTtlMs: opts.mfa?.pincodeTtlMs ?? 3e5,
1703
2215
  pincodeResendTimeoutMs: opts.mfa?.pincodeResendTimeoutMs ?? 6e4,
1704
- pincodeMaxAttempts: opts.mfa?.pincodeMaxAttempts ?? 5
2216
+ pincodeMaxAttempts: opts.mfa?.pincodeMaxAttempts ?? 5,
2217
+ pincodeMaxFailures: opts.mfa?.pincodeMaxFailures ?? 10,
2218
+ pincodeFailureWindowMs: opts.mfa?.pincodeFailureWindowMs ?? 36e5,
2219
+ pincodeMaxFailuresGlobal: opts.mfa?.pincodeMaxFailuresGlobal ?? 100,
2220
+ pincodeMaxSendsGlobal: opts.mfa?.pincodeMaxSendsGlobal ?? 10
1705
2221
  },
1706
2222
  recoveryStateTtlMs: opts.recoveryStateTtlMs ?? 36e5,
2223
+ magicLinkTtlMs: opts.magicLinkTtlMs ?? 9e5,
1707
2224
  loginUrl: opts.loginUrl ?? "/login",
1708
2225
  totpIssuer: opts.totpIssuer ?? "aooth",
1709
2226
  deviceTrust,
@@ -1912,8 +2429,8 @@ function pickDefined(src, keys) {
1912
2429
  * Thrown by `recoveryPincodeTarget`'s registered (M2) branch when the confirmed
1913
2430
  * recovery method that `request`'s guard saw has VANISHED before send time
1914
2431
  * (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
2432
+ * catches it and degrades to the ghost OTP run instead of surfacing a
2433
+ * distinguishable 500, so a known account can never become
1917
2434
  * distinguishable from an unknown one on a resend. Recovery-only; the MFA
1918
2435
  * challenge branch keeps its own `HttpError(500)` (that path is post-password,
1919
2436
  * so enumeration is moot there).
@@ -2252,6 +2769,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2252
2769
  });
2253
2770
  }
2254
2771
  /**
2772
+ * How recovery proves the inbox: `'otp'` (default — a one-time code),
2773
+ * `'magicLink'` (a single-use link, sent through the email outlet as
2774
+ * `recovery.magicLink`) or `'choice'` (the user picks on
2775
+ * `RecoveryModeSelectForm` after the identifier). Reached from recovery.flow.
2776
+ */
2777
+ resolveRecoveryDeliveryMode(_ctx) {
2778
+ return "otp";
2779
+ }
2780
+ /**
2255
2781
  * Resolve the alternate-credentials policy (forgot-password / signup /
2256
2782
  * magic-link / SSO providers). Reached from login.flow.
2257
2783
  */
@@ -2260,11 +2786,9 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2260
2786
  forgotPassword: true,
2261
2787
  signup: false,
2262
2788
  magicLink: false,
2263
- magicLinkSkipsMfa: false,
2264
2789
  ssoProviders: [],
2265
2790
  recoveryUrl: "/recover",
2266
- signupUrl: "/signup",
2267
- embedRecovery: false
2791
+ signupUrl: "/signup"
2268
2792
  };
2269
2793
  }
2270
2794
  /**
@@ -2556,7 +3080,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2556
3080
  * `freshLoginRequired` field is GONE — the auto-login choice is the static
2557
3081
  * `AuthWorkflowOpts.autoLoginOnInvite` boolean (per §2 decision). Return
2558
3082
  * `confirmationMessage` to replace the default confirmation text
2559
- * (`ACCOUNT_CREATED`, rendered in the finishing request's language) with your
3083
+ * (`AOOTH_ACCOUNT_CREATED`, rendered in the finishing request's language) with your
2560
3084
  * own, shown as is.
2561
3085
  */
2562
3086
  resolveAccept(_ctx) {
@@ -2622,6 +3146,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2622
3146
  * set) or from `ctx.email` (recovery path). Loads the user to read the raw
2623
3147
  * method `value` — the `ctx.mfa.enrolledMethods` summary carries only the
2624
3148
  * MASKED form, which is for display, never for delivery.
3149
+ *
3150
+ * In recovery it also runs for an identifier with no account a code can go
3151
+ * to (unknown, inactive), on a copy of `ctx` whose `subject` is the
3152
+ * placeholder `00000000-0000-4000-8000-000000000000` — so every identifier
3153
+ * makes the same calls. Its result (or any error) is discarded there.
2625
3154
  */
2626
3155
  resolvePincodeTarget(ctx) {
2627
3156
  if (ctx.mfa?.method && ctx.mfa.method !== "totp") {
@@ -2653,11 +3182,9 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2653
3182
  * row (`selectRecoveryRegisteredMethod`) and the channel is that method's own
2654
3183
  * kind. The user only typed an account identifier; the destination is a
2655
3184
  * 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.
3185
+ * cross-account. With no deliverable method this throws
3186
+ * `RecoveryMethodUnavailableError`, which recovery treats as "no account"
3187
+ * (nothing sent, every code refused) — never a distinguishable 500.
2661
3188
  */
2662
3189
  recoveryPincodeTarget(ctx, source) {
2663
3190
  if (source === "registered") {
@@ -2682,6 +3209,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2682
3209
  channel
2683
3210
  };
2684
3211
  }
3212
+ /** `resolveRecoveryDeliverySource`, awaited. */
3213
+ async recoveryDeliverySource(ctx) {
3214
+ const source = this.resolveRecoveryDeliverySource(ctx);
3215
+ return source instanceof Promise ? await source : source;
3216
+ }
2685
3217
  /**
2686
3218
  * Recovery OTP delivery channel. The address is ALWAYS the typed recovery
2687
3219
  * identifier (`ctx.email`) — symmetric with how email recovery already works:
@@ -2706,7 +3238,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2706
3238
  * row** — `selectRecoveryRegisteredMethod` picks the confirmed MFA method;
2707
3239
  * the destination is never taken from user input, so it cannot be redirected
2708
3240
  * to an attacker-controlled address. A row with no deliverable confirmed
2709
- * method finishes with the generic anti-enumeration envelope (see `request`).
3241
+ * method runs the ghost OTP pause, like an unknown identifier (see `request`).
2710
3242
  *
2711
3243
  * Consulted inline by `request` (no-method guard) and `recoveryPincodeTarget`
2712
3244
  * — no `prepare-*` step, mirroring `resolveRecoveryChannel`. Override to arm
@@ -2720,7 +3252,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2720
3252
  * its OTP to. Prefers a confirmed SMS method, then a confirmed email method —
2721
3253
  * phone-recovery-first. TOTP carries no deliverable address and is skipped.
2722
3254
  * 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
3255
+ * turns that into the ghost OTP run (anti-enumeration). Stays sync (operates on
2724
3256
  * an already-loaded row); override to change the selection policy (e.g. honour
2725
3257
  * the user's `mfa.defaultMethod`).
2726
3258
  */
@@ -2879,6 +3411,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2879
3411
  if (sub) pub.proveControl = sub;
2880
3412
  }
2881
3413
  if (ctx.newPasswordRequired !== void 0) pub.newPasswordRequired = ctx.newPasswordRequired;
3414
+ if (ctx.magicLink?.sentAt && ctx.magicLink.address && !ctx.magicLink.confirmed) pub.magicLink = { account: this.maskAddress(ctx.magicLink.address, "email") };
2882
3415
  if (ctx.authz) {
2883
3416
  const sub = pickDefined(ctx.authz, [
2884
3417
  "clientName",
@@ -2923,40 +3456,170 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2923
3456
  throw err;
2924
3457
  }
2925
3458
  }
2926
- /** Mint a numeric pincode + stash it onto ctx. Returns the plain code. */
2927
- mintPin(ctx, length, ttlMs) {
3459
+ /**
3460
+ * Mint a numeric one-time code for `binding` (who it is sent for) and return
3461
+ * the plain code for delivery. The state keeps only a random nonce and a
3462
+ * keyed digest of `nonce|binding|code` — fixed lengths, never the code — so
3463
+ * a read of the state does not reveal it, and {@link verifyPin} accepts it
3464
+ * only for the same binding. `length` and `ttlMs` default to
3465
+ * `mfa.pincodeLength` / `mfa.pincodeTtlMs`.
3466
+ */
3467
+ mintPin(ctx, binding, length = this.opts.mfa.pincodeLength, ttlMs = this.opts.mfa.pincodeTtlMs) {
2928
3468
  const code = generateMfaCode(length);
2929
- ctx.pin = code;
3469
+ ctx.pinNonce = randomBytes(16).toString("base64url");
3470
+ ctx.pinDigest = this.pinDigest(ctx.pinNonce, binding, code);
2930
3471
  ctx.pinExpire = Date.now() + ttlMs;
2931
- delete ctx.pinAttempts;
2932
3472
  return code;
2933
3473
  }
3474
+ /** Drop the code in flight (its nonce stays spent or counted server-side). */
3475
+ clearPin(ctx) {
3476
+ delete ctx.pinNonce;
3477
+ delete ctx.pinDigest;
3478
+ delete ctx.pinExpire;
3479
+ }
3480
+ /** Binding of a code sent to `address` in this run (and for its subject, once known). */
3481
+ pinFor(ctx, address) {
3482
+ return `${ctx.subject ?? ""}|${address}`;
3483
+ }
2934
3484
  /**
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;
3485
+ * Binding of a recovery code: the account and the address it went to (a
3486
+ * changed registered channel refuses the old channel's code). Without an
3487
+ * account, the placeholder — the digest has the same length either way.
3488
+ */
3489
+ recoveryBinding(account) {
3490
+ return account ? `${account.subject}|${account.address}` : `${UNKNOWN_ACCOUNT_ID}|`;
3491
+ }
3492
+ /**
3493
+ * Server-side key of where a code goes — its resend cooldown and failed-code
3494
+ * budget. Never an account id the caller could not know: recovery and signup
3495
+ * key on the typed identifier, so known and unknown ones behave alike.
3496
+ */
3497
+ codeTarget(...parts) {
3498
+ return sha256url(parts.map((p) => (p ?? "").trim().toLowerCase()).join("|"));
3499
+ }
3500
+ /** {@link codeTarget} of a code sent to `address` to enrol or verify a channel. */
3501
+ enrollTarget(ctx, address) {
3502
+ return this.codeTarget("enroll", ctx.subject, address);
3503
+ }
3504
+ /** {@link codeTarget} of a federated link's proof-of-control code. */
3505
+ linkTarget(pending) {
3506
+ return this.codeTarget("link", pending.candidateUserId);
3507
+ }
3508
+ /** {@link codeTarget} of the `pincode-send` / `pincode-check` pair. */
3509
+ pincodeTarget(ctx, address) {
3510
+ if (ctx.mfa?.method) return this.codeTarget("mfa", ctx.subject, address);
3511
+ return this.codeTarget(ctx.signup ? "signup" : "recovery", ctx.email);
3512
+ }
3513
+ /**
3514
+ * Server-side gate of a code send to `target`, before minting: answers
3515
+ * `429 AOOTH_CODE_LIMIT_REACHED` once the target's failed-code budget is
3516
+ * spent (this client IP's, or all IPs' together), applies the per-account
3517
+ * `aooth.send-user` limit when `account` is given (sends after a first
3518
+ * factor), and claims this client IP's resend wait for the target
3519
+ * (`mfa.pincodeResendTimeoutMs`) and a slot of the target's send cap from
3520
+ * all IPs (`mfa.pincodeMaxSendsGlobal` per `pincodeFailureWindowMs`).
3521
+ * Returns whether the code may go out: `false` inside the wait or past the
3522
+ * cap — the caller mints a code all the same and sends nothing, for known
3523
+ * and unknown destinations alike.
3524
+ */
3525
+ async claimCodeSend(target, account) {
3526
+ if (account !== void 0) await enforceRateLimit(SEND_USER_RATE_LIMIT, `user:${account}`);
3527
+ await this.assertCodeBudget(this.counterKeys(CODE_FAIL_PREFIX, target));
3528
+ const store = this.opts.lockoutShadowStore;
3529
+ const keys = this.counterKeys(CODE_SEND_PREFIX, target);
3530
+ if (await store.hit(keys.client, this.opts.mfa.pincodeResendTimeoutMs) > 1) return false;
3531
+ return await store.hit(keys.global, this.opts.mfa.pincodeFailureWindowMs) <= this.opts.mfa.pincodeMaxSendsGlobal;
3532
+ }
3533
+ /** Whether a send to `target` is cooling down (`false` when the store cannot peek). */
3534
+ async codeSendCoolingDown(target) {
3535
+ const store = this.opts.lockoutShadowStore;
3536
+ if (!store.get) return false;
3537
+ const keys = this.counterKeys(CODE_SEND_PREFIX, target);
3538
+ return await store.get(keys.client) > 0 || await store.get(keys.global) >= this.opts.mfa.pincodeMaxSendsGlobal;
3539
+ }
3540
+ /**
3541
+ * Counters of a destination, per client IP and across all IPs:
3542
+ * - sends (`CODE_SEND_PREFIX`): this client's resend wait, and the sends
3543
+ * from all IPs together in the window (the cap on mail-bombing and SMS
3544
+ * pumping spread over many IPs);
3545
+ * - failed codes (`CODE_FAIL_PREFIX`): the budget one caller can spend (so
3546
+ * an attacker cannot lock the owner out from elsewhere), and the backstop
3547
+ * against distributed guessing.
3548
+ *
3549
+ * The client IP is hashed: fixed-size keys, no raw IPs in the store.
3550
+ */
3551
+ counterKeys(prefix, target) {
3552
+ return {
3553
+ client: `${prefix}${target}:${sha256url(requestClientIp())}`,
3554
+ global: `${prefix}${target}`
3555
+ };
3556
+ }
3557
+ /** Answer `429 AOOTH_CODE_LIMIT_REACHED` once a destination's failed-code budget is spent. */
3558
+ async assertCodeBudget(keys) {
3559
+ const store = this.opts.lockoutShadowStore;
3560
+ if (!store.get) return;
3561
+ const [client, global] = await Promise.all([store.get(keys.client), store.get(keys.global)]);
3562
+ if (client >= this.opts.mfa.pincodeMaxFailures || global >= this.opts.mfa.pincodeMaxFailuresGlobal) throw aoothHttpError(429, "AOOTH_CODE_LIMIT_REACHED");
3563
+ }
3564
+ /**
3565
+ * Verify a submitted code against the one minted for `binding`. Returns an
3566
+ * error map (keyed under `code` so it renders on the code input) or `null`
3567
+ * on success.
3568
+ *
3569
+ * Attempts are counted server-side in `lockoutShadowStore`, per minted code
3570
+ * (its nonce), before the comparison: a replayed older state token shares
3571
+ * the counter, so `pincodeMaxAttempts` holds across replays and parallel
3572
+ * submits. A code is single-use: once it verifies, its nonce is spent and
3573
+ * the same code through any copy of the state is refused. A binding that
3574
+ * differs from the one at mint (the account resolved differently since the
3575
+ * send) reads as a wrong code. Wrong codes also count against `target`'s
3576
+ * failed-code budgets across resends (`mfa.pincodeMaxFailures` per client
3577
+ * IP, `pincodeMaxFailuresGlobal` for all IPs, per
3578
+ * `pincodeFailureWindowMs`); once one is spent every check answers
3579
+ * `429 AOOTH_CODE_LIMIT_REACHED`.
3580
+ */
3581
+ async verifyPin(ctx, submitted, binding, target) {
3582
+ const failureKeys = this.counterKeys(CODE_FAIL_PREFIX, target);
3583
+ await this.assertCodeBudget(failureKeys);
3584
+ const { pinNonce: nonce, pinDigest: digest, pinExpire: expire } = ctx;
3585
+ const now = Date.now();
3586
+ if (!nonce || !digest || !expire || now > expire) return { code: this.msg("AOOTH_CODE_EXPIRED") };
3587
+ const store = this.opts.lockoutShadowStore;
3588
+ const ttl = expire - now + PIN_COUNTER_GRACE_MS;
3589
+ const attempts = await store.hit(`${PIN_ATTEMPT_PREFIX}${nonce}`, ttl);
3590
+ const max = this.opts.mfa.pincodeMaxAttempts;
3591
+ if (attempts > max) return { code: this.msg("AOOTH_TOO_MANY_CODE_ATTEMPTS") };
3592
+ if (!safeEqual(this.pinDigest(nonce, binding, submitted ?? ""), digest)) {
3593
+ const window = this.opts.mfa.pincodeFailureWindowMs;
3594
+ const [client, global] = await Promise.all([store.hit(failureKeys.client, window), store.hit(failureKeys.global, window)]);
3595
+ if (client > this.opts.mfa.pincodeMaxFailures || global > this.opts.mfa.pincodeMaxFailuresGlobal) throw aoothHttpError(429, "AOOTH_CODE_LIMIT_REACHED");
3596
+ return { code: this.msg(attempts >= max ? "AOOTH_TOO_MANY_CODE_ATTEMPTS" : "AOOTH_INVALID_CODE") };
3597
+ }
3598
+ const spent = await store.hit(`${PIN_SPENT_PREFIX}${nonce}`, ttl);
3599
+ this.clearPin(ctx);
3600
+ if (spent > 1) return { code: this.msg("AOOTH_CODE_EXPIRED") };
2958
3601
  return null;
2959
3602
  }
3603
+ /** Keyed digest of a code, bound to its nonce and to who it was sent for. */
3604
+ pinDigest(nonce, binding, code) {
3605
+ return createHmac("sha256", this.pincodeKey()).update(`${nonce}|${binding}|${code}`).digest("base64url");
3606
+ }
3607
+ /**
3608
+ * Key of the code digests: the one `WfTriggerProvider` publishes for the
3609
+ * request (derived from its `pincodeSecret()`), else the key a default
3610
+ * provider publishes (`defaultPincodeKey`: derived from the default wf-state
3611
+ * secret), so a code minted on one path verifies on the other. Throws
3612
+ * `INVALID_CONFIG` outside a provider when the credential store has no
3613
+ * derivable secret. Override when the workflow runs outside a
3614
+ * `WfTriggerProvider` whose `wfStateSecret()` / `pincodeSecret()` is
3615
+ * overridden — return that provider's key; every instance must agree.
3616
+ */
3617
+ pincodeKey() {
3618
+ const ctx = tryGetCurrent();
3619
+ if (ctx?.has(pincodeKeySlot)) return ctx.get(pincodeKeySlot);
3620
+ return this.fallbackPincodeKey ??= defaultPincodeKey(this.auth);
3621
+ }
3622
+ fallbackPincodeKey;
2960
3623
  /**
2961
3624
  * Validate + stash inline-consent fields submitted on a carrier form.
2962
3625
  * SECURITY: silently drops unknown ids (audit-grade defense — see base
@@ -3017,12 +3680,19 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3017
3680
  * `enrollConfirm`, so the arming policy cannot drift between first send
3018
3681
  * and resend.
3019
3682
  */
3020
- async mintAndSendEnrollPincode(ctx, address) {
3021
- const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
3683
+ async mintAndSendEnrollPincode(ctx, address, claimed) {
3684
+ const deliver = claimed ?? await this.claimCodeSend(this.enrollTarget(ctx, address), ctx.subject);
3685
+ const code = this.mintPin(ctx, this.pinFor(ctx, address));
3022
3686
  const pincode = ctx.pincode ??= {};
3023
3687
  pincode.resendAllowedAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
3024
3688
  pincode.codeLength = this.opts.mfa.pincodeLength;
3025
- await this.sendEnrollPincode(ctx, address, code);
3689
+ if (deliver) await this.sendEnrollPincode(ctx, address, code);
3690
+ }
3691
+ /** Seconds a resend still has to wait — the state's hint, else a full cooldown. */
3692
+ resendWaitSeconds(until) {
3693
+ const now = Date.now();
3694
+ const ms = until && until > now ? until - now : this.opts.mfa.pincodeResendTimeoutMs;
3695
+ return Math.ceil(ms / 1e3);
3026
3696
  }
3027
3697
  /**
3028
3698
  * Idempotent TOTP secret provisioning into wf-state ONLY (the QR renders
@@ -3067,8 +3737,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3067
3737
  delete m.qrSeen;
3068
3738
  delete m.preConfirmed;
3069
3739
  }
3070
- delete ctx.pin;
3071
- delete ctx.pinExpire;
3740
+ this.clearPin(ctx);
3072
3741
  if (ctx.pincode) delete ctx.pincode.sentTo;
3073
3742
  }
3074
3743
  /**
@@ -3097,11 +3766,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3097
3766
  */
3098
3767
  validateMfaAddress(_ctx, method, value) {
3099
3768
  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");
3769
+ if (!v) return this.msg("AOOTH_ADDRESS_REQUIRED");
3770
+ if (method === "email") return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? void 0 : this.msg("AOOTH_INVALID_EMAIL_ADDRESS");
3102
3771
  if (method === "sms") {
3103
3772
  const digits = v.replace(/[\s()+.-]/g, "");
3104
- return /^[1-9]\d{6,14}$/.test(digits) ? void 0 : this.msg("INVALID_PHONE_NUMBER");
3773
+ return /^[1-9]\d{6,14}$/.test(digits) ? void 0 : this.msg("AOOTH_INVALID_PHONE_NUMBER");
3105
3774
  }
3106
3775
  }
3107
3776
  /**
@@ -3339,6 +4008,10 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3339
4008
  if (alt.ssoProviders.length > 0) altActions.ssoProviders = alt.ssoProviders;
3340
4009
  const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.loginCredentials);
3341
4010
  const action = wf.resolveAction();
4011
+ if (action === "magicLink" && alt.magicLink) {
4012
+ ctx.magicLink = { purpose: "login" };
4013
+ return;
4014
+ }
3342
4015
  if (action) {
3343
4016
  const typedUsername = getInputField("username");
3344
4017
  if (await this.handleCredentialsAlt(action, typedUsername, alt, ctx.authz?.handle) === ALT_HANDLED) return void 0;
@@ -3346,35 +4019,48 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3346
4019
  const input = wf.resolveInput();
3347
4020
  try {
3348
4021
  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
4022
  ctx.loginRecorded = true;
3352
4023
  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);
4024
+ await this.bindSignedInUser(ctx, result.user);
3369
4025
  } catch (err) {
3370
4026
  if (err instanceof UserAuthError) {
3371
4027
  const locked = await this.failedLoginReadsLocked(ctx, err, input.username);
3372
- throw this.throwPublic(ctx, wf, { formMessage: this.msg(locked ? "ACCOUNT_LOCKED" : "INVALID_CREDENTIALS") });
4028
+ throw this.throwPublic(ctx, wf, { formMessage: this.msg(locked ? "AOOTH_ACCOUNT_LOCKED" : "INVALID_CREDENTIALS") });
3373
4029
  }
3374
4030
  throw err;
3375
4031
  }
3376
4032
  }
3377
4033
  /**
4034
+ * Bind the login run to the account that passed its first factor — shared
4035
+ * by the password and magic-link sign-ins, so both leave the run alike:
4036
+ * - `ctx.subject` and the password stamp;
4037
+ * - the inline password guards (`ctx.guards`): top-level
4038
+ * `isPasswordInitial` / `isPasswordExpired` (read by
4039
+ * `prepare-semantic-flags` later as a fallback) and the change reason;
4040
+ * - the account's confirmed channels, so `ensureEmail` / `ensurePhone` skip
4041
+ * what is already confirmed and security notices have a recipient.
4042
+ */
4043
+ async bindSignedInUser(ctx, user) {
4044
+ ctx.subject = user.id;
4045
+ ctx.passwordStamp = user.password.lastChanged ?? 0;
4046
+ if (ctx.guards?.passwordInitial && user.password.isInitial) ctx.isPasswordInitial = true;
4047
+ if (ctx.guards?.passwordExpiry && this.users.isPasswordExpired(user)) ctx.isPasswordExpired = true;
4048
+ if (ctx.isPasswordInitial) (ctx.password ??= {}).changeReason = "initial";
4049
+ else if (ctx.isPasswordExpired) (ctx.password ??= {}).changeReason = "expired";
4050
+ const email = user.mfa.methods.find((m) => m.name === "email" && m.confirmed);
4051
+ if (email) {
4052
+ (ctx.notice ??= {}).email = email.value;
4053
+ (ctx.channel ??= {}).emailConfirmed = true;
4054
+ }
4055
+ const phone = user.mfa.methods.find((m) => m.name === "sms" && m.confirmed);
4056
+ if (phone) {
4057
+ const channel = ctx.channel ??= {};
4058
+ channel.phone = phone.value;
4059
+ channel.phoneConfirmed = true;
4060
+ }
4061
+ if (!ctx.notice?.email) await this.seedCorrespondenceEmail(ctx, user);
4062
+ }
4063
+ /**
3378
4064
  * Whether a failed password sign-in answers "Account locked" — see
3379
4065
  * `AuthWorkflowOpts.lockoutDisclosure`. Under `'uniform'` an unknown or
3380
4066
  * inactive handle keeps a shadow failure counter in `lockoutShadowStore`
@@ -3396,7 +4082,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3396
4082
  };
3397
4083
  if (threshold <= 0) return false;
3398
4084
  const store = this.opts.lockoutShadowStore;
3399
- const id = createHash("sha256").update(handle.trim().toLowerCase()).digest("base64url");
4085
+ const id = sha256url(handle.trim().toLowerCase());
3400
4086
  const lockKey = `${SHADOW_LOCK_PREFIX}${id}`;
3401
4087
  if (store.get && await store.get(lockKey) > 0) {
3402
4088
  if (duration <= 0) await store.expire?.(lockKey, SHADOW_TTL_MS);
@@ -3438,7 +4124,6 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3438
4124
  } });
3439
4125
  return ALT_HANDLED;
3440
4126
  }
3441
- if (action === "magicLink" && alt.magicLink) throw new HttpError$1(501, "Magic-link login path not implemented in this version");
3442
4127
  if (action === "sso") {
3443
4128
  const providerId = getInputField("ssoProvider");
3444
4129
  const sso = providerId ? alt.ssoProviders.find((p) => p.id === providerId) : void 0;
@@ -3463,28 +4148,75 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3463
4148
  if (prefilled) ctx.defaults = { email: prefilled };
3464
4149
  throw this.throwPublic(ctx, emailWf);
3465
4150
  }
3466
- const email = emailWf.resolveInput().email;
3467
- ctx.email = email;
3468
- let subject;
4151
+ ctx.email = emailWf.resolveInput().email;
4152
+ const modeResult = this.resolveRecoveryDeliveryMode(ctx);
4153
+ await this.applyRecoveryMode(ctx, modeResult instanceof Promise ? await modeResult : modeResult);
4154
+ }
4155
+ /**
4156
+ * Start recovery's delivery `mode` — the same way for known and unknown
4157
+ * identifiers:
4158
+ * - `'magicLink'`: the link for the typed identifier, resolved now but held
4159
+ * only in the link's server-side pause (the requester never gets a token
4160
+ * for it, and an earlier picker's state holds nothing about the account);
4161
+ * - `'otp'`: the durable store strategy. Nothing about the account goes into
4162
+ * the state before the code is verified: `pincode-send` /
4163
+ * `pincode-check` resolve it from the typed identifier each time.
4164
+ */
4165
+ async applyRecoveryMode(ctx, mode) {
4166
+ ctx.recoveryDelivery = mode;
4167
+ if (mode === "magicLink") ctx.magicLink = await this.recoveryMagicLink(ctx);
4168
+ else if (mode === "otp") swapStrategy("store");
4169
+ }
4170
+ /** A recovery magic link for the typed identifier (`subject` unset when it matches no account). */
4171
+ async recoveryMagicLink(ctx) {
4172
+ const email = ctx.email ?? "";
4173
+ const subject = await this.lookupRecoverySubject(email);
4174
+ return {
4175
+ purpose: "recovery",
4176
+ identifier: email.trim().toLowerCase(),
4177
+ ...subject && { subject }
4178
+ };
4179
+ }
4180
+ /** `emailToUserId`, with an unknown identifier as `undefined`. */
4181
+ async lookupRecoverySubject(identifier) {
3469
4182
  try {
3470
- subject = await this.emailToUserId(email) ?? void 0;
4183
+ return await this.emailToUserId(identifier) ?? void 0;
3471
4184
  } catch (err) {
3472
4185
  if (!(err instanceof UserAuthError) || err.type !== "NOT_FOUND") throw err;
3473
- }
3474
- if (!subject) {
3475
- this.finishGenericRecovery();
3476
4186
  return;
3477
4187
  }
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
- }
4188
+ }
4189
+ /**
4190
+ * The account a recovery code for the typed identifier goes to, and where —
4191
+ * or `null` when no code can go anywhere: an unknown identifier, an inactive
4192
+ * (pending / deactivated) account, or under M2 an account without a
4193
+ * deliverable confirmed channel. A locked account may recover (self-service
4194
+ * unlock). Resolved from `ctx.email` on every send and at verification —
4195
+ * never kept in the state — and with the same reads for every identifier
4196
+ * (an unknown one reads a placeholder row).
4197
+ */
4198
+ async recoveryAccount(ctx) {
4199
+ const subject = await this.lookupRecoverySubject(ctx.email ?? "");
4200
+ let user;
4201
+ try {
4202
+ user = await this.users.getUser(subject ?? UNKNOWN_ACCOUNT_ID);
4203
+ } catch (err) {
4204
+ if (!(err instanceof UserAuthError) || err.type !== "NOT_FOUND") throw err;
4205
+ }
4206
+ const known = Boolean(subject && user?.account.active);
4207
+ try {
4208
+ const target = await this.resolvePincodeTarget({
4209
+ ...ctx,
4210
+ subject: known ? subject : UNKNOWN_ACCOUNT_ID
4211
+ });
4212
+ return known ? {
4213
+ subject,
4214
+ ...target
4215
+ } : null;
4216
+ } catch (err) {
4217
+ if (!known || err instanceof RecoveryMethodUnavailableError) return null;
4218
+ throw err;
3485
4219
  }
3486
- ctx.subject = subject;
3487
- swapStrategy("store");
3488
4220
  }
3489
4221
  /**
3490
4222
  * Resolves the recovery-step `email` input to the user's stable `id` (the
@@ -3495,16 +4227,6 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3495
4227
  async emailToUserId(email) {
3496
4228
  return (await this.users.findByHandle(email))?.id ?? null;
3497
4229
  }
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
4230
  /**
3509
4231
  * Stamp `recoveryStateTtlMs` on a paused-state error so the wf engine's
3510
4232
  * persisted-state strategy expires the state at that timestamp. Use at
@@ -3747,12 +4469,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3747
4469
  const parsed = this.effectiveInviteRoles(ctx, roles);
3748
4470
  if (Array.isArray(ctx.admin?.availableRoles)) {
3749
4471
  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") } });
4472
+ if (parsed.find((r) => !allowed.has(r)) !== void 0) throw this.throwPublic(ctx, wf, { errors: { roles: this.msg("AOOTH_INVALID_ROLE") } });
3751
4473
  }
3752
4474
  if (Object.keys(extra).length > 0) (ctx.admin ??= {}).form = extra;
3753
4475
  const existing = await this.users.findByHandle(email);
3754
4476
  const invitedBy = useAuth().getAuthContext()?.userId;
3755
- const pendingIssuer = existing?.account?.pendingInvitation ? existing.account.invitedBy : void 0;
4477
+ const pendingIssuer = existing?.account?.pendingInvitation ? existing.account.invitedBy ?? void 0 : void 0;
3756
4478
  if (invitedBy) (ctx.admin ??= {}).invitedBy = invitedBy;
3757
4479
  const action = await this.duplicateInviteCheck({
3758
4480
  email,
@@ -3762,7 +4484,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3762
4484
  });
3763
4485
  if (action === "reject") {
3764
4486
  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") } });
4487
+ if (existing) throw this.throwPublic(ctx, wf, { errors: { email: this.msg("AOOTH_USER_ALREADY_EXISTS") } });
3766
4488
  throw this.throwPublic(ctx, wf, { errors: { email: this.msg("DUPLICATE_INVITE_REJECTED") } });
3767
4489
  }
3768
4490
  if (action === "reuse") {
@@ -3848,7 +4570,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3848
4570
  if (admin.reuseExisting) {
3849
4571
  const existing = await this.users.findByHandle(ctx.email);
3850
4572
  if (existing) {
3851
- if (!existing.account?.pendingInvitation) throw this.httpError(409, "USER_ALREADY_EXISTS");
4573
+ if (!existing.account?.pendingInvitation) throw this.httpError(409, "AOOTH_USER_ALREADY_EXISTS");
3852
4574
  await this.users.update(existing.id, {
3853
4575
  ...fields,
3854
4576
  account: pendingAccount
@@ -3861,7 +4583,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3861
4583
  try {
3862
4584
  created = await this.users.createUser(ctx.email, void 0, fields);
3863
4585
  } catch (err) {
3864
- if (err instanceof UserAuthError && err.type === "ALREADY_EXISTS") throw this.httpError(409, "USER_ALREADY_EXISTS");
4586
+ if (err instanceof UserAuthError && err.type === "ALREADY_EXISTS") throw this.httpError(409, "AOOTH_USER_ALREADY_EXISTS");
3865
4587
  throw err;
3866
4588
  }
3867
4589
  await this.users.update(created.id, { account: pendingAccount });
@@ -3955,7 +4677,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3955
4677
  const user = await this.users.findByIdentifier(ctx.subject);
3956
4678
  if (!user) throw this.httpError(410, "INVITE_CANCELLED");
3957
4679
  const current = user.account?.inviteNonce;
3958
- if (current !== void 0 && current !== ctx.admin?.inviteNonce) throw this.httpError(410, "INVITE_REPLACED");
4680
+ if (current != null && current !== ctx.admin?.inviteNonce) throw this.httpError(410, "INVITE_REPLACED");
3959
4681
  return user;
3960
4682
  }
3961
4683
  /**
@@ -4021,7 +4743,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4021
4743
  data: { confirmed: true },
4022
4744
  message: {
4023
4745
  level: "success",
4024
- text: ctx.accept?.confirmationMessage ?? this.msg("ACCOUNT_CREATED")
4746
+ text: ctx.accept?.confirmationMessage ?? this.msg("AOOTH_ACCOUNT_CREATED")
4025
4747
  }
4026
4748
  });
4027
4749
  }
@@ -4087,7 +4809,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4087
4809
  next: {
4088
4810
  trigger: "manual",
4089
4811
  primary: {
4090
- label: this.msg("BACK"),
4812
+ label: this.msg("AOOTH_BACK"),
4091
4813
  action: {
4092
4814
  type: "redirect",
4093
4815
  target: this.opts.loginUrl,
@@ -4268,7 +4990,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4268
4990
  },
4269
4991
  message: {
4270
4992
  level: "info",
4271
- text: addMfa.blocked === "last-required-factor" ? this.msg("LAST_MFA_METHOD_NOT_REMOVABLE") : this.msg("METHOD_NOT_CHANGEABLE")
4993
+ text: addMfa.blocked === "last-required-factor" ? this.msg("LAST_MFA_METHOD_NOT_REMOVABLE") : this.msg("AOOTH_METHOD_NOT_CHANGEABLE")
4272
4994
  }
4273
4995
  };
4274
4996
  else if (candidates.length === 0 && !addMfa?.stepUpRequired) envelope = {
@@ -4425,12 +5147,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4425
5147
  const action = sep >= 0 ? input.operation.slice(0, sep) : "";
4426
5148
  const target = sep >= 0 ? input.operation.slice(sep + 1) : "";
4427
5149
  if (action === "add") {
4428
- if (!candidates.includes(target)) throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("METHOD_UNAVAILABLE") } });
5150
+ if (!candidates.includes(target)) throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("AOOTH_METHOD_UNAVAILABLE") } });
4429
5151
  } 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") } });
5152
+ if (locked.has(target)) throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_METHOD_NOT_CHANGEABLE") });
5153
+ if (!enrolled.some((e) => e.kind === target)) throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("AOOTH_UNKNOWN_METHOD") } });
4432
5154
  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") } });
5155
+ } else throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("AOOTH_CHOOSE_OPTION") } });
4434
5156
  addMfa.action = action;
4435
5157
  addMfa.target = target;
4436
5158
  const m = ctx.mfaEnroll ??= {};
@@ -4498,20 +5220,30 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4498
5220
  }));
4499
5221
  if (isEmail) (ctx.channel ??= {}).email = value;
4500
5222
  else (ctx.channel ??= {}).phone = value;
4501
- const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
4502
- await this.dispatch({
5223
+ const deliver = await this.claimCodeSend(this.enrollTarget(ctx, value), ctx.subject);
5224
+ await this.sendChannelPincode(ctx, value, isEmail ? "email" : "sms", deliver);
5225
+ const pincodeWf = this.useAtscriptWfPublic(ctx, this.opts.forms.pincode);
5226
+ throw this.throwPublic(ctx, pincodeWf);
5227
+ }
5228
+ /**
5229
+ * Mint the code proving a channel (`ask/*`, `verify/*`), deliver it when
5230
+ * `deliver`, and arm the PincodeForm: the resend wait `verifyChannel`
5231
+ * gates "Resend code" on (the same cooldown contract as `pincode-send`),
5232
+ * the masked `sentTo` its "Code sent to …" hint renders, and the code length.
5233
+ */
5234
+ async sendChannelPincode(ctx, address, channel, deliver) {
5235
+ const code = this.mintPin(ctx, this.pinFor(ctx, address));
5236
+ if (deliver) await this.dispatch({
4503
5237
  kind: "enroll-pincode",
4504
- channel: isEmail ? "email" : "sms",
4505
- recipient: value,
5238
+ channel,
5239
+ recipient: address,
4506
5240
  code,
4507
5241
  expiresInMs: this.opts.mfa.pincodeTtlMs
4508
5242
  });
4509
5243
  const pincode = ctx.pincode ??= {};
4510
5244
  pincode.resendAllowedAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
4511
- pincode.sentTo = this.maskAddress(value, isEmail ? "email" : "sms");
5245
+ pincode.sentTo = this.maskAddress(address, channel);
4512
5246
  pincode.codeLength = this.opts.mfa.pincodeLength;
4513
- const pincodeWf = this.useAtscriptWfPublic(ctx, this.opts.forms.pincode);
4514
- throw this.throwPublic(ctx, pincodeWf);
4515
5247
  }
4516
5248
  async verifyChannel(ctx, channel) {
4517
5249
  this.requireSubject(ctx);
@@ -4519,27 +5251,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4519
5251
  const pincodeWf = this.useAtscriptWfPublic(ctx, this.opts.forms.pincode);
4520
5252
  const action = pincodeWf.resolveAction();
4521
5253
  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
- }
5254
+ const cooldown = ctx.pincode?.resendAllowedAt;
4526
5255
  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;
5256
+ 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) }) });
5257
+ await this.sendChannelPincode(ctx, recipient, isEmail ? "email" : "sms", true);
4539
5258
  throw this.throwPublic(ctx, pincodeWf);
4540
5259
  }
4541
5260
  const input = pincodeWf.resolveInput();
4542
- const pinErr = this.verifyPin(ctx, input.code);
5261
+ const recipient = (isEmail ? ctx.channel?.email : ctx.channel?.phone) ?? "";
5262
+ const pinErr = await this.verifyPin(ctx, input.code, this.pinFor(ctx, recipient), this.enrollTarget(ctx, recipient));
4543
5263
  if (pinErr) throw this.throwPublic(ctx, pincodeWf, { errors: pinErr });
4544
5264
  await this.withStoreErrorTranslation(() => this.users.confirmMfaMethod(ctx.subject, isEmail ? "email" : "sms"));
4545
5265
  const channelState = ctx.channel ??= {};
@@ -4555,8 +5275,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4555
5275
  const target = isEmail ? channelState.email : channelState.phone;
4556
5276
  await this.consentStore.recordOtpChannelConsent(ctx.subject, channelArg, target, channelState.otpDisclosure);
4557
5277
  }
4558
- delete ctx.pin;
4559
- delete ctx.pinExpire;
5278
+ this.clearPin(ctx);
4560
5279
  if (ctx.pincode) {
4561
5280
  delete ctx.pincode.resendAllowedAt;
4562
5281
  delete ctx.pincode.sentTo;
@@ -4582,16 +5301,13 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4582
5301
  } else trust.newDevice = true;
4583
5302
  }
4584
5303
  /**
4585
- * Resolve the client IP from the active HTTP request, swallowing the case
4586
- * where there is no HTTP context (unit tests that hand-roll the wf runtime).
4587
- * Ported from `AuthWorkflowBase`.
5304
+ * Resolve the client IP from the active HTTP request — the IP the HTTP app
5305
+ * resolves (its `trustProxy` / `proxyHeaders`), the same one the rate
5306
+ * limiter keys on — swallowing the case where there is no HTTP context
5307
+ * (unit tests that hand-roll the wf runtime).
4588
5308
  */
4589
5309
  resolveClientIp() {
4590
- try {
4591
- return useRequest().getIp() || void 0;
4592
- } catch {
4593
- return;
4594
- }
5310
+ return requestClientIp() || void 0;
4595
5311
  }
4596
5312
  /**
4597
5313
  * Resolve the client `User-Agent` from the active HTTP request. Sibling to
@@ -4694,7 +5410,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4694
5410
  if (cooldownUntil && Date.now() < cooldownUntil) {
4695
5411
  const waitSec = Math.ceil((cooldownUntil - Date.now()) / 1e3);
4696
5412
  const channel = picked.kind === "sms" ? "SMS" : "email";
4697
- throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_CHANNEL", {
5413
+ throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_RESEND_WAIT_CHANNEL", {
4698
5414
  seconds: waitSec,
4699
5415
  channel
4700
5416
  }) });
@@ -4711,45 +5427,52 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4711
5427
  * `resolvePincodeTarget` (which discriminate on `ctx.mfa?.method` presence).
4712
5428
  */
4713
5429
  async pincodeSend(ctx) {
5430
+ const recovery = !ctx.mfa?.method && !ctx.signup;
5431
+ if (!ctx.mfa?.method) await enforceRateLimit(SEND_RATE_LIMIT);
4714
5432
  let target;
4715
- try {
5433
+ let account = null;
5434
+ if (recovery) {
5435
+ account = await this.recoveryAccount(ctx);
5436
+ target = await this.recoveryPincodeTarget(ctx, "typed");
5437
+ } else {
4716
5438
  const targetResult = this.resolvePincodeTarget(ctx);
4717
5439
  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
5440
  }
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;
5441
+ const registeredRecovery = recovery && await this.recoveryDeliverySource(ctx) === "registered";
5442
+ const binding = recovery ? this.recoveryBinding(account) : this.pinFor(ctx, target.address);
5443
+ const deliver = await this.claimCodeSend(this.pincodeTarget(ctx, target.address), ctx.mfa?.method ? ctx.subject : void 0);
5444
+ const code = this.mintPin(ctx, binding);
5445
+ if (deliver) {
5446
+ if (ctx.mfa?.method) await this.dispatch({
5447
+ kind: "mfa-pincode",
5448
+ channel: target.channel,
5449
+ recipient: target.address,
5450
+ code,
5451
+ expiresInMs: this.opts.mfa.pincodeTtlMs
5452
+ });
5453
+ else if (ctx.signup) await this.dispatch({
5454
+ kind: "signup-pincode",
5455
+ channel: "email",
5456
+ recipient: target.address,
5457
+ code,
5458
+ expiresInMs: this.opts.mfa.pincodeTtlMs
5459
+ });
5460
+ else if (account) await this.dispatch({
5461
+ kind: "recovery-pincode",
5462
+ channel: account.channel,
5463
+ recipient: account.address,
5464
+ code,
5465
+ expiresInMs: this.opts.mfa.pincodeTtlMs
5466
+ });
5467
+ }
5468
+ if (!recovery) {
5469
+ const otp = ctx.otp ??= {};
5470
+ otp.deliveredTo = target.address;
5471
+ otp.deliveredChannel = target.channel;
5472
+ }
4751
5473
  const pincode = ctx.pincode ??= {};
4752
- pincode.sentTo = this.maskAddress(target.address, target.channel);
5474
+ if (registeredRecovery) delete pincode.sentTo;
5475
+ else pincode.sentTo = this.maskAddress(target.address, target.channel);
4753
5476
  pincode.codeLength = this.opts.mfa.pincodeLength;
4754
5477
  const cooldownAt = Date.now() + this.opts.mfa.pincodeResendTimeoutMs;
4755
5478
  pincode.resendAllowedAt = cooldownAt;
@@ -4766,12 +5489,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4766
5489
  if (action) {
4767
5490
  const outcome = this.resolvePincodeAltAction(ctx, action);
4768
5491
  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;
5492
+ 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) }) });
5493
+ this.clearPin(ctx);
4775
5494
  return;
4776
5495
  }
4777
5496
  if (outcome === "exit") {
@@ -4783,8 +5502,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4783
5502
  ctx.mfa.ignoreDefault = true;
4784
5503
  delete ctx.mfa.method;
4785
5504
  }
4786
- delete ctx.pin;
4787
- delete ctx.pinExpire;
5505
+ this.clearPin(ctx);
4788
5506
  if (ctx.pincode) delete ctx.pincode.resendAllowedAt;
4789
5507
  return;
4790
5508
  }
@@ -4796,15 +5514,22 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4796
5514
  if (ctx.postReset && err instanceof StepRetriableError) throw this.stampRecoveryExpiry(err);
4797
5515
  throw err;
4798
5516
  }
4799
- const pinErr = this.verifyPin(ctx, input.code);
5517
+ const recovery = !ctx.mfa?.method && !ctx.signup;
5518
+ const account = recovery ? await this.recoveryAccount(ctx) : null;
5519
+ const binding = recovery ? this.recoveryBinding(account) : this.pinFor(ctx, ctx.otp?.deliveredTo ?? "");
5520
+ const pinErr = await this.verifyPin(ctx, recovery && !account ? NO_CODE : input.code, binding, this.pincodeTarget(ctx, ctx.otp?.deliveredTo));
4800
5521
  if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
4801
5522
  const otp = ctx.otp ??= {};
5523
+ if (account) {
5524
+ ctx.subject = account.subject;
5525
+ otp.deliveredTo = account.address;
5526
+ otp.deliveredChannel = account.channel;
5527
+ }
4802
5528
  otp.verified = true;
4803
5529
  if (ctx.subject && otp.deliveredChannel === "email" && otp.deliveredTo) await this.users.setVerifiedEmail(ctx.subject, otp.deliveredTo);
4804
5530
  (ctx.session ??= {}).riskStepUpEvaluated = false;
4805
5531
  if (ctx.deviceTrust?.enabled && ctx.deviceTrust?.optIn) (ctx.trust ??= {}).rememberDevice = Boolean(input.rememberDevice);
4806
- delete ctx.pin;
4807
- delete ctx.pinExpire;
5532
+ this.clearPin(ctx);
4808
5533
  }
4809
5534
  /**
4810
5535
  * TOTP MFA challenge step body. Verifies a TOTP code via `users.verifyMfa`
@@ -4828,12 +5553,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4828
5553
  if (ctx.deviceTrust?.enabled && ctx.deviceTrust?.optIn) (ctx.trust ??= {}).rememberDevice = Boolean(input.rememberDevice);
4829
5554
  } catch (err) {
4830
5555
  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") } });
5556
+ if (err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_ACCOUNT_LOCKED") });
5557
+ if (err.type === "INACTIVE") throw this.throwPublic(ctx, wf, { errors: { code: this.msg("AOOTH_INVALID_CODE") } });
4833
5558
  if (err.type === "MFA_NOT_CONFIGURED") throw this.httpError(400, "TOTP_NOT_CONFIGURED");
4834
5559
  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") } });
5560
+ if (err.details?.lockEnds !== void 0) throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_ACCOUNT_LOCKED") });
5561
+ throw this.throwPublic(ctx, wf, { errors: { code: this.msg("AOOTH_INVALID_CODE") } });
4837
5562
  }
4838
5563
  }
4839
5564
  throw err;
@@ -4876,7 +5601,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4876
5601
  return;
4877
5602
  }
4878
5603
  const picked = wf.resolveInput().method;
4879
- if (!m.availableTransports.includes(picked)) throw this.throwPublic(ctx, wf, { errors: { method: this.msg("UNKNOWN_METHOD") } });
5604
+ if (!m.availableTransports.includes(picked)) throw this.throwPublic(ctx, wf, { errors: { method: this.msg("AOOTH_UNKNOWN_METHOD") } });
4880
5605
  m.method = picked;
4881
5606
  }
4882
5607
  return this.provisionTotpSecret(ctx);
@@ -5009,18 +5734,15 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5009
5734
  if (action === "resend") {
5010
5735
  if (m.method === "totp") throw this.throwPublic(ctx, wf, { formMessage: this.msg("TOTP_RESEND_NOT_APPLICABLE") });
5011
5736
  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);
5737
+ 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) }) });
5738
+ await this.mintAndSendEnrollPincode(ctx, m.address, true);
5017
5739
  return;
5018
5740
  }
5019
5741
  const input = wf.resolveInput();
5020
5742
  if (m.method === "totp") {
5021
- if (verifyTotpCode(m.secret, input.code) === null) throw this.throwPublic(ctx, wf, { errors: { code: this.msg("INVALID_CODE") } });
5743
+ if (verifyTotpCode(m.secret, input.code) === null) throw this.throwPublic(ctx, wf, { errors: { code: this.msg("AOOTH_INVALID_CODE") } });
5022
5744
  } else {
5023
- const pinErr = this.verifyPin(ctx, input.code);
5745
+ const pinErr = await this.verifyPin(ctx, input.code, this.pinFor(ctx, m.address ?? ""), this.enrollTarget(ctx, m.address));
5024
5746
  if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
5025
5747
  }
5026
5748
  await this.confirmEnrolledFactor(ctx);
@@ -5050,8 +5772,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5050
5772
  if (!m.keepExistingDefault) await this.users.setDefaultMfaMethod(username, methodName);
5051
5773
  m.done = true;
5052
5774
  (ctx.otp ??= {}).verified = true;
5053
- delete ctx.pin;
5054
- delete ctx.pinExpire;
5775
+ this.clearPin(ctx);
5055
5776
  }
5056
5777
  /**
5057
5778
  * Promote a freshly-confirmed channel into its login-handle column so future
@@ -5105,8 +5826,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5105
5826
  if (res.require) {
5106
5827
  session.riskStepUpReason = res.reason ?? "additional verification required";
5107
5828
  if (ctx.otp) delete ctx.otp.verified;
5108
- delete ctx.pin;
5109
- delete ctx.pinExpire;
5829
+ this.clearPin(ctx);
5110
5830
  } else delete session.riskStepUpReason;
5111
5831
  }
5112
5832
  /**
@@ -5299,6 +6019,36 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5299
6019
  }
5300
6020
  }
5301
6021
  /**
6022
+ * Login-only guard before the `record-login` funnel: an account deactivated
6023
+ * or locked while the run was paused (MFA, enrolment, consents …) is not
6024
+ * stamped, announced or signed in — the run finishes with an error.
6025
+ */
6026
+ async checkCanSignIn(ctx) {
6027
+ await this.loginAccountBlocked(ctx);
6028
+ }
6029
+ /**
6030
+ * Whether the run's account can no longer sign in (deactivated, locked or
6031
+ * deleted since it authenticated). If so the run is finished with an error
6032
+ * (`AOOTH_ACCOUNT_LOCKED` for a lock unless `lockoutDisclosure` is
6033
+ * `'generic'`, else `INVALID_CREDENTIALS`) and `ctx.aborted` is set.
6034
+ */
6035
+ async loginAccountBlocked(ctx) {
6036
+ this.requireSubject(ctx);
6037
+ try {
6038
+ await this.users.assertCanSignIn(ctx.subject);
6039
+ return false;
6040
+ } catch (err) {
6041
+ if (!(err instanceof UserAuthError)) throw err;
6042
+ const locked = err.type === "LOCKED" && this.opts.lockoutDisclosure !== "generic";
6043
+ ctx.aborted = true;
6044
+ finishWf({ message: {
6045
+ level: "error",
6046
+ text: this.msg(locked ? "AOOTH_ACCOUNT_LOCKED" : "INVALID_CREDENTIALS")
6047
+ } });
6048
+ return true;
6049
+ }
6050
+ }
6051
+ /**
5302
6052
  * The SINGLE login-completion funnel. Every flow that establishes an
5303
6053
  * authenticated session routes through here — placed in each login schema
5304
6054
  * right after the guards and BEFORE the delivery terminal (`issue` /
@@ -5346,6 +6096,21 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5346
6096
  }
5347
6097
  }
5348
6098
  /**
6099
+ * Auto-login guard, ahead of `record-login` on every auto-login path (invite,
6100
+ * recovery, signup): never stamp a login, fire `afterLogin` or issue a
6101
+ * session for an account that is no longer active (deactivated meanwhile —
6102
+ * every flow reaching here activated or verified it first). Recovery and
6103
+ * invite fall back to the fresh-login finish (no session); signup fails.
6104
+ */
6105
+ async autoLoginCheck(ctx) {
6106
+ this.requireSubject(ctx);
6107
+ const { account } = await this.users.getUser(ctx.subject);
6108
+ if (account.active) return void 0;
6109
+ if (!ctx.postReset && !ctx.accept) throw new HttpError$1(403, "Account is not active");
6110
+ this.finalizeFreshLogin(ctx);
6111
+ ctx.autoLogin = false;
6112
+ }
6113
+ /**
5349
6114
  * Thin dispatcher steps for the flow-specific lifecycle hooks. Each is its own
5350
6115
  * schema step (rather than an in-terminal call) because its flow's finalize
5351
6116
  * terminals are SHARED across flows (`finalize-auto-login` serves invite +
@@ -5370,6 +6135,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5370
6135
  */
5371
6136
  async issue(ctx) {
5372
6137
  this.requireSubject(ctx);
6138
+ try {
6139
+ await this.users.assertCanSignIn(ctx.subject);
6140
+ } catch (err) {
6141
+ if (err instanceof UserAuthError) throw new HttpError$1(403, "Account cannot sign in");
6142
+ throw err;
6143
+ }
5373
6144
  const issue = await this.issueForContext(ctx);
5374
6145
  const auth = useAuth();
5375
6146
  const envelope = {
@@ -5548,6 +6319,10 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5548
6319
  } });
5549
6320
  return;
5550
6321
  }
6322
+ if (await this.loginAccountBlocked(ctx)) {
6323
+ await pending.delete(handle);
6324
+ return;
6325
+ }
5551
6326
  const { code } = await codes.mint({
5552
6327
  userId: ctx.subject,
5553
6328
  codeChallenge: req.codeChallenge,
@@ -5650,7 +6425,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5650
6425
  target,
5651
6426
  reason: "reset-success"
5652
6427
  },
5653
- skipButton: { label: this.msg("GO_NOW") }
6428
+ skipButton: { label: this.msg("AOOTH_GO_NOW") }
5654
6429
  }
5655
6430
  });
5656
6431
  (ctx.completion ??= {}).redirectUrl = target;
@@ -5663,13 +6438,14 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5663
6438
  * tokens (WF-INVITE-020).
5664
6439
  *
5665
6440
  * 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.
6441
+ * `afterLogin` hook are owned by the upstream `record-login` funnel step,
6442
+ * the inactive-account guard by `auto-login-check`, and the
6443
+ * admin-only-survived-lock guard by `recovery-lock-check` — all upstream, so
6444
+ * an inactive or still-frozen account never reaches here.
5670
6445
  */
5671
6446
  async finalizeAutoLogin(ctx) {
5672
6447
  this.requireSubject(ctx);
6448
+ if (!(await this.users.getUser(ctx.subject)).account.active) throw new HttpError$1(403, "Account is not active");
5673
6449
  const issue = await this.issueForContext(ctx);
5674
6450
  const auth = useAuth();
5675
6451
  const previousMessage = (useWfFinished().get()?.value)?.message;
@@ -5772,7 +6548,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5772
6548
  finishWf({
5773
6549
  message: {
5774
6550
  level: "info",
5775
- text: this.msg("ALREADY_HAVE_ACCOUNT")
6551
+ text: this.msg("AOOTH_ALREADY_HAVE_ACCOUNT")
5776
6552
  },
5777
6553
  next: {
5778
6554
  trigger: "immediate",
@@ -5792,9 +6568,215 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5792
6568
  * the freshly-created `ctx.subject`. Mirrors login's `extra-step` seam.
5793
6569
  */
5794
6570
  signupExtraStep(_ctx) {}
5795
- magicLinkRequest(_ctx) {}
5796
- magicLinkSend(_ctx) {}
5797
- magicLinkVerified(_ctx) {}
6571
+ /**
6572
+ * Login's `magicLink` alt-action: the identifier form. Resolves the account
6573
+ * (unknown, inactive or locked identifiers resolve to none — the answer is
6574
+ * the same) and hands over to `magic-link-send`.
6575
+ */
6576
+ async magicLinkRequest(ctx) {
6577
+ const ml = ctx.magicLink;
6578
+ if (!ml || ml.purpose !== "login" || ml.sentAt !== void 0) return void 0;
6579
+ const { identifier } = this.useAtscriptWfPublic(ctx, this.opts.forms.magicLinkRequest).resolveInput();
6580
+ const user = await this.users.findByHandle(identifier.trim());
6581
+ if (user) ml.subject = user.id;
6582
+ ml.identifier = identifier.trim().toLowerCase();
6583
+ }
6584
+ /**
6585
+ * Send a magic link (recovery or sign-in) and pause until it is used. The
6586
+ * pause is persisted under the `magic-link` strategy — a fresh, hashed,
6587
+ * single-use handle that expires with the link (`magicLinkTtlMs`) — and the
6588
+ * `magic-link` outlet hands the token to the email outlet only. Known and
6589
+ * unknown identifiers take the same path and get the same answer; nothing is
6590
+ * sent for an unknown identifier, an account without a proven inbox, a
6591
+ * sign-in the account may not start (inactive, locked), or a repeat within
6592
+ * `mfa.pincodeResendTimeoutMs`. The click resumes here and moves on to the
6593
+ * purpose's verify step.
6594
+ */
6595
+ async magicLinkSend(ctx) {
6596
+ const ml = ctx.magicLink;
6597
+ if (!ml || ml.sentAt !== void 0) return void 0;
6598
+ await enforceRateLimit(SEND_RATE_LIMIT);
6599
+ const now = Date.now();
6600
+ ml.sentAt = now;
6601
+ ml.expiresAt = now + this.opts.magicLinkTtlMs;
6602
+ const address = await this.magicLinkAddress(ctx, ml);
6603
+ if (address) ml.address = address;
6604
+ const cooldownKey = sha256url(`${ml.purpose}|${ml.subject ?? ml.identifier ?? ""}`);
6605
+ const sends = await this.opts.lockoutShadowStore.hit(`${MAGIC_LINK_SEND_PREFIX}${cooldownKey}`, this.opts.mfa.pincodeResendTimeoutMs);
6606
+ const deliver = !!address && sends === 1;
6607
+ delete ml.identifier;
6608
+ if (ml.purpose === "login" && ctx.alternateCredentials?.magicLinkSameBrowser) ml.browser = this.bindMagicLinkBrowser();
6609
+ swapStrategy(MAGIC_LINK_STRATEGY);
6610
+ return {
6611
+ ...outlet(MAGIC_LINK_OUTLET, {
6612
+ target: deliver ? address : "",
6613
+ template: ml.purpose === "recovery" ? "recovery.magicLink" : "login.magicLink",
6614
+ context: {
6615
+ deliver,
6616
+ expiresAtMs: this.opts.magicLinkTtlMs
6617
+ }
6618
+ }),
6619
+ expires: ml.expiresAt
6620
+ };
6621
+ }
6622
+ /**
6623
+ * Where a magic link may go — an inbox the account proved, or `undefined`
6624
+ * (nothing is sent). Recovery with the typed identifier as destination (M1,
6625
+ * email channel) sends to the typed address, like the recovery code; every
6626
+ * other case sends to the account's proven inbox: `account.verifiedEmail`,
6627
+ * else a confirmed email MFA method — never an unproven address. The account
6628
+ * must be active; a sign-in link also needs it unlocked (a recovery link may
6629
+ * go to a locked account — self-service unlock). Override to change the
6630
+ * destination.
6631
+ */
6632
+ async magicLinkAddress(ctx, ml) {
6633
+ let user;
6634
+ try {
6635
+ user = ml.purpose === "login" ? await this.users.assertCanSignIn(ml.subject ?? UNKNOWN_ACCOUNT_ID) : await this.users.getUser(ml.subject ?? UNKNOWN_ACCOUNT_ID);
6636
+ } catch (err) {
6637
+ if (err instanceof UserAuthError) return void 0;
6638
+ throw err;
6639
+ }
6640
+ if (!ml.subject || !user.account.active) return void 0;
6641
+ if (ml.purpose === "recovery" && await this.recoveryDeliverySource(ctx) === "typed") {
6642
+ const typed = await this.recoveryPincodeTarget(ctx, "typed");
6643
+ return typed.channel === "email" && typed.address ? typed.address : void 0;
6644
+ }
6645
+ return user.account.verifiedEmail ?? user.mfa.methods.find((m) => m.name === "email" && m.confirmed)?.value;
6646
+ }
6647
+ /**
6648
+ * The landing step of a clicked link: "Continue as a•••@example.com". Opening
6649
+ * the link (or a mail scanner fetching it) only renders this step — the
6650
+ * pause stays on the link's own handle, so the link still works; it is used
6651
+ * up only when this form is submitted. The masked account lets the user see
6652
+ * which account the link signs into (a forwarded link would be someone
6653
+ * else's).
6654
+ */
6655
+ magicLinkConfirm(ctx) {
6656
+ const ml = ctx.magicLink;
6657
+ if (!ml?.sentAt || ml.confirmed) return void 0;
6658
+ const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.magicLinkConfirm);
6659
+ try {
6660
+ wf.resolveInput();
6661
+ } catch (err) {
6662
+ if (err instanceof StepRetriableError) err.expires = ml.expiresAt;
6663
+ throw err;
6664
+ }
6665
+ ml.confirmed = true;
6666
+ }
6667
+ /** Name of the cookie binding a sign-in link to the browser that asked for it. */
6668
+ magicLinkBrowserCookie() {
6669
+ return MAGIC_LINK_BROWSER_COOKIE;
6670
+ }
6671
+ /** Set the browser-binding cookie; returns the hash the link keeps. */
6672
+ bindMagicLinkBrowser() {
6673
+ const nonce = randomBytes(24).toString("base64url");
6674
+ useResponse(current()).setCookie(this.magicLinkBrowserCookie(), nonce, authzBindingCookieAttrs({
6675
+ secure: useAuth().options.cookie.secure,
6676
+ maxAgeSec: Math.ceil(this.opts.magicLinkTtlMs / 1e3)
6677
+ }));
6678
+ return sha256url(nonce);
6679
+ }
6680
+ /** Whether this request carries the browser-binding cookie the link was sent with. */
6681
+ sameMagicLinkBrowser(expected) {
6682
+ const cookie = useCookies(current()).getCookie(this.magicLinkBrowserCookie());
6683
+ if (!cookie) return false;
6684
+ return safeEqual(sha256url(cookie), expected);
6685
+ }
6686
+ /**
6687
+ * A used sign-in link: the FIRST factor only. Re-checks the account
6688
+ * (active, not locked), binds `ctx.subject` and leaves the second factor to
6689
+ * the MFA loop, exactly as after a password. Refuses a link of another
6690
+ * purpose, an expired one, and one sent for no account.
6691
+ */
6692
+ async magicLinkVerified(ctx) {
6693
+ const ml = this.usedMagicLink(ctx, "login");
6694
+ if (!ml) return void 0;
6695
+ if (!ml.subject || ml.browser && !this.sameMagicLinkBrowser(ml.browser)) {
6696
+ this.finishMagicLinkInvalid(ctx);
6697
+ return;
6698
+ }
6699
+ let user;
6700
+ try {
6701
+ user = await this.users.assertCanSignIn(ml.subject);
6702
+ } catch (err) {
6703
+ if (!(err instanceof UserAuthError)) throw err;
6704
+ this.finishMagicLinkInvalid(ctx);
6705
+ return;
6706
+ }
6707
+ ctx.subject = user.id;
6708
+ const guardsResult = this.resolveGuards(ctx);
6709
+ ctx.guards = guardsResult instanceof Promise ? await guardsResult : guardsResult;
6710
+ await this.bindSignedInUser(ctx, user);
6711
+ }
6712
+ /**
6713
+ * A used recovery link: proof of the inbox it went to, exactly like a
6714
+ * verified recovery code — `ctx.otp.verified` set, the inbox recorded as
6715
+ * the account's verified email, and the flow goes on to the new password.
6716
+ * Refuses a link of another purpose, an expired one, one sent for no
6717
+ * account, and one whose account is no longer active.
6718
+ */
6719
+ async recoveryLinkVerified(ctx) {
6720
+ const ml = this.usedMagicLink(ctx, "recovery");
6721
+ if (!ml) return void 0;
6722
+ let active = false;
6723
+ if (ml.subject && ml.address) try {
6724
+ active = (await this.users.getUser(ml.subject)).account.active;
6725
+ } catch (err) {
6726
+ if (!(err instanceof UserAuthError)) throw err;
6727
+ }
6728
+ if (!active || !ml.subject || !ml.address) {
6729
+ this.finishMagicLinkInvalid(ctx);
6730
+ return;
6731
+ }
6732
+ ctx.subject = ml.subject;
6733
+ const otp = ctx.otp ??= {};
6734
+ otp.verified = true;
6735
+ otp.deliveredTo = ml.address;
6736
+ otp.deliveredChannel = "email";
6737
+ await this.users.setVerifiedEmail(ml.subject, ml.address);
6738
+ }
6739
+ /**
6740
+ * The magic link this run was resumed through, checked for `purpose` and
6741
+ * expiry — or `undefined` after emitting the "invalid link" finish. Swaps
6742
+ * off the `magic-link` strategy first, so the link's token is never the
6743
+ * continuation (the next pause gets a fresh handle).
6744
+ */
6745
+ usedMagicLink(ctx, purpose) {
6746
+ const ml = ctx.magicLink;
6747
+ if (!ml?.sentAt) return void 0;
6748
+ swapStrategy("store");
6749
+ if (ml.purpose !== purpose || !ml.expiresAt || Date.now() > ml.expiresAt) {
6750
+ this.finishMagicLinkInvalid(ctx);
6751
+ return;
6752
+ }
6753
+ return ml;
6754
+ }
6755
+ /** The finish of a link that cannot be used (wrong purpose, expired, no account). */
6756
+ finishMagicLinkInvalid(ctx) {
6757
+ ctx.aborted = true;
6758
+ finishWf({ message: {
6759
+ level: "error",
6760
+ text: this.msg("AOOTH_MAGIC_LINK_INVALID")
6761
+ } });
6762
+ }
6763
+ /**
6764
+ * Recovery's `'choice'` delivery: the user picks a magic link or a one-time
6765
+ * code. Shown for known and unknown identifiers alike. A one-time code for
6766
+ * an unknown identifier runs the ghost OTP pause, like the default path.
6767
+ */
6768
+ async selectRecoveryMode(ctx) {
6769
+ const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.recoveryModeSelect);
6770
+ let mode;
6771
+ try {
6772
+ ({mode} = wf.resolveInput());
6773
+ } catch (err) {
6774
+ if (err instanceof StepRetriableError) throw this.stampRecoveryExpiry(err);
6775
+ throw err;
6776
+ }
6777
+ if (mode !== "magicLink" && mode !== "otp") throw this.throwPublic(ctx, wf, { errors: { mode: this.msg("AOOTH_CHOOSE_OPTION") } });
6778
+ await this.applyRecoveryMode(ctx, mode);
6779
+ }
5798
6780
  passkey(_ctx) {}
5799
6781
  /**
5800
6782
  * Verify the OAuth callback and resolve a user. Reaches here (instead of
@@ -5854,7 +6836,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
5854
6836
  finishWf({
5855
6837
  message: {
5856
6838
  level: "success",
5857
- text: this.msg("ACCOUNT_LINKED")
6839
+ text: this.msg("AOOTH_ACCOUNT_LINKED")
5858
6840
  },
5859
6841
  next: {
5860
6842
  trigger: "immediate",
@@ -6005,11 +6987,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
6005
6987
  * the confirmed channel vanished between resolve and dispatch (the caller
6006
6988
  * routes that to the safe generic terminal).
6007
6989
  */
6008
- async deliverPendingLinkPin(candidate, pending) {
6990
+ async deliverPendingLinkPin(candidate, pending, claimed) {
6009
6991
  const method = candidate.mfa.methods.find((m) => m.name === pending.otpChannel && m.confirmed);
6010
6992
  if (!method) return null;
6011
- const code = this.mintPin(pending, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
6012
- await this.dispatch({
6993
+ const deliver = claimed ?? await this.claimCodeSend(this.linkTarget(pending), pending.candidateUserId);
6994
+ const code = this.mintPin(pending, pending.candidateUserId);
6995
+ if (deliver) await this.dispatch({
6013
6996
  kind: "mfa-pincode",
6014
6997
  channel: pending.otpChannel,
6015
6998
  recipient: method.value,
@@ -6067,11 +7050,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
6067
7050
  }
6068
7051
  if (isOtp && action === "resend") {
6069
7052
  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);
7053
+ 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) }) });
7054
+ const sentTo = await this.deliverPendingLinkPin(candidate, pending, true);
6075
7055
  if (sentTo === null) {
6076
7056
  delete ctx.pendingLink;
6077
7057
  return this.finishOAuth(ctx, "needs-link");
@@ -6081,12 +7061,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
6081
7061
  }
6082
7062
  const input = wf.resolveInput();
6083
7063
  if (isOtp) {
6084
- const pinErr = this.verifyPin(pending, input.code);
7064
+ const pinErr = await this.verifyPin(pending, input.code, pending.candidateUserId, this.linkTarget(pending));
6085
7065
  if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
6086
7066
  } else try {
6087
7067
  await this.users.login(candidate.username, input.password ?? "", this.lockoutOverride(ctx));
6088
7068
  } catch (err) {
6089
- if (err instanceof UserAuthError && err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
7069
+ if (err instanceof UserAuthError && err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("AOOTH_ACCOUNT_LOCKED") });
6090
7070
  throw this.throwPublic(ctx, wf, { errors: { password: this.msg("INVALID_PASSWORD") } });
6091
7071
  }
6092
7072
  if (this.isAccountBlocked(candidate)) {
@@ -6132,8 +7112,9 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
6132
7112
  */
6133
7113
  inviteFlow() {}
6134
7114
  /**
6135
- * recovery.flow — OTP-via-email reset. `@Public()` on the body because
6136
- * anonymous users start recovery.
7115
+ * recovery.flow — reset by a one-time code or a magic link
7116
+ * (`resolveRecoveryDeliveryMode`). `@Public()` on the body because anonymous
7117
+ * users start recovery.
6137
7118
  */
6138
7119
  recoveryFlow() {}
6139
7120
  /**
@@ -6823,6 +7804,14 @@ __decorate([
6823
7804
  __decorateMetadata("design:paramtypes", [Object]),
6824
7805
  __decorateMetadata("design:returntype", Promise)
6825
7806
  ], AuthWorkflow.prototype, "checkPasswordUnchanged", null);
7807
+ __decorate([
7808
+ Step("check-can-sign-in"),
7809
+ Public(),
7810
+ __decorateParam(0, WorkflowParam("context")),
7811
+ __decorateMetadata("design:type", Function),
7812
+ __decorateMetadata("design:paramtypes", [Object]),
7813
+ __decorateMetadata("design:returntype", Promise)
7814
+ ], AuthWorkflow.prototype, "checkCanSignIn", null);
6826
7815
  __decorate([
6827
7816
  Step("record-login"),
6828
7817
  Public(),
@@ -6839,6 +7828,14 @@ __decorate([
6839
7828
  __decorateMetadata("design:paramtypes", [Object]),
6840
7829
  __decorateMetadata("design:returntype", Promise)
6841
7830
  ], AuthWorkflow.prototype, "recoveryLockCheck", null);
7831
+ __decorate([
7832
+ Step("auto-login-check"),
7833
+ Public(),
7834
+ __decorateParam(0, WorkflowParam("context")),
7835
+ __decorateMetadata("design:type", Function),
7836
+ __decorateMetadata("design:paramtypes", [Object]),
7837
+ __decorateMetadata("design:returntype", Promise)
7838
+ ], AuthWorkflow.prototype, "autoLoginCheck", null);
6842
7839
  __decorate([
6843
7840
  Step("after-invitation-accepted"),
6844
7841
  Public(),
@@ -6957,7 +7954,7 @@ __decorate([
6957
7954
  __decorateParam(0, WorkflowParam("context")),
6958
7955
  __decorateMetadata("design:type", Function),
6959
7956
  __decorateMetadata("design:paramtypes", [Object]),
6960
- __decorateMetadata("design:returntype", Object)
7957
+ __decorateMetadata("design:returntype", Promise)
6961
7958
  ], AuthWorkflow.prototype, "magicLinkRequest", null);
6962
7959
  __decorate([
6963
7960
  Step("magic-link-send"),
@@ -6965,16 +7962,40 @@ __decorate([
6965
7962
  __decorateParam(0, WorkflowParam("context")),
6966
7963
  __decorateMetadata("design:type", Function),
6967
7964
  __decorateMetadata("design:paramtypes", [Object]),
6968
- __decorateMetadata("design:returntype", Object)
7965
+ __decorateMetadata("design:returntype", Promise)
6969
7966
  ], AuthWorkflow.prototype, "magicLinkSend", null);
6970
7967
  __decorate([
6971
- Step("magic-link-verified"),
7968
+ Step("magic-link-confirm"),
6972
7969
  Public(),
6973
7970
  __decorateParam(0, WorkflowParam("context")),
6974
7971
  __decorateMetadata("design:type", Function),
6975
7972
  __decorateMetadata("design:paramtypes", [Object]),
6976
7973
  __decorateMetadata("design:returntype", Object)
7974
+ ], AuthWorkflow.prototype, "magicLinkConfirm", null);
7975
+ __decorate([
7976
+ Step("magic-link-verified"),
7977
+ Public(),
7978
+ __decorateParam(0, WorkflowParam("context")),
7979
+ __decorateMetadata("design:type", Function),
7980
+ __decorateMetadata("design:paramtypes", [Object]),
7981
+ __decorateMetadata("design:returntype", Promise)
6977
7982
  ], AuthWorkflow.prototype, "magicLinkVerified", null);
7983
+ __decorate([
7984
+ Step("recovery-link-verified"),
7985
+ Public(),
7986
+ __decorateParam(0, WorkflowParam("context")),
7987
+ __decorateMetadata("design:type", Function),
7988
+ __decorateMetadata("design:paramtypes", [Object]),
7989
+ __decorateMetadata("design:returntype", Promise)
7990
+ ], AuthWorkflow.prototype, "recoveryLinkVerified", null);
7991
+ __decorate([
7992
+ Step("select-recovery-mode"),
7993
+ Public(),
7994
+ __decorateParam(0, WorkflowParam("context")),
7995
+ __decorateMetadata("design:type", Function),
7996
+ __decorateMetadata("design:paramtypes", [Object]),
7997
+ __decorateMetadata("design:returntype", Promise)
7998
+ ], AuthWorkflow.prototype, "selectRecoveryMode", null);
6978
7999
  __decorate([
6979
8000
  Step("passkey"),
6980
8001
  Public(),
@@ -7010,7 +8031,19 @@ __decorate([
7010
8031
  },
7011
8032
  {
7012
8033
  id: "credentials",
7013
- condition: (ctx) => !ctx.idpInbound && !ctx.subject
8034
+ condition: (ctx) => !ctx.idpInbound && !ctx.subject && !ctx.magicLink
8035
+ },
8036
+ {
8037
+ condition: (ctx) => ctx.magicLink?.purpose === "login" && !ctx.subject,
8038
+ steps: [
8039
+ { id: "magic-link-request" },
8040
+ { id: "magic-link-send" },
8041
+ { id: "magic-link-confirm" },
8042
+ {
8043
+ id: "magic-link-verified",
8044
+ condition: (ctx) => !ctx.aborted
8045
+ }
8046
+ ]
7014
8047
  },
7015
8048
  {
7016
8049
  id: "prove-control",
@@ -7030,12 +8063,7 @@ __decorate([
7030
8063
  { break: (ctx) => !!ctx.aborted },
7031
8064
  {
7032
8065
  condition: () => false,
7033
- steps: [
7034
- { id: "magic-link-request" },
7035
- { id: "magic-link-send" },
7036
- { id: "magic-link-verified" },
7037
- { id: "passkey" }
7038
- ]
8066
+ steps: [{ id: "passkey" }]
7039
8067
  },
7040
8068
  {
7041
8069
  id: "ask/email",
@@ -7083,6 +8111,10 @@ __decorate([
7083
8111
  id: "check-password-unchanged",
7084
8112
  condition: (ctx) => ctx.passwordStamp !== void 0 && !ctx.passwordChanged
7085
8113
  },
8114
+ {
8115
+ id: "check-can-sign-in",
8116
+ condition: (ctx) => !!ctx.subject && !ctx.aborted
8117
+ },
7086
8118
  { break: (ctx) => !!ctx.aborted },
7087
8119
  {
7088
8120
  id: "record-login",
@@ -7184,6 +8216,10 @@ __decorate([
7184
8216
  id: "finalize-fresh-login",
7185
8217
  condition: (ctx) => !ctx.autoLogin
7186
8218
  },
8219
+ {
8220
+ id: "auto-login-check",
8221
+ condition: (ctx) => !!ctx.autoLogin
8222
+ },
7187
8223
  {
7188
8224
  id: "record-login",
7189
8225
  condition: (ctx) => !!ctx.autoLogin
@@ -7205,11 +8241,22 @@ __decorate([
7205
8241
  WorkflowSchema([
7206
8242
  { id: "init-recovery" },
7207
8243
  { id: "request" },
7208
- { break: (ctx) => !ctx.subject },
8244
+ {
8245
+ id: "select-recovery-mode",
8246
+ condition: (ctx) => ctx.recoveryDelivery === "choice"
8247
+ },
8248
+ {
8249
+ condition: (ctx) => ctx.recoveryDelivery === "magicLink",
8250
+ steps: [
8251
+ { id: "magic-link-send" },
8252
+ { id: "magic-link-confirm" },
8253
+ { id: "recovery-link-verified" }
8254
+ ]
8255
+ },
8256
+ { break: (ctx) => !!ctx.aborted || !ctx.subject && ctx.recoveryDelivery !== "otp" },
7209
8257
  { id: "prepare-post-reset" },
7210
8258
  { id: "prepare-recovery-alt-actions" },
7211
8259
  { id: "prepare-lockout" },
7212
- { id: "prepare-consents" },
7213
8260
  { id: "prepare-semantic-flags" },
7214
8261
  {
7215
8262
  while: (ctx) => !ctx.otp?.verified && !ctx.aborted,
@@ -7218,7 +8265,11 @@ __decorate([
7218
8265
  { break: (ctx) => !!ctx.aborted },
7219
8266
  {
7220
8267
  condition: (ctx) => !!ctx.otp?.verified,
7221
- steps: [{ id: "prepare-password-rules" }, { id: "create-password-form" }]
8268
+ steps: [
8269
+ { id: "prepare-consents" },
8270
+ { id: "prepare-password-rules" },
8271
+ { id: "create-password-form" }
8272
+ ]
7222
8273
  },
7223
8274
  { break: (ctx) => !!ctx.aborted },
7224
8275
  {
@@ -7240,6 +8291,10 @@ __decorate([
7240
8291
  id: "finalize-fresh-login",
7241
8292
  condition: (ctx) => !ctx.autoLogin
7242
8293
  },
8294
+ {
8295
+ id: "auto-login-check",
8296
+ condition: (ctx) => !!ctx.autoLogin
8297
+ },
7243
8298
  {
7244
8299
  id: "record-login",
7245
8300
  condition: (ctx) => !!ctx.autoLogin
@@ -7341,6 +8396,7 @@ __decorate([
7341
8396
  ...consentsPersistTailSchema,
7342
8397
  { id: "signup-extra-step" },
7343
8398
  { id: "after-signup" },
8399
+ { id: "auto-login-check" },
7344
8400
  { id: "record-login" },
7345
8401
  { id: "finalize-auto-login" }
7346
8402
  ]),
@@ -7383,12 +8439,16 @@ const ADD_MFA_WORKFLOW = "auth/add-mfa/flow";
7383
8439
  function inviteNotFound() {
7384
8440
  return aoothHttpError(404, "INVITE_NOT_FOUND");
7385
8441
  }
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
- }
8442
+ /**
8443
+ * Default rate limits of `POST /auth/refresh` (see `refresh()`), by policy id —
8444
+ * re-tune or switch one off with `rateLimitInterceptors({ policies })`.
8445
+ */
8446
+ const REFRESH_RATE_LIMITS = {
8447
+ /** Per client IP — bounds the token lookups any one caller can force. */
8448
+ "aooth.refresh": "150/5m",
8449
+ /** Per presented refresh token, from any IP — bounds re-presenting one token. */
8450
+ "aooth.refresh-token": "10/1m"
8451
+ };
7392
8452
  let AuthController = class AuthController {
7393
8453
  auth;
7394
8454
  users;
@@ -7414,13 +8474,13 @@ let AuthController = class AuthController {
7414
8474
  }
7415
8475
  async logout(body) {
7416
8476
  const auth = useAuth();
7417
- if (!auth.getAuthContext()) throw aoothHttpError(401, "NOT_AUTHENTICATED");
8477
+ if (!auth.getAuthContext()) throw aoothHttpError(401, "AOOTH_NOT_AUTHENTICATED");
7418
8478
  const sessionId = auth.getSessionId();
7419
8479
  if (sessionId) try {
7420
8480
  await this.auth.revokeSession(auth.getUserId(), sessionId);
7421
8481
  } catch {}
7422
8482
  const accessToken = auth.extractToken();
7423
- const refreshToken = resolveRefreshToken(auth, body);
8483
+ const refreshToken = resolveRefreshToken(auth.options, body);
7424
8484
  if (accessToken) try {
7425
8485
  await this.auth.revoke(accessToken);
7426
8486
  } catch {}
@@ -7430,9 +8490,17 @@ let AuthController = class AuthController {
7430
8490
  auth.clearCookies();
7431
8491
  return { ok: true };
7432
8492
  }
8493
+ /**
8494
+ * Rotate the access/refresh pair. Rate limited by two policies, enforced
8495
+ * when `rateLimitInterceptors` are installed ({@link REFRESH_RATE_LIMITS}):
8496
+ * `aooth.refresh` per client IP (checked before the auth guard, so a flood
8497
+ * of junk tokens costs no lookups), and `aooth.refresh-token` per presented
8498
+ * refresh token from any IP (a request without one skips it — the handler
8499
+ * answers 401).
8500
+ */
7433
8501
  async refresh(body) {
7434
8502
  const auth = useAuth();
7435
- const refreshToken = resolveRefreshToken(auth, body);
8503
+ const refreshToken = resolveRefreshToken(auth.options, body);
7436
8504
  if (!refreshToken) throw aoothHttpError(401, "MISSING_REFRESH_TOKEN");
7437
8505
  const fromBody = typeof body?.refreshToken === "string";
7438
8506
  let issue;
@@ -7449,7 +8517,7 @@ let AuthController = class AuthController {
7449
8517
  }
7450
8518
  status() {
7451
8519
  const auth = useAuth().getAuthContext();
7452
- if (!auth) throw aoothHttpError(401, "NOT_AUTHENTICATED");
8520
+ if (!auth) throw aoothHttpError(401, "AOOTH_NOT_AUTHENTICATED");
7453
8521
  return auth;
7454
8522
  }
7455
8523
  triggerWf() {}
@@ -7498,7 +8566,7 @@ let AuthController = class AuthController {
7498
8566
  */
7499
8567
  async invitePostRedemption(uid) {
7500
8568
  if (!this.invitePostRedemptionEnabled()) throw inviteNotFound();
7501
- if (!uid) throw aoothHttpError(400, "MISSING_UID");
8569
+ if (!uid) throw aoothHttpError(400, "AOOTH_MISSING_UID");
7502
8570
  if (!this.users) throw new HttpError$1(500, "UserService not wired — cannot resolve post-redemption state");
7503
8571
  let user;
7504
8572
  try {
@@ -7553,6 +8621,11 @@ __decorate([
7553
8621
  __decorate([
7554
8622
  Post("refresh"),
7555
8623
  Public(),
8624
+ RateLimit(REFRESH_RATE_LIMITS["aooth.refresh"], { id: "aooth.refresh" }),
8625
+ RateLimit(REFRESH_RATE_LIMITS["aooth.refresh-token"], {
8626
+ key: "refresh-token",
8627
+ id: "aooth.refresh-token"
8628
+ }),
7556
8629
  __decorateParam(0, Body()),
7557
8630
  __decorateMetadata("design:type", Function),
7558
8631
  __decorateMetadata("design:paramtypes", [Object]),
@@ -7594,7 +8667,7 @@ __decorate([
7594
8667
  __decorate([
7595
8668
  Get("invite/post-redemption"),
7596
8669
  Public(),
7597
- RateLimit("30/5m"),
8670
+ RateLimit("30/5m", { id: "aooth.invite-post-redemption" }),
7598
8671
  __decorateParam(0, Query("uid")),
7599
8672
  __decorateMetadata("design:type", Function),
7600
8673
  __decorateMetadata("design:paramtypes", [Object]),
@@ -7613,6 +8686,15 @@ let SessionEnricherProvider = class SessionEnricherProvider {
7613
8686
  }
7614
8687
  };
7615
8688
  SessionEnricherProvider = __decorate([Injectable()], SessionEnricherProvider);
8689
+ /**
8690
+ * `?kind=` as the `listSessions` filter: a comma list, values trimmed, empty
8691
+ * ones dropped (none left = the default browser-safe set). A comma list is
8692
+ * the list form — a repeated query key is refused by the HTTP layer.
8693
+ */
8694
+ function parseKindFilter(kind) {
8695
+ const kinds = kind?.split(",").map((k) => k.trim()).filter((k) => k !== "");
8696
+ return kinds?.length ? kinds : void 0;
8697
+ }
7616
8698
  let SessionsController = class SessionsController {
7617
8699
  auth;
7618
8700
  enricher;
@@ -7622,9 +8704,10 @@ let SessionsController = class SessionsController {
7622
8704
  }
7623
8705
  async listSessions(kind) {
7624
8706
  const auth = useAuth();
8707
+ const kinds = parseKindFilter(kind);
7625
8708
  const sessions = await this.auth.listSessions(auth.getUserId(), {
7626
8709
  enrich: (s) => this.enricher.enrich(s),
7627
- ...kind !== void 0 && { kind }
8710
+ ...kinds && { kind: kinds }
7628
8711
  });
7629
8712
  const current = auth.getSessionId();
7630
8713
  for (const s of sessions) s.current = s.sessionId === current;
@@ -7636,9 +8719,10 @@ let SessionsController = class SessionsController {
7636
8719
  * granting cross-user visibility.
7637
8720
  */
7638
8721
  async listSessionsOf(userId, kind) {
8722
+ const kinds = parseKindFilter(kind);
7639
8723
  return await this.auth.listSessions(userId, {
7640
8724
  enrich: (s) => this.enricher.enrich(s),
7641
- ...kind !== void 0 && { kind }
8725
+ ...kinds && { kind: kinds }
7642
8726
  });
7643
8727
  }
7644
8728
  async revokeSession(sessionId) {
@@ -7697,6 +8781,39 @@ SessionsController = __decorate([
7697
8781
  ArbacResource("auth.sessions"),
7698
8782
  __decorateMetadata("design:paramtypes", [typeof AuthCredential === "undefined" ? Object : AuthCredential, typeof SessionEnricherProvider === "undefined" ? Object : SessionEnricherProvider])
7699
8783
  ], SessionsController);
8784
+ // src/workflow/invite-peek.ts
8785
+ /** Id of the invite workflow (`AuthWorkflow`'s `@Workflow("auth/invite/start")`). */
8786
+ const INVITE_WORKFLOW = "auth/invite/start";
8787
+ /**
8788
+ * Read what an invite link (its `wfs` token) is for — the invited address,
8789
+ * the issuer, the roles and the link's expiry — WITHOUT consuming it, e.g. to
8790
+ * show "Ann invited you as an editor" on the invite page before the invitee
8791
+ * acts. Resolves the token through {@link WfTriggerProvider.peek}, then checks
8792
+ * it against the account: an invite that was replaced by a re-invite, accepted,
8793
+ * cancelled or that is not an invite link reads as `null`, the same as an
8794
+ * unknown or expired token.
8795
+ *
8796
+ * Mount it on your own route and rate-limit that route like invite
8797
+ * redemption — e.g. `@RateLimit("30/5m", { id: "app.invite-info" })`.
8798
+ */
8799
+ async function peekInvite(token, deps) {
8800
+ const state = await deps.trigger.peek(token);
8801
+ if (!state || normalizeWfId(state.schemaId) !== INVITE_WORKFLOW) return null;
8802
+ const ctx = state.context;
8803
+ const admin = ctx?.admin;
8804
+ if (!ctx?.subject || !ctx.email || !admin?.emailDispatched) return null;
8805
+ const user = await deps.users.findByIdentifier(ctx.subject);
8806
+ if (!user?.account?.pendingInvitation) return null;
8807
+ const current = user.account.inviteNonce;
8808
+ if (current != null && current !== admin.inviteNonce) return null;
8809
+ const expiresAt = state.meta?.[STATE_EXPIRES_KEY];
8810
+ return {
8811
+ email: ctx.email,
8812
+ ...admin.invitedBy && { invitedBy: admin.invitedBy },
8813
+ ...admin.roles && admin.roles.length > 0 && { roles: admin.roles },
8814
+ ...typeof expiresAt === "number" && { expiresAt }
8815
+ };
8816
+ }
7700
8817
  // src/oauth/oauth-tokens.ts
7701
8818
  /**
7702
8819
  * Explicit string DI token for the ABSTRACT `FederatedIdentityStore`.
@@ -7841,7 +8958,7 @@ let OAuthController = class OAuthController {
7841
8958
  try {
7842
8959
  return this.registry.require(providerId);
7843
8960
  } catch (err) {
7844
- if (err instanceof OAuthError && err.type === "UNKNOWN_PROVIDER") throw aoothHttpError(404, "UNKNOWN_PROVIDER", { provider: providerId });
8961
+ if (err instanceof OAuthError && err.type === "UNKNOWN_PROVIDER") throw aoothHttpError(404, "AOOTH_UNKNOWN_PROVIDER", { provider: providerId });
7845
8962
  throw err;
7846
8963
  }
7847
8964
  }
@@ -7896,14 +9013,26 @@ function toConnectedAccount(i) {
7896
9013
  provider: i.provider,
7897
9014
  subject: i.subject,
7898
9015
  linkedAt: i.linkedAt,
7899
- ...i.lastLoginAt !== void 0 && { lastLoginAt: i.lastLoginAt },
7900
- ...i.email !== void 0 && { email: i.email },
7901
- ...i.emailVerified !== void 0 && { emailVerified: i.emailVerified },
7902
- ...i.displayName !== void 0 && { displayName: i.displayName },
7903
- ...i.avatarUrl !== void 0 && { avatarUrl: i.avatarUrl }
9016
+ ...i.lastLoginAt != null && { lastLoginAt: i.lastLoginAt },
9017
+ ...i.email != null && { email: i.email },
9018
+ ...i.emailVerified != null && { emailVerified: i.emailVerified },
9019
+ ...i.displayName != null && { displayName: i.displayName },
9020
+ ...i.avatarUrl != null && { avatarUrl: i.avatarUrl }
7904
9021
  };
7905
9022
  }
7906
9023
  // src/authz/authorize.controller.ts
9024
+ /**
9025
+ * Default rate limits of the authorization server's public token endpoints, by
9026
+ * policy id — re-tune or switch one off with `rateLimitInterceptors({ policies })`.
9027
+ */
9028
+ const AUTHZ_RATE_LIMITS = {
9029
+ /** `POST /auth/token`, per client IP — every grant. */
9030
+ "aooth.token": "150/5m",
9031
+ /** `POST /auth/token` with `grant_type=refresh_token`, per presented refresh token, from any IP. */
9032
+ "aooth.token-refresh": "10/1m",
9033
+ /** `POST /auth/register` (dynamic client registration), per client IP. */
9034
+ "aooth.register": "20/1h"
9035
+ };
7907
9036
  /** Shared default claims resolver — stateless, so one instance is reused across requests. */
7908
9037
  const NOOP_OIDC_CLAIMS_RESOLVER = new NoopOidcClaimsResolver();
7909
9038
  let AuthorizeController = class AuthorizeController {
@@ -8019,6 +9148,13 @@ let AuthorizeController = class AuthorizeController {
8019
9148
  res.setHeader("Location", target);
8020
9149
  return "";
8021
9150
  }
9151
+ /**
9152
+ * Rate limited when `rateLimitInterceptors` are installed
9153
+ * ({@link AUTHZ_RATE_LIMITS}): `aooth.token` per client IP, and
9154
+ * `aooth.token-refresh` per presented `refresh_token` of a refresh grant.
9155
+ * Both are checked before the auth guard; over the limit the endpoint
9156
+ * answers the coded `429` (`RATE_LIMITED`, `Retry-After`).
9157
+ */
8022
9158
  async token(body) {
8023
9159
  if (body?.grant_type === "refresh_token") return await this.refreshTokenGrant(body);
8024
9160
  const res = useResponse(current());
@@ -8338,6 +9474,11 @@ __decorate([
8338
9474
  __decorate([
8339
9475
  Post("token"),
8340
9476
  Public(),
9477
+ RateLimit(AUTHZ_RATE_LIMITS["aooth.token"], { id: "aooth.token" }),
9478
+ RateLimit(AUTHZ_RATE_LIMITS["aooth.token-refresh"], {
9479
+ key: oauthRefreshTokenSubject,
9480
+ id: "aooth.token-refresh"
9481
+ }),
8341
9482
  __decorateParam(0, Body()),
8342
9483
  __decorateMetadata("design:type", Function),
8343
9484
  __decorateMetadata("design:paramtypes", [Object]),
@@ -8360,6 +9501,7 @@ __decorate([
8360
9501
  __decorate([
8361
9502
  Post("register"),
8362
9503
  Public(),
9504
+ RateLimit(AUTHZ_RATE_LIMITS["aooth.register"], { id: "aooth.register" }),
8363
9505
  __decorateParam(0, Body()),
8364
9506
  __decorateMetadata("design:type", Function),
8365
9507
  __decorateMetadata("design:paramtypes", [Object]),
@@ -8417,4 +9559,4 @@ function createAuthEmailOutlet(deps) {
8417
9559
  await deps.emailSender.send(event);
8418
9560
  });
8419
9561
  }
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 };
9562
+ 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, peekInvite, rateLimitInterceptors, renderAoothMessage, resolveAoothMessage, resolveOAuthRedirect, setRateLimitSubject, stripReservedUserKeys, useAuth, useRateLimit, userAuthErrorInterceptor, userAuthErrorToHttp };