@aooth/auth-moost 0.2.1 → 0.2.3

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,5 +1,5 @@
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-DDn6m5rP.mjs";
2
- import { Controller, HandlerPaths, Inherit, Inject, InjectMoostLogger, Injectable, Intercept, MoostInit, Optional, Param, Resolve, TInterceptorPriority, defineAfterInterceptor, defineBeforeInterceptor, getMoostMate, useControllerContext, useLogger } from "moost";
1
+ import { C as RemoveMfaConfirmForm, D as StepUpConfirmForm, E as SignupForm, O as TermsBumpForm, T as SetPasswordForm, _ as PasswordReauthForm, a as ConcurrencyLimitForm, b as ProveControlOtpForm, c as EnrollConfirmForm, d as InviteChooseUsernameForm, f as InviteForm, g as MfaCodeForm, h as ManageMfaForm, i as ChangePasswordForm, l as EnrollPickMethodForm, n as AskPhoneForm, o as EmailIdentifierForm, p as LoginCredentialsForm, r as AuthorizeConsentForm, s as EnrollAddressForm, t as AskEmailForm, u as EnrollTotpQrForm, v as PincodeForm, w as Select2faForm, y as ProveControlForm } from "./forms-C_VNxSDn.mjs";
2
+ import { Controller, HandlerPaths, Inherit, Inject, InjectMoostLogger, Injectable, Intercept, MoostInit, Optional, Param, Resolve, TInterceptorPriority, defineAfterInterceptor, defineBeforeInterceptor, defineErrorInterceptor, getMoostMate, useControllerContext, useLogger } from "moost";
3
3
  import { AuthCredential, AuthError, RateLimitStoreMemory, RateLimitStoreMemory as RateLimitStoreMemory$1, RateLimiter, RateLimiter as RateLimiter$1, generateMagicLinkToken, generateOpaqueToken, parseRateLimitRule, pickGoverning } from "@aooth/auth";
4
4
  import { current, defineWook, eventTypeKey, key } from "@wooksjs/event-core";
5
5
  import { HttpError, resolveForwarded, useAuthorization, useCookies, useHeaders, useRequest, useResponse, useUrlParams } from "@wooksjs/event-http";
@@ -11,15 +11,14 @@ import { createAsHttpOutlet, finishWf, handleAsOutletRequest, useAtscriptWf } fr
11
11
  import { EncapsulatedStateStrategy, MoostWf, Step, StepRetriableError, StepTTL, Workflow, WorkflowParam, WorkflowSchema, createEmailOutlet, outlet, outletEmail, swapStrategy, useWfFinished, useWfState } from "@moostjs/event-wf";
12
12
  import { FederatedLoginService, OAuthError, OAuthProviderRegistry, generateRandomState, pkceChallengeFor } from "@aooth/idp";
13
13
  import { ClientRegistrationError, DynamicClientRegistration, NoopOidcClaimsResolver, buildAuthorizationServerMetadata, buildAuthorizationServerMetadata as buildAuthorizationServerMetadata$1, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, canonicalizeIssuer as canonicalizeIssuer$1, tokenPolicyToIssueOptions } from "@aooth/auth/authz";
14
- //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
14
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/decorate.js
15
15
  function __decorate(decorators, target, key, desc) {
16
16
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17
17
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
18
18
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
19
19
  return c > 3 && r && Object.defineProperty(target, key, r), r;
20
20
  }
21
- //#endregion
22
- //#region src/consent.store.ts
21
+ // src/consent.store.ts
23
22
  let ConsentStore = class ConsentStore {
24
23
  /**
25
24
  * Returns descriptors for general-purpose consents this user still needs to
@@ -60,8 +59,7 @@ let ConsentStore = class ConsentStore {
60
59
  async recordOtpChannelConsent(_username, _channel, _target, _disclosure) {}
61
60
  };
62
61
  ConsentStore = __decorate([Injectable()], ConsentStore);
63
- //#endregion
64
- //#region src/auth.config.ts
62
+ // src/auth.config.ts
65
63
  /**
66
64
  * Resolve `AuthOptions` to its `ResolvedAuthOptions` form, applying the same
67
65
  * defaults the legacy `MoostAuthConfig` constructor did. Pure — call once per
@@ -97,8 +95,7 @@ function resolveAuthOptions(opts = {}) {
97
95
  exposeTokensInBody: opts.exposeTokensInBody ?? !enableCookie
98
96
  };
99
97
  }
100
- //#endregion
101
- //#region src/auth.composables.ts
98
+ // src/auth.composables.ts
102
99
  const authContextKey = key("auth.context");
103
100
  const authCredentialKey = key("auth.credential");
104
101
  /**
@@ -271,8 +268,7 @@ function setAuthContext(ctx, value) {
271
268
  function setAuthCredential(ctx, value) {
272
269
  ctx.set(authCredentialKey, value);
273
270
  }
274
- //#endregion
275
- //#region src/auth.route.ts
271
+ // src/auth.route.ts
276
272
  /**
277
273
  * Normalize a router path into a value usable as a cookie `Path` attribute:
278
274
  * a single leading slash, no doubled slashes, and no trailing slash (except
@@ -286,8 +282,7 @@ let RefreshCookiePathHolder = class RefreshCookiePathHolder {
286
282
  path;
287
283
  };
288
284
  RefreshCookiePathHolder = __decorate([Injectable()], RefreshCookiePathHolder);
289
- //#endregion
290
- //#region src/auth.guard.ts
285
+ // src/auth.guard.ts
291
286
  /**
292
287
  * `GUARD`-priority interceptor factory that authenticates incoming requests.
293
288
  *
@@ -356,13 +351,11 @@ function authGuardInterceptor(opts) {
356
351
  function AuthGuarded(opts) {
357
352
  return Intercept(authGuardInterceptor(opts));
358
353
  }
359
- //#endregion
360
- //#region src/auth.mate.ts
354
+ // src/auth.mate.ts
361
355
  function getAuthMate() {
362
356
  return getMoostMate();
363
357
  }
364
- //#endregion
365
- //#region src/auth.decorator.ts
358
+ // src/auth.decorator.ts
366
359
  /**
367
360
  * Marks a route or controller as fully public — opts out of BOTH
368
361
  * authentication (auth-moost's bearer guard) AND authorization
@@ -392,8 +385,7 @@ const Public = () => {
392
385
  * does not own a user profile type.
393
386
  */
394
387
  const UserId = () => Resolve(() => useAuth().getUserId());
395
- //#endregion
396
- //#region src/rate-limit/composables.ts
388
+ // src/rate-limit/composables.ts
397
389
  /**
398
390
  * Internal: the governing decision for this event (across every policy
399
391
  * evaluated so far), written by `rateLimitInterceptors`.
@@ -431,8 +423,7 @@ function getRateLimitSubject(kind, ctx = current()) {
431
423
  function useRateLimit(ctx = current()) {
432
424
  return { decision: ctx.has(rateLimitDecisionKey) ? ctx.get(rateLimitDecisionKey) : null };
433
425
  }
434
- //#endregion
435
- //#region src/rate-limit/interceptor.ts
426
+ // src/rate-limit/interceptor.ts
436
427
  /**
437
428
  * Global interceptor PAIR enforcing `@RateLimit` metadata (RL.spec.md §5.2)
438
429
  * — register with spread:
@@ -463,7 +454,9 @@ function useRateLimit(ctx = current()) {
463
454
  *
464
455
  * On rejection: draft `RateLimit-*` headers + `Retry-After` are written to
465
456
  * the accumulated response (they survive the throw — wooks renders the error
466
- * onto the same `HttpResponse`), then `HttpError(429, message)` is thrown.
457
+ * onto the same `HttpResponse`), then an `HttpError(429)` is thrown whose body
458
+ * carries the rendered `message`, `code: "RATE_LIMITED"` and
459
+ * `params: { policy, limit, window, retryAfter }` (seconds) — translate by code.
467
460
  */
468
461
  function rateLimitInterceptors(opts) {
469
462
  const defaultRules = opts?.rules?.map((r) => parseRateLimitRule(r));
@@ -542,7 +535,11 @@ function rateLimitInterceptors(opts) {
542
535
  }
543
536
  if (!decision.allowed) {
544
537
  response.setHeader("retry-after", String(Math.ceil(decision.resetAfterMs / 1e3)));
545
- throw new HttpError(429, decision.message ?? "Too many requests");
538
+ throw new HttpError(429, {
539
+ message: decision.message ?? "Too many requests",
540
+ code: decision.code ?? "RATE_LIMITED",
541
+ ...decision.params && { params: decision.params }
542
+ });
546
543
  }
547
544
  };
548
545
  return [defineBeforeInterceptor(() => evaluate("pre"), TInterceptorPriority.BEFORE_GUARD), defineBeforeInterceptor(() => evaluate("post"), TInterceptorPriority.AFTER_GUARD)];
@@ -569,13 +566,11 @@ function clientIp(trustProxy, ctx) {
569
566
  const req = useRequest(ctx);
570
567
  return trustProxy ? resolveForwarded(req.raw, trustOneHop).ip : req.getIp();
571
568
  }
572
- //#endregion
573
- //#region src/rate-limit/mate.ts
569
+ // src/rate-limit/mate.ts
574
570
  function getRateLimitMate() {
575
571
  return getMoostMate();
576
572
  }
577
- //#endregion
578
- //#region src/rate-limit/decorator.ts
573
+ // src/rate-limit/decorator.ts
579
574
  function RateLimit(...args) {
580
575
  const mate = getRateLimitMate();
581
576
  if (args.length === 1 && args[0] === false) return mate.decorate("rateLimitDisabled", true);
@@ -610,8 +605,7 @@ function RateLimited(opts) {
610
605
  interceptPost(target, key, descriptor);
611
606
  });
612
607
  }
613
- //#endregion
614
- //#region src/workflow/invite-outlet.ts
608
+ // src/workflow/invite-outlet.ts
615
609
  /** Name of the outlet `AuthWorkflow` pauses on for `inviteDelivery: 'deliver' | 'return-link'`. */
616
610
  const INVITE_OUTLET = "invite";
617
611
  const pendingInviteLinkKey = key("aooth.invite.pendingLink");
@@ -647,13 +641,18 @@ function createInviteOutlet() {
647
641
  }
648
642
  };
649
643
  }
650
- //#endregion
651
- //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateMetadata.js
644
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/decorateMetadata.js
652
645
  function __decorateMetadata(k, v) {
653
646
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
654
647
  }
655
- //#endregion
656
- //#region src/wf-trigger/provider.ts
648
+ // src/wf-trigger/provider.ts
649
+ const HOOK_NAMES = [
650
+ "around",
651
+ "beforePersist",
652
+ "renderEnvelope",
653
+ "restoreOnError",
654
+ "maxRestores"
655
+ ];
657
656
  /**
658
657
  * Derive the exact 32-byte key the encapsulated wf-state strategy requires from
659
658
  * an arbitrary-length app secret.
@@ -691,18 +690,38 @@ function notAllowed(id) {
691
690
  * Wrap a strategy so a resume is checked against the allow list BEFORE the
692
691
  * state is consumed: the state is peeked (`retrieve`), refused with 403 when
693
692
  * its workflow is not allowed on this route (the token stays usable on its
694
- * own route), and only then consumed.
693
+ * own route), and only then consumed. The optional expiry-reporting methods
694
+ * (`persistEntry` / `consumeEntry`, which `restoreOnError` needs) are kept
695
+ * when the wrapped strategy has them.
695
696
  */
696
697
  function guardStrategy(strategy, permits) {
697
- return {
698
+ const check = async (token) => {
699
+ const peeked = await strategy.retrieve(token);
700
+ if (peeked && !permits(peeked.schemaId)) throw notAllowed(peeked.schemaId);
701
+ };
702
+ const guarded = {
698
703
  persist: (state, options, overrides) => strategy.persist(state, options, overrides),
699
704
  retrieve: (token) => strategy.retrieve(token),
700
705
  consume: async (token) => {
701
- const peeked = await strategy.retrieve(token);
702
- if (peeked && !permits(peeked.schemaId)) throw notAllowed(peeked.schemaId);
706
+ await check(token);
703
707
  return strategy.consume(token);
704
708
  }
705
709
  };
710
+ if (strategy.persistEntry) guarded.persistEntry = (state, options, overrides) => strategy.persistEntry(state, options, overrides);
711
+ if (strategy.consumeEntry) guarded.consumeEntry = async (token) => {
712
+ await check(token);
713
+ return strategy.consumeEntry(token);
714
+ };
715
+ return guarded;
716
+ }
717
+ /**
718
+ * Run one trigger attempt. The invite outlet reads the link callback from a
719
+ * slot reserved on the HTTP event; it is reserved per run, so a run that
720
+ * `around` retries starts clean.
721
+ */
722
+ function runTrigger(run) {
723
+ reservePendingInviteLink();
724
+ return run();
706
725
  }
707
726
  let WfTriggerProvider = class WfTriggerProvider {
708
727
  wf;
@@ -750,6 +769,21 @@ let WfTriggerProvider = class WfTriggerProvider {
750
769
  defaultTtl: this.wfStateEncapsulatedTtlMs()
751
770
  });
752
771
  }
772
+ /**
773
+ * App-wide workflow-trigger hooks ({@link WfTriggerHooks}): `around`,
774
+ * `beforePersist`, `renderEnvelope`, `restoreOnError` / `maxRestores`.
775
+ * Default: none. A route's `@WfTrigger({...})` option of the same name
776
+ * replaces the hook returned here. Called once per trigger request.
777
+ *
778
+ * ```ts
779
+ * protected override triggerHooks(): WfTriggerHooks {
780
+ * return { around: (run) => db.transaction(run) };
781
+ * }
782
+ * ```
783
+ */
784
+ triggerHooks() {
785
+ return {};
786
+ }
753
787
  cachedState;
754
788
  /** Named strategy registry: every wf starts on `encapsulated` (default); a step calls swapStrategy('store') to move durable. Built lazily so subclass overrides (storeStrategy/wfStateSecret) are in effect. */
755
789
  stateRegistry() {
@@ -766,7 +800,8 @@ let WfTriggerProvider = class WfTriggerProvider {
766
800
  * Handle one trigger request. `allow` lists the workflow ids this route may
767
801
  * START and RESUME (matched without a leading `/`); omitted = unrestricted,
768
802
  * `[]` = deny all. A state token minted for a workflow outside the list is
769
- * refused with 403 before it is consumed.
803
+ * refused with 403 before it is consumed. Trigger hooks set in `opts`
804
+ * replace the {@link triggerHooks} of the same name.
770
805
  */
771
806
  async handle(opts = {}) {
772
807
  const wfApp = this.wf.getWfApp();
@@ -795,8 +830,16 @@ let WfTriggerProvider = class WfTriggerProvider {
795
830
  });
796
831
  }
797
832
  };
798
- reservePendingInviteLink();
833
+ const base = this.triggerHooks();
834
+ const hooks = {};
835
+ for (const name of HOOK_NAMES) {
836
+ const value = opts[name] ?? base[name];
837
+ if (value !== void 0) hooks[name] = value;
838
+ }
839
+ const around = opts.around ?? base.around;
799
840
  return handleAsOutletRequest({
841
+ ...hooks,
842
+ around: around ? (run) => around(() => runTrigger(run)) : runTrigger,
800
843
  state: stateConfig,
801
844
  outlets: this.outlets,
802
845
  token: opts.token ?? this.token
@@ -804,8 +847,7 @@ let WfTriggerProvider = class WfTriggerProvider {
804
847
  }
805
848
  };
806
849
  WfTriggerProvider = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [typeof MoostWf === "undefined" ? Object : MoostWf, typeof AuthCredential === "undefined" ? Object : AuthCredential])], WfTriggerProvider);
807
- //#endregion
808
- //#region src/wf-trigger/decorator.ts
850
+ // src/wf-trigger/decorator.ts
809
851
  /**
810
852
  * Method decorator that turns a handler into a workflow trigger.
811
853
  *
@@ -814,6 +856,11 @@ WfTriggerProvider = __decorate([Injectable(), __decorateMetadata("design:paramty
814
856
  * that need to short-circuit (e.g. emit a custom error response) just return a
815
857
  * non-undefined value from the overridden handler and the trigger is skipped.
816
858
  *
859
+ * `opts` also takes the workflow-trigger hooks (`around`, `beforePersist`,
860
+ * `renderEnvelope`, `restoreOnError`, `maxRestores` — see `WfTriggerHooks`);
861
+ * each one set here replaces the provider's `triggerHooks()` hook of the
862
+ * same name for this route.
863
+ *
817
864
  * The single `useControllerContext().instantiate(...)` call is the one
818
865
  * documented escape hatch: interceptors are functions, not classes, so there's
819
866
  * no ctor to inject into. Every class still uses constructor injection.
@@ -859,8 +906,7 @@ async function buildOAuthAuthorizeRequest(registry, provider, input) {
859
906
  })
860
907
  };
861
908
  }
862
- //#endregion
863
- //#region src/oauth/oauth-csrf.ts
909
+ // src/oauth/oauth-csrf.ts
864
910
  /**
865
911
  * Name of the double-submit anti-CSRF cookie set at `/:provider/start` and
866
912
  * verified in `oauth-exchange`. Holds the signed-state `random`; the callback
@@ -902,8 +948,7 @@ function safeEqual(a, b) {
902
948
  if (ab.length !== bb.length) return false;
903
949
  return timingSafeEqual(ab, bb);
904
950
  }
905
- //#endregion
906
- //#region src/authz/authz-binding.ts
951
+ // src/authz/authz-binding.ts
907
952
  /**
908
953
  * Name of the double-submit cookie that binds an in-flight authorization
909
954
  * request to the browser that started it. Set at `GET /auth/authorize` (holding
@@ -937,8 +982,7 @@ function authzBindingCookieAttrs(opts) {
937
982
  maxAgeSec: opts.maxAgeSec
938
983
  });
939
984
  }
940
- //#endregion
941
- //#region src/authz/authz-redirect.ts
985
+ // src/authz/authz-redirect.ts
942
986
  /**
943
987
  * Build the client redirect URL for an authorization-server result (RFC 6749
944
988
  * §4.1.2 / §4.1.2.1): append the result params (`code` on success, `error` on
@@ -952,8 +996,7 @@ function authzRedirectUrl(redirectUri, params) {
952
996
  for (const [key, value] of Object.entries(params)) if (value !== void 0) url.searchParams.set(key, value);
953
997
  return url.toString();
954
998
  }
955
- //#endregion
956
- //#region src/oauth/oauth-redirect.ts
999
+ // src/oauth/oauth-redirect.ts
957
1000
  /**
958
1001
  * Open-redirect defense for the post-login `redirect` carried across the OAuth
959
1002
  * bounce (RFC IDP.md §7). The provider round-trips whatever target the SPA
@@ -988,8 +1031,7 @@ function isSafeRelativeRedirect(target) {
988
1031
  function resolveOAuthRedirect(requested, fallback) {
989
1032
  return isSafeRelativeRedirect(requested) ? requested : fallback;
990
1033
  }
991
- //#endregion
992
- //#region src/authz/authz-tokens.ts
1034
+ // src/authz/authz-tokens.ts
993
1035
  /**
994
1036
  * Explicit string DI tokens for the ABSTRACT authorization-server stores
995
1037
  * ({@link import("@aooth/auth/authz").PendingAuthorizationStore},
@@ -1034,15 +1076,13 @@ const CLIENT_REDIRECT_POLICY_TOKEN = "aooth:ClientRedirectPolicy";
1034
1076
  * backs the `DynamicClientPolicy` composed into the redirect policy.
1035
1077
  */
1036
1078
  const DYNAMIC_CLIENT_STORE_TOKEN = "aooth:DynamicClientStore";
1037
- //#endregion
1038
- //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
1079
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/decorateParam.js
1039
1080
  function __decorateParam(paramIndex, decorator) {
1040
1081
  return function(target, key) {
1041
1082
  decorator(target, key, paramIndex);
1042
1083
  };
1043
1084
  }
1044
- //#endregion
1045
- //#region src/authz/authorize-runtime.ts
1085
+ // src/authz/authorize-runtime.ts
1046
1086
  let AuthorizeRuntime = class AuthorizeRuntime {
1047
1087
  pending;
1048
1088
  codes;
@@ -1057,8 +1097,7 @@ AuthorizeRuntime = __decorate([
1057
1097
  __decorateParam(1, Inject(AUTH_CODE_STORE_TOKEN)),
1058
1098
  __decorateMetadata("design:paramtypes", [Object, Object])
1059
1099
  ], AuthorizeRuntime);
1060
- //#endregion
1061
- //#region src/oauth/oauth-runtime.ts
1100
+ // src/oauth/oauth-runtime.ts
1062
1101
  let OAuthRuntime = class OAuthRuntime {
1063
1102
  registry;
1064
1103
  federated;
@@ -1068,8 +1107,83 @@ let OAuthRuntime = class OAuthRuntime {
1068
1107
  }
1069
1108
  };
1070
1109
  OAuthRuntime = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [typeof OAuthProviderRegistry === "undefined" ? Object : OAuthProviderRegistry, typeof FederatedLoginService === "undefined" ? Object : FederatedLoginService])], OAuthRuntime);
1071
- //#endregion
1072
- //#region src/workflow/auth-messages.ts
1110
+ // src/user-errors.ts
1111
+ const STATUS = {
1112
+ NOT_FOUND: 404,
1113
+ ALREADY_EXISTS: 409,
1114
+ CAS_EXHAUSTED: 409,
1115
+ INVALID_CREDENTIALS: 400,
1116
+ MFA_INVALID: 400,
1117
+ MFA_NOT_CONFIGURED: 400,
1118
+ PASSWORDS_MISMATCH: 400,
1119
+ PASSWORD_IN_HISTORY: 400,
1120
+ POLICY_VIOLATION: 422,
1121
+ INACTIVE: 403,
1122
+ LOCKED: 403,
1123
+ MFA_REQUIRED: 403
1124
+ };
1125
+ const FIELD = {
1126
+ INVALID_CREDENTIALS: "currentPassword",
1127
+ POLICY_VIOLATION: "newPassword",
1128
+ PASSWORD_IN_HISTORY: "newPassword",
1129
+ PASSWORDS_MISMATCH: "confirmPassword"
1130
+ };
1131
+ /** The password-form field an error belongs to (shared with the bundled password forms). */
1132
+ function userAuthErrorField(type) {
1133
+ return FIELD[type];
1134
+ }
1135
+ /**
1136
+ * Map a `UserAuthError` (thrown by `UserService`) to an `HttpError` whose body
1137
+ * carries `code` (the error type), the message and — for password errors —
1138
+ * the form `field` it belongs to (named as in the bundled password forms):
1139
+ *
1140
+ * | type | status | field |
1141
+ * |---|---|---|
1142
+ * | `NOT_FOUND` | 404 | |
1143
+ * | `ALREADY_EXISTS`, `CAS_EXHAUSTED` | 409 | |
1144
+ * | `INVALID_CREDENTIALS` | 400 | `currentPassword` |
1145
+ * | `PASSWORD_IN_HISTORY` | 400 | `newPassword` |
1146
+ * | `POLICY_VIOLATION` (+ `params.policies`) | 422 | `newPassword` |
1147
+ * | `PASSWORDS_MISMATCH` | 400 | `confirmPassword` |
1148
+ * | `MFA_INVALID`, `MFA_NOT_CONFIGURED` | 400 | |
1149
+ * | `INACTIVE`, `LOCKED`, `MFA_REQUIRED` | 403 | |
1150
+ *
1151
+ * For routes such as an admin "set password" endpoint. Do not use it on a
1152
+ * sign-in endpoint: distinct answers for unknown, inactive and locked accounts
1153
+ * let a caller enumerate accounts (the bundled login workflow answers them
1154
+ * uniformly).
1155
+ */
1156
+ function userAuthErrorToHttp(err) {
1157
+ const field = userAuthErrorField(err.type);
1158
+ const policies = err.type === "POLICY_VIOLATION" ? err.details?.policies : void 0;
1159
+ return new HttpError(STATUS[err.type], {
1160
+ message: err.message,
1161
+ code: err.type,
1162
+ ...policies !== void 0 && { params: { policies } },
1163
+ ...field && { field }
1164
+ });
1165
+ }
1166
+ /**
1167
+ * Error interceptor answering every `UserAuthError` a handler throws with
1168
+ * {@link userAuthErrorToHttp}; other errors pass through. Attach it per
1169
+ * controller (or per handler) where `UserService` errors should become 4xx
1170
+ * instead of 500 — typically admin and self-service routes:
1171
+ *
1172
+ * ```ts
1173
+ * @Controller("admin/users")
1174
+ * @Intercept(userAuthErrorInterceptor)
1175
+ * export class AdminUsersController {}
1176
+ * ```
1177
+ *
1178
+ * Don't install it globally: a custom sign-in or recovery handler calling
1179
+ * `login()` / `verifyMfa()` would then answer unknown, inactive and locked
1180
+ * accounts with distinct 404 / 403 codes — account enumeration, defeating
1181
+ * `lockoutDisclosure: 'uniform'`.
1182
+ */
1183
+ const userAuthErrorInterceptor = defineErrorInterceptor((error, reply) => {
1184
+ if (error instanceof UserAuthError) reply(userAuthErrorToHttp(error));
1185
+ }, TInterceptorPriority.CATCH_ERROR);
1186
+ // src/workflow/auth-messages.ts
1073
1187
  /**
1074
1188
  * Code-keyed catalogue of every user-facing text `AuthWorkflow` produces —
1075
1189
  * form errors, banners, finish envelopes and button labels. Templates are
@@ -1141,8 +1255,7 @@ function resolveAoothMessage(code, params = {}, messages) {
1141
1255
  } else if (messages?.[code] !== void 0) return renderAoothMessage(messages[code], params);
1142
1256
  return renderAoothMessage(AOOTH_MESSAGES[code], params);
1143
1257
  }
1144
- //#endregion
1145
- //#region src/workflow/auth-workflow.schemas.ts
1258
+ // src/workflow/auth-workflow.schemas.ts
1146
1259
  /**
1147
1260
  * Canonical OTP send-then-check pair. Used by:
1148
1261
  * - Login's MFA-loop SMS/email challenge sub-branch (the outer MFA while provides iteration)
@@ -1312,8 +1425,7 @@ const consentsPersistTailSchema = [{
1312
1425
  id: "persist-consents",
1313
1426
  condition: (ctx) => (ctx.consents?.pending?.length ?? 0) > 0 && !!ctx.consents?.decidedAt
1314
1427
  }];
1315
- //#endregion
1316
- //#region src/workflow/auth-workflow.ts
1428
+ // src/workflow/auth-workflow.ts
1317
1429
  /**
1318
1430
  * Unified `AuthWorkflow` — single concrete class with three `@Workflow`
1319
1431
  * methods (`loginFlow`, `inviteFlow`, `recoveryFlow`) replacing the prior
@@ -1383,7 +1495,7 @@ const warnedOnce = {
1383
1495
  crossIssuerReuse: false
1384
1496
  };
1385
1497
  /** Sliding lifetime of a shadow failure counter (and of a shadow "permanent" lock). */
1386
- const SHADOW_TTL_MS = 720 * 60 * 6e4;
1498
+ const SHADOW_TTL_MS = 2592e6;
1387
1499
  /** Key prefix of an active shadow lock (kept longest by the default store). */
1388
1500
  const SHADOW_LOCK_PREFIX = "shadow-lock:";
1389
1501
  /** Cap of the default (process-wide, in-memory) shadow-lockout store. */
@@ -1399,7 +1511,7 @@ function defaultShadowStore() {
1399
1511
  function mergeAuthWorkflowOpts(opts) {
1400
1512
  const deviceTrust = {
1401
1513
  cookieName: "aooth_trusted_device",
1402
- ttlMs: 1440 * 6e4,
1514
+ ttlMs: 864e5,
1403
1515
  bindsTo: "cookie",
1404
1516
  ...opts.deviceTrust
1405
1517
  };
@@ -1416,17 +1528,17 @@ function mergeAuthWorkflowOpts(opts) {
1416
1528
  lockoutShadowStore: opts.lockoutShadowStore ?? defaultShadowStore(),
1417
1529
  mfa: {
1418
1530
  pincodeLength: opts.mfa?.pincodeLength ?? 6,
1419
- pincodeTtlMs: opts.mfa?.pincodeTtlMs ?? 300 * 1e3,
1531
+ pincodeTtlMs: opts.mfa?.pincodeTtlMs ?? 3e5,
1420
1532
  pincodeResendTimeoutMs: opts.mfa?.pincodeResendTimeoutMs ?? 6e4,
1421
1533
  pincodeMaxAttempts: opts.mfa?.pincodeMaxAttempts ?? 5
1422
1534
  },
1423
- recoveryStateTtlMs: opts.recoveryStateTtlMs ?? 3600 * 1e3,
1535
+ recoveryStateTtlMs: opts.recoveryStateTtlMs ?? 36e5,
1424
1536
  loginUrl: opts.loginUrl ?? "/login",
1425
1537
  totpIssuer: opts.totpIssuer ?? "aooth",
1426
1538
  deviceTrust,
1427
1539
  deviceRecognition: {
1428
1540
  cookieName: opts.deviceRecognition?.cookieName ?? `${deviceTrust.cookieName}_seen`,
1429
- ttlMs: opts.deviceRecognition?.ttlMs ?? 4320 * 60 * 6e4,
1541
+ ttlMs: opts.deviceRecognition?.ttlMs ?? 15552e6,
1430
1542
  maxDevices: opts.deviceRecognition?.maxDevices ?? SEEN_DEVICES_DEFAULT_CAP
1431
1543
  },
1432
1544
  forms: {
@@ -1571,7 +1683,7 @@ const ALT_HANDLED = Symbol("ALT_HANDLED");
1571
1683
  * industry-standard invite-link window (Slack/GitHub/Atlassian). Override by
1572
1684
  * re-decorating the step in a subclass.
1573
1685
  */
1574
- const INVITE_LINK_TTL_MS = 10080 * 60 * 1e3;
1686
+ const INVITE_LINK_TTL_MS = 6048e5;
1575
1687
  /** One canonical form of a chosen username: Unicode NFKC, surrounding whitespace trimmed. */
1576
1688
  function normalizeUsername(raw) {
1577
1689
  return String(raw).normalize("NFKC").trim();
@@ -2616,7 +2728,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
2616
2728
  try {
2617
2729
  return await op();
2618
2730
  } catch (err) {
2619
- if (err instanceof UserAuthError && err.type === "CAS_EXHAUSTED") throw new HttpError$1(409, err.message);
2731
+ if (err instanceof UserAuthError && err.type === "CAS_EXHAUSTED") throw userAuthErrorToHttp(err);
2620
2732
  throw err;
2621
2733
  }
2622
2734
  }
@@ -3113,11 +3225,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3113
3225
  */
3114
3226
  async handleCredentialsAlt(action, typedUsername, alt, authzHandle) {
3115
3227
  if (action === "forgotPassword" && alt.forgotPassword) {
3228
+ const url = this.resolveRecoveryUrl(typedUsername, alt);
3116
3229
  finishWf({ next: {
3117
3230
  trigger: "immediate",
3118
3231
  action: {
3119
3232
  type: "redirect",
3120
- target: this.resolveRecoveryUrl(typedUsername, alt),
3233
+ target: url,
3121
3234
  reason: "forgot-password"
3122
3235
  }
3123
3236
  } });
@@ -3734,6 +3847,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3734
3847
  const copy = await this.resolveSetPasswordCopy(ctx);
3735
3848
  if (copy.heading !== void 0) password.heading = copy.heading;
3736
3849
  if (copy.intro !== void 0) password.intro = copy.intro;
3850
+ const user = await this.refusePasswordFormReplay(ctx);
3737
3851
  const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.setPassword);
3738
3852
  let input;
3739
3853
  try {
@@ -3743,7 +3857,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3743
3857
  throw err;
3744
3858
  }
3745
3859
  if (input.newPassword !== input.confirmPassword) throw this.throwPublic(ctx, wf, { errors: { confirmPassword: this.msg("PASSWORDS_DO_NOT_MATCH") } });
3746
- if (ctx.accept) await this.assertInviteStillOpen(ctx);
3860
+ if (ctx.accept && !user?.account?.pendingInvitation) throw this.httpError(410, "INVITE_ALREADY_ACCEPTED");
3747
3861
  try {
3748
3862
  await this.users.setPassword(ctx.subject, input.newPassword);
3749
3863
  } catch (err) {
@@ -3754,6 +3868,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3754
3868
  ctx.isPasswordInitial = false;
3755
3869
  ctx.isPasswordExpired = false;
3756
3870
  ctx.passwordChanged = true;
3871
+ delete ctx.passwordFormStamp;
3757
3872
  ctx.newPasswordRequired = false;
3758
3873
  delete password.changeReason;
3759
3874
  delete password.heading;
@@ -3805,6 +3920,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3805
3920
  */
3806
3921
  async changePasswordForm(ctx) {
3807
3922
  this.requireSubject(ctx);
3923
+ await this.refusePasswordFormReplay(ctx);
3808
3924
  const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.changePassword);
3809
3925
  const input = wf.resolveInput();
3810
3926
  if (input.newPassword !== input.confirmPassword) throw this.throwPublic(ctx, wf, { errors: { confirmPassword: this.msg("PASSWORDS_DO_NOT_MATCH") } });
@@ -3812,11 +3928,35 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
3812
3928
  await this.users.changePassword(ctx.subject, input.currentPassword, input.newPassword, input.confirmPassword);
3813
3929
  } catch (err) {
3814
3930
  if (err instanceof UserAuthError) {
3815
- const field = err.type === "INVALID_CREDENTIALS" ? "currentPassword" : err.type === "PASSWORDS_MISMATCH" ? "confirmPassword" : "newPassword";
3931
+ const field = userAuthErrorField(err.type) ?? "newPassword";
3816
3932
  throw this.throwPublic(ctx, wf, { errors: { [field]: err.message } });
3817
3933
  }
3818
3934
  throw err;
3819
3935
  }
3936
+ delete ctx.passwordFormStamp;
3937
+ }
3938
+ /**
3939
+ * Refuse a password form whose account password changed after the form was
3940
+ * first reached: the first visit stamps `password.lastChanged`
3941
+ * (`ctx.passwordFormStamp`); a later visit that finds another value is a
3942
+ * replay of an already-used form — a single-use token put back by the
3943
+ * trigger's `restoreOnError` after a later failure, or a re-submitted
3944
+ * encapsulated token — and answers 410 `PASSWORD_CHANGED_SIGN_IN_AGAIN`
3945
+ * instead of changing the password again. Returns the account row; on an
3946
+ * invite accept it is read through {@link currentInviteRow}, so a cancelled
3947
+ * or superseded invite answers 410. A deleted account returns `null` and is
3948
+ * not checked: the step's own password write then answers it as a form error.
3949
+ */
3950
+ async refusePasswordFormReplay(ctx) {
3951
+ const user = ctx.accept ? await this.currentInviteRow(ctx) : await this.users.getUser(ctx.subject).catch((err) => {
3952
+ if (err instanceof UserAuthError && err.type === "NOT_FOUND") return null;
3953
+ throw err;
3954
+ });
3955
+ if (!user) return null;
3956
+ const current = user.password.lastChanged ?? 0;
3957
+ if (ctx.passwordFormStamp === void 0) ctx.passwordFormStamp = current;
3958
+ else if (ctx.passwordFormStamp !== current) throw this.httpError(410, "PASSWORD_CHANGED_SIGN_IN_AGAIN");
3959
+ return user;
3820
3960
  }
3821
3961
  /**
3822
3962
  * Change-password terminal — sign the current device in on a FRESH session
@@ -4497,7 +4637,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4497
4637
  const input = wf.resolveInput();
4498
4638
  this.requireSubject(ctx);
4499
4639
  try {
4500
- await this.users.verifyMfa(ctx.subject, input.code, void 0, this.lockoutOverride(ctx));
4640
+ await this.withStoreErrorTranslation(() => this.users.verifyMfa(ctx.subject, input.code, void 0, this.lockoutOverride(ctx)));
4501
4641
  (ctx.otp ??= {}).verified = true;
4502
4642
  (ctx.session ??= {}).riskStepUpEvaluated = false;
4503
4643
  if (ctx.deviceTrust?.enabled && ctx.deviceTrust?.optIn) (ctx.trust ??= {}).rememberDevice = Boolean(input.rememberDevice);
@@ -4510,7 +4650,6 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
4510
4650
  if (err.details?.lockEnds !== void 0) throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
4511
4651
  throw this.throwPublic(ctx, wf, { errors: { code: this.msg("INVALID_CODE") } });
4512
4652
  }
4513
- if (err.type === "CAS_EXHAUSTED") throw new HttpError$1(409, err.message);
4514
4653
  }
4515
4654
  throw err;
4516
4655
  }
@@ -7034,8 +7173,7 @@ AuthWorkflow = _AuthWorkflow = __decorate([
7034
7173
  typeof ConsentStore === "undefined" ? Object : ConsentStore
7035
7174
  ])
7036
7175
  ], AuthWorkflow);
7037
- //#endregion
7038
- //#region src/auth.controller.ts
7176
+ // src/auth.controller.ts
7039
7177
  /** Workflows allowed by the bundled `/auth/trigger` endpoint. Subclasses override `triggerWf()` to extend. */
7040
7178
  const DEFAULT_AUTH_WORKFLOWS = [
7041
7179
  "auth/login/flow",
@@ -7283,8 +7421,7 @@ AuthController = __decorate([
7283
7421
  __decorateParam(1, Optional()),
7284
7422
  __decorateMetadata("design:paramtypes", [typeof AuthCredential === "undefined" ? Object : AuthCredential, typeof UserService === "undefined" ? Object : UserService])
7285
7423
  ], AuthController);
7286
- //#endregion
7287
- //#region src/sessions.controller.ts
7424
+ // src/sessions.controller.ts
7288
7425
  let SessionEnricherProvider = class SessionEnricherProvider {
7289
7426
  enrich(session) {
7290
7427
  return session;
@@ -7375,8 +7512,7 @@ SessionsController = __decorate([
7375
7512
  ArbacResource("auth.sessions"),
7376
7513
  __decorateMetadata("design:paramtypes", [typeof AuthCredential === "undefined" ? Object : AuthCredential, typeof SessionEnricherProvider === "undefined" ? Object : SessionEnricherProvider])
7377
7514
  ], SessionsController);
7378
- //#endregion
7379
- //#region src/oauth/oauth-tokens.ts
7515
+ // src/oauth/oauth-tokens.ts
7380
7516
  /**
7381
7517
  * Explicit string DI token for the ABSTRACT `FederatedIdentityStore`.
7382
7518
  *
@@ -7398,8 +7534,7 @@ SessionsController = __decorate([
7398
7534
  * ```
7399
7535
  */
7400
7536
  const FEDERATED_IDENTITY_STORE_TOKEN = "aooth:FederatedIdentityStore";
7401
- //#endregion
7402
- //#region src/oauth/oauth.controller.ts
7537
+ // src/oauth/oauth.controller.ts
7403
7538
  let OAuthController = class OAuthController {
7404
7539
  registry;
7405
7540
  auth;
@@ -7583,8 +7718,7 @@ function toConnectedAccount(i) {
7583
7718
  ...i.avatarUrl !== void 0 && { avatarUrl: i.avatarUrl }
7584
7719
  };
7585
7720
  }
7586
- //#endregion
7587
- //#region src/authz/authorize.controller.ts
7721
+ // src/authz/authorize.controller.ts
7588
7722
  /** Shared default claims resolver — stateless, so one instance is reused across requests. */
7589
7723
  const NOOP_OIDC_CLAIMS_RESOLVER = new NoopOidcClaimsResolver();
7590
7724
  let AuthorizeController = class AuthorizeController {
@@ -8069,8 +8203,7 @@ AuthorizeController = __decorate([
8069
8203
  function expiresInSeconds(expiresAt) {
8070
8204
  return Math.max(0, Math.floor((expiresAt - Date.now()) / 1e3));
8071
8205
  }
8072
- //#endregion
8073
- //#region src/workflows/auth-email-outlet.ts
8206
+ // src/workflows/auth-email-outlet.ts
8074
8207
  /**
8075
8208
  * Build the email outlet that delivers magic links via the consumer's
8076
8209
  * `EmailSender`. Single-use: pass the same instance into one
@@ -8097,5 +8230,4 @@ function createAuthEmailOutlet(deps) {
8097
8230
  await deps.emailSender.send(event);
8098
8231
  });
8099
8232
  }
8100
- //#endregion
8101
- export { ADD_MFA_WORKFLOW, AOOTH_MESSAGES, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, AuthController, AuthGuarded, AuthWorkflow, AuthorizeController, AuthorizeRuntime, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, FEDERATED_IDENTITY_STORE_TOKEN, INVITE_OUTLET, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, Public, RESERVED_USER_KEYS, RateLimit, RateLimitStoreMemory, RateLimited, RateLimiter, SessionEnricherProvider, SessionsController, UserId, WfTrigger, WfTriggerProvider, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, createInviteOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, getRateLimitMate, getRateLimitSubject, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, renderAoothMessage, resolveAoothMessage, resolveOAuthRedirect, setRateLimitSubject, stripReservedUserKeys, useAuth, useRateLimit };
8233
+ export { ADD_MFA_WORKFLOW, AOOTH_MESSAGES, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, AuthController, AuthGuarded, AuthWorkflow, AuthorizeController, AuthorizeRuntime, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, FEDERATED_IDENTITY_STORE_TOKEN, INVITE_OUTLET, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, Public, RESERVED_USER_KEYS, RateLimit, RateLimitStoreMemory, RateLimited, RateLimiter, SessionEnricherProvider, SessionsController, UserId, WfTrigger, WfTriggerProvider, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, createInviteOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, getRateLimitMate, getRateLimitSubject, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, renderAoothMessage, resolveAoothMessage, resolveOAuthRedirect, setRateLimitSubject, stripReservedUserKeys, useAuth, useRateLimit, userAuthErrorInterceptor, userAuthErrorToHttp };