@krizaka/rate-limit

中文文档
0.2.2发布于 2026/11/01Apache-2.0TypeScriptES Module构建来源已验证

Limits per action for every Krizaka product: fixed windows per address and per subject, the limits read from the admin's settings, a memory store and a PostgreSQL store whose atomic upsert counts exactly under concurrency, a stable 429 with Retry-After. N

原始使用文档

@krizaka/rate-limit

Limits per action for every Krizaka product: fixed windows per address and per subject, the limits read from the admin's settings, a memory store and a PostgreSQL store shared by every instance. It replaces the rate-limit.ts that Yomizaka and Akinaza carried byte for byte, and the PostgreSQL variants some products carried.

import { emitMigration } from "@krizaka/db";
import { createLimiter, dbLimitStore, rateLimitSchema, RateLimited } from "@krizaka/rate-limit";
import { limitsFromSettings, rateLimitSettings } from "@krizaka/rate-limit/settings";
import { clientIp } from "@krizaka/auth";

emitMigration(rateLimitSchema, 1, { tables: {} }); // commit the SQL once, in your migrations: table rate_limit.bucket

// the registry fragment: limits.signIn.perIp, limits.signIn.perSubject, limits.signIn.windowSeconds… the admin changes them without a redeploy
export const limitSettings = rateLimitSettings({ signIn: { perIp: 30, perSubject: 10, windowSeconds: 900 }, me: { perIp: 600, windowSeconds: 3600 } });

const limiter = createLimiter({
  store: dbLimitStore(query),                       // or memoryLimitStore() in one process and in tests
  clock: { now: () => new Date() },
  limits: limitsFromSettings((key) => settings.get(key)), // or a plain table: { signIn: { perIp: 30, perSubject: 10, windowSeconds: 900 } }
  onStoreError: (error, action) => log.error({ error, action }),
});

// in a route
await limiter.enforce("signIn", { ip: clientIp(req.headers, rules), subject: email }); // throws RateLimited: status 429, headers { "Retry-After" }
const verdict = await limiter.check("signIn", keys); // { ok: true } | { ok: false, retryAfterSeconds, scope: "ip" | "subject" }
await limiter.forget("signIn", keys); // a successful sign-in clears its failures
  • The semantics of the copies, so their tests pass unchanged: a window starts at its first hit and lasts windowSeconds; a refused hit is counted too; the address is counted first and a refusal stops there; the subject is compared in lower case and counted only when the action has a perSubject limit and one is given; an unknown address is counted under unknown. The old call limit("sign-in", req, email, [30, 900], [10, 900]) is enforce("signIn", { ip, subject: email }) with { perIp: 30, perSubject: 10, windowSeconds: 900 } in the settings.
  • The limiter takes keys, never a request. The client's address is extracted by clientIp of @krizaka/auth; the package reads no header.
  • Limits are settings. rateLimitSettings (@krizaka/rate-limit/settings, needs @krizaka/settings and zod) declares limits.<action>.perIp, .perSubject and .windowSeconds as integers with the product's defaults; limitsFromSettings reads them back at each check. An action id is letters and digits (signIn), because it sits in a settings key.
  • Stores: memoryLimitStore({ maxKeys }) keeps the copies' bound (10 000 windows; ended ones dropped first, then one shared overflow window, so a flood of keys limits itself and never clears a blocked caller's count). dbLimitStore(query, { schema }) counts in one atomic statement (INSERT … ON CONFLICT DO UPDATE … RETURNING), so 100 parallel checks count exactly and every instance sees the same counters; times come from the injected clock, not the database's. The table is rate_limit.bucket (key, count, window_start, reset_at), one row per key (a deviation from (key, window_start) as primary key: with the first hit starting the window, two concurrent first hits would otherwise open two rows). purge(now) deletes the ended windows: call it from the product's job.
  • A store that fails lets the request through (the limiter must not take the site down) and tells onStoreError; failOpen: false rethrows instead.
  • The extras are in the port: peek (read without counting), set (a lock-out) and reset.
  • limitStoreContract (from @krizaka/rate-limit/testkit) is the contract every store runs.

Turnstile (@krizaka/rate-limit/turnstile)

A Cloudflare Turnstile widget protects nothing until the server asks Cloudflare about the token it produced. createTurnstileVerifier({ secret, hostnames, now }) returns verify({ token, remoteIp, action }) → { ok: true } or { ok: false, reason, errorCodes }. It fails closed: no secret (not-configured), no or oversized token (missing-token), a refusal (rejected), a token solved on another hostname or for another form's action, a replayed token (single-use, remembered for Cloudflare's 300 s), a timeout or an unreachable service (unavailable) all refuse. The secret is ABUSE_CAPTCHA_SECRET_KEY with ABUSE_CAPTCHA_PROVIDER=turnstile (the provider is a value; never in the browser); the site key is the public NEXT_PUBLIC_ABUSE_CAPTCHA_SITE_KEY. Answer a refusal with a 4xx and send nothing; log the reason only (no address, no message). Rule turnstile-server-side of the org registry.

版本与发布记录

@krizaka/rate-limit 共发布 7 个版本,首次发布于 2026/10/27;过去 12 个月发布了 7 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.2latest2026/11/011 天前
0.2.12026/10/304 天前
0.2.02026/10/295 天前
0.1.22026/10/295 天前
0.1.12026/10/277 天前
0.1.02026/10/277 天前

关于 @krizaka/rate-limit 的常见问题

@krizaka/rate-limit 是什么?

每个Krizaka产品的每个操作限制:每个地址和每个主题的固定窗口,从管理设置中读取的限制,内存存储和PostgreSQL存储的原子upsert计数恰好在并发下,Retry-After的稳定429。N

如何安装 @krizaka/rate-limit?

在项目目录运行 npm install @krizaka/rate-limit,或使用 pnpm add / yarn add / bun add。

@krizaka/rate-limit 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@krizaka/rate-limit 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@krizaka/rate-limit 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@krizaka/rate-limit 可以商用吗?

@krizaka/rate-limit 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@krizaka/rate-limit 还在维护吗?

最新版本 0.2.2 发布于 2026/11/01(1 天前);至今共发布 7 个版本,其中过去 12 个月发布了 7 个;首次发布于 2026/10/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。