@aooth/auth-moost 0.1.32 → 0.1.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +149 -2
- package/dist/index.mjs +161 -2
- package/package.json +9 -9
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Mate, TConsoleBase, TInterceptorDef, TMateParamMeta, TMoostMetadata } from "moost";
|
|
2
|
-
import { AuthContext, AuthContext as AuthContext$1, AuthCredential, AuthEmailEvent, AuthEmailKind, AuthEmailKind as AuthEmailKind$1, AuthSmsEvent, AuthSmsKind, BuildMagicLinkUrl, BuildMagicLinkUrl as BuildMagicLinkUrl$1, CredentialMetadata, EmailSender, EmailSender as EmailSender$1, EnrichedSession, EnrichedSession as EnrichedSession$1, IssueResult, IssueResult as IssueResult$1, SessionEnricher, SessionEnricher as SessionEnricher$1, SessionInfo, SessionInfo as SessionInfo$1, SmsSender, generateMagicLinkToken } from "@aooth/auth";
|
|
2
|
+
import { AuthContext, AuthContext as AuthContext$1, AuthCredential, AuthEmailEvent, AuthEmailKind, AuthEmailKind as AuthEmailKind$1, AuthSmsEvent, AuthSmsKind, BuildMagicLinkUrl, BuildMagicLinkUrl as BuildMagicLinkUrl$1, CredentialMetadata, EmailSender, EmailSender as EmailSender$1, EnrichedSession, EnrichedSession as EnrichedSession$1, IssueResult, IssueResult as IssueResult$1, RateLimitDecision, RateLimitDecision as RateLimitDecision$1, RateLimitRule, RateLimitRule as RateLimitRule$1, RateLimitRuleInput, RateLimitRuleInput as RateLimitRuleInput$1, RateLimitStore, RateLimitStoreMemory, RateLimiter, RateLimiter as RateLimiter$1, RateLimiterOptions, SessionEnricher, SessionEnricher as SessionEnricher$1, SessionInfo, SessionInfo as SessionInfo$1, SmsSender, generateMagicLinkToken } from "@aooth/auth";
|
|
3
|
+
import { EventContext } from "@wooksjs/event-core";
|
|
3
4
|
import { TCookieAttributesInput } from "@wooksjs/event-http";
|
|
4
5
|
import { FederatedIdentityStore, FederatedProfileSnapshot, MfaMethod, TransferablePolicy, TrustedDeviceRecord, UserCredentials, UserService } from "@aooth/user";
|
|
5
6
|
import { FinishWfOpts, WfFinished, useAtscriptWf } from "@atscript/moost-wf";
|
|
@@ -623,6 +624,152 @@ declare class WfTriggerProvider {
|
|
|
623
624
|
}): Promise<unknown>;
|
|
624
625
|
}
|
|
625
626
|
//#endregion
|
|
627
|
+
//#region src/rate-limit/mate.d.ts
|
|
628
|
+
/**
|
|
629
|
+
* Caller-identity strategy for a rate-limited route (RL.spec.md §5.3):
|
|
630
|
+
* - `'ip'` — client IP (the public-endpoint mode; honors `trustProxy`)
|
|
631
|
+
* - `'user'` / `'auto'` — authenticated user id, falling back to IP for
|
|
632
|
+
* anonymous callers (both spellings share one behavior; `'auto'` reads
|
|
633
|
+
* better on mixed public/authed routes)
|
|
634
|
+
* - custom function — runs inside the event context, so any composable is
|
|
635
|
+
* usable (tenant id, API key, `userId + ip`, …)
|
|
636
|
+
*/
|
|
637
|
+
type RateLimitKeyStrategy = "ip" | "user" | "auto" | (() => string | Promise<string>);
|
|
638
|
+
/** Trailing options object accepted by `@RateLimit(...rules, opts)`. */
|
|
639
|
+
interface RateLimitDecoratorOptions {
|
|
640
|
+
/** Overrides the interceptor-level default key strategy for this route. */
|
|
641
|
+
key?: RateLimitKeyStrategy;
|
|
642
|
+
/** Default 429 message template for rules without an inline `| message`. */
|
|
643
|
+
message?: string;
|
|
644
|
+
/**
|
|
645
|
+
* Bucket id — handlers sharing an id share counters. Default scope is
|
|
646
|
+
* `<ControllerClass>.<methodName>` (per-handler isolation).
|
|
647
|
+
*/
|
|
648
|
+
id?: string;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Rate-limit metadata written by `@RateLimit()` and read by
|
|
652
|
+
* `rateLimitInterceptors`. Merged into `TMoostMetadata` so other moost-aware
|
|
653
|
+
* tooling sees it.
|
|
654
|
+
*/
|
|
655
|
+
interface TRateLimitMeta {
|
|
656
|
+
/** Rules normalized at decoration time — bad grammar fails at boot. */
|
|
657
|
+
rateLimitRules?: RateLimitRule$1[];
|
|
658
|
+
rateLimitOptions?: RateLimitDecoratorOptions;
|
|
659
|
+
/** `@RateLimit(false)` — opt this route out of interceptor-level default rules. */
|
|
660
|
+
rateLimitDisabled?: boolean;
|
|
661
|
+
}
|
|
662
|
+
declare module "moost" {
|
|
663
|
+
interface TMoostMetadata extends TRateLimitMeta {}
|
|
664
|
+
}
|
|
665
|
+
type RateLimitMate = Mate<TMoostMetadata & {
|
|
666
|
+
params: TMateParamMeta[];
|
|
667
|
+
}, TMoostMetadata & {
|
|
668
|
+
params: TMateParamMeta[];
|
|
669
|
+
}>;
|
|
670
|
+
declare function getRateLimitMate(): RateLimitMate;
|
|
671
|
+
//#endregion
|
|
672
|
+
//#region src/rate-limit/interceptor.d.ts
|
|
673
|
+
interface RateLimitInterceptorOptions {
|
|
674
|
+
/**
|
|
675
|
+
* The shared limiter (wire your `RateLimitStoreRedis` here). When omitted,
|
|
676
|
+
* a memory-store `RateLimiter` is created ONCE per factory call — stable
|
|
677
|
+
* across requests, but single-process and private to this interceptor
|
|
678
|
+
* pair. Pass an explicit limiter for anything beyond zero-config dev.
|
|
679
|
+
*/
|
|
680
|
+
limiter?: RateLimiter$1;
|
|
681
|
+
/**
|
|
682
|
+
* App-wide default rules applied to EVERY http route without its own
|
|
683
|
+
* `@RateLimit(...)` metadata. Opt out per-route with `@RateLimit(false)`.
|
|
684
|
+
*/
|
|
685
|
+
rules?: RateLimitRuleInput$1[];
|
|
686
|
+
/** Default key strategy for routes whose `@RateLimit` doesn't set one. Default: `'ip'`. */
|
|
687
|
+
key?: RateLimitKeyStrategy;
|
|
688
|
+
/** Trust `x-forwarded-for` for the client IP (behind a proxy). Default: `false`. */
|
|
689
|
+
trustProxy?: boolean;
|
|
690
|
+
/** Emit draft `RateLimit-*` headers on every response of a limited route. Default: `true`. */
|
|
691
|
+
headers?: boolean;
|
|
692
|
+
/** App-wide default 429 message template. */
|
|
693
|
+
message?: string;
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Global interceptor PAIR enforcing `@RateLimit` metadata (RL.spec.md §5.2)
|
|
697
|
+
* — register with spread:
|
|
698
|
+
*
|
|
699
|
+
* ```ts
|
|
700
|
+
* app.applyGlobalInterceptors(
|
|
701
|
+
* authGuardInterceptor({ ... }),
|
|
702
|
+
* ...rateLimitInterceptors({ limiter, trustProxy: true }),
|
|
703
|
+
* )
|
|
704
|
+
* ```
|
|
705
|
+
*
|
|
706
|
+
* Two phases, because the primary target is public endpoints and
|
|
707
|
+
* `authGuardInterceptor` is NOT free there — with any `Authorization`
|
|
708
|
+
* header present it runs full credential validation before tolerating the
|
|
709
|
+
* failure on `@Public()` routes:
|
|
710
|
+
*
|
|
711
|
+
* - `BEFORE_GUARD` phase owns routes whose effective key strategy is
|
|
712
|
+
* `'ip'` or a custom resolver — floods are rejected before any
|
|
713
|
+
* token/credential work.
|
|
714
|
+
* - `AFTER_GUARD` phase owns `'user'` / `'auto'` keyed routes — those need
|
|
715
|
+
* the auth context `useAuth()` reads, and by definition target
|
|
716
|
+
* authenticated traffic where the guard must run anyway.
|
|
717
|
+
*
|
|
718
|
+
* Ownership is static per route (from metadata/options), so exactly one
|
|
719
|
+
* phase evaluates each event; the decision event-slot additionally guards
|
|
720
|
+
* against double counting when the pair is also attached per-controller
|
|
721
|
+
* (see {@link RateLimited}).
|
|
722
|
+
*
|
|
723
|
+
* On rejection: draft `RateLimit-*` headers + `Retry-After` are written to
|
|
724
|
+
* the accumulated response (they survive the throw — wooks renders the error
|
|
725
|
+
* onto the same `HttpResponse`), then `HttpError(429, message)` is thrown.
|
|
726
|
+
*/
|
|
727
|
+
declare function rateLimitInterceptors(opts?: RateLimitInterceptorOptions): TInterceptorDef[];
|
|
728
|
+
//#endregion
|
|
729
|
+
//#region src/rate-limit/decorator.d.ts
|
|
730
|
+
/**
|
|
731
|
+
* Declares rate-limit rules for a controller method (or every method of a
|
|
732
|
+
* controller, when applied at class level — method-level metadata replaces
|
|
733
|
+
* class-level). Metadata-only: enforcement happens in the globally registered
|
|
734
|
+
* `rateLimitInterceptors(...)` (RL.spec.md §5) or a per-controller
|
|
735
|
+
* {@link RateLimited}.
|
|
736
|
+
*
|
|
737
|
+
* ```ts
|
|
738
|
+
* RateLimit('6/5m | Too many login attempts, please wait {{delta}}')
|
|
739
|
+
* RateLimit('1/1s', '30/1m') // stacked windows, one budget each
|
|
740
|
+
* RateLimit('100/1h', { key: 'user' }) // per-user budget on an authed route
|
|
741
|
+
* RateLimit(false) // opt out of interceptor-level default rules
|
|
742
|
+
* ```
|
|
743
|
+
*
|
|
744
|
+
* Rules are parsed eagerly, so a bad rule string throws at decoration
|
|
745
|
+
* (boot) time, not per request.
|
|
746
|
+
*/
|
|
747
|
+
declare function RateLimit(disabled: false): ClassDecorator & MethodDecorator;
|
|
748
|
+
declare function RateLimit(...rulesAndOpts: [RateLimitRuleInput$1, ...Array<RateLimitRuleInput$1 | RateLimitDecoratorOptions>]): ClassDecorator & MethodDecorator;
|
|
749
|
+
/**
|
|
750
|
+
* Decorator-factory sugar for attaching the `rateLimitInterceptors(opts)`
|
|
751
|
+
* PAIR to a specific controller or method instead of globally — the
|
|
752
|
+
* `AuthGuarded` counterpart. Attaching the pair (not one phase) matters:
|
|
753
|
+
* dropping the pre-guard def loses flood protection for ip-keyed routes,
|
|
754
|
+
* dropping the post-guard def silently disables `key: 'user'` routes.
|
|
755
|
+
*/
|
|
756
|
+
declare function RateLimited(opts?: RateLimitInterceptorOptions): ClassDecorator & MethodDecorator;
|
|
757
|
+
//#endregion
|
|
758
|
+
//#region src/rate-limit/composables.d.ts
|
|
759
|
+
interface RateLimitBindings {
|
|
760
|
+
/**
|
|
761
|
+
* The decision the interceptor computed for this event, or `null` when the
|
|
762
|
+
* route has no rules (or the interceptors are not installed).
|
|
763
|
+
*/
|
|
764
|
+
decision: RateLimitDecision$1 | null;
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Read the current event's rate-limit state. A plain function (not a cached
|
|
768
|
+
* wook) — it's a single slot read, and workflow child events inherit the
|
|
769
|
+
* HTTP parent's slot transparently.
|
|
770
|
+
*/
|
|
771
|
+
declare function useRateLimit(ctx?: EventContext): RateLimitBindings;
|
|
772
|
+
//#endregion
|
|
626
773
|
//#region src/oauth/oauth.controller.d.ts
|
|
627
774
|
/**
|
|
628
775
|
* REST surface for federated-login ACCOUNT MANAGEMENT (OAuth2 / OIDC), RFC
|
|
@@ -3915,4 +4062,4 @@ interface AuditEmitter {
|
|
|
3915
4062
|
emit(event: AuditEvent): Promise<void> | void;
|
|
3916
4063
|
}
|
|
3917
4064
|
//#endregion
|
|
3918
|
-
export { ADD_MFA_WORKFLOW, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, type AuditEmitter, type AuditEvent, type AuthBindings, type AuthContext, AuthController, type AuthDeliveryPayload, type AuthEmailEvent, type AuthEmailKind, type AuthEmailOutletDeps, AuthGuarded, type AuthLoginResponse, type AuthLogoutBody, type AuthOkResponse, type AuthOptions, type AuthRefreshBody, type AuthSmsEvent, type AuthSmsKind, type AuthWfCompletionState, type AuthWfConsentsState, type AuthWfCtx, type AuthWfMfaEnrollState, type AuthWfOAuthState, type AuthWfPasswordUiState, type AuthWfPincodeUiState, AuthWorkflow, type AuthWorkflowOpts, type AuthorizationServerMetadata, AuthorizeController, AuthorizeRuntime, type BuildAuthorizationServerMetadataOptions, type BuildMagicLinkUrl, type BuildProtectedResourceMetadataOptions, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, type ConcurrencyLimitOptions, type ConnectedAccount, type ConsentDescriptor, type ConsentDescriptorLike, type ConsentEvent, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, type DynamicClientRegistrationOptions, type EmailSender, type EnrichedSession, FEDERATED_IDENTITY_STORE_TOKEN, type IssueResult, type LoginRedirect, type MfaSummary, type MfaTransport, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, type ProtectedResourceMetadata, Public, RESERVED_USER_KEYS, type ResolvedAuthCookieConfig, type ResolvedAuthOptions, type ResolvedAuthWorkflowOpts, type SessionEnricher, SessionEnricherProvider, type SessionInfo, SessionsController, type SmsSender, type SsoProvider, type TAuthMeta, UserId, WfTrigger, type WfTriggerOpts, WfTriggerProvider, type WwwAuthenticateBearerChallengeOptions, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, resolveOAuthRedirect, stripReservedUserKeys, useAuth };
|
|
4065
|
+
export { ADD_MFA_WORKFLOW, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, type AuditEmitter, type AuditEvent, type AuthBindings, type AuthContext, AuthController, type AuthDeliveryPayload, type AuthEmailEvent, type AuthEmailKind, type AuthEmailOutletDeps, AuthGuarded, type AuthLoginResponse, type AuthLogoutBody, type AuthOkResponse, type AuthOptions, type AuthRefreshBody, type AuthSmsEvent, type AuthSmsKind, type AuthWfCompletionState, type AuthWfConsentsState, type AuthWfCtx, type AuthWfMfaEnrollState, type AuthWfOAuthState, type AuthWfPasswordUiState, type AuthWfPincodeUiState, AuthWorkflow, type AuthWorkflowOpts, type AuthorizationServerMetadata, AuthorizeController, AuthorizeRuntime, type BuildAuthorizationServerMetadataOptions, type BuildMagicLinkUrl, type BuildProtectedResourceMetadataOptions, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, type ConcurrencyLimitOptions, type ConnectedAccount, type ConsentDescriptor, type ConsentDescriptorLike, type ConsentEvent, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, type DynamicClientRegistrationOptions, type EmailSender, type EnrichedSession, FEDERATED_IDENTITY_STORE_TOKEN, type IssueResult, type LoginRedirect, type MfaSummary, type MfaTransport, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, type ProtectedResourceMetadata, Public, RESERVED_USER_KEYS, RateLimit, type RateLimitBindings, type RateLimitDecision, type RateLimitDecoratorOptions, type RateLimitInterceptorOptions, type RateLimitKeyStrategy, type RateLimitRule, type RateLimitRuleInput, type RateLimitStore, RateLimitStoreMemory, RateLimited, RateLimiter, type RateLimiterOptions, type ResolvedAuthCookieConfig, type ResolvedAuthOptions, type ResolvedAuthWorkflowOpts, type SessionEnricher, SessionEnricherProvider, type SessionInfo, SessionsController, type SmsSender, type SsoProvider, type TAuthMeta, type TRateLimitMeta, UserId, WfTrigger, type WfTriggerOpts, WfTriggerProvider, type WwwAuthenticateBearerChallengeOptions, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, getRateLimitMate, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, resolveOAuthRedirect, stripReservedUserKeys, useAuth, useRateLimit };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { C as Select2faForm, D as TermsBumpForm, E as StepUpConfirmForm, S as RemoveMfaConfirmForm, T as SignupForm, _ as PincodeForm, a as ConcurrencyLimitForm, c as EnrollConfirmForm, d as InviteForm, f as LoginCredentialsForm, g as PasswordReauthForm, h as MfaCodeForm, i as ChangePasswordForm, l as EnrollPickMethodForm, m as ManageMfaForm, n as AskPhoneForm, o as EmailIdentifierForm, r as AuthorizeConsentForm, s as EnrollAddressForm, t as AskEmailForm, u as EnrollTotpQrForm, v as ProveControlForm, w as SetPasswordForm, y as ProveControlOtpForm } from "./forms-xaBNc5Ng.mjs";
|
|
2
2
|
import { Controller, HandlerPaths, Inherit, Inject, InjectMoostLogger, Injectable, Intercept, MoostInit, Optional, Param, Resolve, TInterceptorPriority, defineAfterInterceptor, defineBeforeInterceptor, getMoostMate, useControllerContext, useLogger } from "moost";
|
|
3
|
-
import { AuthCredential, AuthError, generateMagicLinkToken } from "@aooth/auth";
|
|
3
|
+
import { AuthCredential, AuthError, RateLimitStoreMemory, RateLimiter, RateLimiter as RateLimiter$1, generateMagicLinkToken, parseRateLimitRule } from "@aooth/auth";
|
|
4
4
|
import { current, defineWook, eventTypeKey, key } from "@wooksjs/event-core";
|
|
5
5
|
import { HttpError, useAuthorization, useCookies, useHeaders, useRequest, useResponse, useUrlParams } from "@wooksjs/event-http";
|
|
6
6
|
import { ArbacAction, ArbacResource, getArbacMate, useArbac } from "@aooth/arbac-moost";
|
|
@@ -6548,6 +6548,165 @@ SessionsController = __decorate([
|
|
|
6548
6548
|
__decorateMetadata("design:paramtypes", [typeof AuthCredential === "undefined" ? Object : AuthCredential, typeof SessionEnricherProvider === "undefined" ? Object : SessionEnricherProvider])
|
|
6549
6549
|
], SessionsController);
|
|
6550
6550
|
//#endregion
|
|
6551
|
+
//#region src/rate-limit/composables.ts
|
|
6552
|
+
/**
|
|
6553
|
+
* Internal: the decision for this event, written by `rateLimitInterceptors`.
|
|
6554
|
+
* Its presence also serves as the "already evaluated" marker that prevents
|
|
6555
|
+
* double counting when the interceptor pair is registered more than once
|
|
6556
|
+
* (global + `@Intercept`) — moost runs `before` hooks sequentially, so a
|
|
6557
|
+
* duplicate instance always observes the first one's write.
|
|
6558
|
+
*/
|
|
6559
|
+
const rateLimitDecisionKey = key("aooth.rateLimit.decision");
|
|
6560
|
+
/**
|
|
6561
|
+
* Read the current event's rate-limit state. A plain function (not a cached
|
|
6562
|
+
* wook) — it's a single slot read, and workflow child events inherit the
|
|
6563
|
+
* HTTP parent's slot transparently.
|
|
6564
|
+
*/
|
|
6565
|
+
function useRateLimit(ctx = current()) {
|
|
6566
|
+
return { decision: ctx.has(rateLimitDecisionKey) ? ctx.get(rateLimitDecisionKey) : null };
|
|
6567
|
+
}
|
|
6568
|
+
//#endregion
|
|
6569
|
+
//#region src/rate-limit/interceptor.ts
|
|
6570
|
+
/**
|
|
6571
|
+
* Global interceptor PAIR enforcing `@RateLimit` metadata (RL.spec.md §5.2)
|
|
6572
|
+
* — register with spread:
|
|
6573
|
+
*
|
|
6574
|
+
* ```ts
|
|
6575
|
+
* app.applyGlobalInterceptors(
|
|
6576
|
+
* authGuardInterceptor({ ... }),
|
|
6577
|
+
* ...rateLimitInterceptors({ limiter, trustProxy: true }),
|
|
6578
|
+
* )
|
|
6579
|
+
* ```
|
|
6580
|
+
*
|
|
6581
|
+
* Two phases, because the primary target is public endpoints and
|
|
6582
|
+
* `authGuardInterceptor` is NOT free there — with any `Authorization`
|
|
6583
|
+
* header present it runs full credential validation before tolerating the
|
|
6584
|
+
* failure on `@Public()` routes:
|
|
6585
|
+
*
|
|
6586
|
+
* - `BEFORE_GUARD` phase owns routes whose effective key strategy is
|
|
6587
|
+
* `'ip'` or a custom resolver — floods are rejected before any
|
|
6588
|
+
* token/credential work.
|
|
6589
|
+
* - `AFTER_GUARD` phase owns `'user'` / `'auto'` keyed routes — those need
|
|
6590
|
+
* the auth context `useAuth()` reads, and by definition target
|
|
6591
|
+
* authenticated traffic where the guard must run anyway.
|
|
6592
|
+
*
|
|
6593
|
+
* Ownership is static per route (from metadata/options), so exactly one
|
|
6594
|
+
* phase evaluates each event; the decision event-slot additionally guards
|
|
6595
|
+
* against double counting when the pair is also attached per-controller
|
|
6596
|
+
* (see {@link RateLimited}).
|
|
6597
|
+
*
|
|
6598
|
+
* On rejection: draft `RateLimit-*` headers + `Retry-After` are written to
|
|
6599
|
+
* the accumulated response (they survive the throw — wooks renders the error
|
|
6600
|
+
* onto the same `HttpResponse`), then `HttpError(429, message)` is thrown.
|
|
6601
|
+
*/
|
|
6602
|
+
function rateLimitInterceptors(opts) {
|
|
6603
|
+
const defaultRules = opts?.rules?.map((r) => parseRateLimitRule(r));
|
|
6604
|
+
const limiter = opts?.limiter ?? new RateLimiter$1();
|
|
6605
|
+
const emitHeaders = opts?.headers ?? true;
|
|
6606
|
+
const ipOpts = { trustProxy: opts?.trustProxy ?? false };
|
|
6607
|
+
const routeConfigs = /* @__PURE__ */ new WeakMap();
|
|
6608
|
+
const resolveRouteConfig = (cc) => {
|
|
6609
|
+
const ctor = cc.getController().constructor;
|
|
6610
|
+
const method = String(cc.getMethod());
|
|
6611
|
+
let byMethod = routeConfigs.get(ctor);
|
|
6612
|
+
if (!byMethod) {
|
|
6613
|
+
byMethod = /* @__PURE__ */ new Map();
|
|
6614
|
+
routeConfigs.set(ctor, byMethod);
|
|
6615
|
+
}
|
|
6616
|
+
const cached = byMethod.get(method);
|
|
6617
|
+
if (cached !== void 0) return cached;
|
|
6618
|
+
const cMeta = cc.getControllerMeta();
|
|
6619
|
+
const mMeta = cc.getMethodMeta();
|
|
6620
|
+
let config = null;
|
|
6621
|
+
const disabled = mMeta?.rateLimitDisabled ?? cMeta?.rateLimitDisabled ?? false;
|
|
6622
|
+
const rules = mMeta?.rateLimitRules ?? cMeta?.rateLimitRules ?? defaultRules;
|
|
6623
|
+
if (!disabled && rules && rules.length > 0) {
|
|
6624
|
+
const metaOpts = mMeta?.rateLimitOptions ?? cMeta?.rateLimitOptions;
|
|
6625
|
+
const rawKey = metaOpts?.key ?? opts?.key ?? "ip";
|
|
6626
|
+
const keyStrategy = rawKey === "auto" ? "user" : rawKey;
|
|
6627
|
+
config = {
|
|
6628
|
+
rules,
|
|
6629
|
+
keyStrategy,
|
|
6630
|
+
authKeyed: keyStrategy === "user",
|
|
6631
|
+
scope: metaOpts?.id ?? `${ctor.name}.${method}`,
|
|
6632
|
+
...(metaOpts?.message ?? opts?.message) !== void 0 && { defaultMessage: metaOpts?.message ?? opts?.message },
|
|
6633
|
+
policyHeader: rules.map((p) => `${p.limit};w=${Math.max(1, Math.round(p.window / 1e3))}`).join(", ")
|
|
6634
|
+
};
|
|
6635
|
+
}
|
|
6636
|
+
byMethod.set(method, config);
|
|
6637
|
+
return config;
|
|
6638
|
+
};
|
|
6639
|
+
const evaluate = async (phase) => {
|
|
6640
|
+
const ctx = current();
|
|
6641
|
+
if (ctx.get(eventTypeKey) !== "http") return;
|
|
6642
|
+
if (ctx.has(rateLimitDecisionKey)) return;
|
|
6643
|
+
const config = resolveRouteConfig(useControllerContext(ctx));
|
|
6644
|
+
if (!config) return;
|
|
6645
|
+
if (config.authKeyed !== (phase === "post")) return;
|
|
6646
|
+
const subject = await resolveSubject(config.keyStrategy, ipOpts, ctx);
|
|
6647
|
+
const decision = await limiter.check(config.scope, subject, config.rules, { ...config.defaultMessage !== void 0 && { defaultMessage: config.defaultMessage } });
|
|
6648
|
+
ctx.set(rateLimitDecisionKey, decision);
|
|
6649
|
+
const response = useResponse(ctx);
|
|
6650
|
+
if (emitHeaders) {
|
|
6651
|
+
response.setHeader("ratelimit-limit", String(decision.limit));
|
|
6652
|
+
response.setHeader("ratelimit-remaining", String(decision.remaining));
|
|
6653
|
+
response.setHeader("ratelimit-reset", String(Math.ceil(decision.resetAfterMs / 1e3)));
|
|
6654
|
+
response.setHeader("ratelimit-policy", config.policyHeader);
|
|
6655
|
+
}
|
|
6656
|
+
if (!decision.allowed) {
|
|
6657
|
+
response.setHeader("retry-after", String(Math.ceil(decision.resetAfterMs / 1e3)));
|
|
6658
|
+
throw new HttpError(429, decision.message ?? "Too many requests");
|
|
6659
|
+
}
|
|
6660
|
+
};
|
|
6661
|
+
return [defineBeforeInterceptor(() => evaluate("pre"), TInterceptorPriority.BEFORE_GUARD), defineBeforeInterceptor(() => evaluate("post"), TInterceptorPriority.AFTER_GUARD)];
|
|
6662
|
+
}
|
|
6663
|
+
async function resolveSubject(strategy, ipOpts, ctx) {
|
|
6664
|
+
if (typeof strategy === "function") return await strategy();
|
|
6665
|
+
if (strategy === "user") {
|
|
6666
|
+
const userId = useAuth(ctx).getAuthContext()?.userId;
|
|
6667
|
+
if (userId !== void 0) return `u:${userId}`;
|
|
6668
|
+
}
|
|
6669
|
+
return `ip:${useRequest(ctx).getIp(ipOpts)}`;
|
|
6670
|
+
}
|
|
6671
|
+
//#endregion
|
|
6672
|
+
//#region src/rate-limit/mate.ts
|
|
6673
|
+
function getRateLimitMate() {
|
|
6674
|
+
return getMoostMate();
|
|
6675
|
+
}
|
|
6676
|
+
//#endregion
|
|
6677
|
+
//#region src/rate-limit/decorator.ts
|
|
6678
|
+
function RateLimit(...args) {
|
|
6679
|
+
const mate = getRateLimitMate();
|
|
6680
|
+
if (args.length === 1 && args[0] === false) return mate.decorate("rateLimitDisabled", true);
|
|
6681
|
+
const inputs = [...args];
|
|
6682
|
+
let options;
|
|
6683
|
+
const last = inputs[inputs.length - 1];
|
|
6684
|
+
if (typeof last === "object" && last !== null && !("limit" in last)) options = inputs.pop();
|
|
6685
|
+
if (inputs.length === 0) throw new Error("@RateLimit requires at least one rule (or the literal `false` to opt out)");
|
|
6686
|
+
const rules = inputs.map((r) => parseRateLimitRule(r));
|
|
6687
|
+
return mate.decorate((meta) => {
|
|
6688
|
+
meta.rateLimitRules = rules;
|
|
6689
|
+
if (options) meta.rateLimitOptions = options;
|
|
6690
|
+
return meta;
|
|
6691
|
+
});
|
|
6692
|
+
}
|
|
6693
|
+
/**
|
|
6694
|
+
* Decorator-factory sugar for attaching the `rateLimitInterceptors(opts)`
|
|
6695
|
+
* PAIR to a specific controller or method instead of globally — the
|
|
6696
|
+
* `AuthGuarded` counterpart. Attaching the pair (not one phase) matters:
|
|
6697
|
+
* dropping the pre-guard def loses flood protection for ip-keyed routes,
|
|
6698
|
+
* dropping the post-guard def silently disables `key: 'user'` routes.
|
|
6699
|
+
*/
|
|
6700
|
+
function RateLimited(opts) {
|
|
6701
|
+
const [pre, post] = rateLimitInterceptors(opts);
|
|
6702
|
+
const interceptPre = Intercept(pre);
|
|
6703
|
+
const interceptPost = Intercept(post);
|
|
6704
|
+
return ((target, key, descriptor) => {
|
|
6705
|
+
interceptPre(target, key, descriptor);
|
|
6706
|
+
interceptPost(target, key, descriptor);
|
|
6707
|
+
});
|
|
6708
|
+
}
|
|
6709
|
+
//#endregion
|
|
6551
6710
|
//#region src/oauth/oauth-tokens.ts
|
|
6552
6711
|
/**
|
|
6553
6712
|
* Explicit string DI token for the ABSTRACT `FederatedIdentityStore`.
|
|
@@ -7208,4 +7367,4 @@ function createAuthEmailOutlet(deps) {
|
|
|
7208
7367
|
});
|
|
7209
7368
|
}
|
|
7210
7369
|
//#endregion
|
|
7211
|
-
export { ADD_MFA_WORKFLOW, 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, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, Public, RESERVED_USER_KEYS, SessionEnricherProvider, SessionsController, UserId, WfTrigger, WfTriggerProvider, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, resolveOAuthRedirect, stripReservedUserKeys, useAuth };
|
|
7370
|
+
export { ADD_MFA_WORKFLOW, 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, 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, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, getRateLimitMate, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, resolveOAuthRedirect, stripReservedUserKeys, useAuth, useRateLimit };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aooth/auth-moost",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.34",
|
|
4
4
|
"description": "Moost auth integration for aoothjs — AuthGuard interceptor, useAuth composable, REST endpoints, workflows",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"aoothjs",
|
|
@@ -57,18 +57,18 @@
|
|
|
57
57
|
"access": "public"
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@atscript/moost-wf": "^0.1.
|
|
60
|
+
"@atscript/moost-wf": "^0.1.109",
|
|
61
61
|
"@wooksjs/http-body": "^0.7.19",
|
|
62
|
-
"@aooth/
|
|
63
|
-
"@aooth/
|
|
64
|
-
"@aooth/
|
|
65
|
-
"@aooth/
|
|
62
|
+
"@aooth/arbac-moost": "^0.1.34",
|
|
63
|
+
"@aooth/auth": "0.1.34",
|
|
64
|
+
"@aooth/idp": "0.1.34",
|
|
65
|
+
"@aooth/user": "0.1.34"
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@atscript/core": "^0.1.78",
|
|
69
69
|
"@atscript/typescript": "^0.1.78",
|
|
70
|
-
"@atscript/ui": "^0.1.
|
|
71
|
-
"@atscript/ui-fns": "^0.1.
|
|
70
|
+
"@atscript/ui": "^0.1.109",
|
|
71
|
+
"@atscript/ui-fns": "^0.1.109",
|
|
72
72
|
"@moostjs/event-http": "^0.6.28",
|
|
73
73
|
"@moostjs/event-wf": "^0.6.28",
|
|
74
74
|
"moost": "^0.6.28",
|
|
@@ -76,7 +76,7 @@
|
|
|
76
76
|
"wooks": "^0.7.19"
|
|
77
77
|
},
|
|
78
78
|
"peerDependencies": {
|
|
79
|
-
"@atscript/moost-wf": "^0.1.
|
|
79
|
+
"@atscript/moost-wf": "^0.1.109",
|
|
80
80
|
"@atscript/typescript": "^0.1.78",
|
|
81
81
|
"@moostjs/event-http": "^0.6.28",
|
|
82
82
|
"@moostjs/event-wf": "^0.6.28",
|