Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

chore: remove upstash from stack (#589)

Sidf08cce249de9
diff --git a/.env.example b/.env.example
index ae6c5e74ce..4a57642c76 100644
--- a/.env.example
+++ b/.env.example
@@ -42,8 +42,7 @@ TRIGGER_SECRET_KEY="tr_dev_********************"
TRIGGER_API_URL="https://api.trigger.dev"
TRIGGER_PROJECT_ID="proj_**********************"
-UPSTASH_REDIS_REST_URL="https://**.upstash.io"
-UPSTASH_REDIS_REST_TOKEN="*******************"
+REDIS_URL="redis://localhost:6379"
VERCEL_URL="http://localhost:3000"
diff --git a/README.md b/README.md
index 558e95d241..35f1049b97 100644
--- a/README.md
+++ b/README.md
@@ -170,10 +170,9 @@ $ cp ./.env.example ./.env
- `SUPABASE_SERVICE_ROLE_KEY=[service_role key]`
- `SUPABASE_ANON_KEY=[anon key]`
-2. [Create a Redis database in upstash](https://console.upstash.com/redis) and copy the following from the `REST API` section:
+2. Set up a Redis instance (local or cloud) and add the connection URL:
-- `UPSTASH_REDIS_REST_URL=[UPSTASH_REDIS_REST_URL]`
-- `UPSTASH_REDIS_REST_TOKEN=[UPSTASH_REDIS_REST_TOKEN]`
+- `REDIS_URL=[redis://user:password@host:port]`
3. Navigate to the project you created in [https://cloud.trigger.dev](https://cloud.trigger.dev) and copy the following from the `Environments & API Keys` section:
diff --git a/apps/academy/app/config.tsx b/apps/academy/app/config.tsx
index 1f37c45cc1..c026bdc6b5 100644
--- a/apps/academy/app/config.tsx
+++ b/apps/academy/app/config.tsx
@@ -1290,7 +1290,8 @@ export const modules: Config = [
},
{
id: "gauges-calibrations",
- loomUrl: "https://www.loom.com/share/e78ae8fb641f4543b1bc4980e9c3acaa",
+ loomUrl:
+ "https://www.loom.com/share/e78ae8fb641f4543b1bc4980e9c3acaa",
name: "Gauges and Calibrations",
description:
"Learn how to manage measurement equipment and calibration schedules.",
diff --git a/apps/academy/app/routes/_auth+/login.tsx b/apps/academy/app/routes/_auth+/login.tsx
index 8caae51946..f16586926a 100644
--- a/apps/academy/app/routes/_auth+/login.tsx
+++ b/apps/academy/app/routes/_auth+/login.tsx
@@ -11,7 +11,7 @@ import { sendMagicLink, verifyAuthSession } from "@carbon/auth/auth.server";
import { flash, getAuthSession } from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";
-import { redis } from "@carbon/kv";
+import { Ratelimit, redis } from "@carbon/kv";
import {
Alert,
AlertDescription,
@@ -22,7 +22,6 @@ import {
toast,
VStack
} from "@carbon/react";
-import { Ratelimit } from "@upstash/ratelimit";
import { LuCircleAlert } from "react-icons/lu";
import type {
ActionFunctionArgs,
diff --git a/apps/academy/package.json b/apps/academy/package.json
index 74676b2c6a..814b2a2991 100644
--- a/apps/academy/package.json
+++ b/apps/academy/package.json
@@ -18,7 +18,6 @@
"@tailwindcss/forms": "^0.5.7",
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.10",
- "@upstash/ratelimit": "^2.0.5",
"@vercel/analytics": "^1.2.2",
"@vercel/react-router": "^1.2.4",
"framer-motion": "^11.1.7",
diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.ts
index b457e9dde4..5ed04580f4 100644
--- a/apps/erp/app/modules/settings/settings.server.ts
+++ b/apps/erp/app/modules/settings/settings.server.ts
@@ -365,10 +365,10 @@ export async function getIntegrationHealth(
const key = `integrations:${companyId}:${integration.id}:health`;
- const cached = await redis.get<number>(key);
+ const cached = await redis.get(key);
// Only cache healthy status
- if (cached && cached == 1) {
+ if (cached === "1") {
return {
...integration,
health: "healthy"
@@ -380,9 +380,7 @@ export async function getIntegrationHealth(
integration.metadata as Record<string, any>
);
- await redis.set(key, status ? "1" : "0", {
- ex: INTEGRATION_CACHE_TTL * 5 // Cache for 5 minutes
- });
+ await redis.set(key, status ? "1" : "0", "EX", INTEGRATION_CACHE_TTL * 5); // Cache for 5 minutes
return {
...integration,
diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsx
index fe524b0a23..41f99c508a 100644
--- a/apps/erp/app/routes/_public+/login.tsx
+++ b/apps/erp/app/routes/_public+/login.tsx
@@ -15,7 +15,7 @@ import { flash, getAuthSession } from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
import { sendVerificationCode } from "@carbon/auth/verification.server";
import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";
-import { redis } from "@carbon/kv";
+import { Ratelimit, redis } from "@carbon/kv";
import {
Alert,
AlertDescription,
@@ -29,7 +29,6 @@ import {
import { ItarLoginDisclaimer, useMode } from "@carbon/remix";
import { Edition } from "@carbon/utils";
import { Turnstile } from "@marsidev/react-turnstile";
-import { Ratelimit } from "@upstash/ratelimit";
import { useEffect, useState } from "react";
import { LuCircleAlert } from "react-icons/lu";
import type {
diff --git a/apps/erp/app/routes/_public+/verify.tsx b/apps/erp/app/routes/_public+/verify.tsx
index 5397e2326a..e1c9adba1b 100644
--- a/apps/erp/app/routes/_public+/verify.tsx
+++ b/apps/erp/app/routes/_public+/verify.tsx
@@ -11,7 +11,7 @@ import {
} from "@carbon/auth/session.server";
import { verifyEmailCode } from "@carbon/auth/verification.server";
import { Hidden, InputOTP, ValidatedForm, validator } from "@carbon/form";
-import { redis } from "@carbon/kv";
+import { Ratelimit, redis } from "@carbon/kv";
import {
Alert,
AlertDescription,
@@ -20,7 +20,6 @@ import {
Heading,
VStack
} from "@carbon/react";
-import { Ratelimit } from "@upstash/ratelimit";
import { LuCircleAlert } from "react-icons/lu";
import type {
ActionFunctionArgs,
diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts
index 964605c274..dd77ed42d6 100644
--- a/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts
+++ b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts
@@ -1,18 +1,12 @@
import { openai } from "@ai-sdk/openai";
import type { AgentConfig } from "@ai-sdk-tools/agents";
import { Agent } from "@ai-sdk-tools/agents";
-import { UpstashProvider } from "@ai-sdk-tools/memory/upstash";
-import { UPSTASH_REDIS_REST_TOKEN, UPSTASH_REDIS_REST_URL } from "@carbon/auth";
-import { Redis } from "@upstash/redis";
+import { RedisProvider } from "@ai-sdk-tools/memory/redis";
+import { redis } from "@carbon/kv";
import type { ChatContext } from "./context";
import { PROFILE_PROMPT, SUGGESTION_PROMPT, TITLE_PROMPT } from "./prompts";
-export const memoryProvider = new UpstashProvider(
- new Redis({
- url: UPSTASH_REDIS_REST_URL,
- token: UPSTASH_REDIS_REST_TOKEN
- })
-);
+export const memoryProvider = new RedisProvider(redis);
export const createAgent = (config: AgentConfig<ChatContext>) => {
return new Agent({
diff --git a/apps/erp/app/routes/api+/docs.ts b/apps/erp/app/routes/api+/docs.ts
index 14c58b302f..1a26076dff 100644
--- a/apps/erp/app/routes/api+/docs.ts
+++ b/apps/erp/app/routes/api+/docs.ts
@@ -1,6 +1,5 @@
import swaggerDocsSchema from "@carbon/database/swagger-docs-schema";
-import { redis } from "@carbon/kv";
-import { Ratelimit } from "@upstash/ratelimit";
+import { Ratelimit, redis } from "@carbon/kv";
import {
type ClientLoaderFunctionArgs,
data,
diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsx
index 98a7f10925..c58419e99b 100644
--- a/apps/erp/app/routes/share+/customer.$id.$.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx
@@ -1,7 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { redis } from "@carbon/kv";
+import { Ratelimit, redis } from "@carbon/kv";
import { supportedModelTypes } from "@carbon/utils";
-import { Ratelimit } from "@upstash/ratelimit";
import type { LoaderFunctionArgs } from "react-router";
import { getJobByOperationId } from "~/modules/production";
import { getCustomerPortal } from "~/modules/shared/shared.service";
diff --git a/apps/erp/package.json b/apps/erp/package.json
index 47b4be3e45..a358e9a79c 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -49,7 +49,6 @@
"@tanstack/react-virtual": "^3.5.0",
"@trigger.dev/react-hooks": "4.0.6",
"@trigger.dev/sdk": "4.0.6",
- "@upstash/ratelimit": "^2.0.5",
"@vercel/analytics": "^1.2.2",
"@vercel/react-router": "^1.2.4",
"@visx/responsive": "^2.1.0",
diff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsx
index c3f7655344..d1484c66c1 100644
--- a/apps/mes/app/routes/_public+/login.tsx
+++ b/apps/mes/app/routes/_public+/login.tsx
@@ -12,7 +12,7 @@ import { sendMagicLink, verifyAuthSession } from "@carbon/auth/auth.server";
import { flash, getAuthSession } from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";
-import { redis } from "@carbon/kv";
+import { Ratelimit, redis } from "@carbon/kv";
import {
Alert,
AlertDescription,
@@ -25,7 +25,6 @@ import {
} from "@carbon/react";
import { ItarLoginDisclaimer } from "@carbon/remix";
import { Edition } from "@carbon/utils";
-import { Ratelimit } from "@upstash/ratelimit";
import { LuCircleAlert } from "react-icons/lu";
import type {
ActionFunctionArgs,
diff --git a/apps/mes/package.json b/apps/mes/package.json
index 9823864cfa..aa8521b536 100644
--- a/apps/mes/package.json
+++ b/apps/mes/package.json
@@ -26,7 +26,6 @@
"@tailwindcss/forms": "^0.5.7",
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.10",
- "@upstash/ratelimit": "^2.0.5",
"@vercel/analytics": "^1.2.2",
"@vercel/react-router": "^1.2.4",
"cookie": "0.6.0",
diff --git a/apps/starter/app/routes/_public+/login.tsx b/apps/starter/app/routes/_public+/login.tsx
index 1bcfef06a8..55cca2044a 100644
--- a/apps/starter/app/routes/_public+/login.tsx
+++ b/apps/starter/app/routes/_public+/login.tsx
@@ -11,7 +11,7 @@ import { sendMagicLink, verifyAuthSession } from "@carbon/auth/auth.server";
import { flash, getAuthSession } from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";
-import { redis } from "@carbon/kv";
+import { Ratelimit, redis } from "@carbon/kv";
import {
Alert,
AlertDescription,
@@ -22,7 +22,6 @@ import {
toast,
VStack
} from "@carbon/react";
-import { Ratelimit } from "@upstash/ratelimit";
import { LuCircleAlert } from "react-icons/lu";
import type {
ActionFunctionArgs,
diff --git a/apps/starter/package.json b/apps/starter/package.json
index 8817b66690..01a6ac8e26 100644
--- a/apps/starter/package.json
+++ b/apps/starter/package.json
@@ -18,7 +18,6 @@
"@tailwindcss/forms": "^0.5.7",
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.10",
- "@upstash/ratelimit": "^2.0.5",
"@vercel/analytics": "^1.2.2",
"@vercel/react-router": "^1.2.4",
"framer-motion": "^11.1.7",
diff --git a/ci/src/deploy.ts b/ci/src/deploy.ts
index 8e71994322..73231ba66e 100644
--- a/ci/src/deploy.ts
+++ b/ci/src/deploy.ts
@@ -63,8 +63,7 @@ export type Workspace = {
trigger_api_url: string | null;
trigger_project_id: string | null;
trigger_secret_key: string | null;
- upstash_redis_rest_token: string | null;
- upstash_redis_rest_url: string | null;
+ redis_url: string | null;
url_erp: string | null;
url_mes: string | null;
xero_client_id: string | null;
@@ -144,8 +143,6 @@ async function deploy(): Promise<void> {
trigger_project_id,
trigger_secret_key,
redis_url,
- upstash_redis_rest_token,
- upstash_redis_rest_url,
url_erp,
url_mes,
xero_client_id,
@@ -236,15 +233,8 @@ async function deploy(): Promise<void> {
continue;
}
- if (!upstash_redis_rest_token) {
- console.log(
- `🔴🍳 Missing Upstash Redis REST token for ${workspace.id}`
- );
- continue;
- }
-
- if (!upstash_redis_rest_url) {
- console.log(`🔴🍳 Missing Upstash Redis rest url for ${workspace.id}`);
+ if (!redis_url) {
+ console.log(`🔴🍳 Missing Redis URL for ${workspace.id}`);
continue;
}
@@ -307,8 +297,7 @@ async function deploy(): Promise<void> {
TRIGGER_API_URL: trigger_api_url,
TRIGGER_PROJECT_ID: trigger_project_id,
TRIGGER_SECRET_KEY: trigger_secret_key,
- UPSTASH_REDIS_REST_TOKEN: upstash_redis_rest_token,
- UPSTASH_REDIS_REST_URL: upstash_redis_rest_url,
+ REDIS_URL: redis_url,
URL_ERP: url_erp,
URL_MES: url_mes,
VERCEL_ENV: "production",
diff --git a/llm/cache/environment-configuration.md b/llm/cache/environment-configuration.md
index 0f857e0f79..b8c24969b3 100644
--- a/llm/cache/environment-configuration.md
+++ b/llm/cache/environment-configuration.md
@@ -36,7 +36,7 @@
- `POSTHOG_API_HOST` & `POSTHOG_PROJECT_PUBLIC_KEY` - Analytics
- `SLACK_BOT_TOKEN` - Slack integration
- `TRIGGER_ID`, `TRIGGER_API_KEY`, `TRIGGER_API_URL`, `TRIGGER_SECRET_KEY` - Trigger.dev job queue
-- `UPSTASH_REDIS_REST_URL` & `UPSTASH_REDIS_REST_TOKEN` - Redis KV store
+- `REDIS_URL` - Redis connection URL (ioredis)
- `ONSHAPE_SECRET_KEY` - CAD integration
- `EXCHANGE_RATES_API_KEY` - Currency exchange rates
diff --git a/llm/cache/project-overview.md b/llm/cache/project-overview.md
index a21f78afa8..8833a1ea86 100644
--- a/llm/cache/project-overview.md
+++ b/llm/cache/project-overview.md
@@ -23,6 +23,7 @@ Carbon is a manufacturing system built with modern web technologies. It consists
- **Database**: Supabase (PostgreSQL)
- **Edge Functions**: Vercel Edge Runtime
- **Authentication**: Supabase Auth via `/packages/auth/`
+- **Redis**: ioredis via `/packages/kv/` (rate limiting, caching)
### Build Tools
@@ -39,7 +40,7 @@ The monorepo uses NPM workspaces with packages located in `/packages/`:
- `database` - Database types and migrations
- `documents` - PDF/Email/ZPL document generation
- `form` - Form components and validation
-- `kv` - Key-value store (Redis)
+- `kv` - Redis client (ioredis) with rate limiting (Ratelimit class)
- `logger` - Logging utilities
- `notifications` - Notification services
- `react` - Shared React components
diff --git a/package-lock.json b/package-lock.json
index 051135e7b0..5ed5c834f3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -59,7 +59,6 @@
"@tailwindcss/forms": "^0.5.7",
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.10",
- "@upstash/ratelimit": "^2.0.5",
"@vercel/analytics": "^1.2.2",
"@vercel/react-router": "^1.2.4",
"framer-motion": "^11.1.7",
@@ -257,7 +256,6 @@
"@tanstack/react-virtual": "^3.5.0",
"@trigger.dev/react-hooks": "4.0.6",
"@trigger.dev/sdk": "4.0.6",
- "@upstash/ratelimit": "^2.0.5",
"@vercel/analytics": "^1.2.2",
"@vercel/react-router": "^1.2.4",
"@visx/responsive": "^2.1.0",
@@ -475,7 +473,6 @@
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.10",
"@trigger.dev/sdk": "4.0.6",
- "@upstash/ratelimit": "^2.0.5",
"@vercel/analytics": "^1.2.2",
"@vercel/react-router": "^1.2.4",
"cookie": "0.6.0",
@@ -643,7 +640,6 @@
"@tailwindcss/forms": "^0.5.7",
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.10",
- "@upstash/ratelimit": "^2.0.5",
"@vercel/analytics": "^1.2.2",
"@vercel/react-router": "^1.2.4",
"framer-motion": "^11.1.7",
@@ -3052,6 +3048,19 @@
"@swc/helpers": "^0.5.0"
}
},
+ "node_modules/@ioredis/as-callback": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@ioredis/as-callback/-/as-callback-3.0.0.tgz",
+ "integrity": "sha512-Kqv1rZ3WbgOrS+hgzJ5xG5WQuhvzzSTRYvNeyPMLOAM78MHSnuKI20JeJGbpuAt//LCuP0vsexZcorqW7kWhJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@ioredis/commands": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.1.tgz",
+ "integrity": "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw==",
+ "license": "MIT"
+ },
"node_modules/@isaacs/balanced-match": {
"version": "4.0.1",
"license": "MIT",
@@ -10366,6 +10375,17 @@
"@babel/types": "^7.28.2"
}
},
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
"node_modules/@types/cookie": {
"version": "0.4.1",
"license": "MIT"
@@ -10611,6 +10631,13 @@
"@types/ms": "*"
}
},
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/dompurify": {
"version": "2.4.0",
"dev": true,
@@ -10653,6 +10680,17 @@
"@types/unist": "*"
}
},
+ "node_modules/@types/ioredis-mock": {
+ "version": "8.2.7",
+ "resolved": "https://registry.npmjs.org/@types/ioredis-mock/-/ioredis-mock-8.2.7.tgz",
+ "integrity": "sha512-YsGiaOIYBKeVvu/7GYziAD8qX3LJem5LK00d5PKykzsQJMLysAqXA61AkNuYWCekYl64tbMTqVOMF4SYoCPbQg==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "ioredis": ">=5"
+ }
+ },
"node_modules/@types/istanbul-lib-coverage": {
"version": "2.0.6",
"license": "MIT"
@@ -10991,35 +11029,6 @@
"version": "1.3.0",
"license": "ISC"
},
- "node_modules/@upstash/core-analytics": {
- "version": "v0.0.10",
- "license": "MIT",
- "dependencies": {
- "@upstash/redis": "^1.28.3"
- },
- "engines": {
- "node": ">=16.0.0"
- }
- },
- "node_modules/@upstash/ratelimit": {
- "version": "v2.0.7",
- "license": "MIT",
- "dependencies": {
- "@upstash/core-analytics": "^0.0.10"
- },
- "peerDependencies": {
- "@upstash/redis": "^1.34.3"
- }
- },
- "node_modules/@upstash/redis": {
- "version": "1.34.3",
- "resolved": "https://registry.npmjs.org/@upstash/redis/-/redis-1.34.3.tgz",
- "integrity": "sha512-VT25TyODGy/8ljl7GADnJoMmtmJ1F8d84UXfGonRRF8fWYJz7+2J6GzW+a6ETGtk4OyuRTt7FRSvFG5GvrfSdQ==",
- "license": "MIT",
- "dependencies": {
- "crypto-js": "^4.2.0"
- }
- },
"node_modules/@vercel/analytics": {
"version": "1.6.1",
"license": "MPL-2.0",
@@ -11401,6 +11410,140 @@
"node": ">=12"
}
},
+ "node_modules/@vitest/expect": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.0.tgz",
+ "integrity": "sha512-EIxG7k4wlWweuCLG9Y5InKFwpMEOyrMb6ZJ1ihYu02LVj/bzUwn2VMU+13PinsjRW75XnITeFrQBMH5+dLvCDA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.0",
+ "@vitest/utils": "4.1.0",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.0.tgz",
+ "integrity": "sha512-evxREh+Hork43+Y4IOhTo+h5lGmVRyjqI739Rz4RlUPqwrkFFDF6EMvOOYjTx4E8Tl6gyCLRL8Mu7Ry12a13Tw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.0",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.0.tgz",
+ "integrity": "sha512-3RZLZlh88Ib0J7NQTRATfc/3ZPOnSUn2uDBUoGNn5T36+bALixmzphN26OUD3LRXWkJu4H0s5vvUeqBiw+kS0A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.0.tgz",
+ "integrity": "sha512-Duvx2OzQ7d6OjchL+trw+aSrb9idh7pnNfxrklo14p3zmNL4qPCDeIJAK+eBKYjkIwG96Bc6vYuxhqDXQOWpoQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.0",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner/node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.0.tgz",
+ "integrity": "sha512-0Vy9euT1kgsnj1CHttwi9i9o+4rRLEaPRSOJ5gyv579GJkNpgJK+B4HSv/rAWixx2wdAFci1X4CEPjiu2bXIMg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.0",
+ "@vitest/utils": "4.1.0",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot/node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.0.tgz",
+ "integrity": "sha512-pz77k+PgNpyMDv2FV6qmk5ZVau6c3R8HC8v342T2xlFxQKTrSeYw9waIJG8KgV9fFwAtTu4ceRzMivPTH6wSxw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.0.tgz",
+ "integrity": "sha512-XfPXT6a8TZY3dcGY8EdwsBulFCIw+BeeX0RZn2x/BtiY/75YGh8FeWGG8QISN/WhaqSrE2OrlDgtF8q5uhOTmw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.0",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils/node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@web3-storage/multipart-parser": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@web3-storage/multipart-parser/-/multipart-parser-1.0.0.tgz",
@@ -11778,6 +11921,16 @@
"version": "1.4.0",
"license": "MIT"
},
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/assign-symbols": {
"version": "1.0.0",
"license": "MIT",
@@ -12598,6 +12751,16 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/chalk": {
"version": "5.3.0",
"license": "MIT",
@@ -12866,6 +13029,15 @@
"node": ">=6"
}
},
+ "node_modules/cluster-key-slot": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
+ "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/cmd-shim": {
"version": "8.0.0",
"license": "ISC",
@@ -14125,6 +14297,15 @@
"license": "MIT",
"optional": true
},
+ "node_modules/denque": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
+ "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
"node_modules/depd": {
"version": "2.0.0",
"license": "MIT",
@@ -14835,6 +15016,16 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
"node_modules/esutils": {
"version": "2.0.3",
"license": "BSD-2-Clause",
@@ -15008,6 +15199,16 @@
"node": ">= 10.14.2"
}
},
+ "node_modules/expect-type": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",
+ "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/expect/node_modules/ansi-styles": {
"version": "4.3.0",
"license": "MIT",
@@ -15283,6 +15484,35 @@
}
}
},
+ "node_modules/fengari": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/fengari/-/fengari-0.1.5.tgz",
+ "integrity": "sha512-0DS4Nn4rV8qyFlQCpKK8brT61EUtswynrpfFTcgLErcilBIBskSMQ86fO2WVuybr14ywyKdRjv91FiRZwnEuvQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "readline-sync": "^1.4.10",
+ "sprintf-js": "^1.1.3",
+ "tmp": "^0.2.5"
+ }
+ },
+ "node_modules/fengari-interop": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/fengari-interop/-/fengari-interop-0.1.4.tgz",
+ "integrity": "sha512-4/CW/3PJUo3ebD4ACgE1g/3NGEYSq7OQAyETyypsAl/WeySDBbxExikkayNkZzbpgyC9GyJp8v1DU2VOXxNq7Q==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "fengari": "^0.1.0"
+ }
+ },
+ "node_modules/fengari/node_modules/sprintf-js": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
+ "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
"node_modules/fetch-blob": {
"version": "3.2.0",
"funding": [
@@ -16639,6 +16869,51 @@
"node": ">=14"
}
},
+ "node_modules/ioredis": {
+ "version": "5.10.1",
+ "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.10.1.tgz",
+ "integrity": "sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==",
+ "license": "MIT",
+ "dependencies": {
+ "@ioredis/commands": "1.5.1",
+ "cluster-key-slot": "^1.1.0",
+ "debug": "^4.3.4",
+ "denque": "^2.1.0",
+ "lodash.defaults": "^4.2.0",
+ "lodash.isarguments": "^3.1.0",
+ "redis-errors": "^1.2.0",
+ "redis-parser": "^3.0.0",
+ "standard-as-callback": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=12.22.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/ioredis"
+ }
+ },
+ "node_modules/ioredis-mock": {
+ "version": "8.13.1",
+ "resolved": "https://registry.npmjs.org/ioredis-mock/-/ioredis-mock-8.13.1.tgz",
+ "integrity": "sha512-Wsi50AU+cMiI32nAgfwpUaJVBtb4iQdVsOHl9M6R3tePCO/8vGsToCVIG82XWAxN4Se55TZoOzVseu+QngFLyw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@ioredis/as-callback": "^3.0.0",
+ "@ioredis/commands": "^1.4.0",
+ "fengari": "^0.1.4",
+ "fengari-interop": "^0.1.3",
+ "semver": "^7.7.2"
+ },
+ "engines": {
+ "node": ">=12.22"
+ },
+ "peerDependencies": {
+ "@types/ioredis-mock": "^8",
+ "ioredis": "^5"
+ }
+ },
"node_modules/ipaddr.js": {
"version": "1.9.1",
"license": "MIT",
@@ -19234,6 +19509,12 @@
"version": "4.0.8",
"license": "MIT"
},
+ "node_modules/lodash.defaults": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
+ "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==",
+ "license": "MIT"
+ },
"node_modules/lodash.get": {
"version": "4.4.2",
"license": "MIT"
@@ -19242,6 +19523,12 @@
"version": "4.3.0",
"license": "MIT"
},
+ "node_modules/lodash.isarguments": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz",
+ "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==",
+ "license": "MIT"
+ },
"node_modules/lodash.isboolean": {
"version": "3.0.3",
"license": "MIT"
@@ -19346,6 +19633,16 @@
"lz-string": "bin/bin.js"
}
},
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
"node_modules/make-cancellable-promise": {
"version": "1.3.2",
"license": "MIT",
@@ -21177,6 +21474,17 @@
"node": ">=0.10.0"
}
},
+ "node_modules/obug": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz",
+ "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT"
+ },
"node_modules/oidc-token-hash": {
"version": "5.2.0",
"license": "MIT",
@@ -23188,6 +23496,16 @@
"url": "https://paulmillr.com/funding/"
}
},
+ "node_modules/readline-sync": {
+ "version": "1.4.10",
+ "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz",
+ "integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
"node_modules/recharts": {
"version": "2.15.4",
"license": "MIT",
@@ -23224,6 +23542,27 @@
"version": "18.3.1",
"license": "MIT"
},
+ "node_modules/redis-errors": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz",
+ "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/redis-parser": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz",
+ "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==",
+ "license": "MIT",
+ "dependencies": {
+ "redis-errors": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/reduce-css-calc": {
"version": "1.3.0",
"license": "MIT",
@@ -24443,6 +24782,13 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/signal-exit": {
"version": "3.0.7",
"license": "ISC"
@@ -25017,6 +25363,19 @@
"node": ">=8"
}
},
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/standard-as-callback": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz",
+ "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==",
+ "license": "MIT"
+ },
"node_modules/starter": {
"resolved": "apps/starter",
"link": true
@@ -25818,6 +26177,13 @@
"version": "1.3.3",
"license": "MIT"
},
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/tinyexec": {
"version": "0.3.2",
"license": "MIT"
@@ -25836,6 +26202,16 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
+ "node_modules/tinyrainbow": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",
+ "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
"node_modules/tippy.js": {
"version": "6.3.7",
"license": "MIT",
@@ -28174,6 +28550,119 @@
"fsevents": "~2.3.2"
}
},
+ "node_modules/vitest": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.0.tgz",
+ "integrity": "sha512-YbDrMF9jM2Lqc++2530UourxZHmkKLxrs4+mYhEwqWS97WJ7wOYEkcr+QfRgJ3PW9wz3odRijLZjHEaRLTNbqw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.0",
+ "@vitest/mocker": "4.1.0",
+ "@vitest/pretty-format": "4.1.0",
+ "@vitest/runner": "4.1.0",
+ "@vitest/snapshot": "4.1.0",
+ "@vitest/spy": "4.1.0",
+ "@vitest/utils": "4.1.0",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.0.3",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.0",
+ "@vitest/browser-preview": "4.1.0",
+ "@vitest/browser-webdriverio": "4.1.0",
+ "@vitest/ui": "4.1.0",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/vitest/node_modules/es-module-lexer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz",
+ "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vitest/node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vitest/node_modules/std-env": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.0.0.tgz",
+ "integrity": "sha512-zUMPtQ/HBY3/50VbpkupYHbRroTRZJPRLvreamgErJVys0ceuzMkD44J/QjqhHjOzK42GQ3QZIeFG1OYfOtKqQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vitest/node_modules/tinyexec": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz",
+ "integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/w3c-hr-time": {
"version": "1.0.2",
"license": "MIT",
@@ -28383,6 +28872,23 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/wide-align": {
"version": "1.1.5",
"license": "ISC",
@@ -29321,17 +29827,19 @@
"name": "@carbon/kv",
"version": "*",
"dependencies": {
- "@upstash/redis": "1.34.3"
+ "ioredis": "^5.10.1"
},
"devDependencies": {
"@carbon/logger": "*",
"@carbon/tsconfig": "*",
"@types/node": "^20.12.5",
"dotenv": "16.3.1",
+ "ioredis-mock": "^8.13.1",
"rimraf": "^5.0.5",
"tsup": "^6.5.0",
"tsx": "^4.13.2",
- "typescript": "^5.2.2"
+ "typescript": "^5.2.2",
+ "vitest": "^4.1.0"
}
},
"packages/lib": {
diff --git a/packages/auth/src/config/env.ts b/packages/auth/src/config/env.ts
index 58fe0eaf1d..a5ec99305d 100644
--- a/packages/auth/src/config/env.ts
+++ b/packages/auth/src/config/env.ts
@@ -70,8 +70,7 @@ declare global {
SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID: string;
SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID: string;
SUPABASE_SERVICE_ROLE_KEY: string;
- UPSTASH_REDIS_REST_URL: string;
- UPSTASH_REDIS_REST_TOKEN: string;
+ REDIS_URL: string;
VERCEL_URL: string;
VERCEL_ENV: string;
XERO_CLIENT_SECRET: string;
@@ -273,10 +272,7 @@ export const STRIPE_BYPASS_COMPANY_IDS = getEnv("STRIPE_BYPASS_COMPANY_IDS", {
export const STRIPE_BYPASS_USER_IDS = getEnv("STRIPE_BYPASS_USER_IDS", {
isRequired: false
});
-export const UPSTASH_REDIS_REST_URL = getEnv("UPSTASH_REDIS_REST_URL", {
- isRequired: false
-});
-export const UPSTASH_REDIS_REST_TOKEN = getEnv("UPSTASH_REDIS_REST_TOKEN", {
+export const REDIS_URL = getEnv("REDIS_URL", {
isRequired: false
});
export const SESSION_MAX_AGE = 60 * 60 * 24 * 7; // 7 days;
diff --git a/packages/auth/src/services/verification.server.ts b/packages/auth/src/services/verification.server.ts
index b5ab25492c..6cd50c99e2 100644
--- a/packages/auth/src/services/verification.server.ts
+++ b/packages/auth/src/services/verification.server.ts
@@ -12,9 +12,12 @@ export async function sendVerificationCode(email: string) {
).toString();
// Store in Redis with 10-minute expiration
- await redis.set(`verification:${email.toLowerCase()}`, verificationCode, {
- ex: 600
- });
+ await redis.set(
+ `verification:${email.toLowerCase()}`,
+ verificationCode,
+ "EX",
+ 600
+ );
// Send email with verification code using React template
const html = await render(
diff --git a/packages/kv/README.md b/packages/kv/README.md
new file mode 100644
index 0000000000..3f6ef35eab
--- /dev/null
+++ b/packages/kv/README.md
@@ -0,0 +1,174 @@
+# @carbon/kv
+
+Redis client and rate limiting utilities for Carbon applications using ioredis.
+
+## Installation
+
+This package is part of the Carbon monorepo and is available as `@carbon/kv`.
+
+## Environment Variables
+
+```bash
+REDIS_URL="redis://user:password@host:port"
+```
+
+## Usage
+
+### Redis Client
+
+```typescript
+import { redis } from "@carbon/kv";
+
+// Basic operations
+await redis.set("key", "value");
+await redis.set("key", "value", "EX", 300); // With 5 min expiration
+const value = await redis.get("key");
+await redis.del("key");
+```
+
+### Rate Limiting
+
+The `Ratelimit` class provides a drop-in replacement for `@upstash/ratelimit` using ioredis.
+
+```typescript
+import { Ratelimit, redis } from "@carbon/kv";
+
+const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"), // 10 requests per hour
+ analytics: true, // Compatibility option (no-op)
+});
+
+// Check rate limit
+const { success, limit, remaining, reset } = await ratelimit.limit(identifier);
+
+if (!success) {
+ // Rate limited - return 429
+}
+```
+
+## Algorithms
+
+### Sliding Window
+
+Combines two fixed windows with weighted scoring for smooth rate limiting. Prevents boundary burst issues.
+
+```typescript
+Ratelimit.slidingWindow(tokens, window);
+
+// Examples
+Ratelimit.slidingWindow(10, "1 h"); // 10 requests per hour
+Ratelimit.slidingWindow(100, "1 m"); // 100 requests per minute
+Ratelimit.slidingWindow(5, "10 s"); // 5 requests per 10 seconds
+```
+
+### Fixed Window
+
+Simple counter that resets at fixed intervals. Low memory usage but can allow bursts at boundaries.
+
+```typescript
+Ratelimit.fixedWindow(tokens, window);
+
+// Examples
+Ratelimit.fixedWindow(100, "1 m"); // 100 requests per minute
+Ratelimit.fixedWindow(1000, "1 h"); // 1000 requests per hour
+```
+
+### Token Bucket
+
+Refillable bucket that allows controlled bursts while maintaining average rate.
+
+```typescript
+Ratelimit.tokenBucket(refillRate, interval, maxTokens?);
+
+// Examples
+Ratelimit.tokenBucket(1, "1 s", 10); // 1 token/sec, burst up to 10
+Ratelimit.tokenBucket(10, "1 m", 50); // 10 tokens/min, burst up to 50
+```
+
+## Configuration Options
+
+```typescript
+interface RatelimitConfig {
+ redis: Redis; // ioredis client instance
+ limiter: () => Algorithm; // Algorithm factory
+ prefix?: string; // Key prefix (default: "@upstash/ratelimit")
+ ephemeralCache?: boolean | Map<string, number>; // In-memory cache for blocked IDs
+ timeout?: number; // Redis timeout in ms (default: 5000)
+ analytics?: boolean; // Compatibility option (no-op)
+}
+```
+
+## Response Object
+
+```typescript
+interface RatelimitResponse {
+ success: boolean; // Whether request is allowed
+ limit: number; // Maximum requests in window
+ remaining: number; // Remaining requests in window
+ reset: number; // Unix timestamp (ms) when limit resets
+ pending: Promise<unknown>; // Resolves when operations complete
+}
+```
+
+## Additional Methods
+
+```typescript
+// Get remaining without consuming
+const { remaining, reset, limit } = await ratelimit.getRemaining(identifier);
+
+// Reset rate limit for identifier
+await ratelimit.resetUsedTokens(identifier);
+
+// Block until allowed or timeout
+const result = await ratelimit.blockUntilReady(identifier, timeoutMs);
+```
+
+## Duration Format
+
+Durations can be specified with or without spaces:
+
+- `ms` - milliseconds: `"100ms"`, `"100 ms"`
+- `s` - seconds: `"10s"`, `"10 s"`
+- `m` - minutes: `"5m"`, `"5 m"`
+- `h` - hours: `"1h"`, `"1 h"`
+- `d` - days: `"7d"`, `"7 d"`
+
+## Migration from @upstash/ratelimit
+
+1. Update imports:
+```typescript
+// Before
+import { Ratelimit } from "@upstash/ratelimit";
+import { redis } from "@carbon/kv";
+
+// After
+import { Ratelimit, redis } from "@carbon/kv";
+```
+
+2. Update environment variables:
+```bash
+# Before
+UPSTASH_REDIS_REST_URL="https://..."
+UPSTASH_REDIS_REST_TOKEN="..."
+
+# After
+REDIS_URL="redis://..."
+```
+
+3. Update `redis.set()` calls with expiration:
+```typescript
+// Before (Upstash syntax)
+await redis.set(key, value, { ex: 300 });
+
+// After (ioredis syntax)
+await redis.set(key, value, "EX", 300);
+```
+
+## Testing
+
+```bash
+npm test # Run tests
+npm run test:watch # Watch mode
+npm run test:coverage # With coverage
+```
diff --git a/packages/kv/package.json b/packages/kv/package.json
index d4befeb668..be5360fa43 100644
--- a/packages/kv/package.json
+++ b/packages/kv/package.json
@@ -1,17 +1,19 @@
{
"name": "@carbon/kv",
"dependencies": {
- "@upstash/redis": "1.34.3"
+ "ioredis": "^5.10.1"
},
"devDependencies": {
"@carbon/logger": "*",
"@carbon/tsconfig": "*",
"@types/node": "^20.12.5",
"dotenv": "16.3.1",
+ "ioredis-mock": "^8.13.1",
"rimraf": "^5.0.5",
"tsup": "^6.5.0",
"tsx": "^4.13.2",
- "typescript": "^5.2.2"
+ "typescript": "^5.2.2",
+ "vitest": "^4.1.0"
},
"exports": {
".": "./src/index.ts"
@@ -20,7 +22,10 @@
"scripts": {
"clean": "rimraf .turbo node_modules dist",
"dev": "tsup --watch",
- "lint": "biome lint --write "
+ "lint": "biome lint --write ",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "test:coverage": "vitest run --coverage"
},
"sideEffects": false,
"version": "*"
diff --git a/packages/kv/src/client.ts b/packages/kv/src/client.ts
index 34b75fe71e..73cc1ddabf 100644
--- a/packages/kv/src/client.ts
+++ b/packages/kv/src/client.ts
@@ -1,34 +1,37 @@
-import { UPSTASH_REDIS_REST_TOKEN, UPSTASH_REDIS_REST_URL } from "@carbon/auth";
-import type { Redis as RedisType } from "@upstash/redis";
-import { Redis } from "@upstash/redis";
+import { REDIS_URL } from "@carbon/auth";
+import Redis from "ioredis";
-let redis: RedisType;
+let redis: Redis;
declare global {
- var __redis: RedisType | undefined;
+ var __redis: Redis | undefined;
}
-if (!UPSTASH_REDIS_REST_URL) {
- throw new Error("UPSTASH_REDIS_REST_URL is not defined");
-}
-
-if (!UPSTASH_REDIS_REST_TOKEN) {
- throw new Error("UPSTASH_REDIS_REST_TOKEN is not defined");
+if (!REDIS_URL) {
+ throw new Error("REDIS_URL is not defined");
}
// this is needed because in development we don't want to restart
// the server with every change, but we want to make sure we don't
-// create a new connection to the Redis with every change either.
+// create a new connection to Redis with every change either.
if (process.env.VERCEL_ENV === "production") {
- redis = new Redis({
- url: UPSTASH_REDIS_REST_URL,
- token: UPSTASH_REDIS_REST_TOKEN
+ redis = new Redis(REDIS_URL, {
+ maxRetriesPerRequest: 3,
+ enableReadyCheck: true,
+ retryStrategy(times) {
+ const delay = Math.min(times * 50, 2000);
+ return delay;
+ }
});
} else {
if (!global.__redis) {
- global.__redis = new Redis({
- url: UPSTASH_REDIS_REST_URL,
- token: UPSTASH_REDIS_REST_TOKEN
+ global.__redis = new Redis(REDIS_URL, {
+ maxRetriesPerRequest: 3,
+ enableReadyCheck: true,
+ retryStrategy(times) {
+ const delay = Math.min(times * 50, 2000);
+ return delay;
+ }
});
}
redis = global.__redis;
diff --git a/packages/kv/src/index.ts b/packages/kv/src/index.ts
index d1284a4e30..ec946ed163 100644
--- a/packages/kv/src/index.ts
+++ b/packages/kv/src/index.ts
@@ -1,3 +1,9 @@
import redis from "./client";
export { redis };
+export type {
+ Duration,
+ RatelimitConfig,
+ RatelimitResponse
+} from "./ratelimit";
+export { Ratelimit } from "./ratelimit";
diff --git a/packages/kv/src/ratelimit/cache.test.ts b/packages/kv/src/ratelimit/cache.test.ts
new file mode 100644
index 0000000000..0397376c5b
--- /dev/null
+++ b/packages/kv/src/ratelimit/cache.test.ts
@@ -0,0 +1,146 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Cache } from "./cache";
+
+describe("Cache", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ describe("constructor", () => {
+ it("should create cache with empty map by default", () => {
+ const cache = new Cache();
+ expect(cache.get("key")).toBeUndefined();
+ });
+
+ it("should create cache with provided map", () => {
+ const existingMap = new Map<string, number>();
+ existingMap.set("existing", 123);
+ const cache = new Cache(existingMap);
+ expect(cache.get("existing")).toBe(123);
+ });
+ });
+
+ describe("isBlocked()", () => {
+ it("should return not blocked for unknown key", () => {
+ const cache = new Cache();
+ const result = cache.isBlocked("unknown");
+ expect(result.blocked).toBe(false);
+ expect(result.reset).toBe(0);
+ });
+
+ it("should return blocked when reset time is in the future", () => {
+ const cache = new Cache();
+ const futureTime = Date.now() + 10000; // 10 seconds in future
+ cache.blockUntil("user:123", futureTime);
+
+ const result = cache.isBlocked("user:123");
+ expect(result.blocked).toBe(true);
+ expect(result.reset).toBe(futureTime);
+ });
+
+ it("should return not blocked when reset time has passed", () => {
+ const cache = new Cache();
+ const pastTime = Date.now() + 5000;
+ cache.blockUntil("user:123", pastTime);
+
+ // Advance time past the reset
+ vi.advanceTimersByTime(6000);
+
+ const result = cache.isBlocked("user:123");
+ expect(result.blocked).toBe(false);
+ expect(result.reset).toBe(0);
+ });
+
+ it("should clean up expired entries on check", () => {
+ const cache = new Cache();
+ const resetTime = Date.now() + 5000;
+ cache.blockUntil("user:123", resetTime);
+
+ // Advance time past the reset
+ vi.advanceTimersByTime(6000);
+
+ // First check should clean up
+ cache.isBlocked("user:123");
+
+ // Key should now be gone
+ expect(cache.get("user:123")).toBeUndefined();
+ });
+ });
+
+ describe("blockUntil()", () => {
+ it("should block a key until specified time", () => {
+ const cache = new Cache();
+ const resetTime = Date.now() + 10000;
+ cache.blockUntil("user:123", resetTime);
+
+ expect(cache.get("user:123")).toBe(resetTime);
+ });
+
+ it("should overwrite existing block time", () => {
+ const cache = new Cache();
+ const firstReset = Date.now() + 5000;
+ const secondReset = Date.now() + 10000;
+
+ cache.blockUntil("user:123", firstReset);
+ cache.blockUntil("user:123", secondReset);
+
+ expect(cache.get("user:123")).toBe(secondReset);
+ });
+ });
+
+ describe("set() and get()", () => {
+ it("should set and get values", () => {
+ const cache = new Cache();
+ cache.set("key1", 100);
+ cache.set("key2", 200);
+
+ expect(cache.get("key1")).toBe(100);
+ expect(cache.get("key2")).toBe(200);
+ });
+
+ it("should return undefined for non-existent keys", () => {
+ const cache = new Cache();
+ expect(cache.get("nonexistent")).toBeUndefined();
+ });
+
+ it("should overwrite existing values", () => {
+ const cache = new Cache();
+ cache.set("key", 100);
+ cache.set("key", 200);
+ expect(cache.get("key")).toBe(200);
+ });
+ });
+
+ describe("incr()", () => {
+ it("should increment from 0 for new keys", () => {
+ const cache = new Cache();
+ const result = cache.incr("counter");
+ expect(result).toBe(1);
+ expect(cache.get("counter")).toBe(1);
+ });
+
+ it("should increment existing values", () => {
+ const cache = new Cache();
+ cache.set("counter", 5);
+
+ expect(cache.incr("counter")).toBe(6);
+ expect(cache.incr("counter")).toBe(7);
+ expect(cache.incr("counter")).toBe(8);
+ });
+
+ it("should handle multiple counters independently", () => {
+ const cache = new Cache();
+
+ cache.incr("counter1");
+ cache.incr("counter1");
+ cache.incr("counter2");
+
+ expect(cache.get("counter1")).toBe(2);
+ expect(cache.get("counter2")).toBe(1);
+ });
+ });
+});
diff --git a/packages/kv/src/ratelimit/cache.ts b/packages/kv/src/ratelimit/cache.ts
new file mode 100644
index 0000000000..53f7d05fdc
--- /dev/null
+++ b/packages/kv/src/ratelimit/cache.ts
@@ -0,0 +1,61 @@
+import type { EphemeralCache } from "./types";
+
+/**
+ * In-memory cache for blocking identifiers that have exceeded their rate limit.
+ * This prevents unnecessary Redis calls for already-blocked identifiers.
+ */
+export class Cache implements EphemeralCache {
+ private readonly cache: Map<string, number>;
+
+ constructor(cache?: Map<string, number>) {
+ this.cache = cache ?? new Map();
+ }
+
+ /**
+ * Check if an identifier is blocked
+ */
+ isBlocked(key: string): { blocked: boolean; reset: number } {
+ const reset = this.cache.get(key);
+ if (!reset) {
+ return { blocked: false, reset: 0 };
+ }
+
+ if (Date.now() >= reset) {
+ this.cache.delete(key);
+ return { blocked: false, reset: 0 };
+ }
+
+ return { blocked: true, reset };
+ }
+
+ /**
+ * Block an identifier until a specific timestamp
+ */
+ blockUntil(key: string, reset: number): void {
+ this.cache.set(key, reset);
+ }
+
+ /**
+ * Set a value in the cache
+ */
+ set(key: string, value: number): void {
+ this.cache.set(key, value);
+ }
+
+ /**
+ * Get a value from the cache
+ */
+ get(key: string): number | undefined {
+ return this.cache.get(key);
+ }
+
+ /**
+ * Increment a value in the cache
+ */
+ incr(key: string): number {
+ const current = this.cache.get(key) ?? 0;
+ const next = current + 1;
+ this.cache.set(key, next);
+ return next;
+ }
+}
diff --git a/packages/kv/src/ratelimit/duration.test.ts b/packages/kv/src/ratelimit/duration.test.ts
new file mode 100644
index 0000000000..2be7932fcf
--- /dev/null
+++ b/packages/kv/src/ratelimit/duration.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+import { ms } from "./duration";
+
+describe("duration parser", () => {
+ describe("ms()", () => {
+ it("should parse milliseconds", () => {
+ expect(ms("100ms")).toBe(100);
+ expect(ms("1ms")).toBe(1);
+ expect(ms("1000ms")).toBe(1000);
+ });
+
+ it("should parse milliseconds with space", () => {
+ expect(ms("100 ms")).toBe(100);
+ expect(ms("1 ms")).toBe(1);
+ });
+
+ it("should parse seconds", () => {
+ expect(ms("1s")).toBe(1000);
+ expect(ms("10s")).toBe(10000);
+ expect(ms("60s")).toBe(60000);
+ });
+
+ it("should parse seconds with space", () => {
+ expect(ms("1 s")).toBe(1000);
+ expect(ms("10 s")).toBe(10000);
+ });
+
+ it("should parse minutes", () => {
+ expect(ms("1m")).toBe(60000);
+ expect(ms("5m")).toBe(300000);
+ expect(ms("60m")).toBe(3600000);
+ });
+
+ it("should parse minutes with space", () => {
+ expect(ms("1 m")).toBe(60000);
+ expect(ms("5 m")).toBe(300000);
+ });
+
+ it("should parse hours", () => {
+ expect(ms("1h")).toBe(3600000);
+ expect(ms("24h")).toBe(86400000);
+ });
+
+ it("should parse hours with space", () => {
+ expect(ms("1 h")).toBe(3600000);
+ expect(ms("24 h")).toBe(86400000);
+ });
+
+ it("should parse days", () => {
+ expect(ms("1d")).toBe(86400000);
+ expect(ms("7d")).toBe(604800000);
+ });
+
+ it("should parse days with space", () => {
+ expect(ms("1 d")).toBe(86400000);
+ expect(ms("7 d")).toBe(604800000);
+ });
+
+ it("should throw on invalid format", () => {
+ expect(() => ms("invalid" as any)).toThrow("Unable to parse window size");
+ expect(() => ms("10" as any)).toThrow("Unable to parse window size");
+ expect(() => ms("10x" as any)).toThrow("Unable to parse window size");
+ expect(() => ms("" as any)).toThrow("Unable to parse window size");
+ });
+
+ it("should handle edge cases", () => {
+ expect(ms("0s")).toBe(0);
+ expect(ms("0 s")).toBe(0);
+ expect(ms("0m")).toBe(0);
+ });
+ });
+});
diff --git a/packages/kv/src/ratelimit/duration.ts b/packages/kv/src/ratelimit/duration.ts
new file mode 100644
index 0000000000..28bf4bcc1d
--- /dev/null
+++ b/packages/kv/src/ratelimit/duration.ts
@@ -0,0 +1,35 @@
+import type { Duration } from "./types";
+
+/**
+ * Convert a human-readable duration string to milliseconds
+ * Matches @upstash/ratelimit duration parsing
+ *
+ * @example
+ * ms("10 s") // 10000
+ * ms("1m") // 60000
+ * ms("1 h") // 3600000
+ */
+export function ms(d: Duration): number {
+ const match = d.match(/^(\d+)\s?(ms|s|m|h|d)$/);
+ if (!match) {
+ throw new Error(`Unable to parse window size: ${d}`);
+ }
+
+ const time = Number.parseInt(match[1]);
+ const unit = match[2] as "ms" | "s" | "m" | "h" | "d";
+
+ switch (unit) {
+ case "ms":
+ return time;
+ case "s":
+ return time * 1000;
+ case "m":
+ return time * 1000 * 60;
+ case "h":
+ return time * 1000 * 60 * 60;
+ case "d":
+ return time * 1000 * 60 * 60 * 24;
+ default:
+ throw new Error(`Unable to parse window size: ${d}`);
+ }
+}
diff --git a/packages/kv/src/ratelimit/index.ts b/packages/kv/src/ratelimit/index.ts
new file mode 100644
index 0000000000..62710df689
--- /dev/null
+++ b/packages/kv/src/ratelimit/index.ts
@@ -0,0 +1,10 @@
+export { Ratelimit } from "./ratelimit";
+export type {
+ Algorithm,
+ Duration,
+ EphemeralCache,
+ LimitOptions,
+ RatelimitConfig,
+ RatelimitContext,
+ RatelimitResponse
+} from "./types";
diff --git a/packages/kv/src/ratelimit/ratelimit.test.ts b/packages/kv/src/ratelimit/ratelimit.test.ts
new file mode 100644
index 0000000000..daf449a062
--- /dev/null
+++ b/packages/kv/src/ratelimit/ratelimit.test.ts
@@ -0,0 +1,538 @@
+import type { Redis } from "ioredis";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Ratelimit } from "./ratelimit";
+
+// Create a mock Redis client
+const createMockRedis = () => {
+ const storage = new Map<string, any>();
+ const hashStorage = new Map<string, Map<string, any>>();
+
+ return {
+ eval: vi.fn(),
+ del: vi.fn().mockImplementation((...keys: string[]) => {
+ keys.forEach((key) => {
+ storage.delete(key);
+ hashStorage.delete(key);
+ });
+ return Promise.resolve(keys.length);
+ }),
+ get: vi.fn().mockImplementation((key: string) => {
+ return Promise.resolve(storage.get(key) ?? null);
+ }),
+ set: vi.fn().mockImplementation((key: string, value: any) => {
+ storage.set(key, value);
+ return Promise.resolve("OK");
+ }),
+ // Helper to access internal storage for testing
+ _storage: storage,
+ _hashStorage: hashStorage
+ } as unknown as Redis & {
+ _storage: Map<string, any>;
+ _hashStorage: Map<string, Map<string, any>>;
+ };
+};
+
+describe("Ratelimit", () => {
+ let mockRedis: ReturnType<typeof createMockRedis>;
+
+ beforeEach(() => {
+ mockRedis = createMockRedis();
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2024-01-01T00:00:00.000Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ describe("constructor", () => {
+ it("should create a ratelimiter with default options", () => {
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h")
+ });
+
+ expect(ratelimit).toBeInstanceOf(Ratelimit);
+ });
+
+ it("should create a ratelimiter with custom prefix", () => {
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"),
+ prefix: "custom-prefix"
+ });
+
+ expect(ratelimit).toBeInstanceOf(Ratelimit);
+ });
+
+ it("should create a ratelimiter with ephemeral cache enabled", () => {
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"),
+ ephemeralCache: true
+ });
+
+ expect(ratelimit).toBeInstanceOf(Ratelimit);
+ });
+
+ it("should create a ratelimiter with custom cache map", () => {
+ const customCache = new Map<string, number>();
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"),
+ ephemeralCache: customCache
+ });
+
+ expect(ratelimit).toBeInstanceOf(Ratelimit);
+ });
+ });
+
+ describe("fixedWindow algorithm", () => {
+ it("should allow requests within limit", async () => {
+ // Mock Redis eval to return [1, 10] (1 request used, limit of 10)
+ mockRedis.eval = vi.fn().mockResolvedValue([1, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.fixedWindow(10, "1 m")
+ });
+
+ const result = await ratelimit.limit("user:123");
+
+ expect(result.success).toBe(true);
+ expect(result.limit).toBe(10);
+ expect(result.remaining).toBe(9);
+ expect(result.reset).toBeGreaterThan(Date.now());
+ });
+
+ it("should block requests when limit exceeded", async () => {
+ // Mock Redis eval to return [11, 10] (11 requests used, limit of 10)
+ mockRedis.eval = vi.fn().mockResolvedValue([11, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.fixedWindow(10, "1 m")
+ });
+
+ const result = await ratelimit.limit("user:123");
+
+ expect(result.success).toBe(false);
+ expect(result.limit).toBe(10);
+ expect(result.remaining).toBe(0);
+ });
+
+ it("should call Redis eval with correct parameters", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([1, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.fixedWindow(10, "1 m"),
+ prefix: "test"
+ });
+
+ await ratelimit.limit("user:123");
+
+ expect(mockRedis.eval).toHaveBeenCalledWith(
+ expect.any(String), // Lua script
+ 1, // Number of keys
+ "test:user:123", // Key
+ 10, // Limit
+ 60000, // Window in ms
+ 1 // Increment by
+ );
+ });
+ });
+
+ describe("slidingWindow algorithm", () => {
+ it("should allow requests within limit", async () => {
+ // Mock Redis eval to return [9, 10] (9 remaining, limit of 10)
+ mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h")
+ });
+
+ const result = await ratelimit.limit("user:123");
+
+ expect(result.success).toBe(true);
+ expect(result.limit).toBe(10);
+ expect(result.remaining).toBe(9);
+ });
+
+ it("should block requests when limit exceeded", async () => {
+ // Mock Redis eval to return [-1, 10] (blocked, limit of 10)
+ mockRedis.eval = vi.fn().mockResolvedValue([-1, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h")
+ });
+
+ const result = await ratelimit.limit("user:123");
+
+ expect(result.success).toBe(false);
+ expect(result.limit).toBe(10);
+ expect(result.remaining).toBe(0);
+ });
+
+ it("should call Redis eval with two keys (current and previous window)", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"),
+ prefix: "test"
+ });
+
+ await ratelimit.limit("user:123");
+
+ expect(mockRedis.eval).toHaveBeenCalledWith(
+ expect.any(String), // Lua script
+ 2, // Number of keys (current + previous window)
+ expect.stringMatching(/^test:user:123:\d+$/), // Current window key
+ expect.stringMatching(/^test:user:123:\d+$/), // Previous window key
+ 10, // Limit
+ expect.any(Number), // Current timestamp
+ 3600000, // Window in ms (1 hour)
+ 1 // Increment by
+ );
+ });
+ });
+
+ describe("tokenBucket algorithm", () => {
+ it("should allow requests when tokens available", async () => {
+ // Mock Redis eval to return [9, next_refill_time, 10]
+ const nextRefill = Date.now() + 1000;
+ mockRedis.eval = vi.fn().mockResolvedValue([9, nextRefill, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.tokenBucket(1, "1 s", 10)
+ });
+
+ const result = await ratelimit.limit("user:123");
+
+ expect(result.success).toBe(true);
+ expect(result.limit).toBe(10);
+ expect(result.remaining).toBe(9);
+ expect(result.reset).toBe(nextRefill);
+ });
+
+ it("should block requests when bucket is empty", async () => {
+ const nextRefill = Date.now() + 1000;
+ mockRedis.eval = vi.fn().mockResolvedValue([-1, nextRefill, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.tokenBucket(1, "1 s", 10)
+ });
+
+ const result = await ratelimit.limit("user:123");
+
+ expect(result.success).toBe(false);
+ expect(result.limit).toBe(10);
+ expect(result.remaining).toBe(0);
+ expect(result.reset).toBe(nextRefill);
+ });
+
+ it("should use refillRate as maxTokens when not specified", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([4, Date.now() + 1000, 5]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.tokenBucket(5, "10 s"), // No maxTokens specified
+ prefix: "test"
+ });
+
+ await ratelimit.limit("user:123");
+
+ // Check that maxTokens (5) was passed to the script
+ expect(mockRedis.eval).toHaveBeenCalledWith(
+ expect.any(String),
+ 1,
+ "test:user:123",
+ 5, // maxTokens defaults to refillRate
+ 10000, // 10 seconds in ms
+ 5, // refillRate
+ expect.any(Number),
+ 1
+ );
+ });
+ });
+
+ describe("ephemeral cache", () => {
+ it("should use cache to block subsequent requests", async () => {
+ // First call: blocked (returns [-1, 10] meaning blocked with limit 10)
+ mockRedis.eval = vi.fn().mockResolvedValue([-1, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"),
+ ephemeralCache: true
+ });
+
+ // First request - blocked by Redis
+ const firstResult = await ratelimit.limit("user:123");
+ expect(firstResult.success).toBe(false);
+
+ // Clear the mock call history but keep returning blocked result
+ vi.clearAllMocks();
+
+ // Second request - should be blocked by cache, not Redis
+ // The cache blocks based on the key prefix + identifier
+ const result = await ratelimit.limit("user:123");
+
+ expect(result.success).toBe(false);
+ // Cache uses the full key including prefix
+ expect(mockRedis.eval).not.toHaveBeenCalled(); // Cache should prevent Redis call
+ });
+
+ it("should allow requests after cache expires", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([-1, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"),
+ ephemeralCache: true
+ });
+
+ // First request - blocked
+ await ratelimit.limit("user:123");
+
+ // Advance time past the window
+ vi.advanceTimersByTime(3600001);
+
+ // Mock successful response for next call
+ mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);
+
+ // Second request - should go to Redis again
+ const result = await ratelimit.limit("user:123");
+
+ expect(mockRedis.eval).toHaveBeenCalled();
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe("timeout handling", () => {
+ it("should return success on timeout", async () => {
+ // Create a promise that never resolves
+ mockRedis.eval = vi.fn().mockImplementation(() => new Promise(() => {}));
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"),
+ timeout: 1000
+ });
+
+ const resultPromise = ratelimit.limit("user:123");
+
+ // Advance time past timeout
+ vi.advanceTimersByTime(1001);
+
+ const result = await resultPromise;
+
+ expect(result.success).toBe(true);
+ expect(result.limit).toBe(0);
+ expect(result.remaining).toBe(0);
+ expect(result.reset).toBe(0);
+ });
+ });
+
+ describe("getRemaining()", () => {
+ it("should return remaining tokens for fixedWindow", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([7, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.fixedWindow(10, "1 m")
+ });
+
+ const result = await ratelimit.getRemaining("user:123");
+
+ expect(result.remaining).toBe(7);
+ expect(result.limit).toBe(10);
+ expect(result.reset).toBeGreaterThan(Date.now());
+ });
+
+ it("should return remaining tokens for slidingWindow", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([5, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h")
+ });
+
+ const result = await ratelimit.getRemaining("user:123");
+
+ expect(result.remaining).toBe(5);
+ expect(result.limit).toBe(10);
+ });
+
+ it("should return remaining tokens for tokenBucket", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([8, Date.now() + 1000, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.tokenBucket(1, "1 s", 10)
+ });
+
+ const result = await ratelimit.getRemaining("user:123");
+
+ expect(result.remaining).toBe(8);
+ expect(result.limit).toBe(10);
+ });
+ });
+
+ describe("resetUsedTokens()", () => {
+ it("should delete the key for fixedWindow", async () => {
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.fixedWindow(10, "1 m"),
+ prefix: "test"
+ });
+
+ await ratelimit.resetUsedTokens("user:123");
+
+ expect(mockRedis.del).toHaveBeenCalledWith("test:user:123");
+ });
+
+ it("should delete both window keys for slidingWindow", async () => {
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"),
+ prefix: "test"
+ });
+
+ await ratelimit.resetUsedTokens("user:123");
+
+ expect(mockRedis.del).toHaveBeenCalledWith(
+ expect.stringMatching(/^test:user:123:\d+$/),
+ expect.stringMatching(/^test:user:123:\d+$/)
+ );
+ });
+
+ it("should delete the key for tokenBucket", async () => {
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.tokenBucket(1, "1 s", 10),
+ prefix: "test"
+ });
+
+ await ratelimit.resetUsedTokens("user:123");
+
+ expect(mockRedis.del).toHaveBeenCalledWith("test:user:123");
+ });
+ });
+
+ describe("blockUntilReady()", () => {
+ it("should return immediately if not rate limited", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h")
+ });
+
+ const result = await ratelimit.blockUntilReady("user:123", 5000);
+
+ expect(result.success).toBe(true);
+ });
+
+ it("should throw error for non-positive timeout", async () => {
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h")
+ });
+
+ await expect(ratelimit.blockUntilReady("user:123", 0)).rejects.toThrow(
+ "timeout must be positive"
+ );
+
+ await expect(ratelimit.blockUntilReady("user:123", -1)).rejects.toThrow(
+ "timeout must be positive"
+ );
+ });
+
+ it("should wait and retry when rate limited", async () => {
+ // Use real timers for this test since fake timers + async is tricky
+ vi.useRealTimers();
+
+ // First call: blocked, second call: allowed
+ mockRedis.eval = vi
+ .fn()
+ .mockResolvedValueOnce([-1, 10]) // First: blocked
+ .mockResolvedValueOnce([9, 10]); // Second: allowed
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "100 ms") // Short window for fast test
+ });
+
+ const result = await ratelimit.blockUntilReady("user:123", 500);
+
+ expect(result.success).toBe(true);
+ expect(mockRedis.eval).toHaveBeenCalledTimes(2);
+
+ // Restore fake timers for other tests
+ vi.useFakeTimers();
+ });
+ });
+
+ describe("analytics option (compatibility)", () => {
+ it("should accept analytics option without error", () => {
+ // analytics is a no-op for compatibility
+ expect(() => {
+ new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.slidingWindow(10, "1 h"),
+ analytics: true
+ });
+ }).not.toThrow();
+ });
+ });
+
+ describe("prefix handling", () => {
+ it("should use default prefix when not specified", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.fixedWindow(10, "1 m")
+ });
+
+ await ratelimit.limit("user:123");
+
+ expect(mockRedis.eval).toHaveBeenCalledWith(
+ expect.any(String),
+ 1,
+ "@upstash/ratelimit:user:123", // Default prefix
+ expect.anything(),
+ expect.anything(),
+ expect.anything()
+ );
+ });
+
+ it("should use custom prefix when specified", async () => {
+ mockRedis.eval = vi.fn().mockResolvedValue([9, 10]);
+
+ const ratelimit = new Ratelimit({
+ redis: mockRedis,
+ limiter: Ratelimit.fixedWindow(10, "1 m"),
+ prefix: "myapp:ratelimit"
+ });
+
+ await ratelimit.limit("user:123");
+
+ expect(mockRedis.eval).toHaveBeenCalledWith(
+ expect.any(String),
+ 1,
+ "myapp:ratelimit:user:123",
+ expect.anything(),
+ expect.anything(),
+ expect.anything()
+ );
+ });
+ });
+});
diff --git a/packages/kv/src/ratelimit/ratelimit.ts b/packages/kv/src/ratelimit/ratelimit.ts
new file mode 100644
index 0000000000..4ad57ae8ee
--- /dev/null
+++ b/packages/kv/src/ratelimit/ratelimit.ts
@@ -0,0 +1,394 @@
+import type { Redis } from "ioredis";
+import { Cache } from "./cache";
+import { ms } from "./duration";
+import {
+ fixedWindowRemainingScript,
+ fixedWindowScript,
+ slidingWindowRemainingScript,
+ slidingWindowScript,
+ tokenBucketRemainingScript,
+ tokenBucketScript
+} from "./scripts";
+import type {
+ Algorithm,
+ Duration,
+ EphemeralCache,
+ LimitOptions,
+ RatelimitConfig,
+ RatelimitContext,
+ RatelimitResponse
+} from "./types";
+
+const DEFAULT_PREFIX = "@carbon/ratelimit";
+
+/**
+ * Rate limiter implementation compatible with @upstash/ratelimit API
+ * Uses ioredis instead of Upstash REST client
+ */
+export class Ratelimit {
+ private readonly redis: Redis;
+ private readonly limiter: () => Algorithm;
+ private readonly prefix: string;
+ private readonly timeout: number;
+ private readonly ctx: RatelimitContext;
+
+ constructor(config: RatelimitConfig) {
+ this.redis = config.redis;
+ this.limiter = config.limiter;
+ this.prefix = config.prefix ?? DEFAULT_PREFIX;
+ this.timeout = config.timeout ?? 5000;
+
+ let cache: EphemeralCache | undefined;
+ if (config.ephemeralCache === true) {
+ cache = new Cache(new Map());
+ } else if (config.ephemeralCache instanceof Map) {
+ cache = new Cache(config.ephemeralCache);
+ }
+
+ this.ctx = {
+ redis: this.redis,
+ prefix: this.prefix,
+ cache
+ };
+ }
+
+ /**
+ * Check rate limit for an identifier
+ * @param identifier - Unique identifier (e.g., user ID, IP address)
+ * @param opts - Optional limit options
+ */
+ async limit(
+ identifier: string,
+ opts?: LimitOptions
+ ): Promise<RatelimitResponse> {
+ const key = this.getKey(identifier);
+
+ // Check ephemeral cache first (use key for consistency with blockUntil)
+ if (this.ctx.cache) {
+ const { blocked, reset } = this.ctx.cache.isBlocked(key);
+ if (blocked) {
+ return {
+ success: false,
+ limit: 0,
+ remaining: 0,
+ reset,
+ pending: Promise.resolve()
+ };
+ }
+ }
+
+ // Apply timeout
+ const response = this.limiter().limit(this.ctx, key, opts?.rate);
+
+ if (this.timeout > 0) {
+ const timeoutPromise = new Promise<RatelimitResponse>((resolve) => {
+ setTimeout(() => {
+ resolve({
+ success: true,
+ limit: 0,
+ remaining: 0,
+ reset: 0,
+ pending: Promise.resolve()
+ });
+ }, this.timeout);
+ });
+
+ return Promise.race([response, timeoutPromise]);
+ }
+
+ return response;
+ }
+
+ /**
+ * Block until the rate limit allows the request or timeout is reached
+ * @param identifier - Unique identifier
+ * @param timeout - Maximum time to wait in ms
+ */
+ async blockUntilReady(
+ identifier: string,
+ timeout: number
+ ): Promise<RatelimitResponse> {
+ if (timeout <= 0) {
+ throw new Error("timeout must be positive");
+ }
+
+ const deadline = Date.now() + timeout;
+ let res: RatelimitResponse;
+
+ while (true) {
+ res = await this.limit(identifier);
+
+ if (res.success) {
+ return res;
+ }
+
+ if (res.reset === 0) {
+ throw new Error("Unexpected reset value of 0");
+ }
+
+ const wait = Math.min(res.reset, deadline) - Date.now();
+ if (wait <= 0 || Date.now() >= deadline) {
+ return res;
+ }
+
+ await new Promise((r) => setTimeout(r, wait));
+ }
+ }
+
+ /**
+ * Get remaining tokens for an identifier without consuming
+ * @param identifier - Unique identifier
+ */
+ async getRemaining(
+ identifier: string
+ ): Promise<{ remaining: number; reset: number; limit: number }> {
+ const key = this.getKey(identifier);
+ return this.limiter().getRemaining(this.ctx, key);
+ }
+
+ /**
+ * Reset the rate limit for an identifier
+ * @param identifier - Unique identifier
+ */
+ async resetUsedTokens(identifier: string): Promise<void> {
+ const key = this.getKey(identifier);
+ return this.limiter().resetTokens(this.ctx, key);
+ }
+
+ private getKey(identifier: string): string {
+ return `${this.prefix}:${identifier}`;
+ }
+
+ // ===== Static Algorithm Factory Methods =====
+
+ /**
+ * Fixed Window Rate Limiting
+ *
+ * Each request inside a fixed time window increases a counter.
+ * Once the counter reaches the maximum, all further requests are rejected.
+ *
+ * Pros: Simple, low memory usage
+ * Cons: Can allow bursts at window boundaries
+ *
+ * @param tokens - Maximum requests per window
+ * @param window - Window duration (e.g., "10 s", "1 m", "1 h")
+ */
+ static fixedWindow(tokens: number, window: Duration): () => Algorithm {
+ const windowMs = ms(window);
+
+ return () => ({
+ async limit(ctx, key, rate?): Promise<RatelimitResponse> {
+ const limit = rate ?? tokens;
+ const now = Date.now();
+
+ const result = (await ctx.redis.eval(
+ fixedWindowScript,
+ 1,
+ key,
+ limit,
+ windowMs,
+ 1
+ )) as [number, number];
+
+ const [current, effectiveLimit] = result;
+ const remaining = Math.max(0, effectiveLimit - current);
+ const reset = now + windowMs - (now % windowMs) + windowMs;
+ const success = current <= effectiveLimit;
+
+ // Update ephemeral cache if blocked
+ if (!success && ctx.cache) {
+ ctx.cache.blockUntil(key, reset);
+ }
+
+ return {
+ success,
+ limit: effectiveLimit,
+ remaining,
+ reset,
+ pending: Promise.resolve()
+ };
+ },
+
+ async getRemaining(ctx, key) {
+ const result = (await ctx.redis.eval(
+ fixedWindowRemainingScript,
+ 1,
+ key,
+ tokens
+ )) as [number, number];
+
+ const [remaining, limit] = result;
+ const now = Date.now();
+ const reset = now + windowMs - (now % windowMs) + windowMs;
+
+ return { remaining: Math.max(0, remaining), reset, limit };
+ },
+
+ async resetTokens(ctx, key) {
+ await ctx.redis.del(key);
+ }
+ });
+ }
+
+ /**
+ * Sliding Window Rate Limiting
+ *
+ * Combines two fixed windows with a weighted score for smoother rate limiting.
+ * Prevents the boundary burst problem of fixed windows.
+ *
+ * Pros: Better boundary behavior, more accurate rate limiting
+ * Cons: Slightly higher memory (2 keys per identifier)
+ *
+ * @param tokens - Maximum requests per window
+ * @param window - Window duration (e.g., "10 s", "1 m", "1 h")
+ */
+ static slidingWindow(tokens: number, window: Duration): () => Algorithm {
+ const windowMs = ms(window);
+
+ return () => ({
+ async limit(ctx, key, rate?): Promise<RatelimitResponse> {
+ const limit = rate ?? tokens;
+ const now = Date.now();
+ const currentWindow = Math.floor(now / windowMs);
+ const currentKey = `${key}:${currentWindow}`;
+ const previousKey = `${key}:${currentWindow - 1}`;
+
+ const result = (await ctx.redis.eval(
+ slidingWindowScript,
+ 2,
+ currentKey,
+ previousKey,
+ limit,
+ now,
+ windowMs,
+ 1
+ )) as [number, number];
+
+ const [remaining, effectiveLimit] = result;
+ const success = remaining >= 0;
+ const reset = (currentWindow + 1) * windowMs;
+
+ // Update ephemeral cache if blocked
+ if (!success && ctx.cache) {
+ ctx.cache.blockUntil(key, reset);
+ }
+
+ return {
+ success,
+ limit: effectiveLimit,
+ remaining: Math.max(0, remaining),
+ reset,
+ pending: Promise.resolve()
+ };
+ },
+
+ async getRemaining(ctx, key) {
+ const now = Date.now();
+ const currentWindow = Math.floor(now / windowMs);
+ const currentKey = `${key}:${currentWindow}`;
+ const previousKey = `${key}:${currentWindow - 1}`;
+
+ const result = (await ctx.redis.eval(
+ slidingWindowRemainingScript,
+ 2,
+ currentKey,
+ previousKey,
+ tokens,
+ now,
+ windowMs
+ )) as [number, number];
+
+ const [remaining, limit] = result;
+ const reset = (currentWindow + 1) * windowMs;
+
+ return { remaining: Math.max(0, remaining), reset, limit };
+ },
+
+ async resetTokens(ctx, key) {
+ const now = Date.now();
+ const currentWindow = Math.floor(now / windowMs);
+ const currentKey = `${key}:${currentWindow}`;
+ const previousKey = `${key}:${currentWindow - 1}`;
+ await ctx.redis.del(currentKey, previousKey);
+ }
+ });
+ }
+
+ /**
+ * Token Bucket Rate Limiting
+ *
+ * A bucket filled with tokens that refills at a constant rate.
+ * Allows bursts up to the bucket size while maintaining an average rate.
+ *
+ * Pros: Allows controlled bursts, smooth rate limiting
+ * Cons: Slightly more complex, requires hash storage
+ *
+ * @param refillRate - Tokens added per interval
+ * @param interval - Refill interval duration (e.g., "1 s", "10 s")
+ * @param maxTokens - Maximum tokens in bucket (burst capacity)
+ */
+ static tokenBucket(
+ refillRate: number,
+ interval: Duration,
+ maxTokens?: number
+ ): () => Algorithm {
+ const intervalMs = ms(interval);
+ const bucketSize = maxTokens ?? refillRate;
+
+ return () => ({
+ async limit(ctx, key, rate?): Promise<RatelimitResponse> {
+ const limit = rate ?? bucketSize;
+ const now = Date.now();
+
+ const result = (await ctx.redis.eval(
+ tokenBucketScript,
+ 1,
+ key,
+ limit,
+ intervalMs,
+ refillRate,
+ now,
+ 1
+ )) as [number, number, number];
+
+ const [remaining, reset, effectiveLimit] = result;
+ const success = remaining >= 0;
+
+ // Update ephemeral cache if blocked
+ if (!success && ctx.cache) {
+ ctx.cache.blockUntil(key, reset);
+ }
+
+ return {
+ success,
+ limit: effectiveLimit,
+ remaining: Math.max(0, remaining),
+ reset,
+ pending: Promise.resolve()
+ };
+ },
+
+ async getRemaining(ctx, key) {
+ const now = Date.now();
+
+ const result = (await ctx.redis.eval(
+ tokenBucketRemainingScript,
+ 1,
+ key,
+ bucketSize,
+ intervalMs,
+ refillRate,
+ now
+ )) as [number, number, number];
+
+ const [remaining, reset, limit] = result;
+
+ return { remaining: Math.max(0, remaining), reset, limit };
+ },
+
+ async resetTokens(ctx, key) {
+ await ctx.redis.del(key);
+ }
+ });
+ }
+}
diff --git a/packages/kv/src/ratelimit/scripts.ts b/packages/kv/src/ratelimit/scripts.ts
new file mode 100644
index 0000000000..3b806d8d0a
--- /dev/null
+++ b/packages/kv/src/ratelimit/scripts.ts
@@ -0,0 +1,236 @@
+/**
+ * Lua scripts for Redis rate limiting operations
+ * These scripts ensure atomic operations for rate limiting
+ */
+
+/**
+ * Fixed Window Rate Limiting
+ *
+ * Each request inside a fixed time window increases a counter.
+ * Once the counter reaches the maximum, all further requests are rejected.
+ *
+ * KEYS[1] = rate limit key
+ * ARGV[1] = max tokens (limit)
+ * ARGV[2] = window size in ms
+ * ARGV[3] = increment by (default 1)
+ *
+ * Returns: [current_count, limit]
+ */
+export const fixedWindowScript = `
+local key = KEYS[1]
+local tokens = tonumber(ARGV[1])
+local window = ARGV[2]
+local incrementBy = tonumber(ARGV[3])
+
+local r = redis.call("INCRBY", key, incrementBy)
+if r == incrementBy then
+ redis.call("PEXPIRE", key, window)
+end
+
+return {r, tokens}
+`;
+
+/**
+ * Fixed Window Remaining Tokens
+ *
+ * KEYS[1] = rate limit key
+ * ARGV[1] = max tokens (limit)
+ *
+ * Returns: [remaining, limit]
+ */
+export const fixedWindowRemainingScript = `
+local key = KEYS[1]
+local tokens = tonumber(ARGV[1])
+
+local value = redis.call('GET', key)
+local usedTokens = 0
+if value then
+ usedTokens = tonumber(value)
+end
+
+return {tokens - usedTokens, tokens}
+`;
+
+/**
+ * Sliding Window Rate Limiting
+ *
+ * Combines a weighted score between two windows for smoother rate limiting.
+ * Prevents the boundary burst problem of fixed windows.
+ *
+ * KEYS[1] = current window key
+ * KEYS[2] = previous window key
+ * ARGV[1] = max tokens (limit)
+ * ARGV[2] = current timestamp in ms
+ * ARGV[3] = window size in ms
+ * ARGV[4] = increment by (default 1)
+ *
+ * Returns: [remaining, limit] or [-1, limit] if blocked
+ */
+export const slidingWindowScript = `
+local currentKey = KEYS[1]
+local previousKey = KEYS[2]
+local tokens = tonumber(ARGV[1])
+local now = tonumber(ARGV[2])
+local window = tonumber(ARGV[3])
+local incrementBy = tonumber(ARGV[4])
+
+local requestsInCurrentWindow = redis.call("GET", currentKey)
+if requestsInCurrentWindow == false then
+ requestsInCurrentWindow = 0
+else
+ requestsInCurrentWindow = tonumber(requestsInCurrentWindow)
+end
+
+local requestsInPreviousWindow = redis.call("GET", previousKey)
+if requestsInPreviousWindow == false then
+ requestsInPreviousWindow = 0
+else
+ requestsInPreviousWindow = tonumber(requestsInPreviousWindow)
+end
+
+local percentageInCurrent = (now % window) / window
+requestsInPreviousWindow = math.floor((1 - percentageInCurrent) * requestsInPreviousWindow)
+
+if incrementBy > 0 and requestsInPreviousWindow + requestsInCurrentWindow >= tokens then
+ return {-1, tokens}
+end
+
+local newValue = redis.call("INCRBY", currentKey, incrementBy)
+if newValue == incrementBy then
+ redis.call("PEXPIRE", currentKey, window * 2 + 1000)
+end
+
+return {tokens - (newValue + requestsInPreviousWindow), tokens}
+`;
+
+/**
+ * Sliding Window Remaining Tokens
+ *
+ * KEYS[1] = current window key
+ * KEYS[2] = previous window key
+ * ARGV[1] = max tokens (limit)
+ * ARGV[2] = current timestamp in ms
+ * ARGV[3] = window size in ms
+ *
+ * Returns: [remaining, limit]
+ */
+export const slidingWindowRemainingScript = `
+local currentKey = KEYS[1]
+local previousKey = KEYS[2]
+local tokens = tonumber(ARGV[1])
+local now = tonumber(ARGV[2])
+local window = tonumber(ARGV[3])
+
+local requestsInCurrentWindow = redis.call("GET", currentKey)
+if requestsInCurrentWindow == false then
+ requestsInCurrentWindow = 0
+else
+ requestsInCurrentWindow = tonumber(requestsInCurrentWindow)
+end
+
+local requestsInPreviousWindow = redis.call("GET", previousKey)
+if requestsInPreviousWindow == false then
+ requestsInPreviousWindow = 0
+else
+ requestsInPreviousWindow = tonumber(requestsInPreviousWindow)
+end
+
+local percentageInCurrent = (now % window) / window
+requestsInPreviousWindow = math.floor((1 - percentageInCurrent) * requestsInPreviousWindow)
+
+local usedTokens = requestsInPreviousWindow + requestsInCurrentWindow
+return {tokens - usedTokens, tokens}
+`;
+
+/**
+ * Token Bucket Rate Limiting
+ *
+ * A bucket filled with tokens that refills at a constant rate.
+ * Allows bursts up to the bucket size while maintaining an average rate.
+ *
+ * KEYS[1] = bucket key
+ * ARGV[1] = max tokens (bucket size)
+ * ARGV[2] = refill interval in ms
+ * ARGV[3] = refill rate (tokens per interval)
+ * ARGV[4] = current timestamp in ms
+ * ARGV[5] = tokens to consume (default 1)
+ *
+ * Returns: [remaining, reset_timestamp, limit] or [-1, reset_timestamp, limit] if blocked
+ */
+export const tokenBucketScript = `
+local key = KEYS[1]
+local maxTokens = tonumber(ARGV[1])
+local interval = tonumber(ARGV[2])
+local refillRate = tonumber(ARGV[3])
+local now = tonumber(ARGV[4])
+local incrementBy = tonumber(ARGV[5])
+
+local bucket = redis.call("HMGET", key, "refilledAt", "tokens")
+
+local refilledAt
+local tokens
+
+if bucket[1] == false then
+ refilledAt = now
+ tokens = maxTokens
+else
+ refilledAt = tonumber(bucket[1])
+ tokens = tonumber(bucket[2])
+end
+
+if now >= refilledAt + interval then
+ local numRefills = math.floor((now - refilledAt) / interval)
+ tokens = math.min(maxTokens, tokens + numRefills * refillRate)
+ refilledAt = refilledAt + numRefills * interval
+end
+
+if tokens == 0 and incrementBy > 0 then
+ return {-1, refilledAt + interval, maxTokens}
+end
+
+local remaining = tokens - incrementBy
+local expireAt = math.ceil(((maxTokens - remaining) / refillRate)) * interval
+
+redis.call("HSET", key, "refilledAt", refilledAt, "tokens", remaining)
+
+if expireAt > 0 then
+ redis.call("PEXPIRE", key, expireAt)
+end
+
+return {remaining, refilledAt + interval, maxTokens}
+`;
+
+/**
+ * Token Bucket Remaining Tokens
+ *
+ * KEYS[1] = bucket key
+ * ARGV[1] = max tokens (bucket size)
+ * ARGV[2] = refill interval in ms
+ * ARGV[3] = refill rate (tokens per interval)
+ * ARGV[4] = current timestamp in ms
+ *
+ * Returns: [remaining, reset_timestamp, limit]
+ */
+export const tokenBucketRemainingScript = `
+local key = KEYS[1]
+local maxTokens = tonumber(ARGV[1])
+local interval = tonumber(ARGV[2])
+local refillRate = tonumber(ARGV[3])
+local now = tonumber(ARGV[4])
+
+local bucket = redis.call("HMGET", key, "refilledAt", "tokens")
+
+if bucket[1] == false then
+ return {maxTokens, now + interval, maxTokens}
+end
+
+local refilledAt = tonumber(bucket[1])
+local tokens = tonumber(bucket[2])
+
+if now >= refilledAt + interval then
+ local numRefills = math.floor((now - refilledAt) / interval)
+ tokens = math.min(maxTokens, tokens + numRefills * refillRate)
+end
+
+return {tokens, refilledAt + interval, maxTokens}
+`;
diff --git a/packages/kv/src/ratelimit/types.ts b/packages/kv/src/ratelimit/types.ts
new file mode 100644
index 0000000000..30d6d57a86
--- /dev/null
+++ b/packages/kv/src/ratelimit/types.ts
@@ -0,0 +1,103 @@
+import type { Redis } from "ioredis";
+
+/**
+ * Duration unit types
+ */
+type Unit = "ms" | "s" | "m" | "h" | "d";
+
+/**
+ * Duration string format matching @upstash/ratelimit
+ * Examples: "10 s", "1 m", "24 h", "7 d", "10s", "1m"
+ */
+export type Duration = `${number} ${Unit}` | `${number}${Unit}`;
+
+/**
+ * Response returned by the rate limiter's limit() method
+ * Matches @upstash/ratelimit RatelimitResponse
+ */
+export interface RatelimitResponse {
+ /** Whether the request should be allowed */
+ success: boolean;
+ /** Maximum number of requests allowed in the window */
+ limit: number;
+ /** Remaining requests in the current window */
+ remaining: number;
+ /** Unix timestamp (ms) when the rate limit resets */
+ reset: number;
+ /** Promise that resolves when all pending operations complete */
+ pending: Promise<unknown>;
+}
+
+/**
+ * Algorithm implementation interface
+ */
+export interface Algorithm {
+ /**
+ * Check rate limit and consume a token
+ */
+ limit: (
+ ctx: RatelimitContext,
+ key: string,
+ rate?: number
+ ) => Promise<RatelimitResponse>;
+
+ /**
+ * Get remaining tokens without consuming
+ */
+ getRemaining: (
+ ctx: RatelimitContext,
+ key: string
+ ) => Promise<{ remaining: number; reset: number; limit: number }>;
+
+ /**
+ * Reset the rate limit for a key
+ */
+ resetTokens: (ctx: RatelimitContext, key: string) => Promise<void>;
+}
+
+/**
+ * Configuration for creating a Ratelimit instance
+ * Matches @upstash/ratelimit RatelimitConfig
+ */
+export interface RatelimitConfig {
+ /** ioredis client instance */
+ redis: Redis;
+ /** Algorithm factory returned by static methods */
+ limiter: () => Algorithm;
+ /** Key prefix for Redis keys (default: "@upstash/ratelimit") */
+ prefix?: string;
+ /** Enable ephemeral in-memory cache for blocked identifiers */
+ ephemeralCache?: boolean | Map<string, number>;
+ /** Timeout for Redis operations in ms (default: 5000) */
+ timeout?: number;
+ /** Enable analytics (currently a no-op for compatibility) */
+ analytics?: boolean;
+}
+
+/**
+ * Options for the limit() method
+ */
+export interface LimitOptions {
+ /** Custom rate limit for this specific request */
+ rate?: number;
+}
+
+/**
+ * Internal context passed to algorithm implementations
+ */
+export interface RatelimitContext {
+ redis: Redis;
+ prefix: string;
+ cache?: EphemeralCache;
+}
+
+/**
+ * Ephemeral cache interface for in-memory blocking
+ */
+export interface EphemeralCache {
+ isBlocked: (key: string) => { blocked: boolean; reset: number };
+ blockUntil: (key: string, reset: number) => void;
+ set: (key: string, value: number) => void;
+ get: (key: string) => number | undefined;
+ incr: (key: string) => number;
+}
diff --git a/packages/kv/vitest.config.ts b/packages/kv/vitest.config.ts
new file mode 100644
index 0000000000..cee251eea9
--- /dev/null
+++ b/packages/kv/vitest.config.ts
@@ -0,0 +1,15 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: "node",
+ include: ["src/**/*.test.ts"],
+ coverage: {
+ provider: "v8",
+ reporter: ["text", "json", "html"],
+ include: ["src/ratelimit/**/*.ts"],
+ exclude: ["src/**/*.test.ts", "src/**/index.ts"],
+ },
+ },
+});
diff --git a/scripts/migrations/stripe-customer-migrations.ts b/scripts/migrations/stripe-customer-migrations.ts
index 6a88a220c8..c1dd149e8e 100644
--- a/scripts/migrations/stripe-customer-migrations.ts
+++ b/scripts/migrations/stripe-customer-migrations.ts
@@ -1,8 +1,8 @@
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
import { createClient } from "@supabase/supabase-js";
-import { Redis } from "@upstash/redis";
import { config } from "dotenv";
+import Redis from "ioredis";
import { Stripe } from "stripe";
import { z } from 'zod/v3';
import { localCompanies, productionCompanies } from "./data/stripe-customers";
@@ -12,33 +12,19 @@ const PROD = true;
const companies = PROD ? productionCompanies : localCompanies;
-const upstashRedisRestUrl = PROD
- ? process.env.PROD_UPSTASH_REDIS_REST_URL
- : process.env.UPSTASH_REDIS_REST_URL;
-const upstashRedisRestToken = PROD
- ? process.env.PROD_UPSTASH_REDIS_REST_TOKEN
- : process.env.UPSTASH_REDIS_REST_TOKEN;
+const redisUrl = PROD
+ ? process.env.PROD_REDIS_URL
+ : process.env.REDIS_URL;
-if (!upstashRedisRestUrl) {
+if (!redisUrl) {
throw new Error(
PROD
- ? "PROD_UPSTASH_REDIS_REST_URL is not defined"
- : "UPSTASH_REDIS_REST_URL is not defined"
+ ? "PROD_REDIS_URL is not defined"
+ : "REDIS_URL is not defined"
);
}
-if (!upstashRedisRestToken) {
- throw new Error(
- PROD
- ? "PROD_UPSTASH_REDIS_REST_TOKEN is not defined"
- : "UPSTASH_REDIS_REST_TOKEN is not defined"
- );
-}
-
-const redis = new Redis({
- url: upstashRedisRestUrl,
- token: upstashRedisRestToken,
-});
+const redis = new Redis(redisUrl);
const supabaseUrl = PROD
? process.env.PROD_SUPABASE_URL
diff --git a/sst.config.ts b/sst.config.ts
index a95f8527a9..7b09d9d4db 100644
--- a/sst.config.ts
+++ b/sst.config.ts
@@ -87,8 +87,7 @@ export default $config({
TRIGGER_API_URL: process.env.TRIGGER_API_URL,
TRIGGER_PROJECT_ID: process.env.TRIGGER_PROJECT_ID,
TRIGGER_SECRET_KEY: process.env.TRIGGER_SECRET_KEY,
- UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN,
- UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL,
+ REDIS_URL: process.env.REDIS_URL,
VERCEL_ENV: "production",
VERCEL_URL: process.env.URL_ERP ?? "itar.carbon.ms",
XERO_CLIENT_ID: process.env.XERO_CLIENT_ID,
@@ -169,8 +168,7 @@ export default $config({
TRIGGER_API_URL: process.env.TRIGGER_API_URL,
TRIGGER_PROJECT_ID: process.env.TRIGGER_PROJECT_ID,
TRIGGER_SECRET_KEY: process.env.TRIGGER_SECRET_KEY,
- UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN,
- UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL,
+ REDIS_URL: process.env.REDIS_URL,
VERCEL_ENV: "production",
VERCEL_URL: process.env.URL_MES ?? "mes.itar.carbon.ms",
},