@miguelmorales13/nestkit 0.26.0 → 0.29.0
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/README.md +69 -0
- package/dist/alerts/alert-on-failure.decorator.d.ts +5 -0
- package/dist/alerts/alert-sinks.d.ts +29 -0
- package/dist/alerts/alerts.module.d.ts +19 -0
- package/dist/alerts/alerts.options.d.ts +1 -0
- package/dist/alerts/alerts.service.d.ts +28 -0
- package/dist/alerts/alerts.types.d.ts +66 -0
- package/dist/alerts/index.cjs +276 -0
- package/dist/alerts/index.d.ts +10 -0
- package/dist/alerts/index.js +276 -0
- package/dist/alerts/logger-with-alerts.d.ts +18 -0
- package/dist/alerts/process-guards.d.ts +21 -0
- package/dist/alerts/runtime.d.ts +4 -0
- package/dist/audit/index.cjs +13 -13
- package/dist/audit/index.js +2 -2
- package/dist/auth/index.cjs +21 -21
- package/dist/auth/index.js +3 -3
- package/dist/auth/oauth/index.cjs +101 -101
- package/dist/auth/oauth/index.js +3 -3
- package/dist/bootstrap/apply-defaults.d.ts +9 -0
- package/dist/bootstrap/index.cjs +7 -6
- package/dist/bootstrap/index.js +6 -5
- package/dist/chunk-33KFVAUZ.cjs +151 -0
- package/dist/chunk-3TUMVLPJ.js +14 -0
- package/dist/{chunk-PA24P76K.js → chunk-45SW7FBE.js} +1 -1
- package/dist/{chunk-RF75KC63.cjs → chunk-47IYXZHW.cjs} +2 -2
- package/dist/{chunk-TUNDBBQF.js → chunk-4WWOKZIO.js} +4 -4
- package/dist/{chunk-2DUEQKOI.js → chunk-5LVGCTJ3.js} +4 -4
- package/dist/chunk-A6YGIZCQ.cjs +14 -0
- package/dist/chunk-A7FI6HXV.js +40 -0
- package/dist/chunk-CU4FUIVJ.cjs +8 -0
- package/dist/{chunk-FH5UNWWW.cjs → chunk-D35TBVRO.cjs} +4 -4
- package/dist/{chunk-4MGIQFAJ.js → chunk-D3DDJWUD.js} +5 -0
- package/dist/chunk-DVGPEBUL.js +8 -0
- package/dist/{chunk-VKOPDDCC.js → chunk-ENZ7LQRE.js} +1 -1
- package/dist/{chunk-3AUOOEQO.cjs → chunk-F77X4QUN.cjs} +2 -2
- package/dist/chunk-FBNV5X6C.js +61 -0
- package/dist/{chunk-APUFKA4K.cjs → chunk-FDZQCLLK.cjs} +6 -6
- package/dist/{chunk-DYHSOULW.js → chunk-IGSNB5BX.js} +1 -1
- package/dist/chunk-IVWPA6QH.cjs +90 -0
- package/dist/{chunk-LSDY6ETG.cjs → chunk-JJKGQNGD.cjs} +5 -5
- package/dist/{chunk-ALIKVFOV.cjs → chunk-JRFE7NSO.cjs} +12 -4
- package/dist/{chunk-HVHYZXBB.cjs → chunk-KNU5RN3O.cjs} +3 -3
- package/dist/{chunk-52IOOHNX.cjs → chunk-KQPJCVN3.cjs} +26 -26
- package/dist/chunk-LGFHLAY3.cjs +61 -0
- package/dist/{chunk-2REOCMUD.cjs → chunk-LRX7AMSS.cjs} +6 -1
- package/dist/chunk-LU3HO7B3.js +151 -0
- package/dist/{chunk-4PFAKLT3.js → chunk-MUWHGBIB.js} +1 -1
- package/dist/{chunk-ZJMLEP5H.js → chunk-NJYLQDB3.js} +1 -1
- package/dist/{chunk-IFNYRZP2.js → chunk-OSRH6KYZ.js} +4 -4
- package/dist/{chunk-6RAPVLJM.js → chunk-OTE77ONL.js} +1 -1
- package/dist/chunk-UDACUMLO.cjs +40 -0
- package/dist/{chunk-PFHHLB7B.js → chunk-UGAAJRPO.js} +10 -2
- package/dist/{chunk-SPTDXUED.cjs → chunk-URLDTS2Q.cjs} +2 -2
- package/dist/{chunk-W2T2VFLC.cjs → chunk-VALDHJOO.cjs} +5 -5
- package/dist/chunk-WFCQDOSN.js +90 -0
- package/dist/consent/consent.interceptor.d.ts +20 -0
- package/dist/consent/consent.module.d.ts +25 -0
- package/dist/consent/consent.options.d.ts +30 -0
- package/dist/consent/consent.port.d.ts +17 -0
- package/dist/consent/consent.service.d.ts +44 -0
- package/dist/consent/guard/index.cjs +13 -0
- package/dist/consent/guard/index.d.ts +31 -0
- package/dist/consent/guard/index.js +13 -0
- package/dist/consent/index.cjs +271 -0
- package/dist/consent/index.d.ts +13 -0
- package/dist/consent/index.js +271 -0
- package/dist/consent/memory.store.d.ts +7 -0
- package/dist/consent/shared/index.cjs +11 -0
- package/dist/consent/shared/index.d.ts +19 -0
- package/dist/consent/shared/index.js +11 -0
- package/dist/consent/typeorm.store.d.ts +22 -0
- package/dist/crud/index.cjs +4 -4
- package/dist/crud/index.js +3 -3
- package/dist/database/postgres/index.cjs +3 -3
- package/dist/database/postgres/index.js +2 -2
- package/dist/database/supabase/index.cjs +3 -3
- package/dist/database/supabase/index.js +2 -2
- package/dist/database/typeorm/index.cjs +2 -2
- package/dist/database/typeorm/index.js +1 -1
- package/dist/devices/device-check.interceptor.d.ts +20 -0
- package/dist/devices/devices.module.d.ts +28 -0
- package/dist/devices/devices.options.d.ts +53 -0
- package/dist/devices/devices.port.d.ts +62 -0
- package/dist/devices/devices.service.d.ts +58 -0
- package/dist/devices/index.cjs +327 -0
- package/dist/devices/index.d.ts +8 -0
- package/dist/devices/index.js +327 -0
- package/dist/devices/memory.store.d.ts +12 -0
- package/dist/email/index.cjs +2 -2
- package/dist/email/index.js +1 -1
- package/dist/email/nodemailer/index.cjs +2 -2
- package/dist/email/nodemailer/index.js +1 -1
- package/dist/email/resend/index.cjs +2 -2
- package/dist/email/resend/index.js +1 -1
- package/dist/entities/index.cjs +1 -1
- package/dist/entities/index.js +1 -1
- package/dist/errors/index.cjs +7 -7
- package/dist/errors/index.js +7 -7
- package/dist/events/buses.d.ts +27 -0
- package/dist/events/events.controller.d.ts +15 -0
- package/dist/events/events.module.d.ts +29 -0
- package/dist/events/events.options.d.ts +50 -0
- package/dist/events/events.service.d.ts +49 -0
- package/dist/events/events.types.d.ts +77 -0
- package/dist/events/index.cjs +557 -0
- package/dist/events/index.d.ts +10 -0
- package/dist/events/index.js +557 -0
- package/dist/events/memory-ticket.store.d.ts +9 -0
- package/dist/google-business/google-business-http.d.ts +41 -0
- package/dist/google-business/google-business.errors.d.ts +75 -0
- package/dist/google-business/google-business.mappers.d.ts +52 -0
- package/dist/google-business/google-business.module.d.ts +26 -0
- package/dist/google-business/google-business.options.d.ts +40 -0
- package/dist/google-business/google-business.ports.d.ts +18 -0
- package/dist/google-business/google-business.service.d.ts +120 -0
- package/dist/google-business/google-business.types.d.ts +155 -0
- package/dist/google-business/index.cjs +1025 -0
- package/dist/google-business/index.d.ts +15 -0
- package/dist/google-business/index.js +1025 -0
- package/dist/google-business/testing/google-simulator.d.ts +61 -0
- package/dist/hardening/body-limits.d.ts +24 -0
- package/dist/hardening/http.types.d.ts +26 -0
- package/dist/hardening/index.cjs +179 -0
- package/dist/hardening/index.d.ts +19 -0
- package/dist/hardening/index.js +179 -0
- package/dist/hardening/memory-rate-limit.store.d.ts +10 -0
- package/dist/hardening/origin-secret.d.ts +29 -0
- package/dist/hardening/rate-limit.decorator.d.ts +8 -0
- package/dist/hardening/rate-limit.guard.d.ts +18 -0
- package/dist/hardening/rate-limit.module.d.ts +23 -0
- package/dist/hardening/rate-limit.options.d.ts +35 -0
- package/dist/hardening/rate-limit.port.d.ts +11 -0
- package/dist/hardening/redis-rate-limit.store.d.ts +23 -0
- package/dist/hardening/trust-proxy.d.ts +22 -0
- package/dist/health/health.controller.d.ts +32 -0
- package/dist/health/health.module.d.ts +15 -0
- package/dist/health/health.options.d.ts +24 -0
- package/dist/health/index.cjs +103 -0
- package/dist/health/index.d.ts +5 -0
- package/dist/health/index.js +103 -0
- package/dist/i18n/index.cjs +3 -3
- package/dist/i18n/index.js +2 -2
- package/dist/idempotency/idempotency.interceptor.d.ts +1 -0
- package/dist/idempotency/idempotency.options.d.ts +15 -0
- package/dist/idempotency/index.cjs +214 -7
- package/dist/idempotency/index.d.ts +5 -0
- package/dist/idempotency/index.js +210 -3
- package/dist/idempotency/no-idempotency.decorator.d.ts +8 -0
- package/dist/idempotency/postgres.store.d.ts +49 -0
- package/dist/idempotency/redis.store.d.ts +59 -0
- package/dist/index.cjs +21 -20
- package/dist/index.js +33 -32
- package/dist/invoicing/index.cjs +2 -2
- package/dist/invoicing/index.js +1 -1
- package/dist/jobs/defer-job.d.ts +10 -0
- package/dist/jobs/index.cjs +318 -0
- package/dist/jobs/index.d.ts +8 -0
- package/dist/jobs/index.js +318 -0
- package/dist/jobs/jobs-admin.controller.d.ts +18 -0
- package/dist/jobs/jobs.module.d.ts +33 -0
- package/dist/jobs/jobs.options.d.ts +62 -0
- package/dist/jobs/jobs.service.d.ts +53 -0
- package/dist/jobs/jobs.sql.d.ts +11 -0
- package/dist/media/index.cjs +14 -14
- package/dist/media/index.js +1 -1
- package/dist/meta/index.cjs +3 -3
- package/dist/meta/index.js +1 -1
- package/dist/notifications/index.cjs +375 -0
- package/dist/notifications/index.d.ts +8 -0
- package/dist/notifications/index.js +375 -0
- package/dist/notifications/memory.stores.d.ts +23 -0
- package/dist/notifications/notifications.controller.d.ts +11 -0
- package/dist/notifications/notifications.module.d.ts +31 -0
- package/dist/notifications/notifications.options.d.ts +33 -0
- package/dist/notifications/notifications.port.d.ts +97 -0
- package/dist/notifications/notifier.service.d.ts +31 -0
- package/dist/payments/connect/credentials-cipher.d.ts +14 -0
- package/dist/payments/connect/mercadopago-refund.d.ts +118 -0
- package/dist/payments/connect/mercadopago-signature.d.ts +6 -0
- package/dist/payments/connect/online-checkout.d.ts +69 -0
- package/dist/payments/connect/rejection.d.ts +7 -0
- package/dist/payments/connect/status.d.ts +20 -0
- package/dist/payments/connect/terminal-connections.d.ts +291 -0
- package/dist/payments/index.cjs +908 -10
- package/dist/payments/index.d.ts +10 -0
- package/dist/payments/index.js +900 -2
- package/dist/pinterest/index.cjs +3 -3
- package/dist/pinterest/index.js +1 -1
- package/dist/privacy/anonymizer.d.ts +14 -0
- package/dist/privacy/index.cjs +768 -0
- package/dist/privacy/index.d.ts +13 -0
- package/dist/privacy/index.js +768 -0
- package/dist/privacy/memory.store.d.ts +15 -0
- package/dist/privacy/privacy.module.d.ts +30 -0
- package/dist/privacy/privacy.options.d.ts +43 -0
- package/dist/privacy/privacy.port.d.ts +25 -0
- package/dist/privacy/privacy.service.d.ts +69 -0
- package/dist/privacy/privacy.types.d.ts +125 -0
- package/dist/privacy/sql.d.ts +7 -0
- package/dist/privacy/sql.store.d.ts +21 -0
- package/dist/privacy/zip.d.ts +23 -0
- package/dist/push/index.cjs +13 -13
- package/dist/push/index.js +5 -5
- package/dist/resilience/alert-channels.d.ts +39 -0
- package/dist/resilience/alert-errors.interceptor.d.ts +10 -0
- package/dist/resilience/alert-on-failure.decorator.d.ts +10 -0
- package/dist/resilience/alert.service.d.ts +77 -0
- package/dist/resilience/index.cjs +863 -0
- package/dist/resilience/index.d.ts +18 -0
- package/dist/resilience/index.js +863 -0
- package/dist/resilience/memory-alert-store.d.ts +26 -0
- package/dist/resilience/provider-health.controller.d.ts +14 -0
- package/dist/resilience/provider-unavailable.exception.d.ts +11 -0
- package/dist/resilience/resilience.module.d.ts +34 -0
- package/dist/resilience/resilience.options.d.ts +28 -0
- package/dist/resilience/resilience.types.d.ts +167 -0
- package/dist/resilience/resilient-fetch.d.ts +38 -0
- package/dist/resilience/runtime.d.ts +24 -0
- package/dist/resilience/typeorm/alert.entity.d.ts +21 -0
- package/dist/resilience/typeorm/index.cjs +102 -0
- package/dist/resilience/typeorm/index.d.ts +3 -0
- package/dist/resilience/typeorm/index.js +102 -0
- package/dist/resilience/typeorm/typeorm-alert-store.d.ts +39 -0
- package/dist/resilience/validate-destination.d.ts +63 -0
- package/dist/response/index.cjs +3 -3
- package/dist/response/index.js +2 -2
- package/dist/scheduling/cron-lock.service.d.ts +36 -0
- package/dist/scheduling/cron-unico.decorator.d.ts +27 -0
- package/dist/scheduling/fallback.store.d.ts +34 -0
- package/dist/scheduling/index.cjs +392 -0
- package/dist/scheduling/index.d.ts +18 -0
- package/dist/scheduling/index.js +392 -0
- package/dist/scheduling/lock-store.port.d.ts +19 -0
- package/dist/scheduling/memory.store.d.ts +15 -0
- package/dist/scheduling/redis.module.d.ts +31 -0
- package/dist/scheduling/redis.store.d.ts +24 -0
- package/dist/scheduling/scheduling.module.d.ts +24 -0
- package/dist/scheduling/scheduling.options.d.ts +27 -0
- package/dist/scheduling/sql.store.d.ts +26 -0
- package/dist/secrets/index.cjs +274 -0
- package/dist/secrets/index.d.ts +8 -0
- package/dist/secrets/index.js +274 -0
- package/dist/secrets/secrets.errors.d.ts +6 -0
- package/dist/secrets/secrets.module.d.ts +21 -0
- package/dist/secrets/secrets.options.d.ts +32 -0
- package/dist/secrets/secrets.service.d.ts +54 -0
- package/dist/secrets/secrets.transformer.d.ts +33 -0
- package/dist/security/hash.d.ts +8 -0
- package/dist/security/index.cjs +27 -35
- package/dist/security/index.d.ts +5 -0
- package/dist/security/index.js +24 -32
- package/dist/security/mask.d.ts +22 -0
- package/dist/security/signed-grant.d.ts +30 -0
- package/dist/storage/index.cjs +2 -2
- package/dist/storage/index.js +1 -1
- package/dist/stripe/index.cjs +7 -7
- package/dist/stripe/index.js +1 -1
- package/dist/telegram/index.cjs +2 -2
- package/dist/telegram/index.js +1 -1
- package/dist/tenancy/app-role.d.ts +24 -0
- package/dist/tenancy/db-helpers.d.ts +12 -0
- package/dist/tenancy/index.cjs +205 -0
- package/dist/tenancy/index.d.ts +14 -0
- package/dist/tenancy/index.js +205 -0
- package/dist/tenancy/pg/index.cjs +34 -0
- package/dist/tenancy/pg/index.d.ts +2 -0
- package/dist/tenancy/pg/index.js +34 -0
- package/dist/tenancy/pg/with-tenant.d.ts +23 -0
- package/dist/tenancy/request-context.d.ts +18 -0
- package/dist/tenancy/rls-guardrail.d.ts +38 -0
- package/dist/tenancy/scope.d.ts +5 -0
- package/dist/tenancy/tenancy.errors.d.ts +5 -0
- package/dist/tenancy/tenancy.middleware.d.ts +8 -0
- package/dist/tenancy/tenancy.module.d.ts +37 -0
- package/dist/tenancy/tenancy.options.d.ts +34 -0
- package/dist/tenancy/typeorm/index.cjs +41 -0
- package/dist/tenancy/typeorm/index.d.ts +2 -0
- package/dist/tenancy/typeorm/index.js +41 -0
- package/dist/tenancy/typeorm/with-tenant.d.ts +23 -0
- package/dist/tiktok/index.cjs +3 -3
- package/dist/tiktok/index.js +1 -1
- package/dist/tracking/index.cjs +3 -3
- package/dist/tracking/index.js +2 -2
- package/dist/umami/index.cjs +4 -4
- package/dist/umami/index.js +1 -1
- package/dist/whatsapp/index.cjs +2 -2
- package/dist/whatsapp/index.js +1 -1
- package/package.json +108 -3
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory fake of the Google endpoints `GoogleBusinessService` uses: OAuth
|
|
3
|
+
* token, account management, business information, verifications and the v4
|
|
4
|
+
* posts/reviews/media. Hand `sim.fetch` to `options.fetchImpl`; no server, no
|
|
5
|
+
* port. Routes match on host + path, so it works with the default URLs.
|
|
6
|
+
*
|
|
7
|
+
* Behaviours worth knowing (they mirror what Google does, simplified):
|
|
8
|
+
* - A code is valid once; `code-*` codes are accepted by default (`validCodes` to restrict).
|
|
9
|
+
* - Calls without a live bearer answer 401 UNAUTHENTICATED (`expireAccessTokens()` to force it).
|
|
10
|
+
* - `revokeRefreshToken()` makes the refresh grant answer `invalid_grant`.
|
|
11
|
+
* - Creating a location whose title+phone (or storeCode) exists answers 409 ALREADY_EXISTS.
|
|
12
|
+
* - `unverifiableTitles` makes verification calls fail with FAILED_PRECONDITION.
|
|
13
|
+
* - `failNext(match, status, body)` injects errors (quota 429, 503…) for the next N matching calls.
|
|
14
|
+
*/
|
|
15
|
+
type Json = Record<string, any>;
|
|
16
|
+
export interface GoogleSimulatorOptions {
|
|
17
|
+
/** Codes the token endpoint accepts. Default: any string starting with `code-`. */
|
|
18
|
+
validCodes?: string[];
|
|
19
|
+
/** Whether the first grant returns a refresh token. Default true. */
|
|
20
|
+
issueRefreshToken?: boolean;
|
|
21
|
+
/** Titles Google refuses to verify. */
|
|
22
|
+
unverifiableTitles?: string[];
|
|
23
|
+
expiresInSeconds?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface SimRequest {
|
|
26
|
+
method: string;
|
|
27
|
+
url: string;
|
|
28
|
+
host: string;
|
|
29
|
+
path: string;
|
|
30
|
+
headers: Record<string, string>;
|
|
31
|
+
body: any;
|
|
32
|
+
}
|
|
33
|
+
export interface GoogleSimulator {
|
|
34
|
+
fetch: (input: string, init?: RequestInit) => Promise<Response>;
|
|
35
|
+
requests: SimRequest[];
|
|
36
|
+
/** Requests whose `host+path` contains/matches `match`. */
|
|
37
|
+
callsTo(match: string | RegExp): SimRequest[];
|
|
38
|
+
failNext(match: string | RegExp, status: number, body?: Json, times?: number): void;
|
|
39
|
+
expireAccessTokens(): void;
|
|
40
|
+
revokeRefreshToken(): void;
|
|
41
|
+
/** Make a pending verification finish (`COMPLETED`) or fail. */
|
|
42
|
+
resolveVerification(locationId: string, state: 'COMPLETED' | 'FAILED'): void;
|
|
43
|
+
addReview(accountId: string, locationId: string, review: {
|
|
44
|
+
autor?: string;
|
|
45
|
+
estrellas?: 1 | 2 | 3 | 4 | 5;
|
|
46
|
+
comentario?: string;
|
|
47
|
+
}): string;
|
|
48
|
+
/** Pre-existing location in the account (for `claim` / linking). */
|
|
49
|
+
seedLocation(accountId: string, location: Json): string;
|
|
50
|
+
readonly state: {
|
|
51
|
+
accounts: Json[];
|
|
52
|
+
locations: Map<string, Json>;
|
|
53
|
+
verifications: Json[];
|
|
54
|
+
posts: Json[];
|
|
55
|
+
media: Json[];
|
|
56
|
+
reviews: Map<string, Json>;
|
|
57
|
+
pins: Map<string, string>;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export declare function createGoogleSimulator(opts?: GoogleSimulatorOptions): GoogleSimulator;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type NextLike, type PathRule } from './http.types.js';
|
|
2
|
+
export interface BodyLimitsOptions {
|
|
3
|
+
/** Default JSON body limit (body-parser syntax: `'1mb'`, `'200kb'` or bytes). Express' own default is 100kb. */
|
|
4
|
+
default?: string | number;
|
|
5
|
+
/** Bigger (or smaller) limits for specific routes. First match wins. */
|
|
6
|
+
routes?: {
|
|
7
|
+
match: PathRule;
|
|
8
|
+
limit: string | number;
|
|
9
|
+
}[];
|
|
10
|
+
}
|
|
11
|
+
export declare const DEFAULT_BODY_LIMIT = "1mb";
|
|
12
|
+
/** Builds a JSON body parser middleware for a limit. Injectable for tests; defaults to `express.json`. */
|
|
13
|
+
export type JsonParserFactory = (limit: string | number) => (req: any, res: any, next: NextLike) => void;
|
|
14
|
+
/**
|
|
15
|
+
* Per-route JSON limits. A middleware per distinct limit parses first for matching routes (body-parser
|
|
16
|
+
* skips a request whose body is already parsed), then the default parser registered with
|
|
17
|
+
* `app.useBodyParser('json', { limit })` handles everything else. Call before `app.listen()`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function applyBodyLimits(app: {
|
|
20
|
+
use(mw: (req: any, res: any, next: NextLike) => void): unknown;
|
|
21
|
+
useBodyParser?: (type: string, options: {
|
|
22
|
+
limit: string | number;
|
|
23
|
+
}) => unknown;
|
|
24
|
+
}, options: BodyLimitsOptions, factory?: JsonParserFactory): void;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Minimal structural view of an HTTP request (Express/Fastify) so this module imports no HTTP lib. */
|
|
2
|
+
export interface HttpRequestLike {
|
|
3
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
4
|
+
ips?: string[];
|
|
5
|
+
ip?: string;
|
|
6
|
+
path?: string;
|
|
7
|
+
url?: string;
|
|
8
|
+
originalUrl?: string;
|
|
9
|
+
method?: string;
|
|
10
|
+
user?: {
|
|
11
|
+
sub?: string;
|
|
12
|
+
} & Record<string, unknown>;
|
|
13
|
+
}
|
|
14
|
+
/** Minimal structural view of an HTTP response. */
|
|
15
|
+
export interface HttpResponseLike {
|
|
16
|
+
status(code: number): HttpResponseLike;
|
|
17
|
+
json(body: unknown): unknown;
|
|
18
|
+
setHeader(name: string, value: string | number): unknown;
|
|
19
|
+
}
|
|
20
|
+
export type NextLike = (err?: unknown) => void;
|
|
21
|
+
/** Path without query string. */
|
|
22
|
+
export declare function pathOf(req: HttpRequestLike): string;
|
|
23
|
+
export declare function headerOf(req: HttpRequestLike, name: string): string | undefined;
|
|
24
|
+
/** A path rule: exact string, string prefix ending in `*`, or a RegExp. */
|
|
25
|
+
export type PathRule = string | RegExp;
|
|
26
|
+
export declare function matchesPath(rule: PathRule, path: string): boolean;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
var _chunkIVWPA6QHcjs = require('../chunk-IVWPA6QH.cjs');
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
var _chunkLRX7AMSScjs = require('../chunk-LRX7AMSS.cjs');
|
|
14
|
+
|
|
15
|
+
// src/hardening/rate-limit.port.ts
|
|
16
|
+
var RATE_LIMIT_STORE = /* @__PURE__ */ Symbol("NESTKIT_RATE_LIMIT_STORE");
|
|
17
|
+
|
|
18
|
+
// src/hardening/memory-rate-limit.store.ts
|
|
19
|
+
var MemoryRateLimitStore = class {
|
|
20
|
+
constructor(now = Date.now, maxKeys = 5e3) {
|
|
21
|
+
this.now = now;
|
|
22
|
+
this.maxKeys = maxKeys;
|
|
23
|
+
this.windows = /* @__PURE__ */ new Map();
|
|
24
|
+
}
|
|
25
|
+
async hit(key, windowMs) {
|
|
26
|
+
const t = this.now();
|
|
27
|
+
if (this.windows.size > this.maxKeys) this.purge(t);
|
|
28
|
+
let w = this.windows.get(key);
|
|
29
|
+
if (!w || t - w.start >= w.windowMs) {
|
|
30
|
+
w = { start: t, count: 0, windowMs };
|
|
31
|
+
this.windows.set(key, w);
|
|
32
|
+
}
|
|
33
|
+
w.count++;
|
|
34
|
+
return { count: w.count, resetMs: Math.max(0, w.start + w.windowMs - t) };
|
|
35
|
+
}
|
|
36
|
+
purge(t) {
|
|
37
|
+
for (const [k, w] of this.windows) if (t - w.start >= w.windowMs) this.windows.delete(k);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// src/hardening/redis-rate-limit.store.ts
|
|
42
|
+
var LUA_HIT = `
|
|
43
|
+
local c = redis.call('INCR', KEYS[1])
|
|
44
|
+
if c == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
|
|
45
|
+
local t = redis.call('PTTL', KEYS[1])
|
|
46
|
+
if t < 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]); t = tonumber(ARGV[1]) end
|
|
47
|
+
return {c, t}`;
|
|
48
|
+
var RedisRateLimitStore = class {
|
|
49
|
+
constructor(options, fallback = new MemoryRateLimitStore()) {
|
|
50
|
+
this.options = options;
|
|
51
|
+
this.fallback = fallback;
|
|
52
|
+
this.prefix = _nullishCoalesce(options.prefix, () => ( "nestkit:rl:"));
|
|
53
|
+
}
|
|
54
|
+
async hit(key, windowMs) {
|
|
55
|
+
try {
|
|
56
|
+
const ms = Math.max(1, Math.ceil(windowMs));
|
|
57
|
+
const [count, ttl] = await this.options.client.eval(
|
|
58
|
+
LUA_HIT,
|
|
59
|
+
1,
|
|
60
|
+
`${this.prefix}${ms}:${key}`,
|
|
61
|
+
ms
|
|
62
|
+
);
|
|
63
|
+
return { count: Number(count), resetMs: Number(ttl) };
|
|
64
|
+
} catch (err) {
|
|
65
|
+
_optionalChain([this, 'access', _ => _.options, 'access', _2 => _2.onError, 'optionalCall', _3 => _3(err)]);
|
|
66
|
+
return this.fallback.hit(key, windowMs);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// src/hardening/rate-limit.options.ts
|
|
72
|
+
var RATE_LIMIT_OPTIONS = /* @__PURE__ */ Symbol("NESTKIT_RATE_LIMIT_OPTIONS");
|
|
73
|
+
var RATE_LIMIT_META = "nestkit:rate-limit";
|
|
74
|
+
var RATE_LIMIT_SKIP_META = "nestkit:rate-limit-skip";
|
|
75
|
+
|
|
76
|
+
// src/hardening/rate-limit.decorator.ts
|
|
77
|
+
var _common = require('@nestjs/common');
|
|
78
|
+
var RateLimit = (limit) => _common.SetMetadata.call(void 0, RATE_LIMIT_META, limit);
|
|
79
|
+
var SkipRateLimit = () => _common.SetMetadata.call(void 0, RATE_LIMIT_SKIP_META, true);
|
|
80
|
+
|
|
81
|
+
// src/hardening/rate-limit.guard.ts
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
var _core = require('@nestjs/core');
|
|
89
|
+
var RateLimitGuard = class {
|
|
90
|
+
constructor(options, reflector) {
|
|
91
|
+
this.options = options;
|
|
92
|
+
this.reflector = reflector;
|
|
93
|
+
this.store = _nullishCoalesce(options.store, () => ( new MemoryRateLimitStore()));
|
|
94
|
+
}
|
|
95
|
+
async canActivate(context) {
|
|
96
|
+
if (context.getType() !== "http") return true;
|
|
97
|
+
const targets = [context.getHandler(), context.getClass()];
|
|
98
|
+
if (this.reflector.getAllAndOverride(RATE_LIMIT_SKIP_META, targets)) return true;
|
|
99
|
+
const http = context.switchToHttp();
|
|
100
|
+
const req = http.getRequest();
|
|
101
|
+
const res = http.getResponse();
|
|
102
|
+
const path = _chunkIVWPA6QHcjs.pathOf.call(void 0, req);
|
|
103
|
+
if (_optionalChain([this, 'access', _4 => _4.options, 'access', _5 => _5.skip, 'optionalCall', _6 => _6(req)])) return true;
|
|
104
|
+
if (_optionalChain([this, 'access', _7 => _7.options, 'access', _8 => _8.skipPaths, 'optionalAccess', _9 => _9.some, 'call', _10 => _10((r) => _chunkIVWPA6QHcjs.matchesPath.call(void 0, r, path))])) return true;
|
|
105
|
+
const own = this.reflector.getAllAndOverride(RATE_LIMIT_META, targets);
|
|
106
|
+
const max = _nullishCoalesce(_optionalChain([own, 'optionalAccess', _11 => _11.max]), () => ( this.options.max));
|
|
107
|
+
const windowMs = _nullishCoalesce(_optionalChain([own, 'optionalAccess', _12 => _12.windowMs]), () => ( this.options.windowMs));
|
|
108
|
+
const who = this.options.key ? await this.options.key(req) : `ip:${_chunkIVWPA6QHcjs.trustedIp.call(void 0, req, this.options)}`;
|
|
109
|
+
const perRoute = own !== void 0 || this.options.shared === false;
|
|
110
|
+
const scope = perRoute ? `${context.getClass().name}.${context.getHandler().name}` : "all";
|
|
111
|
+
const { count, resetMs } = await this.store.hit(`${scope}:${who}`, windowMs);
|
|
112
|
+
const retryAfter = Math.max(1, Math.ceil(resetMs / 1e3));
|
|
113
|
+
if (this.options.headers !== false) {
|
|
114
|
+
res.setHeader("X-RateLimit-Limit", max);
|
|
115
|
+
res.setHeader("X-RateLimit-Remaining", Math.max(0, max - count));
|
|
116
|
+
res.setHeader("X-RateLimit-Reset", retryAfter);
|
|
117
|
+
}
|
|
118
|
+
if (count > max) {
|
|
119
|
+
res.setHeader("Retry-After", retryAfter);
|
|
120
|
+
throw new (0, _common.HttpException)(
|
|
121
|
+
{
|
|
122
|
+
success: false,
|
|
123
|
+
error: {
|
|
124
|
+
code: _nullishCoalesce(this.options.code, () => ( "RATE_LIMITED")),
|
|
125
|
+
message: _nullishCoalesce(this.options.message, () => ( "Too many requests. Try again later.")),
|
|
126
|
+
retryAfter
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
_common.HttpStatus.TOO_MANY_REQUESTS
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
RateLimitGuard = exports.RateLimitGuard = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
|
|
136
|
+
_common.Injectable.call(void 0, ),
|
|
137
|
+
_chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, RATE_LIMIT_OPTIONS))
|
|
138
|
+
], RateLimitGuard);
|
|
139
|
+
|
|
140
|
+
// src/hardening/rate-limit.module.ts
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
var RateLimitModule = class {
|
|
144
|
+
static forRoot(options) {
|
|
145
|
+
return RateLimitModule.build([{ provide: RATE_LIMIT_OPTIONS, useValue: options }], [], options.global);
|
|
146
|
+
}
|
|
147
|
+
static forRootAsync(config) {
|
|
148
|
+
return RateLimitModule.build(
|
|
149
|
+
[{ provide: RATE_LIMIT_OPTIONS, useFactory: config.useFactory, inject: _nullishCoalesce(config.inject, () => ( [])) }],
|
|
150
|
+
_nullishCoalesce(config.imports, () => ( [])),
|
|
151
|
+
config.global
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
static build(providers, imports, global = true) {
|
|
155
|
+
const all = [...providers, RateLimitGuard];
|
|
156
|
+
if (global) all.push({ provide: _core.APP_GUARD, useExisting: RateLimitGuard });
|
|
157
|
+
return { module: RateLimitModule, imports, providers: all, exports: [RATE_LIMIT_OPTIONS, RateLimitGuard] };
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
RateLimitModule = exports.RateLimitModule = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
|
|
161
|
+
_common.Module.call(void 0, {})
|
|
162
|
+
], RateLimitModule);
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
exports.DEFAULT_BODY_LIMIT = _chunkIVWPA6QHcjs.DEFAULT_BODY_LIMIT; exports.MemoryRateLimitStore = MemoryRateLimitStore; exports.RATE_LIMIT_OPTIONS = RATE_LIMIT_OPTIONS; exports.RATE_LIMIT_STORE = RATE_LIMIT_STORE; exports.RateLimit = RateLimit; exports.RateLimitGuard = RateLimitGuard; exports.RateLimitModule = RateLimitModule; exports.RedisRateLimitStore = RedisRateLimitStore; exports.SkipRateLimit = SkipRateLimit; exports.applyBodyLimits = _chunkIVWPA6QHcjs.applyBodyLimits; exports.applyTrustProxy = _chunkIVWPA6QHcjs.applyTrustProxy; exports.matchesPath = _chunkIVWPA6QHcjs.matchesPath; exports.originSecretMiddleware = _chunkIVWPA6QHcjs.originSecretMiddleware; exports.pathOf = _chunkIVWPA6QHcjs.pathOf; exports.trustedIp = _chunkIVWPA6QHcjs.trustedIp;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type { HttpRequestLike, HttpResponseLike, NextLike, PathRule } from './http.types.js';
|
|
2
|
+
export { matchesPath, pathOf } from './http.types.js';
|
|
3
|
+
export { trustedIp, applyTrustProxy } from './trust-proxy.js';
|
|
4
|
+
export type { TrustedIpOptions, TrustProxyValue } from './trust-proxy.js';
|
|
5
|
+
export { originSecretMiddleware } from './origin-secret.js';
|
|
6
|
+
export type { OriginSecretOptions } from './origin-secret.js';
|
|
7
|
+
export { applyBodyLimits, DEFAULT_BODY_LIMIT } from './body-limits.js';
|
|
8
|
+
export type { BodyLimitsOptions, JsonParserFactory } from './body-limits.js';
|
|
9
|
+
export { RATE_LIMIT_STORE } from './rate-limit.port.js';
|
|
10
|
+
export type { RateLimitStorePort, RateLimitHit } from './rate-limit.port.js';
|
|
11
|
+
export { MemoryRateLimitStore } from './memory-rate-limit.store.js';
|
|
12
|
+
export { RedisRateLimitStore } from './redis-rate-limit.store.js';
|
|
13
|
+
export type { RedisEvalClient, RedisRateLimitStoreOptions } from './redis-rate-limit.store.js';
|
|
14
|
+
export { RATE_LIMIT_OPTIONS } from './rate-limit.options.js';
|
|
15
|
+
export type { RateLimitOptions } from './rate-limit.options.js';
|
|
16
|
+
export { RateLimit, SkipRateLimit } from './rate-limit.decorator.js';
|
|
17
|
+
export type { RouteRateLimit } from './rate-limit.decorator.js';
|
|
18
|
+
export { RateLimitGuard } from './rate-limit.guard.js';
|
|
19
|
+
export { RateLimitModule } from './rate-limit.module.js';
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_BODY_LIMIT,
|
|
3
|
+
applyBodyLimits,
|
|
4
|
+
applyTrustProxy,
|
|
5
|
+
matchesPath,
|
|
6
|
+
originSecretMiddleware,
|
|
7
|
+
pathOf,
|
|
8
|
+
trustedIp
|
|
9
|
+
} from "../chunk-WFCQDOSN.js";
|
|
10
|
+
import {
|
|
11
|
+
__decorateClass,
|
|
12
|
+
__decorateParam
|
|
13
|
+
} from "../chunk-D3DDJWUD.js";
|
|
14
|
+
|
|
15
|
+
// src/hardening/rate-limit.port.ts
|
|
16
|
+
var RATE_LIMIT_STORE = /* @__PURE__ */ Symbol("NESTKIT_RATE_LIMIT_STORE");
|
|
17
|
+
|
|
18
|
+
// src/hardening/memory-rate-limit.store.ts
|
|
19
|
+
var MemoryRateLimitStore = class {
|
|
20
|
+
constructor(now = Date.now, maxKeys = 5e3) {
|
|
21
|
+
this.now = now;
|
|
22
|
+
this.maxKeys = maxKeys;
|
|
23
|
+
this.windows = /* @__PURE__ */ new Map();
|
|
24
|
+
}
|
|
25
|
+
async hit(key, windowMs) {
|
|
26
|
+
const t = this.now();
|
|
27
|
+
if (this.windows.size > this.maxKeys) this.purge(t);
|
|
28
|
+
let w = this.windows.get(key);
|
|
29
|
+
if (!w || t - w.start >= w.windowMs) {
|
|
30
|
+
w = { start: t, count: 0, windowMs };
|
|
31
|
+
this.windows.set(key, w);
|
|
32
|
+
}
|
|
33
|
+
w.count++;
|
|
34
|
+
return { count: w.count, resetMs: Math.max(0, w.start + w.windowMs - t) };
|
|
35
|
+
}
|
|
36
|
+
purge(t) {
|
|
37
|
+
for (const [k, w] of this.windows) if (t - w.start >= w.windowMs) this.windows.delete(k);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// src/hardening/redis-rate-limit.store.ts
|
|
42
|
+
var LUA_HIT = `
|
|
43
|
+
local c = redis.call('INCR', KEYS[1])
|
|
44
|
+
if c == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
|
|
45
|
+
local t = redis.call('PTTL', KEYS[1])
|
|
46
|
+
if t < 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]); t = tonumber(ARGV[1]) end
|
|
47
|
+
return {c, t}`;
|
|
48
|
+
var RedisRateLimitStore = class {
|
|
49
|
+
constructor(options, fallback = new MemoryRateLimitStore()) {
|
|
50
|
+
this.options = options;
|
|
51
|
+
this.fallback = fallback;
|
|
52
|
+
this.prefix = options.prefix ?? "nestkit:rl:";
|
|
53
|
+
}
|
|
54
|
+
async hit(key, windowMs) {
|
|
55
|
+
try {
|
|
56
|
+
const ms = Math.max(1, Math.ceil(windowMs));
|
|
57
|
+
const [count, ttl] = await this.options.client.eval(
|
|
58
|
+
LUA_HIT,
|
|
59
|
+
1,
|
|
60
|
+
`${this.prefix}${ms}:${key}`,
|
|
61
|
+
ms
|
|
62
|
+
);
|
|
63
|
+
return { count: Number(count), resetMs: Number(ttl) };
|
|
64
|
+
} catch (err) {
|
|
65
|
+
this.options.onError?.(err);
|
|
66
|
+
return this.fallback.hit(key, windowMs);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// src/hardening/rate-limit.options.ts
|
|
72
|
+
var RATE_LIMIT_OPTIONS = /* @__PURE__ */ Symbol("NESTKIT_RATE_LIMIT_OPTIONS");
|
|
73
|
+
var RATE_LIMIT_META = "nestkit:rate-limit";
|
|
74
|
+
var RATE_LIMIT_SKIP_META = "nestkit:rate-limit-skip";
|
|
75
|
+
|
|
76
|
+
// src/hardening/rate-limit.decorator.ts
|
|
77
|
+
import { SetMetadata } from "@nestjs/common";
|
|
78
|
+
var RateLimit = (limit) => SetMetadata(RATE_LIMIT_META, limit);
|
|
79
|
+
var SkipRateLimit = () => SetMetadata(RATE_LIMIT_SKIP_META, true);
|
|
80
|
+
|
|
81
|
+
// src/hardening/rate-limit.guard.ts
|
|
82
|
+
import {
|
|
83
|
+
HttpException,
|
|
84
|
+
HttpStatus,
|
|
85
|
+
Inject,
|
|
86
|
+
Injectable
|
|
87
|
+
} from "@nestjs/common";
|
|
88
|
+
import "@nestjs/core";
|
|
89
|
+
var RateLimitGuard = class {
|
|
90
|
+
constructor(options, reflector) {
|
|
91
|
+
this.options = options;
|
|
92
|
+
this.reflector = reflector;
|
|
93
|
+
this.store = options.store ?? new MemoryRateLimitStore();
|
|
94
|
+
}
|
|
95
|
+
async canActivate(context) {
|
|
96
|
+
if (context.getType() !== "http") return true;
|
|
97
|
+
const targets = [context.getHandler(), context.getClass()];
|
|
98
|
+
if (this.reflector.getAllAndOverride(RATE_LIMIT_SKIP_META, targets)) return true;
|
|
99
|
+
const http = context.switchToHttp();
|
|
100
|
+
const req = http.getRequest();
|
|
101
|
+
const res = http.getResponse();
|
|
102
|
+
const path = pathOf(req);
|
|
103
|
+
if (this.options.skip?.(req)) return true;
|
|
104
|
+
if (this.options.skipPaths?.some((r) => matchesPath(r, path))) return true;
|
|
105
|
+
const own = this.reflector.getAllAndOverride(RATE_LIMIT_META, targets);
|
|
106
|
+
const max = own?.max ?? this.options.max;
|
|
107
|
+
const windowMs = own?.windowMs ?? this.options.windowMs;
|
|
108
|
+
const who = this.options.key ? await this.options.key(req) : `ip:${trustedIp(req, this.options)}`;
|
|
109
|
+
const perRoute = own !== void 0 || this.options.shared === false;
|
|
110
|
+
const scope = perRoute ? `${context.getClass().name}.${context.getHandler().name}` : "all";
|
|
111
|
+
const { count, resetMs } = await this.store.hit(`${scope}:${who}`, windowMs);
|
|
112
|
+
const retryAfter = Math.max(1, Math.ceil(resetMs / 1e3));
|
|
113
|
+
if (this.options.headers !== false) {
|
|
114
|
+
res.setHeader("X-RateLimit-Limit", max);
|
|
115
|
+
res.setHeader("X-RateLimit-Remaining", Math.max(0, max - count));
|
|
116
|
+
res.setHeader("X-RateLimit-Reset", retryAfter);
|
|
117
|
+
}
|
|
118
|
+
if (count > max) {
|
|
119
|
+
res.setHeader("Retry-After", retryAfter);
|
|
120
|
+
throw new HttpException(
|
|
121
|
+
{
|
|
122
|
+
success: false,
|
|
123
|
+
error: {
|
|
124
|
+
code: this.options.code ?? "RATE_LIMITED",
|
|
125
|
+
message: this.options.message ?? "Too many requests. Try again later.",
|
|
126
|
+
retryAfter
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
HttpStatus.TOO_MANY_REQUESTS
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
RateLimitGuard = __decorateClass([
|
|
136
|
+
Injectable(),
|
|
137
|
+
__decorateParam(0, Inject(RATE_LIMIT_OPTIONS))
|
|
138
|
+
], RateLimitGuard);
|
|
139
|
+
|
|
140
|
+
// src/hardening/rate-limit.module.ts
|
|
141
|
+
import { Module } from "@nestjs/common";
|
|
142
|
+
import { APP_GUARD } from "@nestjs/core";
|
|
143
|
+
var RateLimitModule = class {
|
|
144
|
+
static forRoot(options) {
|
|
145
|
+
return RateLimitModule.build([{ provide: RATE_LIMIT_OPTIONS, useValue: options }], [], options.global);
|
|
146
|
+
}
|
|
147
|
+
static forRootAsync(config) {
|
|
148
|
+
return RateLimitModule.build(
|
|
149
|
+
[{ provide: RATE_LIMIT_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] }],
|
|
150
|
+
config.imports ?? [],
|
|
151
|
+
config.global
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
static build(providers, imports, global = true) {
|
|
155
|
+
const all = [...providers, RateLimitGuard];
|
|
156
|
+
if (global) all.push({ provide: APP_GUARD, useExisting: RateLimitGuard });
|
|
157
|
+
return { module: RateLimitModule, imports, providers: all, exports: [RATE_LIMIT_OPTIONS, RateLimitGuard] };
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
RateLimitModule = __decorateClass([
|
|
161
|
+
Module({})
|
|
162
|
+
], RateLimitModule);
|
|
163
|
+
export {
|
|
164
|
+
DEFAULT_BODY_LIMIT,
|
|
165
|
+
MemoryRateLimitStore,
|
|
166
|
+
RATE_LIMIT_OPTIONS,
|
|
167
|
+
RATE_LIMIT_STORE,
|
|
168
|
+
RateLimit,
|
|
169
|
+
RateLimitGuard,
|
|
170
|
+
RateLimitModule,
|
|
171
|
+
RedisRateLimitStore,
|
|
172
|
+
SkipRateLimit,
|
|
173
|
+
applyBodyLimits,
|
|
174
|
+
applyTrustProxy,
|
|
175
|
+
matchesPath,
|
|
176
|
+
originSecretMiddleware,
|
|
177
|
+
pathOf,
|
|
178
|
+
trustedIp
|
|
179
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { RateLimitHit, RateLimitStorePort } from './rate-limit.port.js';
|
|
2
|
+
/** In-process fixed window. Right for a single instance; with several, use the Redis store. */
|
|
3
|
+
export declare class MemoryRateLimitStore implements RateLimitStorePort {
|
|
4
|
+
private readonly now;
|
|
5
|
+
private readonly maxKeys;
|
|
6
|
+
private readonly windows;
|
|
7
|
+
constructor(now?: () => number, maxKeys?: number);
|
|
8
|
+
hit(key: string, windowMs: number): Promise<RateLimitHit>;
|
|
9
|
+
private purge;
|
|
10
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type HttpRequestLike, type HttpResponseLike, type NextLike, type PathRule } from './http.types.js';
|
|
2
|
+
export interface OriginSecretOptions {
|
|
3
|
+
/** Header the edge adds to every request (e.g. a CDN transform rule). */
|
|
4
|
+
header: string;
|
|
5
|
+
/** Expected value. Empty/undefined disables the check entirely (dev, tests, before cut-over). */
|
|
6
|
+
value: string | undefined;
|
|
7
|
+
/** Paths that skip the check (probes and external monitors). */
|
|
8
|
+
exclude?: PathRule[];
|
|
9
|
+
/**
|
|
10
|
+
* Additional secrets that only open a subset of routes (e.g. a server-side storefront that bypasses the CDN).
|
|
11
|
+
* Each entry: its own header + value and the paths it opens.
|
|
12
|
+
*/
|
|
13
|
+
scoped?: {
|
|
14
|
+
header: string;
|
|
15
|
+
value: string | undefined;
|
|
16
|
+
paths: PathRule[];
|
|
17
|
+
}[];
|
|
18
|
+
/** Rejection status code (default 403). */
|
|
19
|
+
status?: number;
|
|
20
|
+
/** Error body code (default `UNTRUSTED_ORIGIN`). */
|
|
21
|
+
code?: string;
|
|
22
|
+
message?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Only serves requests that really come from the trusted edge: without the shared secret header
|
|
26
|
+
* (or with another value) it answers 403 before anything else runs. Constant-time comparison.
|
|
27
|
+
* Mount it as the first middleware: `app.use(originSecretMiddleware({...}))`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function originSecretMiddleware(options: OriginSecretOptions): (req: HttpRequestLike, res: HttpResponseLike, next: NextLike) => void;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface RouteRateLimit {
|
|
2
|
+
max: number;
|
|
3
|
+
windowMs: number;
|
|
4
|
+
}
|
|
5
|
+
/** A route (or controller) with its own budget and its own counter, apart from the shared one. */
|
|
6
|
+
export declare const RateLimit: (limit: RouteRateLimit) => import("@nestjs/common").CustomDecorator<string>;
|
|
7
|
+
/** The route is not rate limited. */
|
|
8
|
+
export declare const SkipRateLimit: () => import("@nestjs/common").CustomDecorator<string>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type CanActivate, type ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import { type RateLimitOptions } from './rate-limit.options.js';
|
|
4
|
+
/**
|
|
5
|
+
* Fixed-window rate limit. Over the cap it answers 429 with `Retry-After` (seconds, standard) and the
|
|
6
|
+
* `RATE_LIMITED` error code. Routes with `@RateLimit({max, windowMs})` get their own counter and cap;
|
|
7
|
+
* `@SkipRateLimit()` exempts a route.
|
|
8
|
+
*
|
|
9
|
+
* Note: as an `APP_GUARD` it runs before guards registered later (e.g. the app's auth guard), so
|
|
10
|
+
* `req.user` is not set yet; derive the key from the token yourself in `key(req)` if you need per-user.
|
|
11
|
+
*/
|
|
12
|
+
export declare class RateLimitGuard implements CanActivate {
|
|
13
|
+
private readonly options;
|
|
14
|
+
private readonly reflector;
|
|
15
|
+
private readonly store;
|
|
16
|
+
constructor(options: RateLimitOptions, reflector: Reflector);
|
|
17
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
18
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type DynamicModule } from '@nestjs/common';
|
|
2
|
+
import { type RateLimitOptions } from './rate-limit.options.js';
|
|
3
|
+
/**
|
|
4
|
+
* ```ts
|
|
5
|
+
* RateLimitModule.forRoot({
|
|
6
|
+
* windowMs: 60_000, max: 300,
|
|
7
|
+
* trustedHeaders: ['x-client-ip'], // set by your edge, see originSecret
|
|
8
|
+
* store: new RedisRateLimitStore({ client: redis }), // omit for in-memory
|
|
9
|
+
* key: (req) => userFromToken(req) ?? `ip:${req.ip}`,
|
|
10
|
+
* })
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export declare class RateLimitModule {
|
|
14
|
+
static forRoot(options: RateLimitOptions): DynamicModule;
|
|
15
|
+
static forRootAsync(config: {
|
|
16
|
+
imports?: any[];
|
|
17
|
+
inject?: any[];
|
|
18
|
+
useFactory: (...args: any[]) => RateLimitOptions | Promise<RateLimitOptions>;
|
|
19
|
+
/** Whether to register the APP_GUARD (default true). */
|
|
20
|
+
global?: boolean;
|
|
21
|
+
}): DynamicModule;
|
|
22
|
+
private static build;
|
|
23
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { RateLimitStorePort } from './rate-limit.port.js';
|
|
2
|
+
import type { HttpRequestLike, PathRule } from './http.types.js';
|
|
3
|
+
import type { TrustedIpOptions } from './trust-proxy.js';
|
|
4
|
+
export interface RateLimitOptions extends TrustedIpOptions {
|
|
5
|
+
/** Window length in ms. */
|
|
6
|
+
windowMs: number;
|
|
7
|
+
/** Max requests per key per window. */
|
|
8
|
+
max: number;
|
|
9
|
+
/** Counter backend (default: in-memory). */
|
|
10
|
+
store?: RateLimitStorePort;
|
|
11
|
+
/**
|
|
12
|
+
* Who is being counted. Default: `ip:<trusted ip>`. Typical override: `u:<userId>` when authenticated,
|
|
13
|
+
* falling back to the IP. Called once per request.
|
|
14
|
+
*/
|
|
15
|
+
key?: (req: HttpRequestLike) => string | Promise<string>;
|
|
16
|
+
/** Requests that are never counted. */
|
|
17
|
+
skip?: (req: HttpRequestLike) => boolean;
|
|
18
|
+
/** Paths that are never counted (health probes, webhooks…). */
|
|
19
|
+
skipPaths?: PathRule[];
|
|
20
|
+
/**
|
|
21
|
+
* `true` (default): the budget is shared across all routes of a key. `false`: one counter per route,
|
|
22
|
+
* so each route has its own window.
|
|
23
|
+
*/
|
|
24
|
+
shared?: boolean;
|
|
25
|
+
/** Error `code` of the 429 body (default `RATE_LIMITED`). */
|
|
26
|
+
code?: string;
|
|
27
|
+
message?: string;
|
|
28
|
+
/** Registers the guard as `APP_GUARD` (default true). */
|
|
29
|
+
global?: boolean;
|
|
30
|
+
/** Also send `X-RateLimit-Limit/Remaining/Reset` on every response (default true). */
|
|
31
|
+
headers?: boolean;
|
|
32
|
+
}
|
|
33
|
+
export declare const RATE_LIMIT_OPTIONS: unique symbol;
|
|
34
|
+
export declare const RATE_LIMIT_META = "nestkit:rate-limit";
|
|
35
|
+
export declare const RATE_LIMIT_SKIP_META = "nestkit:rate-limit-skip";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface RateLimitHit {
|
|
2
|
+
/** Hits in the current window, including this one. */
|
|
3
|
+
count: number;
|
|
4
|
+
/** Milliseconds until the window resets. */
|
|
5
|
+
resetMs: number;
|
|
6
|
+
}
|
|
7
|
+
/** Fixed-window counter behind the rate limiter. Implement it for any backend. */
|
|
8
|
+
export interface RateLimitStorePort {
|
|
9
|
+
hit(key: string, windowMs: number): Promise<RateLimitHit>;
|
|
10
|
+
}
|
|
11
|
+
export declare const RATE_LIMIT_STORE: unique symbol;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { RateLimitHit, RateLimitStorePort } from './rate-limit.port.js';
|
|
2
|
+
/** Structural slice of an ioredis client (`eval`), so this package never imports ioredis. */
|
|
3
|
+
export interface RedisEvalClient {
|
|
4
|
+
eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
|
|
5
|
+
}
|
|
6
|
+
export interface RedisRateLimitStoreOptions {
|
|
7
|
+
client: RedisEvalClient;
|
|
8
|
+
/** Key prefix (default `nestkit:rl:`). */
|
|
9
|
+
prefix?: string;
|
|
10
|
+
/** Called when Redis fails and the instance falls back to memory. */
|
|
11
|
+
onError?: (err: unknown) => void;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Window shared across instances: one `EVAL` per request. If Redis fails it counts in this instance's
|
|
15
|
+
* memory (and reports through `onError`): the limiter never takes a request down because of Redis.
|
|
16
|
+
*/
|
|
17
|
+
export declare class RedisRateLimitStore implements RateLimitStorePort {
|
|
18
|
+
private readonly options;
|
|
19
|
+
private readonly fallback;
|
|
20
|
+
private readonly prefix;
|
|
21
|
+
constructor(options: RedisRateLimitStoreOptions, fallback?: RateLimitStorePort);
|
|
22
|
+
hit(key: string, windowMs: number): Promise<RateLimitHit>;
|
|
23
|
+
}
|