@lunora/ratelimit 0.0.0 → 1.0.0-alpha.10

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.
@@ -0,0 +1,103 @@
1
+ const createMemoryStore = () => {
2
+ const map = /* @__PURE__ */ new Map();
3
+ return {
4
+ delete: (storageKey) => {
5
+ map.delete(storageKey);
6
+ },
7
+ get: (storageKey) => map.get(storageKey),
8
+ set: (storageKey, value) => {
9
+ map.set(storageKey, value);
10
+ }
11
+ };
12
+ };
13
+ const runSql = (sql, query, ...params) => {
14
+ const runner = sql.exec;
15
+ return runner.call(sql, query, ...params).toArray();
16
+ };
17
+ const createSqlStore = (options) => {
18
+ const { sql } = options;
19
+ const table = options.table ?? "_lunora_rate_limits";
20
+ runSql(sql, `CREATE TABLE IF NOT EXISTS "${table}" (k TEXT PRIMARY KEY, value REAL NOT NULL, ts INTEGER NOT NULL, prev REAL)`);
21
+ return {
22
+ delete: (storageKey) => {
23
+ runSql(sql, `DELETE FROM "${table}" WHERE k = ?`, storageKey);
24
+ },
25
+ get: (storageKey) => {
26
+ const rows = runSql(sql, `SELECT value, ts, prev FROM "${table}" WHERE k = ?`, storageKey);
27
+ const row = rows[0];
28
+ if (!row) {
29
+ return void 0;
30
+ }
31
+ const value = { ts: row.ts, value: row.value };
32
+ if (row.prev !== null) {
33
+ value.prev = row.prev;
34
+ }
35
+ return value;
36
+ },
37
+ set: (storageKey, value) => {
38
+ runSql(
39
+ sql,
40
+ `INSERT INTO "${table}" (k, value, ts, prev) VALUES (?, ?, ?, ?) ON CONFLICT(k) DO UPDATE SET value = excluded.value, ts = excluded.ts, prev = excluded.prev`,
41
+ storageKey,
42
+ value.value,
43
+ value.ts,
44
+ // SQL bind: a missing `prev` must bind as SQL NULL, not undefined.
45
+ // eslint-disable-next-line unicorn/no-null -- SQLite/D1 bind parameters require null for a NULL column
46
+ value.prev ?? null
47
+ );
48
+ }
49
+ };
50
+ };
51
+ const createDatabaseStore = (options) => {
52
+ const { db } = options;
53
+ const table = options.table ?? "rateLimits";
54
+ const index = options.index ?? "by_key";
55
+ const keyField = options.keyField ?? "key";
56
+ const idCache = /* @__PURE__ */ new Map();
57
+ const find = async (storageKey) => {
58
+ const row = await db.query(table).withIndex(index, (q) => q.eq(keyField, storageKey)).first();
59
+ idCache.set(storageKey, row ? row._id : void 0);
60
+ return row;
61
+ };
62
+ const resolveId = async (storageKey) => {
63
+ if (idCache.has(storageKey)) {
64
+ return idCache.get(storageKey);
65
+ }
66
+ await find(storageKey);
67
+ return idCache.get(storageKey);
68
+ };
69
+ return {
70
+ delete: async (storageKey) => {
71
+ const id = await resolveId(storageKey);
72
+ if (id !== void 0) {
73
+ await db.delete(id);
74
+ }
75
+ idCache.delete(storageKey);
76
+ },
77
+ get: async (storageKey) => {
78
+ const row = await find(storageKey);
79
+ if (!row) {
80
+ return void 0;
81
+ }
82
+ const value = { ts: row.ts, value: row.value };
83
+ if (row.prev !== null && row.prev !== void 0) {
84
+ value.prev = row.prev;
85
+ }
86
+ return value;
87
+ },
88
+ set: async (storageKey, value) => {
89
+ const id = await resolveId(storageKey);
90
+ const document = { [keyField]: storageKey, ts: value.ts, value: value.value };
91
+ if (value.prev !== void 0) {
92
+ document.prev = value.prev;
93
+ }
94
+ if (id === void 0) {
95
+ idCache.set(storageKey, await db.insert(table, document));
96
+ } else {
97
+ await db.patch(id, document);
98
+ }
99
+ }
100
+ };
101
+ };
102
+
103
+ export { createDatabaseStore as createDbStore, createMemoryStore, createSqlStore };
@@ -0,0 +1,7 @@
1
+ import { rateLimit } from './rateLimit-BBdG9GFo.mjs';
2
+ import { RateLimiter } from './RateLimiter-rDCxu_Nx.mjs';
3
+ import { createDbStore as createDatabaseStore } from './createDbStore-L1kD1g1n.mjs';
4
+
5
+ const databaseRateLimit = (config, name, options = {}) => rateLimit((context) => new RateLimiter({ config, store: createDatabaseStore({ db: context.db, ...options.store }) }), name, options);
6
+
7
+ export { databaseRateLimit as default };
@@ -0,0 +1,40 @@
1
+ import { isLunoraError, isInternalCode, LunoraError } from '@lunora/errors';
2
+
3
+ const STATUS_BY_REASON = {
4
+ deny: { code: "FORBIDDEN", status: 403 },
5
+ rate: { code: "TOO_MANY_REQUESTS", status: 429 }
6
+ };
7
+ const defaultMessage = (name, reason, retryAfter) => {
8
+ if (reason === "deny") {
9
+ return `request denied for "${name}"`;
10
+ }
11
+ return retryAfter === void 0 ? `rate limit "${name}" exceeded` : `rate limit "${name}" exceeded; retry after ${String(retryAfter)}ms`;
12
+ };
13
+ const rateLimit = (limiter, name, options = {}) => async ({ ctx, next }) => {
14
+ let status;
15
+ try {
16
+ const resolved = typeof limiter === "function" ? await limiter(ctx) : limiter;
17
+ status = await resolved.limit(name, { count: options.count, key: options.key?.(ctx) });
18
+ } catch (error) {
19
+ if (isLunoraError(error) && isInternalCode(error.code)) {
20
+ throw error;
21
+ }
22
+ console.error(`@lunora/ratelimit: rateLimit("${name}") threw; ${options.failOpen ? "failing open" : "failing closed"}`, error);
23
+ if (options.failOpen) {
24
+ return next();
25
+ }
26
+ throw new LunoraError("SERVICE_UNAVAILABLE", `rate limiter unavailable for "${name}"`, { cause: error, status: 503 });
27
+ }
28
+ if (!status.ok) {
29
+ const reason = status.reason ?? "rate";
30
+ const mapped = STATUS_BY_REASON[reason];
31
+ const retryAfter = Number.isFinite(status.retryAfter) ? Math.ceil(status.retryAfter) : void 0;
32
+ throw new LunoraError(mapped.code, options.message ?? defaultMessage(name, reason, retryAfter), {
33
+ status: mapped.status,
34
+ data: retryAfter === void 0 ? void 0 : { retryAfter }
35
+ });
36
+ }
37
+ return next();
38
+ };
39
+
40
+ export { STATUS_BY_REASON, rateLimit };
@@ -0,0 +1,12 @@
1
+ const ratelimitPlugin = (limiter) => {
2
+ return {
3
+ key: "ratelimit",
4
+ middleware: async ({ ctx, next }) => {
5
+ const resolved = typeof limiter === "function" ? await limiter(ctx) : limiter;
6
+ const existingApi = ctx.api ?? {};
7
+ return next({ ctx: { api: { ...existingApi, ratelimit: resolved } } });
8
+ }
9
+ };
10
+ };
11
+
12
+ export { ratelimitPlugin };
package/package.json CHANGED
@@ -1,31 +1,54 @@
1
1
  {
2
2
  "name": "@lunora/ratelimit",
3
- "version": "0.0.0",
3
+ "version": "1.0.0-alpha.10",
4
4
  "description": "Rate limiting: token-bucket / fixed-window / sliding-window algorithms, deny list, sharding, pluggable stores, and procedure middleware",
5
- "license": "FSL-1.1-Apache-2.0",
5
+ "keywords": [
6
+ "cloudflare",
7
+ "durable-objects",
8
+ "lunora",
9
+ "middleware",
10
+ "rate-limit",
11
+ "sliding-window",
12
+ "token-bucket",
13
+ "workers"
14
+ ],
6
15
  "homepage": "https://lunora.sh",
16
+ "bugs": "https://github.com/anolilab/lunora/issues",
17
+ "license": "FSL-1.1-Apache-2.0",
18
+ "author": {
19
+ "name": "Daniel Bannert",
20
+ "email": "d.bannert@anolilab.de"
21
+ },
7
22
  "repository": {
8
23
  "type": "git",
9
24
  "url": "git+https://github.com/anolilab/lunora.git",
10
25
  "directory": "packages/ratelimit"
11
26
  },
12
- "bugs": {
13
- "url": "https://github.com/anolilab/lunora/issues"
14
- },
15
- "keywords": [
16
- "lunora",
17
- "cloudflare",
18
- "workers",
19
- "durable-objects",
20
- "rate-limit",
21
- "token-bucket",
22
- "sliding-window",
23
- "middleware"
27
+ "files": [
28
+ "./dist",
29
+ "__assets__",
30
+ "README.md",
31
+ "LICENSE.md"
24
32
  ],
33
+ "type": "module",
34
+ "sideEffects": false,
35
+ "main": "./dist/index.mjs",
36
+ "module": "./dist/index.mjs",
37
+ "types": "./dist/index.d.ts",
38
+ "exports": {
39
+ ".": {
40
+ "types": "./dist/index.d.ts",
41
+ "import": "./dist/index.mjs"
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
25
45
  "publishConfig": {
26
46
  "access": "public"
27
47
  },
28
- "files": [
29
- "README.md"
30
- ]
48
+ "dependencies": {
49
+ "@lunora/errors": "1.0.0-alpha.8"
50
+ },
51
+ "engines": {
52
+ "node": "^22.15.0 || >=24.11.0"
53
+ }
31
54
  }