Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: rate-limit OTP send endpoint and surface 429 in sign-in UI

Gener1e2257d6effa
diff --git a/src/web/src/app/(auth)/sign-in/page.tsx b/src/web/src/app/(auth)/sign-in/page.tsx
index 7ca35e511..ed2f568b9 100644
--- a/src/web/src/app/(auth)/sign-in/page.tsx
+++ b/src/web/src/app/(auth)/sign-in/page.tsx
@@ -1,7 +1,8 @@
"use client"
-import { useState } from "react"
+import { useEffect, useState } from "react"
import { signIn, signUp, authClient } from "@/lib/auth-client"
+import { parseRetryAfterSeconds } from "@/lib/retry-after"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
@@ -29,18 +30,39 @@ function OTPSignIn() {
const [step, setStep] = useState<"email" | "code">("email")
const [error, setError] = useState("")
const [loading, setLoading] = useState(false)
+ const [retryAfter, setRetryAfter] = useState<number | null>(null)
+
+ useEffect(() => {
+ if (retryAfter == null) return
+ const id = setTimeout(() => {
+ setRetryAfter((v) => (v == null || v <= 1 ? null : v - 1))
+ }, 1000)
+ return () => clearTimeout(id)
+ }, [retryAfter])
+
+ const rateLimitHandler = {
+ onError: (ctx: { response: Response }) => {
+ if (ctx.response.status === 429) {
+ const seconds = parseRetryAfterSeconds(ctx.response.headers)
+ if (seconds != null) setRetryAfter(seconds)
+ }
+ },
+ }
async function handleSendCode(e: React.FormEvent) {
e.preventDefault()
+ if (retryAfter != null) return
setError("")
+ setRetryAfter(null)
setLoading(true)
try {
const { error } = await authClient.emailOtp.sendVerificationOtp({
email,
type: "sign-in",
+ fetchOptions: rateLimitHandler,
})
if (error) {
- setError(error.message ?? "Failed to send code")
+ if (error.status !== 429) setError(error.message ?? "Failed to send code")
} else {
setStep("code")
}
@@ -75,6 +97,13 @@ function OTPSignIn() {
setLoading(false)
}
+ const isCoolingDown = retryAfter != null
+ const sendLabel = loading
+ ? "Sending..."
+ : isCoolingDown
+ ? `Wait ${retryAfter}s`
+ : "Send Code"
+
return (
<FieldGroup>
<div className="flex flex-col items-center gap-2 text-center">
@@ -85,7 +114,12 @@ function OTPSignIn() {
: "Enter the code we sent you"}
</p>
</div>
- {error && <FieldError>{error}</FieldError>}
+ {isCoolingDown && (
+ <FieldError>
+ Too many requests. Try again in {retryAfter}s.
+ </FieldError>
+ )}
+ {error && !isCoolingDown && <FieldError>{error}</FieldError>}
{step === "email" ? (
<form onSubmit={handleSendCode}>
<FieldGroup>
@@ -102,8 +136,12 @@ function OTPSignIn() {
/>
</Field>
<Field>
- <Button type="submit" disabled={loading} className="w-full">
- {loading ? "Sending..." : "Send Code"}
+ <Button
+ type="submit"
+ disabled={loading || isCoolingDown}
+ className="w-full"
+ >
+ {sendLabel}
</Button>
</Field>
</FieldGroup>
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index 15b8281df..be824b7fd 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -13,6 +13,9 @@ declare namespace Cloudflare {
GOOGLE_CLIENT_SECRET: string
BETTER_AUTH_SECRET: string
BETTER_AUTH_URL: string
+ RATE_LIMIT_KV: KVNamespace
+ AUTH_OTP_RATE_LIMIT_MAX?: string
+ AUTH_OTP_RATE_LIMIT_WINDOW_SEC?: string
}
}
diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.ts
new file mode 100644
index 000000000..760259b17
--- /dev/null
+++ b/src/web/src/lib/auth.test.ts
@@ -0,0 +1,162 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+vi.mock("better-auth", () => ({
+ betterAuth: vi.fn((opts: unknown) => ({ __options: opts })),
+}))
+
+vi.mock("better-auth/plugins", () => ({
+ emailOTP: vi.fn((cfg: unknown) => ({ __plugin: "emailOTP", cfg })),
+}))
+
+vi.mock("@alook/shared", () => ({
+ createLogger: () => ({ info: vi.fn(), error: vi.fn() }),
+ DEV_EMAIL_WORKER_URL: "http://localhost:0",
+}))
+
+vi.mock("./email-templates", () => ({
+ getOtpSubject: () => "subject",
+ renderOtpEmail: () => "<html></html>",
+}))
+
+type RateLimitValue = { count: number; lastRequest: number } | undefined
+
+function makeKv() {
+ const store = new Map<string, { value: string; expirationTtl?: number }>()
+ return {
+ store,
+ get: vi.fn(async (key: string) => store.get(key)?.value ?? null),
+ put: vi.fn(async (key: string, value: string, opts?: { expirationTtl?: number }) => {
+ store.set(key, { value, expirationTtl: opts?.expirationTtl })
+ }),
+ }
+}
+
+function makeEnv(overrides: Partial<Record<string, unknown>> = {}) {
+ return {
+ DB: {},
+ EMAIL_BUCKET: {},
+ WS_DO_WORKER: {},
+ EMAIL_WORKER: { fetch: vi.fn() },
+ NEXT_INC_CACHE_R2_BUCKET: {},
+ NEXT_TAG_CACHE_D1: {},
+ NEXT_CACHE_DO_QUEUE: {},
+ GITHUB_CLIENT_ID: "gh",
+ GITHUB_CLIENT_SECRET: "gh-s",
+ GOOGLE_CLIENT_ID: "gg",
+ GOOGLE_CLIENT_SECRET: "gg-s",
+ BETTER_AUTH_SECRET: "secret",
+ BETTER_AUTH_URL: "http://localhost:3000",
+ RATE_LIMIT_KV: makeKv(),
+ ...overrides,
+ }
+}
+
+type AuthOptions = {
+ rateLimit: {
+ enabled: boolean
+ customRules: Record<string, { window: number; max: number }>
+ customStorage: {
+ get: (key: string) => Promise<RateLimitValue>
+ set: (key: string, value: RateLimitValue) => Promise<void>
+ }
+ }
+}
+
+async function loadCreateAuth(nodeEnv: "production" | "development" | "test") {
+ vi.resetModules()
+ const prev = process.env.NODE_ENV
+ vi.stubEnv("NODE_ENV", nodeEnv)
+ try {
+ const mod = await import("./auth")
+ return mod.createAuth
+ } finally {
+ vi.stubEnv("NODE_ENV", prev ?? "test")
+ }
+}
+
+describe("createAuth rate limiting", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("enables rate limiting only in production", async () => {
+ const createAuthProd = await loadCreateAuth("production")
+ const envProd = makeEnv()
+ const optsProd = (createAuthProd(envProd as never) as { __options: AuthOptions }).__options
+ expect(optsProd.rateLimit.enabled).toBe(true)
+
+ const createAuthDev = await loadCreateAuth("development")
+ const envDev = makeEnv()
+ const optsDev = (createAuthDev(envDev as never) as { __options: AuthOptions }).__options
+ expect(optsDev.rateLimit.enabled).toBe(false)
+ })
+
+ it("uses default 5/60s for the OTP path when env vars are unset", async () => {
+ const createAuth = await loadCreateAuth("production")
+ const env = makeEnv()
+ const opts = (createAuth(env as never) as { __options: AuthOptions }).__options
+ expect(opts.rateLimit.customRules["/email-otp/send-verification-otp"]).toEqual({
+ window: 60,
+ max: 5,
+ })
+ })
+
+ it("honours AUTH_OTP_RATE_LIMIT_MAX / _WINDOW_SEC overrides", async () => {
+ const createAuth = await loadCreateAuth("production")
+ const env = makeEnv({
+ AUTH_OTP_RATE_LIMIT_MAX: "3",
+ AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "120",
+ })
+ const opts = (createAuth(env as never) as { __options: AuthOptions }).__options
+ expect(opts.rateLimit.customRules["/email-otp/send-verification-otp"]).toEqual({
+ window: 120,
+ max: 3,
+ })
+ })
+
+ it("falls back to defaults when env overrides are non-numeric or zero", async () => {
+ const createAuth = await loadCreateAuth("production")
+ const env = makeEnv({
+ AUTH_OTP_RATE_LIMIT_MAX: "not-a-number",
+ AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "0",
+ })
+ const opts = (createAuth(env as never) as { __options: AuthOptions }).__options
+ expect(opts.rateLimit.customRules["/email-otp/send-verification-otp"]).toEqual({
+ window: 60,
+ max: 5,
+ })
+ })
+
+ it("customStorage round-trips values through KV with a >=60s TTL", async () => {
+ const createAuth = await loadCreateAuth("production")
+ const env = makeEnv()
+ const opts = (createAuth(env as never) as { __options: AuthOptions }).__options
+ const { get, set } = opts.rateLimit.customStorage
+ const kv = env.RATE_LIMIT_KV as ReturnType<typeof makeKv>
+
+ expect(await get("missing")).toBeUndefined()
+
+ await set("k1", { count: 2, lastRequest: 123 })
+ const stored = kv.store.get("k1")
+ expect(stored?.value).toBe(JSON.stringify({ count: 2, lastRequest: 123 }))
+ expect(stored?.expirationTtl).toBeGreaterThanOrEqual(60)
+
+ expect(await get("k1")).toEqual({ count: 2, lastRequest: 123 })
+ })
+
+ it("clamps KV TTL to 60s when the configured window is shorter", async () => {
+ const createAuth = await loadCreateAuth("production")
+ const env = makeEnv({ AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "10" })
+ const opts = (createAuth(env as never) as { __options: AuthOptions }).__options
+ const kv = env.RATE_LIMIT_KV as ReturnType<typeof makeKv>
+ await opts.rateLimit.customStorage.set("k", { count: 1, lastRequest: 0 })
+ expect(kv.store.get("k")?.expirationTtl).toBe(60)
+ })
+
+ it("uses the configured window as TTL when it exceeds 60s", async () => {
+ const createAuth = await loadCreateAuth("production")
+ const env = makeEnv({ AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "180" })
+ const opts = (createAuth(env as never) as { __options: AuthOptions }).__options
+ const kv = env.RATE_LIMIT_KV as ReturnType<typeof makeKv>
+ await opts.rateLimit.customStorage.set("k", { count: 1, lastRequest: 0 })
+ expect(kv.store.get("k")?.expirationTtl).toBe(180)
+ })
+})
diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.ts
index d1220dc39..53975116d 100644
--- a/src/web/src/lib/auth.ts
+++ b/src/web/src/lib/auth.ts
@@ -6,7 +6,25 @@ import { getOtpSubject, renderOtpEmail } from "./email-templates"
const isProd = process.env.NODE_ENV === "production"
const log = createLogger({ service: "auth" })
+const OTP_RATE_LIMIT_PATH = "/email-otp/send-verification-otp"
+const DEFAULT_OTP_RATE_LIMIT_MAX = 5
+const DEFAULT_OTP_RATE_LIMIT_WINDOW_SEC = 60
+const KV_MIN_TTL_SEC = 60
+
+function parsePositiveInt(raw: string | undefined, fallback: number): number {
+ if (!raw) return fallback
+ const n = Number.parseInt(raw, 10)
+ return Number.isFinite(n) && n > 0 ? n : fallback
+}
+
export function createAuth(env: Env) {
+ const otpMax = parsePositiveInt(env.AUTH_OTP_RATE_LIMIT_MAX, DEFAULT_OTP_RATE_LIMIT_MAX)
+ const otpWindow = parsePositiveInt(
+ env.AUTH_OTP_RATE_LIMIT_WINDOW_SEC,
+ DEFAULT_OTP_RATE_LIMIT_WINDOW_SEC,
+ )
+ const kvTtl = Math.max(KV_MIN_TTL_SEC, otpWindow)
+
return betterAuth({
baseURL: env.BETTER_AUTH_URL,
database: env.DB,
@@ -25,6 +43,21 @@ export function createAuth(env: Env) {
clientSecret: env.GOOGLE_CLIENT_SECRET,
},
},
+ rateLimit: {
+ enabled: isProd,
+ customRules: {
+ [OTP_RATE_LIMIT_PATH]: { window: otpWindow, max: otpMax },
+ },
+ customStorage: {
+ get: async (key) => {
+ const raw = await env.RATE_LIMIT_KV.get(key)
+ return raw ? JSON.parse(raw) : undefined
+ },
+ set: async (key, value) => {
+ await env.RATE_LIMIT_KV.put(key, JSON.stringify(value), { expirationTtl: kvTtl })
+ },
+ },
+ },
plugins: isProd
? [
emailOTP({
diff --git a/src/web/src/lib/retry-after.test.ts b/src/web/src/lib/retry-after.test.ts
new file mode 100644
index 000000000..9cc43889e
--- /dev/null
+++ b/src/web/src/lib/retry-after.test.ts
@@ -0,0 +1,33 @@
+import { describe, it, expect } from "vitest"
+import { parseRetryAfterSeconds } from "./retry-after"
+
+describe("parseRetryAfterSeconds", () => {
+ it("reads a positive integer from X-Retry-After", () => {
+ const h = new Headers({ "X-Retry-After": "42" })
+ expect(parseRetryAfterSeconds(h)).toBe(42)
+ })
+
+ it("falls back to Retry-After when X-Retry-After is absent", () => {
+ const h = new Headers({ "Retry-After": "7" })
+ expect(parseRetryAfterSeconds(h)).toBe(7)
+ })
+
+ it("returns null when neither header is set", () => {
+ expect(parseRetryAfterSeconds(new Headers())).toBeNull()
+ })
+
+ it("returns null when the value is not numeric", () => {
+ const h = new Headers({ "X-Retry-After": "soon" })
+ expect(parseRetryAfterSeconds(h)).toBeNull()
+ })
+
+ it("returns null when the value is zero", () => {
+ const h = new Headers({ "X-Retry-After": "0" })
+ expect(parseRetryAfterSeconds(h)).toBeNull()
+ })
+
+ it("returns null when the value is negative", () => {
+ const h = new Headers({ "X-Retry-After": "-5" })
+ expect(parseRetryAfterSeconds(h)).toBeNull()
+ })
+})
diff --git a/src/web/src/lib/retry-after.ts b/src/web/src/lib/retry-after.ts
new file mode 100644
index 000000000..43b326d7e
--- /dev/null
+++ b/src/web/src/lib/retry-after.ts
@@ -0,0 +1,6 @@
+export function parseRetryAfterSeconds(headers: Headers): number | null {
+ const raw = headers.get("X-Retry-After") ?? headers.get("Retry-After")
+ if (!raw) return null
+ const n = Number.parseInt(raw, 10)
+ return Number.isFinite(n) && n > 0 ? n : null
+}
diff --git a/src/web/wrangler.toml b/src/web/wrangler.toml
index 9b85d1305..fa33212b4 100644
--- a/src/web/wrangler.toml
+++ b/src/web/wrangler.toml
@@ -57,3 +57,7 @@ service = "alook-ws-do"
binding = "EMAIL_WORKER"
service = "alook-email-worker"
+[[kv_namespaces]]
+binding = "RATE_LIMIT_KV"
+id = "a3d035bea7bc49d99377b82ec21ce4c1"
+