@agent-score/commerce 2.0.1 → 2.1.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 +26 -11
- package/dist/_core-kI7FRAiZ.d.mts +10 -0
- package/dist/_core-kI7FRAiZ.d.ts +10 -0
- package/dist/challenge/index.d.mts +3 -3
- package/dist/challenge/index.d.ts +3 -3
- package/dist/challenge/index.js +21 -14
- package/dist/challenge/index.js.map +1 -1
- package/dist/challenge/index.mjs +21 -14
- package/dist/challenge/index.mjs.map +1 -1
- package/dist/{checkout-B1JuEcbx.d.ts → checkout-BH-I_Ns8.d.ts} +19 -12
- package/dist/{checkout-BN5i1Fi7.d.mts → checkout-Bd_4aQ6c.d.mts} +19 -12
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/core.mjs +1 -1
- package/dist/core.mjs.map +1 -1
- package/dist/default_rails-BWAquZeu.d.mts +188 -0
- package/dist/default_rails-BxBzcCA1.d.ts +188 -0
- package/dist/discovery/index.d.mts +5 -5
- package/dist/discovery/index.d.ts +5 -5
- package/dist/discovery/index.js +14 -1
- package/dist/discovery/index.js.map +1 -1
- package/dist/discovery/index.mjs +14 -1
- package/dist/discovery/index.mjs.map +1 -1
- package/dist/identity/express.d.mts +7 -3
- package/dist/identity/express.d.ts +7 -3
- package/dist/identity/express.js +39 -96
- package/dist/identity/express.js.map +1 -1
- package/dist/identity/express.mjs +37 -87
- package/dist/identity/express.mjs.map +1 -1
- package/dist/identity/fastify.d.mts +4 -4
- package/dist/identity/fastify.d.ts +4 -4
- package/dist/identity/fastify.js +60 -96
- package/dist/identity/fastify.js.map +1 -1
- package/dist/identity/fastify.mjs +58 -87
- package/dist/identity/fastify.mjs.map +1 -1
- package/dist/identity/hono.d.mts +11 -3
- package/dist/identity/hono.d.ts +11 -3
- package/dist/identity/hono.js +39 -93
- package/dist/identity/hono.js.map +1 -1
- package/dist/identity/hono.mjs +37 -84
- package/dist/identity/hono.mjs.map +1 -1
- package/dist/identity/nextjs.d.mts +10 -3
- package/dist/identity/nextjs.d.ts +10 -3
- package/dist/identity/nextjs.js +49 -93
- package/dist/identity/nextjs.js.map +1 -1
- package/dist/identity/nextjs.mjs +46 -84
- package/dist/identity/nextjs.mjs.map +1 -1
- package/dist/identity/policy.js +220 -129
- package/dist/identity/policy.js.map +1 -1
- package/dist/identity/policy.mjs +222 -131
- package/dist/identity/policy.mjs.map +1 -1
- package/dist/identity/web.d.mts +9 -3
- package/dist/identity/web.d.ts +9 -3
- package/dist/identity/web.js +45 -93
- package/dist/identity/web.js.map +1 -1
- package/dist/identity/web.mjs +42 -84
- package/dist/identity/web.mjs.map +1 -1
- package/dist/index.d.mts +554 -90
- package/dist/index.d.ts +554 -90
- package/dist/index.js +951 -152
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +939 -152
- package/dist/index.mjs.map +1 -1
- package/dist/middleware/express.d.mts +10 -0
- package/dist/middleware/express.d.ts +10 -0
- package/dist/middleware/express.js +128 -0
- package/dist/middleware/express.js.map +1 -0
- package/dist/middleware/express.mjs +91 -0
- package/dist/middleware/express.mjs.map +1 -0
- package/dist/middleware/fastify.d.mts +10 -0
- package/dist/middleware/fastify.d.ts +10 -0
- package/dist/middleware/fastify.js +127 -0
- package/dist/middleware/fastify.js.map +1 -0
- package/dist/middleware/fastify.mjs +90 -0
- package/dist/middleware/fastify.mjs.map +1 -0
- package/dist/middleware/hono.d.mts +10 -0
- package/dist/middleware/hono.d.ts +10 -0
- package/dist/middleware/hono.js +122 -0
- package/dist/middleware/hono.js.map +1 -0
- package/dist/middleware/hono.mjs +85 -0
- package/dist/middleware/hono.mjs.map +1 -0
- package/dist/middleware/nextjs.d.mts +22 -0
- package/dist/middleware/nextjs.d.ts +22 -0
- package/dist/middleware/nextjs.js +143 -0
- package/dist/middleware/nextjs.js.map +1 -0
- package/dist/middleware/nextjs.mjs +105 -0
- package/dist/middleware/nextjs.mjs.map +1 -0
- package/dist/middleware/web.d.mts +25 -0
- package/dist/middleware/web.d.ts +25 -0
- package/dist/middleware/web.js +128 -0
- package/dist/middleware/web.js.map +1 -0
- package/dist/middleware/web.mjs +91 -0
- package/dist/middleware/web.mjs.map +1 -0
- package/dist/payment/index.d.mts +21 -6
- package/dist/payment/index.d.ts +21 -6
- package/dist/payment/index.js +136 -9
- package/dist/payment/index.js.map +1 -1
- package/dist/payment/index.mjs +127 -9
- package/dist/payment/index.mjs.map +1 -1
- package/dist/{pricing-CxzwyiO6.d.mts → pricing-4n5Ota0D.d.mts} +14 -4
- package/dist/{pricing-CQ9DIFaw.d.ts → pricing-DHfH3ogG.d.ts} +14 -4
- package/dist/{rail_spec-XP0wKgJV.d.mts → rail_spec-D6qzh3J0.d.mts} +1 -1
- package/dist/{rail_spec-XP0wKgJV.d.ts → rail_spec-D6qzh3J0.d.ts} +1 -1
- package/dist/stripe-multichain/index.d.mts +150 -47
- package/dist/stripe-multichain/index.d.ts +150 -47
- package/dist/stripe-multichain/index.js +19749 -42
- package/dist/stripe-multichain/index.js.map +1 -1
- package/dist/stripe-multichain/index.mjs +19758 -27
- package/dist/stripe-multichain/index.mjs.map +1 -1
- package/dist/{x402_server-hgQzWQwB.d.mts → x402_server-Ciz2mls2.d.mts} +1 -1
- package/dist/{x402_server-hgQzWQwB.d.ts → x402_server-Ciz2mls2.d.ts} +1 -1
- package/package.json +43 -5
- package/dist/_response-BFYN3b6i.d.mts +0 -142
- package/dist/_response-_iPD5AIj.d.ts +0 -142
- package/dist/solana-Cds87OTu.d.mts +0 -67
- package/dist/solana-Cds87OTu.d.ts +0 -67
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { R as RateLimitCoreOptions } from '../_core-kI7FRAiZ.mjs';
|
|
2
|
+
import { Request, RequestHandler } from 'express';
|
|
3
|
+
|
|
4
|
+
interface RateLimitExpressOptions extends RateLimitCoreOptions {
|
|
5
|
+
/** Bucket key resolver. Default: first hop of `x-forwarded-for`, else req.ip, else `'unknown'`. */
|
|
6
|
+
keyResolver?: (req: Request) => string;
|
|
7
|
+
}
|
|
8
|
+
declare function rateLimitExpress(opts?: RateLimitExpressOptions): RequestHandler;
|
|
9
|
+
|
|
10
|
+
export { type RateLimitExpressOptions, rateLimitExpress };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { R as RateLimitCoreOptions } from '../_core-kI7FRAiZ.js';
|
|
2
|
+
import { Request, RequestHandler } from 'express';
|
|
3
|
+
|
|
4
|
+
interface RateLimitExpressOptions extends RateLimitCoreOptions {
|
|
5
|
+
/** Bucket key resolver. Default: first hop of `x-forwarded-for`, else req.ip, else `'unknown'`. */
|
|
6
|
+
keyResolver?: (req: Request) => string;
|
|
7
|
+
}
|
|
8
|
+
declare function rateLimitExpress(opts?: RateLimitExpressOptions): RequestHandler;
|
|
9
|
+
|
|
10
|
+
export { type RateLimitExpressOptions, rateLimitExpress };
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/middleware/express.ts
|
|
31
|
+
var express_exports = {};
|
|
32
|
+
__export(express_exports, {
|
|
33
|
+
rateLimitExpress: () => rateLimitExpress
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(express_exports);
|
|
36
|
+
|
|
37
|
+
// src/_redis.ts
|
|
38
|
+
async function tryCreateRedis(opts) {
|
|
39
|
+
const url = opts.url ?? process.env.REDIS_URL;
|
|
40
|
+
if (!url) return null;
|
|
41
|
+
try {
|
|
42
|
+
const mod = await import("ioredis");
|
|
43
|
+
const client = new mod.default(url, {
|
|
44
|
+
connectTimeout: opts.connectTimeout ?? 3e3,
|
|
45
|
+
maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,
|
|
46
|
+
tls: url.startsWith("rediss://") ? {} : void 0
|
|
47
|
+
});
|
|
48
|
+
client.on("error", (err) => console.error(`[${opts.label}] Redis error:`, err.message));
|
|
49
|
+
return client;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function memoizedRedis(opts) {
|
|
55
|
+
let promise = null;
|
|
56
|
+
return () => {
|
|
57
|
+
if (!promise) promise = tryCreateRedis(opts);
|
|
58
|
+
return promise;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/middleware/_core.ts
|
|
63
|
+
function createRateLimiter(opts = {}) {
|
|
64
|
+
const windowSeconds = opts.windowSeconds ?? 60;
|
|
65
|
+
const maxRequests = opts.maxRequests ?? 60;
|
|
66
|
+
const keyPrefix = opts.keyPrefix ?? "rl:";
|
|
67
|
+
const memMap = /* @__PURE__ */ new Map();
|
|
68
|
+
const getRedis = memoizedRedis({ url: opts.redisUrl, label: "rate-limit" });
|
|
69
|
+
const checkMem = (key) => {
|
|
70
|
+
const now = Date.now();
|
|
71
|
+
const entry = memMap.get(key);
|
|
72
|
+
if (!entry || entry.resetAt < now) {
|
|
73
|
+
memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1e3 });
|
|
74
|
+
return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };
|
|
75
|
+
}
|
|
76
|
+
entry.count++;
|
|
77
|
+
const remaining = Math.max(0, maxRequests - entry.count);
|
|
78
|
+
return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
async check(key) {
|
|
82
|
+
const r = await getRedis();
|
|
83
|
+
if (!r) return checkMem(key);
|
|
84
|
+
try {
|
|
85
|
+
const fullKey = `${keyPrefix}${key}`;
|
|
86
|
+
const count = await r.incr(fullKey);
|
|
87
|
+
if (count === 1) await r.expire(fullKey, windowSeconds);
|
|
88
|
+
const remaining = Math.max(0, maxRequests - count);
|
|
89
|
+
return { allowed: count <= maxRequests, remaining, limit: maxRequests };
|
|
90
|
+
} catch {
|
|
91
|
+
return checkMem(key);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
var RATE_LIMIT_JSON_BODY = {
|
|
97
|
+
error: { code: "rate_limited", message: "Too many requests" }
|
|
98
|
+
};
|
|
99
|
+
function defaultKeyFromForwardedFor(forwardedFor) {
|
|
100
|
+
if (!forwardedFor) return "unknown";
|
|
101
|
+
return forwardedFor.split(",")[0]?.trim() || "unknown";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/middleware/express.ts
|
|
105
|
+
function rateLimitExpress(opts = {}) {
|
|
106
|
+
const limiter = createRateLimiter(opts);
|
|
107
|
+
const keyResolver = opts.keyResolver ?? ((req) => {
|
|
108
|
+
const forwarded = req.header("x-forwarded-for");
|
|
109
|
+
if (forwarded) return defaultKeyFromForwardedFor(forwarded);
|
|
110
|
+
return req.ip ?? "unknown";
|
|
111
|
+
});
|
|
112
|
+
return async (req, res, next) => {
|
|
113
|
+
const { allowed, remaining, limit } = await limiter.check(keyResolver(req));
|
|
114
|
+
res.setHeader("X-RateLimit-Limit", String(limit));
|
|
115
|
+
res.setHeader("X-RateLimit-Remaining", String(remaining));
|
|
116
|
+
if (!allowed) {
|
|
117
|
+
res.setHeader("Cache-Control", "no-store");
|
|
118
|
+
res.status(429).json(RATE_LIMIT_JSON_BODY);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
next();
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
125
|
+
0 && (module.exports = {
|
|
126
|
+
rateLimitExpress
|
|
127
|
+
});
|
|
128
|
+
//# sourceMappingURL=express.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/middleware/express.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nexport interface RateLimitExpressOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else req.ip, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport function rateLimitExpress(opts: RateLimitExpressOptions = {}): RequestHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: Request): string => {\n const forwarded = req.header('x-forwarded-for');\n if (forwarded) return defaultKeyFromForwardedFor(forwarded);\n return req.ip ?? 'unknown';\n });\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n res.setHeader('X-RateLimit-Limit', String(limit));\n res.setHeader('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n res.setHeader('Cache-Control', 'no-store');\n res.status(429).json(RATE_LIMIT_JSON_BODY);\n return;\n }\n next();\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF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xE,QAAQ;AACN,eAAO,SAAS,GAAG;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC,OAAO,EAAE,MAAM,gBAAgB,SAAS,oBAAoB;AAC9D;AAIO,SAAS,2BAA2B,cAAiD;AAC1F,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;AF/DO,SAAS,iBAAiB,OAAgC,CAAC,GAAmB;AACnF,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBACJ,CAAC,QAAyB;AACzB,UAAM,YAAY,IAAI,OAAO,iBAAiB;AAC9C,QAAI,UAAW,QAAO,2BAA2B,SAAS;AAC1D,WAAO,IAAI,MAAM;AAAA,EACnB;AAEF,SAAO,OAAO,KAAc,KAAe,SAAuB;AAChE,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,QAAI,UAAU,qBAAqB,OAAO,KAAK,CAAC;AAChD,QAAI,UAAU,yBAAyB,OAAO,SAAS,CAAC;AACxD,QAAI,CAAC,SAAS;AACZ,UAAI,UAAU,iBAAiB,UAAU;AACzC,UAAI,OAAO,GAAG,EAAE,KAAK,oBAAoB;AACzC;AAAA,IACF;AACA,SAAK;AAAA,EACP;AACF;","names":[]}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// src/_redis.ts
|
|
2
|
+
async function tryCreateRedis(opts) {
|
|
3
|
+
const url = opts.url ?? process.env.REDIS_URL;
|
|
4
|
+
if (!url) return null;
|
|
5
|
+
try {
|
|
6
|
+
const mod = await import("ioredis");
|
|
7
|
+
const client = new mod.default(url, {
|
|
8
|
+
connectTimeout: opts.connectTimeout ?? 3e3,
|
|
9
|
+
maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,
|
|
10
|
+
tls: url.startsWith("rediss://") ? {} : void 0
|
|
11
|
+
});
|
|
12
|
+
client.on("error", (err) => console.error(`[${opts.label}] Redis error:`, err.message));
|
|
13
|
+
return client;
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function memoizedRedis(opts) {
|
|
19
|
+
let promise = null;
|
|
20
|
+
return () => {
|
|
21
|
+
if (!promise) promise = tryCreateRedis(opts);
|
|
22
|
+
return promise;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/middleware/_core.ts
|
|
27
|
+
function createRateLimiter(opts = {}) {
|
|
28
|
+
const windowSeconds = opts.windowSeconds ?? 60;
|
|
29
|
+
const maxRequests = opts.maxRequests ?? 60;
|
|
30
|
+
const keyPrefix = opts.keyPrefix ?? "rl:";
|
|
31
|
+
const memMap = /* @__PURE__ */ new Map();
|
|
32
|
+
const getRedis = memoizedRedis({ url: opts.redisUrl, label: "rate-limit" });
|
|
33
|
+
const checkMem = (key) => {
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const entry = memMap.get(key);
|
|
36
|
+
if (!entry || entry.resetAt < now) {
|
|
37
|
+
memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1e3 });
|
|
38
|
+
return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };
|
|
39
|
+
}
|
|
40
|
+
entry.count++;
|
|
41
|
+
const remaining = Math.max(0, maxRequests - entry.count);
|
|
42
|
+
return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
async check(key) {
|
|
46
|
+
const r = await getRedis();
|
|
47
|
+
if (!r) return checkMem(key);
|
|
48
|
+
try {
|
|
49
|
+
const fullKey = `${keyPrefix}${key}`;
|
|
50
|
+
const count = await r.incr(fullKey);
|
|
51
|
+
if (count === 1) await r.expire(fullKey, windowSeconds);
|
|
52
|
+
const remaining = Math.max(0, maxRequests - count);
|
|
53
|
+
return { allowed: count <= maxRequests, remaining, limit: maxRequests };
|
|
54
|
+
} catch {
|
|
55
|
+
return checkMem(key);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
var RATE_LIMIT_JSON_BODY = {
|
|
61
|
+
error: { code: "rate_limited", message: "Too many requests" }
|
|
62
|
+
};
|
|
63
|
+
function defaultKeyFromForwardedFor(forwardedFor) {
|
|
64
|
+
if (!forwardedFor) return "unknown";
|
|
65
|
+
return forwardedFor.split(",")[0]?.trim() || "unknown";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/middleware/express.ts
|
|
69
|
+
function rateLimitExpress(opts = {}) {
|
|
70
|
+
const limiter = createRateLimiter(opts);
|
|
71
|
+
const keyResolver = opts.keyResolver ?? ((req) => {
|
|
72
|
+
const forwarded = req.header("x-forwarded-for");
|
|
73
|
+
if (forwarded) return defaultKeyFromForwardedFor(forwarded);
|
|
74
|
+
return req.ip ?? "unknown";
|
|
75
|
+
});
|
|
76
|
+
return async (req, res, next) => {
|
|
77
|
+
const { allowed, remaining, limit } = await limiter.check(keyResolver(req));
|
|
78
|
+
res.setHeader("X-RateLimit-Limit", String(limit));
|
|
79
|
+
res.setHeader("X-RateLimit-Remaining", String(remaining));
|
|
80
|
+
if (!allowed) {
|
|
81
|
+
res.setHeader("Cache-Control", "no-store");
|
|
82
|
+
res.status(429).json(RATE_LIMIT_JSON_BODY);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
next();
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export {
|
|
89
|
+
rateLimitExpress
|
|
90
|
+
};
|
|
91
|
+
//# sourceMappingURL=express.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/express.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nexport interface RateLimitExpressOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else req.ip, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport function rateLimitExpress(opts: RateLimitExpressOptions = {}): RequestHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: Request): string => {\n const forwarded = req.header('x-forwarded-for');\n if (forwarded) return defaultKeyFromForwardedFor(forwarded);\n return req.ip ?? 'unknown';\n });\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n res.setHeader('X-RateLimit-Limit', String(limit));\n res.setHeader('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n res.setHeader('Cache-Control', 'no-store');\n res.status(429).json(RATE_LIMIT_JSON_BODY);\n return;\n }\n next();\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;A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ookHandler } from 'fastify';
|
|
3
|
+
|
|
4
|
+
interface RateLimitFastifyOptions extends RateLimitCoreOptions {
|
|
5
|
+
/** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `req.ip`, else `'unknown'`. */
|
|
6
|
+
keyResolver?: (req: FastifyRequest) => string;
|
|
7
|
+
}
|
|
8
|
+
declare function rateLimitFastify(opts?: RateLimitFastifyOptions): preHandlerHookHandler;
|
|
9
|
+
|
|
10
|
+
export { type RateLimitFastifyOptions, rateLimitFastify };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { R as RateLimitCoreOptions } from '../_core-kI7FRAiZ.js';
|
|
2
|
+
import { FastifyRequest, preHandlerHookHandler } from 'fastify';
|
|
3
|
+
|
|
4
|
+
interface RateLimitFastifyOptions extends RateLimitCoreOptions {
|
|
5
|
+
/** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `req.ip`, else `'unknown'`. */
|
|
6
|
+
keyResolver?: (req: FastifyRequest) => string;
|
|
7
|
+
}
|
|
8
|
+
declare function rateLimitFastify(opts?: RateLimitFastifyOptions): preHandlerHookHandler;
|
|
9
|
+
|
|
10
|
+
export { type RateLimitFastifyOptions, rateLimitFastify };
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/middleware/fastify.ts
|
|
31
|
+
var fastify_exports = {};
|
|
32
|
+
__export(fastify_exports, {
|
|
33
|
+
rateLimitFastify: () => rateLimitFastify
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(fastify_exports);
|
|
36
|
+
|
|
37
|
+
// src/_redis.ts
|
|
38
|
+
async function tryCreateRedis(opts) {
|
|
39
|
+
const url = opts.url ?? process.env.REDIS_URL;
|
|
40
|
+
if (!url) return null;
|
|
41
|
+
try {
|
|
42
|
+
const mod = await import("ioredis");
|
|
43
|
+
const client = new mod.default(url, {
|
|
44
|
+
connectTimeout: opts.connectTimeout ?? 3e3,
|
|
45
|
+
maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,
|
|
46
|
+
tls: url.startsWith("rediss://") ? {} : void 0
|
|
47
|
+
});
|
|
48
|
+
client.on("error", (err) => console.error(`[${opts.label}] Redis error:`, err.message));
|
|
49
|
+
return client;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function memoizedRedis(opts) {
|
|
55
|
+
let promise = null;
|
|
56
|
+
return () => {
|
|
57
|
+
if (!promise) promise = tryCreateRedis(opts);
|
|
58
|
+
return promise;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/middleware/_core.ts
|
|
63
|
+
function createRateLimiter(opts = {}) {
|
|
64
|
+
const windowSeconds = opts.windowSeconds ?? 60;
|
|
65
|
+
const maxRequests = opts.maxRequests ?? 60;
|
|
66
|
+
const keyPrefix = opts.keyPrefix ?? "rl:";
|
|
67
|
+
const memMap = /* @__PURE__ */ new Map();
|
|
68
|
+
const getRedis = memoizedRedis({ url: opts.redisUrl, label: "rate-limit" });
|
|
69
|
+
const checkMem = (key) => {
|
|
70
|
+
const now = Date.now();
|
|
71
|
+
const entry = memMap.get(key);
|
|
72
|
+
if (!entry || entry.resetAt < now) {
|
|
73
|
+
memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1e3 });
|
|
74
|
+
return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };
|
|
75
|
+
}
|
|
76
|
+
entry.count++;
|
|
77
|
+
const remaining = Math.max(0, maxRequests - entry.count);
|
|
78
|
+
return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
async check(key) {
|
|
82
|
+
const r = await getRedis();
|
|
83
|
+
if (!r) return checkMem(key);
|
|
84
|
+
try {
|
|
85
|
+
const fullKey = `${keyPrefix}${key}`;
|
|
86
|
+
const count = await r.incr(fullKey);
|
|
87
|
+
if (count === 1) await r.expire(fullKey, windowSeconds);
|
|
88
|
+
const remaining = Math.max(0, maxRequests - count);
|
|
89
|
+
return { allowed: count <= maxRequests, remaining, limit: maxRequests };
|
|
90
|
+
} catch {
|
|
91
|
+
return checkMem(key);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
var RATE_LIMIT_JSON_BODY = {
|
|
97
|
+
error: { code: "rate_limited", message: "Too many requests" }
|
|
98
|
+
};
|
|
99
|
+
function defaultKeyFromForwardedFor(forwardedFor) {
|
|
100
|
+
if (!forwardedFor) return "unknown";
|
|
101
|
+
return forwardedFor.split(",")[0]?.trim() || "unknown";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/middleware/fastify.ts
|
|
105
|
+
function rateLimitFastify(opts = {}) {
|
|
106
|
+
const limiter = createRateLimiter(opts);
|
|
107
|
+
const keyResolver = opts.keyResolver ?? ((req) => {
|
|
108
|
+
const forwarded = req.headers["x-forwarded-for"];
|
|
109
|
+
const forwardedStr = Array.isArray(forwarded) ? forwarded[0] : forwarded;
|
|
110
|
+
if (forwardedStr) return defaultKeyFromForwardedFor(forwardedStr);
|
|
111
|
+
return req.ip ?? "unknown";
|
|
112
|
+
});
|
|
113
|
+
return async (req, reply) => {
|
|
114
|
+
const { allowed, remaining, limit } = await limiter.check(keyResolver(req));
|
|
115
|
+
reply.header("X-RateLimit-Limit", String(limit));
|
|
116
|
+
reply.header("X-RateLimit-Remaining", String(remaining));
|
|
117
|
+
if (!allowed) {
|
|
118
|
+
reply.header("Cache-Control", "no-store");
|
|
119
|
+
reply.code(429).send(RATE_LIMIT_JSON_BODY);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
124
|
+
0 && (module.exports = {
|
|
125
|
+
rateLimitFastify
|
|
126
|
+
});
|
|
127
|
+
//# sourceMappingURL=fastify.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/middleware/fastify.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface RateLimitFastifyOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `req.ip`, else `'unknown'`. */\n keyResolver?: (req: FastifyRequest) => string;\n}\n\nexport function rateLimitFastify(opts: RateLimitFastifyOptions = {}): preHandlerHookHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: FastifyRequest): string => {\n const forwarded = req.headers['x-forwarded-for'];\n const forwardedStr = Array.isArray(forwarded) ? forwarded[0] : forwarded;\n if (forwardedStr) return defaultKeyFromForwardedFor(forwardedStr);\n return req.ip ?? 'unknown';\n });\n\n return async (req: FastifyRequest, reply: FastifyReply) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n reply.header('X-RateLimit-Limit', String(limit));\n reply.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n reply.header('Cache-Control', 'no-store');\n reply.code(429).send(RATE_LIMIT_JSON_BODY);\n }\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAA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}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// src/_redis.ts
|
|
2
|
+
async function tryCreateRedis(opts) {
|
|
3
|
+
const url = opts.url ?? process.env.REDIS_URL;
|
|
4
|
+
if (!url) return null;
|
|
5
|
+
try {
|
|
6
|
+
const mod = await import("ioredis");
|
|
7
|
+
const client = new mod.default(url, {
|
|
8
|
+
connectTimeout: opts.connectTimeout ?? 3e3,
|
|
9
|
+
maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,
|
|
10
|
+
tls: url.startsWith("rediss://") ? {} : void 0
|
|
11
|
+
});
|
|
12
|
+
client.on("error", (err) => console.error(`[${opts.label}] Redis error:`, err.message));
|
|
13
|
+
return client;
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function memoizedRedis(opts) {
|
|
19
|
+
let promise = null;
|
|
20
|
+
return () => {
|
|
21
|
+
if (!promise) promise = tryCreateRedis(opts);
|
|
22
|
+
return promise;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/middleware/_core.ts
|
|
27
|
+
function createRateLimiter(opts = {}) {
|
|
28
|
+
const windowSeconds = opts.windowSeconds ?? 60;
|
|
29
|
+
const maxRequests = opts.maxRequests ?? 60;
|
|
30
|
+
const keyPrefix = opts.keyPrefix ?? "rl:";
|
|
31
|
+
const memMap = /* @__PURE__ */ new Map();
|
|
32
|
+
const getRedis = memoizedRedis({ url: opts.redisUrl, label: "rate-limit" });
|
|
33
|
+
const checkMem = (key) => {
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const entry = memMap.get(key);
|
|
36
|
+
if (!entry || entry.resetAt < now) {
|
|
37
|
+
memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1e3 });
|
|
38
|
+
return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };
|
|
39
|
+
}
|
|
40
|
+
entry.count++;
|
|
41
|
+
const remaining = Math.max(0, maxRequests - entry.count);
|
|
42
|
+
return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
async check(key) {
|
|
46
|
+
const r = await getRedis();
|
|
47
|
+
if (!r) return checkMem(key);
|
|
48
|
+
try {
|
|
49
|
+
const fullKey = `${keyPrefix}${key}`;
|
|
50
|
+
const count = await r.incr(fullKey);
|
|
51
|
+
if (count === 1) await r.expire(fullKey, windowSeconds);
|
|
52
|
+
const remaining = Math.max(0, maxRequests - count);
|
|
53
|
+
return { allowed: count <= maxRequests, remaining, limit: maxRequests };
|
|
54
|
+
} catch {
|
|
55
|
+
return checkMem(key);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
var RATE_LIMIT_JSON_BODY = {
|
|
61
|
+
error: { code: "rate_limited", message: "Too many requests" }
|
|
62
|
+
};
|
|
63
|
+
function defaultKeyFromForwardedFor(forwardedFor) {
|
|
64
|
+
if (!forwardedFor) return "unknown";
|
|
65
|
+
return forwardedFor.split(",")[0]?.trim() || "unknown";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/middleware/fastify.ts
|
|
69
|
+
function rateLimitFastify(opts = {}) {
|
|
70
|
+
const limiter = createRateLimiter(opts);
|
|
71
|
+
const keyResolver = opts.keyResolver ?? ((req) => {
|
|
72
|
+
const forwarded = req.headers["x-forwarded-for"];
|
|
73
|
+
const forwardedStr = Array.isArray(forwarded) ? forwarded[0] : forwarded;
|
|
74
|
+
if (forwardedStr) return defaultKeyFromForwardedFor(forwardedStr);
|
|
75
|
+
return req.ip ?? "unknown";
|
|
76
|
+
});
|
|
77
|
+
return async (req, reply) => {
|
|
78
|
+
const { allowed, remaining, limit } = await limiter.check(keyResolver(req));
|
|
79
|
+
reply.header("X-RateLimit-Limit", String(limit));
|
|
80
|
+
reply.header("X-RateLimit-Remaining", String(remaining));
|
|
81
|
+
if (!allowed) {
|
|
82
|
+
reply.header("Cache-Control", "no-store");
|
|
83
|
+
reply.code(429).send(RATE_LIMIT_JSON_BODY);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
export {
|
|
88
|
+
rateLimitFastify
|
|
89
|
+
};
|
|
90
|
+
//# sourceMappingURL=fastify.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/fastify.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface RateLimitFastifyOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `req.ip`, else `'unknown'`. */\n keyResolver?: (req: FastifyRequest) => string;\n}\n\nexport function rateLimitFastify(opts: RateLimitFastifyOptions = {}): preHandlerHookHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: FastifyRequest): string => {\n const forwarded = req.headers['x-forwarded-for'];\n const forwardedStr = Array.isArray(forwarded) ? forwarded[0] : forwarded;\n if (forwardedStr) return defaultKeyFromForwardedFor(forwardedStr);\n return req.ip ?? 'unknown';\n });\n\n return async (req: FastifyRequest, reply: FastifyReply) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n reply.header('X-RateLimit-Limit', String(limit));\n reply.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n reply.header('Cache-Control', 'no-store');\n reply.code(429).send(RATE_LIMIT_JSON_BODY);\n }\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC,GAAgB;AAC9E,QAAM,gBAAgB,KAAK,iBAAiB;AAC5C,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,YAAY,KAAK,aAAa;AAEpC,QAAM,SAAS,oBAAI,IAAgD;AACnE,QAAM,WAAW,cAAyB,EAAE,KAAK,KAAK,UAAU,OAAO,aAAa,CAAC;AAErF,QAAM,WAAW,CAAC,QAAmC;AACnD,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,QAAQ,OAAO,IAAI,GAAG;AAC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BAA2B,YAAY;AAChE,WAAO,IAAI,MAAM;AAAA,EACnB;AAEF,SAAO,OAAO,KAAqB,UAAwB;AACzD,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,UAAM,OAAO,qBAAqB,OAAO,KAAK,CAAC;AAC/C,UAAM,OAAO,yBAAyB,OAAO,SAAS,CAAC;AACvD,QAAI,CAAC,SAAS;AACZ,YAAM,OAAO,iBAAiB,UAAU;AACxC,YAAM,KAAK,GAAG,EAAE,KAAK,oBAAoB;AAAA,IAC3C;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { R as RateLimitCoreOptions } from '../_core-kI7FRAiZ.mjs';
|
|
2
|
+
import { Context, MiddlewareHandler } from 'hono';
|
|
3
|
+
|
|
4
|
+
interface RateLimitHonoOptions extends RateLimitCoreOptions {
|
|
5
|
+
/** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */
|
|
6
|
+
keyResolver?: (c: Context) => string;
|
|
7
|
+
}
|
|
8
|
+
declare function rateLimitHono(opts?: RateLimitHonoOptions): MiddlewareHandler;
|
|
9
|
+
|
|
10
|
+
export { type RateLimitHonoOptions, rateLimitHono };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { R as RateLimitCoreOptions } from '../_core-kI7FRAiZ.js';
|
|
2
|
+
import { Context, MiddlewareHandler } from 'hono';
|
|
3
|
+
|
|
4
|
+
interface RateLimitHonoOptions extends RateLimitCoreOptions {
|
|
5
|
+
/** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */
|
|
6
|
+
keyResolver?: (c: Context) => string;
|
|
7
|
+
}
|
|
8
|
+
declare function rateLimitHono(opts?: RateLimitHonoOptions): MiddlewareHandler;
|
|
9
|
+
|
|
10
|
+
export { type RateLimitHonoOptions, rateLimitHono };
|