@sourceregistry/sveltekit-enhance 1.4.2 → 1.5.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.
@@ -1,6 +1,6 @@
1
1
  import { type EnhanceFunction, type EnhanceInput } from "../index.js";
2
2
  import type { MaybePromise } from "../index.js";
3
- import type { Logger } from "./logger.js";
3
+ import type { Logger } from "./internal/logger.js";
4
4
  export declare const CSRF: {
5
5
  inspect: (checker: (input: EnhanceInput) => MaybePromise<boolean>, logger?: Logger) => EnhanceFunction<"handle">;
6
6
  };
@@ -3,7 +3,8 @@ export * from './cache.js';
3
3
  export * from './devtools.js';
4
4
  export * from './featureflag.js';
5
5
  export * from './form.ts';
6
- export * from './request-correlation.ts';
6
+ export * from './request-correlation.js';
7
7
  export * from './request-monitor.js';
8
+ export * from './request-rate-limit.js';
8
9
  export * from './CSRF.js';
9
- export * from './logger.js';
10
+ export * from './internal/logger.js';
@@ -3,7 +3,8 @@ export * from './cache.js';
3
3
  export * from './devtools.js';
4
4
  export * from './featureflag.js';
5
5
  export * from "./form.js";
6
- export * from "./request-correlation.js";
6
+ export * from './request-correlation.js';
7
7
  export * from './request-monitor.js';
8
+ export * from './request-rate-limit.js';
8
9
  export * from './CSRF.js';
9
- export * from './logger.js';
10
+ export * from './internal/logger.js';
@@ -0,0 +1,11 @@
1
+ export declare const ClientIp: (defaults?: {
2
+ TRUST_PROXY_HEADERS: boolean;
3
+ TRUST_PROXY_HOPS: number;
4
+ }) => {
5
+ forwardedChain: (value: string | null) => string[];
6
+ fromForwardedFor(value: string | null, trustedProxyHops?: number): string | undefined;
7
+ fromRequest(request: Request, options?: {
8
+ trustProxyHeaders?: boolean;
9
+ trustedProxyHops?: number;
10
+ }): string | undefined;
11
+ };
@@ -0,0 +1,25 @@
1
+ const normalizeIp = (value) => {
2
+ const ip = value?.trim();
3
+ return ip ? ip : undefined;
4
+ };
5
+ const forwardedChain = (value) => (value ?? '')
6
+ .split(',')
7
+ .map((part) => part.trim())
8
+ .filter(Boolean);
9
+ export const ClientIp = (defaults = { TRUST_PROXY_HEADERS: false, TRUST_PROXY_HOPS: 1 }) => ({
10
+ forwardedChain,
11
+ fromForwardedFor(value, trustedProxyHops = defaults.TRUST_PROXY_HOPS) {
12
+ const chain = forwardedChain(value);
13
+ if (chain.length < trustedProxyHops)
14
+ return undefined;
15
+ return normalizeIp(chain[chain.length - trustedProxyHops]);
16
+ },
17
+ fromRequest(request, options = {}) {
18
+ const trustProxyHeaders = options.trustProxyHeaders ?? defaults.TRUST_PROXY_HEADERS;
19
+ const trustedProxyHops = Math.max(1, options.trustedProxyHops ?? defaults.TRUST_PROXY_HOPS);
20
+ if (!trustProxyHeaders)
21
+ return undefined;
22
+ return (ClientIp(defaults).fromForwardedFor(request.headers.get('x-forwarded-for'), trustedProxyHops) ??
23
+ normalizeIp(request.headers.get('x-real-ip')));
24
+ }
25
+ });
@@ -1,5 +1,5 @@
1
1
  import type { EnhanceFunction } from "../index.js";
2
- import type { Logger } from "./logger.js";
2
+ import type { Logger } from "./internal/logger.js";
3
3
  export type RequestTraceLocals = {
4
4
  trace?: {
5
5
  id: string;
@@ -0,0 +1,48 @@
1
+ import type { EnhanceInput, MaybePromise } from "../index.js";
2
+ import type { Logger } from "./internal/logger.js";
3
+ export type RateLimitRule<RuleId extends string = string> = {
4
+ id: RuleId;
5
+ pattern: RegExp;
6
+ methods?: ReadonlySet<string> | ReadonlyArray<string>;
7
+ limit: number;
8
+ windowMs: number;
9
+ };
10
+ type Bucket = {
11
+ count: number;
12
+ resetAt: number;
13
+ };
14
+ export type RateLimitStore = {
15
+ /**
16
+ * Increment key's counter for current window, creating it if absent/expired.
17
+ * Return counter state after increment.
18
+ */
19
+ increment(key: string, windowMs: number, now: number): MaybePromise<Bucket>;
20
+ };
21
+ export type MemoryRateLimitStoreOptions = {
22
+ cleanupIntervalMs?: number;
23
+ };
24
+ /**
25
+ * Single-process, in-memory store. Fine for one instance; buckets aren't
26
+ * shared across processes/machines, so a multi-instance deployment (eg.
27
+ * serverless, multiple pods) under-counts unless a shared store (Redis, etc.)
28
+ * is supplied via `RequestRateLimitOptions.store` instead.
29
+ */
30
+ export declare const createMemoryRateLimitStore: (options?: MemoryRateLimitStoreOptions) => RateLimitStore;
31
+ export type RequestRateLimitOptions<RuleId extends string> = {
32
+ enabled?: boolean;
33
+ rules: RateLimitRule<RuleId>[];
34
+ correlationHeader?: string;
35
+ correlationId?: (input: EnhanceInput<'handle'>) => string | undefined;
36
+ clientIdentifier?: (input: EnhanceInput<'handle'>) => string;
37
+ /**
38
+ * Bucket storage backend. Defaults to a single-process in-memory store.
39
+ * Pass a shared store (eg. Redis-backed) when running multiple
40
+ * instances/processes so limits are enforced consistently across them.
41
+ */
42
+ store?: RateLimitStore;
43
+ logger?: Logger;
44
+ };
45
+ export declare const RequestRateLimit: {
46
+ inspect: <RuleId extends string>(options: RequestRateLimitOptions<RuleId>) => (input: EnhanceInput<"handle">) => Promise<void>;
47
+ };
48
+ export {};
@@ -0,0 +1,126 @@
1
+ import { ClientIp } from "./internal/client_ip.js";
2
+ /**
3
+ * Single-process, in-memory store. Fine for one instance; buckets aren't
4
+ * shared across processes/machines, so a multi-instance deployment (eg.
5
+ * serverless, multiple pods) under-counts unless a shared store (Redis, etc.)
6
+ * is supplied via `RequestRateLimitOptions.store` instead.
7
+ */
8
+ export const createMemoryRateLimitStore = (options = {}) => {
9
+ const buckets = new Map();
10
+ const cleanupTimer = setInterval(() => {
11
+ const now = Date.now();
12
+ for (const [key, bucket] of buckets.entries()) {
13
+ if (bucket.resetAt <= now)
14
+ buckets.delete(key);
15
+ }
16
+ }, options.cleanupIntervalMs ?? 30_000);
17
+ cleanupTimer.unref?.();
18
+ return {
19
+ increment(key, windowMs, now) {
20
+ const previous = buckets.get(key);
21
+ const bucket = !previous || previous.resetAt <= now
22
+ ? { count: 0, resetAt: now + windowMs }
23
+ : previous;
24
+ bucket.count += 1;
25
+ buckets.set(key, bucket);
26
+ return bucket;
27
+ }
28
+ };
29
+ };
30
+ const defaultStore = createMemoryRateLimitStore();
31
+ const includes = (input, element) => {
32
+ return input[Symbol.iterator]().find((v) => v === element);
33
+ };
34
+ const findRule = (rules, method, pathname) => rules.find((rule) => rule.pattern.test(pathname) && (!rule.methods || includes(rule.methods, method.toUpperCase())));
35
+ const getClientIdentifier = (input) => {
36
+ try {
37
+ const address = input.getClientAddress?.();
38
+ if (address)
39
+ return address;
40
+ }
41
+ catch {
42
+ // adapter may not support getClientAddress (eg. prerendering); fall through
43
+ }
44
+ return ClientIp().fromRequest(input.request) ?? 'unknown';
45
+ };
46
+ const decorateRateLimitHeaders = (response, input) => {
47
+ const setHeaders = (headers) => {
48
+ headers.set('x-ratelimit-limit', String(input.limit));
49
+ headers.set('x-ratelimit-remaining', String(Math.max(input.remaining, 0)));
50
+ headers.set('x-ratelimit-reset', String(Math.ceil(input.resetAt / 1000)));
51
+ headers.set('x-ratelimit-policy', `${input.limit};w=${Math.ceil(input.windowMs / 1000)}`);
52
+ if (input.correlationId)
53
+ headers.set(input.correlationHeader ?? 'x-correlation-id', input.correlationId);
54
+ };
55
+ try {
56
+ setHeaders(response.headers);
57
+ return response;
58
+ }
59
+ catch {
60
+ const headers = new Headers(response.headers);
61
+ setHeaders(headers);
62
+ return new Response(response.body, {
63
+ status: response.status,
64
+ statusText: response.statusText,
65
+ headers
66
+ });
67
+ }
68
+ };
69
+ export const RequestRateLimit = ({
70
+ inspect: (options) => async (input) => {
71
+ if (options.enabled === false)
72
+ return;
73
+ const method = input.request.method.toUpperCase();
74
+ const pathname = input.url.pathname;
75
+ const rule = findRule(options.rules, method, pathname);
76
+ if (!rule)
77
+ return;
78
+ if (rule.limit <= 0 || rule.windowMs <= 0)
79
+ return;
80
+ const now = Date.now();
81
+ const client = options.clientIdentifier?.(input) ?? getClientIdentifier(input);
82
+ const key = `${rule.id}:${client}`;
83
+ const correlationId = options.correlationId?.(input) ?? input.locals.correlation_id;
84
+ const store = options.store ?? defaultStore;
85
+ const bucket = await store.increment(key, rule.windowMs, now);
86
+ const remaining = rule.limit - bucket.count;
87
+ const retryAfterSeconds = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000));
88
+ if (bucket.count > rule.limit) {
89
+ options?.logger?.warn('request.rate_limited', {
90
+ correlationId,
91
+ rule: rule.id,
92
+ method,
93
+ path: pathname,
94
+ client,
95
+ limit: rule.limit,
96
+ windowMs: rule.windowMs,
97
+ retryAfterSeconds
98
+ });
99
+ const headers = new Headers({
100
+ 'content-type': 'application/json',
101
+ 'retry-after': String(retryAfterSeconds),
102
+ 'x-ratelimit-limit': String(rule.limit),
103
+ 'x-ratelimit-remaining': '0',
104
+ 'x-ratelimit-reset': String(Math.ceil(bucket.resetAt / 1000)),
105
+ 'x-ratelimit-policy': `${rule.limit};w=${Math.ceil(rule.windowMs / 1000)}`
106
+ });
107
+ if (correlationId)
108
+ headers.set(options.correlationHeader ?? 'x-correlation-id', correlationId);
109
+ throw new Response(JSON.stringify({
110
+ message: 'Too many requests. Please retry later.'
111
+ }), {
112
+ status: 429,
113
+ headers
114
+ });
115
+ }
116
+ const respond = ({ response }) => decorateRateLimitHeaders(response, {
117
+ limit: rule.limit,
118
+ remaining,
119
+ resetAt: bucket.resetAt,
120
+ windowMs: rule.windowMs,
121
+ correlationId,
122
+ correlationHeader: options.correlationHeader
123
+ });
124
+ input.responseHandlers.push(respond);
125
+ }
126
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourceregistry/sveltekit-enhance",
3
- "version": "1.4.2",
3
+ "version": "1.5.0",
4
4
  "description": "Composable enhance and form utilities for SvelteKit actions, loads, methods, and hooks.",
5
5
  "author": "A.P.A. Slaa (a.p.a.slaa@projectsource.nl)",
6
6
  "scripts": {
File without changes