@neon-pixels/rate-limit 0.0.0 → 0.4.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Neon Pixels Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # @neon-pixels/rate-limit
2
+
3
+ Fixed-window rate limiting that holds across function instances because the counters live in Postgres. One store interface, one table shape, one set of response headers. Policies, route matching, reading the client address from request headers, and the 429 response body stay in your app.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm add @neon-pixels/rate-limit
9
+ ```
10
+
11
+ `drizzle-orm` is a peer dependency, so your app controls its version. The package does not import an error-reporting SDK or `@neon-pixels/db`.
12
+
13
+ ## Usage
14
+
15
+ ### 1. Add the table to your schema
16
+
17
+ ```ts
18
+ // server/db/schema.ts
19
+ import { rateLimitCountersTable } from "@neon-pixels/rate-limit";
20
+
21
+ export const rateLimitCounters = rateLimitCountersTable();
22
+ ```
23
+
24
+ The table is `rate_limit_counters`: the key as primary key, the hit `count`, and an indexed `expires_at`. Generate and run your migration as usual.
25
+
26
+ ### 2. Create a store and consume
27
+
28
+ ```ts
29
+ import {
30
+ consumeFailOpen,
31
+ createPostgresStore,
32
+ rateLimitHeaders,
33
+ } from "@neon-pixels/rate-limit";
34
+ import { rateLimitCounters } from "./schema";
35
+
36
+ const store = createPostgresStore(database, rateLimitCounters);
37
+
38
+ const policy = { limit: 60, windowMs: 60_000 };
39
+ const result = await consumeFailOpen(store, key, policy, {
40
+ timeoutMs: 1500,
41
+ onFailure: (error) => reportError(error),
42
+ });
43
+
44
+ const headers = rateLimitHeaders(result);
45
+ if (!result.allowed) {
46
+ // respond 429 with `headers`
47
+ }
48
+ ```
49
+
50
+ `consume` is a single `INSERT ... ON CONFLICT DO UPDATE` that opens a new window when the stored one has ended and increments otherwise, so concurrent requests each get a distinct count. Window timing uses the `now` you pass (default `Date.now()`), so instances that share a table should have synced clocks.
51
+
52
+ ### Stores
53
+
54
+ Both stores implement `consume(key, policy, now?)`, returning `{ allowed, limit, remaining, resetAt }`, and `refund(key)`, which gives back one hit and never takes the count below zero. A policy is `{ limit, windowMs }`.
55
+
56
+ - `createPostgresStore(database, table)` for production. Any drizzle Postgres database works.
57
+ - `createMemoryStore({ maxKeys })` for tests and local development. State is per process. At the key cap (default 10,000) it drops expired windows, then the least recently used key.
58
+
59
+ ### Pruning
60
+
61
+ `consume` never deletes rows and never waits on a delete. Call `prune` from a scheduled job:
62
+
63
+ ```ts
64
+ const removed = await store.prune({ batchSize: 1000 });
65
+ ```
66
+
67
+ `prune` deletes at most `batchSize` expired rows (default 1000) and returns how many it removed. Run it again while it returns a full batch.
68
+
69
+ ### Failing open
70
+
71
+ `consumeFailOpen(store, key, policy, { timeoutMs, onFailure })` allows the request when the store throws or does not answer within `timeoutMs` (default 1500). The error, or a `RateLimitTimeoutError`, goes to `onFailure`; send it to your own error reporting. An allowed fail-open result reports the full budget as remaining.
72
+
73
+ ### Client keys
74
+
75
+ ```ts
76
+ // Read the secret once at startup so a missing value fails at boot, not per request.
77
+ const rateLimitSecret = process.env.RATE_LIMIT_SECRET;
78
+ if (!rateLimitSecret) {
79
+ throw new Error("RATE_LIMIT_SECRET is not set");
80
+ }
81
+
82
+ const key = `sign-in:${clientKeyForAddress(address, rateLimitSecret)}`;
83
+ ```
84
+
85
+ `clientKeyForAddress(address, secret)` unwraps IPv4-mapped IPv6 addresses (`::ffff:203.0.113.10`, in any notation), drops a port, groups IPv6 addresses by their /64 prefix, and returns the hex HMAC-SHA256 of the result. It throws when `secret` is empty, so a bare address or unkeyed hash is never stored. Keep the secret out of source control; changing it starts every client on a fresh bucket.
86
+
87
+ ### Headers
88
+
89
+ `rateLimitHeaders(result, now?)` returns `RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset` (whole seconds until the window ends), following the IETF `RateLimit-*` field names (draft-06 style, one header per value) rather than the older `X-RateLimit-*` names. A denied result also gets `Retry-After`.
90
+
91
+ ### Failed sign-in attempts: reserve, then refund
92
+
93
+ Count the attempt before you verify the credential, so concurrent guesses cannot all slip past the limit. Refund it when the credential is right, so only failures use up the budget.
94
+
95
+ ```ts
96
+ const policy = { limit: 5, windowMs: 15 * 60_000 };
97
+ const reservation = await store.consume(key, policy);
98
+ if (!reservation.allowed) {
99
+ return tooManyAttempts(rateLimitHeaders(reservation));
100
+ }
101
+
102
+ const valid = await verifyPassword(user, password);
103
+ if (valid) {
104
+ // A failed refund must not turn a correct sign-in into an error.
105
+ await store.refund(key).catch((error) => reportError(error));
106
+ }
107
+ ```
108
+
109
+ A refund after the window has rolled over takes a hit off the new window, which only ever errs in the user's favor.
110
+
111
+ ## Fixed windows
112
+
113
+ A client can use its full limit at the end of one window and again at the start of the next. That burst of up to twice the limit is inherent to fixed windows.
@@ -0,0 +1,155 @@
1
+ import { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core";
2
+ /**
3
+ * The address a client is limited under: IPv4 as written (also when mapped
4
+ * into IPv6, in any notation), IPv6 reduced to its /64 prefix so one customer
5
+ * cannot mint new buckets by rotating the low 64 bits. A port (`1.2.3.4:80`,
6
+ * `[::1]:80`) is dropped. Anything that is not an
7
+ * IP address is returned trimmed and lowercased.
8
+ */
9
+ export declare function normalizeAddress(address: string): string;
10
+ /**
11
+ * HMAC-SHA256 (hex) of the normalized address, keyed with `secret`. The raw
12
+ * address is never part of the result, and without the secret the few billion
13
+ * IPv4 values cannot be brute-forced back out, so an empty secret throws.
14
+ */
15
+ export declare function clientKeyForAddress(address: string, secret: string): string;
16
+ interface RateLimitPolicy {
17
+ /** Requests allowed per window. */
18
+ limit: number;
19
+ /** Window length in milliseconds. */
20
+ windowMs: number;
21
+ }
22
+ interface RateLimitResult {
23
+ allowed: boolean;
24
+ limit: number;
25
+ remaining: number;
26
+ /** Epoch milliseconds when the current window ends. */
27
+ resetAt: number;
28
+ }
29
+ interface RateLimitStore {
30
+ /** Counts one request against `key`. `now` is epoch milliseconds. */
31
+ consume(key: string, policy: RateLimitPolicy, now?: number): Promise<RateLimitResult>;
32
+ /** Gives back one hit on `key`. The count never goes below zero. */
33
+ refund(key: string): Promise<void>;
34
+ }
35
+ export declare const DEFAULT_TIMEOUT_MS = 1500;
36
+ export declare class RateLimitTimeoutError extends Error {
37
+ constructor(timeoutMs: number);
38
+ }
39
+ interface FailOpenOptions {
40
+ /** Longest to wait for the store. Defaults to 1500 ms. */
41
+ timeoutMs?: number;
42
+ /** Called with the error when the store fails or times out. */
43
+ onFailure?: (error: unknown) => void | Promise<void>;
44
+ /** Epoch milliseconds passed to the store. Defaults to `Date.now()`. */
45
+ now?: number;
46
+ }
47
+ /**
48
+ * Counts a request, but allows it when the store throws or does not answer in
49
+ * time, so a database problem cannot take the app down. The failure goes to
50
+ * `onFailure`; wire that to your own error reporting.
51
+ */
52
+ export declare function consumeFailOpen(store: RateLimitStore, key: string, policy: RateLimitPolicy, options?: FailOpenOptions): Promise<RateLimitResult>;
53
+ /**
54
+ * IETF `RateLimit-*` response headers, plus `Retry-After` on a denied request.
55
+ * Reset values are whole seconds until the window ends.
56
+ */
57
+ export declare function rateLimitHeaders(result: RateLimitResult, now?: number): Record<string, string>;
58
+ export declare const DEFAULT_MAX_KEYS = 10000;
59
+ interface MemoryStoreOptions {
60
+ /** Most keys tracked at once. Defaults to 10,000. */
61
+ maxKeys?: number;
62
+ }
63
+ interface MemoryRateLimitStore extends RateLimitStore {
64
+ /** Number of keys currently tracked. */
65
+ readonly size: number;
66
+ }
67
+ /**
68
+ * In-process store for tests and local development. State is per process, so
69
+ * it does not hold across function instances. When the key cap is reached it
70
+ * drops expired windows first, then the least recently used key.
71
+ */
72
+ export declare function createMemoryStore(options?: MemoryStoreOptions): MemoryRateLimitStore;
73
+ export declare const RATE_LIMIT_TABLE_NAME = "rate_limit_counters";
74
+ /**
75
+ * The counters table. Export the result from your drizzle schema so your
76
+ * migrations create it, then pass the same table to `createPostgresStore`.
77
+ */
78
+ export declare function rateLimitCountersTable(): import("drizzle-orm/pg-core").PgTableWithColumns<{
79
+ name: "rate_limit_counters";
80
+ schema: undefined;
81
+ columns: {
82
+ key: import("drizzle-orm/pg-core").PgColumn<{
83
+ name: "key";
84
+ tableName: "rate_limit_counters";
85
+ dataType: "string";
86
+ columnType: "PgText";
87
+ data: string;
88
+ driverParam: string;
89
+ notNull: true;
90
+ hasDefault: false;
91
+ isPrimaryKey: true;
92
+ isAutoincrement: false;
93
+ hasRuntimeDefault: false;
94
+ enumValues: [string, ...string[]];
95
+ baseColumn: never;
96
+ identity: undefined;
97
+ generated: undefined;
98
+ }, {}, {}>;
99
+ count: import("drizzle-orm/pg-core").PgColumn<{
100
+ name: "count";
101
+ tableName: "rate_limit_counters";
102
+ dataType: "number";
103
+ columnType: "PgInteger";
104
+ data: number;
105
+ driverParam: string | number;
106
+ notNull: true;
107
+ hasDefault: false;
108
+ isPrimaryKey: false;
109
+ isAutoincrement: false;
110
+ hasRuntimeDefault: false;
111
+ enumValues: undefined;
112
+ baseColumn: never;
113
+ identity: undefined;
114
+ generated: undefined;
115
+ }, {}, {}>;
116
+ expiresAt: import("drizzle-orm/pg-core").PgColumn<{
117
+ name: "expires_at";
118
+ tableName: "rate_limit_counters";
119
+ dataType: "date";
120
+ columnType: "PgTimestamp";
121
+ data: Date;
122
+ driverParam: string;
123
+ notNull: true;
124
+ hasDefault: false;
125
+ isPrimaryKey: false;
126
+ isAutoincrement: false;
127
+ hasRuntimeDefault: false;
128
+ enumValues: undefined;
129
+ baseColumn: never;
130
+ identity: undefined;
131
+ generated: undefined;
132
+ }, {}, {}>;
133
+ };
134
+ dialect: "pg";
135
+ }>;
136
+ type RateLimitCountersTable = ReturnType<typeof rateLimitCountersTable>;
137
+ export declare const DEFAULT_PRUNE_BATCH_SIZE = 1000;
138
+ interface PruneOptions {
139
+ /** Most rows to delete in this call. Defaults to 1000. */
140
+ batchSize?: number;
141
+ /** Epoch milliseconds treated as the current time. Defaults to `Date.now()`. */
142
+ now?: number;
143
+ }
144
+ interface PostgresRateLimitStore extends RateLimitStore {
145
+ /** Deletes up to `batchSize` expired rows and returns how many it removed. */
146
+ prune(options?: PruneOptions): Promise<number>;
147
+ }
148
+ /**
149
+ * Fixed-window counters in Postgres. `consume` is one INSERT ... ON CONFLICT
150
+ * DO UPDATE that opens a new window when the stored one has ended and
151
+ * increments otherwise, so concurrent requests from any number of instances
152
+ * each get a distinct count. It never prunes; call `prune` from a scheduled job.
153
+ */
154
+ export declare function createPostgresStore(database: PgDatabase<PgQueryResultHKT, any, any>, table: RateLimitCountersTable): PostgresRateLimitStore;
155
+ export type { FailOpenOptions, MemoryRateLimitStore, MemoryStoreOptions, PostgresRateLimitStore, PruneOptions, RateLimitCountersTable, RateLimitPolicy, RateLimitResult, RateLimitStore };
package/dist/index.js ADDED
@@ -0,0 +1,298 @@
1
+ import { createHmac } from "node:crypto";
2
+ import { isIPv4, isIPv6 } from "node:net";
3
+ import { and, eq, inArray, lte, sql } from "drizzle-orm";
4
+ import { index, integer, pgTable, text, timestamp } from "drizzle-orm/pg-core";
5
+ // src/client-key.ts
6
+ const HASH_ALGORITHM = "sha256";
7
+ const IPV6_GROUP_COUNT = 8;
8
+ const IPV6_PREFIX_GROUPS = 4;
9
+ const IPV4_MAPPED_MARKER = 65535;
10
+ const IPV4_MAPPED_MARKER_INDEX = 5;
11
+ const IPV4_EMBEDDED_HIGH_INDEX = 6;
12
+ const IPV4_EMBEDDED_LOW_INDEX = 7;
13
+ const BRACKETED_ADDRESS_PATTERN = /^\[(.+)\](?::\d+)?$/;
14
+ const IPV4_WITH_PORT_PATTERN = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/;
15
+ const BITS_PER_BYTE = 8;
16
+ const BYTE_MASK = 255;
17
+ function ipv4ToGroups(address) {
18
+ const [first = 0, second = 0, third = 0, fourth = 0] = address.split(".").map(Number);
19
+ return [first << BITS_PER_BYTE | second, third << BITS_PER_BYTE | fourth];
20
+ }
21
+ function groupsToIpv4(high, low) {
22
+ return [
23
+ high >> BITS_PER_BYTE,
24
+ high & BYTE_MASK,
25
+ low >> BITS_PER_BYTE,
26
+ low & BYTE_MASK
27
+ ].join(".");
28
+ }
29
+ function parseGroups(text) {
30
+ if (text === "") return [];
31
+ return text.split(":").flatMap((part) => {
32
+ return isIPv4(part) ? ipv4ToGroups(part) : [parseInt(part, 16)];
33
+ });
34
+ }
35
+ function ipv6ToGroups(address) {
36
+ const withoutZone = address.split("%")[0] ?? address;
37
+ const [head = "", tail = ""] = withoutZone.split("::");
38
+ const headGroups = parseGroups(head);
39
+ if (!withoutZone.includes("::")) return headGroups;
40
+ const tailGroups = parseGroups(tail);
41
+ const zeros = new Array(Math.max(IPV6_GROUP_COUNT - headGroups.length - tailGroups.length, 0)).fill(0);
42
+ return [
43
+ ...headGroups,
44
+ ...zeros,
45
+ ...tailGroups
46
+ ];
47
+ }
48
+ function isIpv4Mapped(groups) {
49
+ return groups.slice(0, IPV4_MAPPED_MARKER_INDEX).every((group) => group === 0) && groups[IPV4_MAPPED_MARKER_INDEX] === IPV4_MAPPED_MARKER;
50
+ }
51
+ function stripPort(address) {
52
+ const bracketed = BRACKETED_ADDRESS_PATTERN.exec(address);
53
+ if (bracketed) return bracketed[1] ?? address;
54
+ return IPV4_WITH_PORT_PATTERN.exec(address)?.[1] ?? address;
55
+ }
56
+ /**
57
+ * The address a client is limited under: IPv4 as written (also when mapped
58
+ * into IPv6, in any notation), IPv6 reduced to its /64 prefix so one customer
59
+ * cannot mint new buckets by rotating the low 64 bits. A port (`1.2.3.4:80`,
60
+ * `[::1]:80`) is dropped. Anything that is not an
61
+ * IP address is returned trimmed and lowercased.
62
+ */
63
+ function normalizeAddress(address) {
64
+ const trimmed = stripPort(address.trim().toLowerCase());
65
+ if (isIPv4(trimmed)) return trimmed;
66
+ if (!isIPv6(trimmed)) return trimmed;
67
+ const groups = ipv6ToGroups(trimmed);
68
+ if (isIpv4Mapped(groups)) return groupsToIpv4(groups[IPV4_EMBEDDED_HIGH_INDEX] ?? 0, groups[IPV4_EMBEDDED_LOW_INDEX] ?? 0);
69
+ return groups.slice(0, IPV6_PREFIX_GROUPS).map((group) => group.toString(16)).join(":");
70
+ }
71
+ /**
72
+ * HMAC-SHA256 (hex) of the normalized address, keyed with `secret`. The raw
73
+ * address is never part of the result, and without the secret the few billion
74
+ * IPv4 values cannot be brute-forced back out, so an empty secret throws.
75
+ */
76
+ function clientKeyForAddress(address, secret) {
77
+ if (!secret) throw new Error("clientKeyForAddress requires a non-empty secret");
78
+ const normalized = normalizeAddress(address);
79
+ if (!normalized) throw new Error("clientKeyForAddress requires a non-empty address");
80
+ return createHmac(HASH_ALGORITHM, secret).update(normalized).digest("hex");
81
+ }
82
+ /** Longest window accepted; keeps window end timestamps inside Date's range. */
83
+ const MAX_WINDOW_MS = 31536e7;
84
+ /** Throws on a policy that would silently disable or break limiting. */
85
+ function assertValidPolicy(policy) {
86
+ if (!Number.isInteger(policy.limit) || policy.limit < 1) throw new RangeError("policy.limit must be a positive integer");
87
+ if (!Number.isSafeInteger(policy.windowMs) || policy.windowMs < 1 || policy.windowMs > 31536e7) throw new RangeError(`policy.windowMs must be an integer between 1 and ${MAX_WINDOW_MS}`);
88
+ }
89
+ /** Throws on a clock value that would make every window look expired. */
90
+ function assertValidNow(now) {
91
+ if (!Number.isFinite(now)) throw new RangeError("now must be a finite number of epoch milliseconds");
92
+ }
93
+ // src/fail-open.ts
94
+ const DEFAULT_TIMEOUT_MS = 1500;
95
+ const MAX_TIMEOUT_MS = 0x7fffffff;
96
+ var RateLimitTimeoutError = class extends Error {
97
+ constructor(timeoutMs) {
98
+ super(`rate limit store did not answer within ${timeoutMs}ms`);
99
+ this.name = "RateLimitTimeoutError";
100
+ }
101
+ };
102
+ function rejectAfter(timeoutMs) {
103
+ let timer;
104
+ return {
105
+ promise: new Promise((_resolve, reject) => {
106
+ timer = setTimeout(() => reject(new RateLimitTimeoutError(timeoutMs)), timeoutMs);
107
+ }),
108
+ cancel: () => clearTimeout(timer)
109
+ };
110
+ }
111
+ function assertValidTimeout(timeoutMs) {
112
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS) throw new RangeError(`timeoutMs must be between 1 and ${MAX_TIMEOUT_MS} milliseconds`);
113
+ }
114
+ function openResult(policy, now) {
115
+ return {
116
+ allowed: true,
117
+ limit: policy.limit,
118
+ remaining: policy.limit,
119
+ resetAt: now + policy.windowMs
120
+ };
121
+ }
122
+ function reportFailure(onFailure, error) {
123
+ try {
124
+ (onFailure?.(error))?.catch(() => {});
125
+ } catch {}
126
+ }
127
+ /**
128
+ * Counts a request, but allows it when the store throws or does not answer in
129
+ * time, so a database problem cannot take the app down. The failure goes to
130
+ * `onFailure`; wire that to your own error reporting.
131
+ */
132
+ async function consumeFailOpen(store, key, policy, options = {}) {
133
+ const { timeoutMs = DEFAULT_TIMEOUT_MS, onFailure, now = Date.now() } = options;
134
+ assertValidPolicy(policy);
135
+ assertValidTimeout(timeoutMs);
136
+ assertValidNow(now);
137
+ const timeout = rejectAfter(timeoutMs);
138
+ try {
139
+ return await Promise.race([Promise.resolve().then(() => store.consume(key, policy, now)), timeout.promise]);
140
+ } catch (error) {
141
+ reportFailure(onFailure, error);
142
+ return openResult(policy, now);
143
+ } finally {
144
+ timeout.cancel();
145
+ }
146
+ }
147
+ // src/headers.ts
148
+ const MILLISECONDS_PER_SECOND = 1e3;
149
+ /**
150
+ * IETF `RateLimit-*` response headers, plus `Retry-After` on a denied request.
151
+ * Reset values are whole seconds until the window ends.
152
+ */
153
+ function rateLimitHeaders(result, now = Date.now()) {
154
+ const resetSeconds = Math.max(Math.ceil((result.resetAt - now) / MILLISECONDS_PER_SECOND), 0);
155
+ const headers = {
156
+ "RateLimit-Limit": String(result.limit),
157
+ "RateLimit-Remaining": String(result.remaining),
158
+ "RateLimit-Reset": String(resetSeconds)
159
+ };
160
+ if (!result.allowed) headers["Retry-After"] = String(resetSeconds);
161
+ return headers;
162
+ }
163
+ // src/memory-store.ts
164
+ const DEFAULT_MAX_KEYS = 1e4;
165
+ /**
166
+ * In-process store for tests and local development. State is per process, so
167
+ * it does not hold across function instances. When the key cap is reached it
168
+ * drops expired windows first, then the least recently used key.
169
+ */
170
+ function createMemoryStore(options = {}) {
171
+ const { maxKeys = DEFAULT_MAX_KEYS } = options;
172
+ if (!Number.isInteger(maxKeys) || maxKeys < 1) throw new RangeError("maxKeys must be a positive integer");
173
+ const windows = /* @__PURE__ */ new Map();
174
+ function dropExpired(now) {
175
+ for (const [key, state] of windows) {
176
+ if (state.expiresAt > now) continue;
177
+ windows.delete(key);
178
+ }
179
+ }
180
+ function makeRoomForNewKey(now) {
181
+ if (windows.size < maxKeys) return;
182
+ dropExpired(now);
183
+ while (windows.size >= maxKeys) {
184
+ const oldest = windows.keys().next().value;
185
+ if (oldest === void 0) return;
186
+ windows.delete(oldest);
187
+ }
188
+ }
189
+ function openWindow(key, policy, now) {
190
+ const existing = windows.get(key);
191
+ windows.delete(key);
192
+ if (!existing) makeRoomForNewKey(now);
193
+ const state = (existing && existing.expiresAt > now ? existing : void 0) ?? {
194
+ count: 0,
195
+ expiresAt: now + policy.windowMs
196
+ };
197
+ windows.set(key, state);
198
+ return state;
199
+ }
200
+ async function consume(key, policy, now = Date.now()) {
201
+ assertValidPolicy(policy);
202
+ assertValidNow(now);
203
+ const state = openWindow(key, policy, now);
204
+ state.count += 1;
205
+ return {
206
+ allowed: state.count <= policy.limit,
207
+ limit: policy.limit,
208
+ remaining: Math.max(policy.limit - state.count, 0),
209
+ resetAt: state.expiresAt
210
+ };
211
+ }
212
+ async function refund(key) {
213
+ const state = windows.get(key);
214
+ if (!state) return;
215
+ state.count = Math.max(state.count - 1, 0);
216
+ }
217
+ return {
218
+ consume,
219
+ refund,
220
+ get size() {
221
+ return windows.size;
222
+ }
223
+ };
224
+ }
225
+ // src/postgres-store.ts
226
+ const DEFAULT_PRUNE_BATCH_SIZE = 1e3;
227
+ function timestampSql(epochMs) {
228
+ return sql`${new Date(epochMs).toISOString()}::timestamptz`;
229
+ }
230
+ /**
231
+ * Fixed-window counters in Postgres. `consume` is one INSERT ... ON CONFLICT
232
+ * DO UPDATE that opens a new window when the stored one has ended and
233
+ * increments otherwise, so concurrent requests from any number of instances
234
+ * each get a distinct count. It never prunes; call `prune` from a scheduled job.
235
+ */
236
+ function createPostgresStore(database, table) {
237
+ async function consume(key, policy, now = Date.now()) {
238
+ assertValidPolicy(policy);
239
+ assertValidNow(now);
240
+ const nowSql = timestampSql(now);
241
+ const windowEndSql = timestampSql(now + policy.windowMs);
242
+ const expired = sql`${table.expiresAt} <= ${nowSql}`;
243
+ const [row] = await database.insert(table).values({
244
+ key,
245
+ count: 1,
246
+ expiresAt: new Date(now + policy.windowMs)
247
+ }).onConflictDoUpdate({
248
+ target: table.key,
249
+ set: {
250
+ count: sql`CASE WHEN ${expired} THEN 1 ELSE LEAST(${table.count}, ${policy.limit}::integer) + 1 END`,
251
+ expiresAt: sql`CASE WHEN ${expired} THEN ${windowEndSql} ELSE ${table.expiresAt} END`
252
+ }
253
+ }).returning({
254
+ count: table.count,
255
+ expiresAt: table.expiresAt
256
+ });
257
+ if (!row) throw new Error("rate limit upsert returned no row");
258
+ return {
259
+ allowed: row.count <= policy.limit,
260
+ limit: policy.limit,
261
+ remaining: Math.max(policy.limit - row.count, 0),
262
+ resetAt: row.expiresAt.getTime()
263
+ };
264
+ }
265
+ async function refund(key) {
266
+ await database.update(table).set({ count: sql`GREATEST(${table.count} - 1, 0)` }).where(eq(table.key, key));
267
+ }
268
+ async function prune(options = {}) {
269
+ const { batchSize = DEFAULT_PRUNE_BATCH_SIZE, now = Date.now() } = options;
270
+ if (!Number.isInteger(batchSize) || batchSize < 1) throw new RangeError("batchSize must be a positive integer");
271
+ assertValidNow(now);
272
+ const expiredBefore = new Date(now);
273
+ const expiredKeys = database.select({ key: table.key }).from(table).where(lte(table.expiresAt, expiredBefore)).limit(batchSize);
274
+ return (await database.delete(table).where(and(inArray(table.key, expiredKeys), lte(table.expiresAt, expiredBefore))).returning({ key: table.key })).length;
275
+ }
276
+ return {
277
+ consume,
278
+ refund,
279
+ prune
280
+ };
281
+ }
282
+ // src/table.ts
283
+ const RATE_LIMIT_TABLE_NAME = "rate_limit_counters";
284
+ /**
285
+ * The counters table. Export the result from your drizzle schema so your
286
+ * migrations create it, then pass the same table to `createPostgresStore`.
287
+ */
288
+ function rateLimitCountersTable() {
289
+ return pgTable(RATE_LIMIT_TABLE_NAME, {
290
+ key: text("key").primaryKey(),
291
+ count: integer("count").notNull(),
292
+ expiresAt: timestamp("expires_at", {
293
+ withTimezone: true,
294
+ mode: "date"
295
+ }).notNull()
296
+ }, (table) => [index("rate_limit_counters_expires_at_idx").on(table.expiresAt)]);
297
+ }
298
+ export { DEFAULT_MAX_KEYS, DEFAULT_PRUNE_BATCH_SIZE, DEFAULT_TIMEOUT_MS, RATE_LIMIT_TABLE_NAME, RateLimitTimeoutError, clientKeyForAddress, consumeFailOpen, createMemoryStore, createPostgresStore, normalizeAddress, rateLimitCountersTable, rateLimitHeaders };
package/package.json CHANGED
@@ -1 +1,39 @@
1
- {"name":"@neon-pixels/rate-limit","version":"0.0.0","description":"Placeholder. The first real release follows.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/neonpixels-studio/packages.git"}}
1
+ {
2
+ "name": "@neon-pixels/rate-limit",
3
+ "version": "0.4.0",
4
+ "description": "Fixed-window rate limiting on Postgres with a memory store, fail-open wrapper, hashed client keys, and RateLimit headers.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/neonpixels-studio/packages.git",
10
+ "directory": "packages/rate-limit"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": "^22.17.0 || ^24.0.0 || >=26.0.0"
27
+ },
28
+ "peerDependencies": {
29
+ "drizzle-orm": ">=0.45.0 <1.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@electric-sql/pglite": "^0.5.17",
33
+ "drizzle-orm": "^0.45.4"
34
+ },
35
+ "scripts": {
36
+ "build": "tsdown",
37
+ "typecheck": "tsc --noEmit -p tsconfig.json"
38
+ }
39
+ }