@aooth/auth-moost 0.1.33 → 0.1.35
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 +164 -2
- package/dist/index.mjs +186 -2
- package/package.json +5 -5
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,167 @@ 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
|
+
* Evaluated PRE-guard — floods rejected before credential work.
|
|
632
|
+
* - any other string — a NAMED SUBJECT, looked up in the per-event
|
|
633
|
+
* subjects slot (see `setRateLimitSubject`) and evaluated POST-guard so
|
|
634
|
+
* GUARD-priority writers have run. When the slot is empty, `'user'` and
|
|
635
|
+
* `'session'` (per login/device) derive from the auth context; anything
|
|
636
|
+
* unresolved falls back to the IP budget. `'auto'` is an alias of
|
|
637
|
+
* `'user'`. Apps supply their own kinds (`'tenant'`, `'apiKey'`, …) via
|
|
638
|
+
* `setRateLimitSubject`.
|
|
639
|
+
* - custom function — runs inside the event context PRE-guard; must be
|
|
640
|
+
* self-sufficient (it cannot read what GUARD-priority code sets).
|
|
641
|
+
*/
|
|
642
|
+
type RateLimitKeyStrategy = "ip" | "user" | "auto" | "session" | (string & {}) | (() => string | Promise<string>);
|
|
643
|
+
/** Trailing options object accepted by `@RateLimit(...rules, opts)`. */
|
|
644
|
+
interface RateLimitDecoratorOptions {
|
|
645
|
+
/** Overrides the interceptor-level default key strategy for this route. */
|
|
646
|
+
key?: RateLimitKeyStrategy;
|
|
647
|
+
/** Default 429 message template for rules without an inline `| message`. */
|
|
648
|
+
message?: string;
|
|
649
|
+
/**
|
|
650
|
+
* Bucket id — handlers sharing an id share counters. Default scope is
|
|
651
|
+
* `<ControllerClass>.<methodName>` (per-handler isolation).
|
|
652
|
+
*/
|
|
653
|
+
id?: string;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Rate-limit metadata written by `@RateLimit()` and read by
|
|
657
|
+
* `rateLimitInterceptors`. Merged into `TMoostMetadata` so other moost-aware
|
|
658
|
+
* tooling sees it.
|
|
659
|
+
*/
|
|
660
|
+
interface TRateLimitMeta {
|
|
661
|
+
/** Rules normalized at decoration time — bad grammar fails at boot. */
|
|
662
|
+
rateLimitRules?: RateLimitRule$1[];
|
|
663
|
+
rateLimitOptions?: RateLimitDecoratorOptions;
|
|
664
|
+
/** `@RateLimit(false)` — opt this route out of interceptor-level default rules. */
|
|
665
|
+
rateLimitDisabled?: boolean;
|
|
666
|
+
}
|
|
667
|
+
declare module "moost" {
|
|
668
|
+
interface TMoostMetadata extends TRateLimitMeta {}
|
|
669
|
+
}
|
|
670
|
+
type RateLimitMate = Mate<TMoostMetadata & {
|
|
671
|
+
params: TMateParamMeta[];
|
|
672
|
+
}, TMoostMetadata & {
|
|
673
|
+
params: TMateParamMeta[];
|
|
674
|
+
}>;
|
|
675
|
+
declare function getRateLimitMate(): RateLimitMate;
|
|
676
|
+
//#endregion
|
|
677
|
+
//#region src/rate-limit/interceptor.d.ts
|
|
678
|
+
interface RateLimitInterceptorOptions {
|
|
679
|
+
/**
|
|
680
|
+
* The shared limiter (wire your `RateLimitStoreRedis` here). When omitted,
|
|
681
|
+
* a memory-store `RateLimiter` is created ONCE per factory call — stable
|
|
682
|
+
* across requests, but single-process and private to this interceptor
|
|
683
|
+
* pair. Pass an explicit limiter for anything beyond zero-config dev.
|
|
684
|
+
*/
|
|
685
|
+
limiter?: RateLimiter$1;
|
|
686
|
+
/**
|
|
687
|
+
* App-wide default rules applied to EVERY http route without its own
|
|
688
|
+
* `@RateLimit(...)` metadata. Opt out per-route with `@RateLimit(false)`.
|
|
689
|
+
*/
|
|
690
|
+
rules?: RateLimitRuleInput$1[];
|
|
691
|
+
/** Default key strategy for routes whose `@RateLimit` doesn't set one. Default: `'ip'`. */
|
|
692
|
+
key?: RateLimitKeyStrategy;
|
|
693
|
+
/** Trust `x-forwarded-for` for the client IP (behind a proxy). Default: `false`. */
|
|
694
|
+
trustProxy?: boolean;
|
|
695
|
+
/** Emit draft `RateLimit-*` headers on every response of a limited route. Default: `true`. */
|
|
696
|
+
headers?: boolean;
|
|
697
|
+
/** App-wide default 429 message template. */
|
|
698
|
+
message?: string;
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Global interceptor PAIR enforcing `@RateLimit` metadata (RL.spec.md §5.2)
|
|
702
|
+
* — register with spread:
|
|
703
|
+
*
|
|
704
|
+
* ```ts
|
|
705
|
+
* app.applyGlobalInterceptors(
|
|
706
|
+
* authGuardInterceptor({ ... }),
|
|
707
|
+
* ...rateLimitInterceptors({ limiter, trustProxy: true }),
|
|
708
|
+
* )
|
|
709
|
+
* ```
|
|
710
|
+
*
|
|
711
|
+
* Two phases, because the primary target is public endpoints and
|
|
712
|
+
* `authGuardInterceptor` is NOT free there — with any `Authorization`
|
|
713
|
+
* header present it runs full credential validation before tolerating the
|
|
714
|
+
* failure on `@Public()` routes:
|
|
715
|
+
*
|
|
716
|
+
* - `BEFORE_GUARD` phase owns routes whose effective key strategy is
|
|
717
|
+
* `'ip'` or a custom resolver — floods are rejected before any
|
|
718
|
+
* token/credential work.
|
|
719
|
+
* - `AFTER_GUARD` phase owns `'user'` / `'auto'` keyed routes — those need
|
|
720
|
+
* the auth context `useAuth()` reads, and by definition target
|
|
721
|
+
* authenticated traffic where the guard must run anyway.
|
|
722
|
+
*
|
|
723
|
+
* Ownership is static per route (from metadata/options), so exactly one
|
|
724
|
+
* phase evaluates each event; the decision event-slot additionally guards
|
|
725
|
+
* against double counting when the pair is also attached per-controller
|
|
726
|
+
* (see {@link RateLimited}).
|
|
727
|
+
*
|
|
728
|
+
* On rejection: draft `RateLimit-*` headers + `Retry-After` are written to
|
|
729
|
+
* the accumulated response (they survive the throw — wooks renders the error
|
|
730
|
+
* onto the same `HttpResponse`), then `HttpError(429, message)` is thrown.
|
|
731
|
+
*/
|
|
732
|
+
declare function rateLimitInterceptors(opts?: RateLimitInterceptorOptions): TInterceptorDef[];
|
|
733
|
+
//#endregion
|
|
734
|
+
//#region src/rate-limit/decorator.d.ts
|
|
735
|
+
/**
|
|
736
|
+
* Declares rate-limit rules for a controller method (or every method of a
|
|
737
|
+
* controller, when applied at class level — method-level metadata replaces
|
|
738
|
+
* class-level). Metadata-only: enforcement happens in the globally registered
|
|
739
|
+
* `rateLimitInterceptors(...)` (RL.spec.md §5) or a per-controller
|
|
740
|
+
* {@link RateLimited}.
|
|
741
|
+
*
|
|
742
|
+
* ```ts
|
|
743
|
+
* RateLimit('6/5m | Too many login attempts, please wait {{delta}}')
|
|
744
|
+
* RateLimit('1/1s', '30/1m') // stacked windows, one budget each
|
|
745
|
+
* RateLimit('100/1h', { key: 'user' }) // per-user budget on an authed route
|
|
746
|
+
* RateLimit(false) // opt out of interceptor-level default rules
|
|
747
|
+
* ```
|
|
748
|
+
*
|
|
749
|
+
* Rules are parsed eagerly, so a bad rule string throws at decoration
|
|
750
|
+
* (boot) time, not per request.
|
|
751
|
+
*/
|
|
752
|
+
declare function RateLimit(disabled: false): ClassDecorator & MethodDecorator;
|
|
753
|
+
declare function RateLimit(...rulesAndOpts: [RateLimitRuleInput$1, ...Array<RateLimitRuleInput$1 | RateLimitDecoratorOptions>]): ClassDecorator & MethodDecorator;
|
|
754
|
+
/**
|
|
755
|
+
* Decorator-factory sugar for attaching the `rateLimitInterceptors(opts)`
|
|
756
|
+
* PAIR to a specific controller or method instead of globally — the
|
|
757
|
+
* `AuthGuarded` counterpart. Attaching the pair (not one phase) matters:
|
|
758
|
+
* dropping the pre-guard def loses flood protection for ip-keyed routes,
|
|
759
|
+
* dropping the post-guard def silently disables `key: 'user'` routes.
|
|
760
|
+
*/
|
|
761
|
+
declare function RateLimited(opts?: RateLimitInterceptorOptions): ClassDecorator & MethodDecorator;
|
|
762
|
+
//#endregion
|
|
763
|
+
//#region src/rate-limit/composables.d.ts
|
|
764
|
+
/**
|
|
765
|
+
* Supply the rate-limit subject for a named key strategy — the seam for
|
|
766
|
+
* custom IAMs / tenant resolvers. Call from GUARD-priority (or earlier)
|
|
767
|
+
* code; the value is used VERBATIM as the counter subject (include your own
|
|
768
|
+
* prefix, e.g. `iam:<sub>`) and always wins over the built-in `user` /
|
|
769
|
+
* `session` derivations. Full contract: docs `/moost/rate-limit`.
|
|
770
|
+
*/
|
|
771
|
+
declare function setRateLimitSubject(kind: string, subject: string, ctx?: EventContext): void;
|
|
772
|
+
/** Read a named rate-limit subject set for this event (or `undefined`). */
|
|
773
|
+
declare function getRateLimitSubject(kind: string, ctx?: EventContext): string | undefined;
|
|
774
|
+
interface RateLimitBindings {
|
|
775
|
+
/**
|
|
776
|
+
* The decision the interceptor computed for this event, or `null` when the
|
|
777
|
+
* route has no rules (or the interceptors are not installed).
|
|
778
|
+
*/
|
|
779
|
+
decision: RateLimitDecision$1 | null;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Read the current event's rate-limit state. A plain function (not a cached
|
|
783
|
+
* wook) — it's a single slot read, and workflow child events inherit the
|
|
784
|
+
* HTTP parent's slot transparently.
|
|
785
|
+
*/
|
|
786
|
+
declare function useRateLimit(ctx?: EventContext): RateLimitBindings;
|
|
787
|
+
//#endregion
|
|
626
788
|
//#region src/oauth/oauth.controller.d.ts
|
|
627
789
|
/**
|
|
628
790
|
* REST surface for federated-login ACCOUNT MANAGEMENT (OAuth2 / OIDC), RFC
|
|
@@ -3915,4 +4077,4 @@ interface AuditEmitter {
|
|
|
3915
4077
|
emit(event: AuditEvent): Promise<void> | void;
|
|
3916
4078
|
}
|
|
3917
4079
|
//#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 };
|
|
4080
|
+
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, getRateLimitSubject, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, resolveOAuthRedirect, setRateLimitSubject, 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,190 @@ 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
|
+
* Internal: named rate-limit subjects for this event — subject kind
|
|
6562
|
+
* (`'user'`, `'tenant'`, …) → resolved caller identity, written via
|
|
6563
|
+
* {@link setRateLimitSubject} and read by the post-guard rate-limit phase.
|
|
6564
|
+
*/
|
|
6565
|
+
const rateLimitSubjectsKey = key("aooth.rateLimit.subjects");
|
|
6566
|
+
/**
|
|
6567
|
+
* Supply the rate-limit subject for a named key strategy — the seam for
|
|
6568
|
+
* custom IAMs / tenant resolvers. Call from GUARD-priority (or earlier)
|
|
6569
|
+
* code; the value is used VERBATIM as the counter subject (include your own
|
|
6570
|
+
* prefix, e.g. `iam:<sub>`) and always wins over the built-in `user` /
|
|
6571
|
+
* `session` derivations. Full contract: docs `/moost/rate-limit`.
|
|
6572
|
+
*/
|
|
6573
|
+
function setRateLimitSubject(kind, subject, ctx = current()) {
|
|
6574
|
+
const subjects = ctx.has(rateLimitSubjectsKey) ? ctx.get(rateLimitSubjectsKey) : {};
|
|
6575
|
+
subjects[kind] = subject;
|
|
6576
|
+
ctx.set(rateLimitSubjectsKey, subjects);
|
|
6577
|
+
}
|
|
6578
|
+
/** Read a named rate-limit subject set for this event (or `undefined`). */
|
|
6579
|
+
function getRateLimitSubject(kind, ctx = current()) {
|
|
6580
|
+
return ctx.has(rateLimitSubjectsKey) ? ctx.get(rateLimitSubjectsKey)[kind] : void 0;
|
|
6581
|
+
}
|
|
6582
|
+
/**
|
|
6583
|
+
* Read the current event's rate-limit state. A plain function (not a cached
|
|
6584
|
+
* wook) — it's a single slot read, and workflow child events inherit the
|
|
6585
|
+
* HTTP parent's slot transparently.
|
|
6586
|
+
*/
|
|
6587
|
+
function useRateLimit(ctx = current()) {
|
|
6588
|
+
return { decision: ctx.has(rateLimitDecisionKey) ? ctx.get(rateLimitDecisionKey) : null };
|
|
6589
|
+
}
|
|
6590
|
+
//#endregion
|
|
6591
|
+
//#region src/rate-limit/interceptor.ts
|
|
6592
|
+
/**
|
|
6593
|
+
* Global interceptor PAIR enforcing `@RateLimit` metadata (RL.spec.md §5.2)
|
|
6594
|
+
* — register with spread:
|
|
6595
|
+
*
|
|
6596
|
+
* ```ts
|
|
6597
|
+
* app.applyGlobalInterceptors(
|
|
6598
|
+
* authGuardInterceptor({ ... }),
|
|
6599
|
+
* ...rateLimitInterceptors({ limiter, trustProxy: true }),
|
|
6600
|
+
* )
|
|
6601
|
+
* ```
|
|
6602
|
+
*
|
|
6603
|
+
* Two phases, because the primary target is public endpoints and
|
|
6604
|
+
* `authGuardInterceptor` is NOT free there — with any `Authorization`
|
|
6605
|
+
* header present it runs full credential validation before tolerating the
|
|
6606
|
+
* failure on `@Public()` routes:
|
|
6607
|
+
*
|
|
6608
|
+
* - `BEFORE_GUARD` phase owns routes whose effective key strategy is
|
|
6609
|
+
* `'ip'` or a custom resolver — floods are rejected before any
|
|
6610
|
+
* token/credential work.
|
|
6611
|
+
* - `AFTER_GUARD` phase owns `'user'` / `'auto'` keyed routes — those need
|
|
6612
|
+
* the auth context `useAuth()` reads, and by definition target
|
|
6613
|
+
* authenticated traffic where the guard must run anyway.
|
|
6614
|
+
*
|
|
6615
|
+
* Ownership is static per route (from metadata/options), so exactly one
|
|
6616
|
+
* phase evaluates each event; the decision event-slot additionally guards
|
|
6617
|
+
* against double counting when the pair is also attached per-controller
|
|
6618
|
+
* (see {@link RateLimited}).
|
|
6619
|
+
*
|
|
6620
|
+
* On rejection: draft `RateLimit-*` headers + `Retry-After` are written to
|
|
6621
|
+
* the accumulated response (they survive the throw — wooks renders the error
|
|
6622
|
+
* onto the same `HttpResponse`), then `HttpError(429, message)` is thrown.
|
|
6623
|
+
*/
|
|
6624
|
+
function rateLimitInterceptors(opts) {
|
|
6625
|
+
const defaultRules = opts?.rules?.map((r) => parseRateLimitRule(r));
|
|
6626
|
+
const limiter = opts?.limiter ?? new RateLimiter$1();
|
|
6627
|
+
const emitHeaders = opts?.headers ?? true;
|
|
6628
|
+
const ipOpts = { trustProxy: opts?.trustProxy ?? false };
|
|
6629
|
+
const routeConfigs = /* @__PURE__ */ new WeakMap();
|
|
6630
|
+
const resolveRouteConfig = (cc) => {
|
|
6631
|
+
const ctor = cc.getController().constructor;
|
|
6632
|
+
const method = String(cc.getMethod());
|
|
6633
|
+
let byMethod = routeConfigs.get(ctor);
|
|
6634
|
+
if (!byMethod) {
|
|
6635
|
+
byMethod = /* @__PURE__ */ new Map();
|
|
6636
|
+
routeConfigs.set(ctor, byMethod);
|
|
6637
|
+
}
|
|
6638
|
+
const cached = byMethod.get(method);
|
|
6639
|
+
if (cached !== void 0) return cached;
|
|
6640
|
+
const cMeta = cc.getControllerMeta();
|
|
6641
|
+
const mMeta = cc.getMethodMeta();
|
|
6642
|
+
let config = null;
|
|
6643
|
+
const disabled = mMeta?.rateLimitDisabled ?? cMeta?.rateLimitDisabled ?? false;
|
|
6644
|
+
const rules = mMeta?.rateLimitRules ?? cMeta?.rateLimitRules ?? defaultRules;
|
|
6645
|
+
if (!disabled && rules && rules.length > 0) {
|
|
6646
|
+
const metaOpts = mMeta?.rateLimitOptions ?? cMeta?.rateLimitOptions;
|
|
6647
|
+
const rawKey = metaOpts?.key ?? opts?.key ?? "ip";
|
|
6648
|
+
const keyStrategy = rawKey === "auto" ? "user" : rawKey;
|
|
6649
|
+
config = {
|
|
6650
|
+
rules,
|
|
6651
|
+
keyStrategy,
|
|
6652
|
+
postGuardKeyed: typeof keyStrategy === "string" && keyStrategy !== "ip",
|
|
6653
|
+
scope: metaOpts?.id ?? `${ctor.name}.${method}`,
|
|
6654
|
+
...(metaOpts?.message ?? opts?.message) !== void 0 && { defaultMessage: metaOpts?.message ?? opts?.message },
|
|
6655
|
+
policyHeader: rules.map((p) => `${p.limit};w=${Math.max(1, Math.round(p.window / 1e3))}`).join(", ")
|
|
6656
|
+
};
|
|
6657
|
+
}
|
|
6658
|
+
byMethod.set(method, config);
|
|
6659
|
+
return config;
|
|
6660
|
+
};
|
|
6661
|
+
const evaluate = async (phase) => {
|
|
6662
|
+
const ctx = current();
|
|
6663
|
+
if (ctx.get(eventTypeKey) !== "http") return;
|
|
6664
|
+
if (ctx.has(rateLimitDecisionKey)) return;
|
|
6665
|
+
const config = resolveRouteConfig(useControllerContext(ctx));
|
|
6666
|
+
if (!config) return;
|
|
6667
|
+
if (config.postGuardKeyed !== (phase === "post")) return;
|
|
6668
|
+
const subject = await resolveSubject(config.keyStrategy, ipOpts, ctx);
|
|
6669
|
+
const decision = await limiter.check(config.scope, subject, config.rules, { ...config.defaultMessage !== void 0 && { defaultMessage: config.defaultMessage } });
|
|
6670
|
+
ctx.set(rateLimitDecisionKey, decision);
|
|
6671
|
+
const response = useResponse(ctx);
|
|
6672
|
+
if (emitHeaders) {
|
|
6673
|
+
response.setHeader("ratelimit-limit", String(decision.limit));
|
|
6674
|
+
response.setHeader("ratelimit-remaining", String(decision.remaining));
|
|
6675
|
+
response.setHeader("ratelimit-reset", String(Math.ceil(decision.resetAfterMs / 1e3)));
|
|
6676
|
+
response.setHeader("ratelimit-policy", config.policyHeader);
|
|
6677
|
+
}
|
|
6678
|
+
if (!decision.allowed) {
|
|
6679
|
+
response.setHeader("retry-after", String(Math.ceil(decision.resetAfterMs / 1e3)));
|
|
6680
|
+
throw new HttpError(429, decision.message ?? "Too many requests");
|
|
6681
|
+
}
|
|
6682
|
+
};
|
|
6683
|
+
return [defineBeforeInterceptor(() => evaluate("pre"), TInterceptorPriority.BEFORE_GUARD), defineBeforeInterceptor(() => evaluate("post"), TInterceptorPriority.AFTER_GUARD)];
|
|
6684
|
+
}
|
|
6685
|
+
async function resolveSubject(strategy, ipOpts, ctx) {
|
|
6686
|
+
if (typeof strategy === "function") return await strategy();
|
|
6687
|
+
if (strategy !== "ip") {
|
|
6688
|
+
const subject = getRateLimitSubject(strategy, ctx);
|
|
6689
|
+
if (subject !== void 0) return subject;
|
|
6690
|
+
const auth = strategy === "user" || strategy === "session" ? useAuth(ctx).getAuthContext() : null;
|
|
6691
|
+
if (strategy === "user" && auth?.userId !== void 0) return `u:${auth.userId}`;
|
|
6692
|
+
if (strategy === "session" && auth?.sessionId !== void 0) return `s:${auth.sessionId}`;
|
|
6693
|
+
}
|
|
6694
|
+
return `ip:${useRequest(ctx).getIp(ipOpts)}`;
|
|
6695
|
+
}
|
|
6696
|
+
//#endregion
|
|
6697
|
+
//#region src/rate-limit/mate.ts
|
|
6698
|
+
function getRateLimitMate() {
|
|
6699
|
+
return getMoostMate();
|
|
6700
|
+
}
|
|
6701
|
+
//#endregion
|
|
6702
|
+
//#region src/rate-limit/decorator.ts
|
|
6703
|
+
function RateLimit(...args) {
|
|
6704
|
+
const mate = getRateLimitMate();
|
|
6705
|
+
if (args.length === 1 && args[0] === false) return mate.decorate("rateLimitDisabled", true);
|
|
6706
|
+
const inputs = [...args];
|
|
6707
|
+
let options;
|
|
6708
|
+
const last = inputs[inputs.length - 1];
|
|
6709
|
+
if (typeof last === "object" && last !== null && !("limit" in last)) options = inputs.pop();
|
|
6710
|
+
if (inputs.length === 0) throw new Error("@RateLimit requires at least one rule (or the literal `false` to opt out)");
|
|
6711
|
+
const rules = inputs.map((r) => parseRateLimitRule(r));
|
|
6712
|
+
return mate.decorate((meta) => {
|
|
6713
|
+
meta.rateLimitRules = rules;
|
|
6714
|
+
if (options) meta.rateLimitOptions = options;
|
|
6715
|
+
return meta;
|
|
6716
|
+
});
|
|
6717
|
+
}
|
|
6718
|
+
/**
|
|
6719
|
+
* Decorator-factory sugar for attaching the `rateLimitInterceptors(opts)`
|
|
6720
|
+
* PAIR to a specific controller or method instead of globally — the
|
|
6721
|
+
* `AuthGuarded` counterpart. Attaching the pair (not one phase) matters:
|
|
6722
|
+
* dropping the pre-guard def loses flood protection for ip-keyed routes,
|
|
6723
|
+
* dropping the post-guard def silently disables `key: 'user'` routes.
|
|
6724
|
+
*/
|
|
6725
|
+
function RateLimited(opts) {
|
|
6726
|
+
const [pre, post] = rateLimitInterceptors(opts);
|
|
6727
|
+
const interceptPre = Intercept(pre);
|
|
6728
|
+
const interceptPost = Intercept(post);
|
|
6729
|
+
return ((target, key, descriptor) => {
|
|
6730
|
+
interceptPre(target, key, descriptor);
|
|
6731
|
+
interceptPost(target, key, descriptor);
|
|
6732
|
+
});
|
|
6733
|
+
}
|
|
6734
|
+
//#endregion
|
|
6551
6735
|
//#region src/oauth/oauth-tokens.ts
|
|
6552
6736
|
/**
|
|
6553
6737
|
* Explicit string DI token for the ABSTRACT `FederatedIdentityStore`.
|
|
@@ -7208,4 +7392,4 @@ function createAuthEmailOutlet(deps) {
|
|
|
7208
7392
|
});
|
|
7209
7393
|
}
|
|
7210
7394
|
//#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 };
|
|
7395
|
+
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, getRateLimitSubject, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, resolveOAuthRedirect, setRateLimitSubject, 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.35",
|
|
4
4
|
"description": "Moost auth integration for aoothjs — AuthGuard interceptor, useAuth composable, REST endpoints, workflows",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"aoothjs",
|
|
@@ -59,10 +59,10 @@
|
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"@atscript/moost-wf": "^0.1.109",
|
|
61
61
|
"@wooksjs/http-body": "^0.7.19",
|
|
62
|
-
"@aooth/arbac-moost": "^0.1.
|
|
63
|
-
"@aooth/auth": "0.1.
|
|
64
|
-
"@aooth/
|
|
65
|
-
"@aooth/
|
|
62
|
+
"@aooth/arbac-moost": "^0.1.35",
|
|
63
|
+
"@aooth/auth": "0.1.35",
|
|
64
|
+
"@aooth/user": "0.1.35",
|
|
65
|
+
"@aooth/idp": "0.1.35"
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@atscript/core": "^0.1.78",
|